diff --git a/README.md b/README.md index 3f1be0c06d0..d202ee0b43a 100644 --- a/README.md +++ b/README.md @@ -1,30 +1,22 @@ # ARM mbed OS -mbed OS is an open-source embedded operating system designed for the "things" in the Internet of Things (IoT). mbed OS includes the features you need to develop a connected product using an ARM Cortex-M microcontroller. +mbed OS is an open-source embedded operating system designed specifically for the "things" in the Internet of Things (IoT). It includes all the features you need to develop a connected product based on an ARM Cortex-M microcontroller. -mbed OS provides a platform that includes: - - Security foundations. - - Cloud management services. - - Drivers for sensors, I/O devices and connectivity. - -mbed OS is modular, configurable software that you can customize it to your device and to reduce memory requirements by excluding unused software. - +mbed OS accelerates the process of creating a connected product by providing a platform operating system that includes robust security foundations, standards based communication capabilities, built-in cloud management services, and drivers for sensors, I/O devices and connectivity. mbed OS is built as a modular, configurable software stack so that you can readily customize it to the device you're developing for, and reduce memory requirements by excluding unnecessary software components. -## Release Notes - -The [Release Notes](https://docs.mbed.com/docs/mbed-os-release-notes/en/latest/) detail the current release and previous versions. - -## Continuous Integration Status +## Current release -We run continuous integration on all of our branches and pull requests to verify the stability of mbed OS. The following are the Travis CI indicators for mbed OS. - - - Master branch [![Master Branch CI Badge](https://travis-ci.org/ARMmbed/mbed-os.svg?branch=master)](https://travis-ci.org/ARMmbed/mbed-os) - - Latest release [![Latest Tag CI Badge](https://travis-ci.org/ARMmbed/mbed-os.svg?branch=latest)](https://travis-ci.org/ARMmbed/mbed-os/branches) +The current release, along with a selection of previous versions are detailed here: +[Release Notes](https://docs.mbed.com/docs/mbed-os-release-notes/en/latest/) ## Getting Started for Developers -You need [mbed CLI](https://github.com/ARMmbed/mbed-cli) to build mbed OS. For more details, read the [mbed OS Handbook](https://docs.mbed.com/docs/mbed-os-handbook/en/latest/). +Please note that you will require [mbed CLI](https://github.com/ARMmbed/mbed-cli) to build mbed OS. For more details, please read the getting started guide for developers using mbed OS in applications: + +- [Getting Started](https://docs.mbed.com/docs/mbed-os-handbook/en/latest/) ## Getting Started for Contributors -We have a [Contributing and Publishing Guide](https://docs.mbed.com/docs/mbed-os-handbook/en/latest/cont/contributing/) in the mbed OS Handbook. +We have a getting started guide for contributors working on mbed OS: + +- Have a look in the docs directory diff --git a/TESTS/events/queue/main.cpp b/TESTS/events/queue/main.cpp index c034d60d419..e1b77b99723 100644 --- a/TESTS/events/queue/main.cpp +++ b/TESTS/events/queue/main.cpp @@ -7,7 +7,6 @@ using namespace utest::v1; -#define TEST_EQUEUE_SIZE 1024 // flag for called volatile bool touched = false; @@ -44,7 +43,7 @@ void func0() { #define SIMPLE_POSTS_TEST(i, ...) \ void simple_posts_test##i() { \ - EventQueue queue(TEST_EQUEUE_SIZE); \ + EventQueue queue; \ \ touched = false; \ queue.call(func##i,##__VA_ARGS__); \ @@ -79,7 +78,7 @@ template void call_in_test() { Timer tickers[N]; - EventQueue queue(TEST_EQUEUE_SIZE); + EventQueue queue; for (int i = 0; i < N; i++) { tickers[i].start(); @@ -93,7 +92,7 @@ template void call_every_test() { Timer tickers[N]; - EventQueue queue(TEST_EQUEUE_SIZE); + EventQueue queue; for (int i = 0; i < N; i++) { tickers[i].start(); @@ -104,7 +103,7 @@ void call_every_test() { } void allocate_failure_test() { - EventQueue queue(TEST_EQUEUE_SIZE); + EventQueue queue; int id; for (int i = 0; i < 100; i++) { @@ -120,7 +119,7 @@ void no() { template void cancel_test1() { - EventQueue queue(TEST_EQUEUE_SIZE); + EventQueue queue; int ids[N]; @@ -165,7 +164,7 @@ void count0() { void event_class_test() { counter = 0; - EventQueue queue(TEST_EQUEUE_SIZE); + EventQueue queue(2048); Event e5(&queue, count5); Event e4(&queue, count5, 1); @@ -188,7 +187,7 @@ void event_class_test() { void event_class_helper_test() { counter = 0; - EventQueue queue(TEST_EQUEUE_SIZE); + EventQueue queue(2048); Event e5 = queue.event(count5, 1, 1, 1, 1, 1); Event e4 = queue.event(count4, 1, 1, 1, 1); @@ -211,7 +210,7 @@ void event_class_helper_test() { void event_inference_test() { counter = 0; - EventQueue queue(TEST_EQUEUE_SIZE); + EventQueue queue(2048); queue.event(count5, 1, 1, 1, 1, 1).post(); queue.event(count5, 1, 1, 1, 1).post(1); diff --git a/TESTS/events/timing/main.cpp b/TESTS/events/timing/main.cpp index 6a7e0fcf6f6..aa361d8dd28 100644 --- a/TESTS/events/timing/main.cpp +++ b/TESTS/events/timing/main.cpp @@ -104,7 +104,7 @@ void semaphore_timing_test() { // Test setup utest::v1::status_t test_setup(const size_t number_of_cases) { - GREENTEA_SETUP((number_of_cases+1)*TEST_EVENTS_TIMING_TIME/1000, "default_auto"); + GREENTEA_SETUP((number_of_cases+1)*TEST_EVENTS_TIMING_TIME, "default_auto"); return verbose_test_setup_handler(number_of_cases); } diff --git a/TESTS/mbed_drivers/race_test/main.cpp b/TESTS/mbed_drivers/race_test/main.cpp index df8a47e0d12..006c9a12b2f 100644 --- a/TESTS/mbed_drivers/race_test/main.cpp +++ b/TESTS/mbed_drivers/race_test/main.cpp @@ -22,24 +22,22 @@ #include "SingletonPtr.h" #include -#ifndef MBED_RTOS_SINGLE_THREAD - #error [NOT_SUPPORTED] test not supported for single threaded enviroment -#endif - using namespace utest::v1; -#define TEST_STACK_SIZE 512 +#define TEST_STACK_SIZE 1024 static uint32_t instance_count = 0; class TestClass { public: TestClass() { + printf("TestClass ctor start\r\n"); Thread::wait(500); instance_count++; + printf("TestClass ctor end\r\n"); } void do_something() { - Thread::wait(100); + printf("Do something called\r\n"); } ~TestClass() { @@ -67,6 +65,7 @@ static void main_class_race() void test_case_func_race() { + printf("Running function race test\r\n"); Callback cb(main_func_race); Thread *t1 = new Thread(osPriorityNormal, TEST_STACK_SIZE); Thread *t2 = new Thread(osPriorityNormal, TEST_STACK_SIZE); @@ -92,6 +91,7 @@ void test_case_func_race() void test_case_class_race() { + printf("Running class race test\r\n"); Callback cb(main_class_race); Thread *t1 = new Thread(osPriorityNormal, TEST_STACK_SIZE); Thread *t2 = new Thread(osPriorityNormal, TEST_STACK_SIZE); diff --git a/TESTS/mbed_drivers/stats/main.cpp b/TESTS/mbed_drivers/stats/main.cpp index 2d5404d0d55..f1cb47830b1 100644 --- a/TESTS/mbed_drivers/stats/main.cpp +++ b/TESTS/mbed_drivers/stats/main.cpp @@ -30,7 +30,7 @@ using namespace utest::v1; #define ALLOCATION_SIZE_DEFAULT 564 #define ALLOCATION_SIZE_SMALL 124 -#define ALLOCATION_SIZE_LARGE 700 +#define ALLOCATION_SIZE_LARGE 790 #define ALLOCATION_SIZE_FAIL (1024 * 1024 *1024) typedef void* (*malloc_cb_t) (uint32_t size); @@ -49,6 +49,7 @@ malloc_cb_t malloc_thunk_array[] = { void test_case_malloc_free_size() { + printf("Initial print to setup stdio buffers\n"); mbed_stats_heap_t stats_start; mbed_stats_heap_t stats_current; void *data; @@ -126,22 +127,26 @@ void test_case_allocate_fail() static void* thunk_malloc(uint32_t size) { + printf("Malloc thunk\n"); return malloc(size); } static void* thunk_calloc_1(uint32_t size) { + printf("Calloc thunk 1 byte\n"); return calloc(size / 1, 1); } static void* thunk_calloc_4(uint32_t size) { + printf("Calloc thunk 4 bytes\n"); return calloc(size / 4, 4); } static void* thunk_realloc(uint32_t size) { + printf("Realloc thunk\n"); return realloc(NULL, size); } diff --git a/TESTS/mbed_drivers/stl_features/main.cpp b/TESTS/mbed_drivers/stl_features/main.cpp index eda36c58191..2cfbd2b50cb 100644 --- a/TESTS/mbed_drivers/stl_features/main.cpp +++ b/TESTS/mbed_drivers/stl_features/main.cpp @@ -32,10 +32,15 @@ using namespace utest::v1; #define TABLE_SIZE(TAB) (sizeof(TAB) / sizeof(TAB[0])) #define NEGATIVE_INTEGERS -32768,-3214,-999,-100,-1,0,1,4231,999,4123,32760,99999 +#define POSITIVE_INTEGERS 32768,3214,999,100,1,0,1,4231,999,4123,32760,99999 #define FLOATS 0.002,0.92430,15.91320,791.77368,6208.2,25719.4952,426815.982588,6429271.046,42468024.93,212006462.910 #define FLOATS_STR "0.002","0.92430","15.91320","791.77368","6208.2","25719.4952","426815.982588","6429271.046","42468024.93","212006462.910" + namespace { +int p_integers[] = {POSITIVE_INTEGERS}; +int n_integers[] = {NEGATIVE_INTEGERS}; +float floats[] = {FLOATS}; template void BubbleSort(T& _array, size_t array_size, F functor) { @@ -54,6 +59,18 @@ void BubbleSort(T& _array, size_t array_size, F functor) { } } +struct printInt { + void operator()(int i) { printf("%d ", i); } +}; + +struct printFloat { + void operator()(float f) { printf("%f ", f); } +}; + +struct printString { + void operator()(const char* s) { printf("%s ", s); } +}; + struct greaterAbs { bool operator()(int a, int b) { return abs(a) > abs(b); } }; @@ -61,42 +78,43 @@ struct greaterAbs { } // namespace void test_case_stl_equal() { - const int n_integers[] = {NEGATIVE_INTEGERS}; - std::vector v_pints(n_integers, n_integers + TABLE_SIZE(n_integers)); - TEST_ASSERT_TRUE(std::equal(v_pints.begin(), v_pints.end(), n_integers)); + std::vector v_pints(p_integers, p_integers + TABLE_SIZE(p_integers)); + TEST_ASSERT_TRUE(std::equal(v_pints.begin(), v_pints.end(), p_integers)); } void test_case_stl_transform() { - const float floats[] = {FLOATS}; const char* floats_str[] = {FLOATS_STR}; float floats_transform[TABLE_SIZE(floats_str)] = {0.0}; std::transform(floats_str, floats_str + TABLE_SIZE(floats_str), floats_transform, atof); + //printf("stl_transform::floats_str: "); + //std::for_each(floats_str, floats_str + TABLE_SIZE(floats_str), printString()); + //printf("stl_transform::floats_transform: "); + //std::for_each(floats_transform, floats_transform + TABLE_SIZE(floats_transform), printFloat()); + //printf("\n"); TEST_ASSERT_TRUE(std::equal(floats_transform, floats_transform + TABLE_SIZE(floats_transform), floats)); } void test_case_stl_sort_greater() { - int n_integers[] = {NEGATIVE_INTEGERS}; - int n_integers2[] = {NEGATIVE_INTEGERS}; + std::vector v_nints_1(n_integers, n_integers + TABLE_SIZE(n_integers)); + std::vector v_nints_2(n_integers, n_integers + TABLE_SIZE(n_integers)); - BubbleSort(n_integers, TABLE_SIZE(n_integers), std::greater()); - std::sort(n_integers2, n_integers2 + TABLE_SIZE(n_integers2), std::greater()); + BubbleSort(v_nints_1, v_nints_1.size(), std::greater()); + std::sort(v_nints_2.begin(), v_nints_2.end(), std::greater()); - TEST_ASSERT_TRUE(std::equal(n_integers2, n_integers2 + TABLE_SIZE(n_integers2), n_integers)); + TEST_ASSERT_TRUE(std::equal(v_nints_1.begin(), v_nints_1.end(), v_nints_2.begin())); } - void test_case_stl_sort_abs() { - int n_integers[] = {NEGATIVE_INTEGERS}; - int n_integers2[] = {NEGATIVE_INTEGERS}; + std::vector v_nints_1(n_integers, n_integers + TABLE_SIZE(n_integers)); + std::vector v_nints_2(n_integers, n_integers + TABLE_SIZE(n_integers)); - BubbleSort(n_integers, TABLE_SIZE(n_integers), greaterAbs()); - std::sort(n_integers2, n_integers2 + TABLE_SIZE(n_integers2), greaterAbs()); + BubbleSort(v_nints_1, v_nints_1.size(), greaterAbs()); + std::sort(v_nints_2.begin(), v_nints_2.end(), greaterAbs()); - TEST_ASSERT_TRUE(std::equal(n_integers2, n_integers2 + TABLE_SIZE(n_integers2), n_integers)); + TEST_ASSERT_TRUE(std::equal(v_nints_1.begin(), v_nints_1.end(), v_nints_2.begin())); } - utest::v1::status_t greentea_failure_handler(const Case *const source, const failure_t reason) { greentea_case_failure_abort_handler(source, reason); return STATUS_CONTINUE; diff --git a/TESTS/mbedmicro-rtos-mbed/basic/main.cpp b/TESTS/mbedmicro-rtos-mbed/basic/main.cpp index 88256007405..75183cbd836 100644 --- a/TESTS/mbedmicro-rtos-mbed/basic/main.cpp +++ b/TESTS/mbedmicro-rtos-mbed/basic/main.cpp @@ -6,7 +6,26 @@ #error [NOT_SUPPORTED] test not supported #endif -#define TEST_STACK_SIZE 768 +/* + * The stack size is defined in cmsis_os.h mainly dependent on the underlying toolchain and + * the C standard library. For GCC, ARM_STD and IAR it is defined with a size of 2048 bytes + * and for ARM_MICRO 512. Because of reduce RAM size some targets need a reduced stacksize. + */ +#if defined(TARGET_STM32F070RB) && defined(TOOLCHAIN_GCC) +#define STACK_SIZE DEFAULT_STACK_SIZE/2 +#elif (defined(TARGET_EFM32HG_STK3400)) && !defined(TOOLCHAIN_ARM_MICRO) +#define STACK_SIZE 512 +#elif (defined(TARGET_EFM32LG_STK3600) || defined(TARGET_EFM32WG_STK3800) || defined(TARGET_EFM32PG_STK3401)) && !defined(TOOLCHAIN_ARM_MICRO) +#define STACK_SIZE 768 +#elif (defined(TARGET_EFM32GG_STK3700)) && !defined(TOOLCHAIN_ARM_MICRO) +#define STACK_SIZE 1536 +#elif defined(TARGET_MCU_NRF51822) || defined(TARGET_MCU_NRF52832) +#define STACK_SIZE 768 +#elif defined(TARGET_XDOT_L151CC) +#define STACK_SIZE 1024 +#else +#define STACK_SIZE DEFAULT_STACK_SIZE +#endif #define SIGNAL_PRINT_TICK 0x01 @@ -24,15 +43,15 @@ void print_tick_thread() { int main() { GREENTEA_SETUP(total_ticks + 5, "timing_drift_auto"); - - Thread tick_thread(osPriorityNormal, TEST_STACK_SIZE); + + Thread tick_thread(osPriorityNormal, STACK_SIZE); tick_thread.start(print_tick_thread); - + for (int i = 0; i <= total_ticks; i++) { Thread::wait(1000); tick_thread.signal_set(SIGNAL_PRINT_TICK); } - + tick_thread.join(); GREENTEA_TESTSUITE_RESULT(1); } diff --git a/TESTS/mbedmicro-rtos-mbed/isr/main.cpp b/TESTS/mbedmicro-rtos-mbed/isr/main.cpp index 17baca863c5..048f785377c 100644 --- a/TESTS/mbedmicro-rtos-mbed/isr/main.cpp +++ b/TESTS/mbedmicro-rtos-mbed/isr/main.cpp @@ -11,7 +11,24 @@ #define QUEUE_PUT_ISR_VALUE 128 #define QUEUE_PUT_THREAD_VALUE 127 -#define TEST_STACK_SIZE 512 +/* + * The stack size is defined in cmsis_os.h mainly dependent on the underlying toolchain and + * the C standard library. For GCC, ARM_STD and IAR it is defined with a size of 2048 bytes + * and for ARM_MICRO 512. Because of reduce RAM size some targets need a reduced stacksize. + */ +#if (defined(TARGET_EFM32HG_STK3400)) && !defined(TOOLCHAIN_ARM_MICRO) + #define STACK_SIZE 512 +#elif (defined(TARGET_EFM32LG_STK3600) || defined(TARGET_EFM32WG_STK3800) || defined(TARGET_EFM32PG_STK3401)) && !defined(TOOLCHAIN_ARM_MICRO) + #define STACK_SIZE 768 +#elif (defined(TARGET_EFM32GG_STK3700)) && !defined(TOOLCHAIN_ARM_MICRO) + #define STACK_SIZE 1536 +#elif defined(TARGET_MCU_NRF51822) || defined(TARGET_MCU_NRF52832) + #define STACK_SIZE 768 +#elif defined(TARGET_XDOT_L151CC) + #define STACK_SIZE 1024 +#else + #define STACK_SIZE DEFAULT_STACK_SIZE +#endif Queue queue; @@ -33,7 +50,7 @@ void queue_thread() { int main (void) { GREENTEA_SETUP(20, "default_auto"); - Thread thread(osPriorityNormal, TEST_STACK_SIZE); + Thread thread(osPriorityNormal, STACK_SIZE); thread.start(queue_thread); Ticker ticker; ticker.attach(queue_isr, 1.0); @@ -43,7 +60,7 @@ int main (void) { while (true) { osEvent evt = queue.get(); if (evt.status != osEventMessage) { - printf("QUEUE_GET: FAIL\r\n"); + printf("QUEUE_GET: Status(0x%02X) ... [FAIL]\r\n", evt.status); result = false; break; } else { diff --git a/TESTS/mbedmicro-rtos-mbed/mail/main.cpp b/TESTS/mbedmicro-rtos-mbed/mail/main.cpp index f66e307e521..187aa1a094f 100644 --- a/TESTS/mbedmicro-rtos-mbed/mail/main.cpp +++ b/TESTS/mbedmicro-rtos-mbed/mail/main.cpp @@ -17,7 +17,24 @@ typedef struct { #define QUEUE_SIZE 16 #define QUEUE_PUT_DELAY 100 -#define STACK_SIZE 1024 +/* + * The stack size is defined in cmsis_os.h mainly dependent on the underlying toolchain and + * the C standard library. For GCC, ARM_STD and IAR it is defined with a size of 2048 bytes + * and for ARM_MICRO 512. Because of reduce RAM size some targets need a reduced stacksize. + */ +#if (defined(TARGET_EFM32HG_STK3400)) && !defined(TOOLCHAIN_ARM_MICRO) + #define STACK_SIZE 512 +#elif (defined(TARGET_EFM32LG_STK3600) || defined(TARGET_EFM32WG_STK3800) || defined(TARGET_EFM32PG_STK3401)) && !defined(TOOLCHAIN_ARM_MICRO) + #define STACK_SIZE 768 +#elif (defined(TARGET_EFM32GG_STK3700)) && !defined(TOOLCHAIN_ARM_MICRO) + #define STACK_SIZE 1536 +#elif defined(TARGET_MCU_NRF51822) || defined(TARGET_MCU_NRF52832) + #define STACK_SIZE 768 +#elif defined(TARGET_XDOT_L151CC) + #define STACK_SIZE 1024 +#else + #define STACK_SIZE DEFAULT_STACK_SIZE +#endif Mail mail_box; diff --git a/TESTS/mbedmicro-rtos-mbed/malloc/main.cpp b/TESTS/mbedmicro-rtos-mbed/malloc/main.cpp index e9ca87bef98..fb7f8f9b9d4 100644 --- a/TESTS/mbedmicro-rtos-mbed/malloc/main.cpp +++ b/TESTS/mbedmicro-rtos-mbed/malloc/main.cpp @@ -7,7 +7,6 @@ #endif #define NUM_THREADS 5 - #if defined(__CORTEX_A9) #define THREAD_STACK_SIZE DEFAULT_STACK_SIZE #else diff --git a/TESTS/mbedmicro-rtos-mbed/mutex/main.cpp b/TESTS/mbedmicro-rtos-mbed/mutex/main.cpp index 507197499e9..6fa2efaec36 100644 --- a/TESTS/mbedmicro-rtos-mbed/mutex/main.cpp +++ b/TESTS/mbedmicro-rtos-mbed/mutex/main.cpp @@ -10,6 +10,11 @@ using namespace utest::v1; +/* + * The stack size is defined in cmsis_os.h mainly dependent on the underlying toolchain and + * the C standard library. For GCC, ARM_STD and IAR it is defined with a size of 2048 bytes + * and for ARM_MICRO 512. Because of reduce RAM size some targets need a reduced stacksize. + */ #define TEST_STACK_SIZE 512 #define TEST_ONE_SEC_MS (1000) @@ -101,7 +106,7 @@ template void test_dual_thread_nolock(void) { Mutex mutex; - Thread thread(osPriorityNormal, TEST_STACK_SIZE); + Thread thread; thread.start(callback(F, &mutex)); diff --git a/TESTS/mbedmicro-rtos-mbed/queue/main.cpp b/TESTS/mbedmicro-rtos-mbed/queue/main.cpp index 016b99c182b..d6371c4b830 100644 --- a/TESTS/mbedmicro-rtos-mbed/queue/main.cpp +++ b/TESTS/mbedmicro-rtos-mbed/queue/main.cpp @@ -17,7 +17,24 @@ typedef struct { #define QUEUE_SIZE 16 #define QUEUE_PUT_DELAY 100 -#define TEST_STACK_SIZE 512 +/* + * The stack size is defined in cmsis_os.h mainly dependent on the underlying toolchain and + * the C standard library. For GCC, ARM_STD and IAR it is defined with a size of 2048 bytes + * and for ARM_MICRO 512. Because of reduce RAM size some targets need a reduced stacksize. + */ +#if (defined(TARGET_EFM32HG_STK3400)) && !defined(TOOLCHAIN_ARM_MICRO) + #define STACK_SIZE 512 +#elif (defined(TARGET_EFM32LG_STK3600) || defined(TARGET_EFM32WG_STK3800) || defined(TARGET_EFM32PG_STK3401)) && !defined(TOOLCHAIN_ARM_MICRO) + #define STACK_SIZE 768 +#elif (defined(TARGET_EFM32GG_STK3700)) && !defined(TOOLCHAIN_ARM_MICRO) + #define STACK_SIZE 1536 +#elif defined(TARGET_MCU_NRF51822) || defined(TARGET_MCU_NRF52832) + #define STACK_SIZE 768 +#elif defined(TARGET_XDOT_L151CC) + #define STACK_SIZE 1024 +#else + #define STACK_SIZE DEFAULT_STACK_SIZE +#endif MemoryPool mpool; Queue queue; @@ -39,7 +56,7 @@ void send_thread () { int main (void) { GREENTEA_SETUP(20, "default_auto"); - Thread thread(osPriorityNormal, TEST_STACK_SIZE); + Thread thread(osPriorityNormal, STACK_SIZE); thread.start(send_thread); bool result = true; int result_counter = 0; diff --git a/TESTS/mbedmicro-rtos-mbed/semaphore/main.cpp b/TESTS/mbedmicro-rtos-mbed/semaphore/main.cpp index ba2b52f1643..626c339eff5 100644 --- a/TESTS/mbedmicro-rtos-mbed/semaphore/main.cpp +++ b/TESTS/mbedmicro-rtos-mbed/semaphore/main.cpp @@ -10,7 +10,45 @@ #define SEMAPHORE_SLOTS 2 #define SEM_CHANGES 100 -#define THREAD_STACK_SIZE 512 +/* + * The stack size is defined in cmsis_os.h mainly dependent on the underlying toolchain and + * the C standard library. For GCC, ARM_STD and IAR it is defined with a size of 2048 bytes + * and for ARM_MICRO 512. Because of reduce RAM size some targets need a reduced stacksize. + */ +#if defined(TARGET_STM32F334R8) && (defined(TOOLCHAIN_GCC) || defined(TOOLCHAIN_IAR)) + #define STACK_SIZE DEFAULT_STACK_SIZE/4 +#elif defined(TARGET_STM32F103RB) + #define STACK_SIZE DEFAULT_STACK_SIZE/2 +#elif defined(TARGET_STM32F070RB) + #define STACK_SIZE DEFAULT_STACK_SIZE/2 +#elif defined(TARGET_STM32F072RB) + #define STACK_SIZE DEFAULT_STACK_SIZE/2 +#elif defined(TARGET_STM32F302R8) && defined(TOOLCHAIN_IAR) + #define STACK_SIZE DEFAULT_STACK_SIZE/2 +#elif defined(TARGET_STM32L073RZ) + #define STACK_SIZE DEFAULT_STACK_SIZE/2 +#elif defined(TARGET_STM32F303K8) && defined(TOOLCHAIN_IAR) + #define STACK_SIZE DEFAULT_STACK_SIZE/4 +#elif (defined(TARGET_EFM32HG_STK3400)) && !defined(TOOLCHAIN_ARM_MICRO) + #define STACK_SIZE 512 +#elif (defined(TARGET_EFM32LG_STK3600) || defined(TARGET_EFM32WG_STK3800) || defined(TARGET_EFM32PG_STK3401)) && !defined(TOOLCHAIN_ARM_MICRO) + #define STACK_SIZE 768 +#elif (defined(TARGET_EFM32GG_STK3700)) && !defined(TOOLCHAIN_ARM_MICRO) + #define STACK_SIZE 1536 +#elif (defined(TARGET_EFR32)) && !defined(TOOLCHAIN_ARM_MICRO) + #define STACK_SIZE 768 +#elif defined(TARGET_MCU_NRF51822) || defined(TARGET_MCU_NRF52832) + #define STACK_SIZE 768 +#elif defined(TARGET_XDOT_L151CC) + #define STACK_SIZE 1024 +#else + #define STACK_SIZE DEFAULT_STACK_SIZE +#endif + +void print_char(char c = '*') { + printf("%c", c); + fflush(stdout); +} Semaphore two_slots(SEMAPHORE_SLOTS); @@ -24,10 +62,13 @@ void test_thread(int const *delay) { two_slots.wait(); sem_counter++; const bool sem_lock_failed = sem_counter > SEMAPHORE_SLOTS; + const char msg = sem_lock_failed ? 'e' : sem_counter + '0'; + print_char(msg); if (sem_lock_failed) { sem_defect = true; } Thread::wait(thread_delay); + print_char('.'); sem_counter--; change_counter++; two_slots.release(); @@ -40,10 +81,9 @@ int main (void) { const int t1_delay = THREAD_DELAY * 1; const int t2_delay = THREAD_DELAY * 2; const int t3_delay = THREAD_DELAY * 3; - - Thread t1(osPriorityNormal, THREAD_STACK_SIZE); - Thread t2(osPriorityNormal, THREAD_STACK_SIZE); - Thread t3(osPriorityNormal, THREAD_STACK_SIZE); + Thread t1(osPriorityNormal, STACK_SIZE); + Thread t2(osPriorityNormal, STACK_SIZE); + Thread t3(osPriorityNormal, STACK_SIZE); t1.start(callback(test_thread, &t1_delay)); t2.start(callback(test_thread, &t2_delay)); @@ -58,6 +98,7 @@ int main (void) { } } + fflush(stdout); GREENTEA_TESTSUITE_RESULT(!sem_defect); return 0; } diff --git a/TESTS/mbedmicro-rtos-mbed/signals/main.cpp b/TESTS/mbedmicro-rtos-mbed/signals/main.cpp index 06e05db970c..25e0e776374 100644 --- a/TESTS/mbedmicro-rtos-mbed/signals/main.cpp +++ b/TESTS/mbedmicro-rtos-mbed/signals/main.cpp @@ -6,12 +6,29 @@ #error [NOT_SUPPORTED] test not supported #endif -#define TEST_STACK_SIZE 512 - #define SIGNAL_SET_VALUE 0x01 const int SIGNALS_TO_EMIT = 100; const int SIGNAL_HANDLE_DELEY = 25; +/* + * The stack size is defined in cmsis_os.h mainly dependent on the underlying toolchain and + * the C standard library. For GCC, ARM_STD and IAR it is defined with a size of 2048 bytes + * and for ARM_MICRO 512. Because of reduce RAM size some targets need a reduced stacksize. + */ +#if (defined(TARGET_EFM32HG_STK3400)) && !defined(TOOLCHAIN_ARM_MICRO) + #define STACK_SIZE 512 +#elif (defined(TARGET_EFM32LG_STK3600) || defined(TARGET_EFM32WG_STK3800) || defined(TARGET_EFM32PG_STK3401)) && !defined(TOOLCHAIN_ARM_MICRO) + #define STACK_SIZE 768 +#elif (defined(TARGET_EFM32GG_STK3700)) && !defined(TOOLCHAIN_ARM_MICRO) + #define STACK_SIZE 1536 +#elif defined(TARGET_MCU_NRF51822) || defined(TARGET_MCU_NRF52832) + #define STACK_SIZE 768 +#elif defined(TARGET_XDOT_L151CC) + #define STACK_SIZE 1024 +#else + #define STACK_SIZE DEFAULT_STACK_SIZE +#endif + DigitalOut led(LED1); int signal_counter = 0; @@ -27,9 +44,8 @@ void led_thread() { int main (void) { GREENTEA_SETUP(20, "default_auto"); - Thread thread(osPriorityNormal, TEST_STACK_SIZE); + Thread thread(osPriorityNormal, STACK_SIZE); thread.start(led_thread); - bool result = false; printf("Handling %d signals...\r\n", SIGNALS_TO_EMIT); diff --git a/TESTS/mbedmicro-rtos-mbed/threads/main.cpp b/TESTS/mbedmicro-rtos-mbed/threads/main.cpp index 0f98d6621f7..f93655c9164 100644 --- a/TESTS/mbedmicro-rtos-mbed/threads/main.cpp +++ b/TESTS/mbedmicro-rtos-mbed/threads/main.cpp @@ -10,7 +10,12 @@ #error [NOT_SUPPORTED] test not supported #endif -#define THREAD_STACK_SIZE 768 +/* + * The stack size is defined in cmsis_os.h mainly dependent on the underlying toolchain and + * the C standard library. For GCC, ARM_STD and IAR it is defined with a size of 2048 bytes + * and for ARM_MICRO 512. Because of reduce RAM size some targets need a reduced stacksize. + */ +#define PARALLEL_STACK_SIZE 512 using namespace utest::v1; @@ -34,7 +39,7 @@ void increment_with_wait(counter_t* counter) { } void increment_with_child(counter_t* counter) { - Thread child(osPriorityNormal, THREAD_STACK_SIZE/2); + Thread child; child.start(callback(increment, counter)); child.join(); } @@ -44,7 +49,7 @@ void increment_with_murder(counter_t* counter) { // take ownership of the counter mutex so it prevent the child to // modify counter. LockGuard lock(counter->internal_mutex()); - Thread child(osPriorityNormal, THREAD_STACK_SIZE); + Thread child; child.start(callback(increment, counter)); child.terminate(); } @@ -62,7 +67,7 @@ void self_terminate(Thread *self) { template void test_single_thread() { counter_t counter(0); - Thread thread(osPriorityNormal, THREAD_STACK_SIZE, NULL); + Thread thread; thread.start(callback(F, &counter)); thread.join(); TEST_ASSERT_EQUAL(counter, 1); @@ -74,7 +79,7 @@ void test_parallel_threads() { Thread *threads[N]; for (int i = 0; i < N; i++) { - threads[i] = new Thread(osPriorityNormal, THREAD_STACK_SIZE); + threads[i] = new Thread(osPriorityNormal, PARALLEL_STACK_SIZE); threads[i]->start(callback(F, &counter)); } @@ -91,7 +96,7 @@ void test_serial_threads() { counter_t counter(0); for (int i = 0; i < N; i++) { - Thread thread(osPriorityNormal, THREAD_STACK_SIZE); + Thread thread; thread.start(callback(F, &counter)); thread.join(); } @@ -100,7 +105,7 @@ void test_serial_threads() { } void test_self_terminate() { - Thread *thread = new Thread(osPriorityNormal, THREAD_STACK_SIZE); + Thread *thread = new Thread(); thread->start(callback(self_terminate, thread)); thread->join(); delete thread; @@ -126,7 +131,7 @@ Case cases[] = { Case("Testing serial threads with wait", test_serial_threads<10, increment_with_wait>), Case("Testing single thread with child", test_single_thread), - Case("Testing parallel threads with child", test_parallel_threads<3, increment_with_child>), + Case("Testing parallel threads with child", test_parallel_threads<2, increment_with_child>), Case("Testing serial threads with child", test_serial_threads<10, increment_with_child>), Case("Testing single thread with murder", test_single_thread), diff --git a/cmsis/TOOLCHAIN_GCC/TARGET_CORTEX_A/cache.S b/cmsis/TOOLCHAIN_GCC/TARGET_CORTEX_A/cache.S new file mode 100644 index 00000000000..d37f889191d --- /dev/null +++ b/cmsis/TOOLCHAIN_GCC/TARGET_CORTEX_A/cache.S @@ -0,0 +1,94 @@ +/* Copyright (c) 2009 - 2012 ARM LIMITED + + All rights reserved. + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + - Neither the name of ARM nor the names of its contributors may be used + to endorse or promote products derived from this software without + specific prior written permission. + * + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + ---------------------------------------------------------------------------*/ + +/*---------------------------------------------------------------------------- + * Functions + *---------------------------------------------------------------------------*/ + .text + .global __v7_all_cache +/* + * __STATIC_ASM void __v7_all_cache(uint32_t op) { + */ +__v7_all_cache: + .arm + + PUSH {R4-R11} + + MRC p15, 1, R6, c0, c0, 1 /* Read CLIDR */ + ANDS R3, R6, #0x07000000 /* Extract coherency level */ + MOV R3, R3, LSR #23 /* Total cache levels << 1 */ + BEQ Finished /* If 0, no need to clean */ + + MOV R10, #0 /* R10 holds current cache level << 1 */ +Loop1: ADD R2, R10, R10, LSR #1 /* R2 holds cache "Set" position */ + MOV R1, R6, LSR R2 /* Bottom 3 bits are the Cache-type for this level */ + AND R1, R1, #7 /* Isolate those lower 3 bits */ + CMP R1, #2 + BLT Skip /* No cache or only instruction cache at this level */ + + MCR p15, 2, R10, c0, c0, 0 /* Write the Cache Size selection register */ + ISB /* ISB to sync the change to the CacheSizeID reg */ + MRC p15, 1, R1, c0, c0, 0 /* Reads current Cache Size ID register */ + AND R2, R1, #7 /* Extract the line length field */ + ADD R2, R2, #4 /* Add 4 for the line length offset (log2 16 bytes) */ + LDR R4, =0x3FF + ANDS R4, R4, R1, LSR #3 /* R4 is the max number on the way size (right aligned) */ + CLZ R5, R4 /* R5 is the bit position of the way size increment */ + LDR R7, =0x7FFF + ANDS R7, R7, R1, LSR #13 /* R7 is the max number of the index size (right aligned) */ + +Loop2: MOV R9, R4 /* R9 working copy of the max way size (right aligned) */ + +Loop3: ORR R11, R10, R9, LSL R5 /* Factor in the Way number and cache number into R11 */ + ORR R11, R11, R7, LSL R2 /* Factor in the Set number */ + CMP R0, #0 + BNE Dccsw + MCR p15, 0, R11, c7, c6, 2 /* DCISW. Invalidate by Set/Way */ + B cont +Dccsw: CMP R0, #1 + BNE Dccisw + MCR p15, 0, R11, c7, c10, 2 /* DCCSW. Clean by Set/Way */ + B cont +Dccisw: MCR p15, 0, R11, c7, c14, 2 /* DCCISW, Clean and Invalidate by Set/Way */ +cont: SUBS R9, R9, #1 /* Decrement the Way number */ + BGE Loop3 + SUBS R7, R7, #1 /* Decrement the Set number */ + BGE Loop2 +Skip: ADD R10, R10, #2 /* increment the cache number */ + CMP R3, R10 + BGT Loop1 + +Finished: + DSB + POP {R4-R11} + BX lr + + + .END +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ diff --git a/cmsis/TOOLCHAIN_IAR/TARGET_CORTEX_A/cache.s b/cmsis/TOOLCHAIN_IAR/TARGET_CORTEX_A/cache.s new file mode 100644 index 00000000000..00352787a20 --- /dev/null +++ b/cmsis/TOOLCHAIN_IAR/TARGET_CORTEX_A/cache.s @@ -0,0 +1,97 @@ +/* Copyright (c) 2009 - 2012 ARM LIMITED + + All rights reserved. + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + - Neither the name of ARM nor the names of its contributors may be used + to endorse or promote products derived from this software without + specific prior written permission. + * + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + ---------------------------------------------------------------------------*/ + +/*---------------------------------------------------------------------------- + * Functions + *---------------------------------------------------------------------------*/ + SECTION `.text`:CODE:NOROOT(2) + arm + PUBLIC __v7_all_cache +/* + * __STATIC_ASM void __v7_all_cache(uint32_t op) { + */ + +__v7_all_cache: + + + PUSH {R4-R11} + + MRC p15, 1, R6, c0, c0, 1 /* Read CLIDR */ + ANDS R3, R6, #0x07000000 /* Extract coherency level */ + MOV R3, R3, LSR #23 /* Total cache levels << 1 */ + BEQ Finished /* If 0, no need to clean */ + + MOV R10, #0 /* R10 holds current cache level << 1 */ +Loop1: ADD R2, R10, R10, LSR #1 /* R2 holds cache "Set" position */ + MOV R1, R6, LSR R2 /* Bottom 3 bits are the Cache-type for this level */ + AND R1, R1, #7 /* Isolate those lower 3 bits */ + CMP R1, #2 + BLT Skip /* No cache or only instruction cache at this level */ + + MCR p15, 2, R10, c0, c0, 0 /* Write the Cache Size selection register */ + ISB /* ISB to sync the change to the CacheSizeID reg */ + MRC p15, 1, R1, c0, c0, 0 /* Reads current Cache Size ID register */ + AND R2, R1, #7 /* Extract the line length field */ + ADD R2, R2, #4 /* Add 4 for the line length offset (log2 16 bytes) */ + LDR R4, =0x3FF + ANDS R4, R4, R1, LSR #3 /* R4 is the max number on the way size (right aligned) */ + CLZ R5, R4 /* R5 is the bit position of the way size increment */ + LDR R7, =0x7FFF + ANDS R7, R7, R1, LSR #13 /* R7 is the max number of the index size (right aligned) */ + +Loop2: MOV R9, R4 /* R9 working copy of the max way size (right aligned) */ + +Loop3: ORR R11, R10, R9, LSL R5 /* Factor in the Way number and cache number into R11 */ + ORR R11, R11, R7, LSL R2 /* Factor in the Set number */ + CMP R0, #0 + BNE Dccsw + MCR p15, 0, R11, c7, c6, 2 /* DCISW. Invalidate by Set/Way */ + B cont +Dccsw: CMP R0, #1 + BNE Dccisw + MCR p15, 0, R11, c7, c10, 2 /* DCCSW. Clean by Set/Way */ + B cont +Dccisw: MCR p15, 0, R11, c7, c14, 2 /* DCCISW, Clean and Invalidate by Set/Way */ +cont: SUBS R9, R9, #1 /* Decrement the Way number */ + BGE Loop3 + SUBS R7, R7, #1 /* Decrement the Set number */ + BGE Loop2 +Skip: ADD R10, R10, #2 /* increment the cache number */ + CMP R3, R10 + BGT Loop1 + +Finished: + DSB + POP {R4-R11} + BX lr + + + END +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ + diff --git a/cmsis/TOOLCHAIN_IAR/cmain.S b/cmsis/TOOLCHAIN_IAR/cmain.S new file mode 100644 index 00000000000..7395d3fa576 --- /dev/null +++ b/cmsis/TOOLCHAIN_IAR/cmain.S @@ -0,0 +1,81 @@ +/************************************************** + * + * Part two of the system initialization code, contains C-level + * initialization, thumb-2 only variant. + * + * Copyright 2006 IAR Systems. All rights reserved. + * + * $Revision: 59783 $ + * + **************************************************/ + + +; -------------------------------------------------- +; Module ?cmain, C-level initialization. +; + + + SECTION SHT$$PREINIT_ARRAY:CONST:NOROOT(2) + SECTION SHT$$INIT_ARRAY:CONST:NOROOT(2) + + SECTION .text:CODE:NOROOT(2) + + PUBLIC __cmain + ;; Keep ?main for legacy reasons, it is accessed in countless instances of cstartup.s around the world... + PUBLIC ?main + EXTWEAK __iar_data_init3 + EXTWEAK __iar_argc_argv + EXTERN __low_level_init + EXTERN __call_ctors + EXTERN main + EXTERN exit + EXTERN __iar_dynamic_initialization + EXTERN mbed_sdk_init + EXTERN SystemInit + + THUMB +__cmain: +?main: + +; Initialize segments. +; __segment_init and __low_level_init are assumed to use the same +; instruction set and to be reachable by BL from the ICODE segment +; (it is safest to link them in segment ICODE). + + FUNCALL __cmain, __low_level_init + bl __low_level_init + cmp r0,#0 + beq ?l1 + FUNCALL __cmain, __iar_data_init3 + bl __iar_data_init3 + MOVS r0,#0 ; No parameters + FUNCALL __cmain, mbed_sdk_init + BL mbed_sdk_init + MOVS r0,#0 ; No parameters + FUNCALL __cmain, __iar_dynamic_initialization + BL __iar_dynamic_initialization ; C++ dynamic initialization + +?l1: + REQUIRE ?l3 + + SECTION .text:CODE:NOROOT(2) + + PUBLIC _main + PUBLIC _call_main + THUMB + +__iar_init$$done: ; Copy initialization is done + +?l3: +_call_main: + MOVS r0,#0 ; No parameters + FUNCALL __cmain, __iar_argc_argv + BL __iar_argc_argv ; Maybe setup command line + + FUNCALL __cmain, main + BL main +_main: + FUNCALL __cmain, exit + BL exit + + END diff --git a/cmsis/arm_common_tables.h b/cmsis/arm_common_tables.h new file mode 100644 index 00000000000..039cc3d66bb --- /dev/null +++ b/cmsis/arm_common_tables.h @@ -0,0 +1,136 @@ +/* ---------------------------------------------------------------------- +* Copyright (C) 2010-2014 ARM Limited. All rights reserved. +* +* $Date: 19. March 2015 +* $Revision: V.1.4.5 +* +* Project: CMSIS DSP Library +* Title: arm_common_tables.h +* +* Description: This file has extern declaration for common tables like Bitreverse, reciprocal etc which are used across different functions +* +* Target Processor: Cortex-M4/Cortex-M3 +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions +* are met: +* - Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* - Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in +* the documentation and/or other materials provided with the +* distribution. +* - Neither the name of ARM LIMITED nor the names of its contributors +* may be used to endorse or promote products derived from this +* software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +* POSSIBILITY OF SUCH DAMAGE. +* -------------------------------------------------------------------- */ + +#ifndef _ARM_COMMON_TABLES_H +#define _ARM_COMMON_TABLES_H + +#include "arm_math.h" + +extern const uint16_t armBitRevTable[1024]; +extern const q15_t armRecipTableQ15[64]; +extern const q31_t armRecipTableQ31[64]; +//extern const q31_t realCoefAQ31[1024]; +//extern const q31_t realCoefBQ31[1024]; +extern const float32_t twiddleCoef_16[32]; +extern const float32_t twiddleCoef_32[64]; +extern const float32_t twiddleCoef_64[128]; +extern const float32_t twiddleCoef_128[256]; +extern const float32_t twiddleCoef_256[512]; +extern const float32_t twiddleCoef_512[1024]; +extern const float32_t twiddleCoef_1024[2048]; +extern const float32_t twiddleCoef_2048[4096]; +extern const float32_t twiddleCoef_4096[8192]; +#define twiddleCoef twiddleCoef_4096 +extern const q31_t twiddleCoef_16_q31[24]; +extern const q31_t twiddleCoef_32_q31[48]; +extern const q31_t twiddleCoef_64_q31[96]; +extern const q31_t twiddleCoef_128_q31[192]; +extern const q31_t twiddleCoef_256_q31[384]; +extern const q31_t twiddleCoef_512_q31[768]; +extern const q31_t twiddleCoef_1024_q31[1536]; +extern const q31_t twiddleCoef_2048_q31[3072]; +extern const q31_t twiddleCoef_4096_q31[6144]; +extern const q15_t twiddleCoef_16_q15[24]; +extern const q15_t twiddleCoef_32_q15[48]; +extern const q15_t twiddleCoef_64_q15[96]; +extern const q15_t twiddleCoef_128_q15[192]; +extern const q15_t twiddleCoef_256_q15[384]; +extern const q15_t twiddleCoef_512_q15[768]; +extern const q15_t twiddleCoef_1024_q15[1536]; +extern const q15_t twiddleCoef_2048_q15[3072]; +extern const q15_t twiddleCoef_4096_q15[6144]; +extern const float32_t twiddleCoef_rfft_32[32]; +extern const float32_t twiddleCoef_rfft_64[64]; +extern const float32_t twiddleCoef_rfft_128[128]; +extern const float32_t twiddleCoef_rfft_256[256]; +extern const float32_t twiddleCoef_rfft_512[512]; +extern const float32_t twiddleCoef_rfft_1024[1024]; +extern const float32_t twiddleCoef_rfft_2048[2048]; +extern const float32_t twiddleCoef_rfft_4096[4096]; + + +/* floating-point bit reversal tables */ +#define ARMBITREVINDEXTABLE__16_TABLE_LENGTH ((uint16_t)20 ) +#define ARMBITREVINDEXTABLE__32_TABLE_LENGTH ((uint16_t)48 ) +#define ARMBITREVINDEXTABLE__64_TABLE_LENGTH ((uint16_t)56 ) +#define ARMBITREVINDEXTABLE_128_TABLE_LENGTH ((uint16_t)208 ) +#define ARMBITREVINDEXTABLE_256_TABLE_LENGTH ((uint16_t)440 ) +#define ARMBITREVINDEXTABLE_512_TABLE_LENGTH ((uint16_t)448 ) +#define ARMBITREVINDEXTABLE1024_TABLE_LENGTH ((uint16_t)1800) +#define ARMBITREVINDEXTABLE2048_TABLE_LENGTH ((uint16_t)3808) +#define ARMBITREVINDEXTABLE4096_TABLE_LENGTH ((uint16_t)4032) + +extern const uint16_t armBitRevIndexTable16[ARMBITREVINDEXTABLE__16_TABLE_LENGTH]; +extern const uint16_t armBitRevIndexTable32[ARMBITREVINDEXTABLE__32_TABLE_LENGTH]; +extern const uint16_t armBitRevIndexTable64[ARMBITREVINDEXTABLE__64_TABLE_LENGTH]; +extern const uint16_t armBitRevIndexTable128[ARMBITREVINDEXTABLE_128_TABLE_LENGTH]; +extern const uint16_t armBitRevIndexTable256[ARMBITREVINDEXTABLE_256_TABLE_LENGTH]; +extern const uint16_t armBitRevIndexTable512[ARMBITREVINDEXTABLE_512_TABLE_LENGTH]; +extern const uint16_t armBitRevIndexTable1024[ARMBITREVINDEXTABLE1024_TABLE_LENGTH]; +extern const uint16_t armBitRevIndexTable2048[ARMBITREVINDEXTABLE2048_TABLE_LENGTH]; +extern const uint16_t armBitRevIndexTable4096[ARMBITREVINDEXTABLE4096_TABLE_LENGTH]; + +/* fixed-point bit reversal tables */ +#define ARMBITREVINDEXTABLE_FIXED___16_TABLE_LENGTH ((uint16_t)12 ) +#define ARMBITREVINDEXTABLE_FIXED___32_TABLE_LENGTH ((uint16_t)24 ) +#define ARMBITREVINDEXTABLE_FIXED___64_TABLE_LENGTH ((uint16_t)56 ) +#define ARMBITREVINDEXTABLE_FIXED__128_TABLE_LENGTH ((uint16_t)112 ) +#define ARMBITREVINDEXTABLE_FIXED__256_TABLE_LENGTH ((uint16_t)240 ) +#define ARMBITREVINDEXTABLE_FIXED__512_TABLE_LENGTH ((uint16_t)480 ) +#define ARMBITREVINDEXTABLE_FIXED_1024_TABLE_LENGTH ((uint16_t)992 ) +#define ARMBITREVINDEXTABLE_FIXED_2048_TABLE_LENGTH ((uint16_t)1984) +#define ARMBITREVINDEXTABLE_FIXED_4096_TABLE_LENGTH ((uint16_t)4032) + +extern const uint16_t armBitRevIndexTable_fixed_16[ARMBITREVINDEXTABLE_FIXED___16_TABLE_LENGTH]; +extern const uint16_t armBitRevIndexTable_fixed_32[ARMBITREVINDEXTABLE_FIXED___32_TABLE_LENGTH]; +extern const uint16_t armBitRevIndexTable_fixed_64[ARMBITREVINDEXTABLE_FIXED___64_TABLE_LENGTH]; +extern const uint16_t armBitRevIndexTable_fixed_128[ARMBITREVINDEXTABLE_FIXED__128_TABLE_LENGTH]; +extern const uint16_t armBitRevIndexTable_fixed_256[ARMBITREVINDEXTABLE_FIXED__256_TABLE_LENGTH]; +extern const uint16_t armBitRevIndexTable_fixed_512[ARMBITREVINDEXTABLE_FIXED__512_TABLE_LENGTH]; +extern const uint16_t armBitRevIndexTable_fixed_1024[ARMBITREVINDEXTABLE_FIXED_1024_TABLE_LENGTH]; +extern const uint16_t armBitRevIndexTable_fixed_2048[ARMBITREVINDEXTABLE_FIXED_2048_TABLE_LENGTH]; +extern const uint16_t armBitRevIndexTable_fixed_4096[ARMBITREVINDEXTABLE_FIXED_4096_TABLE_LENGTH]; + +/* Tables for Fast Math Sine and Cosine */ +extern const float32_t sinTable_f32[FAST_MATH_TABLE_SIZE + 1]; +extern const q31_t sinTable_q31[FAST_MATH_TABLE_SIZE + 1]; +extern const q15_t sinTable_q15[FAST_MATH_TABLE_SIZE + 1]; + +#endif /* ARM_COMMON_TABLES_H */ diff --git a/cmsis/arm_const_structs.h b/cmsis/arm_const_structs.h new file mode 100644 index 00000000000..726d06eb692 --- /dev/null +++ b/cmsis/arm_const_structs.h @@ -0,0 +1,79 @@ +/* ---------------------------------------------------------------------- +* Copyright (C) 2010-2014 ARM Limited. All rights reserved. +* +* $Date: 19. March 2015 +* $Revision: V.1.4.5 +* +* Project: CMSIS DSP Library +* Title: arm_const_structs.h +* +* Description: This file has constant structs that are initialized for +* user convenience. For example, some can be given as +* arguments to the arm_cfft_f32() function. +* +* Target Processor: Cortex-M4/Cortex-M3 +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions +* are met: +* - Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* - Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in +* the documentation and/or other materials provided with the +* distribution. +* - Neither the name of ARM LIMITED nor the names of its contributors +* may be used to endorse or promote products derived from this +* software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +* POSSIBILITY OF SUCH DAMAGE. +* -------------------------------------------------------------------- */ + +#ifndef _ARM_CONST_STRUCTS_H +#define _ARM_CONST_STRUCTS_H + +#include "arm_math.h" +#include "arm_common_tables.h" + + extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len16; + extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len32; + extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len64; + extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len128; + extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len256; + extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len512; + extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len1024; + extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len2048; + extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len4096; + + extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len16; + extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len32; + extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len64; + extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len128; + extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len256; + extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len512; + extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len1024; + extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len2048; + extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len4096; + + extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len16; + extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len32; + extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len64; + extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len128; + extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len256; + extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len512; + extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len1024; + extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len2048; + extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len4096; + +#endif diff --git a/cmsis/core_ca9.h b/cmsis/core_ca9.h new file mode 100644 index 00000000000..c7c402d7508 --- /dev/null +++ b/cmsis/core_ca9.h @@ -0,0 +1,276 @@ +/**************************************************************************//** + * @file core_ca9.h + * @brief CMSIS Cortex-A9 Core Peripheral Access Layer Header File + * @version + * @date 25 March 2013 + * + * @note + * + ******************************************************************************/ +/* Copyright (c) 2009 - 2012 ARM LIMITED + + All rights reserved. + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + - Neither the name of ARM nor the names of its contributors may be used + to endorse or promote products derived from this software without + specific prior written permission. + * + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + ---------------------------------------------------------------------------*/ + + +#if defined ( __ICCARM__ ) + #pragma system_include /* treat file as system include file for MISRA check */ +#endif + +#ifdef __cplusplus + extern "C" { +#endif + +#ifndef __CORE_CA9_H_GENERIC +#define __CORE_CA9_H_GENERIC + + +/** \page CMSIS_MISRA_Exceptions MISRA-C:2004 Compliance Exceptions + CMSIS violates the following MISRA-C:2004 rules: + + \li Required Rule 8.5, object/function definition in header file.
+ Function definitions in header files are used to allow 'inlining'. + + \li Required Rule 18.4, declaration of union type or object of union type: '{...}'.
+ Unions are used for effective representation of core registers. + + \li Advisory Rule 19.7, Function-like macro defined.
+ Function-like macros are used to allow more efficient code. + */ + + +/******************************************************************************* + * CMSIS definitions + ******************************************************************************/ +/** \ingroup Cortex_A9 + @{ + */ + +/* CMSIS CA9 definitions */ +#define __CA9_CMSIS_VERSION_MAIN (0x03) /*!< [31:16] CMSIS HAL main version */ +#define __CA9_CMSIS_VERSION_SUB (0x10) /*!< [15:0] CMSIS HAL sub version */ +#define __CA9_CMSIS_VERSION ((__CA9_CMSIS_VERSION_MAIN << 16) | \ + __CA9_CMSIS_VERSION_SUB ) /*!< CMSIS HAL version number */ + +#define __CORTEX_A (0x09) /*!< Cortex-A Core */ + + +#if defined ( __CC_ARM ) + #define __ASM __asm /*!< asm keyword for ARM Compiler */ + #define __INLINE __inline /*!< inline keyword for ARM Compiler */ + #define __STATIC_INLINE static __inline + #define __STATIC_ASM static __asm + +#elif defined ( __ICCARM__ ) + #define __ASM __asm /*!< asm keyword for IAR Compiler */ + #define __INLINE inline /*!< inline keyword for IAR Compiler. Only available in High optimization mode! */ + #define __STATIC_INLINE static inline + #define __STATIC_ASM static __asm + +#include +inline uint32_t __get_PSR(void) { + __ASM("mrs r0, cpsr"); +} + +#elif defined ( __TMS470__ ) + #define __ASM __asm /*!< asm keyword for TI CCS Compiler */ + #define __STATIC_INLINE static inline + #define __STATIC_ASM static __asm + +#elif defined ( __GNUC__ ) + #define __ASM __asm /*!< asm keyword for GNU Compiler */ + #define __INLINE inline /*!< inline keyword for GNU Compiler */ + #define __STATIC_INLINE static inline + #define __STATIC_ASM static __asm + +#elif defined ( __TASKING__ ) + #define __ASM __asm /*!< asm keyword for TASKING Compiler */ + #define __INLINE inline /*!< inline keyword for TASKING Compiler */ + #define __STATIC_INLINE static inline + #define __STATIC_ASM static __asm + +#endif + +/** __FPU_USED indicates whether an FPU is used or not. For this, __FPU_PRESENT has to be checked prior to making use of FPU specific registers and functions. +*/ +#if defined ( __CC_ARM ) + #if defined __TARGET_FPU_VFP + #if (__FPU_PRESENT == 1) + #define __FPU_USED 1 + #else + #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" + #define __FPU_USED 0 + #endif + #else + #define __FPU_USED 0 + #endif + +#elif defined ( __ICCARM__ ) + #if defined __ARMVFP__ + #if (__FPU_PRESENT == 1) + #define __FPU_USED 1 + #else + #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" + #define __FPU_USED 0 + #endif + #else + #define __FPU_USED 0 + #endif + +#elif defined ( __TMS470__ ) + #if defined __TI_VFP_SUPPORT__ + #if (__FPU_PRESENT == 1) + #define __FPU_USED 1 + #else + #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" + #define __FPU_USED 0 + #endif + #else + #define __FPU_USED 0 + #endif + +#elif defined ( __GNUC__ ) + #if defined (__VFP_FP__) && !defined(__SOFTFP__) + #if (__FPU_PRESENT == 1) + #define __FPU_USED 1 + #else + #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" + #define __FPU_USED 0 + #endif + #else + #define __FPU_USED 0 + #endif + +#elif defined ( __TASKING__ ) + #if defined __FPU_VFP__ + #if (__FPU_PRESENT == 1) + #define __FPU_USED 1 + #else + #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" + #define __FPU_USED 0 + #endif + #else + #define __FPU_USED 0 + #endif +#endif + +#include /*!< standard types definitions */ +#include "core_caInstr.h" /*!< Core Instruction Access */ +#include "core_caFunc.h" /*!< Core Function Access */ +#include "core_cm4_simd.h" /*!< Compiler specific SIMD Intrinsics */ + +#endif /* __CORE_CA9_H_GENERIC */ + +#ifndef __CMSIS_GENERIC + +#ifndef __CORE_CA9_H_DEPENDANT +#define __CORE_CA9_H_DEPENDANT + +/* check device defines and use defaults */ +#if defined __CHECK_DEVICE_DEFINES + #ifndef __CA9_REV + #define __CA9_REV 0x0000 + #warning "__CA9_REV not defined in device header file; using default!" + #endif + + #ifndef __FPU_PRESENT + #define __FPU_PRESENT 1 + #warning "__FPU_PRESENT not defined in device header file; using default!" + #endif + + #ifndef __Vendor_SysTickConfig + #define __Vendor_SysTickConfig 1 + #endif + + #if __Vendor_SysTickConfig == 0 + #error "__Vendor_SysTickConfig set to 0, but vendor systick timer must be supplied for Cortex-A9" + #endif +#endif + +/* IO definitions (access restrictions to peripheral registers) */ +/** + \defgroup CMSIS_glob_defs CMSIS Global Defines + + IO Type Qualifiers are used + \li to specify the access to peripheral variables. + \li for automatic generation of peripheral register debug information. +*/ +#ifdef __cplusplus + #define __I volatile /*!< Defines 'read only' permissions */ +#else + #define __I volatile const /*!< Defines 'read only' permissions */ +#endif +#define __O volatile /*!< Defines 'write only' permissions */ +#define __IO volatile /*!< Defines 'read / write' permissions */ + +/*@} end of group Cortex_A9 */ + + +/******************************************************************************* + * Register Abstraction + ******************************************************************************/ +/** \defgroup CMSIS_core_register Defines and Type Definitions + \brief Type definitions and defines for Cortex-A processor based devices. +*/ + +/** \ingroup CMSIS_core_register + \defgroup CMSIS_CORE Status and Control Registers + \brief Core Register type definitions. + @{ + */ + +/** \brief Union type to access the Application Program Status Register (APSR). + */ +typedef union +{ + struct + { + uint32_t _reserved0:16; /*!< bit: 0..15 Reserved */ + uint32_t GE:4; /*!< bit: 16..19 Greater than or Equal flags */ + uint32_t reserved1:7; /*!< bit: 20..23 Reserved */ + uint32_t Q:1; /*!< bit: 27 Saturation condition flag */ + uint32_t V:1; /*!< bit: 28 Overflow condition code flag */ + uint32_t C:1; /*!< bit: 29 Carry condition code flag */ + uint32_t Z:1; /*!< bit: 30 Zero condition code flag */ + uint32_t N:1; /*!< bit: 31 Negative condition code flag */ + } b; /*!< Structure used for bit access */ + uint32_t w; /*!< Type used for word access */ +} APSR_Type; + + +/*@} end of group CMSIS_CORE */ + +/*@} end of CMSIS_Core_FPUFunctions */ + + +#endif /* __CORE_CA9_H_GENERIC */ + +#endif /* __CMSIS_GENERIC */ + +#ifdef __cplusplus +} + + +#endif diff --git a/cmsis/core_caFunc.h b/cmsis/core_caFunc.h new file mode 100644 index 00000000000..6e473214b68 --- /dev/null +++ b/cmsis/core_caFunc.h @@ -0,0 +1,1444 @@ +/**************************************************************************//** + * @file core_caFunc.h + * @brief CMSIS Cortex-A Core Function Access Header File + * @version V3.10 + * @date 30 Oct 2013 + * + * @note + * + ******************************************************************************/ +/* Copyright (c) 2009 - 2013 ARM LIMITED + + All rights reserved. + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + - Neither the name of ARM nor the names of its contributors may be used + to endorse or promote products derived from this software without + specific prior written permission. + * + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + ---------------------------------------------------------------------------*/ + + +#ifndef __CORE_CAFUNC_H__ +#define __CORE_CAFUNC_H__ + + +/* ########################### Core Function Access ########################### */ +/** \ingroup CMSIS_Core_FunctionInterface + \defgroup CMSIS_Core_RegAccFunctions CMSIS Core Register Access Functions + @{ + */ + +#if defined ( __CC_ARM ) /*------------------RealView Compiler -----------------*/ +/* ARM armcc specific functions */ + +#if (__ARMCC_VERSION < 400677) + #error "Please use ARM Compiler Toolchain V4.0.677 or later!" +#endif + +#define MODE_USR 0x10 +#define MODE_FIQ 0x11 +#define MODE_IRQ 0x12 +#define MODE_SVC 0x13 +#define MODE_MON 0x16 +#define MODE_ABT 0x17 +#define MODE_HYP 0x1A +#define MODE_UND 0x1B +#define MODE_SYS 0x1F + +/** \brief Get APSR Register + + This function returns the content of the APSR Register. + + \return APSR Register value + */ +__STATIC_INLINE uint32_t __get_APSR(void) +{ + register uint32_t __regAPSR __ASM("apsr"); + return(__regAPSR); +} + + +/** \brief Get CPSR Register + + This function returns the content of the CPSR Register. + + \return CPSR Register value + */ +__STATIC_INLINE uint32_t __get_CPSR(void) +{ + register uint32_t __regCPSR __ASM("cpsr"); + return(__regCPSR); +} + +/** \brief Set Stack Pointer + + This function assigns the given value to the current stack pointer. + + \param [in] topOfStack Stack Pointer value to set + */ +register uint32_t __regSP __ASM("sp"); +__STATIC_INLINE void __set_SP(uint32_t topOfStack) +{ + __regSP = topOfStack; +} + + +/** \brief Get link register + + This function returns the value of the link register + + \return Value of link register + */ +register uint32_t __reglr __ASM("lr"); +__STATIC_INLINE uint32_t __get_LR(void) +{ + return(__reglr); +} + +/** \brief Set link register + + This function sets the value of the link register + + \param [in] lr LR value to set + */ +__STATIC_INLINE void __set_LR(uint32_t lr) +{ + __reglr = lr; +} + +/** \brief Set Process Stack Pointer + + This function assigns the given value to the USR/SYS Stack Pointer (PSP). + + \param [in] topOfProcStack USR/SYS Stack Pointer value to set + */ +__STATIC_ASM void __set_PSP(uint32_t topOfProcStack) +{ + ARM + PRESERVE8 + + BIC R0, R0, #7 ;ensure stack is 8-byte aligned + MRS R1, CPSR + CPS #MODE_SYS ;no effect in USR mode + MOV SP, R0 + MSR CPSR_c, R1 ;no effect in USR mode + ISB + BX LR + +} + +/** \brief Set User Mode + + This function changes the processor state to User Mode + */ +__STATIC_ASM void __set_CPS_USR(void) +{ + ARM + + CPS #MODE_USR + BX LR +} + + +/** \brief Enable FIQ + + This function enables FIQ interrupts by clearing the F-bit in the CPSR. + Can only be executed in Privileged modes. + */ +#define __enable_fault_irq __enable_fiq + + +/** \brief Disable FIQ + + This function disables FIQ interrupts by setting the F-bit in the CPSR. + Can only be executed in Privileged modes. + */ +#define __disable_fault_irq __disable_fiq + + +/** \brief Get FPSCR + + This function returns the current value of the Floating Point Status/Control register. + + \return Floating Point Status/Control register value + */ +__STATIC_INLINE uint32_t __get_FPSCR(void) +{ +#if (__FPU_PRESENT == 1) && (__FPU_USED == 1) + register uint32_t __regfpscr __ASM("fpscr"); + return(__regfpscr); +#else + return(0); +#endif +} + + +/** \brief Set FPSCR + + This function assigns the given value to the Floating Point Status/Control register. + + \param [in] fpscr Floating Point Status/Control value to set + */ +__STATIC_INLINE void __set_FPSCR(uint32_t fpscr) +{ +#if (__FPU_PRESENT == 1) && (__FPU_USED == 1) + register uint32_t __regfpscr __ASM("fpscr"); + __regfpscr = (fpscr); +#endif +} + +/** \brief Get FPEXC + + This function returns the current value of the Floating Point Exception Control register. + + \return Floating Point Exception Control register value + */ +__STATIC_INLINE uint32_t __get_FPEXC(void) +{ +#if (__FPU_PRESENT == 1) + register uint32_t __regfpexc __ASM("fpexc"); + return(__regfpexc); +#else + return(0); +#endif +} + + +/** \brief Set FPEXC + + This function assigns the given value to the Floating Point Exception Control register. + + \param [in] fpscr Floating Point Exception Control value to set + */ +__STATIC_INLINE void __set_FPEXC(uint32_t fpexc) +{ +#if (__FPU_PRESENT == 1) + register uint32_t __regfpexc __ASM("fpexc"); + __regfpexc = (fpexc); +#endif +} + +/** \brief Get CPACR + + This function returns the current value of the Coprocessor Access Control register. + + \return Coprocessor Access Control register value + */ +__STATIC_INLINE uint32_t __get_CPACR(void) +{ + register uint32_t __regCPACR __ASM("cp15:0:c1:c0:2"); + return __regCPACR; +} + +/** \brief Set CPACR + + This function assigns the given value to the Coprocessor Access Control register. + + \param [in] cpacr Coprocessor Acccess Control value to set + */ +__STATIC_INLINE void __set_CPACR(uint32_t cpacr) +{ + register uint32_t __regCPACR __ASM("cp15:0:c1:c0:2"); + __regCPACR = cpacr; + __ISB(); +} + +/** \brief Get CBAR + + This function returns the value of the Configuration Base Address register. + + \return Configuration Base Address register value + */ +__STATIC_INLINE uint32_t __get_CBAR() { + register uint32_t __regCBAR __ASM("cp15:4:c15:c0:0"); + return(__regCBAR); +} + +/** \brief Get TTBR0 + + This function returns the value of the Translation Table Base Register 0. + + \return Translation Table Base Register 0 value + */ +__STATIC_INLINE uint32_t __get_TTBR0() { + register uint32_t __regTTBR0 __ASM("cp15:0:c2:c0:0"); + return(__regTTBR0); +} + +/** \brief Set TTBR0 + + This function assigns the given value to the Translation Table Base Register 0. + + \param [in] ttbr0 Translation Table Base Register 0 value to set + */ +__STATIC_INLINE void __set_TTBR0(uint32_t ttbr0) { + register uint32_t __regTTBR0 __ASM("cp15:0:c2:c0:0"); + __regTTBR0 = ttbr0; + __ISB(); +} + +/** \brief Get DACR + + This function returns the value of the Domain Access Control Register. + + \return Domain Access Control Register value + */ +__STATIC_INLINE uint32_t __get_DACR() { + register uint32_t __regDACR __ASM("cp15:0:c3:c0:0"); + return(__regDACR); +} + +/** \brief Set DACR + + This function assigns the given value to the Domain Access Control Register. + + \param [in] dacr Domain Access Control Register value to set + */ +__STATIC_INLINE void __set_DACR(uint32_t dacr) { + register uint32_t __regDACR __ASM("cp15:0:c3:c0:0"); + __regDACR = dacr; + __ISB(); +} + +/******************************** Cache and BTAC enable ****************************************************/ + +/** \brief Set SCTLR + + This function assigns the given value to the System Control Register. + + \param [in] sctlr System Control Register value to set + */ +__STATIC_INLINE void __set_SCTLR(uint32_t sctlr) +{ + register uint32_t __regSCTLR __ASM("cp15:0:c1:c0:0"); + __regSCTLR = sctlr; +} + +/** \brief Get SCTLR + + This function returns the value of the System Control Register. + + \return System Control Register value + */ +__STATIC_INLINE uint32_t __get_SCTLR() { + register uint32_t __regSCTLR __ASM("cp15:0:c1:c0:0"); + return(__regSCTLR); +} + +/** \brief Enable Caches + + Enable Caches + */ +__STATIC_INLINE void __enable_caches(void) { + // Set I bit 12 to enable I Cache + // Set C bit 2 to enable D Cache + __set_SCTLR( __get_SCTLR() | (1 << 12) | (1 << 2)); +} + +/** \brief Disable Caches + + Disable Caches + */ +__STATIC_INLINE void __disable_caches(void) { + // Clear I bit 12 to disable I Cache + // Clear C bit 2 to disable D Cache + __set_SCTLR( __get_SCTLR() & ~(1 << 12) & ~(1 << 2)); + __ISB(); +} + +/** \brief Enable BTAC + + Enable BTAC + */ +__STATIC_INLINE void __enable_btac(void) { + // Set Z bit 11 to enable branch prediction + __set_SCTLR( __get_SCTLR() | (1 << 11)); + __ISB(); +} + +/** \brief Disable BTAC + + Disable BTAC + */ +__STATIC_INLINE void __disable_btac(void) { + // Clear Z bit 11 to disable branch prediction + __set_SCTLR( __get_SCTLR() & ~(1 << 11)); +} + + +/** \brief Enable MMU + + Enable MMU + */ +__STATIC_INLINE void __enable_mmu(void) { + // Set M bit 0 to enable the MMU + // Set AFE bit to enable simplified access permissions model + // Clear TRE bit to disable TEX remap and A bit to disable strict alignment fault checking + __set_SCTLR( (__get_SCTLR() & ~(1 << 28) & ~(1 << 1)) | 1 | (1 << 29)); + __ISB(); +} + +/** \brief Disable MMU + + Disable MMU + */ +__STATIC_INLINE void __disable_mmu(void) { + // Clear M bit 0 to disable the MMU + __set_SCTLR( __get_SCTLR() & ~1); + __ISB(); +} + +/******************************** TLB maintenance operations ************************************************/ +/** \brief Invalidate the whole tlb + + TLBIALL. Invalidate the whole tlb + */ + +__STATIC_INLINE void __ca9u_inv_tlb_all(void) { + register uint32_t __TLBIALL __ASM("cp15:0:c8:c7:0"); + __TLBIALL = 0; + __DSB(); + __ISB(); +} + +/******************************** BTB maintenance operations ************************************************/ +/** \brief Invalidate entire branch predictor array + + BPIALL. Branch Predictor Invalidate All. + */ + +__STATIC_INLINE void __v7_inv_btac(void) { + register uint32_t __BPIALL __ASM("cp15:0:c7:c5:6"); + __BPIALL = 0; + __DSB(); //ensure completion of the invalidation + __ISB(); //ensure instruction fetch path sees new state +} + + +/******************************** L1 cache operations ******************************************************/ + +/** \brief Invalidate the whole I$ + + ICIALLU. Instruction Cache Invalidate All to PoU + */ +__STATIC_INLINE void __v7_inv_icache_all(void) { + register uint32_t __ICIALLU __ASM("cp15:0:c7:c5:0"); + __ICIALLU = 0; + __DSB(); //ensure completion of the invalidation + __ISB(); //ensure instruction fetch path sees new I cache state +} + +/** \brief Clean D$ by MVA + + DCCMVAC. Data cache clean by MVA to PoC + */ +__STATIC_INLINE void __v7_clean_dcache_mva(void *va) { + register uint32_t __DCCMVAC __ASM("cp15:0:c7:c10:1"); + __DCCMVAC = (uint32_t)va; + __DMB(); //ensure the ordering of data cache maintenance operations and their effects +} + +/** \brief Invalidate D$ by MVA + + DCIMVAC. Data cache invalidate by MVA to PoC + */ +__STATIC_INLINE void __v7_inv_dcache_mva(void *va) { + register uint32_t __DCIMVAC __ASM("cp15:0:c7:c6:1"); + __DCIMVAC = (uint32_t)va; + __DMB(); //ensure the ordering of data cache maintenance operations and their effects +} + +/** \brief Clean and Invalidate D$ by MVA + + DCCIMVAC. Data cache clean and invalidate by MVA to PoC + */ +__STATIC_INLINE void __v7_clean_inv_dcache_mva(void *va) { + register uint32_t __DCCIMVAC __ASM("cp15:0:c7:c14:1"); + __DCCIMVAC = (uint32_t)va; + __DMB(); //ensure the ordering of data cache maintenance operations and their effects +} + +/** \brief Clean and Invalidate the entire data or unified cache + + Generic mechanism for cleaning/invalidating the entire data or unified cache to the point of coherency. + */ +#pragma push +#pragma arm +__STATIC_ASM void __v7_all_cache(uint32_t op) { + ARM + + PUSH {R4-R11} + + MRC p15, 1, R6, c0, c0, 1 // Read CLIDR + ANDS R3, R6, #0x07000000 // Extract coherency level + MOV R3, R3, LSR #23 // Total cache levels << 1 + BEQ Finished // If 0, no need to clean + + MOV R10, #0 // R10 holds current cache level << 1 +Loop1 ADD R2, R10, R10, LSR #1 // R2 holds cache "Set" position + MOV R1, R6, LSR R2 // Bottom 3 bits are the Cache-type for this level + AND R1, R1, #7 // Isolate those lower 3 bits + CMP R1, #2 + BLT Skip // No cache or only instruction cache at this level + + MCR p15, 2, R10, c0, c0, 0 // Write the Cache Size selection register + ISB // ISB to sync the change to the CacheSizeID reg + MRC p15, 1, R1, c0, c0, 0 // Reads current Cache Size ID register + AND R2, R1, #7 // Extract the line length field + ADD R2, R2, #4 // Add 4 for the line length offset (log2 16 bytes) + LDR R4, =0x3FF + ANDS R4, R4, R1, LSR #3 // R4 is the max number on the way size (right aligned) + CLZ R5, R4 // R5 is the bit position of the way size increment + LDR R7, =0x7FFF + ANDS R7, R7, R1, LSR #13 // R7 is the max number of the index size (right aligned) + +Loop2 MOV R9, R4 // R9 working copy of the max way size (right aligned) + +Loop3 ORR R11, R10, R9, LSL R5 // Factor in the Way number and cache number into R11 + ORR R11, R11, R7, LSL R2 // Factor in the Set number + CMP R0, #0 + BNE Dccsw + MCR p15, 0, R11, c7, c6, 2 // DCISW. Invalidate by Set/Way + B cont +Dccsw CMP R0, #1 + BNE Dccisw + MCR p15, 0, R11, c7, c10, 2 // DCCSW. Clean by Set/Way + B cont +Dccisw MCR p15, 0, R11, c7, c14, 2 // DCCISW. Clean and Invalidate by Set/Way +cont SUBS R9, R9, #1 // Decrement the Way number + BGE Loop3 + SUBS R7, R7, #1 // Decrement the Set number + BGE Loop2 +Skip ADD R10, R10, #2 // Increment the cache number + CMP R3, R10 + BGT Loop1 + +Finished + DSB + POP {R4-R11} + BX lr + +} +#pragma pop + + +/** \brief Invalidate the whole D$ + + DCISW. Invalidate by Set/Way + */ + +__STATIC_INLINE void __v7_inv_dcache_all(void) { + __v7_all_cache(0); +} + +/** \brief Clean the whole D$ + + DCCSW. Clean by Set/Way + */ + +__STATIC_INLINE void __v7_clean_dcache_all(void) { + __v7_all_cache(1); +} + +/** \brief Clean and invalidate the whole D$ + + DCCISW. Clean and Invalidate by Set/Way + */ + +__STATIC_INLINE void __v7_clean_inv_dcache_all(void) { + __v7_all_cache(2); +} + +#include "core_ca_mmu.h" + +#elif (defined (__ICCARM__)) /*---------------- ICC Compiler ---------------------*/ + +#define __inline inline + +inline static uint32_t __disable_irq_iar() { + int irq_dis = __get_CPSR() & 0x80; // 7bit CPSR.I + __disable_irq(); + return irq_dis; +} + +#define MODE_USR 0x10 +#define MODE_FIQ 0x11 +#define MODE_IRQ 0x12 +#define MODE_SVC 0x13 +#define MODE_MON 0x16 +#define MODE_ABT 0x17 +#define MODE_HYP 0x1A +#define MODE_UND 0x1B +#define MODE_SYS 0x1F + +/** \brief Set Process Stack Pointer + + This function assigns the given value to the USR/SYS Stack Pointer (PSP). + + \param [in] topOfProcStack USR/SYS Stack Pointer value to set + */ +// from rt_CMSIS.c +__arm static inline void __set_PSP(uint32_t topOfProcStack) { +__asm( + " ARM\n" +// " PRESERVE8\n" + + " BIC R0, R0, #7 ;ensure stack is 8-byte aligned \n" + " MRS R1, CPSR \n" + " CPS #0x1F ;no effect in USR mode \n" // MODE_SYS + " MOV SP, R0 \n" + " MSR CPSR_c, R1 ;no effect in USR mode \n" + " ISB \n" + " BX LR \n"); +} + +/** \brief Set User Mode + + This function changes the processor state to User Mode + */ +// from rt_CMSIS.c +__arm static inline void __set_CPS_USR(void) { +__asm( + " ARM \n" + + " CPS #0x10 \n" // MODE_USR + " BX LR\n"); +} + +/** \brief Set TTBR0 + + This function assigns the given value to the Translation Table Base Register 0. + + \param [in] ttbr0 Translation Table Base Register 0 value to set + */ +// from mmu_Renesas_RZ_A1.c +__STATIC_INLINE void __set_TTBR0(uint32_t ttbr0) { + __MCR(15, 0, ttbr0, 2, 0, 0); // reg to cp15 + __ISB(); +} + +/** \brief Set DACR + + This function assigns the given value to the Domain Access Control Register. + + \param [in] dacr Domain Access Control Register value to set + */ +// from mmu_Renesas_RZ_A1.c +__STATIC_INLINE void __set_DACR(uint32_t dacr) { + __MCR(15, 0, dacr, 3, 0, 0); // reg to cp15 + __ISB(); +} + + +/******************************** Cache and BTAC enable ****************************************************/ +/** \brief Set SCTLR + + This function assigns the given value to the System Control Register. + + \param [in] sctlr System Control Register value to set + */ +// from __enable_mmu() +__STATIC_INLINE void __set_SCTLR(uint32_t sctlr) { + __MCR(15, 0, sctlr, 1, 0, 0); // reg to cp15 +} + +/** \brief Get SCTLR + + This function returns the value of the System Control Register. + + \return System Control Register value + */ +// from __enable_mmu() +__STATIC_INLINE uint32_t __get_SCTLR() { + uint32_t __regSCTLR = __MRC(15, 0, 1, 0, 0); + return __regSCTLR; +} + +/** \brief Enable Caches + + Enable Caches + */ +// from system_Renesas_RZ_A1.c +__STATIC_INLINE void __enable_caches(void) { + __set_SCTLR( __get_SCTLR() | (1 << 12) | (1 << 2)); +} + +/** \brief Enable BTAC + + Enable BTAC + */ +// from system_Renesas_RZ_A1.c +__STATIC_INLINE void __enable_btac(void) { + __set_SCTLR( __get_SCTLR() | (1 << 11)); + __ISB(); +} + +/** \brief Enable MMU + + Enable MMU + */ +// from system_Renesas_RZ_A1.c +__STATIC_INLINE void __enable_mmu(void) { + // Set M bit 0 to enable the MMU + // Set AFE bit to enable simplified access permissions model + // Clear TRE bit to disable TEX remap and A bit to disable strict alignment fault checking + __set_SCTLR( (__get_SCTLR() & ~(1 << 28) & ~(1 << 1)) | 1 | (1 << 29)); + __ISB(); +} + +/******************************** TLB maintenance operations ************************************************/ +/** \brief Invalidate the whole tlb + + TLBIALL. Invalidate the whole tlb + */ +// from system_Renesas_RZ_A1.c +__STATIC_INLINE void __ca9u_inv_tlb_all(void) { + uint32_t val = 0; + __MCR(15, 0, val, 8, 7, 0); // reg to cp15 + __MCR(15, 0, val, 8, 6, 0); // reg to cp15 + __MCR(15, 0, val, 8, 5, 0); // reg to cp15 + __DSB(); + __ISB(); +} + +/******************************** BTB maintenance operations ************************************************/ +/** \brief Invalidate entire branch predictor array + + BPIALL. Branch Predictor Invalidate All. + */ +// from system_Renesas_RZ_A1.c +__STATIC_INLINE void __v7_inv_btac(void) { + uint32_t val = 0; + __MCR(15, 0, val, 7, 5, 6); // reg to cp15 + __DSB(); //ensure completion of the invalidation + __ISB(); //ensure instruction fetch path sees new state +} + + +/******************************** L1 cache operations ******************************************************/ + +/** \brief Invalidate the whole I$ + + ICIALLU. Instruction Cache Invalidate All to PoU + */ +// from system_Renesas_RZ_A1.c +__STATIC_INLINE void __v7_inv_icache_all(void) { + uint32_t val = 0; + __MCR(15, 0, val, 7, 5, 0); // reg to cp15 + __DSB(); //ensure completion of the invalidation + __ISB(); //ensure instruction fetch path sees new I cache state +} + +// from __v7_inv_dcache_all() +__arm static inline void __v7_all_cache(uint32_t op) { +__asm( + " ARM \n" + + " PUSH {R4-R11} \n" + + " MRC p15, 1, R6, c0, c0, 1\n" // Read CLIDR + " ANDS R3, R6, #0x07000000\n" // Extract coherency level + " MOV R3, R3, LSR #23\n" // Total cache levels << 1 + " BEQ Finished\n" // If 0, no need to clean + + " MOV R10, #0\n" // R10 holds current cache level << 1 + "Loop1: ADD R2, R10, R10, LSR #1\n" // R2 holds cache "Set" position + " MOV R1, R6, LSR R2 \n" // Bottom 3 bits are the Cache-type for this level + " AND R1, R1, #7 \n" // Isolate those lower 3 bits + " CMP R1, #2 \n" + " BLT Skip \n" // No cache or only instruction cache at this level + + " MCR p15, 2, R10, c0, c0, 0 \n" // Write the Cache Size selection register + " ISB \n" // ISB to sync the change to the CacheSizeID reg + " MRC p15, 1, R1, c0, c0, 0 \n" // Reads current Cache Size ID register + " AND R2, R1, #7 \n" // Extract the line length field + " ADD R2, R2, #4 \n" // Add 4 for the line length offset (log2 16 bytes) + " movw R4, #0x3FF \n" + " ANDS R4, R4, R1, LSR #3 \n" // R4 is the max number on the way size (right aligned) + " CLZ R5, R4 \n" // R5 is the bit position of the way size increment + " movw R7, #0x7FFF \n" + " ANDS R7, R7, R1, LSR #13 \n" // R7 is the max number of the index size (right aligned) + + "Loop2: MOV R9, R4 \n" // R9 working copy of the max way size (right aligned) + + "Loop3: ORR R11, R10, R9, LSL R5 \n" // Factor in the Way number and cache number into R11 + " ORR R11, R11, R7, LSL R2 \n" // Factor in the Set number + " CMP R0, #0 \n" + " BNE Dccsw \n" + " MCR p15, 0, R11, c7, c6, 2 \n" // DCISW. Invalidate by Set/Way + " B cont \n" + "Dccsw: CMP R0, #1 \n" + " BNE Dccisw \n" + " MCR p15, 0, R11, c7, c10, 2 \n" // DCCSW. Clean by Set/Way + " B cont \n" + "Dccisw: MCR p15, 0, R11, c7, c14, 2 \n" // DCCISW, Clean and Invalidate by Set/Way + "cont: SUBS R9, R9, #1 \n" // Decrement the Way number + " BGE Loop3 \n" + " SUBS R7, R7, #1 \n" // Decrement the Set number + " BGE Loop2 \n" + "Skip: ADD R10, R10, #2 \n" // increment the cache number + " CMP R3, R10 \n" + " BGT Loop1 \n" + + "Finished: \n" + " DSB \n" + " POP {R4-R11} \n" + " BX lr \n" ); +} + +/** \brief Invalidate the whole D$ + + DCISW. Invalidate by Set/Way + */ +// from system_Renesas_RZ_A1.c +__STATIC_INLINE void __v7_inv_dcache_all(void) { + __v7_all_cache(0); +} +/** \brief Clean the whole D$ + + DCCSW. Clean by Set/Way + */ + +__STATIC_INLINE void __v7_clean_dcache_all(void) { + __v7_all_cache(1); +} + +/** \brief Clean and invalidate the whole D$ + + DCCISW. Clean and Invalidate by Set/Way + */ + +__STATIC_INLINE void __v7_clean_inv_dcache_all(void) { + __v7_all_cache(2); +} +/** \brief Clean and Invalidate D$ by MVA + + DCCIMVAC. Data cache clean and invalidate by MVA to PoC + */ +__STATIC_INLINE void __v7_clean_inv_dcache_mva(void *va) { + __MCR(15, 0, (uint32_t)va, 7, 14, 1); + __DMB(); +} + +#include "core_ca_mmu.h" + +#elif (defined (__GNUC__)) /*------------------ GNU Compiler ---------------------*/ +/* GNU gcc specific functions */ + +#define MODE_USR 0x10 +#define MODE_FIQ 0x11 +#define MODE_IRQ 0x12 +#define MODE_SVC 0x13 +#define MODE_MON 0x16 +#define MODE_ABT 0x17 +#define MODE_HYP 0x1A +#define MODE_UND 0x1B +#define MODE_SYS 0x1F + + +__attribute__( ( always_inline ) ) __STATIC_INLINE void __enable_irq(void) +{ + __ASM volatile ("cpsie i"); +} + +/** \brief Disable IRQ Interrupts + + This function disables IRQ interrupts by setting the I-bit in the CPSR. + Can only be executed in Privileged modes. + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __disable_irq(void) +{ + uint32_t result; + + __ASM volatile ("mrs %0, cpsr" : "=r" (result)); + __ASM volatile ("cpsid i"); + return(result & 0x80); +} + + +/** \brief Get APSR Register + + This function returns the content of the APSR Register. + + \return APSR Register value + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_APSR(void) +{ +#if 1 + register uint32_t __regAPSR; + __ASM volatile ("mrs %0, apsr" : "=r" (__regAPSR) ); +#else + register uint32_t __regAPSR __ASM("apsr"); +#endif + return(__regAPSR); +} + + +/** \brief Get CPSR Register + + This function returns the content of the CPSR Register. + + \return CPSR Register value + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_CPSR(void) +{ +#if 1 + register uint32_t __regCPSR; + __ASM volatile ("mrs %0, cpsr" : "=r" (__regCPSR)); +#else + register uint32_t __regCPSR __ASM("cpsr"); +#endif + return(__regCPSR); +} + +#if 0 +/** \brief Set Stack Pointer + + This function assigns the given value to the current stack pointer. + + \param [in] topOfStack Stack Pointer value to set + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_SP(uint32_t topOfStack) +{ + register uint32_t __regSP __ASM("sp"); + __regSP = topOfStack; +} +#endif + +/** \brief Get link register + + This function returns the value of the link register + + \return Value of link register + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_LR(void) +{ + register uint32_t __reglr __ASM("lr"); + return(__reglr); +} + +#if 0 +/** \brief Set link register + + This function sets the value of the link register + + \param [in] lr LR value to set + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_LR(uint32_t lr) +{ + register uint32_t __reglr __ASM("lr"); + __reglr = lr; +} +#endif + +/** \brief Set Process Stack Pointer + + This function assigns the given value to the USR/SYS Stack Pointer (PSP). + + \param [in] topOfProcStack USR/SYS Stack Pointer value to set + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_PSP(uint32_t topOfProcStack) +{ + __asm__ volatile ( + ".ARM;" + ".eabi_attribute Tag_ABI_align8_preserved,1;" + + "BIC R0, R0, #7;" /* ;ensure stack is 8-byte aligned */ + "MRS R1, CPSR;" + "CPS %0;" /* ;no effect in USR mode */ + "MOV SP, R0;" + "MSR CPSR_c, R1;" /* ;no effect in USR mode */ + "ISB;" + //"BX LR;" + : + : "i"(MODE_SYS) + : "r0", "r1"); + return; +} + +/** \brief Set User Mode + + This function changes the processor state to User Mode + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_CPS_USR(void) +{ + __asm__ volatile ( + ".ARM;" + + "CPS %0;" + //"BX LR;" + : + : "i"(MODE_USR) + : ); + return; +} + + +/** \brief Enable FIQ + + This function enables FIQ interrupts by clearing the F-bit in the CPSR. + Can only be executed in Privileged modes. + */ +#define __enable_fault_irq() __asm__ volatile ("cpsie f") + + +/** \brief Disable FIQ + + This function disables FIQ interrupts by setting the F-bit in the CPSR. + Can only be executed in Privileged modes. + */ +#define __disable_fault_irq() __asm__ volatile ("cpsid f") + + +/** \brief Get FPSCR + + This function returns the current value of the Floating Point Status/Control register. + + \return Floating Point Status/Control register value + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_FPSCR(void) +{ +#if (__FPU_PRESENT == 1) && (__FPU_USED == 1) +#if 1 + uint32_t result; + + __ASM volatile ("vmrs %0, fpscr" : "=r" (result) ); + return (result); +#else + register uint32_t __regfpscr __ASM("fpscr"); + return(__regfpscr); +#endif +#else + return(0); +#endif +} + + +/** \brief Set FPSCR + + This function assigns the given value to the Floating Point Status/Control register. + + \param [in] fpscr Floating Point Status/Control value to set + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_FPSCR(uint32_t fpscr) +{ +#if (__FPU_PRESENT == 1) && (__FPU_USED == 1) +#if 1 + __ASM volatile ("vmsr fpscr, %0" : : "r" (fpscr) ); +#else + register uint32_t __regfpscr __ASM("fpscr"); + __regfpscr = (fpscr); +#endif +#endif +} + +/** \brief Get FPEXC + + This function returns the current value of the Floating Point Exception Control register. + + \return Floating Point Exception Control register value + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_FPEXC(void) +{ +#if (__FPU_PRESENT == 1) +#if 1 + uint32_t result; + + __ASM volatile ("vmrs %0, fpexc" : "=r" (result)); + return (result); +#else + register uint32_t __regfpexc __ASM("fpexc"); + return(__regfpexc); +#endif +#else + return(0); +#endif +} + + +/** \brief Set FPEXC + + This function assigns the given value to the Floating Point Exception Control register. + + \param [in] fpscr Floating Point Exception Control value to set + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_FPEXC(uint32_t fpexc) +{ +#if (__FPU_PRESENT == 1) +#if 1 + __ASM volatile ("vmsr fpexc, %0" : : "r" (fpexc)); +#else + register uint32_t __regfpexc __ASM("fpexc"); + __regfpexc = (fpexc); +#endif +#endif +} + +/** \brief Get CPACR + + This function returns the current value of the Coprocessor Access Control register. + + \return Coprocessor Access Control register value + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_CPACR(void) +{ +#if 1 + register uint32_t __regCPACR; + __ASM volatile ("mrc p15, 0, %0, c1, c0, 2" : "=r" (__regCPACR)); +#else + register uint32_t __regCPACR __ASM("cp15:0:c1:c0:2"); +#endif + return __regCPACR; +} + +/** \brief Set CPACR + + This function assigns the given value to the Coprocessor Access Control register. + + \param [in] cpacr Coprocessor Acccess Control value to set + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_CPACR(uint32_t cpacr) +{ +#if 1 + __ASM volatile ("mcr p15, 0, %0, c1, c0, 2" : : "r" (cpacr)); +#else + register uint32_t __regCPACR __ASM("cp15:0:c1:c0:2"); + __regCPACR = cpacr; +#endif + __ISB(); +} + +/** \brief Get CBAR + + This function returns the value of the Configuration Base Address register. + + \return Configuration Base Address register value + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_CBAR() { +#if 1 + register uint32_t __regCBAR; + __ASM volatile ("mrc p15, 4, %0, c15, c0, 0" : "=r" (__regCBAR)); +#else + register uint32_t __regCBAR __ASM("cp15:4:c15:c0:0"); +#endif + return(__regCBAR); +} + +/** \brief Get TTBR0 + + This function returns the value of the Translation Table Base Register 0. + + \return Translation Table Base Register 0 value + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_TTBR0() { +#if 1 + register uint32_t __regTTBR0; + __ASM volatile ("mrc p15, 0, %0, c2, c0, 0" : "=r" (__regTTBR0)); +#else + register uint32_t __regTTBR0 __ASM("cp15:0:c2:c0:0"); +#endif + return(__regTTBR0); +} + +/** \brief Set TTBR0 + + This function assigns the given value to the Translation Table Base Register 0. + + \param [in] ttbr0 Translation Table Base Register 0 value to set + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_TTBR0(uint32_t ttbr0) { +#if 1 + __ASM volatile ("mcr p15, 0, %0, c2, c0, 0" : : "r" (ttbr0)); +#else + register uint32_t __regTTBR0 __ASM("cp15:0:c2:c0:0"); + __regTTBR0 = ttbr0; +#endif + __ISB(); +} + +/** \brief Get DACR + + This function returns the value of the Domain Access Control Register. + + \return Domain Access Control Register value + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_DACR() { +#if 1 + register uint32_t __regDACR; + __ASM volatile ("mrc p15, 0, %0, c3, c0, 0" : "=r" (__regDACR)); +#else + register uint32_t __regDACR __ASM("cp15:0:c3:c0:0"); +#endif + return(__regDACR); +} + +/** \brief Set DACR + + This function assigns the given value to the Domain Access Control Register. + + \param [in] dacr Domain Access Control Register value to set + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_DACR(uint32_t dacr) { +#if 1 + __ASM volatile ("mcr p15, 0, %0, c3, c0, 0" : : "r" (dacr)); +#else + register uint32_t __regDACR __ASM("cp15:0:c3:c0:0"); + __regDACR = dacr; +#endif + __ISB(); +} + +/******************************** Cache and BTAC enable ****************************************************/ + +/** \brief Set SCTLR + + This function assigns the given value to the System Control Register. + + \param [in] sctlr System Control Register value to set + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_SCTLR(uint32_t sctlr) +{ +#if 1 + __ASM volatile ("mcr p15, 0, %0, c1, c0, 0" : : "r" (sctlr)); +#else + register uint32_t __regSCTLR __ASM("cp15:0:c1:c0:0"); + __regSCTLR = sctlr; +#endif +} + +/** \brief Get SCTLR + + This function returns the value of the System Control Register. + + \return System Control Register value + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_SCTLR() { +#if 1 + register uint32_t __regSCTLR; + __ASM volatile ("mrc p15, 0, %0, c1, c0, 0" : "=r" (__regSCTLR)); +#else + register uint32_t __regSCTLR __ASM("cp15:0:c1:c0:0"); +#endif + return(__regSCTLR); +} + +/** \brief Enable Caches + + Enable Caches + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE void __enable_caches(void) { + // Set I bit 12 to enable I Cache + // Set C bit 2 to enable D Cache + __set_SCTLR( __get_SCTLR() | (1 << 12) | (1 << 2)); +} + +/** \brief Disable Caches + + Disable Caches + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE void __disable_caches(void) { + // Clear I bit 12 to disable I Cache + // Clear C bit 2 to disable D Cache + __set_SCTLR( __get_SCTLR() & ~(1 << 12) & ~(1 << 2)); + __ISB(); +} + +/** \brief Enable BTAC + + Enable BTAC + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE void __enable_btac(void) { + // Set Z bit 11 to enable branch prediction + __set_SCTLR( __get_SCTLR() | (1 << 11)); + __ISB(); +} + +/** \brief Disable BTAC + + Disable BTAC + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE void __disable_btac(void) { + // Clear Z bit 11 to disable branch prediction + __set_SCTLR( __get_SCTLR() & ~(1 << 11)); +} + + +/** \brief Enable MMU + + Enable MMU + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE void __enable_mmu(void) { + // Set M bit 0 to enable the MMU + // Set AFE bit to enable simplified access permissions model + // Clear TRE bit to disable TEX remap and A bit to disable strict alignment fault checking + __set_SCTLR( (__get_SCTLR() & ~(1 << 28) & ~(1 << 1)) | 1 | (1 << 29)); + __ISB(); +} + +/** \brief Disable MMU + + Disable MMU + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE void __disable_mmu(void) { + // Clear M bit 0 to disable the MMU + __set_SCTLR( __get_SCTLR() & ~1); + __ISB(); +} + +/******************************** TLB maintenance operations ************************************************/ +/** \brief Invalidate the whole tlb + + TLBIALL. Invalidate the whole tlb + */ + +__attribute__( ( always_inline ) ) __STATIC_INLINE void __ca9u_inv_tlb_all(void) { +#if 1 + __ASM volatile ("mcr p15, 0, %0, c8, c7, 0" : : "r" (0)); +#else + register uint32_t __TLBIALL __ASM("cp15:0:c8:c7:0"); + __TLBIALL = 0; +#endif + __DSB(); + __ISB(); +} + +/******************************** BTB maintenance operations ************************************************/ +/** \brief Invalidate entire branch predictor array + + BPIALL. Branch Predictor Invalidate All. + */ + +__attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_inv_btac(void) { +#if 1 + __ASM volatile ("mcr p15, 0, %0, c7, c5, 6" : : "r" (0)); +#else + register uint32_t __BPIALL __ASM("cp15:0:c7:c5:6"); + __BPIALL = 0; +#endif + __DSB(); //ensure completion of the invalidation + __ISB(); //ensure instruction fetch path sees new state +} + + +/******************************** L1 cache operations ******************************************************/ + +/** \brief Invalidate the whole I$ + + ICIALLU. Instruction Cache Invalidate All to PoU + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_inv_icache_all(void) { +#if 1 + __ASM volatile ("mcr p15, 0, %0, c7, c5, 0" : : "r" (0)); +#else + register uint32_t __ICIALLU __ASM("cp15:0:c7:c5:0"); + __ICIALLU = 0; +#endif + __DSB(); //ensure completion of the invalidation + __ISB(); //ensure instruction fetch path sees new I cache state +} + +/** \brief Clean D$ by MVA + + DCCMVAC. Data cache clean by MVA to PoC + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_clean_dcache_mva(void *va) { +#if 1 + __ASM volatile ("mcr p15, 0, %0, c7, c10, 1" : : "r" ((uint32_t)va)); +#else + register uint32_t __DCCMVAC __ASM("cp15:0:c7:c10:1"); + __DCCMVAC = (uint32_t)va; +#endif + __DMB(); //ensure the ordering of data cache maintenance operations and their effects +} + +/** \brief Invalidate D$ by MVA + + DCIMVAC. Data cache invalidate by MVA to PoC + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_inv_dcache_mva(void *va) { +#if 1 + __ASM volatile ("mcr p15, 0, %0, c7, c6, 1" : : "r" ((uint32_t)va)); +#else + register uint32_t __DCIMVAC __ASM("cp15:0:c7:c6:1"); + __DCIMVAC = (uint32_t)va; +#endif + __DMB(); //ensure the ordering of data cache maintenance operations and their effects +} + +/** \brief Clean and Invalidate D$ by MVA + + DCCIMVAC. Data cache clean and invalidate by MVA to PoC + */ +__attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_clean_inv_dcache_mva(void *va) { +#if 1 + __ASM volatile ("mcr p15, 0, %0, c7, c14, 1" : : "r" ((uint32_t)va)); +#else + register uint32_t __DCCIMVAC __ASM("cp15:0:c7:c14:1"); + __DCCIMVAC = (uint32_t)va; +#endif + __DMB(); //ensure the ordering of data cache maintenance operations and their effects +} + +/** \brief Clean and Invalidate the entire data or unified cache + + Generic mechanism for cleaning/invalidating the entire data or unified cache to the point of coherency. + */ +extern void __v7_all_cache(uint32_t op); + + +/** \brief Invalidate the whole D$ + + DCISW. Invalidate by Set/Way + */ + +__attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_inv_dcache_all(void) { + __v7_all_cache(0); +} + +/** \brief Clean the whole D$ + + DCCSW. Clean by Set/Way + */ + +__attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_clean_dcache_all(void) { + __v7_all_cache(1); +} + +/** \brief Clean and invalidate the whole D$ + + DCCISW. Clean and Invalidate by Set/Way + */ + +__attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_clean_inv_dcache_all(void) { + __v7_all_cache(2); +} + +#include "core_ca_mmu.h" + +#elif (defined (__TASKING__)) /*--------------- TASKING Compiler -----------------*/ + +#error TASKING Compiler support not implemented for Cortex-A + +#endif + +/*@} end of CMSIS_Core_RegAccFunctions */ + + +#endif /* __CORE_CAFUNC_H__ */ diff --git a/cmsis/core_caInstr.h b/cmsis/core_caInstr.h new file mode 100644 index 00000000000..b1d34357650 --- /dev/null +++ b/cmsis/core_caInstr.h @@ -0,0 +1,45 @@ +/**************************************************************************//** + * @file core_caInstr.h + * @brief CMSIS Cortex-A9 Core Peripheral Access Layer Header File + * @version + * @date 04. December 2012 + * + * @note + * + ******************************************************************************/ +/* Copyright (c) 2009 - 2012 ARM LIMITED + + All rights reserved. + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + - Neither the name of ARM nor the names of its contributors may be used + to endorse or promote products derived from this software without + specific prior written permission. + * + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + ---------------------------------------------------------------------------*/ + +#ifndef __CORE_CAINSTR_H__ +#define __CORE_CAINSTR_H__ + +#define __CORTEX_M 0x3 +#include "core_cmInstr.h" +#undef __CORTEX_M + +#endif + diff --git a/cmsis/core_ca_mmu.h b/cmsis/core_ca_mmu.h new file mode 100644 index 00000000000..189b073dbc9 --- /dev/null +++ b/cmsis/core_ca_mmu.h @@ -0,0 +1,847 @@ +;/**************************************************************************//** +; * @file core_ca_mmu.h +; * @brief MMU Startup File for A9_MP Device Series +; * @version V1.01 +; * @date 10 Sept 2014 +; * +; * @note +; * +; ******************************************************************************/ +;/* Copyright (c) 2012-2014 ARM LIMITED +; +; All rights reserved. +; Redistribution and use in source and binary forms, with or without +; modification, are permitted provided that the following conditions are met: +; - Redistributions of source code must retain the above copyright +; notice, this list of conditions and the following disclaimer. +; - Redistributions in binary form must reproduce the above copyright +; notice, this list of conditions and the following disclaimer in the +; documentation and/or other materials provided with the distribution. +; - Neither the name of ARM nor the names of its contributors may be used +; to endorse or promote products derived from this software without +; specific prior written permission. +; * +; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +; ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE +; LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +; SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +; CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +; ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +; POSSIBILITY OF SUCH DAMAGE. +; ---------------------------------------------------------------------------*/ + +#ifdef __cplusplus + extern "C" { +#endif + +#ifndef _MMU_FUNC_H +#define _MMU_FUNC_H + +#define SECTION_DESCRIPTOR (0x2) +#define SECTION_MASK (0xFFFFFFFC) + +#define SECTION_TEXCB_MASK (0xFFFF8FF3) +#define SECTION_B_SHIFT (2) +#define SECTION_C_SHIFT (3) +#define SECTION_TEX0_SHIFT (12) +#define SECTION_TEX1_SHIFT (13) +#define SECTION_TEX2_SHIFT (14) + +#define SECTION_XN_MASK (0xFFFFFFEF) +#define SECTION_XN_SHIFT (4) + +#define SECTION_DOMAIN_MASK (0xFFFFFE1F) +#define SECTION_DOMAIN_SHIFT (5) + +#define SECTION_P_MASK (0xFFFFFDFF) +#define SECTION_P_SHIFT (9) + +#define SECTION_AP_MASK (0xFFFF73FF) +#define SECTION_AP_SHIFT (10) +#define SECTION_AP2_SHIFT (15) + +#define SECTION_S_MASK (0xFFFEFFFF) +#define SECTION_S_SHIFT (16) + +#define SECTION_NG_MASK (0xFFFDFFFF) +#define SECTION_NG_SHIFT (17) + +#define SECTION_NS_MASK (0xFFF7FFFF) +#define SECTION_NS_SHIFT (19) + + +#define PAGE_L1_DESCRIPTOR (0x1) +#define PAGE_L1_MASK (0xFFFFFFFC) + +#define PAGE_L2_4K_DESC (0x2) +#define PAGE_L2_4K_MASK (0xFFFFFFFD) + +#define PAGE_L2_64K_DESC (0x1) +#define PAGE_L2_64K_MASK (0xFFFFFFFC) + +#define PAGE_4K_TEXCB_MASK (0xFFFFFE33) +#define PAGE_4K_B_SHIFT (2) +#define PAGE_4K_C_SHIFT (3) +#define PAGE_4K_TEX0_SHIFT (6) +#define PAGE_4K_TEX1_SHIFT (7) +#define PAGE_4K_TEX2_SHIFT (8) + +#define PAGE_64K_TEXCB_MASK (0xFFFF8FF3) +#define PAGE_64K_B_SHIFT (2) +#define PAGE_64K_C_SHIFT (3) +#define PAGE_64K_TEX0_SHIFT (12) +#define PAGE_64K_TEX1_SHIFT (13) +#define PAGE_64K_TEX2_SHIFT (14) + +#define PAGE_TEXCB_MASK (0xFFFF8FF3) +#define PAGE_B_SHIFT (2) +#define PAGE_C_SHIFT (3) +#define PAGE_TEX_SHIFT (12) + +#define PAGE_XN_4K_MASK (0xFFFFFFFE) +#define PAGE_XN_4K_SHIFT (0) +#define PAGE_XN_64K_MASK (0xFFFF7FFF) +#define PAGE_XN_64K_SHIFT (15) + + +#define PAGE_DOMAIN_MASK (0xFFFFFE1F) +#define PAGE_DOMAIN_SHIFT (5) + +#define PAGE_P_MASK (0xFFFFFDFF) +#define PAGE_P_SHIFT (9) + +#define PAGE_AP_MASK (0xFFFFFDCF) +#define PAGE_AP_SHIFT (4) +#define PAGE_AP2_SHIFT (9) + +#define PAGE_S_MASK (0xFFFFFBFF) +#define PAGE_S_SHIFT (10) + +#define PAGE_NG_MASK (0xFFFFF7FF) +#define PAGE_NG_SHIFT (11) + +#define PAGE_NS_MASK (0xFFFFFFF7) +#define PAGE_NS_SHIFT (3) + +#define OFFSET_1M (0x00100000) +#define OFFSET_64K (0x00010000) +#define OFFSET_4K (0x00001000) + +#define DESCRIPTOR_FAULT (0x00000000) + +/* ########################### MMU Function Access ########################### */ +/** \ingroup MMU_FunctionInterface + \defgroup MMU_Functions MMU Functions Interface + @{ + */ + +/* Attributes enumerations */ + +/* Region size attributes */ +typedef enum +{ + SECTION, + PAGE_4k, + PAGE_64k, +} mmu_region_size_Type; + +/* Region type attributes */ +typedef enum +{ + NORMAL, + DEVICE, + SHARED_DEVICE, + NON_SHARED_DEVICE, + STRONGLY_ORDERED +} mmu_memory_Type; + +/* Region cacheability attributes */ +typedef enum +{ + NON_CACHEABLE, + WB_WA, + WT, + WB_NO_WA, +} mmu_cacheability_Type; + +/* Region parity check attributes */ +typedef enum +{ + ECC_DISABLED, + ECC_ENABLED, +} mmu_ecc_check_Type; + +/* Region execution attributes */ +typedef enum +{ + EXECUTE, + NON_EXECUTE, +} mmu_execute_Type; + +/* Region global attributes */ +typedef enum +{ + GLOBAL, + NON_GLOBAL, +} mmu_global_Type; + +/* Region shareability attributes */ +typedef enum +{ + NON_SHARED, + SHARED, +} mmu_shared_Type; + +/* Region security attributes */ +typedef enum +{ + SECURE, + NON_SECURE, +} mmu_secure_Type; + +/* Region access attributes */ +typedef enum +{ + NO_ACCESS, + RW, + READ, +} mmu_access_Type; + +/* Memory Region definition */ +typedef struct RegionStruct { + mmu_region_size_Type rg_t; + mmu_memory_Type mem_t; + uint8_t domain; + mmu_cacheability_Type inner_norm_t; + mmu_cacheability_Type outer_norm_t; + mmu_ecc_check_Type e_t; + mmu_execute_Type xn_t; + mmu_global_Type g_t; + mmu_secure_Type sec_t; + mmu_access_Type priv_t; + mmu_access_Type user_t; + mmu_shared_Type sh_t; + +} mmu_region_attributes_Type; + +/** \brief Set section execution-never attribute + + The function sets section execution-never attribute + + \param [out] descriptor_l1 L1 descriptor. + \param [in] xn Section execution-never attribute : EXECUTE , NON_EXECUTE. + + \return 0 + */ +__STATIC_INLINE int __xn_section(uint32_t *descriptor_l1, mmu_execute_Type xn) +{ + *descriptor_l1 &= SECTION_XN_MASK; + *descriptor_l1 |= ((xn & 0x1) << SECTION_XN_SHIFT); + return 0; +} + +/** \brief Set section domain + + The function sets section domain + + \param [out] descriptor_l1 L1 descriptor. + \param [in] domain Section domain + + \return 0 + */ +__STATIC_INLINE int __domain_section(uint32_t *descriptor_l1, uint8_t domain) +{ + *descriptor_l1 &= SECTION_DOMAIN_MASK; + *descriptor_l1 |= ((domain & 0xF) << SECTION_DOMAIN_SHIFT); + return 0; +} + +/** \brief Set section parity check + + The function sets section parity check + + \param [out] descriptor_l1 L1 descriptor. + \param [in] p_bit Parity check: ECC_DISABLED, ECC_ENABLED + + \return 0 + */ +__STATIC_INLINE int __p_section(uint32_t *descriptor_l1, mmu_ecc_check_Type p_bit) +{ + *descriptor_l1 &= SECTION_P_MASK; + *descriptor_l1 |= ((p_bit & 0x1) << SECTION_P_SHIFT); + return 0; +} + +/** \brief Set section access privileges + + The function sets section access privileges + + \param [out] descriptor_l1 L1 descriptor. + \param [in] user User Level Access: NO_ACCESS, RW, READ + \param [in] priv Privilege Level Access: NO_ACCESS, RW, READ + \param [in] afe Access flag enable + + \return 0 + */ +__STATIC_INLINE int __ap_section(uint32_t *descriptor_l1, mmu_access_Type user, mmu_access_Type priv, uint32_t afe) +{ + uint32_t ap = 0; + + if (afe == 0) { //full access + if ((priv == NO_ACCESS) && (user == NO_ACCESS)) { ap = 0x0; } + else if ((priv == RW) && (user == NO_ACCESS)) { ap = 0x1; } + else if ((priv == RW) && (user == READ)) { ap = 0x2; } + else if ((priv == RW) && (user == RW)) { ap = 0x3; } + else if ((priv == READ) && (user == NO_ACCESS)) { ap = 0x5; } + else if ((priv == READ) && (user == READ)) { ap = 0x7; } + } + + else { //Simplified access + if ((priv == RW) && (user == NO_ACCESS)) { ap = 0x1; } + else if ((priv == RW) && (user == RW)) { ap = 0x3; } + else if ((priv == READ) && (user == NO_ACCESS)) { ap = 0x5; } + else if ((priv == READ) && (user == READ)) { ap = 0x7; } + } + + *descriptor_l1 &= SECTION_AP_MASK; + *descriptor_l1 |= (ap & 0x3) << SECTION_AP_SHIFT; + *descriptor_l1 |= ((ap & 0x4)>>2) << SECTION_AP2_SHIFT; + + return 0; +} + +/** \brief Set section shareability + + The function sets section shareability + + \param [out] descriptor_l1 L1 descriptor. + \param [in] s_bit Section shareability: NON_SHARED, SHARED + + \return 0 + */ +__STATIC_INLINE int __shared_section(uint32_t *descriptor_l1, mmu_shared_Type s_bit) +{ + *descriptor_l1 &= SECTION_S_MASK; + *descriptor_l1 |= ((s_bit & 0x1) << SECTION_S_SHIFT); + return 0; +} + +/** \brief Set section Global attribute + + The function sets section Global attribute + + \param [out] descriptor_l1 L1 descriptor. + \param [in] g_bit Section attribute: GLOBAL, NON_GLOBAL + + \return 0 + */ +__STATIC_INLINE int __global_section(uint32_t *descriptor_l1, mmu_global_Type g_bit) +{ + *descriptor_l1 &= SECTION_NG_MASK; + *descriptor_l1 |= ((g_bit & 0x1) << SECTION_NG_SHIFT); + return 0; +} + +/** \brief Set section Security attribute + + The function sets section Global attribute + + \param [out] descriptor_l1 L1 descriptor. + \param [in] s_bit Section Security attribute: SECURE, NON_SECURE + + \return 0 + */ +__STATIC_INLINE int __secure_section(uint32_t *descriptor_l1, mmu_secure_Type s_bit) +{ + *descriptor_l1 &= SECTION_NS_MASK; + *descriptor_l1 |= ((s_bit & 0x1) << SECTION_NS_SHIFT); + return 0; +} + +/* Page 4k or 64k */ +/** \brief Set 4k/64k page execution-never attribute + + The function sets 4k/64k page execution-never attribute + + \param [out] descriptor_l2 L2 descriptor. + \param [in] xn Page execution-never attribute : EXECUTE , NON_EXECUTE. + \param [in] page Page size: PAGE_4k, PAGE_64k, + + \return 0 + */ +__STATIC_INLINE int __xn_page(uint32_t *descriptor_l2, mmu_execute_Type xn, mmu_region_size_Type page) +{ + if (page == PAGE_4k) + { + *descriptor_l2 &= PAGE_XN_4K_MASK; + *descriptor_l2 |= ((xn & 0x1) << PAGE_XN_4K_SHIFT); + } + else + { + *descriptor_l2 &= PAGE_XN_64K_MASK; + *descriptor_l2 |= ((xn & 0x1) << PAGE_XN_64K_SHIFT); + } + return 0; +} + +/** \brief Set 4k/64k page domain + + The function sets 4k/64k page domain + + \param [out] descriptor_l1 L1 descriptor. + \param [in] domain Page domain + + \return 0 + */ +__STATIC_INLINE int __domain_page(uint32_t *descriptor_l1, uint8_t domain) +{ + *descriptor_l1 &= PAGE_DOMAIN_MASK; + *descriptor_l1 |= ((domain & 0xf) << PAGE_DOMAIN_SHIFT); + return 0; +} + +/** \brief Set 4k/64k page parity check + + The function sets 4k/64k page parity check + + \param [out] descriptor_l1 L1 descriptor. + \param [in] p_bit Parity check: ECC_DISABLED, ECC_ENABLED + + \return 0 + */ +__STATIC_INLINE int __p_page(uint32_t *descriptor_l1, mmu_ecc_check_Type p_bit) +{ + *descriptor_l1 &= SECTION_P_MASK; + *descriptor_l1 |= ((p_bit & 0x1) << SECTION_P_SHIFT); + return 0; +} + +/** \brief Set 4k/64k page access privileges + + The function sets 4k/64k page access privileges + + \param [out] descriptor_l2 L2 descriptor. + \param [in] user User Level Access: NO_ACCESS, RW, READ + \param [in] priv Privilege Level Access: NO_ACCESS, RW, READ + \param [in] afe Access flag enable + + \return 0 + */ +__STATIC_INLINE int __ap_page(uint32_t *descriptor_l2, mmu_access_Type user, mmu_access_Type priv, uint32_t afe) +{ + uint32_t ap = 0; + + if (afe == 0) { //full access + if ((priv == NO_ACCESS) && (user == NO_ACCESS)) { ap = 0x0; } + else if ((priv == RW) && (user == NO_ACCESS)) { ap = 0x1; } + else if ((priv == RW) && (user == READ)) { ap = 0x2; } + else if ((priv == RW) && (user == RW)) { ap = 0x3; } + else if ((priv == READ) && (user == NO_ACCESS)) { ap = 0x5; } + else if ((priv == READ) && (user == READ)) { ap = 0x6; } + } + + else { //Simplified access + if ((priv == RW) && (user == NO_ACCESS)) { ap = 0x1; } + else if ((priv == RW) && (user == RW)) { ap = 0x3; } + else if ((priv == READ) && (user == NO_ACCESS)) { ap = 0x5; } + else if ((priv == READ) && (user == READ)) { ap = 0x7; } + } + + *descriptor_l2 &= PAGE_AP_MASK; + *descriptor_l2 |= (ap & 0x3) << PAGE_AP_SHIFT; + *descriptor_l2 |= ((ap & 0x4)>>2) << PAGE_AP2_SHIFT; + + return 0; +} + +/** \brief Set 4k/64k page shareability + + The function sets 4k/64k page shareability + + \param [out] descriptor_l2 L2 descriptor. + \param [in] s_bit 4k/64k page shareability: NON_SHARED, SHARED + + \return 0 + */ +__STATIC_INLINE int __shared_page(uint32_t *descriptor_l2, mmu_shared_Type s_bit) +{ + *descriptor_l2 &= PAGE_S_MASK; + *descriptor_l2 |= ((s_bit & 0x1) << PAGE_S_SHIFT); + return 0; +} + +/** \brief Set 4k/64k page Global attribute + + The function sets 4k/64k page Global attribute + + \param [out] descriptor_l2 L2 descriptor. + \param [in] g_bit 4k/64k page attribute: GLOBAL, NON_GLOBAL + + \return 0 + */ +__STATIC_INLINE int __global_page(uint32_t *descriptor_l2, mmu_global_Type g_bit) +{ + *descriptor_l2 &= PAGE_NG_MASK; + *descriptor_l2 |= ((g_bit & 0x1) << PAGE_NG_SHIFT); + return 0; +} + +/** \brief Set 4k/64k page Security attribute + + The function sets 4k/64k page Global attribute + + \param [out] descriptor_l1 L1 descriptor. + \param [in] s_bit 4k/64k page Security attribute: SECURE, NON_SECURE + + \return 0 + */ +__STATIC_INLINE int __secure_page(uint32_t *descriptor_l1, mmu_secure_Type s_bit) +{ + *descriptor_l1 &= PAGE_NS_MASK; + *descriptor_l1 |= ((s_bit & 0x1) << PAGE_NS_SHIFT); + return 0; +} + + +/** \brief Set Section memory attributes + + The function sets section memory attributes + + \param [out] descriptor_l1 L1 descriptor. + \param [in] mem Section memory type: NORMAL, DEVICE, SHARED_DEVICE, NON_SHARED_DEVICE, STRONGLY_ORDERED + \param [in] outer Outer cacheability: NON_CACHEABLE, WB_WA, WT, WB_NO_WA, + \param [in] inner Inner cacheability: NON_CACHEABLE, WB_WA, WT, WB_NO_WA, + + \return 0 + */ +__STATIC_INLINE int __memory_section(uint32_t *descriptor_l1, mmu_memory_Type mem, mmu_cacheability_Type outer, mmu_cacheability_Type inner) +{ + *descriptor_l1 &= SECTION_TEXCB_MASK; + + if (STRONGLY_ORDERED == mem) + { + return 0; + } + else if (SHARED_DEVICE == mem) + { + *descriptor_l1 |= (1 << SECTION_B_SHIFT); + } + else if (NON_SHARED_DEVICE == mem) + { + *descriptor_l1 |= (1 << SECTION_TEX1_SHIFT); + } + else if (NORMAL == mem) + { + *descriptor_l1 |= 1 << SECTION_TEX2_SHIFT; + switch(inner) + { + case NON_CACHEABLE: + break; + case WB_WA: + *descriptor_l1 |= (1 << SECTION_B_SHIFT); + break; + case WT: + *descriptor_l1 |= 1 << SECTION_C_SHIFT; + break; + case WB_NO_WA: + *descriptor_l1 |= (1 << SECTION_B_SHIFT) | (1 << SECTION_C_SHIFT); + break; + } + switch(outer) + { + case NON_CACHEABLE: + break; + case WB_WA: + *descriptor_l1 |= (1 << SECTION_TEX0_SHIFT); + break; + case WT: + *descriptor_l1 |= 1 << SECTION_TEX1_SHIFT; + break; + case WB_NO_WA: + *descriptor_l1 |= (1 << SECTION_TEX0_SHIFT) | (1 << SECTION_TEX0_SHIFT); + break; + } + } + + return 0; +} + +/** \brief Set 4k/64k page memory attributes + + The function sets 4k/64k page memory attributes + + \param [out] descriptor_l2 L2 descriptor. + \param [in] mem 4k/64k page memory type: NORMAL, DEVICE, SHARED_DEVICE, NON_SHARED_DEVICE, STRONGLY_ORDERED + \param [in] outer Outer cacheability: NON_CACHEABLE, WB_WA, WT, WB_NO_WA, + \param [in] inner Inner cacheability: NON_CACHEABLE, WB_WA, WT, WB_NO_WA, + + \return 0 + */ +__STATIC_INLINE int __memory_page(uint32_t *descriptor_l2, mmu_memory_Type mem, mmu_cacheability_Type outer, mmu_cacheability_Type inner, mmu_region_size_Type page) +{ + *descriptor_l2 &= PAGE_4K_TEXCB_MASK; + + if (page == PAGE_64k) + { + //same as section + __memory_section(descriptor_l2, mem, outer, inner); + } + else + { + if (STRONGLY_ORDERED == mem) + { + return 0; + } + else if (SHARED_DEVICE == mem) + { + *descriptor_l2 |= (1 << PAGE_4K_B_SHIFT); + } + else if (NON_SHARED_DEVICE == mem) + { + *descriptor_l2 |= (1 << PAGE_4K_TEX1_SHIFT); + } + else if (NORMAL == mem) + { + *descriptor_l2 |= 1 << PAGE_4K_TEX2_SHIFT; + switch(inner) + { + case NON_CACHEABLE: + break; + case WB_WA: + *descriptor_l2 |= (1 << PAGE_4K_B_SHIFT); + break; + case WT: + *descriptor_l2 |= 1 << PAGE_4K_C_SHIFT; + break; + case WB_NO_WA: + *descriptor_l2 |= (1 << PAGE_4K_B_SHIFT) | (1 << PAGE_4K_C_SHIFT); + break; + } + switch(outer) + { + case NON_CACHEABLE: + break; + case WB_WA: + *descriptor_l2 |= (1 << PAGE_4K_TEX0_SHIFT); + break; + case WT: + *descriptor_l2 |= 1 << PAGE_4K_TEX1_SHIFT; + break; + case WB_NO_WA: + *descriptor_l2 |= (1 << PAGE_4K_TEX0_SHIFT) | (1 << PAGE_4K_TEX0_SHIFT); + break; + } + } + } + + return 0; +} + +/** \brief Create a L1 section descriptor + + The function creates a section descriptor. + + Assumptions: + - 16MB super sections not supported + - TEX remap disabled, so memory type and attributes are described directly by bits in the descriptor + - Functions always return 0 + + \param [out] descriptor L1 descriptor + \param [out] descriptor2 L2 descriptor + \param [in] reg Section attributes + + \return 0 + */ +__STATIC_INLINE int __get_section_descriptor(uint32_t *descriptor, mmu_region_attributes_Type reg) +{ + *descriptor = 0; + + __memory_section(descriptor, reg.mem_t, reg.outer_norm_t, reg.inner_norm_t); + __xn_section(descriptor,reg.xn_t); + __domain_section(descriptor, reg.domain); + __p_section(descriptor, reg.e_t); + __ap_section(descriptor, reg.priv_t, reg.user_t, 1); + __shared_section(descriptor,reg.sh_t); + __global_section(descriptor,reg.g_t); + __secure_section(descriptor,reg.sec_t); + *descriptor &= SECTION_MASK; + *descriptor |= SECTION_DESCRIPTOR; + + return 0; + +} + + +/** \brief Create a L1 and L2 4k/64k page descriptor + + The function creates a 4k/64k page descriptor. + Assumptions: + - TEX remap disabled, so memory type and attributes are described directly by bits in the descriptor + - Functions always return 0 + + \param [out] descriptor L1 descriptor + \param [out] descriptor2 L2 descriptor + \param [in] reg 4k/64k page attributes + + \return 0 + */ +__STATIC_INLINE int __get_page_descriptor(uint32_t *descriptor, uint32_t *descriptor2, mmu_region_attributes_Type reg) +{ + *descriptor = 0; + *descriptor2 = 0; + + switch (reg.rg_t) + { + case PAGE_4k: + __memory_page(descriptor2, reg.mem_t, reg.outer_norm_t, reg.inner_norm_t, PAGE_4k); + __xn_page(descriptor2, reg.xn_t, PAGE_4k); + __domain_page(descriptor, reg.domain); + __p_page(descriptor, reg.e_t); + __ap_page(descriptor2, reg.priv_t, reg.user_t, 1); + __shared_page(descriptor2,reg.sh_t); + __global_page(descriptor2,reg.g_t); + __secure_page(descriptor,reg.sec_t); + *descriptor &= PAGE_L1_MASK; + *descriptor |= PAGE_L1_DESCRIPTOR; + *descriptor2 &= PAGE_L2_4K_MASK; + *descriptor2 |= PAGE_L2_4K_DESC; + break; + + case PAGE_64k: + __memory_page(descriptor2, reg.mem_t, reg.outer_norm_t, reg.inner_norm_t, PAGE_64k); + __xn_page(descriptor2, reg.xn_t, PAGE_64k); + __domain_page(descriptor, reg.domain); + __p_page(descriptor, reg.e_t); + __ap_page(descriptor2, reg.priv_t, reg.user_t, 1); + __shared_page(descriptor2,reg.sh_t); + __global_page(descriptor2,reg.g_t); + __secure_page(descriptor,reg.sec_t); + *descriptor &= PAGE_L1_MASK; + *descriptor |= PAGE_L1_DESCRIPTOR; + *descriptor2 &= PAGE_L2_64K_MASK; + *descriptor2 |= PAGE_L2_64K_DESC; + break; + + case SECTION: + //error + break; + + } + + return 0; + +} + +/** \brief Create a 1MB Section + + \param [in] ttb Translation table base address + \param [in] base_address Section base address + \param [in] count Number of sections to create + \param [in] descriptor_l1 L1 descriptor (region attributes) + + */ +__STATIC_INLINE void __TTSection(uint32_t *ttb, uint32_t base_address, uint32_t count, uint32_t descriptor_l1) +{ + uint32_t offset; + uint32_t entry; + uint32_t i; + + offset = base_address >> 20; + entry = (base_address & 0xFFF00000) | descriptor_l1; + + //4 bytes aligned + ttb = ttb + offset; + + for (i = 0; i < count; i++ ) + { + //4 bytes aligned + *ttb++ = entry; + entry += OFFSET_1M; + } +} + +/** \brief Create a 4k page entry + + \param [in] ttb L1 table base address + \param [in] base_address 4k base address + \param [in] count Number of 4k pages to create + \param [in] descriptor_l1 L1 descriptor (region attributes) + \param [in] ttb_l2 L2 table base address + \param [in] descriptor_l2 L2 descriptor (region attributes) + + */ +__STATIC_INLINE void __TTPage_4k(uint32_t *ttb, uint32_t base_address, uint32_t count, uint32_t descriptor_l1, uint32_t *ttb_l2, uint32_t descriptor_l2 ) +{ + + uint32_t offset, offset2; + uint32_t entry, entry2; + uint32_t i; + + + offset = base_address >> 20; + entry = ((int)ttb_l2 & 0xFFFFFC00) | descriptor_l1; + + //4 bytes aligned + ttb += offset; + //create l1_entry + *ttb = entry; + + offset2 = (base_address & 0xff000) >> 12; + ttb_l2 += offset2; + entry2 = (base_address & 0xFFFFF000) | descriptor_l2; + for (i = 0; i < count; i++ ) + { + //4 bytes aligned + *ttb_l2++ = entry2; + entry2 += OFFSET_4K; + } +} + +/** \brief Create a 64k page entry + + \param [in] ttb L1 table base address + \param [in] base_address 64k base address + \param [in] count Number of 64k pages to create + \param [in] descriptor_l1 L1 descriptor (region attributes) + \param [in] ttb_l2 L2 table base address + \param [in] descriptor_l2 L2 descriptor (region attributes) + + */ +__STATIC_INLINE void __TTPage_64k(uint32_t *ttb, uint32_t base_address, uint32_t count, uint32_t descriptor_l1, uint32_t *ttb_l2, uint32_t descriptor_l2 ) +{ + uint32_t offset, offset2; + uint32_t entry, entry2; + uint32_t i,j; + + + offset = base_address >> 20; + entry = ((int)ttb_l2 & 0xFFFFFC00) | descriptor_l1; + + //4 bytes aligned + ttb += offset; + //create l1_entry + *ttb = entry; + + offset2 = (base_address & 0xff000) >> 12; + ttb_l2 += offset2; + entry2 = (base_address & 0xFFFF0000) | descriptor_l2; + for (i = 0; i < count; i++ ) + { + //create 16 entries + for (j = 0; j < 16; j++) + //4 bytes aligned + *ttb_l2++ = entry2; + entry2 += OFFSET_64K; + } +} + +/*@} end of MMU_Functions */ +#endif + +#ifdef __cplusplus +} +#endif diff --git a/doxygen_options.json b/doxygen_options.json deleted file mode 100644 index 11871773d79..00000000000 --- a/doxygen_options.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "ENABLE_PREPROCESSING": "YES", - "MACRO_EXPANSION": "YES", - "EXPAND_ONLY_PREDEF": "NO", - "SEARCH_INCLUDES": "YES", - "INCLUDE_PATH": "", - "INCLUDE_FILE_PATTERNS": "", - "PREDEFINED": "DOXYGEN_ONLY \"MBED_DEPRECATED_SINCE(f, g)=\" \"MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, M)=\"", - "EXPAND_AS_DEFINED": "", - "SKIP_FUNCTION_MACROS": "NO", - "EXCLUDE_PATTERNS": "*/tools/* */TESTS/* */targets/* */features/FEATURE_*/* */features/mbedtls/* */features/nanostack/* */features/storage/* */features/unsupported/* */features/frameworks/* */features/filesystem/fat/* */BUILD/* */rtos/* */events/* */cmsis/* */hal/* */features/*" -} \ No newline at end of file diff --git a/drivers/AnalogIn.h b/drivers/AnalogIn.h index e81428fc21f..3a0505808f7 100644 --- a/drivers/AnalogIn.h +++ b/drivers/AnalogIn.h @@ -18,7 +18,7 @@ #include "platform/platform.h" -#if defined (DEVICE_ANALOGIN) || defined(DOXYGEN_ONLY) +#if DEVICE_ANALOGIN #include "hal/analogin_api.h" #include "platform/SingletonPtr.h" @@ -26,10 +26,11 @@ namespace mbed { /** \addtogroup drivers */ +/** @{*/ /** An analog input, used for reading the voltage on a pin * - * @note Synchronization level: Thread safe + * @Note Synchronization level: Thread safe * * Example: * @code @@ -47,7 +48,6 @@ namespace mbed { * } * } * @endcode - * @ingroup drivers */ class AnalogIn { @@ -56,6 +56,7 @@ class AnalogIn { /** Create an AnalogIn, connected to the specified pin * * @param pin AnalogIn pin to connect to + * @param name (optional) A string to identify the object */ AnalogIn(PinName pin) { lock(); @@ -128,3 +129,4 @@ class AnalogIn { #endif +/** @}*/ diff --git a/drivers/AnalogOut.h b/drivers/AnalogOut.h index cde5cf26dbc..ad14dee807d 100644 --- a/drivers/AnalogOut.h +++ b/drivers/AnalogOut.h @@ -18,17 +18,18 @@ #include "platform/platform.h" -#if defined (DEVICE_ANALOGOUT) || defined(DOXYGEN_ONLY) +#if DEVICE_ANALOGOUT #include "hal/analogout_api.h" #include "platform/PlatformMutex.h" namespace mbed { /** \addtogroup drivers */ +/** @{*/ /** An analog output, used for setting the voltage on a pin * - * @note Synchronization level: Thread safe + * @Note Synchronization level: Thread safe * * Example: * @code @@ -47,7 +48,6 @@ namespace mbed { * } * } * @endcode - * @ingroup drivers */ class AnalogOut { @@ -55,7 +55,7 @@ class AnalogOut { /** Create an AnalogOut connected to the specified pin * - * @param pin AnalogOut pin to connect to + * @param AnalogOut pin to connect to (18) */ AnalogOut(PinName pin) { analogout_init(&_dac, pin); @@ -146,3 +146,5 @@ class AnalogOut { #endif #endif + +/** @}*/ diff --git a/drivers/BusIn.h b/drivers/BusIn.h index ddf432ee1c3..f11709add60 100644 --- a/drivers/BusIn.h +++ b/drivers/BusIn.h @@ -22,11 +22,11 @@ namespace mbed { /** \addtogroup drivers */ +/** @{*/ /** A digital input bus, used for reading the state of a collection of pins * - * @note Synchronization level: Thread safe - * @ingroup drivers + * @Note Synchronization level: Thread safe */ class BusIn { @@ -35,22 +35,7 @@ class BusIn { /** Create an BusIn, connected to the specified pins * - * @param p0 DigitalIn pin to connect to bus bit - * @param p1 DigitalIn pin to connect to bus bit - * @param p2 DigitalIn pin to connect to bus bit - * @param p3 DigitalIn pin to connect to bus bit - * @param p4 DigitalIn pin to connect to bus bit - * @param p5 DigitalIn pin to connect to bus bit - * @param p6 DigitalIn pin to connect to bus bit - * @param p7 DigitalIn pin to connect to bus bit - * @param p8 DigitalIn pin to connect to bus bit - * @param p9 DigitalIn pin to connect to bus bit - * @param p10 DigitalIn pin to connect to bus bit - * @param p11 DigitalIn pin to connect to bus bit - * @param p12 DigitalIn pin to connect to bus bit - * @param p13 DigitalIn pin to connect to bus bit - * @param p14 DigitalIn pin to connect to bus bit - * @param p15 DigitalIn pin to connect to bus bit + * @param DigitalIn pin to connect to bus bit (p5-p30, NC) * * @note * It is only required to specify as many pin variables as is required @@ -61,12 +46,7 @@ class BusIn { PinName p8 = NC, PinName p9 = NC, PinName p10 = NC, PinName p11 = NC, PinName p12 = NC, PinName p13 = NC, PinName p14 = NC, PinName p15 = NC); - - /** Create an BusIn, connected to the specified pins - * - * @param pins An array of pins to connect to bus bit - */ - BusIn(PinName pins[16]); + BusIn(PinName pins[16]); virtual ~BusIn(); @@ -79,7 +59,7 @@ class BusIn { /** Set the input pin mode * - * @param pull PullUp, PullDown, PullNone + * @param mode PullUp, PullDown, PullNone */ void mode(PinMode pull); @@ -105,7 +85,7 @@ class BusIn { protected: DigitalIn* _pin[16]; - /* Mask of bus's NC pins + /** Mask of bus's NC pins * If bit[n] is set to 1 - pin is connected * if bit[n] is cleared - pin is not connected (NC) */ @@ -125,3 +105,4 @@ class BusIn { #endif +/** @}*/ diff --git a/drivers/BusInOut.h b/drivers/BusInOut.h index 116433f9ee9..4abb6aa3ead 100644 --- a/drivers/BusInOut.h +++ b/drivers/BusInOut.h @@ -21,11 +21,11 @@ namespace mbed { /** \addtogroup drivers */ +/** @{*/ /** A digital input output bus, used for setting the state of a collection of pins * - * @note Synchronization level: Thread safe - * @ingroup drivers + * @Note Synchronization level: Thread safe */ class BusInOut { @@ -33,22 +33,7 @@ class BusInOut { /** Create an BusInOut, connected to the specified pins * - * @param p0 DigitalInOut pin to connect to bus bit - * @param p1 DigitalInOut pin to connect to bus bit - * @param p2 DigitalInOut pin to connect to bus bit - * @param p3 DigitalInOut pin to connect to bus bit - * @param p4 DigitalInOut pin to connect to bus bit - * @param p5 DigitalInOut pin to connect to bus bit - * @param p6 DigitalInOut pin to connect to bus bit - * @param p7 DigitalInOut pin to connect to bus bit - * @param p8 DigitalInOut pin to connect to bus bit - * @param p9 DigitalInOut pin to connect to bus bit - * @param p10 DigitalInOut pin to connect to bus bit - * @param p11 DigitalInOut pin to connect to bus bit - * @param p12 DigitalInOut pin to connect to bus bit - * @param p13 DigitalInOut pin to connect to bus bit - * @param p14 DigitalInOut pin to connect to bus bit - * @param p15 DigitalInOut pin to connect to bus bit + * @param p DigitalInOut pin to connect to bus bit p (p5-p30, NC) * * @note * It is only required to specify as many pin variables as is required @@ -59,10 +44,6 @@ class BusInOut { PinName p8 = NC, PinName p9 = NC, PinName p10 = NC, PinName p11 = NC, PinName p12 = NC, PinName p13 = NC, PinName p14 = NC, PinName p15 = NC); - /** Create an BusInOut, connected to the specified pins - * - * @param pins An array of pins to construct a BusInOut from - */ BusInOut(PinName pins[16]); virtual ~BusInOut(); @@ -92,7 +73,7 @@ class BusInOut { /** Set the input pin mode * - * @param pull PullUp, PullDown, PullNone + * @param mode PullUp, PullDown, PullNone */ void mode(PinMode pull); @@ -125,7 +106,7 @@ class BusInOut { virtual void unlock(); DigitalInOut* _pin[16]; - /* Mask of bus's NC pins + /** Mask of bus's NC pins * If bit[n] is set to 1 - pin is connected * if bit[n] is cleared - pin is not connected (NC) */ @@ -142,3 +123,5 @@ class BusInOut { } // namespace mbed #endif + +/** @}*/ diff --git a/drivers/BusOut.h b/drivers/BusOut.h index 495541731dc..c0c576666a0 100644 --- a/drivers/BusOut.h +++ b/drivers/BusOut.h @@ -21,9 +21,9 @@ namespace mbed { /** \addtogroup drivers */ +/** @{*/ /** A digital output bus, used for setting the state of a collection of pins - * @ingroup drivers */ class BusOut { @@ -31,24 +31,9 @@ class BusOut { /** Create an BusOut, connected to the specified pins * - * @param p0 DigitalOut pin to connect to bus bit - * @param p1 DigitalOut pin to connect to bus bit - * @param p2 DigitalOut pin to connect to bus bit - * @param p3 DigitalOut pin to connect to bus bit - * @param p4 DigitalOut pin to connect to bus bit - * @param p5 DigitalOut pin to connect to bus bit - * @param p6 DigitalOut pin to connect to bus bit - * @param p7 DigitalOut pin to connect to bus bit - * @param p8 DigitalOut pin to connect to bus bit - * @param p9 DigitalOut pin to connect to bus bit - * @param p10 DigitalOut pin to connect to bus bit - * @param p11 DigitalOut pin to connect to bus bit - * @param p12 DigitalOut pin to connect to bus bit - * @param p13 DigitalOut pin to connect to bus bit - * @param p14 DigitalOut pin to connect to bus bit - * @param p15 DigitalOut pin to connect to bus bit + * @param p DigitalOut pin to connect to bus bit (p5-p30, NC) * - * @note Synchronization level: Thread safe + * @Note Synchronization level: Thread safe * * @note * It is only required to specify as many pin variables as is required @@ -59,10 +44,6 @@ class BusOut { PinName p8 = NC, PinName p9 = NC, PinName p10 = NC, PinName p11 = NC, PinName p12 = NC, PinName p13 = NC, PinName p14 = NC, PinName p15 = NC); - /** Create an BusOut, connected to the specified pins - * - * @param pins An array of pins to connect to bus the bit - */ BusOut(PinName pins[16]); virtual ~BusOut(); @@ -109,7 +90,7 @@ class BusOut { virtual void unlock(); DigitalOut* _pin[16]; - /* Mask of bus's NC pins + /** Mask of bus's NC pins * If bit[n] is set to 1 - pin is connected * if bit[n] is cleared - pin is not connected (NC) */ @@ -126,3 +107,5 @@ class BusOut { } // namespace mbed #endif + +/** @}*/ diff --git a/drivers/CAN.cpp b/drivers/CAN.cpp index 93d6f6315d7..c4fc17957e8 100644 --- a/drivers/CAN.cpp +++ b/drivers/CAN.cpp @@ -27,7 +27,7 @@ CAN::CAN(PinName rd, PinName td) : _can(), _irq() { // No lock needed in constructor for (int i = 0; i < sizeof _irq / sizeof _irq[0]; i++) { - _irq[i] = callback(donothing); + _irq[i].attach(donothing); } can_init(&_can, rd, td); @@ -104,10 +104,10 @@ int CAN::filter(unsigned int id, unsigned int mask, CANFormat format, int handle void CAN::attach(Callback func, IrqType type) { lock(); if (func) { - _irq[(CanIrqType)type] = func; + _irq[(CanIrqType)type].attach(func); can_irq_set(&_can, (CanIrqType)type, 1); } else { - _irq[(CanIrqType)type] = callback(donothing); + _irq[(CanIrqType)type].attach(donothing); can_irq_set(&_can, (CanIrqType)type, 0); } unlock(); diff --git a/drivers/CAN.h b/drivers/CAN.h index 9a81e9c7874..66e2cdf3ab5 100644 --- a/drivers/CAN.h +++ b/drivers/CAN.h @@ -18,7 +18,7 @@ #include "platform/platform.h" -#if defined (DEVICE_CAN) || defined(DOXYGEN_ONLY) +#if DEVICE_CAN #include "hal/can_api.h" #include "platform/Callback.h" @@ -26,11 +26,11 @@ namespace mbed { /** \addtogroup drivers */ +/** @{*/ /** CANMessage class * - * @note Synchronization level: Thread safe - * @ingroup drivers + * @Note Synchronization level: Thread safe */ class CANMessage : public CAN_Message { @@ -67,7 +67,6 @@ class CANMessage : public CAN_Message { }; /** A can bus client, used for communicating with can devices - * @ingroup drivers */ class CAN { @@ -214,7 +213,7 @@ class CAN { * generated. * * @param func A pointer to a void function, or 0 to set as none - * @param type Which CAN interrupt to attach the member function to (CAN::RxIrq for message received, CAN::TxIrq for transmitted or aborted, CAN::EwIrq for error warning, CAN::DoIrq for data overrun, CAN::WuIrq for wake-up, CAN::EpIrq for error passive, CAN::AlIrq for arbitration lost, CAN::BeIrq for bus error) + * @param event Which CAN interrupt to attach the member function to (CAN::RxIrq for message received, CAN::TxIrq for transmitted or aborted, CAN::EwIrq for error warning, CAN::DoIrq for data overrun, CAN::WuIrq for wake-up, CAN::EpIrq for error passive, CAN::AlIrq for arbitration lost, CAN::BeIrq for bus error) */ void attach(Callback func, IrqType type=RxIrq); @@ -223,18 +222,12 @@ class CAN { * * @param obj pointer to the object to call the member function on * @param method pointer to the member function to be called - * @param type Which CAN interrupt to attach the member function to (CAN::RxIrq for message received, TxIrq for transmitted or aborted, EwIrq for error warning, DoIrq for data overrun, WuIrq for wake-up, EpIrq for error passive, AlIrq for arbitration lost, BeIrq for bus error) - * @deprecated - * The attach function does not support cv-qualifiers. Replaced by - * attach(callback(obj, method), type). + * @param event Which CAN interrupt to attach the member function to (CAN::RxIrq for message received, TxIrq for transmitted or aborted, EwIrq for error warning, DoIrq for data overrun, WuIrq for wake-up, EpIrq for error passive, AlIrq for arbitration lost, BeIrq for bus error) */ template - MBED_DEPRECATED_SINCE("mbed-os-5.1", - "The attach function does not support cv-qualifiers. Replaced by " - "attach(callback(obj, method), type).") void attach(T* obj, void (T::*method)(), IrqType type=RxIrq) { // Underlying call thread safe - attach(callback(obj, method), type); + attach(Callback(obj, method), type); } /** Attach a member function to call whenever a CAN frame received interrupt @@ -242,18 +235,12 @@ class CAN { * * @param obj pointer to the object to call the member function on * @param method pointer to the member function to be called - * @param type Which CAN interrupt to attach the member function to (CAN::RxIrq for message received, TxIrq for transmitted or aborted, EwIrq for error warning, DoIrq for data overrun, WuIrq for wake-up, EpIrq for error passive, AlIrq for arbitration lost, BeIrq for bus error) - * @deprecated - * The attach function does not support cv-qualifiers. Replaced by - * attach(callback(obj, method), type). + * @param event Which CAN interrupt to attach the member function to (CAN::RxIrq for message received, TxIrq for transmitted or aborted, EwIrq for error warning, DoIrq for data overrun, WuIrq for wake-up, EpIrq for error passive, AlIrq for arbitration lost, BeIrq for bus error) */ template - MBED_DEPRECATED_SINCE("mbed-os-5.1", - "The attach function does not support cv-qualifiers. Replaced by " - "attach(callback(obj, method), type).") void attach(T* obj, void (*method)(T*), IrqType type=RxIrq) { // Underlying call thread safe - attach(callback(obj, method), type); + attach(Callback(obj, method), type); } static void _irq_handler(uint32_t id, CanIrqType type); @@ -272,3 +259,4 @@ class CAN { #endif // MBED_CAN_H +/** @}*/ diff --git a/drivers/DigitalIn.h b/drivers/DigitalIn.h index ee3890e8ce2..75b51260ca6 100644 --- a/drivers/DigitalIn.h +++ b/drivers/DigitalIn.h @@ -23,10 +23,11 @@ namespace mbed { /** \addtogroup drivers */ +/** @{*/ /** A digital input, used for reading the state of a pin * - * @note Synchronization level: Interrupt safe + * @Note Synchronization level: Interrupt safe * * Example: * @code @@ -46,7 +47,6 @@ namespace mbed { * } * } * @endcode - * @ingroup drivers */ class DigitalIn { @@ -82,7 +82,7 @@ class DigitalIn { /** Set the input pin mode * - * @param pull PullUp, PullDown, PullNone, OpenDrain + * @param mode PullUp, PullDown, PullNone, OpenDrain */ void mode(PinMode pull) { core_util_critical_section_enter(); @@ -115,3 +115,5 @@ class DigitalIn { } // namespace mbed #endif + +/** @}*/ diff --git a/drivers/DigitalInOut.h b/drivers/DigitalInOut.h index 656d334a5e7..f5b4e7ac3a8 100644 --- a/drivers/DigitalInOut.h +++ b/drivers/DigitalInOut.h @@ -23,11 +23,11 @@ namespace mbed { /** \addtogroup drivers */ +/** @{*/ /** A digital input/output, used for setting or reading a bi-directional pin * - * @note Synchronization level: Interrupt safe - * @ingroup drivers + * @Note Synchronization level: Interrupt safe */ class DigitalInOut { @@ -92,7 +92,7 @@ class DigitalInOut { /** Set the input pin mode * - * @param pull PullUp, PullDown, PullNone, OpenDrain + * @param mode PullUp, PullDown, PullNone, OpenDrain */ void mode(PinMode pull) { core_util_critical_section_enter(); @@ -140,3 +140,5 @@ class DigitalInOut { } // namespace mbed #endif + +/** @}*/ diff --git a/drivers/DigitalOut.h b/drivers/DigitalOut.h index 75a2311d0d1..0a98518c8d7 100644 --- a/drivers/DigitalOut.h +++ b/drivers/DigitalOut.h @@ -22,10 +22,11 @@ namespace mbed { /** \addtogroup drivers */ +/** @{*/ /** A digital output, used for setting the state of a pin * - * @note Synchronization level: Interrupt safe + * @Note Synchronization level: Interrupt safe * * Example: * @code @@ -41,7 +42,6 @@ namespace mbed { * } * } * @endcode - * @ingroup drivers */ class DigitalOut { @@ -126,3 +126,5 @@ class DigitalOut { } // namespace mbed #endif + +/** @}*/ diff --git a/drivers/Ethernet.h b/drivers/Ethernet.h index 8c9bcf4fd73..c9864e8d074 100644 --- a/drivers/Ethernet.h +++ b/drivers/Ethernet.h @@ -18,14 +18,15 @@ #include "platform/platform.h" -#if defined (DEVICE_ETHERNET) || defined(DOXYGEN_ONLY) +#if DEVICE_ETHERNET namespace mbed { /** \addtogroup drivers */ +/** @{*/ /** An ethernet interface, to use with the ethernet pins. * - * @note Synchronization level: Not protected + * @Note Synchronization level: Not protected * * Example: * @code @@ -52,7 +53,6 @@ namespace mbed { * } * } * @endcode - * @ingroup drivers */ class Ethernet { @@ -172,3 +172,5 @@ class Ethernet { #endif #endif + +/** @}*/ diff --git a/drivers/FlashIAP.h b/drivers/FlashIAP.h index e1943c03b30..fcb376dd5f5 100644 --- a/drivers/FlashIAP.h +++ b/drivers/FlashIAP.h @@ -22,7 +22,7 @@ #ifndef MBED_FLASHIAP_H #define MBED_FLASHIAP_H -#if defined (DEVICE_FLASH) || defined(DOXYGEN_ONLY) +#ifdef DEVICE_FLASH #include "flash_api.h" #include "platform/SingletonPtr.h" @@ -31,11 +31,11 @@ namespace mbed { /** \addtogroup drivers */ +/** @{*/ /** Flash IAP driver. It invokes flash HAL functions. * - * @note Synchronization level: Thread safe - * @ingroup drivers + * Note Synchronization level: Thread safe */ class FlashIAP { public: @@ -117,7 +117,7 @@ class FlashIAP { private: - /* Check if address and size are aligned to a sector + /** Check if address and size are aligned to a sector * * @param addr Address of block to check for alignment * @param size Size of block to check for alignment @@ -134,3 +134,5 @@ class FlashIAP { #endif /* DEVICE_FLASH */ #endif /* MBED_FLASHIAP_H */ + +/** @}*/ diff --git a/drivers/I2C.h b/drivers/I2C.h index 4932cd06598..69561dd0399 100644 --- a/drivers/I2C.h +++ b/drivers/I2C.h @@ -18,7 +18,7 @@ #include "platform/platform.h" -#if defined (DEVICE_I2C) || defined(DOXYGEN_ONLY) +#if DEVICE_I2C #include "hal/i2c_api.h" #include "platform/SingletonPtr.h" @@ -32,10 +32,11 @@ namespace mbed { /** \addtogroup drivers */ +/** @{*/ /** An I2C Master, used for communicating with I2C slave devices * - * @note Synchronization level: Thread safe + * @Note Synchronization level: Thread safe * * Example: * @code @@ -51,7 +52,6 @@ namespace mbed { * i2c.read(address, data, 2); * } * @endcode - * @ingroup drivers */ class I2C { @@ -194,3 +194,5 @@ class I2C { #endif #endif + +/** @}*/ diff --git a/drivers/I2CSlave.h b/drivers/I2CSlave.h index 047ef77ea44..a5a9c5865e0 100644 --- a/drivers/I2CSlave.h +++ b/drivers/I2CSlave.h @@ -18,16 +18,17 @@ #include "platform/platform.h" -#if defined (DEVICE_I2CSLAVE) || defined(DOXYGEN_ONLY) +#if DEVICE_I2CSLAVE #include "hal/i2c_api.h" namespace mbed { /** \addtogroup drivers */ +/** @{*/ /** An I2C Slave, used for communicating with an I2C Master device * - * @note Synchronization level: Not protected + * @Note Synchronization level: Not protected * * Example: * @code @@ -60,7 +61,6 @@ namespace mbed { * } * } * @endcode - * @ingroup drivers */ class I2CSlave { @@ -127,7 +127,7 @@ class I2CSlave { /** Write a single byte to an I2C master. * - * @param data the byte to write + * @data the byte to write * * @returns * '1' if an ACK was received, @@ -156,3 +156,5 @@ class I2CSlave { #endif #endif + +/** @}*/ diff --git a/drivers/InterruptIn.h b/drivers/InterruptIn.h index aac567a39f3..17ccf1ab35d 100644 --- a/drivers/InterruptIn.h +++ b/drivers/InterruptIn.h @@ -18,7 +18,7 @@ #include "platform/platform.h" -#if defined (DEVICE_INTERRUPTIN) || defined(DOXYGEN_ONLY) +#if DEVICE_INTERRUPTIN #include "hal/gpio_api.h" #include "hal/gpio_irq_api.h" @@ -28,10 +28,11 @@ namespace mbed { /** \addtogroup drivers */ +/** @{*/ /** A digital interrupt input, used to call a function on a rising or falling edge * - * @note Synchronization level: Interrupt safe + * @Note Synchronization level: Interrupt safe * * Example: * @code @@ -54,7 +55,6 @@ namespace mbed { * } * } * @endcode - * @ingroup drivers */ class InterruptIn { @@ -63,6 +63,7 @@ class InterruptIn { /** Create an InterruptIn connected to the specified pin * * @param pin InterruptIn pin to connect to + * @param name (optional) A string to identify the object */ InterruptIn(PinName pin); virtual ~InterruptIn(); @@ -130,7 +131,7 @@ class InterruptIn { /** Set the input pin mode * - * @param pull PullUp, PullDown, PullNone + * @param mode PullUp, PullDown, PullNone */ void mode(PinMode pull); @@ -159,3 +160,5 @@ class InterruptIn { #endif #endif + +/** @}*/ diff --git a/drivers/InterruptManager.h b/drivers/InterruptManager.h index bab71a893c7..abdbf47542d 100644 --- a/drivers/InterruptManager.h +++ b/drivers/InterruptManager.h @@ -23,10 +23,11 @@ namespace mbed { /** \addtogroup drivers */ +/** @{*/ /** Use this singleton if you need to chain interrupt handlers. * - * @note Synchronization level: Thread safe + * @Note Synchronization level: Thread safe * * Example (for LPC1768): * @code @@ -51,7 +52,6 @@ namespace mbed { * InterruptManager::get()->add_handler(handler, TIMER3_IRQn); * } * @endcode - * @ingroup drivers */ class InterruptManager { public: @@ -170,3 +170,6 @@ class InterruptManager { } // namespace mbed #endif + + +/** @}*/ diff --git a/drivers/LowPowerTicker.h b/drivers/LowPowerTicker.h index 8a076141d26..367f7a665a5 100644 --- a/drivers/LowPowerTicker.h +++ b/drivers/LowPowerTicker.h @@ -19,17 +19,17 @@ #include "platform/platform.h" #include "drivers/Ticker.h" -#if defined (DEVICE_LOWPOWERTIMER) || defined(DOXYGEN_ONLY) +#if DEVICE_LOWPOWERTIMER #include "hal/lp_ticker_api.h" namespace mbed { /** \addtogroup drivers */ +/** @{*/ /** Low Power Ticker * - * @note Synchronization level: Interrupt safe - * @ingroup drivers + * @Note Synchronization level: Interrupt safe */ class LowPowerTicker : public Ticker { @@ -46,3 +46,5 @@ class LowPowerTicker : public Ticker { #endif #endif + +/** @}*/ diff --git a/drivers/LowPowerTimeout.h b/drivers/LowPowerTimeout.h index c246ac1bc1d..9139ccda6c7 100644 --- a/drivers/LowPowerTimeout.h +++ b/drivers/LowPowerTimeout.h @@ -18,18 +18,18 @@ #include "platform/platform.h" -#if defined (DEVICE_LOWPOWERTIMER) || defined(DOXYGEN_ONLY) +#if DEVICE_LOWPOWERTIMER #include "hal/lp_ticker_api.h" #include "drivers/LowPowerTicker.h" namespace mbed { /** \addtogroup drivers */ +/** @{*/ /** Low Power Timout * - * @note Synchronization level: Interrupt safe - * @ingroup drivers + * @Note Synchronization level: Interrupt safe */ class LowPowerTimeout : public LowPowerTicker { @@ -44,3 +44,5 @@ class LowPowerTimeout : public LowPowerTicker { #endif #endif + +/** @}*/ diff --git a/drivers/LowPowerTimer.h b/drivers/LowPowerTimer.h index 4f1e15e2fbc..e110c9b57f3 100644 --- a/drivers/LowPowerTimer.h +++ b/drivers/LowPowerTimer.h @@ -19,17 +19,17 @@ #include "platform/platform.h" #include "drivers/Timer.h" -#if defined (DEVICE_LOWPOWERTIMER) || defined(DOXYGEN_ONLY) +#if DEVICE_LOWPOWERTIMER #include "hal/lp_ticker_api.h" namespace mbed { /** \addtogroup drivers */ +/** @{*/ /** Low power timer * - * @note Synchronization level: Interrupt safe - * @ingroup drivers + * @Note Synchronization level: Interrupt safe */ class LowPowerTimer : public Timer { @@ -44,3 +44,5 @@ class LowPowerTimer : public Timer { #endif #endif + +/** @}*/ diff --git a/drivers/PortIn.h b/drivers/PortIn.h index 2796916fe25..a7b59831dab 100644 --- a/drivers/PortIn.h +++ b/drivers/PortIn.h @@ -18,17 +18,18 @@ #include "platform/platform.h" -#if defined (DEVICE_PORTIN) || defined(DOXYGEN_ONLY) +#if DEVICE_PORTIN #include "hal/port_api.h" #include "platform/mbed_critical.h" namespace mbed { /** \addtogroup drivers */ +/** @{*/ /** A multiple pin digital input * - * @note Synchronization level: Interrupt safe + * @Note Synchronization level: Interrupt safe * * Example: * @code @@ -50,7 +51,6 @@ namespace mbed { * } * } * @endcode - * @ingroup drivers */ class PortIn { public: @@ -100,3 +100,5 @@ class PortIn { #endif #endif + +/** @}*/ diff --git a/drivers/PortInOut.h b/drivers/PortInOut.h index 5502c60b7e7..3000c8d68e4 100644 --- a/drivers/PortInOut.h +++ b/drivers/PortInOut.h @@ -18,18 +18,18 @@ #include "platform/platform.h" -#if defined (DEVICE_PORTINOUT) || defined(DOXYGEN_ONLY) +#if DEVICE_PORTINOUT #include "hal/port_api.h" #include "platform/mbed_critical.h" namespace mbed { /** \addtogroup drivers */ +/** @{*/ /** A multiple pin digital in/out used to set/read multiple bi-directional pins * - * @note Synchronization level: Interrupt safe - * @ingroup drivers + * @Note Synchronization level: Interrupt safe */ class PortInOut { public: @@ -115,3 +115,5 @@ class PortInOut { #endif #endif + +/** @}*/ diff --git a/drivers/PortOut.h b/drivers/PortOut.h index 7dbc2d130bd..3df721cfa86 100644 --- a/drivers/PortOut.h +++ b/drivers/PortOut.h @@ -18,16 +18,17 @@ #include "platform/platform.h" -#if defined (DEVICE_PORTOUT) || defined(DOXYGEN_ONLY) +#if DEVICE_PORTOUT #include "hal/port_api.h" #include "platform/mbed_critical.h" namespace mbed { /** \addtogroup drivers */ +/** @{*/ /** A multiple pin digital out * - * @note Synchronization level: Interrupt safe + * @Note Synchronization level: Interrupt safe * * Example: * @code @@ -49,7 +50,6 @@ namespace mbed { * } * } * @endcode - * @ingroup drivers */ class PortOut { public: @@ -109,3 +109,5 @@ class PortOut { #endif #endif + +/** @}*/ diff --git a/drivers/PwmOut.h b/drivers/PwmOut.h index c779701b835..0b4bd9ec769 100644 --- a/drivers/PwmOut.h +++ b/drivers/PwmOut.h @@ -18,16 +18,17 @@ #include "platform/platform.h" -#if defined (DEVICE_PWMOUT) || defined(DOXYGEN_ONLY) +#if DEVICE_PWMOUT #include "hal/pwmout_api.h" #include "platform/mbed_critical.h" namespace mbed { /** \addtogroup drivers */ +/** @{*/ /** A pulse-width modulation digital output * - * @note Synchronization level: Interrupt safe + * @Note Synchronization level: Interrupt safe * * Example * @code @@ -46,7 +47,13 @@ namespace mbed { * } * } * @endcode - * @ingroup drivers + * + * @note + * On the LPC1768 and LPC2368, the PWMs all share the same + * period - if you change the period for one, you change it for all. + * Although routines that change the period maintain the duty cycle + * for its PWM, all other PWMs will require their duty cycle to be + * refreshed. */ class PwmOut { @@ -83,7 +90,7 @@ class PwmOut { * 0.0f (representing on 0%) and 1.0f (representing on 100%). * * @note - * This value may not match exactly the value set by a previous write(). + * This value may not match exactly the value set by a previous . */ float read() { core_util_critical_section_enter(); @@ -94,7 +101,6 @@ class PwmOut { /** Set the PWM period, specified in seconds (float), keeping the duty cycle the same. * - * @param seconds Change the period of a PWM signal in seconds (float) without modifying the duty cycle * @note * The resolution is currently in microseconds; periods smaller than this * will be set to zero. @@ -106,7 +112,6 @@ class PwmOut { } /** Set the PWM period, specified in milli-seconds (int), keeping the duty cycle the same. - * @param ms Change the period of a PWM signal in milli-seconds without modifying the duty cycle */ void period_ms(int ms) { core_util_critical_section_enter(); @@ -115,7 +120,6 @@ class PwmOut { } /** Set the PWM period, specified in micro-seconds (int), keeping the duty cycle the same. - * @param us Change the period of a PWM signal in micro-seconds without modifying the duty cycle */ void period_us(int us) { core_util_critical_section_enter(); @@ -124,7 +128,6 @@ class PwmOut { } /** Set the PWM pulsewidth, specified in seconds (float), keeping the period the same. - * @param seconds Change the pulse width of a PWM signal specified in seconds (float) */ void pulsewidth(float seconds) { core_util_critical_section_enter(); @@ -133,7 +136,6 @@ class PwmOut { } /** Set the PWM pulsewidth, specified in milli-seconds (int), keeping the period the same. - * @param ms Change the pulse width of a PWM signal specified in milli-seconds */ void pulsewidth_ms(int ms) { core_util_critical_section_enter(); @@ -142,7 +144,6 @@ class PwmOut { } /** Set the PWM pulsewidth, specified in micro-seconds (int), keeping the period the same. - * @param us Change the pulse width of a PWM signal specified in micro-seconds */ void pulsewidth_us(int us) { core_util_critical_section_enter(); @@ -158,8 +159,6 @@ class PwmOut { return *this; } - /** A operator shorthand for write() - */ PwmOut& operator= (PwmOut& rhs) { // Underlying call is thread safe write(rhs.read()); @@ -182,3 +181,5 @@ class PwmOut { #endif #endif + +/** @}*/ diff --git a/drivers/RawSerial.h b/drivers/RawSerial.h index 2026e111702..2421869b35f 100644 --- a/drivers/RawSerial.h +++ b/drivers/RawSerial.h @@ -18,13 +18,14 @@ #include "platform/platform.h" -#if defined (DEVICE_SERIAL) || defined(DOXYGEN_ONLY) +#if DEVICE_SERIAL #include "drivers/SerialBase.h" #include "hal/serial_api.h" namespace mbed { /** \addtogroup drivers */ +/** @{*/ /** A serial port (UART) for communication with other serial devices * This is a variation of the Serial class that doesn't use streams, @@ -33,7 +34,7 @@ namespace mbed { * Can be used for Full Duplex communication, or Simplex by specifying * one pin as NC (Not Connected) * - * @note Synchronization level: Not protected + * @Note Synchronization level: Not protected * * Example: * @code @@ -47,7 +48,6 @@ namespace mbed { * pc.putc('A'); * } * @endcode - * @ingroup drivers */ class RawSerial: public SerialBase { @@ -89,11 +89,11 @@ class RawSerial: public SerialBase { protected: - /* Acquire exclusive access to this serial port + /** Acquire exclusive access to this serial port */ virtual void lock(void); - /* Release exclusive access to this serial port + /** Release exclusive access to this serial port */ virtual void unlock(void); }; @@ -103,3 +103,5 @@ class RawSerial: public SerialBase { #endif #endif + +/** @}*/ diff --git a/drivers/SPI.h b/drivers/SPI.h index 6eede8a7979..866531e68bd 100644 --- a/drivers/SPI.h +++ b/drivers/SPI.h @@ -18,7 +18,7 @@ #include "platform/platform.h" -#if defined (DEVICE_SPI) || defined(DOXYGEN_ONLY) +#if DEVICE_SPI #include "platform/PlatformMutex.h" #include "hal/spi_api.h" @@ -34,15 +34,16 @@ namespace mbed { /** \addtogroup drivers */ +/** @{*/ /** A SPI Master, used for communicating with SPI slave devices * * The default format is set to 8-bits, mode 0, and a clock frequency of 1MHz * * Most SPI devices will also require Chip Select and Reset signals. These - * can be controlled using DigitalOut pins + * can be controlled using pins * - * @note Synchronization level: Thread safe + * @Note Synchronization level: Thread safe * * Example: * @code @@ -70,7 +71,6 @@ namespace mbed { * * } * @endcode - * @ingroup drivers */ class SPI { @@ -261,3 +261,5 @@ class SPI { #endif #endif + +/** @}*/ diff --git a/drivers/SPISlave.h b/drivers/SPISlave.h index 29a90466950..a7d07ea8119 100644 --- a/drivers/SPISlave.h +++ b/drivers/SPISlave.h @@ -18,18 +18,19 @@ #include "platform/platform.h" -#if defined (DEVICE_SPISLAVE) || defined(DOXYGEN_ONLY) +#if DEVICE_SPISLAVE #include "hal/spi_api.h" namespace mbed { /** \addtogroup drivers */ +/** @{*/ /** A SPI slave, used for communicating with a SPI Master device * * The default format is set to 8-bits, mode 0, and a clock frequency of 1MHz * - * @note Synchronization level: Not protected + * @Note Synchronization level: Not protected * * Example: * @code @@ -50,7 +51,6 @@ namespace mbed { * } * } * @endcode - * @ingroup drivers */ class SPISlave { @@ -124,3 +124,5 @@ class SPISlave { #endif #endif + +/** @}*/ diff --git a/drivers/Serial.h b/drivers/Serial.h index 7a9a2875fe1..c4ce0f30b0d 100644 --- a/drivers/Serial.h +++ b/drivers/Serial.h @@ -18,7 +18,7 @@ #include "platform/platform.h" -#if defined (DEVICE_SERIAL) || defined(DOXYGEN_ONLY) +#if DEVICE_SERIAL #include "Stream.h" #include "SerialBase.h" @@ -27,13 +27,14 @@ namespace mbed { /** \addtogroup drivers */ +/** @{*/ /** A serial port (UART) for communication with other serial devices * * Can be used for Full Duplex communication, or Simplex by specifying * one pin as NC (Not Connected) * - * @note Synchronization level: Thread safe + * @Note Synchronization level: Thread safe * * Example: * @code @@ -47,7 +48,6 @@ namespace mbed { * pc.printf("Hello World\n"); * } * @endcode - * @ingroup drivers */ class Serial : public SerialBase, public Stream { @@ -95,3 +95,5 @@ class Serial : public SerialBase, public Stream { #endif #endif + +/** @}*/ diff --git a/drivers/SerialBase.h b/drivers/SerialBase.h index 83ef34c661c..d13c1e61383 100644 --- a/drivers/SerialBase.h +++ b/drivers/SerialBase.h @@ -18,7 +18,7 @@ #include "platform/platform.h" -#if defined (DEVICE_SERIAL) || defined(DOXYGEN_ONLY) +#if DEVICE_SERIAL #include "Stream.h" #include "Callback.h" @@ -32,12 +32,12 @@ namespace mbed { /** \addtogroup drivers */ +/** @{*/ /** A base class for serial port implementations * Can't be instantiated directly (use Serial or RawSerial) * - * @note Synchronization level: Set by subclass - * @ingroup drivers + * @Note Synchronization level: Set by subclass */ class SerialBase { @@ -74,7 +74,7 @@ class SerialBase { * * @param bits The number of bits in a word (5-8; default = 8) * @param parity The parity used (SerialBase::None, SerialBase::Odd, SerialBase::Even, SerialBase::Forced1, SerialBase::Forced0; default = SerialBase::None) - * @param stop_bits The number of stop bits (1 or 2; default = 1) + * @param stop The number of stop bits (1 or 2; default = 1) */ void format(int bits=8, Parity parity=SerialBase::None, int stop_bits=1); @@ -258,3 +258,5 @@ class SerialBase { #endif #endif + +/** @}*/ diff --git a/drivers/Ticker.h b/drivers/Ticker.h index 5434ef7f8f2..fe79c3a9f9f 100644 --- a/drivers/Ticker.h +++ b/drivers/Ticker.h @@ -22,12 +22,13 @@ namespace mbed { /** \addtogroup drivers */ +/** @{*/ /** A Ticker is used to call a function at a recurring interval * * You can use as many seperate Ticker objects as you require. * - * @note Synchronization level: Interrupt safe + * @Note Synchronization level: Interrupt safe * * Example: * @code @@ -57,7 +58,6 @@ namespace mbed { * } * } * @endcode - * @ingroup drivers */ class Ticker : public TimerEvent { @@ -97,7 +97,7 @@ class Ticker : public TimerEvent { /** Attach a function to be called by the Ticker, specifiying the interval in micro-seconds * - * @param func pointer to the function to be called + * @param fptr pointer to the function to be called * @param t the time between calls in micro-seconds */ void attach_us(Callback func, timestamp_t t) { @@ -107,8 +107,8 @@ class Ticker : public TimerEvent { /** Attach a member function to be called by the Ticker, specifiying the interval in micro-seconds * - * @param obj pointer to the object to call the member function on - * @param method pointer to the member function to be called + * @param tptr pointer to the object to call the member function on + * @param mptr pointer to the member function to be called * @param t the time between calls in micro-seconds * @deprecated * The attach_us function does not support cv-qualifiers. Replaced by @@ -135,10 +135,12 @@ class Ticker : public TimerEvent { virtual void handler(); protected: - timestamp_t _delay; /* Time delay (in microseconds) for re-setting the multi-shot callback. */ - Callback _function; /* Callback. */ + timestamp_t _delay; /**< Time delay (in microseconds) for re-setting the multi-shot callback. */ + Callback _function; /**< Callback. */ }; } // namespace mbed #endif + +/** @}*/ diff --git a/drivers/Timeout.h b/drivers/Timeout.h index 54240bf783f..ad89130aa2f 100644 --- a/drivers/Timeout.h +++ b/drivers/Timeout.h @@ -20,12 +20,13 @@ namespace mbed { /** \addtogroup drivers */ +/** @{*/ /** A Timeout is used to call a function at a point in the future * * You can use as many seperate Timeout objects as you require. * - * @note Synchronization level: Interrupt safe + * @Note Synchronization level: Interrupt safe * * Example: * @code @@ -50,7 +51,6 @@ namespace mbed { * } * } * @endcode - * @ingroup drivers */ class Timeout : public Ticker { @@ -61,3 +61,5 @@ class Timeout : public Ticker { } // namespace mbed #endif + +/** @}*/ diff --git a/drivers/Timer.h b/drivers/Timer.h index 51ed940966a..76a8415aa5a 100644 --- a/drivers/Timer.h +++ b/drivers/Timer.h @@ -21,10 +21,11 @@ namespace mbed { /** \addtogroup drivers */ +/** @{*/ /** A general purpose timer * - * @note Synchronization level: Interrupt safe + * @Note Synchronization level: Interrupt safe * * Example: * @code @@ -44,7 +45,6 @@ namespace mbed { * printf("Toggle the led takes %d us", end - begin); * } * @endcode - * @ingroup drivers */ class Timer { @@ -93,3 +93,5 @@ class Timer { } // namespace mbed #endif + +/** @}*/ diff --git a/drivers/TimerEvent.h b/drivers/TimerEvent.h index b186c25b930..f217ca339f6 100644 --- a/drivers/TimerEvent.h +++ b/drivers/TimerEvent.h @@ -21,11 +21,11 @@ namespace mbed { /** \addtogroup drivers */ +/** @{*/ /** Base abstraction for timer interrupts * - * @note Synchronization level: Interrupt safe - * @ingroup drivers + * @Note Synchronization level: Interrupt safe */ class TimerEvent { public: @@ -58,3 +58,5 @@ class TimerEvent { } // namespace mbed #endif + +/** @}*/ diff --git a/events/Event.h b/events/Event.h index 9e25a942799..7c4132af906 100644 --- a/events/Event.h +++ b/events/Event.h @@ -21,11 +21,11 @@ namespace events { /** \addtogroup events */ +/** @{*/ /** Event * * Representation of an event for fine-grain dispatch control - * @ingroup events */ template class Event; @@ -33,7 +33,6 @@ class Event; /** Event * * Representation of an event for fine-grain dispatch control - * @ingroup events */ template <> class Event { @@ -430,7 +429,6 @@ class Event { /** Event * * Representation of an event for fine-grain dispatch control - * @ingroup events */ template class Event { @@ -827,7 +825,6 @@ class Event { /** Event * * Representation of an event for fine-grain dispatch control - * @ingroup events */ template class Event { @@ -1224,7 +1221,6 @@ class Event { /** Event * * Representation of an event for fine-grain dispatch control - * @ingroup events */ template class Event { @@ -1621,7 +1617,6 @@ class Event { /** Event * * Representation of an event for fine-grain dispatch control - * @ingroup events */ template class Event { @@ -2018,7 +2013,6 @@ class Event { /** Event * * Representation of an event for fine-grain dispatch control - * @ingroup events */ template class Event { @@ -2413,8 +2407,6 @@ class Event { }; -/** \addtogroup events */ -/** @{ */ // Convenience functions declared here to avoid cyclic // dependency between Event and EventQueue diff --git a/events/EventQueue.h b/events/EventQueue.h index 9695c1c827a..f87872fd5ff 100644 --- a/events/EventQueue.h +++ b/events/EventQueue.h @@ -24,6 +24,7 @@ namespace events { /** \addtogroup events */ +/** @{*/ /** EVENTS_EVENT_SIZE * Minimum size of an event @@ -45,7 +46,6 @@ class Event; /** EventQueue * * Flexible event queue for dispatching events - * @ingroup events */ class EventQueue { public: @@ -2698,3 +2698,4 @@ class EventQueue { #endif +/** @}*/ diff --git a/events/equeue/equeue_mbed.cpp b/events/equeue/equeue_mbed.cpp index bb30c64f3bd..5c72b38dea3 100644 --- a/events/equeue/equeue_mbed.cpp +++ b/events/equeue/equeue_mbed.cpp @@ -42,12 +42,13 @@ static void equeue_tick_init() { "The equeue_timer buffer must fit the class Timer"); MBED_STATIC_ASSERT(sizeof(equeue_ticker) >= sizeof(Ticker), "The equeue_ticker buffer must fit the class Ticker"); - Timer *timer = new (equeue_timer) Timer; - Ticker *ticker = new (equeue_ticker) Ticker; + new (equeue_timer) Timer; + new (equeue_ticker) Ticker; equeue_minutes = 0; - timer->start(); - ticker->attach_us(equeue_tick_update, 1000 << 16); + reinterpret_cast(equeue_timer)->start(); + reinterpret_cast(equeue_ticker) + ->attach_us(equeue_tick_update, 1000 << 16); equeue_tick_inited = true; } @@ -130,9 +131,7 @@ static void equeue_sema_timeout(equeue_sema_t *s) { bool equeue_sema_wait(equeue_sema_t *s, int ms) { int signal = 0; Timeout timeout; - if (ms == 0) { - return false; - } else if (ms > 0) { + if (ms > 0) { timeout.attach_us(callback(equeue_sema_timeout, s), ms*1000); } diff --git a/events/equeue/equeue_platform.h b/events/equeue/equeue_platform.h index 8b7c4f735d5..ef2a8e38631 100644 --- a/events/equeue/equeue_platform.h +++ b/events/equeue/equeue_platform.h @@ -129,8 +129,7 @@ typedef volatile int equeue_sema_t; // The equeue_sema_wait waits for a semaphore to be signalled or returns // immediately if equeue_sema_signal had been called since the last // equeue_sema_wait. The equeue_sema_wait returns true if it detected that -// equeue_sema_signal had been called. If ms is negative, equeue_sema_wait -// will wait for a signal indefinitely. +// equeue_sema_signal had been called. int equeue_sema_create(equeue_sema_t *sema); void equeue_sema_destroy(equeue_sema_t *sema); void equeue_sema_signal(equeue_sema_t *sema); diff --git a/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/btle/btle.cpp b/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/btle/btle.cpp index 811e7152544..1274151d0d4 100644 --- a/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/btle/btle.cpp +++ b/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/btle/btle.cpp @@ -24,6 +24,7 @@ #include "ble_conn_params.h" #include "btle_gap.h" +#include "btle_advertising.h" #include "custom/custom_helper.h" #include "ble/GapEvents.h" @@ -164,10 +165,6 @@ error_t btle_init(void) return ERROR_INVALID_PARAM; } - // Peer Manger must been initialised prior any other call to its API (this file and btle_security_pm.cpp) - pm_init(); - -#if (NRF_SD_BLE_API_VERSION <= 2) ble_gap_addr_t addr; if (sd_ble_gap_address_get(&addr) != NRF_SUCCESS) { return ERROR_INVALID_PARAM; @@ -175,11 +172,6 @@ error_t btle_init(void) if (sd_ble_gap_address_set(BLE_GAP_ADDR_CYCLE_MODE_NONE, &addr) != NRF_SUCCESS) { return ERROR_INVALID_PARAM; } -#else - ble_gap_privacy_params_t privacy_params = {0}; - privacy_params.privacy_mode = BLE_GAP_PRIVACY_MODE_OFF; - pm_privacy_set(&privacy_params); -#endif ASSERT_STATUS( softdevice_ble_evt_handler_set(btle_handler)); ASSERT_STATUS( softdevice_sys_evt_handler_set(sys_evt_dispatch)); @@ -227,25 +219,12 @@ static void btle_handler(ble_evt_t *p_ble_evt) gap.setConnectionHandle(handle); const Gap::ConnectionParams_t *params = reinterpret_cast(&(p_ble_evt->evt.gap_evt.params.connected.conn_params)); const ble_gap_addr_t *peer = &p_ble_evt->evt.gap_evt.params.connected.peer_addr; -#if (NRF_SD_BLE_API_VERSION <= 2) const ble_gap_addr_t *own = &p_ble_evt->evt.gap_evt.params.connected.own_addr; - gap.processConnectionEvent(handle, - role, - static_cast(peer->addr_type), peer->addr, - static_cast(own->addr_type), own->addr, - params); -#else - Gap::AddressType_t addr_type; - Gap::Address_t own_address; - gap.getAddress(&addr_type, own_address); - - gap.processConnectionEvent(handle, - role, - static_cast(peer->addr_type), peer->addr, - addr_type, own_address, - params); -#endif + role, + static_cast(peer->addr_type), peer->addr, + static_cast(own->addr_type), own->addr, + params); break; } diff --git a/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/btle/btle.h b/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/btle/btle.h index 021dd50513b..2e6fe3d9f7d 100644 --- a/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/btle/btle.h +++ b/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/btle/btle.h @@ -24,7 +24,7 @@ extern "C" { #include "common/common.h" #include "ble_srv_common.h" -#include "headers/nrf_ble.h" +#include "nrf_ble.h" error_t btle_init(void); diff --git a/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/btle/btle_advertising.cpp b/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/btle/btle_advertising.cpp new file mode 100644 index 00000000000..cdaf6a4a49c --- /dev/null +++ b/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/btle/btle_advertising.cpp @@ -0,0 +1,46 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * 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. + */ +#include "common/common.h" + +#include "ble_advdata.h" +#include "btle.h" + +/**************************************************************************/ +/*! + @brief Starts the advertising process + + @returns +*/ +/**************************************************************************/ +error_t btle_advertising_start(void) +{ + ble_gap_adv_params_t adv_para = {0}; + + /* Set the default advertising parameters */ + adv_para.type = BLE_GAP_ADV_TYPE_ADV_IND; + adv_para.p_peer_addr = NULL; /* Undirected advertising */ + adv_para.fp = BLE_GAP_ADV_FP_ANY; + adv_para.p_whitelist = NULL; + adv_para.interval = (CFG_GAP_ADV_INTERVAL_MS * 8) / 5; /* Advertising + * interval in + * units of 0.625 + * ms */ + adv_para.timeout = CFG_GAP_ADV_TIMEOUT_S; + + ASSERT_STATUS( sd_ble_gap_adv_start(&adv_para)); + + return ERROR_NONE; +} diff --git a/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/btle/btle_advertising.h b/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/btle/btle_advertising.h new file mode 100644 index 00000000000..a215153ab5e --- /dev/null +++ b/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/btle/btle_advertising.h @@ -0,0 +1,24 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * 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. + */ + +#ifndef _BTLE_ADVERTISING_H_ +#define _BTLE_ADVERTISING_H_ + +#include "common/common.h" + +error_t btle_advertising_start(void); + +#endif // ifndef _BTLE_ADVERTISING_H_ diff --git a/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/btle/btle_discovery.cpp b/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/btle/btle_discovery.cpp index 99059f6623a..0b6b1d6a9cc 100644 --- a/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/btle/btle_discovery.cpp +++ b/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/btle/btle_discovery.cpp @@ -57,7 +57,7 @@ void bleGattcEventHandler(const ble_evt_t *p_ble_evt) case BLE_GATTC_EVT_CHAR_VAL_BY_UUID_READ_RSP: if (sdSingleton.isActive()) { - sdSingleton.processDiscoverUUIDResponse(&p_ble_evt->evt.gattc_evt); + sdSingleton.processDiscoverUUIDResponse(&p_ble_evt->evt.gattc_evt.params.char_val_by_uuid_read_rsp); } break; diff --git a/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/btle/btle_gap.cpp b/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/btle/btle_gap.cpp index 8bc8600d7b1..5dbc372135f 100644 --- a/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/btle/btle_gap.cpp +++ b/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/btle/btle_gap.cpp @@ -15,7 +15,7 @@ */ #include "common/common.h" -#include "headers/nrf_ble_gap.h" +#include "nrf_ble_gap.h" #include "ble_conn_params.h" static inline uint32_t msec_to_1_25msec(uint32_t interval_ms) ATTR_ALWAYS_INLINE ATTR_CONST; diff --git a/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/btle/btle_security.h b/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/btle/btle_security.h index 3197e838818..4f863975ab3 100644 --- a/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/btle/btle_security.h +++ b/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/btle/btle_security.h @@ -84,7 +84,6 @@ ble_error_t btle_setLinkSecurity(Gap::Handle_t connectionHandle, SecurityManager */ ble_error_t btle_purgeAllBondingState(void); -#if (NRF_SD_BLE_API_VERSION <= 2) /** * Query the SoftDevice bond table to extract a whitelist containing the BLE * addresses and IRKs of bonded devices. @@ -99,7 +98,6 @@ ble_error_t btle_purgeAllBondingState(void); * @return BLE_ERROR_NONE Or appropriate error code indicating reason for failure. */ ble_error_t btle_createWhitelistFromBondTable(ble_gap_whitelist_t *p_whitelist); -#endif /** * Function to test whether a BLE address is generated using an IRK. diff --git a/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/btle/btle_security_pm.cpp b/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/btle/btle_security_pm.cpp index 8b0c16175e1..e29002d07ab 100644 --- a/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/btle/btle_security_pm.cpp +++ b/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/btle/btle_security_pm.cpp @@ -14,7 +14,7 @@ * limitations under the License. */ -#if defined(S130) || defined(S132) || defined(S140) +#if defined(S130) || defined(S132) #include "btle.h" #include "nRF5xn.h" @@ -94,6 +94,10 @@ btle_initializeSecurity(bool enableBonding, } } + if (pm_init() != NRF_SUCCESS) { + return BLE_ERROR_UNSPECIFIED; + } + // update default security parameters with function call parameters securityParameters.bond = enableBonding; securityParameters.mitm = requireMITM; @@ -389,7 +393,6 @@ void pm_handler(pm_evt_t const *p_event) } } -#if (NRF_SD_BLE_API_VERSION <= 2) ble_error_t btle_createWhitelistFromBondTable(ble_gap_whitelist_t *p_whitelist) { @@ -405,7 +408,7 @@ btle_createWhitelistFromBondTable(ble_gap_whitelist_t *p_whitelist) return BLE_ERROR_INVALID_STATE; } } -#endif + bool btle_matchAddressAndIrk(ble_gap_addr_t const * p_addr, ble_gap_irk_t const * p_irk) diff --git a/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/btle/custom/custom_helper.h b/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/btle/custom/custom_helper.h index af47fb98527..22a32907c1b 100644 --- a/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/btle/custom/custom_helper.h +++ b/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/btle/custom/custom_helper.h @@ -18,7 +18,7 @@ #define _CUSTOM_HELPER_H_ #include "common/common.h" -#include "headers/nrf_ble.h" +#include "nrf_ble.h" #include "ble/UUID.h" #include "ble/GattCharacteristic.h" diff --git a/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/nRF5xCharacteristicDescriptorDiscoverer.cpp b/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/nRF5xCharacteristicDescriptorDiscoverer.cpp index 0dee44efbfc..a06de22ffd1 100644 --- a/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/nRF5xCharacteristicDescriptorDiscoverer.cpp +++ b/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/nRF5xCharacteristicDescriptorDiscoverer.cpp @@ -14,7 +14,7 @@ * limitations under the License. */ #include "nRF5xCharacteristicDescriptorDiscoverer.h" -#include "headers/nrf_ble_err.h" +#include "nrf_ble_err.h" #include "ble/DiscoveredCharacteristicDescriptor.h" nRF5xCharacteristicDescriptorDiscoverer::nRF5xCharacteristicDescriptorDiscoverer() : @@ -136,7 +136,6 @@ void nRF5xCharacteristicDescriptorDiscoverer::processAttributeInformation( return; } -#if (NRF_SD_BLE_API_VERSION <= 2) // for all UUIDS found, process the discovery for (uint16_t i = 0; i < infos.count; ++i) { bool use_16bits_uuids = infos.format == BLE_GATTC_ATTR_INFO_FORMAT_16BIT; @@ -147,27 +146,6 @@ void nRF5xCharacteristicDescriptorDiscoverer::processAttributeInformation( // prepare the next round of descriptors discovery uint16_t startHandle = infos.attr_info[infos.count - 1].handle + 1; -#else - uint16_t startHandle; - // for all UUIDS found, process the discovery - if (infos.format == BLE_GATTC_ATTR_INFO_FORMAT_16BIT) { - for (uint16_t i = 0; i < infos.count; ++i) { - UUID uuid = UUID(infos.info.attr_info16[i].uuid.uuid); - discovery->process(infos.info.attr_info16[i].handle, uuid); - } - - // prepare the next round of descriptors discovery - startHandle = infos.info.attr_info16[infos.count - 1].handle + 1; - } else { - for (uint16_t i = 0; i < infos.count; ++i) { - UUID uuid = UUID(infos.info.attr_info128[i].uuid.uuid128, UUID::LSB); - discovery->process(infos.info.attr_info128[i].handle, uuid); - } - - // prepare the next round of descriptors discovery - startHandle = infos.info.attr_info128[infos.count - 1].handle + 1; - } -#endif uint16_t endHandle = discovery->getCharacteristic().getLastHandle(); if(startHandle > endHandle) { diff --git a/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/nRF5xCharacteristicDescriptorDiscoverer.h b/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/nRF5xCharacteristicDescriptorDiscoverer.h index 753e368f0fe..285a4a12885 100644 --- a/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/nRF5xCharacteristicDescriptorDiscoverer.h +++ b/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/nRF5xCharacteristicDescriptorDiscoverer.h @@ -21,7 +21,7 @@ #include "ble/DiscoveredCharacteristic.h" #include "ble/CharacteristicDescriptorDiscovery.h" #include "ble/GattClient.h" -#include "headers/nrf_ble_gattc.h" +#include "nrf_ble_gattc.h" /** * @brief Manage the discovery of Characteristic descriptors diff --git a/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/nRF5xDiscoveredCharacteristic.cpp b/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/nRF5xDiscoveredCharacteristic.cpp index f7d6996f4d8..a228a624d2b 100644 --- a/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/nRF5xDiscoveredCharacteristic.cpp +++ b/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/nRF5xDiscoveredCharacteristic.cpp @@ -16,7 +16,7 @@ #include "nRF5xDiscoveredCharacteristic.h" #include "nRF5xGattClient.h" -#include "headers/nrf_ble_gatt.h" +#include "nrf_ble_gatt.h" void nRF5xDiscoveredCharacteristic::setup(nRF5xGattClient *gattcIn, diff --git a/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/nRF5xDiscoveredCharacteristic.h b/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/nRF5xDiscoveredCharacteristic.h index 87ebbbf7679..7b4bfc82c7c 100644 --- a/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/nRF5xDiscoveredCharacteristic.h +++ b/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/nRF5xDiscoveredCharacteristic.h @@ -18,7 +18,7 @@ #define __NRF_DISCOVERED_CHARACTERISTIC_H__ #include "ble/DiscoveredCharacteristic.h" -#include "headers/nrf_ble_gatt.h" +#include "nrf_ble_gatt.h" class nRF5xGattClient; /* forward declaration */ diff --git a/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/nRF5xGap.cpp b/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/nRF5xGap.cpp index 56c9218feeb..f874bfefe52 100644 --- a/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/nRF5xGap.cpp +++ b/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/nRF5xGap.cpp @@ -24,13 +24,7 @@ #include "common/common.h" #include "ble_advdata.h" -#include "headers/nrf_ble_hci.h" - -#if (NRF_SD_BLE_API_VERSION >= 3) - #include "peer_manager.h" - #include "peer_data_storage.h" -#endif - +#include "nrf_ble_hci.h" void radioNotificationStaticCallback(bool param) { nRF5xGap &gap = (nRF5xGap &) nRF5xn::Instance(BLE::DEFAULT_INSTANCE).getGap(); @@ -141,9 +135,6 @@ ble_error_t nRF5xGap::setAdvertisingData(const GapAdvertisingData &advData, cons /**************************************************************************/ ble_error_t nRF5xGap::startAdvertising(const GapAdvertisingParams ¶ms) { - uint32_t err; - ble_gap_adv_params_t adv_para = {0}; - /* Make sure we support the advertising type */ if (params.getAdvertisingType() == GapAdvertisingParams::ADV_CONNECTABLE_DIRECTED) { /* ToDo: This requires a propery security implementation, etc. */ @@ -177,7 +168,6 @@ ble_error_t nRF5xGap::startAdvertising(const GapAdvertisingParams ¶ms) return BLE_ERROR_PARAM_OUT_OF_RANGE; } -#if (NRF_SD_BLE_API_VERSION <= 2) /* Allocate the stack's whitelist statically */ ble_gap_whitelist_t whitelist; ble_gap_addr_t *whitelistAddressPtrs[YOTTA_CFG_WHITELIST_MAX_SIZE]; @@ -195,22 +185,18 @@ ble_error_t nRF5xGap::startAdvertising(const GapAdvertisingParams ¶ms) return error; } } - - adv_para.p_whitelist = &whitelist; -#endif - /* For NRF_SD_BLE_API_VERSION >= 3 nRF5xGap::setWhitelist setups the whitelist. */ - - /* Start Advertising */ + /* Start Advertising */ + ble_gap_adv_params_t adv_para = {0}; adv_para.type = params.getAdvertisingType(); adv_para.p_peer_addr = NULL; // Undirected advertisement adv_para.fp = advertisingPolicyMode; + adv_para.p_whitelist = &whitelist; adv_para.interval = params.getIntervalInADVUnits(); // advertising interval (in units of 0.625 ms) adv_para.timeout = params.getTimeout(); - - err = sd_ble_gap_adv_start(&adv_para); + uint32_t err = sd_ble_gap_adv_start(&adv_para); switch(err) { case ERROR_NONE: return BLE_ERROR_NONE; @@ -225,10 +211,6 @@ ble_error_t nRF5xGap::startAdvertising(const GapAdvertisingParams ¶ms) #if !defined(TARGET_MCU_NRF51_16K_S110) && !defined(TARGET_MCU_NRF51_32K_S110) ble_error_t nRF5xGap::startRadioScan(const GapScanningParams &scanningParams) { - - ble_gap_scan_params_t scanParams; - -#if (NRF_SD_BLE_API_VERSION <= 2) /* Allocate the stack's whitelist statically */ ble_gap_whitelist_t whitelist; ble_gap_addr_t *whitelistAddressPtrs[YOTTA_CFG_WHITELIST_MAX_SIZE]; @@ -247,17 +229,11 @@ ble_error_t nRF5xGap::startRadioScan(const GapScanningParams &scanningParams) } } - scanParams.selective = scanningPolicyMode; /**< If 1, ignore unknown devices (non whitelisted). */ - scanParams.p_whitelist = &whitelist; /**< Pointer to whitelist, NULL if none is given. */ -#else - /* For NRF_SD_BLE_API_VERSION >= 3 nRF5xGap::setWhitelist setups the whitelist. */ - - scanParams.use_whitelist = scanningPolicyMode; - scanParams.adv_dir_report = 0; -#endif + ble_gap_scan_params_t scanParams; scanParams.active = scanningParams.getActiveScanning(); /**< If 1, perform active scanning (scan requests). */ - + scanParams.selective = scanningPolicyMode; /**< If 1, ignore unknown devices (non whitelisted). */ + scanParams.p_whitelist = &whitelist; /**< Pointer to whitelist, NULL if none is given. */ scanParams.interval = scanningParams.getInterval(); /**< Scan interval between 0x0004 and 0x4000 in 0.625ms units (2.5ms to 10.24s). */ scanParams.window = scanningParams.getWindow(); /**< Scan window between 0x0004 and 0x4000 in 0.625ms units (2.5ms to 10.24s). */ scanParams.timeout = scanningParams.getTimeout(); /**< Scan timeout between 0x0001 and 0xFFFF in seconds, 0x0000 disables timeout. */ @@ -326,9 +302,6 @@ ble_error_t nRF5xGap::connect(const Address_t peerAddr, connParams.conn_sup_timeout = 600; } - ble_gap_scan_params_t scanParams ={0}; - -#if (NRF_SD_BLE_API_VERSION <= 2) /* Allocate the stack's whitelist statically */ ble_gap_whitelist_t whitelist; ble_gap_addr_t *whitelistAddressPtrs[YOTTA_CFG_WHITELIST_MAX_SIZE]; @@ -346,28 +319,10 @@ ble_error_t nRF5xGap::connect(const Address_t peerAddr, return error; } } - + + ble_gap_scan_params_t scanParams; scanParams.selective = scanningPolicyMode; /**< If 1, ignore unknown devices (non whitelisted). */ scanParams.p_whitelist = &whitelist; /**< Pointer to whitelist, NULL if none is given. */ -#else - /* For NRF_SD_BLE_API_VERSION >= 3 nRF5xGap::setWhitelist setups the whitelist. */ - - scanParams.use_whitelist = (whitelistAddressesSize) ? 1 : 0; - - if ((addr.addr_type == BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE) - || (addr.addr_type == BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_NON_RESOLVABLE)) { - /* If a device is using Resolvable Private Addresses Section 1.3.2.2 (Core spec v4.2 volume 6 part B), - it shall also have an Identity Address that is either a Public or Random Static address type.” - To establish a connection, a static address must be provided by the application to the SoftDevice. - The SoftDevice resolves the address and connects to the right device if it is available. */ - addr.addr_id_peer = 1; - addr.addr_type = BLE_GAP_ADDR_TYPE_PUBLIC; - } else { - addr.addr_id_peer = 0; - } - -#endif - if (scanParamsIn != NULL) { scanParams.active = scanParamsIn->getActiveScanning(); /**< If 1, perform active scanning (scan requests). */ scanParams.interval = scanParamsIn->getInterval(); /**< Scan interval between 0x0004 and 0x4000 in 0.625ms units (2.5ms to 10.24s). */ @@ -492,7 +447,6 @@ ble_error_t nRF5xGap::reset(void) /* Clear the internal whitelist */ whitelistAddressesSize = 0; - return BLE_ERROR_NONE; } @@ -535,13 +489,7 @@ uint16_t nRF5xGap::getConnectionHandle(void) /**************************************************************************/ ble_error_t nRF5xGap::setAddress(AddressType_t type, const Address_t address) { -#if (NRF_SD_BLE_API_VERSION <= 2) uint8_t cycle_mode; -#else - ble_gap_privacy_params_t privacy_params = {0}; -#endif - - ble_gap_addr_t dev_addr; /* When using Public or Static addresses, the cycle mode must be None. @@ -550,27 +498,12 @@ ble_error_t nRF5xGap::setAddress(AddressType_t type, const Address_t address) */ if ((type == BLEProtocol::AddressType::PUBLIC) || (type == BLEProtocol::AddressType::RANDOM_STATIC)) { - memcpy(dev_addr.addr, address, ADDR_LEN); -#if (NRF_SD_BLE_API_VERSION <= 2) cycle_mode = BLE_GAP_ADDR_CYCLE_MODE_NONE; -#else - privacy_params.privacy_mode = BLE_GAP_PRIVACY_MODE_OFF; - dev_addr.addr_type = type; - - ASSERT_INT(ERROR_NONE, pm_id_addr_set(&dev_addr), BLE_ERROR_PARAM_OUT_OF_RANGE); - ASSERT_INT(ERROR_NONE, pm_privacy_set(&privacy_params), BLE_ERROR_PARAM_OUT_OF_RANGE); -#endif + memcpy(dev_addr.addr, address, ADDR_LEN); } else if ((type == BLEProtocol::AddressType::RANDOM_PRIVATE_RESOLVABLE) || (type == BLEProtocol::AddressType::RANDOM_PRIVATE_NON_RESOLVABLE)) { -#if (NRF_SD_BLE_API_VERSION <= 2) cycle_mode = BLE_GAP_ADDR_CYCLE_MODE_AUTO; -#else - privacy_params.privacy_mode = BLE_GAP_PRIVACY_MODE_DEVICE_PRIVACY; - privacy_params.private_addr_type = type; - - ASSERT_INT(ERROR_NONE, pm_privacy_set(&privacy_params), BLE_ERROR_PARAM_OUT_OF_RANGE); -#endif // address is ignored when in auto mode } else @@ -578,10 +511,8 @@ ble_error_t nRF5xGap::setAddress(AddressType_t type, const Address_t address) return BLE_ERROR_PARAM_OUT_OF_RANGE; } -#if (NRF_SD_BLE_API_VERSION <= 2) dev_addr.addr_type = type; ASSERT_INT(ERROR_NONE, sd_ble_gap_address_set(cycle_mode, &dev_addr), BLE_ERROR_PARAM_OUT_OF_RANGE); -#endif return BLE_ERROR_NONE; } @@ -589,11 +520,7 @@ ble_error_t nRF5xGap::setAddress(AddressType_t type, const Address_t address) ble_error_t nRF5xGap::getAddress(AddressType_t *typeP, Address_t address) { ble_gap_addr_t dev_addr; -#if (NRF_SD_BLE_API_VERSION <= 2) if (sd_ble_gap_address_get(&dev_addr) != NRF_SUCCESS) { -#else - if (sd_ble_gap_addr_get(&dev_addr) != NRF_SUCCESS) { -#endif return BLE_ERROR_PARAM_OUT_OF_RANGE; } @@ -672,10 +599,6 @@ void nRF5xGap::getPermittedTxPowerValues(const int8_t **valueArrayPP, size_t *co static const int8_t permittedTxValues[] = { -40, -20, -16, -12, -8, -4, 0, 4 }; -#elif defined(NRF52840_XXAA) - static const int8_t permittedTxValues[] = { - -40, -20, -16, -12, -8, -4, 0, 2, 3, 4, 5, 6, 7, 8, 9 - }; #else #error permitted TX power values unknown for this SOC #endif @@ -725,12 +648,9 @@ uint8_t nRF5xGap::getMaxWhitelistSize(void) const /**************************************************************************/ ble_error_t nRF5xGap::getWhitelist(Gap::Whitelist_t &whitelistOut) const { - uint32_t i; + uint8_t i; for (i = 0; i < whitelistAddressesSize && i < whitelistOut.capacity; ++i) { - memcpy( &whitelistOut.addresses[i].address, &whitelistAddresses[i].addr, sizeof(whitelistOut.addresses[0].address)); - whitelistOut.addresses[i].type = static_cast (whitelistAddresses[i].addr_type); - - + memcpy(&whitelistOut.addresses[i], &whitelistAddresses[i], sizeof(BLEProtocol::Address_t)); } whitelistOut.size = i; @@ -774,24 +694,19 @@ ble_error_t nRF5xGap::setWhitelist(const Gap::Whitelist_t &whitelistIn) } /* Test for invalid parameters before we change the internal state */ - for (uint32_t i = 0; i < whitelistIn.size; ++i) { + for (uint8_t i = 0; i < whitelistIn.size; ++i) { if (whitelistIn.addresses[i].type == BLEProtocol::AddressType::RANDOM_PRIVATE_NON_RESOLVABLE) { /* This is not allowed because it is completely meaningless */ return BLE_ERROR_INVALID_PARAM; } } - whitelistAddressesSize = whitelistIn.size; - - for (uint32_t i = 0; i < whitelistIn.size; ++i) { - memcpy(&whitelistAddresses[i].addr , &whitelistIn.addresses[i].address , sizeof(whitelistAddresses[0].addr)); - whitelistAddresses[i].addr_type = static_cast (whitelistIn.addresses[i].type); + whitelistAddressesSize = 0; + for (uint8_t i = 0; i < whitelistIn.size; ++i) { + memcpy(&whitelistAddresses[whitelistAddressesSize], &whitelistIn.addresses[i], sizeof(BLEProtocol::Address_t)); + whitelistAddressesSize++; } -#if (NRF_SD_BLE_API_VERSION >= 3) - updateWhiteAndIdentityListInStack(); -#endif - return BLE_ERROR_NONE; } @@ -931,7 +846,6 @@ Gap::InitiatorPolicyMode_t nRF5xGap::getInitiatorPolicyMode(void) const return Gap::INIT_POLICY_IGNORE_WHITELIST; } -#if (NRF_SD_BLE_API_VERSION <= 2) /**************************************************************************/ /*! @brief Helper function used to populate the ble_gap_whitelist_t that @@ -1031,167 +945,3 @@ ble_error_t nRF5xGap::generateStackWhitelist(ble_gap_whitelist_t &whitelist) return BLE_ERROR_NONE; } -#endif - -#if (NRF_SD_BLE_API_VERSION >= 3) - -/** - * Function for preparing settings of the whitelist feature and the identity-resolving feature (privacy) for the SoftDevice. - * - * Gap::setWhitelist provides the base for preparation of these settings. - * This function matches resolvable addresses (passed by Gap::setWhitelist) to IRK data in bonds table. - * Therefore resolvable addresses instead of being passed to the whitelist (intended to be passed to the Softdevice) - * are passed to the identities list (intended to be passed to the Softdevice). - * - * @param[out] gapAdrHelper Reference to the struct for storing settings. - */ - -ble_error_t nRF5xGap::getStackWhiteIdentityList(GapWhiteAndIdentityList_t &gapAdrHelper) -{ - pm_peer_id_t peer_id; - - ret_code_t ret; - - pm_peer_data_bonding_t bond_data; - - uint8_t irk_found[YOTTA_CFG_WHITELIST_MAX_SIZE]; - - memset(irk_found, 0x00, sizeof(irk_found)); - - - gapAdrHelper.identities_cnt = 0; - - - peer_id = pm_next_peer_id_get(PM_PEER_ID_INVALID); - - nRF5xSecurityManager& securityManager = (nRF5xSecurityManager&) nRF5xn::Instance(0).getSecurityManager(); - - /** - * Build identities list: - * For every private resolvable address in the bond table check if - * there is maching address in th provided whitelist. - */ - while (peer_id != PM_PEER_ID_INVALID) - { - memset(&bond_data, 0x00, sizeof(bond_data)); - - // Read peer data from flash. - ret = pm_peer_data_bonding_load(peer_id, &bond_data); - - - if ((ret == NRF_ERROR_NOT_FOUND) || (ret == NRF_ERROR_INVALID_PARAM)) - { - // Peer data could not be found in flash or peer ID is not valid. - return BLE_ERROR_UNSPECIFIED; - } - - if ( bond_data.peer_ble_id.id_addr_info.addr_type == BLEProtocol::AddressType::RANDOM_PRIVATE_RESOLVABLE) - { - for (uint8_t i = 0; i < whitelistAddressesSize; ++i) - { - if (!irk_found[i]) - { - if (whitelistAddresses[i].addr_type == BLEProtocol::AddressType::RANDOM_PRIVATE_RESOLVABLE) - { - - //ble_gap_irk_t *p_dfg = &bond_data.peer_ble_id.id_info; - if (securityManager.matchAddressAndIrk(&whitelistAddresses[i], &bond_data.peer_ble_id.id_info)) - { - // Copy data to the buffer. - memcpy(&gapAdrHelper.identities[i], &bond_data.peer_ble_id, sizeof(ble_gap_id_key_t)); - gapAdrHelper.identities_cnt++; - - irk_found[i] = 1; // don't look at this address again - } - } - } - } - } - - // get next peer id - peer_id = pm_next_peer_id_get(peer_id); - } - - gapAdrHelper.addrs_cnt = 0; - - /** - * Build whitelist from the rest of addresses (explicit addresses) - */ - for (uint8_t i = 0; i < whitelistAddressesSize; ++i) - { - if (!irk_found[i]) - { - memcpy(&gapAdrHelper.addrs[i], &whitelistAddresses[i], sizeof(ble_gap_addr_t)); - gapAdrHelper.addrs[i].addr_id_peer = 0; - gapAdrHelper.addrs_cnt++; - } - } - - return BLE_ERROR_NONE; -} - -ble_error_t nRF5xGap::applyWhiteIdentityList(GapWhiteAndIdentityList_t &gapAdrHelper) -{ - uint32_t retc; - - if (gapAdrHelper.identities_cnt == 0) { - retc = sd_ble_gap_device_identities_set(NULL, NULL, 0); - } else { - ble_gap_id_key_t * pp_identities[YOTTA_CFG_IRK_TABLE_MAX_SIZE]; - - for (uint32_t i = 0; i < gapAdrHelper.identities_cnt; ++i) - { - pp_identities[i] = &gapAdrHelper.identities[i]; - } - - retc = sd_ble_gap_device_identities_set(pp_identities, NULL /* Don't use local IRKs*/,gapAdrHelper.identities_cnt); - } - - if (retc == NRF_SUCCESS) { - if (gapAdrHelper.addrs_cnt == 0) { - retc = sd_ble_gap_whitelist_set(NULL, 0); - } else { - ble_gap_addr_t * pp_addrs[YOTTA_CFG_IRK_TABLE_MAX_SIZE]; - - for (uint32_t i = 0; i < gapAdrHelper.addrs_cnt; ++i) - { - pp_addrs[i] = &gapAdrHelper.addrs[i]; - } - - retc = sd_ble_gap_whitelist_set(pp_addrs, gapAdrHelper.addrs_cnt); - } - } - - switch(retc) { - case NRF_SUCCESS: - return BLE_ERROR_NONE; - - case BLE_ERROR_GAP_WHITELIST_IN_USE: //The whitelist is in use by a BLE role and cannot be set or cleared. - case BLE_ERROR_GAP_DEVICE_IDENTITIES_IN_USE: //The device identity list is in use and cannot be set or cleared. - return BLE_ERROR_ALREADY_INITIALIZED; - - case NRF_ERROR_INVALID_ADDR: - case BLE_ERROR_GAP_INVALID_BLE_ADDR: //Invalid address type is supplied. - case NRF_ERROR_DATA_SIZE: - case BLE_ERROR_GAP_DEVICE_IDENTITIES_DUPLICATE: //The device identity list contains multiple entries with the same identity address. - return BLE_ERROR_INVALID_PARAM; - - default: - return BLE_ERROR_UNSPECIFIED; - } -} - -ble_error_t nRF5xGap::updateWhiteAndIdentityListInStack() -{ - GapWhiteAndIdentityList_t whiteAndIdentityList; - uint32_t err; - - err = getStackWhiteIdentityList(whiteAndIdentityList); - - if (err != BLE_ERROR_NONE) { - return (ble_error_t)err; - } - - return applyWhiteIdentityList(whiteAndIdentityList); -} -#endif diff --git a/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/nRF5xGap.h b/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/nRF5xGap.h index 922260954a5..cdcd9fa8fea 100644 --- a/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/nRF5xGap.h +++ b/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/nRF5xGap.h @@ -29,17 +29,13 @@ #define YOTTA_CFG_WHITELIST_MAX_SIZE BLE_GAP_WHITELIST_ADDR_MAX_COUNT #endif #ifndef YOTTA_CFG_IRK_TABLE_MAX_SIZE - #if (NRF_SD_BLE_API_VERSION >= 3) - #define YOTTA_CFG_IRK_TABLE_MAX_SIZE BLE_GAP_DEVICE_IDENTITIES_MAX_COUNT - #else - #define YOTTA_CFG_IRK_TABLE_MAX_SIZE BLE_GAP_WHITELIST_IRK_MAX_COUNT - #endif + #define YOTTA_CFG_IRK_TABLE_MAX_SIZE BLE_GAP_WHITELIST_IRK_MAX_COUNT #elif YOTTA_CFG_IRK_TABLE_MAX_SIZE > BLE_GAP_WHITELIST_IRK_MAX_COUNT #undef YOTTA_CFG_IRK_TABLE_MAX_SIZE #define YOTTA_CFG_IRK_TABLE_MAX_SIZE BLE_GAP_WHITELIST_IRK_MAX_COUNT #endif #include "ble/blecommon.h" -#include "headers/nrf_ble.h" +#include "nrf_ble.h" #include "ble/GapAdvertisingParams.h" #include "ble/GapAdvertisingData.h" #include "ble/Gap.h" @@ -139,7 +135,6 @@ class nRF5xGap : public Gap uint8_t whitelistAddressesSize; ble_gap_addr_t whitelistAddresses[YOTTA_CFG_WHITELIST_MAX_SIZE]; -#if (NRF_SD_BLE_API_VERSION <= 2) /* * An internal function used to populate the ble_gap_whitelist_t that will be used by * the SoftDevice for filtering requests. This function is needed because for the BLE @@ -147,30 +142,6 @@ class nRF5xGap : public Gap * the IRK table. */ ble_error_t generateStackWhitelist(ble_gap_whitelist_t &whitelist); -#endif - -#if (NRF_SD_BLE_API_VERSION >= 3) - /* internal type for passing a whitelist and a identities list. */ - typedef struct - { - ble_gap_addr_t addrs[YOTTA_CFG_WHITELIST_MAX_SIZE]; - uint32_t addrs_cnt; - - ble_gap_id_key_t identities[YOTTA_CFG_IRK_TABLE_MAX_SIZE]; - uint32_t identities_cnt; - } GapWhiteAndIdentityList_t; - - /* Function for preparing setting of the whitelist feature and the identity-resolving feature (privacy).*/ - ble_error_t getStackWhiteIdentityList(GapWhiteAndIdentityList_t &whiteAndIdentityList); - - /* Function for applying setting of the whitelist feature and identity-resolving feature (privacy).*/ - ble_error_t applyWhiteIdentityList(GapWhiteAndIdentityList_t &whiteAndIdentityList); - - /* Function for introducing whitelist feature and the identity-resolving feature setting into SoftDevice. - * - * This function incorporates getStackWhiteIdentityList and applyWhiteIdentityList together. */ - ble_error_t updateWhiteAndIdentityListInStack(void); -#endif private: bool radioNotificationCallbackParam; /* parameter to be passed into the Timeout-generated radio notification callback. */ diff --git a/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/nRF5xGattServer.h b/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/nRF5xGattServer.h index 77bfd26d908..dc40f8b3619 100644 --- a/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/nRF5xGattServer.h +++ b/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/nRF5xGattServer.h @@ -20,7 +20,7 @@ #include #include "ble/blecommon.h" -#include "headers/nrf_ble.h" /* nordic ble */ +#include "nrf_ble.h" /* nordic ble */ #include "ble/Gap.h" #include "ble/GattServer.h" diff --git a/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/nRF5xSecurityManager.h b/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/nRF5xSecurityManager.h index 1b675806d93..2fa7b05511e 100644 --- a/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/nRF5xSecurityManager.h +++ b/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/nRF5xSecurityManager.h @@ -45,7 +45,7 @@ class nRF5xSecurityManager : public SecurityManager virtual ble_error_t purgeAllBondingState(void) { return btle_purgeAllBondingState(); } -#if (NRF_SD_BLE_API_VERSION <= 2) + /** * @brief Returns a list of addresses from peers in the stacks bond table. * @@ -57,8 +57,6 @@ class nRF5xSecurityManager : public SecurityManager * * @return * BLE_ERROR_NONE if successful. - * - * @todo check whether remove this function (because it is never called) */ virtual ble_error_t getAddressesFromBondTable(Gap::Whitelist_t &addresses) const { uint8_t i; @@ -114,7 +112,7 @@ class nRF5xSecurityManager : public SecurityManager return BLE_ERROR_NONE; } -#endif + /** * @brief Clear nRF5xSecurityManager's state. * @@ -148,7 +146,6 @@ class nRF5xSecurityManager : public SecurityManager nRF5xSecurityManager(const nRF5xSecurityManager &); const nRF5xSecurityManager& operator=(const nRF5xSecurityManager &); -#if (NRF_SD_BLE_API_VERSION <= 2) /* * Expose an interface that allows us to query the SoftDevice bond table * and extract a whitelist. @@ -156,7 +153,7 @@ class nRF5xSecurityManager : public SecurityManager ble_error_t createWhitelistFromBondTable(ble_gap_whitelist_t &whitelistFromBondTable) const { return btle_createWhitelistFromBondTable(&whitelistFromBondTable); } -#endif + /* * Given a BLE address and a IRK this function check whether the address * can be generated from the IRK. To do so, this function uses the hash diff --git a/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/nRF5xServiceDiscovery.cpp b/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/nRF5xServiceDiscovery.cpp index 87ac20c8ff0..4bd0da6dd7b 100644 --- a/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/nRF5xServiceDiscovery.cpp +++ b/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/nRF5xServiceDiscovery.cpp @@ -281,22 +281,12 @@ nRF5xServiceDiscovery::CharUUIDDiscoveryQueue::triggerFirst(void) } void -nRF5xServiceDiscovery::processDiscoverUUIDResponse(const ble_gattc_evt_t *p_gattc_evt) +nRF5xServiceDiscovery::processDiscoverUUIDResponse(const ble_gattc_evt_char_val_by_uuid_read_rsp_t *response) { - const ble_gattc_evt_char_val_by_uuid_read_rsp_t * response = &p_gattc_evt->params.char_val_by_uuid_read_rsp; - if (state == DISCOVER_SERVICE_UUIDS) { if ((response->count == 1) && (response->value_len == UUID::LENGTH_OF_LONG_UUID)) { UUID::LongUUIDBytes_t uuid; - -#if (NRF_SD_BLE_API_VERSION >= 3) - ble_gattc_handle_value_t iter; - memset(&iter, 0, sizeof(ble_gattc_handle_value_t)); - (void) sd_ble_gattc_evt_char_val_by_uuid_read_rsp_iter(const_cast(p_gattc_evt), &iter); - memcpy(uuid, iter.p_value, UUID::LENGTH_OF_LONG_UUID); -#else - memcpy(uuid, &(response->handle_value[0].p_value[0]), UUID::LENGTH_OF_LONG_UUID); -#endif + memcpy(uuid, response->handle_value[0].p_value, UUID::LENGTH_OF_LONG_UUID); unsigned serviceIndex = serviceUUIDDiscoveryQueue.dequeue(); services[serviceIndex].setupLongUUID(uuid, UUID::LSB); @@ -308,16 +298,9 @@ nRF5xServiceDiscovery::processDiscoverUUIDResponse(const ble_gattc_evt_t *p_gatt } else if (state == DISCOVER_CHARACTERISTIC_UUIDS) { if ((response->count == 1) && (response->value_len == UUID::LENGTH_OF_LONG_UUID + 1 /* props */ + 2 /* value handle */)) { UUID::LongUUIDBytes_t uuid; - -#if (NRF_SD_BLE_API_VERSION >= 3) - ble_gattc_handle_value_t iter; - memset(&iter, 0, sizeof(ble_gattc_handle_value_t)); - (void) sd_ble_gattc_evt_char_val_by_uuid_read_rsp_iter(const_cast(p_gattc_evt), &iter); - memcpy(uuid, &(iter.p_value[3]), UUID::LENGTH_OF_LONG_UUID); -#else + memcpy(uuid, &(response->handle_value[0].p_value[3]), UUID::LENGTH_OF_LONG_UUID); -#endif - + unsigned charIndex = charUUIDDiscoveryQueue.dequeue(); characteristics[charIndex].setupLongUUID(uuid, UUID::LSB); diff --git a/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/nRF5xServiceDiscovery.h b/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/nRF5xServiceDiscovery.h index 9fb28f1d798..20bf505936e 100644 --- a/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/nRF5xServiceDiscovery.h +++ b/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF5/source/nRF5xServiceDiscovery.h @@ -21,8 +21,8 @@ #include "ble/DiscoveredService.h" #include "nRF5xDiscoveredCharacteristic.h" -#include "headers/nrf_ble.h" -#include "headers/nrf_ble_gattc.h" +#include "nrf_ble.h" +#include "nrf_ble_gattc.h" class nRF5xGattClient; /* forward declaration */ @@ -139,7 +139,7 @@ class nRF5xServiceDiscovery : public ServiceDiscovery void setupDiscoveredCharacteristics(const ble_gattc_evt_char_disc_rsp_t *response); void triggerServiceUUIDDiscovery(void); - void processDiscoverUUIDResponse(const ble_gattc_evt_t *p_gattc_evt); + void processDiscoverUUIDResponse(const ble_gattc_evt_char_val_by_uuid_read_rsp_t *response); void removeFirstServiceNeedingUUIDDiscovery(void); void terminateServiceDiscovery(void) { diff --git a/features/FEATURE_COMMON_PAL/nanostack-libservice/Makefile b/features/FEATURE_COMMON_PAL/nanostack-libservice/Makefile deleted file mode 100644 index 24fd3418e93..00000000000 --- a/features/FEATURE_COMMON_PAL/nanostack-libservice/Makefile +++ /dev/null @@ -1,13 +0,0 @@ -SRCS := \ -source/IPv6_fcf_lib/ip_fsc.c \ -source/libBits/common_functions.c \ -source/libip6string/ip6tos.c \ -source/libip6string/stoip6.c \ -source/libList/ns_list.c \ -source/nsdynmemLIB/nsdynmemLIB.c \ -source/nvmHelper/ns_nvm_helper.c \ - -LIB := libservice.a -EXPORT_HEADERS := mbed-client-libservice - -include ../exported_rules.mk diff --git a/features/FEATURE_COMMON_PAL/nanostack-libservice/mbed-client-libservice/common_functions.h b/features/FEATURE_COMMON_PAL/nanostack-libservice/mbed-client-libservice/common_functions.h index 5caf17353b2..77c52a5ab19 100644 --- a/features/FEATURE_COMMON_PAL/nanostack-libservice/mbed-client-libservice/common_functions.h +++ b/features/FEATURE_COMMON_PAL/nanostack-libservice/mbed-client-libservice/common_functions.h @@ -172,41 +172,12 @@ NS_INLINE uint_fast8_t common_count_bits(uint8_t byte); /* * Count leading zeros in a byte * - * \deprecated Use common_count_leading_zeros_8 - * * \param byte byte to inspect * * \return number of leading zeros in byte (0-8) */ NS_INLINE uint_fast8_t common_count_leading_zeros(uint8_t byte); -/* - * Count leading zeros in a byte - * - * \param byte byte to inspect - * - * \return number of leading zeros in byte (0-8) - */ -NS_INLINE uint_fast8_t common_count_leading_zeros_8(uint8_t byte); - -/* - * Count leading zeros in a 16-bit value - * - * \param value value to inspect - * - * \return number of leading zeros in byte (0-16) - */ -NS_INLINE uint_fast8_t common_count_leading_zeros_16(uint16_t value); - -/* - * Count leading zeros in a 32-bit value - * - * \param value value to inspect - * - * \return number of leading zeros in byte (0-32) - */ -NS_INLINE uint_fast8_t common_count_leading_zeros_32(uint32_t value); - /* * Compare 8-bit serial numbers * @@ -463,11 +434,6 @@ COMMON_FUNCTIONS_FN uint_fast8_t common_count_bits(uint8_t byte) } COMMON_FUNCTIONS_FN uint_fast8_t common_count_leading_zeros(uint8_t byte) -{ - return common_count_leading_zeros_8(byte); -} - -COMMON_FUNCTIONS_FN uint_fast8_t common_count_leading_zeros_8(uint8_t byte) { #ifdef __CC_ARM return byte ? __clz((unsigned int) byte << 24) : 8; @@ -494,72 +460,6 @@ COMMON_FUNCTIONS_FN uint_fast8_t common_count_leading_zeros_8(uint8_t byte) #endif } -COMMON_FUNCTIONS_FN uint_fast8_t common_count_leading_zeros_16(uint16_t value) -{ -#ifdef __CC_ARM - return value ? __clz((unsigned int) value << 16) : 16; -#elif defined __GNUC__ - return value ? __builtin_clz((unsigned int) value << 16) : 16; -#else - uint_fast8_t cnt = 0; - if (value == 0) { - return 16; - } - if ((value & 0xFF00) == 0) { - value <<= 8; - cnt += 8; - } - if ((value & 0xF000) == 0) { - value <<= 4; - cnt += 4; - } - if ((value & 0xC000) == 0) { - value <<= 2; - cnt += 2; - } - if ((value & 0x8000) == 0) { - cnt += 1; - } - - return cnt; -#endif -} - -COMMON_FUNCTIONS_FN uint_fast8_t common_count_leading_zeros_32(uint32_t value) -{ -#ifdef __CC_ARM - return __clz(value); -#elif defined __GNUC__ - return value ? __builtin_clz(value) : 32; -#else - uint_fast8_t cnt = 0; - if (value == 0) { - return 32; - } - if ((value & 0xFFFF0000) == 0) { - value <<= 16; - cnt += 16; - } - if ((value & 0xFF000000) == 0) { - value <<= 8; - cnt += 8; - } - if ((value & 0xF0000000) == 0) { - value <<= 4; - cnt += 4; - } - if ((value & 0xC0000000) == 0) { - value <<= 2; - cnt += 2; - } - if ((value & 0x80000000) == 0) { - cnt += 1; - } - - return cnt; -#endif -} - COMMON_FUNCTIONS_FN bool common_serial_number_greater_8(uint8_t s1, uint8_t s2) { return (s1 > s2 && s1 - s2 < UINT8_C(0x80)) || (s1 < s2 && s2 - s1 > UINT8_C(0x80)); diff --git a/features/FEATURE_COMMON_PAL/nanostack-libservice/mbed-client-libservice/ip6string.h b/features/FEATURE_COMMON_PAL/nanostack-libservice/mbed-client-libservice/ip6string.h index bf1f339c763..e54469ed794 100644 --- a/features/FEATURE_COMMON_PAL/nanostack-libservice/mbed-client-libservice/ip6string.h +++ b/features/FEATURE_COMMON_PAL/nanostack-libservice/mbed-client-libservice/ip6string.h @@ -20,9 +20,6 @@ extern "C" { #endif #include "ns_types.h" - -#define MAX_IPV6_STRING_LEN_WITH_TRAILING_NULL 40 - /** * Print binary IPv6 address to a string. * diff --git a/features/FEATURE_COMMON_PAL/nanostack-libservice/mbed-client-libservice/ns_trace.h b/features/FEATURE_COMMON_PAL/nanostack-libservice/mbed-client-libservice/ns_trace.h index 206e2399827..517e8858ff2 100644 --- a/features/FEATURE_COMMON_PAL/nanostack-libservice/mbed-client-libservice/ns_trace.h +++ b/features/FEATURE_COMMON_PAL/nanostack-libservice/mbed-client-libservice/ns_trace.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015-2017 ARM Limited. All rights reserved. + * Copyright (c) 2015 ARM Limited. All rights reserved. * SPDX-License-Identifier: Apache-2.0 * Licensed under the Apache License, Version 2.0 (the License); you may * not use this file except in compliance with the License. @@ -16,13 +16,38 @@ /** * \file ns_trace.h - * Trace interface abstraction for NanoStack library as well as application. + * Trace interface for NanoStack library as well as application. + * This file provide simple but flexible way to handle software traces. + * Trace library are abstract layer, which use stdout (printf) by default, + * but outputs can be easily redirect to custom function, for example to + * store traces to memory or other interfaces. * - * Actual used trace library is mbed-trace. For usage details check mbed_trace.h. + * usage example: + * \code(main.c:) + * #include "ns_trace.h" + * #define TRACE_GROUP "main" + * + * int main(void){ + * trace_init(); // initialize trace library + * tr_debug("this is debug msg"); //print debug message to stdout: "[DBG] + * tr_err("this is error msg"); + * tr_warn("this is warning msg"); + * tr_info("this is info msg"); + * return 0; + * } + * \endcode * */ #ifndef NS_TRACE_H_ #define NS_TRACE_H_ +#include "ns_types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define NS_TRACE_USE_MBED_TRACE +#if defined(NS_TRACE_USE_MBED_TRACE) #if defined(HAVE_DEBUG) && !defined(FEA_TRACE_SUPPORT) #define FEA_TRACE_SUPPORT @@ -30,4 +55,333 @@ #include "mbed-trace/mbed_trace.h" + +/* Convert libTrace calls to mbed-trace calls */ +#define trace_init() mbed_trace_init() +#define trace_free() mbed_trace_free() +#define set_trace_config(config) mbed_trace_config_set(config) +#define get_trace_config() mbed_trace_config_get() +#define set_trace_prefix_function(pref_f) mbed_trace_prefix_function_set(pref_f) +#define set_trace_suffix_function(suffix_f) mbed_trace_suffix_function_set(suffix_f) +#define set_trace_print_function(print_f) mbed_trace_print_function_set(print_f) +#define set_trace_cmdprint_function(printf) mbed_trace_cmdprint_function_set(printf) +#define set_trace_exclude_filters(filters) mbed_trace_exclude_filters_set(filters) +#define set_trace_include_filters(filters) mbed_trace_include_filters_set(filters) +#define get_trace_exclude_filters() mbed_trace_exclude_filters_get() +#define get_trace_include_filters() mbed_trace_include_filters_get() +#define trace_last() mbed_trace_last() + + +/* Definitions for the old functions with no equivalents in mbed-trace. These work without any special init. + * */ +#if defined(FEA_TRACE_SUPPORT) || defined(HAVE_DEBUG) || (defined(YOTTA_CFG) && !defined(NDEBUG)) /*backward compatible*/ +#if defined __GNUC__ || defined __CC_ARM +/** obsolete function */ +void debugf(const char *fmt, ...) __attribute__ ((__format__(__printf__, 1, 2))); //!< obsolete function +void debug(const char *s); //!< obsolete function +void debug_put(char c); //!< obsolete function +void debug_hex(uint8_t x); //!< obsolete function +void debug_int(int i); //!< obsolete function +void printf_array(const void *buf, uint16_t len); //!< obsolete function +void printf_string(const void *buf, uint16_t len); //!< obsolete function +void printf_ipv6_address(const void *addr); //!< obsolete function +#else //__GNUC__ || __CC_ARM +//obsolete functions: +void debugf(const char *fmt, ...); +void debug(const char *s); +void debug_put(char c); +void debug_hex(uint8_t x); +void debug_int(int i); +void printf_array(const void *buf, uint16_t len); +void printf_string(const void *buf, uint16_t len); +void printf_ipv6_address(const void *addr); +#endif +#else /*FEA_TRACE_SUPPORT*/ +// trace functionality not supported +//obsolete +#define debugf(...) ((void) 0) +#define debug(s) ((void) 0) +#define debug_put(c) ((void) 0) +#define debug_hex(x) ((void) 0) +#define debug_int(i) ((void) 0) +#define printf_array(buf, len) ((void) 0) +#define printf_string(buf, len) ((void) 0) +#define printf_ipv6_address(addr) ((void) 0) + +#endif /*FEA_TRACE_SUPPORT*/ + +#else /* NS_TRACE_USE_MBED_TRACE */ + +/** 3 upper bits are trace modes related, + and 5 lower bits are trace level configuration */ + +/** Config mask */ +#define TRACE_MASK_CONFIG 0xE0 +/** Trace level mask */ +#define TRACE_MASK_LEVEL 0x1F + +/** plain trace data instead of "headers" */ +#define TRACE_MODE_PLAIN 0x80 +/** color mode */ +#define TRACE_MODE_COLOR 0x40 +/** Use print CR before trace line */ +#define TRACE_CARRIAGE_RETURN 0x20 + +/** used to activate all trace levels */ +#define TRACE_ACTIVE_LEVEL_ALL 0x1F +/** print all traces same as above */ +#define TRACE_ACTIVE_LEVEL_DEBUG 0x1f +/** print info,warn and error traces */ +#define TRACE_ACTIVE_LEVEL_INFO 0x0f +/** print warn and error traces */ +#define TRACE_ACTIVE_LEVEL_WARN 0x07 +/** print only error trace */ +#define TRACE_ACTIVE_LEVEL_ERROR 0x03 +/** print only cmd line data */ +#define TRACE_ACTIVE_LEVEL_CMD 0x01 +/** trace nothing */ +#define TRACE_ACTIVE_LEVEL_NONE 0x00 + +/** this print is some deep information for debug purpose */ +#define TRACE_LEVEL_DEBUG 0x10 +/** Info print, for general purpose prints */ +#define TRACE_LEVEL_INFO 0x08 +/** warning prints, which shouldn't causes any huge problems */ +#define TRACE_LEVEL_WARN 0x04 +/** Error prints, which causes probably problems, e.g. out of mem. */ +#define TRACE_LEVEL_ERROR 0x02 +/** special level for cmdline. Behaviours like "plain mode" */ +#define TRACE_LEVEL_CMD 0x01 + +//usage macros: +#define tr_info(...) tracef(TRACE_LEVEL_INFO, TRACE_GROUP, __VA_ARGS__) //!< Print info message +#define tr_debug(...) tracef(TRACE_LEVEL_DEBUG, TRACE_GROUP, __VA_ARGS__) //!< Print debug message +#define tr_warning(...) tracef(TRACE_LEVEL_WARN, TRACE_GROUP, __VA_ARGS__) //!< Print warning message +#define tr_warn(...) tracef(TRACE_LEVEL_WARN, TRACE_GROUP, __VA_ARGS__) //!< Alternative warning message +#define tr_error(...) tracef(TRACE_LEVEL_ERROR, TRACE_GROUP, __VA_ARGS__) //!< Print Error Message +#define tr_err(...) tracef(TRACE_LEVEL_ERROR, TRACE_GROUP, __VA_ARGS__) //!< Alternative error message +#define tr_cmdline(...) tracef(TRACE_LEVEL_CMD, TRACE_GROUP, __VA_ARGS__) //!< Special print for cmdline. See more from TRACE_LEVEL_CMD -level + +/** Possible to skip all traces in compile time */ +#if defined(FEA_TRACE_SUPPORT) || defined(HAVE_DEBUG) || (defined(YOTTA_CFG) && !defined(NDEBUG)) /*backward compatible*/ + +#if defined __GNUC__ || defined __CC_ARM +/** + * Initialize trace functionality. This method must be called from application process. + * @return 0 when all success, otherwise non zero + */ +int trace_init( void ); +/** + * Free trace memory. This method must be called from application process. + */ +void trace_free( void ); +/** + * Set trace configurations + * Possible parameters: + * + * TRACE_MODE_COLOR + * TRACE_MODE_PLAIN (this exclude color mode) + * TRACE_CARRIAGE_RETURN (print CR before trace line) + * + * TRACE_ACTIVE_LEVEL_ALL - to activate all trace levels + * or TRACE_ACTIVE_LEVEL_DEBUG (alternative) + * TRACE_ACTIVE_LEVEL_INFO + * TRACE_ACTIVE_LEVEL_WARN + * TRACE_ACTIVE_LEVEL_ERROR + * TRACE_ACTIVE_LEVEL_CMD + * TRACE_LEVEL_NONE - to deactivate all traces + * + * @param config Byte size Bit-mask. Bits are descripted above. + * usage e.g. + * @code + * set_trace_config( TRACE_ACTIVE_LEVEL_ALL|TRACE_MODE_COLOR ); + * @endcode + */ +void set_trace_config(uint8_t config); +/** get trace configurations + * @return trace configuration byte + */ +uint8_t get_trace_config(void); +/** + * Set trace prefix function + * pref_f -function return string with null terminated + * Can be used for e.g. time string + * e.g. + * char* trace_time(){ return "rtc-time-in-string"; } + * set_trace_prefix_function( &trace_time ); + */ +void set_trace_prefix_function( char* (*pref_f)(size_t) ); +/** + * Set trace suffix function + * suffix -function return string with null terminated + * Can be used for e.g. time string + * e.g. + * char* trace_suffix(){ return " END"; } + * set_trace_suffix_function( &trace_suffix ); + */ +void set_trace_suffix_function(char* (*suffix_f)(void) ); +/** + * Set trace print function + * By default, trace module print using printf() function, + * but with this you can write own print function, + * for e.g. to other IO device. + */ +void set_trace_print_function( void (*print_f)(const char*) ); +/** + * Set trace print function for tr_cmdline() + */ +void set_trace_cmdprint_function( void (*printf)(const char*) ); +/** + * When trace group contains text in filters, + * trace print will be ignored. + * e.g.: + * set_trace_exclude_filters("mygr"); + * tracef(TRACE_ACTIVE_LEVEL_DEBUG, "ougr", "This is not printed"); + */ +void set_trace_exclude_filters(char* filters); +/** get trace exclude filters + */ +const char* get_trace_exclude_filters(void); +/** + * When trace group contains text in filter, + * trace will be printed. + * e.g.: + * set_trace_include_filters("mygr"); + * tracef(TRACE_ACTIVE_LEVEL_DEBUG, "mygr", "Hi There"); + * tracef(TRACE_ACTIVE_LEVEL_DEBUG, "grp2", "This is not printed"); + */ +void set_trace_include_filters(char* filters); +/** get trace include filters + */ +const char* get_trace_include_filters(void); +/** + * General trace function + * This should be used every time when user want to print out something important thing + * Usage e.g. + * tracef( TRACE_LEVEL_INFO, "mygr", "Hello world!"); + * + * @param dlevel debug level + * @param grp trace group + * @param fmt trace format (like printf) + * @param ... variable arguments related to fmt + */ +void tracef(uint8_t dlevel, const char* grp, const char *fmt, ...) __attribute__ ((__format__(__printf__, 3, 4))); +/** + * Get last trace from buffer + */ +const char* trace_last(void); +/** + * tracef helping function for convert ipv6 + * table to human readable string. + * usage e.g. + * char ipv6[16] = {...}; // ! array length is 16 bytes ! + * tracef(TRACE_LEVEL_INFO, "mygr", "ipv6 addr: %s", trace_ipv6(ipv6)); + * + * @param add_ptr IPv6 Address pointer + * @return temporary buffer where ipv6 is in string format + */ +char* trace_ipv6(const void *addr_ptr); +/** + * tracef helping function for print ipv6 prefix + * usage e.g. + * char ipv6[16] = {...}; // ! array length is 16 bytes ! + * tracef(TRACE_LEVEL_INFO, "mygr", "ipv6 addr: %s", trace_ipv6_prefix(ipv6, 4)); + * + * @param prefix IPv6 Address pointer + * @param prefix_len prefix length + * @return temporary buffer where ipv6 is in string format + */ +char* trace_ipv6_prefix(const uint8_t *prefix, uint8_t prefix_len); +/** + * tracef helping function for convert hex-array to string. + * usage e.g. + * char myarr[] = {0x10, 0x20}; + * tracef(TRACE_LEVEL_INFO, "mygr", "arr: %s", trace_array(myarr, 2)); + * + * @param buf hex array pointer + * @param len buffer length + * @return temporary buffer where string copied + */ +char* trace_array(const uint8_t* buf, uint16_t len); + + +/* + * obsolete - only because of backward compatible reason + * As soon as all these functions are replaced by new tracef() function, these can be removed. + */ + +/** obsolete function */ +void debugf(const char *fmt, ...) __attribute__ ((__format__(__printf__, 1, 2))); //!< obsolete function +void debug(const char *s); //!< obsolete function +void debug_put(char c); //!< obsolete function +void debug_hex(uint8_t x); //!< obsolete function +void debug_int(int i); //!< obsolete function +void printf_array(const void *buf, uint16_t len); //!< obsolete function +void printf_string(const void *buf, uint16_t len); //!< obsolete function +void printf_ipv6_address(const void *addr); //!< obsolete function + +#else //__GNUC__ || __CC_ARM +int trace_init( void ); +void trace_free( void ); +void set_trace_config(uint8_t config); +void set_trace_prefix_function( char* (*pref_f)(size_t) ); +void set_trace_print_function( void (*print_f)(const char*) ); +void set_trace_cmdprint_function( void (*printf)(const char*) ); +void set_trace_exclude_filters(char* filters); +const char* get_trace_exclude_filters(void); +void set_trace_include_filters(char* filters); +const char* get_trace_include_filters(void); +void tracef(uint8_t dlevel, const char* grp, const char *fmt, ...); +char* trace_ipv6(const void *addr_ptr); +char* trace_array(const uint8_t* buf, uint16_t len); +char* trace_ipv6_prefix(const uint8_t *prefix, uint8_t prefix_len); + +//obsolete functions: +void debugf(const char *fmt, ...); +void debug(const char *s); +void debug_put(char c); +void debug_hex(uint8_t x); +void debug_int(int i); +void printf_array(const void *buf, uint16_t len); +void printf_string(const void *buf, uint16_t len); +void printf_ipv6_address(const void *addr); + +#endif + + +#else /*FEA_TRACE_SUPPORT*/ + +// trace functionality not supported +#define trace_init(...) ((int) 0) +#define trace_free(...) ((void) 0) +#define set_trace_config(...) ((void) 0) +#define set_trace_prefix_function(...) ((void) 0) +#define set_trace_print_function(...) ((void) 0) +#define set_trace_cmdprint_function(...) ((void) 0) +#define set_trace_exclude_filters(...) ((void) 0) +#define set_trace_include_filters(...) ((void) 0) +#define get_trace_exclude_filters(...) ((const char*) 0) +#define get_trace_include_filters(...) ((const char*) 0) + +#define tracef(...) ((void) 0) +#define trace_ipv6(...) ((char*) 0) +#define trace_array(...) ((char*) 0) +#define trace_ipv6_prefix(...) ((char*) 0) + +//obsolete +#define debugf(...) ((void) 0) +#define debug(s) ((void) 0) +#define debug_put(c) ((void) 0) +#define debug_hex(x) ((void) 0) +#define debug_int(i) ((void) 0) +#define printf_array(buf, len) ((void) 0) +#define printf_string(buf, len) ((void) 0) +#define printf_ipv6_address(addr) ((void) 0) + +#endif /*FEA_TRACE_SUPPORT*/ +#endif /* NS_TRACE_USE_MBED_TRACE */ + +#ifdef __cplusplus +} +#endif #endif /* NS_TRACE_H_ */ diff --git a/features/FEATURE_COMMON_PAL/nanostack-libservice/mbed-client-libservice/ns_types.h b/features/FEATURE_COMMON_PAL/nanostack-libservice/mbed-client-libservice/ns_types.h index 61b31f3dc06..b89ea4b818d 100644 --- a/features/FEATURE_COMMON_PAL/nanostack-libservice/mbed-client-libservice/ns_types.h +++ b/features/FEATURE_COMMON_PAL/nanostack-libservice/mbed-client-libservice/ns_types.h @@ -62,7 +62,7 @@ * to use them, as they could exist and be more efficient than 32-bit on 8-bit * systems...) */ -#ifndef UINT_LEAST24_MAX +#ifndef UINT24_LEAST_MAX typedef uint_least32_t uint_least24_t; #define UINT_LEAST24_MAX UINT_LEAST32_MAX #define UINT24_C(x) UINT32_C(x) @@ -72,16 +72,16 @@ typedef uint_least32_t uint_least24_t; #define PRIXLEAST24 PRIXLEAST32 #endif -#ifndef INT_LEAST24_MAX +#ifndef INT24_LEAST_MAX typedef int_least32_t int_least24_t; -#define INT_LEAST24_MIN INT_LEAST32_MIN -#define INT_LEAST24_MAX INT_LEAST32_MAX +#define INT24_LEAST_MIN INT_LEAST32_MIN +#define INT24_LEAST_MAX INT_LEAST32_MAX #define INT24_C(x) INT32_C(x) #define PRIdLEAST24 PRIdLEAST32 #define PRIiLEAST24 PRIiLEAST32 #endif -#ifndef UINT_FAST24_MAX +#ifndef UINT24_FAST_MAX typedef uint_fast32_t uint_fast24_t; #define UINT_FAST24_MAX UINT_FAST32_MAX #define PRIoFAST24 PRIoFAST32 @@ -90,7 +90,7 @@ typedef uint_fast32_t uint_fast24_t; #define PRIXFAST24 PRIXFAST32 #endif -#ifndef INT_FAST24_MAX +#ifndef INT24_FAST_MAX typedef int_fast32_t int_fast24_t; #define INT_FAST24_MIN INT_FAST32_MIN #define INT_FAST24_MAX INT_FAST32_MAX diff --git a/features/FEATURE_COMMON_PAL/nanostack-libservice/source/libTrace/ns_trace.c b/features/FEATURE_COMMON_PAL/nanostack-libservice/source/libTrace/ns_trace.c new file mode 100644 index 00000000000..750d9be2c44 --- /dev/null +++ b/features/FEATURE_COMMON_PAL/nanostack-libservice/source/libTrace/ns_trace.c @@ -0,0 +1,552 @@ +/* + * Copyright (c) 2014-2015 ARM Limited. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + * Licensed under the Apache License, Version 2.0 (the License); 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 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, 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. + */ +#include +#include +#include +#include + +#define HAVE_DEBUG 1 + +#include "ns_trace.h" +#include "ip6string.h" +#include "common_functions.h" + +#if defined(_WIN32) || defined(__unix__) || defined(__unix) || defined(unix) || (defined(YOTTA_CFG) && !defined(NDEBUG)) +//NOTE! It is not allowed to use this MEM_ALLOC/MEM_FREE from interrupt context. +#ifndef MEM_ALLOC +#define MEM_ALLOC malloc +#endif +#ifndef MEM_FREE +#define MEM_FREE free +#endif +#else +#include "nsdynmemLIB.h" +#ifndef MEM_ALLOC +#define MEM_ALLOC ns_dyn_mem_alloc +#endif +#ifndef MEM_FREE +#define MEM_FREE ns_dyn_mem_free +#endif +#endif + +#ifndef NS_TRACE_USE_MBED_TRACE + +#define VT100_COLOR_ERROR "\x1b[31m" +#define VT100_COLOR_WARN "\x1b[33m" +#define VT100_COLOR_INFO "\x1b[39m" +#define VT100_COLOR_DEBUG "\x1b[90m" + +/** default max trace line size in bytes */ +#define DEFAULT_TRACE_LINE_LENGTH 1024 +/** default max temporary buffer size in bytes, used in + trace_ipv6, trace_array and trace_strn */ +#define DEFAULT_TRACE_TMP_LINE_LEN 512 +/** default max filters (include/exclude) length in bytes */ +#define DEFAULT_TRACE_FILTER_LENGTH 24 + +/** default print function, just redirect str to printf */ +static void default_print(const char *str); + +typedef struct { + /** trace configuration bits */ + uint8_t trace_config; + /** exclude filters list, related group name */ + char *filters_exclude; + /** include filters list, related group name */ + char *filters_include; + /** Filters length */ + int filters_length; + /** trace line */ + char *line; + /** trace line length */ + int line_length; + /** temporary data */ + char *tmp_data; + /** temporary data array length */ + int tmp_data_length; + /** temporary data pointer */ + char *tmp_data_ptr; + + /** prefix function, which can be used to put time to the trace line */ + char *(*prefix_f)(size_t); + /** suffix function, which can be used to some string to the end of trace line */ + char *(*suffix_f)(void); + /** print out function. Can be redirect to flash for example. */ + void (*printf)(const char *); + /** print out function for TRACE_LEVEL_CMD */ + void (*cmd_printf)(const char *); +} trace_s; + +static trace_s m_trace = { + .filters_exclude = 0, + .filters_include = 0, + .line = 0, + .tmp_data = 0, + .prefix_f = 0, + .suffix_f = 0, + .printf = 0, + .cmd_printf = 0 +}; + +int trace_init(void) +{ + m_trace.trace_config = TRACE_MODE_COLOR | TRACE_ACTIVE_LEVEL_ALL | TRACE_CARRIAGE_RETURN; + m_trace.line_length = DEFAULT_TRACE_LINE_LENGTH; + if (m_trace.line == NULL) { + m_trace.line = MEM_ALLOC(m_trace.line_length); + } + m_trace.tmp_data_length = DEFAULT_TRACE_TMP_LINE_LEN; + if (m_trace.tmp_data == NULL) { + m_trace.tmp_data = MEM_ALLOC(m_trace.tmp_data_length); + } + m_trace.tmp_data_ptr = m_trace.tmp_data; + m_trace.filters_length = DEFAULT_TRACE_FILTER_LENGTH; + if (m_trace.filters_exclude == NULL) { + m_trace.filters_exclude = MEM_ALLOC(m_trace.filters_length); + } + if (m_trace.filters_include == NULL) { + m_trace.filters_include = MEM_ALLOC(m_trace.filters_length); + } + + if (m_trace.line == NULL || + m_trace.tmp_data == NULL || + m_trace.filters_exclude == NULL || + m_trace.filters_include == NULL) { + //memory allocation fail + trace_free(); + return -1; + } + memset(m_trace.tmp_data, 0, m_trace.tmp_data_length); + memset(m_trace.filters_exclude, 0, m_trace.filters_length); + memset(m_trace.filters_include, 0, m_trace.filters_length); + memset(m_trace.line, 0, m_trace.line_length); + + m_trace.prefix_f = 0; + m_trace.suffix_f = 0; + m_trace.printf = default_print; + m_trace.cmd_printf = 0; + + return 0; +} +void trace_free(void) +{ + MEM_FREE(m_trace.line); + m_trace.line_length = 0; + m_trace.line = 0; + MEM_FREE(m_trace.tmp_data); + m_trace.tmp_data = 0; + m_trace.tmp_data_ptr = 0; + MEM_FREE(m_trace.filters_exclude); + m_trace.filters_exclude = 0; + MEM_FREE(m_trace.filters_include); + m_trace.filters_include = 0; + m_trace.filters_length = 0; +} +/** @TODO do we need dynamically change trace buffer sizes ? +// reconfigure trace buffer sizes +void set_trace_buffer_sizes(int lineLength, int tmpLength) +{ + REALLOC( m_trace.line, dataLength ); + REALLOC( m_trace.tmp_data, tmpLength); + m_trace.tmp_data_length = tmpLength; +} +*/ +void set_trace_config(uint8_t config) +{ + m_trace.trace_config = config; +} +uint8_t get_trace_config(void) +{ + return m_trace.trace_config; +} +void set_trace_prefix_function(char *(*pref_f)(size_t)) +{ + m_trace.prefix_f = pref_f; +} +void set_trace_suffix_function(char *(*suffix_f)(void)) +{ + m_trace.suffix_f = suffix_f; +} +void set_trace_print_function(void (*printf)(const char *)) +{ + m_trace.printf = printf; +} +void set_trace_cmdprint_function(void (*printf)(const char *)) +{ + m_trace.cmd_printf = printf; +} +void set_trace_exclude_filters(char *filters) +{ + if (filters) { + (void)strncpy(m_trace.filters_exclude, filters, m_trace.filters_length); + } else { + m_trace.filters_exclude[0] = 0; + } +} +const char *get_trace_exclude_filters(void) +{ + return m_trace.filters_exclude; +} +const char *get_trace_include_filters(void) +{ + return m_trace.filters_include; +} +void set_trace_include_filters(char *filters) +{ + if (filters) { + (void)strncpy(m_trace.filters_include, filters, m_trace.filters_length); + } else { + m_trace.filters_include[0] = 0; + } +} +static int8_t trace_skip(int8_t dlevel, const char *grp) +{ + if (dlevel >= 0 && grp != 0) { + // filter debug prints only when dlevel is >0 and grp is given + + /// @TODO this could be much better.. + if (m_trace.filters_exclude[0] != '\0' && + strstr(m_trace.filters_exclude, grp) != 0) { + //grp was in exclude list + return 1; + } + if (m_trace.filters_include[0] != '\0' && + strstr(m_trace.filters_include, grp) == 0) { + //grp was in include list + return 1; + } + } + return 0; +} +static void default_print(const char *str) +{ + puts(str); +} +void tracef(uint8_t dlevel, const char *grp, const char *fmt, ...) +{ + if (m_trace.line == NULL) { + // Quite likely the trace_init() has not been called yet, + // but it is better to just shut up instead of crashing with + // null pointer dereference. + m_trace.tmp_data_ptr = m_trace.tmp_data; + return; + } + + m_trace.line[0] = 0; //by default trace is empty + if (trace_skip(dlevel, grp) || fmt == 0 || grp == 0) { + m_trace.tmp_data_ptr = m_trace.tmp_data; + return; + } + if ((m_trace.trace_config & TRACE_MASK_LEVEL) & dlevel) { + bool color = (m_trace.trace_config & TRACE_MODE_COLOR) != 0; + bool plain = (m_trace.trace_config & TRACE_MODE_PLAIN) != 0; + bool cr = (m_trace.trace_config & TRACE_CARRIAGE_RETURN) != 0; + //printf("CFG: 0x%02x, plain: %i, color: %i, cr: %i\n", m_trace.trace_config, plain, color, cr); + + int retval = 0, bLeft = m_trace.line_length; + char *ptr = m_trace.line; + if (plain == true || dlevel == TRACE_LEVEL_CMD) { + va_list ap; + va_start(ap, fmt); + //add trace data + retval = vsnprintf(ptr, bLeft, fmt, ap); + va_end(ap); + if (dlevel == TRACE_LEVEL_CMD && m_trace.cmd_printf) { + m_trace.cmd_printf(m_trace.line); + m_trace.cmd_printf("\n"); + } else { + //print out whole data + m_trace.printf(m_trace.line); + } + } else { + if (color) { + if (cr) { + retval = snprintf(ptr, bLeft, "\r\x1b[2K"); + if (retval >= bLeft) { + retval = 0; + } + if (retval > 0) { + ptr += retval; + bLeft -= retval; + } + } + if (bLeft > 0) { + //include color in ANSI/VT100 escape code + switch (dlevel) { + case (TRACE_LEVEL_ERROR): + retval = snprintf(ptr, bLeft, "%s", VT100_COLOR_ERROR); + break; + case (TRACE_LEVEL_WARN): + retval = snprintf(ptr, bLeft, "%s", VT100_COLOR_WARN); + break; + case (TRACE_LEVEL_INFO): + retval = snprintf(ptr, bLeft, "%s", VT100_COLOR_INFO); + break; + case (TRACE_LEVEL_DEBUG): + retval = snprintf(ptr, bLeft, "%s", VT100_COLOR_DEBUG); + break; + default: + color = 0; //avoid unneeded color-terminate code + retval = 0; + break; + } + if (retval >= bLeft) { + retval = 0; + } + if (retval > 0 && color) { + ptr += retval; + bLeft -= retval; + } + } + + } + if (bLeft > 0 && m_trace.prefix_f) { + va_list ap; + va_start(ap, fmt); + //find out length of body + size_t sz = 0; + sz = vsnprintf(NULL, 0, fmt, ap) + retval + (retval ? 4 : 0); + //add prefix string + retval = snprintf(ptr, bLeft, "%s", m_trace.prefix_f(sz)); + if (retval >= bLeft) { + retval = 0; + } + if (retval > 0) { + ptr += retval; + bLeft -= retval; + } + va_end(ap); + } + if (bLeft > 0) { + //add group tag + switch (dlevel) { + case (TRACE_LEVEL_ERROR): + retval = snprintf(ptr, bLeft, "[ERR ][%-4s]: ", grp); + break; + case (TRACE_LEVEL_WARN): + retval = snprintf(ptr, bLeft, "[WARN][%-4s]: ", grp); + break; + case (TRACE_LEVEL_INFO): + retval = snprintf(ptr, bLeft, "[INFO][%-4s]: ", grp); + break; + case (TRACE_LEVEL_DEBUG): + retval = snprintf(ptr, bLeft, "[DBG ][%-4s]: ", grp); + break; + default: + retval = snprintf(ptr, bLeft, " "); + break; + } + if (retval >= bLeft) { + retval = 0; + } + if (retval > 0) { + ptr += retval; + bLeft -= retval; + } + } + if (retval > 0 && bLeft > 0) { + va_list ap; + va_start(ap, fmt); + //add trace text + retval = vsnprintf(ptr, bLeft, fmt, ap); + if (retval >= bLeft) { + retval = 0; + } + if (retval > 0) { + ptr += retval; + bLeft -= retval; + } + va_end(ap); + } + + if (retval > 0 && bLeft > 0 && m_trace.suffix_f) { + //add suffix string + retval = snprintf(ptr, bLeft, "%s", m_trace.suffix_f()); + if (retval >= bLeft) { + retval = 0; + } + if (retval > 0) { + ptr += retval; + bLeft -= retval; + } + } + + if (retval > 0 && bLeft > 0 && color) { + //add zero color VT100 when color mode + retval = snprintf(ptr, bLeft, "\x1b[0m"); + if (retval >= bLeft) { + retval = 0; + } + if (retval > 0) { + ptr += retval; + bLeft -= retval; + } + } + //print out whole data + m_trace.printf(m_trace.line); + } + //return tmp data pointer back to the beginning + } + m_trace.tmp_data_ptr = m_trace.tmp_data; +} +const char *trace_last(void) +{ + return m_trace.line; +} +/* Helping functions */ +#define tmp_data_left() m_trace.tmp_data_length-(m_trace.tmp_data_ptr-m_trace.tmp_data) +char *trace_ipv6(const void *addr_ptr) +{ + char *str = m_trace.tmp_data_ptr; + if (str == NULL) { + return ""; + } + if (tmp_data_left() < 41) { + return ""; + } + if (addr_ptr == NULL) { + return ""; + } + str[0] = 0; + ip6tos(addr_ptr, str); + m_trace.tmp_data_ptr += strlen(str) + 1; + return str; +} +char *trace_ipv6_prefix(const uint8_t *prefix, uint8_t prefix_len) +{ + char *str = m_trace.tmp_data_ptr; + int retval, bLeft = tmp_data_left(); + char tmp[40]; + uint8_t addr[16] = {0}; + + if (str == NULL) { + return ""; + } + if (bLeft < 40 + 1 + 3 + 1) {// "ipv6 addr" + "/" + "128" + nul + return ""; + } + + if (prefix_len != 0) { + if (prefix == NULL || prefix_len > 128) { + return ""; + } + bitcopy(addr, prefix, prefix_len); + } + + ip6tos(addr, tmp); + retval = snprintf(str, bLeft, "%s/%u", tmp, prefix_len); + if (retval <= 0 || retval > bLeft) { + return ""; + } + + m_trace.tmp_data_ptr += retval + 1; + return str; +} +char *trace_array(const uint8_t *buf, uint16_t len) +{ + int i, retval, bLeft = tmp_data_left(); + char *str, *wptr; + str = m_trace.tmp_data_ptr; + if (str == NULL || bLeft == 0) { + return ""; + } + if (buf == NULL) { + return ""; + } + if (!bLeft) { + return ""; + } + wptr = str; + wptr[0] = 0; + const uint8_t *ptr = buf; + char overflow = 0; + for (i = 0; i < len; i++) { + if (bLeft <= 3) { + overflow = 1; + break; + } + retval = snprintf(wptr, bLeft, "%02x:", *ptr++); + if (retval <= 0 || retval > bLeft) { + break; + } + bLeft -= retval; + wptr += retval; + } + if (wptr > str) { + if( overflow ) { + // replace last character as 'star', + // which indicate buffer len is not enough + *(wptr - 1) = '*'; + } else { + //null to replace last ':' character + *(wptr - 1) = 0; + } + } + m_trace.tmp_data_ptr = wptr; + return str; +} +#endif /* NS_TRACE_USE_MBED_TRACE */ + +// rest of debug print functions will be obsolete and will be overridden with new trace interface.. +void debugf(const char *fmt, ...) +{ + va_list ap; + va_start(ap, fmt); + vprintf(fmt, ap); + va_end(ap); +} + +void debug(const char *s) +{ + fputs(s, stdout); +} + +void debug_put(char c) +{ + putchar(c); +} + +void debug_hex(uint8_t x) +{ + printf("%02x", x); +} +void debug_int(int i) +{ + printf("%d", i); +} +void printf_array(const void *buf , uint16_t len) +{ + int i; + const uint8_t *ptr = buf; + for (i = 0; i < len; i++) { + if (i && (0 == i % 16)) { + putchar('\n'); + } + printf("%02x:", *ptr++); + + } + putchar('\n'); +} +void printf_ipv6_address(const void *addr_ptr) +{ + char buf[40] = {0}; + ip6tos(addr_ptr, buf); + printf("%s\n", buf); +} +void printf_string(const void *ptr, uint16_t len) +{ + printf("%.*s\n", len, (const char *)ptr); +} diff --git a/features/FEATURE_COMMON_PAL/nanostack-libservice/source/libip6string/stoip6.c b/features/FEATURE_COMMON_PAL/nanostack-libservice/source/libip6string/stoip6.c index 8e6f705a546..1bdf58fe21a 100644 --- a/features/FEATURE_COMMON_PAL/nanostack-libservice/source/libip6string/stoip6.c +++ b/features/FEATURE_COMMON_PAL/nanostack-libservice/source/libip6string/stoip6.c @@ -41,7 +41,7 @@ void stoip6(const char *ip6addr, size_t len, void *dest) } // First go forward the string, until end, noting :: position if any - for (field_no = 0, p = ip6addr; (len > (size_t)(p - ip6addr)) && *p && field_no < 8; p = q + 1) { + for (field_no = 0, p = ip6addr; (len > (p - ip6addr)) && *p && field_no < 8; p = q + 1) { q = p; // Seek for ':' or end while (*q && (*q != ':')) { @@ -51,7 +51,7 @@ void stoip6(const char *ip6addr, size_t len, void *dest) addr = common_write_16_bit(hex(p), addr); field_no++; //Check if we reached "::" - if ((len > (size_t)(q - ip6addr)) && *q && (q[0] == ':') && (q[1] == ':')) { + if ((len > (q - ip6addr)) && *q && (q[0] == ':') && (q[1] == ':')) { coloncolon = field_no; q++; } diff --git a/features/FEATURE_COMMON_PAL/nanostack-libservice/source/nsdynmemLIB/nsdynmemLIB.c b/features/FEATURE_COMMON_PAL/nanostack-libservice/source/nsdynmemLIB/nsdynmemLIB.c index 32218d7dfe8..9f41e347966 100644 --- a/features/FEATURE_COMMON_PAL/nanostack-libservice/source/nsdynmemLIB/nsdynmemLIB.c +++ b/features/FEATURE_COMMON_PAL/nanostack-libservice/source/nsdynmemLIB/nsdynmemLIB.c @@ -144,7 +144,7 @@ static int convert_allocation_size(int16_t requested_bytes) heap_failure(NS_DYN_MEM_HEAP_SECTOR_UNITIALIZED); } else if (requested_bytes < 1) { heap_failure(NS_DYN_MEM_ALLOCATE_SIZE_NOT_VALID); - } else if ((size_t)requested_bytes > (heap_size - 2 * sizeof(int)) ) { + } else if (requested_bytes > (heap_size - 2 * sizeof(int)) ) { heap_failure(NS_DYN_MEM_ALLOCATE_SIZE_NOT_VALID); } return (requested_bytes + sizeof(int) - 1) / sizeof(int); @@ -153,7 +153,8 @@ static int convert_allocation_size(int16_t requested_bytes) // Checks that block length indicators are valid // Block has format: Size of data area [1 word] | data area [abs(size) words]| Size of data area [1 word] // If Size is negative it means area is unallocated -static int8_t ns_block_validate(int *block_start) +// For direction, use 1 for direction up and -1 for down +static int8_t ns_block_validate(int *block_start, int direction) { int8_t ret_val = -1; int *end = block_start; @@ -187,7 +188,7 @@ static void *ns_dyn_mem_internal_alloc(const int16_t alloc_size, int direction) : ns_list_get_previous(&holes_list, cur_hole) ) { int *p = block_start_from_hole(cur_hole); - if (ns_block_validate(p) != 0 || *p >= 0) { + if (ns_block_validate(p, direction) != 0 || *p >= 0) { //Validation failed, or this supposed hole has positive (allocated) size heap_failure(NS_DYN_MEM_HEAP_SECTOR_CORRUPTED); break; @@ -203,7 +204,7 @@ static void *ns_dyn_mem_internal_alloc(const int16_t alloc_size, int direction) goto done; } - size_t block_data_size = -*block_ptr; + int block_data_size = -*block_ptr; if (block_data_size >= (data_size + 2 + HOLE_T_SIZE)) { int hole_size = block_data_size - data_size - 2; int *hole_ptr; @@ -273,7 +274,7 @@ void *ns_dyn_mem_temporary_alloc(int16_t alloc_size) } #ifndef STANDARD_MALLOC -static void ns_free_and_merge_with_adjacent_blocks(int * const cur_block, int data_size) +static void ns_free_and_merge_with_adjacent_blocks(int *cur_block, int data_size) { // Theory of operation: Block is always in form | Len | Data | Len | // So we need to check length of previous (if current not heap start) @@ -285,37 +286,32 @@ static void ns_free_and_merge_with_adjacent_blocks(int * const cur_block, int da int *start = cur_block; int *end = cur_block + data_size + 1; //invalidate current block - *start = -data_size; + *cur_block = -data_size; *end = -data_size; - size_t merged_data_size = data_size; - - if (start != heap_main) { - if (*(start - 1) < 0) { - int *block_end = start - 1; - size_t block_size = 1 + (-*block_end) + 1; - merged_data_size += block_size; - start -= block_size; - if (*start != *block_end) { - heap_failure(NS_DYN_MEM_HEAP_SECTOR_CORRUPTED); - } - if (block_size >= 1 + HOLE_T_SIZE + 1) { + int merged_data_size = data_size; + + if (cur_block != heap_main) { + cur_block--; + if (*cur_block < 0) { + merged_data_size += (2 - *cur_block); + start -= (2 - *cur_block); + if (-*start >= HOLE_T_SIZE) { existing_start = hole_from_block_start(start); } } + cur_block++; } if (end != heap_main_end) { - if (*(end + 1) < 0) { - int *block_start = end + 1; - size_t block_size = 1 + (-*block_start) + 1; - merged_data_size += block_size; - end += block_size; - if (*end != *block_start) { - heap_failure(NS_DYN_MEM_HEAP_SECTOR_CORRUPTED); - } - if (block_size >= 1 + HOLE_T_SIZE + 1) { - existing_end = hole_from_block_start(block_start); + end++; + if (*end < 0) { + merged_data_size += (2 - *end); + if (-*end >= HOLE_T_SIZE) { + existing_end = hole_from_block_start(end); } + end += (1 - *end); + }else{ + end--; } } @@ -386,7 +382,7 @@ void ns_dyn_mem_free(void *block) } else if ((ptr + size) >= heap_main_end) { heap_failure(NS_DYN_MEM_POINTER_NOT_VALID); } else { - if (ns_block_validate(ptr) != 0) { + if (ns_block_validate(ptr, 1) != 0) { heap_failure(NS_DYN_MEM_HEAP_SECTOR_CORRUPTED); } else { ns_free_and_merge_with_adjacent_blocks(ptr, size); diff --git a/features/FEATURE_COMMON_PAL/nanostack-libservice/source/nvmHelper/ns_nvm_helper.c b/features/FEATURE_COMMON_PAL/nanostack-libservice/source/nvmHelper/ns_nvm_helper.c index c7671e9172d..75cf77ae19b 100644 --- a/features/FEATURE_COMMON_PAL/nanostack-libservice/source/nvmHelper/ns_nvm_helper.c +++ b/features/FEATURE_COMMON_PAL/nanostack-libservice/source/nvmHelper/ns_nvm_helper.c @@ -5,6 +5,8 @@ #include #include #include +#define HAVE_DEBUG +#include "ns_trace.h" #include "ns_list.h" #include "platform/arm_hal_nvm.h" #include "ns_nvm_helper.h" @@ -91,6 +93,7 @@ int ns_nvm_key_delete(ns_nvm_callback *callback, const char *key_name, void *con if (!callback || !key_name) { return NS_NVM_ERROR; } + tr_debug("ns_nvm_key_delete() key=%s, ctx=%p", key_name, context); ns_nvm_request_t *ns_nvm_request_ptr = ns_nvm_create_request(callback, context, key_name, NULL, NULL, NS_NVM_KEY_DELETE); return ns_nvm_operation_start(ns_nvm_request_ptr); } @@ -100,6 +103,7 @@ int ns_nvm_data_read(ns_nvm_callback *callback, const char *key_name, uint8_t *b if (!callback || !key_name || !buf || !buf_len) { return NS_NVM_ERROR; } + tr_debug("ns_nvm_data_read() key=%s, len=%d, ctx=%p", key_name, (int)*buf_len, context); ns_nvm_request_t *ns_nvm_request_ptr = ns_nvm_create_request(callback, context, key_name, buf, buf_len, NS_NVM_KEY_READ); return ns_nvm_operation_start(ns_nvm_request_ptr); } @@ -109,6 +113,7 @@ int ns_nvm_data_write(ns_nvm_callback *callback, const char *key_name, uint8_t * if (!callback || !key_name || !buf || !buf_len) { return NS_NVM_ERROR; } + tr_debug("ns_nvm_data_write() key=%s, len=%d, ctx=%p", key_name, (int)*buf_len, context); ns_nvm_request_t *ns_nvm_request_ptr = ns_nvm_create_request(callback, context, key_name, buf, buf_len, NS_NVM_KEY_WRITE); return ns_nvm_operation_start(ns_nvm_request_ptr); } diff --git a/features/FEATURE_COMMON_PAL/nanostack-libservice/test/libService/unittest/Makefile b/features/FEATURE_COMMON_PAL/nanostack-libservice/test/libService/unittest/Makefile deleted file mode 100755 index b353517548f..00000000000 --- a/features/FEATURE_COMMON_PAL/nanostack-libservice/test/libService/unittest/Makefile +++ /dev/null @@ -1,23 +0,0 @@ -#scan for folders having "Makefile" in them and remove 'this' to prevent loop -ifeq ($(OS),Windows_NT) -all: -clean: -else -DIRS := $(filter-out ./, $(sort $(dir $(shell find . -name 'Makefile')))) - -all: - for dir in $(DIRS); do \ - cd $$dir; make gcov; cd ..;\ - done - -clean: - for dir in $(DIRS); do \ - cd $$dir; make clean; cd ..;\ - done - rm -rf ../source/*gcov ../source/*gcda ../source/*o - rm -rf stubs/*gcov stubs/*gcda stubs/*o - rm -rf results/* - rm -rf coverages/* - rm -rf results - rm -rf coverages -endif diff --git a/features/FEATURE_COMMON_PAL/nanostack-libservice/test/libService/unittest/MakefileWorker.mk b/features/FEATURE_COMMON_PAL/nanostack-libservice/test/libService/unittest/MakefileWorker.mk old mode 100755 new mode 100644 diff --git a/features/FEATURE_COMMON_PAL/nanostack-libservice/test/libService/unittest/ip6tos/Makefile b/features/FEATURE_COMMON_PAL/nanostack-libservice/test/libService/unittest/ip6tos/Makefile deleted file mode 100644 index 7ec8277d7cf..00000000000 --- a/features/FEATURE_COMMON_PAL/nanostack-libservice/test/libService/unittest/ip6tos/Makefile +++ /dev/null @@ -1,21 +0,0 @@ -include ../makefile_defines.txt - -COMPONENT_NAME = ip6tos_unit -SRC_FILES = \ - ../../../../source/libip6string/ip6tos.c - -TEST_SRC_FILES = \ - main.cpp \ - ip6tos_test.cpp \ - ../../../../source/libBits/common_functions.c -# ../stubs/some_stub.c \ - -# XXX: without this, the CppUTest complains for memory leak even without one. -# The funny thing is that the CppUTest does not find the memory leak on -# this app when there actually is one. -CPPUTEST_USE_MEM_LEAK_DETECTION = N - -include ../MakefileWorker.mk - -CPPUTESTFLAGS += -DFEA_TRACE_SUPPORT - diff --git a/features/FEATURE_COMMON_PAL/nanostack-libservice/test/libService/unittest/libTrace/libtracetest.cpp b/features/FEATURE_COMMON_PAL/nanostack-libservice/test/libService/unittest/libTrace/libtracetest.cpp new file mode 100644 index 00000000000..604080b8bde --- /dev/null +++ b/features/FEATURE_COMMON_PAL/nanostack-libservice/test/libService/unittest/libTrace/libtracetest.cpp @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2015 ARM Limited. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + * Licensed under the Apache License, Version 2.0 (the License); 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 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, 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. + */ +//CppUTest includes should be after your and system includes +#include "CppUTest/TestHarness.h" +#include "test_libtrace.h" + +TEST_GROUP(LibTrace) +{ + Test_LibTrace *lib_trace; + + void setup() { + lib_trace = new Test_LibTrace(); + } + + void teardown() { + delete lib_trace; + } +}; + +TEST(LibTrace, Create) +{ + CHECK(lib_trace != NULL); +} + +TEST(LibTrace, test_libTrace_tracef) +{ + lib_trace->test_libTrace_tracef(); +} + +TEST(LibTrace, test_libTrace_trace_ipv6_prefix) +{ + lib_trace->test_libTrace_trace_ipv6_prefix(); +} diff --git a/features/FEATURE_COMMON_PAL/nanostack-libservice/test/libService/unittest/libTrace/main.cpp b/features/FEATURE_COMMON_PAL/nanostack-libservice/test/libService/unittest/libTrace/main.cpp new file mode 100644 index 00000000000..cd7ce87ce1b --- /dev/null +++ b/features/FEATURE_COMMON_PAL/nanostack-libservice/test/libService/unittest/libTrace/main.cpp @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2015 ARM Limited. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + * Licensed under the Apache License, Version 2.0 (the License); 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 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, 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. + */ +#include "CppUTest/CommandLineTestRunner.h" +#include "CppUTest/TestPlugin.h" +#include "CppUTest/TestRegistry.h" +#include "CppUTestExt/MockSupportPlugin.h" +int main(int ac, char **av) +{ + return CommandLineTestRunner::RunAllTests(ac, av); +} + +IMPORT_TEST_GROUP(LibTrace); diff --git a/features/FEATURE_COMMON_PAL/nanostack-libservice/test/libService/unittest/libTrace/test_libtrace.cpp b/features/FEATURE_COMMON_PAL/nanostack-libservice/test/libService/unittest/libTrace/test_libtrace.cpp new file mode 100644 index 00000000000..62f6bdbbe01 --- /dev/null +++ b/features/FEATURE_COMMON_PAL/nanostack-libservice/test/libService/unittest/libTrace/test_libtrace.cpp @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2015 ARM Limited. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + * Licensed under the Apache License, Version 2.0 (the License); 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 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, 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. + */ +#include "CppUTest/TestHarness.h" +#include "test_libtrace.h" +#include +#include "ip6tos_stub.h" + +char buf[1024]; + +static void myprint(const char *str) +{ + strcpy(buf, str); +} + +Test_LibTrace::Test_LibTrace() +{ + trace_init(); + set_trace_print_function(myprint); +} + +Test_LibTrace::~Test_LibTrace() +{ + trace_free(); +} + +void Test_LibTrace::test_libTrace_tracef() +{ + set_trace_config(TRACE_MODE_PLAIN | TRACE_ACTIVE_LEVEL_ALL); + + memset(buf, 0, 1024); + unsigned char longStr[1000] = {0x76}; + tracef(TRACE_LEVEL_DEBUG, "mygr", "%s", trace_array(longStr, 1000)); + CHECK(buf[0] == '7'); + + memset(buf, 0, 1024); + const char longStr2[200] = {0x36}; + tracef(TRACE_LEVEL_DEBUG, "mygr", longStr2); + CHECK(buf[0] == '6'); + + +} + +void Test_LibTrace::test_libTrace_trace_ipv6_prefix() +{ + memset(buf, 0, 1024); + uint8_t prefix[] = { 0x14, 0x6e, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00 }; + int prefix_len = 64; + ip6tos_stub.c = '7'; + ip6tos_stub.h = false; + char *str = trace_ipv6_prefix(prefix, prefix_len); + SimpleString ss(str); + + CHECK("/64" == ss); + + ip6tos_stub.h = true; + char *str2 = trace_ipv6_prefix(prefix, prefix_len); + SimpleString ss2(str2); + + CHECK("7/64" == ss2); +} diff --git a/features/FEATURE_COMMON_PAL/nanostack-libservice/test/libService/unittest/libTrace/test_libtrace.h b/features/FEATURE_COMMON_PAL/nanostack-libservice/test/libService/unittest/libTrace/test_libtrace.h new file mode 100644 index 00000000000..3ad1fadf82b --- /dev/null +++ b/features/FEATURE_COMMON_PAL/nanostack-libservice/test/libService/unittest/libTrace/test_libtrace.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2015 ARM Limited. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + * Licensed under the Apache License, Version 2.0 (the License); 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 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, 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. + */ +#ifndef TEST_LIB_TRACE_H +#define TEST_LIB_TRACE_H + +#include "ns_trace.h" + +class Test_LibTrace +{ +public: + Test_LibTrace(); + + virtual ~Test_LibTrace(); + + void test_libTrace_tracef(); + + void test_libTrace_trace_ipv6_prefix(); +}; + +#endif // TEST_LIB_TRACE_H diff --git a/features/FEATURE_COMMON_PAL/nanostack-libservice/test/libService/unittest/makefile_defines.txt b/features/FEATURE_COMMON_PAL/nanostack-libservice/test/libService/unittest/makefile_defines.txt old mode 100755 new mode 100644 index 46410f7762c..93f467ca1ee --- a/features/FEATURE_COMMON_PAL/nanostack-libservice/test/libService/unittest/makefile_defines.txt +++ b/features/FEATURE_COMMON_PAL/nanostack-libservice/test/libService/unittest/makefile_defines.txt @@ -1,5 +1,4 @@ #--- Inputs ----# -MBED_TRACE_HOME = ../../../../../mbed-trace CPPUTEST_HOME = /usr CPPUTEST_USE_EXTENSIONS = Y CPPUTEST_USE_VPATH = Y @@ -12,7 +11,6 @@ INCLUDE_DIRS =\ ../../../..\ ../../../../source\ ../../../../mbed-client-libservice\ - $(MBED_TRACE_HOME)\ /usr/include\ $(CPPUTEST_HOME)/include\ diff --git a/features/FEATURE_COMMON_PAL/nanostack-libservice/test/libService/unittest/nsdynmem/Makefile b/features/FEATURE_COMMON_PAL/nanostack-libservice/test/libService/unittest/nsdynmem/Makefile deleted file mode 100644 index 8178c5d5158..00000000000 --- a/features/FEATURE_COMMON_PAL/nanostack-libservice/test/libService/unittest/nsdynmem/Makefile +++ /dev/null @@ -1,25 +0,0 @@ -include ../makefile_defines.txt - -COMPONENT_NAME = dynmem_unit -SRC_FILES = \ - ../../../../source/nsdynmemLIB/nsdynmemLIB.c - -TEST_SRC_FILES = \ - main.cpp \ - dynmemtest.cpp \ - error_callback.c \ - ../stubs/platform_critical.c \ - ../stubs/ns_list_stub.c - -# ../../../../source/libBits/common_functions.c -# ../stubs/some_stub.c \ - -# XXX: without this, the CppUTest complains for memory leak even without one. -# The funny thing is that the CppUTest does not find the memory leak on -# this app when there actually is one. -CPPUTEST_USE_MEM_LEAK_DETECTION = Y - -include ../MakefileWorker.mk - -CPPUTESTFLAGS += -DFEA_TRACE_SUPPORT - diff --git a/features/FEATURE_COMMON_PAL/nanostack-libservice/test/libService/unittest/nsdynmem/dynmemtest.cpp b/features/FEATURE_COMMON_PAL/nanostack-libservice/test/libService/unittest/nsdynmem/dynmemtest.cpp index bb978904da7..dfb0c57ed19 100644 --- a/features/FEATURE_COMMON_PAL/nanostack-libservice/test/libService/unittest/nsdynmem/dynmemtest.cpp +++ b/features/FEATURE_COMMON_PAL/nanostack-libservice/test/libService/unittest/nsdynmem/dynmemtest.cpp @@ -384,6 +384,7 @@ TEST(dynmem, free_on_empty_heap) free(heap); } + TEST(dynmem, not_negative_stats) { uint16_t size = 1000; @@ -428,48 +429,6 @@ TEST(dynmem, test_invalid_pointer_freed) { free(heap); } -TEST(dynmem, test_merge_corrupted_previous_block) { - uint16_t size = 1000; - uint8_t *heap = (uint8_t*)malloc(size); - uint8_t *p; - CHECK(NULL != heap); - reset_heap_error(); - ns_dyn_mem_init(heap, size, &heap_fail_callback, NULL); - CHECK(!heap_have_failed()); - - int *ptr = (int *)ns_dyn_mem_alloc(4); - int *ptr2 = (int *)ns_dyn_mem_alloc(4); - ns_dyn_mem_free(ptr); - ptr = ptr2 - 2; - *ptr = -2; - ns_dyn_mem_free(ptr2); - - CHECK(NS_DYN_MEM_HEAP_SECTOR_CORRUPTED == current_heap_error); - - free(heap); -} - -TEST(dynmem, test_free_corrupted_next_block) { - uint16_t size = 1000; - uint8_t *heap = (uint8_t*)malloc(size); - uint8_t *p; - CHECK(NULL != heap); - reset_heap_error(); - ns_dyn_mem_init(heap, size, &heap_fail_callback, NULL); - CHECK(!heap_have_failed()); - - int *ptr = (int *)ns_dyn_mem_temporary_alloc(4); - int *ptr2 = (int *)ns_dyn_mem_temporary_alloc(4); - ns_dyn_mem_free(ptr); - ptr = ptr2 + 2; - *ptr = -2; - ns_dyn_mem_free(ptr2); - - CHECK(NS_DYN_MEM_HEAP_SECTOR_CORRUPTED == current_heap_error); - - free(heap); -} - //NOTE! This test must be last! TEST(dynmem, uninitialized_test){ ns_dyn_mem_alloc(4); diff --git a/features/FEATURE_COMMON_PAL/nanostack-libservice/test/libService/unittest/nsnvmhelper/Makefile b/features/FEATURE_COMMON_PAL/nanostack-libservice/test/libService/unittest/nsnvmhelper/Makefile deleted file mode 100644 index f931a090c97..00000000000 --- a/features/FEATURE_COMMON_PAL/nanostack-libservice/test/libService/unittest/nsnvmhelper/Makefile +++ /dev/null @@ -1,18 +0,0 @@ -include ../makefile_defines.txt - -COMPONENT_NAME = ns_nvm_helper_unit - -SRC_FILES = ../../../../source/nvmHelper/ns_nvm_helper.c - -TEST_SRC_FILES = main.cpp \ - nsnvmhelpertest.cpp \ - test_ns_nvm_helper.c \ - ../stubs/platform_nvm_stub.c \ - ../stubs/nsdynmemLIB_stub.c \ - ../stubs/mbed_trace_stub.c \ - ../stubs/ns_list_stub.c - -include ../MakefileWorker.mk - -CPPUTESTFLAGS += -DFEA_TRACE_SUPPORT - diff --git a/features/FEATURE_COMMON_PAL/nanostack-libservice/test/libService/unittest/run_tests b/features/FEATURE_COMMON_PAL/nanostack-libservice/test/libService/unittest/run_tests old mode 100755 new mode 100644 diff --git a/features/FEATURE_COMMON_PAL/nanostack-libservice/test/libService/unittest/stoip6/Makefile b/features/FEATURE_COMMON_PAL/nanostack-libservice/test/libService/unittest/stoip6/Makefile deleted file mode 100644 index 68964c0d40d..00000000000 --- a/features/FEATURE_COMMON_PAL/nanostack-libservice/test/libService/unittest/stoip6/Makefile +++ /dev/null @@ -1,21 +0,0 @@ -include ../makefile_defines.txt - -COMPONENT_NAME = stoip6_unit -SRC_FILES = \ - ../../../../source/libip6string/stoip6.c - -TEST_SRC_FILES = \ - main.cpp \ - stoip6test.cpp \ - ../../../../source/libBits/common_functions.c -# ../stubs/some_stub.c \ - -# XXX: without this, the CppUTest complains for memory leak even without one. -# The funny thing is that the CppUTest does not find the memory leak on -# this app when there actually is one. -CPPUTEST_USE_MEM_LEAK_DETECTION = N - -include ../MakefileWorker.mk - -CPPUTESTFLAGS += -DFEA_TRACE_SUPPORT - diff --git a/features/FEATURE_COMMON_PAL/nanostack-libservice/test/libService/unittest/stubs/mbed_trace_stub.c b/features/FEATURE_COMMON_PAL/nanostack-libservice/test/libService/unittest/stubs/mbed_trace_stub.c deleted file mode 100644 index d3458b22235..00000000000 --- a/features/FEATURE_COMMON_PAL/nanostack-libservice/test/libService/unittest/stubs/mbed_trace_stub.c +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Copyright (c) 2014-2017 ARM Limited. All rights reserved. - * SPDX-License-Identifier: Apache-2.0 - * Licensed under the Apache License, Version 2.0 (the License); 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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an AS IS BASIS, 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. - */ -#include -#include -#include -#include - -#ifndef YOTTA_CFG_MBED_TRACE -#define YOTTA_CFG_MBED_TRACE 1 -#define YOTTA_CFG_MBED_TRACE_FEA_IPV6 1 -#endif - -#include "mbed-trace/mbed_trace.h" -#if YOTTA_CFG_MBED_TRACE_FEA_IPV6 == 1 -#include "mbed-client-libservice/ip6string.h" -#include "mbed-client-libservice/common_functions.h" -#endif - - -int mbed_trace_init(void) -{ - return 0; -} -void mbed_trace_free(void) -{ -} - -void mbed_trace_buffer_sizes(int lineLength, int tmpLength) -{ -} - -void mbed_trace_config_set(uint8_t config) -{ -} - -uint8_t mbed_trace_config_get(void) -{ - return 0; -} - -void mbed_trace_prefix_function_set(char *(*pref_f)(size_t)) -{ -} - -void mbed_trace_suffix_function_set(char *(*suffix_f)(void)) -{ -} - -void mbed_trace_print_function_set(void (*printf)(const char *)) -{ -} - -void mbed_trace_cmdprint_function_set(void (*printf)(const char *)) -{ -} - -void mbed_trace_exclude_filters_set(char *filters) -{ - -} - -const char *mbed_trace_exclude_filters_get(void) -{ - return NULL; -} - -const char *mbed_trace_include_filters_get(void) -{ - return NULL; -} - -void mbed_trace_include_filters_set(char *filters) -{ - -} - -void mbed_tracef(uint8_t dlevel, const char *grp, const char *fmt, ...) -{ -} - -void mbed_vtracef(uint8_t dlevel, const char *grp, const char *fmt, va_list ap) -{ -} - -const char *mbed_trace_last(void) -{ - return NULL; -} - -/* Helping functions */ -#if YOTTA_CFG_MBED_TRACE_FEA_IPV6 == 1 -char *mbed_trace_ipv6(const void *addr_ptr) -{ - return NULL; -} - -char *mbed_trace_ipv6_prefix(const uint8_t *prefix, uint8_t prefix_len) -{ - return NULL; -} -#endif //YOTTA_CFG_MBED_TRACE_FEA_IPV6 - -char *mbed_trace_array(const uint8_t *buf, uint16_t len) -{ - return NULL; -} diff --git a/features/FEATURE_COMMON_PAL/nanostack-libservice/test/libService/unittest/stubs/ns_trace_stub.c b/features/FEATURE_COMMON_PAL/nanostack-libservice/test/libService/unittest/stubs/ns_trace_stub.c new file mode 100644 index 00000000000..1c45fd401e3 --- /dev/null +++ b/features/FEATURE_COMMON_PAL/nanostack-libservice/test/libService/unittest/stubs/ns_trace_stub.c @@ -0,0 +1,202 @@ +/* + * Copyright (c) 2014-2015 ARM Limited. All rights reserved. + */ +#include +#include +#include +#include + +#include "ns_trace.h" +#include "ip6string.h" +#include "common_functions.h" + +#if defined(_WIN32) || defined(__unix__) || defined(__unix) || defined(unix) +#ifndef MEM_ALLOC +#define MEM_ALLOC malloc +#endif +#ifndef MEM_FREE +#define MEM_FREE free +#endif +#else +#include "nsdynmemLIB.h" +#ifndef MEM_ALLOC +#define MEM_ALLOC ns_dyn_mem_alloc +#endif +#ifndef MEM_FREE +#define MEM_FREE ns_dyn_mem_free +#endif +#endif + +#define VT100_COLOR_ERROR "\x1b[31m" +#define VT100_COLOR_WARN "\x1b[33m" +#define VT100_COLOR_INFO "\x1b[39m" +#define VT100_COLOR_DEBUG "\x1b[90m" + +/** default max trace line size in bytes */ +#define DEFAULT_TRACE_LINE_LENGTH 1024 +/** default max temporary buffer size in bytes, used in + trace_ipv6, trace_array and trace_strn */ +#define DEFAULT_TRACE_TMP_LINE_LEN 128 +/** default max filters (include/exclude) length in bytes */ +#define DEFAULT_TRACE_FILTER_LENGTH 24 + +static void default_print(const char *str); + +typedef struct { + /** trace configuration bits */ + uint8_t trace_config; + /** exclude filters list, related group name */ + char *filters_exclude; + /** include filters list, related group name */ + char *filters_include; + /** Filters length */ + int filters_length; + /** trace line */ + char *line; + /** trace line length */ + int line_length; + /** temporary data */ + char *tmp_data; + /** temporary data array length */ + int tmp_data_length; + /** temporary data pointer */ + char *tmp_data_ptr; + + /** prefix function, which can be used to put time to the trace line */ + char *(*prefix_f)(size_t); + /** suffix function, which can be used to some string to the end of trace line */ + char *(*suffix_f)(void); + /** print out function. Can be redirect to flash for example. */ + void (*printf)(const char *); + /** print out function for TRACE_LEVEL_CMD */ + void (*cmd_printf)(const char *); +} trace_s; + +static trace_s m_trace = { + .filters_exclude = 0, + .filters_include = 0, + .line = 0, + .tmp_data = 0, + .prefix_f = 0, + .suffix_f = 0, + .printf = 0, + .cmd_printf = 0 +}; + +int trace_init(void) +{ + return 0; +} +void trace_free(void) +{ + +} + +void set_trace_config(uint8_t config) +{ + +} +uint8_t get_trace_config(void) +{ + return 0; +} +void set_trace_prefix_function(char *(*pref_f)(size_t)) +{ +} + +void set_trace_suffix_function(char *(*suffix_f)(void)) +{ +} + +void set_trace_print_function(void (*printf)(const char *)) +{ +} + +void set_trace_cmdprint_function(void (*printf)(const char *)) +{ +} + +void set_trace_exclude_filters(char *filters) +{ +} +const char *get_trace_exclude_filters(void) +{ + return NULL; +} + +const char *get_trace_include_filters(void) +{ + return NULL; +} + +void set_trace_include_filters(char *filters) +{ +} + +static int8_t trace_skip(int8_t dlevel, const char *grp) +{ + return 0; +} + +static void default_print(const char *str) +{ +} + +void tracef(uint8_t dlevel, const char *grp, const char *fmt, ...) +{ + +} +const char *trace_last(void) +{ + return ""; +} + +/* Helping functions */ +#define tmp_data_left() m_trace.tmp_data_length-(m_trace.tmp_data_ptr-m_trace.tmp_data) +char *trace_ipv6(const void *addr_ptr) +{ + return ""; +} + +char *trace_ipv6_prefix(const uint8_t *prefix, uint8_t prefix_len) +{ + return ""; +} + +char *trace_array(const uint8_t *buf, uint16_t len) +{ + return ""; +} + +// rest of debug print functions will be obsolete and will be overridden with new trace interface.. +void debugf(const char *fmt, ...) +{ +} + +void debug(const char *s) +{ +} + +void debug_put(char c) +{ +} + +void debug_hex(uint8_t x) +{ +} + +void debug_int(int i) +{ +} + +void printf_array(const void *buf , uint16_t len) +{ +} + +void printf_ipv6_address(const void *addr_ptr) +{ +} + +void printf_string(const void *ptr, uint16_t len) +{ +} diff --git a/features/FEATURE_LWIP/TESTS/mbedmicro-net/tcp_echo_parallel/main.cpp b/features/FEATURE_LWIP/TESTS/mbedmicro-net/tcp_echo_parallel/main.cpp index bc42ca885f4..15036a2f4ad 100644 --- a/features/FEATURE_LWIP/TESTS/mbedmicro-net/tcp_echo_parallel/main.cpp +++ b/features/FEATURE_LWIP/TESTS/mbedmicro-net/tcp_echo_parallel/main.cpp @@ -84,11 +84,12 @@ class Echo { } }; +Echo echoers[MBED_CFG_TCP_CLIENT_ECHO_THREADS]; + + int main() { GREENTEA_SETUP(60, "tcp_echo"); - Echo echoers[MBED_CFG_TCP_CLIENT_ECHO_THREADS]; - int err = net.connect(); TEST_ASSERT_EQUAL(0, err); diff --git a/features/FEATURE_LWIP/TESTS/mbedmicro-net/udp_echo_parallel/main.cpp b/features/FEATURE_LWIP/TESTS/mbedmicro-net/udp_echo_parallel/main.cpp index 7ac28ff1484..3f42d00c3b2 100644 --- a/features/FEATURE_LWIP/TESTS/mbedmicro-net/udp_echo_parallel/main.cpp +++ b/features/FEATURE_LWIP/TESTS/mbedmicro-net/udp_echo_parallel/main.cpp @@ -95,11 +95,12 @@ class Echo { } }; +Echo echoers[MBED_CFG_UDP_CLIENT_ECHO_THREADS]; + + int main() { GREENTEA_SETUP(60, "udp_echo"); - Echo echoers[MBED_CFG_UDP_CLIENT_ECHO_THREADS]; - int err = net.connect(); TEST_ASSERT_EQUAL(0, err); printf("UDP client IP Address is %s\n", net.get_ip_address()); diff --git a/features/FEATURE_LWIP/lwip-interface/EthernetInterface.cpp b/features/FEATURE_LWIP/lwip-interface/EthernetInterface.cpp index 79fbfd11249..9a05a981302 100644 --- a/features/FEATURE_LWIP/lwip-interface/EthernetInterface.cpp +++ b/features/FEATURE_LWIP/lwip-interface/EthernetInterface.cpp @@ -27,14 +27,9 @@ EthernetInterface::EthernetInterface() nsapi_error_t EthernetInterface::set_network(const char *ip_address, const char *netmask, const char *gateway) { _dhcp = false; - strncpy(_ip_address, ip_address ? ip_address : "", sizeof(_ip_address)); - _ip_address[sizeof(_ip_address) - 1] = '\0'; strncpy(_netmask, netmask ? netmask : "", sizeof(_netmask)); - _netmask[sizeof(_netmask) - 1] = '\0'; strncpy(_gateway, gateway ? gateway : "", sizeof(_gateway)); - _gateway[sizeof(_gateway) - 1] = '\0'; - return NSAPI_ERROR_OK; } diff --git a/features/FEATURE_LWIP/lwip-interface/emac_lwip.c b/features/FEATURE_LWIP/lwip-interface/emac_lwip.c index f189bb2a988..f79be5d4717 100644 --- a/features/FEATURE_LWIP/lwip-interface/emac_lwip.c +++ b/features/FEATURE_LWIP/lwip-interface/emac_lwip.c @@ -63,14 +63,11 @@ err_t emac_lwip_if_init(struct netif *netif) mac->ops.set_link_input_cb(mac, emac_lwip_input, netif); mac->ops.set_link_state_cb(mac, emac_lwip_state_change, netif); - if (!mac->ops.power_up(mac)) { - err = ERR_IF; - } - - netif->mtu = mac->ops.get_mtu_size(mac); netif->hwaddr_len = mac->ops.get_hwaddr_size(mac); mac->ops.get_hwaddr(mac, netif->hwaddr); + netif->mtu = mac->ops.get_mtu_size(mac); + /* Interface capabilities */ netif->flags = NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP | NETIF_FLAG_ETHERNET | NETIF_FLAG_IGMP; @@ -82,6 +79,10 @@ err_t emac_lwip_if_init(struct netif *netif) netif->linkoutput = emac_lwip_low_level_output; + if (!mac->ops.power_up(mac)) { + err = ERR_IF; + } + return err; } diff --git a/features/FEATURE_LWIP/lwip-interface/lwip-eth/arch/TARGET_NXP/lpc17_emac.c b/features/FEATURE_LWIP/lwip-interface/lwip-eth/arch/TARGET_NXP/lpc17_emac.c index 9fa203df68f..99072c0d0ef 100644 --- a/features/FEATURE_LWIP/lwip-interface/lwip-eth/arch/TARGET_NXP/lpc17_emac.c +++ b/features/FEATURE_LWIP/lwip-interface/lwip-eth/arch/TARGET_NXP/lpc17_emac.c @@ -402,6 +402,7 @@ static struct pbuf *lpc_low_level_input(struct netif *netif) */ void lpc_enetif_input(struct netif *netif) { + struct eth_hdr *ethhdr; struct pbuf *p; /* move received packet into a new pbuf */ @@ -669,7 +670,7 @@ static err_t lpc_low_level_output(struct netif *netif, struct pbuf *p) * This function handles the transmit, receive, and error interrupt of * the LPC177x_8x. This is meant to be used when NO_SYS=0. */ -void LPC17xxEthernetHandler(void) +void ENET_IRQHandler(void) { #if NO_SYS == 1 /* Interrupts are not used without an RTOS */ @@ -860,7 +861,11 @@ static err_t low_level_init(struct netif *netif) return ERR_BUF; /* Enable packet reception */ +#if IP_SOF_BROADCAST_RECV LPC_EMAC->RxFilterCtrl = EMAC_RFC_PERFECT_EN | EMAC_RFC_BCAST_EN | EMAC_RFC_MCAST_EN; +#else + LPC_EMAC->RxFilterCtrl = EMAC_RFC_PERFECT_EN; +#endif /* Clear and enable rx/tx interrupts */ LPC_EMAC->IntClear = 0xFFFF; @@ -1045,7 +1050,6 @@ err_t eth_arch_enetif_init(struct netif *netif) } void eth_arch_enable_interrupts(void) { - NVIC_SetVector(ENET_IRQn, (uint32_t)LPC17xxEthernetHandler); NVIC_SetPriority(ENET_IRQn, ((0x01 << 3) | 0x01)); NVIC_EnableIRQ(ENET_IRQn); } diff --git a/features/FEATURE_LWIP/lwip-interface/lwip-eth/arch/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_C030/stm32f4_eth_init.c b/features/FEATURE_LWIP/lwip-interface/lwip-eth/arch/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_C030/stm32f4_eth_init.c deleted file mode 100644 index 10177d1ce25..00000000000 --- a/features/FEATURE_LWIP/lwip-interface/lwip-eth/arch/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_C030/stm32f4_eth_init.c +++ /dev/null @@ -1,86 +0,0 @@ -#include "stm32f4xx_hal.h" - -/** - * Override HAL Eth Init function - */ -void HAL_ETH_MspInit(ETH_HandleTypeDef* heth) -{ - GPIO_InitTypeDef GPIO_InitStructure; - if (heth->Instance == ETH) { - - /* Enable GPIOs clocks */ - __HAL_RCC_GPIOA_CLK_ENABLE(); - __HAL_RCC_GPIOB_CLK_ENABLE(); - __HAL_RCC_GPIOC_CLK_ENABLE(); - - /** ETH GPIO Configuration - RMII_REF_CLK ----------------------> PA1 - RMII_MDIO -------------------------> PA2 - RMII_MDC --------------------------> PC1 - RMII_MII_CRS_DV -------------------> PA7 - RMII_MII_RXD0 ---------------------> PC4 - RMII_MII_RXD1 ---------------------> PC5 - RMII_MII_RXER ---------------------> PG2 - RMII_MII_TX_EN --------------------> PB11 - RMII_MII_TXD0 ---------------------> PB12 - RMII_MII_TXD1 ---------------------> PB13 - */ - /* Configure PA1, PA2 and PA7 */ - GPIO_InitStructure.Speed = GPIO_SPEED_HIGH; - GPIO_InitStructure.Mode = GPIO_MODE_AF_PP; - GPIO_InitStructure.Pull = GPIO_PULLUP; - GPIO_InitStructure.Pin = GPIO_PIN_2 | GPIO_PIN_7; - GPIO_InitStructure.Alternate = GPIO_AF11_ETH; - HAL_GPIO_Init(GPIOA, &GPIO_InitStructure); - - GPIO_InitStructure.Pull = GPIO_NOPULL; - GPIO_InitStructure.Pin = GPIO_PIN_1; - HAL_GPIO_Init(GPIOA, &GPIO_InitStructure); - - /* Configure PB13 */ - GPIO_InitStructure.Pin = GPIO_PIN_13 | GPIO_PIN_11 | GPIO_PIN_12; - HAL_GPIO_Init(GPIOB, &GPIO_InitStructure); - - /* Configure PC1, PC4 and PC5 */ - GPIO_InitStructure.Pin = GPIO_PIN_1 | GPIO_PIN_4 | GPIO_PIN_5; - HAL_GPIO_Init(GPIOC, &GPIO_InitStructure); - - - /* Enable the Ethernet global Interrupt */ - HAL_NVIC_SetPriority(ETH_IRQn, 0x7, 0); - HAL_NVIC_EnableIRQ(ETH_IRQn); - - /* Enable ETHERNET clock */ - __HAL_RCC_ETH_CLK_ENABLE(); - } -} - -/** - * Override HAL Eth DeInit function - */ -void HAL_ETH_MspDeInit(ETH_HandleTypeDef* heth) -{ - if (heth->Instance == ETH) { - /* Peripheral clock disable */ - __HAL_RCC_ETH_CLK_DISABLE(); - - /** ETH GPIO Configuration - RMII_REF_CLK ----------------------> PA1 - RMII_MDIO -------------------------> PA2 - RMII_MDC --------------------------> PC1 - RMII_MII_CRS_DV -------------------> PA7 - RMII_MII_RXD0 ---------------------> PC4 - RMII_MII_RXD1 ---------------------> PC5 - RMII_MII_RXER ---------------------> PG2 - RMII_MII_TX_EN --------------------> PB11 - RMII_MII_TXD0 ---------------------> PB12 - RMII_MII_TXD1 ---------------------> PB13 - */ - HAL_GPIO_DeInit(GPIOA, GPIO_PIN_1 | GPIO_PIN_2 | GPIO_PIN_7); - HAL_GPIO_DeInit(GPIOB, GPIO_PIN_13 | GPIO_PIN_11 | GPIO_PIN_12); - HAL_GPIO_DeInit(GPIOC, GPIO_PIN_1 | GPIO_PIN_4 | GPIO_PIN_5); - - /* Disable the Ethernet global Interrupt */ - NVIC_DisableIRQ(ETH_IRQn); - } -} diff --git a/features/FEATURE_LWIP/lwip-interface/lwip-sys/lwip_random.h b/features/FEATURE_LWIP/lwip-interface/lwip-sys/lwip_random.h deleted file mode 100644 index 2734924cf8a..00000000000 --- a/features/FEATURE_LWIP/lwip-interface/lwip-sys/lwip_random.h +++ /dev/null @@ -1,54 +0,0 @@ -/* mbed Microcontroller Library - * Copyright (c) 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. - * You may obtain a copy of the License at - * - * 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, - * 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. - */ - -#ifndef LWIP_HDR_RANDOM_H -#define LWIP_HDR_RANDOM_H - -#include "lwip/opt.h" -#include "lwip/debug.h" -#include "lwip/def.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/** Init seed for Pseudo Random - * - * Function shall seed the pseudo-random generator. Function - * is called during lwip initialisation. - */ -void lwip_seed_random(void); - -/** Update seed for pseudo-random generator - * - * Adds seed information to existing generator, to perturb the - * sequence. - * - * @param seed 64 bits of data to add to the seed. - */ -void lwip_add_random_seed(uint64_t seed); - -/** Generates random number. - * - * @return 32-bit random number - */ -uint32_t lwip_get_random(void); - -#ifdef __cplusplus -} -#endif - -#endif /* LWIP_HDR_RANDOM_H */ diff --git a/features/FEATURE_LWIP/lwip-interface/lwip-sys/lwip_tcp_isn.c b/features/FEATURE_LWIP/lwip-interface/lwip-sys/lwip_tcp_isn.c deleted file mode 100644 index 5ddd47522bb..00000000000 --- a/features/FEATURE_LWIP/lwip-interface/lwip-sys/lwip_tcp_isn.c +++ /dev/null @@ -1,185 +0,0 @@ -/** - * @file - * - * Reference implementation of the TCP ISN algorithm standardized in RFC 6528. - * Produce TCP Initial Sequence Numbers by combining an MD5-generated hash - * based on the new TCP connection's identity and a stable secret, with the - * current time at 4-microsecond granularity. - * - * Specifically, the implementation uses MD5 to compute a hash of the input - * buffer, which contains both the four-tuple of the new TCP connection (local - * and remote IP address and port), as well as a 16-byte secret to make the - * results unpredictable to external parties. The secret must be given at - * initialization time and should ideally remain the same across system - * reboots. To be sure: the spoofing-resistance of the resulting ISN depends - * mainly on the strength of the supplied secret! - * - * The implementation takes 32 bits from the computed hash, and adds to it the - * current time, in 4-microsecond units. The current time is computed from a - * boot time given at initialization, and the current uptime as provided by - * sys_now(). Thus, it assumes that sys_now() returns a time value that is - * relative to the boot time, i.e., that it starts at 0 at system boot, and - * only ever increases monotonically. - * - * For efficiency reasons, a single MD5 input buffer is used, and partially - * filled in at initialization time. Specifically, of this 64-byte buffer, the - * first 36 bytes are used for the four-way TCP tuple data, followed by the - * 16-byte secret, followed by 12-byte zero padding. The 64-byte size of the - * buffer should achieve the best performance for the actual MD5 computation. - * - * Basic usage: - * - * 1. in your lwipopts.h, add the following lines: - * - * #include - * struct ip_addr; - * u32_t lwip_hook_tcp_isn(const struct ip_addr *local_ip, u16_t local_port, - * const struct ip_addr *remote_ip, u16_t remote_port); - * "#define LWIP_HOOK_TCP_ISN lwip_hook_tcp_isn"; - * - * 2. from your own code, call lwip_init_tcp_isn() at initialization time, with - * appropriate parameters. - */ - -/* - * Copyright (c) 2016 The MINIX 3 Project. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. The name of the author may not be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT - * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT - * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING - * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY - * OF SUCH DAMAGE. - * - * Author: David van Moolenbroek - */ - -#include "lwip_tcp_isn.h" -#include "lwip/ip_addr.h" -#include "lwip/sys.h" -#include - -/* pull in md5 of ppp? */ -#define PPP_SUPPORT 1 -#include "netif/ppp/ppp_opts.h" -#include "netif/ppp/ppp.h" -#include "netif/ppp/pppcrypt.h" -#if !LWIP_USE_EXTERNAL_POLARSSL && !LWIP_USE_EXTERNAL_MBEDTLS -#undef LWIP_INCLUDED_POLARSSL_MD5 -#define LWIP_INCLUDED_POLARSSL_MD5 1 -#include "netif/ppp/polarssl/lwip_md5.c" -#endif -#if LWIP_USE_EXTERNAL_MBEDTLS -#include "mbedtls/inc/mbedtls/md5.h" -#define md5_context mbedtls_md5_context -#endif - -static u8_t input[64]; -static u32_t base_time; - -/** - * Initialize the TCP ISN module, with the boot time and a secret. - * - * @param boot_time Wall clock boot time of the system, in seconds. - * @param secret_16_bytes A 16-byte secret used to randomize the TCP ISNs. - */ -void -lwip_init_tcp_isn(u32_t boot_time, const u8_t *secret_16_bytes) -{ - /* Initialize the input buffer with the secret and trailing zeroes. */ - memset(input, 0, sizeof(input)); - - MEMCPY(&input[36], secret_16_bytes, 16); - - /* Save the boot time in 4-us units. Overflow is no problem here. */ - base_time = boot_time * 250000; -} - -/** - * Hook to generate an Initial Sequence Number (ISN) for a new TCP connection. - * - * @param local_ip The local IP address. - * @param local_port The local port number, in host-byte order. - * @param remote_ip The remote IP address. - * @param remote_port The remote port number, in host-byte order. - * @return The ISN to use for the new TCP connection. - */ -u32_t -lwip_hook_tcp_isn(const ip_addr_t *local_ip, u16_t local_port, - const ip_addr_t *remote_ip, u16_t remote_port) -{ - md5_context ctx; - u8_t output[16]; - u32_t isn; - -#if LWIP_IPV4 && LWIP_IPV6 - if (IP_IS_V6(local_ip)) -#endif /* LWIP_IPV4 && LWIP_IPV6 */ -#if LWIP_IPV6 - { - const ip6_addr_t *local_ip6, *remote_ip6; - - local_ip6 = ip_2_ip6(local_ip); - remote_ip6 = ip_2_ip6(remote_ip); - - SMEMCPY(&input[0], &local_ip6->addr, 16); - SMEMCPY(&input[16], &remote_ip6->addr, 16); - } -#endif /* LWIP_IPV6 */ -#if LWIP_IPV4 && LWIP_IPV6 - else -#endif /* LWIP_IPV4 && LWIP_IPV6 */ -#if LWIP_IPV4 - { - const ip4_addr_t *local_ip4, *remote_ip4; - - local_ip4 = ip_2_ip4(local_ip); - remote_ip4 = ip_2_ip4(remote_ip); - - /* Represent IPv4 addresses as IPv4-mapped IPv6 addresses, to ensure that - * the IPv4 and IPv6 address spaces are completely disjoint. */ - memset(&input[0], 0, 10); - input[10] = 0xff; - input[11] = 0xff; - SMEMCPY(&input[12], &local_ip4->addr, 4); - memset(&input[16], 0, 10); - input[26] = 0xff; - input[27] = 0xff; - SMEMCPY(&input[28], &remote_ip4->addr, 4); - } -#endif /* LWIP_IPV4 */ - - input[32] = local_port >> 8; - input[33] = local_port & 0xff; - input[34] = remote_port >> 8; - input[35] = remote_port & 0xff; - - /* The secret and padding are already filled in. */ - - /* Generate the hash, using MD5. */ - lwip_md5_starts(&ctx); - lwip_md5_update(&ctx, input, sizeof(input)); - lwip_md5_finish(&ctx, output); - - /* Arbitrarily take the first 32 bits from the generated hash. */ - MEMCPY(&isn, output, sizeof(isn)); - - /* Add the current time in 4-microsecond units. */ - return isn + base_time + sys_now() * 250; -} diff --git a/features/FEATURE_LWIP/lwip-interface/lwip_stack.c b/features/FEATURE_LWIP/lwip-interface/lwip_stack.c index a1e7709d3e7..dffc1610fb7 100644 --- a/features/FEATURE_LWIP/lwip-interface/lwip_stack.c +++ b/features/FEATURE_LWIP/lwip-interface/lwip_stack.c @@ -34,7 +34,6 @@ #include "lwip/udp.h" #include "emac_api.h" -#include "lwip_tcp_isn.h" #if DEVICE_EMAC #define MBED_NETIF_INIT_FN emac_lwip_if_init @@ -109,9 +108,7 @@ static void mbed_lwip_socket_callback(struct netconn *nc, enum netconn_evt eh, u /* TCP/IP and Network Interface Initialisation */ static struct netif lwip_netif; -#if LWIP_IPV4 static bool lwip_dhcp = false; -#endif static char lwip_mac_address[NSAPI_MAC_SIZE]; #if !LWIP_IPV4 || !LWIP_IPV6 @@ -192,9 +189,7 @@ static bool convert_lwip_addr_to_mbed(nsapi_addr_t *out, const ip_addr_t *in) return true; } #endif -#if LWIP_IPV6 && LWIP_IPV4 return false; -#endif } static const ip_addr_t *mbed_lwip_get_ipv4_addr(const struct netif *netif) @@ -329,23 +324,15 @@ static void mbed_lwip_netif_status_irq(struct netif *lwip_netif) static void mbed_lwip_set_mac_address(void) { #if (MBED_MAC_ADDRESS_SUM != MBED_MAC_ADDR_INTERFACE) - (void) snprintf(lwip_mac_address, NSAPI_MAC_SIZE, "%02x:%02x:%02x:%02x:%02x:%02x", + snprintf(lwip_mac_address, NSAPI_MAC_SIZE, "%02x:%02x:%02x:%02x:%02x:%02x", MBED_MAC_ADDR_0, MBED_MAC_ADDR_1, MBED_MAC_ADDR_2, MBED_MAC_ADDR_3, MBED_MAC_ADDR_4, MBED_MAC_ADDR_5); #else char mac[6]; mbed_mac_address(mac); - (void) snprintf(lwip_mac_address, NSAPI_MAC_SIZE, "%02x:%02x:%02x:%02x:%02x:%02x", + snprintf(lwip_mac_address, NSAPI_MAC_SIZE, "%02x:%02x:%02x:%02x:%02x:%02x", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); #endif - - /* Use mac address as additional seed to random number generator */ - uint64_t seed = mac[0]; - for (uint8_t i = 1; i < 8; i++) { - seed <<= 8; - seed |= mac[i % 6]; - } - lwip_add_random_seed(seed); } /* LWIP interface implementation */ @@ -370,9 +357,7 @@ char *mbed_lwip_get_ip_address(char *buf, nsapi_size_t buflen) return ip4addr_ntoa_r(ip_2_ip4(addr), buf, buflen); } #endif -#if LWIP_IPV6 && LWIP_IPV4 return NULL; -#endif } const char *mbed_lwip_get_netmask(char *buf, nsapi_size_t buflen) @@ -405,19 +390,10 @@ char *mbed_lwip_get_gateway(char *buf, nsapi_size_t buflen) nsapi_error_t mbed_lwip_init(emac_interface_t *emac) { - // Check if we've already brought up lwip if (!mbed_lwip_get_mac_address()) { - // Seed lwip random - lwip_seed_random(); - // Set up network - // Initialise TCP sequence number - uint32_t tcp_isn_secret[4]; - for (int i = 0; i < 4; i++) { - tcp_isn_secret[i] = LWIP_RAND(); - } - lwip_init_tcp_isn(0, (u8_t *) &tcp_isn_secret); + mbed_lwip_set_mac_address(); sys_sem_new(&lwip_tcpip_inited, 0); sys_sem_new(&lwip_netif_linked, 0); @@ -435,7 +411,6 @@ nsapi_error_t mbed_lwip_init(emac_interface_t *emac) return NSAPI_ERROR_DEVICE_ERROR; } - mbed_lwip_set_mac_address(); netif_set_default(&lwip_netif); netif_set_link_callback(&lwip_netif, mbed_lwip_netif_link_irq); @@ -682,7 +657,7 @@ static nsapi_error_t mbed_lwip_socket_open(nsapi_stack_t *stack, nsapi_socket_t return NSAPI_ERROR_NO_SOCKET; } - enum netconn_type lwip_proto = proto == NSAPI_TCP ? NETCONN_TCP : NETCONN_UDP; + u8_t lwip_proto = proto == NSAPI_TCP ? NETCONN_TCP : NETCONN_UDP; #if LWIP_IPV6 && LWIP_IPV4 const ip_addr_t *ip_addr; diff --git a/features/FEATURE_LWIP/lwip-interface/lwipopts.h b/features/FEATURE_LWIP/lwip-interface/lwipopts.h index e28b008e33b..9bf0a203280 100644 --- a/features/FEATURE_LWIP/lwip-interface/lwipopts.h +++ b/features/FEATURE_LWIP/lwip-interface/lwipopts.h @@ -80,28 +80,18 @@ #define DEFAULT_RAW_RECVMBOX_SIZE 8 #define DEFAULT_ACCEPTMBOX_SIZE 8 -// Thread stack size for lwip tcpip thread -#ifndef MBED_CONF_LWIP_TCPIP_THREAD_STACKSIZE -#define MBED_CONF_LWIP_TCPIP_THREAD_STACKSIZE 1200 -#endif - #ifdef LWIP_DEBUG -#define TCPIP_THREAD_STACKSIZE MBED_CONF_LWIP_TCPIP_THREAD_STACKSIZE*2 +#define TCPIP_THREAD_STACKSIZE 1200*2 #else -#define TCPIP_THREAD_STACKSIZE MBED_CONF_LWIP_TCPIP_THREAD_STACKSIZE +#define TCPIP_THREAD_STACKSIZE 1200 #endif #define TCPIP_THREAD_PRIO (osPriorityNormal) -// Thread stack size for lwip system threads -#ifndef MBED_CONF_LWIP_DEFAULT_THREAD_STACKSIZE -#define MBED_CONF_LWIP_DEFAULT_THREAD_STACKSIZE 512 -#endif - #ifdef LWIP_DEBUG -#define DEFAULT_THREAD_STACKSIZE MBED_CONF_LWIP_DEFAULT_THREAD_STACKSIZE*2 +#define DEFAULT_THREAD_STACKSIZE 512*2 #else -#define DEFAULT_THREAD_STACKSIZE MBED_CONF_LWIP_DEFAULT_THREAD_STACKSIZE +#define DEFAULT_THREAD_STACKSIZE 512 #endif #define MEMP_NUM_SYS_TIMEOUT 16 @@ -176,7 +166,7 @@ // Support Multicast #include "stdlib.h" #define LWIP_IGMP LWIP_IPV4 -#define LWIP_RAND() lwip_get_random() +#define LWIP_RAND() rand() #define LWIP_COMPAT_SOCKETS 0 #define LWIP_POSIX_SOCKETS_IO_NAMES 0 @@ -249,8 +239,7 @@ #define LWIP_BROADCAST_PING 1 -// Checksum-on-copy disabled due to https://savannah.nongnu.org/bugs/?50914 -#define LWIP_CHECKSUM_ON_COPY 0 +#define LWIP_CHECKSUM_ON_COPY 1 #define LWIP_NETIF_HOSTNAME 1 #define LWIP_NETIF_STATUS_CALLBACK 1 @@ -276,12 +265,4 @@ #error A transport mechanism (Ethernet or PPP) must be defined #endif -#include -#include "lwip_random.h" -#include "lwip_tcp_isn.h" -#define LWIP_HOOK_TCP_ISN lwip_hook_tcp_isn -#if MBEDTLS_MD5_C -#define LWIP_USE_EXTERNAL_MBEDTLS 1 -#endif - #endif /* LWIPOPTS_H_ */ diff --git a/features/FEATURE_LWIP/lwip-interface/mbed_lib.json b/features/FEATURE_LWIP/lwip-interface/mbed_lib.json index 0ec67b79191..a594e4e4a09 100644 --- a/features/FEATURE_LWIP/lwip-interface/mbed_lib.json +++ b/features/FEATURE_LWIP/lwip-interface/mbed_lib.json @@ -32,14 +32,6 @@ "udp-socket-max": { "help": "Maximum number of open UDPSocket instances allowed, including one used internally for DNS. Each requires 84 bytes of pre-allocated RAM", "value": 4 - }, - "tcpip-thread-stacksize": { - "help": "Stack size for lwip TCPIP thread", - "value": 1200 - }, - "default-thread-stacksize": { - "help": "Stack size for lwip system threads", - "value": 512 } } } diff --git a/features/FEATURE_UVISOR/importer/Makefile b/features/FEATURE_UVISOR/importer/Makefile index 1d385076288..45a79e619bc 100644 --- a/features/FEATURE_UVISOR/importer/Makefile +++ b/features/FEATURE_UVISOR/importer/Makefile @@ -84,7 +84,7 @@ rsync: cp $(UVISOR_DIR)/core/cmsis/inc/core_cmSecureAccess.h $(MBED_OS_CMSIS)/ # # Copying the documentation... - cp $(UVISOR_DIR)/docs/*/QUICKSTART.md $(TARGET_PREFIX)/README.md + cp $(UVISOR_DIR)/docs/api/QUICKSTART.md $(TARGET_PREFIX)/README.md # # Copying licenses cp $(UVISOR_DIR)/LICENSE* $(TARGET_SUPPORTED) diff --git a/features/TESTS/filesystem/fat_filesystem/main.cpp b/features/TESTS/filesystem/fat_filesystem/main.cpp index 45d393ffd97..5ef12fb4716 100644 --- a/features/TESTS/filesystem/fat_filesystem/main.cpp +++ b/features/TESTS/filesystem/fat_filesystem/main.cpp @@ -116,13 +116,7 @@ void test_read_dir() { while ((de = readdir(&dir))) { printf("d_name: %.32s, d_type: %x\n", de->d_name, de->d_type); - if (strcmp(de->d_name, ".") == 0) { - test_dir_found = true; - TEST_ASSERT_EQUAL(DT_DIR, de->d_type); - } else if (strcmp(de->d_name, "..") == 0) { - test_dir_found = true; - TEST_ASSERT_EQUAL(DT_DIR, de->d_type); - } else if (strcmp(de->d_name, "test_dir") == 0) { + if (strcmp(de->d_name, "test_dir") == 0) { test_dir_found = true; TEST_ASSERT_EQUAL(DT_DIR, de->d_type); } else if (strcmp(de->d_name, "test_file") == 0) { diff --git a/features/TESTS/filesystem/heap_block_device/main.cpp b/features/TESTS/filesystem/heap_block_device/main.cpp index 2a5e9d6e7fa..8d337ed73e2 100644 --- a/features/TESTS/filesystem/heap_block_device/main.cpp +++ b/features/TESTS/filesystem/heap_block_device/main.cpp @@ -24,11 +24,7 @@ using namespace utest::v1; #define TEST_BLOCK_SIZE 512 -#if MBED_SMALL_TARGET -# define TEST_BLOCK_DEVICE_SIZE 8*TEST_BLOCK_SIZE -#else -# define TEST_BLOCK_DEVICE_SIZE 16*TEST_BLOCK_SIZE -#endif +#define TEST_BLOCK_DEVICE_SIZE 16*TEST_BLOCK_SIZE #define TEST_BLOCK_COUNT 10 #define TEST_ERROR_MASK 16 diff --git a/features/filesystem/fat/ChaN/ffconf.h b/features/filesystem/fat/ChaN/ffconf.h index f8da280725a..838e72ce00e 100644 --- a/features/filesystem/fat/ChaN/ffconf.h +++ b/features/filesystem/fat/ChaN/ffconf.h @@ -126,7 +126,7 @@ / When _LFN_UNICODE is 0, this option has no effect. */ -#define _FS_RPATH 1 +#define _FS_RPATH 0 /* This option configures relative path feature. / / 0: Disable relative path feature and remove related functions. diff --git a/features/nanostack/FEATURE_NANOSTACK/mbed-mesh-api/README.md b/features/nanostack/FEATURE_NANOSTACK/mbed-mesh-api/README.md index bf105db083f..2339bdbc625 100644 --- a/features/nanostack/FEATURE_NANOSTACK/mbed-mesh-api/README.md +++ b/features/nanostack/FEATURE_NANOSTACK/mbed-mesh-api/README.md @@ -41,18 +41,13 @@ An example of the configuration file: | --------------- | ------------- | ----------- | | thread-pskd | string [6-255 chars] | Human-scaled commissioning credentials. | | thread-device-type | enum from mesh_device_type_t | Set device operating mode. | -| thread-use-static-link-config | boolean | True: Use the below link config, False: Use commissioning, ignore the below link config. | | thread-config-channel-mask | number [0-0x07fff800] | Channel mask, 0x07fff800 scans all channels. | | thread-config-channel-page | number [0, 2]| Channel page, 0 for 2,4 GHz and 2 for sub-GHz radios. | | thread-config-channel | number [0-27] | RF channel to use. | | thread-config-panid | number [0-0xFFFF] | Network identifier. | -| thread-config-network-name | string [1-16] | -| thread-config-commissioning-dataset-timestamp | [0-0xFFFFFFFFFFFFFFFF] | [48 bit timestamp seconds]-[15 bit timestamp ticks]-[U bit] | -|thread-config-extended-panid | byte array [8] | Extended PAN ID | | thread-master-key | byte array [16]| Network master key. | | thread-config-ml-prefix | byte array [8] | Mesh local prefix. | | thread-config-pskc | byte array [16] | Pre-Shared Key for the Commissioner. | -| thread-security-policy | number [0-0xFF] | Commissioning security policy bits | ### 6LoWPAN related configuration parameters diff --git a/features/nanostack/FEATURE_NANOSTACK/mbed-mesh-api/mbed_lib.json b/features/nanostack/FEATURE_NANOSTACK/mbed-mesh-api/mbed_lib.json index d668e2261d5..28b7ea179d6 100644 --- a/features/nanostack/FEATURE_NANOSTACK/mbed-mesh-api/mbed_lib.json +++ b/features/nanostack/FEATURE_NANOSTACK/mbed-mesh-api/mbed_lib.json @@ -12,18 +12,16 @@ "6lowpan-nd-sec-level": 5, "6lowpan-nd-device-type": "NET_6LOWPAN_ROUTER", "thread-pskd": "\"abcdefghijklmno\"", - "thread-use-static-link-config": true, "thread-config-channel-mask": "0x7fff800", "thread-config-channel-page": 0, "thread-config-channel": 22, "thread-config-panid": "0x0700", "thread-config-network-name": "\"Thread Network\"", - "thread-config-commissioning-dataset-timestamp": "0x10000", + "thread-config-commissioning-dataset-timestamp": "0x00010000", "thread-config-extended-panid": "{0xf1, 0xb5, 0xa1, 0xb2,0xc4, 0xd5, 0xa1, 0xbd }", "thread-master-key": "{0x10, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff}", "thread-config-ml-prefix": "{0xfd, 0x0, 0x0d, 0xb8, 0x0, 0x0, 0x0, 0x0}", "thread-config-pskc": "{0xc8, 0xa6, 0x2e, 0xae, 0xf3, 0x68, 0xf3, 0x46, 0xa9, 0x9e, 0x57, 0x85, 0x98, 0x9d, 0x1c, 0xd0}", - "thread-device-type": "MESH_DEVICE_TYPE_THREAD_ROUTER", - "thread-security-policy": 255 + "thread-device-type": "MESH_DEVICE_TYPE_THREAD_ROUTER" } } diff --git a/features/nanostack/FEATURE_NANOSTACK/mbed-mesh-api/source/ethernet_tasklet.c b/features/nanostack/FEATURE_NANOSTACK/mbed-mesh-api/source/ethernet_tasklet.c index c2c4d3e3605..cdab9beb895 100644 --- a/features/nanostack/FEATURE_NANOSTACK/mbed-mesh-api/source/ethernet_tasklet.c +++ b/features/nanostack/FEATURE_NANOSTACK/mbed-mesh-api/source/ethernet_tasklet.c @@ -20,6 +20,7 @@ #include "net_interface.h" #include "ip6string.h" //ip6tos #include "nsdynmemLIB.h" +#include "include/static_config.h" #include "include/mesh_system.h" #include "ns_event_loop.h" #include "mesh_interface_types.h" diff --git a/features/nanostack/FEATURE_NANOSTACK/mbed-mesh-api/source/include/static_config.h b/features/nanostack/FEATURE_NANOSTACK/mbed-mesh-api/source/include/static_config.h new file mode 100644 index 00000000000..19123f4b215 --- /dev/null +++ b/features/nanostack/FEATURE_NANOSTACK/mbed-mesh-api/source/include/static_config.h @@ -0,0 +1,177 @@ +/* + * Copyright (c) 2015 ARM Limited. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + * Licensed under the Apache License, Version 2.0 (the License); 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 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, 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. + */ + +#ifndef __INCLUDE_STATIC_CONFIG__ +#define __INCLUDE_STATIC_CONFIG__ +#include "ns_types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#if defined MBED_CONF_MBED_MESH_API_HEAP_SIZE +#define MBED_MESH_API_HEAP_SIZE MBED_CONF_MBED_MESH_API_HEAP_SIZE +#else +#define MBED_MESH_API_HEAP_SIZE 32500 +#endif + +/* + * Channel list is defined as 1 shifted by the channel number + * f.e.: + * channel 4 = 1<<4. + * channel 10 = 1<<10 + * + * Channel page. + * -for scan channels 0-10 use value 2 = CHANNEL_PAGE_2 + * -for scan channels 11-26 use value 0 = CHANNEL_PAGE_0 + * Possible channels are 0,1,2,3,4,5,6,9,10, see arm_hal_phy.h for details + */ + +#if defined MBED_CONF_MBED_MESH_API_6LOWPAN_ND_CHANNEL_PAGE +#define MBED_MESH_API_6LOWPAN_ND_CHANNEL_PAGE MBED_CONF_MBED_MESH_API_6LOWPAN_ND_CHANNEL_PAGE +#else +#define MBED_MESH_API_6LOWPAN_ND_CHANNEL_PAGE 0 +#endif + +#if defined MBED_CONF_MBED_MESH_API_6LOWPAN_ND_CHANNEL +#define MBED_MESH_API_6LOWPAN_ND_CHANNEL MBED_CONF_MBED_MESH_API_6LOWPAN_ND_CHANNEL +#else +#define MBED_MESH_API_6LOWPAN_ND_CHANNEL 0 +#endif + +#if defined MBED_CONF_MBED_MESH_API_6LOWPAN_ND_CHANNEL_MASK +#define MBED_MESH_API_6LOWPAN_ND_CHANNEL_MASK MBED_CONF_MBED_MESH_API_6LOWPAN_ND_CHANNEL_MASK +#elif defined MBED_MESH_API_6LOWPAN_ND_CHANNEL +#define MBED_MESH_API_6LOWPAN_ND_CHANNEL_MASK (1<channel_list, 0, sizeof(tasklet_data_ptr->channel_list)); - tasklet_data_ptr->channel_list.channel_page = (channel_page_e)MBED_CONF_MBED_MESH_API_6LOWPAN_ND_CHANNEL_PAGE; - tasklet_data_ptr->channel_list.channel_mask[0] = MBED_CONF_MBED_MESH_API_6LOWPAN_ND_CHANNEL_MASK; + tasklet_data_ptr->channel_list.channel_page = (channel_page_e)MBED_MESH_API_6LOWPAN_ND_CHANNEL_PAGE; + tasklet_data_ptr->channel_list.channel_mask[0] = MBED_MESH_API_6LOWPAN_ND_CHANNEL_MASK; if (channel > 0) { memset(&tasklet_data_ptr->channel_list.channel_mask, 0, sizeof(tasklet_data_ptr->channel_list.channel_mask)); @@ -232,13 +233,13 @@ void nd_tasklet_configure_and_connect_to_network(void) tasklet_data_ptr->network_interface_id, tasklet_data_ptr->mode, NET_6LOWPAN_ND_WITH_MLE); - sec_mode = STR(MBED_CONF_MBED_MESH_API_6LOWPAN_ND_SECURITY_MODE); + sec_mode = STR(MBED_MESH_API_6LOWPAN_ND_SECURITY_MODE); if (strcmp(sec_mode, "PSK") == 0) { tr_debug("Using PSK security mode."); tasklet_data_ptr->sec_mode = NET_SEC_MODE_PSK_LINK_SECURITY; - tasklet_data_ptr->psk_sec_info.key_id = MBED_CONF_MBED_MESH_API_6LOWPAN_ND_PSK_KEY_ID; - memcpy(tasklet_data_ptr->psk_sec_info.security_key, (const uint8_t[16])MBED_CONF_MBED_MESH_API_6LOWPAN_ND_PSK_KEY, 16); + tasklet_data_ptr->psk_sec_info.key_id = MBED_MESH_API_6LOWPAN_ND_PSK_KEY_ID; + memcpy(tasklet_data_ptr->psk_sec_info.security_key, (const uint8_t[16])MBED_MESH_API_6LOWPAN_ND_PSK_KEY, 16); } else { tr_debug("Link-layer security NOT enabled."); tasklet_data_ptr->sec_mode = NET_SEC_MODE_NO_LINK_SECURITY; @@ -248,7 +249,7 @@ void nd_tasklet_configure_and_connect_to_network(void) arm_nwk_link_layer_security_mode( tasklet_data_ptr->network_interface_id, tasklet_data_ptr->sec_mode, - MBED_CONF_MBED_MESH_API_6LOWPAN_ND_SEC_LEVEL, + MBED_MESH_API_6LOWPAN_ND_SEC_LEVEL, &tasklet_data_ptr->psk_sec_info); // configure scan parameters @@ -263,7 +264,7 @@ void nd_tasklet_configure_and_connect_to_network(void) arm_nwk_6lowpan_link_panid_filter_for_nwk_scan( tasklet_data_ptr->network_interface_id, - MBED_CONF_MBED_MESH_API_6LOWPAN_ND_PANID_FILTER); + MBED_MESH_API_6LOWPAN_ND_PANID_FILTER); status = arm_nwk_interface_up(tasklet_data_ptr->network_interface_id); if (status >= 0) { diff --git a/features/nanostack/FEATURE_NANOSTACK/mbed-mesh-api/source/thread_tasklet.c b/features/nanostack/FEATURE_NANOSTACK/mbed-mesh-api/source/thread_tasklet.c index 2f2f274dd1e..b49c91d8d87 100644 --- a/features/nanostack/FEATURE_NANOSTACK/mbed-mesh-api/source/thread_tasklet.c +++ b/features/nanostack/FEATURE_NANOSTACK/mbed-mesh-api/source/thread_tasklet.c @@ -23,6 +23,7 @@ #include "thread_management_if.h" #include "net_polling_api.h" #include "include/thread_tasklet.h" +#include "include/static_config.h" #include "include/mesh_system.h" #include #include "ns_event_loop.h" @@ -75,7 +76,11 @@ typedef struct { /** Default network ID*/ uint8_t networkid[16]; - uint8_t extented_panid[8]; + uint8_t extented_panid[8]; + uint32_t pan_id; + uint32_t rfChannel; + uint8_t scan_time; + net_6lowpan_gp_address_mode_e address_mode; } thread_tasklet_data_str_t; @@ -204,48 +209,6 @@ void thread_tasklet_parse_network_event(arm_event_s *event) } } -void read_link_configuration() { - - thread_tasklet_data_ptr->link_config.panId = MBED_CONF_MBED_MESH_API_THREAD_CONFIG_PANID; - TRACE_DETAIL("PANID %x", thread_tasklet_data_ptr->link_config.panId); - - thread_tasklet_data_ptr->link_config.rfChannel = MBED_CONF_MBED_MESH_API_THREAD_CONFIG_CHANNEL; - TRACE_DETAIL("channel: %d", thread_tasklet_data_ptr->link_config.rfChannel); - - // Mesh prefix - const uint8_t mesh_local_prefix[] = MBED_CONF_MBED_MESH_API_THREAD_CONFIG_ML_PREFIX; - MBED_ASSERT(sizeof(mesh_local_prefix) == 8); - - memcpy(thread_tasklet_data_ptr->link_config.mesh_local_ula_prefix, mesh_local_prefix, 8); - TRACE_DETAIL("Mesh prefix: %s", trace_array(mesh_local_prefix, 8)); - - // Master Key - const uint8_t master_key[] = MBED_CONF_MBED_MESH_API_THREAD_MASTER_KEY; - MBED_ASSERT(sizeof(master_key) == 16); - memcpy(thread_tasklet_data_ptr->link_config.master_key, master_key, 16); - - // PSKc - const uint8_t PSKc[] = MBED_CONF_MBED_MESH_API_THREAD_CONFIG_PSKC; - MBED_ASSERT(sizeof(PSKc) == 16); - memcpy(thread_tasklet_data_ptr->link_config.PSKc, PSKc, 16); - - thread_tasklet_data_ptr->link_config.key_rotation = 3600; - thread_tasklet_data_ptr->link_config.key_sequence = 0; - - thread_tasklet_data_ptr->link_config.securityPolicy = MBED_CONF_MBED_MESH_API_THREAD_SECURITY_POLICY; - - // network name - MBED_ASSERT(strlen(MBED_CONF_MBED_MESH_API_THREAD_CONFIG_NETWORK_NAME) > 0 && strlen(MBED_CONF_MBED_MESH_API_THREAD_CONFIG_NETWORK_NAME) < 17); - memcpy(thread_tasklet_data_ptr->link_config.name, MBED_CONF_MBED_MESH_API_THREAD_CONFIG_NETWORK_NAME, strlen(MBED_CONF_MBED_MESH_API_THREAD_CONFIG_NETWORK_NAME)); - - thread_tasklet_data_ptr->link_config.timestamp = MBED_CONF_MBED_MESH_API_THREAD_CONFIG_COMMISSIONING_DATASET_TIMESTAMP; - - // extended pan-id - const uint8_t extented_panid[] = MBED_CONF_MBED_MESH_API_THREAD_CONFIG_EXTENDED_PANID; - MBED_ASSERT(sizeof(extented_panid) == 8); - memcpy(thread_tasklet_data_ptr->link_config.extented_pan_id, extented_panid, sizeof(extented_panid)); -} - /* * \brief Configure mesh network * @@ -253,9 +216,8 @@ void read_link_configuration() { void thread_tasklet_configure_and_connect_to_network(void) { int8_t status; - link_configuration_s* temp_link_config=NULL; - if (MBED_CONF_MBED_MESH_API_THREAD_DEVICE_TYPE == MESH_DEVICE_TYPE_THREAD_SLEEPY_END_DEVICE) { + if (MBED_MESH_API_THREAD_DEVICE_TYPE == MESH_DEVICE_TYPE_THREAD_SLEEPY_END_DEVICE) { thread_tasklet_data_ptr->operating_mode = NET_6LOWPAN_SLEEPY_HOST; } else { thread_tasklet_data_ptr->operating_mode = NET_6LOWPAN_ROUTER; @@ -265,32 +227,69 @@ void thread_tasklet_configure_and_connect_to_network(void) thread_tasklet_data_ptr->nwk_if_id, thread_tasklet_data_ptr->operating_mode, NET_6LOWPAN_THREAD); - - thread_tasklet_data_ptr->channel_list.channel_page = (channel_page_e)MBED_CONF_MBED_MESH_API_THREAD_CONFIG_CHANNEL_PAGE; - thread_tasklet_data_ptr->channel_list.channel_mask[0] = MBED_CONF_MBED_MESH_API_THREAD_CONFIG_CHANNEL_MASK; - + + // Link configuration + thread_tasklet_data_ptr->link_config.panId = MBED_MESH_API_THREAD_CONFIG_PANID; + TRACE_DETAIL("PANID %x", thread_tasklet_data_ptr->link_config.panId); + + thread_tasklet_data_ptr->link_config.rfChannel = MBED_MESH_API_THREAD_CONFIG_CHANNEL; + thread_tasklet_data_ptr->channel_list.channel_page = (channel_page_e)MBED_MESH_API_THREAD_CONFIG_CHANNEL_PAGE; + thread_tasklet_data_ptr->channel_list.channel_mask[0] = MBED_MESH_API_THREAD_CONFIG_CHANNEL_MASK; + TRACE_DETAIL("channel: %d", thread_tasklet_data_ptr->link_config.rfChannel); TRACE_DETAIL("channel page: %d", thread_tasklet_data_ptr->channel_list.channel_page); TRACE_DETAIL("channel mask: %d", (int)thread_tasklet_data_ptr->channel_list.channel_mask[0]); - + + // Beacon data setting + thread_tasklet_data_ptr->link_config.Protocol_id = 0x03; + thread_tasklet_data_ptr->link_config.version = 1; + memcpy(thread_tasklet_data_ptr->link_config.extended_random_mac, device_configuration.eui64, 8); + thread_tasklet_data_ptr->link_config.extended_random_mac[0] |= 0x02; + + // network name + MBED_ASSERT(strlen(MBED_MESH_API_THREAD_CONFIG_NETWORK_NAME) > 0 && strlen(MBED_MESH_API_THREAD_CONFIG_NETWORK_NAME) < 17); + memcpy(thread_tasklet_data_ptr->link_config.name, MBED_MESH_API_THREAD_CONFIG_NETWORK_NAME, strlen(MBED_MESH_API_THREAD_CONFIG_NETWORK_NAME)); + + thread_tasklet_data_ptr->link_config.timestamp = MBED_MESH_API_THREAD_CONFIG_COMMISSIONING_DATASET_TIMESTAMP; + + // extended pan-id + const uint8_t extented_panid[] = MBED_MESH_API_THREAD_CONFIG_EXTENDED_PANID; + MBED_ASSERT(sizeof(extented_panid) == 8); + memcpy(thread_tasklet_data_ptr->link_config.extented_pan_id, extented_panid, sizeof(extented_panid)); + + // Mesh prefix + const uint8_t mesh_local_prefix[] = MBED_MESH_API_THREAD_CONFIG_ML_PREFIX; + MBED_ASSERT(sizeof(mesh_local_prefix) == 8); + + memcpy(thread_tasklet_data_ptr->link_config.mesh_local_ula_prefix, mesh_local_prefix, 8); + TRACE_DETAIL("Mesh prefix: %s", trace_array(mesh_local_prefix, 8)); + + // Master Key + const uint8_t master_key[] = MBED_MESH_API_THREAD_MASTER_KEY; + MBED_ASSERT(sizeof(master_key) == 16); + memcpy(thread_tasklet_data_ptr->link_config.master_key, master_key, 16); + + // PSKc + const uint8_t PSKc[] = MBED_MESH_API_THREAD_CONFIG_PSKC; + MBED_ASSERT(sizeof(PSKc) == 16); + memcpy(thread_tasklet_data_ptr->link_config.PSKc, PSKc, 16); + // PSKd - const char PSKd[] = MBED_CONF_MBED_MESH_API_THREAD_PSKD; - MBED_ASSERT(sizeof(PSKd) > 5 && sizeof(PSKd) < 33); + const char PSKd[] = MBED_MESH_API_THREAD_PSKD; + MBED_ASSERT(sizeof(PSKd) > 5 && sizeof(PSKd) < 33); char *dyn_buf = ns_dyn_mem_alloc(sizeof(PSKd)); strcpy(dyn_buf, PSKd); ns_dyn_mem_free(device_configuration.PSKd_ptr); device_configuration.PSKd_ptr = (uint8_t*)dyn_buf; - device_configuration.PSKd_len = sizeof(PSKd) - 1; - - if (true == MBED_CONF_MBED_MESH_API_THREAD_USE_STATIC_LINK_CONFIG) { - read_link_configuration(); - temp_link_config = &thread_tasklet_data_ptr->link_config; - } - + device_configuration.PSKd_len = sizeof(PSKd) - 1; + + thread_tasklet_data_ptr->link_config.key_rotation = 3600; + thread_tasklet_data_ptr->link_config.key_sequence = 0; + thread_management_node_init(thread_tasklet_data_ptr->nwk_if_id, - &thread_tasklet_data_ptr->channel_list, - &device_configuration, - temp_link_config); + &thread_tasklet_data_ptr->channel_list, + &device_configuration, + &thread_tasklet_data_ptr->link_config); status = arm_nwk_interface_up(thread_tasklet_data_ptr->nwk_if_id); @@ -414,7 +413,6 @@ void thread_tasklet_init(void) { if (thread_tasklet_data_ptr == NULL) { thread_tasklet_data_ptr = ns_dyn_mem_alloc(sizeof(thread_tasklet_data_str_t)); - memset(thread_tasklet_data_ptr, 0, sizeof(thread_tasklet_data_str_t)); thread_tasklet_data_ptr->tasklet_state = TASKLET_STATE_CREATED; thread_tasklet_data_ptr->nwk_if_id = INVALID_INTERFACE_ID; } diff --git a/features/netsocket/nsapi_dns.cpp b/features/netsocket/nsapi_dns.cpp index 4f957717021..4e1970a266d 100644 --- a/features/netsocket/nsapi_dns.cpp +++ b/features/netsocket/nsapi_dns.cpp @@ -227,7 +227,7 @@ static nsapi_size_or_error_t nsapi_dns_query_multiple(NetworkStack *stack, const uint8_t *question = packet; dns_append_question(&question, host, version); - err = socket.sendto(SocketAddress(dns_servers[i], 53), packet, question - packet); + err = socket.sendto(SocketAddress(dns_servers[i], 53), packet, DNS_BUFFER_SIZE); // send may fail for various reasons, including wrong address type - move on if (err < 0) { continue; diff --git a/features/unsupported/USBDevice/USBDevice/TARGET_STM/TARGET_STM32F7/TARGET_STM32F767xI/TARGET_NUCLEO_F767ZI/USBHAL_STM_TARGET.h b/features/unsupported/USBDevice/USBDevice/TARGET_STM/TARGET_STM32F7/TARGET_STM32F767xI/TARGET_NUCLEO_F767ZI/USBHAL_STM_TARGET.h deleted file mode 100644 index 238f70e2963..00000000000 --- a/features/unsupported/USBDevice/USBDevice/TARGET_STM/TARGET_STM32F7/TARGET_STM32F767xI/TARGET_NUCLEO_F767ZI/USBHAL_STM_TARGET.h +++ /dev/null @@ -1,18 +0,0 @@ -/* Copyright (c) 2016 mbed.org, MIT License -* -* Permission is hereby granted, free of charge, to any person obtaining a copy of this software -* and associated documentation files (the "Software"), to deal in the Software without -* restriction, including without limitation the rights to use, copy, modify, merge, publish, -* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the -* Software is furnished to do so, subject to the following conditions: -* -* The above copyright notice and this permission notice shall be included in all copies or -* substantial portions of the Software. -* -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING -* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -*/ -#include "USBHAL_STM_144_64pins.h" diff --git a/features/unsupported/USBDevice/USBDevice/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L053C8/USBHAL_STM32L053C8.h b/features/unsupported/USBDevice/USBDevice/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L053C8/USBHAL_STM32L053C8.h deleted file mode 100644 index 69b6b8196cb..00000000000 --- a/features/unsupported/USBDevice/USBDevice/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L053C8/USBHAL_STM32L053C8.h +++ /dev/null @@ -1,134 +0,0 @@ -/* Copyright (c) 2016 mbed.org, MIT License -* -* Permission is hereby granted, free of charge, to any person obtaining a copy of this software -* and associated documentation files (the "Software"), to deal in the Software without -* restriction, including without limitation the rights to use, copy, modify, merge, publish, -* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the -* Software is furnished to do so, subject to the following conditions: -* -* The above copyright notice and this permission notice shall be included in all copies or -* substantial portions of the Software. -* -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING -* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -*/ -#ifndef USBHAL_STM32L053C8_H -#define USBHAL_STM32L053C8_H - -#define USBHAL_IRQn USB_IRQn - -/* must be multiple of 4 bytes */ -#define NB_ENDPOINT 8 -#define MAXTRANSFER_SIZE 0x200 -#define FIFO_USB_RAM_SIZE (MAXTRANSFER_SIZE+MAX_PACKET_SIZE_EP0+MAX_PACKET_SIZE_EP1+MAX_PACKET_SIZE_EP2+MAX_PACKET_SIZE_EP3) -#if (FIFO_USB_RAM_SIZE > 0x500) -#error "FIFO dimensioning incorrect" -#endif - -typedef struct -{ - USBHAL *inst; - void (USBHAL::*bus_reset)(void); - void (USBHAL::*sof)(int frame); - void (USBHAL::*connect_change)(unsigned int connected); - void (USBHAL::*suspend_change)(unsigned int suspended); - void (USBHAL::*ep0_setup)(void); - void (USBHAL::*ep0_in)(void); - void (USBHAL::*ep0_out)(void); - void (USBHAL::*ep0_read)(void); - bool (USBHAL::*ep_realise)(uint8_t endpoint, uint32_t maxPacket, uint32_t flags); - bool (USBHAL::*epCallback[6])(void); - uint8_t epComplete[2*NB_ENDPOINT]; - /* memorize dummy buffer used for reception */ - uint32_t pBufRx[MAXTRANSFER_SIZE>>2]; - uint32_t pBufRx0[MAX_PACKET_SIZE_EP0>>2]; - gpio_t usb_switch; -}USBHAL_Private_t; - -uint32_t HAL_PCDEx_GetTxFiFo(PCD_HandleTypeDef *hpcd, uint8_t fifo) -{ - return 1024; -} - -void HAL_PCDEx_SetConnectionState(PCD_HandleTypeDef *hpcd, uint8_t state) -{ - USBHAL_Private_t *priv=((USBHAL_Private_t *)(hpcd->pData)); - gpio_write(&(priv->usb_switch),state); -} - -void HAL_PCD_SOFCallback(PCD_HandleTypeDef *hpcd) -{ - USBHAL_Private_t *priv=((USBHAL_Private_t *)(hpcd->pData)); - USBHAL *obj= priv->inst; - uint32_t sofnum = (hpcd->Instance->FNR) & USB_FNR_FN; - void (USBHAL::*func)(int frame) = priv->sof; - (obj->*func)(sofnum); -} - -USBHAL * USBHAL::instance; - -USBHAL::USBHAL(void) -{ - /* init parameter */ - USBHAL_Private_t *HALPriv = new(USBHAL_Private_t); - hpcd.Instance = USB; - /* initialized Init to zero (constructor does not zero initialized the - * area */ - /* initialized all field of init including 0 field */ - /* constructor does not fill with zero */ - memset(&hpcd.Init, 0, sizeof(hpcd.Init)); - hpcd.Init.dev_endpoints = NB_ENDPOINT; - hpcd.Init.ep0_mps = MAX_PACKET_SIZE_EP0; - hpcd.Init.phy_itface = PCD_PHY_EMBEDDED; - hpcd.Init.Sof_enable = 1; - hpcd.Init.speed = PCD_SPEED_FULL; - /* pass instance for usage inside call back */ - HALPriv->inst = this; - HALPriv->bus_reset = &USBHAL::busReset; - HALPriv->suspend_change = &USBHAL::suspendStateChanged; - HALPriv->connect_change = &USBHAL::connectStateChanged; - HALPriv->sof = &USBHAL::SOF; - HALPriv->ep0_setup = &USBHAL::EP0setupCallback; - HALPriv->ep_realise = &USBHAL::realiseEndpoint; - HALPriv->ep0_in = &USBHAL::EP0in; - HALPriv->ep0_out = &USBHAL::EP0out; - HALPriv->ep0_read = &USBHAL::EP0read; - hpcd.pData = (void*)HALPriv; - HALPriv->epCallback[0] = &USBHAL::EP1_OUT_callback; - HALPriv->epCallback[1] = &USBHAL::EP1_IN_callback; - HALPriv->epCallback[2] = &USBHAL::EP2_OUT_callback; - HALPriv->epCallback[3] = &USBHAL::EP2_IN_callback; - HALPriv->epCallback[4] = &USBHAL::EP3_OUT_callback; - HALPriv->epCallback[5] = &USBHAL::EP3_IN_callback; - instance = this; - - /* Configure USB DM pin. This is optional, and maintained only for user guidance. */ - __HAL_RCC_GPIOA_CLK_ENABLE(); - pin_function(PA_11, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF2_USB)); - pin_function(PA_12, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF2_USB)); - - /* Enable USB Clock */ - __HAL_RCC_USB_CLK_ENABLE(); - - /* Enable SYSCFG Clock */ - __HAL_RCC_SYSCFG_CLK_ENABLE(); - hpcd.State = HAL_PCD_STATE_RESET; - HAL_PCD_Init(&hpcd); - - /* hardcoded size of FIFO according definition*/ - HAL_PCDEx_PMAConfig(&hpcd , 0x00 , PCD_SNG_BUF, 0x30); - HAL_PCDEx_PMAConfig(&hpcd , 0x80 , PCD_SNG_BUF, 0x70); -#if 1 - HAL_PCDEx_PMAConfig(&hpcd , 0x3, PCD_DBL_BUF, 0x018000b0); -#else - HAL_PCDEx_PMAConfig(&hpcd , 0x3, PCD_SNG_BUF, 0x180); -#endif - HAL_PCDEx_PMAConfig(&hpcd , 0x83, PCD_SNG_BUF, 0xb0); - NVIC_SetVector(USBHAL_IRQn,(uint32_t)&_usbisr); - NVIC_SetPriority(USBHAL_IRQn, 1); - HAL_PCD_Start(&hpcd); -} -#endif diff --git a/features/unsupported/USBDevice/USBDevice/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L053C8/USBHAL_STM_TARGET.h b/features/unsupported/USBDevice/USBDevice/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L053C8/USBHAL_STM_TARGET.h deleted file mode 100644 index d06d442af47..00000000000 --- a/features/unsupported/USBDevice/USBDevice/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L053C8/USBHAL_STM_TARGET.h +++ /dev/null @@ -1,18 +0,0 @@ -/* Copyright (c) 2016 mbed.org, MIT License -* -* Permission is hereby granted, free of charge, to any person obtaining a copy of this software -* and associated documentation files (the "Software"), to deal in the Software without -* restriction, including without limitation the rights to use, copy, modify, merge, publish, -* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the -* Software is furnished to do so, subject to the following conditions: -* -* The above copyright notice and this permission notice shall be included in all copies or -* substantial portions of the Software. -* -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING -* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -*/ -#include "USBHAL_STM32L053C8.h" diff --git a/features/unsupported/USBDevice/USBDevice/USBEndpoints.h b/features/unsupported/USBDevice/USBDevice/USBEndpoints.h index b9de9cd7bc3..9da0b572251 100644 --- a/features/unsupported/USBDevice/USBDevice/USBEndpoints.h +++ b/features/unsupported/USBDevice/USBDevice/USBEndpoints.h @@ -45,7 +45,7 @@ typedef enum { #include "USBEndpoints_KL25Z.h" #elif !defined(USB_STM_HAL) && defined(TARGET_STM32F4) #include "USBEndpoints_STM32F4.h" -#elif defined (TARGET_STM32F4) || defined (TARGET_STM32F2) || defined (TARGET_STM32F7) || defined (TARGET_STM32F3) || defined(TARGET_STM32L0) || defined(TARGET_STM32L4) || defined(TARGET_STM32F1) +#elif defined (TARGET_STM32F4) || defined (TARGET_STM32F2) || defined (TARGET_STM32F7) || defined (TARGET_STM32F3) || defined(TARGET_STM32L4) || defined(TARGET_STM32F1) #include "USBEndpoints_STM32.h" #elif defined (TARGET_RZ_A1H) || defined (TARGET_VK_RZ_A1H) #include "USBEndpoints_RZ_A1H.h" diff --git a/features/unsupported/USBDevice/USBDevice/USBHAL_KL25Z.cpp b/features/unsupported/USBDevice/USBDevice/USBHAL_KL25Z.cpp index e44a1247985..853f1cc4331 100644 --- a/features/unsupported/USBDevice/USBDevice/USBHAL_KL25Z.cpp +++ b/features/unsupported/USBDevice/USBDevice/USBHAL_KL25Z.cpp @@ -455,9 +455,6 @@ void USBHAL::usbisr(void) { USB0->ERREN = 0xFF; // enable error interrupt sources USB0->ADDR = 0x00; // set default address - // reset bus for USBDevice layer - busReset(); - return; } diff --git a/features/unsupported/USBDevice/USBDevice/USBHAL_Maxim.cpp b/features/unsupported/USBDevice/USBDevice/USBHAL_Maxim.cpp index 9b2dc4320e2..fe9e5e736ed 100644 --- a/features/unsupported/USBDevice/USBDevice/USBHAL_Maxim.cpp +++ b/features/unsupported/USBDevice/USBDevice/USBHAL_Maxim.cpp @@ -37,10 +37,6 @@ #include "usb_regs.h" #include "clkman_regs.h" -#if defined(TARGET_MAX32625) || defined(TARGET_MAX32630) -#include "pwrman_regs.h" -#endif - #define CONNECT_INTS (MXC_F_USB_DEV_INTEN_BRST | MXC_F_USB_DEV_INTEN_SETUP | MXC_F_USB_DEV_INTEN_EP_IN | MXC_F_USB_DEV_INTEN_EP_OUT | MXC_F_USB_DEV_INTEN_DMA_ERR) USBHAL *USBHAL::instance; @@ -138,7 +134,7 @@ USBHAL::USBHAL(void) // attach IRQ handler and enable interrupts instance = this; - NVIC_SetVector(USB_IRQn, &_usbisr); + NVIC_SetVector(USB_IRQn, (uint32_t)&_usbisr); NVIC_EnableIRQ(USB_IRQn); } diff --git a/features/unsupported/USBDevice/USBHID/USBKeyboard.h b/features/unsupported/USBDevice/USBHID/USBKeyboard.h index d21293568c5..c58ae56f0eb 100644 --- a/features/unsupported/USBDevice/USBHID/USBKeyboard.h +++ b/features/unsupported/USBDevice/USBHID/USBKeyboard.h @@ -22,16 +22,11 @@ #include "USBHID.h" #include "Stream.h" -/* Modifiers, left keys then right keys. */ +/* Modifiers */ enum MODIFIER_KEY { - KEY_CTRL = 0x01, - KEY_SHIFT = 0x02, - KEY_ALT = 0x04, - KEY_LOGO = 0x08, - KEY_RCTRL = 0x10, - KEY_RSHIFT = 0x20, - KEY_RALT = 0x40, - KEY_RLOGO = 0x80, + KEY_CTRL = 1, + KEY_SHIFT = 2, + KEY_ALT = 4, }; diff --git a/features/unsupported/USBDevice/USBSerial/USBCDC.cpp b/features/unsupported/USBDevice/USBSerial/USBCDC.cpp index d6dc16ef2f8..aa55541f376 100644 --- a/features/unsupported/USBDevice/USBSerial/USBCDC.cpp +++ b/features/unsupported/USBDevice/USBSerial/USBCDC.cpp @@ -38,10 +38,6 @@ USBCDC::USBCDC(uint16_t vendor_id, uint16_t product_id, uint16_t product_release USBDevice::connect(connect_blocking); } -void USBCDC::USBCallback_busReset(void) { - terminal_connected = false; -}; - bool USBCDC::USBCallback_request(void) { /* Called in ISR context */ diff --git a/features/unsupported/USBDevice/USBSerial/USBCDC.h b/features/unsupported/USBDevice/USBSerial/USBCDC.h index c41e4252125..33c6b0a024d 100644 --- a/features/unsupported/USBDevice/USBSerial/USBCDC.h +++ b/features/unsupported/USBDevice/USBSerial/USBCDC.h @@ -116,7 +116,6 @@ class USBCDC: public USBDevice { virtual bool USBCallback_request(); virtual void USBCallback_requestCompleted(uint8_t *buf, uint32_t length); virtual bool USBCallback_setConfiguration(uint8_t configuration); - virtual void USBCallback_busReset(void); volatile bool terminal_connected; }; diff --git a/features/unsupported/USBDevice/USBSerial/USBSerial.cpp b/features/unsupported/USBDevice/USBSerial/USBSerial.cpp index e0906f336e7..03e039e63f9 100644 --- a/features/unsupported/USBDevice/USBSerial/USBSerial.cpp +++ b/features/unsupported/USBDevice/USBSerial/USBSerial.cpp @@ -66,7 +66,3 @@ bool USBSerial::EPBULK_OUT_callback() { uint8_t USBSerial::available() { return buf.available(); } - -bool USBSerial::connected() { - return terminal_connected; -} diff --git a/features/unsupported/USBDevice/USBSerial/USBSerial.h b/features/unsupported/USBDevice/USBSerial/USBSerial.h index 825b03caf67..286b5a384d8 100644 --- a/features/unsupported/USBDevice/USBSerial/USBSerial.h +++ b/features/unsupported/USBDevice/USBSerial/USBSerial.h @@ -83,13 +83,6 @@ class USBSerial: public USBCDC, public Stream { */ uint8_t available(); - /** - * Check if the terminal is connected. - * - * @returns connection status - */ - bool connected(); - /** Determine if there is a character available to read * * @returns diff --git a/features/unsupported/USBHost/USBHost/TARGET_STM/TARGET_STM32F7/TARGET_STM32F756xG/TARGET_NUCLEO_F756ZG/USBHALHost_STM_TARGET.h b/features/unsupported/USBHost/USBHost/TARGET_STM/TARGET_STM32F7/TARGET_STM32F756xG/TARGET_NUCLEO_F756ZG/USBHALHost_STM_TARGET.h deleted file mode 100644 index 29d3666cf2b..00000000000 --- a/features/unsupported/USBHost/USBHost/TARGET_STM/TARGET_STM32F7/TARGET_STM32F756xG/TARGET_NUCLEO_F756ZG/USBHALHost_STM_TARGET.h +++ /dev/null @@ -1,18 +0,0 @@ -/* Copyright (c) 2016 mbed.org, MIT License -* -* Permission is hereby granted, free of charge, to any person obtaining a copy of this software -* and associated documentation files (the "Software"), to deal in the Software without -* restriction, including without limitation the rights to use, copy, modify, merge, publish, -* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the -* Software is furnished to do so, subject to the following conditions: -* -* The above copyright notice and this permission notice shall be included in all copies or -* substantial portions of the Software. -* -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING -* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -*/ -#include "USBHALHost_STM_144_64pins.h" diff --git a/features/unsupported/USBHost/USBHost/TARGET_STM/USBEndpoint_STM.cpp b/features/unsupported/USBHost/USBHost/TARGET_STM/USBEndpoint_STM.cpp index a12d60e821e..17aedacf531 100644 --- a/features/unsupported/USBHost/USBHost/TARGET_STM/USBEndpoint_STM.cpp +++ b/features/unsupported/USBHost/USBHost/TARGET_STM/USBEndpoint_STM.cpp @@ -19,17 +19,10 @@ #include "USBEndpoint.h" extern uint32_t HAL_HCD_HC_GetMaxPacket(HCD_HandleTypeDef *hhcd, uint8_t chn_num); extern uint32_t HAL_HCD_HC_GetType(HCD_HandleTypeDef *hhcd, uint8_t chn_num); -extern void HAL_HCD_DisableInt(HCD_HandleTypeDef* hhcd, uint8_t chn_num); -extern void HAL_HCD_EnableInt(HCD_HandleTypeDef* hhcd, uint8_t chn_num); - - void USBEndpoint::init(HCED * hced_, ENDPOINT_TYPE type_, ENDPOINT_DIRECTION dir_, uint32_t size, uint8_t ep_number, HCTD* td_list_[2]) { - HCD_HandleTypeDef *hhcd; - uint32_t *addr; - hced = hced_; type = type_; dir = dir_; @@ -53,14 +46,10 @@ void USBEndpoint::init(HCED * hced_, ENDPOINT_TYPE type_, ENDPOINT_DIRECTION dir td_current = td_list[0]; td_next = td_list[1]; - /* remove potential post pending from previous endpoint */ - ep_queue.get(0); + intf_nb = 0; - hhcd = (HCD_HandleTypeDef*)hced->hhcd; - addr = &((uint32_t *)hhcd->pData)[hced->ch_num]; - *addr = 0; + state = USB_TYPE_IDLE; - speed =false; } void USBEndpoint::setSize(uint32_t size) { @@ -70,16 +59,8 @@ void USBEndpoint::setSize(uint32_t size) void USBEndpoint::setDeviceAddress(uint8_t addr) { - HCD_HandleTypeDef *hhcd; - uint8_t hcd_speed = HCD_SPEED_FULL; - /* fix me : small speed device with hub not supported - if (this->speed) hcd_speed = HCD_SPEED_LOW; */ - if (this->speed) { - USB_WARN("small speed device on hub not supported"); - } - MBED_ASSERT(HAL_HCD_HC_Init((HCD_HandleTypeDef*)hced->hhcd,hced->ch_num, address, addr, hcd_speed, type, size)!=HAL_BUSY); this->device_address = addr; - + HAL_HCD_HC_Init((HCD_HandleTypeDef*)hced->hhcd,hced->ch_num, address, addr, HCD_SPEED_FULL, type, size); } void USBEndpoint::setSpeed(uint8_t speed) @@ -89,43 +70,19 @@ void USBEndpoint::setSpeed(uint8_t speed) -void USBEndpoint::setState(USB_TYPE st) -{ - /* modify this state is possible only with a plug */ - if (state == USB_TYPE_FREE) { +void USBEndpoint::setState(uint8_t st) { + if (st > 18) return; - } - - state = st; - if (st == USB_TYPE_FREE) { - HCD_HandleTypeDef *hhcd = (HCD_HandleTypeDef*)hced->hhcd; - uint32_t *addr = &((uint32_t *)hhcd->pData)[hced->ch_num]; - if ((*addr) && (type != INTERRUPT_ENDPOINT)) { - this->ep_queue.put((uint8_t*)1); - } - MBED_ASSERT(HAL_HCD_HC_Halt((HCD_HandleTypeDef*)hced->hhcd, hced->ch_num)!=HAL_BUSY); - HAL_HCD_DisableInt((HCD_HandleTypeDef*)hced->hhcd, hced->ch_num); - *addr = 0; + if (state == USB_TYPE_FREE) HAL_HCD_HC_Halt((HCD_HandleTypeDef*)hced->hhcd, hced->ch_num); - } - if (st == USB_TYPE_ERROR) { - MBED_ASSERT(HAL_HCD_HC_Halt((HCD_HandleTypeDef*)hced->hhcd, hced->ch_num)!=HAL_BUSY); - HAL_HCD_DisableInt((HCD_HandleTypeDef*)hced->hhcd, hced->ch_num); - - } - if (st == USB_TYPE_ERROR) { - uint8_t hcd_speed = HCD_SPEED_FULL; - /* small speed device with hub not supported - if (this->speed) hcd_speed = HCD_SPEED_LOW;*/ - MBED_ASSERT(HAL_HCD_HC_Init((HCD_HandleTypeDef*)hced->hhcd,hced->ch_num, address, 0, hcd_speed, type, size)!=HAL_BUSY); - } + state = (USB_TYPE)st; } extern uint32_t HAL_HCD_HC_GetMaxPacket(HCD_HandleTypeDef *hhcd, uint8_t chn_num); extern uint32_t HAL_HCD_HC_GetType(HCD_HandleTypeDef *hhcd, uint8_t chn_num); - + USB_TYPE USBEndpoint::queueTransfer() { HCD_HandleTypeDef *hhcd = (HCD_HandleTypeDef*)hced->hhcd; @@ -133,38 +90,38 @@ USB_TYPE USBEndpoint::queueTransfer() uint32_t type = HAL_HCD_HC_GetType(hhcd, hced->ch_num); uint32_t max_size = HAL_HCD_HC_GetMaxPacket(hhcd, hced->ch_num); /* if a packet is queue on disconnected ; no solution for now */ - if (state == USB_TYPE_FREE) { - td_current->state = USB_TYPE_FREE; - return USB_TYPE_FREE; + if(*addr == (uint32_t) -1) { + /* set td as disconnected */ + td_current->state = USB_TYPE_DISCONNECTED; + return USB_TYPE_DISCONNECTED; } - ep_queue.get(0); MBED_ASSERT(*addr ==0); - transfer_len = td_current->size <= max_size ? td_current->size : max_size; + if ((type == EP_TYPE_BULK) || (type== EP_TYPE_CTRL)) { + transfer_len = td_current->size <= max_size ? td_current->size : max_size; + transferred = td_current->size; + } else { + transfer_len = td_current->size; + transferred = td_current->size; + MBED_ASSERT(transferred <= (int)max_size); + } buf_start = (uint8_t *)td_current->currBufPtr; //Now add this free TD at this end of the queue state = USB_TYPE_PROCESSING; /* one request */ td_current->nextTD = (hcTd*)0; -#if defined(MAX_NYET_RETRY) - td_current->retry = 0; -#endif - td_current->setup = setup; + *addr = (uint32_t)td_current; /* dir /setup is inverted for ST */ /* token is useful only ctrl endpoint */ /* last parameter is ping ? */ MBED_ASSERT(HAL_HCD_HC_SubmitRequest((HCD_HandleTypeDef*)hced->hhcd, hced->ch_num, dir-1, type,!setup,(uint8_t*) td_current->currBufPtr, transfer_len, 0)==HAL_OK); - HAL_HCD_EnableInt((HCD_HandleTypeDef*)hced->hhcd, hced->ch_num); - return USB_TYPE_PROCESSING; } void USBEndpoint::unqueueTransfer(volatile HCTD * td) { - if (state==USB_TYPE_FREE) { - return; - } + uint32_t *addr = &((uint32_t *)((HCD_HandleTypeDef*)hced->hhcd)->pData)[hced->ch_num]; td->state=0; td->currBufPtr=0; diff --git a/features/unsupported/USBHost/USBHost/TARGET_STM/USBHALHost_STM.cpp b/features/unsupported/USBHost/USBHost/TARGET_STM/USBHALHost_STM.cpp index 012889e1b1d..4a8c333cec0 100644 --- a/features/unsupported/USBHost/USBHost/TARGET_STM/USBHALHost_STM.cpp +++ b/features/unsupported/USBHost/USBHost/TARGET_STM/USBHALHost_STM.cpp @@ -26,44 +26,52 @@ void HAL_HCD_Connect_Callback(HCD_HandleTypeDef *hhcd) { USBHALHost_Private_t *priv=(USBHALHost_Private_t *)(hhcd->pData); USBHALHost *obj= priv->inst; + int i; void (USBHALHost::*func)(int hub, int port, bool lowSpeed, USBHostHub * hub_parent ) = priv->deviceConnected; - (obj->*func)(0,1,0,NULL); + for (i=0; iaddr[i]==(uint32_t)-1)priv->addr[i]=0; + (obj->*func)(0,1,1,NULL); } void HAL_HCD_Disconnect_Callback(HCD_HandleTypeDef *hhcd) { USBHALHost_Private_t *priv=(USBHALHost_Private_t *)(hhcd->pData); USBHALHost *obj= priv->inst; void (USBHALHost::*func1)(int hub, int port, USBHostHub * hub_parent, volatile uint32_t addr)= priv->deviceDisconnected; + void (USBHALHost::*func2)(volatile uint32_t addr)= priv->transferCompleted; + int i; (obj->*func1)(0,1,(USBHostHub *)NULL,0); + + /* fix me call with same frame number */ + /* all on going transaction must end and any new one must be rejected */ + for (i=0; iaddr[i]; + priv->addr[i]=(uint32_t)-1; + if ((addr!=(uint32_t)-1)&& (addr!=0)){ + HCTD *td = (HCTD *)addr; + td->currBufPtr +=HAL_HCD_HC_GetXferCount(hhcd, i); + td->state = USB_TYPE_DISCONNECTED; + (obj->*func2)(addr); + } + } + for (i=1; i< MAX_ENDPOINT;i++)HAL_HCD_HC_Halt(hhcd,i); } int HAL_HCD_HC_GetDirection(HCD_HandleTypeDef *hhcd,uint8_t chnum) { - /* useful for transmission */ - return hhcd->hc[chnum].ep_is_in; +/* useful for transmission */ + return hhcd->hc[chnum].ep_is_in; } uint32_t HAL_HCD_HC_GetMaxPacket(HCD_HandleTypeDef *hhcd,uint8_t chnum) { - /* useful for transmission */ - return hhcd->hc[chnum].max_packet; -} - -void HAL_HCD_EnableInt(HCD_HandleTypeDef *hhcd,uint8_t chnum) -{ - USB_OTG_GlobalTypeDef *USBx = hhcd->Instance; - USBx_HOST->HAINTMSK |= (1 << chnum); +/* useful for transmission */ + return hhcd->hc[chnum].max_packet; } -void HAL_HCD_DisableInt(HCD_HandleTypeDef *hhcd,uint8_t chnum) -{ - USB_OTG_GlobalTypeDef *USBx = hhcd->Instance; - USBx_HOST->HAINTMSK &= ~(1 << chnum); -} uint32_t HAL_HCD_HC_GetType(HCD_HandleTypeDef *hhcd,uint8_t chnum) { - /* useful for transmission */ - return hhcd->hc[chnum].ep_type; +/* useful for transmission */ + return hhcd->hc[chnum].ep_type; } void HAL_HCD_HC_NotifyURBChange_Callback(HCD_HandleTypeDef *hhcd,uint8_t chnum, HCD_URBStateTypeDef urb_state) @@ -71,158 +79,105 @@ void HAL_HCD_HC_NotifyURBChange_Callback(HCD_HandleTypeDef *hhcd,uint8_t chnum, USBHALHost_Private_t *priv=(USBHALHost_Private_t *)(hhcd->pData); USBHALHost *obj= priv->inst; void (USBHALHost::*func)(volatile uint32_t addr)= priv->transferCompleted; - uint32_t addr = priv->addr[chnum]; uint32_t max_size = HAL_HCD_HC_GetMaxPacket(hhcd, chnum); uint32_t type = HAL_HCD_HC_GetType(hhcd, chnum); uint32_t dir = HAL_HCD_HC_GetDirection(hhcd,chnum); uint32_t length; - if ( (addr!=0)) { + if ((addr!=(uint32_t)-1) && (addr!=0)) { HCTD *td = (HCTD *)addr; - - if ((type == EP_TYPE_BULK) || (type == EP_TYPE_CTRL )) { - switch (urb_state) { - case URB_DONE: -#if defined(MAX_NYET_RETRY) - td->retry = 0; -#endif - if (td->size > max_size) { - /* enqueue another request */ - td->currBufPtr += max_size; - td->size -= max_size; - length = td->size <= max_size ? td->size : max_size; - MBED_ASSERT(HAL_HCD_HC_SubmitRequest(hhcd, chnum, dir ,type , !td->setup,(uint8_t*) td->currBufPtr, length, 0)==HAL_OK); - HAL_HCD_EnableInt(hhcd, chnum); - return; - } - break; - case URB_NOTREADY: - /* try again */ - /* abritary limit , to avoid dead lock if other error than - * slow response is */ -#if defined(MAX_NYET_RETRY) - if (td->retry < MAX_NYET_RETRY) { - /* increment retry counter */ - td->retry++; -#endif - length = td->size <= max_size ? td->size : max_size; - MBED_ASSERT(HAL_HCD_HC_SubmitRequest(hhcd, chnum, dir ,type , !td->setup,(uint8_t*) td->currBufPtr, length, 0)==HAL_OK); - HAL_HCD_EnableInt(hhcd, chnum); - return; -#if defined(MAX_NYET_RETRY) - } else { - USB_ERR("urb_state != URB_NOTREADY"); - } -#endif - break; - } + /* put the state */ + if ((urb_state == URB_IDLE) && (type == EP_TYPE_INTR) ) { + length = td->size; + MBED_ASSERT(HAL_HCD_HC_SubmitRequest(hhcd, chnum, dir ,type , 1,(uint8_t*) td->currBufPtr, length, 0)==HAL_OK); + return; } - if ((type == EP_TYPE_INTR) ) { - /* reply a packet of length NULL, this will be analyse in call back - * for mouse or hub */ - td->state =USB_TYPE_IDLE ; - HAL_HCD_DisableInt(hhcd, chnum); - + td->state = (urb_state == URB_DONE) ? USB_TYPE_IDLE : USB_TYPE_ERROR; + if (urb_state == URB_NOTREADY) + USB_ERR("urb_state != URB_NOTREADY"); + /* move buffer pointer , for size */ + if ((type != EP_TYPE_BULK) && (type != EP_TYPE_CTRL )) { + /* in packet */ } else { - td->state = (urb_state == URB_DONE) ? USB_TYPE_IDLE : USB_TYPE_ERROR; + if (urb_state == URB_DONE) { + if (td->size > max_size) { + /* enqueue another request */ + td->currBufPtr += max_size; + td->size -= max_size; + length = td->size <= max_size ? td->size : max_size; + MBED_ASSERT(HAL_HCD_HC_SubmitRequest(hhcd, chnum, dir ,type , 1,(uint8_t*) td->currBufPtr, length, 0)==HAL_OK); + return; + } + } } + td->state = (urb_state == URB_DONE) ? USB_TYPE_IDLE : USB_TYPE_ERROR; td->currBufPtr +=HAL_HCD_HC_GetXferCount(hhcd, chnum); + priv->addr[chnum]=0; (obj->*func)(addr); - } else { - if (urb_state !=0) { - USB_DBG_EVENT("spurious %d %d",chnum, urb_state); - } + } + else + { + USB_DBG_EVENT("spurious %d %d",chnum, urb_state); } } - USBHALHost * USBHALHost::instHost; -void USBHALHost::init() -{ +void USBHALHost::init() { NVIC_DisableIRQ(USBHAL_IRQn); NVIC_SetVector(USBHAL_IRQn, (uint32_t)(_usbisr)); HAL_HCD_Init((HCD_HandleTypeDef *) usb_hcca); NVIC_EnableIRQ(USBHAL_IRQn); - control_disable = 0; HAL_HCD_Start((HCD_HandleTypeDef *) usb_hcca); usb_vbus(1); } -uint32_t USBHALHost::controlHeadED() -{ +uint32_t USBHALHost::controlHeadED() { return 0xffffffff; } -uint32_t USBHALHost::bulkHeadED() -{ - return 0xffffffff; +uint32_t USBHALHost::bulkHeadED() { + return 0xffffffff; } -uint32_t USBHALHost::interruptHeadED() -{ - return 0xffffffff; +uint32_t USBHALHost::interruptHeadED() { + return 0xffffffff; } -void USBHALHost::updateBulkHeadED(uint32_t addr) -{ +void USBHALHost::updateBulkHeadED(uint32_t addr) { } -void USBHALHost::updateControlHeadED(uint32_t addr) -{ +void USBHALHost::updateControlHeadED(uint32_t addr) { } -void USBHALHost::updateInterruptHeadED(uint32_t addr) -{ +void USBHALHost::updateInterruptHeadED(uint32_t addr) { } -void USBHALHost::enableList(ENDPOINT_TYPE type) -{ - /* react when the 3 lists are requested to be disabled */ - if (type == CONTROL_ENDPOINT) { - control_disable--; - if (control_disable == 0) { - NVIC_EnableIRQ(USBHAL_IRQn); - } else { - printf("reent\n"); - } - } +void USBHALHost::enableList(ENDPOINT_TYPE type) { } -bool USBHALHost::disableList(ENDPOINT_TYPE type) -{ - if (type == CONTROL_ENDPOINT) { - NVIC_DisableIRQ(USBHAL_IRQn); - control_disable++; - if (control_disable > 1) { - printf("disable reentrance !!!\n"); - } - return true; - } - return false; +bool USBHALHost::disableList(ENDPOINT_TYPE type) { + return true; } -void USBHALHost::memInit() -{ - usb_hcca = (volatile HCD_HandleTypeDef *)usb_buf; +void USBHALHost::memInit() { + usb_hcca = (volatile HCD_HandleTypeDef *)usb_buf; usb_edBuf = usb_buf + HCCA_SIZE; usb_tdBuf = usb_buf + HCCA_SIZE +(MAX_ENDPOINT*ED_SIZE); - /* init channel */ - memset((void*)usb_buf,0, TOTAL_SIZE); - for (int i=0; i < MAX_ENDPOINT; i++) { - HCED *hced = (HCED*)(usb_edBuf + i*ED_SIZE); - hced->ch_num = i; - hced->hhcd = (HCCA *) usb_hcca; - } + /* init channel */ + for (int i=0; i < MAX_ENDPOINT; i++) { + HCED *hced = (HCED*)(usb_edBuf + i*ED_SIZE); + hced->ch_num = i; + hced->hhcd = (HCCA *) usb_hcca; + } } -volatile uint8_t * USBHALHost::getED() -{ +volatile uint8_t * USBHALHost::getED() { for (int i = 0; i < MAX_ENDPOINT; i++) { if ( !edBufAlloc[i] ) { edBufAlloc[i] = true; @@ -233,8 +188,7 @@ volatile uint8_t * USBHALHost::getED() return NULL; //Could not alloc ED } -volatile uint8_t * USBHALHost::getTD() -{ +volatile uint8_t * USBHALHost::getTD() { int i; for (i = 0; i < MAX_TD; i++) { if ( !tdBufAlloc[i] ) { @@ -247,38 +201,33 @@ volatile uint8_t * USBHALHost::getTD() } -void USBHALHost::freeED(volatile uint8_t * ed) -{ +void USBHALHost::freeED(volatile uint8_t * ed) { int i; i = (ed - usb_edBuf) / ED_SIZE; edBufAlloc[i] = false; } -void USBHALHost::freeTD(volatile uint8_t * td) -{ +void USBHALHost::freeTD(volatile uint8_t * td) { int i; i = (td - usb_tdBuf) / TD_SIZE; tdBufAlloc[i] = false; } -void USBHALHost::resetRootHub() -{ +void USBHALHost::resetRootHub() { // Initiate port reset wait(0.2); HAL_HCD_ResetPort((HCD_HandleTypeDef *)usb_hcca); } -void USBHALHost::_usbisr(void) -{ +void USBHALHost::_usbisr(void) { if (instHost) { instHost->UsbIrqhandler(); } } -void USBHALHost::UsbIrqhandler() -{ +void USBHALHost::UsbIrqhandler() { HAL_HCD_IRQHandler((HCD_HandleTypeDef *)usb_hcca); } #endif diff --git a/features/unsupported/USBHost/USBHost/USBEndpoint.h b/features/unsupported/USBHost/USBHost/USBEndpoint.h index 5b1287f4215..5517944adb4 100644 --- a/features/unsupported/USBHost/USBHost/USBEndpoint.h +++ b/features/unsupported/USBHost/USBHost/USBEndpoint.h @@ -33,9 +33,6 @@ class USBEndpoint * Constructor */ USBEndpoint() { -#ifdef USBHOST_OTHER - speed = false; -#endif state = USB_TYPE_FREE; nextEp = NULL; }; @@ -114,11 +111,7 @@ class USBEndpoint // setters -#ifdef USBHOST_OTHER - void setState(USB_TYPE st); -#else inline void setState(USB_TYPE st) { state = st; } -#endif void setState(uint8_t st); void setDeviceAddress(uint8_t addr); inline void setLengthTransferred(int len) { transferred = len; }; diff --git a/features/unsupported/USBHost/USBHost/USBHALHost.h b/features/unsupported/USBHost/USBHost/USBHALHost.h index 12f16fc328b..e32969de363 100644 --- a/features/unsupported/USBHost/USBHost/USBHALHost.h +++ b/features/unsupported/USBHost/USBHost/USBHALHost.h @@ -164,10 +164,6 @@ class USBHALHost { bool volatile edBufAlloc[MAX_ENDPOINT]; bool volatile tdBufAlloc[MAX_TD]; -#ifdef USBHOST_OTHER - int control_disable; -#endif - }; #endif diff --git a/features/unsupported/USBHost/USBHost/USBHost.cpp b/features/unsupported/USBHost/USBHost/USBHost.cpp index b9424f73f1c..a10eb5a59a9 100644 --- a/features/unsupported/USBHost/USBHost/USBHost.cpp +++ b/features/unsupported/USBHost/USBHost/USBHost.cpp @@ -46,8 +46,7 @@ USBHost * USBHost::instHost = NULL; * - when the usb_thread receives the event, it: * - call the callback attached to the endpoint where the td is attached */ -void USBHost::usb_process() -{ +void USBHost::usb_process() { bool controlListState; bool bulkListState; @@ -80,130 +79,110 @@ void USBHost::usb_process() too_many_hub = false; buf[4] = 0; - do { - Lock lock(this); - bool hub_unplugged = true; - - int idx = findDevice(usb_msg->hub, usb_msg->port, (USBHostHub *)(usb_msg->hub_parent)); - /* check that hub is connected to root port */ - if (usb_msg->hub_parent) { - /* a hub device must be present */ - for (k = 0; k < MAX_HUB_NB; k++) { - if ((&hubs[k] == usb_msg->hub_parent) && (hub_in_use[k])) { - hub_unplugged=false; - } - } - } else { - hub_unplugged = false; - } - - if (((idx!=-1) && deviceInUse[idx] ) || ((idx == -1) && hub_unplugged)) { - break; - } - - for (i =0 ; i < MAX_DEVICE_CONNECTED; i++) { - if (!deviceInUse[i]) { - USB_DBG_EVENT("new device connected: %p\r\n", &devices[i]); - devices[i].init(usb_msg->hub, usb_msg->port, usb_msg->lowSpeed); - deviceReset[i] = false; - deviceInited[i] = true; - break; - } - } - - if (i == MAX_DEVICE_CONNECTED) { - USB_ERR("Too many device connected!!\r\n"); - continue; - } - - if (!controlEndpointAllocated) { - control = newEndpoint(CONTROL_ENDPOINT, OUT, 0x08, 0x00); - addEndpoint(NULL, 0, (USBEndpoint*)control); - controlEndpointAllocated = true; - } - -#if MAX_HUB_NB - if (usb_msg->hub_parent) { - devices[i].setHubParent((USBHostHub *)(usb_msg->hub_parent)); - } -#endif - - for (j = 0; j < timeout_set_addr; j++) { - - resetDevice(&devices[i]); - - // set size of control endpoint - devices[i].setSizeControlEndpoint(8); - - devices[i].activeAddress(false); - - // get first 8 bit of device descriptor - // and check if we deal with a hub - USB_DBG("usb_thread read device descriptor on dev: %p\r\n", &devices[i]); - res = getDeviceDescriptor(&devices[i], buf, 8); - - if (res != USB_TYPE_OK) { - USB_ERR("usb_thread could not read dev descr"); - continue; - } - - // set size of control endpoint - devices[i].setSizeControlEndpoint(buf[7]); - - // second step: set an address to the device - res = setAddress(&devices[i], devices[i].getAddress()); - - if (res != USB_TYPE_OK) { - USB_ERR("SET ADDR FAILED"); - continue; - } - devices[i].activeAddress(true); - USB_DBG("Address of %p: %d", &devices[i], devices[i].getAddress()); - - // try to read again the device descriptor to check if the device - // answers to its new address - res = getDeviceDescriptor(&devices[i], buf, 8); - - if (res == USB_TYPE_OK) { - break; - } - - Thread::wait(100); - } - - USB_INFO("New device connected: %p [hub: %d - port: %d]", &devices[i], usb_msg->hub, usb_msg->port); - -#if MAX_HUB_NB - if (buf[4] == HUB_CLASS) { - for (k = 0; k < MAX_HUB_NB; k++) { - if (hub_in_use[k] == false) { - for (uint8_t j = 0; j < MAX_TRY_ENUMERATE_HUB; j++) { - if (hubs[k].connect(&devices[i])) { - devices[i].hub = &hubs[k]; - hub_in_use[k] = true; - break; - } - } - if (hub_in_use[k] == true) { - break; - } - } - } - - if (k == MAX_HUB_NB) { - USB_ERR("Too many hubs connected!!\r\n"); - too_many_hub = true; - } - } - - if (usb_msg->hub_parent) { - ((USBHostHub *)(usb_msg->hub_parent))->deviceConnected(&devices[i]); - } -#endif - - if ((i < MAX_DEVICE_CONNECTED) && !too_many_hub) { - deviceInUse[i] = true; - } + do + { + Lock lock(this); + + for (i = 0; i < MAX_DEVICE_CONNECTED; i++) { + if (!deviceInUse[i]) { + USB_DBG_EVENT("new device connected: %p\r\n", &devices[i]); + devices[i].init(usb_msg->hub, usb_msg->port, usb_msg->lowSpeed); + deviceReset[i] = false; + deviceInited[i] = true; + break; + } + } + + if (i == MAX_DEVICE_CONNECTED) { + USB_ERR("Too many device connected!!\r\n"); + continue; + } + + if (!controlEndpointAllocated) { + control = newEndpoint(CONTROL_ENDPOINT, OUT, 0x08, 0x00); + addEndpoint(NULL, 0, (USBEndpoint*)control); + controlEndpointAllocated = true; + } + + #if MAX_HUB_NB + if (usb_msg->hub_parent) + devices[i].setHubParent((USBHostHub *)(usb_msg->hub_parent)); + #endif + + for (j = 0; j < timeout_set_addr; j++) { + + resetDevice(&devices[i]); + + // set size of control endpoint + devices[i].setSizeControlEndpoint(8); + + devices[i].activeAddress(false); + + // get first 8 bit of device descriptor + // and check if we deal with a hub + USB_DBG("usb_thread read device descriptor on dev: %p\r\n", &devices[i]); + res = getDeviceDescriptor(&devices[i], buf, 8); + + if (res != USB_TYPE_OK) { + USB_ERR("usb_thread could not read dev descr"); + continue; + } + + // set size of control endpoint + devices[i].setSizeControlEndpoint(buf[7]); + + // second step: set an address to the device + res = setAddress(&devices[i], devices[i].getAddress()); + + if (res != USB_TYPE_OK) { + USB_ERR("SET ADDR FAILED"); + continue; + } + devices[i].activeAddress(true); + USB_DBG("Address of %p: %d", &devices[i], devices[i].getAddress()); + + // try to read again the device descriptor to check if the device + // answers to its new address + res = getDeviceDescriptor(&devices[i], buf, 8); + + if (res == USB_TYPE_OK) { + break; + } + + Thread::wait(100); + } + + USB_INFO("New device connected: %p [hub: %d - port: %d]", &devices[i], usb_msg->hub, usb_msg->port); + + #if MAX_HUB_NB + if (buf[4] == HUB_CLASS) { + for (k = 0; k < MAX_HUB_NB; k++) { + if (hub_in_use[k] == false) { + for (uint8_t j = 0; j < MAX_TRY_ENUMERATE_HUB; j++) { + if (hubs[k].connect(&devices[i])) { + devices[i].hub = &hubs[k]; + hub_in_use[k] = true; + break; + } + } + if (hub_in_use[k] == true) + break; + } + } + + if (k == MAX_HUB_NB) { + USB_ERR("Too many hubs connected!!\r\n"); + too_many_hub = true; + } + } + + if (usb_msg->hub_parent) + ((USBHostHub *)(usb_msg->hub_parent))->deviceConnected(&devices[i]); + #endif + + if ((i < MAX_DEVICE_CONNECTED) && !too_many_hub) { + deviceInUse[i] = true; + } } while(0); @@ -212,28 +191,22 @@ void USBHost::usb_process() // a device has been disconnected case DEVICE_DISCONNECTED_EVENT: - do { - Lock lock(this); + do + { + Lock lock(this); - controlListState = disableList(CONTROL_ENDPOINT); - bulkListState = disableList(BULK_ENDPOINT); - interruptListState = disableList(INTERRUPT_ENDPOINT); + controlListState = disableList(CONTROL_ENDPOINT); + bulkListState = disableList(BULK_ENDPOINT); + interruptListState = disableList(INTERRUPT_ENDPOINT); - idx = findDevice(usb_msg->hub, usb_msg->port, (USBHostHub *)(usb_msg->hub_parent)); - if (idx != -1) { - freeDevice((USBDeviceConnected*)&devices[idx]); - deviceInited[idx]=false; - } + idx = findDevice(usb_msg->hub, usb_msg->port, (USBHostHub *)(usb_msg->hub_parent)); + if (idx != -1) { + freeDevice((USBDeviceConnected*)&devices[idx]); + } - if (controlListState) { - enableList(CONTROL_ENDPOINT); - } - if (bulkListState) { - enableList(BULK_ENDPOINT); - } - if (interruptListState) { - enableList(INTERRUPT_ENDPOINT); - } + if (controlListState) enableList(CONTROL_ENDPOINT); + if (bulkListState) enableList(BULK_ENDPOINT); + if (interruptListState) enableList(INTERRUPT_ENDPOINT); } while(0); @@ -251,9 +224,8 @@ void USBHost::usb_process() if (ep->getDir() == IN) { buf_transfer = ep->getBufStart(); printf("READ SUCCESS [%d bytes transferred - td: 0x%08X] on ep: [%p - addr: %02X]: ", ep->getLengthTransferred(), usb_msg->td_addr, ep, ep->getAddress()); - for (int i = 0; i < ep->getLengthTransferred(); i++) { + for (int i = 0; i < ep->getLengthTransferred(); i++) printf("%02X ", buf_transfer[i]); - } printf("\r\n\r\n"); } #endif @@ -264,12 +236,6 @@ void USBHost::usb_process() if (deviceInUse[idx]) { USB_WARN("td %p processed but not in idle state: %s [ep: %p - dev: %p - %s]", usb_msg->td_addr, ep->getStateString(), ep, ep->dev, ep->dev->getName(ep->getIntfNb())); ep->setState(USB_TYPE_IDLE); - /* as error, on interrupt endpoint can be - * reported, call the call back registered , - * if device still in use, this call back - * shall ask again an interrupt request. - */ - ep->call(); } } } @@ -300,9 +266,8 @@ USBHost::USBHost() : usbThread(osPriorityNormal, USB_THREAD_STACK) devices[i].setAddress(i + 1); deviceReset[i] = false; deviceInited[i] = false; - for (uint8_t j = 0; j < MAX_INTF; j++) { + for (uint8_t j = 0; j < MAX_INTF; j++) deviceAttachedDriver[i][j] = false; - } } #if MAX_HUB_NB @@ -317,21 +282,20 @@ USBHost::USBHost() : usbThread(osPriorityNormal, USB_THREAD_STACK) USBHost::Lock::Lock(USBHost* pHost) : m_pHost(pHost) { - m_pHost->usb_mutex.lock(); + m_pHost->usb_mutex.lock(); } USBHost::Lock::~Lock() { - m_pHost->usb_mutex.unlock(); + m_pHost->usb_mutex.unlock(); } void USBHost::transferCompleted(volatile uint32_t addr) { uint8_t state; - if(addr == 0) { + if(addr == 0) return; - } volatile HCTD* tdList = NULL; @@ -351,23 +315,20 @@ void USBHost::transferCompleted(volatile uint32_t addr) #ifdef USBHOST_OTHER state = ((HCTD *)td)->state; - if (state == USB_TYPE_IDLE) { + if (state == USB_TYPE_IDLE) ep->setLengthTransferred((uint32_t)td->currBufPtr - (uint32_t)ep->getBufStart()); - } #else if (((HCTD *)td)->control >> 28) { state = ((HCTD *)td)->control >> 28; } else { - if (td->currBufPtr) { + if (td->currBufPtr) ep->setLengthTransferred((uint32_t)td->currBufPtr - (uint32_t)ep->getBufStart()); - } state = 16 /*USB_TYPE_IDLE*/; } #endif - if (state == USB_TYPE_IDLE) { + if (state == USB_TYPE_IDLE) ep->setLengthTransferred((uint32_t)td->currBufPtr - (uint32_t)ep->getBufStart()); - } ep->unqueueTransfer(td); @@ -379,7 +340,7 @@ void USBHost::transferCompleted(volatile uint32_t addr) usb_msg->td_state = state; mail_usb_event.put(usb_msg); } - ep->setState((USB_TYPE)state); + ep->setState(state); ep->ep_queue.put((uint8_t*)1); } } @@ -404,9 +365,8 @@ USBHost * USBHost::getHostInst() // be sure that the new device connected is not already connected... int idx = findDevice(hub, port, hub_parent); if (idx != -1) { - if (deviceInited[idx]) { + if (deviceInited[idx]) return; - } } message_t * usb_msg = mail_usb_event.alloc(); @@ -427,9 +387,8 @@ USBHost * USBHost::getHostInst() // be sure that the device disconnected is connected... int idx = findDevice(hub, port, hub_parent); if (idx != -1) { - if (!deviceInUse[idx]) { + if (!deviceInUse[idx]) return; - } } else { return; } @@ -463,9 +422,8 @@ void USBHost::freeDevice(USBDeviceConnected * dev) } // notify hub parent that this device has been disconnected - if (dev->getHubParent()) { + if (dev->getHubParent()) dev->getHubParent()->deviceDisconnected(dev); - } #endif @@ -709,9 +667,8 @@ int USBHost::findDevice(uint8_t hub, uint8_t port, USBHostHub * hub_parent) for (int i = 0; i < MAX_DEVICE_CONNECTED; i++) { if (devices[i].getHub() == hub && devices[i].getPort() == port) { if (hub_parent != NULL) { - if (hub_parent == devices[i].getHubParent()) { + if (hub_parent == devices[i].getHubParent()) return i; - } } else { return i; } @@ -738,14 +695,14 @@ void USBHost::printList(ENDPOINT_TYPE type) volatile HCTD * hctd = NULL; const char * type_str = (type == BULK_ENDPOINT) ? "BULK" : ((type == INTERRUPT_ENDPOINT) ? "INTERRUPT" : - ((type == CONTROL_ENDPOINT) ? "CONTROL" : "ISOCHRONOUS")); + ((type == CONTROL_ENDPOINT) ? "CONTROL" : "ISOCHRONOUS")); printf("State of %s:\r\n", type_str); while (hced != NULL) { uint8_t dir = ((hced->control & (3 << 11)) >> 11); printf("hced: %p [ADDR: %d, DIR: %s, EP_NB: 0x%X]\r\n", hced, - hced->control & 0x7f, - (dir == 1) ? "OUT" : ((dir == 0) ? "FROM_TD":"IN"), - (hced->control & (0xf << 7)) >> 7); + hced->control & 0x7f, + (dir == 1) ? "OUT" : ((dir == 0) ? "FROM_TD":"IN"), + (hced->control & (0xf << 7)) >> 7); hctd = (HCTD *)((uint32_t)(hced->headTD) & ~(0xf)); while (hctd != hced->tailTD) { printf("\thctd: %p [DIR: %s]\r\n", hctd, ((hctd->control & (3 << 19)) >> 19) == 1 ? "OUT" : "IN"); @@ -763,7 +720,7 @@ void USBHost::printList(ENDPOINT_TYPE type) USB_TYPE USBHost::addTransfer(USBEndpoint * ed, uint8_t * buf, uint32_t len) { USB_TYPE ret=USB_TYPE_PROCESSING; - td_mutex.lock(); + td_mutex.lock(); // allocate a TD which will be freed in TDcompletion volatile HCTD * td = ed->getNextTD(); @@ -771,7 +728,7 @@ USB_TYPE USBHost::addTransfer(USBEndpoint * ed, uint8_t * buf, uint32_t len) return USB_TYPE_ERROR; } -#ifndef USBHOST_OTHER +#ifndef USBHOST_OTHER uint32_t token = (ed->isSetup() ? TD_SETUP : ( (ed->getDir() == IN) ? TD_IN : TD_OUT )); uint32_t td_toggle; @@ -797,10 +754,10 @@ USB_TYPE USBHost::addTransfer(USBEndpoint * ed, uint8_t * buf, uint32_t len) printList(type); enableList(type); #else - /* call method specific for endpoint */ - td->currBufPtr = buf; - td->size = len; - ret = ed->queueTransfer(); + /* call method specific for endpoint */ + td->currBufPtr = buf; + td->size = len; + ret = ed->queueTransfer(); #endif td_mutex.unlock(); @@ -813,13 +770,12 @@ USB_TYPE USBHost::addTransfer(USBEndpoint * ed, uint8_t * buf, uint32_t len) USB_TYPE USBHost::getDeviceDescriptor(USBDeviceConnected * dev, uint8_t * buf, uint16_t max_len_buf, uint16_t * len_dev_descr) { USB_TYPE t = controlRead( dev, - USB_DEVICE_TO_HOST | USB_RECIPIENT_DEVICE, - GET_DESCRIPTOR, - (DEVICE_DESCRIPTOR << 8) | (0), - 0, buf, MIN(DEVICE_DESCRIPTOR_LENGTH, max_len_buf)); - if (len_dev_descr) { + USB_DEVICE_TO_HOST | USB_RECIPIENT_DEVICE, + GET_DESCRIPTOR, + (DEVICE_DESCRIPTOR << 8) | (0), + 0, buf, MIN(DEVICE_DESCRIPTOR_LENGTH, max_len_buf)); + if (len_dev_descr) *len_dev_descr = MIN(DEVICE_DESCRIPTOR_LENGTH, max_len_buf); - } return t; } @@ -843,9 +799,8 @@ USB_TYPE USBHost::getConfigurationDescriptor(USBDeviceConnected * dev, uint8_t * total_conf_descr_length = buf[2] | (buf[3] << 8); total_conf_descr_length = MIN(max_len_buf, total_conf_descr_length); - if (len_conf_descr) { + if (len_conf_descr) *len_conf_descr = total_conf_descr_length; - } USB_DBG("TOTAL_LENGTH: %d \t NUM_INTERF: %d", total_conf_descr_length, buf[4]); @@ -857,8 +812,7 @@ USB_TYPE USBHost::getConfigurationDescriptor(USBDeviceConnected * dev, uint8_t * } -USB_TYPE USBHost::setAddress(USBDeviceConnected * dev, uint8_t address) -{ +USB_TYPE USBHost::setAddress(USBDeviceConnected * dev, uint8_t address) { return controlWrite( dev, USB_HOST_TO_DEVICE | USB_RECIPIENT_DEVICE, SET_ADDRESS, @@ -876,17 +830,14 @@ USB_TYPE USBHost::setConfiguration(USBDeviceConnected * dev, uint8_t conf) 0, NULL, 0); } -uint8_t USBHost::numberDriverAttached(USBDeviceConnected * dev) -{ +uint8_t USBHost::numberDriverAttached(USBDeviceConnected * dev) { int index = findDevice(dev); uint8_t cnt = 0; - if (index == -1) { + if (index == -1) return 0; - } for (uint8_t i = 0; i < MAX_INTF; i++) { - if (deviceAttachedDriver[index][i]) { + if (deviceAttachedDriver[index][i]) cnt++; - } } return cnt; } @@ -897,76 +848,76 @@ USB_TYPE USBHost::enumerate(USBDeviceConnected * dev, IUSBEnumerator* pEnumerato uint16_t total_conf_descr_length = 0; USB_TYPE res; - do { - Lock lock(this); + do + { + Lock lock(this); - // don't enumerate a device which all interfaces are registered to a specific driver - int index = findDevice(dev); + // don't enumerate a device which all interfaces are registered to a specific driver + int index = findDevice(dev); - if (index == -1) { - return USB_TYPE_ERROR; - } + if (index == -1) { + return USB_TYPE_ERROR; + } - uint8_t nb_intf_attached = numberDriverAttached(dev); - USB_DBG("dev: %p nb_intf: %d", dev, dev->getNbIntf()); - USB_DBG("dev: %p nb_intf_attached: %d", dev, nb_intf_attached); - if ((nb_intf_attached != 0) && (dev->getNbIntf() == nb_intf_attached)) { - USB_DBG("Don't enumerate dev: %p because all intf are registered with a driver", dev); - return USB_TYPE_OK; - } + uint8_t nb_intf_attached = numberDriverAttached(dev); + USB_DBG("dev: %p nb_intf: %d", dev, dev->getNbIntf()); + USB_DBG("dev: %p nb_intf_attached: %d", dev, nb_intf_attached); + if ((nb_intf_attached != 0) && (dev->getNbIntf() == nb_intf_attached)) { + USB_DBG("Don't enumerate dev: %p because all intf are registered with a driver", dev); + return USB_TYPE_OK; + } - USB_DBG("Enumerate dev: %p", dev); + USB_DBG("Enumerate dev: %p", dev); - // third step: get the whole device descriptor to see vid, pid - res = getDeviceDescriptor(dev, data, DEVICE_DESCRIPTOR_LENGTH); + // third step: get the whole device descriptor to see vid, pid + res = getDeviceDescriptor(dev, data, DEVICE_DESCRIPTOR_LENGTH); - if (res != USB_TYPE_OK) { - USB_DBG("GET DEV DESCR FAILED"); - return res; - } + if (res != USB_TYPE_OK) { + USB_DBG("GET DEV DESCR FAILED"); + return res; + } - dev->setClass(data[4]); - dev->setSubClass(data[5]); - dev->setProtocol(data[6]); - dev->setVid(data[8] | (data[9] << 8)); - dev->setPid(data[10] | (data[11] << 8)); - USB_DBG("CLASS: %02X \t VID: %04X \t PID: %04X", data[4], data[8] | (data[9] << 8), data[10] | (data[11] << 8)); + dev->setClass(data[4]); + dev->setSubClass(data[5]); + dev->setProtocol(data[6]); + dev->setVid(data[8] | (data[9] << 8)); + dev->setPid(data[10] | (data[11] << 8)); + USB_DBG("CLASS: %02X \t VID: %04X \t PID: %04X", data[4], data[8] | (data[9] << 8), data[10] | (data[11] << 8)); - pEnumerator->setVidPid( data[8] | (data[9] << 8), data[10] | (data[11] << 8) ); + pEnumerator->setVidPid( data[8] | (data[9] << 8), data[10] | (data[11] << 8) ); - res = getConfigurationDescriptor(dev, data, sizeof(data), &total_conf_descr_length); - if (res != USB_TYPE_OK) { - return res; - } + res = getConfigurationDescriptor(dev, data, sizeof(data), &total_conf_descr_length); + if (res != USB_TYPE_OK) { + return res; + } -#if (DEBUG > 3) - USB_DBG("CONFIGURATION DESCRIPTOR:\r\n"); - for (int i = 0; i < total_conf_descr_length; i++) { - printf("%02X ", data[i]); - } - printf("\r\n\r\n"); -#endif + #if (DEBUG > 3) + USB_DBG("CONFIGURATION DESCRIPTOR:\r\n"); + for (int i = 0; i < total_conf_descr_length; i++) + printf("%02X ", data[i]); + printf("\r\n\r\n"); + #endif - // Parse the configuration descriptor - parseConfDescr(dev, data, total_conf_descr_length, pEnumerator); + // Parse the configuration descriptor + parseConfDescr(dev, data, total_conf_descr_length, pEnumerator); - // only set configuration if not enumerated before - if (!dev->isEnumerated()) { + // only set configuration if not enumerated before + if (!dev->isEnumerated()) { - USB_DBG("Set configuration 1 on dev: %p", dev); - // sixth step: set configuration (only 1 supported) - res = setConfiguration(dev, 1); + USB_DBG("Set configuration 1 on dev: %p", dev); + // sixth step: set configuration (only 1 supported) + res = setConfiguration(dev, 1); - if (res != USB_TYPE_OK) { - USB_DBG("SET CONF FAILED"); - return res; - } - } + if (res != USB_TYPE_OK) { + USB_DBG("SET CONF FAILED"); + return res; + } + } - dev->setEnumerated(); + dev->setEnumerated(); - // Now the device is enumerated! - USB_DBG("dev %p is enumerated\r\n", dev); + // Now the device is enumerated! + USB_DBG("dev %p is enumerated\r\n", dev); } while(0); @@ -1065,8 +1016,7 @@ USB_TYPE USBHost::interruptRead(USBDeviceConnected * dev, USBEndpoint * ep, uint return generalTransfer(dev, ep, buf, len, blocking, INTERRUPT_ENDPOINT, false); } -USB_TYPE USBHost::generalTransfer(USBDeviceConnected * dev, USBEndpoint * ep, uint8_t * buf, uint32_t len, bool blocking, ENDPOINT_TYPE type, bool write) -{ +USB_TYPE USBHost::generalTransfer(USBDeviceConnected * dev, USBEndpoint * ep, uint8_t * buf, uint32_t len, bool blocking, ENDPOINT_TYPE type, bool write) { #if DEBUG_TRANSFER const char * type_str = (type == BULK_ENDPOINT) ? "BULK" : ((type == INTERRUPT_ENDPOINT) ? "INTERRUPT" : "ISOCHRONOUS"); @@ -1106,28 +1056,16 @@ USB_TYPE USBHost::generalTransfer(USBDeviceConnected * dev, USBEndpoint * ep, ui #if DEBUG_TRANSFER if (write) { USB_DBG_TRANSFER("%s WRITE buffer", type_str); - for (int i = 0; i < ep->getLengthTransferred(); i++) { + for (int i = 0; i < ep->getLengthTransferred(); i++) printf("%02X ", buf[i]); - } printf("\r\n\r\n"); } #endif res = addTransfer(ep, buf, len); if ((blocking)&& (res == USB_TYPE_PROCESSING)) { -#ifdef USBHOST_OTHER - osEvent event = ep->ep_queue.get(TD_TIMEOUT); - if (event.status == osEventTimeout) { - /* control endpoint is confusing for merge on b */ - disableList(CONTROL_ENDPOINT); - ep->setState(USB_TYPE_ERROR); - ep->ep_queue.get(0); - ep->unqueueTransfer(ep->getProcessedTD()); - enableList(CONTROL_ENDPOINT); - } -#else + ep->ep_queue.get(); -#endif res = ep->getState(); USB_DBG_TRANSFER("%s TRANSFER res: %s on ep: %p\r\n", type_str, ep->getStateString(), ep); @@ -1144,13 +1082,11 @@ USB_TYPE USBHost::generalTransfer(USBDeviceConnected * dev, USBEndpoint * ep, ui } -USB_TYPE USBHost::controlRead(USBDeviceConnected * dev, uint8_t requestType, uint8_t request, uint32_t value, uint32_t index, uint8_t * buf, uint32_t len) -{ +USB_TYPE USBHost::controlRead(USBDeviceConnected * dev, uint8_t requestType, uint8_t request, uint32_t value, uint32_t index, uint8_t * buf, uint32_t len) { return controlTransfer(dev, requestType, request, value, index, buf, len, false); } -USB_TYPE USBHost::controlWrite(USBDeviceConnected * dev, uint8_t requestType, uint8_t request, uint32_t value, uint32_t index, uint8_t * buf, uint32_t len) -{ +USB_TYPE USBHost::controlWrite(USBDeviceConnected * dev, uint8_t requestType, uint8_t request, uint32_t value, uint32_t index, uint8_t * buf, uint32_t len) { return controlTransfer(dev, requestType, request, value, index, buf, len, true); } @@ -1176,30 +1112,15 @@ USB_TYPE USBHost::controlTransfer(USBDeviceConnected * dev, uint8_t requestType, #if DEBUG_TRANSFER USB_DBG_TRANSFER("SETUP PACKET: "); - for (int i = 0; i < 8; i++) { + for (int i = 0; i < 8; i++) printf("%01X ", setupPacket[i]); - } printf("\r\n"); #endif control->setNextToken(TD_SETUP); res = addTransfer(control, (uint8_t*)setupPacket, 8); - if (res == USB_TYPE_PROCESSING) -#ifdef USBHOST_OTHER - { - osEvent event = control->ep_queue.get(TD_TIMEOUT_CTRL); - if (event.status == osEventTimeout) { - disableList(CONTROL_ENDPOINT); - control->setState(USB_TYPE_ERROR); - control->ep_queue.get(0); - control->unqueueTransfer(control->getProcessedTD()); - enableList(CONTROL_ENDPOINT); - } - } -#else - control->ep_queue.get(); -#endif + if (res == USB_TYPE_PROCESSING) control->ep_queue.get(); res = control->getState(); USB_DBG_TRANSFER("CONTROL setup stage %s", control->getStateString()); @@ -1213,36 +1134,20 @@ USB_TYPE USBHost::controlTransfer(USBDeviceConnected * dev, uint8_t requestType, control->setNextToken(token); res = addTransfer(control, (uint8_t *)buf, length_transfer); - if (res == USB_TYPE_PROCESSING) -#ifdef USBHOST_OTHER - { - osEvent event = control->ep_queue.get(TD_TIMEOUT_CTRL); - if (event.status == osEventTimeout) { - disableList(CONTROL_ENDPOINT); - control->setState(USB_TYPE_ERROR); - control->ep_queue.get(0); - control->unqueueTransfer(control->getProcessedTD()); - enableList(CONTROL_ENDPOINT); - } - } -#else - control->ep_queue.get(); -#endif + if (res == USB_TYPE_PROCESSING) control->ep_queue.get(); res = control->getState(); #if DEBUG_TRANSFER USB_DBG_TRANSFER("CONTROL %s stage %s", (write) ? "WRITE" : "READ", control->getStateString()); if (write) { USB_DBG_TRANSFER("CONTROL WRITE buffer"); - for (int i = 0; i < control->getLengthTransferred(); i++) { + for (int i = 0; i < control->getLengthTransferred(); i++) printf("%02X ", buf[i]); - } printf("\r\n\r\n"); } else { USB_DBG_TRANSFER("CONTROL READ SUCCESS [%d bytes transferred]", control->getLengthTransferred()); - for (int i = 0; i < control->getLengthTransferred(); i++) { + for (int i = 0; i < control->getLengthTransferred(); i++) printf("%02X ", buf[i]); - } printf("\r\n\r\n"); } #endif @@ -1255,28 +1160,14 @@ USB_TYPE USBHost::controlTransfer(USBDeviceConnected * dev, uint8_t requestType, token = (write) ? TD_IN : TD_OUT; control->setNextToken(token); res = addTransfer(control, NULL, 0); - if (res == USB_TYPE_PROCESSING) -#ifdef USBHOST_OTHER - { - osEvent event = control->ep_queue.get(TD_TIMEOUT_CTRL); - if (event.status == osEventTimeout) { - disableList(CONTROL_ENDPOINT); - control->setState(USB_TYPE_ERROR); - control->ep_queue.get(0); - control->unqueueTransfer(control->getProcessedTD()); - enableList(CONTROL_ENDPOINT); - } - } -#else - control->ep_queue.get(); -#endif + + if (res == USB_TYPE_PROCESSING) control->ep_queue.get(); res = control->getState(); USB_DBG_TRANSFER("CONTROL ack stage %s", control->getStateString()); - if (res != USB_TYPE_IDLE) { + if (res != USB_TYPE_IDLE) return res; - } return USB_TYPE_OK; } diff --git a/features/unsupported/USBHost/USBHost/USBHostConf.h b/features/unsupported/USBHost/USBHost/USBHostConf.h index d361f75de31..dba23359362 100644 --- a/features/unsupported/USBHost/USBHost/USBHostConf.h +++ b/features/unsupported/USBHost/USBHost/USBHostConf.h @@ -22,17 +22,17 @@ * to the usb host */ /* hub + 2 devices */ -#define MAX_DEVICE_CONNECTED 5 +#define MAX_DEVICE_CONNECTED 3 /* * Maximum of Hub connected to the usb host */ -#define MAX_HUB_NB 3 +#define MAX_HUB_NB 0 /* * Maximum number of ports on a USB hub */ -#define MAX_HUB_PORT 4 +#define MAX_HUB_PORT 2 /* * Enable USBHostMSD diff --git a/features/unsupported/USBHost/USBHost/USBHostTypes.h b/features/unsupported/USBHost/USBHost/USBHostTypes.h index 527c0693606..b4c68b77de9 100644 --- a/features/unsupported/USBHost/USBHost/USBHostTypes.h +++ b/features/unsupported/USBHost/USBHost/USBHostTypes.h @@ -117,8 +117,6 @@ enum ENDPOINT_TYPE { #else -#define TD_TIMEOUT_CTRL 100 -#define TD_TIMEOUT 2000 #define TD_SETUP (uint32_t)(0) // Direction of Setup Packet #define TD_IN (uint32_t)(0x00100000) // Direction In #define TD_OUT (uint32_t)(0x00080000) // Direction Out @@ -154,13 +152,11 @@ enum ENDPOINT_TYPE { #if defined(USBHOST_OTHER) typedef struct hcTd { - __IO uint32_t state; + __IO uint32_t state; __IO uint8_t * currBufPtr; // Physical address of current buffer pointer __IO hcTd * nextTD; // Physical pointer to next Transfer Descriptor __IO uint32_t size; // size of buffer void * ep; // ep address where a td is linked in - __IO uint32_t retry; - __IO uint32_t setup; } PACKED HCTD; // ----------- HostController EndPoint Descriptor ------------- typedef struct hcEd { diff --git a/features/unsupported/USBHost/USBHostHID/USBHostKeyboard.cpp b/features/unsupported/USBHost/USBHostHID/USBHostKeyboard.cpp index 9c496db728e..dbb2cda53e8 100644 --- a/features/unsupported/USBHost/USBHostHID/USBHostKeyboard.cpp +++ b/features/unsupported/USBHost/USBHostHID/USBHostKeyboard.cpp @@ -19,81 +19,71 @@ #if USBHOST_KEYBOARD static uint8_t keymap[4][0x39] = { - { - 0, 0, 0, 0, 'a', 'b' /*0x05*/, - 'c', 'd', 'e', 'f', 'g' /*0x0a*/, - 'h', 'i', 'j', 'k', 'l'/*0x0f*/, - 'm', 'n', 'o', 'p', 'q'/*0x14*/, - 'r', 's', 't', 'u', 'v'/*0x19*/, - 'w', 'x', 'y', 'z', '1'/*0x1E*/, - '2', '3', '4', '5', '6'/*0x23*/, - '7', '8', '9', '0', 0x0A /*enter*/, /*0x28*/ - 0x1B /*escape*/, 0x08 /*backspace*/, 0x09/*tab*/, 0x20/*space*/, '-', /*0x2d*/ - '=', '[', ']', '\\', '#', /*0x32*/ - ';', '\'', 0, ',', '.', /*0x37*/ - '/' - }, + { 0, 0, 0, 0, 'a', 'b' /*0x05*/, + 'c', 'd', 'e', 'f', 'g' /*0x0a*/, + 'h', 'i', 'j', 'k', 'l'/*0x0f*/, + 'm', 'n', 'o', 'p', 'q'/*0x14*/, + 'r', 's', 't', 'u', 'v'/*0x19*/, + 'w', 'x', 'y', 'z', '1'/*0x1E*/, + '2', '3', '4', '5', '6'/*0x23*/, + '7', '8', '9', '0', 0x0A /*enter*/, /*0x28*/ + 0x1B /*escape*/, 0x08 /*backspace*/, 0x09/*tab*/, 0x20/*space*/, '-', /*0x2d*/ + '=', '[', ']', '\\', '#', /*0x32*/ + ';', '\'', 0, ',', '.', /*0x37*/ + '/'}, /* CTRL MODIFIER */ - { - 0, 0, 0, 0, 0, 0 /*0x05*/, - 0, 0, 0, 0, 0 /*0x0a*/, - 0, 0, 0, 0, 0/*0x0f*/, - 0, 0, 0, 0, 0/*0x14*/, - 0, 0, 0, 0, 0/*0x19*/, - 0, 0, 0, 0, 0/*0x1E*/, - 0, 0, 0, 0, 0/*0x23*/, - 0, 0, 0, 0, 0 /*enter*/, /*0x28*/ - 0, 0, 0, 0, 0, /*0x2d*/ - 0, 0, 0, 0, 0, /*0x32*/ - 0, 0, 0, 0, 0, /*0x37*/ - 0 - }, + { 0, 0, 0, 0, 0, 0 /*0x05*/, + 0, 0, 0, 0, 0 /*0x0a*/, + 0, 0, 0, 0, 0/*0x0f*/, + 0, 0, 0, 0, 0/*0x14*/, + 0, 0, 0, 0, 0/*0x19*/, + 0, 0, 0, 0, 0/*0x1E*/, + 0, 0, 0, 0, 0/*0x23*/, + 0, 0, 0, 0, 0 /*enter*/, /*0x28*/ + 0, 0, 0, 0, 0, /*0x2d*/ + 0, 0, 0, 0, 0, /*0x32*/ + 0, 0, 0, 0, 0, /*0x37*/ + 0}, /* SHIFT MODIFIER */ - { - 0, 0, 0, 0, 'A', 'B' /*0x05*/, - 'C', 'D', 'E', 'F', 'G' /*0x0a*/, - 'H', 'I', 'J', 'K', 'L'/*0x0f*/, - 'M', 'N', 'O', 'P', 'Q'/*0x14*/, - 'R', 'S', 'T', 'U', 'V'/*0x19*/, - 'W', 'X', 'Y', 'Z', '!'/*0x1E*/, - '@', '#', '$', '%', '^'/*0x23*/, - '&', '*', '(', ')', 0, /*0x28*/ - 0, 0, 0, 0, 0, /*0x2d*/ - '+', '{', '}', '|', '~', /*0x32*/ - ':', '"', 0, '<', '>', /*0x37*/ - '?' - }, + { 0, 0, 0, 0, 'A', 'B' /*0x05*/, + 'C', 'D', 'E', 'F', 'G' /*0x0a*/, + 'H', 'I', 'J', 'K', 'L'/*0x0f*/, + 'M', 'N', 'O', 'P', 'Q'/*0x14*/, + 'R', 'S', 'T', 'U', 'V'/*0x19*/, + 'W', 'X', 'Y', 'Z', '!'/*0x1E*/, + '@', '#', '$', '%', '^'/*0x23*/, + '&', '*', '(', ')', 0, /*0x28*/ + 0, 0, 0, 0, 0, /*0x2d*/ + '+', '{', '}', '|', '~', /*0x32*/ + ':', '"', 0, '<', '>', /*0x37*/ + '?'}, /* ALT MODIFIER */ - { - 0, 0, 0, 0, 0, 0 /*0x05*/, - 0, 0, 0, 0, 0 /*0x0a*/, - 0, 0, 0, 0, 0/*0x0f*/, - 0, 0, 0, 0, 0/*0x14*/, - 0, 0, 0, 0, 0/*0x19*/, - 0, 0, 0, 0, 0/*0x1E*/, - 0, 0, 0, 0, 0/*0x23*/, - 0, 0, 0, 0, 0 /*enter*/, /*0x28*/ - 0, 0, 0, 0, 0, /*0x2d*/ - 0, 0, 0, 0, 0, /*0x32*/ - 0, 0, 0, 0, 0, /*0x37*/ - 0 - } + { 0, 0, 0, 0, 0, 0 /*0x05*/, + 0, 0, 0, 0, 0 /*0x0a*/, + 0, 0, 0, 0, 0/*0x0f*/, + 0, 0, 0, 0, 0/*0x14*/, + 0, 0, 0, 0, 0/*0x19*/, + 0, 0, 0, 0, 0/*0x1E*/, + 0, 0, 0, 0, 0/*0x23*/, + 0, 0, 0, 0, 0 /*enter*/, /*0x28*/ + 0, 0, 0, 0, 0, /*0x2d*/ + 0, 0, 0, 0, 0, /*0x32*/ + 0, 0, 0, 0, 0, /*0x37*/ + 0} }; -USBHostKeyboard::USBHostKeyboard() -{ +USBHostKeyboard::USBHostKeyboard() { host = USBHost::getHostInst(); init(); } -void USBHostKeyboard::init() -{ +void USBHostKeyboard::init() { dev = NULL; int_in = NULL; report_id = 0; @@ -104,14 +94,12 @@ void USBHostKeyboard::init() keyboard_device_found = false; } -bool USBHostKeyboard::connected() -{ +bool USBHostKeyboard::connected() { return dev_connected; } -bool USBHostKeyboard::connect() -{ +bool USBHostKeyboard::connect() { if (dev_connected) { return true; @@ -120,29 +108,20 @@ bool USBHostKeyboard::connect() for (uint8_t i = 0; i < MAX_DEVICE_CONNECTED; i++) { if ((dev = host->getDevice(i)) != NULL) { - if (host->enumerate(dev, this)) { + if (host->enumerate(dev, this)) break; - } if (keyboard_device_found) { - { - /* As this is done in a specific thread - * this lock is taken to avoid to process the device - * disconnect in usb process during the device registering */ - USBHost::Lock Lock(host); - - int_in = dev->getEndpoint(keyboard_intf, INTERRUPT_ENDPOINT, IN); + int_in = dev->getEndpoint(keyboard_intf, INTERRUPT_ENDPOINT, IN); - if (!int_in) { - break; - } + if (!int_in) + break; - USB_INFO("New Keyboard device: VID:%04x PID:%04x [dev: %p - intf: %d]", dev->getVid(), dev->getPid(), dev, keyboard_intf); - dev->setName("Keyboard", keyboard_intf); - host->registerDriver(dev, keyboard_intf, this, &USBHostKeyboard::init); + USB_INFO("New Keyboard device: VID:%04x PID:%04x [dev: %p - intf: %d]", dev->getVid(), dev->getPid(), dev, keyboard_intf); + dev->setName("Keyboard", keyboard_intf); + host->registerDriver(dev, keyboard_intf, this, &USBHostKeyboard::init); - int_in->attach(this, &USBHostKeyboard::rxHandler); - } + int_in->attach(this, &USBHostKeyboard::rxHandler); host->interruptRead(dev, int_in, report, int_in->getSize(), false); dev_connected = true; @@ -154,8 +133,7 @@ bool USBHostKeyboard::connect() return false; } -void USBHostKeyboard::rxHandler() -{ +void USBHostKeyboard::rxHandler() { int len = int_in->getLengthTransferred(); int index = (len == 9) ? 1 : 0; int len_listen = int_in->getSize(); @@ -171,9 +149,8 @@ void USBHostKeyboard::rxHandler() (*onKeyCode)(report[index + 2], modifier); } } - if (dev && int_in) { + if (dev && int_in) host->interruptRead(dev, int_in, report, len_listen, false); - } } /*virtual*/ void USBHostKeyboard::setVidPid(uint16_t vid, uint16_t pid) @@ -184,9 +161,9 @@ void USBHostKeyboard::rxHandler() /*virtual*/ bool USBHostKeyboard::parseInterface(uint8_t intf_nb, uint8_t intf_class, uint8_t intf_subclass, uint8_t intf_protocol) //Must return true if the interface should be parsed { if ((keyboard_intf == -1) && - (intf_class == HID_CLASS) && - (intf_subclass == 0x01) && - (intf_protocol == 0x01)) { + (intf_class == HID_CLASS) && + (intf_subclass == 0x01) && + (intf_protocol == 0x01)) { keyboard_intf = intf_nb; return true; } diff --git a/features/unsupported/USBHost/USBHostHID/USBHostKeyboard.h b/features/unsupported/USBHost/USBHostHID/USBHostKeyboard.h index c5c40a644a9..93730061c52 100644 --- a/features/unsupported/USBHost/USBHostHID/USBHostKeyboard.h +++ b/features/unsupported/USBHost/USBHostHID/USBHostKeyboard.h @@ -26,8 +26,7 @@ /** * A class to communicate a USB keyboard */ -class USBHostKeyboard : public IUSBEnumerator -{ +class USBHostKeyboard : public IUSBEnumerator { public: /** @@ -54,8 +53,7 @@ class USBHostKeyboard : public IUSBEnumerator * * @param ptr function pointer */ - inline void attach(void (*ptr)(uint8_t key)) - { + inline void attach(void (*ptr)(uint8_t key)) { if (ptr != NULL) { onKey = ptr; } @@ -66,8 +64,7 @@ class USBHostKeyboard : public IUSBEnumerator * * @param ptr function pointer */ - inline void attach(void (*ptr)(uint8_t keyCode, uint8_t modifier)) - { + inline void attach(void (*ptr)(uint8_t keyCode, uint8_t modifier)) { if (ptr != NULL) { onKeyCode = ptr; } diff --git a/features/unsupported/USBHost/USBHostHID/USBHostMouse.cpp b/features/unsupported/USBHost/USBHostHID/USBHostMouse.cpp index f257f8cf6b5..52fcf8c5b30 100644 --- a/features/unsupported/USBHost/USBHostHID/USBHostMouse.cpp +++ b/features/unsupported/USBHost/USBHostHID/USBHostMouse.cpp @@ -18,14 +18,12 @@ #if USBHOST_MOUSE -USBHostMouse::USBHostMouse() -{ +USBHostMouse::USBHostMouse() { host = USBHost::getHostInst(); init(); } -void USBHostMouse::init() -{ +void USBHostMouse::init() { dev = NULL; int_in = NULL; onUpdate = NULL; @@ -44,13 +42,11 @@ void USBHostMouse::init() z = 0; } -bool USBHostMouse::connected() -{ +bool USBHostMouse::connected() { return dev_connected; } -bool USBHostMouse::connect() -{ +bool USBHostMouse::connect() { int len_listen; if (dev_connected) { @@ -60,38 +56,27 @@ bool USBHostMouse::connect() for (uint8_t i = 0; i < MAX_DEVICE_CONNECTED; i++) { if ((dev = host->getDevice(i)) != NULL) { - if(host->enumerate(dev, this)) { + if(host->enumerate(dev, this)) break; - } + if (mouse_device_found) { - { - /* As this is done in a specific thread - * this lock is taken to avoid to process the device - * disconnect in usb process during the device registering */ - USBHost::Lock Lock(host); - int_in = dev->getEndpoint(mouse_intf, INTERRUPT_ENDPOINT, IN); - if (!int_in) { - break; - } - - USB_INFO("New Mouse device: VID:%04x PID:%04x [dev: %p - intf: %d]", dev->getVid(), dev->getPid(), dev, mouse_intf); - dev->setName("Mouse", mouse_intf); - host->registerDriver(dev, mouse_intf, this, &USBHostMouse::init); - - int_in->attach(this, &USBHostMouse::rxHandler); - len_listen = int_in->getSize(); - if (len_listen > sizeof(report)) { - len_listen = sizeof(report); - } - } - int ret=host->interruptRead(dev, int_in, report, len_listen, false); - MBED_ASSERT((ret==USB_TYPE_OK) || (ret ==USB_TYPE_PROCESSING) || (ret == USB_TYPE_FREE)); - if ((ret==USB_TYPE_OK) || (ret ==USB_TYPE_PROCESSING)) { - dev_connected = true; - } - if (ret == USB_TYPE_FREE) { - dev_connected = false; + + int_in = dev->getEndpoint(mouse_intf, INTERRUPT_ENDPOINT, IN); + if (!int_in) + break; + + USB_INFO("New Mouse device: VID:%04x PID:%04x [dev: %p - intf: %d]", dev->getVid(), dev->getPid(), dev, mouse_intf); + dev->setName("Mouse", mouse_intf); + host->registerDriver(dev, mouse_intf, this, &USBHostMouse::init); + + int_in->attach(this, &USBHostMouse::rxHandler); + len_listen = int_in->getSize(); + if (len_listen > sizeof(report)) { + len_listen = sizeof(report); } + host->interruptRead(dev, int_in, report, len_listen, false); + + dev_connected = true; return true; } } @@ -100,47 +85,41 @@ bool USBHostMouse::connect() return false; } -void USBHostMouse::rxHandler() -{ - int len_listen = int_in->getLengthTransferred(); - if (len_listen !=0) { +void USBHostMouse::rxHandler() { + int len_listen = int_in->getSize(); - if (onUpdate) { - (*onUpdate)(report[0] & 0x07, report[1], report[2], report[3]); - } - - if (onButtonUpdate && (buttons != (report[0] & 0x07))) { - (*onButtonUpdate)(report[0] & 0x07); - } + if (onUpdate) { + (*onUpdate)(report[0] & 0x07, report[1], report[2], report[3]); + } - if (onXUpdate && (x != report[1])) { - (*onXUpdate)(report[1]); - } + if (onButtonUpdate && (buttons != (report[0] & 0x07))) { + (*onButtonUpdate)(report[0] & 0x07); + } - if (onYUpdate && (y != report[2])) { - (*onYUpdate)(report[2]); - } + if (onXUpdate && (x != report[1])) { + (*onXUpdate)(report[1]); + } - if (onZUpdate && (z != report[3])) { - (*onZUpdate)(report[3]); - } + if (onYUpdate && (y != report[2])) { + (*onYUpdate)(report[2]); + } - // update mouse state - buttons = report[0] & 0x07; - x = report[1]; - y = report[2]; - z = report[3]; + if (onZUpdate && (z != report[3])) { + (*onZUpdate)(report[3]); } - /* set again the maximum value */ - len_listen = int_in->getSize(); + + // update mouse state + buttons = report[0] & 0x07; + x = report[1]; + y = report[2]; + z = report[3]; if (len_listen > sizeof(report)) { len_listen = sizeof(report); } - if (dev) { + if (dev) host->interruptRead(dev, int_in, report, len_listen, false); - } } /*virtual*/ void USBHostMouse::setVidPid(uint16_t vid, uint16_t pid) @@ -151,9 +130,9 @@ void USBHostMouse::rxHandler() /*virtual*/ bool USBHostMouse::parseInterface(uint8_t intf_nb, uint8_t intf_class, uint8_t intf_subclass, uint8_t intf_protocol) //Must return true if the interface should be parsed { if ((mouse_intf == -1) && - (intf_class == HID_CLASS) && - (intf_subclass == 0x01) && - (intf_protocol == 0x02)) { + (intf_class == HID_CLASS) && + (intf_subclass == 0x01) && + (intf_protocol == 0x02)) { mouse_intf = intf_nb; return true; } diff --git a/features/unsupported/USBHost/USBHostHID/USBHostMouse.h b/features/unsupported/USBHost/USBHostHID/USBHostMouse.h index 84cd33b3fe2..03e09944828 100644 --- a/features/unsupported/USBHost/USBHostHID/USBHostMouse.h +++ b/features/unsupported/USBHost/USBHostHID/USBHostMouse.h @@ -26,8 +26,7 @@ /** * A class to communicate a USB mouse */ -class USBHostMouse : public IUSBEnumerator -{ +class USBHostMouse : public IUSBEnumerator { public: /** @@ -54,8 +53,7 @@ class USBHostMouse : public IUSBEnumerator * * @param ptr function pointer */ - inline void attachEvent(void (*ptr)(uint8_t buttons, int8_t x, int8_t y, int8_t z)) - { + inline void attachEvent(void (*ptr)(uint8_t buttons, int8_t x, int8_t y, int8_t z)) { if (ptr != NULL) { onUpdate = ptr; } @@ -66,8 +64,7 @@ class USBHostMouse : public IUSBEnumerator * * @param ptr function pointer */ - inline void attachButtonEvent(void (*ptr)(uint8_t buttons)) - { + inline void attachButtonEvent(void (*ptr)(uint8_t buttons)) { if (ptr != NULL) { onButtonUpdate = ptr; } @@ -78,8 +75,7 @@ class USBHostMouse : public IUSBEnumerator * * @param ptr function pointer */ - inline void attachXEvent(void (*ptr)(int8_t x)) - { + inline void attachXEvent(void (*ptr)(int8_t x)) { if (ptr != NULL) { onXUpdate = ptr; } @@ -90,8 +86,7 @@ class USBHostMouse : public IUSBEnumerator * * @param ptr function pointer */ - inline void attachYEvent(void (*ptr)(int8_t y)) - { + inline void attachYEvent(void (*ptr)(int8_t y)) { if (ptr != NULL) { onYUpdate = ptr; } @@ -102,8 +97,7 @@ class USBHostMouse : public IUSBEnumerator * * @param ptr function pointer */ - inline void attachZEvent(void (*ptr)(int8_t z)) - { + inline void attachZEvent(void (*ptr)(int8_t z)) { if (ptr != NULL) { onZUpdate = ptr; } @@ -119,7 +113,8 @@ class USBHostMouse : public IUSBEnumerator USBHost * host; USBDeviceConnected * dev; USBEndpoint * int_in; - uint8_t report[64]; + uint8_t report[4]; + bool dev_connected; bool mouse_device_found; int mouse_intf; diff --git a/features/unsupported/USBHost/USBHostHub/USBHostHub.cpp b/features/unsupported/USBHost/USBHostHub/USBHostHub.cpp index 946029039a4..6ccaa90a973 100644 --- a/features/unsupported/USBHost/USBHostHub/USBHostHub.cpp +++ b/features/unsupported/USBHost/USBHostHub/USBHostHub.cpp @@ -50,14 +50,12 @@ #define C_PORT_OVER_CURRENT (1 << 19) #define C_PORT_RESET (1 << 20) -USBHostHub::USBHostHub() -{ +USBHostHub::USBHostHub() { host = NULL; init(); } -void USBHostHub::init() -{ +void USBHostHub::init() { dev_connected = false; dev = NULL; int_in = NULL; @@ -72,8 +70,7 @@ void USBHostHub::init() } } -void USBHostHub::setHost(USBHost * host_) -{ +void USBHostHub::setHost(USBHost * host_) { host = host_; } @@ -132,8 +129,7 @@ bool USBHostHub::connect(USBDeviceConnected * dev) return false; } -void USBHostHub::disconnect() -{ +void USBHostHub::disconnect() { init(); } @@ -145,9 +141,9 @@ void USBHostHub::disconnect() /*virtual*/ bool USBHostHub::parseInterface(uint8_t intf_nb, uint8_t intf_class, uint8_t intf_subclass, uint8_t intf_protocol) //Must return true if the interface should be parsed { if ((hub_intf == -1) && - (intf_class == HUB_CLASS) && - (intf_subclass == 0) && - (intf_protocol == 0)) { + (intf_class == HUB_CLASS) && + (intf_subclass == 0) && + (intf_protocol == 0)) { hub_intf = intf_nb; return true; } @@ -165,18 +161,15 @@ void USBHostHub::disconnect() return false; } -void USBHostHub::deviceConnected(USBDeviceConnected * dev) -{ +void USBHostHub::deviceConnected(USBDeviceConnected * dev) { device_children[dev->getPort() - 1] = dev; } -void USBHostHub::deviceDisconnected(USBDeviceConnected * dev) -{ +void USBHostHub::deviceDisconnected(USBDeviceConnected * dev) { device_children[dev->getPort() - 1] = NULL; } -void USBHostHub::hubDisconnected() -{ +void USBHostHub::hubDisconnected() { for (uint8_t i = 0; i < MAX_HUB_PORT; i++) { if (device_children[i] != NULL) { host->freeDevice(device_children[i]); @@ -184,11 +177,10 @@ void USBHostHub::hubDisconnected() } } -void USBHostHub::rxHandler() -{ +void USBHostHub::rxHandler() { uint32_t status; if (int_in) { - if ((int_in->getLengthTransferred())&&(int_in->getState() == USB_TYPE_IDLE)) { + if (int_in->getState() == USB_TYPE_IDLE) { for (int port = 1; port <= nb_port; port++) { status = getPortStatus(port); USB_DBG("[hub handler hub: %d] status port %d [hub: %p]: 0x%X", dev->getHub(), port, dev, status); @@ -225,8 +217,7 @@ void USBHostHub::rxHandler() } } -void USBHostHub::portReset(uint8_t port) -{ +void USBHostHub::portReset(uint8_t port) { // reset port uint32_t status; USB_DBG("reset port %d on hub: %p [this: %p]", port, dev, this) @@ -237,12 +228,10 @@ void USBHostHub::portReset(uint8_t port) while(1) { status = getPortStatus(port); /* disconnection since reset request */ - if (!(status & PORT_CONNECTION)) { + if (!(status & PORT_CONNECTION)) break; - } - if (status & (PORT_ENABLE | PORT_RESET)) { + if (status & (PORT_ENABLE | PORT_RESET)) break; - } if (status & PORT_OVER_CURRENT) { USB_ERR("OVER CURRENT DETECTED\r\n"); clearPortFeature(PORT_OVER_CURRENT, port); @@ -253,8 +242,7 @@ void USBHostHub::portReset(uint8_t port) } } -void USBHostHub::setPortFeature(uint32_t feature, uint8_t port) -{ +void USBHostHub::setPortFeature(uint32_t feature, uint8_t port) { host->controlWrite( dev, USB_HOST_TO_DEVICE | USB_REQUEST_TYPE_CLASS | USB_RECIPIENT_INTERFACE | USB_RECIPIENT_ENDPOINT, SET_FEATURE, @@ -264,8 +252,7 @@ void USBHostHub::setPortFeature(uint32_t feature, uint8_t port) 0); } -void USBHostHub::clearPortFeature(uint32_t feature, uint8_t port) -{ +void USBHostHub::clearPortFeature(uint32_t feature, uint8_t port) { host->controlWrite( dev, USB_HOST_TO_DEVICE | USB_REQUEST_TYPE_CLASS | USB_RECIPIENT_INTERFACE | USB_RECIPIENT_ENDPOINT, CLEAR_FEATURE, @@ -275,8 +262,7 @@ void USBHostHub::clearPortFeature(uint32_t feature, uint8_t port) 0); } -uint32_t USBHostHub::getPortStatus(uint8_t port) -{ +uint32_t USBHostHub::getPortStatus(uint8_t port) { uint32_t st; host->controlRead( dev, USB_DEVICE_TO_HOST | USB_REQUEST_TYPE_CLASS | USB_RECIPIENT_INTERFACE | USB_RECIPIENT_ENDPOINT, diff --git a/features/unsupported/USBHost/USBHostHub/USBHostHub.h b/features/unsupported/USBHost/USBHostHub/USBHostHub.h index 6e46c638b4b..e199c369e7c 100644 --- a/features/unsupported/USBHost/USBHostHub/USBHostHub.h +++ b/features/unsupported/USBHost/USBHostHub/USBHostHub.h @@ -31,8 +31,7 @@ class USBEndpoint; /** * A class to use a USB Hub */ -class USBHostHub : public IUSBEnumerator -{ +class USBHostHub : public IUSBEnumerator { public: /** * Constructor diff --git a/features/unsupported/net/cellular/CellularModem/CellularModem.h b/features/unsupported/net/cellular/CellularModem/CellularModem.h new file mode 100644 index 00000000000..fd47622c860 --- /dev/null +++ b/features/unsupported/net/cellular/CellularModem/CellularModem.h @@ -0,0 +1,78 @@ +/* CellularModem.h */ +/* Copyright (C) 2013 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef CELLULARMODEM_H_ +#define CELLULARMODEM_H_ + +#include "core/fwk.h" +#include "at/ATCommandsInterface.h" + +class CellularModem +{ +public: + //Internet-related functions + + /** Open a 3G internet connection + @return 0 on success, error code on failure + */ + virtual int connect(const char* apn = NULL, const char* user = NULL, const char* password = NULL) = 0; + + /** Close the internet connection + @return 0 on success, error code on failure + */ + virtual int disconnect() = 0; + + + /** Send a SM + @param number The receiver's phone number + @param message The message to send + @return 0 on success, error code on failure + */ + virtual int sendSM(const char* number, const char* message) = 0; + + + /** Receive a SM + @param number Pointer to a buffer to store the sender's phone number (must be at least 17 characters-long, including the sapce for the null-terminating char) + @param message Pointer to a buffer to store the the incoming message + @param maxLength Maximum message length that can be stored in buffer (including null-terminating character) + @return 0 on success, error code on failure + */ + virtual int getSM(char* number, char* message, size_t maxLength) = 0; + + /** Get the number of SMs in the incoming box + @param pCount pointer to store the number of unprocessed SMs on + @return 0 on success, error code on failure + */ + virtual int getSMCount(size_t* pCount) = 0; + + /** Get the ATCommandsInterface instance + @return Pointer to the ATCommandsInterface instance + */ + virtual ATCommandsInterface* getATCommandsInterface() = 0; + + /** Switch power on or off + In order to use this function, a pin name must have been entered in the constructor + @param enable true to switch the dongle on, false to switch it off + @return 0 on success, error code on failure + */ + virtual int power(bool enable) = 0; +}; + + +#endif /* CELLULARMODEM_H_ */ diff --git a/features/unsupported/net/cellular/CellularModem/at/ATCommandsInterface.cpp b/features/unsupported/net/cellular/CellularModem/at/ATCommandsInterface.cpp new file mode 100644 index 00000000000..9f711630ce5 --- /dev/null +++ b/features/unsupported/net/cellular/CellularModem/at/ATCommandsInterface.cpp @@ -0,0 +1,902 @@ +/* ATCommandsInterface.cpp */ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#define __DEBUG__ 2 //ERR+WARN +#ifndef __MODULE__ +#define __MODULE__ "ATCommandsInterface.cpp" +#endif + +#include "core/fwk.h" + +#include +#include //For memset, strstr... + +using std::memmove; + +#include "ATCommandsInterface.h" + +ATCommandsInterface::ATCommandsInterface(IOStream* pStream) : + m_pStream(pStream), m_open(false), m_transactionState(IDLE), m_env2AT(), m_AT2Env(), m_processingMtx(), + m_processingThread(&ATCommandsInterface::staticCallback, this, (osPriority)AT_THREAD_PRIORITY, 4*192), + m_eventsMgmtMtx(), m_eventsProcessingMtx() +{ + memset(m_eventsHandlers, 0, MAX_AT_EVENTS_HANDLERS * sizeof(IATEventsHandler*)); + + m_processingMtx.lock(); +} + +//Open connection to AT Interface in order to execute command & register/unregister events +int ATCommandsInterface::open() +{ + if( m_open ) + { + WARN("AT interface is already open"); + return OK; + } + DBG("Opening AT interface"); + //Start processing + m_processingThread.signal_set(AT_SIG_PROCESSING_START); + + m_processingMtx.unlock(); + + m_open = true; + + DBG("AT interface opened"); + + return OK; +} + +//Initialize AT link & start events processing +int ATCommandsInterface::init(bool reset /* = true*/) +{ + + //Lock transaction mutex + m_transactionMtx.lock(); + + if (reset) + { + DBG("Sending ATZ E1 V1"); + //Should we flush m_pStream at this point ??? + int err; + int tries = 5; + do + { + err = executeInternal("ATZ E1 V1", this, NULL, 3000); //Enable echo and verbosity + if(err && tries) + { + WARN("No response, trying again"); + Thread::wait(1000); //Give dongle time to recover + } + } while(err && tries--); + if( err ) + { + ERR("Sending ATZ E1 V1 returned with err code %d", err); + m_transactionMtx.unlock(); + return err; + } + } + + //Enable events handling and execute events enabling commands + enableEvents(); + + DBG("AT interface initialized"); + + //Unlock transaction mutex + m_transactionMtx.unlock(); + + return OK; +} + +//Close connection +int ATCommandsInterface::close() +{ + if( !m_open ) + { + WARN("AT interface is already closed"); + return OK; + } + + DBG("Closing AT interface"); + + //Lock transaction mutex + m_transactionMtx.lock(); + + //Disable events handling and advertize this to the events handlers + disableEvents(); + + //Stop processing + m_processingThread.signal_set(AT_SIG_PROCESSING_STOP); + //m_stopSphre.release(); + + int* msg = m_env2AT.alloc(osWaitForever); + *msg = AT_STOP; + m_env2AT.put(msg); //Used to unstall the process if needed + + //Unlock process routine (abort read) + m_pStream->abortRead(); //This is thread-safe + m_processingMtx.lock(); + m_open = false; + + //Unlock transaction mutex + m_transactionMtx.unlock(); + + DBG("AT interface closed"); + return OK; +} + +bool ATCommandsInterface::isOpen() +{ + return m_open; +} + +int ATCommandsInterface::executeSimple(const char* command, ATResult* pResult, uint32_t timeout/*=1000*/) +{ + return execute(command, this, pResult, timeout); +} + +int ATCommandsInterface::execute(const char* command, IATCommandsProcessor* pProcessor, ATResult* pResult, uint32_t timeout/*=1000*/) +{ + if(!m_open) + { + WARN("Interface is not open!"); + return NET_INVALID; + } + + //Lock transaction mutex + m_transactionMtx.lock(); + + disableEvents(); //Disable unsollicited result codes + int ret = executeInternal(command, pProcessor, pResult, timeout); + enableEvents(); //Re-enable unsollicited result codes whatever the result of the command is + + //Unlock transaction mutex + m_transactionMtx.unlock(); + + return ret; +} + +int ATCommandsInterface::registerEventsHandler(IATEventsHandler* pHdlr) +{ + m_eventsMgmtMtx.lock(); + m_eventsProcessingMtx.lock(); + for(int i = 0; i < MAX_AT_EVENTS_HANDLERS; i++) //Find a free slot + { + if( m_eventsHandlers[i] == NULL ) + { + m_eventsHandlers[i] = pHdlr; + m_eventsProcessingMtx.unlock(); + m_eventsMgmtMtx.unlock(); + return OK; + } + } + m_eventsProcessingMtx.unlock(); + m_eventsMgmtMtx.unlock(); + return NET_OOM; //No room left +} + +int ATCommandsInterface::deregisterEventsHandler(IATEventsHandler* pHdlr) +{ + m_eventsMgmtMtx.lock(); + m_eventsProcessingMtx.lock(); + for(int i = 0; i < MAX_AT_EVENTS_HANDLERS; i++) //Find handler in list + { + if( m_eventsHandlers[i] == pHdlr ) + { + m_eventsHandlers[i] = NULL; + m_eventsProcessingMtx.unlock(); + m_eventsMgmtMtx.unlock(); + return OK; + } + } + m_eventsProcessingMtx.unlock(); + m_eventsMgmtMtx.unlock(); + return NET_NOTFOUND; //Not found +} + +//Private methods + +int ATCommandsInterface::executeInternal(const char* command, IATCommandsProcessor* pProcessor, ATResult* pResult, uint32_t timeout/*=1000*/) +{ + DBG("Executing command %s", command); + + //Discard previous result if it arrived too late + osEvent evt = m_AT2Env.get(0); + + if(evt.status == osEventMail) + { + m_AT2Env.free((int*)evt.value.p); + WARN("Previous result discarded"); + } + + //Send params to the process routine + m_transactionCommand = command; + if(pProcessor != NULL) + { + m_pTransactionProcessor = pProcessor; + } + else + { + m_pTransactionProcessor = this; //Use default behaviour + } + + DBG("Sending command ready signal to AT thread & aborting current blocking read operation"); + + //Produce command ready signal + int* msg = m_env2AT.alloc(osWaitForever); + *msg = AT_CMD_READY; + m_env2AT.put(msg); + + DBG("Trying to enter abortRead()"); + //Unlock process routine (abort read) + m_pStream->abortRead(); //This is thread-safe + + //Wait for a result (get result message) + evt = m_AT2Env.get(timeout); + + if(evt.status != osEventMail) + { + //Cancel request + msg = m_env2AT.alloc(osWaitForever); + *msg = AT_TIMEOUT; + m_env2AT.put(msg); + + DBG("Trying to enter abortRead()"); + //Unlock process routine (abort read) + m_pStream->abortRead(); //This is thread-safe + + //Wait for acknowledge + int msgResult; + do + { + evt = m_AT2Env.get(osWaitForever); + msgResult = *((int*) evt.value.p); + m_AT2Env.free((int*)evt.value.p); + } while(msgResult != AT_TIMEOUT); + + WARN("Command returned no message"); + WARN("Command \"%s\" returned no message", command); + return NET_TIMEOUT; + } + DBG("Command returned with message %d", *msg); + + m_AT2Env.free((int*)evt.value.p); + + if(pResult != NULL) + { + *pResult = m_transactionResult; + } + + int ret = ATResultToReturnCode(m_transactionResult); + if(ret != OK) + { + WARN("Command returned AT result %d with code %d", m_transactionResult.result, m_transactionResult.code); + WARN("Command \"%s\" returned AT result %d with code %d", command, m_transactionResult.result, m_transactionResult.code); + } + + DBG("Command returned successfully"); + + return ret; +} + +int ATCommandsInterface::tryReadLine() +{ + static bool lineDetected = false; + + //Block on serial read or incoming command + DBG("Trying to read a new line from stream"); + int ret = m_pStream->waitAvailable(); //This can be aborted + size_t readLen = 0; + if(ret == OK) + { + ret = m_pStream->read((uint8_t*)m_inputBuf + m_inputPos, &readLen, AT_INPUT_BUF_SIZE - 1 - m_inputPos, 0); //Do NOT wait at this point + } + if(ret == OK) + { + m_inputPos+=readLen; + m_inputBuf[m_inputPos] = '\0'; //Add null terminating character to ease the use of str* functions + DBG("In buffer: [%s]", m_inputBuf); + } + + if( ret == NET_INTERRUPTED ) //It is worth checking readLen as data might have been read even though the read was interrupted + { + DBG("Read was interrupted"); + return NET_INTERRUPTED; //0 chars were read + } + else if(readLen == 0) + { + DBG("Nothing read"); + return OK; //0 chars were read + } + + DBG("Trying to process incoming line"); + bool lineProcessed = false; + + do + { + lineProcessed = false; //Reset flag + + DBG("New iteration"); + + //Look for a new line + if(!lineDetected) + { + DBG("No line detected yet"); + //Try to look for a starting CRLF + char* crPtr = strchr(m_inputBuf, CR); + /* + Different cases at this point: + - CRLF%c sequence: this is the start of a line + - CRLFCR(LF) sequence: this is the end of a line (followed by the beginning of the next one) + - LF: this is the trailing LF char of the previous line, discard + - CR / CRLF incomplete sequence: more data is needed to determine which action to take + - %c ... CR sequence: this should be the echo of the previous sequence + - %c sequence: This might be the echo of the previous command; more data is needed to determine which action to take + + In every case, move mem at the beginning + */ + if(crPtr != NULL) + { + DBG("CR char found"); + +#if 0 + //Discard all preceding characters (can do nothing if m_inputBuf == crPtr) + memmove(m_inputBuf, crPtr, (m_inputPos + 1) - (crPtr-m_inputBuf)); //Move null-terminating char as well + m_inputPos = m_inputPos - (crPtr-m_inputBuf); //Adjust m_inputPos +#endif + + //If the line starts with CR, this should be a result code + if( crPtr == m_inputBuf ) + { + //To determine the sequence we need at least 3 chars + if(m_inputPos >= 3) + { + //Look for a LF char next to the CR char + if(m_inputBuf[1] == LF) + { + //At this point we can check whether this is the end of a preceding line or the beginning of a new one + if(m_inputBuf[2] != CR) + { + DBG("Beginning of new line found"); + //Beginning of a line + lineDetected = true; //Move to next state-machine step + } + else + { + //End of an unprocessed line + WARN("End of unprocessed line"); + } + //In both cases discard CRLF + DBG("Discarding CRLF"); + memmove(m_inputBuf, m_inputBuf + 2, (m_inputPos + 1) - 2); //Move null-terminating char as well + m_inputPos = m_inputPos - 2; //Adjust m_inputPos + } + else + { + //This is completely unexpected, discard the CR char to try to recover good state + WARN("Unexpected %c char (%02d code) found after CR char", m_inputBuf[1]); + memmove(m_inputBuf, m_inputBuf + 1, (m_inputPos + 1) - 1); //Move null-terminating char as well + m_inputPos = m_inputPos - 1; //Adjust m_inputPos + } + } + } + //if the line does NOT begin with CR, this can be an echo of the previous command, process it + else + { + int crPos = crPtr - m_inputBuf; + int lfOff = 0; //Offset for LF if present + DBG("New line found (possible echo of command)"); + //This is the end of line + //Replace m_inputBuf[crPos] with null-terminating char + m_inputBuf[crPos] = '\0'; + //Check if there is a LF char afterwards + if(m_inputPos - crPos >= 1) + { + if(m_inputBuf[crPos+1] == LF) + { + lfOff++; //We will discard LF char as well + } + } + //Process line + int ret = processReadLine(); + if(ret) + { + m_inputPos = 0; + m_inputBuf[0] = '\0'; //Always have a null-terminating char at start of buffer + lineDetected = false; + return ret; + } + + //If sendData has been called, all incoming data has been discarded + if(m_inputPos > 0) + { + memmove(m_inputBuf, m_inputBuf + crPos + lfOff + 1, (m_inputPos + 1) - (crPos + lfOff + 1)); //Move null-terminating char as well + m_inputPos = m_inputPos - (crPos + lfOff + 1); //Adjust m_inputPos + } + DBG("One line was successfully processed"); + lineProcessed = true; //Line was processed with success + lineDetected = false; //Search now for a new line + } + } + else if(m_inputBuf[0] == LF) //If there is a remaining LF char from the previous line, discard it + { + DBG("Discarding single LF char"); + memmove(m_inputBuf, m_inputBuf + 1, (m_inputPos + 1) - 1); //Move null-terminating char as well + m_inputPos = m_inputPos - 1; //Adjust m_inputPos + } + } + + //Look for the end of line + if(lineDetected) + { + DBG("Looking for end of line"); + //Try to look for a terminating CRLF + char* crPtr = strchr(m_inputBuf, CR); + /* + Different cases at this point: + - CRLF sequence: this is the end of the line + - CR%c sequence : unexpected + - CR incomplete sequence: more data is needed to determine which action to take + */ + + //Try to look for a '>' (greater than character) that marks an entry prompt + char* greaterThanPtr = strchr(m_inputBuf, GD); + /* + This character must be detected as there is no CRLF sequence at the end of an entry prompt + */ + + if(crPtr != NULL) + { + DBG("CR char found"); + int crPos = crPtr - m_inputBuf; + //To determine the sequence we need at least 2 chars + if(m_inputPos - crPos >= 2) + { + //Look for a LF char next to the CR char + if(m_inputBuf[crPos + 1] == LF) + { + DBG("End of new line found"); + //This is the end of line + //Replace m_inputBuf[crPos] with null-terminating char + m_inputBuf[crPos] = '\0'; + //Process line + int ret = processReadLine(); + if(ret) + { + m_inputPos = 0; + m_inputBuf[0] = '\0'; //Always have a null-terminating char at start of buffer + lineDetected = false; + return ret; + } + + //If sendData has been called, all incoming data has been discarded + if(m_inputPos > 0) + { + //Shift remaining data to beginning of buffer + memmove(m_inputBuf, m_inputBuf + crPos + 2, (m_inputPos + 1) - (crPos + 2)); //Move null-terminating char as well + m_inputPos = m_inputPos - (crPos + 2); //Adjust m_inputPos + } + + DBG("One line was successfully processed"); + lineProcessed = true; //Line was processed with success + } + else + { + //This is completely unexpected, discard all chars till the CR char to try to recover good state + WARN("Unexpected %c char (%02d code) found in incoming line", m_inputBuf[crPos + 1]); + memmove(m_inputBuf, m_inputBuf + crPos + 1, (m_inputPos + 1) - (crPos + 1)); //Move null-terminating char as well + m_inputPos = m_inputPos - (crPos + 1); //Adjust m_inputPos + } + lineDetected = false; //In both case search now for a new line + } + } + else if(greaterThanPtr != NULL) + { + DBG("> char found"); + int gdPos = greaterThanPtr - m_inputBuf; + //To determine the sequence we need at least 2 chars + if(m_inputPos - gdPos >= 2) + { + //Look for a space char next to the GD char + if(m_inputBuf[gdPos + 1] == ' ') + { + //This is an entry prompt + //Replace m_inputBuf[gdPos] with null-terminating char + m_inputBuf[gdPos] = '\0'; + + //Shift remaining data to beginning of buffer + memmove(m_inputBuf, m_inputBuf + gdPos + 1, (m_inputPos + 1) - (gdPos + 1)); //Move null-terminating char as well + m_inputPos = m_inputPos - (gdPos + 1); //Adjust m_inputPos + + //Process prompt + ret = processEntryPrompt(); + if(ret) + { + m_inputPos = 0; + m_inputBuf[0] = '\0'; //Always have a null-terminating char at start of buffer + lineDetected = false; + return ret; + } + + DBG("One line was successfully processed"); + lineProcessed = true; //Line was processed with success + } + else + { + //This is completely unexpected, discard all chars till the GD char to try to recover good state + WARN("Unexpected %c char (%02d code) found in incoming line", m_inputBuf[gdPos + 1]); + memmove(m_inputBuf, m_inputBuf + gdPos + 1, (m_inputPos + 1) - (gdPos + 1)); //Move null-terminating char as well + m_inputPos = m_inputPos - (gdPos + 1); //Adjust m_inputPos + } + lineDetected = false; //In both case search now for a new line + } + } + } + } while(lineProcessed); //If one complete line was processed there might be other incoming lines that can also be processed without reading the buffer again + + //If the line could not be processed AND buffer is full, it means that we won't ever be able to process it (buffer too short) + if(m_inputPos == AT_INPUT_BUF_SIZE - 1) + { + //Discard everything + m_inputPos = 0; + m_inputBuf[0] = '\0'; //Always have a null-terminating char at start of buffer + WARN("Incoming buffer is too short to process incoming line"); + //Look for a new line + lineDetected = false; + } + + DBG("Processed every full incoming lines"); + + return OK; +} + +int ATCommandsInterface::trySendCommand() +{ + osEvent evt = m_env2AT.get(0); + DBG("status = %d, msg = %d", evt.status, evt.value.p); + if(evt.status == osEventMail) + { + int* msg = (int*) evt.value.p; + if( *msg == AT_CMD_READY ) //Command pending + { + if(m_transactionState != IDLE) + { + WARN("Previous command not processed!"); + } + DBG("Sending pending command"); + m_pStream->write((uint8_t*)m_transactionCommand, strlen(m_transactionCommand), osWaitForever); + char cr = CR; + m_pStream->write((uint8_t*)&cr, 1, osWaitForever); //Carriage return line terminator + m_transactionState = COMMAND_SENT; + } + else //Timeout + { + //Acknowledge + int* msg = m_AT2Env.alloc(osWaitForever); + *msg = AT_TIMEOUT; + m_AT2Env.put(msg); //Command has timed out + m_transactionState = IDLE; //State-machine reset + } + m_env2AT.free(msg); + } + return OK; +} + +int ATCommandsInterface::processReadLine() +{ + DBG("Processing read line [%s]", m_inputBuf); + //The line is stored in m_inputBuf + if(m_transactionState == COMMAND_SENT) + { + //If the command has been sent, checks echo to see if it has been received properly + if( strcmp(m_transactionCommand, m_inputBuf) == 0 ) + { + DBG("Command echo received"); + //If so, it means that the following lines will only be solicited results + m_transactionState = READING_RESULT; + return OK; + } + } + if(m_transactionState == IDLE || m_transactionState == COMMAND_SENT) + { + bool found = false; + char* pSemicol = strchr(m_inputBuf, ':'); + char* pData = NULL; + if( pSemicol != NULL ) //Split the identifier & the result code (if it exists) + { + *pSemicol = '\0'; + pData = pSemicol + 1; + if(pData[0]==' ') + { + pData++; //Suppress whitespace + } + } + //Looks for a unsolicited result code; we can have m_transactionState == COMMAND_SENT as the code may have arrived just before we sent the command + m_eventsProcessingMtx.lock(); + //Go through the list + for(int i = 0; i < MAX_AT_EVENTS_HANDLERS; i++) //Find a free slot + { + if( m_eventsHandlers[i] != NULL ) + { + if( m_eventsHandlers[i]->isATCodeHandled(m_inputBuf) ) + { + m_eventsHandlers[i]->onEvent(m_inputBuf, pData); + found = true; //Do not break here as there might be multiple handlers for one event type + } + } + } + m_eventsProcessingMtx.unlock(); + if(found) + { + return OK; + } + } + if(m_transactionState == READING_RESULT) + { + //The following lines can either be a command response or a result code (OK / ERROR / CONNECT / +CME ERROR: %s / +CMS ERROR: %s) + if(strcmp("OK", m_inputBuf) == 0) + { + DBG("OK result received"); + m_transactionResult.code = 0; + m_transactionResult.result = ATResult::AT_OK; + m_transactionState = IDLE; + int* msg = m_AT2Env.alloc(osWaitForever); + *msg = AT_RESULT_READY; + m_AT2Env.put(msg); //Command has been processed + return OK; + } + else if(strcmp("ERROR", m_inputBuf) == 0) + { + DBG("ERROR result received"); + m_transactionResult.code = 0; + m_transactionResult.result = ATResult::AT_ERROR; + m_transactionState = IDLE; + int* msg = m_AT2Env.alloc(osWaitForever); + *msg = AT_RESULT_READY; + m_AT2Env.put(msg); //Command has been processed + return OK; + } + else if(strncmp("CONNECT", m_inputBuf, 7 /*=strlen("CONNECT")*/) == 0) //Result can be "CONNECT" or "CONNECT %d", indicating baudrate + { + DBG("CONNECT result received"); + m_transactionResult.code = 0; + m_transactionResult.result = ATResult::AT_CONNECT; + m_transactionState = IDLE; + int* msg = m_AT2Env.alloc(osWaitForever); + *msg = AT_RESULT_READY; + m_AT2Env.put(msg); //Command has been processed + return OK; + } + else if(strcmp("COMMAND NOT SUPPORT", m_inputBuf) == 0) //Huawei-specific, not normalized + { + DBG("COMMAND NOT SUPPORT result received"); + m_transactionResult.code = 0; + m_transactionResult.result = ATResult::AT_ERROR; + m_transactionState = IDLE; + int* msg = m_AT2Env.alloc(osWaitForever); + *msg = AT_RESULT_READY; + m_AT2Env.put(msg); //Command has been processed + return OK; + } + else if(strstr(m_inputBuf, "+CME ERROR:") == m_inputBuf) //Mobile Equipment Error + { + std::sscanf(m_inputBuf + 12 /* =strlen("+CME ERROR: ") */, "%d", &m_transactionResult.code); + DBG("+CME ERROR: %d result received", m_transactionResult.code); + m_transactionResult.result = ATResult::AT_CME_ERROR; + m_transactionState = IDLE; + int* msg = m_AT2Env.alloc(osWaitForever); + *msg = AT_RESULT_READY; + m_AT2Env.put(msg); //Command has been processed + return OK; + } + else if(strstr(m_inputBuf, "+CMS ERROR:") == m_inputBuf) //SIM Error + { + std::sscanf(m_inputBuf + 13 /* =strlen("+CME ERROR: ") */, "%d", &m_transactionResult.code); + DBG("+CMS ERROR: %d result received", m_transactionResult.code); + m_transactionResult.result = ATResult::AT_CMS_ERROR; + m_transactionState = IDLE; + int* msg = m_AT2Env.alloc(osWaitForever); + *msg = AT_RESULT_READY; + m_AT2Env.put(msg); //Command has been processed + return OK; + } + else + { + DBG("Unprocessed result received: '%s'", m_inputBuf); + //Must call transaction processor to complete line processing + int ret = m_pTransactionProcessor->onNewATResponseLine(this, m_inputBuf); //Here sendData can be called + return ret; + } + } + + return OK; +} + +int ATCommandsInterface::processEntryPrompt() +{ + DBG("Calling prompt handler"); + int ret = m_pTransactionProcessor->onNewEntryPrompt(this); //Here sendData can be called + + if( ret != NET_MOREINFO ) //A new prompt is expected + { + DBG("Sending break character"); + //Send CTRL+Z (break sequence) to exit prompt + char seq[2] = {BRK, 0x00}; + sendData(seq); + } + return OK; +} + +//This will be called on initialization & after the execution of a command +void ATCommandsInterface::enableEvents() +{ + //Advertize this to events handlers + m_eventsMgmtMtx.lock(); + for(int i = 0; i < MAX_AT_EVENTS_HANDLERS; i++) //Find a free slot + { + if( m_eventsHandlers[i] != NULL ) + { + m_eventsHandlers[i]->onDispatchStart(); + //Enable this kind of events + const char* cmd = m_eventsHandlers[i]->getEventsEnableCommand(); + if(cmd != NULL) + { + int ret = executeInternal(cmd, this, NULL); //Execute enable command + if(ret) + { + WARN("Events enabling command \"%s\" failed", cmd); + } + } + } + } + m_eventsMgmtMtx.unlock(); +} + +//This will be called on de-initialization & before the execution of a command to prevent unsollicited result codes from polluting the results +void ATCommandsInterface::disableEvents() +{ + //Advertize this to events handlers + m_eventsMgmtMtx.lock(); + for(int i = 0; i < MAX_AT_EVENTS_HANDLERS; i++) //Find a free slot + { + if( m_eventsHandlers[i] != NULL ) + { + m_eventsHandlers[i]->onDispatchStart(); + //Disable this kind of events + const char* cmd = m_eventsHandlers[i]->getEventsDisableCommand(); + if(cmd != NULL) + { + int ret = executeInternal(cmd, this, NULL); //Execute disable command + if(ret) + { + WARN("Events disabling command \"%s\" failed", cmd); + } + } + } + } + m_eventsMgmtMtx.unlock(); +} + +//Commands that can be called during onNewATResponseLine callback, additionally to close() +//Access to this method is protected (can ONLY be called on processing thread during IATCommandsProcessor::onNewATResponseLine execution) +int ATCommandsInterface::sendData(const char* data) +{ + //m_inputBuf is cleared at this point (and MUST therefore be empty) + int dataLen = strlen(data); + DBG("Sending raw string of length %d", dataLen); + int ret = m_pStream->write((uint8_t*)data, dataLen, osWaitForever); + if(ret) + { + WARN("Could not write to stream (returned %d)", ret); + return ret; + } + + int dataPos = 0; + do + { + //Read echo + size_t readLen; + int ret = m_pStream->read((uint8_t*)m_inputBuf, &readLen, MIN(dataLen - dataPos, AT_INPUT_BUF_SIZE - 1), osWaitForever); //Make sure we do not read more than needed otherwise it could break the parser + if(ret) + { + WARN("Could not read from stream (returned %d)", ret); + m_inputPos = 0; //Reset input buffer state + m_inputBuf[0] = '\0'; //Always have a null-terminating char at start of buffer + return ret; + } + + if( memcmp(m_inputBuf, data + dataPos, readLen) != 0 ) + { + //Echo does not match output + m_inputBuf[readLen] = '\0'; + WARN("Echo does not match output, got '%s' instead", m_inputBuf); + m_inputPos = 0; //Reset input buffer state + m_inputBuf[0] = '\0'; //Always have a null-terminating char at start of buffer + return NET_DIFF; + } + + dataPos += readLen; + //If all characters have not been read yet + + } while(dataPos < dataLen); + + DBG("String sent successfully"); + + m_inputPos = 0; //Reset input buffer state + m_inputBuf[0] = '\0'; //Always have a null-terminating char at start of buffer + + return OK; +} + +/*static*/ void ATCommandsInterface::staticCallback(void const* p) +{ + ((ATCommandsInterface*)p)->process(); +} + +int ATCommandsInterface::ATResultToReturnCode(ATResult result) //Helper +{ + if(result.result == ATResult::AT_OK) + { + return OK; + } + else + { + return NET_MOREINFO; + } +} + +/*virtual*/ int ATCommandsInterface::onNewATResponseLine(ATCommandsInterface* pInst, const char* line) //Default implementation for simple commands handling +{ + return OK; +} + +/*virtual*/ int ATCommandsInterface::onNewEntryPrompt(ATCommandsInterface* pInst) //Default implementation (just sends Ctrl+Z to exit the prompt by returning OK right-away) +{ + return OK; +} + +void ATCommandsInterface::process() //Processing thread +{ + DBG("AT Thread started"); + while(true) + { + DBG("AT Processing on hold"); + m_processingThread.signal_wait(AT_SIG_PROCESSING_START); //Block until the process is started + + m_processingMtx.lock(); + DBG("AT Processing started"); + //First of all discard buffer + int ret; + size_t readLen; + do //Drop everything + { + ret = m_pStream->read((uint8_t*)m_inputBuf, &readLen, AT_INPUT_BUF_SIZE - 1, 0); //Do NOT wait at this point + } while(ret == OK); + m_inputPos = 0; //Clear input buffer + do + { + DBG("Trying to send a pending command"); + trySendCommand(); //This must be tried first as we discarded the buffer before and therefore would be blocking though there is a pending command + DBG("Trying to read a new line"); + tryReadLine(); + } while( m_processingThread.signal_wait(AT_SIG_PROCESSING_STOP, 0).status != osEventSignal ); //Loop until the process is interrupted + m_processingMtx.unlock(); + DBG("AT Processing stopped"); + } +} + diff --git a/features/unsupported/net/cellular/CellularModem/at/ATCommandsInterface.h b/features/unsupported/net/cellular/CellularModem/at/ATCommandsInterface.h new file mode 100644 index 00000000000..8334df8957c --- /dev/null +++ b/features/unsupported/net/cellular/CellularModem/at/ATCommandsInterface.h @@ -0,0 +1,153 @@ +/* ATCommandsInterface.h */ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef ATCOMMANDSINTERFACE_H_ +#define ATCOMMANDSINTERFACE_H_ + +#include "core/fwk.h" +#include "rtos.h" + +#define MAX_AT_EVENTS_HANDLERS 4 + +class ATCommandsInterface; + +/** Interface implemented by components handling AT events + * + */ +class IATEventsHandler +{ +protected: + virtual bool isATCodeHandled(const char* atCode) = 0; //Is this AT code handled + virtual void onDispatchStart() = 0; + virtual void onDispatchStop() = 0; + virtual char* getEventsEnableCommand() = 0; + virtual char* getEventsDisableCommand() = 0; + virtual void onEvent(const char* atCode, const char* evt) = 0; + friend class ATCommandsInterface; +}; + +/** Interface implemented by components executing complex AT commands + * + */ +class IATCommandsProcessor +{ +protected: + virtual int onNewATResponseLine(ATCommandsInterface* pInst, const char* line) = 0; + virtual int onNewEntryPrompt(ATCommandsInterface* pInst) = 0; + friend class ATCommandsInterface; +}; + +#define AT_INPUT_BUF_SIZE 192//64 + +//Signals to be sent to the processing thread +#define AT_SIG_PROCESSING_START 1 +#define AT_SIG_PROCESSING_STOP 2 +//Messages to be sent to the processing thread +#define AT_CMD_READY 1 +#define AT_TIMEOUT 2 +#define AT_STOP 3 +//Messages to be sent from the processing thread +#define AT_RESULT_READY 1 + +/** AT Commands interface class + * + */ +class ATCommandsInterface : protected IATCommandsProcessor +{ +public: + ATCommandsInterface(IOStream* pStream); + + //Open connection to AT Interface in order to execute command & register/unregister events + int open(); + + //Initialize AT link + int init(bool reset = true); + + //Close connection + int close(); + + bool isOpen(); + + class ATResult + { + public: + enum { AT_OK, AT_ERROR, AT_CONNECT, AT_CMS_ERROR, AT_CME_ERROR } result; + int code; + }; + + int executeSimple(const char* command, ATResult* pResult, uint32_t timeout=1000); + int execute(const char* command, IATCommandsProcessor* pProcessor, ATResult* pResult, uint32_t timeout=1000); + + int registerEventsHandler(IATEventsHandler* pHdlr); + int deregisterEventsHandler(IATEventsHandler* pHdlr); + + //Commands that can be called during onNewATResponseLine callback, additionally to close() + //Access to this method is protected (can ONLY be called on processing thread during IATCommandsProcessor::onNewATResponseLine execution) + int sendData(const char* data); + + static void staticCallback(void const* p); +private: + int executeInternal(const char* command, IATCommandsProcessor* pProcessor, ATResult* pResult, uint32_t timeout=1000); + + int tryReadLine(); + int trySendCommand(); + int processReadLine(); + int processEntryPrompt(); + + void enableEvents(); + void disableEvents(); + + int ATResultToReturnCode(ATResult result); //Helper + + virtual int onNewATResponseLine(ATCommandsInterface* pInst, const char* line); //Default implementation for simple commands handling + virtual int onNewEntryPrompt(ATCommandsInterface* pInst); //Default implementation (just sends Ctrl+Z to exit the prompt) + + void process(); //Processing thread + + IOStream* m_pStream; + + bool m_open; //< TRUE when the AT interface is open, and FALSE when it is not. + + const char* m_transactionCommand; + const char* m_transactionData; + + IATCommandsProcessor* m_pTransactionProcessor; + ATResult m_transactionResult; + + enum { IDLE, COMMAND_SENT, READING_RESULT, ABORTED } m_transactionState; + + char m_inputBuf[AT_INPUT_BUF_SIZE]; // Stores characters received from the modem. + int m_inputPos; // Current position of fill pointer in the input buffer. + + Mutex m_transactionMtx; + + // These are RTOS queues, concurrent access protected. In this case both only contain an integer. + Mail m_env2AT; // used by calling function to inform processing thread of events + Mail m_AT2Env; // used by processing thread to inform calling function of events + + IATEventsHandler* m_eventsHandlers[MAX_AT_EVENTS_HANDLERS]; // all registered events handlers + + Mutex m_processingMtx; + Thread m_processingThread; + + Mutex m_eventsMgmtMtx; //Lock events use within the calling thread + Mutex m_eventsProcessingMtx; //Lock events use within the processing thread +}; + +#endif /* ATCOMMANDSINTERFACE_H_ */ diff --git a/features/unsupported/net/cellular/CellularModem/core/IOStream.h b/features/unsupported/net/cellular/CellularModem/core/IOStream.h new file mode 100644 index 00000000000..6d411b8e4bb --- /dev/null +++ b/features/unsupported/net/cellular/CellularModem/core/IOStream.h @@ -0,0 +1,59 @@ +/* IOStream.h */ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef IOSTREAM_H_ +#define IOSTREAM_H_ + +#include "rtos.h" + +class IStream +{ +public: + //IStream(); + //virtual ~IStream(); + + //0 for non-blocking (returns immediately), osWaitForever for infinite blocking + virtual int read(uint8_t* buf, size_t* pLength, size_t maxLength, uint32_t timeout=osWaitForever) = 0; + virtual size_t available() = 0; + virtual int waitAvailable(uint32_t timeout=osWaitForever) = 0; //Wait for data to be available + virtual int abortRead() = 0; //Abort current reading (or waiting) operation +}; + +class OStream +{ +public: + //OStream(); + //virtual ~OStream(); + + //0 for non-blocking (returns immediately), osWaitForever for infinite blocking + virtual int write(uint8_t* buf, size_t length, uint32_t timeout=osWaitForever) = 0; + virtual size_t space() = 0; + virtual int waitSpace(uint32_t timeout=osWaitForever) = 0; //Wait for space to be available + virtual int abortWrite() = 0; //Abort current writing (or waiting) operation +}; + +class IOStream : public IStream, public OStream +{ +public: + //IOStream(); + //virtual ~IOStream(); +}; + + +#endif /* IOSTREAM_H_ */ diff --git a/features/unsupported/net/cellular/CellularModem/core/MtxCircBuffer.h b/features/unsupported/net/cellular/CellularModem/core/MtxCircBuffer.h new file mode 100644 index 00000000000..b011693eb42 --- /dev/null +++ b/features/unsupported/net/cellular/CellularModem/core/MtxCircBuffer.h @@ -0,0 +1,95 @@ +/* MtxCircBuf.h */ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef MTXCIRCBUFFER_H +#define MTXCIRCBUFFER_H + +#include "rtos.h" + +//Mutex protected circualr buffer +template +class MtxCircBuffer +{ +public: + MtxCircBuffer() //: + //mtx() + { + write = 0; + read = 0; + } + + bool isFull() + { + mtx.lock(); + bool r = (((write + 1) % size) == read); + mtx.unlock(); + return r; + } + + bool isEmpty() + { + mtx.lock(); + bool r = (read == write); + mtx.unlock(); + return r; + } + + void queue(T k) + { + mtx.lock(); + buf[write++] = k; + write %= size; + if (isFull()) + { + read++; + read %= size; + } + mtx.unlock(); + } + + uint16_t available() + { + mtx.lock(); + uint16_t a = (write >= read) ? (write - read) : (size - read + write); + mtx.unlock(); + return a; + } + + bool dequeue(T * c) + { + mtx.lock(); + bool empty = (read == write); + if (!empty) + { + *c = buf[read++]; + read %= size; + } + mtx.unlock(); + return (!empty); + } + +private: + volatile uint16_t write; + volatile uint16_t read; + volatile T buf[size]; + Mutex mtx; +}; + +#endif + diff --git a/features/unsupported/net/cellular/CellularModem/core/config.h b/features/unsupported/net/cellular/CellularModem/core/config.h new file mode 100644 index 00000000000..508424dc663 --- /dev/null +++ b/features/unsupported/net/cellular/CellularModem/core/config.h @@ -0,0 +1,27 @@ +/* config.h */ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +#ifndef CONFIG_H_ +#define CONFIG_H_ + + +//Configuration +#define AT_THREAD_PRIORITY 0 + + +#endif /* CONFIG_H_ */ diff --git a/features/unsupported/net/cellular/CellularModem/core/dbg.cpp b/features/unsupported/net/cellular/CellularModem/core/dbg.cpp new file mode 100644 index 00000000000..4314e2342f2 --- /dev/null +++ b/features/unsupported/net/cellular/CellularModem/core/dbg.cpp @@ -0,0 +1,127 @@ +/* dbg.cpp */ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#include "dbg.h" + +#include "mbed.h" +#include "rtos.h" + +#include +#include + +using namespace std; + +static Serial debug_pc(USBTX, USBRX); + +static char debug_newline[3]; + +static void debug_lock(bool set) +{ + static Mutex* mtx = new Mutex(); //Singleton runtime initialisation to avoid static initialisation chaos problems + static bool init = false; + if(set) + { + mtx->lock(); + if(!init) + { + strncpy( debug_newline, "\n", 2 ); + printf("[START]\n"); + fflush(stdout); + init = true; + } + } + else + { + mtx->unlock(); + } +} + +void debug_init() +{ + debug_lock(true); //Force init + debug_lock(false); +} + +void debug_set_newline(const char* newline) +{ + debug_lock(true); + strncpy( debug_newline, newline, 2 ); + debug_newline[2] = '\0'; + debug_lock(false); +} + +void debug_set_speed(int speed) +{ + debug_pc.baud(speed); +} + +void debug(int level, const char* module, int line, const char* fmt, ...) +{ + debug_lock(true); + switch(level) + { + default: + case 1: + printf("[ERROR]"); + break; + case 2: + printf("[WARN]"); + break; + case 3: + printf("[INFO]"); + break; + case 4: + printf("[DBG]"); + break; + } + + printf(" Module %s - Line %d: ", module, line); + + va_list argp; + + va_start(argp, fmt); + vprintf(fmt, argp); + va_end(argp); + + printf(debug_newline); + + fflush(stdout); + + debug_lock(false); + +} + +void debug_error(const char* module, int line, int ret) +{ + debug_lock(true); + printf("[RC] Module %s - Line %d : Error %d\n", module, line, ret); + fflush(stdout); + debug_lock(false); +} + +void debug_exact(const char* fmt, ...) +{ + debug_lock(true); + va_list argp; + + va_start(argp, fmt); + vprintf(fmt, argp); + va_end(argp); + debug_lock(false); +} diff --git a/features/unsupported/net/cellular/CellularModem/core/dbg.h b/features/unsupported/net/cellular/CellularModem/core/dbg.h new file mode 100644 index 00000000000..2ff24e1b310 --- /dev/null +++ b/features/unsupported/net/cellular/CellularModem/core/dbg.h @@ -0,0 +1,79 @@ +/* dbg.h */ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef DBG_H_ +#define DBG_H_ + +#ifdef __cplusplus +extern "C" { +#endif + + +void debug_init(void); +void debug(int level, const char* module, int line, const char* fmt, ...); +void debug_set_newline(const char* newline); +void debug_set_speed(int speed); +void debug_error(const char* module, int line, int ret); +void debug_exact(const char* fmt, ...); + +#define DBG_INIT() do{ debug_init(); }while(0) + +#define DBG_SET_NEWLINE( x ) do{ debug_set_newline(x); }while(0) + +#define DBG_SET_SPEED( x ) do{ debug_set_speed(x); }while(0) + +#if __DEBUG__ > 0 +#ifndef __MODULE__ +#error "__MODULE__ must be defined" +#endif +#endif + +#if __DEBUG__ >= 1 +#define ERR(...) do{ debug(1, __MODULE__, __LINE__, __VA_ARGS__); }while(0) +#else +#define ERR(...) do{ }while(0) +#endif + +#if __DEBUG__ >= 2 +#define WARN(...) do{ debug(2, __MODULE__, __LINE__, __VA_ARGS__); }while(0) +#else +#define WARN(...) do{ }while(0) +#endif + +#if __DEBUG__ >= 3 +#define INFO(...) do{ debug(3, __MODULE__, __LINE__, __VA_ARGS__); }while(0) +#define CHECK(ret) do{ if(ret){ debug_error(__MODULE__, __LINE__, ret); } }while(0) +#else +#define INFO(...) do{ }while(0) +#define CHECK(ret) do{ }while(0) +#endif + +#if __DEBUG__ >= 4 +#define DBG(...) do{ debug(4, __MODULE__, __LINE__, __VA_ARGS__); }while(0) +#define DBGX(...) do{ debug_exact(__VA_ARGS__); }while(0) +#else +#define DBG(...) do{ }while(0) +#define DBGX(...) do{ }while(0) +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* DBG_H_ */ diff --git a/features/unsupported/net/cellular/CellularModem/core/errors.h b/features/unsupported/net/cellular/CellularModem/core/errors.h new file mode 100644 index 00000000000..73ca00c1c4c --- /dev/null +++ b/features/unsupported/net/cellular/CellularModem/core/errors.h @@ -0,0 +1,47 @@ +/* errors.h */ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef ERRORS_H_ +#define ERRORS_H_ + +/** \page Network-related errors */ + +#define OK 0 //No error + +#define NET_FULL 1 //>All available resources are already used +#define NET_EMPTY 2 //>No resource +#define NET_NOTFOUND 3 //>Element cannot be found +#define NET_INVALID 4 //>Invalid +#define NET_CONTEXT 5 //>Called in a wrong context (eg during an interrupt) +#define NET_TIMEOUT 6 //>Timeout +#define NET_UNKNOWN 7 //>Unknown error +#define NET_OVERFLOW 8 //>Overflow +#define NET_PROCESSING 9 //>Command is processing +#define NET_INTERRUPTED 10 //>Current operation has been interrupted +#define NET_MOREINFO 11 //>More info on this error can be retrieved elsewhere (eg in a parameter passed as ptr) +#define NET_ABORT 12 //>Current operation must be aborted +#define NET_DIFF 13 //>Items that should match are different +#define NET_AUTH 14 //>Authentication failed +#define NET_PROTOCOL 15 //>Protocol error +#define NET_OOM 16 //>Out of memory +#define NET_CONN 17 //>Connection error +#define NET_CLOSED 18 //>Connection was closed by remote end +#define NET_TOOSMALL 19 //>Buffer is too small + +#endif /* ERRORS_H_ */ diff --git a/features/unsupported/net/cellular/CellularModem/core/fwk.h b/features/unsupported/net/cellular/CellularModem/core/fwk.h new file mode 100644 index 00000000000..4efc281c0ea --- /dev/null +++ b/features/unsupported/net/cellular/CellularModem/core/fwk.h @@ -0,0 +1,61 @@ +/* fwk.h */ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef FWK_H_ +#define FWK_H_ + +#include "config.h" + +#include "string.h" +//using namespace std; + +#include "stdint.h" +typedef unsigned int size_t; + +#ifndef __cplusplus +//boolean type compatibility +typedef byte bool; +#define true 1 +#define false 0 +#endif + +#ifndef NULL +#define NULL ((void*)0) +#endif + +#define CR '\x0D' +#define LF '\x0A' +#define GD '\x3E' +#define BRK '\x1A' + +//Custom utility classes +#include "IOStream.h" +//#include "String.h" + +//Error codes +#include "errors.h" + +//Debug +#include "dbg.h" + +//Utility macros +#define MIN(x,y) (((x)<(y))?(x):(y)) +#define MAX(x,y) (((x)>(y))?(x):(y)) + +#endif /* FWK_H_ */ diff --git a/features/unsupported/net/cellular/CellularModem/ip/IPInterface.cpp b/features/unsupported/net/cellular/CellularModem/ip/IPInterface.cpp new file mode 100644 index 00000000000..3732303e24b --- /dev/null +++ b/features/unsupported/net/cellular/CellularModem/ip/IPInterface.cpp @@ -0,0 +1,81 @@ +/* IPInterface.cpp */ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#include "core/fwk.h" + +#include "IPInterface.h" + +#include //For strcpy + + +IPInterface::IPInterface() : m_connected(false) +{ + +} + +/*virtual*/ IPInterface::~IPInterface() +{ + +} + +void IPInterface::registerAsDefaultInterface() //First come, first served +{ + s_pDefaultInterface = this; +} + +void IPInterface::unregisterAsDefaultInterface() //Must be called before inst is destroyed to avoid invalid ptr fault +{ + s_pDefaultInterface = NULL; +} + +/*static*/ IPInterface* IPInterface::getDefaultInterface() //For use by TCP, UDP sockets library +{ + return s_pDefaultInterface; +} + +/*static*/ IPInterface* IPInterface::s_pDefaultInterface = NULL; + + +char* IPInterface::getIPAddress() //Get IP Address as a string ('a.b.c.d') +{ + if(isConnected()) + { + return m_ipAddr; + } + else + { + return NULL; + } +} + +bool IPInterface::isConnected() //Is the interface connected? +{ + return m_connected; +} + +void IPInterface::setIPAddress(char* ipAddr) +{ + std::strcpy(m_ipAddr, ipAddr); //Let's trust the derived class not to buffer overflow us +} + +void IPInterface::setConnected(bool connected) +{ + m_connected = connected; +} + diff --git a/features/unsupported/net/cellular/CellularModem/ip/IPInterface.h b/features/unsupported/net/cellular/CellularModem/ip/IPInterface.h new file mode 100644 index 00000000000..6655aec9cae --- /dev/null +++ b/features/unsupported/net/cellular/CellularModem/ip/IPInterface.h @@ -0,0 +1,60 @@ +/* IPInterface.h */ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef IPINTERFACE_H_ +#define IPINTERFACE_H_ + +#include "core/fwk.h" + +/** Generic IP-based network interface + * + */ +class IPInterface +{ +public: + IPInterface(); + virtual ~IPInterface(); + + //int init(); //Initialize interface; no connection should be performed at this stage + virtual int connect() = 0; //Do connect the interface + virtual int disconnect() = 0; + //It is encouraged that the derived class implement a "setup(...)" function to configure the interface before the connection + + char* getIPAddress(); //Get IP Address as a string ('a.b.c.d') + bool isConnected(); //Is the interface connected? + + static IPInterface* getDefaultInterface(); //For use by TCP, UDP sockets library + + //WARN: Implementation will have to be more careful in case of multiple interfaces (or implement a routing protocol based on local IP addresses differentiation) + void registerAsDefaultInterface(); //First come, first served + void unregisterAsDefaultInterface(); //Must be called before inst is destroyed to avoid invalid ptr fault + +protected: + //Must be called by subclasses + void setIPAddress(char* ipAddr); + void setConnected(bool connected); + +private: + char m_ipAddr[16]; + bool m_connected; + + static IPInterface* s_pDefaultInterface; +}; + +#endif /* IPINTERFACE_H_ */ diff --git a/features/unsupported/net/cellular/CellularModem/ip/LwIPInterface.cpp b/features/unsupported/net/cellular/CellularModem/ip/LwIPInterface.cpp new file mode 100644 index 00000000000..b20f2a6617c --- /dev/null +++ b/features/unsupported/net/cellular/CellularModem/ip/LwIPInterface.cpp @@ -0,0 +1,52 @@ +/* LwIPInterface.cpp */ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + + +#include "core/fwk.h" + +#include "LwIPInterface.h" + +extern "C" { +#include "lwip/init.h" +#include "lwip/tcpip.h" +} + +LwIPInterface::LwIPInterface() : IPInterface(), m_rdySphre(1) +{ + m_rdySphre.wait(); +} + +LwIPInterface::~LwIPInterface() +{ + +} + +int LwIPInterface::init() //Init LwIP-specific stuff, create the right bindings, etc +{ + //lwip_init(); //All LwIP initialisation functions called on a per-module basis (according to lwipopts.h) + tcpip_init(LwIPInterface::tcpipRdyCb, this); //Start TCP/IP processing thread + m_rdySphre.wait(); //Wait for callback to produce resource + return OK; +} + +/*static*/ void LwIPInterface::tcpipRdyCb(void* ctx) //Result of TCP/IP thread launch +{ + LwIPInterface* pIf = (LwIPInterface*) ctx; + pIf->m_rdySphre.release(); +} diff --git a/features/unsupported/net/cellular/CellularModem/ip/LwIPInterface.h b/features/unsupported/net/cellular/CellularModem/ip/LwIPInterface.h new file mode 100644 index 00000000000..7e5471e2045 --- /dev/null +++ b/features/unsupported/net/cellular/CellularModem/ip/LwIPInterface.h @@ -0,0 +1,44 @@ +/* LwIPInterface.h */ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef LWIPINTERFACE_H_ +#define LWIPINTERFACE_H_ + +#include "core/fwk.h" +#include "IPInterface.h" + +#include "rtos.h" + +/** LwIP-based network interface + * + */ +class LwIPInterface : public IPInterface +{ +public: + LwIPInterface(); + virtual ~LwIPInterface(); + + int init(); //Init LwIP-specific stuff, create the right bindings, etc + +private: + static void tcpipRdyCb(void* ctx); //Result of TCP/IP thread launch + Semaphore m_rdySphre; +}; + +#endif /* LWIPINTERFACE_H_ */ diff --git a/features/unsupported/net/cellular/CellularModem/ip/PPPIPInterface.cpp b/features/unsupported/net/cellular/CellularModem/ip/PPPIPInterface.cpp new file mode 100644 index 00000000000..98614050efa --- /dev/null +++ b/features/unsupported/net/cellular/CellularModem/ip/PPPIPInterface.cpp @@ -0,0 +1,466 @@ +/* PPPIPInterface.cpp */ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#define __DEBUG__ 0 +#ifndef __MODULE__ +#define __MODULE__ "PPPIPInterface.cpp" +#endif + +#include "core/fwk.h" +#include "rtos.h" + +#include +using std::sscanf; +using std::sprintf; + +#include "PPPIPInterface.h" + +#define MSISDN "*99#" + +#define CONNECT_CMD_PREFIX "ATD " +#define CONNECT_CMD_SUFFIX "\x0D" +#define EXPECTED_RESP_SUFFIX "\x0D" "\x0A" "CONNECT" "\x0D" "\x0A" +#define EXPECTED_RESP_DATARATE_SUFFIX "\x0D" "\x0A" "CONNECT %d" "\x0D" "\x0A" +#define EXPECTED_RESP_MIN_LEN 20 +#define OK_RESP "\x0D" "\x0A" "OK" "\x0D" "\x0A" +#define ESCAPE_SEQ "+++" +#define HANGUP_CMD "ATH" "\x0D" +#define NO_CARRIER_RESP "\x0D" "\x0A" "NO CARRIER" "\x0D" "\x0A" +extern "C" { +#include "lwip/ip_addr.h" +#include "lwip/inet.h" +#include "lwip/err.h" +#include "lwip/dns.h" + +#include "netif/ppp/ppp.h" +} + +PPPIPInterface::PPPIPInterface(IOStream* pStream) : LwIPInterface(), m_linkStatusSphre(1), m_pppErrCode(0), m_pStream(pStream), m_streamAvail(true), m_pppd(-1) +{ + m_linkStatusSphre.wait(); +} + + + +/*virtual*/ PPPIPInterface::~PPPIPInterface() +{ +} + +/*virtual*/ int PPPIPInterface::init() //Init PPP-specific stuff, create the right bindings, etc +{ + DBG("Initializing LwIP"); + LwIPInterface::init(); //Init LwIP, NOT including PPP + DBG("Initializing PPP"); + pppInit(); + DBG("Done"); + return OK; +} + +int PPPIPInterface::setup(const char* user, const char* pw, const char* msisdn) +{ + DBG("Configuring PPP authentication method"); + pppSetAuth(PPPAUTHTYPE_ANY, user, pw); + m_msisdn = msisdn; + DBG("Done"); + return OK; +} + +/*virtual*/ int PPPIPInterface::connect() +{ + int ret; + char cmd[32]; + int cmdLen; + char buf[32]; + size_t len; + DBG("Trying to connect with PPP"); + + cleanupLink(); + + cmdLen = sprintf(cmd, "%s%s%s", CONNECT_CMD_PREFIX, m_msisdn, CONNECT_CMD_SUFFIX); + DBG("Sending %s", cmd); + ret = m_pStream->write((uint8_t*)cmd, cmdLen, osWaitForever); + if( ret != OK ) + { + return NET_UNKNOWN; + } + + len = 0; + size_t readLen; + ret = m_pStream->read((uint8_t*)buf + len, &readLen, EXPECTED_RESP_MIN_LEN, 10000); + if( ret != OK ) + { + return NET_UNKNOWN; + } + len += readLen; + while( (len < EXPECTED_RESP_MIN_LEN) || (buf[len-1] != LF) ) + { + ret = m_pStream->read((uint8_t*)buf + len, &readLen, 1, 10000); + if( ret != OK ) + { + return NET_UNKNOWN; + } + len += readLen; + } + + buf[len]=0; + + DBG("Got %s[len %d]", buf, len); + + int datarate = 0; + strcpy(&cmd[cmdLen], EXPECTED_RESP_DATARATE_SUFFIX); + if( (sscanf(buf, cmd, &datarate ) != 1)) + { + strcpy(&cmd[cmdLen], EXPECTED_RESP_SUFFIX); + if (strcmp(cmd, buf) != 0) + { + //Discard buffer + do //Clear buf + { + ret = m_pStream->read((uint8_t*)buf, &len, 32, 0); + } while( (ret == OK) && (len > 0) ); + return NET_CONN; + } + } + + DBG("Transport link open"); + if(datarate != 0) + { + DBG("Datarate: %d bps", datarate); + } + m_linkStatusSphre.wait(0); + if((m_pppd != -1) && (m_pppErrCode == 0)) //Already connected + { + return NET_INVALID; + } + + ret = pppOverSerialOpen(this, PPPIPInterface::linkStatusCb, this); + if(ret < 0) + { + switch(ret) + { + case PPPERR_OPEN: + default: + return NET_FULL; //All available resources are already used + } + } + m_pppd = ret; //PPP descriptor + m_linkStatusSphre.wait(); //Block indefinitely; there should be a timeout there + if(m_pppErrCode != PPPERR_NONE) + { + m_pppd = -1; + } + switch(m_pppErrCode) + { + case PPPERR_NONE: //Connected OK + return OK; + case PPPERR_CONNECT: //Connection lost + return NET_INTERRUPTED; + case PPPERR_AUTHFAIL: //Authentication failed + return NET_AUTH; + case PPPERR_PROTOCOL: //Protocol error + return NET_PROTOCOL; + default: + return NET_UNKNOWN; + } +} + +/*virtual*/ int PPPIPInterface::disconnect() +{ + int ret = m_linkStatusSphre.wait(0); + if(ret > 0) //Already disconnected? + { + m_pppd = -1; //Discard PPP descriptor + switch(m_pppErrCode) + { + case PPPERR_CONNECT: //Connection terminated + case PPPERR_AUTHFAIL: //Authentication failed + case PPPERR_PROTOCOL: //Protocol error + case PPPERR_USER: + return OK; + default: + return NET_UNKNOWN; + } + } + else + { + if(m_pppd == -1) + { + return NET_INVALID; + } + pppClose(m_pppd); + do + { + m_linkStatusSphre.wait(); //Block indefinitely; there should be a timeout there + DBG("Received PPP err code %d", m_pppErrCode); + } while(m_pppErrCode != PPPERR_USER); + m_pppd = -1; //Discard PPP descriptor + } + + DBG("Sending %s", ESCAPE_SEQ); + + ret = m_pStream->write((uint8_t*)ESCAPE_SEQ, strlen(ESCAPE_SEQ), osWaitForever); + if( ret != OK ) + { + return NET_UNKNOWN; + } + + cleanupLink(); + + return OK; +} + + +int PPPIPInterface::cleanupLink() +{ + int ret; + char buf[32]; + size_t len; + + do //Clear buf + { + ret = m_pStream->read((uint8_t*)buf, &len, 32, 100); + if(ret == OK) + { + buf[len] = '\0'; + DBG("Got %s", buf); + } + } while( (ret == OK) && (len > 0) ); + + DBG("Sending %s", HANGUP_CMD); + + ret = m_pStream->write((uint8_t*)HANGUP_CMD, strlen(HANGUP_CMD), osWaitForever); + if( ret != OK ) + { + return NET_UNKNOWN; + } + + size_t readLen; + + //Hangup + DBG("Expect %s", HANGUP_CMD); + + len = 0; + while( len < strlen(HANGUP_CMD) ) + { + ret = m_pStream->read((uint8_t*)buf + len, &readLen, strlen(HANGUP_CMD) - len, 100); + if( ret != OK ) + { + break; + } + len += readLen; + ///// + buf[len]=0; + DBG("Got %s", buf); + } + + buf[len]=0; + + DBG("Got %s[len %d]", buf, len); + + //OK response + DBG("Expect %s", OK_RESP); + + len = 0; + while( len < strlen(OK_RESP) ) + { + ret = m_pStream->read((uint8_t*)buf + len, &readLen, strlen(OK_RESP) - len, 100); + if( ret != OK ) + { + break; + } + len += readLen; + ///// + buf[len]=0; + DBG("Got %s", buf); + } + + buf[len]=0; + + DBG("Got %s[len %d]", buf, len); + + //NO CARRIER event + DBG("Expect %s", NO_CARRIER_RESP); + + len = 0; + while( len < strlen(NO_CARRIER_RESP) ) + { + ret = m_pStream->read((uint8_t*)buf + len, &readLen, strlen(NO_CARRIER_RESP) - len, 100); + if( ret != OK ) + { + break; + } + len += readLen; + ///// + buf[len]=0; + DBG("Got %s", buf); + } + + buf[len]=0; + + DBG("Got %s[len %d]", buf, len); + + do //Clear buf + { + ret = m_pStream->read((uint8_t*)buf, &len, 32, 100); + if(ret == OK) + { + buf[len] = '\0'; + DBG("Got %s", buf); + } + } while( (ret == OK) && (len > 0) ); + + + return OK; +} + +/*static*/ void PPPIPInterface::linkStatusCb(void *ctx, int errCode, void *arg) //PPP link status +{ + PPPIPInterface* pIf = (PPPIPInterface*)ctx; + struct ppp_addrs* addrs = (struct ppp_addrs*) arg; + + switch(errCode) + { + case PPPERR_NONE: + WARN("Connected via PPP."); + DBG("Local IP address: %s", inet_ntoa(addrs->our_ipaddr)); + DBG("Netmask: %s", inet_ntoa(addrs->netmask)); + DBG("Remote IP address: %s", inet_ntoa(addrs->his_ipaddr)); + DBG("Primary DNS: %s", inet_ntoa(addrs->dns1)); + DBG("Secondary DNS: %s", inet_ntoa(addrs->dns2)); + //Setup DNS + if (addrs->dns1.addr != 0) + { + dns_setserver(0, (struct ip_addr*)&(addrs->dns1)); + } + if (addrs->dns2.addr != 0) + { + dns_setserver(1, (struct ip_addr*)&(addrs->dns1)); + } + + pIf->setConnected(true); + pIf->setIPAddress(inet_ntoa(addrs->our_ipaddr)); + break; + case PPPERR_CONNECT: //Connection lost + WARN("Connection lost/terminated"); + pIf->setConnected(false); + break; + case PPPERR_AUTHFAIL: //Authentication failed + WARN("Authentication failed"); + pIf->setConnected(false); + break; + case PPPERR_PROTOCOL: //Protocol error + WARN("Protocol error"); + pIf->setConnected(false); + break; + case PPPERR_USER: + WARN("Disconnected by user"); + pIf->setConnected(false); + break; + default: + WARN("Unknown error (%d)", errCode); + pIf->setConnected(false); + break; + } + + pIf->m_linkStatusSphre.wait(0); //If previous event has not been handled, "delete" it now + pIf->m_pppErrCode = errCode; + pIf->m_linkStatusSphre.release(); +} + +//LwIP PPP implementation +extern "C" +{ + +/** + * Writes to the serial device. + * + * @param fd serial device handle + * @param data pointer to data to send + * @param len length (in bytes) of data to send + * @return number of bytes actually sent + * + * @note This function will block until all data can be sent. + */ +u32_t sio_write(sio_fd_t fd, u8_t *data, u32_t len) +{ + DBG("sio_write"); + PPPIPInterface* pIf = (PPPIPInterface*)fd; + int ret; + if(!pIf->m_streamAvail) //If stream is not available (it is a shared resource) don't go further + { + return 0; + } + ret = pIf->m_pStream->write(data, len, osWaitForever); //Blocks until all data is sent or an error happens + if(ret != OK) + { + return 0; + } + return len; +} + +/** + * Reads from the serial device. + * + * @param fd serial device handle + * @param data pointer to data buffer for receiving + * @param len maximum length (in bytes) of data to receive + * @return number of bytes actually received - may be 0 if aborted by sio_read_abort + * + * @note This function will block until data can be received. The blocking + * can be cancelled by calling sio_read_abort(). + */ +u32_t sio_read(sio_fd_t fd, u8_t *data, u32_t len) +{ + DBG("sio_read"); + PPPIPInterface* pIf = (PPPIPInterface*)fd; + int ret; + size_t readLen; + if(!pIf->m_streamAvail) //If stream is not available (it is a shared resource) don't go further + { + WARN("EXIT NOT AVAIL"); + return 0; + } + ret = pIf->m_pStream->read(data, &readLen, len, osWaitForever); //Blocks until some data is received or an error happens + if(ret != OK) + { + return 0; + } + DBG("ret"); + return readLen; +} + +/** + * Aborts a blocking sio_read() call. + * + * @param fd serial device handle + */ +void sio_read_abort(sio_fd_t fd) +{ + DBG("sio_read_abort"); + PPPIPInterface* pIf = (PPPIPInterface*)fd; + if(!pIf->m_streamAvail) //If stream is not available (it is a shared resource) don't go further + { + return; + } + pIf->m_pStream->abortRead(); + DBG("ret"); +} + +} + diff --git a/features/unsupported/net/cellular/CellularModem/ip/PPPIPInterface.h b/features/unsupported/net/cellular/CellularModem/ip/PPPIPInterface.h new file mode 100644 index 00000000000..2d24009dcd8 --- /dev/null +++ b/features/unsupported/net/cellular/CellularModem/ip/PPPIPInterface.h @@ -0,0 +1,69 @@ +/* PPPIPInterface.h */ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef PPPIPINTERFACE_H_ +#define PPPIPINTERFACE_H_ + +#include "core/fwk.h" + +#include "LwIPInterface.h" + +#include "lwip/sio.h" + +namespace rtos { +class Semaphore; +} +using namespace rtos; + +#define DEFAULT_MSISDN_GSM "*99#" +#define DEFAULT_MSISDN_CDMA "#777" + +/** Interface using PPP to connect to an IP-based network + * + */ +class PPPIPInterface : public LwIPInterface +{ +public: + PPPIPInterface(IOStream* pStream); + virtual ~PPPIPInterface(); + + int init(); //Init PPP-specific stuff, create the right bindings, etc + int setup(const char* user, const char* pw, const char* msisdn); //Setup authentication + virtual int connect(); + virtual int disconnect(); + +private: + int cleanupLink(); + + static void linkStatusCb(void *ctx, int errCode, void *arg); //PPP link status + Semaphore m_linkStatusSphre; + int m_pppErrCode; + + IOStream* m_pStream; //Serial stream + bool m_streamAvail; + const char* m_msisdn; + + int m_pppd; + + friend u32_t sio_write(sio_fd_t fd, u8_t *data, u32_t len); + friend u32_t sio_read(sio_fd_t fd, u8_t *data, u32_t len); + friend void sio_read_abort(sio_fd_t fd); +}; + +#endif /* PPPIPINTERFACE_H_ */ diff --git a/features/unsupported/net/cellular/CellularModem/link/LinkMonitor.cpp b/features/unsupported/net/cellular/CellularModem/link/LinkMonitor.cpp new file mode 100644 index 00000000000..612b3769216 --- /dev/null +++ b/features/unsupported/net/cellular/CellularModem/link/LinkMonitor.cpp @@ -0,0 +1,175 @@ +/* LinkMonitor.cpp */ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#define __DEBUG__ 0 +#ifndef __MODULE__ +#define __MODULE__ "LinkMonitor.cpp" +#endif + +#include "core/fwk.h" + +#include "LinkMonitor.h" + +#include +using std::sscanf; + +#define DEFAULT_TIMEOUT 10000 + +LinkMonitor::LinkMonitor(ATCommandsInterface* pIf) : m_pIf(pIf), m_rssi(0), m_registrationState(REGISTRATION_STATE_UNKNOWN), m_bearer(BEARER_UNKNOWN) +{ + m_gsm = true; +} + +int LinkMonitor::init(bool gsm) +{ + m_gsm = gsm; + if (m_gsm) + { + // we need to make sure that we setup the operator selection to be in 'numeric' format. + // i.e. it is made up of a network and country code when returned by the modem e.g. Operator = 23415. This allows easy logic parsing for + // setting up other network parameters in future. + DBG("LinkMonitor::init() being called. This should only happen once: executinging AT+COPS=0,2"); + int ret = m_pIf->executeSimple("AT+COPS=0,2", NULL, DEFAULT_TIMEOUT); //Configure to set the operator string to Country Code and mobile network code + if(ret != OK) + { + WARN(" NET_PROTOCOL error from sending the AT+COPS command to the modem. "); + return NET_PROTOCOL; + } + } + return OK; +} + +/*virtual*/ int LinkMonitor::onNewATResponseLine(ATCommandsInterface* pInst, const char* line) +{ + DBG("Line is %s", line); + char n[32] = ""; + char s[32] = ""; + int v; + if( sscanf(line, "+CREG: %*d,%d", &v) >= 1 ) //Reg state is valid + { + DBG("+CREG %d", v); + switch( v ) + { + case 0: + m_registrationState = REGISTRATION_STATE_UNKNOWN; + break; + case 1: + m_registrationState = REGISTRATION_STATE_HOME_NETWORK; + break; + case 2: + m_registrationState = REGISTRATION_STATE_REGISTERING; + break; + case 3: + m_registrationState = REGISTRATION_STATE_DENIED; + break; + case 4: + m_registrationState = REGISTRATION_STATE_NO_SIGNAL; + break; + case 5: + m_registrationState = REGISTRATION_STATE_ROAMING; + break; + default: + m_registrationState = REGISTRATION_STATE_UNKNOWN; + break; + } + } + else if( sscanf(line, "+COPS: %*d,%*d,\"%*[^\"]\",%d", &v) >= 1 ) + { + DBG("+COPS %d", v); + switch( v ) + { + case 0: + m_bearer = BEARER_GSM; + break; + case 2: + m_bearer = BEARER_UMTS; + break; + case 3: + m_bearer = BEARER_EDGE; + break; + case 4: //HSDPA + case 5: //HSUPA + case 6: //HSDPA + HSUPA + m_bearer = BEARER_HSPA; + break; + case 7: + m_bearer = BEARER_LTE; + break; + case 1: //GSM Compact + default: + m_bearer = BEARER_UNKNOWN; + break; + } + } + else if( sscanf(line, "+CSQ: %d,%*d", &v) >= 1 ) + { + DBG("+CSQ %d", v); + if(v == 99) //Unknown + { + m_rssi = 0; //Unknown + } + else + { + m_rssi = -113 + 2*v; + } + } + else if ( (sscanf(line, "+CNUM: \"%[^\"]\",\"%[^\"]\",%d", n, s, &v) == 3) || + (sscanf(line, "+CNUM: \"\",\"%[^\"]\",%d", s, &v) == 2) ) + { + if (*s && ((v == 145/*number includes + */) || (v == 129/*otherwise*/))) { + strcpy(m_phoneNumber, s); + } + } + return OK; +} + +/*virtual*/ int LinkMonitor::onNewEntryPrompt(ATCommandsInterface* pInst) +{ + return OK; +} + +int LinkMonitor::getState(int* pRssi, REGISTRATION_STATE* pRegistrationState, BEARER* pBearer) +{ + m_rssi = 0; + m_registrationState = REGISTRATION_STATE_UNKNOWN; + m_bearer = BEARER_UNKNOWN; + int ret = m_pIf->execute(m_gsm ? "AT+CREG?;+COPS?;+CSQ" : "AT+CREG?;+CSQ", this, NULL, DEFAULT_TIMEOUT); //Configure to get registration info & get it; get signal quality + if(ret != OK) + { + return NET_PROTOCOL; + } + *pRssi = m_rssi; + *pRegistrationState = m_registrationState; + *pBearer = m_bearer; + return OK; +} + +int LinkMonitor::getPhoneNumber(char* phoneNumber) +{ + *m_phoneNumber = '\0'; + if (m_gsm) { + int ret = m_pIf->execute("AT+CNUM", this, NULL, DEFAULT_TIMEOUT); + if(ret != OK) + { + return NET_PROTOCOL; + } + } + strcpy(phoneNumber, m_phoneNumber); + return OK; +} \ No newline at end of file diff --git a/features/unsupported/net/cellular/CellularModem/link/LinkMonitor.h b/features/unsupported/net/cellular/CellularModem/link/LinkMonitor.h new file mode 100644 index 00000000000..864909d6c50 --- /dev/null +++ b/features/unsupported/net/cellular/CellularModem/link/LinkMonitor.h @@ -0,0 +1,96 @@ +/* LinkMonitor.h */ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef LINKMONITOR_H_ +#define LINKMONITOR_H_ + +#include "core/fwk.h" + +#include "rtos.h" + +#include "at/ATCommandsInterface.h" + +/** Component to monitor link quality + * + */ +class LinkMonitor : protected IATCommandsProcessor +{ +public: + /** Create LinkMonitor instance + @param pIf Pointer to the ATCommandsInterface instance to use + */ + LinkMonitor(ATCommandsInterface* pIf); + + /** Initialize monitor + */ + int init(bool gsm = true); + + /** Registration State + */ + enum REGISTRATION_STATE + { + REGISTRATION_STATE_UNKNOWN, //!< Unknown + REGISTRATION_STATE_REGISTERING, //!< Registering + REGISTRATION_STATE_DENIED, //!< Denied + REGISTRATION_STATE_NO_SIGNAL, //!< No Signal + REGISTRATION_STATE_HOME_NETWORK, //!< Registered on home network + REGISTRATION_STATE_ROAMING //!< Registered on roaming network + }; + + /** Bearer type + */ + enum BEARER + { + BEARER_UNKNOWN, //!< Unknown + BEARER_GSM, //!< GSM (2G) + BEARER_EDGE, //!< EDGE (2.5G) + BEARER_UMTS, //!< UMTS (3G) + BEARER_HSPA, //!< HSPA (3G+) + BEARER_LTE //!< LTE (4G) + }; + + /** Get link state + @param pRssi pointer to store the current RSSI in dBm, between -51 dBm and -113 dBm if known; -51 dBm means -51 dBm or more; -113 dBm means -113 dBm or less; 0 if unknown + @param pRegistrationState pointer to store the current registration state + @param pBearer pointer to store the current bearer + @return 0 on success, error code on failure + */ + int getState(int* pRssi, REGISTRATION_STATE* pRegistrationState, BEARER* pBearer); + + /** Get my phone number + @param phoneNumber pointer to store the current phoneNumber + @return 0 on success, error code on failure + */ + int getPhoneNumber(char* phoneNumber); +protected: + //IATCommandsProcessor + virtual int onNewATResponseLine(ATCommandsInterface* pInst, const char* line); + virtual int onNewEntryPrompt(ATCommandsInterface* pInst); + +private: + ATCommandsInterface* m_pIf; + + int m_rssi; + bool m_gsm; + REGISTRATION_STATE m_registrationState; + BEARER m_bearer; + char m_phoneNumber[16]; +}; + +#endif /* LINKMONITOR_H_ */ diff --git a/features/unsupported/net/cellular/CellularModem/lwipopts_conf.h b/features/unsupported/net/cellular/CellularModem/lwipopts_conf.h new file mode 100644 index 00000000000..5cd84be875f --- /dev/null +++ b/features/unsupported/net/cellular/CellularModem/lwipopts_conf.h @@ -0,0 +1,26 @@ +/* lwipopts.h */ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef LWIPOPTS_CONF_H_ +#define LWIPOPTS_CONF_H_ + +#define LWIP_TRANSPORT_PPP 1 + +#endif /* LWIPOPTS_CONF_H_ */ + diff --git a/features/unsupported/net/cellular/CellularModem/sms/CDMASMSInterface.cpp b/features/unsupported/net/cellular/CellularModem/sms/CDMASMSInterface.cpp new file mode 100644 index 00000000000..978b3e1e8b0 --- /dev/null +++ b/features/unsupported/net/cellular/CellularModem/sms/CDMASMSInterface.cpp @@ -0,0 +1,350 @@ +/* CDMASMSInterface.cpp */ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#define __DEBUG__ 0 +#ifndef __MODULE__ +#define __MODULE__ "CDMASMSInterface.cpp" +#endif + +#include "core/fwk.h" + +#include "CDMASMSInterface.h" + +#include +#include + +using std::sscanf; + +#define DEFAULT_TIMEOUT 10000 + +CDMASMSInterface::CDMASMSInterface(ATCommandsInterface* pIf) : m_pIf(pIf), m_msg(NULL), m_maxMsgLength(0), m_msisdn(NULL) +{ +} + +int CDMASMSInterface::init() +{ + m_state = SMS_IDLE; + + DBG("Get number of messages in the different inboxes"); + int ret = updateInbox(); + if(ret) + { + return NET_PROTOCOL; + } + + DBG("Initialization done"); + return OK; +} + +int CDMASMSInterface::send(const char* number, const char* message) +{ + if( strlen(number) > 16 ) + { + return NET_INVALID; //Number too long + } + + int ret; + + //Prepare infos + m_state = SMS_SEND_CMD_SENT; + + bool intlNumber=(number[0]=='+'); //If the number starts with the + sign, replace it with 011 instead (int'l dialing code in the US) + + DBG("Send SM"); + //Send command + char cmd[32+strlen(message)]; + std::sprintf(cmd, "AT!SSMS=0,%s%s,,\"%s\"",intlNumber?"011":"", intlNumber?(number+1):number, message); //Send with normal priority + ret = m_pIf->execute(cmd, this, NULL, DEFAULT_TIMEOUT); + + if(ret != OK) + { + WARN("ret %d", ret); + m_state = SMS_IDLE; + return NET_PROTOCOL; + } + + DBG("Check status"); + m_txState = SMS_PENDING; + + int tries = 10; + while(tries--) + { + m_state = SMS_GET_TX_STATUS_CMD_SENT; + ret = m_pIf->execute("AT!SSMS?", this, NULL, DEFAULT_TIMEOUT); + if(ret) + { + m_state = SMS_IDLE; + return ret; + } + m_state = SMS_IDLE; + if(m_txState == SMS_PENDING) //Wait more + { + Thread::wait(1000); + continue; + } + else if(m_txState == SMS_FAILED) + { + ERR("The modem could not send the SM"); + return NET_CONN; //Probably a conenction issue, the user can retry + } + else + { + break; + } + } + if(!tries) + { + ERR("The is still trying to send the SM"); + return NET_TIMEOUT; + } + return OK; +} + + +int CDMASMSInterface::get(char* number, char* message, size_t maxLength) +{ + if( maxLength < 1 ) + { + return NET_INVALID; //Buffer too short + } + + int ret; + + DBG("Get next message"); + if( (m_msgInListsCount[0] + m_msgInListsCount[1] + m_msgInListsCount[2]) == 0) + { + DBG("Message list count is 0 and needs updating. Running updateInbox."); + ret = updateInbox(); + if (ret) + { + return ret; + } + } + + if( (m_msgInListsCount[0] + m_msgInListsCount[1] + m_msgInListsCount[2]) == 0) + { + DBG("Message list count is 0"); + return NET_EMPTY; //No message to read + } + + //Determine which index to use : 3 (read), then 1 (urgent), then 2 (regular) + int index; + if(m_msgInListsCount[2]) + { + index = 3; + } + else if(m_msgInListsCount[0]) + { + index = 1; + } + else //if(m_msgInListsCount[1]) + { + index = 2; + } + + //Prepare infos + m_state = SMS_GET_CMD_SENT; + m_msisdn = (char*) number; + m_msg = (char*) message; + m_maxMsgLength = maxLength; + m_headersToRead = 3; + + m_msisdn[0] = '\0'; + + DBG("Get SMS"); + //Read command + char cmd[32]; + std::sprintf(cmd, "AT!GSMS?%d,1", index); //1 is the oldest message + ret = m_pIf->execute(cmd, this, NULL, DEFAULT_TIMEOUT); + if( ret != OK ) + { + WARN("AT!GSMS returned %d", ret); + m_state = SMS_IDLE; + return NET_PROTOCOL; + } + + //If message is not read, it will be put at the end of the read list + int item; + if( index != 3 ) + { + //Decrement count in relevant list + m_msgInListsCount[index-1]--; + //Increment count in read list + m_msgInListsCount[3-1]++; + item = m_msgInListsCount[3-1]; + //Normally item should be equal to 1 as we'd have read any older messages first + if( item != 1 ) + { + WARN("Still some older messages pending in the read inbox"); + } + } + else + { + //The item is still the oldest one + item = 1; + } + + DBG("Deleting message"); + //Delete message from inbox + std::sprintf(cmd, "AT!DSMS=3"/*,%d", item*/); //FIXME why doesn't that work when specifying the index?? + ret = m_pIf->executeSimple(cmd, NULL, DEFAULT_TIMEOUT); + if(ret != OK) + { + ERR("Could not delete message"); + } + else + { + //Now we can decrease the number of read messages + m_msgInListsCount[3-1]--; + } + + if (m_state != SMS_CMD_PROCESSED) + { + WARN("Message could not be retrieved properly"); + m_state = SMS_IDLE; + return NET_EMPTY; + } + + m_state = SMS_IDLE; + + return OK; +} + + +int CDMASMSInterface::getCount(size_t* pCount) +{ + int ret = updateInbox(); + if(ret) + { + return NET_PROTOCOL; + } + + *pCount = m_msgInListsCount[0] + m_msgInListsCount[1] + m_msgInListsCount[2]; //Urgent messages + regular messages + read messages + + return OK; +} + + +/*virtual*/ int CDMASMSInterface::onNewATResponseLine(ATCommandsInterface* pInst, const char* line) +{ + if(m_state == SMS_SEND_CMD_SENT) + { + DBG("SMS Send: %s", line); + } + else if(m_state == SMS_GET_TX_STATUS_CMD_SENT) + { + if(!strcmp(line, "sent")) + { + m_txState = SMS_SENT; + m_state = SMS_CMD_PROCESSED; + } + else if(!strcmp(line, "failed")) + { + m_txState = SMS_FAILED; + m_state = SMS_CMD_PROCESSED; + } + else if(!strcmp(line, "none")) + { + m_txState = SMS_NONE; + m_state = SMS_CMD_PROCESSED; + } + else if(!strcmp(line, "pending")) + { + m_txState = SMS_PENDING; + m_state = SMS_CMD_PROCESSED; + } + } + else if(m_state == SMS_GET_CMD_SENT) + { + DBG("Header: %s", line); + + if(m_msisdn[0]=='\0') + { + sscanf(line, "From: %16s", m_msisdn); + } + + m_headersToRead--; + + if(m_headersToRead==0) //End of headers + { + if(m_msisdn[0]!='\0') //Checks that the incoming number has been retrieved + { + m_state = SMS_GET_HDR_RECEIVED; + } + else + { + m_state = SMS_IDLE; //Error, signal it + } + } + } + else if(m_state == SMS_GET_HDR_RECEIVED) + { + DBG("Message: %s", line); + size_t cpyLen = MIN( std::strlen(line), m_maxMsgLength - 1 ); + std::memcpy( m_msg, line, cpyLen ); + m_msg[cpyLen] = '\0'; + m_state = SMS_CMD_PROCESSED; + } + else if(m_state == SMS_GET_COUNT_CMD_SENT) + { + DBG("Inbox: %s", line); + int index; + size_t count; + if((strlen(line) > 16) && sscanf(line + 16, "{Index = %d}: %d", &index, &count) == 2) + { + if((index > 0) && (index <=4)) + { + m_msgInListsCount[index-1] = count; + } + if(index == 4) + { + m_state = SMS_CMD_PROCESSED; + } + } + } + return OK; +} + +/*virtual*/ int CDMASMSInterface::onNewEntryPrompt(ATCommandsInterface* pInst) +{ + return OK; +} + + +int CDMASMSInterface::updateInbox() +{ + //Get number of unread/read messages + + DBG("Updating inbox"); + m_msgInListsCount[0] = m_msgInListsCount[1] = m_msgInListsCount[2] = m_msgInListsCount[3] = 0; //Reset counts + + //Get counts + m_state = SMS_GET_COUNT_CMD_SENT; + int ret = m_pIf->execute("AT!CNTSMS", this, NULL, DEFAULT_TIMEOUT); + if( ret != OK ) + { + WARN("AT!CNTSMS returned %d", ret); + m_msgInListsCount[0] = m_msgInListsCount[1] = m_msgInListsCount[2] = m_msgInListsCount[3] = 0; //Invalidate counts + m_state = SMS_IDLE; + return NET_PROTOCOL; + } + + return OK; +} + diff --git a/features/unsupported/net/cellular/CellularModem/sms/CDMASMSInterface.h b/features/unsupported/net/cellular/CellularModem/sms/CDMASMSInterface.h new file mode 100644 index 00000000000..6aa4557c364 --- /dev/null +++ b/features/unsupported/net/cellular/CellularModem/sms/CDMASMSInterface.h @@ -0,0 +1,90 @@ +/* SMSInterface.h */ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef CDMASMSINTERFACE_H_ +#define CDMASMSINTERFACE_H_ + +#include "SMSInterface.h" + +#define MAX_SM 8 + +/** Component to use the Short Messages Service (SMS) + * + */ +class CDMASMSInterface : public ISMSInterface, protected IATCommandsProcessor +{ +public: + /** Create SMSInterface instance + @param pIf Pointer to the ATCommandsInterface instance to use + */ + CDMASMSInterface(ATCommandsInterface* pIf); + + /** Initialize interface + Configure SMS commands & register for SMS-related unsolicited result codes + */ + virtual int init(); + + /** Send a SM + @param number The receiver's phone number + @param message The message to send + @return 0 on success, error code on failure + */ + virtual int send(const char* number, const char* message); + + + /** Receive a SM + @param number Pointer to a buffer to store the sender's phone number (must be at least 17 characters-long, including the space for the null-terminating char) + @param message Pointer to a buffer to store the the incoming message + @param maxLength Maximum message length that can be stored in buffer (including null-terminating character) + @return 0 on success, error code on failure + */ + virtual int get(char* number, char* message, size_t maxLength); + + + /** Get the number of SMs in the incoming box + @param pCount pointer to store the number of unprocessed SMs on + @return 0 on success, error code on failure + */ + virtual int getCount(size_t* pCount); + +protected: + //IATCommandsProcessor + virtual int onNewATResponseLine(ATCommandsInterface* pInst, const char* line); + virtual int onNewEntryPrompt(ATCommandsInterface* pInst); + + int updateInbox(); //Update messages count in the different inboxes + +private: + ATCommandsInterface* m_pIf; + + //Current message + char* m_msg; + size_t m_maxMsgLength; + char* m_msisdn; + + //Messages list + size_t m_msgInListsCount[4]; //4 lists + + size_t m_headersToRead; + + enum { SMS_NONE, SMS_SENT, SMS_PENDING, SMS_FAILED } m_txState; + enum { SMS_IDLE, SMS_SEND_CMD_SENT, SMS_GET_TX_STATUS_CMD_SENT, SMS_GET_CMD_SENT, SMS_GET_HDR_RECEIVED, SMS_GET_COUNT_CMD_SENT, SMS_CMD_PROCESSED } m_state; +}; + +#endif /* CDMASMSINTERFACE_H_ */ diff --git a/features/unsupported/net/cellular/CellularModem/sms/GSMSMSInterface.cpp b/features/unsupported/net/cellular/CellularModem/sms/GSMSMSInterface.cpp new file mode 100644 index 00000000000..2ed50ad1262 --- /dev/null +++ b/features/unsupported/net/cellular/CellularModem/sms/GSMSMSInterface.cpp @@ -0,0 +1,423 @@ +/* GSMSMSInterface.cpp */ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#define __DEBUG__ 2 +#ifndef __MODULE__ +#define __MODULE__ "GSMSMSInterface.cpp" +#endif + +#include "core/fwk.h" + +#include "GSMSMSInterface.h" + +#include +#include + +#define DEFAULT_TIMEOUT 10000 + +GSMSMSInterface::GSMSMSInterface(ATCommandsInterface* pIf) : m_pIf(pIf), m_msg(NULL), m_maxMsgLength(0), m_msisdn(NULL) +{ + m_pIf->registerEventsHandler(this); //Add us to the unsolicited result codes handlers +} + +int GSMSMSInterface::init() +{ + m_msgRefListCount = 0; + m_needsUpdate = true; + m_state = SMS_IDLE; + + DBG("Set format"); + //Set Text mode format + int ret = m_pIf->executeSimple("AT+CMGF=1", NULL, DEFAULT_TIMEOUT); + if(ret != OK) + { + return NET_PROTOCOL; + } + + DBG("Setup new messages indication"); + //Setup new messages indication + ret = m_pIf->executeSimple("AT+CNMI=2,1,0,0,0", NULL, DEFAULT_TIMEOUT); + if(ret != OK) + { + return NET_PROTOCOL; + } + + DBG("Try to fetch inbox"); + m_inboxMtx.lock(); + if( m_needsUpdate ) + { + ret = updateInbox(); //Fetch existing messages references + if(ret) + { + m_inboxMtx.unlock(); + return NET_PROTOCOL; + } + } + m_inboxMtx.unlock(); + + DBG("Initialization done"); + return OK; +} + +int GSMSMSInterface::send(const char* number, const char* message) +{ + if( strlen(number) > 16 ) + { + return NET_INVALID; //Number too long to match 3GPP spec + } + + int ret; + + //Prepare infos + m_state = SMS_SEND_CMD_SENT; + m_msg = (char*) message; + + DBG("Send SM"); + //Send command + char cmd[32]; + std::sprintf(cmd, "AT+CMGS=\"%s\"", number); + ret = m_pIf->execute(cmd, this, NULL, DEFAULT_TIMEOUT); + + if( (ret != OK) || (m_state != SMS_CMD_PROCESSED) ) + { + WARN("ret %d, state %d", ret, m_state); + m_state = SMS_IDLE; + return NET_PROTOCOL; + } + + DBG("SM sent"); + m_state = SMS_IDLE; + return OK; +} + + +int GSMSMSInterface::get(char* number, char* message, size_t maxLength) +{ + if( maxLength < 1 ) + { + return NET_INVALID; //Buffer too short + } + + int ret; + + DBG("Get next message"); + m_inboxMtx.lock(); + if( ((m_msgRefListCount == 0) && m_needsUpdate) || ((m_msgRefListCount > 0) && (m_msgRefList[0] == -1)) ) + { + DBG("Message list count is 0 and needs updating or next index is unknown, calling updateInbox()"); + ret = updateInbox(); + + if (ret) + { + m_inboxMtx.unlock(); + return ret; + } + } + + DBG("%d messages to read", m_msgRefListCount); + + if(m_msgRefListCount == 0) + { + m_inboxMtx.unlock(); + DBG("Message list count is 0, I think it's empty and returning."); + return NET_EMPTY; //No message to read + } + + //Prepare infos + m_state = SMS_GET_CMD_SENT; + m_msisdn = (char*) number; + m_msg = (char*) message; + m_maxMsgLength = maxLength; + + DBG("Get SMS"); + //List command + char cmd[32]; + std::sprintf(cmd, "AT+CMGR=%d", m_msgRefList[0]); + ret = m_pIf->execute(cmd, this, NULL, DEFAULT_TIMEOUT); + if( ret != OK ) + { + WARN("AT+CMGR returned %d", ret); + m_state = SMS_IDLE; + m_inboxMtx.unlock(); + return NET_PROTOCOL; + } + + if (m_state != SMS_CMD_PROCESSED) + { + WARN("State variable is not 'SMS_CMD_PROCESSED' - returning 'NET_EMPTY'"); + } + + DBG("Deleting message from index number: %d", m_msgRefList[0] ); + //Delete message from outbox + std::sprintf(cmd, "AT+CMGD=%d", m_msgRefList[0]); + ret = m_pIf->executeSimple(cmd, NULL, DEFAULT_TIMEOUT); + if(ret != OK) + { + ERR("Could not delete message"); + } + //Remove message from list + std::memmove(&m_msgRefList[0], &m_msgRefList[1], MIN(m_msgRefListCount-1,MAX_SM-1)*sizeof(m_msgRefList[0])); + m_msgRefListCount--; + + if(m_msgRefListCount > MAX_SM - 1) //Last message index is unknown, so put -1 to tell the lib to fetch it when needed + { + DBG("Last message index is unknown, will need to be updated"); + m_msgRefList[MAX_SM - 1] = -1; + } + + DBG("%d messages to read", m_msgRefListCount); + + if (m_state != SMS_CMD_PROCESSED) + { + m_state = SMS_IDLE; + m_inboxMtx.unlock(); + return NET_EMPTY; + } + + m_state = SMS_IDLE; + m_inboxMtx.unlock(); + + return OK; +} + + +int GSMSMSInterface::getCount(size_t* pCount) +{ + int ret; + + m_inboxMtx.lock(); + if( m_needsUpdate ) + { + ret = updateInbox(); + if(ret) + { + m_inboxMtx.unlock(); + return NET_PROTOCOL; + } + } + + *pCount = m_msgRefListCount; + m_inboxMtx.unlock(); + + return OK; +} + + +/*virtual*/ int GSMSMSInterface::onNewATResponseLine(ATCommandsInterface* pInst, const char* line) +{ + if(m_state == SMS_SEND_CMD_SENT) + { + if( std::sscanf(line, "+CMGS: %*d") == 0 ) + { + DBG("SM sent"); + m_state = SMS_CMD_PROCESSED; + } + } + else if(m_state == SMS_GET_CMD_SENT) + { + DBG("Header: %s", line); + if( std::sscanf(line, "+CMGR: %*[^,],\"%16[^\"]\"", m_msisdn) == 1 ) //Get message ref + { + m_state = SMS_GET_HDR_RECEIVED; + } + } + else if(m_state == SMS_GET_HDR_RECEIVED) + { + DBG("Message: %s", line); + size_t cpyLen = MIN( std::strlen(line), m_maxMsgLength - 1 ); + std::memcpy( m_msg, line, cpyLen ); + m_msg[cpyLen] = '\0'; + m_state = SMS_CMD_PROCESSED; + } + else if(m_state == SMS_GET_COUNT_CMD_SENT) + { + DBG("Header: %s", line); + int msgRef; + if( std::sscanf(line, "+CMGL: %d,\"REC", &msgRef) == 1 ) //Filter on REC READ and REC UNREAD messages + { + m_state = SMS_GET_COUNT_HDR_RECEIVED; + //Add message to list + if(m_msgRefListCount < MAX_SM) + { + m_msgRefList[m_msgRefListCount] = msgRef; + } + m_msgRefListCount++; //Always count message + DBG("m_msgRefListCount=%d",m_msgRefListCount); + } + } + else if(m_state == SMS_GET_COUNT_HDR_RECEIVED) + { + DBG("Message (debug only): %s", line); //For debug only + m_state = SMS_GET_COUNT_CMD_SENT; + } + return OK; +} + +/*virtual*/ int GSMSMSInterface::onNewEntryPrompt(ATCommandsInterface* pInst) +{ + if(m_state == SMS_SEND_CMD_SENT) + { + char* crPtr = strchr(m_msg, CR); + if(crPtr != NULL) + { + int crPos = crPtr - m_msg; + //Replace m_inputBuf[crPos] with null-terminating char + m_msg[crPos] = '\x0'; + + //If there is a CR char, split message there + + //Do print the message + int ret = pInst->sendData(m_msg); + if(ret) + { + return ret; + } + + char cr[2] = {CR, '\0'}; + ret = pInst->sendData(cr); + if(ret) + { + return ret; + } + + m_msg += crPos; + + if(m_msg[0] == LF) + { + m_msg++; //Discard LF char as well + } + + return NET_MOREINFO; + } + else + { + //Do print the message + pInst->sendData(m_msg); + return OK; + } + } + + return OK; +} + +/*virtual*/ bool GSMSMSInterface::isATCodeHandled(const char* atCode) //Is this AT code handled +{ + DBG("AT code is %s", atCode); + if( strcmp("+CMTI", atCode) == 0 ) + { + return true; + } + + DBG("Not handled"); + return false; +} + +/*virtual*/ void GSMSMSInterface::onDispatchStart() +{ + +} + +/*virtual*/ void GSMSMSInterface::onDispatchStop() +{ + +} + +/*virtual*/ char* GSMSMSInterface::getEventsEnableCommand() +{ + return "AT+CNMI=2,1,0,0,0"; +} + +/*virtual*/ char* GSMSMSInterface::getEventsDisableCommand() +{ + return "AT+CNMI=0,0,0,0,0"; //Indications will be buffered within the modem and flushed back when the former command is executed +} + +/*virtual*/ void GSMSMSInterface::onEvent(const char* atCode, const char* evt) +{ + if( strcmp("+CMTI", atCode) != 0 ) + { + return; //Not supported + } + + DBG("Unsollicited result code: %s - %s", atCode, evt); + + //Get index + int msgRef; + if(( std::sscanf(evt, "\"SM\",%d", &msgRef) == 1 ) || + ( std::sscanf(evt, "\"ME\",%d", &msgRef) == 1 )) + { + DBG("Adding message to list (ref %d)", msgRef); + if(m_inboxMtx.trylock()) + { + //Add message to list + if(m_msgRefListCount < MAX_SM) + { + m_msgRefList[m_msgRefListCount] = msgRef; + } + m_msgRefListCount++; //Always count message + m_inboxMtx.unlock(); + } + else + { + WARN("Could not get lock"); + m_needsUpdate = true; + } + } +} + +int GSMSMSInterface::updateInbox() +{ + //Get memory indexes of unread messages + + DBG("Updating inbox"); + m_msgRefListCount = 0; //Reset list + m_needsUpdate = false; //Assume we won't need update after this routine (can be set to true by an incoming SM event) + + //First list the "REC READ" messages that were not processed in the previous session + m_state = SMS_GET_COUNT_CMD_SENT; + int ret = m_pIf->execute("AT+CMGL=\"REC READ\"", this, NULL, DEFAULT_TIMEOUT); + if( ret != OK ) + { + WARN("AT+CMGL returned %d", ret); + m_state = SMS_IDLE; + m_msgRefListCount = 0; //List could be invalid + m_needsUpdate = true; + return NET_PROTOCOL; + } + + //Now list the "REC UNREAD" messages that were received by the modem since + m_state = SMS_GET_COUNT_CMD_SENT; + ret = m_pIf->execute("AT+CMGL=\"REC UNREAD\"", this, NULL, DEFAULT_TIMEOUT); + if( ret != OK ) + { + WARN("AT+CMGL returned %d", ret); + m_state = SMS_IDLE; + m_msgRefListCount = 0; //List could be invalid + m_needsUpdate = true; + return NET_PROTOCOL; + } + + DBG("%d incoming messages in inbox", m_msgRefListCount); + + m_state = SMS_IDLE; + + return OK; +} + + diff --git a/features/unsupported/net/cellular/CellularModem/sms/GSMSMSInterface.h b/features/unsupported/net/cellular/CellularModem/sms/GSMSMSInterface.h new file mode 100644 index 00000000000..446a73e518a --- /dev/null +++ b/features/unsupported/net/cellular/CellularModem/sms/GSMSMSInterface.h @@ -0,0 +1,97 @@ +/* SMSInterface.h */ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef GSMSMSINTERFACE_H_ +#define GSMSMSINTERFACE_H_ + +#include "SMSInterface.h" + +/** Component to use the Short Messages Service (SMS) + * + */ +class GSMSMSInterface : public ISMSInterface, protected IATCommandsProcessor, IATEventsHandler +{ +public: + /** Create SMSInterface instance + @param pIf Pointer to the ATCommandsInterface instance to use + */ + GSMSMSInterface(ATCommandsInterface* pIf); + + /** Initialize interface + Configure SMS commands & register for SMS-related unsolicited result codes + */ + virtual int init(); + + /** Send a SM + @param number The receiver's phone number + @param message The message to send + @return 0 on success, error code on failure + */ + virtual int send(const char* number, const char* message); + + + /** Receive a SM + @param number Pointer to a buffer to store the sender's phone number (must be at least 17 characters-long, including the space for the null-terminating char) + @param message Pointer to a buffer to store the the incoming message + @param maxLength Maximum message length that can be stored in buffer (including null-terminating character) + @return 0 on success, error code on failure + */ + virtual int get(char* number, char* message, size_t maxLength); + + + /** Get the number of SMs in the incoming box + @param pCount pointer to store the number of unprocessed SMs on + @return 0 on success, error code on failure + */ + virtual int getCount(size_t* pCount); + +protected: + //IATCommandsProcessor + virtual int onNewATResponseLine(ATCommandsInterface* pInst, const char* line); + virtual int onNewEntryPrompt(ATCommandsInterface* pInst); + + //IATEventsHandler + virtual bool isATCodeHandled(const char* atCode); //Is this AT code handled + virtual void onDispatchStart(); + virtual void onDispatchStop(); + virtual char* getEventsEnableCommand(); + virtual char* getEventsDisableCommand(); + virtual void onEvent(const char* atCode, const char* evt); + + //Updates messages count/references + int updateInbox(); + +private: + ATCommandsInterface* m_pIf; + + //Current message + char* m_msg; + size_t m_maxMsgLength; + char* m_msisdn; + + //Messages list + int m_msgRefList[MAX_SM]; + size_t m_msgRefListCount; + bool m_needsUpdate; + Mutex m_inboxMtx; //To protect concurrent accesses btw the user's thread and the AT thread + + enum { SMS_IDLE, SMS_SEND_CMD_SENT, SMS_GET_CMD_SENT, SMS_GET_HDR_RECEIVED, SMS_GET_COUNT_CMD_SENT, SMS_GET_COUNT_HDR_RECEIVED, SMS_CMD_PROCESSED } m_state; +}; + +#endif /* GSMSMSINTERFACE_H_ */ diff --git a/features/unsupported/net/cellular/CellularModem/sms/SMSInterface.h b/features/unsupported/net/cellular/CellularModem/sms/SMSInterface.h new file mode 100644 index 00000000000..df226709d10 --- /dev/null +++ b/features/unsupported/net/cellular/CellularModem/sms/SMSInterface.h @@ -0,0 +1,67 @@ +/* SMSInterface.h */ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef ISMSINTERFACE_H_ +#define ISMSINTERFACE_H_ + +#include "core/fwk.h" + +#include "rtos.h" + +#include "at/ATCommandsInterface.h" + +#define MAX_SM 8 + +/** Component to use the Short Messages Service (SMS) + * + */ +class ISMSInterface +{ +public: + /** Initialize interface + Configure SMS commands & register for SMS-related unsolicited result codes + */ + virtual int init() = 0; + + + /** Send a SM + @param number The receiver's phone number + @param message The message to send + @return 0 on success, error code on failure + */ + virtual int send(const char* number, const char* message) = 0; + + + /** Receive a SM + @param number Pointer to a buffer to store the sender's phone number (must be at least 17 characters-long, including the space for the null-terminating char) + @param message Pointer to a buffer to store the the incoming message + @param maxLength Maximum message length that can be stored in buffer (including null-terminating character) + @return 0 on success, error code on failure + */ + virtual int get(char* number, char* message, size_t maxLength) = 0; + + + /** Get the number of SMs in the incoming box + @param pCount pointer to store the number of unprocessed SMs on + @return 0 on success, error code on failure + */ + virtual int getCount(size_t* pCount) = 0; +}; + +#endif /* ISMSINTERFACE_H_ */ diff --git a/features/unsupported/net/cellular/CellularModem/ussd/USSDInterface.cpp b/features/unsupported/net/cellular/CellularModem/ussd/USSDInterface.cpp new file mode 100644 index 00000000000..4815babd6a0 --- /dev/null +++ b/features/unsupported/net/cellular/CellularModem/ussd/USSDInterface.cpp @@ -0,0 +1,196 @@ +/* USSDInterface.cpp */ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#define __DEBUG__ 0 +#ifndef __MODULE__ +#define __MODULE__ "USSDInterface.cpp" +#endif + +#include "core/fwk.h" + +#include "USSDInterface.h" + +#include + +#define DEFAULT_TIMEOUT 10000 +#define USSD_TIMEOUT 15000 + +USSDInterface::USSDInterface(ATCommandsInterface* pIf) : m_pIf(pIf), m_responseMtx(), m_responseSphre(1), m_result(NULL), m_maxResultLength(0) +{ + m_responseSphre.wait(0); //Take ownership of the semaphore + m_pIf->registerEventsHandler(this); //Add us to the unsolicited result codes handlers +} + +int USSDInterface::init() +{ + DBG("Initialization done"); + return OK; +} + +int USSDInterface::send(const char* command, char* result, size_t maxLength) +{ + if (strlen(command) > 20) //Prevent buffer overflow + { + return NET_TOOSMALL; + } + + m_responseMtx.lock(); + m_result = result; + m_maxResultLength = maxLength; + m_responseMtx.unlock(); + + m_responseSphre.wait(0); //Make sure there is not a pending result that needs to be discarded + + DBG("Send USSD command & register for unsolicited result codes"); + //Send USSD command to the network + char cmd[32]; + std::sprintf(cmd, "AT+CUSD=1,\"%s\"", command); + int ret = m_pIf->execute(cmd, this, NULL, DEFAULT_TIMEOUT); + if( ret != OK ) + { + return NET_PROTOCOL; + } + + //Did we already get a response (3GPP rev < 6) ? + + //Now wait for response + int res = m_responseSphre.wait(USSD_TIMEOUT); + + //Reset data + m_responseMtx.lock(); + m_result = NULL; + m_maxResultLength = 0; + m_responseMtx.unlock(); + + if(res <= 0) + { + DBG("No result received"); + ret = m_pIf->executeSimple("AT+CUSD=2", NULL, DEFAULT_TIMEOUT); //Cancel command + if( ret != OK ) + { + return NET_PROTOCOL; + } + return NET_TIMEOUT; + } + + DBG("Result received: %s", result); + + return OK; +} + +/*virtual*/ int USSDInterface::onNewATResponseLine(ATCommandsInterface* pInst, const char* line) +{ + const char* pSemicol = strchr(line, ':'); + if( ( (pSemicol - line) != strlen("+CUSD") ) || ( memcmp(line, "+CUSD", strlen("+CUSD")) != 0) ) + { + WARN("Unknown code"); + return OK; + } + + const char* pData = NULL; + if( pSemicol != NULL ) //Split the identifier & the result code (if it exists) + { + pData = pSemicol + 1; + if(pData[0]==' ') + { + pData++; //Suppress whitespace + } + processResult(pData); + } + return OK; +} + +/*virtual*/ int USSDInterface::onNewEntryPrompt(ATCommandsInterface* pInst) +{ + return OK; +} + +/*virtual*/ bool USSDInterface::isATCodeHandled(const char* atCode) //Is this AT code handled +{ + DBG("AT code is %s", atCode); + if( strcmp("+CUSD", atCode) == 0 ) + { + return true; + } + + DBG("Not handled"); + return false; +} + +/*virtual*/ void USSDInterface::onDispatchStart() +{ + + +} + +/*virtual*/ void USSDInterface::onDispatchStop() +{ + +} + +/*virtual*/ char* USSDInterface::getEventsEnableCommand() +{ + return NULL; //No need to disable events here +} + +/*virtual*/ char* USSDInterface::getEventsDisableCommand() +{ + return NULL; //No need to re-enable events here +} + +/*virtual*/ void USSDInterface::onEvent(const char* atCode, const char* evt) +{ + if( strcmp("+CUSD", atCode) != 0 ) + { + WARN("Wrong AT Code"); + return; //Not supported + } + + processResult(evt); +} + +void USSDInterface::processResult(const char* data) +{ + char* pStart = (char*) strchr(data,'\"'); + if(pStart==NULL) + { + WARN("Could not find opening quote"); + return; //Invalid/incomplete response + } + pStart++; //Point to first char of response + char* pEnd = (char*) strchr(pStart,'\"'); + if(pEnd==NULL) + { + WARN("Could not find closing quote"); + return; //Invalid/incomplete response + } + m_responseMtx.lock(); + if(m_maxResultLength == 0) //No pending command + { + WARN("No pending command"); + m_responseMtx.unlock(); + return; + } + size_t cpyLen = MIN( pEnd - pStart, m_maxResultLength - 1 ); + memcpy((void*)m_result, pStart, cpyLen); + m_result[cpyLen] = '\0'; + DBG("Got USSD response: %s", m_result); + m_responseMtx.unlock(); + m_responseSphre.release(); //Signal user thread that response is ready +} diff --git a/features/unsupported/net/cellular/CellularModem/ussd/USSDInterface.h b/features/unsupported/net/cellular/CellularModem/ussd/USSDInterface.h new file mode 100644 index 00000000000..47984d1d911 --- /dev/null +++ b/features/unsupported/net/cellular/CellularModem/ussd/USSDInterface.h @@ -0,0 +1,80 @@ +/* USSDInterface.h */ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef USSDINTERFACE_H_ +#define USSDINTERFACE_H_ + +#include "core/fwk.h" + +#include "rtos.h" + +#include "at/ATCommandsInterface.h" + +/** Component to send/receive Unstructured Supplementary Service Data (USSD) + * + */ +class USSDInterface : protected IATCommandsProcessor, IATEventsHandler +{ +public: + /** Create USSDInterface instance + @param pIf Pointer to the ATCommandsInterface instance to use + */ + USSDInterface(ATCommandsInterface* pIf); + + /** Initialize interface + Configure USSD commands & register for USSD-related unsolicited result codes + */ + int init(); + + /** Send a USSD command & wait for its result + @param command The command to send + @param result Buffer in which to store the result + @param maxLength Maximum result length that can be stored in buffer (including null-terminating character) + @return 0 on success, error code on failure + */ + int send(const char* command, char* result, size_t maxLength); + +protected: + //IATCommandsProcessor, needed for implementations of 3GGP standard < r06 + virtual int onNewATResponseLine(ATCommandsInterface* pInst, const char* line); + virtual int onNewEntryPrompt(ATCommandsInterface* pInst); + + //IATEventsHandler, needed for implementations of 3GGP standard >= r06 + virtual bool isATCodeHandled(const char* atCode); //Is this AT code handled + virtual void onDispatchStart(); + virtual void onDispatchStop(); + virtual char* getEventsEnableCommand(); + virtual char* getEventsDisableCommand(); + virtual void onEvent(const char* atCode, const char* evt); + +private: + void processResult(const char* data); + + ATCommandsInterface* m_pIf; + Mutex m_responseMtx; //To protect concurrent accesses btw the user's thread and the AT thread + Semaphore m_responseSphre; + + //Result + volatile char* m_result; + volatile size_t m_maxResultLength; + +}; + + +#endif /* USSDINTERFACE_H_ */ diff --git a/features/unsupported/net/cellular/CellularUSBModem/serial/io/IOSerialStream.cpp b/features/unsupported/net/cellular/CellularUSBModem/serial/io/IOSerialStream.cpp new file mode 100644 index 00000000000..2a05c1c2c4f --- /dev/null +++ b/features/unsupported/net/cellular/CellularUSBModem/serial/io/IOSerialStream.cpp @@ -0,0 +1,253 @@ +/* IOSerialStream.cpp */ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#define __DEBUG__ 0 //Maximum verbosity +#ifndef __MODULE__ +#define __MODULE__ "IOSerialStream.cpp" +#endif + +#include "core/fwk.h" + +#include + +#include "IOSerialStream.h" + +#define UART_X ((LPC_UART_TypeDef *)(UART_1)) + +IOSerialStream::IOSerialStream(mbed::RawSerial& serial) : m_serial(serial), m_serialTxFifoEmpty(true), +m_availableSphre(1), m_spaceSphre(1), m_inBuf(), m_outBuf() +{ + m_availableSphre.wait(); + m_spaceSphre.wait(); + //Attach interrupts + m_serial.attach(this, &IOSerialStream::readable, mbed::SerialBase::RxIrq); + m_serial.attach(this, &IOSerialStream::writeable, mbed::SerialBase::TxIrq); +} + +/*virtual*/ IOSerialStream::~IOSerialStream() +{ + m_serial.attach(NULL, mbed::SerialBase::RxIrq); + m_serial.attach(NULL, mbed::SerialBase::TxIrq); +} + +//0 for non-blocking (returns immediately), osWaitForever for infinite blocking +/*virtual*/ int IOSerialStream::read(uint8_t* buf, size_t* pLength, size_t maxLength, uint32_t timeout/*=osWaitForever*/) +{ + DBG("Trying to read at most %d chars", maxLength); + int ret = waitAvailable(timeout); + if(ret) + { + WARN("Error %d while waiting for incoming data", ret); + return ret; + } + int readLen = MIN( available(), maxLength ); + *pLength = readLen; + setupReadableISR(false); + while(readLen--) + { + m_inBuf.dequeue(buf); + buf++; + } + setupReadableISR(true); + DBG("Read %d chars successfully", *pLength); + return OK; +} + +/*virtual*/ size_t IOSerialStream::available() +{ + setupReadableISR(false); //m_inBuf.available() is not reentrant + size_t len = m_inBuf.available(); + setupReadableISR(true); + return len; +} + +/*virtual*/ int IOSerialStream::waitAvailable(uint32_t timeout/*=osWaitForever*/) //Wait for data to be available +{ + int ret; + if(available()) //Is data already available? + { + m_availableSphre.wait(0); //Clear the queue as data is available + return OK; + } + + DBG("Waiting for data availability %d ms (-1 is infinite)", timeout); + ret = m_availableSphre.wait(timeout); //Wait for data to arrive or for abort + if(ret <= 0) + { + DBG("Timeout"); + return NET_TIMEOUT; + } + if(!available()) //Even if abort has been called, return that data is available + { + DBG("Aborted"); + return NET_INTERRUPTED; + } + DBG("Finished waiting"); + m_availableSphre.wait(0); //Clear the queue as data is available + return OK; +} + +/*virtual*/ int IOSerialStream::abortRead() //Abort current reading (or waiting) operation +{ + if( !available() ) //If there is data pending, no need to abort + { + m_availableSphre.release(); //Force exiting the waiting state; kludge to pass a RC directly + } + else + { + DBG("Serial is readable"); ; + } + return OK; +} + +void IOSerialStream::setupReadableISR(bool en) +{ + if(en) + { + UART_X->IER |= 1 << 0; + } + else + { + UART_X->IER &= ~(1 << 0); + } +} + +void IOSerialStream::readable() //Callback from m_serial when new data is available +{ + do + { + m_inBuf.queue(m_serial.getc()); + } while(m_serial.readable()); + m_availableSphre.release(); //Force exiting the waiting state +} + +//0 for non-blocking (returns immediately), osWaitForever for infinite blocking +/*virtual*/ int IOSerialStream::write(uint8_t* buf, size_t length, uint32_t timeout/*=osWaitForever*/) +{ + DBG("Trying to write %d chars", length); + int ret = waitSpace(timeout); + if(ret) + { + WARN("Error %d while waiting for space", ret); + return ret; + } + DBG("Writing %d chars", length); + setupWriteableISR(false); + while(length) + { + m_outBuf.queue(*buf); + buf++; + length--; + if(length && !space()) + { + DBG("Waiting to write remaining %d chars", length); + setupWriteableISR(true); + ret = waitSpace(timeout); + if(ret) + { + WARN("Error %d while waiting for space", ret); + return ret; + } + setupWriteableISR(false); + } + } + //If m_serial tx fifo is empty we need to manually tx a byte in order to trigger the interrupt + if( m_outBuf.available() && m_serialTxFifoEmpty ) + { + m_serialTxFifoEmpty = false; + uint8_t c; + m_outBuf.dequeue(&c); + m_serial.putc((char)c); + } + setupWriteableISR(true); + DBG("Write successful"); + return OK; +} + +/*virtual*/ size_t IOSerialStream::space() +{ + setupWriteableISR(false); //m_outBuf.available() is not reentrant + size_t len = CIRCBUF_SIZE - m_outBuf.available(); + setupWriteableISR(true); + return len; +} + +/*virtual*/ int IOSerialStream::waitSpace(uint32_t timeout/*=osWaitForever*/) //Wait for space to be available +{ + int ret; + if(space()) //Is still space already left? + { + m_spaceSphre.wait(0); //Clear the queue as space is available + return OK; + } + + DBG("Waiting for data space %d ms (-1 is infinite)", timeout); + ret = m_spaceSphre.wait(timeout); //Wait for space to be made or for abort + if(ret <= 0) + { + DBG("Timeout"); + return NET_TIMEOUT; + } + if(!space()) //Even if abort has been called, return that space is available + { + DBG("Aborted"); + return NET_INTERRUPTED; + } + m_spaceSphre.wait(0); //Clear the queue as space is available + return OK; +} + +/*virtual*/ int IOSerialStream::abortWrite() //Abort current writing (or waiting) operation +{ + if( !space() ) //If there is space left, no need to abort + { + m_spaceSphre.release(); //Force exiting the waiting state + } + return OK; +} + +void IOSerialStream::setupWriteableISR(bool en) +{ + if(en) + { + UART_X->IER |= 1 << 1; + } + else + { + UART_X->IER &= ~(1 << 1); + } +} + +void IOSerialStream::writeable() //Callback from m_serial when new space is available +{ + if(m_outBuf.isEmpty()) + { + m_serialTxFifoEmpty = true; + } + else + { + while(m_serial.writeable() && !m_outBuf.isEmpty()) + { + uint8_t c; + m_outBuf.dequeue(&c); + m_serial.putc((char)c); + } + } + m_spaceSphre.release(); //Force exiting the waiting state +} diff --git a/features/unsupported/net/cellular/CellularUSBModem/serial/io/IOSerialStream.h b/features/unsupported/net/cellular/CellularUSBModem/serial/io/IOSerialStream.h new file mode 100644 index 00000000000..7e9ef89d059 --- /dev/null +++ b/features/unsupported/net/cellular/CellularUSBModem/serial/io/IOSerialStream.h @@ -0,0 +1,72 @@ +/* IOSerialStream.h */ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +#ifndef IOSERIALSTREAM_H_ +#define IOSERIALSTREAM_H_ + +#include "core/fwk.h" + +#include "RawSerial.h" + +#include "rtos.h" +#include "core/MtxCircBuffer.h" + +/** Input Serial Stream for physical serial interfaces (UART...) +This class is not thread-safe, except for the *Abort() methods that can be called by any thread/ISR +*/ +class IOSerialStream : public IOStream +{ +public: + enum { CIRCBUF_SIZE = 255 }; + IOSerialStream(mbed::RawSerial& serial); + /*virtual*/ ~IOSerialStream(); + + //0 for non-blocking (returns immediately), osWaitForever for infinite blocking + virtual int read(uint8_t* buf, size_t* pLength, size_t maxLength, uint32_t timeout=osWaitForever); + virtual size_t available(); + virtual int waitAvailable(uint32_t timeout=osWaitForever); //Wait for data to be available + virtual int abortRead(); //Abort current reading (or waiting) operation + + + //0 for non-blocking (returns immediately), osWaitForever for infinite blocking + virtual int write(uint8_t* buf, size_t length, uint32_t timeout=osWaitForever); + virtual size_t space(); + virtual int waitSpace(uint32_t timeout=osWaitForever); //Wait for space to be available + virtual int abortWrite(); //Abort current writing (or waiting) operation + +private: + + mbed::RawSerial& m_serial; + volatile bool m_serialTxFifoEmpty; + + void setupReadableISR(bool en); + void readable(); //Callback from m_serial when new data is available + + Semaphore m_availableSphre; //Used for signalling + + void setupWriteableISR(bool en); + void writeable(); //Callback from m_serial when new space is available + + Semaphore m_spaceSphre; //Used for signalling + + MtxCircBuffer m_inBuf; + MtxCircBuffer m_outBuf; + +}; + +#endif /* IOSERIALSTREAM_H_ */ diff --git a/features/unsupported/net/cellular/CellularUSBModem/serial/usb/USBSerialStream.cpp b/features/unsupported/net/cellular/CellularUSBModem/serial/usb/USBSerialStream.cpp new file mode 100644 index 00000000000..81349ce8845 --- /dev/null +++ b/features/unsupported/net/cellular/CellularUSBModem/serial/usb/USBSerialStream.cpp @@ -0,0 +1,236 @@ +/* USBSerialStream.cpp */ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#define __DEBUG__ 0 +#ifndef __MODULE__ +#define __MODULE__ "USBSerialStream.cpp" +#endif + +#include "core/fwk.h" + +#include + +#include "USBSerialStream.h" + + +USBSerialStream::USBSerialStream(IUSBHostSerial& serial) : m_serial(serial), m_serialTxFifoEmpty(true), +m_availableSphre(1), m_spaceSphre(1), m_inBuf() +{ + m_availableSphre.wait(); + m_spaceSphre.wait(); + //Attach interrupts + m_serial.attach(this); +} + +/*virtual*/ USBSerialStream::~USBSerialStream() +{ + m_serial.attach(NULL); +} + +//0 for non-blocking (returns immediately), -1 for infinite blocking +/*virtual*/ int USBSerialStream::read(uint8_t* buf, size_t* pLength, size_t maxLength, uint32_t timeout/*=osWaitForever*/) +{ + DBG("Trying to read at most %d chars", maxLength); + int ret = waitAvailable(timeout); + if(ret) + { + WARN("Error %d while waiting for incoming data", ret); + return ret; + } + int a = available(); //Prevent macro issues + int readLen = MIN( a, maxLength ); + *pLength = readLen; + + setupReadableISR(false); + while(readLen--) + { + m_inBuf.dequeue(buf); + buf++; + } + setupReadableISR(true); + DBG("Read %d chars successfully", *pLength); + return OK; +} + +/*virtual*/ size_t USBSerialStream::available() +{ + setupReadableISR(false); //m_inBuf.available() is not reentrant + size_t len = m_inBuf.available(); + setupReadableISR(true); + return len; +} + +/*virtual*/ int USBSerialStream::waitAvailable(uint32_t timeout/*=osWaitForever*/) //Wait for data to be available +{ + int ret; + if(available()) //Is data already available? + { + while( m_availableSphre.wait(0) > 0 ); //Clear the queue as data is available + return OK; + } + + DBG("Waiting for data availability %d ms (-1 is infinite)", timeout); + ret = m_availableSphre.wait(timeout); //Wait for data to arrive or for abort + if(ret <= 0) + { + DBG("Timeout"); + return NET_TIMEOUT; + } + if(!m_inBuf.available()) //Even if abort has been called, return that data is available + { + DBG("Aborted"); + return NET_INTERRUPTED; + } + DBG("Finished waiting"); + while( m_availableSphre.wait(0) > 0 ); //Clear the queue as data is available + return OK; +} + +/*virtual*/ int USBSerialStream::abortRead() //Abort current reading (or waiting) operation +{ + if( /*!available()*/true ) //If there is data pending, no need to abort + { + m_availableSphre.release(); //Force exiting the waiting state + } + else + { + DBG("Serial is readable"); ; + } + return OK; +} + +void USBSerialStream::setupReadableISR(bool en) +{ + m_serial.setupIrq(en, IUSBHostSerial::RxIrq); +} + +void USBSerialStream::readable() //Callback from m_serial when new data is available +{ + while(m_serial.readable()) + { + m_inBuf.queue(m_serial.getc()); + } + m_serial.readPacket(); //Start read of next packet + m_availableSphre.release(); //Force exiting the waiting state +} + +//0 for non-blocking (returns immediately), -1 for infinite blocking +/*virtual*/ int USBSerialStream::write(uint8_t* buf, size_t length, uint32_t timeout/*=-1*/) +{ + DBG("Trying to write %d chars", length); + do + { + int ret = waitSpace(timeout); + if(ret) + { + WARN("Error %d while waiting for space", ret); + return ret; + } + int s = space(); //Prevent macro issues + int writeLen = MIN( s, length ); + DBG("Writing %d chars", writeLen); + setupWriteableISR(false); + while(writeLen) + { + m_outBuf.queue(*buf); + buf++; + length--; + writeLen--; + } + //If m_serial tx fifo is empty we need to start the packet write + if( m_outBuf.available() && m_serialTxFifoEmpty ) + { + writeable(); + } + setupWriteableISR(true); + } while(length); + + DBG("Write successful"); + return OK; +} + +/*virtual*/ size_t USBSerialStream::space() +{ + setupWriteableISR(false); //m_outBuf.available() is not reentrant + size_t len = CIRCBUF_SIZE - m_outBuf.available(); + setupWriteableISR(true); + return len; +} + +/*virtual*/ int USBSerialStream::waitSpace(uint32_t timeout/*=-1*/) //Wait for space to be available +{ + int ret; + if(space()) //Is still space already left? + { + while( m_spaceSphre.wait(0) > 0); //Clear the queue as space is available + return OK; + } + + DBG("Waiting for data space %d ms (-1 is infinite)", timeout); + ret = m_spaceSphre.wait(timeout); //Wait for space to be made or for abort + if(ret <= 0) + { + DBG("Timeout"); + return NET_TIMEOUT; + } + if(!space()) //Even if abort has been called, return that space is available + { + DBG("Aborted"); + return NET_INTERRUPTED; + } + while( m_spaceSphre.wait(0) > 0); //Clear the queue as space is available + return OK; +} + +/*virtual*/ int USBSerialStream::abortWrite() //Abort current writing (or waiting) operation +{ + if( !space() ) //If there is space left, no need to abort + { + m_spaceSphre.release(); //Force exiting the waiting state + } + return OK; +} + +void USBSerialStream::setupWriteableISR(bool en) +{ + m_serial.setupIrq(en, IUSBHostSerial::TxIrq); +} + +void USBSerialStream::writeable() //Callback from m_serial when new space is available +{ + if(m_outBuf.isEmpty()) + { + m_serialTxFifoEmpty = true; + } + else + { + m_serialTxFifoEmpty = false; + while(m_serial.writeable() && !m_outBuf.isEmpty()) + { + uint8_t c; + m_outBuf.dequeue(&c); + m_serial.putc((char)c); + } + m_serial.writePacket(); //Start packet write + } + if(!m_outBuf.isFull()) + { + m_spaceSphre.release(); //Force exiting the waiting state + } +} diff --git a/features/unsupported/net/cellular/CellularUSBModem/serial/usb/USBSerialStream.h b/features/unsupported/net/cellular/CellularUSBModem/serial/usb/USBSerialStream.h new file mode 100644 index 00000000000..97cf3c68601 --- /dev/null +++ b/features/unsupported/net/cellular/CellularUSBModem/serial/usb/USBSerialStream.h @@ -0,0 +1,74 @@ +/* USBSerialStream.h */ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef USBSERIALSTREAM_H_ +#define USBSERIALSTREAM_H_ + + +#include "core/fwk.h" + +#include "USBHost3GModule/IUSBHostSerial.h" +#include "USBHost3GModule/IUSBHostSerialListener.h" + +#include "rtos.h" +#include "core/MtxCircBuffer.h" + +/* Input Serial Stream for USB virtual serial ports interfaces +This class is not thread-safe, except for the *Abort() methods that can be called by any thread/ISR +*/ + +class USBSerialStream : public IOStream, IUSBHostSerialListener +{ +public: + enum { CIRCBUF_SIZE = 127 }; + USBSerialStream(IUSBHostSerial& serial); + /*virtual*/ ~USBSerialStream(); + + //0 for non-blocking (returns immediately), osWaitForever for infinite blocking + virtual int read(uint8_t* buf, size_t* pLength, size_t maxLength, uint32_t timeout=osWaitForever); + virtual size_t available(); + virtual int waitAvailable(uint32_t timeout=osWaitForever); //Wait for data to be available + virtual int abortRead(); //Abort current reading (or waiting) operation + + + //0 for non-blocking (returns immediately), osWaitForever for infinite blocking + virtual int write(uint8_t* buf, size_t length, uint32_t timeout=osWaitForever); + virtual size_t space(); + virtual int waitSpace(uint32_t timeout=osWaitForever); //Wait for space to be available + virtual int abortWrite(); //Abort current writing (or waiting) operation + +private: + IUSBHostSerial& m_serial; + volatile bool m_serialTxFifoEmpty; + + void setupReadableISR(bool en); + virtual void readable(); //Callback from m_serial when new data is available + + Semaphore m_availableSphre; //Used for signalling + + void setupWriteableISR(bool en); + virtual void writeable(); //Callback from m_serial when new space is available + + Semaphore m_spaceSphre; //Used for signalling + + MtxCircBuffer m_inBuf; + MtxCircBuffer m_outBuf; +}; + +#endif /* USBSERIALSTREAM_H_ */ diff --git a/features/unsupported/net/cellular/UbloxUSBModem/UbloxCDMAModemInitializer.cpp b/features/unsupported/net/cellular/UbloxUSBModem/UbloxCDMAModemInitializer.cpp new file mode 100644 index 00000000000..6464afc984a --- /dev/null +++ b/features/unsupported/net/cellular/UbloxUSBModem/UbloxCDMAModemInitializer.cpp @@ -0,0 +1,114 @@ +/* Copyright (c) 2010-2012 mbed.org, MIT License +* +* Permission is hereby granted, free of charge, to any person obtaining a copy of this software +* and associated documentation files (the "Software"), to deal in the Software without +* restriction, including without limitation the rights to use, copy, modify, merge, publish, +* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the +* Software is furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all copies or +* substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING +* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +#define __DEBUG__ 4 +#ifndef __MODULE__ +#define __MODULE__ "UbloxCDMAModemInitializer.cpp" +#endif + +#include "core/dbg.h" + +#include + +#include "UbloxCDMAModemInitializer.h" + +UbloxCDMAModemInitializer::UbloxCDMAModemInitializer(USBHost* pHost) : WANDongleInitializer(pHost) +{ +} + +uint16_t UbloxCDMAModemInitializer::getMSDVid() +{ + return 0x05C6; +} +uint16_t UbloxCDMAModemInitializer::getMSDPid() +{ + return 0x0000; //No MSD mode (presumably) +} + +uint16_t UbloxCDMAModemInitializer::getSerialVid() +{ + return 0x05C6; +} +uint16_t UbloxCDMAModemInitializer::getSerialPid() +{ + return 0x9004; +} + +bool UbloxCDMAModemInitializer::switchMode(USBDeviceConnected* pDev) +{ + return true; +} + +int UbloxCDMAModemInitializer::getSerialPortCount() +{ + return 2; +} + +/*virtual*/ void UbloxCDMAModemInitializer::setVidPid(uint16_t vid, uint16_t pid) +{ + m_currentSerialIntf = 0; + m_currentEndpoint = 0; +} + +/*virtual*/ bool UbloxCDMAModemInitializer::parseInterface(uint8_t intf_nb, uint8_t intf_class, uint8_t intf_subclass, uint8_t intf_protocol) //Must return true if the interface should be parsed +{ + DBG("Interface #%d; Class:%02x; SubClass:%02x; Protocol:%02x", intf_nb, intf_class, intf_subclass, intf_protocol); + + if( intf_class == 0xFF ) { + if( m_currentSerialIntf == 0 || m_currentSerialIntf == 1) { + m_serialIntfMap[m_currentSerialIntf++] = intf_nb; + return true; + } + m_currentSerialIntf++; + } + + return false; +} + +/*virtual*/ bool UbloxCDMAModemInitializer::useEndpoint(uint8_t intf_nb, ENDPOINT_TYPE type, ENDPOINT_DIRECTION dir) //Must return true if the endpoint will be used +{ + DBG("USBEndpoint on Interface #%d; Type:%d; Direction:%d Current %d", intf_nb, type, dir, m_currentEndpoint); + if(type == BULK_ENDPOINT) { + if( intf_nb == 1 || intf_nb == 0) { + m_currentEndpoint++; + return true; + } else { + m_currentEndpoint++; + } + } + + /* + if(type == INTERRUPT_ENDPOINT) { + if( intf_nb == 1) { + m_currentEndpoint++; + return true; + } else { + m_currentEndpoint++; + } + } + */ + + return false; +} + + +/*virtual*/ int UbloxCDMAModemInitializer::getType() +{ + return WAN_DONGLE_TYPE_UBLOX_LISAC200; +} + diff --git a/features/unsupported/net/cellular/UbloxUSBModem/UbloxCDMAModemInitializer.h b/features/unsupported/net/cellular/UbloxUSBModem/UbloxCDMAModemInitializer.h new file mode 100644 index 00000000000..4836680da2e --- /dev/null +++ b/features/unsupported/net/cellular/UbloxUSBModem/UbloxCDMAModemInitializer.h @@ -0,0 +1,63 @@ +/* Copyright (c) 2010-2012 mbed.org, MIT License +* +* Permission is hereby granted, free of charge, to any person obtaining a copy of this software +* and associated documentation files (the "Software"), to deal in the Software without +* restriction, including without limitation the rights to use, copy, modify, merge, publish, +* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the +* Software is furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all copies or +* substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING +* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +#ifndef UBLOXCDMAMODEMINITIALIZER_H +#define UBLOXCDMAMODEMINITIALIZER_H + +#include + +#include "WANDongleInitializer.h" +#include "USBHost.h" +#include "IUSBEnumerator.h" + +enum +{ + WAN_DONGLE_TYPE_UBLOX_LISAC200 = 0xC200, +}; + +class UbloxCDMAModemInitializer : public WANDongleInitializer +{ +public: + UbloxCDMAModemInitializer(USBHost* pHost); + + virtual uint16_t getMSDVid(); + virtual uint16_t getMSDPid(); + + virtual uint16_t getSerialVid(); + virtual uint16_t getSerialPid(); + + virtual bool switchMode(USBDeviceConnected* pDev); + + virtual int getSerialPortCount(); + + virtual void setVidPid(uint16_t vid, uint16_t pid); + + virtual bool parseInterface(uint8_t intf_nb, uint8_t intf_class, uint8_t intf_subclass, uint8_t intf_protocol); //Must return true if the interface should be parsed + + virtual bool useEndpoint(uint8_t intf_nb, ENDPOINT_TYPE type, ENDPOINT_DIRECTION dir); //Must return true if the endpoint will be used + + virtual int getType(); + +private: + + int m_currentSerialIntf; + int m_currentEndpoint; +}; + +#endif + diff --git a/features/unsupported/net/cellular/UbloxUSBModem/UbloxGSMModemInitializer.cpp b/features/unsupported/net/cellular/UbloxUSBModem/UbloxGSMModemInitializer.cpp new file mode 100644 index 00000000000..e28632593a8 --- /dev/null +++ b/features/unsupported/net/cellular/UbloxUSBModem/UbloxGSMModemInitializer.cpp @@ -0,0 +1,131 @@ +/* Copyright (c) 2010-2012 mbed.org, MIT License +* +* Permission is hereby granted, free of charge, to any person obtaining a copy of this software +* and associated documentation files (the "Software"), to deal in the Software without +* restriction, including without limitation the rights to use, copy, modify, merge, publish, +* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the +* Software is furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all copies or +* substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING +* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +#include "UbloxGSMModemInitializer.h" +#include "core/dbg.h" + +#define __DEBUG__ 0 +#ifndef __MODULE__ +#define __MODULE__ "UbloxGSMModemInitializer.cpp" +#endif + +//----------------------------------------------------------------------- +// mamm, u-blox Modem +//----------------------------------------------------------------------- + +UbloxGSMModemInitializer::UbloxGSMModemInitializer(USBHost* pHost) : WANDongleInitializer(pHost) +{ + +} + +uint16_t UbloxGSMModemInitializer::getMSDVid() { return 0x1546; } +uint16_t UbloxGSMModemInitializer::getMSDPid() { return 0x0000; } + +uint16_t UbloxGSMModemInitializer::getSerialVid() { return 0x1546; } +uint16_t UbloxGSMModemInitializer::getSerialPid() { return 0x1102; } + +bool UbloxGSMModemInitializer::switchMode(USBDeviceConnected* pDev) +{ + for (int i = 0; i < pDev->getNbIntf(); i++) + { + if (pDev->getInterface(i)->intf_class == MSD_CLASS) + { + USBEndpoint* pEp = pDev->getEndpoint(i, BULK_ENDPOINT, OUT); + if ( pEp != NULL ) + { + ERR("MSD descriptor found on device %p, intf %d", (void *)pDev, i); + } + } + } + return false; +} + +#define UBX_SERIALCOUNT 7 + +int UbloxGSMModemInitializer::getSerialPortCount() +{ + return UBX_SERIALCOUNT; +} + +/*virtual*/ void UbloxGSMModemInitializer::setVidPid(uint16_t vid, uint16_t pid) +{ + if( (vid == getSerialVid() ) && ( pid == getSerialPid() ) ) + { + m_hasSwitched = true; + m_currentSerialIntf = 0; + m_endpointsToFetch = UBX_SERIALCOUNT*2; + } + else + { + m_hasSwitched = false; + m_endpointsToFetch = 1; + } +} + +/*virtual*/ bool UbloxGSMModemInitializer::parseInterface(uint8_t intf_nb, uint8_t intf_class, uint8_t intf_subclass, uint8_t intf_protocol) //Must return true if the interface should be parsed +{ + if( m_hasSwitched ) + { + DBG("Interface #%d; Class:%02x; SubClass:%02x; Protocol:%02x", intf_nb, intf_class, intf_subclass, intf_protocol); + if( intf_class == 0x0A ) + { + if( (m_currentSerialIntf == 0) || (m_currentSerialIntf == 1) ) + { + m_serialIntfMap[m_currentSerialIntf++] = intf_nb; + return true; + } + m_currentSerialIntf++; + } + } + else + { + if( (intf_nb == 0) && (intf_class == MSD_CLASS) ) + { + return true; + } + } + return false; +} + +/*virtual*/ bool UbloxGSMModemInitializer::useEndpoint(uint8_t intf_nb, ENDPOINT_TYPE type, ENDPOINT_DIRECTION dir) //Must return true if the endpoint will be used +{ + if( m_hasSwitched ) + { + DBG("USBEndpoint on Interface #%d; Type:%d; Direction:%d", intf_nb, type, dir); + if( (type == BULK_ENDPOINT) && m_endpointsToFetch ) + { + m_endpointsToFetch--; + return true; + } + } + else + { + if( (type == BULK_ENDPOINT) && (dir == OUT) && m_endpointsToFetch ) + { + m_endpointsToFetch--; + return true; + } + } + return false; +} + +/*virtual*/ int UbloxGSMModemInitializer::getType() +{ + return WAN_DONGLE_TYPE_UBLOX_LISAU200; +} + diff --git a/features/unsupported/net/cellular/UbloxUSBModem/UbloxGSMModemInitializer.h b/features/unsupported/net/cellular/UbloxUSBModem/UbloxGSMModemInitializer.h new file mode 100644 index 00000000000..383c443eb36 --- /dev/null +++ b/features/unsupported/net/cellular/UbloxUSBModem/UbloxGSMModemInitializer.h @@ -0,0 +1,63 @@ +/* Copyright (c) 2010-2012 mbed.org, MIT License +* +* Permission is hereby granted, free of charge, to any person obtaining a copy of this software +* and associated documentation files (the "Software"), to deal in the Software without +* restriction, including without limitation the rights to use, copy, modify, merge, publish, +* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the +* Software is furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all copies or +* substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING +* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +#ifndef UBLOXGSMMODEMINITIALIZER_H +#define UBLOXGSNMODEMINITIALIZER_H + +#include "WANDongleInitializer.h" + +enum +{ + WAN_DONGLE_TYPE_UBLOX_LISAU200 = 0x0200 +}; + +//----------------------------------------------------------------------- +// mamm, u-blox Modem +//----------------------------------------------------------------------- + +class UbloxGSMModemInitializer : public WANDongleInitializer +{ +public: + UbloxGSMModemInitializer(USBHost* pHost); + + virtual uint16_t getMSDVid(); + virtual uint16_t getMSDPid(); + + virtual uint16_t getSerialVid(); + virtual uint16_t getSerialPid(); + + virtual bool switchMode(USBDeviceConnected* pDev); + + virtual int getSerialPortCount(); + + virtual void setVidPid(uint16_t vid, uint16_t pid); + + virtual bool parseInterface(uint8_t intf_nb, uint8_t intf_class, uint8_t intf_subclass, uint8_t intf_protocol); //Must return true if the interface should be parsed + + virtual bool useEndpoint(uint8_t intf_nb, ENDPOINT_TYPE type, ENDPOINT_DIRECTION dir); //Must return true if the endpoint will be used + + virtual int getType(); + +private: + + bool m_hasSwitched; + int m_currentSerialIntf; + int m_endpointsToFetch; +}; + +#endif diff --git a/features/unsupported/net/cellular/UbloxUSBModem/UbloxModem.cpp b/features/unsupported/net/cellular/UbloxUSBModem/UbloxModem.cpp new file mode 100644 index 00000000000..a9fec4cbf05 --- /dev/null +++ b/features/unsupported/net/cellular/UbloxUSBModem/UbloxModem.cpp @@ -0,0 +1,559 @@ +/* UbloxModem.cpp */ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#define __DEBUG__ 3 +#ifndef __MODULE__ +#define __MODULE__ "UbloxModem.cpp" +#endif + +#include "core/fwk.h" +#include "sms/GSMSMSInterface.h" +#include "sms/CDMASMSInterface.h" + +#include "UbloxModem.h" + +UbloxModem::UbloxModem(IOStream* atStream, IOStream* pppStream) : + m_at(atStream), // Construct ATCommandsInterface with the AT serial channel + m_CdmaSms(&m_at), // Construct SMSInterface with the ATCommandsInterface + m_GsmSms(&m_at), // Construct SMSInterface with the ATCommandsInterface + m_ussd(&m_at), // Construct USSDInterface with the ATCommandsInterface + m_linkMonitor(&m_at), // Construct LinkMonitor with the ATCommandsInterface + m_ppp(pppStream ? pppStream : atStream), // Construct PPPIPInterface with the PPP serial channel + m_ipInit(false), // PPIPInterface connection is initially down + m_smsInit(false), // SMSInterface starts un-initialised + m_ussdInit(false), // USSDInterface starts un-initialised + m_linkMonitorInit(false), // LinkMonitor subsystem starts un-initialised + m_atOpen(false), // ATCommandsInterface starts in a closed state + m_onePort(pppStream == NULL), + m_type(UNKNOWN) +{ +} + + +genericAtProcessor::genericAtProcessor() +{ + i = 0; + str[0] = '\0'; +} + +const char* genericAtProcessor::getResponse(void) +{ + return str; +} + +int genericAtProcessor::onNewATResponseLine(ATCommandsInterface* pInst, const char* line) +{ + int l = strlen(line); + if (i + l + 2 > sizeof(str)) + return NET_OVERFLOW; + if (i) str[i++] = ','; + strcat(&str[i], line); + i += l; + return OK; +} + +int genericAtProcessor::onNewEntryPrompt(ATCommandsInterface* pInst) +{ + return OK; +} + +class CREGProcessor : public IATCommandsProcessor +{ +public: + CREGProcessor(bool gsm) : status(STATUS_REGISTERING) + { + m_gsm = gsm; + } + enum REGISTERING_STATUS { STATUS_REGISTERING, STATUS_OK, STATUS_FAILED }; + REGISTERING_STATUS getStatus() + { + return status; + } + const char* getAtCommand() + { + return m_gsm ? "AT+CREG?" : "AT+CSS?"; + } +private: + virtual int onNewATResponseLine(ATCommandsInterface* pInst, const char* line) + { + int r; + if (m_gsm) + { + if( sscanf(line, "+CREG: %*d,%d", &r) == 1 ) + { + status = (r == 1 || r == 5) ? STATUS_OK : + (r == 0 || r == 2) ? STATUS_REGISTERING : + // (r == 3) ? STATUS_FAILED : + STATUS_FAILED; + } + } + else + { + char bc[3] = ""; + if(sscanf(line, "%*s %*c,%2s,%*d",bc)==1) + { + status = (strcmp("Z", bc) == 0) ? STATUS_REGISTERING : STATUS_OK; + } + } + return OK; + } + virtual int onNewEntryPrompt(ATCommandsInterface* pInst) + { + return OK; + } + volatile REGISTERING_STATUS status; + bool m_gsm; +}; + +int UbloxModem::connect(const char* apn, const char* user, const char* password) +{ + if( !m_ipInit ) + { + m_ipInit = true; + m_ppp.init(); + } + m_ppp.setup(user, password, (m_type != LISA_C200) ? DEFAULT_MSISDN_GSM : DEFAULT_MSISDN_CDMA); + + int ret = init(); + if(ret) + { + return ret; + } + + if (m_onePort) + { + m_smsInit = false; //SMS status reset + m_ussdInit = false; //USSD status reset + m_linkMonitorInit = false; //Link monitor status reset + } + + ATCommandsInterface::ATResult result; + + if(apn != NULL) + { + char cmd[48]; + int tries = 30; + sprintf(cmd, "AT+CGDCONT=1,\"IP\",\"%s\"", apn); + do //Try 30 times because for some reasons it can fail *a lot* with the K3772-Z dongle + { + ret = m_at.executeSimple(cmd, &result); + DBG("Result of command: Err code=%d", ret); + if(ret) + { + Thread::wait(500); + } + } while(ret && --tries); + DBG("ATResult: AT return=%d (code %d)", result.result, result.code); + DBG("APN set to %s", apn); + } + + //Connect + DBG("Connecting"); + if (m_onePort) + { + m_at.close(); // Closing AT parser + m_atOpen = false; //Will need to be reinitialized afterwards + } + + DBG("Connecting PPP"); + + ret = m_ppp.connect(); + DBG("Result of connect: Err code=%d", ret); + return ret; +} + + +int UbloxModem::disconnect() +{ + DBG("Disconnecting from PPP"); + int ret = m_ppp.disconnect(); + if(ret) + { + ERR("Disconnect returned %d, still trying to disconnect", ret); + } + + //Ugly but leave dongle time to recover + Thread::wait(500); + + if (m_onePort) + { + //ATCommandsInterface::ATResult result; + DBG("Starting AT thread"); + ret = m_at.open(); + if(ret) + { + return ret; + } + } + + DBG("Trying to hangup"); + + if (m_onePort) + { + //Reinit AT parser + ret = m_at.init(false); + DBG("Result of command: Err code=%d\n", ret); + if(ret) + { + m_at.close(); // Closing AT parser + DBG("AT Parser closed, could not complete disconnection"); + return NET_TIMEOUT; + } + + } + return OK; +} + +int UbloxModem::sendSM(const char* number, const char* message) +{ + int ret = init(); + if(ret) + { + return ret; + } + + ISMSInterface* sms; + if (m_type == LISA_C200) sms = &m_CdmaSms; + else sms = &m_GsmSms; + if(!m_smsInit) + { + ret = sms->init(); + if(ret) + { + return ret; + } + m_smsInit = true; + } + + ret = sms->send(number, message); + if(ret) + { + return ret; + } + + return OK; +} + +int UbloxModem::getSM(char* number, char* message, size_t maxLength) +{ + int ret = init(); + if(ret) + { + return ret; + } + + ISMSInterface* sms; + if (m_type == LISA_C200) sms = &m_CdmaSms; + else sms = &m_GsmSms; + if(!m_smsInit) + { + ret = sms->init(); + if(ret) + { + return ret; + } + m_smsInit = true; + } + + ret = sms->get(number, message, maxLength); + if(ret) + { + return ret; + } + + return OK; +} + +int UbloxModem::getSMCount(size_t* pCount) +{ + int ret = init(); + if(ret) + { + return ret; + } + + ISMSInterface* sms; + if (m_type == LISA_C200) sms = &m_CdmaSms; + else sms = &m_GsmSms; + if(!m_smsInit) + { + ret = sms->init(); + if(ret) + { + return ret; + } + m_smsInit = true; + } + + ret = sms->getCount(pCount); + if(ret) + { + return ret; + } + + return OK; +} + +ATCommandsInterface* UbloxModem::getATCommandsInterface() +{ + return &m_at; +} + +int UbloxModem::init() +{ + if(m_atOpen) + { + return OK; + } + + DBG("Starting AT thread if needed"); + int ret = m_at.open(); + if(ret) + { + return ret; + } + + DBG("Sending initialisation commands"); + ret = m_at.init(false); + if(ret) + { + return ret; + } + + + ATCommandsInterface::ATResult result; + genericAtProcessor atiProcessor; + ret = m_at.execute("ATI", &atiProcessor, &result); + if (OK != ret) + return ret; + const char* info = atiProcessor.getResponse(); + INFO("Modem Identification [%s]", info); + if (strstr(info, "LISA-C200")) { + m_type = LISA_C200; + m_onePort = true; // force use of only one port + } + else if (strstr(info, "LISA-U200")) { + m_type = LISA_U200; + } + else if (strstr(info, "SARA-G350")) { + m_type = SARA_G350; + } + + // enable the network indicator + if (m_type == SARA_G350) { + m_at.executeSimple("AT+UGPIOC=16,2", &result); + } + else if (m_type == LISA_U200) { + m_at.executeSimple("AT+UGPIOC=20,2", &result); + } + else if (m_type == LISA_C200) { + // LISA-C200 02S/22S : GPIO1 do not support network status indication + // m_at.executeSimple("AT+UGPIOC=20,2", &result); + } + INFO("Modem Identification [%s]", info); + + CREGProcessor cregProcessor(m_type != LISA_C200); + //Wait for network registration + do + { + DBG("Waiting for network registration"); + ret = m_at.execute(cregProcessor.getAtCommand(), &cregProcessor, &result); + DBG("Result of command: Err code=%d\n", ret); + DBG("ATResult: AT return=%d (code %d)\n", result.result, result.code); + if(cregProcessor.getStatus() == CREGProcessor::STATUS_REGISTERING) + { + Thread::wait(3000); + } + } while(cregProcessor.getStatus() == CREGProcessor::STATUS_REGISTERING); + if(cregProcessor.getStatus() == CREGProcessor::STATUS_FAILED) + { + ERR("Registration denied"); + return NET_AUTH; + } + + m_atOpen = true; + + return OK; +} + +int UbloxModem::cleanup() +{ + if(m_ppp.isConnected()) + { + WARN("Data connection is still open"); //Try to encourage good behaviour from the user + m_ppp.disconnect(); + } + + m_smsInit = false; + m_ussdInit = false; + m_linkMonitorInit = false; + //We don't reset m_ipInit as PPPIPInterface::init() only needs to be called once + + if(m_atOpen) + { + m_at.close(); + m_atOpen = false; + } + + return OK; +} + +int UbloxModem::sendUSSD(const char* command, char* result, size_t maxLength) +{ + int ret = init(); + if(ret) + { + return ret; + } + + if(!m_ussdInit) + { + ret = m_ussd.init(); + if(ret) + { + return ret; + } + m_ussdInit = true; + } + + ret = m_ussd.send(command, result, maxLength); + if(ret) + { + return ret; + } + + return OK; +} + +int UbloxModem::getLinkState(int* pRssi, LinkMonitor::REGISTRATION_STATE* pRegistrationState, LinkMonitor::BEARER* pBearer) +{ + int ret = init(); + if(ret) + { + return ret; + } + + if(!m_linkMonitorInit) + { + ret = m_linkMonitor.init(m_type != LISA_C200); + if(ret) + { + return ret; + } + m_linkMonitorInit = true; + } + + ret = m_linkMonitor.getState(pRssi, pRegistrationState, pBearer); + if(ret) + { + return ret; + } + + return OK; +} + +int UbloxModem::getPhoneNumber(char* phoneNumber) +{ + int ret = init(); + if(ret) + { + return ret; + } + + if(!m_linkMonitorInit) + { + ret = m_linkMonitor.init(m_type != LISA_C200); + if(ret) + { + return ret; + } + m_linkMonitorInit = true; + } + + ret = m_linkMonitor.getPhoneNumber(phoneNumber); + if(ret) + { + return ret; + } + + return OK; +} + +#include "USBHost.h" +#include "UbloxGSMModemInitializer.h" +#include "UbloxCDMAModemInitializer.h" + +UbloxUSBModem::UbloxUSBModem() : + UbloxModem(&m_atStream, &m_pppStream), + m_dongle(), // Construct WANDongle: USB interface with two serial channels to the modem (USBSerialStream objects) + m_atStream(m_dongle.getSerial(1)), // AT commands are sent down one serial channel. + m_pppStream(m_dongle.getSerial(0)), // PPP connections are managed via another serial channel. + m_dongleConnected(false) // Dongle is initially not ready for anything +{ + USBHost* host = USBHost::getHostInst(); + m_dongle.addInitializer(new UbloxGSMModemInitializer(host)); + m_dongle.addInitializer(new UbloxCDMAModemInitializer(host)); +} + +int UbloxUSBModem::init() +{ + if( !m_dongleConnected ) + { + m_dongleConnected = true; + while( !m_dongle.connected() ) + { + m_dongle.tryConnect(); + Thread::wait(10); + } + if(m_dongle.getDongleType() == WAN_DONGLE_TYPE_UBLOX_LISAU200) + { + INFO("Using a u-blox LISA-U200 3G/WCDMA Modem"); + m_type = LISA_U200; + } + else if(m_dongle.getDongleType() == WAN_DONGLE_TYPE_UBLOX_LISAC200) + { + INFO("Using a u-blox LISA-C200 CDMA Modem"); + m_type = LISA_C200; + m_onePort = true; + } + else + { + WARN("Using an Unknown Dongle"); + } + } + return UbloxModem::init(); +} + +int UbloxUSBModem::cleanup() +{ + UbloxModem::cleanup(); + m_dongle.disconnect(); + m_dongleConnected = false; + return OK; +} + +UbloxSerModem::UbloxSerModem() : + UbloxModem(&m_atStream, NULL), + m_Serial(P0_15/*MDMTXD*/,P0_16/*MDMRXD*/), + m_atStream(m_Serial) +{ + m_Serial.baud(115200/*MDMBAUD*/); + m_Serial.set_flow_control(SerialBase::RTSCTS, P0_22/*MDMRTS*/, P0_17/*MDMCTS*/); +} + diff --git a/features/unsupported/net/cellular/UbloxUSBModem/UbloxModem.h b/features/unsupported/net/cellular/UbloxUSBModem/UbloxModem.h new file mode 100644 index 00000000000..dc0e1205a40 --- /dev/null +++ b/features/unsupported/net/cellular/UbloxUSBModem/UbloxModem.h @@ -0,0 +1,183 @@ +/* VodafoneUSBModem.h */ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef UBLOXMODEM_H_ +#define UBLOXMODEM_H_ + +#include "core/fwk.h" + +#include "at/ATCommandsInterface.h" +#include "ip/PPPIPInterface.h" +#include "sms/GSMSMSInterface.h" +#include "sms/CDMASMSInterface.h" +#include "ussd/USSDInterface.h" +#include "link/LinkMonitor.h" +#include "CellularModem.h" + +class genericAtProcessor : public IATCommandsProcessor +{ +public: + genericAtProcessor(); + const char* getResponse(void); +private: + virtual int onNewATResponseLine(ATCommandsInterface* pInst, const char* line); + virtual int onNewEntryPrompt(ATCommandsInterface* pInst); +protected: + char str[256]; + int i; +}; + +/** u-blox WCDMA modem (LISA-U200) + */ +class UbloxModem: public CellularModem +{ +public: + /** Create u-blox API instance + @param powerGatingPin Optional pin commanding a power gating transistor on the modem's power line + @param powerGatingOnWhenPinHigh true if the pin needs to be high to power the dongle, defaults to true + */ + UbloxModem(IOStream* atStream, IOStream* pppStream); + + //Internet-related functions + + /** Open a 3G internet connection + @return 0 on success, error code on failure + */ + virtual int connect(const char* apn = NULL, const char* user = NULL, const char* password = NULL); + + /** Close the internet connection + @return 0 on success, error code on failure + */ + virtual int disconnect(); + + + /** Send a SM + @param number The receiver's phone number + @param message The message to send + @return 0 on success, error code on failure + */ + virtual int sendSM(const char* number, const char* message); + + + /** Receive a SM + @param number Pointer to a buffer to store the sender's phone number (must be at least 17 characters-long, including the sapce for the null-terminating char) + @param message Pointer to a buffer to store the the incoming message + @param maxLength Maximum message length that can be stored in buffer (including null-terminating character) + @return 0 on success, error code on failure + */ + virtual int getSM(char* number, char* message, size_t maxLength); + + /** Get the number of SMs in the incoming box + @param pCount pointer to store the number of unprocessed SMs on + @return 0 on success, error code on failure + */ + virtual int getSMCount(size_t* pCount); + + /** Send a USSD command & wait for its result + @param command The command to send + @param result Buffer in which to store the result + @param maxLength Maximum result length that can be stored in buffer (including null-terminating character) + @return 0 on success, error code on failure + */ + int sendUSSD(const char* command, char* result, size_t maxLength); + + /** Get link state + @param pRssi pointer to store the current RSSI in dBm, between -51 dBm and -113 dBm if known; -51 dBm means -51 dBm or more; -113 dBm means -113 dBm or less; 0 if unknown + @param pRegistrationState pointer to store the current registration state + @param pBearer pointer to store the current bearer + @return 0 on success, error code on failure + */ + int getLinkState(int* pRssi, LinkMonitor::REGISTRATION_STATE* pRegistrationState, LinkMonitor::BEARER* pBearer); + + int getPhoneNumber(char* phoneNumber); + + /** Get the ATCommandsInterface instance + @return Pointer to the ATCommandsInterface instance + */ + virtual ATCommandsInterface* getATCommandsInterface(); + +protected: + /** Initialise dongle. + * The following actions are performed: + * 1) Start AT interface thread + * 2) Wait for network registration + */ + virtual int init(); + + /** De-initialise dongle. + * The following actions are performed: + * 1) Tear down PPP session + * 2) Set SMS,USSD, and LinkMonitor subsystems to un-initialised + * 3) Close the AT commands interface + */ + virtual int cleanup(); + +private: + ATCommandsInterface m_at; //< Interface to AT commands processing + + CDMASMSInterface m_CdmaSms; //< Interface to SMS manager (send/receive etc) + GSMSMSInterface m_GsmSms; //< Interface to SMS manager (send/receive etc) + USSDInterface m_ussd; //< Interface to USSD manager (send etc) + LinkMonitor m_linkMonitor; //< Interface to link monitor (RSSI) + + PPPIPInterface m_ppp; //< Interface to PPP conection manager (IP assignment etc) + + bool m_ipInit; //< Has PPIPInterface object (m_ppp) been initialised? true/false + bool m_smsInit; //< Has SMSInterface object (m_sms) been initialised? true/false + bool m_ussdInit; //< Has USSDInterface object (m_ussd) been initialised? true/false + bool m_linkMonitorInit; //< Has LinkMonitor object (m_linkMonitor) been initialised? true/false + bool m_atOpen; //< Is the interface to the ATCommandsInterface open? true/false +protected: + bool m_onePort; + enum { LISA_C200, LISA_U200, SARA_G350, UNKNOWN } m_type; +}; + +#include "WANDongle.h" +#include "serial/usb/USBSerialStream.h" + +class UbloxUSBModem: public UbloxModem +{ +public: + UbloxUSBModem(); + virtual int init(); + virtual int cleanup(); + virtual int power(bool enable) { return 1; } + +private: + WANDongle m_dongle; //< Interface to USB connected WAN dongle + + USBSerialStream m_atStream; //< Serial interface to AT channel on modem + USBSerialStream m_pppStream; //< Serial interface to PPP channel on modem + + bool m_dongleConnected; //< Is the dongle physically connected (does the USB stack respond)? true/false +}; + +#include "serial/io/IOSerialStream.h" + +class UbloxSerModem: public UbloxModem +{ +public: + UbloxSerModem(); + virtual int power(bool enable) { return 1; } +private: + RawSerial m_Serial; + IOSerialStream m_atStream; //< Serial interface to AT channel on modem +}; + +#endif /* UBLOXMODEM_H_ */ diff --git a/features/unsupported/net/cellular/UbloxUSBModem/UbloxUSBCDMAModem.cpp b/features/unsupported/net/cellular/UbloxUSBModem/UbloxUSBCDMAModem.cpp new file mode 100644 index 00000000000..5e4e32a2b57 --- /dev/null +++ b/features/unsupported/net/cellular/UbloxUSBModem/UbloxUSBCDMAModem.cpp @@ -0,0 +1,398 @@ +/* UbloxUSBCDMAModem.cpp */ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#define __DEBUG__ 4 +#ifndef __MODULE__ +#define __MODULE__ "UbloxUSBCDMAModem.cpp" +#endif + +#include "core/fwk.h" + +#include "UbloxUSBCDMAModem.h" +#include "UbloxCDMAModemInitializer.h" +#include "USBHost.h" + +#define USE_ONE_PORT 1 + +UbloxUSBCDMAModem::UbloxUSBCDMAModem(PinName powerGatingPin /*= NC*/, bool powerGatingOnWhenPinHigh /* = true*/, int serial /* 0 */) : m_dongle(), +m_stream(m_dongle.getSerial(serial)), +m_at(&m_stream), +m_sms(&m_at), m_ppp(&m_stream), +m_dongleConnected(false), m_ipInit(false), m_smsInit(false), m_atOpen(false), +m_powerGatingPin(powerGatingPin), m_powerGatingOnWhenPinHigh(powerGatingOnWhenPinHigh) +{ + USBHost* host = USBHost::getHostInst(); + m_dongle.addInitializer(new UbloxCDMAModemInitializer(host)); + if( m_powerGatingPin != NC ) + { + power(false); //Dongle will have to be powered on manually + } +} + +class CSSProcessor : public IATCommandsProcessor +{ +public: + CSSProcessor() : status(STATUS_REGISTERING) + { + + } + enum REGISTERING_STATUS { STATUS_REGISTERING, STATUS_OK }; + REGISTERING_STATUS getStatus() + { + return status; + } +private: + virtual int onNewATResponseLine(ATCommandsInterface* pInst, const char* line) + { + char b; + char bc[3] = ""; + int sid = 99999; + + //if( sscanf(line, "%*d, %c", &r) == 1 ) + if(sscanf(line, "%*s %c,%2s,%d", &b,bc,&sid)==3) + { + if(strcmp("Z", bc) == 0) + status = STATUS_REGISTERING; + else + status = STATUS_OK; + } + return OK; + } + virtual int onNewEntryPrompt(ATCommandsInterface* pInst) + { + return OK; + } + volatile REGISTERING_STATUS status; +}; + +int UbloxUSBCDMAModem::connect(const char* apn, const char* user, const char* password) +{ + if( !m_ipInit ) + { + m_ipInit = true; + m_ppp.init(); + } + m_ppp.setup(user, password, DEFAULT_MSISDN_CDMA); + + int ret = init(); + if(ret) + { + return ret; + } + + #if USE_ONE_PORT + m_smsInit = false; //SMS status reset + //m_ussdInit = false; //USSD status reset + //m_linkMonitorInit = false; //Link monitor status reset + #endif + + ATCommandsInterface::ATResult result; + + if(apn != NULL) + { + char cmd[48]; + sprintf(cmd, "AT+CGDCONT=1,\"IP\",\"%s\"", apn); + ret = m_at.executeSimple(cmd, &result); + DBG("Result of command: Err code=%d", ret); + DBG("ATResult: AT return=%d (code %d)", result.result, result.code); + DBG("APN set to %s", apn); + } + + + //Connect + DBG("Connecting"); + #if USE_ONE_PORT + m_at.close(); // Closing AT parser + m_atOpen = false; //Will need to be reinitialized afterwards + #endif + + DBG("Connecting PPP"); + + ret = m_ppp.connect(); + DBG("Result of connect: Err code=%d", ret); + return ret; +} + + +int UbloxUSBCDMAModem::disconnect() +{ + DBG("Disconnecting from PPP"); + int ret = m_ppp.disconnect(); + if(ret) + { + ERR("Disconnect returned %d, still trying to disconnect", ret); + } + + //Ugly but leave dongle time to recover + Thread::wait(500); + + #if USE_ONE_PORT + ATCommandsInterface::ATResult result; + DBG("Starting AT thread"); + ret = m_at.open(); + if(ret) + { + return ret; + } + #endif + + DBG("Trying to hangup"); + + #if 0 //Does not appear to work + int tries = 10; + do + { + ret = m_at.executeSimple("+++", &result, 1000); + DBG("Result of command: Err code=%d\n", ret); + DBG("ATResult: AT return=%d (code %d)\n", result.result, result.code); + } while(tries-- && ret); + if(!ret) + { + ret = m_at.executeSimple("ATH", &result); + DBG("Result of command: Err code=%d\n", ret); + DBG("ATResult: AT return=%d (code %d)\n", result.result, result.code); + } + #endif + + #if USE_ONE_PORT + //Reinit AT parser + ret = m_at.init(); + DBG("Result of command: Err code=%d\n", ret); + if(ret) + { + m_at.close(); // Closing AT parser + DBG("AT Parser closed, could not complete disconnection"); + return NET_TIMEOUT; + } + + #if 0 + m_at.close(); // Closing AT parser + DBG("AT Parser closed"); + #endif + #endif + return OK; +} + +int UbloxUSBCDMAModem::sendSM(const char* number, const char* message) +{ + int ret = init(); + if(ret) + { + return ret; + } + + if(!m_smsInit) + { + ret = m_sms.init(); + if(ret) + { + return ret; + } + m_smsInit = true; + } + + ret = m_sms.send(number, message); + if(ret) + { + return ret; + } + + return OK; +} + +int UbloxUSBCDMAModem::getSM(char* number, char* message, size_t maxLength) +{ + int ret = init(); + if(ret) + { + return ret; + } + + if(!m_smsInit) + { + ret = m_sms.init(); + if(ret) + { + return ret; + } + m_smsInit = true; + } + + ret = m_sms.get(number, message, maxLength); + if(ret) + { + return ret; + } + + return OK; +} + +int UbloxUSBCDMAModem::getSMCount(size_t* pCount) +{ + int ret = init(); + if(ret) + { + return ret; + } + + if(!m_smsInit) + { + ret = m_sms.init(); + if(ret) + { + return ret; + } + m_smsInit = true; + } + + ret = m_sms.getCount(pCount); + if(ret) + { + return ret; + } + + return OK; +} + +ATCommandsInterface* UbloxUSBCDMAModem::getATCommandsInterface() +{ + return &m_at; +} + +int UbloxUSBCDMAModem::power(bool enable) +{ + if( m_powerGatingPin == NC ) + { + return NET_INVALID; //A pin name has not been provided in the constructor + } + + if(!enable) //Will force components to re-init + { + cleanup(); + } + + DigitalOut powerGatingOut(m_powerGatingPin); + powerGatingOut = m_powerGatingOnWhenPinHigh?enable:!enable; + + return OK; +} + +bool UbloxUSBCDMAModem::power() +{ + if( m_powerGatingPin == NC ) + { + return true; //Assume power is always on + } + + DigitalOut powerGatingOut(m_powerGatingPin); + return m_powerGatingOnWhenPinHigh?powerGatingOut:!powerGatingOut; +} + +int UbloxUSBCDMAModem::init() +{ + if( !m_dongleConnected ) + { + if(!power()) + { + //Obviously cannot initialize the dongle if it is disconnected... + ERR("Power is off"); + return NET_INVALID; + } + m_dongleConnected = true; + while( !m_dongle.connected() ) + { + m_dongle.tryConnect(); + Thread::wait(100); + } + } + + if(m_atOpen) + { + return OK; + } + + DBG("Starting AT thread if needed"); + int ret = m_at.open(); + if(ret) + { + return ret; + } + + DBG("Sending initialisation commands"); + ret = m_at.init(); + if(ret) + { + return ret; + } + + if(m_dongle.getDongleType() == WAN_DONGLE_TYPE_UBLOX_LISAC200) + { + INFO("Using a UBLOX C200 Dongle"); + } + else + { + WARN("Using an Unknown Dongle"); + } + + ATCommandsInterface::ATResult result; + + //Wait for network registration + CSSProcessor cssProcessor; + do + { + DBG("Waiting for network registration"); + ret = m_at.execute("AT+CSS?", &cssProcessor, &result); + DBG("Result of command: Err code=%d\n", ret); + DBG("ATResult: AT return=%d (code %d)\n", result.result, result.code); + if(cssProcessor.getStatus() == CSSProcessor::STATUS_REGISTERING) + { + Thread::wait(3000); + } + } while(cssProcessor.getStatus() == CSSProcessor::STATUS_REGISTERING); + + m_atOpen = true; + + return OK; +} + +int UbloxUSBCDMAModem::cleanup() +{ + if(m_ppp.isConnected()) + { + WARN("Data connection is still open"); //Try to encourage good behaviour from the user + m_ppp.disconnect(); + } + + m_smsInit = false; +// m_linkMonitorInit = false; + //We don't reset m_ipInit as PPPIPInterface::init() only needs to be called once + + if(m_atOpen) + { + m_at.close(); + m_atOpen = false; + } + + m_dongle.disconnect(); + m_dongleConnected = false; + + return OK; +} + + diff --git a/features/unsupported/net/cellular/UbloxUSBModem/UbloxUSBCDMAModem.h b/features/unsupported/net/cellular/UbloxUSBModem/UbloxUSBCDMAModem.h new file mode 100644 index 00000000000..988afb29ad4 --- /dev/null +++ b/features/unsupported/net/cellular/UbloxUSBModem/UbloxUSBCDMAModem.h @@ -0,0 +1,118 @@ +/* UbloxUSBCDMAModem.h */ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef UBLOXUSBCDMAMODEM_H_ +#define UBLOXUSBCDMAMODEM_H_ + +#include "core/fwk.h" + +#include "WANDongle.h" +#include "at/ATCommandsInterface.h" +#include "USBSerialStream.h" +#include "ip/PPPIPInterface.h" +#include "sms/CDMASMSInterface.h" +#include "CellularModem.h" + +/** u-blox LISA-C200 modem + */ +class UbloxUSBCDMAModem: public CellularModem +{ +public: + /** Create Sprint USB Modem (Sierra Wireless 598U) API instance + @param powerGatingPin Optional pin commanding a power gating transistor on the modem's power line + @param powerGatingOnWhenPinHigh true if the pin needs to be high to power the dongle, defaults to true + */ + UbloxUSBCDMAModem(PinName powerGatingPin = NC, bool powerGatingOnWhenPinHigh = true, int serial = 0); + + //Internet-related functions + + /** Open a 3G internet connection + @return 0 on success, error code on failure + */ + virtual int connect(const char* apn = NULL, const char* user = NULL, const char* password = NULL); + + /** Close the internet connection + @return 0 on success, error code on failure + */ + virtual int disconnect(); + + + /** Send a SM + @param number The receiver's phone number + @param message The message to send + @return 0 on success, error code on failure + */ + virtual int sendSM(const char* number, const char* message); + + + /** Receive a SM + @param number Pointer to a buffer to store the sender's phone number (must be at least 17 characters-long, including the sapce for the null-terminating char) + @param message Pointer to a buffer to store the the incoming message + @param maxLength Maximum message length that can be stored in buffer (including null-terminating character) + @return 0 on success, error code on failure + */ + virtual int getSM(char* number, char* message, size_t maxLength); + + /** Get the number of SMs in the incoming box + @param pCount pointer to store the number of unprocessed SMs on + @return 0 on success, error code on failure + */ + virtual int getSMCount(size_t* pCount); + + /** Get the ATCommandsInterface instance + @return Pointer to the ATCommandsInterface instance + */ + virtual ATCommandsInterface* getATCommandsInterface(); + + /** Switch power on or off + In order to use this function, a pin name must have been entered in the constructor + @param enable true to switch the dongle on, false to switch it off + @return 0 on success, error code on failure + */ + virtual int power(bool enable); + +protected: + bool power(); + + int init(); + int cleanup(); + +private: + WANDongle m_dongle; + + USBSerialStream m_stream; + + ATCommandsInterface m_at; + + CDMASMSInterface m_sms; + + PPPIPInterface m_ppp; + + bool m_dongleConnected; + bool m_ipInit; + bool m_smsInit; + bool m_atOpen; + + PinName m_powerGatingPin; + bool m_powerGatingOnWhenPinHigh; +}; + + +#endif /* UBLOXUSBCDMAMODEM_H_ */ + diff --git a/features/unsupported/net/cellular/UbloxUSBModem/UbloxUSBGSMModem.cpp b/features/unsupported/net/cellular/UbloxUSBModem/UbloxUSBGSMModem.cpp new file mode 100644 index 00000000000..8209dc6a883 --- /dev/null +++ b/features/unsupported/net/cellular/UbloxUSBModem/UbloxUSBGSMModem.cpp @@ -0,0 +1,605 @@ +/* UbloxUSBGSMModem.cpp */ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#define __DEBUG__ 3 +#ifndef __MODULE__ +#define __MODULE__ "UbloxUSBGSMModem.cpp" +#endif + +#include "core/fwk.h" + +#include "UbloxUSBGSMModem.h" +#include "UbloxGSMModemInitializer.h" +#include "USBHost.h" + +UbloxUSBGSMModem::UbloxUSBGSMModem(PinName powerGatingPin /*= NC*/, bool powerGatingOnWhenPinHigh /* = true*/) : + m_dongle(), // Construct WANDongle: USB interface with two serial channels to the modem (USBSerialStream objects) + m_atStream(m_dongle.getSerial(1)), // AT commands are sent down one serial channel. + m_pppStream(m_dongle.getSerial(0)), // PPP connections are managed via another serial channel. + m_at(&m_atStream), // Construct ATCommandsInterface with the AT serial channel + m_sms(&m_at), // Construct SMSInterface with the ATCommandsInterface + m_ussd(&m_at), // Construct USSDInterface with the ATCommandsInterface + m_linkMonitor(&m_at), // Construct LinkMonitor with the ATCommandsInterface + m_ppp(&m_pppStream), // Construct PPPIPInterface with the PPP serial channel + m_dongleConnected(false), // Dongle is initially not ready for anything + m_ipInit(false), // PPIPInterface connection is initially down + m_smsInit(false), // SMSInterface starts un-initialised + m_ussdInit(false), // USSDInterface starts un-initialised + m_linkMonitorInit(false), // LinkMonitor subsystem starts un-initialised + m_atOpen(false), // ATCommandsInterface starts in a closed state + m_powerGatingPin(powerGatingPin), // set power gating pin + m_powerGatingOnWhenPinHigh(powerGatingOnWhenPinHigh) // set state semantics for power gating pin +{ + USBHost* host = USBHost::getHostInst(); + m_dongle.addInitializer(new UbloxGSMModemInitializer(host)); + if( m_powerGatingPin != NC ) + { + power(false); //Dongle will have to be powered on manually + } +} + +class CREGProcessor : public IATCommandsProcessor +{ +public: + CREGProcessor() : status(STATUS_REGISTERING) + { + + } + enum REGISTERING_STATUS { STATUS_REGISTERING, STATUS_OK, STATUS_FAILED }; + REGISTERING_STATUS getStatus() + { + return status; + } +private: + virtual int onNewATResponseLine(ATCommandsInterface* pInst, const char* line) + { + int r; + if( sscanf(line, "+CREG: %*d,%d", &r) == 1 ) + { + switch(r) + { + case 1: + case 5: + status = STATUS_OK; + break; + case 0: + case 2: + status = STATUS_REGISTERING; + break; + case 3: + default: + status = STATUS_FAILED; + break; + } + } + return OK; + } + virtual int onNewEntryPrompt(ATCommandsInterface* pInst) + { + return OK; + } + volatile REGISTERING_STATUS status; +}; + +#if 0 +class COPSProcessor : public IATCommandsProcessor +{ +public: + COPSProcessor() : valid(false) + { + network[0] = '\0'; + apn[0] = '\0'; + bearer[0] = '\0'; + } + char* getNetwork() + { + return network; + } + char* getAPN() + { + return apn; + } + char* getBearer() + { + return bearer; + } + bool isValid() + { + return valid; + } +private: + virtual int onNewATResponseLine(ATCommandsInterface* pInst, const char* line) + { + int networkId; + int bearerId; + int s = sscanf(line, "+COPS: %*d,%*d,\"%d\",%d", &networkId, &bearerId); + if( s == 2 ) + { + switch(networkId) + { + case 23415: + strcpy(network, "Vodafone UK"); + strcpy(apn, "pp.vodafone.co.uk"); + valid = true; + break; + case 20810: + strcpy(network, "SFR FR"); + strcpy(apn, "websfr"); + valid = true; + break; + default: + break; + } + } + else + { + return OK; + } + switch(bearerId) + { + case 0: strcpy(bearer, "GSM"); break; + case 1: strcpy(bearer, "GSM Compact"); break; + case 2: strcpy(bearer, "UTRAN"); break; + case 3: strcpy(bearer, "GSM w/EGPRS"); break; + case 4: strcpy(bearer, "UTRAN w/HSDPA"); break; + case 5: strcpy(bearer, "UTRAN w/HSUPA"); break; + case 6: strcpy(bearer, "UTRAN w/HSDPA and HSUPA"); break; + case 7: strcpy(bearer, "E-UTRAN"); break; + + default: + break; + } + return OK; + } + virtual int onNewEntryPrompt(ATCommandsInterface* pInst) + { + return OK; + } + char network[24]; + char bearer[24]; + char apn[24]; + volatile bool valid; +}; +#endif + +int UbloxUSBGSMModem::connect(const char* apn, const char* user, const char* password) +{ + if( !m_ipInit ) + { + m_ipInit = true; + m_ppp.init(); + } + m_ppp.setup(user, password, DEFAULT_MSISDN_GSM); + + int ret = init(); + if(ret) + { + return ret; + } + + #if USE_ONE_PORT + m_smsInit = false; //SMS status reset + m_ussdInit = false; //USSD status reset + m_linkMonitorInit = false; //Link monitor status reset + #endif + + ATCommandsInterface::ATResult result; + + #if 0 + //Get network info & select corresponding APN + COPSProcessor copsProcessor; + DBG("Get network info & select APN from DB"); + ret = m_at.execute("AT+COPS=,2;+COPS?", &copsProcessor, &result); //Configure to get operator's info in numeric code & get operator's id + DBG("Result of command: Err code=%d", ret); + DBG("ATResult: AT return=%d (code %d)", result.result, result.code); + + if(!copsProcessor.isValid()) + { + WARN("Connected to an unknown network, try to connect with default parameters"); + DBG("Connected with %s", copsProcessor.getBearer()); + } + else + { + DBG("Connected to %s with %s", copsProcessor.getNetwork(), copsProcessor.getBearer()); + char cmd[48]; + int tries = 3; + sprintf(cmd, "AT+CGDCONT=1,\"IP\",\"%s\"", copsProcessor.getAPN()); + do //Try 3 times because for some reasons it can fail with the K3772-Z dongle + { + ret = m_at.executeSimple(cmd, &result); + DBG("Result of command: Err code=%d", ret); + } while(ret && --tries); + DBG("ATResult: AT return=%d (code %d)", result.result, result.code); + DBG("APN set to %s", copsProcessor.getAPN()); + } + #else + if(apn != NULL) + { + char cmd[48]; + int tries = 30; + sprintf(cmd, "AT+CGDCONT=1,\"IP\",\"%s\"", apn); + do //Try 30 times because for some reasons it can fail *a lot* with the K3772-Z dongle + { + ret = m_at.executeSimple(cmd, &result); + DBG("Result of command: Err code=%d", ret); + if(ret) + { + Thread::wait(500); + } + } while(ret && --tries); + DBG("ATResult: AT return=%d (code %d)", result.result, result.code); + DBG("APN set to %s", apn); + } + #endif + + + //Connect + DBG("Connecting"); + #if 0 + ret = m_at.executeSimple("ATDT *99#", &result); + DBG("Result of command: Err code=%d", ret); + DBG("ATResult: AT return=%d (code %d)", result.result, result.code); + #endif + #if USE_ONE_PORT + m_at.close(); // Closing AT parser + m_atOpen = false; //Will need to be reinitialized afterwards + #endif + + #if 0 + DBG("AT Parser closed"); + if( (ret!=NET_MOREINFO) || (result.result != ATCommandsInterface::ATResult::AT_CONNECT)) + { + ERR("Could not connect"); + return ret; //Could not connect + } + #endif + DBG("Connecting PPP"); + + ret = m_ppp.connect(); + DBG("Result of connect: Err code=%d", ret); + return ret; +} + + +int UbloxUSBGSMModem::disconnect() +{ + DBG("Disconnecting from PPP"); + int ret = m_ppp.disconnect(); + if(ret) + { + ERR("Disconnect returned %d, still trying to disconnect", ret); + } + + //Ugly but leave dongle time to recover + Thread::wait(500); + + #if USE_ONE_PORT + ATCommandsInterface::ATResult result; + DBG("Starting AT thread"); + ret = m_at.open(); + if(ret) + { + return ret; + } + #endif + + DBG("Trying to hangup"); + + #if 0 //Does not appear to work + int tries = 10; + do + { + ret = m_at.executeSimple("+++", &result, 1000); + DBG("Result of command: Err code=%d\n", ret); + DBG("ATResult: AT return=%d (code %d)\n", result.result, result.code); + } while(tries-- && ret); + if(!ret) + { + ret = m_at.executeSimple("ATH", &result); + DBG("Result of command: Err code=%d\n", ret); + DBG("ATResult: AT return=%d (code %d)\n", result.result, result.code); + } + #endif + + #if USE_ONE_PORT + //Reinit AT parser + ret = m_at.init(); + DBG("Result of command: Err code=%d\n", ret); + if(ret) + { + m_at.close(); // Closing AT parser + DBG("AT Parser closed, could not complete disconnection"); + return NET_TIMEOUT; + } + + #if 0 + m_at.close(); // Closing AT parser + DBG("AT Parser closed"); + #endif + #endif + return OK; +} + +int UbloxUSBGSMModem::sendSM(const char* number, const char* message) +{ + int ret = init(); + if(ret) + { + return ret; + } + + if(!m_smsInit) + { + ret = m_sms.init(); + if(ret) + { + return ret; + } + m_smsInit = true; + } + + ret = m_sms.send(number, message); + if(ret) + { + return ret; + } + + return OK; +} + +int UbloxUSBGSMModem::getSM(char* number, char* message, size_t maxLength) +{ + int ret = init(); + if(ret) + { + return ret; + } + + if(!m_smsInit) + { + ret = m_sms.init(); + if(ret) + { + return ret; + } + m_smsInit = true; + } + + ret = m_sms.get(number, message, maxLength); + if(ret) + { + return ret; + } + + return OK; +} + +int UbloxUSBGSMModem::getSMCount(size_t* pCount) +{ + int ret = init(); + if(ret) + { + return ret; + } + + if(!m_smsInit) + { + ret = m_sms.init(); + if(ret) + { + return ret; + } + m_smsInit = true; + } + + ret = m_sms.getCount(pCount); + if(ret) + { + return ret; + } + + return OK; +} + +int UbloxUSBGSMModem::sendUSSD(const char* command, char* result, size_t maxLength) +{ + int ret = init(); + if(ret) + { + return ret; + } + + if(!m_ussdInit) + { + ret = m_ussd.init(); + if(ret) + { + return ret; + } + m_ussdInit = true; + } + + ret = m_ussd.send(command, result, maxLength); + if(ret) + { + return ret; + } + + return OK; +} + +int UbloxUSBGSMModem::getLinkState(int* pRssi, LinkMonitor::REGISTRATION_STATE* pRegistrationState, LinkMonitor::BEARER* pBearer) +{ + int ret = init(); + if(ret) + { + return ret; + } + + if(!m_linkMonitorInit) + { + ret = m_linkMonitor.init(); + if(ret) + { + return ret; + } + m_linkMonitorInit = true; + } + + ret = m_linkMonitor.getState(pRssi, pRegistrationState, pBearer); + if(ret) + { + return ret; + } + + return OK; +} + + +ATCommandsInterface* UbloxUSBGSMModem::getATCommandsInterface() +{ + return &m_at; +} + +int UbloxUSBGSMModem::power(bool enable) +{ + if( m_powerGatingPin == NC ) + { + return NET_INVALID; //A pin name has not been provided in the constructor + } + + if(!enable) //Will force components to re-init + { + cleanup(); + } + + DigitalOut powerGatingOut(m_powerGatingPin); + powerGatingOut = m_powerGatingOnWhenPinHigh?enable:!enable; + + return OK; +} + +bool UbloxUSBGSMModem::power() +{ + if( m_powerGatingPin == NC ) + { + return true; //Assume power is always on + } + + DigitalOut powerGatingOut(m_powerGatingPin); + return m_powerGatingOnWhenPinHigh?powerGatingOut:!powerGatingOut; +} + +int UbloxUSBGSMModem::init() +{ + if( !m_dongleConnected ) + { + if(!power()) + { + //Obviously cannot initialize the dongle if it is disconnected... + ERR("Power is off"); + return NET_INVALID; + } + m_dongleConnected = true; + while( !m_dongle.connected() ) + { + m_dongle.tryConnect(); + Thread::wait(10); + } + } + + if(m_atOpen) + { + return OK; + } + + DBG("Starting AT thread if needed"); + int ret = m_at.open(); + if(ret) + { + return ret; + } + + DBG("Sending initialisation commands"); + ret = m_at.init(); + if(ret) + { + return ret; + } + + if(m_dongle.getDongleType() == WAN_DONGLE_TYPE_UBLOX_LISAU200) + { + INFO("Using a u-blox LISA-U"); + } + else + { + WARN("Using an Unknown Dongle"); + } + + ATCommandsInterface::ATResult result; + + //Wait for network registration + CREGProcessor cregProcessor; + do + { + DBG("Waiting for network registration"); + ret = m_at.execute("AT+CREG?", &cregProcessor, &result); + DBG("Result of command: Err code=%d\n", ret); + DBG("ATResult: AT return=%d (code %d)\n", result.result, result.code); + if(cregProcessor.getStatus() == CREGProcessor::STATUS_REGISTERING) + { + Thread::wait(3000); + } + } while(cregProcessor.getStatus() == CREGProcessor::STATUS_REGISTERING); + if(cregProcessor.getStatus() == CREGProcessor::STATUS_FAILED) + { + ERR("Registration denied"); + return NET_AUTH; + } + + m_atOpen = true; + + return OK; +} + +int UbloxUSBGSMModem::cleanup() +{ + if(m_ppp.isConnected()) + { + WARN("Data connection is still open"); //Try to encourage good behaviour from the user + m_ppp.disconnect(); + } + + m_smsInit = false; + m_ussdInit = false; + m_linkMonitorInit = false; + //We don't reset m_ipInit as PPPIPInterface::init() only needs to be called once + + if(m_atOpen) + { + m_at.close(); + m_atOpen = false; + } + + m_dongle.disconnect(); + m_dongleConnected = false; + + return OK; +} + diff --git a/features/unsupported/net/cellular/UbloxUSBModem/UbloxUSBGSMModem.h b/features/unsupported/net/cellular/UbloxUSBModem/UbloxUSBGSMModem.h new file mode 100644 index 00000000000..2cc432a2c22 --- /dev/null +++ b/features/unsupported/net/cellular/UbloxUSBModem/UbloxUSBGSMModem.h @@ -0,0 +1,155 @@ +/* VodafoneUSBModem.h */ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef UBLOXUSBGSMMODEM_H_ +#define UBLOXUSBGSMMODEM_H_ + +#include "core/fwk.h" + +#include "WANDongle.h" +#include "at/ATCommandsInterface.h" +#include "serial/usb/USBSerialStream.h" +#include "ip/PPPIPInterface.h" +#include "sms/GSMSMSInterface.h" +#include "ussd/USSDInterface.h" +#include "link/LinkMonitor.h" +#include "CellularModem.h" + +/** u-blox WCDMA modem (LISA-U200) + */ +class UbloxUSBGSMModem: public CellularModem +{ +public: + /** Create u-blox API instance + @param powerGatingPin Optional pin commanding a power gating transistor on the modem's power line + @param powerGatingOnWhenPinHigh true if the pin needs to be high to power the dongle, defaults to true + */ + UbloxUSBGSMModem(PinName powerGatingPin = NC, bool powerGatingOnWhenPinHigh = true); + + //Internet-related functions + + /** Open a 3G internet connection + @return 0 on success, error code on failure + */ + virtual int connect(const char* apn = NULL, const char* user = NULL, const char* password = NULL); + + /** Close the internet connection + @return 0 on success, error code on failure + */ + virtual int disconnect(); + + + /** Send a SM + @param number The receiver's phone number + @param message The message to send + @return 0 on success, error code on failure + */ + virtual int sendSM(const char* number, const char* message); + + + /** Receive a SM + @param number Pointer to a buffer to store the sender's phone number (must be at least 17 characters-long, including the sapce for the null-terminating char) + @param message Pointer to a buffer to store the the incoming message + @param maxLength Maximum message length that can be stored in buffer (including null-terminating character) + @return 0 on success, error code on failure + */ + virtual int getSM(char* number, char* message, size_t maxLength); + + /** Get the number of SMs in the incoming box + @param pCount pointer to store the number of unprocessed SMs on + @return 0 on success, error code on failure + */ + virtual int getSMCount(size_t* pCount); + + /** Send a USSD command & wait for its result + @param command The command to send + @param result Buffer in which to store the result + @param maxLength Maximum result length that can be stored in buffer (including null-terminating character) + @return 0 on success, error code on failure + */ + int sendUSSD(const char* command, char* result, size_t maxLength); + + /** Get link state + @param pRssi pointer to store the current RSSI in dBm, between -51 dBm and -113 dBm if known; -51 dBm means -51 dBm or more; -113 dBm means -113 dBm or less; 0 if unknown + @param pRegistrationState pointer to store the current registration state + @param pBearer pointer to store the current bearer + @return 0 on success, error code on failure + */ + int getLinkState(int* pRssi, LinkMonitor::REGISTRATION_STATE* pRegistrationState, LinkMonitor::BEARER* pBearer); + + /** Get the ATCommandsInterface instance + @return Pointer to the ATCommandsInterface instance + */ + virtual ATCommandsInterface* getATCommandsInterface(); + + /** Switch power on or off + In order to use this function, a pin name must have been entered in the constructor + @param enable true to switch the dongle on, false to switch it off + @return 0 on success, error code on failure + */ + virtual int power(bool enable); + +protected: + bool power(); //< Turn power to USB dongle ON. + + /** Initialise dongle. + * The following actions are performed: + * 1) Power up + * 2) Establish USB connection to dongle + * 3) Start AT interface thread + * 4) Wait for network registration + */ + int init(); + + /** De-initialise dongle. + * The following actions are performed: + * 1) Tear down PPP session + * 2) Set SMS,USSD, and LinkMonitor subsystems to un-initialised + * 3) Close the AT commands interface + * 4) Tear down the USB connection to dongle + */ + int cleanup(); + +private: + WANDongle m_dongle; //< Interface to USB connected WAN dongle + + USBSerialStream m_atStream; //< Serial interface to AT channel on modem + USBSerialStream m_pppStream; //< Serial interface to PPP channel on modem + + ATCommandsInterface m_at; //< Interface to AT commands processing + + GSMSMSInterface m_sms; //< Interface to SMS manager (send/receive etc) + USSDInterface m_ussd; //< Interface to USSD manager (send etc) + LinkMonitor m_linkMonitor; //< Interface to link monitor (RSSI) + + PPPIPInterface m_ppp; //< Interface to PPP conection manager (IP assignment etc) + + bool m_dongleConnected; //< Is the dongle physically connected (does the USB stack respond)? true/false + bool m_ipInit; //< Has PPIPInterface object (m_ppp) been initialised? true/false + bool m_smsInit; //< Has SMSInterface object (m_sms) been initialised? true/false + bool m_ussdInit; //< Has USSDInterface object (m_ussd) been initialised? true/false + bool m_linkMonitorInit; //< Has LinkMonitor object (m_linkMonitor) been initialised? true/false + bool m_atOpen; //< Is the interface to the ATCommandsInterface open? true/false + + PinName m_powerGatingPin; //< Pin which toggles power gating + bool m_powerGatingOnWhenPinHigh; //< Semantics of power gating (whether high or low toggles power gating) +}; + + +#endif /* UBLOXMODEM_H_ */ diff --git a/features/unsupported/net/eth/EthernetInterface/EthernetInterface.cpp b/features/unsupported/net/eth/EthernetInterface/EthernetInterface.cpp new file mode 100644 index 00000000000..73ce896bb88 --- /dev/null +++ b/features/unsupported/net/eth/EthernetInterface/EthernetInterface.cpp @@ -0,0 +1,156 @@ +/* EthernetInterface.cpp */ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +#include "EthernetInterface.h" + +#include "lwip/inet.h" +#include "lwip/netif.h" +#include "netif/etharp.h" +#include "lwip/dhcp.h" +#include "eth_arch.h" +#include "lwip/tcpip.h" + +#include "mbed.h" + +/* TCP/IP and Network Interface Initialisation */ +static struct netif netif; + +static char mac_addr[19]; +static char ip_addr[17] = "\0"; +static char gateway[17] = "\0"; +static char networkmask[17] = "\0"; +static bool use_dhcp = false; + +static Semaphore tcpip_inited(0); +static Semaphore netif_linked(0); +static Semaphore netif_up(0); + +static void tcpip_init_done(void *arg) { + tcpip_inited.release(); +} + +static void netif_link_callback(struct netif *netif) { + if (netif_is_link_up(netif)) { + netif_linked.release(); + } +} + +static void netif_status_callback(struct netif *netif) { + if (netif_is_up(netif)) { + strcpy(ip_addr, inet_ntoa(netif->ip_addr)); + strcpy(gateway, inet_ntoa(netif->gw)); + strcpy(networkmask, inet_ntoa(netif->netmask)); + netif_up.release(); + } +} + +static void init_netif(ip_addr_t *ipaddr, ip_addr_t *netmask, ip_addr_t *gw) { + tcpip_init(tcpip_init_done, NULL); + tcpip_inited.wait(); + + memset((void*) &netif, 0, sizeof(netif)); + netif_add(&netif, ipaddr, netmask, gw, NULL, eth_arch_enetif_init, tcpip_input); + netif_set_default(&netif); + + netif_set_link_callback (&netif, netif_link_callback); + netif_set_status_callback(&netif, netif_status_callback); +} + +static void set_mac_address(void) { +#if (MBED_MAC_ADDRESS_SUM != MBED_MAC_ADDR_INTERFACE) + snprintf(mac_addr, 19, "%02x:%02x:%02x:%02x:%02x:%02x", MBED_MAC_ADDR_0, MBED_MAC_ADDR_1, MBED_MAC_ADDR_2, + MBED_MAC_ADDR_3, MBED_MAC_ADDR_4, MBED_MAC_ADDR_5); +#else + char mac[6]; + mbed_mac_address(mac); + snprintf(mac_addr, 19, "%02x:%02x:%02x:%02x:%02x:%02x", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); +#endif +} + +int EthernetInterface::init() { + use_dhcp = true; + set_mac_address(); + init_netif(NULL, NULL, NULL); + return 0; +} + +int EthernetInterface::init(const char* ip, const char* mask, const char* gateway) { + use_dhcp = false; + + set_mac_address(); + strcpy(ip_addr, ip); + + ip_addr_t ip_n, mask_n, gateway_n; + inet_aton(ip, &ip_n); + inet_aton(mask, &mask_n); + inet_aton(gateway, &gateway_n); + init_netif(&ip_n, &mask_n, &gateway_n); + + return 0; +} + +int EthernetInterface::connect(unsigned int timeout_ms) { + eth_arch_enable_interrupts(); + + int inited; + if (use_dhcp) { + dhcp_start(&netif); + + // Wait for an IP Address + // -1: error, 0: timeout + inited = netif_up.wait(timeout_ms); + } else { + netif_set_up(&netif); + + // Wait for the link up + inited = netif_linked.wait(timeout_ms); + } + + return (inited > 0) ? (0) : (-1); +} + +int EthernetInterface::disconnect() { + if (use_dhcp) { + dhcp_release(&netif); + dhcp_stop(&netif); + } else { + netif_set_down(&netif); + } + + eth_arch_disable_interrupts(); + + return 0; +} + +char* EthernetInterface::getMACAddress() { + return mac_addr; +} + +char* EthernetInterface::getIPAddress() { + return ip_addr; +} + +char* EthernetInterface::getGateway() { + return gateway; +} + +char* EthernetInterface::getNetworkMask() { + return networkmask; +} + + diff --git a/features/unsupported/net/eth/EthernetInterface/EthernetInterface.h b/features/unsupported/net/eth/EthernetInterface/EthernetInterface.h new file mode 100644 index 00000000000..9473b8e084d --- /dev/null +++ b/features/unsupported/net/eth/EthernetInterface/EthernetInterface.h @@ -0,0 +1,90 @@ +/* EthernetInterface.h */ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef ETHERNETINTERFACE_H_ +#define ETHERNETINTERFACE_H_ + +#if !defined(TARGET_LPC1768) && !defined(TARGET_LPC4088) && !defined(TARGET_LPC4088_DM) && !defined(TARGET_K64F) && !defined(TARGET_K66F) && !defined(TARGET_RZ_A1H) && !defined(TARGET_VK_RZ_A1H) && !defined(TARGET_STM32F4) +#error The Ethernet Interface library is not supported on this target +#endif + +#include "rtos.h" +#include "lwip/netif.h" + + /** Interface using Ethernet to connect to an IP-based network + * + */ +class EthernetInterface { +public: + /** Initialize the interface with DHCP. + * Initialize the interface and configure it to use DHCP (no connection at this point). + * \return 0 on success, a negative number on failure + */ + static int init(); //With DHCP + + /** Initialize the interface with a static IP address. + * Initialize the interface and configure it with the following static configuration (no connection at this point). + * \param ip the IP address to use + * \param mask the IP address mask + * \param gateway the gateway to use + * \return 0 on success, a negative number on failure + */ + static int init(const char* ip, const char* mask, const char* gateway); + + /** Connect + * Bring the interface up, start DHCP if needed. + * \param timeout_ms timeout in ms (default: (15)s). + * \return 0 on success, a negative number on failure + */ + static int connect(unsigned int timeout_ms=15000); + + /** Disconnect + * Bring the interface down + * \return 0 on success, a negative number on failure + */ + static int disconnect(); + + /** Get the MAC address of your Ethernet interface + * \return a pointer to a string containing the MAC address + */ + static char* getMACAddress(); + + /** Get the IP address of your Ethernet interface + * \return a pointer to a string containing the IP address + */ + static char* getIPAddress(); + + /** Get the Gateway address of your Ethernet interface + * \return a pointer to a string containing the Gateway address + */ + static char* getGateway(); + + /** Get the Network mask of your Ethernet interface + * \return a pointer to a string containing the Network mask + */ + static char* getNetworkMask(); +}; + +#include "TCPSocketConnection.h" +#include "TCPSocketServer.h" + +#include "Endpoint.h" +#include "UDPSocket.h" + +#endif /* ETHERNETINTERFACE_H_ */ diff --git a/features/unsupported/net/eth/EthernetInterface/eth_arch.h b/features/unsupported/net/eth/EthernetInterface/eth_arch.h new file mode 100644 index 00000000000..25bdde38dda --- /dev/null +++ b/features/unsupported/net/eth/EthernetInterface/eth_arch.h @@ -0,0 +1,45 @@ +/* EthernetInterface.h */ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +// Architecture specific Ethernet interface +// Must be implemented by each target + +#ifndef ETHARCH_H_ +#define ETHARCH_H_ + +#include "lwip/netif.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#if DEVICE_EMAC +err_t emac_lwip_if_init(struct netif *netif); + +#else /* DEVICE_EMAC */ +void eth_arch_enable_interrupts(void); +void eth_arch_disable_interrupts(void); +err_t eth_arch_enetif_init(struct netif *netif); +#endif + +#ifdef __cplusplus +} +#endif + +#endif // #ifndef ETHARCHINTERFACE_H_ diff --git a/features/unsupported/net/eth/lwip-eth/arch/TARGET_Freescale/hardware_init_MK64F12.c b/features/unsupported/net/eth/lwip-eth/arch/TARGET_Freescale/hardware_init_MK64F12.c new file mode 100644 index 00000000000..a259e76fe2e --- /dev/null +++ b/features/unsupported/net/eth/lwip-eth/arch/TARGET_Freescale/hardware_init_MK64F12.c @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2013 - 2014, Freescale Semiconductor, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * o Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * o Redistributions in binary form must reproduce the above copyright notice, this + * list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * o Neither the name of Freescale Semiconductor, Inc. nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "fsl_port.h" + +/******************************************************************************* + * Code + ******************************************************************************/ +void k64f_init_eth_hardware(void) +{ + port_pin_config_t configENET = {0}; + + /* Disable MPU. */ + MPU->CESR &= ~MPU_CESR_VLD_MASK; + + CLOCK_EnableClock(kCLOCK_PortC); + CLOCK_EnableClock(kCLOCK_PortB); + /* Affects PORTC_PCR16 register */ + PORT_SetPinMux(PORTC, 16u, kPORT_MuxAlt4); + /* Affects PORTC_PCR17 register */ + PORT_SetPinMux(PORTC, 17u, kPORT_MuxAlt4); + /* Affects PORTC_PCR18 register */ + PORT_SetPinMux(PORTC, 18u, kPORT_MuxAlt4); + /* Affects PORTC_PCR19 register */ + PORT_SetPinMux(PORTC, 19u, kPORT_MuxAlt4); + /* Affects PORTB_PCR1 register */ + PORT_SetPinMux(PORTB, 1u, kPORT_MuxAlt4); + + configENET.openDrainEnable = kPORT_OpenDrainEnable; + configENET.mux = kPORT_MuxAlt4; + configENET.pullSelect = kPORT_PullUp; + /* Ungate the port clock */ + CLOCK_EnableClock(kCLOCK_PortA); + /* Affects PORTB_PCR0 register */ + PORT_SetPinConfig(PORTB, 0u, &configENET); + + /* Affects PORTA_PCR13 register */ + PORT_SetPinMux(PORTA, 13u, kPORT_MuxAlt4); + /* Affects PORTA_PCR12 register */ + PORT_SetPinMux(PORTA, 12u, kPORT_MuxAlt4); + /* Affects PORTA_PCR14 register */ + PORT_SetPinMux(PORTA, 14u, kPORT_MuxAlt4); + /* Affects PORTA_PCR5 register */ + PORT_SetPinMux(PORTA, 5u, kPORT_MuxAlt4); + /* Affects PORTA_PCR16 register */ + PORT_SetPinMux(PORTA, 16u, kPORT_MuxAlt4); + /* Affects PORTA_PCR17 register */ + PORT_SetPinMux(PORTA, 17u, kPORT_MuxAlt4); + /* Affects PORTA_PCR15 register */ + PORT_SetPinMux(PORTA, 15u, kPORT_MuxAlt4); + /* Affects PORTA_PCR28 register */ + PORT_SetPinMux(PORTA, 28u, kPORT_MuxAlt4); + + /* Select the Ethernet timestamp clock source */ + CLOCK_SetEnetTime0Clock(0x2); +} + +/******************************************************************************* + * EOF + ******************************************************************************/ + + diff --git a/features/unsupported/net/eth/lwip-eth/arch/TARGET_Freescale/k64f_emac.c b/features/unsupported/net/eth/lwip-eth/arch/TARGET_Freescale/k64f_emac.c new file mode 100644 index 00000000000..705db64484b --- /dev/null +++ b/features/unsupported/net/eth/lwip-eth/arch/TARGET_Freescale/k64f_emac.c @@ -0,0 +1,643 @@ +#include "lwip/opt.h" +#include "lwip/sys.h" +#include "lwip/def.h" +#include "lwip/mem.h" +#include "lwip/pbuf.h" +#include "lwip/stats.h" +#include "lwip/snmp.h" +#include "lwip/tcpip.h" +#include "netif/etharp.h" +#include "netif/ppp_oe.h" + +#include "eth_arch.h" +#include "sys_arch.h" + +#include "fsl_phy.h" +#include "k64f_emac_config.h" +#include +#include +#include +#include + +#include "mbed_interface.h" + +enet_handle_t g_handle; +// TX Buffer descriptors +uint8_t *tx_desc_start_addr; +// RX Buffer descriptors +uint8_t *rx_desc_start_addr; +// RX packet buffer pointers +struct pbuf *rx_buff[ENET_RX_RING_LEN]; +// TX packet buffer pointers +struct pbuf *tx_buff[ENET_RX_RING_LEN]; +// RX packet payload pointers +uint32_t *rx_ptr[ENET_RX_RING_LEN]; + +/******************************************************************************** + * Internal data + ********************************************************************************/ +#define ENET_BuffSizeAlign(n) ENET_ALIGN(n, ENET_BUFF_ALIGNMENT) +#define ENET_ALIGN(x,align) ((unsigned int)((x) + ((align)-1)) & (unsigned int)(~(unsigned int)((align)- 1))) +extern void k64f_init_eth_hardware(void); + +/* K64F EMAC driver data structure */ +struct k64f_enetdata { + struct netif *netif; /**< Reference back to LWIP parent netif */ + sys_sem_t RxReadySem; /**< RX packet ready semaphore */ + sys_sem_t TxCleanSem; /**< TX cleanup thread wakeup semaphore */ + sys_mutex_t TXLockMutex; /**< TX critical section mutex */ + sys_sem_t xTXDCountSem; /**< TX free buffer counting semaphore */ + uint8_t tx_consume_index, tx_produce_index; /**< TX buffers ring */ +}; + +static struct k64f_enetdata k64f_enetdata; + +/** \brief Driver transmit and receive thread priorities + * + * Thread priorities for receive thread and TX cleanup thread. Alter + * to prioritize receive or transmit bandwidth. In a heavily loaded + * system or with LEIP_DEBUG enabled, the priorities might be better + * the same. */ +#define RX_PRIORITY (osPriorityNormal) +#define TX_PRIORITY (osPriorityNormal) +#define PHY_PRIORITY (osPriorityNormal) + +/******************************************************************************** + * Buffer management + ********************************************************************************/ +/* + * This function will queue a new receive buffer + */ +static void update_read_buffer(uint8_t *buf) +{ + if (buf != NULL) { + g_handle.rxBdCurrent->buffer = buf; + } + + /* Clears status. */ + g_handle.rxBdCurrent->control &= ENET_BUFFDESCRIPTOR_RX_WRAP_MASK; + + /* Sets the receive buffer descriptor with the empty flag. */ + g_handle.rxBdCurrent->control |= ENET_BUFFDESCRIPTOR_RX_EMPTY_MASK; + + /* Increases the buffer descriptor to the next one. */ + if (g_handle.rxBdCurrent->control & ENET_BUFFDESCRIPTOR_RX_WRAP_MASK) { + g_handle.rxBdCurrent = g_handle.rxBdBase; + g_handle.rxBdDirty = g_handle.rxBdBase; + } else { + g_handle.rxBdCurrent++; + g_handle.rxBdDirty++; + } + + /* Actives the receive buffer descriptor. */ + ENET->RDAR = ENET_RDAR_RDAR_MASK; +} + +/** \brief Free TX buffers that are complete + * + * \param[in] k64f_enet Pointer to driver data structure + */ +static void k64f_tx_reclaim(struct k64f_enetdata *k64f_enet) +{ + uint8_t i = 0 ; + + /* Get exclusive access */ + sys_mutex_lock(&k64f_enet->TXLockMutex); + + i = k64f_enet->tx_consume_index; + // Traverse all descriptors, looking for the ones modified by the uDMA + while((i != k64f_enet->tx_produce_index) && (!(g_handle.txBdDirty->control & ENET_BUFFDESCRIPTOR_TX_READY_MASK))) { + pbuf_free(tx_buff[i]); + if (g_handle.txBdDirty->control & ENET_BUFFDESCRIPTOR_TX_WRAP_MASK) + g_handle.txBdDirty = g_handle.txBdBase; + else + g_handle.txBdDirty++; + + i = (i + 1) % ENET_TX_RING_LEN; + } + + k64f_enet->tx_consume_index = i; + /* Restore access */ + sys_mutex_unlock(&k64f_enet->TXLockMutex); +} + +/** \brief Ethernet receive interrupt handler + * + * This function handles the receive interrupt of K64F. + */ +void enet_mac_rx_isr() +{ + sys_sem_signal(&k64f_enetdata.RxReadySem); +} + +void enet_mac_tx_isr() +{ + sys_sem_signal(&k64f_enetdata.TxCleanSem); +} + +void ethernet_callback(ENET_Type *base, enet_handle_t *handle, enet_event_t event, void *param) +{ + switch (event) + { + case kENET_RxEvent: + enet_mac_rx_isr(); + break; + case kENET_TxEvent: + enet_mac_tx_isr(); + break; + default: + break; + } +} + +/** \brief Low level init of the MAC and PHY. + * + * \param[in] netif Pointer to LWIP netif structure + */ +static err_t low_level_init(struct netif *netif) +{ + struct k64f_enetdata *k64f_enet = netif->state; + uint8_t i; + uint32_t sysClock; + phy_speed_t phy_speed; + phy_duplex_t phy_duplex; + uint32_t phyAddr = 0; + bool link = false; + enet_config_t config; + + // Allocate RX descriptors + rx_desc_start_addr = (uint8_t *)calloc(1, sizeof(enet_rx_bd_struct_t) * ENET_RX_RING_LEN + ENET_BUFF_ALIGNMENT); + if(!rx_desc_start_addr) + return ERR_MEM; + + // Allocate TX descriptors + tx_desc_start_addr = (uint8_t *)calloc(1, sizeof(enet_tx_bd_struct_t) * ENET_TX_RING_LEN + ENET_BUFF_ALIGNMENT); + if(!tx_desc_start_addr) + return ERR_MEM; + + rx_desc_start_addr = (uint8_t *)ENET_ALIGN(rx_desc_start_addr, ENET_BUFF_ALIGNMENT); + tx_desc_start_addr = (uint8_t *)ENET_ALIGN(tx_desc_start_addr, ENET_BUFF_ALIGNMENT); + + /* Create buffers for each receive BD */ + for (i = 0; i < ENET_RX_RING_LEN; i++) { + rx_buff[i] = pbuf_alloc(PBUF_RAW, ENET_ETH_MAX_FLEN + ENET_BUFF_ALIGNMENT, PBUF_RAM); + if (NULL == rx_buff[i]) + return ERR_MEM; + + /* K64F note: the next line ensures that the RX buffer is properly aligned for the K64F + RX descriptors (16 bytes alignment). However, by doing so, we're effectively changing + a data structure which is internal to lwIP. This might not prove to be a good idea + in the long run, but a better fix would probably involve modifying lwIP itself */ + rx_buff[i]->payload = (void*)ENET_ALIGN((uint32_t)rx_buff[i]->payload, ENET_BUFF_ALIGNMENT); + rx_ptr[i] = rx_buff[i]->payload; + } + + k64f_enet->tx_consume_index = k64f_enet->tx_produce_index = 0; + + /* prepare the buffer configuration. */ + enet_buffer_config_t buffCfg = { + ENET_RX_RING_LEN, + ENET_TX_RING_LEN, + ENET_ALIGN(ENET_ETH_MAX_FLEN, ENET_BUFF_ALIGNMENT), + 0, + (volatile enet_rx_bd_struct_t *)rx_desc_start_addr, + (volatile enet_tx_bd_struct_t *)tx_desc_start_addr, + (uint8_t *)&rx_ptr, + NULL, + }; + + k64f_init_eth_hardware(); + + sysClock = CLOCK_GetFreq(kCLOCK_CoreSysClk); + + ENET_GetDefaultConfig(&config); + + PHY_Init(ENET, 0, sysClock); + PHY_GetLinkStatus(ENET, phyAddr, &link); + if (link) + { + /* Get link information from PHY */ + PHY_GetLinkSpeedDuplex(ENET, phyAddr, &phy_speed, &phy_duplex); + /* Change the MII speed and duplex for actual link status. */ + config.miiSpeed = (enet_mii_speed_t)phy_speed; + config.miiDuplex = (enet_mii_duplex_t)phy_duplex; + config.interrupt = kENET_RxFrameInterrupt | kENET_TxFrameInterrupt; + } + config.rxMaxFrameLen = ENET_ETH_MAX_FLEN; + config.macSpecialConfig = kENET_ControlFlowControlEnable; + config.txAccelerConfig = kENET_TxAccelIsShift16Enabled; + config.rxAccelerConfig = kENET_RxAccelisShift16Enabled | kENET_RxAccelMacCheckEnabled; + ENET_Init(ENET, &g_handle, &config, &buffCfg, netif->hwaddr, sysClock); + ENET_SetCallback(&g_handle, ethernet_callback, netif); + ENET_ActiveRead(ENET); + + return ERR_OK; +} + + +/** + * This function is the ethernet packet send function. It calls + * etharp_output after checking link status. + * + * \param[in] netif the lwip network interface structure for this enetif + * \param[in] q Pointer to pbug to send + * \param[in] ipaddr IP address + * \return ERR_OK or error code + */ +err_t k64f_etharp_output(struct netif *netif, struct pbuf *q, ip_addr_t *ipaddr) +{ + /* Only send packet is link is up */ + if (netif->flags & NETIF_FLAG_LINK_UP) + return etharp_output(netif, q, ipaddr); + + return ERR_CONN; +} + +/** \brief Allocates a pbuf and returns the data from the incoming packet. + * + * \param[in] netif the lwip network interface structure + * \param[in] idx index of packet to be read + * \return a pbuf filled with the received packet (including MAC header) + */ +static struct pbuf *k64f_low_level_input(struct netif *netif, int idx) +{ + volatile enet_rx_bd_struct_t *bdPtr = g_handle.rxBdCurrent; + struct pbuf *p = NULL; + struct pbuf *temp_rxbuf = NULL; + u32_t length = 0; + const u16_t err_mask = ENET_BUFFDESCRIPTOR_RX_TRUNC_MASK | ENET_BUFFDESCRIPTOR_RX_CRC_MASK | + ENET_BUFFDESCRIPTOR_RX_NOOCTET_MASK | ENET_BUFFDESCRIPTOR_RX_LENVLIOLATE_MASK; + + +#ifdef LOCK_RX_THREAD + /* Get exclusive access */ + sys_mutex_lock(&k64f_enet->TXLockMutex); +#endif + + /* Determine if a frame has been received */ + if ((bdPtr->control & err_mask) != 0) { +#if LINK_STATS + if ((bdPtr->control & ENET_BUFFDESCRIPTOR_RX_LENVLIOLATE_MASK) != 0) + LINK_STATS_INC(link.lenerr); + else + LINK_STATS_INC(link.chkerr); +#endif + LINK_STATS_INC(link.drop); + /* Re-use the same buffer in case of error */ + update_read_buffer(NULL); + } else { + /* A packet is waiting, get length */ + length = bdPtr->length; + + /* Zero-copy */ + p = rx_buff[idx]; + p->len = length; + + /* Attempt to queue new buffer */ + temp_rxbuf = pbuf_alloc(PBUF_RAW, ENET_ETH_MAX_FLEN + ENET_BUFF_ALIGNMENT, PBUF_RAM); + if (NULL == temp_rxbuf) { + /* Drop frame (out of memory) */ + LINK_STATS_INC(link.drop); + + /* Re-queue the same buffer */ + update_read_buffer(NULL); + + LWIP_DEBUGF(UDP_LPC_EMAC | LWIP_DBG_TRACE, + ("k64f_low_level_input: Packet index %d dropped for OOM\n", + idx)); +#ifdef LOCK_RX_THREAD + sys_mutex_unlock(&k64f_enet->TXLockMutex); +#endif + + return NULL; + } + + rx_buff[idx] = temp_rxbuf; + /* K64F note: the next line ensures that the RX buffer is properly aligned for the K64F + RX descriptors (16 bytes alignment). However, by doing so, we're effectively changing + a data structure which is internal to lwIP. This might not prove to be a good idea + in the long run, but a better fix would probably involve modifying lwIP itself */ + rx_buff[idx]->payload = (void*)ENET_ALIGN((uint32_t)rx_buff[idx]->payload, ENET_BUFF_ALIGNMENT); + rx_ptr[idx] = rx_buff[idx]->payload; + + update_read_buffer(rx_buff[idx]->payload); + LWIP_DEBUGF(UDP_LPC_EMAC | LWIP_DBG_TRACE, + ("k64f_low_level_input: Packet received: %p, size %d (index=%d)\n", + p, length, idx)); + + /* Save size */ + p->tot_len = (u16_t) length; + LINK_STATS_INC(link.recv); + } + +#ifdef LOCK_RX_THREAD + sys_mutex_unlock(&k64f_enet->TXLockMutex); +#endif + + return p; +} + +/** \brief Attempt to read a packet from the EMAC interface. + * + * \param[in] netif the lwip network interface structure + * \param[in] idx index of packet to be read + */ +void k64f_enetif_input(struct netif *netif, int idx) +{ + struct eth_hdr *ethhdr; + struct pbuf *p; + + /* move received packet into a new pbuf */ + p = k64f_low_level_input(netif, idx); + if (p == NULL) + return; + + /* points to packet payload, which starts with an Ethernet header */ + ethhdr = (struct eth_hdr*)p->payload; + + switch (htons(ethhdr->type)) { + case ETHTYPE_IP: + case ETHTYPE_ARP: +#if PPPOE_SUPPORT + case ETHTYPE_PPPOEDISC: + case ETHTYPE_PPPOE: +#endif /* PPPOE_SUPPORT */ + /* full packet send to tcpip_thread to process */ + if (netif->input(p, netif) != ERR_OK) { + LWIP_DEBUGF(NETIF_DEBUG, ("k64f_enetif_input: IP input error\n")); + /* Free buffer */ + pbuf_free(p); + } + break; + + default: + /* Return buffer */ + pbuf_free(p); + break; + } +} + +/** \brief Packet reception task + * + * This task is called when a packet is received. It will + * pass the packet to the LWIP core. + * + * \param[in] pvParameters pointer to the interface data + */ +static void packet_rx(void* pvParameters) { + struct k64f_enetdata *k64f_enet = pvParameters; + int idx = 0; + + while (1) { + /* Wait for receive task to wakeup */ + sys_arch_sem_wait(&k64f_enet->RxReadySem, 0); + + while ((g_handle.rxBdCurrent->control & ENET_BUFFDESCRIPTOR_RX_EMPTY_MASK) == 0) { + k64f_enetif_input(k64f_enet->netif, idx); + idx = (idx + 1) % ENET_RX_RING_LEN; + } + } +} + +/** \brief Transmit cleanup task + * + * This task is called when a transmit interrupt occurs and + * reclaims the pbuf and descriptor used for the packet once + * the packet has been transferred. + * + * \param[in] pvParameters pointer to the interface data + */ +static void packet_tx(void* pvParameters) { + struct k64f_enetdata *k64f_enet = pvParameters; + + while (1) { + /* Wait for transmit cleanup task to wakeup */ + sys_arch_sem_wait(&k64f_enet->TxCleanSem, 0); + k64f_tx_reclaim(k64f_enet); + } +} + +/** \brief Low level output of a packet. Never call this from an + * interrupt context, as it may block until TX descriptors + * become available. + * + * \param[in] netif the lwip network interface structure for this netif + * \param[in] p the MAC packet to send (e.g. IP packet including MAC addresses and type) + * \return ERR_OK if the packet could be sent or an err_t value if the packet couldn't be sent + */ +static err_t k64f_low_level_output(struct netif *netif, struct pbuf *p) +{ + struct k64f_enetdata *k64f_enet = netif->state; + struct pbuf *q; + struct pbuf *temp_pbuf; + uint8_t *psend = NULL, *dst; + + + temp_pbuf = pbuf_alloc(PBUF_RAW, p->tot_len + ENET_BUFF_ALIGNMENT, PBUF_RAM); + if (NULL == temp_pbuf) + return ERR_MEM; + + /* K64F note: the next line ensures that the RX buffer is properly aligned for the K64F + RX descriptors (16 bytes alignment). However, by doing so, we're effectively changing + a data structure which is internal to lwIP. This might not prove to be a good idea + in the long run, but a better fix would probably involve modifying lwIP itself */ + psend = (uint8_t *)ENET_ALIGN((uint32_t)temp_pbuf->payload, ENET_BUFF_ALIGNMENT); + + for (q = p, dst = psend; q != NULL; q = q->next) { + MEMCPY(dst, q->payload, q->len); + dst += q->len; + } + + /* Wait until a descriptor is available for the transfer. */ + /* THIS WILL BLOCK UNTIL THERE ARE A DESCRIPTOR AVAILABLE */ + while (g_handle.txBdCurrent->control & ENET_BUFFDESCRIPTOR_TX_READY_MASK) + osSemaphoreWait(k64f_enet->xTXDCountSem.id, osWaitForever); + + /* Get exclusive access */ + sys_mutex_lock(&k64f_enet->TXLockMutex); + + /* Save the buffer so that it can be freed when transmit is done */ + tx_buff[k64f_enet->tx_produce_index] = temp_pbuf; + k64f_enet->tx_produce_index = (k64f_enet->tx_produce_index + 1) % ENET_TX_RING_LEN; + + /* Setup transfers */ + g_handle.txBdCurrent->buffer = psend; + g_handle.txBdCurrent->length = p->tot_len; + g_handle.txBdCurrent->control |= (ENET_BUFFDESCRIPTOR_TX_READY_MASK | ENET_BUFFDESCRIPTOR_TX_LAST_MASK); + + /* Increase the buffer descriptor address. */ + if (g_handle.txBdCurrent->control & ENET_BUFFDESCRIPTOR_TX_WRAP_MASK) + g_handle.txBdCurrent = g_handle.txBdBase; + else + g_handle.txBdCurrent++; + + /* Active the transmit buffer descriptor. */ + ENET->TDAR = ENET_TDAR_TDAR_MASK; + + LINK_STATS_INC(link.xmit); + + /* Restore access */ + sys_mutex_unlock(&k64f_enet->TXLockMutex); + + return ERR_OK; +} + +/******************************************************************************* + * PHY task: monitor link +*******************************************************************************/ + +#define PHY_TASK_PERIOD_MS 200 +#define STATE_UNKNOWN (-1) + +typedef struct { + int connected; + phy_speed_t speed; + phy_duplex_t duplex; +} PHY_STATE; + +int phy_link_status() { + bool connection_status; + uint32_t phyAddr = 0; + + PHY_GetLinkStatus(ENET, phyAddr, &connection_status); + return (int)connection_status; +} + +static void k64f_phy_task(void *data) { + struct netif *netif = (struct netif*)data; + bool connection_status; + PHY_STATE crt_state = {STATE_UNKNOWN, (phy_speed_t)STATE_UNKNOWN, (phy_duplex_t)STATE_UNKNOWN}; + PHY_STATE prev_state; + uint32_t phyAddr = 0; + uint32_t rcr = 0; + + prev_state = crt_state; + while (true) { + // Get current status + PHY_GetLinkStatus(ENET, phyAddr, &connection_status); + crt_state.connected = connection_status ? 1 : 0; + // Get the actual PHY link speed + PHY_GetLinkSpeedDuplex(ENET, phyAddr, &crt_state.speed, &crt_state.duplex); + + // Compare with previous state + if (crt_state.connected != prev_state.connected) { + if (crt_state.connected) + tcpip_callback_with_block((tcpip_callback_fn)netif_set_link_up, (void*) netif, 1); + else + tcpip_callback_with_block((tcpip_callback_fn)netif_set_link_down, (void*) netif, 1); + } + + if (crt_state.speed != prev_state.speed) { + rcr = ENET->RCR; + rcr &= ~ENET_RCR_RMII_10T_MASK; + rcr |= ENET_RCR_RMII_10T(!crt_state.speed); + ENET->RCR = rcr; + } + + prev_state = crt_state; + osDelay(PHY_TASK_PERIOD_MS); + } +} + +/** + * Should be called at the beginning of the program to set up the + * network interface. + * + * This function should be passed as a parameter to netif_add(). + * + * @param[in] netif the lwip network interface structure for this netif + * @return ERR_OK if the loopif is initialized + * ERR_MEM if private data couldn't be allocated + * any other err_t on error + */ +err_t eth_arch_enetif_init(struct netif *netif) +{ + err_t err; + + LWIP_ASSERT("netif != NULL", (netif != NULL)); + + k64f_enetdata.netif = netif; + + /* set MAC hardware address */ +#if (MBED_MAC_ADDRESS_SUM != MBED_MAC_ADDR_INTERFACE) + netif->hwaddr[0] = MBED_MAC_ADDR_0; + netif->hwaddr[1] = MBED_MAC_ADDR_1; + netif->hwaddr[2] = MBED_MAC_ADDR_2; + netif->hwaddr[3] = MBED_MAC_ADDR_3; + netif->hwaddr[4] = MBED_MAC_ADDR_4; + netif->hwaddr[5] = MBED_MAC_ADDR_5; +#else + mbed_mac_address((char *)netif->hwaddr); +#endif + netif->hwaddr_len = ETHARP_HWADDR_LEN; + + /* maximum transfer unit */ + netif->mtu = 1500; + + /* device capabilities */ + // TODOETH: check if the flags are correct below + netif->flags = NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP | NETIF_FLAG_ETHERNET | NETIF_FLAG_IGMP; + + /* Initialize the hardware */ + netif->state = &k64f_enetdata; + err = low_level_init(netif); + if (err != ERR_OK) + return err; + +#if LWIP_NETIF_HOSTNAME + /* Initialize interface hostname */ + netif->hostname = "lwipk64f"; +#endif /* LWIP_NETIF_HOSTNAME */ + + netif->name[0] = 'e'; + netif->name[1] = 'n'; + + netif->output = k64f_etharp_output; + netif->linkoutput = k64f_low_level_output; + + /* CMSIS-RTOS, start tasks */ +#ifdef CMSIS_OS_RTX + memset(k64f_enetdata.xTXDCountSem.data, 0, sizeof(k64f_enetdata.xTXDCountSem.data)); + k64f_enetdata.xTXDCountSem.def.semaphore = k64f_enetdata.xTXDCountSem.data; +#endif + k64f_enetdata.xTXDCountSem.id = osSemaphoreCreate(&k64f_enetdata.xTXDCountSem.def, ENET_TX_RING_LEN); + + LWIP_ASSERT("xTXDCountSem creation error", (k64f_enetdata.xTXDCountSem.id != NULL)); + + err = sys_mutex_new(&k64f_enetdata.TXLockMutex); + LWIP_ASSERT("TXLockMutex creation error", (err == ERR_OK)); + + /* Packet receive task */ + err = sys_sem_new(&k64f_enetdata.RxReadySem, 0); + LWIP_ASSERT("RxReadySem creation error", (err == ERR_OK)); + sys_thread_new("receive_thread", packet_rx, netif->state, DEFAULT_THREAD_STACKSIZE, RX_PRIORITY); + + /* Transmit cleanup task */ + err = sys_sem_new(&k64f_enetdata.TxCleanSem, 0); + LWIP_ASSERT("TxCleanSem creation error", (err == ERR_OK)); + sys_thread_new("txclean_thread", packet_tx, netif->state, DEFAULT_THREAD_STACKSIZE, TX_PRIORITY); + + /* PHY monitoring task */ + sys_thread_new("phy_thread", k64f_phy_task, netif, DEFAULT_THREAD_STACKSIZE, PHY_PRIORITY); + + /* Allow the PHY task to detect the initial link state and set up the proper flags */ + osDelay(10); + + return ERR_OK; +} + +void eth_arch_enable_interrupts(void) { + //NVIC_SetPriority(ENET_Receive_IRQn, 6U); + //NVIC_SetPriority(ENET_Transmit_IRQn, 6U); +} + +void eth_arch_disable_interrupts(void) { + +} + +/** + * @} + */ + +/* --------------------------------- End Of File ------------------------------ */ + diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/TARGET_RO359B/fsl_clock_config.h b/features/unsupported/net/eth/lwip-eth/arch/TARGET_Freescale/k64f_emac_config.h similarity index 70% rename from targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/TARGET_RO359B/fsl_clock_config.h rename to features/unsupported/net/eth/lwip-eth/arch/TARGET_Freescale/k64f_emac_config.h index 050c3ab79b0..8ec5f2ddaf3 100644 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/TARGET_RO359B/fsl_clock_config.h +++ b/features/unsupported/net/eth/lwip-eth/arch/TARGET_Freescale/k64f_emac_config.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, Freescale Semiconductor, Inc. + * Copyright (c) 2013 - 2014, Freescale Semiconductor, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -27,27 +27,25 @@ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef _CLOCK_CONFIG_H_ -#define _CLOCK_CONFIG_H_ - -/******************************************************************************* - * DEFINITION - ******************************************************************************/ -#define BOARD_XTAL0_CLK_HZ 50000000U -#define BOARD_XTAL32K_CLK_HZ 32768U - -/******************************************************************************* - * API - ******************************************************************************/ +#ifndef K64F_EMAC_CONFIG_H__ +#define K64F_EMAC_CONFIG_H__ + +#include "fsl_enet.h" + +#define ENET_RX_RING_LEN (16) +#define ENET_TX_RING_LEN (8) + +#define ENET_ETH_MAX_FLEN (1522) // recommended size for a VLAN frame + #if defined(__cplusplus) extern "C" { -#endif /* __cplusplus*/ +#endif -void BOARD_BootClockVLPR(void); -void BOARD_BootClockRUN(void); +int phy_link_status(void); #if defined(__cplusplus) } -#endif /* __cplusplus*/ +#endif + +#endif // #define K64F_EMAC_CONFIG_H__ -#endif /* _CLOCK_CONFIG_H_ */ diff --git a/features/unsupported/net/eth/lwip-eth/arch/TARGET_Freescale/lwipopts_conf.h b/features/unsupported/net/eth/lwip-eth/arch/TARGET_Freescale/lwipopts_conf.h new file mode 100644 index 00000000000..20d961abe5a --- /dev/null +++ b/features/unsupported/net/eth/lwip-eth/arch/TARGET_Freescale/lwipopts_conf.h @@ -0,0 +1,29 @@ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef LWIPOPTS_CONF_H +#define LWIPOPTS_CONF_H + +#include "k64f_emac_config.h" + +#define LWIP_TRANSPORT_ETHERNET 1 +#define ETH_PAD_SIZE 2 + +#define MEM_SIZE (ENET_RX_RING_LEN * (ENET_ETH_MAX_FLEN + ENET_BUFF_ALIGNMENT) + ENET_TX_RING_LEN * ENET_ETH_MAX_FLEN) + +#endif diff --git a/features/unsupported/net/eth/lwip-eth/arch/TARGET_NXP/lpc17_emac.c b/features/unsupported/net/eth/lwip-eth/arch/TARGET_NXP/lpc17_emac.c new file mode 100644 index 00000000000..82ad9b951cb --- /dev/null +++ b/features/unsupported/net/eth/lwip-eth/arch/TARGET_NXP/lpc17_emac.c @@ -0,0 +1,1046 @@ +/********************************************************************** +* $Id$ lpc17_emac.c 2011-11-20 +*//** +* @file lpc17_emac.c +* @brief LPC17 ethernet driver for LWIP +* @version 1.0 +* @date 20. Nov. 2011 +* @author NXP MCU SW Application Team +* +* Copyright(C) 2011, NXP Semiconductor +* All rights reserved. +* +*********************************************************************** +* Software that is described herein is for illustrative purposes only +* which provides customers with programming information regarding the +* products. This software is supplied "AS IS" without any warranties. +* NXP Semiconductors assumes no responsibility or liability for the +* use of the software, conveys no license or title under any patent, +* copyright, or mask work right to the product. NXP Semiconductors +* reserves the right to make changes in the software without +* notification. NXP Semiconductors also make no representation or +* warranty that such application will be suitable for the specified +* use without further testing or modification. +**********************************************************************/ + +#include "lwip/opt.h" +#include "lwip/sys.h" +#include "lwip/def.h" +#include "lwip/mem.h" +#include "lwip/pbuf.h" +#include "lwip/stats.h" +#include "lwip/snmp.h" +#include "netif/etharp.h" +#include "netif/ppp_oe.h" + +#include "lpc17xx_emac.h" +#include "eth_arch.h" +#include "lpc_emac_config.h" +#include "lpc_phy.h" +#include "sys_arch.h" + +#include "mbed_interface.h" +#include + +#ifndef LPC_EMAC_RMII +#error LPC_EMAC_RMII is not defined! +#endif + +#if LPC_NUM_BUFF_TXDESCS < 2 +#error LPC_NUM_BUFF_TXDESCS must be at least 2 +#endif + +#if LPC_NUM_BUFF_RXDESCS < 3 +#error LPC_NUM_BUFF_RXDESCS must be at least 3 +#endif + +/** @defgroup lwip17xx_emac_DRIVER lpc17 EMAC driver for LWIP + * @ingroup lwip_emac + * + * @{ + */ + +#if NO_SYS == 0 +/** \brief Driver transmit and receive thread priorities + * + * Thread priorities for receive thread and TX cleanup thread. Alter + * to prioritize receive or transmit bandwidth. In a heavily loaded + * system or with LEIP_DEBUG enabled, the priorities might be better + * the same. */ +#define RX_PRIORITY (osPriorityNormal) +#define TX_PRIORITY (osPriorityNormal) + +/** \brief Debug output formatter lock define + * + * When using FreeRTOS and with LWIP_DEBUG enabled, enabling this + * define will allow RX debug messages to not interleave with the + * TX messages (so they are actually readable). Not enabling this + * define when the system is under load will cause the output to + * be unreadable. There is a small tradeoff in performance for this + * so use it only for debug. */ +//#define LOCK_RX_THREAD + +/** \brief Receive group interrupts + */ +#define RXINTGROUP (EMAC_INT_RX_OVERRUN | EMAC_INT_RX_ERR | EMAC_INT_RX_DONE) + +/** \brief Transmit group interrupts + */ +#define TXINTGROUP (EMAC_INT_TX_UNDERRUN | EMAC_INT_TX_ERR | EMAC_INT_TX_DONE) + +/** \brief Signal used for ethernet ISR to signal packet_rx() thread. + */ +#define RX_SIGNAL 1 + +#else +#define RXINTGROUP 0 +#define TXINTGROUP 0 +#endif + + /** \brief Structure of a TX/RX descriptor + */ +typedef struct +{ + volatile u32_t packet; /**< Pointer to buffer */ + volatile u32_t control; /**< Control word */ +} LPC_TXRX_DESC_T; + +/** \brief Structure of a RX status entry + */ +typedef struct +{ + volatile u32_t statusinfo; /**< RX status word */ + volatile u32_t statushashcrc; /**< RX hash CRC */ +} LPC_TXRX_STATUS_T; + +/* LPC EMAC driver data structure */ +struct lpc_enetdata { + /* prxs must be 8 byte aligned! */ + LPC_TXRX_STATUS_T prxs[LPC_NUM_BUFF_RXDESCS]; /**< Pointer to RX statuses */ + struct netif *netif; /**< Reference back to LWIP parent netif */ + LPC_TXRX_DESC_T ptxd[LPC_NUM_BUFF_TXDESCS]; /**< Pointer to TX descriptor list */ + LPC_TXRX_STATUS_T ptxs[LPC_NUM_BUFF_TXDESCS]; /**< Pointer to TX statuses */ + LPC_TXRX_DESC_T prxd[LPC_NUM_BUFF_RXDESCS]; /**< Pointer to RX descriptor list */ + struct pbuf *rxb[LPC_NUM_BUFF_RXDESCS]; /**< RX pbuf pointer list, zero-copy mode */ + u32_t rx_fill_desc_index; /**< RX descriptor next available index */ + volatile u32_t rx_free_descs; /**< Count of free RX descriptors */ + struct pbuf *txb[LPC_NUM_BUFF_TXDESCS]; /**< TX pbuf pointer list, zero-copy mode */ + u32_t lpc_last_tx_idx; /**< TX last descriptor index, zero-copy mode */ +#if NO_SYS == 0 + sys_thread_t RxThread; /**< RX receive thread data object pointer */ + sys_sem_t TxCleanSem; /**< TX cleanup thread wakeup semaphore */ + sys_mutex_t TXLockMutex; /**< TX critical section mutex */ + sys_sem_t xTXDCountSem; /**< TX free buffer counting semaphore */ +#endif +}; + +#if defined(TARGET_LPC4088) || defined(TARGET_LPC4088_DM) +# if defined (__ICCARM__) +# define ETHMEM_SECTION +# elif defined(TOOLCHAIN_GCC_CR) +# define ETHMEM_SECTION __attribute__((section(".data.$RamPeriph32"), aligned)) +# else +# define ETHMEM_SECTION __attribute__((section("AHBSRAM1"),aligned)) +# endif +#elif defined(TARGET_LPC1768) +# if defined(TOOLCHAIN_GCC_ARM) +# define ETHMEM_SECTION __attribute__((section("AHBSRAM1"),aligned)) +# endif +#endif + +#ifndef ETHMEM_SECTION +#define ETHMEM_SECTION ALIGNED(8) +#endif + +/** \brief LPC EMAC driver work data + */ +ETHMEM_SECTION struct lpc_enetdata lpc_enetdata; + +/** \brief Queues a pbuf into the RX descriptor list + * + * \param[in] lpc_enetif Pointer to the drvier data structure + * \param[in] p Pointer to pbuf to queue + */ +static void lpc_rxqueue_pbuf(struct lpc_enetdata *lpc_enetif, struct pbuf *p) +{ + u32_t idx; + + /* Get next free descriptor index */ + idx = lpc_enetif->rx_fill_desc_index; + + /* Setup descriptor and clear statuses */ + lpc_enetif->prxd[idx].control = EMAC_RCTRL_INT | ((u32_t) (p->len - 1)); + lpc_enetif->prxd[idx].packet = (u32_t) p->payload; + lpc_enetif->prxs[idx].statusinfo = 0xFFFFFFFF; + lpc_enetif->prxs[idx].statushashcrc = 0xFFFFFFFF; + + /* Save pbuf pointer for push to network layer later */ + lpc_enetif->rxb[idx] = p; + + /* Wrap at end of descriptor list */ + idx++; + if (idx >= LPC_NUM_BUFF_RXDESCS) + idx = 0; + + /* Queue descriptor(s) */ + lpc_enetif->rx_free_descs -= 1; + lpc_enetif->rx_fill_desc_index = idx; + LPC_EMAC->RxConsumeIndex = idx; + + LWIP_DEBUGF(UDP_LPC_EMAC | LWIP_DBG_TRACE, + ("lpc_rxqueue_pbuf: pbuf packet queued: %p (free desc=%d)\n", p, + lpc_enetif->rx_free_descs)); +} + +/** \brief Attempt to allocate and requeue a new pbuf for RX + * + * \param[in] netif Pointer to the netif structure + * \returns 1 if a packet was allocated and requeued, otherwise 0 + */ +s32_t lpc_rx_queue(struct netif *netif) +{ + struct lpc_enetdata *lpc_enetif = netif->state; + struct pbuf *p; + s32_t queued = 0; + + /* Attempt to requeue as many packets as possible */ + while (lpc_enetif->rx_free_descs > 0) { + /* Allocate a pbuf from the pool. We need to allocate at the + maximum size as we don't know the size of the yet to be + received packet. */ + p = pbuf_alloc(PBUF_RAW, (u16_t) EMAC_ETH_MAX_FLEN, PBUF_RAM); + if (p == NULL) { + LWIP_DEBUGF(UDP_LPC_EMAC | LWIP_DBG_TRACE, + ("lpc_rx_queue: could not allocate RX pbuf (free desc=%d)\n", + lpc_enetif->rx_free_descs)); + return queued; + } + + /* pbufs allocated from the RAM pool should be non-chained. */ + LWIP_ASSERT("lpc_rx_queue: pbuf is not contiguous (chained)", + pbuf_clen(p) <= 1); + + /* Queue packet */ + lpc_rxqueue_pbuf(lpc_enetif, p); + + /* Update queued count */ + queued++; + } + + return queued; +} + +/** \brief Sets up the RX descriptor ring buffers. + * + * This function sets up the descriptor list used for receive packets. + * + * \param[in] lpc_enetif Pointer to driver data structure + * \returns Always returns ERR_OK + */ +static err_t lpc_rx_setup(struct lpc_enetdata *lpc_enetif) +{ + /* Setup pointers to RX structures */ + LPC_EMAC->RxDescriptor = (u32_t) &lpc_enetif->prxd[0]; + LPC_EMAC->RxStatus = (u32_t) &lpc_enetif->prxs[0]; + LPC_EMAC->RxDescriptorNumber = LPC_NUM_BUFF_RXDESCS - 1; + + lpc_enetif->rx_free_descs = LPC_NUM_BUFF_RXDESCS; + lpc_enetif->rx_fill_desc_index = 0; + + /* Build RX buffer and descriptors */ + lpc_rx_queue(lpc_enetif->netif); + + return ERR_OK; +} + +/** \brief Allocates a pbuf and returns the data from the incoming packet. + * + * \param[in] netif the lwip network interface structure for this lpc_enetif + * \return a pbuf filled with the received packet (including MAC header) + * NULL on memory error + */ +static struct pbuf *lpc_low_level_input(struct netif *netif) +{ + struct lpc_enetdata *lpc_enetif = netif->state; + struct pbuf *p = NULL; + u32_t idx, length; + u16_t origLength; + +#ifdef LOCK_RX_THREAD +#if NO_SYS == 0 + /* Get exclusive access */ + sys_mutex_lock(&lpc_enetif->TXLockMutex); +#endif +#endif + + /* Monitor RX overrun status. This should never happen unless + (possibly) the internal bus is behing held up by something. + Unless your system is running at a very low clock speed or + there are possibilities that the internal buses may be held + up for a long time, this can probably safely be removed. */ + if (LPC_EMAC->IntStatus & EMAC_INT_RX_OVERRUN) { + LINK_STATS_INC(link.err); + LINK_STATS_INC(link.drop); + + /* Temporarily disable RX */ + LPC_EMAC->MAC1 &= ~EMAC_MAC1_REC_EN; + + /* Reset the RX side */ + LPC_EMAC->MAC1 |= EMAC_MAC1_RES_RX; + LPC_EMAC->IntClear = EMAC_INT_RX_OVERRUN; + + /* De-allocate all queued RX pbufs */ + for (idx = 0; idx < LPC_NUM_BUFF_RXDESCS; idx++) { + if (lpc_enetif->rxb[idx] != NULL) { + pbuf_free(lpc_enetif->rxb[idx]); + lpc_enetif->rxb[idx] = NULL; + } + } + + /* Start RX side again */ + lpc_rx_setup(lpc_enetif); + + /* Re-enable RX */ + LPC_EMAC->MAC1 |= EMAC_MAC1_REC_EN; + +#ifdef LOCK_RX_THREAD +#if NO_SYS == 0 + sys_mutex_unlock(&lpc_enetif->TXLockMutex); +#endif +#endif + + return NULL; + } + + /* Determine if a frame has been received */ + length = 0; + idx = LPC_EMAC->RxConsumeIndex; + if (LPC_EMAC->RxProduceIndex != idx) { + /* Handle errors */ + if (lpc_enetif->prxs[idx].statusinfo & (EMAC_RINFO_CRC_ERR | + EMAC_RINFO_SYM_ERR | EMAC_RINFO_ALIGN_ERR | EMAC_RINFO_LEN_ERR)) { +#if LINK_STATS + if (lpc_enetif->prxs[idx].statusinfo & (EMAC_RINFO_CRC_ERR | + EMAC_RINFO_SYM_ERR | EMAC_RINFO_ALIGN_ERR)) + LINK_STATS_INC(link.chkerr); + if (lpc_enetif->prxs[idx].statusinfo & EMAC_RINFO_LEN_ERR) + LINK_STATS_INC(link.lenerr); +#endif + + /* Drop the frame */ + LINK_STATS_INC(link.drop); + + /* Re-queue the pbuf for receive */ + lpc_enetif->rx_free_descs++; + p = lpc_enetif->rxb[idx]; + lpc_enetif->rxb[idx] = NULL; + lpc_rxqueue_pbuf(lpc_enetif, p); + + LWIP_DEBUGF(UDP_LPC_EMAC | LWIP_DBG_TRACE, + ("lpc_low_level_input: Packet dropped with errors (0x%x)\n", + lpc_enetif->prxs[idx].statusinfo)); + + p = NULL; + } else { + /* A packet is waiting, get length */ + length = (lpc_enetif->prxs[idx].statusinfo & 0x7FF) + 1; + + /* Zero-copy */ + p = lpc_enetif->rxb[idx]; + origLength = p->len; + p->len = (u16_t) length; + + /* Free pbuf from descriptor */ + lpc_enetif->rxb[idx] = NULL; + lpc_enetif->rx_free_descs++; + + /* Attempt to queue new buffer(s) */ + if (lpc_rx_queue(lpc_enetif->netif) == 0) { + /* Drop the frame due to OOM. */ + LINK_STATS_INC(link.drop); + + /* Re-queue the pbuf for receive */ + p->len = origLength; + lpc_rxqueue_pbuf(lpc_enetif, p); + + LWIP_DEBUGF(UDP_LPC_EMAC | LWIP_DBG_TRACE, + ("lpc_low_level_input: Packet index %d dropped for OOM\n", + idx)); + +#ifdef LOCK_RX_THREAD +#if NO_SYS == 0 + sys_mutex_unlock(&lpc_enetif->TXLockMutex); +#endif +#endif + + return NULL; + } + + LWIP_DEBUGF(UDP_LPC_EMAC | LWIP_DBG_TRACE, + ("lpc_low_level_input: Packet received: %p, size %d (index=%d)\n", + p, length, idx)); + + /* Save size */ + p->tot_len = (u16_t) length; + LINK_STATS_INC(link.recv); + } + } + +#ifdef LOCK_RX_THREAD +#if NO_SYS == 0 + sys_mutex_unlock(&lpc_enetif->TXLockMutex); +#endif +#endif + + return p; +} + +/** \brief Attempt to read a packet from the EMAC interface. + * + * \param[in] netif the lwip network interface structure for this lpc_enetif + */ +void lpc_enetif_input(struct netif *netif) +{ + struct eth_hdr *ethhdr; + struct pbuf *p; + + /* move received packet into a new pbuf */ + p = lpc_low_level_input(netif); + if (p == NULL) + return; + + /* points to packet payload, which starts with an Ethernet header */ + ethhdr = p->payload; + + switch (htons(ethhdr->type)) { + case ETHTYPE_IP: + case ETHTYPE_ARP: +#if PPPOE_SUPPORT + case ETHTYPE_PPPOEDISC: + case ETHTYPE_PPPOE: +#endif /* PPPOE_SUPPORT */ + /* full packet send to tcpip_thread to process */ + if (netif->input(p, netif) != ERR_OK) { + LWIP_DEBUGF(NETIF_DEBUG, ("lpc_enetif_input: IP input error\n")); + /* Free buffer */ + pbuf_free(p); + } + break; + + default: + /* Return buffer */ + pbuf_free(p); + break; + } +} + +/** \brief Determine if the passed address is usable for the ethernet + * DMA controller. + * + * \param[in] addr Address of packet to check for DMA safe operation + * \return 1 if the packet address is not safe, otherwise 0 + */ +static s32_t lpc_packet_addr_notsafe(void *addr) { + /* Check for legal address ranges */ +#if defined(TARGET_LPC1768) + if ((((u32_t) addr >= 0x2007C000) && ((u32_t) addr < 0x20083FFF))) { +#elif defined(TARGET_LPC4088) || defined(TARGET_LPC4088_DM) + if ((((u32_t) addr >= 0x20000000) && ((u32_t) addr < 0x20007FFF))) { +#endif + return 0; + } + return 1; +} + +/** \brief Sets up the TX descriptor ring buffers. + * + * This function sets up the descriptor list used for transmit packets. + * + * \param[in] lpc_enetif Pointer to driver data structure + */ +static err_t lpc_tx_setup(struct lpc_enetdata *lpc_enetif) +{ + s32_t idx; + + /* Build TX descriptors for local buffers */ + for (idx = 0; idx < LPC_NUM_BUFF_TXDESCS; idx++) { + lpc_enetif->ptxd[idx].control = 0; + lpc_enetif->ptxs[idx].statusinfo = 0xFFFFFFFF; + } + + /* Setup pointers to TX structures */ + LPC_EMAC->TxDescriptor = (u32_t) &lpc_enetif->ptxd[0]; + LPC_EMAC->TxStatus = (u32_t) &lpc_enetif->ptxs[0]; + LPC_EMAC->TxDescriptorNumber = LPC_NUM_BUFF_TXDESCS - 1; + + lpc_enetif->lpc_last_tx_idx = 0; + + return ERR_OK; +} + +/** \brief Free TX buffers that are complete + * + * \param[in] lpc_enetif Pointer to driver data structure + * \param[in] cidx EMAC current descriptor comsumer index + */ +static void lpc_tx_reclaim_st(struct lpc_enetdata *lpc_enetif, u32_t cidx) +{ +#if NO_SYS == 0 + /* Get exclusive access */ + sys_mutex_lock(&lpc_enetif->TXLockMutex); +#endif + + while (cidx != lpc_enetif->lpc_last_tx_idx) { + if (lpc_enetif->txb[lpc_enetif->lpc_last_tx_idx] != NULL) { + LWIP_DEBUGF(UDP_LPC_EMAC | LWIP_DBG_TRACE, + ("lpc_tx_reclaim_st: Freeing packet %p (index %d)\n", + lpc_enetif->txb[lpc_enetif->lpc_last_tx_idx], + lpc_enetif->lpc_last_tx_idx)); + pbuf_free(lpc_enetif->txb[lpc_enetif->lpc_last_tx_idx]); + lpc_enetif->txb[lpc_enetif->lpc_last_tx_idx] = NULL; + } + +#if NO_SYS == 0 + osSemaphoreRelease(lpc_enetif->xTXDCountSem.id); +#endif + lpc_enetif->lpc_last_tx_idx++; + if (lpc_enetif->lpc_last_tx_idx >= LPC_NUM_BUFF_TXDESCS) + lpc_enetif->lpc_last_tx_idx = 0; + } + +#if NO_SYS == 0 + /* Restore access */ + sys_mutex_unlock(&lpc_enetif->TXLockMutex); +#endif +} + +/** \brief User call for freeingTX buffers that are complete + * + * \param[in] netif the lwip network interface structure for this lpc_enetif + */ +void lpc_tx_reclaim(struct netif *netif) +{ + lpc_tx_reclaim_st((struct lpc_enetdata *) netif->state, + LPC_EMAC->TxConsumeIndex); +} + + /** \brief Polls if an available TX descriptor is ready. Can be used to + * determine if the low level transmit function will block. + * + * \param[in] netif the lwip network interface structure for this lpc_enetif + * \return 0 if no descriptors are read, or >0 + */ +s32_t lpc_tx_ready(struct netif *netif) +{ + s32_t fb; + u32_t idx, cidx; + + cidx = LPC_EMAC->TxConsumeIndex; + idx = LPC_EMAC->TxProduceIndex; + + /* Determine number of free buffers */ + if (idx == cidx) + fb = LPC_NUM_BUFF_TXDESCS; + else if (cidx > idx) + fb = (LPC_NUM_BUFF_TXDESCS - 1) - + ((idx + LPC_NUM_BUFF_TXDESCS) - cidx); + else + fb = (LPC_NUM_BUFF_TXDESCS - 1) - (cidx - idx); + + return fb; +} + +/** \brief Low level output of a packet. Never call this from an + * interrupt context, as it may block until TX descriptors + * become available. + * + * \param[in] netif the lwip network interface structure for this lpc_enetif + * \param[in] p the MAC packet to send (e.g. IP packet including MAC addresses and type) + * \return ERR_OK if the packet could be sent or an err_t value if the packet couldn't be sent + */ +static err_t lpc_low_level_output(struct netif *netif, struct pbuf *p) +{ + struct lpc_enetdata *lpc_enetif = netif->state; + struct pbuf *q; + u8_t *dst; + u32_t idx, notdmasafe = 0; + struct pbuf *np; + s32_t dn; + + /* Zero-copy TX buffers may be fragmented across mutliple payload + chains. Determine the number of descriptors needed for the + transfer. The pbuf chaining can be a mess! */ + dn = (s32_t) pbuf_clen(p); + + /* Test to make sure packet addresses are DMA safe. A DMA safe + address is once that uses external memory or periphheral RAM. + IRAM and FLASH are not safe! */ + for (q = p; q != NULL; q = q->next) + notdmasafe += lpc_packet_addr_notsafe(q->payload); + +#if LPC_TX_PBUF_BOUNCE_EN==1 + /* If the pbuf is not DMA safe, a new bounce buffer (pbuf) will be + created that will be used instead. This requires an copy from the + non-safe DMA region to the new pbuf */ + if (notdmasafe) { + /* Allocate a pbuf in DMA memory */ + np = pbuf_alloc(PBUF_RAW, p->tot_len, PBUF_RAM); + if (np == NULL) + return ERR_MEM; + + /* This buffer better be contiguous! */ + LWIP_ASSERT("lpc_low_level_output: New transmit pbuf is chained", + (pbuf_clen(np) == 1)); + + /* Copy to DMA safe pbuf */ + dst = (u8_t *) np->payload; + for(q = p; q != NULL; q = q->next) { + /* Copy the buffer to the descriptor's buffer */ + MEMCPY(dst, (u8_t *) q->payload, q->len); + dst += q->len; + } + np->len = p->tot_len; + + LWIP_DEBUGF(UDP_LPC_EMAC | LWIP_DBG_TRACE, + ("lpc_low_level_output: Switched to DMA safe buffer, old=%p, new=%p\n", + q, np)); + + /* use the new buffer for descrptor queueing. The original pbuf will + be de-allocated outsuide this driver. */ + p = np; + dn = 1; + } +#else + if (notdmasafe) + LWIP_ASSERT("lpc_low_level_output: Not a DMA safe pbuf", + (notdmasafe == 0)); +#endif + + /* Wait until enough descriptors are available for the transfer. */ + /* THIS WILL BLOCK UNTIL THERE ARE ENOUGH DESCRIPTORS AVAILABLE */ + while (dn > lpc_tx_ready(netif)) +#if NO_SYS == 0 + osSemaphoreWait(lpc_enetif->xTXDCountSem.id, osWaitForever); +#else + osDelay(1); +#endif + + /* Get free TX buffer index */ + idx = LPC_EMAC->TxProduceIndex; + +#if NO_SYS == 0 + /* Get exclusive access */ + sys_mutex_lock(&lpc_enetif->TXLockMutex); +#endif + + /* Prevent LWIP from de-allocating this pbuf. The driver will + free it once it's been transmitted. */ + if (!notdmasafe) + pbuf_ref(p); + + /* Setup transfers */ + q = p; + while (dn > 0) { + dn--; + + /* Only save pointer to free on last descriptor */ + if (dn == 0) { + /* Save size of packet and signal it's ready */ + lpc_enetif->ptxd[idx].control = (q->len - 1) | EMAC_TCTRL_INT | + EMAC_TCTRL_LAST; + lpc_enetif->txb[idx] = p; + } + else { + /* Save size of packet, descriptor is not last */ + lpc_enetif->ptxd[idx].control = (q->len - 1) | EMAC_TCTRL_INT; + lpc_enetif->txb[idx] = NULL; + } + + LWIP_DEBUGF(UDP_LPC_EMAC | LWIP_DBG_TRACE, + ("lpc_low_level_output: pbuf packet(%p) sent, chain#=%d," + " size = %d (index=%d)\n", q->payload, dn, q->len, idx)); + + lpc_enetif->ptxd[idx].packet = (u32_t) q->payload; + + q = q->next; + + idx++; + if (idx >= LPC_NUM_BUFF_TXDESCS) + idx = 0; + } + + LPC_EMAC->TxProduceIndex = idx; + + LINK_STATS_INC(link.xmit); + +#if NO_SYS == 0 + /* Restore access */ + sys_mutex_unlock(&lpc_enetif->TXLockMutex); +#endif + + return ERR_OK; +} + +/** \brief LPC EMAC interrupt handler. + * + * This function handles the transmit, receive, and error interrupt of + * the LPC177x_8x. This is meant to be used when NO_SYS=0. + */ +void ENET_IRQHandler(void) +{ +#if NO_SYS == 1 + /* Interrupts are not used without an RTOS */ + NVIC_DisableIRQ(ENET_IRQn); +#else + uint32_t ints; + + /* Interrupts are of 2 groups - transmit or receive. Based on the + interrupt, kick off the receive or transmit (cleanup) task */ + + /* Get pending interrupts */ + ints = LPC_EMAC->IntStatus; + + if (ints & RXINTGROUP) { + /* RX group interrupt(s): Give signal to wakeup RX receive task.*/ + osSignalSet(lpc_enetdata.RxThread->id, RX_SIGNAL); + } + + if (ints & TXINTGROUP) { + /* TX group interrupt(s): Give semaphore to wakeup TX cleanup task. */ + sys_sem_signal(&lpc_enetdata.TxCleanSem); + } + + /* Clear pending interrupts */ + LPC_EMAC->IntClear = ints; +#endif +} + +#if NO_SYS == 0 +/** \brief Packet reception task + * + * This task is called when a packet is received. It will + * pass the packet to the LWIP core. + * + * \param[in] pvParameters Not used yet + */ +static void packet_rx(void* pvParameters) { + struct lpc_enetdata *lpc_enetif = pvParameters; + + while (1) { + /* Wait for receive task to wakeup */ + osSignalWait(RX_SIGNAL, osWaitForever); + + /* Process packets until all empty */ + while (LPC_EMAC->RxConsumeIndex != LPC_EMAC->RxProduceIndex) + lpc_enetif_input(lpc_enetif->netif); + } +} + +/** \brief Transmit cleanup task + * + * This task is called when a transmit interrupt occurs and + * reclaims the pbuf and descriptor used for the packet once + * the packet has been transferred. + * + * \param[in] pvParameters Not used yet + */ +static void packet_tx(void* pvParameters) { + struct lpc_enetdata *lpc_enetif = pvParameters; + s32_t idx; + + while (1) { + /* Wait for transmit cleanup task to wakeup */ + sys_arch_sem_wait(&lpc_enetif->TxCleanSem, 0); + + /* Error handling for TX underruns. This should never happen unless + something is holding the bus or the clocks are going too slow. It + can probably be safely removed. */ + if (LPC_EMAC->IntStatus & EMAC_INT_TX_UNDERRUN) { + LINK_STATS_INC(link.err); + LINK_STATS_INC(link.drop); + +#if NO_SYS == 0 + /* Get exclusive access */ + sys_mutex_lock(&lpc_enetif->TXLockMutex); +#endif + /* Reset the TX side */ + LPC_EMAC->MAC1 |= EMAC_MAC1_RES_TX; + LPC_EMAC->IntClear = EMAC_INT_TX_UNDERRUN; + + /* De-allocate all queued TX pbufs */ + for (idx = 0; idx < LPC_NUM_BUFF_TXDESCS; idx++) { + if (lpc_enetif->txb[idx] != NULL) { + pbuf_free(lpc_enetif->txb[idx]); + lpc_enetif->txb[idx] = NULL; + } + } + +#if NO_SYS == 0 + /* Restore access */ + sys_mutex_unlock(&lpc_enetif->TXLockMutex); +#endif + /* Start TX side again */ + lpc_tx_setup(lpc_enetif); + } else { + /* Free TX buffers that are done sending */ + lpc_tx_reclaim(lpc_enetdata.netif); + } + } +} +#endif + +/** \brief Low level init of the MAC and PHY. + * + * \param[in] netif Pointer to LWIP netif structure + */ +static err_t low_level_init(struct netif *netif) +{ + struct lpc_enetdata *lpc_enetif = netif->state; + err_t err = ERR_OK; + + /* Enable MII clocking */ + LPC_SC->PCONP |= CLKPWR_PCONP_PCENET; + +#if defined(TARGET_LPC1768) + LPC_PINCON->PINSEL2 = 0x50150105; /* Enable P1 Ethernet Pins. */ + LPC_PINCON->PINSEL3 = (LPC_PINCON->PINSEL3 & ~0x0000000F) | 0x00000005; +#elif defined(TARGET_LPC4088) || defined(TARGET_LPC4088_DM) + LPC_IOCON->P1_0 &= ~0x07; /* ENET I/O config */ + LPC_IOCON->P1_0 |= 0x01; /* ENET_TXD0 */ + LPC_IOCON->P1_1 &= ~0x07; + LPC_IOCON->P1_1 |= 0x01; /* ENET_TXD1 */ + LPC_IOCON->P1_4 &= ~0x07; + LPC_IOCON->P1_4 |= 0x01; /* ENET_TXEN */ + LPC_IOCON->P1_8 &= ~0x07; + LPC_IOCON->P1_8 |= 0x01; /* ENET_CRS */ + LPC_IOCON->P1_9 &= ~0x07; + LPC_IOCON->P1_9 |= 0x01; /* ENET_RXD0 */ + LPC_IOCON->P1_10 &= ~0x07; + LPC_IOCON->P1_10 |= 0x01; /* ENET_RXD1 */ + LPC_IOCON->P1_14 &= ~0x07; + LPC_IOCON->P1_14 |= 0x01; /* ENET_RX_ER */ + LPC_IOCON->P1_15 &= ~0x07; + LPC_IOCON->P1_15 |= 0x01; /* ENET_REF_CLK */ + LPC_IOCON->P1_16 &= ~0x07; /* ENET/PHY I/O config */ + LPC_IOCON->P1_16 |= 0x01; /* ENET_MDC */ + LPC_IOCON->P1_17 &= ~0x07; + LPC_IOCON->P1_17 |= 0x01; /* ENET_MDIO */ +#endif + + /* Reset all MAC logic */ + LPC_EMAC->MAC1 = EMAC_MAC1_RES_TX | EMAC_MAC1_RES_MCS_TX | + EMAC_MAC1_RES_RX | EMAC_MAC1_RES_MCS_RX | EMAC_MAC1_SIM_RES | + EMAC_MAC1_SOFT_RES; + LPC_EMAC->Command = EMAC_CR_REG_RES | EMAC_CR_TX_RES | EMAC_CR_RX_RES | + EMAC_CR_PASS_RUNT_FRM; + osDelay(10); + + /* Initial MAC initialization */ + LPC_EMAC->MAC1 = EMAC_MAC1_PASS_ALL; + LPC_EMAC->MAC2 = EMAC_MAC2_CRC_EN | EMAC_MAC2_PAD_EN | + EMAC_MAC2_VLAN_PAD_EN; + LPC_EMAC->MAXF = EMAC_ETH_MAX_FLEN; + + /* Set RMII management clock rate to lowest speed */ + LPC_EMAC->MCFG = EMAC_MCFG_CLK_SEL(11) | EMAC_MCFG_RES_MII; + LPC_EMAC->MCFG &= ~EMAC_MCFG_RES_MII; + + /* Maximum number of retries, 0x37 collision window, gap */ + LPC_EMAC->CLRT = EMAC_CLRT_DEF; + LPC_EMAC->IPGR = EMAC_IPGR_P1_DEF | EMAC_IPGR_P2_DEF; + +#if LPC_EMAC_RMII + /* RMII setup */ + LPC_EMAC->Command = EMAC_CR_PASS_RUNT_FRM | EMAC_CR_RMII; +#else + /* MII setup */ + LPC_EMAC->CR = EMAC_CR_PASS_RUNT_FRM; +#endif + + /* Initialize the PHY and reset */ + err = lpc_phy_init(netif, LPC_EMAC_RMII); + if (err != ERR_OK) + return err; + + /* Save station address */ + LPC_EMAC->SA2 = (u32_t) netif->hwaddr[0] | + (((u32_t) netif->hwaddr[1]) << 8); + LPC_EMAC->SA1 = (u32_t) netif->hwaddr[2] | + (((u32_t) netif->hwaddr[3]) << 8); + LPC_EMAC->SA0 = (u32_t) netif->hwaddr[4] | + (((u32_t) netif->hwaddr[5]) << 8); + + /* Setup transmit and receive descriptors */ + if (lpc_tx_setup(lpc_enetif) != ERR_OK) + return ERR_BUF; + if (lpc_rx_setup(lpc_enetif) != ERR_OK) + return ERR_BUF; + + /* Enable packet reception */ +#if IP_SOF_BROADCAST_RECV + LPC_EMAC->RxFilterCtrl = EMAC_RFC_PERFECT_EN | EMAC_RFC_BCAST_EN | EMAC_RFC_MCAST_EN; +#else + LPC_EMAC->RxFilterCtrl = EMAC_RFC_PERFECT_EN; +#endif + + /* Clear and enable rx/tx interrupts */ + LPC_EMAC->IntClear = 0xFFFF; + LPC_EMAC->IntEnable = RXINTGROUP | TXINTGROUP; + + /* Enable RX and TX */ + LPC_EMAC->Command |= EMAC_CR_RX_EN | EMAC_CR_TX_EN; + LPC_EMAC->MAC1 |= EMAC_MAC1_REC_EN; + + return err; +} + +/* This function provides a method for the PHY to setup the EMAC + for the PHY negotiated duplex mode */ +void lpc_emac_set_duplex(int full_duplex) +{ + if (full_duplex) { + LPC_EMAC->MAC2 |= EMAC_MAC2_FULL_DUP; + LPC_EMAC->Command |= EMAC_CR_FULL_DUP; + LPC_EMAC->IPGT = EMAC_IPGT_FULL_DUP; + } else { + LPC_EMAC->MAC2 &= ~EMAC_MAC2_FULL_DUP; + LPC_EMAC->Command &= ~EMAC_CR_FULL_DUP; + LPC_EMAC->IPGT = EMAC_IPGT_HALF_DUP; + } +} + +/* This function provides a method for the PHY to setup the EMAC + for the PHY negotiated bit rate */ +void lpc_emac_set_speed(int mbs_100) +{ + if (mbs_100) + LPC_EMAC->SUPP = EMAC_SUPP_SPEED; + else + LPC_EMAC->SUPP = 0; +} + +/** + * This function is the ethernet packet send function. It calls + * etharp_output after checking link status. + * + * \param[in] netif the lwip network interface structure for this lpc_enetif + * \param[in] q Pointer to pbug to send + * \param[in] ipaddr IP address + * \return ERR_OK or error code + */ +err_t lpc_etharp_output(struct netif *netif, struct pbuf *q, + ip_addr_t *ipaddr) +{ + /* Only send packet is link is up */ + if (netif->flags & NETIF_FLAG_LINK_UP) + return etharp_output(netif, q, ipaddr); + + return ERR_CONN; +} + +#if NO_SYS == 0 +/* periodic PHY status update */ +void phy_update(void const *nif) { + lpc_phy_sts_sm((struct netif*)nif); +} +osTimerDef(phy_update, phy_update); +#endif + +/** + * Should be called at the beginning of the program to set up the + * network interface. + * + * This function should be passed as a parameter to netif_add(). + * + * @param[in] netif the lwip network interface structure for this lpc_enetif + * @return ERR_OK if the loopif is initialized + * ERR_MEM if private data couldn't be allocated + * any other err_t on error + */ +err_t eth_arch_enetif_init(struct netif *netif) +{ + err_t err; + + LWIP_ASSERT("netif != NULL", (netif != NULL)); + + lpc_enetdata.netif = netif; + + /* set MAC hardware address */ +#if (MBED_MAC_ADDRESS_SUM != MBED_MAC_ADDR_INTERFACE) + netif->hwaddr[0] = MBED_MAC_ADDR_0; + netif->hwaddr[1] = MBED_MAC_ADDR_1; + netif->hwaddr[2] = MBED_MAC_ADDR_2; + netif->hwaddr[3] = MBED_MAC_ADDR_3; + netif->hwaddr[4] = MBED_MAC_ADDR_4; + netif->hwaddr[5] = MBED_MAC_ADDR_5; +#else + mbed_mac_address((char *)netif->hwaddr); +#endif + netif->hwaddr_len = ETHARP_HWADDR_LEN; + + /* maximum transfer unit */ + netif->mtu = 1500; + + /* device capabilities */ + netif->flags = NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP | NETIF_FLAG_ETHERNET | NETIF_FLAG_IGMP; + + /* Initialize the hardware */ + netif->state = &lpc_enetdata; + err = low_level_init(netif); + if (err != ERR_OK) + return err; + +#if LWIP_NETIF_HOSTNAME + /* Initialize interface hostname */ + netif->hostname = "lwiplpc"; +#endif /* LWIP_NETIF_HOSTNAME */ + + netif->name[0] = 'e'; + netif->name[1] = 'n'; + + netif->output = lpc_etharp_output; + netif->linkoutput = lpc_low_level_output; + + /* CMSIS-RTOS, start tasks */ +#if NO_SYS == 0 +#ifdef CMSIS_OS_RTX + memset(lpc_enetdata.xTXDCountSem.data, 0, sizeof(lpc_enetdata.xTXDCountSem.data)); + lpc_enetdata.xTXDCountSem.def.semaphore = lpc_enetdata.xTXDCountSem.data; +#endif + lpc_enetdata.xTXDCountSem.id = osSemaphoreCreate(&lpc_enetdata.xTXDCountSem.def, LPC_NUM_BUFF_TXDESCS); + LWIP_ASSERT("xTXDCountSem creation error", (lpc_enetdata.xTXDCountSem.id != NULL)); + + err = sys_mutex_new(&lpc_enetdata.TXLockMutex); + LWIP_ASSERT("TXLockMutex creation error", (err == ERR_OK)); + + /* Packet receive task */ + lpc_enetdata.RxThread = sys_thread_new("receive_thread", packet_rx, netif->state, DEFAULT_THREAD_STACKSIZE, RX_PRIORITY); + LWIP_ASSERT("RxThread creation error", (lpc_enetdata.RxThread)); + + /* Transmit cleanup task */ + err = sys_sem_new(&lpc_enetdata.TxCleanSem, 0); + LWIP_ASSERT("TxCleanSem creation error", (err == ERR_OK)); + sys_thread_new("txclean_thread", packet_tx, netif->state, DEFAULT_THREAD_STACKSIZE, TX_PRIORITY); + + /* periodic PHY status update */ + osTimerId phy_timer = osTimerCreate(osTimer(phy_update), osTimerPeriodic, (void *)netif); + osTimerStart(phy_timer, 250); +#endif + + return ERR_OK; +} + +void eth_arch_enable_interrupts(void) { + NVIC_SetPriority(ENET_IRQn, ((0x01 << 3) | 0x01)); + NVIC_EnableIRQ(ENET_IRQn); +} + +void eth_arch_disable_interrupts(void) { + NVIC_DisableIRQ(ENET_IRQn); +} + +/** + * @} + */ + +/* --------------------------------- End Of File ------------------------------ */ diff --git a/features/unsupported/net/eth/lwip-eth/arch/TARGET_NXP/lpc17xx_emac.h b/features/unsupported/net/eth/lwip-eth/arch/TARGET_NXP/lpc17xx_emac.h new file mode 100644 index 00000000000..9979a2560cc --- /dev/null +++ b/features/unsupported/net/eth/lwip-eth/arch/TARGET_NXP/lpc17xx_emac.h @@ -0,0 +1,661 @@ +/********************************************************************** +* $Id$ lpc17xx_emac.h 2010-05-21 +*//** +* @file lpc17xx_emac.h +* @brief Contains all macro definitions and function prototypes +* support for Ethernet MAC firmware library on LPC17xx +* @version 2.0 +* @date 21. May. 2010 +* @author NXP MCU SW Application Team +* +* Copyright(C) 2010, NXP Semiconductor +* All rights reserved. +* +*********************************************************************** +* Software that is described herein is for illustrative purposes only +* which provides customers with programming information regarding the +* products. This software is supplied "AS IS" without any warranties. +* NXP Semiconductors assumes no responsibility or liability for the +* use of the software, conveys no license or title under any patent, +* copyright, or mask work right to the product. NXP Semiconductors +* reserves the right to make changes in the software without +* notification. NXP Semiconductors also make no representation or +* warranty that such application will be suitable for the specified +* use without further testing or modification. +**********************************************************************/ + +/* Peripheral group ----------------------------------------------------------- */ +/** @defgroup EMAC EMAC (Ethernet Media Access Controller) + * @ingroup LPC1700CMSIS_FwLib_Drivers + * @{ + */ + +#ifndef LPC17XX_EMAC_H_ +#define LPC17XX_EMAC_H_ + +/* Includes ------------------------------------------------------------------- */ +#include "cmsis.h" + +#ifdef __cplusplus +extern "C" +{ +#endif + +#define MCB_LPC_1768 +//#define IAR_LPC_1768 + +/* Public Macros -------------------------------------------------------------- */ +/** @defgroup EMAC_Public_Macros EMAC Public Macros + * @{ + */ + + +/* EMAC PHY status type definitions */ +#define EMAC_PHY_STAT_LINK (0) /**< Link Status */ +#define EMAC_PHY_STAT_SPEED (1) /**< Speed Status */ +#define EMAC_PHY_STAT_DUP (2) /**< Duplex Status */ + +/* EMAC PHY device Speed definitions */ +#define EMAC_MODE_AUTO (0) /**< Auto-negotiation mode */ +#define EMAC_MODE_10M_FULL (1) /**< 10Mbps FullDuplex mode */ +#define EMAC_MODE_10M_HALF (2) /**< 10Mbps HalfDuplex mode */ +#define EMAC_MODE_100M_FULL (3) /**< 100Mbps FullDuplex mode */ +#define EMAC_MODE_100M_HALF (4) /**< 100Mbps HalfDuplex mode */ + +/** + * @} + */ +/* Private Macros ------------------------------------------------------------- */ +/** @defgroup EMAC_Private_Macros EMAC Private Macros + * @{ + */ + + +/* EMAC Memory Buffer configuration for 16K Ethernet RAM */ +#define EMAC_NUM_RX_FRAG 4 /**< Num.of RX Fragments 4*1536= 6.0kB */ +#define EMAC_NUM_TX_FRAG 3 /**< Num.of TX Fragments 3*1536= 4.6kB */ +#define EMAC_ETH_MAX_FLEN 1536 /**< Max. Ethernet Frame Size */ +#define EMAC_TX_FRAME_TOUT 0x00100000 /**< Frame Transmit timeout count */ + +/* --------------------- BIT DEFINITIONS -------------------------------------- */ +/*********************************************************************//** + * Macro defines for MAC Configuration Register 1 + **********************************************************************/ +#define EMAC_MAC1_REC_EN 0x00000001 /**< Receive Enable */ +#define EMAC_MAC1_PASS_ALL 0x00000002 /**< Pass All Receive Frames */ +#define EMAC_MAC1_RX_FLOWC 0x00000004 /**< RX Flow Control */ +#define EMAC_MAC1_TX_FLOWC 0x00000008 /**< TX Flow Control */ +#define EMAC_MAC1_LOOPB 0x00000010 /**< Loop Back Mode */ +#define EMAC_MAC1_RES_TX 0x00000100 /**< Reset TX Logic */ +#define EMAC_MAC1_RES_MCS_TX 0x00000200 /**< Reset MAC TX Control Sublayer */ +#define EMAC_MAC1_RES_RX 0x00000400 /**< Reset RX Logic */ +#define EMAC_MAC1_RES_MCS_RX 0x00000800 /**< Reset MAC RX Control Sublayer */ +#define EMAC_MAC1_SIM_RES 0x00004000 /**< Simulation Reset */ +#define EMAC_MAC1_SOFT_RES 0x00008000 /**< Soft Reset MAC */ + +/*********************************************************************//** + * Macro defines for MAC Configuration Register 2 + **********************************************************************/ +#define EMAC_MAC2_FULL_DUP 0x00000001 /**< Full-Duplex Mode */ +#define EMAC_MAC2_FRM_LEN_CHK 0x00000002 /**< Frame Length Checking */ +#define EMAC_MAC2_HUGE_FRM_EN 0x00000004 /**< Huge Frame Enable */ +#define EMAC_MAC2_DLY_CRC 0x00000008 /**< Delayed CRC Mode */ +#define EMAC_MAC2_CRC_EN 0x00000010 /**< Append CRC to every Frame */ +#define EMAC_MAC2_PAD_EN 0x00000020 /**< Pad all Short Frames */ +#define EMAC_MAC2_VLAN_PAD_EN 0x00000040 /**< VLAN Pad Enable */ +#define EMAC_MAC2_ADET_PAD_EN 0x00000080 /**< Auto Detect Pad Enable */ +#define EMAC_MAC2_PPREAM_ENF 0x00000100 /**< Pure Preamble Enforcement */ +#define EMAC_MAC2_LPREAM_ENF 0x00000200 /**< Long Preamble Enforcement */ +#define EMAC_MAC2_NO_BACKOFF 0x00001000 /**< No Backoff Algorithm */ +#define EMAC_MAC2_BACK_PRESSURE 0x00002000 /**< Backoff Presurre / No Backoff */ +#define EMAC_MAC2_EXCESS_DEF 0x00004000 /**< Excess Defer */ + +/*********************************************************************//** + * Macro defines for Back-to-Back Inter-Packet-Gap Register + **********************************************************************/ +/** Programmable field representing the nibble time offset of the minimum possible period + * between the end of any transmitted packet to the beginning of the next */ +#define EMAC_IPGT_BBIPG(n) (n&0x7F) +/** Recommended value for Full Duplex of Programmable field representing the nibble time + * offset of the minimum possible period between the end of any transmitted packet to the + * beginning of the next */ +#define EMAC_IPGT_FULL_DUP (EMAC_IPGT_BBIPG(0x15)) +/** Recommended value for Half Duplex of Programmable field representing the nibble time + * offset of the minimum possible period between the end of any transmitted packet to the + * beginning of the next */ +#define EMAC_IPGT_HALF_DUP (EMAC_IPGT_BBIPG(0x12)) + +/*********************************************************************//** + * Macro defines for Non Back-to-Back Inter-Packet-Gap Register + **********************************************************************/ +/** Programmable field representing the Non-Back-to-Back Inter-Packet-Gap */ +#define EMAC_IPGR_NBBIPG_P2(n) (n&0x7F) +/** Recommended value for Programmable field representing the Non-Back-to-Back Inter-Packet-Gap Part 1 */ +#define EMAC_IPGR_P2_DEF (EMAC_IPGR_NBBIPG_P2(0x12)) +/** Programmable field representing the optional carrierSense window referenced in + * IEEE 802.3/4.2.3.2.1 'Carrier Deference' */ +#define EMAC_IPGR_NBBIPG_P1(n) ((n&0x7F)<<8) +/** Recommended value for Programmable field representing the Non-Back-to-Back Inter-Packet-Gap Part 2 */ +#define EMAC_IPGR_P1_DEF EMAC_IPGR_NBBIPG_P1(0x0C) + +/*********************************************************************//** + * Macro defines for Collision Window/Retry Register + **********************************************************************/ +/** Programmable field specifying the number of retransmission attempts following a collision before + * aborting the packet due to excessive collisions */ +#define EMAC_CLRT_MAX_RETX(n) (n&0x0F) +/** Programmable field representing the slot time or collision window during which collisions occur + * in properly configured networks */ +#define EMAC_CLRT_COLL(n) ((n&0x3F)<<8) +/** Default value for Collision Window / Retry register */ +#define EMAC_CLRT_DEF ((EMAC_CLRT_MAX_RETX(0x0F))|(EMAC_CLRT_COLL(0x37))) + +/*********************************************************************//** + * Macro defines for Maximum Frame Register + **********************************************************************/ +/** Represents a maximum receive frame of 1536 octets */ +#define EMAC_MAXF_MAXFRMLEN(n) (n&0xFFFF) + +/*********************************************************************//** + * Macro defines for PHY Support Register + **********************************************************************/ +#define EMAC_SUPP_SPEED 0x00000100 /**< Reduced MII Logic Current Speed */ +#define EMAC_SUPP_RES_RMII 0x00000800 /**< Reset Reduced MII Logic */ + +/*********************************************************************//** + * Macro defines for Test Register + **********************************************************************/ +#define EMAC_TEST_SHCUT_PQUANTA 0x00000001 /**< Shortcut Pause Quanta */ +#define EMAC_TEST_TST_PAUSE 0x00000002 /**< Test Pause */ +#define EMAC_TEST_TST_BACKP 0x00000004 /**< Test Back Pressure */ + +/*********************************************************************//** + * Macro defines for MII Management Configuration Register + **********************************************************************/ +#define EMAC_MCFG_SCAN_INC 0x00000001 /**< Scan Increment PHY Address */ +#define EMAC_MCFG_SUPP_PREAM 0x00000002 /**< Suppress Preamble */ +#define EMAC_MCFG_CLK_SEL(n) ((n&0x0F)<<2) /**< Clock Select Field */ +#define EMAC_MCFG_RES_MII 0x00008000 /**< Reset MII Management Hardware */ +#define EMAC_MCFG_MII_MAXCLK 2500000UL /**< MII Clock max */ + +/*********************************************************************//** + * Macro defines for MII Management Command Register + **********************************************************************/ +#define EMAC_MCMD_READ 0x00000001 /**< MII Read */ +#define EMAC_MCMD_SCAN 0x00000002 /**< MII Scan continuously */ + +#define EMAC_MII_WR_TOUT 0x00050000 /**< MII Write timeout count */ +#define EMAC_MII_RD_TOUT 0x00050000 /**< MII Read timeout count */ + +/*********************************************************************//** + * Macro defines for MII Management Address Register + **********************************************************************/ +#define EMAC_MADR_REG_ADR(n) (n&0x1F) /**< MII Register Address field */ +#define EMAC_MADR_PHY_ADR(n) ((n&0x1F)<<8) /**< PHY Address Field */ + +/*********************************************************************//** + * Macro defines for MII Management Write Data Register + **********************************************************************/ +#define EMAC_MWTD_DATA(n) (n&0xFFFF) /**< Data field for MMI Management Write Data register */ + +/*********************************************************************//** + * Macro defines for MII Management Read Data Register + **********************************************************************/ +#define EMAC_MRDD_DATA(n) (n&0xFFFF) /**< Data field for MMI Management Read Data register */ + +/*********************************************************************//** + * Macro defines for MII Management Indicators Register + **********************************************************************/ +#define EMAC_MIND_BUSY 0x00000001 /**< MII is Busy */ +#define EMAC_MIND_SCAN 0x00000002 /**< MII Scanning in Progress */ +#define EMAC_MIND_NOT_VAL 0x00000004 /**< MII Read Data not valid */ +#define EMAC_MIND_MII_LINK_FAIL 0x00000008 /**< MII Link Failed */ + +/* Station Address 0 Register */ +/* Station Address 1 Register */ +/* Station Address 2 Register */ + + +/* Control register definitions --------------------------------------------------------------------------- */ +/*********************************************************************//** + * Macro defines for Command Register + **********************************************************************/ +#define EMAC_CR_RX_EN 0x00000001 /**< Enable Receive */ +#define EMAC_CR_TX_EN 0x00000002 /**< Enable Transmit */ +#define EMAC_CR_REG_RES 0x00000008 /**< Reset Host Registers */ +#define EMAC_CR_TX_RES 0x00000010 /**< Reset Transmit Datapath */ +#define EMAC_CR_RX_RES 0x00000020 /**< Reset Receive Datapath */ +#define EMAC_CR_PASS_RUNT_FRM 0x00000040 /**< Pass Runt Frames */ +#define EMAC_CR_PASS_RX_FILT 0x00000080 /**< Pass RX Filter */ +#define EMAC_CR_TX_FLOW_CTRL 0x00000100 /**< TX Flow Control */ +#define EMAC_CR_RMII 0x00000200 /**< Reduced MII Interface */ +#define EMAC_CR_FULL_DUP 0x00000400 /**< Full Duplex */ + +/*********************************************************************//** + * Macro defines for Status Register + **********************************************************************/ +#define EMAC_SR_RX_EN 0x00000001 /**< Enable Receive */ +#define EMAC_SR_TX_EN 0x00000002 /**< Enable Transmit */ + +/*********************************************************************//** + * Macro defines for Transmit Status Vector 0 Register + **********************************************************************/ +#define EMAC_TSV0_CRC_ERR 0x00000001 /**< CRC error */ +#define EMAC_TSV0_LEN_CHKERR 0x00000002 /**< Length Check Error */ +#define EMAC_TSV0_LEN_OUTRNG 0x00000004 /**< Length Out of Range */ +#define EMAC_TSV0_DONE 0x00000008 /**< Tramsmission Completed */ +#define EMAC_TSV0_MCAST 0x00000010 /**< Multicast Destination */ +#define EMAC_TSV0_BCAST 0x00000020 /**< Broadcast Destination */ +#define EMAC_TSV0_PKT_DEFER 0x00000040 /**< Packet Deferred */ +#define EMAC_TSV0_EXC_DEFER 0x00000080 /**< Excessive Packet Deferral */ +#define EMAC_TSV0_EXC_COLL 0x00000100 /**< Excessive Collision */ +#define EMAC_TSV0_LATE_COLL 0x00000200 /**< Late Collision Occured */ +#define EMAC_TSV0_GIANT 0x00000400 /**< Giant Frame */ +#define EMAC_TSV0_UNDERRUN 0x00000800 /**< Buffer Underrun */ +#define EMAC_TSV0_BYTES 0x0FFFF000 /**< Total Bytes Transferred */ +#define EMAC_TSV0_CTRL_FRAME 0x10000000 /**< Control Frame */ +#define EMAC_TSV0_PAUSE 0x20000000 /**< Pause Frame */ +#define EMAC_TSV0_BACK_PRESS 0x40000000 /**< Backpressure Method Applied */ +#define EMAC_TSV0_VLAN 0x80000000 /**< VLAN Frame */ + +/*********************************************************************//** + * Macro defines for Transmit Status Vector 1 Register + **********************************************************************/ +#define EMAC_TSV1_BYTE_CNT 0x0000FFFF /**< Transmit Byte Count */ +#define EMAC_TSV1_COLL_CNT 0x000F0000 /**< Transmit Collision Count */ + +/*********************************************************************//** + * Macro defines for Receive Status Vector Register + **********************************************************************/ +#define EMAC_RSV_BYTE_CNT 0x0000FFFF /**< Receive Byte Count */ +#define EMAC_RSV_PKT_IGNORED 0x00010000 /**< Packet Previously Ignored */ +#define EMAC_RSV_RXDV_SEEN 0x00020000 /**< RXDV Event Previously Seen */ +#define EMAC_RSV_CARR_SEEN 0x00040000 /**< Carrier Event Previously Seen */ +#define EMAC_RSV_REC_CODEV 0x00080000 /**< Receive Code Violation */ +#define EMAC_RSV_CRC_ERR 0x00100000 /**< CRC Error */ +#define EMAC_RSV_LEN_CHKERR 0x00200000 /**< Length Check Error */ +#define EMAC_RSV_LEN_OUTRNG 0x00400000 /**< Length Out of Range */ +#define EMAC_RSV_REC_OK 0x00800000 /**< Frame Received OK */ +#define EMAC_RSV_MCAST 0x01000000 /**< Multicast Frame */ +#define EMAC_RSV_BCAST 0x02000000 /**< Broadcast Frame */ +#define EMAC_RSV_DRIB_NIBB 0x04000000 /**< Dribble Nibble */ +#define EMAC_RSV_CTRL_FRAME 0x08000000 /**< Control Frame */ +#define EMAC_RSV_PAUSE 0x10000000 /**< Pause Frame */ +#define EMAC_RSV_UNSUPP_OPC 0x20000000 /**< Unsupported Opcode */ +#define EMAC_RSV_VLAN 0x40000000 /**< VLAN Frame */ + +/*********************************************************************//** + * Macro defines for Flow Control Counter Register + **********************************************************************/ +#define EMAC_FCC_MIRR_CNT(n) (n&0xFFFF) /**< Mirror Counter */ +#define EMAC_FCC_PAUSE_TIM(n) ((n&0xFFFF)<<16) /**< Pause Timer */ + +/*********************************************************************//** + * Macro defines for Flow Control Status Register + **********************************************************************/ +#define EMAC_FCS_MIRR_CNT(n) (n&0xFFFF) /**< Mirror Counter Current */ + + +/* Receive filter register definitions -------------------------------------------------------- */ +/*********************************************************************//** + * Macro defines for Receive Filter Control Register + **********************************************************************/ +#define EMAC_RFC_UCAST_EN 0x00000001 /**< Accept Unicast Frames Enable */ +#define EMAC_RFC_BCAST_EN 0x00000002 /**< Accept Broadcast Frames Enable */ +#define EMAC_RFC_MCAST_EN 0x00000004 /**< Accept Multicast Frames Enable */ +#define EMAC_RFC_UCAST_HASH_EN 0x00000008 /**< Accept Unicast Hash Filter Frames */ +#define EMAC_RFC_MCAST_HASH_EN 0x00000010 /**< Accept Multicast Hash Filter Fram.*/ +#define EMAC_RFC_PERFECT_EN 0x00000020 /**< Accept Perfect Match Enable */ +#define EMAC_RFC_MAGP_WOL_EN 0x00001000 /**< Magic Packet Filter WoL Enable */ +#define EMAC_RFC_PFILT_WOL_EN 0x00002000 /**< Perfect Filter WoL Enable */ + +/*********************************************************************//** + * Macro defines for Receive Filter WoL Status/Clear Registers + **********************************************************************/ +#define EMAC_WOL_UCAST 0x00000001 /**< Unicast Frame caused WoL */ +#define EMAC_WOL_BCAST 0x00000002 /**< Broadcast Frame caused WoL */ +#define EMAC_WOL_MCAST 0x00000004 /**< Multicast Frame caused WoL */ +#define EMAC_WOL_UCAST_HASH 0x00000008 /**< Unicast Hash Filter Frame WoL */ +#define EMAC_WOL_MCAST_HASH 0x00000010 /**< Multicast Hash Filter Frame WoL */ +#define EMAC_WOL_PERFECT 0x00000020 /**< Perfect Filter WoL */ +#define EMAC_WOL_RX_FILTER 0x00000080 /**< RX Filter caused WoL */ +#define EMAC_WOL_MAG_PACKET 0x00000100 /**< Magic Packet Filter caused WoL */ +#define EMAC_WOL_BITMASK 0x01BF /**< Receive Filter WoL Status/Clear bitmasl value */ + + +/* Module control register definitions ---------------------------------------------------- */ +/*********************************************************************//** + * Macro defines for Interrupt Status/Enable/Clear/Set Registers + **********************************************************************/ +#define EMAC_INT_RX_OVERRUN 0x00000001 /**< Overrun Error in RX Queue */ +#define EMAC_INT_RX_ERR 0x00000002 /**< Receive Error */ +#define EMAC_INT_RX_FIN 0x00000004 /**< RX Finished Process Descriptors */ +#define EMAC_INT_RX_DONE 0x00000008 /**< Receive Done */ +#define EMAC_INT_TX_UNDERRUN 0x00000010 /**< Transmit Underrun */ +#define EMAC_INT_TX_ERR 0x00000020 /**< Transmit Error */ +#define EMAC_INT_TX_FIN 0x00000040 /**< TX Finished Process Descriptors */ +#define EMAC_INT_TX_DONE 0x00000080 /**< Transmit Done */ +#define EMAC_INT_SOFT_INT 0x00001000 /**< Software Triggered Interrupt */ +#define EMAC_INT_WAKEUP 0x00002000 /**< Wakeup Event Interrupt */ + +/*********************************************************************//** + * Macro defines for Power Down Register + **********************************************************************/ +#define EMAC_PD_POWER_DOWN 0x80000000 /**< Power Down MAC */ + +/* Descriptor and status formats ---------------------------------------------------- */ +/*********************************************************************//** + * Macro defines for RX Descriptor Control Word + **********************************************************************/ +#define EMAC_RCTRL_SIZE(n) (n&0x7FF) /**< Buffer size field */ +#define EMAC_RCTRL_INT 0x80000000 /**< Generate RxDone Interrupt */ + +/*********************************************************************//** + * Macro defines for RX Status Hash CRC Word + **********************************************************************/ +#define EMAC_RHASH_SA 0x000001FF /**< Hash CRC for Source Address */ +#define EMAC_RHASH_DA 0x001FF000 /**< Hash CRC for Destination Address */ + +/*********************************************************************//** + * Macro defines for RX Status Information Word + **********************************************************************/ +#define EMAC_RINFO_SIZE 0x000007FF /**< Data size in bytes */ +#define EMAC_RINFO_CTRL_FRAME 0x00040000 /**< Control Frame */ +#define EMAC_RINFO_VLAN 0x00080000 /**< VLAN Frame */ +#define EMAC_RINFO_FAIL_FILT 0x00100000 /**< RX Filter Failed */ +#define EMAC_RINFO_MCAST 0x00200000 /**< Multicast Frame */ +#define EMAC_RINFO_BCAST 0x00400000 /**< Broadcast Frame */ +#define EMAC_RINFO_CRC_ERR 0x00800000 /**< CRC Error in Frame */ +#define EMAC_RINFO_SYM_ERR 0x01000000 /**< Symbol Error from PHY */ +#define EMAC_RINFO_LEN_ERR 0x02000000 /**< Length Error */ +#define EMAC_RINFO_RANGE_ERR 0x04000000 /**< Range Error (exceeded max. size) */ +#define EMAC_RINFO_ALIGN_ERR 0x08000000 /**< Alignment Error */ +#define EMAC_RINFO_OVERRUN 0x10000000 /**< Receive overrun */ +#define EMAC_RINFO_NO_DESCR 0x20000000 /**< No new Descriptor available */ +#define EMAC_RINFO_LAST_FLAG 0x40000000 /**< Last Fragment in Frame */ +#define EMAC_RINFO_ERR 0x80000000 /**< Error Occured (OR of all errors) */ +#define EMAC_RINFO_ERR_MASK (EMAC_RINFO_FAIL_FILT | EMAC_RINFO_CRC_ERR | EMAC_RINFO_SYM_ERR | \ +EMAC_RINFO_LEN_ERR | EMAC_RINFO_ALIGN_ERR | EMAC_RINFO_OVERRUN) + +/*********************************************************************//** + * Macro defines for TX Descriptor Control Word + **********************************************************************/ +#define EMAC_TCTRL_SIZE 0x000007FF /**< Size of data buffer in bytes */ +#define EMAC_TCTRL_OVERRIDE 0x04000000 /**< Override Default MAC Registers */ +#define EMAC_TCTRL_HUGE 0x08000000 /**< Enable Huge Frame */ +#define EMAC_TCTRL_PAD 0x10000000 /**< Pad short Frames to 64 bytes */ +#define EMAC_TCTRL_CRC 0x20000000 /**< Append a hardware CRC to Frame */ +#define EMAC_TCTRL_LAST 0x40000000 /**< Last Descriptor for TX Frame */ +#define EMAC_TCTRL_INT 0x80000000 /**< Generate TxDone Interrupt */ + +/*********************************************************************//** + * Macro defines for TX Status Information Word + **********************************************************************/ +#define EMAC_TINFO_COL_CNT 0x01E00000 /**< Collision Count */ +#define EMAC_TINFO_DEFER 0x02000000 /**< Packet Deferred (not an error) */ +#define EMAC_TINFO_EXCESS_DEF 0x04000000 /**< Excessive Deferral */ +#define EMAC_TINFO_EXCESS_COL 0x08000000 /**< Excessive Collision */ +#define EMAC_TINFO_LATE_COL 0x10000000 /**< Late Collision Occured */ +#define EMAC_TINFO_UNDERRUN 0x20000000 /**< Transmit Underrun */ +#define EMAC_TINFO_NO_DESCR 0x40000000 /**< No new Descriptor available */ +#define EMAC_TINFO_ERR 0x80000000 /**< Error Occured (OR of all errors) */ + +#ifdef MCB_LPC_1768 +/* DP83848C PHY definition ------------------------------------------------------------ */ + +/** PHY device reset time out definition */ +#define EMAC_PHY_RESP_TOUT 0x100000UL + +/* ENET Device Revision ID */ +#define EMAC_OLD_EMAC_MODULE_ID 0x39022000 /**< Rev. ID for first rev '-' */ + +/*********************************************************************//** + * Macro defines for DP83848C PHY Registers + **********************************************************************/ +#define EMAC_PHY_REG_BMCR 0x00 /**< Basic Mode Control Register */ +#define EMAC_PHY_REG_BMSR 0x01 /**< Basic Mode Status Register */ +#define EMAC_PHY_REG_IDR1 0x02 /**< PHY Identifier 1 */ +#define EMAC_PHY_REG_IDR2 0x03 /**< PHY Identifier 2 */ +#define EMAC_PHY_REG_ANAR 0x04 /**< Auto-Negotiation Advertisement */ +#define EMAC_PHY_REG_ANLPAR 0x05 /**< Auto-Neg. Link Partner Abitily */ +#define EMAC_PHY_REG_ANER 0x06 /**< Auto-Neg. Expansion Register */ +#define EMAC_PHY_REG_ANNPTR 0x07 /**< Auto-Neg. Next Page TX */ +#define EMAC_PHY_REG_LPNPA 0x08 + +/*********************************************************************//** + * Macro defines for PHY Extended Registers + **********************************************************************/ +#define EMAC_PHY_REG_STS 0x10 /**< Status Register */ +#define EMAC_PHY_REG_MICR 0x11 /**< MII Interrupt Control Register */ +#define EMAC_PHY_REG_MISR 0x12 /**< MII Interrupt Status Register */ +#define EMAC_PHY_REG_FCSCR 0x14 /**< False Carrier Sense Counter */ +#define EMAC_PHY_REG_RECR 0x15 /**< Receive Error Counter */ +#define EMAC_PHY_REG_PCSR 0x16 /**< PCS Sublayer Config. and Status */ +#define EMAC_PHY_REG_RBR 0x17 /**< RMII and Bypass Register */ +#define EMAC_PHY_REG_LEDCR 0x18 /**< LED Direct Control Register */ +#define EMAC_PHY_REG_PHYCR 0x19 /**< PHY Control Register */ +#define EMAC_PHY_REG_10BTSCR 0x1A /**< 10Base-T Status/Control Register */ +#define EMAC_PHY_REG_CDCTRL1 0x1B /**< CD Test Control and BIST Extens. */ +#define EMAC_PHY_REG_EDCR 0x1D /**< Energy Detect Control Register */ + +/*********************************************************************//** + * Macro defines for PHY Basic Mode Control Register + **********************************************************************/ +#define EMAC_PHY_BMCR_RESET (1<<15) /**< Reset bit */ +#define EMAC_PHY_BMCR_LOOPBACK (1<<14) /**< Loop back */ +#define EMAC_PHY_BMCR_SPEED_SEL (1<<13) /**< Speed selection */ +#define EMAC_PHY_BMCR_AN (1<<12) /**< Auto Negotiation */ +#define EMAC_PHY_BMCR_POWERDOWN (1<<11) /**< Power down mode */ +#define EMAC_PHY_BMCR_ISOLATE (1<<10) /**< Isolate */ +#define EMAC_PHY_BMCR_RE_AN (1<<9) /**< Restart auto negotiation */ +#define EMAC_PHY_BMCR_DUPLEX (1<<8) /**< Duplex mode */ + +/*********************************************************************//** + * Macro defines for PHY Basic Mode Status Status Register + **********************************************************************/ +#define EMAC_PHY_BMSR_100BE_T4 (1<<15) /**< 100 base T4 */ +#define EMAC_PHY_BMSR_100TX_FULL (1<<14) /**< 100 base full duplex */ +#define EMAC_PHY_BMSR_100TX_HALF (1<<13) /**< 100 base half duplex */ +#define EMAC_PHY_BMSR_10BE_FULL (1<<12) /**< 10 base T full duplex */ +#define EMAC_PHY_BMSR_10BE_HALF (1<<11) /**< 10 base T half duplex */ +#define EMAC_PHY_BMSR_NOPREAM (1<<6) /**< MF Preamable Supress */ +#define EMAC_PHY_BMSR_AUTO_DONE (1<<5) /**< Auto negotiation complete */ +#define EMAC_PHY_BMSR_REMOTE_FAULT (1<<4) /**< Remote fault */ +#define EMAC_PHY_BMSR_NO_AUTO (1<<3) /**< Auto Negotiation ability */ +#define EMAC_PHY_BMSR_LINK_ESTABLISHED (1<<2) /**< Link status */ + +/*********************************************************************//** + * Macro defines for PHY Status Register + **********************************************************************/ +#define EMAC_PHY_SR_REMOTE_FAULT (1<<6) /**< Remote Fault */ +#define EMAC_PHY_SR_JABBER (1<<5) /**< Jabber detect */ +#define EMAC_PHY_SR_AUTO_DONE (1<<4) /**< Auto Negotiation complete */ +#define EMAC_PHY_SR_LOOPBACK (1<<3) /**< Loop back status */ +#define EMAC_PHY_SR_DUP (1<<2) /**< Duplex status */ +#define EMAC_PHY_SR_SPEED (1<<1) /**< Speed status */ +#define EMAC_PHY_SR_LINK (1<<0) /**< Link Status */ + +#define EMAC_PHY_FULLD_100M 0x2100 /**< Full Duplex 100Mbit */ +#define EMAC_PHY_HALFD_100M 0x2000 /**< Half Duplex 100Mbit */ +#define EMAC_PHY_FULLD_10M 0x0100 /**< Full Duplex 10Mbit */ +#define EMAC_PHY_HALFD_10M 0x0000 /**< Half Duplex 10MBit */ +#define EMAC_PHY_AUTO_NEG 0x3000 /**< Select Auto Negotiation */ + +#define EMAC_DEF_ADR 0x0100 /**< Default PHY device address */ +#define EMAC_DP83848C_ID 0x20005C90 /**< PHY Identifier */ + +#define EMAC_PHY_SR_100_SPEED ((1<<14)|(1<<13)) +#define EMAC_PHY_SR_FULL_DUP ((1<<14)|(1<<12)) +#define EMAC_PHY_BMSR_LINK_STATUS (1<<2) /**< Link status */ + +#elif defined(IAR_LPC_1768) +/* KSZ8721BL PHY definition ------------------------------------------------------------ */ +/** PHY device reset time out definition */ +#define EMAC_PHY_RESP_TOUT 0x100000UL + +/* ENET Device Revision ID */ +#define EMAC_OLD_EMAC_MODULE_ID 0x39022000 /**< Rev. ID for first rev '-' */ + +/*********************************************************************//** + * Macro defines for KSZ8721BL PHY Registers + **********************************************************************/ +#define EMAC_PHY_REG_BMCR 0x00 /**< Basic Mode Control Register */ +#define EMAC_PHY_REG_BMSR 0x01 /**< Basic Mode Status Register */ +#define EMAC_PHY_REG_IDR1 0x02 /**< PHY Identifier 1 */ +#define EMAC_PHY_REG_IDR2 0x03 /**< PHY Identifier 2 */ +#define EMAC_PHY_REG_ANAR 0x04 /**< Auto-Negotiation Advertisement */ +#define EMAC_PHY_REG_ANLPAR 0x05 /**< Auto-Neg. Link Partner Abitily */ +#define EMAC_PHY_REG_ANER 0x06 /**< Auto-Neg. Expansion Register */ +#define EMAC_PHY_REG_ANNPTR 0x07 /**< Auto-Neg. Next Page TX */ +#define EMAC_PHY_REG_LPNPA 0x08 /**< Link Partner Next Page Ability */ +#define EMAC_PHY_REG_REC 0x15 /**< RXError Counter Register */ +#define EMAC_PHY_REG_ISC 0x1b /**< Interrupt Control/Status Register */ +#define EMAC_PHY_REG_100BASE 0x1f /**< 100BASE-TX PHY Control Register */ + +/*********************************************************************//** + * Macro defines for PHY Basic Mode Control Register + **********************************************************************/ +#define EMAC_PHY_BMCR_RESET (1<<15) /**< Reset bit */ +#define EMAC_PHY_BMCR_LOOPBACK (1<<14) /**< Loop back */ +#define EMAC_PHY_BMCR_SPEED_SEL (1<<13) /**< Speed selection */ +#define EMAC_PHY_BMCR_AN (1<<12) /**< Auto Negotiation */ +#define EMAC_PHY_BMCR_POWERDOWN (1<<11) /**< Power down mode */ +#define EMAC_PHY_BMCR_ISOLATE (1<<10) /**< Isolate */ +#define EMAC_PHY_BMCR_RE_AN (1<<9) /**< Restart auto negotiation */ +#define EMAC_PHY_BMCR_DUPLEX (1<<8) /**< Duplex mode */ +#define EMAC_PHY_BMCR_COLLISION (1<<7) /**< Collision test */ +#define EMAC_PHY_BMCR_TXDIS (1<<0) /**< Disable transmit */ + +/*********************************************************************//** + * Macro defines for PHY Basic Mode Status Register + **********************************************************************/ +#define EMAC_PHY_BMSR_100BE_T4 (1<<15) /**< 100 base T4 */ +#define EMAC_PHY_BMSR_100TX_FULL (1<<14) /**< 100 base full duplex */ +#define EMAC_PHY_BMSR_100TX_HALF (1<<13) /**< 100 base half duplex */ +#define EMAC_PHY_BMSR_10BE_FULL (1<<12) /**< 10 base T full duplex */ +#define EMAC_PHY_BMSR_10BE_HALF (1<<11) /**< 10 base T half duplex */ +#define EMAC_PHY_BMSR_NOPREAM (1<<6) /**< MF Preamable Supress */ +#define EMAC_PHY_BMSR_AUTO_DONE (1<<5) /**< Auto negotiation complete */ +#define EMAC_PHY_BMSR_REMOTE_FAULT (1<<4) /**< Remote fault */ +#define EMAC_PHY_BMSR_NO_AUTO (1<<3) /**< Auto Negotiation ability */ +#define EMAC_PHY_BMSR_LINK_STATUS (1<<2) /**< Link status */ +#define EMAC_PHY_BMSR_JABBER_DETECT (1<<1) /**< Jabber detect */ +#define EMAC_PHY_BMSR_EXTEND (1<<0) /**< Extended support */ + +/*********************************************************************//** + * Macro defines for PHY Identifier + **********************************************************************/ +/* PHY Identifier 1 bitmap definitions */ +#define EMAC_PHY_IDR1(n) (n & 0xFFFF) /**< PHY ID1 Number */ + +/* PHY Identifier 2 bitmap definitions */ +#define EMAC_PHY_IDR2(n) (n & 0xFFFF) /**< PHY ID2 Number */ + +/*********************************************************************//** + * Macro defines for Auto-Negotiation Advertisement + **********************************************************************/ +#define EMAC_PHY_AN_NEXTPAGE (1<<15) /**< Next page capable */ +#define EMAC_PHY_AN_REMOTE_FAULT (1<<13) /**< Remote Fault support */ +#define EMAC_PHY_AN_PAUSE (1<<10) /**< Pause support */ +#define EMAC_PHY_AN_100BASE_T4 (1<<9) /**< T4 capable */ +#define EMAC_PHY_AN_100BASE_TX_FD (1<<8) /**< TX with Full-duplex capable */ +#define EMAC_PHY_AN_100BASE_TX (1<<7) /**< TX capable */ +#define EMAC_PHY_AN_10BASE_T_FD (1<<6) /**< 10Mbps with full-duplex capable */ +#define EMAC_PHY_AN_10BASE_T (1<<5) /**< 10Mbps capable */ +#define EMAC_PHY_AN_FIELD(n) (n & 0x1F) /**< Selector Field */ + +#define EMAC_PHY_FULLD_100M 0x2100 /**< Full Duplex 100Mbit */ +#define EMAC_PHY_HALFD_100M 0x2000 /**< Half Duplex 100Mbit */ +#define EMAC_PHY_FULLD_10M 0x0100 /**< Full Duplex 10Mbit */ +#define EMAC_PHY_HALFD_10M 0x0000 /**< Half Duplex 10MBit */ +#define EMAC_PHY_AUTO_NEG 0x3000 /**< Select Auto Negotiation */ + +#define EMAC_PHY_SR_100_SPEED ((1<<14)|(1<<13)) +#define EMAC_PHY_SR_FULL_DUP ((1<<14)|(1<<12)) + +#define EMAC_DEF_ADR (0x01<<8) /**< Default PHY device address */ +#define EMAC_KSZ8721BL_ID ((0x22 << 16) | 0x1619 ) /**< PHY Identifier */ +#endif + +/** + * @} + */ + + +/* Public Types --------------------------------------------------------------- */ +/** @defgroup EMAC_Public_Types EMAC Public Types + * @{ + */ + +/* Descriptor and status formats ---------------------------------------------- */ + +/** + * @brief RX Descriptor structure type definition + */ +typedef struct { + uint32_t Packet; /**< Receive Packet Descriptor */ + uint32_t Ctrl; /**< Receive Control Descriptor */ +} RX_Desc; + +/** + * @brief RX Status structure type definition + */ +typedef struct { + uint32_t Info; /**< Receive Information Status */ + uint32_t HashCRC; /**< Receive Hash CRC Status */ +} RX_Stat; + +/** + * @brief TX Descriptor structure type definition + */ +typedef struct { + uint32_t Packet; /**< Transmit Packet Descriptor */ + uint32_t Ctrl; /**< Transmit Control Descriptor */ +} TX_Desc; + +/** + * @brief TX Status structure type definition + */ +typedef struct { + uint32_t Info; /**< Transmit Information Status */ +} TX_Stat; + + +/** + * @brief TX Data Buffer structure definition + */ +typedef struct { + uint32_t ulDataLen; /**< Data length */ + uint32_t *pbDataBuf; /**< A word-align data pointer to data buffer */ +} EMAC_PACKETBUF_Type; + +/** + * @brief EMAC configuration structure definition + */ +typedef struct { + uint32_t Mode; /**< Supported EMAC PHY device speed, should be one of the following: + - EMAC_MODE_AUTO + - EMAC_MODE_10M_FULL + - EMAC_MODE_10M_HALF + - EMAC_MODE_100M_FULL + - EMAC_MODE_100M_HALF + */ + uint8_t *pbEMAC_Addr; /**< Pointer to EMAC Station address that contains 6-bytes + of MAC address, it must be sorted in order (bEMAC_Addr[0]..[5]) + */ +} EMAC_CFG_Type; + +/** Ethernet block power/clock control bit*/ +#define CLKPWR_PCONP_PCENET ((uint32_t)(1<<30)) + +#ifdef __cplusplus +} +#endif + +#endif /* LPC17XX_EMAC_H_ */ + +/** + * @} + */ + +/* --------------------------------- End Of File ------------------------------ */ diff --git a/features/unsupported/net/eth/lwip-eth/arch/TARGET_NXP/lpc_emac_config.h b/features/unsupported/net/eth/lwip-eth/arch/TARGET_NXP/lpc_emac_config.h new file mode 100644 index 00000000000..831b3d76d09 --- /dev/null +++ b/features/unsupported/net/eth/lwip-eth/arch/TARGET_NXP/lpc_emac_config.h @@ -0,0 +1,111 @@ +/********************************************************************** +* $Id$ lpc_emac_config.h 2011-11-20 +*//** +* @file lpc_emac_config.h +* @brief PHY and EMAC configuration file +* @version 1.0 +* @date 20 Nov. 2011 +* @author NXP MCU SW Application Team +* +* Copyright(C) 2011, NXP Semiconductor +* All rights reserved. +* +*********************************************************************** +* Software that is described herein is for illustrative purposes only +* which provides customers with programming information regarding the +* products. This software is supplied "AS IS" without any warranties. +* NXP Semiconductors assumes no responsibility or liability for the +* use of the software, conveys no license or title under any patent, +* copyright, or mask work right to the product. NXP Semiconductors +* reserves the right to make changes in the software without +* notification. NXP Semiconductors also make no representation or +* warranty that such application will be suitable for the specified +* use without further testing or modification. +**********************************************************************/ + +#ifndef __LPC_EMAC_CONFIG_H +#define __LPC_EMAC_CONFIG_H + +#include "lwip/opt.h" + +#ifdef __cplusplus +extern "C" +{ +#endif + +/** @defgroup lwip_phy_config LWIP PHY configuration + * @ingroup lwip_phy + * + * Configuration options for the PHY connected to the LPC EMAC. + * @{ + */ + +/** \brief The PHY address connected the to MII/RMII + */ +#define LPC_PHYDEF_PHYADDR 1 /**< The PHY address on the PHY device. */ + +/** \brief Enable autonegotiation mode. + * If this is enabled, the PHY will attempt to auto-negotiate the + * best link mode if the PHY supports it. If this is not enabled, + * the PHY_USE_FULL_DUPLEX and PHY_USE_100MBS defines will be + * used to select the link mode. Note that auto-negotiation may + * take a few seconds to complete. + */ +#define PHY_USE_AUTONEG 1 /**< Enables auto-negotiation mode. */ + +/** \brief Sets up the PHY interface to either full duplex operation or + * half duplex operation if PHY_USE_AUTONEG is not enabled. + */ +#define PHY_USE_FULL_DUPLEX 1 /**< Sets duplex mode to full. */ + +/** \brief Sets up the PHY interface to either 100MBS operation or 10MBS + * operation if PHY_USE_AUTONEG is not enabled. + */ +#define PHY_USE_100MBS 1 /**< Sets data rate to 100Mbps. */ + +/** + * @} + */ + +/** @defgroup lwip_emac_config LWIP EMAC configuration + * @ingroup lwip_emac + * + * Configuration options for the LPC EMAC. + * @{ + */ + +/** \brief Selects RMII or MII connection type in the EMAC peripheral + */ +#define LPC_EMAC_RMII 1 /**< Use the RMII or MII driver variant .*/ + +/** \brief Defines the number of descriptors used for RX. This + * must be a minimum value of 2. + */ +#define LPC_NUM_BUFF_RXDESCS 3 + +/** \brief Defines the number of descriptors used for TX. Must + * be a minimum value of 2. + */ +#define LPC_NUM_BUFF_TXDESCS (TCP_SND_QUEUELEN + 1) + +/** \brief Set this define to 1 to enable bounce buffers for transmit pbufs + * that cannot be sent via the zero-copy method. Some chained pbufs + * may have a payload address that links to an area of memory that + * cannot be used for transmit DMA operations. If this define is + * set to 1, an extra check will be made with the pbufs. If a buffer + * is determined to be non-usable for zero-copy, a temporary bounce + * buffer will be created and used instead. + */ +#define LPC_TX_PBUF_BOUNCE_EN 1 + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __LPC_EMAC_CONFIG_H */ + +/* --------------------------------- End Of File ------------------------------ */ diff --git a/features/unsupported/net/eth/lwip-eth/arch/TARGET_NXP/lpc_phy.h b/features/unsupported/net/eth/lwip-eth/arch/TARGET_NXP/lpc_phy.h new file mode 100644 index 00000000000..fa53656a775 --- /dev/null +++ b/features/unsupported/net/eth/lwip-eth/arch/TARGET_NXP/lpc_phy.h @@ -0,0 +1,151 @@ +/********************************************************************** +* $Id$ lpc_phy.h 2011-11-20 +*//** +* @file lpc_phy.h +* @brief Common PHY definitions used with all PHYs +* @version 1.0 +* @date 20 Nov. 2011 +* @author NXP MCU SW Application Team +* +* Copyright(C) 2011, NXP Semiconductor +* All rights reserved. +* +*********************************************************************** +* Software that is described herein is for illustrative purposes only +* which provides customers with programming information regarding the +* products. This software is supplied "AS IS" without any warranties. +* NXP Semiconductors assumes no responsibility or liability for the +* use of the software, conveys no license or title under any patent, +* copyright, or mask work right to the product. NXP Semiconductors +* reserves the right to make changes in the software without +* notification. NXP Semiconductors also make no representation or +* warranty that such application will be suitable for the specified +* use without further testing or modification. +**********************************************************************/ + +#ifndef __LPC_PHY_H_ +#define __LPC_PHY_H_ + +#include "lwip/opt.h" +#include "lwip/err.h" +#include "lwip/netif.h" + +#ifdef __cplusplus +extern "C" +{ +#endif + +/* These PHY functions are usually part of the EMAC driver */ + +/** \brief Phy status update state machine + * + * This function provides a state machine for maintaining the PHY + * status without blocking. It must be occasionally called for the + * PHY status to be maintained. + * + * \param[in] netif NETIF structure + */ +s32_t lpc_phy_sts_sm(struct netif *netif); + +/** \brief Initialize the PHY + * + * This function initializes the PHY. It will block until complete. + * This function is called as part of the EMAC driver + * initialization. Configuration of the PHY at startup is + * controlled by setting up configuration defines in lpc_phy.h. + * + * \param[in] netif NETIF structure + * \param[in] rmii If set, configures the PHY for RMII mode + * \return ERR_OK if the setup was successful, otherwise ERR_TIMEOUT + */ +err_t lpc_phy_init(struct netif *netif, int rmii); + +/** \brief Write a value via the MII link (non-blocking) + * + * This function will write a value on the MII link interface to a PHY + * or a connected device. The function will return immediately without + * a status. Status needs to be polled later to determine if the write + * was successful. + * + * \param[in] PhyReg PHY register to write to + * \param[in] Value Value to write + */ +void lpc_mii_write_noblock(u32_t PhyReg, u32_t Value); + +/** \brief Write a value via the MII link (blocking) + * + * This function will write a value on the MII link interface to a PHY + * or a connected device. The function will block until complete. + * + * \param[in] PhyReg PHY register to write to + * \param[in] Value Value to write + * \returns 0 if the write was successful, otherwise !0 + */ +err_t lpc_mii_write(u32_t PhyReg, u32_t Value); + +/** \brief Reads current MII link busy status + * + * This function will return the current MII link busy status and is meant to + * be used with non-blocking functions for monitor PHY status such as + * connection state. + * + * \returns !0 if the MII link is busy, otherwise 0 + */ +u32_t lpc_mii_is_busy(void); + +/** \brief Starts a read operation via the MII link (non-blocking) + * + * This function returns the current value in the MII data register. It is + * meant to be used with the non-blocking oeprations. This value should + * only be read after a non-block read command has been issued and the + * MII status has been determined to be good. + * + * \returns The current value in the MII value register + */ +u32_t lpc_mii_read_data(void); + +/** \brief Starts a read operation via the MII link (non-blocking) + * + * This function will start a read operation on the MII link interface + * from a PHY or a connected device. The function will not block and + * the status mist be polled until complete. Once complete, the data + * can be read. + * + * \param[in] PhyReg PHY register to read from + */ +err_t lpc_mii_read(u32_t PhyReg, u32_t *data); + +/** \brief Read a value via the MII link (blocking) + * + * This function will read a value on the MII link interface from a PHY + * or a connected device. The function will block until complete. + * + * \param[in] PhyReg PHY register to read from + * \param[in] data Pointer to where to save data read via MII + * \returns 0 if the read was successful, otherwise !0 + */ +void lpc_mii_read_noblock(u32_t PhyReg); + +/** + * This function provides a method for the PHY to setup the EMAC + * for the PHY negotiated duplex mode. + * + * @param[in] full_duplex 0 = half duplex, 1 = full duplex + */ +void lpc_emac_set_duplex(int full_duplex); + +/** + * This function provides a method for the PHY to setup the EMAC + * for the PHY negotiated bit rate. + * + * @param[in] mbs_100 0 = 10mbs mode, 1 = 100mbs mode + */ +void lpc_emac_set_speed(int mbs_100); + +#ifdef __cplusplus +} +#endif + +#endif /* __LPC_PHY_H_ */ + +/* --------------------------------- End Of File ------------------------------ */ diff --git a/features/unsupported/net/eth/lwip-eth/arch/TARGET_NXP/lpc_phy_dp83848.c b/features/unsupported/net/eth/lwip-eth/arch/TARGET_NXP/lpc_phy_dp83848.c new file mode 100644 index 00000000000..14813a561b0 --- /dev/null +++ b/features/unsupported/net/eth/lwip-eth/arch/TARGET_NXP/lpc_phy_dp83848.c @@ -0,0 +1,438 @@ +/********************************************************************** +* $Id$ lpc_phy_dp83848.c 2011-11-20 +*//** +* @file lpc_phy_dp83848.c +* @brief DP83848C PHY status and control. +* @version 1.0 +* @date 20 Nov. 2011 +* @author NXP MCU SW Application Team +* +* Copyright(C) 2011, NXP Semiconductor +* All rights reserved. +* +*********************************************************************** +* Software that is described herein is for illustrative purposes only +* which provides customers with programming information regarding the +* products. This software is supplied "AS IS" without any warranties. +* NXP Semiconductors assumes no responsibility or liability for the +* use of the software, conveys no license or title under any patent, +* copyright, or mask work right to the product. NXP Semiconductors +* reserves the right to make changes in the software without +* notification. NXP Semiconductors also make no representation or +* warranty that such application will be suitable for the specified +* use without further testing or modification. +**********************************************************************/ + +#include "lwip/opt.h" +#include "lwip/err.h" +#include "lwip/tcpip.h" +#include "lwip/snmp.h" +#include "lpc_emac_config.h" +#include "lpc_phy.h" +#include "lpc17xx_emac.h" + +/** @defgroup dp83848_phy PHY status and control for the DP83848. + * @ingroup lwip_phy + * + * Various functions for controlling and monitoring the status of the + * DP83848 PHY. In polled (standalone) systems, the PHY state must be + * monitored as part of the application. In a threaded (RTOS) system, + * the PHY state is monitored by the PHY handler thread. The MAC + * driver will not transmit unless the PHY link is active. + * @{ + */ + +/** \brief DP83848 PHY register offsets */ +#define DP8_BMCR_REG 0x0 /**< Basic Mode Control Register */ +#define DP8_BMSR_REG 0x1 /**< Basic Mode Status Reg */ +#define DP8_IDR1_REG 0x2 /**< Basic Mode Status Reg */ +#define DP8_IDR2_REG 0x3 /**< Basic Mode Status Reg */ +#define DP8_ANADV_REG 0x4 /**< Auto_Neg Advt Reg */ +#define DP8_ANLPA_REG 0x5 /**< Auto_neg Link Partner Ability Reg */ +#define DP8_ANEEXP_REG 0x6 /**< Auto-neg Expansion Reg */ +#define DP8_PHY_STAT_REG 0x10 /**< PHY Status Register */ +#define DP8_PHY_INT_CTL_REG 0x11 /**< PHY Interrupt Control Register */ +#define DP8_PHY_RBR_REG 0x17 /**< PHY RMII and Bypass Register */ +#define DP8_PHY_STS_REG 0x19 /**< PHY Status Register */ + +#define DP8_PHY_SCSR_REG 0x1f /**< PHY Special Control/Status Register (LAN8720) */ + +/** \brief DP83848 Control register definitions */ +#define DP8_RESET (1 << 15) /**< 1= S/W Reset */ +#define DP8_LOOPBACK (1 << 14) /**< 1=loopback Enabled */ +#define DP8_SPEED_SELECT (1 << 13) /**< 1=Select 100MBps */ +#define DP8_AUTONEG (1 << 12) /**< 1=Enable auto-negotiation */ +#define DP8_POWER_DOWN (1 << 11) /**< 1=Power down PHY */ +#define DP8_ISOLATE (1 << 10) /**< 1=Isolate PHY */ +#define DP8_RESTART_AUTONEG (1 << 9) /**< 1=Restart auto-negoatiation */ +#define DP8_DUPLEX_MODE (1 << 8) /**< 1=Full duplex mode */ +#define DP8_COLLISION_TEST (1 << 7) /**< 1=Perform collsion test */ + +/** \brief DP83848 Status register definitions */ +#define DP8_100BASE_T4 (1 << 15) /**< T4 mode */ +#define DP8_100BASE_TX_FD (1 << 14) /**< 100MBps full duplex */ +#define DP8_100BASE_TX_HD (1 << 13) /**< 100MBps half duplex */ +#define DP8_10BASE_T_FD (1 << 12) /**< 100Bps full duplex */ +#define DP8_10BASE_T_HD (1 << 11) /**< 10MBps half duplex */ +#define DP8_MF_PREAMB_SUPPR (1 << 6) /**< Preamble suppress */ +#define DP8_AUTONEG_COMP (1 << 5) /**< Auto-negotation complete */ +#define DP8_RMT_FAULT (1 << 4) /**< Fault */ +#define DP8_AUTONEG_ABILITY (1 << 3) /**< Auto-negotation supported */ +#define DP8_LINK_STATUS (1 << 2) /**< 1=Link active */ +#define DP8_JABBER_DETECT (1 << 1) /**< Jabber detect */ +#define DP8_EXTEND_CAPAB (1 << 0) /**< Supports extended capabilities */ + +/** \brief DP83848 PHY RBR MII dode definitions */ +#define DP8_RBR_RMII_MODE (1 << 5) /**< Use RMII mode */ + +/** \brief DP83848 PHY status definitions */ +#define DP8_REMOTEFAULT (1 << 6) /**< Remote fault */ +#define DP8_FULLDUPLEX (1 << 2) /**< 1=full duplex */ +#define DP8_SPEED10MBPS (1 << 1) /**< 1=10MBps speed */ +#define DP8_VALID_LINK (1 << 0) /**< 1=Link active */ + +/** \brief DP83848 PHY ID register definitions */ +#define DP8_PHYID1_OUI 0x2000 /**< Expected PHY ID1 */ +#define DP8_PHYID2_OUI 0x5c90 /**< Expected PHY ID2 */ + +/** \brief LAN8720 PHY Special Control/Status Register */ +#define PHY_SCSR_100MBIT 0x0008 /**< Speed: 1=100 MBit, 0=10Mbit */ +#define PHY_SCSR_DUPLEX 0x0010 /**< PHY Duplex Mask */ + +/** \brief Link status bits */ +#define LNK_STAT_VALID 0x01 +#define LNK_STAT_FULLDUPLEX 0x02 +#define LNK_STAT_SPEED10MPS 0x04 + +/** \brief PHY ID definitions */ +#define DP83848C_ID 0x20005C90 /**< PHY Identifier - DP83848C */ +#define LAN8720_ID 0x0007C0F0 /**< PHY Identifier - LAN8720 */ + +/** \brief PHY status structure used to indicate current status of PHY. + */ +typedef struct { + u32_t phy_speed_100mbs:1; /**< 10/100 MBS connection speed flag. */ + u32_t phy_full_duplex:1; /**< Half/full duplex connection speed flag. */ + u32_t phy_link_active:1; /**< Phy link active flag. */ +} PHY_STATUS_TYPE; + +/** \brief PHY update flags */ +static PHY_STATUS_TYPE physts; + +/** \brief Last PHY update flags, used for determing if something has changed */ +static PHY_STATUS_TYPE olddphysts; + +/** \brief PHY update counter for state machine */ +static s32_t phyustate; + +/** \brief Holds the PHY ID */ +static u32_t phy_id; + +/** \brief Temporary holder of link status for LAN7420 */ +static u32_t phy_lan7420_sts_tmp; + +/* Write a value via the MII link (non-blocking) */ +void lpc_mii_write_noblock(u32_t PhyReg, u32_t Value) +{ + /* Write value at PHY address and register */ + LPC_EMAC->MADR = (LPC_PHYDEF_PHYADDR << 8) | PhyReg; + LPC_EMAC->MWTD = Value; +} + +/* Write a value via the MII link (blocking) */ +err_t lpc_mii_write(u32_t PhyReg, u32_t Value) +{ + u32_t mst = 250; + err_t sts = ERR_OK; + + /* Write value at PHY address and register */ + lpc_mii_write_noblock(PhyReg, Value); + + /* Wait for unbusy status */ + while (mst > 0) { + sts = LPC_EMAC->MIND; + if ((sts & EMAC_MIND_BUSY) == 0) + mst = 0; + else { + mst--; + osDelay(1); + } + } + + if (sts != 0) + sts = ERR_TIMEOUT; + + return sts; +} + +/* Reads current MII link busy status */ +u32_t lpc_mii_is_busy(void) +{ + return (u32_t) (LPC_EMAC->MIND & EMAC_MIND_BUSY); +} + +/* Starts a read operation via the MII link (non-blocking) */ +u32_t lpc_mii_read_data(void) +{ + u32_t data = LPC_EMAC->MRDD; + LPC_EMAC->MCMD = 0; + + return data; +} + +/* Starts a read operation via the MII link (non-blocking) */ +void lpc_mii_read_noblock(u32_t PhyReg) +{ + /* Read value at PHY address and register */ + LPC_EMAC->MADR = (LPC_PHYDEF_PHYADDR << 8) | PhyReg; + LPC_EMAC->MCMD = EMAC_MCMD_READ; +} + +/* Read a value via the MII link (blocking) */ +err_t lpc_mii_read(u32_t PhyReg, u32_t *data) +{ + u32_t mst = 250; + err_t sts = ERR_OK; + + /* Read value at PHY address and register */ + lpc_mii_read_noblock(PhyReg); + + /* Wait for unbusy status */ + while (mst > 0) { + sts = LPC_EMAC->MIND & ~EMAC_MIND_MII_LINK_FAIL; + if ((sts & EMAC_MIND_BUSY) == 0) { + mst = 0; + *data = LPC_EMAC->MRDD; + } else { + mst--; + osDelay(1); + } + } + + LPC_EMAC->MCMD = 0; + + if (sts != 0) + sts = ERR_TIMEOUT; + + return sts; +} + + + +/** \brief Update PHY status from passed value + * + * This function updates the current PHY status based on the + * passed PHY status word. The PHY status indicate if the link + * is active, the connection speed, and duplex. + * + * \param[in] netif NETIF structure + * \param[in] linksts Status word from PHY + * \return 1 if the status has changed, otherwise 0 + */ +static s32_t lpc_update_phy_sts(struct netif *netif, u32_t linksts) +{ + s32_t changed = 0; + + /* Update link active status */ + if (linksts & LNK_STAT_VALID) + physts.phy_link_active = 1; + else + physts.phy_link_active = 0; + + /* Full or half duplex */ + if (linksts & LNK_STAT_FULLDUPLEX) + physts.phy_full_duplex = 1; + else + physts.phy_full_duplex = 0; + + /* Configure 100MBit/10MBit mode. */ + if (linksts & LNK_STAT_SPEED10MPS) + physts.phy_speed_100mbs = 0; + else + physts.phy_speed_100mbs = 1; + + if (physts.phy_speed_100mbs != olddphysts.phy_speed_100mbs) { + changed = 1; + if (physts.phy_speed_100mbs) { + /* 100MBit mode. */ + lpc_emac_set_speed(1); + + NETIF_INIT_SNMP(netif, snmp_ifType_ethernet_csmacd, 100000000); + } + else { + /* 10MBit mode. */ + lpc_emac_set_speed(0); + + NETIF_INIT_SNMP(netif, snmp_ifType_ethernet_csmacd, 10000000); + } + + olddphysts.phy_speed_100mbs = physts.phy_speed_100mbs; + } + + if (physts.phy_full_duplex != olddphysts.phy_full_duplex) { + changed = 1; + if (physts.phy_full_duplex) + lpc_emac_set_duplex(1); + else + lpc_emac_set_duplex(0); + + olddphysts.phy_full_duplex = physts.phy_full_duplex; + } + + if (physts.phy_link_active != olddphysts.phy_link_active) { + changed = 1; +#if NO_SYS == 1 + if (physts.phy_link_active) + netif_set_link_up(netif); + else + netif_set_link_down(netif); +#else + if (physts.phy_link_active) + tcpip_callback_with_block((tcpip_callback_fn) netif_set_link_up, + (void*) netif, 1); + else + tcpip_callback_with_block((tcpip_callback_fn) netif_set_link_down, + (void*) netif, 1); +#endif + + olddphysts.phy_link_active = physts.phy_link_active; + } + + return changed; +} + +/** \brief Initialize the DP83848 PHY. + * + * This function initializes the DP83848 PHY. It will block until + * complete. This function is called as part of the EMAC driver + * initialization. Configuration of the PHY at startup is + * controlled by setting up configuration defines in lpc_phy.h. + * + * \param[in] netif NETIF structure + * \param[in] rmii If set, configures the PHY for RMII mode + * \return ERR_OK if the setup was successful, otherwise ERR_TIMEOUT + */ +err_t lpc_phy_init(struct netif *netif, int rmii) +{ + u32_t tmp; + s32_t i; + + physts.phy_speed_100mbs = olddphysts.phy_speed_100mbs = 0; + physts.phy_full_duplex = olddphysts.phy_full_duplex = 0; + physts.phy_link_active = olddphysts.phy_link_active = 0; + phyustate = 0; + + /* Only first read and write are checked for failure */ + /* Put the DP83848C in reset mode and wait for completion */ + if (lpc_mii_write(DP8_BMCR_REG, DP8_RESET) != 0) + return ERR_TIMEOUT; + i = 400; + while (i > 0) { + osDelay(1); /* 1 ms */ + if (lpc_mii_read(DP8_BMCR_REG, &tmp) != 0) + return ERR_TIMEOUT; + + if (!(tmp & (DP8_RESET | DP8_POWER_DOWN))) + i = -1; + else + i--; + } + /* Timeout? */ + if (i == 0) + return ERR_TIMEOUT; + + // read PHY ID + lpc_mii_read(DP8_IDR1_REG, &tmp); + phy_id = (tmp << 16); + lpc_mii_read(DP8_IDR2_REG, &tmp); + phy_id |= (tmp & 0XFFF0); + + /* Setup link based on configuration options */ +#if PHY_USE_AUTONEG==1 + tmp = DP8_AUTONEG; +#else + tmp = 0; +#endif +#if PHY_USE_100MBS==1 + tmp |= DP8_SPEED_SELECT; +#endif +#if PHY_USE_FULL_DUPLEX==1 + tmp |= DP8_DUPLEX_MODE; +#endif + lpc_mii_write(DP8_BMCR_REG, tmp); + + /* Enable RMII mode for PHY */ + if (rmii) + lpc_mii_write(DP8_PHY_RBR_REG, DP8_RBR_RMII_MODE); + + /* The link is not set active at this point, but will be detected + later */ + + return ERR_OK; +} + +/* Phy status update state machine */ +s32_t lpc_phy_sts_sm(struct netif *netif) +{ + s32_t changed = 0; + u32_t data = 0; + u32_t tmp; + + switch (phyustate) { + default: + case 0: + if (phy_id == DP83848C_ID) { + lpc_mii_read_noblock(DP8_PHY_STAT_REG); + phyustate = 2; + } + else if (phy_id == LAN8720_ID) { + lpc_mii_read_noblock(DP8_PHY_SCSR_REG); + phyustate = 1; + } + break; + + case 1: + if (phy_id == LAN8720_ID) { + tmp = lpc_mii_read_data(); + // we get speed and duplex here. + phy_lan7420_sts_tmp = (tmp & PHY_SCSR_DUPLEX) ? LNK_STAT_FULLDUPLEX : 0; + phy_lan7420_sts_tmp |= (tmp & PHY_SCSR_100MBIT) ? 0 : LNK_STAT_SPEED10MPS; + + //read the status register to get link status + lpc_mii_read_noblock(DP8_BMSR_REG); + phyustate = 2; + } + break; + + case 2: + /* Wait for read status state */ + if (!lpc_mii_is_busy()) { + /* Update PHY status */ + tmp = lpc_mii_read_data(); + + if (phy_id == DP83848C_ID) { + // STS register contains all needed status bits + data = (tmp & DP8_VALID_LINK) ? LNK_STAT_VALID : 0; + data |= (tmp & DP8_FULLDUPLEX) ? LNK_STAT_FULLDUPLEX : 0; + data |= (tmp & DP8_SPEED10MBPS) ? LNK_STAT_SPEED10MPS : 0; + } + else if (phy_id == LAN8720_ID) { + // we only get the link status here. + phy_lan7420_sts_tmp |= (tmp & DP8_LINK_STATUS) ? LNK_STAT_VALID : 0; + data = phy_lan7420_sts_tmp; + } + + changed = lpc_update_phy_sts(netif, data); + phyustate = 0; + } + break; + } + + return changed; +} + +/** + * @} + */ + +/* --------------------------------- End Of File ------------------------------ */ diff --git a/features/unsupported/net/eth/lwip-eth/arch/TARGET_NXP/lwipopts_conf.h b/features/unsupported/net/eth/lwip-eth/arch/TARGET_NXP/lwipopts_conf.h new file mode 100644 index 00000000000..e78e3d258e0 --- /dev/null +++ b/features/unsupported/net/eth/lwip-eth/arch/TARGET_NXP/lwipopts_conf.h @@ -0,0 +1,36 @@ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef LWIPOPTS_CONF_H +#define LWIPOPTS_CONF_H + +#define LWIP_TRANSPORT_ETHERNET 1 + +#if defined(TARGET_LPC4088) || defined(TARGET_LPC4088_DM) +#define MEM_SIZE 15360 +#elif defined(TARGET_LPC1768) +#define MEM_SIZE 16362 +#endif + +#if defined (TOOLCHAIN_GCC_CR) + /* For LPCXpresso IDE above v8.0.0 to avoid clash with timeval struct */ + #include + #define LWIP_TIMEVAL_PRIVATE 0 +#endif + +#endif diff --git a/features/unsupported/net/eth/lwip-eth/arch/TARGET_RZ_A1H/lwipopts_conf.h b/features/unsupported/net/eth/lwip-eth/arch/TARGET_RZ_A1H/lwipopts_conf.h new file mode 100644 index 00000000000..1ad186c7a14 --- /dev/null +++ b/features/unsupported/net/eth/lwip-eth/arch/TARGET_RZ_A1H/lwipopts_conf.h @@ -0,0 +1,26 @@ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef LWIPOPTS_CONF_H +#define LWIPOPTS_CONF_H + +#define LWIP_TRANSPORT_ETHERNET 1 + +#define MEM_SIZE (1600 * 16) + +#endif diff --git a/features/unsupported/net/eth/lwip-eth/arch/TARGET_RZ_A1H/rza1_emac.c b/features/unsupported/net/eth/lwip-eth/arch/TARGET_RZ_A1H/rza1_emac.c new file mode 100644 index 00000000000..40b339d856b --- /dev/null +++ b/features/unsupported/net/eth/lwip-eth/arch/TARGET_RZ_A1H/rza1_emac.c @@ -0,0 +1,194 @@ +#include "lwip/opt.h" +#include "lwip/tcpip.h" +#include "netif/etharp.h" +#include "mbed_interface.h" +#include "ethernet_api.h" +#include "ethernetext_api.h" + +#define RECV_TASK_PRI (osPriorityNormal) +#define PHY_TASK_PRI (osPriorityNormal) +#define PHY_TASK_WAIT (200) + +/* memory */ +static sys_sem_t recv_ready_sem; /* receive ready semaphore */ + +/* function */ +static void rza1_recv_task(void *arg); +static void rza1_phy_task(void *arg); +static err_t rza1_etharp_output(struct netif *netif, struct pbuf *q, ip_addr_t *ipaddr); +static err_t rza1_low_level_output(struct netif *netif, struct pbuf *p); +static void rza1_recv_callback(void); + +static void rza1_recv_task(void *arg) { + struct netif *netif = (struct netif*)arg; + struct eth_hdr *ethhdr; + u16_t recv_size; + struct pbuf *p; + int cnt; + + while (1) { + sys_arch_sem_wait(&recv_ready_sem, 0); + for (cnt = 0; cnt < 16; cnt++) { + recv_size = ethernet_receive(); + if (recv_size != 0) { + p = pbuf_alloc(PBUF_RAW, recv_size, PBUF_RAM); + if (p != NULL) { + (void)ethernet_read((char *)p->payload, p->len); + ethhdr = p->payload; + switch (htons(ethhdr->type)) { + case ETHTYPE_IP: + case ETHTYPE_ARP: +#if PPPOE_SUPPORT + case ETHTYPE_PPPOEDISC: + case ETHTYPE_PPPOE: +#endif /* PPPOE_SUPPORT */ + /* full packet send to tcpip_thread to process */ + if (netif->input(p, netif) != ERR_OK) { + /* Free buffer */ + pbuf_free(p); + } + break; + default: + /* Return buffer */ + pbuf_free(p); + break; + } + } + } else { + break; + } + } + } +} + +static void rza1_phy_task(void *arg) { + struct netif *netif = (struct netif*)arg; + s32_t connect_sts = 0; /* 0: disconnect, 1:connect */ + s32_t link_sts; + s32_t link_mode_new = NEGO_FAIL; + s32_t link_mode_old = NEGO_FAIL; + + while (1) { + link_sts = ethernet_link(); + if (link_sts == 1) { + link_mode_new = ethernetext_chk_link_mode(); + if (link_mode_new != link_mode_old) { + if (connect_sts == 1) { + tcpip_callback_with_block((tcpip_callback_fn)netif_set_link_down, (void*) netif, 1); + } + if (link_mode_new != NEGO_FAIL) { + ethernetext_set_link_mode(link_mode_new); + tcpip_callback_with_block((tcpip_callback_fn)netif_set_link_up, (void*) netif, 1); + connect_sts = 1; + } + } + } else { + if (connect_sts != 0) { + tcpip_callback_with_block((tcpip_callback_fn)netif_set_link_down, (void*) netif, 1); + link_mode_new = NEGO_FAIL; + connect_sts = 0; + } + } + link_mode_old = link_mode_new; + osDelay(PHY_TASK_WAIT); + } +} + +static err_t rza1_etharp_output(struct netif *netif, struct pbuf *q, ip_addr_t *ipaddr) { + /* Only send packet is link is up */ + if (netif->flags & NETIF_FLAG_LINK_UP) { + return etharp_output(netif, q, ipaddr); + } + + return ERR_CONN; +} + +static err_t rza1_low_level_output(struct netif *netif, struct pbuf *p) { + struct pbuf *q; + s32_t cnt; + err_t err = ERR_MEM; + s32_t write_size = 0; + + if ((p->payload != NULL) && (p->len != 0)) { + /* If the first data can't be written, transmit descriptor is full. */ + for (cnt = 0; cnt < 100; cnt++) { + write_size = ethernet_write((char *)p->payload, p->len); + if (write_size != 0) { + break; + } + osDelay(1); + } + if (write_size != 0) { + for (q = p->next; q != NULL; q = q->next) { + (void)ethernet_write((char *)q->payload, q->len); + } + if (ethernet_send() == 1) { + err = ERR_OK; + } + } + } + + return err; +} + +static void rza1_recv_callback(void) { + sys_sem_signal(&recv_ready_sem); +} + +err_t eth_arch_enetif_init(struct netif *netif) +{ + ethernet_cfg_t ethcfg; + + /* set MAC hardware address */ +#if (MBED_MAC_ADDRESS_SUM != MBED_MAC_ADDR_INTERFACE) + netif->hwaddr[0] = MBED_MAC_ADDR_0; + netif->hwaddr[1] = MBED_MAC_ADDR_1; + netif->hwaddr[2] = MBED_MAC_ADDR_2; + netif->hwaddr[3] = MBED_MAC_ADDR_3; + netif->hwaddr[4] = MBED_MAC_ADDR_4; + netif->hwaddr[5] = MBED_MAC_ADDR_5; +#else + mbed_mac_address((char *)netif->hwaddr); +#endif + netif->hwaddr_len = ETHARP_HWADDR_LEN; + + /* maximum transfer unit */ + netif->mtu = 1500; + + /* device capabilities */ + netif->flags = NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP | NETIF_FLAG_ETHERNET | NETIF_FLAG_IGMP; + +#if LWIP_NETIF_HOSTNAME + /* Initialize interface hostname */ + netif->hostname = "lwiprza1"; +#endif /* LWIP_NETIF_HOSTNAME */ + + netif->name[0] = 'e'; + netif->name[1] = 'n'; + + netif->output = rza1_etharp_output; + netif->linkoutput = rza1_low_level_output; + + /* Initialize the hardware */ + ethcfg.int_priority = 6; + ethcfg.recv_cb = &rza1_recv_callback; + ethcfg.ether_mac = (char *)netif->hwaddr; + ethernetext_init(ðcfg); + + /* semaphore */ + sys_sem_new(&recv_ready_sem, 0); + + /* task */ + sys_thread_new("rza1_recv_task", rza1_recv_task, netif, DEFAULT_THREAD_STACKSIZE, RECV_TASK_PRI); + sys_thread_new("rza1_phy_task", rza1_phy_task, netif, DEFAULT_THREAD_STACKSIZE, PHY_TASK_PRI); + + return ERR_OK; +} + +void eth_arch_enable_interrupts(void) { + ethernetext_start_stop(1); +} + +void eth_arch_disable_interrupts(void) { + ethernetext_start_stop(0); +} diff --git a/features/unsupported/net/eth/lwip-eth/arch/TARGET_STM/lwipopts_conf.h b/features/unsupported/net/eth/lwip-eth/arch/TARGET_STM/lwipopts_conf.h new file mode 100644 index 00000000000..0851fd63feb --- /dev/null +++ b/features/unsupported/net/eth/lwip-eth/arch/TARGET_STM/lwipopts_conf.h @@ -0,0 +1,26 @@ +/* Copyright (C) 2015 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef LWIPOPTS_CONF_H +#define LWIPOPTS_CONF_H + +#define LWIP_TRANSPORT_ETHERNET 1 + +#define MEM_SIZE (1600 * 16) + +#endif diff --git a/features/unsupported/net/eth/lwip-eth/arch/TARGET_STM/stm32f4_emac.c b/features/unsupported/net/eth/lwip-eth/arch/TARGET_STM/stm32f4_emac.c new file mode 100644 index 00000000000..d7be37bbc8b --- /dev/null +++ b/features/unsupported/net/eth/lwip-eth/arch/TARGET_STM/stm32f4_emac.c @@ -0,0 +1,560 @@ + +#include "stm32f4xx_hal.h" +#include "lwip/opt.h" + +#include "lwip/timers.h" +#include "netif/etharp.h" +#include "lwip/tcpip.h" +#include +#include "cmsis_os.h" +#include "mbed_interface.h" + +/** @defgroup lwipstm32f4xx_emac_DRIVER stm32f4 EMAC driver for LWIP + * @ingroup lwip_emac + * + * @{ + */ + +#define RECV_TASK_PRI (osPriorityHigh) +#define PHY_TASK_PRI (osPriorityLow) +#define PHY_TASK_WAIT (200) + + +#if defined (__ICCARM__) /*!< IAR Compiler */ + #pragma data_alignment=4 +#endif +__ALIGN_BEGIN ETH_DMADescTypeDef DMARxDscrTab[ETH_RXBUFNB] __ALIGN_END; /* Ethernet Rx MA Descriptor */ + +#if defined (__ICCARM__) /*!< IAR Compiler */ + #pragma data_alignment=4 +#endif +__ALIGN_BEGIN ETH_DMADescTypeDef DMATxDscrTab[ETH_TXBUFNB] __ALIGN_END; /* Ethernet Tx DMA Descriptor */ + +#if defined (__ICCARM__) /*!< IAR Compiler */ + #pragma data_alignment=4 +#endif +__ALIGN_BEGIN uint8_t Rx_Buff[ETH_RXBUFNB][ETH_RX_BUF_SIZE] __ALIGN_END; /* Ethernet Receive Buffer */ + +#if defined (__ICCARM__) /*!< IAR Compiler */ + #pragma data_alignment=4 +#endif +__ALIGN_BEGIN uint8_t Tx_Buff[ETH_TXBUFNB][ETH_TX_BUF_SIZE] __ALIGN_END; /* Ethernet Transmit Buffer */ + + +ETH_HandleTypeDef heth; + +static sys_sem_t rx_ready_sem; /* receive ready semaphore */ +static sys_mutex_t tx_lock_mutex; + +/* function */ +static void stm32f4_rx_task(void *arg); +static void stm32f4_phy_task(void *arg); +static err_t stm32f4_etharp_output(struct netif *netif, struct pbuf *q, ip_addr_t *ipaddr); +static err_t stm32f4_low_level_output(struct netif *netif, struct pbuf *p); + +/** + * Override HAL Eth Init function + */ +void HAL_ETH_MspInit(ETH_HandleTypeDef* heth) +{ + GPIO_InitTypeDef GPIO_InitStruct; + if (heth->Instance == ETH) { + /* Peripheral clock enable */ + __ETH_CLK_ENABLE(); + + __GPIOA_CLK_ENABLE(); + __GPIOB_CLK_ENABLE(); + __GPIOC_CLK_ENABLE(); + + /**ETH GPIO Configuration + PC1 ------> ETH_MDC + PA1 ------> ETH_REF_CLK + PA2 ------> ETH_MDIO + PA7 ------> ETH_CRS_DV + PC4 ------> ETH_RXD0 + PC5 ------> ETH_RXD1 + PB11 ------> ETH_TX_EN + PB12 ------> ETH_TXD0 + PB13 ------> ETH_TXD1 + */ + GPIO_InitStruct.Pin = GPIO_PIN_1 | GPIO_PIN_4 | GPIO_PIN_5; + GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; + GPIO_InitStruct.Pull = GPIO_NOPULL; + GPIO_InitStruct.Speed = GPIO_SPEED_HIGH; + GPIO_InitStruct.Alternate = GPIO_AF11_ETH; + HAL_GPIO_Init(GPIOC, &GPIO_InitStruct); + + GPIO_InitStruct.Pin = GPIO_PIN_1 | GPIO_PIN_2 | GPIO_PIN_7; + GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; + GPIO_InitStruct.Pull = GPIO_NOPULL; + GPIO_InitStruct.Speed = GPIO_SPEED_HIGH; + GPIO_InitStruct.Alternate = GPIO_AF11_ETH; + HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); + + GPIO_InitStruct.Pin = GPIO_PIN_11 | GPIO_PIN_12 | GPIO_PIN_13; + GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; + GPIO_InitStruct.Pull = GPIO_NOPULL; + GPIO_InitStruct.Speed = GPIO_SPEED_HIGH; + GPIO_InitStruct.Alternate = GPIO_AF11_ETH; + HAL_GPIO_Init(GPIOB, &GPIO_InitStruct); + + /* Peripheral interrupt init*/ + /* Sets the priority grouping field */ + HAL_NVIC_SetPriorityGrouping(NVIC_PRIORITYGROUP_4); + HAL_NVIC_SetPriority(ETH_IRQn, 0, 0); + HAL_NVIC_EnableIRQ(ETH_IRQn); + } +} + +/** + * Override HAL Eth DeInit function + */ +void HAL_ETH_MspDeInit(ETH_HandleTypeDef* heth) +{ + if (heth->Instance == ETH) { + /* Peripheral clock disable */ + __ETH_CLK_DISABLE(); + + /**ETH GPIO Configuration + PC1 ------> ETH_MDC + PA1 ------> ETH_REF_CLK + PA2 ------> ETH_MDIO + PA7 ------> ETH_CRS_DV + PC4 ------> ETH_RXD0 + PC5 ------> ETH_RXD1 + PB11 ------> ETH_TX_EN + PB12 ------> ETH_TXD0 + PB13 ------> ETH_TXD1 + */ + HAL_GPIO_DeInit(GPIOC, GPIO_PIN_1 | GPIO_PIN_4 | GPIO_PIN_5); + + HAL_GPIO_DeInit(GPIOA, GPIO_PIN_1 | GPIO_PIN_2 | GPIO_PIN_7); + + HAL_GPIO_DeInit(GPIOB, GPIO_PIN_11 | GPIO_PIN_12 | GPIO_PIN_13); + + /* Peripheral interrupt Deinit*/ + HAL_NVIC_DisableIRQ(ETH_IRQn); + } +} + +/** + * Ethernet Rx Transfer completed callback + * + * @param heth: ETH handle + * @retval None + */ +void HAL_ETH_RxCpltCallback(ETH_HandleTypeDef *heth) +{ + + sys_sem_signal(&rx_ready_sem); +} + + +/** + * Ethernet IRQ Handler + * + * @param None + * @retval None + */ +void ETH_IRQHandler(void) +{ + HAL_ETH_IRQHandler(&heth); +} + + + +/** + * In this function, the hardware should be initialized. + * Called from eth_arch_enetif_init(). + * + * @param netif the already initialized lwip network interface structure + * for this ethernetif + */ +static void stm32f4_low_level_init(struct netif *netif) +{ + uint32_t regvalue = 0; + HAL_StatusTypeDef hal_eth_init_status; + + /* Init ETH */ + uint8_t MACAddr[6]; + heth.Instance = ETH; + heth.Init.AutoNegotiation = ETH_AUTONEGOTIATION_ENABLE; + heth.Init.Speed = ETH_SPEED_10M; + heth.Init.DuplexMode = ETH_MODE_FULLDUPLEX; + heth.Init.PhyAddress = 1; +#if (MBED_MAC_ADDRESS_SUM != MBED_MAC_ADDR_INTERFACE) + MACAddr[0] = MBED_MAC_ADDR_0; + MACAddr[1] = MBED_MAC_ADDR_1; + MACAddr[2] = MBED_MAC_ADDR_2; + MACAddr[3] = MBED_MAC_ADDR_3; + MACAddr[4] = MBED_MAC_ADDR_4; + MACAddr[5] = MBED_MAC_ADDR_5; +#else + mbed_mac_address((char *)MACAddr); +#endif + heth.Init.MACAddr = &MACAddr[0]; + heth.Init.RxMode = ETH_RXINTERRUPT_MODE; + heth.Init.ChecksumMode = ETH_CHECKSUM_BY_HARDWARE; + heth.Init.MediaInterface = ETH_MEDIA_INTERFACE_RMII; + hal_eth_init_status = HAL_ETH_Init(&heth); + + if (hal_eth_init_status == HAL_OK) { + /* Set netif link flag */ + netif->flags |= NETIF_FLAG_LINK_UP; + } + + /* Initialize Tx Descriptors list: Chain Mode */ + HAL_ETH_DMATxDescListInit(&heth, DMATxDscrTab, &Tx_Buff[0][0], ETH_TXBUFNB); + + /* Initialize Rx Descriptors list: Chain Mode */ + HAL_ETH_DMARxDescListInit(&heth, DMARxDscrTab, &Rx_Buff[0][0], ETH_RXBUFNB); + + #if LWIP_ARP || LWIP_ETHERNET + /* set MAC hardware address length */ + netif->hwaddr_len = ETHARP_HWADDR_LEN; + + /* set MAC hardware address */ + netif->hwaddr[0] = heth.Init.MACAddr[0]; + netif->hwaddr[1] = heth.Init.MACAddr[1]; + netif->hwaddr[2] = heth.Init.MACAddr[2]; + netif->hwaddr[3] = heth.Init.MACAddr[3]; + netif->hwaddr[4] = heth.Init.MACAddr[4]; + netif->hwaddr[5] = heth.Init.MACAddr[5]; + + /* maximum transfer unit */ + netif->mtu = 1500; + + /* device capabilities */ + /* don't set NETIF_FLAG_ETHARP if this device is not an ethernet one */ + netif->flags |= NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP; + + /* Enable MAC and DMA transmission and reception */ + HAL_ETH_Start(&heth); + + /**** Configure PHY to generate an interrupt when Eth Link state changes ****/ + /* Read Register Configuration */ + HAL_ETH_ReadPHYRegister(&heth, PHY_MICR, ®value); + + regvalue |= (PHY_MICR_INT_EN | PHY_MICR_INT_OE); + + /* Enable Interrupts */ + HAL_ETH_WritePHYRegister(&heth, PHY_MICR, regvalue); + + /* Read Register Configuration */ + HAL_ETH_ReadPHYRegister(&heth, PHY_MISR, ®value); + + regvalue |= PHY_MISR_LINK_INT_EN; + + /* Enable Interrupt on change of link status */ + HAL_ETH_WritePHYRegister(&heth, PHY_MISR, regvalue); +#endif +} + +/** + * This function should do the actual transmission of the packet. The packet is + * contained in the pbuf that is passed to the function. This pbuf + * might be chained. + * + * @param netif the lwip network interface structure for this ethernetif + * @param p the MAC packet to send (e.g. IP packet including MAC addresses and type) + * @return ERR_OK if the packet could be sent + * an err_t value if the packet couldn't be sent + * + * @note Returning ERR_MEM here if a DMA queue of your MAC is full can lead to + * strange results. You might consider waiting for space in the DMA queue + * to become availale since the stack doesn't retry to send a packet + * dropped because of memory failure (except for the TCP timers). + */ + +static err_t stm32f4_low_level_output(struct netif *netif, struct pbuf *p) +{ + err_t errval; + struct pbuf *q; + uint8_t *buffer = (uint8_t*)(heth.TxDesc->Buffer1Addr); + __IO ETH_DMADescTypeDef *DmaTxDesc; + uint32_t framelength = 0; + uint32_t bufferoffset = 0; + uint32_t byteslefttocopy = 0; + uint32_t payloadoffset = 0; + DmaTxDesc = heth.TxDesc; + bufferoffset = 0; + + + sys_mutex_lock(&tx_lock_mutex); + + /* copy frame from pbufs to driver buffers */ + for (q = p; q != NULL; q = q->next) { + /* Is this buffer available? If not, goto error */ + if ((DmaTxDesc->Status & ETH_DMATXDESC_OWN) != (uint32_t)RESET) { + errval = ERR_USE; + goto error; + } + + /* Get bytes in current lwIP buffer */ + byteslefttocopy = q->len; + payloadoffset = 0; + + /* Check if the length of data to copy is bigger than Tx buffer size*/ + while ((byteslefttocopy + bufferoffset) > ETH_TX_BUF_SIZE) { + /* Copy data to Tx buffer*/ + memcpy((uint8_t*)((uint8_t*)buffer + bufferoffset), (uint8_t*)((uint8_t*)q->payload + payloadoffset), (ETH_TX_BUF_SIZE - bufferoffset)); + + /* Point to next descriptor */ + DmaTxDesc = (ETH_DMADescTypeDef*)(DmaTxDesc->Buffer2NextDescAddr); + + /* Check if the buffer is available */ + if ((DmaTxDesc->Status & ETH_DMATXDESC_OWN) != (uint32_t)RESET) { + errval = ERR_USE; + goto error; + } + + buffer = (uint8_t*)(DmaTxDesc->Buffer1Addr); + + byteslefttocopy = byteslefttocopy - (ETH_TX_BUF_SIZE - bufferoffset); + payloadoffset = payloadoffset + (ETH_TX_BUF_SIZE - bufferoffset); + framelength = framelength + (ETH_TX_BUF_SIZE - bufferoffset); + bufferoffset = 0; + } + + /* Copy the remaining bytes */ + memcpy((uint8_t*)((uint8_t*)buffer + bufferoffset), (uint8_t*)((uint8_t*)q->payload + payloadoffset), byteslefttocopy); + bufferoffset = bufferoffset + byteslefttocopy; + framelength = framelength + byteslefttocopy; + } + + /* Prepare transmit descriptors to give to DMA */ + HAL_ETH_TransmitFrame(&heth, framelength); + + errval = ERR_OK; + +error: + + /* When Transmit Underflow flag is set, clear it and issue a Transmit Poll Demand to resume transmission */ + if ((heth.Instance->DMASR & ETH_DMASR_TUS) != (uint32_t)RESET) { + /* Clear TUS ETHERNET DMA flag */ + heth.Instance->DMASR = ETH_DMASR_TUS; + + /* Resume DMA transmission*/ + heth.Instance->DMATPDR = 0; + } + + sys_mutex_unlock(&tx_lock_mutex); + + return errval; +} + + +/** + * Should allocate a pbuf and transfer the bytes of the incoming + * packet from the interface into the pbuf. + * + * @param netif the lwip network interface structure for this ethernetif + * @return a pbuf filled with the received packet (including MAC header) + * NULL on memory error + */ +static struct pbuf * stm32f4_low_level_input(struct netif *netif) +{ + struct pbuf *p = NULL; + struct pbuf *q; + uint16_t len = 0; + uint8_t *buffer; + __IO ETH_DMADescTypeDef *dmarxdesc; + uint32_t bufferoffset = 0; + uint32_t payloadoffset = 0; + uint32_t byteslefttocopy = 0; + uint32_t i = 0; + + + /* get received frame */ + if (HAL_ETH_GetReceivedFrame(&heth) != HAL_OK) + return NULL; + + /* Obtain the size of the packet and put it into the "len" variable. */ + len = heth.RxFrameInfos.length; + buffer = (uint8_t*)heth.RxFrameInfos.buffer; + + if (len > 0) { + /* We allocate a pbuf chain of pbufs from the Lwip buffer pool */ + p = pbuf_alloc(PBUF_RAW, len, PBUF_POOL); + } + + if (p != NULL) { + dmarxdesc = heth.RxFrameInfos.FSRxDesc; + bufferoffset = 0; + for (q = p; q != NULL; q = q->next) { + byteslefttocopy = q->len; + payloadoffset = 0; + + /* Check if the length of bytes to copy in current pbuf is bigger than Rx buffer size*/ + while ((byteslefttocopy + bufferoffset) > ETH_RX_BUF_SIZE) { + /* Copy data to pbuf */ + memcpy((uint8_t*)((uint8_t*)q->payload + payloadoffset), (uint8_t*)((uint8_t*)buffer + bufferoffset), (ETH_RX_BUF_SIZE - bufferoffset)); + + /* Point to next descriptor */ + dmarxdesc = (ETH_DMADescTypeDef*)(dmarxdesc->Buffer2NextDescAddr); + buffer = (uint8_t*)(dmarxdesc->Buffer1Addr); + + byteslefttocopy = byteslefttocopy - (ETH_RX_BUF_SIZE - bufferoffset); + payloadoffset = payloadoffset + (ETH_RX_BUF_SIZE - bufferoffset); + bufferoffset = 0; + } + /* Copy remaining data in pbuf */ + memcpy((uint8_t*)((uint8_t*)q->payload + payloadoffset), (uint8_t*)((uint8_t*)buffer + bufferoffset), byteslefttocopy); + bufferoffset = bufferoffset + byteslefttocopy; + } + + /* Release descriptors to DMA */ + /* Point to first descriptor */ + dmarxdesc = heth.RxFrameInfos.FSRxDesc; + /* Set Own bit in Rx descriptors: gives the buffers back to DMA */ + for (i = 0; i < heth.RxFrameInfos.SegCount; i++) { + dmarxdesc->Status |= ETH_DMARXDESC_OWN; + dmarxdesc = (ETH_DMADescTypeDef*)(dmarxdesc->Buffer2NextDescAddr); + } + + /* Clear Segment_Count */ + heth.RxFrameInfos.SegCount = 0; + } + + /* When Rx Buffer unavailable flag is set: clear it and resume reception */ + if ((heth.Instance->DMASR & ETH_DMASR_RBUS) != (uint32_t)RESET) { + /* Clear RBUS ETHERNET DMA flag */ + heth.Instance->DMASR = ETH_DMASR_RBUS; + /* Resume DMA reception */ + heth.Instance->DMARPDR = 0; + } + return p; +} + +/** + * This task receives input data + * + * \param[in] netif the lwip network interface structure + */ +static void stm32f4_rx_task(void *arg) +{ + struct netif *netif = (struct netif*)arg; + struct pbuf *p; + + while (1) { + sys_arch_sem_wait(&rx_ready_sem, 0); + p = stm32f4_low_level_input(netif); + if (p != NULL) { + if (netif->input(p, netif) != ERR_OK) { + pbuf_free(p); + p = NULL; + } + } + } +} + +/** + * This task checks phy link status and updates net status + * + * \param[in] netif the lwip network interface structure + */ +static void stm32f4_phy_task(void *arg) +{ + struct netif *netif = (struct netif*)arg; + uint32_t phy_status = 0; + + while (1) { + uint32_t status; + if (HAL_ETH_ReadPHYRegister(&heth, PHY_SR, &status) == HAL_OK) { + if ((status & PHY_LINK_STATUS) && !(phy_status & PHY_LINK_STATUS)) { + tcpip_callback_with_block((tcpip_callback_fn)netif_set_link_up, (void*) netif, 1); + } else if (!(status & PHY_LINK_STATUS) && (phy_status & PHY_LINK_STATUS)) { + tcpip_callback_with_block((tcpip_callback_fn)netif_set_link_down, (void*) netif, 1); + } + + phy_status = status; + } + + osDelay(PHY_TASK_WAIT); + } +} + +/** + * This function is the ethernet packet send function. It calls + * etharp_output after checking link status. + * + * \param[in] netif the lwip network interface structure for this lpc_enetif + * \param[in] q Pointer to pbug to send + * \param[in] ipaddr IP address + * \return ERR_OK or error code + */ +static err_t stm32f4_etharp_output(struct netif *netif, struct pbuf *q, ip_addr_t *ipaddr) +{ + /* Only send packet is link is up */ + if (netif->flags & NETIF_FLAG_LINK_UP) { + return etharp_output(netif, q, ipaddr); + } + + return ERR_CONN; +} + +/** + * Should be called at the beginning of the program to set up the + * network interface. + * + * This function should be passed as a parameter to netif_add(). + * + * @param[in] netif the lwip network interface structure for this lpc_enetif + * @return ERR_OK if the loopif is initialized + * ERR_MEM if private data couldn't be allocated + * any other err_t on error + */ +err_t eth_arch_enetif_init(struct netif *netif) +{ + /* set MAC hardware address */ + netif->hwaddr_len = ETHARP_HWADDR_LEN; + + /* maximum transfer unit */ + netif->mtu = 1500; + + /* device capabilities */ + netif->flags = NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP | NETIF_FLAG_ETHERNET | NETIF_FLAG_IGMP; + +#if LWIP_NETIF_HOSTNAME + /* Initialize interface hostname */ + netif->hostname = "lwipstm32f4"; +#endif /* LWIP_NETIF_HOSTNAME */ + + netif->name[0] = 'e'; + netif->name[1] = 'n'; + + netif->output = stm32f4_etharp_output; + netif->linkoutput = stm32f4_low_level_output; + + /* semaphore */ + sys_sem_new(&rx_ready_sem, 0); + + sys_mutex_new(&tx_lock_mutex); + + /* task */ + sys_thread_new("stm32f4_recv_task", stm32f4_rx_task, netif, DEFAULT_THREAD_STACKSIZE, RECV_TASK_PRI); + sys_thread_new("stm32f4_phy_task", stm32f4_phy_task, netif, DEFAULT_THREAD_STACKSIZE, PHY_TASK_PRI); + + /* initialize the hardware */ + stm32f4_low_level_init(netif); + + return ERR_OK; +} + +void eth_arch_enable_interrupts(void) +{ + HAL_NVIC_SetPriorityGrouping(NVIC_PRIORITYGROUP_4); + HAL_NVIC_SetPriority(ETH_IRQn, 0, 0); + HAL_NVIC_EnableIRQ(ETH_IRQn); +} + +void eth_arch_disable_interrupts(void) +{ + NVIC_DisableIRQ(ETH_IRQn); +} + +/** + * @} + */ + +/* --------------------------------- End Of File ------------------------------ */ diff --git a/features/unsupported/net/eth/lwip-eth/arch/TARGET_VK_RZ_A1H/lwipopts_conf.h b/features/unsupported/net/eth/lwip-eth/arch/TARGET_VK_RZ_A1H/lwipopts_conf.h new file mode 100644 index 00000000000..1ad186c7a14 --- /dev/null +++ b/features/unsupported/net/eth/lwip-eth/arch/TARGET_VK_RZ_A1H/lwipopts_conf.h @@ -0,0 +1,26 @@ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef LWIPOPTS_CONF_H +#define LWIPOPTS_CONF_H + +#define LWIP_TRANSPORT_ETHERNET 1 + +#define MEM_SIZE (1600 * 16) + +#endif diff --git a/features/unsupported/net/eth/lwip-eth/arch/TARGET_VK_RZ_A1H/rza1_emac.c b/features/unsupported/net/eth/lwip-eth/arch/TARGET_VK_RZ_A1H/rza1_emac.c new file mode 100644 index 00000000000..40b339d856b --- /dev/null +++ b/features/unsupported/net/eth/lwip-eth/arch/TARGET_VK_RZ_A1H/rza1_emac.c @@ -0,0 +1,194 @@ +#include "lwip/opt.h" +#include "lwip/tcpip.h" +#include "netif/etharp.h" +#include "mbed_interface.h" +#include "ethernet_api.h" +#include "ethernetext_api.h" + +#define RECV_TASK_PRI (osPriorityNormal) +#define PHY_TASK_PRI (osPriorityNormal) +#define PHY_TASK_WAIT (200) + +/* memory */ +static sys_sem_t recv_ready_sem; /* receive ready semaphore */ + +/* function */ +static void rza1_recv_task(void *arg); +static void rza1_phy_task(void *arg); +static err_t rza1_etharp_output(struct netif *netif, struct pbuf *q, ip_addr_t *ipaddr); +static err_t rza1_low_level_output(struct netif *netif, struct pbuf *p); +static void rza1_recv_callback(void); + +static void rza1_recv_task(void *arg) { + struct netif *netif = (struct netif*)arg; + struct eth_hdr *ethhdr; + u16_t recv_size; + struct pbuf *p; + int cnt; + + while (1) { + sys_arch_sem_wait(&recv_ready_sem, 0); + for (cnt = 0; cnt < 16; cnt++) { + recv_size = ethernet_receive(); + if (recv_size != 0) { + p = pbuf_alloc(PBUF_RAW, recv_size, PBUF_RAM); + if (p != NULL) { + (void)ethernet_read((char *)p->payload, p->len); + ethhdr = p->payload; + switch (htons(ethhdr->type)) { + case ETHTYPE_IP: + case ETHTYPE_ARP: +#if PPPOE_SUPPORT + case ETHTYPE_PPPOEDISC: + case ETHTYPE_PPPOE: +#endif /* PPPOE_SUPPORT */ + /* full packet send to tcpip_thread to process */ + if (netif->input(p, netif) != ERR_OK) { + /* Free buffer */ + pbuf_free(p); + } + break; + default: + /* Return buffer */ + pbuf_free(p); + break; + } + } + } else { + break; + } + } + } +} + +static void rza1_phy_task(void *arg) { + struct netif *netif = (struct netif*)arg; + s32_t connect_sts = 0; /* 0: disconnect, 1:connect */ + s32_t link_sts; + s32_t link_mode_new = NEGO_FAIL; + s32_t link_mode_old = NEGO_FAIL; + + while (1) { + link_sts = ethernet_link(); + if (link_sts == 1) { + link_mode_new = ethernetext_chk_link_mode(); + if (link_mode_new != link_mode_old) { + if (connect_sts == 1) { + tcpip_callback_with_block((tcpip_callback_fn)netif_set_link_down, (void*) netif, 1); + } + if (link_mode_new != NEGO_FAIL) { + ethernetext_set_link_mode(link_mode_new); + tcpip_callback_with_block((tcpip_callback_fn)netif_set_link_up, (void*) netif, 1); + connect_sts = 1; + } + } + } else { + if (connect_sts != 0) { + tcpip_callback_with_block((tcpip_callback_fn)netif_set_link_down, (void*) netif, 1); + link_mode_new = NEGO_FAIL; + connect_sts = 0; + } + } + link_mode_old = link_mode_new; + osDelay(PHY_TASK_WAIT); + } +} + +static err_t rza1_etharp_output(struct netif *netif, struct pbuf *q, ip_addr_t *ipaddr) { + /* Only send packet is link is up */ + if (netif->flags & NETIF_FLAG_LINK_UP) { + return etharp_output(netif, q, ipaddr); + } + + return ERR_CONN; +} + +static err_t rza1_low_level_output(struct netif *netif, struct pbuf *p) { + struct pbuf *q; + s32_t cnt; + err_t err = ERR_MEM; + s32_t write_size = 0; + + if ((p->payload != NULL) && (p->len != 0)) { + /* If the first data can't be written, transmit descriptor is full. */ + for (cnt = 0; cnt < 100; cnt++) { + write_size = ethernet_write((char *)p->payload, p->len); + if (write_size != 0) { + break; + } + osDelay(1); + } + if (write_size != 0) { + for (q = p->next; q != NULL; q = q->next) { + (void)ethernet_write((char *)q->payload, q->len); + } + if (ethernet_send() == 1) { + err = ERR_OK; + } + } + } + + return err; +} + +static void rza1_recv_callback(void) { + sys_sem_signal(&recv_ready_sem); +} + +err_t eth_arch_enetif_init(struct netif *netif) +{ + ethernet_cfg_t ethcfg; + + /* set MAC hardware address */ +#if (MBED_MAC_ADDRESS_SUM != MBED_MAC_ADDR_INTERFACE) + netif->hwaddr[0] = MBED_MAC_ADDR_0; + netif->hwaddr[1] = MBED_MAC_ADDR_1; + netif->hwaddr[2] = MBED_MAC_ADDR_2; + netif->hwaddr[3] = MBED_MAC_ADDR_3; + netif->hwaddr[4] = MBED_MAC_ADDR_4; + netif->hwaddr[5] = MBED_MAC_ADDR_5; +#else + mbed_mac_address((char *)netif->hwaddr); +#endif + netif->hwaddr_len = ETHARP_HWADDR_LEN; + + /* maximum transfer unit */ + netif->mtu = 1500; + + /* device capabilities */ + netif->flags = NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP | NETIF_FLAG_ETHERNET | NETIF_FLAG_IGMP; + +#if LWIP_NETIF_HOSTNAME + /* Initialize interface hostname */ + netif->hostname = "lwiprza1"; +#endif /* LWIP_NETIF_HOSTNAME */ + + netif->name[0] = 'e'; + netif->name[1] = 'n'; + + netif->output = rza1_etharp_output; + netif->linkoutput = rza1_low_level_output; + + /* Initialize the hardware */ + ethcfg.int_priority = 6; + ethcfg.recv_cb = &rza1_recv_callback; + ethcfg.ether_mac = (char *)netif->hwaddr; + ethernetext_init(ðcfg); + + /* semaphore */ + sys_sem_new(&recv_ready_sem, 0); + + /* task */ + sys_thread_new("rza1_recv_task", rza1_recv_task, netif, DEFAULT_THREAD_STACKSIZE, RECV_TASK_PRI); + sys_thread_new("rza1_phy_task", rza1_phy_task, netif, DEFAULT_THREAD_STACKSIZE, PHY_TASK_PRI); + + return ERR_OK; +} + +void eth_arch_enable_interrupts(void) { + ethernetext_start_stop(1); +} + +void eth_arch_disable_interrupts(void) { + ethernetext_start_stop(0); +} diff --git a/features/unsupported/net/https/HTTPHeader.cpp b/features/unsupported/net/https/HTTPHeader.cpp new file mode 100644 index 00000000000..4fe525357d1 --- /dev/null +++ b/features/unsupported/net/https/HTTPHeader.cpp @@ -0,0 +1,24 @@ +#include "HTTPHeader.h" +#include +using std::map; +using std::string; + +HTTPHeader::HTTPHeader(): +_status(HTTP_ERROR), +_fields() +{ +} + +std::string HTTPHeader::getField(const std::string& name) +{ + map::iterator itor = _fields.find(name); + if(itor == _fields.end()) + return string(); + return itor->second; +} + +int HTTPHeader::getBodyLength() +{ + return atoi(getField("Content-Length").c_str()); +} + diff --git a/features/unsupported/net/https/HTTPHeader.h b/features/unsupported/net/https/HTTPHeader.h new file mode 100644 index 00000000000..63cfea1b74d --- /dev/null +++ b/features/unsupported/net/https/HTTPHeader.h @@ -0,0 +1,29 @@ +#ifndef HTTPHEADER_H +#define HTTPHEADER_H + +#include +#include + +enum HTTPStatus { HTTP_OK, HTTP_ERROR }; + +class HTTPSClient; + +class HTTPHeader +{ + friend class HTTPSClient; + + public : + + HTTPHeader(); + + std::string getField(const std::string& name); + int getBodyLength(); + + private : + + HTTPStatus _status; + std::map _fields; +}; + + +#endif diff --git a/features/unsupported/net/https/HTTPSClient.cpp b/features/unsupported/net/https/HTTPSClient.cpp new file mode 100644 index 00000000000..76eae5b4a97 --- /dev/null +++ b/features/unsupported/net/https/HTTPSClient.cpp @@ -0,0 +1,163 @@ +#include "HTTPSClient.h" +#include "HTTPHeader.h" +#include +#include +#include "mbed.h" +#include +#include + +using std::memset; +using std::memcpy; +using std::string; + +const static int HTTPS_PORT = 443; +char buf[256]; + +HTTPSClient::HTTPSClient() : + _is_connected(false), + _ssl_ctx(), + _ssl(), + _host() { +} + +HTTPSClient::~HTTPSClient() { + close(); +} + +int HTTPSClient::connect(const char* host) { + if (init_socket(SOCK_STREAM) < 0) + return -1; + + if (set_address(host, HTTPS_PORT) != 0) + return -1; + + if (lwip_connect(_sock_fd, (const struct sockaddr *) &_remoteHost, sizeof(_remoteHost)) < 0) { + close(); + return -1; + } + + if(ssl_ctx_new(&_ssl_ctx, SSL_SERVER_VERIFY_LATER, SSL_DEFAULT_CLNT_SESS) != &_ssl_ctx) + return -1; + + _ssl.ssl_ctx = &_ssl_ctx; + + if(ssl_client_new(&_ssl, _sock_fd, NULL, 0) == NULL) + { + close(); + return -1; + } + if(_ssl.hs_status != SSL_OK) + { + close(); + return -1; + } + + _is_connected = true; + _host = host; + return 0; +} + +bool HTTPSClient::is_connected(void) { + return _is_connected; +} + +int HTTPSClient::send(char* data, int length) { + if ((_sock_fd < 0) || !_is_connected) + return -1; + + return ssl_write(&_ssl, (uint8_t*)data, length); +} + + + +HTTPHeader HTTPSClient::get(char *request) +{ + if((_sock_fd < 0) || !_is_connected) + return HTTPHeader(); + + sprintf(buf, "GET %s HTTP/1.1\r\nHost: %s\r\n\r\n", request, _host.c_str()); + printf("buf=%s\n", buf); + if(send(buf, strlen(buf)) != strlen(buf)) + return HTTPHeader(); + printf("Finished sending request\n"); + return read_header(); +} + + +HTTPHeader HTTPSClient::read_header() +{ + _ssl.bm_read_index = 0; + _ssl.bm_index = 0; + HTTPHeader hdr; + if(read_line()) + return hdr; + + int status; + + if(sscanf(buf, "HTTP/%*d.%*d %d %*s", &status) == -1) + return hdr; + + if(status == 200) + hdr._status = HTTP_OK; + if(read_line()) + return hdr; + do + { + string tmp(buf); + std::size_t sep = tmp.find(':'); + string name = tmp.substr(0, sep); + string value = tmp.substr(sep+2, tmp.size()); + hdr._fields[name] = value; + if(read_line()) + return hdr; + }while(strlen(buf)); + + return hdr; +} + +uint8_t HTTPSClient::read_line() +{ + int index = 0; + do + { + if(ssl_read(&_ssl, (uint8_t*)(&buf[index]), 1) != 1) + { + return 1; + } + index++; + }while(buf[index-1] != '\r' && index < 256); + ssl_read(&_ssl, (uint8_t*)(&buf[index-1]), 1); // skip '\n' + buf[index-1] = '\0'; + + return 0; +} + +// -1:error +// otherwise return nb of characters read. Cannot be > than len +int HTTPSClient::read(char *data, int len) +{ + return ssl_read(&_ssl, (uint8_t*)data, len); +} +/* + 0 : must close connection + -1 : error + else : get data + +int HTTPSClient::receive(char* data, int length) { + if ((_sock_fd < 0) || !_is_connected) + return -1; + + if(read_record(&_ssl) < 0) + return -1; + return process_data(&_ssl, (uint8_t*)data, length); +} +*/ +void HTTPSClient::close() +{ + if(!_is_connected) + return; + ssl_ctx_free(_ssl.ssl_ctx); + Socket::close(); + _is_connected = false; + _host.clear(); +} diff --git a/features/unsupported/net/https/HTTPSClient.h b/features/unsupported/net/https/HTTPSClient.h new file mode 100644 index 00000000000..92c6908479b --- /dev/null +++ b/features/unsupported/net/https/HTTPSClient.h @@ -0,0 +1,56 @@ +#ifndef HTTPSCLIENT_H +#define HTTPSCLIENT_H + +#include "Socket/Socket.h" +#include "Socket/Endpoint.h" +#include "axTLS/ssl/ssl.h" +#include "HTTPHeader.h" + +/** +TCP socket connection +*/ +class HTTPSClient : public Socket, public Endpoint { + +public: + /** TCP socket connection + */ + HTTPSClient(); + + + virtual ~HTTPSClient(); + + /** Connects this TCP socket to the server + \param host The host to connect to. It can either be an IP Address or a hostname that will be resolved with DNS. + \param port The host's port to connect to. + \return 0 on success, -1 on failure. + */ + int connect(const char* host); + + /** Check if the socket is connected + \return true if connected, false otherwise. + */ + bool is_connected(void); + + // Returns the size of the body + HTTPHeader get(char *path); + + int read(char *data, int len); + + + void close(); + +private: + + + int send(char* data, int length); + + uint8_t read_line(); + HTTPHeader read_header(); + + bool _is_connected; + SSL_CTX _ssl_ctx; + SSL _ssl; + std::string _host; +}; + +#endif diff --git a/features/unsupported/net/https/axTLS/crypto/aes.c b/features/unsupported/net/https/axTLS/crypto/aes.c new file mode 100644 index 00000000000..2ab1e86d4aa --- /dev/null +++ b/features/unsupported/net/https/axTLS/crypto/aes.c @@ -0,0 +1,460 @@ +/* + * Copyright (c) 2007, Cameron Rich + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * * Neither the name of the axTLS project nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * AES implementation - this is a small code version. There are much faster + * versions around but they are much larger in size (i.e. they use large + * submix tables). + */ + +#include +//#include "os_port.h" +#include "crypto.h" +#include + +/* all commented out in skeleton mode */ +#ifndef CONFIG_SSL_SKELETON_MODE + +#define rot1(x) (((x) << 24) | ((x) >> 8)) +#define rot2(x) (((x) << 16) | ((x) >> 16)) +#define rot3(x) (((x) << 8) | ((x) >> 24)) + +/* + * This cute trick does 4 'mul by two' at once. Stolen from + * Dr B. R. Gladman but I'm sure the u-(u>>7) is + * a standard graphics trick + * The key to this is that we need to xor with 0x1b if the top bit is set. + * a 1xxx xxxx 0xxx 0xxx First we mask the 7bit, + * b 1000 0000 0000 0000 then we shift right by 7 putting the 7bit in 0bit, + * c 0000 0001 0000 0000 we then subtract (c) from (b) + * d 0111 1111 0000 0000 and now we and with our mask + * e 0001 1011 0000 0000 + */ +#define mt 0x80808080 +#define ml 0x7f7f7f7f +#define mh 0xfefefefe +#define mm 0x1b1b1b1b +#define mul2(x,t) ((t)=((x)&mt), \ + ((((x)+(x))&mh)^(((t)-((t)>>7))&mm))) + +#define inv_mix_col(x,f2,f4,f8,f9) (\ + (f2)=mul2(x,f2), \ + (f4)=mul2(f2,f4), \ + (f8)=mul2(f4,f8), \ + (f9)=(x)^(f8), \ + (f8)=((f2)^(f4)^(f8)), \ + (f2)^=(f9), \ + (f4)^=(f9), \ + (f8)^=rot3(f2), \ + (f8)^=rot2(f4), \ + (f8)^rot1(f9)) + +/* + * AES S-box + */ +static const uint8_t aes_sbox[256] = +{ + 0x63,0x7C,0x77,0x7B,0xF2,0x6B,0x6F,0xC5, + 0x30,0x01,0x67,0x2B,0xFE,0xD7,0xAB,0x76, + 0xCA,0x82,0xC9,0x7D,0xFA,0x59,0x47,0xF0, + 0xAD,0xD4,0xA2,0xAF,0x9C,0xA4,0x72,0xC0, + 0xB7,0xFD,0x93,0x26,0x36,0x3F,0xF7,0xCC, + 0x34,0xA5,0xE5,0xF1,0x71,0xD8,0x31,0x15, + 0x04,0xC7,0x23,0xC3,0x18,0x96,0x05,0x9A, + 0x07,0x12,0x80,0xE2,0xEB,0x27,0xB2,0x75, + 0x09,0x83,0x2C,0x1A,0x1B,0x6E,0x5A,0xA0, + 0x52,0x3B,0xD6,0xB3,0x29,0xE3,0x2F,0x84, + 0x53,0xD1,0x00,0xED,0x20,0xFC,0xB1,0x5B, + 0x6A,0xCB,0xBE,0x39,0x4A,0x4C,0x58,0xCF, + 0xD0,0xEF,0xAA,0xFB,0x43,0x4D,0x33,0x85, + 0x45,0xF9,0x02,0x7F,0x50,0x3C,0x9F,0xA8, + 0x51,0xA3,0x40,0x8F,0x92,0x9D,0x38,0xF5, + 0xBC,0xB6,0xDA,0x21,0x10,0xFF,0xF3,0xD2, + 0xCD,0x0C,0x13,0xEC,0x5F,0x97,0x44,0x17, + 0xC4,0xA7,0x7E,0x3D,0x64,0x5D,0x19,0x73, + 0x60,0x81,0x4F,0xDC,0x22,0x2A,0x90,0x88, + 0x46,0xEE,0xB8,0x14,0xDE,0x5E,0x0B,0xDB, + 0xE0,0x32,0x3A,0x0A,0x49,0x06,0x24,0x5C, + 0xC2,0xD3,0xAC,0x62,0x91,0x95,0xE4,0x79, + 0xE7,0xC8,0x37,0x6D,0x8D,0xD5,0x4E,0xA9, + 0x6C,0x56,0xF4,0xEA,0x65,0x7A,0xAE,0x08, + 0xBA,0x78,0x25,0x2E,0x1C,0xA6,0xB4,0xC6, + 0xE8,0xDD,0x74,0x1F,0x4B,0xBD,0x8B,0x8A, + 0x70,0x3E,0xB5,0x66,0x48,0x03,0xF6,0x0E, + 0x61,0x35,0x57,0xB9,0x86,0xC1,0x1D,0x9E, + 0xE1,0xF8,0x98,0x11,0x69,0xD9,0x8E,0x94, + 0x9B,0x1E,0x87,0xE9,0xCE,0x55,0x28,0xDF, + 0x8C,0xA1,0x89,0x0D,0xBF,0xE6,0x42,0x68, + 0x41,0x99,0x2D,0x0F,0xB0,0x54,0xBB,0x16, +}; + +/* + * AES is-box + */ +static const uint8_t aes_isbox[256] = +{ + 0x52,0x09,0x6a,0xd5,0x30,0x36,0xa5,0x38, + 0xbf,0x40,0xa3,0x9e,0x81,0xf3,0xd7,0xfb, + 0x7c,0xe3,0x39,0x82,0x9b,0x2f,0xff,0x87, + 0x34,0x8e,0x43,0x44,0xc4,0xde,0xe9,0xcb, + 0x54,0x7b,0x94,0x32,0xa6,0xc2,0x23,0x3d, + 0xee,0x4c,0x95,0x0b,0x42,0xfa,0xc3,0x4e, + 0x08,0x2e,0xa1,0x66,0x28,0xd9,0x24,0xb2, + 0x76,0x5b,0xa2,0x49,0x6d,0x8b,0xd1,0x25, + 0x72,0xf8,0xf6,0x64,0x86,0x68,0x98,0x16, + 0xd4,0xa4,0x5c,0xcc,0x5d,0x65,0xb6,0x92, + 0x6c,0x70,0x48,0x50,0xfd,0xed,0xb9,0xda, + 0x5e,0x15,0x46,0x57,0xa7,0x8d,0x9d,0x84, + 0x90,0xd8,0xab,0x00,0x8c,0xbc,0xd3,0x0a, + 0xf7,0xe4,0x58,0x05,0xb8,0xb3,0x45,0x06, + 0xd0,0x2c,0x1e,0x8f,0xca,0x3f,0x0f,0x02, + 0xc1,0xaf,0xbd,0x03,0x01,0x13,0x8a,0x6b, + 0x3a,0x91,0x11,0x41,0x4f,0x67,0xdc,0xea, + 0x97,0xf2,0xcf,0xce,0xf0,0xb4,0xe6,0x73, + 0x96,0xac,0x74,0x22,0xe7,0xad,0x35,0x85, + 0xe2,0xf9,0x37,0xe8,0x1c,0x75,0xdf,0x6e, + 0x47,0xf1,0x1a,0x71,0x1d,0x29,0xc5,0x89, + 0x6f,0xb7,0x62,0x0e,0xaa,0x18,0xbe,0x1b, + 0xfc,0x56,0x3e,0x4b,0xc6,0xd2,0x79,0x20, + 0x9a,0xdb,0xc0,0xfe,0x78,0xcd,0x5a,0xf4, + 0x1f,0xdd,0xa8,0x33,0x88,0x07,0xc7,0x31, + 0xb1,0x12,0x10,0x59,0x27,0x80,0xec,0x5f, + 0x60,0x51,0x7f,0xa9,0x19,0xb5,0x4a,0x0d, + 0x2d,0xe5,0x7a,0x9f,0x93,0xc9,0x9c,0xef, + 0xa0,0xe0,0x3b,0x4d,0xae,0x2a,0xf5,0xb0, + 0xc8,0xeb,0xbb,0x3c,0x83,0x53,0x99,0x61, + 0x17,0x2b,0x04,0x7e,0xba,0x77,0xd6,0x26, + 0xe1,0x69,0x14,0x63,0x55,0x21,0x0c,0x7d +}; + +static const unsigned char Rcon[30]= +{ + 0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80, + 0x1b,0x36,0x6c,0xd8,0xab,0x4d,0x9a,0x2f, + 0x5e,0xbc,0x63,0xc6,0x97,0x35,0x6a,0xd4, + 0xb3,0x7d,0xfa,0xef,0xc5,0x91, +}; + +/* ----- static functions ----- */ +static void AES_encrypt(const AES_CTX *ctx, uint32_t *data); +static void AES_decrypt(const AES_CTX *ctx, uint32_t *data); + +/* Perform doubling in Galois Field GF(2^8) using the irreducible polynomial + x^8+x^4+x^3+x+1 */ +static unsigned char AES_xtime(uint32_t x) +{ + return (x&0x80) ? (x<<1)^0x1b : x<<1; +} + +/** + * Set up AES with the key/iv and cipher size. + */ +void AES_set_key(AES_CTX *ctx, const uint8_t *key, + const uint8_t *iv, AES_MODE mode) +{ + int i, ii; + uint32_t *W, tmp, tmp2; + const unsigned char *ip; + int words; + + switch (mode) + { + case AES_MODE_128: + i = 10; + words = 4; + break; + + case AES_MODE_256: + i = 14; + words = 8; + break; + + default: /* fail silently */ + return; + } + + ctx->rounds = i; + ctx->key_size = words; + W = ctx->ks; + for (i = 0; i < words; i+=2) + { + W[i+0]= ((uint32_t)key[ 0]<<24)| + ((uint32_t)key[ 1]<<16)| + ((uint32_t)key[ 2]<< 8)| + ((uint32_t)key[ 3] ); + W[i+1]= ((uint32_t)key[ 4]<<24)| + ((uint32_t)key[ 5]<<16)| + ((uint32_t)key[ 6]<< 8)| + ((uint32_t)key[ 7] ); + key += 8; + } + + ip = Rcon; + ii = 4 * (ctx->rounds+1); + for (i = words; i> 8)&0xff]<<16; + tmp2|=(uint32_t)aes_sbox[(tmp>>16)&0xff]<<24; + tmp2|=(uint32_t)aes_sbox[(tmp>>24) ]; + tmp=tmp2^(((unsigned int)*ip)<<24); + ip++; + } + + if ((words == 8) && ((i % words) == 4)) + { + tmp2 =(uint32_t)aes_sbox[(tmp )&0xff] ; + tmp2|=(uint32_t)aes_sbox[(tmp>> 8)&0xff]<< 8; + tmp2|=(uint32_t)aes_sbox[(tmp>>16)&0xff]<<16; + tmp2|=(uint32_t)aes_sbox[(tmp>>24) ]<<24; + tmp=tmp2; + } + + W[i]=W[i-words]^tmp; + } + + /* copy the iv across */ + memcpy(ctx->iv, iv, 16); +} + +/** + * Change a key for decryption. + */ +void AES_convert_key(AES_CTX *ctx) +{ + int i; + uint32_t *k,w,t1,t2,t3,t4; + + k = ctx->ks; + k += 4; + + for (i= ctx->rounds*4; i > 4; i--) + { + w= *k; + w = inv_mix_col(w,t1,t2,t3,t4); + *k++ =w; + } +} + +/** + * Encrypt a byte sequence (with a block size 16) using the AES cipher. + */ +void AES_cbc_encrypt(AES_CTX *ctx, const uint8_t *msg, uint8_t *out, int length) +{ + int i; + uint32_t tin[4], tout[4], iv[4]; + + memcpy(iv, ctx->iv, AES_IV_SIZE); + for (i = 0; i < 4; i++) + tout[i] = ntohl(iv[i]); + + for (length -= AES_BLOCKSIZE; length >= 0; length -= AES_BLOCKSIZE) + { + uint32_t msg_32[4]; + uint32_t out_32[4]; + memcpy(msg_32, msg, AES_BLOCKSIZE); + msg += AES_BLOCKSIZE; + + for (i = 0; i < 4; i++) + tin[i] = ntohl(msg_32[i])^tout[i]; + + AES_encrypt(ctx, tin); + + for (i = 0; i < 4; i++) + { + tout[i] = tin[i]; + out_32[i] = htonl(tout[i]); + } + + memcpy(out, out_32, AES_BLOCKSIZE); + out += AES_BLOCKSIZE; + } + + for (i = 0; i < 4; i++) + iv[i] = htonl(tout[i]); + memcpy(ctx->iv, iv, AES_IV_SIZE); +} + +/** + * Decrypt a byte sequence (with a block size 16) using the AES cipher. + */ +void AES_cbc_decrypt(AES_CTX *ctx, const uint8_t *msg, uint8_t *out, int length) +{ + int i; + uint32_t tin[4], xor[4], tout[4], data[4], iv[4]; + + memcpy(iv, ctx->iv, AES_IV_SIZE); + for (i = 0; i < 4; i++) + xor[i] = ntohl(iv[i]); + for (length -= 16; length >= 0; length -= 16) + { + uint32_t msg_32[4]; + uint32_t out_32[4]; + memcpy(msg_32, msg, AES_BLOCKSIZE); + msg += AES_BLOCKSIZE; + + for (i = 0; i < 4; i++) + { + tin[i] = ntohl(msg_32[i]); + data[i] = tin[i]; + } + + AES_decrypt(ctx, data); + + for (i = 0; i < 4; i++) + { + tout[i] = data[i]^xor[i]; + xor[i] = tin[i]; + out_32[i] = htonl(tout[i]); + } + + memcpy(out, out_32, AES_BLOCKSIZE); + out += AES_BLOCKSIZE; + + } + + for (i = 0; i < 4; i++) + iv[i] = htonl(xor[i]); + memcpy(ctx->iv, iv, AES_IV_SIZE); + +} + +/** + * Encrypt a single block (16 bytes) of data + */ +static void AES_encrypt(const AES_CTX *ctx, uint32_t *data) +{ + /* To make this code smaller, generate the sbox entries on the fly. + * This will have a really heavy effect upon performance. + */ + uint32_t tmp[4]; + uint32_t tmp1, old_a0, a0, a1, a2, a3, row; + int curr_rnd; + int rounds = ctx->rounds; + const uint32_t *k = ctx->ks; + + /* Pre-round key addition */ + for (row = 0; row < 4; row++) + data[row] ^= *(k++); + + /* Encrypt one block. */ + for (curr_rnd = 0; curr_rnd < rounds; curr_rnd++) + { + /* Perform ByteSub and ShiftRow operations together */ + for (row = 0; row < 4; row++) + { + a0 = (uint32_t)aes_sbox[(data[row%4]>>24)&0xFF]; + a1 = (uint32_t)aes_sbox[(data[(row+1)%4]>>16)&0xFF]; + a2 = (uint32_t)aes_sbox[(data[(row+2)%4]>>8)&0xFF]; + a3 = (uint32_t)aes_sbox[(data[(row+3)%4])&0xFF]; + + /* Perform MixColumn iff not last round */ + if (curr_rnd < (rounds - 1)) + { + tmp1 = a0 ^ a1 ^ a2 ^ a3; + old_a0 = a0; + a0 ^= tmp1 ^ AES_xtime(a0 ^ a1); + a1 ^= tmp1 ^ AES_xtime(a1 ^ a2); + a2 ^= tmp1 ^ AES_xtime(a2 ^ a3); + a3 ^= tmp1 ^ AES_xtime(a3 ^ old_a0); + } + + tmp[row] = ((a0 << 24) | (a1 << 16) | (a2 << 8) | a3); + } + + /* KeyAddition - note that it is vital that this loop is separate from + the MixColumn operation, which must be atomic...*/ + for (row = 0; row < 4; row++) + data[row] = tmp[row] ^ *(k++); + } +} + +/** + * Decrypt a single block (16 bytes) of data + */ +static void AES_decrypt(const AES_CTX *ctx, uint32_t *data) +{ + uint32_t tmp[4]; + uint32_t xt0,xt1,xt2,xt3,xt4,xt5,xt6; + uint32_t a0, a1, a2, a3, row; + int curr_rnd; + int rounds = ctx->rounds; + const uint32_t *k = ctx->ks + ((rounds+1)*4); + /* pre-round key addition */ + for (row=4; row > 0;row--) + data[row-1] ^= *(--k); + + /* Decrypt one block */ + for (curr_rnd = 0; curr_rnd < rounds; curr_rnd++) + { + + /* Perform ByteSub and ShiftRow operations together */ + for (row = 4; row > 0; row--) + { + + a0 = aes_isbox[(data[(row+3)%4]>>24)&0xFF]; + a1 = aes_isbox[(data[(row+2)%4]>>16)&0xFF]; + a2 = aes_isbox[(data[(row+1)%4]>>8)&0xFF]; + a3 = aes_isbox[(data[row%4])&0xFF]; + + /* Perform MixColumn iff not last round */ + if (curr_rnd<(rounds-1)) + { + /* The MDS cofefficients (0x09, 0x0B, 0x0D, 0x0E) + are quite large compared to encryption; this + operation slows decryption down noticeably. */ + xt0 = AES_xtime(a0^a1); + xt1 = AES_xtime(a1^a2); + xt2 = AES_xtime(a2^a3); + xt3 = AES_xtime(a3^a0); + xt4 = AES_xtime(xt0^xt1); + xt5 = AES_xtime(xt1^xt2); + xt6 = AES_xtime(xt4^xt5); + + xt0 ^= a1^a2^a3^xt4^xt6; + xt1 ^= a0^a2^a3^xt5^xt6; + xt2 ^= a0^a1^a3^xt4^xt6; + xt3 ^= a0^a1^a2^xt5^xt6; + tmp[row-1] = ((xt0<<24)|(xt1<<16)|(xt2<<8)|xt3); + } + else + tmp[row-1] = ((a0<<24)|(a1<<16)|(a2<<8)|a3); + } + + for (row = 4; row > 0; row--) + data[row-1] = tmp[row-1] ^ *(--k); + } +} + +#endif diff --git a/features/unsupported/net/https/axTLS/crypto/bigint.c b/features/unsupported/net/https/axTLS/crypto/bigint.c new file mode 100644 index 00000000000..7275ed1fc7c --- /dev/null +++ b/features/unsupported/net/https/axTLS/crypto/bigint.c @@ -0,0 +1,1515 @@ +/* + * Copyright (c) 2007, Cameron Rich + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * * Neither the name of the axTLS project nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @defgroup bigint_api Big Integer API + * @brief The bigint implementation as used by the axTLS project. + * + * The bigint library is for RSA encryption/decryption as well as signing. + * This code tries to minimise use of malloc/free by maintaining a small + * cache. A bigint context may maintain state by being made "permanent". + * It be be later released with a bi_depermanent() and bi_free() call. + * + * It supports the following reduction techniques: + * - Classical + * - Barrett + * - Montgomery + * + * It also implements the following: + * - Karatsuba multiplication + * - Squaring + * - Sliding window exponentiation + * - Chinese Remainder Theorem (implemented in rsa.c). + * + * All the algorithms used are pretty standard, and designed for different + * data bus sizes. Negative numbers are not dealt with at all, so a subtraction + * may need to be tested for negativity. + * + * This library steals some ideas from Jef Poskanzer + * + * and GMP . It gets most of its implementation + * detail from "The Handbook of Applied Cryptography" + * + * @{ + */ + +#include +#include +#include +#include +#include +#include "os_port.h" +#include "bigint.h" + +#define V1 v->comps[v->size-1] /**< v1 for division */ +#define V2 v->comps[v->size-2] /**< v2 for division */ +#define U(j) tmp_u->comps[tmp_u->size-j-1] /**< uj for division */ +#define Q(j) quotient->comps[quotient->size-j-1] /**< qj for division */ + +static bigint *bi_int_multiply(BI_CTX *ctx, bigint *bi, comp i); +static bigint *bi_int_divide(BI_CTX *ctx, bigint *biR, comp denom); +static bigint *alloc(BI_CTX *ctx, int size); +static bigint *trim(bigint *bi); +static void more_comps(bigint *bi, int n); +#if defined(CONFIG_BIGINT_KARATSUBA) || defined(CONFIG_BIGINT_BARRETT) || \ + defined(CONFIG_BIGINT_MONTGOMERY) +static bigint *comp_right_shift(bigint *biR, int num_shifts); +static bigint *comp_left_shift(bigint *biR, int num_shifts); +#endif + +#ifdef CONFIG_BIGINT_CHECK_ON +static void check(const bigint *bi); +#else +#define check(A) /**< disappears in normal production mode */ +#endif + + +/** + * @brief Start a new bigint context. + * @return A bigint context. + */ +BI_CTX *bi_initialize(void) +{ + /* calloc() sets everything to zero */ + BI_CTX *ctx = (BI_CTX *)calloc(1, sizeof(BI_CTX)); + + /* the radix */ + ctx->bi_radix = alloc(ctx, 2); + ctx->bi_radix->comps[0] = 0; + ctx->bi_radix->comps[1] = 1; + bi_permanent(ctx->bi_radix); + return ctx; +} + +/** + * @brief Close the bigint context and free any resources. + * + * Free up any used memory - a check is done if all objects were not + * properly freed. + * @param ctx [in] The bigint session context. + */ +void bi_terminate(BI_CTX *ctx) +{ + bi_depermanent(ctx->bi_radix); + bi_free(ctx, ctx->bi_radix); + + if (ctx->active_count != 0) + { +#ifdef CONFIG_SSL_FULL_MODE + printf("bi_terminate: there were %d un-freed bigints\n", + ctx->active_count); +#endif + abort(); + } + + bi_clear_cache(ctx); + free(ctx); +} + +/** + *@brief Clear the memory cache. + */ +void bi_clear_cache(BI_CTX *ctx) +{ + bigint *p, *pn; + + if (ctx->free_list == NULL) + return; + + for (p = ctx->free_list; p != NULL; p = pn) + { + pn = p->next; + free(p->comps); + free(p); + } + + ctx->free_count = 0; + ctx->free_list = NULL; +} + +/** + * @brief Increment the number of references to this object. + * It does not do a full copy. + * @param bi [in] The bigint to copy. + * @return A reference to the same bigint. + */ +bigint *bi_copy(bigint *bi) +{ + check(bi); + if (bi->refs != PERMANENT) + bi->refs++; + return bi; +} + +/** + * @brief Simply make a bigint object "unfreeable" if bi_free() is called on it. + * + * For this object to be freed, bi_depermanent() must be called. + * @param bi [in] The bigint to be made permanent. + */ +void bi_permanent(bigint *bi) +{ + check(bi); + if (bi->refs != 1) + { +#ifdef CONFIG_SSL_FULL_MODE + printf("bi_permanent: refs was not 1\n"); +#endif + abort(); + } + + bi->refs = PERMANENT; +} + +/** + * @brief Take a permanent object and make it eligible for freedom. + * @param bi [in] The bigint to be made back to temporary. + */ +void bi_depermanent(bigint *bi) +{ + check(bi); + if (bi->refs != PERMANENT) + { +#ifdef CONFIG_SSL_FULL_MODE + printf("bi_depermanent: bigint was not permanent\n"); +#endif + abort(); + } + + bi->refs = 1; +} + +/** + * @brief Free a bigint object so it can be used again. + * + * The memory itself it not actually freed, just tagged as being available + * @param ctx [in] The bigint session context. + * @param bi [in] The bigint to be freed. + */ +void bi_free(BI_CTX *ctx, bigint *bi) +{ + check(bi); + if (bi->refs == PERMANENT) + { + return; + } + + if (--bi->refs > 0) + { + return; + } + + bi->next = ctx->free_list; + ctx->free_list = bi; + ctx->free_count++; + + if (--ctx->active_count < 0) + { +#ifdef CONFIG_SSL_FULL_MODE + printf("bi_free: active_count went negative " + "- double-freed bigint?\n"); +#endif + abort(); + } +} + +/** + * @brief Convert an (unsigned) integer into a bigint. + * @param ctx [in] The bigint session context. + * @param i [in] The (unsigned) integer to be converted. + * + */ +bigint *int_to_bi(BI_CTX *ctx, comp i) +{ + bigint *biR = alloc(ctx, 1); + biR->comps[0] = i; + return biR; +} + +/** + * @brief Do a full copy of the bigint object. + * @param ctx [in] The bigint session context. + * @param bi [in] The bigint object to be copied. + */ +bigint *bi_clone(BI_CTX *ctx, const bigint *bi) +{ + bigint *biR = alloc(ctx, bi->size); + check(bi); + memcpy(biR->comps, bi->comps, bi->size*COMP_BYTE_SIZE); + return biR; +} + +/** + * @brief Perform an addition operation between two bigints. + * @param ctx [in] The bigint session context. + * @param bia [in] A bigint. + * @param bib [in] Another bigint. + * @return The result of the addition. + */ +bigint *bi_add(BI_CTX *ctx, bigint *bia, bigint *bib) +{ + int n; + comp carry = 0; + comp *pa, *pb; + + check(bia); + check(bib); + + n = max(bia->size, bib->size); + more_comps(bia, n+1); + more_comps(bib, n); + pa = bia->comps; + pb = bib->comps; + + do + { + comp sl, rl, cy1; + sl = *pa + *pb++; + rl = sl + carry; + cy1 = sl < *pa; + carry = cy1 | (rl < sl); + *pa++ = rl; + } while (--n != 0); + + *pa = carry; /* do overflow */ + bi_free(ctx, bib); + return trim(bia); +} + +/** + * @brief Perform a subtraction operation between two bigints. + * @param ctx [in] The bigint session context. + * @param bia [in] A bigint. + * @param bib [in] Another bigint. + * @param is_negative [out] If defined, indicates that the result was negative. + * is_negative may be null. + * @return The result of the subtraction. The result is always positive. + */ +bigint *bi_subtract(BI_CTX *ctx, + bigint *bia, bigint *bib, int *is_negative) +{ + int n = bia->size; + comp *pa, *pb, carry = 0; + + check(bia); + check(bib); + more_comps(bib, n); + pa = bia->comps; + pb = bib->comps; + + do + { + comp sl, rl, cy1; + sl = *pa - *pb++; + rl = sl - carry; + cy1 = sl > *pa; + carry = cy1 | (rl > sl); + *pa++ = rl; + } while (--n != 0); + + if (is_negative) /* indicate a negative result */ + { + *is_negative = carry; + } + + bi_free(ctx, trim(bib)); /* put bib back to the way it was */ + return trim(bia); +} + +/** + * Perform a multiply between a bigint an an (unsigned) integer + */ +static bigint *bi_int_multiply(BI_CTX *ctx, bigint *bia, comp b) +{ + int j = 0, n = bia->size; + bigint *biR = alloc(ctx, n + 1); + comp carry = 0; + comp *r = biR->comps; + comp *a = bia->comps; + + check(bia); + + /* clear things to start with */ + memset(r, 0, ((n+1)*COMP_BYTE_SIZE)); + + do + { + long_comp tmp = *r + (long_comp)a[j]*b + carry; + *r++ = (comp)tmp; /* downsize */ + carry = (comp)(tmp >> COMP_BIT_SIZE); + } while (++j < n); + + *r = carry; + bi_free(ctx, bia); + return trim(biR); +} + +/** + * @brief Does both division and modulo calculations. + * + * Used extensively when doing classical reduction. + * @param ctx [in] The bigint session context. + * @param u [in] A bigint which is the numerator. + * @param v [in] Either the denominator or the modulus depending on the mode. + * @param is_mod [n] Determines if this is a normal division (0) or a reduction + * (1). + * @return The result of the division/reduction. + */ +bigint *bi_divide(BI_CTX *ctx, bigint *u, bigint *v, int is_mod) +{ + int n = v->size, m = u->size-n; + int j = 0, orig_u_size = u->size; + uint8_t mod_offset = ctx->mod_offset; + comp d; + bigint *quotient, *tmp_u; + comp q_dash; + + check(u); + check(v); + + /* if doing reduction and we are < mod, then return mod */ + if (is_mod && bi_compare(v, u) > 0) + { + bi_free(ctx, v); + return u; + } + + quotient = alloc(ctx, m+1); + tmp_u = alloc(ctx, n+1); + v = trim(v); /* make sure we have no leading 0's */ + d = (comp)((long_comp)COMP_RADIX/(V1+1)); + + /* clear things to start with */ + memset(quotient->comps, 0, ((quotient->size)*COMP_BYTE_SIZE)); + + /* normalise */ + if (d > 1) + { + u = bi_int_multiply(ctx, u, d); + + if (is_mod) + { + v = ctx->bi_normalised_mod[mod_offset]; + } + else + { + v = bi_int_multiply(ctx, v, d); + } + } + + if (orig_u_size == u->size) /* new digit position u0 */ + { + more_comps(u, orig_u_size + 1); + } + + do + { + /* get a temporary short version of u */ + memcpy(tmp_u->comps, &u->comps[u->size-n-1-j], (n+1)*COMP_BYTE_SIZE); + + /* calculate q' */ + if (U(0) == V1) + { + q_dash = COMP_RADIX-1; + } + else + { + q_dash = (comp)(((long_comp)U(0)*COMP_RADIX + U(1))/V1); + + if (v->size > 1 && V2) + { + /* we are implementing the following: + if (V2*q_dash > (((U(0)*COMP_RADIX + U(1) - + q_dash*V1)*COMP_RADIX) + U(2))) ... */ + comp inner = (comp)((long_comp)COMP_RADIX*U(0) + U(1) - + (long_comp)q_dash*V1); + if ((long_comp)V2*q_dash > (long_comp)inner*COMP_RADIX + U(2)) + { + q_dash--; + } + } + } + + /* multiply and subtract */ + if (q_dash) + { + int is_negative; + tmp_u = bi_subtract(ctx, tmp_u, + bi_int_multiply(ctx, bi_copy(v), q_dash), &is_negative); + more_comps(tmp_u, n+1); + + Q(j) = q_dash; + + /* add back */ + if (is_negative) + { + Q(j)--; + tmp_u = bi_add(ctx, tmp_u, bi_copy(v)); + + /* lop off the carry */ + tmp_u->size--; + v->size--; + } + } + else + { + Q(j) = 0; + } + + /* copy back to u */ + memcpy(&u->comps[u->size-n-1-j], tmp_u->comps, (n+1)*COMP_BYTE_SIZE); + } while (++j <= m); + + bi_free(ctx, tmp_u); + bi_free(ctx, v); + + if (is_mod) /* get the remainder */ + { + bi_free(ctx, quotient); + return bi_int_divide(ctx, trim(u), d); + } + else /* get the quotient */ + { + bi_free(ctx, u); + return trim(quotient); + } +} + +/* + * Perform an integer divide on a bigint. + */ +static bigint *bi_int_divide(BI_CTX *ctx, bigint *biR, comp denom) +{ + int i = biR->size - 1; + long_comp r = 0; + + check(biR); + + do + { + r = (r<comps[i]; + biR->comps[i] = (comp)(r / denom); + r %= denom; + } while (--i >= 0); + + return trim(biR); +} + +#ifdef CONFIG_BIGINT_MONTGOMERY +/** + * There is a need for the value of integer N' such that B^-1(B-1)-N^-1N'=1, + * where B^-1(B-1) mod N=1. Actually, only the least significant part of + * N' is needed, hence the definition N0'=N' mod b. We reproduce below the + * simple algorithm from an article by Dusse and Kaliski to efficiently + * find N0' from N0 and b */ +static comp modular_inverse(bigint *bim) +{ + int i; + comp t = 1; + comp two_2_i_minus_1 = 2; /* 2^(i-1) */ + long_comp two_2_i = 4; /* 2^i */ + comp N = bim->comps[0]; + + for (i = 2; i <= COMP_BIT_SIZE; i++) + { + if ((long_comp)N*t%two_2_i >= two_2_i_minus_1) + { + t += two_2_i_minus_1; + } + + two_2_i_minus_1 <<= 1; + two_2_i <<= 1; + } + + return (comp)(COMP_RADIX-t); +} +#endif + +#if defined(CONFIG_BIGINT_KARATSUBA) || defined(CONFIG_BIGINT_BARRETT) || \ + defined(CONFIG_BIGINT_MONTGOMERY) +/** + * Take each component and shift down (in terms of components) + */ +static bigint *comp_right_shift(bigint *biR, int num_shifts) +{ + int i = biR->size-num_shifts; + comp *x = biR->comps; + comp *y = &biR->comps[num_shifts]; + + check(biR); + + if (i <= 0) /* have we completely right shifted? */ + { + biR->comps[0] = 0; /* return 0 */ + biR->size = 1; + return biR; + } + + do + { + *x++ = *y++; + } while (--i > 0); + + biR->size -= num_shifts; + return biR; +} + +/** + * Take each component and shift it up (in terms of components) + */ +static bigint *comp_left_shift(bigint *biR, int num_shifts) +{ + int i = biR->size-1; + comp *x, *y; + + check(biR); + + if (num_shifts <= 0) + { + return biR; + } + + more_comps(biR, biR->size + num_shifts); + + x = &biR->comps[i+num_shifts]; + y = &biR->comps[i]; + + do + { + *x-- = *y--; + } while (i--); + + memset(biR->comps, 0, num_shifts*COMP_BYTE_SIZE); /* zero LS comps */ + return biR; +} +#endif + +/** + * @brief Allow a binary sequence to be imported as a bigint. + * @param ctx [in] The bigint session context. + * @param data [in] The data to be converted. + * @param size [in] The number of bytes of data. + * @return A bigint representing this data. + */ +bigint *bi_import(BI_CTX *ctx, const uint8_t *data, int size) +{ + bigint *biR = alloc(ctx, (size+COMP_BYTE_SIZE-1)/COMP_BYTE_SIZE); + int i, j = 0, offset = 0; + + memset(biR->comps, 0, biR->size*COMP_BYTE_SIZE); + + for (i = size-1; i >= 0; i--) + { + biR->comps[offset] += data[i] << (j*8); + + if (++j == COMP_BYTE_SIZE) + { + j = 0; + offset ++; + } + } + + return trim(biR); +} + +#ifdef CONFIG_SSL_FULL_MODE +/** + * @brief The testharness uses this code to import text hex-streams and + * convert them into bigints. + * @param ctx [in] The bigint session context. + * @param data [in] A string consisting of hex characters. The characters must + * be in upper case. + * @return A bigint representing this data. + */ +bigint *bi_str_import(BI_CTX *ctx, const char *data) +{ + int size = strlen(data); + bigint *biR = alloc(ctx, (size+COMP_NUM_NIBBLES-1)/COMP_NUM_NIBBLES); + int i, j = 0, offset = 0; + memset(biR->comps, 0, biR->size*COMP_BYTE_SIZE); + + for (i = size-1; i >= 0; i--) + { + int num = (data[i] <= '9') ? (data[i] - '0') : (data[i] - 'A' + 10); + biR->comps[offset] += num << (j*4); + + if (++j == COMP_NUM_NIBBLES) + { + j = 0; + offset ++; + } + } + + return biR; +} + +void bi_print(const char *label, bigint *x) +{ + int i, j; + + if (x == NULL) + { + printf("%s: (null)\n", label); + return; + } + + printf("%s: (size %d)\n", label, x->size); + for (i = x->size-1; i >= 0; i--) + { + for (j = COMP_NUM_NIBBLES-1; j >= 0; j--) + { + comp mask = 0x0f << (j*4); + comp num = (x->comps[i] & mask) >> (j*4); + putc((num <= 9) ? (num + '0') : (num + 'A' - 10), stdout); + } + } + + printf("\r\n"); +} +#endif + +/** + * @brief Take a bigint and convert it into a byte sequence. + * + * This is useful after a decrypt operation. + * @param ctx [in] The bigint session context. + * @param x [in] The bigint to be converted. + * @param data [out] The converted data as a byte stream. + * @param size [in] The maximum size of the byte stream. Unused bytes will be + * zeroed. + */ +void bi_export(BI_CTX *ctx, bigint *x, uint8_t *data, int size) +{ + int i, j, k = size-1; + + check(x); + memset(data, 0, size); /* ensure all leading 0's are cleared */ + + for (i = 0; i < x->size; i++) + { + for (j = 0; j < COMP_BYTE_SIZE; j++) + { + comp mask = 0xff << (j*8); + int num = (x->comps[i] & mask) >> (j*8); + data[k--] = num; + + if (k < 0) + { + goto buf_done; + } + } + } +buf_done: + + bi_free(ctx, x); +} + +/** + * @brief Pre-calculate some of the expensive steps in reduction. + * + * This function should only be called once (normally when a session starts). + * When the session is over, bi_free_mod() should be called. bi_mod_power() + * relies on this function being called. + * @param ctx [in] The bigint session context. + * @param bim [in] The bigint modulus that will be used. + * @param mod_offset [in] There are three moduluii that can be stored - the + * standard modulus, and its two primes p and q. This offset refers to which + * modulus we are referring to. + * @see bi_free_mod(), bi_mod_power(). + */ +void bi_set_mod(BI_CTX *ctx, bigint *bim, int mod_offset) +{ + int k = bim->size; + comp d = (comp)((long_comp)COMP_RADIX/(bim->comps[k-1]+1)); +#ifdef CONFIG_BIGINT_MONTGOMERY + bigint *R, *R2; +#endif + + ctx->bi_mod[mod_offset] = bim; + bi_permanent(ctx->bi_mod[mod_offset]); + ctx->bi_normalised_mod[mod_offset] = bi_int_multiply(ctx, bim, d); + bi_permanent(ctx->bi_normalised_mod[mod_offset]); + +#if defined(CONFIG_BIGINT_MONTGOMERY) + /* set montgomery variables */ + R = comp_left_shift(bi_clone(ctx, ctx->bi_radix), k-1); /* R */ + R2 = comp_left_shift(bi_clone(ctx, ctx->bi_radix), k*2-1); /* R^2 */ + ctx->bi_RR_mod_m[mod_offset] = bi_mod(ctx, R2); /* R^2 mod m */ + ctx->bi_R_mod_m[mod_offset] = bi_mod(ctx, R); /* R mod m */ + + bi_permanent(ctx->bi_RR_mod_m[mod_offset]); + bi_permanent(ctx->bi_R_mod_m[mod_offset]); + + ctx->N0_dash[mod_offset] = modular_inverse(ctx->bi_mod[mod_offset]); + +#elif defined (CONFIG_BIGINT_BARRETT) + ctx->bi_mu[mod_offset] = + bi_divide(ctx, comp_left_shift( + bi_clone(ctx, ctx->bi_radix), k*2-1), ctx->bi_mod[mod_offset], 0); + bi_permanent(ctx->bi_mu[mod_offset]); +#endif +} + +/** + * @brief Used when cleaning various bigints at the end of a session. + * @param ctx [in] The bigint session context. + * @param mod_offset [in] The offset to use. + * @see bi_set_mod(). + */ +void bi_free_mod(BI_CTX *ctx, int mod_offset) +{ + bi_depermanent(ctx->bi_mod[mod_offset]); + bi_free(ctx, ctx->bi_mod[mod_offset]); +#if defined (CONFIG_BIGINT_MONTGOMERY) + bi_depermanent(ctx->bi_RR_mod_m[mod_offset]); + bi_depermanent(ctx->bi_R_mod_m[mod_offset]); + bi_free(ctx, ctx->bi_RR_mod_m[mod_offset]); + bi_free(ctx, ctx->bi_R_mod_m[mod_offset]); +#elif defined(CONFIG_BIGINT_BARRETT) + bi_depermanent(ctx->bi_mu[mod_offset]); + bi_free(ctx, ctx->bi_mu[mod_offset]); +#endif + bi_depermanent(ctx->bi_normalised_mod[mod_offset]); + bi_free(ctx, ctx->bi_normalised_mod[mod_offset]); +} + +/** + * Perform a standard multiplication between two bigints. + * + * Barrett reduction has no need for some parts of the product, so ignore bits + * of the multiply. This routine gives Barrett its big performance + * improvements over Classical/Montgomery reduction methods. + */ +static bigint *regular_multiply(BI_CTX *ctx, bigint *bia, bigint *bib, + int inner_partial, int outer_partial) +{ + int i = 0, j; + int n = bia->size; + int t = bib->size; + bigint *biR = alloc(ctx, n + t); + comp *sr = biR->comps; + comp *sa = bia->comps; + comp *sb = bib->comps; + + check(bia); + check(bib); + + /* clear things to start with */ + memset(biR->comps, 0, ((n+t)*COMP_BYTE_SIZE)); + + do + { + long_comp tmp; + comp carry = 0; + int r_index = i; + j = 0; + + if (outer_partial && outer_partial-i > 0 && outer_partial < n) + { + r_index = outer_partial-1; + j = outer_partial-i-1; + } + + do + { + if (inner_partial && r_index >= inner_partial) + { + break; + } + + tmp = sr[r_index] + ((long_comp)sa[j])*sb[i] + carry; + sr[r_index++] = (comp)tmp; /* downsize */ + carry = tmp >> COMP_BIT_SIZE; + } while (++j < n); + + sr[r_index] = carry; + } while (++i < t); + + bi_free(ctx, bia); + bi_free(ctx, bib); + return trim(biR); +} + +#ifdef CONFIG_BIGINT_KARATSUBA +/* + * Karatsuba improves on regular multiplication due to only 3 multiplications + * being done instead of 4. The additional additions/subtractions are O(N) + * rather than O(N^2) and so for big numbers it saves on a few operations + */ +static bigint *karatsuba(BI_CTX *ctx, bigint *bia, bigint *bib, int is_square) +{ + bigint *x0, *x1; + bigint *p0, *p1, *p2; + int m; + + if (is_square) + { + m = (bia->size + 1)/2; + } + else + { + m = (max(bia->size, bib->size) + 1)/2; + } + + x0 = bi_clone(ctx, bia); + x0->size = m; + x1 = bi_clone(ctx, bia); + comp_right_shift(x1, m); + bi_free(ctx, bia); + + /* work out the 3 partial products */ + if (is_square) + { + p0 = bi_square(ctx, bi_copy(x0)); + p2 = bi_square(ctx, bi_copy(x1)); + p1 = bi_square(ctx, bi_add(ctx, x0, x1)); + } + else /* normal multiply */ + { + bigint *y0, *y1; + y0 = bi_clone(ctx, bib); + y0->size = m; + y1 = bi_clone(ctx, bib); + comp_right_shift(y1, m); + bi_free(ctx, bib); + + p0 = bi_multiply(ctx, bi_copy(x0), bi_copy(y0)); + p2 = bi_multiply(ctx, bi_copy(x1), bi_copy(y1)); + p1 = bi_multiply(ctx, bi_add(ctx, x0, x1), bi_add(ctx, y0, y1)); + } + + p1 = bi_subtract(ctx, + bi_subtract(ctx, p1, bi_copy(p2), NULL), bi_copy(p0), NULL); + + comp_left_shift(p1, m); + comp_left_shift(p2, 2*m); + return bi_add(ctx, p1, bi_add(ctx, p0, p2)); +} +#endif + +/** + * @brief Perform a multiplication operation between two bigints. + * @param ctx [in] The bigint session context. + * @param bia [in] A bigint. + * @param bib [in] Another bigint. + * @return The result of the multiplication. + */ +bigint *bi_multiply(BI_CTX *ctx, bigint *bia, bigint *bib) +{ + check(bia); + check(bib); + +#ifdef CONFIG_BIGINT_KARATSUBA + if (min(bia->size, bib->size) < MUL_KARATSUBA_THRESH) + { + return regular_multiply(ctx, bia, bib, 0, 0); + } + + return karatsuba(ctx, bia, bib, 0); +#else + return regular_multiply(ctx, bia, bib, 0, 0); +#endif +} + +#ifdef CONFIG_BIGINT_SQUARE +/* + * Perform the actual square operion. It takes into account overflow. + */ +static bigint *regular_square(BI_CTX *ctx, bigint *bi) +{ + int t = bi->size; + int i = 0, j; + bigint *biR = alloc(ctx, t*2+1); + comp *w = biR->comps; + comp *x = bi->comps; + long_comp carry; + memset(w, 0, biR->size*COMP_BYTE_SIZE); + + do + { + long_comp tmp = w[2*i] + (long_comp)x[i]*x[i]; + w[2*i] = (comp)tmp; + carry = tmp >> COMP_BIT_SIZE; + + for (j = i+1; j < t; j++) + { + uint8_t c = 0; + long_comp xx = (long_comp)x[i]*x[j]; + if ((COMP_MAX-xx) < xx) + c = 1; + + tmp = (xx<<1); + + if ((COMP_MAX-tmp) < w[i+j]) + c = 1; + + tmp += w[i+j]; + + if ((COMP_MAX-tmp) < carry) + c = 1; + + tmp += carry; + w[i+j] = (comp)tmp; + carry = tmp >> COMP_BIT_SIZE; + + if (c) + carry += COMP_RADIX; + } + + tmp = w[i+t] + carry; + w[i+t] = (comp)tmp; + w[i+t+1] = tmp >> COMP_BIT_SIZE; + } while (++i < t); + + bi_free(ctx, bi); + return trim(biR); +} + +/** + * @brief Perform a square operation on a bigint. + * @param ctx [in] The bigint session context. + * @param bia [in] A bigint. + * @return The result of the multiplication. + */ +bigint *bi_square(BI_CTX *ctx, bigint *bia) +{ + check(bia); + +#ifdef CONFIG_BIGINT_KARATSUBA + if (bia->size < SQU_KARATSUBA_THRESH) + { + return regular_square(ctx, bia); + } + + return karatsuba(ctx, bia, NULL, 1); +#else + return regular_square(ctx, bia); +#endif +} +#endif + +/** + * @brief Compare two bigints. + * @param bia [in] A bigint. + * @param bib [in] Another bigint. + * @return -1 if smaller, 1 if larger and 0 if equal. + */ +int bi_compare(bigint *bia, bigint *bib) +{ + int r, i; + + check(bia); + check(bib); + + if (bia->size > bib->size) + r = 1; + else if (bia->size < bib->size) + r = -1; + else + { + comp *a = bia->comps; + comp *b = bib->comps; + + /* Same number of components. Compare starting from the high end + * and working down. */ + r = 0; + i = bia->size - 1; + + do + { + if (a[i] > b[i]) + { + r = 1; + break; + } + else if (a[i] < b[i]) + { + r = -1; + break; + } + } while (--i >= 0); + } + + return r; +} + +/* + * Allocate and zero more components. Does not consume bi. + */ +static void more_comps(bigint *bi, int n) +{ + if (n > bi->max_comps) + { + bi->max_comps = max(bi->max_comps * 2, n); + bi->comps = (comp*)realloc(bi->comps, bi->max_comps * COMP_BYTE_SIZE); + } + + if (n > bi->size) + { + memset(&bi->comps[bi->size], 0, (n-bi->size)*COMP_BYTE_SIZE); + } + + bi->size = n; +} + +/* + * Make a new empty bigint. It may just use an old one if one is available. + * Otherwise get one off the heap. + */ +static bigint *alloc(BI_CTX *ctx, int size) +{ + bigint *biR; + + /* Can we recycle an old bigint? */ + if (ctx->free_list != NULL) + { + biR = ctx->free_list; + ctx->free_list = biR->next; + ctx->free_count--; + + if (biR->refs != 0) + { +#ifdef CONFIG_SSL_FULL_MODE + printf("alloc: refs was not 0\n"); +#endif + abort(); /* create a stack trace from a core dump */ + } + + more_comps(biR, size); + } + else + { + /* No free bigints available - create a new one. */ + biR = (bigint *)malloc(sizeof(bigint)); + biR->comps = (comp*)malloc(size * COMP_BYTE_SIZE); + biR->max_comps = size; /* give some space to spare */ + } + + biR->size = size; + biR->refs = 1; + biR->next = NULL; + ctx->active_count++; + return biR; +} + +/* + * Work out the highest '1' bit in an exponent. Used when doing sliding-window + * exponentiation. + */ +static int find_max_exp_index(bigint *biexp) +{ + int i = COMP_BIT_SIZE-1; + comp shift = COMP_RADIX/2; + comp test = biexp->comps[biexp->size-1]; /* assume no leading zeroes */ + + check(biexp); + + do + { + if (test & shift) + { + return i+(biexp->size-1)*COMP_BIT_SIZE; + } + + shift >>= 1; + } while (i-- != 0); + + return -1; /* error - must have been a leading 0 */ +} + +/* + * Is a particular bit is an exponent 1 or 0? Used when doing sliding-window + * exponentiation. + */ +static int exp_bit_is_one(bigint *biexp, int offset) +{ + comp test = biexp->comps[offset / COMP_BIT_SIZE]; + int num_shifts = offset % COMP_BIT_SIZE; + comp shift = 1; + int i; + + check(biexp); + + for (i = 0; i < num_shifts; i++) + { + shift <<= 1; + } + + return (test & shift) != 0; +} + +#ifdef CONFIG_BIGINT_CHECK_ON +/* + * Perform a sanity check on bi. + */ +static void check(const bigint *bi) +{ + if (bi->refs <= 0) + { + printf("check: zero or negative refs in bigint\n"); + abort(); + } + + if (bi->next != NULL) + { + printf("check: attempt to use a bigint from " + "the free list\n"); + abort(); + } +} +#endif + +/* + * Delete any leading 0's (and allow for 0). + */ +static bigint *trim(bigint *bi) +{ + check(bi); + + while (bi->comps[bi->size-1] == 0 && bi->size > 1) + { + bi->size--; + } + + return bi; +} + +#if defined(CONFIG_BIGINT_MONTGOMERY) +/** + * @brief Perform a single montgomery reduction. + * @param ctx [in] The bigint session context. + * @param bixy [in] A bigint. + * @return The result of the montgomery reduction. + */ +bigint *bi_mont(BI_CTX *ctx, bigint *bixy) +{ + int i = 0, n; + uint8_t mod_offset = ctx->mod_offset; + bigint *bim = ctx->bi_mod[mod_offset]; + comp mod_inv = ctx->N0_dash[mod_offset]; + + check(bixy); + + if (ctx->use_classical) /* just use classical instead */ + { + return bi_mod(ctx, bixy); + } + + n = bim->size; + + do + { + bixy = bi_add(ctx, bixy, comp_left_shift( + bi_int_multiply(ctx, bim, bixy->comps[i]*mod_inv), i)); + } while (++i < n); + + comp_right_shift(bixy, n); + + if (bi_compare(bixy, bim) >= 0) + { + bixy = bi_subtract(ctx, bixy, bim, NULL); + } + + return bixy; +} + +#elif defined(CONFIG_BIGINT_BARRETT) +/* + * Stomp on the most significant components to give the illusion of a "mod base + * radix" operation + */ +static bigint *comp_mod(bigint *bi, int mod) +{ + check(bi); + + if (bi->size > mod) + { + bi->size = mod; + } + + return bi; +} + +/** + * @brief Perform a single Barrett reduction. + * @param ctx [in] The bigint session context. + * @param bi [in] A bigint. + * @return The result of the Barrett reduction. + */ +bigint *bi_barrett(BI_CTX *ctx, bigint *bi) +{ + + bigint *q1, *q2, *q3, *r1, *r2, *r; + uint8_t mod_offset = ctx->mod_offset; + bigint *bim = ctx->bi_mod[mod_offset]; + int k = bim->size; + + check(bi); + check(bim); + + /* use Classical method instead - Barrett cannot help here */ + if (bi->size > k*2) + { + + return bi_mod(ctx, bi); + } + bigint* a = bi_clone(ctx, bi); + q1 = comp_right_shift(a, k-1); + + /* do outer partial multiply */ + q2 = regular_multiply(ctx, q1, ctx->bi_mu[mod_offset], 0, k-1); + q3 = comp_right_shift(q2, k+1); + r1 = comp_mod(bi, k+1); + + /* do inner partial multiply */ + r2 = comp_mod(regular_multiply(ctx, q3, bim, k+1, 0), k+1); + r = bi_subtract(ctx, r1, r2, NULL); + + /* if (r >= m) r = r - m; */ + if (bi_compare(r, bim) >= 0) + { + + r = bi_subtract(ctx, r, bim, NULL); + } + + return r; +} +#endif /* CONFIG_BIGINT_BARRETT */ + +#ifdef CONFIG_BIGINT_SLIDING_WINDOW +/* + * Work out g1, g3, g5, g7... etc for the sliding-window algorithm + */ +static void precompute_slide_window(BI_CTX *ctx, int window, bigint *g1) +{ + int k = 1, i; + bigint *g2; + + for (i = 0; i < window-1; i++) /* compute 2^(window-1) */ + { + k <<= 1; + } + + ctx->g = (bigint **)malloc(k*sizeof(bigint *)); + ctx->g[0] = bi_clone(ctx, g1); + bi_permanent(ctx->g[0]); + g2 = bi_residue(ctx, bi_square(ctx, ctx->g[0])); /* g^2 */ + + for (i = 1; i < k; i++) + { + ctx->g[i] = bi_residue(ctx, bi_multiply(ctx, ctx->g[i-1], bi_copy(g2))); + bi_permanent(ctx->g[i]); + } + + bi_free(ctx, g2); + ctx->window = k; +} +#endif + +/** + * @brief Perform a modular exponentiation. + * + * This function requires bi_set_mod() to have been called previously. This is + * one of the optimisations used for performance. + * @param ctx [in] The bigint session context. + * @param bi [in] The bigint on which to perform the mod power operation. + * @param biexp [in] The bigint exponent. + * @return The result of the mod exponentiation operation + * @see bi_set_mod(). + */ +bigint *bi_mod_power(BI_CTX *ctx, bigint *bi, bigint *biexp) +{ + int i = find_max_exp_index(biexp), j, window_size = 1; + bigint *biR = int_to_bi(ctx, 1); + + +#if defined(CONFIG_BIGINT_MONTGOMERY) + uint8_t mod_offset = ctx->mod_offset; + if (!ctx->use_classical) + { + /* preconvert */ + bi = bi_mont(ctx, + bi_multiply(ctx, bi, ctx->bi_RR_mod_m[mod_offset])); /* x' */ + bi_free(ctx, biR); + biR = ctx->bi_R_mod_m[mod_offset]; /* A */ + } +#endif + + check(bi); + check(biexp); + +#ifdef CONFIG_BIGINT_SLIDING_WINDOW + for (j = i; j > 32; j /= 5) /* work out an optimum size */ + window_size++; + + /* work out the slide constants */ + precompute_slide_window(ctx, window_size, bi); +#else /* just one constant */ + ctx->g = (bigint **)malloc(sizeof(bigint *)); + ctx->g[0] = bi_clone(ctx, bi); + ctx->window = 1; + bi_permanent(ctx->g[0]); +#endif + + /* if sliding-window is off, then only one bit will be done at a time and + * will reduce to standard left-to-right exponentiation */ + do + { + if (exp_bit_is_one(biexp, i)) + { + int l = i-window_size+1; + int part_exp = 0; + + if (l < 0) /* LSB of exponent will always be 1 */ + l = 0; + else + { + while (exp_bit_is_one(biexp, l) == 0) + l++; /* go back up */ + } + /* build up the section of the exponent */ + for (j = i; j >= l; j--) + { + biR = bi_residue(ctx, bi_square(ctx, biR)); + if (exp_bit_is_one(biexp, j)) + part_exp++; + + if (j != l) + part_exp <<= 1; + } + part_exp = (part_exp-1)/2; /* adjust for array */ + bigint* a = bi_multiply(ctx, biR, ctx->g[part_exp]); + biR = bi_residue(ctx, a); + i = l-1; + } + else /* square it */ + { + biR = bi_residue(ctx, bi_square(ctx, biR)); + i--; + } + + } while (i >= 0); + + /* cleanup */ + for (i = 0; i < ctx->window; i++) + { + bi_depermanent(ctx->g[i]); + bi_free(ctx, ctx->g[i]); + } + + free(ctx->g); + bi_free(ctx, bi); + bi_free(ctx, biexp); +#if defined CONFIG_BIGINT_MONTGOMERY + return ctx->use_classical ? biR : bi_mont(ctx, biR); /* convert back */ +#else /* CONFIG_BIGINT_CLASSICAL or CONFIG_BIGINT_BARRETT */ + return biR; +#endif +} + +#ifdef CONFIG_SSL_CERT_VERIFICATION +/** + * @brief Perform a modular exponentiation using a temporary modulus. + * + * We need this function to check the signatures of certificates. The modulus + * of this function is temporary as it's just used for authentication. + * @param ctx [in] The bigint session context. + * @param bi [in] The bigint to perform the exp/mod. + * @param bim [in] The temporary modulus. + * @param biexp [in] The bigint exponent. + * @return The result of the mod exponentiation operation + * @see bi_set_mod(). + */ +bigint *bi_mod_power2(BI_CTX *ctx, bigint *bi, bigint *bim, bigint *biexp) +{ + bigint *biR, *tmp_biR; + + /* Set up a temporary bigint context and transfer what we need between + * them. We need to do this since we want to keep the original modulus + * which is already in this context. This operation is only called when + * doing peer verification, and so is not expensive :-) */ + BI_CTX *tmp_ctx = bi_initialize(); + bi_set_mod(tmp_ctx, bi_clone(tmp_ctx, bim), BIGINT_M_OFFSET); + tmp_biR = bi_mod_power(tmp_ctx, + bi_clone(tmp_ctx, bi), + bi_clone(tmp_ctx, biexp)); + biR = bi_clone(ctx, tmp_biR); + bi_free(tmp_ctx, tmp_biR); + bi_free_mod(tmp_ctx, BIGINT_M_OFFSET); + bi_terminate(tmp_ctx); + + bi_free(ctx, bi); + bi_free(ctx, bim); + bi_free(ctx, biexp); + return biR; +} +#endif + +#ifdef CONFIG_BIGINT_CRT +/** + * @brief Use the Chinese Remainder Theorem to quickly perform RSA decrypts. + * + * @param ctx [in] The bigint session context. + * @param bi [in] The bigint to perform the exp/mod. + * @param dP [in] CRT's dP bigint + * @param dQ [in] CRT's dQ bigint + * @param p [in] CRT's p bigint + * @param q [in] CRT's q bigint + * @param qInv [in] CRT's qInv bigint + * @return The result of the CRT operation + */ +bigint *bi_crt(BI_CTX *ctx, bigint *bi, + bigint *dP, bigint *dQ, + bigint *p, bigint *q, bigint *qInv) +{ + bigint *m1, *m2, *h; + + /* Montgomery has a condition the 0 < x, y < m and these products violate + * that condition. So disable Montgomery when using CRT */ +#if defined(CONFIG_BIGINT_MONTGOMERY) + ctx->use_classical = 1; +#endif + ctx->mod_offset = BIGINT_P_OFFSET; + m1 = bi_mod_power(ctx, bi_copy(bi), dP); + + ctx->mod_offset = BIGINT_Q_OFFSET; + m2 = bi_mod_power(ctx, bi, dQ); + + h = bi_subtract(ctx, bi_add(ctx, m1, p), bi_copy(m2), NULL); + h = bi_multiply(ctx, h, qInv); + ctx->mod_offset = BIGINT_P_OFFSET; + h = bi_residue(ctx, h); +#if defined(CONFIG_BIGINT_MONTGOMERY) + ctx->use_classical = 0; /* reset for any further operation */ +#endif + return bi_add(ctx, m2, bi_multiply(ctx, q, h)); +} +#endif +/** @} */ diff --git a/features/unsupported/net/https/axTLS/crypto/bigint.h b/features/unsupported/net/https/axTLS/crypto/bigint.h new file mode 100644 index 00000000000..2966a3edb3c --- /dev/null +++ b/features/unsupported/net/https/axTLS/crypto/bigint.h @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2007, Cameron Rich + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * * Neither the name of the axTLS project nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef BIGINT_HEADER +#define BIGINT_HEADER + +#include "crypto.h" + +BI_CTX *bi_initialize(void); +void bi_terminate(BI_CTX *ctx); +void bi_permanent(bigint *bi); +void bi_depermanent(bigint *bi); +void bi_clear_cache(BI_CTX *ctx); +void bi_free(BI_CTX *ctx, bigint *bi); +bigint *bi_copy(bigint *bi); +bigint *bi_clone(BI_CTX *ctx, const bigint *bi); +void bi_export(BI_CTX *ctx, bigint *bi, uint8_t *data, int size); +bigint *bi_import(BI_CTX *ctx, const uint8_t *data, int len); +bigint *int_to_bi(BI_CTX *ctx, comp i); + +/* the functions that actually do something interesting */ +bigint *bi_add(BI_CTX *ctx, bigint *bia, bigint *bib); +bigint *bi_subtract(BI_CTX *ctx, bigint *bia, + bigint *bib, int *is_negative); +bigint *bi_divide(BI_CTX *ctx, bigint *bia, bigint *bim, int is_mod); +bigint *bi_multiply(BI_CTX *ctx, bigint *bia, bigint *bib); +bigint *bi_mod_power(BI_CTX *ctx, bigint *bi, bigint *biexp); +bigint *bi_mod_power2(BI_CTX *ctx, bigint *bi, bigint *bim, bigint *biexp); +int bi_compare(bigint *bia, bigint *bib); +void bi_set_mod(BI_CTX *ctx, bigint *bim, int mod_offset); +void bi_free_mod(BI_CTX *ctx, int mod_offset); + +#ifdef CONFIG_SSL_FULL_MODE +void bi_print(const char *label, bigint *bi); +bigint *bi_str_import(BI_CTX *ctx, const char *data); +#endif + +/** + * @def bi_mod + * Find the residue of B. bi_set_mod() must be called before hand. + */ +#define bi_mod(A, B) bi_divide(A, B, ctx->bi_mod[ctx->mod_offset], 1) + +/** + * bi_residue() is technically the same as bi_mod(), but it uses the + * appropriate reduction technique (which is bi_mod() when doing classical + * reduction). + */ +#if defined(CONFIG_BIGINT_MONTGOMERY) +#define bi_residue(A, B) bi_mont(A, B) +bigint *bi_mont(BI_CTX *ctx, bigint *bixy); +#elif defined(CONFIG_BIGINT_BARRETT) +#define bi_residue(A, B) bi_barrett(A, B) +bigint *bi_barrett(BI_CTX *ctx, bigint *bi); +#else /* if defined(CONFIG_BIGINT_CLASSICAL) */ +#define bi_residue(A, B) bi_mod(A, B) +#endif + +#ifdef CONFIG_BIGINT_SQUARE +bigint *bi_square(BI_CTX *ctx, bigint *bi); +#else +#define bi_square(A, B) bi_multiply(A, bi_copy(B), B) +#endif + +#ifdef CONFIG_BIGINT_CRT +bigint *bi_crt(BI_CTX *ctx, bigint *bi, + bigint *dP, bigint *dQ, + bigint *p, bigint *q, + bigint *qInv); +#endif + +#endif diff --git a/features/unsupported/net/https/axTLS/crypto/bigint_impl.h b/features/unsupported/net/https/axTLS/crypto/bigint_impl.h new file mode 100644 index 00000000000..b9fc2ae24ad --- /dev/null +++ b/features/unsupported/net/https/axTLS/crypto/bigint_impl.h @@ -0,0 +1,133 @@ +/* + * Copyright (c) 2007, Cameron Rich + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * * Neither the name of the axTLS project nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef BIGINT_IMPL_HEADER +#define BIGINT_IMPL_HEADER + +/* Maintain a number of precomputed variables when doing reduction */ +#define BIGINT_M_OFFSET 0 /**< Normal modulo offset. */ +#ifdef CONFIG_BIGINT_CRT +#define BIGINT_P_OFFSET 1 /**< p modulo offset. */ +#define BIGINT_Q_OFFSET 2 /**< q module offset. */ +#define BIGINT_NUM_MODS 3 /**< The number of modulus constants used. */ +#else +#define BIGINT_NUM_MODS 1 +#endif + + +/* Architecture specific functions for big ints */ +#if defined(CONFIG_INTEGER_8BIT) +#define COMP_RADIX 256U /**< Max component + 1 */ +#define COMP_MAX 0xFFFFU/**< (Max dbl comp -1) */ +#define COMP_BIT_SIZE 8 /**< Number of bits in a component. */ +#define COMP_BYTE_SIZE 1 /**< Number of bytes in a component. */ +#define COMP_NUM_NIBBLES 2 /**< Used For diagnostics only. */ +typedef uint8_t comp; /**< A single precision component. */ +typedef uint16_t long_comp; /**< A double precision component. */ +typedef int16_t slong_comp; /**< A signed double precision component. */ +#elif defined(CONFIG_INTEGER_16BIT) +#define COMP_RADIX 65536U /**< Max component + 1 */ +#define COMP_MAX 0xFFFFFFFFU/**< (Max dbl comp -1) */ +#define COMP_BIT_SIZE 16 /**< Number of bits in a component. */ +#define COMP_BYTE_SIZE 2 /**< Number of bytes in a component. */ +#define COMP_NUM_NIBBLES 4 /**< Used For diagnostics only. */ +typedef uint16_t comp; /**< A single precision component. */ +typedef uint32_t long_comp; /**< A double precision component. */ +typedef int32_t slong_comp; /**< A signed double precision component. */ +#else /* regular 32 bit */ +#ifdef WIN32 +#define COMP_RADIX 4294967296i64 +#define COMP_MAX 0xFFFFFFFFFFFFFFFFui64 +#else +#define COMP_RADIX 4294967296ULL /**< Max component + 1 */ +#define COMP_MAX 0xFFFFFFFFFFFFFFFFULL/**< (Max dbl comp -1) */ +#endif +#define COMP_BIT_SIZE 32 /**< Number of bits in a component. */ +#define COMP_BYTE_SIZE 4 /**< Number of bytes in a component. */ +#define COMP_NUM_NIBBLES 8 /**< Used For diagnostics only. */ +#include +typedef uint32_t comp; /**< A single precision component. */ +typedef uint64_t long_comp; /**< A double precision component. */ +typedef int64_t slong_comp; /**< A signed double precision component. */ +#endif + +/** + * @struct _bigint + * @brief A big integer basic object + */ +struct _bigint +{ + struct _bigint* next; /**< The next bigint in the cache. */ + short size; /**< The number of components in this bigint. */ + short max_comps; /**< The heapsize allocated for this bigint */ + int refs; /**< An internal reference count. */ + comp* comps; /**< A ptr to the actual component data */ +}; + +typedef struct _bigint bigint; /**< An alias for _bigint */ + +/** + * Maintains the state of the cache, and a number of variables used in + * reduction. + */ +typedef struct /**< A big integer "session" context. */ +{ + bigint *active_list; /**< Bigints currently used. */ + bigint *free_list; /**< Bigints not used. */ + bigint *bi_radix; /**< The radix used. */ + bigint *bi_mod[BIGINT_NUM_MODS]; /**< modulus */ + +#if defined(CONFIG_BIGINT_MONTGOMERY) + bigint *bi_RR_mod_m[BIGINT_NUM_MODS]; /**< R^2 mod m */ + bigint *bi_R_mod_m[BIGINT_NUM_MODS]; /**< R mod m */ + comp N0_dash[BIGINT_NUM_MODS]; +#elif defined(CONFIG_BIGINT_BARRETT) + bigint *bi_mu[BIGINT_NUM_MODS]; /**< Storage for mu */ +#endif + bigint *bi_normalised_mod[BIGINT_NUM_MODS]; /**< Normalised mod storage. */ + bigint **g; /**< Used by sliding-window. */ + int window; /**< The size of the sliding window */ + int active_count; /**< Number of active bigints. */ + int free_count; /**< Number of free bigints. */ + +#ifdef CONFIG_BIGINT_MONTGOMERY + uint8_t use_classical; /**< Use classical reduction. */ +#endif + uint8_t mod_offset; /**< The mod offset we are using */ +} BI_CTX; + +#ifndef WIN32 +#define max(a,b) ((a)>(b)?(a):(b)) /**< Find the maximum of 2 numbers. */ +#define min(a,b) ((a)<(b)?(a):(b)) /**< Find the minimum of 2 numbers. */ +#endif + +#define PERMANENT 0x7FFF55AA /**< A magic number for permanents. */ + +#endif diff --git a/features/unsupported/net/https/axTLS/crypto/crypto.h b/features/unsupported/net/https/axTLS/crypto/crypto.h new file mode 100644 index 00000000000..3f32e614244 --- /dev/null +++ b/features/unsupported/net/https/axTLS/crypto/crypto.h @@ -0,0 +1,229 @@ +/* + * Copyright (c) 2007, Cameron Rich + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * * Neither the name of the axTLS project nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @file crypto.h + */ + +#ifndef HEADER_CRYPTO_H +#define HEADER_CRYPTO_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include "bigint_impl.h" +#include "bigint.h" + +#ifndef STDCALL +#define STDCALL +#endif +#ifndef EXP_FUNC +#define EXP_FUNC +#endif + + +/* enable features based on a 'super-set' capbaility. */ +#if defined(CONFIG_SSL_FULL_MODE) +#define CONFIG_SSL_ENABLE_CLIENT +#define CONFIG_SSL_CERT_VERIFICATION +#elif defined(CONFIG_SSL_ENABLE_CLIENT) +#define CONFIG_SSL_CERT_VERIFICATION +#endif + +/************************************************************************** + * AES declarations + **************************************************************************/ + +#define AES_MAXROUNDS 14 +#define AES_BLOCKSIZE 16 +#define AES_IV_SIZE 16 + +typedef struct aes_key_st +{ + uint16_t rounds; + uint16_t key_size; + uint32_t ks[(AES_MAXROUNDS+1)*8]; + uint8_t iv[AES_IV_SIZE]; +} AES_CTX; + +typedef enum +{ + AES_MODE_128, + AES_MODE_256 +} AES_MODE; + +void AES_set_key(AES_CTX *ctx, const uint8_t *key, + const uint8_t *iv, AES_MODE mode); +void AES_cbc_encrypt(AES_CTX *ctx, const uint8_t *msg, + uint8_t *out, int length); +void AES_cbc_decrypt(AES_CTX *ks, const uint8_t *in, uint8_t *out, int length); +void AES_convert_key(AES_CTX *ctx); + +/************************************************************************** + * RC4 declarations + **************************************************************************/ + +typedef struct +{ + uint8_t x, y, m[256]; +} RC4_CTX; + +void RC4_setup(RC4_CTX *s, const uint8_t *key, int length); +void RC4_crypt(RC4_CTX *s, const uint8_t *msg, uint8_t *data, int length); + +/************************************************************************** + * SHA1 declarations + **************************************************************************/ + +#define SHA1_SIZE 20 + +/* + * This structure will hold context information for the SHA-1 + * hashing operation + */ +typedef struct +{ + uint32_t Intermediate_Hash[SHA1_SIZE/4]; /* Message Digest */ + uint32_t Length_Low; /* Message length in bits */ + uint32_t Length_High; /* Message length in bits */ + uint16_t Message_Block_Index; /* Index into message block array */ + uint8_t Message_Block[64]; /* 512-bit message blocks */ +} SHA1_CTX; + +void SHA1_Init(SHA1_CTX *); +void SHA1_Update(SHA1_CTX *, const uint8_t * msg, int len); +void SHA1_Final(uint8_t *digest, SHA1_CTX *); + +/************************************************************************** + * MD2 declarations + **************************************************************************/ + +#define MD2_SIZE 16 + +typedef struct +{ + unsigned char cksum[16]; /* checksum of the data block */ + unsigned char state[48]; /* intermediate digest state */ + unsigned char buffer[16]; /* data block being processed */ + int left; /* amount of data in buffer */ +} MD2_CTX; + +EXP_FUNC void STDCALL MD2_Init(MD2_CTX *ctx); +EXP_FUNC void STDCALL MD2_Update(MD2_CTX *ctx, const uint8_t *input, int ilen); +EXP_FUNC void STDCALL MD2_Final(uint8_t *digest, MD2_CTX *ctx); + +/************************************************************************** + * MD5 declarations + **************************************************************************/ + +#define MD5_SIZE 16 +#define MAX_KEYBLOCK_SIZE 136 +typedef struct +{ + uint32_t state[4]; /* state (ABCD) */ + uint32_t count[2]; /* number of bits, modulo 2^64 (lsb first) */ + uint8_t buffer[64]; /* input buffer */ +} MD5_CTX; + +EXP_FUNC void STDCALL MD5_Init(MD5_CTX *); +EXP_FUNC void STDCALL MD5_Update(MD5_CTX *, const uint8_t *msg, int len); +EXP_FUNC void STDCALL MD5_Final(uint8_t *digest, MD5_CTX *); + +/************************************************************************** + * HMAC declarations + **************************************************************************/ +void hmac_md5(const uint8_t *msg, int length, const uint8_t *key, + int key_len, uint8_t *digest); +void hmac_sha1(const uint8_t *msg, int length, const uint8_t *key, + int key_len, uint8_t *digest); + +/************************************************************************** + * RSA declarations + **************************************************************************/ + +typedef struct +{ + bigint *m; /* modulus */ + bigint *e; /* public exponent */ + bigint *d; /* private exponent */ +#ifdef CONFIG_BIGINT_CRT + bigint *p; /* p as in m = pq */ + bigint *q; /* q as in m = pq */ + bigint *dP; /* d mod (p-1) */ + bigint *dQ; /* d mod (q-1) */ + bigint *qInv; /* q^-1 mod p */ +#endif + int num_octets; + BI_CTX *bi_ctx; +} RSA_CTX; + +void RSA_priv_key_new(RSA_CTX **rsa_ctx, + const uint8_t *modulus, int mod_len, + const uint8_t *pub_exp, int pub_len, + const uint8_t *priv_exp, int priv_len +#ifdef CONFIG_BIGINT_CRT + , const uint8_t *p, int p_len, + const uint8_t *q, int q_len, + const uint8_t *dP, int dP_len, + const uint8_t *dQ, int dQ_len, + const uint8_t *qInv, int qInv_len +#endif + ); +void RSA_pub_key_new(RSA_CTX **rsa_ctx, + const uint8_t *modulus, int mod_len, + const uint8_t *pub_exp, int pub_len); +void RSA_free(RSA_CTX *ctx); +int RSA_decrypt(const RSA_CTX *ctx, const uint8_t *in_data, uint8_t *out_data, + int is_decryption); +bigint *RSA_private(const RSA_CTX *c, bigint *bi_msg); +#if defined(CONFIG_SSL_CERT_VERIFICATION) || defined(CONFIG_SSL_GENERATE_X509_CERT) +bigint *RSA_sign_verify(BI_CTX *ctx, const uint8_t *sig, int sig_len, + bigint *modulus, bigint *pub_exp); +bigint *RSA_public(const RSA_CTX * c, bigint *bi_msg); +int RSA_encrypt(const RSA_CTX *ctx, const uint8_t *in_data, uint16_t in_len, + uint8_t *out_data, int is_signing); +void RSA_print(const RSA_CTX *ctx); +#endif + +/************************************************************************** + * RNG declarations + **************************************************************************/ +EXP_FUNC void STDCALL RNG_initialize(void); +EXP_FUNC void STDCALL RNG_custom_init(const uint8_t *seed_buf, int size); +EXP_FUNC void STDCALL RNG_terminate(void); +EXP_FUNC void STDCALL get_random(int num_rand_bytes, uint8_t *rand_data); +void get_random_NZ(int num_rand_bytes, uint8_t *rand_data); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/features/unsupported/net/https/axTLS/crypto/crypto_misc.c b/features/unsupported/net/https/axTLS/crypto/crypto_misc.c new file mode 100644 index 00000000000..0f9d3dcbfd8 --- /dev/null +++ b/features/unsupported/net/https/axTLS/crypto/crypto_misc.c @@ -0,0 +1,375 @@ +/* + * Copyright (c) 2007, Cameron Rich + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * * Neither the name of the axTLS project nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * Some misc. routines to help things out + */ + +#include +#include +#include +#include +#include "os_port.h" +#include +#include "sockets.h" +#include "crypto_misc.h" +#include "config.h" + +#include +#ifdef CONFIG_WIN32_USE_CRYPTO_LIB +#include "wincrypt.h" +#endif + +#ifndef WIN32 +static int rng_fd = -1; +#elif defined(CONFIG_WIN32_USE_CRYPTO_LIB) +static HCRYPTPROV gCryptProv; +#endif + +#if (!defined(CONFIG_USE_DEV_URANDOM) && !defined(CONFIG_WIN32_USE_CRYPTO_LIB)) +/* change to processor registers as appropriate */ +#define ENTROPY_POOL_SIZE 32 +#define ENTROPY_COUNTER1 ((((uint64_t)tv.tv_sec)<<32) | tv.tv_usec) +#define ENTROPY_COUNTER2 rand() +static uint8_t entropy_pool[ENTROPY_POOL_SIZE]; +#endif + +const char * const unsupported_str = "Error: Feature not supported\n"; + +#ifndef CONFIG_SSL_SKELETON_MODE +/** + * Retrieve a file and put it into memory + * @return The size of the file, or -1 on failure. + */ +int get_file(const char *filename, uint8_t **buf) +{ + int total_bytes = 0; + int bytes_read = 0; + int filesize; + FILE *stream = fopen(filename, "rb"); + + if (stream == NULL) + { +#ifdef CONFIG_SSL_FULL_MODE + printf("file '%s' does not exist\n", filename); TTY_FLUSH(); +#endif + return -1; + } + + /* Win CE doesn't support stat() */ + fseek(stream, 0, SEEK_END); + filesize = ftell(stream); + *buf = (uint8_t *)malloc(filesize); + fseek(stream, 0, SEEK_SET); + + do + { + bytes_read = fread(*buf+total_bytes, 1, filesize-total_bytes, stream); + total_bytes += bytes_read; + } while (total_bytes < filesize && bytes_read > 0); + + fclose(stream); + return filesize; +} +#endif + +/** + * Initialise the Random Number Generator engine. + * - On Win32 use the platform SDK's crypto engine. + * - On Linux use /dev/urandom + * - If none of these work then use a custom RNG. + */ +EXP_FUNC void STDCALL RNG_initialize() +{ +#if !defined(WIN32) && defined(CONFIG_USE_DEV_URANDOM) + rng_fd = ax_open("/dev/urandom", O_RDONLY); +#elif defined(WIN32) && defined(CONFIG_WIN32_USE_CRYPTO_LIB) + if (!CryptAcquireContext(&gCryptProv, + NULL, NULL, PROV_RSA_FULL, 0)) + { + if (GetLastError() == NTE_BAD_KEYSET && + !CryptAcquireContext(&gCryptProv, + NULL, + NULL, + PROV_RSA_FULL, + CRYPT_NEWKEYSET)) + { + printf("CryptoLib: %x\n", unsupported_str, GetLastError()); + exit(1); + } + } +#else + /* start of with a stack to copy across */ + int i; + memcpy(entropy_pool, &i, ENTROPY_POOL_SIZE); + srand((unsigned int)&i); +#endif +} + +/** + * If no /dev/urandom, then initialise the RNG with something interesting. + */ +EXP_FUNC void STDCALL RNG_custom_init(const uint8_t *seed_buf, int size) +{ +#if defined(WIN32) || defined(CONFIG_WIN32_USE_CRYPTO_LIB) + int i; + + for (i = 0; i < ENTROPY_POOL_SIZE && i < size; i++) + entropy_pool[i] ^= seed_buf[i]; +#endif +} + +/** + * Terminate the RNG engine. + */ +EXP_FUNC void STDCALL RNG_terminate(void) +{ +#ifndef WIN32 + //close(rng_fd); +#elif defined(CONFIG_WIN32_USE_CRYPTO_LIB) + CryptReleaseContext(gCryptProv, 0); +#endif +} + +/** + * Set a series of bytes with a random number. Individual bytes can be 0 + */ +EXP_FUNC void STDCALL get_random(int num_rand_bytes, uint8_t *rand_data) +{ +#if !defined(WIN32) && defined(CONFIG_USE_DEV_URANDOM) + /* use the Linux default */ + read(rng_fd, rand_data, num_rand_bytes); /* read from /dev/urandom */ +#elif defined(WIN32) && defined(CONFIG_WIN32_USE_CRYPTO_LIB) + /* use Microsoft Crypto Libraries */ + CryptGenRandom(gCryptProv, num_rand_bytes, rand_data); +#else /* nothing else to use, so use a custom RNG */ + /* The method we use when we've got nothing better. Use RC4, time + and a couple of random seeds to generate a random sequence */ + RC4_CTX rng_ctx; + struct timeval tv; + MD5_CTX rng_digest_ctx; + uint8_t digest[MD5_SIZE]; + uint64_t *ep; + int i; + + /* A proper implementation would use counters etc for entropy */ + // XXX XXX XX X need to seed this properly + gettimeofday(&tv, NULL); + ep = (uint64_t *)entropy_pool; + + ep[0] ^= ENTROPY_COUNTER1; + ep[1] ^= ENTROPY_COUNTER2; + + + /* use a digested version of the entropy pool as a key */ + MD5_Init(&rng_digest_ctx); + MD5_Update(&rng_digest_ctx, entropy_pool, ENTROPY_POOL_SIZE); + MD5_Final(digest, &rng_digest_ctx); + + /* come up with the random sequence */ + RC4_setup(&rng_ctx, digest, MD5_SIZE); /* use as a key */ + memcpy(rand_data, entropy_pool, num_rand_bytes < ENTROPY_POOL_SIZE ? + num_rand_bytes : ENTROPY_POOL_SIZE); + RC4_crypt(&rng_ctx, rand_data, rand_data, num_rand_bytes); + + /* move things along */ + for (i = ENTROPY_POOL_SIZE-1; i >= MD5_SIZE ; i--) + entropy_pool[i] = entropy_pool[i-MD5_SIZE]; + + /* insert the digest at the start of the entropy pool */ + memcpy(entropy_pool, digest, MD5_SIZE); +#endif +} + +/** + * Set a series of bytes with a random number. Individual bytes are not zero. + */ +void get_random_NZ(int num_rand_bytes, uint8_t *rand_data) +{ + int i; + get_random(num_rand_bytes, rand_data); + + for (i = 0; i < num_rand_bytes; i++) + { + while (rand_data[i] == 0) /* can't be 0 */ + rand_data[i] = (uint8_t)(rand()); + } +} + +/** + * Some useful diagnostic routines + */ +#if defined(CONFIG_SSL_FULL_MODE) || defined(CONFIG_DEBUG) +int hex_finish; +int hex_index; + +static void print_hex_init(int finish) +{ + hex_finish = finish; + hex_index = 0; +} + +static void print_hex(uint8_t hex) +{ + static int column; + + if (hex_index == 0) + { + column = 0; + } + + printf("%02x ", hex); + if (++column == 8) + { + printf(": "); + } + else if (column >= 16) + { + printf("\r\n"); + column = 0; + } + + if (++hex_index >= hex_finish && column > 0) + { + printf("\r\n"); + } +} + +/** + * Spit out a blob of data for diagnostics. The data is is a nice column format + * for easy reading. + * + * @param format [in] The string (with possible embedded format characters) + * @param size [in] The number of numbers to print + * @param data [in] The start of data to use + * @param ... [in] Any additional arguments + */ +EXP_FUNC void STDCALL print_blob(const char *format, + const uint8_t *data, int size, ...) +{ + int i; + char tmp[80]; + va_list(ap); + + va_start(ap, size); + sprintf(tmp, "%s\n", format); + vprintf(tmp, ap); + print_hex_init(size); + for (i = 0; i < size; i++) + { + print_hex(data[i]); + } + + va_end(ap); + TTY_FLUSH(); +} +#elif defined(WIN32) +/* VC6.0 doesn't handle variadic macros */ +EXP_FUNC void STDCALL print_blob(const char *format, const unsigned char *data, + int size, ...) {} +#endif + +#if defined(CONFIG_SSL_HAS_PEM) || defined(CONFIG_HTTP_HAS_AUTHORIZATION) +/* base64 to binary lookup table */ +static const uint8_t map[128] = +{ + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 62, 255, 255, 255, 63, + 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 255, 255, + 255, 254, 255, 255, 255, 0, 1, 2, 3, 4, 5, 6, + 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, + 19, 20, 21, 22, 23, 24, 25, 255, 255, 255, 255, 255, + 255, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, + 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, + 49, 50, 51, 255, 255, 255, 255, 255 +}; + +EXP_FUNC int STDCALL base64_decode(const char *in, int len, + uint8_t *out, int *outlen) +{ + int g, t, x, y, z; + uint8_t c; + int ret = -1; + + g = 3; + for (x = y = z = t = 0; x < len; x++) + { + if ((c = map[in[x]&0x7F]) == 0xff) + continue; + + if (c == 254) /* this is the end... */ + { + c = 0; + + if (--g < 0) + goto error; + } + else if (g != 3) /* only allow = at end */ + goto error; + + t = (t<<6) | c; + + if (++y == 4) + { + out[z++] = (uint8_t)((t>>16)&255); + + if (g > 1) + out[z++] = (uint8_t)((t>>8)&255); + + if (g > 2) + out[z++] = (uint8_t)(t&255); + + y = t = 0; + } + + /* check that we don't go past the output buffer */ + if (z > *outlen) + goto error; + } + + if (y != 0) + goto error; + + *outlen = z; + ret = 0; + +error: +#ifdef CONFIG_SSL_FULL_MODE + if (ret < 0) + printf("Error: Invalid base64\n"); TTY_FLUSH(); +#endif + TTY_FLUSH(); + return ret; + +} +#endif + diff --git a/features/unsupported/net/https/axTLS/crypto/hmac.c b/features/unsupported/net/https/axTLS/crypto/hmac.c new file mode 100644 index 00000000000..24a04d77aee --- /dev/null +++ b/features/unsupported/net/https/axTLS/crypto/hmac.c @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2007, Cameron Rich + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * * Neither the name of the axTLS project nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * HMAC implementation - This code was originally taken from RFC2104 + * See http://www.ietf.org/rfc/rfc2104.txt and + * http://www.faqs.org/rfcs/rfc2202.html + */ + +#include +#include "os_port.h" +#include "crypto.h" + +/** + * Perform HMAC-MD5 + * NOTE: does not handle keys larger than the block size. + */ +void hmac_md5(const uint8_t *msg, int length, const uint8_t *key, + int key_len, uint8_t *digest) +{ + MD5_CTX context; + uint8_t k_ipad[64]; + uint8_t k_opad[64]; + int i; + + memset(k_ipad, 0, sizeof k_ipad); + memset(k_opad, 0, sizeof k_opad); + memcpy(k_ipad, key, key_len); + memcpy(k_opad, key, key_len); + + for (i = 0; i < 64; i++) + { + k_ipad[i] ^= 0x36; + k_opad[i] ^= 0x5c; + } + + MD5_Init(&context); + MD5_Update(&context, k_ipad, 64); + MD5_Update(&context, msg, length); + MD5_Final(digest, &context); + MD5_Init(&context); + MD5_Update(&context, k_opad, 64); + MD5_Update(&context, digest, MD5_SIZE); + MD5_Final(digest, &context); +} + +/** + * Perform HMAC-SHA1 + * NOTE: does not handle keys larger than the block size. + */ +void hmac_sha1(const uint8_t *msg, int length, const uint8_t *key, + int key_len, uint8_t *digest) +{ + SHA1_CTX context; + uint8_t k_ipad[64]; + uint8_t k_opad[64]; + int i; + + memset(k_ipad, 0, sizeof k_ipad); + memset(k_opad, 0, sizeof k_opad); + memcpy(k_ipad, key, key_len); + memcpy(k_opad, key, key_len); + + for (i = 0; i < 64; i++) + { + k_ipad[i] ^= 0x36; + k_opad[i] ^= 0x5c; + } + + SHA1_Init(&context); + SHA1_Update(&context, k_ipad, 64); + SHA1_Update(&context, msg, length); + SHA1_Final(digest, &context); + SHA1_Init(&context); + SHA1_Update(&context, k_opad, 64); + SHA1_Update(&context, digest, SHA1_SIZE); + SHA1_Final(digest, &context); +} diff --git a/features/unsupported/net/https/axTLS/crypto/md2.c b/features/unsupported/net/https/axTLS/crypto/md2.c new file mode 100644 index 00000000000..0df38c9ebac --- /dev/null +++ b/features/unsupported/net/https/axTLS/crypto/md2.c @@ -0,0 +1,163 @@ +/* + * Copyright (c) 2007, Cameron Rich + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * * Neither the name of the axTLS project nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/* + * RFC 1115/1319 compliant MD2 implementation + * The MD2 algorithm was designed by Ron Rivest in 1989. + * + * http://www.ietf.org/rfc/rfc1115.txt + * http://www.ietf.org/rfc/rfc1319.txt + */ + +#include +#include +#include "os_port.h" +#include "crypto.h" +#include "config.h" + +/** + * This code is only here to enable the verification of Verisign root + * certificates. So only enable it for verification mode. + */ +#ifdef CONFIG_SSL_CERT_VERIFICATION + +static const uint8_t PI_SUBST[256] = +{ + 0x29, 0x2E, 0x43, 0xC9, 0xA2, 0xD8, 0x7C, 0x01, 0x3D, 0x36, + 0x54, 0xA1, 0xEC, 0xF0, 0x06, 0x13, 0x62, 0xA7, 0x05, 0xF3, + 0xC0, 0xC7, 0x73, 0x8C, 0x98, 0x93, 0x2B, 0xD9, 0xBC, 0x4C, + 0x82, 0xCA, 0x1E, 0x9B, 0x57, 0x3C, 0xFD, 0xD4, 0xE0, 0x16, + 0x67, 0x42, 0x6F, 0x18, 0x8A, 0x17, 0xE5, 0x12, 0xBE, 0x4E, + 0xC4, 0xD6, 0xDA, 0x9E, 0xDE, 0x49, 0xA0, 0xFB, 0xF5, 0x8E, + 0xBB, 0x2F, 0xEE, 0x7A, 0xA9, 0x68, 0x79, 0x91, 0x15, 0xB2, + 0x07, 0x3F, 0x94, 0xC2, 0x10, 0x89, 0x0B, 0x22, 0x5F, 0x21, + 0x80, 0x7F, 0x5D, 0x9A, 0x5A, 0x90, 0x32, 0x27, 0x35, 0x3E, + 0xCC, 0xE7, 0xBF, 0xF7, 0x97, 0x03, 0xFF, 0x19, 0x30, 0xB3, + 0x48, 0xA5, 0xB5, 0xD1, 0xD7, 0x5E, 0x92, 0x2A, 0xAC, 0x56, + 0xAA, 0xC6, 0x4F, 0xB8, 0x38, 0xD2, 0x96, 0xA4, 0x7D, 0xB6, + 0x76, 0xFC, 0x6B, 0xE2, 0x9C, 0x74, 0x04, 0xF1, 0x45, 0x9D, + 0x70, 0x59, 0x64, 0x71, 0x87, 0x20, 0x86, 0x5B, 0xCF, 0x65, + 0xE6, 0x2D, 0xA8, 0x02, 0x1B, 0x60, 0x25, 0xAD, 0xAE, 0xB0, + 0xB9, 0xF6, 0x1C, 0x46, 0x61, 0x69, 0x34, 0x40, 0x7E, 0x0F, + 0x55, 0x47, 0xA3, 0x23, 0xDD, 0x51, 0xAF, 0x3A, 0xC3, 0x5C, + 0xF9, 0xCE, 0xBA, 0xC5, 0xEA, 0x26, 0x2C, 0x53, 0x0D, 0x6E, + 0x85, 0x28, 0x84, 0x09, 0xD3, 0xDF, 0xCD, 0xF4, 0x41, 0x81, + 0x4D, 0x52, 0x6A, 0xDC, 0x37, 0xC8, 0x6C, 0xC1, 0xAB, 0xFA, + 0x24, 0xE1, 0x7B, 0x08, 0x0C, 0xBD, 0xB1, 0x4A, 0x78, 0x88, + 0x95, 0x8B, 0xE3, 0x63, 0xE8, 0x6D, 0xE9, 0xCB, 0xD5, 0xFE, + 0x3B, 0x00, 0x1D, 0x39, 0xF2, 0xEF, 0xB7, 0x0E, 0x66, 0x58, + 0xD0, 0xE4, 0xA6, 0x77, 0x72, 0xF8, 0xEB, 0x75, 0x4B, 0x0A, + 0x31, 0x44, 0x50, 0xB4, 0x8F, 0xED, 0x1F, 0x1A, 0xDB, 0x99, + 0x8D, 0x33, 0x9F, 0x11, 0x83, 0x14 +}; + +/* + * MD2 context setup + */ +EXP_FUNC void STDCALL MD2_Init(MD2_CTX *ctx) +{ + memset(ctx, 0, sizeof *ctx); +} + +static void md2_process(MD2_CTX *ctx) +{ + int i, j; + uint8_t t = 0; + + for (i = 0; i < 16; i++) + { + ctx->state[i + 16] = ctx->buffer[i]; + ctx->state[i + 32] = ctx->buffer[i] ^ ctx->state[i]; + } + + for (i = 0; i < 18; i++) + { + for (j = 0; j < 48; j++) + t = (ctx->state[j] ^= PI_SUBST[t]); + + t = (t + i) & 0xFF; + } + + t = ctx->cksum[15]; + + for (i = 0; i < 16; i++) + t = (ctx->cksum[i] ^= PI_SUBST[ctx->buffer[i] ^ t]); +} + +/* + * MD2 process buffer + */ +EXP_FUNC void STDCALL MD2_Update(MD2_CTX *ctx, const uint8_t *input, int ilen) +{ + int fill; + + while (ilen > 0) + { + if (ctx->left + ilen > 16) + fill = 16 - ctx->left; + else + fill = ilen; + + memcpy(ctx->buffer + ctx->left, input, fill); + + ctx->left += fill; + input += fill; + ilen -= fill; + + if (ctx->left == 16) + { + ctx->left = 0; + md2_process(ctx); + } + } +} + +/* + * MD2 final digest + */ +EXP_FUNC void STDCALL MD2_Final(uint8_t *output, MD2_CTX *ctx) +{ + int i; + uint8_t x; + + x = (uint8_t)(16 - ctx->left); + + for (i = ctx->left; i < 16; i++) + ctx->buffer[i] = x; + + md2_process(ctx); + + memcpy(ctx->buffer, ctx->cksum, 16); + md2_process(ctx); + + memcpy(output, ctx->state, 16); +} + +#endif diff --git a/features/unsupported/net/https/axTLS/crypto/md5.c b/features/unsupported/net/https/axTLS/crypto/md5.c new file mode 100644 index 00000000000..7f507130065 --- /dev/null +++ b/features/unsupported/net/https/axTLS/crypto/md5.c @@ -0,0 +1,294 @@ +/* + * Copyright (c) 2007, Cameron Rich + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * * Neither the name of the axTLS project nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * This file implements the MD5 algorithm as defined in RFC1321 + */ + +#include +#include "os_port.h" +#include "crypto.h" + +/* Constants for MD5Transform routine. + */ +#define S11 7 +#define S12 12 +#define S13 17 +#define S14 22 +#define S21 5 +#define S22 9 +#define S23 14 +#define S24 20 +#define S31 4 +#define S32 11 +#define S33 16 +#define S34 23 +#define S41 6 +#define S42 10 +#define S43 15 +#define S44 21 + +/* ----- static functions ----- */ +static void MD5Transform(uint32_t state[4], const uint8_t block[64]); +static void Encode(uint8_t *output, uint32_t *input, uint32_t len); +static void Decode(uint32_t *output, const uint8_t *input, uint32_t len); + +static const uint8_t PADDING[64] = +{ + 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 +}; + +/* F, G, H and I are basic MD5 functions. + */ +#define F(x, y, z) (((x) & (y)) | ((~x) & (z))) +#define G(x, y, z) (((x) & (z)) | ((y) & (~z))) +#define H(x, y, z) ((x) ^ (y) ^ (z)) +#define I(x, y, z) ((y) ^ ((x) | (~z))) + +/* ROTATE_LEFT rotates x left n bits. */ +#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32-(n)))) + +/* FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4. + Rotation is separate from addition to prevent recomputation. */ +#define FF(a, b, c, d, x, s, ac) { \ + (a) += F ((b), (c), (d)) + (x) + (uint32_t)(ac); \ + (a) = ROTATE_LEFT ((a), (s)); \ + (a) += (b); \ + } +#define GG(a, b, c, d, x, s, ac) { \ + (a) += G ((b), (c), (d)) + (x) + (uint32_t)(ac); \ + (a) = ROTATE_LEFT ((a), (s)); \ + (a) += (b); \ + } +#define HH(a, b, c, d, x, s, ac) { \ + (a) += H ((b), (c), (d)) + (x) + (uint32_t)(ac); \ + (a) = ROTATE_LEFT ((a), (s)); \ + (a) += (b); \ + } +#define II(a, b, c, d, x, s, ac) { \ + (a) += I ((b), (c), (d)) + (x) + (uint32_t)(ac); \ + (a) = ROTATE_LEFT ((a), (s)); \ + (a) += (b); \ + } + +/** + * MD5 initialization - begins an MD5 operation, writing a new ctx. + */ +EXP_FUNC void STDCALL MD5_Init(MD5_CTX *ctx) +{ + ctx->count[0] = ctx->count[1] = 0; + + /* Load magic initialization constants. + */ + ctx->state[0] = 0x67452301; + ctx->state[1] = 0xefcdab89; + ctx->state[2] = 0x98badcfe; + ctx->state[3] = 0x10325476; +} + +/** + * Accepts an array of octets as the next portion of the message. + */ +EXP_FUNC void STDCALL MD5_Update(MD5_CTX *ctx, const uint8_t * msg, int len) +{ + uint32_t x; + int i, partLen; + + /* Compute number of bytes mod 64 */ + x = (uint32_t)((ctx->count[0] >> 3) & 0x3F); + + /* Update number of bits */ + if ((ctx->count[0] += ((uint32_t)len << 3)) < ((uint32_t)len << 3)) + ctx->count[1]++; + ctx->count[1] += ((uint32_t)len >> 29); + + partLen = 64 - x; + + /* Transform as many times as possible. */ + if (len >= partLen) + { + memcpy(&ctx->buffer[x], msg, partLen); + MD5Transform(ctx->state, ctx->buffer); + + for (i = partLen; i + 63 < len; i += 64) + MD5Transform(ctx->state, &msg[i]); + + x = 0; + } + else + i = 0; + + /* Buffer remaining input */ + memcpy(&ctx->buffer[x], &msg[i], len-i); +} + +/** + * Return the 128-bit message digest into the user's array + */ +EXP_FUNC void STDCALL MD5_Final(uint8_t *digest, MD5_CTX *ctx) +{ + uint8_t bits[8]; + uint32_t x, padLen; + + /* Save number of bits */ + Encode(bits, ctx->count, 8); + + /* Pad out to 56 mod 64. + */ + x = (uint32_t)((ctx->count[0] >> 3) & 0x3f); + padLen = (x < 56) ? (56 - x) : (120 - x); + MD5_Update(ctx, PADDING, padLen); + + /* Append length (before padding) */ + MD5_Update(ctx, bits, 8); + + /* Store state in digest */ + Encode(digest, ctx->state, MD5_SIZE); +} + +/** + * MD5 basic transformation. Transforms state based on block. + */ +static void MD5Transform(uint32_t state[4], const uint8_t block[64]) +{ + uint32_t a = state[0], b = state[1], c = state[2], + d = state[3], x[MD5_SIZE]; + + Decode(x, block, 64); + + /* Round 1 */ + FF (a, b, c, d, x[ 0], S11, 0xd76aa478); /* 1 */ + FF (d, a, b, c, x[ 1], S12, 0xe8c7b756); /* 2 */ + FF (c, d, a, b, x[ 2], S13, 0x242070db); /* 3 */ + FF (b, c, d, a, x[ 3], S14, 0xc1bdceee); /* 4 */ + FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); /* 5 */ + FF (d, a, b, c, x[ 5], S12, 0x4787c62a); /* 6 */ + FF (c, d, a, b, x[ 6], S13, 0xa8304613); /* 7 */ + FF (b, c, d, a, x[ 7], S14, 0xfd469501); /* 8 */ + FF (a, b, c, d, x[ 8], S11, 0x698098d8); /* 9 */ + FF (d, a, b, c, x[ 9], S12, 0x8b44f7af); /* 10 */ + FF (c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */ + FF (b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */ + FF (a, b, c, d, x[12], S11, 0x6b901122); /* 13 */ + FF (d, a, b, c, x[13], S12, 0xfd987193); /* 14 */ + FF (c, d, a, b, x[14], S13, 0xa679438e); /* 15 */ + FF (b, c, d, a, x[15], S14, 0x49b40821); /* 16 */ + + /* Round 2 */ + GG (a, b, c, d, x[ 1], S21, 0xf61e2562); /* 17 */ + GG (d, a, b, c, x[ 6], S22, 0xc040b340); /* 18 */ + GG (c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */ + GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa); /* 20 */ + GG (a, b, c, d, x[ 5], S21, 0xd62f105d); /* 21 */ + GG (d, a, b, c, x[10], S22, 0x2441453); /* 22 */ + GG (c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */ + GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8); /* 24 */ + GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); /* 25 */ + GG (d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */ + GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); /* 27 */ + GG (b, c, d, a, x[ 8], S24, 0x455a14ed); /* 28 */ + GG (a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */ + GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8); /* 30 */ + GG (c, d, a, b, x[ 7], S23, 0x676f02d9); /* 31 */ + GG (b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */ + + /* Round 3 */ + HH (a, b, c, d, x[ 5], S31, 0xfffa3942); /* 33 */ + HH (d, a, b, c, x[ 8], S32, 0x8771f681); /* 34 */ + HH (c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */ + HH (b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */ + HH (a, b, c, d, x[ 1], S31, 0xa4beea44); /* 37 */ + HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9); /* 38 */ + HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); /* 39 */ + HH (b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */ + HH (a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */ + HH (d, a, b, c, x[ 0], S32, 0xeaa127fa); /* 42 */ + HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); /* 43 */ + HH (b, c, d, a, x[ 6], S34, 0x4881d05); /* 44 */ + HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); /* 45 */ + HH (d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */ + HH (c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */ + HH (b, c, d, a, x[ 2], S34, 0xc4ac5665); /* 48 */ + + /* Round 4 */ + II (a, b, c, d, x[ 0], S41, 0xf4292244); /* 49 */ + II (d, a, b, c, x[ 7], S42, 0x432aff97); /* 50 */ + II (c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */ + II (b, c, d, a, x[ 5], S44, 0xfc93a039); /* 52 */ + II (a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */ + II (d, a, b, c, x[ 3], S42, 0x8f0ccc92); /* 54 */ + II (c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */ + II (b, c, d, a, x[ 1], S44, 0x85845dd1); /* 56 */ + II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); /* 57 */ + II (d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */ + II (c, d, a, b, x[ 6], S43, 0xa3014314); /* 59 */ + II (b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */ + II (a, b, c, d, x[ 4], S41, 0xf7537e82); /* 61 */ + II (d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */ + II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); /* 63 */ + II (b, c, d, a, x[ 9], S44, 0xeb86d391); /* 64 */ + + state[0] += a; + state[1] += b; + state[2] += c; + state[3] += d; +} + +/** + * Encodes input (uint32_t) into output (uint8_t). Assumes len is + * a multiple of 4. + */ +static void Encode(uint8_t *output, uint32_t *input, uint32_t len) +{ + uint32_t i, j; + + for (i = 0, j = 0; j < len; i++, j += 4) + { + output[j] = (uint8_t)(input[i] & 0xff); + output[j+1] = (uint8_t)((input[i] >> 8) & 0xff); + output[j+2] = (uint8_t)((input[i] >> 16) & 0xff); + output[j+3] = (uint8_t)((input[i] >> 24) & 0xff); + } +} + +/** + * Decodes input (uint8_t) into output (uint32_t). Assumes len is + * a multiple of 4. + */ +static void Decode(uint32_t *output, const uint8_t *input, uint32_t len) +{ + uint32_t i, j; + + for (i = 0, j = 0; j < len; i++, j += 4) + output[i] = ((uint32_t)input[j]) | (((uint32_t)input[j+1]) << 8) | + (((uint32_t)input[j+2]) << 16) | (((uint32_t)input[j+3]) << 24); +} diff --git a/features/unsupported/net/https/axTLS/crypto/os_int.h b/features/unsupported/net/https/axTLS/crypto/os_int.h new file mode 100644 index 00000000000..87885672388 --- /dev/null +++ b/features/unsupported/net/https/axTLS/crypto/os_int.h @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2012, Cameron Rich + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * * Neither the name of the axTLS project nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @file os_int.h + * + * Ensure a consistent bit size + */ + +#ifndef HEADER_OS_INT_H +#define HEADER_OS_INT_H + +#ifdef __cplusplus +extern "C" { +#endif + +#if defined(WIN32) +typedef UINT8 uint8_t; +typedef INT8 int8_t; +typedef UINT16 uint16_t; +typedef INT16 int16_t; +typedef UINT32 uint32_t; +typedef INT32 int32_t; +typedef UINT64 uint64_t; +typedef INT64 int64_t; +#else /* Not Win32 */ + +#ifdef CONFIG_PLATFORM_SOLARIS +#include +#else +#include +#endif /* Not Solaris */ + +#endif /* Not Win32 */ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/features/unsupported/net/https/axTLS/crypto/rc4.c b/features/unsupported/net/https/axTLS/crypto/rc4.c new file mode 100644 index 00000000000..12a121151d8 --- /dev/null +++ b/features/unsupported/net/https/axTLS/crypto/rc4.c @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2007, Cameron Rich + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * * Neither the name of the axTLS project nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * An implementation of the RC4/ARC4 algorithm. + * Originally written by Christophe Devine. + */ + +#include +#include "os_port.h" +#include "crypto.h" + +/** + * Get ready for an encrypt/decrypt operation + */ +void RC4_setup(RC4_CTX *ctx, const uint8_t *key, int length) +{ + int i, j = 0, k = 0, a; + uint8_t *m; + + ctx->x = 0; + ctx->y = 0; + m = ctx->m; + + for (i = 0; i < 256; i++) + m[i] = i; + + for (i = 0; i < 256; i++) + { + a = m[i]; + j = (uint8_t)(j + a + key[k]); + m[i] = m[j]; + m[j] = a; + + if (++k >= length) + k = 0; + } +} + +/** + * Perform the encrypt/decrypt operation (can use it for either since + * this is a stream cipher). + * NOTE: *msg and *out must be the same pointer (performance tweak) + */ +void RC4_crypt(RC4_CTX *ctx, const uint8_t *msg, uint8_t *out, int length) +{ + int i; + uint8_t *m, x, y, a, b; + + x = ctx->x; + y = ctx->y; + m = ctx->m; + + for (i = 0; i < length; i++) + { + a = m[++x]; + y += a; + m[x] = b = m[y]; + m[y] = a; + out[i] ^= m[(uint8_t)(a + b)]; + } + + ctx->x = x; + ctx->y = y; +} diff --git a/features/unsupported/net/https/axTLS/crypto/rsa.c b/features/unsupported/net/https/axTLS/crypto/rsa.c new file mode 100644 index 00000000000..64282a26279 --- /dev/null +++ b/features/unsupported/net/https/axTLS/crypto/rsa.c @@ -0,0 +1,270 @@ +/* + * Copyright (c) 2007, Cameron Rich + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * * Neither the name of the axTLS project nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * Implements the RSA public encryption algorithm. Uses the bigint library to + * perform its calculations. + */ + +#include +#include +#include +#include +#include "os_port.h" +#include "crypto.h" + +void RSA_priv_key_new(RSA_CTX **ctx, + const uint8_t *modulus, int mod_len, + const uint8_t *pub_exp, int pub_len, + const uint8_t *priv_exp, int priv_len +#if CONFIG_BIGINT_CRT + , const uint8_t *p, int p_len, + const uint8_t *q, int q_len, + const uint8_t *dP, int dP_len, + const uint8_t *dQ, int dQ_len, + const uint8_t *qInv, int qInv_len +#endif + ) +{ + RSA_CTX *rsa_ctx; + BI_CTX *bi_ctx; + RSA_pub_key_new(ctx, modulus, mod_len, pub_exp, pub_len); + rsa_ctx = *ctx; + bi_ctx = rsa_ctx->bi_ctx; + rsa_ctx->d = bi_import(bi_ctx, priv_exp, priv_len); + bi_permanent(rsa_ctx->d); + +#ifdef CONFIG_BIGINT_CRT + rsa_ctx->p = bi_import(bi_ctx, p, p_len); + rsa_ctx->q = bi_import(bi_ctx, q, q_len); + rsa_ctx->dP = bi_import(bi_ctx, dP, dP_len); + rsa_ctx->dQ = bi_import(bi_ctx, dQ, dQ_len); + rsa_ctx->qInv = bi_import(bi_ctx, qInv, qInv_len); + bi_permanent(rsa_ctx->dP); + bi_permanent(rsa_ctx->dQ); + bi_permanent(rsa_ctx->qInv); + bi_set_mod(bi_ctx, rsa_ctx->p, BIGINT_P_OFFSET); + bi_set_mod(bi_ctx, rsa_ctx->q, BIGINT_Q_OFFSET); +#endif +} + +void RSA_pub_key_new(RSA_CTX **ctx, + const uint8_t *modulus, int mod_len, + const uint8_t *pub_exp, int pub_len) +{ + RSA_CTX *rsa_ctx; + BI_CTX *bi_ctx; + + if (*ctx) /* if we load multiple certs, dump the old one */ + RSA_free(*ctx); + + bi_ctx = bi_initialize(); + *ctx = (RSA_CTX *)calloc(1, sizeof(RSA_CTX)); + rsa_ctx = *ctx; + rsa_ctx->bi_ctx = bi_ctx; + rsa_ctx->num_octets = mod_len; + rsa_ctx->m = bi_import(bi_ctx, modulus, mod_len); + bi_set_mod(bi_ctx, rsa_ctx->m, BIGINT_M_OFFSET); + rsa_ctx->e = bi_import(bi_ctx, pub_exp, pub_len); + bi_permanent(rsa_ctx->e); +} + +/** + * Free up any RSA context resources. + */ +void RSA_free(RSA_CTX *rsa_ctx) +{ + BI_CTX *bi_ctx; + if (rsa_ctx == NULL) /* deal with ptrs that are null */ + return; + + bi_ctx = rsa_ctx->bi_ctx; + + bi_depermanent(rsa_ctx->e); + bi_free(bi_ctx, rsa_ctx->e); + bi_free_mod(rsa_ctx->bi_ctx, BIGINT_M_OFFSET); + + if (rsa_ctx->d) + { + bi_depermanent(rsa_ctx->d); + bi_free(bi_ctx, rsa_ctx->d); +#ifdef CONFIG_BIGINT_CRT + bi_depermanent(rsa_ctx->dP); + bi_depermanent(rsa_ctx->dQ); + bi_depermanent(rsa_ctx->qInv); + bi_free(bi_ctx, rsa_ctx->dP); + bi_free(bi_ctx, rsa_ctx->dQ); + bi_free(bi_ctx, rsa_ctx->qInv); + bi_free_mod(rsa_ctx->bi_ctx, BIGINT_P_OFFSET); + bi_free_mod(rsa_ctx->bi_ctx, BIGINT_Q_OFFSET); +#endif + } + + bi_terminate(bi_ctx); + free(rsa_ctx); +} + +/** + * @brief Use PKCS1.5 for decryption/verification. + * @param ctx [in] The context + * @param in_data [in] The data to encrypt (must be < modulus size-11) + * @param out_data [out] The encrypted data. + * @param is_decryption [in] Decryption or verify operation. + * @return The number of bytes that were originally encrypted. -1 on error. + * @see http://www.rsasecurity.com/rsalabs/node.asp?id=2125 + */ +int RSA_decrypt(const RSA_CTX *ctx, const uint8_t *in_data, + uint8_t *out_data, int is_decryption) +{ + const int byte_size = ctx->num_octets; + int i, size; + bigint *decrypted_bi, *dat_bi; + uint8_t *block = (uint8_t *)alloca(byte_size); + + memset(out_data, 0, byte_size); /* initialise */ + + /* decrypt */ + dat_bi = bi_import(ctx->bi_ctx, in_data, byte_size); +#ifdef CONFIG_SSL_CERT_VERIFICATION + decrypted_bi = is_decryption ? /* decrypt or verify? */ + RSA_private(ctx, dat_bi) : RSA_public(ctx, dat_bi); +#else /* always a decryption */ + decrypted_bi = RSA_private(ctx, dat_bi); +#endif + + /* convert to a normal block */ + bi_export(ctx->bi_ctx, decrypted_bi, block, byte_size); + + i = 10; /* start at the first possible non-padded byte */ + +#ifdef CONFIG_SSL_CERT_VERIFICATION + if (is_decryption == 0) /* PKCS1.5 signing pads with "0xff"s */ + { + while (block[i++] == 0xff && i < byte_size); + + if (block[i-2] != 0xff) + i = byte_size; /*ensure size is 0 */ + } + else /* PKCS1.5 encryption padding is random */ +#endif + { + while (block[i++] && i < byte_size); + } + size = byte_size - i; + + /* get only the bit we want */ + if (size > 0) + memcpy(out_data, &block[i], size); + + return size ? size : -1; +} + +/** + * Performs m = c^d mod n + */ +bigint *RSA_private(const RSA_CTX *c, bigint *bi_msg) +{ + printf("RSA private\n"); +#ifdef CONFIG_BIGINT_CRT + return bi_crt(c->bi_ctx, bi_msg, c->dP, c->dQ, c->p, c->q, c->qInv); +#else + BI_CTX *ctx = c->bi_ctx; + ctx->mod_offset = BIGINT_M_OFFSET; + return bi_mod_power(ctx, bi_msg, c->d); +#endif +} + +#ifdef CONFIG_SSL_FULL_MODE +/** + * Used for diagnostics. + */ +void RSA_print(const RSA_CTX *rsa_ctx) +{ + if (rsa_ctx == NULL) + return; + + printf("----------------- RSA DEBUG ----------------\n"); + printf("Size:\t%d\n", rsa_ctx->num_octets); + bi_print("Modulus", rsa_ctx->m); + bi_print("Public Key", rsa_ctx->e); + bi_print("Private Key", rsa_ctx->d); +} +#endif + +#if defined(CONFIG_SSL_CERT_VERIFICATION) || defined(CONFIG_SSL_GENERATE_X509_CERT) +/** + * Performs c = m^e mod n + */ +bigint *RSA_public(const RSA_CTX * c, bigint *bi_msg) +{ + c->bi_ctx->mod_offset = BIGINT_M_OFFSET; + return bi_mod_power(c->bi_ctx, bi_msg, c->e); +} + +/** + * Use PKCS1.5 for encryption/signing. + * see http://www.rsasecurity.com/rsalabs/node.asp?id=2125 + */ +int RSA_encrypt(const RSA_CTX *ctx, const uint8_t *in_data, uint16_t in_len, + uint8_t *out_data, int is_signing) +{ + int byte_size = ctx->num_octets; + int num_pads_needed = byte_size-in_len-3; + bigint *dat_bi, *encrypt_bi; + /* note: in_len+11 must be > byte_size */ + out_data[0] = 0; /* ensure encryption block is < modulus */ + if (is_signing) + { + out_data[1] = 1; /* PKCS1.5 signing pads with "0xff"'s */ + memset(&out_data[2], 0xff, num_pads_needed); + } + else /* randomize the encryption padding with non-zero bytes */ + { + out_data[1] = 2; + get_random_NZ(num_pads_needed, &out_data[2]); + } + + out_data[2+num_pads_needed] = 0; + memcpy(&out_data[3+num_pads_needed], in_data, in_len); + + /* now encrypt it */ + dat_bi = bi_import(ctx->bi_ctx, out_data, byte_size); + + encrypt_bi = is_signing ? RSA_private(ctx, dat_bi) : + RSA_public(ctx, dat_bi); + + bi_export(ctx->bi_ctx, encrypt_bi, out_data, byte_size); + /* save a few bytes of memory */ + bi_clear_cache(ctx->bi_ctx); + + return byte_size; +} + +#endif /* CONFIG_SSL_CERT_VERIFICATION */ diff --git a/features/unsupported/net/https/axTLS/crypto/sha1.c b/features/unsupported/net/https/axTLS/crypto/sha1.c new file mode 100644 index 00000000000..1082733e7ec --- /dev/null +++ b/features/unsupported/net/https/axTLS/crypto/sha1.c @@ -0,0 +1,249 @@ +/* + * Copyright (c) 2007, Cameron Rich + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * * Neither the name of the axTLS project nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * SHA1 implementation - as defined in FIPS PUB 180-1 published April 17, 1995. + * This code was originally taken from RFC3174 + */ + +#include +#include "os_port.h" +#include "crypto.h" + +/* + * Define the SHA1 circular left shift macro + */ +#define SHA1CircularShift(bits,word) \ + (((word) << (bits)) | ((word) >> (32-(bits)))) + +/* ----- static functions ----- */ +static void SHA1PadMessage(SHA1_CTX *ctx); +static void SHA1ProcessMessageBlock(SHA1_CTX *ctx); + +/** + * Initialize the SHA1 context + */ +void SHA1_Init(SHA1_CTX *ctx) +{ + ctx->Length_Low = 0; + ctx->Length_High = 0; + ctx->Message_Block_Index = 0; + ctx->Intermediate_Hash[0] = 0x67452301; + ctx->Intermediate_Hash[1] = 0xEFCDAB89; + ctx->Intermediate_Hash[2] = 0x98BADCFE; + ctx->Intermediate_Hash[3] = 0x10325476; + ctx->Intermediate_Hash[4] = 0xC3D2E1F0; +} + +/** + * Accepts an array of octets as the next portion of the message. + */ +void SHA1_Update(SHA1_CTX *ctx, const uint8_t *msg, int len) +{ + while (len--) + { + ctx->Message_Block[ctx->Message_Block_Index++] = (*msg & 0xFF); + ctx->Length_Low += 8; + + if (ctx->Length_Low == 0) + ctx->Length_High++; + + if (ctx->Message_Block_Index == 64) + SHA1ProcessMessageBlock(ctx); + + msg++; + } +} + +/** + * Return the 160-bit message digest into the user's array + */ +void SHA1_Final(uint8_t *digest, SHA1_CTX *ctx) +{ + int i; + + SHA1PadMessage(ctx); + memset(ctx->Message_Block, 0, 64); + ctx->Length_Low = 0; /* and clear length */ + ctx->Length_High = 0; + + for (i = 0; i < SHA1_SIZE; i++) + { + digest[i] = ctx->Intermediate_Hash[i>>2] >> 8 * ( 3 - ( i & 0x03 ) ); + } +} + +/** + * Process the next 512 bits of the message stored in the array. + */ +static void SHA1ProcessMessageBlock(SHA1_CTX *ctx) +{ + const uint32_t K[] = { /* Constants defined in SHA-1 */ + 0x5A827999, + 0x6ED9EBA1, + 0x8F1BBCDC, + 0xCA62C1D6 + }; + int t; /* Loop counter */ + uint32_t temp; /* Temporary word value */ + uint32_t W[80]; /* Word sequence */ + uint32_t A, B, C, D, E; /* Word buffers */ + + /* + * Initialize the first 16 words in the array W + */ + for (t = 0; t < 16; t++) + { + W[t] = ctx->Message_Block[t * 4] << 24; + W[t] |= ctx->Message_Block[t * 4 + 1] << 16; + W[t] |= ctx->Message_Block[t * 4 + 2] << 8; + W[t] |= ctx->Message_Block[t * 4 + 3]; + } + + for (t = 16; t < 80; t++) + { + W[t] = SHA1CircularShift(1,W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16]); + } + + A = ctx->Intermediate_Hash[0]; + B = ctx->Intermediate_Hash[1]; + C = ctx->Intermediate_Hash[2]; + D = ctx->Intermediate_Hash[3]; + E = ctx->Intermediate_Hash[4]; + + for (t = 0; t < 20; t++) + { + temp = SHA1CircularShift(5,A) + + ((B & C) | ((~B) & D)) + E + W[t] + K[0]; + E = D; + D = C; + C = SHA1CircularShift(30,B); + + B = A; + A = temp; + } + + for (t = 20; t < 40; t++) + { + temp = SHA1CircularShift(5,A) + (B ^ C ^ D) + E + W[t] + K[1]; + E = D; + D = C; + C = SHA1CircularShift(30,B); + B = A; + A = temp; + } + + for (t = 40; t < 60; t++) + { + temp = SHA1CircularShift(5,A) + + ((B & C) | (B & D) | (C & D)) + E + W[t] + K[2]; + E = D; + D = C; + C = SHA1CircularShift(30,B); + B = A; + A = temp; + } + + for (t = 60; t < 80; t++) + { + temp = SHA1CircularShift(5,A) + (B ^ C ^ D) + E + W[t] + K[3]; + E = D; + D = C; + C = SHA1CircularShift(30,B); + B = A; + A = temp; + } + + ctx->Intermediate_Hash[0] += A; + ctx->Intermediate_Hash[1] += B; + ctx->Intermediate_Hash[2] += C; + ctx->Intermediate_Hash[3] += D; + ctx->Intermediate_Hash[4] += E; + ctx->Message_Block_Index = 0; +} + +/* + * According to the standard, the message must be padded to an even + * 512 bits. The first padding bit must be a '1'. The last 64 + * bits represent the length of the original message. All bits in + * between should be 0. This function will pad the message + * according to those rules by filling the Message_Block array + * accordingly. It will also call the ProcessMessageBlock function + * provided appropriately. When it returns, it can be assumed that + * the message digest has been computed. + * + * @param ctx [in, out] The SHA1 context + */ +static void SHA1PadMessage(SHA1_CTX *ctx) +{ + /* + * Check to see if the current message block is too small to hold + * the initial padding bits and length. If so, we will pad the + * block, process it, and then continue padding into a second + * block. + */ + if (ctx->Message_Block_Index > 55) + { + ctx->Message_Block[ctx->Message_Block_Index++] = 0x80; + while(ctx->Message_Block_Index < 64) + { + ctx->Message_Block[ctx->Message_Block_Index++] = 0; + } + + SHA1ProcessMessageBlock(ctx); + + while (ctx->Message_Block_Index < 56) + { + ctx->Message_Block[ctx->Message_Block_Index++] = 0; + } + } + else + { + ctx->Message_Block[ctx->Message_Block_Index++] = 0x80; + while(ctx->Message_Block_Index < 56) + { + + ctx->Message_Block[ctx->Message_Block_Index++] = 0; + } + } + + /* + * Store the message length as the last 8 octets + */ + ctx->Message_Block[56] = ctx->Length_High >> 24; + ctx->Message_Block[57] = ctx->Length_High >> 16; + ctx->Message_Block[58] = ctx->Length_High >> 8; + ctx->Message_Block[59] = ctx->Length_High; + ctx->Message_Block[60] = ctx->Length_Low >> 24; + ctx->Message_Block[61] = ctx->Length_Low >> 16; + ctx->Message_Block[62] = ctx->Length_Low >> 8; + ctx->Message_Block[63] = ctx->Length_Low; + SHA1ProcessMessageBlock(ctx); +} diff --git a/features/unsupported/net/https/axTLS/ssl/asn1.c b/features/unsupported/net/https/axTLS/ssl/asn1.c new file mode 100644 index 00000000000..d95c9117c58 --- /dev/null +++ b/features/unsupported/net/https/axTLS/ssl/asn1.c @@ -0,0 +1,565 @@ +/* + * Copyright (c) 2007, Cameron Rich + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * * Neither the name of the axTLS project nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * Some primitive asn methods for extraction ASN.1 data. + */ + +#include +#include +#include +#include +#include "os_port.h" +#include "crypto.h" +#include "crypto_misc.h" +#include "config.h" + +#define SIG_OID_PREFIX_SIZE 8 +#define SIG_IIS6_OID_SIZE 5 +#define SIG_SUBJECT_ALT_NAME_SIZE 3 + +/* Must be an RSA algorithm with either SHA1 or MD5 for verifying to work */ +static const uint8_t sig_oid_prefix[SIG_OID_PREFIX_SIZE] = +{ + 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01 +}; + +static const uint8_t sig_sha1WithRSAEncrypt[SIG_IIS6_OID_SIZE] = +{ + 0x2b, 0x0e, 0x03, 0x02, 0x1d +}; + +static const uint8_t sig_subject_alt_name[SIG_SUBJECT_ALT_NAME_SIZE] = +{ + 0x55, 0x1d, 0x11 +}; + +/* CN, O, OU */ +static const uint8_t g_dn_types[] = { 3, 10, 11 }; + +int get_asn1_length(const uint8_t *buf, int *offset) +{ + int len, i; + + if (!(buf[*offset] & 0x80)) /* short form */ + { + len = buf[(*offset)++]; + } + else /* long form */ + { + int length_bytes = buf[(*offset)++]&0x7f; + len = 0; + for (i = 0; i < length_bytes; i++) + { + len <<= 8; + len += buf[(*offset)++]; + } + } + + return len; +} + +/** + * Skip the ASN1.1 object type and its length. Get ready to read the object's + * data. + */ +int asn1_next_obj(const uint8_t *buf, int *offset, int obj_type) +{ + if (buf[*offset] != obj_type) + return X509_NOT_OK; + (*offset)++; + int tmp = get_asn1_length(buf, offset); + return tmp; +} + +/** + * Skip over an ASN.1 object type completely. Get ready to read the next + * object. + */ +int asn1_skip_obj(const uint8_t *buf, int *offset, int obj_type) +{ + int len; + if (buf[*offset] != obj_type) + return X509_NOT_OK; + (*offset)++; + len = get_asn1_length(buf, offset); + *offset += len; + return 0; +} + +/** + * Read an integer value for ASN.1 data + * Note: This function allocates memory which must be freed by the user. + */ +int asn1_get_int(const uint8_t *buf, int *offset, uint8_t **object) +{ + int len; + + if ((len = asn1_next_obj(buf, offset, ASN1_INTEGER)) < 0) + goto end_int_array; + + if (len > 1 && buf[*offset] == 0x00) /* ignore the negative byte */ + { + len--; + (*offset)++; + } + + *object = (uint8_t *)malloc(len); + memcpy(*object, &buf[*offset], len); + *offset += len; + +end_int_array: + return len; +} + +/** + * Get all the RSA private key specifics from an ASN.1 encoded file + */ +int asn1_get_private_key(const uint8_t *buf, int len, RSA_CTX **rsa_ctx) +{ + int offset = 7; + uint8_t *modulus = NULL, *priv_exp = NULL, *pub_exp = NULL; + int mod_len, priv_len, pub_len; +#ifdef CONFIG_BIGINT_CRT + uint8_t *p = NULL, *q = NULL, *dP = NULL, *dQ = NULL, *qInv = NULL; + int p_len, q_len, dP_len, dQ_len, qInv_len; +#endif + + /* not in der format */ + if (buf[0] != ASN1_SEQUENCE) /* basic sanity check */ + { +#ifdef CONFIG_SSL_FULL_MODE + printf("Error: This is not a valid ASN.1 file\n"); +#endif + return X509_INVALID_PRIV_KEY; + } + + /* Use the private key to mix up the RNG if possible. */ + RNG_custom_init(buf, len); + + mod_len = asn1_get_int(buf, &offset, &modulus); + pub_len = asn1_get_int(buf, &offset, &pub_exp); + priv_len = asn1_get_int(buf, &offset, &priv_exp); + + if (mod_len <= 0 || pub_len <= 0 || priv_len <= 0) + return X509_INVALID_PRIV_KEY; + +#ifdef CONFIG_BIGINT_CRT + p_len = asn1_get_int(buf, &offset, &p); + q_len = asn1_get_int(buf, &offset, &q); + dP_len = asn1_get_int(buf, &offset, &dP); + dQ_len = asn1_get_int(buf, &offset, &dQ); + qInv_len = asn1_get_int(buf, &offset, &qInv); + + if (p_len <= 0 || q_len <= 0 || dP_len <= 0 || dQ_len <= 0 || qInv_len <= 0) + return X509_INVALID_PRIV_KEY; + + RSA_priv_key_new(rsa_ctx, + modulus, mod_len, pub_exp, pub_len, priv_exp, priv_len, + p, p_len, q, p_len, dP, dP_len, dQ, dQ_len, qInv, qInv_len); + + free(p); + free(q); + free(dP); + free(dQ); + free(qInv); +#else + RSA_priv_key_new(rsa_ctx, + modulus, mod_len, pub_exp, pub_len, priv_exp, priv_len); +#endif + + free(modulus); + free(priv_exp); + free(pub_exp); + return X509_OK; +} + +/** + * Get the time of a certificate. Ignore hours/minutes/seconds. + */ +static int asn1_get_utc_time(const uint8_t *buf, int *offset, time_t *t) +{ + int ret = X509_NOT_OK, len, t_offset; + struct tm tm; + + if (buf[(*offset)++] != ASN1_UTC_TIME) + goto end_utc_time; + + len = get_asn1_length(buf, offset); + t_offset = *offset; + + memset(&tm, 0, sizeof(struct tm)); + tm.tm_year = (buf[t_offset] - '0')*10 + (buf[t_offset+1] - '0'); + + if (tm.tm_year <= 50) /* 1951-2050 thing */ + { + tm.tm_year += 100; + } + + tm.tm_mon = (buf[t_offset+2] - '0')*10 + (buf[t_offset+3] - '0') - 1; + tm.tm_mday = (buf[t_offset+4] - '0')*10 + (buf[t_offset+5] - '0'); + *t = mktime(&tm); + *offset += len; + ret = X509_OK; + +end_utc_time: + return ret; +} + +/** + * Get the version type of a certificate (which we don't actually care about) + */ +int asn1_version(const uint8_t *cert, int *offset, X509_CTX *x509_ctx) +{ + int ret = X509_NOT_OK; + + (*offset) += 2; /* get past explicit tag */ + if (asn1_skip_obj(cert, offset, ASN1_INTEGER)) + goto end_version; + + ret = X509_OK; +end_version: + return ret; +} + +/** + * Retrieve the notbefore and notafter certificate times. + */ +int asn1_validity(const uint8_t *cert, int *offset, X509_CTX *x509_ctx) +{ + return (asn1_next_obj(cert, offset, ASN1_SEQUENCE) < 0 || + asn1_get_utc_time(cert, offset, &x509_ctx->not_before) || + asn1_get_utc_time(cert, offset, &x509_ctx->not_after)); +} + +/** + * Get the components of a distinguished name + */ +static int asn1_get_oid_x520(const uint8_t *buf, int *offset) +{ + int dn_type = 0; + int len; + + if ((len = asn1_next_obj(buf, offset, ASN1_OID)) < 0) + goto end_oid; + + /* expect a sequence of 2.5.4.[x] where x is a one of distinguished name + components we are interested in. */ + if (len == 3 && buf[(*offset)++] == 0x55 && buf[(*offset)++] == 0x04) + dn_type = buf[(*offset)++]; + else + { + *offset += len; /* skip over it */ + } + +end_oid: + return dn_type; +} + +/** + * Obtain an ASN.1 printable string type. + */ +static int asn1_get_printable_str(const uint8_t *buf, int *offset, char **str) +{ + int len = X509_NOT_OK; + int asn1_type = buf[*offset]; + + /* some certs have this awful crud in them for some reason */ + if (asn1_type != ASN1_PRINTABLE_STR && + asn1_type != ASN1_PRINTABLE_STR2 && + asn1_type != ASN1_TELETEX_STR && + asn1_type != ASN1_IA5_STR && + asn1_type != ASN1_UNICODE_STR) + goto end_pnt_str; + + (*offset)++; + len = get_asn1_length(buf, offset); + + if (asn1_type == ASN1_UNICODE_STR) + { + int i; + *str = (char *)malloc(len/2+1); /* allow for null */ + + for (i = 0; i < len; i += 2) + (*str)[i/2] = buf[*offset + i + 1]; + + (*str)[len/2] = 0; /* null terminate */ + } + else + { + *str = (char *)malloc(len+1); /* allow for null */ + memcpy(*str, &buf[*offset], len); + (*str)[len] = 0; /* null terminate */ + } + + *offset += len; + +end_pnt_str: + return len; +} + +/** + * Get the subject name (or the issuer) of a certificate. + */ +int asn1_name(const uint8_t *cert, int *offset, char *dn[]) +{ + int ret = X509_NOT_OK; + int dn_type; + char *tmp; + + if (asn1_next_obj(cert, offset, ASN1_SEQUENCE) < 0) + goto end_name; + + while (asn1_next_obj(cert, offset, ASN1_SET) >= 0) + { + int i, found = 0; + + if (asn1_next_obj(cert, offset, ASN1_SEQUENCE) < 0 || + (dn_type = asn1_get_oid_x520(cert, offset)) < 0) + goto end_name; + + tmp = NULL; + + if (asn1_get_printable_str(cert, offset, &tmp) < 0) + { + free(tmp); + goto end_name; + } + + /* find the distinguished named type */ + for (i = 0; i < X509_NUM_DN_TYPES; i++) + { + if (dn_type == g_dn_types[i]) + { + if (dn[i] == NULL) + { + dn[i] = tmp; + found = 1; + break; + } + } + } + + if (found == 0) /* not found so get rid of it */ + { + free(tmp); + } + } + + ret = X509_OK; +end_name: + return ret; +} + +/** + * Read the modulus and public exponent of a certificate. + */ +int asn1_public_key(const uint8_t *cert, int *offset, X509_CTX *x509_ctx) +{ + int ret = X509_NOT_OK, mod_len, pub_len; + uint8_t *modulus = NULL, *pub_exp = NULL; + + if (asn1_next_obj(cert, offset, ASN1_SEQUENCE) < 0 || + asn1_skip_obj(cert, offset, ASN1_SEQUENCE) || + asn1_next_obj(cert, offset, ASN1_BIT_STRING) < 0) + goto end_pub_key; + + (*offset)++; /* ignore the padding bit field */ + + if (asn1_next_obj(cert, offset, ASN1_SEQUENCE) < 0) + goto end_pub_key; + + mod_len = asn1_get_int(cert, offset, &modulus); + pub_len = asn1_get_int(cert, offset, &pub_exp); + RSA_pub_key_new(&x509_ctx->rsa_ctx, modulus, mod_len, pub_exp, pub_len); + free(modulus); + free(pub_exp); + ret = X509_OK; + +end_pub_key: + return ret; +} + +#ifdef CONFIG_SSL_CERT_VERIFICATION +/** + * Read the signature of the certificate. + */ +int asn1_signature(const uint8_t *cert, int *offset, X509_CTX *x509_ctx) +{ + int ret = X509_NOT_OK; + + if (cert[(*offset)++] != ASN1_BIT_STRING) + goto end_sig; + + x509_ctx->sig_len = get_asn1_length(cert, offset)-1; + (*offset)++; /* ignore bit string padding bits */ + x509_ctx->signature = (uint8_t *)malloc(x509_ctx->sig_len); + memcpy(x509_ctx->signature, &cert[*offset], x509_ctx->sig_len); + *offset += x509_ctx->sig_len; + ret = X509_OK; + +end_sig: + return ret; +} + +/* + * Compare 2 distinguished name components for equality + * @return 0 if a match + */ +static int asn1_compare_dn_comp(const char *dn1, const char *dn2) +{ + int ret; + + if (dn1 == NULL && dn2 == NULL) + ret = 0; + else + ret = (dn1 && dn2) ? strcmp(dn1, dn2) : 1; + + return ret; +} + +/** + * Clean up all of the CA certificates. + */ +void remove_ca_certs(CA_CERT_CTX *ca_cert_ctx) +{ + int i = 0; + + if (ca_cert_ctx == NULL) + return; + + while (i < CONFIG_X509_MAX_CA_CERTS && ca_cert_ctx->cert[i]) + { + x509_free(ca_cert_ctx->cert[i]); + ca_cert_ctx->cert[i++] = NULL; + } + + free(ca_cert_ctx); +} + +/* + * Compare 2 distinguished names for equality + * @return 0 if a match + */ +int asn1_compare_dn(char * const dn1[], char * const dn2[]) +{ + int i; + + for (i = 0; i < X509_NUM_DN_TYPES; i++) + { + if (asn1_compare_dn_comp(dn1[i], dn2[i])) + return 1; + } + + return 0; /* all good */ +} + +int asn1_find_oid(const uint8_t* cert, int* offset, + const uint8_t* oid, int oid_length) +{ + int seqlen; + if ((seqlen = asn1_next_obj(cert, offset, ASN1_SEQUENCE))> 0) + { + int end = *offset + seqlen; + + while (*offset < end) + { + int type = cert[(*offset)++]; + int length = get_asn1_length(cert, offset); + int noffset = *offset + length; + + if (type == ASN1_SEQUENCE) + { + type = cert[(*offset)++]; + length = get_asn1_length(cert, offset); + + if (type == ASN1_OID && length == oid_length && + memcmp(cert + *offset, oid, oid_length) == 0) + { + *offset += oid_length; + return 1; + } + } + + *offset = noffset; + } + } + + return 0; +} + +int asn1_find_subjectaltname(const uint8_t* cert, int offset) +{ + if (asn1_find_oid(cert, &offset, sig_subject_alt_name, + SIG_SUBJECT_ALT_NAME_SIZE)) + { + return offset; + } + + return 0; +} + +#endif /* CONFIG_SSL_CERT_VERIFICATION */ + +/** + * Read the signature type of the certificate. We only support RSA-MD5 and + * RSA-SHA1 signature types. + */ +int asn1_signature_type(const uint8_t *cert, + int *offset, X509_CTX *x509_ctx) +{ + int ret = X509_NOT_OK, len; + + if (cert[(*offset)++] != ASN1_OID) + goto end_check_sig; + + len = get_asn1_length(cert, offset); + + if (len == 5 && memcmp(sig_sha1WithRSAEncrypt, &cert[*offset], + SIG_IIS6_OID_SIZE) == 0) + { + x509_ctx->sig_type = SIG_TYPE_SHA1; + } + else + { + if (memcmp(sig_oid_prefix, &cert[*offset], SIG_OID_PREFIX_SIZE)) + goto end_check_sig; /* unrecognised cert type */ + + x509_ctx->sig_type = cert[*offset + SIG_OID_PREFIX_SIZE]; + } + + *offset += len; + asn1_skip_obj(cert, offset, ASN1_NULL); /* if it's there */ + ret = X509_OK; + +end_check_sig: + return ret; +} + diff --git a/features/unsupported/net/https/axTLS/ssl/cert.h b/features/unsupported/net/https/axTLS/ssl/cert.h new file mode 100644 index 00000000000..48b901b048f --- /dev/null +++ b/features/unsupported/net/https/axTLS/ssl/cert.h @@ -0,0 +1,133 @@ +#ifndef CERT_H +#define CERT_H + +/* +unsigned char default_certificate[] = { + 0x30, 0x82, 0x01, 0xd7, 0x30, 0x82, 0x01, 0x40, 0x02, 0x09, 0x00, 0xab, + 0x08, 0x18, 0xa7, 0x03, 0x07, 0x27, 0xfd, 0x30, 0x0d, 0x06, 0x09, 0x2a, + 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x05, 0x05, 0x00, 0x30, 0x34, + 0x31, 0x32, 0x30, 0x30, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x13, 0x29, 0x61, + 0x78, 0x54, 0x4c, 0x53, 0x20, 0x50, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74, + 0x20, 0x44, 0x6f, 0x64, 0x67, 0x79, 0x20, 0x43, 0x65, 0x72, 0x74, 0x69, + 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x20, 0x41, 0x75, 0x74, 0x68, 0x6f, + 0x72, 0x69, 0x74, 0x79, 0x30, 0x1e, 0x17, 0x0d, 0x31, 0x30, 0x31, 0x32, + 0x32, 0x36, 0x32, 0x32, 0x33, 0x33, 0x33, 0x39, 0x5a, 0x17, 0x0d, 0x32, + 0x34, 0x30, 0x39, 0x30, 0x33, 0x32, 0x32, 0x33, 0x33, 0x33, 0x39, 0x5a, + 0x30, 0x2c, 0x31, 0x16, 0x30, 0x14, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x13, + 0x0d, 0x61, 0x78, 0x54, 0x4c, 0x53, 0x20, 0x50, 0x72, 0x6f, 0x6a, 0x65, + 0x63, 0x74, 0x31, 0x12, 0x30, 0x10, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, + 0x09, 0x31, 0x32, 0x37, 0x2e, 0x30, 0x2e, 0x30, 0x2e, 0x31, 0x30, 0x81, + 0x9f, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, + 0x01, 0x01, 0x05, 0x00, 0x03, 0x81, 0x8d, 0x00, 0x30, 0x81, 0x89, 0x02, + 0x81, 0x81, 0x00, 0xcd, 0xfd, 0x89, 0x48, 0xbe, 0x36, 0xb9, 0x95, 0x76, + 0xd4, 0x13, 0x30, 0x0e, 0xbf, 0xb2, 0xed, 0x67, 0x0a, 0xc0, 0x16, 0x3f, + 0x51, 0x09, 0x9d, 0x29, 0x2f, 0xb2, 0x6d, 0x3f, 0x3e, 0x6c, 0x2f, 0x90, + 0x80, 0xa1, 0x71, 0xdf, 0xbe, 0x38, 0xc5, 0xcb, 0xa9, 0x9a, 0x40, 0x14, + 0x90, 0x0a, 0xf9, 0xb7, 0x07, 0x0b, 0xe1, 0xda, 0xe7, 0x09, 0xbf, 0x0d, + 0x57, 0x41, 0x86, 0x60, 0xa1, 0xc1, 0x27, 0x91, 0x5b, 0x0a, 0x98, 0x46, + 0x1b, 0xf6, 0xa2, 0x84, 0xf8, 0x65, 0xc7, 0xce, 0x2d, 0x96, 0x17, 0xaa, + 0x91, 0xf8, 0x61, 0x04, 0x50, 0x70, 0xeb, 0xb4, 0x43, 0xb7, 0xdc, 0x9a, + 0xcc, 0x31, 0x01, 0x14, 0xd4, 0xcd, 0xcc, 0xc2, 0x37, 0x6d, 0x69, 0x82, + 0xd6, 0xc6, 0xc4, 0xbe, 0xf2, 0x34, 0xa5, 0xc9, 0xa6, 0x19, 0x53, 0x32, + 0x7a, 0x86, 0x0e, 0x91, 0x82, 0x0f, 0xa1, 0x42, 0x54, 0xaa, 0x01, 0x02, + 0x03, 0x01, 0x00, 0x01, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, + 0xf7, 0x0d, 0x01, 0x01, 0x05, 0x05, 0x00, 0x03, 0x81, 0x81, 0x00, 0x40, + 0xb4, 0x94, 0x9a, 0xa8, 0x89, 0x72, 0x1d, 0x07, 0xe5, 0xb3, 0x6b, 0x88, + 0x21, 0xc2, 0x38, 0x36, 0x9e, 0x7a, 0x8c, 0x49, 0x48, 0x68, 0x0c, 0x06, + 0xe8, 0xdb, 0x1f, 0x4e, 0x05, 0xe6, 0x31, 0xe3, 0xfd, 0xe6, 0x0d, 0x6b, + 0xd8, 0x13, 0x17, 0xe0, 0x2d, 0x0d, 0xb8, 0x7e, 0xcb, 0x20, 0x6c, 0xa8, + 0x73, 0xa7, 0xfd, 0xe3, 0xa7, 0xfa, 0xf3, 0x02, 0x60, 0x78, 0x1f, 0x13, + 0x40, 0x45, 0xee, 0x75, 0xf5, 0x10, 0xfd, 0x8f, 0x68, 0x74, 0xd4, 0xac, + 0xae, 0x04, 0x09, 0x55, 0x2c, 0xdb, 0xd8, 0x07, 0x07, 0x65, 0x69, 0x27, + 0x6e, 0xbf, 0x5e, 0x61, 0x40, 0x56, 0x8b, 0xd7, 0x33, 0x3b, 0xff, 0x6e, + 0x53, 0x7e, 0x9d, 0x3f, 0xc0, 0x40, 0x3a, 0xab, 0xa0, 0x50, 0x4e, 0x80, + 0x47, 0x46, 0x0d, 0x1e, 0xdb, 0x4c, 0xf1, 0x1b, 0x5d, 0x3c, 0x2a, 0x54, + 0xa7, 0x4d, 0xfa, 0x7b, 0x72, 0x66, 0xc5 +}; +unsigned int default_certificate_len = 475; +*/ +unsigned char default_certificate[] = { + 0x30, 0x82, 0x03, 0xb8, 0x30, 0x82, 0x03, 0x21, 0xa0, 0x03, 0x02, 0x01, + 0x02, 0x02, 0x09, 0x00, 0xe1, 0x40, 0xf0, 0x81, 0x55, 0x5d, 0xa4, 0x8f, + 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, + 0x05, 0x05, 0x00, 0x30, 0x81, 0x9a, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, + 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x4b, 0x31, 0x0d, 0x30, 0x0b, 0x06, + 0x03, 0x55, 0x04, 0x08, 0x13, 0x04, 0x54, 0x65, 0x73, 0x74, 0x31, 0x12, + 0x30, 0x10, 0x06, 0x03, 0x55, 0x04, 0x07, 0x13, 0x09, 0x54, 0x65, 0x73, + 0x74, 0x76, 0x69, 0x6c, 0x6c, 0x65, 0x31, 0x17, 0x30, 0x15, 0x06, 0x03, + 0x55, 0x04, 0x0a, 0x13, 0x0e, 0x4e, 0x6f, 0x69, 0x73, 0x79, 0x20, 0x41, + 0x74, 0x6f, 0x6d, 0x20, 0x4c, 0x74, 0x64, 0x31, 0x11, 0x30, 0x0f, 0x06, + 0x03, 0x55, 0x04, 0x0b, 0x14, 0x08, 0x53, 0x65, 0x63, 0x75, 0x69, 0x72, + 0x08, 0x08, 0x31, 0x15, 0x30, 0x13, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, + 0x0c, 0x41, 0x73, 0x68, 0x6c, 0x65, 0x79, 0x20, 0x4d, 0x69, 0x6c, 0x6c, + 0x73, 0x31, 0x25, 0x30, 0x23, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, + 0x0d, 0x01, 0x09, 0x01, 0x16, 0x16, 0x61, 0x73, 0x68, 0x6c, 0x65, 0x79, + 0x40, 0x61, 0x73, 0x68, 0x6c, 0x65, 0x79, 0x6d, 0x69, 0x6c, 0x6c, 0x73, + 0x2e, 0x63, 0x6f, 0x6d, 0x30, 0x1e, 0x17, 0x0d, 0x31, 0x33, 0x30, 0x35, + 0x31, 0x33, 0x31, 0x37, 0x35, 0x32, 0x34, 0x31, 0x5a, 0x17, 0x0d, 0x34, + 0x36, 0x30, 0x33, 0x32, 0x31, 0x31, 0x37, 0x35, 0x32, 0x34, 0x31, 0x5a, + 0x30, 0x81, 0x9a, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, + 0x13, 0x02, 0x55, 0x4b, 0x31, 0x0d, 0x30, 0x0b, 0x06, 0x03, 0x55, 0x04, + 0x08, 0x13, 0x04, 0x54, 0x65, 0x73, 0x74, 0x31, 0x12, 0x30, 0x10, 0x06, + 0x03, 0x55, 0x04, 0x07, 0x13, 0x09, 0x54, 0x65, 0x73, 0x74, 0x76, 0x69, + 0x6c, 0x6c, 0x65, 0x31, 0x17, 0x30, 0x15, 0x06, 0x03, 0x55, 0x04, 0x0a, + 0x13, 0x0e, 0x4e, 0x6f, 0x69, 0x73, 0x79, 0x20, 0x41, 0x74, 0x6f, 0x6d, + 0x20, 0x4c, 0x74, 0x64, 0x31, 0x11, 0x30, 0x0f, 0x06, 0x03, 0x55, 0x04, + 0x0b, 0x14, 0x08, 0x53, 0x65, 0x63, 0x75, 0x69, 0x72, 0x08, 0x08, 0x31, + 0x15, 0x30, 0x13, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x0c, 0x41, 0x73, + 0x68, 0x6c, 0x65, 0x79, 0x20, 0x4d, 0x69, 0x6c, 0x6c, 0x73, 0x31, 0x25, + 0x30, 0x23, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x09, + 0x01, 0x16, 0x16, 0x61, 0x73, 0x68, 0x6c, 0x65, 0x79, 0x40, 0x61, 0x73, + 0x68, 0x6c, 0x65, 0x79, 0x6d, 0x69, 0x6c, 0x6c, 0x73, 0x2e, 0x63, 0x6f, + 0x6d, 0x30, 0x81, 0x9f, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, + 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x81, 0x8d, 0x00, 0x30, + 0x81, 0x89, 0x02, 0x81, 0x81, 0x00, 0xb1, 0xe0, 0x59, 0x6a, 0x19, 0x08, + 0x0d, 0x21, 0x98, 0x79, 0x96, 0x16, 0x2a, 0x5a, 0x5c, 0x20, 0xeb, 0x66, + 0x1e, 0x9e, 0x1e, 0xc4, 0xef, 0x83, 0x42, 0x15, 0xd8, 0x4b, 0x14, 0xd3, + 0xe7, 0xba, 0xc8, 0xf6, 0xb4, 0x52, 0xdf, 0x18, 0xa6, 0x6b, 0x8b, 0xca, + 0x84, 0xdc, 0x21, 0x26, 0xfd, 0x7c, 0xde, 0xbd, 0x2b, 0x64, 0x0d, 0xd3, + 0x20, 0x7c, 0xe7, 0x0c, 0xfc, 0x3c, 0xa9, 0x09, 0xc0, 0xa7, 0x78, 0x3d, + 0xe9, 0x48, 0x50, 0x90, 0xd7, 0x3e, 0x46, 0x78, 0x8f, 0xfc, 0xc8, 0xb6, + 0x89, 0x41, 0x49, 0x15, 0x47, 0x27, 0x4b, 0x46, 0xcb, 0x11, 0x82, 0xd8, + 0x7b, 0x68, 0xb7, 0xc5, 0x64, 0x70, 0xaf, 0xe6, 0x80, 0x63, 0xfe, 0x53, + 0x70, 0xee, 0xd2, 0xa9, 0x2c, 0x40, 0x96, 0x9c, 0xd4, 0xa1, 0xcf, 0xd4, + 0x51, 0x9d, 0xe1, 0xa7, 0xf0, 0xfb, 0xa6, 0x49, 0x4c, 0x00, 0x05, 0xff, + 0x8f, 0x61, 0x02, 0x03, 0x01, 0x00, 0x01, 0xa3, 0x82, 0x01, 0x02, 0x30, + 0x81, 0xff, 0x30, 0x1d, 0x06, 0x03, 0x55, 0x1d, 0x0e, 0x04, 0x16, 0x04, + 0x14, 0xf1, 0x67, 0xe6, 0xd7, 0x73, 0xe7, 0x12, 0x0a, 0xe1, 0xc3, 0x5f, + 0x34, 0x97, 0x23, 0x0d, 0xa0, 0xc6, 0x7e, 0x10, 0xe8, 0x30, 0x81, 0xcf, + 0x06, 0x03, 0x55, 0x1d, 0x23, 0x04, 0x81, 0xc7, 0x30, 0x81, 0xc4, 0x80, + 0x14, 0xf1, 0x67, 0xe6, 0xd7, 0x73, 0xe7, 0x12, 0x0a, 0xe1, 0xc3, 0x5f, + 0x34, 0x97, 0x23, 0x0d, 0xa0, 0xc6, 0x7e, 0x10, 0xe8, 0xa1, 0x81, 0xa0, + 0xa4, 0x81, 0x9d, 0x30, 0x81, 0x9a, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, + 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x4b, 0x31, 0x0d, 0x30, 0x0b, 0x06, + 0x03, 0x55, 0x04, 0x08, 0x13, 0x04, 0x54, 0x65, 0x73, 0x74, 0x31, 0x12, + 0x30, 0x10, 0x06, 0x03, 0x55, 0x04, 0x07, 0x13, 0x09, 0x54, 0x65, 0x73, + 0x74, 0x76, 0x69, 0x6c, 0x6c, 0x65, 0x31, 0x17, 0x30, 0x15, 0x06, 0x03, + 0x55, 0x04, 0x0a, 0x13, 0x0e, 0x4e, 0x6f, 0x69, 0x73, 0x79, 0x20, 0x41, + 0x74, 0x6f, 0x6d, 0x20, 0x4c, 0x74, 0x64, 0x31, 0x11, 0x30, 0x0f, 0x06, + 0x03, 0x55, 0x04, 0x0b, 0x14, 0x08, 0x53, 0x65, 0x63, 0x75, 0x69, 0x72, + 0x08, 0x08, 0x31, 0x15, 0x30, 0x13, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, + 0x0c, 0x41, 0x73, 0x68, 0x6c, 0x65, 0x79, 0x20, 0x4d, 0x69, 0x6c, 0x6c, + 0x73, 0x31, 0x25, 0x30, 0x23, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, + 0x0d, 0x01, 0x09, 0x01, 0x16, 0x16, 0x61, 0x73, 0x68, 0x6c, 0x65, 0x79, + 0x40, 0x61, 0x73, 0x68, 0x6c, 0x65, 0x79, 0x6d, 0x69, 0x6c, 0x6c, 0x73, + 0x2e, 0x63, 0x6f, 0x6d, 0x82, 0x09, 0x00, 0xe1, 0x40, 0xf0, 0x81, 0x55, + 0x5d, 0xa4, 0x8f, 0x30, 0x0c, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x04, 0x05, + 0x30, 0x03, 0x01, 0x01, 0xff, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, + 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x05, 0x05, 0x00, 0x03, 0x81, 0x81, 0x00, + 0x89, 0x79, 0xf2, 0xa8, 0xd3, 0xc7, 0x02, 0x2d, 0x02, 0x68, 0x9a, 0xf1, + 0xa7, 0x10, 0xa2, 0x2c, 0x52, 0x12, 0xf2, 0x97, 0x39, 0x52, 0x83, 0x69, + 0xd7, 0xe7, 0x73, 0x1f, 0xf1, 0x02, 0x5e, 0xbe, 0x5f, 0xbe, 0x94, 0xa9, + 0x4d, 0x8f, 0xb7, 0x3c, 0x52, 0x35, 0x09, 0x0a, 0x69, 0xed, 0x5e, 0x12, + 0xc9, 0x4d, 0x59, 0xec, 0x47, 0xfa, 0x82, 0xe5, 0x79, 0xbc, 0x17, 0x9d, + 0xae, 0x02, 0x17, 0xb5, 0xfb, 0xca, 0xc7, 0x42, 0xf4, 0xb5, 0x48, 0x19, + 0x1c, 0xd4, 0xd6, 0xfb, 0x2a, 0x7b, 0x0e, 0x8b, 0x56, 0xcc, 0x8e, 0x7a, + 0xa8, 0xaf, 0x4e, 0x5a, 0xa1, 0xf1, 0x78, 0x37, 0x4d, 0x09, 0x03, 0x9a, + 0xde, 0x4c, 0x87, 0xbe, 0xb1, 0x93, 0x1a, 0x39, 0x9a, 0xbb, 0xa0, 0x5c, + 0xfe, 0x58, 0x71, 0x62, 0x20, 0x74, 0x04, 0xc5, 0x50, 0x6e, 0x7b, 0xad, + 0xbe, 0xb0, 0xaa, 0x64, 0xea, 0x48, 0xa7, 0x9f +}; +unsigned int default_certificate_len = 956; + +#endif diff --git a/features/unsupported/net/https/axTLS/ssl/config.h b/features/unsupported/net/https/axTLS/ssl/config.h new file mode 100644 index 00000000000..f4f4b1422fd --- /dev/null +++ b/features/unsupported/net/https/axTLS/ssl/config.h @@ -0,0 +1,62 @@ +#ifndef CONFIG_H +#define CONFIG_H +#define CONFIG_DEBUG +#define CONFIG_STRIP_UNWANTED_SECTIONS 1 + +/* + * BigInt Options + */ +#define CONFIG_BIGINT_BARRETT 1 +#define CONFIG_BIGINT_CRT 1 +#define CONFIG_INTEGER_32BIT 1 + +/* + * SSL Library + */ +#define CONFIG_SSL_ENABLE_CLIENT 1 +//#define CONFIG_SSL_SKELETON_MODE +#define CONFIG_SSL_PROT_LOW 1 +//#undef CONFIG_SSL_PROT_MEDIUM +//#undef CONFIG_SSL_PROT_HIGH +#define CONFIG_SSL_USE_DEFAULT_KEY 1 +#define CONFIG_SSL_PRIVATE_KEY_LOCATION "" +#define CONFIG_SSL_PRIVATE_KEY_PASSWORD "" +#define CONFIG_SSL_X509_CERT_LOCATION "" +#undef CONFIG_SSL_GENERATE_X509_CERT +#define CONFIG_SSL_X509_COMMON_NAME "" +#define CONFIG_SSL_X509_ORGANIZATION_NAME "" +#define CONFIG_SSL_X509_ORGANIZATION_UNIT_NAME "" +#undef CONFIG_SSL_ENABLE_V23_HANDSHAKE +#undef CONFIG_SSL_HAS_PEM +#undef CONFIG_SSL_USE_PKCS12 +#define CONFIG_SSL_EXPIRY_TIME 24 +#define CONFIG_X509_MAX_CA_CERTS 1 +#define CONFIG_SSL_MAX_CERTS 1 +#undef CONFIG_SSL_CTX_MUTEXING +#undef CONFIG_USE_DEV_URANDOM +#undef CONFIG_WIN32_USE_CRYPTO_LIB +#undef CONFIG_OPENSSL_COMPATIBLE +#undef CONFIG_PERFORMANCE_TESTING +#undef CONFIG_SSL_TEST +#undef CONFIG_AXTLSWRAP +#undef CONFIG_AXHTTPD +#undef CONFIG_HTTP_STATIC_BUILD +#undef CONFIG_HTTP_HAS_CGI +#define CONFIG_HTTP_CGI_EXTENSIONS "" +#undef CONFIG_HTTP_ENABLE_LUA +#define CONFIG_HTTP_LUA_PREFIX "" +#undef CONFIG_HTTP_BUILD_LUA +#define CONFIG_HTTP_CGI_LAUNCHER "" +#undef CONFIG_HTTP_DIRECTORIES +#undef CONFIG_HTTP_HAS_AUTHORIZATION +#undef CONFIG_HTTP_HAS_IPV6 +#undef CONFIG_HTTP_ENABLE_DIFFERENT_USER +#define CONFIG_HTTP_USER "" +#undef CONFIG_HTTP_VERBOSE +#undef CONFIG_HTTP_IS_DAEMON +#define CONFIG_SSL_CERT_VERIFICATION +#define CONFIG_SSL_FULL_MODE + +#define MBED + +#endif diff --git a/features/unsupported/net/https/axTLS/ssl/crypto_misc.h b/features/unsupported/net/https/axTLS/ssl/crypto_misc.h new file mode 100644 index 00000000000..5c50a11b27f --- /dev/null +++ b/features/unsupported/net/https/axTLS/ssl/crypto_misc.h @@ -0,0 +1,176 @@ +/* + * Copyright (c) 2007, Cameron Rich + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * * Neither the name of the axTLS project nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +/** + * @file crypto_misc.h + */ + +#ifndef HEADER_CRYPTO_MISC_H +#define HEADER_CRYPTO_MISC_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include "crypto.h" +#include "bigint.h" +#include "config.h" + +/************************************************************************** + * X509 declarations + **************************************************************************/ +#define X509_OK 0 +#define X509_NOT_OK -1 +#define X509_VFY_ERROR_NO_TRUSTED_CERT -2 +#define X509_VFY_ERROR_BAD_SIGNATURE -3 +#define X509_VFY_ERROR_NOT_YET_VALID -4 +#define X509_VFY_ERROR_EXPIRED -5 +#define X509_VFY_ERROR_SELF_SIGNED -6 +#define X509_VFY_ERROR_INVALID_CHAIN -7 +#define X509_VFY_ERROR_UNSUPPORTED_DIGEST -8 +#define X509_INVALID_PRIV_KEY -9 + +/* + * The Distinguished Name + */ +#define X509_NUM_DN_TYPES 3 +#define X509_COMMON_NAME 0 +#define X509_ORGANIZATION 1 +#define X509_ORGANIZATIONAL_UNIT 2 + +#include + +struct _x509_ctx +{ + char *ca_cert_dn[X509_NUM_DN_TYPES]; + char *cert_dn[X509_NUM_DN_TYPES]; + char **subject_alt_dnsnames; + time_t not_before; + time_t not_after; + uint8_t *signature; + uint16_t sig_len; + uint8_t sig_type; + RSA_CTX *rsa_ctx; + bigint *digest; + struct _x509_ctx *next; +}; + +typedef struct _x509_ctx X509_CTX; +typedef struct +{ + X509_CTX *cert[CONFIG_X509_MAX_CA_CERTS]; +} CA_CERT_CTX; +#ifdef CONFIG_SSL_CERT_VERIFICATION + +#endif + +int x509_new(const uint8_t *cert, int *len, X509_CTX **ctx); +void x509_free(X509_CTX *x509_ctx); +int x509_verify(const CA_CERT_CTX *ca_cert_ctx, const X509_CTX *cert); + +#ifdef CONFIG_SSL_CERT_VERIFICATION +#endif +#ifdef CONFIG_SSL_FULL_MODE +void x509_print(const X509_CTX *cert, CA_CERT_CTX *ca_cert_ctx); +const char * x509_display_error(int error); +#endif + +/************************************************************************** + * ASN1 declarations + **************************************************************************/ +#define ASN1_INTEGER 0x02 +#define ASN1_BIT_STRING 0x03 +#define ASN1_OCTET_STRING 0x04 +#define ASN1_NULL 0x05 +#define ASN1_PRINTABLE_STR2 0x0C +#define ASN1_OID 0x06 +#define ASN1_PRINTABLE_STR2 0x0C +#define ASN1_PRINTABLE_STR 0x13 +#define ASN1_TELETEX_STR 0x14 +#define ASN1_IA5_STR 0x16 +#define ASN1_UTC_TIME 0x17 +#define ASN1_UNICODE_STR 0x1e +#define ASN1_SEQUENCE 0x30 +#define ASN1_CONTEXT_DNSNAME 0x82 +#define ASN1_SET 0x31 +#define ASN1_V3_DATA 0xa3 +#define ASN1_IMPLICIT_TAG 0x80 +#define ASN1_CONTEXT_DNSNAME 0x82 +#define ASN1_EXPLICIT_TAG 0xa0 +#define ASN1_V3_DATA 0xa3 + +#define SIG_TYPE_MD2 0x02 +#define SIG_TYPE_MD5 0x04 +#define SIG_TYPE_SHA1 0x05 + +int get_asn1_length(const uint8_t *buf, int *offset); +int asn1_get_private_key(const uint8_t *buf, int len, RSA_CTX **rsa_ctx); +int asn1_next_obj(const uint8_t *buf, int *offset, int obj_type); +int asn1_skip_obj(const uint8_t *buf, int *offset, int obj_type); +int asn1_get_int(const uint8_t *buf, int *offset, uint8_t **object); +int asn1_version(const uint8_t *cert, int *offset, X509_CTX *x509_ctx); +int asn1_validity(const uint8_t *cert, int *offset, X509_CTX *x509_ctx); +int asn1_name(const uint8_t *cert, int *offset, char *dn[]); +int asn1_public_key(const uint8_t *cert, int *offset, X509_CTX *x509_ctx); +#ifdef CONFIG_SSL_CERT_VERIFICATION +int asn1_signature(const uint8_t *cert, int *offset, X509_CTX *x509_ctx); +int asn1_find_subjectaltname(const uint8_t* cert, int offset); +int asn1_compare_dn(char * const dn1[], char * const dn2[]); +#endif /* CONFIG_SSL_CERT_VERIFICATION */ +int asn1_signature_type(const uint8_t *cert, + int *offset, X509_CTX *x509_ctx); + +/************************************************************************** + * MISC declarations + **************************************************************************/ +#define SALT_SIZE 8 + +extern const char * const unsupported_str; + +typedef void (*crypt_func)(void *, const uint8_t *, uint8_t *, int); +typedef void (*hmac_func)(const uint8_t *msg, int length, const uint8_t *key, + int key_len, uint8_t *digest); + +int get_file(const char *filename, uint8_t **buf); + +#if defined(CONFIG_SSL_FULL_MODE) || defined(WIN32) || defined(CONFIG_DEBUG) +EXP_FUNC void STDCALL print_blob(const char *format, const uint8_t *data, int size, ...); +#else + #define print_blob(...) +#endif + +EXP_FUNC int STDCALL base64_decode(const char *in, int len, + uint8_t *out, int *outlen); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/features/unsupported/net/https/axTLS/ssl/gen_cert.c b/features/unsupported/net/https/axTLS/ssl/gen_cert.c new file mode 100644 index 00000000000..c2fe381eb94 --- /dev/null +++ b/features/unsupported/net/https/axTLS/ssl/gen_cert.c @@ -0,0 +1,364 @@ +/* + * Copyright (c) 2007, Cameron Rich + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * * Neither the name of the axTLS project nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" + +#ifdef CONFIG_SSL_GENERATE_X509_CERT +#include +#include +#include "os_port.h" +#include "ssl.h" + +/** + * Generate a basic X.509 certificate + */ + +static uint8_t set_gen_length(int len, uint8_t *buf, int *offset) +{ + if (len < 0x80) /* short form */ + { + buf[(*offset)++] = len; + return 1; + } + else /* long form */ + { + int i, length_bytes = 0; + + if (len & 0x00FF0000) + length_bytes = 3; + else if (len & 0x0000FF00) + length_bytes = 2; + else if (len & 0x000000FF) + length_bytes = 1; + + buf[(*offset)++] = 0x80 + length_bytes; + + for (i = length_bytes-1; i >= 0; i--) + { + buf[*offset+i] = len & 0xFF; + len >>= 8; + } + + *offset += length_bytes; + return length_bytes+1; + } +} + +static int pre_adjust_with_size(uint8_t type, + int *seq_offset, uint8_t *buf, int *offset) +{ + buf[(*offset)++] = type; + *seq_offset = *offset; + *offset += 4; /* fill in later */ + return *offset; +} + +static void adjust_with_size(int seq_size, int seq_start, + uint8_t *buf, int *offset) +{ + uint8_t seq_byte_size; + int orig_seq_size = seq_size; + int orig_seq_start = seq_start; + + seq_size = *offset-seq_size; + seq_byte_size = set_gen_length(seq_size, buf, &seq_start); + + if (seq_byte_size != 4) + { + memmove(&buf[orig_seq_start+seq_byte_size], + &buf[orig_seq_size], seq_size); + *offset -= 4-seq_byte_size; + } +} + +static void gen_serial_number(uint8_t *buf, int *offset) +{ + static const uint8_t ser_oid[] = { ASN1_INTEGER, 1, 0x7F }; + memcpy(&buf[*offset], ser_oid , sizeof(ser_oid)); + *offset += sizeof(ser_oid); +} + +static void gen_signature_alg(uint8_t *buf, int *offset) +{ + /* OBJECT IDENTIFIER sha1withRSAEncryption (1 2 840 113549 1 1 5) */ + static const uint8_t sig_oid[] = + { + ASN1_SEQUENCE, 0x0d, ASN1_OID, 0x09, + 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x05, + ASN1_NULL, 0x00 + }; + + memcpy(&buf[*offset], sig_oid, sizeof(sig_oid)); + *offset += sizeof(sig_oid); +} + +static int gen_dn(const char *name, uint8_t dn_type, + uint8_t *buf, int *offset) +{ + int ret = X509_OK; + int name_size = strlen(name); + + if (name_size > 0x70) /* just too big */ + { + ret = X509_NOT_OK; + goto error; + } + + buf[(*offset)++] = ASN1_SET; + set_gen_length(9+name_size, buf, offset); + buf[(*offset)++] = ASN1_SEQUENCE; + set_gen_length(7+name_size, buf, offset); + buf[(*offset)++] = ASN1_OID; + buf[(*offset)++] = 3; + buf[(*offset)++] = 0x55; + buf[(*offset)++] = 0x04; + buf[(*offset)++] = dn_type; + buf[(*offset)++] = ASN1_PRINTABLE_STR; + buf[(*offset)++] = name_size; + strcpy(&buf[*offset], name); + *offset += name_size; + +error: + return ret; +} + +static int gen_issuer(const char * dn[], uint8_t *buf, int *offset) +{ + int ret = X509_OK; + int seq_offset; + int seq_size = pre_adjust_with_size( + ASN1_SEQUENCE, &seq_offset, buf, offset); + char fqdn[128]; + + /* we need the common name, so if not configured, work out the fully + * qualified domain name */ + if (dn[X509_COMMON_NAME] == NULL || strlen(dn[X509_COMMON_NAME]) == 0) + { + int fqdn_len; + gethostname(fqdn, sizeof(fqdn)); + fqdn_len = strlen(fqdn); + fqdn[fqdn_len++] = '.'; + getdomainname(&fqdn[fqdn_len], sizeof(fqdn)-fqdn_len); + fqdn_len = strlen(fqdn); + + if (fqdn[fqdn_len-1] == '.') /* ensure '.' is not last char */ + fqdn[fqdn_len-1] = 0; + + dn[X509_COMMON_NAME] = fqdn; + } + + if ((ret = gen_dn(dn[X509_COMMON_NAME], 3, buf, offset))) + goto error; + + if (dn[X509_ORGANIZATION] != NULL && strlen(dn[X509_ORGANIZATION]) > 0) + { + if ((ret = gen_dn(dn[X509_ORGANIZATION], 10, buf, offset))) + goto error; + } + + if (dn[X509_ORGANIZATIONAL_UNIT] != NULL && + strlen(dn[X509_ORGANIZATIONAL_UNIT]) > 0) + { + if ((ret = gen_dn(dn[X509_ORGANIZATIONAL_UNIT], 11, buf, offset))) + goto error; + } + + adjust_with_size(seq_size, seq_offset, buf, offset); + +error: + return ret; +} + +static void gen_utc_time(uint8_t *buf, int *offset) +{ + static const uint8_t time_seq[] = + { + ASN1_SEQUENCE, 30, + ASN1_UTC_TIME, 13, + '0', '7', '0', '1', '0', '1', '0', '0', '0', '0', '0', '0', 'Z', + ASN1_UTC_TIME, 13, /* make it good for 30 or so years */ + '3', '8', '0', '1', '0', '1', '0', '0', '0', '0', '0', '0', 'Z' + }; + + /* fixed time */ + memcpy(&buf[*offset], time_seq, sizeof(time_seq)); + *offset += sizeof(time_seq); +} + +static void gen_pub_key2(const RSA_CTX *rsa_ctx, uint8_t *buf, int *offset) +{ + static const uint8_t pub_key_seq[] = + { + ASN1_INTEGER, 0x03, 0x01, 0x00, 0x01 /* INTEGER 65537 */ + }; + + int seq_offset; + int pub_key_size = rsa_ctx->num_octets; + uint8_t *block = (uint8_t *)alloca(pub_key_size); + int seq_size = pre_adjust_with_size( + ASN1_SEQUENCE, &seq_offset, buf, offset); + buf[(*offset)++] = ASN1_INTEGER; + bi_export(rsa_ctx->bi_ctx, rsa_ctx->m, block, pub_key_size); + + if (*block & 0x80) /* make integer positive */ + { + set_gen_length(pub_key_size+1, buf, offset); + buf[(*offset)++] = 0; + } + else + set_gen_length(pub_key_size, buf, offset); + + memcpy(&buf[*offset], block, pub_key_size); + *offset += pub_key_size; + memcpy(&buf[*offset], pub_key_seq, sizeof(pub_key_seq)); + *offset += sizeof(pub_key_seq); + adjust_with_size(seq_size, seq_offset, buf, offset); +} + +static void gen_pub_key1(const RSA_CTX *rsa_ctx, uint8_t *buf, int *offset) +{ + int seq_offset; + int seq_size = pre_adjust_with_size( + ASN1_BIT_STRING, &seq_offset, buf, offset); + buf[(*offset)++] = 0; /* bit string is multiple of 8 */ + gen_pub_key2(rsa_ctx, buf, offset); + adjust_with_size(seq_size, seq_offset, buf, offset); +} + +static void gen_pub_key(const RSA_CTX *rsa_ctx, uint8_t *buf, int *offset) +{ + /* OBJECT IDENTIFIER rsaEncryption (1 2 840 113549 1 1 1) */ + static const uint8_t rsa_enc_oid[] = + { + ASN1_SEQUENCE, 0x0d, ASN1_OID, 0x09, + 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, + ASN1_NULL, 0x00 + }; + + int seq_offset; + int seq_size = pre_adjust_with_size( + ASN1_SEQUENCE, &seq_offset, buf, offset); + + memcpy(&buf[*offset], rsa_enc_oid, sizeof(rsa_enc_oid)); + *offset += sizeof(rsa_enc_oid); + gen_pub_key1(rsa_ctx, buf, offset); + adjust_with_size(seq_size, seq_offset, buf, offset); +} + +static void gen_signature(const RSA_CTX *rsa_ctx, const uint8_t *sha_dgst, + uint8_t *buf, int *offset) +{ + static const uint8_t asn1_sig[] = + { + ASN1_SEQUENCE, 0x21, ASN1_SEQUENCE, 0x09, ASN1_OID, 0x05, + 0x2b, 0x0e, 0x03, 0x02, 0x1a, /* sha1 (1 3 14 3 2 26) */ + ASN1_NULL, 0x00, ASN1_OCTET_STRING, 0x14 + }; + + uint8_t *enc_block = (uint8_t *)alloca(rsa_ctx->num_octets); + uint8_t *block = (uint8_t *)alloca(sizeof(asn1_sig) + SHA1_SIZE); + int sig_size; + + /* add the digest as an embedded asn.1 sequence */ + memcpy(block, asn1_sig, sizeof(asn1_sig)); + memcpy(&block[sizeof(asn1_sig)], sha_dgst, SHA1_SIZE); + + sig_size = RSA_encrypt(rsa_ctx, block, + sizeof(asn1_sig) + SHA1_SIZE, enc_block, 1); + + buf[(*offset)++] = ASN1_BIT_STRING; + set_gen_length(sig_size+1, buf, offset); + buf[(*offset)++] = 0; /* bit string is multiple of 8 */ + memcpy(&buf[*offset], enc_block, sig_size); + *offset += sig_size; +} + +static int gen_tbs_cert(const char * dn[], + const RSA_CTX *rsa_ctx, uint8_t *buf, int *offset, + uint8_t *sha_dgst) +{ + int ret = X509_OK; + SHA1_CTX sha_ctx; + int seq_offset; + int begin_tbs = *offset; + int seq_size = pre_adjust_with_size( + ASN1_SEQUENCE, &seq_offset, buf, offset); + + gen_serial_number(buf, offset); + gen_signature_alg(buf, offset); + + /* CA certicate issuer */ + if ((ret = gen_issuer(dn, buf, offset))) + goto error; + + gen_utc_time(buf, offset); + + /* certificate issuer */ + if ((ret = gen_issuer(dn, buf, offset))) + goto error; + + gen_pub_key(rsa_ctx, buf, offset); + adjust_with_size(seq_size, seq_offset, buf, offset); + + SHA1_Init(&sha_ctx); + SHA1_Update(&sha_ctx, &buf[begin_tbs], *offset-begin_tbs); + SHA1_Final(sha_dgst, &sha_ctx); + +error: + return ret; +} + +/** + * Create a new certificate. + */ +EXP_FUNC int STDCALL ssl_x509_create(SSL_CTX *ssl_ctx, uint32_t options, const char * dn[], uint8_t **cert_data) +{ + int ret = X509_OK, offset = 0, seq_offset; + /* allocate enough space to load a new certificate */ + uint8_t *buf = (uint8_t *)alloca(ssl_ctx->rsa_ctx->num_octets*2 + 512); + uint8_t sha_dgst[SHA1_SIZE]; + int seq_size = pre_adjust_with_size(ASN1_SEQUENCE, + &seq_offset, buf, &offset); + + if ((ret = gen_tbs_cert(dn, ssl_ctx->rsa_ctx, buf, &offset, sha_dgst)) < 0) + goto error; + + gen_signature_alg(buf, &offset); + gen_signature(ssl_ctx->rsa_ctx, sha_dgst, buf, &offset); + adjust_with_size(seq_size, seq_offset, buf, &offset); + *cert_data = (uint8_t *)malloc(offset); /* create the exact memory for it */ + memcpy(*cert_data, buf, offset); + +error: + return ret < 0 ? ret : offset; +} + +#endif + diff --git a/features/unsupported/net/https/axTLS/ssl/loader.c b/features/unsupported/net/https/axTLS/ssl/loader.c new file mode 100644 index 00000000000..8cc80d9c77e --- /dev/null +++ b/features/unsupported/net/https/axTLS/ssl/loader.c @@ -0,0 +1,480 @@ +/* + * Copyright (c) 2007, Cameron Rich + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * * Neither the name of the axTLS project nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * Load certificates/keys into memory. These can be in many different formats. + * PEM support and other formats can be processed here. + * + * The PEM private keys may be optionally encrypted with AES128 or AES256. + * The encrypted PEM keys were generated with something like: + * + * openssl genrsa -aes128 -passout pass:abcd -out axTLS.key_aes128.pem 512 + */ + +#include +#include +#include +#include "os_port.h" +#include "ssl.h" +#include "config.h" + +static int do_obj(SSL_CTX *ssl_ctx, int obj_type, + SSLObjLoader *ssl_obj, const char *password); +#ifdef CONFIG_SSL_HAS_PEM +static int ssl_obj_PEM_load(SSL_CTX *ssl_ctx, int obj_type, + SSLObjLoader *ssl_obj, const char *password); +#endif + +/* + * Load a file into memory that is in binary DER (or ascii PEM) format. + */ +EXP_FUNC int STDCALL ssl_obj_load(SSL_CTX *ssl_ctx, int obj_type, + const char *filename, const char *password) +{ +#ifndef CONFIG_SSL_SKELETON_MODE + static const char * const begin = "-----BEGIN"; + int ret = SSL_OK; + SSLObjLoader *ssl_obj = NULL; + + if (filename == NULL) + { + ret = SSL_ERROR_INVALID_KEY; + goto error; + } + + ssl_obj = (SSLObjLoader *)calloc(1, sizeof(SSLObjLoader)); + ssl_obj->len = get_file(filename, &ssl_obj->buf); + if (ssl_obj->len <= 0) + { + ret = SSL_ERROR_INVALID_KEY; + goto error; + } + + /* is the file a PEM file? */ + if (strstr((char *)ssl_obj->buf, begin) != NULL) + { +#ifdef CONFIG_SSL_HAS_PEM + ret = ssl_obj_PEM_load(ssl_ctx, obj_type, ssl_obj, password); +#else + printf(unsupported_str); + ret = SSL_ERROR_NOT_SUPPORTED; +#endif + } + else + ret = do_obj(ssl_ctx, obj_type, ssl_obj, password); + +error: + ssl_obj_free(ssl_obj); + return ret; +#else + printf(unsupported_str); + return SSL_ERROR_NOT_SUPPORTED; +#endif /* CONFIG_SSL_SKELETON_MODE */ +} + +/* + * Transfer binary data into the object loader. + */ +EXP_FUNC int STDCALL ssl_obj_memory_load(SSL_CTX *ssl_ctx, int mem_type, + const uint8_t *data, int len, const char *password) +{ + int ret; + SSLObjLoader ssl_obj; + ssl_obj.buf = data; + ssl_obj.len = len; + ret = do_obj(ssl_ctx, mem_type, &ssl_obj, password); + + return ret; +} + +/* + * Actually work out what we are doing + */ +static int do_obj(SSL_CTX *ssl_ctx, int obj_type, + SSLObjLoader *ssl_obj, const char *password) +{ + int ret = SSL_OK; + + switch (obj_type) + { + case SSL_OBJ_RSA_KEY: + ret = add_private_key(ssl_ctx, ssl_obj); + break; + + case SSL_OBJ_X509_CERT: + ret = add_cert(ssl_ctx, ssl_obj->buf, ssl_obj->len); + break; + +#ifdef CONFIG_SSL_CERT_VERIFICATION + case SSL_OBJ_X509_CACERT: + add_cert_auth(ssl_ctx, ssl_obj->buf, ssl_obj->len); + break; +#endif + +#ifdef CONFIG_SSL_USE_PKCS12 + case SSL_OBJ_PKCS8: + ret = pkcs8_decode(ssl_ctx, ssl_obj, password); + break; + + case SSL_OBJ_PKCS12: + ret = pkcs12_decode(ssl_ctx, ssl_obj, password); + break; +#endif + default: + printf(unsupported_str); + ret = SSL_ERROR_NOT_SUPPORTED; + break; + } + + return ret; +} + +/* + * Clean up our mess. + */ +void ssl_obj_free(SSLObjLoader *ssl_obj) +{ + if (ssl_obj) + { + free(ssl_obj->buf); + free(ssl_obj); + } +} + +/* + * Support for PEM encoded keys/certificates. + */ +#ifdef CONFIG_SSL_HAS_PEM + +#define NUM_PEM_TYPES 4 +#define IV_SIZE 16 +#define IS_RSA_PRIVATE_KEY 0 +#define IS_ENCRYPTED_PRIVATE_KEY 1 +#define IS_PRIVATE_KEY 2 +#define IS_CERTIFICATE 3 + +static const char * const begins[NUM_PEM_TYPES] = +{ + "-----BEGIN RSA PRIVATE KEY-----", + "-----BEGIN ENCRYPTED PRIVATE KEY-----", + "-----BEGIN PRIVATE KEY-----", + "-----BEGIN CERTIFICATE-----", +}; + +static const char * const ends[NUM_PEM_TYPES] = +{ + "-----END RSA PRIVATE KEY-----", + "-----END ENCRYPTED PRIVATE KEY-----", + "-----END PRIVATE KEY-----", + "-----END CERTIFICATE-----", +}; + +static const char * const aes_str[2] = +{ + "DEK-Info: AES-128-CBC,", + "DEK-Info: AES-256-CBC," +}; + +/** + * Take a base64 blob of data and decrypt it (using AES) into its + * proper ASN.1 form. + */ +static int pem_decrypt(const char *where, const char *end, + const char *password, SSLObjLoader *ssl_obj) +{ + int ret = -1; + int is_aes_256 = 0; + char *start = NULL; + uint8_t iv[IV_SIZE]; + int i, pem_size; + MD5_CTX md5_ctx; + AES_CTX aes_ctx; + uint8_t key[32]; /* AES256 size */ + + if (password == NULL || strlen(password) == 0) + { +#ifdef CONFIG_SSL_FULL_MODE + printf("Error: Need a password for this PEM file\n"); TTY_FLUSH(); +#endif + goto error; + } + + if ((start = strstr((const char *)where, aes_str[0]))) /* AES128? */ + { + start += strlen(aes_str[0]); + } + else if ((start = strstr((const char *)where, aes_str[1]))) /* AES256? */ + { + is_aes_256 = 1; + start += strlen(aes_str[1]); + } + else + { +#ifdef CONFIG_SSL_FULL_MODE + printf("Error: Unsupported password cipher\n"); TTY_FLUSH(); +#endif + goto error; + } + + /* convert from hex to binary - assumes uppercase hex */ + for (i = 0; i < IV_SIZE; i++) + { + char c = *start++ - '0'; + iv[i] = (c > 9 ? c + '0' - 'A' + 10 : c) << 4; + c = *start++ - '0'; + iv[i] += (c > 9 ? c + '0' - 'A' + 10 : c); + } + + while (*start == '\r' || *start == '\n') + start++; + + /* turn base64 into binary */ + pem_size = (int)(end-start); + if (base64_decode(start, pem_size, ssl_obj->buf, &ssl_obj->len) != 0) + goto error; + + /* work out the key */ + MD5_Init(&md5_ctx); + MD5_Update(&md5_ctx, (const uint8_t *)password, strlen(password)); + MD5_Update(&md5_ctx, iv, SALT_SIZE); + MD5_Final(key, &md5_ctx); + + if (is_aes_256) + { + MD5_Init(&md5_ctx); + MD5_Update(&md5_ctx, key, MD5_SIZE); + MD5_Update(&md5_ctx, (const uint8_t *)password, strlen(password)); + MD5_Update(&md5_ctx, iv, SALT_SIZE); + MD5_Final(&key[MD5_SIZE], &md5_ctx); + } + + /* decrypt using the key/iv */ + AES_set_key(&aes_ctx, key, iv, is_aes_256 ? AES_MODE_256 : AES_MODE_128); + AES_convert_key(&aes_ctx); + AES_cbc_decrypt(&aes_ctx, ssl_obj->buf, ssl_obj->buf, ssl_obj->len); + ret = 0; + +error: + return ret; +} + +/** + * Take a base64 blob of data and turn it into its proper ASN.1 form. + */ +static int new_pem_obj(SSL_CTX *ssl_ctx, int is_cacert, char *where, + int remain, const char *password) +{ + int ret = SSL_ERROR_BAD_CERTIFICATE; + SSLObjLoader *ssl_obj = NULL; + + while (remain > 0) + { + int i, pem_size, obj_type; + char *start = NULL, *end = NULL; + + for (i = 0; i < NUM_PEM_TYPES; i++) + { + if ((start = strstr(where, begins[i])) && + (end = strstr(where, ends[i]))) + { + remain -= (int)(end-where); + start += strlen(begins[i]); + pem_size = (int)(end-start); + + ssl_obj = (SSLObjLoader *)calloc(1, sizeof(SSLObjLoader)); + + /* 4/3 bigger than what we need but so what */ + ssl_obj->buf = (uint8_t *)calloc(1, pem_size); + ssl_obj->len = pem_size; + + if (i == IS_RSA_PRIVATE_KEY && + strstr(start, "Proc-Type:") && + strstr(start, "4,ENCRYPTED")) + { + /* check for encrypted PEM file */ + if (pem_decrypt(start, end, password, ssl_obj) < 0) + { + ret = SSL_ERROR_BAD_CERTIFICATE; + goto error; + } + } + else + { + ssl_obj->len = pem_size; + if (base64_decode(start, pem_size, + ssl_obj->buf, &ssl_obj->len) != 0) + { + ret = SSL_ERROR_BAD_CERTIFICATE; + goto error; + } + } + + switch (i) + { + case IS_RSA_PRIVATE_KEY: + obj_type = SSL_OBJ_RSA_KEY; + break; + + case IS_ENCRYPTED_PRIVATE_KEY: + case IS_PRIVATE_KEY: + obj_type = SSL_OBJ_PKCS8; + break; + + case IS_CERTIFICATE: + obj_type = is_cacert ? + SSL_OBJ_X509_CACERT : SSL_OBJ_X509_CERT; + break; + + default: + ret = SSL_ERROR_BAD_CERTIFICATE; + goto error; + } + + /* In a format we can now understand - so process it */ + if ((ret = do_obj(ssl_ctx, obj_type, ssl_obj, password))) + goto error; + + end += strlen(ends[i]); + remain -= strlen(ends[i]); + while (remain > 0 && (*end == '\r' || *end == '\n')) + { + end++; + remain--; + } + + where = end; + break; + } + } + + ssl_obj_free(ssl_obj); + ssl_obj = NULL; + if (start == NULL) + break; + } +error: + ssl_obj_free(ssl_obj); + return ret; +} + +/* + * Load a file into memory that is in ASCII PEM format. + */ +static int ssl_obj_PEM_load(SSL_CTX *ssl_ctx, int obj_type, + SSLObjLoader *ssl_obj, const char *password) +{ + char *start; + + /* add a null terminator */ + ssl_obj->len++; + ssl_obj->buf = (uint8_t *)realloc(ssl_obj->buf, ssl_obj->len); + ssl_obj->buf[ssl_obj->len-1] = 0; + start = (char *)ssl_obj->buf; + return new_pem_obj(ssl_ctx, obj_type == SSL_OBJ_X509_CACERT, + start, ssl_obj->len, password); +} +#endif /* CONFIG_SSL_HAS_PEM */ + +/** + * Load the key/certificates in memory depending on compile-time and user + * options. + */ +int load_key_certs(SSL_CTX *ssl_ctx) +{ + int ret = SSL_OK; + uint32_t options = ssl_ctx->options; +#ifdef CONFIG_SSL_GENERATE_X509_CERT + uint8_t *cert_data = NULL; + int cert_size; + static const char *dn[] = + { + CONFIG_SSL_X509_COMMON_NAME, + CONFIG_SSL_X509_ORGANIZATION_NAME, + CONFIG_SSL_X509_ORGANIZATION_UNIT_NAME + }; +#endif + + /* do the private key first */ + if (strlen(CONFIG_SSL_PRIVATE_KEY_LOCATION) > 0) + { + if ((ret = ssl_obj_load(ssl_ctx, SSL_OBJ_RSA_KEY, + CONFIG_SSL_PRIVATE_KEY_LOCATION, + CONFIG_SSL_PRIVATE_KEY_PASSWORD)) < 0) + goto error; + } + else if (!(options & SSL_NO_DEFAULT_KEY)) + { +#if defined(CONFIG_SSL_USE_DEFAULT_KEY) || defined(CONFIG_SSL_SKELETON_MODE) +// static const /* saves a few more bytes */ +//#include "private_key.h" +// ssl_obj_memory_load(ssl_ctx, SSL_OBJ_RSA_KEY, default_private_key, + // default_private_key_len, NULL); +#endif + } + + /* now load the certificate */ +#ifdef CONFIG_SSL_GENERATE_X509_CERT + if ((cert_size = ssl_x509_create(ssl_ctx, 0, dn, &cert_data)) < 0) + { + ret = cert_size; + goto error; + } + + ssl_obj_memory_load(ssl_ctx, SSL_OBJ_X509_CERT, cert_data, cert_size, NULL); + free(cert_data); +#else + if (strlen(CONFIG_SSL_X509_CERT_LOCATION)) + { + if ((ret = ssl_obj_load(ssl_ctx, SSL_OBJ_X509_CERT, + CONFIG_SSL_X509_CERT_LOCATION, NULL)) < 0) + goto error; + } + else if (!(options & SSL_NO_DEFAULT_KEY)) + { +#if defined(CONFIG_SSL_USE_DEFAULT_KEY) || defined(CONFIG_SSL_SKELETON_MODE) + static const /* saves a few bytes and RAM */ +#include "cert.h" + ssl_obj_memory_load(ssl_ctx, SSL_OBJ_X509_CERT, + default_certificate, default_certificate_len, NULL); +#endif + } +#endif + +error: +#ifdef CONFIG_SSL_FULL_MODE + if (ret) + { + printf("Error: Certificate or key not loaded\n"); TTY_FLUSH(); + } +#endif + + return ret; + +} diff --git a/features/unsupported/net/https/axTLS/ssl/openssl.c b/features/unsupported/net/https/axTLS/ssl/openssl.c new file mode 100644 index 00000000000..6b5c4d8ee9f --- /dev/null +++ b/features/unsupported/net/https/axTLS/ssl/openssl.c @@ -0,0 +1,323 @@ +/* + * Copyright (c) 2007, Cameron Rich + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * * Neither the name of the axTLS project nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/* + * Enable a subset of openssl compatible functions. We don't aim to be 100% + * compatible - just to be able to do basic ports etc. + * + * Only really tested on mini_httpd, so I'm not too sure how extensive this + * port is. + */ + +#include "config.h" + +#ifdef CONFIG_OPENSSL_COMPATIBLE +#include +#include +#include +#include "os_port.h" +#include "ssl.h" + +#define OPENSSL_CTX_ATTR ((OPENSSL_CTX *)ssl_ctx->bonus_attr) + +static char *key_password = NULL; + +void *SSLv23_server_method(void) { return NULL; } +void *SSLv3_server_method(void) { return NULL; } +void *TLSv1_server_method(void) { return NULL; } +void *SSLv23_client_method(void) { return NULL; } +void *SSLv3_client_method(void) { return NULL; } +void *TLSv1_client_method(void) { return NULL; } + +typedef void * (*ssl_func_type_t)(void); +typedef void * (*bio_func_type_t)(void); + +typedef struct +{ + ssl_func_type_t ssl_func_type; +} OPENSSL_CTX; + +SSL_CTX * SSL_CTX_new(ssl_func_type_t meth) +{ + SSL_CTX *ssl_ctx = ssl_ctx_new(0, 5); + ssl_ctx->bonus_attr = malloc(sizeof(OPENSSL_CTX)); + OPENSSL_CTX_ATTR->ssl_func_type = meth; + return ssl_ctx; +} + +void SSL_CTX_free(SSL_CTX * ssl_ctx) +{ + free(ssl_ctx->bonus_attr); + ssl_ctx_free(ssl_ctx); +} + +SSL * SSL_new(SSL_CTX *ssl_ctx) +{ + SSL *ssl; + ssl_func_type_t ssl_func_type; + + ssl = ssl_new(ssl_ctx, -1); /* fd is set later */ + ssl_func_type = OPENSSL_CTX_ATTR->ssl_func_type; + +#ifdef CONFIG_SSL_ENABLE_CLIENT + if (ssl_func_type == SSLv23_client_method || + ssl_func_type == SSLv3_client_method || + ssl_func_type == TLSv1_client_method) + { + SET_SSL_FLAG(SSL_IS_CLIENT); + } + else +#endif + { + ssl->next_state = HS_CLIENT_HELLO; + } + + return ssl; +} + +int SSL_set_fd(SSL *s, int fd) +{ + s->client_fd = fd; + return 1; /* always succeeds */ +} + +int SSL_accept(SSL *ssl) +{ + while (ssl_read(ssl, NULL) == SSL_OK) + { + if (ssl->next_state == HS_CLIENT_HELLO) + return 1; /* we're done */ + } + + return -1; +} + +#ifdef CONFIG_SSL_ENABLE_CLIENT +int SSL_connect(SSL *ssl) +{ + return do_client_connect(ssl) == SSL_OK ? 1 : -1; +} +#endif + +void SSL_free(SSL *ssl) +{ + ssl_free(ssl); +} + +int SSL_read(SSL *ssl, void *buf, int num) +{ + uint8_t *read_buf; + int ret; + + while ((ret = ssl_read(ssl, &read_buf)) == SSL_OK); + + if (ret > SSL_OK) + { + memcpy(buf, read_buf, ret > num ? num : ret); + } + + return ret; +} + +int SSL_write(SSL *ssl, const void *buf, int num) +{ + return ssl_write(ssl, buf, num); +} + +int SSL_CTX_use_certificate_file(SSL_CTX *ssl_ctx, const char *file, int type) +{ + return (ssl_obj_load(ssl_ctx, SSL_OBJ_X509_CERT, file, NULL) == SSL_OK); +} + +int SSL_CTX_use_PrivateKey_file(SSL_CTX *ssl_ctx, const char *file, int type) +{ + return (ssl_obj_load(ssl_ctx, SSL_OBJ_RSA_KEY, file, key_password) == SSL_OK); +} + +int SSL_CTX_use_certificate_ASN1(SSL_CTX *ssl_ctx, int len, const uint8_t *d) +{ + return (ssl_obj_memory_load(ssl_ctx, + SSL_OBJ_X509_CERT, d, len, NULL) == SSL_OK); +} + +int SSL_CTX_set_session_id_context(SSL_CTX *ctx, const unsigned char *sid_ctx, + unsigned int sid_ctx_len) +{ + return 1; +} + +int SSL_CTX_set_default_verify_paths(SSL_CTX *ctx) +{ + return 1; +} + +int SSL_CTX_use_certificate_chain_file(SSL_CTX *ssl_ctx, const char *file) +{ + return (ssl_obj_load(ssl_ctx, + SSL_OBJ_X509_CERT, file, NULL) == SSL_OK); +} + +int SSL_shutdown(SSL *ssl) +{ + return 1; +} + +/*** get/set session ***/ +SSL_SESSION *SSL_get1_session(SSL *ssl) +{ + return (SSL_SESSION *)ssl_get_session_id(ssl); /* note: wrong cast */ +} + +int SSL_set_session(SSL *ssl, SSL_SESSION *session) +{ + memcpy(ssl->session_id, (uint8_t *)session, SSL_SESSION_ID_SIZE); + return 1; +} + +void SSL_SESSION_free(SSL_SESSION *session) { } +/*** end get/set session ***/ + +long SSL_CTX_ctrl(SSL_CTX *ctx, int cmd, long larg, void *parg) +{ + return 0; +} + +void SSL_CTX_set_verify(SSL_CTX *ctx, int mode, + int (*verify_callback)(int, void *)) { } + +void SSL_CTX_set_verify_depth(SSL_CTX *ctx,int depth) { } + +int SSL_CTX_load_verify_locations(SSL_CTX *ctx, const char *CAfile, + const char *CApath) +{ + return 1; +} + +void *SSL_load_client_CA_file(const char *file) +{ + return (void *)file; +} + +void SSL_CTX_set_client_CA_list(SSL_CTX *ssl_ctx, void *file) +{ + + ssl_obj_load(ssl_ctx, SSL_OBJ_X509_CERT, (const char *)file, NULL); +} + +void SSLv23_method(void) { } + +void SSL_CTX_set_default_passwd_cb(SSL_CTX *ctx, void *cb) { } + +void SSL_CTX_set_default_passwd_cb_userdata(SSL_CTX *ctx, void *u) +{ + key_password = (char *)u; +} + +int SSL_peek(SSL *ssl, void *buf, int num) +{ + memcpy(buf, ssl->bm_data, num); + return num; +} + +void SSL_set_bio(SSL *ssl, void *rbio, void *wbio) { } + +long SSL_get_verify_result(const SSL *ssl) +{ + return ssl_handshake_status(ssl); +} + +int SSL_state(SSL *ssl) +{ + return 0x03; // ok state +} + +/** end of could do better list */ + +void *SSL_get_peer_certificate(const SSL *ssl) +{ + return &ssl->ssl_ctx->certs[0]; +} + +int SSL_clear(SSL *ssl) +{ + return 1; +} + + +int SSL_CTX_check_private_key(const SSL_CTX *ctx) +{ + return 1; +} + +int SSL_CTX_set_cipher_list(SSL *s, const char *str) +{ + return 1; +} + +int SSL_get_error(const SSL *ssl, int ret) +{ + ssl_display_error(ret); + return 0; /* TODO: return proper return code */ +} + +void SSL_CTX_set_options(SSL_CTX *ssl_ctx, int option) {} +int SSL_library_init(void ) { return 1; } +void SSL_load_error_strings(void ) {} +void ERR_print_errors_fp(FILE *fp) {} + +#ifndef CONFIG_SSL_SKELETON_MODE +long SSL_CTX_get_timeout(const SSL_CTX *ssl_ctx) { + return CONFIG_SSL_EXPIRY_TIME*3600; } +long SSL_CTX_set_timeout(SSL_CTX *ssl_ctx, long t) { + return SSL_CTX_get_timeout(ssl_ctx); } +#endif +void BIO_printf(FILE *f, const char *format, ...) +{ + va_list(ap); + va_start(ap, format); + vfprintf(f, format, ap); + va_end(ap); +} + +void* BIO_s_null(void) { return NULL; } +FILE *BIO_new(bio_func_type_t func) +{ + if (func == BIO_s_null) + return fopen("/dev/null", "r"); + else + return NULL; +} + +FILE *BIO_new_fp(FILE *stream, int close_flag) { return stream; } +int BIO_free(FILE *a) { if (a != stdout && a != stderr) fclose(a); return 1; } + + + +#endif diff --git a/features/unsupported/net/https/axTLS/ssl/os_port.c b/features/unsupported/net/https/axTLS/ssl/os_port.c new file mode 100644 index 00000000000..a0627bf620e --- /dev/null +++ b/features/unsupported/net/https/axTLS/ssl/os_port.c @@ -0,0 +1,280 @@ +/* + * Copyright (c) 2007, Cameron Rich + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * * Neither the name of the axTLS project nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @file os_port.c + * + * OS specific functions. + */ +#include +#include +#include +#include +#include "os_port.h" +#include +#include "sockets.h" + +static int memory_buf[400]; +static char enable = 1; +static int nb_entries = 0; +static int nb_alloc = 0; + +void disable_memory_buf(void) +{ + enable = 0; +} +void enable_memory_buf(void) +{ + enable = 1; +} +void init_memory_buf(void) +{ + for(int i = 0; i < 400; i += 2) + { + memory_buf[i] = -1; + memory_buf[i+1] = 0; + } +} +void print_buf_stats(void) +{ + if(enable) + { + int used = 0; + for(int i = 1; i < 400; i += 2) + used += memory_buf[i]; + printf("%d\n", used); + } +} + +void print_all_buf_stats(void) +{ + int used = 0; + for(int i = 1; i < 400; i += 2) + used += memory_buf[i]; + printf("used: %d bytes\n", used); + + for(int i = 0; i < 400; i += 2) + if(memory_buf[i] != -1) + printf("ptr:%X, size:%d\n", memory_buf[i], memory_buf[i+1]); +} + +static void add_entry(void *x, size_t s, const char* f, const int l) +{ + nb_entries++; + for(int i = 0; i < 400; i += 2) + { + if(memory_buf[i] == -1) + { + if(enable) + printf("new ptr:%X, size:%d at %s:%d\n", x, s, f, l); + memory_buf[i] = (int)(x); + memory_buf[i+1] = s; + return; + } + } + if(enable) + printf("No space left in buffer\n"); +} + +static void remove_entry(void *x, const char* f, const int l) +{ + nb_entries--; + for(int i = 0; i < 400; i += 2) + { + if(memory_buf[i] == (int)(x)) + { + if(enable) + printf("free ptr:%X, size:%d at %s:%d\n", memory_buf[i], memory_buf[i+1], f, l); + memory_buf[i] = -1; + memory_buf[i+1] = 0; + return; + } + } + if(enable) + printf("not found\n"); +} + +#ifdef MBED +/** + * gettimeofday() not in mbed + */ +EXP_FUNC void STDCALL gettimeofday(struct timeval* t, void* timezone) +{ + t->tv_sec = time(NULL); + t->tv_usec = 0; /* 1sec precision only */ +} + +#endif + +#ifdef WIN32 +/** + * gettimeofday() not in Win32 + */ +EXP_FUNC void STDCALL gettimeofday(struct timeval* t, void* timezone) +{ +#if defined(_WIN32_WCE) + t->tv_sec = time(NULL); + t->tv_usec = 0; /* 1sec precision only */ +#else + struct _timeb timebuffer; + _ftime(&timebuffer); + t->tv_sec = (long)timebuffer.time; + t->tv_usec = 1000 * timebuffer.millitm; /* 1ms precision */ +#endif +} + + +/** + * strcasecmp() not in Win32 + */ +EXP_FUNC int STDCALL strcasecmp(const char *s1, const char *s2) +{ + while (tolower(*s1) == tolower(*s2++)) + { + if (*s1++ == '\0') + { + return 0; + } + } + + return *(unsigned char *)s1 - *(unsigned char *)(s2 - 1); +} + + +EXP_FUNC int STDCALL getdomainname(char *buf, int buf_size) +{ + HKEY hKey; + unsigned long datatype; + unsigned long bufferlength = buf_size; + + if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, + TEXT("SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters"), + 0, KEY_QUERY_VALUE, &hKey) != ERROR_SUCCESS) + return -1; + + RegQueryValueEx(hKey, "Domain", NULL, &datatype, buf, &bufferlength); + RegCloseKey(hKey); + return 0; +} +#endif + +#undef malloc +#undef realloc +#undef calloc +#undef free + +static const char * out_of_mem_str = "out of memory"; +static const char * file_open_str = "Could not open file \"%s\""; + +/* + * Some functions that call display some error trace and then call abort(). + * This just makes life much easier on embedded systems, since we're + * suffering major trauma... + */ +EXP_FUNC void * STDCALL ax_malloc(size_t s, const char* f, const int l) +{ + if(enable) + printf("malloc\t"); + + void *x; + + if ((x = malloc(s)) == NULL) + exit_now(out_of_mem_str); + add_entry(x,s, f, l); + print_buf_stats(); + + return x; +} + +EXP_FUNC void * STDCALL ax_realloc(void *y, size_t s, const char* f, const int l) +{ + if(enable) + printf("realloc\t"); + + void *x; + + if ((x = realloc(y, s)) == NULL) + exit_now(out_of_mem_str); + remove_entry(y, f, l); + add_entry(x,s, f, l); + print_buf_stats(); + return x; +} + +EXP_FUNC void * STDCALL ax_calloc(size_t n, size_t s, const char* f, const int l) +{ + if(enable) + printf("calloc\t"); + void *x; + + if ((x = calloc(n, s)) == NULL) { + exit_now(out_of_mem_str); + } + + add_entry(x,n*s, f, l); + print_buf_stats(); + return x; +} + +EXP_FUNC void STDCALL ax_free(void *y, const char* f, const int l) +{ + if(enable) + printf("free\t"); + + remove_entry(y, f, l); + print_buf_stats(); + free(y); +} +/* +EXP_FUNC int STDCALL ax_open(const char *pathname, int flags) +{ + int x; + + if ((x = open(pathname, flags)) < 0) + exit_now(file_open_str, pathname); + + return x; +} +*/ + +/** + * This is a call which will deliberately exit an application, but will + * display some information before dying. + */ +void exit_now(const char *format, ...) +{ + va_list argp; + + va_start(argp, format); + vfprintf(stderr, format, argp); + va_end(argp); + abort(); +} + diff --git a/features/unsupported/net/https/axTLS/ssl/os_port.h b/features/unsupported/net/https/axTLS/ssl/os_port.h new file mode 100644 index 00000000000..3937261a758 --- /dev/null +++ b/features/unsupported/net/https/axTLS/ssl/os_port.h @@ -0,0 +1,45 @@ +#ifndef HEADER_OS_PORT_H +#define HEADER_OS_PORT_H +#ifdef __cplusplus +extern "C" { +#endif + +#include "config.h" + +//#include +#define SSL_CTX_MUTEX_TYPE //Mutex +#define SSL_CTX_MUTEX_INIT(A) //pthread_mutex_init(&A, NULL) +#define SSL_CTX_MUTEX_DESTROY(A) //pthread_mutex_destroy(&A) +#define SSL_CTX_LOCK(A) //pthread_mutex_lock(&A) +#define SSL_CTX_UNLOCK(A) //pthread_mutex_unlock(&A) + +#define malloc(A) ax_malloc(A, __FILE__, __LINE__) +#ifndef realloc +#define realloc(A,B) ax_realloc(A,B, __FILE__, __LINE__) +#endif +#define calloc(A,B) ax_calloc(A,B, __FILE__, __LINE__) +#define free(A) ax_free(A, __FILE__, __LINE__) + +#define STDCALL +#define EXP_FUNC +void init_memory_buf(void); +void disable_memory_buf(void); +void enable_memory_buf(void); +void print_buf_stats(void); +void print_all_buf_stats(void); + +EXP_FUNC void * STDCALL ax_malloc(size_t s, const char* f, const int l); +EXP_FUNC void * STDCALL ax_realloc(void *y, size_t s, const char* f, const int l); +EXP_FUNC void * STDCALL ax_calloc(size_t n, size_t s, const char* f, const int l); +EXP_FUNC void STDCALL ax_free(void *y, const char* f, const int l); + +//EXP_FUNC int STDCALL ax_open(const char *pathname, int flags); + +#define SOCKET_READ(A,B,C) lwip_read(A,B,C) +#define SOCKET_WRITE(A,B,C) lwip_write(A,B,C) +#define SOCKET_CLOSE(A) closesocket(A) +#define TTY_FLUSH() +#ifdef __cplusplus +} +#endif +#endif diff --git a/features/unsupported/net/https/axTLS/ssl/os_port_old.h b/features/unsupported/net/https/axTLS/ssl/os_port_old.h new file mode 100644 index 00000000000..a9ac7393d76 --- /dev/null +++ b/features/unsupported/net/https/axTLS/ssl/os_port_old.h @@ -0,0 +1,194 @@ +/* + * Copyright (c) 2007, Cameron Rich + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * * Neither the name of the axTLS project nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @file os_port.h + * + * Some stuff to minimise the differences between windows and linux/unix + */ + +#ifndef HEADER_OS_PORT_H +#define HEADER_OS_PORT_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include "os_int.h" +#include + +#if defined(WIN32) +#define STDCALL __stdcall +#define EXP_FUNC __declspec(dllexport) +#else +#define STDCALL +#define EXP_FUNC +#endif + +#if defined(_WIN32_WCE) +#undef WIN32 +#define WIN32 +#endif + +#ifdef WIN32 + +/* Windows CE stuff */ +#if defined(_WIN32_WCE) +#include +#define abort() exit(1) +#else +#include +#include +#include +#include +#endif /* _WIN32_WCE */ + +#include +#include +#undef getpid +#undef open +#undef close +#undef sleep +#undef gettimeofday +#undef dup2 +#undef unlink + +#define SOCKET_READ(A,B,C) recv(A,B,C,0) +#define SOCKET_WRITE(A,B,C) send(A,B,C,0) +#define SOCKET_CLOSE(A) closesocket(A) +#define srandom(A) srand(A) +#define random() rand() +#define getpid() _getpid() +#define snprintf _snprintf +#define open(A,B) _open(A,B) +#define dup2(A,B) _dup2(A,B) +#define unlink(A) _unlink(A) +#define close(A) _close(A) +#define read(A,B,C) _read(A,B,C) +#define write(A,B,C) _write(A,B,C) +#define sleep(A) Sleep(A*1000) +#define usleep(A) Sleep(A/1000) +#define strdup(A) _strdup(A) +#define chroot(A) _chdir(A) +#define chdir(A) _chdir(A) +#define alloca(A) _alloca(A) + + +#ifndef lseek +#define lseek(A,B,C) _lseek(A,B,C) + +#endif + +/* This fix gets around a problem where a win32 application on a cygwin xterm + doesn't display regular output (until a certain buffer limit) - but it works + fine under a normal DOS window. This is a hack to get around the issue - + see http://www.khngai.com/emacs/tty.php */ +#define TTY_FLUSH() if (!_isatty(_fileno(stdout))) fflush(stdout); + +/* + * automatically build some library dependencies. + */ +#pragma comment(lib, "WS2_32.lib") +#pragma comment(lib, "AdvAPI32.lib") + +typedef int socklen_t; + +EXP_FUNC void STDCALL gettimeofday(struct timeval* t,void* timezone); +EXP_FUNC int STDCALL strcasecmp(const char *s1, const char *s2); +EXP_FUNC int STDCALL getdomainname(char *buf, int buf_size); + +#else /* Not Win32 */ + +//#include +//#include +//#include +//#include +//#include +#include +//#include +#include +#include +//#include +#include +#include + +#define SOCKET_READ(A,B,C) read(A,B,C) +#define SOCKET_WRITE(A,B,C) write(A,B,C) +#define SOCKET_CLOSE(A) if (A >= 0) close(A) +#define TTY_FLUSH() + +#endif /* Not Win32 */ + +/* some functions to mutate the way these work */ +#define malloc(A) ax_malloc(A) +#ifndef realloc +#define realloc(A,B) ax_realloc(A,B) +#endif +#define calloc(A,B) ax_calloc(A,B) + +EXP_FUNC void * STDCALL ax_malloc(size_t s); +EXP_FUNC void * STDCALL ax_realloc(void *y, size_t s); +EXP_FUNC void * STDCALL ax_calloc(size_t n, size_t s); +EXP_FUNC int STDCALL ax_open(const char *pathname, int flags); + +#ifdef CONFIG_PLATFORM_LINUX +void exit_now(const char *format, ...) __attribute((noreturn)); +#else +void exit_now(const char *format, ...); +#endif + +/* Mutexing definitions */ +#if defined(CONFIG_SSL_CTX_MUTEXING) +#if defined(WIN32) +#define SSL_CTX_MUTEX_TYPE HANDLE +#define SSL_CTX_MUTEX_INIT(A) A=CreateMutex(0, FALSE, 0) +#define SSL_CTX_MUTEX_DESTROY(A) CloseHandle(A) +#define SSL_CTX_LOCK(A) WaitForSingleObject(A, INFINITE) +#define SSL_CTX_UNLOCK(A) ReleaseMutex(A) +#else +#include +#define SSL_CTX_MUTEX_TYPE pthread_mutex_t +#define SSL_CTX_MUTEX_INIT(A) pthread_mutex_init(&A, NULL) +#define SSL_CTX_MUTEX_DESTROY(A) pthread_mutex_destroy(&A) +#define SSL_CTX_LOCK(A) pthread_mutex_lock(&A) +#define SSL_CTX_UNLOCK(A) pthread_mutex_unlock(&A) +#endif +#else /* no mutexing */ +#define SSL_CTX_MUTEX_INIT(A) +#define SSL_CTX_MUTEX_DESTROY(A) +#define SSL_CTX_LOCK(A) +#define SSL_CTX_UNLOCK(A) +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/features/unsupported/net/https/axTLS/ssl/p12.c b/features/unsupported/net/https/axTLS/ssl/p12.c new file mode 100644 index 00000000000..2bafaf7eaf9 --- /dev/null +++ b/features/unsupported/net/https/axTLS/ssl/p12.c @@ -0,0 +1,483 @@ +/* + * Copyright (c) 2007, Cameron Rich + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * * Neither the name of the axTLS project nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * Process PKCS#8/PKCS#12 keys. + * + * The decoding of a PKCS#12 key is fairly specific - this code was tested on a + * key generated with: + * + * openssl pkcs12 -export -in axTLS.x509_1024.pem -inkey axTLS.key_1024.pem + * -keypbe PBE-SHA1-RC4-128 -certpbe PBE-SHA1-RC4-128 + * -name "p12_withoutCA" -out axTLS.withoutCA.p12 -password pass:abcd + * + * or with a certificate chain: + * + * openssl pkcs12 -export -in axTLS.x509_1024.pem -inkey axTLS.key_1024.pem + * -certfile axTLS.ca_x509.pem -keypbe PBE-SHA1-RC4-128 -certpbe + * PBE-SHA1-RC4-128 -name "p12_withCA" -out axTLS.withCA.p12 -password pass:abcd + * + * Note that the PBE has to be specified with PBE-SHA1-RC4-128. The + * private/public keys/certs have to use RSA encryption. Both the integrity + * and privacy passwords are the same. + * + * The PKCS#8 files were generated with something like: + * + * PEM format: + * openssl pkcs8 -in axTLS.key_512.pem -passout pass:abcd -topk8 -v1 + * PBE-SHA1-RC4-128 -out axTLS.encrypted_pem.p8 + * + * DER format: + * openssl pkcs8 -in axTLS.key_512.pem -passout pass:abcd -topk8 -outform DER + * -v1 PBE-SHA1-RC4-128 -out axTLS.encrypted.p8 + */ + +#include +#include +#include +#include "os_port.h" +#include "ssl.h" + +/* all commented out if not used */ +#ifdef CONFIG_SSL_USE_PKCS12 + +#define BLOCK_SIZE 64 +#define PKCS12_KEY_ID 1 +#define PKCS12_IV_ID 2 +#define PKCS12_MAC_ID 3 + +static char *make_uni_pass(const char *password, int *uni_pass_len); +static int p8_decrypt(const char *uni_pass, int uni_pass_len, + const uint8_t *salt, int iter, + uint8_t *priv_key, int priv_key_len, int id); +static int p8_add_key(SSL_CTX *ssl_ctx, uint8_t *priv_key); +static int get_pbe_params(uint8_t *buf, int *offset, + const uint8_t **salt, int *iterations); + +/* + * Take a raw pkcs8 block and then decrypt it and turn it into a normal key. + */ +int pkcs8_decode(SSL_CTX *ssl_ctx, SSLObjLoader *ssl_obj, const char *password) +{ + uint8_t *buf = ssl_obj->buf; + int len, offset = 0; + int iterations; + int ret = SSL_NOT_OK; + uint8_t *version = NULL; + const uint8_t *salt; + uint8_t *priv_key; + int uni_pass_len; + char *uni_pass = make_uni_pass(password, &uni_pass_len); + + if (asn1_next_obj(buf, &offset, ASN1_SEQUENCE) < 0) + { +#ifdef CONFIG_SSL_FULL_MODE + printf("Error: Invalid p8 ASN.1 file\n"); +#endif + goto error; + } + + /* unencrypted key? */ + if (asn1_get_int(buf, &offset, &version) > 0 && *version == 0) + { + ret = p8_add_key(ssl_ctx, buf); + goto error; + } + + if (get_pbe_params(buf, &offset, &salt, &iterations) < 0) + goto error; + + if ((len = asn1_next_obj(buf, &offset, ASN1_OCTET_STRING)) < 0) + goto error; + + priv_key = &buf[offset]; + + p8_decrypt(uni_pass, uni_pass_len, salt, + iterations, priv_key, len, PKCS12_KEY_ID); + ret = p8_add_key(ssl_ctx, priv_key); + +error: + free(version); + free(uni_pass); + return ret; +} + +/* + * Take the unencrypted pkcs8 and turn it into a private key + */ +static int p8_add_key(SSL_CTX *ssl_ctx, uint8_t *priv_key) +{ + uint8_t *buf = priv_key; + int len, offset = 0; + int ret = SSL_NOT_OK; + + /* Skip the preamble and go straight to the private key. + We only support rsaEncryption (1.2.840.113549.1.1.1) */ + if (asn1_next_obj(buf, &offset, ASN1_SEQUENCE) < 0 || + asn1_skip_obj(buf, &offset, ASN1_INTEGER) < 0 || + asn1_skip_obj(buf, &offset, ASN1_SEQUENCE) < 0 || + (len = asn1_next_obj(buf, &offset, ASN1_OCTET_STRING)) < 0) + goto error; + + ret = asn1_get_private_key(&buf[offset], len, &ssl_ctx->rsa_ctx); + +error: + return ret; +} + +/* + * Create the unicode password + */ +static char *make_uni_pass(const char *password, int *uni_pass_len) +{ + int pass_len = 0, i; + char *uni_pass; + + if (password == NULL) + { + password = ""; + } + + uni_pass = (char *)malloc((strlen(password)+1)*2); + + /* modify the password into a unicode version */ + for (i = 0; i < (int)strlen(password); i++) + { + uni_pass[pass_len++] = 0; + uni_pass[pass_len++] = password[i]; + } + + uni_pass[pass_len++] = 0; /* null terminate */ + uni_pass[pass_len++] = 0; + *uni_pass_len = pass_len; + return uni_pass; +} + +/* + * Decrypt a pkcs8 block. + */ +static int p8_decrypt(const char *uni_pass, int uni_pass_len, + const uint8_t *salt, int iter, + uint8_t *priv_key, int priv_key_len, int id) +{ + uint8_t p[BLOCK_SIZE*2]; + uint8_t d[BLOCK_SIZE]; + uint8_t Ai[SHA1_SIZE]; + SHA1_CTX sha_ctx; + RC4_CTX rc4_ctx; + int i; + + for (i = 0; i < BLOCK_SIZE; i++) + { + p[i] = salt[i % SALT_SIZE]; + p[BLOCK_SIZE+i] = uni_pass[i % uni_pass_len]; + d[i] = id; + } + + /* get the key - no IV since we are using RC4 */ + SHA1_Init(&sha_ctx); + SHA1_Update(&sha_ctx, d, sizeof(d)); + SHA1_Update(&sha_ctx, p, sizeof(p)); + SHA1_Final(Ai, &sha_ctx); + + for (i = 1; i < iter; i++) + { + SHA1_Init(&sha_ctx); + SHA1_Update(&sha_ctx, Ai, SHA1_SIZE); + SHA1_Final(Ai, &sha_ctx); + } + + /* do the decryption */ + if (id == PKCS12_KEY_ID) + { + RC4_setup(&rc4_ctx, Ai, 16); + RC4_crypt(&rc4_ctx, priv_key, priv_key, priv_key_len); + } + else /* MAC */ + memcpy(priv_key, Ai, SHA1_SIZE); + + return 0; +} + +/* + * Take a raw pkcs12 block and the decrypt it and turn it into a certificate(s) + * and keys. + */ +int pkcs12_decode(SSL_CTX *ssl_ctx, SSLObjLoader *ssl_obj, const char *password) +{ + uint8_t *buf = ssl_obj->buf; + int len, iterations, auth_safes_start, + auth_safes_end, auth_safes_len, key_offset, offset = 0; + int all_certs = 0; + uint8_t *version = NULL, *auth_safes = NULL, *cert, *orig_mac; + uint8_t key[SHA1_SIZE]; + uint8_t mac[SHA1_SIZE]; + const uint8_t *salt; + int uni_pass_len, ret = SSL_OK; + char *uni_pass = make_uni_pass(password, &uni_pass_len); + static const uint8_t pkcs_data[] = /* pkc7 data */ + { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x01 }; + static const uint8_t pkcs_encrypted[] = /* pkc7 encrypted */ + { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x06 }; + static const uint8_t pkcs8_key_bag[] = /* 1.2.840.113549.1.12.10.1.2 */ + { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x0c, 0x0a, 0x01, 0x02 }; + + if (asn1_next_obj(buf, &offset, ASN1_SEQUENCE) < 0) + { +#ifdef CONFIG_SSL_FULL_MODE + printf("Error: Invalid p12 ASN.1 file\n"); +#endif + goto error; + } + + if (asn1_get_int(buf, &offset, &version) < 0 || *version != 3) + { + ret = SSL_ERROR_INVALID_VERSION; + goto error; + } + + /* remove all the boring pcks7 bits */ + if (asn1_next_obj(buf, &offset, ASN1_SEQUENCE) < 0 || + (len = asn1_next_obj(buf, &offset, ASN1_OID)) < 0 || + len != sizeof(pkcs_data) || + memcmp(&buf[offset], pkcs_data, sizeof(pkcs_data))) + goto error; + + offset += len; + + if (asn1_next_obj(buf, &offset, ASN1_EXPLICIT_TAG) < 0 || + asn1_next_obj(buf, &offset, ASN1_OCTET_STRING) < 0) + goto error; + + /* work out the MAC start/end points (done on AuthSafes) */ + auth_safes_start = offset; + auth_safes_end = offset; + if (asn1_skip_obj(buf, &auth_safes_end, ASN1_SEQUENCE) < 0) + goto error; + + auth_safes_len = auth_safes_end - auth_safes_start; + auth_safes = malloc(auth_safes_len); + + memcpy(auth_safes, &buf[auth_safes_start], auth_safes_len); + + if (asn1_next_obj(buf, &offset, ASN1_SEQUENCE) < 0 || + asn1_next_obj(buf, &offset, ASN1_SEQUENCE) < 0 || + (len = asn1_next_obj(buf, &offset, ASN1_OID)) < 0 || + (len != sizeof(pkcs_encrypted) || + memcmp(&buf[offset], pkcs_encrypted, sizeof(pkcs_encrypted)))) + goto error; + + offset += len; + + if (asn1_next_obj(buf, &offset, ASN1_EXPLICIT_TAG) < 0 || + asn1_next_obj(buf, &offset, ASN1_SEQUENCE) < 0 || + asn1_skip_obj(buf, &offset, ASN1_INTEGER) < 0 || + asn1_next_obj(buf, &offset, ASN1_SEQUENCE) < 0 || + (len = asn1_next_obj(buf, &offset, ASN1_OID)) < 0 || + len != sizeof(pkcs_data) || + memcmp(&buf[offset], pkcs_data, sizeof(pkcs_data))) + goto error; + + offset += len; + + /* work out the salt for the certificate */ + if (get_pbe_params(buf, &offset, &salt, &iterations) < 0 || + (len = asn1_next_obj(buf, &offset, ASN1_IMPLICIT_TAG)) < 0) + goto error; + + /* decrypt the certificate */ + cert = &buf[offset]; + if ((ret = p8_decrypt(uni_pass, uni_pass_len, salt, iterations, cert, + len, PKCS12_KEY_ID)) < 0) + goto error; + + offset += len; + + /* load the certificate */ + key_offset = 0; + all_certs = asn1_next_obj(cert, &key_offset, ASN1_SEQUENCE); + + /* keep going until all certs are loaded */ + while (key_offset < all_certs) + { + int cert_offset = key_offset; + + if (asn1_skip_obj(cert, &cert_offset, ASN1_SEQUENCE) < 0 || + asn1_next_obj(cert, &key_offset, ASN1_SEQUENCE) < 0 || + asn1_skip_obj(cert, &key_offset, ASN1_OID) < 0 || + asn1_next_obj(cert, &key_offset, ASN1_EXPLICIT_TAG) < 0 || + asn1_next_obj(cert, &key_offset, ASN1_SEQUENCE) < 0 || + asn1_skip_obj(cert, &key_offset, ASN1_OID) < 0 || + asn1_next_obj(cert, &key_offset, ASN1_EXPLICIT_TAG) < 0 || + (len = asn1_next_obj(cert, &key_offset, ASN1_OCTET_STRING)) < 0) + goto error; + + if ((ret = add_cert(ssl_ctx, &cert[key_offset], len)) < 0) + goto error; + + key_offset = cert_offset; + } + + if (asn1_next_obj(buf, &offset, ASN1_SEQUENCE) < 0 || + (len = asn1_next_obj(buf, &offset, ASN1_OID)) < 0 || + len != sizeof(pkcs_data) || + memcmp(&buf[offset], pkcs_data, sizeof(pkcs_data))) + goto error; + + offset += len; + + if (asn1_next_obj(buf, &offset, ASN1_EXPLICIT_TAG) < 0 || + asn1_next_obj(buf, &offset, ASN1_OCTET_STRING) < 0 || + asn1_next_obj(buf, &offset, ASN1_SEQUENCE) < 0 || + asn1_next_obj(buf, &offset, ASN1_SEQUENCE) < 0 || + (len = asn1_next_obj(buf, &offset, ASN1_OID)) < 0 || + (len != sizeof(pkcs8_key_bag)) || + memcmp(&buf[offset], pkcs8_key_bag, sizeof(pkcs8_key_bag))) + goto error; + + offset += len; + + /* work out the salt for the private key */ + if (asn1_next_obj(buf, &offset, ASN1_EXPLICIT_TAG) < 0 || + asn1_next_obj(buf, &offset, ASN1_SEQUENCE) < 0 || + get_pbe_params(buf, &offset, &salt, &iterations) < 0 || + (len = asn1_next_obj(buf, &offset, ASN1_OCTET_STRING)) < 0) + goto error; + + /* decrypt the private key */ + cert = &buf[offset]; + if ((ret = p8_decrypt(uni_pass, uni_pass_len, salt, iterations, cert, + len, PKCS12_KEY_ID)) < 0) + goto error; + + offset += len; + + /* load the private key */ + if ((ret = p8_add_key(ssl_ctx, cert)) < 0) + goto error; + + /* miss out on friendly name, local key id etc */ + if (asn1_skip_obj(buf, &offset, ASN1_SET) < 0) + goto error; + + /* work out the MAC */ + if (asn1_next_obj(buf, &offset, ASN1_SEQUENCE) < 0 || + asn1_next_obj(buf, &offset, ASN1_SEQUENCE) < 0 || + asn1_skip_obj(buf, &offset, ASN1_SEQUENCE) < 0 || + (len = asn1_next_obj(buf, &offset, ASN1_OCTET_STRING)) < 0 || + len != SHA1_SIZE) + goto error; + + orig_mac = &buf[offset]; + offset += len; + + /* get the salt */ + if ((len = asn1_next_obj(buf, &offset, ASN1_OCTET_STRING)) < 0 || len != 8) + goto error; + + salt = &buf[offset]; + + /* work out what the mac should be */ + if ((ret = p8_decrypt(uni_pass, uni_pass_len, salt, iterations, + key, SHA1_SIZE, PKCS12_MAC_ID)) < 0) + goto error; + + hmac_sha1(auth_safes, auth_safes_len, key, SHA1_SIZE, mac); + + if (memcmp(mac, orig_mac, SHA1_SIZE)) + { + ret = SSL_ERROR_INVALID_HMAC; + goto error; + } + +error: + free(version); + free(uni_pass); + free(auth_safes); + return ret; +} + +/* + * Retrieve the salt/iteration details from a PBE block. + */ +static int get_pbe_params(uint8_t *buf, int *offset, + const uint8_t **salt, int *iterations) +{ + static const uint8_t pbeSH1RC4[] = /* pbeWithSHAAnd128BitRC4 */ + { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x0c, 0x01, 0x01 }; + + int i, len; + uint8_t *iter = NULL; + int error_code = SSL_ERROR_NOT_SUPPORTED; + + /* Get the PBE type */ + if (asn1_next_obj(buf, offset, ASN1_SEQUENCE) < 0 || + (len = asn1_next_obj(buf, offset, ASN1_OID)) < 0) + goto error; + + /* we expect pbeWithSHAAnd128BitRC4 (1.2.840.113549.1.12.1.1) + which is the only algorithm we support */ + if (len != sizeof(pbeSH1RC4) || + memcmp(&buf[*offset], pbeSH1RC4, sizeof(pbeSH1RC4))) + { +#ifdef CONFIG_SSL_FULL_MODE + printf("Error: pkcs8/pkcs12 must use \"PBE-SHA1-RC4-128\"\n"); +#endif + goto error; + } + + *offset += len; + + if (asn1_next_obj(buf, offset, ASN1_SEQUENCE) < 0 || + (len = asn1_next_obj(buf, offset, ASN1_OCTET_STRING)) < 0 || + len != 8) + goto error; + + *salt = &buf[*offset]; + *offset += len; + + if ((len = asn1_get_int(buf, offset, &iter)) < 0) + goto error; + + *iterations = 0; + for (i = 0; i < len; i++) + { + (*iterations) <<= 8; + (*iterations) += iter[i]; + } + + free(iter); + error_code = SSL_OK; /* got here - we are ok */ + +error: + return error_code; +} + +#endif diff --git a/features/unsupported/net/https/axTLS/ssl/private_key.h b/features/unsupported/net/https/axTLS/ssl/private_key.h new file mode 100644 index 00000000000..ce7985c5a78 --- /dev/null +++ b/features/unsupported/net/https/axTLS/ssl/private_key.h @@ -0,0 +1,54 @@ +unsigned char default_private_key[] = { + 0x30, 0x82, 0x02, 0x5d, 0x02, 0x01, 0x00, 0x02, 0x81, 0x81, 0x00, 0xcd, + 0xfd, 0x89, 0x48, 0xbe, 0x36, 0xb9, 0x95, 0x76, 0xd4, 0x13, 0x30, 0x0e, + 0xbf, 0xb2, 0xed, 0x67, 0x0a, 0xc0, 0x16, 0x3f, 0x51, 0x09, 0x9d, 0x29, + 0x2f, 0xb2, 0x6d, 0x3f, 0x3e, 0x6c, 0x2f, 0x90, 0x80, 0xa1, 0x71, 0xdf, + 0xbe, 0x38, 0xc5, 0xcb, 0xa9, 0x9a, 0x40, 0x14, 0x90, 0x0a, 0xf9, 0xb7, + 0x07, 0x0b, 0xe1, 0xda, 0xe7, 0x09, 0xbf, 0x0d, 0x57, 0x41, 0x86, 0x60, + 0xa1, 0xc1, 0x27, 0x91, 0x5b, 0x0a, 0x98, 0x46, 0x1b, 0xf6, 0xa2, 0x84, + 0xf8, 0x65, 0xc7, 0xce, 0x2d, 0x96, 0x17, 0xaa, 0x91, 0xf8, 0x61, 0x04, + 0x50, 0x70, 0xeb, 0xb4, 0x43, 0xb7, 0xdc, 0x9a, 0xcc, 0x31, 0x01, 0x14, + 0xd4, 0xcd, 0xcc, 0xc2, 0x37, 0x6d, 0x69, 0x82, 0xd6, 0xc6, 0xc4, 0xbe, + 0xf2, 0x34, 0xa5, 0xc9, 0xa6, 0x19, 0x53, 0x32, 0x7a, 0x86, 0x0e, 0x91, + 0x82, 0x0f, 0xa1, 0x42, 0x54, 0xaa, 0x01, 0x02, 0x03, 0x01, 0x00, 0x01, + 0x02, 0x81, 0x81, 0x00, 0x95, 0xaa, 0x6e, 0x11, 0xf5, 0x6a, 0x8b, 0xa2, + 0xc6, 0x48, 0xc6, 0x7c, 0x37, 0x6b, 0x1f, 0x55, 0x10, 0x76, 0x26, 0x24, + 0xc3, 0xf2, 0x5c, 0x5a, 0xdd, 0x2e, 0xf3, 0xa4, 0x1e, 0xbc, 0x7b, 0x1c, + 0x80, 0x10, 0x85, 0xbc, 0xd8, 0x45, 0x3c, 0xb8, 0xb2, 0x06, 0x53, 0xb5, + 0xd5, 0x7a, 0xe7, 0x0e, 0x92, 0xe6, 0x42, 0xc2, 0xe2, 0x2a, 0xd5, 0xd1, + 0x03, 0x9f, 0x6f, 0x53, 0x74, 0x68, 0x72, 0x8e, 0xbf, 0x03, 0xbb, 0xab, + 0xbd, 0xa1, 0xf9, 0x81, 0x7d, 0x12, 0xd4, 0x9d, 0xb6, 0xae, 0x4c, 0xad, + 0xca, 0xa8, 0xc9, 0x80, 0x8d, 0x0d, 0xd5, 0xd0, 0xa1, 0xbf, 0xec, 0x60, + 0x48, 0x49, 0xed, 0x97, 0x0f, 0x5e, 0xed, 0xfc, 0x39, 0x15, 0x96, 0x9e, + 0x5d, 0xe2, 0xb4, 0x5d, 0x2e, 0x04, 0xdc, 0x08, 0xa2, 0x65, 0x29, 0x2d, + 0x37, 0xfb, 0x62, 0x90, 0x1b, 0x7b, 0xe5, 0x3a, 0x58, 0x05, 0x55, 0xc1, + 0x02, 0x41, 0x00, 0xfc, 0x69, 0x28, 0xc9, 0xa8, 0xc4, 0x5c, 0xe3, 0xd0, + 0x5e, 0xaa, 0xda, 0xde, 0x87, 0x74, 0xdb, 0xcb, 0x40, 0x78, 0x8e, 0x1d, + 0x12, 0x96, 0x16, 0x61, 0x3f, 0xb3, 0x3e, 0xa3, 0x0d, 0xdc, 0x49, 0xa5, + 0x25, 0x87, 0xc5, 0x97, 0x85, 0x9d, 0xbb, 0xb4, 0xf0, 0x44, 0xfd, 0x6c, + 0xe8, 0xd2, 0x8c, 0xec, 0x33, 0x81, 0x46, 0x1e, 0x10, 0x12, 0x33, 0x16, + 0x95, 0x00, 0x4f, 0x75, 0xb4, 0xe5, 0x79, 0x02, 0x41, 0x00, 0xd0, 0xeb, + 0x65, 0x07, 0x10, 0x3b, 0xd9, 0x03, 0xeb, 0xdc, 0x6f, 0x4b, 0x8f, 0xc3, + 0x87, 0xce, 0x76, 0xd6, 0xc5, 0x14, 0x21, 0x4e, 0xe7, 0x4f, 0x1b, 0xe8, + 0x05, 0xf8, 0x84, 0x1a, 0xe0, 0xc5, 0xd6, 0xe3, 0x08, 0xb3, 0x54, 0x57, + 0x02, 0x1f, 0xd4, 0xd9, 0xfb, 0xff, 0x40, 0xb1, 0x56, 0x1c, 0x60, 0xf7, + 0xac, 0x91, 0xf3, 0xd3, 0xc6, 0x7f, 0x84, 0xfd, 0x84, 0x9d, 0xea, 0x26, + 0xee, 0xc9, 0x02, 0x41, 0x00, 0xa6, 0xcf, 0x1c, 0x6c, 0x81, 0x03, 0x1c, + 0x5c, 0x56, 0x05, 0x6a, 0x26, 0x70, 0xef, 0xd6, 0x13, 0xb7, 0x74, 0x28, + 0xf7, 0xca, 0x50, 0xd1, 0x2d, 0x83, 0x21, 0x64, 0xe4, 0xdd, 0x3f, 0x38, + 0xb8, 0xd6, 0xd2, 0x41, 0xb3, 0x1c, 0x9a, 0xea, 0x0d, 0xf5, 0xda, 0xdf, + 0xcd, 0x17, 0x9f, 0x9a, 0x1e, 0x15, 0xaf, 0x48, 0x1c, 0xbd, 0x9b, 0x63, + 0x5b, 0xad, 0xed, 0xd4, 0xa1, 0xae, 0xa9, 0x59, 0x09, 0x02, 0x40, 0x4e, + 0x08, 0xce, 0xa8, 0x8f, 0xc0, 0xba, 0xf3, 0x83, 0x02, 0xc8, 0x33, 0x62, + 0x14, 0x77, 0xc2, 0x7f, 0x93, 0x02, 0xf3, 0xdc, 0xe9, 0x1a, 0xee, 0xea, + 0x8e, 0x84, 0xc4, 0x69, 0x9b, 0x9c, 0x7f, 0x69, 0x1f, 0x4e, 0x1d, 0xa5, + 0x90, 0x06, 0x44, 0x1b, 0x7d, 0xfc, 0x69, 0x40, 0x21, 0xbc, 0xf7, 0x46, + 0xa4, 0xdc, 0x39, 0x7b, 0xe8, 0x8b, 0x49, 0x10, 0x44, 0x9d, 0x67, 0x5a, + 0x91, 0x86, 0x39, 0x02, 0x40, 0x41, 0x2c, 0x4e, 0xfe, 0xd9, 0x90, 0x89, + 0x00, 0x5c, 0x94, 0x0a, 0x4a, 0x7e, 0x1b, 0x1a, 0x80, 0x06, 0x01, 0x37, + 0xda, 0x50, 0x61, 0x9d, 0x9c, 0xfe, 0x25, 0x7f, 0xd8, 0xd4, 0xc4, 0x9e, + 0x81, 0xf2, 0x0c, 0x1e, 0x38, 0x21, 0x1e, 0x90, 0x3f, 0xd4, 0xba, 0x6c, + 0x53, 0xcb, 0xf0, 0x77, 0x79, 0x9b, 0xf1, 0xfa, 0x3f, 0x81, 0xdc, 0xf3, + 0x21, 0x02, 0x6d, 0xb7, 0x95, 0xc3, 0x2e, 0xce, 0xd5 +}; +unsigned int default_private_key_len = 609; diff --git a/features/unsupported/net/https/axTLS/ssl/ssl.h b/features/unsupported/net/https/axTLS/ssl/ssl.h new file mode 100644 index 00000000000..9625896d111 --- /dev/null +++ b/features/unsupported/net/https/axTLS/ssl/ssl.h @@ -0,0 +1,499 @@ +/* + * Copyright (c) 2007, Cameron Rich + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * * Neither the name of the axTLS project nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @mainpage axTLS API + * + * @image html axolotl.jpg + * + * The axTLS library has features such as: + * - The TLSv1 SSL client/server protocol + * - No requirement to use any openssl libraries. + * - A choice between AES block (128/256 bit) and RC4 (128 bit) stream ciphers. + * - RSA encryption/decryption with variable sized keys (up to 4096 bits). + * - Certificate chaining and peer authentication. + * - Session resumption, session renegotiation. + * - ASN.1, X.509, PKCS#8, PKCS#12 keys/certificates with DER/PEM encoding. + * - Highly configurable compile time options. + * - Portable across many platforms (written in ANSI C), and has language + * bindings in C, C#, VB.NET, Java, Perl and Lua. + * - Partial openssl API compatibility (via a wrapper). + * - A very small footprint (around 50-60kB for the library in 'server-only' + * mode). + * - No dependencies on sockets - can use serial connections for example. + * - A very simple API - ~ 20 functions/methods. + * + * A list of these functions/methods are described below. + * + * @ref c_api + * + * @ref bigint_api + * + * @ref csharp_api + * + * @ref java_api + */ +#ifndef HEADER_SSL_H +#define HEADER_SSL_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +/* need to predefine before ssl_lib.h gets to it */ +#define SSL_SESSION_ID_SIZE 32 + +#include "tls1.h" + +/* The optional parameters that can be given to the client/server SSL engine */ +#define SSL_CLIENT_AUTHENTICATION 0x00010000 +#define SSL_SERVER_VERIFY_LATER 0x00020000 +#define SSL_NO_DEFAULT_KEY 0x00040000 +#define SSL_DISPLAY_STATES 0x00080000 +#define SSL_DISPLAY_BYTES 0x00100000 +#define SSL_DISPLAY_CERTS 0x00200000 +#define SSL_DISPLAY_RSA 0x00400000 +#define SSL_CONNECT_IN_PARTS 0x00800000 + +/* errors that can be generated */ +#define SSL_OK 0 +#define SSL_NOT_OK -1 +#define SSL_ERROR_DEAD -2 +#define SSL_CLOSE_NOTIFY -3 +#define SSL_ERROR_CONN_LOST -256 +#define SSL_ERROR_SOCK_SETUP_FAILURE -258 +#define SSL_ERROR_INVALID_HANDSHAKE -260 +#define SSL_ERROR_INVALID_PROT_MSG -261 +#define SSL_ERROR_INVALID_HMAC -262 +#define SSL_ERROR_INVALID_VERSION -263 +#define SSL_ERROR_INVALID_SESSION -265 +#define SSL_ERROR_NO_CIPHER -266 +#define SSL_ERROR_BAD_CERTIFICATE -268 +#define SSL_ERROR_INVALID_KEY -269 +#define SSL_ERROR_FINISHED_INVALID -271 +#define SSL_ERROR_NO_CERT_DEFINED -272 +#define SSL_ERROR_NO_CLIENT_RENOG -273 +#define SSL_ERROR_NOT_SUPPORTED -274 +#define SSL_X509_OFFSET -512 +#define SSL_X509_ERROR(A) (SSL_X509_OFFSET+A) + +/* alert types that are recognized */ +#define SSL_ALERT_TYPE_WARNING 1 +#define SLL_ALERT_TYPE_FATAL 2 + +/* these are all the alerts that are recognized */ +#define SSL_ALERT_CLOSE_NOTIFY 0 +#define SSL_ALERT_UNEXPECTED_MESSAGE 10 +#define SSL_ALERT_BAD_RECORD_MAC 20 +#define SSL_ALERT_HANDSHAKE_FAILURE 40 +#define SSL_ALERT_BAD_CERTIFICATE 42 +#define SSL_ALERT_ILLEGAL_PARAMETER 47 +#define SSL_ALERT_DECODE_ERROR 50 +#define SSL_ALERT_DECRYPT_ERROR 51 +#define SSL_ALERT_INVALID_VERSION 70 +#define SSL_ALERT_NO_RENEGOTIATION 100 + +/* The ciphers that are supported */ +#define SSL_AES128_SHA 0x2f +#define SSL_AES256_SHA 0x35 +#define SSL_RC4_128_SHA 0x05 +#define SSL_RC4_128_MD5 0x04 + +/* build mode ids' */ +#define SSL_BUILD_SKELETON_MODE 0x01 +#define SSL_BUILD_SERVER_ONLY 0x02 +#define SSL_BUILD_ENABLE_VERIFICATION 0x03 +#define SSL_BUILD_ENABLE_CLIENT 0x04 +#define SSL_BUILD_FULL_MODE 0x05 + +/* offsets to retrieve configuration information */ +#define SSL_BUILD_MODE 0 +#define SSL_MAX_CERT_CFG_OFFSET 1 +#define SSL_MAX_CA_CERT_CFG_OFFSET 2 +#define SSL_HAS_PEM 3 + +/* default session sizes */ +#define SSL_DEFAULT_SVR_SESS 5 +#define SSL_DEFAULT_CLNT_SESS 1 + +/* X.509/X.520 distinguished name types */ +#define SSL_X509_CERT_COMMON_NAME 0 +#define SSL_X509_CERT_ORGANIZATION 1 +#define SSL_X509_CERT_ORGANIZATIONAL_NAME 2 +#define SSL_X509_CA_CERT_COMMON_NAME 3 +#define SSL_X509_CA_CERT_ORGANIZATION 4 +#define SSL_X509_CA_CERT_ORGANIZATIONAL_NAME 5 + +/* SSL object loader types */ +#define SSL_OBJ_X509_CERT 1 +#define SSL_OBJ_X509_CACERT 2 +#define SSL_OBJ_RSA_KEY 3 +#define SSL_OBJ_PKCS8 4 +#define SSL_OBJ_PKCS12 5 + +/** + * @defgroup c_api Standard C API + * @brief The standard interface in C. + * @{ + */ + +/** + * @brief Establish a new client/server context. + * + * This function is called before any client/server SSL connections are made. + * + * Each new connection will use the this context's private key and + * certificate chain. If a different certificate chain is required, then a + * different context needs to be be used. + * + * There are two threading models supported - a single thread with one + * SSL_CTX can support any number of SSL connections - and multiple threads can + * support one SSL_CTX object each (the default). But if a single SSL_CTX + * object uses many SSL objects in individual threads, then the + * CONFIG_SSL_CTX_MUTEXING option needs to be configured. + * + * @param options [in] Any particular options. At present the options + * supported are: + * - SSL_SERVER_VERIFY_LATER (client only): Don't stop a handshake if the server + * authentication fails. The certificate can be authenticated later with a + * call to ssl_verify_cert(). + * - SSL_CLIENT_AUTHENTICATION (server only): Enforce client authentication + * i.e. each handshake will include a "certificate request" message from the + * server. Only available if verification has been enabled. + * - SSL_DISPLAY_BYTES (full mode build only): Display the byte sequences + * during the handshake. + * - SSL_DISPLAY_STATES (full mode build only): Display the state changes + * during the handshake. + * - SSL_DISPLAY_CERTS (full mode build only): Display the certificates that + * are passed during a handshake. + * - SSL_DISPLAY_RSA (full mode build only): Display the RSA key details that + * are passed during a handshake. + * - SSL_CONNECT_IN_PARTS (client only): To use a non-blocking version of + * ssl_client_new(). + * @param num_sessions [in] The number of sessions to be used for session + * caching. If this value is 0, then there is no session caching. This option + * is not used in skeleton mode. + * @return A client/server context. + */ +EXP_FUNC SSL_CTX * STDCALL ssl_ctx_new(SSL_CTX *ssl_ctx, uint32_t options, int num_sessions); + +/** + * @brief Remove a client/server context. + * + * Frees any used resources used by this context. Each connection will be + * sent a "Close Notify" alert (if possible). + * @param ssl_ctx [in] The client/server context. + */ +EXP_FUNC void STDCALL ssl_ctx_free(SSL_CTX *ssl_ctx); + +/** + * @brief (server only) Establish a new SSL connection to an SSL client. + * + * It is up to the application to establish the logical connection (whether it + * is a socket, serial connection etc). + * @param ssl_ctx [in] The server context. + * @param client_fd [in] The client's file descriptor. + * @return An SSL object reference. + */ +EXP_FUNC SSL * STDCALL ssl_server_new(SSL_CTX *ssl_ctx, int client_fd); + +/** + * @brief (client only) Establish a new SSL connection to an SSL server. + * + * It is up to the application to establish the initial logical connection + * (whether it is a socket, serial connection etc). + * + * This is a normally a blocking call - it will finish when the handshake is + * complete (or has failed). To use in non-blocking mode, set + * SSL_CONNECT_IN_PARTS in ssl_ctx_new(). + * @param ssl_ctx [in] The client context. + * @param client_fd [in] The client's file descriptor. + * @param session_id [in] A 32 byte session id for session resumption. This + * can be null if no session resumption is being used or required. This option + * is not used in skeleton mode. + * @param sess_id_size The size of the session id (max 32) + * @return An SSL object reference. Use ssl_handshake_status() to check + * if a handshake succeeded. + */ +EXP_FUNC SSL * STDCALL ssl_client_new(SSL *ssl, int client_fd, const uint8_t *session_id, uint8_t sess_id_size); + +/** + * @brief Free any used resources on this connection. + + * A "Close Notify" message is sent on this connection (if possible). It is up + * to the application to close the socket or file descriptor. + * @param ssl [in] The ssl object reference. + */ +EXP_FUNC void STDCALL ssl_free(SSL *ssl); + +/** + * @brief Read the SSL data stream. + * If the socket is non-blocking and data is blocked then SSO_OK will be + * returned. + * @param ssl [in] An SSL object reference. + * @param in_data [out] If the read was successful, a pointer to the read + * buffer will be here. Do NOT ever free this memory as this buffer is used in + * sucessive calls. If the call was unsuccessful, this value will be null. + * @return The number of decrypted bytes: + * - if > 0, then the handshaking is complete and we are returning the number + * of decrypted bytes. + * - SSL_OK if the handshaking stage is successful (but not yet complete). + * - < 0 if an error. + * @see ssl.h for the error code list. + * @note Use in_data before doing any successive ssl calls. + */ +//EXP_FUNC int STDCALL ssl_read(SSL *ssl, uint8_t **in_data); + +/** + * @brief Write to the SSL data stream. + * if the socket is non-blocking and data is blocked then a check is made + * to ensure that all data is sent (i.e. blocked mode is forced). + * @param ssl [in] An SSL obect reference. + * @param out_data [in] The data to be written + * @param out_len [in] The number of bytes to be written. + * @return The number of bytes sent, or if < 0 if an error. + * @see ssl.h for the error code list. + */ +EXP_FUNC int STDCALL ssl_write(SSL *ssl, const uint8_t *out_data, int out_len); + +/** + * @brief Find an ssl object based on a file descriptor. + * + * Goes through the list of SSL objects maintained in a client/server context + * to look for a file descriptor match. + * @param ssl_ctx [in] The client/server context. + * @param client_fd [in] The file descriptor. + * @return A reference to the SSL object. Returns null if the object could not + * be found. + */ +EXP_FUNC SSL * STDCALL ssl_find(SSL_CTX *ssl_ctx, int client_fd); + +/** + * @brief Get the session id for a handshake. + * + * This will be a 32 byte sequence and is available after the first + * handshaking messages are sent. + * @param ssl [in] An SSL object reference. + * @return The session id as a 32 byte sequence. + * @note A SSLv23 handshake may have only 16 valid bytes. + */ +EXP_FUNC const uint8_t * STDCALL ssl_get_session_id(const SSL *ssl); + +/** + * @brief Get the session id size for a handshake. + * + * This will normally be 32 but could be 0 (no session id) or something else. + * @param ssl [in] An SSL object reference. + * @return The size of the session id. + */ +EXP_FUNC uint8_t STDCALL ssl_get_session_id_size(const SSL *ssl); + +/** + * @brief Return the cipher id (in the SSL form). + * @param ssl [in] An SSL object reference. + * @return The cipher id. This will be one of the following: + * - SSL_AES128_SHA (0x2f) + * - SSL_AES256_SHA (0x35) + * - SSL_RC4_128_SHA (0x05) + * - SSL_RC4_128_MD5 (0x04) + */ +EXP_FUNC uint8_t STDCALL ssl_get_cipher_id(const SSL *ssl); + +/** + * @brief Return the status of the handshake. + * @param ssl [in] An SSL object reference. + * @return SSL_OK if the handshake is complete and ok. + * @see ssl.h for the error code list. + */ +EXP_FUNC int STDCALL ssl_handshake_status(const SSL *ssl); + +/** + * @brief Retrieve various parameters about the axTLS engine. + * @param offset [in] The configuration offset. It will be one of the following: + * - SSL_BUILD_MODE The build mode. This will be one of the following: + * - SSL_BUILD_SERVER_ONLY (basic server mode) + * - SSL_BUILD_ENABLE_VERIFICATION (server can do client authentication) + * - SSL_BUILD_ENABLE_CLIENT (client/server capabilties) + * - SSL_BUILD_FULL_MODE (client/server with diagnostics) + * - SSL_BUILD_SKELETON_MODE (skeleton mode) + * - SSL_MAX_CERT_CFG_OFFSET The maximum number of certificates allowed. + * - SSL_MAX_CA_CERT_CFG_OFFSET The maximum number of CA certificates allowed. + * - SSL_HAS_PEM 1 if supported + * @return The value of the requested parameter. + */ +EXP_FUNC int STDCALL ssl_get_config(int offset); + +/** + * @brief Display why the handshake failed. + * + * This call is only useful in a 'full mode' build. The output is to stdout. + * @param error_code [in] An error code. + * @see ssl.h for the error code list. + */ +EXP_FUNC void STDCALL ssl_display_error(int error_code); + +/** + * @brief Authenticate a received certificate. + * + * This call is usually made by a client after a handshake is complete and the + * context is in SSL_SERVER_VERIFY_LATER mode. + * @param ssl [in] An SSL object reference. + * @return SSL_OK if the certificate is verified. + */ +EXP_FUNC int STDCALL ssl_verify_cert(const SSL *ssl); + +/** + * @brief Retrieve an X.509 distinguished name component. + * + * When a handshake is complete and a certificate has been exchanged, then the + * details of the remote certificate can be retrieved. + * + * This will usually be used by a client to check that the server's common + * name matches the URL. + * + * @param ssl [in] An SSL object reference. + * @param component [in] one of: + * - SSL_X509_CERT_COMMON_NAME + * - SSL_X509_CERT_ORGANIZATION + * - SSL_X509_CERT_ORGANIZATIONAL_NAME + * - SSL_X509_CA_CERT_COMMON_NAME + * - SSL_X509_CA_CERT_ORGANIZATION + * - SSL_X509_CA_CERT_ORGANIZATIONAL_NAME + * @return The appropriate string (or null if not defined) + * @note Verification build mode must be enabled. + */ +EXP_FUNC const char * STDCALL ssl_get_cert_dn(const SSL *ssl, int component); + +/** + * @brief Retrieve a Subject Alternative DNSName + * + * When a handshake is complete and a certificate has been exchanged, then the + * details of the remote certificate can be retrieved. + * + * This will usually be used by a client to check that the server's DNS + * name matches the URL. + * + * @param ssl [in] An SSL object reference. + * @param dnsindex [in] The index of the DNS name to retrieve. + * @return The appropriate string (or null if not defined) + * @note Verification build mode must be enabled. + */ +EXP_FUNC const char * STDCALL ssl_get_cert_subject_alt_dnsname(const SSL *ssl, int dnsindex); + +/** + * @brief Force the client to perform its handshake again. + * + * For a client this involves sending another "client hello" message. + * For the server is means sending a "hello request" message. + * + * This is a blocking call on the client (until the handshake completes). + * + * @param ssl [in] An SSL object reference. + * @return SSL_OK if renegotiation instantiation was ok + */ +EXP_FUNC int STDCALL ssl_renegotiate(SSL *ssl); + +/** + * @brief Process a file that is in binary DER or ASCII PEM format. + * + * These are temporary objects that are used to load private keys, + * certificates etc into memory. + * @param ssl_ctx [in] The client/server context. + * @param obj_type [in] The format of the file. Can be one of: + * - SSL_OBJ_X509_CERT (no password required) + * - SSL_OBJ_X509_CACERT (no password required) + * - SSL_OBJ_RSA_KEY (AES128/AES256 PEM encryption supported) + * - SSL_OBJ_PKCS8 (RC4-128 encrypted data supported) + * - SSL_OBJ_PKCS12 (RC4-128 encrypted data supported) + * + * PEM files are automatically detected (if supported). The object type is + * also detected, and so is not relevant for these types of files. + * @param filename [in] The location of a file in DER/PEM format. + * @param password [in] The password used. Can be null if not required. + * @return SSL_OK if all ok + * @note Not available in skeleton build mode. + */ +EXP_FUNC int STDCALL ssl_obj_load(SSL_CTX *ssl_ctx, int obj_type, const char *filename, const char *password); + +/** + * @brief Process binary data. + * + * These are temporary objects that are used to load private keys, + * certificates etc into memory. + * @param ssl_ctx [in] The client/server context. + * @param obj_type [in] The format of the memory data. + * @param data [in] The binary data to be loaded. + * @param len [in] The amount of data to be loaded. + * @param password [in] The password used. Can be null if not required. + * @return SSL_OK if all ok + * @see ssl_obj_load for more details on obj_type. + */ +EXP_FUNC int STDCALL ssl_obj_memory_load(SSL_CTX *ssl_ctx, int obj_type, const uint8_t *data, int len, const char *password); + +#ifdef CONFIG_SSL_GENERATE_X509_CERT +/** + * @brief Create an X.509 certificate. + * + * This certificate is a self-signed v1 cert with a fixed start/stop validity + * times. It is signed with an internal private key in ssl_ctx. + * + * @param ssl_ctx [in] The client/server context. + * @param options [in] Not used yet. + * @param dn [in] An array of distinguished name strings. The array is defined + * by: + * - SSL_X509_CERT_COMMON_NAME (0) + * - If SSL_X509_CERT_COMMON_NAME is empty or not defined, then the + * hostname will be used. + * - SSL_X509_CERT_ORGANIZATION (1) + * - If SSL_X509_CERT_ORGANIZATION is empty or not defined, then $USERNAME + * will be used. + * - SSL_X509_CERT_ORGANIZATIONAL_NAME (2) + * - SSL_X509_CERT_ORGANIZATIONAL_NAME is optional. + * @param cert_data [out] The certificate as a sequence of bytes. + * @return < 0 if an error, or the size of the certificate in bytes. + * @note cert_data must be freed when there is no more need for it. + */ +EXP_FUNC int STDCALL ssl_x509_create(SSL_CTX *ssl_ctx, uint32_t options, const char * dn[], uint8_t **cert_data); +#endif + +/** + * @brief Return the axTLS library version as a string. + */ +EXP_FUNC const char * STDCALL ssl_version(void); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/features/unsupported/net/https/axTLS/ssl/tls1.c b/features/unsupported/net/https/axTLS/ssl/tls1.c new file mode 100644 index 00000000000..ab1e86d1555 --- /dev/null +++ b/features/unsupported/net/https/axTLS/ssl/tls1.c @@ -0,0 +1,2324 @@ +/* + * Copyright (c) 2007, Cameron Rich + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * * Neither the name of the axTLS project nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * Common ssl/tlsv1 code to both the client and server implementations. + */ + + +#include +#include +#include +#include +#include + + + +#include "lwip/sockets.h" +#include "os_port.h" +#include "ssl.h" +#include "arch.h" + + +/* The session expiry time */ +#define SSL_EXPIRY_TIME (CONFIG_SSL_EXPIRY_TIME*3600) + +static const uint8_t g_hello_request[] = { HS_HELLO_REQUEST, 0, 0, 0 }; +static const uint8_t g_chg_cipher_spec_pkt[] = { 1 }; +static const char * server_finished = "server finished"; +static const char * client_finished = "client finished"; + +static int do_handshake(SSL *ssl, uint8_t *buf, int read_len); +static int set_key_block(SSL *ssl, int is_write); +static int verify_digest(SSL *ssl, int mode, const uint8_t *buf, int read_len); +static void *crypt_new(SSL *ssl, uint8_t *key, uint8_t *iv, int is_decrypt); +static int send_raw_packet(SSL *ssl, uint8_t protocol); + +/** + * The server will pick the cipher based on the order that the order that the + * ciphers are listed. This order is defined at compile time. + */ +#ifdef CONFIG_SSL_SKELETON_MODE +const uint8_t ssl_prot_prefs[NUM_PROTOCOLS] = +{ SSL_RC4_128_SHA }; +#else +static void session_free(SSL_SESSION *ssl_sessions[], int sess_index); + +const uint8_t ssl_prot_prefs[NUM_PROTOCOLS] = +#ifdef CONFIG_SSL_PROT_LOW /* low security, fast speed */ +{ SSL_RC4_128_SHA, SSL_AES128_SHA, SSL_AES256_SHA, SSL_RC4_128_MD5 }; +#elif CONFIG_SSL_PROT_MEDIUM /* medium security, medium speed */ +{ SSL_AES128_SHA, SSL_AES256_SHA, SSL_RC4_128_SHA, SSL_RC4_128_MD5 }; +#else /* CONFIG_SSL_PROT_HIGH */ /* high security, low speed */ +{ SSL_AES256_SHA, SSL_AES128_SHA, SSL_RC4_128_SHA, SSL_RC4_128_MD5 }; +#endif +#endif /* CONFIG_SSL_SKELETON_MODE */ + +/** + * The cipher map containing all the essentials for each cipher. + */ +#ifdef CONFIG_SSL_SKELETON_MODE +static const cipher_info_t cipher_info[NUM_PROTOCOLS] = +{ + { /* RC4-SHA */ + SSL_RC4_128_SHA, /* RC4-SHA */ + 16, /* key size */ + 0, /* iv size */ + 2*(SHA1_SIZE+16), /* key block size */ + 0, /* no padding */ + SHA1_SIZE, /* digest size */ + hmac_sha1, /* hmac algorithm */ + (crypt_func)RC4_crypt, /* encrypt */ + (crypt_func)RC4_crypt /* decrypt */ + }, +}; +#else +static const cipher_info_t cipher_info[NUM_PROTOCOLS] = +{ + { /* AES128-SHA */ + SSL_AES128_SHA, /* AES128-SHA */ + 16, /* key size */ + 16, /* iv size */ + 2*(SHA1_SIZE+16+16), /* key block size */ + 16, /* block padding size */ + SHA1_SIZE, /* digest size */ + hmac_sha1, /* hmac algorithm */ + (crypt_func)AES_cbc_encrypt, /* encrypt */ + (crypt_func)AES_cbc_decrypt /* decrypt */ + }, + { /* AES256-SHA */ + SSL_AES256_SHA, /* AES256-SHA */ + 32, /* key size */ + 16, /* iv size */ + 2*(SHA1_SIZE+32+16), /* key block size */ + 16, /* block padding size */ + SHA1_SIZE, /* digest size */ + hmac_sha1, /* hmac algorithm */ + (crypt_func)AES_cbc_encrypt, /* encrypt */ + (crypt_func)AES_cbc_decrypt /* decrypt */ + }, + { /* RC4-SHA */ + SSL_RC4_128_SHA, /* RC4-SHA */ + 16, /* key size */ + 0, /* iv size */ + 2*(SHA1_SIZE+16), /* key block size */ + 0, /* no padding */ + SHA1_SIZE, /* digest size */ + hmac_sha1, /* hmac algorithm */ + (crypt_func)RC4_crypt, /* encrypt */ + (crypt_func)RC4_crypt /* decrypt */ + }, + /* + * This protocol is from SSLv2 days and is unlikely to be used - but was + * useful for testing different possible digest algorithms. + */ + { /* RC4-MD5 */ + SSL_RC4_128_MD5, /* RC4-MD5 */ + 16, /* key size */ + 0, /* iv size */ + 2*(MD5_SIZE+16), /* key block size */ + 0, /* no padding */ + MD5_SIZE, /* digest size */ + hmac_md5, /* hmac algorithm */ + (crypt_func)RC4_crypt, /* encrypt */ + (crypt_func)RC4_crypt /* decrypt */ + }, +}; +#endif + +static void prf(const uint8_t *sec, int sec_len, uint8_t *seed, int seed_len, + uint8_t *out, int olen); +static const cipher_info_t *get_cipher_info(uint8_t cipher); +static void increment_read_sequence(SSL *ssl); +static void increment_write_sequence(SSL *ssl); +static void add_hmac_digest(SSL *ssl, int snd, uint8_t *hmac_header, + const uint8_t *buf, int buf_len, uint8_t *hmac_buf); + +/* win32 VC6.0 doesn't have variadic macros */ +#if defined(WIN32) && !defined(CONFIG_SSL_FULL_MODE) +void DISPLAY_BYTES(SSL *ssl, const char *format, + const uint8_t *data, int size, ...) {} +#endif + +/** + * Establish a new client/server context. + */ +EXP_FUNC SSL_CTX *STDCALL ssl_ctx_new(SSL_CTX *ssl_ctx, uint32_t options, int num_sessions) +{ + ssl_ctx->options = options; + RNG_initialize(); + + if (load_key_certs(ssl_ctx) < 0) + { + printf("error loading key certs\r\n"); + //free(ssl_ctx); /* can't load our key/certificate pair, so die */ + return NULL; + } + +#ifndef CONFIG_SSL_SKELETON_MODE + ssl_ctx->num_sessions = num_sessions; +#endif + + SSL_CTX_MUTEX_INIT(ssl_ctx->mutex); + +#ifndef CONFIG_SSL_SKELETON_MODE + if (num_sessions) + { + ssl_ctx->ssl_sessions = (SSL_SESSION **) + calloc(1, num_sessions*sizeof(SSL_SESSION *)); + } +#endif + + return ssl_ctx; +} + +/* + * Remove a client/server context. + */ +EXP_FUNC void STDCALL ssl_ctx_free(SSL_CTX *ssl_ctx) +{ + SSL *ssl; + int i; + + if (ssl_ctx == NULL) + return; + + ssl = ssl_ctx->head; + + /* clear out all the ssl entries */ + while (ssl) + { + SSL *next = ssl->next; + ssl_free(ssl); + ssl = next; + } + +#ifndef CONFIG_SSL_SKELETON_MODE + /* clear out all the sessions */ + for (i = 0; i < ssl_ctx->num_sessions; i++) + session_free(ssl_ctx->ssl_sessions, i); + + free(ssl_ctx->ssl_sessions); +#endif + + i = 0; + //while (i < CONFIG_SSL_MAX_CERTS && ssl_ctx->certs[i].buf) + { + //free(ssl_ctx->certs[i].buf); + //ssl_ctx->certs[i++].buf = NULL; + } + +#ifdef CONFIG_SSL_CERT_VERIFICATION + remove_ca_certs(ssl_ctx->ca_cert_ctx); +#endif + ssl_ctx->chain_length = 0; + SSL_CTX_MUTEX_DESTROY(ssl_ctx->mutex); + RSA_free(ssl_ctx->rsa_ctx); + RNG_terminate(); + //free(ssl_ctx); +} + +/* + * Free any used resources used by this connection. + */ +EXP_FUNC void STDCALL ssl_free(SSL *ssl) +{ + SSL_CTX *ssl_ctx; + + if (ssl == NULL) /* just ignore null pointers */ + return; + + /* only notify if we weren't notified first */ + /* spec says we must notify when we are dying */ + if (!IS_SET_SSL_FLAG(SSL_SENT_CLOSE_NOTIFY)) + send_alert(ssl, SSL_ALERT_CLOSE_NOTIFY); + + ssl_ctx = ssl->ssl_ctx; + + SSL_CTX_LOCK(ssl_ctx->mutex); + + /* adjust the server SSL list */ + if (ssl->prev) + ssl->prev->next = ssl->next; + else + ssl_ctx->head = ssl->next; + + if (ssl->next) + ssl->next->prev = ssl->prev; + else + ssl_ctx->tail = ssl->prev; + + SSL_CTX_UNLOCK(ssl_ctx->mutex); + + /* may already be free - but be sure */ + free(ssl->encrypt_ctx); + free(ssl->decrypt_ctx); + disposable_free(ssl); + +#ifdef CONFIG_SSL_CERT_VERIFICATION + x509_free(ssl->x509_ctx); +#endif + //free(ssl->ssl_ctx); + //free(ssl); +} + +/* + * Write application data to the client + */ +EXP_FUNC int STDCALL ssl_write(SSL *ssl, const uint8_t *out_data, int out_len) +{ + int n = out_len, nw, i, tot = 0; + + /* maximum size of a TLS packet is around 16kB, so fragment */ + do + { + nw = n; + + if (nw > RT_MAX_PLAIN_LENGTH) /* fragment if necessary */ + nw = RT_MAX_PLAIN_LENGTH; + + if ((i = send_packet(ssl, PT_APP_PROTOCOL_DATA, + &out_data[tot], nw)) <= 0) + { + out_len = i; /* an error */ + break; + } + + tot += i; + n -= i; + } while (n > 0); + + return out_len; +} + +/** + * Add a certificate to the certificate chain. + */ +int add_cert(SSL_CTX *ssl_ctx, const uint8_t *buf, int len) +{ + int ret = SSL_ERROR_NO_CERT_DEFINED, i = 0; + SSL_CERT *ssl_cert; + X509_CTX *cert = NULL; + int offset; + + while (ssl_ctx->certs[i].buf && i < CONFIG_SSL_MAX_CERTS) + i++; + + if (i == CONFIG_SSL_MAX_CERTS) /* too many certs */ + { +#ifdef CONFIG_SSL_FULL_MODE + printf("Error: maximum number of certs added (%d) - change of " + "compile-time configuration required\n", + CONFIG_SSL_MAX_CERTS); +#endif + goto error; + } + + if ((ret = x509_new(buf, &offset, &cert))) + goto error; + +#if defined (CONFIG_SSL_FULL_MODE) + if (ssl_ctx->options & SSL_DISPLAY_CERTS) + x509_print(cert, NULL); +#endif + + ssl_cert = &ssl_ctx->certs[i]; + ssl_cert->size = len; + ssl_cert->buf = buf; + ssl_ctx->chain_length++; + len -= offset; + ret = SSL_OK; /* ok so far */ + + /* recurse? */ + if (len > 0) + { + ret = add_cert(ssl_ctx, &buf[offset], len); + } + +error: + x509_free(cert); /* don't need anymore */ + return ret; +} + +#ifdef CONFIG_SSL_CERT_VERIFICATION +/** + * Add a certificate authority. + */ +int add_cert_auth(SSL_CTX *ssl_ctx, const uint8_t *buf, int len) +{ + int ret = SSL_OK; /* ignore errors for now */ + int i = 0; + CA_CERT_CTX *ca_cert_ctx; + + if (ssl_ctx->ca_cert_ctx == NULL) + ssl_ctx->ca_cert_ctx = (CA_CERT_CTX *)calloc(1, sizeof(CA_CERT_CTX)); + + ca_cert_ctx = ssl_ctx->ca_cert_ctx; + + while (i < CONFIG_X509_MAX_CA_CERTS && ca_cert_ctx->cert[i]) + i++; + + while (len > 0) + { + int offset; + if (i >= CONFIG_X509_MAX_CA_CERTS) + { +#ifdef CONFIG_SSL_FULL_MODE + printf("Error: maximum number of CA certs added (%d) - change of " + "compile-time configuration required\n", + CONFIG_X509_MAX_CA_CERTS); +#endif + break; + } + + + /* ignore the return code */ + if (x509_new(buf, &offset, &ca_cert_ctx->cert[i]) == X509_OK) + { +#if defined (CONFIG_SSL_FULL_MODE) + if (ssl_ctx->options & SSL_DISPLAY_CERTS) + x509_print(ca_cert_ctx->cert[i], NULL); +#endif + } + + i++; + len -= offset; + } + + return ret; +} + +/* + * Retrieve an X.509 distinguished name component + */ +EXP_FUNC const char * STDCALL ssl_get_cert_dn(const SSL *ssl, int component) +{ + if (ssl->x509_ctx == NULL) + return NULL; + + switch (component) + { + case SSL_X509_CERT_COMMON_NAME: + return ssl->x509_ctx->cert_dn[X509_COMMON_NAME]; + + case SSL_X509_CERT_ORGANIZATION: + return ssl->x509_ctx->cert_dn[X509_ORGANIZATION]; + + case SSL_X509_CERT_ORGANIZATIONAL_NAME: + return ssl->x509_ctx->cert_dn[X509_ORGANIZATIONAL_UNIT]; + + case SSL_X509_CA_CERT_COMMON_NAME: + return ssl->x509_ctx->ca_cert_dn[X509_COMMON_NAME]; + + case SSL_X509_CA_CERT_ORGANIZATION: + return ssl->x509_ctx->ca_cert_dn[X509_ORGANIZATION]; + + case SSL_X509_CA_CERT_ORGANIZATIONAL_NAME: + return ssl->x509_ctx->ca_cert_dn[X509_ORGANIZATIONAL_UNIT]; + + default: + return NULL; + } +} + +/* + * Retrieve a "Subject Alternative Name" from a v3 certificate + */ +EXP_FUNC const char * STDCALL ssl_get_cert_subject_alt_dnsname(const SSL *ssl, + int dnsindex) +{ + int i; + + if (ssl->x509_ctx == NULL || ssl->x509_ctx->subject_alt_dnsnames == NULL) + return NULL; + + for (i = 0; i < dnsindex; ++i) + { + if (ssl->x509_ctx->subject_alt_dnsnames[i] == NULL) + return NULL; + } + + return ssl->x509_ctx->subject_alt_dnsnames[dnsindex]; +} + +#endif /* CONFIG_SSL_CERT_VERIFICATION */ + +/* + * Find an ssl object based on the client's file descriptor. + */ +EXP_FUNC SSL * STDCALL ssl_find(SSL_CTX *ssl_ctx, int client_fd) +{ + SSL *ssl; + + SSL_CTX_LOCK(ssl_ctx->mutex); + ssl = ssl_ctx->head; + + /* search through all the ssl entries */ + while (ssl) + { + if (ssl->client_fd == client_fd) + { + SSL_CTX_UNLOCK(ssl_ctx->mutex); + return ssl; + } + + ssl = ssl->next; + } + + SSL_CTX_UNLOCK(ssl_ctx->mutex); + return NULL; +} + +/* + * Force the client to perform its handshake again. + */ +EXP_FUNC int STDCALL ssl_renegotiate(SSL *ssl) +{ + int ret = SSL_OK; + + disposable_new(ssl); +#ifdef CONFIG_SSL_ENABLE_CLIENT + if (IS_SET_SSL_FLAG(SSL_IS_CLIENT)) + { + ret = do_client_connect(ssl); + } + else +#endif + { + send_packet(ssl, PT_HANDSHAKE_PROTOCOL, + g_hello_request, sizeof(g_hello_request)); + SET_SSL_FLAG(SSL_NEED_RECORD); + } + + return ret; +} + +/** + * @brief Get what we need for key info. + * @param cipher [in] The cipher information we are after + * @param key_size [out] The key size for the cipher + * @param iv_size [out] The iv size for the cipher + * @return The amount of key information we need. + */ +static const cipher_info_t *get_cipher_info(uint8_t cipher) +{ + int i; + + for (i = 0; i < NUM_PROTOCOLS; i++) + { + if (cipher_info[i].cipher == cipher) + { + return &cipher_info[i]; + } + } + + return NULL; /* error */ +} + +/* + * Get a new ssl context for a new connection. + */ +SSL *ssl_new(SSL *ssl, int client_fd) +{ + SSL_CTX* ssl_ctx = ssl->ssl_ctx; + ssl->need_bytes = SSL_RECORD_SIZE; /* need a record */ + ssl->client_fd = 0; + ssl->flag = SSL_NEED_RECORD; + ssl->bm_data = ssl->bm_all_data + BM_RECORD_OFFSET; + ssl->bm_read_index = 0; + ssl->hs_status = SSL_NOT_OK; /* not connected */ +#ifdef CONFIG_ENABLE_VERIFICATION + ssl->ca_cert_ctx = ssl_ctx->ca_cert_ctx; +#endif + disposable_new(ssl); + + /* a bit hacky but saves a few bytes of memory */ + ssl->flag |= ssl_ctx->options; + SSL_CTX_LOCK(ssl_ctx->mutex); + + if (ssl_ctx->head == NULL) + { + ssl_ctx->head = ssl; + ssl_ctx->tail = ssl; + } + else + { + ssl->prev = ssl_ctx->tail; + ssl_ctx->tail->next = ssl; + ssl_ctx->tail = ssl; + } + ssl->encrypt_ctx = NULL; + ssl->decrypt_ctx = NULL; + + SSL_CTX_UNLOCK(ssl_ctx->mutex); + return ssl; +} + +/* + * Add a private key to a context. + */ +int add_private_key(SSL_CTX *ssl_ctx, SSLObjLoader *ssl_obj) +{ + int ret = SSL_OK; + + /* get the private key details */ + if (asn1_get_private_key(ssl_obj->buf, ssl_obj->len, &ssl_ctx->rsa_ctx)) + { + ret = SSL_ERROR_INVALID_KEY; + goto error; + } + +error: + return ret; +} + +/** + * Increment the read sequence number (as a 64 bit endian indepenent #) + */ +static void increment_read_sequence(SSL *ssl) +{ + int i; + + for (i = 7; i >= 0; i--) + { + if (++ssl->read_sequence[i]) + break; + } +} + +/** + * Increment the read sequence number (as a 64 bit endian indepenent #) + */ +static void increment_write_sequence(SSL *ssl) +{ + int i; + + for (i = 7; i >= 0; i--) + { + if (++ssl->write_sequence[i]) + break; + } +} + +/** + * Work out the HMAC digest in a packet. + */ +static void add_hmac_digest(SSL *ssl, int mode, uint8_t *hmac_header, + const uint8_t *buf, int buf_len, uint8_t *hmac_buf) +{ + int hmac_len = buf_len + 8 + SSL_RECORD_SIZE; + uint8_t *t_buf = (uint8_t *)alloca(hmac_len+10); + + memcpy(t_buf, (mode == SSL_SERVER_WRITE || mode == SSL_CLIENT_WRITE) ? + ssl->write_sequence : ssl->read_sequence, 8); + memcpy(&t_buf[8], hmac_header, SSL_RECORD_SIZE); + memcpy(&t_buf[8+SSL_RECORD_SIZE], buf, buf_len); + + ssl->cipher_info->hmac(t_buf, hmac_len, + (mode == SSL_SERVER_WRITE || mode == SSL_CLIENT_READ) ? + ssl->server_mac : ssl->client_mac, + ssl->cipher_info->digest_size, hmac_buf); + +#if 0 + print_blob("record", hmac_header, SSL_RECORD_SIZE); + print_blob("buf", buf, buf_len); + if (mode == SSL_SERVER_WRITE || mode == SSL_CLIENT_WRITE) + { + print_blob("write seq", ssl->write_sequence, 8); + } + else + { + print_blob("read seq", ssl->read_sequence, 8); + } + + if (mode == SSL_SERVER_WRITE || mode == SSL_CLIENT_READ) + { + print_blob("server mac", + ssl->server_mac, ssl->cipher_info->digest_size); + } + else + { + print_blob("client mac", + ssl->client_mac, ssl->cipher_info->digest_size); + } + print_blob("hmac", hmac_buf, SHA1_SIZE); +#endif +} + +/** + * Verify that the digest of a packet is correct. + */ +static int verify_digest(SSL *ssl, int mode, const uint8_t *buf, int read_len) +{ + uint8_t hmac_buf[SHA1_SIZE]; + int hmac_offset; + + if (ssl->cipher_info->padding_size) + { + int last_blk_size = buf[read_len-1], i; + hmac_offset = read_len-last_blk_size-ssl->cipher_info->digest_size-1; + + /* guard against a timing attack - make sure we do the digest */ + if (hmac_offset < 0) + { + hmac_offset = 0; + } + else + { + /* already looked at last byte */ + for (i = 1; i < last_blk_size; i++) + { + if (buf[read_len-i] != last_blk_size) + { + hmac_offset = 0; + break; + } + } + } + } + else /* stream cipher */ + { + hmac_offset = read_len - ssl->cipher_info->digest_size; + + if (hmac_offset < 0) + { + hmac_offset = 0; + } + } + + /* sanity check the offset */ + ssl->hmac_header[3] = hmac_offset >> 8; /* insert size */ + ssl->hmac_header[4] = hmac_offset & 0xff; + add_hmac_digest(ssl, mode, ssl->hmac_header, buf, hmac_offset, hmac_buf); + + if (memcmp(hmac_buf, &buf[hmac_offset], ssl->cipher_info->digest_size)) + { + return SSL_ERROR_INVALID_HMAC; + } + + return hmac_offset; +} + +/** + * Add a packet to the end of our sent and received packets, so that we may use + * it to calculate the hash at the end. + */ +void add_packet(SSL *ssl, const uint8_t *pkt, int len) +{ + MD5_Update(&ssl->dc->md5_ctx, pkt, len); + SHA1_Update(&ssl->dc->sha1_ctx, pkt, len); +} + +/** + * Work out the MD5 PRF. + */ +static void p_hash_md5(const uint8_t *sec, int sec_len, + uint8_t *seed, int seed_len, uint8_t *out, int olen) +{ + uint8_t a1[128]; + + /* A(1) */ + hmac_md5(seed, seed_len, sec, sec_len, a1); + memcpy(&a1[MD5_SIZE], seed, seed_len); + hmac_md5(a1, MD5_SIZE+seed_len, sec, sec_len, out); + + while (olen > MD5_SIZE) + { + uint8_t a2[MD5_SIZE]; + out += MD5_SIZE; + olen -= MD5_SIZE; + + /* A(N) */ + hmac_md5(a1, MD5_SIZE, sec, sec_len, a2); + memcpy(a1, a2, MD5_SIZE); + + /* work out the actual hash */ + hmac_md5(a1, MD5_SIZE+seed_len, sec, sec_len, out); + } +} + +/** + * Work out the SHA1 PRF. + */ +static void p_hash_sha1(const uint8_t *sec, int sec_len, + uint8_t *seed, int seed_len, uint8_t *out, int olen) +{ + uint8_t a1[128]; + + /* A(1) */ + hmac_sha1(seed, seed_len, sec, sec_len, a1); + memcpy(&a1[SHA1_SIZE], seed, seed_len); + hmac_sha1(a1, SHA1_SIZE+seed_len, sec, sec_len, out); + + while (olen > SHA1_SIZE) + { + uint8_t a2[SHA1_SIZE]; + out += SHA1_SIZE; + olen -= SHA1_SIZE; + + /* A(N) */ + hmac_sha1(a1, SHA1_SIZE, sec, sec_len, a2); + memcpy(a1, a2, SHA1_SIZE); + + /* work out the actual hash */ + hmac_sha1(a1, SHA1_SIZE+seed_len, sec, sec_len, out); + } +} + +/** + * Work out the PRF. + */ +static void prf(const uint8_t *sec, int sec_len, uint8_t *seed, int seed_len, + uint8_t *out, int olen) +{ + int len, i; + const uint8_t *S1, *S2; + uint8_t xbuf[256]; /* needs to be > the amount of key data */ + uint8_t ybuf[256]; /* needs to be > the amount of key data */ + + len = sec_len/2; + S1 = sec; + S2 = &sec[len]; + len += (sec_len & 1); /* add for odd, make longer */ + + p_hash_md5(S1, len, seed, seed_len, xbuf, olen); + p_hash_sha1(S2, len, seed, seed_len, ybuf, olen); + + for (i = 0; i < olen; i++) + out[i] = xbuf[i] ^ ybuf[i]; +} + +/** + * Generate a master secret based on the client/server random data and the + * premaster secret. + */ +void generate_master_secret(SSL *ssl, const uint8_t *premaster_secret) +{ + uint8_t buf[128]; /* needs to be > 13+32+32 in size */ + strcpy((char *)buf, "master secret"); + memcpy(&buf[13], ssl->dc->client_random, SSL_RANDOM_SIZE); + memcpy(&buf[45], ssl->dc->server_random, SSL_RANDOM_SIZE); + prf(premaster_secret, SSL_SECRET_SIZE, buf, 77, ssl->dc->master_secret, + SSL_SECRET_SIZE); +} + +/** + * Generate a 'random' blob of data used for the generation of keys. + */ +static void generate_key_block(uint8_t *client_random, uint8_t *server_random, + uint8_t *master_secret, uint8_t *key_block, int key_block_size) +{ + uint8_t buf[128]; + strcpy((char *)buf, "key expansion"); + memcpy(&buf[13], server_random, SSL_RANDOM_SIZE); + memcpy(&buf[45], client_random, SSL_RANDOM_SIZE); + prf(master_secret, SSL_SECRET_SIZE, buf, 77, key_block, key_block_size); +} + +/** + * Calculate the digest used in the finished message. This function also + * doubles up as a certificate verify function. + */ +void finished_digest(SSL *ssl, const char *label, uint8_t *digest) +{ + uint8_t mac_buf[128]; + uint8_t *q = mac_buf; + MD5_CTX md5_ctx = ssl->dc->md5_ctx; + SHA1_CTX sha1_ctx = ssl->dc->sha1_ctx; + + if (label) + { + strcpy((char *)q, label); + q += strlen(label); + } + + MD5_Final(q, &md5_ctx); + q += MD5_SIZE; + + SHA1_Final(q, &sha1_ctx); + q += SHA1_SIZE; + + if (label) + { + prf(ssl->dc->master_secret, SSL_SECRET_SIZE, mac_buf, (int)(q-mac_buf), + digest, SSL_FINISHED_HASH_SIZE); + } + else /* for use in a certificate verify */ + { + memcpy(digest, mac_buf, MD5_SIZE + SHA1_SIZE); + } + +#if 0 + printf("label: %s\r\n", label); + print_blob("master secret", ssl->dc->master_secret, 48); + print_blob("mac_buf", mac_buf, q-mac_buf); + print_blob("finished digest", digest, SSL_FINISHED_HASH_SIZE); +#endif +} + +/** + * Retrieve (and initialise) the context of a cipher. + */ +static void *crypt_new(SSL *ssl, uint8_t *key, uint8_t *iv, int is_decrypt) +{ + switch (ssl->cipher) + { +#ifndef CONFIG_SSL_SKELETON_MODE + case SSL_AES128_SHA: + { + AES_CTX *aes_ctx = (AES_CTX *)malloc(sizeof(AES_CTX)); + AES_set_key(aes_ctx, key, iv, AES_MODE_128); + + if (is_decrypt) + { + AES_convert_key(aes_ctx); + } + + return (void *)aes_ctx; + } + + case SSL_AES256_SHA: + { + AES_CTX *aes_ctx = (AES_CTX *)malloc(sizeof(AES_CTX)); + AES_set_key(aes_ctx, key, iv, AES_MODE_256); + + if (is_decrypt) + { + AES_convert_key(aes_ctx); + } + + return (void *)aes_ctx; + } + + case SSL_RC4_128_MD5: +#endif + case SSL_RC4_128_SHA: + { + RC4_CTX *rc4_ctx = (RC4_CTX *)malloc(sizeof(RC4_CTX)); + RC4_setup(rc4_ctx, key, 16); + return (void *)rc4_ctx; + } + } + + return NULL; /* its all gone wrong */ +} + + +/** + * Send a packet over the socket. + */ +static int send_raw_packet(SSL *ssl, uint8_t protocol) +{ + uint8_t *rec_buf = ssl->bm_all_data; + int pkt_size = SSL_RECORD_SIZE+ssl->bm_index; + int sent = 0; + int ret = SSL_OK; + rec_buf[0] = protocol; + rec_buf[1] = 0x03; /* version = 3.1 or higher */ + rec_buf[2] = ssl->version & 0x0f; + rec_buf[3] = ssl->bm_index >> 8; + rec_buf[4] = ssl->bm_index & 0xff; + + DISPLAY_BYTES(ssl, "sending %d bytes", ssl->bm_all_data, + pkt_size, pkt_size); + + + + while (sent < pkt_size) + { + ret = SOCKET_WRITE(ssl->client_fd, + &ssl->bm_all_data[sent], pkt_size-sent); + if (ret >= 0) + sent += ret; + else + { + +#ifdef WIN32 + if (GetLastError() != WSAEWOULDBLOCK) +#else + if (errno != EAGAIN && errno != EWOULDBLOCK) +#endif + return SSL_ERROR_CONN_LOST; + } + + /* keep going until the write buffer has some space */ + if (sent != pkt_size) + { + fd_set wfds; + FD_ZERO(&wfds); + FD_SET(ssl->client_fd, &wfds); + + /* block and wait for it */ + if (lwip_select(FD_SETSIZE, NULL, &wfds, NULL, NULL) < 0) + return SSL_ERROR_CONN_LOST; + + } + } + fd_set wfds; + FD_ZERO(&wfds); + FD_SET(ssl->client_fd, &wfds); + + /* block and wait for it */ + if (lwip_select(FD_SETSIZE, NULL, &wfds, NULL, NULL) < 0) + return SSL_ERROR_CONN_LOST; + + SET_SSL_FLAG(SSL_NEED_RECORD); /* reset for next time */ + ssl->bm_index = 0; + + if (protocol != PT_APP_PROTOCOL_DATA) + { + /* always return SSL_OK during handshake */ + ret = SSL_OK; + } + + return ret; +} + +/** + * Send an encrypted packet with padding bytes if necessary. + */ +int send_packet(SSL *ssl, uint8_t protocol, const uint8_t *in, int length) +{ + int ret, msg_length = 0; + + /* if our state is bad, don't bother */ + if (ssl->hs_status == SSL_ERROR_DEAD) + return SSL_ERROR_CONN_LOST; + + if (in) /* has the buffer already been initialised? */ + { + memcpy(ssl->bm_data, in, length); + } + + msg_length += length; + + if (IS_SET_SSL_FLAG(SSL_TX_ENCRYPTED)) + { + int mode = IS_SET_SSL_FLAG(SSL_IS_CLIENT) ? + SSL_CLIENT_WRITE : SSL_SERVER_WRITE; + uint8_t hmac_header[SSL_RECORD_SIZE] = + { + protocol, + 0x03, /* version = 3.1 or higher */ + ssl->version & 0x0f, + msg_length >> 8, + msg_length & 0xff + }; + + if (protocol == PT_HANDSHAKE_PROTOCOL) + { + DISPLAY_STATE(ssl, 1, ssl->bm_data[0], 0); + + if (ssl->bm_data[0] != HS_HELLO_REQUEST) + { + add_packet(ssl, ssl->bm_data, msg_length); + } + } + + /* add the packet digest */ + add_hmac_digest(ssl, mode, hmac_header, ssl->bm_data, msg_length, + &ssl->bm_data[msg_length]); + msg_length += ssl->cipher_info->digest_size; + + /* add padding? */ + if (ssl->cipher_info->padding_size) + { + int last_blk_size = msg_length%ssl->cipher_info->padding_size; + int pad_bytes = ssl->cipher_info->padding_size - last_blk_size; + + /* ensure we always have at least 1 padding byte */ + if (pad_bytes == 0) + pad_bytes += ssl->cipher_info->padding_size; + + memset(&ssl->bm_data[msg_length], pad_bytes-1, pad_bytes); + msg_length += pad_bytes; + } + + DISPLAY_BYTES(ssl, "unencrypted write", ssl->bm_data, msg_length); + increment_write_sequence(ssl); + + /* add the explicit IV for TLS1.1 */ + if (ssl->version >= SSL_PROTOCOL_VERSION1_1 && + ssl->cipher_info->iv_size) + { + uint8_t iv_size = ssl->cipher_info->iv_size; + uint8_t *t_buf = alloca(msg_length + iv_size); + memcpy(t_buf + iv_size, ssl->bm_data, msg_length); + get_random(iv_size, t_buf); + msg_length += iv_size; + memcpy(ssl->bm_data, t_buf, msg_length); + } + + /* now encrypt the packet */ + ssl->cipher_info->encrypt(ssl->encrypt_ctx, ssl->bm_data, + ssl->bm_data, msg_length); + } + else if (protocol == PT_HANDSHAKE_PROTOCOL) + { + DISPLAY_STATE(ssl, 1, ssl->bm_data[0], 0); + + if (ssl->bm_data[0] != HS_HELLO_REQUEST) + { + add_packet(ssl, ssl->bm_data, length); + } + } + + ssl->bm_index = msg_length; + if ((ret = send_raw_packet(ssl, protocol)) <= 0) + return ret; + + return length; /* just return what we wanted to send */ +} + +/** + * Work out the cipher keys we are going to use for this session based on the + * master secret. + */ +static int set_key_block(SSL *ssl, int is_write) +{ + const cipher_info_t *ciph_info = get_cipher_info(ssl->cipher); + uint8_t *q; + uint8_t client_key[32], server_key[32]; /* big enough for AES256 */ + uint8_t client_iv[16], server_iv[16]; /* big enough for AES128/256 */ + int is_client = IS_SET_SSL_FLAG(SSL_IS_CLIENT); + + if (ciph_info == NULL) + return -1; + + uint8_t key_tmp[MAX_KEYBLOCK_SIZE] = {0}; + /* only do once in a handshake */ + if (memcmp(ssl->dc->key_block, key_tmp, MAX_KEYBLOCK_SIZE) == 0) + { +#if 0 + print_blob("client", ssl->dc->client_random, 32); + print_blob("server", ssl->dc->server_random, 32); + print_blob("master", ssl->dc->master_secret, SSL_SECRET_SIZE); +#endif + generate_key_block(ssl->dc->client_random, ssl->dc->server_random, + ssl->dc->master_secret, ssl->dc->key_block, + ciph_info->key_block_size); +#if 0 + print_blob("keyblock", ssl->dc->key_block, ciph_info->key_block_size); +#endif + } + + q = ssl->dc->key_block; + + if ((is_client && is_write) || (!is_client && !is_write)) + { + memcpy(ssl->client_mac, q, ciph_info->digest_size); + } + + q += ciph_info->digest_size; + + if ((!is_client && is_write) || (is_client && !is_write)) + { + memcpy(ssl->server_mac, q, ciph_info->digest_size); + } + + q += ciph_info->digest_size; + memcpy(client_key, q, ciph_info->key_size); + q += ciph_info->key_size; + memcpy(server_key, q, ciph_info->key_size); + q += ciph_info->key_size; + +#ifndef CONFIG_SSL_SKELETON_MODE + if (ciph_info->iv_size) /* RC4 has no IV, AES does */ + { + memcpy(client_iv, q, ciph_info->iv_size); + q += ciph_info->iv_size; + memcpy(server_iv, q, ciph_info->iv_size); + q += ciph_info->iv_size; + } +#endif + + if( (is_write ? ssl->encrypt_ctx : ssl->decrypt_ctx) != NULL) + free(is_write ? ssl->encrypt_ctx : ssl->decrypt_ctx); + + /* now initialise the ciphers */ + if (is_client) + { + finished_digest(ssl, server_finished, ssl->dc->final_finish_mac); + + if (is_write) + ssl->encrypt_ctx = crypt_new(ssl, client_key, client_iv, 0); + else + ssl->decrypt_ctx = crypt_new(ssl, server_key, server_iv, 1); + } + else + { + finished_digest(ssl, client_finished, ssl->dc->final_finish_mac); + + if (is_write) + ssl->encrypt_ctx = crypt_new(ssl, server_key, server_iv, 0); + else + ssl->decrypt_ctx = crypt_new(ssl, client_key, client_iv, 1); + } + + ssl->cipher_info = ciph_info; + return 0; +} + +/** + * Blocking read + * data must be valid buffer of size length at least + * length + */ +int basic_read2(SSL *ssl, uint8_t *data, uint32_t length) +{ + // printf("basic_read2\n"); + if(data == NULL) + return -1; + + int ret = 0; + + do + { + //printf("before_lwip_select\n"); + fd_set rfds; + FD_ZERO(&rfds); + FD_SET(ssl->client_fd, &rfds); + + /* block and wait for it */ + if (lwip_select(FD_SETSIZE, &rfds, NULL, NULL, NULL) < 0) + return SSL_ERROR_CONN_LOST; + // printf("after_lwip_select\n"); + + int read_len = SOCKET_READ(ssl->client_fd, &data[ret], length-ret); + // printf("read_len = %d\n", read_len); + + if (read_len < 0) + { + +#ifdef WIN32 + if (GetLastError() == WSAEWOULDBLOCK) +#else + if (errno == EAGAIN || errno == EWOULDBLOCK) +#endif + continue; + } + + /* connection has gone, so die */ + if (read_len <= 0) + { + printf("SSL_ERROR_CONN_LOST\n"); + ssl->hs_status = SSL_ERROR_DEAD; /* make sure it stays dead */ + return SSL_ERROR_CONN_LOST; + } + + ret += read_len; + + }while(ret < length); + DISPLAY_BYTES(ssl, "received %d bytes", data, ret, ret); + return ret; +} + +int read_record(SSL *ssl) +{ + if(!IS_SET_SSL_FLAG(SSL_NEED_RECORD)) + return 0; + uint8_t record[SSL_RECORD_SIZE]; + int ret = basic_read2(ssl, record, SSL_RECORD_SIZE); + if(ret != SSL_RECORD_SIZE) + return ret; + + /* check for sslv2 "client hello" */ + if (record[0] & 0x80 && record[2] == 1) + { +#ifdef CONFIG_SSL_ENABLE_V23_HANDSHAKE + uint8_t version = (record[3] << 4) + record[4]; + DISPLAY_BYTES(ssl, "ssl2 record", record, 5); + + /* should be v3.1 (TLSv1) or better */ + ssl->version = ssl->client_version = version; + + if (version > SSL_PROTOCOL_VERSION_MAX) + { + /* use client's version */ + ssl->version = SSL_PROTOCOL_VERSION_MAX; + } + else if (version < SSL_PROTOCOL_MIN_VERSION) + { + ret = SSL_ERROR_INVALID_VERSION; + ssl_display_error(ret); + return ret; + } + + add_packet(ssl, &record[2], 3); + ret = process_sslv23_client_hello(ssl); +#else + printf("Error: no SSLv23 handshaking allowed\n"); TTY_FLUSH(); + ret = SSL_ERROR_NOT_SUPPORTED; +#endif + return ret; + } + + ssl->need_bytes = (record[3] << 8) + record[4]; + + + memcpy(ssl->hmac_header, record, 3); /* store for hmac */ + ssl->record_type = record[0]; + CLR_SSL_FLAG(SSL_NEED_RECORD); + return SSL_OK; +} + +int basic_decrypt(SSL *ssl, uint8_t *buf, int len) +{ + if (IS_SET_SSL_FLAG(SSL_RX_ENCRYPTED)) + { + ssl->cipher_info->decrypt(ssl->decrypt_ctx, buf, buf, len); + + if (ssl->version >= SSL_PROTOCOL_VERSION1_1 && + ssl->cipher_info->iv_size) + { + buf += ssl->cipher_info->iv_size; + ssl->need_bytes -= ssl->cipher_info->iv_size; + } + if(ssl->record_type != PT_APP_PROTOCOL_DATA) + len = verify_digest(ssl, + IS_SET_SSL_FLAG(SSL_IS_CLIENT) ? SSL_CLIENT_READ : SSL_SERVER_READ, buf, len); + + /* does the hmac work? */ + if (ssl->need_bytes < 0) + { + return ssl->need_bytes; + } + + DISPLAY_BYTES(ssl, "decrypted", buf, len); + increment_read_sequence(ssl); + } + return len; +} + +int ssl_read(SSL *ssl, uint8_t *in_data, int len) +{ + if(len <= 0 || in_data == NULL) + return 0; + + if(IS_SET_SSL_FLAG(SSL_NEED_RECORD)) + { + read_record(ssl); + } + + return process_data(ssl, in_data, len); +} + +int process_data(SSL* ssl, uint8_t *in_data, int len) +{ + /* The main part of the SSL packet */ + switch (ssl->record_type) + { + case PT_HANDSHAKE_PROTOCOL: + + if (ssl->dc != NULL) + { + ssl->dc->bm_proc_index = 0; + int ret = do_handshake(ssl, NULL, 0); + SET_SSL_FLAG(SSL_NEED_RECORD); + return ret; + } + else /* no client renegotiation allowed */ + { + SET_SSL_FLAG(SSL_NEED_RECORD); + return SSL_ERROR_NO_CLIENT_RENOG; + } + + case PT_CHANGE_CIPHER_SPEC: + + if(basic_read2(ssl, ssl->bm_data, ssl->need_bytes) != ssl->need_bytes) + return -1; + ssl->need_bytes = basic_decrypt(ssl, ssl->bm_data, ssl->need_bytes); + if(ssl->need_bytes < 0) + return -1; + + if (ssl->next_state != HS_FINISHED) + { + return SSL_ERROR_INVALID_HANDSHAKE; + } + + /* all encrypted from now on */ + SET_SSL_FLAG(SSL_RX_ENCRYPTED); + if (set_key_block(ssl, 0) < 0) + { + return SSL_ERROR_INVALID_HANDSHAKE; + } + + memset(ssl->read_sequence, 0, 8); + SET_SSL_FLAG(SSL_NEED_RECORD); + break; + + case PT_APP_PROTOCOL_DATA: + if(len <= 0) + return 0; + if(ssl->need_bytes == 0) + return 0; + if (in_data) + { + uint16_t index = ssl->bm_index % 2048; + if(ssl->bm_read_index == 0) + { + int read_len = len; + if(read_len > 2048-index) + read_len = 2048-index; + if(read_len > ssl->need_bytes) + read_len = ssl->need_bytes; + read_len -= read_len % AES_BLOCKSIZE; + + if(read_len <= 0) + read_len = AES_BLOCKSIZE; + if(ssl->need_bytes < AES_BLOCKSIZE) + read_len = AES_BLOCKSIZE; + int ret = basic_read2(ssl, ssl->bm_all_data + index, read_len); + if(ret != read_len) + return 0; + + ssl->bm_read_index = basic_decrypt(ssl, ssl->bm_all_data + index, read_len); + ssl->need_bytes -= ssl->bm_read_index; + if(ssl->need_bytes == 0) + { + ssl->bm_read_index = 0; + SET_SSL_FLAG(SSL_NEED_RECORD); + return ssl_read(ssl, in_data, len); + } + } + if(len > ssl->bm_read_index) + len = ssl->bm_read_index; + memcpy(in_data, ssl->bm_all_data+index, len); + ssl->bm_index += len; + ssl->bm_read_index -= len; + + if(ssl->need_bytes == 0) + SET_SSL_FLAG(SSL_NEED_RECORD); + if(ssl->bm_index >= 2048) + ssl->bm_index = 0; + return len; + } + return 0; + + case PT_ALERT_PROTOCOL: + if(basic_read2(ssl, ssl->bm_data, ssl->need_bytes) != ssl->need_bytes) + return -1; + ssl->need_bytes = basic_decrypt(ssl, ssl->bm_data, ssl->need_bytes); + if(ssl->need_bytes < 0) + return -1; + + SET_SSL_FLAG(SSL_NEED_RECORD); + + /* return the alert # with alert bit set */ + if(ssl->bm_data[0] == SSL_ALERT_TYPE_WARNING && + ssl->bm_data[1] == SSL_ALERT_CLOSE_NOTIFY) + { + send_alert(ssl, SSL_ALERT_CLOSE_NOTIFY); + SET_SSL_FLAG(SSL_SENT_CLOSE_NOTIFY); + return SSL_CLOSE_NOTIFY; + } + else + { + int ret = -ssl->bm_data[1]; + DISPLAY_ALERT(ssl, -ret); + return ret; + } + + default: + return SSL_ERROR_INVALID_PROT_MSG; + + } +} + + +/** + * Do some basic checking of data and then perform the appropriate handshaking. + */ +static int do_handshake(SSL *ssl, uint8_t *buf, int read_len) +{ + uint8_t hs_hdr[SSL_HS_HDR_SIZE]; + if (IS_SET_SSL_FLAG(SSL_RX_ENCRYPTED)) + { + if(basic_read2(ssl, ssl->bm_data, ssl->need_bytes) != ssl->need_bytes) + return -1; + ssl->need_bytes = basic_decrypt(ssl, ssl->bm_data, ssl->need_bytes); + if(ssl->need_bytes < 0) + return -1; + buf = ssl->bm_data; + } + else + { + if(basic_read2(ssl, hs_hdr, SSL_HS_HDR_SIZE) != SSL_HS_HDR_SIZE) + return -1; + buf = hs_hdr; + } + + int hs_len = (buf[2]<<8) + buf[3]; + uint8_t handshake_type = buf[0]; + int ret = SSL_OK; + int is_client = IS_SET_SSL_FLAG(SSL_IS_CLIENT); + + /* some integrity checking on the handshake */ + //PARANOIA_CHECK(read_len-SSL_HS_HDR_SIZE, hs_len); + + if (handshake_type != ssl->next_state) + { + /* handle a special case on the client */ + if (!is_client || handshake_type != HS_CERT_REQ || + ssl->next_state != HS_SERVER_HELLO_DONE) + { + return SSL_ERROR_INVALID_HANDSHAKE; + } + } + + //hs_len += SSL_HS_HDR_SIZE; /* adjust for when adding packets */ + ssl->bm_index = hs_len+SSL_HS_HDR_SIZE; /* store the size and check later */ + DISPLAY_STATE(ssl, 0, handshake_type, 0); + + if (handshake_type != HS_CERT_VERIFY && handshake_type != HS_HELLO_REQUEST) + { + add_packet(ssl, buf, SSL_HS_HDR_SIZE); + } + + if(!IS_SET_SSL_FLAG(SSL_RX_ENCRYPTED)) + { + if(hs_len != 0 && handshake_type != HS_CERTIFICATE) + { + if(basic_read2(ssl, ssl->bm_data, hs_len) != hs_len) + return -1; + hs_len = basic_decrypt(ssl, ssl->bm_data, hs_len); + if(hs_len < 0) + return -1; + + buf = ssl->bm_data; + if (handshake_type != HS_CERT_VERIFY && handshake_type != HS_HELLO_REQUEST) + add_packet(ssl, buf, hs_len); + } + } + else if (handshake_type != HS_CERT_VERIFY && handshake_type != HS_HELLO_REQUEST) + add_packet(ssl, ssl->bm_data+SSL_HS_HDR_SIZE, hs_len-SSL_HS_HDR_SIZE); + +#if defined(CONFIG_SSL_ENABLE_CLIENT) + ret = is_client ? + do_clnt_handshake(ssl, handshake_type, buf, hs_len) : + do_svr_handshake(ssl, handshake_type, buf, hs_len); +#else + ret = do_svr_handshake(ssl, handshake_type, buf, hs_len); +#endif + + /* just use recursion to get the rest */ + //if (hs_len < read_len && ret == SSL_OK) + //ret = do_handshake(ssl, &buf[hs_len], read_len-hs_len); + + return ret; +} + +/** + * Sends the change cipher spec message. We have just read a finished message + * from the client. + */ +int send_change_cipher_spec(SSL *ssl) +{ + int ret = send_packet(ssl, PT_CHANGE_CIPHER_SPEC, + g_chg_cipher_spec_pkt, sizeof(g_chg_cipher_spec_pkt)); + SET_SSL_FLAG(SSL_TX_ENCRYPTED); + + if (ret >= 0 && set_key_block(ssl, 1) < 0) + ret = SSL_ERROR_INVALID_HANDSHAKE; + + memset(ssl->write_sequence, 0, 8); + return ret; +} + +/** + * Send a "finished" message + */ +int send_finished(SSL *ssl) +{ + uint8_t buf[SSL_FINISHED_HASH_SIZE+4] = { + HS_FINISHED, 0, 0, SSL_FINISHED_HASH_SIZE }; + + /* now add the finished digest mac (12 bytes) */ + finished_digest(ssl, + IS_SET_SSL_FLAG(SSL_IS_CLIENT) ? + client_finished : server_finished, &buf[4]); + +#ifndef CONFIG_SSL_SKELETON_MODE + /* store in the session cache */ + if (!IS_SET_SSL_FLAG(SSL_SESSION_RESUME) && ssl->ssl_ctx->num_sessions) + { + memcpy(ssl->session->master_secret, + ssl->dc->master_secret, SSL_SECRET_SIZE); + } +#endif + + return send_packet(ssl, PT_HANDSHAKE_PROTOCOL, + buf, SSL_FINISHED_HASH_SIZE+4); +} + +/** + * Send an alert message. + * Return 1 if the alert was an "error". + */ +int send_alert(SSL *ssl, int error_code) +{ + int alert_num = 0; + int is_warning = 0; + uint8_t buf[2]; + + /* Don't bother we're already dead */ + if (ssl->hs_status == SSL_ERROR_DEAD) + { + return SSL_ERROR_CONN_LOST; + } + +#ifdef CONFIG_SSL_FULL_MODE + if (IS_SET_SSL_FLAG(SSL_DISPLAY_STATES)) + ssl_display_error(error_code); +#endif + + switch (error_code) + { + case SSL_ALERT_CLOSE_NOTIFY: + is_warning = 1; + alert_num = SSL_ALERT_CLOSE_NOTIFY; + break; + + case SSL_ERROR_CONN_LOST: /* don't send alert just yet */ + is_warning = 1; + break; + + case SSL_ERROR_INVALID_HANDSHAKE: + case SSL_ERROR_INVALID_PROT_MSG: + alert_num = SSL_ALERT_HANDSHAKE_FAILURE; + break; + + case SSL_ERROR_INVALID_HMAC: + case SSL_ERROR_FINISHED_INVALID: + alert_num = SSL_ALERT_BAD_RECORD_MAC; + break; + + case SSL_ERROR_INVALID_VERSION: + alert_num = SSL_ALERT_INVALID_VERSION; + break; + + case SSL_ERROR_INVALID_SESSION: + case SSL_ERROR_NO_CIPHER: + case SSL_ERROR_INVALID_KEY: + alert_num = SSL_ALERT_ILLEGAL_PARAMETER; + break; + + case SSL_ERROR_BAD_CERTIFICATE: + alert_num = SSL_ALERT_BAD_CERTIFICATE; + break; + + case SSL_ERROR_NO_CLIENT_RENOG: + alert_num = SSL_ALERT_NO_RENEGOTIATION; + break; + + default: + /* a catch-all for any badly verified certificates */ + alert_num = (error_code <= SSL_X509_OFFSET) ? + SSL_ALERT_BAD_CERTIFICATE : SSL_ALERT_UNEXPECTED_MESSAGE; + break; + } + + buf[0] = is_warning ? 1 : 2; + buf[1] = alert_num; + + send_packet(ssl, PT_ALERT_PROTOCOL, buf, sizeof(buf)); + DISPLAY_ALERT(ssl, alert_num); + return is_warning ? 0 : 1; +} + +/** + * Process a client finished message. + */ +int process_finished(SSL *ssl, uint8_t *buf, int hs_len) +{ + int is_client = IS_SET_SSL_FLAG(SSL_IS_CLIENT); + int ret = SSL_OK; + int resume = IS_SET_SSL_FLAG(SSL_SESSION_RESUME); + + PARANOIA_CHECK(ssl->bm_index, SSL_FINISHED_HASH_SIZE); + + /* check that we all work before we continue */ + if (memcmp(ssl->dc->final_finish_mac, &buf[4], SSL_FINISHED_HASH_SIZE)) + { + return SSL_ERROR_FINISHED_INVALID; + } + if ((!is_client && !resume) || (is_client && resume)) + { + if ((ret = send_change_cipher_spec(ssl)) == SSL_OK) + ret = send_finished(ssl); + } + + /* if we ever renegotiate */ + ssl->next_state = is_client ? HS_HELLO_REQUEST : HS_CLIENT_HELLO; + ssl->hs_status = ret; /* set the final handshake status */ +error: + return ret; +} + +/** + * Send a certificate. + */ +int send_certificate(SSL *ssl) +{ + int i = 0; + uint8_t *buf = ssl->bm_data; + int offset = 7; + int chain_length; + + buf[0] = HS_CERTIFICATE; + buf[1] = 0; + buf[4] = 0; + + while (i < ssl->ssl_ctx->chain_length) + { + SSL_CERT *cert = &ssl->ssl_ctx->certs[i]; + buf[offset++] = 0; + buf[offset++] = cert->size >> 8; /* cert 1 length */ + buf[offset++] = cert->size & 0xff; + memcpy(&buf[offset], cert->buf, cert->size); + offset += cert->size; + i++; + } + + chain_length = offset - 7; + buf[5] = chain_length >> 8; /* cert chain length */ + buf[6] = chain_length & 0xff; + chain_length += 3; + buf[2] = chain_length >> 8; /* handshake length */ + buf[3] = chain_length & 0xff; + ssl->bm_index = offset; + return send_packet(ssl, PT_HANDSHAKE_PROTOCOL, NULL, offset); +} + +/** + * Create a blob of memory that we'll get rid of once the handshake is + * complete. + */ +void disposable_new(SSL *ssl) +{ + if (ssl->dc == NULL) + { + ssl->dc = (DISPOSABLE_CTX *)calloc(1, sizeof(DISPOSABLE_CTX)); + memset(ssl->dc->key_block, 0, MAX_KEYBLOCK_SIZE); + MD5_Init(&ssl->dc->md5_ctx); + SHA1_Init(&ssl->dc->sha1_ctx); + } +} + +/** + * Remove the temporary blob of memory. + */ +void disposable_free(SSL *ssl) +{ + if (ssl->dc) + { + //free(ssl->dc->key_block); + memset(ssl->dc, 0, sizeof(DISPOSABLE_CTX)); + free(ssl->dc); + ssl->dc = NULL; + } + +} + +#ifndef CONFIG_SSL_SKELETON_MODE /* no session resumption in this mode */ +/** + * Find if an existing session has the same session id. If so, use the + * master secret from this session for session resumption. + */ +SSL_SESSION *ssl_session_update(int max_sessions, SSL_SESSION *ssl_sessions[], + SSL *ssl, const uint8_t *session_id) +{ + time_t tm = time(NULL); + time_t oldest_sess_time = tm; + SSL_SESSION *oldest_sess = NULL; + int i; + + /* no sessions? Then bail */ + if (max_sessions == 0) + return NULL; + + SSL_CTX_LOCK(ssl->ssl_ctx->mutex); + if (session_id) + { + for (i = 0; i < max_sessions; i++) + { + if (ssl_sessions[i]) + { + /* kill off any expired sessions (including those in + the future) */ + if ((tm > ssl_sessions[i]->conn_time + SSL_EXPIRY_TIME) || + (tm < ssl_sessions[i]->conn_time)) + { + session_free(ssl_sessions, i); + continue; + } + + /* if the session id matches, it must still be less than + the expiry time */ + if (memcmp(ssl_sessions[i]->session_id, session_id, + SSL_SESSION_ID_SIZE) == 0) + { + ssl->session_index = i; + memcpy(ssl->dc->master_secret, + ssl_sessions[i]->master_secret, SSL_SECRET_SIZE); + SET_SSL_FLAG(SSL_SESSION_RESUME); + SSL_CTX_UNLOCK(ssl->ssl_ctx->mutex); + return ssl_sessions[i]; /* a session was found */ + } + } + } + } + + /* If we've got here, no matching session was found - so create one */ + for (i = 0; i < max_sessions; i++) + { + if (ssl_sessions[i] == NULL) + { + /* perfect, this will do */ + ssl_sessions[i] = (SSL_SESSION *)calloc(1, sizeof(SSL_SESSION)); + ssl_sessions[i]->conn_time = tm; + ssl->session_index = i; + SSL_CTX_UNLOCK(ssl->ssl_ctx->mutex); + return ssl_sessions[i]; /* return the session object */ + } + else if (ssl_sessions[i]->conn_time <= oldest_sess_time) + { + /* find the oldest session */ + oldest_sess_time = ssl_sessions[i]->conn_time; + oldest_sess = ssl_sessions[i]; + ssl->session_index = i; + } + } + + /* ok, we've used up all of our sessions. So blow the oldest session away */ + oldest_sess->conn_time = tm; + memset(oldest_sess->session_id, 0, sizeof(SSL_SESSION_ID_SIZE)); + memset(oldest_sess->master_secret, 0, sizeof(SSL_SECRET_SIZE)); + SSL_CTX_UNLOCK(ssl->ssl_ctx->mutex); + return oldest_sess; +} + +/** + * Free an existing session. + */ +static void session_free(SSL_SESSION *ssl_sessions[], int sess_index) +{ + if (ssl_sessions[sess_index]) + { + free(ssl_sessions[sess_index]); + ssl_sessions[sess_index] = NULL; + } +} + +/** + * This ssl object doesn't want this session anymore. + */ +void kill_ssl_session(SSL_SESSION **ssl_sessions, SSL *ssl) +{ + SSL_CTX_LOCK(ssl->ssl_ctx->mutex); + + if (ssl->ssl_ctx->num_sessions) + { + session_free(ssl_sessions, ssl->session_index); + ssl->session = NULL; + } + + SSL_CTX_UNLOCK(ssl->ssl_ctx->mutex); +} +#endif /* CONFIG_SSL_SKELETON_MODE */ + +/* + * Get the session id for a handshake. This will be a 32 byte sequence. + */ +EXP_FUNC const uint8_t * STDCALL ssl_get_session_id(const SSL *ssl) +{ + return ssl->session_id; +} + +/* + * Get the session id size for a handshake. + */ +EXP_FUNC uint8_t STDCALL ssl_get_session_id_size(const SSL *ssl) +{ + return ssl->sess_id_size; +} + +/* + * Return the cipher id (in the SSL form). + */ +EXP_FUNC uint8_t STDCALL ssl_get_cipher_id(const SSL *ssl) +{ + return ssl->cipher; +} + +/* + * Return the status of the handshake. + */ +EXP_FUNC int STDCALL ssl_handshake_status(const SSL *ssl) +{ + return ssl->hs_status; +} + +/* + * Retrieve various parameters about the SSL engine. + */ +EXP_FUNC int STDCALL ssl_get_config(int offset) +{ + switch (offset) + { + /* return the appropriate build mode */ + case SSL_BUILD_MODE: +#if defined(CONFIG_SSL_FULL_MODE) + return SSL_BUILD_FULL_MODE; +#elif defined(CONFIG_SSL_ENABLE_CLIENT) + return SSL_BUILD_ENABLE_CLIENT; +#elif defined(CONFIG_ENABLE_VERIFICATION) + return SSL_BUILD_ENABLE_VERIFICATION; +#elif defined(CONFIG_SSL_SERVER_ONLY ) + return SSL_BUILD_SERVER_ONLY; +#else + return SSL_BUILD_SKELETON_MODE; +#endif + + case SSL_MAX_CERT_CFG_OFFSET: + return CONFIG_SSL_MAX_CERTS; + +#ifdef CONFIG_SSL_CERT_VERIFICATION + case SSL_MAX_CA_CERT_CFG_OFFSET: + return CONFIG_X509_MAX_CA_CERTS; +#endif +#ifdef CONFIG_SSL_HAS_PEM + case SSL_HAS_PEM: + return 1; +#endif + default: + return 0; + } +} + +#ifdef CONFIG_SSL_CERT_VERIFICATION +/** + * Authenticate a received certificate. + */ +EXP_FUNC int STDCALL ssl_verify_cert(const SSL *ssl) +{ + int ret; + SSL_CTX_LOCK(ssl->ssl_ctx->mutex); + ret = x509_verify(ssl->ssl_ctx->ca_cert_ctx, ssl->x509_ctx); + SSL_CTX_UNLOCK(ssl->ssl_ctx->mutex); + + if (ret) /* modify into an SSL error type */ + { + ret = SSL_X509_ERROR(ret); + } + + return ret; +} + +/** + * Process a certificate message. + */ +int process_certificate(SSL *ssl, X509_CTX **x509_ctx) +{ + int ret = SSL_OK; + + uint8_t cert_hdr[3]; + if(basic_read2(ssl, cert_hdr, 3) != 3) + { + ret = SSL_NOT_OK; + return ret; + } + + add_packet(ssl, cert_hdr, 3); + int len = 5; + int pkt_size = ssl->bm_index; + int cert_size; + int total_cert_size = (cert_hdr[1]<<8) + cert_hdr[2]; + int is_client = IS_SET_SSL_FLAG(SSL_IS_CLIENT); + X509_CTX **chain = x509_ctx; + len += 2; + PARANOIA_CHECK(total_cert_size, 3); + + while (len < total_cert_size) + { + + if(basic_read2(ssl, cert_hdr, 3) != 3) + { + ret = SSL_NOT_OK; + return ret; + } + + add_packet(ssl, cert_hdr, 3); + + cert_size = (cert_hdr[1]<<8) + cert_hdr[2]; + if(cert_size > RT_MAX_PLAIN_LENGTH) + { + ret = SSL_NOT_OK; + return ret; + } + + len += 3; + + if(basic_read2(ssl, ssl->bm_data, cert_size) != cert_size) + { + return SSL_NOT_OK; + } + + add_packet(ssl, ssl->bm_data, cert_size); + + if (x509_new(ssl->bm_data, NULL, chain)) + { + ret = SSL_ERROR_BAD_CERTIFICATE; + goto error; + } + + chain = &((*chain)->next); + len += cert_size; + } + PARANOIA_CHECK(pkt_size, len); + + /* if we are client we can do the verify now or later */ + if (is_client && !IS_SET_SSL_FLAG(SSL_SERVER_VERIFY_LATER)) + { + ret = ssl_verify_cert(ssl); + } + + ssl->next_state = is_client ? HS_SERVER_HELLO_DONE : HS_CLIENT_KEY_XCHG; + ssl->dc->bm_proc_index += len; +error: + + return ret; +} + +#endif /* CONFIG_SSL_CERT_VERIFICATION */ + +/** + * Debugging routine to display SSL handshaking stuff. + */ +#ifdef CONFIG_SSL_FULL_MODE +/** + * Debugging routine to display SSL states. + */ +void DISPLAY_STATE(SSL *ssl, int is_send, uint8_t state, int not_ok) +{ + const char *str; + + if (!IS_SET_SSL_FLAG(SSL_DISPLAY_STATES)) + return; + + printf(not_ok ? "Error - invalid State:\t" : "State:\t"); + printf(is_send ? "sending " : "receiving "); + + switch (state) + { + case HS_HELLO_REQUEST: + str = "Hello Request (0)"; + break; + + case HS_CLIENT_HELLO: + str = "Client Hello (1)"; + break; + + case HS_SERVER_HELLO: + str = "Server Hello (2)"; + break; + + case HS_CERTIFICATE: + str = "Certificate (11)"; + break; + + case HS_SERVER_KEY_XCHG: + str = "Certificate Request (12)"; + break; + + case HS_CERT_REQ: + str = "Certificate Request (13)"; + break; + + case HS_SERVER_HELLO_DONE: + str = "Server Hello Done (14)"; + break; + + case HS_CERT_VERIFY: + str = "Certificate Verify (15)"; + break; + + case HS_CLIENT_KEY_XCHG: + str = "Client Key Exchange (16)"; + break; + + case HS_FINISHED: + str = "Finished (16)"; + break; + + default: + str = "Error (Unknown)"; + + break; + } + + printf("%s\r\n", str); + TTY_FLUSH(); +} + +/** + * Debugging routine to display RSA objects + */ +void DISPLAY_RSA(SSL *ssl, const RSA_CTX *rsa_ctx) +{ + if (!IS_SET_SSL_FLAG(SSL_DISPLAY_RSA)) + return; + + RSA_print(rsa_ctx); + TTY_FLUSH(); +} + +/** + * Debugging routine to display SSL handshaking bytes. + */ +void DISPLAY_BYTES(SSL *ssl, const char *format, + const uint8_t *data, int size, ...) +{ + va_list(ap); + + if (!IS_SET_SSL_FLAG(SSL_DISPLAY_BYTES)) + return; + + va_start(ap, size); + print_blob(format, data, size, va_arg(ap, char *)); + va_end(ap); + TTY_FLUSH(); +} + +/** + * Debugging routine to display SSL handshaking errors. + */ +EXP_FUNC void STDCALL ssl_display_error(int error_code) +{ + if (error_code == SSL_OK) + return; + + printf("Error: "); + + /* X509 error? */ + if (error_code < SSL_X509_OFFSET) + { + printf("%s\r\n", x509_display_error(error_code - SSL_X509_OFFSET)); + return; + } + + /* SSL alert error code */ + if (error_code > SSL_ERROR_CONN_LOST) + { + printf("SSL error %d\n", -error_code); + return; + } + + switch (error_code) + { + case SSL_ERROR_DEAD: + printf("connection dead"); + break; + + case SSL_ERROR_INVALID_HANDSHAKE: + printf("invalid handshake"); + break; + + case SSL_ERROR_INVALID_PROT_MSG: + printf("invalid protocol message"); + break; + + case SSL_ERROR_INVALID_HMAC: + printf("invalid mac"); + break; + + case SSL_ERROR_INVALID_VERSION: + printf("invalid version"); + break; + + case SSL_ERROR_INVALID_SESSION: + printf("invalid session"); + break; + + case SSL_ERROR_NO_CIPHER: + printf("no cipher"); + break; + + case SSL_ERROR_CONN_LOST: + printf("connection lost"); + break; + + case SSL_ERROR_BAD_CERTIFICATE: + printf("bad certificate"); + break; + + case SSL_ERROR_INVALID_KEY: + printf("invalid key"); + break; + + case SSL_ERROR_FINISHED_INVALID: + printf("finished invalid"); + break; + + case SSL_ERROR_NO_CERT_DEFINED: + printf("no certificate defined"); + break; + + case SSL_ERROR_NO_CLIENT_RENOG: + printf("client renegotiation not supported"); + break; + + case SSL_ERROR_NOT_SUPPORTED: + printf("Option not supported"); + break; + + default: + printf("undefined as yet - %d", error_code); + break; + } + + printf("\r\n"); + TTY_FLUSH(); +} + +/** + * Debugging routine to display alerts. + */ +void DISPLAY_ALERT(SSL *ssl, int alert) +{ + if (!IS_SET_SSL_FLAG(SSL_DISPLAY_STATES)) + return; + + printf("Alert: "); + + switch (alert) + { + case SSL_ALERT_CLOSE_NOTIFY: + printf("close notify"); + break; + + case SSL_ALERT_INVALID_VERSION: + printf("invalid version"); + break; + + case SSL_ALERT_BAD_CERTIFICATE: + printf("bad certificate"); + break; + + case SSL_ALERT_UNEXPECTED_MESSAGE: + printf("unexpected message"); + break; + + case SSL_ALERT_BAD_RECORD_MAC: + printf("bad record mac"); + break; + + case SSL_ALERT_HANDSHAKE_FAILURE: + printf("handshake failure"); + break; + + case SSL_ALERT_ILLEGAL_PARAMETER: + printf("illegal parameter"); + break; + + case SSL_ALERT_DECODE_ERROR: + printf("decode error"); + break; + + case SSL_ALERT_DECRYPT_ERROR: + printf("decrypt error"); + break; + + case SSL_ALERT_NO_RENEGOTIATION: + printf("no renegotiation"); + break; + + default: + printf("alert - (unknown %d)", alert); + break; + } + + printf("\r\n"); + TTY_FLUSH(); +} + +#endif /* CONFIG_SSL_FULL_MODE */ + +/** + * Return the version of this library. + */ +EXP_FUNC const char * STDCALL ssl_version() +{ + static const char * axtls_version = AXTLS_VERSION; + return axtls_version; +} + +/** + * Enable the various language bindings to work regardless of the + * configuration - they just return an error statement and a bad return code. + */ +#if !defined(CONFIG_SSL_FULL_MODE) +EXP_FUNC void STDCALL ssl_display_error(int error_code) {} +#endif + +#ifdef CONFIG_BINDINGS +#if !defined(CONFIG_SSL_ENABLE_CLIENT) +EXP_FUNC SSL * STDCALL ssl_client_new(SSL_CTX *ssl_ctx, int client_fd, const + uint8_t *session_id, uint8_t sess_id_size) +{ + printf(unsupported_str); + return NULL; +} +#endif + +#if !defined(CONFIG_SSL_CERT_VERIFICATION) +EXP_FUNC int STDCALL ssl_verify_cert(const SSL *ssl) +{ + printf(unsupported_str); + return -1; +} + + +EXP_FUNC const char * STDCALL ssl_get_cert_dn(const SSL *ssl, int component) +{ + printf(unsupported_str); + return NULL; +} + +EXP_FUNC const char * STDCALL ssl_get_cert_subject_alt_dnsname(const SSL *ssl, int index) +{ + printf(unsupported_str); + return NULL; +} + +#endif /* CONFIG_SSL_CERT_VERIFICATION */ + +#endif /* CONFIG_BINDINGS */ + diff --git a/features/unsupported/net/https/axTLS/ssl/tls1.h b/features/unsupported/net/https/axTLS/ssl/tls1.h new file mode 100644 index 00000000000..4a4f453fe2d --- /dev/null +++ b/features/unsupported/net/https/axTLS/ssl/tls1.h @@ -0,0 +1,304 @@ +/* + * Copyright (c) 2007, Cameron Rich + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * * Neither the name of the axTLS project nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @file tls1.h + * + * @brief The definitions for the TLS library. + */ +#ifndef HEADER_SSL_LIB_H +#define HEADER_SSL_LIB_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include "version.h" +#include "os_int.h" +#include "crypto.h" +#include "crypto_misc.h" + +#include "config.h" + +#define SSL_PROTOCOL_MIN_VERSION 0x31 /* TLS v1.0 */ +#define SSL_PROTOCOL_MINOR_VERSION 0x02 /* TLS v1.1 */ +#define SSL_PROTOCOL_VERSION_MAX 0x32 /* TLS v1.1 */ +#define SSL_PROTOCOL_VERSION1_1 0x32 /* TLS v1.1 */ +#define SSL_RANDOM_SIZE 32 +#define SSL_SECRET_SIZE 48 +#define SSL_FINISHED_HASH_SIZE 12 +#define SSL_RECORD_SIZE 5 +#define SSL_SERVER_READ 0 +#define SSL_SERVER_WRITE 1 +#define SSL_CLIENT_READ 2 +#define SSL_CLIENT_WRITE 3 +#define SSL_HS_HDR_SIZE 4 + +/* the flags we use while establishing a connection */ +#define SSL_NEED_RECORD 0x0001 +#define SSL_TX_ENCRYPTED 0x0002 +#define SSL_RX_ENCRYPTED 0x0004 +#define SSL_SESSION_RESUME 0x0008 +#define SSL_IS_CLIENT 0x0010 +#define SSL_HAS_CERT_REQ 0x0020 +#define SSL_SENT_CLOSE_NOTIFY 0x0040 + +/* some macros to muck around with flag bits */ +#define SET_SSL_FLAG(A) (ssl->flag |= A) +#define CLR_SSL_FLAG(A) (ssl->flag &= ~A) +#define IS_SET_SSL_FLAG(A) (ssl->flag & A) + +#define MAX_KEY_BYTE_SIZE 512 /* for a 4096 bit key */ +#define RT_MAX_PLAIN_LENGTH 2048//16384 +#define RT_EXTRA 512//1024 +#define BM_RECORD_OFFSET 5 +#define BM_ALL_DATA_SIZE (RT_MAX_PLAIN_LENGTH+RT_EXTRA-BM_RECORD_OFFSET) + +#ifdef CONFIG_SSL_SKELETON_MODE +#define NUM_PROTOCOLS 1 +#else +#define NUM_PROTOCOLS 4 +#endif + +#define PARANOIA_CHECK(A, B) if (A < B) { \ + ret = SSL_ERROR_INVALID_HANDSHAKE; goto error; } + +/* protocol types */ +enum +{ + PT_CHANGE_CIPHER_SPEC = 20, + PT_ALERT_PROTOCOL, + PT_HANDSHAKE_PROTOCOL, + PT_APP_PROTOCOL_DATA +}; + +/* handshaking types */ +enum +{ + HS_HELLO_REQUEST, + HS_CLIENT_HELLO, + HS_SERVER_HELLO, + HS_CERTIFICATE = 11, + HS_SERVER_KEY_XCHG, + HS_CERT_REQ, + HS_SERVER_HELLO_DONE, + HS_CERT_VERIFY, + HS_CLIENT_KEY_XCHG, + HS_FINISHED = 20 +}; + +typedef struct +{ + uint8_t cipher; + uint8_t key_size; + uint8_t iv_size; + uint8_t key_block_size; + uint8_t padding_size; + uint8_t digest_size; + hmac_func hmac; + crypt_func encrypt; + crypt_func decrypt; +} cipher_info_t; + +struct _SSLObjLoader +{ + uint8_t *buf; + int len; +}; + +typedef struct _SSLObjLoader SSLObjLoader; + +typedef struct +{ + time_t conn_time; + uint8_t session_id[SSL_SESSION_ID_SIZE]; + uint8_t master_secret[SSL_SECRET_SIZE]; +} SSL_SESSION; + +typedef struct +{ + uint8_t *buf; + int size; +} SSL_CERT; + +typedef struct +{ + MD5_CTX md5_ctx; + SHA1_CTX sha1_ctx; + uint8_t final_finish_mac[SSL_FINISHED_HASH_SIZE]; + uint8_t key_block[MAX_KEYBLOCK_SIZE]; + uint8_t master_secret[SSL_SECRET_SIZE]; + uint8_t client_random[SSL_RANDOM_SIZE]; /* client's random sequence */ + uint8_t server_random[SSL_RANDOM_SIZE]; /* server's random sequence */ + uint16_t bm_proc_index; +} DISPOSABLE_CTX; + +struct _SSL +{ + uint32_t flag; + uint16_t need_bytes; + uint16_t got_bytes; + uint8_t record_type; + uint8_t cipher; + uint8_t sess_id_size; + uint8_t version; + uint8_t client_version; + int16_t next_state; + int16_t hs_status; + DISPOSABLE_CTX *dc; /* temporary data which we'll get rid of soon */ + int client_fd; + void *connection; + const cipher_info_t *cipher_info; + void *encrypt_ctx; + void *decrypt_ctx; + uint8_t bm_all_data[RT_MAX_PLAIN_LENGTH]; + uint8_t *bm_data; + uint16_t bm_index; + uint16_t bm_read_index; + struct _SSL *next; /* doubly linked list */ + struct _SSL *prev; + struct _SSL_CTX *ssl_ctx; /* back reference to a clnt/svr ctx */ +#ifndef CONFIG_SSL_SKELETON_MODE + uint16_t session_index; + SSL_SESSION *session; +#endif +#ifdef CONFIG_SSL_CERT_VERIFICATION + X509_CTX *x509_ctx; +#endif + + uint8_t session_id[SSL_SESSION_ID_SIZE]; + uint8_t client_mac[SHA1_SIZE]; /* for HMAC verification */ + uint8_t server_mac[SHA1_SIZE]; /* for HMAC verification */ + uint8_t read_sequence[8]; /* 64 bit sequence number */ + uint8_t write_sequence[8]; /* 64 bit sequence number */ + uint8_t hmac_header[SSL_RECORD_SIZE]; /* rx hmac */ +}; + +typedef struct _SSL SSL; + +struct _SSL_CTX +{ + uint32_t options; + uint8_t chain_length; + RSA_CTX *rsa_ctx; +#ifdef CONFIG_SSL_CERT_VERIFICATION + CA_CERT_CTX *ca_cert_ctx; +#endif + SSL *head; + SSL *tail; + SSL_CERT certs[CONFIG_SSL_MAX_CERTS]; +#ifndef CONFIG_SSL_SKELETON_MODE + uint16_t num_sessions; + SSL_SESSION **ssl_sessions; +#endif +#ifdef CONFIG_SSL_CTX_MUTEXING + SSL_CTX_MUTEX_TYPE mutex; +#endif +#ifdef CONFIG_OPENSSL_COMPATIBLE + void *bonus_attr; +#endif +}; + +typedef struct _SSL_CTX SSL_CTX; + +/* backwards compatibility */ +typedef struct _SSL_CTX SSLCTX; + +extern const uint8_t ssl_prot_prefs[NUM_PROTOCOLS]; + +SSL *ssl_new(SSL *ssl, int client_fd); +void disposable_new(SSL *ssl); +void disposable_free(SSL *ssl); +int send_packet(SSL *ssl, uint8_t protocol, + const uint8_t *in, int length); +int do_svr_handshake(SSL *ssl, int handshake_type, uint8_t *buf, int hs_len); +int do_clnt_handshake(SSL *ssl, int handshake_type, uint8_t *buf, int hs_len); +int process_finished(SSL *ssl, uint8_t *buf, int hs_len); +int process_sslv23_client_hello(SSL *ssl); +int send_alert(SSL *ssl, int error_code); +int send_finished(SSL *ssl); +int send_certificate(SSL *ssl); +int basic_read2(SSL *ssl, uint8_t *data, uint32_t length); +int read_record(SSL *ssl); +int basic_decrypt(SSL *ssl, uint8_t *buf, int len); +int process_data(SSL* ssl, uint8_t *in_data, int len); +int ssl_read(SSL *ssl, uint8_t *in_data, int len); +int send_change_cipher_spec(SSL *ssl); +void finished_digest(SSL *ssl, const char *label, uint8_t *digest); +void generate_master_secret(SSL *ssl, const uint8_t *premaster_secret); +void add_packet(SSL *ssl, const uint8_t *pkt, int len); +int add_cert(SSL_CTX *ssl_ctx, const uint8_t *buf, int len); +int add_private_key(SSL_CTX *ssl_ctx, SSLObjLoader *ssl_obj); +void ssl_obj_free(SSLObjLoader *ssl_obj); +int pkcs8_decode(SSL_CTX *ssl_ctx, SSLObjLoader *ssl_obj, const char *password); +int pkcs12_decode(SSL_CTX *ssl_ctx, SSLObjLoader *ssl_obj, const char *password); +int load_key_certs(SSL_CTX *ssl_ctx); +#ifdef CONFIG_SSL_CERT_VERIFICATION +int add_cert_auth(SSL_CTX *ssl_ctx, const uint8_t *buf, int len); +void remove_ca_certs(CA_CERT_CTX *ca_cert_ctx); +#endif +#ifdef CONFIG_SSL_ENABLE_CLIENT +int do_client_connect(SSL *ssl); +#endif + +#ifdef CONFIG_SSL_FULL_MODE +void DISPLAY_STATE(SSL *ssl, int is_send, uint8_t state, int not_ok); +void DISPLAY_BYTES(SSL *ssl, const char *format, + const uint8_t *data, int size, ...); +void DISPLAY_CERT(SSL *ssl, const X509_CTX *x509_ctx); +void DISPLAY_RSA(SSL *ssl, const RSA_CTX *rsa_ctx); +void DISPLAY_ALERT(SSL *ssl, int alert); +#else +#define DISPLAY_STATE(A,B,C,D) +#define DISPLAY_CERT(A,B) +#define DISPLAY_RSA(A,B) +#define DISPLAY_ALERT(A, B) +#ifdef WIN32 +void DISPLAY_BYTES(SSL *ssl, const char *format,/* win32 has no variadic macros */ + const uint8_t *data, int size, ...); +#else +#define DISPLAY_BYTES(A,B,C,D,...) +#endif +#endif + +#ifdef CONFIG_SSL_CERT_VERIFICATION +int process_certificate(SSL *ssl, X509_CTX **x509_ctx); +#endif + +SSL_SESSION *ssl_session_update(int max_sessions, + SSL_SESSION *ssl_sessions[], SSL *ssl, + const uint8_t *session_id); +void kill_ssl_session(SSL_SESSION **ssl_sessions, SSL *ssl); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/features/unsupported/net/https/axTLS/ssl/tls1_clnt.c b/features/unsupported/net/https/axTLS/ssl/tls1_clnt.c new file mode 100644 index 00000000000..5595716556e --- /dev/null +++ b/features/unsupported/net/https/axTLS/ssl/tls1_clnt.c @@ -0,0 +1,414 @@ +/* + * Copyright (c) 2007, Cameron Rich + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * * Neither the name of the axTLS project nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include +#include +#include "os_port.h" +#include "ssl.h" + +#ifdef CONFIG_SSL_ENABLE_CLIENT /* all commented out if no client */ + +static int send_client_hello(SSL *ssl); +static int process_server_hello(SSL *ssl); +static int process_server_hello_done(SSL *ssl); +static int send_client_key_xchg(SSL *ssl); +static int process_cert_req(SSL *ssl); +static int send_cert_verify(SSL *ssl); + +/* + * Establish a new SSL connection to an SSL server. + */ +EXP_FUNC SSL * STDCALL ssl_client_new(SSL *ssl, int client_fd, const + uint8_t *session_id, uint8_t sess_id_size) +{ + SSL_CTX *ssl_ctx = ssl->ssl_ctx; + ssl_new(ssl, client_fd); + ssl->version = SSL_PROTOCOL_VERSION_MAX; /* try top version first */ + + if (session_id && ssl_ctx->num_sessions) + { + if (sess_id_size > SSL_SESSION_ID_SIZE) /* validity check */ + { + ssl_free(ssl); + return NULL; + } + + memcpy(ssl->session_id, session_id, sess_id_size); + ssl->sess_id_size = sess_id_size; + SET_SSL_FLAG(SSL_SESSION_RESUME); /* just flag for later */ + } + + SET_SSL_FLAG(SSL_IS_CLIENT); + do_client_connect(ssl); + return ssl; +} + +/* + * Process the handshake record. + */ +int do_clnt_handshake(SSL *ssl, int handshake_type, uint8_t *buf, int hs_len) +{ + int ret; + + /* To get here the state must be valid */ + switch (handshake_type) + { + case HS_SERVER_HELLO: + ret = process_server_hello(ssl); + break; + + case HS_CERTIFICATE: + ret = process_certificate(ssl, &ssl->x509_ctx); + break; + + case HS_SERVER_HELLO_DONE: + if ((ret = process_server_hello_done(ssl)) == SSL_OK) + { + if (IS_SET_SSL_FLAG(SSL_HAS_CERT_REQ)) + { + if ((ret = send_certificate(ssl)) == SSL_OK && + (ret = send_client_key_xchg(ssl)) == SSL_OK) + { + send_cert_verify(ssl); + } + } + else + { + ret = send_client_key_xchg(ssl); + } + + if (ret == SSL_OK && + (ret = send_change_cipher_spec(ssl)) == SSL_OK) + { + ret = send_finished(ssl); + } + } + break; + + case HS_CERT_REQ: + ret = process_cert_req(ssl); + break; + + case HS_FINISHED: + ret = process_finished(ssl, buf, hs_len); + disposable_free(ssl); /* free up some memory */ + /* note: client renegotiation is not allowed after this */ + break; + + case HS_HELLO_REQUEST: + disposable_new(ssl); + ret = do_client_connect(ssl); + break; + + default: + ret = SSL_ERROR_INVALID_HANDSHAKE; + break; + } + + return ret; +} + +/* + * Do the handshaking from the beginning. + */ +int do_client_connect(SSL *ssl) +{ + int ret = SSL_OK; + + send_client_hello(ssl); /* send the client hello */ + ssl->bm_read_index = 0; + ssl->next_state = HS_SERVER_HELLO; + ssl->hs_status = SSL_NOT_OK; /* not connected */ + + /* sit in a loop until it all looks good */ + if (!IS_SET_SSL_FLAG(SSL_CONNECT_IN_PARTS)) + { + while (ssl->hs_status != SSL_OK) + { + ret = read_record(ssl); + if (ret < SSL_OK) + break; + ret = process_data(ssl, NULL, 0); + if (ret < SSL_OK) + break; + } + ssl->hs_status = ret; /* connected? */ + } + return ret; +} + +static int compute_size_send_client_hello(SSL *ssl) +{ + int size = 6 + SSL_RANDOM_SIZE; + size++; + if (IS_SET_SSL_FLAG(SSL_SESSION_RESUME)) + { + + size += ssl->sess_id_size; + } + size += 2; + int i; + for (i = 0; i < NUM_PROTOCOLS; i++) + size += 2; + size += 2; + return size+BM_RECORD_OFFSET; +} + +/* + * Send the initial client hello. + */ +static int send_client_hello(SSL *ssl) +{ + uint8_t *buf = ssl->bm_data; + time_t tm = time(NULL); + uint8_t *tm_ptr = &buf[6]; /* time will go here */ + int i, offset; + + buf[0] = HS_CLIENT_HELLO; + buf[1] = 0; + buf[2] = 0; + /* byte 3 is calculated later */ + buf[4] = 0x03; + buf[5] = ssl->version & 0x0f; + + /* client random value - spec says that 1st 4 bytes are big endian time */ + *tm_ptr++ = (uint8_t)(((long)tm & 0xff000000) >> 24); + *tm_ptr++ = (uint8_t)(((long)tm & 0x00ff0000) >> 16); + *tm_ptr++ = (uint8_t)(((long)tm & 0x0000ff00) >> 8); + *tm_ptr++ = (uint8_t)(((long)tm & 0x000000ff)); + get_random(SSL_RANDOM_SIZE-4, &buf[10]); + memcpy(ssl->dc->client_random, &buf[6], SSL_RANDOM_SIZE); + offset = 6 + SSL_RANDOM_SIZE; + + /* give session resumption a go */ + if (IS_SET_SSL_FLAG(SSL_SESSION_RESUME)) /* set initially by user */ + { + buf[offset++] = ssl->sess_id_size; + memcpy(&buf[offset], ssl->session_id, ssl->sess_id_size); + offset += ssl->sess_id_size; + CLR_SSL_FLAG(SSL_SESSION_RESUME); /* clear so we can set later */ + } + else + { + /* no session id - because no session resumption just yet */ + buf[offset++] = 0; + } + + buf[offset++] = 0; /* number of ciphers */ + buf[offset++] = NUM_PROTOCOLS*2;/* number of ciphers */ + + /* put all our supported protocols in our request */ + for (i = 0; i < NUM_PROTOCOLS; i++) + { + buf[offset++] = 0; /* cipher we are using */ + buf[offset++] = ssl_prot_prefs[i]; + } + + buf[offset++] = 1; /* no compression */ + buf[offset++] = 0; + buf[3] = offset - 4; /* handshake size */ + + return send_packet(ssl, PT_HANDSHAKE_PROTOCOL, NULL, offset); +} + +/* + * Process the server hello. + */ +static int process_server_hello(SSL *ssl) +{ + uint8_t *buf = ssl->bm_data; + int pkt_size = ssl->bm_index; + int num_sessions = ssl->ssl_ctx->num_sessions; + uint8_t sess_id_size; + int offset, ret = SSL_OK; + + /* check that we are talking to a TLSv1 server */ + uint8_t version = (buf[0] << 4) + buf[1]; + if (version > SSL_PROTOCOL_VERSION_MAX) + { + version = SSL_PROTOCOL_VERSION_MAX; + } + else if (ssl->version < SSL_PROTOCOL_MIN_VERSION) + { + ret = SSL_ERROR_INVALID_VERSION; + ssl_display_error(ret); + goto error; + } + + ssl->version = version; + + /* get the server random value */ + memcpy(ssl->dc->server_random, &buf[2], SSL_RANDOM_SIZE); + offset = 2 + SSL_RANDOM_SIZE; /* skip of session id size */ + sess_id_size = buf[offset++]; + + if (sess_id_size > SSL_SESSION_ID_SIZE) + { + ret = SSL_ERROR_INVALID_SESSION; + goto error; + } + + if (num_sessions) + { + ssl->session = ssl_session_update(num_sessions, + ssl->ssl_ctx->ssl_sessions, ssl, &buf[offset]); + memcpy(ssl->session->session_id, &buf[offset], sess_id_size); + + /* pad the rest with 0's */ + if (sess_id_size < SSL_SESSION_ID_SIZE) + { + memset(&ssl->session->session_id[sess_id_size], 0, + SSL_SESSION_ID_SIZE-sess_id_size); + } + } + + memcpy(ssl->session_id, &buf[offset], sess_id_size); + ssl->sess_id_size = sess_id_size; + offset += sess_id_size; + + /* get the real cipher we are using */ + ssl->cipher = buf[++offset]; + ssl->next_state = IS_SET_SSL_FLAG(SSL_SESSION_RESUME) ? + HS_FINISHED : HS_CERTIFICATE; + + offset++; // skip the compr + PARANOIA_CHECK(pkt_size, offset); + ssl->dc->bm_proc_index = offset+1; + +error: + return ret; +} + +/** + * Process the server hello done message. + */ +static int process_server_hello_done(SSL *ssl) +{ + ssl->next_state = HS_FINISHED; + return SSL_OK; +} + +/* + * Send a client key exchange message. + */ +static int send_client_key_xchg(SSL *ssl) +{ + uint8_t *buf = ssl->bm_data; + uint8_t premaster_secret[SSL_SECRET_SIZE]; + int enc_secret_size = -1; + + buf[0] = HS_CLIENT_KEY_XCHG; + buf[1] = 0; + + premaster_secret[0] = 0x03; /* encode the version number */ + premaster_secret[1] = SSL_PROTOCOL_MINOR_VERSION; /* must be TLS 1.1 */ + get_random(SSL_SECRET_SIZE-2, &premaster_secret[2]); + DISPLAY_RSA(ssl, ssl->x509_ctx->rsa_ctx); + + /* rsa_ctx->bi_ctx is not thread-safe */ + SSL_CTX_LOCK(ssl->ssl_ctx->mutex); + enc_secret_size = RSA_encrypt(ssl->x509_ctx->rsa_ctx, premaster_secret, + SSL_SECRET_SIZE, &buf[6], 0); + SSL_CTX_UNLOCK(ssl->ssl_ctx->mutex); + + buf[2] = (enc_secret_size + 2) >> 8; + buf[3] = (enc_secret_size + 2) & 0xff; + buf[4] = enc_secret_size >> 8; + buf[5] = enc_secret_size & 0xff; + + generate_master_secret(ssl, premaster_secret); + + return send_packet(ssl, PT_HANDSHAKE_PROTOCOL, NULL, enc_secret_size+6); +} + +/* + * Process the certificate request. + */ +static int process_cert_req(SSL *ssl) +{ + uint8_t *buf = &ssl->bm_data[ssl->dc->bm_proc_index]; + int ret = SSL_OK; + int offset = (buf[2] << 4) + buf[3]; + int pkt_size = ssl->bm_index; + + /* don't do any processing - we will send back an RSA certificate anyway */ + ssl->next_state = HS_SERVER_HELLO_DONE; + SET_SSL_FLAG(SSL_HAS_CERT_REQ); + ssl->dc->bm_proc_index += offset; + PARANOIA_CHECK(pkt_size, offset); +error: + return ret; +} + +/* + * Send a certificate verify message. + */ +static int send_cert_verify(SSL *ssl) +{ + uint8_t *buf = ssl->bm_data; + uint8_t dgst[MD5_SIZE+SHA1_SIZE]; + RSA_CTX *rsa_ctx = ssl->ssl_ctx->rsa_ctx; + int n = 0, ret; + + DISPLAY_RSA(ssl, rsa_ctx); + + buf[0] = HS_CERT_VERIFY; + buf[1] = 0; + + finished_digest(ssl, NULL, dgst); /* calculate the digest */ + + /* rsa_ctx->bi_ctx is not thread-safe */ + if (rsa_ctx) + { + SSL_CTX_LOCK(ssl->ssl_ctx->mutex); + n = RSA_encrypt(rsa_ctx, dgst, sizeof(dgst), &buf[6], 1); + SSL_CTX_UNLOCK(ssl->ssl_ctx->mutex); + + if (n == 0) + { + ret = SSL_ERROR_INVALID_KEY; + goto error; + } + } + + buf[4] = n >> 8; /* add the RSA size (not officially documented) */ + buf[5] = n & 0xff; + n += 2; + buf[2] = n >> 8; + buf[3] = n & 0xff; + ret = send_packet(ssl, PT_HANDSHAKE_PROTOCOL, NULL, n+4); + +error: + return ret; +} + +#endif /* CONFIG_SSL_ENABLE_CLIENT */ diff --git a/features/unsupported/net/https/axTLS/ssl/tls1_svr.c b/features/unsupported/net/https/axTLS/ssl/tls1_svr.c new file mode 100644 index 00000000000..51c9d76e8dd --- /dev/null +++ b/features/unsupported/net/https/axTLS/ssl/tls1_svr.c @@ -0,0 +1,478 @@ +/* + * Copyright (c) 2007, Cameron Rich + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * * Neither the name of the axTLS project nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include +#include "os_port.h" +#include "ssl.h" + +static const uint8_t g_hello_done[] = { HS_SERVER_HELLO_DONE, 0, 0, 0 }; + +static int process_client_hello(SSL *ssl); +static int send_server_hello_sequence(SSL *ssl); +static int send_server_hello(SSL *ssl); +static int send_server_hello_done(SSL *ssl); +static int process_client_key_xchg(SSL *ssl); +#ifdef CONFIG_SSL_CERT_VERIFICATION +static int send_certificate_request(SSL *ssl); +static int process_cert_verify(SSL *ssl); +#endif + +/* + * Establish a new SSL connection to an SSL client. + */ +EXP_FUNC SSL * STDCALL ssl_server_new(SSL_CTX *ssl_ctx, int client_fd) +{ + SSL *ssl; + + ssl = ssl_new(ssl_ctx, client_fd); + ssl->next_state = HS_CLIENT_HELLO; + +#ifdef CONFIG_SSL_FULL_MODE + if (ssl_ctx->chain_length == 0) + printf("Warning - no server certificate defined\n"); TTY_FLUSH(); +#endif + + return ssl; +} + +/* + * Process the handshake record. + */ +int do_svr_handshake(SSL *ssl, int handshake_type, uint8_t *buf, int hs_len) +{ + int ret = SSL_OK; + ssl->hs_status = SSL_NOT_OK; /* not connected */ + + /* To get here the state must be valid */ + switch (handshake_type) + { + case HS_CLIENT_HELLO: + if ((ret = process_client_hello(ssl)) == SSL_OK) + ret = send_server_hello_sequence(ssl); + break; + +#ifdef CONFIG_SSL_CERT_VERIFICATION + case HS_CERTIFICATE:/* the client sends its cert */ + ret = process_certificate(ssl, &ssl->x509_ctx); + + if (ret == SSL_OK) /* verify the cert */ + { + int cert_res; + cert_res = x509_verify( + ssl->ssl_ctx->ca_cert_ctx, ssl->x509_ctx); + ret = (cert_res == 0) ? SSL_OK : SSL_X509_ERROR(cert_res); + } + break; + + case HS_CERT_VERIFY: + ret = process_cert_verify(ssl); + add_packet(ssl, buf, hs_len); /* needs to be done after */ + break; +#endif + case HS_CLIENT_KEY_XCHG: + ret = process_client_key_xchg(ssl); + break; + + case HS_FINISHED: + ret = process_finished(ssl, buf, hs_len); + disposable_free(ssl); /* free up some memory */ + break; + } + + return ret; +} + +/* + * Process a client hello message. + */ +static int process_client_hello(SSL *ssl) +{ + uint8_t *buf = ssl->bm_data; + uint8_t *record_buf = ssl->hmac_header; + int pkt_size = ssl->bm_index; + int i, j, cs_len, id_len, offset = 6 + SSL_RANDOM_SIZE; + int ret = SSL_OK; + + uint8_t version = (buf[4] << 4) + buf[5]; + ssl->version = ssl->client_version = version; + + if (version > SSL_PROTOCOL_VERSION_MAX) + { + /* use client's version instead */ + ssl->version = SSL_PROTOCOL_VERSION_MAX; + } + else if (version < SSL_PROTOCOL_MIN_VERSION) /* old version supported? */ + { + ret = SSL_ERROR_INVALID_VERSION; + ssl_display_error(ret); + goto error; + } + + memcpy(ssl->dc->client_random, &buf[6], SSL_RANDOM_SIZE); + + /* process the session id */ + id_len = buf[offset++]; + if (id_len > SSL_SESSION_ID_SIZE) + { + return SSL_ERROR_INVALID_SESSION; + } + +#ifndef CONFIG_SSL_SKELETON_MODE + ssl->session = ssl_session_update(ssl->ssl_ctx->num_sessions, + ssl->ssl_ctx->ssl_sessions, ssl, id_len ? &buf[offset] : NULL); +#endif + + offset += id_len; + cs_len = (buf[offset]<<8) + buf[offset+1]; + offset += 3; /* add 1 due to all cipher suites being 8 bit */ + + PARANOIA_CHECK(pkt_size, offset); + + /* work out what cipher suite we are going to use - client defines + the preference */ + for (i = 0; i < cs_len; i += 2) + { + for (j = 0; j < NUM_PROTOCOLS; j++) + { + if (ssl_prot_prefs[j] == buf[offset+i]) /* got a match? */ + { + ssl->cipher = ssl_prot_prefs[j]; + goto do_state; + } + } + } + + /* ouch! protocol is not supported */ + ret = SSL_ERROR_NO_CIPHER; + +do_state: +error: + return ret; +} + +#ifdef CONFIG_SSL_ENABLE_V23_HANDSHAKE +/* + * Some browsers use a hybrid SSLv2 "client hello" + */ +int process_sslv23_client_hello(SSL *ssl) +{ + uint8_t *buf = ssl->bm_data; + int bytes_needed = ((buf[0] & 0x7f) << 8) + buf[1]; + int ret = SSL_OK; + + /* we have already read 3 extra bytes so far */ + int read_len = SOCKET_READ(ssl->client_fd, buf, bytes_needed-3); + int cs_len = buf[1]; + int id_len = buf[3]; + int ch_len = buf[5]; + int i, j, offset = 8; /* start at first cipher */ + int random_offset = 0; + + DISPLAY_BYTES(ssl, "received %d bytes", buf, read_len, read_len); + + add_packet(ssl, buf, read_len); + + /* connection has gone, so die */ + if (bytes_needed < 0) + { + return SSL_ERROR_CONN_LOST; + } + + /* now work out what cipher suite we are going to use */ + for (j = 0; j < NUM_PROTOCOLS; j++) + { + for (i = 0; i < cs_len; i += 3) + { + if (ssl_prot_prefs[j] == buf[offset+i]) + { + ssl->cipher = ssl_prot_prefs[j]; + goto server_hello; + } + } + } + + /* ouch! protocol is not supported */ + ret = SSL_ERROR_NO_CIPHER; + goto error; + +server_hello: + /* get the session id */ + offset += cs_len - 2; /* we've gone 2 bytes past the end */ +#ifndef CONFIG_SSL_SKELETON_MODE + ssl->session = ssl_session_update(ssl->ssl_ctx->num_sessions, + ssl->ssl_ctx->ssl_sessions, ssl, id_len ? &buf[offset] : NULL); +#endif + + /* get the client random data */ + offset += id_len; + + /* random can be anywhere between 16 and 32 bytes long - so it is padded + * with 0's to the left */ + if (ch_len == 0x10) + { + random_offset += 0x10; + } + + memcpy(&ssl->dc->client_random[random_offset], &buf[offset], ch_len); + ret = send_server_hello_sequence(ssl); + +error: + return ret; +} +#endif + +/* + * Send the entire server hello sequence + */ +static int send_server_hello_sequence(SSL *ssl) +{ + int ret; + + if ((ret = send_server_hello(ssl)) == SSL_OK) + { +#ifndef CONFIG_SSL_SKELETON_MODE + /* resume handshake? */ + if (IS_SET_SSL_FLAG(SSL_SESSION_RESUME)) + { + if ((ret = send_change_cipher_spec(ssl)) == SSL_OK) + { + ret = send_finished(ssl); + ssl->next_state = HS_FINISHED; + } + } + else +#endif + if ((ret = send_certificate(ssl)) == SSL_OK) + { +#ifdef CONFIG_SSL_CERT_VERIFICATION + /* ask the client for its certificate */ + if (IS_SET_SSL_FLAG(SSL_CLIENT_AUTHENTICATION)) + { + if ((ret = send_certificate_request(ssl)) == SSL_OK) + { + ret = send_server_hello_done(ssl); + ssl->next_state = HS_CERTIFICATE; + } + } + else +#endif + { + ret = send_server_hello_done(ssl); + ssl->next_state = HS_CLIENT_KEY_XCHG; + } + } + } + + return ret; +} + +/* + * Send a server hello message. + */ +static int send_server_hello(SSL *ssl) +{ + uint8_t *buf = ssl->bm_data; + int offset = 0; + + buf[0] = HS_SERVER_HELLO; + buf[1] = 0; + buf[2] = 0; + /* byte 3 is calculated later */ + buf[4] = 0x03; + buf[5] = ssl->version & 0x0f; + + /* server random value */ + get_random(SSL_RANDOM_SIZE, &buf[6]); + memcpy(ssl->dc->server_random, &buf[6], SSL_RANDOM_SIZE); + offset = 6 + SSL_RANDOM_SIZE; + +#ifndef CONFIG_SSL_SKELETON_MODE + if (IS_SET_SSL_FLAG(SSL_SESSION_RESUME)) + { + /* retrieve id from session cache */ + buf[offset++] = SSL_SESSION_ID_SIZE; + memcpy(&buf[offset], ssl->session->session_id, SSL_SESSION_ID_SIZE); + memcpy(ssl->session_id, ssl->session->session_id, SSL_SESSION_ID_SIZE); + ssl->sess_id_size = SSL_SESSION_ID_SIZE; + offset += SSL_SESSION_ID_SIZE; + } + else /* generate our own session id */ +#endif + { +#ifndef CONFIG_SSL_SKELETON_MODE + buf[offset++] = SSL_SESSION_ID_SIZE; + get_random(SSL_SESSION_ID_SIZE, &buf[offset]); + memcpy(ssl->session_id, &buf[offset], SSL_SESSION_ID_SIZE); + ssl->sess_id_size = SSL_SESSION_ID_SIZE; + + /* store id in session cache */ + if (ssl->ssl_ctx->num_sessions) + { + memcpy(ssl->session->session_id, + ssl->session_id, SSL_SESSION_ID_SIZE); + } + + offset += SSL_SESSION_ID_SIZE; +#else + buf[offset++] = 0; /* don't bother with session id in skelton mode */ +#endif + } + + buf[offset++] = 0; /* cipher we are using */ + buf[offset++] = ssl->cipher; + buf[offset++] = 0; /* no compression */ + buf[3] = offset - 4; /* handshake size */ + return send_packet(ssl, PT_HANDSHAKE_PROTOCOL, NULL, offset); +} + +/* + * Send the server hello done message. + */ +static int send_server_hello_done(SSL *ssl) +{ + return send_packet(ssl, PT_HANDSHAKE_PROTOCOL, + g_hello_done, sizeof(g_hello_done)); +} + +/* + * Pull apart a client key exchange message. Decrypt the pre-master key (using + * our RSA private key) and then work out the master key. Initialise the + * ciphers. + */ +static int process_client_key_xchg(SSL *ssl) +{ + uint8_t *buf = &ssl->bm_data[ssl->dc->bm_proc_index]; + int pkt_size = ssl->bm_index; + int premaster_size, secret_length = (buf[2] << 8) + buf[3]; + uint8_t premaster_secret[MAX_KEY_BYTE_SIZE]; + RSA_CTX *rsa_ctx = ssl->ssl_ctx->rsa_ctx; + int offset = 4; + int ret = SSL_OK; + + if (rsa_ctx == NULL) + { + ret = SSL_ERROR_NO_CERT_DEFINED; + goto error; + } + + /* is there an extra size field? */ + if ((secret_length - 2) == rsa_ctx->num_octets) + offset += 2; + + PARANOIA_CHECK(pkt_size, rsa_ctx->num_octets+offset); + + /* rsa_ctx->bi_ctx is not thread-safe */ + SSL_CTX_LOCK(ssl->ssl_ctx->mutex); + premaster_size = RSA_decrypt(rsa_ctx, &buf[offset], premaster_secret, 1); + SSL_CTX_UNLOCK(ssl->ssl_ctx->mutex); + + if (premaster_size != SSL_SECRET_SIZE || + premaster_secret[0] != 0x03 || /* must be the same as client + offered version */ + premaster_secret[1] != (ssl->client_version & 0x0f)) + { + /* guard against a Bleichenbacher attack */ + get_random(SSL_SECRET_SIZE, premaster_secret); + /* and continue - will die eventually when checking the mac */ + } + +#if 0 + print_blob("pre-master", premaster_secret, SSL_SECRET_SIZE); +#endif + + generate_master_secret(ssl, premaster_secret); + +#ifdef CONFIG_SSL_CERT_VERIFICATION + ssl->next_state = IS_SET_SSL_FLAG(SSL_CLIENT_AUTHENTICATION) ? + HS_CERT_VERIFY : HS_FINISHED; +#else + ssl->next_state = HS_FINISHED; +#endif + + ssl->dc->bm_proc_index += rsa_ctx->num_octets+offset; +error: + return ret; +} + +#ifdef CONFIG_SSL_CERT_VERIFICATION +static const uint8_t g_cert_request[] = { HS_CERT_REQ, 0, 0, 4, 1, 0, 0, 0 }; + +/* + * Send the certificate request message. + */ +static int send_certificate_request(SSL *ssl) +{ + return send_packet(ssl, PT_HANDSHAKE_PROTOCOL, + g_cert_request, sizeof(g_cert_request)); +} + +/* + * Ensure the client has the private key by first decrypting the packet and + * then checking the packet digests. + */ +static int process_cert_verify(SSL *ssl) +{ + uint8_t *buf = &ssl->bm_data[ssl->dc->bm_proc_index]; + int pkt_size = ssl->bm_index; + uint8_t dgst_buf[MAX_KEY_BYTE_SIZE]; + uint8_t dgst[MD5_SIZE+SHA1_SIZE]; + X509_CTX *x509_ctx = ssl->x509_ctx; + int ret = SSL_OK; + int n; + + PARANOIA_CHECK(pkt_size, x509_ctx->rsa_ctx->num_octets+6); + DISPLAY_RSA(ssl, x509_ctx->rsa_ctx); + + /* rsa_ctx->bi_ctx is not thread-safe */ + SSL_CTX_LOCK(ssl->ssl_ctx->mutex); + n = RSA_decrypt(x509_ctx->rsa_ctx, &buf[6], dgst_buf, 0); + SSL_CTX_UNLOCK(ssl->ssl_ctx->mutex); + + if (n != SHA1_SIZE + MD5_SIZE) + { + ret = SSL_ERROR_INVALID_KEY; + goto end_cert_vfy; + } + + finished_digest(ssl, NULL, dgst); /* calculate the digest */ + if (memcmp(dgst_buf, dgst, MD5_SIZE + SHA1_SIZE)) + { + ret = SSL_ERROR_INVALID_KEY; + } + +end_cert_vfy: + ssl->next_state = HS_FINISHED; +error: + return ret; +} + +#endif diff --git a/features/unsupported/net/https/axTLS/ssl/version.h b/features/unsupported/net/https/axTLS/ssl/version.h new file mode 100644 index 00000000000..e8158cc0d9f --- /dev/null +++ b/features/unsupported/net/https/axTLS/ssl/version.h @@ -0,0 +1 @@ +#define AXTLS_VERSION "1.4.9" diff --git a/features/unsupported/net/https/axTLS/ssl/x509.c b/features/unsupported/net/https/axTLS/ssl/x509.c new file mode 100644 index 00000000000..4f88c8738d2 --- /dev/null +++ b/features/unsupported/net/https/axTLS/ssl/x509.c @@ -0,0 +1,556 @@ +/* + * Copyright (c) 2007, Cameron Rich + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * * Neither the name of the axTLS project nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @file x509.c + * + * Certificate processing. + */ + +#include +#include +#include +#include +#include "os_port.h" +#include "crypto_misc.h" +#include "sockets.h" +#include "config.h" +#ifdef CONFIG_SSL_CERT_VERIFICATION +/** + * Retrieve the signature from a certificate. + */ +static const uint8_t *get_signature(const uint8_t *asn1_sig, int *len) +{ + int offset = 0; + const uint8_t *ptr = NULL; + + if (asn1_next_obj(asn1_sig, &offset, ASN1_SEQUENCE) < 0 || + asn1_skip_obj(asn1_sig, &offset, ASN1_SEQUENCE)) + goto end_get_sig; + + if (asn1_sig[offset++] != ASN1_OCTET_STRING) + goto end_get_sig; + *len = get_asn1_length(asn1_sig, &offset); + ptr = &asn1_sig[offset]; /* all ok */ + +end_get_sig: + return ptr; +} + +#endif + +/** + * Construct a new x509 object. + * @return 0 if ok. < 0 if there was a problem. + */ +int x509_new(const uint8_t *cert, int *len, X509_CTX **ctx) +{ + + int begin_tbs, end_tbs; + int ret = X509_NOT_OK, offset = 0, cert_size = 0; + X509_CTX *x509_ctx; + BI_CTX *bi_ctx; + *ctx = (X509_CTX *)calloc(1, sizeof(X509_CTX)); + x509_ctx = *ctx; + /* get the certificate size */ + asn1_skip_obj(cert, &cert_size, ASN1_SEQUENCE); + + if (asn1_next_obj(cert, &offset, ASN1_SEQUENCE) < 0) + goto end_cert; + + begin_tbs = offset; /* start of the tbs */ + end_tbs = begin_tbs; /* work out the end of the tbs */ + asn1_skip_obj(cert, &end_tbs, ASN1_SEQUENCE); + if (asn1_next_obj(cert, &offset, ASN1_SEQUENCE) < 0) + goto end_cert; + if (cert[offset] == ASN1_EXPLICIT_TAG) /* optional version */ + { + if (asn1_version(cert, &offset, x509_ctx)) + goto end_cert; + } + if (asn1_skip_obj(cert, &offset, ASN1_INTEGER) || /* serial number */ + asn1_next_obj(cert, &offset, ASN1_SEQUENCE) < 0) + { + goto end_cert; + } + /* make sure the signature is ok */ + if (asn1_signature_type(cert, &offset, x509_ctx)) + { + ret = X509_VFY_ERROR_UNSUPPORTED_DIGEST; + goto end_cert; + } + if (asn1_name(cert, &offset, x509_ctx->ca_cert_dn) || + asn1_validity(cert, &offset, x509_ctx) || + asn1_name(cert, &offset, x509_ctx->cert_dn) || + asn1_public_key(cert, &offset, x509_ctx)) + { + goto end_cert; + } + bi_ctx = x509_ctx->rsa_ctx->bi_ctx; +#ifdef CONFIG_SSL_CERT_VERIFICATION /* only care if doing verification */ + + /* use the appropriate signature algorithm (SHA1/MD5/MD2) */ + if (x509_ctx->sig_type == SIG_TYPE_MD5) + { + MD5_CTX md5_ctx; + uint8_t md5_dgst[MD5_SIZE]; + MD5_Init(&md5_ctx); + MD5_Update(&md5_ctx, &cert[begin_tbs], end_tbs-begin_tbs); + MD5_Final(md5_dgst, &md5_ctx); + x509_ctx->digest = bi_import(bi_ctx, md5_dgst, MD5_SIZE); + } + else if (x509_ctx->sig_type == SIG_TYPE_SHA1) + { + SHA1_CTX sha_ctx; + uint8_t sha_dgst[SHA1_SIZE]; + SHA1_Init(&sha_ctx); + SHA1_Update(&sha_ctx, &cert[begin_tbs], end_tbs-begin_tbs); + SHA1_Final(sha_dgst, &sha_ctx); + x509_ctx->digest = bi_import(bi_ctx, sha_dgst, SHA1_SIZE); + } + else if (x509_ctx->sig_type == SIG_TYPE_MD2) + { + MD2_CTX md2_ctx; + uint8_t md2_dgst[MD2_SIZE]; + MD2_Init(&md2_ctx); + MD2_Update(&md2_ctx, &cert[begin_tbs], end_tbs-begin_tbs); + MD2_Final(md2_dgst, &md2_ctx); + x509_ctx->digest = bi_import(bi_ctx, md2_dgst, MD2_SIZE); + } + + if (cert[offset] == ASN1_V3_DATA) + { + int suboffset; + + ++offset; + get_asn1_length(cert, &offset); + + if ((suboffset = asn1_find_subjectaltname(cert, offset)) > 0) + { + if (asn1_next_obj(cert, &suboffset, ASN1_OCTET_STRING) > 0) + { + int altlen; + + if ((altlen = asn1_next_obj(cert, + &suboffset, ASN1_SEQUENCE)) > 0) + { + int endalt = suboffset + altlen; + int totalnames = 0; + + while (suboffset < endalt) + { + int type = cert[suboffset++]; + int dnslen = get_asn1_length(cert, &suboffset); + + if (type == ASN1_CONTEXT_DNSNAME) + { + x509_ctx->subject_alt_dnsnames = (char**) + realloc(x509_ctx->subject_alt_dnsnames, + (totalnames + 2) * sizeof(char*)); + x509_ctx->subject_alt_dnsnames[totalnames] = + (char*)malloc(dnslen + 1); + x509_ctx->subject_alt_dnsnames[totalnames+1] = NULL; + memcpy(x509_ctx->subject_alt_dnsnames[totalnames], + cert + suboffset, dnslen); + x509_ctx->subject_alt_dnsnames[ + totalnames][dnslen] = 0; + ++totalnames; + } + + suboffset += dnslen; + } + } + } + } + } + + offset = end_tbs; /* skip the rest of v3 data */ + if (asn1_skip_obj(cert, &offset, ASN1_SEQUENCE) || + asn1_signature(cert, &offset, x509_ctx)) + goto end_cert; + +#endif + ret = X509_OK; +end_cert: + if (len) + { + *len = cert_size; + } + + if (ret) + { +#ifdef CONFIG_SSL_FULL_MODE + printf("Error: Invalid X509 ASN.1 file (%s)\n", + x509_display_error(ret)); +#endif + x509_free(x509_ctx); + *ctx = NULL; + } + return ret; +} + +/** + * Free an X.509 object's resources. + */ +void x509_free(X509_CTX *x509_ctx) +{ + X509_CTX *next; + int i; + + if (x509_ctx == NULL) /* if already null, then don't bother */ + return; + + for (i = 0; i < X509_NUM_DN_TYPES; i++) + { + free(x509_ctx->ca_cert_dn[i]); + free(x509_ctx->cert_dn[i]); + } + + free(x509_ctx->signature); + +#ifdef CONFIG_SSL_CERT_VERIFICATION + if (x509_ctx->digest) + { + bi_free(x509_ctx->rsa_ctx->bi_ctx, x509_ctx->digest); + } + + if (x509_ctx->subject_alt_dnsnames) + { + for (i = 0; x509_ctx->subject_alt_dnsnames[i]; ++i) + free(x509_ctx->subject_alt_dnsnames[i]); + + free(x509_ctx->subject_alt_dnsnames); + } +#endif + + RSA_free(x509_ctx->rsa_ctx); + next = x509_ctx->next; + free(x509_ctx); + x509_free(next); /* clear the chain */ +} + +#ifdef CONFIG_SSL_CERT_VERIFICATION +/** + * Take a signature and decrypt it. + */ +static bigint *sig_verify(BI_CTX *ctx, const uint8_t *sig, int sig_len, + bigint *modulus, bigint *pub_exp) +{ + int i, size; + bigint *decrypted_bi, *dat_bi; + bigint *bir = NULL; + uint8_t *block = (uint8_t *)alloca(sig_len); + + /* decrypt */ + dat_bi = bi_import(ctx, sig, sig_len); + ctx->mod_offset = BIGINT_M_OFFSET; + + /* convert to a normal block */ + decrypted_bi = bi_mod_power2(ctx, dat_bi, modulus, pub_exp); + + bi_export(ctx, decrypted_bi, block, sig_len); + ctx->mod_offset = BIGINT_M_OFFSET; + + i = 10; /* start at the first possible non-padded byte */ + while (block[i++] && i < sig_len); + size = sig_len - i; + + /* get only the bit we want */ + if (size > 0) + { + int len; + const uint8_t *sig_ptr = get_signature(&block[i], &len); + + if (sig_ptr) + { + bir = bi_import(ctx, sig_ptr, len); + } + } + + /* save a few bytes of memory */ + bi_clear_cache(ctx); + return bir; +} + +/** + * Do some basic checks on the certificate chain. + * + * Certificate verification consists of a number of checks: + * - The date of the certificate is after the start date. + * - The date of the certificate is before the finish date. + * - A root certificate exists in the certificate store. + * - That the certificate(s) are not self-signed. + * - The certificate chain is valid. + * - The signature of the certificate is valid. + */ +int x509_verify(const CA_CERT_CTX *ca_cert_ctx, const X509_CTX *cert) +{ + int ret = X509_OK, i = 0; + bigint *cert_sig; + X509_CTX *next_cert = NULL; + BI_CTX *ctx = NULL; + bigint *mod = NULL, *expn = NULL; + int match_ca_cert = 0; + struct timeval tv; + uint8_t is_self_signed = 0; + + if (cert == NULL) + { + ret = X509_VFY_ERROR_NO_TRUSTED_CERT; + goto end_verify; + } + + /* a self-signed certificate that is not in the CA store - use this + to check the signature */ + if (asn1_compare_dn(cert->ca_cert_dn, cert->cert_dn) == 0) + { + printf("self signed cert\r\n"); + is_self_signed = 1; + ctx = cert->rsa_ctx->bi_ctx; + mod = cert->rsa_ctx->m; + expn = cert->rsa_ctx->e; + } + + gettimeofday(&tv, NULL); + + /* check the not before date */ + if (tv.tv_sec < cert->not_before) + { + ret = X509_VFY_ERROR_NOT_YET_VALID; + goto end_verify; + } + + /* check the not after date */ + if (tv.tv_sec > cert->not_after) + { + ret = X509_VFY_ERROR_EXPIRED; + goto end_verify; + } + + next_cert = cert->next; + + /* last cert in the chain - look for a trusted cert */ + if (next_cert == NULL) + { + if (ca_cert_ctx != NULL) + { + /* go thu the CA store */ + while (i < CONFIG_X509_MAX_CA_CERTS && ca_cert_ctx->cert[i]) + { + if (asn1_compare_dn(cert->ca_cert_dn, + ca_cert_ctx->cert[i]->cert_dn) == 0) + { + /* use this CA certificate for signature verification */ + match_ca_cert = 1; + ctx = ca_cert_ctx->cert[i]->rsa_ctx->bi_ctx; + mod = ca_cert_ctx->cert[i]->rsa_ctx->m; + expn = ca_cert_ctx->cert[i]->rsa_ctx->e; + break; + } + + i++; + } + } + + /* couldn't find a trusted cert (& let self-signed errors + be returned) */ + if (!match_ca_cert && !is_self_signed) + { + ret = X509_VFY_ERROR_NO_TRUSTED_CERT; + goto end_verify; + } + } + else if (asn1_compare_dn(cert->ca_cert_dn, next_cert->cert_dn) != 0) + { + /* check the chain */ + ret = X509_VFY_ERROR_INVALID_CHAIN; + goto end_verify; + } + else /* use the next certificate in the chain for signature verify */ + { + ctx = next_cert->rsa_ctx->bi_ctx; + mod = next_cert->rsa_ctx->m; + expn = next_cert->rsa_ctx->e; + } + + /* cert is self signed */ + if (!match_ca_cert && is_self_signed) + { + ret = X509_VFY_ERROR_SELF_SIGNED; + goto end_verify; + } + + /* check the signature */ + cert_sig = sig_verify(ctx, cert->signature, cert->sig_len, + bi_clone(ctx, mod), bi_clone(ctx, expn)); + + if (cert_sig && cert->digest) + { + if (bi_compare(cert_sig, cert->digest) != 0) + ret = X509_VFY_ERROR_BAD_SIGNATURE; + + + bi_free(ctx, cert_sig); + } + else + { + ret = X509_VFY_ERROR_BAD_SIGNATURE; + } + + if (ret) + goto end_verify; + + /* go down the certificate chain using recursion. */ + if (next_cert != NULL) + { + ret = x509_verify(ca_cert_ctx, next_cert); + } + +end_verify: + return ret; +} +#endif + +#if defined (CONFIG_SSL_FULL_MODE) +/** + * Used for diagnostics. + */ +static const char *not_part_of_cert = ""; +void x509_print(const X509_CTX *cert, CA_CERT_CTX *ca_cert_ctx) +{ + if (cert == NULL) + return; + + printf("=== CERTIFICATE ISSUED TO ===\n"); + printf("Common Name (CN):\t\t"); + printf("%s\r\n", cert->cert_dn[X509_COMMON_NAME] ? + cert->cert_dn[X509_COMMON_NAME] : not_part_of_cert); + + printf("Organization (O):\t\t"); + printf("%s\r\n", cert->cert_dn[X509_ORGANIZATION] ? + cert->cert_dn[X509_ORGANIZATION] : not_part_of_cert); + + printf("Organizational Unit (OU):\t"); + printf("%s\r\n", cert->cert_dn[X509_ORGANIZATIONAL_UNIT] ? + cert->cert_dn[X509_ORGANIZATIONAL_UNIT] : not_part_of_cert); + + printf("=== CERTIFICATE ISSUED BY ===\r\n"); + printf("Common Name (CN):\t\t"); + printf("%s\r\n", cert->ca_cert_dn[X509_COMMON_NAME] ? + cert->ca_cert_dn[X509_COMMON_NAME] : not_part_of_cert); + + printf("Organization (O):\t\t"); + printf("%s\r\n", cert->ca_cert_dn[X509_ORGANIZATION] ? + cert->ca_cert_dn[X509_ORGANIZATION] : not_part_of_cert); + + printf("Organizational Unit (OU):\t"); + printf("%s\r\n", cert->ca_cert_dn[X509_ORGANIZATIONAL_UNIT] ? + cert->ca_cert_dn[X509_ORGANIZATIONAL_UNIT] : not_part_of_cert); + + printf("Not Before:\t\t\t%s\r\n", ctime(&cert->not_before)); + printf("Not After:\t\t\t%s\r\n", ctime(&cert->not_after)); + printf("RSA bitsize:\t\t\t%d\r\n", cert->rsa_ctx->num_octets*8); + printf("Sig Type:\t\t\t"); + switch (cert->sig_type) + { + case SIG_TYPE_MD5: + printf("MD5\r\n"); + break; + case SIG_TYPE_SHA1: + printf("SHA1\r\n"); + break; + case SIG_TYPE_MD2: + printf("MD2\r\n"); + break; + default: + printf("Unrecognized: %d\r\n", cert->sig_type); + break; + } + + if (ca_cert_ctx) + { + printf("Verify:\t\t\t\t%s\r\n", + x509_display_error(x509_verify(ca_cert_ctx, cert))); + } + +#if 0 + print_blob("Signature", cert->signature, cert->sig_len); + bi_print("Modulus", cert->rsa_ctx->m); + bi_print("Pub Exp", cert->rsa_ctx->e); +#endif + + if (ca_cert_ctx) + { + x509_print(cert->next, ca_cert_ctx); + } + + TTY_FLUSH(); +} + +const char * x509_display_error(int error) +{ + switch (error) + { + case X509_OK: + return "Certificate verify successful"; + + case X509_NOT_OK: + return "X509 not ok"; + + case X509_VFY_ERROR_NO_TRUSTED_CERT: + return "No trusted cert is available"; + + case X509_VFY_ERROR_BAD_SIGNATURE: + return "Bad signature"; + + case X509_VFY_ERROR_NOT_YET_VALID: + return "Cert is not yet valid"; + + case X509_VFY_ERROR_EXPIRED: + return "Cert has expired"; + + case X509_VFY_ERROR_SELF_SIGNED: + return "Cert is self-signed"; + + case X509_VFY_ERROR_INVALID_CHAIN: + return "Chain is invalid (check order of certs)"; + + case X509_VFY_ERROR_UNSUPPORTED_DIGEST: + return "Unsupported digest"; + + case X509_INVALID_PRIV_KEY: + return "Invalid private key"; + + default: + return "Unknown"; + } +} +#endif /* CONFIG_SSL_FULL_MODE */ + diff --git a/features/unsupported/net/lwip/Socket/Endpoint.cpp b/features/unsupported/net/lwip/Socket/Endpoint.cpp new file mode 100644 index 00000000000..25688d0e29e --- /dev/null +++ b/features/unsupported/net/lwip/Socket/Endpoint.cpp @@ -0,0 +1,73 @@ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +#include "Socket/Socket.h" +#include "Socket/Endpoint.h" +#include +#include + +Endpoint::Endpoint() { + reset_address(); +} +Endpoint::~Endpoint() {} + +void Endpoint::reset_address(void) { + std::memset(&_remoteHost, 0, sizeof(struct sockaddr_in)); + _ipAddress[0] = '\0'; +} + +#include "stdio.h" + +int Endpoint::set_address(const char* host, const int port) { + reset_address(); + + // IP Address + char address[5]; + char *p_address = address; + + // Dot-decimal notation + int result = std::sscanf(host, "%3u.%3u.%3u.%3u", + (unsigned int*)&address[0], (unsigned int*)&address[1], + (unsigned int*)&address[2], (unsigned int*)&address[3]); + + if (result != 4) { + // Resolve address with DNS + struct hostent *host_address = lwip_gethostbyname(host); + if (host_address == NULL) + return -1; //Could not resolve address + p_address = (char*)host_address->h_addr_list[0]; + } + std::memcpy((char*)&_remoteHost.sin_addr.s_addr, p_address, 4); + + // Address family + _remoteHost.sin_family = AF_INET; + + // Set port + _remoteHost.sin_port = htons(port); + + return 0; +} + +char* Endpoint::get_address() { + if ((_ipAddress[0] == '\0') && (_remoteHost.sin_addr.s_addr != 0)) + inet_ntoa_r(_remoteHost.sin_addr, _ipAddress, sizeof(_ipAddress)); + return _ipAddress; +} + +int Endpoint::get_port() { + return ntohs(_remoteHost.sin_port); +} diff --git a/features/unsupported/net/lwip/Socket/Endpoint.h b/features/unsupported/net/lwip/Socket/Endpoint.h new file mode 100644 index 00000000000..788a0a82177 --- /dev/null +++ b/features/unsupported/net/lwip/Socket/Endpoint.h @@ -0,0 +1,63 @@ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +#ifndef ENDPOINT_H +#define ENDPOINT_H + +class UDPSocket; + +/** +IP Endpoint (address, port) +*/ +class Endpoint { + friend class UDPSocket; + +public: + /** IP Endpoint (address, port) + */ + Endpoint(void); + + ~Endpoint(void); + + /** Reset the address of this endpoint + */ + void reset_address(void); + + /** Set the address of this endpoint + \param host The endpoint address (it can either be an IP Address or a hostname that will be resolved with DNS). + \param port The endpoint port + \return 0 on success, -1 on failure (when an hostname cannot be resolved by DNS). + */ + int set_address(const char* host, const int port); + + /** Get the IP address of this endpoint + \return The IP address of this endpoint. + */ + char* get_address(void); + + /** Get the port of this endpoint + \return The port of this endpoint + */ + int get_port(void); + +protected: + char _ipAddress[17]; + struct sockaddr_in _remoteHost; + +}; + +#endif diff --git a/features/unsupported/net/lwip/Socket/Socket.cpp b/features/unsupported/net/lwip/Socket/Socket.cpp new file mode 100644 index 00000000000..04a883c158b --- /dev/null +++ b/features/unsupported/net/lwip/Socket/Socket.cpp @@ -0,0 +1,91 @@ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +#include "Socket/Socket.h" +#include + +using std::memset; + +Socket::Socket() : _sock_fd(-1), _blocking(true), _timeout(1500) { + +} + +void Socket::set_blocking(bool blocking, unsigned int timeout) { + _blocking = blocking; + _timeout = timeout; +} + +int Socket::init_socket(int type) { + if (_sock_fd != -1) + return -1; + + int fd = lwip_socket(AF_INET, type, 0); + if (fd < 0) + return -1; + + _sock_fd = fd; + return 0; +} + +int Socket::set_option(int level, int optname, const void *optval, socklen_t optlen) { + return lwip_setsockopt(_sock_fd, level, optname, optval, optlen); +} + +int Socket::get_option(int level, int optname, void *optval, socklen_t *optlen) { + return lwip_getsockopt(_sock_fd, level, optname, optval, optlen); +} + +int Socket::select(struct timeval *timeout, bool read, bool write) { + fd_set fdSet; + FD_ZERO(&fdSet); + FD_SET(_sock_fd, &fdSet); + + fd_set* readset = (read ) ? (&fdSet) : (NULL); + fd_set* writeset = (write) ? (&fdSet) : (NULL); + + int ret = lwip_select(FD_SETSIZE, readset, writeset, NULL, timeout); + return (ret <= 0 || !FD_ISSET(_sock_fd, &fdSet)) ? (-1) : (0); +} + +int Socket::wait_readable(TimeInterval& timeout) { + return select(&timeout._time, true, false); +} + +int Socket::wait_writable(TimeInterval& timeout) { + return select(&timeout._time, false, true); +} + +int Socket::close(bool shutdown) { + if (_sock_fd < 0) + return -1; + + if (shutdown) + lwip_shutdown(_sock_fd, SHUT_RDWR); + lwip_close(_sock_fd); + _sock_fd = -1; + + return 0; +} + +Socket::~Socket() { + close(); //Don't want to leak +} + +TimeInterval::TimeInterval(unsigned int ms) { + _time.tv_sec = ms / 1000; + _time.tv_usec = (ms - (_time.tv_sec * 1000)) * 1000; +} diff --git a/features/unsupported/net/lwip/Socket/Socket.h b/features/unsupported/net/lwip/Socket/Socket.h new file mode 100644 index 00000000000..e2e1803e85e --- /dev/null +++ b/features/unsupported/net/lwip/Socket/Socket.h @@ -0,0 +1,104 @@ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +#ifndef SOCKET_H_ +#define SOCKET_H_ + +#include "lwip/sockets.h" +#include "lwip/netdb.h" + +//DNS +inline struct hostent *gethostbyname(const char *name) { + return lwip_gethostbyname(name); +} + +inline int gethostbyname_r(const char *name, struct hostent *ret, char *buf, size_t buflen, struct hostent **result, int *h_errnop) { + return lwip_gethostbyname_r(name, ret, buf, buflen, result, h_errnop); +} + +class TimeInterval; + +/** Socket file descriptor and select wrapper + */ +class Socket { +public: + /** Socket + */ + Socket(); + + /** Set blocking or non-blocking mode of the socket and a timeout on + blocking socket operations + \param blocking true for blocking mode, false for non-blocking mode. + \param timeout timeout in ms [Default: (1500)ms]. + */ + void set_blocking(bool blocking, unsigned int timeout=1500); + + /** Set socket options + \param level stack level (see: lwip/sockets.h) + \param optname option ID + \param optval option value + \param socklen_t length of the option value + \return 0 on success, -1 on failure + */ + int set_option(int level, int optname, const void *optval, socklen_t optlen); + + /** Get socket options + \param level stack level (see: lwip/sockets.h) + \param optname option ID + \param optval buffer pointer where to write the option value + \param socklen_t length of the option value + \return 0 on success, -1 on failure + */ + int get_option(int level, int optname, void *optval, socklen_t *optlen); + + /** Close the socket + \param shutdown free the left-over data in message queues + */ + int close(bool shutdown=true); + + ~Socket(); + +protected: + int _sock_fd; + int init_socket(int type); + + int wait_readable(TimeInterval& timeout); + int wait_writable(TimeInterval& timeout); + + bool _blocking; + unsigned int _timeout; + +private: + int select(struct timeval *timeout, bool read, bool write); +}; + +/** Time interval class used to specify timeouts + */ +class TimeInterval { + friend class Socket; + +public: + /** Time Interval + \param ms time interval expressed in milliseconds + */ + TimeInterval(unsigned int ms); + +private: + struct timeval _time; +}; + +#endif /* SOCKET_H_ */ diff --git a/features/unsupported/net/lwip/Socket/TCPSocketConnection.cpp b/features/unsupported/net/lwip/Socket/TCPSocketConnection.cpp new file mode 100644 index 00000000000..b8533040994 --- /dev/null +++ b/features/unsupported/net/lwip/Socket/TCPSocketConnection.cpp @@ -0,0 +1,133 @@ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +#include "TCPSocketConnection.h" +#include + +using std::memset; +using std::memcpy; + +TCPSocketConnection::TCPSocketConnection() : + _is_connected(false) { +} + +int TCPSocketConnection::connect(const char* host, const int port) { + if (init_socket(SOCK_STREAM) < 0) + return -1; + + if (set_address(host, port) != 0) + return -1; + + if (lwip_connect(_sock_fd, (const struct sockaddr *) &_remoteHost, sizeof(_remoteHost)) < 0) { + close(); + return -1; + } + _is_connected = true; + + return 0; +} + +bool TCPSocketConnection::is_connected(void) { + return _is_connected; +} + +int TCPSocketConnection::send(char* data, int length) { + if ((_sock_fd < 0) || !_is_connected) + return -1; + + if (!_blocking) { + TimeInterval timeout(_timeout); + if (wait_writable(timeout) != 0) + return -1; + } + + int n = lwip_send(_sock_fd, data, length, 0); + _is_connected = (n != 0); + + return n; +} + +// -1 if unsuccessful, else number of bytes written +int TCPSocketConnection::send_all(char* data, int length) { + if ((_sock_fd < 0) || !_is_connected) + return -1; + + int writtenLen = 0; + TimeInterval timeout(_timeout); + while (writtenLen < length) { + if (!_blocking) { + // Wait for socket to be writeable + if (wait_writable(timeout) != 0) + return writtenLen; + } + + int ret = lwip_send(_sock_fd, data + writtenLen, length - writtenLen, 0); + if (ret > 0) { + writtenLen += ret; + continue; + } else if (ret == 0) { + _is_connected = false; + return writtenLen; + } else { + return -1; //Connnection error + } + } + return writtenLen; +} + +int TCPSocketConnection::receive(char* data, int length) { + if ((_sock_fd < 0) || !_is_connected) + return -1; + + if (!_blocking) { + TimeInterval timeout(_timeout); + if (wait_readable(timeout) != 0) + return -1; + } + + int n = lwip_recv(_sock_fd, data, length, 0); + _is_connected = (n != 0); + + return n; +} + +// -1 if unsuccessful, else number of bytes received +int TCPSocketConnection::receive_all(char* data, int length) { + if ((_sock_fd < 0) || !_is_connected) + return -1; + + int readLen = 0; + TimeInterval timeout(_timeout); + while (readLen < length) { + if (!_blocking) { + //Wait for socket to be readable + if (wait_readable(timeout) != 0) + return readLen; + } + + int ret = lwip_recv(_sock_fd, data + readLen, length - readLen, 0); + if (ret > 0) { + readLen += ret; + } else if (ret == 0) { + _is_connected = false; + return readLen; + } else { + return -1; //Connnection error + } + } + return readLen; +} diff --git a/features/unsupported/net/lwip/Socket/TCPSocketConnection.h b/features/unsupported/net/lwip/Socket/TCPSocketConnection.h new file mode 100644 index 00000000000..7af7bf624c1 --- /dev/null +++ b/features/unsupported/net/lwip/Socket/TCPSocketConnection.h @@ -0,0 +1,81 @@ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef TCPSOCKET_H +#define TCPSOCKET_H + +#include "Socket/Socket.h" +#include "Socket/Endpoint.h" + +/** +TCP socket connection +*/ +class TCPSocketConnection : public Socket, public Endpoint { + friend class TCPSocketServer; + +public: + /** TCP socket connection + */ + TCPSocketConnection(); + + /** Connects this TCP socket to the server + \param host The host to connect to. It can either be an IP Address or a hostname that will be resolved with DNS. + \param port The host's port to connect to. + \return 0 on success, -1 on failure. + */ + int connect(const char* host, const int port); + + /** Check if the socket is connected + \return true if connected, false otherwise. + */ + bool is_connected(void); + + /** Send data to the remote host. + \param data The buffer to send to the host. + \param length The length of the buffer to send. + \return the number of written bytes on success (>=0) or -1 on failure + */ + int send(char* data, int length); + + /** Send all the data to the remote host. + \param data The buffer to send to the host. + \param length The length of the buffer to send. + \return the number of written bytes on success (>=0) or -1 on failure + */ + int send_all(char* data, int length); + + /** Receive data from the remote host. + \param data The buffer in which to store the data received from the host. + \param length The maximum length of the buffer. + \return the number of received bytes on success (>=0) or -1 on failure + */ + int receive(char* data, int length); + + /** Receive all the data from the remote host. + \param data The buffer in which to store the data received from the host. + \param length The maximum length of the buffer. + \return the number of received bytes on success (>=0) or -1 on failure + */ + int receive_all(char* data, int length); + +private: + bool _is_connected; + +}; + +#endif diff --git a/features/unsupported/net/lwip/Socket/TCPSocketServer.cpp b/features/unsupported/net/lwip/Socket/TCPSocketServer.cpp new file mode 100644 index 00000000000..d894b94e398 --- /dev/null +++ b/features/unsupported/net/lwip/Socket/TCPSocketServer.cpp @@ -0,0 +1,78 @@ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +#include "TCPSocketServer.h" + +#include + +using std::memset; +using std::memcpy; + +TCPSocketServer::TCPSocketServer() { + +} + +int TCPSocketServer::bind(int port) { + if (init_socket(SOCK_STREAM) < 0) + return -1; + + struct sockaddr_in localHost; + memset(&localHost, 0, sizeof(localHost)); + + localHost.sin_family = AF_INET; + localHost.sin_port = htons(port); + localHost.sin_addr.s_addr = INADDR_ANY; + + if (lwip_bind(_sock_fd, (const struct sockaddr *) &localHost, sizeof(localHost)) < 0) { + close(); + return -1; + } + + return 0; +} + +int TCPSocketServer::listen(int max) { + if (_sock_fd < 0) + return -1; + + if (lwip_listen(_sock_fd, max) < 0) { + close(); + return -1; + } + + return 0; +} + +int TCPSocketServer::accept(TCPSocketConnection& connection) { + if (_sock_fd < 0) + return -1; + + if (!_blocking) { + TimeInterval timeout(_timeout); + if (wait_readable(timeout) != 0) + return -1; + } + connection.reset_address(); + socklen_t newSockRemoteHostLen = sizeof(connection._remoteHost); + int fd = lwip_accept(_sock_fd, (struct sockaddr*) &connection._remoteHost, &newSockRemoteHostLen); + if (fd < 0) + return -1; //Accept failed + connection._sock_fd = fd; + connection._is_connected = true; + + return 0; +} diff --git a/features/unsupported/net/lwip/Socket/TCPSocketServer.h b/features/unsupported/net/lwip/Socket/TCPSocketServer.h new file mode 100644 index 00000000000..214791ce45d --- /dev/null +++ b/features/unsupported/net/lwip/Socket/TCPSocketServer.h @@ -0,0 +1,52 @@ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +#ifndef TCPSOCKETSERVER_H +#define TCPSOCKETSERVER_H + +#include "Socket/Socket.h" +#include "TCPSocketConnection.h" + +/** TCP Server. + */ +class TCPSocketServer : public Socket { + public: + /** Instantiate a TCP Server. + */ + TCPSocketServer(); + + /** Bind a socket to a specific port. + \param port The port to listen for incoming connections on. + \return 0 on success, -1 on failure. + */ + int bind(int port); + + /** Start listening for incoming connections. + \param backlog number of pending connections that can be queued up at any + one time [Default: 1]. + \return 0 on success, -1 on failure. + */ + int listen(int backlog=1); + + /** Accept a new connection. + \param connection A TCPSocketConnection instance that will handle the incoming connection. + \return 0 on success, -1 on failure. + */ + int accept(TCPSocketConnection& connection); +}; + +#endif diff --git a/features/unsupported/net/lwip/Socket/UDPSocket.cpp b/features/unsupported/net/lwip/Socket/UDPSocket.cpp new file mode 100644 index 00000000000..baf845b203f --- /dev/null +++ b/features/unsupported/net/lwip/Socket/UDPSocket.cpp @@ -0,0 +1,94 @@ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#include "Socket/UDPSocket.h" + +#include + +using std::memset; + +UDPSocket::UDPSocket() { +} + +int UDPSocket::init(void) { + return init_socket(SOCK_DGRAM); +} + +// Server initialization +int UDPSocket::bind(int port) { + if (init_socket(SOCK_DGRAM) < 0) + return -1; + + struct sockaddr_in localHost; + std::memset(&localHost, 0, sizeof(localHost)); + + localHost.sin_family = AF_INET; + localHost.sin_port = htons(port); + localHost.sin_addr.s_addr = INADDR_ANY; + + if (lwip_bind(_sock_fd, (const struct sockaddr *) &localHost, sizeof(localHost)) < 0) { + close(); + return -1; + } + + return 0; +} + +int UDPSocket::join_multicast_group(const char* address) { + struct ip_mreq mreq; + + // Set up group address + mreq.imr_multiaddr.s_addr = inet_addr(address); + mreq.imr_interface.s_addr = htonl(INADDR_ANY); + + return set_option(IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)); +} + +int UDPSocket::set_broadcasting(bool broadcast) { + int option = (broadcast) ? (1) : (0); + return set_option(SOL_SOCKET, SO_BROADCAST, &option, sizeof(option)); +} + +// -1 if unsuccessful, else number of bytes written +int UDPSocket::sendTo(Endpoint &remote, char *packet, int length) { + if (_sock_fd < 0) + return -1; + + if (!_blocking) { + TimeInterval timeout(_timeout); + if (wait_writable(timeout) != 0) + return 0; + } + + return lwip_sendto(_sock_fd, packet, length, 0, (const struct sockaddr *) &remote._remoteHost, sizeof(remote._remoteHost)); +} + +// -1 if unsuccessful, else number of bytes received +int UDPSocket::receiveFrom(Endpoint &remote, char *buffer, int length) { + if (_sock_fd < 0) + return -1; + + if (!_blocking) { + TimeInterval timeout(_timeout); + if (wait_readable(timeout) != 0) + return 0; + } + remote.reset_address(); + socklen_t remoteHostLen = sizeof(remote._remoteHost); + return lwip_recvfrom(_sock_fd, buffer, length, 0, (struct sockaddr*) &remote._remoteHost, &remoteHostLen); +} diff --git a/features/unsupported/net/lwip/Socket/UDPSocket.h b/features/unsupported/net/lwip/Socket/UDPSocket.h new file mode 100644 index 00000000000..734b256be81 --- /dev/null +++ b/features/unsupported/net/lwip/Socket/UDPSocket.h @@ -0,0 +1,75 @@ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef UDPSOCKET_H +#define UDPSOCKET_H + +#include "Socket/Socket.h" +#include "Socket/Endpoint.h" + +/** +UDP Socket +*/ +class UDPSocket : public Socket { + +public: + /** Instantiate an UDP Socket. + */ + UDPSocket(); + + /** Init the UDP Client Socket without binding it to any specific port + \return 0 on success, -1 on failure. + */ + int init(void); + + /** Bind a UDP Server Socket to a specific port + \param port The port to listen for incoming connections on + \return 0 on success, -1 on failure. + */ + int bind(int port); + + /** Join the multicast group at the given address + \param address The address of the multicast group + \return 0 on success, -1 on failure. + */ + int join_multicast_group(const char* address); + + /** Set the socket in broadcasting mode + \return 0 on success, -1 on failure. + */ + int set_broadcasting(bool broadcast=true); + + /** Send a packet to a remote endpoint + \param remote The remote endpoint + \param packet The packet to be sent + \param length The length of the packet to be sent + \return the number of written bytes on success (>=0) or -1 on failure + */ + int sendTo(Endpoint &remote, char *packet, int length); + + /** Receive a packet from a remote endpoint + \param remote The remote endpoint + \param buffer The buffer for storing the incoming packet data. If a packet + is too long to fit in the supplied buffer, excess bytes are discarded + \param length The length of the buffer + \return the number of received bytes on success (>=0) or -1 on failure + */ + int receiveFrom(Endpoint &remote, char *buffer, int length); +}; + +#endif diff --git a/features/unsupported/net/lwip/lwip-sys/arch/cc.h b/features/unsupported/net/lwip/lwip-sys/arch/cc.h new file mode 100644 index 00000000000..c960cbe9d67 --- /dev/null +++ b/features/unsupported/net/lwip/lwip-sys/arch/cc.h @@ -0,0 +1,120 @@ +/* + * Copyright (c) 2001-2003 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef __CC_H__ +#define __CC_H__ + +#include +#include + +/* Types based on stdint.h */ +typedef uint8_t u8_t; +typedef int8_t s8_t; +typedef uint16_t u16_t; +typedef int16_t s16_t; +typedef uint32_t u32_t; +typedef int32_t s32_t; +typedef uintptr_t mem_ptr_t; + +/* Define (sn)printf formatters for these lwIP types */ +#define U16_F "hu" +#define S16_F "hd" +#define X16_F "hx" +#define U32_F "lu" +#define S32_F "ld" +#define X32_F "lx" +#define SZT_F "uz" + +/* ARM/LPC17xx is little endian only */ +#define BYTE_ORDER LITTLE_ENDIAN + +/* Use LWIP error codes */ +#define LWIP_PROVIDE_ERRNO + +#if defined(__arm__) && defined(__ARMCC_VERSION) + /* Keil uVision4 tools */ + #define PACK_STRUCT_BEGIN __packed + #define PACK_STRUCT_STRUCT + #define PACK_STRUCT_END + #define PACK_STRUCT_FIELD(fld) fld + #define ALIGNED(n) __align(n) +#elif defined (__IAR_SYSTEMS_ICC__) + /* IAR Embedded Workbench tools */ + #define PACK_STRUCT_BEGIN __packed + #define PACK_STRUCT_STRUCT + #define PACK_STRUCT_END + #define PACK_STRUCT_FIELD(fld) fld + #define IAR_STR(a) #a + #define ALIGNED(n) _Pragma(IAR_STR(data_alignment= ## n ##)) +#else + /* GCC tools (CodeSourcery) */ + #define PACK_STRUCT_BEGIN + #define PACK_STRUCT_STRUCT __attribute__ ((__packed__)) + #define PACK_STRUCT_END + #define PACK_STRUCT_FIELD(fld) fld + #define ALIGNED(n) __attribute__((aligned (n))) +#endif + +/* Provide Thumb-2 routines for GCC to improve performance */ +#if defined(TOOLCHAIN_GCC) && defined(__thumb2__) + #define MEMCPY(dst,src,len) thumb2_memcpy(dst,src,len) + #define LWIP_CHKSUM thumb2_checksum + /* Set algorithm to 0 so that unused lwip_standard_chksum function + doesn't generate compiler warning */ + #define LWIP_CHKSUM_ALGORITHM 0 + + void* thumb2_memcpy(void* pDest, const void* pSource, size_t length); + u16_t thumb2_checksum(void* pData, int length); +#else + /* Used with IP headers only */ + #define LWIP_CHKSUM_ALGORITHM 1 +#endif + + +#ifdef LWIP_DEBUG + +#include "stdio.h" + +void assert_printf(char *msg, int line, char *file); + +/* Plaform specific diagnostic output */ +#define LWIP_PLATFORM_DIAG(vars) printf vars +#define LWIP_PLATFORM_ASSERT(flag) { assert_printf((flag), __LINE__, __FILE__); } +#else +#define LWIP_PLATFORM_DIAG(msg) { ; } +#define LWIP_PLATFORM_ASSERT(flag) { ; } +#endif + +#include "cmsis.h" +#define LWIP_PLATFORM_HTONS(x) __REV16(x) +#define LWIP_PLATFORM_HTONL(x) __REV(x) + +#endif /* __CC_H__ */ diff --git a/features/unsupported/net/lwip/lwip-sys/arch/checksum.c b/features/unsupported/net/lwip/lwip-sys/arch/checksum.c new file mode 100644 index 00000000000..e97aef39d06 --- /dev/null +++ b/features/unsupported/net/lwip/lwip-sys/arch/checksum.c @@ -0,0 +1,126 @@ +/* Copyright (C) 2013 - Adam Green (https://github.com/adamgreen) + + Licensed under the Apache License, Version 2.0 (the "License"); + 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 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + 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. +*/ +#if defined(TOOLCHAIN_GCC) && defined(__thumb2__) + + +/* This is a hand written Thumb-2 assembly language version of the + algorithm 3 version of lwip_standard_chksum in lwIP's inet_chksum.c. It + performs the checksumming 32-bits at a time and even unrolls the loop to + perform two of these 32-bit adds per loop iteration. + + Returns: + 16-bit 1's complement summation (not inversed). + + NOTE: This function does return a uint16_t from the assembly language code + but is marked as void so that GCC doesn't issue warning because it + doesn't know about this low level return. +*/ +__attribute__((naked)) void /*uint16_t*/ thumb2_checksum(const void* pData, int length) +{ + __asm ( + ".syntax unified\n" + ".thumb\n" + + // Push non-volatile registers we use on stack. Push link register too to + // keep stack 8-byte aligned and allow single pop to restore and return. + " push {r4, lr}\n" + // Initialize sum, r2, to 0. + " movs r2, #0\n" + // Remember whether pData was at odd address in r3. This is used later to + // know if it needs to swap the result since the summation will be done at + // an offset of 1, rather than 0. + " ands r3, r0, #1\n" + // Need to 2-byte align? If not skip ahead. + " beq 1$\n" + // We can return if there are no bytes to sum. + " cbz r1, 9$\n" + + // 2-byte align. + // Place the first data byte in odd summation location since it needs to be + // swapped later. It's ok to overwrite r2 here as it only had a value of 0 + // up until now. Advance r0 pointer and decrement r1 length as we go. + " ldrb r2, [r0], #1\n" + " lsls r2, r2, #8\n" + " subs r1, r1, #1\n" + + // Need to 4-byte align? If not skip ahead. + "1$:\n" + " ands r4, r0, #3\n" + " beq 2$\n" + // Have more than 1 byte left to align? If not skip ahead to take care of + // trailing byte. + " cmp r1, #2\n" + " blt 7$\n" + + // 4-byte align. + " ldrh r4, [r0], #2\n" + " adds r2, r2, r4\n" + " subs r1, r1, #2\n" + + // Main summing loop which sums up data 2 words at a time. + // Make sure that we have more than 7 bytes left to sum. + "2$:\n" + " cmp r1, #8\n" + " blt 3$\n" + // Sum next two words. Applying previous upper 16-bit carry to + // lower 16-bits. + " ldr r4, [r0], #4\n" + " adds r2, r4\n" + " adc r2, r2, #0\n" + " ldr r4, [r0], #4\n" + " adds r2, r4\n" + " adc r2, r2, #0\n" + " subs r1, r1, #8\n" + " b 2$\n" + + // Sum up any remaining half-words. + "3$:\n" + // Make sure that we have more than 1 byte left to sum. + " cmp r1, #2\n" + " blt 7$\n" + // Sum up next half word, continue to apply carry. + " ldrh r4, [r0], #2\n" + " adds r2, r4\n" + " adc r2, r2, #0\n" + " subs r1, r1, #2\n" + " b 3$\n" + + // Handle trailing byte, if it exists + "7$:\n" + " cbz r1, 8$\n" + " ldrb r4, [r0]\n" + " adds r2, r4\n" + " adc r2, r2, #0\n" + + // Fold 32-bit checksum into 16-bit checksum. + "8$:\n" + " ubfx r4, r2, #16, #16\n" + " ubfx r2, r2, #0, #16\n" + " adds r2, r4\n" + " ubfx r4, r2, #16, #16\n" + " ubfx r2, r2, #0, #16\n" + " adds r2, r4\n" + + // Swap bytes if started at odd address + " cbz r3, 9$\n" + " rev16 r2, r2\n" + + // Return final sum. + "9$: mov r0, r2\n" + " pop {r4, pc}\n" + ); +} + +#endif diff --git a/features/unsupported/net/lwip/lwip-sys/arch/memcpy.c b/features/unsupported/net/lwip/lwip-sys/arch/memcpy.c new file mode 100644 index 00000000000..fefbcda3c2e --- /dev/null +++ b/features/unsupported/net/lwip/lwip-sys/arch/memcpy.c @@ -0,0 +1,59 @@ +/* Copyright (C) 2013 - Adam Green (https://github.com/adamgreen) + + Licensed under the Apache License, Version 2.0 (the "License"); + 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 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + 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. +*/ +#if defined(TOOLCHAIN_GCC) && defined(__thumb2__) + +#include + + +/* This is a hand written Thumb-2 assembly language version of the + standard C memcpy() function that can be used by the lwIP networking + stack to improve its performance. It copies 4 bytes at a time and + unrolls the loop to perform 4 of these copies per loop iteration. +*/ +__attribute__((naked)) void thumb2_memcpy(void* pDest, const void* pSource, size_t length) +{ + __asm ( + ".syntax unified\n" + ".thumb\n" + + // Copy 16 bytes at a time first. + " lsrs r3, r2, #4\n" + " beq.n 2$\n" + "1$: ldr r12, [r1], #4\n" + " str r12, [r0], #4\n" + " ldr r12, [r1], #4\n" + " str r12, [r0], #4\n" + " ldr r12, [r1], #4\n" + " str r12, [r0], #4\n" + " ldr r12, [r1], #4\n" + " str r12, [r0], #4\n" + " subs r3, #1\n" + " bne 1$\n" + + // Copy byte by byte for what is left. + "2$:\n" + " ands r3, r2, #0xf\n" + " beq.n 4$\n" + "3$: ldrb r12, [r1], #1\n" + " strb r12, [r0], #1\n" + " subs r3, #1\n" + " bne 3$\n" + + // Return to caller. + "4$: bx lr\n" + ); +} + +#endif diff --git a/features/unsupported/net/lwip/lwip-sys/arch/perf.h b/features/unsupported/net/lwip/lwip-sys/arch/perf.h new file mode 100644 index 00000000000..334d42af8cd --- /dev/null +++ b/features/unsupported/net/lwip/lwip-sys/arch/perf.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2001-2003 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef __PERF_H__ +#define __PERF_H__ + +#define PERF_START /* null definition */ +#define PERF_STOP(x) /* null definition */ + +#endif /* __PERF_H__ */ diff --git a/features/unsupported/net/lwip/lwip-sys/arch/sys_arch.c b/features/unsupported/net/lwip/lwip-sys/arch/sys_arch.c new file mode 100644 index 00000000000..25e2f14ef5d --- /dev/null +++ b/features/unsupported/net/lwip/lwip-sys/arch/sys_arch.c @@ -0,0 +1,465 @@ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +#include + +/* mbed includes */ +#include "mbed_error.h" +#include "mbed_interface.h" +#include "us_ticker_api.h" + +/* lwIP includes. */ +#include "lwip/opt.h" +#include "lwip/debug.h" +#include "lwip/def.h" +#include "lwip/sys.h" +#include "lwip/mem.h" + + #if NO_SYS==1 +#include "cmsis.h" + +/* Saved total time in ms since timer was enabled */ +static volatile u32_t systick_timems; + +/* Enable systick rate and interrupt */ +void SysTick_Init(void) { + if (SysTick_Config(SystemCoreClock / 1000)) { + while (1); /* Capture error */ + } +} + +/** \brief SysTick IRQ handler and timebase management + * + * This function keeps a timebase for the sysTick that can be + * used for other functions. It also calls an external function + * (SysTick_User) that must be defined outside this handler. + */ +void SysTick_Handler(void) { + systick_timems++; +} + +/* Delay for the specified number of milliSeconds */ +void osDelay(uint32_t ms) { + uint32_t to = ms + systick_timems; + while (to > systick_timems); +} + +/* Returns the current time in mS. This is needed for the LWIP timers */ +u32_t sys_now(void) { + return (u32_t) systick_timems; +} + +#else +/* CMSIS-RTOS implementation of the lwip operating system abstraction */ +#include "arch/sys_arch.h" + +/*---------------------------------------------------------------------------* + * Routine: sys_mbox_new + *---------------------------------------------------------------------------* + * Description: + * Creates a new mailbox + * Inputs: + * sys_mbox_t mbox -- Handle of mailbox + * int queue_sz -- Size of elements in the mailbox + * Outputs: + * err_t -- ERR_OK if message posted, else ERR_MEM + *---------------------------------------------------------------------------*/ +err_t sys_mbox_new(sys_mbox_t *mbox, int queue_sz) { + if (queue_sz > MB_SIZE) + error("sys_mbox_new size error\n"); + +#ifdef CMSIS_OS_RTX + memset(mbox->queue, 0, sizeof(mbox->queue)); + mbox->def.pool = mbox->queue; + mbox->def.queue_sz = queue_sz; +#endif + mbox->id = osMessageCreate(&mbox->def, NULL); + return (mbox->id == NULL) ? (ERR_MEM) : (ERR_OK); +} + +/*---------------------------------------------------------------------------* + * Routine: sys_mbox_free + *---------------------------------------------------------------------------* + * Description: + * Deallocates a mailbox. If there are messages still present in the + * mailbox when the mailbox is deallocated, it is an indication of a + * programming error in lwIP and the developer should be notified. + * Inputs: + * sys_mbox_t *mbox -- Handle of mailbox + *---------------------------------------------------------------------------*/ +void sys_mbox_free(sys_mbox_t *mbox) { + osEvent event = osMessageGet(mbox->id, 0); + if (event.status == osEventMessage) + error("sys_mbox_free error\n"); +} + +/*---------------------------------------------------------------------------* + * Routine: sys_mbox_post + *---------------------------------------------------------------------------* + * Description: + * Post the "msg" to the mailbox. + * Inputs: + * sys_mbox_t mbox -- Handle of mailbox + * void *msg -- Pointer to data to post + *---------------------------------------------------------------------------*/ +void sys_mbox_post(sys_mbox_t *mbox, void *msg) { + if (osMessagePut(mbox->id, (uint32_t)msg, osWaitForever) != osOK) + error("sys_mbox_post error\n"); +} + +/*---------------------------------------------------------------------------* + * Routine: sys_mbox_trypost + *---------------------------------------------------------------------------* + * Description: + * Try to post the "msg" to the mailbox. Returns immediately with + * error if cannot. + * Inputs: + * sys_mbox_t mbox -- Handle of mailbox + * void *msg -- Pointer to data to post + * Outputs: + * err_t -- ERR_OK if message posted, else ERR_MEM + * if not. + *---------------------------------------------------------------------------*/ +err_t sys_mbox_trypost(sys_mbox_t *mbox, void *msg) { + osStatus status = osMessagePut(mbox->id, (uint32_t)msg, 0); + return (status == osOK) ? (ERR_OK) : (ERR_MEM); +} + +/*---------------------------------------------------------------------------* + * Routine: sys_arch_mbox_fetch + *---------------------------------------------------------------------------* + * Description: + * Blocks the thread until a message arrives in the mailbox, but does + * not block the thread longer than "timeout" milliseconds (similar to + * the sys_arch_sem_wait() function). The "msg" argument is a result + * parameter that is set by the function (i.e., by doing "*msg = + * ptr"). The "msg" parameter maybe NULL to indicate that the message + * should be dropped. + * + * The return values are the same as for the sys_arch_sem_wait() function: + * Number of milliseconds spent waiting or SYS_ARCH_TIMEOUT if there was a + * timeout. + * + * Note that a function with a similar name, sys_mbox_fetch(), is + * implemented by lwIP. + * Inputs: + * sys_mbox_t mbox -- Handle of mailbox + * void **msg -- Pointer to pointer to msg received + * u32_t timeout -- Number of milliseconds until timeout + * Outputs: + * u32_t -- SYS_ARCH_TIMEOUT if timeout, else number + * of milliseconds until received. + *---------------------------------------------------------------------------*/ +u32_t sys_arch_mbox_fetch(sys_mbox_t *mbox, void **msg, u32_t timeout) { + u32_t start = us_ticker_read(); + + osEvent event = osMessageGet(mbox->id, (timeout != 0)?(timeout):(osWaitForever)); + if (event.status != osEventMessage) + return SYS_ARCH_TIMEOUT; + + *msg = (void *)event.value.v; + + return (us_ticker_read() - start) / 1000; +} + +/*---------------------------------------------------------------------------* + * Routine: sys_arch_mbox_tryfetch + *---------------------------------------------------------------------------* + * Description: + * Similar to sys_arch_mbox_fetch, but if message is not ready + * immediately, we'll return with SYS_MBOX_EMPTY. On success, 0 is + * returned. + * Inputs: + * sys_mbox_t mbox -- Handle of mailbox + * void **msg -- Pointer to pointer to msg received + * Outputs: + * u32_t -- SYS_MBOX_EMPTY if no messages. Otherwise, + * return ERR_OK. + *---------------------------------------------------------------------------*/ +u32_t sys_arch_mbox_tryfetch(sys_mbox_t *mbox, void **msg) { + osEvent event = osMessageGet(mbox->id, 0); + if (event.status != osEventMessage) + return SYS_MBOX_EMPTY; + + *msg = (void *)event.value.v; + + return ERR_OK; +} + +/*---------------------------------------------------------------------------* + * Routine: sys_sem_new + *---------------------------------------------------------------------------* + * Description: + * Creates and returns a new semaphore. The "ucCount" argument specifies + * the initial state of the semaphore. + * NOTE: Currently this routine only creates counts of 1 or 0 + * Inputs: + * sys_sem_t sem -- Handle of semaphore + * u8_t count -- Initial count of semaphore + * Outputs: + * err_t -- ERR_OK if semaphore created + *---------------------------------------------------------------------------*/ +err_t sys_sem_new(sys_sem_t *sem, u8_t count) { +#ifdef CMSIS_OS_RTX + memset(sem->data, 0, sizeof(uint32_t)*2); + sem->def.semaphore = sem->data; +#endif + sem->id = osSemaphoreCreate(&sem->def, count); + if (sem->id == NULL) + error("sys_sem_new create error\n"); + + return ERR_OK; +} + +/*---------------------------------------------------------------------------* + * Routine: sys_arch_sem_wait + *---------------------------------------------------------------------------* + * Description: + * Blocks the thread while waiting for the semaphore to be + * signaled. If the "timeout" argument is non-zero, the thread should + * only be blocked for the specified time (measured in + * milliseconds). + * + * If the timeout argument is non-zero, the return value is the number of + * milliseconds spent waiting for the semaphore to be signaled. If the + * semaphore wasn't signaled within the specified time, the return value is + * SYS_ARCH_TIMEOUT. If the thread didn't have to wait for the semaphore + * (i.e., it was already signaled), the function may return zero. + * + * Notice that lwIP implements a function with a similar name, + * sys_sem_wait(), that uses the sys_arch_sem_wait() function. + * Inputs: + * sys_sem_t sem -- Semaphore to wait on + * u32_t timeout -- Number of milliseconds until timeout + * Outputs: + * u32_t -- Time elapsed or SYS_ARCH_TIMEOUT. + *---------------------------------------------------------------------------*/ +u32_t sys_arch_sem_wait(sys_sem_t *sem, u32_t timeout) { + u32_t start = us_ticker_read(); + + if (osSemaphoreWait(sem->id, (timeout != 0)?(timeout):(osWaitForever)) < 1) + return SYS_ARCH_TIMEOUT; + + return (us_ticker_read() - start) / 1000; +} + +/*---------------------------------------------------------------------------* + * Routine: sys_sem_signal + *---------------------------------------------------------------------------* + * Description: + * Signals (releases) a semaphore + * Inputs: + * sys_sem_t sem -- Semaphore to signal + *---------------------------------------------------------------------------*/ +void sys_sem_signal(sys_sem_t *data) { + if (osSemaphoreRelease(data->id) != osOK) + mbed_die(); /* Can be called by ISR do not use printf */ +} + +/*---------------------------------------------------------------------------* + * Routine: sys_sem_free + *---------------------------------------------------------------------------* + * Description: + * Deallocates a semaphore + * Inputs: + * sys_sem_t sem -- Semaphore to free + *---------------------------------------------------------------------------*/ +void sys_sem_free(sys_sem_t *sem) {} + +/** Create a new mutex + * @param mutex pointer to the mutex to create + * @return a new mutex */ +err_t sys_mutex_new(sys_mutex_t *mutex) { +#ifdef CMSIS_OS_RTX +#if defined(__MBED_CMSIS_RTOS_CA9) || defined(__MBED_CMSIS_RTOS_CM) + memset(mutex->data, 0, sizeof(int32_t)*4); +#else + memset(mutex->data, 0, sizeof(int32_t)*3); +#endif + mutex->def.mutex = mutex->data; +#endif + mutex->id = osMutexCreate(&mutex->def); + if (mutex->id == NULL) + return ERR_MEM; + + return ERR_OK; +} + +/** Lock a mutex + * @param mutex the mutex to lock */ +void sys_mutex_lock(sys_mutex_t *mutex) { + if (osMutexWait(mutex->id, osWaitForever) != osOK) + error("sys_mutex_lock error\n"); +} + +/** Unlock a mutex + * @param mutex the mutex to unlock */ +void sys_mutex_unlock(sys_mutex_t *mutex) { + if (osMutexRelease(mutex->id) != osOK) + error("sys_mutex_unlock error\n"); +} + +/** Delete a mutex + * @param mutex the mutex to delete */ +void sys_mutex_free(sys_mutex_t *mutex) {} + +/*---------------------------------------------------------------------------* + * Routine: sys_init + *---------------------------------------------------------------------------* + * Description: + * Initialize sys arch + *---------------------------------------------------------------------------*/ +osMutexId lwip_sys_mutex; +osMutexDef(lwip_sys_mutex); + +void sys_init(void) { + us_ticker_read(); // Init sys tick + lwip_sys_mutex = osMutexCreate(osMutex(lwip_sys_mutex)); + if (lwip_sys_mutex == NULL) + error("sys_init error\n"); +} + +/*---------------------------------------------------------------------------* + * Routine: sys_jiffies + *---------------------------------------------------------------------------* + * Description: + * Used by PPP as a timestamp-ish value + *---------------------------------------------------------------------------*/ +u32_t sys_jiffies(void) { + static u32_t jiffies = 0; + jiffies += 1 + (us_ticker_read()/10000); + return jiffies; +} + +/*---------------------------------------------------------------------------* + * Routine: sys_arch_protect + *---------------------------------------------------------------------------* + * Description: + * This optional function does a "fast" critical region protection and + * returns the previous protection level. This function is only called + * during very short critical regions. An embedded system which supports + * ISR-based drivers might want to implement this function by disabling + * interrupts. Task-based systems might want to implement this by using + * a mutex or disabling tasking. This function should support recursive + * calls from the same task or interrupt. In other words, + * sys_arch_protect() could be called while already protected. In + * that case the return value indicates that it is already protected. + * + * sys_arch_protect() is only required if your port is supporting an + * operating system. + * Outputs: + * sys_prot_t -- Previous protection level (not used here) + *---------------------------------------------------------------------------*/ +sys_prot_t sys_arch_protect(void) { + if (osMutexWait(lwip_sys_mutex, osWaitForever) != osOK) + error("sys_arch_protect error\n"); + return (sys_prot_t) 1; +} + +/*---------------------------------------------------------------------------* + * Routine: sys_arch_unprotect + *---------------------------------------------------------------------------* + * Description: + * This optional function does a "fast" set of critical region + * protection to the value specified by pval. See the documentation for + * sys_arch_protect() for more information. This function is only + * required if your port is supporting an operating system. + * Inputs: + * sys_prot_t -- Previous protection level (not used here) + *---------------------------------------------------------------------------*/ +void sys_arch_unprotect(sys_prot_t p) { + if (osMutexRelease(lwip_sys_mutex) != osOK) + error("sys_arch_unprotect error\n"); +} + +u32_t sys_now(void) { + return us_ticker_read() / 1000; +} + +void sys_msleep(u32_t ms) { + osDelay(ms); +} + +// Keep a pool of thread structures +static int thread_pool_index = 0; +static sys_thread_data_t thread_pool[SYS_THREAD_POOL_N]; + +/*---------------------------------------------------------------------------* + * Routine: sys_thread_new + *---------------------------------------------------------------------------* + * Description: + * Starts a new thread with priority "prio" that will begin its + * execution in the function "thread()". The "arg" argument will be + * passed as an argument to the thread() function. The id of the new + * thread is returned. Both the id and the priority are system + * dependent. + * Inputs: + * char *name -- Name of thread + * void (*thread)(void *arg) -- Pointer to function to run. + * void *arg -- Argument passed into function + * int stacksize -- Required stack amount in bytes + * int priority -- Thread priority + * Outputs: + * sys_thread_t -- Pointer to thread handle. + *---------------------------------------------------------------------------*/ +sys_thread_t sys_thread_new(const char *pcName, + void (*thread)(void *arg), + void *arg, int stacksize, int priority) { + LWIP_DEBUGF(SYS_DEBUG, ("New Thread: %s\n", pcName)); + + if (thread_pool_index >= SYS_THREAD_POOL_N) + error("sys_thread_new number error\n"); + sys_thread_t t = (sys_thread_t)&thread_pool[thread_pool_index]; + thread_pool_index++; + +#ifdef CMSIS_OS_RTX + t->def.pthread = (os_pthread)thread; + t->def.tpriority = (osPriority)priority; + t->def.stacksize = stacksize; + t->def.stack_pointer = (uint32_t*)malloc(stacksize); + if (t->def.stack_pointer == NULL) { + error("Error allocating the stack memory"); + } +#endif + t->id = osThreadCreate(&t->def, arg); + if (t->id == NULL) + error("sys_thread_new create error\n"); + + return t; +} + +#endif + +#ifdef LWIP_DEBUG + +/** \brief Displays an error message on assertion + + This function will display an error message on an assertion + to the debug output. + + \param[in] msg Error message to display + \param[in] line Line number in file with error + \param[in] file Filename with error + */ +void assert_printf(char *msg, int line, char *file) { + if (msg) + error("%s:%d in file %s\n", msg, line, file); + else + error("LWIP ASSERT\n"); +} + +#endif /* LWIP_DEBUG */ diff --git a/features/unsupported/net/lwip/lwip-sys/arch/sys_arch.h b/features/unsupported/net/lwip/lwip-sys/arch/sys_arch.h new file mode 100644 index 00000000000..7678e24eab1 --- /dev/null +++ b/features/unsupported/net/lwip/lwip-sys/arch/sys_arch.h @@ -0,0 +1,124 @@ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +#ifndef __ARCH_SYS_ARCH_H__ +#define __ARCH_SYS_ARCH_H__ + +#include "lwip/opt.h" + +#if NO_SYS == 0 +#include "cmsis_os.h" + +// === SEMAPHORE === +typedef struct { + osSemaphoreId id; + osSemaphoreDef_t def; +#ifdef CMSIS_OS_RTX + uint32_t data[2]; +#endif +} sys_sem_t; + +#define sys_sem_valid(x) (((*x).id == NULL) ? 0 : 1) +#define sys_sem_set_invalid(x) ( (*x).id = NULL) + +// === MUTEX === +typedef struct { + osMutexId id; + osMutexDef_t def; +#ifdef CMSIS_OS_RTX +#if defined(__MBED_CMSIS_RTOS_CA9) || defined(__MBED_CMSIS_RTOS_CM) + int32_t data[4]; +#else + int32_t data[3]; +#endif +#endif +} sys_mutex_t; + +// === MAIL BOX === +#define MB_SIZE 8 + +typedef struct { + osMessageQId id; + osMessageQDef_t def; +#ifdef CMSIS_OS_RTX + uint32_t queue[4+MB_SIZE]; /* The +4 is required for RTX OS_MCB overhead. */ +#endif +} sys_mbox_t; + +#define SYS_MBOX_NULL ((uint32_t) NULL) +#define sys_mbox_valid(x) (((*x).id == NULL) ? 0 : 1 ) +#define sys_mbox_set_invalid(x) ( (*x).id = NULL ) + +#if ((DEFAULT_RAW_RECVMBOX_SIZE) > (MB_SIZE)) || \ + ((DEFAULT_UDP_RECVMBOX_SIZE) > (MB_SIZE)) || \ + ((DEFAULT_TCP_RECVMBOX_SIZE) > (MB_SIZE)) || \ + ((DEFAULT_ACCEPTMBOX_SIZE) > (MB_SIZE)) || \ + ((TCPIP_MBOX_SIZE) > (MB_SIZE)) +# error Mailbox size not supported +#endif + +// === THREAD === +typedef struct { + osThreadId id; + osThreadDef_t def; +} sys_thread_data_t; +typedef sys_thread_data_t* sys_thread_t; + +#define SYS_THREAD_POOL_N 6 +#define SYS_DEFAULT_THREAD_STACK_DEPTH DEFAULT_STACK_SIZE + +// === PROTECTION === +typedef int sys_prot_t; + +#else +#ifdef __cplusplus +extern "C" { +#endif + +/** \brief Init systick to 1ms rate + * + * This init the systick to 1ms rate. This function is only used in standalone + * systems. + */ +void SysTick_Init(void); + + +/** \brief Get the current systick time in milliSeconds + * + * Returns the current systick time in milliSeconds. This function is only + * used in standalone systems. + * + * /returns current systick time in milliSeconds + */ +uint32_t SysTick_GetMS(void); + +/** \brief Delay for the specified number of milliSeconds + * + * For standalone systems. This function will block for the specified + * number of milliSconds. For RTOS based systems, this function will delay + * the task by the specified number of milliSeconds. + * + * \param[in] ms Time in milliSeconds to delay + */ +void osDelay(uint32_t ms); + +#ifdef __cplusplus +} +#endif +#endif + +#endif /* __ARCH_SYS_ARCH_H__ */ diff --git a/features/unsupported/net/lwip/lwip/COPYING b/features/unsupported/net/lwip/lwip/COPYING new file mode 100644 index 00000000000..e23898b5e8f --- /dev/null +++ b/features/unsupported/net/lwip/lwip/COPYING @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2001, 2002 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ + + diff --git a/features/unsupported/net/lwip/lwip/api/api_lib.c b/features/unsupported/net/lwip/lwip/api/api_lib.c new file mode 100644 index 00000000000..b1a9e5253d8 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/api/api_lib.c @@ -0,0 +1,740 @@ +/** + * @file + * Sequential API External module + * + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ + +/* This is the part of the API that is linked with + the application */ + +#include "lwip/opt.h" + +#if LWIP_NETCONN /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/api.h" +#include "lwip/tcpip.h" +#include "lwip/memp.h" + +#include "lwip/ip.h" +#include "lwip/raw.h" +#include "lwip/udp.h" +#include "lwip/tcp.h" + +#include + +/** + * Create a new netconn (of a specific type) that has a callback function. + * The corresponding pcb is also created. + * + * @param t the type of 'connection' to create (@see enum netconn_type) + * @param proto the IP protocol for RAW IP pcbs + * @param callback a function to call on status changes (RX available, TX'ed) + * @return a newly allocated struct netconn or + * NULL on memory error + */ +struct netconn* +netconn_new_with_proto_and_callback(enum netconn_type t, u8_t proto, netconn_callback callback) +{ + struct netconn *conn; + struct api_msg msg; + + conn = netconn_alloc(t, callback); + if (conn != NULL) { + msg.function = do_newconn; + msg.msg.msg.n.proto = proto; + msg.msg.conn = conn; + if (TCPIP_APIMSG(&msg) != ERR_OK) { + LWIP_ASSERT("freeing conn without freeing pcb", conn->pcb.tcp == NULL); + LWIP_ASSERT("conn has no op_completed", sys_sem_valid(&conn->op_completed)); + LWIP_ASSERT("conn has no recvmbox", sys_mbox_valid(&conn->recvmbox)); +#if LWIP_TCP + LWIP_ASSERT("conn->acceptmbox shouldn't exist", !sys_mbox_valid(&conn->acceptmbox)); +#endif /* LWIP_TCP */ + sys_sem_free(&conn->op_completed); + sys_mbox_free(&conn->recvmbox); + memp_free(MEMP_NETCONN, conn); + return NULL; + } + } + return conn; +} + +/** + * Close a netconn 'connection' and free its resources. + * UDP and RAW connection are completely closed, TCP pcbs might still be in a waitstate + * after this returns. + * + * @param conn the netconn to delete + * @return ERR_OK if the connection was deleted + */ +err_t +netconn_delete(struct netconn *conn) +{ + struct api_msg msg; + + /* No ASSERT here because possible to get a (conn == NULL) if we got an accept error */ + if (conn == NULL) { + return ERR_OK; + } + + msg.function = do_delconn; + msg.msg.conn = conn; + tcpip_apimsg(&msg); + + netconn_free(conn); + + /* don't care for return value of do_delconn since it only calls void functions */ + + return ERR_OK; +} + +/** + * Get the local or remote IP address and port of a netconn. + * For RAW netconns, this returns the protocol instead of a port! + * + * @param conn the netconn to query + * @param addr a pointer to which to save the IP address + * @param port a pointer to which to save the port (or protocol for RAW) + * @param local 1 to get the local IP address, 0 to get the remote one + * @return ERR_CONN for invalid connections + * ERR_OK if the information was retrieved + */ +err_t +netconn_getaddr(struct netconn *conn, ip_addr_t *addr, u16_t *port, u8_t local) +{ + struct api_msg msg; + err_t err; + + LWIP_ERROR("netconn_getaddr: invalid conn", (conn != NULL), return ERR_ARG;); + LWIP_ERROR("netconn_getaddr: invalid addr", (addr != NULL), return ERR_ARG;); + LWIP_ERROR("netconn_getaddr: invalid port", (port != NULL), return ERR_ARG;); + + msg.function = do_getaddr; + msg.msg.conn = conn; + msg.msg.msg.ad.ipaddr = addr; + msg.msg.msg.ad.port = port; + msg.msg.msg.ad.local = local; + err = TCPIP_APIMSG(&msg); + + NETCONN_SET_SAFE_ERR(conn, err); + return err; +} + +/** + * Bind a netconn to a specific local IP address and port. + * Binding one netconn twice might not always be checked correctly! + * + * @param conn the netconn to bind + * @param addr the local IP address to bind the netconn to (use IP_ADDR_ANY + * to bind to all addresses) + * @param port the local port to bind the netconn to (not used for RAW) + * @return ERR_OK if bound, any other err_t on failure + */ +err_t +netconn_bind(struct netconn *conn, ip_addr_t *addr, u16_t port) +{ + struct api_msg msg; + err_t err; + + LWIP_ERROR("netconn_bind: invalid conn", (conn != NULL), return ERR_ARG;); + + msg.function = do_bind; + msg.msg.conn = conn; + msg.msg.msg.bc.ipaddr = addr; + msg.msg.msg.bc.port = port; + err = TCPIP_APIMSG(&msg); + + NETCONN_SET_SAFE_ERR(conn, err); + return err; +} + +/** + * Connect a netconn to a specific remote IP address and port. + * + * @param conn the netconn to connect + * @param addr the remote IP address to connect to + * @param port the remote port to connect to (no used for RAW) + * @return ERR_OK if connected, return value of tcp_/udp_/raw_connect otherwise + */ +err_t +netconn_connect(struct netconn *conn, ip_addr_t *addr, u16_t port) +{ + struct api_msg msg; + err_t err; + + LWIP_ERROR("netconn_connect: invalid conn", (conn != NULL), return ERR_ARG;); + + msg.function = do_connect; + msg.msg.conn = conn; + msg.msg.msg.bc.ipaddr = addr; + msg.msg.msg.bc.port = port; + /* This is the only function which need to not block tcpip_thread */ + err = tcpip_apimsg(&msg); + + NETCONN_SET_SAFE_ERR(conn, err); + return err; +} + +/** + * Disconnect a netconn from its current peer (only valid for UDP netconns). + * + * @param conn the netconn to disconnect + * @return TODO: return value is not set here... + */ +err_t +netconn_disconnect(struct netconn *conn) +{ + struct api_msg msg; + err_t err; + + LWIP_ERROR("netconn_disconnect: invalid conn", (conn != NULL), return ERR_ARG;); + + msg.function = do_disconnect; + msg.msg.conn = conn; + err = TCPIP_APIMSG(&msg); + + NETCONN_SET_SAFE_ERR(conn, err); + return err; +} + +/** + * Set a TCP netconn into listen mode + * + * @param conn the tcp netconn to set to listen mode + * @param backlog the listen backlog, only used if TCP_LISTEN_BACKLOG==1 + * @return ERR_OK if the netconn was set to listen (UDP and RAW netconns + * don't return any error (yet?)) + */ +err_t +netconn_listen_with_backlog(struct netconn *conn, u8_t backlog) +{ +#if LWIP_TCP + struct api_msg msg; + err_t err; + + /* This does no harm. If TCP_LISTEN_BACKLOG is off, backlog is unused. */ + LWIP_UNUSED_ARG(backlog); + + LWIP_ERROR("netconn_listen: invalid conn", (conn != NULL), return ERR_ARG;); + + msg.function = do_listen; + msg.msg.conn = conn; +#if TCP_LISTEN_BACKLOG + msg.msg.msg.lb.backlog = backlog; +#endif /* TCP_LISTEN_BACKLOG */ + err = TCPIP_APIMSG(&msg); + + NETCONN_SET_SAFE_ERR(conn, err); + return err; +#else /* LWIP_TCP */ + LWIP_UNUSED_ARG(conn); + LWIP_UNUSED_ARG(backlog); + return ERR_ARG; +#endif /* LWIP_TCP */ +} + +/** + * Accept a new connection on a TCP listening netconn. + * + * @param conn the TCP listen netconn + * @param new_conn pointer where the new connection is stored + * @return ERR_OK if a new connection has been received or an error + * code otherwise + */ +err_t +netconn_accept(struct netconn *conn, struct netconn **new_conn) +{ +#if LWIP_TCP + struct netconn *newconn; + err_t err; +#if TCP_LISTEN_BACKLOG + struct api_msg msg; +#endif /* TCP_LISTEN_BACKLOG */ + + LWIP_ERROR("netconn_accept: invalid pointer", (new_conn != NULL), return ERR_ARG;); + *new_conn = NULL; + LWIP_ERROR("netconn_accept: invalid conn", (conn != NULL), return ERR_ARG;); + LWIP_ERROR("netconn_accept: invalid acceptmbox", sys_mbox_valid(&conn->acceptmbox), return ERR_ARG;); + + err = conn->last_err; + if (ERR_IS_FATAL(err)) { + /* don't recv on fatal errors: this might block the application task + waiting on acceptmbox forever! */ + return err; + } + +#if LWIP_SO_RCVTIMEO + if (sys_arch_mbox_fetch(&conn->acceptmbox, (void **)&newconn, conn->recv_timeout) == SYS_ARCH_TIMEOUT) { + NETCONN_SET_SAFE_ERR(conn, ERR_TIMEOUT); + return ERR_TIMEOUT; + } +#else + sys_arch_mbox_fetch(&conn->acceptmbox, (void **)&newconn, 0); +#endif /* LWIP_SO_RCVTIMEO*/ + /* Register event with callback */ + API_EVENT(conn, NETCONN_EVT_RCVMINUS, 0); + + if (newconn == NULL) { + /* connection has been aborted */ + NETCONN_SET_SAFE_ERR(conn, ERR_ABRT); + return ERR_ABRT; + } +#if TCP_LISTEN_BACKLOG + /* Let the stack know that we have accepted the connection. */ + msg.function = do_recv; + msg.msg.conn = conn; + /* don't care for the return value of do_recv */ + TCPIP_APIMSG(&msg); +#endif /* TCP_LISTEN_BACKLOG */ + + *new_conn = newconn; + /* don't set conn->last_err: it's only ERR_OK, anyway */ + return ERR_OK; +#else /* LWIP_TCP */ + LWIP_UNUSED_ARG(conn); + LWIP_UNUSED_ARG(new_conn); + return ERR_ARG; +#endif /* LWIP_TCP */ +} + +/** + * Receive data: actual implementation that doesn't care whether pbuf or netbuf + * is received + * + * @param conn the netconn from which to receive data + * @param new_buf pointer where a new pbuf/netbuf is stored when received data + * @return ERR_OK if data has been received, an error code otherwise (timeout, + * memory error or another error) + */ +static err_t +netconn_recv_data(struct netconn *conn, void **new_buf) +{ + void *buf = NULL; + u16_t len; + err_t err; +#if LWIP_TCP + struct api_msg msg; +#endif /* LWIP_TCP */ + + LWIP_ERROR("netconn_recv: invalid pointer", (new_buf != NULL), return ERR_ARG;); + *new_buf = NULL; + LWIP_ERROR("netconn_recv: invalid conn", (conn != NULL), return ERR_ARG;); + LWIP_ERROR("netconn_accept: invalid recvmbox", sys_mbox_valid(&conn->recvmbox), return ERR_CONN;); + + err = conn->last_err; + if (ERR_IS_FATAL(err)) { + /* don't recv on fatal errors: this might block the application task + waiting on recvmbox forever! */ + /* @todo: this does not allow us to fetch data that has been put into recvmbox + before the fatal error occurred - is that a problem? */ + return err; + } + +#if LWIP_SO_RCVTIMEO + if (sys_arch_mbox_fetch(&conn->recvmbox, &buf, conn->recv_timeout) == SYS_ARCH_TIMEOUT) { + NETCONN_SET_SAFE_ERR(conn, ERR_TIMEOUT); + return ERR_TIMEOUT; + } +#else + sys_arch_mbox_fetch(&conn->recvmbox, &buf, 0); +#endif /* LWIP_SO_RCVTIMEO*/ + +#if LWIP_TCP + if (conn->type == NETCONN_TCP) { + if (!netconn_get_noautorecved(conn) || (buf == NULL)) { + /* Let the stack know that we have taken the data. */ + /* TODO: Speedup: Don't block and wait for the answer here + (to prevent multiple thread-switches). */ + msg.function = do_recv; + msg.msg.conn = conn; + if (buf != NULL) { + msg.msg.msg.r.len = ((struct pbuf *)buf)->tot_len; + } else { + msg.msg.msg.r.len = 1; + } + /* don't care for the return value of do_recv */ + TCPIP_APIMSG(&msg); + } + + /* If we are closed, we indicate that we no longer wish to use the socket */ + if (buf == NULL) { + API_EVENT(conn, NETCONN_EVT_RCVMINUS, 0); + /* Avoid to lose any previous error code */ + NETCONN_SET_SAFE_ERR(conn, ERR_CLSD); + return ERR_CLSD; + } + len = ((struct pbuf *)buf)->tot_len; + } +#endif /* LWIP_TCP */ +#if LWIP_TCP && (LWIP_UDP || LWIP_RAW) + else +#endif /* LWIP_TCP && (LWIP_UDP || LWIP_RAW) */ +#if (LWIP_UDP || LWIP_RAW) + { + LWIP_ASSERT("buf != NULL", buf != NULL); + len = netbuf_len((struct netbuf *)buf); + } +#endif /* (LWIP_UDP || LWIP_RAW) */ + +#if LWIP_SO_RCVBUF + SYS_ARCH_DEC(conn->recv_avail, len); +#endif /* LWIP_SO_RCVBUF */ + /* Register event with callback */ + API_EVENT(conn, NETCONN_EVT_RCVMINUS, len); + + LWIP_DEBUGF(API_LIB_DEBUG, ("netconn_recv_data: received %p, len=%"U16_F"\n", buf, len)); + + *new_buf = buf; + /* don't set conn->last_err: it's only ERR_OK, anyway */ + return ERR_OK; +} + +/** + * Receive data (in form of a pbuf) from a TCP netconn + * + * @param conn the netconn from which to receive data + * @param new_buf pointer where a new pbuf is stored when received data + * @return ERR_OK if data has been received, an error code otherwise (timeout, + * memory error or another error) + * ERR_ARG if conn is not a TCP netconn + */ +err_t +netconn_recv_tcp_pbuf(struct netconn *conn, struct pbuf **new_buf) +{ + LWIP_ERROR("netconn_recv: invalid conn", (conn != NULL) && + netconn_type(conn) == NETCONN_TCP, return ERR_ARG;); + + return netconn_recv_data(conn, (void **)new_buf); +} + +/** + * Receive data (in form of a netbuf containing a packet buffer) from a netconn + * + * @param conn the netconn from which to receive data + * @param new_buf pointer where a new netbuf is stored when received data + * @return ERR_OK if data has been received, an error code otherwise (timeout, + * memory error or another error) + */ +err_t +netconn_recv(struct netconn *conn, struct netbuf **new_buf) +{ +#if LWIP_TCP + struct netbuf *buf = NULL; + err_t err; +#endif /* LWIP_TCP */ + + LWIP_ERROR("netconn_recv: invalid pointer", (new_buf != NULL), return ERR_ARG;); + *new_buf = NULL; + LWIP_ERROR("netconn_recv: invalid conn", (conn != NULL), return ERR_ARG;); + LWIP_ERROR("netconn_accept: invalid recvmbox", sys_mbox_valid(&conn->recvmbox), return ERR_CONN;); + +#if LWIP_TCP + if (conn->type == NETCONN_TCP) { + struct pbuf *p = NULL; + /* This is not a listening netconn, since recvmbox is set */ + + buf = (struct netbuf *)memp_malloc(MEMP_NETBUF); + if (buf == NULL) { + NETCONN_SET_SAFE_ERR(conn, ERR_MEM); + return ERR_MEM; + } + + err = netconn_recv_data(conn, (void **)&p); + if (err != ERR_OK) { + memp_free(MEMP_NETBUF, buf); + return err; + } + LWIP_ASSERT("p != NULL", p != NULL); + + buf->p = p; + buf->ptr = p; + buf->port = 0; + ip_addr_set_any(&buf->addr); + *new_buf = buf; + /* don't set conn->last_err: it's only ERR_OK, anyway */ + return ERR_OK; + } else +#endif /* LWIP_TCP */ + { +#if (LWIP_UDP || LWIP_RAW) + return netconn_recv_data(conn, (void **)new_buf); +#endif /* (LWIP_UDP || LWIP_RAW) */ + } +} + +/** + * TCP: update the receive window: by calling this, the application + * tells the stack that it has processed data and is able to accept + * new data. + * ATTENTION: use with care, this is mainly used for sockets! + * Can only be used when calling netconn_set_noautorecved(conn, 1) before. + * + * @param conn the netconn for which to update the receive window + * @param length amount of data processed (ATTENTION: this must be accurate!) + */ +void +netconn_recved(struct netconn *conn, u32_t length) +{ +#if LWIP_TCP + if ((conn != NULL) && (conn->type == NETCONN_TCP) && + (netconn_get_noautorecved(conn))) { + struct api_msg msg; + /* Let the stack know that we have taken the data. */ + /* TODO: Speedup: Don't block and wait for the answer here + (to prevent multiple thread-switches). */ + msg.function = do_recv; + msg.msg.conn = conn; + msg.msg.msg.r.len = length; + /* don't care for the return value of do_recv */ + TCPIP_APIMSG(&msg); + } +#else /* LWIP_TCP */ + LWIP_UNUSED_ARG(conn); + LWIP_UNUSED_ARG(length); +#endif /* LWIP_TCP */ +} + +/** + * Send data (in form of a netbuf) to a specific remote IP address and port. + * Only to be used for UDP and RAW netconns (not TCP). + * + * @param conn the netconn over which to send data + * @param buf a netbuf containing the data to send + * @param addr the remote IP address to which to send the data + * @param port the remote port to which to send the data + * @return ERR_OK if data was sent, any other err_t on error + */ +err_t +netconn_sendto(struct netconn *conn, struct netbuf *buf, ip_addr_t *addr, u16_t port) +{ + if (buf != NULL) { + ip_addr_set(&buf->addr, addr); + buf->port = port; + return netconn_send(conn, buf); + } + return ERR_VAL; +} + +/** + * Send data over a UDP or RAW netconn (that is already connected). + * + * @param conn the UDP or RAW netconn over which to send data + * @param buf a netbuf containing the data to send + * @return ERR_OK if data was sent, any other err_t on error + */ +err_t +netconn_send(struct netconn *conn, struct netbuf *buf) +{ + struct api_msg msg; + err_t err; + + LWIP_ERROR("netconn_send: invalid conn", (conn != NULL), return ERR_ARG;); + + LWIP_DEBUGF(API_LIB_DEBUG, ("netconn_send: sending %"U16_F" bytes\n", buf->p->tot_len)); + msg.function = do_send; + msg.msg.conn = conn; + msg.msg.msg.b = buf; + err = TCPIP_APIMSG(&msg); + + NETCONN_SET_SAFE_ERR(conn, err); + return err; +} + +/** + * Send data over a TCP netconn. + * + * @param conn the TCP netconn over which to send data + * @param dataptr pointer to the application buffer that contains the data to send + * @param size size of the application data to send + * @param apiflags combination of following flags : + * - NETCONN_COPY: data will be copied into memory belonging to the stack + * - NETCONN_MORE: for TCP connection, PSH flag will be set on last segment sent + * - NETCONN_DONTBLOCK: only write the data if all dat can be written at once + * @return ERR_OK if data was sent, any other err_t on error + */ +err_t +netconn_write(struct netconn *conn, const void *dataptr, size_t size, u8_t apiflags) +{ + struct api_msg msg; + err_t err; + + LWIP_ERROR("netconn_write: invalid conn", (conn != NULL), return ERR_ARG;); + LWIP_ERROR("netconn_write: invalid conn->type", (conn->type == NETCONN_TCP), return ERR_VAL;); + if (size == 0) { + return ERR_OK; + } + + /* @todo: for non-blocking write, check if 'size' would ever fit into + snd_queue or snd_buf */ + msg.function = do_write; + msg.msg.conn = conn; + msg.msg.msg.w.dataptr = dataptr; + msg.msg.msg.w.apiflags = apiflags; + msg.msg.msg.w.len = size; + /* For locking the core: this _can_ be delayed on low memory/low send buffer, + but if it is, this is done inside api_msg.c:do_write(), so we can use the + non-blocking version here. */ + err = TCPIP_APIMSG(&msg); + + NETCONN_SET_SAFE_ERR(conn, err); + return err; +} + +/** + * Close ot shutdown a TCP netconn (doesn't delete it). + * + * @param conn the TCP netconn to close or shutdown + * @param how fully close or only shutdown one side? + * @return ERR_OK if the netconn was closed, any other err_t on error + */ +static err_t +netconn_close_shutdown(struct netconn *conn, u8_t how) +{ + struct api_msg msg; + err_t err; + + LWIP_ERROR("netconn_close: invalid conn", (conn != NULL), return ERR_ARG;); + + msg.function = do_close; + msg.msg.conn = conn; + /* shutting down both ends is the same as closing */ + msg.msg.msg.sd.shut = how; + /* because of the LWIP_TCPIP_CORE_LOCKING implementation of do_close, + don't use TCPIP_APIMSG here */ + err = tcpip_apimsg(&msg); + + NETCONN_SET_SAFE_ERR(conn, err); + return err; +} + +/** + * Close a TCP netconn (doesn't delete it). + * + * @param conn the TCP netconn to close + * @return ERR_OK if the netconn was closed, any other err_t on error + */ +err_t +netconn_close(struct netconn *conn) +{ + /* shutting down both ends is the same as closing */ + return netconn_close_shutdown(conn, NETCONN_SHUT_RDWR); +} + +/** + * Shut down one or both sides of a TCP netconn (doesn't delete it). + * + * @param conn the TCP netconn to shut down + * @return ERR_OK if the netconn was closed, any other err_t on error + */ +err_t +netconn_shutdown(struct netconn *conn, u8_t shut_rx, u8_t shut_tx) +{ + return netconn_close_shutdown(conn, (shut_rx ? NETCONN_SHUT_RD : 0) | (shut_tx ? NETCONN_SHUT_WR : 0)); +} + +#if LWIP_IGMP +/** + * Join multicast groups for UDP netconns. + * + * @param conn the UDP netconn for which to change multicast addresses + * @param multiaddr IP address of the multicast group to join or leave + * @param netif_addr the IP address of the network interface on which to send + * the igmp message + * @param join_or_leave flag whether to send a join- or leave-message + * @return ERR_OK if the action was taken, any err_t on error + */ +err_t +netconn_join_leave_group(struct netconn *conn, + ip_addr_t *multiaddr, + ip_addr_t *netif_addr, + enum netconn_igmp join_or_leave) +{ + struct api_msg msg; + err_t err; + + LWIP_ERROR("netconn_join_leave_group: invalid conn", (conn != NULL), return ERR_ARG;); + + msg.function = do_join_leave_group; + msg.msg.conn = conn; + msg.msg.msg.jl.multiaddr = multiaddr; + msg.msg.msg.jl.netif_addr = netif_addr; + msg.msg.msg.jl.join_or_leave = join_or_leave; + err = TCPIP_APIMSG(&msg); + + NETCONN_SET_SAFE_ERR(conn, err); + return err; +} +#endif /* LWIP_IGMP */ + +#if LWIP_DNS +/** + * Execute a DNS query, only one IP address is returned + * + * @param name a string representation of the DNS host name to query + * @param addr a preallocated ip_addr_t where to store the resolved IP address + * @return ERR_OK: resolving succeeded + * ERR_MEM: memory error, try again later + * ERR_ARG: dns client not initialized or invalid hostname + * ERR_VAL: dns server response was invalid + */ +err_t +netconn_gethostbyname(const char *name, ip_addr_t *addr) +{ + struct dns_api_msg msg; + err_t err; + sys_sem_t sem; + + LWIP_ERROR("netconn_gethostbyname: invalid name", (name != NULL), return ERR_ARG;); + LWIP_ERROR("netconn_gethostbyname: invalid addr", (addr != NULL), return ERR_ARG;); + + err = sys_sem_new(&sem, 0); + if (err != ERR_OK) { + return err; + } + + msg.name = name; + msg.addr = addr; + msg.err = &err; + msg.sem = &sem; + + tcpip_callback(do_gethostbyname, &msg); + sys_sem_wait(&sem); + sys_sem_free(&sem); + + return err; +} +#endif /* LWIP_DNS*/ + +#endif /* LWIP_NETCONN */ diff --git a/features/unsupported/net/lwip/lwip/api/api_msg.c b/features/unsupported/net/lwip/lwip/api/api_msg.c new file mode 100644 index 00000000000..448f96dda0a --- /dev/null +++ b/features/unsupported/net/lwip/lwip/api/api_msg.c @@ -0,0 +1,1535 @@ +/** + * @file + * Sequential API Internal module + * + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ + +#include "lwip/opt.h" + +#if LWIP_NETCONN /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/api_msg.h" + +#include "lwip/ip.h" +#include "lwip/udp.h" +#include "lwip/tcp.h" +#include "lwip/raw.h" + +#include "lwip/memp.h" +#include "lwip/tcpip.h" +#include "lwip/igmp.h" +#include "lwip/dns.h" + +#include + +#define SET_NONBLOCKING_CONNECT(conn, val) do { if(val) { \ + (conn)->flags |= NETCONN_FLAG_IN_NONBLOCKING_CONNECT; \ +} else { \ + (conn)->flags &= ~ NETCONN_FLAG_IN_NONBLOCKING_CONNECT; }} while(0) +#define IN_NONBLOCKING_CONNECT(conn) (((conn)->flags & NETCONN_FLAG_IN_NONBLOCKING_CONNECT) != 0) + +/* forward declarations */ +#if LWIP_TCP +static err_t do_writemore(struct netconn *conn); +static void do_close_internal(struct netconn *conn); +#endif + +#if LWIP_RAW +/** + * Receive callback function for RAW netconns. + * Doesn't 'eat' the packet, only references it and sends it to + * conn->recvmbox + * + * @see raw.h (struct raw_pcb.recv) for parameters and return value + */ +static u8_t +recv_raw(void *arg, struct raw_pcb *pcb, struct pbuf *p, + ip_addr_t *addr) +{ + struct pbuf *q; + struct netbuf *buf; + struct netconn *conn; + + LWIP_UNUSED_ARG(addr); + conn = (struct netconn *)arg; + + if ((conn != NULL) && sys_mbox_valid(&conn->recvmbox)) { +#if LWIP_SO_RCVBUF + int recv_avail; + SYS_ARCH_GET(conn->recv_avail, recv_avail); + if ((recv_avail + (int)(p->tot_len)) > conn->recv_bufsize) { + return 0; + } +#endif /* LWIP_SO_RCVBUF */ + /* copy the whole packet into new pbufs */ + q = pbuf_alloc(PBUF_RAW, p->tot_len, PBUF_RAM); + if(q != NULL) { + if (pbuf_copy(q, p) != ERR_OK) { + pbuf_free(q); + q = NULL; + } + } + + if (q != NULL) { + u16_t len; + buf = (struct netbuf *)memp_malloc(MEMP_NETBUF); + if (buf == NULL) { + pbuf_free(q); + return 0; + } + + buf->p = q; + buf->ptr = q; + ip_addr_copy(buf->addr, *ip_current_src_addr()); + buf->port = pcb->protocol; + + len = q->tot_len; + if (sys_mbox_trypost(&conn->recvmbox, buf) != ERR_OK) { + netbuf_delete(buf); + return 0; + } else { +#if LWIP_SO_RCVBUF + SYS_ARCH_INC(conn->recv_avail, len); +#endif /* LWIP_SO_RCVBUF */ + /* Register event with callback */ + API_EVENT(conn, NETCONN_EVT_RCVPLUS, len); + } + } + } + + return 0; /* do not eat the packet */ +} +#endif /* LWIP_RAW*/ + +#if LWIP_UDP +/** + * Receive callback function for UDP netconns. + * Posts the packet to conn->recvmbox or deletes it on memory error. + * + * @see udp.h (struct udp_pcb.recv) for parameters + */ +static void +recv_udp(void *arg, struct udp_pcb *pcb, struct pbuf *p, + ip_addr_t *addr, u16_t port) +{ + struct netbuf *buf; + struct netconn *conn; + u16_t len; +#if LWIP_SO_RCVBUF + int recv_avail; +#endif /* LWIP_SO_RCVBUF */ + + LWIP_UNUSED_ARG(pcb); /* only used for asserts... */ + LWIP_ASSERT("recv_udp must have a pcb argument", pcb != NULL); + LWIP_ASSERT("recv_udp must have an argument", arg != NULL); + conn = (struct netconn *)arg; + LWIP_ASSERT("recv_udp: recv for wrong pcb!", conn->pcb.udp == pcb); + +#if LWIP_SO_RCVBUF + SYS_ARCH_GET(conn->recv_avail, recv_avail); + if ((conn == NULL) || !sys_mbox_valid(&conn->recvmbox) || + ((recv_avail + (int)(p->tot_len)) > conn->recv_bufsize)) { +#else /* LWIP_SO_RCVBUF */ + if ((conn == NULL) || !sys_mbox_valid(&conn->recvmbox)) { +#endif /* LWIP_SO_RCVBUF */ + pbuf_free(p); + return; + } + + buf = (struct netbuf *)memp_malloc(MEMP_NETBUF); + if (buf == NULL) { + pbuf_free(p); + return; + } else { + buf->p = p; + buf->ptr = p; + ip_addr_set(&buf->addr, addr); + buf->port = port; +#if LWIP_NETBUF_RECVINFO + { + const struct ip_hdr* iphdr = ip_current_header(); + /* get the UDP header - always in the first pbuf, ensured by udp_input */ + const struct udp_hdr* udphdr = (void*)(((char*)iphdr) + IPH_LEN(iphdr)); +#if LWIP_CHECKSUM_ON_COPY + buf->flags = NETBUF_FLAG_DESTADDR; +#endif /* LWIP_CHECKSUM_ON_COPY */ + ip_addr_set(&buf->toaddr, ip_current_dest_addr()); + buf->toport_chksum = udphdr->dest; + } +#endif /* LWIP_NETBUF_RECVINFO */ + } + + len = p->tot_len; + if (sys_mbox_trypost(&conn->recvmbox, buf) != ERR_OK) { + netbuf_delete(buf); + return; + } else { +#if LWIP_SO_RCVBUF + SYS_ARCH_INC(conn->recv_avail, len); +#endif /* LWIP_SO_RCVBUF */ + /* Register event with callback */ + API_EVENT(conn, NETCONN_EVT_RCVPLUS, len); + } +} +#endif /* LWIP_UDP */ + +#if LWIP_TCP +/** + * Receive callback function for TCP netconns. + * Posts the packet to conn->recvmbox, but doesn't delete it on errors. + * + * @see tcp.h (struct tcp_pcb.recv) for parameters and return value + */ +static err_t +recv_tcp(void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err) +{ + struct netconn *conn; + u16_t len; + + LWIP_UNUSED_ARG(pcb); + LWIP_ASSERT("recv_tcp must have a pcb argument", pcb != NULL); + LWIP_ASSERT("recv_tcp must have an argument", arg != NULL); + conn = (struct netconn *)arg; + LWIP_ASSERT("recv_tcp: recv for wrong pcb!", conn->pcb.tcp == pcb); + + if (conn == NULL) { + return ERR_VAL; + } + if (!sys_mbox_valid(&conn->recvmbox)) { + /* recvmbox already deleted */ + if (p != NULL) { + tcp_recved(pcb, p->tot_len); + pbuf_free(p); + } + return ERR_OK; + } + /* Unlike for UDP or RAW pcbs, don't check for available space + using recv_avail since that could break the connection + (data is already ACKed) */ + + /* don't overwrite fatal errors! */ + NETCONN_SET_SAFE_ERR(conn, err); + + if (p != NULL) { + len = p->tot_len; + } else { + len = 0; + } + + if (sys_mbox_trypost(&conn->recvmbox, p) != ERR_OK) { + /* don't deallocate p: it is presented to us later again from tcp_fasttmr! */ + return ERR_MEM; + } else { +#if LWIP_SO_RCVBUF + SYS_ARCH_INC(conn->recv_avail, len); +#endif /* LWIP_SO_RCVBUF */ + /* Register event with callback */ + API_EVENT(conn, NETCONN_EVT_RCVPLUS, len); + } + + return ERR_OK; +} + +/** + * Poll callback function for TCP netconns. + * Wakes up an application thread that waits for a connection to close + * or data to be sent. The application thread then takes the + * appropriate action to go on. + * + * Signals the conn->sem. + * netconn_close waits for conn->sem if closing failed. + * + * @see tcp.h (struct tcp_pcb.poll) for parameters and return value + */ +static err_t +poll_tcp(void *arg, struct tcp_pcb *pcb) +{ + struct netconn *conn = (struct netconn *)arg; + + LWIP_UNUSED_ARG(pcb); + LWIP_ASSERT("conn != NULL", (conn != NULL)); + + if (conn->state == NETCONN_WRITE) { + do_writemore(conn); + } else if (conn->state == NETCONN_CLOSE) { + do_close_internal(conn); + } + /* @todo: implement connect timeout here? */ + + /* Did a nonblocking write fail before? Then check available write-space. */ + if (conn->flags & NETCONN_FLAG_CHECK_WRITESPACE) { + /* If the queued byte- or pbuf-count drops below the configured low-water limit, + let select mark this pcb as writable again. */ + if ((conn->pcb.tcp != NULL) && (tcp_sndbuf(conn->pcb.tcp) > TCP_SNDLOWAT) && + (tcp_sndqueuelen(conn->pcb.tcp) < TCP_SNDQUEUELOWAT)) { + conn->flags &= ~NETCONN_FLAG_CHECK_WRITESPACE; + API_EVENT(conn, NETCONN_EVT_SENDPLUS, 0); + } + } + + return ERR_OK; +} + +/** + * Sent callback function for TCP netconns. + * Signals the conn->sem and calls API_EVENT. + * netconn_write waits for conn->sem if send buffer is low. + * + * @see tcp.h (struct tcp_pcb.sent) for parameters and return value + */ +static err_t +sent_tcp(void *arg, struct tcp_pcb *pcb, u16_t len) +{ + struct netconn *conn = (struct netconn *)arg; + + LWIP_UNUSED_ARG(pcb); + LWIP_ASSERT("conn != NULL", (conn != NULL)); + + if (conn->state == NETCONN_WRITE) { + do_writemore(conn); + } else if (conn->state == NETCONN_CLOSE) { + do_close_internal(conn); + } + + if (conn) { + /* If the queued byte- or pbuf-count drops below the configured low-water limit, + let select mark this pcb as writable again. */ + if ((conn->pcb.tcp != NULL) && (tcp_sndbuf(conn->pcb.tcp) > TCP_SNDLOWAT) && + (tcp_sndqueuelen(conn->pcb.tcp) < TCP_SNDQUEUELOWAT)) { + conn->flags &= ~NETCONN_FLAG_CHECK_WRITESPACE; + API_EVENT(conn, NETCONN_EVT_SENDPLUS, len); + } + } + + return ERR_OK; +} + +/** + * Error callback function for TCP netconns. + * Signals conn->sem, posts to all conn mboxes and calls API_EVENT. + * The application thread has then to decide what to do. + * + * @see tcp.h (struct tcp_pcb.err) for parameters + */ +static void +err_tcp(void *arg, err_t err) +{ + struct netconn *conn; + enum netconn_state old_state; + SYS_ARCH_DECL_PROTECT(lev); + + conn = (struct netconn *)arg; + LWIP_ASSERT("conn != NULL", (conn != NULL)); + + conn->pcb.tcp = NULL; + + /* no check since this is always fatal! */ + SYS_ARCH_PROTECT(lev); + conn->last_err = err; + SYS_ARCH_UNPROTECT(lev); + + /* reset conn->state now before waking up other threads */ + old_state = conn->state; + conn->state = NETCONN_NONE; + + /* Notify the user layer about a connection error. Used to signal + select. */ + API_EVENT(conn, NETCONN_EVT_ERROR, 0); + /* Try to release selects pending on 'read' or 'write', too. + They will get an error if they actually try to read or write. */ + API_EVENT(conn, NETCONN_EVT_RCVPLUS, 0); + API_EVENT(conn, NETCONN_EVT_SENDPLUS, 0); + + /* pass NULL-message to recvmbox to wake up pending recv */ + if (sys_mbox_valid(&conn->recvmbox)) { + /* use trypost to prevent deadlock */ + sys_mbox_trypost(&conn->recvmbox, NULL); + } + /* pass NULL-message to acceptmbox to wake up pending accept */ + if (sys_mbox_valid(&conn->acceptmbox)) { + /* use trypost to preven deadlock */ + sys_mbox_trypost(&conn->acceptmbox, NULL); + } + + if ((old_state == NETCONN_WRITE) || (old_state == NETCONN_CLOSE) || + (old_state == NETCONN_CONNECT)) { + /* calling do_writemore/do_close_internal is not necessary + since the pcb has already been deleted! */ + int was_nonblocking_connect = IN_NONBLOCKING_CONNECT(conn); + SET_NONBLOCKING_CONNECT(conn, 0); + + if (!was_nonblocking_connect) { + /* set error return code */ + LWIP_ASSERT("conn->current_msg != NULL", conn->current_msg != NULL); + conn->current_msg->err = err; + conn->current_msg = NULL; + /* wake up the waiting task */ + sys_sem_signal(&conn->op_completed); + } + } else { + LWIP_ASSERT("conn->current_msg == NULL", conn->current_msg == NULL); + } +} + +/** + * Setup a tcp_pcb with the correct callback function pointers + * and their arguments. + * + * @param conn the TCP netconn to setup + */ +static void +setup_tcp(struct netconn *conn) +{ + struct tcp_pcb *pcb; + + pcb = conn->pcb.tcp; + tcp_arg(pcb, conn); + tcp_recv(pcb, recv_tcp); + tcp_sent(pcb, sent_tcp); + tcp_poll(pcb, poll_tcp, 4); + tcp_err(pcb, err_tcp); +} + +/** + * Accept callback function for TCP netconns. + * Allocates a new netconn and posts that to conn->acceptmbox. + * + * @see tcp.h (struct tcp_pcb_listen.accept) for parameters and return value + */ +static err_t +accept_function(void *arg, struct tcp_pcb *newpcb, err_t err) +{ + struct netconn *newconn; + struct netconn *conn = (struct netconn *)arg; + + LWIP_DEBUGF(API_MSG_DEBUG, ("accept_function: newpcb->tate: %s\n", tcp_debug_state_str(newpcb->state))); + + if (!sys_mbox_valid(&conn->acceptmbox)) { + LWIP_DEBUGF(API_MSG_DEBUG, ("accept_function: acceptmbox already deleted\n")); + return ERR_VAL; + } + + /* We have to set the callback here even though + * the new socket is unknown. conn->socket is marked as -1. */ + newconn = netconn_alloc(conn->type, conn->callback); + if (newconn == NULL) { + return ERR_MEM; + } + newconn->pcb.tcp = newpcb; + setup_tcp(newconn); + /* no protection: when creating the pcb, the netconn is not yet known + to the application thread */ + newconn->last_err = err; + + if (sys_mbox_trypost(&conn->acceptmbox, newconn) != ERR_OK) { + /* When returning != ERR_OK, the pcb is aborted in tcp_process(), + so do nothing here! */ + newconn->pcb.tcp = NULL; + /* no need to drain since we know the recvmbox is empty. */ + sys_mbox_free(&newconn->recvmbox); + sys_mbox_set_invalid(&newconn->recvmbox); + netconn_free(newconn); + return ERR_MEM; + } else { + /* Register event with callback */ + API_EVENT(conn, NETCONN_EVT_RCVPLUS, 0); + } + + return ERR_OK; +} +#endif /* LWIP_TCP */ + +/** + * Create a new pcb of a specific type. + * Called from do_newconn(). + * + * @param msg the api_msg_msg describing the connection type + * @return msg->conn->err, but the return value is currently ignored + */ +static void +pcb_new(struct api_msg_msg *msg) +{ + LWIP_ASSERT("pcb_new: pcb already allocated", msg->conn->pcb.tcp == NULL); + + /* Allocate a PCB for this connection */ + switch(NETCONNTYPE_GROUP(msg->conn->type)) { +#if LWIP_RAW + case NETCONN_RAW: + msg->conn->pcb.raw = raw_new(msg->msg.n.proto); + if(msg->conn->pcb.raw == NULL) { + msg->err = ERR_MEM; + break; + } + raw_recv(msg->conn->pcb.raw, recv_raw, msg->conn); + break; +#endif /* LWIP_RAW */ +#if LWIP_UDP + case NETCONN_UDP: + msg->conn->pcb.udp = udp_new(); + if(msg->conn->pcb.udp == NULL) { + msg->err = ERR_MEM; + break; + } +#if LWIP_UDPLITE + if (msg->conn->type==NETCONN_UDPLITE) { + udp_setflags(msg->conn->pcb.udp, UDP_FLAGS_UDPLITE); + } +#endif /* LWIP_UDPLITE */ + if (msg->conn->type==NETCONN_UDPNOCHKSUM) { + udp_setflags(msg->conn->pcb.udp, UDP_FLAGS_NOCHKSUM); + } + udp_recv(msg->conn->pcb.udp, recv_udp, msg->conn); + break; +#endif /* LWIP_UDP */ +#if LWIP_TCP + case NETCONN_TCP: + msg->conn->pcb.tcp = tcp_new(); + if(msg->conn->pcb.tcp == NULL) { + msg->err = ERR_MEM; + break; + } + setup_tcp(msg->conn); + break; +#endif /* LWIP_TCP */ + default: + /* Unsupported netconn type, e.g. protocol disabled */ + msg->err = ERR_VAL; + break; + } +} + +/** + * Create a new pcb of a specific type inside a netconn. + * Called from netconn_new_with_proto_and_callback. + * + * @param msg the api_msg_msg describing the connection type + */ +void +do_newconn(struct api_msg_msg *msg) +{ + msg->err = ERR_OK; + if(msg->conn->pcb.tcp == NULL) { + pcb_new(msg); + } + /* Else? This "new" connection already has a PCB allocated. */ + /* Is this an error condition? Should it be deleted? */ + /* We currently just are happy and return. */ + + TCPIP_APIMSG_ACK(msg); +} + +/** + * Create a new netconn (of a specific type) that has a callback function. + * The corresponding pcb is NOT created! + * + * @param t the type of 'connection' to create (@see enum netconn_type) + * @param proto the IP protocol for RAW IP pcbs + * @param callback a function to call on status changes (RX available, TX'ed) + * @return a newly allocated struct netconn or + * NULL on memory error + */ +struct netconn* +netconn_alloc(enum netconn_type t, netconn_callback callback) +{ + struct netconn *conn; + int size; + + conn = (struct netconn *)memp_malloc(MEMP_NETCONN); + if (conn == NULL) { + return NULL; + } + + conn->last_err = ERR_OK; + conn->type = t; + conn->pcb.tcp = NULL; + +#if (DEFAULT_RAW_RECVMBOX_SIZE == DEFAULT_UDP_RECVMBOX_SIZE) && \ + (DEFAULT_RAW_RECVMBOX_SIZE == DEFAULT_TCP_RECVMBOX_SIZE) + size = DEFAULT_RAW_RECVMBOX_SIZE; +#else + switch(NETCONNTYPE_GROUP(t)) { +#if LWIP_RAW + case NETCONN_RAW: + size = DEFAULT_RAW_RECVMBOX_SIZE; + break; +#endif /* LWIP_RAW */ +#if LWIP_UDP + case NETCONN_UDP: + size = DEFAULT_UDP_RECVMBOX_SIZE; + break; +#endif /* LWIP_UDP */ +#if LWIP_TCP + case NETCONN_TCP: + size = DEFAULT_TCP_RECVMBOX_SIZE; + break; +#endif /* LWIP_TCP */ + default: + LWIP_ASSERT("netconn_alloc: undefined netconn_type", 0); + break; + } +#endif + + if (sys_sem_new(&conn->op_completed, 0) != ERR_OK) { + memp_free(MEMP_NETCONN, conn); + return NULL; + } + if (sys_mbox_new(&conn->recvmbox, size) != ERR_OK) { + sys_sem_free(&conn->op_completed); + memp_free(MEMP_NETCONN, conn); + return NULL; + } + +#if LWIP_TCP + sys_mbox_set_invalid(&conn->acceptmbox); +#endif + conn->state = NETCONN_NONE; +#if LWIP_SOCKET + /* initialize socket to -1 since 0 is a valid socket */ + conn->socket = -1; +#endif /* LWIP_SOCKET */ + conn->callback = callback; +#if LWIP_TCP + conn->current_msg = NULL; + conn->write_offset = 0; +#endif /* LWIP_TCP */ +#if LWIP_SO_RCVTIMEO + conn->recv_timeout = 0; +#endif /* LWIP_SO_RCVTIMEO */ +#if LWIP_SO_RCVBUF + conn->recv_bufsize = RECV_BUFSIZE_DEFAULT; + conn->recv_avail = 0; +#endif /* LWIP_SO_RCVBUF */ + conn->flags = 0; + return conn; +} + +/** + * Delete a netconn and all its resources. + * The pcb is NOT freed (since we might not be in the right thread context do this). + * + * @param conn the netconn to free + */ +void +netconn_free(struct netconn *conn) +{ + LWIP_ASSERT("PCB must be deallocated outside this function", conn->pcb.tcp == NULL); + LWIP_ASSERT("recvmbox must be deallocated before calling this function", + !sys_mbox_valid(&conn->recvmbox)); +#if LWIP_TCP + LWIP_ASSERT("acceptmbox must be deallocated before calling this function", + !sys_mbox_valid(&conn->acceptmbox)); +#endif /* LWIP_TCP */ + + sys_sem_free(&conn->op_completed); + sys_sem_set_invalid(&conn->op_completed); + + memp_free(MEMP_NETCONN, conn); +} + +/** + * Delete rcvmbox and acceptmbox of a netconn and free the left-over data in + * these mboxes + * + * @param conn the netconn to free + * @bytes_drained bytes drained from recvmbox + * @accepts_drained pending connections drained from acceptmbox + */ +static void +netconn_drain(struct netconn *conn) +{ + void *mem; +#if LWIP_TCP + struct pbuf *p; +#endif /* LWIP_TCP */ + + /* This runs in tcpip_thread, so we don't need to lock against rx packets */ + + /* Delete and drain the recvmbox. */ + if (sys_mbox_valid(&conn->recvmbox)) { + while (sys_mbox_tryfetch(&conn->recvmbox, &mem) != SYS_MBOX_EMPTY) { +#if LWIP_TCP + if (conn->type == NETCONN_TCP) { + if(mem != NULL) { + p = (struct pbuf*)mem; + /* pcb might be set to NULL already by err_tcp() */ + if (conn->pcb.tcp != NULL) { + tcp_recved(conn->pcb.tcp, p->tot_len); + } + pbuf_free(p); + } + } else +#endif /* LWIP_TCP */ + { + netbuf_delete((struct netbuf *)mem); + } + } + sys_mbox_free(&conn->recvmbox); + sys_mbox_set_invalid(&conn->recvmbox); + } + + /* Delete and drain the acceptmbox. */ +#if LWIP_TCP + if (sys_mbox_valid(&conn->acceptmbox)) { + while (sys_mbox_tryfetch(&conn->acceptmbox, &mem) != SYS_MBOX_EMPTY) { + struct netconn *newconn = (struct netconn *)mem; + /* Only tcp pcbs have an acceptmbox, so no need to check conn->type */ + /* pcb might be set to NULL already by err_tcp() */ + if (conn->pcb.tcp != NULL) { + tcp_accepted(conn->pcb.tcp); + } + /* drain recvmbox */ + netconn_drain(newconn); + if (newconn->pcb.tcp != NULL) { + tcp_abort(newconn->pcb.tcp); + newconn->pcb.tcp = NULL; + } + netconn_free(newconn); + } + sys_mbox_free(&conn->acceptmbox); + sys_mbox_set_invalid(&conn->acceptmbox); + } +#endif /* LWIP_TCP */ +} + +#if LWIP_TCP +/** + * Internal helper function to close a TCP netconn: since this sometimes + * doesn't work at the first attempt, this function is called from multiple + * places. + * + * @param conn the TCP netconn to close + */ +static void +do_close_internal(struct netconn *conn) +{ + err_t err; + u8_t shut, shut_rx, shut_tx, close; + + LWIP_ASSERT("invalid conn", (conn != NULL)); + LWIP_ASSERT("this is for tcp netconns only", (conn->type == NETCONN_TCP)); + LWIP_ASSERT("conn must be in state NETCONN_CLOSE", (conn->state == NETCONN_CLOSE)); + LWIP_ASSERT("pcb already closed", (conn->pcb.tcp != NULL)); + LWIP_ASSERT("conn->current_msg != NULL", conn->current_msg != NULL); + + shut = conn->current_msg->msg.sd.shut; + shut_rx = shut & NETCONN_SHUT_RD; + shut_tx = shut & NETCONN_SHUT_WR; + /* shutting down both ends is the same as closing */ + close = shut == NETCONN_SHUT_RDWR; + + /* Set back some callback pointers */ + if (close) { + tcp_arg(conn->pcb.tcp, NULL); + } + if (conn->pcb.tcp->state == LISTEN) { + tcp_accept(conn->pcb.tcp, NULL); + } else { + /* some callbacks have to be reset if tcp_close is not successful */ + if (shut_rx) { + tcp_recv(conn->pcb.tcp, NULL); + tcp_accept(conn->pcb.tcp, NULL); + } + if (shut_tx) { + tcp_sent(conn->pcb.tcp, NULL); + } + if (close) { + tcp_poll(conn->pcb.tcp, NULL, 4); + tcp_err(conn->pcb.tcp, NULL); + } + } + /* Try to close the connection */ + if (shut == NETCONN_SHUT_RDWR) { + err = tcp_close(conn->pcb.tcp); + } else { + err = tcp_shutdown(conn->pcb.tcp, shut & NETCONN_SHUT_RD, shut & NETCONN_SHUT_WR); + } + if (err == ERR_OK) { + /* Closing succeeded */ + conn->current_msg->err = ERR_OK; + conn->current_msg = NULL; + conn->state = NETCONN_NONE; + /* Set back some callback pointers as conn is going away */ + conn->pcb.tcp = NULL; + /* Trigger select() in socket layer. Make sure everybody notices activity + on the connection, error first! */ + if (close) { + API_EVENT(conn, NETCONN_EVT_ERROR, 0); + } + if (shut_rx) { + API_EVENT(conn, NETCONN_EVT_RCVPLUS, 0); + } + if (shut_tx) { + API_EVENT(conn, NETCONN_EVT_SENDPLUS, 0); + } + /* wake up the application task */ + sys_sem_signal(&conn->op_completed); + } else { + /* Closing failed, restore some of the callbacks */ + /* Closing of listen pcb will never fail! */ + LWIP_ASSERT("Closing a listen pcb may not fail!", (conn->pcb.tcp->state != LISTEN)); + tcp_sent(conn->pcb.tcp, sent_tcp); + tcp_poll(conn->pcb.tcp, poll_tcp, 4); + tcp_err(conn->pcb.tcp, err_tcp); + tcp_arg(conn->pcb.tcp, conn); + /* don't restore recv callback: we don't want to receive any more data */ + } + /* If closing didn't succeed, we get called again either + from poll_tcp or from sent_tcp */ +} +#endif /* LWIP_TCP */ + +/** + * Delete the pcb inside a netconn. + * Called from netconn_delete. + * + * @param msg the api_msg_msg pointing to the connection + */ +void +do_delconn(struct api_msg_msg *msg) +{ + /* @todo TCP: abort running write/connect? */ + if ((msg->conn->state != NETCONN_NONE) && + (msg->conn->state != NETCONN_LISTEN) && + (msg->conn->state != NETCONN_CONNECT)) { + /* this only happens for TCP netconns */ + LWIP_ASSERT("msg->conn->type == NETCONN_TCP", msg->conn->type == NETCONN_TCP); + msg->err = ERR_INPROGRESS; + } else { + LWIP_ASSERT("blocking connect in progress", + (msg->conn->state != NETCONN_CONNECT) || IN_NONBLOCKING_CONNECT(msg->conn)); + /* Drain and delete mboxes */ + netconn_drain(msg->conn); + + if (msg->conn->pcb.tcp != NULL) { + + switch (NETCONNTYPE_GROUP(msg->conn->type)) { +#if LWIP_RAW + case NETCONN_RAW: + raw_remove(msg->conn->pcb.raw); + break; +#endif /* LWIP_RAW */ +#if LWIP_UDP + case NETCONN_UDP: + msg->conn->pcb.udp->recv_arg = NULL; + udp_remove(msg->conn->pcb.udp); + break; +#endif /* LWIP_UDP */ +#if LWIP_TCP + case NETCONN_TCP: + LWIP_ASSERT("already writing or closing", msg->conn->current_msg == NULL && + msg->conn->write_offset == 0); + msg->conn->state = NETCONN_CLOSE; + msg->msg.sd.shut = NETCONN_SHUT_RDWR; + msg->conn->current_msg = msg; + do_close_internal(msg->conn); + /* API_EVENT is called inside do_close_internal, before releasing + the application thread, so we can return at this point! */ + return; +#endif /* LWIP_TCP */ + default: + break; + } + msg->conn->pcb.tcp = NULL; + } + /* tcp netconns don't come here! */ + + /* @todo: this lets select make the socket readable and writable, + which is wrong! errfd instead? */ + API_EVENT(msg->conn, NETCONN_EVT_RCVPLUS, 0); + API_EVENT(msg->conn, NETCONN_EVT_SENDPLUS, 0); + } + if (sys_sem_valid(&msg->conn->op_completed)) { + sys_sem_signal(&msg->conn->op_completed); + } +} + +/** + * Bind a pcb contained in a netconn + * Called from netconn_bind. + * + * @param msg the api_msg_msg pointing to the connection and containing + * the IP address and port to bind to + */ +void +do_bind(struct api_msg_msg *msg) +{ + if (ERR_IS_FATAL(msg->conn->last_err)) { + msg->err = msg->conn->last_err; + } else { + msg->err = ERR_VAL; + if (msg->conn->pcb.tcp != NULL) { + switch (NETCONNTYPE_GROUP(msg->conn->type)) { +#if LWIP_RAW + case NETCONN_RAW: + msg->err = raw_bind(msg->conn->pcb.raw, msg->msg.bc.ipaddr); + break; +#endif /* LWIP_RAW */ +#if LWIP_UDP + case NETCONN_UDP: + msg->err = udp_bind(msg->conn->pcb.udp, msg->msg.bc.ipaddr, msg->msg.bc.port); + break; +#endif /* LWIP_UDP */ +#if LWIP_TCP + case NETCONN_TCP: + msg->err = tcp_bind(msg->conn->pcb.tcp, msg->msg.bc.ipaddr, msg->msg.bc.port); + break; +#endif /* LWIP_TCP */ + default: + break; + } + } + } + TCPIP_APIMSG_ACK(msg); +} + +#if LWIP_TCP +/** + * TCP callback function if a connection (opened by tcp_connect/do_connect) has + * been established (or reset by the remote host). + * + * @see tcp.h (struct tcp_pcb.connected) for parameters and return values + */ +static err_t +do_connected(void *arg, struct tcp_pcb *pcb, err_t err) +{ + struct netconn *conn; + int was_blocking; + + LWIP_UNUSED_ARG(pcb); + + conn = (struct netconn *)arg; + + if (conn == NULL) { + return ERR_VAL; + } + + LWIP_ASSERT("conn->state == NETCONN_CONNECT", conn->state == NETCONN_CONNECT); + LWIP_ASSERT("(conn->current_msg != NULL) || conn->in_non_blocking_connect", + (conn->current_msg != NULL) || IN_NONBLOCKING_CONNECT(conn)); + + if (conn->current_msg != NULL) { + conn->current_msg->err = err; + } + if ((conn->type == NETCONN_TCP) && (err == ERR_OK)) { + setup_tcp(conn); + } + was_blocking = !IN_NONBLOCKING_CONNECT(conn); + SET_NONBLOCKING_CONNECT(conn, 0); + conn->current_msg = NULL; + conn->state = NETCONN_NONE; + if (!was_blocking) { + NETCONN_SET_SAFE_ERR(conn, ERR_OK); + } + API_EVENT(conn, NETCONN_EVT_SENDPLUS, 0); + + if (was_blocking) { + sys_sem_signal(&conn->op_completed); + } + return ERR_OK; +} +#endif /* LWIP_TCP */ + +/** + * Connect a pcb contained inside a netconn + * Called from netconn_connect. + * + * @param msg the api_msg_msg pointing to the connection and containing + * the IP address and port to connect to + */ +void +do_connect(struct api_msg_msg *msg) +{ + if (msg->conn->pcb.tcp == NULL) { + /* This may happen when calling netconn_connect() a second time */ + msg->err = ERR_CLSD; + } else { + switch (NETCONNTYPE_GROUP(msg->conn->type)) { +#if LWIP_RAW + case NETCONN_RAW: + msg->err = raw_connect(msg->conn->pcb.raw, msg->msg.bc.ipaddr); + break; +#endif /* LWIP_RAW */ +#if LWIP_UDP + case NETCONN_UDP: + msg->err = udp_connect(msg->conn->pcb.udp, msg->msg.bc.ipaddr, msg->msg.bc.port); + break; +#endif /* LWIP_UDP */ +#if LWIP_TCP + case NETCONN_TCP: + /* Prevent connect while doing any other action. */ + if (msg->conn->state != NETCONN_NONE) { + msg->err = ERR_ISCONN; + } else { + setup_tcp(msg->conn); + msg->err = tcp_connect(msg->conn->pcb.tcp, msg->msg.bc.ipaddr, + msg->msg.bc.port, do_connected); + if (msg->err == ERR_OK) { + u8_t non_blocking = netconn_is_nonblocking(msg->conn); + msg->conn->state = NETCONN_CONNECT; + SET_NONBLOCKING_CONNECT(msg->conn, non_blocking); + if (non_blocking) { + msg->err = ERR_INPROGRESS; + } else { + msg->conn->current_msg = msg; + /* sys_sem_signal() is called from do_connected (or err_tcp()), + * when the connection is established! */ + return; + } + } + } + break; +#endif /* LWIP_TCP */ + default: + LWIP_ERROR("Invalid netconn type", 0, do{ msg->err = ERR_VAL; }while(0)); + break; + } + } + sys_sem_signal(&msg->conn->op_completed); +} + +/** + * Connect a pcb contained inside a netconn + * Only used for UDP netconns. + * Called from netconn_disconnect. + * + * @param msg the api_msg_msg pointing to the connection to disconnect + */ +void +do_disconnect(struct api_msg_msg *msg) +{ +#if LWIP_UDP + if (NETCONNTYPE_GROUP(msg->conn->type) == NETCONN_UDP) { + udp_disconnect(msg->conn->pcb.udp); + msg->err = ERR_OK; + } else +#endif /* LWIP_UDP */ + { + msg->err = ERR_VAL; + } + TCPIP_APIMSG_ACK(msg); +} + +#if LWIP_TCP +/** + * Set a TCP pcb contained in a netconn into listen mode + * Called from netconn_listen. + * + * @param msg the api_msg_msg pointing to the connection + */ +void +do_listen(struct api_msg_msg *msg) +{ + if (ERR_IS_FATAL(msg->conn->last_err)) { + msg->err = msg->conn->last_err; + } else { + msg->err = ERR_CONN; + if (msg->conn->pcb.tcp != NULL) { + if (msg->conn->type == NETCONN_TCP) { + if (msg->conn->state == NETCONN_NONE) { +#if TCP_LISTEN_BACKLOG + struct tcp_pcb* lpcb = tcp_listen_with_backlog(msg->conn->pcb.tcp, msg->msg.lb.backlog); +#else /* TCP_LISTEN_BACKLOG */ + struct tcp_pcb* lpcb = tcp_listen(msg->conn->pcb.tcp); +#endif /* TCP_LISTEN_BACKLOG */ + if (lpcb == NULL) { + /* in this case, the old pcb is still allocated */ + msg->err = ERR_MEM; + } else { + /* delete the recvmbox and allocate the acceptmbox */ + if (sys_mbox_valid(&msg->conn->recvmbox)) { + /** @todo: should we drain the recvmbox here? */ + sys_mbox_free(&msg->conn->recvmbox); + sys_mbox_set_invalid(&msg->conn->recvmbox); + } + msg->err = ERR_OK; + if (!sys_mbox_valid(&msg->conn->acceptmbox)) { + msg->err = sys_mbox_new(&msg->conn->acceptmbox, DEFAULT_ACCEPTMBOX_SIZE); + } + if (msg->err == ERR_OK) { + msg->conn->state = NETCONN_LISTEN; + msg->conn->pcb.tcp = lpcb; + tcp_arg(msg->conn->pcb.tcp, msg->conn); + tcp_accept(msg->conn->pcb.tcp, accept_function); + } else { + /* since the old pcb is already deallocated, free lpcb now */ + tcp_close(lpcb); + msg->conn->pcb.tcp = NULL; + } + } + } + } + } + } + TCPIP_APIMSG_ACK(msg); +} +#endif /* LWIP_TCP */ + +/** + * Send some data on a RAW or UDP pcb contained in a netconn + * Called from netconn_send + * + * @param msg the api_msg_msg pointing to the connection + */ +void +do_send(struct api_msg_msg *msg) +{ + if (ERR_IS_FATAL(msg->conn->last_err)) { + msg->err = msg->conn->last_err; + } else { + msg->err = ERR_CONN; + if (msg->conn->pcb.tcp != NULL) { + switch (NETCONNTYPE_GROUP(msg->conn->type)) { +#if LWIP_RAW + case NETCONN_RAW: + if (ip_addr_isany(&msg->msg.b->addr)) { + msg->err = raw_send(msg->conn->pcb.raw, msg->msg.b->p); + } else { + msg->err = raw_sendto(msg->conn->pcb.raw, msg->msg.b->p, &msg->msg.b->addr); + } + break; +#endif +#if LWIP_UDP + case NETCONN_UDP: +#if LWIP_CHECKSUM_ON_COPY + if (ip_addr_isany(&msg->msg.b->addr)) { + msg->err = udp_send_chksum(msg->conn->pcb.udp, msg->msg.b->p, + msg->msg.b->flags & NETBUF_FLAG_CHKSUM, msg->msg.b->toport_chksum); + } else { + msg->err = udp_sendto_chksum(msg->conn->pcb.udp, msg->msg.b->p, + &msg->msg.b->addr, msg->msg.b->port, + msg->msg.b->flags & NETBUF_FLAG_CHKSUM, msg->msg.b->toport_chksum); + } +#else /* LWIP_CHECKSUM_ON_COPY */ + if (ip_addr_isany(&msg->msg.b->addr)) { + msg->err = udp_send(msg->conn->pcb.udp, msg->msg.b->p); + } else { + msg->err = udp_sendto(msg->conn->pcb.udp, msg->msg.b->p, &msg->msg.b->addr, msg->msg.b->port); + } +#endif /* LWIP_CHECKSUM_ON_COPY */ + break; +#endif /* LWIP_UDP */ + default: + break; + } + } + } + TCPIP_APIMSG_ACK(msg); +} + +#if LWIP_TCP +/** + * Indicate data has been received from a TCP pcb contained in a netconn + * Called from netconn_recv + * + * @param msg the api_msg_msg pointing to the connection + */ +void +do_recv(struct api_msg_msg *msg) +{ + msg->err = ERR_OK; + if (msg->conn->pcb.tcp != NULL) { + if (msg->conn->type == NETCONN_TCP) { +#if TCP_LISTEN_BACKLOG + if (msg->conn->pcb.tcp->state == LISTEN) { + tcp_accepted(msg->conn->pcb.tcp); + } else +#endif /* TCP_LISTEN_BACKLOG */ + { + u32_t remaining = msg->msg.r.len; + do { + u16_t recved = (remaining > 0xffff) ? 0xffff : (u16_t)remaining; + tcp_recved(msg->conn->pcb.tcp, recved); + remaining -= recved; + }while(remaining != 0); + } + } + } + TCPIP_APIMSG_ACK(msg); +} + +/** + * See if more data needs to be written from a previous call to netconn_write. + * Called initially from do_write. If the first call can't send all data + * (because of low memory or empty send-buffer), this function is called again + * from sent_tcp() or poll_tcp() to send more data. If all data is sent, the + * blocking application thread (waiting in netconn_write) is released. + * + * @param conn netconn (that is currently in state NETCONN_WRITE) to process + * @return ERR_OK + * ERR_MEM if LWIP_TCPIP_CORE_LOCKING=1 and sending hasn't yet finished + */ +static err_t +do_writemore(struct netconn *conn) +{ + err_t err = ERR_OK; + void *dataptr; + u16_t len, available; + u8_t write_finished = 0; + size_t diff; + u8_t dontblock = netconn_is_nonblocking(conn) || + (conn->current_msg->msg.w.apiflags & NETCONN_DONTBLOCK); + u8_t apiflags = conn->current_msg->msg.w.apiflags; + + LWIP_ASSERT("conn != NULL", conn != NULL); + LWIP_ASSERT("conn->state == NETCONN_WRITE", (conn->state == NETCONN_WRITE)); + LWIP_ASSERT("conn->current_msg != NULL", conn->current_msg != NULL); + LWIP_ASSERT("conn->pcb.tcp != NULL", conn->pcb.tcp != NULL); + LWIP_ASSERT("conn->write_offset < conn->current_msg->msg.w.len", + conn->write_offset < conn->current_msg->msg.w.len); + + dataptr = (u8_t*)conn->current_msg->msg.w.dataptr + conn->write_offset; + diff = conn->current_msg->msg.w.len - conn->write_offset; + if (diff > 0xffffUL) { /* max_u16_t */ + len = 0xffff; +#if LWIP_TCPIP_CORE_LOCKING + conn->flags |= NETCONN_FLAG_WRITE_DELAYED; +#endif + apiflags |= TCP_WRITE_FLAG_MORE; + } else { + len = (u16_t)diff; + } + available = tcp_sndbuf(conn->pcb.tcp); + if (available < len) { + /* don't try to write more than sendbuf */ + len = available; +#if LWIP_TCPIP_CORE_LOCKING + conn->flags |= NETCONN_FLAG_WRITE_DELAYED; +#endif + apiflags |= TCP_WRITE_FLAG_MORE; + } + if (dontblock && (len < conn->current_msg->msg.w.len)) { + /* failed to send all data at once -> nonblocking write not possible */ + err = ERR_MEM; + } + if (err == ERR_OK) { + LWIP_ASSERT("do_writemore: invalid length!", ((conn->write_offset + len) <= conn->current_msg->msg.w.len)); + err = tcp_write(conn->pcb.tcp, dataptr, len, apiflags); + } + if (dontblock && (err == ERR_MEM)) { + /* nonblocking write failed */ + write_finished = 1; + err = ERR_WOULDBLOCK; + /* let poll_tcp check writable space to mark the pcb + writable again */ + conn->flags |= NETCONN_FLAG_CHECK_WRITESPACE; + /* let select mark this pcb as non-writable. */ + API_EVENT(conn, NETCONN_EVT_SENDMINUS, len); + } else { + /* if OK or memory error, check available space */ + if (((err == ERR_OK) || (err == ERR_MEM)) && + ((tcp_sndbuf(conn->pcb.tcp) <= TCP_SNDLOWAT) || + (tcp_sndqueuelen(conn->pcb.tcp) >= TCP_SNDQUEUELOWAT))) { + /* The queued byte- or pbuf-count exceeds the configured low-water limit, + let select mark this pcb as non-writable. */ + API_EVENT(conn, NETCONN_EVT_SENDMINUS, len); + } + + if (err == ERR_OK) { + conn->write_offset += len; + if (conn->write_offset == conn->current_msg->msg.w.len) { + /* everything was written */ + write_finished = 1; + conn->write_offset = 0; + } + tcp_output(conn->pcb.tcp); + } else if (err == ERR_MEM) { + /* If ERR_MEM, we wait for sent_tcp or poll_tcp to be called + we do NOT return to the application thread, since ERR_MEM is + only a temporary error! */ + + /* tcp_write returned ERR_MEM, try tcp_output anyway */ + tcp_output(conn->pcb.tcp); + + #if LWIP_TCPIP_CORE_LOCKING + conn->flags |= NETCONN_FLAG_WRITE_DELAYED; + #endif + } else { + /* On errors != ERR_MEM, we don't try writing any more but return + the error to the application thread. */ + write_finished = 1; + } + } + + if (write_finished) { + /* everything was written: set back connection state + and back to application task */ + conn->current_msg->err = err; + conn->current_msg = NULL; + conn->state = NETCONN_NONE; +#if LWIP_TCPIP_CORE_LOCKING + if ((conn->flags & NETCONN_FLAG_WRITE_DELAYED) != 0) +#endif + { + sys_sem_signal(&conn->op_completed); + } + } +#if LWIP_TCPIP_CORE_LOCKING + else + return ERR_MEM; +#endif + return ERR_OK; +} +#endif /* LWIP_TCP */ + +/** + * Send some data on a TCP pcb contained in a netconn + * Called from netconn_write + * + * @param msg the api_msg_msg pointing to the connection + */ +void +do_write(struct api_msg_msg *msg) +{ + if (ERR_IS_FATAL(msg->conn->last_err)) { + msg->err = msg->conn->last_err; + } else { + if (msg->conn->type == NETCONN_TCP) { +#if LWIP_TCP + if (msg->conn->state != NETCONN_NONE) { + /* netconn is connecting, closing or in blocking write */ + msg->err = ERR_INPROGRESS; + } else if (msg->conn->pcb.tcp != NULL) { + msg->conn->state = NETCONN_WRITE; + /* set all the variables used by do_writemore */ + LWIP_ASSERT("already writing or closing", msg->conn->current_msg == NULL && + msg->conn->write_offset == 0); + LWIP_ASSERT("msg->msg.w.len != 0", msg->msg.w.len != 0); + msg->conn->current_msg = msg; + msg->conn->write_offset = 0; +#if LWIP_TCPIP_CORE_LOCKING + msg->conn->flags &= ~NETCONN_FLAG_WRITE_DELAYED; + if (do_writemore(msg->conn) != ERR_OK) { + LWIP_ASSERT("state!", msg->conn->state == NETCONN_WRITE); + UNLOCK_TCPIP_CORE(); + sys_arch_sem_wait(&msg->conn->op_completed, 0); + LOCK_TCPIP_CORE(); + LWIP_ASSERT("state!", msg->conn->state == NETCONN_NONE); + } +#else /* LWIP_TCPIP_CORE_LOCKING */ + do_writemore(msg->conn); +#endif /* LWIP_TCPIP_CORE_LOCKING */ + /* for both cases: if do_writemore was called, don't ACK the APIMSG + since do_writemore ACKs it! */ + return; + } else { + msg->err = ERR_CONN; + } +#else /* LWIP_TCP */ + msg->err = ERR_VAL; +#endif /* LWIP_TCP */ +#if (LWIP_UDP || LWIP_RAW) + } else { + msg->err = ERR_VAL; +#endif /* (LWIP_UDP || LWIP_RAW) */ + } + } + TCPIP_APIMSG_ACK(msg); +} + +/** + * Return a connection's local or remote address + * Called from netconn_getaddr + * + * @param msg the api_msg_msg pointing to the connection + */ +void +do_getaddr(struct api_msg_msg *msg) +{ + if (msg->conn->pcb.ip != NULL) { + *(msg->msg.ad.ipaddr) = (msg->msg.ad.local ? msg->conn->pcb.ip->local_ip : + msg->conn->pcb.ip->remote_ip); + + msg->err = ERR_OK; + switch (NETCONNTYPE_GROUP(msg->conn->type)) { +#if LWIP_RAW + case NETCONN_RAW: + if (msg->msg.ad.local) { + *(msg->msg.ad.port) = msg->conn->pcb.raw->protocol; + } else { + /* return an error as connecting is only a helper for upper layers */ + msg->err = ERR_CONN; + } + break; +#endif /* LWIP_RAW */ +#if LWIP_UDP + case NETCONN_UDP: + if (msg->msg.ad.local) { + *(msg->msg.ad.port) = msg->conn->pcb.udp->local_port; + } else { + if ((msg->conn->pcb.udp->flags & UDP_FLAGS_CONNECTED) == 0) { + msg->err = ERR_CONN; + } else { + *(msg->msg.ad.port) = msg->conn->pcb.udp->remote_port; + } + } + break; +#endif /* LWIP_UDP */ +#if LWIP_TCP + case NETCONN_TCP: + *(msg->msg.ad.port) = (msg->msg.ad.local?msg->conn->pcb.tcp->local_port:msg->conn->pcb.tcp->remote_port); + break; +#endif /* LWIP_TCP */ + default: + LWIP_ASSERT("invalid netconn_type", 0); + break; + } + } else { + msg->err = ERR_CONN; + } + TCPIP_APIMSG_ACK(msg); +} + +/** + * Close a TCP pcb contained in a netconn + * Called from netconn_close + * + * @param msg the api_msg_msg pointing to the connection + */ +void +do_close(struct api_msg_msg *msg) +{ +#if LWIP_TCP + /* @todo: abort running write/connect? */ + if ((msg->conn->state != NETCONN_NONE) && (msg->conn->state != NETCONN_LISTEN)) { + /* this only happens for TCP netconns */ + LWIP_ASSERT("msg->conn->type == NETCONN_TCP", msg->conn->type == NETCONN_TCP); + msg->err = ERR_INPROGRESS; + } else if ((msg->conn->pcb.tcp != NULL) && (msg->conn->type == NETCONN_TCP)) { + if ((msg->msg.sd.shut != NETCONN_SHUT_RDWR) && (msg->conn->state == NETCONN_LISTEN)) { + /* LISTEN doesn't support half shutdown */ + msg->err = ERR_CONN; + } else { + if (msg->msg.sd.shut & NETCONN_SHUT_RD) { + /* Drain and delete mboxes */ + netconn_drain(msg->conn); + } + LWIP_ASSERT("already writing or closing", msg->conn->current_msg == NULL && + msg->conn->write_offset == 0); + msg->conn->state = NETCONN_CLOSE; + msg->conn->current_msg = msg; + do_close_internal(msg->conn); + /* for tcp netconns, do_close_internal ACKs the message */ + return; + } + } else +#endif /* LWIP_TCP */ + { + msg->err = ERR_VAL; + } + sys_sem_signal(&msg->conn->op_completed); +} + +#if LWIP_IGMP +/** + * Join multicast groups for UDP netconns. + * Called from netconn_join_leave_group + * + * @param msg the api_msg_msg pointing to the connection + */ +void +do_join_leave_group(struct api_msg_msg *msg) +{ + if (ERR_IS_FATAL(msg->conn->last_err)) { + msg->err = msg->conn->last_err; + } else { + if (msg->conn->pcb.tcp != NULL) { + if (NETCONNTYPE_GROUP(msg->conn->type) == NETCONN_UDP) { +#if LWIP_UDP + if (msg->msg.jl.join_or_leave == NETCONN_JOIN) { + msg->err = igmp_joingroup(msg->msg.jl.netif_addr, msg->msg.jl.multiaddr); + } else { + msg->err = igmp_leavegroup(msg->msg.jl.netif_addr, msg->msg.jl.multiaddr); + } +#endif /* LWIP_UDP */ +#if (LWIP_TCP || LWIP_RAW) + } else { + msg->err = ERR_VAL; +#endif /* (LWIP_TCP || LWIP_RAW) */ + } + } else { + msg->err = ERR_CONN; + } + } + TCPIP_APIMSG_ACK(msg); +} +#endif /* LWIP_IGMP */ + +#if LWIP_DNS +/** + * Callback function that is called when DNS name is resolved + * (or on timeout). A waiting application thread is waked up by + * signaling the semaphore. + */ +static void +do_dns_found(const char *name, ip_addr_t *ipaddr, void *arg) +{ + struct dns_api_msg *msg = (struct dns_api_msg*)arg; + + LWIP_ASSERT("DNS response for wrong host name", strcmp(msg->name, name) == 0); + LWIP_UNUSED_ARG(name); + + if (ipaddr == NULL) { + /* timeout or memory error */ + *msg->err = ERR_VAL; + } else { + /* address was resolved */ + *msg->err = ERR_OK; + *msg->addr = *ipaddr; + } + /* wake up the application task waiting in netconn_gethostbyname */ + sys_sem_signal(msg->sem); +} + +/** + * Execute a DNS query + * Called from netconn_gethostbyname + * + * @param arg the dns_api_msg pointing to the query + */ +void +do_gethostbyname(void *arg) +{ + struct dns_api_msg *msg = (struct dns_api_msg*)arg; + + *msg->err = dns_gethostbyname(msg->name, msg->addr, do_dns_found, msg); + if (*msg->err != ERR_INPROGRESS) { + /* on error or immediate success, wake up the application + * task waiting in netconn_gethostbyname */ + sys_sem_signal(msg->sem); + } +} +#endif /* LWIP_DNS */ + +#endif /* LWIP_NETCONN */ diff --git a/features/unsupported/net/lwip/lwip/api/err.c b/features/unsupported/net/lwip/lwip/api/err.c new file mode 100644 index 00000000000..92fa8b7dba1 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/api/err.c @@ -0,0 +1,75 @@ +/** + * @file + * Error Management module + * + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ + +#include "lwip/err.h" + +#ifdef LWIP_DEBUG + +static const char *err_strerr[] = { + "Ok.", /* ERR_OK 0 */ + "Out of memory error.", /* ERR_MEM -1 */ + "Buffer error.", /* ERR_BUF -2 */ + "Timeout.", /* ERR_TIMEOUT -3 */ + "Routing problem.", /* ERR_RTE -4 */ + "Operation in progress.", /* ERR_INPROGRESS -5 */ + "Illegal value.", /* ERR_VAL -6 */ + "Operation would block.", /* ERR_WOULDBLOCK -7 */ + "Address in use.", /* ERR_USE -8 */ + "Already connected.", /* ERR_ISCONN -9 */ + "Connection aborted.", /* ERR_ABRT -10 */ + "Connection reset.", /* ERR_RST -11 */ + "Connection closed.", /* ERR_CLSD -12 */ + "Not connected.", /* ERR_CONN -13 */ + "Illegal argument.", /* ERR_ARG -14 */ + "Low-level netif error.", /* ERR_IF -15 */ +}; + +/** + * Convert an lwip internal error to a string representation. + * + * @param err an lwip internal err_t + * @return a string representation for err + */ +const char * +lwip_strerr(err_t err) +{ + return err_strerr[-err]; + +} + +#endif /* LWIP_DEBUG */ diff --git a/features/unsupported/net/lwip/lwip/api/netbuf.c b/features/unsupported/net/lwip/lwip/api/netbuf.c new file mode 100644 index 00000000000..9390c9ee983 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/api/netbuf.c @@ -0,0 +1,245 @@ +/** + * @file + * Network buffer management + * + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ + +#include "lwip/opt.h" + +#if LWIP_NETCONN /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/netbuf.h" +#include "lwip/memp.h" + +#include + +/** + * Create (allocate) and initialize a new netbuf. + * The netbuf doesn't yet contain a packet buffer! + * + * @return a pointer to a new netbuf + * NULL on lack of memory + */ +struct +netbuf *netbuf_new(void) +{ + struct netbuf *buf; + + buf = (struct netbuf *)memp_malloc(MEMP_NETBUF); + if (buf != NULL) { + buf->p = NULL; + buf->ptr = NULL; + ip_addr_set_any(&buf->addr); + buf->port = 0; +#if LWIP_NETBUF_RECVINFO || LWIP_CHECKSUM_ON_COPY +#if LWIP_CHECKSUM_ON_COPY + buf->flags = 0; +#endif /* LWIP_CHECKSUM_ON_COPY */ + buf->toport_chksum = 0; +#if LWIP_NETBUF_RECVINFO + ip_addr_set_any(&buf->toaddr); +#endif /* LWIP_NETBUF_RECVINFO */ +#endif /* LWIP_NETBUF_RECVINFO || LWIP_CHECKSUM_ON_COPY */ + return buf; + } else { + return NULL; + } +} + +/** + * Deallocate a netbuf allocated by netbuf_new(). + * + * @param buf pointer to a netbuf allocated by netbuf_new() + */ +void +netbuf_delete(struct netbuf *buf) +{ + if (buf != NULL) { + if (buf->p != NULL) { + pbuf_free(buf->p); + buf->p = buf->ptr = NULL; + } + memp_free(MEMP_NETBUF, buf); + } +} + +/** + * Allocate memory for a packet buffer for a given netbuf. + * + * @param buf the netbuf for which to allocate a packet buffer + * @param size the size of the packet buffer to allocate + * @return pointer to the allocated memory + * NULL if no memory could be allocated + */ +void * +netbuf_alloc(struct netbuf *buf, u16_t size) +{ + LWIP_ERROR("netbuf_alloc: invalid buf", (buf != NULL), return NULL;); + + /* Deallocate any previously allocated memory. */ + if (buf->p != NULL) { + pbuf_free(buf->p); + } + buf->p = pbuf_alloc(PBUF_TRANSPORT, size, PBUF_RAM); + if (buf->p == NULL) { + return NULL; + } + LWIP_ASSERT("check that first pbuf can hold size", + (buf->p->len >= size)); + buf->ptr = buf->p; + return buf->p->payload; +} + +/** + * Free the packet buffer included in a netbuf + * + * @param buf pointer to the netbuf which contains the packet buffer to free + */ +void +netbuf_free(struct netbuf *buf) +{ + LWIP_ERROR("netbuf_free: invalid buf", (buf != NULL), return;); + if (buf->p != NULL) { + pbuf_free(buf->p); + } + buf->p = buf->ptr = NULL; +} + +/** + * Let a netbuf reference existing (non-volatile) data. + * + * @param buf netbuf which should reference the data + * @param dataptr pointer to the data to reference + * @param size size of the data + * @return ERR_OK if data is referenced + * ERR_MEM if data couldn't be referenced due to lack of memory + */ +err_t +netbuf_ref(struct netbuf *buf, const void *dataptr, u16_t size) +{ + LWIP_ERROR("netbuf_ref: invalid buf", (buf != NULL), return ERR_ARG;); + if (buf->p != NULL) { + pbuf_free(buf->p); + } + buf->p = pbuf_alloc(PBUF_TRANSPORT, 0, PBUF_REF); + if (buf->p == NULL) { + buf->ptr = NULL; + return ERR_MEM; + } + buf->p->payload = (void*)dataptr; + buf->p->len = buf->p->tot_len = size; + buf->ptr = buf->p; + return ERR_OK; +} + +/** + * Chain one netbuf to another (@see pbuf_chain) + * + * @param head the first netbuf + * @param tail netbuf to chain after head, freed by this function, may not be reference after returning + */ +void +netbuf_chain(struct netbuf *head, struct netbuf *tail) +{ + LWIP_ERROR("netbuf_ref: invalid head", (head != NULL), return;); + LWIP_ERROR("netbuf_chain: invalid tail", (tail != NULL), return;); + pbuf_cat(head->p, tail->p); + head->ptr = head->p; + memp_free(MEMP_NETBUF, tail); +} + +/** + * Get the data pointer and length of the data inside a netbuf. + * + * @param buf netbuf to get the data from + * @param dataptr pointer to a void pointer where to store the data pointer + * @param len pointer to an u16_t where the length of the data is stored + * @return ERR_OK if the information was retreived, + * ERR_BUF on error. + */ +err_t +netbuf_data(struct netbuf *buf, void **dataptr, u16_t *len) +{ + LWIP_ERROR("netbuf_data: invalid buf", (buf != NULL), return ERR_ARG;); + LWIP_ERROR("netbuf_data: invalid dataptr", (dataptr != NULL), return ERR_ARG;); + LWIP_ERROR("netbuf_data: invalid len", (len != NULL), return ERR_ARG;); + + if (buf->ptr == NULL) { + return ERR_BUF; + } + *dataptr = buf->ptr->payload; + *len = buf->ptr->len; + return ERR_OK; +} + +/** + * Move the current data pointer of a packet buffer contained in a netbuf + * to the next part. + * The packet buffer itself is not modified. + * + * @param buf the netbuf to modify + * @return -1 if there is no next part + * 1 if moved to the next part but now there is no next part + * 0 if moved to the next part and there are still more parts + */ +s8_t +netbuf_next(struct netbuf *buf) +{ + LWIP_ERROR("netbuf_free: invalid buf", (buf != NULL), return -1;); + if (buf->ptr->next == NULL) { + return -1; + } + buf->ptr = buf->ptr->next; + if (buf->ptr->next == NULL) { + return 1; + } + return 0; +} + +/** + * Move the current data pointer of a packet buffer contained in a netbuf + * to the beginning of the packet. + * The packet buffer itself is not modified. + * + * @param buf the netbuf to modify + */ +void +netbuf_first(struct netbuf *buf) +{ + LWIP_ERROR("netbuf_free: invalid buf", (buf != NULL), return;); + buf->ptr = buf->p; +} + +#endif /* LWIP_NETCONN */ diff --git a/features/unsupported/net/lwip/lwip/api/netdb.c b/features/unsupported/net/lwip/lwip/api/netdb.c new file mode 100644 index 00000000000..a7e4e06bca2 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/api/netdb.c @@ -0,0 +1,352 @@ +/** + * @file + * API functions for name resolving + * + */ + +/* + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Simon Goldschmidt + * + */ + +#include "lwip/netdb.h" + +#if LWIP_DNS && LWIP_SOCKET + +#include "lwip/err.h" +#include "lwip/mem.h" +#include "lwip/memp.h" +#include "lwip/ip_addr.h" +#include "lwip/api.h" +#include "lwip/dns.h" + +#include +#include + +/** helper struct for gethostbyname_r to access the char* buffer */ +struct gethostbyname_r_helper { + ip_addr_t *addrs; + ip_addr_t addr; + char *aliases; +}; + +/** h_errno is exported in netdb.h for access by applications. */ +#if LWIP_DNS_API_DECLARE_H_ERRNO +int h_errno; +#endif /* LWIP_DNS_API_DECLARE_H_ERRNO */ + +/** define "hostent" variables storage: 0 if we use a static (but unprotected) + * set of variables for lwip_gethostbyname, 1 if we use a local storage */ +#ifndef LWIP_DNS_API_HOSTENT_STORAGE +#define LWIP_DNS_API_HOSTENT_STORAGE 0 +#endif + +/** define "hostent" variables storage */ +#if LWIP_DNS_API_HOSTENT_STORAGE +#define HOSTENT_STORAGE +#else +#define HOSTENT_STORAGE static +#endif /* LWIP_DNS_API_STATIC_HOSTENT */ + +/** + * Returns an entry containing addresses of address family AF_INET + * for the host with name name. + * Due to dns_gethostbyname limitations, only one address is returned. + * + * @param name the hostname to resolve + * @return an entry containing addresses of address family AF_INET + * for the host with name name + */ +struct hostent* +lwip_gethostbyname(const char *name) +{ + err_t err; + ip_addr_t addr; + + /* buffer variables for lwip_gethostbyname() */ + HOSTENT_STORAGE struct hostent s_hostent; + HOSTENT_STORAGE char *s_aliases; + HOSTENT_STORAGE ip_addr_t s_hostent_addr; + HOSTENT_STORAGE ip_addr_t *s_phostent_addr[2]; + + /* query host IP address */ + err = netconn_gethostbyname(name, &addr); + if (err != ERR_OK) { + LWIP_DEBUGF(DNS_DEBUG, ("lwip_gethostbyname(%s) failed, err=%d\n", name, err)); + h_errno = HOST_NOT_FOUND; + return NULL; + } + + /* fill hostent */ + s_hostent_addr = addr; + s_phostent_addr[0] = &s_hostent_addr; + s_phostent_addr[1] = NULL; + s_hostent.h_name = (char*)name; + s_hostent.h_aliases = &s_aliases; + s_hostent.h_addrtype = AF_INET; + s_hostent.h_length = sizeof(ip_addr_t); + s_hostent.h_addr_list = (char**)&s_phostent_addr; + +#if DNS_DEBUG + /* dump hostent */ + LWIP_DEBUGF(DNS_DEBUG, ("hostent.h_name == %s\n", s_hostent.h_name)); + LWIP_DEBUGF(DNS_DEBUG, ("hostent.h_aliases == %p\n", s_hostent.h_aliases)); + if (s_hostent.h_aliases != NULL) { + u8_t idx; + for ( idx=0; s_hostent.h_aliases[idx]; idx++) { + LWIP_DEBUGF(DNS_DEBUG, ("hostent.h_aliases[%i]-> == %p\n", idx, s_hostent.h_aliases[idx])); + LWIP_DEBUGF(DNS_DEBUG, ("hostent.h_aliases[%i]-> == %s\n", idx, s_hostent.h_aliases[idx])); + } + } + LWIP_DEBUGF(DNS_DEBUG, ("hostent.h_addrtype == %d\n", s_hostent.h_addrtype)); + LWIP_DEBUGF(DNS_DEBUG, ("hostent.h_length == %d\n", s_hostent.h_length)); + LWIP_DEBUGF(DNS_DEBUG, ("hostent.h_addr_list == %p\n", s_hostent.h_addr_list)); + if (s_hostent.h_addr_list != NULL) { + u8_t idx; + for ( idx=0; s_hostent.h_addr_list[idx]; idx++) { + LWIP_DEBUGF(DNS_DEBUG, ("hostent.h_addr_list[%i] == %p\n", idx, s_hostent.h_addr_list[idx])); + LWIP_DEBUGF(DNS_DEBUG, ("hostent.h_addr_list[%i]-> == %s\n", idx, ip_ntoa((ip_addr_t*)s_hostent.h_addr_list[idx]))); + } + } +#endif /* DNS_DEBUG */ + +#if LWIP_DNS_API_HOSTENT_STORAGE + /* this function should return the "per-thread" hostent after copy from s_hostent */ + return sys_thread_hostent(&s_hostent); +#else + return &s_hostent; +#endif /* LWIP_DNS_API_HOSTENT_STORAGE */ +} + +/** + * Thread-safe variant of lwip_gethostbyname: instead of using a static + * buffer, this function takes buffer and errno pointers as arguments + * and uses these for the result. + * + * @param name the hostname to resolve + * @param ret pre-allocated struct where to store the result + * @param buf pre-allocated buffer where to store additional data + * @param buflen the size of buf + * @param result pointer to a hostent pointer that is set to ret on success + * and set to zero on error + * @param h_errnop pointer to an int where to store errors (instead of modifying + * the global h_errno) + * @return 0 on success, non-zero on error, additional error information + * is stored in *h_errnop instead of h_errno to be thread-safe + */ +int +lwip_gethostbyname_r(const char *name, struct hostent *ret, char *buf, + size_t buflen, struct hostent **result, int *h_errnop) +{ + err_t err; + struct gethostbyname_r_helper *h; + char *hostname; + size_t namelen; + int lh_errno; + + if (h_errnop == NULL) { + /* ensure h_errnop is never NULL */ + h_errnop = &lh_errno; + } + + if (result == NULL) { + /* not all arguments given */ + *h_errnop = EINVAL; + return -1; + } + /* first thing to do: set *result to nothing */ + *result = NULL; + if ((name == NULL) || (ret == NULL) || (buf == 0)) { + /* not all arguments given */ + *h_errnop = EINVAL; + return -1; + } + + namelen = strlen(name); + if (buflen < (sizeof(struct gethostbyname_r_helper) + namelen + 1 + (MEM_ALIGNMENT - 1))) { + /* buf can't hold the data needed + a copy of name */ + *h_errnop = ERANGE; + return -1; + } + + h = (struct gethostbyname_r_helper*)LWIP_MEM_ALIGN(buf); + hostname = ((char*)h) + sizeof(struct gethostbyname_r_helper); + + /* query host IP address */ + err = netconn_gethostbyname(name, &(h->addr)); + if (err != ERR_OK) { + LWIP_DEBUGF(DNS_DEBUG, ("lwip_gethostbyname(%s) failed, err=%d\n", name, err)); + *h_errnop = ENSRNOTFOUND; + return -1; + } + + /* copy the hostname into buf */ + MEMCPY(hostname, name, namelen); + hostname[namelen] = 0; + + /* fill hostent */ + h->addrs = &(h->addr); + h->aliases = NULL; + ret->h_name = (char*)hostname; + ret->h_aliases = &(h->aliases); + ret->h_addrtype = AF_INET; + ret->h_length = sizeof(ip_addr_t); + ret->h_addr_list = (char**)&(h->addrs); + + /* set result != NULL */ + *result = ret; + + /* return success */ + return 0; +} + +/** + * Frees one or more addrinfo structures returned by getaddrinfo(), along with + * any additional storage associated with those structures. If the ai_next field + * of the structure is not null, the entire list of structures is freed. + * + * @param ai struct addrinfo to free + */ +void +lwip_freeaddrinfo(struct addrinfo *ai) +{ + struct addrinfo *next; + + while (ai != NULL) { + next = ai->ai_next; + memp_free(MEMP_NETDB, ai); + ai = next; + } +} + +/** + * Translates the name of a service location (for example, a host name) and/or + * a service name and returns a set of socket addresses and associated + * information to be used in creating a socket with which to address the + * specified service. + * Memory for the result is allocated internally and must be freed by calling + * lwip_freeaddrinfo()! + * + * Due to a limitation in dns_gethostbyname, only the first address of a + * host is returned. + * Also, service names are not supported (only port numbers)! + * + * @param nodename descriptive name or address string of the host + * (may be NULL -> local address) + * @param servname port number as string of NULL + * @param hints structure containing input values that set socktype and protocol + * @param res pointer to a pointer where to store the result (set to NULL on failure) + * @return 0 on success, non-zero on failure + */ +int +lwip_getaddrinfo(const char *nodename, const char *servname, + const struct addrinfo *hints, struct addrinfo **res) +{ + err_t err; + ip_addr_t addr; + struct addrinfo *ai; + struct sockaddr_in *sa = NULL; + int port_nr = 0; + size_t total_size; + size_t namelen = 0; + + if (res == NULL) { + return EAI_FAIL; + } + *res = NULL; + if ((nodename == NULL) && (servname == NULL)) { + return EAI_NONAME; + } + + if (servname != NULL) { + /* service name specified: convert to port number + * @todo?: currently, only ASCII integers (port numbers) are supported! */ + port_nr = atoi(servname); + if ((port_nr <= 0) || (port_nr > 0xffff)) { + return EAI_SERVICE; + } + } + + if (nodename != NULL) { + /* service location specified, try to resolve */ + err = netconn_gethostbyname(nodename, &addr); + if (err != ERR_OK) { + return EAI_FAIL; + } + } else { + /* service location specified, use loopback address */ + ip_addr_set_loopback(&addr); + } + + total_size = sizeof(struct addrinfo) + sizeof(struct sockaddr_in); + if (nodename != NULL) { + namelen = strlen(nodename); + LWIP_ASSERT("namelen is too long", (namelen + 1) <= (mem_size_t)-1); + total_size += namelen + 1; + } + /* If this fails, please report to lwip-devel! :-) */ + LWIP_ASSERT("total_size <= NETDB_ELEM_SIZE: please report this!", + total_size <= NETDB_ELEM_SIZE); + ai = (struct addrinfo *)memp_malloc(MEMP_NETDB); + if (ai == NULL) { + goto memerr; + } + memset(ai, 0, total_size); + sa = (struct sockaddr_in*)((u8_t*)ai + sizeof(struct addrinfo)); + /* set up sockaddr */ + inet_addr_from_ipaddr(&sa->sin_addr, &addr); + sa->sin_family = AF_INET; + sa->sin_len = sizeof(struct sockaddr_in); + sa->sin_port = htons((u16_t)port_nr); + + /* set up addrinfo */ + ai->ai_family = AF_INET; + if (hints != NULL) { + /* copy socktype & protocol from hints if specified */ + ai->ai_socktype = hints->ai_socktype; + ai->ai_protocol = hints->ai_protocol; + } + if (nodename != NULL) { + /* copy nodename to canonname if specified */ + ai->ai_canonname = ((char*)ai + sizeof(struct addrinfo) + sizeof(struct sockaddr_in)); + MEMCPY(ai->ai_canonname, nodename, namelen); + ai->ai_canonname[namelen] = 0; + } + ai->ai_addrlen = sizeof(struct sockaddr_in); + ai->ai_addr = (struct sockaddr*)sa; + + *res = ai; + + return 0; +memerr: + if (ai != NULL) { + memp_free(MEMP_NETDB, ai); + } + return EAI_MEMORY; +} + +#endif /* LWIP_DNS && LWIP_SOCKET */ diff --git a/features/unsupported/net/lwip/lwip/api/netifapi.c b/features/unsupported/net/lwip/lwip/api/netifapi.c new file mode 100644 index 00000000000..43e47203a9a --- /dev/null +++ b/features/unsupported/net/lwip/lwip/api/netifapi.c @@ -0,0 +1,160 @@ +/** + * @file + * Network Interface Sequential API module + * + */ + +/* + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + */ + +#include "lwip/opt.h" + +#if LWIP_NETIF_API /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/netifapi.h" +#include "lwip/tcpip.h" + +/** + * Call netif_add() inside the tcpip_thread context. + */ +void +do_netifapi_netif_add(struct netifapi_msg_msg *msg) +{ + if (!netif_add( msg->netif, + msg->msg.add.ipaddr, + msg->msg.add.netmask, + msg->msg.add.gw, + msg->msg.add.state, + msg->msg.add.init, + msg->msg.add.input)) { + msg->err = ERR_IF; + } else { + msg->err = ERR_OK; + } + TCPIP_NETIFAPI_ACK(msg); +} + +/** + * Call netif_set_addr() inside the tcpip_thread context. + */ +void +do_netifapi_netif_set_addr(struct netifapi_msg_msg *msg) +{ + netif_set_addr( msg->netif, + msg->msg.add.ipaddr, + msg->msg.add.netmask, + msg->msg.add.gw); + msg->err = ERR_OK; + TCPIP_NETIFAPI_ACK(msg); +} + +/** + * Call the "errtfunc" (or the "voidfunc" if "errtfunc" is NULL) inside the + * tcpip_thread context. + */ +void +do_netifapi_netif_common(struct netifapi_msg_msg *msg) +{ + if (msg->msg.common.errtfunc != NULL) { + msg->err = msg->msg.common.errtfunc(msg->netif); + } else { + msg->err = ERR_OK; + msg->msg.common.voidfunc(msg->netif); + } + TCPIP_NETIFAPI_ACK(msg); +} + +/** + * Call netif_add() in a thread-safe way by running that function inside the + * tcpip_thread context. + * + * @note for params @see netif_add() + */ +err_t +netifapi_netif_add(struct netif *netif, + ip_addr_t *ipaddr, + ip_addr_t *netmask, + ip_addr_t *gw, + void *state, + netif_init_fn init, + netif_input_fn input) +{ + struct netifapi_msg msg; + msg.function = do_netifapi_netif_add; + msg.msg.netif = netif; + msg.msg.msg.add.ipaddr = ipaddr; + msg.msg.msg.add.netmask = netmask; + msg.msg.msg.add.gw = gw; + msg.msg.msg.add.state = state; + msg.msg.msg.add.init = init; + msg.msg.msg.add.input = input; + TCPIP_NETIFAPI(&msg); + return msg.msg.err; +} + +/** + * Call netif_set_addr() in a thread-safe way by running that function inside the + * tcpip_thread context. + * + * @note for params @see netif_set_addr() + */ +err_t +netifapi_netif_set_addr(struct netif *netif, + ip_addr_t *ipaddr, + ip_addr_t *netmask, + ip_addr_t *gw) +{ + struct netifapi_msg msg; + msg.function = do_netifapi_netif_set_addr; + msg.msg.netif = netif; + msg.msg.msg.add.ipaddr = ipaddr; + msg.msg.msg.add.netmask = netmask; + msg.msg.msg.add.gw = gw; + TCPIP_NETIFAPI(&msg); + return msg.msg.err; +} + +/** + * call the "errtfunc" (or the "voidfunc" if "errtfunc" is NULL) in a thread-safe + * way by running that function inside the tcpip_thread context. + * + * @note use only for functions where there is only "netif" parameter. + */ +err_t +netifapi_netif_common(struct netif *netif, netifapi_void_fn voidfunc, + netifapi_errt_fn errtfunc) +{ + struct netifapi_msg msg; + msg.function = do_netifapi_netif_common; + msg.msg.netif = netif; + msg.msg.msg.common.voidfunc = voidfunc; + msg.msg.msg.common.errtfunc = errtfunc; + TCPIP_NETIFAPI(&msg); + return msg.msg.err; +} + +#endif /* LWIP_NETIF_API */ diff --git a/features/unsupported/net/lwip/lwip/api/sockets.c b/features/unsupported/net/lwip/lwip/api/sockets.c new file mode 100644 index 00000000000..e36012ce43b --- /dev/null +++ b/features/unsupported/net/lwip/lwip/api/sockets.c @@ -0,0 +1,2347 @@ +/** + * @file + * Sockets BSD-Like API module + * + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + * Improved by Marc Boucher and David Haas + * + */ + +#include "lwip/opt.h" + +#if LWIP_SOCKET /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/sockets.h" +#include "lwip/api.h" +#include "lwip/sys.h" +#include "lwip/igmp.h" +#include "lwip/inet.h" +#include "lwip/tcp.h" +#include "lwip/raw.h" +#include "lwip/udp.h" +#include "lwip/tcpip.h" +#include "lwip/pbuf.h" +#if LWIP_CHECKSUM_ON_COPY +#include "lwip/inet_chksum.h" +#endif + +#include + +#define NUM_SOCKETS MEMP_NUM_NETCONN + +/** Contains all internal pointers and states used for a socket */ +struct lwip_sock { + /** sockets currently are built on netconns, each socket has one netconn */ + struct netconn *conn; + /** data that was left from the previous read */ + void *lastdata; + /** offset in the data that was left from the previous read */ + u16_t lastoffset; + /** number of times data was received, set by event_callback(), + tested by the receive and select functions */ + s16_t rcvevent; + /** number of times data was ACKed (free send buffer), set by event_callback(), + tested by select */ + u16_t sendevent; + /** error happened for this socket, set by event_callback(), tested by select */ + u16_t errevent; + /** last error that occurred on this socket */ + int err; + /** counter of how many threads are waiting for this socket using select */ + int select_waiting; +}; + +/** Description for a task waiting in select */ +struct lwip_select_cb { + /** Pointer to the next waiting task */ + struct lwip_select_cb *next; + /** Pointer to the previous waiting task */ + struct lwip_select_cb *prev; + /** readset passed to select */ + fd_set *readset; + /** writeset passed to select */ + fd_set *writeset; + /** unimplemented: exceptset passed to select */ + fd_set *exceptset; + /** don't signal the same semaphore twice: set to 1 when signalled */ + int sem_signalled; + /** semaphore to wake up a task waiting for select */ + sys_sem_t sem; +}; + +/** This struct is used to pass data to the set/getsockopt_internal + * functions running in tcpip_thread context (only a void* is allowed) */ +struct lwip_setgetsockopt_data { + /** socket struct for which to change options */ + struct lwip_sock *sock; +#ifdef LWIP_DEBUG + /** socket index for which to change options */ + int s; +#endif /* LWIP_DEBUG */ + /** level of the option to process */ + int level; + /** name of the option to process */ + int optname; + /** set: value to set the option to + * get: value of the option is stored here */ + void *optval; + /** size of *optval */ + socklen_t *optlen; + /** if an error occures, it is temporarily stored here */ + err_t err; +}; + +/** The global array of available sockets */ +static struct lwip_sock sockets[NUM_SOCKETS]; +/** The global list of tasks waiting for select */ +static struct lwip_select_cb *select_cb_list; +/** This counter is increased from lwip_select when the list is chagned + and checked in event_callback to see if it has changed. */ +static volatile int select_cb_ctr; + +/** Table to quickly map an lwIP error (err_t) to a socket error + * by using -err as an index */ +static const int err_to_errno_table[] = { + 0, /* ERR_OK 0 No error, everything OK. */ + ENOMEM, /* ERR_MEM -1 Out of memory error. */ + ENOBUFS, /* ERR_BUF -2 Buffer error. */ + EWOULDBLOCK, /* ERR_TIMEOUT -3 Timeout */ + EHOSTUNREACH, /* ERR_RTE -4 Routing problem. */ + EINPROGRESS, /* ERR_INPROGRESS -5 Operation in progress */ + EINVAL, /* ERR_VAL -6 Illegal value. */ + EWOULDBLOCK, /* ERR_WOULDBLOCK -7 Operation would block. */ + EADDRINUSE, /* ERR_USE -8 Address in use. */ + EALREADY, /* ERR_ISCONN -9 Already connected. */ + ECONNABORTED, /* ERR_ABRT -10 Connection aborted. */ + ECONNRESET, /* ERR_RST -11 Connection reset. */ + ENOTCONN, /* ERR_CLSD -12 Connection closed. */ + ENOTCONN, /* ERR_CONN -13 Not connected. */ + EIO, /* ERR_ARG -14 Illegal argument. */ + -1, /* ERR_IF -15 Low-level netif error */ +}; + +#define ERR_TO_ERRNO_TABLE_SIZE \ + (sizeof(err_to_errno_table)/sizeof(err_to_errno_table[0])) + +#define err_to_errno(err) \ + ((unsigned)(-(err)) < ERR_TO_ERRNO_TABLE_SIZE ? \ + err_to_errno_table[-(err)] : EIO) + +#ifdef ERRNO +#ifndef set_errno +#define set_errno(err) errno = (err) +#endif +#else /* ERRNO */ +#define set_errno(err) +#endif /* ERRNO */ + +#define sock_set_errno(sk, e) do { \ + sk->err = (e); \ + set_errno(sk->err); \ +} while (0) + +/* Forward delcaration of some functions */ +static void event_callback(struct netconn *conn, enum netconn_evt evt, u16_t len); +static void lwip_getsockopt_internal(void *arg); +static void lwip_setsockopt_internal(void *arg); + +/** + * Initialize this module. This function has to be called before any other + * functions in this module! + */ +void +lwip_socket_init(void) +{ +} + +/** + * Map a externally used socket index to the internal socket representation. + * + * @param s externally used socket index + * @return struct lwip_sock for the socket or NULL if not found + */ +static struct lwip_sock * +get_socket(int s) +{ + struct lwip_sock *sock; + + if ((s < 0) || (s >= NUM_SOCKETS)) { + LWIP_DEBUGF(SOCKETS_DEBUG, ("get_socket(%d): invalid\n", s)); + set_errno(EBADF); + return NULL; + } + + sock = &sockets[s]; + + if (!sock->conn) { + LWIP_DEBUGF(SOCKETS_DEBUG, ("get_socket(%d): not active\n", s)); + set_errno(EBADF); + return NULL; + } + + return sock; +} + +/** + * Same as get_socket but doesn't set errno + * + * @param s externally used socket index + * @return struct lwip_sock for the socket or NULL if not found + */ +static struct lwip_sock * +tryget_socket(int s) +{ + if ((s < 0) || (s >= NUM_SOCKETS)) { + return NULL; + } + if (!sockets[s].conn) { + return NULL; + } + return &sockets[s]; +} + +/** + * Allocate a new socket for a given netconn. + * + * @param newconn the netconn for which to allocate a socket + * @param accepted 1 if socket has been created by accept(), + * 0 if socket has been created by socket() + * @return the index of the new socket; -1 on error + */ +static int +alloc_socket(struct netconn *newconn, int accepted) +{ + int i; + SYS_ARCH_DECL_PROTECT(lev); + + /* allocate a new socket identifier */ + for (i = 0; i < NUM_SOCKETS; ++i) { + /* Protect socket array */ + SYS_ARCH_PROTECT(lev); + if (!sockets[i].conn) { + sockets[i].conn = newconn; + /* The socket is not yet known to anyone, so no need to protect + after having marked it as used. */ + SYS_ARCH_UNPROTECT(lev); + sockets[i].lastdata = NULL; + sockets[i].lastoffset = 0; + sockets[i].rcvevent = 0; + /* TCP sendbuf is empty, but the socket is not yet writable until connected + * (unless it has been created by accept()). */ + sockets[i].sendevent = (newconn->type == NETCONN_TCP ? (accepted != 0) : 1); + sockets[i].errevent = 0; + sockets[i].err = 0; + sockets[i].select_waiting = 0; + return i; + } + SYS_ARCH_UNPROTECT(lev); + } + return -1; +} + +/** Free a socket. The socket's netconn must have been + * delete before! + * + * @param sock the socket to free + * @param is_tcp != 0 for TCP sockets, used to free lastdata + */ +static void +free_socket(struct lwip_sock *sock, int is_tcp) +{ + void *lastdata; + SYS_ARCH_DECL_PROTECT(lev); + + lastdata = sock->lastdata; + sock->lastdata = NULL; + sock->lastoffset = 0; + sock->err = 0; + + /* Protect socket array */ + SYS_ARCH_PROTECT(lev); + sock->conn = NULL; + SYS_ARCH_UNPROTECT(lev); + /* don't use 'sock' after this line, as another task might have allocated it */ + + if (lastdata != NULL) { + if (is_tcp) { + pbuf_free((struct pbuf *)lastdata); + } else { + netbuf_delete((struct netbuf *)lastdata); + } + } +} + +/* Below this, the well-known socket functions are implemented. + * Use google.com or opengroup.org to get a good description :-) + * + * Exceptions are documented! + */ + +int +lwip_accept(int s, struct sockaddr *addr, socklen_t *addrlen) +{ + struct lwip_sock *sock, *nsock; + struct netconn *newconn; + ip_addr_t naddr; + u16_t port; + int newsock; + struct sockaddr_in sin; + err_t err; + SYS_ARCH_DECL_PROTECT(lev); + + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_accept(%d)...\n", s)); + sock = get_socket(s); + if (!sock) { + return -1; + } + + if (netconn_is_nonblocking(sock->conn) && (sock->rcvevent <= 0)) { + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_accept(%d): returning EWOULDBLOCK\n", s)); + sock_set_errno(sock, EWOULDBLOCK); + return -1; + } + + /* wait for a new connection */ + err = netconn_accept(sock->conn, &newconn); + if (err != ERR_OK) { + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_accept(%d): netconn_acept failed, err=%d\n", s, err)); + sock_set_errno(sock, err_to_errno(err)); + return -1; + } + LWIP_ASSERT("newconn != NULL", newconn != NULL); + /* Prevent automatic window updates, we do this on our own! */ + netconn_set_noautorecved(newconn, 1); + + /* get the IP address and port of the remote host */ + err = netconn_peer(newconn, &naddr, &port); + if (err != ERR_OK) { + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_accept(%d): netconn_peer failed, err=%d\n", s, err)); + netconn_delete(newconn); + sock_set_errno(sock, err_to_errno(err)); + return -1; + } + + /* Note that POSIX only requires us to check addr is non-NULL. addrlen must + * not be NULL if addr is valid. + */ + if (NULL != addr) { + LWIP_ASSERT("addr valid but addrlen NULL", addrlen != NULL); + memset(&sin, 0, sizeof(sin)); + sin.sin_len = sizeof(sin); + sin.sin_family = AF_INET; + sin.sin_port = htons(port); + inet_addr_from_ipaddr(&sin.sin_addr, &naddr); + + if (*addrlen > sizeof(sin)) + *addrlen = sizeof(sin); + + MEMCPY(addr, &sin, *addrlen); + } + + newsock = alloc_socket(newconn, 1); + if (newsock == -1) { + netconn_delete(newconn); + sock_set_errno(sock, ENFILE); + return -1; + } + LWIP_ASSERT("invalid socket index", (newsock >= 0) && (newsock < NUM_SOCKETS)); + LWIP_ASSERT("newconn->callback == event_callback", newconn->callback == event_callback); + nsock = &sockets[newsock]; + + /* See event_callback: If data comes in right away after an accept, even + * though the server task might not have created a new socket yet. + * In that case, newconn->socket is counted down (newconn->socket--), + * so nsock->rcvevent is >= 1 here! + */ + SYS_ARCH_PROTECT(lev); + nsock->rcvevent += (s16_t)(-1 - newconn->socket); + newconn->socket = newsock; + SYS_ARCH_UNPROTECT(lev); + + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_accept(%d) returning new sock=%d addr=", s, newsock)); + ip_addr_debug_print(SOCKETS_DEBUG, &naddr); + LWIP_DEBUGF(SOCKETS_DEBUG, (" port=%"U16_F"\n", port)); + + sock_set_errno(sock, 0); + return newsock; +} + +int +lwip_bind(int s, const struct sockaddr *name, socklen_t namelen) +{ + struct lwip_sock *sock; + ip_addr_t local_addr; + u16_t local_port; + err_t err; + const struct sockaddr_in *name_in; + + sock = get_socket(s); + if (!sock) { + return -1; + } + + /* check size, familiy and alignment of 'name' */ + LWIP_ERROR("lwip_bind: invalid address", ((namelen == sizeof(struct sockaddr_in)) && + ((name->sa_family) == AF_INET) && ((((mem_ptr_t)name) % 4) == 0)), + sock_set_errno(sock, err_to_errno(ERR_ARG)); return -1;); + name_in = (const struct sockaddr_in *)(void*)name; + + inet_addr_to_ipaddr(&local_addr, &name_in->sin_addr); + local_port = name_in->sin_port; + + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_bind(%d, addr=", s)); + ip_addr_debug_print(SOCKETS_DEBUG, &local_addr); + LWIP_DEBUGF(SOCKETS_DEBUG, (" port=%"U16_F")\n", ntohs(local_port))); + + err = netconn_bind(sock->conn, &local_addr, ntohs(local_port)); + + if (err != ERR_OK) { + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_bind(%d) failed, err=%d\n", s, err)); + sock_set_errno(sock, err_to_errno(err)); + return -1; + } + + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_bind(%d) succeeded\n", s)); + sock_set_errno(sock, 0); + return 0; +} + +int +lwip_close(int s) +{ + struct lwip_sock *sock; + int is_tcp = 0; + + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_close(%d)\n", s)); + + sock = get_socket(s); + if (!sock) { + return -1; + } + + if(sock->conn != NULL) { + is_tcp = netconn_type(sock->conn) == NETCONN_TCP; + } else { + LWIP_ASSERT("sock->lastdata == NULL", sock->lastdata == NULL); + } + + netconn_delete(sock->conn); + + free_socket(sock, is_tcp); + set_errno(0); + return 0; +} + +int +lwip_connect(int s, const struct sockaddr *name, socklen_t namelen) +{ + struct lwip_sock *sock; + err_t err; + const struct sockaddr_in *name_in; + + sock = get_socket(s); + if (!sock) { + return -1; + } + + /* check size, familiy and alignment of 'name' */ + LWIP_ERROR("lwip_connect: invalid address", ((namelen == sizeof(struct sockaddr_in)) && + ((name->sa_family) == AF_INET) && ((((mem_ptr_t)name) % 4) == 0)), + sock_set_errno(sock, err_to_errno(ERR_ARG)); return -1;); + name_in = (const struct sockaddr_in *)(void*)name; + + if (name_in->sin_family == AF_UNSPEC) { + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_connect(%d, AF_UNSPEC)\n", s)); + err = netconn_disconnect(sock->conn); + } else { + ip_addr_t remote_addr; + u16_t remote_port; + + inet_addr_to_ipaddr(&remote_addr, &name_in->sin_addr); + remote_port = name_in->sin_port; + + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_connect(%d, addr=", s)); + ip_addr_debug_print(SOCKETS_DEBUG, &remote_addr); + LWIP_DEBUGF(SOCKETS_DEBUG, (" port=%"U16_F")\n", ntohs(remote_port))); + + err = netconn_connect(sock->conn, &remote_addr, ntohs(remote_port)); + } + + if (err != ERR_OK) { + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_connect(%d) failed, err=%d\n", s, err)); + sock_set_errno(sock, err_to_errno(err)); + return -1; + } + + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_connect(%d) succeeded\n", s)); + sock_set_errno(sock, 0); + return 0; +} + +/** + * Set a socket into listen mode. + * The socket may not have been used for another connection previously. + * + * @param s the socket to set to listening mode + * @param backlog (ATTENTION: needs TCP_LISTEN_BACKLOG=1) + * @return 0 on success, non-zero on failure + */ +int +lwip_listen(int s, int backlog) +{ + struct lwip_sock *sock; + err_t err; + + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_listen(%d, backlog=%d)\n", s, backlog)); + + sock = get_socket(s); + if (!sock) { + return -1; + } + + /* limit the "backlog" parameter to fit in an u8_t */ + backlog = LWIP_MIN(LWIP_MAX(backlog, 0), 0xff); + + err = netconn_listen_with_backlog(sock->conn, (u8_t)backlog); + + if (err != ERR_OK) { + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_listen(%d) failed, err=%d\n", s, err)); + sock_set_errno(sock, err_to_errno(err)); + return -1; + } + + sock_set_errno(sock, 0); + return 0; +} + +int +lwip_recvfrom(int s, void *mem, size_t len, int flags, + struct sockaddr *from, socklen_t *fromlen) +{ + struct lwip_sock *sock; + void *buf = NULL; + struct pbuf *p; + u16_t buflen, copylen; + int off = 0; + ip_addr_t *addr; + u16_t port; + u8_t done = 0; + err_t err; + + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_recvfrom(%d, %p, %"SZT_F", 0x%x, ..)\n", s, mem, len, flags)); + sock = get_socket(s); + if (!sock) { + return -1; + } + + do { + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_recvfrom: top while sock->lastdata=%p\n", sock->lastdata)); + /* Check if there is data left from the last recv operation. */ + if (sock->lastdata) { + buf = sock->lastdata; + } else { + /* If this is non-blocking call, then check first */ + if (((flags & MSG_DONTWAIT) || netconn_is_nonblocking(sock->conn)) && + (sock->rcvevent <= 0)) { + if (off > 0) { + /* update receive window */ + netconn_recved(sock->conn, (u32_t)off); + /* already received data, return that */ + sock_set_errno(sock, 0); + return off; + } + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_recvfrom(%d): returning EWOULDBLOCK\n", s)); + sock_set_errno(sock, EWOULDBLOCK); + return -1; + } + + /* No data was left from the previous operation, so we try to get + some from the network. */ + if (netconn_type(sock->conn) == NETCONN_TCP) { + err = netconn_recv_tcp_pbuf(sock->conn, (struct pbuf **)&buf); + } else { + err = netconn_recv(sock->conn, (struct netbuf **)&buf); + } + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_recvfrom: netconn_recv err=%d, netbuf=%p\n", + err, buf)); + + if (err != ERR_OK) { + if (off > 0) { + /* update receive window */ + netconn_recved(sock->conn, (u32_t)off); + /* already received data, return that */ + sock_set_errno(sock, 0); + return off; + } + /* We should really do some error checking here. */ + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_recvfrom(%d): buf == NULL, error is \"%s\"!\n", + s, lwip_strerr(err))); + sock_set_errno(sock, err_to_errno(err)); + if (err == ERR_CLSD) { + return 0; + } else { + return -1; + } + } + LWIP_ASSERT("buf != NULL", buf != NULL); + sock->lastdata = buf; + } + + if (netconn_type(sock->conn) == NETCONN_TCP) { + p = (struct pbuf *)buf; + } else { + p = ((struct netbuf *)buf)->p; + } + buflen = p->tot_len; + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_recvfrom: buflen=%"U16_F" len=%"SZT_F" off=%d sock->lastoffset=%"U16_F"\n", + buflen, len, off, sock->lastoffset)); + + buflen -= sock->lastoffset; + + if (len > buflen) { + copylen = buflen; + } else { + copylen = (u16_t)len; + } + + /* copy the contents of the received buffer into + the supplied memory pointer mem */ + pbuf_copy_partial(p, (u8_t*)mem + off, copylen, sock->lastoffset); + + off += copylen; + + if (netconn_type(sock->conn) == NETCONN_TCP) { + LWIP_ASSERT("invalid copylen, len would underflow", len >= copylen); + len -= copylen; + if ( (len <= 0) || + (p->flags & PBUF_FLAG_PUSH) || + (sock->rcvevent <= 0) || + ((flags & MSG_PEEK)!=0)) { + done = 1; + } + } else { + done = 1; + } + + /* Check to see from where the data was.*/ + if (done) { + ip_addr_t fromaddr; + if (from && fromlen) { + struct sockaddr_in sin; + + if (netconn_type(sock->conn) == NETCONN_TCP) { + addr = &fromaddr; + netconn_getaddr(sock->conn, addr, &port, 0); + } else { + addr = netbuf_fromaddr((struct netbuf *)buf); + port = netbuf_fromport((struct netbuf *)buf); + } + + memset(&sin, 0, sizeof(sin)); + sin.sin_len = sizeof(sin); + sin.sin_family = AF_INET; + sin.sin_port = htons(port); + inet_addr_from_ipaddr(&sin.sin_addr, addr); + + if (*fromlen > sizeof(sin)) { + *fromlen = sizeof(sin); + } + + MEMCPY(from, &sin, *fromlen); + + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_recvfrom(%d): addr=", s)); + ip_addr_debug_print(SOCKETS_DEBUG, addr); + LWIP_DEBUGF(SOCKETS_DEBUG, (" port=%"U16_F" len=%d\n", port, off)); + } else { +#if SOCKETS_DEBUG + if (netconn_type(sock->conn) == NETCONN_TCP) { + addr = &fromaddr; + netconn_getaddr(sock->conn, addr, &port, 0); + } else { + addr = netbuf_fromaddr((struct netbuf *)buf); + port = netbuf_fromport((struct netbuf *)buf); + } + + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_recvfrom(%d): addr=", s)); + ip_addr_debug_print(SOCKETS_DEBUG, addr); + LWIP_DEBUGF(SOCKETS_DEBUG, (" port=%"U16_F" len=%d\n", port, off)); +#endif /* SOCKETS_DEBUG */ + } + } + + /* If we don't peek the incoming message... */ + if ((flags & MSG_PEEK) == 0) { + /* If this is a TCP socket, check if there is data left in the + buffer. If so, it should be saved in the sock structure for next + time around. */ + if ((netconn_type(sock->conn) == NETCONN_TCP) && (buflen - copylen > 0)) { + sock->lastdata = buf; + sock->lastoffset += copylen; + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_recvfrom: lastdata now netbuf=%p\n", buf)); + } else { + sock->lastdata = NULL; + sock->lastoffset = 0; + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_recvfrom: deleting netbuf=%p\n", buf)); + if (netconn_type(sock->conn) == NETCONN_TCP) { + pbuf_free((struct pbuf *)buf); + } else { + netbuf_delete((struct netbuf *)buf); + } + } + } + } while (!done); + + if (off > 0) { + /* update receive window */ + netconn_recved(sock->conn, (u32_t)off); + } + sock_set_errno(sock, 0); + return off; +} + +int +lwip_read(int s, void *mem, size_t len) +{ + return lwip_recvfrom(s, mem, len, 0, NULL, NULL); +} + +int +lwip_recv(int s, void *mem, size_t len, int flags) +{ + return lwip_recvfrom(s, mem, len, flags, NULL, NULL); +} + +int +lwip_send(int s, const void *data, size_t size, int flags) +{ + struct lwip_sock *sock; + err_t err; + u8_t write_flags; + + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_send(%d, data=%p, size=%"SZT_F", flags=0x%x)\n", + s, data, size, flags)); + + sock = get_socket(s); + if (!sock) { + return -1; + } + + if (sock->conn->type != NETCONN_TCP) { +#if (LWIP_UDP || LWIP_RAW) + return lwip_sendto(s, data, size, flags, NULL, 0); +#else /* (LWIP_UDP || LWIP_RAW) */ + sock_set_errno(sock, err_to_errno(ERR_ARG)); + return -1; +#endif /* (LWIP_UDP || LWIP_RAW) */ + } + + if ((flags & MSG_DONTWAIT) || netconn_is_nonblocking(sock->conn)) { + if ((size > TCP_SND_BUF) || ((size / TCP_MSS) > TCP_SND_QUEUELEN)) { + /* too much data to ever send nonblocking! */ + sock_set_errno(sock, EMSGSIZE); + return -1; + } + } + + write_flags = NETCONN_COPY | + ((flags & MSG_MORE) ? NETCONN_MORE : 0) | + ((flags & MSG_DONTWAIT) ? NETCONN_DONTBLOCK : 0); + err = netconn_write(sock->conn, data, size, write_flags); + + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_send(%d) err=%d size=%"SZT_F"\n", s, err, size)); + sock_set_errno(sock, err_to_errno(err)); + return (err == ERR_OK ? (int)size : -1); +} + +int +lwip_sendto(int s, const void *data, size_t size, int flags, + const struct sockaddr *to, socklen_t tolen) +{ + struct lwip_sock *sock; + err_t err; + u16_t short_size; + const struct sockaddr_in *to_in; + u16_t remote_port; +#if !LWIP_TCPIP_CORE_LOCKING + struct netbuf buf; +#endif + + sock = get_socket(s); + if (!sock) { + return -1; + } + + if (sock->conn->type == NETCONN_TCP) { +#if LWIP_TCP + return lwip_send(s, data, size, flags); +#else /* LWIP_TCP */ + LWIP_UNUSED_ARG(flags); + sock_set_errno(sock, err_to_errno(ERR_ARG)); + return -1; +#endif /* LWIP_TCP */ + } + + /* @todo: split into multiple sendto's? */ + LWIP_ASSERT("lwip_sendto: size must fit in u16_t", size <= 0xffff); + short_size = (u16_t)size; + LWIP_ERROR("lwip_sendto: invalid address", (((to == NULL) && (tolen == 0)) || + ((tolen == sizeof(struct sockaddr_in)) && + ((to->sa_family) == AF_INET) && ((((mem_ptr_t)to) % 4) == 0))), + sock_set_errno(sock, err_to_errno(ERR_ARG)); return -1;); + to_in = (const struct sockaddr_in *)(void*)to; + +#if LWIP_TCPIP_CORE_LOCKING + /* Should only be consider like a sample or a simple way to experiment this option (no check of "to" field...) */ + { + struct pbuf* p; + ip_addr_t *remote_addr; + +#if LWIP_NETIF_TX_SINGLE_PBUF + p = pbuf_alloc(PBUF_TRANSPORT, short_size, PBUF_RAM); + if (p != NULL) { +#if LWIP_CHECKSUM_ON_COPY + u16_t chksum = 0; + if (sock->conn->type != NETCONN_RAW) { + chksum = LWIP_CHKSUM_COPY(p->payload, data, short_size); + } else +#endif /* LWIP_CHECKSUM_ON_COPY */ + MEMCPY(p->payload, data, size); +#else /* LWIP_NETIF_TX_SINGLE_PBUF */ + p = pbuf_alloc(PBUF_TRANSPORT, short_size, PBUF_REF); + if (p != NULL) { + p->payload = (void*)data; +#endif /* LWIP_NETIF_TX_SINGLE_PBUF */ + + if (to_in != NULL) { + inet_addr_to_ipaddr_p(remote_addr, &to_in->sin_addr); + remote_port = ntohs(to_in->sin_port); + } else { + remote_addr = &sock->conn->pcb.raw->remote_ip; + if (sock->conn->type == NETCONN_RAW) { + remote_port = 0; + } else { + remote_port = sock->conn->pcb.udp->remote_port; + } + } + + LOCK_TCPIP_CORE(); + if (sock->conn->type == NETCONN_RAW) { + err = sock->conn->last_err = raw_sendto(sock->conn->pcb.raw, p, remote_addr); + } else { +#if LWIP_UDP +#if LWIP_CHECKSUM_ON_COPY && LWIP_NETIF_TX_SINGLE_PBUF + err = sock->conn->last_err = udp_sendto_chksum(sock->conn->pcb.udp, p, + remote_addr, remote_port, 1, chksum); +#else /* LWIP_CHECKSUM_ON_COPY && LWIP_NETIF_TX_SINGLE_PBUF */ + err = sock->conn->last_err = udp_sendto(sock->conn->pcb.udp, p, + remote_addr, remote_port); +#endif /* LWIP_CHECKSUM_ON_COPY && LWIP_NETIF_TX_SINGLE_PBUF */ +#else /* LWIP_UDP */ + err = ERR_ARG; +#endif /* LWIP_UDP */ + } + UNLOCK_TCPIP_CORE(); + + pbuf_free(p); + } else { + err = ERR_MEM; + } + } +#else /* LWIP_TCPIP_CORE_LOCKING */ + /* initialize a buffer */ + buf.p = buf.ptr = NULL; +#if LWIP_CHECKSUM_ON_COPY + buf.flags = 0; +#endif /* LWIP_CHECKSUM_ON_COPY */ + if (to) { + inet_addr_to_ipaddr(&buf.addr, &to_in->sin_addr); + remote_port = ntohs(to_in->sin_port); + netbuf_fromport(&buf) = remote_port; + } else { + remote_port = 0; + ip_addr_set_any(&buf.addr); + netbuf_fromport(&buf) = 0; + } + + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_sendto(%d, data=%p, short_size=%"U16_F", flags=0x%x to=", + s, data, short_size, flags)); + ip_addr_debug_print(SOCKETS_DEBUG, &buf.addr); + LWIP_DEBUGF(SOCKETS_DEBUG, (" port=%"U16_F"\n", remote_port)); + + /* make the buffer point to the data that should be sent */ +#if LWIP_NETIF_TX_SINGLE_PBUF + /* Allocate a new netbuf and copy the data into it. */ + if (netbuf_alloc(&buf, short_size) == NULL) { + err = ERR_MEM; + } else { +#if LWIP_CHECKSUM_ON_COPY + if (sock->conn->type != NETCONN_RAW) { + u16_t chksum = LWIP_CHKSUM_COPY(buf.p->payload, data, short_size); + netbuf_set_chksum(&buf, chksum); + err = ERR_OK; + } else +#endif /* LWIP_CHECKSUM_ON_COPY */ + { + err = netbuf_take(&buf, data, short_size); + } + } +#else /* LWIP_NETIF_TX_SINGLE_PBUF */ + err = netbuf_ref(&buf, data, short_size); +#endif /* LWIP_NETIF_TX_SINGLE_PBUF */ + if (err == ERR_OK) { + /* send the data */ + err = netconn_send(sock->conn, &buf); + } + + /* deallocated the buffer */ + netbuf_free(&buf); +#endif /* LWIP_TCPIP_CORE_LOCKING */ + sock_set_errno(sock, err_to_errno(err)); + return (err == ERR_OK ? short_size : -1); +} + +int +lwip_socket(int domain, int type, int protocol) +{ + struct netconn *conn; + int i; + + LWIP_UNUSED_ARG(domain); + + /* create a netconn */ + switch (type) { + case SOCK_RAW: + conn = netconn_new_with_proto_and_callback(NETCONN_RAW, (u8_t)protocol, event_callback); + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_socket(%s, SOCK_RAW, %d) = ", + domain == PF_INET ? "PF_INET" : "UNKNOWN", protocol)); + break; + case SOCK_DGRAM: + conn = netconn_new_with_callback( (protocol == IPPROTO_UDPLITE) ? + NETCONN_UDPLITE : NETCONN_UDP, event_callback); + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_socket(%s, SOCK_DGRAM, %d) = ", + domain == PF_INET ? "PF_INET" : "UNKNOWN", protocol)); + break; + case SOCK_STREAM: + conn = netconn_new_with_callback(NETCONN_TCP, event_callback); + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_socket(%s, SOCK_STREAM, %d) = ", + domain == PF_INET ? "PF_INET" : "UNKNOWN", protocol)); + if (conn != NULL) { + /* Prevent automatic window updates, we do this on our own! */ + netconn_set_noautorecved(conn, 1); + } + break; + default: + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_socket(%d, %d/UNKNOWN, %d) = -1\n", + domain, type, protocol)); + set_errno(EINVAL); + return -1; + } + + if (!conn) { + LWIP_DEBUGF(SOCKETS_DEBUG, ("-1 / ENOBUFS (could not create netconn)\n")); + set_errno(ENOBUFS); + return -1; + } + + i = alloc_socket(conn, 0); + + if (i == -1) { + netconn_delete(conn); + set_errno(ENFILE); + return -1; + } + conn->socket = i; + LWIP_DEBUGF(SOCKETS_DEBUG, ("%d\n", i)); + set_errno(0); + return i; +} + +int +lwip_write(int s, const void *data, size_t size) +{ + return lwip_send(s, data, size, 0); +} + +/** + * Go through the readset and writeset lists and see which socket of the sockets + * set in the sets has events. On return, readset, writeset and exceptset have + * the sockets enabled that had events. + * + * exceptset is not used for now!!! + * + * @param maxfdp1 the highest socket index in the sets + * @param readset_in: set of sockets to check for read events + * @param writeset_in: set of sockets to check for write events + * @param exceptset_in: set of sockets to check for error events + * @param readset_out: set of sockets that had read events + * @param writeset_out: set of sockets that had write events + * @param exceptset_out: set os sockets that had error events + * @return number of sockets that had events (read/write/exception) (>= 0) + */ +static int +lwip_selscan(int maxfdp1, fd_set *readset_in, fd_set *writeset_in, fd_set *exceptset_in, + fd_set *readset_out, fd_set *writeset_out, fd_set *exceptset_out) +{ + int i, nready = 0; + fd_set lreadset, lwriteset, lexceptset; + struct lwip_sock *sock; + SYS_ARCH_DECL_PROTECT(lev); + + FD_ZERO(&lreadset); + FD_ZERO(&lwriteset); + FD_ZERO(&lexceptset); + + /* Go through each socket in each list to count number of sockets which + currently match */ + for(i = 0; i < maxfdp1; i++) { + void* lastdata = NULL; + s16_t rcvevent = 0; + u16_t sendevent = 0; + u16_t errevent = 0; + /* First get the socket's status (protected)... */ + SYS_ARCH_PROTECT(lev); + sock = tryget_socket(i); + if (sock != NULL) { + lastdata = sock->lastdata; + rcvevent = sock->rcvevent; + sendevent = sock->sendevent; + errevent = sock->errevent; + } + SYS_ARCH_UNPROTECT(lev); + /* ... then examine it: */ + /* See if netconn of this socket is ready for read */ + if (readset_in && FD_ISSET(i, readset_in) && ((lastdata != NULL) || (rcvevent > 0))) { + FD_SET(i, &lreadset); + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_selscan: fd=%d ready for reading\n", i)); + nready++; + } + /* See if netconn of this socket is ready for write */ + if (writeset_in && FD_ISSET(i, writeset_in) && (sendevent != 0)) { + FD_SET(i, &lwriteset); + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_selscan: fd=%d ready for writing\n", i)); + nready++; + } + /* See if netconn of this socket had an error */ + if (exceptset_in && FD_ISSET(i, exceptset_in) && (errevent != 0)) { + FD_SET(i, &lexceptset); + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_selscan: fd=%d ready for exception\n", i)); + nready++; + } + } + /* copy local sets to the ones provided as arguments */ + *readset_out = lreadset; + *writeset_out = lwriteset; + *exceptset_out = lexceptset; + + LWIP_ASSERT("nready >= 0", nready >= 0); + return nready; +} + +/** + * Processing exceptset is not yet implemented. + */ +int +lwip_select(int maxfdp1, fd_set *readset, fd_set *writeset, fd_set *exceptset, + struct timeval *timeout) +{ + u32_t waitres = 0; + int nready; + fd_set lreadset, lwriteset, lexceptset; + u32_t msectimeout; + struct lwip_select_cb select_cb; + err_t err; + int i; + SYS_ARCH_DECL_PROTECT(lev); + + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_select(%d, %p, %p, %p, tvsec=%"S32_F" tvusec=%"S32_F")\n", + maxfdp1, (void *)readset, (void *) writeset, (void *) exceptset, + timeout ? (s32_t)timeout->tv_sec : (s32_t)-1, + timeout ? (s32_t)timeout->tv_usec : (s32_t)-1)); + + /* Go through each socket in each list to count number of sockets which + currently match */ + nready = lwip_selscan(maxfdp1, readset, writeset, exceptset, &lreadset, &lwriteset, &lexceptset); + + /* If we don't have any current events, then suspend if we are supposed to */ + if (!nready) { + if (timeout && timeout->tv_sec == 0 && timeout->tv_usec == 0) { + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_select: no timeout, returning 0\n")); + /* This is OK as the local fdsets are empty and nready is zero, + or we would have returned earlier. */ + goto return_copy_fdsets; + } + + /* None ready: add our semaphore to list: + We don't actually need any dynamic memory. Our entry on the + list is only valid while we are in this function, so it's ok + to use local variables. */ + + select_cb.next = NULL; + select_cb.prev = NULL; + select_cb.readset = readset; + select_cb.writeset = writeset; + select_cb.exceptset = exceptset; + select_cb.sem_signalled = 0; + err = sys_sem_new(&select_cb.sem, 0); + if (err != ERR_OK) { + /* failed to create semaphore */ + set_errno(ENOMEM); + return -1; + } + + /* Protect the select_cb_list */ + SYS_ARCH_PROTECT(lev); + + /* Put this select_cb on top of list */ + select_cb.next = select_cb_list; + if (select_cb_list != NULL) { + select_cb_list->prev = &select_cb; + } + select_cb_list = &select_cb; + /* Increasing this counter tells even_callback that the list has changed. */ + select_cb_ctr++; + + /* Now we can safely unprotect */ + SYS_ARCH_UNPROTECT(lev); + + /* Increase select_waiting for each socket we are interested in */ + for(i = 0; i < maxfdp1; i++) { + if ((readset && FD_ISSET(i, readset)) || + (writeset && FD_ISSET(i, writeset)) || + (exceptset && FD_ISSET(i, exceptset))) { + struct lwip_sock *sock = tryget_socket(i); + LWIP_ASSERT("sock != NULL", sock != NULL); + SYS_ARCH_PROTECT(lev); + sock->select_waiting++; + LWIP_ASSERT("sock->select_waiting > 0", sock->select_waiting > 0); + SYS_ARCH_UNPROTECT(lev); + } + } + + /* Call lwip_selscan again: there could have been events between + the last scan (whithout us on the list) and putting us on the list! */ + nready = lwip_selscan(maxfdp1, readset, writeset, exceptset, &lreadset, &lwriteset, &lexceptset); + if (!nready) { + /* Still none ready, just wait to be woken */ + if (timeout == 0) { + /* Wait forever */ + msectimeout = 0; + } else { + msectimeout = ((timeout->tv_sec * 1000) + ((timeout->tv_usec + 500)/1000)); + if (msectimeout == 0) { + /* Wait 1ms at least (0 means wait forever) */ + msectimeout = 1; + } + } + + waitres = sys_arch_sem_wait(&select_cb.sem, msectimeout); + } + /* Increase select_waiting for each socket we are interested in */ + for(i = 0; i < maxfdp1; i++) { + if ((readset && FD_ISSET(i, readset)) || + (writeset && FD_ISSET(i, writeset)) || + (exceptset && FD_ISSET(i, exceptset))) { + struct lwip_sock *sock = tryget_socket(i); + LWIP_ASSERT("sock != NULL", sock != NULL); + SYS_ARCH_PROTECT(lev); + sock->select_waiting--; + LWIP_ASSERT("sock->select_waiting >= 0", sock->select_waiting >= 0); + SYS_ARCH_UNPROTECT(lev); + } + } + /* Take us off the list */ + SYS_ARCH_PROTECT(lev); + if (select_cb.next != NULL) { + select_cb.next->prev = select_cb.prev; + } + if (select_cb_list == &select_cb) { + LWIP_ASSERT("select_cb.prev == NULL", select_cb.prev == NULL); + select_cb_list = select_cb.next; + } else { + LWIP_ASSERT("select_cb.prev != NULL", select_cb.prev != NULL); + select_cb.prev->next = select_cb.next; + } + /* Increasing this counter tells even_callback that the list has changed. */ + select_cb_ctr++; + SYS_ARCH_UNPROTECT(lev); + + sys_sem_free(&select_cb.sem); + if (waitres == SYS_ARCH_TIMEOUT) { + /* Timeout */ + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_select: timeout expired\n")); + /* This is OK as the local fdsets are empty and nready is zero, + or we would have returned earlier. */ + goto return_copy_fdsets; + } + + /* See what's set */ + nready = lwip_selscan(maxfdp1, readset, writeset, exceptset, &lreadset, &lwriteset, &lexceptset); + } + + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_select: nready=%d\n", nready)); +return_copy_fdsets: + set_errno(0); + if (readset) { + *readset = lreadset; + } + if (writeset) { + *writeset = lwriteset; + } + if (exceptset) { + *exceptset = lexceptset; + } + + + return nready; +} + +/** + * Callback registered in the netconn layer for each socket-netconn. + * Processes recvevent (data available) and wakes up tasks waiting for select. + */ +static void +event_callback(struct netconn *conn, enum netconn_evt evt, u16_t len) +{ + int s; + struct lwip_sock *sock; + struct lwip_select_cb *scb; + int last_select_cb_ctr; + SYS_ARCH_DECL_PROTECT(lev); + + LWIP_UNUSED_ARG(len); + + /* Get socket */ + if (conn) { + s = conn->socket; + if (s < 0) { + /* Data comes in right away after an accept, even though + * the server task might not have created a new socket yet. + * Just count down (or up) if that's the case and we + * will use the data later. Note that only receive events + * can happen before the new socket is set up. */ + SYS_ARCH_PROTECT(lev); + if (conn->socket < 0) { + if (evt == NETCONN_EVT_RCVPLUS) { + conn->socket--; + } + SYS_ARCH_UNPROTECT(lev); + return; + } + s = conn->socket; + SYS_ARCH_UNPROTECT(lev); + } + + sock = get_socket(s); + if (!sock) { + return; + } + } else { + return; + } + + SYS_ARCH_PROTECT(lev); + /* Set event as required */ + switch (evt) { + case NETCONN_EVT_RCVPLUS: + sock->rcvevent++; + break; + case NETCONN_EVT_RCVMINUS: + sock->rcvevent--; + break; + case NETCONN_EVT_SENDPLUS: + sock->sendevent = 1; + break; + case NETCONN_EVT_SENDMINUS: + sock->sendevent = 0; + break; + case NETCONN_EVT_ERROR: + sock->errevent = 1; + break; + default: + LWIP_ASSERT("unknown event", 0); + break; + } + + if (sock->select_waiting == 0) { + /* noone is waiting for this socket, no need to check select_cb_list */ + SYS_ARCH_UNPROTECT(lev); + return; + } + + /* Now decide if anyone is waiting for this socket */ + /* NOTE: This code goes through the select_cb_list list multiple times + ONLY IF a select was actually waiting. We go through the list the number + of waiting select calls + 1. This list is expected to be small. */ + + /* At this point, SYS_ARCH is still protected! */ +again: + for (scb = select_cb_list; scb != NULL; scb = scb->next) { + if (scb->sem_signalled == 0) { + /* semaphore not signalled yet */ + int do_signal = 0; + /* Test this select call for our socket */ + if (sock->rcvevent > 0) { + if (scb->readset && FD_ISSET(s, scb->readset)) { + do_signal = 1; + } + } + if (sock->sendevent != 0) { + if (!do_signal && scb->writeset && FD_ISSET(s, scb->writeset)) { + do_signal = 1; + } + } + if (sock->errevent != 0) { + if (!do_signal && scb->exceptset && FD_ISSET(s, scb->exceptset)) { + do_signal = 1; + } + } + if (do_signal) { + scb->sem_signalled = 1; + /* Don't call SYS_ARCH_UNPROTECT() before signaling the semaphore, as this might + lead to the select thread taking itself off the list, invalidagin the semaphore. */ + sys_sem_signal(&scb->sem); + } + } + /* unlock interrupts with each step */ + last_select_cb_ctr = select_cb_ctr; + SYS_ARCH_UNPROTECT(lev); + /* this makes sure interrupt protection time is short */ + SYS_ARCH_PROTECT(lev); + if (last_select_cb_ctr != select_cb_ctr) { + /* someone has changed select_cb_list, restart at the beginning */ + goto again; + } + } + SYS_ARCH_UNPROTECT(lev); +} + +/** + * Unimplemented: Close one end of a full-duplex connection. + * Currently, the full connection is closed. + */ +int +lwip_shutdown(int s, int how) +{ + struct lwip_sock *sock; + err_t err; + u8_t shut_rx = 0, shut_tx = 0; + + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_shutdown(%d, how=%d)\n", s, how)); + + sock = get_socket(s); + if (!sock) { + return -1; + } + + if (sock->conn != NULL) { + if (netconn_type(sock->conn) != NETCONN_TCP) { + sock_set_errno(sock, EOPNOTSUPP); + return EOPNOTSUPP; + } + } else { + sock_set_errno(sock, ENOTCONN); + return ENOTCONN; + } + + if (how == SHUT_RD) { + shut_rx = 1; + } else if (how == SHUT_WR) { + shut_tx = 1; + } else if(how == SHUT_RDWR) { + shut_rx = 1; + shut_tx = 1; + } else { + sock_set_errno(sock, EINVAL); + return EINVAL; + } + err = netconn_shutdown(sock->conn, shut_rx, shut_tx); + + sock_set_errno(sock, err_to_errno(err)); + return (err == ERR_OK ? 0 : -1); +} + +static int +lwip_getaddrname(int s, struct sockaddr *name, socklen_t *namelen, u8_t local) +{ + struct lwip_sock *sock; + struct sockaddr_in sin; + ip_addr_t naddr; + + sock = get_socket(s); + if (!sock) { + return -1; + } + + memset(&sin, 0, sizeof(sin)); + sin.sin_len = sizeof(sin); + sin.sin_family = AF_INET; + + /* get the IP address and port */ + netconn_getaddr(sock->conn, &naddr, &sin.sin_port, local); + + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getaddrname(%d, addr=", s)); + ip_addr_debug_print(SOCKETS_DEBUG, &naddr); + LWIP_DEBUGF(SOCKETS_DEBUG, (" port=%"U16_F")\n", sin.sin_port)); + + sin.sin_port = htons(sin.sin_port); + inet_addr_from_ipaddr(&sin.sin_addr, &naddr); + + if (*namelen > sizeof(sin)) { + *namelen = sizeof(sin); + } + + MEMCPY(name, &sin, *namelen); + sock_set_errno(sock, 0); + return 0; +} + +int +lwip_getpeername(int s, struct sockaddr *name, socklen_t *namelen) +{ + return lwip_getaddrname(s, name, namelen, 0); +} + +int +lwip_getsockname(int s, struct sockaddr *name, socklen_t *namelen) +{ + return lwip_getaddrname(s, name, namelen, 1); +} + +int +lwip_getsockopt(int s, int level, int optname, void *optval, socklen_t *optlen) +{ + err_t err = ERR_OK; + struct lwip_sock *sock = get_socket(s); + struct lwip_setgetsockopt_data data; + + if (!sock) { + return -1; + } + + if ((NULL == optval) || (NULL == optlen)) { + sock_set_errno(sock, EFAULT); + return -1; + } + + /* Do length and type checks for the various options first, to keep it readable. */ + switch (level) { + +/* Level: SOL_SOCKET */ + case SOL_SOCKET: + switch (optname) { + + case SO_ACCEPTCONN: + case SO_BROADCAST: + /* UNIMPL case SO_DEBUG: */ + /* UNIMPL case SO_DONTROUTE: */ + case SO_ERROR: + case SO_KEEPALIVE: + /* UNIMPL case SO_CONTIMEO: */ + /* UNIMPL case SO_SNDTIMEO: */ +#if LWIP_SO_RCVTIMEO + case SO_RCVTIMEO: +#endif /* LWIP_SO_RCVTIMEO */ +#if LWIP_SO_RCVBUF + case SO_RCVBUF: +#endif /* LWIP_SO_RCVBUF */ + /* UNIMPL case SO_OOBINLINE: */ + /* UNIMPL case SO_SNDBUF: */ + /* UNIMPL case SO_RCVLOWAT: */ + /* UNIMPL case SO_SNDLOWAT: */ +#if SO_REUSE + case SO_REUSEADDR: + case SO_REUSEPORT: +#endif /* SO_REUSE */ + case SO_TYPE: + /* UNIMPL case SO_USELOOPBACK: */ + if (*optlen < sizeof(int)) { + err = EINVAL; + } + break; + + case SO_NO_CHECK: + if (*optlen < sizeof(int)) { + err = EINVAL; + } +#if LWIP_UDP + if ((sock->conn->type != NETCONN_UDP) || + ((udp_flags(sock->conn->pcb.udp) & UDP_FLAGS_UDPLITE) != 0)) { + /* this flag is only available for UDP, not for UDP lite */ + err = EAFNOSUPPORT; + } +#endif /* LWIP_UDP */ + break; + + default: + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, SOL_SOCKET, UNIMPL: optname=0x%x, ..)\n", + s, optname)); + err = ENOPROTOOPT; + } /* switch (optname) */ + break; + +/* Level: IPPROTO_IP */ + case IPPROTO_IP: + switch (optname) { + /* UNIMPL case IP_HDRINCL: */ + /* UNIMPL case IP_RCVDSTADDR: */ + /* UNIMPL case IP_RCVIF: */ + case IP_TTL: + case IP_TOS: + if (*optlen < sizeof(int)) { + err = EINVAL; + } + break; +#if LWIP_IGMP + case IP_MULTICAST_TTL: + if (*optlen < sizeof(u8_t)) { + err = EINVAL; + } + break; + case IP_MULTICAST_IF: + if (*optlen < sizeof(struct in_addr)) { + err = EINVAL; + } + break; + case IP_MULTICAST_LOOP: + if (*optlen < sizeof(u8_t)) { + err = EINVAL; + } + if (NETCONNTYPE_GROUP(sock->conn->type) != NETCONN_UDP) { + err = EAFNOSUPPORT; + } + break; +#endif /* LWIP_IGMP */ + + default: + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_IP, UNIMPL: optname=0x%x, ..)\n", + s, optname)); + err = ENOPROTOOPT; + } /* switch (optname) */ + break; + +#if LWIP_TCP +/* Level: IPPROTO_TCP */ + case IPPROTO_TCP: + if (*optlen < sizeof(int)) { + err = EINVAL; + break; + } + + /* If this is no TCP socket, ignore any options. */ + if (sock->conn->type != NETCONN_TCP) + return 0; + + switch (optname) { + case TCP_NODELAY: + case TCP_KEEPALIVE: +#if LWIP_TCP_KEEPALIVE + case TCP_KEEPIDLE: + case TCP_KEEPINTVL: + case TCP_KEEPCNT: +#endif /* LWIP_TCP_KEEPALIVE */ + break; + + default: + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_TCP, UNIMPL: optname=0x%x, ..)\n", + s, optname)); + err = ENOPROTOOPT; + } /* switch (optname) */ + break; +#endif /* LWIP_TCP */ +#if LWIP_UDP && LWIP_UDPLITE +/* Level: IPPROTO_UDPLITE */ + case IPPROTO_UDPLITE: + if (*optlen < sizeof(int)) { + err = EINVAL; + break; + } + + /* If this is no UDP lite socket, ignore any options. */ + if (sock->conn->type != NETCONN_UDPLITE) { + return 0; + } + + switch (optname) { + case UDPLITE_SEND_CSCOV: + case UDPLITE_RECV_CSCOV: + break; + + default: + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_UDPLITE, UNIMPL: optname=0x%x, ..)\n", + s, optname)); + err = ENOPROTOOPT; + } /* switch (optname) */ + break; +#endif /* LWIP_UDP && LWIP_UDPLITE*/ +/* UNDEFINED LEVEL */ + default: + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, level=0x%x, UNIMPL: optname=0x%x, ..)\n", + s, level, optname)); + err = ENOPROTOOPT; + } /* switch */ + + + if (err != ERR_OK) { + sock_set_errno(sock, err); + return -1; + } + + /* Now do the actual option processing */ + data.sock = sock; +#ifdef LWIP_DEBUG + data.s = s; +#endif /* LWIP_DEBUG */ + data.level = level; + data.optname = optname; + data.optval = optval; + data.optlen = optlen; + data.err = err; + tcpip_callback(lwip_getsockopt_internal, &data); + sys_arch_sem_wait(&sock->conn->op_completed, 0); + /* maybe lwip_getsockopt_internal has changed err */ + err = data.err; + + sock_set_errno(sock, err); + return err ? -1 : 0; +} + +static void +lwip_getsockopt_internal(void *arg) +{ + struct lwip_sock *sock; +#ifdef LWIP_DEBUG + int s; +#endif /* LWIP_DEBUG */ + int level, optname; + void *optval; + struct lwip_setgetsockopt_data *data; + + LWIP_ASSERT("arg != NULL", arg != NULL); + + data = (struct lwip_setgetsockopt_data*)arg; + sock = data->sock; +#ifdef LWIP_DEBUG + s = data->s; +#endif /* LWIP_DEBUG */ + level = data->level; + optname = data->optname; + optval = data->optval; + + switch (level) { + +/* Level: SOL_SOCKET */ + case SOL_SOCKET: + switch (optname) { + + /* The option flags */ + case SO_ACCEPTCONN: + case SO_BROADCAST: + /* UNIMPL case SO_DEBUG: */ + /* UNIMPL case SO_DONTROUTE: */ + case SO_KEEPALIVE: + /* UNIMPL case SO_OOBINCLUDE: */ +#if SO_REUSE + case SO_REUSEADDR: + case SO_REUSEPORT: +#endif /* SO_REUSE */ + /*case SO_USELOOPBACK: UNIMPL */ + *(int*)optval = sock->conn->pcb.ip->so_options & optname; + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, SOL_SOCKET, optname=0x%x, ..) = %s\n", + s, optname, (*(int*)optval?"on":"off"))); + break; + + case SO_TYPE: + switch (NETCONNTYPE_GROUP(sock->conn->type)) { + case NETCONN_RAW: + *(int*)optval = SOCK_RAW; + break; + case NETCONN_TCP: + *(int*)optval = SOCK_STREAM; + break; + case NETCONN_UDP: + *(int*)optval = SOCK_DGRAM; + break; + default: /* unrecognized socket type */ + *(int*)optval = sock->conn->type; + LWIP_DEBUGF(SOCKETS_DEBUG, + ("lwip_getsockopt(%d, SOL_SOCKET, SO_TYPE): unrecognized socket type %d\n", + s, *(int *)optval)); + } /* switch (sock->conn->type) */ + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, SOL_SOCKET, SO_TYPE) = %d\n", + s, *(int *)optval)); + break; + + case SO_ERROR: + /* only overwrite ERR_OK or tempoary errors */ + if ((sock->err == 0) || (sock->err == EINPROGRESS)) { + sock_set_errno(sock, err_to_errno(sock->conn->last_err)); + } + *(int *)optval = sock->err; + sock->err = 0; + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, SOL_SOCKET, SO_ERROR) = %d\n", + s, *(int *)optval)); + break; + +#if LWIP_SO_RCVTIMEO + case SO_RCVTIMEO: + *(int *)optval = netconn_get_recvtimeout(sock->conn); + break; +#endif /* LWIP_SO_RCVTIMEO */ +#if LWIP_SO_RCVBUF + case SO_RCVBUF: + *(int *)optval = netconn_get_recvbufsize(sock->conn); + break; +#endif /* LWIP_SO_RCVBUF */ +#if LWIP_UDP + case SO_NO_CHECK: + *(int*)optval = (udp_flags(sock->conn->pcb.udp) & UDP_FLAGS_NOCHKSUM) ? 1 : 0; + break; +#endif /* LWIP_UDP*/ + default: + LWIP_ASSERT("unhandled optname", 0); + break; + } /* switch (optname) */ + break; + +/* Level: IPPROTO_IP */ + case IPPROTO_IP: + switch (optname) { + case IP_TTL: + *(int*)optval = sock->conn->pcb.ip->ttl; + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_IP, IP_TTL) = %d\n", + s, *(int *)optval)); + break; + case IP_TOS: + *(int*)optval = sock->conn->pcb.ip->tos; + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_IP, IP_TOS) = %d\n", + s, *(int *)optval)); + break; +#if LWIP_IGMP + case IP_MULTICAST_TTL: + *(u8_t*)optval = sock->conn->pcb.ip->ttl; + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_IP, IP_MULTICAST_TTL) = %d\n", + s, *(int *)optval)); + break; + case IP_MULTICAST_IF: + inet_addr_from_ipaddr((struct in_addr*)optval, &sock->conn->pcb.udp->multicast_ip); + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_IP, IP_MULTICAST_IF) = 0x%"X32_F"\n", + s, *(u32_t *)optval)); + break; + case IP_MULTICAST_LOOP: + if ((sock->conn->pcb.udp->flags & UDP_FLAGS_MULTICAST_LOOP) != 0) { + *(u8_t*)optval = 1; + } else { + *(u8_t*)optval = 0; + } + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_IP, IP_MULTICAST_LOOP) = %d\n", + s, *(int *)optval)); + break; +#endif /* LWIP_IGMP */ + default: + LWIP_ASSERT("unhandled optname", 0); + break; + } /* switch (optname) */ + break; + +#if LWIP_TCP +/* Level: IPPROTO_TCP */ + case IPPROTO_TCP: + switch (optname) { + case TCP_NODELAY: + *(int*)optval = tcp_nagle_disabled(sock->conn->pcb.tcp); + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_TCP, TCP_NODELAY) = %s\n", + s, (*(int*)optval)?"on":"off") ); + break; + case TCP_KEEPALIVE: + *(int*)optval = (int)sock->conn->pcb.tcp->keep_idle; + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_IP, TCP_KEEPALIVE) = %d\n", + s, *(int *)optval)); + break; + +#if LWIP_TCP_KEEPALIVE + case TCP_KEEPIDLE: + *(int*)optval = (int)(sock->conn->pcb.tcp->keep_idle/1000); + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_IP, TCP_KEEPIDLE) = %d\n", + s, *(int *)optval)); + break; + case TCP_KEEPINTVL: + *(int*)optval = (int)(sock->conn->pcb.tcp->keep_intvl/1000); + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_IP, TCP_KEEPINTVL) = %d\n", + s, *(int *)optval)); + break; + case TCP_KEEPCNT: + *(int*)optval = (int)sock->conn->pcb.tcp->keep_cnt; + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_IP, TCP_KEEPCNT) = %d\n", + s, *(int *)optval)); + break; +#endif /* LWIP_TCP_KEEPALIVE */ + default: + LWIP_ASSERT("unhandled optname", 0); + break; + } /* switch (optname) */ + break; +#endif /* LWIP_TCP */ +#if LWIP_UDP && LWIP_UDPLITE + /* Level: IPPROTO_UDPLITE */ + case IPPROTO_UDPLITE: + switch (optname) { + case UDPLITE_SEND_CSCOV: + *(int*)optval = sock->conn->pcb.udp->chksum_len_tx; + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_UDPLITE, UDPLITE_SEND_CSCOV) = %d\n", + s, (*(int*)optval)) ); + break; + case UDPLITE_RECV_CSCOV: + *(int*)optval = sock->conn->pcb.udp->chksum_len_rx; + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_UDPLITE, UDPLITE_RECV_CSCOV) = %d\n", + s, (*(int*)optval)) ); + break; + default: + LWIP_ASSERT("unhandled optname", 0); + break; + } /* switch (optname) */ + break; +#endif /* LWIP_UDP */ + default: + LWIP_ASSERT("unhandled level", 0); + break; + } /* switch (level) */ + sys_sem_signal(&sock->conn->op_completed); +} + +int +lwip_setsockopt(int s, int level, int optname, const void *optval, socklen_t optlen) +{ + struct lwip_sock *sock = get_socket(s); + err_t err = ERR_OK; + struct lwip_setgetsockopt_data data; + + if (!sock) { + return -1; + } + + if (NULL == optval) { + sock_set_errno(sock, EFAULT); + return -1; + } + + /* Do length and type checks for the various options first, to keep it readable. */ + switch (level) { + +/* Level: SOL_SOCKET */ + case SOL_SOCKET: + switch (optname) { + + case SO_BROADCAST: + /* UNIMPL case SO_DEBUG: */ + /* UNIMPL case SO_DONTROUTE: */ + case SO_KEEPALIVE: + /* UNIMPL case case SO_CONTIMEO: */ + /* UNIMPL case case SO_SNDTIMEO: */ +#if LWIP_SO_RCVTIMEO + case SO_RCVTIMEO: +#endif /* LWIP_SO_RCVTIMEO */ +#if LWIP_SO_RCVBUF + case SO_RCVBUF: +#endif /* LWIP_SO_RCVBUF */ + /* UNIMPL case SO_OOBINLINE: */ + /* UNIMPL case SO_SNDBUF: */ + /* UNIMPL case SO_RCVLOWAT: */ + /* UNIMPL case SO_SNDLOWAT: */ +#if SO_REUSE + case SO_REUSEADDR: + case SO_REUSEPORT: +#endif /* SO_REUSE */ + /* UNIMPL case SO_USELOOPBACK: */ + if (optlen < sizeof(int)) { + err = EINVAL; + } + break; + case SO_NO_CHECK: + if (optlen < sizeof(int)) { + err = EINVAL; + } +#if LWIP_UDP + if ((sock->conn->type != NETCONN_UDP) || + ((udp_flags(sock->conn->pcb.udp) & UDP_FLAGS_UDPLITE) != 0)) { + /* this flag is only available for UDP, not for UDP lite */ + err = EAFNOSUPPORT; + } +#endif /* LWIP_UDP */ + break; + default: + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, SOL_SOCKET, UNIMPL: optname=0x%x, ..)\n", + s, optname)); + err = ENOPROTOOPT; + } /* switch (optname) */ + break; + +/* Level: IPPROTO_IP */ + case IPPROTO_IP: + switch (optname) { + /* UNIMPL case IP_HDRINCL: */ + /* UNIMPL case IP_RCVDSTADDR: */ + /* UNIMPL case IP_RCVIF: */ + case IP_TTL: + case IP_TOS: + if (optlen < sizeof(int)) { + err = EINVAL; + } + break; +#if LWIP_IGMP + case IP_MULTICAST_TTL: + if (optlen < sizeof(u8_t)) { + err = EINVAL; + } + if (NETCONNTYPE_GROUP(sock->conn->type) != NETCONN_UDP) { + err = EAFNOSUPPORT; + } + break; + case IP_MULTICAST_IF: + if (optlen < sizeof(struct in_addr)) { + err = EINVAL; + } + if (NETCONNTYPE_GROUP(sock->conn->type) != NETCONN_UDP) { + err = EAFNOSUPPORT; + } + break; + case IP_MULTICAST_LOOP: + if (optlen < sizeof(u8_t)) { + err = EINVAL; + } + if (NETCONNTYPE_GROUP(sock->conn->type) != NETCONN_UDP) { + err = EAFNOSUPPORT; + } + break; + case IP_ADD_MEMBERSHIP: + case IP_DROP_MEMBERSHIP: + if (optlen < sizeof(struct ip_mreq)) { + err = EINVAL; + } + if (NETCONNTYPE_GROUP(sock->conn->type) != NETCONN_UDP) { + err = EAFNOSUPPORT; + } + break; +#endif /* LWIP_IGMP */ + default: + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, IPPROTO_IP, UNIMPL: optname=0x%x, ..)\n", + s, optname)); + err = ENOPROTOOPT; + } /* switch (optname) */ + break; + +#if LWIP_TCP +/* Level: IPPROTO_TCP */ + case IPPROTO_TCP: + if (optlen < sizeof(int)) { + err = EINVAL; + break; + } + + /* If this is no TCP socket, ignore any options. */ + if (sock->conn->type != NETCONN_TCP) + return 0; + + switch (optname) { + case TCP_NODELAY: + case TCP_KEEPALIVE: +#if LWIP_TCP_KEEPALIVE + case TCP_KEEPIDLE: + case TCP_KEEPINTVL: + case TCP_KEEPCNT: +#endif /* LWIP_TCP_KEEPALIVE */ + break; + + default: + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, IPPROTO_TCP, UNIMPL: optname=0x%x, ..)\n", + s, optname)); + err = ENOPROTOOPT; + } /* switch (optname) */ + break; +#endif /* LWIP_TCP */ +#if LWIP_UDP && LWIP_UDPLITE +/* Level: IPPROTO_UDPLITE */ + case IPPROTO_UDPLITE: + if (optlen < sizeof(int)) { + err = EINVAL; + break; + } + + /* If this is no UDP lite socket, ignore any options. */ + if (sock->conn->type != NETCONN_UDPLITE) + return 0; + + switch (optname) { + case UDPLITE_SEND_CSCOV: + case UDPLITE_RECV_CSCOV: + break; + + default: + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, IPPROTO_UDPLITE, UNIMPL: optname=0x%x, ..)\n", + s, optname)); + err = ENOPROTOOPT; + } /* switch (optname) */ + break; +#endif /* LWIP_UDP && LWIP_UDPLITE */ +/* UNDEFINED LEVEL */ + default: + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, level=0x%x, UNIMPL: optname=0x%x, ..)\n", + s, level, optname)); + err = ENOPROTOOPT; + } /* switch (level) */ + + + if (err != ERR_OK) { + sock_set_errno(sock, err); + return -1; + } + + + /* Now do the actual option processing */ + data.sock = sock; +#ifdef LWIP_DEBUG + data.s = s; +#endif /* LWIP_DEBUG */ + data.level = level; + data.optname = optname; + data.optval = (void*)optval; + data.optlen = &optlen; + data.err = err; + tcpip_callback(lwip_setsockopt_internal, &data); + sys_arch_sem_wait(&sock->conn->op_completed, 0); + /* maybe lwip_setsockopt_internal has changed err */ + err = data.err; + + sock_set_errno(sock, err); + return err ? -1 : 0; +} + +static void +lwip_setsockopt_internal(void *arg) +{ + struct lwip_sock *sock; +#ifdef LWIP_DEBUG + int s; +#endif /* LWIP_DEBUG */ + int level, optname; + const void *optval; + struct lwip_setgetsockopt_data *data; + + LWIP_ASSERT("arg != NULL", arg != NULL); + + data = (struct lwip_setgetsockopt_data*)arg; + sock = data->sock; +#ifdef LWIP_DEBUG + s = data->s; +#endif /* LWIP_DEBUG */ + level = data->level; + optname = data->optname; + optval = data->optval; + + switch (level) { + +/* Level: SOL_SOCKET */ + case SOL_SOCKET: + switch (optname) { + + /* The option flags */ + case SO_BROADCAST: + /* UNIMPL case SO_DEBUG: */ + /* UNIMPL case SO_DONTROUTE: */ + case SO_KEEPALIVE: + /* UNIMPL case SO_OOBINCLUDE: */ +#if SO_REUSE + case SO_REUSEADDR: + case SO_REUSEPORT: +#endif /* SO_REUSE */ + /* UNIMPL case SO_USELOOPBACK: */ + if (*(int*)optval) { + sock->conn->pcb.ip->so_options |= optname; + } else { + sock->conn->pcb.ip->so_options &= ~optname; + } + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, SOL_SOCKET, optname=0x%x, ..) -> %s\n", + s, optname, (*(int*)optval?"on":"off"))); + break; +#if LWIP_SO_RCVTIMEO + case SO_RCVTIMEO: + netconn_set_recvtimeout(sock->conn, *(int*)optval); + break; +#endif /* LWIP_SO_RCVTIMEO */ +#if LWIP_SO_RCVBUF + case SO_RCVBUF: + netconn_set_recvbufsize(sock->conn, *(int*)optval); + break; +#endif /* LWIP_SO_RCVBUF */ +#if LWIP_UDP + case SO_NO_CHECK: + if (*(int*)optval) { + udp_setflags(sock->conn->pcb.udp, udp_flags(sock->conn->pcb.udp) | UDP_FLAGS_NOCHKSUM); + } else { + udp_setflags(sock->conn->pcb.udp, udp_flags(sock->conn->pcb.udp) & ~UDP_FLAGS_NOCHKSUM); + } + break; +#endif /* LWIP_UDP */ + default: + LWIP_ASSERT("unhandled optname", 0); + break; + } /* switch (optname) */ + break; + +/* Level: IPPROTO_IP */ + case IPPROTO_IP: + switch (optname) { + case IP_TTL: + sock->conn->pcb.ip->ttl = (u8_t)(*(int*)optval); + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, IPPROTO_IP, IP_TTL, ..) -> %d\n", + s, sock->conn->pcb.ip->ttl)); + break; + case IP_TOS: + sock->conn->pcb.ip->tos = (u8_t)(*(int*)optval); + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, IPPROTO_IP, IP_TOS, ..)-> %d\n", + s, sock->conn->pcb.ip->tos)); + break; +#if LWIP_IGMP + case IP_MULTICAST_TTL: + sock->conn->pcb.udp->ttl = (u8_t)(*(u8_t*)optval); + break; + case IP_MULTICAST_IF: + inet_addr_to_ipaddr(&sock->conn->pcb.udp->multicast_ip, (struct in_addr*)optval); + break; + case IP_MULTICAST_LOOP: + if (*(u8_t*)optval) { + udp_setflags(sock->conn->pcb.udp, udp_flags(sock->conn->pcb.udp) | UDP_FLAGS_MULTICAST_LOOP); + } else { + udp_setflags(sock->conn->pcb.udp, udp_flags(sock->conn->pcb.udp) & ~UDP_FLAGS_MULTICAST_LOOP); + } + break; + case IP_ADD_MEMBERSHIP: + case IP_DROP_MEMBERSHIP: + { + /* If this is a TCP or a RAW socket, ignore these options. */ + struct ip_mreq *imr = (struct ip_mreq *)optval; + ip_addr_t if_addr; + ip_addr_t multi_addr; + inet_addr_to_ipaddr(&if_addr, &imr->imr_interface); + inet_addr_to_ipaddr(&multi_addr, &imr->imr_multiaddr); + if(optname == IP_ADD_MEMBERSHIP){ + data->err = igmp_joingroup(&if_addr, &multi_addr); + } else { + data->err = igmp_leavegroup(&if_addr, &multi_addr); + } + if(data->err != ERR_OK) { + data->err = EADDRNOTAVAIL; + } + } + break; +#endif /* LWIP_IGMP */ + default: + LWIP_ASSERT("unhandled optname", 0); + break; + } /* switch (optname) */ + break; + +#if LWIP_TCP +/* Level: IPPROTO_TCP */ + case IPPROTO_TCP: + switch (optname) { + case TCP_NODELAY: + if (*(int*)optval) { + tcp_nagle_disable(sock->conn->pcb.tcp); + } else { + tcp_nagle_enable(sock->conn->pcb.tcp); + } + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, IPPROTO_TCP, TCP_NODELAY) -> %s\n", + s, (*(int *)optval)?"on":"off") ); + break; + case TCP_KEEPALIVE: + sock->conn->pcb.tcp->keep_idle = (u32_t)(*(int*)optval); + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, IPPROTO_TCP, TCP_KEEPALIVE) -> %"U32_F"\n", + s, sock->conn->pcb.tcp->keep_idle)); + break; + +#if LWIP_TCP_KEEPALIVE + case TCP_KEEPIDLE: + sock->conn->pcb.tcp->keep_idle = 1000*(u32_t)(*(int*)optval); + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, IPPROTO_TCP, TCP_KEEPIDLE) -> %"U32_F"\n", + s, sock->conn->pcb.tcp->keep_idle)); + break; + case TCP_KEEPINTVL: + sock->conn->pcb.tcp->keep_intvl = 1000*(u32_t)(*(int*)optval); + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, IPPROTO_TCP, TCP_KEEPINTVL) -> %"U32_F"\n", + s, sock->conn->pcb.tcp->keep_intvl)); + break; + case TCP_KEEPCNT: + sock->conn->pcb.tcp->keep_cnt = (u32_t)(*(int*)optval); + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, IPPROTO_TCP, TCP_KEEPCNT) -> %"U32_F"\n", + s, sock->conn->pcb.tcp->keep_cnt)); + break; +#endif /* LWIP_TCP_KEEPALIVE */ + default: + LWIP_ASSERT("unhandled optname", 0); + break; + } /* switch (optname) */ + break; +#endif /* LWIP_TCP*/ +#if LWIP_UDP && LWIP_UDPLITE + /* Level: IPPROTO_UDPLITE */ + case IPPROTO_UDPLITE: + switch (optname) { + case UDPLITE_SEND_CSCOV: + if ((*(int*)optval != 0) && ((*(int*)optval < 8)) || (*(int*)optval > 0xffff)) { + /* don't allow illegal values! */ + sock->conn->pcb.udp->chksum_len_tx = 8; + } else { + sock->conn->pcb.udp->chksum_len_tx = (u16_t)*(int*)optval; + } + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, IPPROTO_UDPLITE, UDPLITE_SEND_CSCOV) -> %d\n", + s, (*(int*)optval)) ); + break; + case UDPLITE_RECV_CSCOV: + if ((*(int*)optval != 0) && ((*(int*)optval < 8)) || (*(int*)optval > 0xffff)) { + /* don't allow illegal values! */ + sock->conn->pcb.udp->chksum_len_rx = 8; + } else { + sock->conn->pcb.udp->chksum_len_rx = (u16_t)*(int*)optval; + } + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, IPPROTO_UDPLITE, UDPLITE_RECV_CSCOV) -> %d\n", + s, (*(int*)optval)) ); + break; + default: + LWIP_ASSERT("unhandled optname", 0); + break; + } /* switch (optname) */ + break; +#endif /* LWIP_UDP */ + default: + LWIP_ASSERT("unhandled level", 0); + break; + } /* switch (level) */ + sys_sem_signal(&sock->conn->op_completed); +} + +int +lwip_ioctl(int s, long cmd, void *argp) +{ + struct lwip_sock *sock = get_socket(s); + u8_t val; +#if LWIP_SO_RCVBUF + u16_t buflen = 0; + s16_t recv_avail; +#endif /* LWIP_SO_RCVBUF */ + + if (!sock) { + return -1; + } + + switch (cmd) { +#if LWIP_SO_RCVBUF + case FIONREAD: + if (!argp) { + sock_set_errno(sock, EINVAL); + return -1; + } + + SYS_ARCH_GET(sock->conn->recv_avail, recv_avail); + if (recv_avail < 0) { + recv_avail = 0; + } + *((u16_t*)argp) = (u16_t)recv_avail; + + /* Check if there is data left from the last recv operation. /maq 041215 */ + if (sock->lastdata) { + struct pbuf *p = (struct pbuf *)sock->lastdata; + if (netconn_type(sock->conn) != NETCONN_TCP) { + p = ((struct netbuf *)p)->p; + } + buflen = p->tot_len; + buflen -= sock->lastoffset; + + *((u16_t*)argp) += buflen; + } + + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_ioctl(%d, FIONREAD, %p) = %"U16_F"\n", s, argp, *((u16_t*)argp))); + sock_set_errno(sock, 0); + return 0; +#endif /* LWIP_SO_RCVBUF */ + + case FIONBIO: + val = 0; + if (argp && *(u32_t*)argp) { + val = 1; + } + netconn_set_nonblocking(sock->conn, val); + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_ioctl(%d, FIONBIO, %d)\n", s, val)); + sock_set_errno(sock, 0); + return 0; + + default: + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_ioctl(%d, UNIMPL: 0x%lx, %p)\n", s, cmd, argp)); + sock_set_errno(sock, ENOSYS); /* not yet implemented */ + return -1; + } /* switch (cmd) */ +} + +/** A minimal implementation of fcntl. + * Currently only the commands F_GETFL and F_SETFL are implemented. + * Only the flag O_NONBLOCK is implemented. + */ +int +lwip_fcntl(int s, int cmd, int val) +{ + struct lwip_sock *sock = get_socket(s); + int ret = -1; + + if (!sock || !sock->conn) { + return -1; + } + + switch (cmd) { + case F_GETFL: + ret = netconn_is_nonblocking(sock->conn) ? O_NONBLOCK : 0; + break; + case F_SETFL: + if ((val & ~O_NONBLOCK) == 0) { + /* only O_NONBLOCK, all other bits are zero */ + netconn_set_nonblocking(sock->conn, val & O_NONBLOCK); + ret = 0; + } + break; + default: + LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_fcntl(%d, UNIMPL: %d, %d)\n", s, cmd, val)); + break; + } + return ret; +} + +#endif /* LWIP_SOCKET */ diff --git a/features/unsupported/net/lwip/lwip/api/tcpip.c b/features/unsupported/net/lwip/lwip/api/tcpip.c new file mode 100644 index 00000000000..857e7d9bd64 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/api/tcpip.c @@ -0,0 +1,460 @@ +/** + * @file + * Sequential API Main thread module + * + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ + +#include "lwip/opt.h" + +#if !NO_SYS /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/sys.h" +#include "lwip/memp.h" +#include "lwip/mem.h" +#include "lwip/pbuf.h" +#include "lwip/tcpip.h" +#include "lwip/init.h" +#include "netif/etharp.h" +#include "netif/ppp_oe.h" + +/* global variables */ +static tcpip_init_done_fn tcpip_init_done; +static void *tcpip_init_done_arg; +static sys_mbox_t mbox; + +#if LWIP_TCPIP_CORE_LOCKING +/** The global semaphore to lock the stack. */ +sys_mutex_t lock_tcpip_core; +#endif /* LWIP_TCPIP_CORE_LOCKING */ + + +/** + * The main lwIP thread. This thread has exclusive access to lwIP core functions + * (unless access to them is not locked). Other threads communicate with this + * thread using message boxes. + * + * It also starts all the timers to make sure they are running in the right + * thread context. + * + * @param arg unused argument + */ +static void +tcpip_thread(void *arg) +{ + struct tcpip_msg *msg; + LWIP_UNUSED_ARG(arg); + + if (tcpip_init_done != NULL) { + tcpip_init_done(tcpip_init_done_arg); + } + + LOCK_TCPIP_CORE(); + while (1) { /* MAIN Loop */ + UNLOCK_TCPIP_CORE(); + LWIP_TCPIP_THREAD_ALIVE(); + /* wait for a message, timeouts are processed while waiting */ + sys_timeouts_mbox_fetch(&mbox, (void **)&msg); + LOCK_TCPIP_CORE(); + switch (msg->type) { +#if LWIP_NETCONN + case TCPIP_MSG_API: + LWIP_DEBUGF(TCPIP_DEBUG, ("tcpip_thread: API message %p\n", (void *)msg)); + msg->msg.apimsg->function(&(msg->msg.apimsg->msg)); + break; +#endif /* LWIP_NETCONN */ + +#if !LWIP_TCPIP_CORE_LOCKING_INPUT + case TCPIP_MSG_INPKT: + LWIP_DEBUGF(TCPIP_DEBUG, ("tcpip_thread: PACKET %p\n", (void *)msg)); +#if LWIP_ETHERNET + if (msg->msg.inp.netif->flags & (NETIF_FLAG_ETHARP | NETIF_FLAG_ETHERNET)) { + ethernet_input(msg->msg.inp.p, msg->msg.inp.netif); + } else +#endif /* LWIP_ETHERNET */ + { + ip_input(msg->msg.inp.p, msg->msg.inp.netif); + } + memp_free(MEMP_TCPIP_MSG_INPKT, msg); + break; +#endif /* LWIP_TCPIP_CORE_LOCKING_INPUT */ + +#if LWIP_NETIF_API + case TCPIP_MSG_NETIFAPI: + LWIP_DEBUGF(TCPIP_DEBUG, ("tcpip_thread: Netif API message %p\n", (void *)msg)); + msg->msg.netifapimsg->function(&(msg->msg.netifapimsg->msg)); + break; +#endif /* LWIP_NETIF_API */ + + case TCPIP_MSG_CALLBACK: + LWIP_DEBUGF(TCPIP_DEBUG, ("tcpip_thread: CALLBACK %p\n", (void *)msg)); + msg->msg.cb.function(msg->msg.cb.ctx); + memp_free(MEMP_TCPIP_MSG_API, msg); + break; + +#if LWIP_TCPIP_TIMEOUT + case TCPIP_MSG_TIMEOUT: + LWIP_DEBUGF(TCPIP_DEBUG, ("tcpip_thread: TIMEOUT %p\n", (void *)msg)); + sys_timeout(msg->msg.tmo.msecs, msg->msg.tmo.h, msg->msg.tmo.arg); + memp_free(MEMP_TCPIP_MSG_API, msg); + break; + case TCPIP_MSG_UNTIMEOUT: + LWIP_DEBUGF(TCPIP_DEBUG, ("tcpip_thread: UNTIMEOUT %p\n", (void *)msg)); + sys_untimeout(msg->msg.tmo.h, msg->msg.tmo.arg); + memp_free(MEMP_TCPIP_MSG_API, msg); + break; +#endif /* LWIP_TCPIP_TIMEOUT */ + + default: + LWIP_DEBUGF(TCPIP_DEBUG, ("tcpip_thread: invalid message: %d\n", msg->type)); + LWIP_ASSERT("tcpip_thread: invalid message", 0); + break; + } + } +} + +/** + * Pass a received packet to tcpip_thread for input processing + * + * @param p the received packet, p->payload pointing to the Ethernet header or + * to an IP header (if inp doesn't have NETIF_FLAG_ETHARP or + * NETIF_FLAG_ETHERNET flags) + * @param inp the network interface on which the packet was received + */ +err_t +tcpip_input(struct pbuf *p, struct netif *inp) +{ +#if LWIP_TCPIP_CORE_LOCKING_INPUT + err_t ret; + LWIP_DEBUGF(TCPIP_DEBUG, ("tcpip_input: PACKET %p/%p\n", (void *)p, (void *)inp)); + LOCK_TCPIP_CORE(); +#if LWIP_ETHERNET + if (inp->flags & (NETIF_FLAG_ETHARP | NETIF_FLAG_ETHERNET)) { + ret = ethernet_input(p, inp); + } else +#endif /* LWIP_ETHERNET */ + { + ret = ip_input(p, inp); + } + UNLOCK_TCPIP_CORE(); + return ret; +#else /* LWIP_TCPIP_CORE_LOCKING_INPUT */ + struct tcpip_msg *msg; + + if (sys_mbox_valid(&mbox)) { + msg = (struct tcpip_msg *)memp_malloc(MEMP_TCPIP_MSG_INPKT); + if (msg == NULL) { + return ERR_MEM; + } + + msg->type = TCPIP_MSG_INPKT; + msg->msg.inp.p = p; + msg->msg.inp.netif = inp; + if (sys_mbox_trypost(&mbox, msg) != ERR_OK) { + memp_free(MEMP_TCPIP_MSG_INPKT, msg); + return ERR_MEM; + } + return ERR_OK; + } + return ERR_VAL; +#endif /* LWIP_TCPIP_CORE_LOCKING_INPUT */ +} + +/** + * Call a specific function in the thread context of + * tcpip_thread for easy access synchronization. + * A function called in that way may access lwIP core code + * without fearing concurrent access. + * + * @param f the function to call + * @param ctx parameter passed to f + * @param block 1 to block until the request is posted, 0 to non-blocking mode + * @return ERR_OK if the function was called, another err_t if not + */ +err_t +tcpip_callback_with_block(tcpip_callback_fn function, void *ctx, u8_t block) +{ + struct tcpip_msg *msg; + + if (sys_mbox_valid(&mbox)) { + msg = (struct tcpip_msg *)memp_malloc(MEMP_TCPIP_MSG_API); + if (msg == NULL) { + return ERR_MEM; + } + + msg->type = TCPIP_MSG_CALLBACK; + msg->msg.cb.function = function; + msg->msg.cb.ctx = ctx; + if (block) { + sys_mbox_post(&mbox, msg); + } else { + if (sys_mbox_trypost(&mbox, msg) != ERR_OK) { + memp_free(MEMP_TCPIP_MSG_API, msg); + return ERR_MEM; + } + } + return ERR_OK; + } + return ERR_VAL; +} + +#if LWIP_TCPIP_TIMEOUT +/** + * call sys_timeout in tcpip_thread + * + * @param msec time in milliseconds for timeout + * @param h function to be called on timeout + * @param arg argument to pass to timeout function h + * @return ERR_MEM on memory error, ERR_OK otherwise + */ +err_t +tcpip_timeout(u32_t msecs, sys_timeout_handler h, void *arg) +{ + struct tcpip_msg *msg; + + if (sys_mbox_valid(&mbox)) { + msg = (struct tcpip_msg *)memp_malloc(MEMP_TCPIP_MSG_API); + if (msg == NULL) { + return ERR_MEM; + } + + msg->type = TCPIP_MSG_TIMEOUT; + msg->msg.tmo.msecs = msecs; + msg->msg.tmo.h = h; + msg->msg.tmo.arg = arg; + sys_mbox_post(&mbox, msg); + return ERR_OK; + } + return ERR_VAL; +} + +/** + * call sys_untimeout in tcpip_thread + * + * @param msec time in milliseconds for timeout + * @param h function to be called on timeout + * @param arg argument to pass to timeout function h + * @return ERR_MEM on memory error, ERR_OK otherwise + */ +err_t +tcpip_untimeout(sys_timeout_handler h, void *arg) +{ + struct tcpip_msg *msg; + + if (sys_mbox_valid(&mbox)) { + msg = (struct tcpip_msg *)memp_malloc(MEMP_TCPIP_MSG_API); + if (msg == NULL) { + return ERR_MEM; + } + + msg->type = TCPIP_MSG_UNTIMEOUT; + msg->msg.tmo.h = h; + msg->msg.tmo.arg = arg; + sys_mbox_post(&mbox, msg); + return ERR_OK; + } + return ERR_VAL; +} +#endif /* LWIP_TCPIP_TIMEOUT */ + +#if LWIP_NETCONN +/** + * Call the lower part of a netconn_* function + * This function is then running in the thread context + * of tcpip_thread and has exclusive access to lwIP core code. + * + * @param apimsg a struct containing the function to call and its parameters + * @return ERR_OK if the function was called, another err_t if not + */ +err_t +tcpip_apimsg(struct api_msg *apimsg) +{ + struct tcpip_msg msg; +#ifdef LWIP_DEBUG + /* catch functions that don't set err */ + apimsg->msg.err = ERR_VAL; +#endif + + if (sys_mbox_valid(&mbox)) { + msg.type = TCPIP_MSG_API; + msg.msg.apimsg = apimsg; + sys_mbox_post(&mbox, &msg); + sys_arch_sem_wait(&apimsg->msg.conn->op_completed, 0); + return apimsg->msg.err; + } + return ERR_VAL; +} + +#if LWIP_TCPIP_CORE_LOCKING +/** + * Call the lower part of a netconn_* function + * This function has exclusive access to lwIP core code by locking it + * before the function is called. + * + * @param apimsg a struct containing the function to call and its parameters + * @return ERR_OK (only for compatibility fo tcpip_apimsg()) + */ +err_t +tcpip_apimsg_lock(struct api_msg *apimsg) +{ +#ifdef LWIP_DEBUG + /* catch functions that don't set err */ + apimsg->msg.err = ERR_VAL; +#endif + + LOCK_TCPIP_CORE(); + apimsg->function(&(apimsg->msg)); + UNLOCK_TCPIP_CORE(); + return apimsg->msg.err; + +} +#endif /* LWIP_TCPIP_CORE_LOCKING */ +#endif /* LWIP_NETCONN */ + +#if LWIP_NETIF_API +#if !LWIP_TCPIP_CORE_LOCKING +/** + * Much like tcpip_apimsg, but calls the lower part of a netifapi_* + * function. + * + * @param netifapimsg a struct containing the function to call and its parameters + * @return error code given back by the function that was called + */ +err_t +tcpip_netifapi(struct netifapi_msg* netifapimsg) +{ + struct tcpip_msg msg; + + if (sys_mbox_valid(&mbox)) { + err_t err = sys_sem_new(&netifapimsg->msg.sem, 0); + if (err != ERR_OK) { + netifapimsg->msg.err = err; + return err; + } + + msg.type = TCPIP_MSG_NETIFAPI; + msg.msg.netifapimsg = netifapimsg; + sys_mbox_post(&mbox, &msg); + sys_sem_wait(&netifapimsg->msg.sem); + sys_sem_free(&netifapimsg->msg.sem); + return netifapimsg->msg.err; + } + return ERR_VAL; +} +#else /* !LWIP_TCPIP_CORE_LOCKING */ +/** + * Call the lower part of a netifapi_* function + * This function has exclusive access to lwIP core code by locking it + * before the function is called. + * + * @param netifapimsg a struct containing the function to call and its parameters + * @return ERR_OK (only for compatibility fo tcpip_netifapi()) + */ +err_t +tcpip_netifapi_lock(struct netifapi_msg* netifapimsg) +{ + LOCK_TCPIP_CORE(); + netifapimsg->function(&(netifapimsg->msg)); + UNLOCK_TCPIP_CORE(); + return netifapimsg->msg.err; +} +#endif /* !LWIP_TCPIP_CORE_LOCKING */ +#endif /* LWIP_NETIF_API */ + +/** + * Initialize this module: + * - initialize all sub modules + * - start the tcpip_thread + * + * @param initfunc a function to call when tcpip_thread is running and finished initializing + * @param arg argument to pass to initfunc + */ +void +tcpip_init(tcpip_init_done_fn initfunc, void *arg) +{ + lwip_init(); + + tcpip_init_done = initfunc; + tcpip_init_done_arg = arg; + if(sys_mbox_new(&mbox, TCPIP_MBOX_SIZE) != ERR_OK) { + LWIP_ASSERT("failed to create tcpip_thread mbox", 0); + } +#if LWIP_TCPIP_CORE_LOCKING + if(sys_mutex_new(&lock_tcpip_core) != ERR_OK) { + LWIP_ASSERT("failed to create lock_tcpip_core", 0); + } +#endif /* LWIP_TCPIP_CORE_LOCKING */ + + sys_thread_new(TCPIP_THREAD_NAME, tcpip_thread, NULL, TCPIP_THREAD_STACKSIZE, TCPIP_THREAD_PRIO); +} + +/** + * Simple callback function used with tcpip_callback to free a pbuf + * (pbuf_free has a wrong signature for tcpip_callback) + * + * @param p The pbuf (chain) to be dereferenced. + */ +static void +pbuf_free_int(void *p) +{ + struct pbuf *q = (struct pbuf *)p; + pbuf_free(q); +} + +/** + * A simple wrapper function that allows you to free a pbuf from interrupt context. + * + * @param p The pbuf (chain) to be dereferenced. + * @return ERR_OK if callback could be enqueued, an err_t if not + */ +err_t +pbuf_free_callback(struct pbuf *p) +{ + return tcpip_callback_with_block(pbuf_free_int, p, 0); +} + +/** + * A simple wrapper function that allows you to free heap memory from + * interrupt context. + * + * @param m the heap memory to free + * @return ERR_OK if callback could be enqueued, an err_t if not + */ +err_t +mem_free_callback(void *m) +{ + return tcpip_callback_with_block(mem_free, m, 0); +} + +#endif /* !NO_SYS */ diff --git a/features/unsupported/net/lwip/lwip/core/def.c b/features/unsupported/net/lwip/lwip/core/def.c new file mode 100644 index 00000000000..352b55241a5 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/core/def.c @@ -0,0 +1,108 @@ +/** + * @file + * Common functions used throughout the stack. + * + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Simon Goldschmidt + * + */ + +#include "lwip/opt.h" +#include "lwip/def.h" + +/** + * These are reference implementations of the byte swapping functions. + * Again with the aim of being simple, correct and fully portable. + * Byte swapping is the second thing you would want to optimize. You will + * need to port it to your architecture and in your cc.h: + * + * #define LWIP_PLATFORM_BYTESWAP 1 + * #define LWIP_PLATFORM_HTONS(x) + * #define LWIP_PLATFORM_HTONL(x) + * + * Note ntohs() and ntohl() are merely references to the htonx counterparts. + */ + +#if (LWIP_PLATFORM_BYTESWAP == 0) && (BYTE_ORDER == LITTLE_ENDIAN) + +/** + * Convert an u16_t from host- to network byte order. + * + * @param n u16_t in host byte order + * @return n in network byte order + */ +u16_t +lwip_htons(u16_t n) +{ + return ((n & 0xff) << 8) | ((n & 0xff00) >> 8); +} + +/** + * Convert an u16_t from network- to host byte order. + * + * @param n u16_t in network byte order + * @return n in host byte order + */ +u16_t +lwip_ntohs(u16_t n) +{ + return lwip_htons(n); +} + +/** + * Convert an u32_t from host- to network byte order. + * + * @param n u32_t in host byte order + * @return n in network byte order + */ +u32_t +lwip_htonl(u32_t n) +{ + return ((n & 0xff) << 24) | + ((n & 0xff00) << 8) | + ((n & 0xff0000UL) >> 8) | + ((n & 0xff000000UL) >> 24); +} + +/** + * Convert an u32_t from network- to host byte order. + * + * @param n u32_t in network byte order + * @return n in host byte order + */ +u32_t +lwip_ntohl(u32_t n) +{ + return lwip_htonl(n); +} + +#endif /* (LWIP_PLATFORM_BYTESWAP == 0) && (BYTE_ORDER == LITTLE_ENDIAN) */ diff --git a/features/unsupported/net/lwip/lwip/core/dhcp.c b/features/unsupported/net/lwip/lwip/core/dhcp.c new file mode 100644 index 00000000000..03c0c62384c --- /dev/null +++ b/features/unsupported/net/lwip/lwip/core/dhcp.c @@ -0,0 +1,1749 @@ +/** + * @file + * Dynamic Host Configuration Protocol client + * + */ + +/* + * + * Copyright (c) 2001-2004 Leon Woestenberg + * Copyright (c) 2001-2004 Axon Digital Design B.V., The Netherlands. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is a contribution to the lwIP TCP/IP stack. + * The Swedish Institute of Computer Science and Adam Dunkels + * are specifically granted permission to redistribute this + * source code. + * + * Author: Leon Woestenberg + * + * This is a DHCP client for the lwIP TCP/IP stack. It aims to conform + * with RFC 2131 and RFC 2132. + * + * TODO: + * - Support for interfaces other than Ethernet (SLIP, PPP, ...) + * + * Please coordinate changes and requests with Leon Woestenberg + * + * + * Integration with your code: + * + * In lwip/dhcp.h + * #define DHCP_COARSE_TIMER_SECS (recommended 60 which is a minute) + * #define DHCP_FINE_TIMER_MSECS (recommended 500 which equals TCP coarse timer) + * + * Then have your application call dhcp_coarse_tmr() and + * dhcp_fine_tmr() on the defined intervals. + * + * dhcp_start(struct netif *netif); + * starts a DHCP client instance which configures the interface by + * obtaining an IP address lease and maintaining it. + * + * Use dhcp_release(netif) to end the lease and use dhcp_stop(netif) + * to remove the DHCP client. + * + */ + +#include "lwip/opt.h" + +#if LWIP_DHCP /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/stats.h" +#include "lwip/mem.h" +#include "lwip/udp.h" +#include "lwip/ip_addr.h" +#include "lwip/netif.h" +#include "lwip/def.h" +#include "lwip/sys.h" +#include "lwip/dhcp.h" +#include "lwip/autoip.h" +#include "lwip/dns.h" +#include "netif/etharp.h" + +#include + +/** Default for DHCP_GLOBAL_XID is 0xABCD0000 + * This can be changed by defining DHCP_GLOBAL_XID and DHCP_GLOBAL_XID_HEADER, e.g. + * #define DHCP_GLOBAL_XID_HEADER "stdlib.h" + * #define DHCP_GLOBAL_XID rand() + */ +#ifdef DHCP_GLOBAL_XID_HEADER +#include DHCP_GLOBAL_XID_HEADER /* include optional starting XID generation prototypes */ +#endif + +/** DHCP_OPTION_MAX_MSG_SIZE is set to the MTU + * MTU is checked to be big enough in dhcp_start */ +#define DHCP_MAX_MSG_LEN(netif) (netif->mtu) +#define DHCP_MAX_MSG_LEN_MIN_REQUIRED 576 +/** Minimum length for reply before packet is parsed */ +#define DHCP_MIN_REPLY_LEN 44 + +#define REBOOT_TRIES 2 + +/** Option handling: options are parsed in dhcp_parse_reply + * and saved in an array where other functions can load them from. + * This might be moved into the struct dhcp (not necessarily since + * lwIP is single-threaded and the array is only used while in recv + * callback). */ +#define DHCP_OPTION_IDX_OVERLOAD 0 +#define DHCP_OPTION_IDX_MSG_TYPE 1 +#define DHCP_OPTION_IDX_SERVER_ID 2 +#define DHCP_OPTION_IDX_LEASE_TIME 3 +#define DHCP_OPTION_IDX_T1 4 +#define DHCP_OPTION_IDX_T2 5 +#define DHCP_OPTION_IDX_SUBNET_MASK 6 +#define DHCP_OPTION_IDX_ROUTER 7 +#define DHCP_OPTION_IDX_DNS_SERVER 8 +#define DHCP_OPTION_IDX_MAX (DHCP_OPTION_IDX_DNS_SERVER + DNS_MAX_SERVERS) + +/** Holds the decoded option values, only valid while in dhcp_recv. + @todo: move this into struct dhcp? */ +u32_t dhcp_rx_options_val[DHCP_OPTION_IDX_MAX]; +/** Holds a flag which option was received and is contained in dhcp_rx_options_val, + only valid while in dhcp_recv. + @todo: move this into struct dhcp? */ +u8_t dhcp_rx_options_given[DHCP_OPTION_IDX_MAX]; + +#define dhcp_option_given(dhcp, idx) (dhcp_rx_options_given[idx] != 0) +#define dhcp_got_option(dhcp, idx) (dhcp_rx_options_given[idx] = 1) +#define dhcp_clear_option(dhcp, idx) (dhcp_rx_options_given[idx] = 0) +#define dhcp_clear_all_options(dhcp) (memset(dhcp_rx_options_given, 0, sizeof(dhcp_rx_options_given))) +#define dhcp_get_option_value(dhcp, idx) (dhcp_rx_options_val[idx]) +#define dhcp_set_option_value(dhcp, idx, val) (dhcp_rx_options_val[idx] = (val)) + + +/* DHCP client state machine functions */ +static err_t dhcp_discover(struct netif *netif); +static err_t dhcp_select(struct netif *netif); +static void dhcp_bind(struct netif *netif); +#if DHCP_DOES_ARP_CHECK +static err_t dhcp_decline(struct netif *netif); +#endif /* DHCP_DOES_ARP_CHECK */ +static err_t dhcp_rebind(struct netif *netif); +static err_t dhcp_reboot(struct netif *netif); +static void dhcp_set_state(struct dhcp *dhcp, u8_t new_state); + +/* receive, unfold, parse and free incoming messages */ +static void dhcp_recv(void *arg, struct udp_pcb *pcb, struct pbuf *p, ip_addr_t *addr, u16_t port); + +/* set the DHCP timers */ +static void dhcp_timeout(struct netif *netif); +static void dhcp_t1_timeout(struct netif *netif); +static void dhcp_t2_timeout(struct netif *netif); + +/* build outgoing messages */ +/* create a DHCP message, fill in common headers */ +static err_t dhcp_create_msg(struct netif *netif, struct dhcp *dhcp, u8_t message_type); +/* free a DHCP request */ +static void dhcp_delete_msg(struct dhcp *dhcp); +/* add a DHCP option (type, then length in bytes) */ +static void dhcp_option(struct dhcp *dhcp, u8_t option_type, u8_t option_len); +/* add option values */ +static void dhcp_option_byte(struct dhcp *dhcp, u8_t value); +static void dhcp_option_short(struct dhcp *dhcp, u16_t value); +static void dhcp_option_long(struct dhcp *dhcp, u32_t value); +/* always add the DHCP options trailer to end and pad */ +static void dhcp_option_trailer(struct dhcp *dhcp); + +/** + * Back-off the DHCP client (because of a received NAK response). + * + * Back-off the DHCP client because of a received NAK. Receiving a + * NAK means the client asked for something non-sensible, for + * example when it tries to renew a lease obtained on another network. + * + * We clear any existing set IP address and restart DHCP negotiation + * afresh (as per RFC2131 3.2.3). + * + * @param netif the netif under DHCP control + */ +static void +dhcp_handle_nak(struct netif *netif) +{ + struct dhcp *dhcp = netif->dhcp; + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_handle_nak(netif=%p) %c%c%"U16_F"\n", + (void*)netif, netif->name[0], netif->name[1], (u16_t)netif->num)); + /* Set the interface down since the address must no longer be used, as per RFC2131 */ + netif_set_down(netif); + /* remove IP address from interface */ + netif_set_ipaddr(netif, IP_ADDR_ANY); + netif_set_gw(netif, IP_ADDR_ANY); + netif_set_netmask(netif, IP_ADDR_ANY); + /* Change to a defined state */ + dhcp_set_state(dhcp, DHCP_BACKING_OFF); + /* We can immediately restart discovery */ + dhcp_discover(netif); +} + +#if DHCP_DOES_ARP_CHECK +/** + * Checks if the offered IP address is already in use. + * + * It does so by sending an ARP request for the offered address and + * entering CHECKING state. If no ARP reply is received within a small + * interval, the address is assumed to be free for use by us. + * + * @param netif the netif under DHCP control + */ +static void +dhcp_check(struct netif *netif) +{ + struct dhcp *dhcp = netif->dhcp; + err_t result; + u16_t msecs; + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_check(netif=%p) %c%c\n", (void *)netif, (s16_t)netif->name[0], + (s16_t)netif->name[1])); + dhcp_set_state(dhcp, DHCP_CHECKING); + /* create an ARP query for the offered IP address, expecting that no host + responds, as the IP address should not be in use. */ + result = etharp_query(netif, &dhcp->offered_ip_addr, NULL); + if (result != ERR_OK) { + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_WARNING, ("dhcp_check: could not perform ARP query\n")); + } + dhcp->tries++; + msecs = 500; + dhcp->request_timeout = (msecs + DHCP_FINE_TIMER_MSECS - 1) / DHCP_FINE_TIMER_MSECS; + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_check(): set request timeout %"U16_F" msecs\n", msecs)); +} +#endif /* DHCP_DOES_ARP_CHECK */ + +/** + * Remember the configuration offered by a DHCP server. + * + * @param netif the netif under DHCP control + */ +static void +dhcp_handle_offer(struct netif *netif) +{ + struct dhcp *dhcp = netif->dhcp; + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_handle_offer(netif=%p) %c%c%"U16_F"\n", + (void*)netif, netif->name[0], netif->name[1], (u16_t)netif->num)); + /* obtain the server address */ + if (dhcp_option_given(dhcp, DHCP_OPTION_IDX_SERVER_ID)) { + ip4_addr_set_u32(&dhcp->server_ip_addr, htonl(dhcp_get_option_value(dhcp, DHCP_OPTION_IDX_SERVER_ID))); + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_STATE, ("dhcp_handle_offer(): server 0x%08"X32_F"\n", + ip4_addr_get_u32(&dhcp->server_ip_addr))); + /* remember offered address */ + ip_addr_copy(dhcp->offered_ip_addr, dhcp->msg_in->yiaddr); + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_STATE, ("dhcp_handle_offer(): offer for 0x%08"X32_F"\n", + ip4_addr_get_u32(&dhcp->offered_ip_addr))); + + dhcp_select(netif); + } else { + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS, + ("dhcp_handle_offer(netif=%p) did not get server ID!\n", (void*)netif)); + } +} + +/** + * Select a DHCP server offer out of all offers. + * + * Simply select the first offer received. + * + * @param netif the netif under DHCP control + * @return lwIP specific error (see error.h) + */ +static err_t +dhcp_select(struct netif *netif) +{ + struct dhcp *dhcp = netif->dhcp; + err_t result; + u16_t msecs; + + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_select(netif=%p) %c%c%"U16_F"\n", (void*)netif, netif->name[0], netif->name[1], (u16_t)netif->num)); + dhcp_set_state(dhcp, DHCP_REQUESTING); + + /* create and initialize the DHCP message header */ + result = dhcp_create_msg(netif, dhcp, DHCP_REQUEST); + if (result == ERR_OK) { + dhcp_option(dhcp, DHCP_OPTION_MAX_MSG_SIZE, DHCP_OPTION_MAX_MSG_SIZE_LEN); + dhcp_option_short(dhcp, DHCP_MAX_MSG_LEN(netif)); + + /* MUST request the offered IP address */ + dhcp_option(dhcp, DHCP_OPTION_REQUESTED_IP, 4); + dhcp_option_long(dhcp, ntohl(ip4_addr_get_u32(&dhcp->offered_ip_addr))); + + dhcp_option(dhcp, DHCP_OPTION_SERVER_ID, 4); + dhcp_option_long(dhcp, ntohl(ip4_addr_get_u32(&dhcp->server_ip_addr))); + + dhcp_option(dhcp, DHCP_OPTION_PARAMETER_REQUEST_LIST, 4/*num options*/); + dhcp_option_byte(dhcp, DHCP_OPTION_SUBNET_MASK); + dhcp_option_byte(dhcp, DHCP_OPTION_ROUTER); + dhcp_option_byte(dhcp, DHCP_OPTION_BROADCAST); + dhcp_option_byte(dhcp, DHCP_OPTION_DNS_SERVER); + +#if LWIP_NETIF_HOSTNAME + if (netif->hostname != NULL) { + const char *p = (const char*)netif->hostname; + u8_t namelen = (u8_t)strlen(p); + if (namelen > 0) { + LWIP_ASSERT("DHCP: hostname is too long!", namelen < 255); + dhcp_option(dhcp, DHCP_OPTION_HOSTNAME, namelen); + while (*p) { + dhcp_option_byte(dhcp, *p++); + } + } + } +#endif /* LWIP_NETIF_HOSTNAME */ + + dhcp_option_trailer(dhcp); + /* shrink the pbuf to the actual content length */ + pbuf_realloc(dhcp->p_out, sizeof(struct dhcp_msg) - DHCP_OPTIONS_LEN + dhcp->options_out_len); + + /* send broadcast to any DHCP server */ + udp_sendto_if(dhcp->pcb, dhcp->p_out, IP_ADDR_BROADCAST, DHCP_SERVER_PORT, netif); + dhcp_delete_msg(dhcp); + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_select: REQUESTING\n")); + } else { + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_WARNING, ("dhcp_select: could not allocate DHCP request\n")); + } + dhcp->tries++; + msecs = (dhcp->tries < 6 ? 1 << dhcp->tries : 60) * 1000; + dhcp->request_timeout = (msecs + DHCP_FINE_TIMER_MSECS - 1) / DHCP_FINE_TIMER_MSECS; + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_STATE, ("dhcp_select(): set request timeout %"U16_F" msecs\n", msecs)); + return result; +} + +/** + * The DHCP timer that checks for lease renewal/rebind timeouts. + */ +void +dhcp_coarse_tmr() +{ + struct netif *netif = netif_list; + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_coarse_tmr()\n")); + /* iterate through all network interfaces */ + while (netif != NULL) { + /* only act on DHCP configured interfaces */ + if (netif->dhcp != NULL) { + /* timer is active (non zero), and triggers (zeroes) now? */ + if (netif->dhcp->t2_timeout-- == 1) { + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_coarse_tmr(): t2 timeout\n")); + /* this clients' rebind timeout triggered */ + dhcp_t2_timeout(netif); + /* timer is active (non zero), and triggers (zeroes) now */ + } else if (netif->dhcp->t1_timeout-- == 1) { + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_coarse_tmr(): t1 timeout\n")); + /* this clients' renewal timeout triggered */ + dhcp_t1_timeout(netif); + } + } + /* proceed to next netif */ + netif = netif->next; + } +} + +/** + * DHCP transaction timeout handling + * + * A DHCP server is expected to respond within a short period of time. + * This timer checks whether an outstanding DHCP request is timed out. + */ +void +dhcp_fine_tmr() +{ + struct netif *netif = netif_list; + /* loop through netif's */ + while (netif != NULL) { + /* only act on DHCP configured interfaces */ + if (netif->dhcp != NULL) { + /* timer is active (non zero), and is about to trigger now */ + if (netif->dhcp->request_timeout > 1) { + netif->dhcp->request_timeout--; + } + else if (netif->dhcp->request_timeout == 1) { + netif->dhcp->request_timeout--; + /* { netif->dhcp->request_timeout == 0 } */ + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_fine_tmr(): request timeout\n")); + /* this client's request timeout triggered */ + dhcp_timeout(netif); + } + } + /* proceed to next network interface */ + netif = netif->next; + } +} + +/** + * A DHCP negotiation transaction, or ARP request, has timed out. + * + * The timer that was started with the DHCP or ARP request has + * timed out, indicating no response was received in time. + * + * @param netif the netif under DHCP control + */ +static void +dhcp_timeout(struct netif *netif) +{ + struct dhcp *dhcp = netif->dhcp; + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_timeout()\n")); + /* back-off period has passed, or server selection timed out */ + if ((dhcp->state == DHCP_BACKING_OFF) || (dhcp->state == DHCP_SELECTING)) { + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_timeout(): restarting discovery\n")); + dhcp_discover(netif); + /* receiving the requested lease timed out */ + } else if (dhcp->state == DHCP_REQUESTING) { + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_timeout(): REQUESTING, DHCP request timed out\n")); + if (dhcp->tries <= 5) { + dhcp_select(netif); + } else { + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_timeout(): REQUESTING, releasing, restarting\n")); + dhcp_release(netif); + dhcp_discover(netif); + } +#if DHCP_DOES_ARP_CHECK + /* received no ARP reply for the offered address (which is good) */ + } else if (dhcp->state == DHCP_CHECKING) { + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_timeout(): CHECKING, ARP request timed out\n")); + if (dhcp->tries <= 1) { + dhcp_check(netif); + /* no ARP replies on the offered address, + looks like the IP address is indeed free */ + } else { + /* bind the interface to the offered address */ + dhcp_bind(netif); + } +#endif /* DHCP_DOES_ARP_CHECK */ + } + /* did not get response to renew request? */ + else if (dhcp->state == DHCP_RENEWING) { + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_timeout(): RENEWING, DHCP request timed out\n")); + /* just retry renewal */ + /* note that the rebind timer will eventually time-out if renew does not work */ + dhcp_renew(netif); + /* did not get response to rebind request? */ + } else if (dhcp->state == DHCP_REBINDING) { + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_timeout(): REBINDING, DHCP request timed out\n")); + if (dhcp->tries <= 8) { + dhcp_rebind(netif); + } else { + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_timeout(): RELEASING, DISCOVERING\n")); + dhcp_release(netif); + dhcp_discover(netif); + } + } else if (dhcp->state == DHCP_REBOOTING) { + if (dhcp->tries < REBOOT_TRIES) { + dhcp_reboot(netif); + } else { + dhcp_discover(netif); + } + } +} + +/** + * The renewal period has timed out. + * + * @param netif the netif under DHCP control + */ +static void +dhcp_t1_timeout(struct netif *netif) +{ + struct dhcp *dhcp = netif->dhcp; + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_STATE, ("dhcp_t1_timeout()\n")); + if ((dhcp->state == DHCP_REQUESTING) || (dhcp->state == DHCP_BOUND) || + (dhcp->state == DHCP_RENEWING)) { + /* just retry to renew - note that the rebind timer (t2) will + * eventually time-out if renew tries fail. */ + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, + ("dhcp_t1_timeout(): must renew\n")); + /* This slightly different to RFC2131: DHCPREQUEST will be sent from state + DHCP_RENEWING, not DHCP_BOUND */ + dhcp_renew(netif); + } +} + +/** + * The rebind period has timed out. + * + * @param netif the netif under DHCP control + */ +static void +dhcp_t2_timeout(struct netif *netif) +{ + struct dhcp *dhcp = netif->dhcp; + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_t2_timeout()\n")); + if ((dhcp->state == DHCP_REQUESTING) || (dhcp->state == DHCP_BOUND) || + (dhcp->state == DHCP_RENEWING)) { + /* just retry to rebind */ + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, + ("dhcp_t2_timeout(): must rebind\n")); + /* This slightly different to RFC2131: DHCPREQUEST will be sent from state + DHCP_REBINDING, not DHCP_BOUND */ + dhcp_rebind(netif); + } +} + +/** + * Handle a DHCP ACK packet + * + * @param netif the netif under DHCP control + */ +static void +dhcp_handle_ack(struct netif *netif) +{ + struct dhcp *dhcp = netif->dhcp; +#if LWIP_DNS + u8_t n; +#endif /* LWIP_DNS */ + + /* clear options we might not get from the ACK */ + ip_addr_set_zero(&dhcp->offered_sn_mask); + ip_addr_set_zero(&dhcp->offered_gw_addr); +#if LWIP_DHCP_BOOTP_FILE + ip_addr_set_zero(&dhcp->offered_si_addr); +#endif /* LWIP_DHCP_BOOTP_FILE */ + + /* lease time given? */ + if (dhcp_option_given(dhcp, DHCP_OPTION_IDX_LEASE_TIME)) { + /* remember offered lease time */ + dhcp->offered_t0_lease = dhcp_get_option_value(dhcp, DHCP_OPTION_IDX_LEASE_TIME); + } + /* renewal period given? */ + if (dhcp_option_given(dhcp, DHCP_OPTION_IDX_T1)) { + /* remember given renewal period */ + dhcp->offered_t1_renew = dhcp_get_option_value(dhcp, DHCP_OPTION_IDX_T1); + } else { + /* calculate safe periods for renewal */ + dhcp->offered_t1_renew = dhcp->offered_t0_lease / 2; + } + + /* renewal period given? */ + if (dhcp_option_given(dhcp, DHCP_OPTION_IDX_T2)) { + /* remember given rebind period */ + dhcp->offered_t2_rebind = dhcp_get_option_value(dhcp, DHCP_OPTION_IDX_T2); + } else { + /* calculate safe periods for rebinding */ + dhcp->offered_t2_rebind = dhcp->offered_t0_lease; + } + + /* (y)our internet address */ + ip_addr_copy(dhcp->offered_ip_addr, dhcp->msg_in->yiaddr); + +#if LWIP_DHCP_BOOTP_FILE + /* copy boot server address, + boot file name copied in dhcp_parse_reply if not overloaded */ + ip_addr_copy(dhcp->offered_si_addr, dhcp->msg_in->siaddr); +#endif /* LWIP_DHCP_BOOTP_FILE */ + + /* subnet mask given? */ + if (dhcp_option_given(dhcp, DHCP_OPTION_IDX_SUBNET_MASK)) { + /* remember given subnet mask */ + ip4_addr_set_u32(&dhcp->offered_sn_mask, htonl(dhcp_get_option_value(dhcp, DHCP_OPTION_IDX_SUBNET_MASK))); + dhcp->subnet_mask_given = 1; + } else { + dhcp->subnet_mask_given = 0; + } + + /* gateway router */ + if (dhcp_option_given(dhcp, DHCP_OPTION_IDX_ROUTER)) { + ip4_addr_set_u32(&dhcp->offered_gw_addr, htonl(dhcp_get_option_value(dhcp, DHCP_OPTION_IDX_ROUTER))); + } + +#if LWIP_DNS + /* DNS servers */ + n = 0; + while((n < DNS_MAX_SERVERS) && dhcp_option_given(dhcp, DHCP_OPTION_IDX_DNS_SERVER + n)) { + ip_addr_t dns_addr; + ip4_addr_set_u32(&dns_addr, htonl(dhcp_get_option_value(dhcp, DHCP_OPTION_IDX_DNS_SERVER + n))); + dns_setserver(n, &dns_addr); + n++; + } +#endif /* LWIP_DNS */ +} + +/** Set a statically allocated struct dhcp to work with. + * Using this prevents dhcp_start to allocate it using mem_malloc. + * + * @param netif the netif for which to set the struct dhcp + * @param dhcp (uninitialised) dhcp struct allocated by the application + */ +void +dhcp_set_struct(struct netif *netif, struct dhcp *dhcp) +{ + LWIP_ASSERT("netif != NULL", netif != NULL); + LWIP_ASSERT("dhcp != NULL", dhcp != NULL); + LWIP_ASSERT("netif already has a struct dhcp set", netif->dhcp == NULL); + + /* clear data structure */ + memset(dhcp, 0, sizeof(struct dhcp)); + /* dhcp_set_state(&dhcp, DHCP_OFF); */ + netif->dhcp = dhcp; +} + +/** Removes a struct dhcp from a netif. + * + * ATTENTION: Only use this when not using dhcp_set_struct() to allocate the + * struct dhcp since the memory is passed back to the heap. + * + * @param netif the netif from which to remove the struct dhcp + */ +void dhcp_cleanup(struct netif *netif) +{ + LWIP_ASSERT("netif != NULL", netif != NULL); + + if (netif->dhcp != NULL) { + mem_free(netif->dhcp); + netif->dhcp = NULL; + } +} + +/** + * Start DHCP negotiation for a network interface. + * + * If no DHCP client instance was attached to this interface, + * a new client is created first. If a DHCP client instance + * was already present, it restarts negotiation. + * + * @param netif The lwIP network interface + * @return lwIP error code + * - ERR_OK - No error + * - ERR_MEM - Out of memory + */ +err_t +dhcp_start(struct netif *netif) +{ + struct dhcp *dhcp; + err_t result = ERR_OK; + + LWIP_ERROR("netif != NULL", (netif != NULL), return ERR_ARG;); + dhcp = netif->dhcp; + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_start(netif=%p) %c%c%"U16_F"\n", (void*)netif, netif->name[0], netif->name[1], (u16_t)netif->num)); + /* Remove the flag that says this netif is handled by DHCP, + it is set when we succeeded starting. */ + netif->flags &= ~NETIF_FLAG_DHCP; + + /* check hwtype of the netif */ + if ((netif->flags & NETIF_FLAG_ETHARP) == 0) { + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_start(): No ETHARP netif\n")); + return ERR_ARG; + } + + /* check MTU of the netif */ + if (netif->mtu < DHCP_MAX_MSG_LEN_MIN_REQUIRED) { + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_start(): Cannot use this netif with DHCP: MTU is too small\n")); + return ERR_MEM; + } + + /* no DHCP client attached yet? */ + if (dhcp == NULL) { + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_start(): starting new DHCP client\n")); + dhcp = (struct dhcp *)mem_malloc(sizeof(struct dhcp)); + if (dhcp == NULL) { + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_start(): could not allocate dhcp\n")); + return ERR_MEM; + } + /* store this dhcp client in the netif */ + netif->dhcp = dhcp; + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_start(): allocated dhcp")); + /* already has DHCP client attached */ + } else { + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_start(): restarting DHCP configuration\n")); + if (dhcp->pcb != NULL) { + udp_remove(dhcp->pcb); + } + LWIP_ASSERT("pbuf p_out wasn't freed", dhcp->p_out == NULL); + LWIP_ASSERT("reply wasn't freed", dhcp->msg_in == NULL ); + } + + /* clear data structure */ + memset(dhcp, 0, sizeof(struct dhcp)); + /* dhcp_set_state(&dhcp, DHCP_OFF); */ + /* allocate UDP PCB */ + dhcp->pcb = udp_new(); + if (dhcp->pcb == NULL) { + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_start(): could not obtain pcb\n")); + return ERR_MEM; + } + dhcp->pcb->so_options |= SOF_BROADCAST; + /* set up local and remote port for the pcb */ + udp_bind(dhcp->pcb, IP_ADDR_ANY, DHCP_CLIENT_PORT); + udp_connect(dhcp->pcb, IP_ADDR_ANY, DHCP_SERVER_PORT); + /* set up the recv callback and argument */ + udp_recv(dhcp->pcb, dhcp_recv, netif); + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_start(): starting DHCP configuration\n")); + /* (re)start the DHCP negotiation */ + result = dhcp_discover(netif); + if (result != ERR_OK) { + /* free resources allocated above */ + dhcp_stop(netif); + return ERR_MEM; + } + /* Set the flag that says this netif is handled by DHCP. */ + netif->flags |= NETIF_FLAG_DHCP; + return result; +} + +/** + * Inform a DHCP server of our manual configuration. + * + * This informs DHCP servers of our fixed IP address configuration + * by sending an INFORM message. It does not involve DHCP address + * configuration, it is just here to be nice to the network. + * + * @param netif The lwIP network interface + */ +void +dhcp_inform(struct netif *netif) +{ + struct dhcp dhcp; + err_t result = ERR_OK; + struct udp_pcb *pcb; + + LWIP_ERROR("netif != NULL", (netif != NULL), return;); + + memset(&dhcp, 0, sizeof(struct dhcp)); + dhcp_set_state(&dhcp, DHCP_INFORM); + + if ((netif->dhcp != NULL) && (netif->dhcp->pcb != NULL)) { + /* re-use existing pcb */ + pcb = netif->dhcp->pcb; + } else { + pcb = udp_new(); + if (pcb == NULL) { + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS, ("dhcp_inform(): could not obtain pcb")); + return; + } + dhcp.pcb = pcb; + dhcp.pcb->so_options |= SOF_BROADCAST; + udp_bind(dhcp.pcb, IP_ADDR_ANY, DHCP_CLIENT_PORT); + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_inform(): created new udp pcb\n")); + } + /* create and initialize the DHCP message header */ + result = dhcp_create_msg(netif, &dhcp, DHCP_INFORM); + if (result == ERR_OK) { + dhcp_option(&dhcp, DHCP_OPTION_MAX_MSG_SIZE, DHCP_OPTION_MAX_MSG_SIZE_LEN); + dhcp_option_short(&dhcp, DHCP_MAX_MSG_LEN(netif)); + + dhcp_option_trailer(&dhcp); + + pbuf_realloc(dhcp.p_out, sizeof(struct dhcp_msg) - DHCP_OPTIONS_LEN + dhcp.options_out_len); + + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_inform: INFORMING\n")); + udp_sendto_if(pcb, dhcp.p_out, IP_ADDR_BROADCAST, DHCP_SERVER_PORT, netif); + dhcp_delete_msg(&dhcp); + } else { + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS, ("dhcp_inform: could not allocate DHCP request\n")); + } + + if (dhcp.pcb != NULL) { + /* otherwise, the existing pcb was used */ + udp_remove(dhcp.pcb); + } +} + +/** Handle a possible change in the network configuration. + * + * This enters the REBOOTING state to verify that the currently bound + * address is still valid. + */ +void +dhcp_network_changed(struct netif *netif) +{ + struct dhcp *dhcp = netif->dhcp; + if (!dhcp) + return; + switch (dhcp->state) { + case DHCP_REBINDING: + case DHCP_RENEWING: + case DHCP_BOUND: + case DHCP_REBOOTING: + netif_set_down(netif); + dhcp->tries = 0; + dhcp_reboot(netif); + break; + case DHCP_OFF: + /* stay off */ + break; + default: + dhcp->tries = 0; +#if LWIP_DHCP_AUTOIP_COOP + if(dhcp->autoip_coop_state == DHCP_AUTOIP_COOP_STATE_ON) { + autoip_stop(netif); + dhcp->autoip_coop_state = DHCP_AUTOIP_COOP_STATE_OFF; + } +#endif /* LWIP_DHCP_AUTOIP_COOP */ + dhcp_discover(netif); + break; + } +} + +#if DHCP_DOES_ARP_CHECK +/** + * Match an ARP reply with the offered IP address. + * + * @param netif the network interface on which the reply was received + * @param addr The IP address we received a reply from + */ +void dhcp_arp_reply(struct netif *netif, ip_addr_t *addr) +{ + LWIP_ERROR("netif != NULL", (netif != NULL), return;); + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_arp_reply()\n")); + /* is a DHCP client doing an ARP check? */ + if ((netif->dhcp != NULL) && (netif->dhcp->state == DHCP_CHECKING)) { + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_arp_reply(): CHECKING, arp reply for 0x%08"X32_F"\n", + ip4_addr_get_u32(addr))); + /* did a host respond with the address we + were offered by the DHCP server? */ + if (ip_addr_cmp(addr, &netif->dhcp->offered_ip_addr)) { + /* we will not accept the offered address */ + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE | LWIP_DBG_LEVEL_WARNING, + ("dhcp_arp_reply(): arp reply matched with offered address, declining\n")); + dhcp_decline(netif); + } + } +} + +/** + * Decline an offered lease. + * + * Tell the DHCP server we do not accept the offered address. + * One reason to decline the lease is when we find out the address + * is already in use by another host (through ARP). + * + * @param netif the netif under DHCP control + */ +static err_t +dhcp_decline(struct netif *netif) +{ + struct dhcp *dhcp = netif->dhcp; + err_t result = ERR_OK; + u16_t msecs; + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_decline()\n")); + dhcp_set_state(dhcp, DHCP_BACKING_OFF); + /* create and initialize the DHCP message header */ + result = dhcp_create_msg(netif, dhcp, DHCP_DECLINE); + if (result == ERR_OK) { + dhcp_option(dhcp, DHCP_OPTION_REQUESTED_IP, 4); + dhcp_option_long(dhcp, ntohl(ip4_addr_get_u32(&dhcp->offered_ip_addr))); + + dhcp_option_trailer(dhcp); + /* resize pbuf to reflect true size of options */ + pbuf_realloc(dhcp->p_out, sizeof(struct dhcp_msg) - DHCP_OPTIONS_LEN + dhcp->options_out_len); + + /* per section 4.4.4, broadcast DECLINE messages */ + udp_sendto_if(dhcp->pcb, dhcp->p_out, IP_ADDR_BROADCAST, DHCP_SERVER_PORT, netif); + dhcp_delete_msg(dhcp); + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_decline: BACKING OFF\n")); + } else { + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS, + ("dhcp_decline: could not allocate DHCP request\n")); + } + dhcp->tries++; + msecs = 10*1000; + dhcp->request_timeout = (msecs + DHCP_FINE_TIMER_MSECS - 1) / DHCP_FINE_TIMER_MSECS; + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_decline(): set request timeout %"U16_F" msecs\n", msecs)); + return result; +} +#endif /* DHCP_DOES_ARP_CHECK */ + + +/** + * Start the DHCP process, discover a DHCP server. + * + * @param netif the netif under DHCP control + */ +static err_t +dhcp_discover(struct netif *netif) +{ + struct dhcp *dhcp = netif->dhcp; + err_t result = ERR_OK; + u16_t msecs; + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_discover()\n")); + ip_addr_set_any(&dhcp->offered_ip_addr); + dhcp_set_state(dhcp, DHCP_SELECTING); + /* create and initialize the DHCP message header */ + result = dhcp_create_msg(netif, dhcp, DHCP_DISCOVER); + if (result == ERR_OK) { + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_discover: making request\n")); + + dhcp_option(dhcp, DHCP_OPTION_MAX_MSG_SIZE, DHCP_OPTION_MAX_MSG_SIZE_LEN); + dhcp_option_short(dhcp, DHCP_MAX_MSG_LEN(netif)); + + dhcp_option(dhcp, DHCP_OPTION_PARAMETER_REQUEST_LIST, 4/*num options*/); + dhcp_option_byte(dhcp, DHCP_OPTION_SUBNET_MASK); + dhcp_option_byte(dhcp, DHCP_OPTION_ROUTER); + dhcp_option_byte(dhcp, DHCP_OPTION_BROADCAST); + dhcp_option_byte(dhcp, DHCP_OPTION_DNS_SERVER); + + dhcp_option_trailer(dhcp); + + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_discover: realloc()ing\n")); + pbuf_realloc(dhcp->p_out, sizeof(struct dhcp_msg) - DHCP_OPTIONS_LEN + dhcp->options_out_len); + + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_discover: sendto(DISCOVER, IP_ADDR_BROADCAST, DHCP_SERVER_PORT)\n")); + udp_sendto_if(dhcp->pcb, dhcp->p_out, IP_ADDR_BROADCAST, DHCP_SERVER_PORT, netif); + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_discover: deleting()ing\n")); + dhcp_delete_msg(dhcp); + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_discover: SELECTING\n")); + } else { + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS, ("dhcp_discover: could not allocate DHCP request\n")); + } + dhcp->tries++; +#if LWIP_DHCP_AUTOIP_COOP + if(dhcp->tries >= LWIP_DHCP_AUTOIP_COOP_TRIES && dhcp->autoip_coop_state == DHCP_AUTOIP_COOP_STATE_OFF) { + dhcp->autoip_coop_state = DHCP_AUTOIP_COOP_STATE_ON; + autoip_start(netif); + } +#endif /* LWIP_DHCP_AUTOIP_COOP */ + msecs = (dhcp->tries < 6 ? 1 << dhcp->tries : 60) * 1000; + dhcp->request_timeout = (msecs + DHCP_FINE_TIMER_MSECS - 1) / DHCP_FINE_TIMER_MSECS; + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_discover(): set request timeout %"U16_F" msecs\n", msecs)); + return result; +} + + +/** + * Bind the interface to the offered IP address. + * + * @param netif network interface to bind to the offered address + */ +static void +dhcp_bind(struct netif *netif) +{ + u32_t timeout; + struct dhcp *dhcp; + ip_addr_t sn_mask, gw_addr; + LWIP_ERROR("dhcp_bind: netif != NULL", (netif != NULL), return;); + dhcp = netif->dhcp; + LWIP_ERROR("dhcp_bind: dhcp != NULL", (dhcp != NULL), return;); + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_bind(netif=%p) %c%c%"U16_F"\n", (void*)netif, netif->name[0], netif->name[1], (u16_t)netif->num)); + + /* temporary DHCP lease? */ + if (dhcp->offered_t1_renew != 0xffffffffUL) { + /* set renewal period timer */ + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_bind(): t1 renewal timer %"U32_F" secs\n", dhcp->offered_t1_renew)); + timeout = (dhcp->offered_t1_renew + DHCP_COARSE_TIMER_SECS / 2) / DHCP_COARSE_TIMER_SECS; + if(timeout > 0xffff) { + timeout = 0xffff; + } + dhcp->t1_timeout = (u16_t)timeout; + if (dhcp->t1_timeout == 0) { + dhcp->t1_timeout = 1; + } + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_bind(): set request timeout %"U32_F" msecs\n", dhcp->offered_t1_renew*1000)); + } + /* set renewal period timer */ + if (dhcp->offered_t2_rebind != 0xffffffffUL) { + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_bind(): t2 rebind timer %"U32_F" secs\n", dhcp->offered_t2_rebind)); + timeout = (dhcp->offered_t2_rebind + DHCP_COARSE_TIMER_SECS / 2) / DHCP_COARSE_TIMER_SECS; + if(timeout > 0xffff) { + timeout = 0xffff; + } + dhcp->t2_timeout = (u16_t)timeout; + if (dhcp->t2_timeout == 0) { + dhcp->t2_timeout = 1; + } + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_bind(): set request timeout %"U32_F" msecs\n", dhcp->offered_t2_rebind*1000)); + } + + if (dhcp->subnet_mask_given) { + /* copy offered network mask */ + ip_addr_copy(sn_mask, dhcp->offered_sn_mask); + } else { + /* subnet mask not given, choose a safe subnet mask given the network class */ + u8_t first_octet = ip4_addr1(&dhcp->offered_ip_addr); + if (first_octet <= 127) { + ip4_addr_set_u32(&sn_mask, PP_HTONL(0xff000000UL)); + } else if (first_octet >= 192) { + ip4_addr_set_u32(&sn_mask, PP_HTONL(0xffffff00UL)); + } else { + ip4_addr_set_u32(&sn_mask, PP_HTONL(0xffff0000UL)); + } + } + + ip_addr_copy(gw_addr, dhcp->offered_gw_addr); + /* gateway address not given? */ + if (gw_addr.addr == IPADDR_ANY) { + /* copy network address */ + ip_addr_get_network(&gw_addr, &dhcp->offered_ip_addr, &sn_mask); + /* use first host address on network as gateway */ + ip4_addr_set_u32(&gw_addr, ip4_addr_get_u32(&gw_addr) | PP_HTONL(0x00000001UL)); + } + +#if LWIP_DHCP_AUTOIP_COOP + if(dhcp->autoip_coop_state == DHCP_AUTOIP_COOP_STATE_ON) { + autoip_stop(netif); + dhcp->autoip_coop_state = DHCP_AUTOIP_COOP_STATE_OFF; + } +#endif /* LWIP_DHCP_AUTOIP_COOP */ + + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_STATE, ("dhcp_bind(): IP: 0x%08"X32_F"\n", + ip4_addr_get_u32(&dhcp->offered_ip_addr))); + netif_set_ipaddr(netif, &dhcp->offered_ip_addr); + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_STATE, ("dhcp_bind(): SN: 0x%08"X32_F"\n", + ip4_addr_get_u32(&sn_mask))); + netif_set_netmask(netif, &sn_mask); + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_STATE, ("dhcp_bind(): GW: 0x%08"X32_F"\n", + ip4_addr_get_u32(&gw_addr))); + netif_set_gw(netif, &gw_addr); + /* bring the interface up */ + netif_set_up(netif); + /* netif is now bound to DHCP leased address */ + dhcp_set_state(dhcp, DHCP_BOUND); +} + +/** + * Renew an existing DHCP lease at the involved DHCP server. + * + * @param netif network interface which must renew its lease + */ +err_t +dhcp_renew(struct netif *netif) +{ + struct dhcp *dhcp = netif->dhcp; + err_t result; + u16_t msecs; + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_renew()\n")); + dhcp_set_state(dhcp, DHCP_RENEWING); + + /* create and initialize the DHCP message header */ + result = dhcp_create_msg(netif, dhcp, DHCP_REQUEST); + if (result == ERR_OK) { + dhcp_option(dhcp, DHCP_OPTION_MAX_MSG_SIZE, DHCP_OPTION_MAX_MSG_SIZE_LEN); + dhcp_option_short(dhcp, DHCP_MAX_MSG_LEN(netif)); + +#if LWIP_NETIF_HOSTNAME + if (netif->hostname != NULL) { + const char *p = (const char*)netif->hostname; + u8_t namelen = (u8_t)strlen(p); + if (namelen > 0) { + LWIP_ASSERT("DHCP: hostname is too long!", namelen < 255); + dhcp_option(dhcp, DHCP_OPTION_HOSTNAME, namelen); + while (*p) { + dhcp_option_byte(dhcp, *p++); + } + } + } +#endif /* LWIP_NETIF_HOSTNAME */ + +#if 0 + dhcp_option(dhcp, DHCP_OPTION_REQUESTED_IP, 4); + dhcp_option_long(dhcp, ntohl(dhcp->offered_ip_addr.addr)); +#endif + +#if 0 + dhcp_option(dhcp, DHCP_OPTION_SERVER_ID, 4); + dhcp_option_long(dhcp, ntohl(dhcp->server_ip_addr.addr)); +#endif + /* append DHCP message trailer */ + dhcp_option_trailer(dhcp); + + pbuf_realloc(dhcp->p_out, sizeof(struct dhcp_msg) - DHCP_OPTIONS_LEN + dhcp->options_out_len); + + udp_sendto_if(dhcp->pcb, dhcp->p_out, &dhcp->server_ip_addr, DHCP_SERVER_PORT, netif); + dhcp_delete_msg(dhcp); + + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_renew: RENEWING\n")); + } else { + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS, ("dhcp_renew: could not allocate DHCP request\n")); + } + dhcp->tries++; + /* back-off on retries, but to a maximum of 20 seconds */ + msecs = dhcp->tries < 10 ? dhcp->tries * 2000 : 20 * 1000; + dhcp->request_timeout = (msecs + DHCP_FINE_TIMER_MSECS - 1) / DHCP_FINE_TIMER_MSECS; + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_renew(): set request timeout %"U16_F" msecs\n", msecs)); + return result; +} + +/** + * Rebind with a DHCP server for an existing DHCP lease. + * + * @param netif network interface which must rebind with a DHCP server + */ +static err_t +dhcp_rebind(struct netif *netif) +{ + struct dhcp *dhcp = netif->dhcp; + err_t result; + u16_t msecs; + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_rebind()\n")); + dhcp_set_state(dhcp, DHCP_REBINDING); + + /* create and initialize the DHCP message header */ + result = dhcp_create_msg(netif, dhcp, DHCP_REQUEST); + if (result == ERR_OK) { + dhcp_option(dhcp, DHCP_OPTION_MAX_MSG_SIZE, DHCP_OPTION_MAX_MSG_SIZE_LEN); + dhcp_option_short(dhcp, DHCP_MAX_MSG_LEN(netif)); + +#if LWIP_NETIF_HOSTNAME + if (netif->hostname != NULL) { + const char *p = (const char*)netif->hostname; + u8_t namelen = (u8_t)strlen(p); + if (namelen > 0) { + LWIP_ASSERT("DHCP: hostname is too long!", namelen < 255); + dhcp_option(dhcp, DHCP_OPTION_HOSTNAME, namelen); + while (*p) { + dhcp_option_byte(dhcp, *p++); + } + } + } +#endif /* LWIP_NETIF_HOSTNAME */ + +#if 0 + dhcp_option(dhcp, DHCP_OPTION_REQUESTED_IP, 4); + dhcp_option_long(dhcp, ntohl(dhcp->offered_ip_addr.addr)); + + dhcp_option(dhcp, DHCP_OPTION_SERVER_ID, 4); + dhcp_option_long(dhcp, ntohl(dhcp->server_ip_addr.addr)); +#endif + + dhcp_option_trailer(dhcp); + + pbuf_realloc(dhcp->p_out, sizeof(struct dhcp_msg) - DHCP_OPTIONS_LEN + dhcp->options_out_len); + + /* broadcast to server */ + udp_sendto_if(dhcp->pcb, dhcp->p_out, IP_ADDR_BROADCAST, DHCP_SERVER_PORT, netif); + dhcp_delete_msg(dhcp); + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_rebind: REBINDING\n")); + } else { + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS, ("dhcp_rebind: could not allocate DHCP request\n")); + } + dhcp->tries++; + msecs = dhcp->tries < 10 ? dhcp->tries * 1000 : 10 * 1000; + dhcp->request_timeout = (msecs + DHCP_FINE_TIMER_MSECS - 1) / DHCP_FINE_TIMER_MSECS; + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_rebind(): set request timeout %"U16_F" msecs\n", msecs)); + return result; +} + +/** + * Enter REBOOTING state to verify an existing lease + * + * @param netif network interface which must reboot + */ +static err_t +dhcp_reboot(struct netif *netif) +{ + struct dhcp *dhcp = netif->dhcp; + err_t result; + u16_t msecs; + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_reboot()\n")); + dhcp_set_state(dhcp, DHCP_REBOOTING); + + /* create and initialize the DHCP message header */ + result = dhcp_create_msg(netif, dhcp, DHCP_REQUEST); + if (result == ERR_OK) { + dhcp_option(dhcp, DHCP_OPTION_MAX_MSG_SIZE, DHCP_OPTION_MAX_MSG_SIZE_LEN); + dhcp_option_short(dhcp, 576); + + dhcp_option(dhcp, DHCP_OPTION_REQUESTED_IP, 4); + dhcp_option_long(dhcp, ntohl(ip4_addr_get_u32(&dhcp->offered_ip_addr))); + + dhcp_option_trailer(dhcp); + + pbuf_realloc(dhcp->p_out, sizeof(struct dhcp_msg) - DHCP_OPTIONS_LEN + dhcp->options_out_len); + + /* broadcast to server */ + udp_sendto_if(dhcp->pcb, dhcp->p_out, IP_ADDR_BROADCAST, DHCP_SERVER_PORT, netif); + dhcp_delete_msg(dhcp); + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_reboot: REBOOTING\n")); + } else { + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS, ("dhcp_reboot: could not allocate DHCP request\n")); + } + dhcp->tries++; + msecs = dhcp->tries < 10 ? dhcp->tries * 1000 : 10 * 1000; + dhcp->request_timeout = (msecs + DHCP_FINE_TIMER_MSECS - 1) / DHCP_FINE_TIMER_MSECS; + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_reboot(): set request timeout %"U16_F" msecs\n", msecs)); + return result; +} + + +/** + * Release a DHCP lease. + * + * @param netif network interface which must release its lease + */ +err_t +dhcp_release(struct netif *netif) +{ + struct dhcp *dhcp = netif->dhcp; + err_t result; + u16_t msecs; + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_release()\n")); + + /* idle DHCP client */ + dhcp_set_state(dhcp, DHCP_OFF); + /* clean old DHCP offer */ + ip_addr_set_zero(&dhcp->server_ip_addr); + ip_addr_set_zero(&dhcp->offered_ip_addr); + ip_addr_set_zero(&dhcp->offered_sn_mask); + ip_addr_set_zero(&dhcp->offered_gw_addr); +#if LWIP_DHCP_BOOTP_FILE + ip_addr_set_zero(&dhcp->offered_si_addr); +#endif /* LWIP_DHCP_BOOTP_FILE */ + dhcp->offered_t0_lease = dhcp->offered_t1_renew = dhcp->offered_t2_rebind = 0; + + /* create and initialize the DHCP message header */ + result = dhcp_create_msg(netif, dhcp, DHCP_RELEASE); + if (result == ERR_OK) { + dhcp_option_trailer(dhcp); + + pbuf_realloc(dhcp->p_out, sizeof(struct dhcp_msg) - DHCP_OPTIONS_LEN + dhcp->options_out_len); + + udp_sendto_if(dhcp->pcb, dhcp->p_out, &dhcp->server_ip_addr, DHCP_SERVER_PORT, netif); + dhcp_delete_msg(dhcp); + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_release: RELEASED, DHCP_OFF\n")); + } else { + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS, ("dhcp_release: could not allocate DHCP request\n")); + } + dhcp->tries++; + msecs = dhcp->tries < 10 ? dhcp->tries * 1000 : 10 * 1000; + dhcp->request_timeout = (msecs + DHCP_FINE_TIMER_MSECS - 1) / DHCP_FINE_TIMER_MSECS; + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp_release(): set request timeout %"U16_F" msecs\n", msecs)); + /* bring the interface down */ + netif_set_down(netif); + /* remove IP address from interface */ + netif_set_ipaddr(netif, IP_ADDR_ANY); + netif_set_gw(netif, IP_ADDR_ANY); + netif_set_netmask(netif, IP_ADDR_ANY); + + return result; +} + +/** + * Remove the DHCP client from the interface. + * + * @param netif The network interface to stop DHCP on + */ +void +dhcp_stop(struct netif *netif) +{ + struct dhcp *dhcp; + LWIP_ERROR("dhcp_stop: netif != NULL", (netif != NULL), return;); + dhcp = netif->dhcp; + /* Remove the flag that says this netif is handled by DHCP. */ + netif->flags &= ~NETIF_FLAG_DHCP; + + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_stop()\n")); + /* netif is DHCP configured? */ + if (dhcp != NULL) { +#if LWIP_DHCP_AUTOIP_COOP + if(dhcp->autoip_coop_state == DHCP_AUTOIP_COOP_STATE_ON) { + autoip_stop(netif); + dhcp->autoip_coop_state = DHCP_AUTOIP_COOP_STATE_OFF; + } +#endif /* LWIP_DHCP_AUTOIP_COOP */ + + if (dhcp->pcb != NULL) { + udp_remove(dhcp->pcb); + dhcp->pcb = NULL; + } + LWIP_ASSERT("reply wasn't freed", dhcp->msg_in == NULL); + dhcp_set_state(dhcp, DHCP_OFF); + } +} + +/* + * Set the DHCP state of a DHCP client. + * + * If the state changed, reset the number of tries. + */ +static void +dhcp_set_state(struct dhcp *dhcp, u8_t new_state) +{ + if (new_state != dhcp->state) { + dhcp->state = new_state; + dhcp->tries = 0; + dhcp->request_timeout = 0; + } +} + +/* + * Concatenate an option type and length field to the outgoing + * DHCP message. + * + */ +static void +dhcp_option(struct dhcp *dhcp, u8_t option_type, u8_t option_len) +{ + LWIP_ASSERT("dhcp_option: dhcp->options_out_len + 2 + option_len <= DHCP_OPTIONS_LEN", dhcp->options_out_len + 2U + option_len <= DHCP_OPTIONS_LEN); + dhcp->msg_out->options[dhcp->options_out_len++] = option_type; + dhcp->msg_out->options[dhcp->options_out_len++] = option_len; +} +/* + * Concatenate a single byte to the outgoing DHCP message. + * + */ +static void +dhcp_option_byte(struct dhcp *dhcp, u8_t value) +{ + LWIP_ASSERT("dhcp_option_byte: dhcp->options_out_len < DHCP_OPTIONS_LEN", dhcp->options_out_len < DHCP_OPTIONS_LEN); + dhcp->msg_out->options[dhcp->options_out_len++] = value; +} + +static void +dhcp_option_short(struct dhcp *dhcp, u16_t value) +{ + LWIP_ASSERT("dhcp_option_short: dhcp->options_out_len + 2 <= DHCP_OPTIONS_LEN", dhcp->options_out_len + 2U <= DHCP_OPTIONS_LEN); + dhcp->msg_out->options[dhcp->options_out_len++] = (u8_t)((value & 0xff00U) >> 8); + dhcp->msg_out->options[dhcp->options_out_len++] = (u8_t) (value & 0x00ffU); +} + +static void +dhcp_option_long(struct dhcp *dhcp, u32_t value) +{ + LWIP_ASSERT("dhcp_option_long: dhcp->options_out_len + 4 <= DHCP_OPTIONS_LEN", dhcp->options_out_len + 4U <= DHCP_OPTIONS_LEN); + dhcp->msg_out->options[dhcp->options_out_len++] = (u8_t)((value & 0xff000000UL) >> 24); + dhcp->msg_out->options[dhcp->options_out_len++] = (u8_t)((value & 0x00ff0000UL) >> 16); + dhcp->msg_out->options[dhcp->options_out_len++] = (u8_t)((value & 0x0000ff00UL) >> 8); + dhcp->msg_out->options[dhcp->options_out_len++] = (u8_t)((value & 0x000000ffUL)); +} + +/** + * Extract the DHCP message and the DHCP options. + * + * Extract the DHCP message and the DHCP options, each into a contiguous + * piece of memory. As a DHCP message is variable sized by its options, + * and also allows overriding some fields for options, the easy approach + * is to first unfold the options into a conitguous piece of memory, and + * use that further on. + * + */ +static err_t +dhcp_parse_reply(struct dhcp *dhcp, struct pbuf *p) +{ + u8_t *options; + u16_t offset; + u16_t offset_max; + u16_t options_idx; + u16_t options_idx_max; + struct pbuf *q; + int parse_file_as_options = 0; + int parse_sname_as_options = 0; + + /* clear received options */ + dhcp_clear_all_options(dhcp); + /* check that beginning of dhcp_msg (up to and including chaddr) is in first pbuf */ + if (p->len < DHCP_SNAME_OFS) { + return ERR_BUF; + } + dhcp->msg_in = (struct dhcp_msg *)p->payload; +#if LWIP_DHCP_BOOTP_FILE + /* clear boot file name */ + dhcp->boot_file_name[0] = 0; +#endif /* LWIP_DHCP_BOOTP_FILE */ + + /* parse options */ + + /* start with options field */ + options_idx = DHCP_OPTIONS_OFS; + /* parse options to the end of the received packet */ + options_idx_max = p->tot_len; +again: + q = p; + while((q != NULL) && (options_idx >= q->len)) { + options_idx -= q->len; + options_idx_max -= q->len; + q = q->next; + } + if (q == NULL) { + return ERR_BUF; + } + offset = options_idx; + offset_max = options_idx_max; + options = (u8_t*)q->payload; + /* at least 1 byte to read and no end marker, then at least 3 bytes to read? */ + while((q != NULL) && (options[offset] != DHCP_OPTION_END) && (offset < offset_max)) { + u8_t op = options[offset]; + u8_t len; + u8_t decode_len = 0; + int decode_idx = -1; + u16_t val_offset = offset + 2; + /* len byte might be in the next pbuf */ + if (offset + 1 < q->len) { + len = options[offset + 1]; + } else { + len = (q->next != NULL ? ((u8_t*)q->next->payload)[0] : 0); + } + /* LWIP_DEBUGF(DHCP_DEBUG, ("msg_offset=%"U16_F", q->len=%"U16_F, msg_offset, q->len)); */ + decode_len = len; + switch(op) { + /* case(DHCP_OPTION_END): handled above */ + case(DHCP_OPTION_PAD): + /* special option: no len encoded */ + decode_len = len = 0; + /* will be increased below */ + offset--; + break; + case(DHCP_OPTION_SUBNET_MASK): + LWIP_ASSERT("len == 4", len == 4); + decode_idx = DHCP_OPTION_IDX_SUBNET_MASK; + break; + case(DHCP_OPTION_ROUTER): + decode_len = 4; /* only copy the first given router */ + LWIP_ASSERT("len >= decode_len", len >= decode_len); + decode_idx = DHCP_OPTION_IDX_ROUTER; + break; + case(DHCP_OPTION_DNS_SERVER): + /* special case: there might be more than one server */ + LWIP_ASSERT("len % 4 == 0", len % 4 == 0); + /* limit number of DNS servers */ + decode_len = LWIP_MIN(len, 4 * DNS_MAX_SERVERS); + LWIP_ASSERT("len >= decode_len", len >= decode_len); + decode_idx = DHCP_OPTION_IDX_DNS_SERVER; + break; + case(DHCP_OPTION_LEASE_TIME): + LWIP_ASSERT("len == 4", len == 4); + decode_idx = DHCP_OPTION_IDX_LEASE_TIME; + break; + case(DHCP_OPTION_OVERLOAD): + LWIP_ASSERT("len == 1", len == 1); + decode_idx = DHCP_OPTION_IDX_OVERLOAD; + break; + case(DHCP_OPTION_MESSAGE_TYPE): + LWIP_ASSERT("len == 1", len == 1); + decode_idx = DHCP_OPTION_IDX_MSG_TYPE; + break; + case(DHCP_OPTION_SERVER_ID): + LWIP_ASSERT("len == 4", len == 4); + decode_idx = DHCP_OPTION_IDX_SERVER_ID; + break; + case(DHCP_OPTION_T1): + LWIP_ASSERT("len == 4", len == 4); + decode_idx = DHCP_OPTION_IDX_T1; + break; + case(DHCP_OPTION_T2): + LWIP_ASSERT("len == 4", len == 4); + decode_idx = DHCP_OPTION_IDX_T2; + break; + default: + decode_len = 0; + LWIP_DEBUGF(DHCP_DEBUG, ("skipping option %"U16_F" in options\n", op)); + break; + } + offset += len + 2; + if (decode_len > 0) { + u32_t value = 0; + u16_t copy_len; +decode_next: + LWIP_ASSERT("check decode_idx", decode_idx >= 0 && decode_idx < DHCP_OPTION_IDX_MAX); + LWIP_ASSERT("option already decoded", !dhcp_option_given(dhcp, decode_idx)); + copy_len = LWIP_MIN(decode_len, 4); + pbuf_copy_partial(q, &value, copy_len, val_offset); + if (decode_len > 4) { + /* decode more than one u32_t */ + LWIP_ASSERT("decode_len % 4 == 0", decode_len % 4 == 0); + dhcp_got_option(dhcp, decode_idx); + dhcp_set_option_value(dhcp, decode_idx, htonl(value)); + decode_len -= 4; + val_offset += 4; + decode_idx++; + goto decode_next; + } else if (decode_len == 4) { + value = ntohl(value); + } else { + LWIP_ASSERT("invalid decode_len", decode_len == 1); + value = ((u8_t*)&value)[0]; + } + dhcp_got_option(dhcp, decode_idx); + dhcp_set_option_value(dhcp, decode_idx, value); + } + if (offset >= q->len) { + offset -= q->len; + offset_max -= q->len; + q = q->next; + options = (u8_t*)q->payload; + } + } + /* is this an overloaded message? */ + if (dhcp_option_given(dhcp, DHCP_OPTION_IDX_OVERLOAD)) { + u32_t overload = dhcp_get_option_value(dhcp, DHCP_OPTION_IDX_OVERLOAD); + dhcp_clear_option(dhcp, DHCP_OPTION_IDX_OVERLOAD); + if (overload == DHCP_OVERLOAD_FILE) { + parse_file_as_options = 1; + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("overloaded file field\n")); + } else if (overload == DHCP_OVERLOAD_SNAME) { + parse_sname_as_options = 1; + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("overloaded sname field\n")); + } else if (overload == DHCP_OVERLOAD_SNAME_FILE) { + parse_sname_as_options = 1; + parse_file_as_options = 1; + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("overloaded sname and file field\n")); + } else { + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("invalid overload option: %d\n", (int)overload)); + } +#if LWIP_DHCP_BOOTP_FILE + if (!parse_file_as_options) { + /* only do this for ACK messages */ + if (dhcp_option_given(dhcp, DHCP_OPTION_IDX_MSG_TYPE) && + (dhcp_get_option_value(dhcp, DHCP_OPTION_IDX_MSG_TYPE) == DHCP_ACK)) + /* copy bootp file name, don't care for sname (server hostname) */ + pbuf_copy_partial(p, dhcp->boot_file_name, DHCP_FILE_LEN-1, DHCP_FILE_OFS); + /* make sure the string is really NULL-terminated */ + dhcp->boot_file_name[DHCP_FILE_LEN-1] = 0; + } +#endif /* LWIP_DHCP_BOOTP_FILE */ + } + if (parse_file_as_options) { + /* if both are overloaded, parse file first and then sname (RFC 2131 ch. 4.1) */ + parse_file_as_options = 0; + options_idx = DHCP_FILE_OFS; + options_idx_max = DHCP_FILE_OFS + DHCP_FILE_LEN; + goto again; + } else if (parse_sname_as_options) { + parse_sname_as_options = 0; + options_idx = DHCP_SNAME_OFS; + options_idx_max = DHCP_SNAME_OFS + DHCP_SNAME_LEN; + goto again; + } + return ERR_OK; +} + +/** + * If an incoming DHCP message is in response to us, then trigger the state machine + */ +static void +dhcp_recv(void *arg, struct udp_pcb *pcb, struct pbuf *p, ip_addr_t *addr, u16_t port) +{ + struct netif *netif = (struct netif *)arg; + struct dhcp *dhcp = netif->dhcp; + struct dhcp_msg *reply_msg = (struct dhcp_msg *)p->payload; + u8_t msg_type; + u8_t i; + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_recv(pbuf = %p) from DHCP server %"U16_F".%"U16_F".%"U16_F".%"U16_F" port %"U16_F"\n", (void*)p, + ip4_addr1_16(addr), ip4_addr2_16(addr), ip4_addr3_16(addr), ip4_addr4_16(addr), port)); + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("pbuf->len = %"U16_F"\n", p->len)); + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("pbuf->tot_len = %"U16_F"\n", p->tot_len)); + /* prevent warnings about unused arguments */ + LWIP_UNUSED_ARG(pcb); + LWIP_UNUSED_ARG(addr); + LWIP_UNUSED_ARG(port); + + LWIP_ASSERT("reply wasn't freed", dhcp->msg_in == NULL); + + if (p->len < DHCP_MIN_REPLY_LEN) { + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_WARNING, ("DHCP reply message or pbuf too short\n")); + goto free_pbuf_and_return; + } + + if (reply_msg->op != DHCP_BOOTREPLY) { + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_WARNING, ("not a DHCP reply message, but type %"U16_F"\n", (u16_t)reply_msg->op)); + goto free_pbuf_and_return; + } + /* iterate through hardware address and match against DHCP message */ + for (i = 0; i < netif->hwaddr_len; i++) { + if (netif->hwaddr[i] != reply_msg->chaddr[i]) { + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_WARNING, + ("netif->hwaddr[%"U16_F"]==%02"X16_F" != reply_msg->chaddr[%"U16_F"]==%02"X16_F"\n", + (u16_t)i, (u16_t)netif->hwaddr[i], (u16_t)i, (u16_t)reply_msg->chaddr[i])); + goto free_pbuf_and_return; + } + } + /* match transaction ID against what we expected */ + if (ntohl(reply_msg->xid) != dhcp->xid) { + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_WARNING, + ("transaction id mismatch reply_msg->xid(%"X32_F")!=dhcp->xid(%"X32_F")\n",ntohl(reply_msg->xid),dhcp->xid)); + goto free_pbuf_and_return; + } + /* option fields could be unfold? */ + if (dhcp_parse_reply(dhcp, p) != ERR_OK) { + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS, + ("problem unfolding DHCP message - too short on memory?\n")); + goto free_pbuf_and_return; + } + + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("searching DHCP_OPTION_MESSAGE_TYPE\n")); + /* obtain pointer to DHCP message type */ + if (!dhcp_option_given(dhcp, DHCP_OPTION_IDX_MSG_TYPE)) { + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_WARNING, ("DHCP_OPTION_MESSAGE_TYPE option not found\n")); + goto free_pbuf_and_return; + } + + /* read DHCP message type */ + msg_type = (u8_t)dhcp_get_option_value(dhcp, DHCP_OPTION_IDX_MSG_TYPE); + /* message type is DHCP ACK? */ + if (msg_type == DHCP_ACK) { + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("DHCP_ACK received\n")); + /* in requesting state? */ + if (dhcp->state == DHCP_REQUESTING) { + dhcp_handle_ack(netif); +#if DHCP_DOES_ARP_CHECK + /* check if the acknowledged lease address is already in use */ + dhcp_check(netif); +#else + /* bind interface to the acknowledged lease address */ + dhcp_bind(netif); +#endif + } + /* already bound to the given lease address? */ + else if ((dhcp->state == DHCP_REBOOTING) || (dhcp->state == DHCP_REBINDING) || (dhcp->state == DHCP_RENEWING)) { + dhcp_bind(netif); + } + } + /* received a DHCP_NAK in appropriate state? */ + else if ((msg_type == DHCP_NAK) && + ((dhcp->state == DHCP_REBOOTING) || (dhcp->state == DHCP_REQUESTING) || + (dhcp->state == DHCP_REBINDING) || (dhcp->state == DHCP_RENEWING ))) { + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("DHCP_NAK received\n")); + dhcp_handle_nak(netif); + } + /* received a DHCP_OFFER in DHCP_SELECTING state? */ + else if ((msg_type == DHCP_OFFER) && (dhcp->state == DHCP_SELECTING)) { + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("DHCP_OFFER received in DHCP_SELECTING state\n")); + dhcp->request_timeout = 0; + /* remember offered lease */ + dhcp_handle_offer(netif); + } +free_pbuf_and_return: + dhcp->msg_in = NULL; + pbuf_free(p); +} + +/** + * Create a DHCP request, fill in common headers + * + * @param netif the netif under DHCP control + * @param dhcp dhcp control struct + * @param message_type message type of the request + */ +static err_t +dhcp_create_msg(struct netif *netif, struct dhcp *dhcp, u8_t message_type) +{ + u16_t i; +#ifndef DHCP_GLOBAL_XID + /** default global transaction identifier starting value (easy to match + * with a packet analyser). We simply increment for each new request. + * Predefine DHCP_GLOBAL_XID to a better value or a function call to generate one + * at runtime, any supporting function prototypes can be defined in DHCP_GLOBAL_XID_HEADER */ + static u32_t xid = 0xABCD0000; +#else + static u32_t xid; + static u8_t xid_initialised = 0; + if (!xid_initialised) { + xid = DHCP_GLOBAL_XID; + xid_initialised = !xid_initialised; + } +#endif + LWIP_ERROR("dhcp_create_msg: netif != NULL", (netif != NULL), return ERR_ARG;); + LWIP_ERROR("dhcp_create_msg: dhcp != NULL", (dhcp != NULL), return ERR_VAL;); + LWIP_ASSERT("dhcp_create_msg: dhcp->p_out == NULL", dhcp->p_out == NULL); + LWIP_ASSERT("dhcp_create_msg: dhcp->msg_out == NULL", dhcp->msg_out == NULL); + dhcp->p_out = pbuf_alloc(PBUF_TRANSPORT, sizeof(struct dhcp_msg), PBUF_RAM); + if (dhcp->p_out == NULL) { + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS, + ("dhcp_create_msg(): could not allocate pbuf\n")); + return ERR_MEM; + } + LWIP_ASSERT("dhcp_create_msg: check that first pbuf can hold struct dhcp_msg", + (dhcp->p_out->len >= sizeof(struct dhcp_msg))); + + /* reuse transaction identifier in retransmissions */ + if (dhcp->tries == 0) { + xid++; + } + dhcp->xid = xid; + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, + ("transaction id xid(%"X32_F")\n", xid)); + + dhcp->msg_out = (struct dhcp_msg *)dhcp->p_out->payload; + + dhcp->msg_out->op = DHCP_BOOTREQUEST; + /* TODO: make link layer independent */ + dhcp->msg_out->htype = DHCP_HTYPE_ETH; + dhcp->msg_out->hlen = netif->hwaddr_len; + dhcp->msg_out->hops = 0; + dhcp->msg_out->xid = htonl(dhcp->xid); + dhcp->msg_out->secs = 0; + /* we don't need the broadcast flag since we can receive unicast traffic + before being fully configured! */ + dhcp->msg_out->flags = 0; + ip_addr_set_zero(&dhcp->msg_out->ciaddr); + /* set ciaddr to netif->ip_addr based on message_type and state */ + if ((message_type == DHCP_INFORM) || (message_type == DHCP_DECLINE) || + ((message_type == DHCP_REQUEST) && /* DHCP_BOUND not used for sending! */ + ((dhcp->state==DHCP_RENEWING) || dhcp->state==DHCP_REBINDING))) { + ip_addr_copy(dhcp->msg_out->ciaddr, netif->ip_addr); + } + ip_addr_set_zero(&dhcp->msg_out->yiaddr); + ip_addr_set_zero(&dhcp->msg_out->siaddr); + ip_addr_set_zero(&dhcp->msg_out->giaddr); + for (i = 0; i < netif->hwaddr_len; i++) { + /* copy netif hardware address */ + dhcp->msg_out->chaddr[i] = netif->hwaddr[i]; + } + for ( ; i < DHCP_CHADDR_LEN; i++) { + /* ... pad rest with zeroes */ + dhcp->msg_out->chaddr[i] = 0; + } + for (i = 0; i < DHCP_SNAME_LEN; i++) { + dhcp->msg_out->sname[i] = 0; + } + for (i = 0; i < DHCP_FILE_LEN; i++) { + dhcp->msg_out->file[i] = 0; + } + dhcp->msg_out->cookie = PP_HTONL(DHCP_MAGIC_COOKIE); + dhcp->options_out_len = 0; + /* fill options field with an incrementing array (for debugging purposes) */ + for (i = 0; i < DHCP_OPTIONS_LEN; i++) { + dhcp->msg_out->options[i] = (u8_t)i; /* for debugging only, no matter if truncated */ + } + /* Add option MESSAGE_TYPE */ + dhcp_option(dhcp, DHCP_OPTION_MESSAGE_TYPE, DHCP_OPTION_MESSAGE_TYPE_LEN); + dhcp_option_byte(dhcp, message_type); + return ERR_OK; +} + +/** + * Free previously allocated memory used to send a DHCP request. + * + * @param dhcp the dhcp struct to free the request from + */ +static void +dhcp_delete_msg(struct dhcp *dhcp) +{ + LWIP_ERROR("dhcp_delete_msg: dhcp != NULL", (dhcp != NULL), return;); + LWIP_ASSERT("dhcp_delete_msg: dhcp->p_out != NULL", dhcp->p_out != NULL); + LWIP_ASSERT("dhcp_delete_msg: dhcp->msg_out != NULL", dhcp->msg_out != NULL); + if (dhcp->p_out != NULL) { + pbuf_free(dhcp->p_out); + } + dhcp->p_out = NULL; + dhcp->msg_out = NULL; +} + +/** + * Add a DHCP message trailer + * + * Adds the END option to the DHCP message, and if + * necessary, up to three padding bytes. + * + * @param dhcp DHCP state structure + */ +static void +dhcp_option_trailer(struct dhcp *dhcp) +{ + LWIP_ERROR("dhcp_option_trailer: dhcp != NULL", (dhcp != NULL), return;); + LWIP_ASSERT("dhcp_option_trailer: dhcp->msg_out != NULL\n", dhcp->msg_out != NULL); + LWIP_ASSERT("dhcp_option_trailer: dhcp->options_out_len < DHCP_OPTIONS_LEN\n", dhcp->options_out_len < DHCP_OPTIONS_LEN); + dhcp->msg_out->options[dhcp->options_out_len++] = DHCP_OPTION_END; + /* packet is too small, or not 4 byte aligned? */ + while ((dhcp->options_out_len < DHCP_MIN_OPTIONS_LEN) || (dhcp->options_out_len & 3)) { + /* LWIP_DEBUGF(DHCP_DEBUG,("dhcp_option_trailer:dhcp->options_out_len=%"U16_F", DHCP_OPTIONS_LEN=%"U16_F, dhcp->options_out_len, DHCP_OPTIONS_LEN)); */ + LWIP_ASSERT("dhcp_option_trailer: dhcp->options_out_len < DHCP_OPTIONS_LEN\n", dhcp->options_out_len < DHCP_OPTIONS_LEN); + /* add a fill/padding byte */ + dhcp->msg_out->options[dhcp->options_out_len++] = 0; + } +} + +#endif /* LWIP_DHCP */ diff --git a/features/unsupported/net/lwip/lwip/core/dns.c b/features/unsupported/net/lwip/lwip/core/dns.c new file mode 100644 index 00000000000..d63361226f2 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/core/dns.c @@ -0,0 +1,970 @@ +/** + * @file + * DNS - host name to IP address resolver. + * + */ + +/** + + * This file implements a DNS host name to IP address resolver. + + * Port to lwIP from uIP + * by Jim Pettinato April 2007 + + * uIP version Copyright (c) 2002-2003, Adam Dunkels. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote + * products derived from this software without specific prior + * written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS + * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * + * DNS.C + * + * The lwIP DNS resolver functions are used to lookup a host name and + * map it to a numerical IP address. It maintains a list of resolved + * hostnames that can be queried with the dns_lookup() function. + * New hostnames can be resolved using the dns_query() function. + * + * The lwIP version of the resolver also adds a non-blocking version of + * gethostbyname() that will work with a raw API application. This function + * checks for an IP address string first and converts it if it is valid. + * gethostbyname() then does a dns_lookup() to see if the name is + * already in the table. If so, the IP is returned. If not, a query is + * issued and the function returns with a ERR_INPROGRESS status. The app + * using the dns client must then go into a waiting state. + * + * Once a hostname has been resolved (or found to be non-existent), + * the resolver code calls a specified callback function (which + * must be implemented by the module that uses the resolver). + */ + +/*----------------------------------------------------------------------------- + * RFC 1035 - Domain names - implementation and specification + * RFC 2181 - Clarifications to the DNS Specification + *----------------------------------------------------------------------------*/ + +/** @todo: define good default values (rfc compliance) */ +/** @todo: improve answer parsing, more checkings... */ +/** @todo: check RFC1035 - 7.3. Processing responses */ + +/*----------------------------------------------------------------------------- + * Includes + *----------------------------------------------------------------------------*/ + +#include "lwip/opt.h" + +#if LWIP_DNS /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/udp.h" +#include "lwip/mem.h" +#include "lwip/memp.h" +#include "lwip/dns.h" + +#include + +/** DNS server IP address */ +#ifndef DNS_SERVER_ADDRESS +#define DNS_SERVER_ADDRESS(ipaddr) (ip4_addr_set_u32(ipaddr, ipaddr_addr("208.67.222.222"))) /* resolver1.opendns.com */ +#endif + +/** DNS server port address */ +#ifndef DNS_SERVER_PORT +#define DNS_SERVER_PORT 53 +#endif + +/** DNS maximum number of retries when asking for a name, before "timeout". */ +#ifndef DNS_MAX_RETRIES +#define DNS_MAX_RETRIES 4 +#endif + +/** DNS resource record max. TTL (one week as default) */ +#ifndef DNS_MAX_TTL +#define DNS_MAX_TTL 604800 +#endif + +/* DNS protocol flags */ +#define DNS_FLAG1_RESPONSE 0x80 +#define DNS_FLAG1_OPCODE_STATUS 0x10 +#define DNS_FLAG1_OPCODE_INVERSE 0x08 +#define DNS_FLAG1_OPCODE_STANDARD 0x00 +#define DNS_FLAG1_AUTHORATIVE 0x04 +#define DNS_FLAG1_TRUNC 0x02 +#define DNS_FLAG1_RD 0x01 +#define DNS_FLAG2_RA 0x80 +#define DNS_FLAG2_ERR_MASK 0x0f +#define DNS_FLAG2_ERR_NONE 0x00 +#define DNS_FLAG2_ERR_NAME 0x03 + +/* DNS protocol states */ +#define DNS_STATE_UNUSED 0 +#define DNS_STATE_NEW 1 +#define DNS_STATE_ASKING 2 +#define DNS_STATE_DONE 3 + +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +/** DNS message header */ +struct dns_hdr { + PACK_STRUCT_FIELD(u16_t id); + PACK_STRUCT_FIELD(u8_t flags1); + PACK_STRUCT_FIELD(u8_t flags2); + PACK_STRUCT_FIELD(u16_t numquestions); + PACK_STRUCT_FIELD(u16_t numanswers); + PACK_STRUCT_FIELD(u16_t numauthrr); + PACK_STRUCT_FIELD(u16_t numextrarr); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif +#define SIZEOF_DNS_HDR 12 + +/** DNS query message structure. + No packing needed: only used locally on the stack. */ +struct dns_query { + /* DNS query record starts with either a domain name or a pointer + to a name already present somewhere in the packet. */ + u16_t type; + u16_t cls; +}; +#define SIZEOF_DNS_QUERY 4 + +/** DNS answer message structure. + No packing needed: only used locally on the stack. */ +struct dns_answer { + /* DNS answer record starts with either a domain name or a pointer + to a name already present somewhere in the packet. */ + u16_t type; + u16_t cls; + u32_t ttl; + u16_t len; +}; +#define SIZEOF_DNS_ANSWER 10 + +/** DNS table entry */ +struct dns_table_entry { + u8_t state; + u8_t numdns; + u8_t tmr; + u8_t retries; + u8_t seqno; + u8_t err; + u32_t ttl; + char name[DNS_MAX_NAME_LENGTH]; + ip_addr_t ipaddr; + /* pointer to callback on DNS query done */ + dns_found_callback found; + void *arg; +}; + +#if DNS_LOCAL_HOSTLIST + +#if DNS_LOCAL_HOSTLIST_IS_DYNAMIC +/** Local host-list. For hostnames in this list, no + * external name resolution is performed */ +static struct local_hostlist_entry *local_hostlist_dynamic; +#else /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */ + +/** Defining this allows the local_hostlist_static to be placed in a different + * linker section (e.g. FLASH) */ +#ifndef DNS_LOCAL_HOSTLIST_STORAGE_PRE +#define DNS_LOCAL_HOSTLIST_STORAGE_PRE static +#endif /* DNS_LOCAL_HOSTLIST_STORAGE_PRE */ +/** Defining this allows the local_hostlist_static to be placed in a different + * linker section (e.g. FLASH) */ +#ifndef DNS_LOCAL_HOSTLIST_STORAGE_POST +#define DNS_LOCAL_HOSTLIST_STORAGE_POST +#endif /* DNS_LOCAL_HOSTLIST_STORAGE_POST */ +DNS_LOCAL_HOSTLIST_STORAGE_PRE struct local_hostlist_entry local_hostlist_static[] + DNS_LOCAL_HOSTLIST_STORAGE_POST = DNS_LOCAL_HOSTLIST_INIT; + +#endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */ + +static void dns_init_local(); +#endif /* DNS_LOCAL_HOSTLIST */ + + +/* forward declarations */ +static void dns_recv(void *s, struct udp_pcb *pcb, struct pbuf *p, ip_addr_t *addr, u16_t port); +static void dns_check_entries(void); + +/*----------------------------------------------------------------------------- + * Globales + *----------------------------------------------------------------------------*/ + +/* DNS variables */ +static struct udp_pcb *dns_pcb; +static u8_t dns_seqno; +static struct dns_table_entry dns_table[DNS_TABLE_SIZE]; +static ip_addr_t dns_servers[DNS_MAX_SERVERS]; +/** Contiguous buffer for processing responses */ +static u8_t dns_payload_buffer[LWIP_MEM_ALIGN_BUFFER(DNS_MSG_SIZE)]; +static u8_t* dns_payload; + +/** + * Initialize the resolver: set up the UDP pcb and configure the default server + * (DNS_SERVER_ADDRESS). + */ +void +dns_init() +{ + ip_addr_t dnsserver; + + dns_payload = (u8_t *)LWIP_MEM_ALIGN(dns_payload_buffer); + + /* initialize default DNS server address */ + DNS_SERVER_ADDRESS(&dnsserver); + + LWIP_DEBUGF(DNS_DEBUG, ("dns_init: initializing\n")); + + /* if dns client not yet initialized... */ + if (dns_pcb == NULL) { + dns_pcb = udp_new(); + + if (dns_pcb != NULL) { + /* initialize DNS table not needed (initialized to zero since it is a + * global variable) */ + LWIP_ASSERT("For implicit initialization to work, DNS_STATE_UNUSED needs to be 0", + DNS_STATE_UNUSED == 0); + + /* initialize DNS client */ + udp_bind(dns_pcb, IP_ADDR_ANY, 0); + udp_recv(dns_pcb, dns_recv, NULL); + + /* initialize default DNS primary server */ + dns_setserver(0, &dnsserver); + } + } +#if DNS_LOCAL_HOSTLIST + dns_init_local(); +#endif +} + +/** + * Initialize one of the DNS servers. + * + * @param numdns the index of the DNS server to set must be < DNS_MAX_SERVERS + * @param dnsserver IP address of the DNS server to set + */ +void +dns_setserver(u8_t numdns, ip_addr_t *dnsserver) +{ + if ((numdns < DNS_MAX_SERVERS) && (dns_pcb != NULL) && + (dnsserver != NULL) && !ip_addr_isany(dnsserver)) { + dns_servers[numdns] = (*dnsserver); + } +} + +/** + * Obtain one of the currently configured DNS server. + * + * @param numdns the index of the DNS server + * @return IP address of the indexed DNS server or "ip_addr_any" if the DNS + * server has not been configured. + */ +ip_addr_t +dns_getserver(u8_t numdns) +{ + if (numdns < DNS_MAX_SERVERS) { + return dns_servers[numdns]; + } else { + return *IP_ADDR_ANY; + } +} + +/** + * The DNS resolver client timer - handle retries and timeouts and should + * be called every DNS_TMR_INTERVAL milliseconds (every second by default). + */ +void +dns_tmr(void) +{ + if (dns_pcb != NULL) { + LWIP_DEBUGF(DNS_DEBUG, ("dns_tmr: dns_check_entries\n")); + dns_check_entries(); + } +} + +#if DNS_LOCAL_HOSTLIST +static void +dns_init_local() +{ +#if DNS_LOCAL_HOSTLIST_IS_DYNAMIC && defined(DNS_LOCAL_HOSTLIST_INIT) + int i; + struct local_hostlist_entry *entry; + /* Dynamic: copy entries from DNS_LOCAL_HOSTLIST_INIT to list */ + struct local_hostlist_entry local_hostlist_init[] = DNS_LOCAL_HOSTLIST_INIT; + size_t namelen; + for (i = 0; i < sizeof(local_hostlist_init) / sizeof(struct local_hostlist_entry); i++) { + struct local_hostlist_entry *init_entry = &local_hostlist_init[i]; + LWIP_ASSERT("invalid host name (NULL)", init_entry->name != NULL); + namelen = strlen(init_entry->name); + LWIP_ASSERT("namelen <= DNS_LOCAL_HOSTLIST_MAX_NAMELEN", namelen <= DNS_LOCAL_HOSTLIST_MAX_NAMELEN); + entry = (struct local_hostlist_entry *)memp_malloc(MEMP_LOCALHOSTLIST); + LWIP_ASSERT("mem-error in dns_init_local", entry != NULL); + if (entry != NULL) { + entry->name = (char*)entry + sizeof(struct local_hostlist_entry); + MEMCPY((char*)entry->name, init_entry->name, namelen); + ((char*)entry->name)[namelen] = 0; + entry->addr = init_entry->addr; + entry->next = local_hostlist_dynamic; + local_hostlist_dynamic = entry; + } + } +#endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC && defined(DNS_LOCAL_HOSTLIST_INIT) */ +} + +/** + * Scans the local host-list for a hostname. + * + * @param hostname Hostname to look for in the local host-list + * @return The first IP address for the hostname in the local host-list or + * IPADDR_NONE if not found. + */ +static u32_t +dns_lookup_local(const char *hostname) +{ +#if DNS_LOCAL_HOSTLIST_IS_DYNAMIC + struct local_hostlist_entry *entry = local_hostlist_dynamic; + while(entry != NULL) { + if(strcmp(entry->name, hostname) == 0) { + return ip4_addr_get_u32(&entry->addr); + } + entry = entry->next; + } +#else /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */ + int i; + for (i = 0; i < sizeof(local_hostlist_static) / sizeof(struct local_hostlist_entry); i++) { + if(strcmp(local_hostlist_static[i].name, hostname) == 0) { + return ip4_addr_get_u32(&local_hostlist_static[i].addr); + } + } +#endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */ + return IPADDR_NONE; +} + +#if DNS_LOCAL_HOSTLIST_IS_DYNAMIC +/** Remove all entries from the local host-list for a specific hostname + * and/or IP addess + * + * @param hostname hostname for which entries shall be removed from the local + * host-list + * @param addr address for which entries shall be removed from the local host-list + * @return the number of removed entries + */ +int +dns_local_removehost(const char *hostname, const ip_addr_t *addr) +{ + int removed = 0; + struct local_hostlist_entry *entry = local_hostlist_dynamic; + struct local_hostlist_entry *last_entry = NULL; + while (entry != NULL) { + if (((hostname == NULL) || !strcmp(entry->name, hostname)) && + ((addr == NULL) || ip_addr_cmp(&entry->addr, addr))) { + struct local_hostlist_entry *free_entry; + if (last_entry != NULL) { + last_entry->next = entry->next; + } else { + local_hostlist_dynamic = entry->next; + } + free_entry = entry; + entry = entry->next; + memp_free(MEMP_LOCALHOSTLIST, free_entry); + removed++; + } else { + last_entry = entry; + entry = entry->next; + } + } + return removed; +} + +/** + * Add a hostname/IP address pair to the local host-list. + * Duplicates are not checked. + * + * @param hostname hostname of the new entry + * @param addr IP address of the new entry + * @return ERR_OK if succeeded or ERR_MEM on memory error + */ +err_t +dns_local_addhost(const char *hostname, const ip_addr_t *addr) +{ + struct local_hostlist_entry *entry; + size_t namelen; + LWIP_ASSERT("invalid host name (NULL)", hostname != NULL); + namelen = strlen(hostname); + LWIP_ASSERT("namelen <= DNS_LOCAL_HOSTLIST_MAX_NAMELEN", namelen <= DNS_LOCAL_HOSTLIST_MAX_NAMELEN); + entry = (struct local_hostlist_entry *)memp_malloc(MEMP_LOCALHOSTLIST); + if (entry == NULL) { + return ERR_MEM; + } + entry->name = (char*)entry + sizeof(struct local_hostlist_entry); + MEMCPY((char*)entry->name, hostname, namelen); + ((char*)entry->name)[namelen] = 0; + ip_addr_copy(entry->addr, *addr); + entry->next = local_hostlist_dynamic; + local_hostlist_dynamic = entry; + return ERR_OK; +} +#endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC*/ +#endif /* DNS_LOCAL_HOSTLIST */ + +/** + * Look up a hostname in the array of known hostnames. + * + * @note This function only looks in the internal array of known + * hostnames, it does not send out a query for the hostname if none + * was found. The function dns_enqueue() can be used to send a query + * for a hostname. + * + * @param name the hostname to look up + * @return the hostname's IP address, as u32_t (instead of ip_addr_t to + * better check for failure: != IPADDR_NONE) or IPADDR_NONE if the hostname + * was not found in the cached dns_table. + */ +static u32_t +dns_lookup(const char *name) +{ + u8_t i; +#if DNS_LOCAL_HOSTLIST || defined(DNS_LOOKUP_LOCAL_EXTERN) + u32_t addr; +#endif /* DNS_LOCAL_HOSTLIST || defined(DNS_LOOKUP_LOCAL_EXTERN) */ +#if DNS_LOCAL_HOSTLIST + if ((addr = dns_lookup_local(name)) != IPADDR_NONE) { + return addr; + } +#endif /* DNS_LOCAL_HOSTLIST */ +#ifdef DNS_LOOKUP_LOCAL_EXTERN + if((addr = DNS_LOOKUP_LOCAL_EXTERN(name)) != IPADDR_NONE) { + return addr; + } +#endif /* DNS_LOOKUP_LOCAL_EXTERN */ + + /* Walk through name list, return entry if found. If not, return NULL. */ + for (i = 0; i < DNS_TABLE_SIZE; ++i) { + if ((dns_table[i].state == DNS_STATE_DONE) && + (strcmp(name, dns_table[i].name) == 0)) { + LWIP_DEBUGF(DNS_DEBUG, ("dns_lookup: \"%s\": found = ", name)); + ip_addr_debug_print(DNS_DEBUG, &(dns_table[i].ipaddr)); + LWIP_DEBUGF(DNS_DEBUG, ("\n")); + return ip4_addr_get_u32(&dns_table[i].ipaddr); + } + } + + return IPADDR_NONE; +} + +#if DNS_DOES_NAME_CHECK +/** + * Compare the "dotted" name "query" with the encoded name "response" + * to make sure an answer from the DNS server matches the current dns_table + * entry (otherwise, answers might arrive late for hostname not on the list + * any more). + * + * @param query hostname (not encoded) from the dns_table + * @param response encoded hostname in the DNS response + * @return 0: names equal; 1: names differ + */ +static u8_t +dns_compare_name(unsigned char *query, unsigned char *response) +{ + unsigned char n; + + do { + n = *response++; + /** @see RFC 1035 - 4.1.4. Message compression */ + if ((n & 0xc0) == 0xc0) { + /* Compressed name */ + break; + } else { + /* Not compressed name */ + while (n > 0) { + if ((*query) != (*response)) { + return 1; + } + ++response; + ++query; + --n; + }; + ++query; + } + } while (*response != 0); + + return 0; +} +#endif /* DNS_DOES_NAME_CHECK */ + +/** + * Walk through a compact encoded DNS name and return the end of the name. + * + * @param query encoded DNS name in the DNS server response + * @return end of the name + */ +static unsigned char * +dns_parse_name(unsigned char *query) +{ + unsigned char n; + + do { + n = *query++; + /** @see RFC 1035 - 4.1.4. Message compression */ + if ((n & 0xc0) == 0xc0) { + /* Compressed name */ + break; + } else { + /* Not compressed name */ + while (n > 0) { + ++query; + --n; + }; + } + } while (*query != 0); + + return query + 1; +} + +/** + * Send a DNS query packet. + * + * @param numdns index of the DNS server in the dns_servers table + * @param name hostname to query + * @param id index of the hostname in dns_table, used as transaction ID in the + * DNS query packet + * @return ERR_OK if packet is sent; an err_t indicating the problem otherwise + */ +static err_t +dns_send(u8_t numdns, const char* name, u8_t id) +{ + err_t err; + struct dns_hdr *hdr; + struct dns_query qry; + struct pbuf *p; + char *query, *nptr; + const char *pHostname; + u8_t n; + + LWIP_DEBUGF(DNS_DEBUG, ("dns_send: dns_servers[%"U16_F"] \"%s\": request\n", + (u16_t)(numdns), name)); + LWIP_ASSERT("dns server out of array", numdns < DNS_MAX_SERVERS); + LWIP_ASSERT("dns server has no IP address set", !ip_addr_isany(&dns_servers[numdns])); + + /* if here, we have either a new query or a retry on a previous query to process */ + p = pbuf_alloc(PBUF_TRANSPORT, SIZEOF_DNS_HDR + DNS_MAX_NAME_LENGTH + + SIZEOF_DNS_QUERY, PBUF_RAM); + if (p != NULL) { + LWIP_ASSERT("pbuf must be in one piece", p->next == NULL); + /* fill dns header */ + hdr = (struct dns_hdr*)p->payload; + memset(hdr, 0, SIZEOF_DNS_HDR); + hdr->id = htons(id); + hdr->flags1 = DNS_FLAG1_RD; + hdr->numquestions = PP_HTONS(1); + query = (char*)hdr + SIZEOF_DNS_HDR; + pHostname = name; + --pHostname; + + /* convert hostname into suitable query format. */ + do { + ++pHostname; + nptr = query; + ++query; + for(n = 0; *pHostname != '.' && *pHostname != 0; ++pHostname) { + *query = *pHostname; + ++query; + ++n; + } + *nptr = n; + } while(*pHostname != 0); + *query++='\0'; + + /* fill dns query */ + qry.type = PP_HTONS(DNS_RRTYPE_A); + qry.cls = PP_HTONS(DNS_RRCLASS_IN); + SMEMCPY(query, &qry, SIZEOF_DNS_QUERY); + + /* resize pbuf to the exact dns query */ + pbuf_realloc(p, (u16_t)((query + SIZEOF_DNS_QUERY) - ((char*)(p->payload)))); + + /* connect to the server for faster receiving */ + udp_connect(dns_pcb, &dns_servers[numdns], DNS_SERVER_PORT); + /* send dns packet */ + err = udp_sendto(dns_pcb, p, &dns_servers[numdns], DNS_SERVER_PORT); + + /* free pbuf */ + pbuf_free(p); + } else { + err = ERR_MEM; + } + + return err; +} + +/** + * dns_check_entry() - see if pEntry has not yet been queried and, if so, sends out a query. + * Check an entry in the dns_table: + * - send out query for new entries + * - retry old pending entries on timeout (also with different servers) + * - remove completed entries from the table if their TTL has expired + * + * @param i index of the dns_table entry to check + */ +static void +dns_check_entry(u8_t i) +{ + err_t err; + struct dns_table_entry *pEntry = &dns_table[i]; + + LWIP_ASSERT("array index out of bounds", i < DNS_TABLE_SIZE); + + switch(pEntry->state) { + + case DNS_STATE_NEW: { + /* initialize new entry */ + pEntry->state = DNS_STATE_ASKING; + pEntry->numdns = 0; + pEntry->tmr = 1; + pEntry->retries = 0; + + /* send DNS packet for this entry */ + err = dns_send(pEntry->numdns, pEntry->name, i); + if (err != ERR_OK) { + LWIP_DEBUGF(DNS_DEBUG | LWIP_DBG_LEVEL_WARNING, + ("dns_send returned error: %s\n", lwip_strerr(err))); + } + break; + } + + case DNS_STATE_ASKING: { + if (--pEntry->tmr == 0) { + if (++pEntry->retries == DNS_MAX_RETRIES) { + if ((pEntry->numdns+1numdns+1])) { + /* change of server */ + pEntry->numdns++; + pEntry->tmr = 1; + pEntry->retries = 0; + break; + } else { + LWIP_DEBUGF(DNS_DEBUG, ("dns_check_entry: \"%s\": timeout\n", pEntry->name)); + /* call specified callback function if provided */ + if (pEntry->found) + (*pEntry->found)(pEntry->name, NULL, pEntry->arg); + /* flush this entry */ + pEntry->state = DNS_STATE_UNUSED; + pEntry->found = NULL; + break; + } + } + + /* wait longer for the next retry */ + pEntry->tmr = pEntry->retries; + + /* send DNS packet for this entry */ + err = dns_send(pEntry->numdns, pEntry->name, i); + if (err != ERR_OK) { + LWIP_DEBUGF(DNS_DEBUG | LWIP_DBG_LEVEL_WARNING, + ("dns_send returned error: %s\n", lwip_strerr(err))); + } + } + break; + } + + case DNS_STATE_DONE: { + /* if the time to live is nul */ + if (--pEntry->ttl == 0) { + LWIP_DEBUGF(DNS_DEBUG, ("dns_check_entry: \"%s\": flush\n", pEntry->name)); + /* flush this entry */ + pEntry->state = DNS_STATE_UNUSED; + pEntry->found = NULL; + } + break; + } + case DNS_STATE_UNUSED: + /* nothing to do */ + break; + default: + LWIP_ASSERT("unknown dns_table entry state:", 0); + break; + } +} + +/** + * Call dns_check_entry for each entry in dns_table - check all entries. + */ +static void +dns_check_entries(void) +{ + u8_t i; + + for (i = 0; i < DNS_TABLE_SIZE; ++i) { + dns_check_entry(i); + } +} + +/** + * Receive input function for DNS response packets arriving for the dns UDP pcb. + * + * @params see udp.h + */ +static void +dns_recv(void *arg, struct udp_pcb *pcb, struct pbuf *p, ip_addr_t *addr, u16_t port) +{ + u16_t i; + char *pHostname; + struct dns_hdr *hdr; + struct dns_answer ans; + struct dns_table_entry *pEntry; + u16_t nquestions, nanswers; + + LWIP_UNUSED_ARG(arg); + LWIP_UNUSED_ARG(pcb); + LWIP_UNUSED_ARG(addr); + LWIP_UNUSED_ARG(port); + + /* is the dns message too big ? */ + if (p->tot_len > DNS_MSG_SIZE) { + LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: pbuf too big\n")); + /* free pbuf and return */ + goto memerr; + } + + /* is the dns message big enough ? */ + if (p->tot_len < (SIZEOF_DNS_HDR + SIZEOF_DNS_QUERY + SIZEOF_DNS_ANSWER)) { + LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: pbuf too small\n")); + /* free pbuf and return */ + goto memerr; + } + + /* copy dns payload inside static buffer for processing */ + if (pbuf_copy_partial(p, dns_payload, p->tot_len, 0) == p->tot_len) { + /* The ID in the DNS header should be our entry into the name table. */ + hdr = (struct dns_hdr*)dns_payload; + i = htons(hdr->id); + if (i < DNS_TABLE_SIZE) { + pEntry = &dns_table[i]; + if(pEntry->state == DNS_STATE_ASKING) { + /* This entry is now completed. */ + pEntry->state = DNS_STATE_DONE; + pEntry->err = hdr->flags2 & DNS_FLAG2_ERR_MASK; + + /* We only care about the question(s) and the answers. The authrr + and the extrarr are simply discarded. */ + nquestions = htons(hdr->numquestions); + nanswers = htons(hdr->numanswers); + + /* Check for error. If so, call callback to inform. */ + if (((hdr->flags1 & DNS_FLAG1_RESPONSE) == 0) || (pEntry->err != 0) || (nquestions != 1)) { + LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: \"%s\": error in flags\n", pEntry->name)); + /* call callback to indicate error, clean up memory and return */ + goto responseerr; + } + +#if DNS_DOES_NAME_CHECK + /* Check if the name in the "question" part match with the name in the entry. */ + if (dns_compare_name((unsigned char *)(pEntry->name), (unsigned char *)dns_payload + SIZEOF_DNS_HDR) != 0) { + LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: \"%s\": response not match to query\n", pEntry->name)); + /* call callback to indicate error, clean up memory and return */ + goto responseerr; + } +#endif /* DNS_DOES_NAME_CHECK */ + + /* Skip the name in the "question" part */ + pHostname = (char *) dns_parse_name((unsigned char *)dns_payload + SIZEOF_DNS_HDR) + SIZEOF_DNS_QUERY; + + while (nanswers > 0) { + /* skip answer resource record's host name */ + pHostname = (char *) dns_parse_name((unsigned char *)pHostname); + + /* Check for IP address type and Internet class. Others are discarded. */ + SMEMCPY(&ans, pHostname, SIZEOF_DNS_ANSWER); + if((ans.type == PP_HTONS(DNS_RRTYPE_A)) && (ans.cls == PP_HTONS(DNS_RRCLASS_IN)) && + (ans.len == PP_HTONS(sizeof(ip_addr_t))) ) { + /* read the answer resource record's TTL, and maximize it if needed */ + pEntry->ttl = ntohl(ans.ttl); + if (pEntry->ttl > DNS_MAX_TTL) { + pEntry->ttl = DNS_MAX_TTL; + } + /* read the IP address after answer resource record's header */ + SMEMCPY(&(pEntry->ipaddr), (pHostname+SIZEOF_DNS_ANSWER), sizeof(ip_addr_t)); + LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: \"%s\": response = ", pEntry->name)); + ip_addr_debug_print(DNS_DEBUG, (&(pEntry->ipaddr))); + LWIP_DEBUGF(DNS_DEBUG, ("\n")); + /* call specified callback function if provided */ + if (pEntry->found) { + (*pEntry->found)(pEntry->name, &pEntry->ipaddr, pEntry->arg); + } + /* deallocate memory and return */ + goto memerr; + } else { + pHostname = pHostname + SIZEOF_DNS_ANSWER + htons(ans.len); + } + --nanswers; + } + LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: \"%s\": error in response\n", pEntry->name)); + /* call callback to indicate error, clean up memory and return */ + goto responseerr; + } + } + } + + /* deallocate memory and return */ + goto memerr; + +responseerr: + /* ERROR: call specified callback function with NULL as name to indicate an error */ + if (pEntry->found) { + (*pEntry->found)(pEntry->name, NULL, pEntry->arg); + } + /* flush this entry */ + pEntry->state = DNS_STATE_UNUSED; + pEntry->found = NULL; + +memerr: + /* free pbuf */ + pbuf_free(p); + return; +} + +/** + * Queues a new hostname to resolve and sends out a DNS query for that hostname + * + * @param name the hostname that is to be queried + * @param found a callback founction to be called on success, failure or timeout + * @param callback_arg argument to pass to the callback function + * @return @return a err_t return code. + */ +static err_t +dns_enqueue(const char *name, dns_found_callback found, void *callback_arg) +{ + u8_t i; + u8_t lseq, lseqi; + struct dns_table_entry *pEntry = NULL; + size_t namelen; + + /* search an unused entry, or the oldest one */ + lseq = lseqi = 0; + for (i = 0; i < DNS_TABLE_SIZE; ++i) { + pEntry = &dns_table[i]; + /* is it an unused entry ? */ + if (pEntry->state == DNS_STATE_UNUSED) + break; + + /* check if this is the oldest completed entry */ + if (pEntry->state == DNS_STATE_DONE) { + if ((dns_seqno - pEntry->seqno) > lseq) { + lseq = dns_seqno - pEntry->seqno; + lseqi = i; + } + } + } + + /* if we don't have found an unused entry, use the oldest completed one */ + if (i == DNS_TABLE_SIZE) { + if ((lseqi >= DNS_TABLE_SIZE) || (dns_table[lseqi].state != DNS_STATE_DONE)) { + /* no entry can't be used now, table is full */ + LWIP_DEBUGF(DNS_DEBUG, ("dns_enqueue: \"%s\": DNS entries table is full\n", name)); + return ERR_MEM; + } else { + /* use the oldest completed one */ + i = lseqi; + pEntry = &dns_table[i]; + } + } + + /* use this entry */ + LWIP_DEBUGF(DNS_DEBUG, ("dns_enqueue: \"%s\": use DNS entry %"U16_F"\n", name, (u16_t)(i))); + + /* fill the entry */ + pEntry->state = DNS_STATE_NEW; + pEntry->seqno = dns_seqno++; + pEntry->found = found; + pEntry->arg = callback_arg; + namelen = LWIP_MIN(strlen(name), DNS_MAX_NAME_LENGTH-1); + MEMCPY(pEntry->name, name, namelen); + pEntry->name[namelen] = 0; + + /* force to send query without waiting timer */ + dns_check_entry(i); + + /* dns query is enqueued */ + return ERR_INPROGRESS; +} + +/** + * Resolve a hostname (string) into an IP address. + * NON-BLOCKING callback version for use with raw API!!! + * + * Returns immediately with one of err_t return codes: + * - ERR_OK if hostname is a valid IP address string or the host + * name is already in the local names table. + * - ERR_INPROGRESS enqueue a request to be sent to the DNS server + * for resolution if no errors are present. + * - ERR_ARG: dns client not initialized or invalid hostname + * + * @param hostname the hostname that is to be queried + * @param addr pointer to a ip_addr_t where to store the address if it is already + * cached in the dns_table (only valid if ERR_OK is returned!) + * @param found a callback function to be called on success, failure or timeout (only if + * ERR_INPROGRESS is returned!) + * @param callback_arg argument to pass to the callback function + * @return a err_t return code. + */ +err_t +dns_gethostbyname(const char *hostname, ip_addr_t *addr, dns_found_callback found, + void *callback_arg) +{ + u32_t ipaddr; + /* not initialized or no valid server yet, or invalid addr pointer + * or invalid hostname or invalid hostname length */ + if ((dns_pcb == NULL) || (addr == NULL) || + (!hostname) || (!hostname[0]) || + (strlen(hostname) >= DNS_MAX_NAME_LENGTH)) { + return ERR_ARG; + } + +#if LWIP_HAVE_LOOPIF + if (strcmp(hostname, "localhost")==0) { + ip_addr_set_loopback(addr); + return ERR_OK; + } +#endif /* LWIP_HAVE_LOOPIF */ + + /* host name already in octet notation? set ip addr and return ERR_OK */ + ipaddr = ipaddr_addr(hostname); + if (ipaddr == IPADDR_NONE) { + /* already have this address cached? */ + ipaddr = dns_lookup(hostname); + } + if (ipaddr != IPADDR_NONE) { + ip4_addr_set_u32(addr, ipaddr); + return ERR_OK; + } + + /* queue query with specified callback */ + return dns_enqueue(hostname, found, callback_arg); +} + +#endif /* LWIP_DNS */ diff --git a/features/unsupported/net/lwip/lwip/core/init.c b/features/unsupported/net/lwip/lwip/core/init.c new file mode 100644 index 00000000000..bf5c79da0d6 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/core/init.c @@ -0,0 +1,306 @@ +/** + * @file + * Modules initialization + * + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ + +#include "lwip/opt.h" + +#include "lwip/init.h" +#include "lwip/stats.h" +#include "lwip/sys.h" +#include "lwip/mem.h" +#include "lwip/memp.h" +#include "lwip/pbuf.h" +#include "lwip/netif.h" +#include "lwip/sockets.h" +#include "lwip/ip.h" +#include "lwip/raw.h" +#include "lwip/udp.h" +#include "lwip/tcp_impl.h" +#include "lwip/snmp_msg.h" +#include "lwip/autoip.h" +#include "lwip/igmp.h" +#include "lwip/dns.h" +#include "lwip/timers.h" +#include "netif/etharp.h" + +/* Compile-time sanity checks for configuration errors. + * These can be done independently of LWIP_DEBUG, without penalty. + */ +#ifndef BYTE_ORDER + #error "BYTE_ORDER is not defined, you have to define it in your cc.h" +#endif +#if (!IP_SOF_BROADCAST && IP_SOF_BROADCAST_RECV) + #error "If you want to use broadcast filter per pcb on recv operations, you have to define IP_SOF_BROADCAST=1 in your lwipopts.h" +#endif +#if (!LWIP_ARP && ARP_QUEUEING) + #error "If you want to use ARP Queueing, you have to define LWIP_ARP=1 in your lwipopts.h" +#endif +#if (!LWIP_UDP && LWIP_UDPLITE) + #error "If you want to use UDP Lite, you have to define LWIP_UDP=1 in your lwipopts.h" +#endif +#if (!LWIP_UDP && LWIP_SNMP) + #error "If you want to use SNMP, you have to define LWIP_UDP=1 in your lwipopts.h" +#endif +#if (!LWIP_UDP && LWIP_DHCP) + #error "If you want to use DHCP, you have to define LWIP_UDP=1 in your lwipopts.h" +#endif +#if (!LWIP_UDP && LWIP_IGMP) + #error "If you want to use IGMP, you have to define LWIP_UDP=1 in your lwipopts.h" +#endif +#if (!LWIP_UDP && LWIP_SNMP) + #error "If you want to use SNMP, you have to define LWIP_UDP=1 in your lwipopts.h" +#endif +#if (!LWIP_UDP && LWIP_DNS) + #error "If you want to use DNS, you have to define LWIP_UDP=1 in your lwipopts.h" +#endif +#if (LWIP_ARP && ARP_QUEUEING && (MEMP_NUM_ARP_QUEUE<=0)) + #error "If you want to use ARP Queueing, you have to define MEMP_NUM_ARP_QUEUE>=1 in your lwipopts.h" +#endif +#if (LWIP_RAW && (MEMP_NUM_RAW_PCB<=0)) + #error "If you want to use RAW, you have to define MEMP_NUM_RAW_PCB>=1 in your lwipopts.h" +#endif +#if (LWIP_UDP && (MEMP_NUM_UDP_PCB<=0)) + #error "If you want to use UDP, you have to define MEMP_NUM_UDP_PCB>=1 in your lwipopts.h" +#endif +#if (LWIP_TCP && (MEMP_NUM_TCP_PCB<=0)) + #error "If you want to use TCP, you have to define MEMP_NUM_TCP_PCB>=1 in your lwipopts.h" +#endif +#if (LWIP_TCP && (TCP_WND > 0xffff)) + #error "If you want to use TCP, TCP_WND must fit in an u16_t, so, you have to reduce it in your lwipopts.h" +#endif +#if (LWIP_TCP && (TCP_SND_QUEUELEN > 0xffff)) + #error "If you want to use TCP, TCP_SND_QUEUELEN must fit in an u16_t, so, you have to reduce it in your lwipopts.h" +#endif +#if (LWIP_TCP && (TCP_SND_QUEUELEN < 2)) + #error "TCP_SND_QUEUELEN must be at least 2 for no-copy TCP writes to work" +#endif +#if (LWIP_TCP && ((TCP_MAXRTX > 12) || (TCP_SYNMAXRTX > 12))) + #error "If you want to use TCP, TCP_MAXRTX and TCP_SYNMAXRTX must less or equal to 12 (due to tcp_backoff table), so, you have to reduce them in your lwipopts.h" +#endif +#if (LWIP_TCP && TCP_LISTEN_BACKLOG && (TCP_DEFAULT_LISTEN_BACKLOG < 0) || (TCP_DEFAULT_LISTEN_BACKLOG > 0xff)) + #error "If you want to use TCP backlog, TCP_DEFAULT_LISTEN_BACKLOG must fit into an u8_t" +#endif +#if (LWIP_IGMP && (MEMP_NUM_IGMP_GROUP<=1)) + #error "If you want to use IGMP, you have to define MEMP_NUM_IGMP_GROUP>1 in your lwipopts.h" +#endif +#if (LWIP_NETIF_API && (NO_SYS==1)) + #error "If you want to use NETIF API, you have to define NO_SYS=0 in your lwipopts.h" +#endif +#if ((LWIP_SOCKET || LWIP_NETCONN) && (NO_SYS==1)) + #error "If you want to use Sequential API, you have to define NO_SYS=0 in your lwipopts.h" +#endif +#if ((LWIP_NETCONN || LWIP_SOCKET) && (MEMP_NUM_TCPIP_MSG_API<=0)) + #error "If you want to use Sequential API, you have to define MEMP_NUM_TCPIP_MSG_API>=1 in your lwipopts.h" +#endif +#if (!LWIP_NETCONN && LWIP_SOCKET) + #error "If you want to use Socket API, you have to define LWIP_NETCONN=1 in your lwipopts.h" +#endif +#if (((!LWIP_DHCP) || (!LWIP_AUTOIP)) && LWIP_DHCP_AUTOIP_COOP) + #error "If you want to use DHCP/AUTOIP cooperation mode, you have to define LWIP_DHCP=1 and LWIP_AUTOIP=1 in your lwipopts.h" +#endif +#if (((!LWIP_DHCP) || (!LWIP_ARP)) && DHCP_DOES_ARP_CHECK) + #error "If you want to use DHCP ARP checking, you have to define LWIP_DHCP=1 and LWIP_ARP=1 in your lwipopts.h" +#endif +#if (!LWIP_ARP && LWIP_AUTOIP) + #error "If you want to use AUTOIP, you have to define LWIP_ARP=1 in your lwipopts.h" +#endif +#if (LWIP_SNMP && (SNMP_CONCURRENT_REQUESTS<=0)) + #error "If you want to use SNMP, you have to define SNMP_CONCURRENT_REQUESTS>=1 in your lwipopts.h" +#endif +#if (LWIP_SNMP && (SNMP_TRAP_DESTINATIONS<=0)) + #error "If you want to use SNMP, you have to define SNMP_TRAP_DESTINATIONS>=1 in your lwipopts.h" +#endif +#if (LWIP_TCP && ((LWIP_EVENT_API && LWIP_CALLBACK_API) || (!LWIP_EVENT_API && !LWIP_CALLBACK_API))) + #error "One and exactly one of LWIP_EVENT_API and LWIP_CALLBACK_API has to be enabled in your lwipopts.h" +#endif +/* There must be sufficient timeouts, taking into account requirements of the subsystems. */ +#if LWIP_TIMERS && (MEMP_NUM_SYS_TIMEOUT < (LWIP_TCP + IP_REASSEMBLY + LWIP_ARP + (2*LWIP_DHCP) + LWIP_AUTOIP + LWIP_IGMP + LWIP_DNS + PPP_SUPPORT)) + #error "MEMP_NUM_SYS_TIMEOUT is too low to accomodate all required timeouts" +#endif +#if (IP_REASSEMBLY && (MEMP_NUM_REASSDATA > IP_REASS_MAX_PBUFS)) + #error "MEMP_NUM_REASSDATA > IP_REASS_MAX_PBUFS doesn't make sense since each struct ip_reassdata must hold 2 pbufs at least!" +#endif +#if (MEM_LIBC_MALLOC && MEM_USE_POOLS) + #error "MEM_LIBC_MALLOC and MEM_USE_POOLS may not both be simultaneously enabled in your lwipopts.h" +#endif +#if (MEM_USE_POOLS && !MEMP_USE_CUSTOM_POOLS) + #error "MEM_USE_POOLS requires custom pools (MEMP_USE_CUSTOM_POOLS) to be enabled in your lwipopts.h" +#endif +#if (PBUF_POOL_BUFSIZE <= MEM_ALIGNMENT) + #error "PBUF_POOL_BUFSIZE must be greater than MEM_ALIGNMENT or the offset may take the full first pbuf" +#endif +#if (TCP_QUEUE_OOSEQ && !LWIP_TCP) + #error "TCP_QUEUE_OOSEQ requires LWIP_TCP" +#endif +#if (DNS_LOCAL_HOSTLIST && !DNS_LOCAL_HOSTLIST_IS_DYNAMIC && !(defined(DNS_LOCAL_HOSTLIST_INIT))) + #error "you have to define define DNS_LOCAL_HOSTLIST_INIT {{'host1', 0x123}, {'host2', 0x234}} to initialize DNS_LOCAL_HOSTLIST" +#endif +#if PPP_SUPPORT && !PPPOS_SUPPORT & !PPPOE_SUPPORT + #error "PPP_SUPPORT needs either PPPOS_SUPPORT or PPPOE_SUPPORT turned on" +#endif +#if !LWIP_ETHERNET && (LWIP_ARP || PPPOE_SUPPORT) + #error "LWIP_ETHERNET needs to be turned on for LWIP_ARP or PPPOE_SUPPORT" +#endif +#if LWIP_IGMP && !defined(LWIP_RAND) + #error "When using IGMP, LWIP_RAND() needs to be defined to a random-function returning an u32_t random value" +#endif +#if LWIP_TCPIP_CORE_LOCKING_INPUT && !LWIP_TCPIP_CORE_LOCKING + #error "When using LWIP_TCPIP_CORE_LOCKING_INPUT, LWIP_TCPIP_CORE_LOCKING must be enabled, too" +#endif +#if LWIP_TCP && LWIP_NETIF_TX_SINGLE_PBUF && !TCP_OVERSIZE + #error "LWIP_NETIF_TX_SINGLE_PBUF needs TCP_OVERSIZE enabled to create single-pbuf TCP packets" +#endif +#if IP_FRAG && IP_FRAG_USES_STATIC_BUF && LWIP_NETIF_TX_SINGLE_PBUF + #error "LWIP_NETIF_TX_SINGLE_PBUF does not work with IP_FRAG_USES_STATIC_BUF==1 as that creates pbuf queues" +#endif + + +/* Compile-time checks for deprecated options. + */ +#ifdef MEMP_NUM_TCPIP_MSG + #error "MEMP_NUM_TCPIP_MSG option is deprecated. Remove it from your lwipopts.h." +#endif +#ifdef MEMP_NUM_API_MSG + #error "MEMP_NUM_API_MSG option is deprecated. Remove it from your lwipopts.h." +#endif +#ifdef TCP_REXMIT_DEBUG + #error "TCP_REXMIT_DEBUG option is deprecated. Remove it from your lwipopts.h." +#endif +#ifdef RAW_STATS + #error "RAW_STATS option is deprecated. Remove it from your lwipopts.h." +#endif +#ifdef ETHARP_QUEUE_FIRST + #error "ETHARP_QUEUE_FIRST option is deprecated. Remove it from your lwipopts.h." +#endif +#ifdef ETHARP_ALWAYS_INSERT + #error "ETHARP_ALWAYS_INSERT option is deprecated. Remove it from your lwipopts.h." +#endif + +#ifdef LWIP_DEBUG +static void +lwip_sanity_check(void) +{ + /* Warnings */ +#if LWIP_NETCONN + if (MEMP_NUM_NETCONN > (MEMP_NUM_TCP_PCB+MEMP_NUM_TCP_PCB_LISTEN+MEMP_NUM_UDP_PCB+MEMP_NUM_RAW_PCB)) + LWIP_PLATFORM_DIAG(("lwip_sanity_check: WARNING: MEMP_NUM_NETCONN should be less than the sum of MEMP_NUM_{TCP,RAW,UDP}_PCB+MEMP_NUM_TCP_PCB_LISTEN\n")); +#endif /* LWIP_NETCONN */ +#if LWIP_TCP + if (MEMP_NUM_TCP_SEG < TCP_SND_QUEUELEN) + LWIP_PLATFORM_DIAG(("lwip_sanity_check: WARNING: MEMP_NUM_TCP_SEG should be at least as big as TCP_SND_QUEUELEN\n")); + if (TCP_SND_BUF < 2 * TCP_MSS) + LWIP_PLATFORM_DIAG(("lwip_sanity_check: WARNING: TCP_SND_BUF must be at least as much as (2 * TCP_MSS) for things to work smoothly\n")); + if (TCP_SND_QUEUELEN < (2 * (TCP_SND_BUF/TCP_MSS))) + LWIP_PLATFORM_DIAG(("lwip_sanity_check: WARNING: TCP_SND_QUEUELEN must be at least as much as (2 * TCP_SND_BUF/TCP_MSS) for things to work\n")); + if (TCP_SNDLOWAT >= TCP_SND_BUF) + LWIP_PLATFORM_DIAG(("lwip_sanity_check: WARNING: TCP_SNDLOWAT must be less than TCP_SND_BUF.\n")); + if (TCP_SNDQUEUELOWAT >= TCP_SND_QUEUELEN) + LWIP_PLATFORM_DIAG(("lwip_sanity_check: WARNING: TCP_SNDQUEUELOWAT must be less than TCP_SND_QUEUELEN.\n")); + if (TCP_WND > (PBUF_POOL_SIZE*PBUF_POOL_BUFSIZE)) + LWIP_PLATFORM_DIAG(("lwip_sanity_check: WARNING: TCP_WND is larger than space provided by PBUF_POOL_SIZE*PBUF_POOL_BUFSIZE\n")); + if (TCP_WND < TCP_MSS) + LWIP_PLATFORM_DIAG(("lwip_sanity_check: WARNING: TCP_WND is smaller than MSS\n")); +#endif /* LWIP_TCP */ +#if LWIP_SOCKET + /* Check that the SO_* socket options and SOF_* lwIP-internal flags match */ + if (SO_ACCEPTCONN != SOF_ACCEPTCONN) + LWIP_PLATFORM_DIAG(("lwip_sanity_check: WARNING: SO_ACCEPTCONN != SOF_ACCEPTCONN\n")); + if (SO_REUSEADDR != SOF_REUSEADDR) + LWIP_PLATFORM_DIAG(("lwip_sanity_check: WARNING: SO_REUSEADDR != SOF_REUSEADDR\n")); + if (SO_KEEPALIVE != SOF_KEEPALIVE) + LWIP_PLATFORM_DIAG(("lwip_sanity_check: WARNING: SO_KEEPALIVE != SOF_KEEPALIVE\n")); + if (SO_BROADCAST != SOF_BROADCAST) + LWIP_PLATFORM_DIAG(("lwip_sanity_check: WARNING: SO_BROADCAST != SOF_BROADCAST\n")); + if (SO_LINGER != SOF_LINGER) + LWIP_PLATFORM_DIAG(("lwip_sanity_check: WARNING: SO_LINGER != SOF_LINGER\n")); +#endif /* LWIP_SOCKET */ +} +#else /* LWIP_DEBUG */ +#define lwip_sanity_check() +#endif /* LWIP_DEBUG */ + +/** + * Perform Sanity check of user-configurable values, and initialize all modules. + */ +void +lwip_init(void) +{ + /* Sanity check user-configurable values */ + lwip_sanity_check(); + + /* Modules initialization */ + stats_init(); +#if !NO_SYS + sys_init(); +#endif /* !NO_SYS */ + mem_init(); + memp_init(); + pbuf_init(); + netif_init(); +#if LWIP_SOCKET + lwip_socket_init(); +#endif /* LWIP_SOCKET */ + ip_init(); +#if LWIP_ARP + etharp_init(); +#endif /* LWIP_ARP */ +#if LWIP_RAW + raw_init(); +#endif /* LWIP_RAW */ +#if LWIP_UDP + udp_init(); +#endif /* LWIP_UDP */ +#if LWIP_TCP + tcp_init(); +#endif /* LWIP_TCP */ +#if LWIP_SNMP + snmp_init(); +#endif /* LWIP_SNMP */ +#if LWIP_AUTOIP + autoip_init(); +#endif /* LWIP_AUTOIP */ +#if LWIP_IGMP + igmp_init(); +#endif /* LWIP_IGMP */ +#if LWIP_DNS + dns_init(); +#endif /* LWIP_DNS */ + +#if LWIP_TIMERS + sys_timeouts_init(); +#endif /* LWIP_TIMERS */ +} diff --git a/features/unsupported/net/lwip/lwip/core/ipv4/autoip.c b/features/unsupported/net/lwip/lwip/core/ipv4/autoip.c new file mode 100644 index 00000000000..92bb4591f1a --- /dev/null +++ b/features/unsupported/net/lwip/lwip/core/ipv4/autoip.c @@ -0,0 +1,536 @@ +/** + * @file + * AutoIP Automatic LinkLocal IP Configuration + * + */ + +/* + * + * Copyright (c) 2007 Dominik Spies + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * Author: Dominik Spies + * + * This is a AutoIP implementation for the lwIP TCP/IP stack. It aims to conform + * with RFC 3927. + * + * + * Please coordinate changes and requests with Dominik Spies + * + */ + +/******************************************************************************* + * USAGE: + * + * define LWIP_AUTOIP 1 in your lwipopts.h + * + * If you don't use tcpip.c (so, don't call, you don't call tcpip_init): + * - First, call autoip_init(). + * - call autoip_tmr() all AUTOIP_TMR_INTERVAL msces, + * that should be defined in autoip.h. + * I recommend a value of 100. The value must divide 1000 with a remainder almost 0. + * Possible values are 1000, 500, 333, 250, 200, 166, 142, 125, 111, 100 .... + * + * Without DHCP: + * - Call autoip_start() after netif_add(). + * + * With DHCP: + * - define LWIP_DHCP_AUTOIP_COOP 1 in your lwipopts.h. + * - Configure your DHCP Client. + * + */ + +#include "lwip/opt.h" + +#if LWIP_AUTOIP /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/mem.h" +#include "lwip/udp.h" +#include "lwip/ip_addr.h" +#include "lwip/netif.h" +#include "lwip/autoip.h" +#include "netif/etharp.h" + +#include +#include + +/* 169.254.0.0 */ +#define AUTOIP_NET 0xA9FE0000 +/* 169.254.1.0 */ +#define AUTOIP_RANGE_START (AUTOIP_NET | 0x0100) +/* 169.254.254.255 */ +#define AUTOIP_RANGE_END (AUTOIP_NET | 0xFEFF) + + +/** Pseudo random macro based on netif informations. + * You could use "rand()" from the C Library if you define LWIP_AUTOIP_RAND in lwipopts.h */ +#ifndef LWIP_AUTOIP_RAND +#define LWIP_AUTOIP_RAND(netif) ( (((u32_t)((netif->hwaddr[5]) & 0xff) << 24) | \ + ((u32_t)((netif->hwaddr[3]) & 0xff) << 16) | \ + ((u32_t)((netif->hwaddr[2]) & 0xff) << 8) | \ + ((u32_t)((netif->hwaddr[4]) & 0xff))) + \ + (netif->autoip?netif->autoip->tried_llipaddr:0)) +#endif /* LWIP_AUTOIP_RAND */ + +/** + * Macro that generates the initial IP address to be tried by AUTOIP. + * If you want to override this, define it to something else in lwipopts.h. + */ +#ifndef LWIP_AUTOIP_CREATE_SEED_ADDR +#define LWIP_AUTOIP_CREATE_SEED_ADDR(netif) \ + htonl(AUTOIP_RANGE_START + ((u32_t)(((u8_t)(netif->hwaddr[4])) | \ + ((u32_t)((u8_t)(netif->hwaddr[5]))) << 8))) +#endif /* LWIP_AUTOIP_CREATE_SEED_ADDR */ + +/* static functions */ +static void autoip_handle_arp_conflict(struct netif *netif); + +/* creates a pseudo random LL IP-Address for a network interface */ +static void autoip_create_addr(struct netif *netif, ip_addr_t *ipaddr); + +/* sends an ARP probe */ +static err_t autoip_arp_probe(struct netif *netif); + +/* sends an ARP announce */ +static err_t autoip_arp_announce(struct netif *netif); + +/* configure interface for use with current LL IP-Address */ +static err_t autoip_bind(struct netif *netif); + +/* start sending probes for llipaddr */ +static void autoip_start_probing(struct netif *netif); + +/** + * Initialize this module + */ +void +autoip_init(void) +{ + LWIP_DEBUGF(AUTOIP_DEBUG | LWIP_DBG_TRACE, ("autoip_init()\n")); +} + +/** Set a statically allocated struct autoip to work with. + * Using this prevents autoip_start to allocate it using mem_malloc. + * + * @param netif the netif for which to set the struct autoip + * @param dhcp (uninitialised) dhcp struct allocated by the application + */ +void +autoip_set_struct(struct netif *netif, struct autoip *autoip) +{ + LWIP_ASSERT("netif != NULL", netif != NULL); + LWIP_ASSERT("autoip != NULL", autoip != NULL); + LWIP_ASSERT("netif already has a struct autoip set", netif->autoip == NULL); + + /* clear data structure */ + memset(autoip, 0, sizeof(struct autoip)); + /* autoip->state = AUTOIP_STATE_OFF; */ + netif->autoip = autoip; +} + +/** Restart AutoIP client and check the next address (conflict detected) + * + * @param netif The netif under AutoIP control + */ +static void +autoip_restart(struct netif *netif) +{ + netif->autoip->tried_llipaddr++; + autoip_start(netif); +} + +/** + * Handle a IP address conflict after an ARP conflict detection + */ +static void +autoip_handle_arp_conflict(struct netif *netif) +{ + /* Somehow detect if we are defending or retreating */ + unsigned char defend = 1; /* tbd */ + + if(defend) { + if(netif->autoip->lastconflict > 0) { + /* retreat, there was a conflicting ARP in the last + * DEFEND_INTERVAL seconds + */ + LWIP_DEBUGF(AUTOIP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, + ("autoip_handle_arp_conflict(): we are defending, but in DEFEND_INTERVAL, retreating\n")); + + /* TODO: close all TCP sessions */ + autoip_restart(netif); + } else { + LWIP_DEBUGF(AUTOIP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, + ("autoip_handle_arp_conflict(): we are defend, send ARP Announce\n")); + autoip_arp_announce(netif); + netif->autoip->lastconflict = DEFEND_INTERVAL * AUTOIP_TICKS_PER_SECOND; + } + } else { + LWIP_DEBUGF(AUTOIP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, + ("autoip_handle_arp_conflict(): we do not defend, retreating\n")); + /* TODO: close all TCP sessions */ + autoip_restart(netif); + } +} + +/** + * Create an IP-Address out of range 169.254.1.0 to 169.254.254.255 + * + * @param netif network interface on which create the IP-Address + * @param ipaddr ip address to initialize + */ +static void +autoip_create_addr(struct netif *netif, ip_addr_t *ipaddr) +{ + /* Here we create an IP-Address out of range 169.254.1.0 to 169.254.254.255 + * compliant to RFC 3927 Section 2.1 + * We have 254 * 256 possibilities */ + + u32_t addr = ntohl(LWIP_AUTOIP_CREATE_SEED_ADDR(netif)); + addr += netif->autoip->tried_llipaddr; + addr = AUTOIP_NET | (addr & 0xffff); + /* Now, 169.254.0.0 <= addr <= 169.254.255.255 */ + + if (addr < AUTOIP_RANGE_START) { + addr += AUTOIP_RANGE_END - AUTOIP_RANGE_START + 1; + } + if (addr > AUTOIP_RANGE_END) { + addr -= AUTOIP_RANGE_END - AUTOIP_RANGE_START + 1; + } + LWIP_ASSERT("AUTOIP address not in range", (addr >= AUTOIP_RANGE_START) && + (addr <= AUTOIP_RANGE_END)); + ip4_addr_set_u32(ipaddr, htonl(addr)); + + LWIP_DEBUGF(AUTOIP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, + ("autoip_create_addr(): tried_llipaddr=%"U16_F", %"U16_F".%"U16_F".%"U16_F".%"U16_F"\n", + (u16_t)(netif->autoip->tried_llipaddr), ip4_addr1_16(ipaddr), ip4_addr2_16(ipaddr), + ip4_addr3_16(ipaddr), ip4_addr4_16(ipaddr))); +} + +/** + * Sends an ARP probe from a network interface + * + * @param netif network interface used to send the probe + */ +static err_t +autoip_arp_probe(struct netif *netif) +{ + return etharp_raw(netif, (struct eth_addr *)netif->hwaddr, ðbroadcast, + (struct eth_addr *)netif->hwaddr, IP_ADDR_ANY, ðzero, + &netif->autoip->llipaddr, ARP_REQUEST); +} + +/** + * Sends an ARP announce from a network interface + * + * @param netif network interface used to send the announce + */ +static err_t +autoip_arp_announce(struct netif *netif) +{ + return etharp_raw(netif, (struct eth_addr *)netif->hwaddr, ðbroadcast, + (struct eth_addr *)netif->hwaddr, &netif->autoip->llipaddr, ðzero, + &netif->autoip->llipaddr, ARP_REQUEST); +} + +/** + * Configure interface for use with current LL IP-Address + * + * @param netif network interface to configure with current LL IP-Address + */ +static err_t +autoip_bind(struct netif *netif) +{ + struct autoip *autoip = netif->autoip; + ip_addr_t sn_mask, gw_addr; + + LWIP_DEBUGF(AUTOIP_DEBUG | LWIP_DBG_TRACE, + ("autoip_bind(netif=%p) %c%c%"U16_F" %"U16_F".%"U16_F".%"U16_F".%"U16_F"\n", + (void*)netif, netif->name[0], netif->name[1], (u16_t)netif->num, + ip4_addr1_16(&autoip->llipaddr), ip4_addr2_16(&autoip->llipaddr), + ip4_addr3_16(&autoip->llipaddr), ip4_addr4_16(&autoip->llipaddr))); + + IP4_ADDR(&sn_mask, 255, 255, 0, 0); + IP4_ADDR(&gw_addr, 0, 0, 0, 0); + + netif_set_ipaddr(netif, &autoip->llipaddr); + netif_set_netmask(netif, &sn_mask); + netif_set_gw(netif, &gw_addr); + + /* bring the interface up */ + netif_set_up(netif); + + return ERR_OK; +} + +/** + * Start AutoIP client + * + * @param netif network interface on which start the AutoIP client + */ +err_t +autoip_start(struct netif *netif) +{ + struct autoip *autoip = netif->autoip; + err_t result = ERR_OK; + + if(netif_is_up(netif)) { + netif_set_down(netif); + } + + /* Set IP-Address, Netmask and Gateway to 0 to make sure that + * ARP Packets are formed correctly + */ + ip_addr_set_zero(&netif->ip_addr); + ip_addr_set_zero(&netif->netmask); + ip_addr_set_zero(&netif->gw); + + LWIP_DEBUGF(AUTOIP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, + ("autoip_start(netif=%p) %c%c%"U16_F"\n", (void*)netif, netif->name[0], + netif->name[1], (u16_t)netif->num)); + if(autoip == NULL) { + /* no AutoIP client attached yet? */ + LWIP_DEBUGF(AUTOIP_DEBUG | LWIP_DBG_TRACE, + ("autoip_start(): starting new AUTOIP client\n")); + autoip = (struct autoip *)mem_malloc(sizeof(struct autoip)); + if(autoip == NULL) { + LWIP_DEBUGF(AUTOIP_DEBUG | LWIP_DBG_TRACE, + ("autoip_start(): could not allocate autoip\n")); + return ERR_MEM; + } + memset(autoip, 0, sizeof(struct autoip)); + /* store this AutoIP client in the netif */ + netif->autoip = autoip; + LWIP_DEBUGF(AUTOIP_DEBUG | LWIP_DBG_TRACE, ("autoip_start(): allocated autoip")); + } else { + autoip->state = AUTOIP_STATE_OFF; + autoip->ttw = 0; + autoip->sent_num = 0; + ip_addr_set_zero(&autoip->llipaddr); + autoip->lastconflict = 0; + } + + autoip_create_addr(netif, &(autoip->llipaddr)); + autoip_start_probing(netif); + + return result; +} + +static void +autoip_start_probing(struct netif *netif) +{ + struct autoip *autoip = netif->autoip; + + autoip->state = AUTOIP_STATE_PROBING; + autoip->sent_num = 0; + LWIP_DEBUGF(AUTOIP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, + ("autoip_start_probing(): changing state to PROBING: %"U16_F".%"U16_F".%"U16_F".%"U16_F"\n", + ip4_addr1_16(&netif->autoip->llipaddr), ip4_addr2_16(&netif->autoip->llipaddr), + ip4_addr3_16(&netif->autoip->llipaddr), ip4_addr4_16(&netif->autoip->llipaddr))); + + /* time to wait to first probe, this is randomly + * choosen out of 0 to PROBE_WAIT seconds. + * compliant to RFC 3927 Section 2.2.1 + */ + autoip->ttw = (u16_t)(LWIP_AUTOIP_RAND(netif) % (PROBE_WAIT * AUTOIP_TICKS_PER_SECOND)); + + /* + * if we tried more then MAX_CONFLICTS we must limit our rate for + * accquiring and probing address + * compliant to RFC 3927 Section 2.2.1 + */ + if(autoip->tried_llipaddr > MAX_CONFLICTS) { + autoip->ttw = RATE_LIMIT_INTERVAL * AUTOIP_TICKS_PER_SECOND; + } +} + +/** + * Handle a possible change in the network configuration. + * + * If there is an AutoIP address configured, take the interface down + * and begin probing with the same address. + */ +void +autoip_network_changed(struct netif *netif) +{ + if (netif->autoip && netif->autoip->state != AUTOIP_STATE_OFF) { + netif_set_down(netif); + autoip_start_probing(netif); + } +} + +/** + * Stop AutoIP client + * + * @param netif network interface on which stop the AutoIP client + */ +err_t +autoip_stop(struct netif *netif) +{ + netif->autoip->state = AUTOIP_STATE_OFF; + netif_set_down(netif); + return ERR_OK; +} + +/** + * Has to be called in loop every AUTOIP_TMR_INTERVAL milliseconds + */ +void +autoip_tmr() +{ + struct netif *netif = netif_list; + /* loop through netif's */ + while (netif != NULL) { + /* only act on AutoIP configured interfaces */ + if (netif->autoip != NULL) { + if(netif->autoip->lastconflict > 0) { + netif->autoip->lastconflict--; + } + + LWIP_DEBUGF(AUTOIP_DEBUG | LWIP_DBG_TRACE, + ("autoip_tmr() AutoIP-State: %"U16_F", ttw=%"U16_F"\n", + (u16_t)(netif->autoip->state), netif->autoip->ttw)); + + switch(netif->autoip->state) { + case AUTOIP_STATE_PROBING: + if(netif->autoip->ttw > 0) { + netif->autoip->ttw--; + } else { + if(netif->autoip->sent_num >= PROBE_NUM) { + netif->autoip->state = AUTOIP_STATE_ANNOUNCING; + netif->autoip->sent_num = 0; + netif->autoip->ttw = ANNOUNCE_WAIT * AUTOIP_TICKS_PER_SECOND; + LWIP_DEBUGF(AUTOIP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, + ("autoip_tmr(): changing state to ANNOUNCING: %"U16_F".%"U16_F".%"U16_F".%"U16_F"\n", + ip4_addr1_16(&netif->autoip->llipaddr), ip4_addr2_16(&netif->autoip->llipaddr), + ip4_addr3_16(&netif->autoip->llipaddr), ip4_addr4_16(&netif->autoip->llipaddr))); + } else { + autoip_arp_probe(netif); + LWIP_DEBUGF(AUTOIP_DEBUG | LWIP_DBG_TRACE, + ("autoip_tmr() PROBING Sent Probe\n")); + netif->autoip->sent_num++; + /* calculate time to wait to next probe */ + netif->autoip->ttw = (u16_t)((LWIP_AUTOIP_RAND(netif) % + ((PROBE_MAX - PROBE_MIN) * AUTOIP_TICKS_PER_SECOND) ) + + PROBE_MIN * AUTOIP_TICKS_PER_SECOND); + } + } + break; + + case AUTOIP_STATE_ANNOUNCING: + if(netif->autoip->ttw > 0) { + netif->autoip->ttw--; + } else { + if(netif->autoip->sent_num == 0) { + /* We are here the first time, so we waited ANNOUNCE_WAIT seconds + * Now we can bind to an IP address and use it. + * + * autoip_bind calls netif_set_up. This triggers a gratuitous ARP + * which counts as an announcement. + */ + autoip_bind(netif); + } else { + autoip_arp_announce(netif); + LWIP_DEBUGF(AUTOIP_DEBUG | LWIP_DBG_TRACE, + ("autoip_tmr() ANNOUNCING Sent Announce\n")); + } + netif->autoip->ttw = ANNOUNCE_INTERVAL * AUTOIP_TICKS_PER_SECOND; + netif->autoip->sent_num++; + + if(netif->autoip->sent_num >= ANNOUNCE_NUM) { + netif->autoip->state = AUTOIP_STATE_BOUND; + netif->autoip->sent_num = 0; + netif->autoip->ttw = 0; + LWIP_DEBUGF(AUTOIP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, + ("autoip_tmr(): changing state to BOUND: %"U16_F".%"U16_F".%"U16_F".%"U16_F"\n", + ip4_addr1_16(&netif->autoip->llipaddr), ip4_addr2_16(&netif->autoip->llipaddr), + ip4_addr3_16(&netif->autoip->llipaddr), ip4_addr4_16(&netif->autoip->llipaddr))); + } + } + break; + } + } + /* proceed to next network interface */ + netif = netif->next; + } +} + +/** + * Handles every incoming ARP Packet, called by etharp_arp_input. + * + * @param netif network interface to use for autoip processing + * @param hdr Incoming ARP packet + */ +void +autoip_arp_reply(struct netif *netif, struct etharp_hdr *hdr) +{ + LWIP_DEBUGF(AUTOIP_DEBUG | LWIP_DBG_TRACE, ("autoip_arp_reply()\n")); + if ((netif->autoip != NULL) && (netif->autoip->state != AUTOIP_STATE_OFF)) { + /* when ip.src == llipaddr && hw.src != netif->hwaddr + * + * when probing ip.dst == llipaddr && hw.src != netif->hwaddr + * we have a conflict and must solve it + */ + ip_addr_t sipaddr, dipaddr; + struct eth_addr netifaddr; + ETHADDR16_COPY(netifaddr.addr, netif->hwaddr); + + /* Copy struct ip_addr2 to aligned ip_addr, to support compilers without + * structure packing (not using structure copy which breaks strict-aliasing rules). + */ + IPADDR2_COPY(&sipaddr, &hdr->sipaddr); + IPADDR2_COPY(&dipaddr, &hdr->dipaddr); + + if ((netif->autoip->state == AUTOIP_STATE_PROBING) || + ((netif->autoip->state == AUTOIP_STATE_ANNOUNCING) && + (netif->autoip->sent_num == 0))) { + /* RFC 3927 Section 2.2.1: + * from beginning to after ANNOUNCE_WAIT + * seconds we have a conflict if + * ip.src == llipaddr OR + * ip.dst == llipaddr && hw.src != own hwaddr + */ + if ((ip_addr_cmp(&sipaddr, &netif->autoip->llipaddr)) || + (ip_addr_cmp(&dipaddr, &netif->autoip->llipaddr) && + !eth_addr_cmp(&netifaddr, &hdr->shwaddr))) { + LWIP_DEBUGF(AUTOIP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE | LWIP_DBG_LEVEL_WARNING, + ("autoip_arp_reply(): Probe Conflict detected\n")); + autoip_restart(netif); + } + } else { + /* RFC 3927 Section 2.5: + * in any state we have a conflict if + * ip.src == llipaddr && hw.src != own hwaddr + */ + if (ip_addr_cmp(&sipaddr, &netif->autoip->llipaddr) && + !eth_addr_cmp(&netifaddr, &hdr->shwaddr)) { + LWIP_DEBUGF(AUTOIP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE | LWIP_DBG_LEVEL_WARNING, + ("autoip_arp_reply(): Conflicting ARP-Packet detected\n")); + autoip_handle_arp_conflict(netif); + } + } + } +} + +#endif /* LWIP_AUTOIP */ diff --git a/features/unsupported/net/lwip/lwip/core/ipv4/icmp.c b/features/unsupported/net/lwip/lwip/core/ipv4/icmp.c new file mode 100644 index 00000000000..32902a522ca --- /dev/null +++ b/features/unsupported/net/lwip/lwip/core/ipv4/icmp.c @@ -0,0 +1,335 @@ +/** + * @file + * ICMP - Internet Control Message Protocol + * + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ + +/* Some ICMP messages should be passed to the transport protocols. This + is not implemented. */ + +#include "lwip/opt.h" + +#if LWIP_ICMP /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/icmp.h" +#include "lwip/inet_chksum.h" +#include "lwip/ip.h" +#include "lwip/def.h" +#include "lwip/stats.h" +#include "lwip/snmp.h" + +#include + +/** Small optimization: set to 0 if incoming PBUF_POOL pbuf always can be + * used to modify and send a response packet (and to 1 if this is not the case, + * e.g. when link header is stripped of when receiving) */ +#ifndef LWIP_ICMP_ECHO_CHECK_INPUT_PBUF_LEN +#define LWIP_ICMP_ECHO_CHECK_INPUT_PBUF_LEN 1 +#endif /* LWIP_ICMP_ECHO_CHECK_INPUT_PBUF_LEN */ + +/* The amount of data from the original packet to return in a dest-unreachable */ +#define ICMP_DEST_UNREACH_DATASIZE 8 + +static void icmp_send_response(struct pbuf *p, u8_t type, u8_t code); + +/** + * Processes ICMP input packets, called from ip_input(). + * + * Currently only processes icmp echo requests and sends + * out the echo response. + * + * @param p the icmp echo request packet, p->payload pointing to the ip header + * @param inp the netif on which this packet was received + */ +void +icmp_input(struct pbuf *p, struct netif *inp) +{ + u8_t type; +#ifdef LWIP_DEBUG + u8_t code; +#endif /* LWIP_DEBUG */ + struct icmp_echo_hdr *iecho; + struct ip_hdr *iphdr; + s16_t hlen; + + ICMP_STATS_INC(icmp.recv); + snmp_inc_icmpinmsgs(); + + + iphdr = (struct ip_hdr *)p->payload; + hlen = IPH_HL(iphdr) * 4; + if (pbuf_header(p, -hlen) || (p->tot_len < sizeof(u16_t)*2)) { + LWIP_DEBUGF(ICMP_DEBUG, ("icmp_input: short ICMP (%"U16_F" bytes) received\n", p->tot_len)); + goto lenerr; + } + + type = *((u8_t *)p->payload); +#ifdef LWIP_DEBUG + code = *(((u8_t *)p->payload)+1); +#endif /* LWIP_DEBUG */ + switch (type) { + case ICMP_ER: + /* This is OK, echo reply might have been parsed by a raw PCB + (as obviously, an echo request has been sent, too). */ + break; + case ICMP_ECHO: +#if !LWIP_MULTICAST_PING || !LWIP_BROADCAST_PING + { + int accepted = 1; +#if !LWIP_MULTICAST_PING + /* multicast destination address? */ + if (ip_addr_ismulticast(¤t_iphdr_dest)) { + accepted = 0; + } +#endif /* LWIP_MULTICAST_PING */ +#if !LWIP_BROADCAST_PING + /* broadcast destination address? */ + if (ip_addr_isbroadcast(¤t_iphdr_dest, inp)) { + accepted = 0; + } +#endif /* LWIP_BROADCAST_PING */ + /* broadcast or multicast destination address not acceptd? */ + if (!accepted) { + LWIP_DEBUGF(ICMP_DEBUG, ("icmp_input: Not echoing to multicast or broadcast pings\n")); + ICMP_STATS_INC(icmp.err); + pbuf_free(p); + return; + } + } +#endif /* !LWIP_MULTICAST_PING || !LWIP_BROADCAST_PING */ + LWIP_DEBUGF(ICMP_DEBUG, ("icmp_input: ping\n")); + if (p->tot_len < sizeof(struct icmp_echo_hdr)) { + LWIP_DEBUGF(ICMP_DEBUG, ("icmp_input: bad ICMP echo received\n")); + goto lenerr; + } + if (inet_chksum_pbuf(p) != 0) { + LWIP_DEBUGF(ICMP_DEBUG, ("icmp_input: checksum failed for received ICMP echo\n")); + pbuf_free(p); + ICMP_STATS_INC(icmp.chkerr); + snmp_inc_icmpinerrors(); + return; + } +#if LWIP_ICMP_ECHO_CHECK_INPUT_PBUF_LEN + if (pbuf_header(p, (PBUF_IP_HLEN + PBUF_LINK_HLEN))) { + /* p is not big enough to contain link headers + * allocate a new one and copy p into it + */ + struct pbuf *r; + /* switch p->payload to ip header */ + if (pbuf_header(p, hlen)) { + LWIP_ASSERT("icmp_input: moving p->payload to ip header failed\n", 0); + goto memerr; + } + /* allocate new packet buffer with space for link headers */ + r = pbuf_alloc(PBUF_LINK, p->tot_len, PBUF_RAM); + if (r == NULL) { + LWIP_DEBUGF(ICMP_DEBUG, ("icmp_input: allocating new pbuf failed\n")); + goto memerr; + } + LWIP_ASSERT("check that first pbuf can hold struct the ICMP header", + (r->len >= hlen + sizeof(struct icmp_echo_hdr))); + /* copy the whole packet including ip header */ + if (pbuf_copy(r, p) != ERR_OK) { + LWIP_ASSERT("icmp_input: copying to new pbuf failed\n", 0); + goto memerr; + } + iphdr = (struct ip_hdr *)r->payload; + /* switch r->payload back to icmp header */ + if (pbuf_header(r, -hlen)) { + LWIP_ASSERT("icmp_input: restoring original p->payload failed\n", 0); + goto memerr; + } + /* free the original p */ + pbuf_free(p); + /* we now have an identical copy of p that has room for link headers */ + p = r; + } else { + /* restore p->payload to point to icmp header */ + if (pbuf_header(p, -(s16_t)(PBUF_IP_HLEN + PBUF_LINK_HLEN))) { + LWIP_ASSERT("icmp_input: restoring original p->payload failed\n", 0); + goto memerr; + } + } +#endif /* LWIP_ICMP_ECHO_CHECK_INPUT_PBUF_LEN */ + /* At this point, all checks are OK. */ + /* We generate an answer by switching the dest and src ip addresses, + * setting the icmp type to ECHO_RESPONSE and updating the checksum. */ + iecho = (struct icmp_echo_hdr *)p->payload; + ip_addr_copy(iphdr->src, *ip_current_dest_addr()); + ip_addr_copy(iphdr->dest, *ip_current_src_addr()); + ICMPH_TYPE_SET(iecho, ICMP_ER); + /* adjust the checksum */ + if (iecho->chksum >= PP_HTONS(0xffffU - (ICMP_ECHO << 8))) { + iecho->chksum += PP_HTONS(ICMP_ECHO << 8) + 1; + } else { + iecho->chksum += PP_HTONS(ICMP_ECHO << 8); + } + + /* Set the correct TTL and recalculate the header checksum. */ + IPH_TTL_SET(iphdr, ICMP_TTL); + IPH_CHKSUM_SET(iphdr, 0); +#if CHECKSUM_GEN_IP + IPH_CHKSUM_SET(iphdr, inet_chksum(iphdr, IP_HLEN)); +#endif /* CHECKSUM_GEN_IP */ + + ICMP_STATS_INC(icmp.xmit); + /* increase number of messages attempted to send */ + snmp_inc_icmpoutmsgs(); + /* increase number of echo replies attempted to send */ + snmp_inc_icmpoutechoreps(); + + if(pbuf_header(p, hlen)) { + LWIP_ASSERT("Can't move over header in packet", 0); + } else { + err_t ret; + /* send an ICMP packet, src addr is the dest addr of the curren packet */ + ret = ip_output_if(p, ip_current_dest_addr(), IP_HDRINCL, + ICMP_TTL, 0, IP_PROTO_ICMP, inp); + if (ret != ERR_OK) { + LWIP_DEBUGF(ICMP_DEBUG, ("icmp_input: ip_output_if returned an error: %c.\n", ret)); + } + } + break; + default: + LWIP_DEBUGF(ICMP_DEBUG, ("icmp_input: ICMP type %"S16_F" code %"S16_F" not supported.\n", + (s16_t)type, (s16_t)code)); + ICMP_STATS_INC(icmp.proterr); + ICMP_STATS_INC(icmp.drop); + } + pbuf_free(p); + return; +lenerr: + pbuf_free(p); + ICMP_STATS_INC(icmp.lenerr); + snmp_inc_icmpinerrors(); + return; +#if LWIP_ICMP_ECHO_CHECK_INPUT_PBUF_LEN +memerr: + pbuf_free(p); + ICMP_STATS_INC(icmp.err); + snmp_inc_icmpinerrors(); + return; +#endif /* LWIP_ICMP_ECHO_CHECK_INPUT_PBUF_LEN */ +} + +/** + * Send an icmp 'destination unreachable' packet, called from ip_input() if + * the transport layer protocol is unknown and from udp_input() if the local + * port is not bound. + * + * @param p the input packet for which the 'unreachable' should be sent, + * p->payload pointing to the IP header + * @param t type of the 'unreachable' packet + */ +void +icmp_dest_unreach(struct pbuf *p, enum icmp_dur_type t) +{ + icmp_send_response(p, ICMP_DUR, t); +} + +#if IP_FORWARD || IP_REASSEMBLY +/** + * Send a 'time exceeded' packet, called from ip_forward() if TTL is 0. + * + * @param p the input packet for which the 'time exceeded' should be sent, + * p->payload pointing to the IP header + * @param t type of the 'time exceeded' packet + */ +void +icmp_time_exceeded(struct pbuf *p, enum icmp_te_type t) +{ + icmp_send_response(p, ICMP_TE, t); +} + +#endif /* IP_FORWARD || IP_REASSEMBLY */ + +/** + * Send an icmp packet in response to an incoming packet. + * + * @param p the input packet for which the 'unreachable' should be sent, + * p->payload pointing to the IP header + * @param type Type of the ICMP header + * @param code Code of the ICMP header + */ +static void +icmp_send_response(struct pbuf *p, u8_t type, u8_t code) +{ + struct pbuf *q; + struct ip_hdr *iphdr; + /* we can use the echo header here */ + struct icmp_echo_hdr *icmphdr; + ip_addr_t iphdr_src; + + /* ICMP header + IP header + 8 bytes of data */ + q = pbuf_alloc(PBUF_IP, sizeof(struct icmp_echo_hdr) + IP_HLEN + ICMP_DEST_UNREACH_DATASIZE, + PBUF_RAM); + if (q == NULL) { + LWIP_DEBUGF(ICMP_DEBUG, ("icmp_time_exceeded: failed to allocate pbuf for ICMP packet.\n")); + return; + } + LWIP_ASSERT("check that first pbuf can hold icmp message", + (q->len >= (sizeof(struct icmp_echo_hdr) + IP_HLEN + ICMP_DEST_UNREACH_DATASIZE))); + + iphdr = (struct ip_hdr *)p->payload; + LWIP_DEBUGF(ICMP_DEBUG, ("icmp_time_exceeded from ")); + ip_addr_debug_print(ICMP_DEBUG, &(iphdr->src)); + LWIP_DEBUGF(ICMP_DEBUG, (" to ")); + ip_addr_debug_print(ICMP_DEBUG, &(iphdr->dest)); + LWIP_DEBUGF(ICMP_DEBUG, ("\n")); + + icmphdr = (struct icmp_echo_hdr *)q->payload; + icmphdr->type = type; + icmphdr->code = code; + icmphdr->id = 0; + icmphdr->seqno = 0; + + /* copy fields from original packet */ + SMEMCPY((u8_t *)q->payload + sizeof(struct icmp_echo_hdr), (u8_t *)p->payload, + IP_HLEN + ICMP_DEST_UNREACH_DATASIZE); + + /* calculate checksum */ + icmphdr->chksum = 0; + icmphdr->chksum = inet_chksum(icmphdr, q->len); + ICMP_STATS_INC(icmp.xmit); + /* increase number of messages attempted to send */ + snmp_inc_icmpoutmsgs(); + /* increase number of destination unreachable messages attempted to send */ + snmp_inc_icmpouttimeexcds(); + ip_addr_copy(iphdr_src, iphdr->src); + ip_output(q, NULL, &iphdr_src, ICMP_TTL, 0, IP_PROTO_ICMP); + pbuf_free(q); +} + +#endif /* LWIP_ICMP */ diff --git a/features/unsupported/net/lwip/lwip/core/ipv4/igmp.c b/features/unsupported/net/lwip/lwip/core/ipv4/igmp.c new file mode 100644 index 00000000000..45bb5d95c29 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/core/ipv4/igmp.c @@ -0,0 +1,805 @@ +/** + * @file + * IGMP - Internet Group Management Protocol + * + */ + +/* + * Copyright (c) 2002 CITEL Technologies Ltd. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of CITEL Technologies Ltd nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY CITEL TECHNOLOGIES AND CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL CITEL TECHNOLOGIES OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * This file is a contribution to the lwIP TCP/IP stack. + * The Swedish Institute of Computer Science and Adam Dunkels + * are specifically granted permission to redistribute this + * source code. +*/ + +/*------------------------------------------------------------- +Note 1) +Although the rfc requires V1 AND V2 capability +we will only support v2 since now V1 is very old (August 1989) +V1 can be added if required + +a debug print and statistic have been implemented to +show this up. +------------------------------------------------------------- +------------------------------------------------------------- +Note 2) +A query for a specific group address (as opposed to ALLHOSTS) +has now been implemented as I am unsure if it is required + +a debug print and statistic have been implemented to +show this up. +------------------------------------------------------------- +------------------------------------------------------------- +Note 3) +The router alert rfc 2113 is implemented in outgoing packets +but not checked rigorously incoming +------------------------------------------------------------- +Steve Reynolds +------------------------------------------------------------*/ + +/*----------------------------------------------------------------------------- + * RFC 988 - Host extensions for IP multicasting - V0 + * RFC 1054 - Host extensions for IP multicasting - + * RFC 1112 - Host extensions for IP multicasting - V1 + * RFC 2236 - Internet Group Management Protocol, Version 2 - V2 <- this code is based on this RFC (it's the "de facto" standard) + * RFC 3376 - Internet Group Management Protocol, Version 3 - V3 + * RFC 4604 - Using Internet Group Management Protocol Version 3... - V3+ + * RFC 2113 - IP Router Alert Option - + *----------------------------------------------------------------------------*/ + +/*----------------------------------------------------------------------------- + * Includes + *----------------------------------------------------------------------------*/ + +#include "lwip/opt.h" + +#if LWIP_IGMP /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/igmp.h" +#include "lwip/debug.h" +#include "lwip/def.h" +#include "lwip/mem.h" +#include "lwip/ip.h" +#include "lwip/inet_chksum.h" +#include "lwip/netif.h" +#include "lwip/icmp.h" +#include "lwip/udp.h" +#include "lwip/tcp.h" +#include "lwip/stats.h" + +#include "string.h" + +/* + * IGMP constants + */ +#define IGMP_TTL 1 +#define IGMP_MINLEN 8 +#define ROUTER_ALERT 0x9404U +#define ROUTER_ALERTLEN 4 + +/* + * IGMP message types, including version number. + */ +#define IGMP_MEMB_QUERY 0x11 /* Membership query */ +#define IGMP_V1_MEMB_REPORT 0x12 /* Ver. 1 membership report */ +#define IGMP_V2_MEMB_REPORT 0x16 /* Ver. 2 membership report */ +#define IGMP_LEAVE_GROUP 0x17 /* Leave-group message */ + +/* Group membership states */ +#define IGMP_GROUP_NON_MEMBER 0 +#define IGMP_GROUP_DELAYING_MEMBER 1 +#define IGMP_GROUP_IDLE_MEMBER 2 + +/** + * IGMP packet format. + */ +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct igmp_msg { + PACK_STRUCT_FIELD(u8_t igmp_msgtype); + PACK_STRUCT_FIELD(u8_t igmp_maxresp); + PACK_STRUCT_FIELD(u16_t igmp_checksum); + PACK_STRUCT_FIELD(ip_addr_p_t igmp_group_address); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + + +static struct igmp_group *igmp_lookup_group(struct netif *ifp, ip_addr_t *addr); +static err_t igmp_remove_group(struct igmp_group *group); +static void igmp_timeout( struct igmp_group *group); +static void igmp_start_timer(struct igmp_group *group, u8_t max_time); +static void igmp_delaying_member(struct igmp_group *group, u8_t maxresp); +static err_t igmp_ip_output_if(struct pbuf *p, ip_addr_t *src, ip_addr_t *dest, struct netif *netif); +static void igmp_send(struct igmp_group *group, u8_t type); + + +static struct igmp_group* igmp_group_list; +static ip_addr_t allsystems; +static ip_addr_t allrouters; + + +/** + * Initialize the IGMP module + */ +void +igmp_init(void) +{ + LWIP_DEBUGF(IGMP_DEBUG, ("igmp_init: initializing\n")); + + IP4_ADDR(&allsystems, 224, 0, 0, 1); + IP4_ADDR(&allrouters, 224, 0, 0, 2); +} + +#ifdef LWIP_DEBUG +/** + * Dump global IGMP groups list + */ +void +igmp_dump_group_list() +{ + struct igmp_group *group = igmp_group_list; + + while (group != NULL) { + LWIP_DEBUGF(IGMP_DEBUG, ("igmp_dump_group_list: [%"U32_F"] ", (u32_t)(group->group_state))); + ip_addr_debug_print(IGMP_DEBUG, &group->group_address); + LWIP_DEBUGF(IGMP_DEBUG, (" on if %p\n", group->netif)); + group = group->next; + } + LWIP_DEBUGF(IGMP_DEBUG, ("\n")); +} +#else +#define igmp_dump_group_list() +#endif /* LWIP_DEBUG */ + +/** + * Start IGMP processing on interface + * + * @param netif network interface on which start IGMP processing + */ +err_t +igmp_start(struct netif *netif) +{ + struct igmp_group* group; + + LWIP_DEBUGF(IGMP_DEBUG, ("igmp_start: starting IGMP processing on if %p\n", netif)); + + group = igmp_lookup_group(netif, &allsystems); + + if (group != NULL) { + group->group_state = IGMP_GROUP_IDLE_MEMBER; + group->use++; + + /* Allow the igmp messages at the MAC level */ + if (netif->igmp_mac_filter != NULL) { + LWIP_DEBUGF(IGMP_DEBUG, ("igmp_start: igmp_mac_filter(ADD ")); + ip_addr_debug_print(IGMP_DEBUG, &allsystems); + LWIP_DEBUGF(IGMP_DEBUG, (") on if %p\n", netif)); + netif->igmp_mac_filter(netif, &allsystems, IGMP_ADD_MAC_FILTER); + } + + return ERR_OK; + } + + return ERR_MEM; +} + +/** + * Stop IGMP processing on interface + * + * @param netif network interface on which stop IGMP processing + */ +err_t +igmp_stop(struct netif *netif) +{ + struct igmp_group *group = igmp_group_list; + struct igmp_group *prev = NULL; + struct igmp_group *next; + + /* look for groups joined on this interface further down the list */ + while (group != NULL) { + next = group->next; + /* is it a group joined on this interface? */ + if (group->netif == netif) { + /* is it the first group of the list? */ + if (group == igmp_group_list) { + igmp_group_list = next; + } + /* is there a "previous" group defined? */ + if (prev != NULL) { + prev->next = next; + } + /* disable the group at the MAC level */ + if (netif->igmp_mac_filter != NULL) { + LWIP_DEBUGF(IGMP_DEBUG, ("igmp_stop: igmp_mac_filter(DEL ")); + ip_addr_debug_print(IGMP_DEBUG, &group->group_address); + LWIP_DEBUGF(IGMP_DEBUG, (") on if %p\n", netif)); + netif->igmp_mac_filter(netif, &(group->group_address), IGMP_DEL_MAC_FILTER); + } + /* free group */ + memp_free(MEMP_IGMP_GROUP, group); + } else { + /* change the "previous" */ + prev = group; + } + /* move to "next" */ + group = next; + } + return ERR_OK; +} + +/** + * Report IGMP memberships for this interface + * + * @param netif network interface on which report IGMP memberships + */ +void +igmp_report_groups(struct netif *netif) +{ + struct igmp_group *group = igmp_group_list; + + LWIP_DEBUGF(IGMP_DEBUG, ("igmp_report_groups: sending IGMP reports on if %p\n", netif)); + + while (group != NULL) { + if (group->netif == netif) { + igmp_delaying_member(group, IGMP_JOIN_DELAYING_MEMBER_TMR); + } + group = group->next; + } +} + +/** + * Search for a group in the global igmp_group_list + * + * @param ifp the network interface for which to look + * @param addr the group ip address to search for + * @return a struct igmp_group* if the group has been found, + * NULL if the group wasn't found. + */ +struct igmp_group * +igmp_lookfor_group(struct netif *ifp, ip_addr_t *addr) +{ + struct igmp_group *group = igmp_group_list; + + while (group != NULL) { + if ((group->netif == ifp) && (ip_addr_cmp(&(group->group_address), addr))) { + return group; + } + group = group->next; + } + + /* to be clearer, we return NULL here instead of + * 'group' (which is also NULL at this point). + */ + return NULL; +} + +/** + * Search for a specific igmp group and create a new one if not found- + * + * @param ifp the network interface for which to look + * @param addr the group ip address to search + * @return a struct igmp_group*, + * NULL on memory error. + */ +struct igmp_group * +igmp_lookup_group(struct netif *ifp, ip_addr_t *addr) +{ + struct igmp_group *group = igmp_group_list; + + /* Search if the group already exists */ + group = igmp_lookfor_group(ifp, addr); + if (group != NULL) { + /* Group already exists. */ + return group; + } + + /* Group doesn't exist yet, create a new one */ + group = (struct igmp_group *)memp_malloc(MEMP_IGMP_GROUP); + if (group != NULL) { + group->netif = ifp; + ip_addr_set(&(group->group_address), addr); + group->timer = 0; /* Not running */ + group->group_state = IGMP_GROUP_NON_MEMBER; + group->last_reporter_flag = 0; + group->use = 0; + group->next = igmp_group_list; + + igmp_group_list = group; + } + + LWIP_DEBUGF(IGMP_DEBUG, ("igmp_lookup_group: %sallocated a new group with address ", (group?"":"impossible to "))); + ip_addr_debug_print(IGMP_DEBUG, addr); + LWIP_DEBUGF(IGMP_DEBUG, (" on if %p\n", ifp)); + + return group; +} + +/** + * Remove a group in the global igmp_group_list + * + * @param group the group to remove from the global igmp_group_list + * @return ERR_OK if group was removed from the list, an err_t otherwise + */ +static err_t +igmp_remove_group(struct igmp_group *group) +{ + err_t err = ERR_OK; + + /* Is it the first group? */ + if (igmp_group_list == group) { + igmp_group_list = group->next; + } else { + /* look for group further down the list */ + struct igmp_group *tmpGroup; + for (tmpGroup = igmp_group_list; tmpGroup != NULL; tmpGroup = tmpGroup->next) { + if (tmpGroup->next == group) { + tmpGroup->next = group->next; + break; + } + } + /* Group not found in the global igmp_group_list */ + if (tmpGroup == NULL) + err = ERR_ARG; + } + /* free group */ + memp_free(MEMP_IGMP_GROUP, group); + + return err; +} + +/** + * Called from ip_input() if a new IGMP packet is received. + * + * @param p received igmp packet, p->payload pointing to the ip header + * @param inp network interface on which the packet was received + * @param dest destination ip address of the igmp packet + */ +void +igmp_input(struct pbuf *p, struct netif *inp, ip_addr_t *dest) +{ + struct ip_hdr * iphdr; + struct igmp_msg* igmp; + struct igmp_group* group; + struct igmp_group* groupref; + + IGMP_STATS_INC(igmp.recv); + + /* Note that the length CAN be greater than 8 but only 8 are used - All are included in the checksum */ + iphdr = (struct ip_hdr *)p->payload; + if (pbuf_header(p, -(s16_t)(IPH_HL(iphdr) * 4)) || (p->len < IGMP_MINLEN)) { + pbuf_free(p); + IGMP_STATS_INC(igmp.lenerr); + LWIP_DEBUGF(IGMP_DEBUG, ("igmp_input: length error\n")); + return; + } + + LWIP_DEBUGF(IGMP_DEBUG, ("igmp_input: message from ")); + ip_addr_debug_print(IGMP_DEBUG, &(iphdr->src)); + LWIP_DEBUGF(IGMP_DEBUG, (" to address ")); + ip_addr_debug_print(IGMP_DEBUG, &(iphdr->dest)); + LWIP_DEBUGF(IGMP_DEBUG, (" on if %p\n", inp)); + + /* Now calculate and check the checksum */ + igmp = (struct igmp_msg *)p->payload; + if (inet_chksum(igmp, p->len)) { + pbuf_free(p); + IGMP_STATS_INC(igmp.chkerr); + LWIP_DEBUGF(IGMP_DEBUG, ("igmp_input: checksum error\n")); + return; + } + + /* Packet is ok so find an existing group */ + group = igmp_lookfor_group(inp, dest); /* use the destination IP address of incoming packet */ + + /* If group can be found or create... */ + if (!group) { + pbuf_free(p); + IGMP_STATS_INC(igmp.drop); + LWIP_DEBUGF(IGMP_DEBUG, ("igmp_input: IGMP frame not for us\n")); + return; + } + + /* NOW ACT ON THE INCOMING MESSAGE TYPE... */ + switch (igmp->igmp_msgtype) { + case IGMP_MEMB_QUERY: { + /* IGMP_MEMB_QUERY to the "all systems" address ? */ + if ((ip_addr_cmp(dest, &allsystems)) && ip_addr_isany(&igmp->igmp_group_address)) { + /* THIS IS THE GENERAL QUERY */ + LWIP_DEBUGF(IGMP_DEBUG, ("igmp_input: General IGMP_MEMB_QUERY on \"ALL SYSTEMS\" address (224.0.0.1) [igmp_maxresp=%i]\n", (int)(igmp->igmp_maxresp))); + + if (igmp->igmp_maxresp == 0) { + IGMP_STATS_INC(igmp.rx_v1); + LWIP_DEBUGF(IGMP_DEBUG, ("igmp_input: got an all hosts query with time== 0 - this is V1 and not implemented - treat as v2\n")); + igmp->igmp_maxresp = IGMP_V1_DELAYING_MEMBER_TMR; + } else { + IGMP_STATS_INC(igmp.rx_general); + } + + groupref = igmp_group_list; + while (groupref) { + /* Do not send messages on the all systems group address! */ + if ((groupref->netif == inp) && (!(ip_addr_cmp(&(groupref->group_address), &allsystems)))) { + igmp_delaying_member(groupref, igmp->igmp_maxresp); + } + groupref = groupref->next; + } + } else { + /* IGMP_MEMB_QUERY to a specific group ? */ + if (!ip_addr_isany(&igmp->igmp_group_address)) { + LWIP_DEBUGF(IGMP_DEBUG, ("igmp_input: IGMP_MEMB_QUERY to a specific group ")); + ip_addr_debug_print(IGMP_DEBUG, &igmp->igmp_group_address); + if (ip_addr_cmp(dest, &allsystems)) { + ip_addr_t groupaddr; + LWIP_DEBUGF(IGMP_DEBUG, (" using \"ALL SYSTEMS\" address (224.0.0.1) [igmp_maxresp=%i]\n", (int)(igmp->igmp_maxresp))); + /* we first need to re-look for the group since we used dest last time */ + ip_addr_copy(groupaddr, igmp->igmp_group_address); + group = igmp_lookfor_group(inp, &groupaddr); + } else { + LWIP_DEBUGF(IGMP_DEBUG, (" with the group address as destination [igmp_maxresp=%i]\n", (int)(igmp->igmp_maxresp))); + } + + if (group != NULL) { + IGMP_STATS_INC(igmp.rx_group); + igmp_delaying_member(group, igmp->igmp_maxresp); + } else { + IGMP_STATS_INC(igmp.drop); + } + } else { + IGMP_STATS_INC(igmp.proterr); + } + } + break; + } + case IGMP_V2_MEMB_REPORT: { + LWIP_DEBUGF(IGMP_DEBUG, ("igmp_input: IGMP_V2_MEMB_REPORT\n")); + IGMP_STATS_INC(igmp.rx_report); + if (group->group_state == IGMP_GROUP_DELAYING_MEMBER) { + /* This is on a specific group we have already looked up */ + group->timer = 0; /* stopped */ + group->group_state = IGMP_GROUP_IDLE_MEMBER; + group->last_reporter_flag = 0; + } + break; + } + default: { + LWIP_DEBUGF(IGMP_DEBUG, ("igmp_input: unexpected msg %d in state %d on group %p on if %p\n", + igmp->igmp_msgtype, group->group_state, &group, group->netif)); + IGMP_STATS_INC(igmp.proterr); + break; + } + } + + pbuf_free(p); + return; +} + +/** + * Join a group on one network interface. + * + * @param ifaddr ip address of the network interface which should join a new group + * @param groupaddr the ip address of the group which to join + * @return ERR_OK if group was joined on the netif(s), an err_t otherwise + */ +err_t +igmp_joingroup(ip_addr_t *ifaddr, ip_addr_t *groupaddr) +{ + err_t err = ERR_VAL; /* no matching interface */ + struct igmp_group *group; + struct netif *netif; + + /* make sure it is multicast address */ + LWIP_ERROR("igmp_joingroup: attempt to join non-multicast address", ip_addr_ismulticast(groupaddr), return ERR_VAL;); + LWIP_ERROR("igmp_joingroup: attempt to join allsystems address", (!ip_addr_cmp(groupaddr, &allsystems)), return ERR_VAL;); + + /* loop through netif's */ + netif = netif_list; + while (netif != NULL) { + /* Should we join this interface ? */ + if ((netif->flags & NETIF_FLAG_IGMP) && ((ip_addr_isany(ifaddr) || ip_addr_cmp(&(netif->ip_addr), ifaddr)))) { + /* find group or create a new one if not found */ + group = igmp_lookup_group(netif, groupaddr); + + if (group != NULL) { + /* This should create a new group, check the state to make sure */ + if (group->group_state != IGMP_GROUP_NON_MEMBER) { + LWIP_DEBUGF(IGMP_DEBUG, ("igmp_joingroup: join to group not in state IGMP_GROUP_NON_MEMBER\n")); + } else { + /* OK - it was new group */ + LWIP_DEBUGF(IGMP_DEBUG, ("igmp_joingroup: join to new group: ")); + ip_addr_debug_print(IGMP_DEBUG, groupaddr); + LWIP_DEBUGF(IGMP_DEBUG, ("\n")); + + /* If first use of the group, allow the group at the MAC level */ + if ((group->use==0) && (netif->igmp_mac_filter != NULL)) { + LWIP_DEBUGF(IGMP_DEBUG, ("igmp_joingroup: igmp_mac_filter(ADD ")); + ip_addr_debug_print(IGMP_DEBUG, groupaddr); + LWIP_DEBUGF(IGMP_DEBUG, (") on if %p\n", netif)); + netif->igmp_mac_filter(netif, groupaddr, IGMP_ADD_MAC_FILTER); + } + + IGMP_STATS_INC(igmp.tx_join); + igmp_send(group, IGMP_V2_MEMB_REPORT); + + igmp_start_timer(group, IGMP_JOIN_DELAYING_MEMBER_TMR); + + /* Need to work out where this timer comes from */ + group->group_state = IGMP_GROUP_DELAYING_MEMBER; + } + /* Increment group use */ + group->use++; + /* Join on this interface */ + err = ERR_OK; + } else { + /* Return an error even if some network interfaces are joined */ + /** @todo undo any other netif already joined */ + LWIP_DEBUGF(IGMP_DEBUG, ("igmp_joingroup: Not enought memory to join to group\n")); + return ERR_MEM; + } + } + /* proceed to next network interface */ + netif = netif->next; + } + + return err; +} + +/** + * Leave a group on one network interface. + * + * @param ifaddr ip address of the network interface which should leave a group + * @param groupaddr the ip address of the group which to leave + * @return ERR_OK if group was left on the netif(s), an err_t otherwise + */ +err_t +igmp_leavegroup(ip_addr_t *ifaddr, ip_addr_t *groupaddr) +{ + err_t err = ERR_VAL; /* no matching interface */ + struct igmp_group *group; + struct netif *netif; + + /* make sure it is multicast address */ + LWIP_ERROR("igmp_leavegroup: attempt to leave non-multicast address", ip_addr_ismulticast(groupaddr), return ERR_VAL;); + LWIP_ERROR("igmp_leavegroup: attempt to leave allsystems address", (!ip_addr_cmp(groupaddr, &allsystems)), return ERR_VAL;); + + /* loop through netif's */ + netif = netif_list; + while (netif != NULL) { + /* Should we leave this interface ? */ + if ((netif->flags & NETIF_FLAG_IGMP) && ((ip_addr_isany(ifaddr) || ip_addr_cmp(&(netif->ip_addr), ifaddr)))) { + /* find group */ + group = igmp_lookfor_group(netif, groupaddr); + + if (group != NULL) { + /* Only send a leave if the flag is set according to the state diagram */ + LWIP_DEBUGF(IGMP_DEBUG, ("igmp_leavegroup: Leaving group: ")); + ip_addr_debug_print(IGMP_DEBUG, groupaddr); + LWIP_DEBUGF(IGMP_DEBUG, ("\n")); + + /* If there is no other use of the group */ + if (group->use <= 1) { + /* If we are the last reporter for this group */ + if (group->last_reporter_flag) { + LWIP_DEBUGF(IGMP_DEBUG, ("igmp_leavegroup: sending leaving group\n")); + IGMP_STATS_INC(igmp.tx_leave); + igmp_send(group, IGMP_LEAVE_GROUP); + } + + /* Disable the group at the MAC level */ + if (netif->igmp_mac_filter != NULL) { + LWIP_DEBUGF(IGMP_DEBUG, ("igmp_leavegroup: igmp_mac_filter(DEL ")); + ip_addr_debug_print(IGMP_DEBUG, groupaddr); + LWIP_DEBUGF(IGMP_DEBUG, (") on if %p\n", netif)); + netif->igmp_mac_filter(netif, groupaddr, IGMP_DEL_MAC_FILTER); + } + + LWIP_DEBUGF(IGMP_DEBUG, ("igmp_leavegroup: remove group: ")); + ip_addr_debug_print(IGMP_DEBUG, groupaddr); + LWIP_DEBUGF(IGMP_DEBUG, ("\n")); + + /* Free the group */ + igmp_remove_group(group); + } else { + /* Decrement group use */ + group->use--; + } + /* Leave on this interface */ + err = ERR_OK; + } else { + /* It's not a fatal error on "leavegroup" */ + LWIP_DEBUGF(IGMP_DEBUG, ("igmp_leavegroup: not member of group\n")); + } + } + /* proceed to next network interface */ + netif = netif->next; + } + + return err; +} + +/** + * The igmp timer function (both for NO_SYS=1 and =0) + * Should be called every IGMP_TMR_INTERVAL milliseconds (100 ms is default). + */ +void +igmp_tmr(void) +{ + struct igmp_group *group = igmp_group_list; + + while (group != NULL) { + if (group->timer > 0) { + group->timer--; + if (group->timer == 0) { + igmp_timeout(group); + } + } + group = group->next; + } +} + +/** + * Called if a timeout for one group is reached. + * Sends a report for this group. + * + * @param group an igmp_group for which a timeout is reached + */ +static void +igmp_timeout(struct igmp_group *group) +{ + /* If the state is IGMP_GROUP_DELAYING_MEMBER then we send a report for this group */ + if (group->group_state == IGMP_GROUP_DELAYING_MEMBER) { + LWIP_DEBUGF(IGMP_DEBUG, ("igmp_timeout: report membership for group with address ")); + ip_addr_debug_print(IGMP_DEBUG, &(group->group_address)); + LWIP_DEBUGF(IGMP_DEBUG, (" on if %p\n", group->netif)); + + IGMP_STATS_INC(igmp.tx_report); + igmp_send(group, IGMP_V2_MEMB_REPORT); + } +} + +/** + * Start a timer for an igmp group + * + * @param group the igmp_group for which to start a timer + * @param max_time the time in multiples of IGMP_TMR_INTERVAL (decrease with + * every call to igmp_tmr()) + */ +static void +igmp_start_timer(struct igmp_group *group, u8_t max_time) +{ + /* ensure the input value is > 0 */ + if (max_time == 0) { + max_time = 1; + } + /* ensure the random value is > 0 */ + group->timer = (LWIP_RAND() % (max_time - 1)) + 1; +} + +/** + * Delaying membership report for a group if necessary + * + * @param group the igmp_group for which "delaying" membership report + * @param maxresp query delay + */ +static void +igmp_delaying_member(struct igmp_group *group, u8_t maxresp) +{ + if ((group->group_state == IGMP_GROUP_IDLE_MEMBER) || + ((group->group_state == IGMP_GROUP_DELAYING_MEMBER) && + ((group->timer == 0) || (maxresp < group->timer)))) { + igmp_start_timer(group, maxresp); + group->group_state = IGMP_GROUP_DELAYING_MEMBER; + } +} + + +/** + * Sends an IP packet on a network interface. This function constructs the IP header + * and calculates the IP header checksum. If the source IP address is NULL, + * the IP address of the outgoing network interface is filled in as source address. + * + * @param p the packet to send (p->payload points to the data, e.g. next + protocol header; if dest == IP_HDRINCL, p already includes an IP + header and p->payload points to that IP header) + * @param src the source IP address to send from (if src == IP_ADDR_ANY, the + * IP address of the netif used to send is used as source address) + * @param dest the destination IP address to send the packet to + * @param ttl the TTL value to be set in the IP header + * @param proto the PROTOCOL to be set in the IP header + * @param netif the netif on which to send this packet + * @return ERR_OK if the packet was sent OK + * ERR_BUF if p doesn't have enough space for IP/LINK headers + * returns errors returned by netif->output + */ +static err_t +igmp_ip_output_if(struct pbuf *p, ip_addr_t *src, ip_addr_t *dest, struct netif *netif) +{ + /* This is the "router alert" option */ + u16_t ra[2]; + ra[0] = PP_HTONS(ROUTER_ALERT); + ra[1] = 0x0000; /* Router shall examine packet */ + IGMP_STATS_INC(igmp.xmit); + return ip_output_if_opt(p, src, dest, IGMP_TTL, 0, IP_PROTO_IGMP, netif, ra, ROUTER_ALERTLEN); +} + +/** + * Send an igmp packet to a specific group. + * + * @param group the group to which to send the packet + * @param type the type of igmp packet to send + */ +static void +igmp_send(struct igmp_group *group, u8_t type) +{ + struct pbuf* p = NULL; + struct igmp_msg* igmp = NULL; + ip_addr_t src = *IP_ADDR_ANY; + ip_addr_t* dest = NULL; + + /* IP header + "router alert" option + IGMP header */ + p = pbuf_alloc(PBUF_TRANSPORT, IGMP_MINLEN, PBUF_RAM); + + if (p) { + igmp = (struct igmp_msg *)p->payload; + LWIP_ASSERT("igmp_send: check that first pbuf can hold struct igmp_msg", + (p->len >= sizeof(struct igmp_msg))); + ip_addr_copy(src, group->netif->ip_addr); + + if (type == IGMP_V2_MEMB_REPORT) { + dest = &(group->group_address); + ip_addr_copy(igmp->igmp_group_address, group->group_address); + group->last_reporter_flag = 1; /* Remember we were the last to report */ + } else { + if (type == IGMP_LEAVE_GROUP) { + dest = &allrouters; + ip_addr_copy(igmp->igmp_group_address, group->group_address); + } + } + + if ((type == IGMP_V2_MEMB_REPORT) || (type == IGMP_LEAVE_GROUP)) { + igmp->igmp_msgtype = type; + igmp->igmp_maxresp = 0; + igmp->igmp_checksum = 0; + igmp->igmp_checksum = inet_chksum(igmp, IGMP_MINLEN); + + igmp_ip_output_if(p, &src, dest, group->netif); + } + + pbuf_free(p); + } else { + LWIP_DEBUGF(IGMP_DEBUG, ("igmp_send: not enough memory for igmp_send\n")); + IGMP_STATS_INC(igmp.memerr); + } +} + +#endif /* LWIP_IGMP */ diff --git a/features/FEATURE_LWIP/lwip-interface/lwip-sys/lwip_tcp_isn.h b/features/unsupported/net/lwip/lwip/core/ipv4/inet.c similarity index 73% rename from features/FEATURE_LWIP/lwip-interface/lwip-sys/lwip_tcp_isn.h rename to features/unsupported/net/lwip/lwip/core/ipv4/inet.c index ebaeca24729..e283a576604 100644 --- a/features/FEATURE_LWIP/lwip-interface/lwip-sys/lwip_tcp_isn.h +++ b/features/unsupported/net/lwip/lwip/core/ipv4/inet.c @@ -1,5 +1,11 @@ +/** + * @file + * Functions common to all TCP/IPv4 modules, such as the byte order functions. + * + */ + /* - * Copyright (c) 2016 The MINIX 3 Project. + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, @@ -24,25 +30,13 @@ * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * - * Author: David van Moolenbroek + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * */ -#ifndef LWIP_HDR_CONTRIB_ADDONS_TCP_ISN_H -#define LWIP_HDR_CONTRIB_ADDONS_TCP_ISN_H - #include "lwip/opt.h" -#include "lwip/ip_addr.h" - -#ifdef __cplusplus -extern "C" { -#endif - -void lwip_init_tcp_isn(u32_t boot_time, const u8_t *secret_16_bytes); -u32_t lwip_hook_tcp_isn(const ip_addr_t *local_ip, u16_t local_port, - const ip_addr_t *remote_ip, u16_t remote_port); -#ifdef __cplusplus -} -#endif +#include "lwip/inet.h" -#endif /* LWIP_HDR_CONTRIB_ADDONS_TCP_ISN_H */ diff --git a/features/unsupported/net/lwip/lwip/core/ipv4/inet_chksum.c b/features/unsupported/net/lwip/lwip/core/ipv4/inet_chksum.c new file mode 100644 index 00000000000..960252f64f1 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/core/ipv4/inet_chksum.c @@ -0,0 +1,450 @@ +/** + * @file + * Incluse internet checksum functions. + * + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ + +#include "lwip/opt.h" + +#include "lwip/inet_chksum.h" +#include "lwip/def.h" + +#include +#include + +/* These are some reference implementations of the checksum algorithm, with the + * aim of being simple, correct and fully portable. Checksumming is the + * first thing you would want to optimize for your platform. If you create + * your own version, link it in and in your cc.h put: + * + * #define LWIP_CHKSUM + * + * Or you can select from the implementations below by defining + * LWIP_CHKSUM_ALGORITHM to 1, 2 or 3. + */ + +#ifndef LWIP_CHKSUM +# define LWIP_CHKSUM lwip_standard_chksum +# ifndef LWIP_CHKSUM_ALGORITHM +# define LWIP_CHKSUM_ALGORITHM 2 +# endif +#endif +/* If none set: */ +#ifndef LWIP_CHKSUM_ALGORITHM +# define LWIP_CHKSUM_ALGORITHM 0 +#endif + +#if (LWIP_CHKSUM_ALGORITHM == 1) /* Version #1 */ +/** + * lwip checksum + * + * @param dataptr points to start of data to be summed at any boundary + * @param len length of data to be summed + * @return host order (!) lwip checksum (non-inverted Internet sum) + * + * @note accumulator size limits summable length to 64k + * @note host endianess is irrelevant (p3 RFC1071) + */ +static u16_t +lwip_standard_chksum(void *dataptr, u16_t len) +{ + u32_t acc; + u16_t src; + u8_t *octetptr; + + acc = 0; + /* dataptr may be at odd or even addresses */ + octetptr = (u8_t*)dataptr; + while (len > 1) { + /* declare first octet as most significant + thus assume network order, ignoring host order */ + src = (*octetptr) << 8; + octetptr++; + /* declare second octet as least significant */ + src |= (*octetptr); + octetptr++; + acc += src; + len -= 2; + } + if (len > 0) { + /* accumulate remaining octet */ + src = (*octetptr) << 8; + acc += src; + } + /* add deferred carry bits */ + acc = (acc >> 16) + (acc & 0x0000ffffUL); + if ((acc & 0xffff0000UL) != 0) { + acc = (acc >> 16) + (acc & 0x0000ffffUL); + } + /* This maybe a little confusing: reorder sum using htons() + instead of ntohs() since it has a little less call overhead. + The caller must invert bits for Internet sum ! */ + return htons((u16_t)acc); +} +#endif + +#if (LWIP_CHKSUM_ALGORITHM == 2) /* Alternative version #2 */ +/* + * Curt McDowell + * Broadcom Corp. + * csm@broadcom.com + * + * IP checksum two bytes at a time with support for + * unaligned buffer. + * Works for len up to and including 0x20000. + * by Curt McDowell, Broadcom Corp. 12/08/2005 + * + * @param dataptr points to start of data to be summed at any boundary + * @param len length of data to be summed + * @return host order (!) lwip checksum (non-inverted Internet sum) + */ + +static u16_t +lwip_standard_chksum(void *dataptr, int len) +{ + u8_t *pb = (u8_t *)dataptr; + u16_t *ps, t = 0; + u32_t sum = 0; + int odd = ((mem_ptr_t)pb & 1); + + /* Get aligned to u16_t */ + if (odd && len > 0) { + ((u8_t *)&t)[1] = *pb++; + len--; + } + + /* Add the bulk of the data */ + ps = (u16_t *)(void *)pb; + while (len > 1) { + sum += *ps++; + len -= 2; + } + + /* Consume left-over byte, if any */ + if (len > 0) { + ((u8_t *)&t)[0] = *(u8_t *)ps; + } + + /* Add end bytes */ + sum += t; + + /* Fold 32-bit sum to 16 bits + calling this twice is propably faster than if statements... */ + sum = FOLD_U32T(sum); + sum = FOLD_U32T(sum); + + /* Swap if alignment was odd */ + if (odd) { + sum = SWAP_BYTES_IN_WORD(sum); + } + + return (u16_t)sum; +} +#endif + +#if (LWIP_CHKSUM_ALGORITHM == 3) /* Alternative version #3 */ +/** + * An optimized checksum routine. Basically, it uses loop-unrolling on + * the checksum loop, treating the head and tail bytes specially, whereas + * the inner loop acts on 8 bytes at a time. + * + * @arg start of buffer to be checksummed. May be an odd byte address. + * @len number of bytes in the buffer to be checksummed. + * @return host order (!) lwip checksum (non-inverted Internet sum) + * + * by Curt McDowell, Broadcom Corp. December 8th, 2005 + */ + +static u16_t +lwip_standard_chksum(void *dataptr, int len) +{ + u8_t *pb = (u8_t *)dataptr; + u16_t *ps, t = 0; + u32_t *pl; + u32_t sum = 0, tmp; + /* starts at odd byte address? */ + int odd = ((mem_ptr_t)pb & 1); + + if (odd && len > 0) { + ((u8_t *)&t)[1] = *pb++; + len--; + } + + ps = (u16_t *)pb; + + if (((mem_ptr_t)ps & 3) && len > 1) { + sum += *ps++; + len -= 2; + } + + pl = (u32_t *)ps; + + while (len > 7) { + tmp = sum + *pl++; /* ping */ + if (tmp < sum) { + tmp++; /* add back carry */ + } + + sum = tmp + *pl++; /* pong */ + if (sum < tmp) { + sum++; /* add back carry */ + } + + len -= 8; + } + + /* make room in upper bits */ + sum = FOLD_U32T(sum); + + ps = (u16_t *)pl; + + /* 16-bit aligned word remaining? */ + while (len > 1) { + sum += *ps++; + len -= 2; + } + + /* dangling tail byte remaining? */ + if (len > 0) { /* include odd byte */ + ((u8_t *)&t)[0] = *(u8_t *)ps; + } + + sum += t; /* add end bytes */ + + /* Fold 32-bit sum to 16 bits + calling this twice is propably faster than if statements... */ + sum = FOLD_U32T(sum); + sum = FOLD_U32T(sum); + + if (odd) { + sum = SWAP_BYTES_IN_WORD(sum); + } + + return (u16_t)sum; +} +#endif + +/* inet_chksum_pseudo: + * + * Calculates the pseudo Internet checksum used by TCP and UDP for a pbuf chain. + * IP addresses are expected to be in network byte order. + * + * @param p chain of pbufs over that a checksum should be calculated (ip data part) + * @param src source ip address (used for checksum of pseudo header) + * @param dst destination ip address (used for checksum of pseudo header) + * @param proto ip protocol (used for checksum of pseudo header) + * @param proto_len length of the ip data part (used for checksum of pseudo header) + * @return checksum (as u16_t) to be saved directly in the protocol header + */ +u16_t +inet_chksum_pseudo(struct pbuf *p, + ip_addr_t *src, ip_addr_t *dest, + u8_t proto, u16_t proto_len) +{ + u32_t acc; + u32_t addr; + struct pbuf *q; + u8_t swapped; + + acc = 0; + swapped = 0; + /* iterate through all pbuf in chain */ + for(q = p; q != NULL; q = q->next) { + LWIP_DEBUGF(INET_DEBUG, ("inet_chksum_pseudo(): checksumming pbuf %p (has next %p) \n", + (void *)q, (void *)q->next)); + acc += LWIP_CHKSUM(q->payload, q->len); + /*LWIP_DEBUGF(INET_DEBUG, ("inet_chksum_pseudo(): unwrapped lwip_chksum()=%"X32_F" \n", acc));*/ + /* just executing this next line is probably faster that the if statement needed + to check whether we really need to execute it, and does no harm */ + acc = FOLD_U32T(acc); + if (q->len % 2 != 0) { + swapped = 1 - swapped; + acc = SWAP_BYTES_IN_WORD(acc); + } + /*LWIP_DEBUGF(INET_DEBUG, ("inet_chksum_pseudo(): wrapped lwip_chksum()=%"X32_F" \n", acc));*/ + } + + if (swapped) { + acc = SWAP_BYTES_IN_WORD(acc); + } + addr = ip4_addr_get_u32(src); + acc += (addr & 0xffffUL); + acc += ((addr >> 16) & 0xffffUL); + addr = ip4_addr_get_u32(dest); + acc += (addr & 0xffffUL); + acc += ((addr >> 16) & 0xffffUL); + acc += (u32_t)htons((u16_t)proto); + acc += (u32_t)htons(proto_len); + + /* Fold 32-bit sum to 16 bits + calling this twice is propably faster than if statements... */ + acc = FOLD_U32T(acc); + acc = FOLD_U32T(acc); + LWIP_DEBUGF(INET_DEBUG, ("inet_chksum_pseudo(): pbuf chain lwip_chksum()=%"X32_F"\n", acc)); + return (u16_t)~(acc & 0xffffUL); +} + +/* inet_chksum_pseudo: + * + * Calculates the pseudo Internet checksum used by TCP and UDP for a pbuf chain. + * IP addresses are expected to be in network byte order. + * + * @param p chain of pbufs over that a checksum should be calculated (ip data part) + * @param src source ip address (used for checksum of pseudo header) + * @param dst destination ip address (used for checksum of pseudo header) + * @param proto ip protocol (used for checksum of pseudo header) + * @param proto_len length of the ip data part (used for checksum of pseudo header) + * @return checksum (as u16_t) to be saved directly in the protocol header + */ +u16_t +inet_chksum_pseudo_partial(struct pbuf *p, + ip_addr_t *src, ip_addr_t *dest, + u8_t proto, u16_t proto_len, u16_t chksum_len) +{ + u32_t acc; + u32_t addr; + struct pbuf *q; + u8_t swapped; + u16_t chklen; + + acc = 0; + swapped = 0; + /* iterate through all pbuf in chain */ + for(q = p; (q != NULL) && (chksum_len > 0); q = q->next) { + LWIP_DEBUGF(INET_DEBUG, ("inet_chksum_pseudo(): checksumming pbuf %p (has next %p) \n", + (void *)q, (void *)q->next)); + chklen = q->len; + if (chklen > chksum_len) { + chklen = chksum_len; + } + acc += LWIP_CHKSUM(q->payload, chklen); + chksum_len -= chklen; + LWIP_ASSERT("delete me", chksum_len < 0x7fff); + /*LWIP_DEBUGF(INET_DEBUG, ("inet_chksum_pseudo(): unwrapped lwip_chksum()=%"X32_F" \n", acc));*/ + /* fold the upper bit down */ + acc = FOLD_U32T(acc); + if (q->len % 2 != 0) { + swapped = 1 - swapped; + acc = SWAP_BYTES_IN_WORD(acc); + } + /*LWIP_DEBUGF(INET_DEBUG, ("inet_chksum_pseudo(): wrapped lwip_chksum()=%"X32_F" \n", acc));*/ + } + + if (swapped) { + acc = SWAP_BYTES_IN_WORD(acc); + } + addr = ip4_addr_get_u32(src); + acc += (addr & 0xffffUL); + acc += ((addr >> 16) & 0xffffUL); + addr = ip4_addr_get_u32(dest); + acc += (addr & 0xffffUL); + acc += ((addr >> 16) & 0xffffUL); + acc += (u32_t)htons((u16_t)proto); + acc += (u32_t)htons(proto_len); + + /* Fold 32-bit sum to 16 bits + calling this twice is propably faster than if statements... */ + acc = FOLD_U32T(acc); + acc = FOLD_U32T(acc); + LWIP_DEBUGF(INET_DEBUG, ("inet_chksum_pseudo(): pbuf chain lwip_chksum()=%"X32_F"\n", acc)); + return (u16_t)~(acc & 0xffffUL); +} + +/* inet_chksum: + * + * Calculates the Internet checksum over a portion of memory. Used primarily for IP + * and ICMP. + * + * @param dataptr start of the buffer to calculate the checksum (no alignment needed) + * @param len length of the buffer to calculate the checksum + * @return checksum (as u16_t) to be saved directly in the protocol header + */ + +u16_t +inet_chksum(void *dataptr, u16_t len) +{ + return ~LWIP_CHKSUM(dataptr, len); +} + +/** + * Calculate a checksum over a chain of pbufs (without pseudo-header, much like + * inet_chksum only pbufs are used). + * + * @param p pbuf chain over that the checksum should be calculated + * @return checksum (as u16_t) to be saved directly in the protocol header + */ +u16_t +inet_chksum_pbuf(struct pbuf *p) +{ + u32_t acc; + struct pbuf *q; + u8_t swapped; + + acc = 0; + swapped = 0; + for(q = p; q != NULL; q = q->next) { + acc += LWIP_CHKSUM(q->payload, q->len); + acc = FOLD_U32T(acc); + if (q->len % 2 != 0) { + swapped = 1 - swapped; + acc = SWAP_BYTES_IN_WORD(acc); + } + } + + if (swapped) { + acc = SWAP_BYTES_IN_WORD(acc); + } + return (u16_t)~(acc & 0xffffUL); +} + +/* These are some implementations for LWIP_CHKSUM_COPY, which copies data + * like MEMCPY but generates a checksum at the same time. Since this is a + * performance-sensitive function, you might want to create your own version + * in assembly targeted at your hardware by defining it in lwipopts.h: + * #define LWIP_CHKSUM_COPY(dst, src, len) your_chksum_copy(dst, src, len) + */ + +#if (LWIP_CHKSUM_COPY_ALGORITHM == 1) /* Version #1 */ +/** Safe but slow: first call MEMCPY, then call LWIP_CHKSUM. + * For architectures with big caches, data might still be in cache when + * generating the checksum after copying. + */ +u16_t +lwip_chksum_copy(void *dst, const void *src, u16_t len) +{ + MEMCPY(dst, src, len); + return LWIP_CHKSUM(dst, len); +} +#endif /* (LWIP_CHKSUM_COPY_ALGORITHM == 1) */ diff --git a/features/unsupported/net/lwip/lwip/core/ipv4/ip.c b/features/unsupported/net/lwip/lwip/core/ipv4/ip.c new file mode 100644 index 00000000000..56843273d1d --- /dev/null +++ b/features/unsupported/net/lwip/lwip/core/ipv4/ip.c @@ -0,0 +1,857 @@ +/** + * @file + * This is the IPv4 layer implementation for incoming and outgoing IP traffic. + * + * @see ip_frag.c + * + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ + +#include "lwip/opt.h" +#include "lwip/ip.h" +#include "lwip/def.h" +#include "lwip/mem.h" +#include "lwip/ip_frag.h" +#include "lwip/inet_chksum.h" +#include "lwip/netif.h" +#include "lwip/icmp.h" +#include "lwip/igmp.h" +#include "lwip/raw.h" +#include "lwip/udp.h" +#include "lwip/tcp_impl.h" +#include "lwip/snmp.h" +#include "lwip/dhcp.h" +#include "lwip/autoip.h" +#include "lwip/stats.h" +#include "arch/perf.h" + +#include + +/** Set this to 0 in the rare case of wanting to call an extra function to + * generate the IP checksum (in contrast to calculating it on-the-fly). */ +#ifndef LWIP_INLINE_IP_CHKSUM +#define LWIP_INLINE_IP_CHKSUM 1 +#endif +#if LWIP_INLINE_IP_CHKSUM && CHECKSUM_GEN_IP +#define CHECKSUM_GEN_IP_INLINE 1 +#else +#define CHECKSUM_GEN_IP_INLINE 0 +#endif + +#if LWIP_DHCP || defined(LWIP_IP_ACCEPT_UDP_PORT) +#define IP_ACCEPT_LINK_LAYER_ADDRESSING 1 + +/** Some defines for DHCP to let link-layer-addressed packets through while the + * netif is down. + * To use this in your own application/protocol, define LWIP_IP_ACCEPT_UDP_PORT + * to return 1 if the port is accepted and 0 if the port is not accepted. + */ +#if LWIP_DHCP && defined(LWIP_IP_ACCEPT_UDP_PORT) +/* accept DHCP client port and custom port */ +#define IP_ACCEPT_LINK_LAYER_ADDRESSED_PORT(port) (((port) == PP_NTOHS(DHCP_CLIENT_PORT)) \ + || (LWIP_IP_ACCEPT_UDP_PORT(port))) +#elif defined(LWIP_IP_ACCEPT_UDP_PORT) /* LWIP_DHCP && defined(LWIP_IP_ACCEPT_UDP_PORT) */ +/* accept custom port only */ +#define IP_ACCEPT_LINK_LAYER_ADDRESSED_PORT(port) (LWIP_IP_ACCEPT_UDP_PORT(dst_port)) +#else /* LWIP_DHCP && defined(LWIP_IP_ACCEPT_UDP_PORT) */ +/* accept DHCP client port only */ +#define IP_ACCEPT_LINK_LAYER_ADDRESSED_PORT(port) ((port) == PP_NTOHS(DHCP_CLIENT_PORT)) +#endif /* LWIP_DHCP && defined(LWIP_IP_ACCEPT_UDP_PORT) */ + +#else /* LWIP_DHCP */ +#define IP_ACCEPT_LINK_LAYER_ADDRESSING 0 +#endif /* LWIP_DHCP */ + +/** + * The interface that provided the packet for the current callback + * invocation. + */ +struct netif *current_netif; + +/** + * Header of the input packet currently being processed. + */ +const struct ip_hdr *current_header; +/** Source IP address of current_header */ +ip_addr_t current_iphdr_src; +/** Destination IP address of current_header */ +ip_addr_t current_iphdr_dest; + +/** The IP header ID of the next outgoing IP packet */ +static u16_t ip_id; + +/** + * Finds the appropriate network interface for a given IP address. It + * searches the list of network interfaces linearly. A match is found + * if the masked IP address of the network interface equals the masked + * IP address given to the function. + * + * @param dest the destination IP address for which to find the route + * @return the netif on which to send to reach dest + */ +struct netif * +ip_route(ip_addr_t *dest) +{ + struct netif *netif; + + /* iterate through netifs */ + for(netif = netif_list; netif != NULL; netif = netif->next) { + /* network mask matches? */ + if (netif_is_up(netif)) { + if (ip_addr_netcmp(dest, &(netif->ip_addr), &(netif->netmask))) { + /* return netif on which to forward IP packet */ + return netif; + } + } + } + if ((netif_default == NULL) || (!netif_is_up(netif_default))) { + LWIP_DEBUGF(IP_DEBUG | LWIP_DBG_LEVEL_SERIOUS, ("ip_route: No route to %"U16_F".%"U16_F".%"U16_F".%"U16_F"\n", + ip4_addr1_16(dest), ip4_addr2_16(dest), ip4_addr3_16(dest), ip4_addr4_16(dest))); + IP_STATS_INC(ip.rterr); + snmp_inc_ipoutnoroutes(); + return NULL; + } + /* no matching netif found, use default netif */ + return netif_default; +} + +#if IP_FORWARD +/** + * Forwards an IP packet. It finds an appropriate route for the + * packet, decrements the TTL value of the packet, adjusts the + * checksum and outputs the packet on the appropriate interface. + * + * @param p the packet to forward (p->payload points to IP header) + * @param iphdr the IP header of the input packet + * @param inp the netif on which this packet was received + */ +static void +ip_forward(struct pbuf *p, struct ip_hdr *iphdr, struct netif *inp) +{ + struct netif *netif; + + PERF_START; + + /* RFC3927 2.7: do not forward link-local addresses */ + if (ip_addr_islinklocal(¤t_iphdr_dest)) { + LWIP_DEBUGF(IP_DEBUG, ("ip_forward: not forwarding LLA %"U16_F".%"U16_F".%"U16_F".%"U16_F"\n", + ip4_addr1_16(¤t_iphdr_dest), ip4_addr2_16(¤t_iphdr_dest), + ip4_addr3_16(¤t_iphdr_dest), ip4_addr4_16(¤t_iphdr_dest))); + goto return_noroute; + } + + /* Find network interface where to forward this IP packet to. */ + netif = ip_route(¤t_iphdr_dest); + if (netif == NULL) { + LWIP_DEBUGF(IP_DEBUG, ("ip_forward: no forwarding route for %"U16_F".%"U16_F".%"U16_F".%"U16_F" found\n", + ip4_addr1_16(¤t_iphdr_dest), ip4_addr2_16(¤t_iphdr_dest), + ip4_addr3_16(¤t_iphdr_dest), ip4_addr4_16(¤t_iphdr_dest))); + goto return_noroute; + } + /* Do not forward packets onto the same network interface on which + * they arrived. */ + if (netif == inp) { + LWIP_DEBUGF(IP_DEBUG, ("ip_forward: not bouncing packets back on incoming interface.\n")); + goto return_noroute; + } + + /* decrement TTL */ + IPH_TTL_SET(iphdr, IPH_TTL(iphdr) - 1); + /* send ICMP if TTL == 0 */ + if (IPH_TTL(iphdr) == 0) { + snmp_inc_ipinhdrerrors(); +#if LWIP_ICMP + /* Don't send ICMP messages in response to ICMP messages */ + if (IPH_PROTO(iphdr) != IP_PROTO_ICMP) { + icmp_time_exceeded(p, ICMP_TE_TTL); + } +#endif /* LWIP_ICMP */ + return; + } + + /* Incrementally update the IP checksum. */ + if (IPH_CHKSUM(iphdr) >= PP_HTONS(0xffffU - 0x100)) { + IPH_CHKSUM_SET(iphdr, IPH_CHKSUM(iphdr) + PP_HTONS(0x100) + 1); + } else { + IPH_CHKSUM_SET(iphdr, IPH_CHKSUM(iphdr) + PP_HTONS(0x100)); + } + + LWIP_DEBUGF(IP_DEBUG, ("ip_forward: forwarding packet to %"U16_F".%"U16_F".%"U16_F".%"U16_F"\n", + ip4_addr1_16(¤t_iphdr_dest), ip4_addr2_16(¤t_iphdr_dest), + ip4_addr3_16(¤t_iphdr_dest), ip4_addr4_16(¤t_iphdr_dest))); + + IP_STATS_INC(ip.fw); + IP_STATS_INC(ip.xmit); + snmp_inc_ipforwdatagrams(); + + PERF_STOP("ip_forward"); + /* transmit pbuf on chosen interface */ + netif->output(netif, p, ¤t_iphdr_dest); + return; +return_noroute: + snmp_inc_ipoutnoroutes(); +} +#endif /* IP_FORWARD */ + +/** + * This function is called by the network interface device driver when + * an IP packet is received. The function does the basic checks of the + * IP header such as packet size being at least larger than the header + * size etc. If the packet was not destined for us, the packet is + * forwarded (using ip_forward). The IP checksum is always checked. + * + * Finally, the packet is sent to the upper layer protocol input function. + * + * @param p the received IP packet (p->payload points to IP header) + * @param inp the netif on which this packet was received + * @return ERR_OK if the packet was processed (could return ERR_* if it wasn't + * processed, but currently always returns ERR_OK) + */ +err_t +ip_input(struct pbuf *p, struct netif *inp) +{ + struct ip_hdr *iphdr; + struct netif *netif; + u16_t iphdr_hlen; + u16_t iphdr_len; +#if IP_ACCEPT_LINK_LAYER_ADDRESSING + int check_ip_src=1; +#endif /* IP_ACCEPT_LINK_LAYER_ADDRESSING */ + + IP_STATS_INC(ip.recv); + snmp_inc_ipinreceives(); + + /* identify the IP header */ + iphdr = (struct ip_hdr *)p->payload; + if (IPH_V(iphdr) != 4) { + LWIP_DEBUGF(IP_DEBUG | LWIP_DBG_LEVEL_WARNING, ("IP packet dropped due to bad version number %"U16_F"\n", IPH_V(iphdr))); + ip_debug_print(p); + pbuf_free(p); + IP_STATS_INC(ip.err); + IP_STATS_INC(ip.drop); + snmp_inc_ipinhdrerrors(); + return ERR_OK; + } + + /* obtain IP header length in number of 32-bit words */ + iphdr_hlen = IPH_HL(iphdr); + /* calculate IP header length in bytes */ + iphdr_hlen *= 4; + /* obtain ip length in bytes */ + iphdr_len = ntohs(IPH_LEN(iphdr)); + + /* header length exceeds first pbuf length, or ip length exceeds total pbuf length? */ + if ((iphdr_hlen > p->len) || (iphdr_len > p->tot_len)) { + if (iphdr_hlen > p->len) { + LWIP_DEBUGF(IP_DEBUG | LWIP_DBG_LEVEL_SERIOUS, + ("IP header (len %"U16_F") does not fit in first pbuf (len %"U16_F"), IP packet dropped.\n", + iphdr_hlen, p->len)); + } + if (iphdr_len > p->tot_len) { + LWIP_DEBUGF(IP_DEBUG | LWIP_DBG_LEVEL_SERIOUS, + ("IP (len %"U16_F") is longer than pbuf (len %"U16_F"), IP packet dropped.\n", + iphdr_len, p->tot_len)); + } + /* free (drop) packet pbufs */ + pbuf_free(p); + IP_STATS_INC(ip.lenerr); + IP_STATS_INC(ip.drop); + snmp_inc_ipindiscards(); + return ERR_OK; + } + + /* verify checksum */ +#if CHECKSUM_CHECK_IP + if (inet_chksum(iphdr, iphdr_hlen) != 0) { + + LWIP_DEBUGF(IP_DEBUG | LWIP_DBG_LEVEL_SERIOUS, + ("Checksum (0x%"X16_F") failed, IP packet dropped.\n", inet_chksum(iphdr, iphdr_hlen))); + ip_debug_print(p); + pbuf_free(p); + IP_STATS_INC(ip.chkerr); + IP_STATS_INC(ip.drop); + snmp_inc_ipinhdrerrors(); + return ERR_OK; + } +#endif + + /* Trim pbuf. This should have been done at the netif layer, + * but we'll do it anyway just to be sure that its done. */ + pbuf_realloc(p, iphdr_len); + + /* copy IP addresses to aligned ip_addr_t */ + ip_addr_copy(current_iphdr_dest, iphdr->dest); + ip_addr_copy(current_iphdr_src, iphdr->src); + + /* match packet against an interface, i.e. is this packet for us? */ +#if LWIP_IGMP + if (ip_addr_ismulticast(¤t_iphdr_dest)) { + if ((inp->flags & NETIF_FLAG_IGMP) && (igmp_lookfor_group(inp, ¤t_iphdr_dest))) { + netif = inp; + } else { + netif = NULL; + } + } else +#endif /* LWIP_IGMP */ + { + /* start trying with inp. if that's not acceptable, start walking the + list of configured netifs. + 'first' is used as a boolean to mark whether we started walking the list */ + int first = 1; + netif = inp; + do { + LWIP_DEBUGF(IP_DEBUG, ("ip_input: iphdr->dest 0x%"X32_F" netif->ip_addr 0x%"X32_F" (0x%"X32_F", 0x%"X32_F", 0x%"X32_F")\n", + ip4_addr_get_u32(&iphdr->dest), ip4_addr_get_u32(&netif->ip_addr), + ip4_addr_get_u32(&iphdr->dest) & ip4_addr_get_u32(&netif->netmask), + ip4_addr_get_u32(&netif->ip_addr) & ip4_addr_get_u32(&netif->netmask), + ip4_addr_get_u32(&iphdr->dest) & ~ip4_addr_get_u32(&netif->netmask))); + + /* interface is up and configured? */ + if ((netif_is_up(netif)) && (!ip_addr_isany(&(netif->ip_addr)))) { + /* unicast to this interface address? */ + if (ip_addr_cmp(¤t_iphdr_dest, &(netif->ip_addr)) || + /* or broadcast on this interface network address? */ + ip_addr_isbroadcast(¤t_iphdr_dest, netif)) { + LWIP_DEBUGF(IP_DEBUG, ("ip_input: packet accepted on interface %c%c\n", + netif->name[0], netif->name[1])); + /* break out of for loop */ + break; + } +#if LWIP_AUTOIP + /* connections to link-local addresses must persist after changing + the netif's address (RFC3927 ch. 1.9) */ + if ((netif->autoip != NULL) && + ip_addr_cmp(¤t_iphdr_dest, &(netif->autoip->llipaddr))) { + LWIP_DEBUGF(IP_DEBUG, ("ip_input: LLA packet accepted on interface %c%c\n", + netif->name[0], netif->name[1])); + /* break out of for loop */ + break; + } +#endif /* LWIP_AUTOIP */ + } + if (first) { + first = 0; + netif = netif_list; + } else { + netif = netif->next; + } + if (netif == inp) { + netif = netif->next; + } + } while(netif != NULL); + } + +#if IP_ACCEPT_LINK_LAYER_ADDRESSING + /* Pass DHCP messages regardless of destination address. DHCP traffic is addressed + * using link layer addressing (such as Ethernet MAC) so we must not filter on IP. + * According to RFC 1542 section 3.1.1, referred by RFC 2131). + * + * If you want to accept private broadcast communication while a netif is down, + * define LWIP_IP_ACCEPT_UDP_PORT(dst_port), e.g.: + * + * #define LWIP_IP_ACCEPT_UDP_PORT(dst_port) ((dst_port) == PP_NTOHS(12345)) + */ + if (netif == NULL) { + /* remote port is DHCP server? */ + if (IPH_PROTO(iphdr) == IP_PROTO_UDP) { + struct udp_hdr *udphdr = (struct udp_hdr *)((u8_t *)iphdr + iphdr_hlen); + LWIP_DEBUGF(IP_DEBUG | LWIP_DBG_TRACE, ("ip_input: UDP packet to DHCP client port %"U16_F"\n", + ntohs(udphdr->dest))); + if (IP_ACCEPT_LINK_LAYER_ADDRESSED_PORT(udphdr->dest)) { + LWIP_DEBUGF(IP_DEBUG | LWIP_DBG_TRACE, ("ip_input: DHCP packet accepted.\n")); + netif = inp; + check_ip_src = 0; + } + } + } +#endif /* IP_ACCEPT_LINK_LAYER_ADDRESSING */ + + /* broadcast or multicast packet source address? Compliant with RFC 1122: 3.2.1.3 */ +#if IP_ACCEPT_LINK_LAYER_ADDRESSING + /* DHCP servers need 0.0.0.0 to be allowed as source address (RFC 1.1.2.2: 3.2.1.3/a) */ + if (check_ip_src && current_iphdr_src.addr != IPADDR_ANY) +#endif /* IP_ACCEPT_LINK_LAYER_ADDRESSING */ + { if ((ip_addr_isbroadcast(¤t_iphdr_src, inp)) || + (ip_addr_ismulticast(¤t_iphdr_src))) { + /* packet source is not valid */ + LWIP_DEBUGF(IP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_WARNING, ("ip_input: packet source is not valid.\n")); + /* free (drop) packet pbufs */ + pbuf_free(p); + IP_STATS_INC(ip.drop); + snmp_inc_ipinaddrerrors(); + snmp_inc_ipindiscards(); + return ERR_OK; + } + } + + /* packet not for us? */ + if (netif == NULL) { + /* packet not for us, route or discard */ + LWIP_DEBUGF(IP_DEBUG | LWIP_DBG_TRACE, ("ip_input: packet not for us.\n")); +#if IP_FORWARD + /* non-broadcast packet? */ + if (!ip_addr_isbroadcast(¤t_iphdr_dest, inp)) { + /* try to forward IP packet on (other) interfaces */ + ip_forward(p, iphdr, inp); + } else +#endif /* IP_FORWARD */ + { + snmp_inc_ipinaddrerrors(); + snmp_inc_ipindiscards(); + } + pbuf_free(p); + return ERR_OK; + } + /* packet consists of multiple fragments? */ + if ((IPH_OFFSET(iphdr) & PP_HTONS(IP_OFFMASK | IP_MF)) != 0) { +#if IP_REASSEMBLY /* packet fragment reassembly code present? */ + LWIP_DEBUGF(IP_DEBUG, ("IP packet is a fragment (id=0x%04"X16_F" tot_len=%"U16_F" len=%"U16_F" MF=%"U16_F" offset=%"U16_F"), calling ip_reass()\n", + ntohs(IPH_ID(iphdr)), p->tot_len, ntohs(IPH_LEN(iphdr)), !!(IPH_OFFSET(iphdr) & PP_HTONS(IP_MF)), (ntohs(IPH_OFFSET(iphdr)) & IP_OFFMASK)*8)); + /* reassemble the packet*/ + p = ip_reass(p); + /* packet not fully reassembled yet? */ + if (p == NULL) { + return ERR_OK; + } + iphdr = (struct ip_hdr *)p->payload; +#else /* IP_REASSEMBLY == 0, no packet fragment reassembly code present */ + pbuf_free(p); + LWIP_DEBUGF(IP_DEBUG | LWIP_DBG_LEVEL_SERIOUS, ("IP packet dropped since it was fragmented (0x%"X16_F") (while IP_REASSEMBLY == 0).\n", + ntohs(IPH_OFFSET(iphdr)))); + IP_STATS_INC(ip.opterr); + IP_STATS_INC(ip.drop); + /* unsupported protocol feature */ + snmp_inc_ipinunknownprotos(); + return ERR_OK; +#endif /* IP_REASSEMBLY */ + } + +#if IP_OPTIONS_ALLOWED == 0 /* no support for IP options in the IP header? */ + +#if LWIP_IGMP + /* there is an extra "router alert" option in IGMP messages which we allow for but do not police */ + if((iphdr_hlen > IP_HLEN) && (IPH_PROTO(iphdr) != IP_PROTO_IGMP)) { +#else + if (iphdr_hlen > IP_HLEN) { +#endif /* LWIP_IGMP */ + LWIP_DEBUGF(IP_DEBUG | LWIP_DBG_LEVEL_SERIOUS, ("IP packet dropped since there were IP options (while IP_OPTIONS_ALLOWED == 0).\n")); + pbuf_free(p); + IP_STATS_INC(ip.opterr); + IP_STATS_INC(ip.drop); + /* unsupported protocol feature */ + snmp_inc_ipinunknownprotos(); + return ERR_OK; + } +#endif /* IP_OPTIONS_ALLOWED == 0 */ + + /* send to upper layers */ + LWIP_DEBUGF(IP_DEBUG, ("ip_input: \n")); + ip_debug_print(p); + LWIP_DEBUGF(IP_DEBUG, ("ip_input: p->len %"U16_F" p->tot_len %"U16_F"\n", p->len, p->tot_len)); + + current_netif = inp; + current_header = iphdr; + +#if LWIP_RAW + /* raw input did not eat the packet? */ + if (raw_input(p, inp) == 0) +#endif /* LWIP_RAW */ + { + + switch (IPH_PROTO(iphdr)) { +#if LWIP_UDP + case IP_PROTO_UDP: +#if LWIP_UDPLITE + case IP_PROTO_UDPLITE: +#endif /* LWIP_UDPLITE */ + snmp_inc_ipindelivers(); + udp_input(p, inp); + break; +#endif /* LWIP_UDP */ +#if LWIP_TCP + case IP_PROTO_TCP: + snmp_inc_ipindelivers(); + tcp_input(p, inp); + break; +#endif /* LWIP_TCP */ +#if LWIP_ICMP + case IP_PROTO_ICMP: + snmp_inc_ipindelivers(); + icmp_input(p, inp); + break; +#endif /* LWIP_ICMP */ +#if LWIP_IGMP + case IP_PROTO_IGMP: + igmp_input(p, inp, ¤t_iphdr_dest); + break; +#endif /* LWIP_IGMP */ + default: +#if LWIP_ICMP + /* send ICMP destination protocol unreachable unless is was a broadcast */ + if (!ip_addr_isbroadcast(¤t_iphdr_dest, inp) && + !ip_addr_ismulticast(¤t_iphdr_dest)) { + p->payload = iphdr; + icmp_dest_unreach(p, ICMP_DUR_PROTO); + } +#endif /* LWIP_ICMP */ + pbuf_free(p); + + LWIP_DEBUGF(IP_DEBUG | LWIP_DBG_LEVEL_SERIOUS, ("Unsupported transport protocol %"U16_F"\n", IPH_PROTO(iphdr))); + + IP_STATS_INC(ip.proterr); + IP_STATS_INC(ip.drop); + snmp_inc_ipinunknownprotos(); + } + } + + current_netif = NULL; + current_header = NULL; + ip_addr_set_any(¤t_iphdr_src); + ip_addr_set_any(¤t_iphdr_dest); + + return ERR_OK; +} + +/** + * Sends an IP packet on a network interface. This function constructs + * the IP header and calculates the IP header checksum. If the source + * IP address is NULL, the IP address of the outgoing network + * interface is filled in as source address. + * If the destination IP address is IP_HDRINCL, p is assumed to already + * include an IP header and p->payload points to it instead of the data. + * + * @param p the packet to send (p->payload points to the data, e.g. next + protocol header; if dest == IP_HDRINCL, p already includes an IP + header and p->payload points to that IP header) + * @param src the source IP address to send from (if src == IP_ADDR_ANY, the + * IP address of the netif used to send is used as source address) + * @param dest the destination IP address to send the packet to + * @param ttl the TTL value to be set in the IP header + * @param tos the TOS value to be set in the IP header + * @param proto the PROTOCOL to be set in the IP header + * @param netif the netif on which to send this packet + * @return ERR_OK if the packet was sent OK + * ERR_BUF if p doesn't have enough space for IP/LINK headers + * returns errors returned by netif->output + * + * @note ip_id: RFC791 "some host may be able to simply use + * unique identifiers independent of destination" + */ +err_t +ip_output_if(struct pbuf *p, ip_addr_t *src, ip_addr_t *dest, + u8_t ttl, u8_t tos, + u8_t proto, struct netif *netif) +{ +#if IP_OPTIONS_SEND + return ip_output_if_opt(p, src, dest, ttl, tos, proto, netif, NULL, 0); +} + +/** + * Same as ip_output_if() but with the possibility to include IP options: + * + * @ param ip_options pointer to the IP options, copied into the IP header + * @ param optlen length of ip_options + */ +err_t ip_output_if_opt(struct pbuf *p, ip_addr_t *src, ip_addr_t *dest, + u8_t ttl, u8_t tos, u8_t proto, struct netif *netif, void *ip_options, + u16_t optlen) +{ +#endif /* IP_OPTIONS_SEND */ + struct ip_hdr *iphdr; + ip_addr_t dest_addr; +#if CHECKSUM_GEN_IP_INLINE + u32_t chk_sum = 0; +#endif /* CHECKSUM_GEN_IP_INLINE */ + + /* pbufs passed to IP must have a ref-count of 1 as their payload pointer + gets altered as the packet is passed down the stack */ + LWIP_ASSERT("p->ref == 1", p->ref == 1); + + snmp_inc_ipoutrequests(); + + /* Should the IP header be generated or is it already included in p? */ + if (dest != IP_HDRINCL) { + u16_t ip_hlen = IP_HLEN; +#if IP_OPTIONS_SEND + u16_t optlen_aligned = 0; + if (optlen != 0) { +#if CHECKSUM_GEN_IP_INLINE + int i; +#endif /* CHECKSUM_GEN_IP_INLINE */ + /* round up to a multiple of 4 */ + optlen_aligned = ((optlen + 3) & ~3); + ip_hlen += optlen_aligned; + /* First write in the IP options */ + if (pbuf_header(p, optlen_aligned)) { + LWIP_DEBUGF(IP_DEBUG | LWIP_DBG_LEVEL_SERIOUS, ("ip_output_if_opt: not enough room for IP options in pbuf\n")); + IP_STATS_INC(ip.err); + snmp_inc_ipoutdiscards(); + return ERR_BUF; + } + MEMCPY(p->payload, ip_options, optlen); + if (optlen < optlen_aligned) { + /* zero the remaining bytes */ + memset(((char*)p->payload) + optlen, 0, optlen_aligned - optlen); + } +#if CHECKSUM_GEN_IP_INLINE + for (i = 0; i < optlen_aligned/2; i++) { + chk_sum += ((u16_t*)p->payload)[i]; + } +#endif /* CHECKSUM_GEN_IP_INLINE */ + } +#endif /* IP_OPTIONS_SEND */ + /* generate IP header */ + if (pbuf_header(p, IP_HLEN)) { + LWIP_DEBUGF(IP_DEBUG | LWIP_DBG_LEVEL_SERIOUS, ("ip_output: not enough room for IP header in pbuf\n")); + + IP_STATS_INC(ip.err); + snmp_inc_ipoutdiscards(); + return ERR_BUF; + } + + iphdr = (struct ip_hdr *)p->payload; + LWIP_ASSERT("check that first pbuf can hold struct ip_hdr", + (p->len >= sizeof(struct ip_hdr))); + + IPH_TTL_SET(iphdr, ttl); + IPH_PROTO_SET(iphdr, proto); +#if CHECKSUM_GEN_IP_INLINE + chk_sum += LWIP_MAKE_U16(proto, ttl); +#endif /* CHECKSUM_GEN_IP_INLINE */ + + /* dest cannot be NULL here */ + ip_addr_copy(iphdr->dest, *dest); +#if CHECKSUM_GEN_IP_INLINE + chk_sum += ip4_addr_get_u32(&iphdr->dest) & 0xFFFF; + chk_sum += ip4_addr_get_u32(&iphdr->dest) >> 16; +#endif /* CHECKSUM_GEN_IP_INLINE */ + + IPH_VHLTOS_SET(iphdr, 4, ip_hlen / 4, tos); +#if CHECKSUM_GEN_IP_INLINE + chk_sum += iphdr->_v_hl_tos; +#endif /* CHECKSUM_GEN_IP_INLINE */ + IPH_LEN_SET(iphdr, htons(p->tot_len)); +#if CHECKSUM_GEN_IP_INLINE + chk_sum += iphdr->_len; +#endif /* CHECKSUM_GEN_IP_INLINE */ + IPH_OFFSET_SET(iphdr, 0); + IPH_ID_SET(iphdr, htons(ip_id)); +#if CHECKSUM_GEN_IP_INLINE + chk_sum += iphdr->_id; +#endif /* CHECKSUM_GEN_IP_INLINE */ + ++ip_id; + + if (ip_addr_isany(src)) { + ip_addr_copy(iphdr->src, netif->ip_addr); + } else { + /* src cannot be NULL here */ + ip_addr_copy(iphdr->src, *src); + } + +#if CHECKSUM_GEN_IP_INLINE + chk_sum += ip4_addr_get_u32(&iphdr->src) & 0xFFFF; + chk_sum += ip4_addr_get_u32(&iphdr->src) >> 16; + chk_sum = (chk_sum >> 16) + (chk_sum & 0xFFFF); + chk_sum = (chk_sum >> 16) + chk_sum; + chk_sum = ~chk_sum; + iphdr->_chksum = chk_sum; /* network order */ +#else /* CHECKSUM_GEN_IP_INLINE */ + IPH_CHKSUM_SET(iphdr, 0); +#if CHECKSUM_GEN_IP + IPH_CHKSUM_SET(iphdr, inet_chksum(iphdr, ip_hlen)); +#endif +#endif /* CHECKSUM_GEN_IP_INLINE */ + } else { + /* IP header already included in p */ + iphdr = (struct ip_hdr *)p->payload; + ip_addr_copy(dest_addr, iphdr->dest); + dest = &dest_addr; + } + + IP_STATS_INC(ip.xmit); + + LWIP_DEBUGF(IP_DEBUG, ("ip_output_if: %c%c%"U16_F"\n", netif->name[0], netif->name[1], netif->num)); + ip_debug_print(p); + +#if ENABLE_LOOPBACK + if (ip_addr_cmp(dest, &netif->ip_addr)) { + /* Packet to self, enqueue it for loopback */ + LWIP_DEBUGF(IP_DEBUG, ("netif_loop_output()")); + return netif_loop_output(netif, p, dest); + } +#if LWIP_IGMP + if ((p->flags & PBUF_FLAG_MCASTLOOP) != 0) { + netif_loop_output(netif, p, dest); + } +#endif /* LWIP_IGMP */ +#endif /* ENABLE_LOOPBACK */ +#if IP_FRAG + /* don't fragment if interface has mtu set to 0 [loopif] */ + if (netif->mtu && (p->tot_len > netif->mtu)) { + return ip_frag(p, netif, dest); + } +#endif /* IP_FRAG */ + + LWIP_DEBUGF(IP_DEBUG, ("netif->output()")); + return netif->output(netif, p, dest); +} + +/** + * Simple interface to ip_output_if. It finds the outgoing network + * interface and calls upon ip_output_if to do the actual work. + * + * @param p the packet to send (p->payload points to the data, e.g. next + protocol header; if dest == IP_HDRINCL, p already includes an IP + header and p->payload points to that IP header) + * @param src the source IP address to send from (if src == IP_ADDR_ANY, the + * IP address of the netif used to send is used as source address) + * @param dest the destination IP address to send the packet to + * @param ttl the TTL value to be set in the IP header + * @param tos the TOS value to be set in the IP header + * @param proto the PROTOCOL to be set in the IP header + * + * @return ERR_RTE if no route is found + * see ip_output_if() for more return values + */ +err_t +ip_output(struct pbuf *p, ip_addr_t *src, ip_addr_t *dest, + u8_t ttl, u8_t tos, u8_t proto) +{ + struct netif *netif; + + /* pbufs passed to IP must have a ref-count of 1 as their payload pointer + gets altered as the packet is passed down the stack */ + LWIP_ASSERT("p->ref == 1", p->ref == 1); + + if ((netif = ip_route(dest)) == NULL) { + LWIP_DEBUGF(IP_DEBUG, ("ip_output: No route to %"U16_F".%"U16_F".%"U16_F".%"U16_F"\n", + ip4_addr1_16(dest), ip4_addr2_16(dest), ip4_addr3_16(dest), ip4_addr4_16(dest))); + IP_STATS_INC(ip.rterr); + return ERR_RTE; + } + + return ip_output_if(p, src, dest, ttl, tos, proto, netif); +} + +#if LWIP_NETIF_HWADDRHINT +/** Like ip_output, but takes and addr_hint pointer that is passed on to netif->addr_hint + * before calling ip_output_if. + * + * @param p the packet to send (p->payload points to the data, e.g. next + protocol header; if dest == IP_HDRINCL, p already includes an IP + header and p->payload points to that IP header) + * @param src the source IP address to send from (if src == IP_ADDR_ANY, the + * IP address of the netif used to send is used as source address) + * @param dest the destination IP address to send the packet to + * @param ttl the TTL value to be set in the IP header + * @param tos the TOS value to be set in the IP header + * @param proto the PROTOCOL to be set in the IP header + * @param addr_hint address hint pointer set to netif->addr_hint before + * calling ip_output_if() + * + * @return ERR_RTE if no route is found + * see ip_output_if() for more return values + */ +err_t +ip_output_hinted(struct pbuf *p, ip_addr_t *src, ip_addr_t *dest, + u8_t ttl, u8_t tos, u8_t proto, u8_t *addr_hint) +{ + struct netif *netif; + err_t err; + + /* pbufs passed to IP must have a ref-count of 1 as their payload pointer + gets altered as the packet is passed down the stack */ + LWIP_ASSERT("p->ref == 1", p->ref == 1); + + if ((netif = ip_route(dest)) == NULL) { + LWIP_DEBUGF(IP_DEBUG, ("ip_output: No route to %"U16_F".%"U16_F".%"U16_F".%"U16_F"\n", + ip4_addr1_16(dest), ip4_addr2_16(dest), ip4_addr3_16(dest), ip4_addr4_16(dest))); + IP_STATS_INC(ip.rterr); + return ERR_RTE; + } + + netif->addr_hint = addr_hint; + err = ip_output_if(p, src, dest, ttl, tos, proto, netif); + netif->addr_hint = NULL; + + return err; +} +#endif /* LWIP_NETIF_HWADDRHINT*/ + +#if IP_DEBUG +/* Print an IP header by using LWIP_DEBUGF + * @param p an IP packet, p->payload pointing to the IP header + */ +void +ip_debug_print(struct pbuf *p) +{ + struct ip_hdr *iphdr = (struct ip_hdr *)p->payload; + u8_t *payload; + + payload = (u8_t *)iphdr + IP_HLEN; + + LWIP_DEBUGF(IP_DEBUG, ("IP header:\n")); + LWIP_DEBUGF(IP_DEBUG, ("+-------------------------------+\n")); + LWIP_DEBUGF(IP_DEBUG, ("|%2"S16_F" |%2"S16_F" | 0x%02"X16_F" | %5"U16_F" | (v, hl, tos, len)\n", + IPH_V(iphdr), + IPH_HL(iphdr), + IPH_TOS(iphdr), + ntohs(IPH_LEN(iphdr)))); + LWIP_DEBUGF(IP_DEBUG, ("+-------------------------------+\n")); + LWIP_DEBUGF(IP_DEBUG, ("| %5"U16_F" |%"U16_F"%"U16_F"%"U16_F"| %4"U16_F" | (id, flags, offset)\n", + ntohs(IPH_ID(iphdr)), + ntohs(IPH_OFFSET(iphdr)) >> 15 & 1, + ntohs(IPH_OFFSET(iphdr)) >> 14 & 1, + ntohs(IPH_OFFSET(iphdr)) >> 13 & 1, + ntohs(IPH_OFFSET(iphdr)) & IP_OFFMASK)); + LWIP_DEBUGF(IP_DEBUG, ("+-------------------------------+\n")); + LWIP_DEBUGF(IP_DEBUG, ("| %3"U16_F" | %3"U16_F" | 0x%04"X16_F" | (ttl, proto, chksum)\n", + IPH_TTL(iphdr), + IPH_PROTO(iphdr), + ntohs(IPH_CHKSUM(iphdr)))); + LWIP_DEBUGF(IP_DEBUG, ("+-------------------------------+\n")); + LWIP_DEBUGF(IP_DEBUG, ("| %3"U16_F" | %3"U16_F" | %3"U16_F" | %3"U16_F" | (src)\n", + ip4_addr1_16(&iphdr->src), + ip4_addr2_16(&iphdr->src), + ip4_addr3_16(&iphdr->src), + ip4_addr4_16(&iphdr->src))); + LWIP_DEBUGF(IP_DEBUG, ("+-------------------------------+\n")); + LWIP_DEBUGF(IP_DEBUG, ("| %3"U16_F" | %3"U16_F" | %3"U16_F" | %3"U16_F" | (dest)\n", + ip4_addr1_16(&iphdr->dest), + ip4_addr2_16(&iphdr->dest), + ip4_addr3_16(&iphdr->dest), + ip4_addr4_16(&iphdr->dest))); + LWIP_DEBUGF(IP_DEBUG, ("+-------------------------------+\n")); +} +#endif /* IP_DEBUG */ diff --git a/features/unsupported/net/lwip/lwip/core/ipv4/ip_addr.c b/features/unsupported/net/lwip/lwip/core/ipv4/ip_addr.c new file mode 100644 index 00000000000..8f633ff2310 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/core/ipv4/ip_addr.c @@ -0,0 +1,312 @@ +/** + * @file + * This is the IPv4 address tools implementation. + * + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ + +#include "lwip/opt.h" +#include "lwip/ip_addr.h" +#include "lwip/netif.h" + +/* used by IP_ADDR_ANY and IP_ADDR_BROADCAST in ip_addr.h */ +const ip_addr_t ip_addr_any = { IPADDR_ANY }; +const ip_addr_t ip_addr_broadcast = { IPADDR_BROADCAST }; + +/** + * Determine if an address is a broadcast address on a network interface + * + * @param addr address to be checked + * @param netif the network interface against which the address is checked + * @return returns non-zero if the address is a broadcast address + */ +u8_t +ip4_addr_isbroadcast(u32_t addr, const struct netif *netif) +{ + ip_addr_t ipaddr; + ip4_addr_set_u32(&ipaddr, addr); + + /* all ones (broadcast) or all zeroes (old skool broadcast) */ + if ((~addr == IPADDR_ANY) || + (addr == IPADDR_ANY)) { + return 1; + /* no broadcast support on this network interface? */ + } else if ((netif->flags & NETIF_FLAG_BROADCAST) == 0) { + /* the given address cannot be a broadcast address + * nor can we check against any broadcast addresses */ + return 0; + /* address matches network interface address exactly? => no broadcast */ + } else if (addr == ip4_addr_get_u32(&netif->ip_addr)) { + return 0; + /* on the same (sub) network... */ + } else if (ip_addr_netcmp(&ipaddr, &(netif->ip_addr), &(netif->netmask)) + /* ...and host identifier bits are all ones? =>... */ + && ((addr & ~ip4_addr_get_u32(&netif->netmask)) == + (IPADDR_BROADCAST & ~ip4_addr_get_u32(&netif->netmask)))) { + /* => network broadcast address */ + return 1; + } else { + return 0; + } +} + +/** Checks if a netmask is valid (starting with ones, then only zeros) + * + * @param netmask the IPv4 netmask to check (in network byte order!) + * @return 1 if the netmask is valid, 0 if it is not + */ +u8_t +ip4_addr_netmask_valid(u32_t netmask) +{ + u32_t mask; + u32_t nm_hostorder = lwip_htonl(netmask); + + /* first, check for the first zero */ + for (mask = 1UL << 31 ; mask != 0; mask >>= 1) { + if ((nm_hostorder & mask) == 0) { + break; + } + } + /* then check that there is no one */ + for (; mask != 0; mask >>= 1) { + if ((nm_hostorder & mask) != 0) { + /* there is a one after the first zero -> invalid */ + return 0; + } + } + /* no one after the first zero -> valid */ + return 1; +} + +/* Here for now until needed in other places in lwIP */ +#ifndef isprint +#define in_range(c, lo, up) ((u8_t)c >= lo && (u8_t)c <= up) +#define isprint(c) in_range(c, 0x20, 0x7f) +#define isdigit(c) in_range(c, '0', '9') +#define isxdigit(c) (isdigit(c) || in_range(c, 'a', 'f') || in_range(c, 'A', 'F')) +#define islower(c) in_range(c, 'a', 'z') +#define isspace(c) (c == ' ' || c == '\f' || c == '\n' || c == '\r' || c == '\t' || c == '\v') +#endif + +/** + * Ascii internet address interpretation routine. + * The value returned is in network order. + * + * @param cp IP address in ascii represenation (e.g. "127.0.0.1") + * @return ip address in network order + */ +u32_t +ipaddr_addr(const char *cp) +{ + ip_addr_t val; + + if (ipaddr_aton(cp, &val)) { + return ip4_addr_get_u32(&val); + } + return (IPADDR_NONE); +} + +/** + * Check whether "cp" is a valid ascii representation + * of an Internet address and convert to a binary address. + * Returns 1 if the address is valid, 0 if not. + * This replaces inet_addr, the return value from which + * cannot distinguish between failure and a local broadcast address. + * + * @param cp IP address in ascii represenation (e.g. "127.0.0.1") + * @param addr pointer to which to save the ip address in network order + * @return 1 if cp could be converted to addr, 0 on failure + */ +int +ipaddr_aton(const char *cp, ip_addr_t *addr) +{ + u32_t val; + u8_t base; + char c; + u32_t parts[4]; + u32_t *pp = parts; + + c = *cp; + for (;;) { + /* + * Collect number up to ``.''. + * Values are specified as for C: + * 0x=hex, 0=octal, 1-9=decimal. + */ + if (!isdigit(c)) + return (0); + val = 0; + base = 10; + if (c == '0') { + c = *++cp; + if (c == 'x' || c == 'X') { + base = 16; + c = *++cp; + } else + base = 8; + } + for (;;) { + if (isdigit(c)) { + val = (val * base) + (int)(c - '0'); + c = *++cp; + } else if (base == 16 && isxdigit(c)) { + val = (val << 4) | (int)(c + 10 - (islower(c) ? 'a' : 'A')); + c = *++cp; + } else + break; + } + if (c == '.') { + /* + * Internet format: + * a.b.c.d + * a.b.c (with c treated as 16 bits) + * a.b (with b treated as 24 bits) + */ + if (pp >= parts + 3) { + return (0); + } + *pp++ = val; + c = *++cp; + } else + break; + } + /* + * Check for trailing characters. + */ + if (c != '\0' && !isspace(c)) { + return (0); + } + /* + * Concoct the address according to + * the number of parts specified. + */ + switch (pp - parts + 1) { + + case 0: + return (0); /* initial nondigit */ + + case 1: /* a -- 32 bits */ + break; + + case 2: /* a.b -- 8.24 bits */ + if (val > 0xffffffUL) { + return (0); + } + val |= parts[0] << 24; + break; + + case 3: /* a.b.c -- 8.8.16 bits */ + if (val > 0xffff) { + return (0); + } + val |= (parts[0] << 24) | (parts[1] << 16); + break; + + case 4: /* a.b.c.d -- 8.8.8.8 bits */ + if (val > 0xff) { + return (0); + } + val |= (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8); + break; + default: + LWIP_ASSERT("unhandled", 0); + break; + } + if (addr) { + ip4_addr_set_u32(addr, htonl(val)); + } + return (1); +} + +/** + * Convert numeric IP address into decimal dotted ASCII representation. + * returns ptr to static buffer; not reentrant! + * + * @param addr ip address in network order to convert + * @return pointer to a global static (!) buffer that holds the ASCII + * represenation of addr + */ +char * +ipaddr_ntoa(const ip_addr_t *addr) +{ + static char str[16]; + return ipaddr_ntoa_r(addr, str, 16); +} + +/** + * Same as ipaddr_ntoa, but reentrant since a user-supplied buffer is used. + * + * @param addr ip address in network order to convert + * @param buf target buffer where the string is stored + * @param buflen length of buf + * @return either pointer to buf which now holds the ASCII + * representation of addr or NULL if buf was too small + */ +char *ipaddr_ntoa_r(const ip_addr_t *addr, char *buf, int buflen) +{ + u32_t s_addr; + char inv[3]; + char *rp; + u8_t *ap; + u8_t rem; + u8_t n; + u8_t i; + int len = 0; + + s_addr = ip4_addr_get_u32(addr); + + rp = buf; + ap = (u8_t *)&s_addr; + for(n = 0; n < 4; n++) { + i = 0; + do { + rem = *ap % (u8_t)10; + *ap /= (u8_t)10; + inv[i++] = '0' + rem; + } while(*ap); + while(i--) { + if (len++ >= buflen) { + return NULL; + } + *rp++ = inv[i]; + } + if (len++ >= buflen) { + return NULL; + } + *rp++ = '.'; + ap++; + } + *--rp = 0; + return buf; +} diff --git a/features/unsupported/net/lwip/lwip/core/ipv4/ip_frag.c b/features/unsupported/net/lwip/lwip/core/ipv4/ip_frag.c new file mode 100644 index 00000000000..8d184345dff --- /dev/null +++ b/features/unsupported/net/lwip/lwip/core/ipv4/ip_frag.c @@ -0,0 +1,863 @@ +/** + * @file + * This is the IPv4 packet segmentation and reassembly implementation. + * + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Jani Monoses + * Simon Goldschmidt + * original reassembly code by Adam Dunkels + * + */ + +#include "lwip/opt.h" +#include "lwip/ip_frag.h" +#include "lwip/def.h" +#include "lwip/inet_chksum.h" +#include "lwip/netif.h" +#include "lwip/snmp.h" +#include "lwip/stats.h" +#include "lwip/icmp.h" + +#include + +#if IP_REASSEMBLY +/** + * The IP reassembly code currently has the following limitations: + * - IP header options are not supported + * - fragments must not overlap (e.g. due to different routes), + * currently, overlapping or duplicate fragments are thrown away + * if IP_REASS_CHECK_OVERLAP=1 (the default)! + * + * @todo: work with IP header options + */ + +/** Setting this to 0, you can turn off checking the fragments for overlapping + * regions. The code gets a little smaller. Only use this if you know that + * overlapping won't occur on your network! */ +#ifndef IP_REASS_CHECK_OVERLAP +#define IP_REASS_CHECK_OVERLAP 1 +#endif /* IP_REASS_CHECK_OVERLAP */ + +/** Set to 0 to prevent freeing the oldest datagram when the reassembly buffer is + * full (IP_REASS_MAX_PBUFS pbufs are enqueued). The code gets a little smaller. + * Datagrams will be freed by timeout only. Especially useful when MEMP_NUM_REASSDATA + * is set to 1, so one datagram can be reassembled at a time, only. */ +#ifndef IP_REASS_FREE_OLDEST +#define IP_REASS_FREE_OLDEST 1 +#endif /* IP_REASS_FREE_OLDEST */ + +#define IP_REASS_FLAG_LASTFRAG 0x01 + +/** This is a helper struct which holds the starting + * offset and the ending offset of this fragment to + * easily chain the fragments. + * It has the same packing requirements as the IP header, since it replaces + * the IP header in memory in incoming fragments (after copying it) to keep + * track of the various fragments. (-> If the IP header doesn't need packing, + * this struct doesn't need packing, too.) + */ +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct ip_reass_helper { + PACK_STRUCT_FIELD(struct pbuf *next_pbuf); + PACK_STRUCT_FIELD(u16_t start); + PACK_STRUCT_FIELD(u16_t end); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +#define IP_ADDRESSES_AND_ID_MATCH(iphdrA, iphdrB) \ + (ip_addr_cmp(&(iphdrA)->src, &(iphdrB)->src) && \ + ip_addr_cmp(&(iphdrA)->dest, &(iphdrB)->dest) && \ + IPH_ID(iphdrA) == IPH_ID(iphdrB)) ? 1 : 0 + +/* global variables */ +static struct ip_reassdata *reassdatagrams; +static u16_t ip_reass_pbufcount; + +/* function prototypes */ +static void ip_reass_dequeue_datagram(struct ip_reassdata *ipr, struct ip_reassdata *prev); +static int ip_reass_free_complete_datagram(struct ip_reassdata *ipr, struct ip_reassdata *prev); + +/** + * Reassembly timer base function + * for both NO_SYS == 0 and 1 (!). + * + * Should be called every 1000 msec (defined by IP_TMR_INTERVAL). + */ +void +ip_reass_tmr(void) +{ + struct ip_reassdata *r, *prev = NULL; + + r = reassdatagrams; + while (r != NULL) { + /* Decrement the timer. Once it reaches 0, + * clean up the incomplete fragment assembly */ + if (r->timer > 0) { + r->timer--; + LWIP_DEBUGF(IP_REASS_DEBUG, ("ip_reass_tmr: timer dec %"U16_F"\n",(u16_t)r->timer)); + prev = r; + r = r->next; + } else { + /* reassembly timed out */ + struct ip_reassdata *tmp; + LWIP_DEBUGF(IP_REASS_DEBUG, ("ip_reass_tmr: timer timed out\n")); + tmp = r; + /* get the next pointer before freeing */ + r = r->next; + /* free the helper struct and all enqueued pbufs */ + ip_reass_free_complete_datagram(tmp, prev); + } + } +} + +/** + * Free a datagram (struct ip_reassdata) and all its pbufs. + * Updates the total count of enqueued pbufs (ip_reass_pbufcount), + * SNMP counters and sends an ICMP time exceeded packet. + * + * @param ipr datagram to free + * @param prev the previous datagram in the linked list + * @return the number of pbufs freed + */ +static int +ip_reass_free_complete_datagram(struct ip_reassdata *ipr, struct ip_reassdata *prev) +{ + u16_t pbufs_freed = 0; + u8_t clen; + struct pbuf *p; + struct ip_reass_helper *iprh; + + LWIP_ASSERT("prev != ipr", prev != ipr); + if (prev != NULL) { + LWIP_ASSERT("prev->next == ipr", prev->next == ipr); + } + + snmp_inc_ipreasmfails(); +#if LWIP_ICMP + iprh = (struct ip_reass_helper *)ipr->p->payload; + if (iprh->start == 0) { + /* The first fragment was received, send ICMP time exceeded. */ + /* First, de-queue the first pbuf from r->p. */ + p = ipr->p; + ipr->p = iprh->next_pbuf; + /* Then, copy the original header into it. */ + SMEMCPY(p->payload, &ipr->iphdr, IP_HLEN); + icmp_time_exceeded(p, ICMP_TE_FRAG); + clen = pbuf_clen(p); + LWIP_ASSERT("pbufs_freed + clen <= 0xffff", pbufs_freed + clen <= 0xffff); + pbufs_freed += clen; + pbuf_free(p); + } +#endif /* LWIP_ICMP */ + + /* First, free all received pbufs. The individual pbufs need to be released + separately as they have not yet been chained */ + p = ipr->p; + while (p != NULL) { + struct pbuf *pcur; + iprh = (struct ip_reass_helper *)p->payload; + pcur = p; + /* get the next pointer before freeing */ + p = iprh->next_pbuf; + clen = pbuf_clen(pcur); + LWIP_ASSERT("pbufs_freed + clen <= 0xffff", pbufs_freed + clen <= 0xffff); + pbufs_freed += clen; + pbuf_free(pcur); + } + /* Then, unchain the struct ip_reassdata from the list and free it. */ + ip_reass_dequeue_datagram(ipr, prev); + LWIP_ASSERT("ip_reass_pbufcount >= clen", ip_reass_pbufcount >= pbufs_freed); + ip_reass_pbufcount -= pbufs_freed; + + return pbufs_freed; +} + +#if IP_REASS_FREE_OLDEST +/** + * Free the oldest datagram to make room for enqueueing new fragments. + * The datagram 'fraghdr' belongs to is not freed! + * + * @param fraghdr IP header of the current fragment + * @param pbufs_needed number of pbufs needed to enqueue + * (used for freeing other datagrams if not enough space) + * @return the number of pbufs freed + */ +static int +ip_reass_remove_oldest_datagram(struct ip_hdr *fraghdr, int pbufs_needed) +{ + /* @todo Can't we simply remove the last datagram in the + * linked list behind reassdatagrams? + */ + struct ip_reassdata *r, *oldest, *prev; + int pbufs_freed = 0, pbufs_freed_current; + int other_datagrams; + + /* Free datagrams until being allowed to enqueue 'pbufs_needed' pbufs, + * but don't free the datagram that 'fraghdr' belongs to! */ + do { + oldest = NULL; + prev = NULL; + other_datagrams = 0; + r = reassdatagrams; + while (r != NULL) { + if (!IP_ADDRESSES_AND_ID_MATCH(&r->iphdr, fraghdr)) { + /* Not the same datagram as fraghdr */ + other_datagrams++; + if (oldest == NULL) { + oldest = r; + } else if (r->timer <= oldest->timer) { + /* older than the previous oldest */ + oldest = r; + } + } + if (r->next != NULL) { + prev = r; + } + r = r->next; + } + if (oldest != NULL) { + pbufs_freed_current = ip_reass_free_complete_datagram(oldest, prev); + pbufs_freed += pbufs_freed_current; + } + } while ((pbufs_freed < pbufs_needed) && (other_datagrams > 1)); + return pbufs_freed; +} +#endif /* IP_REASS_FREE_OLDEST */ + +/** + * Enqueues a new fragment into the fragment queue + * @param fraghdr points to the new fragments IP hdr + * @param clen number of pbufs needed to enqueue (used for freeing other datagrams if not enough space) + * @return A pointer to the queue location into which the fragment was enqueued + */ +static struct ip_reassdata* +ip_reass_enqueue_new_datagram(struct ip_hdr *fraghdr, int clen) +{ + struct ip_reassdata* ipr; + /* No matching previous fragment found, allocate a new reassdata struct */ + ipr = (struct ip_reassdata *)memp_malloc(MEMP_REASSDATA); + if (ipr == NULL) { +#if IP_REASS_FREE_OLDEST + if (ip_reass_remove_oldest_datagram(fraghdr, clen) >= clen) { + ipr = (struct ip_reassdata *)memp_malloc(MEMP_REASSDATA); + } + if (ipr == NULL) +#endif /* IP_REASS_FREE_OLDEST */ + { + IPFRAG_STATS_INC(ip_frag.memerr); + LWIP_DEBUGF(IP_REASS_DEBUG,("Failed to alloc reassdata struct\n")); + return NULL; + } + } + memset(ipr, 0, sizeof(struct ip_reassdata)); + ipr->timer = IP_REASS_MAXAGE; + + /* enqueue the new structure to the front of the list */ + ipr->next = reassdatagrams; + reassdatagrams = ipr; + /* copy the ip header for later tests and input */ + /* @todo: no ip options supported? */ + SMEMCPY(&(ipr->iphdr), fraghdr, IP_HLEN); + return ipr; +} + +/** + * Dequeues a datagram from the datagram queue. Doesn't deallocate the pbufs. + * @param ipr points to the queue entry to dequeue + */ +static void +ip_reass_dequeue_datagram(struct ip_reassdata *ipr, struct ip_reassdata *prev) +{ + + /* dequeue the reass struct */ + if (reassdatagrams == ipr) { + /* it was the first in the list */ + reassdatagrams = ipr->next; + } else { + /* it wasn't the first, so it must have a valid 'prev' */ + LWIP_ASSERT("sanity check linked list", prev != NULL); + prev->next = ipr->next; + } + + /* now we can free the ip_reass struct */ + memp_free(MEMP_REASSDATA, ipr); +} + +/** + * Chain a new pbuf into the pbuf list that composes the datagram. The pbuf list + * will grow over time as new pbufs are rx. + * Also checks that the datagram passes basic continuity checks (if the last + * fragment was received at least once). + * @param root_p points to the 'root' pbuf for the current datagram being assembled. + * @param new_p points to the pbuf for the current fragment + * @return 0 if invalid, >0 otherwise + */ +static int +ip_reass_chain_frag_into_datagram_and_validate(struct ip_reassdata *ipr, struct pbuf *new_p) +{ + struct ip_reass_helper *iprh, *iprh_tmp, *iprh_prev=NULL; + struct pbuf *q; + u16_t offset,len; + struct ip_hdr *fraghdr; + int valid = 1; + + /* Extract length and fragment offset from current fragment */ + fraghdr = (struct ip_hdr*)new_p->payload; + len = ntohs(IPH_LEN(fraghdr)) - IPH_HL(fraghdr) * 4; + offset = (ntohs(IPH_OFFSET(fraghdr)) & IP_OFFMASK) * 8; + + /* overwrite the fragment's ip header from the pbuf with our helper struct, + * and setup the embedded helper structure. */ + /* make sure the struct ip_reass_helper fits into the IP header */ + LWIP_ASSERT("sizeof(struct ip_reass_helper) <= IP_HLEN", + sizeof(struct ip_reass_helper) <= IP_HLEN); + iprh = (struct ip_reass_helper*)new_p->payload; + iprh->next_pbuf = NULL; + iprh->start = offset; + iprh->end = offset + len; + + /* Iterate through until we either get to the end of the list (append), + * or we find on with a larger offset (insert). */ + for (q = ipr->p; q != NULL;) { + iprh_tmp = (struct ip_reass_helper*)q->payload; + if (iprh->start < iprh_tmp->start) { + /* the new pbuf should be inserted before this */ + iprh->next_pbuf = q; + if (iprh_prev != NULL) { + /* not the fragment with the lowest offset */ +#if IP_REASS_CHECK_OVERLAP + if ((iprh->start < iprh_prev->end) || (iprh->end > iprh_tmp->start)) { + /* fragment overlaps with previous or following, throw away */ + goto freepbuf; + } +#endif /* IP_REASS_CHECK_OVERLAP */ + iprh_prev->next_pbuf = new_p; + } else { + /* fragment with the lowest offset */ + ipr->p = new_p; + } + break; + } else if(iprh->start == iprh_tmp->start) { + /* received the same datagram twice: no need to keep the datagram */ + goto freepbuf; +#if IP_REASS_CHECK_OVERLAP + } else if(iprh->start < iprh_tmp->end) { + /* overlap: no need to keep the new datagram */ + goto freepbuf; +#endif /* IP_REASS_CHECK_OVERLAP */ + } else { + /* Check if the fragments received so far have no wholes. */ + if (iprh_prev != NULL) { + if (iprh_prev->end != iprh_tmp->start) { + /* There is a fragment missing between the current + * and the previous fragment */ + valid = 0; + } + } + } + q = iprh_tmp->next_pbuf; + iprh_prev = iprh_tmp; + } + + /* If q is NULL, then we made it to the end of the list. Determine what to do now */ + if (q == NULL) { + if (iprh_prev != NULL) { + /* this is (for now), the fragment with the highest offset: + * chain it to the last fragment */ +#if IP_REASS_CHECK_OVERLAP + LWIP_ASSERT("check fragments don't overlap", iprh_prev->end <= iprh->start); +#endif /* IP_REASS_CHECK_OVERLAP */ + iprh_prev->next_pbuf = new_p; + if (iprh_prev->end != iprh->start) { + valid = 0; + } + } else { +#if IP_REASS_CHECK_OVERLAP + LWIP_ASSERT("no previous fragment, this must be the first fragment!", + ipr->p == NULL); +#endif /* IP_REASS_CHECK_OVERLAP */ + /* this is the first fragment we ever received for this ip datagram */ + ipr->p = new_p; + } + } + + /* At this point, the validation part begins: */ + /* If we already received the last fragment */ + if ((ipr->flags & IP_REASS_FLAG_LASTFRAG) != 0) { + /* and had no wholes so far */ + if (valid) { + /* then check if the rest of the fragments is here */ + /* Check if the queue starts with the first datagram */ + if (((struct ip_reass_helper*)ipr->p->payload)->start != 0) { + valid = 0; + } else { + /* and check that there are no wholes after this datagram */ + iprh_prev = iprh; + q = iprh->next_pbuf; + while (q != NULL) { + iprh = (struct ip_reass_helper*)q->payload; + if (iprh_prev->end != iprh->start) { + valid = 0; + break; + } + iprh_prev = iprh; + q = iprh->next_pbuf; + } + /* if still valid, all fragments are received + * (because to the MF==0 already arrived */ + if (valid) { + LWIP_ASSERT("sanity check", ipr->p != NULL); + LWIP_ASSERT("sanity check", + ((struct ip_reass_helper*)ipr->p->payload) != iprh); + LWIP_ASSERT("validate_datagram:next_pbuf!=NULL", + iprh->next_pbuf == NULL); + LWIP_ASSERT("validate_datagram:datagram end!=datagram len", + iprh->end == ipr->datagram_len); + } + } + } + /* If valid is 0 here, there are some fragments missing in the middle + * (since MF == 0 has already arrived). Such datagrams simply time out if + * no more fragments are received... */ + return valid; + } + /* If we come here, not all fragments were received, yet! */ + return 0; /* not yet valid! */ +#if IP_REASS_CHECK_OVERLAP +freepbuf: + ip_reass_pbufcount -= pbuf_clen(new_p); + pbuf_free(new_p); + return 0; +#endif /* IP_REASS_CHECK_OVERLAP */ +} + +/** + * Reassembles incoming IP fragments into an IP datagram. + * + * @param p points to a pbuf chain of the fragment + * @return NULL if reassembly is incomplete, ? otherwise + */ +struct pbuf * +ip_reass(struct pbuf *p) +{ + struct pbuf *r; + struct ip_hdr *fraghdr; + struct ip_reassdata *ipr; + struct ip_reass_helper *iprh; + u16_t offset, len; + u8_t clen; + struct ip_reassdata *ipr_prev = NULL; + + IPFRAG_STATS_INC(ip_frag.recv); + snmp_inc_ipreasmreqds(); + + fraghdr = (struct ip_hdr*)p->payload; + + if ((IPH_HL(fraghdr) * 4) != IP_HLEN) { + LWIP_DEBUGF(IP_REASS_DEBUG,("ip_reass: IP options currently not supported!\n")); + IPFRAG_STATS_INC(ip_frag.err); + goto nullreturn; + } + + offset = (ntohs(IPH_OFFSET(fraghdr)) & IP_OFFMASK) * 8; + len = ntohs(IPH_LEN(fraghdr)) - IPH_HL(fraghdr) * 4; + + /* Check if we are allowed to enqueue more datagrams. */ + clen = pbuf_clen(p); + if ((ip_reass_pbufcount + clen) > IP_REASS_MAX_PBUFS) { +#if IP_REASS_FREE_OLDEST + if (!ip_reass_remove_oldest_datagram(fraghdr, clen) || + ((ip_reass_pbufcount + clen) > IP_REASS_MAX_PBUFS)) +#endif /* IP_REASS_FREE_OLDEST */ + { + /* No datagram could be freed and still too many pbufs enqueued */ + LWIP_DEBUGF(IP_REASS_DEBUG,("ip_reass: Overflow condition: pbufct=%d, clen=%d, MAX=%d\n", + ip_reass_pbufcount, clen, IP_REASS_MAX_PBUFS)); + IPFRAG_STATS_INC(ip_frag.memerr); + /* @todo: send ICMP time exceeded here? */ + /* drop this pbuf */ + goto nullreturn; + } + } + + /* Look for the datagram the fragment belongs to in the current datagram queue, + * remembering the previous in the queue for later dequeueing. */ + for (ipr = reassdatagrams; ipr != NULL; ipr = ipr->next) { + /* Check if the incoming fragment matches the one currently present + in the reassembly buffer. If so, we proceed with copying the + fragment into the buffer. */ + if (IP_ADDRESSES_AND_ID_MATCH(&ipr->iphdr, fraghdr)) { + LWIP_DEBUGF(IP_REASS_DEBUG, ("ip_reass: matching previous fragment ID=%"X16_F"\n", + ntohs(IPH_ID(fraghdr)))); + IPFRAG_STATS_INC(ip_frag.cachehit); + break; + } + ipr_prev = ipr; + } + + if (ipr == NULL) { + /* Enqueue a new datagram into the datagram queue */ + ipr = ip_reass_enqueue_new_datagram(fraghdr, clen); + /* Bail if unable to enqueue */ + if(ipr == NULL) { + goto nullreturn; + } + } else { + if (((ntohs(IPH_OFFSET(fraghdr)) & IP_OFFMASK) == 0) && + ((ntohs(IPH_OFFSET(&ipr->iphdr)) & IP_OFFMASK) != 0)) { + /* ipr->iphdr is not the header from the first fragment, but fraghdr is + * -> copy fraghdr into ipr->iphdr since we want to have the header + * of the first fragment (for ICMP time exceeded and later, for copying + * all options, if supported)*/ + SMEMCPY(&ipr->iphdr, fraghdr, IP_HLEN); + } + } + /* Track the current number of pbufs current 'in-flight', in order to limit + the number of fragments that may be enqueued at any one time */ + ip_reass_pbufcount += clen; + + /* At this point, we have either created a new entry or pointing + * to an existing one */ + + /* check for 'no more fragments', and update queue entry*/ + if ((IPH_OFFSET(fraghdr) & PP_NTOHS(IP_MF)) == 0) { + ipr->flags |= IP_REASS_FLAG_LASTFRAG; + ipr->datagram_len = offset + len; + LWIP_DEBUGF(IP_REASS_DEBUG, + ("ip_reass: last fragment seen, total len %"S16_F"\n", + ipr->datagram_len)); + } + /* find the right place to insert this pbuf */ + /* @todo: trim pbufs if fragments are overlapping */ + if (ip_reass_chain_frag_into_datagram_and_validate(ipr, p)) { + /* the totally last fragment (flag more fragments = 0) was received at least + * once AND all fragments are received */ + ipr->datagram_len += IP_HLEN; + + /* save the second pbuf before copying the header over the pointer */ + r = ((struct ip_reass_helper*)ipr->p->payload)->next_pbuf; + + /* copy the original ip header back to the first pbuf */ + fraghdr = (struct ip_hdr*)(ipr->p->payload); + SMEMCPY(fraghdr, &ipr->iphdr, IP_HLEN); + IPH_LEN_SET(fraghdr, htons(ipr->datagram_len)); + IPH_OFFSET_SET(fraghdr, 0); + IPH_CHKSUM_SET(fraghdr, 0); + /* @todo: do we need to set calculate the correct checksum? */ + IPH_CHKSUM_SET(fraghdr, inet_chksum(fraghdr, IP_HLEN)); + + p = ipr->p; + + /* chain together the pbufs contained within the reass_data list. */ + while(r != NULL) { + iprh = (struct ip_reass_helper*)r->payload; + + /* hide the ip header for every succeding fragment */ + pbuf_header(r, -IP_HLEN); + pbuf_cat(p, r); + r = iprh->next_pbuf; + } + /* release the sources allocate for the fragment queue entry */ + ip_reass_dequeue_datagram(ipr, ipr_prev); + + /* and adjust the number of pbufs currently queued for reassembly. */ + ip_reass_pbufcount -= pbuf_clen(p); + + /* Return the pbuf chain */ + return p; + } + /* the datagram is not (yet?) reassembled completely */ + LWIP_DEBUGF(IP_REASS_DEBUG,("ip_reass_pbufcount: %d out\n", ip_reass_pbufcount)); + return NULL; + +nullreturn: + LWIP_DEBUGF(IP_REASS_DEBUG,("ip_reass: nullreturn\n")); + IPFRAG_STATS_INC(ip_frag.drop); + pbuf_free(p); + return NULL; +} +#endif /* IP_REASSEMBLY */ + +#if IP_FRAG +#if IP_FRAG_USES_STATIC_BUF +static u8_t buf[LWIP_MEM_ALIGN_SIZE(IP_FRAG_MAX_MTU + MEM_ALIGNMENT - 1)]; +#else /* IP_FRAG_USES_STATIC_BUF */ + +#if !LWIP_NETIF_TX_SINGLE_PBUF +/** Allocate a new struct pbuf_custom_ref */ +static struct pbuf_custom_ref* +ip_frag_alloc_pbuf_custom_ref(void) +{ + return (struct pbuf_custom_ref*)memp_malloc(MEMP_FRAG_PBUF); +} + +/** Free a struct pbuf_custom_ref */ +static void +ip_frag_free_pbuf_custom_ref(struct pbuf_custom_ref* p) +{ + LWIP_ASSERT("p != NULL", p != NULL); + memp_free(MEMP_FRAG_PBUF, p); +} + +/** Free-callback function to free a 'struct pbuf_custom_ref', called by + * pbuf_free. */ +static void +ipfrag_free_pbuf_custom(struct pbuf *p) +{ + struct pbuf_custom_ref *pcr = (struct pbuf_custom_ref*)p; + LWIP_ASSERT("pcr != NULL", pcr != NULL); + LWIP_ASSERT("pcr == p", (void*)pcr == (void*)p); + if (pcr->original != NULL) { + pbuf_free(pcr->original); + } + ip_frag_free_pbuf_custom_ref(pcr); +} +#endif /* !LWIP_NETIF_TX_SINGLE_PBUF */ +#endif /* IP_FRAG_USES_STATIC_BUF */ + +/** + * Fragment an IP datagram if too large for the netif. + * + * Chop the datagram in MTU sized chunks and send them in order + * by using a fixed size static memory buffer (PBUF_REF) or + * point PBUF_REFs into p (depending on IP_FRAG_USES_STATIC_BUF). + * + * @param p ip packet to send + * @param netif the netif on which to send + * @param dest destination ip address to which to send + * + * @return ERR_OK if sent successfully, err_t otherwise + */ +err_t +ip_frag(struct pbuf *p, struct netif *netif, ip_addr_t *dest) +{ + struct pbuf *rambuf; +#if IP_FRAG_USES_STATIC_BUF + struct pbuf *header; +#else +#if !LWIP_NETIF_TX_SINGLE_PBUF + struct pbuf *newpbuf; +#endif + struct ip_hdr *original_iphdr; +#endif + struct ip_hdr *iphdr; + u16_t nfb; + u16_t left, cop; + u16_t mtu = netif->mtu; + u16_t ofo, omf; + u16_t last; + u16_t poff = IP_HLEN; + u16_t tmp; +#if !IP_FRAG_USES_STATIC_BUF && !LWIP_NETIF_TX_SINGLE_PBUF + u16_t newpbuflen = 0; + u16_t left_to_copy; +#endif + + /* Get a RAM based MTU sized pbuf */ +#if IP_FRAG_USES_STATIC_BUF + /* When using a static buffer, we use a PBUF_REF, which we will + * use to reference the packet (without link header). + * Layer and length is irrelevant. + */ + rambuf = pbuf_alloc(PBUF_LINK, 0, PBUF_REF); + if (rambuf == NULL) { + LWIP_DEBUGF(IP_REASS_DEBUG, ("ip_frag: pbuf_alloc(PBUF_LINK, 0, PBUF_REF) failed\n")); + return ERR_MEM; + } + rambuf->tot_len = rambuf->len = mtu; + rambuf->payload = LWIP_MEM_ALIGN((void *)buf); + + /* Copy the IP header in it */ + iphdr = (struct ip_hdr *)rambuf->payload; + SMEMCPY(iphdr, p->payload, IP_HLEN); +#else /* IP_FRAG_USES_STATIC_BUF */ + original_iphdr = (struct ip_hdr *)p->payload; + iphdr = original_iphdr; +#endif /* IP_FRAG_USES_STATIC_BUF */ + + /* Save original offset */ + tmp = ntohs(IPH_OFFSET(iphdr)); + ofo = tmp & IP_OFFMASK; + omf = tmp & IP_MF; + + left = p->tot_len - IP_HLEN; + + nfb = (mtu - IP_HLEN) / 8; + + while (left) { + last = (left <= mtu - IP_HLEN); + + /* Set new offset and MF flag */ + tmp = omf | (IP_OFFMASK & (ofo)); + if (!last) { + tmp = tmp | IP_MF; + } + + /* Fill this fragment */ + cop = last ? left : nfb * 8; + +#if IP_FRAG_USES_STATIC_BUF + poff += pbuf_copy_partial(p, (u8_t*)iphdr + IP_HLEN, cop, poff); +#else /* IP_FRAG_USES_STATIC_BUF */ +#if LWIP_NETIF_TX_SINGLE_PBUF + rambuf = pbuf_alloc(PBUF_IP, cop, PBUF_RAM); + if (rambuf == NULL) { + return ERR_MEM; + } + LWIP_ASSERT("this needs a pbuf in one piece!", + (rambuf->len == rambuf->tot_len) && (rambuf->next == NULL)); + poff += pbuf_copy_partial(p, rambuf->payload, cop, poff); + /* make room for the IP header */ + if(pbuf_header(rambuf, IP_HLEN)) { + pbuf_free(rambuf); + return ERR_MEM; + } + /* fill in the IP header */ + SMEMCPY(rambuf->payload, original_iphdr, IP_HLEN); + iphdr = rambuf->payload; +#else /* LWIP_NETIF_TX_SINGLE_PBUF */ + /* When not using a static buffer, create a chain of pbufs. + * The first will be a PBUF_RAM holding the link and IP header. + * The rest will be PBUF_REFs mirroring the pbuf chain to be fragged, + * but limited to the size of an mtu. + */ + rambuf = pbuf_alloc(PBUF_LINK, IP_HLEN, PBUF_RAM); + if (rambuf == NULL) { + return ERR_MEM; + } + LWIP_ASSERT("this needs a pbuf in one piece!", + (p->len >= (IP_HLEN))); + SMEMCPY(rambuf->payload, original_iphdr, IP_HLEN); + iphdr = (struct ip_hdr *)rambuf->payload; + + /* Can just adjust p directly for needed offset. */ + p->payload = (u8_t *)p->payload + poff; + p->len -= poff; + + left_to_copy = cop; + while (left_to_copy) { + struct pbuf_custom_ref *pcr; + newpbuflen = (left_to_copy < p->len) ? left_to_copy : p->len; + /* Is this pbuf already empty? */ + if (!newpbuflen) { + p = p->next; + continue; + } + pcr = ip_frag_alloc_pbuf_custom_ref(); + if (pcr == NULL) { + pbuf_free(rambuf); + return ERR_MEM; + } + /* Mirror this pbuf, although we might not need all of it. */ + newpbuf = pbuf_alloced_custom(PBUF_RAW, newpbuflen, PBUF_REF, &pcr->pc, p->payload, newpbuflen); + if (newpbuf == NULL) { + ip_frag_free_pbuf_custom_ref(pcr); + pbuf_free(rambuf); + return ERR_MEM; + } + pbuf_ref(p); + pcr->original = p; + pcr->pc.custom_free_function = ipfrag_free_pbuf_custom; + + /* Add it to end of rambuf's chain, but using pbuf_cat, not pbuf_chain + * so that it is removed when pbuf_dechain is later called on rambuf. + */ + pbuf_cat(rambuf, newpbuf); + left_to_copy -= newpbuflen; + if (left_to_copy) { + p = p->next; + } + } + poff = newpbuflen; +#endif /* LWIP_NETIF_TX_SINGLE_PBUF */ +#endif /* IP_FRAG_USES_STATIC_BUF */ + + /* Correct header */ + IPH_OFFSET_SET(iphdr, htons(tmp)); + IPH_LEN_SET(iphdr, htons(cop + IP_HLEN)); + IPH_CHKSUM_SET(iphdr, 0); + IPH_CHKSUM_SET(iphdr, inet_chksum(iphdr, IP_HLEN)); + +#if IP_FRAG_USES_STATIC_BUF + if (last) { + pbuf_realloc(rambuf, left + IP_HLEN); + } + + /* This part is ugly: we alloc a RAM based pbuf for + * the link level header for each chunk and then + * free it.A PBUF_ROM style pbuf for which pbuf_header + * worked would make things simpler. + */ + header = pbuf_alloc(PBUF_LINK, 0, PBUF_RAM); + if (header != NULL) { + pbuf_chain(header, rambuf); + netif->output(netif, header, dest); + IPFRAG_STATS_INC(ip_frag.xmit); + snmp_inc_ipfragcreates(); + pbuf_free(header); + } else { + LWIP_DEBUGF(IP_REASS_DEBUG, ("ip_frag: pbuf_alloc() for header failed\n")); + pbuf_free(rambuf); + return ERR_MEM; + } +#else /* IP_FRAG_USES_STATIC_BUF */ + /* No need for separate header pbuf - we allowed room for it in rambuf + * when allocated. + */ + netif->output(netif, rambuf, dest); + IPFRAG_STATS_INC(ip_frag.xmit); + + /* Unfortunately we can't reuse rambuf - the hardware may still be + * using the buffer. Instead we free it (and the ensuing chain) and + * recreate it next time round the loop. If we're lucky the hardware + * will have already sent the packet, the free will really free, and + * there will be zero memory penalty. + */ + + pbuf_free(rambuf); +#endif /* IP_FRAG_USES_STATIC_BUF */ + left -= cop; + ofo += nfb; + } +#if IP_FRAG_USES_STATIC_BUF + pbuf_free(rambuf); +#endif /* IP_FRAG_USES_STATIC_BUF */ + snmp_inc_ipfragoks(); + return ERR_OK; +} +#endif /* IP_FRAG */ diff --git a/features/unsupported/net/lwip/lwip/core/mem.c b/features/unsupported/net/lwip/lwip/core/mem.c new file mode 100644 index 00000000000..7ebe3041388 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/core/mem.c @@ -0,0 +1,657 @@ +/** + * @file + * Dynamic memory manager + * + * This is a lightweight replacement for the standard C library malloc(). + * + * If you want to use the standard C library malloc() instead, define + * MEM_LIBC_MALLOC to 1 in your lwipopts.h + * + * To let mem_malloc() use pools (prevents fragmentation and is much faster than + * a heap but might waste some memory), define MEM_USE_POOLS to 1, define + * MEM_USE_CUSTOM_POOLS to 1 and create a file "lwippools.h" that includes a list + * of pools like this (more pools can be added between _START and _END): + * + * Define three pools with sizes 256, 512, and 1512 bytes + * LWIP_MALLOC_MEMPOOL_START + * LWIP_MALLOC_MEMPOOL(20, 256) + * LWIP_MALLOC_MEMPOOL(10, 512) + * LWIP_MALLOC_MEMPOOL(5, 1512) + * LWIP_MALLOC_MEMPOOL_END + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * Simon Goldschmidt + * + */ + +#include "lwip/opt.h" + +#if !MEM_LIBC_MALLOC /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/def.h" +#include "lwip/mem.h" +#include "lwip/sys.h" +#include "lwip/stats.h" +#include "lwip/err.h" + +#include + +#if MEM_USE_POOLS +/* lwIP head implemented with different sized pools */ + +/** + * Allocate memory: determine the smallest pool that is big enough + * to contain an element of 'size' and get an element from that pool. + * + * @param size the size in bytes of the memory needed + * @return a pointer to the allocated memory or NULL if the pool is empty + */ +void * +mem_malloc(mem_size_t size) +{ + struct memp_malloc_helper *element; + memp_t poolnr; + mem_size_t required_size = size + sizeof(struct memp_malloc_helper); + + for (poolnr = MEMP_POOL_FIRST; poolnr <= MEMP_POOL_LAST; poolnr = (memp_t)(poolnr + 1)) { +#if MEM_USE_POOLS_TRY_BIGGER_POOL +again: +#endif /* MEM_USE_POOLS_TRY_BIGGER_POOL */ + /* is this pool big enough to hold an element of the required size + plus a struct memp_malloc_helper that saves the pool this element came from? */ + if (required_size <= memp_sizes[poolnr]) { + break; + } + } + if (poolnr > MEMP_POOL_LAST) { + LWIP_ASSERT("mem_malloc(): no pool is that big!", 0); + return NULL; + } + element = (struct memp_malloc_helper*)memp_malloc(poolnr); + if (element == NULL) { + /* No need to DEBUGF or ASSERT: This error is already + taken care of in memp.c */ +#if MEM_USE_POOLS_TRY_BIGGER_POOL + /** Try a bigger pool if this one is empty! */ + if (poolnr < MEMP_POOL_LAST) { + poolnr++; + goto again; + } +#endif /* MEM_USE_POOLS_TRY_BIGGER_POOL */ + return NULL; + } + + /* save the pool number this element came from */ + element->poolnr = poolnr; + /* and return a pointer to the memory directly after the struct memp_malloc_helper */ + element++; + + return element; +} + +/** + * Free memory previously allocated by mem_malloc. Loads the pool number + * and calls memp_free with that pool number to put the element back into + * its pool + * + * @param rmem the memory element to free + */ +void +mem_free(void *rmem) +{ + struct memp_malloc_helper *hmem = (struct memp_malloc_helper*)rmem; + + LWIP_ASSERT("rmem != NULL", (rmem != NULL)); + LWIP_ASSERT("rmem == MEM_ALIGN(rmem)", (rmem == LWIP_MEM_ALIGN(rmem))); + + /* get the original struct memp_malloc_helper */ + hmem--; + + LWIP_ASSERT("hmem != NULL", (hmem != NULL)); + LWIP_ASSERT("hmem == MEM_ALIGN(hmem)", (hmem == LWIP_MEM_ALIGN(hmem))); + LWIP_ASSERT("hmem->poolnr < MEMP_MAX", (hmem->poolnr < MEMP_MAX)); + + /* and put it in the pool we saved earlier */ + memp_free(hmem->poolnr, hmem); +} + +#else /* MEM_USE_POOLS */ +/* lwIP replacement for your libc malloc() */ + +/** + * The heap is made up as a list of structs of this type. + * This does not have to be aligned since for getting its size, + * we only use the macro SIZEOF_STRUCT_MEM, which automatically alignes. + */ +struct mem { + /** index (-> ram[next]) of the next struct */ + mem_size_t next; + /** index (-> ram[prev]) of the previous struct */ + mem_size_t prev; + /** 1: this area is used; 0: this area is unused */ + u8_t used; +}; + +/** All allocated blocks will be MIN_SIZE bytes big, at least! + * MIN_SIZE can be overridden to suit your needs. Smaller values save space, + * larger values could prevent too small blocks to fragment the RAM too much. */ +#ifndef MIN_SIZE +#define MIN_SIZE 12 +#endif /* MIN_SIZE */ +/* some alignment macros: we define them here for better source code layout */ +#define MIN_SIZE_ALIGNED LWIP_MEM_ALIGN_SIZE(MIN_SIZE) +#define SIZEOF_STRUCT_MEM LWIP_MEM_ALIGN_SIZE(sizeof(struct mem)) +#define MEM_SIZE_ALIGNED LWIP_MEM_ALIGN_SIZE(MEM_SIZE) + +/** If you want to relocate the heap to external memory, simply define + * LWIP_RAM_HEAP_POINTER as a void-pointer to that location. + * If so, make sure the memory at that location is big enough (see below on + * how that space is calculated). */ +#ifndef LWIP_RAM_HEAP_POINTER + +#if defined(TARGET_LPC4088) || defined(TARGET_LPC4088_DM) +# if defined (__ICCARM__) +# define ETHMEM_SECTION +# elif defined(TOOLCHAIN_GCC_CR) +# define ETHMEM_SECTION __attribute__((section(".data.$RamPeriph32"))) +# else +# define ETHMEM_SECTION __attribute__((section("AHBSRAM1"),aligned)) +# endif +#elif defined(TARGET_LPC1768) +# define ETHMEM_SECTION __attribute((section("AHBSRAM0"))) +#else +# define ETHMEM_SECTION +#endif + +/** the heap. we need one struct mem at the end and some room for alignment */ +u8_t ram_heap[MEM_SIZE_ALIGNED + (2*SIZEOF_STRUCT_MEM) + MEM_ALIGNMENT] ETHMEM_SECTION; +#define LWIP_RAM_HEAP_POINTER ram_heap +#endif /* LWIP_RAM_HEAP_POINTER */ + +/** pointer to the heap (ram_heap): for alignment, ram is now a pointer instead of an array */ +static u8_t *ram; +/** the last entry, always unused! */ +static struct mem *ram_end; +/** pointer to the lowest free block, this is used for faster search */ +static struct mem *lfree; + +/** concurrent access protection */ +static sys_mutex_t mem_mutex; + +#if LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT + +static volatile u8_t mem_free_count; + +/* Allow mem_free from other (e.g. interrupt) context */ +#define LWIP_MEM_FREE_DECL_PROTECT() SYS_ARCH_DECL_PROTECT(lev_free) +#define LWIP_MEM_FREE_PROTECT() SYS_ARCH_PROTECT(lev_free) +#define LWIP_MEM_FREE_UNPROTECT() SYS_ARCH_UNPROTECT(lev_free) +#define LWIP_MEM_ALLOC_DECL_PROTECT() SYS_ARCH_DECL_PROTECT(lev_alloc) +#define LWIP_MEM_ALLOC_PROTECT() SYS_ARCH_PROTECT(lev_alloc) +#define LWIP_MEM_ALLOC_UNPROTECT() SYS_ARCH_UNPROTECT(lev_alloc) + +#else /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */ + +/* Protect the heap only by using a semaphore */ +#define LWIP_MEM_FREE_DECL_PROTECT() +#define LWIP_MEM_FREE_PROTECT() sys_mutex_lock(&mem_mutex) +#define LWIP_MEM_FREE_UNPROTECT() sys_mutex_unlock(&mem_mutex) +/* mem_malloc is protected using semaphore AND LWIP_MEM_ALLOC_PROTECT */ +#define LWIP_MEM_ALLOC_DECL_PROTECT() +#define LWIP_MEM_ALLOC_PROTECT() +#define LWIP_MEM_ALLOC_UNPROTECT() + +#endif /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */ + + +/** + * "Plug holes" by combining adjacent empty struct mems. + * After this function is through, there should not exist + * one empty struct mem pointing to another empty struct mem. + * + * @param mem this points to a struct mem which just has been freed + * @internal this function is only called by mem_free() and mem_trim() + * + * This assumes access to the heap is protected by the calling function + * already. + */ +static void +plug_holes(struct mem *mem) +{ + struct mem *nmem; + struct mem *pmem; + + LWIP_ASSERT("plug_holes: mem >= ram", (u8_t *)mem >= ram); + LWIP_ASSERT("plug_holes: mem < ram_end", (u8_t *)mem < (u8_t *)ram_end); + LWIP_ASSERT("plug_holes: mem->used == 0", mem->used == 0); + + /* plug hole forward */ + LWIP_ASSERT("plug_holes: mem->next <= MEM_SIZE_ALIGNED", mem->next <= MEM_SIZE_ALIGNED); + + nmem = (struct mem *)(void *)&ram[mem->next]; + if (mem != nmem && nmem->used == 0 && (u8_t *)nmem != (u8_t *)ram_end) { + /* if mem->next is unused and not end of ram, combine mem and mem->next */ + if (lfree == nmem) { + lfree = mem; + } + mem->next = nmem->next; + ((struct mem *)(void *)&ram[nmem->next])->prev = (mem_size_t)((u8_t *)mem - ram); + } + + /* plug hole backward */ + pmem = (struct mem *)(void *)&ram[mem->prev]; + if (pmem != mem && pmem->used == 0) { + /* if mem->prev is unused, combine mem and mem->prev */ + if (lfree == mem) { + lfree = pmem; + } + pmem->next = mem->next; + ((struct mem *)(void *)&ram[mem->next])->prev = (mem_size_t)((u8_t *)pmem - ram); + } +} + +/** + * Zero the heap and initialize start, end and lowest-free + */ +void +mem_init(void) +{ + struct mem *mem; + + LWIP_ASSERT("Sanity check alignment", + (SIZEOF_STRUCT_MEM & (MEM_ALIGNMENT-1)) == 0); + + /* align the heap */ + ram = (u8_t *)LWIP_MEM_ALIGN(LWIP_RAM_HEAP_POINTER); + /* initialize the start of the heap */ + mem = (struct mem *)(void *)ram; + mem->next = MEM_SIZE_ALIGNED; + mem->prev = 0; + mem->used = 0; + /* initialize the end of the heap */ + ram_end = (struct mem *)(void *)&ram[MEM_SIZE_ALIGNED]; + ram_end->used = 1; + ram_end->next = MEM_SIZE_ALIGNED; + ram_end->prev = MEM_SIZE_ALIGNED; + + /* initialize the lowest-free pointer to the start of the heap */ + lfree = (struct mem *)(void *)ram; + + MEM_STATS_AVAIL(avail, MEM_SIZE_ALIGNED); + + if(sys_mutex_new(&mem_mutex) != ERR_OK) { + LWIP_ASSERT("failed to create mem_mutex", 0); + } +} + +/** + * Put a struct mem back on the heap + * + * @param rmem is the data portion of a struct mem as returned by a previous + * call to mem_malloc() + */ +void +mem_free(void *rmem) +{ + struct mem *mem; + LWIP_MEM_FREE_DECL_PROTECT(); + + if (rmem == NULL) { + LWIP_DEBUGF(MEM_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS, ("mem_free(p == NULL) was called.\n")); + return; + } + LWIP_ASSERT("mem_free: sanity check alignment", (((mem_ptr_t)rmem) & (MEM_ALIGNMENT-1)) == 0); + + LWIP_ASSERT("mem_free: legal memory", (u8_t *)rmem >= (u8_t *)ram && + (u8_t *)rmem < (u8_t *)ram_end); + + if ((u8_t *)rmem < (u8_t *)ram || (u8_t *)rmem >= (u8_t *)ram_end) { + SYS_ARCH_DECL_PROTECT(lev); + LWIP_DEBUGF(MEM_DEBUG | LWIP_DBG_LEVEL_SEVERE, ("mem_free: illegal memory\n")); + /* protect mem stats from concurrent access */ + SYS_ARCH_PROTECT(lev); + MEM_STATS_INC(illegal); + SYS_ARCH_UNPROTECT(lev); + return; + } + /* protect the heap from concurrent access */ + LWIP_MEM_FREE_PROTECT(); + /* Get the corresponding struct mem ... */ + mem = (struct mem *)(void *)((u8_t *)rmem - SIZEOF_STRUCT_MEM); + /* ... which has to be in a used state ... */ + LWIP_ASSERT("mem_free: mem->used", mem->used); + /* ... and is now unused. */ + mem->used = 0; + + if (mem < lfree) { + /* the newly freed struct is now the lowest */ + lfree = mem; + } + + MEM_STATS_DEC_USED(used, mem->next - (mem_size_t)(((u8_t *)mem - ram))); + + /* finally, see if prev or next are free also */ + plug_holes(mem); +#if LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT + mem_free_count = 1; +#endif /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */ + LWIP_MEM_FREE_UNPROTECT(); +} + +/** + * Shrink memory returned by mem_malloc(). + * + * @param rmem pointer to memory allocated by mem_malloc the is to be shrinked + * @param newsize required size after shrinking (needs to be smaller than or + * equal to the previous size) + * @return for compatibility reasons: is always == rmem, at the moment + * or NULL if newsize is > old size, in which case rmem is NOT touched + * or freed! + */ +void * +mem_trim(void *rmem, mem_size_t newsize) +{ + mem_size_t size; + mem_size_t ptr, ptr2; + struct mem *mem, *mem2; + /* use the FREE_PROTECT here: it protects with sem OR SYS_ARCH_PROTECT */ + LWIP_MEM_FREE_DECL_PROTECT(); + + /* Expand the size of the allocated memory region so that we can + adjust for alignment. */ + newsize = LWIP_MEM_ALIGN_SIZE(newsize); + + if(newsize < MIN_SIZE_ALIGNED) { + /* every data block must be at least MIN_SIZE_ALIGNED long */ + newsize = MIN_SIZE_ALIGNED; + } + + if (newsize > MEM_SIZE_ALIGNED) { + return NULL; + } + + LWIP_ASSERT("mem_trim: legal memory", (u8_t *)rmem >= (u8_t *)ram && + (u8_t *)rmem < (u8_t *)ram_end); + + if ((u8_t *)rmem < (u8_t *)ram || (u8_t *)rmem >= (u8_t *)ram_end) { + SYS_ARCH_DECL_PROTECT(lev); + LWIP_DEBUGF(MEM_DEBUG | LWIP_DBG_LEVEL_SEVERE, ("mem_trim: illegal memory\n")); + /* protect mem stats from concurrent access */ + SYS_ARCH_PROTECT(lev); + MEM_STATS_INC(illegal); + SYS_ARCH_UNPROTECT(lev); + return rmem; + } + /* Get the corresponding struct mem ... */ + mem = (struct mem *)(void *)((u8_t *)rmem - SIZEOF_STRUCT_MEM); + /* ... and its offset pointer */ + ptr = (mem_size_t)((u8_t *)mem - ram); + + size = mem->next - ptr - SIZEOF_STRUCT_MEM; + LWIP_ASSERT("mem_trim can only shrink memory", newsize <= size); + if (newsize > size) { + /* not supported */ + return NULL; + } + if (newsize == size) { + /* No change in size, simply return */ + return rmem; + } + + /* protect the heap from concurrent access */ + LWIP_MEM_FREE_PROTECT(); + + mem2 = (struct mem *)(void *)&ram[mem->next]; + if(mem2->used == 0) { + /* The next struct is unused, we can simply move it at little */ + mem_size_t next; + /* remember the old next pointer */ + next = mem2->next; + /* create new struct mem which is moved directly after the shrinked mem */ + ptr2 = ptr + SIZEOF_STRUCT_MEM + newsize; + if (lfree == mem2) { + lfree = (struct mem *)(void *)&ram[ptr2]; + } + mem2 = (struct mem *)(void *)&ram[ptr2]; + mem2->used = 0; + /* restore the next pointer */ + mem2->next = next; + /* link it back to mem */ + mem2->prev = ptr; + /* link mem to it */ + mem->next = ptr2; + /* last thing to restore linked list: as we have moved mem2, + * let 'mem2->next->prev' point to mem2 again. but only if mem2->next is not + * the end of the heap */ + if (mem2->next != MEM_SIZE_ALIGNED) { + ((struct mem *)(void *)&ram[mem2->next])->prev = ptr2; + } + MEM_STATS_DEC_USED(used, (size - newsize)); + /* no need to plug holes, we've already done that */ + } else if (newsize + SIZEOF_STRUCT_MEM + MIN_SIZE_ALIGNED <= size) { + /* Next struct is used but there's room for another struct mem with + * at least MIN_SIZE_ALIGNED of data. + * Old size ('size') must be big enough to contain at least 'newsize' plus a struct mem + * ('SIZEOF_STRUCT_MEM') with some data ('MIN_SIZE_ALIGNED'). + * @todo we could leave out MIN_SIZE_ALIGNED. We would create an empty + * region that couldn't hold data, but when mem->next gets freed, + * the 2 regions would be combined, resulting in more free memory */ + ptr2 = ptr + SIZEOF_STRUCT_MEM + newsize; + mem2 = (struct mem *)(void *)&ram[ptr2]; + if (mem2 < lfree) { + lfree = mem2; + } + mem2->used = 0; + mem2->next = mem->next; + mem2->prev = ptr; + mem->next = ptr2; + if (mem2->next != MEM_SIZE_ALIGNED) { + ((struct mem *)(void *)&ram[mem2->next])->prev = ptr2; + } + MEM_STATS_DEC_USED(used, (size - newsize)); + /* the original mem->next is used, so no need to plug holes! */ + } + /* else { + next struct mem is used but size between mem and mem2 is not big enough + to create another struct mem + -> don't do anyhting. + -> the remaining space stays unused since it is too small + } */ +#if LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT + mem_free_count = 1; +#endif /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */ + LWIP_MEM_FREE_UNPROTECT(); + return rmem; +} + +/** + * Adam's mem_malloc() plus solution for bug #17922 + * Allocate a block of memory with a minimum of 'size' bytes. + * + * @param size is the minimum size of the requested block in bytes. + * @return pointer to allocated memory or NULL if no free memory was found. + * + * Note that the returned value will always be aligned (as defined by MEM_ALIGNMENT). + */ +void * +mem_malloc(mem_size_t size) +{ + mem_size_t ptr, ptr2; + struct mem *mem, *mem2; +#if LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT + u8_t local_mem_free_count = 0; +#endif /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */ + LWIP_MEM_ALLOC_DECL_PROTECT(); + + if (size == 0) { + return NULL; + } + + /* Expand the size of the allocated memory region so that we can + adjust for alignment. */ + size = LWIP_MEM_ALIGN_SIZE(size); + + if(size < MIN_SIZE_ALIGNED) { + /* every data block must be at least MIN_SIZE_ALIGNED long */ + size = MIN_SIZE_ALIGNED; + } + + if (size > MEM_SIZE_ALIGNED) { + return NULL; + } + + /* protect the heap from concurrent access */ + sys_mutex_lock(&mem_mutex); + LWIP_MEM_ALLOC_PROTECT(); +#if LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT + /* run as long as a mem_free disturbed mem_malloc */ + do { + local_mem_free_count = 0; +#endif /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */ + + /* Scan through the heap searching for a free block that is big enough, + * beginning with the lowest free block. + */ + for (ptr = (mem_size_t)((u8_t *)lfree - ram); ptr < MEM_SIZE_ALIGNED - size; + ptr = ((struct mem *)(void *)&ram[ptr])->next) { + mem = (struct mem *)(void *)&ram[ptr]; +#if LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT + mem_free_count = 0; + LWIP_MEM_ALLOC_UNPROTECT(); + /* allow mem_free to run */ + LWIP_MEM_ALLOC_PROTECT(); + if (mem_free_count != 0) { + local_mem_free_count = mem_free_count; + } + mem_free_count = 0; +#endif /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */ + + if ((!mem->used) && + (mem->next - (ptr + SIZEOF_STRUCT_MEM)) >= size) { + /* mem is not used and at least perfect fit is possible: + * mem->next - (ptr + SIZEOF_STRUCT_MEM) gives us the 'user data size' of mem */ + + if (mem->next - (ptr + SIZEOF_STRUCT_MEM) >= (size + SIZEOF_STRUCT_MEM + MIN_SIZE_ALIGNED)) { + /* (in addition to the above, we test if another struct mem (SIZEOF_STRUCT_MEM) containing + * at least MIN_SIZE_ALIGNED of data also fits in the 'user data space' of 'mem') + * -> split large block, create empty remainder, + * remainder must be large enough to contain MIN_SIZE_ALIGNED data: if + * mem->next - (ptr + (2*SIZEOF_STRUCT_MEM)) == size, + * struct mem would fit in but no data between mem2 and mem2->next + * @todo we could leave out MIN_SIZE_ALIGNED. We would create an empty + * region that couldn't hold data, but when mem->next gets freed, + * the 2 regions would be combined, resulting in more free memory + */ + ptr2 = ptr + SIZEOF_STRUCT_MEM + size; + /* create mem2 struct */ + mem2 = (struct mem *)(void *)&ram[ptr2]; + mem2->used = 0; + mem2->next = mem->next; + mem2->prev = ptr; + /* and insert it between mem and mem->next */ + mem->next = ptr2; + mem->used = 1; + + if (mem2->next != MEM_SIZE_ALIGNED) { + ((struct mem *)(void *)&ram[mem2->next])->prev = ptr2; + } + MEM_STATS_INC_USED(used, (size + SIZEOF_STRUCT_MEM)); + } else { + /* (a mem2 struct does no fit into the user data space of mem and mem->next will always + * be used at this point: if not we have 2 unused structs in a row, plug_holes should have + * take care of this). + * -> near fit or excact fit: do not split, no mem2 creation + * also can't move mem->next directly behind mem, since mem->next + * will always be used at this point! + */ + mem->used = 1; + MEM_STATS_INC_USED(used, mem->next - (mem_size_t)((u8_t *)mem - ram)); + } + + if (mem == lfree) { + /* Find next free block after mem and update lowest free pointer */ + while (lfree->used && lfree != ram_end) { + LWIP_MEM_ALLOC_UNPROTECT(); + /* prevent high interrupt latency... */ + LWIP_MEM_ALLOC_PROTECT(); + lfree = (struct mem *)(void *)&ram[lfree->next]; + } + LWIP_ASSERT("mem_malloc: !lfree->used", ((lfree == ram_end) || (!lfree->used))); + } + LWIP_MEM_ALLOC_UNPROTECT(); + sys_mutex_unlock(&mem_mutex); + LWIP_ASSERT("mem_malloc: allocated memory not above ram_end.", + (mem_ptr_t)mem + SIZEOF_STRUCT_MEM + size <= (mem_ptr_t)ram_end); + LWIP_ASSERT("mem_malloc: allocated memory properly aligned.", + ((mem_ptr_t)mem + SIZEOF_STRUCT_MEM) % MEM_ALIGNMENT == 0); + LWIP_ASSERT("mem_malloc: sanity check alignment", + (((mem_ptr_t)mem) & (MEM_ALIGNMENT-1)) == 0); + + return (u8_t *)mem + SIZEOF_STRUCT_MEM; + } + } +#if LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT + /* if we got interrupted by a mem_free, try again */ + } while(local_mem_free_count != 0); +#endif /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */ + LWIP_DEBUGF(MEM_DEBUG | LWIP_DBG_LEVEL_SERIOUS, ("mem_malloc: could not allocate %"S16_F" bytes\n", (s16_t)size)); + MEM_STATS_INC(err); + LWIP_MEM_ALLOC_UNPROTECT(); + sys_mutex_unlock(&mem_mutex); + return NULL; +} + +#endif /* MEM_USE_POOLS */ +/** + * Contiguously allocates enough space for count objects that are size bytes + * of memory each and returns a pointer to the allocated memory. + * + * The allocated memory is filled with bytes of value zero. + * + * @param count number of objects to allocate + * @param size size of the objects to allocate + * @return pointer to allocated memory / NULL pointer if there is an error + */ +void *mem_calloc(mem_size_t count, mem_size_t size) +{ + void *p; + + /* allocate 'count' objects of size 'size' */ + p = mem_malloc(count * size); + if (p) { + /* zero the memory */ + memset(p, 0, count * size); + } + return p; +} + +#endif /* !MEM_LIBC_MALLOC */ diff --git a/features/unsupported/net/lwip/lwip/core/memp.c b/features/unsupported/net/lwip/lwip/core/memp.c new file mode 100644 index 00000000000..19bc5579dba --- /dev/null +++ b/features/unsupported/net/lwip/lwip/core/memp.c @@ -0,0 +1,475 @@ +/** + * @file + * Dynamic pool memory manager + * + * lwIP has dedicated pools for many structures (netconn, protocol control blocks, + * packet buffers, ...). All these pools are managed here. + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ + +#include "lwip/opt.h" + +#include "lwip/memp.h" +#include "lwip/pbuf.h" +#include "lwip/udp.h" +#include "lwip/raw.h" +#include "lwip/tcp_impl.h" +#include "lwip/igmp.h" +#include "lwip/api.h" +#include "lwip/api_msg.h" +#include "lwip/tcpip.h" +#include "lwip/sys.h" +#include "lwip/timers.h" +#include "lwip/stats.h" +#include "netif/etharp.h" +#include "lwip/ip_frag.h" +#include "lwip/snmp_structs.h" +#include "lwip/snmp_msg.h" +#include "lwip/dns.h" +#include "netif/ppp_oe.h" + +#include + +#if !MEMP_MEM_MALLOC /* don't build if not configured for use in lwipopts.h */ + +struct memp { + struct memp *next; +#if MEMP_OVERFLOW_CHECK + const char *file; + int line; +#endif /* MEMP_OVERFLOW_CHECK */ +}; + +#if MEMP_OVERFLOW_CHECK +/* if MEMP_OVERFLOW_CHECK is turned on, we reserve some bytes at the beginning + * and at the end of each element, initialize them as 0xcd and check + * them later. */ +/* If MEMP_OVERFLOW_CHECK is >= 2, on every call to memp_malloc or memp_free, + * every single element in each pool is checked! + * This is VERY SLOW but also very helpful. */ +/* MEMP_SANITY_REGION_BEFORE and MEMP_SANITY_REGION_AFTER can be overridden in + * lwipopts.h to change the amount reserved for checking. */ +#ifndef MEMP_SANITY_REGION_BEFORE +#define MEMP_SANITY_REGION_BEFORE 16 +#endif /* MEMP_SANITY_REGION_BEFORE*/ +#if MEMP_SANITY_REGION_BEFORE > 0 +#define MEMP_SANITY_REGION_BEFORE_ALIGNED LWIP_MEM_ALIGN_SIZE(MEMP_SANITY_REGION_BEFORE) +#else +#define MEMP_SANITY_REGION_BEFORE_ALIGNED 0 +#endif /* MEMP_SANITY_REGION_BEFORE*/ +#ifndef MEMP_SANITY_REGION_AFTER +#define MEMP_SANITY_REGION_AFTER 16 +#endif /* MEMP_SANITY_REGION_AFTER*/ +#if MEMP_SANITY_REGION_AFTER > 0 +#define MEMP_SANITY_REGION_AFTER_ALIGNED LWIP_MEM_ALIGN_SIZE(MEMP_SANITY_REGION_AFTER) +#else +#define MEMP_SANITY_REGION_AFTER_ALIGNED 0 +#endif /* MEMP_SANITY_REGION_AFTER*/ + +/* MEMP_SIZE: save space for struct memp and for sanity check */ +#define MEMP_SIZE (LWIP_MEM_ALIGN_SIZE(sizeof(struct memp)) + MEMP_SANITY_REGION_BEFORE_ALIGNED) +#define MEMP_ALIGN_SIZE(x) (LWIP_MEM_ALIGN_SIZE(x) + MEMP_SANITY_REGION_AFTER_ALIGNED) + +#else /* MEMP_OVERFLOW_CHECK */ + +/* No sanity checks + * We don't need to preserve the struct memp while not allocated, so we + * can save a little space and set MEMP_SIZE to 0. + */ +#define MEMP_SIZE 0 +#define MEMP_ALIGN_SIZE(x) (LWIP_MEM_ALIGN_SIZE(x)) + +#endif /* MEMP_OVERFLOW_CHECK */ + +/** This array holds the first free element of each pool. + * Elements form a linked list. */ +static struct memp *memp_tab[MEMP_MAX]; + +#else /* MEMP_MEM_MALLOC */ + +#define MEMP_ALIGN_SIZE(x) (LWIP_MEM_ALIGN_SIZE(x)) + +#endif /* MEMP_MEM_MALLOC */ + +/** This array holds the element sizes of each pool. */ +#if !MEM_USE_POOLS && !MEMP_MEM_MALLOC +static +#endif +const u16_t memp_sizes[MEMP_MAX] = { +#define LWIP_MEMPOOL(name,num,size,desc) LWIP_MEM_ALIGN_SIZE(size), +#include "lwip/memp_std.h" +}; + +#if !MEMP_MEM_MALLOC /* don't build if not configured for use in lwipopts.h */ + +/** This array holds the number of elements in each pool. */ +static const u16_t memp_num[MEMP_MAX] = { +#define LWIP_MEMPOOL(name,num,size,desc) (num), +#include "lwip/memp_std.h" +}; + +/** This array holds a textual description of each pool. */ +#ifdef LWIP_DEBUG +static const char *memp_desc[MEMP_MAX] = { +#define LWIP_MEMPOOL(name,num,size,desc) (desc), +#include "lwip/memp_std.h" +}; +#endif /* LWIP_DEBUG */ + +#if MEMP_SEPARATE_POOLS + +/** This creates each memory pool. These are named memp_memory_XXX_base (where + * XXX is the name of the pool defined in memp_std.h). + * To relocate a pool, declare it as extern in cc.h. Example for GCC: + * extern u8_t __attribute__((section(".onchip_mem"))) memp_memory_UDP_PCB_base[]; + */ +#define LWIP_MEMPOOL(name,num,size,desc) u8_t memp_memory_ ## name ## _base \ + [((num) * (MEMP_SIZE + MEMP_ALIGN_SIZE(size)))]; +#include "lwip/memp_std.h" + +/** This array holds the base of each memory pool. */ +static u8_t *const memp_bases[] = { +#define LWIP_MEMPOOL(name,num,size,desc) memp_memory_ ## name ## _base, +#include "lwip/memp_std.h" +}; + +#else /* MEMP_SEPARATE_POOLS */ + +#if defined(TARGET_LPC1768) +# define ETHMEM_SECTION __attribute((section("AHBSRAM1"))) +#else +# define ETHMEM_SECTION +#endif + +/** This is the actual memory used by the pools (all pools in one big block). */ +static u8_t memp_memory[MEM_ALIGNMENT - 1 +#define LWIP_MEMPOOL(name,num,size,desc) + ( (num) * (MEMP_SIZE + MEMP_ALIGN_SIZE(size) ) ) +#include "lwip/memp_std.h" +] ETHMEM_SECTION; + +#endif /* MEMP_SEPARATE_POOLS */ + +#if MEMP_SANITY_CHECK +/** + * Check that memp-lists don't form a circle + */ +static int +memp_sanity(void) +{ + s16_t i, c; + struct memp *m, *n; + + for (i = 0; i < MEMP_MAX; i++) { + for (m = memp_tab[i]; m != NULL; m = m->next) { + c = 1; + for (n = memp_tab[i]; n != NULL; n = n->next) { + if (n == m && --c < 0) { + return 0; + } + } + } + } + return 1; +} +#endif /* MEMP_SANITY_CHECK*/ +#if MEMP_OVERFLOW_CHECK +#if defined(LWIP_DEBUG) && MEMP_STATS +static const char * memp_overflow_names[] = { +#define LWIP_MEMPOOL(name,num,size,desc) "/"desc, +#include "lwip/memp_std.h" + }; +#endif + +/** + * Check if a memp element was victim of an overflow + * (e.g. the restricted area after it has been altered) + * + * @param p the memp element to check + * @param memp_type the pool p comes from + */ +static void +memp_overflow_check_element_overflow(struct memp *p, u16_t memp_type) +{ + u16_t k; + u8_t *m; +#if MEMP_SANITY_REGION_AFTER_ALIGNED > 0 + m = (u8_t*)p + MEMP_SIZE + memp_sizes[memp_type]; + for (k = 0; k < MEMP_SANITY_REGION_AFTER_ALIGNED; k++) { + if (m[k] != 0xcd) { + char errstr[128] = "detected memp overflow in pool "; + char digit[] = "0"; + if(memp_type >= 10) { + digit[0] = '0' + (memp_type/10); + strcat(errstr, digit); + } + digit[0] = '0' + (memp_type%10); + strcat(errstr, digit); +#if defined(LWIP_DEBUG) && MEMP_STATS + strcat(errstr, memp_overflow_names[memp_type]); +#endif + LWIP_ASSERT(errstr, 0); + } + } +#endif +} + +/** + * Check if a memp element was victim of an underflow + * (e.g. the restricted area before it has been altered) + * + * @param p the memp element to check + * @param memp_type the pool p comes from + */ +static void +memp_overflow_check_element_underflow(struct memp *p, u16_t memp_type) +{ + u16_t k; + u8_t *m; +#if MEMP_SANITY_REGION_BEFORE_ALIGNED > 0 + m = (u8_t*)p + MEMP_SIZE - MEMP_SANITY_REGION_BEFORE_ALIGNED; + for (k = 0; k < MEMP_SANITY_REGION_BEFORE_ALIGNED; k++) { + if (m[k] != 0xcd) { + char errstr[128] = "detected memp underflow in pool "; + char digit[] = "0"; + if(memp_type >= 10) { + digit[0] = '0' + (memp_type/10); + strcat(errstr, digit); + } + digit[0] = '0' + (memp_type%10); + strcat(errstr, digit); +#if defined(LWIP_DEBUG) && MEMP_STATS + strcat(errstr, memp_overflow_names[memp_type]); +#endif + LWIP_ASSERT(errstr, 0); + } + } +#endif +} + +/** + * Do an overflow check for all elements in every pool. + * + * @see memp_overflow_check_element for a description of the check + */ +static void +memp_overflow_check_all(void) +{ + u16_t i, j; + struct memp *p; + + p = (struct memp *)LWIP_MEM_ALIGN(memp_memory); + for (i = 0; i < MEMP_MAX; ++i) { + p = p; + for (j = 0; j < memp_num[i]; ++j) { + memp_overflow_check_element_overflow(p, i); + p = (struct memp*)((u8_t*)p + MEMP_SIZE + memp_sizes[i] + MEMP_SANITY_REGION_AFTER_ALIGNED); + } + } + p = (struct memp *)LWIP_MEM_ALIGN(memp_memory); + for (i = 0; i < MEMP_MAX; ++i) { + p = p; + for (j = 0; j < memp_num[i]; ++j) { + memp_overflow_check_element_underflow(p, i); + p = (struct memp*)((u8_t*)p + MEMP_SIZE + memp_sizes[i] + MEMP_SANITY_REGION_AFTER_ALIGNED); + } + } +} + +/** + * Initialize the restricted areas of all memp elements in every pool. + */ +static void +memp_overflow_init(void) +{ + u16_t i, j; + struct memp *p; + u8_t *m; + + p = (struct memp *)LWIP_MEM_ALIGN(memp_memory); + for (i = 0; i < MEMP_MAX; ++i) { + p = p; + for (j = 0; j < memp_num[i]; ++j) { +#if MEMP_SANITY_REGION_BEFORE_ALIGNED > 0 + m = (u8_t*)p + MEMP_SIZE - MEMP_SANITY_REGION_BEFORE_ALIGNED; + memset(m, 0xcd, MEMP_SANITY_REGION_BEFORE_ALIGNED); +#endif +#if MEMP_SANITY_REGION_AFTER_ALIGNED > 0 + m = (u8_t*)p + MEMP_SIZE + memp_sizes[i]; + memset(m, 0xcd, MEMP_SANITY_REGION_AFTER_ALIGNED); +#endif + p = (struct memp*)((u8_t*)p + MEMP_SIZE + memp_sizes[i] + MEMP_SANITY_REGION_AFTER_ALIGNED); + } + } +} +#endif /* MEMP_OVERFLOW_CHECK */ + +/** + * Initialize this module. + * + * Carves out memp_memory into linked lists for each pool-type. + */ +void +memp_init(void) +{ + struct memp *memp; + u16_t i, j; + + for (i = 0; i < MEMP_MAX; ++i) { + MEMP_STATS_AVAIL(used, i, 0); + MEMP_STATS_AVAIL(max, i, 0); + MEMP_STATS_AVAIL(err, i, 0); + MEMP_STATS_AVAIL(avail, i, memp_num[i]); + } + +#if !MEMP_SEPARATE_POOLS + memp = (struct memp *)LWIP_MEM_ALIGN(memp_memory); +#endif /* !MEMP_SEPARATE_POOLS */ + /* for every pool: */ + for (i = 0; i < MEMP_MAX; ++i) { + memp_tab[i] = NULL; +#if MEMP_SEPARATE_POOLS + memp = (struct memp*)memp_bases[i]; +#endif /* MEMP_SEPARATE_POOLS */ + /* create a linked list of memp elements */ + for (j = 0; j < memp_num[i]; ++j) { + memp->next = memp_tab[i]; + memp_tab[i] = memp; + memp = (struct memp *)(void *)((u8_t *)memp + MEMP_SIZE + memp_sizes[i] +#if MEMP_OVERFLOW_CHECK + + MEMP_SANITY_REGION_AFTER_ALIGNED +#endif + ); + } + } +#if MEMP_OVERFLOW_CHECK + memp_overflow_init(); + /* check everything a first time to see if it worked */ + memp_overflow_check_all(); +#endif /* MEMP_OVERFLOW_CHECK */ +} + +/** + * Get an element from a specific pool. + * + * @param type the pool to get an element from + * + * the debug version has two more parameters: + * @param file file name calling this function + * @param line number of line where this function is called + * + * @return a pointer to the allocated memory or a NULL pointer on error + */ +void * +#if !MEMP_OVERFLOW_CHECK +memp_malloc(memp_t type) +#else +memp_malloc_fn(memp_t type, const char* file, const int line) +#endif +{ + struct memp *memp; + SYS_ARCH_DECL_PROTECT(old_level); + + LWIP_ERROR("memp_malloc: type < MEMP_MAX", (type < MEMP_MAX), return NULL;); + + SYS_ARCH_PROTECT(old_level); +#if MEMP_OVERFLOW_CHECK >= 2 + memp_overflow_check_all(); +#endif /* MEMP_OVERFLOW_CHECK >= 2 */ + + memp = memp_tab[type]; + + if (memp != NULL) { + memp_tab[type] = memp->next; +#if MEMP_OVERFLOW_CHECK + memp->next = NULL; + memp->file = file; + memp->line = line; +#endif /* MEMP_OVERFLOW_CHECK */ + MEMP_STATS_INC_USED(used, type); + LWIP_ASSERT("memp_malloc: memp properly aligned", + ((mem_ptr_t)memp % MEM_ALIGNMENT) == 0); + memp = (struct memp*)(void *)((u8_t*)memp + MEMP_SIZE); + } else { + LWIP_DEBUGF(MEMP_DEBUG | LWIP_DBG_LEVEL_SERIOUS, ("memp_malloc: out of memory in pool %s\n", memp_desc[type])); + MEMP_STATS_INC(err, type); + } + + SYS_ARCH_UNPROTECT(old_level); + + return memp; +} + +/** + * Put an element back into its pool. + * + * @param type the pool where to put mem + * @param mem the memp element to free + */ +void +memp_free(memp_t type, void *mem) +{ + struct memp *memp; + SYS_ARCH_DECL_PROTECT(old_level); + + if (mem == NULL) { + return; + } + LWIP_ASSERT("memp_free: mem properly aligned", + ((mem_ptr_t)mem % MEM_ALIGNMENT) == 0); + + memp = (struct memp *)(void *)((u8_t*)mem - MEMP_SIZE); + + SYS_ARCH_PROTECT(old_level); +#if MEMP_OVERFLOW_CHECK +#if MEMP_OVERFLOW_CHECK >= 2 + memp_overflow_check_all(); +#else + memp_overflow_check_element_overflow(memp, type); + memp_overflow_check_element_underflow(memp, type); +#endif /* MEMP_OVERFLOW_CHECK >= 2 */ +#endif /* MEMP_OVERFLOW_CHECK */ + + MEMP_STATS_DEC(used, type); + + memp->next = memp_tab[type]; + memp_tab[type] = memp; + +#if MEMP_SANITY_CHECK + LWIP_ASSERT("memp sanity", memp_sanity()); +#endif /* MEMP_SANITY_CHECK */ + + SYS_ARCH_UNPROTECT(old_level); +} + +#endif /* MEMP_MEM_MALLOC */ diff --git a/features/unsupported/net/lwip/lwip/core/netif.c b/features/unsupported/net/lwip/lwip/core/netif.c new file mode 100644 index 00000000000..b3a5e16337c --- /dev/null +++ b/features/unsupported/net/lwip/lwip/core/netif.c @@ -0,0 +1,758 @@ +/** + * @file + * lwIP network interface abstraction + * + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ + +#include "lwip/opt.h" + +#include "lwip/def.h" +#include "lwip/ip_addr.h" +#include "lwip/netif.h" +#include "lwip/tcp_impl.h" +#include "lwip/snmp.h" +#include "lwip/igmp.h" +#include "netif/etharp.h" +#include "lwip/stats.h" +#if ENABLE_LOOPBACK +#include "lwip/sys.h" +#if LWIP_NETIF_LOOPBACK_MULTITHREADING +#include "lwip/tcpip.h" +#endif /* LWIP_NETIF_LOOPBACK_MULTITHREADING */ +#endif /* ENABLE_LOOPBACK */ + +#if LWIP_AUTOIP +#include "lwip/autoip.h" +#endif /* LWIP_AUTOIP */ +#if LWIP_DHCP +#include "lwip/dhcp.h" +#endif /* LWIP_DHCP */ + +#if LWIP_NETIF_STATUS_CALLBACK +#define NETIF_STATUS_CALLBACK(n) do{ if (n->status_callback) { (n->status_callback)(n); }}while(0) +#else +#define NETIF_STATUS_CALLBACK(n) +#endif /* LWIP_NETIF_STATUS_CALLBACK */ + +#if LWIP_NETIF_LINK_CALLBACK +#define NETIF_LINK_CALLBACK(n) do{ if (n->link_callback) { (n->link_callback)(n); }}while(0) +#else +#define NETIF_LINK_CALLBACK(n) +#endif /* LWIP_NETIF_LINK_CALLBACK */ + +struct netif *netif_list; +struct netif *netif_default; + +#if LWIP_HAVE_LOOPIF +static struct netif loop_netif; + +/** + * Initialize a lwip network interface structure for a loopback interface + * + * @param netif the lwip network interface structure for this loopif + * @return ERR_OK if the loopif is initialized + * ERR_MEM if private data couldn't be allocated + */ +static err_t +netif_loopif_init(struct netif *netif) +{ + /* initialize the snmp variables and counters inside the struct netif + * ifSpeed: no assumption can be made! + */ + NETIF_INIT_SNMP(netif, snmp_ifType_softwareLoopback, 0); + + netif->name[0] = 'l'; + netif->name[1] = 'o'; + netif->output = netif_loop_output; + return ERR_OK; +} +#endif /* LWIP_HAVE_LOOPIF */ + +void +netif_init(void) +{ +#if LWIP_HAVE_LOOPIF + ip_addr_t loop_ipaddr, loop_netmask, loop_gw; + IP4_ADDR(&loop_gw, 127,0,0,1); + IP4_ADDR(&loop_ipaddr, 127,0,0,1); + IP4_ADDR(&loop_netmask, 255,0,0,0); + +#if NO_SYS + netif_add(&loop_netif, &loop_ipaddr, &loop_netmask, &loop_gw, NULL, netif_loopif_init, ip_input); +#else /* NO_SYS */ + netif_add(&loop_netif, &loop_ipaddr, &loop_netmask, &loop_gw, NULL, netif_loopif_init, tcpip_input); +#endif /* NO_SYS */ + netif_set_up(&loop_netif); + +#endif /* LWIP_HAVE_LOOPIF */ +} + +/** + * Add a network interface to the list of lwIP netifs. + * + * @param netif a pre-allocated netif structure + * @param ipaddr IP address for the new netif + * @param netmask network mask for the new netif + * @param gw default gateway IP address for the new netif + * @param state opaque data passed to the new netif + * @param init callback function that initializes the interface + * @param input callback function that is called to pass + * ingress packets up in the protocol layer stack. + * + * @return netif, or NULL if failed. + */ +struct netif * +netif_add(struct netif *netif, ip_addr_t *ipaddr, ip_addr_t *netmask, + ip_addr_t *gw, void *state, netif_init_fn init, netif_input_fn input) +{ + static u8_t netifnum = 0; + + LWIP_ASSERT("No init function given", init != NULL); + + /* reset new interface configuration state */ + ip_addr_set_zero(&netif->ip_addr); + ip_addr_set_zero(&netif->netmask); + ip_addr_set_zero(&netif->gw); + netif->flags = 0; +#if LWIP_DHCP + /* netif not under DHCP control by default */ + netif->dhcp = NULL; +#endif /* LWIP_DHCP */ +#if LWIP_AUTOIP + /* netif not under AutoIP control by default */ + netif->autoip = NULL; +#endif /* LWIP_AUTOIP */ +#if LWIP_NETIF_STATUS_CALLBACK + netif->status_callback = NULL; +#endif /* LWIP_NETIF_STATUS_CALLBACK */ +#if LWIP_NETIF_LINK_CALLBACK + netif->link_callback = NULL; +#endif /* LWIP_NETIF_LINK_CALLBACK */ +#if LWIP_IGMP + netif->igmp_mac_filter = NULL; +#endif /* LWIP_IGMP */ +#if ENABLE_LOOPBACK + netif->loop_first = NULL; + netif->loop_last = NULL; +#endif /* ENABLE_LOOPBACK */ + + /* remember netif specific state information data */ + netif->state = state; + netif->num = netifnum++; + netif->input = input; +#if LWIP_NETIF_HWADDRHINT + netif->addr_hint = NULL; +#endif /* LWIP_NETIF_HWADDRHINT*/ +#if ENABLE_LOOPBACK && LWIP_LOOPBACK_MAX_PBUFS + netif->loop_cnt_current = 0; +#endif /* ENABLE_LOOPBACK && LWIP_LOOPBACK_MAX_PBUFS */ + + netif_set_addr(netif, ipaddr, netmask, gw); + + /* call user specified initialization function for netif */ + if (init(netif) != ERR_OK) { + return NULL; + } + + /* add this netif to the list */ + netif->next = netif_list; + netif_list = netif; + snmp_inc_iflist(); + +#if LWIP_IGMP + /* start IGMP processing */ + if (netif->flags & NETIF_FLAG_IGMP) { + igmp_start(netif); + } +#endif /* LWIP_IGMP */ + + LWIP_DEBUGF(NETIF_DEBUG, ("netif: added interface %c%c IP addr ", + netif->name[0], netif->name[1])); + ip_addr_debug_print(NETIF_DEBUG, ipaddr); + LWIP_DEBUGF(NETIF_DEBUG, (" netmask ")); + ip_addr_debug_print(NETIF_DEBUG, netmask); + LWIP_DEBUGF(NETIF_DEBUG, (" gw ")); + ip_addr_debug_print(NETIF_DEBUG, gw); + LWIP_DEBUGF(NETIF_DEBUG, ("\n")); + return netif; +} + +/** + * Change IP address configuration for a network interface (including netmask + * and default gateway). + * + * @param netif the network interface to change + * @param ipaddr the new IP address + * @param netmask the new netmask + * @param gw the new default gateway + */ +void +netif_set_addr(struct netif *netif, ip_addr_t *ipaddr, ip_addr_t *netmask, + ip_addr_t *gw) +{ + netif_set_ipaddr(netif, ipaddr); + netif_set_netmask(netif, netmask); + netif_set_gw(netif, gw); +} + +/** + * Remove a network interface from the list of lwIP netifs. + * + * @param netif the network interface to remove + */ +void +netif_remove(struct netif *netif) +{ + if (netif == NULL) { + return; + } + +#if LWIP_IGMP + /* stop IGMP processing */ + if (netif->flags & NETIF_FLAG_IGMP) { + igmp_stop(netif); + } +#endif /* LWIP_IGMP */ + if (netif_is_up(netif)) { + /* set netif down before removing (call callback function) */ + netif_set_down(netif); + } + + snmp_delete_ipaddridx_tree(netif); + + /* is it the first netif? */ + if (netif_list == netif) { + netif_list = netif->next; + } else { + /* look for netif further down the list */ + struct netif * tmpNetif; + for (tmpNetif = netif_list; tmpNetif != NULL; tmpNetif = tmpNetif->next) { + if (tmpNetif->next == netif) { + tmpNetif->next = netif->next; + break; + } + } + if (tmpNetif == NULL) + return; /* we didn't find any netif today */ + } + snmp_dec_iflist(); + /* this netif is default? */ + if (netif_default == netif) { + /* reset default netif */ + netif_set_default(NULL); + } + LWIP_DEBUGF( NETIF_DEBUG, ("netif_remove: removed netif\n") ); +} + +/** + * Find a network interface by searching for its name + * + * @param name the name of the netif (like netif->name) plus concatenated number + * in ascii representation (e.g. 'en0') + */ +struct netif * +netif_find(char *name) +{ + struct netif *netif; + u8_t num; + + if (name == NULL) { + return NULL; + } + + num = name[2] - '0'; + + for(netif = netif_list; netif != NULL; netif = netif->next) { + if (num == netif->num && + name[0] == netif->name[0] && + name[1] == netif->name[1]) { + LWIP_DEBUGF(NETIF_DEBUG, ("netif_find: found %c%c\n", name[0], name[1])); + return netif; + } + } + LWIP_DEBUGF(NETIF_DEBUG, ("netif_find: didn't find %c%c\n", name[0], name[1])); + return NULL; +} + +/** + * Change the IP address of a network interface + * + * @param netif the network interface to change + * @param ipaddr the new IP address + * + * @note call netif_set_addr() if you also want to change netmask and + * default gateway + */ +void +netif_set_ipaddr(struct netif *netif, ip_addr_t *ipaddr) +{ + /* Protect against dereferencing NULL pointers by + treating like ANY, as does ip_addr_set() */ + if (!ipaddr) { + ipaddr = IP_ADDR_ANY; + } + + /* TODO: Handling of obsolete pcbs */ + /* See: http://mail.gnu.org/archive/html/lwip-users/2003-03/msg00118.html */ +#if LWIP_TCP + struct tcp_pcb *pcb; + struct tcp_pcb_listen *lpcb; + + /* address is actually being changed? */ + if ((ip_addr_cmp(ipaddr, &(netif->ip_addr))) == 0) { + /* extern struct tcp_pcb *tcp_active_pcbs; defined by tcp.h */ + LWIP_DEBUGF(NETIF_DEBUG | LWIP_DBG_STATE, ("netif_set_ipaddr: netif address being changed\n")); + pcb = tcp_active_pcbs; + while (pcb != NULL) { + /* PCB bound to current local interface address? */ + if (ip_addr_cmp(&(pcb->local_ip), &(netif->ip_addr)) +#if LWIP_AUTOIP + /* connections to link-local addresses must persist (RFC3927 ch. 1.9) */ + && !ip_addr_islinklocal(&(pcb->local_ip)) +#endif /* LWIP_AUTOIP */ + ) { + /* this connection must be aborted */ + struct tcp_pcb *next = pcb->next; + LWIP_DEBUGF(NETIF_DEBUG | LWIP_DBG_STATE, ("netif_set_ipaddr: aborting TCP pcb %p\n", (void *)pcb)); + tcp_abort(pcb); + pcb = next; + } else { + pcb = pcb->next; + } + } + for (lpcb = tcp_listen_pcbs.listen_pcbs; lpcb != NULL; lpcb = lpcb->next) { + /* PCB bound to current local interface address? */ + if ((!(ip_addr_isany(&(lpcb->local_ip)))) && + (ip_addr_cmp(&(lpcb->local_ip), &(netif->ip_addr)))) { + /* The PCB is listening to the old ipaddr and + * is set to listen to the new one instead */ + ip_addr_set(&(lpcb->local_ip), ipaddr); + } + } + } +#endif + snmp_delete_ipaddridx_tree(netif); + snmp_delete_iprteidx_tree(0,netif); + /* set new IP address to netif */ + ip_addr_set(&(netif->ip_addr), ipaddr); + snmp_insert_ipaddridx_tree(netif); + snmp_insert_iprteidx_tree(0,netif); + + LWIP_DEBUGF(NETIF_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("netif: IP address of interface %c%c set to %"U16_F".%"U16_F".%"U16_F".%"U16_F"\n", + netif->name[0], netif->name[1], + ip4_addr1_16(&netif->ip_addr), + ip4_addr2_16(&netif->ip_addr), + ip4_addr3_16(&netif->ip_addr), + ip4_addr4_16(&netif->ip_addr))); +} + +/** + * Change the default gateway for a network interface + * + * @param netif the network interface to change + * @param gw the new default gateway + * + * @note call netif_set_addr() if you also want to change ip address and netmask + */ +void +netif_set_gw(struct netif *netif, ip_addr_t *gw) +{ + ip_addr_set(&(netif->gw), gw); + LWIP_DEBUGF(NETIF_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("netif: GW address of interface %c%c set to %"U16_F".%"U16_F".%"U16_F".%"U16_F"\n", + netif->name[0], netif->name[1], + ip4_addr1_16(&netif->gw), + ip4_addr2_16(&netif->gw), + ip4_addr3_16(&netif->gw), + ip4_addr4_16(&netif->gw))); +} + +/** + * Change the netmask of a network interface + * + * @param netif the network interface to change + * @param netmask the new netmask + * + * @note call netif_set_addr() if you also want to change ip address and + * default gateway + */ +void +netif_set_netmask(struct netif *netif, ip_addr_t *netmask) +{ + snmp_delete_iprteidx_tree(0, netif); + /* set new netmask to netif */ + ip_addr_set(&(netif->netmask), netmask); + snmp_insert_iprteidx_tree(0, netif); + LWIP_DEBUGF(NETIF_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("netif: netmask of interface %c%c set to %"U16_F".%"U16_F".%"U16_F".%"U16_F"\n", + netif->name[0], netif->name[1], + ip4_addr1_16(&netif->netmask), + ip4_addr2_16(&netif->netmask), + ip4_addr3_16(&netif->netmask), + ip4_addr4_16(&netif->netmask))); +} + +/** + * Set a network interface as the default network interface + * (used to output all packets for which no specific route is found) + * + * @param netif the default network interface + */ +void +netif_set_default(struct netif *netif) +{ + if (netif == NULL) { + /* remove default route */ + snmp_delete_iprteidx_tree(1, netif); + } else { + /* install default route */ + snmp_insert_iprteidx_tree(1, netif); + } + netif_default = netif; + LWIP_DEBUGF(NETIF_DEBUG, ("netif: setting default interface %c%c\n", + netif ? netif->name[0] : '\'', netif ? netif->name[1] : '\'')); +} + +/** + * Bring an interface up, available for processing + * traffic. + * + * @note: Enabling DHCP on a down interface will make it come + * up once configured. + * + * @see dhcp_start() + */ +void netif_set_up(struct netif *netif) +{ + if (!(netif->flags & NETIF_FLAG_UP)) { + netif->flags |= NETIF_FLAG_UP; + +#if LWIP_SNMP + snmp_get_sysuptime(&netif->ts); +#endif /* LWIP_SNMP */ + + NETIF_STATUS_CALLBACK(netif); + + if (netif->flags & NETIF_FLAG_LINK_UP) { +#if LWIP_ARP + /* For Ethernet network interfaces, we would like to send a "gratuitous ARP" */ + if (netif->flags & (NETIF_FLAG_ETHARP)) { + etharp_gratuitous(netif); + } +#endif /* LWIP_ARP */ + +#if LWIP_IGMP + /* resend IGMP memberships */ + if (netif->flags & NETIF_FLAG_IGMP) { + igmp_report_groups( netif); + } +#endif /* LWIP_IGMP */ + } + } +} + +/** + * Bring an interface down, disabling any traffic processing. + * + * @note: Enabling DHCP on a down interface will make it come + * up once configured. + * + * @see dhcp_start() + */ +void netif_set_down(struct netif *netif) +{ + if (netif->flags & NETIF_FLAG_UP) { + netif->flags &= ~NETIF_FLAG_UP; +#if LWIP_SNMP + snmp_get_sysuptime(&netif->ts); +#endif + + NETIF_STATUS_CALLBACK(netif); + } +} + +#if LWIP_NETIF_STATUS_CALLBACK +/** + * Set callback to be called when interface is brought up/down + */ +void netif_set_status_callback(struct netif *netif, netif_status_callback_fn status_callback) +{ + if (netif) { + netif->status_callback = status_callback; + } +} +#endif /* LWIP_NETIF_STATUS_CALLBACK */ + +/** + * Called by a driver when its link goes up + */ +void netif_set_link_up(struct netif *netif ) +{ + if (!(netif->flags & NETIF_FLAG_LINK_UP)) { + netif->flags |= NETIF_FLAG_LINK_UP; + +#if LWIP_DHCP + if (netif->dhcp) { + dhcp_network_changed(netif); + } +#endif /* LWIP_DHCP */ + +#if LWIP_AUTOIP + if (netif->autoip) { + autoip_network_changed(netif); + } +#endif /* LWIP_AUTOIP */ + + if (netif->flags & NETIF_FLAG_UP) { +#if LWIP_ARP + /* For Ethernet network interfaces, we would like to send a "gratuitous ARP" */ + if (netif->flags & NETIF_FLAG_ETHARP) { + etharp_gratuitous(netif); + } +#endif /* LWIP_ARP */ + +#if LWIP_IGMP + /* resend IGMP memberships */ + if (netif->flags & NETIF_FLAG_IGMP) { + igmp_report_groups( netif); + } +#endif /* LWIP_IGMP */ + } + NETIF_LINK_CALLBACK(netif); + } +} + +/** + * Called by a driver when its link goes down + */ +void netif_set_link_down(struct netif *netif ) +{ + if (netif->flags & NETIF_FLAG_LINK_UP) { + netif->flags &= ~NETIF_FLAG_LINK_UP; + NETIF_LINK_CALLBACK(netif); + } +} + +#if LWIP_NETIF_LINK_CALLBACK +/** + * Set callback to be called when link is brought up/down + */ +void netif_set_link_callback(struct netif *netif, netif_status_callback_fn link_callback) +{ + if (netif) { + netif->link_callback = link_callback; + } +} +#endif /* LWIP_NETIF_LINK_CALLBACK */ + +#if ENABLE_LOOPBACK +/** + * Send an IP packet to be received on the same netif (loopif-like). + * The pbuf is simply copied and handed back to netif->input. + * In multithreaded mode, this is done directly since netif->input must put + * the packet on a queue. + * In callback mode, the packet is put on an internal queue and is fed to + * netif->input by netif_poll(). + * + * @param netif the lwip network interface structure + * @param p the (IP) packet to 'send' + * @param ipaddr the ip address to send the packet to (not used) + * @return ERR_OK if the packet has been sent + * ERR_MEM if the pbuf used to copy the packet couldn't be allocated + */ +err_t +netif_loop_output(struct netif *netif, struct pbuf *p, + ip_addr_t *ipaddr) +{ + struct pbuf *r; + err_t err; + struct pbuf *last; +#if LWIP_LOOPBACK_MAX_PBUFS + u8_t clen = 0; +#endif /* LWIP_LOOPBACK_MAX_PBUFS */ + /* If we have a loopif, SNMP counters are adjusted for it, + * if not they are adjusted for 'netif'. */ +#if LWIP_SNMP +#if LWIP_HAVE_LOOPIF + struct netif *stats_if = &loop_netif; +#else /* LWIP_HAVE_LOOPIF */ + struct netif *stats_if = netif; +#endif /* LWIP_HAVE_LOOPIF */ +#endif /* LWIP_SNMP */ + SYS_ARCH_DECL_PROTECT(lev); + LWIP_UNUSED_ARG(ipaddr); + + /* Allocate a new pbuf */ + r = pbuf_alloc(PBUF_LINK, p->tot_len, PBUF_RAM); + if (r == NULL) { + LINK_STATS_INC(link.memerr); + LINK_STATS_INC(link.drop); + snmp_inc_ifoutdiscards(stats_if); + return ERR_MEM; + } +#if LWIP_LOOPBACK_MAX_PBUFS + clen = pbuf_clen(r); + /* check for overflow or too many pbuf on queue */ + if(((netif->loop_cnt_current + clen) < netif->loop_cnt_current) || + ((netif->loop_cnt_current + clen) > LWIP_LOOPBACK_MAX_PBUFS)) { + pbuf_free(r); + LINK_STATS_INC(link.memerr); + LINK_STATS_INC(link.drop); + snmp_inc_ifoutdiscards(stats_if); + return ERR_MEM; + } + netif->loop_cnt_current += clen; +#endif /* LWIP_LOOPBACK_MAX_PBUFS */ + + /* Copy the whole pbuf queue p into the single pbuf r */ + if ((err = pbuf_copy(r, p)) != ERR_OK) { + pbuf_free(r); + LINK_STATS_INC(link.memerr); + LINK_STATS_INC(link.drop); + snmp_inc_ifoutdiscards(stats_if); + return err; + } + + /* Put the packet on a linked list which gets emptied through calling + netif_poll(). */ + + /* let last point to the last pbuf in chain r */ + for (last = r; last->next != NULL; last = last->next); + + SYS_ARCH_PROTECT(lev); + if(netif->loop_first != NULL) { + LWIP_ASSERT("if first != NULL, last must also be != NULL", netif->loop_last != NULL); + netif->loop_last->next = r; + netif->loop_last = last; + } else { + netif->loop_first = r; + netif->loop_last = last; + } + SYS_ARCH_UNPROTECT(lev); + + LINK_STATS_INC(link.xmit); + snmp_add_ifoutoctets(stats_if, p->tot_len); + snmp_inc_ifoutucastpkts(stats_if); + +#if LWIP_NETIF_LOOPBACK_MULTITHREADING + /* For multithreading environment, schedule a call to netif_poll */ + tcpip_callback((tcpip_callback_fn)netif_poll, netif); +#endif /* LWIP_NETIF_LOOPBACK_MULTITHREADING */ + + return ERR_OK; +} + +/** + * Call netif_poll() in the main loop of your application. This is to prevent + * reentering non-reentrant functions like tcp_input(). Packets passed to + * netif_loop_output() are put on a list that is passed to netif->input() by + * netif_poll(). + */ +void +netif_poll(struct netif *netif) +{ + struct pbuf *in; + /* If we have a loopif, SNMP counters are adjusted for it, + * if not they are adjusted for 'netif'. */ +#if LWIP_SNMP +#if LWIP_HAVE_LOOPIF + struct netif *stats_if = &loop_netif; +#else /* LWIP_HAVE_LOOPIF */ + struct netif *stats_if = netif; +#endif /* LWIP_HAVE_LOOPIF */ +#endif /* LWIP_SNMP */ + SYS_ARCH_DECL_PROTECT(lev); + + do { + /* Get a packet from the list. With SYS_LIGHTWEIGHT_PROT=1, this is protected */ + SYS_ARCH_PROTECT(lev); + in = netif->loop_first; + if (in != NULL) { + struct pbuf *in_end = in; +#if LWIP_LOOPBACK_MAX_PBUFS + u8_t clen = pbuf_clen(in); + /* adjust the number of pbufs on queue */ + LWIP_ASSERT("netif->loop_cnt_current underflow", + ((netif->loop_cnt_current - clen) < netif->loop_cnt_current)); + netif->loop_cnt_current -= clen; +#endif /* LWIP_LOOPBACK_MAX_PBUFS */ + while (in_end->len != in_end->tot_len) { + LWIP_ASSERT("bogus pbuf: len != tot_len but next == NULL!", in_end->next != NULL); + in_end = in_end->next; + } + /* 'in_end' now points to the last pbuf from 'in' */ + if (in_end == netif->loop_last) { + /* this was the last pbuf in the list */ + netif->loop_first = netif->loop_last = NULL; + } else { + /* pop the pbuf off the list */ + netif->loop_first = in_end->next; + LWIP_ASSERT("should not be null since first != last!", netif->loop_first != NULL); + } + /* De-queue the pbuf from its successors on the 'loop_' list. */ + in_end->next = NULL; + } + SYS_ARCH_UNPROTECT(lev); + + if (in != NULL) { + LINK_STATS_INC(link.recv); + snmp_add_ifinoctets(stats_if, in->tot_len); + snmp_inc_ifinucastpkts(stats_if); + /* loopback packets are always IP packets! */ + if (ip_input(in, netif) != ERR_OK) { + pbuf_free(in); + } + /* Don't reference the packet any more! */ + in = NULL; + } + /* go on while there is a packet on the list */ + } while (netif->loop_first != NULL); +} + +#if !LWIP_NETIF_LOOPBACK_MULTITHREADING +/** + * Calls netif_poll() for every netif on the netif_list. + */ +void +netif_poll_all(void) +{ + struct netif *netif = netif_list; + /* loop through netifs */ + while (netif != NULL) { + netif_poll(netif); + /* proceed to next network interface */ + netif = netif->next; + } +} +#endif /* !LWIP_NETIF_LOOPBACK_MULTITHREADING */ +#endif /* ENABLE_LOOPBACK */ diff --git a/features/unsupported/net/lwip/lwip/core/pbuf.c b/features/unsupported/net/lwip/lwip/core/pbuf.c new file mode 100644 index 00000000000..cd37c797237 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/core/pbuf.c @@ -0,0 +1,1158 @@ +/** + * @file + * Packet buffer management + * + * Packets are built from the pbuf data structure. It supports dynamic + * memory allocation for packet contents or can reference externally + * managed packet contents both in RAM and ROM. Quick allocation for + * incoming packets is provided through pools with fixed sized pbufs. + * + * A packet may span over multiple pbufs, chained as a singly linked + * list. This is called a "pbuf chain". + * + * Multiple packets may be queued, also using this singly linked list. + * This is called a "packet queue". + * + * So, a packet queue consists of one or more pbuf chains, each of + * which consist of one or more pbufs. CURRENTLY, PACKET QUEUES ARE + * NOT SUPPORTED!!! Use helper structs to queue multiple packets. + * + * The differences between a pbuf chain and a packet queue are very + * precise but subtle. + * + * The last pbuf of a packet has a ->tot_len field that equals the + * ->len field. It can be found by traversing the list. If the last + * pbuf of a packet has a ->next field other than NULL, more packets + * are on the queue. + * + * Therefore, looping through a pbuf of a single packet, has an + * loop end condition (tot_len == p->len), NOT (next == NULL). + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ + +#include "lwip/opt.h" + +#include "lwip/stats.h" +#include "lwip/def.h" +#include "lwip/mem.h" +#include "lwip/memp.h" +#include "lwip/pbuf.h" +#include "lwip/sys.h" +#include "arch/perf.h" +#if TCP_QUEUE_OOSEQ +#include "lwip/tcp_impl.h" +#endif +#if LWIP_CHECKSUM_ON_COPY +#include "lwip/inet_chksum.h" +#endif + +#include + +#define SIZEOF_STRUCT_PBUF LWIP_MEM_ALIGN_SIZE(sizeof(struct pbuf)) +/* Since the pool is created in memp, PBUF_POOL_BUFSIZE will be automatically + aligned there. Therefore, PBUF_POOL_BUFSIZE_ALIGNED can be used here. */ +#define PBUF_POOL_BUFSIZE_ALIGNED LWIP_MEM_ALIGN_SIZE(PBUF_POOL_BUFSIZE) + +#if !LWIP_TCP || !TCP_QUEUE_OOSEQ || NO_SYS +#define PBUF_POOL_IS_EMPTY() +#else /* !LWIP_TCP || !TCP_QUEUE_OOSEQ || NO_SYS */ +/** Define this to 0 to prevent freeing ooseq pbufs when the PBUF_POOL is empty */ +#ifndef PBUF_POOL_FREE_OOSEQ +#define PBUF_POOL_FREE_OOSEQ 1 +#endif /* PBUF_POOL_FREE_OOSEQ */ + +#if PBUF_POOL_FREE_OOSEQ +#include "lwip/tcpip.h" +#define PBUF_POOL_IS_EMPTY() pbuf_pool_is_empty() +static u8_t pbuf_free_ooseq_queued; +/** + * Attempt to reclaim some memory from queued out-of-sequence TCP segments + * if we run out of pool pbufs. It's better to give priority to new packets + * if we're running out. + * + * This must be done in the correct thread context therefore this function + * can only be used with NO_SYS=0 and through tcpip_callback. + */ +static void +pbuf_free_ooseq(void* arg) +{ + struct tcp_pcb* pcb; + SYS_ARCH_DECL_PROTECT(old_level); + LWIP_UNUSED_ARG(arg); + + SYS_ARCH_PROTECT(old_level); + pbuf_free_ooseq_queued = 0; + SYS_ARCH_UNPROTECT(old_level); + + for (pcb = tcp_active_pcbs; NULL != pcb; pcb = pcb->next) { + if (NULL != pcb->ooseq) { + /** Free the ooseq pbufs of one PCB only */ + LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_free_ooseq: freeing out-of-sequence pbufs\n")); + tcp_segs_free(pcb->ooseq); + pcb->ooseq = NULL; + return; + } + } +} + +/** Queue a call to pbuf_free_ooseq if not already queued. */ +static void +pbuf_pool_is_empty(void) +{ + u8_t queued; + SYS_ARCH_DECL_PROTECT(old_level); + + SYS_ARCH_PROTECT(old_level); + queued = pbuf_free_ooseq_queued; + pbuf_free_ooseq_queued = 1; + SYS_ARCH_UNPROTECT(old_level); + + if(!queued) { + /* queue a call to pbuf_free_ooseq if not already queued */ + if(tcpip_callback_with_block(pbuf_free_ooseq, NULL, 0) != ERR_OK) { + SYS_ARCH_PROTECT(old_level); + pbuf_free_ooseq_queued = 0; + SYS_ARCH_UNPROTECT(old_level); + } + } +} +#endif /* PBUF_POOL_FREE_OOSEQ */ +#endif /* !LWIP_TCP || !TCP_QUEUE_OOSEQ || NO_SYS */ + +/** + * Allocates a pbuf of the given type (possibly a chain for PBUF_POOL type). + * + * The actual memory allocated for the pbuf is determined by the + * layer at which the pbuf is allocated and the requested size + * (from the size parameter). + * + * @param layer flag to define header size + * @param length size of the pbuf's payload + * @param type this parameter decides how and where the pbuf + * should be allocated as follows: + * + * - PBUF_RAM: buffer memory for pbuf is allocated as one large + * chunk. This includes protocol headers as well. + * - PBUF_ROM: no buffer memory is allocated for the pbuf, even for + * protocol headers. Additional headers must be prepended + * by allocating another pbuf and chain in to the front of + * the ROM pbuf. It is assumed that the memory used is really + * similar to ROM in that it is immutable and will not be + * changed. Memory which is dynamic should generally not + * be attached to PBUF_ROM pbufs. Use PBUF_REF instead. + * - PBUF_REF: no buffer memory is allocated for the pbuf, even for + * protocol headers. It is assumed that the pbuf is only + * being used in a single thread. If the pbuf gets queued, + * then pbuf_take should be called to copy the buffer. + * - PBUF_POOL: the pbuf is allocated as a pbuf chain, with pbufs from + * the pbuf pool that is allocated during pbuf_init(). + * + * @return the allocated pbuf. If multiple pbufs where allocated, this + * is the first pbuf of a pbuf chain. + */ +struct pbuf * +pbuf_alloc(pbuf_layer layer, u16_t length, pbuf_type type) +{ + struct pbuf *p, *q, *r; + u16_t offset; + s32_t rem_len; /* remaining length */ + LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_alloc(length=%"U16_F")\n", length)); + + /* determine header offset */ + offset = 0; + switch (layer) { + case PBUF_TRANSPORT: + /* add room for transport (often TCP) layer header */ + offset += PBUF_TRANSPORT_HLEN; + /* FALLTHROUGH */ + case PBUF_IP: + /* add room for IP layer header */ + offset += PBUF_IP_HLEN; + /* FALLTHROUGH */ + case PBUF_LINK: + /* add room for link layer header */ + offset += PBUF_LINK_HLEN; + break; + case PBUF_RAW: + break; + default: + LWIP_ASSERT("pbuf_alloc: bad pbuf layer", 0); + return NULL; + } + + switch (type) { + case PBUF_POOL: + /* allocate head of pbuf chain into p */ + p = (struct pbuf *)memp_malloc(MEMP_PBUF_POOL); + LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_alloc: allocated pbuf %p\n", (void *)p)); + if (p == NULL) { + PBUF_POOL_IS_EMPTY(); + return NULL; + } + p->type = type; + p->next = NULL; + + /* make the payload pointer point 'offset' bytes into pbuf data memory */ + p->payload = LWIP_MEM_ALIGN((void *)((u8_t *)p + (SIZEOF_STRUCT_PBUF + offset))); + LWIP_ASSERT("pbuf_alloc: pbuf p->payload properly aligned", + ((mem_ptr_t)p->payload % MEM_ALIGNMENT) == 0); + /* the total length of the pbuf chain is the requested size */ + p->tot_len = length; + /* set the length of the first pbuf in the chain */ + p->len = LWIP_MIN(length, PBUF_POOL_BUFSIZE_ALIGNED - LWIP_MEM_ALIGN_SIZE(offset)); + LWIP_ASSERT("check p->payload + p->len does not overflow pbuf", + ((u8_t*)p->payload + p->len <= + (u8_t*)p + SIZEOF_STRUCT_PBUF + PBUF_POOL_BUFSIZE_ALIGNED)); + LWIP_ASSERT("PBUF_POOL_BUFSIZE must be bigger than MEM_ALIGNMENT", + (PBUF_POOL_BUFSIZE_ALIGNED - LWIP_MEM_ALIGN_SIZE(offset)) > 0 ); + /* set reference count (needed here in case we fail) */ + p->ref = 1; + + /* now allocate the tail of the pbuf chain */ + + /* remember first pbuf for linkage in next iteration */ + r = p; + /* remaining length to be allocated */ + rem_len = length - p->len; + /* any remaining pbufs to be allocated? */ + while (rem_len > 0) { + q = (struct pbuf *)memp_malloc(MEMP_PBUF_POOL); + if (q == NULL) { + PBUF_POOL_IS_EMPTY(); + /* free chain so far allocated */ + pbuf_free(p); + /* bail out unsuccesfully */ + return NULL; + } + q->type = type; + q->flags = 0; + q->next = NULL; + /* make previous pbuf point to this pbuf */ + r->next = q; + /* set total length of this pbuf and next in chain */ + LWIP_ASSERT("rem_len < max_u16_t", rem_len < 0xffff); + q->tot_len = (u16_t)rem_len; + /* this pbuf length is pool size, unless smaller sized tail */ + q->len = LWIP_MIN((u16_t)rem_len, PBUF_POOL_BUFSIZE_ALIGNED); + q->payload = (void *)((u8_t *)q + SIZEOF_STRUCT_PBUF); + LWIP_ASSERT("pbuf_alloc: pbuf q->payload properly aligned", + ((mem_ptr_t)q->payload % MEM_ALIGNMENT) == 0); + LWIP_ASSERT("check p->payload + p->len does not overflow pbuf", + ((u8_t*)p->payload + p->len <= + (u8_t*)p + SIZEOF_STRUCT_PBUF + PBUF_POOL_BUFSIZE_ALIGNED)); + q->ref = 1; + /* calculate remaining length to be allocated */ + rem_len -= q->len; + /* remember this pbuf for linkage in next iteration */ + r = q; + } + /* end of chain */ + /*r->next = NULL;*/ + + break; + case PBUF_RAM: + /* If pbuf is to be allocated in RAM, allocate memory for it. */ + p = (struct pbuf*)mem_malloc(LWIP_MEM_ALIGN_SIZE(SIZEOF_STRUCT_PBUF + offset) + LWIP_MEM_ALIGN_SIZE(length)); + if (p == NULL) { + return NULL; + } + /* Set up internal structure of the pbuf. */ + p->payload = LWIP_MEM_ALIGN((void *)((u8_t *)p + SIZEOF_STRUCT_PBUF + offset)); + p->len = p->tot_len = length; + p->next = NULL; + p->type = type; + + LWIP_ASSERT("pbuf_alloc: pbuf->payload properly aligned", + ((mem_ptr_t)p->payload % MEM_ALIGNMENT) == 0); + break; + /* pbuf references existing (non-volatile static constant) ROM payload? */ + case PBUF_ROM: + /* pbuf references existing (externally allocated) RAM payload? */ + case PBUF_REF: + /* only allocate memory for the pbuf structure */ + p = (struct pbuf *)memp_malloc(MEMP_PBUF); + if (p == NULL) { + LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_LEVEL_SERIOUS, + ("pbuf_alloc: Could not allocate MEMP_PBUF for PBUF_%s.\n", + (type == PBUF_ROM) ? "ROM" : "REF")); + return NULL; + } + /* caller must set this field properly, afterwards */ + p->payload = NULL; + p->len = p->tot_len = length; + p->next = NULL; + p->type = type; + break; + default: + LWIP_ASSERT("pbuf_alloc: erroneous type", 0); + return NULL; + } + /* set reference count */ + p->ref = 1; + /* set flags */ + p->flags = 0; + LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_alloc(length=%"U16_F") == %p\n", length, (void *)p)); + return p; +} + +#if LWIP_SUPPORT_CUSTOM_PBUF +/** Initialize a custom pbuf (already allocated). + * + * @param layer flag to define header size + * @param length size of the pbuf's payload + * @param type type of the pbuf (only used to treat the pbuf accordingly, as + * this function allocates no memory) + * @param p pointer to the custom pbuf to initialize (already allocated) + * @param payload_mem pointer to the buffer that is used for payload and headers, + * must be at least big enough to hold 'length' plus the header size, + * may be NULL if set later + * @param payload_mem_len the size of the 'payload_mem' buffer, must be at least + * big enough to hold 'length' plus the header size + */ +struct pbuf* +pbuf_alloced_custom(pbuf_layer l, u16_t length, pbuf_type type, struct pbuf_custom *p, + void *payload_mem, u16_t payload_mem_len) +{ + u16_t offset; + LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_alloced_custom(length=%"U16_F")\n", length)); + + /* determine header offset */ + offset = 0; + switch (l) { + case PBUF_TRANSPORT: + /* add room for transport (often TCP) layer header */ + offset += PBUF_TRANSPORT_HLEN; + /* FALLTHROUGH */ + case PBUF_IP: + /* add room for IP layer header */ + offset += PBUF_IP_HLEN; + /* FALLTHROUGH */ + case PBUF_LINK: + /* add room for link layer header */ + offset += PBUF_LINK_HLEN; + break; + case PBUF_RAW: + break; + default: + LWIP_ASSERT("pbuf_alloced_custom: bad pbuf layer", 0); + return NULL; + } + + if (LWIP_MEM_ALIGN_SIZE(offset) + length < payload_mem_len) { + LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_LEVEL_WARNING, ("pbuf_alloced_custom(length=%"U16_F") buffer too short\n", length)); + return NULL; + } + + p->pbuf.next = NULL; + if (payload_mem != NULL) { + p->pbuf.payload = (void *)((u8_t *)payload_mem + offset); + } else { + p->pbuf.payload = NULL; + } + p->pbuf.flags = PBUF_FLAG_IS_CUSTOM; + p->pbuf.len = p->pbuf.tot_len = length; + p->pbuf.type = type; + p->pbuf.ref = 1; + return &p->pbuf; +} +#endif /* LWIP_SUPPORT_CUSTOM_PBUF */ + +/** + * Shrink a pbuf chain to a desired length. + * + * @param p pbuf to shrink. + * @param new_len desired new length of pbuf chain + * + * Depending on the desired length, the first few pbufs in a chain might + * be skipped and left unchanged. The new last pbuf in the chain will be + * resized, and any remaining pbufs will be freed. + * + * @note If the pbuf is ROM/REF, only the ->tot_len and ->len fields are adjusted. + * @note May not be called on a packet queue. + * + * @note Despite its name, pbuf_realloc cannot grow the size of a pbuf (chain). + */ +void +pbuf_realloc(struct pbuf *p, u16_t new_len) +{ + struct pbuf *q; + u16_t rem_len; /* remaining length */ + s32_t grow; + + LWIP_ASSERT("pbuf_realloc: p != NULL", p != NULL); + LWIP_ASSERT("pbuf_realloc: sane p->type", p->type == PBUF_POOL || + p->type == PBUF_ROM || + p->type == PBUF_RAM || + p->type == PBUF_REF); + + /* desired length larger than current length? */ + if (new_len >= p->tot_len) { + /* enlarging not yet supported */ + return; + } + + /* the pbuf chain grows by (new_len - p->tot_len) bytes + * (which may be negative in case of shrinking) */ + grow = new_len - p->tot_len; + + /* first, step over any pbufs that should remain in the chain */ + rem_len = new_len; + q = p; + /* should this pbuf be kept? */ + while (rem_len > q->len) { + /* decrease remaining length by pbuf length */ + rem_len -= q->len; + /* decrease total length indicator */ + LWIP_ASSERT("grow < max_u16_t", grow < 0xffff); + q->tot_len += (u16_t)grow; + /* proceed to next pbuf in chain */ + q = q->next; + LWIP_ASSERT("pbuf_realloc: q != NULL", q != NULL); + } + /* we have now reached the new last pbuf (in q) */ + /* rem_len == desired length for pbuf q */ + + /* shrink allocated memory for PBUF_RAM */ + /* (other types merely adjust their length fields */ + if ((q->type == PBUF_RAM) && (rem_len != q->len)) { + /* reallocate and adjust the length of the pbuf that will be split */ + q = (struct pbuf *)mem_trim(q, (u16_t)((u8_t *)q->payload - (u8_t *)q) + rem_len); + LWIP_ASSERT("mem_trim returned q == NULL", q != NULL); + } + /* adjust length fields for new last pbuf */ + q->len = rem_len; + q->tot_len = q->len; + + /* any remaining pbufs in chain? */ + if (q->next != NULL) { + /* free remaining pbufs in chain */ + pbuf_free(q->next); + } + /* q is last packet in chain */ + q->next = NULL; + +} + +/** + * Adjusts the payload pointer to hide or reveal headers in the payload. + * + * Adjusts the ->payload pointer so that space for a header + * (dis)appears in the pbuf payload. + * + * The ->payload, ->tot_len and ->len fields are adjusted. + * + * @param p pbuf to change the header size. + * @param header_size_increment Number of bytes to increment header size which + * increases the size of the pbuf. New space is on the front. + * (Using a negative value decreases the header size.) + * If hdr_size_inc is 0, this function does nothing and returns succesful. + * + * PBUF_ROM and PBUF_REF type buffers cannot have their sizes increased, so + * the call will fail. A check is made that the increase in header size does + * not move the payload pointer in front of the start of the buffer. + * @return non-zero on failure, zero on success. + * + */ +u8_t +pbuf_header(struct pbuf *p, s16_t header_size_increment) +{ + u16_t type; + void *payload; + u16_t increment_magnitude; + + LWIP_ASSERT("p != NULL", p != NULL); + if ((header_size_increment == 0) || (p == NULL)) { + return 0; + } + + if (header_size_increment < 0){ + increment_magnitude = -header_size_increment; + /* Check that we aren't going to move off the end of the pbuf */ + LWIP_ERROR("increment_magnitude <= p->len", (increment_magnitude <= p->len), return 1;); + } else { + increment_magnitude = header_size_increment; +#if 0 + /* Can't assert these as some callers speculatively call + pbuf_header() to see if it's OK. Will return 1 below instead. */ + /* Check that we've got the correct type of pbuf to work with */ + LWIP_ASSERT("p->type == PBUF_RAM || p->type == PBUF_POOL", + p->type == PBUF_RAM || p->type == PBUF_POOL); + /* Check that we aren't going to move off the beginning of the pbuf */ + LWIP_ASSERT("p->payload - increment_magnitude >= p + SIZEOF_STRUCT_PBUF", + (u8_t *)p->payload - increment_magnitude >= (u8_t *)p + SIZEOF_STRUCT_PBUF); +#endif + } + + type = p->type; + /* remember current payload pointer */ + payload = p->payload; + + /* pbuf types containing payloads? */ + if (type == PBUF_RAM || type == PBUF_POOL) { + /* set new payload pointer */ + p->payload = (u8_t *)p->payload - header_size_increment; + /* boundary check fails? */ + if ((u8_t *)p->payload < (u8_t *)p + SIZEOF_STRUCT_PBUF) { + LWIP_DEBUGF( PBUF_DEBUG | LWIP_DBG_LEVEL_SERIOUS, + ("pbuf_header: failed as %p < %p (not enough space for new header size)\n", + (void *)p->payload, (void *)(p + 1))); + /* restore old payload pointer */ + p->payload = payload; + /* bail out unsuccesfully */ + return 1; + } + /* pbuf types refering to external payloads? */ + } else if (type == PBUF_REF || type == PBUF_ROM) { + /* hide a header in the payload? */ + if ((header_size_increment < 0) && (increment_magnitude <= p->len)) { + /* increase payload pointer */ + p->payload = (u8_t *)p->payload - header_size_increment; + } else { + /* cannot expand payload to front (yet!) + * bail out unsuccesfully */ + return 1; + } + } else { + /* Unknown type */ + LWIP_ASSERT("bad pbuf type", 0); + return 1; + } + /* modify pbuf length fields */ + p->len += header_size_increment; + p->tot_len += header_size_increment; + + LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_header: old %p new %p (%"S16_F")\n", + (void *)payload, (void *)p->payload, header_size_increment)); + + return 0; +} + +/** + * Dereference a pbuf chain or queue and deallocate any no-longer-used + * pbufs at the head of this chain or queue. + * + * Decrements the pbuf reference count. If it reaches zero, the pbuf is + * deallocated. + * + * For a pbuf chain, this is repeated for each pbuf in the chain, + * up to the first pbuf which has a non-zero reference count after + * decrementing. So, when all reference counts are one, the whole + * chain is free'd. + * + * @param p The pbuf (chain) to be dereferenced. + * + * @return the number of pbufs that were de-allocated + * from the head of the chain. + * + * @note MUST NOT be called on a packet queue (Not verified to work yet). + * @note the reference counter of a pbuf equals the number of pointers + * that refer to the pbuf (or into the pbuf). + * + * @internal examples: + * + * Assuming existing chains a->b->c with the following reference + * counts, calling pbuf_free(a) results in: + * + * 1->2->3 becomes ...1->3 + * 3->3->3 becomes 2->3->3 + * 1->1->2 becomes ......1 + * 2->1->1 becomes 1->1->1 + * 1->1->1 becomes ....... + * + */ +u8_t +pbuf_free(struct pbuf *p) +{ + u16_t type; + struct pbuf *q; + u8_t count; + + if (p == NULL) { + LWIP_ASSERT("p != NULL", p != NULL); + /* if assertions are disabled, proceed with debug output */ + LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_LEVEL_SERIOUS, + ("pbuf_free(p == NULL) was called.\n")); + return 0; + } + LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_free(%p)\n", (void *)p)); + + PERF_START; + + LWIP_ASSERT("pbuf_free: sane type", + p->type == PBUF_RAM || p->type == PBUF_ROM || + p->type == PBUF_REF || p->type == PBUF_POOL); + + count = 0; + /* de-allocate all consecutive pbufs from the head of the chain that + * obtain a zero reference count after decrementing*/ + while (p != NULL) { + u16_t ref; + SYS_ARCH_DECL_PROTECT(old_level); + /* Since decrementing ref cannot be guaranteed to be a single machine operation + * we must protect it. We put the new ref into a local variable to prevent + * further protection. */ + SYS_ARCH_PROTECT(old_level); + /* all pbufs in a chain are referenced at least once */ + LWIP_ASSERT("pbuf_free: p->ref > 0", p->ref > 0); + /* decrease reference count (number of pointers to pbuf) */ + ref = --(p->ref); + SYS_ARCH_UNPROTECT(old_level); + /* this pbuf is no longer referenced to? */ + if (ref == 0) { + /* remember next pbuf in chain for next iteration */ + q = p->next; + LWIP_DEBUGF( PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_free: deallocating %p\n", (void *)p)); + type = p->type; +#if LWIP_SUPPORT_CUSTOM_PBUF + /* is this a custom pbuf? */ + if ((p->flags & PBUF_FLAG_IS_CUSTOM) != 0) { + struct pbuf_custom *pc = (struct pbuf_custom*)p; + LWIP_ASSERT("pc->custom_free_function != NULL", pc->custom_free_function != NULL); + pc->custom_free_function(p); + } else +#endif /* LWIP_SUPPORT_CUSTOM_PBUF */ + { + /* is this a pbuf from the pool? */ + if (type == PBUF_POOL) { + memp_free(MEMP_PBUF_POOL, p); + /* is this a ROM or RAM referencing pbuf? */ + } else if (type == PBUF_ROM || type == PBUF_REF) { + memp_free(MEMP_PBUF, p); + /* type == PBUF_RAM */ + } else { + mem_free(p); + } + } + count++; + /* proceed to next pbuf */ + p = q; + /* p->ref > 0, this pbuf is still referenced to */ + /* (and so the remaining pbufs in chain as well) */ + } else { + LWIP_DEBUGF( PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_free: %p has ref %"U16_F", ending here.\n", (void *)p, ref)); + /* stop walking through the chain */ + p = NULL; + } + } + PERF_STOP("pbuf_free"); + /* return number of de-allocated pbufs */ + return count; +} + +/** + * Count number of pbufs in a chain + * + * @param p first pbuf of chain + * @return the number of pbufs in a chain + */ + +u8_t +pbuf_clen(struct pbuf *p) +{ + u8_t len; + + len = 0; + while (p != NULL) { + ++len; + p = p->next; + } + return len; +} + +/** + * Increment the reference count of the pbuf. + * + * @param p pbuf to increase reference counter of + * + */ +void +pbuf_ref(struct pbuf *p) +{ + SYS_ARCH_DECL_PROTECT(old_level); + /* pbuf given? */ + if (p != NULL) { + SYS_ARCH_PROTECT(old_level); + ++(p->ref); + SYS_ARCH_UNPROTECT(old_level); + } +} + +/** + * Concatenate two pbufs (each may be a pbuf chain) and take over + * the caller's reference of the tail pbuf. + * + * @note The caller MAY NOT reference the tail pbuf afterwards. + * Use pbuf_chain() for that purpose. + * + * @see pbuf_chain() + */ + +void +pbuf_cat(struct pbuf *h, struct pbuf *t) +{ + struct pbuf *p; + + LWIP_ERROR("(h != NULL) && (t != NULL) (programmer violates API)", + ((h != NULL) && (t != NULL)), return;); + + /* proceed to last pbuf of chain */ + for (p = h; p->next != NULL; p = p->next) { + /* add total length of second chain to all totals of first chain */ + p->tot_len += t->tot_len; + } + /* { p is last pbuf of first h chain, p->next == NULL } */ + LWIP_ASSERT("p->tot_len == p->len (of last pbuf in chain)", p->tot_len == p->len); + LWIP_ASSERT("p->next == NULL", p->next == NULL); + /* add total length of second chain to last pbuf total of first chain */ + p->tot_len += t->tot_len; + /* chain last pbuf of head (p) with first of tail (t) */ + p->next = t; + /* p->next now references t, but the caller will drop its reference to t, + * so netto there is no change to the reference count of t. + */ +} + +/** + * Chain two pbufs (or pbuf chains) together. + * + * The caller MUST call pbuf_free(t) once it has stopped + * using it. Use pbuf_cat() instead if you no longer use t. + * + * @param h head pbuf (chain) + * @param t tail pbuf (chain) + * @note The pbufs MUST belong to the same packet. + * @note MAY NOT be called on a packet queue. + * + * The ->tot_len fields of all pbufs of the head chain are adjusted. + * The ->next field of the last pbuf of the head chain is adjusted. + * The ->ref field of the first pbuf of the tail chain is adjusted. + * + */ +void +pbuf_chain(struct pbuf *h, struct pbuf *t) +{ + pbuf_cat(h, t); + /* t is now referenced by h */ + pbuf_ref(t); + LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_chain: %p references %p\n", (void *)h, (void *)t)); +} + +/** + * Dechains the first pbuf from its succeeding pbufs in the chain. + * + * Makes p->tot_len field equal to p->len. + * @param p pbuf to dechain + * @return remainder of the pbuf chain, or NULL if it was de-allocated. + * @note May not be called on a packet queue. + */ +struct pbuf * +pbuf_dechain(struct pbuf *p) +{ + struct pbuf *q; + u8_t tail_gone = 1; + /* tail */ + q = p->next; + /* pbuf has successor in chain? */ + if (q != NULL) { + /* assert tot_len invariant: (p->tot_len == p->len + (p->next? p->next->tot_len: 0) */ + LWIP_ASSERT("p->tot_len == p->len + q->tot_len", q->tot_len == p->tot_len - p->len); + /* enforce invariant if assertion is disabled */ + q->tot_len = p->tot_len - p->len; + /* decouple pbuf from remainder */ + p->next = NULL; + /* total length of pbuf p is its own length only */ + p->tot_len = p->len; + /* q is no longer referenced by p, free it */ + LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_dechain: unreferencing %p\n", (void *)q)); + tail_gone = pbuf_free(q); + if (tail_gone > 0) { + LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, + ("pbuf_dechain: deallocated %p (as it is no longer referenced)\n", (void *)q)); + } + /* return remaining tail or NULL if deallocated */ + } + /* assert tot_len invariant: (p->tot_len == p->len + (p->next? p->next->tot_len: 0) */ + LWIP_ASSERT("p->tot_len == p->len", p->tot_len == p->len); + return ((tail_gone > 0) ? NULL : q); +} + +/** + * + * Create PBUF_RAM copies of pbufs. + * + * Used to queue packets on behalf of the lwIP stack, such as + * ARP based queueing. + * + * @note You MUST explicitly use p = pbuf_take(p); + * + * @note Only one packet is copied, no packet queue! + * + * @param p_to pbuf destination of the copy + * @param p_from pbuf source of the copy + * + * @return ERR_OK if pbuf was copied + * ERR_ARG if one of the pbufs is NULL or p_to is not big + * enough to hold p_from + */ +err_t +pbuf_copy(struct pbuf *p_to, struct pbuf *p_from) +{ + u16_t offset_to=0, offset_from=0, len; + + LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_copy(%p, %p)\n", + (void*)p_to, (void*)p_from)); + + /* is the target big enough to hold the source? */ + LWIP_ERROR("pbuf_copy: target not big enough to hold source", ((p_to != NULL) && + (p_from != NULL) && (p_to->tot_len >= p_from->tot_len)), return ERR_ARG;); + + /* iterate through pbuf chain */ + do + { + LWIP_ASSERT("p_to != NULL", p_to != NULL); + /* copy one part of the original chain */ + if ((p_to->len - offset_to) >= (p_from->len - offset_from)) { + /* complete current p_from fits into current p_to */ + len = p_from->len - offset_from; + } else { + /* current p_from does not fit into current p_to */ + len = p_to->len - offset_to; + } + MEMCPY((u8_t*)p_to->payload + offset_to, (u8_t*)p_from->payload + offset_from, len); + offset_to += len; + offset_from += len; + LWIP_ASSERT("offset_to <= p_to->len", offset_to <= p_to->len); + if (offset_to == p_to->len) { + /* on to next p_to (if any) */ + offset_to = 0; + p_to = p_to->next; + } + LWIP_ASSERT("offset_from <= p_from->len", offset_from <= p_from->len); + if (offset_from >= p_from->len) { + /* on to next p_from (if any) */ + offset_from = 0; + p_from = p_from->next; + } + + if((p_from != NULL) && (p_from->len == p_from->tot_len)) { + /* don't copy more than one packet! */ + LWIP_ERROR("pbuf_copy() does not allow packet queues!\n", + (p_from->next == NULL), return ERR_VAL;); + } + if((p_to != NULL) && (p_to->len == p_to->tot_len)) { + /* don't copy more than one packet! */ + LWIP_ERROR("pbuf_copy() does not allow packet queues!\n", + (p_to->next == NULL), return ERR_VAL;); + } + } while (p_from); + LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_copy: end of chain reached.\n")); + return ERR_OK; +} + +/** + * Copy (part of) the contents of a packet buffer + * to an application supplied buffer. + * + * @param buf the pbuf from which to copy data + * @param dataptr the application supplied buffer + * @param len length of data to copy (dataptr must be big enough). No more + * than buf->tot_len will be copied, irrespective of len + * @param offset offset into the packet buffer from where to begin copying len bytes + * @return the number of bytes copied, or 0 on failure + */ +u16_t +pbuf_copy_partial(struct pbuf *buf, void *dataptr, u16_t len, u16_t offset) +{ + struct pbuf *p; + u16_t left; + u16_t buf_copy_len; + u16_t copied_total = 0; + + LWIP_ERROR("pbuf_copy_partial: invalid buf", (buf != NULL), return 0;); + LWIP_ERROR("pbuf_copy_partial: invalid dataptr", (dataptr != NULL), return 0;); + + left = 0; + + if((buf == NULL) || (dataptr == NULL)) { + return 0; + } + + /* Note some systems use byte copy if dataptr or one of the pbuf payload pointers are unaligned. */ + for(p = buf; len != 0 && p != NULL; p = p->next) { + if ((offset != 0) && (offset >= p->len)) { + /* don't copy from this buffer -> on to the next */ + offset -= p->len; + } else { + /* copy from this buffer. maybe only partially. */ + buf_copy_len = p->len - offset; + if (buf_copy_len > len) + buf_copy_len = len; + /* copy the necessary parts of the buffer */ + MEMCPY(&((char*)dataptr)[left], &((char*)p->payload)[offset], buf_copy_len); + copied_total += buf_copy_len; + left += buf_copy_len; + len -= buf_copy_len; + offset = 0; + } + } + return copied_total; +} + +/** + * Copy application supplied data into a pbuf. + * This function can only be used to copy the equivalent of buf->tot_len data. + * + * @param buf pbuf to fill with data + * @param dataptr application supplied data buffer + * @param len length of the application supplied data buffer + * + * @return ERR_OK if successful, ERR_MEM if the pbuf is not big enough + */ +err_t +pbuf_take(struct pbuf *buf, const void *dataptr, u16_t len) +{ + struct pbuf *p; + u16_t buf_copy_len; + u16_t total_copy_len = len; + u16_t copied_total = 0; + + LWIP_ERROR("pbuf_take: invalid buf", (buf != NULL), return 0;); + LWIP_ERROR("pbuf_take: invalid dataptr", (dataptr != NULL), return 0;); + + if ((buf == NULL) || (dataptr == NULL) || (buf->tot_len < len)) { + return ERR_ARG; + } + + /* Note some systems use byte copy if dataptr or one of the pbuf payload pointers are unaligned. */ + for(p = buf; total_copy_len != 0; p = p->next) { + LWIP_ASSERT("pbuf_take: invalid pbuf", p != NULL); + buf_copy_len = total_copy_len; + if (buf_copy_len > p->len) { + /* this pbuf cannot hold all remaining data */ + buf_copy_len = p->len; + } + /* copy the necessary parts of the buffer */ + MEMCPY(p->payload, &((char*)dataptr)[copied_total], buf_copy_len); + total_copy_len -= buf_copy_len; + copied_total += buf_copy_len; + } + LWIP_ASSERT("did not copy all data", total_copy_len == 0 && copied_total == len); + return ERR_OK; +} + +/** + * Creates a single pbuf out of a queue of pbufs. + * + * @remark: Either the source pbuf 'p' is freed by this function or the original + * pbuf 'p' is returned, therefore the caller has to check the result! + * + * @param p the source pbuf + * @param layer pbuf_layer of the new pbuf + * + * @return a new, single pbuf (p->next is NULL) + * or the old pbuf if allocation fails + */ +struct pbuf* +pbuf_coalesce(struct pbuf *p, pbuf_layer layer) +{ + struct pbuf *q; + err_t err; + if (p->next == NULL) { + return p; + } + q = pbuf_alloc(layer, p->tot_len, PBUF_RAM); + if (q == NULL) { + /* @todo: what do we do now? */ + return p; + } + err = pbuf_copy(q, p); + LWIP_ASSERT("pbuf_copy failed", err == ERR_OK); + /* next line references err variable even if LWIP_ASSERT is ignored. */ + (void)err; + pbuf_free(p); + return q; +} + +#if LWIP_CHECKSUM_ON_COPY +/** + * Copies data into a single pbuf (*not* into a pbuf queue!) and updates + * the checksum while copying + * + * @param p the pbuf to copy data into + * @param start_offset offset of p->payload where to copy the data to + * @param dataptr data to copy into the pbuf + * @param len length of data to copy into the pbuf + * @param chksum pointer to the checksum which is updated + * @return ERR_OK if successful, another error if the data does not fit + * within the (first) pbuf (no pbuf queues!) + */ +err_t +pbuf_fill_chksum(struct pbuf *p, u16_t start_offset, const void *dataptr, + u16_t len, u16_t *chksum) +{ + u32_t acc; + u16_t copy_chksum; + char *dst_ptr; + LWIP_ASSERT("p != NULL", p != NULL); + LWIP_ASSERT("dataptr != NULL", dataptr != NULL); + LWIP_ASSERT("chksum != NULL", chksum != NULL); + LWIP_ASSERT("len != 0", len != 0); + + if ((start_offset >= p->len) || (start_offset + len > p->len)) { + return ERR_ARG; + } + + dst_ptr = ((char*)p->payload) + start_offset; + copy_chksum = LWIP_CHKSUM_COPY(dst_ptr, dataptr, len); + if ((start_offset & 1) != 0) { + copy_chksum = SWAP_BYTES_IN_WORD(copy_chksum); + } + acc = *chksum; + acc += copy_chksum; + *chksum = FOLD_U32T(acc); + return ERR_OK; +} +#endif /* LWIP_CHECKSUM_ON_COPY */ + + /** Get one byte from the specified position in a pbuf + * WARNING: returns zero for offset >= p->tot_len + * + * @param p pbuf to parse + * @param offset offset into p of the byte to return + * @return byte at an offset into p OR ZERO IF 'offset' >= p->tot_len + */ +u8_t +pbuf_get_at(struct pbuf* p, u16_t offset) +{ + u16_t copy_from = offset; + struct pbuf* q = p; + + /* get the correct pbuf */ + while ((q != NULL) && (q->len <= copy_from)) { + copy_from -= q->len; + q = q->next; + } + /* return requested data if pbuf is OK */ + if ((q != NULL) && (q->len > copy_from)) { + return ((u8_t*)q->payload)[copy_from]; + } + return 0; +} + +/** Compare pbuf contents at specified offset with memory s2, both of length n + * + * @param p pbuf to compare + * @param offset offset into p at wich to start comparing + * @param s2 buffer to compare + * @param n length of buffer to compare + * @return zero if equal, nonzero otherwise + * (0xffff if p is too short, diffoffset+1 otherwise) + */ +u16_t +pbuf_memcmp(struct pbuf* p, u16_t offset, const void* s2, u16_t n) +{ + u16_t start = offset; + struct pbuf* q = p; + + /* get the correct pbuf */ + while ((q != NULL) && (q->len <= start)) { + start -= q->len; + q = q->next; + } + /* return requested data if pbuf is OK */ + if ((q != NULL) && (q->len > start)) { + u16_t i; + for(i = 0; i < n; i++) { + u8_t a = pbuf_get_at(q, start + i); + u8_t b = ((u8_t*)s2)[i]; + if (a != b) { + return i+1; + } + } + return 0; + } + return 0xffff; +} + +/** Find occurrence of mem (with length mem_len) in pbuf p, starting at offset + * start_offset. + * + * @param p pbuf to search, maximum length is 0xFFFE since 0xFFFF is used as + * return value 'not found' + * @param mem search for the contents of this buffer + * @param mem_len length of 'mem' + * @param start_offset offset into p at which to start searching + * @return 0xFFFF if substr was not found in p or the index where it was found + */ +u16_t +pbuf_memfind(struct pbuf* p, const void* mem, u16_t mem_len, u16_t start_offset) +{ + u16_t i; + u16_t max = p->tot_len - mem_len; + if (p->tot_len >= mem_len + start_offset) { + for(i = start_offset; i <= max; ) { + u16_t plus = pbuf_memcmp(p, i, mem, mem_len); + if (plus == 0) { + return i; + } else { + i += plus; + } + } + } + return 0xFFFF; +} + +/** Find occurrence of substr with length substr_len in pbuf p, start at offset + * start_offset + * WARNING: in contrast to strstr(), this one does not stop at the first \0 in + * the pbuf/source string! + * + * @param p pbuf to search, maximum length is 0xFFFE since 0xFFFF is used as + * return value 'not found' + * @param substr string to search for in p, maximum length is 0xFFFE + * @return 0xFFFF if substr was not found in p or the index where it was found + */ +u16_t +pbuf_strstr(struct pbuf* p, const char* substr) +{ + size_t substr_len; + if ((substr == NULL) || (substr[0] == 0) || (p->tot_len == 0xFFFF)) { + return 0xFFFF; + } + substr_len = strlen(substr); + if (substr_len >= 0xFFFF) { + return 0xFFFF; + } + return pbuf_memfind(p, substr, (u16_t)substr_len, 0); +} diff --git a/features/unsupported/net/lwip/lwip/core/raw.c b/features/unsupported/net/lwip/lwip/core/raw.c new file mode 100644 index 00000000000..9fcb100316d --- /dev/null +++ b/features/unsupported/net/lwip/lwip/core/raw.c @@ -0,0 +1,354 @@ +/** + * @file + * Implementation of raw protocol PCBs for low-level handling of + * different types of protocols besides (or overriding) those + * already available in lwIP. + * + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ + +#include "lwip/opt.h" + +#if LWIP_RAW /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/def.h" +#include "lwip/memp.h" +#include "lwip/ip_addr.h" +#include "lwip/netif.h" +#include "lwip/raw.h" +#include "lwip/stats.h" +#include "arch/perf.h" + +#include + +/** The list of RAW PCBs */ +static struct raw_pcb *raw_pcbs; + +/** + * Determine if in incoming IP packet is covered by a RAW PCB + * and if so, pass it to a user-provided receive callback function. + * + * Given an incoming IP datagram (as a chain of pbufs) this function + * finds a corresponding RAW PCB and calls the corresponding receive + * callback function. + * + * @param p pbuf to be demultiplexed to a RAW PCB. + * @param inp network interface on which the datagram was received. + * @return - 1 if the packet has been eaten by a RAW PCB receive + * callback function. The caller MAY NOT not reference the + * packet any longer, and MAY NOT call pbuf_free(). + * @return - 0 if packet is not eaten (pbuf is still referenced by the + * caller). + * + */ +u8_t +raw_input(struct pbuf *p, struct netif *inp) +{ + struct raw_pcb *pcb, *prev; + struct ip_hdr *iphdr; + s16_t proto; + u8_t eaten = 0; + + LWIP_UNUSED_ARG(inp); + + iphdr = (struct ip_hdr *)p->payload; + proto = IPH_PROTO(iphdr); + + prev = NULL; + pcb = raw_pcbs; + /* loop through all raw pcbs until the packet is eaten by one */ + /* this allows multiple pcbs to match against the packet by design */ + while ((eaten == 0) && (pcb != NULL)) { + if ((pcb->protocol == proto) && + (ip_addr_isany(&pcb->local_ip) || + ip_addr_cmp(&(pcb->local_ip), ¤t_iphdr_dest))) { +#if IP_SOF_BROADCAST_RECV + /* broadcast filter? */ + if ((pcb->so_options & SOF_BROADCAST) || !ip_addr_isbroadcast(¤t_iphdr_dest, inp)) +#endif /* IP_SOF_BROADCAST_RECV */ + { + /* receive callback function available? */ + if (pcb->recv != NULL) { + /* the receive callback function did not eat the packet? */ + if (pcb->recv(pcb->recv_arg, pcb, p, ip_current_src_addr()) != 0) { + /* receive function ate the packet */ + p = NULL; + eaten = 1; + if (prev != NULL) { + /* move the pcb to the front of raw_pcbs so that is + found faster next time */ + prev->next = pcb->next; + pcb->next = raw_pcbs; + raw_pcbs = pcb; + } + } + } + /* no receive callback function was set for this raw PCB */ + } + /* drop the packet */ + } + prev = pcb; + pcb = pcb->next; + } + return eaten; +} + +/** + * Bind a RAW PCB. + * + * @param pcb RAW PCB to be bound with a local address ipaddr. + * @param ipaddr local IP address to bind with. Use IP_ADDR_ANY to + * bind to all local interfaces. + * + * @return lwIP error code. + * - ERR_OK. Successful. No error occured. + * - ERR_USE. The specified IP address is already bound to by + * another RAW PCB. + * + * @see raw_disconnect() + */ +err_t +raw_bind(struct raw_pcb *pcb, ip_addr_t *ipaddr) +{ + ip_addr_set(&pcb->local_ip, ipaddr); + return ERR_OK; +} + +/** + * Connect an RAW PCB. This function is required by upper layers + * of lwip. Using the raw api you could use raw_sendto() instead + * + * This will associate the RAW PCB with the remote address. + * + * @param pcb RAW PCB to be connected with remote address ipaddr and port. + * @param ipaddr remote IP address to connect with. + * + * @return lwIP error code + * + * @see raw_disconnect() and raw_sendto() + */ +err_t +raw_connect(struct raw_pcb *pcb, ip_addr_t *ipaddr) +{ + ip_addr_set(&pcb->remote_ip, ipaddr); + return ERR_OK; +} + + +/** + * Set the callback function for received packets that match the + * raw PCB's protocol and binding. + * + * The callback function MUST either + * - eat the packet by calling pbuf_free() and returning non-zero. The + * packet will not be passed to other raw PCBs or other protocol layers. + * - not free the packet, and return zero. The packet will be matched + * against further PCBs and/or forwarded to another protocol layers. + * + * @return non-zero if the packet was free()d, zero if the packet remains + * available for others. + */ +void +raw_recv(struct raw_pcb *pcb, raw_recv_fn recv, void *recv_arg) +{ + /* remember recv() callback and user data */ + pcb->recv = recv; + pcb->recv_arg = recv_arg; +} + +/** + * Send the raw IP packet to the given address. Note that actually you cannot + * modify the IP headers (this is inconsistent with the receive callback where + * you actually get the IP headers), you can only specify the IP payload here. + * It requires some more changes in lwIP. (there will be a raw_send() function + * then.) + * + * @param pcb the raw pcb which to send + * @param p the IP payload to send + * @param ipaddr the destination address of the IP packet + * + */ +err_t +raw_sendto(struct raw_pcb *pcb, struct pbuf *p, ip_addr_t *ipaddr) +{ + err_t err; + struct netif *netif; + ip_addr_t *src_ip; + struct pbuf *q; /* q will be sent down the stack */ + + LWIP_DEBUGF(RAW_DEBUG | LWIP_DBG_TRACE, ("raw_sendto\n")); + + /* not enough space to add an IP header to first pbuf in given p chain? */ + if (pbuf_header(p, IP_HLEN)) { + /* allocate header in new pbuf */ + q = pbuf_alloc(PBUF_IP, 0, PBUF_RAM); + /* new header pbuf could not be allocated? */ + if (q == NULL) { + LWIP_DEBUGF(RAW_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS, ("raw_sendto: could not allocate header\n")); + return ERR_MEM; + } + if (p->tot_len != 0) { + /* chain header q in front of given pbuf p */ + pbuf_chain(q, p); + } + /* { first pbuf q points to header pbuf } */ + LWIP_DEBUGF(RAW_DEBUG, ("raw_sendto: added header pbuf %p before given pbuf %p\n", (void *)q, (void *)p)); + } else { + /* first pbuf q equals given pbuf */ + q = p; + if(pbuf_header(q, -IP_HLEN)) { + LWIP_ASSERT("Can't restore header we just removed!", 0); + return ERR_MEM; + } + } + + if ((netif = ip_route(ipaddr)) == NULL) { + LWIP_DEBUGF(RAW_DEBUG | LWIP_DBG_LEVEL_WARNING, ("raw_sendto: No route to %"U16_F".%"U16_F".%"U16_F".%"U16_F"\n", + ip4_addr1_16(ipaddr), ip4_addr2_16(ipaddr), ip4_addr3_16(ipaddr), ip4_addr4_16(ipaddr))); + /* free any temporary header pbuf allocated by pbuf_header() */ + if (q != p) { + pbuf_free(q); + } + return ERR_RTE; + } + +#if IP_SOF_BROADCAST + /* broadcast filter? */ + if (((pcb->so_options & SOF_BROADCAST) == 0) && ip_addr_isbroadcast(ipaddr, netif)) { + LWIP_DEBUGF(RAW_DEBUG | LWIP_DBG_LEVEL_WARNING, ("raw_sendto: SOF_BROADCAST not enabled on pcb %p\n", (void *)pcb)); + /* free any temporary header pbuf allocated by pbuf_header() */ + if (q != p) { + pbuf_free(q); + } + return ERR_VAL; + } +#endif /* IP_SOF_BROADCAST */ + + if (ip_addr_isany(&pcb->local_ip)) { + /* use outgoing network interface IP address as source address */ + src_ip = &(netif->ip_addr); + } else { + /* use RAW PCB local IP address as source address */ + src_ip = &(pcb->local_ip); + } + +#if LWIP_NETIF_HWADDRHINT + netif->addr_hint = &(pcb->addr_hint); +#endif /* LWIP_NETIF_HWADDRHINT*/ + err = ip_output_if (q, src_ip, ipaddr, pcb->ttl, pcb->tos, pcb->protocol, netif); +#if LWIP_NETIF_HWADDRHINT + netif->addr_hint = NULL; +#endif /* LWIP_NETIF_HWADDRHINT*/ + + /* did we chain a header earlier? */ + if (q != p) { + /* free the header */ + pbuf_free(q); + } + return err; +} + +/** + * Send the raw IP packet to the address given by raw_connect() + * + * @param pcb the raw pcb which to send + * @param p the IP payload to send + * + */ +err_t +raw_send(struct raw_pcb *pcb, struct pbuf *p) +{ + return raw_sendto(pcb, p, &pcb->remote_ip); +} + +/** + * Remove an RAW PCB. + * + * @param pcb RAW PCB to be removed. The PCB is removed from the list of + * RAW PCB's and the data structure is freed from memory. + * + * @see raw_new() + */ +void +raw_remove(struct raw_pcb *pcb) +{ + struct raw_pcb *pcb2; + /* pcb to be removed is first in list? */ + if (raw_pcbs == pcb) { + /* make list start at 2nd pcb */ + raw_pcbs = raw_pcbs->next; + /* pcb not 1st in list */ + } else { + for(pcb2 = raw_pcbs; pcb2 != NULL; pcb2 = pcb2->next) { + /* find pcb in raw_pcbs list */ + if (pcb2->next != NULL && pcb2->next == pcb) { + /* remove pcb from list */ + pcb2->next = pcb->next; + } + } + } + memp_free(MEMP_RAW_PCB, pcb); +} + +/** + * Create a RAW PCB. + * + * @return The RAW PCB which was created. NULL if the PCB data structure + * could not be allocated. + * + * @param proto the protocol number of the IPs payload (e.g. IP_PROTO_ICMP) + * + * @see raw_remove() + */ +struct raw_pcb * +raw_new(u8_t proto) +{ + struct raw_pcb *pcb; + + LWIP_DEBUGF(RAW_DEBUG | LWIP_DBG_TRACE, ("raw_new\n")); + + pcb = (struct raw_pcb *)memp_malloc(MEMP_RAW_PCB); + /* could allocate RAW PCB? */ + if (pcb != NULL) { + /* initialize PCB to all zeroes */ + memset(pcb, 0, sizeof(struct raw_pcb)); + pcb->protocol = proto; + pcb->ttl = RAW_TTL; + pcb->next = raw_pcbs; + raw_pcbs = pcb; + } + return pcb; +} + +#endif /* LWIP_RAW */ diff --git a/features/unsupported/net/lwip/lwip/core/snmp/asn1_dec.c b/features/unsupported/net/lwip/lwip/core/snmp/asn1_dec.c new file mode 100644 index 00000000000..1d5658207a1 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/core/snmp/asn1_dec.c @@ -0,0 +1,657 @@ +/** + * @file + * Abstract Syntax Notation One (ISO 8824, 8825) decoding + * + * @todo not optimised (yet), favor correctness over speed, favor speed over size + */ + +/* + * Copyright (c) 2006 Axon Digital Design B.V., The Netherlands. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * Author: Christiaan Simons + */ + +#include "lwip/opt.h" + +#if LWIP_SNMP /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/snmp_asn1.h" + +/** + * Retrieves type field from incoming pbuf chain. + * + * @param p points to a pbuf holding an ASN1 coded type field + * @param ofs points to the offset within the pbuf chain of the ASN1 coded type field + * @param type return ASN1 type + * @return ERR_OK if successfull, ERR_ARG if we can't (or won't) decode + */ +err_t +snmp_asn1_dec_type(struct pbuf *p, u16_t ofs, u8_t *type) +{ + u16_t plen, base; + u8_t *msg_ptr; + + plen = 0; + while (p != NULL) + { + base = plen; + plen += p->len; + if (ofs < plen) + { + msg_ptr = (u8_t*)p->payload; + msg_ptr += ofs - base; + *type = *msg_ptr; + return ERR_OK; + } + p = p->next; + } + /* p == NULL, ofs >= plen */ + return ERR_ARG; +} + +/** + * Decodes length field from incoming pbuf chain into host length. + * + * @param p points to a pbuf holding an ASN1 coded length + * @param ofs points to the offset within the pbuf chain of the ASN1 coded length + * @param octets_used returns number of octets used by the length code + * @param length return host order length, upto 64k + * @return ERR_OK if successfull, ERR_ARG if we can't (or won't) decode + */ +err_t +snmp_asn1_dec_length(struct pbuf *p, u16_t ofs, u8_t *octets_used, u16_t *length) +{ + u16_t plen, base; + u8_t *msg_ptr; + + plen = 0; + while (p != NULL) + { + base = plen; + plen += p->len; + if (ofs < plen) + { + msg_ptr = (u8_t*)p->payload; + msg_ptr += ofs - base; + + if (*msg_ptr < 0x80) + { + /* primitive definite length format */ + *octets_used = 1; + *length = *msg_ptr; + return ERR_OK; + } + else if (*msg_ptr == 0x80) + { + /* constructed indefinite length format, termination with two zero octets */ + u8_t zeros; + u8_t i; + + *length = 0; + zeros = 0; + while (zeros != 2) + { + i = 2; + while (i > 0) + { + i--; + (*length) += 1; + ofs += 1; + if (ofs >= plen) + { + /* next octet in next pbuf */ + p = p->next; + if (p == NULL) { return ERR_ARG; } + msg_ptr = (u8_t*)p->payload; + plen += p->len; + } + else + { + /* next octet in same pbuf */ + msg_ptr++; + } + if (*msg_ptr == 0) + { + zeros++; + if (zeros == 2) + { + /* stop while (i > 0) */ + i = 0; + } + } + else + { + zeros = 0; + } + } + } + *octets_used = 1; + return ERR_OK; + } + else if (*msg_ptr == 0x81) + { + /* constructed definite length format, one octet */ + ofs += 1; + if (ofs >= plen) + { + /* next octet in next pbuf */ + p = p->next; + if (p == NULL) { return ERR_ARG; } + msg_ptr = (u8_t*)p->payload; + } + else + { + /* next octet in same pbuf */ + msg_ptr++; + } + *length = *msg_ptr; + *octets_used = 2; + return ERR_OK; + } + else if (*msg_ptr == 0x82) + { + u8_t i; + + /* constructed definite length format, two octets */ + i = 2; + while (i > 0) + { + i--; + ofs += 1; + if (ofs >= plen) + { + /* next octet in next pbuf */ + p = p->next; + if (p == NULL) { return ERR_ARG; } + msg_ptr = (u8_t*)p->payload; + plen += p->len; + } + else + { + /* next octet in same pbuf */ + msg_ptr++; + } + if (i == 0) + { + /* least significant length octet */ + *length |= *msg_ptr; + } + else + { + /* most significant length octet */ + *length = (*msg_ptr) << 8; + } + } + *octets_used = 3; + return ERR_OK; + } + else + { + /* constructed definite length format 3..127 octets, this is too big (>64k) */ + /** @todo: do we need to accept inefficient codings with many leading zero's? */ + *octets_used = 1 + ((*msg_ptr) & 0x7f); + return ERR_ARG; + } + } + p = p->next; + } + + /* p == NULL, ofs >= plen */ + return ERR_ARG; +} + +/** + * Decodes positive integer (counter, gauge, timeticks) into u32_t. + * + * @param p points to a pbuf holding an ASN1 coded integer + * @param ofs points to the offset within the pbuf chain of the ASN1 coded integer + * @param len length of the coded integer field + * @param value return host order integer + * @return ERR_OK if successfull, ERR_ARG if we can't (or won't) decode + * + * @note ASN coded integers are _always_ signed. E.g. +0xFFFF is coded + * as 0x00,0xFF,0xFF. Note the leading sign octet. A positive value + * of 0xFFFFFFFF is preceded with 0x00 and the length is 5 octets!! + */ +err_t +snmp_asn1_dec_u32t(struct pbuf *p, u16_t ofs, u16_t len, u32_t *value) +{ + u16_t plen, base; + u8_t *msg_ptr; + + plen = 0; + while (p != NULL) + { + base = plen; + plen += p->len; + if (ofs < plen) + { + msg_ptr = (u8_t*)p->payload; + msg_ptr += ofs - base; + if ((len > 0) && (len < 6)) + { + /* start from zero */ + *value = 0; + if (*msg_ptr & 0x80) + { + /* negative, expecting zero sign bit! */ + return ERR_ARG; + } + else + { + /* positive */ + if ((len > 1) && (*msg_ptr == 0)) + { + /* skip leading "sign byte" octet 0x00 */ + len--; + ofs += 1; + if (ofs >= plen) + { + /* next octet in next pbuf */ + p = p->next; + if (p == NULL) { return ERR_ARG; } + msg_ptr = (u8_t*)p->payload; + plen += p->len; + } + else + { + /* next octet in same pbuf */ + msg_ptr++; + } + } + } + /* OR octets with value */ + while (len > 1) + { + len--; + *value |= *msg_ptr; + *value <<= 8; + ofs += 1; + if (ofs >= plen) + { + /* next octet in next pbuf */ + p = p->next; + if (p == NULL) { return ERR_ARG; } + msg_ptr = (u8_t*)p->payload; + plen += p->len; + } + else + { + /* next octet in same pbuf */ + msg_ptr++; + } + } + *value |= *msg_ptr; + return ERR_OK; + } + else + { + return ERR_ARG; + } + } + p = p->next; + } + /* p == NULL, ofs >= plen */ + return ERR_ARG; +} + +/** + * Decodes integer into s32_t. + * + * @param p points to a pbuf holding an ASN1 coded integer + * @param ofs points to the offset within the pbuf chain of the ASN1 coded integer + * @param len length of the coded integer field + * @param value return host order integer + * @return ERR_OK if successfull, ERR_ARG if we can't (or won't) decode + * + * @note ASN coded integers are _always_ signed! + */ +err_t +snmp_asn1_dec_s32t(struct pbuf *p, u16_t ofs, u16_t len, s32_t *value) +{ + u16_t plen, base; + u8_t *msg_ptr; +#if BYTE_ORDER == LITTLE_ENDIAN + u8_t *lsb_ptr = (u8_t*)value; +#endif +#if BYTE_ORDER == BIG_ENDIAN + u8_t *lsb_ptr = (u8_t*)value + sizeof(s32_t) - 1; +#endif + u8_t sign; + + plen = 0; + while (p != NULL) + { + base = plen; + plen += p->len; + if (ofs < plen) + { + msg_ptr = (u8_t*)p->payload; + msg_ptr += ofs - base; + if ((len > 0) && (len < 5)) + { + if (*msg_ptr & 0x80) + { + /* negative, start from -1 */ + *value = -1; + sign = 1; + } + else + { + /* positive, start from 0 */ + *value = 0; + sign = 0; + } + /* OR/AND octets with value */ + while (len > 1) + { + len--; + if (sign) + { + *lsb_ptr &= *msg_ptr; + *value <<= 8; + *lsb_ptr |= 255; + } + else + { + *lsb_ptr |= *msg_ptr; + *value <<= 8; + } + ofs += 1; + if (ofs >= plen) + { + /* next octet in next pbuf */ + p = p->next; + if (p == NULL) { return ERR_ARG; } + msg_ptr = (u8_t*)p->payload; + plen += p->len; + } + else + { + /* next octet in same pbuf */ + msg_ptr++; + } + } + if (sign) + { + *lsb_ptr &= *msg_ptr; + } + else + { + *lsb_ptr |= *msg_ptr; + } + return ERR_OK; + } + else + { + return ERR_ARG; + } + } + p = p->next; + } + /* p == NULL, ofs >= plen */ + return ERR_ARG; +} + +/** + * Decodes object identifier from incoming message into array of s32_t. + * + * @param p points to a pbuf holding an ASN1 coded object identifier + * @param ofs points to the offset within the pbuf chain of the ASN1 coded object identifier + * @param len length of the coded object identifier + * @param oid return object identifier struct + * @return ERR_OK if successfull, ERR_ARG if we can't (or won't) decode + */ +err_t +snmp_asn1_dec_oid(struct pbuf *p, u16_t ofs, u16_t len, struct snmp_obj_id *oid) +{ + u16_t plen, base; + u8_t *msg_ptr; + s32_t *oid_ptr; + + plen = 0; + while (p != NULL) + { + base = plen; + plen += p->len; + if (ofs < plen) + { + msg_ptr = (u8_t*)p->payload; + msg_ptr += ofs - base; + + oid->len = 0; + oid_ptr = &oid->id[0]; + if (len > 0) + { + /* first compressed octet */ + if (*msg_ptr == 0x2B) + { + /* (most) common case 1.3 (iso.org) */ + *oid_ptr = 1; + oid_ptr++; + *oid_ptr = 3; + oid_ptr++; + } + else if (*msg_ptr < 40) + { + *oid_ptr = 0; + oid_ptr++; + *oid_ptr = *msg_ptr; + oid_ptr++; + } + else if (*msg_ptr < 80) + { + *oid_ptr = 1; + oid_ptr++; + *oid_ptr = (*msg_ptr) - 40; + oid_ptr++; + } + else + { + *oid_ptr = 2; + oid_ptr++; + *oid_ptr = (*msg_ptr) - 80; + oid_ptr++; + } + oid->len = 2; + } + else + { + /* accepting zero length identifiers e.g. for + getnext operation. uncommon but valid */ + return ERR_OK; + } + len--; + if (len > 0) + { + ofs += 1; + if (ofs >= plen) + { + /* next octet in next pbuf */ + p = p->next; + if (p == NULL) { return ERR_ARG; } + msg_ptr = (u8_t*)p->payload; + plen += p->len; + } + else + { + /* next octet in same pbuf */ + msg_ptr++; + } + } + while ((len > 0) && (oid->len < LWIP_SNMP_OBJ_ID_LEN)) + { + /* sub-identifier uses multiple octets */ + if (*msg_ptr & 0x80) + { + s32_t sub_id = 0; + + while ((*msg_ptr & 0x80) && (len > 1)) + { + len--; + sub_id = (sub_id << 7) + (*msg_ptr & ~0x80); + ofs += 1; + if (ofs >= plen) + { + /* next octet in next pbuf */ + p = p->next; + if (p == NULL) { return ERR_ARG; } + msg_ptr = (u8_t*)p->payload; + plen += p->len; + } + else + { + /* next octet in same pbuf */ + msg_ptr++; + } + } + if (!(*msg_ptr & 0x80) && (len > 0)) + { + /* last octet sub-identifier */ + len--; + sub_id = (sub_id << 7) + *msg_ptr; + *oid_ptr = sub_id; + } + } + else + { + /* !(*msg_ptr & 0x80) sub-identifier uses single octet */ + len--; + *oid_ptr = *msg_ptr; + } + if (len > 0) + { + /* remaining oid bytes available ... */ + ofs += 1; + if (ofs >= plen) + { + /* next octet in next pbuf */ + p = p->next; + if (p == NULL) { return ERR_ARG; } + msg_ptr = (u8_t*)p->payload; + plen += p->len; + } + else + { + /* next octet in same pbuf */ + msg_ptr++; + } + } + oid_ptr++; + oid->len++; + } + if (len == 0) + { + /* len == 0, end of oid */ + return ERR_OK; + } + else + { + /* len > 0, oid->len == LWIP_SNMP_OBJ_ID_LEN or malformed encoding */ + return ERR_ARG; + } + + } + p = p->next; + } + /* p == NULL, ofs >= plen */ + return ERR_ARG; +} + +/** + * Decodes (copies) raw data (ip-addresses, octet strings, opaque encoding) + * from incoming message into array. + * + * @param p points to a pbuf holding an ASN1 coded raw data + * @param ofs points to the offset within the pbuf chain of the ASN1 coded raw data + * @param len length of the coded raw data (zero is valid, e.g. empty string!) + * @param raw_len length of the raw return value + * @param raw return raw bytes + * @return ERR_OK if successfull, ERR_ARG if we can't (or won't) decode + */ +err_t +snmp_asn1_dec_raw(struct pbuf *p, u16_t ofs, u16_t len, u16_t raw_len, u8_t *raw) +{ + u16_t plen, base; + u8_t *msg_ptr; + + if (len > 0) + { + plen = 0; + while (p != NULL) + { + base = plen; + plen += p->len; + if (ofs < plen) + { + msg_ptr = (u8_t*)p->payload; + msg_ptr += ofs - base; + if (raw_len >= len) + { + while (len > 1) + { + /* copy len - 1 octets */ + len--; + *raw = *msg_ptr; + raw++; + ofs += 1; + if (ofs >= plen) + { + /* next octet in next pbuf */ + p = p->next; + if (p == NULL) { return ERR_ARG; } + msg_ptr = (u8_t*)p->payload; + plen += p->len; + } + else + { + /* next octet in same pbuf */ + msg_ptr++; + } + } + /* copy last octet */ + *raw = *msg_ptr; + return ERR_OK; + } + else + { + /* raw_len < len, not enough dst space */ + return ERR_ARG; + } + } + p = p->next; + } + /* p == NULL, ofs >= plen */ + return ERR_ARG; + } + else + { + /* len == 0, empty string */ + return ERR_OK; + } +} + +#endif /* LWIP_SNMP */ diff --git a/features/unsupported/net/lwip/lwip/core/snmp/asn1_enc.c b/features/unsupported/net/lwip/lwip/core/snmp/asn1_enc.c new file mode 100644 index 00000000000..64dfc5f6ead --- /dev/null +++ b/features/unsupported/net/lwip/lwip/core/snmp/asn1_enc.c @@ -0,0 +1,611 @@ +/** + * @file + * Abstract Syntax Notation One (ISO 8824, 8825) encoding + * + * @todo not optimised (yet), favor correctness over speed, favor speed over size + */ + +/* + * Copyright (c) 2006 Axon Digital Design B.V., The Netherlands. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * Author: Christiaan Simons + */ + +#include "lwip/opt.h" + +#if LWIP_SNMP /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/snmp_asn1.h" + +/** + * Returns octet count for length. + * + * @param length + * @param octets_needed points to the return value + */ +void +snmp_asn1_enc_length_cnt(u16_t length, u8_t *octets_needed) +{ + if (length < 0x80U) + { + *octets_needed = 1; + } + else if (length < 0x100U) + { + *octets_needed = 2; + } + else + { + *octets_needed = 3; + } +} + +/** + * Returns octet count for an u32_t. + * + * @param value + * @param octets_needed points to the return value + * + * @note ASN coded integers are _always_ signed. E.g. +0xFFFF is coded + * as 0x00,0xFF,0xFF. Note the leading sign octet. A positive value + * of 0xFFFFFFFF is preceded with 0x00 and the length is 5 octets!! + */ +void +snmp_asn1_enc_u32t_cnt(u32_t value, u16_t *octets_needed) +{ + if (value < 0x80UL) + { + *octets_needed = 1; + } + else if (value < 0x8000UL) + { + *octets_needed = 2; + } + else if (value < 0x800000UL) + { + *octets_needed = 3; + } + else if (value < 0x80000000UL) + { + *octets_needed = 4; + } + else + { + *octets_needed = 5; + } +} + +/** + * Returns octet count for an s32_t. + * + * @param value + * @param octets_needed points to the return value + * + * @note ASN coded integers are _always_ signed. + */ +void +snmp_asn1_enc_s32t_cnt(s32_t value, u16_t *octets_needed) +{ + if (value < 0) + { + value = ~value; + } + if (value < 0x80L) + { + *octets_needed = 1; + } + else if (value < 0x8000L) + { + *octets_needed = 2; + } + else if (value < 0x800000L) + { + *octets_needed = 3; + } + else + { + *octets_needed = 4; + } +} + +/** + * Returns octet count for an object identifier. + * + * @param ident_len object identifier array length + * @param ident points to object identifier array + * @param octets_needed points to the return value + */ +void +snmp_asn1_enc_oid_cnt(u8_t ident_len, s32_t *ident, u16_t *octets_needed) +{ + s32_t sub_id; + u8_t cnt; + + cnt = 0; + if (ident_len > 1) + { + /* compressed prefix in one octet */ + cnt++; + ident_len -= 2; + ident += 2; + } + while(ident_len > 0) + { + ident_len--; + sub_id = *ident; + + sub_id >>= 7; + cnt++; + while(sub_id > 0) + { + sub_id >>= 7; + cnt++; + } + ident++; + } + *octets_needed = cnt; +} + +/** + * Encodes ASN type field into a pbuf chained ASN1 msg. + * + * @param p points to output pbuf to encode value into + * @param ofs points to the offset within the pbuf chain + * @param type input ASN1 type + * @return ERR_OK if successfull, ERR_ARG if we can't (or won't) encode + */ +err_t +snmp_asn1_enc_type(struct pbuf *p, u16_t ofs, u8_t type) +{ + u16_t plen, base; + u8_t *msg_ptr; + + plen = 0; + while (p != NULL) + { + base = plen; + plen += p->len; + if (ofs < plen) + { + msg_ptr = (u8_t*)p->payload; + msg_ptr += ofs - base; + *msg_ptr = type; + return ERR_OK; + } + p = p->next; + } + /* p == NULL, ofs >= plen */ + return ERR_ARG; +} + +/** + * Encodes host order length field into a pbuf chained ASN1 msg. + * + * @param p points to output pbuf to encode length into + * @param ofs points to the offset within the pbuf chain + * @param length is the host order length to be encoded + * @return ERR_OK if successfull, ERR_ARG if we can't (or won't) encode + */ +err_t +snmp_asn1_enc_length(struct pbuf *p, u16_t ofs, u16_t length) +{ + u16_t plen, base; + u8_t *msg_ptr; + + plen = 0; + while (p != NULL) + { + base = plen; + plen += p->len; + if (ofs < plen) + { + msg_ptr = (u8_t*)p->payload; + msg_ptr += ofs - base; + + if (length < 0x80) + { + *msg_ptr = (u8_t)length; + return ERR_OK; + } + else if (length < 0x100) + { + *msg_ptr = 0x81; + ofs += 1; + if (ofs >= plen) + { + /* next octet in next pbuf */ + p = p->next; + if (p == NULL) { return ERR_ARG; } + msg_ptr = (u8_t*)p->payload; + } + else + { + /* next octet in same pbuf */ + msg_ptr++; + } + *msg_ptr = (u8_t)length; + return ERR_OK; + } + else + { + u8_t i; + + /* length >= 0x100 && length <= 0xFFFF */ + *msg_ptr = 0x82; + i = 2; + while (i > 0) + { + i--; + ofs += 1; + if (ofs >= plen) + { + /* next octet in next pbuf */ + p = p->next; + if (p == NULL) { return ERR_ARG; } + msg_ptr = (u8_t*)p->payload; + plen += p->len; + } + else + { + /* next octet in same pbuf */ + msg_ptr++; + } + if (i == 0) + { + /* least significant length octet */ + *msg_ptr = (u8_t)length; + } + else + { + /* most significant length octet */ + *msg_ptr = (u8_t)(length >> 8); + } + } + return ERR_OK; + } + } + p = p->next; + } + /* p == NULL, ofs >= plen */ + return ERR_ARG; +} + +/** + * Encodes u32_t (counter, gauge, timeticks) into a pbuf chained ASN1 msg. + * + * @param p points to output pbuf to encode value into + * @param ofs points to the offset within the pbuf chain + * @param octets_needed encoding length (from snmp_asn1_enc_u32t_cnt()) + * @param value is the host order u32_t value to be encoded + * @return ERR_OK if successfull, ERR_ARG if we can't (or won't) encode + * + * @see snmp_asn1_enc_u32t_cnt() + */ +err_t +snmp_asn1_enc_u32t(struct pbuf *p, u16_t ofs, u16_t octets_needed, u32_t value) +{ + u16_t plen, base; + u8_t *msg_ptr; + + plen = 0; + while (p != NULL) + { + base = plen; + plen += p->len; + if (ofs < plen) + { + msg_ptr = (u8_t*)p->payload; + msg_ptr += ofs - base; + + if (octets_needed == 5) + { + /* not enough bits in 'value' add leading 0x00 */ + octets_needed--; + *msg_ptr = 0x00; + ofs += 1; + if (ofs >= plen) + { + /* next octet in next pbuf */ + p = p->next; + if (p == NULL) { return ERR_ARG; } + msg_ptr = (u8_t*)p->payload; + plen += p->len; + } + else + { + /* next octet in same pbuf */ + msg_ptr++; + } + } + while (octets_needed > 1) + { + octets_needed--; + *msg_ptr = (u8_t)(value >> (octets_needed << 3)); + ofs += 1; + if (ofs >= plen) + { + /* next octet in next pbuf */ + p = p->next; + if (p == NULL) { return ERR_ARG; } + msg_ptr = (u8_t*)p->payload; + plen += p->len; + } + else + { + /* next octet in same pbuf */ + msg_ptr++; + } + } + /* (only) one least significant octet */ + *msg_ptr = (u8_t)value; + return ERR_OK; + } + p = p->next; + } + /* p == NULL, ofs >= plen */ + return ERR_ARG; +} + +/** + * Encodes s32_t integer into a pbuf chained ASN1 msg. + * + * @param p points to output pbuf to encode value into + * @param ofs points to the offset within the pbuf chain + * @param octets_needed encoding length (from snmp_asn1_enc_s32t_cnt()) + * @param value is the host order s32_t value to be encoded + * @return ERR_OK if successfull, ERR_ARG if we can't (or won't) encode + * + * @see snmp_asn1_enc_s32t_cnt() + */ +err_t +snmp_asn1_enc_s32t(struct pbuf *p, u16_t ofs, u16_t octets_needed, s32_t value) +{ + u16_t plen, base; + u8_t *msg_ptr; + + plen = 0; + while (p != NULL) + { + base = plen; + plen += p->len; + if (ofs < plen) + { + msg_ptr = (u8_t*)p->payload; + msg_ptr += ofs - base; + + while (octets_needed > 1) + { + octets_needed--; + *msg_ptr = (u8_t)(value >> (octets_needed << 3)); + ofs += 1; + if (ofs >= plen) + { + /* next octet in next pbuf */ + p = p->next; + if (p == NULL) { return ERR_ARG; } + msg_ptr = (u8_t*)p->payload; + plen += p->len; + } + else + { + /* next octet in same pbuf */ + msg_ptr++; + } + } + /* (only) one least significant octet */ + *msg_ptr = (u8_t)value; + return ERR_OK; + } + p = p->next; + } + /* p == NULL, ofs >= plen */ + return ERR_ARG; +} + +/** + * Encodes object identifier into a pbuf chained ASN1 msg. + * + * @param p points to output pbuf to encode oid into + * @param ofs points to the offset within the pbuf chain + * @param ident_len object identifier array length + * @param ident points to object identifier array + * @return ERR_OK if successfull, ERR_ARG if we can't (or won't) encode + */ +err_t +snmp_asn1_enc_oid(struct pbuf *p, u16_t ofs, u8_t ident_len, s32_t *ident) +{ + u16_t plen, base; + u8_t *msg_ptr; + + plen = 0; + while (p != NULL) + { + base = plen; + plen += p->len; + if (ofs < plen) + { + msg_ptr = (u8_t*)p->payload; + msg_ptr += ofs - base; + + if (ident_len > 1) + { + if ((ident[0] == 1) && (ident[1] == 3)) + { + /* compressed (most common) prefix .iso.org */ + *msg_ptr = 0x2b; + } + else + { + /* calculate prefix */ + *msg_ptr = (u8_t)((ident[0] * 40) + ident[1]); + } + ofs += 1; + if (ofs >= plen) + { + /* next octet in next pbuf */ + p = p->next; + if (p == NULL) { return ERR_ARG; } + msg_ptr = (u8_t*)p->payload; + plen += p->len; + } + else + { + /* next octet in same pbuf */ + msg_ptr++; + } + ident_len -= 2; + ident += 2; + } + else + { +/* @bug: allow empty varbinds for symmetry (we must decode them for getnext), allow partial compression?? */ + /* ident_len <= 1, at least we need zeroDotZero (0.0) (ident_len == 2) */ + return ERR_ARG; + } + while (ident_len > 0) + { + s32_t sub_id; + u8_t shift, tail; + + ident_len--; + sub_id = *ident; + tail = 0; + shift = 28; + while(shift > 0) + { + u8_t code; + + code = (u8_t)(sub_id >> shift); + if ((code != 0) || (tail != 0)) + { + tail = 1; + *msg_ptr = code | 0x80; + ofs += 1; + if (ofs >= plen) + { + /* next octet in next pbuf */ + p = p->next; + if (p == NULL) { return ERR_ARG; } + msg_ptr = (u8_t*)p->payload; + plen += p->len; + } + else + { + /* next octet in same pbuf */ + msg_ptr++; + } + } + shift -= 7; + } + *msg_ptr = (u8_t)sub_id & 0x7F; + if (ident_len > 0) + { + ofs += 1; + if (ofs >= plen) + { + /* next octet in next pbuf */ + p = p->next; + if (p == NULL) { return ERR_ARG; } + msg_ptr = (u8_t*)p->payload; + plen += p->len; + } + else + { + /* next octet in same pbuf */ + msg_ptr++; + } + } + /* proceed to next sub-identifier */ + ident++; + } + return ERR_OK; + } + p = p->next; + } + /* p == NULL, ofs >= plen */ + return ERR_ARG; +} + +/** + * Encodes raw data (octet string, opaque) into a pbuf chained ASN1 msg. + * + * @param p points to output pbuf to encode raw data into + * @param ofs points to the offset within the pbuf chain + * @param raw_len raw data length + * @param raw points raw data + * @return ERR_OK if successfull, ERR_ARG if we can't (or won't) encode + */ +err_t +snmp_asn1_enc_raw(struct pbuf *p, u16_t ofs, u16_t raw_len, u8_t *raw) +{ + u16_t plen, base; + u8_t *msg_ptr; + + plen = 0; + while (p != NULL) + { + base = plen; + plen += p->len; + if (ofs < plen) + { + msg_ptr = (u8_t*)p->payload; + msg_ptr += ofs - base; + + while (raw_len > 1) + { + /* copy raw_len - 1 octets */ + raw_len--; + *msg_ptr = *raw; + raw++; + ofs += 1; + if (ofs >= plen) + { + /* next octet in next pbuf */ + p = p->next; + if (p == NULL) { return ERR_ARG; } + msg_ptr = (u8_t*)p->payload; + plen += p->len; + } + else + { + /* next octet in same pbuf */ + msg_ptr++; + } + } + if (raw_len > 0) + { + /* copy last or single octet */ + *msg_ptr = *raw; + } + return ERR_OK; + } + p = p->next; + } + /* p == NULL, ofs >= plen */ + return ERR_ARG; +} + +#endif /* LWIP_SNMP */ diff --git a/features/unsupported/net/lwip/lwip/core/snmp/mib2.c b/features/unsupported/net/lwip/lwip/core/snmp/mib2.c new file mode 100644 index 00000000000..29decd306f3 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/core/snmp/mib2.c @@ -0,0 +1,4146 @@ +/** + * @file + * Management Information Base II (RFC1213) objects and functions. + * + * @note the object identifiers for this MIB-2 and private MIB tree + * must be kept in sorted ascending order. This to ensure correct getnext operation. + */ + +/* + * Copyright (c) 2006 Axon Digital Design B.V., The Netherlands. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * Author: Christiaan Simons + */ + +#include "lwip/opt.h" + +#if LWIP_SNMP /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/snmp.h" +#include "lwip/netif.h" +#include "lwip/ip.h" +#include "lwip/ip_frag.h" +#include "lwip/mem.h" +#include "lwip/tcp_impl.h" +#include "lwip/udp.h" +#include "lwip/snmp_asn1.h" +#include "lwip/snmp_structs.h" +#include "lwip/sys.h" +#include "netif/etharp.h" + +/** + * IANA assigned enterprise ID for lwIP is 26381 + * @see http://www.iana.org/assignments/enterprise-numbers + * + * @note this enterprise ID is assigned to the lwIP project, + * all object identifiers living under this ID are assigned + * by the lwIP maintainers (contact Christiaan Simons)! + * @note don't change this define, use snmp_set_sysobjid() + * + * If you need to create your own private MIB you'll need + * to apply for your own enterprise ID with IANA: + * http://www.iana.org/numbers.html + */ +#define SNMP_ENTERPRISE_ID 26381 +#define SNMP_SYSOBJID_LEN 7 +#define SNMP_SYSOBJID {1, 3, 6, 1, 4, 1, SNMP_ENTERPRISE_ID} + +#ifndef SNMP_SYSSERVICES +#define SNMP_SYSSERVICES ((1 << 6) | (1 << 3) | ((IP_FORWARD) << 2)) +#endif + +#ifndef SNMP_GET_SYSUPTIME +#define SNMP_GET_SYSUPTIME(sysuptime) +#endif + +static void system_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od); +static void system_get_value(struct obj_def *od, u16_t len, void *value); +static u8_t system_set_test(struct obj_def *od, u16_t len, void *value); +static void system_set_value(struct obj_def *od, u16_t len, void *value); +static void interfaces_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od); +static void interfaces_get_value(struct obj_def *od, u16_t len, void *value); +static void ifentry_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od); +static void ifentry_get_value(struct obj_def *od, u16_t len, void *value); +#if !SNMP_SAFE_REQUESTS +static u8_t ifentry_set_test (struct obj_def *od, u16_t len, void *value); +static void ifentry_set_value (struct obj_def *od, u16_t len, void *value); +#endif /* SNMP_SAFE_REQUESTS */ +static void atentry_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od); +static void atentry_get_value(struct obj_def *od, u16_t len, void *value); +static void ip_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od); +static void ip_get_value(struct obj_def *od, u16_t len, void *value); +static u8_t ip_set_test(struct obj_def *od, u16_t len, void *value); +static void ip_addrentry_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od); +static void ip_addrentry_get_value(struct obj_def *od, u16_t len, void *value); +static void ip_rteentry_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od); +static void ip_rteentry_get_value(struct obj_def *od, u16_t len, void *value); +static void ip_ntomentry_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od); +static void ip_ntomentry_get_value(struct obj_def *od, u16_t len, void *value); +static void icmp_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od); +static void icmp_get_value(struct obj_def *od, u16_t len, void *value); +#if LWIP_TCP +static void tcp_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od); +static void tcp_get_value(struct obj_def *od, u16_t len, void *value); +#ifdef THIS_SEEMS_UNUSED +static void tcpconnentry_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od); +static void tcpconnentry_get_value(struct obj_def *od, u16_t len, void *value); +#endif +#endif +static void udp_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od); +static void udp_get_value(struct obj_def *od, u16_t len, void *value); +static void udpentry_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od); +static void udpentry_get_value(struct obj_def *od, u16_t len, void *value); +static void snmp_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od); +static void snmp_get_value(struct obj_def *od, u16_t len, void *value); +static u8_t snmp_set_test(struct obj_def *od, u16_t len, void *value); +static void snmp_set_value(struct obj_def *od, u16_t len, void *value); + + +/* snmp .1.3.6.1.2.1.11 */ +const mib_scalar_node snmp_scalar = { + &snmp_get_object_def, + &snmp_get_value, + &snmp_set_test, + &snmp_set_value, + MIB_NODE_SC, + 0 +}; +const s32_t snmp_ids[28] = { + 1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 13, 14, 15, 16, + 17, 18, 19, 20, 21, 22, 24, 25, 26, 27, 28, 29, 30 +}; +struct mib_node* const snmp_nodes[28] = { + (struct mib_node*)&snmp_scalar, (struct mib_node*)&snmp_scalar, + (struct mib_node*)&snmp_scalar, (struct mib_node*)&snmp_scalar, + (struct mib_node*)&snmp_scalar, (struct mib_node*)&snmp_scalar, + (struct mib_node*)&snmp_scalar, (struct mib_node*)&snmp_scalar, + (struct mib_node*)&snmp_scalar, (struct mib_node*)&snmp_scalar, + (struct mib_node*)&snmp_scalar, (struct mib_node*)&snmp_scalar, + (struct mib_node*)&snmp_scalar, (struct mib_node*)&snmp_scalar, + (struct mib_node*)&snmp_scalar, (struct mib_node*)&snmp_scalar, + (struct mib_node*)&snmp_scalar, (struct mib_node*)&snmp_scalar, + (struct mib_node*)&snmp_scalar, (struct mib_node*)&snmp_scalar, + (struct mib_node*)&snmp_scalar, (struct mib_node*)&snmp_scalar, + (struct mib_node*)&snmp_scalar, (struct mib_node*)&snmp_scalar, + (struct mib_node*)&snmp_scalar, (struct mib_node*)&snmp_scalar, + (struct mib_node*)&snmp_scalar, (struct mib_node*)&snmp_scalar +}; +const struct mib_array_node snmp = { + &noleafs_get_object_def, + &noleafs_get_value, + &noleafs_set_test, + &noleafs_set_value, + MIB_NODE_AR, + 28, + snmp_ids, + snmp_nodes +}; + +/* dot3 and EtherLike MIB not planned. (transmission .1.3.6.1.2.1.10) */ +/* historical (some say hysterical). (cmot .1.3.6.1.2.1.9) */ +/* lwIP has no EGP, thus may not implement it. (egp .1.3.6.1.2.1.8) */ + +/* udp .1.3.6.1.2.1.7 */ +/** index root node for udpTable */ +struct mib_list_rootnode udp_root = { + &noleafs_get_object_def, + &noleafs_get_value, + &noleafs_set_test, + &noleafs_set_value, + MIB_NODE_LR, + 0, + NULL, + NULL, + 0 +}; +const s32_t udpentry_ids[2] = { 1, 2 }; +struct mib_node* const udpentry_nodes[2] = { + (struct mib_node*)&udp_root, (struct mib_node*)&udp_root, +}; +const struct mib_array_node udpentry = { + &noleafs_get_object_def, + &noleafs_get_value, + &noleafs_set_test, + &noleafs_set_value, + MIB_NODE_AR, + 2, + udpentry_ids, + udpentry_nodes +}; + +s32_t udptable_id = 1; +struct mib_node* udptable_node = (struct mib_node*)&udpentry; +struct mib_ram_array_node udptable = { + &noleafs_get_object_def, + &noleafs_get_value, + &noleafs_set_test, + &noleafs_set_value, + MIB_NODE_RA, + 0, + &udptable_id, + &udptable_node +}; + +const mib_scalar_node udp_scalar = { + &udp_get_object_def, + &udp_get_value, + &noleafs_set_test, + &noleafs_set_value, + MIB_NODE_SC, + 0 +}; +const s32_t udp_ids[5] = { 1, 2, 3, 4, 5 }; +struct mib_node* const udp_nodes[5] = { + (struct mib_node*)&udp_scalar, (struct mib_node*)&udp_scalar, + (struct mib_node*)&udp_scalar, (struct mib_node*)&udp_scalar, + (struct mib_node*)&udptable +}; +const struct mib_array_node udp = { + &noleafs_get_object_def, + &noleafs_get_value, + &noleafs_set_test, + &noleafs_set_value, + MIB_NODE_AR, + 5, + udp_ids, + udp_nodes +}; + +/* tcp .1.3.6.1.2.1.6 */ +#if LWIP_TCP +/* only if the TCP protocol is available may implement this group */ +/** index root node for tcpConnTable */ +struct mib_list_rootnode tcpconntree_root = { + &noleafs_get_object_def, + &noleafs_get_value, + &noleafs_set_test, + &noleafs_set_value, + MIB_NODE_LR, + 0, + NULL, + NULL, + 0 +}; +const s32_t tcpconnentry_ids[5] = { 1, 2, 3, 4, 5 }; +struct mib_node* const tcpconnentry_nodes[5] = { + (struct mib_node*)&tcpconntree_root, (struct mib_node*)&tcpconntree_root, + (struct mib_node*)&tcpconntree_root, (struct mib_node*)&tcpconntree_root, + (struct mib_node*)&tcpconntree_root +}; +const struct mib_array_node tcpconnentry = { + &noleafs_get_object_def, + &noleafs_get_value, + &noleafs_set_test, + &noleafs_set_value, + MIB_NODE_AR, + 5, + tcpconnentry_ids, + tcpconnentry_nodes +}; + +s32_t tcpconntable_id = 1; +struct mib_node* tcpconntable_node = (struct mib_node*)&tcpconnentry; +struct mib_ram_array_node tcpconntable = { + &noleafs_get_object_def, + &noleafs_get_value, + &noleafs_set_test, + &noleafs_set_value, + MIB_NODE_RA, +/** @todo update maxlength when inserting / deleting from table + 0 when table is empty, 1 when more than one entry */ + 0, + &tcpconntable_id, + &tcpconntable_node +}; + +const mib_scalar_node tcp_scalar = { + &tcp_get_object_def, + &tcp_get_value, + &noleafs_set_test, + &noleafs_set_value, + MIB_NODE_SC, + 0 +}; +const s32_t tcp_ids[15] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }; +struct mib_node* const tcp_nodes[15] = { + (struct mib_node*)&tcp_scalar, (struct mib_node*)&tcp_scalar, + (struct mib_node*)&tcp_scalar, (struct mib_node*)&tcp_scalar, + (struct mib_node*)&tcp_scalar, (struct mib_node*)&tcp_scalar, + (struct mib_node*)&tcp_scalar, (struct mib_node*)&tcp_scalar, + (struct mib_node*)&tcp_scalar, (struct mib_node*)&tcp_scalar, + (struct mib_node*)&tcp_scalar, (struct mib_node*)&tcp_scalar, + (struct mib_node*)&tcpconntable, (struct mib_node*)&tcp_scalar, + (struct mib_node*)&tcp_scalar +}; +const struct mib_array_node tcp = { + &noleafs_get_object_def, + &noleafs_get_value, + &noleafs_set_test, + &noleafs_set_value, + MIB_NODE_AR, + 15, + tcp_ids, + tcp_nodes +}; +#endif + +/* icmp .1.3.6.1.2.1.5 */ +const mib_scalar_node icmp_scalar = { + &icmp_get_object_def, + &icmp_get_value, + &noleafs_set_test, + &noleafs_set_value, + MIB_NODE_SC, + 0 +}; +const s32_t icmp_ids[26] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26 }; +struct mib_node* const icmp_nodes[26] = { + (struct mib_node*)&icmp_scalar, (struct mib_node*)&icmp_scalar, + (struct mib_node*)&icmp_scalar, (struct mib_node*)&icmp_scalar, + (struct mib_node*)&icmp_scalar, (struct mib_node*)&icmp_scalar, + (struct mib_node*)&icmp_scalar, (struct mib_node*)&icmp_scalar, + (struct mib_node*)&icmp_scalar, (struct mib_node*)&icmp_scalar, + (struct mib_node*)&icmp_scalar, (struct mib_node*)&icmp_scalar, + (struct mib_node*)&icmp_scalar, (struct mib_node*)&icmp_scalar, + (struct mib_node*)&icmp_scalar, (struct mib_node*)&icmp_scalar, + (struct mib_node*)&icmp_scalar, (struct mib_node*)&icmp_scalar, + (struct mib_node*)&icmp_scalar, (struct mib_node*)&icmp_scalar, + (struct mib_node*)&icmp_scalar, (struct mib_node*)&icmp_scalar, + (struct mib_node*)&icmp_scalar, (struct mib_node*)&icmp_scalar, + (struct mib_node*)&icmp_scalar, (struct mib_node*)&icmp_scalar +}; +const struct mib_array_node icmp = { + &noleafs_get_object_def, + &noleafs_get_value, + &noleafs_set_test, + &noleafs_set_value, + MIB_NODE_AR, + 26, + icmp_ids, + icmp_nodes +}; + +/** index root node for ipNetToMediaTable */ +struct mib_list_rootnode ipntomtree_root = { + &noleafs_get_object_def, + &noleafs_get_value, + &noleafs_set_test, + &noleafs_set_value, + MIB_NODE_LR, + 0, + NULL, + NULL, + 0 +}; +const s32_t ipntomentry_ids[4] = { 1, 2, 3, 4 }; +struct mib_node* const ipntomentry_nodes[4] = { + (struct mib_node*)&ipntomtree_root, (struct mib_node*)&ipntomtree_root, + (struct mib_node*)&ipntomtree_root, (struct mib_node*)&ipntomtree_root +}; +const struct mib_array_node ipntomentry = { + &noleafs_get_object_def, + &noleafs_get_value, + &noleafs_set_test, + &noleafs_set_value, + MIB_NODE_AR, + 4, + ipntomentry_ids, + ipntomentry_nodes +}; + +s32_t ipntomtable_id = 1; +struct mib_node* ipntomtable_node = (struct mib_node*)&ipntomentry; +struct mib_ram_array_node ipntomtable = { + &noleafs_get_object_def, + &noleafs_get_value, + &noleafs_set_test, + &noleafs_set_value, + MIB_NODE_RA, + 0, + &ipntomtable_id, + &ipntomtable_node +}; + +/** index root node for ipRouteTable */ +struct mib_list_rootnode iprtetree_root = { + &noleafs_get_object_def, + &noleafs_get_value, + &noleafs_set_test, + &noleafs_set_value, + MIB_NODE_LR, + 0, + NULL, + NULL, + 0 +}; +const s32_t iprteentry_ids[13] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 }; +struct mib_node* const iprteentry_nodes[13] = { + (struct mib_node*)&iprtetree_root, (struct mib_node*)&iprtetree_root, + (struct mib_node*)&iprtetree_root, (struct mib_node*)&iprtetree_root, + (struct mib_node*)&iprtetree_root, (struct mib_node*)&iprtetree_root, + (struct mib_node*)&iprtetree_root, (struct mib_node*)&iprtetree_root, + (struct mib_node*)&iprtetree_root, (struct mib_node*)&iprtetree_root, + (struct mib_node*)&iprtetree_root, (struct mib_node*)&iprtetree_root, + (struct mib_node*)&iprtetree_root +}; +const struct mib_array_node iprteentry = { + &noleafs_get_object_def, + &noleafs_get_value, + &noleafs_set_test, + &noleafs_set_value, + MIB_NODE_AR, + 13, + iprteentry_ids, + iprteentry_nodes +}; + +s32_t iprtetable_id = 1; +struct mib_node* iprtetable_node = (struct mib_node*)&iprteentry; +struct mib_ram_array_node iprtetable = { + &noleafs_get_object_def, + &noleafs_get_value, + &noleafs_set_test, + &noleafs_set_value, + MIB_NODE_RA, + 0, + &iprtetable_id, + &iprtetable_node +}; + +/** index root node for ipAddrTable */ +struct mib_list_rootnode ipaddrtree_root = { + &noleafs_get_object_def, + &noleafs_get_value, + &noleafs_set_test, + &noleafs_set_value, + MIB_NODE_LR, + 0, + NULL, + NULL, + 0 +}; +const s32_t ipaddrentry_ids[5] = { 1, 2, 3, 4, 5 }; +struct mib_node* const ipaddrentry_nodes[5] = { + (struct mib_node*)&ipaddrtree_root, + (struct mib_node*)&ipaddrtree_root, + (struct mib_node*)&ipaddrtree_root, + (struct mib_node*)&ipaddrtree_root, + (struct mib_node*)&ipaddrtree_root +}; +const struct mib_array_node ipaddrentry = { + &noleafs_get_object_def, + &noleafs_get_value, + &noleafs_set_test, + &noleafs_set_value, + MIB_NODE_AR, + 5, + ipaddrentry_ids, + ipaddrentry_nodes +}; + +s32_t ipaddrtable_id = 1; +struct mib_node* ipaddrtable_node = (struct mib_node*)&ipaddrentry; +struct mib_ram_array_node ipaddrtable = { + &noleafs_get_object_def, + &noleafs_get_value, + &noleafs_set_test, + &noleafs_set_value, + MIB_NODE_RA, + 0, + &ipaddrtable_id, + &ipaddrtable_node +}; + +/* ip .1.3.6.1.2.1.4 */ +const mib_scalar_node ip_scalar = { + &ip_get_object_def, + &ip_get_value, + &ip_set_test, + &noleafs_set_value, + MIB_NODE_SC, + 0 +}; +const s32_t ip_ids[23] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 }; +struct mib_node* const ip_nodes[23] = { + (struct mib_node*)&ip_scalar, (struct mib_node*)&ip_scalar, + (struct mib_node*)&ip_scalar, (struct mib_node*)&ip_scalar, + (struct mib_node*)&ip_scalar, (struct mib_node*)&ip_scalar, + (struct mib_node*)&ip_scalar, (struct mib_node*)&ip_scalar, + (struct mib_node*)&ip_scalar, (struct mib_node*)&ip_scalar, + (struct mib_node*)&ip_scalar, (struct mib_node*)&ip_scalar, + (struct mib_node*)&ip_scalar, (struct mib_node*)&ip_scalar, + (struct mib_node*)&ip_scalar, (struct mib_node*)&ip_scalar, + (struct mib_node*)&ip_scalar, (struct mib_node*)&ip_scalar, + (struct mib_node*)&ip_scalar, (struct mib_node*)&ipaddrtable, + (struct mib_node*)&iprtetable, (struct mib_node*)&ipntomtable, + (struct mib_node*)&ip_scalar +}; +const struct mib_array_node mib2_ip = { + &noleafs_get_object_def, + &noleafs_get_value, + &noleafs_set_test, + &noleafs_set_value, + MIB_NODE_AR, + 23, + ip_ids, + ip_nodes +}; + +/** index root node for atTable */ +struct mib_list_rootnode arptree_root = { + &noleafs_get_object_def, + &noleafs_get_value, + &noleafs_set_test, + &noleafs_set_value, + MIB_NODE_LR, + 0, + NULL, + NULL, + 0 +}; +const s32_t atentry_ids[3] = { 1, 2, 3 }; +struct mib_node* const atentry_nodes[3] = { + (struct mib_node*)&arptree_root, + (struct mib_node*)&arptree_root, + (struct mib_node*)&arptree_root +}; +const struct mib_array_node atentry = { + &noleafs_get_object_def, + &noleafs_get_value, + &noleafs_set_test, + &noleafs_set_value, + MIB_NODE_AR, + 3, + atentry_ids, + atentry_nodes +}; + +const s32_t attable_id = 1; +struct mib_node* const attable_node = (struct mib_node*)&atentry; +const struct mib_array_node attable = { + &noleafs_get_object_def, + &noleafs_get_value, + &noleafs_set_test, + &noleafs_set_value, + MIB_NODE_AR, + 1, + &attable_id, + &attable_node +}; + +/* at .1.3.6.1.2.1.3 */ +s32_t at_id = 1; +struct mib_node* mib2_at_node = (struct mib_node*)&attable; +struct mib_ram_array_node at = { + &noleafs_get_object_def, + &noleafs_get_value, + &noleafs_set_test, + &noleafs_set_value, + MIB_NODE_RA, + 0, + &at_id, + &mib2_at_node +}; + +/** index root node for ifTable */ +struct mib_list_rootnode iflist_root = { + &ifentry_get_object_def, + &ifentry_get_value, +#if SNMP_SAFE_REQUESTS + &noleafs_set_test, + &noleafs_set_value, +#else /* SNMP_SAFE_REQUESTS */ + &ifentry_set_test, + &ifentry_set_value, +#endif /* SNMP_SAFE_REQUESTS */ + MIB_NODE_LR, + 0, + NULL, + NULL, + 0 +}; +const s32_t ifentry_ids[22] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22 }; +struct mib_node* const ifentry_nodes[22] = { + (struct mib_node*)&iflist_root, (struct mib_node*)&iflist_root, + (struct mib_node*)&iflist_root, (struct mib_node*)&iflist_root, + (struct mib_node*)&iflist_root, (struct mib_node*)&iflist_root, + (struct mib_node*)&iflist_root, (struct mib_node*)&iflist_root, + (struct mib_node*)&iflist_root, (struct mib_node*)&iflist_root, + (struct mib_node*)&iflist_root, (struct mib_node*)&iflist_root, + (struct mib_node*)&iflist_root, (struct mib_node*)&iflist_root, + (struct mib_node*)&iflist_root, (struct mib_node*)&iflist_root, + (struct mib_node*)&iflist_root, (struct mib_node*)&iflist_root, + (struct mib_node*)&iflist_root, (struct mib_node*)&iflist_root, + (struct mib_node*)&iflist_root, (struct mib_node*)&iflist_root +}; +const struct mib_array_node ifentry = { + &noleafs_get_object_def, + &noleafs_get_value, + &noleafs_set_test, + &noleafs_set_value, + MIB_NODE_AR, + 22, + ifentry_ids, + ifentry_nodes +}; + +s32_t iftable_id = 1; +struct mib_node* iftable_node = (struct mib_node*)&ifentry; +struct mib_ram_array_node iftable = { + &noleafs_get_object_def, + &noleafs_get_value, + &noleafs_set_test, + &noleafs_set_value, + MIB_NODE_RA, + 0, + &iftable_id, + &iftable_node +}; + +/* interfaces .1.3.6.1.2.1.2 */ +const mib_scalar_node interfaces_scalar = { + &interfaces_get_object_def, + &interfaces_get_value, + &noleafs_set_test, + &noleafs_set_value, + MIB_NODE_SC, + 0 +}; +const s32_t interfaces_ids[2] = { 1, 2 }; +struct mib_node* const interfaces_nodes[2] = { + (struct mib_node*)&interfaces_scalar, (struct mib_node*)&iftable +}; +const struct mib_array_node interfaces = { + &noleafs_get_object_def, + &noleafs_get_value, + &noleafs_set_test, + &noleafs_set_value, + MIB_NODE_AR, + 2, + interfaces_ids, + interfaces_nodes +}; + + +/* 0 1 2 3 4 5 6 */ +/* system .1.3.6.1.2.1.1 */ +const mib_scalar_node sys_tem_scalar = { + &system_get_object_def, + &system_get_value, + &system_set_test, + &system_set_value, + MIB_NODE_SC, + 0 +}; +const s32_t sys_tem_ids[7] = { 1, 2, 3, 4, 5, 6, 7 }; +struct mib_node* const sys_tem_nodes[7] = { + (struct mib_node*)&sys_tem_scalar, (struct mib_node*)&sys_tem_scalar, + (struct mib_node*)&sys_tem_scalar, (struct mib_node*)&sys_tem_scalar, + (struct mib_node*)&sys_tem_scalar, (struct mib_node*)&sys_tem_scalar, + (struct mib_node*)&sys_tem_scalar +}; +/* work around name issue with 'sys_tem', some compiler(s?) seem to reserve 'system' */ +const struct mib_array_node sys_tem = { + &noleafs_get_object_def, + &noleafs_get_value, + &noleafs_set_test, + &noleafs_set_value, + MIB_NODE_AR, + 7, + sys_tem_ids, + sys_tem_nodes +}; + +/* mib-2 .1.3.6.1.2.1 */ +#if LWIP_TCP +#define MIB2_GROUPS 8 +#else +#define MIB2_GROUPS 7 +#endif +const s32_t mib2_ids[MIB2_GROUPS] = +{ + 1, + 2, + 3, + 4, + 5, +#if LWIP_TCP + 6, +#endif + 7, + 11 +}; +struct mib_node* const mib2_nodes[MIB2_GROUPS] = { + (struct mib_node*)&sys_tem, + (struct mib_node*)&interfaces, + (struct mib_node*)&at, + (struct mib_node*)&mib2_ip, + (struct mib_node*)&icmp, +#if LWIP_TCP + (struct mib_node*)&tcp, +#endif + (struct mib_node*)&udp, + (struct mib_node*)&snmp +}; + +const struct mib_array_node mib2 = { + &noleafs_get_object_def, + &noleafs_get_value, + &noleafs_set_test, + &noleafs_set_value, + MIB_NODE_AR, + MIB2_GROUPS, + mib2_ids, + mib2_nodes +}; + +/* mgmt .1.3.6.1.2 */ +const s32_t mgmt_ids[1] = { 1 }; +struct mib_node* const mgmt_nodes[1] = { (struct mib_node*)&mib2 }; +const struct mib_array_node mgmt = { + &noleafs_get_object_def, + &noleafs_get_value, + &noleafs_set_test, + &noleafs_set_value, + MIB_NODE_AR, + 1, + mgmt_ids, + mgmt_nodes +}; + +/* internet .1.3.6.1 */ +#if SNMP_PRIVATE_MIB +/* When using a private MIB, you have to create a file 'private_mib.h' that contains + * a 'struct mib_array_node mib_private' which contains your MIB. */ +s32_t internet_ids[2] = { 2, 4 }; +struct mib_node* const internet_nodes[2] = { (struct mib_node*)&mgmt, (struct mib_node*)&mib_private }; +const struct mib_array_node internet = { + &noleafs_get_object_def, + &noleafs_get_value, + &noleafs_set_test, + &noleafs_set_value, + MIB_NODE_AR, + 2, + internet_ids, + internet_nodes +}; +#else +const s32_t internet_ids[1] = { 2 }; +struct mib_node* const internet_nodes[1] = { (struct mib_node*)&mgmt }; +const struct mib_array_node internet = { + &noleafs_get_object_def, + &noleafs_get_value, + &noleafs_set_test, + &noleafs_set_value, + MIB_NODE_AR, + 1, + internet_ids, + internet_nodes +}; +#endif + +/** mib-2.system.sysObjectID */ +static struct snmp_obj_id sysobjid = {SNMP_SYSOBJID_LEN, SNMP_SYSOBJID}; +/** enterprise ID for generic TRAPs, .iso.org.dod.internet.mgmt.mib-2.snmp */ +static struct snmp_obj_id snmpgrp_id = {7,{1,3,6,1,2,1,11}}; +/** mib-2.system.sysServices */ +static const s32_t sysservices = SNMP_SYSSERVICES; + +/** mib-2.system.sysDescr */ +static const u8_t sysdescr_len_default = 4; +static const u8_t sysdescr_default[] = "lwIP"; +static u8_t* sysdescr_len_ptr = (u8_t*)&sysdescr_len_default; +static u8_t* sysdescr_ptr = (u8_t*)&sysdescr_default[0]; +/** mib-2.system.sysContact */ +static const u8_t syscontact_len_default = 0; +static const u8_t syscontact_default[] = ""; +static u8_t* syscontact_len_ptr = (u8_t*)&syscontact_len_default; +static u8_t* syscontact_ptr = (u8_t*)&syscontact_default[0]; +/** mib-2.system.sysName */ +static const u8_t sysname_len_default = 8; +static const u8_t sysname_default[] = "FQDN-unk"; +static u8_t* sysname_len_ptr = (u8_t*)&sysname_len_default; +static u8_t* sysname_ptr = (u8_t*)&sysname_default[0]; +/** mib-2.system.sysLocation */ +static const u8_t syslocation_len_default = 0; +static const u8_t syslocation_default[] = ""; +static u8_t* syslocation_len_ptr = (u8_t*)&syslocation_len_default; +static u8_t* syslocation_ptr = (u8_t*)&syslocation_default[0]; +/** mib-2.snmp.snmpEnableAuthenTraps */ +static const u8_t snmpenableauthentraps_default = 2; /* disabled */ +static u8_t* snmpenableauthentraps_ptr = (u8_t*)&snmpenableauthentraps_default; + +/** mib-2.interfaces.ifTable.ifEntry.ifSpecific (zeroDotZero) */ +static const struct snmp_obj_id ifspecific = {2, {0, 0}}; +/** mib-2.ip.ipRouteTable.ipRouteEntry.ipRouteInfo (zeroDotZero) */ +static const struct snmp_obj_id iprouteinfo = {2, {0, 0}}; + + + +/* mib-2.system counter(s) */ +static u32_t sysuptime = 0; + +/* mib-2.ip counter(s) */ +static u32_t ipinreceives = 0, + ipinhdrerrors = 0, + ipinaddrerrors = 0, + ipforwdatagrams = 0, + ipinunknownprotos = 0, + ipindiscards = 0, + ipindelivers = 0, + ipoutrequests = 0, + ipoutdiscards = 0, + ipoutnoroutes = 0, + ipreasmreqds = 0, + ipreasmoks = 0, + ipreasmfails = 0, + ipfragoks = 0, + ipfragfails = 0, + ipfragcreates = 0, + iproutingdiscards = 0; +/* mib-2.icmp counter(s) */ +static u32_t icmpinmsgs = 0, + icmpinerrors = 0, + icmpindestunreachs = 0, + icmpintimeexcds = 0, + icmpinparmprobs = 0, + icmpinsrcquenchs = 0, + icmpinredirects = 0, + icmpinechos = 0, + icmpinechoreps = 0, + icmpintimestamps = 0, + icmpintimestampreps = 0, + icmpinaddrmasks = 0, + icmpinaddrmaskreps = 0, + icmpoutmsgs = 0, + icmpouterrors = 0, + icmpoutdestunreachs = 0, + icmpouttimeexcds = 0, + icmpoutparmprobs = 0, + icmpoutsrcquenchs = 0, + icmpoutredirects = 0, + icmpoutechos = 0, + icmpoutechoreps = 0, + icmpouttimestamps = 0, + icmpouttimestampreps = 0, + icmpoutaddrmasks = 0, + icmpoutaddrmaskreps = 0; +/* mib-2.tcp counter(s) */ +static u32_t tcpactiveopens = 0, + tcppassiveopens = 0, + tcpattemptfails = 0, + tcpestabresets = 0, + tcpinsegs = 0, + tcpoutsegs = 0, + tcpretranssegs = 0, + tcpinerrs = 0, + tcpoutrsts = 0; +/* mib-2.udp counter(s) */ +static u32_t udpindatagrams = 0, + udpnoports = 0, + udpinerrors = 0, + udpoutdatagrams = 0; +/* mib-2.snmp counter(s) */ +static u32_t snmpinpkts = 0, + snmpoutpkts = 0, + snmpinbadversions = 0, + snmpinbadcommunitynames = 0, + snmpinbadcommunityuses = 0, + snmpinasnparseerrs = 0, + snmpintoobigs = 0, + snmpinnosuchnames = 0, + snmpinbadvalues = 0, + snmpinreadonlys = 0, + snmpingenerrs = 0, + snmpintotalreqvars = 0, + snmpintotalsetvars = 0, + snmpingetrequests = 0, + snmpingetnexts = 0, + snmpinsetrequests = 0, + snmpingetresponses = 0, + snmpintraps = 0, + snmpouttoobigs = 0, + snmpoutnosuchnames = 0, + snmpoutbadvalues = 0, + snmpoutgenerrs = 0, + snmpoutgetrequests = 0, + snmpoutgetnexts = 0, + snmpoutsetrequests = 0, + snmpoutgetresponses = 0, + snmpouttraps = 0; + + + +/* prototypes of the following functions are in lwip/src/include/lwip/snmp.h */ +/** + * Copy octet string. + * + * @param dst points to destination + * @param src points to source + * @param n number of octets to copy. + */ +static void ocstrncpy(u8_t *dst, u8_t *src, u16_t n) +{ + u16_t i = n; + while (i > 0) { + i--; + *dst++ = *src++; + } +} + +/** + * Copy object identifier (s32_t) array. + * + * @param dst points to destination + * @param src points to source + * @param n number of sub identifiers to copy. + */ +void objectidncpy(s32_t *dst, s32_t *src, u8_t n) +{ + u8_t i = n; + while(i > 0) { + i--; + *dst++ = *src++; + } +} + +/** + * Initializes sysDescr pointers. + * + * @param str if non-NULL then copy str pointer + * @param len points to string length, excluding zero terminator + */ +void snmp_set_sysdesr(u8_t *str, u8_t *len) +{ + if (str != NULL) + { + sysdescr_ptr = str; + sysdescr_len_ptr = len; + } +} + +void snmp_get_sysobjid_ptr(struct snmp_obj_id **oid) +{ + *oid = &sysobjid; +} + +/** + * Initializes sysObjectID value. + * + * @param oid points to stuct snmp_obj_id to copy + */ +void snmp_set_sysobjid(struct snmp_obj_id *oid) +{ + sysobjid = *oid; +} + +/** + * Must be called at regular 10 msec interval from a timer interrupt + * or signal handler depending on your runtime environment. + */ +void snmp_inc_sysuptime(void) +{ + sysuptime++; +} + +void snmp_add_sysuptime(u32_t value) +{ + sysuptime+=value; +} + +void snmp_get_sysuptime(u32_t *value) +{ + SNMP_GET_SYSUPTIME(sysuptime); + *value = sysuptime; +} + +/** + * Initializes sysContact pointers, + * e.g. ptrs to non-volatile memory external to lwIP. + * + * @param ocstr if non-NULL then copy str pointer + * @param ocstrlen points to string length, excluding zero terminator + */ +void snmp_set_syscontact(u8_t *ocstr, u8_t *ocstrlen) +{ + if (ocstr != NULL) + { + syscontact_ptr = ocstr; + syscontact_len_ptr = ocstrlen; + } +} + +/** + * Initializes sysName pointers, + * e.g. ptrs to non-volatile memory external to lwIP. + * + * @param ocstr if non-NULL then copy str pointer + * @param ocstrlen points to string length, excluding zero terminator + */ +void snmp_set_sysname(u8_t *ocstr, u8_t *ocstrlen) +{ + if (ocstr != NULL) + { + sysname_ptr = ocstr; + sysname_len_ptr = ocstrlen; + } +} + +/** + * Initializes sysLocation pointers, + * e.g. ptrs to non-volatile memory external to lwIP. + * + * @param ocstr if non-NULL then copy str pointer + * @param ocstrlen points to string length, excluding zero terminator + */ +void snmp_set_syslocation(u8_t *ocstr, u8_t *ocstrlen) +{ + if (ocstr != NULL) + { + syslocation_ptr = ocstr; + syslocation_len_ptr = ocstrlen; + } +} + + +void snmp_add_ifinoctets(struct netif *ni, u32_t value) +{ + ni->ifinoctets += value; +} + +void snmp_inc_ifinucastpkts(struct netif *ni) +{ + (ni->ifinucastpkts)++; +} + +void snmp_inc_ifinnucastpkts(struct netif *ni) +{ + (ni->ifinnucastpkts)++; +} + +void snmp_inc_ifindiscards(struct netif *ni) +{ + (ni->ifindiscards)++; +} + +void snmp_add_ifoutoctets(struct netif *ni, u32_t value) +{ + ni->ifoutoctets += value; +} + +void snmp_inc_ifoutucastpkts(struct netif *ni) +{ + (ni->ifoutucastpkts)++; +} + +void snmp_inc_ifoutnucastpkts(struct netif *ni) +{ + (ni->ifoutnucastpkts)++; +} + +void snmp_inc_ifoutdiscards(struct netif *ni) +{ + (ni->ifoutdiscards)++; +} + +void snmp_inc_iflist(void) +{ + struct mib_list_node *if_node = NULL; + + snmp_mib_node_insert(&iflist_root, iflist_root.count + 1, &if_node); + /* enable getnext traversal on filled table */ + iftable.maxlength = 1; +} + +void snmp_dec_iflist(void) +{ + snmp_mib_node_delete(&iflist_root, iflist_root.tail); + /* disable getnext traversal on empty table */ + if(iflist_root.count == 0) iftable.maxlength = 0; +} + +/** + * Inserts ARP table indexes (.xIfIndex.xNetAddress) + * into arp table index trees (both atTable and ipNetToMediaTable). + */ +void snmp_insert_arpidx_tree(struct netif *ni, ip_addr_t *ip) +{ + struct mib_list_rootnode *at_rn; + struct mib_list_node *at_node; + s32_t arpidx[5]; + u8_t level, tree; + + LWIP_ASSERT("ni != NULL", ni != NULL); + snmp_netiftoifindex(ni, &arpidx[0]); + snmp_iptooid(ip, &arpidx[1]); + + for (tree = 0; tree < 2; tree++) + { + if (tree == 0) + { + at_rn = &arptree_root; + } + else + { + at_rn = &ipntomtree_root; + } + for (level = 0; level < 5; level++) + { + at_node = NULL; + snmp_mib_node_insert(at_rn, arpidx[level], &at_node); + if ((level != 4) && (at_node != NULL)) + { + if (at_node->nptr == NULL) + { + at_rn = snmp_mib_lrn_alloc(); + at_node->nptr = (struct mib_node*)at_rn; + if (at_rn != NULL) + { + if (level == 3) + { + if (tree == 0) + { + at_rn->get_object_def = atentry_get_object_def; + at_rn->get_value = atentry_get_value; + } + else + { + at_rn->get_object_def = ip_ntomentry_get_object_def; + at_rn->get_value = ip_ntomentry_get_value; + } + at_rn->set_test = noleafs_set_test; + at_rn->set_value = noleafs_set_value; + } + } + else + { + /* at_rn == NULL, malloc failure */ + LWIP_DEBUGF(SNMP_MIB_DEBUG,("snmp_insert_arpidx_tree() insert failed, mem full")); + break; + } + } + else + { + at_rn = (struct mib_list_rootnode*)at_node->nptr; + } + } + } + } + /* enable getnext traversal on filled tables */ + at.maxlength = 1; + ipntomtable.maxlength = 1; +} + +/** + * Removes ARP table indexes (.xIfIndex.xNetAddress) + * from arp table index trees. + */ +void snmp_delete_arpidx_tree(struct netif *ni, ip_addr_t *ip) +{ + struct mib_list_rootnode *at_rn, *next, *del_rn[5]; + struct mib_list_node *at_n, *del_n[5]; + s32_t arpidx[5]; + u8_t fc, tree, level, del_cnt; + + snmp_netiftoifindex(ni, &arpidx[0]); + snmp_iptooid(ip, &arpidx[1]); + + for (tree = 0; tree < 2; tree++) + { + /* mark nodes for deletion */ + if (tree == 0) + { + at_rn = &arptree_root; + } + else + { + at_rn = &ipntomtree_root; + } + level = 0; + del_cnt = 0; + while ((level < 5) && (at_rn != NULL)) + { + fc = snmp_mib_node_find(at_rn, arpidx[level], &at_n); + if (fc == 0) + { + /* arpidx[level] does not exist */ + del_cnt = 0; + at_rn = NULL; + } + else if (fc == 1) + { + del_rn[del_cnt] = at_rn; + del_n[del_cnt] = at_n; + del_cnt++; + at_rn = (struct mib_list_rootnode*)(at_n->nptr); + } + else if (fc == 2) + { + /* reset delete (2 or more childs) */ + del_cnt = 0; + at_rn = (struct mib_list_rootnode*)(at_n->nptr); + } + level++; + } + /* delete marked index nodes */ + while (del_cnt > 0) + { + del_cnt--; + + at_rn = del_rn[del_cnt]; + at_n = del_n[del_cnt]; + + next = snmp_mib_node_delete(at_rn, at_n); + if (next != NULL) + { + LWIP_ASSERT("next_count == 0",next->count == 0); + snmp_mib_lrn_free(next); + } + } + } + /* disable getnext traversal on empty tables */ + if(arptree_root.count == 0) at.maxlength = 0; + if(ipntomtree_root.count == 0) ipntomtable.maxlength = 0; +} + +void snmp_inc_ipinreceives(void) +{ + ipinreceives++; +} + +void snmp_inc_ipinhdrerrors(void) +{ + ipinhdrerrors++; +} + +void snmp_inc_ipinaddrerrors(void) +{ + ipinaddrerrors++; +} + +void snmp_inc_ipforwdatagrams(void) +{ + ipforwdatagrams++; +} + +void snmp_inc_ipinunknownprotos(void) +{ + ipinunknownprotos++; +} + +void snmp_inc_ipindiscards(void) +{ + ipindiscards++; +} + +void snmp_inc_ipindelivers(void) +{ + ipindelivers++; +} + +void snmp_inc_ipoutrequests(void) +{ + ipoutrequests++; +} + +void snmp_inc_ipoutdiscards(void) +{ + ipoutdiscards++; +} + +void snmp_inc_ipoutnoroutes(void) +{ + ipoutnoroutes++; +} + +void snmp_inc_ipreasmreqds(void) +{ + ipreasmreqds++; +} + +void snmp_inc_ipreasmoks(void) +{ + ipreasmoks++; +} + +void snmp_inc_ipreasmfails(void) +{ + ipreasmfails++; +} + +void snmp_inc_ipfragoks(void) +{ + ipfragoks++; +} + +void snmp_inc_ipfragfails(void) +{ + ipfragfails++; +} + +void snmp_inc_ipfragcreates(void) +{ + ipfragcreates++; +} + +void snmp_inc_iproutingdiscards(void) +{ + iproutingdiscards++; +} + +/** + * Inserts ipAddrTable indexes (.ipAdEntAddr) + * into index tree. + */ +void snmp_insert_ipaddridx_tree(struct netif *ni) +{ + struct mib_list_rootnode *ipa_rn; + struct mib_list_node *ipa_node; + s32_t ipaddridx[4]; + u8_t level; + + LWIP_ASSERT("ni != NULL", ni != NULL); + snmp_iptooid(&ni->ip_addr, &ipaddridx[0]); + + level = 0; + ipa_rn = &ipaddrtree_root; + while (level < 4) + { + ipa_node = NULL; + snmp_mib_node_insert(ipa_rn, ipaddridx[level], &ipa_node); + if ((level != 3) && (ipa_node != NULL)) + { + if (ipa_node->nptr == NULL) + { + ipa_rn = snmp_mib_lrn_alloc(); + ipa_node->nptr = (struct mib_node*)ipa_rn; + if (ipa_rn != NULL) + { + if (level == 2) + { + ipa_rn->get_object_def = ip_addrentry_get_object_def; + ipa_rn->get_value = ip_addrentry_get_value; + ipa_rn->set_test = noleafs_set_test; + ipa_rn->set_value = noleafs_set_value; + } + } + else + { + /* ipa_rn == NULL, malloc failure */ + LWIP_DEBUGF(SNMP_MIB_DEBUG,("snmp_insert_ipaddridx_tree() insert failed, mem full")); + break; + } + } + else + { + ipa_rn = (struct mib_list_rootnode*)ipa_node->nptr; + } + } + level++; + } + /* enable getnext traversal on filled table */ + ipaddrtable.maxlength = 1; +} + +/** + * Removes ipAddrTable indexes (.ipAdEntAddr) + * from index tree. + */ +void snmp_delete_ipaddridx_tree(struct netif *ni) +{ + struct mib_list_rootnode *ipa_rn, *next, *del_rn[4]; + struct mib_list_node *ipa_n, *del_n[4]; + s32_t ipaddridx[4]; + u8_t fc, level, del_cnt; + + LWIP_ASSERT("ni != NULL", ni != NULL); + snmp_iptooid(&ni->ip_addr, &ipaddridx[0]); + + /* mark nodes for deletion */ + level = 0; + del_cnt = 0; + ipa_rn = &ipaddrtree_root; + while ((level < 4) && (ipa_rn != NULL)) + { + fc = snmp_mib_node_find(ipa_rn, ipaddridx[level], &ipa_n); + if (fc == 0) + { + /* ipaddridx[level] does not exist */ + del_cnt = 0; + ipa_rn = NULL; + } + else if (fc == 1) + { + del_rn[del_cnt] = ipa_rn; + del_n[del_cnt] = ipa_n; + del_cnt++; + ipa_rn = (struct mib_list_rootnode*)(ipa_n->nptr); + } + else if (fc == 2) + { + /* reset delete (2 or more childs) */ + del_cnt = 0; + ipa_rn = (struct mib_list_rootnode*)(ipa_n->nptr); + } + level++; + } + /* delete marked index nodes */ + while (del_cnt > 0) + { + del_cnt--; + + ipa_rn = del_rn[del_cnt]; + ipa_n = del_n[del_cnt]; + + next = snmp_mib_node_delete(ipa_rn, ipa_n); + if (next != NULL) + { + LWIP_ASSERT("next_count == 0",next->count == 0); + snmp_mib_lrn_free(next); + } + } + /* disable getnext traversal on empty table */ + if (ipaddrtree_root.count == 0) ipaddrtable.maxlength = 0; +} + +/** + * Inserts ipRouteTable indexes (.ipRouteDest) + * into index tree. + * + * @param dflt non-zero for the default rte, zero for network rte + * @param ni points to network interface for this rte + * + * @todo record sysuptime for _this_ route when it is installed + * (needed for ipRouteAge) in the netif. + */ +void snmp_insert_iprteidx_tree(u8_t dflt, struct netif *ni) +{ + u8_t insert = 0; + ip_addr_t dst; + + if (dflt != 0) + { + /* the default route 0.0.0.0 */ + ip_addr_set_any(&dst); + insert = 1; + } + else + { + /* route to the network address */ + ip_addr_get_network(&dst, &ni->ip_addr, &ni->netmask); + /* exclude 0.0.0.0 network (reserved for default rte) */ + if (!ip_addr_isany(&dst)) { + insert = 1; + } + } + if (insert) + { + struct mib_list_rootnode *iprte_rn; + struct mib_list_node *iprte_node; + s32_t iprteidx[4]; + u8_t level; + + snmp_iptooid(&dst, &iprteidx[0]); + level = 0; + iprte_rn = &iprtetree_root; + while (level < 4) + { + iprte_node = NULL; + snmp_mib_node_insert(iprte_rn, iprteidx[level], &iprte_node); + if ((level != 3) && (iprte_node != NULL)) + { + if (iprte_node->nptr == NULL) + { + iprte_rn = snmp_mib_lrn_alloc(); + iprte_node->nptr = (struct mib_node*)iprte_rn; + if (iprte_rn != NULL) + { + if (level == 2) + { + iprte_rn->get_object_def = ip_rteentry_get_object_def; + iprte_rn->get_value = ip_rteentry_get_value; + iprte_rn->set_test = noleafs_set_test; + iprte_rn->set_value = noleafs_set_value; + } + } + else + { + /* iprte_rn == NULL, malloc failure */ + LWIP_DEBUGF(SNMP_MIB_DEBUG,("snmp_insert_iprteidx_tree() insert failed, mem full")); + break; + } + } + else + { + iprte_rn = (struct mib_list_rootnode*)iprte_node->nptr; + } + } + level++; + } + } + /* enable getnext traversal on filled table */ + iprtetable.maxlength = 1; +} + +/** + * Removes ipRouteTable indexes (.ipRouteDest) + * from index tree. + * + * @param dflt non-zero for the default rte, zero for network rte + * @param ni points to network interface for this rte or NULL + * for default route to be removed. + */ +void snmp_delete_iprteidx_tree(u8_t dflt, struct netif *ni) +{ + u8_t del = 0; + ip_addr_t dst; + + if (dflt != 0) + { + /* the default route 0.0.0.0 */ + ip_addr_set_any(&dst); + del = 1; + } + else + { + /* route to the network address */ + ip_addr_get_network(&dst, &ni->ip_addr, &ni->netmask); + /* exclude 0.0.0.0 network (reserved for default rte) */ + if (!ip_addr_isany(&dst)) { + del = 1; + } + } + if (del) + { + struct mib_list_rootnode *iprte_rn, *next, *del_rn[4]; + struct mib_list_node *iprte_n, *del_n[4]; + s32_t iprteidx[4]; + u8_t fc, level, del_cnt; + + snmp_iptooid(&dst, &iprteidx[0]); + /* mark nodes for deletion */ + level = 0; + del_cnt = 0; + iprte_rn = &iprtetree_root; + while ((level < 4) && (iprte_rn != NULL)) + { + fc = snmp_mib_node_find(iprte_rn, iprteidx[level], &iprte_n); + if (fc == 0) + { + /* iprteidx[level] does not exist */ + del_cnt = 0; + iprte_rn = NULL; + } + else if (fc == 1) + { + del_rn[del_cnt] = iprte_rn; + del_n[del_cnt] = iprte_n; + del_cnt++; + iprte_rn = (struct mib_list_rootnode*)(iprte_n->nptr); + } + else if (fc == 2) + { + /* reset delete (2 or more childs) */ + del_cnt = 0; + iprte_rn = (struct mib_list_rootnode*)(iprte_n->nptr); + } + level++; + } + /* delete marked index nodes */ + while (del_cnt > 0) + { + del_cnt--; + + iprte_rn = del_rn[del_cnt]; + iprte_n = del_n[del_cnt]; + + next = snmp_mib_node_delete(iprte_rn, iprte_n); + if (next != NULL) + { + LWIP_ASSERT("next_count == 0",next->count == 0); + snmp_mib_lrn_free(next); + } + } + } + /* disable getnext traversal on empty table */ + if (iprtetree_root.count == 0) iprtetable.maxlength = 0; +} + + +void snmp_inc_icmpinmsgs(void) +{ + icmpinmsgs++; +} + +void snmp_inc_icmpinerrors(void) +{ + icmpinerrors++; +} + +void snmp_inc_icmpindestunreachs(void) +{ + icmpindestunreachs++; +} + +void snmp_inc_icmpintimeexcds(void) +{ + icmpintimeexcds++; +} + +void snmp_inc_icmpinparmprobs(void) +{ + icmpinparmprobs++; +} + +void snmp_inc_icmpinsrcquenchs(void) +{ + icmpinsrcquenchs++; +} + +void snmp_inc_icmpinredirects(void) +{ + icmpinredirects++; +} + +void snmp_inc_icmpinechos(void) +{ + icmpinechos++; +} + +void snmp_inc_icmpinechoreps(void) +{ + icmpinechoreps++; +} + +void snmp_inc_icmpintimestamps(void) +{ + icmpintimestamps++; +} + +void snmp_inc_icmpintimestampreps(void) +{ + icmpintimestampreps++; +} + +void snmp_inc_icmpinaddrmasks(void) +{ + icmpinaddrmasks++; +} + +void snmp_inc_icmpinaddrmaskreps(void) +{ + icmpinaddrmaskreps++; +} + +void snmp_inc_icmpoutmsgs(void) +{ + icmpoutmsgs++; +} + +void snmp_inc_icmpouterrors(void) +{ + icmpouterrors++; +} + +void snmp_inc_icmpoutdestunreachs(void) +{ + icmpoutdestunreachs++; +} + +void snmp_inc_icmpouttimeexcds(void) +{ + icmpouttimeexcds++; +} + +void snmp_inc_icmpoutparmprobs(void) +{ + icmpoutparmprobs++; +} + +void snmp_inc_icmpoutsrcquenchs(void) +{ + icmpoutsrcquenchs++; +} + +void snmp_inc_icmpoutredirects(void) +{ + icmpoutredirects++; +} + +void snmp_inc_icmpoutechos(void) +{ + icmpoutechos++; +} + +void snmp_inc_icmpoutechoreps(void) +{ + icmpoutechoreps++; +} + +void snmp_inc_icmpouttimestamps(void) +{ + icmpouttimestamps++; +} + +void snmp_inc_icmpouttimestampreps(void) +{ + icmpouttimestampreps++; +} + +void snmp_inc_icmpoutaddrmasks(void) +{ + icmpoutaddrmasks++; +} + +void snmp_inc_icmpoutaddrmaskreps(void) +{ + icmpoutaddrmaskreps++; +} + +void snmp_inc_tcpactiveopens(void) +{ + tcpactiveopens++; +} + +void snmp_inc_tcppassiveopens(void) +{ + tcppassiveopens++; +} + +void snmp_inc_tcpattemptfails(void) +{ + tcpattemptfails++; +} + +void snmp_inc_tcpestabresets(void) +{ + tcpestabresets++; +} + +void snmp_inc_tcpinsegs(void) +{ + tcpinsegs++; +} + +void snmp_inc_tcpoutsegs(void) +{ + tcpoutsegs++; +} + +void snmp_inc_tcpretranssegs(void) +{ + tcpretranssegs++; +} + +void snmp_inc_tcpinerrs(void) +{ + tcpinerrs++; +} + +void snmp_inc_tcpoutrsts(void) +{ + tcpoutrsts++; +} + +void snmp_inc_udpindatagrams(void) +{ + udpindatagrams++; +} + +void snmp_inc_udpnoports(void) +{ + udpnoports++; +} + +void snmp_inc_udpinerrors(void) +{ + udpinerrors++; +} + +void snmp_inc_udpoutdatagrams(void) +{ + udpoutdatagrams++; +} + +/** + * Inserts udpTable indexes (.udpLocalAddress.udpLocalPort) + * into index tree. + */ +void snmp_insert_udpidx_tree(struct udp_pcb *pcb) +{ + struct mib_list_rootnode *udp_rn; + struct mib_list_node *udp_node; + s32_t udpidx[5]; + u8_t level; + + LWIP_ASSERT("pcb != NULL", pcb != NULL); + snmp_iptooid(&pcb->local_ip, &udpidx[0]); + udpidx[4] = pcb->local_port; + + udp_rn = &udp_root; + for (level = 0; level < 5; level++) + { + udp_node = NULL; + snmp_mib_node_insert(udp_rn, udpidx[level], &udp_node); + if ((level != 4) && (udp_node != NULL)) + { + if (udp_node->nptr == NULL) + { + udp_rn = snmp_mib_lrn_alloc(); + udp_node->nptr = (struct mib_node*)udp_rn; + if (udp_rn != NULL) + { + if (level == 3) + { + udp_rn->get_object_def = udpentry_get_object_def; + udp_rn->get_value = udpentry_get_value; + udp_rn->set_test = noleafs_set_test; + udp_rn->set_value = noleafs_set_value; + } + } + else + { + /* udp_rn == NULL, malloc failure */ + LWIP_DEBUGF(SNMP_MIB_DEBUG,("snmp_insert_udpidx_tree() insert failed, mem full")); + break; + } + } + else + { + udp_rn = (struct mib_list_rootnode*)udp_node->nptr; + } + } + } + udptable.maxlength = 1; +} + +/** + * Removes udpTable indexes (.udpLocalAddress.udpLocalPort) + * from index tree. + */ +void snmp_delete_udpidx_tree(struct udp_pcb *pcb) +{ + struct udp_pcb *npcb; + struct mib_list_rootnode *udp_rn, *next, *del_rn[5]; + struct mib_list_node *udp_n, *del_n[5]; + s32_t udpidx[5]; + u8_t bindings, fc, level, del_cnt; + + LWIP_ASSERT("pcb != NULL", pcb != NULL); + snmp_iptooid(&pcb->local_ip, &udpidx[0]); + udpidx[4] = pcb->local_port; + + /* count PCBs for a given binding + (e.g. when reusing ports or for temp output PCBs) */ + bindings = 0; + npcb = udp_pcbs; + while ((npcb != NULL)) + { + if (ip_addr_cmp(&npcb->local_ip, &pcb->local_ip) && + (npcb->local_port == udpidx[4])) + { + bindings++; + } + npcb = npcb->next; + } + if (bindings == 1) + { + /* selectively remove */ + /* mark nodes for deletion */ + level = 0; + del_cnt = 0; + udp_rn = &udp_root; + while ((level < 5) && (udp_rn != NULL)) + { + fc = snmp_mib_node_find(udp_rn, udpidx[level], &udp_n); + if (fc == 0) + { + /* udpidx[level] does not exist */ + del_cnt = 0; + udp_rn = NULL; + } + else if (fc == 1) + { + del_rn[del_cnt] = udp_rn; + del_n[del_cnt] = udp_n; + del_cnt++; + udp_rn = (struct mib_list_rootnode*)(udp_n->nptr); + } + else if (fc == 2) + { + /* reset delete (2 or more childs) */ + del_cnt = 0; + udp_rn = (struct mib_list_rootnode*)(udp_n->nptr); + } + level++; + } + /* delete marked index nodes */ + while (del_cnt > 0) + { + del_cnt--; + + udp_rn = del_rn[del_cnt]; + udp_n = del_n[del_cnt]; + + next = snmp_mib_node_delete(udp_rn, udp_n); + if (next != NULL) + { + LWIP_ASSERT("next_count == 0",next->count == 0); + snmp_mib_lrn_free(next); + } + } + } + /* disable getnext traversal on empty table */ + if (udp_root.count == 0) udptable.maxlength = 0; +} + + +void snmp_inc_snmpinpkts(void) +{ + snmpinpkts++; +} + +void snmp_inc_snmpoutpkts(void) +{ + snmpoutpkts++; +} + +void snmp_inc_snmpinbadversions(void) +{ + snmpinbadversions++; +} + +void snmp_inc_snmpinbadcommunitynames(void) +{ + snmpinbadcommunitynames++; +} + +void snmp_inc_snmpinbadcommunityuses(void) +{ + snmpinbadcommunityuses++; +} + +void snmp_inc_snmpinasnparseerrs(void) +{ + snmpinasnparseerrs++; +} + +void snmp_inc_snmpintoobigs(void) +{ + snmpintoobigs++; +} + +void snmp_inc_snmpinnosuchnames(void) +{ + snmpinnosuchnames++; +} + +void snmp_inc_snmpinbadvalues(void) +{ + snmpinbadvalues++; +} + +void snmp_inc_snmpinreadonlys(void) +{ + snmpinreadonlys++; +} + +void snmp_inc_snmpingenerrs(void) +{ + snmpingenerrs++; +} + +void snmp_add_snmpintotalreqvars(u8_t value) +{ + snmpintotalreqvars += value; +} + +void snmp_add_snmpintotalsetvars(u8_t value) +{ + snmpintotalsetvars += value; +} + +void snmp_inc_snmpingetrequests(void) +{ + snmpingetrequests++; +} + +void snmp_inc_snmpingetnexts(void) +{ + snmpingetnexts++; +} + +void snmp_inc_snmpinsetrequests(void) +{ + snmpinsetrequests++; +} + +void snmp_inc_snmpingetresponses(void) +{ + snmpingetresponses++; +} + +void snmp_inc_snmpintraps(void) +{ + snmpintraps++; +} + +void snmp_inc_snmpouttoobigs(void) +{ + snmpouttoobigs++; +} + +void snmp_inc_snmpoutnosuchnames(void) +{ + snmpoutnosuchnames++; +} + +void snmp_inc_snmpoutbadvalues(void) +{ + snmpoutbadvalues++; +} + +void snmp_inc_snmpoutgenerrs(void) +{ + snmpoutgenerrs++; +} + +void snmp_inc_snmpoutgetrequests(void) +{ + snmpoutgetrequests++; +} + +void snmp_inc_snmpoutgetnexts(void) +{ + snmpoutgetnexts++; +} + +void snmp_inc_snmpoutsetrequests(void) +{ + snmpoutsetrequests++; +} + +void snmp_inc_snmpoutgetresponses(void) +{ + snmpoutgetresponses++; +} + +void snmp_inc_snmpouttraps(void) +{ + snmpouttraps++; +} + +void snmp_get_snmpgrpid_ptr(struct snmp_obj_id **oid) +{ + *oid = &snmpgrp_id; +} + +void snmp_set_snmpenableauthentraps(u8_t *value) +{ + if (value != NULL) + { + snmpenableauthentraps_ptr = value; + } +} + +void snmp_get_snmpenableauthentraps(u8_t *value) +{ + *value = *snmpenableauthentraps_ptr; +} + +void +noleafs_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od) +{ + LWIP_UNUSED_ARG(ident_len); + LWIP_UNUSED_ARG(ident); + od->instance = MIB_OBJECT_NONE; +} + +void +noleafs_get_value(struct obj_def *od, u16_t len, void *value) +{ + LWIP_UNUSED_ARG(od); + LWIP_UNUSED_ARG(len); + LWIP_UNUSED_ARG(value); +} + +u8_t +noleafs_set_test(struct obj_def *od, u16_t len, void *value) +{ + LWIP_UNUSED_ARG(od); + LWIP_UNUSED_ARG(len); + LWIP_UNUSED_ARG(value); + /* can't set */ + return 0; +} + +void +noleafs_set_value(struct obj_def *od, u16_t len, void *value) +{ + LWIP_UNUSED_ARG(od); + LWIP_UNUSED_ARG(len); + LWIP_UNUSED_ARG(value); +} + + +/** + * Returns systems object definitions. + * + * @param ident_len the address length (2) + * @param ident points to objectname.0 (object id trailer) + * @param od points to object definition. + */ +static void +system_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od) +{ + u8_t id; + + /* return to object name, adding index depth (1) */ + ident_len += 1; + ident -= 1; + if (ident_len == 2) + { + od->id_inst_len = ident_len; + od->id_inst_ptr = ident; + + LWIP_ASSERT("invalid id", (ident[0] >= 0) && (ident[0] <= 0xff)); + id = (u8_t)ident[0]; + LWIP_DEBUGF(SNMP_MIB_DEBUG,("get_object_def system.%"U16_F".0\n",(u16_t)id)); + switch (id) + { + case 1: /* sysDescr */ + od->instance = MIB_OBJECT_SCALAR; + od->access = MIB_OBJECT_READ_ONLY; + od->asn_type = (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_OC_STR); + od->v_len = *sysdescr_len_ptr; + break; + case 2: /* sysObjectID */ + od->instance = MIB_OBJECT_SCALAR; + od->access = MIB_OBJECT_READ_ONLY; + od->asn_type = (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_OBJ_ID); + od->v_len = sysobjid.len * sizeof(s32_t); + break; + case 3: /* sysUpTime */ + od->instance = MIB_OBJECT_SCALAR; + od->access = MIB_OBJECT_READ_ONLY; + od->asn_type = (SNMP_ASN1_APPLIC | SNMP_ASN1_PRIMIT | SNMP_ASN1_TIMETICKS); + od->v_len = sizeof(u32_t); + break; + case 4: /* sysContact */ + od->instance = MIB_OBJECT_SCALAR; + od->access = MIB_OBJECT_READ_WRITE; + od->asn_type = (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_OC_STR); + od->v_len = *syscontact_len_ptr; + break; + case 5: /* sysName */ + od->instance = MIB_OBJECT_SCALAR; + od->access = MIB_OBJECT_READ_WRITE; + od->asn_type = (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_OC_STR); + od->v_len = *sysname_len_ptr; + break; + case 6: /* sysLocation */ + od->instance = MIB_OBJECT_SCALAR; + od->access = MIB_OBJECT_READ_WRITE; + od->asn_type = (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_OC_STR); + od->v_len = *syslocation_len_ptr; + break; + case 7: /* sysServices */ + od->instance = MIB_OBJECT_SCALAR; + od->access = MIB_OBJECT_READ_ONLY; + od->asn_type = (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_INTEG); + od->v_len = sizeof(s32_t); + break; + default: + LWIP_DEBUGF(SNMP_MIB_DEBUG,("system_get_object_def: no such object\n")); + od->instance = MIB_OBJECT_NONE; + break; + }; + } + else + { + LWIP_DEBUGF(SNMP_MIB_DEBUG,("system_get_object_def: no scalar\n")); + od->instance = MIB_OBJECT_NONE; + } +} + +/** + * Returns system object value. + * + * @param ident_len the address length (2) + * @param ident points to objectname.0 (object id trailer) + * @param len return value space (in bytes) + * @param value points to (varbind) space to copy value into. + */ +static void +system_get_value(struct obj_def *od, u16_t len, void *value) +{ + u8_t id; + + LWIP_ASSERT("invalid id", (od->id_inst_ptr[0] >= 0) && (od->id_inst_ptr[0] <= 0xff)); + id = (u8_t)od->id_inst_ptr[0]; + switch (id) + { + case 1: /* sysDescr */ + ocstrncpy((u8_t*)value, sysdescr_ptr, len); + break; + case 2: /* sysObjectID */ + objectidncpy((s32_t*)value, (s32_t*)sysobjid.id, (u8_t)(len / sizeof(s32_t))); + break; + case 3: /* sysUpTime */ + { + snmp_get_sysuptime((u32_t*)value); + } + break; + case 4: /* sysContact */ + ocstrncpy((u8_t*)value, syscontact_ptr, len); + break; + case 5: /* sysName */ + ocstrncpy((u8_t*)value, sysname_ptr, len); + break; + case 6: /* sysLocation */ + ocstrncpy((u8_t*)value, syslocation_ptr, len); + break; + case 7: /* sysServices */ + { + s32_t *sint_ptr = (s32_t*)value; + *sint_ptr = sysservices; + } + break; + }; +} + +static u8_t +system_set_test(struct obj_def *od, u16_t len, void *value) +{ + u8_t id, set_ok; + + LWIP_UNUSED_ARG(value); + set_ok = 0; + LWIP_ASSERT("invalid id", (od->id_inst_ptr[0] >= 0) && (od->id_inst_ptr[0] <= 0xff)); + id = (u8_t)od->id_inst_ptr[0]; + switch (id) + { + case 4: /* sysContact */ + if ((syscontact_ptr != syscontact_default) && + (len <= 255)) + { + set_ok = 1; + } + break; + case 5: /* sysName */ + if ((sysname_ptr != sysname_default) && + (len <= 255)) + { + set_ok = 1; + } + break; + case 6: /* sysLocation */ + if ((syslocation_ptr != syslocation_default) && + (len <= 255)) + { + set_ok = 1; + } + break; + }; + return set_ok; +} + +static void +system_set_value(struct obj_def *od, u16_t len, void *value) +{ + u8_t id; + + LWIP_ASSERT("invalid len", len <= 0xff); + LWIP_ASSERT("invalid id", (od->id_inst_ptr[0] >= 0) && (od->id_inst_ptr[0] <= 0xff)); + id = (u8_t)od->id_inst_ptr[0]; + switch (id) + { + case 4: /* sysContact */ + ocstrncpy(syscontact_ptr, (u8_t*)value, len); + *syscontact_len_ptr = (u8_t)len; + break; + case 5: /* sysName */ + ocstrncpy(sysname_ptr, (u8_t*)value, len); + *sysname_len_ptr = (u8_t)len; + break; + case 6: /* sysLocation */ + ocstrncpy(syslocation_ptr, (u8_t*)value, len); + *syslocation_len_ptr = (u8_t)len; + break; + }; +} + +/** + * Returns interfaces.ifnumber object definition. + * + * @param ident_len the address length (2) + * @param ident points to objectname.index + * @param od points to object definition. + */ +static void +interfaces_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od) +{ + /* return to object name, adding index depth (1) */ + ident_len += 1; + ident -= 1; + if (ident_len == 2) + { + od->id_inst_len = ident_len; + od->id_inst_ptr = ident; + + od->instance = MIB_OBJECT_SCALAR; + od->access = MIB_OBJECT_READ_ONLY; + od->asn_type = (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_INTEG); + od->v_len = sizeof(s32_t); + } + else + { + LWIP_DEBUGF(SNMP_MIB_DEBUG,("interfaces_get_object_def: no scalar\n")); + od->instance = MIB_OBJECT_NONE; + } +} + +/** + * Returns interfaces.ifnumber object value. + * + * @param ident_len the address length (2) + * @param ident points to objectname.0 (object id trailer) + * @param len return value space (in bytes) + * @param value points to (varbind) space to copy value into. + */ +static void +interfaces_get_value(struct obj_def *od, u16_t len, void *value) +{ + LWIP_UNUSED_ARG(len); + if (od->id_inst_ptr[0] == 1) + { + s32_t *sint_ptr = (s32_t*)value; + *sint_ptr = iflist_root.count; + } +} + +/** + * Returns ifentry object definitions. + * + * @param ident_len the address length (2) + * @param ident points to objectname.index + * @param od points to object definition. + */ +static void +ifentry_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od) +{ + u8_t id; + + /* return to object name, adding index depth (1) */ + ident_len += 1; + ident -= 1; + if (ident_len == 2) + { + od->id_inst_len = ident_len; + od->id_inst_ptr = ident; + + LWIP_ASSERT("invalid id", (ident[0] >= 0) && (ident[0] <= 0xff)); + id = (u8_t)ident[0]; + LWIP_DEBUGF(SNMP_MIB_DEBUG,("get_object_def ifentry.%"U16_F"\n",(u16_t)id)); + switch (id) + { + case 1: /* ifIndex */ + case 3: /* ifType */ + case 4: /* ifMtu */ + case 8: /* ifOperStatus */ + od->instance = MIB_OBJECT_TAB; + od->access = MIB_OBJECT_READ_ONLY; + od->asn_type = (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_INTEG); + od->v_len = sizeof(s32_t); + break; + case 2: /* ifDescr */ + od->instance = MIB_OBJECT_TAB; + od->access = MIB_OBJECT_READ_ONLY; + od->asn_type = (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_OC_STR); + /** @todo this should be some sort of sizeof(struct netif.name) */ + od->v_len = 2; + break; + case 5: /* ifSpeed */ + case 21: /* ifOutQLen */ + od->instance = MIB_OBJECT_TAB; + od->access = MIB_OBJECT_READ_ONLY; + od->asn_type = (SNMP_ASN1_APPLIC | SNMP_ASN1_PRIMIT | SNMP_ASN1_GAUGE); + od->v_len = sizeof(u32_t); + break; + case 6: /* ifPhysAddress */ + { + struct netif *netif; + + snmp_ifindextonetif(ident[1], &netif); + od->instance = MIB_OBJECT_TAB; + od->access = MIB_OBJECT_READ_ONLY; + od->asn_type = (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_OC_STR); + od->v_len = netif->hwaddr_len; + } + break; + case 7: /* ifAdminStatus */ + od->instance = MIB_OBJECT_TAB; + od->access = MIB_OBJECT_READ_WRITE; + od->asn_type = (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_INTEG); + od->v_len = sizeof(s32_t); + break; + case 9: /* ifLastChange */ + od->instance = MIB_OBJECT_TAB; + od->access = MIB_OBJECT_READ_ONLY; + od->asn_type = (SNMP_ASN1_APPLIC | SNMP_ASN1_PRIMIT | SNMP_ASN1_TIMETICKS); + od->v_len = sizeof(u32_t); + break; + case 10: /* ifInOctets */ + case 11: /* ifInUcastPkts */ + case 12: /* ifInNUcastPkts */ + case 13: /* ifInDiscarts */ + case 14: /* ifInErrors */ + case 15: /* ifInUnkownProtos */ + case 16: /* ifOutOctets */ + case 17: /* ifOutUcastPkts */ + case 18: /* ifOutNUcastPkts */ + case 19: /* ifOutDiscarts */ + case 20: /* ifOutErrors */ + od->instance = MIB_OBJECT_TAB; + od->access = MIB_OBJECT_READ_ONLY; + od->asn_type = (SNMP_ASN1_APPLIC | SNMP_ASN1_PRIMIT | SNMP_ASN1_COUNTER); + od->v_len = sizeof(u32_t); + break; + case 22: /* ifSpecific */ + /** @note returning zeroDotZero (0.0) no media specific MIB support */ + od->instance = MIB_OBJECT_TAB; + od->access = MIB_OBJECT_READ_ONLY; + od->asn_type = (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_OBJ_ID); + od->v_len = ifspecific.len * sizeof(s32_t); + break; + default: + LWIP_DEBUGF(SNMP_MIB_DEBUG,("ifentry_get_object_def: no such object\n")); + od->instance = MIB_OBJECT_NONE; + break; + }; + } + else + { + LWIP_DEBUGF(SNMP_MIB_DEBUG,("ifentry_get_object_def: no scalar\n")); + od->instance = MIB_OBJECT_NONE; + } +} + +/** + * Returns ifentry object value. + * + * @param ident_len the address length (2) + * @param ident points to objectname.0 (object id trailer) + * @param len return value space (in bytes) + * @param value points to (varbind) space to copy value into. + */ +static void +ifentry_get_value(struct obj_def *od, u16_t len, void *value) +{ + struct netif *netif; + u8_t id; + + snmp_ifindextonetif(od->id_inst_ptr[1], &netif); + LWIP_ASSERT("invalid id", (od->id_inst_ptr[0] >= 0) && (od->id_inst_ptr[0] <= 0xff)); + id = (u8_t)od->id_inst_ptr[0]; + switch (id) + { + case 1: /* ifIndex */ + { + s32_t *sint_ptr = (s32_t*)value; + *sint_ptr = od->id_inst_ptr[1]; + } + break; + case 2: /* ifDescr */ + ocstrncpy((u8_t*)value, (u8_t*)netif->name, len); + break; + case 3: /* ifType */ + { + s32_t *sint_ptr = (s32_t*)value; + *sint_ptr = netif->link_type; + } + break; + case 4: /* ifMtu */ + { + s32_t *sint_ptr = (s32_t*)value; + *sint_ptr = netif->mtu; + } + break; + case 5: /* ifSpeed */ + { + u32_t *uint_ptr = (u32_t*)value; + *uint_ptr = netif->link_speed; + } + break; + case 6: /* ifPhysAddress */ + ocstrncpy((u8_t*)value, netif->hwaddr, len); + break; + case 7: /* ifAdminStatus */ + { + s32_t *sint_ptr = (s32_t*)value; + if (netif_is_up(netif)) + { + if (netif_is_link_up(netif)) + { + *sint_ptr = 1; /* up */ + } + else + { + *sint_ptr = 7; /* lowerLayerDown */ + } + } + else + { + *sint_ptr = 2; /* down */ + } + } + break; + case 8: /* ifOperStatus */ + { + s32_t *sint_ptr = (s32_t*)value; + if (netif_is_up(netif)) + { + *sint_ptr = 1; + } + else + { + *sint_ptr = 2; + } + } + break; + case 9: /* ifLastChange */ + { + u32_t *uint_ptr = (u32_t*)value; + *uint_ptr = netif->ts; + } + break; + case 10: /* ifInOctets */ + { + u32_t *uint_ptr = (u32_t*)value; + *uint_ptr = netif->ifinoctets; + } + break; + case 11: /* ifInUcastPkts */ + { + u32_t *uint_ptr = (u32_t*)value; + *uint_ptr = netif->ifinucastpkts; + } + break; + case 12: /* ifInNUcastPkts */ + { + u32_t *uint_ptr = (u32_t*)value; + *uint_ptr = netif->ifinnucastpkts; + } + break; + case 13: /* ifInDiscarts */ + { + u32_t *uint_ptr = (u32_t*)value; + *uint_ptr = netif->ifindiscards; + } + break; + case 14: /* ifInErrors */ + case 15: /* ifInUnkownProtos */ + /** @todo add these counters! */ + { + u32_t *uint_ptr = (u32_t*)value; + *uint_ptr = 0; + } + break; + case 16: /* ifOutOctets */ + { + u32_t *uint_ptr = (u32_t*)value; + *uint_ptr = netif->ifoutoctets; + } + break; + case 17: /* ifOutUcastPkts */ + { + u32_t *uint_ptr = (u32_t*)value; + *uint_ptr = netif->ifoutucastpkts; + } + break; + case 18: /* ifOutNUcastPkts */ + { + u32_t *uint_ptr = (u32_t*)value; + *uint_ptr = netif->ifoutnucastpkts; + } + break; + case 19: /* ifOutDiscarts */ + { + u32_t *uint_ptr = (u32_t*)value; + *uint_ptr = netif->ifoutdiscards; + } + break; + case 20: /* ifOutErrors */ + /** @todo add this counter! */ + { + u32_t *uint_ptr = (u32_t*)value; + *uint_ptr = 0; + } + break; + case 21: /* ifOutQLen */ + /** @todo figure out if this must be 0 (no queue) or 1? */ + { + u32_t *uint_ptr = (u32_t*)value; + *uint_ptr = 0; + } + break; + case 22: /* ifSpecific */ + objectidncpy((s32_t*)value, (s32_t*)ifspecific.id, (u8_t)(len / sizeof(s32_t))); + break; + }; +} + +#if !SNMP_SAFE_REQUESTS +static u8_t +ifentry_set_test(struct obj_def *od, u16_t len, void *value) +{ + struct netif *netif; + u8_t id, set_ok; + LWIP_UNUSED_ARG(len); + + set_ok = 0; + snmp_ifindextonetif(od->id_inst_ptr[1], &netif); + id = (u8_t)od->id_inst_ptr[0]; + switch (id) + { + case 7: /* ifAdminStatus */ + { + s32_t *sint_ptr = (s32_t*)value; + if (*sint_ptr == 1 || *sint_ptr == 2) + set_ok = 1; + } + break; + } + return set_ok; +} + +static void +ifentry_set_value(struct obj_def *od, u16_t len, void *value) +{ + struct netif *netif; + u8_t id; + LWIP_UNUSED_ARG(len); + + snmp_ifindextonetif(od->id_inst_ptr[1], &netif); + id = (u8_t)od->id_inst_ptr[0]; + switch (id) + { + case 7: /* ifAdminStatus */ + { + s32_t *sint_ptr = (s32_t*)value; + if (*sint_ptr == 1) + { + netif_set_up(netif); + } + else if (*sint_ptr == 2) + { + netif_set_down(netif); + } + } + break; + } +} +#endif /* SNMP_SAFE_REQUESTS */ + +/** + * Returns atentry object definitions. + * + * @param ident_len the address length (6) + * @param ident points to objectname.atifindex.atnetaddress + * @param od points to object definition. + */ +static void +atentry_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od) +{ + /* return to object name, adding index depth (5) */ + ident_len += 5; + ident -= 5; + + if (ident_len == 6) + { + od->id_inst_len = ident_len; + od->id_inst_ptr = ident; + + switch (ident[0]) + { + case 1: /* atIfIndex */ + od->instance = MIB_OBJECT_TAB; + od->access = MIB_OBJECT_READ_WRITE; + od->asn_type = (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_INTEG); + od->v_len = sizeof(s32_t); + break; + case 2: /* atPhysAddress */ + od->instance = MIB_OBJECT_TAB; + od->access = MIB_OBJECT_READ_WRITE; + od->asn_type = (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_OC_STR); + od->v_len = 6; /** @todo try to use netif::hwaddr_len */ + break; + case 3: /* atNetAddress */ + od->instance = MIB_OBJECT_TAB; + od->access = MIB_OBJECT_READ_WRITE; + od->asn_type = (SNMP_ASN1_APPLIC | SNMP_ASN1_PRIMIT | SNMP_ASN1_IPADDR); + od->v_len = 4; + break; + default: + LWIP_DEBUGF(SNMP_MIB_DEBUG,("atentry_get_object_def: no such object\n")); + od->instance = MIB_OBJECT_NONE; + break; + } + } + else + { + LWIP_DEBUGF(SNMP_MIB_DEBUG,("atentry_get_object_def: no scalar\n")); + od->instance = MIB_OBJECT_NONE; + } +} + +static void +atentry_get_value(struct obj_def *od, u16_t len, void *value) +{ +#if LWIP_ARP + u8_t id; + struct eth_addr* ethaddr_ret; + ip_addr_t* ipaddr_ret; +#endif /* LWIP_ARP */ + ip_addr_t ip; + struct netif *netif; + + LWIP_UNUSED_ARG(len); + LWIP_UNUSED_ARG(value);/* if !LWIP_ARP */ + + snmp_ifindextonetif(od->id_inst_ptr[1], &netif); + snmp_oidtoip(&od->id_inst_ptr[2], &ip); + +#if LWIP_ARP /** @todo implement a netif_find_addr */ + if (etharp_find_addr(netif, &ip, ðaddr_ret, &ipaddr_ret) > -1) + { + LWIP_ASSERT("invalid id", (od->id_inst_ptr[0] >= 0) && (od->id_inst_ptr[0] <= 0xff)); + id = (u8_t)od->id_inst_ptr[0]; + switch (id) + { + case 1: /* atIfIndex */ + { + s32_t *sint_ptr = (s32_t*)value; + *sint_ptr = od->id_inst_ptr[1]; + } + break; + case 2: /* atPhysAddress */ + { + struct eth_addr *dst = (struct eth_addr*)value; + + *dst = *ethaddr_ret; + } + break; + case 3: /* atNetAddress */ + { + ip_addr_t *dst = (ip_addr_t*)value; + + *dst = *ipaddr_ret; + } + break; + } + } +#endif /* LWIP_ARP */ +} + +static void +ip_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od) +{ + u8_t id; + + /* return to object name, adding index depth (1) */ + ident_len += 1; + ident -= 1; + if (ident_len == 2) + { + od->id_inst_len = ident_len; + od->id_inst_ptr = ident; + + LWIP_ASSERT("invalid id", (ident[0] >= 0) && (ident[0] <= 0xff)); + id = (u8_t)ident[0]; + LWIP_DEBUGF(SNMP_MIB_DEBUG,("get_object_def ip.%"U16_F".0\n",(u16_t)id)); + switch (id) + { + case 1: /* ipForwarding */ + case 2: /* ipDefaultTTL */ + od->instance = MIB_OBJECT_SCALAR; + od->access = MIB_OBJECT_READ_WRITE; + od->asn_type = (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_INTEG); + od->v_len = sizeof(s32_t); + break; + case 3: /* ipInReceives */ + case 4: /* ipInHdrErrors */ + case 5: /* ipInAddrErrors */ + case 6: /* ipForwDatagrams */ + case 7: /* ipInUnknownProtos */ + case 8: /* ipInDiscards */ + case 9: /* ipInDelivers */ + case 10: /* ipOutRequests */ + case 11: /* ipOutDiscards */ + case 12: /* ipOutNoRoutes */ + case 14: /* ipReasmReqds */ + case 15: /* ipReasmOKs */ + case 16: /* ipReasmFails */ + case 17: /* ipFragOKs */ + case 18: /* ipFragFails */ + case 19: /* ipFragCreates */ + case 23: /* ipRoutingDiscards */ + od->instance = MIB_OBJECT_SCALAR; + od->access = MIB_OBJECT_READ_ONLY; + od->asn_type = (SNMP_ASN1_APPLIC | SNMP_ASN1_PRIMIT | SNMP_ASN1_COUNTER); + od->v_len = sizeof(u32_t); + break; + case 13: /* ipReasmTimeout */ + od->instance = MIB_OBJECT_SCALAR; + od->access = MIB_OBJECT_READ_ONLY; + od->asn_type = (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_INTEG); + od->v_len = sizeof(s32_t); + break; + default: + LWIP_DEBUGF(SNMP_MIB_DEBUG,("ip_get_object_def: no such object\n")); + od->instance = MIB_OBJECT_NONE; + break; + }; + } + else + { + LWIP_DEBUGF(SNMP_MIB_DEBUG,("ip_get_object_def: no scalar\n")); + od->instance = MIB_OBJECT_NONE; + } +} + +static void +ip_get_value(struct obj_def *od, u16_t len, void *value) +{ + u8_t id; + + LWIP_UNUSED_ARG(len); + LWIP_ASSERT("invalid id", (od->id_inst_ptr[0] >= 0) && (od->id_inst_ptr[0] <= 0xff)); + id = (u8_t)od->id_inst_ptr[0]; + switch (id) + { + case 1: /* ipForwarding */ + { + s32_t *sint_ptr = (s32_t*)value; +#if IP_FORWARD + /* forwarding */ + *sint_ptr = 1; +#else + /* not-forwarding */ + *sint_ptr = 2; +#endif + } + break; + case 2: /* ipDefaultTTL */ + { + s32_t *sint_ptr = (s32_t*)value; + *sint_ptr = IP_DEFAULT_TTL; + } + break; + case 3: /* ipInReceives */ + { + u32_t *uint_ptr = (u32_t*)value; + *uint_ptr = ipinreceives; + } + break; + case 4: /* ipInHdrErrors */ + { + u32_t *uint_ptr = (u32_t*)value; + *uint_ptr = ipinhdrerrors; + } + break; + case 5: /* ipInAddrErrors */ + { + u32_t *uint_ptr = (u32_t*)value; + *uint_ptr = ipinaddrerrors; + } + break; + case 6: /* ipForwDatagrams */ + { + u32_t *uint_ptr = (u32_t*)value; + *uint_ptr = ipforwdatagrams; + } + break; + case 7: /* ipInUnknownProtos */ + { + u32_t *uint_ptr = (u32_t*)value; + *uint_ptr = ipinunknownprotos; + } + break; + case 8: /* ipInDiscards */ + { + u32_t *uint_ptr = (u32_t*)value; + *uint_ptr = ipindiscards; + } + break; + case 9: /* ipInDelivers */ + { + u32_t *uint_ptr = (u32_t*)value; + *uint_ptr = ipindelivers; + } + break; + case 10: /* ipOutRequests */ + { + u32_t *uint_ptr = (u32_t*)value; + *uint_ptr = ipoutrequests; + } + break; + case 11: /* ipOutDiscards */ + { + u32_t *uint_ptr = (u32_t*)value; + *uint_ptr = ipoutdiscards; + } + break; + case 12: /* ipOutNoRoutes */ + { + u32_t *uint_ptr = (u32_t*)value; + *uint_ptr = ipoutnoroutes; + } + break; + case 13: /* ipReasmTimeout */ + { + s32_t *sint_ptr = (s32_t*)value; +#if IP_REASSEMBLY + *sint_ptr = IP_REASS_MAXAGE; +#else + *sint_ptr = 0; +#endif + } + break; + case 14: /* ipReasmReqds */ + { + u32_t *uint_ptr = (u32_t*)value; + *uint_ptr = ipreasmreqds; + } + break; + case 15: /* ipReasmOKs */ + { + u32_t *uint_ptr = (u32_t*)value; + *uint_ptr = ipreasmoks; + } + break; + case 16: /* ipReasmFails */ + { + u32_t *uint_ptr = (u32_t*)value; + *uint_ptr = ipreasmfails; + } + break; + case 17: /* ipFragOKs */ + { + u32_t *uint_ptr = (u32_t*)value; + *uint_ptr = ipfragoks; + } + break; + case 18: /* ipFragFails */ + { + u32_t *uint_ptr = (u32_t*)value; + *uint_ptr = ipfragfails; + } + break; + case 19: /* ipFragCreates */ + { + u32_t *uint_ptr = (u32_t*)value; + *uint_ptr = ipfragcreates; + } + break; + case 23: /* ipRoutingDiscards */ + /** @todo can lwIP discard routes at all?? hardwire this to 0?? */ + { + u32_t *uint_ptr = (u32_t*)value; + *uint_ptr = iproutingdiscards; + } + break; + }; +} + +/** + * Test ip object value before setting. + * + * @param od is the object definition + * @param len return value space (in bytes) + * @param value points to (varbind) space to copy value from. + * + * @note we allow set if the value matches the hardwired value, + * otherwise return badvalue. + */ +static u8_t +ip_set_test(struct obj_def *od, u16_t len, void *value) +{ + u8_t id, set_ok; + s32_t *sint_ptr = (s32_t*)value; + + LWIP_UNUSED_ARG(len); + set_ok = 0; + LWIP_ASSERT("invalid id", (od->id_inst_ptr[0] >= 0) && (od->id_inst_ptr[0] <= 0xff)); + id = (u8_t)od->id_inst_ptr[0]; + switch (id) + { + case 1: /* ipForwarding */ +#if IP_FORWARD + /* forwarding */ + if (*sint_ptr == 1) +#else + /* not-forwarding */ + if (*sint_ptr == 2) +#endif + { + set_ok = 1; + } + break; + case 2: /* ipDefaultTTL */ + if (*sint_ptr == IP_DEFAULT_TTL) + { + set_ok = 1; + } + break; + }; + return set_ok; +} + +static void +ip_addrentry_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od) +{ + /* return to object name, adding index depth (4) */ + ident_len += 4; + ident -= 4; + + if (ident_len == 5) + { + u8_t id; + + od->id_inst_len = ident_len; + od->id_inst_ptr = ident; + + LWIP_ASSERT("invalid id", (ident[0] >= 0) && (ident[0] <= 0xff)); + id = (u8_t)ident[0]; + switch (id) + { + case 1: /* ipAdEntAddr */ + case 3: /* ipAdEntNetMask */ + od->instance = MIB_OBJECT_TAB; + od->access = MIB_OBJECT_READ_ONLY; + od->asn_type = (SNMP_ASN1_APPLIC | SNMP_ASN1_PRIMIT | SNMP_ASN1_IPADDR); + od->v_len = 4; + break; + case 2: /* ipAdEntIfIndex */ + case 4: /* ipAdEntBcastAddr */ + case 5: /* ipAdEntReasmMaxSize */ + od->instance = MIB_OBJECT_TAB; + od->access = MIB_OBJECT_READ_ONLY; + od->asn_type = (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_INTEG); + od->v_len = sizeof(s32_t); + break; + default: + LWIP_DEBUGF(SNMP_MIB_DEBUG,("ip_addrentry_get_object_def: no such object\n")); + od->instance = MIB_OBJECT_NONE; + break; + } + } + else + { + LWIP_DEBUGF(SNMP_MIB_DEBUG,("ip_addrentry_get_object_def: no scalar\n")); + od->instance = MIB_OBJECT_NONE; + } +} + +static void +ip_addrentry_get_value(struct obj_def *od, u16_t len, void *value) +{ + u8_t id; + u16_t ifidx; + ip_addr_t ip; + struct netif *netif = netif_list; + + LWIP_UNUSED_ARG(len); + snmp_oidtoip(&od->id_inst_ptr[1], &ip); + ifidx = 0; + while ((netif != NULL) && !ip_addr_cmp(&ip, &netif->ip_addr)) + { + netif = netif->next; + ifidx++; + } + + if (netif != NULL) + { + LWIP_ASSERT("invalid id", (od->id_inst_ptr[0] >= 0) && (od->id_inst_ptr[0] <= 0xff)); + id = (u8_t)od->id_inst_ptr[0]; + switch (id) + { + case 1: /* ipAdEntAddr */ + { + ip_addr_t *dst = (ip_addr_t*)value; + *dst = netif->ip_addr; + } + break; + case 2: /* ipAdEntIfIndex */ + { + s32_t *sint_ptr = (s32_t*)value; + *sint_ptr = ifidx + 1; + } + break; + case 3: /* ipAdEntNetMask */ + { + ip_addr_t *dst = (ip_addr_t*)value; + *dst = netif->netmask; + } + break; + case 4: /* ipAdEntBcastAddr */ + { + s32_t *sint_ptr = (s32_t*)value; + + /* lwIP oddity, there's no broadcast + address in the netif we can rely on */ + *sint_ptr = IPADDR_BROADCAST & 1; + } + break; + case 5: /* ipAdEntReasmMaxSize */ + { + s32_t *sint_ptr = (s32_t*)value; +#if IP_REASSEMBLY + /* @todo The theoretical maximum is IP_REASS_MAX_PBUFS * size of the pbufs, + * but only if receiving one fragmented packet at a time. + * The current solution is to calculate for 2 simultaneous packets... + */ + *sint_ptr = (IP_HLEN + ((IP_REASS_MAX_PBUFS/2) * + (PBUF_POOL_BUFSIZE - PBUF_LINK_HLEN - IP_HLEN))); +#else + /** @todo returning MTU would be a bad thing and + returning a wild guess like '576' isn't good either */ + *sint_ptr = 0; +#endif + } + break; + } + } +} + +/** + * @note + * lwIP IP routing is currently using the network addresses in netif_list. + * if no suitable network IP is found in netif_list, the default_netif is used. + */ +static void +ip_rteentry_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od) +{ + u8_t id; + + /* return to object name, adding index depth (4) */ + ident_len += 4; + ident -= 4; + + if (ident_len == 5) + { + od->id_inst_len = ident_len; + od->id_inst_ptr = ident; + + LWIP_ASSERT("invalid id", (ident[0] >= 0) && (ident[0] <= 0xff)); + id = (u8_t)ident[0]; + switch (id) + { + case 1: /* ipRouteDest */ + case 7: /* ipRouteNextHop */ + case 11: /* ipRouteMask */ + od->instance = MIB_OBJECT_TAB; + od->access = MIB_OBJECT_READ_WRITE; + od->asn_type = (SNMP_ASN1_APPLIC | SNMP_ASN1_PRIMIT | SNMP_ASN1_IPADDR); + od->v_len = 4; + break; + case 2: /* ipRouteIfIndex */ + case 3: /* ipRouteMetric1 */ + case 4: /* ipRouteMetric2 */ + case 5: /* ipRouteMetric3 */ + case 6: /* ipRouteMetric4 */ + case 8: /* ipRouteType */ + case 10: /* ipRouteAge */ + case 12: /* ipRouteMetric5 */ + od->instance = MIB_OBJECT_TAB; + od->access = MIB_OBJECT_READ_WRITE; + od->asn_type = (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_INTEG); + od->v_len = sizeof(s32_t); + break; + case 9: /* ipRouteProto */ + od->instance = MIB_OBJECT_TAB; + od->access = MIB_OBJECT_READ_ONLY; + od->asn_type = (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_INTEG); + od->v_len = sizeof(s32_t); + break; + case 13: /* ipRouteInfo */ + /** @note returning zeroDotZero (0.0) no routing protocol specific MIB */ + od->instance = MIB_OBJECT_TAB; + od->access = MIB_OBJECT_READ_ONLY; + od->asn_type = (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_OBJ_ID); + od->v_len = iprouteinfo.len * sizeof(s32_t); + break; + default: + LWIP_DEBUGF(SNMP_MIB_DEBUG,("ip_rteentry_get_object_def: no such object\n")); + od->instance = MIB_OBJECT_NONE; + break; + } + } + else + { + LWIP_DEBUGF(SNMP_MIB_DEBUG,("ip_rteentry_get_object_def: no scalar\n")); + od->instance = MIB_OBJECT_NONE; + } +} + +static void +ip_rteentry_get_value(struct obj_def *od, u16_t len, void *value) +{ + struct netif *netif; + ip_addr_t dest; + s32_t *ident; + u8_t id; + + ident = od->id_inst_ptr; + snmp_oidtoip(&ident[1], &dest); + + if (ip_addr_isany(&dest)) + { + /* ip_route() uses default netif for default route */ + netif = netif_default; + } + else + { + /* not using ip_route(), need exact match! */ + netif = netif_list; + while ((netif != NULL) && + !ip_addr_netcmp(&dest, &(netif->ip_addr), &(netif->netmask)) ) + { + netif = netif->next; + } + } + if (netif != NULL) + { + LWIP_ASSERT("invalid id", (ident[0] >= 0) && (ident[0] <= 0xff)); + id = (u8_t)ident[0]; + switch (id) + { + case 1: /* ipRouteDest */ + { + ip_addr_t *dst = (ip_addr_t*)value; + + if (ip_addr_isany(&dest)) + { + /* default rte has 0.0.0.0 dest */ + ip_addr_set_zero(dst); + } + else + { + /* netifs have netaddress dest */ + ip_addr_get_network(dst, &netif->ip_addr, &netif->netmask); + } + } + break; + case 2: /* ipRouteIfIndex */ + { + s32_t *sint_ptr = (s32_t*)value; + + snmp_netiftoifindex(netif, sint_ptr); + } + break; + case 3: /* ipRouteMetric1 */ + { + s32_t *sint_ptr = (s32_t*)value; + + if (ip_addr_isany(&dest)) + { + /* default rte has metric 1 */ + *sint_ptr = 1; + } + else + { + /* other rtes have metric 0 */ + *sint_ptr = 0; + } + } + break; + case 4: /* ipRouteMetric2 */ + case 5: /* ipRouteMetric3 */ + case 6: /* ipRouteMetric4 */ + case 12: /* ipRouteMetric5 */ + { + s32_t *sint_ptr = (s32_t*)value; + /* not used */ + *sint_ptr = -1; + } + break; + case 7: /* ipRouteNextHop */ + { + ip_addr_t *dst = (ip_addr_t*)value; + + if (ip_addr_isany(&dest)) + { + /* default rte: gateway */ + *dst = netif->gw; + } + else + { + /* other rtes: netif ip_addr */ + *dst = netif->ip_addr; + } + } + break; + case 8: /* ipRouteType */ + { + s32_t *sint_ptr = (s32_t*)value; + + if (ip_addr_isany(&dest)) + { + /* default rte is indirect */ + *sint_ptr = 4; + } + else + { + /* other rtes are direct */ + *sint_ptr = 3; + } + } + break; + case 9: /* ipRouteProto */ + { + s32_t *sint_ptr = (s32_t*)value; + /* locally defined routes */ + *sint_ptr = 2; + } + break; + case 10: /* ipRouteAge */ + { + s32_t *sint_ptr = (s32_t*)value; + /** @todo (sysuptime - timestamp last change) / 100 + @see snmp_insert_iprteidx_tree() */ + *sint_ptr = 0; + } + break; + case 11: /* ipRouteMask */ + { + ip_addr_t *dst = (ip_addr_t*)value; + + if (ip_addr_isany(&dest)) + { + /* default rte use 0.0.0.0 mask */ + ip_addr_set_zero(dst); + } + else + { + /* other rtes use netmask */ + *dst = netif->netmask; + } + } + break; + case 13: /* ipRouteInfo */ + objectidncpy((s32_t*)value, (s32_t*)iprouteinfo.id, (u8_t)(len / sizeof(s32_t))); + break; + } + } +} + +static void +ip_ntomentry_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od) +{ + /* return to object name, adding index depth (5) */ + ident_len += 5; + ident -= 5; + + if (ident_len == 6) + { + u8_t id; + + od->id_inst_len = ident_len; + od->id_inst_ptr = ident; + + LWIP_ASSERT("invalid id", (ident[0] >= 0) && (ident[0] <= 0xff)); + id = (u8_t)ident[0]; + switch (id) + { + case 1: /* ipNetToMediaIfIndex */ + case 4: /* ipNetToMediaType */ + od->instance = MIB_OBJECT_TAB; + od->access = MIB_OBJECT_READ_WRITE; + od->asn_type = (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_INTEG); + od->v_len = sizeof(s32_t); + break; + case 2: /* ipNetToMediaPhysAddress */ + od->instance = MIB_OBJECT_TAB; + od->access = MIB_OBJECT_READ_WRITE; + od->asn_type = (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_OC_STR); + od->v_len = 6; /** @todo try to use netif::hwaddr_len */ + break; + case 3: /* ipNetToMediaNetAddress */ + od->instance = MIB_OBJECT_TAB; + od->access = MIB_OBJECT_READ_WRITE; + od->asn_type = (SNMP_ASN1_APPLIC | SNMP_ASN1_PRIMIT | SNMP_ASN1_IPADDR); + od->v_len = 4; + break; + default: + LWIP_DEBUGF(SNMP_MIB_DEBUG,("ip_ntomentry_get_object_def: no such object\n")); + od->instance = MIB_OBJECT_NONE; + break; + } + } + else + { + LWIP_DEBUGF(SNMP_MIB_DEBUG,("ip_ntomentry_get_object_def: no scalar\n")); + od->instance = MIB_OBJECT_NONE; + } +} + +static void +ip_ntomentry_get_value(struct obj_def *od, u16_t len, void *value) +{ +#if LWIP_ARP + u8_t id; + struct eth_addr* ethaddr_ret; + ip_addr_t* ipaddr_ret; +#endif /* LWIP_ARP */ + ip_addr_t ip; + struct netif *netif; + + LWIP_UNUSED_ARG(len); + LWIP_UNUSED_ARG(value);/* if !LWIP_ARP */ + + snmp_ifindextonetif(od->id_inst_ptr[1], &netif); + snmp_oidtoip(&od->id_inst_ptr[2], &ip); + +#if LWIP_ARP /** @todo implement a netif_find_addr */ + if (etharp_find_addr(netif, &ip, ðaddr_ret, &ipaddr_ret) > -1) + { + LWIP_ASSERT("invalid id", (od->id_inst_ptr[0] >= 0) && (od->id_inst_ptr[0] <= 0xff)); + id = (u8_t)od->id_inst_ptr[0]; + switch (id) + { + case 1: /* ipNetToMediaIfIndex */ + { + s32_t *sint_ptr = (s32_t*)value; + *sint_ptr = od->id_inst_ptr[1]; + } + break; + case 2: /* ipNetToMediaPhysAddress */ + { + struct eth_addr *dst = (struct eth_addr*)value; + + *dst = *ethaddr_ret; + } + break; + case 3: /* ipNetToMediaNetAddress */ + { + ip_addr_t *dst = (ip_addr_t*)value; + + *dst = *ipaddr_ret; + } + break; + case 4: /* ipNetToMediaType */ + { + s32_t *sint_ptr = (s32_t*)value; + /* dynamic (?) */ + *sint_ptr = 3; + } + break; + } + } +#endif /* LWIP_ARP */ +} + +static void +icmp_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od) +{ + /* return to object name, adding index depth (1) */ + ident_len += 1; + ident -= 1; + if ((ident_len == 2) && + (ident[0] > 0) && (ident[0] < 27)) + { + od->id_inst_len = ident_len; + od->id_inst_ptr = ident; + + od->instance = MIB_OBJECT_SCALAR; + od->access = MIB_OBJECT_READ_ONLY; + od->asn_type = (SNMP_ASN1_APPLIC | SNMP_ASN1_PRIMIT | SNMP_ASN1_COUNTER); + od->v_len = sizeof(u32_t); + } + else + { + LWIP_DEBUGF(SNMP_MIB_DEBUG,("icmp_get_object_def: no scalar\n")); + od->instance = MIB_OBJECT_NONE; + } +} + +static void +icmp_get_value(struct obj_def *od, u16_t len, void *value) +{ + u32_t *uint_ptr = (u32_t*)value; + u8_t id; + + LWIP_UNUSED_ARG(len); + LWIP_ASSERT("invalid id", (od->id_inst_ptr[0] >= 0) && (od->id_inst_ptr[0] <= 0xff)); + id = (u8_t)od->id_inst_ptr[0]; + switch (id) + { + case 1: /* icmpInMsgs */ + *uint_ptr = icmpinmsgs; + break; + case 2: /* icmpInErrors */ + *uint_ptr = icmpinerrors; + break; + case 3: /* icmpInDestUnreachs */ + *uint_ptr = icmpindestunreachs; + break; + case 4: /* icmpInTimeExcds */ + *uint_ptr = icmpintimeexcds; + break; + case 5: /* icmpInParmProbs */ + *uint_ptr = icmpinparmprobs; + break; + case 6: /* icmpInSrcQuenchs */ + *uint_ptr = icmpinsrcquenchs; + break; + case 7: /* icmpInRedirects */ + *uint_ptr = icmpinredirects; + break; + case 8: /* icmpInEchos */ + *uint_ptr = icmpinechos; + break; + case 9: /* icmpInEchoReps */ + *uint_ptr = icmpinechoreps; + break; + case 10: /* icmpInTimestamps */ + *uint_ptr = icmpintimestamps; + break; + case 11: /* icmpInTimestampReps */ + *uint_ptr = icmpintimestampreps; + break; + case 12: /* icmpInAddrMasks */ + *uint_ptr = icmpinaddrmasks; + break; + case 13: /* icmpInAddrMaskReps */ + *uint_ptr = icmpinaddrmaskreps; + break; + case 14: /* icmpOutMsgs */ + *uint_ptr = icmpoutmsgs; + break; + case 15: /* icmpOutErrors */ + *uint_ptr = icmpouterrors; + break; + case 16: /* icmpOutDestUnreachs */ + *uint_ptr = icmpoutdestunreachs; + break; + case 17: /* icmpOutTimeExcds */ + *uint_ptr = icmpouttimeexcds; + break; + case 18: /* icmpOutParmProbs */ + *uint_ptr = icmpoutparmprobs; + break; + case 19: /* icmpOutSrcQuenchs */ + *uint_ptr = icmpoutsrcquenchs; + break; + case 20: /* icmpOutRedirects */ + *uint_ptr = icmpoutredirects; + break; + case 21: /* icmpOutEchos */ + *uint_ptr = icmpoutechos; + break; + case 22: /* icmpOutEchoReps */ + *uint_ptr = icmpoutechoreps; + break; + case 23: /* icmpOutTimestamps */ + *uint_ptr = icmpouttimestamps; + break; + case 24: /* icmpOutTimestampReps */ + *uint_ptr = icmpouttimestampreps; + break; + case 25: /* icmpOutAddrMasks */ + *uint_ptr = icmpoutaddrmasks; + break; + case 26: /* icmpOutAddrMaskReps */ + *uint_ptr = icmpoutaddrmaskreps; + break; + } +} + +#if LWIP_TCP +/** @todo tcp grp */ +static void +tcp_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od) +{ + u8_t id; + + /* return to object name, adding index depth (1) */ + ident_len += 1; + ident -= 1; + if (ident_len == 2) + { + od->id_inst_len = ident_len; + od->id_inst_ptr = ident; + + LWIP_ASSERT("invalid id", (ident[0] >= 0) && (ident[0] <= 0xff)); + id = (u8_t)ident[0]; + LWIP_DEBUGF(SNMP_MIB_DEBUG,("get_object_def tcp.%"U16_F".0\n",(u16_t)id)); + + switch (id) + { + case 1: /* tcpRtoAlgorithm */ + case 2: /* tcpRtoMin */ + case 3: /* tcpRtoMax */ + case 4: /* tcpMaxConn */ + od->instance = MIB_OBJECT_SCALAR; + od->access = MIB_OBJECT_READ_ONLY; + od->asn_type = (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_INTEG); + od->v_len = sizeof(s32_t); + break; + case 5: /* tcpActiveOpens */ + case 6: /* tcpPassiveOpens */ + case 7: /* tcpAttemptFails */ + case 8: /* tcpEstabResets */ + case 10: /* tcpInSegs */ + case 11: /* tcpOutSegs */ + case 12: /* tcpRetransSegs */ + case 14: /* tcpInErrs */ + case 15: /* tcpOutRsts */ + od->instance = MIB_OBJECT_SCALAR; + od->access = MIB_OBJECT_READ_ONLY; + od->asn_type = (SNMP_ASN1_APPLIC | SNMP_ASN1_PRIMIT | SNMP_ASN1_COUNTER); + od->v_len = sizeof(u32_t); + break; + case 9: /* tcpCurrEstab */ + od->instance = MIB_OBJECT_TAB; + od->access = MIB_OBJECT_READ_ONLY; + od->asn_type = (SNMP_ASN1_APPLIC | SNMP_ASN1_PRIMIT | SNMP_ASN1_GAUGE); + od->v_len = sizeof(u32_t); + break; + default: + LWIP_DEBUGF(SNMP_MIB_DEBUG,("tcp_get_object_def: no such object\n")); + od->instance = MIB_OBJECT_NONE; + break; + }; + } + else + { + LWIP_DEBUGF(SNMP_MIB_DEBUG,("tcp_get_object_def: no scalar\n")); + od->instance = MIB_OBJECT_NONE; + } +} + +static void +tcp_get_value(struct obj_def *od, u16_t len, void *value) +{ + u32_t *uint_ptr = (u32_t*)value; + s32_t *sint_ptr = (s32_t*)value; + u8_t id; + + LWIP_UNUSED_ARG(len); + LWIP_ASSERT("invalid id", (od->id_inst_ptr[0] >= 0) && (od->id_inst_ptr[0] <= 0xff)); + id = (u8_t)od->id_inst_ptr[0]; + switch (id) + { + case 1: /* tcpRtoAlgorithm, vanj(4) */ + *sint_ptr = 4; + break; + case 2: /* tcpRtoMin */ + /* @todo not the actual value, a guess, + needs to be calculated */ + *sint_ptr = 1000; + break; + case 3: /* tcpRtoMax */ + /* @todo not the actual value, a guess, + needs to be calculated */ + *sint_ptr = 60000; + break; + case 4: /* tcpMaxConn */ + *sint_ptr = MEMP_NUM_TCP_PCB; + break; + case 5: /* tcpActiveOpens */ + *uint_ptr = tcpactiveopens; + break; + case 6: /* tcpPassiveOpens */ + *uint_ptr = tcppassiveopens; + break; + case 7: /* tcpAttemptFails */ + *uint_ptr = tcpattemptfails; + break; + case 8: /* tcpEstabResets */ + *uint_ptr = tcpestabresets; + break; + case 9: /* tcpCurrEstab */ + { + u16_t tcpcurrestab = 0; + struct tcp_pcb *pcb = tcp_active_pcbs; + while (pcb != NULL) + { + if ((pcb->state == ESTABLISHED) || + (pcb->state == CLOSE_WAIT)) + { + tcpcurrestab++; + } + pcb = pcb->next; + } + *uint_ptr = tcpcurrestab; + } + break; + case 10: /* tcpInSegs */ + *uint_ptr = tcpinsegs; + break; + case 11: /* tcpOutSegs */ + *uint_ptr = tcpoutsegs; + break; + case 12: /* tcpRetransSegs */ + *uint_ptr = tcpretranssegs; + break; + case 14: /* tcpInErrs */ + *uint_ptr = tcpinerrs; + break; + case 15: /* tcpOutRsts */ + *uint_ptr = tcpoutrsts; + break; + } +} +#ifdef THIS_SEEMS_UNUSED +static void +tcpconnentry_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od) +{ + /* return to object name, adding index depth (10) */ + ident_len += 10; + ident -= 10; + + if (ident_len == 11) + { + u8_t id; + + od->id_inst_len = ident_len; + od->id_inst_ptr = ident; + + id = ident[0]; + LWIP_DEBUGF(SNMP_MIB_DEBUG,("get_object_def tcp.%"U16_F".0\n",(u16_t)id)); + + switch (id) + { + case 1: /* tcpConnState */ + od->instance = MIB_OBJECT_TAB; + od->access = MIB_OBJECT_READ_WRITE; + od->asn_type = (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_INTEG); + od->v_len = sizeof(s32_t); + break; + case 2: /* tcpConnLocalAddress */ + case 4: /* tcpConnRemAddress */ + od->instance = MIB_OBJECT_TAB; + od->access = MIB_OBJECT_READ_ONLY; + od->asn_type = (SNMP_ASN1_APPLIC | SNMP_ASN1_PRIMIT | SNMP_ASN1_IPADDR); + od->v_len = 4; + break; + case 3: /* tcpConnLocalPort */ + case 5: /* tcpConnRemPort */ + od->instance = MIB_OBJECT_TAB; + od->access = MIB_OBJECT_READ_ONLY; + od->asn_type = (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_INTEG); + od->v_len = sizeof(s32_t); + break; + default: + LWIP_DEBUGF(SNMP_MIB_DEBUG,("tcpconnentry_get_object_def: no such object\n")); + od->instance = MIB_OBJECT_NONE; + break; + }; + } + else + { + LWIP_DEBUGF(SNMP_MIB_DEBUG,("tcpconnentry_get_object_def: no such object\n")); + od->instance = MIB_OBJECT_NONE; + } +} + +static void +tcpconnentry_get_value(struct obj_def *od, u16_t len, void *value) +{ + ip_addr_t lip, rip; + u16_t lport, rport; + s32_t *ident; + + ident = od->id_inst_ptr; + snmp_oidtoip(&ident[1], &lip); + lport = ident[5]; + snmp_oidtoip(&ident[6], &rip); + rport = ident[10]; + + /** @todo find matching PCB */ +} +#endif /* if 0 */ +#endif + +static void +udp_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od) +{ + /* return to object name, adding index depth (1) */ + ident_len += 1; + ident -= 1; + if ((ident_len == 2) && + (ident[0] > 0) && (ident[0] < 6)) + { + od->id_inst_len = ident_len; + od->id_inst_ptr = ident; + + od->instance = MIB_OBJECT_SCALAR; + od->access = MIB_OBJECT_READ_ONLY; + od->asn_type = (SNMP_ASN1_APPLIC | SNMP_ASN1_PRIMIT | SNMP_ASN1_COUNTER); + od->v_len = sizeof(u32_t); + } + else + { + LWIP_DEBUGF(SNMP_MIB_DEBUG,("udp_get_object_def: no scalar\n")); + od->instance = MIB_OBJECT_NONE; + } +} + +static void +udp_get_value(struct obj_def *od, u16_t len, void *value) +{ + u32_t *uint_ptr = (u32_t*)value; + u8_t id; + + LWIP_UNUSED_ARG(len); + LWIP_ASSERT("invalid id", (od->id_inst_ptr[0] >= 0) && (od->id_inst_ptr[0] <= 0xff)); + id = (u8_t)od->id_inst_ptr[0]; + switch (id) + { + case 1: /* udpInDatagrams */ + *uint_ptr = udpindatagrams; + break; + case 2: /* udpNoPorts */ + *uint_ptr = udpnoports; + break; + case 3: /* udpInErrors */ + *uint_ptr = udpinerrors; + break; + case 4: /* udpOutDatagrams */ + *uint_ptr = udpoutdatagrams; + break; + } +} + +static void +udpentry_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od) +{ + /* return to object name, adding index depth (5) */ + ident_len += 5; + ident -= 5; + + if (ident_len == 6) + { + od->id_inst_len = ident_len; + od->id_inst_ptr = ident; + + switch (ident[0]) + { + case 1: /* udpLocalAddress */ + od->instance = MIB_OBJECT_TAB; + od->access = MIB_OBJECT_READ_ONLY; + od->asn_type = (SNMP_ASN1_APPLIC | SNMP_ASN1_PRIMIT | SNMP_ASN1_IPADDR); + od->v_len = 4; + break; + case 2: /* udpLocalPort */ + od->instance = MIB_OBJECT_TAB; + od->access = MIB_OBJECT_READ_ONLY; + od->asn_type = (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_INTEG); + od->v_len = sizeof(s32_t); + break; + default: + LWIP_DEBUGF(SNMP_MIB_DEBUG,("udpentry_get_object_def: no such object\n")); + od->instance = MIB_OBJECT_NONE; + break; + } + } + else + { + LWIP_DEBUGF(SNMP_MIB_DEBUG,("udpentry_get_object_def: no scalar\n")); + od->instance = MIB_OBJECT_NONE; + } +} + +static void +udpentry_get_value(struct obj_def *od, u16_t len, void *value) +{ + u8_t id; + struct udp_pcb *pcb; + ip_addr_t ip; + u16_t port; + + LWIP_UNUSED_ARG(len); + snmp_oidtoip(&od->id_inst_ptr[1], &ip); + LWIP_ASSERT("invalid port", (od->id_inst_ptr[5] >= 0) && (od->id_inst_ptr[5] <= 0xffff)); + port = (u16_t)od->id_inst_ptr[5]; + + pcb = udp_pcbs; + while ((pcb != NULL) && + !(ip_addr_cmp(&pcb->local_ip, &ip) && + (pcb->local_port == port))) + { + pcb = pcb->next; + } + + if (pcb != NULL) + { + LWIP_ASSERT("invalid id", (od->id_inst_ptr[0] >= 0) && (od->id_inst_ptr[0] <= 0xff)); + id = (u8_t)od->id_inst_ptr[0]; + switch (id) + { + case 1: /* udpLocalAddress */ + { + ip_addr_t *dst = (ip_addr_t*)value; + *dst = pcb->local_ip; + } + break; + case 2: /* udpLocalPort */ + { + s32_t *sint_ptr = (s32_t*)value; + *sint_ptr = pcb->local_port; + } + break; + } + } +} + +static void +snmp_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od) +{ + /* return to object name, adding index depth (1) */ + ident_len += 1; + ident -= 1; + if (ident_len == 2) + { + u8_t id; + + od->id_inst_len = ident_len; + od->id_inst_ptr = ident; + + LWIP_ASSERT("invalid id", (ident[0] >= 0) && (ident[0] <= 0xff)); + id = (u8_t)ident[0]; + switch (id) + { + case 1: /* snmpInPkts */ + case 2: /* snmpOutPkts */ + case 3: /* snmpInBadVersions */ + case 4: /* snmpInBadCommunityNames */ + case 5: /* snmpInBadCommunityUses */ + case 6: /* snmpInASNParseErrs */ + case 8: /* snmpInTooBigs */ + case 9: /* snmpInNoSuchNames */ + case 10: /* snmpInBadValues */ + case 11: /* snmpInReadOnlys */ + case 12: /* snmpInGenErrs */ + case 13: /* snmpInTotalReqVars */ + case 14: /* snmpInTotalSetVars */ + case 15: /* snmpInGetRequests */ + case 16: /* snmpInGetNexts */ + case 17: /* snmpInSetRequests */ + case 18: /* snmpInGetResponses */ + case 19: /* snmpInTraps */ + case 20: /* snmpOutTooBigs */ + case 21: /* snmpOutNoSuchNames */ + case 22: /* snmpOutBadValues */ + case 24: /* snmpOutGenErrs */ + case 25: /* snmpOutGetRequests */ + case 26: /* snmpOutGetNexts */ + case 27: /* snmpOutSetRequests */ + case 28: /* snmpOutGetResponses */ + case 29: /* snmpOutTraps */ + od->instance = MIB_OBJECT_SCALAR; + od->access = MIB_OBJECT_READ_ONLY; + od->asn_type = (SNMP_ASN1_APPLIC | SNMP_ASN1_PRIMIT | SNMP_ASN1_COUNTER); + od->v_len = sizeof(u32_t); + break; + case 30: /* snmpEnableAuthenTraps */ + od->instance = MIB_OBJECT_SCALAR; + od->access = MIB_OBJECT_READ_WRITE; + od->asn_type = (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_INTEG); + od->v_len = sizeof(s32_t); + break; + default: + LWIP_DEBUGF(SNMP_MIB_DEBUG,("snmp_get_object_def: no such object\n")); + od->instance = MIB_OBJECT_NONE; + break; + }; + } + else + { + LWIP_DEBUGF(SNMP_MIB_DEBUG,("snmp_get_object_def: no scalar\n")); + od->instance = MIB_OBJECT_NONE; + } +} + +static void +snmp_get_value(struct obj_def *od, u16_t len, void *value) +{ + u32_t *uint_ptr = (u32_t*)value; + u8_t id; + + LWIP_UNUSED_ARG(len); + LWIP_ASSERT("invalid id", (od->id_inst_ptr[0] >= 0) && (od->id_inst_ptr[0] <= 0xff)); + id = (u8_t)od->id_inst_ptr[0]; + switch (id) + { + case 1: /* snmpInPkts */ + *uint_ptr = snmpinpkts; + break; + case 2: /* snmpOutPkts */ + *uint_ptr = snmpoutpkts; + break; + case 3: /* snmpInBadVersions */ + *uint_ptr = snmpinbadversions; + break; + case 4: /* snmpInBadCommunityNames */ + *uint_ptr = snmpinbadcommunitynames; + break; + case 5: /* snmpInBadCommunityUses */ + *uint_ptr = snmpinbadcommunityuses; + break; + case 6: /* snmpInASNParseErrs */ + *uint_ptr = snmpinasnparseerrs; + break; + case 8: /* snmpInTooBigs */ + *uint_ptr = snmpintoobigs; + break; + case 9: /* snmpInNoSuchNames */ + *uint_ptr = snmpinnosuchnames; + break; + case 10: /* snmpInBadValues */ + *uint_ptr = snmpinbadvalues; + break; + case 11: /* snmpInReadOnlys */ + *uint_ptr = snmpinreadonlys; + break; + case 12: /* snmpInGenErrs */ + *uint_ptr = snmpingenerrs; + break; + case 13: /* snmpInTotalReqVars */ + *uint_ptr = snmpintotalreqvars; + break; + case 14: /* snmpInTotalSetVars */ + *uint_ptr = snmpintotalsetvars; + break; + case 15: /* snmpInGetRequests */ + *uint_ptr = snmpingetrequests; + break; + case 16: /* snmpInGetNexts */ + *uint_ptr = snmpingetnexts; + break; + case 17: /* snmpInSetRequests */ + *uint_ptr = snmpinsetrequests; + break; + case 18: /* snmpInGetResponses */ + *uint_ptr = snmpingetresponses; + break; + case 19: /* snmpInTraps */ + *uint_ptr = snmpintraps; + break; + case 20: /* snmpOutTooBigs */ + *uint_ptr = snmpouttoobigs; + break; + case 21: /* snmpOutNoSuchNames */ + *uint_ptr = snmpoutnosuchnames; + break; + case 22: /* snmpOutBadValues */ + *uint_ptr = snmpoutbadvalues; + break; + case 24: /* snmpOutGenErrs */ + *uint_ptr = snmpoutgenerrs; + break; + case 25: /* snmpOutGetRequests */ + *uint_ptr = snmpoutgetrequests; + break; + case 26: /* snmpOutGetNexts */ + *uint_ptr = snmpoutgetnexts; + break; + case 27: /* snmpOutSetRequests */ + *uint_ptr = snmpoutsetrequests; + break; + case 28: /* snmpOutGetResponses */ + *uint_ptr = snmpoutgetresponses; + break; + case 29: /* snmpOutTraps */ + *uint_ptr = snmpouttraps; + break; + case 30: /* snmpEnableAuthenTraps */ + *uint_ptr = *snmpenableauthentraps_ptr; + break; + }; +} + +/** + * Test snmp object value before setting. + * + * @param od is the object definition + * @param len return value space (in bytes) + * @param value points to (varbind) space to copy value from. + */ +static u8_t +snmp_set_test(struct obj_def *od, u16_t len, void *value) +{ + u8_t id, set_ok; + + LWIP_UNUSED_ARG(len); + set_ok = 0; + LWIP_ASSERT("invalid id", (od->id_inst_ptr[0] >= 0) && (od->id_inst_ptr[0] <= 0xff)); + id = (u8_t)od->id_inst_ptr[0]; + if (id == 30) + { + /* snmpEnableAuthenTraps */ + s32_t *sint_ptr = (s32_t*)value; + + if (snmpenableauthentraps_ptr != &snmpenableauthentraps_default) + { + /* we should have writable non-volatile mem here */ + if ((*sint_ptr == 1) || (*sint_ptr == 2)) + { + set_ok = 1; + } + } + else + { + /* const or hardwired value */ + if (*sint_ptr == snmpenableauthentraps_default) + { + set_ok = 1; + } + } + } + return set_ok; +} + +static void +snmp_set_value(struct obj_def *od, u16_t len, void *value) +{ + u8_t id; + + LWIP_UNUSED_ARG(len); + LWIP_ASSERT("invalid id", (od->id_inst_ptr[0] >= 0) && (od->id_inst_ptr[0] <= 0xff)); + id = (u8_t)od->id_inst_ptr[0]; + if (id == 30) + { + /* snmpEnableAuthenTraps */ + /* @todo @fixme: which kind of pointer is 'value'? s32_t or u8_t??? */ + u8_t *ptr = (u8_t*)value; + *snmpenableauthentraps_ptr = *ptr; + } +} + +#endif /* LWIP_SNMP */ diff --git a/features/unsupported/net/lwip/lwip/core/snmp/mib_structs.c b/features/unsupported/net/lwip/lwip/core/snmp/mib_structs.c new file mode 100644 index 00000000000..2f185cb4367 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/core/snmp/mib_structs.c @@ -0,0 +1,1174 @@ +/** + * @file + * MIB tree access/construction functions. + */ + +/* + * Copyright (c) 2006 Axon Digital Design B.V., The Netherlands. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * Author: Christiaan Simons + */ + +#include "lwip/opt.h" + +#if LWIP_SNMP /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/snmp_structs.h" +#include "lwip/memp.h" +#include "lwip/netif.h" + +/** .iso.org.dod.internet address prefix, @see snmp_iso_*() */ +const s32_t prefix[4] = {1, 3, 6, 1}; + +#define NODE_STACK_SIZE (LWIP_SNMP_OBJ_ID_LEN) +/** node stack entry (old news?) */ +struct nse +{ + /** right child */ + struct mib_node* r_ptr; + /** right child identifier */ + s32_t r_id; + /** right child next level */ + u8_t r_nl; +}; +static u8_t node_stack_cnt; +static struct nse node_stack[NODE_STACK_SIZE]; + +/** + * Pushes nse struct onto stack. + */ +static void +push_node(struct nse* node) +{ + LWIP_ASSERT("node_stack_cnt < NODE_STACK_SIZE",node_stack_cnt < NODE_STACK_SIZE); + LWIP_DEBUGF(SNMP_MIB_DEBUG,("push_node() node=%p id=%"S32_F"\n",(void*)(node->r_ptr),node->r_id)); + if (node_stack_cnt < NODE_STACK_SIZE) + { + node_stack[node_stack_cnt] = *node; + node_stack_cnt++; + } +} + +/** + * Pops nse struct from stack. + */ +static void +pop_node(struct nse* node) +{ + if (node_stack_cnt > 0) + { + node_stack_cnt--; + *node = node_stack[node_stack_cnt]; + } + LWIP_DEBUGF(SNMP_MIB_DEBUG,("pop_node() node=%p id=%"S32_F"\n",(void *)(node->r_ptr),node->r_id)); +} + +/** + * Conversion from ifIndex to lwIP netif + * @param ifindex is a s32_t object sub-identifier + * @param netif points to returned netif struct pointer + */ +void +snmp_ifindextonetif(s32_t ifindex, struct netif **netif) +{ + struct netif *nif = netif_list; + s32_t i, ifidx; + + ifidx = ifindex - 1; + i = 0; + while ((nif != NULL) && (i < ifidx)) + { + nif = nif->next; + i++; + } + *netif = nif; +} + +/** + * Conversion from lwIP netif to ifIndex + * @param netif points to a netif struct + * @param ifidx points to s32_t object sub-identifier + */ +void +snmp_netiftoifindex(struct netif *netif, s32_t *ifidx) +{ + struct netif *nif = netif_list; + u16_t i; + + i = 0; + while ((nif != NULL) && (nif != netif)) + { + nif = nif->next; + i++; + } + *ifidx = i+1; +} + +/** + * Conversion from oid to lwIP ip_addr + * @param ident points to s32_t ident[4] input + * @param ip points to output struct + */ +void +snmp_oidtoip(s32_t *ident, ip_addr_t *ip) +{ + IP4_ADDR(ip, ident[0], ident[1], ident[2], ident[3]); +} + +/** + * Conversion from lwIP ip_addr to oid + * @param ip points to input struct + * @param ident points to s32_t ident[4] output + */ +void +snmp_iptooid(ip_addr_t *ip, s32_t *ident) +{ + ident[0] = ip4_addr1(ip); + ident[1] = ip4_addr2(ip); + ident[2] = ip4_addr3(ip); + ident[3] = ip4_addr4(ip); +} + +struct mib_list_node * +snmp_mib_ln_alloc(s32_t id) +{ + struct mib_list_node *ln; + + ln = (struct mib_list_node *)memp_malloc(MEMP_SNMP_NODE); + if (ln != NULL) + { + ln->prev = NULL; + ln->next = NULL; + ln->objid = id; + ln->nptr = NULL; + } + return ln; +} + +void +snmp_mib_ln_free(struct mib_list_node *ln) +{ + memp_free(MEMP_SNMP_NODE, ln); +} + +struct mib_list_rootnode * +snmp_mib_lrn_alloc(void) +{ + struct mib_list_rootnode *lrn; + + lrn = (struct mib_list_rootnode*)memp_malloc(MEMP_SNMP_ROOTNODE); + if (lrn != NULL) + { + lrn->get_object_def = noleafs_get_object_def; + lrn->get_value = noleafs_get_value; + lrn->set_test = noleafs_set_test; + lrn->set_value = noleafs_set_value; + lrn->node_type = MIB_NODE_LR; + lrn->maxlength = 0; + lrn->head = NULL; + lrn->tail = NULL; + lrn->count = 0; + } + return lrn; +} + +void +snmp_mib_lrn_free(struct mib_list_rootnode *lrn) +{ + memp_free(MEMP_SNMP_ROOTNODE, lrn); +} + +/** + * Inserts node in idx list in a sorted + * (ascending order) fashion and + * allocates the node if needed. + * + * @param rn points to the root node + * @param objid is the object sub identifier + * @param insn points to a pointer to the inserted node + * used for constructing the tree. + * @return -1 if failed, 1 if inserted, 2 if present. + */ +s8_t +snmp_mib_node_insert(struct mib_list_rootnode *rn, s32_t objid, struct mib_list_node **insn) +{ + struct mib_list_node *nn; + s8_t insert; + + LWIP_ASSERT("rn != NULL",rn != NULL); + + /* -1 = malloc failure, 0 = not inserted, 1 = inserted, 2 = was present */ + insert = 0; + if (rn->head == NULL) + { + /* empty list, add first node */ + LWIP_DEBUGF(SNMP_MIB_DEBUG,("alloc empty list objid==%"S32_F"\n",objid)); + nn = snmp_mib_ln_alloc(objid); + if (nn != NULL) + { + rn->head = nn; + rn->tail = nn; + *insn = nn; + insert = 1; + } + else + { + insert = -1; + } + } + else + { + struct mib_list_node *n; + /* at least one node is present */ + n = rn->head; + while ((n != NULL) && (insert == 0)) + { + if (n->objid == objid) + { + /* node is already there */ + LWIP_DEBUGF(SNMP_MIB_DEBUG,("node already there objid==%"S32_F"\n",objid)); + *insn = n; + insert = 2; + } + else if (n->objid < objid) + { + if (n->next == NULL) + { + /* alloc and insert at the tail */ + LWIP_DEBUGF(SNMP_MIB_DEBUG,("alloc ins tail objid==%"S32_F"\n",objid)); + nn = snmp_mib_ln_alloc(objid); + if (nn != NULL) + { + nn->next = NULL; + nn->prev = n; + n->next = nn; + rn->tail = nn; + *insn = nn; + insert = 1; + } + else + { + /* insertion failure */ + insert = -1; + } + } + else + { + /* there's more to explore: traverse list */ + LWIP_DEBUGF(SNMP_MIB_DEBUG,("traverse list\n")); + n = n->next; + } + } + else + { + /* n->objid > objid */ + /* alloc and insert between n->prev and n */ + LWIP_DEBUGF(SNMP_MIB_DEBUG,("alloc ins n->prev, objid==%"S32_F", n\n",objid)); + nn = snmp_mib_ln_alloc(objid); + if (nn != NULL) + { + if (n->prev == NULL) + { + /* insert at the head */ + nn->next = n; + nn->prev = NULL; + rn->head = nn; + n->prev = nn; + } + else + { + /* insert in the middle */ + nn->next = n; + nn->prev = n->prev; + n->prev->next = nn; + n->prev = nn; + } + *insn = nn; + insert = 1; + } + else + { + /* insertion failure */ + insert = -1; + } + } + } + } + if (insert == 1) + { + rn->count += 1; + } + LWIP_ASSERT("insert != 0",insert != 0); + return insert; +} + +/** + * Finds node in idx list and returns deletion mark. + * + * @param rn points to the root node + * @param objid is the object sub identifier + * @param fn returns pointer to found node + * @return 0 if not found, 1 if deletable, + * 2 can't delete (2 or more children), 3 not a list_node + */ +s8_t +snmp_mib_node_find(struct mib_list_rootnode *rn, s32_t objid, struct mib_list_node **fn) +{ + s8_t fc; + struct mib_list_node *n; + + LWIP_ASSERT("rn != NULL",rn != NULL); + n = rn->head; + while ((n != NULL) && (n->objid != objid)) + { + n = n->next; + } + if (n == NULL) + { + fc = 0; + } + else if (n->nptr == NULL) + { + /* leaf, can delete node */ + fc = 1; + } + else + { + struct mib_list_rootnode *r; + + if (n->nptr->node_type == MIB_NODE_LR) + { + r = (struct mib_list_rootnode *)n->nptr; + if (r->count > 1) + { + /* can't delete node */ + fc = 2; + } + else + { + /* count <= 1, can delete node */ + fc = 1; + } + } + else + { + /* other node type */ + fc = 3; + } + } + *fn = n; + return fc; +} + +/** + * Removes node from idx list + * if it has a single child left. + * + * @param rn points to the root node + * @param n points to the node to delete + * @return the nptr to be freed by caller + */ +struct mib_list_rootnode * +snmp_mib_node_delete(struct mib_list_rootnode *rn, struct mib_list_node *n) +{ + struct mib_list_rootnode *next; + + LWIP_ASSERT("rn != NULL",rn != NULL); + LWIP_ASSERT("n != NULL",n != NULL); + + /* caller must remove this sub-tree */ + next = (struct mib_list_rootnode*)(n->nptr); + rn->count -= 1; + + if (n == rn->head) + { + rn->head = n->next; + if (n->next != NULL) + { + /* not last node, new list begin */ + n->next->prev = NULL; + } + } + else if (n == rn->tail) + { + rn->tail = n->prev; + if (n->prev != NULL) + { + /* not last node, new list end */ + n->prev->next = NULL; + } + } + else + { + /* node must be in the middle */ + n->prev->next = n->next; + n->next->prev = n->prev; + } + LWIP_DEBUGF(SNMP_MIB_DEBUG,("free list objid==%"S32_F"\n",n->objid)); + snmp_mib_ln_free(n); + if (rn->count == 0) + { + rn->head = NULL; + rn->tail = NULL; + } + return next; +} + + + +/** + * Searches tree for the supplied (scalar?) object identifier. + * + * @param node points to the root of the tree ('.internet') + * @param ident_len the length of the supplied object identifier + * @param ident points to the array of sub identifiers + * @param np points to the found object instance (return) + * @return pointer to the requested parent (!) node if success, NULL otherwise + */ +struct mib_node * +snmp_search_tree(struct mib_node *node, u8_t ident_len, s32_t *ident, struct snmp_name_ptr *np) +{ + u8_t node_type, ext_level; + + ext_level = 0; + LWIP_DEBUGF(SNMP_MIB_DEBUG,("node==%p *ident==%"S32_F"\n",(void*)node,*ident)); + while (node != NULL) + { + node_type = node->node_type; + if ((node_type == MIB_NODE_AR) || (node_type == MIB_NODE_RA)) + { + struct mib_array_node *an; + u16_t i; + + if (ident_len > 0) + { + /* array node (internal ROM or RAM, fixed length) */ + an = (struct mib_array_node *)node; + i = 0; + while ((i < an->maxlength) && (an->objid[i] != *ident)) + { + i++; + } + if (i < an->maxlength) + { + /* found it, if available proceed to child, otherwise inspect leaf */ + LWIP_DEBUGF(SNMP_MIB_DEBUG,("an->objid[%"U16_F"]==%"S32_F" *ident==%"S32_F"\n",i,an->objid[i],*ident)); + if (an->nptr[i] == NULL) + { + /* a scalar leaf OR table, + inspect remaining instance number / table index */ + np->ident_len = ident_len; + np->ident = ident; + return (struct mib_node*)an; + } + else + { + /* follow next child pointer */ + ident++; + ident_len--; + node = an->nptr[i]; + } + } + else + { + /* search failed, identifier mismatch (nosuchname) */ + LWIP_DEBUGF(SNMP_MIB_DEBUG,("an search failed *ident==%"S32_F"\n",*ident)); + return NULL; + } + } + else + { + /* search failed, short object identifier (nosuchname) */ + LWIP_DEBUGF(SNMP_MIB_DEBUG,("an search failed, short object identifier\n")); + return NULL; + } + } + else if(node_type == MIB_NODE_LR) + { + struct mib_list_rootnode *lrn; + struct mib_list_node *ln; + + if (ident_len > 0) + { + /* list root node (internal 'RAM', variable length) */ + lrn = (struct mib_list_rootnode *)node; + ln = lrn->head; + /* iterate over list, head to tail */ + while ((ln != NULL) && (ln->objid != *ident)) + { + ln = ln->next; + } + if (ln != NULL) + { + /* found it, proceed to child */; + LWIP_DEBUGF(SNMP_MIB_DEBUG,("ln->objid==%"S32_F" *ident==%"S32_F"\n",ln->objid,*ident)); + if (ln->nptr == NULL) + { + np->ident_len = ident_len; + np->ident = ident; + return (struct mib_node*)lrn; + } + else + { + /* follow next child pointer */ + ident_len--; + ident++; + node = ln->nptr; + } + } + else + { + /* search failed */ + LWIP_DEBUGF(SNMP_MIB_DEBUG,("ln search failed *ident==%"S32_F"\n",*ident)); + return NULL; + } + } + else + { + /* search failed, short object identifier (nosuchname) */ + LWIP_DEBUGF(SNMP_MIB_DEBUG,("ln search failed, short object identifier\n")); + return NULL; + } + } + else if(node_type == MIB_NODE_EX) + { + struct mib_external_node *en; + u16_t i, len; + + if (ident_len > 0) + { + /* external node (addressing and access via functions) */ + en = (struct mib_external_node *)node; + + i = 0; + len = en->level_length(en->addr_inf,ext_level); + while ((i < len) && (en->ident_cmp(en->addr_inf,ext_level,i,*ident) != 0)) + { + i++; + } + if (i < len) + { + s32_t debug_id; + + en->get_objid(en->addr_inf,ext_level,i,&debug_id); + LWIP_DEBUGF(SNMP_MIB_DEBUG,("en->objid==%"S32_F" *ident==%"S32_F"\n",debug_id,*ident)); + if ((ext_level + 1) == en->tree_levels) + { + np->ident_len = ident_len; + np->ident = ident; + return (struct mib_node*)en; + } + else + { + /* found it, proceed to child */ + ident_len--; + ident++; + ext_level++; + } + } + else + { + /* search failed */ + LWIP_DEBUGF(SNMP_MIB_DEBUG,("en search failed *ident==%"S32_F"\n",*ident)); + return NULL; + } + } + else + { + /* search failed, short object identifier (nosuchname) */ + LWIP_DEBUGF(SNMP_MIB_DEBUG,("en search failed, short object identifier\n")); + return NULL; + } + } + else if (node_type == MIB_NODE_SC) + { + mib_scalar_node *sn; + + sn = (mib_scalar_node *)node; + if ((ident_len == 1) && (*ident == 0)) + { + np->ident_len = ident_len; + np->ident = ident; + return (struct mib_node*)sn; + } + else + { + /* search failed, short object identifier (nosuchname) */ + LWIP_DEBUGF(SNMP_MIB_DEBUG,("search failed, invalid object identifier length\n")); + return NULL; + } + } + else + { + /* unknown node_type */ + LWIP_DEBUGF(SNMP_MIB_DEBUG,("search failed node_type %"U16_F" unkown\n",(u16_t)node_type)); + return NULL; + } + } + /* done, found nothing */ + LWIP_DEBUGF(SNMP_MIB_DEBUG,("search failed node==%p\n",(void*)node)); + return NULL; +} + +/** + * Test table for presence of at least one table entry. + */ +static u8_t +empty_table(struct mib_node *node) +{ + u8_t node_type; + u8_t empty = 0; + + if (node != NULL) + { + node_type = node->node_type; + if (node_type == MIB_NODE_LR) + { + struct mib_list_rootnode *lrn; + lrn = (struct mib_list_rootnode *)node; + if ((lrn->count == 0) || (lrn->head == NULL)) + { + empty = 1; + } + } + else if ((node_type == MIB_NODE_AR) || (node_type == MIB_NODE_RA)) + { + struct mib_array_node *an; + an = (struct mib_array_node *)node; + if ((an->maxlength == 0) || (an->nptr == NULL)) + { + empty = 1; + } + } + else if (node_type == MIB_NODE_EX) + { + struct mib_external_node *en; + en = (struct mib_external_node *)node; + if (en->tree_levels == 0) + { + empty = 1; + } + } + } + return empty; +} + +/** + * Tree expansion. + */ +struct mib_node * +snmp_expand_tree(struct mib_node *node, u8_t ident_len, s32_t *ident, struct snmp_obj_id *oidret) +{ + u8_t node_type, ext_level, climb_tree; + + ext_level = 0; + /* reset node stack */ + node_stack_cnt = 0; + while (node != NULL) + { + climb_tree = 0; + node_type = node->node_type; + if ((node_type == MIB_NODE_AR) || (node_type == MIB_NODE_RA)) + { + struct mib_array_node *an; + u16_t i; + + /* array node (internal ROM or RAM, fixed length) */ + an = (struct mib_array_node *)node; + if (ident_len > 0) + { + i = 0; + while ((i < an->maxlength) && (an->objid[i] < *ident)) + { + i++; + } + if (i < an->maxlength) + { + LWIP_DEBUGF(SNMP_MIB_DEBUG,("an->objid[%"U16_F"]==%"S32_F" *ident==%"S32_F"\n",i,an->objid[i],*ident)); + /* add identifier to oidret */ + oidret->id[oidret->len] = an->objid[i]; + (oidret->len)++; + + if (an->nptr[i] == NULL) + { + LWIP_DEBUGF(SNMP_MIB_DEBUG,("leaf node\n")); + /* leaf node (e.g. in a fixed size table) */ + if (an->objid[i] > *ident) + { + return (struct mib_node*)an; + } + else if ((i + 1) < an->maxlength) + { + /* an->objid[i] == *ident */ + (oidret->len)--; + oidret->id[oidret->len] = an->objid[i + 1]; + (oidret->len)++; + return (struct mib_node*)an; + } + else + { + /* (i + 1) == an->maxlength */ + (oidret->len)--; + climb_tree = 1; + } + } + else + { + u8_t j; + struct nse cur_node; + + LWIP_DEBUGF(SNMP_MIB_DEBUG,("non-leaf node\n")); + /* non-leaf, store right child ptr and id */ + LWIP_ASSERT("i < 0xff", i < 0xff); + j = (u8_t)i + 1; + while ((j < an->maxlength) && (empty_table(an->nptr[j]))) + { + j++; + } + if (j < an->maxlength) + { + cur_node.r_ptr = an->nptr[j]; + cur_node.r_id = an->objid[j]; + cur_node.r_nl = 0; + } + else + { + cur_node.r_ptr = NULL; + } + push_node(&cur_node); + if (an->objid[i] == *ident) + { + ident_len--; + ident++; + } + else + { + /* an->objid[i] < *ident */ + ident_len = 0; + } + /* follow next child pointer */ + node = an->nptr[i]; + } + } + else + { + /* i == an->maxlength */ + climb_tree = 1; + } + } + else + { + u8_t j; + /* ident_len == 0, complete with leftmost '.thing' */ + j = 0; + while ((j < an->maxlength) && empty_table(an->nptr[j])) + { + j++; + } + if (j < an->maxlength) + { + LWIP_DEBUGF(SNMP_MIB_DEBUG,("left an->objid[j]==%"S32_F"\n",an->objid[j])); + oidret->id[oidret->len] = an->objid[j]; + (oidret->len)++; + if (an->nptr[j] == NULL) + { + /* leaf node */ + return (struct mib_node*)an; + } + else + { + /* no leaf, continue */ + node = an->nptr[j]; + } + } + else + { + /* j == an->maxlength */ + climb_tree = 1; + } + } + } + else if(node_type == MIB_NODE_LR) + { + struct mib_list_rootnode *lrn; + struct mib_list_node *ln; + + /* list root node (internal 'RAM', variable length) */ + lrn = (struct mib_list_rootnode *)node; + if (ident_len > 0) + { + ln = lrn->head; + /* iterate over list, head to tail */ + while ((ln != NULL) && (ln->objid < *ident)) + { + ln = ln->next; + } + if (ln != NULL) + { + LWIP_DEBUGF(SNMP_MIB_DEBUG,("ln->objid==%"S32_F" *ident==%"S32_F"\n",ln->objid,*ident)); + oidret->id[oidret->len] = ln->objid; + (oidret->len)++; + if (ln->nptr == NULL) + { + /* leaf node */ + if (ln->objid > *ident) + { + return (struct mib_node*)lrn; + } + else if (ln->next != NULL) + { + /* ln->objid == *ident */ + (oidret->len)--; + oidret->id[oidret->len] = ln->next->objid; + (oidret->len)++; + return (struct mib_node*)lrn; + } + else + { + /* ln->next == NULL */ + (oidret->len)--; + climb_tree = 1; + } + } + else + { + struct mib_list_node *jn; + struct nse cur_node; + + /* non-leaf, store right child ptr and id */ + jn = ln->next; + while ((jn != NULL) && empty_table(jn->nptr)) + { + jn = jn->next; + } + if (jn != NULL) + { + cur_node.r_ptr = jn->nptr; + cur_node.r_id = jn->objid; + cur_node.r_nl = 0; + } + else + { + cur_node.r_ptr = NULL; + } + push_node(&cur_node); + if (ln->objid == *ident) + { + ident_len--; + ident++; + } + else + { + /* ln->objid < *ident */ + ident_len = 0; + } + /* follow next child pointer */ + node = ln->nptr; + } + + } + else + { + /* ln == NULL */ + climb_tree = 1; + } + } + else + { + struct mib_list_node *jn; + /* ident_len == 0, complete with leftmost '.thing' */ + jn = lrn->head; + while ((jn != NULL) && empty_table(jn->nptr)) + { + jn = jn->next; + } + if (jn != NULL) + { + LWIP_DEBUGF(SNMP_MIB_DEBUG,("left jn->objid==%"S32_F"\n",jn->objid)); + oidret->id[oidret->len] = jn->objid; + (oidret->len)++; + if (jn->nptr == NULL) + { + /* leaf node */ + LWIP_DEBUGF(SNMP_MIB_DEBUG,("jn->nptr == NULL\n")); + return (struct mib_node*)lrn; + } + else + { + /* no leaf, continue */ + node = jn->nptr; + } + } + else + { + /* jn == NULL */ + climb_tree = 1; + } + } + } + else if(node_type == MIB_NODE_EX) + { + struct mib_external_node *en; + s32_t ex_id; + + /* external node (addressing and access via functions) */ + en = (struct mib_external_node *)node; + if (ident_len > 0) + { + u16_t i, len; + + i = 0; + len = en->level_length(en->addr_inf,ext_level); + while ((i < len) && (en->ident_cmp(en->addr_inf,ext_level,i,*ident) < 0)) + { + i++; + } + if (i < len) + { + /* add identifier to oidret */ + en->get_objid(en->addr_inf,ext_level,i,&ex_id); + LWIP_DEBUGF(SNMP_MIB_DEBUG,("en->objid[%"U16_F"]==%"S32_F" *ident==%"S32_F"\n",i,ex_id,*ident)); + oidret->id[oidret->len] = ex_id; + (oidret->len)++; + + if ((ext_level + 1) == en->tree_levels) + { + LWIP_DEBUGF(SNMP_MIB_DEBUG,("leaf node\n")); + /* leaf node */ + if (ex_id > *ident) + { + return (struct mib_node*)en; + } + else if ((i + 1) < len) + { + /* ex_id == *ident */ + en->get_objid(en->addr_inf,ext_level,i + 1,&ex_id); + (oidret->len)--; + oidret->id[oidret->len] = ex_id; + (oidret->len)++; + return (struct mib_node*)en; + } + else + { + /* (i + 1) == len */ + (oidret->len)--; + climb_tree = 1; + } + } + else + { + u8_t j; + struct nse cur_node; + + LWIP_DEBUGF(SNMP_MIB_DEBUG,("non-leaf node\n")); + /* non-leaf, store right child ptr and id */ + LWIP_ASSERT("i < 0xff", i < 0xff); + j = (u8_t)i + 1; + if (j < len) + { + /* right node is the current external node */ + cur_node.r_ptr = node; + en->get_objid(en->addr_inf,ext_level,j,&cur_node.r_id); + cur_node.r_nl = ext_level + 1; + } + else + { + cur_node.r_ptr = NULL; + } + push_node(&cur_node); + if (en->ident_cmp(en->addr_inf,ext_level,i,*ident) == 0) + { + ident_len--; + ident++; + } + else + { + /* external id < *ident */ + ident_len = 0; + } + /* proceed to child */ + ext_level++; + } + } + else + { + /* i == len (en->level_len()) */ + climb_tree = 1; + } + } + else + { + /* ident_len == 0, complete with leftmost '.thing' */ + en->get_objid(en->addr_inf,ext_level,0,&ex_id); + LWIP_DEBUGF(SNMP_MIB_DEBUG,("left en->objid==%"S32_F"\n",ex_id)); + oidret->id[oidret->len] = ex_id; + (oidret->len)++; + if ((ext_level + 1) == en->tree_levels) + { + /* leaf node */ + LWIP_DEBUGF(SNMP_MIB_DEBUG,("(ext_level + 1) == en->tree_levels\n")); + return (struct mib_node*)en; + } + else + { + /* no leaf, proceed to child */ + ext_level++; + } + } + } + else if(node_type == MIB_NODE_SC) + { + mib_scalar_node *sn; + + /* scalar node */ + sn = (mib_scalar_node *)node; + if (ident_len > 0) + { + /* at .0 */ + climb_tree = 1; + } + else + { + /* ident_len == 0, complete object identifier */ + oidret->id[oidret->len] = 0; + (oidret->len)++; + /* leaf node */ + LWIP_DEBUGF(SNMP_MIB_DEBUG,("completed scalar leaf\n")); + return (struct mib_node*)sn; + } + } + else + { + /* unknown/unhandled node_type */ + LWIP_DEBUGF(SNMP_MIB_DEBUG,("expand failed node_type %"U16_F" unkown\n",(u16_t)node_type)); + return NULL; + } + + if (climb_tree) + { + struct nse child; + + /* find right child ptr */ + child.r_ptr = NULL; + child.r_id = 0; + child.r_nl = 0; + while ((node_stack_cnt > 0) && (child.r_ptr == NULL)) + { + pop_node(&child); + /* trim returned oid */ + (oidret->len)--; + } + if (child.r_ptr != NULL) + { + /* incoming ident is useless beyond this point */ + ident_len = 0; + oidret->id[oidret->len] = child.r_id; + oidret->len++; + node = child.r_ptr; + ext_level = child.r_nl; + } + else + { + /* tree ends here ... */ + LWIP_DEBUGF(SNMP_MIB_DEBUG,("expand failed, tree ends here\n")); + return NULL; + } + } + } + /* done, found nothing */ + LWIP_DEBUGF(SNMP_MIB_DEBUG,("expand failed node==%p\n",(void*)node)); + return NULL; +} + +/** + * Test object identifier for the iso.org.dod.internet prefix. + * + * @param ident_len the length of the supplied object identifier + * @param ident points to the array of sub identifiers + * @return 1 if it matches, 0 otherwise + */ +u8_t +snmp_iso_prefix_tst(u8_t ident_len, s32_t *ident) +{ + if ((ident_len > 3) && + (ident[0] == 1) && (ident[1] == 3) && + (ident[2] == 6) && (ident[3] == 1)) + { + return 1; + } + else + { + return 0; + } +} + +/** + * Expands object identifier to the iso.org.dod.internet + * prefix for use in getnext operation. + * + * @param ident_len the length of the supplied object identifier + * @param ident points to the array of sub identifiers + * @param oidret points to returned expanded object identifier + * @return 1 if it matches, 0 otherwise + * + * @note ident_len 0 is allowed, expanding to the first known object id!! + */ +u8_t +snmp_iso_prefix_expand(u8_t ident_len, s32_t *ident, struct snmp_obj_id *oidret) +{ + const s32_t *prefix_ptr; + s32_t *ret_ptr; + u8_t i; + + i = 0; + prefix_ptr = &prefix[0]; + ret_ptr = &oidret->id[0]; + ident_len = ((ident_len < 4)?ident_len:4); + while ((i < ident_len) && ((*ident) <= (*prefix_ptr))) + { + *ret_ptr++ = *prefix_ptr++; + ident++; + i++; + } + if (i == ident_len) + { + /* match, complete missing bits */ + while (i < 4) + { + *ret_ptr++ = *prefix_ptr++; + i++; + } + oidret->len = i; + return 1; + } + else + { + /* i != ident_len */ + return 0; + } +} + +#endif /* LWIP_SNMP */ diff --git a/features/unsupported/net/lwip/lwip/core/snmp/msg_in.c b/features/unsupported/net/lwip/lwip/core/snmp/msg_in.c new file mode 100644 index 00000000000..2dfb55b253a --- /dev/null +++ b/features/unsupported/net/lwip/lwip/core/snmp/msg_in.c @@ -0,0 +1,1437 @@ +/** + * @file + * SNMP input message processing (RFC1157). + */ + +/* + * Copyright (c) 2006 Axon Digital Design B.V., The Netherlands. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * Author: Christiaan Simons + */ + +#include "lwip/opt.h" + +#if LWIP_SNMP /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/snmp.h" +#include "lwip/snmp_asn1.h" +#include "lwip/snmp_msg.h" +#include "lwip/snmp_structs.h" +#include "lwip/ip_addr.h" +#include "lwip/memp.h" +#include "lwip/udp.h" +#include "lwip/stats.h" + +#include + +/* public (non-static) constants */ +/** SNMP v1 == 0 */ +const s32_t snmp_version = 0; +/** default SNMP community string */ +const char snmp_publiccommunity[7] = "public"; + +/* statically allocated buffers for SNMP_CONCURRENT_REQUESTS */ +struct snmp_msg_pstat msg_input_list[SNMP_CONCURRENT_REQUESTS]; +/* UDP Protocol Control Block */ +struct udp_pcb *snmp1_pcb; + +static void snmp_recv(void *arg, struct udp_pcb *pcb, struct pbuf *p, ip_addr_t *addr, u16_t port); +static err_t snmp_pdu_header_check(struct pbuf *p, u16_t ofs, u16_t pdu_len, u16_t *ofs_ret, struct snmp_msg_pstat *m_stat); +static err_t snmp_pdu_dec_varbindlist(struct pbuf *p, u16_t ofs, u16_t *ofs_ret, struct snmp_msg_pstat *m_stat); + + +/** + * Starts SNMP Agent. + * Allocates UDP pcb and binds it to IP_ADDR_ANY port 161. + */ +void +snmp_init(void) +{ + struct snmp_msg_pstat *msg_ps; + u8_t i; + + snmp1_pcb = udp_new(); + if (snmp1_pcb != NULL) + { + udp_recv(snmp1_pcb, snmp_recv, (void *)SNMP_IN_PORT); + udp_bind(snmp1_pcb, IP_ADDR_ANY, SNMP_IN_PORT); + } + msg_ps = &msg_input_list[0]; + for (i=0; istate = SNMP_MSG_EMPTY; + msg_ps->error_index = 0; + msg_ps->error_status = SNMP_ES_NOERROR; + msg_ps++; + } + trap_msg.pcb = snmp1_pcb; + +#ifdef SNMP_PRIVATE_MIB_INIT + /* If defined, rhis must be a function-like define to initialize the + * private MIB after the stack has been initialized. + * The private MIB can also be initialized in tcpip_callback (or after + * the stack is initialized), this define is only for convenience. */ + SNMP_PRIVATE_MIB_INIT(); +#endif /* SNMP_PRIVATE_MIB_INIT */ + + /* The coldstart trap will only be output + if our outgoing interface is up & configured */ + snmp_coldstart_trap(); +} + +static void +snmp_error_response(struct snmp_msg_pstat *msg_ps, u8_t error) +{ + snmp_varbind_list_free(&msg_ps->outvb); + msg_ps->outvb = msg_ps->invb; + msg_ps->invb.head = NULL; + msg_ps->invb.tail = NULL; + msg_ps->invb.count = 0; + msg_ps->error_status = error; + msg_ps->error_index = 1 + msg_ps->vb_idx; + snmp_send_response(msg_ps); + snmp_varbind_list_free(&msg_ps->outvb); + msg_ps->state = SNMP_MSG_EMPTY; +} + +static void +snmp_ok_response(struct snmp_msg_pstat *msg_ps) +{ + err_t err_ret; + + err_ret = snmp_send_response(msg_ps); + if (err_ret == ERR_MEM) + { + /* serious memory problem, can't return tooBig */ + } + else + { + LWIP_DEBUGF(SNMP_MSG_DEBUG, ("snmp_msg_event = %"S32_F"\n",msg_ps->error_status)); + } + /* free varbinds (if available) */ + snmp_varbind_list_free(&msg_ps->invb); + snmp_varbind_list_free(&msg_ps->outvb); + msg_ps->state = SNMP_MSG_EMPTY; +} + +/** + * Service an internal or external event for SNMP GET. + * + * @param request_id identifies requests from 0 to (SNMP_CONCURRENT_REQUESTS-1) + * @param msg_ps points to the assosicated message process state + */ +static void +snmp_msg_get_event(u8_t request_id, struct snmp_msg_pstat *msg_ps) +{ + LWIP_DEBUGF(SNMP_MSG_DEBUG, ("snmp_msg_get_event: msg_ps->state==%"U16_F"\n",(u16_t)msg_ps->state)); + + if (msg_ps->state == SNMP_MSG_EXTERNAL_GET_OBJDEF) + { + struct mib_external_node *en; + struct snmp_name_ptr np; + + /* get_object_def() answer*/ + en = msg_ps->ext_mib_node; + np = msg_ps->ext_name_ptr; + + /* translate answer into a known lifeform */ + en->get_object_def_a(request_id, np.ident_len, np.ident, &msg_ps->ext_object_def); + if ((msg_ps->ext_object_def.instance != MIB_OBJECT_NONE) && + (msg_ps->ext_object_def.access & MIB_ACCESS_READ)) + { + msg_ps->state = SNMP_MSG_EXTERNAL_GET_VALUE; + en->get_value_q(request_id, &msg_ps->ext_object_def); + } + else + { + en->get_object_def_pc(request_id, np.ident_len, np.ident); + /* search failed, object id points to unknown object (nosuchname) */ + snmp_error_response(msg_ps,SNMP_ES_NOSUCHNAME); + } + } + else if (msg_ps->state == SNMP_MSG_EXTERNAL_GET_VALUE) + { + struct mib_external_node *en; + struct snmp_varbind *vb; + + /* get_value() answer */ + en = msg_ps->ext_mib_node; + + /* allocate output varbind */ + vb = (struct snmp_varbind *)memp_malloc(MEMP_SNMP_VARBIND); + LWIP_ASSERT("vb != NULL",vb != NULL); + if (vb != NULL) + { + vb->next = NULL; + vb->prev = NULL; + + /* move name from invb to outvb */ + vb->ident = msg_ps->vb_ptr->ident; + vb->ident_len = msg_ps->vb_ptr->ident_len; + /* ensure this memory is refereced once only */ + msg_ps->vb_ptr->ident = NULL; + msg_ps->vb_ptr->ident_len = 0; + + vb->value_type = msg_ps->ext_object_def.asn_type; + LWIP_ASSERT("invalid length", msg_ps->ext_object_def.v_len <= 0xff); + vb->value_len = (u8_t)msg_ps->ext_object_def.v_len; + if (vb->value_len > 0) + { + LWIP_ASSERT("SNMP_MAX_OCTET_STRING_LEN is configured too low", vb->value_len <= SNMP_MAX_VALUE_SIZE); + vb->value = memp_malloc(MEMP_SNMP_VALUE); + LWIP_ASSERT("vb->value != NULL",vb->value != NULL); + if (vb->value != NULL) + { + en->get_value_a(request_id, &msg_ps->ext_object_def, vb->value_len, vb->value); + snmp_varbind_tail_add(&msg_ps->outvb, vb); + /* search again (if vb_idx < msg_ps->invb.count) */ + msg_ps->state = SNMP_MSG_SEARCH_OBJ; + msg_ps->vb_idx += 1; + } + else + { + en->get_value_pc(request_id, &msg_ps->ext_object_def); + LWIP_DEBUGF(SNMP_MSG_DEBUG, ("snmp_msg_event: no variable space\n")); + msg_ps->vb_ptr->ident = vb->ident; + msg_ps->vb_ptr->ident_len = vb->ident_len; + memp_free(MEMP_SNMP_VARBIND, vb); + snmp_error_response(msg_ps,SNMP_ES_TOOBIG); + } + } + else + { + /* vb->value_len == 0, empty value (e.g. empty string) */ + en->get_value_a(request_id, &msg_ps->ext_object_def, 0, NULL); + vb->value = NULL; + snmp_varbind_tail_add(&msg_ps->outvb, vb); + /* search again (if vb_idx < msg_ps->invb.count) */ + msg_ps->state = SNMP_MSG_SEARCH_OBJ; + msg_ps->vb_idx += 1; + } + } + else + { + en->get_value_pc(request_id, &msg_ps->ext_object_def); + LWIP_DEBUGF(SNMP_MSG_DEBUG, ("snmp_msg_event: no outvb space\n")); + snmp_error_response(msg_ps,SNMP_ES_TOOBIG); + } + } + + while ((msg_ps->state == SNMP_MSG_SEARCH_OBJ) && + (msg_ps->vb_idx < msg_ps->invb.count)) + { + struct mib_node *mn; + struct snmp_name_ptr np; + + if (msg_ps->vb_idx == 0) + { + msg_ps->vb_ptr = msg_ps->invb.head; + } + else + { + msg_ps->vb_ptr = msg_ps->vb_ptr->next; + } + /** test object identifier for .iso.org.dod.internet prefix */ + if (snmp_iso_prefix_tst(msg_ps->vb_ptr->ident_len, msg_ps->vb_ptr->ident)) + { + mn = snmp_search_tree((struct mib_node*)&internet, msg_ps->vb_ptr->ident_len - 4, + msg_ps->vb_ptr->ident + 4, &np); + if (mn != NULL) + { + if (mn->node_type == MIB_NODE_EX) + { + /* external object */ + struct mib_external_node *en = (struct mib_external_node*)mn; + + msg_ps->state = SNMP_MSG_EXTERNAL_GET_OBJDEF; + /* save en && args in msg_ps!! */ + msg_ps->ext_mib_node = en; + msg_ps->ext_name_ptr = np; + + en->get_object_def_q(en->addr_inf, request_id, np.ident_len, np.ident); + } + else + { + /* internal object */ + struct obj_def object_def; + + msg_ps->state = SNMP_MSG_INTERNAL_GET_OBJDEF; + mn->get_object_def(np.ident_len, np.ident, &object_def); + if ((object_def.instance != MIB_OBJECT_NONE) && + (object_def.access & MIB_ACCESS_READ)) + { + mn = mn; + } + else + { + /* search failed, object id points to unknown object (nosuchname) */ + mn = NULL; + } + if (mn != NULL) + { + struct snmp_varbind *vb; + + msg_ps->state = SNMP_MSG_INTERNAL_GET_VALUE; + /* allocate output varbind */ + vb = (struct snmp_varbind *)memp_malloc(MEMP_SNMP_VARBIND); + LWIP_ASSERT("vb != NULL",vb != NULL); + if (vb != NULL) + { + vb->next = NULL; + vb->prev = NULL; + + /* move name from invb to outvb */ + vb->ident = msg_ps->vb_ptr->ident; + vb->ident_len = msg_ps->vb_ptr->ident_len; + /* ensure this memory is refereced once only */ + msg_ps->vb_ptr->ident = NULL; + msg_ps->vb_ptr->ident_len = 0; + + vb->value_type = object_def.asn_type; + LWIP_ASSERT("invalid length", object_def.v_len <= 0xff); + vb->value_len = (u8_t)object_def.v_len; + if (vb->value_len > 0) + { + LWIP_ASSERT("SNMP_MAX_OCTET_STRING_LEN is configured too low", + vb->value_len <= SNMP_MAX_VALUE_SIZE); + vb->value = memp_malloc(MEMP_SNMP_VALUE); + LWIP_ASSERT("vb->value != NULL",vb->value != NULL); + if (vb->value != NULL) + { + mn->get_value(&object_def, vb->value_len, vb->value); + snmp_varbind_tail_add(&msg_ps->outvb, vb); + msg_ps->state = SNMP_MSG_SEARCH_OBJ; + msg_ps->vb_idx += 1; + } + else + { + LWIP_DEBUGF(SNMP_MSG_DEBUG, ("snmp_msg_event: couldn't allocate variable space\n")); + msg_ps->vb_ptr->ident = vb->ident; + msg_ps->vb_ptr->ident_len = vb->ident_len; + memp_free(MEMP_SNMP_VARBIND, vb); + snmp_error_response(msg_ps,SNMP_ES_TOOBIG); + } + } + else + { + /* vb->value_len == 0, empty value (e.g. empty string) */ + vb->value = NULL; + snmp_varbind_tail_add(&msg_ps->outvb, vb); + msg_ps->state = SNMP_MSG_SEARCH_OBJ; + msg_ps->vb_idx += 1; + } + } + else + { + LWIP_DEBUGF(SNMP_MSG_DEBUG, ("snmp_msg_event: couldn't allocate outvb space\n")); + snmp_error_response(msg_ps,SNMP_ES_TOOBIG); + } + } + } + } + } + else + { + mn = NULL; + } + if (mn == NULL) + { + /* mn == NULL, noSuchName */ + snmp_error_response(msg_ps,SNMP_ES_NOSUCHNAME); + } + } + if ((msg_ps->state == SNMP_MSG_SEARCH_OBJ) && + (msg_ps->vb_idx == msg_ps->invb.count)) + { + snmp_ok_response(msg_ps); + } +} + +/** + * Service an internal or external event for SNMP GETNEXT. + * + * @param request_id identifies requests from 0 to (SNMP_CONCURRENT_REQUESTS-1) + * @param msg_ps points to the assosicated message process state + */ +static void +snmp_msg_getnext_event(u8_t request_id, struct snmp_msg_pstat *msg_ps) +{ + LWIP_DEBUGF(SNMP_MSG_DEBUG, ("snmp_msg_getnext_event: msg_ps->state==%"U16_F"\n",(u16_t)msg_ps->state)); + + if (msg_ps->state == SNMP_MSG_EXTERNAL_GET_OBJDEF) + { + struct mib_external_node *en; + + /* get_object_def() answer*/ + en = msg_ps->ext_mib_node; + + /* translate answer into a known lifeform */ + en->get_object_def_a(request_id, 1, &msg_ps->ext_oid.id[msg_ps->ext_oid.len - 1], &msg_ps->ext_object_def); + if (msg_ps->ext_object_def.instance != MIB_OBJECT_NONE) + { + msg_ps->state = SNMP_MSG_EXTERNAL_GET_VALUE; + en->get_value_q(request_id, &msg_ps->ext_object_def); + } + else + { + en->get_object_def_pc(request_id, 1, &msg_ps->ext_oid.id[msg_ps->ext_oid.len - 1]); + /* search failed, object id points to unknown object (nosuchname) */ + snmp_error_response(msg_ps,SNMP_ES_NOSUCHNAME); + } + } + else if (msg_ps->state == SNMP_MSG_EXTERNAL_GET_VALUE) + { + struct mib_external_node *en; + struct snmp_varbind *vb; + + /* get_value() answer */ + en = msg_ps->ext_mib_node; + + LWIP_ASSERT("invalid length", msg_ps->ext_object_def.v_len <= 0xff); + vb = snmp_varbind_alloc(&msg_ps->ext_oid, + msg_ps->ext_object_def.asn_type, + (u8_t)msg_ps->ext_object_def.v_len); + if (vb != NULL) + { + en->get_value_a(request_id, &msg_ps->ext_object_def, vb->value_len, vb->value); + snmp_varbind_tail_add(&msg_ps->outvb, vb); + msg_ps->state = SNMP_MSG_SEARCH_OBJ; + msg_ps->vb_idx += 1; + } + else + { + en->get_value_pc(request_id, &msg_ps->ext_object_def); + LWIP_DEBUGF(SNMP_MSG_DEBUG, ("snmp_msg_getnext_event: couldn't allocate outvb space\n")); + snmp_error_response(msg_ps,SNMP_ES_TOOBIG); + } + } + + while ((msg_ps->state == SNMP_MSG_SEARCH_OBJ) && + (msg_ps->vb_idx < msg_ps->invb.count)) + { + struct mib_node *mn; + struct snmp_obj_id oid; + + if (msg_ps->vb_idx == 0) + { + msg_ps->vb_ptr = msg_ps->invb.head; + } + else + { + msg_ps->vb_ptr = msg_ps->vb_ptr->next; + } + if (snmp_iso_prefix_expand(msg_ps->vb_ptr->ident_len, msg_ps->vb_ptr->ident, &oid)) + { + if (msg_ps->vb_ptr->ident_len > 3) + { + /* can offset ident_len and ident */ + mn = snmp_expand_tree((struct mib_node*)&internet, + msg_ps->vb_ptr->ident_len - 4, + msg_ps->vb_ptr->ident + 4, &oid); + } + else + { + /* can't offset ident_len -4, ident + 4 */ + mn = snmp_expand_tree((struct mib_node*)&internet, 0, NULL, &oid); + } + } + else + { + mn = NULL; + } + if (mn != NULL) + { + if (mn->node_type == MIB_NODE_EX) + { + /* external object */ + struct mib_external_node *en = (struct mib_external_node*)mn; + + msg_ps->state = SNMP_MSG_EXTERNAL_GET_OBJDEF; + /* save en && args in msg_ps!! */ + msg_ps->ext_mib_node = en; + msg_ps->ext_oid = oid; + + en->get_object_def_q(en->addr_inf, request_id, 1, &oid.id[oid.len - 1]); + } + else + { + /* internal object */ + struct obj_def object_def; + struct snmp_varbind *vb; + + msg_ps->state = SNMP_MSG_INTERNAL_GET_OBJDEF; + mn->get_object_def(1, &oid.id[oid.len - 1], &object_def); + + LWIP_ASSERT("invalid length", object_def.v_len <= 0xff); + vb = snmp_varbind_alloc(&oid, object_def.asn_type, (u8_t)object_def.v_len); + if (vb != NULL) + { + msg_ps->state = SNMP_MSG_INTERNAL_GET_VALUE; + mn->get_value(&object_def, object_def.v_len, vb->value); + snmp_varbind_tail_add(&msg_ps->outvb, vb); + msg_ps->state = SNMP_MSG_SEARCH_OBJ; + msg_ps->vb_idx += 1; + } + else + { + LWIP_DEBUGF(SNMP_MSG_DEBUG, ("snmp_recv couldn't allocate outvb space\n")); + snmp_error_response(msg_ps,SNMP_ES_TOOBIG); + } + } + } + if (mn == NULL) + { + /* mn == NULL, noSuchName */ + snmp_error_response(msg_ps,SNMP_ES_NOSUCHNAME); + } + } + if ((msg_ps->state == SNMP_MSG_SEARCH_OBJ) && + (msg_ps->vb_idx == msg_ps->invb.count)) + { + snmp_ok_response(msg_ps); + } +} + +/** + * Service an internal or external event for SNMP SET. + * + * @param request_id identifies requests from 0 to (SNMP_CONCURRENT_REQUESTS-1) + * @param msg_ps points to the assosicated message process state + */ +static void +snmp_msg_set_event(u8_t request_id, struct snmp_msg_pstat *msg_ps) +{ + LWIP_DEBUGF(SNMP_MSG_DEBUG, ("snmp_msg_set_event: msg_ps->state==%"U16_F"\n",(u16_t)msg_ps->state)); + + if (msg_ps->state == SNMP_MSG_EXTERNAL_GET_OBJDEF) + { + struct mib_external_node *en; + struct snmp_name_ptr np; + + /* get_object_def() answer*/ + en = msg_ps->ext_mib_node; + np = msg_ps->ext_name_ptr; + + /* translate answer into a known lifeform */ + en->get_object_def_a(request_id, np.ident_len, np.ident, &msg_ps->ext_object_def); + if (msg_ps->ext_object_def.instance != MIB_OBJECT_NONE) + { + msg_ps->state = SNMP_MSG_EXTERNAL_SET_TEST; + en->set_test_q(request_id, &msg_ps->ext_object_def); + } + else + { + en->get_object_def_pc(request_id, np.ident_len, np.ident); + /* search failed, object id points to unknown object (nosuchname) */ + snmp_error_response(msg_ps,SNMP_ES_NOSUCHNAME); + } + } + else if (msg_ps->state == SNMP_MSG_EXTERNAL_SET_TEST) + { + struct mib_external_node *en; + + /* set_test() answer*/ + en = msg_ps->ext_mib_node; + + if (msg_ps->ext_object_def.access & MIB_ACCESS_WRITE) + { + if ((msg_ps->ext_object_def.asn_type == msg_ps->vb_ptr->value_type) && + (en->set_test_a(request_id,&msg_ps->ext_object_def, + msg_ps->vb_ptr->value_len,msg_ps->vb_ptr->value) != 0)) + { + msg_ps->state = SNMP_MSG_SEARCH_OBJ; + msg_ps->vb_idx += 1; + } + else + { + en->set_test_pc(request_id,&msg_ps->ext_object_def); + /* bad value */ + snmp_error_response(msg_ps,SNMP_ES_BADVALUE); + } + } + else + { + en->set_test_pc(request_id,&msg_ps->ext_object_def); + /* object not available for set */ + snmp_error_response(msg_ps,SNMP_ES_NOSUCHNAME); + } + } + else if (msg_ps->state == SNMP_MSG_EXTERNAL_GET_OBJDEF_S) + { + struct mib_external_node *en; + struct snmp_name_ptr np; + + /* get_object_def() answer*/ + en = msg_ps->ext_mib_node; + np = msg_ps->ext_name_ptr; + + /* translate answer into a known lifeform */ + en->get_object_def_a(request_id, np.ident_len, np.ident, &msg_ps->ext_object_def); + if (msg_ps->ext_object_def.instance != MIB_OBJECT_NONE) + { + msg_ps->state = SNMP_MSG_EXTERNAL_SET_VALUE; + en->set_value_q(request_id, &msg_ps->ext_object_def, + msg_ps->vb_ptr->value_len,msg_ps->vb_ptr->value); + } + else + { + en->get_object_def_pc(request_id, np.ident_len, np.ident); + /* set_value failed, object has disappeared for some odd reason?? */ + snmp_error_response(msg_ps,SNMP_ES_GENERROR); + } + } + else if (msg_ps->state == SNMP_MSG_EXTERNAL_SET_VALUE) + { + struct mib_external_node *en; + + /** set_value_a() */ + en = msg_ps->ext_mib_node; + en->set_value_a(request_id, &msg_ps->ext_object_def, + msg_ps->vb_ptr->value_len, msg_ps->vb_ptr->value); + + /** @todo use set_value_pc() if toobig */ + msg_ps->state = SNMP_MSG_INTERNAL_SET_VALUE; + msg_ps->vb_idx += 1; + } + + /* test all values before setting */ + while ((msg_ps->state == SNMP_MSG_SEARCH_OBJ) && + (msg_ps->vb_idx < msg_ps->invb.count)) + { + struct mib_node *mn; + struct snmp_name_ptr np; + + if (msg_ps->vb_idx == 0) + { + msg_ps->vb_ptr = msg_ps->invb.head; + } + else + { + msg_ps->vb_ptr = msg_ps->vb_ptr->next; + } + /** test object identifier for .iso.org.dod.internet prefix */ + if (snmp_iso_prefix_tst(msg_ps->vb_ptr->ident_len, msg_ps->vb_ptr->ident)) + { + mn = snmp_search_tree((struct mib_node*)&internet, msg_ps->vb_ptr->ident_len - 4, + msg_ps->vb_ptr->ident + 4, &np); + if (mn != NULL) + { + if (mn->node_type == MIB_NODE_EX) + { + /* external object */ + struct mib_external_node *en = (struct mib_external_node*)mn; + + msg_ps->state = SNMP_MSG_EXTERNAL_GET_OBJDEF; + /* save en && args in msg_ps!! */ + msg_ps->ext_mib_node = en; + msg_ps->ext_name_ptr = np; + + en->get_object_def_q(en->addr_inf, request_id, np.ident_len, np.ident); + } + else + { + /* internal object */ + struct obj_def object_def; + + msg_ps->state = SNMP_MSG_INTERNAL_GET_OBJDEF; + mn->get_object_def(np.ident_len, np.ident, &object_def); + if (object_def.instance != MIB_OBJECT_NONE) + { + mn = mn; + } + else + { + /* search failed, object id points to unknown object (nosuchname) */ + mn = NULL; + } + if (mn != NULL) + { + msg_ps->state = SNMP_MSG_INTERNAL_SET_TEST; + + if (object_def.access & MIB_ACCESS_WRITE) + { + if ((object_def.asn_type == msg_ps->vb_ptr->value_type) && + (mn->set_test(&object_def,msg_ps->vb_ptr->value_len,msg_ps->vb_ptr->value) != 0)) + { + msg_ps->state = SNMP_MSG_SEARCH_OBJ; + msg_ps->vb_idx += 1; + } + else + { + /* bad value */ + snmp_error_response(msg_ps,SNMP_ES_BADVALUE); + } + } + else + { + /* object not available for set */ + snmp_error_response(msg_ps,SNMP_ES_NOSUCHNAME); + } + } + } + } + } + else + { + mn = NULL; + } + if (mn == NULL) + { + /* mn == NULL, noSuchName */ + snmp_error_response(msg_ps,SNMP_ES_NOSUCHNAME); + } + } + + if ((msg_ps->state == SNMP_MSG_SEARCH_OBJ) && + (msg_ps->vb_idx == msg_ps->invb.count)) + { + msg_ps->vb_idx = 0; + msg_ps->state = SNMP_MSG_INTERNAL_SET_VALUE; + } + + /* set all values "atomically" (be as "atomic" as possible) */ + while ((msg_ps->state == SNMP_MSG_INTERNAL_SET_VALUE) && + (msg_ps->vb_idx < msg_ps->invb.count)) + { + struct mib_node *mn; + struct snmp_name_ptr np; + + if (msg_ps->vb_idx == 0) + { + msg_ps->vb_ptr = msg_ps->invb.head; + } + else + { + msg_ps->vb_ptr = msg_ps->vb_ptr->next; + } + /* skip iso prefix test, was done previously while settesting() */ + mn = snmp_search_tree((struct mib_node*)&internet, msg_ps->vb_ptr->ident_len - 4, + msg_ps->vb_ptr->ident + 4, &np); + /* check if object is still available + (e.g. external hot-plug thingy present?) */ + if (mn != NULL) + { + if (mn->node_type == MIB_NODE_EX) + { + /* external object */ + struct mib_external_node *en = (struct mib_external_node*)mn; + + msg_ps->state = SNMP_MSG_EXTERNAL_GET_OBJDEF_S; + /* save en && args in msg_ps!! */ + msg_ps->ext_mib_node = en; + msg_ps->ext_name_ptr = np; + + en->get_object_def_q(en->addr_inf, request_id, np.ident_len, np.ident); + } + else + { + /* internal object */ + struct obj_def object_def; + + msg_ps->state = SNMP_MSG_INTERNAL_GET_OBJDEF_S; + mn->get_object_def(np.ident_len, np.ident, &object_def); + msg_ps->state = SNMP_MSG_INTERNAL_SET_VALUE; + mn->set_value(&object_def,msg_ps->vb_ptr->value_len,msg_ps->vb_ptr->value); + msg_ps->vb_idx += 1; + } + } + } + if ((msg_ps->state == SNMP_MSG_INTERNAL_SET_VALUE) && + (msg_ps->vb_idx == msg_ps->invb.count)) + { + /* simply echo the input if we can set it + @todo do we need to return the actual value? + e.g. if value is silently modified or behaves sticky? */ + msg_ps->outvb = msg_ps->invb; + msg_ps->invb.head = NULL; + msg_ps->invb.tail = NULL; + msg_ps->invb.count = 0; + snmp_ok_response(msg_ps); + } +} + + +/** + * Handle one internal or external event. + * Called for one async event. (recv external/private answer) + * + * @param request_id identifies requests from 0 to (SNMP_CONCURRENT_REQUESTS-1) + */ +void +snmp_msg_event(u8_t request_id) +{ + struct snmp_msg_pstat *msg_ps; + + if (request_id < SNMP_CONCURRENT_REQUESTS) + { + msg_ps = &msg_input_list[request_id]; + if (msg_ps->rt == SNMP_ASN1_PDU_GET_NEXT_REQ) + { + snmp_msg_getnext_event(request_id, msg_ps); + } + else if (msg_ps->rt == SNMP_ASN1_PDU_GET_REQ) + { + snmp_msg_get_event(request_id, msg_ps); + } + else if(msg_ps->rt == SNMP_ASN1_PDU_SET_REQ) + { + snmp_msg_set_event(request_id, msg_ps); + } + } +} + + +/* lwIP UDP receive callback function */ +static void +snmp_recv(void *arg, struct udp_pcb *pcb, struct pbuf *p, ip_addr_t *addr, u16_t port) +{ + struct snmp_msg_pstat *msg_ps; + u8_t req_idx; + err_t err_ret; + u16_t payload_len = p->tot_len; + u16_t payload_ofs = 0; + u16_t varbind_ofs = 0; + + /* suppress unused argument warning */ + LWIP_UNUSED_ARG(arg); + + /* traverse input message process list, look for SNMP_MSG_EMPTY */ + msg_ps = &msg_input_list[0]; + req_idx = 0; + while ((req_idx < SNMP_CONCURRENT_REQUESTS) && (msg_ps->state != SNMP_MSG_EMPTY)) + { + req_idx++; + msg_ps++; + } + if (req_idx == SNMP_CONCURRENT_REQUESTS) + { + /* exceeding number of concurrent requests */ + pbuf_free(p); + return; + } + + /* accepting request */ + snmp_inc_snmpinpkts(); + /* record used 'protocol control block' */ + msg_ps->pcb = pcb; + /* source address (network order) */ + msg_ps->sip = *addr; + /* source port (host order (lwIP oddity)) */ + msg_ps->sp = port; + + /* check total length, version, community, pdu type */ + err_ret = snmp_pdu_header_check(p, payload_ofs, payload_len, &varbind_ofs, msg_ps); + /* Only accept requests and requests without error (be robust) */ + /* Reject response and trap headers or error requests as input! */ + if ((err_ret != ERR_OK) || + ((msg_ps->rt != SNMP_ASN1_PDU_GET_REQ) && + (msg_ps->rt != SNMP_ASN1_PDU_GET_NEXT_REQ) && + (msg_ps->rt != SNMP_ASN1_PDU_SET_REQ)) || + ((msg_ps->error_status != SNMP_ES_NOERROR) || + (msg_ps->error_index != 0)) ) + { + /* header check failed drop request silently, do not return error! */ + pbuf_free(p); + LWIP_DEBUGF(SNMP_MSG_DEBUG, ("snmp_pdu_header_check() failed\n")); + return; + } + LWIP_DEBUGF(SNMP_MSG_DEBUG, ("snmp_recv ok, community %s\n", msg_ps->community)); + + /* Builds a list of variable bindings. Copy the varbinds from the pbuf + chain to glue them when these are divided over two or more pbuf's. */ + err_ret = snmp_pdu_dec_varbindlist(p, varbind_ofs, &varbind_ofs, msg_ps); + /* we've decoded the incoming message, release input msg now */ + pbuf_free(p); + if ((err_ret != ERR_OK) || (msg_ps->invb.count == 0)) + { + /* varbind-list decode failed, or varbind list empty. + drop request silently, do not return error! + (errors are only returned for a specific varbind failure) */ + LWIP_DEBUGF(SNMP_MSG_DEBUG, ("snmp_pdu_dec_varbindlist() failed\n")); + return; + } + + msg_ps->error_status = SNMP_ES_NOERROR; + msg_ps->error_index = 0; + /* find object for each variable binding */ + msg_ps->state = SNMP_MSG_SEARCH_OBJ; + /* first variable binding from list to inspect */ + msg_ps->vb_idx = 0; + + LWIP_DEBUGF(SNMP_MSG_DEBUG, ("snmp_recv varbind cnt=%"U16_F"\n",(u16_t)msg_ps->invb.count)); + + /* handle input event and as much objects as possible in one go */ + snmp_msg_event(req_idx); +} + +/** + * Checks and decodes incoming SNMP message header, logs header errors. + * + * @param p points to pbuf chain of SNMP message (UDP payload) + * @param ofs points to first octet of SNMP message + * @param pdu_len the length of the UDP payload + * @param ofs_ret returns the ofset of the variable bindings + * @param m_stat points to the current message request state return + * @return + * - ERR_OK SNMP header is sane and accepted + * - ERR_ARG SNMP header is either malformed or rejected + */ +static err_t +snmp_pdu_header_check(struct pbuf *p, u16_t ofs, u16_t pdu_len, u16_t *ofs_ret, struct snmp_msg_pstat *m_stat) +{ + err_t derr; + u16_t len, ofs_base; + u8_t len_octets; + u8_t type; + s32_t version; + + ofs_base = ofs; + snmp_asn1_dec_type(p, ofs, &type); + derr = snmp_asn1_dec_length(p, ofs+1, &len_octets, &len); + if ((derr != ERR_OK) || + (pdu_len != (1 + len_octets + len)) || + (type != (SNMP_ASN1_UNIV | SNMP_ASN1_CONSTR | SNMP_ASN1_SEQ))) + { + snmp_inc_snmpinasnparseerrs(); + return ERR_ARG; + } + ofs += (1 + len_octets); + snmp_asn1_dec_type(p, ofs, &type); + derr = snmp_asn1_dec_length(p, ofs+1, &len_octets, &len); + if ((derr != ERR_OK) || (type != (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_INTEG))) + { + /* can't decode or no integer (version) */ + snmp_inc_snmpinasnparseerrs(); + return ERR_ARG; + } + derr = snmp_asn1_dec_s32t(p, ofs + 1 + len_octets, len, &version); + if (derr != ERR_OK) + { + /* can't decode */ + snmp_inc_snmpinasnparseerrs(); + return ERR_ARG; + } + if (version != 0) + { + /* not version 1 */ + snmp_inc_snmpinbadversions(); + return ERR_ARG; + } + ofs += (1 + len_octets + len); + snmp_asn1_dec_type(p, ofs, &type); + derr = snmp_asn1_dec_length(p, ofs+1, &len_octets, &len); + if ((derr != ERR_OK) || (type != (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_OC_STR))) + { + /* can't decode or no octet string (community) */ + snmp_inc_snmpinasnparseerrs(); + return ERR_ARG; + } + derr = snmp_asn1_dec_raw(p, ofs + 1 + len_octets, len, SNMP_COMMUNITY_STR_LEN, m_stat->community); + if (derr != ERR_OK) + { + snmp_inc_snmpinasnparseerrs(); + return ERR_ARG; + } + /* add zero terminator */ + len = ((len < (SNMP_COMMUNITY_STR_LEN))?(len):(SNMP_COMMUNITY_STR_LEN)); + m_stat->community[len] = 0; + m_stat->com_strlen = (u8_t)len; + if (strncmp(snmp_publiccommunity, (const char*)m_stat->community, SNMP_COMMUNITY_STR_LEN) != 0) + { + /** @todo: move this if we need to check more names */ + snmp_inc_snmpinbadcommunitynames(); + snmp_authfail_trap(); + return ERR_ARG; + } + ofs += (1 + len_octets + len); + snmp_asn1_dec_type(p, ofs, &type); + derr = snmp_asn1_dec_length(p, ofs+1, &len_octets, &len); + if (derr != ERR_OK) + { + snmp_inc_snmpinasnparseerrs(); + return ERR_ARG; + } + switch(type) + { + case (SNMP_ASN1_CONTXT | SNMP_ASN1_CONSTR | SNMP_ASN1_PDU_GET_REQ): + /* GetRequest PDU */ + snmp_inc_snmpingetrequests(); + derr = ERR_OK; + break; + case (SNMP_ASN1_CONTXT | SNMP_ASN1_CONSTR | SNMP_ASN1_PDU_GET_NEXT_REQ): + /* GetNextRequest PDU */ + snmp_inc_snmpingetnexts(); + derr = ERR_OK; + break; + case (SNMP_ASN1_CONTXT | SNMP_ASN1_CONSTR | SNMP_ASN1_PDU_GET_RESP): + /* GetResponse PDU */ + snmp_inc_snmpingetresponses(); + derr = ERR_ARG; + break; + case (SNMP_ASN1_CONTXT | SNMP_ASN1_CONSTR | SNMP_ASN1_PDU_SET_REQ): + /* SetRequest PDU */ + snmp_inc_snmpinsetrequests(); + derr = ERR_OK; + break; + case (SNMP_ASN1_CONTXT | SNMP_ASN1_CONSTR | SNMP_ASN1_PDU_TRAP): + /* Trap PDU */ + snmp_inc_snmpintraps(); + derr = ERR_ARG; + break; + default: + snmp_inc_snmpinasnparseerrs(); + derr = ERR_ARG; + break; + } + if (derr != ERR_OK) + { + /* unsupported input PDU for this agent (no parse error) */ + return ERR_ARG; + } + m_stat->rt = type & 0x1F; + ofs += (1 + len_octets); + if (len != (pdu_len - (ofs - ofs_base))) + { + /* decoded PDU length does not equal actual payload length */ + snmp_inc_snmpinasnparseerrs(); + return ERR_ARG; + } + snmp_asn1_dec_type(p, ofs, &type); + derr = snmp_asn1_dec_length(p, ofs+1, &len_octets, &len); + if ((derr != ERR_OK) || (type != (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_INTEG))) + { + /* can't decode or no integer (request ID) */ + snmp_inc_snmpinasnparseerrs(); + return ERR_ARG; + } + derr = snmp_asn1_dec_s32t(p, ofs + 1 + len_octets, len, &m_stat->rid); + if (derr != ERR_OK) + { + /* can't decode */ + snmp_inc_snmpinasnparseerrs(); + return ERR_ARG; + } + ofs += (1 + len_octets + len); + snmp_asn1_dec_type(p, ofs, &type); + derr = snmp_asn1_dec_length(p, ofs+1, &len_octets, &len); + if ((derr != ERR_OK) || (type != (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_INTEG))) + { + /* can't decode or no integer (error-status) */ + snmp_inc_snmpinasnparseerrs(); + return ERR_ARG; + } + /* must be noError (0) for incoming requests. + log errors for mib-2 completeness and for debug purposes */ + derr = snmp_asn1_dec_s32t(p, ofs + 1 + len_octets, len, &m_stat->error_status); + if (derr != ERR_OK) + { + /* can't decode */ + snmp_inc_snmpinasnparseerrs(); + return ERR_ARG; + } + switch (m_stat->error_status) + { + case SNMP_ES_TOOBIG: + snmp_inc_snmpintoobigs(); + break; + case SNMP_ES_NOSUCHNAME: + snmp_inc_snmpinnosuchnames(); + break; + case SNMP_ES_BADVALUE: + snmp_inc_snmpinbadvalues(); + break; + case SNMP_ES_READONLY: + snmp_inc_snmpinreadonlys(); + break; + case SNMP_ES_GENERROR: + snmp_inc_snmpingenerrs(); + break; + } + ofs += (1 + len_octets + len); + snmp_asn1_dec_type(p, ofs, &type); + derr = snmp_asn1_dec_length(p, ofs+1, &len_octets, &len); + if ((derr != ERR_OK) || (type != (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_INTEG))) + { + /* can't decode or no integer (error-index) */ + snmp_inc_snmpinasnparseerrs(); + return ERR_ARG; + } + /* must be 0 for incoming requests. + decode anyway to catch bad integers (and dirty tricks) */ + derr = snmp_asn1_dec_s32t(p, ofs + 1 + len_octets, len, &m_stat->error_index); + if (derr != ERR_OK) + { + /* can't decode */ + snmp_inc_snmpinasnparseerrs(); + return ERR_ARG; + } + ofs += (1 + len_octets + len); + *ofs_ret = ofs; + return ERR_OK; +} + +static err_t +snmp_pdu_dec_varbindlist(struct pbuf *p, u16_t ofs, u16_t *ofs_ret, struct snmp_msg_pstat *m_stat) +{ + err_t derr; + u16_t len, vb_len; + u8_t len_octets; + u8_t type; + + /* variable binding list */ + snmp_asn1_dec_type(p, ofs, &type); + derr = snmp_asn1_dec_length(p, ofs+1, &len_octets, &vb_len); + if ((derr != ERR_OK) || + (type != (SNMP_ASN1_UNIV | SNMP_ASN1_CONSTR | SNMP_ASN1_SEQ))) + { + snmp_inc_snmpinasnparseerrs(); + return ERR_ARG; + } + ofs += (1 + len_octets); + + /* start with empty list */ + m_stat->invb.count = 0; + m_stat->invb.head = NULL; + m_stat->invb.tail = NULL; + + while (vb_len > 0) + { + struct snmp_obj_id oid, oid_value; + struct snmp_varbind *vb; + + snmp_asn1_dec_type(p, ofs, &type); + derr = snmp_asn1_dec_length(p, ofs+1, &len_octets, &len); + if ((derr != ERR_OK) || + (type != (SNMP_ASN1_UNIV | SNMP_ASN1_CONSTR | SNMP_ASN1_SEQ)) || + (len == 0) || (len > vb_len)) + { + snmp_inc_snmpinasnparseerrs(); + /* free varbinds (if available) */ + snmp_varbind_list_free(&m_stat->invb); + return ERR_ARG; + } + ofs += (1 + len_octets); + vb_len -= (1 + len_octets); + + snmp_asn1_dec_type(p, ofs, &type); + derr = snmp_asn1_dec_length(p, ofs+1, &len_octets, &len); + if ((derr != ERR_OK) || (type != (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_OBJ_ID))) + { + /* can't decode object name length */ + snmp_inc_snmpinasnparseerrs(); + /* free varbinds (if available) */ + snmp_varbind_list_free(&m_stat->invb); + return ERR_ARG; + } + derr = snmp_asn1_dec_oid(p, ofs + 1 + len_octets, len, &oid); + if (derr != ERR_OK) + { + /* can't decode object name */ + snmp_inc_snmpinasnparseerrs(); + /* free varbinds (if available) */ + snmp_varbind_list_free(&m_stat->invb); + return ERR_ARG; + } + ofs += (1 + len_octets + len); + vb_len -= (1 + len_octets + len); + + snmp_asn1_dec_type(p, ofs, &type); + derr = snmp_asn1_dec_length(p, ofs+1, &len_octets, &len); + if (derr != ERR_OK) + { + /* can't decode object value length */ + snmp_inc_snmpinasnparseerrs(); + /* free varbinds (if available) */ + snmp_varbind_list_free(&m_stat->invb); + return ERR_ARG; + } + + switch (type) + { + case (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_INTEG): + vb = snmp_varbind_alloc(&oid, type, sizeof(s32_t)); + if (vb != NULL) + { + s32_t *vptr = (s32_t*)vb->value; + + derr = snmp_asn1_dec_s32t(p, ofs + 1 + len_octets, len, vptr); + snmp_varbind_tail_add(&m_stat->invb, vb); + } + else + { + derr = ERR_ARG; + } + break; + case (SNMP_ASN1_APPLIC | SNMP_ASN1_PRIMIT | SNMP_ASN1_COUNTER): + case (SNMP_ASN1_APPLIC | SNMP_ASN1_PRIMIT | SNMP_ASN1_GAUGE): + case (SNMP_ASN1_APPLIC | SNMP_ASN1_PRIMIT | SNMP_ASN1_TIMETICKS): + vb = snmp_varbind_alloc(&oid, type, sizeof(u32_t)); + if (vb != NULL) + { + u32_t *vptr = (u32_t*)vb->value; + + derr = snmp_asn1_dec_u32t(p, ofs + 1 + len_octets, len, vptr); + snmp_varbind_tail_add(&m_stat->invb, vb); + } + else + { + derr = ERR_ARG; + } + break; + case (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_OC_STR): + case (SNMP_ASN1_APPLIC | SNMP_ASN1_PRIMIT | SNMP_ASN1_OPAQUE): + LWIP_ASSERT("invalid length", len <= 0xff); + vb = snmp_varbind_alloc(&oid, type, (u8_t)len); + if (vb != NULL) + { + derr = snmp_asn1_dec_raw(p, ofs + 1 + len_octets, len, vb->value_len, (u8_t*)vb->value); + snmp_varbind_tail_add(&m_stat->invb, vb); + } + else + { + derr = ERR_ARG; + } + break; + case (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_NUL): + vb = snmp_varbind_alloc(&oid, type, 0); + if (vb != NULL) + { + snmp_varbind_tail_add(&m_stat->invb, vb); + derr = ERR_OK; + } + else + { + derr = ERR_ARG; + } + break; + case (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_OBJ_ID): + derr = snmp_asn1_dec_oid(p, ofs + 1 + len_octets, len, &oid_value); + if (derr == ERR_OK) + { + vb = snmp_varbind_alloc(&oid, type, oid_value.len * sizeof(s32_t)); + if (vb != NULL) + { + u8_t i = oid_value.len; + s32_t *vptr = (s32_t*)vb->value; + + while(i > 0) + { + i--; + vptr[i] = oid_value.id[i]; + } + snmp_varbind_tail_add(&m_stat->invb, vb); + derr = ERR_OK; + } + else + { + derr = ERR_ARG; + } + } + break; + case (SNMP_ASN1_APPLIC | SNMP_ASN1_PRIMIT | SNMP_ASN1_IPADDR): + if (len == 4) + { + /* must be exactly 4 octets! */ + vb = snmp_varbind_alloc(&oid, type, 4); + if (vb != NULL) + { + derr = snmp_asn1_dec_raw(p, ofs + 1 + len_octets, len, vb->value_len, (u8_t*)vb->value); + snmp_varbind_tail_add(&m_stat->invb, vb); + } + else + { + derr = ERR_ARG; + } + } + else + { + derr = ERR_ARG; + } + break; + default: + derr = ERR_ARG; + break; + } + if (derr != ERR_OK) + { + snmp_inc_snmpinasnparseerrs(); + /* free varbinds (if available) */ + snmp_varbind_list_free(&m_stat->invb); + return ERR_ARG; + } + ofs += (1 + len_octets + len); + vb_len -= (1 + len_octets + len); + } + + if (m_stat->rt == SNMP_ASN1_PDU_SET_REQ) + { + snmp_add_snmpintotalsetvars(m_stat->invb.count); + } + else + { + snmp_add_snmpintotalreqvars(m_stat->invb.count); + } + + *ofs_ret = ofs; + return ERR_OK; +} + +struct snmp_varbind* +snmp_varbind_alloc(struct snmp_obj_id *oid, u8_t type, u8_t len) +{ + struct snmp_varbind *vb; + + vb = (struct snmp_varbind *)memp_malloc(MEMP_SNMP_VARBIND); + LWIP_ASSERT("vb != NULL",vb != NULL); + if (vb != NULL) + { + u8_t i; + + vb->next = NULL; + vb->prev = NULL; + i = oid->len; + vb->ident_len = i; + if (i > 0) + { + LWIP_ASSERT("SNMP_MAX_TREE_DEPTH is configured too low", i <= SNMP_MAX_TREE_DEPTH); + /* allocate array of s32_t for our object identifier */ + vb->ident = (s32_t*)memp_malloc(MEMP_SNMP_VALUE); + LWIP_ASSERT("vb->ident != NULL",vb->ident != NULL); + if (vb->ident == NULL) + { + memp_free(MEMP_SNMP_VARBIND, vb); + return NULL; + } + while(i > 0) + { + i--; + vb->ident[i] = oid->id[i]; + } + } + else + { + /* i == 0, pass zero length object identifier */ + vb->ident = NULL; + } + vb->value_type = type; + vb->value_len = len; + if (len > 0) + { + LWIP_ASSERT("SNMP_MAX_OCTET_STRING_LEN is configured too low", vb->value_len <= SNMP_MAX_VALUE_SIZE); + /* allocate raw bytes for our object value */ + vb->value = memp_malloc(MEMP_SNMP_VALUE); + LWIP_ASSERT("vb->value != NULL",vb->value != NULL); + if (vb->value == NULL) + { + if (vb->ident != NULL) + { + memp_free(MEMP_SNMP_VALUE, vb->ident); + } + memp_free(MEMP_SNMP_VARBIND, vb); + return NULL; + } + } + else + { + /* ASN1_NUL type, or zero length ASN1_OC_STR */ + vb->value = NULL; + } + } + return vb; +} + +void +snmp_varbind_free(struct snmp_varbind *vb) +{ + if (vb->value != NULL ) + { + memp_free(MEMP_SNMP_VALUE, vb->value); + } + if (vb->ident != NULL ) + { + memp_free(MEMP_SNMP_VALUE, vb->ident); + } + memp_free(MEMP_SNMP_VARBIND, vb); +} + +void +snmp_varbind_list_free(struct snmp_varbind_root *root) +{ + struct snmp_varbind *vb, *prev; + + vb = root->tail; + while ( vb != NULL ) + { + prev = vb->prev; + snmp_varbind_free(vb); + vb = prev; + } + root->count = 0; + root->head = NULL; + root->tail = NULL; +} + +void +snmp_varbind_tail_add(struct snmp_varbind_root *root, struct snmp_varbind *vb) +{ + if (root->count == 0) + { + /* add first varbind to list */ + root->head = vb; + root->tail = vb; + } + else + { + /* add nth varbind to list tail */ + root->tail->next = vb; + vb->prev = root->tail; + root->tail = vb; + } + root->count += 1; +} + +struct snmp_varbind* +snmp_varbind_tail_remove(struct snmp_varbind_root *root) +{ + struct snmp_varbind* vb; + + if (root->count > 0) + { + /* remove tail varbind */ + vb = root->tail; + root->tail = vb->prev; + vb->prev->next = NULL; + root->count -= 1; + } + else + { + /* nothing to remove */ + vb = NULL; + } + return vb; +} + +#endif /* LWIP_SNMP */ diff --git a/features/unsupported/net/lwip/lwip/core/snmp/msg_out.c b/features/unsupported/net/lwip/lwip/core/snmp/msg_out.c new file mode 100644 index 00000000000..4778bee6f41 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/core/snmp/msg_out.c @@ -0,0 +1,681 @@ +/** + * @file + * SNMP output message processing (RFC1157). + * + * Output responses and traps are build in two passes: + * + * Pass 0: iterate over the output message backwards to determine encoding lengths + * Pass 1: the actual forward encoding of internal form into ASN1 + * + * The single-pass encoding method described by Comer & Stevens + * requires extra buffer space and copying for reversal of the packet. + * The buffer requirement can be prohibitively large for big payloads + * (>= 484) therefore we use the two encoding passes. + */ + +/* + * Copyright (c) 2006 Axon Digital Design B.V., The Netherlands. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * Author: Christiaan Simons + */ + +#include "lwip/opt.h" + +#if LWIP_SNMP /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/udp.h" +#include "lwip/netif.h" +#include "lwip/snmp.h" +#include "lwip/snmp_asn1.h" +#include "lwip/snmp_msg.h" + +struct snmp_trap_dst +{ + /* destination IP address in network order */ + ip_addr_t dip; + /* set to 0 when disabled, >0 when enabled */ + u8_t enable; +}; +struct snmp_trap_dst trap_dst[SNMP_TRAP_DESTINATIONS]; + +/** TRAP message structure */ +struct snmp_msg_trap trap_msg; + +static u16_t snmp_resp_header_sum(struct snmp_msg_pstat *m_stat, u16_t vb_len); +static u16_t snmp_trap_header_sum(struct snmp_msg_trap *m_trap, u16_t vb_len); +static u16_t snmp_varbind_list_sum(struct snmp_varbind_root *root); + +static u16_t snmp_resp_header_enc(struct snmp_msg_pstat *m_stat, struct pbuf *p); +static u16_t snmp_trap_header_enc(struct snmp_msg_trap *m_trap, struct pbuf *p); +static u16_t snmp_varbind_list_enc(struct snmp_varbind_root *root, struct pbuf *p, u16_t ofs); + +/** + * Sets enable switch for this trap destination. + * @param dst_idx index in 0 .. SNMP_TRAP_DESTINATIONS-1 + * @param enable switch if 0 destination is disabled >0 enabled. + */ +void +snmp_trap_dst_enable(u8_t dst_idx, u8_t enable) +{ + if (dst_idx < SNMP_TRAP_DESTINATIONS) + { + trap_dst[dst_idx].enable = enable; + } +} + +/** + * Sets IPv4 address for this trap destination. + * @param dst_idx index in 0 .. SNMP_TRAP_DESTINATIONS-1 + * @param dst IPv4 address in host order. + */ +void +snmp_trap_dst_ip_set(u8_t dst_idx, ip_addr_t *dst) +{ + if (dst_idx < SNMP_TRAP_DESTINATIONS) + { + ip_addr_set(&trap_dst[dst_idx].dip, dst); + } +} + +/** + * Sends a 'getresponse' message to the request originator. + * + * @param m_stat points to the current message request state source + * @return ERR_OK when success, ERR_MEM if we're out of memory + * + * @note the caller is responsible for filling in outvb in the m_stat + * and provide error-status and index (except for tooBig errors) ... + */ +err_t +snmp_send_response(struct snmp_msg_pstat *m_stat) +{ + struct snmp_varbind_root emptyvb = {NULL, NULL, 0, 0, 0}; + struct pbuf *p; + u16_t tot_len; + err_t err; + + /* pass 0, calculate length fields */ + tot_len = snmp_varbind_list_sum(&m_stat->outvb); + tot_len = snmp_resp_header_sum(m_stat, tot_len); + + /* try allocating pbuf(s) for complete response */ + p = pbuf_alloc(PBUF_TRANSPORT, tot_len, PBUF_POOL); + if (p == NULL) + { + LWIP_DEBUGF(SNMP_MSG_DEBUG, ("snmp_snd_response() tooBig\n")); + + /* can't construct reply, return error-status tooBig */ + m_stat->error_status = SNMP_ES_TOOBIG; + m_stat->error_index = 0; + /* pass 0, recalculate lengths, for empty varbind-list */ + tot_len = snmp_varbind_list_sum(&emptyvb); + tot_len = snmp_resp_header_sum(m_stat, tot_len); + /* retry allocation once for header and empty varbind-list */ + p = pbuf_alloc(PBUF_TRANSPORT, tot_len, PBUF_POOL); + } + if (p != NULL) + { + /* first pbuf alloc try or retry alloc success */ + u16_t ofs; + + LWIP_DEBUGF(SNMP_MSG_DEBUG, ("snmp_snd_response() p != NULL\n")); + + /* pass 1, size error, encode packet ino the pbuf(s) */ + ofs = snmp_resp_header_enc(m_stat, p); + if (m_stat->error_status == SNMP_ES_TOOBIG) + { + snmp_varbind_list_enc(&emptyvb, p, ofs); + } + else + { + snmp_varbind_list_enc(&m_stat->outvb, p, ofs); + } + + switch (m_stat->error_status) + { + case SNMP_ES_TOOBIG: + snmp_inc_snmpouttoobigs(); + break; + case SNMP_ES_NOSUCHNAME: + snmp_inc_snmpoutnosuchnames(); + break; + case SNMP_ES_BADVALUE: + snmp_inc_snmpoutbadvalues(); + break; + case SNMP_ES_GENERROR: + snmp_inc_snmpoutgenerrs(); + break; + } + snmp_inc_snmpoutgetresponses(); + snmp_inc_snmpoutpkts(); + + /** @todo do we need separate rx and tx pcbs for threaded case? */ + /** connect to the originating source */ + udp_connect(m_stat->pcb, &m_stat->sip, m_stat->sp); + err = udp_send(m_stat->pcb, p); + if (err == ERR_MEM) + { + /** @todo release some memory, retry and return tooBig? tooMuchHassle? */ + err = ERR_MEM; + } + else + { + err = ERR_OK; + } + /** disassociate remote address and port with this pcb */ + udp_disconnect(m_stat->pcb); + + pbuf_free(p); + LWIP_DEBUGF(SNMP_MSG_DEBUG, ("snmp_snd_response() done\n")); + return err; + } + else + { + /* first pbuf alloc try or retry alloc failed + very low on memory, couldn't return tooBig */ + return ERR_MEM; + } +} + + +/** + * Sends an generic or enterprise specific trap message. + * + * @param generic_trap is the trap code + * @param eoid points to enterprise object identifier + * @param specific_trap used for enterprise traps when generic_trap == 6 + * @return ERR_OK when success, ERR_MEM if we're out of memory + * + * @note the caller is responsible for filling in outvb in the trap_msg + * @note the use of the enterpise identifier field + * is per RFC1215. + * Use .iso.org.dod.internet.mgmt.mib-2.snmp for generic traps + * and .iso.org.dod.internet.private.enterprises.yourenterprise + * (sysObjectID) for specific traps. + */ +err_t +snmp_send_trap(s8_t generic_trap, struct snmp_obj_id *eoid, s32_t specific_trap) +{ + struct snmp_trap_dst *td; + struct netif *dst_if; + ip_addr_t dst_ip; + struct pbuf *p; + u16_t i,tot_len; + + for (i=0, td = &trap_dst[0]; ienable != 0) && !ip_addr_isany(&td->dip)) + { + /* network order trap destination */ + ip_addr_copy(trap_msg.dip, td->dip); + /* lookup current source address for this dst */ + dst_if = ip_route(&td->dip); + ip_addr_copy(dst_ip, dst_if->ip_addr); + /* @todo: what about IPv6? */ + trap_msg.sip_raw[0] = ip4_addr1(&dst_ip); + trap_msg.sip_raw[1] = ip4_addr2(&dst_ip); + trap_msg.sip_raw[2] = ip4_addr3(&dst_ip); + trap_msg.sip_raw[3] = ip4_addr4(&dst_ip); + trap_msg.gen_trap = generic_trap; + trap_msg.spc_trap = specific_trap; + if (generic_trap == SNMP_GENTRAP_ENTERPRISESPC) + { + /* enterprise-Specific trap */ + trap_msg.enterprise = eoid; + } + else + { + /* generic (MIB-II) trap */ + snmp_get_snmpgrpid_ptr(&trap_msg.enterprise); + } + snmp_get_sysuptime(&trap_msg.ts); + + /* pass 0, calculate length fields */ + tot_len = snmp_varbind_list_sum(&trap_msg.outvb); + tot_len = snmp_trap_header_sum(&trap_msg, tot_len); + + /* allocate pbuf(s) */ + p = pbuf_alloc(PBUF_TRANSPORT, tot_len, PBUF_POOL); + if (p != NULL) + { + u16_t ofs; + + /* pass 1, encode packet ino the pbuf(s) */ + ofs = snmp_trap_header_enc(&trap_msg, p); + snmp_varbind_list_enc(&trap_msg.outvb, p, ofs); + + snmp_inc_snmpouttraps(); + snmp_inc_snmpoutpkts(); + + /** send to the TRAP destination */ + udp_sendto(trap_msg.pcb, p, &trap_msg.dip, SNMP_TRAP_PORT); + + pbuf_free(p); + } + else + { + return ERR_MEM; + } + } + } + return ERR_OK; +} + +void +snmp_coldstart_trap(void) +{ + trap_msg.outvb.head = NULL; + trap_msg.outvb.tail = NULL; + trap_msg.outvb.count = 0; + snmp_send_trap(SNMP_GENTRAP_COLDSTART, NULL, 0); +} + +void +snmp_authfail_trap(void) +{ + u8_t enable; + snmp_get_snmpenableauthentraps(&enable); + if (enable == 1) + { + trap_msg.outvb.head = NULL; + trap_msg.outvb.tail = NULL; + trap_msg.outvb.count = 0; + snmp_send_trap(SNMP_GENTRAP_AUTHFAIL, NULL, 0); + } +} + +/** + * Sums response header field lengths from tail to head and + * returns resp_header_lengths for second encoding pass. + * + * @param vb_len varbind-list length + * @param rhl points to returned header lengths + * @return the required lenght for encoding the response header + */ +static u16_t +snmp_resp_header_sum(struct snmp_msg_pstat *m_stat, u16_t vb_len) +{ + u16_t tot_len; + struct snmp_resp_header_lengths *rhl; + + rhl = &m_stat->rhl; + tot_len = vb_len; + snmp_asn1_enc_s32t_cnt(m_stat->error_index, &rhl->erridxlen); + snmp_asn1_enc_length_cnt(rhl->erridxlen, &rhl->erridxlenlen); + tot_len += 1 + rhl->erridxlenlen + rhl->erridxlen; + + snmp_asn1_enc_s32t_cnt(m_stat->error_status, &rhl->errstatlen); + snmp_asn1_enc_length_cnt(rhl->errstatlen, &rhl->errstatlenlen); + tot_len += 1 + rhl->errstatlenlen + rhl->errstatlen; + + snmp_asn1_enc_s32t_cnt(m_stat->rid, &rhl->ridlen); + snmp_asn1_enc_length_cnt(rhl->ridlen, &rhl->ridlenlen); + tot_len += 1 + rhl->ridlenlen + rhl->ridlen; + + rhl->pdulen = tot_len; + snmp_asn1_enc_length_cnt(rhl->pdulen, &rhl->pdulenlen); + tot_len += 1 + rhl->pdulenlen; + + rhl->comlen = m_stat->com_strlen; + snmp_asn1_enc_length_cnt(rhl->comlen, &rhl->comlenlen); + tot_len += 1 + rhl->comlenlen + rhl->comlen; + + snmp_asn1_enc_s32t_cnt(snmp_version, &rhl->verlen); + snmp_asn1_enc_length_cnt(rhl->verlen, &rhl->verlenlen); + tot_len += 1 + rhl->verlen + rhl->verlenlen; + + rhl->seqlen = tot_len; + snmp_asn1_enc_length_cnt(rhl->seqlen, &rhl->seqlenlen); + tot_len += 1 + rhl->seqlenlen; + + return tot_len; +} + +/** + * Sums trap header field lengths from tail to head and + * returns trap_header_lengths for second encoding pass. + * + * @param vb_len varbind-list length + * @param thl points to returned header lengths + * @return the required lenght for encoding the trap header + */ +static u16_t +snmp_trap_header_sum(struct snmp_msg_trap *m_trap, u16_t vb_len) +{ + u16_t tot_len; + struct snmp_trap_header_lengths *thl; + + thl = &m_trap->thl; + tot_len = vb_len; + + snmp_asn1_enc_u32t_cnt(m_trap->ts, &thl->tslen); + snmp_asn1_enc_length_cnt(thl->tslen, &thl->tslenlen); + tot_len += 1 + thl->tslen + thl->tslenlen; + + snmp_asn1_enc_s32t_cnt(m_trap->spc_trap, &thl->strplen); + snmp_asn1_enc_length_cnt(thl->strplen, &thl->strplenlen); + tot_len += 1 + thl->strplen + thl->strplenlen; + + snmp_asn1_enc_s32t_cnt(m_trap->gen_trap, &thl->gtrplen); + snmp_asn1_enc_length_cnt(thl->gtrplen, &thl->gtrplenlen); + tot_len += 1 + thl->gtrplen + thl->gtrplenlen; + + thl->aaddrlen = 4; + snmp_asn1_enc_length_cnt(thl->aaddrlen, &thl->aaddrlenlen); + tot_len += 1 + thl->aaddrlen + thl->aaddrlenlen; + + snmp_asn1_enc_oid_cnt(m_trap->enterprise->len, &m_trap->enterprise->id[0], &thl->eidlen); + snmp_asn1_enc_length_cnt(thl->eidlen, &thl->eidlenlen); + tot_len += 1 + thl->eidlen + thl->eidlenlen; + + thl->pdulen = tot_len; + snmp_asn1_enc_length_cnt(thl->pdulen, &thl->pdulenlen); + tot_len += 1 + thl->pdulenlen; + + thl->comlen = sizeof(snmp_publiccommunity) - 1; + snmp_asn1_enc_length_cnt(thl->comlen, &thl->comlenlen); + tot_len += 1 + thl->comlenlen + thl->comlen; + + snmp_asn1_enc_s32t_cnt(snmp_version, &thl->verlen); + snmp_asn1_enc_length_cnt(thl->verlen, &thl->verlenlen); + tot_len += 1 + thl->verlen + thl->verlenlen; + + thl->seqlen = tot_len; + snmp_asn1_enc_length_cnt(thl->seqlen, &thl->seqlenlen); + tot_len += 1 + thl->seqlenlen; + + return tot_len; +} + +/** + * Sums varbind lengths from tail to head and + * annotates lengths in varbind for second encoding pass. + * + * @param root points to the root of the variable binding list + * @return the required lenght for encoding the variable bindings + */ +static u16_t +snmp_varbind_list_sum(struct snmp_varbind_root *root) +{ + struct snmp_varbind *vb; + u32_t *uint_ptr; + s32_t *sint_ptr; + u16_t tot_len; + + tot_len = 0; + vb = root->tail; + while ( vb != NULL ) + { + /* encoded value lenght depends on type */ + switch (vb->value_type) + { + case (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_INTEG): + sint_ptr = (s32_t*)vb->value; + snmp_asn1_enc_s32t_cnt(*sint_ptr, &vb->vlen); + break; + case (SNMP_ASN1_APPLIC | SNMP_ASN1_PRIMIT | SNMP_ASN1_COUNTER): + case (SNMP_ASN1_APPLIC | SNMP_ASN1_PRIMIT | SNMP_ASN1_GAUGE): + case (SNMP_ASN1_APPLIC | SNMP_ASN1_PRIMIT | SNMP_ASN1_TIMETICKS): + uint_ptr = (u32_t*)vb->value; + snmp_asn1_enc_u32t_cnt(*uint_ptr, &vb->vlen); + break; + case (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_OC_STR): + case (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_NUL): + case (SNMP_ASN1_APPLIC | SNMP_ASN1_PRIMIT | SNMP_ASN1_IPADDR): + case (SNMP_ASN1_APPLIC | SNMP_ASN1_PRIMIT | SNMP_ASN1_OPAQUE): + vb->vlen = vb->value_len; + break; + case (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_OBJ_ID): + sint_ptr = (s32_t*)vb->value; + snmp_asn1_enc_oid_cnt(vb->value_len / sizeof(s32_t), sint_ptr, &vb->vlen); + break; + default: + /* unsupported type */ + vb->vlen = 0; + break; + }; + /* encoding length of value length field */ + snmp_asn1_enc_length_cnt(vb->vlen, &vb->vlenlen); + snmp_asn1_enc_oid_cnt(vb->ident_len, vb->ident, &vb->olen); + snmp_asn1_enc_length_cnt(vb->olen, &vb->olenlen); + + vb->seqlen = 1 + vb->vlenlen + vb->vlen; + vb->seqlen += 1 + vb->olenlen + vb->olen; + snmp_asn1_enc_length_cnt(vb->seqlen, &vb->seqlenlen); + + /* varbind seq */ + tot_len += 1 + vb->seqlenlen + vb->seqlen; + + vb = vb->prev; + } + + /* varbind-list seq */ + root->seqlen = tot_len; + snmp_asn1_enc_length_cnt(root->seqlen, &root->seqlenlen); + tot_len += 1 + root->seqlenlen; + + return tot_len; +} + +/** + * Encodes response header from head to tail. + */ +static u16_t +snmp_resp_header_enc(struct snmp_msg_pstat *m_stat, struct pbuf *p) +{ + u16_t ofs; + + ofs = 0; + snmp_asn1_enc_type(p, ofs, (SNMP_ASN1_UNIV | SNMP_ASN1_CONSTR | SNMP_ASN1_SEQ)); + ofs += 1; + snmp_asn1_enc_length(p, ofs, m_stat->rhl.seqlen); + ofs += m_stat->rhl.seqlenlen; + + snmp_asn1_enc_type(p, ofs, (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_INTEG)); + ofs += 1; + snmp_asn1_enc_length(p, ofs, m_stat->rhl.verlen); + ofs += m_stat->rhl.verlenlen; + snmp_asn1_enc_s32t(p, ofs, m_stat->rhl.verlen, snmp_version); + ofs += m_stat->rhl.verlen; + + snmp_asn1_enc_type(p, ofs, (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_OC_STR)); + ofs += 1; + snmp_asn1_enc_length(p, ofs, m_stat->rhl.comlen); + ofs += m_stat->rhl.comlenlen; + snmp_asn1_enc_raw(p, ofs, m_stat->rhl.comlen, m_stat->community); + ofs += m_stat->rhl.comlen; + + snmp_asn1_enc_type(p, ofs, (SNMP_ASN1_CONTXT | SNMP_ASN1_CONSTR | SNMP_ASN1_PDU_GET_RESP)); + ofs += 1; + snmp_asn1_enc_length(p, ofs, m_stat->rhl.pdulen); + ofs += m_stat->rhl.pdulenlen; + + snmp_asn1_enc_type(p, ofs, (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_INTEG)); + ofs += 1; + snmp_asn1_enc_length(p, ofs, m_stat->rhl.ridlen); + ofs += m_stat->rhl.ridlenlen; + snmp_asn1_enc_s32t(p, ofs, m_stat->rhl.ridlen, m_stat->rid); + ofs += m_stat->rhl.ridlen; + + snmp_asn1_enc_type(p, ofs, (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_INTEG)); + ofs += 1; + snmp_asn1_enc_length(p, ofs, m_stat->rhl.errstatlen); + ofs += m_stat->rhl.errstatlenlen; + snmp_asn1_enc_s32t(p, ofs, m_stat->rhl.errstatlen, m_stat->error_status); + ofs += m_stat->rhl.errstatlen; + + snmp_asn1_enc_type(p, ofs, (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_INTEG)); + ofs += 1; + snmp_asn1_enc_length(p, ofs, m_stat->rhl.erridxlen); + ofs += m_stat->rhl.erridxlenlen; + snmp_asn1_enc_s32t(p, ofs, m_stat->rhl.erridxlen, m_stat->error_index); + ofs += m_stat->rhl.erridxlen; + + return ofs; +} + +/** + * Encodes trap header from head to tail. + */ +static u16_t +snmp_trap_header_enc(struct snmp_msg_trap *m_trap, struct pbuf *p) +{ + u16_t ofs; + + ofs = 0; + snmp_asn1_enc_type(p, ofs, (SNMP_ASN1_UNIV | SNMP_ASN1_CONSTR | SNMP_ASN1_SEQ)); + ofs += 1; + snmp_asn1_enc_length(p, ofs, m_trap->thl.seqlen); + ofs += m_trap->thl.seqlenlen; + + snmp_asn1_enc_type(p, ofs, (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_INTEG)); + ofs += 1; + snmp_asn1_enc_length(p, ofs, m_trap->thl.verlen); + ofs += m_trap->thl.verlenlen; + snmp_asn1_enc_s32t(p, ofs, m_trap->thl.verlen, snmp_version); + ofs += m_trap->thl.verlen; + + snmp_asn1_enc_type(p, ofs, (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_OC_STR)); + ofs += 1; + snmp_asn1_enc_length(p, ofs, m_trap->thl.comlen); + ofs += m_trap->thl.comlenlen; + snmp_asn1_enc_raw(p, ofs, m_trap->thl.comlen, (u8_t *)&snmp_publiccommunity[0]); + ofs += m_trap->thl.comlen; + + snmp_asn1_enc_type(p, ofs, (SNMP_ASN1_CONTXT | SNMP_ASN1_CONSTR | SNMP_ASN1_PDU_TRAP)); + ofs += 1; + snmp_asn1_enc_length(p, ofs, m_trap->thl.pdulen); + ofs += m_trap->thl.pdulenlen; + + snmp_asn1_enc_type(p, ofs, (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_OBJ_ID)); + ofs += 1; + snmp_asn1_enc_length(p, ofs, m_trap->thl.eidlen); + ofs += m_trap->thl.eidlenlen; + snmp_asn1_enc_oid(p, ofs, m_trap->enterprise->len, &m_trap->enterprise->id[0]); + ofs += m_trap->thl.eidlen; + + snmp_asn1_enc_type(p, ofs, (SNMP_ASN1_APPLIC | SNMP_ASN1_PRIMIT | SNMP_ASN1_IPADDR)); + ofs += 1; + snmp_asn1_enc_length(p, ofs, m_trap->thl.aaddrlen); + ofs += m_trap->thl.aaddrlenlen; + snmp_asn1_enc_raw(p, ofs, m_trap->thl.aaddrlen, &m_trap->sip_raw[0]); + ofs += m_trap->thl.aaddrlen; + + snmp_asn1_enc_type(p, ofs, (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_INTEG)); + ofs += 1; + snmp_asn1_enc_length(p, ofs, m_trap->thl.gtrplen); + ofs += m_trap->thl.gtrplenlen; + snmp_asn1_enc_u32t(p, ofs, m_trap->thl.gtrplen, m_trap->gen_trap); + ofs += m_trap->thl.gtrplen; + + snmp_asn1_enc_type(p, ofs, (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_INTEG)); + ofs += 1; + snmp_asn1_enc_length(p, ofs, m_trap->thl.strplen); + ofs += m_trap->thl.strplenlen; + snmp_asn1_enc_u32t(p, ofs, m_trap->thl.strplen, m_trap->spc_trap); + ofs += m_trap->thl.strplen; + + snmp_asn1_enc_type(p, ofs, (SNMP_ASN1_APPLIC | SNMP_ASN1_PRIMIT | SNMP_ASN1_TIMETICKS)); + ofs += 1; + snmp_asn1_enc_length(p, ofs, m_trap->thl.tslen); + ofs += m_trap->thl.tslenlen; + snmp_asn1_enc_u32t(p, ofs, m_trap->thl.tslen, m_trap->ts); + ofs += m_trap->thl.tslen; + + return ofs; +} + +/** + * Encodes varbind list from head to tail. + */ +static u16_t +snmp_varbind_list_enc(struct snmp_varbind_root *root, struct pbuf *p, u16_t ofs) +{ + struct snmp_varbind *vb; + s32_t *sint_ptr; + u32_t *uint_ptr; + u8_t *raw_ptr; + + snmp_asn1_enc_type(p, ofs, (SNMP_ASN1_UNIV | SNMP_ASN1_CONSTR | SNMP_ASN1_SEQ)); + ofs += 1; + snmp_asn1_enc_length(p, ofs, root->seqlen); + ofs += root->seqlenlen; + + vb = root->head; + while ( vb != NULL ) + { + snmp_asn1_enc_type(p, ofs, (SNMP_ASN1_UNIV | SNMP_ASN1_CONSTR | SNMP_ASN1_SEQ)); + ofs += 1; + snmp_asn1_enc_length(p, ofs, vb->seqlen); + ofs += vb->seqlenlen; + + snmp_asn1_enc_type(p, ofs, (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_OBJ_ID)); + ofs += 1; + snmp_asn1_enc_length(p, ofs, vb->olen); + ofs += vb->olenlen; + snmp_asn1_enc_oid(p, ofs, vb->ident_len, &vb->ident[0]); + ofs += vb->olen; + + snmp_asn1_enc_type(p, ofs, vb->value_type); + ofs += 1; + snmp_asn1_enc_length(p, ofs, vb->vlen); + ofs += vb->vlenlen; + + switch (vb->value_type) + { + case (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_INTEG): + sint_ptr = (s32_t*)vb->value; + snmp_asn1_enc_s32t(p, ofs, vb->vlen, *sint_ptr); + break; + case (SNMP_ASN1_APPLIC | SNMP_ASN1_PRIMIT | SNMP_ASN1_COUNTER): + case (SNMP_ASN1_APPLIC | SNMP_ASN1_PRIMIT | SNMP_ASN1_GAUGE): + case (SNMP_ASN1_APPLIC | SNMP_ASN1_PRIMIT | SNMP_ASN1_TIMETICKS): + uint_ptr = (u32_t*)vb->value; + snmp_asn1_enc_u32t(p, ofs, vb->vlen, *uint_ptr); + break; + case (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_OC_STR): + case (SNMP_ASN1_APPLIC | SNMP_ASN1_PRIMIT | SNMP_ASN1_IPADDR): + case (SNMP_ASN1_APPLIC | SNMP_ASN1_PRIMIT | SNMP_ASN1_OPAQUE): + raw_ptr = (u8_t*)vb->value; + snmp_asn1_enc_raw(p, ofs, vb->vlen, raw_ptr); + break; + case (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_NUL): + break; + case (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_OBJ_ID): + sint_ptr = (s32_t*)vb->value; + snmp_asn1_enc_oid(p, ofs, vb->value_len / sizeof(s32_t), sint_ptr); + break; + default: + /* unsupported type */ + break; + }; + ofs += vb->vlen; + vb = vb->next; + } + return ofs; +} + +#endif /* LWIP_SNMP */ diff --git a/features/unsupported/net/lwip/lwip/core/stats.c b/features/unsupported/net/lwip/lwip/core/stats.c new file mode 100644 index 00000000000..69f97d41fca --- /dev/null +++ b/features/unsupported/net/lwip/lwip/core/stats.c @@ -0,0 +1,176 @@ +/** + * @file + * Statistics module + * + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ + +#include "lwip/opt.h" + +#if LWIP_STATS /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/def.h" +#include "lwip/stats.h" +#include "lwip/mem.h" + +#include + +struct stats_ lwip_stats; + +void stats_init(void) +{ +#ifdef LWIP_DEBUG +#if MEMP_STATS + const char * memp_names[] = { +#define LWIP_MEMPOOL(name,num,size,desc) desc, +#include "lwip/memp_std.h" + }; + int i; + for (i = 0; i < MEMP_MAX; i++) { + lwip_stats.memp[i].name = memp_names[i]; + } +#endif /* MEMP_STATS */ +#if MEM_STATS + lwip_stats.mem.name = "MEM"; +#endif /* MEM_STATS */ +#endif /* LWIP_DEBUG */ +} + +#if LWIP_STATS_DISPLAY +void +stats_display_proto(struct stats_proto *proto, char *name) +{ + LWIP_PLATFORM_DIAG(("\n%s\n\t", name)); + LWIP_PLATFORM_DIAG(("xmit: %"STAT_COUNTER_F"\n\t", proto->xmit)); + LWIP_PLATFORM_DIAG(("recv: %"STAT_COUNTER_F"\n\t", proto->recv)); + LWIP_PLATFORM_DIAG(("fw: %"STAT_COUNTER_F"\n\t", proto->fw)); + LWIP_PLATFORM_DIAG(("drop: %"STAT_COUNTER_F"\n\t", proto->drop)); + LWIP_PLATFORM_DIAG(("chkerr: %"STAT_COUNTER_F"\n\t", proto->chkerr)); + LWIP_PLATFORM_DIAG(("lenerr: %"STAT_COUNTER_F"\n\t", proto->lenerr)); + LWIP_PLATFORM_DIAG(("memerr: %"STAT_COUNTER_F"\n\t", proto->memerr)); + LWIP_PLATFORM_DIAG(("rterr: %"STAT_COUNTER_F"\n\t", proto->rterr)); + LWIP_PLATFORM_DIAG(("proterr: %"STAT_COUNTER_F"\n\t", proto->proterr)); + LWIP_PLATFORM_DIAG(("opterr: %"STAT_COUNTER_F"\n\t", proto->opterr)); + LWIP_PLATFORM_DIAG(("err: %"STAT_COUNTER_F"\n\t", proto->err)); + LWIP_PLATFORM_DIAG(("cachehit: %"STAT_COUNTER_F"\n", proto->cachehit)); +} + +#if IGMP_STATS +void +stats_display_igmp(struct stats_igmp *igmp) +{ + LWIP_PLATFORM_DIAG(("\nIGMP\n\t")); + LWIP_PLATFORM_DIAG(("xmit: %"STAT_COUNTER_F"\n\t", igmp->xmit)); + LWIP_PLATFORM_DIAG(("recv: %"STAT_COUNTER_F"\n\t", igmp->recv)); + LWIP_PLATFORM_DIAG(("drop: %"STAT_COUNTER_F"\n\t", igmp->drop)); + LWIP_PLATFORM_DIAG(("chkerr: %"STAT_COUNTER_F"\n\t", igmp->chkerr)); + LWIP_PLATFORM_DIAG(("lenerr: %"STAT_COUNTER_F"\n\t", igmp->lenerr)); + LWIP_PLATFORM_DIAG(("memerr: %"STAT_COUNTER_F"\n\t", igmp->memerr)); + LWIP_PLATFORM_DIAG(("proterr: %"STAT_COUNTER_F"\n\t", igmp->proterr)); + LWIP_PLATFORM_DIAG(("rx_v1: %"STAT_COUNTER_F"\n\t", igmp->rx_v1)); + LWIP_PLATFORM_DIAG(("rx_group: %"STAT_COUNTER_F"\n", igmp->rx_group)); + LWIP_PLATFORM_DIAG(("rx_general: %"STAT_COUNTER_F"\n", igmp->rx_general)); + LWIP_PLATFORM_DIAG(("rx_report: %"STAT_COUNTER_F"\n\t", igmp->rx_report)); + LWIP_PLATFORM_DIAG(("tx_join: %"STAT_COUNTER_F"\n\t", igmp->tx_join)); + LWIP_PLATFORM_DIAG(("tx_leave: %"STAT_COUNTER_F"\n\t", igmp->tx_leave)); + LWIP_PLATFORM_DIAG(("tx_report: %"STAT_COUNTER_F"\n\t", igmp->tx_report)); +} +#endif /* IGMP_STATS */ + +#if MEM_STATS || MEMP_STATS +void +stats_display_mem(struct stats_mem *mem, char *name) +{ + LWIP_PLATFORM_DIAG(("\nMEM %s\n\t", name)); + LWIP_PLATFORM_DIAG(("avail: %"U32_F"\n\t", (u32_t)mem->avail)); + LWIP_PLATFORM_DIAG(("used: %"U32_F"\n\t", (u32_t)mem->used)); + LWIP_PLATFORM_DIAG(("max: %"U32_F"\n\t", (u32_t)mem->max)); + LWIP_PLATFORM_DIAG(("err: %"U32_F"\n", (u32_t)mem->err)); +} + +#if MEMP_STATS +void +stats_display_memp(struct stats_mem *mem, int index) +{ + char * memp_names[] = { +#define LWIP_MEMPOOL(name,num,size,desc) desc, +#include "lwip/memp_std.h" + }; + if(index < MEMP_MAX) { + stats_display_mem(mem, memp_names[index]); + } +} +#endif /* MEMP_STATS */ +#endif /* MEM_STATS || MEMP_STATS */ + +#if SYS_STATS +void +stats_display_sys(struct stats_sys *sys) +{ + LWIP_PLATFORM_DIAG(("\nSYS\n\t")); + LWIP_PLATFORM_DIAG(("sem.used: %"U32_F"\n\t", (u32_t)sys->sem.used)); + LWIP_PLATFORM_DIAG(("sem.max: %"U32_F"\n\t", (u32_t)sys->sem.max)); + LWIP_PLATFORM_DIAG(("sem.err: %"U32_F"\n\t", (u32_t)sys->sem.err)); + LWIP_PLATFORM_DIAG(("mutex.used: %"U32_F"\n\t", (u32_t)sys->mutex.used)); + LWIP_PLATFORM_DIAG(("mutex.max: %"U32_F"\n\t", (u32_t)sys->mutex.max)); + LWIP_PLATFORM_DIAG(("mutex.err: %"U32_F"\n\t", (u32_t)sys->mutex.err)); + LWIP_PLATFORM_DIAG(("mbox.used: %"U32_F"\n\t", (u32_t)sys->mbox.used)); + LWIP_PLATFORM_DIAG(("mbox.max: %"U32_F"\n\t", (u32_t)sys->mbox.max)); + LWIP_PLATFORM_DIAG(("mbox.err: %"U32_F"\n\t", (u32_t)sys->mbox.err)); +} +#endif /* SYS_STATS */ + +void +stats_display(void) +{ + s16_t i; + + LINK_STATS_DISPLAY(); + ETHARP_STATS_DISPLAY(); + IPFRAG_STATS_DISPLAY(); + IP_STATS_DISPLAY(); + IGMP_STATS_DISPLAY(); + ICMP_STATS_DISPLAY(); + UDP_STATS_DISPLAY(); + TCP_STATS_DISPLAY(); + MEM_STATS_DISPLAY(); + for (i = 0; i < MEMP_MAX; i++) { + MEMP_STATS_DISPLAY(i); + } + SYS_STATS_DISPLAY(); +} +#endif /* LWIP_STATS_DISPLAY */ + +#endif /* LWIP_STATS */ + diff --git a/features/unsupported/net/lwip/lwip/core/tcp.c b/features/unsupported/net/lwip/lwip/core/tcp.c new file mode 100644 index 00000000000..c629bc4e8ac --- /dev/null +++ b/features/unsupported/net/lwip/lwip/core/tcp.c @@ -0,0 +1,1635 @@ +/** + * @file + * Transmission Control Protocol for IP + * + * This file contains common functions for the TCP implementation, such as functinos + * for manipulating the data structures and the TCP timer functions. TCP functions + * related to input and output is found in tcp_in.c and tcp_out.c respectively. + * + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ + +#include "lwip/opt.h" + +#if LWIP_TCP /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/def.h" +#include "lwip/mem.h" +#include "lwip/memp.h" +#include "lwip/snmp.h" +#include "lwip/tcp.h" +#include "lwip/tcp_impl.h" +#include "lwip/debug.h" +#include "lwip/stats.h" + +#include + +const char * const tcp_state_str[] = { + "CLOSED", + "LISTEN", + "SYN_SENT", + "SYN_RCVD", + "ESTABLISHED", + "FIN_WAIT_1", + "FIN_WAIT_2", + "CLOSE_WAIT", + "CLOSING", + "LAST_ACK", + "TIME_WAIT" +}; + +/* Incremented every coarse grained timer shot (typically every 500 ms). */ +u32_t tcp_ticks; +const u8_t tcp_backoff[13] = + { 1, 2, 3, 4, 5, 6, 7, 7, 7, 7, 7, 7, 7}; + /* Times per slowtmr hits */ +const u8_t tcp_persist_backoff[7] = { 3, 6, 12, 24, 48, 96, 120 }; + +/* The TCP PCB lists. */ + +/** List of all TCP PCBs bound but not yet (connected || listening) */ +struct tcp_pcb *tcp_bound_pcbs; +/** List of all TCP PCBs in LISTEN state */ +union tcp_listen_pcbs_t tcp_listen_pcbs; +/** List of all TCP PCBs that are in a state in which + * they accept or send data. */ +struct tcp_pcb *tcp_active_pcbs; +/** List of all TCP PCBs in TIME-WAIT state */ +struct tcp_pcb *tcp_tw_pcbs; + +#define NUM_TCP_PCB_LISTS 4 +#define NUM_TCP_PCB_LISTS_NO_TIME_WAIT 3 +/** An array with all (non-temporary) PCB lists, mainly used for smaller code size */ +struct tcp_pcb ** const tcp_pcb_lists[] = {&tcp_listen_pcbs.pcbs, &tcp_bound_pcbs, + &tcp_active_pcbs, &tcp_tw_pcbs}; + +/** Only used for temporary storage. */ +struct tcp_pcb *tcp_tmp_pcb; + +/** Timer counter to handle calling slow-timer from tcp_tmr() */ +static u8_t tcp_timer; +static u16_t tcp_new_port(void); + +/** + * Called periodically to dispatch TCP timers. + * + */ +void +tcp_tmr(void) +{ + /* Call tcp_fasttmr() every 250 ms */ + tcp_fasttmr(); + + if (++tcp_timer & 1) { + /* Call tcp_tmr() every 500 ms, i.e., every other timer + tcp_tmr() is called. */ + tcp_slowtmr(); + } +} + +/** + * Closes the TX side of a connection held by the PCB. + * For tcp_close(), a RST is sent if the application didn't receive all data + * (tcp_recved() not called for all data passed to recv callback). + * + * Listening pcbs are freed and may not be referenced any more. + * Connection pcbs are freed if not yet connected and may not be referenced + * any more. If a connection is established (at least SYN received or in + * a closing state), the connection is closed, and put in a closing state. + * The pcb is then automatically freed in tcp_slowtmr(). It is therefore + * unsafe to reference it. + * + * @param pcb the tcp_pcb to close + * @return ERR_OK if connection has been closed + * another err_t if closing failed and pcb is not freed + */ +static err_t +tcp_close_shutdown(struct tcp_pcb *pcb, u8_t rst_on_unacked_data) +{ + err_t err; + + if (rst_on_unacked_data && (pcb->state != LISTEN)) { + if ((pcb->refused_data != NULL) || (pcb->rcv_wnd != TCP_WND)) { + /* Not all data received by application, send RST to tell the remote + side about this. */ + LWIP_ASSERT("pcb->flags & TF_RXCLOSED", pcb->flags & TF_RXCLOSED); + + /* don't call tcp_abort here: we must not deallocate the pcb since + that might not be expected when calling tcp_close */ + tcp_rst(pcb->snd_nxt, pcb->rcv_nxt, &pcb->local_ip, &pcb->remote_ip, + pcb->local_port, pcb->remote_port); + + tcp_pcb_purge(pcb); + + /* TODO: to which state do we move now? */ + + /* move to TIME_WAIT since we close actively */ + TCP_RMV(&tcp_active_pcbs, pcb); + pcb->state = TIME_WAIT; + TCP_REG(&tcp_tw_pcbs, pcb); + + return ERR_OK; + } + } + + switch (pcb->state) { + case CLOSED: + /* Closing a pcb in the CLOSED state might seem erroneous, + * however, it is in this state once allocated and as yet unused + * and the user needs some way to free it should the need arise. + * Calling tcp_close() with a pcb that has already been closed, (i.e. twice) + * or for a pcb that has been used and then entered the CLOSED state + * is erroneous, but this should never happen as the pcb has in those cases + * been freed, and so any remaining handles are bogus. */ + err = ERR_OK; + if (pcb->local_port != 0) { + TCP_RMV(&tcp_bound_pcbs, pcb); + } + memp_free(MEMP_TCP_PCB, pcb); + pcb = NULL; + break; + case LISTEN: + err = ERR_OK; + tcp_pcb_remove(&tcp_listen_pcbs.pcbs, pcb); + memp_free(MEMP_TCP_PCB_LISTEN, pcb); + pcb = NULL; + break; + case SYN_SENT: + err = ERR_OK; + tcp_pcb_remove(&tcp_active_pcbs, pcb); + memp_free(MEMP_TCP_PCB, pcb); + pcb = NULL; + snmp_inc_tcpattemptfails(); + break; + case SYN_RCVD: + err = tcp_send_fin(pcb); + if (err == ERR_OK) { + snmp_inc_tcpattemptfails(); + pcb->state = FIN_WAIT_1; + } + break; + case ESTABLISHED: + err = tcp_send_fin(pcb); + if (err == ERR_OK) { + snmp_inc_tcpestabresets(); + pcb->state = FIN_WAIT_1; + } + break; + case CLOSE_WAIT: + err = tcp_send_fin(pcb); + if (err == ERR_OK) { + snmp_inc_tcpestabresets(); + pcb->state = LAST_ACK; + } + break; + default: + /* Has already been closed, do nothing. */ + err = ERR_OK; + pcb = NULL; + break; + } + + if (pcb != NULL && err == ERR_OK) { + /* To ensure all data has been sent when tcp_close returns, we have + to make sure tcp_output doesn't fail. + Since we don't really have to ensure all data has been sent when tcp_close + returns (unsent data is sent from tcp timer functions, also), we don't care + for the return value of tcp_output for now. */ + /* @todo: When implementing SO_LINGER, this must be changed somehow: + If SOF_LINGER is set, the data should be sent and acked before close returns. + This can only be valid for sequential APIs, not for the raw API. */ + tcp_output(pcb); + } + return err; +} + +/** + * Closes the connection held by the PCB. + * + * Listening pcbs are freed and may not be referenced any more. + * Connection pcbs are freed if not yet connected and may not be referenced + * any more. If a connection is established (at least SYN received or in + * a closing state), the connection is closed, and put in a closing state. + * The pcb is then automatically freed in tcp_slowtmr(). It is therefore + * unsafe to reference it (unless an error is returned). + * + * @param pcb the tcp_pcb to close + * @return ERR_OK if connection has been closed + * another err_t if closing failed and pcb is not freed + */ +err_t +tcp_close(struct tcp_pcb *pcb) +{ +#if TCP_DEBUG + LWIP_DEBUGF(TCP_DEBUG, ("tcp_close: closing in ")); + tcp_debug_print_state(pcb->state); +#endif /* TCP_DEBUG */ + + if (pcb->state != LISTEN) { + /* Set a flag not to receive any more data... */ + pcb->flags |= TF_RXCLOSED; + } + /* ... and close */ + return tcp_close_shutdown(pcb, 1); +} + +/** + * Causes all or part of a full-duplex connection of this PCB to be shut down. + * This doesn't deallocate the PCB! + * + * @param pcb PCB to shutdown + * @param shut_rx shut down receive side if this is != 0 + * @param shut_tx shut down send side if this is != 0 + * @return ERR_OK if shutdown succeeded (or the PCB has already been shut down) + * another err_t on error. + */ +err_t +tcp_shutdown(struct tcp_pcb *pcb, int shut_rx, int shut_tx) +{ + if (pcb->state == LISTEN) { + return ERR_CONN; + } + if (shut_rx) { + /* shut down the receive side: free buffered data... */ + if (pcb->refused_data != NULL) { + pbuf_free(pcb->refused_data); + pcb->refused_data = NULL; + } + /* ... and set a flag not to receive any more data */ + pcb->flags |= TF_RXCLOSED; + } + if (shut_tx) { + /* This can't happen twice since if it succeeds, the pcb's state is changed. + Only close in these states as the others directly deallocate the PCB */ + switch (pcb->state) { + case SYN_RCVD: + case ESTABLISHED: + case CLOSE_WAIT: + return tcp_close_shutdown(pcb, 0); + default: + /* don't shut down other states */ + break; + } + } + /* @todo: return another err_t if not in correct state or already shut? */ + return ERR_OK; +} + +/** + * Abandons a connection and optionally sends a RST to the remote + * host. Deletes the local protocol control block. This is done when + * a connection is killed because of shortage of memory. + * + * @param pcb the tcp_pcb to abort + * @param reset boolean to indicate whether a reset should be sent + */ +void +tcp_abandon(struct tcp_pcb *pcb, int reset) +{ + u32_t seqno, ackno; + u16_t remote_port, local_port; + ip_addr_t remote_ip, local_ip; +#if LWIP_CALLBACK_API + tcp_err_fn errf; +#endif /* LWIP_CALLBACK_API */ + void *errf_arg; + + /* pcb->state LISTEN not allowed here */ + LWIP_ASSERT("don't call tcp_abort/tcp_abandon for listen-pcbs", + pcb->state != LISTEN); + /* Figure out on which TCP PCB list we are, and remove us. If we + are in an active state, call the receive function associated with + the PCB with a NULL argument, and send an RST to the remote end. */ + if (pcb->state == TIME_WAIT) { + tcp_pcb_remove(&tcp_tw_pcbs, pcb); + memp_free(MEMP_TCP_PCB, pcb); + } else { + seqno = pcb->snd_nxt; + ackno = pcb->rcv_nxt; + ip_addr_copy(local_ip, pcb->local_ip); + ip_addr_copy(remote_ip, pcb->remote_ip); + local_port = pcb->local_port; + remote_port = pcb->remote_port; +#if LWIP_CALLBACK_API + errf = pcb->errf; +#endif /* LWIP_CALLBACK_API */ + errf_arg = pcb->callback_arg; + tcp_pcb_remove(&tcp_active_pcbs, pcb); + if (pcb->unacked != NULL) { + tcp_segs_free(pcb->unacked); + } + if (pcb->unsent != NULL) { + tcp_segs_free(pcb->unsent); + } +#if TCP_QUEUE_OOSEQ + if (pcb->ooseq != NULL) { + tcp_segs_free(pcb->ooseq); + } +#endif /* TCP_QUEUE_OOSEQ */ + memp_free(MEMP_TCP_PCB, pcb); + TCP_EVENT_ERR(errf, errf_arg, ERR_ABRT); + if (reset) { + LWIP_DEBUGF(TCP_RST_DEBUG, ("tcp_abandon: sending RST\n")); + tcp_rst(seqno, ackno, &local_ip, &remote_ip, local_port, remote_port); + } + } +} + +/** + * Aborts the connection by sending a RST (reset) segment to the remote + * host. The pcb is deallocated. This function never fails. + * + * ATTENTION: When calling this from one of the TCP callbacks, make + * sure you always return ERR_ABRT (and never return ERR_ABRT otherwise + * or you will risk accessing deallocated memory or memory leaks! + * + * @param pcb the tcp pcb to abort + */ +void +tcp_abort(struct tcp_pcb *pcb) +{ + tcp_abandon(pcb, 1); +} + +/** + * Binds the connection to a local portnumber and IP address. If the + * IP address is not given (i.e., ipaddr == NULL), the IP address of + * the outgoing network interface is used instead. + * + * @param pcb the tcp_pcb to bind (no check is done whether this pcb is + * already bound!) + * @param ipaddr the local ip address to bind to (use IP_ADDR_ANY to bind + * to any local address + * @param port the local port to bind to + * @return ERR_USE if the port is already in use + * ERR_VAL if bind failed because the PCB is not in a valid state + * ERR_OK if bound + */ +err_t +tcp_bind(struct tcp_pcb *pcb, ip_addr_t *ipaddr, u16_t port) +{ + int i; + int max_pcb_list = NUM_TCP_PCB_LISTS; + struct tcp_pcb *cpcb; + + LWIP_ERROR("tcp_bind: can only bind in state CLOSED", pcb->state == CLOSED, return ERR_VAL); + +#if SO_REUSE + /* Unless the REUSEADDR flag is set, + we have to check the pcbs in TIME-WAIT state, also. + We do not dump TIME_WAIT pcb's; they can still be matched by incoming + packets using both local and remote IP addresses and ports to distinguish. + */ + if ((pcb->so_options & SOF_REUSEADDR) != 0) { + max_pcb_list = NUM_TCP_PCB_LISTS_NO_TIME_WAIT; + } +#endif /* SO_REUSE */ + + if (port == 0) { + port = tcp_new_port(); + } + + /* Check if the address already is in use (on all lists) */ + for (i = 0; i < max_pcb_list; i++) { + for(cpcb = *tcp_pcb_lists[i]; cpcb != NULL; cpcb = cpcb->next) { + if (cpcb->local_port == port) { +#if SO_REUSE + /* Omit checking for the same port if both pcbs have REUSEADDR set. + For SO_REUSEADDR, the duplicate-check for a 5-tuple is done in + tcp_connect. */ + if (((pcb->so_options & SOF_REUSEADDR) == 0) || + ((cpcb->so_options & SOF_REUSEADDR) == 0)) +#endif /* SO_REUSE */ + { + if (ip_addr_isany(&(cpcb->local_ip)) || + ip_addr_isany(ipaddr) || + ip_addr_cmp(&(cpcb->local_ip), ipaddr)) { + return ERR_USE; + } + } + } + } + } + + if (!ip_addr_isany(ipaddr)) { + pcb->local_ip = *ipaddr; + } + pcb->local_port = port; + TCP_REG(&tcp_bound_pcbs, pcb); + LWIP_DEBUGF(TCP_DEBUG, ("tcp_bind: bind to port %"U16_F"\n", port)); + return ERR_OK; +} +#if LWIP_CALLBACK_API +/** + * Default accept callback if no accept callback is specified by the user. + */ +static err_t +tcp_accept_null(void *arg, struct tcp_pcb *pcb, err_t err) +{ + LWIP_UNUSED_ARG(arg); + LWIP_UNUSED_ARG(pcb); + LWIP_UNUSED_ARG(err); + + return ERR_ABRT; +} +#endif /* LWIP_CALLBACK_API */ + +/** + * Set the state of the connection to be LISTEN, which means that it + * is able to accept incoming connections. The protocol control block + * is reallocated in order to consume less memory. Setting the + * connection to LISTEN is an irreversible process. + * + * @param pcb the original tcp_pcb + * @param backlog the incoming connections queue limit + * @return tcp_pcb used for listening, consumes less memory. + * + * @note The original tcp_pcb is freed. This function therefore has to be + * called like this: + * tpcb = tcp_listen(tpcb); + */ +struct tcp_pcb * +tcp_listen_with_backlog(struct tcp_pcb *pcb, u8_t backlog) +{ + struct tcp_pcb_listen *lpcb; + + LWIP_UNUSED_ARG(backlog); + LWIP_ERROR("tcp_listen: pcb already connected", pcb->state == CLOSED, return NULL); + + /* already listening? */ + if (pcb->state == LISTEN) { + return pcb; + } +#if SO_REUSE + if ((pcb->so_options & SOF_REUSEADDR) != 0) { + /* Since SOF_REUSEADDR allows reusing a local address before the pcb's usage + is declared (listen-/connection-pcb), we have to make sure now that + this port is only used once for every local IP. */ + for(lpcb = tcp_listen_pcbs.listen_pcbs; lpcb != NULL; lpcb = lpcb->next) { + if (lpcb->local_port == pcb->local_port) { + if (ip_addr_cmp(&lpcb->local_ip, &pcb->local_ip)) { + /* this address/port is already used */ + return NULL; + } + } + } + } +#endif /* SO_REUSE */ + lpcb = (struct tcp_pcb_listen *)memp_malloc(MEMP_TCP_PCB_LISTEN); + if (lpcb == NULL) { + return NULL; + } + lpcb->callback_arg = pcb->callback_arg; + lpcb->local_port = pcb->local_port; + lpcb->state = LISTEN; + lpcb->prio = pcb->prio; + lpcb->so_options = pcb->so_options; + lpcb->so_options |= SOF_ACCEPTCONN; + lpcb->ttl = pcb->ttl; + lpcb->tos = pcb->tos; + ip_addr_copy(lpcb->local_ip, pcb->local_ip); + if (pcb->local_port != 0) { + TCP_RMV(&tcp_bound_pcbs, pcb); + } + memp_free(MEMP_TCP_PCB, pcb); +#if LWIP_CALLBACK_API + lpcb->accept = tcp_accept_null; +#endif /* LWIP_CALLBACK_API */ +#if TCP_LISTEN_BACKLOG + lpcb->accepts_pending = 0; + lpcb->backlog = (backlog ? backlog : 1); +#endif /* TCP_LISTEN_BACKLOG */ + TCP_REG(&tcp_listen_pcbs.pcbs, (struct tcp_pcb *)lpcb); + return (struct tcp_pcb *)lpcb; +} + +/** + * Update the state that tracks the available window space to advertise. + * + * Returns how much extra window would be advertised if we sent an + * update now. + */ +u32_t tcp_update_rcv_ann_wnd(struct tcp_pcb *pcb) +{ + u32_t new_right_edge = pcb->rcv_nxt + pcb->rcv_wnd; + + if (TCP_SEQ_GEQ(new_right_edge, pcb->rcv_ann_right_edge + LWIP_MIN((TCP_WND / 2), pcb->mss))) { + /* we can advertise more window */ + pcb->rcv_ann_wnd = pcb->rcv_wnd; + return new_right_edge - pcb->rcv_ann_right_edge; + } else { + if (TCP_SEQ_GT(pcb->rcv_nxt, pcb->rcv_ann_right_edge)) { + /* Can happen due to other end sending out of advertised window, + * but within actual available (but not yet advertised) window */ + pcb->rcv_ann_wnd = 0; + } else { + /* keep the right edge of window constant */ + u32_t new_rcv_ann_wnd = pcb->rcv_ann_right_edge - pcb->rcv_nxt; + LWIP_ASSERT("new_rcv_ann_wnd <= 0xffff", new_rcv_ann_wnd <= 0xffff); + pcb->rcv_ann_wnd = (u16_t)new_rcv_ann_wnd; + } + return 0; + } +} + +/** + * This function should be called by the application when it has + * processed the data. The purpose is to advertise a larger window + * when the data has been processed. + * + * @param pcb the tcp_pcb for which data is read + * @param len the amount of bytes that have been read by the application + */ +void +tcp_recved(struct tcp_pcb *pcb, u16_t len) +{ + int wnd_inflation; + + LWIP_ASSERT("tcp_recved: len would wrap rcv_wnd\n", + len <= 0xffff - pcb->rcv_wnd ); + + pcb->rcv_wnd += len; + if (pcb->rcv_wnd > TCP_WND) { + pcb->rcv_wnd = TCP_WND; + } + + wnd_inflation = tcp_update_rcv_ann_wnd(pcb); + + /* If the change in the right edge of window is significant (default + * watermark is TCP_WND/4), then send an explicit update now. + * Otherwise wait for a packet to be sent in the normal course of + * events (or more window to be available later) */ + if (wnd_inflation >= TCP_WND_UPDATE_THRESHOLD) { + tcp_ack_now(pcb); + tcp_output(pcb); + } + + LWIP_DEBUGF(TCP_DEBUG, ("tcp_recved: recveived %"U16_F" bytes, wnd %"U16_F" (%"U16_F").\n", + len, pcb->rcv_wnd, TCP_WND - pcb->rcv_wnd)); +} + +/** + * A nastly hack featuring 'goto' statements that allocates a + * new TCP local port. + * + * @return a new (free) local TCP port number + */ +static u16_t +tcp_new_port(void) +{ + int i; + struct tcp_pcb *pcb; +#ifndef TCP_LOCAL_PORT_RANGE_START +/* From http://www.iana.org/assignments/port-numbers: + "The Dynamic and/or Private Ports are those from 49152 through 65535" */ +#define TCP_LOCAL_PORT_RANGE_START 0xc000 +#define TCP_LOCAL_PORT_RANGE_END 0xffff +#endif + static u16_t port = TCP_LOCAL_PORT_RANGE_START; + + again: + if (port++ >= TCP_LOCAL_PORT_RANGE_END) { + port = TCP_LOCAL_PORT_RANGE_START; + } + /* Check all PCB lists. */ + for (i = 0; i < NUM_TCP_PCB_LISTS; i++) { + for(pcb = *tcp_pcb_lists[i]; pcb != NULL; pcb = pcb->next) { + if (pcb->local_port == port) { + goto again; + } + } + } + return port; +} + +/** + * Connects to another host. The function given as the "connected" + * argument will be called when the connection has been established. + * + * @param pcb the tcp_pcb used to establish the connection + * @param ipaddr the remote ip address to connect to + * @param port the remote tcp port to connect to + * @param connected callback function to call when connected (or on error) + * @return ERR_VAL if invalid arguments are given + * ERR_OK if connect request has been sent + * other err_t values if connect request couldn't be sent + */ +err_t +tcp_connect(struct tcp_pcb *pcb, ip_addr_t *ipaddr, u16_t port, + tcp_connected_fn connected) +{ + err_t ret; + u32_t iss; + u16_t old_local_port; + + LWIP_ERROR("tcp_connect: can only connect from state CLOSED", pcb->state == CLOSED, return ERR_ISCONN); + + LWIP_DEBUGF(TCP_DEBUG, ("tcp_connect to port %"U16_F"\n", port)); + if (ipaddr != NULL) { + pcb->remote_ip = *ipaddr; + } else { + return ERR_VAL; + } + pcb->remote_port = port; + + /* check if we have a route to the remote host */ + if (ip_addr_isany(&(pcb->local_ip))) { + /* no local IP address set, yet. */ + struct netif *netif = ip_route(&(pcb->remote_ip)); + if (netif == NULL) { + /* Don't even try to send a SYN packet if we have no route + since that will fail. */ + return ERR_RTE; + } + /* Use the netif's IP address as local address. */ + ip_addr_copy(pcb->local_ip, netif->ip_addr); + } + + old_local_port = pcb->local_port; + if (pcb->local_port == 0) { + pcb->local_port = tcp_new_port(); + } +#if SO_REUSE + if ((pcb->so_options & SOF_REUSEADDR) != 0) { + /* Since SOF_REUSEADDR allows reusing a local address, we have to make sure + now that the 5-tuple is unique. */ + struct tcp_pcb *cpcb; + int i; + /* Don't check listen- and bound-PCBs, check active- and TIME-WAIT PCBs. */ + for (i = 2; i < NUM_TCP_PCB_LISTS; i++) { + for(cpcb = *tcp_pcb_lists[i]; cpcb != NULL; cpcb = cpcb->next) { + if ((cpcb->local_port == pcb->local_port) && + (cpcb->remote_port == port) && + ip_addr_cmp(&cpcb->local_ip, &pcb->local_ip) && + ip_addr_cmp(&cpcb->remote_ip, ipaddr)) { + /* linux returns EISCONN here, but ERR_USE should be OK for us */ + return ERR_USE; + } + } + } + } +#endif /* SO_REUSE */ + iss = tcp_next_iss(); + pcb->rcv_nxt = 0; + pcb->snd_nxt = iss; + pcb->lastack = iss - 1; + pcb->snd_lbb = iss - 1; + pcb->rcv_wnd = TCP_WND; + pcb->rcv_ann_wnd = TCP_WND; + pcb->rcv_ann_right_edge = pcb->rcv_nxt; + pcb->snd_wnd = TCP_WND; + /* As initial send MSS, we use TCP_MSS but limit it to 536. + The send MSS is updated when an MSS option is received. */ + pcb->mss = (TCP_MSS > 536) ? 536 : TCP_MSS; +#if TCP_CALCULATE_EFF_SEND_MSS + pcb->mss = tcp_eff_send_mss(pcb->mss, ipaddr); +#endif /* TCP_CALCULATE_EFF_SEND_MSS */ + pcb->cwnd = 1; + pcb->ssthresh = pcb->mss * 10; +#if LWIP_CALLBACK_API + pcb->connected = connected; +#else /* LWIP_CALLBACK_API */ + LWIP_UNUSED_ARG(connected); +#endif /* LWIP_CALLBACK_API */ + + /* Send a SYN together with the MSS option. */ + ret = tcp_enqueue_flags(pcb, TCP_SYN); + if (ret == ERR_OK) { + /* SYN segment was enqueued, changed the pcbs state now */ + pcb->state = SYN_SENT; + if (old_local_port != 0) { + TCP_RMV(&tcp_bound_pcbs, pcb); + } + TCP_REG(&tcp_active_pcbs, pcb); + snmp_inc_tcpactiveopens(); + + tcp_output(pcb); + } + return ret; +} + +/** + * Called every 500 ms and implements the retransmission timer and the timer that + * removes PCBs that have been in TIME-WAIT for enough time. It also increments + * various timers such as the inactivity timer in each PCB. + * + * Automatically called from tcp_tmr(). + */ +void +tcp_slowtmr(void) +{ + struct tcp_pcb *pcb, *prev; + u16_t eff_wnd; + u8_t pcb_remove; /* flag if a PCB should be removed */ + u8_t pcb_reset; /* flag if a RST should be sent when removing */ + err_t err; + + err = ERR_OK; + + ++tcp_ticks; + + /* Steps through all of the active PCBs. */ + prev = NULL; + pcb = tcp_active_pcbs; + if (pcb == NULL) { + LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: no active pcbs\n")); + } + while (pcb != NULL) { + LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: processing active pcb\n")); + LWIP_ASSERT("tcp_slowtmr: active pcb->state != CLOSED\n", pcb->state != CLOSED); + LWIP_ASSERT("tcp_slowtmr: active pcb->state != LISTEN\n", pcb->state != LISTEN); + LWIP_ASSERT("tcp_slowtmr: active pcb->state != TIME-WAIT\n", pcb->state != TIME_WAIT); + + pcb_remove = 0; + pcb_reset = 0; + + if (pcb->state == SYN_SENT && pcb->nrtx == TCP_SYNMAXRTX) { + ++pcb_remove; + LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: max SYN retries reached\n")); + } + else if (pcb->nrtx == TCP_MAXRTX) { + ++pcb_remove; + LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: max DATA retries reached\n")); + } else { + if (pcb->persist_backoff > 0) { + /* If snd_wnd is zero, use persist timer to send 1 byte probes + * instead of using the standard retransmission mechanism. */ + pcb->persist_cnt++; + if (pcb->persist_cnt >= tcp_persist_backoff[pcb->persist_backoff-1]) { + pcb->persist_cnt = 0; + if (pcb->persist_backoff < sizeof(tcp_persist_backoff)) { + pcb->persist_backoff++; + } + tcp_zero_window_probe(pcb); + } + } else { + /* Increase the retransmission timer if it is running */ + if(pcb->rtime >= 0) + ++pcb->rtime; + + if (pcb->unacked != NULL && pcb->rtime >= pcb->rto) { + /* Time for a retransmission. */ + LWIP_DEBUGF(TCP_RTO_DEBUG, ("tcp_slowtmr: rtime %"S16_F + " pcb->rto %"S16_F"\n", + pcb->rtime, pcb->rto)); + + /* Double retransmission time-out unless we are trying to + * connect to somebody (i.e., we are in SYN_SENT). */ + if (pcb->state != SYN_SENT) { + pcb->rto = ((pcb->sa >> 3) + pcb->sv) << tcp_backoff[pcb->nrtx]; + } + + /* Reset the retransmission timer. */ + pcb->rtime = 0; + + /* Reduce congestion window and ssthresh. */ + eff_wnd = LWIP_MIN(pcb->cwnd, pcb->snd_wnd); + pcb->ssthresh = eff_wnd >> 1; + if (pcb->ssthresh < (pcb->mss << 1)) { + pcb->ssthresh = (pcb->mss << 1); + } + pcb->cwnd = pcb->mss; + LWIP_DEBUGF(TCP_CWND_DEBUG, ("tcp_slowtmr: cwnd %"U16_F + " ssthresh %"U16_F"\n", + pcb->cwnd, pcb->ssthresh)); + + /* The following needs to be called AFTER cwnd is set to one + mss - STJ */ + tcp_rexmit_rto(pcb); + } + } + } + /* Check if this PCB has stayed too long in FIN-WAIT-2 */ + if (pcb->state == FIN_WAIT_2) { + if ((u32_t)(tcp_ticks - pcb->tmr) > + TCP_FIN_WAIT_TIMEOUT / TCP_SLOW_INTERVAL) { + ++pcb_remove; + LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: removing pcb stuck in FIN-WAIT-2\n")); + } + } + + /* Check if KEEPALIVE should be sent */ + if((pcb->so_options & SOF_KEEPALIVE) && + ((pcb->state == ESTABLISHED) || + (pcb->state == CLOSE_WAIT))) { +#if LWIP_TCP_KEEPALIVE + if((u32_t)(tcp_ticks - pcb->tmr) > + (pcb->keep_idle + (pcb->keep_cnt*pcb->keep_intvl)) + / TCP_SLOW_INTERVAL) +#else + if((u32_t)(tcp_ticks - pcb->tmr) > + (pcb->keep_idle + TCP_MAXIDLE) / TCP_SLOW_INTERVAL) +#endif /* LWIP_TCP_KEEPALIVE */ + { + LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: KEEPALIVE timeout. Aborting connection to %"U16_F".%"U16_F".%"U16_F".%"U16_F".\n", + ip4_addr1_16(&pcb->remote_ip), ip4_addr2_16(&pcb->remote_ip), + ip4_addr3_16(&pcb->remote_ip), ip4_addr4_16(&pcb->remote_ip))); + + ++pcb_remove; + ++pcb_reset; + } +#if LWIP_TCP_KEEPALIVE + else if((u32_t)(tcp_ticks - pcb->tmr) > + (pcb->keep_idle + pcb->keep_cnt_sent * pcb->keep_intvl) + / TCP_SLOW_INTERVAL) +#else + else if((u32_t)(tcp_ticks - pcb->tmr) > + (pcb->keep_idle + pcb->keep_cnt_sent * TCP_KEEPINTVL_DEFAULT) + / TCP_SLOW_INTERVAL) +#endif /* LWIP_TCP_KEEPALIVE */ + { + tcp_keepalive(pcb); + pcb->keep_cnt_sent++; + } + } + + /* If this PCB has queued out of sequence data, but has been + inactive for too long, will drop the data (it will eventually + be retransmitted). */ +#if TCP_QUEUE_OOSEQ + if (pcb->ooseq != NULL && + (u32_t)tcp_ticks - pcb->tmr >= pcb->rto * TCP_OOSEQ_TIMEOUT) { + tcp_segs_free(pcb->ooseq); + pcb->ooseq = NULL; + LWIP_DEBUGF(TCP_CWND_DEBUG, ("tcp_slowtmr: dropping OOSEQ queued data\n")); + } +#endif /* TCP_QUEUE_OOSEQ */ + + /* Check if this PCB has stayed too long in SYN-RCVD */ + if (pcb->state == SYN_RCVD) { + if ((u32_t)(tcp_ticks - pcb->tmr) > + TCP_SYN_RCVD_TIMEOUT / TCP_SLOW_INTERVAL) { + ++pcb_remove; + LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: removing pcb stuck in SYN-RCVD\n")); + } + } + + /* Check if this PCB has stayed too long in LAST-ACK */ + if (pcb->state == LAST_ACK) { + if ((u32_t)(tcp_ticks - pcb->tmr) > 2 * TCP_MSL / TCP_SLOW_INTERVAL) { + ++pcb_remove; + LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: removing pcb stuck in LAST-ACK\n")); + } + } + + /* If the PCB should be removed, do it. */ + if (pcb_remove) { + struct tcp_pcb *pcb2; + tcp_pcb_purge(pcb); + /* Remove PCB from tcp_active_pcbs list. */ + if (prev != NULL) { + LWIP_ASSERT("tcp_slowtmr: middle tcp != tcp_active_pcbs", pcb != tcp_active_pcbs); + prev->next = pcb->next; + } else { + /* This PCB was the first. */ + LWIP_ASSERT("tcp_slowtmr: first pcb == tcp_active_pcbs", tcp_active_pcbs == pcb); + tcp_active_pcbs = pcb->next; + } + + TCP_EVENT_ERR(pcb->errf, pcb->callback_arg, ERR_ABRT); + if (pcb_reset) { + tcp_rst(pcb->snd_nxt, pcb->rcv_nxt, &pcb->local_ip, &pcb->remote_ip, + pcb->local_port, pcb->remote_port); + } + + pcb2 = pcb; + pcb = pcb->next; + memp_free(MEMP_TCP_PCB, pcb2); + } else { + /* get the 'next' element now and work with 'prev' below (in case of abort) */ + prev = pcb; + pcb = pcb->next; + + /* We check if we should poll the connection. */ + ++prev->polltmr; + if (prev->polltmr >= prev->pollinterval) { + prev->polltmr = 0; + LWIP_DEBUGF(TCP_DEBUG, ("tcp_slowtmr: polling application\n")); + TCP_EVENT_POLL(prev, err); + /* if err == ERR_ABRT, 'prev' is already deallocated */ + if (err == ERR_OK) { + tcp_output(prev); + } + } + } + } + + + /* Steps through all of the TIME-WAIT PCBs. */ + prev = NULL; + pcb = tcp_tw_pcbs; + while (pcb != NULL) { + LWIP_ASSERT("tcp_slowtmr: TIME-WAIT pcb->state == TIME-WAIT", pcb->state == TIME_WAIT); + pcb_remove = 0; + + /* Check if this PCB has stayed long enough in TIME-WAIT */ + if ((u32_t)(tcp_ticks - pcb->tmr) > 2 * TCP_MSL / TCP_SLOW_INTERVAL) { + ++pcb_remove; + } + + + + /* If the PCB should be removed, do it. */ + if (pcb_remove) { + struct tcp_pcb *pcb2; + tcp_pcb_purge(pcb); + /* Remove PCB from tcp_tw_pcbs list. */ + if (prev != NULL) { + LWIP_ASSERT("tcp_slowtmr: middle tcp != tcp_tw_pcbs", pcb != tcp_tw_pcbs); + prev->next = pcb->next; + } else { + /* This PCB was the first. */ + LWIP_ASSERT("tcp_slowtmr: first pcb == tcp_tw_pcbs", tcp_tw_pcbs == pcb); + tcp_tw_pcbs = pcb->next; + } + pcb2 = pcb; + pcb = pcb->next; + memp_free(MEMP_TCP_PCB, pcb2); + } else { + prev = pcb; + pcb = pcb->next; + } + } +} + +/** + * Is called every TCP_FAST_INTERVAL (250 ms) and process data previously + * "refused" by upper layer (application) and sends delayed ACKs. + * + * Automatically called from tcp_tmr(). + */ +void +tcp_fasttmr(void) +{ + struct tcp_pcb *pcb = tcp_active_pcbs; + + while(pcb != NULL) { + struct tcp_pcb *next = pcb->next; + /* If there is data which was previously "refused" by upper layer */ + if (pcb->refused_data != NULL) { + /* Notify again application with data previously received. */ + err_t err; + LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_fasttmr: notify kept packet\n")); + TCP_EVENT_RECV(pcb, pcb->refused_data, ERR_OK, err); + if (err == ERR_OK) { + pcb->refused_data = NULL; + } else if (err == ERR_ABRT) { + /* if err == ERR_ABRT, 'pcb' is already deallocated */ + pcb = NULL; + } + } + + /* send delayed ACKs */ + if (pcb && (pcb->flags & TF_ACK_DELAY)) { + LWIP_DEBUGF(TCP_DEBUG, ("tcp_fasttmr: delayed ACK\n")); + tcp_ack_now(pcb); + tcp_output(pcb); + pcb->flags &= ~(TF_ACK_DELAY | TF_ACK_NOW); + } + + pcb = next; + } +} + +/** + * Deallocates a list of TCP segments (tcp_seg structures). + * + * @param seg tcp_seg list of TCP segments to free + */ +void +tcp_segs_free(struct tcp_seg *seg) +{ + while (seg != NULL) { + struct tcp_seg *next = seg->next; + tcp_seg_free(seg); + seg = next; + } +} + +/** + * Frees a TCP segment (tcp_seg structure). + * + * @param seg single tcp_seg to free + */ +void +tcp_seg_free(struct tcp_seg *seg) +{ + if (seg != NULL) { + if (seg->p != NULL) { + pbuf_free(seg->p); +#if TCP_DEBUG + seg->p = NULL; +#endif /* TCP_DEBUG */ + } + memp_free(MEMP_TCP_SEG, seg); + } +} + +/** + * Sets the priority of a connection. + * + * @param pcb the tcp_pcb to manipulate + * @param prio new priority + */ +void +tcp_setprio(struct tcp_pcb *pcb, u8_t prio) +{ + pcb->prio = prio; +} + +#if TCP_QUEUE_OOSEQ +/** + * Returns a copy of the given TCP segment. + * The pbuf and data are not copied, only the pointers + * + * @param seg the old tcp_seg + * @return a copy of seg + */ +struct tcp_seg * +tcp_seg_copy(struct tcp_seg *seg) +{ + struct tcp_seg *cseg; + + cseg = (struct tcp_seg *)memp_malloc(MEMP_TCP_SEG); + if (cseg == NULL) { + return NULL; + } + SMEMCPY((u8_t *)cseg, (const u8_t *)seg, sizeof(struct tcp_seg)); + pbuf_ref(cseg->p); + return cseg; +} +#endif /* TCP_QUEUE_OOSEQ */ + +#if LWIP_CALLBACK_API +/** + * Default receive callback that is called if the user didn't register + * a recv callback for the pcb. + */ +err_t +tcp_recv_null(void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err) +{ + LWIP_UNUSED_ARG(arg); + if (p != NULL) { + tcp_recved(pcb, p->tot_len); + pbuf_free(p); + } else if (err == ERR_OK) { + return tcp_close(pcb); + } + return ERR_OK; +} +#endif /* LWIP_CALLBACK_API */ + +/** + * Kills the oldest active connection that has lower priority than prio. + * + * @param prio minimum priority + */ +static void +tcp_kill_prio(u8_t prio) +{ + struct tcp_pcb *pcb, *inactive; + u32_t inactivity; + u8_t mprio; + + + mprio = TCP_PRIO_MAX; + + /* We kill the oldest active connection that has lower priority than prio. */ + inactivity = 0; + inactive = NULL; + for(pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) { + if (pcb->prio <= prio && + pcb->prio <= mprio && + (u32_t)(tcp_ticks - pcb->tmr) >= inactivity) { + inactivity = tcp_ticks - pcb->tmr; + inactive = pcb; + mprio = pcb->prio; + } + } + if (inactive != NULL) { + LWIP_DEBUGF(TCP_DEBUG, ("tcp_kill_prio: killing oldest PCB %p (%"S32_F")\n", + (void *)inactive, inactivity)); + tcp_abort(inactive); + } +} + +/** + * Kills the oldest connection that is in TIME_WAIT state. + * Called from tcp_alloc() if no more connections are available. + */ +static void +tcp_kill_timewait(void) +{ + struct tcp_pcb *pcb, *inactive; + u32_t inactivity; + + inactivity = 0; + inactive = NULL; + /* Go through the list of TIME_WAIT pcbs and get the oldest pcb. */ + for(pcb = tcp_tw_pcbs; pcb != NULL; pcb = pcb->next) { + if ((u32_t)(tcp_ticks - pcb->tmr) >= inactivity) { + inactivity = tcp_ticks - pcb->tmr; + inactive = pcb; + } + } + if (inactive != NULL) { + LWIP_DEBUGF(TCP_DEBUG, ("tcp_kill_timewait: killing oldest TIME-WAIT PCB %p (%"S32_F")\n", + (void *)inactive, inactivity)); + tcp_abort(inactive); + } +} + +/** + * Allocate a new tcp_pcb structure. + * + * @param prio priority for the new pcb + * @return a new tcp_pcb that initially is in state CLOSED + */ +struct tcp_pcb * +tcp_alloc(u8_t prio) +{ + struct tcp_pcb *pcb; + u32_t iss; + + pcb = (struct tcp_pcb *)memp_malloc(MEMP_TCP_PCB); + if (pcb == NULL) { + /* Try killing oldest connection in TIME-WAIT. */ + LWIP_DEBUGF(TCP_DEBUG, ("tcp_alloc: killing off oldest TIME-WAIT connection\n")); + tcp_kill_timewait(); + /* Try to allocate a tcp_pcb again. */ + pcb = (struct tcp_pcb *)memp_malloc(MEMP_TCP_PCB); + if (pcb == NULL) { + /* Try killing active connections with lower priority than the new one. */ + LWIP_DEBUGF(TCP_DEBUG, ("tcp_alloc: killing connection with prio lower than %d\n", prio)); + tcp_kill_prio(prio); + /* Try to allocate a tcp_pcb again. */ + pcb = (struct tcp_pcb *)memp_malloc(MEMP_TCP_PCB); + if (pcb != NULL) { + /* adjust err stats: memp_malloc failed twice before */ + MEMP_STATS_DEC(err, MEMP_TCP_PCB); + } + } + if (pcb != NULL) { + /* adjust err stats: timewait PCB was freed above */ + MEMP_STATS_DEC(err, MEMP_TCP_PCB); + } + } + if (pcb != NULL) { + memset(pcb, 0, sizeof(struct tcp_pcb)); + pcb->prio = prio; + pcb->snd_buf = TCP_SND_BUF; + pcb->snd_queuelen = 0; + pcb->rcv_wnd = TCP_WND; + pcb->rcv_ann_wnd = TCP_WND; + pcb->tos = 0; + pcb->ttl = TCP_TTL; + /* As initial send MSS, we use TCP_MSS but limit it to 536. + The send MSS is updated when an MSS option is received. */ + pcb->mss = (TCP_MSS > 536) ? 536 : TCP_MSS; + pcb->rto = 3000 / TCP_SLOW_INTERVAL; + pcb->sa = 0; + pcb->sv = 3000 / TCP_SLOW_INTERVAL; + pcb->rtime = -1; + pcb->cwnd = 1; + iss = tcp_next_iss(); + pcb->snd_wl2 = iss; + pcb->snd_nxt = iss; + pcb->lastack = iss; + pcb->snd_lbb = iss; + pcb->tmr = tcp_ticks; + + pcb->polltmr = 0; + +#if LWIP_CALLBACK_API + pcb->recv = tcp_recv_null; +#endif /* LWIP_CALLBACK_API */ + + /* Init KEEPALIVE timer */ + pcb->keep_idle = TCP_KEEPIDLE_DEFAULT; + +#if LWIP_TCP_KEEPALIVE + pcb->keep_intvl = TCP_KEEPINTVL_DEFAULT; + pcb->keep_cnt = TCP_KEEPCNT_DEFAULT; +#endif /* LWIP_TCP_KEEPALIVE */ + + pcb->keep_cnt_sent = 0; + } + return pcb; +} + +/** + * Creates a new TCP protocol control block but doesn't place it on + * any of the TCP PCB lists. + * The pcb is not put on any list until binding using tcp_bind(). + * + * @internal: Maybe there should be a idle TCP PCB list where these + * PCBs are put on. Port reservation using tcp_bind() is implemented but + * allocated pcbs that are not bound can't be killed automatically if wanting + * to allocate a pcb with higher prio (@see tcp_kill_prio()) + * + * @return a new tcp_pcb that initially is in state CLOSED + */ +struct tcp_pcb * +tcp_new(void) +{ + return tcp_alloc(TCP_PRIO_NORMAL); +} + +/** + * Used to specify the argument that should be passed callback + * functions. + * + * @param pcb tcp_pcb to set the callback argument + * @param arg void pointer argument to pass to callback functions + */ +void +tcp_arg(struct tcp_pcb *pcb, void *arg) +{ + pcb->callback_arg = arg; +} +#if LWIP_CALLBACK_API + +/** + * Used to specify the function that should be called when a TCP + * connection receives data. + * + * @param pcb tcp_pcb to set the recv callback + * @param recv callback function to call for this pcb when data is received + */ +void +tcp_recv(struct tcp_pcb *pcb, tcp_recv_fn recv) +{ + pcb->recv = recv; +} + +/** + * Used to specify the function that should be called when TCP data + * has been successfully delivered to the remote host. + * + * @param pcb tcp_pcb to set the sent callback + * @param sent callback function to call for this pcb when data is successfully sent + */ +void +tcp_sent(struct tcp_pcb *pcb, tcp_sent_fn sent) +{ + pcb->sent = sent; +} + +/** + * Used to specify the function that should be called when a fatal error + * has occured on the connection. + * + * @param pcb tcp_pcb to set the err callback + * @param err callback function to call for this pcb when a fatal error + * has occured on the connection + */ +void +tcp_err(struct tcp_pcb *pcb, tcp_err_fn err) +{ + pcb->errf = err; +} + +/** + * Used for specifying the function that should be called when a + * LISTENing connection has been connected to another host. + * + * @param pcb tcp_pcb to set the accept callback + * @param accept callback function to call for this pcb when LISTENing + * connection has been connected to another host + */ +void +tcp_accept(struct tcp_pcb *pcb, tcp_accept_fn accept) +{ + pcb->accept = accept; +} +#endif /* LWIP_CALLBACK_API */ + + +/** + * Used to specify the function that should be called periodically + * from TCP. The interval is specified in terms of the TCP coarse + * timer interval, which is called twice a second. + * + */ +void +tcp_poll(struct tcp_pcb *pcb, tcp_poll_fn poll, u8_t interval) +{ +#if LWIP_CALLBACK_API + pcb->poll = poll; +#else /* LWIP_CALLBACK_API */ + LWIP_UNUSED_ARG(poll); +#endif /* LWIP_CALLBACK_API */ + pcb->pollinterval = interval; +} + +/** + * Purges a TCP PCB. Removes any buffered data and frees the buffer memory + * (pcb->ooseq, pcb->unsent and pcb->unacked are freed). + * + * @param pcb tcp_pcb to purge. The pcb itself is not deallocated! + */ +void +tcp_pcb_purge(struct tcp_pcb *pcb) +{ + if (pcb->state != CLOSED && + pcb->state != TIME_WAIT && + pcb->state != LISTEN) { + + LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge\n")); + +#if TCP_LISTEN_BACKLOG + if (pcb->state == SYN_RCVD) { + /* Need to find the corresponding listen_pcb and decrease its accepts_pending */ + struct tcp_pcb_listen *lpcb; + LWIP_ASSERT("tcp_pcb_purge: pcb->state == SYN_RCVD but tcp_listen_pcbs is NULL", + tcp_listen_pcbs.listen_pcbs != NULL); + for (lpcb = tcp_listen_pcbs.listen_pcbs; lpcb != NULL; lpcb = lpcb->next) { + if ((lpcb->local_port == pcb->local_port) && + (ip_addr_isany(&lpcb->local_ip) || + ip_addr_cmp(&pcb->local_ip, &lpcb->local_ip))) { + /* port and address of the listen pcb match the timed-out pcb */ + LWIP_ASSERT("tcp_pcb_purge: listen pcb does not have accepts pending", + lpcb->accepts_pending > 0); + lpcb->accepts_pending--; + break; + } + } + } +#endif /* TCP_LISTEN_BACKLOG */ + + + if (pcb->refused_data != NULL) { + LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge: data left on ->refused_data\n")); + pbuf_free(pcb->refused_data); + pcb->refused_data = NULL; + } + if (pcb->unsent != NULL) { + LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge: not all data sent\n")); + } + if (pcb->unacked != NULL) { + LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge: data left on ->unacked\n")); + } +#if TCP_QUEUE_OOSEQ + if (pcb->ooseq != NULL) { + LWIP_DEBUGF(TCP_DEBUG, ("tcp_pcb_purge: data left on ->ooseq\n")); + } + tcp_segs_free(pcb->ooseq); + pcb->ooseq = NULL; +#endif /* TCP_QUEUE_OOSEQ */ + + /* Stop the retransmission timer as it will expect data on unacked + queue if it fires */ + pcb->rtime = -1; + + tcp_segs_free(pcb->unsent); + tcp_segs_free(pcb->unacked); + pcb->unacked = pcb->unsent = NULL; +#if TCP_OVERSIZE + pcb->unsent_oversize = 0; +#endif /* TCP_OVERSIZE */ + } +} + +/** + * Purges the PCB and removes it from a PCB list. Any delayed ACKs are sent first. + * + * @param pcblist PCB list to purge. + * @param pcb tcp_pcb to purge. The pcb itself is NOT deallocated! + */ +void +tcp_pcb_remove(struct tcp_pcb **pcblist, struct tcp_pcb *pcb) +{ + TCP_RMV(pcblist, pcb); + + tcp_pcb_purge(pcb); + + /* if there is an outstanding delayed ACKs, send it */ + if (pcb->state != TIME_WAIT && + pcb->state != LISTEN && + pcb->flags & TF_ACK_DELAY) { + pcb->flags |= TF_ACK_NOW; + tcp_output(pcb); + } + + if (pcb->state != LISTEN) { + LWIP_ASSERT("unsent segments leaking", pcb->unsent == NULL); + LWIP_ASSERT("unacked segments leaking", pcb->unacked == NULL); +#if TCP_QUEUE_OOSEQ + LWIP_ASSERT("ooseq segments leaking", pcb->ooseq == NULL); +#endif /* TCP_QUEUE_OOSEQ */ + } + + pcb->state = CLOSED; + + LWIP_ASSERT("tcp_pcb_remove: tcp_pcbs_sane()", tcp_pcbs_sane()); +} + +/** + * Calculates a new initial sequence number for new connections. + * + * @return u32_t pseudo random sequence number + */ +u32_t +tcp_next_iss(void) +{ + static u32_t iss = 6510; + + iss += tcp_ticks; /* XXX */ + return iss; +} + +#if TCP_CALCULATE_EFF_SEND_MSS +/** + * Calcluates the effective send mss that can be used for a specific IP address + * by using ip_route to determin the netif used to send to the address and + * calculating the minimum of TCP_MSS and that netif's mtu (if set). + */ +u16_t +tcp_eff_send_mss(u16_t sendmss, ip_addr_t *addr) +{ + u16_t mss_s; + struct netif *outif; + + outif = ip_route(addr); + if ((outif != NULL) && (outif->mtu != 0)) { + mss_s = outif->mtu - IP_HLEN - TCP_HLEN; + /* RFC 1122, chap 4.2.2.6: + * Eff.snd.MSS = min(SendMSS+20, MMS_S) - TCPhdrsize - IPoptionsize + * We correct for TCP options in tcp_write(), and don't support IP options. + */ + sendmss = LWIP_MIN(sendmss, mss_s); + } + return sendmss; +} +#endif /* TCP_CALCULATE_EFF_SEND_MSS */ + +const char* +tcp_debug_state_str(enum tcp_state s) +{ + return tcp_state_str[s]; +} + +#if TCP_DEBUG || TCP_INPUT_DEBUG || TCP_OUTPUT_DEBUG +/** + * Print a tcp header for debugging purposes. + * + * @param tcphdr pointer to a struct tcp_hdr + */ +void +tcp_debug_print(struct tcp_hdr *tcphdr) +{ + LWIP_DEBUGF(TCP_DEBUG, ("TCP header:\n")); + LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n")); + LWIP_DEBUGF(TCP_DEBUG, ("| %5"U16_F" | %5"U16_F" | (src port, dest port)\n", + ntohs(tcphdr->src), ntohs(tcphdr->dest))); + LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n")); + LWIP_DEBUGF(TCP_DEBUG, ("| %010"U32_F" | (seq no)\n", + ntohl(tcphdr->seqno))); + LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n")); + LWIP_DEBUGF(TCP_DEBUG, ("| %010"U32_F" | (ack no)\n", + ntohl(tcphdr->ackno))); + LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n")); + LWIP_DEBUGF(TCP_DEBUG, ("| %2"U16_F" | |%"U16_F"%"U16_F"%"U16_F"%"U16_F"%"U16_F"%"U16_F"| %5"U16_F" | (hdrlen, flags (", + TCPH_HDRLEN(tcphdr), + TCPH_FLAGS(tcphdr) >> 5 & 1, + TCPH_FLAGS(tcphdr) >> 4 & 1, + TCPH_FLAGS(tcphdr) >> 3 & 1, + TCPH_FLAGS(tcphdr) >> 2 & 1, + TCPH_FLAGS(tcphdr) >> 1 & 1, + TCPH_FLAGS(tcphdr) & 1, + ntohs(tcphdr->wnd))); + tcp_debug_print_flags(TCPH_FLAGS(tcphdr)); + LWIP_DEBUGF(TCP_DEBUG, ("), win)\n")); + LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n")); + LWIP_DEBUGF(TCP_DEBUG, ("| 0x%04"X16_F" | %5"U16_F" | (chksum, urgp)\n", + ntohs(tcphdr->chksum), ntohs(tcphdr->urgp))); + LWIP_DEBUGF(TCP_DEBUG, ("+-------------------------------+\n")); +} + +/** + * Print a tcp state for debugging purposes. + * + * @param s enum tcp_state to print + */ +void +tcp_debug_print_state(enum tcp_state s) +{ + LWIP_DEBUGF(TCP_DEBUG, ("State: %s\n", tcp_state_str[s])); +} + +/** + * Print tcp flags for debugging purposes. + * + * @param flags tcp flags, all active flags are printed + */ +void +tcp_debug_print_flags(u8_t flags) +{ + if (flags & TCP_FIN) { + LWIP_DEBUGF(TCP_DEBUG, ("FIN ")); + } + if (flags & TCP_SYN) { + LWIP_DEBUGF(TCP_DEBUG, ("SYN ")); + } + if (flags & TCP_RST) { + LWIP_DEBUGF(TCP_DEBUG, ("RST ")); + } + if (flags & TCP_PSH) { + LWIP_DEBUGF(TCP_DEBUG, ("PSH ")); + } + if (flags & TCP_ACK) { + LWIP_DEBUGF(TCP_DEBUG, ("ACK ")); + } + if (flags & TCP_URG) { + LWIP_DEBUGF(TCP_DEBUG, ("URG ")); + } + if (flags & TCP_ECE) { + LWIP_DEBUGF(TCP_DEBUG, ("ECE ")); + } + if (flags & TCP_CWR) { + LWIP_DEBUGF(TCP_DEBUG, ("CWR ")); + } + LWIP_DEBUGF(TCP_DEBUG, ("\n")); +} + +/** + * Print all tcp_pcbs in every list for debugging purposes. + */ +void +tcp_debug_print_pcbs(void) +{ + struct tcp_pcb *pcb; + LWIP_DEBUGF(TCP_DEBUG, ("Active PCB states:\n")); + for(pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) { + LWIP_DEBUGF(TCP_DEBUG, ("Local port %"U16_F", foreign port %"U16_F" snd_nxt %"U32_F" rcv_nxt %"U32_F" ", + pcb->local_port, pcb->remote_port, + pcb->snd_nxt, pcb->rcv_nxt)); + tcp_debug_print_state(pcb->state); + } + LWIP_DEBUGF(TCP_DEBUG, ("Listen PCB states:\n")); + for(pcb = (struct tcp_pcb *)tcp_listen_pcbs.pcbs; pcb != NULL; pcb = pcb->next) { + LWIP_DEBUGF(TCP_DEBUG, ("Local port %"U16_F", foreign port %"U16_F" snd_nxt %"U32_F" rcv_nxt %"U32_F" ", + pcb->local_port, pcb->remote_port, + pcb->snd_nxt, pcb->rcv_nxt)); + tcp_debug_print_state(pcb->state); + } + LWIP_DEBUGF(TCP_DEBUG, ("TIME-WAIT PCB states:\n")); + for(pcb = tcp_tw_pcbs; pcb != NULL; pcb = pcb->next) { + LWIP_DEBUGF(TCP_DEBUG, ("Local port %"U16_F", foreign port %"U16_F" snd_nxt %"U32_F" rcv_nxt %"U32_F" ", + pcb->local_port, pcb->remote_port, + pcb->snd_nxt, pcb->rcv_nxt)); + tcp_debug_print_state(pcb->state); + } +} + +/** + * Check state consistency of the tcp_pcb lists. + */ +s16_t +tcp_pcbs_sane(void) +{ + struct tcp_pcb *pcb; + for(pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) { + LWIP_ASSERT("tcp_pcbs_sane: active pcb->state != CLOSED", pcb->state != CLOSED); + LWIP_ASSERT("tcp_pcbs_sane: active pcb->state != LISTEN", pcb->state != LISTEN); + LWIP_ASSERT("tcp_pcbs_sane: active pcb->state != TIME-WAIT", pcb->state != TIME_WAIT); + } + for(pcb = tcp_tw_pcbs; pcb != NULL; pcb = pcb->next) { + LWIP_ASSERT("tcp_pcbs_sane: tw pcb->state == TIME-WAIT", pcb->state == TIME_WAIT); + } + return 1; +} +#endif /* TCP_DEBUG */ + +#endif /* LWIP_TCP */ diff --git a/features/unsupported/net/lwip/lwip/core/tcp_in.c b/features/unsupported/net/lwip/lwip/core/tcp_in.c new file mode 100644 index 00000000000..90952648d7f --- /dev/null +++ b/features/unsupported/net/lwip/lwip/core/tcp_in.c @@ -0,0 +1,1567 @@ +/** + * @file + * Transmission Control Protocol, incoming traffic + * + * The input processing functions of the TCP layer. + * + * These functions are generally called in the order (ip_input() ->) + * tcp_input() -> * tcp_process() -> tcp_receive() (-> application). + * + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ + +#include "lwip/opt.h" + +#if LWIP_TCP /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/tcp_impl.h" +#include "lwip/def.h" +#include "lwip/ip_addr.h" +#include "lwip/netif.h" +#include "lwip/mem.h" +#include "lwip/memp.h" +#include "lwip/inet_chksum.h" +#include "lwip/stats.h" +#include "lwip/snmp.h" +#include "arch/perf.h" + +/* These variables are global to all functions involved in the input + processing of TCP segments. They are set by the tcp_input() + function. */ +static struct tcp_seg inseg; +static struct tcp_hdr *tcphdr; +static struct ip_hdr *iphdr; +static u32_t seqno, ackno; +static u8_t flags; +static u16_t tcplen; + +static u8_t recv_flags; +static struct pbuf *recv_data; + +struct tcp_pcb *tcp_input_pcb; + +/* Forward declarations. */ +static err_t tcp_process(struct tcp_pcb *pcb); +static void tcp_receive(struct tcp_pcb *pcb); +static void tcp_parseopt(struct tcp_pcb *pcb); + +static err_t tcp_listen_input(struct tcp_pcb_listen *pcb); +static err_t tcp_timewait_input(struct tcp_pcb *pcb); + +/** + * The initial input processing of TCP. It verifies the TCP header, demultiplexes + * the segment between the PCBs and passes it on to tcp_process(), which implements + * the TCP finite state machine. This function is called by the IP layer (in + * ip_input()). + * + * @param p received TCP segment to process (p->payload pointing to the IP header) + * @param inp network interface on which this segment was received + */ +void +tcp_input(struct pbuf *p, struct netif *inp) +{ + struct tcp_pcb *pcb, *prev; + struct tcp_pcb_listen *lpcb; +#if SO_REUSE + struct tcp_pcb *lpcb_prev = NULL; + struct tcp_pcb_listen *lpcb_any = NULL; +#endif /* SO_REUSE */ + u8_t hdrlen; + err_t err; + + PERF_START; + + TCP_STATS_INC(tcp.recv); + snmp_inc_tcpinsegs(); + + iphdr = (struct ip_hdr *)p->payload; + tcphdr = (struct tcp_hdr *)((u8_t *)p->payload + IPH_HL(iphdr) * 4); + +#if TCP_INPUT_DEBUG + tcp_debug_print(tcphdr); +#endif + + /* remove header from payload */ + if (pbuf_header(p, -((s16_t)(IPH_HL(iphdr) * 4))) || (p->tot_len < sizeof(struct tcp_hdr))) { + /* drop short packets */ + LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_input: short packet (%"U16_F" bytes) discarded\n", p->tot_len)); + TCP_STATS_INC(tcp.lenerr); + TCP_STATS_INC(tcp.drop); + snmp_inc_tcpinerrs(); + pbuf_free(p); + return; + } + + /* Don't even process incoming broadcasts/multicasts. */ + if (ip_addr_isbroadcast(¤t_iphdr_dest, inp) || + ip_addr_ismulticast(¤t_iphdr_dest)) { + TCP_STATS_INC(tcp.proterr); + TCP_STATS_INC(tcp.drop); + snmp_inc_tcpinerrs(); + pbuf_free(p); + return; + } + +#if CHECKSUM_CHECK_TCP + /* Verify TCP checksum. */ + if (inet_chksum_pseudo(p, ip_current_src_addr(), ip_current_dest_addr(), + IP_PROTO_TCP, p->tot_len) != 0) { + LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_input: packet discarded due to failing checksum 0x%04"X16_F"\n", + inet_chksum_pseudo(p, ip_current_src_addr(), ip_current_dest_addr(), + IP_PROTO_TCP, p->tot_len))); +#if TCP_DEBUG + tcp_debug_print(tcphdr); +#endif /* TCP_DEBUG */ + TCP_STATS_INC(tcp.chkerr); + TCP_STATS_INC(tcp.drop); + snmp_inc_tcpinerrs(); + pbuf_free(p); + return; + } +#endif + + /* Move the payload pointer in the pbuf so that it points to the + TCP data instead of the TCP header. */ + hdrlen = TCPH_HDRLEN(tcphdr); + if(pbuf_header(p, -(hdrlen * 4))){ + /* drop short packets */ + LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_input: short packet\n")); + TCP_STATS_INC(tcp.lenerr); + TCP_STATS_INC(tcp.drop); + snmp_inc_tcpinerrs(); + pbuf_free(p); + return; + } + + /* Convert fields in TCP header to host byte order. */ + tcphdr->src = ntohs(tcphdr->src); + tcphdr->dest = ntohs(tcphdr->dest); + seqno = tcphdr->seqno = ntohl(tcphdr->seqno); + ackno = tcphdr->ackno = ntohl(tcphdr->ackno); + tcphdr->wnd = ntohs(tcphdr->wnd); + + flags = TCPH_FLAGS(tcphdr); + tcplen = p->tot_len + ((flags & (TCP_FIN | TCP_SYN)) ? 1 : 0); + + /* Demultiplex an incoming segment. First, we check if it is destined + for an active connection. */ + prev = NULL; + + + for(pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) { + LWIP_ASSERT("tcp_input: active pcb->state != CLOSED", pcb->state != CLOSED); + LWIP_ASSERT("tcp_input: active pcb->state != TIME-WAIT", pcb->state != TIME_WAIT); + LWIP_ASSERT("tcp_input: active pcb->state != LISTEN", pcb->state != LISTEN); + if (pcb->remote_port == tcphdr->src && + pcb->local_port == tcphdr->dest && + ip_addr_cmp(&(pcb->remote_ip), ¤t_iphdr_src) && + ip_addr_cmp(&(pcb->local_ip), ¤t_iphdr_dest)) { + + /* Move this PCB to the front of the list so that subsequent + lookups will be faster (we exploit locality in TCP segment + arrivals). */ + LWIP_ASSERT("tcp_input: pcb->next != pcb (before cache)", pcb->next != pcb); + if (prev != NULL) { + prev->next = pcb->next; + pcb->next = tcp_active_pcbs; + tcp_active_pcbs = pcb; + } + LWIP_ASSERT("tcp_input: pcb->next != pcb (after cache)", pcb->next != pcb); + break; + } + prev = pcb; + } + + if (pcb == NULL) { + /* If it did not go to an active connection, we check the connections + in the TIME-WAIT state. */ + for(pcb = tcp_tw_pcbs; pcb != NULL; pcb = pcb->next) { + LWIP_ASSERT("tcp_input: TIME-WAIT pcb->state == TIME-WAIT", pcb->state == TIME_WAIT); + if (pcb->remote_port == tcphdr->src && + pcb->local_port == tcphdr->dest && + ip_addr_cmp(&(pcb->remote_ip), ¤t_iphdr_src) && + ip_addr_cmp(&(pcb->local_ip), ¤t_iphdr_dest)) { + /* We don't really care enough to move this PCB to the front + of the list since we are not very likely to receive that + many segments for connections in TIME-WAIT. */ + LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_input: packed for TIME_WAITing connection.\n")); + tcp_timewait_input(pcb); + pbuf_free(p); + return; + } + } + + /* Finally, if we still did not get a match, we check all PCBs that + are LISTENing for incoming connections. */ + prev = NULL; + for(lpcb = tcp_listen_pcbs.listen_pcbs; lpcb != NULL; lpcb = lpcb->next) { + if (lpcb->local_port == tcphdr->dest) { +#if SO_REUSE + if (ip_addr_cmp(&(lpcb->local_ip), ¤t_iphdr_dest)) { + /* found an exact match */ + break; + } else if(ip_addr_isany(&(lpcb->local_ip))) { + /* found an ANY-match */ + lpcb_any = lpcb; + lpcb_prev = prev; + } +#else /* SO_REUSE */ + if (ip_addr_cmp(&(lpcb->local_ip), ¤t_iphdr_dest) || + ip_addr_isany(&(lpcb->local_ip))) { + /* found a match */ + break; + } +#endif /* SO_REUSE */ + } + prev = (struct tcp_pcb *)lpcb; + } +#if SO_REUSE + /* first try specific local IP */ + if (lpcb == NULL) { + /* only pass to ANY if no specific local IP has been found */ + lpcb = lpcb_any; + prev = lpcb_prev; + } +#endif /* SO_REUSE */ + if (lpcb != NULL) { + /* Move this PCB to the front of the list so that subsequent + lookups will be faster (we exploit locality in TCP segment + arrivals). */ + if (prev != NULL) { + ((struct tcp_pcb_listen *)prev)->next = lpcb->next; + /* our successor is the remainder of the listening list */ + lpcb->next = tcp_listen_pcbs.listen_pcbs; + /* put this listening pcb at the head of the listening list */ + tcp_listen_pcbs.listen_pcbs = lpcb; + } + + LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_input: packed for LISTENing connection.\n")); + tcp_listen_input(lpcb); + pbuf_free(p); + return; + } + } + +#if TCP_INPUT_DEBUG + LWIP_DEBUGF(TCP_INPUT_DEBUG, ("+-+-+-+-+-+-+-+-+-+-+-+-+-+- tcp_input: flags ")); + tcp_debug_print_flags(TCPH_FLAGS(tcphdr)); + LWIP_DEBUGF(TCP_INPUT_DEBUG, ("-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n")); +#endif /* TCP_INPUT_DEBUG */ + + + if (pcb != NULL) { + /* The incoming segment belongs to a connection. */ +#if TCP_INPUT_DEBUG +#if TCP_DEBUG + tcp_debug_print_state(pcb->state); +#endif /* TCP_DEBUG */ +#endif /* TCP_INPUT_DEBUG */ + + /* Set up a tcp_seg structure. */ + inseg.next = NULL; + inseg.len = p->tot_len; + inseg.p = p; + inseg.tcphdr = tcphdr; + + recv_data = NULL; + recv_flags = 0; + + /* If there is data which was previously "refused" by upper layer */ + if (pcb->refused_data != NULL) { + /* Notify again application with data previously received. */ + LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_input: notify kept packet\n")); + TCP_EVENT_RECV(pcb, pcb->refused_data, ERR_OK, err); + if (err == ERR_OK) { + pcb->refused_data = NULL; + } else if ((err == ERR_ABRT) || (tcplen > 0)) { + /* if err == ERR_ABRT, 'pcb' is already deallocated */ + /* Drop incoming packets because pcb is "full" (only if the incoming + segment contains data). */ + LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_input: drop incoming packets, because pcb is \"full\"\n")); + TCP_STATS_INC(tcp.drop); + snmp_inc_tcpinerrs(); + pbuf_free(p); + return; + } + } + tcp_input_pcb = pcb; + err = tcp_process(pcb); + /* A return value of ERR_ABRT means that tcp_abort() was called + and that the pcb has been freed. If so, we don't do anything. */ + if (err != ERR_ABRT) { + if (recv_flags & TF_RESET) { + /* TF_RESET means that the connection was reset by the other + end. We then call the error callback to inform the + application that the connection is dead before we + deallocate the PCB. */ + TCP_EVENT_ERR(pcb->errf, pcb->callback_arg, ERR_RST); + tcp_pcb_remove(&tcp_active_pcbs, pcb); + memp_free(MEMP_TCP_PCB, pcb); + } else if (recv_flags & TF_CLOSED) { + /* The connection has been closed and we will deallocate the + PCB. */ + tcp_pcb_remove(&tcp_active_pcbs, pcb); + memp_free(MEMP_TCP_PCB, pcb); + } else { + err = ERR_OK; + /* If the application has registered a "sent" function to be + called when new send buffer space is available, we call it + now. */ + if (pcb->acked > 0) { + TCP_EVENT_SENT(pcb, pcb->acked, err); + if (err == ERR_ABRT) { + goto aborted; + } + } + + if (recv_data != NULL) { + LWIP_ASSERT("pcb->refused_data == NULL", pcb->refused_data == NULL); + if (pcb->flags & TF_RXCLOSED) { + /* received data although already closed -> abort (send RST) to + notify the remote host that not all data has been processed */ + pbuf_free(recv_data); + tcp_abort(pcb); + goto aborted; + } + if (flags & TCP_PSH) { + recv_data->flags |= PBUF_FLAG_PUSH; + } + + /* Notify application that data has been received. */ + TCP_EVENT_RECV(pcb, recv_data, ERR_OK, err); + if (err == ERR_ABRT) { + goto aborted; + } + + /* If the upper layer can't receive this data, store it */ + if (err != ERR_OK) { + pcb->refused_data = recv_data; + LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_input: keep incoming packet, because pcb is \"full\"\n")); + } + } + + /* If a FIN segment was received, we call the callback + function with a NULL buffer to indicate EOF. */ + if (recv_flags & TF_GOT_FIN) { + /* correct rcv_wnd as the application won't call tcp_recved() + for the FIN's seqno */ + if (pcb->rcv_wnd != TCP_WND) { + pcb->rcv_wnd++; + } + TCP_EVENT_CLOSED(pcb, err); + if (err == ERR_ABRT) { + goto aborted; + } + } + + tcp_input_pcb = NULL; + /* Try to send something out. */ + tcp_output(pcb); +#if TCP_INPUT_DEBUG +#if TCP_DEBUG + tcp_debug_print_state(pcb->state); +#endif /* TCP_DEBUG */ +#endif /* TCP_INPUT_DEBUG */ + } + } + /* Jump target if pcb has been aborted in a callback (by calling tcp_abort()). + Below this line, 'pcb' may not be dereferenced! */ +aborted: + tcp_input_pcb = NULL; + recv_data = NULL; + + /* give up our reference to inseg.p */ + if (inseg.p != NULL) + { + pbuf_free(inseg.p); + inseg.p = NULL; + } + } else { + + /* If no matching PCB was found, send a TCP RST (reset) to the + sender. */ + LWIP_DEBUGF(TCP_RST_DEBUG, ("tcp_input: no PCB match found, resetting.\n")); + if (!(TCPH_FLAGS(tcphdr) & TCP_RST)) { + TCP_STATS_INC(tcp.proterr); + TCP_STATS_INC(tcp.drop); + tcp_rst(ackno, seqno + tcplen, + ip_current_dest_addr(), ip_current_src_addr(), + tcphdr->dest, tcphdr->src); + } + pbuf_free(p); + } + + LWIP_ASSERT("tcp_input: tcp_pcbs_sane()", tcp_pcbs_sane()); + PERF_STOP("tcp_input"); +} + +/** + * Called by tcp_input() when a segment arrives for a listening + * connection (from tcp_input()). + * + * @param pcb the tcp_pcb_listen for which a segment arrived + * @return ERR_OK if the segment was processed + * another err_t on error + * + * @note the return value is not (yet?) used in tcp_input() + * @note the segment which arrived is saved in global variables, therefore only the pcb + * involved is passed as a parameter to this function + */ +static err_t +tcp_listen_input(struct tcp_pcb_listen *pcb) +{ + struct tcp_pcb *npcb; + err_t rc; + + /* In the LISTEN state, we check for incoming SYN segments, + creates a new PCB, and responds with a SYN|ACK. */ + if (flags & TCP_ACK) { + /* For incoming segments with the ACK flag set, respond with a + RST. */ + LWIP_DEBUGF(TCP_RST_DEBUG, ("tcp_listen_input: ACK in LISTEN, sending reset\n")); + tcp_rst(ackno + 1, seqno + tcplen, + ip_current_dest_addr(), ip_current_src_addr(), + tcphdr->dest, tcphdr->src); + } else if (flags & TCP_SYN) { + LWIP_DEBUGF(TCP_DEBUG, ("TCP connection request %"U16_F" -> %"U16_F".\n", tcphdr->src, tcphdr->dest)); +#if TCP_LISTEN_BACKLOG + if (pcb->accepts_pending >= pcb->backlog) { + LWIP_DEBUGF(TCP_DEBUG, ("tcp_listen_input: listen backlog exceeded for port %"U16_F"\n", tcphdr->dest)); + return ERR_ABRT; + } +#endif /* TCP_LISTEN_BACKLOG */ + npcb = tcp_alloc(pcb->prio); + /* If a new PCB could not be created (probably due to lack of memory), + we don't do anything, but rely on the sender will retransmit the + SYN at a time when we have more memory available. */ + if (npcb == NULL) { + LWIP_DEBUGF(TCP_DEBUG, ("tcp_listen_input: could not allocate PCB\n")); + TCP_STATS_INC(tcp.memerr); + return ERR_MEM; + } +#if TCP_LISTEN_BACKLOG + pcb->accepts_pending++; +#endif /* TCP_LISTEN_BACKLOG */ + /* Set up the new PCB. */ + ip_addr_copy(npcb->local_ip, current_iphdr_dest); + npcb->local_port = pcb->local_port; + ip_addr_copy(npcb->remote_ip, current_iphdr_src); + npcb->remote_port = tcphdr->src; + npcb->state = SYN_RCVD; + npcb->rcv_nxt = seqno + 1; + npcb->rcv_ann_right_edge = npcb->rcv_nxt; + npcb->snd_wnd = tcphdr->wnd; + npcb->ssthresh = npcb->snd_wnd; + npcb->snd_wl1 = seqno - 1;/* initialise to seqno-1 to force window update */ + npcb->callback_arg = pcb->callback_arg; +#if LWIP_CALLBACK_API + npcb->accept = pcb->accept; +#endif /* LWIP_CALLBACK_API */ + /* inherit socket options */ + npcb->so_options = pcb->so_options & SOF_INHERITED; + /* Register the new PCB so that we can begin receiving segments + for it. */ + TCP_REG(&tcp_active_pcbs, npcb); + + /* Parse any options in the SYN. */ + tcp_parseopt(npcb); +#if TCP_CALCULATE_EFF_SEND_MSS + npcb->mss = tcp_eff_send_mss(npcb->mss, &(npcb->remote_ip)); +#endif /* TCP_CALCULATE_EFF_SEND_MSS */ + + snmp_inc_tcppassiveopens(); + + /* Send a SYN|ACK together with the MSS option. */ + rc = tcp_enqueue_flags(npcb, TCP_SYN | TCP_ACK); + if (rc != ERR_OK) { + tcp_abandon(npcb, 0); + return rc; + } + return tcp_output(npcb); + } + return ERR_OK; +} + +/** + * Called by tcp_input() when a segment arrives for a connection in + * TIME_WAIT. + * + * @param pcb the tcp_pcb for which a segment arrived + * + * @note the segment which arrived is saved in global variables, therefore only the pcb + * involved is passed as a parameter to this function + */ +static err_t +tcp_timewait_input(struct tcp_pcb *pcb) +{ + /* RFC 1337: in TIME_WAIT, ignore RST and ACK FINs + any 'acceptable' segments */ + /* RFC 793 3.9 Event Processing - Segment Arrives: + * - first check sequence number - we skip that one in TIME_WAIT (always + * acceptable since we only send ACKs) + * - second check the RST bit (... return) */ + if (flags & TCP_RST) { + return ERR_OK; + } + /* - fourth, check the SYN bit, */ + if (flags & TCP_SYN) { + /* If an incoming segment is not acceptable, an acknowledgment + should be sent in reply */ + if (TCP_SEQ_BETWEEN(seqno, pcb->rcv_nxt, pcb->rcv_nxt+pcb->rcv_wnd)) { + /* If the SYN is in the window it is an error, send a reset */ + tcp_rst(ackno, seqno + tcplen, ip_current_dest_addr(), ip_current_src_addr(), + tcphdr->dest, tcphdr->src); + return ERR_OK; + } + } else if (flags & TCP_FIN) { + /* - eighth, check the FIN bit: Remain in the TIME-WAIT state. + Restart the 2 MSL time-wait timeout.*/ + pcb->tmr = tcp_ticks; + } + + if ((tcplen > 0)) { + /* Acknowledge data, FIN or out-of-window SYN */ + pcb->flags |= TF_ACK_NOW; + return tcp_output(pcb); + } + return ERR_OK; +} + +/** + * Implements the TCP state machine. Called by tcp_input. In some + * states tcp_receive() is called to receive data. The tcp_seg + * argument will be freed by the caller (tcp_input()) unless the + * recv_data pointer in the pcb is set. + * + * @param pcb the tcp_pcb for which a segment arrived + * + * @note the segment which arrived is saved in global variables, therefore only the pcb + * involved is passed as a parameter to this function + */ +static err_t +tcp_process(struct tcp_pcb *pcb) +{ + struct tcp_seg *rseg; + u8_t acceptable = 0; + err_t err; + + err = ERR_OK; + + /* Process incoming RST segments. */ + if (flags & TCP_RST) { + /* First, determine if the reset is acceptable. */ + if (pcb->state == SYN_SENT) { + if (ackno == pcb->snd_nxt) { + acceptable = 1; + } + } else { + if (TCP_SEQ_BETWEEN(seqno, pcb->rcv_nxt, + pcb->rcv_nxt+pcb->rcv_wnd)) { + acceptable = 1; + } + } + + if (acceptable) { + LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_process: Connection RESET\n")); + LWIP_ASSERT("tcp_input: pcb->state != CLOSED", pcb->state != CLOSED); + recv_flags |= TF_RESET; + pcb->flags &= ~TF_ACK_DELAY; + return ERR_RST; + } else { + LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_process: unacceptable reset seqno %"U32_F" rcv_nxt %"U32_F"\n", + seqno, pcb->rcv_nxt)); + LWIP_DEBUGF(TCP_DEBUG, ("tcp_process: unacceptable reset seqno %"U32_F" rcv_nxt %"U32_F"\n", + seqno, pcb->rcv_nxt)); + return ERR_OK; + } + } + + if ((flags & TCP_SYN) && (pcb->state != SYN_SENT && pcb->state != SYN_RCVD)) { + /* Cope with new connection attempt after remote end crashed */ + tcp_ack_now(pcb); + return ERR_OK; + } + + if ((pcb->flags & TF_RXCLOSED) == 0) { + /* Update the PCB (in)activity timer unless rx is closed (see tcp_shutdown) */ + pcb->tmr = tcp_ticks; + } + pcb->keep_cnt_sent = 0; + + tcp_parseopt(pcb); + + /* Do different things depending on the TCP state. */ + switch (pcb->state) { + case SYN_SENT: + LWIP_DEBUGF(TCP_INPUT_DEBUG, ("SYN-SENT: ackno %"U32_F" pcb->snd_nxt %"U32_F" unacked %"U32_F"\n", ackno, + pcb->snd_nxt, ntohl(pcb->unacked->tcphdr->seqno))); + /* received SYN ACK with expected sequence number? */ + if ((flags & TCP_ACK) && (flags & TCP_SYN) + && ackno == ntohl(pcb->unacked->tcphdr->seqno) + 1) { + pcb->snd_buf++; + pcb->rcv_nxt = seqno + 1; + pcb->rcv_ann_right_edge = pcb->rcv_nxt; + pcb->lastack = ackno; + pcb->snd_wnd = tcphdr->wnd; + pcb->snd_wl1 = seqno - 1; /* initialise to seqno - 1 to force window update */ + pcb->state = ESTABLISHED; + +#if TCP_CALCULATE_EFF_SEND_MSS + pcb->mss = tcp_eff_send_mss(pcb->mss, &(pcb->remote_ip)); +#endif /* TCP_CALCULATE_EFF_SEND_MSS */ + + /* Set ssthresh again after changing pcb->mss (already set in tcp_connect + * but for the default value of pcb->mss) */ + pcb->ssthresh = pcb->mss * 10; + + pcb->cwnd = ((pcb->cwnd == 1) ? (pcb->mss * 2) : pcb->mss); + LWIP_ASSERT("pcb->snd_queuelen > 0", (pcb->snd_queuelen > 0)); + --pcb->snd_queuelen; + LWIP_DEBUGF(TCP_QLEN_DEBUG, ("tcp_process: SYN-SENT --queuelen %"U16_F"\n", (u16_t)pcb->snd_queuelen)); + rseg = pcb->unacked; + pcb->unacked = rseg->next; + + /* If there's nothing left to acknowledge, stop the retransmit + timer, otherwise reset it to start again */ + if(pcb->unacked == NULL) + pcb->rtime = -1; + else { + pcb->rtime = 0; + pcb->nrtx = 0; + } + + tcp_seg_free(rseg); + + /* Call the user specified function to call when sucessfully + * connected. */ + TCP_EVENT_CONNECTED(pcb, ERR_OK, err); + if (err == ERR_ABRT) { + return ERR_ABRT; + } + tcp_ack_now(pcb); + } + /* received ACK? possibly a half-open connection */ + else if (flags & TCP_ACK) { + /* send a RST to bring the other side in a non-synchronized state. */ + tcp_rst(ackno, seqno + tcplen, ip_current_dest_addr(), ip_current_src_addr(), + tcphdr->dest, tcphdr->src); + } + break; + case SYN_RCVD: + if (flags & TCP_ACK) { + /* expected ACK number? */ + if (TCP_SEQ_BETWEEN(ackno, pcb->lastack+1, pcb->snd_nxt)) { + u16_t old_cwnd; + pcb->state = ESTABLISHED; + LWIP_DEBUGF(TCP_DEBUG, ("TCP connection established %"U16_F" -> %"U16_F".\n", inseg.tcphdr->src, inseg.tcphdr->dest)); +#if LWIP_CALLBACK_API + LWIP_ASSERT("pcb->accept != NULL", pcb->accept != NULL); +#endif + /* Call the accept function. */ + TCP_EVENT_ACCEPT(pcb, ERR_OK, err); + if (err != ERR_OK) { + /* If the accept function returns with an error, we abort + * the connection. */ + /* Already aborted? */ + if (err != ERR_ABRT) { + tcp_abort(pcb); + } + return ERR_ABRT; + } + old_cwnd = pcb->cwnd; + /* If there was any data contained within this ACK, + * we'd better pass it on to the application as well. */ + tcp_receive(pcb); + + /* Prevent ACK for SYN to generate a sent event */ + if (pcb->acked != 0) { + pcb->acked--; + } + + pcb->cwnd = ((old_cwnd == 1) ? (pcb->mss * 2) : pcb->mss); + + if (recv_flags & TF_GOT_FIN) { + tcp_ack_now(pcb); + pcb->state = CLOSE_WAIT; + } + } else { + /* incorrect ACK number, send RST */ + tcp_rst(ackno, seqno + tcplen, ip_current_dest_addr(), ip_current_src_addr(), + tcphdr->dest, tcphdr->src); + } + } else if ((flags & TCP_SYN) && (seqno == pcb->rcv_nxt - 1)) { + /* Looks like another copy of the SYN - retransmit our SYN-ACK */ + tcp_rexmit(pcb); + } + break; + case CLOSE_WAIT: + /* FALLTHROUGH */ + case ESTABLISHED: + tcp_receive(pcb); + if (recv_flags & TF_GOT_FIN) { /* passive close */ + tcp_ack_now(pcb); + pcb->state = CLOSE_WAIT; + } + break; + case FIN_WAIT_1: + tcp_receive(pcb); + if (recv_flags & TF_GOT_FIN) { + if ((flags & TCP_ACK) && (ackno == pcb->snd_nxt)) { + LWIP_DEBUGF(TCP_DEBUG, + ("TCP connection closed: FIN_WAIT_1 %"U16_F" -> %"U16_F".\n", inseg.tcphdr->src, inseg.tcphdr->dest)); + tcp_ack_now(pcb); + tcp_pcb_purge(pcb); + TCP_RMV(&tcp_active_pcbs, pcb); + pcb->state = TIME_WAIT; + TCP_REG(&tcp_tw_pcbs, pcb); + } else { + tcp_ack_now(pcb); + pcb->state = CLOSING; + } + } else if ((flags & TCP_ACK) && (ackno == pcb->snd_nxt)) { + pcb->state = FIN_WAIT_2; + } + break; + case FIN_WAIT_2: + tcp_receive(pcb); + if (recv_flags & TF_GOT_FIN) { + LWIP_DEBUGF(TCP_DEBUG, ("TCP connection closed: FIN_WAIT_2 %"U16_F" -> %"U16_F".\n", inseg.tcphdr->src, inseg.tcphdr->dest)); + tcp_ack_now(pcb); + tcp_pcb_purge(pcb); + TCP_RMV(&tcp_active_pcbs, pcb); + pcb->state = TIME_WAIT; + TCP_REG(&tcp_tw_pcbs, pcb); + } + break; + case CLOSING: + tcp_receive(pcb); + if (flags & TCP_ACK && ackno == pcb->snd_nxt) { + LWIP_DEBUGF(TCP_DEBUG, ("TCP connection closed: CLOSING %"U16_F" -> %"U16_F".\n", inseg.tcphdr->src, inseg.tcphdr->dest)); + tcp_pcb_purge(pcb); + TCP_RMV(&tcp_active_pcbs, pcb); + pcb->state = TIME_WAIT; + TCP_REG(&tcp_tw_pcbs, pcb); + } + break; + case LAST_ACK: + tcp_receive(pcb); + if (flags & TCP_ACK && ackno == pcb->snd_nxt) { + LWIP_DEBUGF(TCP_DEBUG, ("TCP connection closed: LAST_ACK %"U16_F" -> %"U16_F".\n", inseg.tcphdr->src, inseg.tcphdr->dest)); + /* bugfix #21699: don't set pcb->state to CLOSED here or we risk leaking segments */ + recv_flags |= TF_CLOSED; + } + break; + default: + break; + } + return ERR_OK; +} + +#if TCP_QUEUE_OOSEQ +/** + * Insert segment into the list (segments covered with new one will be deleted) + * + * Called from tcp_receive() + */ +static void +tcp_oos_insert_segment(struct tcp_seg *cseg, struct tcp_seg *next) +{ + struct tcp_seg *old_seg; + + if (TCPH_FLAGS(cseg->tcphdr) & TCP_FIN) { + /* received segment overlaps all following segments */ + tcp_segs_free(next); + next = NULL; + } + else { + /* delete some following segments + oos queue may have segments with FIN flag */ + while (next && + TCP_SEQ_GEQ((seqno + cseg->len), + (next->tcphdr->seqno + next->len))) { + /* cseg with FIN already processed */ + if (TCPH_FLAGS(next->tcphdr) & TCP_FIN) { + TCPH_SET_FLAG(cseg->tcphdr, TCP_FIN); + } + old_seg = next; + next = next->next; + tcp_seg_free(old_seg); + } + if (next && + TCP_SEQ_GT(seqno + cseg->len, next->tcphdr->seqno)) { + /* We need to trim the incoming segment. */ + cseg->len = (u16_t)(next->tcphdr->seqno - seqno); + pbuf_realloc(cseg->p, cseg->len); + } + } + cseg->next = next; +} +#endif /* TCP_QUEUE_OOSEQ */ + +/** + * Called by tcp_process. Checks if the given segment is an ACK for outstanding + * data, and if so frees the memory of the buffered data. Next, is places the + * segment on any of the receive queues (pcb->recved or pcb->ooseq). If the segment + * is buffered, the pbuf is referenced by pbuf_ref so that it will not be freed until + * i it has been removed from the buffer. + * + * If the incoming segment constitutes an ACK for a segment that was used for RTT + * estimation, the RTT is estimated here as well. + * + * Called from tcp_process(). + */ +static void +tcp_receive(struct tcp_pcb *pcb) +{ + struct tcp_seg *next; +#if TCP_QUEUE_OOSEQ + struct tcp_seg *prev, *cseg; +#endif /* TCP_QUEUE_OOSEQ */ + struct pbuf *p; + s32_t off; + s16_t m; + u32_t right_wnd_edge; + u16_t new_tot_len; + int found_dupack = 0; + + if (flags & TCP_ACK) { + right_wnd_edge = pcb->snd_wnd + pcb->snd_wl2; + + /* Update window. */ + if (TCP_SEQ_LT(pcb->snd_wl1, seqno) || + (pcb->snd_wl1 == seqno && TCP_SEQ_LT(pcb->snd_wl2, ackno)) || + (pcb->snd_wl2 == ackno && tcphdr->wnd > pcb->snd_wnd)) { + pcb->snd_wnd = tcphdr->wnd; + pcb->snd_wl1 = seqno; + pcb->snd_wl2 = ackno; + if (pcb->snd_wnd > 0 && pcb->persist_backoff > 0) { + pcb->persist_backoff = 0; + } + LWIP_DEBUGF(TCP_WND_DEBUG, ("tcp_receive: window update %"U16_F"\n", pcb->snd_wnd)); +#if TCP_WND_DEBUG + } else { + if (pcb->snd_wnd != tcphdr->wnd) { + LWIP_DEBUGF(TCP_WND_DEBUG, + ("tcp_receive: no window update lastack %"U32_F" ackno %" + U32_F" wl1 %"U32_F" seqno %"U32_F" wl2 %"U32_F"\n", + pcb->lastack, ackno, pcb->snd_wl1, seqno, pcb->snd_wl2)); + } +#endif /* TCP_WND_DEBUG */ + } + + /* (From Stevens TCP/IP Illustrated Vol II, p970.) Its only a + * duplicate ack if: + * 1) It doesn't ACK new data + * 2) length of received packet is zero (i.e. no payload) + * 3) the advertised window hasn't changed + * 4) There is outstanding unacknowledged data (retransmission timer running) + * 5) The ACK is == biggest ACK sequence number so far seen (snd_una) + * + * If it passes all five, should process as a dupack: + * a) dupacks < 3: do nothing + * b) dupacks == 3: fast retransmit + * c) dupacks > 3: increase cwnd + * + * If it only passes 1-3, should reset dupack counter (and add to + * stats, which we don't do in lwIP) + * + * If it only passes 1, should reset dupack counter + * + */ + + /* Clause 1 */ + if (TCP_SEQ_LEQ(ackno, pcb->lastack)) { + pcb->acked = 0; + /* Clause 2 */ + if (tcplen == 0) { + /* Clause 3 */ + if (pcb->snd_wl2 + pcb->snd_wnd == right_wnd_edge){ + /* Clause 4 */ + if (pcb->rtime >= 0) { + /* Clause 5 */ + if (pcb->lastack == ackno) { + found_dupack = 1; + if (pcb->dupacks + 1 > pcb->dupacks) + ++pcb->dupacks; + if (pcb->dupacks > 3) { + /* Inflate the congestion window, but not if it means that + the value overflows. */ + if ((u16_t)(pcb->cwnd + pcb->mss) > pcb->cwnd) { + pcb->cwnd += pcb->mss; + } + } else if (pcb->dupacks == 3) { + /* Do fast retransmit */ + tcp_rexmit_fast(pcb); + } + } + } + } + } + /* If Clause (1) or more is true, but not a duplicate ack, reset + * count of consecutive duplicate acks */ + if (!found_dupack) { + pcb->dupacks = 0; + } + } else if (TCP_SEQ_BETWEEN(ackno, pcb->lastack+1, pcb->snd_nxt)){ + /* We come here when the ACK acknowledges new data. */ + + /* Reset the "IN Fast Retransmit" flag, since we are no longer + in fast retransmit. Also reset the congestion window to the + slow start threshold. */ + if (pcb->flags & TF_INFR) { + pcb->flags &= ~TF_INFR; + pcb->cwnd = pcb->ssthresh; + } + + /* Reset the number of retransmissions. */ + pcb->nrtx = 0; + + /* Reset the retransmission time-out. */ + pcb->rto = (pcb->sa >> 3) + pcb->sv; + + /* Update the send buffer space. Diff between the two can never exceed 64K? */ + pcb->acked = (u16_t)(ackno - pcb->lastack); + + pcb->snd_buf += pcb->acked; + + /* Reset the fast retransmit variables. */ + pcb->dupacks = 0; + pcb->lastack = ackno; + + /* Update the congestion control variables (cwnd and + ssthresh). */ + if (pcb->state >= ESTABLISHED) { + if (pcb->cwnd < pcb->ssthresh) { + if ((u16_t)(pcb->cwnd + pcb->mss) > pcb->cwnd) { + pcb->cwnd += pcb->mss; + } + LWIP_DEBUGF(TCP_CWND_DEBUG, ("tcp_receive: slow start cwnd %"U16_F"\n", pcb->cwnd)); + } else { + u16_t new_cwnd = (pcb->cwnd + pcb->mss * pcb->mss / pcb->cwnd); + if (new_cwnd > pcb->cwnd) { + pcb->cwnd = new_cwnd; + } + LWIP_DEBUGF(TCP_CWND_DEBUG, ("tcp_receive: congestion avoidance cwnd %"U16_F"\n", pcb->cwnd)); + } + } + LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_receive: ACK for %"U32_F", unacked->seqno %"U32_F":%"U32_F"\n", + ackno, + pcb->unacked != NULL? + ntohl(pcb->unacked->tcphdr->seqno): 0, + pcb->unacked != NULL? + ntohl(pcb->unacked->tcphdr->seqno) + TCP_TCPLEN(pcb->unacked): 0)); + + /* Remove segment from the unacknowledged list if the incoming + ACK acknowlegdes them. */ + while (pcb->unacked != NULL && + TCP_SEQ_LEQ(ntohl(pcb->unacked->tcphdr->seqno) + + TCP_TCPLEN(pcb->unacked), ackno)) { + LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_receive: removing %"U32_F":%"U32_F" from pcb->unacked\n", + ntohl(pcb->unacked->tcphdr->seqno), + ntohl(pcb->unacked->tcphdr->seqno) + + TCP_TCPLEN(pcb->unacked))); + + next = pcb->unacked; + pcb->unacked = pcb->unacked->next; + + LWIP_DEBUGF(TCP_QLEN_DEBUG, ("tcp_receive: queuelen %"U16_F" ... ", (u16_t)pcb->snd_queuelen)); + LWIP_ASSERT("pcb->snd_queuelen >= pbuf_clen(next->p)", (pcb->snd_queuelen >= pbuf_clen(next->p))); + /* Prevent ACK for FIN to generate a sent event */ + if ((pcb->acked != 0) && ((TCPH_FLAGS(next->tcphdr) & TCP_FIN) != 0)) { + pcb->acked--; + } + + pcb->snd_queuelen -= pbuf_clen(next->p); + tcp_seg_free(next); + + LWIP_DEBUGF(TCP_QLEN_DEBUG, ("%"U16_F" (after freeing unacked)\n", (u16_t)pcb->snd_queuelen)); + if (pcb->snd_queuelen != 0) { + LWIP_ASSERT("tcp_receive: valid queue length", pcb->unacked != NULL || + pcb->unsent != NULL); + } + } + + /* If there's nothing left to acknowledge, stop the retransmit + timer, otherwise reset it to start again */ + if(pcb->unacked == NULL) + pcb->rtime = -1; + else + pcb->rtime = 0; + + pcb->polltmr = 0; + } else { + /* Fix bug bug #21582: out of sequence ACK, didn't really ack anything */ + pcb->acked = 0; + } + + /* We go through the ->unsent list to see if any of the segments + on the list are acknowledged by the ACK. This may seem + strange since an "unsent" segment shouldn't be acked. The + rationale is that lwIP puts all outstanding segments on the + ->unsent list after a retransmission, so these segments may + in fact have been sent once. */ + while (pcb->unsent != NULL && + TCP_SEQ_BETWEEN(ackno, ntohl(pcb->unsent->tcphdr->seqno) + + TCP_TCPLEN(pcb->unsent), pcb->snd_nxt)) { + LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_receive: removing %"U32_F":%"U32_F" from pcb->unsent\n", + ntohl(pcb->unsent->tcphdr->seqno), ntohl(pcb->unsent->tcphdr->seqno) + + TCP_TCPLEN(pcb->unsent))); + + next = pcb->unsent; + pcb->unsent = pcb->unsent->next; + LWIP_DEBUGF(TCP_QLEN_DEBUG, ("tcp_receive: queuelen %"U16_F" ... ", (u16_t)pcb->snd_queuelen)); + LWIP_ASSERT("pcb->snd_queuelen >= pbuf_clen(next->p)", (pcb->snd_queuelen >= pbuf_clen(next->p))); + /* Prevent ACK for FIN to generate a sent event */ + if ((pcb->acked != 0) && ((TCPH_FLAGS(next->tcphdr) & TCP_FIN) != 0)) { + pcb->acked--; + } + pcb->snd_queuelen -= pbuf_clen(next->p); + tcp_seg_free(next); + LWIP_DEBUGF(TCP_QLEN_DEBUG, ("%"U16_F" (after freeing unsent)\n", (u16_t)pcb->snd_queuelen)); + if (pcb->snd_queuelen != 0) { + LWIP_ASSERT("tcp_receive: valid queue length", + pcb->unacked != NULL || pcb->unsent != NULL); + } + } + /* End of ACK for new data processing. */ + + LWIP_DEBUGF(TCP_RTO_DEBUG, ("tcp_receive: pcb->rttest %"U32_F" rtseq %"U32_F" ackno %"U32_F"\n", + pcb->rttest, pcb->rtseq, ackno)); + + /* RTT estimation calculations. This is done by checking if the + incoming segment acknowledges the segment we use to take a + round-trip time measurement. */ + if (pcb->rttest && TCP_SEQ_LT(pcb->rtseq, ackno)) { + /* diff between this shouldn't exceed 32K since this are tcp timer ticks + and a round-trip shouldn't be that long... */ + m = (s16_t)(tcp_ticks - pcb->rttest); + + LWIP_DEBUGF(TCP_RTO_DEBUG, ("tcp_receive: experienced rtt %"U16_F" ticks (%"U16_F" msec).\n", + m, m * TCP_SLOW_INTERVAL)); + + /* This is taken directly from VJs original code in his paper */ + m = m - (pcb->sa >> 3); + pcb->sa += m; + if (m < 0) { + m = -m; + } + m = m - (pcb->sv >> 2); + pcb->sv += m; + pcb->rto = (pcb->sa >> 3) + pcb->sv; + + LWIP_DEBUGF(TCP_RTO_DEBUG, ("tcp_receive: RTO %"U16_F" (%"U16_F" milliseconds)\n", + pcb->rto, pcb->rto * TCP_SLOW_INTERVAL)); + + pcb->rttest = 0; + } + } + + /* If the incoming segment contains data, we must process it + further. */ + if (tcplen > 0) { + /* This code basically does three things: + + +) If the incoming segment contains data that is the next + in-sequence data, this data is passed to the application. This + might involve trimming the first edge of the data. The rcv_nxt + variable and the advertised window are adjusted. + + +) If the incoming segment has data that is above the next + sequence number expected (->rcv_nxt), the segment is placed on + the ->ooseq queue. This is done by finding the appropriate + place in the ->ooseq queue (which is ordered by sequence + number) and trim the segment in both ends if needed. An + immediate ACK is sent to indicate that we received an + out-of-sequence segment. + + +) Finally, we check if the first segment on the ->ooseq queue + now is in sequence (i.e., if rcv_nxt >= ooseq->seqno). If + rcv_nxt > ooseq->seqno, we must trim the first edge of the + segment on ->ooseq before we adjust rcv_nxt. The data in the + segments that are now on sequence are chained onto the + incoming segment so that we only need to call the application + once. + */ + + /* First, we check if we must trim the first edge. We have to do + this if the sequence number of the incoming segment is less + than rcv_nxt, and the sequence number plus the length of the + segment is larger than rcv_nxt. */ + /* if (TCP_SEQ_LT(seqno, pcb->rcv_nxt)){ + if (TCP_SEQ_LT(pcb->rcv_nxt, seqno + tcplen)) {*/ + if (TCP_SEQ_BETWEEN(pcb->rcv_nxt, seqno + 1, seqno + tcplen - 1)){ + /* Trimming the first edge is done by pushing the payload + pointer in the pbuf downwards. This is somewhat tricky since + we do not want to discard the full contents of the pbuf up to + the new starting point of the data since we have to keep the + TCP header which is present in the first pbuf in the chain. + + What is done is really quite a nasty hack: the first pbuf in + the pbuf chain is pointed to by inseg.p. Since we need to be + able to deallocate the whole pbuf, we cannot change this + inseg.p pointer to point to any of the later pbufs in the + chain. Instead, we point the ->payload pointer in the first + pbuf to data in one of the later pbufs. We also set the + inseg.data pointer to point to the right place. This way, the + ->p pointer will still point to the first pbuf, but the + ->p->payload pointer will point to data in another pbuf. + + After we are done with adjusting the pbuf pointers we must + adjust the ->data pointer in the seg and the segment + length.*/ + + off = pcb->rcv_nxt - seqno; + p = inseg.p; + LWIP_ASSERT("inseg.p != NULL", inseg.p); + LWIP_ASSERT("insane offset!", (off < 0x7fff)); + if (inseg.p->len < off) { + LWIP_ASSERT("pbuf too short!", (((s32_t)inseg.p->tot_len) >= off)); + new_tot_len = (u16_t)(inseg.p->tot_len - off); + while (p->len < off) { + off -= p->len; + /* KJM following line changed (with addition of new_tot_len var) + to fix bug #9076 + inseg.p->tot_len -= p->len; */ + p->tot_len = new_tot_len; + p->len = 0; + p = p->next; + } + if(pbuf_header(p, (s16_t)-off)) { + /* Do we need to cope with this failing? Assert for now */ + LWIP_ASSERT("pbuf_header failed", 0); + } + } else { + if(pbuf_header(inseg.p, (s16_t)-off)) { + /* Do we need to cope with this failing? Assert for now */ + LWIP_ASSERT("pbuf_header failed", 0); + } + } + inseg.len -= (u16_t)(pcb->rcv_nxt - seqno); + inseg.tcphdr->seqno = seqno = pcb->rcv_nxt; + } + else { + if (TCP_SEQ_LT(seqno, pcb->rcv_nxt)){ + /* the whole segment is < rcv_nxt */ + /* must be a duplicate of a packet that has already been correctly handled */ + + LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_receive: duplicate seqno %"U32_F"\n", seqno)); + tcp_ack_now(pcb); + } + } + + /* The sequence number must be within the window (above rcv_nxt + and below rcv_nxt + rcv_wnd) in order to be further + processed. */ + if (TCP_SEQ_BETWEEN(seqno, pcb->rcv_nxt, + pcb->rcv_nxt + pcb->rcv_wnd - 1)){ + if (pcb->rcv_nxt == seqno) { + /* The incoming segment is the next in sequence. We check if + we have to trim the end of the segment and update rcv_nxt + and pass the data to the application. */ + tcplen = TCP_TCPLEN(&inseg); + + if (tcplen > pcb->rcv_wnd) { + LWIP_DEBUGF(TCP_INPUT_DEBUG, + ("tcp_receive: other end overran receive window" + "seqno %"U32_F" len %"U16_F" right edge %"U32_F"\n", + seqno, tcplen, pcb->rcv_nxt + pcb->rcv_wnd)); + if (TCPH_FLAGS(inseg.tcphdr) & TCP_FIN) { + /* Must remove the FIN from the header as we're trimming + * that byte of sequence-space from the packet */ + TCPH_FLAGS_SET(inseg.tcphdr, TCPH_FLAGS(inseg.tcphdr) &~ TCP_FIN); + } + /* Adjust length of segment to fit in the window. */ + inseg.len = pcb->rcv_wnd; + if (TCPH_FLAGS(inseg.tcphdr) & TCP_SYN) { + inseg.len -= 1; + } + pbuf_realloc(inseg.p, inseg.len); + tcplen = TCP_TCPLEN(&inseg); + LWIP_ASSERT("tcp_receive: segment not trimmed correctly to rcv_wnd\n", + (seqno + tcplen) == (pcb->rcv_nxt + pcb->rcv_wnd)); + } +#if TCP_QUEUE_OOSEQ + /* Received in-sequence data, adjust ooseq data if: + - FIN has been received or + - inseq overlaps with ooseq */ + if (pcb->ooseq != NULL) { + if (TCPH_FLAGS(inseg.tcphdr) & TCP_FIN) { + LWIP_DEBUGF(TCP_INPUT_DEBUG, + ("tcp_receive: received in-order FIN, binning ooseq queue\n")); + /* Received in-order FIN means anything that was received + * out of order must now have been received in-order, so + * bin the ooseq queue */ + while (pcb->ooseq != NULL) { + struct tcp_seg *old_ooseq = pcb->ooseq; + pcb->ooseq = pcb->ooseq->next; + tcp_seg_free(old_ooseq); + } + } + else { + next = pcb->ooseq; + /* Remove all segments on ooseq that are covered by inseg already. + * FIN is copied from ooseq to inseg if present. */ + while (next && + TCP_SEQ_GEQ(seqno + tcplen, + next->tcphdr->seqno + next->len)) { + /* inseg cannot have FIN here (already processed above) */ + if (TCPH_FLAGS(next->tcphdr) & TCP_FIN && + (TCPH_FLAGS(inseg.tcphdr) & TCP_SYN) == 0) { + TCPH_SET_FLAG(inseg.tcphdr, TCP_FIN); + tcplen = TCP_TCPLEN(&inseg); + } + prev = next; + next = next->next; + tcp_seg_free(prev); + } + /* Now trim right side of inseg if it overlaps with the first + * segment on ooseq */ + if (next && + TCP_SEQ_GT(seqno + tcplen, + next->tcphdr->seqno)) { + /* inseg cannot have FIN here (already processed above) */ + inseg.len = (u16_t)(next->tcphdr->seqno - seqno); + if (TCPH_FLAGS(inseg.tcphdr) & TCP_SYN) { + inseg.len -= 1; + } + pbuf_realloc(inseg.p, inseg.len); + tcplen = TCP_TCPLEN(&inseg); + LWIP_ASSERT("tcp_receive: segment not trimmed correctly to ooseq queue\n", + (seqno + tcplen) == next->tcphdr->seqno); + } + pcb->ooseq = next; + } + } +#endif /* TCP_QUEUE_OOSEQ */ + + pcb->rcv_nxt = seqno + tcplen; + + /* Update the receiver's (our) window. */ + LWIP_ASSERT("tcp_receive: tcplen > rcv_wnd\n", pcb->rcv_wnd >= tcplen); + pcb->rcv_wnd -= tcplen; + + tcp_update_rcv_ann_wnd(pcb); + + /* If there is data in the segment, we make preparations to + pass this up to the application. The ->recv_data variable + is used for holding the pbuf that goes to the + application. The code for reassembling out-of-sequence data + chains its data on this pbuf as well. + + If the segment was a FIN, we set the TF_GOT_FIN flag that will + be used to indicate to the application that the remote side has + closed its end of the connection. */ + if (inseg.p->tot_len > 0) { + recv_data = inseg.p; + /* Since this pbuf now is the responsibility of the + application, we delete our reference to it so that we won't + (mistakingly) deallocate it. */ + inseg.p = NULL; + } + if (TCPH_FLAGS(inseg.tcphdr) & TCP_FIN) { + LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_receive: received FIN.\n")); + recv_flags |= TF_GOT_FIN; + } + +#if TCP_QUEUE_OOSEQ + /* We now check if we have segments on the ->ooseq queue that + are now in sequence. */ + while (pcb->ooseq != NULL && + pcb->ooseq->tcphdr->seqno == pcb->rcv_nxt) { + + cseg = pcb->ooseq; + seqno = pcb->ooseq->tcphdr->seqno; + + pcb->rcv_nxt += TCP_TCPLEN(cseg); + LWIP_ASSERT("tcp_receive: ooseq tcplen > rcv_wnd\n", + pcb->rcv_wnd >= TCP_TCPLEN(cseg)); + pcb->rcv_wnd -= TCP_TCPLEN(cseg); + + tcp_update_rcv_ann_wnd(pcb); + + if (cseg->p->tot_len > 0) { + /* Chain this pbuf onto the pbuf that we will pass to + the application. */ + if (recv_data) { + pbuf_cat(recv_data, cseg->p); + } else { + recv_data = cseg->p; + } + cseg->p = NULL; + } + if (TCPH_FLAGS(cseg->tcphdr) & TCP_FIN) { + LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_receive: dequeued FIN.\n")); + recv_flags |= TF_GOT_FIN; + if (pcb->state == ESTABLISHED) { /* force passive close or we can move to active close */ + pcb->state = CLOSE_WAIT; + } + } + + pcb->ooseq = cseg->next; + tcp_seg_free(cseg); + } +#endif /* TCP_QUEUE_OOSEQ */ + + + /* Acknowledge the segment(s). */ + tcp_ack(pcb); + + } else { + /* We get here if the incoming segment is out-of-sequence. */ + tcp_send_empty_ack(pcb); +#if TCP_QUEUE_OOSEQ + /* We queue the segment on the ->ooseq queue. */ + if (pcb->ooseq == NULL) { + pcb->ooseq = tcp_seg_copy(&inseg); + } else { + /* If the queue is not empty, we walk through the queue and + try to find a place where the sequence number of the + incoming segment is between the sequence numbers of the + previous and the next segment on the ->ooseq queue. That is + the place where we put the incoming segment. If needed, we + trim the second edges of the previous and the incoming + segment so that it will fit into the sequence. + + If the incoming segment has the same sequence number as a + segment on the ->ooseq queue, we discard the segment that + contains less data. */ + + prev = NULL; + for(next = pcb->ooseq; next != NULL; next = next->next) { + if (seqno == next->tcphdr->seqno) { + /* The sequence number of the incoming segment is the + same as the sequence number of the segment on + ->ooseq. We check the lengths to see which one to + discard. */ + if (inseg.len > next->len) { + /* The incoming segment is larger than the old + segment. We replace some segments with the new + one. */ + cseg = tcp_seg_copy(&inseg); + if (cseg != NULL) { + if (prev != NULL) { + prev->next = cseg; + } else { + pcb->ooseq = cseg; + } + tcp_oos_insert_segment(cseg, next); + } + break; + } else { + /* Either the lenghts are the same or the incoming + segment was smaller than the old one; in either + case, we ditch the incoming segment. */ + break; + } + } else { + if (prev == NULL) { + if (TCP_SEQ_LT(seqno, next->tcphdr->seqno)) { + /* The sequence number of the incoming segment is lower + than the sequence number of the first segment on the + queue. We put the incoming segment first on the + queue. */ + cseg = tcp_seg_copy(&inseg); + if (cseg != NULL) { + pcb->ooseq = cseg; + tcp_oos_insert_segment(cseg, next); + } + break; + } + } else { + /*if (TCP_SEQ_LT(prev->tcphdr->seqno, seqno) && + TCP_SEQ_LT(seqno, next->tcphdr->seqno)) {*/ + if (TCP_SEQ_BETWEEN(seqno, prev->tcphdr->seqno+1, next->tcphdr->seqno-1)) { + /* The sequence number of the incoming segment is in + between the sequence numbers of the previous and + the next segment on ->ooseq. We trim trim the previous + segment, delete next segments that included in received segment + and trim received, if needed. */ + cseg = tcp_seg_copy(&inseg); + if (cseg != NULL) { + if (TCP_SEQ_GT(prev->tcphdr->seqno + prev->len, seqno)) { + /* We need to trim the prev segment. */ + prev->len = (u16_t)(seqno - prev->tcphdr->seqno); + pbuf_realloc(prev->p, prev->len); + } + prev->next = cseg; + tcp_oos_insert_segment(cseg, next); + } + break; + } + } + /* If the "next" segment is the last segment on the + ooseq queue, we add the incoming segment to the end + of the list. */ + if (next->next == NULL && + TCP_SEQ_GT(seqno, next->tcphdr->seqno)) { + if (TCPH_FLAGS(next->tcphdr) & TCP_FIN) { + /* segment "next" already contains all data */ + break; + } + next->next = tcp_seg_copy(&inseg); + if (next->next != NULL) { + if (TCP_SEQ_GT(next->tcphdr->seqno + next->len, seqno)) { + /* We need to trim the last segment. */ + next->len = (u16_t)(seqno - next->tcphdr->seqno); + pbuf_realloc(next->p, next->len); + } + /* check if the remote side overruns our receive window */ + if ((u32_t)tcplen + seqno > pcb->rcv_nxt + (u32_t)pcb->rcv_wnd) { + LWIP_DEBUGF(TCP_INPUT_DEBUG, + ("tcp_receive: other end overran receive window" + "seqno %"U32_F" len %"U16_F" right edge %"U32_F"\n", + seqno, tcplen, pcb->rcv_nxt + pcb->rcv_wnd)); + if (TCPH_FLAGS(next->next->tcphdr) & TCP_FIN) { + /* Must remove the FIN from the header as we're trimming + * that byte of sequence-space from the packet */ + TCPH_FLAGS_SET(next->next->tcphdr, TCPH_FLAGS(next->next->tcphdr) &~ TCP_FIN); + } + /* Adjust length of segment to fit in the window. */ + next->next->len = pcb->rcv_nxt + pcb->rcv_wnd - seqno; + pbuf_realloc(next->next->p, next->next->len); + tcplen = TCP_TCPLEN(next->next); + LWIP_ASSERT("tcp_receive: segment not trimmed correctly to rcv_wnd\n", + (seqno + tcplen) == (pcb->rcv_nxt + pcb->rcv_wnd)); + } + } + break; + } + } + prev = next; + } + } +#endif /* TCP_QUEUE_OOSEQ */ + + } + } else { + /* The incoming segment is not withing the window. */ + tcp_send_empty_ack(pcb); + } + } else { + /* Segments with length 0 is taken care of here. Segments that + fall out of the window are ACKed. */ + /*if (TCP_SEQ_GT(pcb->rcv_nxt, seqno) || + TCP_SEQ_GEQ(seqno, pcb->rcv_nxt + pcb->rcv_wnd)) {*/ + if(!TCP_SEQ_BETWEEN(seqno, pcb->rcv_nxt, pcb->rcv_nxt + pcb->rcv_wnd-1)){ + tcp_ack_now(pcb); + } + } +} + +/** + * Parses the options contained in the incoming segment. + * + * Called from tcp_listen_input() and tcp_process(). + * Currently, only the MSS option is supported! + * + * @param pcb the tcp_pcb for which a segment arrived + */ +static void +tcp_parseopt(struct tcp_pcb *pcb) +{ + u16_t c, max_c; + u16_t mss; + u8_t *opts, opt; +#if LWIP_TCP_TIMESTAMPS + u32_t tsval; +#endif + + opts = (u8_t *)tcphdr + TCP_HLEN; + + /* Parse the TCP MSS option, if present. */ + if(TCPH_HDRLEN(tcphdr) > 0x5) { + max_c = (TCPH_HDRLEN(tcphdr) - 5) << 2; + for (c = 0; c < max_c; ) { + opt = opts[c]; + switch (opt) { + case 0x00: + /* End of options. */ + LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_parseopt: EOL\n")); + return; + case 0x01: + /* NOP option. */ + ++c; + LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_parseopt: NOP\n")); + break; + case 0x02: + LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_parseopt: MSS\n")); + if (opts[c + 1] != 0x04 || c + 0x04 > max_c) { + /* Bad length */ + LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_parseopt: bad length\n")); + return; + } + /* An MSS option with the right option length. */ + mss = (opts[c + 2] << 8) | opts[c + 3]; + /* Limit the mss to the configured TCP_MSS and prevent division by zero */ + pcb->mss = ((mss > TCP_MSS) || (mss == 0)) ? TCP_MSS : mss; + /* Advance to next option */ + c += 0x04; + break; +#if LWIP_TCP_TIMESTAMPS + case 0x08: + LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_parseopt: TS\n")); + if (opts[c + 1] != 0x0A || c + 0x0A > max_c) { + /* Bad length */ + LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_parseopt: bad length\n")); + return; + } + /* TCP timestamp option with valid length */ + tsval = (opts[c+2]) | (opts[c+3] << 8) | + (opts[c+4] << 16) | (opts[c+5] << 24); + if (flags & TCP_SYN) { + pcb->ts_recent = ntohl(tsval); + pcb->flags |= TF_TIMESTAMP; + } else if (TCP_SEQ_BETWEEN(pcb->ts_lastacksent, seqno, seqno+tcplen)) { + pcb->ts_recent = ntohl(tsval); + } + /* Advance to next option */ + c += 0x0A; + break; +#endif + default: + LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_parseopt: other\n")); + if (opts[c + 1] == 0) { + LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_parseopt: bad length\n")); + /* If the length field is zero, the options are malformed + and we don't process them further. */ + return; + } + /* All other options have a length field, so that we easily + can skip past them. */ + c += opts[c + 1]; + } + } + } +} + +#endif /* LWIP_TCP */ diff --git a/features/unsupported/net/lwip/lwip/core/tcp_out.c b/features/unsupported/net/lwip/lwip/core/tcp_out.c new file mode 100644 index 00000000000..0cc48b1cdb7 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/core/tcp_out.c @@ -0,0 +1,1471 @@ +/** + * @file + * Transmission Control Protocol, outgoing traffic + * + * The output functions of TCP. + * + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ + +#include "lwip/opt.h" + +#if LWIP_TCP /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/tcp_impl.h" +#include "lwip/def.h" +#include "lwip/mem.h" +#include "lwip/memp.h" +#include "lwip/sys.h" +#include "lwip/ip_addr.h" +#include "lwip/netif.h" +#include "lwip/inet_chksum.h" +#include "lwip/stats.h" +#include "lwip/snmp.h" + +#include + +/* Define some copy-macros for checksum-on-copy so that the code looks + nicer by preventing too many ifdef's. */ +#if TCP_CHECKSUM_ON_COPY +#define TCP_DATA_COPY(dst, src, len, seg) do { \ + tcp_seg_add_chksum(LWIP_CHKSUM_COPY(dst, src, len), \ + len, &seg->chksum, &seg->chksum_swapped); \ + seg->flags |= TF_SEG_DATA_CHECKSUMMED; } while(0) +#define TCP_DATA_COPY2(dst, src, len, chksum, chksum_swapped) \ + tcp_seg_add_chksum(LWIP_CHKSUM_COPY(dst, src, len), len, chksum, chksum_swapped); +#else /* TCP_CHECKSUM_ON_COPY*/ +#define TCP_DATA_COPY(dst, src, len, seg) MEMCPY(dst, src, len) +#define TCP_DATA_COPY2(dst, src, len, chksum, chksum_swapped) MEMCPY(dst, src, len) +#endif /* TCP_CHECKSUM_ON_COPY*/ + +/** Define this to 1 for an extra check that the output checksum is valid + * (usefule when the checksum is generated by the application, not the stack) */ +#ifndef TCP_CHECKSUM_ON_COPY_SANITY_CHECK +#define TCP_CHECKSUM_ON_COPY_SANITY_CHECK 0 +#endif + +/* Forward declarations.*/ +static void tcp_output_segment(struct tcp_seg *seg, struct tcp_pcb *pcb); + +/** Allocate a pbuf and create a tcphdr at p->payload, used for output + * functions other than the default tcp_output -> tcp_output_segment + * (e.g. tcp_send_empty_ack, etc.) + * + * @param pcb tcp pcb for which to send a packet (used to initialize tcp_hdr) + * @param optlen length of header-options + * @param datalen length of tcp data to reserve in pbuf + * @param seqno_be seqno in network byte order (big-endian) + * @return pbuf with p->payload being the tcp_hdr + */ +static struct pbuf * +tcp_output_alloc_header(struct tcp_pcb *pcb, u16_t optlen, u16_t datalen, + u32_t seqno_be /* already in network byte order */) +{ + struct tcp_hdr *tcphdr; + struct pbuf *p = pbuf_alloc(PBUF_IP, TCP_HLEN + optlen + datalen, PBUF_RAM); + if (p != NULL) { + LWIP_ASSERT("check that first pbuf can hold struct tcp_hdr", + (p->len >= TCP_HLEN + optlen)); + tcphdr = (struct tcp_hdr *)p->payload; + tcphdr->src = htons(pcb->local_port); + tcphdr->dest = htons(pcb->remote_port); + tcphdr->seqno = seqno_be; + tcphdr->ackno = htonl(pcb->rcv_nxt); + TCPH_HDRLEN_FLAGS_SET(tcphdr, (5 + optlen / 4), TCP_ACK); + tcphdr->wnd = htons(pcb->rcv_ann_wnd); + tcphdr->chksum = 0; + tcphdr->urgp = 0; + + /* If we're sending a packet, update the announced right window edge */ + pcb->rcv_ann_right_edge = pcb->rcv_nxt + pcb->rcv_ann_wnd; + } + return p; +} + +/** + * Called by tcp_close() to send a segment including FIN flag but not data. + * + * @param pcb the tcp_pcb over which to send a segment + * @return ERR_OK if sent, another err_t otherwise + */ +err_t +tcp_send_fin(struct tcp_pcb *pcb) +{ + /* first, try to add the fin to the last unsent segment */ + if (pcb->unsent != NULL) { + struct tcp_seg *last_unsent; + for (last_unsent = pcb->unsent; last_unsent->next != NULL; + last_unsent = last_unsent->next); + + if ((TCPH_FLAGS(last_unsent->tcphdr) & (TCP_SYN | TCP_FIN | TCP_RST)) == 0) { + /* no SYN/FIN/RST flag in the header, we can add the FIN flag */ + TCPH_SET_FLAG(last_unsent->tcphdr, TCP_FIN); + return ERR_OK; + } + } + /* no data, no length, flags, copy=1, no optdata */ + return tcp_enqueue_flags(pcb, TCP_FIN); +} + +/** + * Create a TCP segment with prefilled header. + * + * Called by tcp_write and tcp_enqueue_flags. + * + * @param pcb Protocol control block for the TCP connection. + * @param p pbuf that is used to hold the TCP header. + * @param flags TCP flags for header. + * @param seqno TCP sequence number of this packet + * @param optflags options to include in TCP header + * @return a new tcp_seg pointing to p, or NULL. + * The TCP header is filled in except ackno and wnd. + * p is freed on failure. + */ +static struct tcp_seg * +tcp_create_segment(struct tcp_pcb *pcb, struct pbuf *p, u8_t flags, u32_t seqno, u8_t optflags) +{ + struct tcp_seg *seg; + u8_t optlen = LWIP_TCP_OPT_LENGTH(optflags); + + if ((seg = (struct tcp_seg *)memp_malloc(MEMP_TCP_SEG)) == NULL) { + LWIP_DEBUGF(TCP_OUTPUT_DEBUG | 2, ("tcp_create_segment: no memory.\n")); + pbuf_free(p); + return NULL; + } + seg->flags = optflags; + seg->next = NULL; + seg->p = p; + seg->len = p->tot_len - optlen; +#if TCP_OVERSIZE_DBGCHECK + seg->oversize_left = 0; +#endif /* TCP_OVERSIZE_DBGCHECK */ +#if TCP_CHECKSUM_ON_COPY + seg->chksum = 0; + seg->chksum_swapped = 0; + /* check optflags */ + LWIP_ASSERT("invalid optflags passed: TF_SEG_DATA_CHECKSUMMED", + (optflags & TF_SEG_DATA_CHECKSUMMED) == 0); +#endif /* TCP_CHECKSUM_ON_COPY */ + + /* build TCP header */ + if (pbuf_header(p, TCP_HLEN)) { + LWIP_DEBUGF(TCP_OUTPUT_DEBUG | 2, ("tcp_create_segment: no room for TCP header in pbuf.\n")); + TCP_STATS_INC(tcp.err); + tcp_seg_free(seg); + return NULL; + } + seg->tcphdr = (struct tcp_hdr *)seg->p->payload; + seg->tcphdr->src = htons(pcb->local_port); + seg->tcphdr->dest = htons(pcb->remote_port); + seg->tcphdr->seqno = htonl(seqno); + /* ackno is set in tcp_output */ + TCPH_HDRLEN_FLAGS_SET(seg->tcphdr, (5 + optlen / 4), flags); + /* wnd and chksum are set in tcp_output */ + seg->tcphdr->urgp = 0; + return seg; +} + +/** + * Allocate a PBUF_RAM pbuf, perhaps with extra space at the end. + * + * This function is like pbuf_alloc(layer, length, PBUF_RAM) except + * there may be extra bytes available at the end. + * + * @param layer flag to define header size. + * @param length size of the pbuf's payload. + * @param max_length maximum usable size of payload+oversize. + * @param oversize pointer to a u16_t that will receive the number of usable tail bytes. + * @param pcb The TCP connection that willo enqueue the pbuf. + * @param apiflags API flags given to tcp_write. + * @param first_seg true when this pbuf will be used in the first enqueued segment. + * @param + */ +#if TCP_OVERSIZE +static struct pbuf * +tcp_pbuf_prealloc(pbuf_layer layer, u16_t length, u16_t max_length, + u16_t *oversize, struct tcp_pcb *pcb, u8_t apiflags, + u8_t first_seg) +{ + struct pbuf *p; + u16_t alloc = length; + +#if LWIP_NETIF_TX_SINGLE_PBUF + LWIP_UNUSED_ARG(max_length); + LWIP_UNUSED_ARG(pcb); + LWIP_UNUSED_ARG(apiflags); + LWIP_UNUSED_ARG(first_seg); + /* always create MSS-sized pbufs */ + alloc = TCP_MSS; +#else /* LWIP_NETIF_TX_SINGLE_PBUF */ + if (length < max_length) { + /* Should we allocate an oversized pbuf, or just the minimum + * length required? If tcp_write is going to be called again + * before this segment is transmitted, we want the oversized + * buffer. If the segment will be transmitted immediately, we can + * save memory by allocating only length. We use a simple + * heuristic based on the following information: + * + * Did the user set TCP_WRITE_FLAG_MORE? + * + * Will the Nagle algorithm defer transmission of this segment? + */ + if ((apiflags & TCP_WRITE_FLAG_MORE) || + (!(pcb->flags & TF_NODELAY) && + (!first_seg || + pcb->unsent != NULL || + pcb->unacked != NULL))) { + alloc = LWIP_MIN(max_length, LWIP_MEM_ALIGN_SIZE(length + TCP_OVERSIZE)); + } + } +#endif /* LWIP_NETIF_TX_SINGLE_PBUF */ + p = pbuf_alloc(layer, alloc, PBUF_RAM); + if (p == NULL) { + return NULL; + } + LWIP_ASSERT("need unchained pbuf", p->next == NULL); + *oversize = p->len - length; + /* trim p->len to the currently used size */ + p->len = p->tot_len = length; + return p; +} +#else /* TCP_OVERSIZE */ +#define tcp_pbuf_prealloc(layer, length, mx, os, pcb, api, fst) pbuf_alloc((layer), (length), PBUF_RAM) +#endif /* TCP_OVERSIZE */ + +#if TCP_CHECKSUM_ON_COPY +/** Add a checksum of newly added data to the segment */ +static void +tcp_seg_add_chksum(u16_t chksum, u16_t len, u16_t *seg_chksum, + u8_t *seg_chksum_swapped) +{ + u32_t helper; + /* add chksum to old chksum and fold to u16_t */ + helper = chksum + *seg_chksum; + chksum = FOLD_U32T(helper); + if ((len & 1) != 0) { + *seg_chksum_swapped = 1 - *seg_chksum_swapped; + chksum = SWAP_BYTES_IN_WORD(chksum); + } + *seg_chksum = chksum; +} +#endif /* TCP_CHECKSUM_ON_COPY */ + +/** Checks if tcp_write is allowed or not (checks state, snd_buf and snd_queuelen). + * + * @param pcb the tcp pcb to check for + * @param len length of data to send (checked agains snd_buf) + * @return ERR_OK if tcp_write is allowed to proceed, another err_t otherwise + */ +static err_t +tcp_write_checks(struct tcp_pcb *pcb, u16_t len) +{ + /* connection is in invalid state for data transmission? */ + if ((pcb->state != ESTABLISHED) && + (pcb->state != CLOSE_WAIT) && + (pcb->state != SYN_SENT) && + (pcb->state != SYN_RCVD)) { + LWIP_DEBUGF(TCP_OUTPUT_DEBUG | LWIP_DBG_STATE | LWIP_DBG_LEVEL_SEVERE, ("tcp_write() called in invalid state\n")); + return ERR_CONN; + } else if (len == 0) { + return ERR_OK; + } + + /* fail on too much data */ + if (len > pcb->snd_buf) { + LWIP_DEBUGF(TCP_OUTPUT_DEBUG | 3, ("tcp_write: too much data (len=%"U16_F" > snd_buf=%"U16_F")\n", + len, pcb->snd_buf)); + pcb->flags |= TF_NAGLEMEMERR; + return ERR_MEM; + } + + LWIP_DEBUGF(TCP_QLEN_DEBUG, ("tcp_write: queuelen: %"U16_F"\n", (u16_t)pcb->snd_queuelen)); + + /* If total number of pbufs on the unsent/unacked queues exceeds the + * configured maximum, return an error */ + /* check for configured max queuelen and possible overflow */ + if ((pcb->snd_queuelen >= TCP_SND_QUEUELEN) || (pcb->snd_queuelen > TCP_SNDQUEUELEN_OVERFLOW)) { + LWIP_DEBUGF(TCP_OUTPUT_DEBUG | 3, ("tcp_write: too long queue %"U16_F" (max %"U16_F")\n", + pcb->snd_queuelen, TCP_SND_QUEUELEN)); + TCP_STATS_INC(tcp.memerr); + pcb->flags |= TF_NAGLEMEMERR; + return ERR_MEM; + } + if (pcb->snd_queuelen != 0) { + LWIP_ASSERT("tcp_write: pbufs on queue => at least one queue non-empty", + pcb->unacked != NULL || pcb->unsent != NULL); + } else { + LWIP_ASSERT("tcp_write: no pbufs on queue => both queues empty", + pcb->unacked == NULL && pcb->unsent == NULL); + } + return ERR_OK; +} + +/** + * Write data for sending (but does not send it immediately). + * + * It waits in the expectation of more data being sent soon (as + * it can send them more efficiently by combining them together). + * To prompt the system to send data now, call tcp_output() after + * calling tcp_write(). + * + * @param pcb Protocol control block for the TCP connection to enqueue data for. + * @param arg Pointer to the data to be enqueued for sending. + * @param len Data length in bytes + * @param apiflags combination of following flags : + * - TCP_WRITE_FLAG_COPY (0x01) data will be copied into memory belonging to the stack + * - TCP_WRITE_FLAG_MORE (0x02) for TCP connection, PSH flag will be set on last segment sent, + * @return ERR_OK if enqueued, another err_t on error + */ +err_t +tcp_write(struct tcp_pcb *pcb, const void *arg, u16_t len, u8_t apiflags) +{ + struct pbuf *concat_p = NULL; + struct tcp_seg *last_unsent = NULL, *seg = NULL, *prev_seg = NULL, *queue = NULL; + u16_t pos = 0; /* position in 'arg' data */ + u16_t queuelen; + u8_t optlen = 0; + u8_t optflags = 0; +#if TCP_OVERSIZE + u16_t oversize = 0; + u16_t oversize_used = 0; +#endif /* TCP_OVERSIZE */ +#if TCP_CHECKSUM_ON_COPY + u16_t concat_chksum = 0; + u8_t concat_chksum_swapped = 0; + u16_t concat_chksummed = 0; +#endif /* TCP_CHECKSUM_ON_COPY */ + err_t err; + +#if LWIP_NETIF_TX_SINGLE_PBUF + /* Always copy to try to create single pbufs for TX */ + apiflags |= TCP_WRITE_FLAG_COPY; +#endif /* LWIP_NETIF_TX_SINGLE_PBUF */ + + LWIP_DEBUGF(TCP_OUTPUT_DEBUG, ("tcp_write(pcb=%p, data=%p, len=%"U16_F", apiflags=%"U16_F")\n", + (void *)pcb, arg, len, (u16_t)apiflags)); + LWIP_ERROR("tcp_write: arg == NULL (programmer violates API)", + arg != NULL, return ERR_ARG;); + + err = tcp_write_checks(pcb, len); + if (err != ERR_OK) { + return err; + } + queuelen = pcb->snd_queuelen; + +#if LWIP_TCP_TIMESTAMPS + if ((pcb->flags & TF_TIMESTAMP)) { + optflags = TF_SEG_OPTS_TS; + optlen = LWIP_TCP_OPT_LENGTH(TF_SEG_OPTS_TS); + } +#endif /* LWIP_TCP_TIMESTAMPS */ + + + /* + * TCP segmentation is done in three phases with increasing complexity: + * + * 1. Copy data directly into an oversized pbuf. + * 2. Chain a new pbuf to the end of pcb->unsent. + * 3. Create new segments. + * + * We may run out of memory at any point. In that case we must + * return ERR_MEM and not change anything in pcb. Therefore, all + * changes are recorded in local variables and committed at the end + * of the function. Some pcb fields are maintained in local copies: + * + * queuelen = pcb->snd_queuelen + * oversize = pcb->unsent_oversize + * + * These variables are set consistently by the phases: + * + * seg points to the last segment tampered with. + * + * pos records progress as data is segmented. + */ + + /* Find the tail of the unsent queue. */ + if (pcb->unsent != NULL) { + u16_t space; + u16_t unsent_optlen; + + /* @todo: this could be sped up by keeping last_unsent in the pcb */ + for (last_unsent = pcb->unsent; last_unsent->next != NULL; + last_unsent = last_unsent->next); + + /* Usable space at the end of the last unsent segment */ + unsent_optlen = LWIP_TCP_OPT_LENGTH(last_unsent->flags); + space = pcb->mss - (last_unsent->len + unsent_optlen); + + /* + * Phase 1: Copy data directly into an oversized pbuf. + * + * The number of bytes copied is recorded in the oversize_used + * variable. The actual copying is done at the bottom of the + * function. + */ +#if TCP_OVERSIZE +#if TCP_OVERSIZE_DBGCHECK + /* check that pcb->unsent_oversize matches last_unsent->unsent_oversize */ + LWIP_ASSERT("unsent_oversize mismatch (pcb vs. last_unsent)", + pcb->unsent_oversize == last_unsent->oversize_left); +#endif /* TCP_OVERSIZE_DBGCHECK */ + oversize = pcb->unsent_oversize; + if (oversize > 0) { + LWIP_ASSERT("inconsistent oversize vs. space", oversize_used <= space); + seg = last_unsent; + oversize_used = oversize < len ? oversize : len; + pos += oversize_used; + oversize -= oversize_used; + space -= oversize_used; + } + /* now we are either finished or oversize is zero */ + LWIP_ASSERT("inconsistend oversize vs. len", (oversize == 0) || (pos == len)); +#endif /* TCP_OVERSIZE */ + + /* + * Phase 2: Chain a new pbuf to the end of pcb->unsent. + * + * We don't extend segments containing SYN/FIN flags or options + * (len==0). The new pbuf is kept in concat_p and pbuf_cat'ed at + * the end. + */ + if ((pos < len) && (space > 0) && (last_unsent->len > 0)) { + u16_t seglen = space < len - pos ? space : len - pos; + seg = last_unsent; + + /* Create a pbuf with a copy or reference to seglen bytes. We + * can use PBUF_RAW here since the data appears in the middle of + * a segment. A header will never be prepended. */ + if (apiflags & TCP_WRITE_FLAG_COPY) { + /* Data is copied */ + if ((concat_p = tcp_pbuf_prealloc(PBUF_RAW, seglen, space, &oversize, pcb, apiflags, 1)) == NULL) { + LWIP_DEBUGF(TCP_OUTPUT_DEBUG | 2, + ("tcp_write : could not allocate memory for pbuf copy size %"U16_F"\n", + seglen)); + goto memerr; + } +#if TCP_OVERSIZE_DBGCHECK + last_unsent->oversize_left = oversize; +#endif /* TCP_OVERSIZE_DBGCHECK */ + TCP_DATA_COPY2(concat_p->payload, (u8_t*)arg + pos, seglen, &concat_chksum, &concat_chksum_swapped); +#if TCP_CHECKSUM_ON_COPY + concat_chksummed += seglen; +#endif /* TCP_CHECKSUM_ON_COPY */ + } else { + /* Data is not copied */ + if ((concat_p = pbuf_alloc(PBUF_RAW, seglen, PBUF_ROM)) == NULL) { + LWIP_DEBUGF(TCP_OUTPUT_DEBUG | 2, + ("tcp_write: could not allocate memory for zero-copy pbuf\n")); + goto memerr; + } +#if TCP_CHECKSUM_ON_COPY + /* calculate the checksum of nocopy-data */ + tcp_seg_add_chksum(~inet_chksum((u8_t*)arg + pos, seglen), seglen, + &concat_chksum, &concat_chksum_swapped); + concat_chksummed += seglen; +#endif /* TCP_CHECKSUM_ON_COPY */ + /* reference the non-volatile payload data */ + concat_p->payload = (u8_t*)arg + pos; + } + + pos += seglen; + queuelen += pbuf_clen(concat_p); + } + } else { +#if TCP_OVERSIZE + LWIP_ASSERT("unsent_oversize mismatch (pcb->unsent is NULL)", + pcb->unsent_oversize == 0); +#endif /* TCP_OVERSIZE */ + } + + /* + * Phase 3: Create new segments. + * + * The new segments are chained together in the local 'queue' + * variable, ready to be appended to pcb->unsent. + */ + while (pos < len) { + struct pbuf *p; + u16_t left = len - pos; + u16_t max_len = pcb->mss - optlen; + u16_t seglen = left > max_len ? max_len : left; +#if TCP_CHECKSUM_ON_COPY + u16_t chksum = 0; + u8_t chksum_swapped = 0; +#endif /* TCP_CHECKSUM_ON_COPY */ + + if (apiflags & TCP_WRITE_FLAG_COPY) { + /* If copy is set, memory should be allocated and data copied + * into pbuf */ + if ((p = tcp_pbuf_prealloc(PBUF_TRANSPORT, seglen + optlen, pcb->mss, &oversize, pcb, apiflags, queue == NULL)) == NULL) { + LWIP_DEBUGF(TCP_OUTPUT_DEBUG | 2, ("tcp_write : could not allocate memory for pbuf copy size %"U16_F"\n", seglen)); + goto memerr; + } + LWIP_ASSERT("tcp_write: check that first pbuf can hold the complete seglen", + (p->len >= seglen)); + TCP_DATA_COPY2((char *)p->payload + optlen, (u8_t*)arg + pos, seglen, &chksum, &chksum_swapped); + } else { + /* Copy is not set: First allocate a pbuf for holding the data. + * Since the referenced data is available at least until it is + * sent out on the link (as it has to be ACKed by the remote + * party) we can safely use PBUF_ROM instead of PBUF_REF here. + */ + struct pbuf *p2; +#if TCP_OVERSIZE + LWIP_ASSERT("oversize == 0", oversize == 0); +#endif /* TCP_OVERSIZE */ + if ((p2 = pbuf_alloc(PBUF_TRANSPORT, seglen, PBUF_ROM)) == NULL) { + LWIP_DEBUGF(TCP_OUTPUT_DEBUG | 2, ("tcp_write: could not allocate memory for zero-copy pbuf\n")); + goto memerr; + } +#if TCP_CHECKSUM_ON_COPY + /* calculate the checksum of nocopy-data */ + chksum = ~inet_chksum((u8_t*)arg + pos, seglen); +#endif /* TCP_CHECKSUM_ON_COPY */ + /* reference the non-volatile payload data */ + p2->payload = (u8_t*)arg + pos; + + /* Second, allocate a pbuf for the headers. */ + if ((p = pbuf_alloc(PBUF_TRANSPORT, optlen, PBUF_RAM)) == NULL) { + /* If allocation fails, we have to deallocate the data pbuf as + * well. */ + pbuf_free(p2); + LWIP_DEBUGF(TCP_OUTPUT_DEBUG | 2, ("tcp_write: could not allocate memory for header pbuf\n")); + goto memerr; + } + /* Concatenate the headers and data pbufs together. */ + pbuf_cat(p/*header*/, p2/*data*/); + } + + queuelen += pbuf_clen(p); + + /* Now that there are more segments queued, we check again if the + * length of the queue exceeds the configured maximum or + * overflows. */ + if ((queuelen > TCP_SND_QUEUELEN) || (queuelen > TCP_SNDQUEUELEN_OVERFLOW)) { + LWIP_DEBUGF(TCP_OUTPUT_DEBUG | 2, ("tcp_write: queue too long %"U16_F" (%"U16_F")\n", queuelen, TCP_SND_QUEUELEN)); + pbuf_free(p); + goto memerr; + } + + if ((seg = tcp_create_segment(pcb, p, 0, pcb->snd_lbb + pos, optflags)) == NULL) { + goto memerr; + } +#if TCP_OVERSIZE_DBGCHECK + seg->oversize_left = oversize; +#endif /* TCP_OVERSIZE_DBGCHECK */ +#if TCP_CHECKSUM_ON_COPY + seg->chksum = chksum; + seg->chksum_swapped = chksum_swapped; + seg->flags |= TF_SEG_DATA_CHECKSUMMED; +#endif /* TCP_CHECKSUM_ON_COPY */ + + /* first segment of to-be-queued data? */ + if (queue == NULL) { + queue = seg; + } else { + /* Attach the segment to the end of the queued segments */ + LWIP_ASSERT("prev_seg != NULL", prev_seg != NULL); + prev_seg->next = seg; + } + /* remember last segment of to-be-queued data for next iteration */ + prev_seg = seg; + + LWIP_DEBUGF(TCP_OUTPUT_DEBUG | LWIP_DBG_TRACE, ("tcp_write: queueing %"U32_F":%"U32_F"\n", + ntohl(seg->tcphdr->seqno), + ntohl(seg->tcphdr->seqno) + TCP_TCPLEN(seg))); + + pos += seglen; + } + + /* + * All three segmentation phases were successful. We can commit the + * transaction. + */ + + /* + * Phase 1: If data has been added to the preallocated tail of + * last_unsent, we update the length fields of the pbuf chain. + */ +#if TCP_OVERSIZE + if (oversize_used > 0) { + struct pbuf *p; + /* Bump tot_len of whole chain, len of tail */ + for (p = last_unsent->p; p; p = p->next) { + p->tot_len += oversize_used; + if (p->next == NULL) { + TCP_DATA_COPY((char *)p->payload + p->len, arg, oversize_used, last_unsent); + p->len += oversize_used; + } + } + last_unsent->len += oversize_used; +#if TCP_OVERSIZE_DBGCHECK + last_unsent->oversize_left -= oversize_used; +#endif /* TCP_OVERSIZE_DBGCHECK */ + } + pcb->unsent_oversize = oversize; +#endif /* TCP_OVERSIZE */ + + /* + * Phase 2: concat_p can be concatenated onto last_unsent->p + */ + if (concat_p != NULL) { + LWIP_ASSERT("tcp_write: cannot concatenate when pcb->unsent is empty", + (last_unsent != NULL)); + pbuf_cat(last_unsent->p, concat_p); + last_unsent->len += concat_p->tot_len; +#if TCP_CHECKSUM_ON_COPY + if (concat_chksummed) { + if (concat_chksum_swapped) { + concat_chksum = SWAP_BYTES_IN_WORD(concat_chksum); + } + tcp_seg_add_chksum(concat_chksum, concat_chksummed, &last_unsent->chksum, + &last_unsent->chksum_swapped); + last_unsent->flags |= TF_SEG_DATA_CHECKSUMMED; + } +#endif /* TCP_CHECKSUM_ON_COPY */ + } + + /* + * Phase 3: Append queue to pcb->unsent. Queue may be NULL, but that + * is harmless + */ + if (last_unsent == NULL) { + pcb->unsent = queue; + } else { + last_unsent->next = queue; + } + + /* + * Finally update the pcb state. + */ + pcb->snd_lbb += len; + pcb->snd_buf -= len; + pcb->snd_queuelen = queuelen; + + LWIP_DEBUGF(TCP_QLEN_DEBUG, ("tcp_write: %"S16_F" (after enqueued)\n", + pcb->snd_queuelen)); + if (pcb->snd_queuelen != 0) { + LWIP_ASSERT("tcp_write: valid queue length", + pcb->unacked != NULL || pcb->unsent != NULL); + } + + /* Set the PSH flag in the last segment that we enqueued. */ + if (seg != NULL && seg->tcphdr != NULL && ((apiflags & TCP_WRITE_FLAG_MORE)==0)) { + TCPH_SET_FLAG(seg->tcphdr, TCP_PSH); + } + + return ERR_OK; +memerr: + pcb->flags |= TF_NAGLEMEMERR; + TCP_STATS_INC(tcp.memerr); + + if (concat_p != NULL) { + pbuf_free(concat_p); + } + if (queue != NULL) { + tcp_segs_free(queue); + } + if (pcb->snd_queuelen != 0) { + LWIP_ASSERT("tcp_write: valid queue length", pcb->unacked != NULL || + pcb->unsent != NULL); + } + LWIP_DEBUGF(TCP_QLEN_DEBUG | LWIP_DBG_STATE, ("tcp_write: %"S16_F" (with mem err)\n", pcb->snd_queuelen)); + return ERR_MEM; +} + +/** + * Enqueue TCP options for transmission. + * + * Called by tcp_connect(), tcp_listen_input(), and tcp_send_ctrl(). + * + * @param pcb Protocol control block for the TCP connection. + * @param flags TCP header flags to set in the outgoing segment. + * @param optdata pointer to TCP options, or NULL. + * @param optlen length of TCP options in bytes. + */ +err_t +tcp_enqueue_flags(struct tcp_pcb *pcb, u8_t flags) +{ + struct pbuf *p; + struct tcp_seg *seg; + u8_t optflags = 0; + u8_t optlen = 0; + + LWIP_DEBUGF(TCP_QLEN_DEBUG, ("tcp_enqueue_flags: queuelen: %"U16_F"\n", (u16_t)pcb->snd_queuelen)); + + LWIP_ASSERT("tcp_enqueue_flags: need either TCP_SYN or TCP_FIN in flags (programmer violates API)", + (flags & (TCP_SYN | TCP_FIN)) != 0); + + /* check for configured max queuelen and possible overflow */ + if ((pcb->snd_queuelen >= TCP_SND_QUEUELEN) || (pcb->snd_queuelen > TCP_SNDQUEUELEN_OVERFLOW)) { + LWIP_DEBUGF(TCP_OUTPUT_DEBUG | 3, ("tcp_enqueue_flags: too long queue %"U16_F" (max %"U16_F")\n", + pcb->snd_queuelen, TCP_SND_QUEUELEN)); + TCP_STATS_INC(tcp.memerr); + pcb->flags |= TF_NAGLEMEMERR; + return ERR_MEM; + } + + if (flags & TCP_SYN) { + optflags = TF_SEG_OPTS_MSS; + } +#if LWIP_TCP_TIMESTAMPS + if ((pcb->flags & TF_TIMESTAMP)) { + optflags |= TF_SEG_OPTS_TS; + } +#endif /* LWIP_TCP_TIMESTAMPS */ + optlen = LWIP_TCP_OPT_LENGTH(optflags); + + /* tcp_enqueue_flags is always called with either SYN or FIN in flags. + * We need one available snd_buf byte to do that. + * This means we can't send FIN while snd_buf==0. A better fix would be to + * not include SYN and FIN sequence numbers in the snd_buf count. */ + if (pcb->snd_buf == 0) { + LWIP_DEBUGF(TCP_OUTPUT_DEBUG | 3, ("tcp_enqueue_flags: no send buffer available\n")); + TCP_STATS_INC(tcp.memerr); + return ERR_MEM; + } + + /* Allocate pbuf with room for TCP header + options */ + if ((p = pbuf_alloc(PBUF_TRANSPORT, optlen, PBUF_RAM)) == NULL) { + pcb->flags |= TF_NAGLEMEMERR; + TCP_STATS_INC(tcp.memerr); + return ERR_MEM; + } + LWIP_ASSERT("tcp_enqueue_flags: check that first pbuf can hold optlen", + (p->len >= optlen)); + + /* Allocate memory for tcp_seg, and fill in fields. */ + if ((seg = tcp_create_segment(pcb, p, flags, pcb->snd_lbb, optflags)) == NULL) { + pcb->flags |= TF_NAGLEMEMERR; + TCP_STATS_INC(tcp.memerr); + return ERR_MEM; + } + LWIP_ASSERT("seg->tcphdr not aligned", ((mem_ptr_t)seg->tcphdr % MEM_ALIGNMENT) == 0); + LWIP_ASSERT("tcp_enqueue_flags: invalid segment length", seg->len == 0); + + LWIP_DEBUGF(TCP_OUTPUT_DEBUG | LWIP_DBG_TRACE, + ("tcp_enqueue_flags: queueing %"U32_F":%"U32_F" (0x%"X16_F")\n", + ntohl(seg->tcphdr->seqno), + ntohl(seg->tcphdr->seqno) + TCP_TCPLEN(seg), + (u16_t)flags)); + + /* Now append seg to pcb->unsent queue */ + if (pcb->unsent == NULL) { + pcb->unsent = seg; + } else { + struct tcp_seg *useg; + for (useg = pcb->unsent; useg->next != NULL; useg = useg->next); + useg->next = seg; + } +#if TCP_OVERSIZE + /* The new unsent tail has no space */ + pcb->unsent_oversize = 0; +#endif /* TCP_OVERSIZE */ + + /* SYN and FIN bump the sequence number */ + if ((flags & TCP_SYN) || (flags & TCP_FIN)) { + pcb->snd_lbb++; + /* optlen does not influence snd_buf */ + pcb->snd_buf--; + } + if (flags & TCP_FIN) { + pcb->flags |= TF_FIN; + } + + /* update number of segments on the queues */ + pcb->snd_queuelen += pbuf_clen(seg->p); + LWIP_DEBUGF(TCP_QLEN_DEBUG, ("tcp_enqueue_flags: %"S16_F" (after enqueued)\n", pcb->snd_queuelen)); + if (pcb->snd_queuelen != 0) { + LWIP_ASSERT("tcp_enqueue_flags: invalid queue length", + pcb->unacked != NULL || pcb->unsent != NULL); + } + + return ERR_OK; +} + + +#if LWIP_TCP_TIMESTAMPS +/* Build a timestamp option (12 bytes long) at the specified options pointer) + * + * @param pcb tcp_pcb + * @param opts option pointer where to store the timestamp option + */ +static void +tcp_build_timestamp_option(struct tcp_pcb *pcb, u32_t *opts) +{ + /* Pad with two NOP options to make everything nicely aligned */ + opts[0] = PP_HTONL(0x0101080A); + opts[1] = htonl(sys_now()); + opts[2] = htonl(pcb->ts_recent); +} +#endif + +/** Send an ACK without data. + * + * @param pcb Protocol control block for the TCP connection to send the ACK + */ +err_t +tcp_send_empty_ack(struct tcp_pcb *pcb) +{ + struct pbuf *p; + struct tcp_hdr *tcphdr; + u8_t optlen = 0; + +#if LWIP_TCP_TIMESTAMPS + if (pcb->flags & TF_TIMESTAMP) { + optlen = LWIP_TCP_OPT_LENGTH(TF_SEG_OPTS_TS); + } +#endif + + p = tcp_output_alloc_header(pcb, optlen, 0, htonl(pcb->snd_nxt)); + if (p == NULL) { + LWIP_DEBUGF(TCP_OUTPUT_DEBUG, ("tcp_output: (ACK) could not allocate pbuf\n")); + return ERR_BUF; + } + tcphdr = (struct tcp_hdr *)p->payload; + LWIP_DEBUGF(TCP_OUTPUT_DEBUG, + ("tcp_output: sending ACK for %"U32_F"\n", pcb->rcv_nxt)); + /* remove ACK flags from the PCB, as we send an empty ACK now */ + pcb->flags &= ~(TF_ACK_DELAY | TF_ACK_NOW); + + /* NB. MSS option is only sent on SYNs, so ignore it here */ +#if LWIP_TCP_TIMESTAMPS + pcb->ts_lastacksent = pcb->rcv_nxt; + + if (pcb->flags & TF_TIMESTAMP) { + tcp_build_timestamp_option(pcb, (u32_t *)(tcphdr + 1)); + } +#endif + +#if CHECKSUM_GEN_TCP + tcphdr->chksum = inet_chksum_pseudo(p, &(pcb->local_ip), &(pcb->remote_ip), + IP_PROTO_TCP, p->tot_len); +#endif +#if LWIP_NETIF_HWADDRHINT + ip_output_hinted(p, &(pcb->local_ip), &(pcb->remote_ip), pcb->ttl, pcb->tos, + IP_PROTO_TCP, &(pcb->addr_hint)); +#else /* LWIP_NETIF_HWADDRHINT*/ + ip_output(p, &(pcb->local_ip), &(pcb->remote_ip), pcb->ttl, pcb->tos, + IP_PROTO_TCP); +#endif /* LWIP_NETIF_HWADDRHINT*/ + pbuf_free(p); + + return ERR_OK; +} + +/** + * Find out what we can send and send it + * + * @param pcb Protocol control block for the TCP connection to send data + * @return ERR_OK if data has been sent or nothing to send + * another err_t on error + */ +err_t +tcp_output(struct tcp_pcb *pcb) +{ + struct tcp_seg *seg, *useg; + u32_t wnd, snd_nxt; +#if TCP_CWND_DEBUG + s16_t i = 0; +#endif /* TCP_CWND_DEBUG */ + + /* First, check if we are invoked by the TCP input processing + code. If so, we do not output anything. Instead, we rely on the + input processing code to call us when input processing is done + with. */ + if (tcp_input_pcb == pcb) { + return ERR_OK; + } + + wnd = LWIP_MIN(pcb->snd_wnd, pcb->cwnd); + + seg = pcb->unsent; + + /* If the TF_ACK_NOW flag is set and no data will be sent (either + * because the ->unsent queue is empty or because the window does + * not allow it), construct an empty ACK segment and send it. + * + * If data is to be sent, we will just piggyback the ACK (see below). + */ + if (pcb->flags & TF_ACK_NOW && + (seg == NULL || + ntohl(seg->tcphdr->seqno) - pcb->lastack + seg->len > wnd)) { + return tcp_send_empty_ack(pcb); + } + + /* useg should point to last segment on unacked queue */ + useg = pcb->unacked; + if (useg != NULL) { + for (; useg->next != NULL; useg = useg->next); + } + +#if TCP_OUTPUT_DEBUG + if (seg == NULL) { + LWIP_DEBUGF(TCP_OUTPUT_DEBUG, ("tcp_output: nothing to send (%p)\n", + (void*)pcb->unsent)); + } +#endif /* TCP_OUTPUT_DEBUG */ +#if TCP_CWND_DEBUG + if (seg == NULL) { + LWIP_DEBUGF(TCP_CWND_DEBUG, ("tcp_output: snd_wnd %"U16_F + ", cwnd %"U16_F", wnd %"U32_F + ", seg == NULL, ack %"U32_F"\n", + pcb->snd_wnd, pcb->cwnd, wnd, pcb->lastack)); + } else { + LWIP_DEBUGF(TCP_CWND_DEBUG, + ("tcp_output: snd_wnd %"U16_F", cwnd %"U16_F", wnd %"U32_F + ", effwnd %"U32_F", seq %"U32_F", ack %"U32_F"\n", + pcb->snd_wnd, pcb->cwnd, wnd, + ntohl(seg->tcphdr->seqno) - pcb->lastack + seg->len, + ntohl(seg->tcphdr->seqno), pcb->lastack)); + } +#endif /* TCP_CWND_DEBUG */ + /* data available and window allows it to be sent? */ + while (seg != NULL && + ntohl(seg->tcphdr->seqno) - pcb->lastack + seg->len <= wnd) { + LWIP_ASSERT("RST not expected here!", + (TCPH_FLAGS(seg->tcphdr) & TCP_RST) == 0); + /* Stop sending if the nagle algorithm would prevent it + * Don't stop: + * - if tcp_write had a memory error before (prevent delayed ACK timeout) or + * - if FIN was already enqueued for this PCB (SYN is always alone in a segment - + * either seg->next != NULL or pcb->unacked == NULL; + * RST is no sent using tcp_write/tcp_output. + */ + if((tcp_do_output_nagle(pcb) == 0) && + ((pcb->flags & (TF_NAGLEMEMERR | TF_FIN)) == 0)){ + break; + } +#if TCP_CWND_DEBUG + LWIP_DEBUGF(TCP_CWND_DEBUG, ("tcp_output: snd_wnd %"U16_F", cwnd %"U16_F", wnd %"U32_F", effwnd %"U32_F", seq %"U32_F", ack %"U32_F", i %"S16_F"\n", + pcb->snd_wnd, pcb->cwnd, wnd, + ntohl(seg->tcphdr->seqno) + seg->len - + pcb->lastack, + ntohl(seg->tcphdr->seqno), pcb->lastack, i)); + ++i; +#endif /* TCP_CWND_DEBUG */ + + pcb->unsent = seg->next; + + if (pcb->state != SYN_SENT) { + TCPH_SET_FLAG(seg->tcphdr, TCP_ACK); + pcb->flags &= ~(TF_ACK_DELAY | TF_ACK_NOW); + } + + tcp_output_segment(seg, pcb); + snd_nxt = ntohl(seg->tcphdr->seqno) + TCP_TCPLEN(seg); + if (TCP_SEQ_LT(pcb->snd_nxt, snd_nxt)) { + pcb->snd_nxt = snd_nxt; + } + /* put segment on unacknowledged list if length > 0 */ + if (TCP_TCPLEN(seg) > 0) { + seg->next = NULL; + /* unacked list is empty? */ + if (pcb->unacked == NULL) { + pcb->unacked = seg; + useg = seg; + /* unacked list is not empty? */ + } else { + /* In the case of fast retransmit, the packet should not go to the tail + * of the unacked queue, but rather somewhere before it. We need to check for + * this case. -STJ Jul 27, 2004 */ + if (TCP_SEQ_LT(ntohl(seg->tcphdr->seqno), ntohl(useg->tcphdr->seqno))) { + /* add segment to before tail of unacked list, keeping the list sorted */ + struct tcp_seg **cur_seg = &(pcb->unacked); + while (*cur_seg && + TCP_SEQ_LT(ntohl((*cur_seg)->tcphdr->seqno), ntohl(seg->tcphdr->seqno))) { + cur_seg = &((*cur_seg)->next ); + } + seg->next = (*cur_seg); + (*cur_seg) = seg; + } else { + /* add segment to tail of unacked list */ + useg->next = seg; + useg = useg->next; + } + } + /* do not queue empty segments on the unacked list */ + } else { + tcp_seg_free(seg); + } + seg = pcb->unsent; + } +#if TCP_OVERSIZE + if (pcb->unsent == NULL) { + /* last unsent has been removed, reset unsent_oversize */ + pcb->unsent_oversize = 0; + } +#endif /* TCP_OVERSIZE */ + + if (seg != NULL && pcb->persist_backoff == 0 && + ntohl(seg->tcphdr->seqno) - pcb->lastack + seg->len > pcb->snd_wnd) { + /* prepare for persist timer */ + pcb->persist_cnt = 0; + pcb->persist_backoff = 1; + } + + pcb->flags &= ~TF_NAGLEMEMERR; + return ERR_OK; +} + +/** + * Called by tcp_output() to actually send a TCP segment over IP. + * + * @param seg the tcp_seg to send + * @param pcb the tcp_pcb for the TCP connection used to send the segment + */ +static void +tcp_output_segment(struct tcp_seg *seg, struct tcp_pcb *pcb) +{ + u16_t len; + struct netif *netif; + u32_t *opts; + + /** @bug Exclude retransmitted segments from this count. */ + snmp_inc_tcpoutsegs(); + + /* The TCP header has already been constructed, but the ackno and + wnd fields remain. */ + seg->tcphdr->ackno = htonl(pcb->rcv_nxt); + + /* advertise our receive window size in this TCP segment */ + seg->tcphdr->wnd = htons(pcb->rcv_ann_wnd); + + pcb->rcv_ann_right_edge = pcb->rcv_nxt + pcb->rcv_ann_wnd; + + /* Add any requested options. NB MSS option is only set on SYN + packets, so ignore it here */ + LWIP_ASSERT("seg->tcphdr not aligned", ((mem_ptr_t)seg->tcphdr % MEM_ALIGNMENT) == 0); + opts = (u32_t *)(void *)(seg->tcphdr + 1); + if (seg->flags & TF_SEG_OPTS_MSS) { + TCP_BUILD_MSS_OPTION(*opts); + opts += 1; + } +#if LWIP_TCP_TIMESTAMPS + pcb->ts_lastacksent = pcb->rcv_nxt; + + if (seg->flags & TF_SEG_OPTS_TS) { + tcp_build_timestamp_option(pcb, opts); + opts += 3; + } +#endif + + /* Set retransmission timer running if it is not currently enabled + This must be set before checking the route. */ + if (pcb->rtime == -1) { + pcb->rtime = 0; + } + + /* If we don't have a local IP address, we get one by + calling ip_route(). */ + if (ip_addr_isany(&(pcb->local_ip))) { + netif = ip_route(&(pcb->remote_ip)); + if (netif == NULL) { + return; + } + ip_addr_copy(pcb->local_ip, netif->ip_addr); + } + + if (pcb->rttest == 0) { + pcb->rttest = tcp_ticks; + pcb->rtseq = ntohl(seg->tcphdr->seqno); + + LWIP_DEBUGF(TCP_RTO_DEBUG, ("tcp_output_segment: rtseq %"U32_F"\n", pcb->rtseq)); + } + LWIP_DEBUGF(TCP_OUTPUT_DEBUG, ("tcp_output_segment: %"U32_F":%"U32_F"\n", + htonl(seg->tcphdr->seqno), htonl(seg->tcphdr->seqno) + + seg->len)); + + len = (u16_t)((u8_t *)seg->tcphdr - (u8_t *)seg->p->payload); + + seg->p->len -= len; + seg->p->tot_len -= len; + + seg->p->payload = seg->tcphdr; + + seg->tcphdr->chksum = 0; +#if CHECKSUM_GEN_TCP +#if TCP_CHECKSUM_ON_COPY + { + u32_t acc; +#if TCP_CHECKSUM_ON_COPY_SANITY_CHECK + u16_t chksum_slow = inet_chksum_pseudo(seg->p, &(pcb->local_ip), + &(pcb->remote_ip), + IP_PROTO_TCP, seg->p->tot_len); +#endif /* TCP_CHECKSUM_ON_COPY_SANITY_CHECK */ + if ((seg->flags & TF_SEG_DATA_CHECKSUMMED) == 0) { + LWIP_ASSERT("data included but not checksummed", + seg->p->tot_len == (TCPH_HDRLEN(seg->tcphdr) * 4)); + } + + /* rebuild TCP header checksum (TCP header changes for retransmissions!) */ + acc = inet_chksum_pseudo_partial(seg->p, &(pcb->local_ip), + &(pcb->remote_ip), + IP_PROTO_TCP, seg->p->tot_len, TCPH_HDRLEN(seg->tcphdr) * 4); + /* add payload checksum */ + if (seg->chksum_swapped) { + seg->chksum = SWAP_BYTES_IN_WORD(seg->chksum); + seg->chksum_swapped = 0; + } + acc += (u16_t)~(seg->chksum); + seg->tcphdr->chksum = FOLD_U32T(acc); +#if TCP_CHECKSUM_ON_COPY_SANITY_CHECK + if (chksum_slow != seg->tcphdr->chksum) { + LWIP_DEBUGF(TCP_DEBUG | LWIP_DBG_LEVEL_WARNING, + ("tcp_output_segment: calculated checksum is %"X16_F" instead of %"X16_F"\n", + seg->tcphdr->chksum, chksum_slow)); + seg->tcphdr->chksum = chksum_slow; + } +#endif /* TCP_CHECKSUM_ON_COPY_SANITY_CHECK */ + } +#else /* TCP_CHECKSUM_ON_COPY */ + seg->tcphdr->chksum = inet_chksum_pseudo(seg->p, &(pcb->local_ip), + &(pcb->remote_ip), + IP_PROTO_TCP, seg->p->tot_len); +#endif /* TCP_CHECKSUM_ON_COPY */ +#endif /* CHECKSUM_GEN_TCP */ + TCP_STATS_INC(tcp.xmit); + +#if LWIP_NETIF_HWADDRHINT + ip_output_hinted(seg->p, &(pcb->local_ip), &(pcb->remote_ip), pcb->ttl, pcb->tos, + IP_PROTO_TCP, &(pcb->addr_hint)); +#else /* LWIP_NETIF_HWADDRHINT*/ + ip_output(seg->p, &(pcb->local_ip), &(pcb->remote_ip), pcb->ttl, pcb->tos, + IP_PROTO_TCP); +#endif /* LWIP_NETIF_HWADDRHINT*/ +} + +/** + * Send a TCP RESET packet (empty segment with RST flag set) either to + * abort a connection or to show that there is no matching local connection + * for a received segment. + * + * Called by tcp_abort() (to abort a local connection), tcp_input() (if no + * matching local pcb was found), tcp_listen_input() (if incoming segment + * has ACK flag set) and tcp_process() (received segment in the wrong state) + * + * Since a RST segment is in most cases not sent for an active connection, + * tcp_rst() has a number of arguments that are taken from a tcp_pcb for + * most other segment output functions. + * + * @param seqno the sequence number to use for the outgoing segment + * @param ackno the acknowledge number to use for the outgoing segment + * @param local_ip the local IP address to send the segment from + * @param remote_ip the remote IP address to send the segment to + * @param local_port the local TCP port to send the segment from + * @param remote_port the remote TCP port to send the segment to + */ +void +tcp_rst(u32_t seqno, u32_t ackno, + ip_addr_t *local_ip, ip_addr_t *remote_ip, + u16_t local_port, u16_t remote_port) +{ + struct pbuf *p; + struct tcp_hdr *tcphdr; + p = pbuf_alloc(PBUF_IP, TCP_HLEN, PBUF_RAM); + if (p == NULL) { + LWIP_DEBUGF(TCP_DEBUG, ("tcp_rst: could not allocate memory for pbuf\n")); + return; + } + LWIP_ASSERT("check that first pbuf can hold struct tcp_hdr", + (p->len >= sizeof(struct tcp_hdr))); + + tcphdr = (struct tcp_hdr *)p->payload; + tcphdr->src = htons(local_port); + tcphdr->dest = htons(remote_port); + tcphdr->seqno = htonl(seqno); + tcphdr->ackno = htonl(ackno); + TCPH_HDRLEN_FLAGS_SET(tcphdr, TCP_HLEN/4, TCP_RST | TCP_ACK); + tcphdr->wnd = PP_HTONS(TCP_WND); + tcphdr->chksum = 0; + tcphdr->urgp = 0; + +#if CHECKSUM_GEN_TCP + tcphdr->chksum = inet_chksum_pseudo(p, local_ip, remote_ip, + IP_PROTO_TCP, p->tot_len); +#endif + TCP_STATS_INC(tcp.xmit); + snmp_inc_tcpoutrsts(); + /* Send output with hardcoded TTL since we have no access to the pcb */ + ip_output(p, local_ip, remote_ip, TCP_TTL, 0, IP_PROTO_TCP); + pbuf_free(p); + LWIP_DEBUGF(TCP_RST_DEBUG, ("tcp_rst: seqno %"U32_F" ackno %"U32_F".\n", seqno, ackno)); +} + +/** + * Requeue all unacked segments for retransmission + * + * Called by tcp_slowtmr() for slow retransmission. + * + * @param pcb the tcp_pcb for which to re-enqueue all unacked segments + */ +void +tcp_rexmit_rto(struct tcp_pcb *pcb) +{ + struct tcp_seg *seg; + + if (pcb->unacked == NULL) { + return; + } + + /* Move all unacked segments to the head of the unsent queue */ + for (seg = pcb->unacked; seg->next != NULL; seg = seg->next); + /* concatenate unsent queue after unacked queue */ + seg->next = pcb->unsent; + /* unsent queue is the concatenated queue (of unacked, unsent) */ + pcb->unsent = pcb->unacked; + /* unacked queue is now empty */ + pcb->unacked = NULL; + + /* increment number of retransmissions */ + ++pcb->nrtx; + + /* Don't take any RTT measurements after retransmitting. */ + pcb->rttest = 0; + + /* Do the actual retransmission */ + tcp_output(pcb); +} + +/** + * Requeue the first unacked segment for retransmission + * + * Called by tcp_receive() for fast retramsmit. + * + * @param pcb the tcp_pcb for which to retransmit the first unacked segment + */ +void +tcp_rexmit(struct tcp_pcb *pcb) +{ + struct tcp_seg *seg; + struct tcp_seg **cur_seg; + + if (pcb->unacked == NULL) { + return; + } + + /* Move the first unacked segment to the unsent queue */ + /* Keep the unsent queue sorted. */ + seg = pcb->unacked; + pcb->unacked = seg->next; + + cur_seg = &(pcb->unsent); + while (*cur_seg && + TCP_SEQ_LT(ntohl((*cur_seg)->tcphdr->seqno), ntohl(seg->tcphdr->seqno))) { + cur_seg = &((*cur_seg)->next ); + } + seg->next = *cur_seg; + *cur_seg = seg; + + ++pcb->nrtx; + + /* Don't take any rtt measurements after retransmitting. */ + pcb->rttest = 0; + + /* Do the actual retransmission. */ + snmp_inc_tcpretranssegs(); + /* No need to call tcp_output: we are always called from tcp_input() + and thus tcp_output directly returns. */ +} + + +/** + * Handle retransmission after three dupacks received + * + * @param pcb the tcp_pcb for which to retransmit the first unacked segment + */ +void +tcp_rexmit_fast(struct tcp_pcb *pcb) +{ + if (pcb->unacked != NULL && !(pcb->flags & TF_INFR)) { + /* This is fast retransmit. Retransmit the first unacked segment. */ + LWIP_DEBUGF(TCP_FR_DEBUG, + ("tcp_receive: dupacks %"U16_F" (%"U32_F + "), fast retransmit %"U32_F"\n", + (u16_t)pcb->dupacks, pcb->lastack, + ntohl(pcb->unacked->tcphdr->seqno))); + tcp_rexmit(pcb); + + /* Set ssthresh to half of the minimum of the current + * cwnd and the advertised window */ + if (pcb->cwnd > pcb->snd_wnd) { + pcb->ssthresh = pcb->snd_wnd / 2; + } else { + pcb->ssthresh = pcb->cwnd / 2; + } + + /* The minimum value for ssthresh should be 2 MSS */ + if (pcb->ssthresh < 2*pcb->mss) { + LWIP_DEBUGF(TCP_FR_DEBUG, + ("tcp_receive: The minimum value for ssthresh %"U16_F + " should be min 2 mss %"U16_F"...\n", + pcb->ssthresh, 2*pcb->mss)); + pcb->ssthresh = 2*pcb->mss; + } + + pcb->cwnd = pcb->ssthresh + 3 * pcb->mss; + pcb->flags |= TF_INFR; + } +} + + +/** + * Send keepalive packets to keep a connection active although + * no data is sent over it. + * + * Called by tcp_slowtmr() + * + * @param pcb the tcp_pcb for which to send a keepalive packet + */ +void +tcp_keepalive(struct tcp_pcb *pcb) +{ + struct pbuf *p; + struct tcp_hdr *tcphdr; + + LWIP_DEBUGF(TCP_DEBUG, ("tcp_keepalive: sending KEEPALIVE probe to %"U16_F".%"U16_F".%"U16_F".%"U16_F"\n", + ip4_addr1_16(&pcb->remote_ip), ip4_addr2_16(&pcb->remote_ip), + ip4_addr3_16(&pcb->remote_ip), ip4_addr4_16(&pcb->remote_ip))); + + LWIP_DEBUGF(TCP_DEBUG, ("tcp_keepalive: tcp_ticks %"U32_F" pcb->tmr %"U32_F" pcb->keep_cnt_sent %"U16_F"\n", + tcp_ticks, pcb->tmr, pcb->keep_cnt_sent)); + + p = tcp_output_alloc_header(pcb, 0, 0, htonl(pcb->snd_nxt - 1)); + if(p == NULL) { + LWIP_DEBUGF(TCP_DEBUG, + ("tcp_keepalive: could not allocate memory for pbuf\n")); + return; + } + tcphdr = (struct tcp_hdr *)p->payload; + +#if CHECKSUM_GEN_TCP + tcphdr->chksum = inet_chksum_pseudo(p, &pcb->local_ip, &pcb->remote_ip, + IP_PROTO_TCP, p->tot_len); +#endif + TCP_STATS_INC(tcp.xmit); + + /* Send output to IP */ +#if LWIP_NETIF_HWADDRHINT + ip_output_hinted(p, &pcb->local_ip, &pcb->remote_ip, pcb->ttl, 0, IP_PROTO_TCP, + &(pcb->addr_hint)); +#else /* LWIP_NETIF_HWADDRHINT*/ + ip_output(p, &pcb->local_ip, &pcb->remote_ip, pcb->ttl, 0, IP_PROTO_TCP); +#endif /* LWIP_NETIF_HWADDRHINT*/ + + pbuf_free(p); + + LWIP_DEBUGF(TCP_DEBUG, ("tcp_keepalive: seqno %"U32_F" ackno %"U32_F".\n", + pcb->snd_nxt - 1, pcb->rcv_nxt)); +} + + +/** + * Send persist timer zero-window probes to keep a connection active + * when a window update is lost. + * + * Called by tcp_slowtmr() + * + * @param pcb the tcp_pcb for which to send a zero-window probe packet + */ +void +tcp_zero_window_probe(struct tcp_pcb *pcb) +{ + struct pbuf *p; + struct tcp_hdr *tcphdr; + struct tcp_seg *seg; + u16_t len; + u8_t is_fin; + + LWIP_DEBUGF(TCP_DEBUG, + ("tcp_zero_window_probe: sending ZERO WINDOW probe to %" + U16_F".%"U16_F".%"U16_F".%"U16_F"\n", + ip4_addr1_16(&pcb->remote_ip), ip4_addr2_16(&pcb->remote_ip), + ip4_addr3_16(&pcb->remote_ip), ip4_addr4_16(&pcb->remote_ip))); + + LWIP_DEBUGF(TCP_DEBUG, + ("tcp_zero_window_probe: tcp_ticks %"U32_F + " pcb->tmr %"U32_F" pcb->keep_cnt_sent %"U16_F"\n", + tcp_ticks, pcb->tmr, pcb->keep_cnt_sent)); + + seg = pcb->unacked; + + if(seg == NULL) { + seg = pcb->unsent; + } + if(seg == NULL) { + return; + } + + is_fin = ((TCPH_FLAGS(seg->tcphdr) & TCP_FIN) != 0) && (seg->len == 0); + /* we want to send one seqno: either FIN or data (no options) */ + len = is_fin ? 0 : 1; + + p = tcp_output_alloc_header(pcb, 0, len, seg->tcphdr->seqno); + if(p == NULL) { + LWIP_DEBUGF(TCP_DEBUG, ("tcp_zero_window_probe: no memory for pbuf\n")); + return; + } + tcphdr = (struct tcp_hdr *)p->payload; + + if (is_fin) { + /* FIN segment, no data */ + TCPH_FLAGS_SET(tcphdr, TCP_ACK | TCP_FIN); + } else { + /* Data segment, copy in one byte from the head of the unacked queue */ + struct tcp_hdr *thdr = (struct tcp_hdr *)seg->p->payload; + char *d = ((char *)p->payload + TCP_HLEN); + pbuf_copy_partial(seg->p, d, 1, TCPH_HDRLEN(thdr) * 4); + } + +#if CHECKSUM_GEN_TCP + tcphdr->chksum = inet_chksum_pseudo(p, &pcb->local_ip, &pcb->remote_ip, + IP_PROTO_TCP, p->tot_len); +#endif + TCP_STATS_INC(tcp.xmit); + + /* Send output to IP */ +#if LWIP_NETIF_HWADDRHINT + ip_output_hinted(p, &pcb->local_ip, &pcb->remote_ip, pcb->ttl, 0, IP_PROTO_TCP, + &(pcb->addr_hint)); +#else /* LWIP_NETIF_HWADDRHINT*/ + ip_output(p, &pcb->local_ip, &pcb->remote_ip, pcb->ttl, 0, IP_PROTO_TCP); +#endif /* LWIP_NETIF_HWADDRHINT*/ + + pbuf_free(p); + + LWIP_DEBUGF(TCP_DEBUG, ("tcp_zero_window_probe: seqno %"U32_F + " ackno %"U32_F".\n", + pcb->snd_nxt - 1, pcb->rcv_nxt)); +} +#endif /* LWIP_TCP */ diff --git a/features/unsupported/net/lwip/lwip/core/timers.c b/features/unsupported/net/lwip/lwip/core/timers.c new file mode 100644 index 00000000000..f0e92ccebe7 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/core/timers.c @@ -0,0 +1,482 @@ +/** + * @file + * Stack-internal timers implementation. + * This file includes timer callbacks for stack-internal timers as well as + * functions to set up or stop timers and check for expired timers. + * + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * Simon Goldschmidt + * + */ + +#include "lwip/opt.h" + +#include "lwip/timers.h" +#include "lwip/tcp_impl.h" + +#if LWIP_TIMERS + +#include "lwip/def.h" +#include "lwip/memp.h" +#include "lwip/tcpip.h" + +#include "lwip/ip_frag.h" +#include "netif/etharp.h" +#include "lwip/dhcp.h" +#include "lwip/autoip.h" +#include "lwip/igmp.h" +#include "lwip/dns.h" + + +/** The one and only timeout list */ +static struct sys_timeo *next_timeout; +#if NO_SYS +static u32_t timeouts_last_time; +#endif /* NO_SYS */ + +#if LWIP_TCP +/** global variable that shows if the tcp timer is currently scheduled or not */ +static int tcpip_tcp_timer_active; + +/** + * Timer callback function that calls tcp_tmr() and reschedules itself. + * + * @param arg unused argument + */ +static void +tcpip_tcp_timer(void *arg) +{ + LWIP_UNUSED_ARG(arg); + + /* call TCP timer handler */ + tcp_tmr(); + /* timer still needed? */ + if (tcp_active_pcbs || tcp_tw_pcbs) { + /* restart timer */ + sys_timeout(TCP_TMR_INTERVAL, tcpip_tcp_timer, NULL); + } else { + /* disable timer */ + tcpip_tcp_timer_active = 0; + } +} + +/** + * Called from TCP_REG when registering a new PCB: + * the reason is to have the TCP timer only running when + * there are active (or time-wait) PCBs. + */ +void +tcp_timer_needed(void) +{ + /* timer is off but needed again? */ + if (!tcpip_tcp_timer_active && (tcp_active_pcbs || tcp_tw_pcbs)) { + /* enable and start timer */ + tcpip_tcp_timer_active = 1; + sys_timeout(TCP_TMR_INTERVAL, tcpip_tcp_timer, NULL); + } +} +#endif /* LWIP_TCP */ + +#if IP_REASSEMBLY +/** + * Timer callback function that calls ip_reass_tmr() and reschedules itself. + * + * @param arg unused argument + */ +static void +ip_reass_timer(void *arg) +{ + LWIP_UNUSED_ARG(arg); + LWIP_DEBUGF(TIMERS_DEBUG, ("tcpip: ip_reass_tmr()\n")); + ip_reass_tmr(); + sys_timeout(IP_TMR_INTERVAL, ip_reass_timer, NULL); +} +#endif /* IP_REASSEMBLY */ + +#if LWIP_ARP +/** + * Timer callback function that calls etharp_tmr() and reschedules itself. + * + * @param arg unused argument + */ +static void +arp_timer(void *arg) +{ + LWIP_UNUSED_ARG(arg); + LWIP_DEBUGF(TIMERS_DEBUG, ("tcpip: etharp_tmr()\n")); + etharp_tmr(); + sys_timeout(ARP_TMR_INTERVAL, arp_timer, NULL); +} +#endif /* LWIP_ARP */ + +#if LWIP_DHCP +/** + * Timer callback function that calls dhcp_coarse_tmr() and reschedules itself. + * + * @param arg unused argument + */ +static void +dhcp_timer_coarse(void *arg) +{ + LWIP_UNUSED_ARG(arg); + LWIP_DEBUGF(TIMERS_DEBUG, ("tcpip: dhcp_coarse_tmr()\n")); + dhcp_coarse_tmr(); + sys_timeout(DHCP_COARSE_TIMER_MSECS, dhcp_timer_coarse, NULL); +} + +/** + * Timer callback function that calls dhcp_fine_tmr() and reschedules itself. + * + * @param arg unused argument + */ +static void +dhcp_timer_fine(void *arg) +{ + LWIP_UNUSED_ARG(arg); + LWIP_DEBUGF(TIMERS_DEBUG, ("tcpip: dhcp_fine_tmr()\n")); + dhcp_fine_tmr(); + sys_timeout(DHCP_FINE_TIMER_MSECS, dhcp_timer_fine, NULL); +} +#endif /* LWIP_DHCP */ + +#if LWIP_AUTOIP +/** + * Timer callback function that calls autoip_tmr() and reschedules itself. + * + * @param arg unused argument + */ +static void +autoip_timer(void *arg) +{ + LWIP_UNUSED_ARG(arg); + LWIP_DEBUGF(TIMERS_DEBUG, ("tcpip: autoip_tmr()\n")); + autoip_tmr(); + sys_timeout(AUTOIP_TMR_INTERVAL, autoip_timer, NULL); +} +#endif /* LWIP_AUTOIP */ + +#if LWIP_IGMP +/** + * Timer callback function that calls igmp_tmr() and reschedules itself. + * + * @param arg unused argument + */ +static void +igmp_timer(void *arg) +{ + LWIP_UNUSED_ARG(arg); + LWIP_DEBUGF(TIMERS_DEBUG, ("tcpip: igmp_tmr()\n")); + igmp_tmr(); + sys_timeout(IGMP_TMR_INTERVAL, igmp_timer, NULL); +} +#endif /* LWIP_IGMP */ + +#if LWIP_DNS +/** + * Timer callback function that calls dns_tmr() and reschedules itself. + * + * @param arg unused argument + */ +static void +dns_timer(void *arg) +{ + LWIP_UNUSED_ARG(arg); + LWIP_DEBUGF(TIMERS_DEBUG, ("tcpip: dns_tmr()\n")); + dns_tmr(); + sys_timeout(DNS_TMR_INTERVAL, dns_timer, NULL); +} +#endif /* LWIP_DNS */ + +/** Initialize this module */ +void sys_timeouts_init(void) +{ +#if IP_REASSEMBLY + sys_timeout(IP_TMR_INTERVAL, ip_reass_timer, NULL); +#endif /* IP_REASSEMBLY */ +#if LWIP_ARP + sys_timeout(ARP_TMR_INTERVAL, arp_timer, NULL); +#endif /* LWIP_ARP */ +#if LWIP_DHCP + sys_timeout(DHCP_COARSE_TIMER_MSECS, dhcp_timer_coarse, NULL); + sys_timeout(DHCP_FINE_TIMER_MSECS, dhcp_timer_fine, NULL); +#endif /* LWIP_DHCP */ +#if LWIP_AUTOIP + sys_timeout(AUTOIP_TMR_INTERVAL, autoip_timer, NULL); +#endif /* LWIP_AUTOIP */ +#if LWIP_IGMP + sys_timeout(IGMP_TMR_INTERVAL, igmp_timer, NULL); +#endif /* LWIP_IGMP */ +#if LWIP_DNS + sys_timeout(DNS_TMR_INTERVAL, dns_timer, NULL); +#endif /* LWIP_DNS */ + +#if NO_SYS + /* Initialise timestamp for sys_check_timeouts */ + timeouts_last_time = sys_now(); +#endif +} + +/** + * Create a one-shot timer (aka timeout). Timeouts are processed in the + * following cases: + * - while waiting for a message using sys_timeouts_mbox_fetch() + * - by calling sys_check_timeouts() (NO_SYS==1 only) + * + * @param msecs time in milliseconds after that the timer should expire + * @param handler callback function to call when msecs have elapsed + * @param arg argument to pass to the callback function + */ +#if LWIP_DEBUG_TIMERNAMES +void +sys_timeout_debug(u32_t msecs, sys_timeout_handler handler, void *arg, const char* handler_name) +#else /* LWIP_DEBUG_TIMERNAMES */ +void +sys_timeout(u32_t msecs, sys_timeout_handler handler, void *arg) +#endif /* LWIP_DEBUG_TIMERNAMES */ +{ + struct sys_timeo *timeout, *t; + + timeout = (struct sys_timeo *)memp_malloc(MEMP_SYS_TIMEOUT); + if (timeout == NULL) { + LWIP_ASSERT("sys_timeout: timeout != NULL, pool MEMP_SYS_TIMEOUT is empty", timeout != NULL); + return; + } + timeout->next = NULL; + timeout->h = handler; + timeout->arg = arg; + timeout->time = msecs; +#if LWIP_DEBUG_TIMERNAMES + timeout->handler_name = handler_name; + LWIP_DEBUGF(TIMERS_DEBUG, ("sys_timeout: %p msecs=%"U32_F" handler=%s arg=%p\n", + (void *)timeout, msecs, handler_name, (void *)arg)); +#endif /* LWIP_DEBUG_TIMERNAMES */ + + if (next_timeout == NULL) { + next_timeout = timeout; + return; + } + + if (next_timeout->time > msecs) { + next_timeout->time -= msecs; + timeout->next = next_timeout; + next_timeout = timeout; + } else { + for(t = next_timeout; t != NULL; t = t->next) { + timeout->time -= t->time; + if (t->next == NULL || t->next->time > timeout->time) { + if (t->next != NULL) { + t->next->time -= timeout->time; + } + timeout->next = t->next; + t->next = timeout; + break; + } + } + } +} + +/** + * Go through timeout list (for this task only) and remove the first matching + * entry, even though the timeout has not triggered yet. + * + * @note This function only works as expected if there is only one timeout + * calling 'handler' in the list of timeouts. + * + * @param handler callback function that would be called by the timeout + * @param arg callback argument that would be passed to handler +*/ +void +sys_untimeout(sys_timeout_handler handler, void *arg) +{ + struct sys_timeo *prev_t, *t; + + if (next_timeout == NULL) { + return; + } + + for (t = next_timeout, prev_t = NULL; t != NULL; prev_t = t, t = t->next) { + if ((t->h == handler) && (t->arg == arg)) { + /* We have a match */ + /* Unlink from previous in list */ + if (prev_t == NULL) { + next_timeout = t->next; + } else { + prev_t->next = t->next; + } + /* If not the last one, add time of this one back to next */ + if (t->next != NULL) { + t->next->time += t->time; + } + memp_free(MEMP_SYS_TIMEOUT, t); + return; + } + } + return; +} + +#if NO_SYS + +/** Handle timeouts for NO_SYS==1 (i.e. without using + * tcpip_thread/sys_timeouts_mbox_fetch(). Uses sys_now() to call timeout + * handler functions when timeouts expire. + * + * Must be called periodically from your main loop. + */ +void +sys_check_timeouts(void) +{ + struct sys_timeo *tmptimeout; + u32_t diff; + sys_timeout_handler handler; + void *arg; + int had_one; + u32_t now; + + now = sys_now(); + if (next_timeout) { + /* this cares for wraparounds */ + diff = LWIP_U32_DIFF(now, timeouts_last_time); + do + { + had_one = 0; + tmptimeout = next_timeout; + if (tmptimeout->time <= diff) { + /* timeout has expired */ + had_one = 1; + timeouts_last_time = now; + diff -= tmptimeout->time; + next_timeout = tmptimeout->next; + handler = tmptimeout->h; + arg = tmptimeout->arg; +#if LWIP_DEBUG_TIMERNAMES + if (handler != NULL) { + LWIP_DEBUGF(TIMERS_DEBUG, ("sct calling h=%s arg=%p\n", + tmptimeout->handler_name, arg)); + } +#endif /* LWIP_DEBUG_TIMERNAMES */ + memp_free(MEMP_SYS_TIMEOUT, tmptimeout); + if (handler != NULL) { + handler(arg); + } + } + /* repeat until all expired timers have been called */ + }while(had_one); + } +} + +/** Set back the timestamp of the last call to sys_check_timeouts() + * This is necessary if sys_check_timeouts() hasn't been called for a long + * time (e.g. while saving energy) to prevent all timer functions of that + * period being called. + */ +void +sys_restart_timeouts(void) +{ + timeouts_last_time = sys_now(); +} + +#else /* NO_SYS */ + +/** + * Wait (forever) for a message to arrive in an mbox. + * While waiting, timeouts are processed. + * + * @param mbox the mbox to fetch the message from + * @param msg the place to store the message + */ +void +sys_timeouts_mbox_fetch(sys_mbox_t *mbox, void **msg) +{ + u32_t time_needed; + struct sys_timeo *tmptimeout; + sys_timeout_handler handler; + void *arg; + + again: + if (!next_timeout) { + time_needed = sys_arch_mbox_fetch(mbox, msg, 0); + } else { + if (next_timeout->time > 0) { + time_needed = sys_arch_mbox_fetch(mbox, msg, next_timeout->time); + } else { + time_needed = SYS_ARCH_TIMEOUT; + } + + if (time_needed == SYS_ARCH_TIMEOUT) { + /* If time == SYS_ARCH_TIMEOUT, a timeout occured before a message + could be fetched. We should now call the timeout handler and + deallocate the memory allocated for the timeout. */ + tmptimeout = next_timeout; + next_timeout = tmptimeout->next; + handler = tmptimeout->h; + arg = tmptimeout->arg; +#if LWIP_DEBUG_TIMERNAMES + if (handler != NULL) { + LWIP_DEBUGF(TIMERS_DEBUG, ("stmf calling h=%s arg=%p\n", + tmptimeout->handler_name, arg)); + } +#endif /* LWIP_DEBUG_TIMERNAMES */ + memp_free(MEMP_SYS_TIMEOUT, tmptimeout); + if (handler != NULL) { + /* For LWIP_TCPIP_CORE_LOCKING, lock the core before calling the + timeout handler function. */ + LOCK_TCPIP_CORE(); + handler(arg); + UNLOCK_TCPIP_CORE(); + } + LWIP_TCPIP_THREAD_ALIVE(); + + /* We try again to fetch a message from the mbox. */ + goto again; + } else { + /* If time != SYS_ARCH_TIMEOUT, a message was received before the timeout + occured. The time variable is set to the number of + milliseconds we waited for the message. */ + if (time_needed < next_timeout->time) { + next_timeout->time -= time_needed; + } else { + next_timeout->time = 0; + } + } + } +} + +#endif /* NO_SYS */ + +#else /* LWIP_TIMERS */ +/* Satisfy the TCP code which calls this function */ +void +tcp_timer_needed(void) +{ +} +#endif /* LWIP_TIMERS */ diff --git a/features/unsupported/net/lwip/lwip/core/udp.c b/features/unsupported/net/lwip/lwip/core/udp.c new file mode 100644 index 00000000000..4596ba2b79e --- /dev/null +++ b/features/unsupported/net/lwip/lwip/core/udp.c @@ -0,0 +1,966 @@ +/** + * @file + * User Datagram Protocol module + * + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ + + +/* udp.c + * + * The code for the User Datagram Protocol UDP & UDPLite (RFC 3828). + * + */ + +/* @todo Check the use of '(struct udp_pcb).chksum_len_rx'! + */ + +#include "lwip/opt.h" + +#if LWIP_UDP /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/udp.h" +#include "lwip/def.h" +#include "lwip/memp.h" +#include "lwip/inet_chksum.h" +#include "lwip/ip_addr.h" +#include "lwip/netif.h" +#include "lwip/icmp.h" +#include "lwip/stats.h" +#include "lwip/snmp.h" +#include "arch/perf.h" +#include "lwip/dhcp.h" + +#include + +/* The list of UDP PCBs */ +/* exported in udp.h (was static) */ +struct udp_pcb *udp_pcbs; + +/** + * Process an incoming UDP datagram. + * + * Given an incoming UDP datagram (as a chain of pbufs) this function + * finds a corresponding UDP PCB and hands over the pbuf to the pcbs + * recv function. If no pcb is found or the datagram is incorrect, the + * pbuf is freed. + * + * @param p pbuf to be demultiplexed to a UDP PCB. + * @param inp network interface on which the datagram was received. + * + */ +void +udp_input(struct pbuf *p, struct netif *inp) +{ + struct udp_hdr *udphdr; + struct udp_pcb *pcb, *prev; + struct udp_pcb *uncon_pcb; + struct ip_hdr *iphdr; + u16_t src, dest; + u8_t local_match; + u8_t broadcast; + + PERF_START; + + UDP_STATS_INC(udp.recv); + + iphdr = (struct ip_hdr *)p->payload; + + /* Check minimum length (IP header + UDP header) + * and move payload pointer to UDP header */ + if (p->tot_len < (IPH_HL(iphdr) * 4 + UDP_HLEN) || pbuf_header(p, -(s16_t)(IPH_HL(iphdr) * 4))) { + /* drop short packets */ + LWIP_DEBUGF(UDP_DEBUG, + ("udp_input: short UDP datagram (%"U16_F" bytes) discarded\n", p->tot_len)); + UDP_STATS_INC(udp.lenerr); + UDP_STATS_INC(udp.drop); + snmp_inc_udpinerrors(); + pbuf_free(p); + goto end; + } + + udphdr = (struct udp_hdr *)p->payload; + + /* is broadcast packet ? */ + broadcast = ip_addr_isbroadcast(¤t_iphdr_dest, inp); + + LWIP_DEBUGF(UDP_DEBUG, ("udp_input: received datagram of length %"U16_F"\n", p->tot_len)); + + /* convert src and dest ports to host byte order */ + src = ntohs(udphdr->src); + dest = ntohs(udphdr->dest); + + udp_debug_print(udphdr); + + /* print the UDP source and destination */ + LWIP_DEBUGF(UDP_DEBUG, + ("udp (%"U16_F".%"U16_F".%"U16_F".%"U16_F", %"U16_F") <-- " + "(%"U16_F".%"U16_F".%"U16_F".%"U16_F", %"U16_F")\n", + ip4_addr1_16(&iphdr->dest), ip4_addr2_16(&iphdr->dest), + ip4_addr3_16(&iphdr->dest), ip4_addr4_16(&iphdr->dest), ntohs(udphdr->dest), + ip4_addr1_16(&iphdr->src), ip4_addr2_16(&iphdr->src), + ip4_addr3_16(&iphdr->src), ip4_addr4_16(&iphdr->src), ntohs(udphdr->src))); + +#if LWIP_DHCP + pcb = NULL; + /* when LWIP_DHCP is active, packets to DHCP_CLIENT_PORT may only be processed by + the dhcp module, no other UDP pcb may use the local UDP port DHCP_CLIENT_PORT */ + if (dest == DHCP_CLIENT_PORT) { + /* all packets for DHCP_CLIENT_PORT not coming from DHCP_SERVER_PORT are dropped! */ + if (src == DHCP_SERVER_PORT) { + if ((inp->dhcp != NULL) && (inp->dhcp->pcb != NULL)) { + /* accept the packe if + (- broadcast or directed to us) -> DHCP is link-layer-addressed, local ip is always ANY! + - inp->dhcp->pcb->remote == ANY or iphdr->src */ + if ((ip_addr_isany(&inp->dhcp->pcb->remote_ip) || + ip_addr_cmp(&(inp->dhcp->pcb->remote_ip), ¤t_iphdr_src))) { + pcb = inp->dhcp->pcb; + } + } + } + } else +#endif /* LWIP_DHCP */ + { + prev = NULL; + local_match = 0; + uncon_pcb = NULL; + /* Iterate through the UDP pcb list for a matching pcb. + * 'Perfect match' pcbs (connected to the remote port & ip address) are + * preferred. If no perfect match is found, the first unconnected pcb that + * matches the local port and ip address gets the datagram. */ + for (pcb = udp_pcbs; pcb != NULL; pcb = pcb->next) { + local_match = 0; + /* print the PCB local and remote address */ + LWIP_DEBUGF(UDP_DEBUG, + ("pcb (%"U16_F".%"U16_F".%"U16_F".%"U16_F", %"U16_F") --- " + "(%"U16_F".%"U16_F".%"U16_F".%"U16_F", %"U16_F")\n", + ip4_addr1_16(&pcb->local_ip), ip4_addr2_16(&pcb->local_ip), + ip4_addr3_16(&pcb->local_ip), ip4_addr4_16(&pcb->local_ip), pcb->local_port, + ip4_addr1_16(&pcb->remote_ip), ip4_addr2_16(&pcb->remote_ip), + ip4_addr3_16(&pcb->remote_ip), ip4_addr4_16(&pcb->remote_ip), pcb->remote_port)); + + /* compare PCB local addr+port to UDP destination addr+port */ + if ((pcb->local_port == dest) && + ((!broadcast && ip_addr_isany(&pcb->local_ip)) || + ip_addr_cmp(&(pcb->local_ip), ¤t_iphdr_dest) || +#if LWIP_IGMP + ip_addr_ismulticast(¤t_iphdr_dest) || +#endif /* LWIP_IGMP */ +#if IP_SOF_BROADCAST_RECV + (broadcast && (pcb->so_options & SOF_BROADCAST)))) { +#else /* IP_SOF_BROADCAST_RECV */ + (broadcast))) { +#endif /* IP_SOF_BROADCAST_RECV */ + local_match = 1; + if ((uncon_pcb == NULL) && + ((pcb->flags & UDP_FLAGS_CONNECTED) == 0)) { + /* the first unconnected matching PCB */ + uncon_pcb = pcb; + } + } + /* compare PCB remote addr+port to UDP source addr+port */ + if ((local_match != 0) && + (pcb->remote_port == src) && + (ip_addr_isany(&pcb->remote_ip) || + ip_addr_cmp(&(pcb->remote_ip), ¤t_iphdr_src))) { + /* the first fully matching PCB */ + if (prev != NULL) { + /* move the pcb to the front of udp_pcbs so that is + found faster next time */ + prev->next = pcb->next; + pcb->next = udp_pcbs; + udp_pcbs = pcb; + } else { + UDP_STATS_INC(udp.cachehit); + } + break; + } + prev = pcb; + } + /* no fully matching pcb found? then look for an unconnected pcb */ + if (pcb == NULL) { + pcb = uncon_pcb; + } + } + + /* Check checksum if this is a match or if it was directed at us. */ + if (pcb != NULL || ip_addr_cmp(&inp->ip_addr, ¤t_iphdr_dest)) { + LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE, ("udp_input: calculating checksum\n")); +#if LWIP_UDPLITE + if (IPH_PROTO(iphdr) == IP_PROTO_UDPLITE) { + /* Do the UDP Lite checksum */ +#if CHECKSUM_CHECK_UDP + u16_t chklen = ntohs(udphdr->len); + if (chklen < sizeof(struct udp_hdr)) { + if (chklen == 0) { + /* For UDP-Lite, checksum length of 0 means checksum + over the complete packet (See RFC 3828 chap. 3.1) */ + chklen = p->tot_len; + } else { + /* At least the UDP-Lite header must be covered by the + checksum! (Again, see RFC 3828 chap. 3.1) */ + UDP_STATS_INC(udp.chkerr); + UDP_STATS_INC(udp.drop); + snmp_inc_udpinerrors(); + pbuf_free(p); + goto end; + } + } + if (inet_chksum_pseudo_partial(p, ¤t_iphdr_src, ¤t_iphdr_dest, + IP_PROTO_UDPLITE, p->tot_len, chklen) != 0) { + LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_LEVEL_SERIOUS, + ("udp_input: UDP Lite datagram discarded due to failing checksum\n")); + UDP_STATS_INC(udp.chkerr); + UDP_STATS_INC(udp.drop); + snmp_inc_udpinerrors(); + pbuf_free(p); + goto end; + } +#endif /* CHECKSUM_CHECK_UDP */ + } else +#endif /* LWIP_UDPLITE */ + { +#if CHECKSUM_CHECK_UDP + if (udphdr->chksum != 0) { + if (inet_chksum_pseudo(p, ip_current_src_addr(), ip_current_dest_addr(), + IP_PROTO_UDP, p->tot_len) != 0) { + LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_LEVEL_SERIOUS, + ("udp_input: UDP datagram discarded due to failing checksum\n")); + UDP_STATS_INC(udp.chkerr); + UDP_STATS_INC(udp.drop); + snmp_inc_udpinerrors(); + pbuf_free(p); + goto end; + } + } +#endif /* CHECKSUM_CHECK_UDP */ + } + if(pbuf_header(p, -UDP_HLEN)) { + /* Can we cope with this failing? Just assert for now */ + LWIP_ASSERT("pbuf_header failed\n", 0); + UDP_STATS_INC(udp.drop); + snmp_inc_udpinerrors(); + pbuf_free(p); + goto end; + } + if (pcb != NULL) { + snmp_inc_udpindatagrams(); +#if SO_REUSE && SO_REUSE_RXTOALL + if ((broadcast || ip_addr_ismulticast(¤t_iphdr_dest)) && + ((pcb->so_options & SOF_REUSEADDR) != 0)) { + /* pass broadcast- or multicast packets to all multicast pcbs + if SOF_REUSEADDR is set on the first match */ + struct udp_pcb *mpcb; + u8_t p_header_changed = 0; + for (mpcb = udp_pcbs; mpcb != NULL; mpcb = mpcb->next) { + if (mpcb != pcb) { + /* compare PCB local addr+port to UDP destination addr+port */ + if ((mpcb->local_port == dest) && + ((!broadcast && ip_addr_isany(&mpcb->local_ip)) || + ip_addr_cmp(&(mpcb->local_ip), ¤t_iphdr_dest) || +#if LWIP_IGMP + ip_addr_ismulticast(¤t_iphdr_dest) || +#endif /* LWIP_IGMP */ +#if IP_SOF_BROADCAST_RECV + (broadcast && (mpcb->so_options & SOF_BROADCAST)))) { +#else /* IP_SOF_BROADCAST_RECV */ + (broadcast))) { +#endif /* IP_SOF_BROADCAST_RECV */ + /* pass a copy of the packet to all local matches */ + if (mpcb->recv != NULL) { + struct pbuf *q; + /* for that, move payload to IP header again */ + if (p_header_changed == 0) { + pbuf_header(p, (s16_t)((IPH_HL(iphdr) * 4) + UDP_HLEN)); + p_header_changed = 1; + } + q = pbuf_alloc(PBUF_RAW, p->tot_len, PBUF_RAM); + if (q != NULL) { + err_t err = pbuf_copy(q, p); + if (err == ERR_OK) { + /* move payload to UDP data */ + pbuf_header(q, -(s16_t)((IPH_HL(iphdr) * 4) + UDP_HLEN)); + mpcb->recv(mpcb->recv_arg, mpcb, q, ip_current_src_addr(), src); + } + } + } + } + } + } + if (p_header_changed) { + /* and move payload to UDP data again */ + pbuf_header(p, -(s16_t)((IPH_HL(iphdr) * 4) + UDP_HLEN)); + } + } +#endif /* SO_REUSE && SO_REUSE_RXTOALL */ + /* callback */ + if (pcb->recv != NULL) { + /* now the recv function is responsible for freeing p */ + pcb->recv(pcb->recv_arg, pcb, p, ip_current_src_addr(), src); + } else { + /* no recv function registered? then we have to free the pbuf! */ + pbuf_free(p); + goto end; + } + } else { + LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE, ("udp_input: not for us.\n")); + +#if LWIP_ICMP + /* No match was found, send ICMP destination port unreachable unless + destination address was broadcast/multicast. */ + if (!broadcast && + !ip_addr_ismulticast(¤t_iphdr_dest)) { + /* move payload pointer back to ip header */ + pbuf_header(p, (IPH_HL(iphdr) * 4) + UDP_HLEN); + LWIP_ASSERT("p->payload == iphdr", (p->payload == iphdr)); + icmp_dest_unreach(p, ICMP_DUR_PORT); + } +#endif /* LWIP_ICMP */ + UDP_STATS_INC(udp.proterr); + UDP_STATS_INC(udp.drop); + snmp_inc_udpnoports(); + pbuf_free(p); + } + } else { + pbuf_free(p); + } +end: + PERF_STOP("udp_input"); +} + +/** + * Send data using UDP. + * + * @param pcb UDP PCB used to send the data. + * @param p chain of pbuf's to be sent. + * + * The datagram will be sent to the current remote_ip & remote_port + * stored in pcb. If the pcb is not bound to a port, it will + * automatically be bound to a random port. + * + * @return lwIP error code. + * - ERR_OK. Successful. No error occured. + * - ERR_MEM. Out of memory. + * - ERR_RTE. Could not find route to destination address. + * - More errors could be returned by lower protocol layers. + * + * @see udp_disconnect() udp_sendto() + */ +err_t +udp_send(struct udp_pcb *pcb, struct pbuf *p) +{ + /* send to the packet using remote ip and port stored in the pcb */ + return udp_sendto(pcb, p, &pcb->remote_ip, pcb->remote_port); +} + +#if LWIP_CHECKSUM_ON_COPY +/** Same as udp_send() but with checksum + */ +err_t +udp_send_chksum(struct udp_pcb *pcb, struct pbuf *p, + u8_t have_chksum, u16_t chksum) +{ + /* send to the packet using remote ip and port stored in the pcb */ + return udp_sendto_chksum(pcb, p, &pcb->remote_ip, pcb->remote_port, + have_chksum, chksum); +} +#endif /* LWIP_CHECKSUM_ON_COPY */ + +/** + * Send data to a specified address using UDP. + * + * @param pcb UDP PCB used to send the data. + * @param p chain of pbuf's to be sent. + * @param dst_ip Destination IP address. + * @param dst_port Destination UDP port. + * + * dst_ip & dst_port are expected to be in the same byte order as in the pcb. + * + * If the PCB already has a remote address association, it will + * be restored after the data is sent. + * + * @return lwIP error code (@see udp_send for possible error codes) + * + * @see udp_disconnect() udp_send() + */ +err_t +udp_sendto(struct udp_pcb *pcb, struct pbuf *p, + ip_addr_t *dst_ip, u16_t dst_port) +{ +#if LWIP_CHECKSUM_ON_COPY + return udp_sendto_chksum(pcb, p, dst_ip, dst_port, 0, 0); +} + +/** Same as udp_sendto(), but with checksum */ +err_t +udp_sendto_chksum(struct udp_pcb *pcb, struct pbuf *p, ip_addr_t *dst_ip, + u16_t dst_port, u8_t have_chksum, u16_t chksum) +{ +#endif /* LWIP_CHECKSUM_ON_COPY */ + struct netif *netif; + + LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE, ("udp_send\n")); + + /* find the outgoing network interface for this packet */ +#if LWIP_IGMP + netif = ip_route((ip_addr_ismulticast(dst_ip))?(&(pcb->multicast_ip)):(dst_ip)); +#else + netif = ip_route(dst_ip); +#endif /* LWIP_IGMP */ + + /* no outgoing network interface could be found? */ + if (netif == NULL) { + LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_LEVEL_SERIOUS, ("udp_send: No route to %"U16_F".%"U16_F".%"U16_F".%"U16_F"\n", + ip4_addr1_16(dst_ip), ip4_addr2_16(dst_ip), ip4_addr3_16(dst_ip), ip4_addr4_16(dst_ip))); + UDP_STATS_INC(udp.rterr); + return ERR_RTE; + } +#if LWIP_CHECKSUM_ON_COPY + return udp_sendto_if_chksum(pcb, p, dst_ip, dst_port, netif, have_chksum, chksum); +#else /* LWIP_CHECKSUM_ON_COPY */ + return udp_sendto_if(pcb, p, dst_ip, dst_port, netif); +#endif /* LWIP_CHECKSUM_ON_COPY */ +} + +/** + * Send data to a specified address using UDP. + * The netif used for sending can be specified. + * + * This function exists mainly for DHCP, to be able to send UDP packets + * on a netif that is still down. + * + * @param pcb UDP PCB used to send the data. + * @param p chain of pbuf's to be sent. + * @param dst_ip Destination IP address. + * @param dst_port Destination UDP port. + * @param netif the netif used for sending. + * + * dst_ip & dst_port are expected to be in the same byte order as in the pcb. + * + * @return lwIP error code (@see udp_send for possible error codes) + * + * @see udp_disconnect() udp_send() + */ +err_t +udp_sendto_if(struct udp_pcb *pcb, struct pbuf *p, + ip_addr_t *dst_ip, u16_t dst_port, struct netif *netif) +{ +#if LWIP_CHECKSUM_ON_COPY + return udp_sendto_if_chksum(pcb, p, dst_ip, dst_port, netif, 0, 0); +} + +/** Same as udp_sendto_if(), but with checksum */ +err_t +udp_sendto_if_chksum(struct udp_pcb *pcb, struct pbuf *p, ip_addr_t *dst_ip, + u16_t dst_port, struct netif *netif, u8_t have_chksum, + u16_t chksum) +{ +#endif /* LWIP_CHECKSUM_ON_COPY */ + struct udp_hdr *udphdr; + ip_addr_t *src_ip; + err_t err; + struct pbuf *q; /* q will be sent down the stack */ + +#if IP_SOF_BROADCAST + /* broadcast filter? */ + if ( ((pcb->so_options & SOF_BROADCAST) == 0) && ip_addr_isbroadcast(dst_ip, netif) ) { + LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_LEVEL_SERIOUS, + ("udp_sendto_if: SOF_BROADCAST not enabled on pcb %p\n", (void *)pcb)); + return ERR_VAL; + } +#endif /* IP_SOF_BROADCAST */ + + /* if the PCB is not yet bound to a port, bind it here */ + if (pcb->local_port == 0) { + LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE, ("udp_send: not yet bound to a port, binding now\n")); + err = udp_bind(pcb, &pcb->local_ip, pcb->local_port); + if (err != ERR_OK) { + LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS, ("udp_send: forced port bind failed\n")); + return err; + } + } + + /* not enough space to add an UDP header to first pbuf in given p chain? */ + if (pbuf_header(p, UDP_HLEN)) { + /* allocate header in a separate new pbuf */ + q = pbuf_alloc(PBUF_IP, UDP_HLEN, PBUF_RAM); + /* new header pbuf could not be allocated? */ + if (q == NULL) { + LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS, ("udp_send: could not allocate header\n")); + return ERR_MEM; + } + if (p->tot_len != 0) { + /* chain header q in front of given pbuf p (only if p contains data) */ + pbuf_chain(q, p); + } + /* first pbuf q points to header pbuf */ + LWIP_DEBUGF(UDP_DEBUG, + ("udp_send: added header pbuf %p before given pbuf %p\n", (void *)q, (void *)p)); + } else { + /* adding space for header within p succeeded */ + /* first pbuf q equals given pbuf */ + q = p; + LWIP_DEBUGF(UDP_DEBUG, ("udp_send: added header in given pbuf %p\n", (void *)p)); + } + LWIP_ASSERT("check that first pbuf can hold struct udp_hdr", + (q->len >= sizeof(struct udp_hdr))); + /* q now represents the packet to be sent */ + udphdr = (struct udp_hdr *)q->payload; + udphdr->src = htons(pcb->local_port); + udphdr->dest = htons(dst_port); + /* in UDP, 0 checksum means 'no checksum' */ + udphdr->chksum = 0x0000; + + /* Multicast Loop? */ +#if LWIP_IGMP + if (ip_addr_ismulticast(dst_ip) && ((pcb->flags & UDP_FLAGS_MULTICAST_LOOP) != 0)) { + q->flags |= PBUF_FLAG_MCASTLOOP; + } +#endif /* LWIP_IGMP */ + + + /* PCB local address is IP_ANY_ADDR? */ + if (ip_addr_isany(&pcb->local_ip)) { + /* use outgoing network interface IP address as source address */ + src_ip = &(netif->ip_addr); + } else { + /* check if UDP PCB local IP address is correct + * this could be an old address if netif->ip_addr has changed */ + if (!ip_addr_cmp(&(pcb->local_ip), &(netif->ip_addr))) { + /* local_ip doesn't match, drop the packet */ + if (q != p) { + /* free the header pbuf */ + pbuf_free(q); + q = NULL; + /* p is still referenced by the caller, and will live on */ + } + return ERR_VAL; + } + /* use UDP PCB local IP address as source address */ + src_ip = &(pcb->local_ip); + } + + LWIP_DEBUGF(UDP_DEBUG, ("udp_send: sending datagram of length %"U16_F"\n", q->tot_len)); + +#if LWIP_UDPLITE + /* UDP Lite protocol? */ + if (pcb->flags & UDP_FLAGS_UDPLITE) { + u16_t chklen, chklen_hdr; + LWIP_DEBUGF(UDP_DEBUG, ("udp_send: UDP LITE packet length %"U16_F"\n", q->tot_len)); + /* set UDP message length in UDP header */ + chklen_hdr = chklen = pcb->chksum_len_tx; + if ((chklen < sizeof(struct udp_hdr)) || (chklen > q->tot_len)) { + if (chklen != 0) { + LWIP_DEBUGF(UDP_DEBUG, ("udp_send: UDP LITE pcb->chksum_len is illegal: %"U16_F"\n", chklen)); + } + /* For UDP-Lite, checksum length of 0 means checksum + over the complete packet. (See RFC 3828 chap. 3.1) + At least the UDP-Lite header must be covered by the + checksum, therefore, if chksum_len has an illegal + value, we generate the checksum over the complete + packet to be safe. */ + chklen_hdr = 0; + chklen = q->tot_len; + } + udphdr->len = htons(chklen_hdr); + /* calculate checksum */ +#if CHECKSUM_GEN_UDP + udphdr->chksum = inet_chksum_pseudo_partial(q, src_ip, dst_ip, + IP_PROTO_UDPLITE, q->tot_len, +#if !LWIP_CHECKSUM_ON_COPY + chklen); +#else /* !LWIP_CHECKSUM_ON_COPY */ + (have_chksum ? UDP_HLEN : chklen)); + if (have_chksum) { + u32_t acc; + acc = udphdr->chksum + (u16_t)~(chksum); + udphdr->chksum = FOLD_U32T(acc); + } +#endif /* !LWIP_CHECKSUM_ON_COPY */ + + /* chksum zero must become 0xffff, as zero means 'no checksum' */ + if (udphdr->chksum == 0x0000) { + udphdr->chksum = 0xffff; + } +#endif /* CHECKSUM_GEN_UDP */ + /* output to IP */ + LWIP_DEBUGF(UDP_DEBUG, ("udp_send: ip_output_if (,,,,IP_PROTO_UDPLITE,)\n")); +#if LWIP_NETIF_HWADDRHINT + netif->addr_hint = &(pcb->addr_hint); +#endif /* LWIP_NETIF_HWADDRHINT*/ + err = ip_output_if(q, src_ip, dst_ip, pcb->ttl, pcb->tos, IP_PROTO_UDPLITE, netif); +#if LWIP_NETIF_HWADDRHINT + netif->addr_hint = NULL; +#endif /* LWIP_NETIF_HWADDRHINT*/ + } else +#endif /* LWIP_UDPLITE */ + { /* UDP */ + LWIP_DEBUGF(UDP_DEBUG, ("udp_send: UDP packet length %"U16_F"\n", q->tot_len)); + udphdr->len = htons(q->tot_len); + /* calculate checksum */ +#if CHECKSUM_GEN_UDP + if ((pcb->flags & UDP_FLAGS_NOCHKSUM) == 0) { + u16_t udpchksum; +#if LWIP_CHECKSUM_ON_COPY + if (have_chksum) { + u32_t acc; + udpchksum = inet_chksum_pseudo_partial(q, src_ip, dst_ip, IP_PROTO_UDP, + q->tot_len, UDP_HLEN); + acc = udpchksum + (u16_t)~(chksum); + udpchksum = FOLD_U32T(acc); + } else +#endif /* LWIP_CHECKSUM_ON_COPY */ + { + udpchksum = inet_chksum_pseudo(q, src_ip, dst_ip, IP_PROTO_UDP, q->tot_len); + } + + /* chksum zero must become 0xffff, as zero means 'no checksum' */ + if (udpchksum == 0x0000) { + udpchksum = 0xffff; + } + udphdr->chksum = udpchksum; + } +#endif /* CHECKSUM_GEN_UDP */ + LWIP_DEBUGF(UDP_DEBUG, ("udp_send: UDP checksum 0x%04"X16_F"\n", udphdr->chksum)); + LWIP_DEBUGF(UDP_DEBUG, ("udp_send: ip_output_if (,,,,IP_PROTO_UDP,)\n")); + /* output to IP */ +#if LWIP_NETIF_HWADDRHINT + netif->addr_hint = &(pcb->addr_hint); +#endif /* LWIP_NETIF_HWADDRHINT*/ + err = ip_output_if(q, src_ip, dst_ip, pcb->ttl, pcb->tos, IP_PROTO_UDP, netif); +#if LWIP_NETIF_HWADDRHINT + netif->addr_hint = NULL; +#endif /* LWIP_NETIF_HWADDRHINT*/ + } + /* TODO: must this be increased even if error occured? */ + snmp_inc_udpoutdatagrams(); + + /* did we chain a separate header pbuf earlier? */ + if (q != p) { + /* free the header pbuf */ + pbuf_free(q); + q = NULL; + /* p is still referenced by the caller, and will live on */ + } + + UDP_STATS_INC(udp.xmit); + return err; +} + +/** + * Bind an UDP PCB. + * + * @param pcb UDP PCB to be bound with a local address ipaddr and port. + * @param ipaddr local IP address to bind with. Use IP_ADDR_ANY to + * bind to all local interfaces. + * @param port local UDP port to bind with. Use 0 to automatically bind + * to a random port between UDP_LOCAL_PORT_RANGE_START and + * UDP_LOCAL_PORT_RANGE_END. + * + * ipaddr & port are expected to be in the same byte order as in the pcb. + * + * @return lwIP error code. + * - ERR_OK. Successful. No error occured. + * - ERR_USE. The specified ipaddr and port are already bound to by + * another UDP PCB. + * + * @see udp_disconnect() + */ +err_t +udp_bind(struct udp_pcb *pcb, ip_addr_t *ipaddr, u16_t port) +{ + struct udp_pcb *ipcb; + u8_t rebind; + + LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE, ("udp_bind(ipaddr = ")); + ip_addr_debug_print(UDP_DEBUG, ipaddr); + LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE, (", port = %"U16_F")\n", port)); + + rebind = 0; + /* Check for double bind and rebind of the same pcb */ + for (ipcb = udp_pcbs; ipcb != NULL; ipcb = ipcb->next) { + /* is this UDP PCB already on active list? */ + if (pcb == ipcb) { + /* pcb may occur at most once in active list */ + LWIP_ASSERT("rebind == 0", rebind == 0); + /* pcb already in list, just rebind */ + rebind = 1; + } + + /* By default, we don't allow to bind to a port that any other udp + PCB is alread bound to, unless *all* PCBs with that port have tha + REUSEADDR flag set. */ +#if SO_REUSE + else if (((pcb->so_options & SOF_REUSEADDR) == 0) && + ((ipcb->so_options & SOF_REUSEADDR) == 0)) { +#else /* SO_REUSE */ + /* port matches that of PCB in list and REUSEADDR not set -> reject */ + else { +#endif /* SO_REUSE */ + if ((ipcb->local_port == port) && + /* IP address matches, or one is IP_ADDR_ANY? */ + (ip_addr_isany(&(ipcb->local_ip)) || + ip_addr_isany(ipaddr) || + ip_addr_cmp(&(ipcb->local_ip), ipaddr))) { + /* other PCB already binds to this local IP and port */ + LWIP_DEBUGF(UDP_DEBUG, + ("udp_bind: local port %"U16_F" already bound by another pcb\n", port)); + return ERR_USE; + } + } + } + + ip_addr_set(&pcb->local_ip, ipaddr); + + /* no port specified? */ + if (port == 0) { +#ifndef UDP_LOCAL_PORT_RANGE_START +/* From http://www.iana.org/assignments/port-numbers: + "The Dynamic and/or Private Ports are those from 49152 through 65535" */ +#define UDP_LOCAL_PORT_RANGE_START 0xc000 +#define UDP_LOCAL_PORT_RANGE_END 0xffff +#endif + port = UDP_LOCAL_PORT_RANGE_START; + ipcb = udp_pcbs; + while ((ipcb != NULL) && (port != UDP_LOCAL_PORT_RANGE_END)) { + if (ipcb->local_port == port) { + /* port is already used by another udp_pcb */ + port++; + /* restart scanning all udp pcbs */ + ipcb = udp_pcbs; + } else { + /* go on with next udp pcb */ + ipcb = ipcb->next; + } + } + if (ipcb != NULL) { + /* no more ports available in local range */ + LWIP_DEBUGF(UDP_DEBUG, ("udp_bind: out of free UDP ports\n")); + return ERR_USE; + } + } + pcb->local_port = port; + snmp_insert_udpidx_tree(pcb); + /* pcb not active yet? */ + if (rebind == 0) { + /* place the PCB on the active list if not already there */ + pcb->next = udp_pcbs; + udp_pcbs = pcb; + } + LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, + ("udp_bind: bound to %"U16_F".%"U16_F".%"U16_F".%"U16_F", port %"U16_F"\n", + ip4_addr1_16(&pcb->local_ip), ip4_addr2_16(&pcb->local_ip), + ip4_addr3_16(&pcb->local_ip), ip4_addr4_16(&pcb->local_ip), + pcb->local_port)); + return ERR_OK; +} +/** + * Connect an UDP PCB. + * + * This will associate the UDP PCB with the remote address. + * + * @param pcb UDP PCB to be connected with remote address ipaddr and port. + * @param ipaddr remote IP address to connect with. + * @param port remote UDP port to connect with. + * + * @return lwIP error code + * + * ipaddr & port are expected to be in the same byte order as in the pcb. + * + * The udp pcb is bound to a random local port if not already bound. + * + * @see udp_disconnect() + */ +err_t +udp_connect(struct udp_pcb *pcb, ip_addr_t *ipaddr, u16_t port) +{ + struct udp_pcb *ipcb; + + if (pcb->local_port == 0) { + err_t err = udp_bind(pcb, &pcb->local_ip, pcb->local_port); + if (err != ERR_OK) { + return err; + } + } + + ip_addr_set(&pcb->remote_ip, ipaddr); + pcb->remote_port = port; + pcb->flags |= UDP_FLAGS_CONNECTED; +/** TODO: this functionality belongs in upper layers */ +#ifdef LWIP_UDP_TODO + /* Nail down local IP for netconn_addr()/getsockname() */ + if (ip_addr_isany(&pcb->local_ip) && !ip_addr_isany(&pcb->remote_ip)) { + struct netif *netif; + + if ((netif = ip_route(&(pcb->remote_ip))) == NULL) { + LWIP_DEBUGF(UDP_DEBUG, ("udp_connect: No route to 0x%lx\n", pcb->remote_ip.addr)); + UDP_STATS_INC(udp.rterr); + return ERR_RTE; + } + /** TODO: this will bind the udp pcb locally, to the interface which + is used to route output packets to the remote address. However, we + might want to accept incoming packets on any interface! */ + pcb->local_ip = netif->ip_addr; + } else if (ip_addr_isany(&pcb->remote_ip)) { + pcb->local_ip.addr = 0; + } +#endif + LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, + ("udp_connect: connected to %"U16_F".%"U16_F".%"U16_F".%"U16_F",port %"U16_F"\n", + ip4_addr1_16(&pcb->local_ip), ip4_addr2_16(&pcb->local_ip), + ip4_addr3_16(&pcb->local_ip), ip4_addr4_16(&pcb->local_ip), + pcb->local_port)); + + /* Insert UDP PCB into the list of active UDP PCBs. */ + for (ipcb = udp_pcbs; ipcb != NULL; ipcb = ipcb->next) { + if (pcb == ipcb) { + /* already on the list, just return */ + return ERR_OK; + } + } + /* PCB not yet on the list, add PCB now */ + pcb->next = udp_pcbs; + udp_pcbs = pcb; + return ERR_OK; +} + +/** + * Disconnect a UDP PCB + * + * @param pcb the udp pcb to disconnect. + */ +void +udp_disconnect(struct udp_pcb *pcb) +{ + /* reset remote address association */ + ip_addr_set_any(&pcb->remote_ip); + pcb->remote_port = 0; + /* mark PCB as unconnected */ + pcb->flags &= ~UDP_FLAGS_CONNECTED; +} + +/** + * Set a receive callback for a UDP PCB + * + * This callback will be called when receiving a datagram for the pcb. + * + * @param pcb the pcb for wich to set the recv callback + * @param recv function pointer of the callback function + * @param recv_arg additional argument to pass to the callback function + */ +void +udp_recv(struct udp_pcb *pcb, udp_recv_fn recv, void *recv_arg) +{ + /* remember recv() callback and user data */ + pcb->recv = recv; + pcb->recv_arg = recv_arg; +} + +/** + * Remove an UDP PCB. + * + * @param pcb UDP PCB to be removed. The PCB is removed from the list of + * UDP PCB's and the data structure is freed from memory. + * + * @see udp_new() + */ +void +udp_remove(struct udp_pcb *pcb) +{ + struct udp_pcb *pcb2; + + snmp_delete_udpidx_tree(pcb); + /* pcb to be removed is first in list? */ + if (udp_pcbs == pcb) { + /* make list start at 2nd pcb */ + udp_pcbs = udp_pcbs->next; + /* pcb not 1st in list */ + } else { + for (pcb2 = udp_pcbs; pcb2 != NULL; pcb2 = pcb2->next) { + /* find pcb in udp_pcbs list */ + if (pcb2->next != NULL && pcb2->next == pcb) { + /* remove pcb from list */ + pcb2->next = pcb->next; + } + } + } + memp_free(MEMP_UDP_PCB, pcb); +} + +/** + * Create a UDP PCB. + * + * @return The UDP PCB which was created. NULL if the PCB data structure + * could not be allocated. + * + * @see udp_remove() + */ +struct udp_pcb * +udp_new(void) +{ + struct udp_pcb *pcb; + pcb = (struct udp_pcb *)memp_malloc(MEMP_UDP_PCB); + /* could allocate UDP PCB? */ + if (pcb != NULL) { + /* UDP Lite: by initializing to all zeroes, chksum_len is set to 0 + * which means checksum is generated over the whole datagram per default + * (recommended as default by RFC 3828). */ + /* initialize PCB to all zeroes */ + memset(pcb, 0, sizeof(struct udp_pcb)); + pcb->ttl = UDP_TTL; + } + return pcb; +} + +#if UDP_DEBUG +/** + * Print UDP header information for debug purposes. + * + * @param udphdr pointer to the udp header in memory. + */ +void +udp_debug_print(struct udp_hdr *udphdr) +{ + LWIP_DEBUGF(UDP_DEBUG, ("UDP header:\n")); + LWIP_DEBUGF(UDP_DEBUG, ("+-------------------------------+\n")); + LWIP_DEBUGF(UDP_DEBUG, ("| %5"U16_F" | %5"U16_F" | (src port, dest port)\n", + ntohs(udphdr->src), ntohs(udphdr->dest))); + LWIP_DEBUGF(UDP_DEBUG, ("+-------------------------------+\n")); + LWIP_DEBUGF(UDP_DEBUG, ("| %5"U16_F" | 0x%04"X16_F" | (len, chksum)\n", + ntohs(udphdr->len), ntohs(udphdr->chksum))); + LWIP_DEBUGF(UDP_DEBUG, ("+-------------------------------+\n")); +} +#endif /* UDP_DEBUG */ + +#endif /* LWIP_UDP */ diff --git a/features/unsupported/net/lwip/lwip/include/ipv4/lwip/autoip.h b/features/unsupported/net/lwip/lwip/include/ipv4/lwip/autoip.h new file mode 100644 index 00000000000..23c264a1e04 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/include/ipv4/lwip/autoip.h @@ -0,0 +1,119 @@ +/** + * @file + * + * AutoIP Automatic LinkLocal IP Configuration + */ + +/* + * + * Copyright (c) 2007 Dominik Spies + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * Author: Dominik Spies + * + * This is a AutoIP implementation for the lwIP TCP/IP stack. It aims to conform + * with RFC 3927. + * + * + * Please coordinate changes and requests with Dominik Spies + * + */ + +#ifndef __LWIP_AUTOIP_H__ +#define __LWIP_AUTOIP_H__ + +#include "lwip/opt.h" + +#if LWIP_AUTOIP /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/netif.h" +#include "lwip/udp.h" +#include "netif/etharp.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* AutoIP Timing */ +#define AUTOIP_TMR_INTERVAL 100 +#define AUTOIP_TICKS_PER_SECOND (1000 / AUTOIP_TMR_INTERVAL) + +/* RFC 3927 Constants */ +#define PROBE_WAIT 1 /* second (initial random delay) */ +#define PROBE_MIN 1 /* second (minimum delay till repeated probe) */ +#define PROBE_MAX 2 /* seconds (maximum delay till repeated probe) */ +#define PROBE_NUM 3 /* (number of probe packets) */ +#define ANNOUNCE_NUM 2 /* (number of announcement packets) */ +#define ANNOUNCE_INTERVAL 2 /* seconds (time between announcement packets) */ +#define ANNOUNCE_WAIT 2 /* seconds (delay before announcing) */ +#define MAX_CONFLICTS 10 /* (max conflicts before rate limiting) */ +#define RATE_LIMIT_INTERVAL 60 /* seconds (delay between successive attempts) */ +#define DEFEND_INTERVAL 10 /* seconds (min. wait between defensive ARPs) */ + +/* AutoIP client states */ +#define AUTOIP_STATE_OFF 0 +#define AUTOIP_STATE_PROBING 1 +#define AUTOIP_STATE_ANNOUNCING 2 +#define AUTOIP_STATE_BOUND 3 + +struct autoip +{ + ip_addr_t llipaddr; /* the currently selected, probed, announced or used LL IP-Address */ + u8_t state; /* current AutoIP state machine state */ + u8_t sent_num; /* sent number of probes or announces, dependent on state */ + u16_t ttw; /* ticks to wait, tick is AUTOIP_TMR_INTERVAL long */ + u8_t lastconflict; /* ticks until a conflict can be solved by defending */ + u8_t tried_llipaddr; /* total number of probed/used Link Local IP-Addresses */ +}; + + +/** Init srand, has to be called before entering mainloop */ +void autoip_init(void); + +/** Set a struct autoip allocated by the application to work with */ +void autoip_set_struct(struct netif *netif, struct autoip *autoip); + +/** Start AutoIP client */ +err_t autoip_start(struct netif *netif); + +/** Stop AutoIP client */ +err_t autoip_stop(struct netif *netif); + +/** Handles every incoming ARP Packet, called by etharp_arp_input */ +void autoip_arp_reply(struct netif *netif, struct etharp_hdr *hdr); + +/** Has to be called in loop every AUTOIP_TMR_INTERVAL milliseconds */ +void autoip_tmr(void); + +/** Handle a possible change in the network configuration */ +void autoip_network_changed(struct netif *netif); + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_AUTOIP */ + +#endif /* __LWIP_AUTOIP_H__ */ diff --git a/features/unsupported/net/lwip/lwip/include/ipv4/lwip/icmp.h b/features/unsupported/net/lwip/lwip/include/ipv4/lwip/icmp.h new file mode 100644 index 00000000000..d47a7d8a2e2 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/include/ipv4/lwip/icmp.h @@ -0,0 +1,111 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef __LWIP_ICMP_H__ +#define __LWIP_ICMP_H__ + +#include "lwip/opt.h" +#include "lwip/pbuf.h" +#include "lwip/ip_addr.h" +#include "lwip/netif.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define ICMP_ER 0 /* echo reply */ +#define ICMP_DUR 3 /* destination unreachable */ +#define ICMP_SQ 4 /* source quench */ +#define ICMP_RD 5 /* redirect */ +#define ICMP_ECHO 8 /* echo */ +#define ICMP_TE 11 /* time exceeded */ +#define ICMP_PP 12 /* parameter problem */ +#define ICMP_TS 13 /* timestamp */ +#define ICMP_TSR 14 /* timestamp reply */ +#define ICMP_IRQ 15 /* information request */ +#define ICMP_IR 16 /* information reply */ + +enum icmp_dur_type { + ICMP_DUR_NET = 0, /* net unreachable */ + ICMP_DUR_HOST = 1, /* host unreachable */ + ICMP_DUR_PROTO = 2, /* protocol unreachable */ + ICMP_DUR_PORT = 3, /* port unreachable */ + ICMP_DUR_FRAG = 4, /* fragmentation needed and DF set */ + ICMP_DUR_SR = 5 /* source route failed */ +}; + +enum icmp_te_type { + ICMP_TE_TTL = 0, /* time to live exceeded in transit */ + ICMP_TE_FRAG = 1 /* fragment reassembly time exceeded */ +}; + +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +/** This is the standard ICMP header only that the u32_t data + * is splitted to two u16_t like ICMP echo needs it. + * This header is also used for other ICMP types that do not + * use the data part. + */ +PACK_STRUCT_BEGIN +struct icmp_echo_hdr { + PACK_STRUCT_FIELD(u8_t type); + PACK_STRUCT_FIELD(u8_t code); + PACK_STRUCT_FIELD(u16_t chksum); + PACK_STRUCT_FIELD(u16_t id); + PACK_STRUCT_FIELD(u16_t seqno); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +#define ICMPH_TYPE(hdr) ((hdr)->type) +#define ICMPH_CODE(hdr) ((hdr)->code) + +/** Combines type and code to an u16_t */ +#define ICMPH_TYPE_SET(hdr, t) ((hdr)->type = (t)) +#define ICMPH_CODE_SET(hdr, c) ((hdr)->code = (c)) + + +#if LWIP_ICMP /* don't build if not configured for use in lwipopts.h */ + +void icmp_input(struct pbuf *p, struct netif *inp); +void icmp_dest_unreach(struct pbuf *p, enum icmp_dur_type t); +void icmp_time_exceeded(struct pbuf *p, enum icmp_te_type t); + +#endif /* LWIP_ICMP */ + +#ifdef __cplusplus +} +#endif + +#endif /* __LWIP_ICMP_H__ */ diff --git a/features/unsupported/net/lwip/lwip/include/ipv4/lwip/igmp.h b/features/unsupported/net/lwip/lwip/include/ipv4/lwip/igmp.h new file mode 100644 index 00000000000..8aabac24817 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/include/ipv4/lwip/igmp.h @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2002 CITEL Technologies Ltd. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of CITEL Technologies Ltd nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY CITEL TECHNOLOGIES AND CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL CITEL TECHNOLOGIES OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * This file is a contribution to the lwIP TCP/IP stack. + * The Swedish Institute of Computer Science and Adam Dunkels + * are specifically granted permission to redistribute this + * source code. +*/ + +#ifndef __LWIP_IGMP_H__ +#define __LWIP_IGMP_H__ + +#include "lwip/opt.h" +#include "lwip/ip_addr.h" +#include "lwip/netif.h" +#include "lwip/pbuf.h" + +#if LWIP_IGMP /* don't build if not configured for use in lwipopts.h */ + +#ifdef __cplusplus +extern "C" { +#endif + + +/* IGMP timer */ +#define IGMP_TMR_INTERVAL 100 /* Milliseconds */ +#define IGMP_V1_DELAYING_MEMBER_TMR (1000/IGMP_TMR_INTERVAL) +#define IGMP_JOIN_DELAYING_MEMBER_TMR (500 /IGMP_TMR_INTERVAL) + +/* MAC Filter Actions, these are passed to a netif's + * igmp_mac_filter callback function. */ +#define IGMP_DEL_MAC_FILTER 0 +#define IGMP_ADD_MAC_FILTER 1 + + +/** + * igmp group structure - there is + * a list of groups for each interface + * these should really be linked from the interface, but + * if we keep them separate we will not affect the lwip original code + * too much + * + * There will be a group for the all systems group address but this + * will not run the state machine as it is used to kick off reports + * from all the other groups + */ +struct igmp_group { + /** next link */ + struct igmp_group *next; + /** interface on which the group is active */ + struct netif *netif; + /** multicast address */ + ip_addr_t group_address; + /** signifies we were the last person to report */ + u8_t last_reporter_flag; + /** current state of the group */ + u8_t group_state; + /** timer for reporting, negative is OFF */ + u16_t timer; + /** counter of simultaneous uses */ + u8_t use; +}; + +/* Prototypes */ +void igmp_init(void); +err_t igmp_start(struct netif *netif); +err_t igmp_stop(struct netif *netif); +void igmp_report_groups(struct netif *netif); +struct igmp_group *igmp_lookfor_group(struct netif *ifp, ip_addr_t *addr); +void igmp_input(struct pbuf *p, struct netif *inp, ip_addr_t *dest); +err_t igmp_joingroup(ip_addr_t *ifaddr, ip_addr_t *groupaddr); +err_t igmp_leavegroup(ip_addr_t *ifaddr, ip_addr_t *groupaddr); +void igmp_tmr(void); + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_IGMP */ + +#endif /* __LWIP_IGMP_H__ */ diff --git a/features/unsupported/net/lwip/lwip/include/ipv4/lwip/inet.h b/features/unsupported/net/lwip/lwip/include/ipv4/lwip/inet.h new file mode 100644 index 00000000000..7bff49b59e6 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/include/ipv4/lwip/inet.h @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef __LWIP_INET_H__ +#define __LWIP_INET_H__ + +#include "lwip/opt.h" +#include "lwip/def.h" +#include "lwip/ip_addr.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** For compatibility with BSD code */ +struct in_addr { + u32_t s_addr; +}; + +/** 255.255.255.255 */ +#define INADDR_NONE IPADDR_NONE +/** 127.0.0.1 */ +#define INADDR_LOOPBACK IPADDR_LOOPBACK +/** 0.0.0.0 */ +#define INADDR_ANY IPADDR_ANY +/** 255.255.255.255 */ +#define INADDR_BROADCAST IPADDR_BROADCAST + +/* Definitions of the bits in an Internet address integer. + + On subnets, host and network parts are found according to + the subnet mask, not these masks. */ +#define IN_CLASSA(a) IP_CLASSA(a) +#define IN_CLASSA_NET IP_CLASSA_NET +#define IN_CLASSA_NSHIFT IP_CLASSA_NSHIFT +#define IN_CLASSA_HOST IP_CLASSA_HOST +#define IN_CLASSA_MAX IP_CLASSA_MAX + +#define IN_CLASSB(b) IP_CLASSB(b) +#define IN_CLASSB_NET IP_CLASSB_NET +#define IN_CLASSB_NSHIFT IP_CLASSB_NSHIFT +#define IN_CLASSB_HOST IP_CLASSB_HOST +#define IN_CLASSB_MAX IP_CLASSB_MAX + +#define IN_CLASSC(c) IP_CLASSC(c) +#define IN_CLASSC_NET IP_CLASSC_NET +#define IN_CLASSC_NSHIFT IP_CLASSC_NSHIFT +#define IN_CLASSC_HOST IP_CLASSC_HOST +#define IN_CLASSC_MAX IP_CLASSC_MAX + +#define IN_CLASSD(d) IP_CLASSD(d) +#define IN_CLASSD_NET IP_CLASSD_NET /* These ones aren't really */ +#define IN_CLASSD_NSHIFT IP_CLASSD_NSHIFT /* net and host fields, but */ +#define IN_CLASSD_HOST IP_CLASSD_HOST /* routing needn't know. */ +#define IN_CLASSD_MAX IP_CLASSD_MAX + +#define IN_MULTICAST(a) IP_MULTICAST(a) + +#define IN_EXPERIMENTAL(a) IP_EXPERIMENTAL(a) +#define IN_BADCLASS(a) IP_BADCLASS(a) + +#define IN_LOOPBACKNET IP_LOOPBACKNET + +#define inet_addr_from_ipaddr(target_inaddr, source_ipaddr) ((target_inaddr)->s_addr = ip4_addr_get_u32(source_ipaddr)) +#define inet_addr_to_ipaddr(target_ipaddr, source_inaddr) (ip4_addr_set_u32(target_ipaddr, (source_inaddr)->s_addr)) +/* ATTENTION: the next define only works because both s_addr and ip_addr_t are an u32_t effectively! */ +#define inet_addr_to_ipaddr_p(target_ipaddr_p, source_inaddr) ((target_ipaddr_p) = (ip_addr_t*)&((source_inaddr)->s_addr)) + +/* directly map this to the lwip internal functions */ +#define inet_addr(cp) ipaddr_addr(cp) +#define inet_aton(cp, addr) ipaddr_aton(cp, (ip_addr_t*)addr) +#define inet_ntoa(addr) ipaddr_ntoa((ip_addr_t*)&(addr)) +#define inet_ntoa_r(addr, buf, buflen) ipaddr_ntoa_r((ip_addr_t*)&(addr), buf, buflen) + +#ifdef __cplusplus +} +#endif + +#endif /* __LWIP_INET_H__ */ diff --git a/features/unsupported/net/lwip/lwip/include/ipv4/lwip/inet_chksum.h b/features/unsupported/net/lwip/lwip/include/ipv4/lwip/inet_chksum.h new file mode 100644 index 00000000000..79a2d90f2f7 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/include/ipv4/lwip/inet_chksum.h @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef __LWIP_INET_CHKSUM_H__ +#define __LWIP_INET_CHKSUM_H__ + +#include "lwip/opt.h" + +#include "lwip/pbuf.h" +#include "lwip/ip_addr.h" + +/** Swap the bytes in an u16_t: much like htons() for little-endian */ +#ifndef SWAP_BYTES_IN_WORD +#if LWIP_PLATFORM_BYTESWAP && (BYTE_ORDER == LITTLE_ENDIAN) +/* little endian and PLATFORM_BYTESWAP defined */ +#define SWAP_BYTES_IN_WORD(w) LWIP_PLATFORM_HTONS(w) +#else /* LWIP_PLATFORM_BYTESWAP && (BYTE_ORDER == LITTLE_ENDIAN) */ +/* can't use htons on big endian (or PLATFORM_BYTESWAP not defined)... */ +#define SWAP_BYTES_IN_WORD(w) (((w) & 0xff) << 8) | (((w) & 0xff00) >> 8) +#endif /* LWIP_PLATFORM_BYTESWAP && (BYTE_ORDER == LITTLE_ENDIAN)*/ +#endif /* SWAP_BYTES_IN_WORD */ + +/** Split an u32_t in two u16_ts and add them up */ +#ifndef FOLD_U32T +#define FOLD_U32T(u) (((u) >> 16) + ((u) & 0x0000ffffUL)) +#endif + +#if LWIP_CHECKSUM_ON_COPY +/** Function-like macro: same as MEMCPY but returns the checksum of copied data + as u16_t */ +#ifndef LWIP_CHKSUM_COPY +#define LWIP_CHKSUM_COPY(dst, src, len) lwip_chksum_copy(dst, src, len) +#ifndef LWIP_CHKSUM_COPY_ALGORITHM +#define LWIP_CHKSUM_COPY_ALGORITHM 1 +#endif /* LWIP_CHKSUM_COPY_ALGORITHM */ +#endif /* LWIP_CHKSUM_COPY */ +#else /* LWIP_CHECKSUM_ON_COPY */ +#define LWIP_CHKSUM_COPY_ALGORITHM 0 +#endif /* LWIP_CHECKSUM_ON_COPY */ + +#ifdef __cplusplus +extern "C" { +#endif + +u16_t inet_chksum(void *dataptr, u16_t len); +u16_t inet_chksum_pbuf(struct pbuf *p); +u16_t inet_chksum_pseudo(struct pbuf *p, + ip_addr_t *src, ip_addr_t *dest, + u8_t proto, u16_t proto_len); +u16_t inet_chksum_pseudo_partial(struct pbuf *p, + ip_addr_t *src, ip_addr_t *dest, + u8_t proto, u16_t proto_len, u16_t chksum_len); +#if LWIP_CHKSUM_COPY_ALGORITHM +u16_t lwip_chksum_copy(void *dst, const void *src, u16_t len); +#endif /* LWIP_CHKSUM_COPY_ALGORITHM */ + +#ifdef __cplusplus +} +#endif + +#endif /* __LWIP_INET_H__ */ + diff --git a/features/unsupported/net/lwip/lwip/include/ipv4/lwip/ip.h b/features/unsupported/net/lwip/lwip/include/ipv4/lwip/ip.h new file mode 100644 index 00000000000..74f501d1ab4 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/include/ipv4/lwip/ip.h @@ -0,0 +1,213 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef __LWIP_IP_H__ +#define __LWIP_IP_H__ + +#include "lwip/opt.h" + +#include "lwip/def.h" +#include "lwip/pbuf.h" +#include "lwip/ip_addr.h" +#include "lwip/err.h" +#include "lwip/netif.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** Currently, the function ip_output_if_opt() is only used with IGMP */ +#define IP_OPTIONS_SEND LWIP_IGMP + +#define IP_HLEN 20 + +#define IP_PROTO_ICMP 1 +#define IP_PROTO_IGMP 2 +#define IP_PROTO_UDP 17 +#define IP_PROTO_UDPLITE 136 +#define IP_PROTO_TCP 6 + +/* This is passed as the destination address to ip_output_if (not + to ip_output), meaning that an IP header already is constructed + in the pbuf. This is used when TCP retransmits. */ +#ifdef IP_HDRINCL +#undef IP_HDRINCL +#endif /* IP_HDRINCL */ +#define IP_HDRINCL NULL + +#if LWIP_NETIF_HWADDRHINT +#define IP_PCB_ADDRHINT ;u8_t addr_hint +#else +#define IP_PCB_ADDRHINT +#endif /* LWIP_NETIF_HWADDRHINT */ + +/* This is the common part of all PCB types. It needs to be at the + beginning of a PCB type definition. It is located here so that + changes to this common part are made in one location instead of + having to change all PCB structs. */ +#define IP_PCB \ + /* ip addresses in network byte order */ \ + ip_addr_t local_ip; \ + ip_addr_t remote_ip; \ + /* Socket options */ \ + u8_t so_options; \ + /* Type Of Service */ \ + u8_t tos; \ + /* Time To Live */ \ + u8_t ttl \ + /* link layer address resolution hint */ \ + IP_PCB_ADDRHINT + +struct ip_pcb { +/* Common members of all PCB types */ + IP_PCB; +}; + +/* + * Option flags per-socket. These are the same like SO_XXX. + */ +/*#define SOF_DEBUG (u8_t)0x01U Unimplemented: turn on debugging info recording */ +#define SOF_ACCEPTCONN (u8_t)0x02U /* socket has had listen() */ +#define SOF_REUSEADDR (u8_t)0x04U /* allow local address reuse */ +#define SOF_KEEPALIVE (u8_t)0x08U /* keep connections alive */ +/*#define SOF_DONTROUTE (u8_t)0x10U Unimplemented: just use interface addresses */ +#define SOF_BROADCAST (u8_t)0x20U /* permit to send and to receive broadcast messages (see IP_SOF_BROADCAST option) */ +/*#define SOF_USELOOPBACK (u8_t)0x40U Unimplemented: bypass hardware when possible */ +#define SOF_LINGER (u8_t)0x80U /* linger on close if data present */ +/*#define SOF_OOBINLINE (u16_t)0x0100U Unimplemented: leave received OOB data in line */ +/*#define SOF_REUSEPORT (u16_t)0x0200U Unimplemented: allow local address & port reuse */ + +/* These flags are inherited (e.g. from a listen-pcb to a connection-pcb): */ +#define SOF_INHERITED (SOF_REUSEADDR|SOF_KEEPALIVE|SOF_LINGER/*|SOF_DEBUG|SOF_DONTROUTE|SOF_OOBINLINE*/) + + +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct ip_hdr { + /* version / header length / type of service */ + PACK_STRUCT_FIELD(u16_t _v_hl_tos); + /* total length */ + PACK_STRUCT_FIELD(u16_t _len); + /* identification */ + PACK_STRUCT_FIELD(u16_t _id); + /* fragment offset field */ + PACK_STRUCT_FIELD(u16_t _offset); +#define IP_RF 0x8000U /* reserved fragment flag */ +#define IP_DF 0x4000U /* dont fragment flag */ +#define IP_MF 0x2000U /* more fragments flag */ +#define IP_OFFMASK 0x1fffU /* mask for fragmenting bits */ + /* time to live */ + PACK_STRUCT_FIELD(u8_t _ttl); + /* protocol*/ + PACK_STRUCT_FIELD(u8_t _proto); + /* checksum */ + PACK_STRUCT_FIELD(u16_t _chksum); + /* source and destination IP addresses */ + PACK_STRUCT_FIELD(ip_addr_p_t src); + PACK_STRUCT_FIELD(ip_addr_p_t dest); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +#define IPH_V(hdr) (ntohs((hdr)->_v_hl_tos) >> 12) +#define IPH_HL(hdr) ((ntohs((hdr)->_v_hl_tos) >> 8) & 0x0f) +#define IPH_TOS(hdr) (ntohs((hdr)->_v_hl_tos) & 0xff) +#define IPH_LEN(hdr) ((hdr)->_len) +#define IPH_ID(hdr) ((hdr)->_id) +#define IPH_OFFSET(hdr) ((hdr)->_offset) +#define IPH_TTL(hdr) ((hdr)->_ttl) +#define IPH_PROTO(hdr) ((hdr)->_proto) +#define IPH_CHKSUM(hdr) ((hdr)->_chksum) + +#define IPH_VHLTOS_SET(hdr, v, hl, tos) (hdr)->_v_hl_tos = (htons(((v) << 12) | ((hl) << 8) | (tos))) +#define IPH_LEN_SET(hdr, len) (hdr)->_len = (len) +#define IPH_ID_SET(hdr, id) (hdr)->_id = (id) +#define IPH_OFFSET_SET(hdr, off) (hdr)->_offset = (off) +#define IPH_TTL_SET(hdr, ttl) (hdr)->_ttl = (u8_t)(ttl) +#define IPH_PROTO_SET(hdr, proto) (hdr)->_proto = (u8_t)(proto) +#define IPH_CHKSUM_SET(hdr, chksum) (hdr)->_chksum = (chksum) + +/** The interface that provided the packet for the current callback invocation. */ +extern struct netif *current_netif; +/** Header of the input packet currently being processed. */ +extern const struct ip_hdr *current_header; +/** Source IP address of current_header */ +extern ip_addr_t current_iphdr_src; +/** Destination IP address of current_header */ +extern ip_addr_t current_iphdr_dest; + +#define ip_init() /* Compatibility define, not init needed. */ +struct netif *ip_route(ip_addr_t *dest); +err_t ip_input(struct pbuf *p, struct netif *inp); +err_t ip_output(struct pbuf *p, ip_addr_t *src, ip_addr_t *dest, + u8_t ttl, u8_t tos, u8_t proto); +err_t ip_output_if(struct pbuf *p, ip_addr_t *src, ip_addr_t *dest, + u8_t ttl, u8_t tos, u8_t proto, + struct netif *netif); +#if LWIP_NETIF_HWADDRHINT +err_t ip_output_hinted(struct pbuf *p, ip_addr_t *src, ip_addr_t *dest, + u8_t ttl, u8_t tos, u8_t proto, u8_t *addr_hint); +#endif /* LWIP_NETIF_HWADDRHINT */ +#if IP_OPTIONS_SEND +err_t ip_output_if_opt(struct pbuf *p, ip_addr_t *src, ip_addr_t *dest, + u8_t ttl, u8_t tos, u8_t proto, struct netif *netif, void *ip_options, + u16_t optlen); +#endif /* IP_OPTIONS_SEND */ +/** Get the interface that received the current packet. + * This function must only be called from a receive callback (udp_recv, + * raw_recv, tcp_accept). It will return NULL otherwise. */ +#define ip_current_netif() (current_netif) +/** Get the IP header of the current packet. + * This function must only be called from a receive callback (udp_recv, + * raw_recv, tcp_accept). It will return NULL otherwise. */ +#define ip_current_header() (current_header) +/** Source IP address of current_header */ +#define ip_current_src_addr() (¤t_iphdr_src) +/** Destination IP address of current_header */ +#define ip_current_dest_addr() (¤t_iphdr_dest) + +#if IP_DEBUG +void ip_debug_print(struct pbuf *p); +#else +#define ip_debug_print(p) +#endif /* IP_DEBUG */ + +#ifdef __cplusplus +} +#endif + +#endif /* __LWIP_IP_H__ */ + + diff --git a/features/unsupported/net/lwip/lwip/include/ipv4/lwip/ip_addr.h b/features/unsupported/net/lwip/lwip/include/ipv4/lwip/ip_addr.h new file mode 100644 index 00000000000..77f84e02cfc --- /dev/null +++ b/features/unsupported/net/lwip/lwip/include/ipv4/lwip/ip_addr.h @@ -0,0 +1,244 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef __LWIP_IP_ADDR_H__ +#define __LWIP_IP_ADDR_H__ + +#include "lwip/opt.h" +#include "lwip/def.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* This is the aligned version of ip_addr_t, + used as local variable, on the stack, etc. */ +struct ip_addr { + u32_t addr; +}; + +/* This is the packed version of ip_addr_t, + used in network headers that are itself packed */ +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct ip_addr_packed { + PACK_STRUCT_FIELD(u32_t addr); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +/** ip_addr_t uses a struct for convenience only, so that the same defines can + * operate both on ip_addr_t as well as on ip_addr_p_t. */ +typedef struct ip_addr ip_addr_t; +typedef struct ip_addr_packed ip_addr_p_t; + +/* + * struct ipaddr2 is used in the definition of the ARP packet format in + * order to support compilers that don't have structure packing. + */ +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct ip_addr2 { + PACK_STRUCT_FIELD(u16_t addrw[2]); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +/* Forward declaration to not include netif.h */ +struct netif; + +extern const ip_addr_t ip_addr_any; +extern const ip_addr_t ip_addr_broadcast; + +/** IP_ADDR_ can be used as a fixed IP address + * for the wildcard and the broadcast address + */ +#define IP_ADDR_ANY ((ip_addr_t *)&ip_addr_any) +#define IP_ADDR_BROADCAST ((ip_addr_t *)&ip_addr_broadcast) + +/** 255.255.255.255 */ +#define IPADDR_NONE ((u32_t)0xffffffffUL) +/** 127.0.0.1 */ +#define IPADDR_LOOPBACK ((u32_t)0x7f000001UL) +/** 0.0.0.0 */ +#define IPADDR_ANY ((u32_t)0x00000000UL) +/** 255.255.255.255 */ +#define IPADDR_BROADCAST ((u32_t)0xffffffffUL) + +/* Definitions of the bits in an Internet address integer. + + On subnets, host and network parts are found according to + the subnet mask, not these masks. */ +#define IP_CLASSA(a) ((((u32_t)(a)) & 0x80000000UL) == 0) +#define IP_CLASSA_NET 0xff000000 +#define IP_CLASSA_NSHIFT 24 +#define IP_CLASSA_HOST (0xffffffff & ~IP_CLASSA_NET) +#define IP_CLASSA_MAX 128 + +#define IP_CLASSB(a) ((((u32_t)(a)) & 0xc0000000UL) == 0x80000000UL) +#define IP_CLASSB_NET 0xffff0000 +#define IP_CLASSB_NSHIFT 16 +#define IP_CLASSB_HOST (0xffffffff & ~IP_CLASSB_NET) +#define IP_CLASSB_MAX 65536 + +#define IP_CLASSC(a) ((((u32_t)(a)) & 0xe0000000UL) == 0xc0000000UL) +#define IP_CLASSC_NET 0xffffff00 +#define IP_CLASSC_NSHIFT 8 +#define IP_CLASSC_HOST (0xffffffff & ~IP_CLASSC_NET) + +#define IP_CLASSD(a) (((u32_t)(a) & 0xf0000000UL) == 0xe0000000UL) +#define IP_CLASSD_NET 0xf0000000 /* These ones aren't really */ +#define IP_CLASSD_NSHIFT 28 /* net and host fields, but */ +#define IP_CLASSD_HOST 0x0fffffff /* routing needn't know. */ +#define IP_MULTICAST(a) IP_CLASSD(a) + +#define IP_EXPERIMENTAL(a) (((u32_t)(a) & 0xf0000000UL) == 0xf0000000UL) +#define IP_BADCLASS(a) (((u32_t)(a) & 0xf0000000UL) == 0xf0000000UL) + +#define IP_LOOPBACKNET 127 /* official! */ + + +#if BYTE_ORDER == BIG_ENDIAN +/** Set an IP address given by the four byte-parts */ +#define IP4_ADDR(ipaddr, a,b,c,d) \ + (ipaddr)->addr = ((u32_t)((a) & 0xff) << 24) | \ + ((u32_t)((b) & 0xff) << 16) | \ + ((u32_t)((c) & 0xff) << 8) | \ + (u32_t)((d) & 0xff) +#else +/** Set an IP address given by the four byte-parts. + Little-endian version that prevents the use of htonl. */ +#define IP4_ADDR(ipaddr, a,b,c,d) \ + (ipaddr)->addr = ((u32_t)((d) & 0xff) << 24) | \ + ((u32_t)((c) & 0xff) << 16) | \ + ((u32_t)((b) & 0xff) << 8) | \ + (u32_t)((a) & 0xff) +#endif + +/** MEMCPY-like copying of IP addresses where addresses are known to be + * 16-bit-aligned if the port is correctly configured (so a port could define + * this to copying 2 u16_t's) - no NULL-pointer-checking needed. */ +#ifndef IPADDR2_COPY +#define IPADDR2_COPY(dest, src) SMEMCPY(dest, src, sizeof(ip_addr_t)) +#endif + +/** Copy IP address - faster than ip_addr_set: no NULL check */ +#define ip_addr_copy(dest, src) ((dest).addr = (src).addr) +/** Safely copy one IP address to another (src may be NULL) */ +#define ip_addr_set(dest, src) ((dest)->addr = \ + ((src) == NULL ? 0 : \ + (src)->addr)) +/** Set complete address to zero */ +#define ip_addr_set_zero(ipaddr) ((ipaddr)->addr = 0) +/** Set address to IPADDR_ANY (no need for htonl()) */ +#define ip_addr_set_any(ipaddr) ((ipaddr)->addr = IPADDR_ANY) +/** Set address to loopback address */ +#define ip_addr_set_loopback(ipaddr) ((ipaddr)->addr = PP_HTONL(IPADDR_LOOPBACK)) +/** Safely copy one IP address to another and change byte order + * from host- to network-order. */ +#define ip_addr_set_hton(dest, src) ((dest)->addr = \ + ((src) == NULL ? 0:\ + htonl((src)->addr))) +/** IPv4 only: set the IP address given as an u32_t */ +#define ip4_addr_set_u32(dest_ipaddr, src_u32) ((dest_ipaddr)->addr = (src_u32)) +/** IPv4 only: get the IP address as an u32_t */ +#define ip4_addr_get_u32(src_ipaddr) ((src_ipaddr)->addr) + +/** Get the network address by combining host address with netmask */ +#define ip_addr_get_network(target, host, netmask) ((target)->addr = ((host)->addr) & ((netmask)->addr)) + +/** + * Determine if two address are on the same network. + * + * @arg addr1 IP address 1 + * @arg addr2 IP address 2 + * @arg mask network identifier mask + * @return !0 if the network identifiers of both address match + */ +#define ip_addr_netcmp(addr1, addr2, mask) (((addr1)->addr & \ + (mask)->addr) == \ + ((addr2)->addr & \ + (mask)->addr)) +#define ip_addr_cmp(addr1, addr2) ((addr1)->addr == (addr2)->addr) + +#define ip_addr_isany(addr1) ((addr1) == NULL || (addr1)->addr == IPADDR_ANY) + +#define ip_addr_isbroadcast(ipaddr, netif) ip4_addr_isbroadcast((ipaddr)->addr, (netif)) +u8_t ip4_addr_isbroadcast(u32_t addr, const struct netif *netif); + +#define ip_addr_netmask_valid(netmask) ip4_addr_netmask_valid((netmask)->addr) +u8_t ip4_addr_netmask_valid(u32_t netmask); + +#define ip_addr_ismulticast(addr1) (((addr1)->addr & PP_HTONL(0xf0000000UL)) == PP_HTONL(0xe0000000UL)) + +#define ip_addr_islinklocal(addr1) (((addr1)->addr & PP_HTONL(0xffff0000UL)) == PP_HTONL(0xa9fe0000UL)) + +#define ip_addr_debug_print(debug, ipaddr) \ + LWIP_DEBUGF(debug, ("%"U16_F".%"U16_F".%"U16_F".%"U16_F, \ + ipaddr != NULL ? ip4_addr1_16(ipaddr) : 0, \ + ipaddr != NULL ? ip4_addr2_16(ipaddr) : 0, \ + ipaddr != NULL ? ip4_addr3_16(ipaddr) : 0, \ + ipaddr != NULL ? ip4_addr4_16(ipaddr) : 0)) + +/* Get one byte from the 4-byte address */ +#define ip4_addr1(ipaddr) (((u8_t*)(ipaddr))[0]) +#define ip4_addr2(ipaddr) (((u8_t*)(ipaddr))[1]) +#define ip4_addr3(ipaddr) (((u8_t*)(ipaddr))[2]) +#define ip4_addr4(ipaddr) (((u8_t*)(ipaddr))[3]) +/* These are cast to u16_t, with the intent that they are often arguments + * to printf using the U16_F format from cc.h. */ +#define ip4_addr1_16(ipaddr) ((u16_t)ip4_addr1(ipaddr)) +#define ip4_addr2_16(ipaddr) ((u16_t)ip4_addr2(ipaddr)) +#define ip4_addr3_16(ipaddr) ((u16_t)ip4_addr3(ipaddr)) +#define ip4_addr4_16(ipaddr) ((u16_t)ip4_addr4(ipaddr)) + +/** For backwards compatibility */ +#define ip_ntoa(ipaddr) ipaddr_ntoa(ipaddr) + +u32_t ipaddr_addr(const char *cp); +int ipaddr_aton(const char *cp, ip_addr_t *addr); +/** returns ptr to static buffer; not reentrant! */ +char *ipaddr_ntoa(const ip_addr_t *addr); +char *ipaddr_ntoa_r(const ip_addr_t *addr, char *buf, int buflen); + +#ifdef __cplusplus +} +#endif + +#endif /* __LWIP_IP_ADDR_H__ */ diff --git a/features/unsupported/net/lwip/lwip/include/ipv4/lwip/ip_frag.h b/features/unsupported/net/lwip/lwip/include/ipv4/lwip/ip_frag.h new file mode 100644 index 00000000000..77b5eb1eef7 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/include/ipv4/lwip/ip_frag.h @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Jani Monoses + * + */ + +#ifndef __LWIP_IP_FRAG_H__ +#define __LWIP_IP_FRAG_H__ + +#include "lwip/opt.h" +#include "lwip/err.h" +#include "lwip/pbuf.h" +#include "lwip/netif.h" +#include "lwip/ip_addr.h" +#include "lwip/ip.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#if IP_REASSEMBLY +/* The IP reassembly timer interval in milliseconds. */ +#define IP_TMR_INTERVAL 1000 + +/* IP reassembly helper struct. + * This is exported because memp needs to know the size. + */ +struct ip_reassdata { + struct ip_reassdata *next; + struct pbuf *p; + struct ip_hdr iphdr; + u16_t datagram_len; + u8_t flags; + u8_t timer; +}; + +void ip_reass_init(void); +void ip_reass_tmr(void); +struct pbuf * ip_reass(struct pbuf *p); +#endif /* IP_REASSEMBLY */ + +#if IP_FRAG +#if !IP_FRAG_USES_STATIC_BUF && !LWIP_NETIF_TX_SINGLE_PBUF +/** A custom pbuf that holds a reference to another pbuf, which is freed + * when this custom pbuf is freed. This is used to create a custom PBUF_REF + * that points into the original pbuf. */ +struct pbuf_custom_ref { + /** 'base class' */ + struct pbuf_custom pc; + /** pointer to the original pbuf that is referenced */ + struct pbuf *original; +}; +#endif /* !IP_FRAG_USES_STATIC_BUF && !LWIP_NETIF_TX_SINGLE_PBUF */ + +err_t ip_frag(struct pbuf *p, struct netif *netif, ip_addr_t *dest); +#endif /* IP_FRAG */ + +#ifdef __cplusplus +} +#endif + +#endif /* __LWIP_IP_FRAG_H__ */ diff --git a/features/unsupported/net/lwip/lwip/include/lwip/api.h b/features/unsupported/net/lwip/lwip/include/lwip/api.h new file mode 100644 index 00000000000..91b9e5d2435 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/include/lwip/api.h @@ -0,0 +1,284 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef __LWIP_API_H__ +#define __LWIP_API_H__ + +#include "lwip/opt.h" + +#if LWIP_NETCONN /* don't build if not configured for use in lwipopts.h */ + +#include /* for size_t */ + +#include "lwip/netbuf.h" +#include "lwip/sys.h" +#include "lwip/ip_addr.h" +#include "lwip/err.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* Throughout this file, IP addresses and port numbers are expected to be in + * the same byte order as in the corresponding pcb. + */ + +/* Flags for netconn_write (u8_t) */ +#define NETCONN_NOFLAG 0x00 +#define NETCONN_NOCOPY 0x00 /* Only for source code compatibility */ +#define NETCONN_COPY 0x01 +#define NETCONN_MORE 0x02 +#define NETCONN_DONTBLOCK 0x04 + +/* Flags for struct netconn.flags (u8_t) */ +/** TCP: when data passed to netconn_write doesn't fit into the send buffer, + this temporarily stores whether to wake up the original application task + if data couldn't be sent in the first try. */ +#define NETCONN_FLAG_WRITE_DELAYED 0x01 +/** Should this netconn avoid blocking? */ +#define NETCONN_FLAG_NON_BLOCKING 0x02 +/** Was the last connect action a non-blocking one? */ +#define NETCONN_FLAG_IN_NONBLOCKING_CONNECT 0x04 +/** If this is set, a TCP netconn must call netconn_recved() to update + the TCP receive window (done automatically if not set). */ +#define NETCONN_FLAG_NO_AUTO_RECVED 0x08 +/** If a nonblocking write has been rejected before, poll_tcp needs to + check if the netconn is writable again */ +#define NETCONN_FLAG_CHECK_WRITESPACE 0x10 + + +/* Helpers to process several netconn_types by the same code */ +#define NETCONNTYPE_GROUP(t) (t&0xF0) +#define NETCONNTYPE_DATAGRAM(t) (t&0xE0) + +/** Protocol family and type of the netconn */ +enum netconn_type { + NETCONN_INVALID = 0, + /* NETCONN_TCP Group */ + NETCONN_TCP = 0x10, + /* NETCONN_UDP Group */ + NETCONN_UDP = 0x20, + NETCONN_UDPLITE = 0x21, + NETCONN_UDPNOCHKSUM= 0x22, + /* NETCONN_RAW Group */ + NETCONN_RAW = 0x40 +}; + +/** Current state of the netconn. Non-TCP netconns are always + * in state NETCONN_NONE! */ +enum netconn_state { + NETCONN_NONE, + NETCONN_WRITE, + NETCONN_LISTEN, + NETCONN_CONNECT, + NETCONN_CLOSE +}; + +/** Use to inform the callback function about changes */ +enum netconn_evt { + NETCONN_EVT_RCVPLUS, + NETCONN_EVT_RCVMINUS, + NETCONN_EVT_SENDPLUS, + NETCONN_EVT_SENDMINUS, + NETCONN_EVT_ERROR +}; + +#if LWIP_IGMP +/** Used for netconn_join_leave_group() */ +enum netconn_igmp { + NETCONN_JOIN, + NETCONN_LEAVE +}; +#endif /* LWIP_IGMP */ + +/* forward-declare some structs to avoid to include their headers */ +struct ip_pcb; +struct tcp_pcb; +struct udp_pcb; +struct raw_pcb; +struct netconn; +struct api_msg_msg; + +/** A callback prototype to inform about events for a netconn */ +typedef void (* netconn_callback)(struct netconn *, enum netconn_evt, u16_t len); + +/** A netconn descriptor */ +struct netconn { + /** type of the netconn (TCP, UDP or RAW) */ + enum netconn_type type; + /** current state of the netconn */ + enum netconn_state state; + /** the lwIP internal protocol control block */ + union { + struct ip_pcb *ip; + struct tcp_pcb *tcp; + struct udp_pcb *udp; + struct raw_pcb *raw; + } pcb; + /** the last error this netconn had */ + err_t last_err; + /** sem that is used to synchroneously execute functions in the core context */ + sys_sem_t op_completed; + /** mbox where received packets are stored until they are fetched + by the netconn application thread (can grow quite big) */ + sys_mbox_t recvmbox; +#if LWIP_TCP + /** mbox where new connections are stored until processed + by the application thread */ + sys_mbox_t acceptmbox; +#endif /* LWIP_TCP */ + /** only used for socket layer */ +#if LWIP_SOCKET + int socket; +#endif /* LWIP_SOCKET */ +#if LWIP_SO_RCVTIMEO + /** timeout to wait for new data to be received + (or connections to arrive for listening netconns) */ + int recv_timeout; +#endif /* LWIP_SO_RCVTIMEO */ +#if LWIP_SO_RCVBUF + /** maximum amount of bytes queued in recvmbox + not used for TCP: adjust TCP_WND instead! */ + int recv_bufsize; + /** number of bytes currently in recvmbox to be received, + tested against recv_bufsize to limit bytes on recvmbox + for UDP and RAW, used for FIONREAD */ + s16_t recv_avail; +#endif /* LWIP_SO_RCVBUF */ + /** flags holding more netconn-internal state, see NETCONN_FLAG_* defines */ + u8_t flags; +#if LWIP_TCP + /** TCP: when data passed to netconn_write doesn't fit into the send buffer, + this temporarily stores how much is already sent. */ + size_t write_offset; + /** TCP: when data passed to netconn_write doesn't fit into the send buffer, + this temporarily stores the message. + Also used during connect and close. */ + struct api_msg_msg *current_msg; +#endif /* LWIP_TCP */ + /** A callback function that is informed about events for this netconn */ + netconn_callback callback; +}; + +/** Register an Network connection event */ +#define API_EVENT(c,e,l) if (c->callback) { \ + (*c->callback)(c, e, l); \ + } + +/** Set conn->last_err to err but don't overwrite fatal errors */ +#define NETCONN_SET_SAFE_ERR(conn, err) do { \ + SYS_ARCH_DECL_PROTECT(lev); \ + SYS_ARCH_PROTECT(lev); \ + if (!ERR_IS_FATAL((conn)->last_err)) { \ + (conn)->last_err = err; \ + } \ + SYS_ARCH_UNPROTECT(lev); \ +} while(0); + +/* Network connection functions: */ +#define netconn_new(t) netconn_new_with_proto_and_callback(t, 0, NULL) +#define netconn_new_with_callback(t, c) netconn_new_with_proto_and_callback(t, 0, c) +struct +netconn *netconn_new_with_proto_and_callback(enum netconn_type t, u8_t proto, + netconn_callback callback); +err_t netconn_delete(struct netconn *conn); +/** Get the type of a netconn (as enum netconn_type). */ +#define netconn_type(conn) (conn->type) + +err_t netconn_getaddr(struct netconn *conn, ip_addr_t *addr, + u16_t *port, u8_t local); +#define netconn_peer(c,i,p) netconn_getaddr(c,i,p,0) +#define netconn_addr(c,i,p) netconn_getaddr(c,i,p,1) + +err_t netconn_bind(struct netconn *conn, ip_addr_t *addr, u16_t port); +err_t netconn_connect(struct netconn *conn, ip_addr_t *addr, u16_t port); +err_t netconn_disconnect (struct netconn *conn); +err_t netconn_listen_with_backlog(struct netconn *conn, u8_t backlog); +#define netconn_listen(conn) netconn_listen_with_backlog(conn, TCP_DEFAULT_LISTEN_BACKLOG) +err_t netconn_accept(struct netconn *conn, struct netconn **new_conn); +err_t netconn_recv(struct netconn *conn, struct netbuf **new_buf); +err_t netconn_recv_tcp_pbuf(struct netconn *conn, struct pbuf **new_buf); +void netconn_recved(struct netconn *conn, u32_t length); +err_t netconn_sendto(struct netconn *conn, struct netbuf *buf, + ip_addr_t *addr, u16_t port); +err_t netconn_send(struct netconn *conn, struct netbuf *buf); +err_t netconn_write(struct netconn *conn, const void *dataptr, size_t size, + u8_t apiflags); +err_t netconn_close(struct netconn *conn); +err_t netconn_shutdown(struct netconn *conn, u8_t shut_rx, u8_t shut_tx); + +#if LWIP_IGMP +err_t netconn_join_leave_group(struct netconn *conn, ip_addr_t *multiaddr, + ip_addr_t *netif_addr, enum netconn_igmp join_or_leave); +#endif /* LWIP_IGMP */ +#if LWIP_DNS +err_t netconn_gethostbyname(const char *name, ip_addr_t *addr); +#endif /* LWIP_DNS */ + +#define netconn_err(conn) ((conn)->last_err) +#define netconn_recv_bufsize(conn) ((conn)->recv_bufsize) + +/** Set the blocking status of netconn calls (@todo: write/send is missing) */ +#define netconn_set_nonblocking(conn, val) do { if(val) { \ + (conn)->flags |= NETCONN_FLAG_NON_BLOCKING; \ +} else { \ + (conn)->flags &= ~ NETCONN_FLAG_NON_BLOCKING; }} while(0) +/** Get the blocking status of netconn calls (@todo: write/send is missing) */ +#define netconn_is_nonblocking(conn) (((conn)->flags & NETCONN_FLAG_NON_BLOCKING) != 0) + +/** TCP: Set the no-auto-recved status of netconn calls (see NETCONN_FLAG_NO_AUTO_RECVED) */ +#define netconn_set_noautorecved(conn, val) do { if(val) { \ + (conn)->flags |= NETCONN_FLAG_NO_AUTO_RECVED; \ +} else { \ + (conn)->flags &= ~ NETCONN_FLAG_NO_AUTO_RECVED; }} while(0) +/** TCP: Get the no-auto-recved status of netconn calls (see NETCONN_FLAG_NO_AUTO_RECVED) */ +#define netconn_get_noautorecved(conn) (((conn)->flags & NETCONN_FLAG_NO_AUTO_RECVED) != 0) + +#if LWIP_SO_RCVTIMEO +/** Set the receive timeout in milliseconds */ +#define netconn_set_recvtimeout(conn, timeout) ((conn)->recv_timeout = (timeout)) +/** Get the receive timeout in milliseconds */ +#define netconn_get_recvtimeout(conn) ((conn)->recv_timeout) +#endif /* LWIP_SO_RCVTIMEO */ +#if LWIP_SO_RCVBUF +/** Set the receive buffer in bytes */ +#define netconn_set_recvbufsize(conn, recvbufsize) ((conn)->recv_bufsize = (recvbufsize)) +/** Get the receive buffer in bytes */ +#define netconn_get_recvbufsize(conn) ((conn)->recv_bufsize) +#endif /* LWIP_SO_RCVBUF*/ + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_NETCONN */ + +#endif /* __LWIP_API_H__ */ diff --git a/features/unsupported/net/lwip/lwip/include/lwip/api_msg.h b/features/unsupported/net/lwip/lwip/include/lwip/api_msg.h new file mode 100644 index 00000000000..f99d8c3b719 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/include/lwip/api_msg.h @@ -0,0 +1,174 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef __LWIP_API_MSG_H__ +#define __LWIP_API_MSG_H__ + +#include "lwip/opt.h" + +#if LWIP_NETCONN /* don't build if not configured for use in lwipopts.h */ + +#include /* for size_t */ + +#include "lwip/ip_addr.h" +#include "lwip/err.h" +#include "lwip/sys.h" +#include "lwip/igmp.h" +#include "lwip/api.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* For the netconn API, these values are use as a bitmask! */ +#define NETCONN_SHUT_RD 1 +#define NETCONN_SHUT_WR 2 +#define NETCONN_SHUT_RDWR (NETCONN_SHUT_RD | NETCONN_SHUT_WR) + +/* IP addresses and port numbers are expected to be in + * the same byte order as in the corresponding pcb. + */ +/** This struct includes everything that is necessary to execute a function + for a netconn in another thread context (mainly used to process netconns + in the tcpip_thread context to be thread safe). */ +struct api_msg_msg { + /** The netconn which to process - always needed: it includes the semaphore + which is used to block the application thread until the function finished. */ + struct netconn *conn; + /** The return value of the function executed in tcpip_thread. */ + err_t err; + /** Depending on the executed function, one of these union members is used */ + union { + /** used for do_send */ + struct netbuf *b; + /** used for do_newconn */ + struct { + u8_t proto; + } n; + /** used for do_bind and do_connect */ + struct { + ip_addr_t *ipaddr; + u16_t port; + } bc; + /** used for do_getaddr */ + struct { + ip_addr_t *ipaddr; + u16_t *port; + u8_t local; + } ad; + /** used for do_write */ + struct { + const void *dataptr; + size_t len; + u8_t apiflags; + } w; + /** used for do_recv */ + struct { + u32_t len; + } r; + /** used for do_close (/shutdown) */ + struct { + u8_t shut; + } sd; +#if LWIP_IGMP + /** used for do_join_leave_group */ + struct { + ip_addr_t *multiaddr; + ip_addr_t *netif_addr; + enum netconn_igmp join_or_leave; + } jl; +#endif /* LWIP_IGMP */ +#if TCP_LISTEN_BACKLOG + struct { + u8_t backlog; + } lb; +#endif /* TCP_LISTEN_BACKLOG */ + } msg; +}; + +/** This struct contains a function to execute in another thread context and + a struct api_msg_msg that serves as an argument for this function. + This is passed to tcpip_apimsg to execute functions in tcpip_thread context. */ +struct api_msg { + /** function to execute in tcpip_thread context */ + void (* function)(struct api_msg_msg *msg); + /** arguments for this function */ + struct api_msg_msg msg; +}; + +#if LWIP_DNS +/** As do_gethostbyname requires more arguments but doesn't require a netconn, + it has its own struct (to avoid struct api_msg getting bigger than necessary). + do_gethostbyname must be called using tcpip_callback instead of tcpip_apimsg + (see netconn_gethostbyname). */ +struct dns_api_msg { + /** Hostname to query or dotted IP address string */ + const char *name; + /** Rhe resolved address is stored here */ + ip_addr_t *addr; + /** This semaphore is posted when the name is resolved, the application thread + should wait on it. */ + sys_sem_t *sem; + /** Errors are given back here */ + err_t *err; +}; +#endif /* LWIP_DNS */ + +void do_newconn ( struct api_msg_msg *msg); +void do_delconn ( struct api_msg_msg *msg); +void do_bind ( struct api_msg_msg *msg); +void do_connect ( struct api_msg_msg *msg); +void do_disconnect ( struct api_msg_msg *msg); +void do_listen ( struct api_msg_msg *msg); +void do_send ( struct api_msg_msg *msg); +void do_recv ( struct api_msg_msg *msg); +void do_write ( struct api_msg_msg *msg); +void do_getaddr ( struct api_msg_msg *msg); +void do_close ( struct api_msg_msg *msg); +void do_shutdown ( struct api_msg_msg *msg); +#if LWIP_IGMP +void do_join_leave_group( struct api_msg_msg *msg); +#endif /* LWIP_IGMP */ + +#if LWIP_DNS +void do_gethostbyname(void *arg); +#endif /* LWIP_DNS */ + +struct netconn* netconn_alloc(enum netconn_type t, netconn_callback callback); +void netconn_free(struct netconn *conn); + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_NETCONN */ + +#endif /* __LWIP_API_MSG_H__ */ diff --git a/features/unsupported/net/lwip/lwip/include/lwip/arch.h b/features/unsupported/net/lwip/lwip/include/lwip/arch.h new file mode 100644 index 00000000000..524af6be038 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/include/lwip/arch.h @@ -0,0 +1,238 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef __LWIP_ARCH_H__ +#define __LWIP_ARCH_H__ + +#ifndef LITTLE_ENDIAN +#define LITTLE_ENDIAN 1234 +#endif + +#ifndef BIG_ENDIAN +#define BIG_ENDIAN 4321 +#endif + +#include "arch/cc.h" + +/** Temporary: define format string for size_t if not defined in cc.h */ +#ifndef SZT_F +#define SZT_F U32_F +#endif /* SZT_F */ +/** Temporary upgrade helper: define format string for u8_t as hex if not + defined in cc.h */ +#ifndef X8_F +#define X8_F "02x" +#endif /* X8_F */ + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef PACK_STRUCT_BEGIN +#define PACK_STRUCT_BEGIN +#endif /* PACK_STRUCT_BEGIN */ + +#ifndef PACK_STRUCT_END +#define PACK_STRUCT_END +#endif /* PACK_STRUCT_END */ + +#ifndef PACK_STRUCT_FIELD +#define PACK_STRUCT_FIELD(x) x +#endif /* PACK_STRUCT_FIELD */ + + +#ifndef LWIP_UNUSED_ARG +#define LWIP_UNUSED_ARG(x) (void)x +#endif /* LWIP_UNUSED_ARG */ + + +#ifdef LWIP_PROVIDE_ERRNO + +#define EPERM 1 /* Operation not permitted */ +#define ENOENT 2 /* No such file or directory */ +#define ESRCH 3 /* No such process */ +#define EINTR 4 /* Interrupted system call */ +#define EIO 5 /* I/O error */ +#define ENXIO 6 /* No such device or address */ +#define E2BIG 7 /* Arg list too long */ +#define ENOEXEC 8 /* Exec format error */ +#define EBADF 9 /* Bad file number */ +#define ECHILD 10 /* No child processes */ +#define EAGAIN 11 /* Try again */ +#define ENOMEM 12 /* Out of memory */ +#define EACCES 13 /* Permission denied */ +#define EFAULT 14 /* Bad address */ +#define ENOTBLK 15 /* Block device required */ +#define EBUSY 16 /* Device or resource busy */ +#define EEXIST 17 /* File exists */ +#define EXDEV 18 /* Cross-device link */ +#define ENODEV 19 /* No such device */ +#define ENOTDIR 20 /* Not a directory */ +#define EISDIR 21 /* Is a directory */ +#define EINVAL 22 /* Invalid argument */ +#define ENFILE 23 /* File table overflow */ +#define EMFILE 24 /* Too many open files */ +#define ENOTTY 25 /* Not a typewriter */ +#define ETXTBSY 26 /* Text file busy */ +#define EFBIG 27 /* File too large */ +#define ENOSPC 28 /* No space left on device */ +#define ESPIPE 29 /* Illegal seek */ +#define EROFS 30 /* Read-only file system */ +#define EMLINK 31 /* Too many links */ +#define EPIPE 32 /* Broken pipe */ +#define EDOM 33 /* Math argument out of domain of func */ +#define ERANGE 34 /* Math result not representable */ +#define EDEADLK 35 /* Resource deadlock would occur */ +#define ENAMETOOLONG 36 /* File name too long */ +#define ENOLCK 37 /* No record locks available */ +#define ENOSYS 38 /* Function not implemented */ +#define ENOTEMPTY 39 /* Directory not empty */ +#define ELOOP 40 /* Too many symbolic links encountered */ +#define EWOULDBLOCK EAGAIN /* Operation would block */ +#define ENOMSG 42 /* No message of desired type */ +#define EIDRM 43 /* Identifier removed */ +#define ECHRNG 44 /* Channel number out of range */ +#define EL2NSYNC 45 /* Level 2 not synchronized */ +#define EL3HLT 46 /* Level 3 halted */ +#define EL3RST 47 /* Level 3 reset */ +#define ELNRNG 48 /* Link number out of range */ +#define EUNATCH 49 /* Protocol driver not attached */ +#define ENOCSI 50 /* No CSI structure available */ +#define EL2HLT 51 /* Level 2 halted */ +#define EBADE 52 /* Invalid exchange */ +#define EBADR 53 /* Invalid request descriptor */ +#define EXFULL 54 /* Exchange full */ +#define ENOANO 55 /* No anode */ +#define EBADRQC 56 /* Invalid request code */ +#define EBADSLT 57 /* Invalid slot */ + +#define EDEADLOCK EDEADLK + +#define EBFONT 59 /* Bad font file format */ +#define ENOSTR 60 /* Device not a stream */ +#define ENODATA 61 /* No data available */ +#define ETIME 62 /* Timer expired */ +#define ENOSR 63 /* Out of streams resources */ +#define ENONET 64 /* Machine is not on the network */ +#define ENOPKG 65 /* Package not installed */ +#define EREMOTE 66 /* Object is remote */ +#define ENOLINK 67 /* Link has been severed */ +#define EADV 68 /* Advertise error */ +#define ESRMNT 69 /* Srmount error */ +#define ECOMM 70 /* Communication error on send */ +#define EPROTO 71 /* Protocol error */ +#define EMULTIHOP 72 /* Multihop attempted */ +#define EDOTDOT 73 /* RFS specific error */ +#define EBADMSG 74 /* Not a data message */ +#define EOVERFLOW 75 /* Value too large for defined data type */ +#define ENOTUNIQ 76 /* Name not unique on network */ +#define EBADFD 77 /* File descriptor in bad state */ +#define EREMCHG 78 /* Remote address changed */ +#define ELIBACC 79 /* Can not access a needed shared library */ +#define ELIBBAD 80 /* Accessing a corrupted shared library */ +#define ELIBSCN 81 /* .lib section in a.out corrupted */ +#define ELIBMAX 82 /* Attempting to link in too many shared libraries */ +#define ELIBEXEC 83 /* Cannot exec a shared library directly */ +#define EILSEQ 84 /* Illegal byte sequence */ +#define ERESTART 85 /* Interrupted system call should be restarted */ +#define ESTRPIPE 86 /* Streams pipe error */ +#define EUSERS 87 /* Too many users */ +#define ENOTSOCK 88 /* Socket operation on non-socket */ +#define EDESTADDRREQ 89 /* Destination address required */ +#define EMSGSIZE 90 /* Message too long */ +#define EPROTOTYPE 91 /* Protocol wrong type for socket */ +#define ENOPROTOOPT 92 /* Protocol not available */ +#define EPROTONOSUPPORT 93 /* Protocol not supported */ +#define ESOCKTNOSUPPORT 94 /* Socket type not supported */ +#define EOPNOTSUPP 95 /* Operation not supported on transport endpoint */ +#define EPFNOSUPPORT 96 /* Protocol family not supported */ +#define EAFNOSUPPORT 97 /* Address family not supported by protocol */ +#define EADDRINUSE 98 /* Address already in use */ +#define EADDRNOTAVAIL 99 /* Cannot assign requested address */ +#define ENETDOWN 100 /* Network is down */ +#define ENETUNREACH 101 /* Network is unreachable */ +#define ENETRESET 102 /* Network dropped connection because of reset */ +#define ECONNABORTED 103 /* Software caused connection abort */ +#define ECONNRESET 104 /* Connection reset by peer */ +#define ENOBUFS 105 /* No buffer space available */ +#define EISCONN 106 /* Transport endpoint is already connected */ +#define ENOTCONN 107 /* Transport endpoint is not connected */ +#define ESHUTDOWN 108 /* Cannot send after transport endpoint shutdown */ +#define ETOOMANYREFS 109 /* Too many references: cannot splice */ +#define ETIMEDOUT 110 /* Connection timed out */ +#define ECONNREFUSED 111 /* Connection refused */ +#define EHOSTDOWN 112 /* Host is down */ +#define EHOSTUNREACH 113 /* No route to host */ +#define EALREADY 114 /* Operation already in progress */ +#define EINPROGRESS 115 /* Operation now in progress */ +#define ESTALE 116 /* Stale NFS file handle */ +#define EUCLEAN 117 /* Structure needs cleaning */ +#define ENOTNAM 118 /* Not a XENIX named type file */ +#define ENAVAIL 119 /* No XENIX semaphores available */ +#define EISNAM 120 /* Is a named type file */ +#define EREMOTEIO 121 /* Remote I/O error */ +#define EDQUOT 122 /* Quota exceeded */ + +#define ENOMEDIUM 123 /* No medium found */ +#define EMEDIUMTYPE 124 /* Wrong medium type */ + + +#define ENSROK 0 /* DNS server returned answer with no data */ +#define ENSRNODATA 160 /* DNS server returned answer with no data */ +#define ENSRFORMERR 161 /* DNS server claims query was misformatted */ +#define ENSRSERVFAIL 162 /* DNS server returned general failure */ +#define ENSRNOTFOUND 163 /* Domain name not found */ +#define ENSRNOTIMP 164 /* DNS server does not implement requested operation */ +#define ENSRREFUSED 165 /* DNS server refused query */ +#define ENSRBADQUERY 166 /* Misformatted DNS query */ +#define ENSRBADNAME 167 /* Misformatted domain name */ +#define ENSRBADFAMILY 168 /* Unsupported address family */ +#define ENSRBADRESP 169 /* Misformatted DNS reply */ +#define ENSRCONNREFUSED 170 /* Could not contact DNS servers */ +#define ENSRTIMEOUT 171 /* Timeout while contacting DNS servers */ +#define ENSROF 172 /* End of file */ +#define ENSRFILE 173 /* Error reading file */ +#define ENSRNOMEM 174 /* Out of memory */ +#define ENSRDESTRUCTION 175 /* Application terminated lookup */ +#define ENSRQUERYDOMAINTOOLONG 176 /* Domain name is too long */ +#define ENSRCNAMELOOP 177 /* Domain name is too long */ + +#ifndef errno +extern int errno; +#endif + +#endif /* LWIP_PROVIDE_ERRNO */ + +#ifdef __cplusplus +} +#endif + +#endif /* __LWIP_ARCH_H__ */ diff --git a/features/unsupported/net/lwip/lwip/include/lwip/debug.h b/features/unsupported/net/lwip/lwip/include/lwip/debug.h new file mode 100644 index 00000000000..d8359ea3a53 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/include/lwip/debug.h @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef __LWIP_DEBUG_H__ +#define __LWIP_DEBUG_H__ + +#include "lwip/arch.h" + +/** lower two bits indicate debug level + * - 0 all + * - 1 warning + * - 2 serious + * - 3 severe + */ +#define LWIP_DBG_LEVEL_ALL 0x00 +#define LWIP_DBG_LEVEL_OFF LWIP_DBG_LEVEL_ALL /* compatibility define only */ +#define LWIP_DBG_LEVEL_WARNING 0x01 /* bad checksums, dropped packets, ... */ +#define LWIP_DBG_LEVEL_SERIOUS 0x02 /* memory allocation failures, ... */ +#define LWIP_DBG_LEVEL_SEVERE 0x03 +#define LWIP_DBG_MASK_LEVEL 0x03 + +/** flag for LWIP_DEBUGF to enable that debug message */ +#define LWIP_DBG_ON 0x80U +/** flag for LWIP_DEBUGF to disable that debug message */ +#define LWIP_DBG_OFF 0x00U + +/** flag for LWIP_DEBUGF indicating a tracing message (to follow program flow) */ +#define LWIP_DBG_TRACE 0x40U +/** flag for LWIP_DEBUGF indicating a state debug message (to follow module states) */ +#define LWIP_DBG_STATE 0x20U +/** flag for LWIP_DEBUGF indicating newly added code, not thoroughly tested yet */ +#define LWIP_DBG_FRESH 0x10U +/** flag for LWIP_DEBUGF to halt after printing this debug message */ +#define LWIP_DBG_HALT 0x08U + +#ifndef LWIP_NOASSERT +#define LWIP_ASSERT(message, assertion) do { if(!(assertion)) \ + LWIP_PLATFORM_ASSERT(message); } while(0) +#else /* LWIP_NOASSERT */ +#define LWIP_ASSERT(message, assertion) +#endif /* LWIP_NOASSERT */ + +/** if "expression" isn't true, then print "message" and execute "handler" expression */ +#ifndef LWIP_ERROR +#define LWIP_ERROR(message, expression, handler) do { if (!(expression)) { \ + LWIP_PLATFORM_ASSERT(message); handler;}} while(0) +#endif /* LWIP_ERROR */ + +#ifdef LWIP_DEBUG +/** print debug message only if debug message type is enabled... + * AND is of correct type AND is at least LWIP_DBG_LEVEL + */ +#define LWIP_DEBUGF(debug, message) do { \ + if ( \ + ((debug) & LWIP_DBG_ON) && \ + ((debug) & LWIP_DBG_TYPES_ON) && \ + ((s16_t)((debug) & LWIP_DBG_MASK_LEVEL) >= LWIP_DBG_MIN_LEVEL)) { \ + LWIP_PLATFORM_DIAG(message); \ + if ((debug) & LWIP_DBG_HALT) { \ + while(1); \ + } \ + } \ + } while(0) + +#else /* LWIP_DEBUG */ +#define LWIP_DEBUGF(debug, message) +#endif /* LWIP_DEBUG */ + +#endif /* __LWIP_DEBUG_H__ */ + diff --git a/features/unsupported/net/lwip/lwip/include/lwip/def.h b/features/unsupported/net/lwip/lwip/include/lwip/def.h new file mode 100644 index 00000000000..9b6de6a8b81 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/include/lwip/def.h @@ -0,0 +1,127 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef __LWIP_DEF_H__ +#define __LWIP_DEF_H__ + +/* arch.h might define NULL already */ +#include "lwip/arch.h" +#include "lwip/opt.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define LWIP_MAX(x , y) (((x) > (y)) ? (x) : (y)) +#define LWIP_MIN(x , y) (((x) < (y)) ? (x) : (y)) + +#ifndef NULL +#define NULL ((void *)0) +#endif + +/** Get the absolute difference between 2 u32_t values (correcting overflows) + * 'a' is expected to be 'higher' (without overflow) than 'b'. */ +#define LWIP_U32_DIFF(a, b) (((a) >= (b)) ? ((a) - (b)) : (((a) + ((b) ^ 0xFFFFFFFF) + 1))) + +/* Endianess-optimized shifting of two u8_t to create one u16_t */ +#if BYTE_ORDER == LITTLE_ENDIAN +#define LWIP_MAKE_U16(a, b) ((a << 8) | b) +#else +#define LWIP_MAKE_U16(a, b) ((b << 8) | a) +#endif + +#ifndef LWIP_PLATFORM_BYTESWAP +#define LWIP_PLATFORM_BYTESWAP 0 +#endif + +#ifndef LWIP_PREFIX_BYTEORDER_FUNCS +/* workaround for naming collisions on some platforms */ + +#ifdef htons +#undef htons +#endif /* htons */ +#ifdef htonl +#undef htonl +#endif /* htonl */ +#ifdef ntohs +#undef ntohs +#endif /* ntohs */ +#ifdef ntohl +#undef ntohl +#endif /* ntohl */ + +#define htons(x) lwip_htons(x) +#define ntohs(x) lwip_ntohs(x) +#define htonl(x) lwip_htonl(x) +#define ntohl(x) lwip_ntohl(x) +#endif /* LWIP_PREFIX_BYTEORDER_FUNCS */ + +#if BYTE_ORDER == BIG_ENDIAN +#define lwip_htons(x) (x) +#define lwip_ntohs(x) (x) +#define lwip_htonl(x) (x) +#define lwip_ntohl(x) (x) +#define PP_HTONS(x) (x) +#define PP_NTOHS(x) (x) +#define PP_HTONL(x) (x) +#define PP_NTOHL(x) (x) +#else /* BYTE_ORDER != BIG_ENDIAN */ +#if LWIP_PLATFORM_BYTESWAP +#define lwip_htons(x) LWIP_PLATFORM_HTONS(x) +#define lwip_ntohs(x) LWIP_PLATFORM_HTONS(x) +#define lwip_htonl(x) LWIP_PLATFORM_HTONL(x) +#define lwip_ntohl(x) LWIP_PLATFORM_HTONL(x) +#else /* LWIP_PLATFORM_BYTESWAP */ +u16_t lwip_htons(u16_t x); +u16_t lwip_ntohs(u16_t x); +u32_t lwip_htonl(u32_t x); +u32_t lwip_ntohl(u32_t x); +#endif /* LWIP_PLATFORM_BYTESWAP */ + +/* These macros should be calculated by the preprocessor and are used + with compile-time constants only (so that there is no little-endian + overhead at runtime). */ +#define PP_HTONS(x) ((((x) & 0xff) << 8) | (((x) & 0xff00) >> 8)) +#define PP_NTOHS(x) PP_HTONS(x) +#define PP_HTONL(x) ((((x) & 0xff) << 24) | \ + (((x) & 0xff00) << 8) | \ + (((x) & 0xff0000UL) >> 8) | \ + (((x) & 0xff000000UL) >> 24)) +#define PP_NTOHL(x) PP_HTONL(x) + +#endif /* BYTE_ORDER == BIG_ENDIAN */ + +#ifdef __cplusplus +} +#endif + +#endif /* __LWIP_DEF_H__ */ + diff --git a/features/unsupported/net/lwip/lwip/include/lwip/dhcp.h b/features/unsupported/net/lwip/lwip/include/lwip/dhcp.h new file mode 100644 index 00000000000..32d93381d12 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/include/lwip/dhcp.h @@ -0,0 +1,242 @@ +/** @file + */ + +#ifndef __LWIP_DHCP_H__ +#define __LWIP_DHCP_H__ + +#include "lwip/opt.h" + +#if LWIP_DHCP /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/netif.h" +#include "lwip/udp.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** period (in seconds) of the application calling dhcp_coarse_tmr() */ +#define DHCP_COARSE_TIMER_SECS 60 +/** period (in milliseconds) of the application calling dhcp_coarse_tmr() */ +#define DHCP_COARSE_TIMER_MSECS (DHCP_COARSE_TIMER_SECS * 1000UL) +/** period (in milliseconds) of the application calling dhcp_fine_tmr() */ +#define DHCP_FINE_TIMER_MSECS 500 + +#define DHCP_CHADDR_LEN 16U +#define DHCP_SNAME_LEN 64U +#define DHCP_FILE_LEN 128U + +struct dhcp +{ + /** transaction identifier of last sent request */ + u32_t xid; + /** our connection to the DHCP server */ + struct udp_pcb *pcb; + /** incoming msg */ + struct dhcp_msg *msg_in; + /** current DHCP state machine state */ + u8_t state; + /** retries of current request */ + u8_t tries; +#if LWIP_DHCP_AUTOIP_COOP + u8_t autoip_coop_state; +#endif + u8_t subnet_mask_given; + + struct pbuf *p_out; /* pbuf of outcoming msg */ + struct dhcp_msg *msg_out; /* outgoing msg */ + u16_t options_out_len; /* outgoing msg options length */ + u16_t request_timeout; /* #ticks with period DHCP_FINE_TIMER_SECS for request timeout */ + u16_t t1_timeout; /* #ticks with period DHCP_COARSE_TIMER_SECS for renewal time */ + u16_t t2_timeout; /* #ticks with period DHCP_COARSE_TIMER_SECS for rebind time */ + ip_addr_t server_ip_addr; /* dhcp server address that offered this lease */ + ip_addr_t offered_ip_addr; + ip_addr_t offered_sn_mask; + ip_addr_t offered_gw_addr; + + u32_t offered_t0_lease; /* lease period (in seconds) */ + u32_t offered_t1_renew; /* recommended renew time (usually 50% of lease period) */ + u32_t offered_t2_rebind; /* recommended rebind time (usually 66% of lease period) */ + /* @todo: LWIP_DHCP_BOOTP_FILE configuration option? + integrate with possible TFTP-client for booting? */ +#if LWIP_DHCP_BOOTP_FILE + ip_addr_t offered_si_addr; + char boot_file_name[DHCP_FILE_LEN]; +#endif /* LWIP_DHCP_BOOTPFILE */ +}; + +/* MUST be compiled with "pack structs" or equivalent! */ +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +/** minimum set of fields of any DHCP message */ +struct dhcp_msg +{ + PACK_STRUCT_FIELD(u8_t op); + PACK_STRUCT_FIELD(u8_t htype); + PACK_STRUCT_FIELD(u8_t hlen); + PACK_STRUCT_FIELD(u8_t hops); + PACK_STRUCT_FIELD(u32_t xid); + PACK_STRUCT_FIELD(u16_t secs); + PACK_STRUCT_FIELD(u16_t flags); + PACK_STRUCT_FIELD(ip_addr_p_t ciaddr); + PACK_STRUCT_FIELD(ip_addr_p_t yiaddr); + PACK_STRUCT_FIELD(ip_addr_p_t siaddr); + PACK_STRUCT_FIELD(ip_addr_p_t giaddr); + PACK_STRUCT_FIELD(u8_t chaddr[DHCP_CHADDR_LEN]); + PACK_STRUCT_FIELD(u8_t sname[DHCP_SNAME_LEN]); + PACK_STRUCT_FIELD(u8_t file[DHCP_FILE_LEN]); + PACK_STRUCT_FIELD(u32_t cookie); +#define DHCP_MIN_OPTIONS_LEN 68U +/** make sure user does not configure this too small */ +#if ((defined(DHCP_OPTIONS_LEN)) && (DHCP_OPTIONS_LEN < DHCP_MIN_OPTIONS_LEN)) +# undef DHCP_OPTIONS_LEN +#endif +/** allow this to be configured in lwipopts.h, but not too small */ +#if (!defined(DHCP_OPTIONS_LEN)) +/** set this to be sufficient for your options in outgoing DHCP msgs */ +# define DHCP_OPTIONS_LEN DHCP_MIN_OPTIONS_LEN +#endif + PACK_STRUCT_FIELD(u8_t options[DHCP_OPTIONS_LEN]); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +void dhcp_set_struct(struct netif *netif, struct dhcp *dhcp); +/** Remove a struct dhcp previously set to the netif using dhcp_set_struct() */ +#define dhcp_remove_struct(netif) do { (netif)->dhcp = NULL; } while(0) +void dhcp_cleanup(struct netif *netif); +/** start DHCP configuration */ +err_t dhcp_start(struct netif *netif); +/** enforce early lease renewal (not needed normally)*/ +err_t dhcp_renew(struct netif *netif); +/** release the DHCP lease, usually called before dhcp_stop()*/ +err_t dhcp_release(struct netif *netif); +/** stop DHCP configuration */ +void dhcp_stop(struct netif *netif); +/** inform server of our manual IP address */ +void dhcp_inform(struct netif *netif); +/** Handle a possible change in the network configuration */ +void dhcp_network_changed(struct netif *netif); + +/** if enabled, check whether the offered IP address is not in use, using ARP */ +#if DHCP_DOES_ARP_CHECK +void dhcp_arp_reply(struct netif *netif, ip_addr_t *addr); +#endif + +/** to be called every minute */ +void dhcp_coarse_tmr(void); +/** to be called every half second */ +void dhcp_fine_tmr(void); + +/** DHCP message item offsets and length */ +#define DHCP_OP_OFS 0 +#define DHCP_HTYPE_OFS 1 +#define DHCP_HLEN_OFS 2 +#define DHCP_HOPS_OFS 3 +#define DHCP_XID_OFS 4 +#define DHCP_SECS_OFS 8 +#define DHCP_FLAGS_OFS 10 +#define DHCP_CIADDR_OFS 12 +#define DHCP_YIADDR_OFS 16 +#define DHCP_SIADDR_OFS 20 +#define DHCP_GIADDR_OFS 24 +#define DHCP_CHADDR_OFS 28 +#define DHCP_SNAME_OFS 44 +#define DHCP_FILE_OFS 108 +#define DHCP_MSG_LEN 236 + +#define DHCP_COOKIE_OFS DHCP_MSG_LEN +#define DHCP_OPTIONS_OFS (DHCP_MSG_LEN + 4) + +#define DHCP_CLIENT_PORT 68 +#define DHCP_SERVER_PORT 67 + +/** DHCP client states */ +#define DHCP_OFF 0 +#define DHCP_REQUESTING 1 +#define DHCP_INIT 2 +#define DHCP_REBOOTING 3 +#define DHCP_REBINDING 4 +#define DHCP_RENEWING 5 +#define DHCP_SELECTING 6 +#define DHCP_INFORMING 7 +#define DHCP_CHECKING 8 +#define DHCP_PERMANENT 9 +#define DHCP_BOUND 10 +/** not yet implemented #define DHCP_RELEASING 11 */ +#define DHCP_BACKING_OFF 12 + +/** AUTOIP cooperatation flags */ +#define DHCP_AUTOIP_COOP_STATE_OFF 0 +#define DHCP_AUTOIP_COOP_STATE_ON 1 + +#define DHCP_BOOTREQUEST 1 +#define DHCP_BOOTREPLY 2 + +/** DHCP message types */ +#define DHCP_DISCOVER 1 +#define DHCP_OFFER 2 +#define DHCP_REQUEST 3 +#define DHCP_DECLINE 4 +#define DHCP_ACK 5 +#define DHCP_NAK 6 +#define DHCP_RELEASE 7 +#define DHCP_INFORM 8 + +/** DHCP hardware type, currently only ethernet is supported */ +#define DHCP_HTYPE_ETH 1 + +#define DHCP_MAGIC_COOKIE 0x63825363UL + +/* This is a list of options for BOOTP and DHCP, see RFC 2132 for descriptions */ + +/** BootP options */ +#define DHCP_OPTION_PAD 0 +#define DHCP_OPTION_SUBNET_MASK 1 /* RFC 2132 3.3 */ +#define DHCP_OPTION_ROUTER 3 +#define DHCP_OPTION_DNS_SERVER 6 +#define DHCP_OPTION_HOSTNAME 12 +#define DHCP_OPTION_IP_TTL 23 +#define DHCP_OPTION_MTU 26 +#define DHCP_OPTION_BROADCAST 28 +#define DHCP_OPTION_TCP_TTL 37 +#define DHCP_OPTION_END 255 + +/** DHCP options */ +#define DHCP_OPTION_REQUESTED_IP 50 /* RFC 2132 9.1, requested IP address */ +#define DHCP_OPTION_LEASE_TIME 51 /* RFC 2132 9.2, time in seconds, in 4 bytes */ +#define DHCP_OPTION_OVERLOAD 52 /* RFC2132 9.3, use file and/or sname field for options */ + +#define DHCP_OPTION_MESSAGE_TYPE 53 /* RFC 2132 9.6, important for DHCP */ +#define DHCP_OPTION_MESSAGE_TYPE_LEN 1 + +#define DHCP_OPTION_SERVER_ID 54 /* RFC 2132 9.7, server IP address */ +#define DHCP_OPTION_PARAMETER_REQUEST_LIST 55 /* RFC 2132 9.8, requested option types */ + +#define DHCP_OPTION_MAX_MSG_SIZE 57 /* RFC 2132 9.10, message size accepted >= 576 */ +#define DHCP_OPTION_MAX_MSG_SIZE_LEN 2 + +#define DHCP_OPTION_T1 58 /* T1 renewal time */ +#define DHCP_OPTION_T2 59 /* T2 rebinding time */ +#define DHCP_OPTION_US 60 +#define DHCP_OPTION_CLIENT_ID 61 +#define DHCP_OPTION_TFTP_SERVERNAME 66 +#define DHCP_OPTION_BOOTFILE 67 + +/** possible combinations of overloading the file and sname fields with options */ +#define DHCP_OVERLOAD_NONE 0 +#define DHCP_OVERLOAD_FILE 1 +#define DHCP_OVERLOAD_SNAME 2 +#define DHCP_OVERLOAD_SNAME_FILE 3 + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_DHCP */ + +#endif /*__LWIP_DHCP_H__*/ diff --git a/features/unsupported/net/lwip/lwip/include/lwip/dns.h b/features/unsupported/net/lwip/lwip/include/lwip/dns.h new file mode 100644 index 00000000000..6c7d9b07399 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/include/lwip/dns.h @@ -0,0 +1,124 @@ +/** + * lwip DNS resolver header file. + + * Author: Jim Pettinato + * April 2007 + + * ported from uIP resolv.c Copyright (c) 2002-2003, Adam Dunkels. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote + * products derived from this software without specific prior + * written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS + * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef __LWIP_DNS_H__ +#define __LWIP_DNS_H__ + +#include "lwip/opt.h" + +#if LWIP_DNS /* don't build if not configured for use in lwipopts.h */ + +#ifdef __cplusplus +extern "C" { +#endif + +/** DNS timer period */ +#define DNS_TMR_INTERVAL 1000 + +/** DNS field TYPE used for "Resource Records" */ +#define DNS_RRTYPE_A 1 /* a host address */ +#define DNS_RRTYPE_NS 2 /* an authoritative name server */ +#define DNS_RRTYPE_MD 3 /* a mail destination (Obsolete - use MX) */ +#define DNS_RRTYPE_MF 4 /* a mail forwarder (Obsolete - use MX) */ +#define DNS_RRTYPE_CNAME 5 /* the canonical name for an alias */ +#define DNS_RRTYPE_SOA 6 /* marks the start of a zone of authority */ +#define DNS_RRTYPE_MB 7 /* a mailbox domain name (EXPERIMENTAL) */ +#define DNS_RRTYPE_MG 8 /* a mail group member (EXPERIMENTAL) */ +#define DNS_RRTYPE_MR 9 /* a mail rename domain name (EXPERIMENTAL) */ +#define DNS_RRTYPE_NULL 10 /* a null RR (EXPERIMENTAL) */ +#define DNS_RRTYPE_WKS 11 /* a well known service description */ +#define DNS_RRTYPE_PTR 12 /* a domain name pointer */ +#define DNS_RRTYPE_HINFO 13 /* host information */ +#define DNS_RRTYPE_MINFO 14 /* mailbox or mail list information */ +#define DNS_RRTYPE_MX 15 /* mail exchange */ +#define DNS_RRTYPE_TXT 16 /* text strings */ + +/** DNS field CLASS used for "Resource Records" */ +#define DNS_RRCLASS_IN 1 /* the Internet */ +#define DNS_RRCLASS_CS 2 /* the CSNET class (Obsolete - used only for examples in some obsolete RFCs) */ +#define DNS_RRCLASS_CH 3 /* the CHAOS class */ +#define DNS_RRCLASS_HS 4 /* Hesiod [Dyer 87] */ +#define DNS_RRCLASS_FLUSH 0x800 /* Flush bit */ + +/* The size used for the next line is rather a hack, but it prevents including socket.h in all files + that include memp.h, and that would possibly break portability (since socket.h defines some types + and constants possibly already define by the OS). + Calculation rule: + sizeof(struct addrinfo) + sizeof(struct sockaddr_in) + DNS_MAX_NAME_LENGTH + 1 byte zero-termination */ +#define NETDB_ELEM_SIZE (32 + 16 + DNS_MAX_NAME_LENGTH + 1) + +#if DNS_LOCAL_HOSTLIST +/** struct used for local host-list */ +struct local_hostlist_entry { + /** static hostname */ + const char *name; + /** static host address in network byteorder */ + ip_addr_t addr; + struct local_hostlist_entry *next; +}; +#if DNS_LOCAL_HOSTLIST_IS_DYNAMIC +#ifndef DNS_LOCAL_HOSTLIST_MAX_NAMELEN +#define DNS_LOCAL_HOSTLIST_MAX_NAMELEN DNS_MAX_NAME_LENGTH +#endif +#define LOCALHOSTLIST_ELEM_SIZE ((sizeof(struct local_hostlist_entry) + DNS_LOCAL_HOSTLIST_MAX_NAMELEN + 1)) +#endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */ +#endif /* DNS_LOCAL_HOSTLIST */ + +/** Callback which is invoked when a hostname is found. + * A function of this type must be implemented by the application using the DNS resolver. + * @param name pointer to the name that was looked up. + * @param ipaddr pointer to an ip_addr_t containing the IP address of the hostname, + * or NULL if the name could not be found (or on any other error). + * @param callback_arg a user-specified callback argument passed to dns_gethostbyname +*/ +typedef void (*dns_found_callback)(const char *name, ip_addr_t *ipaddr, void *callback_arg); + +void dns_init(void); +void dns_tmr(void); +void dns_setserver(u8_t numdns, ip_addr_t *dnsserver); +ip_addr_t dns_getserver(u8_t numdns); +err_t dns_gethostbyname(const char *hostname, ip_addr_t *addr, + dns_found_callback found, void *callback_arg); + +#if DNS_LOCAL_HOSTLIST && DNS_LOCAL_HOSTLIST_IS_DYNAMIC +int dns_local_removehost(const char *hostname, const ip_addr_t *addr); +err_t dns_local_addhost(const char *hostname, const ip_addr_t *addr); +#endif /* DNS_LOCAL_HOSTLIST && DNS_LOCAL_HOSTLIST_IS_DYNAMIC */ + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_DNS */ + +#endif /* __LWIP_DNS_H__ */ diff --git a/features/unsupported/net/lwip/lwip/include/lwip/err.h b/features/unsupported/net/lwip/lwip/include/lwip/err.h new file mode 100644 index 00000000000..ac907729fcd --- /dev/null +++ b/features/unsupported/net/lwip/lwip/include/lwip/err.h @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef __LWIP_ERR_H__ +#define __LWIP_ERR_H__ + +#include "lwip/opt.h" +#include "lwip/arch.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** Define LWIP_ERR_T in cc.h if you want to use + * a different type for your platform (must be signed). */ +#ifdef LWIP_ERR_T +typedef LWIP_ERR_T err_t; +#else /* LWIP_ERR_T */ +typedef s8_t err_t; +#endif /* LWIP_ERR_T*/ + +/* Definitions for error constants. */ + +#define ERR_OK 0 /* No error, everything OK. */ +#define ERR_MEM -1 /* Out of memory error. */ +#define ERR_BUF -2 /* Buffer error. */ +#define ERR_TIMEOUT -3 /* Timeout. */ +#define ERR_RTE -4 /* Routing problem. */ +#define ERR_INPROGRESS -5 /* Operation in progress */ +#define ERR_VAL -6 /* Illegal value. */ +#define ERR_WOULDBLOCK -7 /* Operation would block. */ +#define ERR_USE -8 /* Address in use. */ +#define ERR_ISCONN -9 /* Already connected. */ + +#define ERR_IS_FATAL(e) ((e) < ERR_ISCONN) + +#define ERR_ABRT -10 /* Connection aborted. */ +#define ERR_RST -11 /* Connection reset. */ +#define ERR_CLSD -12 /* Connection closed. */ +#define ERR_CONN -13 /* Not connected. */ + +#define ERR_ARG -14 /* Illegal argument. */ + +#define ERR_IF -15 /* Low-level netif error */ + + +#ifdef LWIP_DEBUG +extern const char *lwip_strerr(err_t err); +#else +#define lwip_strerr(x) "" +#endif /* LWIP_DEBUG */ + +#ifdef __cplusplus +} +#endif + +#endif /* __LWIP_ERR_H__ */ diff --git a/features/unsupported/net/lwip/lwip/include/lwip/init.h b/features/unsupported/net/lwip/lwip/include/lwip/init.h new file mode 100644 index 00000000000..77dcdfc7757 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/include/lwip/init.h @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef __LWIP_INIT_H__ +#define __LWIP_INIT_H__ + +#include "lwip/opt.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** X.x.x: Major version of the stack */ +#define LWIP_VERSION_MAJOR 1U +/** x.X.x: Minor version of the stack */ +#define LWIP_VERSION_MINOR 4U +/** x.x.X: Revision of the stack */ +#define LWIP_VERSION_REVISION 0U +/** For release candidates, this is set to 1..254 + * For official releases, this is set to 255 (LWIP_RC_RELEASE) + * For development versions (CVS), this is set to 0 (LWIP_RC_DEVELOPMENT) */ +#define LWIP_VERSION_RC 255U + +/** LWIP_VERSION_RC is set to LWIP_RC_RELEASE for official releases */ +#define LWIP_RC_RELEASE 255U +/** LWIP_VERSION_RC is set to LWIP_RC_DEVELOPMENT for CVS versions */ +#define LWIP_RC_DEVELOPMENT 0U + +#define LWIP_VERSION_IS_RELEASE (LWIP_VERSION_RC == LWIP_RC_RELEASE) +#define LWIP_VERSION_IS_DEVELOPMENT (LWIP_VERSION_RC == LWIP_RC_DEVELOPMENT) +#define LWIP_VERSION_IS_RC ((LWIP_VERSION_RC != LWIP_RC_RELEASE) && (LWIP_VERSION_RC != LWIP_RC_DEVELOPMENT)) + +/** Provides the version of the stack */ +#define LWIP_VERSION (LWIP_VERSION_MAJOR << 24 | LWIP_VERSION_MINOR << 16 | \ + LWIP_VERSION_REVISION << 8 | LWIP_VERSION_RC) + +/* Modules initialization */ +void lwip_init(void); + +#ifdef __cplusplus +} +#endif + +#endif /* __LWIP_INIT_H__ */ diff --git a/features/unsupported/net/lwip/lwip/include/lwip/mem.h b/features/unsupported/net/lwip/lwip/include/lwip/mem.h new file mode 100644 index 00000000000..f4b2f7c010b --- /dev/null +++ b/features/unsupported/net/lwip/lwip/include/lwip/mem.h @@ -0,0 +1,123 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef __LWIP_MEM_H__ +#define __LWIP_MEM_H__ + +#include "lwip/opt.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#if MEM_LIBC_MALLOC + +#include /* for size_t */ + +typedef size_t mem_size_t; + +/* aliases for C library malloc() */ +#define mem_init() +/* in case C library malloc() needs extra protection, + * allow these defines to be overridden. + */ +#ifndef mem_free +#define mem_free free +#endif +#ifndef mem_malloc +#define mem_malloc malloc +#endif +#ifndef mem_calloc +#define mem_calloc calloc +#endif +/* Since there is no C library allocation function to shrink memory without + moving it, define this to nothing. */ +#ifndef mem_trim +#define mem_trim(mem, size) (mem) +#endif +#else /* MEM_LIBC_MALLOC */ + +/* MEM_SIZE would have to be aligned, but using 64000 here instead of + * 65535 leaves some room for alignment... + */ +#if MEM_SIZE > 64000L +typedef u32_t mem_size_t; +#define MEM_SIZE_F U32_F +#else +typedef u16_t mem_size_t; +#define MEM_SIZE_F U16_F +#endif /* MEM_SIZE > 64000 */ + +#if MEM_USE_POOLS +/** mem_init is not used when using pools instead of a heap */ +#define mem_init() +/** mem_trim is not used when using pools instead of a heap: + we can't free part of a pool element and don't want to copy the rest */ +#define mem_trim(mem, size) (mem) +#else /* MEM_USE_POOLS */ +/* lwIP alternative malloc */ +void mem_init(void); +void *mem_trim(void *mem, mem_size_t size); +#endif /* MEM_USE_POOLS */ +void *mem_malloc(mem_size_t size); +void *mem_calloc(mem_size_t count, mem_size_t size); +void mem_free(void *mem); +#endif /* MEM_LIBC_MALLOC */ + +/** Calculate memory size for an aligned buffer - returns the next highest + * multiple of MEM_ALIGNMENT (e.g. LWIP_MEM_ALIGN_SIZE(3) and + * LWIP_MEM_ALIGN_SIZE(4) will both yield 4 for MEM_ALIGNMENT == 4). + */ +#ifndef LWIP_MEM_ALIGN_SIZE +#define LWIP_MEM_ALIGN_SIZE(size) (((size) + MEM_ALIGNMENT - 1) & ~(MEM_ALIGNMENT-1)) +#endif + +/** Calculate safe memory size for an aligned buffer when using an unaligned + * type as storage. This includes a safety-margin on (MEM_ALIGNMENT - 1) at the + * start (e.g. if buffer is u8_t[] and actual data will be u32_t*) + */ +#ifndef LWIP_MEM_ALIGN_BUFFER +#define LWIP_MEM_ALIGN_BUFFER(size) (((size) + MEM_ALIGNMENT - 1)) +#endif + +/** Align a memory pointer to the alignment defined by MEM_ALIGNMENT + * so that ADDR % MEM_ALIGNMENT == 0 + */ +#ifndef LWIP_MEM_ALIGN +#define LWIP_MEM_ALIGN(addr) ((void *)(((mem_ptr_t)(addr) + MEM_ALIGNMENT - 1) & ~(mem_ptr_t)(MEM_ALIGNMENT-1))) +#endif + + +#ifdef __cplusplus +} +#endif + +#endif /* __LWIP_MEM_H__ */ diff --git a/features/unsupported/net/lwip/lwip/include/lwip/memp.h b/features/unsupported/net/lwip/lwip/include/lwip/memp.h new file mode 100644 index 00000000000..f0d07399434 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/include/lwip/memp.h @@ -0,0 +1,116 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ + +#ifndef __LWIP_MEMP_H__ +#define __LWIP_MEMP_H__ + +#include "lwip/opt.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* Create the list of all memory pools managed by memp. MEMP_MAX represents a NULL pool at the end */ +typedef enum { +#define LWIP_MEMPOOL(name,num,size,desc) MEMP_##name, +#include "lwip/memp_std.h" + MEMP_MAX +} memp_t; + +#if MEM_USE_POOLS +/* Use a helper type to get the start and end of the user "memory pools" for mem_malloc */ +typedef enum { + /* Get the first (via: + MEMP_POOL_HELPER_START = ((u8_t) 1*MEMP_POOL_A + 0*MEMP_POOL_B + 0*MEMP_POOL_C + 0)*/ + MEMP_POOL_HELPER_FIRST = ((u8_t) +#define LWIP_MEMPOOL(name,num,size,desc) +#define LWIP_MALLOC_MEMPOOL_START 1 +#define LWIP_MALLOC_MEMPOOL(num, size) * MEMP_POOL_##size + 0 +#define LWIP_MALLOC_MEMPOOL_END +#include "lwip/memp_std.h" + ) , + /* Get the last (via: + MEMP_POOL_HELPER_END = ((u8_t) 0 + MEMP_POOL_A*0 + MEMP_POOL_B*0 + MEMP_POOL_C*1) */ + MEMP_POOL_HELPER_LAST = ((u8_t) +#define LWIP_MEMPOOL(name,num,size,desc) +#define LWIP_MALLOC_MEMPOOL_START +#define LWIP_MALLOC_MEMPOOL(num, size) 0 + MEMP_POOL_##size * +#define LWIP_MALLOC_MEMPOOL_END 1 +#include "lwip/memp_std.h" + ) +} memp_pool_helper_t; + +/* The actual start and stop values are here (cast them over) + We use this helper type and these defines so we can avoid using const memp_t values */ +#define MEMP_POOL_FIRST ((memp_t) MEMP_POOL_HELPER_FIRST) +#define MEMP_POOL_LAST ((memp_t) MEMP_POOL_HELPER_LAST) +#endif /* MEM_USE_POOLS */ + +#if MEMP_MEM_MALLOC || MEM_USE_POOLS +extern const u16_t memp_sizes[MEMP_MAX]; +#endif /* MEMP_MEM_MALLOC || MEM_USE_POOLS */ + +#if MEMP_MEM_MALLOC + +#include "mem.h" + +#define memp_init() +#define memp_malloc(type) mem_malloc(memp_sizes[type]) +#define memp_free(type, mem) mem_free(mem) + +#else /* MEMP_MEM_MALLOC */ + +#if MEM_USE_POOLS +/** This structure is used to save the pool one element came from. */ +struct memp_malloc_helper +{ + memp_t poolnr; +}; +#endif /* MEM_USE_POOLS */ + +void memp_init(void); + +#if MEMP_OVERFLOW_CHECK +void *memp_malloc_fn(memp_t type, const char* file, const int line); +#define memp_malloc(t) memp_malloc_fn((t), __FILE__, __LINE__) +#else +void *memp_malloc(memp_t type); +#endif +void memp_free(memp_t type, void *mem); + +#endif /* MEMP_MEM_MALLOC */ + +#ifdef __cplusplus +} +#endif + +#endif /* __LWIP_MEMP_H__ */ diff --git a/features/unsupported/net/lwip/lwip/include/lwip/memp_std.h b/features/unsupported/net/lwip/lwip/include/lwip/memp_std.h new file mode 100644 index 00000000000..6ce408fb02a --- /dev/null +++ b/features/unsupported/net/lwip/lwip/include/lwip/memp_std.h @@ -0,0 +1,122 @@ +/* + * SETUP: Make sure we define everything we will need. + * + * We have create three types of pools: + * 1) MEMPOOL - standard pools + * 2) MALLOC_MEMPOOL - to be used by mem_malloc in mem.c + * 3) PBUF_MEMPOOL - a mempool of pbuf's, so include space for the pbuf struct + * + * If the include'r doesn't require any special treatment of each of the types + * above, then will declare #2 & #3 to be just standard mempools. + */ +#ifndef LWIP_MALLOC_MEMPOOL +/* This treats "malloc pools" just like any other pool. + The pools are a little bigger to provide 'size' as the amount of user data. */ +#define LWIP_MALLOC_MEMPOOL(num, size) LWIP_MEMPOOL(POOL_##size, num, (size + sizeof(struct memp_malloc_helper)), "MALLOC_"#size) +#define LWIP_MALLOC_MEMPOOL_START +#define LWIP_MALLOC_MEMPOOL_END +#endif /* LWIP_MALLOC_MEMPOOL */ + +#ifndef LWIP_PBUF_MEMPOOL +/* This treats "pbuf pools" just like any other pool. + * Allocates buffers for a pbuf struct AND a payload size */ +#define LWIP_PBUF_MEMPOOL(name, num, payload, desc) LWIP_MEMPOOL(name, num, (MEMP_ALIGN_SIZE(sizeof(struct pbuf)) + MEMP_ALIGN_SIZE(payload)), desc) +#endif /* LWIP_PBUF_MEMPOOL */ + + +/* + * A list of internal pools used by LWIP. + * + * LWIP_MEMPOOL(pool_name, number_elements, element_size, pool_description) + * creates a pool name MEMP_pool_name. description is used in stats.c + */ +#if LWIP_RAW +LWIP_MEMPOOL(RAW_PCB, MEMP_NUM_RAW_PCB, sizeof(struct raw_pcb), "RAW_PCB") +#endif /* LWIP_RAW */ + +#if LWIP_UDP +LWIP_MEMPOOL(UDP_PCB, MEMP_NUM_UDP_PCB, sizeof(struct udp_pcb), "UDP_PCB") +#endif /* LWIP_UDP */ + +#if LWIP_TCP +LWIP_MEMPOOL(TCP_PCB, MEMP_NUM_TCP_PCB, sizeof(struct tcp_pcb), "TCP_PCB") +LWIP_MEMPOOL(TCP_PCB_LISTEN, MEMP_NUM_TCP_PCB_LISTEN, sizeof(struct tcp_pcb_listen), "TCP_PCB_LISTEN") +LWIP_MEMPOOL(TCP_SEG, MEMP_NUM_TCP_SEG, sizeof(struct tcp_seg), "TCP_SEG") +#endif /* LWIP_TCP */ + +#if IP_REASSEMBLY +LWIP_MEMPOOL(REASSDATA, MEMP_NUM_REASSDATA, sizeof(struct ip_reassdata), "REASSDATA") +#endif /* IP_REASSEMBLY */ +#if IP_FRAG && !IP_FRAG_USES_STATIC_BUF && !LWIP_NETIF_TX_SINGLE_PBUF +LWIP_MEMPOOL(FRAG_PBUF, MEMP_NUM_FRAG_PBUF, sizeof(struct pbuf_custom_ref),"FRAG_PBUF") +#endif /* IP_FRAG && !IP_FRAG_USES_STATIC_BUF && !LWIP_NETIF_TX_SINGLE_PBUF */ + +#if LWIP_NETCONN +LWIP_MEMPOOL(NETBUF, MEMP_NUM_NETBUF, sizeof(struct netbuf), "NETBUF") +LWIP_MEMPOOL(NETCONN, MEMP_NUM_NETCONN, sizeof(struct netconn), "NETCONN") +#endif /* LWIP_NETCONN */ + +#if NO_SYS==0 +LWIP_MEMPOOL(TCPIP_MSG_API, MEMP_NUM_TCPIP_MSG_API, sizeof(struct tcpip_msg), "TCPIP_MSG_API") +#if !LWIP_TCPIP_CORE_LOCKING_INPUT +LWIP_MEMPOOL(TCPIP_MSG_INPKT,MEMP_NUM_TCPIP_MSG_INPKT, sizeof(struct tcpip_msg), "TCPIP_MSG_INPKT") +#endif /* !LWIP_TCPIP_CORE_LOCKING_INPUT */ +#endif /* NO_SYS==0 */ + +#if ARP_QUEUEING +LWIP_MEMPOOL(ARP_QUEUE, MEMP_NUM_ARP_QUEUE, sizeof(struct etharp_q_entry), "ARP_QUEUE") +#endif /* ARP_QUEUEING */ + +#if LWIP_IGMP +LWIP_MEMPOOL(IGMP_GROUP, MEMP_NUM_IGMP_GROUP, sizeof(struct igmp_group), "IGMP_GROUP") +#endif /* LWIP_IGMP */ + +#if (!NO_SYS || (NO_SYS && !NO_SYS_NO_TIMERS)) /* LWIP_TIMERS */ +LWIP_MEMPOOL(SYS_TIMEOUT, MEMP_NUM_SYS_TIMEOUT, sizeof(struct sys_timeo), "SYS_TIMEOUT") +#endif /* LWIP_TIMERS */ + +#if LWIP_SNMP +LWIP_MEMPOOL(SNMP_ROOTNODE, MEMP_NUM_SNMP_ROOTNODE, sizeof(struct mib_list_rootnode), "SNMP_ROOTNODE") +LWIP_MEMPOOL(SNMP_NODE, MEMP_NUM_SNMP_NODE, sizeof(struct mib_list_node), "SNMP_NODE") +LWIP_MEMPOOL(SNMP_VARBIND, MEMP_NUM_SNMP_VARBIND, sizeof(struct snmp_varbind), "SNMP_VARBIND") +LWIP_MEMPOOL(SNMP_VALUE, MEMP_NUM_SNMP_VALUE, SNMP_MAX_VALUE_SIZE, "SNMP_VALUE") +#endif /* LWIP_SNMP */ +#if LWIP_DNS && LWIP_SOCKET +LWIP_MEMPOOL(NETDB, MEMP_NUM_NETDB, NETDB_ELEM_SIZE, "NETDB") +#endif /* LWIP_DNS && LWIP_SOCKET */ +#if LWIP_DNS && DNS_LOCAL_HOSTLIST && DNS_LOCAL_HOSTLIST_IS_DYNAMIC +LWIP_MEMPOOL(LOCALHOSTLIST, MEMP_NUM_LOCALHOSTLIST, LOCALHOSTLIST_ELEM_SIZE, "LOCALHOSTLIST") +#endif /* LWIP_DNS && DNS_LOCAL_HOSTLIST && DNS_LOCAL_HOSTLIST_IS_DYNAMIC */ +#if PPP_SUPPORT && PPPOE_SUPPORT +LWIP_MEMPOOL(PPPOE_IF, MEMP_NUM_PPPOE_INTERFACES, sizeof(struct pppoe_softc), "PPPOE_IF") +#endif /* PPP_SUPPORT && PPPOE_SUPPORT */ + +/* + * A list of pools of pbuf's used by LWIP. + * + * LWIP_PBUF_MEMPOOL(pool_name, number_elements, pbuf_payload_size, pool_description) + * creates a pool name MEMP_pool_name. description is used in stats.c + * This allocates enough space for the pbuf struct and a payload. + * (Example: pbuf_payload_size=0 allocates only size for the struct) + */ +LWIP_PBUF_MEMPOOL(PBUF, MEMP_NUM_PBUF, 0, "PBUF_REF/ROM") +LWIP_PBUF_MEMPOOL(PBUF_POOL, PBUF_POOL_SIZE, PBUF_POOL_BUFSIZE, "PBUF_POOL") + + +/* + * Allow for user-defined pools; this must be explicitly set in lwipopts.h + * since the default is to NOT look for lwippools.h + */ +#if MEMP_USE_CUSTOM_POOLS +#include "lwippools.h" +#endif /* MEMP_USE_CUSTOM_POOLS */ + +/* + * REQUIRED CLEANUP: Clear up so we don't get "multiply defined" error later + * (#undef is ignored for something that is not defined) + */ +#undef LWIP_MEMPOOL +#undef LWIP_MALLOC_MEMPOOL +#undef LWIP_MALLOC_MEMPOOL_START +#undef LWIP_MALLOC_MEMPOOL_END +#undef LWIP_PBUF_MEMPOOL diff --git a/features/unsupported/net/lwip/lwip/include/lwip/netbuf.h b/features/unsupported/net/lwip/lwip/include/lwip/netbuf.h new file mode 100644 index 00000000000..7d247d71b60 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/include/lwip/netbuf.h @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef __LWIP_NETBUF_H__ +#define __LWIP_NETBUF_H__ + +#include "lwip/opt.h" +#include "lwip/pbuf.h" +#include "lwip/ip_addr.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** This netbuf has dest-addr/port set */ +#define NETBUF_FLAG_DESTADDR 0x01 +/** This netbuf includes a checksum */ +#define NETBUF_FLAG_CHKSUM 0x02 + +struct netbuf { + struct pbuf *p, *ptr; + ip_addr_t addr; + u16_t port; +#if LWIP_NETBUF_RECVINFO || LWIP_CHECKSUM_ON_COPY +#if LWIP_CHECKSUM_ON_COPY + u8_t flags; +#endif /* LWIP_CHECKSUM_ON_COPY */ + u16_t toport_chksum; +#if LWIP_NETBUF_RECVINFO + ip_addr_t toaddr; +#endif /* LWIP_NETBUF_RECVINFO */ +#endif /* LWIP_NETBUF_RECVINFO || LWIP_CHECKSUM_ON_COPY */ +}; + +/* Network buffer functions: */ +struct netbuf * netbuf_new (void); +void netbuf_delete (struct netbuf *buf); +void * netbuf_alloc (struct netbuf *buf, u16_t size); +void netbuf_free (struct netbuf *buf); +err_t netbuf_ref (struct netbuf *buf, + const void *dataptr, u16_t size); +void netbuf_chain (struct netbuf *head, + struct netbuf *tail); + +err_t netbuf_data (struct netbuf *buf, + void **dataptr, u16_t *len); +s8_t netbuf_next (struct netbuf *buf); +void netbuf_first (struct netbuf *buf); + + +#define netbuf_copy_partial(buf, dataptr, len, offset) \ + pbuf_copy_partial((buf)->p, (dataptr), (len), (offset)) +#define netbuf_copy(buf,dataptr,len) netbuf_copy_partial(buf, dataptr, len, 0) +#define netbuf_take(buf, dataptr, len) pbuf_take((buf)->p, dataptr, len) +#define netbuf_len(buf) ((buf)->p->tot_len) +#define netbuf_fromaddr(buf) (&((buf)->addr)) +#define netbuf_set_fromaddr(buf, fromaddr) ip_addr_set((&(buf)->addr), fromaddr) +#define netbuf_fromport(buf) ((buf)->port) +#if LWIP_NETBUF_RECVINFO +#define netbuf_destaddr(buf) (&((buf)->toaddr)) +#define netbuf_set_destaddr(buf, destaddr) ip_addr_set((&(buf)->addr), destaddr) +#define netbuf_destport(buf) (((buf)->flags & NETBUF_FLAG_DESTADDR) ? (buf)->toport_chksum : 0) +#endif /* LWIP_NETBUF_RECVINFO */ +#if LWIP_CHECKSUM_ON_COPY +#define netbuf_set_chksum(buf, chksum) do { (buf)->flags = NETBUF_FLAG_CHKSUM; \ + (buf)->toport_chksum = chksum; } while(0) +#endif /* LWIP_CHECKSUM_ON_COPY */ + +#ifdef __cplusplus +} +#endif + +#endif /* __LWIP_NETBUF_H__ */ diff --git a/features/unsupported/net/lwip/lwip/include/lwip/netdb.h b/features/unsupported/net/lwip/lwip/include/lwip/netdb.h new file mode 100644 index 00000000000..7587e2f2d16 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/include/lwip/netdb.h @@ -0,0 +1,124 @@ +/* + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Simon Goldschmidt + * + */ +#ifndef __LWIP_NETDB_H__ +#define __LWIP_NETDB_H__ + +#include "lwip/opt.h" + +#if LWIP_DNS && LWIP_SOCKET + +#include /* for size_t */ + +#include "lwip/inet.h" +#include "lwip/sockets.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* some rarely used options */ +#ifndef LWIP_DNS_API_DECLARE_H_ERRNO +#define LWIP_DNS_API_DECLARE_H_ERRNO 1 +#endif + +#ifndef LWIP_DNS_API_DEFINE_ERRORS +#define LWIP_DNS_API_DEFINE_ERRORS 1 +#endif + +#ifndef LWIP_DNS_API_DECLARE_STRUCTS +#define LWIP_DNS_API_DECLARE_STRUCTS 1 +#endif + +#if LWIP_DNS_API_DEFINE_ERRORS +/** Errors used by the DNS API functions, h_errno can be one of them */ +#define EAI_NONAME 200 +#define EAI_SERVICE 201 +#define EAI_FAIL 202 +#define EAI_MEMORY 203 + +#define HOST_NOT_FOUND 210 +#define NO_DATA 211 +#define NO_RECOVERY 212 +#define TRY_AGAIN 213 +#endif /* LWIP_DNS_API_DEFINE_ERRORS */ + +#if LWIP_DNS_API_DECLARE_STRUCTS +struct hostent { + char *h_name; /* Official name of the host. */ + char **h_aliases; /* A pointer to an array of pointers to alternative host names, + terminated by a null pointer. */ + int h_addrtype; /* Address type. */ + int h_length; /* The length, in bytes, of the address. */ + char **h_addr_list; /* A pointer to an array of pointers to network addresses (in + network byte order) for the host, terminated by a null pointer. */ +#define h_addr h_addr_list[0] /* for backward compatibility */ +}; + +struct addrinfo { + int ai_flags; /* Input flags. */ + int ai_family; /* Address family of socket. */ + int ai_socktype; /* Socket type. */ + int ai_protocol; /* Protocol of socket. */ + socklen_t ai_addrlen; /* Length of socket address. */ + struct sockaddr *ai_addr; /* Socket address of socket. */ + char *ai_canonname; /* Canonical name of service location. */ + struct addrinfo *ai_next; /* Pointer to next in list. */ +}; +#endif /* LWIP_DNS_API_DECLARE_STRUCTS */ + +#if LWIP_DNS_API_DECLARE_H_ERRNO +/* application accessable error code set by the DNS API functions */ +extern int h_errno; +#endif /* LWIP_DNS_API_DECLARE_H_ERRNO*/ + +struct hostent *lwip_gethostbyname(const char *name); +int lwip_gethostbyname_r(const char *name, struct hostent *ret, char *buf, + size_t buflen, struct hostent **result, int *h_errnop); +void lwip_freeaddrinfo(struct addrinfo *ai); +int lwip_getaddrinfo(const char *nodename, + const char *servname, + const struct addrinfo *hints, + struct addrinfo **res); + +#if LWIP_COMPAT_SOCKETS +#define gethostbyname(name) lwip_gethostbyname(name) +#define gethostbyname_r(name, ret, buf, buflen, result, h_errnop) \ + lwip_gethostbyname_r(name, ret, buf, buflen, result, h_errnop) +#define freeaddrinfo(addrinfo) lwip_freeaddrinfo(addrinfo) +#define getaddrinfo(nodname, servname, hints, res) \ + lwip_getaddrinfo(nodname, servname, hints, res) +#endif /* LWIP_COMPAT_SOCKETS */ + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_DNS && LWIP_SOCKET */ + +#endif /* __LWIP_NETDB_H__ */ diff --git a/features/unsupported/net/lwip/lwip/include/lwip/netif.h b/features/unsupported/net/lwip/lwip/include/lwip/netif.h new file mode 100644 index 00000000000..a8790b5f6a5 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/include/lwip/netif.h @@ -0,0 +1,315 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef __LWIP_NETIF_H__ +#define __LWIP_NETIF_H__ + +#include "lwip/opt.h" + +#define ENABLE_LOOPBACK (LWIP_NETIF_LOOPBACK || LWIP_HAVE_LOOPIF) + +#include "lwip/err.h" + +#include "lwip/ip_addr.h" + +#include "lwip/def.h" +#include "lwip/pbuf.h" +#if LWIP_DHCP +struct dhcp; +#endif +#if LWIP_AUTOIP +struct autoip; +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/* Throughout this file, IP addresses are expected to be in + * the same byte order as in IP_PCB. */ + +/** must be the maximum of all used hardware address lengths + across all types of interfaces in use */ +#define NETIF_MAX_HWADDR_LEN 6U + +/** Whether the network interface is 'up'. This is + * a software flag used to control whether this network + * interface is enabled and processes traffic. + * It is set by the startup code (for static IP configuration) or + * by dhcp/autoip when an address has been assigned. + */ +#define NETIF_FLAG_UP 0x01U +/** If set, the netif has broadcast capability. + * Set by the netif driver in its init function. */ +#define NETIF_FLAG_BROADCAST 0x02U +/** If set, the netif is one end of a point-to-point connection. + * Set by the netif driver in its init function. */ +#define NETIF_FLAG_POINTTOPOINT 0x04U +/** If set, the interface is configured using DHCP. + * Set by the DHCP code when starting or stopping DHCP. */ +#define NETIF_FLAG_DHCP 0x08U +/** If set, the interface has an active link + * (set by the network interface driver). + * Either set by the netif driver in its init function (if the link + * is up at that time) or at a later point once the link comes up + * (if link detection is supported by the hardware). */ +#define NETIF_FLAG_LINK_UP 0x10U +/** If set, the netif is an ethernet device using ARP. + * Set by the netif driver in its init function. + * Used to check input packet types and use of DHCP. */ +#define NETIF_FLAG_ETHARP 0x20U +/** If set, the netif is an ethernet device. It might not use + * ARP or TCP/IP if it is used for PPPoE only. + */ +#define NETIF_FLAG_ETHERNET 0x40U +/** If set, the netif has IGMP capability. + * Set by the netif driver in its init function. */ +#define NETIF_FLAG_IGMP 0x80U + +/** Function prototype for netif init functions. Set up flags and output/linkoutput + * callback functions in this function. + * + * @param netif The netif to initialize + */ +typedef err_t (*netif_init_fn)(struct netif *netif); +/** Function prototype for netif->input functions. This function is saved as 'input' + * callback function in the netif struct. Call it when a packet has been received. + * + * @param p The received packet, copied into a pbuf + * @param inp The netif which received the packet + */ +typedef err_t (*netif_input_fn)(struct pbuf *p, struct netif *inp); +/** Function prototype for netif->output functions. Called by lwIP when a packet + * shall be sent. For ethernet netif, set this to 'etharp_output' and set + * 'linkoutput'. + * + * @param netif The netif which shall send a packet + * @param p The packet to send (p->payload points to IP header) + * @param ipaddr The IP address to which the packet shall be sent + */ +typedef err_t (*netif_output_fn)(struct netif *netif, struct pbuf *p, + ip_addr_t *ipaddr); +/** Function prototype for netif->linkoutput functions. Only used for ethernet + * netifs. This function is called by ARP when a packet shall be sent. + * + * @param netif The netif which shall send a packet + * @param p The packet to send (raw ethernet packet) + */ +typedef err_t (*netif_linkoutput_fn)(struct netif *netif, struct pbuf *p); +/** Function prototype for netif status- or link-callback functions. */ +typedef void (*netif_status_callback_fn)(struct netif *netif); +/** Function prototype for netif igmp_mac_filter functions */ +typedef err_t (*netif_igmp_mac_filter_fn)(struct netif *netif, + ip_addr_t *group, u8_t action); + +/** Generic data structure used for all lwIP network interfaces. + * The following fields should be filled in by the initialization + * function for the device driver: hwaddr_len, hwaddr[], mtu, flags */ +struct netif { + /** pointer to next in linked list */ + struct netif *next; + + /** IP address configuration in network byte order */ + ip_addr_t ip_addr; + ip_addr_t netmask; + ip_addr_t gw; + + /** This function is called by the network device driver + * to pass a packet up the TCP/IP stack. */ + netif_input_fn input; + /** This function is called by the IP module when it wants + * to send a packet on the interface. This function typically + * first resolves the hardware address, then sends the packet. */ + netif_output_fn output; + /** This function is called by the ARP module when it wants + * to send a packet on the interface. This function outputs + * the pbuf as-is on the link medium. */ + netif_linkoutput_fn linkoutput; +#if LWIP_NETIF_STATUS_CALLBACK + /** This function is called when the netif state is set to up or down + */ + netif_status_callback_fn status_callback; +#endif /* LWIP_NETIF_STATUS_CALLBACK */ +#if LWIP_NETIF_LINK_CALLBACK + /** This function is called when the netif link is set to up or down + */ + netif_status_callback_fn link_callback; +#endif /* LWIP_NETIF_LINK_CALLBACK */ + /** This field can be set by the device driver and could point + * to state information for the device. */ + void *state; +#if LWIP_DHCP + /** the DHCP client state information for this netif */ + struct dhcp *dhcp; +#endif /* LWIP_DHCP */ +#if LWIP_AUTOIP + /** the AutoIP client state information for this netif */ + struct autoip *autoip; +#endif +#if LWIP_NETIF_HOSTNAME + /* the hostname for this netif, NULL is a valid value */ + char* hostname; +#endif /* LWIP_NETIF_HOSTNAME */ + /** maximum transfer unit (in bytes) */ + u16_t mtu; + /** number of bytes used in hwaddr */ + u8_t hwaddr_len; + /** link level hardware address of this interface */ + u8_t hwaddr[NETIF_MAX_HWADDR_LEN]; + /** flags (see NETIF_FLAG_ above) */ + u8_t flags; + /** descriptive abbreviation */ + char name[2]; + /** number of this interface */ + u8_t num; +#if LWIP_SNMP + /** link type (from "snmp_ifType" enum from snmp.h) */ + u8_t link_type; + /** (estimate) link speed */ + u32_t link_speed; + /** timestamp at last change made (up/down) */ + u32_t ts; + /** counters */ + u32_t ifinoctets; + u32_t ifinucastpkts; + u32_t ifinnucastpkts; + u32_t ifindiscards; + u32_t ifoutoctets; + u32_t ifoutucastpkts; + u32_t ifoutnucastpkts; + u32_t ifoutdiscards; +#endif /* LWIP_SNMP */ +#if LWIP_IGMP + /** This function could be called to add or delete a entry in the multicast + filter table of the ethernet MAC.*/ + netif_igmp_mac_filter_fn igmp_mac_filter; +#endif /* LWIP_IGMP */ +#if LWIP_NETIF_HWADDRHINT + u8_t *addr_hint; +#endif /* LWIP_NETIF_HWADDRHINT */ +#if ENABLE_LOOPBACK + /* List of packets to be queued for ourselves. */ + struct pbuf *loop_first; + struct pbuf *loop_last; +#if LWIP_LOOPBACK_MAX_PBUFS + u16_t loop_cnt_current; +#endif /* LWIP_LOOPBACK_MAX_PBUFS */ +#endif /* ENABLE_LOOPBACK */ +}; + +#if LWIP_SNMP +#define NETIF_INIT_SNMP(netif, type, speed) \ + /* use "snmp_ifType" enum from snmp.h for "type", snmp_ifType_ethernet_csmacd by example */ \ + (netif)->link_type = (type); \ + /* your link speed here (units: bits per second) */ \ + (netif)->link_speed = (speed); \ + (netif)->ts = 0; \ + (netif)->ifinoctets = 0; \ + (netif)->ifinucastpkts = 0; \ + (netif)->ifinnucastpkts = 0; \ + (netif)->ifindiscards = 0; \ + (netif)->ifoutoctets = 0; \ + (netif)->ifoutucastpkts = 0; \ + (netif)->ifoutnucastpkts = 0; \ + (netif)->ifoutdiscards = 0 +#else /* LWIP_SNMP */ +#define NETIF_INIT_SNMP(netif, type, speed) +#endif /* LWIP_SNMP */ + + +/** The list of network interfaces. */ +extern struct netif *netif_list; +/** The default network interface. */ +extern struct netif *netif_default; + +void netif_init(void); + +struct netif *netif_add(struct netif *netif, ip_addr_t *ipaddr, ip_addr_t *netmask, + ip_addr_t *gw, void *state, netif_init_fn init, netif_input_fn input); + +void +netif_set_addr(struct netif *netif, ip_addr_t *ipaddr, ip_addr_t *netmask, + ip_addr_t *gw); +void netif_remove(struct netif * netif); + +/* Returns a network interface given its name. The name is of the form + "et0", where the first two letters are the "name" field in the + netif structure, and the digit is in the num field in the same + structure. */ +struct netif *netif_find(char *name); + +void netif_set_default(struct netif *netif); + +void netif_set_ipaddr(struct netif *netif, ip_addr_t *ipaddr); +void netif_set_netmask(struct netif *netif, ip_addr_t *netmask); +void netif_set_gw(struct netif *netif, ip_addr_t *gw); + +void netif_set_up(struct netif *netif); +void netif_set_down(struct netif *netif); +/** Ask if an interface is up */ +#define netif_is_up(netif) (((netif)->flags & NETIF_FLAG_UP) ? (u8_t)1 : (u8_t)0) + +#if LWIP_NETIF_STATUS_CALLBACK +void netif_set_status_callback(struct netif *netif, netif_status_callback_fn status_callback); +#endif /* LWIP_NETIF_STATUS_CALLBACK */ + +void netif_set_link_up(struct netif *netif); +void netif_set_link_down(struct netif *netif); +/** Ask if a link is up */ +#define netif_is_link_up(netif) (((netif)->flags & NETIF_FLAG_LINK_UP) ? (u8_t)1 : (u8_t)0) + +#if LWIP_NETIF_LINK_CALLBACK +void netif_set_link_callback(struct netif *netif, netif_status_callback_fn link_callback); +#endif /* LWIP_NETIF_LINK_CALLBACK */ + +#if LWIP_NETIF_HOSTNAME +#define netif_set_hostname(netif, name) do { if((netif) != NULL) { (netif)->hostname = name; }}while(0) +#define netif_get_hostname(netif) (((netif) != NULL) ? ((netif)->hostname) : NULL) +#endif /* LWIP_NETIF_HOSTNAME */ + +#if LWIP_IGMP +#define netif_set_igmp_mac_filter(netif, function) do { if((netif) != NULL) { (netif)->igmp_mac_filter = function; }}while(0) +#define netif_get_igmp_mac_filter(netif) (((netif) != NULL) ? ((netif)->igmp_mac_filter) : NULL) +#endif /* LWIP_IGMP */ + +#if ENABLE_LOOPBACK +err_t netif_loop_output(struct netif *netif, struct pbuf *p, ip_addr_t *dest_ip); +void netif_poll(struct netif *netif); +#if !LWIP_NETIF_LOOPBACK_MULTITHREADING +void netif_poll_all(void); +#endif /* !LWIP_NETIF_LOOPBACK_MULTITHREADING */ +#endif /* ENABLE_LOOPBACK */ + +#ifdef __cplusplus +} +#endif + +#endif /* __LWIP_NETIF_H__ */ diff --git a/features/unsupported/net/lwip/lwip/include/lwip/netifapi.h b/features/unsupported/net/lwip/lwip/include/lwip/netifapi.h new file mode 100644 index 00000000000..33318efaf6c --- /dev/null +++ b/features/unsupported/net/lwip/lwip/include/lwip/netifapi.h @@ -0,0 +1,108 @@ +/* + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + */ + +#ifndef __LWIP_NETIFAPI_H__ +#define __LWIP_NETIFAPI_H__ + +#include "lwip/opt.h" + +#if LWIP_NETIF_API /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/sys.h" +#include "lwip/netif.h" +#include "lwip/dhcp.h" +#include "lwip/autoip.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef void (*netifapi_void_fn)(struct netif *netif); +typedef err_t (*netifapi_errt_fn)(struct netif *netif); + +struct netifapi_msg_msg { +#if !LWIP_TCPIP_CORE_LOCKING + sys_sem_t sem; +#endif /* !LWIP_TCPIP_CORE_LOCKING */ + err_t err; + struct netif *netif; + union { + struct { + ip_addr_t *ipaddr; + ip_addr_t *netmask; + ip_addr_t *gw; + void *state; + netif_init_fn init; + netif_input_fn input; + } add; + struct { + netifapi_void_fn voidfunc; + netifapi_errt_fn errtfunc; + } common; + } msg; +}; + +struct netifapi_msg { + void (* function)(struct netifapi_msg_msg *msg); + struct netifapi_msg_msg msg; +}; + + +/* API for application */ +err_t netifapi_netif_add ( struct netif *netif, + ip_addr_t *ipaddr, + ip_addr_t *netmask, + ip_addr_t *gw, + void *state, + netif_init_fn init, + netif_input_fn input); + +err_t netifapi_netif_set_addr ( struct netif *netif, + ip_addr_t *ipaddr, + ip_addr_t *netmask, + ip_addr_t *gw ); + +err_t netifapi_netif_common ( struct netif *netif, + netifapi_void_fn voidfunc, + netifapi_errt_fn errtfunc); + +#define netifapi_netif_remove(n) netifapi_netif_common(n, netif_remove, NULL) +#define netifapi_netif_set_up(n) netifapi_netif_common(n, netif_set_up, NULL) +#define netifapi_netif_set_down(n) netifapi_netif_common(n, netif_set_down, NULL) +#define netifapi_netif_set_default(n) netifapi_netif_common(n, netif_set_default, NULL) +#define netifapi_dhcp_start(n) netifapi_netif_common(n, NULL, dhcp_start) +#define netifapi_dhcp_stop(n) netifapi_netif_common(n, dhcp_stop, NULL) +#define netifapi_autoip_start(n) netifapi_netif_common(n, NULL, autoip_start) +#define netifapi_autoip_stop(n) netifapi_netif_common(n, NULL, autoip_stop) + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_NETIF_API */ + +#endif /* __LWIP_NETIFAPI_H__ */ diff --git a/features/unsupported/net/lwip/lwip/include/lwip/opt.h b/features/unsupported/net/lwip/lwip/include/lwip/opt.h new file mode 100644 index 00000000000..a1b876583f1 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/include/lwip/opt.h @@ -0,0 +1,2043 @@ +/** + * @file + * + * lwIP Options Configuration + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef __LWIP_OPT_H__ +#define __LWIP_OPT_H__ + +/* + * Include user defined options first. Anything not defined in these files + * will be set to standard values. Override anything you dont like! + */ +#include "lwipopts.h" +#include "lwip/debug.h" + +/* + ----------------------------------------------- + ---------- Platform specific locking ---------- + ----------------------------------------------- +*/ + +/** + * SYS_LIGHTWEIGHT_PROT==1: if you want inter-task protection for certain + * critical regions during buffer allocation, deallocation and memory + * allocation and deallocation. + */ +#ifndef SYS_LIGHTWEIGHT_PROT +#define SYS_LIGHTWEIGHT_PROT 0 +#endif + +/** + * NO_SYS==1: Provides VERY minimal functionality. Otherwise, + * use lwIP facilities. + */ +#ifndef NO_SYS +#define NO_SYS 0 +#endif + +/** + * NO_SYS_NO_TIMERS==1: Drop support for sys_timeout when NO_SYS==1 + * Mainly for compatibility to old versions. + */ +#ifndef NO_SYS_NO_TIMERS +#define NO_SYS_NO_TIMERS 0 +#endif + +/** + * MEMCPY: override this if you have a faster implementation at hand than the + * one included in your C library + */ +#ifndef MEMCPY +#define MEMCPY(dst,src,len) memcpy(dst,src,len) +#endif + +/** + * SMEMCPY: override this with care! Some compilers (e.g. gcc) can inline a + * call to memcpy() if the length is known at compile time and is small. + */ +#ifndef SMEMCPY +#define SMEMCPY(dst,src,len) memcpy(dst,src,len) +#endif + +/* + ------------------------------------ + ---------- Memory options ---------- + ------------------------------------ +*/ +/** + * MEM_LIBC_MALLOC==1: Use malloc/free/realloc provided by your C-library + * instead of the lwip internal allocator. Can save code size if you + * already use it. + */ +#ifndef MEM_LIBC_MALLOC +#define MEM_LIBC_MALLOC 0 +#endif + +/** +* MEMP_MEM_MALLOC==1: Use mem_malloc/mem_free instead of the lwip pool allocator. +* Especially useful with MEM_LIBC_MALLOC but handle with care regarding execution +* speed and usage from interrupts! +*/ +#ifndef MEMP_MEM_MALLOC +#define MEMP_MEM_MALLOC 0 +#endif + +/** + * MEM_ALIGNMENT: should be set to the alignment of the CPU + * 4 byte alignment -> #define MEM_ALIGNMENT 4 + * 2 byte alignment -> #define MEM_ALIGNMENT 2 + */ +#ifndef MEM_ALIGNMENT +#define MEM_ALIGNMENT 1 +#endif + +/** + * MEM_SIZE: the size of the heap memory. If the application will send + * a lot of data that needs to be copied, this should be set high. + */ +#ifndef MEM_SIZE +#define MEM_SIZE 1600 +#endif + +/** + * MEMP_SEPARATE_POOLS: if defined to 1, each pool is placed in its own array. + * This can be used to individually change the location of each pool. + * Default is one big array for all pools + */ +#ifndef MEMP_SEPARATE_POOLS +#define MEMP_SEPARATE_POOLS 0 +#endif + +/** + * MEMP_OVERFLOW_CHECK: memp overflow protection reserves a configurable + * amount of bytes before and after each memp element in every pool and fills + * it with a prominent default value. + * MEMP_OVERFLOW_CHECK == 0 no checking + * MEMP_OVERFLOW_CHECK == 1 checks each element when it is freed + * MEMP_OVERFLOW_CHECK >= 2 checks each element in every pool every time + * memp_malloc() or memp_free() is called (useful but slow!) + */ +#ifndef MEMP_OVERFLOW_CHECK +#define MEMP_OVERFLOW_CHECK 0 +#endif + +/** + * MEMP_SANITY_CHECK==1: run a sanity check after each memp_free() to make + * sure that there are no cycles in the linked lists. + */ +#ifndef MEMP_SANITY_CHECK +#define MEMP_SANITY_CHECK 0 +#endif + +/** + * MEM_USE_POOLS==1: Use an alternative to malloc() by allocating from a set + * of memory pools of various sizes. When mem_malloc is called, an element of + * the smallest pool that can provide the length needed is returned. + * To use this, MEMP_USE_CUSTOM_POOLS also has to be enabled. + */ +#ifndef MEM_USE_POOLS +#define MEM_USE_POOLS 0 +#endif + +/** + * MEM_USE_POOLS_TRY_BIGGER_POOL==1: if one malloc-pool is empty, try the next + * bigger pool - WARNING: THIS MIGHT WASTE MEMORY but it can make a system more + * reliable. */ +#ifndef MEM_USE_POOLS_TRY_BIGGER_POOL +#define MEM_USE_POOLS_TRY_BIGGER_POOL 0 +#endif + +/** + * MEMP_USE_CUSTOM_POOLS==1: whether to include a user file lwippools.h + * that defines additional pools beyond the "standard" ones required + * by lwIP. If you set this to 1, you must have lwippools.h in your + * inlude path somewhere. + */ +#ifndef MEMP_USE_CUSTOM_POOLS +#define MEMP_USE_CUSTOM_POOLS 0 +#endif + +/** + * Set this to 1 if you want to free PBUF_RAM pbufs (or call mem_free()) from + * interrupt context (or another context that doesn't allow waiting for a + * semaphore). + * If set to 1, mem_malloc will be protected by a semaphore and SYS_ARCH_PROTECT, + * while mem_free will only use SYS_ARCH_PROTECT. mem_malloc SYS_ARCH_UNPROTECTs + * with each loop so that mem_free can run. + * + * ATTENTION: As you can see from the above description, this leads to dis-/ + * enabling interrupts often, which can be slow! Also, on low memory, mem_malloc + * can need longer. + * + * If you don't want that, at least for NO_SYS=0, you can still use the following + * functions to enqueue a deallocation call which then runs in the tcpip_thread + * context: + * - pbuf_free_callback(p); + * - mem_free_callback(m); + */ +#ifndef LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT +#define LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT 0 +#endif + +/* + ------------------------------------------------ + ---------- Internal Memory Pool Sizes ---------- + ------------------------------------------------ +*/ +/** + * MEMP_NUM_PBUF: the number of memp struct pbufs (used for PBUF_ROM and PBUF_REF). + * If the application sends a lot of data out of ROM (or other static memory), + * this should be set high. + */ +#ifndef MEMP_NUM_PBUF +#define MEMP_NUM_PBUF 16 +#endif + +/** + * MEMP_NUM_RAW_PCB: Number of raw connection PCBs + * (requires the LWIP_RAW option) + */ +#ifndef MEMP_NUM_RAW_PCB +#define MEMP_NUM_RAW_PCB 4 +#endif + +/** + * MEMP_NUM_UDP_PCB: the number of UDP protocol control blocks. One + * per active UDP "connection". + * (requires the LWIP_UDP option) + */ +#ifndef MEMP_NUM_UDP_PCB +#define MEMP_NUM_UDP_PCB 4 +#endif + +/** + * MEMP_NUM_TCP_PCB: the number of simulatenously active TCP connections. + * (requires the LWIP_TCP option) + */ +#ifndef MEMP_NUM_TCP_PCB +#define MEMP_NUM_TCP_PCB 5 +#endif + +/** + * MEMP_NUM_TCP_PCB_LISTEN: the number of listening TCP connections. + * (requires the LWIP_TCP option) + */ +#ifndef MEMP_NUM_TCP_PCB_LISTEN +#define MEMP_NUM_TCP_PCB_LISTEN 8 +#endif + +/** + * MEMP_NUM_TCP_SEG: the number of simultaneously queued TCP segments. + * (requires the LWIP_TCP option) + */ +#ifndef MEMP_NUM_TCP_SEG +#define MEMP_NUM_TCP_SEG 16 +#endif + +/** + * MEMP_NUM_REASSDATA: the number of IP packets simultaneously queued for + * reassembly (whole packets, not fragments!) + */ +#ifndef MEMP_NUM_REASSDATA +#define MEMP_NUM_REASSDATA 5 +#endif + +/** + * MEMP_NUM_FRAG_PBUF: the number of IP fragments simultaneously sent + * (fragments, not whole packets!). + * This is only used with IP_FRAG_USES_STATIC_BUF==0 and + * LWIP_NETIF_TX_SINGLE_PBUF==0 and only has to be > 1 with DMA-enabled MACs + * where the packet is not yet sent when netif->output returns. + */ +#ifndef MEMP_NUM_FRAG_PBUF +#define MEMP_NUM_FRAG_PBUF 15 +#endif + +/** + * MEMP_NUM_ARP_QUEUE: the number of simulateously queued outgoing + * packets (pbufs) that are waiting for an ARP request (to resolve + * their destination address) to finish. + * (requires the ARP_QUEUEING option) + */ +#ifndef MEMP_NUM_ARP_QUEUE +#define MEMP_NUM_ARP_QUEUE 30 +#endif + +/** + * MEMP_NUM_IGMP_GROUP: The number of multicast groups whose network interfaces + * can be members et the same time (one per netif - allsystems group -, plus one + * per netif membership). + * (requires the LWIP_IGMP option) + */ +#ifndef MEMP_NUM_IGMP_GROUP +#define MEMP_NUM_IGMP_GROUP 8 +#endif + +/** + * MEMP_NUM_SYS_TIMEOUT: the number of simulateously active timeouts. + * (requires NO_SYS==0) + */ +#ifndef MEMP_NUM_SYS_TIMEOUT +#define MEMP_NUM_SYS_TIMEOUT 3 +#endif + +/** + * MEMP_NUM_NETBUF: the number of struct netbufs. + * (only needed if you use the sequential API, like api_lib.c) + */ +#ifndef MEMP_NUM_NETBUF +#define MEMP_NUM_NETBUF 2 +#endif + +/** + * MEMP_NUM_NETCONN: the number of struct netconns. + * (only needed if you use the sequential API, like api_lib.c) + */ +#ifndef MEMP_NUM_NETCONN +#define MEMP_NUM_NETCONN 4 +#endif + +/** + * MEMP_NUM_TCPIP_MSG_API: the number of struct tcpip_msg, which are used + * for callback/timeout API communication. + * (only needed if you use tcpip.c) + */ +#ifndef MEMP_NUM_TCPIP_MSG_API +#define MEMP_NUM_TCPIP_MSG_API 8 +#endif + +/** + * MEMP_NUM_TCPIP_MSG_INPKT: the number of struct tcpip_msg, which are used + * for incoming packets. + * (only needed if you use tcpip.c) + */ +#ifndef MEMP_NUM_TCPIP_MSG_INPKT +#define MEMP_NUM_TCPIP_MSG_INPKT 8 +#endif + +/** + * MEMP_NUM_SNMP_NODE: the number of leafs in the SNMP tree. + */ +#ifndef MEMP_NUM_SNMP_NODE +#define MEMP_NUM_SNMP_NODE 50 +#endif + +/** + * MEMP_NUM_SNMP_ROOTNODE: the number of branches in the SNMP tree. + * Every branch has one leaf (MEMP_NUM_SNMP_NODE) at least! + */ +#ifndef MEMP_NUM_SNMP_ROOTNODE +#define MEMP_NUM_SNMP_ROOTNODE 30 +#endif + +/** + * MEMP_NUM_SNMP_VARBIND: the number of concurrent requests (does not have to + * be changed normally) - 2 of these are used per request (1 for input, + * 1 for output) + */ +#ifndef MEMP_NUM_SNMP_VARBIND +#define MEMP_NUM_SNMP_VARBIND 2 +#endif + +/** + * MEMP_NUM_SNMP_VALUE: the number of OID or values concurrently used + * (does not have to be changed normally) - 3 of these are used per request + * (1 for the value read and 2 for OIDs - input and output) + */ +#ifndef MEMP_NUM_SNMP_VALUE +#define MEMP_NUM_SNMP_VALUE 3 +#endif + +/** + * MEMP_NUM_NETDB: the number of concurrently running lwip_addrinfo() calls + * (before freeing the corresponding memory using lwip_freeaddrinfo()). + */ +#ifndef MEMP_NUM_NETDB +#define MEMP_NUM_NETDB 1 +#endif + +/** + * MEMP_NUM_LOCALHOSTLIST: the number of host entries in the local host list + * if DNS_LOCAL_HOSTLIST_IS_DYNAMIC==1. + */ +#ifndef MEMP_NUM_LOCALHOSTLIST +#define MEMP_NUM_LOCALHOSTLIST 1 +#endif + +/** + * MEMP_NUM_PPPOE_INTERFACES: the number of concurrently active PPPoE + * interfaces (only used with PPPOE_SUPPORT==1) + */ +#ifndef MEMP_NUM_PPPOE_INTERFACES +#define MEMP_NUM_PPPOE_INTERFACES 1 +#endif + +/** + * PBUF_POOL_SIZE: the number of buffers in the pbuf pool. + */ +#ifndef PBUF_POOL_SIZE +#define PBUF_POOL_SIZE 16 +#endif + +/* + --------------------------------- + ---------- ARP options ---------- + --------------------------------- +*/ +/** + * LWIP_ARP==1: Enable ARP functionality. + */ +#ifndef LWIP_ARP +#define LWIP_ARP 1 +#endif + +/** + * ARP_TABLE_SIZE: Number of active MAC-IP address pairs cached. + */ +#ifndef ARP_TABLE_SIZE +#define ARP_TABLE_SIZE 10 +#endif + +/** + * ARP_QUEUEING==1: Multiple outgoing packets are queued during hardware address + * resolution. By default, only the most recent packet is queued per IP address. + * This is sufficient for most protocols and mainly reduces TCP connection + * startup time. Set this to 1 if you know your application sends more than one + * packet in a row to an IP address that is not in the ARP cache. + */ +#ifndef ARP_QUEUEING +#define ARP_QUEUEING 0 +#endif + +/** + * ETHARP_TRUST_IP_MAC==1: Incoming IP packets cause the ARP table to be + * updated with the source MAC and IP addresses supplied in the packet. + * You may want to disable this if you do not trust LAN peers to have the + * correct addresses, or as a limited approach to attempt to handle + * spoofing. If disabled, lwIP will need to make a new ARP request if + * the peer is not already in the ARP table, adding a little latency. + * The peer *is* in the ARP table if it requested our address before. + * Also notice that this slows down input processing of every IP packet! + */ +#ifndef ETHARP_TRUST_IP_MAC +#define ETHARP_TRUST_IP_MAC 0 +#endif + +/** + * ETHARP_SUPPORT_VLAN==1: support receiving ethernet packets with VLAN header. + * Additionally, you can define ETHARP_VLAN_CHECK to an u16_t VLAN ID to check. + * If ETHARP_VLAN_CHECK is defined, only VLAN-traffic for this VLAN is accepted. + * If ETHARP_VLAN_CHECK is not defined, all traffic is accepted. + */ +#ifndef ETHARP_SUPPORT_VLAN +#define ETHARP_SUPPORT_VLAN 0 +#endif + +/** LWIP_ETHERNET==1: enable ethernet support for PPPoE even though ARP + * might be disabled + */ +#ifndef LWIP_ETHERNET +#define LWIP_ETHERNET (LWIP_ARP || PPPOE_SUPPORT) +#endif + +/** ETH_PAD_SIZE: number of bytes added before the ethernet header to ensure + * alignment of payload after that header. Since the header is 14 bytes long, + * without this padding e.g. addresses in the IP header will not be aligned + * on a 32-bit boundary, so setting this to 2 can speed up 32-bit-platforms. + */ +#ifndef ETH_PAD_SIZE +#define ETH_PAD_SIZE 0 +#endif + +/** ETHARP_SUPPORT_STATIC_ENTRIES==1: enable code to support static ARP table + * entries (using etharp_add_static_entry/etharp_remove_static_entry). + */ +#ifndef ETHARP_SUPPORT_STATIC_ENTRIES +#define ETHARP_SUPPORT_STATIC_ENTRIES 0 +#endif + + +/* + -------------------------------- + ---------- IP options ---------- + -------------------------------- +*/ +/** + * IP_FORWARD==1: Enables the ability to forward IP packets across network + * interfaces. If you are going to run lwIP on a device with only one network + * interface, define this to 0. + */ +#ifndef IP_FORWARD +#define IP_FORWARD 0 +#endif + +/** + * IP_OPTIONS_ALLOWED: Defines the behavior for IP options. + * IP_OPTIONS_ALLOWED==0: All packets with IP options are dropped. + * IP_OPTIONS_ALLOWED==1: IP options are allowed (but not parsed). + */ +#ifndef IP_OPTIONS_ALLOWED +#define IP_OPTIONS_ALLOWED 1 +#endif + +/** + * IP_REASSEMBLY==1: Reassemble incoming fragmented IP packets. Note that + * this option does not affect outgoing packet sizes, which can be controlled + * via IP_FRAG. + */ +#ifndef IP_REASSEMBLY +#define IP_REASSEMBLY 1 +#endif + +/** + * IP_FRAG==1: Fragment outgoing IP packets if their size exceeds MTU. Note + * that this option does not affect incoming packet sizes, which can be + * controlled via IP_REASSEMBLY. + */ +#ifndef IP_FRAG +#define IP_FRAG 1 +#endif + +/** + * IP_REASS_MAXAGE: Maximum time (in multiples of IP_TMR_INTERVAL - so seconds, normally) + * a fragmented IP packet waits for all fragments to arrive. If not all fragments arrived + * in this time, the whole packet is discarded. + */ +#ifndef IP_REASS_MAXAGE +#define IP_REASS_MAXAGE 3 +#endif + +/** + * IP_REASS_MAX_PBUFS: Total maximum amount of pbufs waiting to be reassembled. + * Since the received pbufs are enqueued, be sure to configure + * PBUF_POOL_SIZE > IP_REASS_MAX_PBUFS so that the stack is still able to receive + * packets even if the maximum amount of fragments is enqueued for reassembly! + */ +#ifndef IP_REASS_MAX_PBUFS +#define IP_REASS_MAX_PBUFS 10 +#endif + +/** + * IP_FRAG_USES_STATIC_BUF==1: Use a static MTU-sized buffer for IP + * fragmentation. Otherwise pbufs are allocated and reference the original + * packet data to be fragmented (or with LWIP_NETIF_TX_SINGLE_PBUF==1, + * new PBUF_RAM pbufs are used for fragments). + * ATTENTION: IP_FRAG_USES_STATIC_BUF==1 may not be used for DMA-enabled MACs! + */ +#ifndef IP_FRAG_USES_STATIC_BUF +#define IP_FRAG_USES_STATIC_BUF 0 +#endif + +/** + * IP_FRAG_MAX_MTU: Assumed max MTU on any interface for IP frag buffer + * (requires IP_FRAG_USES_STATIC_BUF==1) + */ +#if IP_FRAG_USES_STATIC_BUF && !defined(IP_FRAG_MAX_MTU) +#define IP_FRAG_MAX_MTU 1500 +#endif + +/** + * IP_DEFAULT_TTL: Default value for Time-To-Live used by transport layers. + */ +#ifndef IP_DEFAULT_TTL +#define IP_DEFAULT_TTL 255 +#endif + +/** + * IP_SOF_BROADCAST=1: Use the SOF_BROADCAST field to enable broadcast + * filter per pcb on udp and raw send operations. To enable broadcast filter + * on recv operations, you also have to set IP_SOF_BROADCAST_RECV=1. + */ +#ifndef IP_SOF_BROADCAST +#define IP_SOF_BROADCAST 0 +#endif + +/** + * IP_SOF_BROADCAST_RECV (requires IP_SOF_BROADCAST=1) enable the broadcast + * filter on recv operations. + */ +#ifndef IP_SOF_BROADCAST_RECV +#define IP_SOF_BROADCAST_RECV 0 +#endif + +/* + ---------------------------------- + ---------- ICMP options ---------- + ---------------------------------- +*/ +/** + * LWIP_ICMP==1: Enable ICMP module inside the IP stack. + * Be careful, disable that make your product non-compliant to RFC1122 + */ +#ifndef LWIP_ICMP +#define LWIP_ICMP 1 +#endif + +/** + * ICMP_TTL: Default value for Time-To-Live used by ICMP packets. + */ +#ifndef ICMP_TTL +#define ICMP_TTL (IP_DEFAULT_TTL) +#endif + +/** + * LWIP_BROADCAST_PING==1: respond to broadcast pings (default is unicast only) + */ +#ifndef LWIP_BROADCAST_PING +#define LWIP_BROADCAST_PING 0 +#endif + +/** + * LWIP_MULTICAST_PING==1: respond to multicast pings (default is unicast only) + */ +#ifndef LWIP_MULTICAST_PING +#define LWIP_MULTICAST_PING 0 +#endif + +/* + --------------------------------- + ---------- RAW options ---------- + --------------------------------- +*/ +/** + * LWIP_RAW==1: Enable application layer to hook into the IP layer itself. + */ +#ifndef LWIP_RAW +#define LWIP_RAW 1 +#endif + +/** + * LWIP_RAW==1: Enable application layer to hook into the IP layer itself. + */ +#ifndef RAW_TTL +#define RAW_TTL (IP_DEFAULT_TTL) +#endif + +/* + ---------------------------------- + ---------- DHCP options ---------- + ---------------------------------- +*/ +/** + * LWIP_DHCP==1: Enable DHCP module. + */ +#ifndef LWIP_DHCP +#define LWIP_DHCP 0 +#endif + +/** + * DHCP_DOES_ARP_CHECK==1: Do an ARP check on the offered address. + */ +#ifndef DHCP_DOES_ARP_CHECK +#define DHCP_DOES_ARP_CHECK ((LWIP_DHCP) && (LWIP_ARP)) +#endif + +/* + ------------------------------------ + ---------- AUTOIP options ---------- + ------------------------------------ +*/ +/** + * LWIP_AUTOIP==1: Enable AUTOIP module. + */ +#ifndef LWIP_AUTOIP +#define LWIP_AUTOIP 0 +#endif + +/** + * LWIP_DHCP_AUTOIP_COOP==1: Allow DHCP and AUTOIP to be both enabled on + * the same interface at the same time. + */ +#ifndef LWIP_DHCP_AUTOIP_COOP +#define LWIP_DHCP_AUTOIP_COOP 0 +#endif + +/** + * LWIP_DHCP_AUTOIP_COOP_TRIES: Set to the number of DHCP DISCOVER probes + * that should be sent before falling back on AUTOIP. This can be set + * as low as 1 to get an AutoIP address very quickly, but you should + * be prepared to handle a changing IP address when DHCP overrides + * AutoIP. + */ +#ifndef LWIP_DHCP_AUTOIP_COOP_TRIES +#define LWIP_DHCP_AUTOIP_COOP_TRIES 9 +#endif + +/* + ---------------------------------- + ---------- SNMP options ---------- + ---------------------------------- +*/ +/** + * LWIP_SNMP==1: Turn on SNMP module. UDP must be available for SNMP + * transport. + */ +#ifndef LWIP_SNMP +#define LWIP_SNMP 0 +#endif + +/** + * SNMP_CONCURRENT_REQUESTS: Number of concurrent requests the module will + * allow. At least one request buffer is required. + * Does not have to be changed unless external MIBs answer request asynchronously + */ +#ifndef SNMP_CONCURRENT_REQUESTS +#define SNMP_CONCURRENT_REQUESTS 1 +#endif + +/** + * SNMP_TRAP_DESTINATIONS: Number of trap destinations. At least one trap + * destination is required + */ +#ifndef SNMP_TRAP_DESTINATIONS +#define SNMP_TRAP_DESTINATIONS 1 +#endif + +/** + * SNMP_PRIVATE_MIB: + * When using a private MIB, you have to create a file 'private_mib.h' that contains + * a 'struct mib_array_node mib_private' which contains your MIB. + */ +#ifndef SNMP_PRIVATE_MIB +#define SNMP_PRIVATE_MIB 0 +#endif + +/** + * Only allow SNMP write actions that are 'safe' (e.g. disabeling netifs is not + * a safe action and disabled when SNMP_SAFE_REQUESTS = 1). + * Unsafe requests are disabled by default! + */ +#ifndef SNMP_SAFE_REQUESTS +#define SNMP_SAFE_REQUESTS 1 +#endif + +/** + * The maximum length of strings used. This affects the size of + * MEMP_SNMP_VALUE elements. + */ +#ifndef SNMP_MAX_OCTET_STRING_LEN +#define SNMP_MAX_OCTET_STRING_LEN 127 +#endif + +/** + * The maximum depth of the SNMP tree. + * With private MIBs enabled, this depends on your MIB! + * This affects the size of MEMP_SNMP_VALUE elements. + */ +#ifndef SNMP_MAX_TREE_DEPTH +#define SNMP_MAX_TREE_DEPTH 15 +#endif + +/** + * The size of the MEMP_SNMP_VALUE elements, normally calculated from + * SNMP_MAX_OCTET_STRING_LEN and SNMP_MAX_TREE_DEPTH. + */ +#ifndef SNMP_MAX_VALUE_SIZE +#define SNMP_MAX_VALUE_SIZE LWIP_MAX((SNMP_MAX_OCTET_STRING_LEN)+1, sizeof(s32_t)*(SNMP_MAX_TREE_DEPTH)) +#endif + +/* + ---------------------------------- + ---------- IGMP options ---------- + ---------------------------------- +*/ +/** + * LWIP_IGMP==1: Turn on IGMP module. + */ +#ifndef LWIP_IGMP +#define LWIP_IGMP 0 +#endif + +/* + ---------------------------------- + ---------- DNS options ----------- + ---------------------------------- +*/ +/** + * LWIP_DNS==1: Turn on DNS module. UDP must be available for DNS + * transport. + */ +#ifndef LWIP_DNS +#define LWIP_DNS 0 +#endif + +/** DNS maximum number of entries to maintain locally. */ +#ifndef DNS_TABLE_SIZE +#define DNS_TABLE_SIZE 4 +#endif + +/** DNS maximum host name length supported in the name table. */ +#ifndef DNS_MAX_NAME_LENGTH +#define DNS_MAX_NAME_LENGTH 256 +#endif + +/** The maximum of DNS servers */ +#ifndef DNS_MAX_SERVERS +#define DNS_MAX_SERVERS 2 +#endif + +/** DNS do a name checking between the query and the response. */ +#ifndef DNS_DOES_NAME_CHECK +#define DNS_DOES_NAME_CHECK 1 +#endif + +/** DNS message max. size. Default value is RFC compliant. */ +#ifndef DNS_MSG_SIZE +#define DNS_MSG_SIZE 512 +#endif + +/** DNS_LOCAL_HOSTLIST: Implements a local host-to-address list. If enabled, + * you have to define + * #define DNS_LOCAL_HOSTLIST_INIT {{"host1", 0x123}, {"host2", 0x234}} + * (an array of structs name/address, where address is an u32_t in network + * byte order). + * + * Instead, you can also use an external function: + * #define DNS_LOOKUP_LOCAL_EXTERN(x) extern u32_t my_lookup_function(const char *name) + * that returns the IP address or INADDR_NONE if not found. + */ +#ifndef DNS_LOCAL_HOSTLIST +#define DNS_LOCAL_HOSTLIST 0 +#endif /* DNS_LOCAL_HOSTLIST */ + +/** If this is turned on, the local host-list can be dynamically changed + * at runtime. */ +#ifndef DNS_LOCAL_HOSTLIST_IS_DYNAMIC +#define DNS_LOCAL_HOSTLIST_IS_DYNAMIC 0 +#endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */ + +/* + --------------------------------- + ---------- UDP options ---------- + --------------------------------- +*/ +/** + * LWIP_UDP==1: Turn on UDP. + */ +#ifndef LWIP_UDP +#define LWIP_UDP 1 +#endif + +/** + * LWIP_UDPLITE==1: Turn on UDP-Lite. (Requires LWIP_UDP) + */ +#ifndef LWIP_UDPLITE +#define LWIP_UDPLITE 0 +#endif + +/** + * UDP_TTL: Default Time-To-Live value. + */ +#ifndef UDP_TTL +#define UDP_TTL (IP_DEFAULT_TTL) +#endif + +/** + * LWIP_NETBUF_RECVINFO==1: append destination addr and port to every netbuf. + */ +#ifndef LWIP_NETBUF_RECVINFO +#define LWIP_NETBUF_RECVINFO 0 +#endif + +/* + --------------------------------- + ---------- TCP options ---------- + --------------------------------- +*/ +/** + * LWIP_TCP==1: Turn on TCP. + */ +#ifndef LWIP_TCP +#define LWIP_TCP 1 +#endif + +/** + * TCP_TTL: Default Time-To-Live value. + */ +#ifndef TCP_TTL +#define TCP_TTL (IP_DEFAULT_TTL) +#endif + +/** + * TCP_WND: The size of a TCP window. This must be at least + * (2 * TCP_MSS) for things to work well + */ +#ifndef TCP_WND +#define TCP_WND (4 * TCP_MSS) +#endif + +/** + * TCP_MAXRTX: Maximum number of retransmissions of data segments. + */ +#ifndef TCP_MAXRTX +#define TCP_MAXRTX 12 +#endif + +/** + * TCP_SYNMAXRTX: Maximum number of retransmissions of SYN segments. + */ +#ifndef TCP_SYNMAXRTX +#define TCP_SYNMAXRTX 6 +#endif + +/** + * TCP_QUEUE_OOSEQ==1: TCP will queue segments that arrive out of order. + * Define to 0 if your device is low on memory. + */ +#ifndef TCP_QUEUE_OOSEQ +#define TCP_QUEUE_OOSEQ (LWIP_TCP) +#endif + +/** + * TCP_MSS: TCP Maximum segment size. (default is 536, a conservative default, + * you might want to increase this.) + * For the receive side, this MSS is advertised to the remote side + * when opening a connection. For the transmit size, this MSS sets + * an upper limit on the MSS advertised by the remote host. + */ +#ifndef TCP_MSS +#define TCP_MSS 536 +#endif + +/** + * TCP_CALCULATE_EFF_SEND_MSS: "The maximum size of a segment that TCP really + * sends, the 'effective send MSS,' MUST be the smaller of the send MSS (which + * reflects the available reassembly buffer size at the remote host) and the + * largest size permitted by the IP layer" (RFC 1122) + * Setting this to 1 enables code that checks TCP_MSS against the MTU of the + * netif used for a connection and limits the MSS if it would be too big otherwise. + */ +#ifndef TCP_CALCULATE_EFF_SEND_MSS +#define TCP_CALCULATE_EFF_SEND_MSS 1 +#endif + + +/** + * TCP_SND_BUF: TCP sender buffer space (bytes). + */ +#ifndef TCP_SND_BUF +#define TCP_SND_BUF 256 +#endif + +/** + * TCP_SND_QUEUELEN: TCP sender buffer space (pbufs). This must be at least + * as much as (2 * TCP_SND_BUF/TCP_MSS) for things to work. + */ +#ifndef TCP_SND_QUEUELEN +#define TCP_SND_QUEUELEN ((4 * (TCP_SND_BUF) + (TCP_MSS - 1))/(TCP_MSS)) +#endif + +/** + * TCP_SNDLOWAT: TCP writable space (bytes). This must be less than + * TCP_SND_BUF. It is the amount of space which must be available in the + * TCP snd_buf for select to return writable (combined with TCP_SNDQUEUELOWAT). + */ +#ifndef TCP_SNDLOWAT +#define TCP_SNDLOWAT ((TCP_SND_BUF)/2) +#endif + +/** + * TCP_SNDQUEUELOWAT: TCP writable bufs (pbuf count). This must be grater + * than TCP_SND_QUEUELEN. If the number of pbufs queued on a pcb drops below + * this number, select returns writable (combined with TCP_SNDLOWAT). + */ +#ifndef TCP_SNDQUEUELOWAT +#define TCP_SNDQUEUELOWAT ((TCP_SND_QUEUELEN)/2) +#endif + +/** + * TCP_LISTEN_BACKLOG: Enable the backlog option for tcp listen pcb. + */ +#ifndef TCP_LISTEN_BACKLOG +#define TCP_LISTEN_BACKLOG 0 +#endif + +/** + * The maximum allowed backlog for TCP listen netconns. + * This backlog is used unless another is explicitly specified. + * 0xff is the maximum (u8_t). + */ +#ifndef TCP_DEFAULT_LISTEN_BACKLOG +#define TCP_DEFAULT_LISTEN_BACKLOG 0xff +#endif + +/** + * TCP_OVERSIZE: The maximum number of bytes that tcp_write may + * allocate ahead of time in an attempt to create shorter pbuf chains + * for transmission. The meaningful range is 0 to TCP_MSS. Some + * suggested values are: + * + * 0: Disable oversized allocation. Each tcp_write() allocates a new + pbuf (old behaviour). + * 1: Allocate size-aligned pbufs with minimal excess. Use this if your + * scatter-gather DMA requires aligned fragments. + * 128: Limit the pbuf/memory overhead to 20%. + * TCP_MSS: Try to create unfragmented TCP packets. + * TCP_MSS/4: Try to create 4 fragments or less per TCP packet. + */ +#ifndef TCP_OVERSIZE +#define TCP_OVERSIZE TCP_MSS +#endif + +/** + * LWIP_TCP_TIMESTAMPS==1: support the TCP timestamp option. + */ +#ifndef LWIP_TCP_TIMESTAMPS +#define LWIP_TCP_TIMESTAMPS 0 +#endif + +/** + * TCP_WND_UPDATE_THRESHOLD: difference in window to trigger an + * explicit window update + */ +#ifndef TCP_WND_UPDATE_THRESHOLD +#define TCP_WND_UPDATE_THRESHOLD (TCP_WND / 4) +#endif + +/** + * LWIP_EVENT_API and LWIP_CALLBACK_API: Only one of these should be set to 1. + * LWIP_EVENT_API==1: The user defines lwip_tcp_event() to receive all + * events (accept, sent, etc) that happen in the system. + * LWIP_CALLBACK_API==1: The PCB callback function is called directly + * for the event. + */ +#ifndef LWIP_EVENT_API +#define LWIP_EVENT_API 0 +#define LWIP_CALLBACK_API 1 +#else +#define LWIP_EVENT_API 1 +#define LWIP_CALLBACK_API 0 +#endif + + +/* + ---------------------------------- + ---------- Pbuf options ---------- + ---------------------------------- +*/ +/** + * PBUF_LINK_HLEN: the number of bytes that should be allocated for a + * link level header. The default is 14, the standard value for + * Ethernet. + */ +#ifndef PBUF_LINK_HLEN +#define PBUF_LINK_HLEN (14 + ETH_PAD_SIZE) +#endif + +/** + * PBUF_POOL_BUFSIZE: the size of each pbuf in the pbuf pool. The default is + * designed to accomodate single full size TCP frame in one pbuf, including + * TCP_MSS, IP header, and link header. + */ +#ifndef PBUF_POOL_BUFSIZE +#define PBUF_POOL_BUFSIZE LWIP_MEM_ALIGN_SIZE(TCP_MSS+40+PBUF_LINK_HLEN) +#endif + +/* + ------------------------------------------------ + ---------- Network Interfaces options ---------- + ------------------------------------------------ +*/ +/** + * LWIP_NETIF_HOSTNAME==1: use DHCP_OPTION_HOSTNAME with netif's hostname + * field. + */ +#ifndef LWIP_NETIF_HOSTNAME +#define LWIP_NETIF_HOSTNAME 0 +#endif + +/** + * LWIP_NETIF_API==1: Support netif api (in netifapi.c) + */ +#ifndef LWIP_NETIF_API +#define LWIP_NETIF_API 0 +#endif + +/** + * LWIP_NETIF_STATUS_CALLBACK==1: Support a callback function whenever an interface + * changes its up/down status (i.e., due to DHCP IP acquistion) + */ +#ifndef LWIP_NETIF_STATUS_CALLBACK +#define LWIP_NETIF_STATUS_CALLBACK 0 +#endif + +/** + * LWIP_NETIF_LINK_CALLBACK==1: Support a callback function from an interface + * whenever the link changes (i.e., link down) + */ +#ifndef LWIP_NETIF_LINK_CALLBACK +#define LWIP_NETIF_LINK_CALLBACK 0 +#endif + +/** + * LWIP_NETIF_HWADDRHINT==1: Cache link-layer-address hints (e.g. table + * indices) in struct netif. TCP and UDP can make use of this to prevent + * scanning the ARP table for every sent packet. While this is faster for big + * ARP tables or many concurrent connections, it might be counterproductive + * if you have a tiny ARP table or if there never are concurrent connections. + */ +#ifndef LWIP_NETIF_HWADDRHINT +#define LWIP_NETIF_HWADDRHINT 0 +#endif + +/** + * LWIP_NETIF_LOOPBACK==1: Support sending packets with a destination IP + * address equal to the netif IP address, looping them back up the stack. + */ +#ifndef LWIP_NETIF_LOOPBACK +#define LWIP_NETIF_LOOPBACK 0 +#endif + +/** + * LWIP_LOOPBACK_MAX_PBUFS: Maximum number of pbufs on queue for loopback + * sending for each netif (0 = disabled) + */ +#ifndef LWIP_LOOPBACK_MAX_PBUFS +#define LWIP_LOOPBACK_MAX_PBUFS 0 +#endif + +/** + * LWIP_NETIF_LOOPBACK_MULTITHREADING: Indicates whether threading is enabled in + * the system, as netifs must change how they behave depending on this setting + * for the LWIP_NETIF_LOOPBACK option to work. + * Setting this is needed to avoid reentering non-reentrant functions like + * tcp_input(). + * LWIP_NETIF_LOOPBACK_MULTITHREADING==1: Indicates that the user is using a + * multithreaded environment like tcpip.c. In this case, netif->input() + * is called directly. + * LWIP_NETIF_LOOPBACK_MULTITHREADING==0: Indicates a polling (or NO_SYS) setup. + * The packets are put on a list and netif_poll() must be called in + * the main application loop. + */ +#ifndef LWIP_NETIF_LOOPBACK_MULTITHREADING +#define LWIP_NETIF_LOOPBACK_MULTITHREADING (!NO_SYS) +#endif + +/** + * LWIP_NETIF_TX_SINGLE_PBUF: if this is set to 1, lwIP tries to put all data + * to be sent into one single pbuf. This is for compatibility with DMA-enabled + * MACs that do not support scatter-gather. + * Beware that this might involve CPU-memcpy before transmitting that would not + * be needed without this flag! Use this only if you need to! + * + * @todo: TCP and IP-frag do not work with this, yet: + */ +#ifndef LWIP_NETIF_TX_SINGLE_PBUF +#define LWIP_NETIF_TX_SINGLE_PBUF 0 +#endif /* LWIP_NETIF_TX_SINGLE_PBUF */ + +/* + ------------------------------------ + ---------- LOOPIF options ---------- + ------------------------------------ +*/ +/** + * LWIP_HAVE_LOOPIF==1: Support loop interface (127.0.0.1) and loopif.c + */ +#ifndef LWIP_HAVE_LOOPIF +#define LWIP_HAVE_LOOPIF 0 +#endif + +/* + ------------------------------------ + ---------- SLIPIF options ---------- + ------------------------------------ +*/ +/** + * LWIP_HAVE_SLIPIF==1: Support slip interface and slipif.c + */ +#ifndef LWIP_HAVE_SLIPIF +#define LWIP_HAVE_SLIPIF 0 +#endif + +/* + ------------------------------------ + ---------- Thread options ---------- + ------------------------------------ +*/ +/** + * TCPIP_THREAD_NAME: The name assigned to the main tcpip thread. + */ +#ifndef TCPIP_THREAD_NAME +#define TCPIP_THREAD_NAME "tcpip_thread" +#endif + +/** + * TCPIP_THREAD_STACKSIZE: The stack size used by the main tcpip thread. + * The stack size value itself is platform-dependent, but is passed to + * sys_thread_new() when the thread is created. + */ +#ifndef TCPIP_THREAD_STACKSIZE +#define TCPIP_THREAD_STACKSIZE 0 +#endif + +/** + * TCPIP_THREAD_PRIO: The priority assigned to the main tcpip thread. + * The priority value itself is platform-dependent, but is passed to + * sys_thread_new() when the thread is created. + */ +#ifndef TCPIP_THREAD_PRIO +#define TCPIP_THREAD_PRIO 1 +#endif + +/** + * TCPIP_MBOX_SIZE: The mailbox size for the tcpip thread messages + * The queue size value itself is platform-dependent, but is passed to + * sys_mbox_new() when tcpip_init is called. + */ +#ifndef TCPIP_MBOX_SIZE +#define TCPIP_MBOX_SIZE 0 +#endif + +/** + * SLIPIF_THREAD_NAME: The name assigned to the slipif_loop thread. + */ +#ifndef SLIPIF_THREAD_NAME +#define SLIPIF_THREAD_NAME "slipif_loop" +#endif + +/** + * SLIP_THREAD_STACKSIZE: The stack size used by the slipif_loop thread. + * The stack size value itself is platform-dependent, but is passed to + * sys_thread_new() when the thread is created. + */ +#ifndef SLIPIF_THREAD_STACKSIZE +#define SLIPIF_THREAD_STACKSIZE 0 +#endif + +/** + * SLIPIF_THREAD_PRIO: The priority assigned to the slipif_loop thread. + * The priority value itself is platform-dependent, but is passed to + * sys_thread_new() when the thread is created. + */ +#ifndef SLIPIF_THREAD_PRIO +#define SLIPIF_THREAD_PRIO 1 +#endif + +/** + * PPP_THREAD_NAME: The name assigned to the pppInputThread. + */ +#ifndef PPP_THREAD_NAME +#define PPP_THREAD_NAME "pppInputThread" +#endif + +/** + * PPP_THREAD_STACKSIZE: The stack size used by the pppInputThread. + * The stack size value itself is platform-dependent, but is passed to + * sys_thread_new() when the thread is created. + */ +#ifndef PPP_THREAD_STACKSIZE +#define PPP_THREAD_STACKSIZE 0 +#endif + +/** + * PPP_THREAD_PRIO: The priority assigned to the pppInputThread. + * The priority value itself is platform-dependent, but is passed to + * sys_thread_new() when the thread is created. + */ +#ifndef PPP_THREAD_PRIO +#define PPP_THREAD_PRIO 1 +#endif + +/** + * DEFAULT_THREAD_NAME: The name assigned to any other lwIP thread. + */ +#ifndef DEFAULT_THREAD_NAME +#define DEFAULT_THREAD_NAME "lwIP" +#endif + +/** + * DEFAULT_THREAD_STACKSIZE: The stack size used by any other lwIP thread. + * The stack size value itself is platform-dependent, but is passed to + * sys_thread_new() when the thread is created. + */ +#ifndef DEFAULT_THREAD_STACKSIZE +#define DEFAULT_THREAD_STACKSIZE 0 +#endif + +/** + * DEFAULT_THREAD_PRIO: The priority assigned to any other lwIP thread. + * The priority value itself is platform-dependent, but is passed to + * sys_thread_new() when the thread is created. + */ +#ifndef DEFAULT_THREAD_PRIO +#define DEFAULT_THREAD_PRIO 1 +#endif + +/** + * DEFAULT_RAW_RECVMBOX_SIZE: The mailbox size for the incoming packets on a + * NETCONN_RAW. The queue size value itself is platform-dependent, but is passed + * to sys_mbox_new() when the recvmbox is created. + */ +#ifndef DEFAULT_RAW_RECVMBOX_SIZE +#define DEFAULT_RAW_RECVMBOX_SIZE 0 +#endif + +/** + * DEFAULT_UDP_RECVMBOX_SIZE: The mailbox size for the incoming packets on a + * NETCONN_UDP. The queue size value itself is platform-dependent, but is passed + * to sys_mbox_new() when the recvmbox is created. + */ +#ifndef DEFAULT_UDP_RECVMBOX_SIZE +#define DEFAULT_UDP_RECVMBOX_SIZE 0 +#endif + +/** + * DEFAULT_TCP_RECVMBOX_SIZE: The mailbox size for the incoming packets on a + * NETCONN_TCP. The queue size value itself is platform-dependent, but is passed + * to sys_mbox_new() when the recvmbox is created. + */ +#ifndef DEFAULT_TCP_RECVMBOX_SIZE +#define DEFAULT_TCP_RECVMBOX_SIZE 0 +#endif + +/** + * DEFAULT_ACCEPTMBOX_SIZE: The mailbox size for the incoming connections. + * The queue size value itself is platform-dependent, but is passed to + * sys_mbox_new() when the acceptmbox is created. + */ +#ifndef DEFAULT_ACCEPTMBOX_SIZE +#define DEFAULT_ACCEPTMBOX_SIZE 0 +#endif + +/* + ---------------------------------------------- + ---------- Sequential layer options ---------- + ---------------------------------------------- +*/ +/** + * LWIP_TCPIP_CORE_LOCKING: (EXPERIMENTAL!) + * Don't use it if you're not an active lwIP project member + */ +#ifndef LWIP_TCPIP_CORE_LOCKING +#define LWIP_TCPIP_CORE_LOCKING 0 +#endif + +/** + * LWIP_TCPIP_CORE_LOCKING_INPUT: (EXPERIMENTAL!) + * Don't use it if you're not an active lwIP project member + */ +#ifndef LWIP_TCPIP_CORE_LOCKING_INPUT +#define LWIP_TCPIP_CORE_LOCKING_INPUT 0 +#endif + +/** + * LWIP_NETCONN==1: Enable Netconn API (require to use api_lib.c) + */ +#ifndef LWIP_NETCONN +#define LWIP_NETCONN 1 +#endif + +/** LWIP_TCPIP_TIMEOUT==1: Enable tcpip_timeout/tcpip_untimeout tod create + * timers running in tcpip_thread from another thread. + */ +#ifndef LWIP_TCPIP_TIMEOUT +#define LWIP_TCPIP_TIMEOUT 1 +#endif + +/* + ------------------------------------ + ---------- Socket options ---------- + ------------------------------------ +*/ +/** + * LWIP_SOCKET==1: Enable Socket API (require to use sockets.c) + */ +#ifndef LWIP_SOCKET +#define LWIP_SOCKET 1 +#endif + +/** + * LWIP_COMPAT_SOCKETS==1: Enable BSD-style sockets functions names. + * (only used if you use sockets.c) + */ +#ifndef LWIP_COMPAT_SOCKETS +#define LWIP_COMPAT_SOCKETS 1 +#endif + +/** + * LWIP_POSIX_SOCKETS_IO_NAMES==1: Enable POSIX-style sockets functions names. + * Disable this option if you use a POSIX operating system that uses the same + * names (read, write & close). (only used if you use sockets.c) + */ +#ifndef LWIP_POSIX_SOCKETS_IO_NAMES +#define LWIP_POSIX_SOCKETS_IO_NAMES 1 +#endif + +/** + * LWIP_TCP_KEEPALIVE==1: Enable TCP_KEEPIDLE, TCP_KEEPINTVL and TCP_KEEPCNT + * options processing. Note that TCP_KEEPIDLE and TCP_KEEPINTVL have to be set + * in seconds. (does not require sockets.c, and will affect tcp.c) + */ +#ifndef LWIP_TCP_KEEPALIVE +#define LWIP_TCP_KEEPALIVE 0 +#endif + +/** + * LWIP_SO_RCVTIMEO==1: Enable SO_RCVTIMEO processing. + */ +#ifndef LWIP_SO_RCVTIMEO +#define LWIP_SO_RCVTIMEO 0 +#endif + +/** + * LWIP_SO_RCVBUF==1: Enable SO_RCVBUF processing. + */ +#ifndef LWIP_SO_RCVBUF +#define LWIP_SO_RCVBUF 0 +#endif + +/** + * If LWIP_SO_RCVBUF is used, this is the default value for recv_bufsize. + */ +#ifndef RECV_BUFSIZE_DEFAULT +#define RECV_BUFSIZE_DEFAULT INT_MAX +#endif + +/** + * SO_REUSE==1: Enable SO_REUSEADDR option. + */ +#ifndef SO_REUSE +#define SO_REUSE 0 +#endif + +/** + * SO_REUSE_RXTOALL==1: Pass a copy of incoming broadcast/multicast packets + * to all local matches if SO_REUSEADDR is turned on. + * WARNING: Adds a memcpy for every packet if passing to more than one pcb! + */ +#ifndef SO_REUSE_RXTOALL +#define SO_REUSE_RXTOALL 0 +#endif + +/* + ---------------------------------------- + ---------- Statistics options ---------- + ---------------------------------------- +*/ +/** + * LWIP_STATS==1: Enable statistics collection in lwip_stats. + */ +#ifndef LWIP_STATS +#define LWIP_STATS 1 +#endif + +#if LWIP_STATS + +/** + * LWIP_STATS_DISPLAY==1: Compile in the statistics output functions. + */ +#ifndef LWIP_STATS_DISPLAY +#define LWIP_STATS_DISPLAY 0 +#endif + +/** + * LINK_STATS==1: Enable link stats. + */ +#ifndef LINK_STATS +#define LINK_STATS 1 +#endif + +/** + * ETHARP_STATS==1: Enable etharp stats. + */ +#ifndef ETHARP_STATS +#define ETHARP_STATS (LWIP_ARP) +#endif + +/** + * IP_STATS==1: Enable IP stats. + */ +#ifndef IP_STATS +#define IP_STATS 1 +#endif + +/** + * IPFRAG_STATS==1: Enable IP fragmentation stats. Default is + * on if using either frag or reass. + */ +#ifndef IPFRAG_STATS +#define IPFRAG_STATS (IP_REASSEMBLY || IP_FRAG) +#endif + +/** + * ICMP_STATS==1: Enable ICMP stats. + */ +#ifndef ICMP_STATS +#define ICMP_STATS 1 +#endif + +/** + * IGMP_STATS==1: Enable IGMP stats. + */ +#ifndef IGMP_STATS +#define IGMP_STATS (LWIP_IGMP) +#endif + +/** + * UDP_STATS==1: Enable UDP stats. Default is on if + * UDP enabled, otherwise off. + */ +#ifndef UDP_STATS +#define UDP_STATS (LWIP_UDP) +#endif + +/** + * TCP_STATS==1: Enable TCP stats. Default is on if TCP + * enabled, otherwise off. + */ +#ifndef TCP_STATS +#define TCP_STATS (LWIP_TCP) +#endif + +/** + * MEM_STATS==1: Enable mem.c stats. + */ +#ifndef MEM_STATS +#define MEM_STATS ((MEM_LIBC_MALLOC == 0) && (MEM_USE_POOLS == 0)) +#endif + +/** + * MEMP_STATS==1: Enable memp.c pool stats. + */ +#ifndef MEMP_STATS +#define MEMP_STATS (MEMP_MEM_MALLOC == 0) +#endif + +/** + * SYS_STATS==1: Enable system stats (sem and mbox counts, etc). + */ +#ifndef SYS_STATS +#define SYS_STATS (NO_SYS == 0) +#endif + +#else + +#define LINK_STATS 0 +#define IP_STATS 0 +#define IPFRAG_STATS 0 +#define ICMP_STATS 0 +#define IGMP_STATS 0 +#define UDP_STATS 0 +#define TCP_STATS 0 +#define MEM_STATS 0 +#define MEMP_STATS 0 +#define SYS_STATS 0 +#define LWIP_STATS_DISPLAY 0 + +#endif /* LWIP_STATS */ + +/* + --------------------------------- + ---------- PPP options ---------- + --------------------------------- +*/ +/** + * PPP_SUPPORT==1: Enable PPP. + */ +#ifndef PPP_SUPPORT +#define PPP_SUPPORT 0 +#endif + +/** + * PPPOE_SUPPORT==1: Enable PPP Over Ethernet + */ +#ifndef PPPOE_SUPPORT +#define PPPOE_SUPPORT 0 +#endif + +/** + * PPPOS_SUPPORT==1: Enable PPP Over Serial + */ +#ifndef PPPOS_SUPPORT +#define PPPOS_SUPPORT PPP_SUPPORT +#endif + +#if PPP_SUPPORT + +/** + * NUM_PPP: Max PPP sessions. + */ +#ifndef NUM_PPP +#define NUM_PPP 1 +#endif + +/** + * PAP_SUPPORT==1: Support PAP. + */ +#ifndef PAP_SUPPORT +#define PAP_SUPPORT 0 +#endif + +/** + * CHAP_SUPPORT==1: Support CHAP. + */ +#ifndef CHAP_SUPPORT +#define CHAP_SUPPORT 0 +#endif + +/** + * MSCHAP_SUPPORT==1: Support MSCHAP. CURRENTLY NOT SUPPORTED! DO NOT SET! + */ +#ifndef MSCHAP_SUPPORT +#define MSCHAP_SUPPORT 0 +#endif + +/** + * CBCP_SUPPORT==1: Support CBCP. CURRENTLY NOT SUPPORTED! DO NOT SET! + */ +#ifndef CBCP_SUPPORT +#define CBCP_SUPPORT 0 +#endif + +/** + * CCP_SUPPORT==1: Support CCP. CURRENTLY NOT SUPPORTED! DO NOT SET! + */ +#ifndef CCP_SUPPORT +#define CCP_SUPPORT 0 +#endif + +/** + * VJ_SUPPORT==1: Support VJ header compression. + */ +#ifndef VJ_SUPPORT +#define VJ_SUPPORT 0 +#endif + +/** + * MD5_SUPPORT==1: Support MD5 (see also CHAP). + */ +#ifndef MD5_SUPPORT +#define MD5_SUPPORT 0 +#endif + +/* + * Timeouts + */ +#ifndef FSM_DEFTIMEOUT +#define FSM_DEFTIMEOUT 6 /* Timeout time in seconds */ +#endif + +#ifndef FSM_DEFMAXTERMREQS +#define FSM_DEFMAXTERMREQS 2 /* Maximum Terminate-Request transmissions */ +#endif + +#ifndef FSM_DEFMAXCONFREQS +#define FSM_DEFMAXCONFREQS 10 /* Maximum Configure-Request transmissions */ +#endif + +#ifndef FSM_DEFMAXNAKLOOPS +#define FSM_DEFMAXNAKLOOPS 5 /* Maximum number of nak loops */ +#endif + +#ifndef UPAP_DEFTIMEOUT +#define UPAP_DEFTIMEOUT 6 /* Timeout (seconds) for retransmitting req */ +#endif + +#ifndef UPAP_DEFREQTIME +#define UPAP_DEFREQTIME 30 /* Time to wait for auth-req from peer */ +#endif + +#ifndef CHAP_DEFTIMEOUT +#define CHAP_DEFTIMEOUT 6 /* Timeout time in seconds */ +#endif + +#ifndef CHAP_DEFTRANSMITS +#define CHAP_DEFTRANSMITS 10 /* max # times to send challenge */ +#endif + +/* Interval in seconds between keepalive echo requests, 0 to disable. */ +#ifndef LCP_ECHOINTERVAL +#define LCP_ECHOINTERVAL 0 +#endif + +/* Number of unanswered echo requests before failure. */ +#ifndef LCP_MAXECHOFAILS +#define LCP_MAXECHOFAILS 3 +#endif + +/* Max Xmit idle time (in jiffies) before resend flag char. */ +#ifndef PPP_MAXIDLEFLAG +#define PPP_MAXIDLEFLAG 100 +#endif + +/* + * Packet sizes + * + * Note - lcp shouldn't be allowed to negotiate stuff outside these + * limits. See lcp.h in the pppd directory. + * (XXX - these constants should simply be shared by lcp.c instead + * of living in lcp.h) + */ +#define PPP_MTU 1500 /* Default MTU (size of Info field) */ +#ifndef PPP_MAXMTU +/* #define PPP_MAXMTU 65535 - (PPP_HDRLEN + PPP_FCSLEN) */ +#define PPP_MAXMTU 1500 /* Largest MTU we allow */ +#endif +#define PPP_MINMTU 64 +#define PPP_MRU 1500 /* default MRU = max length of info field */ +#define PPP_MAXMRU 1500 /* Largest MRU we allow */ +#ifndef PPP_DEFMRU +#define PPP_DEFMRU 296 /* Try for this */ +#endif +#define PPP_MINMRU 128 /* No MRUs below this */ + +#ifndef MAXNAMELEN +#define MAXNAMELEN 256 /* max length of hostname or name for auth */ +#endif +#ifndef MAXSECRETLEN +#define MAXSECRETLEN 256 /* max length of password or secret */ +#endif + +#endif /* PPP_SUPPORT */ + +/* + -------------------------------------- + ---------- Checksum options ---------- + -------------------------------------- +*/ +/** + * CHECKSUM_GEN_IP==1: Generate checksums in software for outgoing IP packets. + */ +#ifndef CHECKSUM_GEN_IP +#define CHECKSUM_GEN_IP 1 +#endif + +/** + * CHECKSUM_GEN_UDP==1: Generate checksums in software for outgoing UDP packets. + */ +#ifndef CHECKSUM_GEN_UDP +#define CHECKSUM_GEN_UDP 1 +#endif + +/** + * CHECKSUM_GEN_TCP==1: Generate checksums in software for outgoing TCP packets. + */ +#ifndef CHECKSUM_GEN_TCP +#define CHECKSUM_GEN_TCP 1 +#endif + +/** + * CHECKSUM_CHECK_IP==1: Check checksums in software for incoming IP packets. + */ +#ifndef CHECKSUM_CHECK_IP +#define CHECKSUM_CHECK_IP 1 +#endif + +/** + * CHECKSUM_CHECK_UDP==1: Check checksums in software for incoming UDP packets. + */ +#ifndef CHECKSUM_CHECK_UDP +#define CHECKSUM_CHECK_UDP 1 +#endif + +/** + * CHECKSUM_CHECK_TCP==1: Check checksums in software for incoming TCP packets. + */ +#ifndef CHECKSUM_CHECK_TCP +#define CHECKSUM_CHECK_TCP 1 +#endif + +/** + * LWIP_CHECKSUM_ON_COPY==1: Calculate checksum when copying data from + * application buffers to pbufs. + */ +#ifndef LWIP_CHECKSUM_ON_COPY +#define LWIP_CHECKSUM_ON_COPY 0 +#endif + +/* + --------------------------------------- + ---------- Debugging options ---------- + --------------------------------------- +*/ +/** + * LWIP_DBG_MIN_LEVEL: After masking, the value of the debug is + * compared against this value. If it is smaller, then debugging + * messages are written. + */ +#ifndef LWIP_DBG_MIN_LEVEL +#define LWIP_DBG_MIN_LEVEL LWIP_DBG_LEVEL_ALL +#endif + +/** + * LWIP_DBG_TYPES_ON: A mask that can be used to globally enable/disable + * debug messages of certain types. + */ +#ifndef LWIP_DBG_TYPES_ON +#define LWIP_DBG_TYPES_ON LWIP_DBG_ON +#endif + +/** + * ETHARP_DEBUG: Enable debugging in etharp.c. + */ +#ifndef ETHARP_DEBUG +#define ETHARP_DEBUG LWIP_DBG_OFF +#endif + +/** + * NETIF_DEBUG: Enable debugging in netif.c. + */ +#ifndef NETIF_DEBUG +#define NETIF_DEBUG LWIP_DBG_OFF +#endif + +/** + * PBUF_DEBUG: Enable debugging in pbuf.c. + */ +#ifndef PBUF_DEBUG +#define PBUF_DEBUG LWIP_DBG_OFF +#endif + +/** + * API_LIB_DEBUG: Enable debugging in api_lib.c. + */ +#ifndef API_LIB_DEBUG +#define API_LIB_DEBUG LWIP_DBG_OFF +#endif + +/** + * API_MSG_DEBUG: Enable debugging in api_msg.c. + */ +#ifndef API_MSG_DEBUG +#define API_MSG_DEBUG LWIP_DBG_OFF +#endif + +/** + * SOCKETS_DEBUG: Enable debugging in sockets.c. + */ +#ifndef SOCKETS_DEBUG +#define SOCKETS_DEBUG LWIP_DBG_OFF +#endif + +/** + * ICMP_DEBUG: Enable debugging in icmp.c. + */ +#ifndef ICMP_DEBUG +#define ICMP_DEBUG LWIP_DBG_OFF +#endif + +/** + * IGMP_DEBUG: Enable debugging in igmp.c. + */ +#ifndef IGMP_DEBUG +#define IGMP_DEBUG LWIP_DBG_OFF +#endif + +/** + * INET_DEBUG: Enable debugging in inet.c. + */ +#ifndef INET_DEBUG +#define INET_DEBUG LWIP_DBG_OFF +#endif + +/** + * IP_DEBUG: Enable debugging for IP. + */ +#ifndef IP_DEBUG +#define IP_DEBUG LWIP_DBG_OFF +#endif + +/** + * IP_REASS_DEBUG: Enable debugging in ip_frag.c for both frag & reass. + */ +#ifndef IP_REASS_DEBUG +#define IP_REASS_DEBUG LWIP_DBG_OFF +#endif + +/** + * RAW_DEBUG: Enable debugging in raw.c. + */ +#ifndef RAW_DEBUG +#define RAW_DEBUG LWIP_DBG_OFF +#endif + +/** + * MEM_DEBUG: Enable debugging in mem.c. + */ +#ifndef MEM_DEBUG +#define MEM_DEBUG LWIP_DBG_OFF +#endif + +/** + * MEMP_DEBUG: Enable debugging in memp.c. + */ +#ifndef MEMP_DEBUG +#define MEMP_DEBUG LWIP_DBG_OFF +#endif + +/** + * SYS_DEBUG: Enable debugging in sys.c. + */ +#ifndef SYS_DEBUG +#define SYS_DEBUG LWIP_DBG_OFF +#endif + +/** + * TIMERS_DEBUG: Enable debugging in timers.c. + */ +#ifndef TIMERS_DEBUG +#define TIMERS_DEBUG LWIP_DBG_OFF +#endif + +/** + * TCP_DEBUG: Enable debugging for TCP. + */ +#ifndef TCP_DEBUG +#define TCP_DEBUG LWIP_DBG_OFF +#endif + +/** + * TCP_INPUT_DEBUG: Enable debugging in tcp_in.c for incoming debug. + */ +#ifndef TCP_INPUT_DEBUG +#define TCP_INPUT_DEBUG LWIP_DBG_OFF +#endif + +/** + * TCP_FR_DEBUG: Enable debugging in tcp_in.c for fast retransmit. + */ +#ifndef TCP_FR_DEBUG +#define TCP_FR_DEBUG LWIP_DBG_OFF +#endif + +/** + * TCP_RTO_DEBUG: Enable debugging in TCP for retransmit + * timeout. + */ +#ifndef TCP_RTO_DEBUG +#define TCP_RTO_DEBUG LWIP_DBG_OFF +#endif + +/** + * TCP_CWND_DEBUG: Enable debugging for TCP congestion window. + */ +#ifndef TCP_CWND_DEBUG +#define TCP_CWND_DEBUG LWIP_DBG_OFF +#endif + +/** + * TCP_WND_DEBUG: Enable debugging in tcp_in.c for window updating. + */ +#ifndef TCP_WND_DEBUG +#define TCP_WND_DEBUG LWIP_DBG_OFF +#endif + +/** + * TCP_OUTPUT_DEBUG: Enable debugging in tcp_out.c output functions. + */ +#ifndef TCP_OUTPUT_DEBUG +#define TCP_OUTPUT_DEBUG LWIP_DBG_OFF +#endif + +/** + * TCP_RST_DEBUG: Enable debugging for TCP with the RST message. + */ +#ifndef TCP_RST_DEBUG +#define TCP_RST_DEBUG LWIP_DBG_OFF +#endif + +/** + * TCP_QLEN_DEBUG: Enable debugging for TCP queue lengths. + */ +#ifndef TCP_QLEN_DEBUG +#define TCP_QLEN_DEBUG LWIP_DBG_OFF +#endif + +/** + * UDP_DEBUG: Enable debugging in UDP. + */ +#ifndef UDP_DEBUG +#define UDP_DEBUG LWIP_DBG_OFF +#endif + +/** + * TCPIP_DEBUG: Enable debugging in tcpip.c. + */ +#ifndef TCPIP_DEBUG +#define TCPIP_DEBUG LWIP_DBG_OFF +#endif + +/** + * PPP_DEBUG: Enable debugging for PPP. + */ +#ifndef PPP_DEBUG +#define PPP_DEBUG LWIP_DBG_OFF +#endif + +/** + * SLIP_DEBUG: Enable debugging in slipif.c. + */ +#ifndef SLIP_DEBUG +#define SLIP_DEBUG LWIP_DBG_OFF +#endif + +/** + * DHCP_DEBUG: Enable debugging in dhcp.c. + */ +#ifndef DHCP_DEBUG +#define DHCP_DEBUG LWIP_DBG_OFF +#endif + +/** + * AUTOIP_DEBUG: Enable debugging in autoip.c. + */ +#ifndef AUTOIP_DEBUG +#define AUTOIP_DEBUG LWIP_DBG_OFF +#endif + +/** + * SNMP_MSG_DEBUG: Enable debugging for SNMP messages. + */ +#ifndef SNMP_MSG_DEBUG +#define SNMP_MSG_DEBUG LWIP_DBG_OFF +#endif + +/** + * SNMP_MIB_DEBUG: Enable debugging for SNMP MIBs. + */ +#ifndef SNMP_MIB_DEBUG +#define SNMP_MIB_DEBUG LWIP_DBG_OFF +#endif + +/** + * DNS_DEBUG: Enable debugging for DNS. + */ +#ifndef DNS_DEBUG +#define DNS_DEBUG LWIP_DBG_OFF +#endif + +#endif /* __LWIP_OPT_H__ */ diff --git a/features/unsupported/net/lwip/lwip/include/lwip/pbuf.h b/features/unsupported/net/lwip/lwip/include/lwip/pbuf.h new file mode 100644 index 00000000000..3b1d608b9cb --- /dev/null +++ b/features/unsupported/net/lwip/lwip/include/lwip/pbuf.h @@ -0,0 +1,154 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ + +#ifndef __LWIP_PBUF_H__ +#define __LWIP_PBUF_H__ + +#include "lwip/opt.h" +#include "lwip/err.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** Currently, the pbuf_custom code is only needed for one specific configuration + * of IP_FRAG */ +#define LWIP_SUPPORT_CUSTOM_PBUF (IP_FRAG && !IP_FRAG_USES_STATIC_BUF && !LWIP_NETIF_TX_SINGLE_PBUF) + +#define PBUF_TRANSPORT_HLEN 20 +#define PBUF_IP_HLEN 20 + +typedef enum { + PBUF_TRANSPORT, + PBUF_IP, + PBUF_LINK, + PBUF_RAW +} pbuf_layer; + +typedef enum { + PBUF_RAM, /* pbuf data is stored in RAM */ + PBUF_ROM, /* pbuf data is stored in ROM */ + PBUF_REF, /* pbuf comes from the pbuf pool */ + PBUF_POOL /* pbuf payload refers to RAM */ +} pbuf_type; + + +/** indicates this packet's data should be immediately passed to the application */ +#define PBUF_FLAG_PUSH 0x01U +/** indicates this is a custom pbuf: pbuf_free and pbuf_header handle such a + a pbuf differently */ +#define PBUF_FLAG_IS_CUSTOM 0x02U +/** indicates this pbuf is UDP multicast to be looped back */ +#define PBUF_FLAG_MCASTLOOP 0x04U + +struct pbuf { + /** next pbuf in singly linked pbuf chain */ + struct pbuf *next; + + /** pointer to the actual data in the buffer */ + void *payload; + + /** + * total length of this buffer and all next buffers in chain + * belonging to the same packet. + * + * For non-queue packet chains this is the invariant: + * p->tot_len == p->len + (p->next? p->next->tot_len: 0) + */ + u16_t tot_len; + + /** length of this buffer */ + u16_t len; + + /** pbuf_type as u8_t instead of enum to save space */ + u8_t /*pbuf_type*/ type; + + /** misc flags */ + u8_t flags; + + /** + * the reference count always equals the number of pointers + * that refer to this pbuf. This can be pointers from an application, + * the stack itself, or pbuf->next pointers from a chain. + */ + u16_t ref; +}; + +#if LWIP_SUPPORT_CUSTOM_PBUF +/** Prototype for a function to free a custom pbuf */ +typedef void (*pbuf_free_custom_fn)(struct pbuf *p); + +/** A custom pbuf: like a pbuf, but following a function pointer to free it. */ +struct pbuf_custom { + /** The actual pbuf */ + struct pbuf pbuf; + /** This function is called when pbuf_free deallocates this pbuf(_custom) */ + pbuf_free_custom_fn custom_free_function; +}; +#endif /* LWIP_SUPPORT_CUSTOM_PBUF */ + +/* Initializes the pbuf module. This call is empty for now, but may not be in future. */ +#define pbuf_init() + +struct pbuf *pbuf_alloc(pbuf_layer l, u16_t length, pbuf_type type); +#if LWIP_SUPPORT_CUSTOM_PBUF +struct pbuf *pbuf_alloced_custom(pbuf_layer l, u16_t length, pbuf_type type, + struct pbuf_custom *p, void *payload_mem, + u16_t payload_mem_len); +#endif /* LWIP_SUPPORT_CUSTOM_PBUF */ +void pbuf_realloc(struct pbuf *p, u16_t size); +u8_t pbuf_header(struct pbuf *p, s16_t header_size); +void pbuf_ref(struct pbuf *p); +u8_t pbuf_free(struct pbuf *p); +u8_t pbuf_clen(struct pbuf *p); +void pbuf_cat(struct pbuf *head, struct pbuf *tail); +void pbuf_chain(struct pbuf *head, struct pbuf *tail); +struct pbuf *pbuf_dechain(struct pbuf *p); +err_t pbuf_copy(struct pbuf *p_to, struct pbuf *p_from); +u16_t pbuf_copy_partial(struct pbuf *p, void *dataptr, u16_t len, u16_t offset); +err_t pbuf_take(struct pbuf *buf, const void *dataptr, u16_t len); +struct pbuf *pbuf_coalesce(struct pbuf *p, pbuf_layer layer); +#if LWIP_CHECKSUM_ON_COPY +err_t pbuf_fill_chksum(struct pbuf *p, u16_t start_offset, const void *dataptr, + u16_t len, u16_t *chksum); +#endif /* LWIP_CHECKSUM_ON_COPY */ + +u8_t pbuf_get_at(struct pbuf* p, u16_t offset); +u16_t pbuf_memcmp(struct pbuf* p, u16_t offset, const void* s2, u16_t n); +u16_t pbuf_memfind(struct pbuf* p, const void* mem, u16_t mem_len, u16_t start_offset); +u16_t pbuf_strstr(struct pbuf* p, const char* substr); + +#ifdef __cplusplus +} +#endif + +#endif /* __LWIP_PBUF_H__ */ diff --git a/features/unsupported/net/lwip/lwip/include/lwip/raw.h b/features/unsupported/net/lwip/lwip/include/lwip/raw.h new file mode 100644 index 00000000000..17d0a1c5406 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/include/lwip/raw.h @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef __LWIP_RAW_H__ +#define __LWIP_RAW_H__ + +#include "lwip/opt.h" + +#if LWIP_RAW /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/pbuf.h" +#include "lwip/def.h" +#include "lwip/ip.h" +#include "lwip/ip_addr.h" + +#ifdef __cplusplus +extern "C" { +#endif + +struct raw_pcb; + +/** Function prototype for raw pcb receive callback functions. + * @param arg user supplied argument (raw_pcb.recv_arg) + * @param pcb the raw_pcb which received data + * @param p the packet buffer that was received + * @param addr the remote IP address from which the packet was received + * @return 1 if the packet was 'eaten' (aka. deleted), + * 0 if the packet lives on + * If returning 1, the callback is responsible for freeing the pbuf + * if it's not used any more. + */ +typedef u8_t (*raw_recv_fn)(void *arg, struct raw_pcb *pcb, struct pbuf *p, + ip_addr_t *addr); + +struct raw_pcb { + /* Common members of all PCB types */ + IP_PCB; + + struct raw_pcb *next; + + u8_t protocol; + + /** receive callback function */ + raw_recv_fn recv; + /* user-supplied argument for the recv callback */ + void *recv_arg; +}; + +/* The following functions is the application layer interface to the + RAW code. */ +struct raw_pcb * raw_new (u8_t proto); +void raw_remove (struct raw_pcb *pcb); +err_t raw_bind (struct raw_pcb *pcb, ip_addr_t *ipaddr); +err_t raw_connect (struct raw_pcb *pcb, ip_addr_t *ipaddr); + +void raw_recv (struct raw_pcb *pcb, raw_recv_fn recv, void *recv_arg); +err_t raw_sendto (struct raw_pcb *pcb, struct pbuf *p, ip_addr_t *ipaddr); +err_t raw_send (struct raw_pcb *pcb, struct pbuf *p); + +/* The following functions are the lower layer interface to RAW. */ +u8_t raw_input (struct pbuf *p, struct netif *inp); +#define raw_init() /* Compatibility define, not init needed. */ + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_RAW */ + +#endif /* __LWIP_RAW_H__ */ diff --git a/features/unsupported/net/lwip/lwip/include/lwip/sio.h b/features/unsupported/net/lwip/lwip/include/lwip/sio.h new file mode 100644 index 00000000000..28ae2f225d6 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/include/lwip/sio.h @@ -0,0 +1,141 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + */ + +/* + * This is the interface to the platform specific serial IO module + * It needs to be implemented by those platforms which need SLIP or PPP + */ + +#ifndef __SIO_H__ +#define __SIO_H__ + +#include "lwip/arch.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* If you want to define sio_fd_t elsewhere or differently, + define this in your cc.h file. */ +#ifndef __sio_fd_t_defined +typedef void * sio_fd_t; +#endif + +/* The following functions can be defined to something else in your cc.h file + or be implemented in your custom sio.c file. */ + +#ifndef sio_open +/** + * Opens a serial device for communication. + * + * @param devnum device number + * @return handle to serial device if successful, NULL otherwise + */ +sio_fd_t sio_open(u8_t devnum); +#endif + +#ifndef sio_send +/** + * Sends a single character to the serial device. + * + * @param c character to send + * @param fd serial device handle + * + * @note This function will block until the character can be sent. + */ +void sio_send(u8_t c, sio_fd_t fd); +#endif + +#ifndef sio_recv +/** + * Receives a single character from the serial device. + * + * @param fd serial device handle + * + * @note This function will block until a character is received. + */ +u8_t sio_recv(sio_fd_t fd); +#endif + +#ifndef sio_read +/** + * Reads from the serial device. + * + * @param fd serial device handle + * @param data pointer to data buffer for receiving + * @param len maximum length (in bytes) of data to receive + * @return number of bytes actually received - may be 0 if aborted by sio_read_abort + * + * @note This function will block until data can be received. The blocking + * can be cancelled by calling sio_read_abort(). + */ +u32_t sio_read(sio_fd_t fd, u8_t *data, u32_t len); +#endif + +#ifndef sio_tryread +/** + * Tries to read from the serial device. Same as sio_read but returns + * immediately if no data is available and never blocks. + * + * @param fd serial device handle + * @param data pointer to data buffer for receiving + * @param len maximum length (in bytes) of data to receive + * @return number of bytes actually received + */ +u32_t sio_tryread(sio_fd_t fd, u8_t *data, u32_t len); +#endif + +#ifndef sio_write +/** + * Writes to the serial device. + * + * @param fd serial device handle + * @param data pointer to data to send + * @param len length (in bytes) of data to send + * @return number of bytes actually sent + * + * @note This function will block until all data can be sent. + */ +u32_t sio_write(sio_fd_t fd, u8_t *data, u32_t len); +#endif + +#ifndef sio_read_abort +/** + * Aborts a blocking sio_read() call. + * + * @param fd serial device handle + */ +void sio_read_abort(sio_fd_t fd); +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* __SIO_H__ */ diff --git a/features/unsupported/net/lwip/lwip/include/lwip/snmp.h b/features/unsupported/net/lwip/lwip/include/lwip/snmp.h new file mode 100644 index 00000000000..2ed043dd5f3 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/include/lwip/snmp.h @@ -0,0 +1,367 @@ +/* + * Copyright (c) 2001, 2002 Leon Woestenberg + * Copyright (c) 2001, 2002 Axon Digital Design B.V., The Netherlands. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Leon Woestenberg + * + */ +#ifndef __LWIP_SNMP_H__ +#define __LWIP_SNMP_H__ + +#include "lwip/opt.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#include "lwip/ip_addr.h" + +struct udp_pcb; +struct netif; + +/** + * @see RFC1213, "MIB-II, 6. Definitions" + */ +enum snmp_ifType { + snmp_ifType_other=1, /* none of the following */ + snmp_ifType_regular1822, + snmp_ifType_hdh1822, + snmp_ifType_ddn_x25, + snmp_ifType_rfc877_x25, + snmp_ifType_ethernet_csmacd, + snmp_ifType_iso88023_csmacd, + snmp_ifType_iso88024_tokenBus, + snmp_ifType_iso88025_tokenRing, + snmp_ifType_iso88026_man, + snmp_ifType_starLan, + snmp_ifType_proteon_10Mbit, + snmp_ifType_proteon_80Mbit, + snmp_ifType_hyperchannel, + snmp_ifType_fddi, + snmp_ifType_lapb, + snmp_ifType_sdlc, + snmp_ifType_ds1, /* T-1 */ + snmp_ifType_e1, /* european equiv. of T-1 */ + snmp_ifType_basicISDN, + snmp_ifType_primaryISDN, /* proprietary serial */ + snmp_ifType_propPointToPointSerial, + snmp_ifType_ppp, + snmp_ifType_softwareLoopback, + snmp_ifType_eon, /* CLNP over IP [11] */ + snmp_ifType_ethernet_3Mbit, + snmp_ifType_nsip, /* XNS over IP */ + snmp_ifType_slip, /* generic SLIP */ + snmp_ifType_ultra, /* ULTRA technologies */ + snmp_ifType_ds3, /* T-3 */ + snmp_ifType_sip, /* SMDS */ + snmp_ifType_frame_relay +}; + +#if LWIP_SNMP /* don't build if not configured for use in lwipopts.h */ + +/** SNMP "sysuptime" Interval */ +#define SNMP_SYSUPTIME_INTERVAL 10 + +/** fixed maximum length for object identifier type */ +#define LWIP_SNMP_OBJ_ID_LEN 32 + +/** internal object identifier representation */ +struct snmp_obj_id +{ + u8_t len; + s32_t id[LWIP_SNMP_OBJ_ID_LEN]; +}; + +/* system */ +void snmp_set_sysdesr(u8_t* str, u8_t* len); +void snmp_set_sysobjid(struct snmp_obj_id *oid); +void snmp_get_sysobjid_ptr(struct snmp_obj_id **oid); +void snmp_inc_sysuptime(void); +void snmp_add_sysuptime(u32_t value); +void snmp_get_sysuptime(u32_t *value); +void snmp_set_syscontact(u8_t *ocstr, u8_t *ocstrlen); +void snmp_set_sysname(u8_t *ocstr, u8_t *ocstrlen); +void snmp_set_syslocation(u8_t *ocstr, u8_t *ocstrlen); + +/* network interface */ +void snmp_add_ifinoctets(struct netif *ni, u32_t value); +void snmp_inc_ifinucastpkts(struct netif *ni); +void snmp_inc_ifinnucastpkts(struct netif *ni); +void snmp_inc_ifindiscards(struct netif *ni); +void snmp_add_ifoutoctets(struct netif *ni, u32_t value); +void snmp_inc_ifoutucastpkts(struct netif *ni); +void snmp_inc_ifoutnucastpkts(struct netif *ni); +void snmp_inc_ifoutdiscards(struct netif *ni); +void snmp_inc_iflist(void); +void snmp_dec_iflist(void); + +/* ARP (for atTable and ipNetToMediaTable) */ +void snmp_insert_arpidx_tree(struct netif *ni, ip_addr_t *ip); +void snmp_delete_arpidx_tree(struct netif *ni, ip_addr_t *ip); + +/* IP */ +void snmp_inc_ipinreceives(void); +void snmp_inc_ipinhdrerrors(void); +void snmp_inc_ipinaddrerrors(void); +void snmp_inc_ipforwdatagrams(void); +void snmp_inc_ipinunknownprotos(void); +void snmp_inc_ipindiscards(void); +void snmp_inc_ipindelivers(void); +void snmp_inc_ipoutrequests(void); +void snmp_inc_ipoutdiscards(void); +void snmp_inc_ipoutnoroutes(void); +void snmp_inc_ipreasmreqds(void); +void snmp_inc_ipreasmoks(void); +void snmp_inc_ipreasmfails(void); +void snmp_inc_ipfragoks(void); +void snmp_inc_ipfragfails(void); +void snmp_inc_ipfragcreates(void); +void snmp_inc_iproutingdiscards(void); +void snmp_insert_ipaddridx_tree(struct netif *ni); +void snmp_delete_ipaddridx_tree(struct netif *ni); +void snmp_insert_iprteidx_tree(u8_t dflt, struct netif *ni); +void snmp_delete_iprteidx_tree(u8_t dflt, struct netif *ni); + +/* ICMP */ +void snmp_inc_icmpinmsgs(void); +void snmp_inc_icmpinerrors(void); +void snmp_inc_icmpindestunreachs(void); +void snmp_inc_icmpintimeexcds(void); +void snmp_inc_icmpinparmprobs(void); +void snmp_inc_icmpinsrcquenchs(void); +void snmp_inc_icmpinredirects(void); +void snmp_inc_icmpinechos(void); +void snmp_inc_icmpinechoreps(void); +void snmp_inc_icmpintimestamps(void); +void snmp_inc_icmpintimestampreps(void); +void snmp_inc_icmpinaddrmasks(void); +void snmp_inc_icmpinaddrmaskreps(void); +void snmp_inc_icmpoutmsgs(void); +void snmp_inc_icmpouterrors(void); +void snmp_inc_icmpoutdestunreachs(void); +void snmp_inc_icmpouttimeexcds(void); +void snmp_inc_icmpoutparmprobs(void); +void snmp_inc_icmpoutsrcquenchs(void); +void snmp_inc_icmpoutredirects(void); +void snmp_inc_icmpoutechos(void); +void snmp_inc_icmpoutechoreps(void); +void snmp_inc_icmpouttimestamps(void); +void snmp_inc_icmpouttimestampreps(void); +void snmp_inc_icmpoutaddrmasks(void); +void snmp_inc_icmpoutaddrmaskreps(void); + +/* TCP */ +void snmp_inc_tcpactiveopens(void); +void snmp_inc_tcppassiveopens(void); +void snmp_inc_tcpattemptfails(void); +void snmp_inc_tcpestabresets(void); +void snmp_inc_tcpinsegs(void); +void snmp_inc_tcpoutsegs(void); +void snmp_inc_tcpretranssegs(void); +void snmp_inc_tcpinerrs(void); +void snmp_inc_tcpoutrsts(void); + +/* UDP */ +void snmp_inc_udpindatagrams(void); +void snmp_inc_udpnoports(void); +void snmp_inc_udpinerrors(void); +void snmp_inc_udpoutdatagrams(void); +void snmp_insert_udpidx_tree(struct udp_pcb *pcb); +void snmp_delete_udpidx_tree(struct udp_pcb *pcb); + +/* SNMP */ +void snmp_inc_snmpinpkts(void); +void snmp_inc_snmpoutpkts(void); +void snmp_inc_snmpinbadversions(void); +void snmp_inc_snmpinbadcommunitynames(void); +void snmp_inc_snmpinbadcommunityuses(void); +void snmp_inc_snmpinasnparseerrs(void); +void snmp_inc_snmpintoobigs(void); +void snmp_inc_snmpinnosuchnames(void); +void snmp_inc_snmpinbadvalues(void); +void snmp_inc_snmpinreadonlys(void); +void snmp_inc_snmpingenerrs(void); +void snmp_add_snmpintotalreqvars(u8_t value); +void snmp_add_snmpintotalsetvars(u8_t value); +void snmp_inc_snmpingetrequests(void); +void snmp_inc_snmpingetnexts(void); +void snmp_inc_snmpinsetrequests(void); +void snmp_inc_snmpingetresponses(void); +void snmp_inc_snmpintraps(void); +void snmp_inc_snmpouttoobigs(void); +void snmp_inc_snmpoutnosuchnames(void); +void snmp_inc_snmpoutbadvalues(void); +void snmp_inc_snmpoutgenerrs(void); +void snmp_inc_snmpoutgetrequests(void); +void snmp_inc_snmpoutgetnexts(void); +void snmp_inc_snmpoutsetrequests(void); +void snmp_inc_snmpoutgetresponses(void); +void snmp_inc_snmpouttraps(void); +void snmp_get_snmpgrpid_ptr(struct snmp_obj_id **oid); +void snmp_set_snmpenableauthentraps(u8_t *value); +void snmp_get_snmpenableauthentraps(u8_t *value); + +/* LWIP_SNMP support not available */ +/* define everything to be empty */ +#else + +/* system */ +#define snmp_set_sysdesr(str, len) +#define snmp_set_sysobjid(oid); +#define snmp_get_sysobjid_ptr(oid) +#define snmp_inc_sysuptime() +#define snmp_add_sysuptime(value) +#define snmp_get_sysuptime(value) +#define snmp_set_syscontact(ocstr, ocstrlen); +#define snmp_set_sysname(ocstr, ocstrlen); +#define snmp_set_syslocation(ocstr, ocstrlen); + +/* network interface */ +#define snmp_add_ifinoctets(ni,value) +#define snmp_inc_ifinucastpkts(ni) +#define snmp_inc_ifinnucastpkts(ni) +#define snmp_inc_ifindiscards(ni) +#define snmp_add_ifoutoctets(ni,value) +#define snmp_inc_ifoutucastpkts(ni) +#define snmp_inc_ifoutnucastpkts(ni) +#define snmp_inc_ifoutdiscards(ni) +#define snmp_inc_iflist() +#define snmp_dec_iflist() + +/* ARP */ +#define snmp_insert_arpidx_tree(ni,ip) +#define snmp_delete_arpidx_tree(ni,ip) + +/* IP */ +#define snmp_inc_ipinreceives() +#define snmp_inc_ipinhdrerrors() +#define snmp_inc_ipinaddrerrors() +#define snmp_inc_ipforwdatagrams() +#define snmp_inc_ipinunknownprotos() +#define snmp_inc_ipindiscards() +#define snmp_inc_ipindelivers() +#define snmp_inc_ipoutrequests() +#define snmp_inc_ipoutdiscards() +#define snmp_inc_ipoutnoroutes() +#define snmp_inc_ipreasmreqds() +#define snmp_inc_ipreasmoks() +#define snmp_inc_ipreasmfails() +#define snmp_inc_ipfragoks() +#define snmp_inc_ipfragfails() +#define snmp_inc_ipfragcreates() +#define snmp_inc_iproutingdiscards() +#define snmp_insert_ipaddridx_tree(ni) +#define snmp_delete_ipaddridx_tree(ni) +#define snmp_insert_iprteidx_tree(dflt, ni) +#define snmp_delete_iprteidx_tree(dflt, ni) + +/* ICMP */ +#define snmp_inc_icmpinmsgs() +#define snmp_inc_icmpinerrors() +#define snmp_inc_icmpindestunreachs() +#define snmp_inc_icmpintimeexcds() +#define snmp_inc_icmpinparmprobs() +#define snmp_inc_icmpinsrcquenchs() +#define snmp_inc_icmpinredirects() +#define snmp_inc_icmpinechos() +#define snmp_inc_icmpinechoreps() +#define snmp_inc_icmpintimestamps() +#define snmp_inc_icmpintimestampreps() +#define snmp_inc_icmpinaddrmasks() +#define snmp_inc_icmpinaddrmaskreps() +#define snmp_inc_icmpoutmsgs() +#define snmp_inc_icmpouterrors() +#define snmp_inc_icmpoutdestunreachs() +#define snmp_inc_icmpouttimeexcds() +#define snmp_inc_icmpoutparmprobs() +#define snmp_inc_icmpoutsrcquenchs() +#define snmp_inc_icmpoutredirects() +#define snmp_inc_icmpoutechos() +#define snmp_inc_icmpoutechoreps() +#define snmp_inc_icmpouttimestamps() +#define snmp_inc_icmpouttimestampreps() +#define snmp_inc_icmpoutaddrmasks() +#define snmp_inc_icmpoutaddrmaskreps() +/* TCP */ +#define snmp_inc_tcpactiveopens() +#define snmp_inc_tcppassiveopens() +#define snmp_inc_tcpattemptfails() +#define snmp_inc_tcpestabresets() +#define snmp_inc_tcpinsegs() +#define snmp_inc_tcpoutsegs() +#define snmp_inc_tcpretranssegs() +#define snmp_inc_tcpinerrs() +#define snmp_inc_tcpoutrsts() + +/* UDP */ +#define snmp_inc_udpindatagrams() +#define snmp_inc_udpnoports() +#define snmp_inc_udpinerrors() +#define snmp_inc_udpoutdatagrams() +#define snmp_insert_udpidx_tree(pcb) +#define snmp_delete_udpidx_tree(pcb) + +/* SNMP */ +#define snmp_inc_snmpinpkts() +#define snmp_inc_snmpoutpkts() +#define snmp_inc_snmpinbadversions() +#define snmp_inc_snmpinbadcommunitynames() +#define snmp_inc_snmpinbadcommunityuses() +#define snmp_inc_snmpinasnparseerrs() +#define snmp_inc_snmpintoobigs() +#define snmp_inc_snmpinnosuchnames() +#define snmp_inc_snmpinbadvalues() +#define snmp_inc_snmpinreadonlys() +#define snmp_inc_snmpingenerrs() +#define snmp_add_snmpintotalreqvars(value) +#define snmp_add_snmpintotalsetvars(value) +#define snmp_inc_snmpingetrequests() +#define snmp_inc_snmpingetnexts() +#define snmp_inc_snmpinsetrequests() +#define snmp_inc_snmpingetresponses() +#define snmp_inc_snmpintraps() +#define snmp_inc_snmpouttoobigs() +#define snmp_inc_snmpoutnosuchnames() +#define snmp_inc_snmpoutbadvalues() +#define snmp_inc_snmpoutgenerrs() +#define snmp_inc_snmpoutgetrequests() +#define snmp_inc_snmpoutgetnexts() +#define snmp_inc_snmpoutsetrequests() +#define snmp_inc_snmpoutgetresponses() +#define snmp_inc_snmpouttraps() +#define snmp_get_snmpgrpid_ptr(oid) +#define snmp_set_snmpenableauthentraps(value) +#define snmp_get_snmpenableauthentraps(value) + +#endif /* LWIP_SNMP */ + +#ifdef __cplusplus +} +#endif + +#endif /* __LWIP_SNMP_H__ */ diff --git a/features/unsupported/net/lwip/lwip/include/lwip/snmp_asn1.h b/features/unsupported/net/lwip/lwip/include/lwip/snmp_asn1.h new file mode 100644 index 00000000000..605fa3f16c9 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/include/lwip/snmp_asn1.h @@ -0,0 +1,101 @@ +/** + * @file + * Abstract Syntax Notation One (ISO 8824, 8825) codec. + */ + +/* + * Copyright (c) 2006 Axon Digital Design B.V., The Netherlands. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * Author: Christiaan Simons + */ + +#ifndef __LWIP_SNMP_ASN1_H__ +#define __LWIP_SNMP_ASN1_H__ + +#include "lwip/opt.h" +#include "lwip/err.h" +#include "lwip/pbuf.h" +#include "lwip/snmp.h" + +#if LWIP_SNMP + +#ifdef __cplusplus +extern "C" { +#endif + +#define SNMP_ASN1_UNIV (0) /* (!0x80 | !0x40) */ +#define SNMP_ASN1_APPLIC (0x40) /* (!0x80 | 0x40) */ +#define SNMP_ASN1_CONTXT (0x80) /* ( 0x80 | !0x40) */ + +#define SNMP_ASN1_CONSTR (0x20) /* ( 0x20) */ +#define SNMP_ASN1_PRIMIT (0) /* (!0x20) */ + +/* universal tags */ +#define SNMP_ASN1_INTEG 2 +#define SNMP_ASN1_OC_STR 4 +#define SNMP_ASN1_NUL 5 +#define SNMP_ASN1_OBJ_ID 6 +#define SNMP_ASN1_SEQ 16 + +/* application specific (SNMP) tags */ +#define SNMP_ASN1_IPADDR 0 /* octet string size(4) */ +#define SNMP_ASN1_COUNTER 1 /* u32_t */ +#define SNMP_ASN1_GAUGE 2 /* u32_t */ +#define SNMP_ASN1_TIMETICKS 3 /* u32_t */ +#define SNMP_ASN1_OPAQUE 4 /* octet string */ + +/* context specific (SNMP) tags */ +#define SNMP_ASN1_PDU_GET_REQ 0 +#define SNMP_ASN1_PDU_GET_NEXT_REQ 1 +#define SNMP_ASN1_PDU_GET_RESP 2 +#define SNMP_ASN1_PDU_SET_REQ 3 +#define SNMP_ASN1_PDU_TRAP 4 + +err_t snmp_asn1_dec_type(struct pbuf *p, u16_t ofs, u8_t *type); +err_t snmp_asn1_dec_length(struct pbuf *p, u16_t ofs, u8_t *octets_used, u16_t *length); +err_t snmp_asn1_dec_u32t(struct pbuf *p, u16_t ofs, u16_t len, u32_t *value); +err_t snmp_asn1_dec_s32t(struct pbuf *p, u16_t ofs, u16_t len, s32_t *value); +err_t snmp_asn1_dec_oid(struct pbuf *p, u16_t ofs, u16_t len, struct snmp_obj_id *oid); +err_t snmp_asn1_dec_raw(struct pbuf *p, u16_t ofs, u16_t len, u16_t raw_len, u8_t *raw); + +void snmp_asn1_enc_length_cnt(u16_t length, u8_t *octets_needed); +void snmp_asn1_enc_u32t_cnt(u32_t value, u16_t *octets_needed); +void snmp_asn1_enc_s32t_cnt(s32_t value, u16_t *octets_needed); +void snmp_asn1_enc_oid_cnt(u8_t ident_len, s32_t *ident, u16_t *octets_needed); +err_t snmp_asn1_enc_type(struct pbuf *p, u16_t ofs, u8_t type); +err_t snmp_asn1_enc_length(struct pbuf *p, u16_t ofs, u16_t length); +err_t snmp_asn1_enc_u32t(struct pbuf *p, u16_t ofs, u16_t octets_needed, u32_t value); +err_t snmp_asn1_enc_s32t(struct pbuf *p, u16_t ofs, u16_t octets_needed, s32_t value); +err_t snmp_asn1_enc_oid(struct pbuf *p, u16_t ofs, u8_t ident_len, s32_t *ident); +err_t snmp_asn1_enc_raw(struct pbuf *p, u16_t ofs, u16_t raw_len, u8_t *raw); + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_SNMP */ + +#endif /* __LWIP_SNMP_ASN1_H__ */ diff --git a/features/unsupported/net/lwip/lwip/include/lwip/snmp_msg.h b/features/unsupported/net/lwip/lwip/include/lwip/snmp_msg.h new file mode 100644 index 00000000000..1183e3a95b7 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/include/lwip/snmp_msg.h @@ -0,0 +1,315 @@ +/** + * @file + * SNMP Agent message handling structures. + */ + +/* + * Copyright (c) 2006 Axon Digital Design B.V., The Netherlands. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * Author: Christiaan Simons + */ + +#ifndef __LWIP_SNMP_MSG_H__ +#define __LWIP_SNMP_MSG_H__ + +#include "lwip/opt.h" +#include "lwip/snmp.h" +#include "lwip/snmp_structs.h" +#include "lwip/ip_addr.h" +#include "lwip/err.h" + +#if LWIP_SNMP + +#if SNMP_PRIVATE_MIB +/* When using a private MIB, you have to create a file 'private_mib.h' that contains + * a 'struct mib_array_node mib_private' which contains your MIB. */ +#include "private_mib.h" +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/* The listen port of the SNMP agent. Clients have to make their requests to + this port. Most standard clients won't work if you change this! */ +#ifndef SNMP_IN_PORT +#define SNMP_IN_PORT 161 +#endif +/* The remote port the SNMP agent sends traps to. Most standard trap sinks won't + work if you change this! */ +#ifndef SNMP_TRAP_PORT +#define SNMP_TRAP_PORT 162 +#endif + +#define SNMP_ES_NOERROR 0 +#define SNMP_ES_TOOBIG 1 +#define SNMP_ES_NOSUCHNAME 2 +#define SNMP_ES_BADVALUE 3 +#define SNMP_ES_READONLY 4 +#define SNMP_ES_GENERROR 5 + +#define SNMP_GENTRAP_COLDSTART 0 +#define SNMP_GENTRAP_WARMSTART 1 +#define SNMP_GENTRAP_AUTHFAIL 4 +#define SNMP_GENTRAP_ENTERPRISESPC 6 + +struct snmp_varbind +{ + /* next pointer, NULL for last in list */ + struct snmp_varbind *next; + /* previous pointer, NULL for first in list */ + struct snmp_varbind *prev; + + /* object identifier length (in s32_t) */ + u8_t ident_len; + /* object identifier array */ + s32_t *ident; + + /* object value ASN1 type */ + u8_t value_type; + /* object value length (in u8_t) */ + u8_t value_len; + /* object value */ + void *value; + + /* encoding varbind seq length length */ + u8_t seqlenlen; + /* encoding object identifier length length */ + u8_t olenlen; + /* encoding object value length length */ + u8_t vlenlen; + /* encoding varbind seq length */ + u16_t seqlen; + /* encoding object identifier length */ + u16_t olen; + /* encoding object value length */ + u16_t vlen; +}; + +struct snmp_varbind_root +{ + struct snmp_varbind *head; + struct snmp_varbind *tail; + /* number of variable bindings in list */ + u8_t count; + /* encoding varbind-list seq length length */ + u8_t seqlenlen; + /* encoding varbind-list seq length */ + u16_t seqlen; +}; + +/** output response message header length fields */ +struct snmp_resp_header_lengths +{ + /* encoding error-index length length */ + u8_t erridxlenlen; + /* encoding error-status length length */ + u8_t errstatlenlen; + /* encoding request id length length */ + u8_t ridlenlen; + /* encoding pdu length length */ + u8_t pdulenlen; + /* encoding community length length */ + u8_t comlenlen; + /* encoding version length length */ + u8_t verlenlen; + /* encoding sequence length length */ + u8_t seqlenlen; + + /* encoding error-index length */ + u16_t erridxlen; + /* encoding error-status length */ + u16_t errstatlen; + /* encoding request id length */ + u16_t ridlen; + /* encoding pdu length */ + u16_t pdulen; + /* encoding community length */ + u16_t comlen; + /* encoding version length */ + u16_t verlen; + /* encoding sequence length */ + u16_t seqlen; +}; + +/** output response message header length fields */ +struct snmp_trap_header_lengths +{ + /* encoding timestamp length length */ + u8_t tslenlen; + /* encoding specific-trap length length */ + u8_t strplenlen; + /* encoding generic-trap length length */ + u8_t gtrplenlen; + /* encoding agent-addr length length */ + u8_t aaddrlenlen; + /* encoding enterprise-id length length */ + u8_t eidlenlen; + /* encoding pdu length length */ + u8_t pdulenlen; + /* encoding community length length */ + u8_t comlenlen; + /* encoding version length length */ + u8_t verlenlen; + /* encoding sequence length length */ + u8_t seqlenlen; + + /* encoding timestamp length */ + u16_t tslen; + /* encoding specific-trap length */ + u16_t strplen; + /* encoding generic-trap length */ + u16_t gtrplen; + /* encoding agent-addr length */ + u16_t aaddrlen; + /* encoding enterprise-id length */ + u16_t eidlen; + /* encoding pdu length */ + u16_t pdulen; + /* encoding community length */ + u16_t comlen; + /* encoding version length */ + u16_t verlen; + /* encoding sequence length */ + u16_t seqlen; +}; + +/* Accepting new SNMP messages. */ +#define SNMP_MSG_EMPTY 0 +/* Search for matching object for variable binding. */ +#define SNMP_MSG_SEARCH_OBJ 1 +/* Perform SNMP operation on in-memory object. + Pass-through states, for symmetry only. */ +#define SNMP_MSG_INTERNAL_GET_OBJDEF 2 +#define SNMP_MSG_INTERNAL_GET_VALUE 3 +#define SNMP_MSG_INTERNAL_SET_TEST 4 +#define SNMP_MSG_INTERNAL_GET_OBJDEF_S 5 +#define SNMP_MSG_INTERNAL_SET_VALUE 6 +/* Perform SNMP operation on object located externally. + In theory this could be used for building a proxy agent. + Practical use is for an enterprise spc. app. gateway. */ +#define SNMP_MSG_EXTERNAL_GET_OBJDEF 7 +#define SNMP_MSG_EXTERNAL_GET_VALUE 8 +#define SNMP_MSG_EXTERNAL_SET_TEST 9 +#define SNMP_MSG_EXTERNAL_GET_OBJDEF_S 10 +#define SNMP_MSG_EXTERNAL_SET_VALUE 11 + +#define SNMP_COMMUNITY_STR_LEN 64 +struct snmp_msg_pstat +{ + /* lwIP local port (161) binding */ + struct udp_pcb *pcb; + /* source IP address */ + ip_addr_t sip; + /* source UDP port */ + u16_t sp; + /* request type */ + u8_t rt; + /* request ID */ + s32_t rid; + /* error status */ + s32_t error_status; + /* error index */ + s32_t error_index; + /* community name (zero terminated) */ + u8_t community[SNMP_COMMUNITY_STR_LEN + 1]; + /* community string length (exclusive zero term) */ + u8_t com_strlen; + /* one out of MSG_EMPTY, MSG_DEMUX, MSG_INTERNAL, MSG_EXTERNAL_x */ + u8_t state; + /* saved arguments for MSG_EXTERNAL_x */ + struct mib_external_node *ext_mib_node; + struct snmp_name_ptr ext_name_ptr; + struct obj_def ext_object_def; + struct snmp_obj_id ext_oid; + /* index into input variable binding list */ + u8_t vb_idx; + /* ptr into input variable binding list */ + struct snmp_varbind *vb_ptr; + /* list of variable bindings from input */ + struct snmp_varbind_root invb; + /* list of variable bindings to output */ + struct snmp_varbind_root outvb; + /* output response lengths used in ASN encoding */ + struct snmp_resp_header_lengths rhl; +}; + +struct snmp_msg_trap +{ + /* lwIP local port (161) binding */ + struct udp_pcb *pcb; + /* destination IP address in network order */ + ip_addr_t dip; + + /* source enterprise ID (sysObjectID) */ + struct snmp_obj_id *enterprise; + /* source IP address, raw network order format */ + u8_t sip_raw[4]; + /* generic trap code */ + u32_t gen_trap; + /* specific trap code */ + u32_t spc_trap; + /* timestamp */ + u32_t ts; + /* list of variable bindings to output */ + struct snmp_varbind_root outvb; + /* output trap lengths used in ASN encoding */ + struct snmp_trap_header_lengths thl; +}; + +/** Agent Version constant, 0 = v1 oddity */ +extern const s32_t snmp_version; +/** Agent default "public" community string */ +extern const char snmp_publiccommunity[7]; + +extern struct snmp_msg_trap trap_msg; + +/** Agent setup, start listening to port 161. */ +void snmp_init(void); +void snmp_trap_dst_enable(u8_t dst_idx, u8_t enable); +void snmp_trap_dst_ip_set(u8_t dst_idx, ip_addr_t *dst); + +/** Varbind-list functions. */ +struct snmp_varbind* snmp_varbind_alloc(struct snmp_obj_id *oid, u8_t type, u8_t len); +void snmp_varbind_free(struct snmp_varbind *vb); +void snmp_varbind_list_free(struct snmp_varbind_root *root); +void snmp_varbind_tail_add(struct snmp_varbind_root *root, struct snmp_varbind *vb); +struct snmp_varbind* snmp_varbind_tail_remove(struct snmp_varbind_root *root); + +/** Handle an internal (recv) or external (private response) event. */ +void snmp_msg_event(u8_t request_id); +err_t snmp_send_response(struct snmp_msg_pstat *m_stat); +err_t snmp_send_trap(s8_t generic_trap, struct snmp_obj_id *eoid, s32_t specific_trap); +void snmp_coldstart_trap(void); +void snmp_authfail_trap(void); + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_SNMP */ + +#endif /* __LWIP_SNMP_MSG_H__ */ diff --git a/features/unsupported/net/lwip/lwip/include/lwip/snmp_structs.h b/features/unsupported/net/lwip/lwip/include/lwip/snmp_structs.h new file mode 100644 index 00000000000..0d3b46a928d --- /dev/null +++ b/features/unsupported/net/lwip/lwip/include/lwip/snmp_structs.h @@ -0,0 +1,268 @@ +/** + * @file + * Generic MIB tree structures. + * + * @todo namespace prefixes + */ + +/* + * Copyright (c) 2006 Axon Digital Design B.V., The Netherlands. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * Author: Christiaan Simons + */ + +#ifndef __LWIP_SNMP_STRUCTS_H__ +#define __LWIP_SNMP_STRUCTS_H__ + +#include "lwip/opt.h" + +#if LWIP_SNMP /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/snmp.h" + +#if SNMP_PRIVATE_MIB +/* When using a private MIB, you have to create a file 'private_mib.h' that contains + * a 'struct mib_array_node mib_private' which contains your MIB. */ +#include "private_mib.h" +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/* MIB object instance */ +#define MIB_OBJECT_NONE 0 +#define MIB_OBJECT_SCALAR 1 +#define MIB_OBJECT_TAB 2 + +/* MIB access types */ +#define MIB_ACCESS_READ 1 +#define MIB_ACCESS_WRITE 2 + +/* MIB object access */ +#define MIB_OBJECT_READ_ONLY MIB_ACCESS_READ +#define MIB_OBJECT_READ_WRITE (MIB_ACCESS_READ | MIB_ACCESS_WRITE) +#define MIB_OBJECT_WRITE_ONLY MIB_ACCESS_WRITE +#define MIB_OBJECT_NOT_ACCESSIBLE 0 + +/** object definition returned by (get_object_def)() */ +struct obj_def +{ + /* MIB_OBJECT_NONE (0), MIB_OBJECT_SCALAR (1), MIB_OBJECT_TAB (2) */ + u8_t instance; + /* 0 read-only, 1 read-write, 2 write-only, 3 not-accessible */ + u8_t access; + /* ASN type for this object */ + u8_t asn_type; + /* value length (host length) */ + u16_t v_len; + /* length of instance part of supplied object identifier */ + u8_t id_inst_len; + /* instance part of supplied object identifier */ + s32_t *id_inst_ptr; +}; + +struct snmp_name_ptr +{ + u8_t ident_len; + s32_t *ident; +}; + +/** MIB const scalar (.0) node */ +#define MIB_NODE_SC 0x01 +/** MIB const array node */ +#define MIB_NODE_AR 0x02 +/** MIB array node (mem_malloced from RAM) */ +#define MIB_NODE_RA 0x03 +/** MIB list root node (mem_malloced from RAM) */ +#define MIB_NODE_LR 0x04 +/** MIB node for external objects */ +#define MIB_NODE_EX 0x05 + +/** node "base class" layout, the mandatory fields for a node */ +struct mib_node +{ + /** returns struct obj_def for the given object identifier */ + void (*get_object_def)(u8_t ident_len, s32_t *ident, struct obj_def *od); + /** returns object value for the given object identifier, + @note the caller must allocate at least len bytes for the value */ + void (*get_value)(struct obj_def *od, u16_t len, void *value); + /** tests length and/or range BEFORE setting */ + u8_t (*set_test)(struct obj_def *od, u16_t len, void *value); + /** sets object value, only to be called when set_test() */ + void (*set_value)(struct obj_def *od, u16_t len, void *value); + /** One out of MIB_NODE_AR, MIB_NODE_LR or MIB_NODE_EX */ + u8_t node_type; + /* array or max list length */ + u16_t maxlength; +}; + +/** derived node for scalars .0 index */ +typedef struct mib_node mib_scalar_node; + +/** derived node, points to a fixed size const array + of sub-identifiers plus a 'child' pointer */ +struct mib_array_node +{ + /* inherited "base class" members */ + void (*get_object_def)(u8_t ident_len, s32_t *ident, struct obj_def *od); + void (*get_value)(struct obj_def *od, u16_t len, void *value); + u8_t (*set_test)(struct obj_def *od, u16_t len, void *value); + void (*set_value)(struct obj_def *od, u16_t len, void *value); + + u8_t node_type; + u16_t maxlength; + + /* additional struct members */ + const s32_t *objid; + struct mib_node* const *nptr; +}; + +/** derived node, points to a fixed size mem_malloced array + of sub-identifiers plus a 'child' pointer */ +struct mib_ram_array_node +{ + /* inherited "base class" members */ + void (*get_object_def)(u8_t ident_len, s32_t *ident, struct obj_def *od); + void (*get_value)(struct obj_def *od, u16_t len, void *value); + u8_t (*set_test)(struct obj_def *od, u16_t len, void *value); + void (*set_value)(struct obj_def *od, u16_t len, void *value); + + u8_t node_type; + u16_t maxlength; + + /* aditional struct members */ + s32_t *objid; + struct mib_node **nptr; +}; + +struct mib_list_node +{ + struct mib_list_node *prev; + struct mib_list_node *next; + s32_t objid; + struct mib_node *nptr; +}; + +/** derived node, points to a doubly linked list + of sub-identifiers plus a 'child' pointer */ +struct mib_list_rootnode +{ + /* inherited "base class" members */ + void (*get_object_def)(u8_t ident_len, s32_t *ident, struct obj_def *od); + void (*get_value)(struct obj_def *od, u16_t len, void *value); + u8_t (*set_test)(struct obj_def *od, u16_t len, void *value); + void (*set_value)(struct obj_def *od, u16_t len, void *value); + + u8_t node_type; + u16_t maxlength; + + /* additional struct members */ + struct mib_list_node *head; + struct mib_list_node *tail; + /* counts list nodes in list */ + u16_t count; +}; + +/** derived node, has access functions for mib object in external memory or device + using 'tree_level' and 'idx', with a range 0 .. (level_length() - 1) */ +struct mib_external_node +{ + /* inherited "base class" members */ + void (*get_object_def)(u8_t ident_len, s32_t *ident, struct obj_def *od); + void (*get_value)(struct obj_def *od, u16_t len, void *value); + u8_t (*set_test)(struct obj_def *od, u16_t len, void *value); + void (*set_value)(struct obj_def *od, u16_t len, void *value); + + u8_t node_type; + u16_t maxlength; + + /* additional struct members */ + /** points to an external (in memory) record of some sort of addressing + information, passed to and interpreted by the funtions below */ + void* addr_inf; + /** tree levels under this node */ + u8_t tree_levels; + /** number of objects at this level */ + u16_t (*level_length)(void* addr_inf, u8_t level); + /** compares object sub identifier with external id + return zero when equal, nonzero when unequal */ + s32_t (*ident_cmp)(void* addr_inf, u8_t level, u16_t idx, s32_t sub_id); + void (*get_objid)(void* addr_inf, u8_t level, u16_t idx, s32_t *sub_id); + + /** async Questions */ + void (*get_object_def_q)(void* addr_inf, u8_t rid, u8_t ident_len, s32_t *ident); + void (*get_value_q)(u8_t rid, struct obj_def *od); + void (*set_test_q)(u8_t rid, struct obj_def *od); + void (*set_value_q)(u8_t rid, struct obj_def *od, u16_t len, void *value); + /** async Answers */ + void (*get_object_def_a)(u8_t rid, u8_t ident_len, s32_t *ident, struct obj_def *od); + void (*get_value_a)(u8_t rid, struct obj_def *od, u16_t len, void *value); + u8_t (*set_test_a)(u8_t rid, struct obj_def *od, u16_t len, void *value); + void (*set_value_a)(u8_t rid, struct obj_def *od, u16_t len, void *value); + /** async Panic Close (agent returns error reply, + e.g. used for external transaction cleanup) */ + void (*get_object_def_pc)(u8_t rid, u8_t ident_len, s32_t *ident); + void (*get_value_pc)(u8_t rid, struct obj_def *od); + void (*set_test_pc)(u8_t rid, struct obj_def *od); + void (*set_value_pc)(u8_t rid, struct obj_def *od); +}; + +/** export MIB tree from mib2.c */ +extern const struct mib_array_node internet; + +/** dummy function pointers for non-leaf MIB nodes from mib2.c */ +void noleafs_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od); +void noleafs_get_value(struct obj_def *od, u16_t len, void *value); +u8_t noleafs_set_test(struct obj_def *od, u16_t len, void *value); +void noleafs_set_value(struct obj_def *od, u16_t len, void *value); + +void snmp_oidtoip(s32_t *ident, ip_addr_t *ip); +void snmp_iptooid(ip_addr_t *ip, s32_t *ident); +void snmp_ifindextonetif(s32_t ifindex, struct netif **netif); +void snmp_netiftoifindex(struct netif *netif, s32_t *ifidx); + +struct mib_list_node* snmp_mib_ln_alloc(s32_t id); +void snmp_mib_ln_free(struct mib_list_node *ln); +struct mib_list_rootnode* snmp_mib_lrn_alloc(void); +void snmp_mib_lrn_free(struct mib_list_rootnode *lrn); + +s8_t snmp_mib_node_insert(struct mib_list_rootnode *rn, s32_t objid, struct mib_list_node **insn); +s8_t snmp_mib_node_find(struct mib_list_rootnode *rn, s32_t objid, struct mib_list_node **fn); +struct mib_list_rootnode *snmp_mib_node_delete(struct mib_list_rootnode *rn, struct mib_list_node *n); + +struct mib_node* snmp_search_tree(struct mib_node *node, u8_t ident_len, s32_t *ident, struct snmp_name_ptr *np); +struct mib_node* snmp_expand_tree(struct mib_node *node, u8_t ident_len, s32_t *ident, struct snmp_obj_id *oidret); +u8_t snmp_iso_prefix_tst(u8_t ident_len, s32_t *ident); +u8_t snmp_iso_prefix_expand(u8_t ident_len, s32_t *ident, struct snmp_obj_id *oidret); + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_SNMP */ + +#endif /* __LWIP_SNMP_STRUCTS_H__ */ diff --git a/features/unsupported/net/lwip/lwip/include/lwip/sockets.h b/features/unsupported/net/lwip/lwip/include/lwip/sockets.h new file mode 100644 index 00000000000..57c4e14cff4 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/include/lwip/sockets.h @@ -0,0 +1,376 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ + + +#ifndef __LWIP_SOCKETS_H__ +#define __LWIP_SOCKETS_H__ + +#include "lwip/opt.h" + +#if LWIP_SOCKET /* don't build if not configured for use in lwipopts.h */ + +#include /* for size_t */ + +#include "lwip/ip_addr.h" +#include "lwip/inet.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* members are in network byte order */ +struct sockaddr_in { + u8_t sin_len; + u8_t sin_family; + u16_t sin_port; + struct in_addr sin_addr; + char sin_zero[8]; +}; + +struct sockaddr { + u8_t sa_len; + u8_t sa_family; + char sa_data[14]; +}; + +#ifndef socklen_t +# define socklen_t u32_t +#endif + +/* Socket protocol types (TCP/UDP/RAW) */ +#define SOCK_STREAM 1 +#define SOCK_DGRAM 2 +#define SOCK_RAW 3 + +/* + * Option flags per-socket. These must match the SOF_ flags in ip.h (checked in init.c) + */ +#define SO_DEBUG 0x0001 /* Unimplemented: turn on debugging info recording */ +#define SO_ACCEPTCONN 0x0002 /* socket has had listen() */ +#define SO_REUSEADDR 0x0004 /* Allow local address reuse */ +#define SO_KEEPALIVE 0x0008 /* keep connections alive */ +#define SO_DONTROUTE 0x0010 /* Unimplemented: just use interface addresses */ +#define SO_BROADCAST 0x0020 /* permit to send and to receive broadcast messages (see IP_SOF_BROADCAST option) */ +#define SO_USELOOPBACK 0x0040 /* Unimplemented: bypass hardware when possible */ +#define SO_LINGER 0x0080 /* linger on close if data present */ +#define SO_OOBINLINE 0x0100 /* Unimplemented: leave received OOB data in line */ +#define SO_REUSEPORT 0x0200 /* Unimplemented: allow local address & port reuse */ + +#define SO_DONTLINGER ((int)(~SO_LINGER)) + +/* + * Additional options, not kept in so_options. + */ +#define SO_SNDBUF 0x1001 /* Unimplemented: send buffer size */ +#define SO_RCVBUF 0x1002 /* receive buffer size */ +#define SO_SNDLOWAT 0x1003 /* Unimplemented: send low-water mark */ +#define SO_RCVLOWAT 0x1004 /* Unimplemented: receive low-water mark */ +#define SO_SNDTIMEO 0x1005 /* Unimplemented: send timeout */ +#define SO_RCVTIMEO 0x1006 /* receive timeout */ +#define SO_ERROR 0x1007 /* get error status and clear */ +#define SO_TYPE 0x1008 /* get socket type */ +#define SO_CONTIMEO 0x1009 /* Unimplemented: connect timeout */ +#define SO_NO_CHECK 0x100a /* don't create UDP checksum */ + + +/* + * Structure used for manipulating linger option. + */ +struct linger { + int l_onoff; /* option on/off */ + int l_linger; /* linger time */ +}; + +/* + * Level number for (get/set)sockopt() to apply to socket itself. + */ +#define SOL_SOCKET 0xfff /* options for socket level */ + + +#define AF_UNSPEC 0 +#define AF_INET 2 +#define PF_INET AF_INET +#define PF_UNSPEC AF_UNSPEC + +#define IPPROTO_IP 0 +#define IPPROTO_TCP 6 +#define IPPROTO_UDP 17 +#define IPPROTO_UDPLITE 136 + +/* Flags we can use with send and recv. */ +#define MSG_PEEK 0x01 /* Peeks at an incoming message */ +#define MSG_WAITALL 0x02 /* Unimplemented: Requests that the function block until the full amount of data requested can be returned */ +#define MSG_OOB 0x04 /* Unimplemented: Requests out-of-band data. The significance and semantics of out-of-band data are protocol-specific */ +#define MSG_DONTWAIT 0x08 /* Nonblocking i/o for this operation only */ +#define MSG_MORE 0x10 /* Sender will send more */ + + +/* + * Options for level IPPROTO_IP + */ +#define IP_TOS 1 +#define IP_TTL 2 + +#if LWIP_TCP +/* + * Options for level IPPROTO_TCP + */ +#define TCP_NODELAY 0x01 /* don't delay send to coalesce packets */ +#define TCP_KEEPALIVE 0x02 /* send KEEPALIVE probes when idle for pcb->keep_idle milliseconds */ +#define TCP_KEEPIDLE 0x03 /* set pcb->keep_idle - Same as TCP_KEEPALIVE, but use seconds for get/setsockopt */ +#define TCP_KEEPINTVL 0x04 /* set pcb->keep_intvl - Use seconds for get/setsockopt */ +#define TCP_KEEPCNT 0x05 /* set pcb->keep_cnt - Use number of probes sent for get/setsockopt */ +#endif /* LWIP_TCP */ + +#if LWIP_UDP && LWIP_UDPLITE +/* + * Options for level IPPROTO_UDPLITE + */ +#define UDPLITE_SEND_CSCOV 0x01 /* sender checksum coverage */ +#define UDPLITE_RECV_CSCOV 0x02 /* minimal receiver checksum coverage */ +#endif /* LWIP_UDP && LWIP_UDPLITE*/ + + +#if LWIP_IGMP +/* + * Options and types for UDP multicast traffic handling + */ +#define IP_ADD_MEMBERSHIP 3 +#define IP_DROP_MEMBERSHIP 4 +#define IP_MULTICAST_TTL 5 +#define IP_MULTICAST_IF 6 +#define IP_MULTICAST_LOOP 7 + +typedef struct ip_mreq { + struct in_addr imr_multiaddr; /* IP multicast address of group */ + struct in_addr imr_interface; /* local IP address of interface */ +} ip_mreq; +#endif /* LWIP_IGMP */ + +/* + * The Type of Service provides an indication of the abstract + * parameters of the quality of service desired. These parameters are + * to be used to guide the selection of the actual service parameters + * when transmitting a datagram through a particular network. Several + * networks offer service precedence, which somehow treats high + * precedence traffic as more important than other traffic (generally + * by accepting only traffic above a certain precedence at time of high + * load). The major choice is a three way tradeoff between low-delay, + * high-reliability, and high-throughput. + * The use of the Delay, Throughput, and Reliability indications may + * increase the cost (in some sense) of the service. In many networks + * better performance for one of these parameters is coupled with worse + * performance on another. Except for very unusual cases at most two + * of these three indications should be set. + */ +#define IPTOS_TOS_MASK 0x1E +#define IPTOS_TOS(tos) ((tos) & IPTOS_TOS_MASK) +#define IPTOS_LOWDELAY 0x10 +#define IPTOS_THROUGHPUT 0x08 +#define IPTOS_RELIABILITY 0x04 +#define IPTOS_LOWCOST 0x02 +#define IPTOS_MINCOST IPTOS_LOWCOST + +/* + * The Network Control precedence designation is intended to be used + * within a network only. The actual use and control of that + * designation is up to each network. The Internetwork Control + * designation is intended for use by gateway control originators only. + * If the actual use of these precedence designations is of concern to + * a particular network, it is the responsibility of that network to + * control the access to, and use of, those precedence designations. + */ +#define IPTOS_PREC_MASK 0xe0 +#define IPTOS_PREC(tos) ((tos) & IPTOS_PREC_MASK) +#define IPTOS_PREC_NETCONTROL 0xe0 +#define IPTOS_PREC_INTERNETCONTROL 0xc0 +#define IPTOS_PREC_CRITIC_ECP 0xa0 +#define IPTOS_PREC_FLASHOVERRIDE 0x80 +#define IPTOS_PREC_FLASH 0x60 +#define IPTOS_PREC_IMMEDIATE 0x40 +#define IPTOS_PREC_PRIORITY 0x20 +#define IPTOS_PREC_ROUTINE 0x00 + + +/* + * Commands for ioctlsocket(), taken from the BSD file fcntl.h. + * lwip_ioctl only supports FIONREAD and FIONBIO, for now + * + * Ioctl's have the command encoded in the lower word, + * and the size of any in or out parameters in the upper + * word. The high 2 bits of the upper word are used + * to encode the in/out status of the parameter; for now + * we restrict parameters to at most 128 bytes. + */ +#if !defined(FIONREAD) || !defined(FIONBIO) +#define IOCPARM_MASK 0x7fU /* parameters must be < 128 bytes */ +#define IOC_VOID 0x20000000UL /* no parameters */ +#define IOC_OUT 0x40000000UL /* copy out parameters */ +#define IOC_IN 0x80000000UL /* copy in parameters */ +#define IOC_INOUT (IOC_IN|IOC_OUT) + /* 0x20000000 distinguishes new & + old ioctl's */ +#define _IO(x,y) (IOC_VOID|((x)<<8)|(y)) + +#define _IOR(x,y,t) (IOC_OUT|(((long)sizeof(t)&IOCPARM_MASK)<<16)|((x)<<8)|(y)) + +#define _IOW(x,y,t) (IOC_IN|(((long)sizeof(t)&IOCPARM_MASK)<<16)|((x)<<8)|(y)) +#endif /* !defined(FIONREAD) || !defined(FIONBIO) */ + +#ifndef FIONREAD +#define FIONREAD _IOR('f', 127, unsigned long) /* get # bytes to read */ +#endif +#ifndef FIONBIO +#define FIONBIO _IOW('f', 126, unsigned long) /* set/clear non-blocking i/o */ +#endif + +/* Socket I/O Controls: unimplemented */ +#ifndef SIOCSHIWAT +#define SIOCSHIWAT _IOW('s', 0, unsigned long) /* set high watermark */ +#define SIOCGHIWAT _IOR('s', 1, unsigned long) /* get high watermark */ +#define SIOCSLOWAT _IOW('s', 2, unsigned long) /* set low watermark */ +#define SIOCGLOWAT _IOR('s', 3, unsigned long) /* get low watermark */ +#define SIOCATMARK _IOR('s', 7, unsigned long) /* at oob mark? */ +#endif + +/* commands for fnctl */ +#ifndef F_GETFL +#define F_GETFL 3 +#endif +#ifndef F_SETFL +#define F_SETFL 4 +#endif + +/* File status flags and file access modes for fnctl, + these are bits in an int. */ +#ifndef O_NONBLOCK +#define O_NONBLOCK 1 /* nonblocking I/O */ +#endif +#ifndef O_NDELAY +#define O_NDELAY 1 /* same as O_NONBLOCK, for compatibility */ +#endif + +#ifndef SHUT_RD + #define SHUT_RD 0 + #define SHUT_WR 1 + #define SHUT_RDWR 2 +#endif + +/* FD_SET used for lwip_select */ +#ifndef FD_SET + #undef FD_SETSIZE + /* Make FD_SETSIZE match NUM_SOCKETS in socket.c */ + #define FD_SETSIZE MEMP_NUM_NETCONN + #define FD_SET(n, p) ((p)->fd_bits[(n)/8] |= (1 << ((n) & 7))) + #define FD_CLR(n, p) ((p)->fd_bits[(n)/8] &= ~(1 << ((n) & 7))) + #define FD_ISSET(n,p) ((p)->fd_bits[(n)/8] & (1 << ((n) & 7))) + #define FD_ZERO(p) memset((void*)(p),0,sizeof(*(p))) + + typedef struct fd_set { + unsigned char fd_bits [(FD_SETSIZE+7)/8]; + } fd_set; + +#endif /* FD_SET */ + +/** LWIP_TIMEVAL_PRIVATE: if you want to use the struct timeval provided + * by your system, set this to 0 and include in cc.h */ +#ifndef LWIP_TIMEVAL_PRIVATE +#define LWIP_TIMEVAL_PRIVATE 0 +#endif + +#if LWIP_TIMEVAL_PRIVATE +struct timeval { + long tv_sec; /* seconds */ + long tv_usec; /* and microseconds */ +}; +#endif /* LWIP_TIMEVAL_PRIVATE */ + +void lwip_socket_init(void); + +int lwip_accept(int s, struct sockaddr *addr, socklen_t *addrlen); +int lwip_bind(int s, const struct sockaddr *name, socklen_t namelen); +int lwip_shutdown(int s, int how); +int lwip_getpeername (int s, struct sockaddr *name, socklen_t *namelen); +int lwip_getsockname (int s, struct sockaddr *name, socklen_t *namelen); +int lwip_getsockopt (int s, int level, int optname, void *optval, socklen_t *optlen); +int lwip_setsockopt (int s, int level, int optname, const void *optval, socklen_t optlen); +int lwip_close(int s); +int lwip_connect(int s, const struct sockaddr *name, socklen_t namelen); +int lwip_listen(int s, int backlog); +int lwip_recv(int s, void *mem, size_t len, int flags); +int lwip_read(int s, void *mem, size_t len); +int lwip_recvfrom(int s, void *mem, size_t len, int flags, + struct sockaddr *from, socklen_t *fromlen); +int lwip_send(int s, const void *dataptr, size_t size, int flags); +int lwip_sendto(int s, const void *dataptr, size_t size, int flags, + const struct sockaddr *to, socklen_t tolen); +int lwip_socket(int domain, int type, int protocol); +int lwip_write(int s, const void *dataptr, size_t size); +int lwip_select(int maxfdp1, fd_set *readset, fd_set *writeset, fd_set *exceptset, + struct timeval *timeout); +int lwip_ioctl(int s, long cmd, void *argp); +int lwip_fcntl(int s, int cmd, int val); + +#if LWIP_COMPAT_SOCKETS +#define accept(a,b,c) lwip_accept(a,b,c) +#define bind(a,b,c) lwip_bind(a,b,c) +#define shutdown(a,b) lwip_shutdown(a,b) +#define closesocket(s) lwip_close(s) +#define connect(a,b,c) lwip_connect(a,b,c) +#define getsockname(a,b,c) lwip_getsockname(a,b,c) +#define getpeername(a,b,c) lwip_getpeername(a,b,c) +#define setsockopt(a,b,c,d,e) lwip_setsockopt(a,b,c,d,e) +#define getsockopt(a,b,c,d,e) lwip_getsockopt(a,b,c,d,e) +#define listen(a,b) lwip_listen(a,b) +#define recv(a,b,c,d) lwip_recv(a,b,c,d) +#define recvfrom(a,b,c,d,e,f) lwip_recvfrom(a,b,c,d,e,f) +#define send(a,b,c,d) lwip_send(a,b,c,d) +#define sendto(a,b,c,d,e,f) lwip_sendto(a,b,c,d,e,f) +#define socket(a,b,c) lwip_socket(a,b,c) +#define select(a,b,c,d,e) lwip_select(a,b,c,d,e) +#define ioctlsocket(a,b,c) lwip_ioctl(a,b,c) + +#if LWIP_POSIX_SOCKETS_IO_NAMES +#define read(a,b,c) lwip_read(a,b,c) +#define write(a,b,c) lwip_write(a,b,c) +#define close(s) lwip_close(s) +#endif /* LWIP_POSIX_SOCKETS_IO_NAMES */ + +#endif /* LWIP_COMPAT_SOCKETS */ + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_SOCKET */ + +#endif /* __LWIP_SOCKETS_H__ */ diff --git a/features/unsupported/net/lwip/lwip/include/lwip/stats.h b/features/unsupported/net/lwip/lwip/include/lwip/stats.h new file mode 100644 index 00000000000..015b7ce79d8 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/include/lwip/stats.h @@ -0,0 +1,292 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef __LWIP_STATS_H__ +#define __LWIP_STATS_H__ + +#include "lwip/opt.h" + +#include "lwip/mem.h" +#include "lwip/memp.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#if LWIP_STATS + +#ifndef LWIP_STATS_LARGE +#define LWIP_STATS_LARGE 0 +#endif + +#if LWIP_STATS_LARGE +#define STAT_COUNTER u32_t +#define STAT_COUNTER_F U32_F +#else +#define STAT_COUNTER u16_t +#define STAT_COUNTER_F U16_F +#endif + +struct stats_proto { + STAT_COUNTER xmit; /* Transmitted packets. */ + STAT_COUNTER recv; /* Received packets. */ + STAT_COUNTER fw; /* Forwarded packets. */ + STAT_COUNTER drop; /* Dropped packets. */ + STAT_COUNTER chkerr; /* Checksum error. */ + STAT_COUNTER lenerr; /* Invalid length error. */ + STAT_COUNTER memerr; /* Out of memory error. */ + STAT_COUNTER rterr; /* Routing error. */ + STAT_COUNTER proterr; /* Protocol error. */ + STAT_COUNTER opterr; /* Error in options. */ + STAT_COUNTER err; /* Misc error. */ + STAT_COUNTER cachehit; +}; + +struct stats_igmp { + STAT_COUNTER xmit; /* Transmitted packets. */ + STAT_COUNTER recv; /* Received packets. */ + STAT_COUNTER drop; /* Dropped packets. */ + STAT_COUNTER chkerr; /* Checksum error. */ + STAT_COUNTER lenerr; /* Invalid length error. */ + STAT_COUNTER memerr; /* Out of memory error. */ + STAT_COUNTER proterr; /* Protocol error. */ + STAT_COUNTER rx_v1; /* Received v1 frames. */ + STAT_COUNTER rx_group; /* Received group-specific queries. */ + STAT_COUNTER rx_general; /* Received general queries. */ + STAT_COUNTER rx_report; /* Received reports. */ + STAT_COUNTER tx_join; /* Sent joins. */ + STAT_COUNTER tx_leave; /* Sent leaves. */ + STAT_COUNTER tx_report; /* Sent reports. */ +}; + +struct stats_mem { +#ifdef LWIP_DEBUG + const char *name; +#endif /* LWIP_DEBUG */ + mem_size_t avail; + mem_size_t used; + mem_size_t max; + STAT_COUNTER err; + STAT_COUNTER illegal; +}; + +struct stats_syselem { + STAT_COUNTER used; + STAT_COUNTER max; + STAT_COUNTER err; +}; + +struct stats_sys { + struct stats_syselem sem; + struct stats_syselem mutex; + struct stats_syselem mbox; +}; + +struct stats_ { +#if LINK_STATS + struct stats_proto link; +#endif +#if ETHARP_STATS + struct stats_proto etharp; +#endif +#if IPFRAG_STATS + struct stats_proto ip_frag; +#endif +#if IP_STATS + struct stats_proto ip; +#endif +#if ICMP_STATS + struct stats_proto icmp; +#endif +#if IGMP_STATS + struct stats_igmp igmp; +#endif +#if UDP_STATS + struct stats_proto udp; +#endif +#if TCP_STATS + struct stats_proto tcp; +#endif +#if MEM_STATS + struct stats_mem mem; +#endif +#if MEMP_STATS + struct stats_mem memp[MEMP_MAX]; +#endif +#if SYS_STATS + struct stats_sys sys; +#endif +}; + +extern struct stats_ lwip_stats; + +void stats_init(void); + +#define STATS_INC(x) ++lwip_stats.x +#define STATS_DEC(x) --lwip_stats.x +#define STATS_INC_USED(x, y) do { lwip_stats.x.used += y; \ + if (lwip_stats.x.max < lwip_stats.x.used) { \ + lwip_stats.x.max = lwip_stats.x.used; \ + } \ + } while(0) +#else /* LWIP_STATS */ +#define stats_init() +#define STATS_INC(x) +#define STATS_DEC(x) +#define STATS_INC_USED(x) +#endif /* LWIP_STATS */ + +#if TCP_STATS +#define TCP_STATS_INC(x) STATS_INC(x) +#define TCP_STATS_DISPLAY() stats_display_proto(&lwip_stats.tcp, "TCP") +#else +#define TCP_STATS_INC(x) +#define TCP_STATS_DISPLAY() +#endif + +#if UDP_STATS +#define UDP_STATS_INC(x) STATS_INC(x) +#define UDP_STATS_DISPLAY() stats_display_proto(&lwip_stats.udp, "UDP") +#else +#define UDP_STATS_INC(x) +#define UDP_STATS_DISPLAY() +#endif + +#if ICMP_STATS +#define ICMP_STATS_INC(x) STATS_INC(x) +#define ICMP_STATS_DISPLAY() stats_display_proto(&lwip_stats.icmp, "ICMP") +#else +#define ICMP_STATS_INC(x) +#define ICMP_STATS_DISPLAY() +#endif + +#if IGMP_STATS +#define IGMP_STATS_INC(x) STATS_INC(x) +#define IGMP_STATS_DISPLAY() stats_display_igmp(&lwip_stats.igmp) +#else +#define IGMP_STATS_INC(x) +#define IGMP_STATS_DISPLAY() +#endif + +#if IP_STATS +#define IP_STATS_INC(x) STATS_INC(x) +#define IP_STATS_DISPLAY() stats_display_proto(&lwip_stats.ip, "IP") +#else +#define IP_STATS_INC(x) +#define IP_STATS_DISPLAY() +#endif + +#if IPFRAG_STATS +#define IPFRAG_STATS_INC(x) STATS_INC(x) +#define IPFRAG_STATS_DISPLAY() stats_display_proto(&lwip_stats.ip_frag, "IP_FRAG") +#else +#define IPFRAG_STATS_INC(x) +#define IPFRAG_STATS_DISPLAY() +#endif + +#if ETHARP_STATS +#define ETHARP_STATS_INC(x) STATS_INC(x) +#define ETHARP_STATS_DISPLAY() stats_display_proto(&lwip_stats.etharp, "ETHARP") +#else +#define ETHARP_STATS_INC(x) +#define ETHARP_STATS_DISPLAY() +#endif + +#if LINK_STATS +#define LINK_STATS_INC(x) STATS_INC(x) +#define LINK_STATS_DISPLAY() stats_display_proto(&lwip_stats.link, "LINK") +#else +#define LINK_STATS_INC(x) +#define LINK_STATS_DISPLAY() +#endif + +#if MEM_STATS +#define MEM_STATS_AVAIL(x, y) lwip_stats.mem.x = y +#define MEM_STATS_INC(x) STATS_INC(mem.x) +#define MEM_STATS_INC_USED(x, y) STATS_INC_USED(mem, y) +#define MEM_STATS_DEC_USED(x, y) lwip_stats.mem.x -= y +#define MEM_STATS_DISPLAY() stats_display_mem(&lwip_stats.mem, "HEAP") +#else +#define MEM_STATS_AVAIL(x, y) +#define MEM_STATS_INC(x) +#define MEM_STATS_INC_USED(x, y) +#define MEM_STATS_DEC_USED(x, y) +#define MEM_STATS_DISPLAY() +#endif + +#if MEMP_STATS +#define MEMP_STATS_AVAIL(x, i, y) lwip_stats.memp[i].x = y +#define MEMP_STATS_INC(x, i) STATS_INC(memp[i].x) +#define MEMP_STATS_DEC(x, i) STATS_DEC(memp[i].x) +#define MEMP_STATS_INC_USED(x, i) STATS_INC_USED(memp[i], 1) +#define MEMP_STATS_DISPLAY(i) stats_display_memp(&lwip_stats.memp[i], i) +#else +#define MEMP_STATS_AVAIL(x, i, y) +#define MEMP_STATS_INC(x, i) +#define MEMP_STATS_DEC(x, i) +#define MEMP_STATS_INC_USED(x, i) +#define MEMP_STATS_DISPLAY(i) +#endif + +#if SYS_STATS +#define SYS_STATS_INC(x) STATS_INC(sys.x) +#define SYS_STATS_DEC(x) STATS_DEC(sys.x) +#define SYS_STATS_INC_USED(x) STATS_INC_USED(sys.x, 1) +#define SYS_STATS_DISPLAY() stats_display_sys(&lwip_stats.sys) +#else +#define SYS_STATS_INC(x) +#define SYS_STATS_DEC(x) +#define SYS_STATS_INC_USED(x) +#define SYS_STATS_DISPLAY() +#endif + +/* Display of statistics */ +#if LWIP_STATS_DISPLAY +void stats_display(void); +void stats_display_proto(struct stats_proto *proto, char *name); +void stats_display_igmp(struct stats_igmp *igmp); +void stats_display_mem(struct stats_mem *mem, char *name); +void stats_display_memp(struct stats_mem *mem, int index); +void stats_display_sys(struct stats_sys *sys); +#else /* LWIP_STATS_DISPLAY */ +#define stats_display() +#define stats_display_proto(proto, name) +#define stats_display_igmp(igmp) +#define stats_display_mem(mem, name) +#define stats_display_memp(mem, index) +#define stats_display_sys(sys) +#endif /* LWIP_STATS_DISPLAY */ + +#ifdef __cplusplus +} +#endif + +#endif /* __LWIP_STATS_H__ */ diff --git a/features/unsupported/net/lwip/lwip/include/lwip/sys.h b/features/unsupported/net/lwip/lwip/include/lwip/sys.h new file mode 100644 index 00000000000..9f62c7540e6 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/include/lwip/sys.h @@ -0,0 +1,331 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef __LWIP_SYS_H__ +#define __LWIP_SYS_H__ + +#include "lwip/opt.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#if NO_SYS + +/* For a totally minimal and standalone system, we provide null + definitions of the sys_ functions. */ +typedef u8_t sys_sem_t; +typedef u8_t sys_mutex_t; +typedef u8_t sys_mbox_t; + +#define sys_sem_new(s, c) ERR_OK +#define sys_sem_signal(s) +#define sys_sem_wait(s) +#define sys_arch_sem_wait(s,t) +#define sys_sem_free(s) +#define sys_mutex_new(mu) ERR_OK +#define sys_mutex_lock(mu) +#define sys_mutex_unlock(mu) +#define sys_mutex_free(mu) +#define sys_mbox_new(m, s) ERR_OK +#define sys_mbox_fetch(m,d) +#define sys_mbox_tryfetch(m,d) +#define sys_mbox_post(m,d) +#define sys_mbox_trypost(m,d) +#define sys_mbox_free(m) + +#define sys_thread_new(n,t,a,s,p) + +#define sys_msleep(t) + +#else /* NO_SYS */ + +/** Return code for timeouts from sys_arch_mbox_fetch and sys_arch_sem_wait */ +#define SYS_ARCH_TIMEOUT 0xffffffffUL + +/** sys_mbox_tryfetch() returns SYS_MBOX_EMPTY if appropriate. + * For now we use the same magic value, but we allow this to change in future. + */ +#define SYS_MBOX_EMPTY SYS_ARCH_TIMEOUT + +#include "lwip/err.h" +#include "arch/sys_arch.h" + +/** Function prototype for thread functions */ +typedef void (*lwip_thread_fn)(void *arg); + +/* Function prototypes for functions to be implemented by platform ports + (in sys_arch.c) */ + +/* Mutex functions: */ + +/** Define LWIP_COMPAT_MUTEX if the port has no mutexes and binary semaphores + should be used instead */ +#if LWIP_COMPAT_MUTEX +/* for old ports that don't have mutexes: define them to binary semaphores */ +#define sys_mutex_t sys_sem_t +#define sys_mutex_new(mutex) sys_sem_new(mutex, 1) +#define sys_mutex_lock(mutex) sys_sem_wait(mutex) +#define sys_mutex_unlock(mutex) sys_sem_signal(mutex) +#define sys_mutex_free(mutex) sys_sem_free(mutex) +#define sys_mutex_valid(mutex) sys_sem_valid(mutex) +#define sys_mutex_set_invalid(mutex) sys_sem_set_invalid(mutex) + +#else /* LWIP_COMPAT_MUTEX */ + +/** Create a new mutex + * @param mutex pointer to the mutex to create + * @return a new mutex */ +err_t sys_mutex_new(sys_mutex_t *mutex); +/** Lock a mutex + * @param mutex the mutex to lock */ +void sys_mutex_lock(sys_mutex_t *mutex); +/** Unlock a mutex + * @param mutex the mutex to unlock */ +void sys_mutex_unlock(sys_mutex_t *mutex); +/** Delete a semaphore + * @param mutex the mutex to delete */ +void sys_mutex_free(sys_mutex_t *mutex); +#ifndef sys_mutex_valid +/** Check if a mutex is valid/allocated: return 1 for valid, 0 for invalid */ +int sys_mutex_valid(sys_mutex_t *mutex); +#endif +#ifndef sys_mutex_set_invalid +/** Set a mutex invalid so that sys_mutex_valid returns 0 */ +void sys_mutex_set_invalid(sys_mutex_t *mutex); +#endif +#endif /* LWIP_COMPAT_MUTEX */ + +/* Semaphore functions: */ + +/** Create a new semaphore + * @param sem pointer to the semaphore to create + * @param count initial count of the semaphore + * @return ERR_OK if successful, another err_t otherwise */ +err_t sys_sem_new(sys_sem_t *sem, u8_t count); +/** Signals a semaphore + * @param sem the semaphore to signal */ +void sys_sem_signal(sys_sem_t *sem); +/** Wait for a semaphore for the specified timeout + * @param sem the semaphore to wait for + * @param timeout timeout in milliseconds to wait (0 = wait forever) + * @return time (in milliseconds) waited for the semaphore + * or SYS_ARCH_TIMEOUT on timeout */ +u32_t sys_arch_sem_wait(sys_sem_t *sem, u32_t timeout); +/** Delete a semaphore + * @param sem semaphore to delete */ +void sys_sem_free(sys_sem_t *sem); +/** Wait for a semaphore - forever/no timeout */ +#define sys_sem_wait(sem) sys_arch_sem_wait(sem, 0) +#ifndef sys_sem_valid +/** Check if a sempahore is valid/allocated: return 1 for valid, 0 for invalid */ +int sys_sem_valid(sys_sem_t *sem); +#endif +#ifndef sys_sem_set_invalid +/** Set a semaphore invalid so that sys_sem_valid returns 0 */ +void sys_sem_set_invalid(sys_sem_t *sem); +#endif + +/* Time functions. */ +#ifndef sys_msleep +void sys_msleep(u32_t ms); /* only has a (close to) 1 jiffy resolution. */ +#endif + +/* Mailbox functions. */ + +/** Create a new mbox of specified size + * @param mbox pointer to the mbox to create + * @param size (miminum) number of messages in this mbox + * @return ERR_OK if successful, another err_t otherwise */ +err_t sys_mbox_new(sys_mbox_t *mbox, int size); +/** Post a message to an mbox - may not fail + * -> blocks if full, only used from tasks not from ISR + * @param mbox mbox to posts the message + * @param msg message to post (ATTENTION: can be NULL) */ +void sys_mbox_post(sys_mbox_t *mbox, void *msg); +/** Try to post a message to an mbox - may fail if full or ISR + * @param mbox mbox to posts the message + * @param msg message to post (ATTENTION: can be NULL) */ +err_t sys_mbox_trypost(sys_mbox_t *mbox, void *msg); +/** Wait for a new message to arrive in the mbox + * @param mbox mbox to get a message from + * @param msg pointer where the message is stored + * @param timeout maximum time (in milliseconds) to wait for a message + * @return time (in milliseconds) waited for a message, may be 0 if not waited + or SYS_ARCH_TIMEOUT on timeout + * The returned time has to be accurate to prevent timer jitter! */ +u32_t sys_arch_mbox_fetch(sys_mbox_t *mbox, void **msg, u32_t timeout); +/* Allow port to override with a macro, e.g. special timout for sys_arch_mbox_fetch() */ +#ifndef sys_arch_mbox_tryfetch +/** Wait for a new message to arrive in the mbox + * @param mbox mbox to get a message from + * @param msg pointer where the message is stored + * @param timeout maximum time (in milliseconds) to wait for a message + * @return 0 (milliseconds) if a message has been received + * or SYS_MBOX_EMPTY if the mailbox is empty */ +u32_t sys_arch_mbox_tryfetch(sys_mbox_t *mbox, void **msg); +#endif +/** For now, we map straight to sys_arch implementation. */ +#define sys_mbox_tryfetch(mbox, msg) sys_arch_mbox_tryfetch(mbox, msg) +/** Delete an mbox + * @param mbox mbox to delete */ +void sys_mbox_free(sys_mbox_t *mbox); +#define sys_mbox_fetch(mbox, msg) sys_arch_mbox_fetch(mbox, msg, 0) +#ifndef sys_mbox_valid +/** Check if an mbox is valid/allocated: return 1 for valid, 0 for invalid */ +int sys_mbox_valid(sys_mbox_t *mbox); +#endif +#ifndef sys_mbox_set_invalid +/** Set an mbox invalid so that sys_mbox_valid returns 0 */ +void sys_mbox_set_invalid(sys_mbox_t *mbox); +#endif + +/** The only thread function: + * Creates a new thread + * @param name human-readable name for the thread (used for debugging purposes) + * @param thread thread-function + * @param arg parameter passed to 'thread' + * @param stacksize stack size in bytes for the new thread (may be ignored by ports) + * @param prio priority of the new thread (may be ignored by ports) */ +sys_thread_t sys_thread_new(const char *name, lwip_thread_fn thread, void *arg, int stacksize, int prio); + +#endif /* NO_SYS */ + +/* sys_init() must be called before anthing else. */ +void sys_init(void); + +#ifndef sys_jiffies +/** Ticks/jiffies since power up. */ +u32_t sys_jiffies(void); +#endif + +/** Returns the current time in milliseconds, + * may be the same as sys_jiffies or at least based on it. */ +u32_t sys_now(void); + +/* Critical Region Protection */ +/* These functions must be implemented in the sys_arch.c file. + In some implementations they can provide a more light-weight protection + mechanism than using semaphores. Otherwise semaphores can be used for + implementation */ +#ifndef SYS_ARCH_PROTECT +/** SYS_LIGHTWEIGHT_PROT + * define SYS_LIGHTWEIGHT_PROT in lwipopts.h if you want inter-task protection + * for certain critical regions during buffer allocation, deallocation and memory + * allocation and deallocation. + */ +#if SYS_LIGHTWEIGHT_PROT + +/** SYS_ARCH_DECL_PROTECT + * declare a protection variable. This macro will default to defining a variable of + * type sys_prot_t. If a particular port needs a different implementation, then + * this macro may be defined in sys_arch.h. + */ +#define SYS_ARCH_DECL_PROTECT(lev) sys_prot_t lev +/** SYS_ARCH_PROTECT + * Perform a "fast" protect. This could be implemented by + * disabling interrupts for an embedded system or by using a semaphore or + * mutex. The implementation should allow calling SYS_ARCH_PROTECT when + * already protected. The old protection level is returned in the variable + * "lev". This macro will default to calling the sys_arch_protect() function + * which should be implemented in sys_arch.c. If a particular port needs a + * different implementation, then this macro may be defined in sys_arch.h + */ +#define SYS_ARCH_PROTECT(lev) lev = sys_arch_protect() +/** SYS_ARCH_UNPROTECT + * Perform a "fast" set of the protection level to "lev". This could be + * implemented by setting the interrupt level to "lev" within the MACRO or by + * using a semaphore or mutex. This macro will default to calling the + * sys_arch_unprotect() function which should be implemented in + * sys_arch.c. If a particular port needs a different implementation, then + * this macro may be defined in sys_arch.h + */ +#define SYS_ARCH_UNPROTECT(lev) sys_arch_unprotect(lev) +sys_prot_t sys_arch_protect(void); +void sys_arch_unprotect(sys_prot_t pval); + +#else + +#define SYS_ARCH_DECL_PROTECT(lev) +#define SYS_ARCH_PROTECT(lev) +#define SYS_ARCH_UNPROTECT(lev) + +#endif /* SYS_LIGHTWEIGHT_PROT */ + +#endif /* SYS_ARCH_PROTECT */ + +/* + * Macros to set/get and increase/decrease variables in a thread-safe way. + * Use these for accessing variable that are used from more than one thread. + */ + +#ifndef SYS_ARCH_INC +#define SYS_ARCH_INC(var, val) do { \ + SYS_ARCH_DECL_PROTECT(old_level); \ + SYS_ARCH_PROTECT(old_level); \ + var += val; \ + SYS_ARCH_UNPROTECT(old_level); \ + } while(0) +#endif /* SYS_ARCH_INC */ + +#ifndef SYS_ARCH_DEC +#define SYS_ARCH_DEC(var, val) do { \ + SYS_ARCH_DECL_PROTECT(old_level); \ + SYS_ARCH_PROTECT(old_level); \ + var -= val; \ + SYS_ARCH_UNPROTECT(old_level); \ + } while(0) +#endif /* SYS_ARCH_DEC */ + +#ifndef SYS_ARCH_GET +#define SYS_ARCH_GET(var, ret) do { \ + SYS_ARCH_DECL_PROTECT(old_level); \ + SYS_ARCH_PROTECT(old_level); \ + ret = var; \ + SYS_ARCH_UNPROTECT(old_level); \ + } while(0) +#endif /* SYS_ARCH_GET */ + +#ifndef SYS_ARCH_SET +#define SYS_ARCH_SET(var, val) do { \ + SYS_ARCH_DECL_PROTECT(old_level); \ + SYS_ARCH_PROTECT(old_level); \ + var = val; \ + SYS_ARCH_UNPROTECT(old_level); \ + } while(0) +#endif /* SYS_ARCH_SET */ + + +#ifdef __cplusplus +} +#endif + +#endif /* __LWIP_SYS_H__ */ diff --git a/features/unsupported/net/lwip/lwip/include/lwip/tcp.h b/features/unsupported/net/lwip/lwip/include/lwip/tcp.h new file mode 100644 index 00000000000..07dcd10e786 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/include/lwip/tcp.h @@ -0,0 +1,377 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef __LWIP_TCP_H__ +#define __LWIP_TCP_H__ + +#include "lwip/opt.h" + +#if LWIP_TCP /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/sys.h" +#include "lwip/mem.h" +#include "lwip/pbuf.h" +#include "lwip/ip.h" +#include "lwip/icmp.h" +#include "lwip/err.h" + +#ifdef __cplusplus +extern "C" { +#endif + +struct tcp_pcb; + +/** Function prototype for tcp accept callback functions. Called when a new + * connection can be accepted on a listening pcb. + * + * @param arg Additional argument to pass to the callback function (@see tcp_arg()) + * @param newpcb The new connection pcb + * @param err An error code if there has been an error accepting. + * Only return ERR_ABRT if you have called tcp_abort from within the + * callback function! + */ +typedef err_t (*tcp_accept_fn)(void *arg, struct tcp_pcb *newpcb, err_t err); + +/** Function prototype for tcp receive callback functions. Called when data has + * been received. + * + * @param arg Additional argument to pass to the callback function (@see tcp_arg()) + * @param tpcb The connection pcb which received data + * @param p The received data (or NULL when the connection has been closed!) + * @param err An error code if there has been an error receiving + * Only return ERR_ABRT if you have called tcp_abort from within the + * callback function! + */ +typedef err_t (*tcp_recv_fn)(void *arg, struct tcp_pcb *tpcb, + struct pbuf *p, err_t err); + +/** Function prototype for tcp sent callback functions. Called when sent data has + * been acknowledged by the remote side. Use it to free corresponding resources. + * This also means that the pcb has now space available to send new data. + * + * @param arg Additional argument to pass to the callback function (@see tcp_arg()) + * @param tpcb The connection pcb for which data has been acknowledged + * @param len The amount of bytes acknowledged + * @return ERR_OK: try to send some data by calling tcp_output + * Only return ERR_ABRT if you have called tcp_abort from within the + * callback function! + */ +typedef err_t (*tcp_sent_fn)(void *arg, struct tcp_pcb *tpcb, + u16_t len); + +/** Function prototype for tcp poll callback functions. Called periodically as + * specified by @see tcp_poll. + * + * @param arg Additional argument to pass to the callback function (@see tcp_arg()) + * @param tpcb tcp pcb + * @return ERR_OK: try to send some data by calling tcp_output + * Only return ERR_ABRT if you have called tcp_abort from within the + * callback function! + */ +typedef err_t (*tcp_poll_fn)(void *arg, struct tcp_pcb *tpcb); + +/** Function prototype for tcp error callback functions. Called when the pcb + * receives a RST or is unexpectedly closed for any other reason. + * + * @note The corresponding pcb is already freed when this callback is called! + * + * @param arg Additional argument to pass to the callback function (@see tcp_arg()) + * @param err Error code to indicate why the pcb has been closed + * ERR_ABRT: aborted through tcp_abort or by a TCP timer + * ERR_RST: the connection was reset by the remote host + */ +typedef void (*tcp_err_fn)(void *arg, err_t err); + +/** Function prototype for tcp connected callback functions. Called when a pcb + * is connected to the remote side after initiating a connection attempt by + * calling tcp_connect(). + * + * @param arg Additional argument to pass to the callback function (@see tcp_arg()) + * @param tpcb The connection pcb which is connected + * @param err An unused error code, always ERR_OK currently ;-) TODO! + * Only return ERR_ABRT if you have called tcp_abort from within the + * callback function! + * + * @note When a connection attempt fails, the error callback is currently called! + */ +typedef err_t (*tcp_connected_fn)(void *arg, struct tcp_pcb *tpcb, err_t err); + +enum tcp_state { + CLOSED = 0, + LISTEN = 1, + SYN_SENT = 2, + SYN_RCVD = 3, + ESTABLISHED = 4, + FIN_WAIT_1 = 5, + FIN_WAIT_2 = 6, + CLOSE_WAIT = 7, + CLOSING = 8, + LAST_ACK = 9, + TIME_WAIT = 10 +}; + +#if LWIP_CALLBACK_API + /* Function to call when a listener has been connected. + * @param arg user-supplied argument (tcp_pcb.callback_arg) + * @param pcb a new tcp_pcb that now is connected + * @param err an error argument (TODO: that is current always ERR_OK?) + * @return ERR_OK: accept the new connection, + * any other err_t abortsthe new connection + */ +#define DEF_ACCEPT_CALLBACK tcp_accept_fn accept; +#else /* LWIP_CALLBACK_API */ +#define DEF_ACCEPT_CALLBACK +#endif /* LWIP_CALLBACK_API */ + +/** + * members common to struct tcp_pcb and struct tcp_listen_pcb + */ +#define TCP_PCB_COMMON(type) \ + type *next; /* for the linked list */ \ + enum tcp_state state; /* TCP state */ \ + u8_t prio; \ + void *callback_arg; \ + /* the accept callback for listen- and normal pcbs, if LWIP_CALLBACK_API */ \ + DEF_ACCEPT_CALLBACK \ + /* ports are in host byte order */ \ + u16_t local_port + + +/* the TCP protocol control block */ +struct tcp_pcb { +/** common PCB members */ + IP_PCB; +/** protocol specific PCB members */ + TCP_PCB_COMMON(struct tcp_pcb); + + /* ports are in host byte order */ + u16_t remote_port; + + u8_t flags; +#define TF_ACK_DELAY ((u8_t)0x01U) /* Delayed ACK. */ +#define TF_ACK_NOW ((u8_t)0x02U) /* Immediate ACK. */ +#define TF_INFR ((u8_t)0x04U) /* In fast recovery. */ +#define TF_TIMESTAMP ((u8_t)0x08U) /* Timestamp option enabled */ +#define TF_RXCLOSED ((u8_t)0x10U) /* rx closed by tcp_shutdown */ +#define TF_FIN ((u8_t)0x20U) /* Connection was closed locally (FIN segment enqueued). */ +#define TF_NODELAY ((u8_t)0x40U) /* Disable Nagle algorithm */ +#define TF_NAGLEMEMERR ((u8_t)0x80U) /* nagle enabled, memerr, try to output to prevent delayed ACK to happen */ + + /* the rest of the fields are in host byte order + as we have to do some math with them */ + /* receiver variables */ + u32_t rcv_nxt; /* next seqno expected */ + u16_t rcv_wnd; /* receiver window available */ + u16_t rcv_ann_wnd; /* receiver window to announce */ + u32_t rcv_ann_right_edge; /* announced right edge of window */ + + /* Timers */ + u32_t tmr; + u8_t polltmr, pollinterval; + + /* Retransmission timer. */ + s16_t rtime; + + u16_t mss; /* maximum segment size */ + + /* RTT (round trip time) estimation variables */ + u32_t rttest; /* RTT estimate in 500ms ticks */ + u32_t rtseq; /* sequence number being timed */ + s16_t sa, sv; /* @todo document this */ + + s16_t rto; /* retransmission time-out */ + u8_t nrtx; /* number of retransmissions */ + + /* fast retransmit/recovery */ + u32_t lastack; /* Highest acknowledged seqno. */ + u8_t dupacks; + + /* congestion avoidance/control variables */ + u16_t cwnd; + u16_t ssthresh; + + /* sender variables */ + u32_t snd_nxt; /* next new seqno to be sent */ + u16_t snd_wnd; /* sender window */ + u32_t snd_wl1, snd_wl2; /* Sequence and acknowledgement numbers of last + window update. */ + u32_t snd_lbb; /* Sequence number of next byte to be buffered. */ + + u16_t acked; + + u16_t snd_buf; /* Available buffer space for sending (in bytes). */ +#define TCP_SNDQUEUELEN_OVERFLOW (0xffffU-3) + u16_t snd_queuelen; /* Available buffer space for sending (in tcp_segs). */ + +#if TCP_OVERSIZE + /* Extra bytes available at the end of the last pbuf in unsent. */ + u16_t unsent_oversize; +#endif /* TCP_OVERSIZE */ + + /* These are ordered by sequence number: */ + struct tcp_seg *unsent; /* Unsent (queued) segments. */ + struct tcp_seg *unacked; /* Sent but unacknowledged segments. */ +#if TCP_QUEUE_OOSEQ + struct tcp_seg *ooseq; /* Received out of sequence segments. */ +#endif /* TCP_QUEUE_OOSEQ */ + + struct pbuf *refused_data; /* Data previously received but not yet taken by upper layer */ + +#if LWIP_CALLBACK_API + /* Function to be called when more send buffer space is available. */ + tcp_sent_fn sent; + /* Function to be called when (in-sequence) data has arrived. */ + tcp_recv_fn recv; + /* Function to be called when a connection has been set up. */ + tcp_connected_fn connected; + /* Function which is called periodically. */ + tcp_poll_fn poll; + /* Function to be called whenever a fatal error occurs. */ + tcp_err_fn errf; +#endif /* LWIP_CALLBACK_API */ + +#if LWIP_TCP_TIMESTAMPS + u32_t ts_lastacksent; + u32_t ts_recent; +#endif /* LWIP_TCP_TIMESTAMPS */ + + /* idle time before KEEPALIVE is sent */ + u32_t keep_idle; +#if LWIP_TCP_KEEPALIVE + u32_t keep_intvl; + u32_t keep_cnt; +#endif /* LWIP_TCP_KEEPALIVE */ + + /* Persist timer counter */ + u32_t persist_cnt; + /* Persist timer back-off */ + u8_t persist_backoff; + + /* KEEPALIVE counter */ + u8_t keep_cnt_sent; +}; + +struct tcp_pcb_listen { +/* Common members of all PCB types */ + IP_PCB; +/* Protocol specific PCB members */ + TCP_PCB_COMMON(struct tcp_pcb_listen); + +#if TCP_LISTEN_BACKLOG + u8_t backlog; + u8_t accepts_pending; +#endif /* TCP_LISTEN_BACKLOG */ +}; + +#if LWIP_EVENT_API + +enum lwip_event { + LWIP_EVENT_ACCEPT, + LWIP_EVENT_SENT, + LWIP_EVENT_RECV, + LWIP_EVENT_CONNECTED, + LWIP_EVENT_POLL, + LWIP_EVENT_ERR +}; + +err_t lwip_tcp_event(void *arg, struct tcp_pcb *pcb, + enum lwip_event, + struct pbuf *p, + u16_t size, + err_t err); + +#endif /* LWIP_EVENT_API */ + +/* Application program's interface: */ +struct tcp_pcb * tcp_new (void); + +void tcp_arg (struct tcp_pcb *pcb, void *arg); +void tcp_accept (struct tcp_pcb *pcb, tcp_accept_fn accept); +void tcp_recv (struct tcp_pcb *pcb, tcp_recv_fn recv); +void tcp_sent (struct tcp_pcb *pcb, tcp_sent_fn sent); +void tcp_poll (struct tcp_pcb *pcb, tcp_poll_fn poll, u8_t interval); +void tcp_err (struct tcp_pcb *pcb, tcp_err_fn err); + +#define tcp_mss(pcb) (((pcb)->flags & TF_TIMESTAMP) ? ((pcb)->mss - 12) : (pcb)->mss) +#define tcp_sndbuf(pcb) ((pcb)->snd_buf) +#define tcp_sndqueuelen(pcb) ((pcb)->snd_queuelen) +#define tcp_nagle_disable(pcb) ((pcb)->flags |= TF_NODELAY) +#define tcp_nagle_enable(pcb) ((pcb)->flags &= ~TF_NODELAY) +#define tcp_nagle_disabled(pcb) (((pcb)->flags & TF_NODELAY) != 0) + +#if TCP_LISTEN_BACKLOG +#define tcp_accepted(pcb) do { \ + LWIP_ASSERT("pcb->state == LISTEN (called for wrong pcb?)", pcb->state == LISTEN); \ + (((struct tcp_pcb_listen *)(pcb))->accepts_pending--); } while(0) +#else /* TCP_LISTEN_BACKLOG */ +#define tcp_accepted(pcb) LWIP_ASSERT("pcb->state == LISTEN (called for wrong pcb?)", \ + pcb->state == LISTEN) +#endif /* TCP_LISTEN_BACKLOG */ + +void tcp_recved (struct tcp_pcb *pcb, u16_t len); +err_t tcp_bind (struct tcp_pcb *pcb, ip_addr_t *ipaddr, + u16_t port); +err_t tcp_connect (struct tcp_pcb *pcb, ip_addr_t *ipaddr, + u16_t port, tcp_connected_fn connected); + +struct tcp_pcb * tcp_listen_with_backlog(struct tcp_pcb *pcb, u8_t backlog); +#define tcp_listen(pcb) tcp_listen_with_backlog(pcb, TCP_DEFAULT_LISTEN_BACKLOG) + +void tcp_abort (struct tcp_pcb *pcb); +err_t tcp_close (struct tcp_pcb *pcb); +err_t tcp_shutdown(struct tcp_pcb *pcb, int shut_rx, int shut_tx); + +/* Flags for "apiflags" parameter in tcp_write */ +#define TCP_WRITE_FLAG_COPY 0x01 +#define TCP_WRITE_FLAG_MORE 0x02 + +err_t tcp_write (struct tcp_pcb *pcb, const void *dataptr, u16_t len, + u8_t apiflags); + +void tcp_setprio (struct tcp_pcb *pcb, u8_t prio); + +#define TCP_PRIO_MIN 1 +#define TCP_PRIO_NORMAL 64 +#define TCP_PRIO_MAX 127 + +err_t tcp_output (struct tcp_pcb *pcb); + + +const char* tcp_debug_state_str(enum tcp_state s); + + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_TCP */ + +#endif /* __LWIP_TCP_H__ */ diff --git a/features/unsupported/net/lwip/lwip/include/lwip/tcp_impl.h b/features/unsupported/net/lwip/lwip/include/lwip/tcp_impl.h new file mode 100644 index 00000000000..b4feec0da19 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/include/lwip/tcp_impl.h @@ -0,0 +1,471 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef __LWIP_TCP_IMPL_H__ +#define __LWIP_TCP_IMPL_H__ + +#include "lwip/opt.h" + +#if LWIP_TCP /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/tcp.h" +#include "lwip/sys.h" +#include "lwip/mem.h" +#include "lwip/pbuf.h" +#include "lwip/ip.h" +#include "lwip/icmp.h" +#include "lwip/err.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* Functions for interfacing with TCP: */ + +/* Lower layer interface to TCP: */ +#define tcp_init() /* Compatibility define, no init needed. */ +void tcp_tmr (void); /* Must be called every + TCP_TMR_INTERVAL + ms. (Typically 250 ms). */ +/* It is also possible to call these two functions at the right + intervals (instead of calling tcp_tmr()). */ +void tcp_slowtmr (void); +void tcp_fasttmr (void); + + +/* Only used by IP to pass a TCP segment to TCP: */ +void tcp_input (struct pbuf *p, struct netif *inp); +/* Used within the TCP code only: */ +struct tcp_pcb * tcp_alloc (u8_t prio); +void tcp_abandon (struct tcp_pcb *pcb, int reset); +err_t tcp_send_empty_ack(struct tcp_pcb *pcb); +void tcp_rexmit (struct tcp_pcb *pcb); +void tcp_rexmit_rto (struct tcp_pcb *pcb); +void tcp_rexmit_fast (struct tcp_pcb *pcb); +u32_t tcp_update_rcv_ann_wnd(struct tcp_pcb *pcb); + +/** + * This is the Nagle algorithm: try to combine user data to send as few TCP + * segments as possible. Only send if + * - no previously transmitted data on the connection remains unacknowledged or + * - the TF_NODELAY flag is set (nagle algorithm turned off for this pcb) or + * - the only unsent segment is at least pcb->mss bytes long (or there is more + * than one unsent segment - with lwIP, this can happen although unsent->len < mss) + * - or if we are in fast-retransmit (TF_INFR) + */ +#define tcp_do_output_nagle(tpcb) ((((tpcb)->unacked == NULL) || \ + ((tpcb)->flags & (TF_NODELAY | TF_INFR)) || \ + (((tpcb)->unsent != NULL) && (((tpcb)->unsent->next != NULL) || \ + ((tpcb)->unsent->len >= (tpcb)->mss))) \ + ) ? 1 : 0) +#define tcp_output_nagle(tpcb) (tcp_do_output_nagle(tpcb) ? tcp_output(tpcb) : ERR_OK) + + +#define TCP_SEQ_LT(a,b) ((s32_t)((a)-(b)) < 0) +#define TCP_SEQ_LEQ(a,b) ((s32_t)((a)-(b)) <= 0) +#define TCP_SEQ_GT(a,b) ((s32_t)((a)-(b)) > 0) +#define TCP_SEQ_GEQ(a,b) ((s32_t)((a)-(b)) >= 0) +/* is b<=a<=c? */ +#if 0 /* see bug #10548 */ +#define TCP_SEQ_BETWEEN(a,b,c) ((c)-(b) >= (a)-(b)) +#endif +#define TCP_SEQ_BETWEEN(a,b,c) (TCP_SEQ_GEQ(a,b) && TCP_SEQ_LEQ(a,c)) +#define TCP_FIN 0x01U +#define TCP_SYN 0x02U +#define TCP_RST 0x04U +#define TCP_PSH 0x08U +#define TCP_ACK 0x10U +#define TCP_URG 0x20U +#define TCP_ECE 0x40U +#define TCP_CWR 0x80U + +#define TCP_FLAGS 0x3fU + +/* Length of the TCP header, excluding options. */ +#define TCP_HLEN 20 + +#ifndef TCP_TMR_INTERVAL +#define TCP_TMR_INTERVAL 250 /* The TCP timer interval in milliseconds. */ +#endif /* TCP_TMR_INTERVAL */ + +#ifndef TCP_FAST_INTERVAL +#define TCP_FAST_INTERVAL TCP_TMR_INTERVAL /* the fine grained timeout in milliseconds */ +#endif /* TCP_FAST_INTERVAL */ + +#ifndef TCP_SLOW_INTERVAL +#define TCP_SLOW_INTERVAL (2*TCP_TMR_INTERVAL) /* the coarse grained timeout in milliseconds */ +#endif /* TCP_SLOW_INTERVAL */ + +#define TCP_FIN_WAIT_TIMEOUT 20000 /* milliseconds */ +#define TCP_SYN_RCVD_TIMEOUT 20000 /* milliseconds */ + +#define TCP_OOSEQ_TIMEOUT 6U /* x RTO */ + +#ifndef TCP_MSL +#define TCP_MSL 60000UL /* The maximum segment lifetime in milliseconds */ +#endif + +/* Keepalive values, compliant with RFC 1122. Don't change this unless you know what you're doing */ +#ifndef TCP_KEEPIDLE_DEFAULT +#define TCP_KEEPIDLE_DEFAULT 7200000UL /* Default KEEPALIVE timer in milliseconds */ +#endif + +#ifndef TCP_KEEPINTVL_DEFAULT +#define TCP_KEEPINTVL_DEFAULT 75000UL /* Default Time between KEEPALIVE probes in milliseconds */ +#endif + +#ifndef TCP_KEEPCNT_DEFAULT +#define TCP_KEEPCNT_DEFAULT 9U /* Default Counter for KEEPALIVE probes */ +#endif + +#define TCP_MAXIDLE TCP_KEEPCNT_DEFAULT * TCP_KEEPINTVL_DEFAULT /* Maximum KEEPALIVE probe time */ + +/* Fields are (of course) in network byte order. + * Some fields are converted to host byte order in tcp_input(). + */ +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct tcp_hdr { + PACK_STRUCT_FIELD(u16_t src); + PACK_STRUCT_FIELD(u16_t dest); + PACK_STRUCT_FIELD(u32_t seqno); + PACK_STRUCT_FIELD(u32_t ackno); + PACK_STRUCT_FIELD(u16_t _hdrlen_rsvd_flags); + PACK_STRUCT_FIELD(u16_t wnd); + PACK_STRUCT_FIELD(u16_t chksum); + PACK_STRUCT_FIELD(u16_t urgp); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +#define TCPH_OFFSET(phdr) (ntohs((phdr)->_hdrlen_rsvd_flags) >> 8) +#define TCPH_HDRLEN(phdr) (ntohs((phdr)->_hdrlen_rsvd_flags) >> 12) +#define TCPH_FLAGS(phdr) (ntohs((phdr)->_hdrlen_rsvd_flags) & TCP_FLAGS) + +#define TCPH_OFFSET_SET(phdr, offset) (phdr)->_hdrlen_rsvd_flags = htons(((offset) << 8) | TCPH_FLAGS(phdr)) +#define TCPH_HDRLEN_SET(phdr, len) (phdr)->_hdrlen_rsvd_flags = htons(((len) << 12) | TCPH_FLAGS(phdr)) +#define TCPH_FLAGS_SET(phdr, flags) (phdr)->_hdrlen_rsvd_flags = (((phdr)->_hdrlen_rsvd_flags & PP_HTONS((u16_t)(~(u16_t)(TCP_FLAGS)))) | htons(flags)) +#define TCPH_HDRLEN_FLAGS_SET(phdr, len, flags) (phdr)->_hdrlen_rsvd_flags = htons(((len) << 12) | (flags)) + +#define TCPH_SET_FLAG(phdr, flags ) (phdr)->_hdrlen_rsvd_flags = ((phdr)->_hdrlen_rsvd_flags | htons(flags)) +#define TCPH_UNSET_FLAG(phdr, flags) (phdr)->_hdrlen_rsvd_flags = htons(ntohs((phdr)->_hdrlen_rsvd_flags) | (TCPH_FLAGS(phdr) & ~(flags)) ) + +#define TCP_TCPLEN(seg) ((seg)->len + ((TCPH_FLAGS((seg)->tcphdr) & (TCP_FIN | TCP_SYN)) != 0)) + +/** Flags used on input processing, not on pcb->flags +*/ +#define TF_RESET (u8_t)0x08U /* Connection was reset. */ +#define TF_CLOSED (u8_t)0x10U /* Connection was sucessfully closed. */ +#define TF_GOT_FIN (u8_t)0x20U /* Connection was closed by the remote end. */ + + +#if LWIP_EVENT_API + +#define TCP_EVENT_ACCEPT(pcb,err,ret) ret = lwip_tcp_event((pcb)->callback_arg, (pcb),\ + LWIP_EVENT_ACCEPT, NULL, 0, err) +#define TCP_EVENT_SENT(pcb,space,ret) ret = lwip_tcp_event((pcb)->callback_arg, (pcb),\ + LWIP_EVENT_SENT, NULL, space, ERR_OK) +#define TCP_EVENT_RECV(pcb,p,err,ret) ret = lwip_tcp_event((pcb)->callback_arg, (pcb),\ + LWIP_EVENT_RECV, (p), 0, (err)) +#define TCP_EVENT_CLOSED(pcb,ret) ret = lwip_tcp_event((pcb)->callback_arg, (pcb),\ + LWIP_EVENT_RECV, NULL, 0, ERR_OK) +#define TCP_EVENT_CONNECTED(pcb,err,ret) ret = lwip_tcp_event((pcb)->callback_arg, (pcb),\ + LWIP_EVENT_CONNECTED, NULL, 0, (err)) +#define TCP_EVENT_POLL(pcb,ret) ret = lwip_tcp_event((pcb)->callback_arg, (pcb),\ + LWIP_EVENT_POLL, NULL, 0, ERR_OK) +#define TCP_EVENT_ERR(errf,arg,err) lwip_tcp_event((arg), NULL, \ + LWIP_EVENT_ERR, NULL, 0, (err)) + +#else /* LWIP_EVENT_API */ + +#define TCP_EVENT_ACCEPT(pcb,err,ret) \ + do { \ + if((pcb)->accept != NULL) \ + (ret) = (pcb)->accept((pcb)->callback_arg,(pcb),(err)); \ + else (ret) = ERR_ARG; \ + } while (0) + +#define TCP_EVENT_SENT(pcb,space,ret) \ + do { \ + if((pcb)->sent != NULL) \ + (ret) = (pcb)->sent((pcb)->callback_arg,(pcb),(space)); \ + else (ret) = ERR_OK; \ + } while (0) + +#define TCP_EVENT_RECV(pcb,p,err,ret) \ + do { \ + if((pcb)->recv != NULL) { \ + (ret) = (pcb)->recv((pcb)->callback_arg,(pcb),(p),(err));\ + } else { \ + (ret) = tcp_recv_null(NULL, (pcb), (p), (err)); \ + } \ + } while (0) + +#define TCP_EVENT_CLOSED(pcb,ret) \ + do { \ + if(((pcb)->recv != NULL)) { \ + (ret) = (pcb)->recv((pcb)->callback_arg,(pcb),NULL,ERR_OK);\ + } else { \ + (ret) = ERR_OK; \ + } \ + } while (0) + +#define TCP_EVENT_CONNECTED(pcb,err,ret) \ + do { \ + if((pcb)->connected != NULL) \ + (ret) = (pcb)->connected((pcb)->callback_arg,(pcb),(err)); \ + else (ret) = ERR_OK; \ + } while (0) + +#define TCP_EVENT_POLL(pcb,ret) \ + do { \ + if((pcb)->poll != NULL) \ + (ret) = (pcb)->poll((pcb)->callback_arg,(pcb)); \ + else (ret) = ERR_OK; \ + } while (0) + +#define TCP_EVENT_ERR(errf,arg,err) \ + do { \ + if((errf) != NULL) \ + (errf)((arg),(err)); \ + } while (0) + +#endif /* LWIP_EVENT_API */ + +/** Enabled extra-check for TCP_OVERSIZE if LWIP_DEBUG is enabled */ +#if TCP_OVERSIZE && defined(LWIP_DEBUG) +#define TCP_OVERSIZE_DBGCHECK 1 +#else +#define TCP_OVERSIZE_DBGCHECK 0 +#endif + +/** Don't generate checksum on copy if CHECKSUM_GEN_TCP is disabled */ +#define TCP_CHECKSUM_ON_COPY (LWIP_CHECKSUM_ON_COPY && CHECKSUM_GEN_TCP) + +/* This structure represents a TCP segment on the unsent, unacked and ooseq queues */ +struct tcp_seg { + struct tcp_seg *next; /* used when putting segements on a queue */ + struct pbuf *p; /* buffer containing data + TCP header */ + u16_t len; /* the TCP length of this segment */ +#if TCP_OVERSIZE_DBGCHECK + u16_t oversize_left; /* Extra bytes available at the end of the last + pbuf in unsent (used for asserting vs. + tcp_pcb.unsent_oversized only) */ +#endif /* TCP_OVERSIZE_DBGCHECK */ +#if TCP_CHECKSUM_ON_COPY + u16_t chksum; + u8_t chksum_swapped; +#endif /* TCP_CHECKSUM_ON_COPY */ + u8_t flags; +#define TF_SEG_OPTS_MSS (u8_t)0x01U /* Include MSS option. */ +#define TF_SEG_OPTS_TS (u8_t)0x02U /* Include timestamp option. */ +#define TF_SEG_DATA_CHECKSUMMED (u8_t)0x04U /* ALL data (not the header) is + checksummed into 'chksum' */ + struct tcp_hdr *tcphdr; /* the TCP header */ +}; + +#define LWIP_TCP_OPT_LENGTH(flags) \ + (flags & TF_SEG_OPTS_MSS ? 4 : 0) + \ + (flags & TF_SEG_OPTS_TS ? 12 : 0) + +/** This returns a TCP header option for MSS in an u32_t */ +#define TCP_BUILD_MSS_OPTION(x) (x) = PP_HTONL(((u32_t)2 << 24) | \ + ((u32_t)4 << 16) | \ + (((u32_t)TCP_MSS / 256) << 8) | \ + (TCP_MSS & 255)) + +/* Global variables: */ +extern struct tcp_pcb *tcp_input_pcb; +extern u32_t tcp_ticks; + +/* The TCP PCB lists. */ +union tcp_listen_pcbs_t { /* List of all TCP PCBs in LISTEN state. */ + struct tcp_pcb_listen *listen_pcbs; + struct tcp_pcb *pcbs; +}; +extern struct tcp_pcb *tcp_bound_pcbs; +extern union tcp_listen_pcbs_t tcp_listen_pcbs; +extern struct tcp_pcb *tcp_active_pcbs; /* List of all TCP PCBs that are in a + state in which they accept or send + data. */ +extern struct tcp_pcb *tcp_tw_pcbs; /* List of all TCP PCBs in TIME-WAIT. */ + +extern struct tcp_pcb *tcp_tmp_pcb; /* Only used for temporary storage. */ + +/* Axioms about the above lists: + 1) Every TCP PCB that is not CLOSED is in one of the lists. + 2) A PCB is only in one of the lists. + 3) All PCBs in the tcp_listen_pcbs list is in LISTEN state. + 4) All PCBs in the tcp_tw_pcbs list is in TIME-WAIT state. +*/ +/* Define two macros, TCP_REG and TCP_RMV that registers a TCP PCB + with a PCB list or removes a PCB from a list, respectively. */ +#ifndef TCP_DEBUG_PCB_LISTS +#define TCP_DEBUG_PCB_LISTS 0 +#endif +#if TCP_DEBUG_PCB_LISTS +#define TCP_REG(pcbs, npcb) do {\ + LWIP_DEBUGF(TCP_DEBUG, ("TCP_REG %p local port %d\n", (npcb), (npcb)->local_port)); \ + for(tcp_tmp_pcb = *(pcbs); \ + tcp_tmp_pcb != NULL; \ + tcp_tmp_pcb = tcp_tmp_pcb->next) { \ + LWIP_ASSERT("TCP_REG: already registered\n", tcp_tmp_pcb != (npcb)); \ + } \ + LWIP_ASSERT("TCP_REG: pcb->state != CLOSED", ((pcbs) == &tcp_bound_pcbs) || ((npcb)->state != CLOSED)); \ + (npcb)->next = *(pcbs); \ + LWIP_ASSERT("TCP_REG: npcb->next != npcb", (npcb)->next != (npcb)); \ + *(pcbs) = (npcb); \ + LWIP_ASSERT("TCP_RMV: tcp_pcbs sane", tcp_pcbs_sane()); \ + tcp_timer_needed(); \ + } while(0) +#define TCP_RMV(pcbs, npcb) do { \ + LWIP_ASSERT("TCP_RMV: pcbs != NULL", *(pcbs) != NULL); \ + LWIP_DEBUGF(TCP_DEBUG, ("TCP_RMV: removing %p from %p\n", (npcb), *(pcbs))); \ + if(*(pcbs) == (npcb)) { \ + *(pcbs) = (*pcbs)->next; \ + } else for(tcp_tmp_pcb = *(pcbs); tcp_tmp_pcb != NULL; tcp_tmp_pcb = tcp_tmp_pcb->next) { \ + if(tcp_tmp_pcb->next == (npcb)) { \ + tcp_tmp_pcb->next = (npcb)->next; \ + break; \ + } \ + } \ + (npcb)->next = NULL; \ + LWIP_ASSERT("TCP_RMV: tcp_pcbs sane", tcp_pcbs_sane()); \ + LWIP_DEBUGF(TCP_DEBUG, ("TCP_RMV: removed %p from %p\n", (npcb), *(pcbs))); \ + } while(0) + +#else /* LWIP_DEBUG */ + +#define TCP_REG(pcbs, npcb) \ + do { \ + (npcb)->next = *pcbs; \ + *(pcbs) = (npcb); \ + tcp_timer_needed(); \ + } while (0) + +#define TCP_RMV(pcbs, npcb) \ + do { \ + if(*(pcbs) == (npcb)) { \ + (*(pcbs)) = (*pcbs)->next; \ + } \ + else { \ + for(tcp_tmp_pcb = *pcbs; \ + tcp_tmp_pcb != NULL; \ + tcp_tmp_pcb = tcp_tmp_pcb->next) { \ + if(tcp_tmp_pcb->next == (npcb)) { \ + tcp_tmp_pcb->next = (npcb)->next; \ + break; \ + } \ + } \ + } \ + (npcb)->next = NULL; \ + } while(0) + +#endif /* LWIP_DEBUG */ + + +/* Internal functions: */ +struct tcp_pcb *tcp_pcb_copy(struct tcp_pcb *pcb); +void tcp_pcb_purge(struct tcp_pcb *pcb); +void tcp_pcb_remove(struct tcp_pcb **pcblist, struct tcp_pcb *pcb); + +void tcp_segs_free(struct tcp_seg *seg); +void tcp_seg_free(struct tcp_seg *seg); +struct tcp_seg *tcp_seg_copy(struct tcp_seg *seg); + +#define tcp_ack(pcb) \ + do { \ + if((pcb)->flags & TF_ACK_DELAY) { \ + (pcb)->flags &= ~TF_ACK_DELAY; \ + (pcb)->flags |= TF_ACK_NOW; \ + } \ + else { \ + (pcb)->flags |= TF_ACK_DELAY; \ + } \ + } while (0) + +#define tcp_ack_now(pcb) \ + do { \ + (pcb)->flags |= TF_ACK_NOW; \ + } while (0) + +err_t tcp_send_fin(struct tcp_pcb *pcb); +err_t tcp_enqueue_flags(struct tcp_pcb *pcb, u8_t flags); + +void tcp_rexmit_seg(struct tcp_pcb *pcb, struct tcp_seg *seg); + +void tcp_rst(u32_t seqno, u32_t ackno, + ip_addr_t *local_ip, ip_addr_t *remote_ip, + u16_t local_port, u16_t remote_port); + +u32_t tcp_next_iss(void); + +void tcp_keepalive(struct tcp_pcb *pcb); +void tcp_zero_window_probe(struct tcp_pcb *pcb); + +#if TCP_CALCULATE_EFF_SEND_MSS +u16_t tcp_eff_send_mss(u16_t sendmss, ip_addr_t *addr); +#endif /* TCP_CALCULATE_EFF_SEND_MSS */ + +#if LWIP_CALLBACK_API +err_t tcp_recv_null(void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err); +#endif /* LWIP_CALLBACK_API */ + +#if TCP_DEBUG || TCP_INPUT_DEBUG || TCP_OUTPUT_DEBUG +void tcp_debug_print(struct tcp_hdr *tcphdr); +void tcp_debug_print_flags(u8_t flags); +void tcp_debug_print_state(enum tcp_state s); +void tcp_debug_print_pcbs(void); +s16_t tcp_pcbs_sane(void); +#else +# define tcp_debug_print(tcphdr) +# define tcp_debug_print_flags(flags) +# define tcp_debug_print_state(s) +# define tcp_debug_print_pcbs() +# define tcp_pcbs_sane() 1 +#endif /* TCP_DEBUG */ + +/** External function (implemented in timers.c), called when TCP detects + * that a timer is needed (i.e. active- or time-wait-pcb found). */ +void tcp_timer_needed(void); + + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_TCP */ + +#endif /* __LWIP_TCP_H__ */ diff --git a/features/unsupported/net/lwip/lwip/include/lwip/tcpip.h b/features/unsupported/net/lwip/lwip/include/lwip/tcpip.h new file mode 100644 index 00000000000..995ba8ad007 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/include/lwip/tcpip.h @@ -0,0 +1,159 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef __LWIP_TCPIP_H__ +#define __LWIP_TCPIP_H__ + +#include "lwip/opt.h" + +#if !NO_SYS /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/api_msg.h" +#include "lwip/netifapi.h" +#include "lwip/pbuf.h" +#include "lwip/api.h" +#include "lwip/sys.h" +#include "lwip/timers.h" +#include "lwip/netif.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** Define this to something that triggers a watchdog. This is called from + * tcpip_thread after processing a message. */ +#ifndef LWIP_TCPIP_THREAD_ALIVE +#define LWIP_TCPIP_THREAD_ALIVE() +#endif + +#if LWIP_TCPIP_CORE_LOCKING +/** The global semaphore to lock the stack. */ +extern sys_mutex_t lock_tcpip_core; +#define LOCK_TCPIP_CORE() sys_mutex_lock(&lock_tcpip_core) +#define UNLOCK_TCPIP_CORE() sys_mutex_unlock(&lock_tcpip_core) +#define TCPIP_APIMSG(m) tcpip_apimsg_lock(m) +#define TCPIP_APIMSG_ACK(m) +#define TCPIP_NETIFAPI(m) tcpip_netifapi_lock(m) +#define TCPIP_NETIFAPI_ACK(m) +#else /* LWIP_TCPIP_CORE_LOCKING */ +#define LOCK_TCPIP_CORE() +#define UNLOCK_TCPIP_CORE() +#define TCPIP_APIMSG(m) tcpip_apimsg(m) +#define TCPIP_APIMSG_ACK(m) sys_sem_signal(&m->conn->op_completed) +#define TCPIP_NETIFAPI(m) tcpip_netifapi(m) +#define TCPIP_NETIFAPI_ACK(m) sys_sem_signal(&m->sem) +#endif /* LWIP_TCPIP_CORE_LOCKING */ + +/** Function prototype for the init_done function passed to tcpip_init */ +typedef void (*tcpip_init_done_fn)(void *arg); +/** Function prototype for functions passed to tcpip_callback() */ +typedef void (*tcpip_callback_fn)(void *ctx); + +void tcpip_init(tcpip_init_done_fn tcpip_init_done, void *arg); + +#if LWIP_NETCONN +err_t tcpip_apimsg(struct api_msg *apimsg); +#if LWIP_TCPIP_CORE_LOCKING +err_t tcpip_apimsg_lock(struct api_msg *apimsg); +#endif /* LWIP_TCPIP_CORE_LOCKING */ +#endif /* LWIP_NETCONN */ + +err_t tcpip_input(struct pbuf *p, struct netif *inp); + +#if LWIP_NETIF_API +err_t tcpip_netifapi(struct netifapi_msg *netifapimsg); +#if LWIP_TCPIP_CORE_LOCKING +err_t tcpip_netifapi_lock(struct netifapi_msg *netifapimsg); +#endif /* LWIP_TCPIP_CORE_LOCKING */ +#endif /* LWIP_NETIF_API */ + +err_t tcpip_callback_with_block(tcpip_callback_fn function, void *ctx, u8_t block); +#define tcpip_callback(f, ctx) tcpip_callback_with_block(f, ctx, 1) + +/* free pbufs or heap memory from another context without blocking */ +err_t pbuf_free_callback(struct pbuf *p); +err_t mem_free_callback(void *m); + +#if LWIP_TCPIP_TIMEOUT +err_t tcpip_timeout(u32_t msecs, sys_timeout_handler h, void *arg); +err_t tcpip_untimeout(sys_timeout_handler h, void *arg); +#endif /* LWIP_TCPIP_TIMEOUT */ + +enum tcpip_msg_type { +#if LWIP_NETCONN + TCPIP_MSG_API, +#endif /* LWIP_NETCONN */ + TCPIP_MSG_INPKT, +#if LWIP_NETIF_API + TCPIP_MSG_NETIFAPI, +#endif /* LWIP_NETIF_API */ +#if LWIP_TCPIP_TIMEOUT + TCPIP_MSG_TIMEOUT, + TCPIP_MSG_UNTIMEOUT, +#endif /* LWIP_TCPIP_TIMEOUT */ + TCPIP_MSG_CALLBACK +}; + +struct tcpip_msg { + enum tcpip_msg_type type; + sys_sem_t *sem; + union { +#if LWIP_NETCONN + struct api_msg *apimsg; +#endif /* LWIP_NETCONN */ +#if LWIP_NETIF_API + struct netifapi_msg *netifapimsg; +#endif /* LWIP_NETIF_API */ + struct { + struct pbuf *p; + struct netif *netif; + } inp; + struct { + tcpip_callback_fn function; + void *ctx; + } cb; +#if LWIP_TCPIP_TIMEOUT + struct { + u32_t msecs; + sys_timeout_handler h; + void *arg; + } tmo; +#endif /* LWIP_TCPIP_TIMEOUT */ + } msg; +}; + +#ifdef __cplusplus +} +#endif + +#endif /* !NO_SYS */ + +#endif /* __LWIP_TCPIP_H__ */ diff --git a/features/unsupported/net/lwip/lwip/include/lwip/timers.h b/features/unsupported/net/lwip/lwip/include/lwip/timers.h new file mode 100644 index 00000000000..fb92b4b47c5 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/include/lwip/timers.h @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * Simon Goldschmidt + * + */ +#ifndef __LWIP_TIMERS_H__ +#define __LWIP_TIMERS_H__ + +#include "lwip/opt.h" + +/* Timers are not supported when NO_SYS==1 and NO_SYS_NO_TIMERS==1 */ +#define LWIP_TIMERS (!NO_SYS || (NO_SYS && !NO_SYS_NO_TIMERS)) + +#if LWIP_TIMERS + +#include "lwip/err.h" +#include "lwip/sys.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef LWIP_DEBUG_TIMERNAMES +#ifdef LWIP_DEBUG +#define LWIP_DEBUG_TIMERNAMES SYS_DEBUG +#else /* LWIP_DEBUG */ +#define LWIP_DEBUG_TIMERNAMES 0 +#endif /* LWIP_DEBUG*/ +#endif + +/** Function prototype for a timeout callback function. Register such a function + * using sys_timeout(). + * + * @param arg Additional argument to pass to the function - set up by sys_timeout() + */ +typedef void (* sys_timeout_handler)(void *arg); + +struct sys_timeo { + struct sys_timeo *next; + u32_t time; + sys_timeout_handler h; + void *arg; +#if LWIP_DEBUG_TIMERNAMES + const char* handler_name; +#endif /* LWIP_DEBUG_TIMERNAMES */ +}; + +void sys_timeouts_init(void); + +#if LWIP_DEBUG_TIMERNAMES +void sys_timeout_debug(u32_t msecs, sys_timeout_handler handler, void *arg, const char* handler_name); +#define sys_timeout(msecs, handler, arg) sys_timeout_debug(msecs, handler, arg, #handler) +#else /* LWIP_DEBUG_TIMERNAMES */ +void sys_timeout(u32_t msecs, sys_timeout_handler handler, void *arg); +#endif /* LWIP_DEBUG_TIMERNAMES */ + +void sys_untimeout(sys_timeout_handler handler, void *arg); +#if NO_SYS +void sys_check_timeouts(void); +void sys_restart_timeouts(void); +#else /* NO_SYS */ +void sys_timeouts_mbox_fetch(sys_mbox_t *mbox, void **msg); +#endif /* NO_SYS */ + + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_TIMERS */ +#endif /* __LWIP_TIMERS_H__ */ diff --git a/features/unsupported/net/lwip/lwip/include/lwip/udp.h b/features/unsupported/net/lwip/lwip/include/lwip/udp.h new file mode 100644 index 00000000000..c98c1b3ec14 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/include/lwip/udp.h @@ -0,0 +1,171 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef __LWIP_UDP_H__ +#define __LWIP_UDP_H__ + +#include "lwip/opt.h" + +#if LWIP_UDP /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/pbuf.h" +#include "lwip/netif.h" +#include "lwip/ip_addr.h" +#include "lwip/ip.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define UDP_HLEN 8 + +/* Fields are (of course) in network byte order. */ +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct udp_hdr { + PACK_STRUCT_FIELD(u16_t src); + PACK_STRUCT_FIELD(u16_t dest); /* src/dest UDP ports */ + PACK_STRUCT_FIELD(u16_t len); + PACK_STRUCT_FIELD(u16_t chksum); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +#define UDP_FLAGS_NOCHKSUM 0x01U +#define UDP_FLAGS_UDPLITE 0x02U +#define UDP_FLAGS_CONNECTED 0x04U +#define UDP_FLAGS_MULTICAST_LOOP 0x08U + +struct udp_pcb; + +/** Function prototype for udp pcb receive callback functions + * addr and port are in same byte order as in the pcb + * The callback is responsible for freeing the pbuf + * if it's not used any more. + * + * ATTENTION: Be aware that 'addr' points into the pbuf 'p' so freeing this pbuf + * makes 'addr' invalid, too. + * + * @param arg user supplied argument (udp_pcb.recv_arg) + * @param pcb the udp_pcb which received data + * @param p the packet buffer that was received + * @param addr the remote IP address from which the packet was received + * @param port the remote port from which the packet was received + */ +typedef void (*udp_recv_fn)(void *arg, struct udp_pcb *pcb, struct pbuf *p, + ip_addr_t *addr, u16_t port); + + +struct udp_pcb { +/* Common members of all PCB types */ + IP_PCB; + +/* Protocol specific PCB members */ + + struct udp_pcb *next; + + u8_t flags; + /** ports are in host byte order */ + u16_t local_port, remote_port; + +#if LWIP_IGMP + /** outgoing network interface for multicast packets */ + ip_addr_t multicast_ip; +#endif /* LWIP_IGMP */ + +#if LWIP_UDPLITE + /** used for UDP_LITE only */ + u16_t chksum_len_rx, chksum_len_tx; +#endif /* LWIP_UDPLITE */ + + /** receive callback function */ + udp_recv_fn recv; + /** user-supplied argument for the recv callback */ + void *recv_arg; +}; +/* udp_pcbs export for exernal reference (e.g. SNMP agent) */ +extern struct udp_pcb *udp_pcbs; + +/* The following functions is the application layer interface to the + UDP code. */ +struct udp_pcb * udp_new (void); +void udp_remove (struct udp_pcb *pcb); +err_t udp_bind (struct udp_pcb *pcb, ip_addr_t *ipaddr, + u16_t port); +err_t udp_connect (struct udp_pcb *pcb, ip_addr_t *ipaddr, + u16_t port); +void udp_disconnect (struct udp_pcb *pcb); +void udp_recv (struct udp_pcb *pcb, udp_recv_fn recv, + void *recv_arg); +err_t udp_sendto_if (struct udp_pcb *pcb, struct pbuf *p, + ip_addr_t *dst_ip, u16_t dst_port, + struct netif *netif); +err_t udp_sendto (struct udp_pcb *pcb, struct pbuf *p, + ip_addr_t *dst_ip, u16_t dst_port); +err_t udp_send (struct udp_pcb *pcb, struct pbuf *p); + +#if LWIP_CHECKSUM_ON_COPY +err_t udp_sendto_if_chksum(struct udp_pcb *pcb, struct pbuf *p, + ip_addr_t *dst_ip, u16_t dst_port, + struct netif *netif, u8_t have_chksum, + u16_t chksum); +err_t udp_sendto_chksum(struct udp_pcb *pcb, struct pbuf *p, + ip_addr_t *dst_ip, u16_t dst_port, + u8_t have_chksum, u16_t chksum); +err_t udp_send_chksum(struct udp_pcb *pcb, struct pbuf *p, + u8_t have_chksum, u16_t chksum); +#endif /* LWIP_CHECKSUM_ON_COPY */ + +#define udp_flags(pcb) ((pcb)->flags) +#define udp_setflags(pcb, f) ((pcb)->flags = (f)) + +/* The following functions are the lower layer interface to UDP. */ +void udp_input (struct pbuf *p, struct netif *inp); + +#define udp_init() /* Compatibility define, not init needed. */ + +#if UDP_DEBUG +void udp_debug_print(struct udp_hdr *udphdr); +#else +#define udp_debug_print(udphdr) +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_UDP */ + +#endif /* __LWIP_UDP_H__ */ diff --git a/features/unsupported/net/lwip/lwip/include/netif/etharp.h b/features/unsupported/net/lwip/lwip/include/netif/etharp.h new file mode 100644 index 00000000000..82c9f20dd9b --- /dev/null +++ b/features/unsupported/net/lwip/lwip/include/netif/etharp.h @@ -0,0 +1,221 @@ +/* + * Copyright (c) 2001-2003 Swedish Institute of Computer Science. + * Copyright (c) 2003-2004 Leon Woestenberg + * Copyright (c) 2003-2004 Axon Digital Design B.V., The Netherlands. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ + +#ifndef __NETIF_ETHARP_H__ +#define __NETIF_ETHARP_H__ + +#include "lwip/opt.h" + +#if LWIP_ARP || LWIP_ETHERNET /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/pbuf.h" +#include "lwip/ip_addr.h" +#include "lwip/netif.h" +#include "lwip/ip.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef ETHARP_HWADDR_LEN +#define ETHARP_HWADDR_LEN 6 +#endif + +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct eth_addr { + PACK_STRUCT_FIELD(u8_t addr[ETHARP_HWADDR_LEN]); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +/** Ethernet header */ +struct eth_hdr { +#if ETH_PAD_SIZE + PACK_STRUCT_FIELD(u8_t padding[ETH_PAD_SIZE]); +#endif + PACK_STRUCT_FIELD(struct eth_addr dest); + PACK_STRUCT_FIELD(struct eth_addr src); + PACK_STRUCT_FIELD(u16_t type); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +#define SIZEOF_ETH_HDR (14 + ETH_PAD_SIZE) + +#if ETHARP_SUPPORT_VLAN + +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +/** VLAN header inserted between ethernet header and payload + * if 'type' in ethernet header is ETHTYPE_VLAN. + * See IEEE802.Q */ +struct eth_vlan_hdr { + PACK_STRUCT_FIELD(u16_t prio_vid); + PACK_STRUCT_FIELD(u16_t tpid); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +#define SIZEOF_VLAN_HDR 4 +#define VLAN_ID(vlan_hdr) (htons((vlan_hdr)->prio_vid) & 0xFFF) + +#endif /* ETHARP_SUPPORT_VLAN */ + +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +/** the ARP message, see RFC 826 ("Packet format") */ +struct etharp_hdr { + PACK_STRUCT_FIELD(u16_t hwtype); + PACK_STRUCT_FIELD(u16_t proto); + PACK_STRUCT_FIELD(u8_t hwlen); + PACK_STRUCT_FIELD(u8_t protolen); + PACK_STRUCT_FIELD(u16_t opcode); + PACK_STRUCT_FIELD(struct eth_addr shwaddr); + PACK_STRUCT_FIELD(struct ip_addr2 sipaddr); + PACK_STRUCT_FIELD(struct eth_addr dhwaddr); + PACK_STRUCT_FIELD(struct ip_addr2 dipaddr); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +#define SIZEOF_ETHARP_HDR 28 +#define SIZEOF_ETHARP_PACKET (SIZEOF_ETH_HDR + SIZEOF_ETHARP_HDR) + +/** 5 seconds period */ +#define ARP_TMR_INTERVAL 5000 + +#define ETHTYPE_ARP 0x0806U +#define ETHTYPE_IP 0x0800U +#define ETHTYPE_VLAN 0x8100U +#define ETHTYPE_PPPOEDISC 0x8863U /* PPP Over Ethernet Discovery Stage */ +#define ETHTYPE_PPPOE 0x8864U /* PPP Over Ethernet Session Stage */ + +/** MEMCPY-like macro to copy to/from struct eth_addr's that are local variables + * or known to be 32-bit aligned within the protocol header. */ +#ifndef ETHADDR32_COPY +#define ETHADDR32_COPY(src, dst) SMEMCPY(src, dst, ETHARP_HWADDR_LEN) +#endif + +/** MEMCPY-like macro to copy to/from struct eth_addr's that are no local + * variables and known to be 16-bit aligned within the protocol header. */ +#ifndef ETHADDR16_COPY +#define ETHADDR16_COPY(src, dst) SMEMCPY(src, dst, ETHARP_HWADDR_LEN) +#endif + +#if LWIP_ARP /* don't build if not configured for use in lwipopts.h */ + +/** ARP message types (opcodes) */ +#define ARP_REQUEST 1 +#define ARP_REPLY 2 + +/** Define this to 1 and define LWIP_ARP_FILTER_NETIF_FN(pbuf, netif, type) + * to a filter function that returns the correct netif when using multiple + * netifs on one hardware interface where the netif's low-level receive + * routine cannot decide for the correct netif (e.g. when mapping multiple + * IP addresses to one hardware interface). + */ +#ifndef LWIP_ARP_FILTER_NETIF +#define LWIP_ARP_FILTER_NETIF 0 +#endif + +#if ARP_QUEUEING +/** struct for queueing outgoing packets for unknown address + * defined here to be accessed by memp.h + */ +struct etharp_q_entry { + struct etharp_q_entry *next; + struct pbuf *p; +}; +#endif /* ARP_QUEUEING */ + +#define etharp_init() /* Compatibility define, not init needed. */ +void etharp_tmr(void); +s8_t etharp_find_addr(struct netif *netif, ip_addr_t *ipaddr, + struct eth_addr **eth_ret, ip_addr_t **ip_ret); +err_t etharp_output(struct netif *netif, struct pbuf *q, ip_addr_t *ipaddr); +err_t etharp_query(struct netif *netif, ip_addr_t *ipaddr, struct pbuf *q); +err_t etharp_request(struct netif *netif, ip_addr_t *ipaddr); +/** For Ethernet network interfaces, we might want to send "gratuitous ARP"; + * this is an ARP packet sent by a node in order to spontaneously cause other + * nodes to update an entry in their ARP cache. + * From RFC 3220 "IP Mobility Support for IPv4" section 4.6. */ +#define etharp_gratuitous(netif) etharp_request((netif), &(netif)->ip_addr) + +#if ETHARP_SUPPORT_STATIC_ENTRIES +err_t etharp_add_static_entry(ip_addr_t *ipaddr, struct eth_addr *ethaddr); +err_t etharp_remove_static_entry(ip_addr_t *ipaddr); +#endif /* ETHARP_SUPPORT_STATIC_ENTRIES */ + +#if LWIP_AUTOIP +err_t etharp_raw(struct netif *netif, const struct eth_addr *ethsrc_addr, + const struct eth_addr *ethdst_addr, + const struct eth_addr *hwsrc_addr, const ip_addr_t *ipsrc_addr, + const struct eth_addr *hwdst_addr, const ip_addr_t *ipdst_addr, + const u16_t opcode); +#endif /* LWIP_AUTOIP */ + +#endif /* LWIP_ARP */ + +err_t ethernet_input(struct pbuf *p, struct netif *netif); + +#define eth_addr_cmp(addr1, addr2) (memcmp((addr1)->addr, (addr2)->addr, ETHARP_HWADDR_LEN) == 0) + +extern const struct eth_addr ethbroadcast, ethzero; + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_ARP || LWIP_ETHERNET */ + +#endif /* __NETIF_ARP_H__ */ diff --git a/features/unsupported/net/lwip/lwip/include/netif/ppp_oe.h b/features/unsupported/net/lwip/lwip/include/netif/ppp_oe.h new file mode 100644 index 00000000000..e1cdfa51991 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/include/netif/ppp_oe.h @@ -0,0 +1,190 @@ +/***************************************************************************** +* ppp_oe.h - PPP Over Ethernet implementation for lwIP. +* +* Copyright (c) 2006 by Marc Boucher, Services Informatiques (MBSI) inc. +* +* The authors hereby grant permission to use, copy, modify, distribute, +* and license this software and its documentation for any purpose, provided +* that existing copyright notices are retained in all copies and that this +* notice and the following disclaimer are included verbatim in any +* distributions. No written agreement, license, or royalty fee is required +* for any of the authorized uses. +* +* THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS *AS IS* AND ANY EXPRESS OR +* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +* IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT +* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +****************************************************************************** +* REVISION HISTORY +* +* 06-01-01 Marc Boucher +* Ported to lwIP. +*****************************************************************************/ + + + +/* based on NetBSD: if_pppoe.c,v 1.64 2006/01/31 23:50:15 martin Exp */ + +/*- + * Copyright (c) 2002 The NetBSD Foundation, Inc. + * All rights reserved. + * + * This code is derived from software contributed to The NetBSD Foundation + * by Martin Husemann . + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the NetBSD + * Foundation, Inc. and its contributors. + * 4. Neither the name of The NetBSD Foundation nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS + * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +#ifndef PPP_OE_H +#define PPP_OE_H + +#include "lwip/opt.h" + +#if PPPOE_SUPPORT > 0 + +#include "netif/etharp.h" + +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct pppoehdr { + PACK_STRUCT_FIELD(u8_t vertype); + PACK_STRUCT_FIELD(u8_t code); + PACK_STRUCT_FIELD(u16_t session); + PACK_STRUCT_FIELD(u16_t plen); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct pppoetag { + PACK_STRUCT_FIELD(u16_t tag); + PACK_STRUCT_FIELD(u16_t len); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + + +#define PPPOE_STATE_INITIAL 0 +#define PPPOE_STATE_PADI_SENT 1 +#define PPPOE_STATE_PADR_SENT 2 +#define PPPOE_STATE_SESSION 3 +#define PPPOE_STATE_CLOSING 4 +/* passive */ +#define PPPOE_STATE_PADO_SENT 1 + +#define PPPOE_HEADERLEN sizeof(struct pppoehdr) +#define PPPOE_VERTYPE 0x11 /* VER=1, TYPE = 1 */ + +#define PPPOE_TAG_EOL 0x0000 /* end of list */ +#define PPPOE_TAG_SNAME 0x0101 /* service name */ +#define PPPOE_TAG_ACNAME 0x0102 /* access concentrator name */ +#define PPPOE_TAG_HUNIQUE 0x0103 /* host unique */ +#define PPPOE_TAG_ACCOOKIE 0x0104 /* AC cookie */ +#define PPPOE_TAG_VENDOR 0x0105 /* vendor specific */ +#define PPPOE_TAG_RELAYSID 0x0110 /* relay session id */ +#define PPPOE_TAG_SNAME_ERR 0x0201 /* service name error */ +#define PPPOE_TAG_ACSYS_ERR 0x0202 /* AC system error */ +#define PPPOE_TAG_GENERIC_ERR 0x0203 /* gerneric error */ + +#define PPPOE_CODE_PADI 0x09 /* Active Discovery Initiation */ +#define PPPOE_CODE_PADO 0x07 /* Active Discovery Offer */ +#define PPPOE_CODE_PADR 0x19 /* Active Discovery Request */ +#define PPPOE_CODE_PADS 0x65 /* Active Discovery Session confirmation */ +#define PPPOE_CODE_PADT 0xA7 /* Active Discovery Terminate */ + +#ifndef ETHERMTU +#define ETHERMTU 1500 +#endif + +/* two byte PPP protocol discriminator, then IP data */ +#define PPPOE_MAXMTU (ETHERMTU-PPPOE_HEADERLEN-2) + +#ifndef PPPOE_MAX_AC_COOKIE_LEN +#define PPPOE_MAX_AC_COOKIE_LEN 64 +#endif + +struct pppoe_softc { + struct pppoe_softc *next; + struct netif *sc_ethif; /* ethernet interface we are using */ + int sc_pd; /* ppp unit number */ + void (*sc_linkStatusCB)(int pd, int up); + + int sc_state; /* discovery phase or session connected */ + struct eth_addr sc_dest; /* hardware address of concentrator */ + u16_t sc_session; /* PPPoE session id */ + +#ifdef PPPOE_TODO + char *sc_service_name; /* if != NULL: requested name of service */ + char *sc_concentrator_name; /* if != NULL: requested concentrator id */ +#endif /* PPPOE_TODO */ + u8_t sc_ac_cookie[PPPOE_MAX_AC_COOKIE_LEN]; /* content of AC cookie we must echo back */ + size_t sc_ac_cookie_len; /* length of cookie data */ +#ifdef PPPOE_SERVER + u8_t *sc_hunique; /* content of host unique we must echo back */ + size_t sc_hunique_len; /* length of host unique */ +#endif + int sc_padi_retried; /* number of PADI retries already done */ + int sc_padr_retried; /* number of PADR retries already done */ +}; + + +#define pppoe_init() /* compatibility define, no initialization needed */ + +err_t pppoe_create(struct netif *ethif, int pd, void (*linkStatusCB)(int pd, int up), struct pppoe_softc **scptr); +err_t pppoe_destroy(struct netif *ifp); + +int pppoe_connect(struct pppoe_softc *sc); +void pppoe_disconnect(struct pppoe_softc *sc); + +void pppoe_disc_input(struct netif *netif, struct pbuf *p); +void pppoe_data_input(struct netif *netif, struct pbuf *p); + +err_t pppoe_xmit(struct pppoe_softc *sc, struct pbuf *pb); + +/** used in ppp.c */ +#define PPPOE_HDRLEN (sizeof(struct eth_hdr) + PPPOE_HEADERLEN) + +#endif /* PPPOE_SUPPORT */ + +#endif /* PPP_OE_H */ diff --git a/features/unsupported/net/lwip/lwip/include/netif/slipif.h b/features/unsupported/net/lwip/lwip/include/netif/slipif.h new file mode 100644 index 00000000000..ccd03c8a16b --- /dev/null +++ b/features/unsupported/net/lwip/lwip/include/netif/slipif.h @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2001, Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef __NETIF_SLIPIF_H__ +#define __NETIF_SLIPIF_H__ + +#include "lwip/netif.h" + +#ifdef __cplusplus +extern "C" { +#endif + +err_t slipif_init(struct netif * netif); +void slipif_poll(struct netif *netif); + +#ifdef __cplusplus +} +#endif + +#endif + diff --git a/features/unsupported/net/lwip/lwip/lwipopts.h b/features/unsupported/net/lwip/lwip/lwipopts.h new file mode 100644 index 00000000000..eb8879d6823 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/lwipopts.h @@ -0,0 +1,150 @@ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef LWIPOPTS_H +#define LWIPOPTS_H + +#include "lwipopts_conf.h" + +// Operating System +#define NO_SYS 0 + +#if NO_SYS == 0 +#include "cmsis_os.h" + +#define SYS_LIGHTWEIGHT_PROT 1 + +#define LWIP_RAW 0 + +#define TCPIP_MBOX_SIZE 8 +#define DEFAULT_TCP_RECVMBOX_SIZE 8 +#define DEFAULT_UDP_RECVMBOX_SIZE 8 +#define DEFAULT_RAW_RECVMBOX_SIZE 8 +#define DEFAULT_ACCEPTMBOX_SIZE 8 + +#define TCPIP_THREAD_STACKSIZE 1024 +#define TCPIP_THREAD_PRIO (osPriorityNormal) + +#define DEFAULT_THREAD_STACKSIZE 512 + +#define MEMP_NUM_SYS_TIMEOUT 16 +#endif + +// 32-bit alignment +#define MEM_ALIGNMENT 4 + +#define PBUF_POOL_SIZE 5 +#define MEMP_NUM_TCP_PCB_LISTEN 4 +#define MEMP_NUM_TCP_PCB 4 +#define MEMP_NUM_UDP_PCB 4 +#define MEMP_NUM_PBUF 8 +#define MEMP_NUM_NETBUF 8 + +#define TCP_QUEUE_OOSEQ 0 +#define TCP_OVERSIZE 0 + +#define LWIP_DHCP 1 +#define LWIP_DNS 1 + +// Support Multicast +#include "stdlib.h" +#define LWIP_IGMP 1 +#define LWIP_RAND() rand() + +#define LWIP_COMPAT_SOCKETS 0 +#define LWIP_POSIX_SOCKETS_IO_NAMES 0 +#define LWIP_SO_RCVTIMEO 1 +#define LWIP_TCP_KEEPALIVE 1 + +// Debug Options +// #define LWIP_DEBUG +#define UDP_LPC_EMAC LWIP_DBG_OFF +#define SYS_DEBUG LWIP_DBG_OFF +#define PPP_DEBUG LWIP_DBG_OFF +#define IP_DEBUG LWIP_DBG_OFF +#define MEM_DEBUG LWIP_DBG_OFF +#define MEMP_DEBUG LWIP_DBG_OFF +#define PBUF_DEBUG LWIP_DBG_OFF +#define API_LIB_DEBUG LWIP_DBG_OFF +#define API_MSG_DEBUG LWIP_DBG_OFF +#define TCPIP_DEBUG LWIP_DBG_OFF +#define SOCKETS_DEBUG LWIP_DBG_OFF +#define TCP_DEBUG LWIP_DBG_OFF +#define TCP_INPUT_DEBUG LWIP_DBG_OFF +#define TCP_FR_DEBUG LWIP_DBG_OFF +#define TCP_RTO_DEBUG LWIP_DBG_OFF +#define TCP_CWND_DEBUG LWIP_DBG_OFF +#define TCP_WND_DEBUG LWIP_DBG_OFF +#define TCP_OUTPUT_DEBUG LWIP_DBG_OFF +#define TCP_RST_DEBUG LWIP_DBG_OFF +#define TCP_QLEN_DEBUG LWIP_DBG_OFF +#define ETHARP_DEBUG LWIP_DBG_OFF +#define NETIF_DEBUG LWIP_DBG_OFF +#define DHCP_DEBUG LWIP_DBG_OFF + +#ifdef LWIP_DEBUG +#define MEMP_OVERFLOW_CHECK 1 +#define MEMP_SANITY_CHECK 1 +#else +#define LWIP_NOASSERT 1 +#define LWIP_STATS 0 +#endif + +#define LWIP_PLATFORM_BYTESWAP 1 + +#if LWIP_TRANSPORT_ETHERNET + +/* MSS should match the hardware packet size */ +#define TCP_MSS 1460 +#define TCP_SND_BUF (2 * TCP_MSS) +#define TCP_WND (2 * TCP_MSS) +#define TCP_SND_QUEUELEN (2 * TCP_SND_BUF/TCP_MSS) + +// Broadcast +#define IP_SOF_BROADCAST 1 +#define IP_SOF_BROADCAST_RECV 1 + +#define LWIP_BROADCAST_PING 1 + +#define LWIP_CHECKSUM_ON_COPY 1 + +#define LWIP_NETIF_HOSTNAME 1 +#define LWIP_NETIF_STATUS_CALLBACK 1 +#define LWIP_NETIF_LINK_CALLBACK 1 + +#elif LWIP_TRANSPORT_PPP + +#define TCP_SND_BUF (3 * 536) +#define TCP_WND (2 * 536) + +#define LWIP_ARP 0 + +#define PPP_SUPPORT 1 +#define CHAP_SUPPORT 1 +#define PAP_SUPPORT 1 +#define PPP_THREAD_STACKSIZE 4*192 +#define PPP_THREAD_PRIO 0 + +#define MAXNAMELEN 64 /* max length of hostname or name for auth */ +#define MAXSECRETLEN 64 + +#else +#error A transport mechanism (Ethernet or PPP) must be defined +#endif + +#endif /* LWIPOPTS_H_ */ diff --git a/features/unsupported/net/lwip/lwip/netif/etharp.c b/features/unsupported/net/lwip/lwip/netif/etharp.c new file mode 100644 index 00000000000..b60dadd0244 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/netif/etharp.c @@ -0,0 +1,1318 @@ +/** + * @file + * Address Resolution Protocol module for IP over Ethernet + * + * Functionally, ARP is divided into two parts. The first maps an IP address + * to a physical address when sending a packet, and the second part answers + * requests from other machines for our physical address. + * + * This implementation complies with RFC 826 (Ethernet ARP). It supports + * Gratuitious ARP from RFC3220 (IP Mobility Support for IPv4) section 4.6 + * if an interface calls etharp_gratuitous(our_netif) upon address change. + */ + +/* + * Copyright (c) 2001-2003 Swedish Institute of Computer Science. + * Copyright (c) 2003-2004 Leon Woestenberg + * Copyright (c) 2003-2004 Axon Digital Design B.V., The Netherlands. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + */ + +#include "lwip/opt.h" + +#if LWIP_ARP || LWIP_ETHERNET + +#include "lwip/ip_addr.h" +#include "lwip/def.h" +#include "lwip/ip.h" +#include "lwip/stats.h" +#include "lwip/snmp.h" +#include "lwip/dhcp.h" +#include "lwip/autoip.h" +#include "netif/etharp.h" + +#if PPPOE_SUPPORT +#include "netif/ppp_oe.h" +#endif /* PPPOE_SUPPORT */ + +#include + +const struct eth_addr ethbroadcast = {{0xff,0xff,0xff,0xff,0xff,0xff}}; +const struct eth_addr ethzero = {{0,0,0,0,0,0}}; + +#if LWIP_ARP /* don't build if not configured for use in lwipopts.h */ + +/** the time an ARP entry stays valid after its last update, + * for ARP_TMR_INTERVAL = 5000, this is + * (240 * 5) seconds = 20 minutes. + */ +#define ARP_MAXAGE 240 +/** the time an ARP entry stays pending after first request, + * for ARP_TMR_INTERVAL = 5000, this is + * (2 * 5) seconds = 10 seconds. + * + * @internal Keep this number at least 2, otherwise it might + * run out instantly if the timeout occurs directly after a request. + */ +#define ARP_MAXPENDING 2 + +#define HWTYPE_ETHERNET 1 + +enum etharp_state { + ETHARP_STATE_EMPTY = 0, + ETHARP_STATE_PENDING, + ETHARP_STATE_STABLE +}; + +struct etharp_entry { +#if ARP_QUEUEING + /** Pointer to queue of pending outgoing packets on this ARP entry. */ + struct etharp_q_entry *q; +#else /* ARP_QUEUEING */ + /** Pointer to a single pending outgoing packet on this ARP entry. */ + struct pbuf *q; +#endif /* ARP_QUEUEING */ + ip_addr_t ipaddr; + struct eth_addr ethaddr; +#if LWIP_SNMP + struct netif *netif; +#endif /* LWIP_SNMP */ + u8_t state; + u8_t ctime; +#if ETHARP_SUPPORT_STATIC_ENTRIES + u8_t static_entry; +#endif /* ETHARP_SUPPORT_STATIC_ENTRIES */ +}; + +static struct etharp_entry arp_table[ARP_TABLE_SIZE]; + +#if !LWIP_NETIF_HWADDRHINT +static u8_t etharp_cached_entry; +#endif /* !LWIP_NETIF_HWADDRHINT */ + +/** Try hard to create a new entry - we want the IP address to appear in + the cache (even if this means removing an active entry or so). */ +#define ETHARP_FLAG_TRY_HARD 1 +#define ETHARP_FLAG_FIND_ONLY 2 +#define ETHARP_FLAG_STATIC_ENTRY 4 + +#if LWIP_NETIF_HWADDRHINT +#define ETHARP_SET_HINT(netif, hint) if (((netif) != NULL) && ((netif)->addr_hint != NULL)) \ + *((netif)->addr_hint) = (hint); +#else /* LWIP_NETIF_HWADDRHINT */ +#define ETHARP_SET_HINT(netif, hint) (etharp_cached_entry = (hint)) +#endif /* LWIP_NETIF_HWADDRHINT */ + +static err_t update_arp_entry(struct netif *netif, ip_addr_t *ipaddr, struct eth_addr *ethaddr, u8_t flags); + + +/* Some checks, instead of etharp_init(): */ +#if (LWIP_ARP && (ARP_TABLE_SIZE > 0x7f)) + #error "ARP_TABLE_SIZE must fit in an s8_t, you have to reduce it in your lwipopts.h" +#endif + + +#if ARP_QUEUEING +/** + * Free a complete queue of etharp entries + * + * @param q a qeueue of etharp_q_entry's to free + */ +static void +free_etharp_q(struct etharp_q_entry *q) +{ + struct etharp_q_entry *r; + LWIP_ASSERT("q != NULL", q != NULL); + LWIP_ASSERT("q->p != NULL", q->p != NULL); + while (q) { + r = q; + q = q->next; + LWIP_ASSERT("r->p != NULL", (r->p != NULL)); + pbuf_free(r->p); + memp_free(MEMP_ARP_QUEUE, r); + } +} +#else /* ARP_QUEUEING */ + +/** Compatibility define: free the queued pbuf */ +#define free_etharp_q(q) pbuf_free(q) + +#endif /* ARP_QUEUEING */ + +/** Clean up ARP table entries */ +static void +free_entry(int i) +{ + /* remove from SNMP ARP index tree */ + snmp_delete_arpidx_tree(arp_table[i].netif, &arp_table[i].ipaddr); + /* and empty packet queue */ + if (arp_table[i].q != NULL) { + /* remove all queued packets */ + LWIP_DEBUGF(ETHARP_DEBUG, ("etharp_timer: freeing entry %"U16_F", packet queue %p.\n", (u16_t)i, (void *)(arp_table[i].q))); + free_etharp_q(arp_table[i].q); + arp_table[i].q = NULL; + } + /* recycle entry for re-use */ + arp_table[i].state = ETHARP_STATE_EMPTY; +#if ETHARP_SUPPORT_STATIC_ENTRIES + arp_table[i].static_entry = 0; +#endif /* ETHARP_SUPPORT_STATIC_ENTRIES */ +#ifdef LWIP_DEBUG + /* for debugging, clean out the complete entry */ + arp_table[i].ctime = 0; +#if LWIP_SNMP + arp_table[i].netif = NULL; +#endif /* LWIP_SNMP */ + ip_addr_set_zero(&arp_table[i].ipaddr); + arp_table[i].ethaddr = ethzero; +#endif /* LWIP_DEBUG */ +} + +/** + * Clears expired entries in the ARP table. + * + * This function should be called every ETHARP_TMR_INTERVAL milliseconds (5 seconds), + * in order to expire entries in the ARP table. + */ +void +etharp_tmr(void) +{ + u8_t i; + + LWIP_DEBUGF(ETHARP_DEBUG, ("etharp_timer\n")); + /* remove expired entries from the ARP table */ + for (i = 0; i < ARP_TABLE_SIZE; ++i) { + u8_t state = arp_table[i].state; + if (state != ETHARP_STATE_EMPTY +#if ETHARP_SUPPORT_STATIC_ENTRIES + && (arp_table[i].static_entry == 0) +#endif /* ETHARP_SUPPORT_STATIC_ENTRIES */ + ) { + arp_table[i].ctime++; + if ((arp_table[i].ctime >= ARP_MAXAGE) || + ((arp_table[i].state == ETHARP_STATE_PENDING) && + (arp_table[i].ctime >= ARP_MAXPENDING))) { + /* pending or stable entry has become old! */ + LWIP_DEBUGF(ETHARP_DEBUG, ("etharp_timer: expired %s entry %"U16_F".\n", + arp_table[i].state == ETHARP_STATE_STABLE ? "stable" : "pending", (u16_t)i)); + /* clean up entries that have just been expired */ + free_entry(i); + } +#if ARP_QUEUEING + /* still pending entry? (not expired) */ + if (arp_table[i].state == ETHARP_STATE_PENDING) { + /* resend an ARP query here? */ + } +#endif /* ARP_QUEUEING */ + } + } +} + +/** + * Search the ARP table for a matching or new entry. + * + * If an IP address is given, return a pending or stable ARP entry that matches + * the address. If no match is found, create a new entry with this address set, + * but in state ETHARP_EMPTY. The caller must check and possibly change the + * state of the returned entry. + * + * If ipaddr is NULL, return a initialized new entry in state ETHARP_EMPTY. + * + * In all cases, attempt to create new entries from an empty entry. If no + * empty entries are available and ETHARP_FLAG_TRY_HARD flag is set, recycle + * old entries. Heuristic choose the least important entry for recycling. + * + * @param ipaddr IP address to find in ARP cache, or to add if not found. + * @param flags @see definition of ETHARP_FLAG_* + * @param netif netif related to this address (used for NETIF_HWADDRHINT) + * + * @return The ARP entry index that matched or is created, ERR_MEM if no + * entry is found or could be recycled. + */ +static s8_t +find_entry(ip_addr_t *ipaddr, u8_t flags) +{ + s8_t old_pending = ARP_TABLE_SIZE, old_stable = ARP_TABLE_SIZE; + s8_t empty = ARP_TABLE_SIZE; + u8_t i = 0, age_pending = 0, age_stable = 0; + /* oldest entry with packets on queue */ + s8_t old_queue = ARP_TABLE_SIZE; + /* its age */ + u8_t age_queue = 0; + + /** + * a) do a search through the cache, remember candidates + * b) select candidate entry + * c) create new entry + */ + + /* a) in a single search sweep, do all of this + * 1) remember the first empty entry (if any) + * 2) remember the oldest stable entry (if any) + * 3) remember the oldest pending entry without queued packets (if any) + * 4) remember the oldest pending entry with queued packets (if any) + * 5) search for a matching IP entry, either pending or stable + * until 5 matches, or all entries are searched for. + */ + + for (i = 0; i < ARP_TABLE_SIZE; ++i) { + u8_t state = arp_table[i].state; + /* no empty entry found yet and now we do find one? */ + if ((empty == ARP_TABLE_SIZE) && (state == ETHARP_STATE_EMPTY)) { + LWIP_DEBUGF(ETHARP_DEBUG, ("find_entry: found empty entry %"U16_F"\n", (u16_t)i)); + /* remember first empty entry */ + empty = i; + } else if (state != ETHARP_STATE_EMPTY) { + LWIP_ASSERT("state == ETHARP_STATE_PENDING || state == ETHARP_STATE_STABLE", + state == ETHARP_STATE_PENDING || state == ETHARP_STATE_STABLE); + /* if given, does IP address match IP address in ARP entry? */ + if (ipaddr && ip_addr_cmp(ipaddr, &arp_table[i].ipaddr)) { + LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("find_entry: found matching entry %"U16_F"\n", (u16_t)i)); + /* found exact IP address match, simply bail out */ + return i; + } + /* pending entry? */ + if (state == ETHARP_STATE_PENDING) { + /* pending with queued packets? */ + if (arp_table[i].q != NULL) { + if (arp_table[i].ctime >= age_queue) { + old_queue = i; + age_queue = arp_table[i].ctime; + } + } else + /* pending without queued packets? */ + { + if (arp_table[i].ctime >= age_pending) { + old_pending = i; + age_pending = arp_table[i].ctime; + } + } + /* stable entry? */ + } else if (state == ETHARP_STATE_STABLE) { +#if ETHARP_SUPPORT_STATIC_ENTRIES + /* don't record old_stable for static entries since they never expire */ + if (arp_table[i].static_entry == 0) +#endif /* ETHARP_SUPPORT_STATIC_ENTRIES */ + { + /* remember entry with oldest stable entry in oldest, its age in maxtime */ + if (arp_table[i].ctime >= age_stable) { + old_stable = i; + age_stable = arp_table[i].ctime; + } + } + } + } + } + /* { we have no match } => try to create a new entry */ + + /* don't create new entry, only search? */ + if (((flags & ETHARP_FLAG_FIND_ONLY) != 0) || + /* or no empty entry found and not allowed to recycle? */ + ((empty == ARP_TABLE_SIZE) && ((flags & ETHARP_FLAG_TRY_HARD) == 0))) { + LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("find_entry: no empty entry found and not allowed to recycle\n")); + return (s8_t)ERR_MEM; + } + + /* b) choose the least destructive entry to recycle: + * 1) empty entry + * 2) oldest stable entry + * 3) oldest pending entry without queued packets + * 4) oldest pending entry with queued packets + * + * { ETHARP_FLAG_TRY_HARD is set at this point } + */ + + /* 1) empty entry available? */ + if (empty < ARP_TABLE_SIZE) { + i = empty; + LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("find_entry: selecting empty entry %"U16_F"\n", (u16_t)i)); + } else { + /* 2) found recyclable stable entry? */ + if (old_stable < ARP_TABLE_SIZE) { + /* recycle oldest stable*/ + i = old_stable; + LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("find_entry: selecting oldest stable entry %"U16_F"\n", (u16_t)i)); + /* no queued packets should exist on stable entries */ + LWIP_ASSERT("arp_table[i].q == NULL", arp_table[i].q == NULL); + /* 3) found recyclable pending entry without queued packets? */ + } else if (old_pending < ARP_TABLE_SIZE) { + /* recycle oldest pending */ + i = old_pending; + LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("find_entry: selecting oldest pending entry %"U16_F" (without queue)\n", (u16_t)i)); + /* 4) found recyclable pending entry with queued packets? */ + } else if (old_queue < ARP_TABLE_SIZE) { + /* recycle oldest pending (queued packets are free in free_entry) */ + i = old_queue; + LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("find_entry: selecting oldest pending entry %"U16_F", freeing packet queue %p\n", (u16_t)i, (void *)(arp_table[i].q))); + /* no empty or recyclable entries found */ + } else { + LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("find_entry: no empty or recyclable entries found\n")); + return (s8_t)ERR_MEM; + } + + /* { empty or recyclable entry found } */ + LWIP_ASSERT("i < ARP_TABLE_SIZE", i < ARP_TABLE_SIZE); + free_entry(i); + } + + LWIP_ASSERT("i < ARP_TABLE_SIZE", i < ARP_TABLE_SIZE); + LWIP_ASSERT("arp_table[i].state == ETHARP_STATE_EMPTY", + arp_table[i].state == ETHARP_STATE_EMPTY); + + /* IP address given? */ + if (ipaddr != NULL) { + /* set IP address */ + ip_addr_copy(arp_table[i].ipaddr, *ipaddr); + } + arp_table[i].ctime = 0; +#if ETHARP_SUPPORT_STATIC_ENTRIES + arp_table[i].static_entry = 0; +#endif /* ETHARP_SUPPORT_STATIC_ENTRIES */ + return (err_t)i; +} + +/** + * Send an IP packet on the network using netif->linkoutput + * The ethernet header is filled in before sending. + * + * @params netif the lwIP network interface on which to send the packet + * @params p the packet to send, p->payload pointing to the (uninitialized) ethernet header + * @params src the source MAC address to be copied into the ethernet header + * @params dst the destination MAC address to be copied into the ethernet header + * @return ERR_OK if the packet was sent, any other err_t on failure + */ +static err_t +etharp_send_ip(struct netif *netif, struct pbuf *p, struct eth_addr *src, struct eth_addr *dst) +{ + struct eth_hdr *ethhdr = (struct eth_hdr *)p->payload; + + LWIP_ASSERT("netif->hwaddr_len must be the same as ETHARP_HWADDR_LEN for etharp!", + (netif->hwaddr_len == ETHARP_HWADDR_LEN)); + ETHADDR32_COPY(ðhdr->dest, dst); + ETHADDR16_COPY(ðhdr->src, src); + ethhdr->type = PP_HTONS(ETHTYPE_IP); + LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_send_ip: sending packet %p\n", (void *)p)); + /* send the packet */ + return netif->linkoutput(netif, p); +} + +/** + * Update (or insert) a IP/MAC address pair in the ARP cache. + * + * If a pending entry is resolved, any queued packets will be sent + * at this point. + * + * @param netif netif related to this entry (used for NETIF_ADDRHINT) + * @param ipaddr IP address of the inserted ARP entry. + * @param ethaddr Ethernet address of the inserted ARP entry. + * @param flags @see definition of ETHARP_FLAG_* + * + * @return + * - ERR_OK Succesfully updated ARP cache. + * - ERR_MEM If we could not add a new ARP entry when ETHARP_FLAG_TRY_HARD was set. + * - ERR_ARG Non-unicast address given, those will not appear in ARP cache. + * + * @see pbuf_free() + */ +static err_t +update_arp_entry(struct netif *netif, ip_addr_t *ipaddr, struct eth_addr *ethaddr, u8_t flags) +{ + s8_t i; + LWIP_ASSERT("netif->hwaddr_len == ETHARP_HWADDR_LEN", netif->hwaddr_len == ETHARP_HWADDR_LEN); + LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("update_arp_entry: %"U16_F".%"U16_F".%"U16_F".%"U16_F" - %02"X16_F":%02"X16_F":%02"X16_F":%02"X16_F":%02"X16_F":%02"X16_F"\n", + ip4_addr1_16(ipaddr), ip4_addr2_16(ipaddr), ip4_addr3_16(ipaddr), ip4_addr4_16(ipaddr), + ethaddr->addr[0], ethaddr->addr[1], ethaddr->addr[2], + ethaddr->addr[3], ethaddr->addr[4], ethaddr->addr[5])); + /* non-unicast address? */ + if (ip_addr_isany(ipaddr) || + ip_addr_isbroadcast(ipaddr, netif) || + ip_addr_ismulticast(ipaddr)) { + LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("update_arp_entry: will not add non-unicast IP address to ARP cache\n")); + return ERR_ARG; + } + /* find or create ARP entry */ + i = find_entry(ipaddr, flags); + /* bail out if no entry could be found */ + if (i < 0) { + return (err_t)i; + } + +#if ETHARP_SUPPORT_STATIC_ENTRIES + if (flags & ETHARP_FLAG_STATIC_ENTRY) { + /* record static type */ + arp_table[i].static_entry = 1; + } +#endif /* ETHARP_SUPPORT_STATIC_ENTRIES */ + + /* mark it stable */ + arp_table[i].state = ETHARP_STATE_STABLE; + +#if LWIP_SNMP + /* record network interface */ + arp_table[i].netif = netif; +#endif /* LWIP_SNMP */ + /* insert in SNMP ARP index tree */ + snmp_insert_arpidx_tree(netif, &arp_table[i].ipaddr); + + LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("update_arp_entry: updating stable entry %"S16_F"\n", (s16_t)i)); + /* update address */ + ETHADDR32_COPY(&arp_table[i].ethaddr, ethaddr); + /* reset time stamp */ + arp_table[i].ctime = 0; + /* this is where we will send out queued packets! */ +#if ARP_QUEUEING + while (arp_table[i].q != NULL) { + struct pbuf *p; + /* remember remainder of queue */ + struct etharp_q_entry *q = arp_table[i].q; + /* pop first item off the queue */ + arp_table[i].q = q->next; + /* get the packet pointer */ + p = q->p; + /* now queue entry can be freed */ + memp_free(MEMP_ARP_QUEUE, q); +#else /* ARP_QUEUEING */ + if (arp_table[i].q != NULL) { + struct pbuf *p = arp_table[i].q; + arp_table[i].q = NULL; +#endif /* ARP_QUEUEING */ + /* send the queued IP packet */ + etharp_send_ip(netif, p, (struct eth_addr*)(netif->hwaddr), ethaddr); + /* free the queued IP packet */ + pbuf_free(p); + } + return ERR_OK; +} + +#if ETHARP_SUPPORT_STATIC_ENTRIES +/** Add a new static entry to the ARP table. If an entry exists for the + * specified IP address, this entry is overwritten. + * If packets are queued for the specified IP address, they are sent out. + * + * @param ipaddr IP address for the new static entry + * @param ethaddr ethernet address for the new static entry + * @return @see return values of etharp_add_static_entry + */ +err_t +etharp_add_static_entry(ip_addr_t *ipaddr, struct eth_addr *ethaddr) +{ + struct netif *netif; + LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_add_static_entry: %"U16_F".%"U16_F".%"U16_F".%"U16_F" - %02"X16_F":%02"X16_F":%02"X16_F":%02"X16_F":%02"X16_F":%02"X16_F"\n", + ip4_addr1_16(ipaddr), ip4_addr2_16(ipaddr), ip4_addr3_16(ipaddr), ip4_addr4_16(ipaddr), + ethaddr->addr[0], ethaddr->addr[1], ethaddr->addr[2], + ethaddr->addr[3], ethaddr->addr[4], ethaddr->addr[5])); + + netif = ip_route(ipaddr); + if (netif == NULL) { + return ERR_RTE; + } + + return update_arp_entry(netif, ipaddr, ethaddr, ETHARP_FLAG_TRY_HARD | ETHARP_FLAG_STATIC_ENTRY); +} + +/** Remove a static entry from the ARP table previously added with a call to + * etharp_add_static_entry. + * + * @param ipaddr IP address of the static entry to remove + * @return ERR_OK: entry removed + * ERR_MEM: entry wasn't found + * ERR_ARG: entry wasn't a static entry but a dynamic one + */ +err_t +etharp_remove_static_entry(ip_addr_t *ipaddr) +{ + s8_t i; + LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_remove_static_entry: %"U16_F".%"U16_F".%"U16_F".%"U16_F"\n", + ip4_addr1_16(ipaddr), ip4_addr2_16(ipaddr), ip4_addr3_16(ipaddr), ip4_addr4_16(ipaddr))); + + /* find or create ARP entry */ + i = find_entry(ipaddr, ETHARP_FLAG_FIND_ONLY); + /* bail out if no entry could be found */ + if (i < 0) { + return (err_t)i; + } + + if ((arp_table[i].state != ETHARP_STATE_STABLE) || + (arp_table[i].static_entry == 0)) { + /* entry wasn't a static entry, cannot remove it */ + return ERR_ARG; + } + /* entry found, free it */ + free_entry(i); + return ERR_OK; +} +#endif /* ETHARP_SUPPORT_STATIC_ENTRIES */ + +/** + * Finds (stable) ethernet/IP address pair from ARP table + * using interface and IP address index. + * @note the addresses in the ARP table are in network order! + * + * @param netif points to interface index + * @param ipaddr points to the (network order) IP address index + * @param eth_ret points to return pointer + * @param ip_ret points to return pointer + * @return table index if found, -1 otherwise + */ +s8_t +etharp_find_addr(struct netif *netif, ip_addr_t *ipaddr, + struct eth_addr **eth_ret, ip_addr_t **ip_ret) +{ + s8_t i; + + LWIP_ASSERT("eth_ret != NULL && ip_ret != NULL", + eth_ret != NULL && ip_ret != NULL); + + LWIP_UNUSED_ARG(netif); + + i = find_entry(ipaddr, ETHARP_FLAG_FIND_ONLY); + if((i >= 0) && arp_table[i].state == ETHARP_STATE_STABLE) { + *eth_ret = &arp_table[i].ethaddr; + *ip_ret = &arp_table[i].ipaddr; + return i; + } + return -1; +} + +#if ETHARP_TRUST_IP_MAC +/** + * Updates the ARP table using the given IP packet. + * + * Uses the incoming IP packet's source address to update the + * ARP cache for the local network. The function does not alter + * or free the packet. This function must be called before the + * packet p is passed to the IP layer. + * + * @param netif The lwIP network interface on which the IP packet pbuf arrived. + * @param p The IP packet that arrived on netif. + * + * @return NULL + * + * @see pbuf_free() + */ +static void +etharp_ip_input(struct netif *netif, struct pbuf *p) +{ + struct eth_hdr *ethhdr; + struct ip_hdr *iphdr; + ip_addr_t iphdr_src; + LWIP_ERROR("netif != NULL", (netif != NULL), return;); + + /* Only insert an entry if the source IP address of the + incoming IP packet comes from a host on the local network. */ + ethhdr = (struct eth_hdr *)p->payload; + iphdr = (struct ip_hdr *)((u8_t*)ethhdr + SIZEOF_ETH_HDR); +#if ETHARP_SUPPORT_VLAN + if (ethhdr->type == PP_HTONS(ETHTYPE_VLAN)) { + iphdr = (struct ip_hdr *)((u8_t*)ethhdr + SIZEOF_ETH_HDR + SIZEOF_VLAN_HDR); + } +#endif /* ETHARP_SUPPORT_VLAN */ + + ip_addr_copy(iphdr_src, iphdr->src); + + /* source is not on the local network? */ + if (!ip_addr_netcmp(&iphdr_src, &(netif->ip_addr), &(netif->netmask))) { + /* do nothing */ + return; + } + + LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_ip_input: updating ETHARP table.\n")); + /* update the source IP address in the cache, if present */ + /* @todo We could use ETHARP_FLAG_TRY_HARD if we think we are going to talk + * back soon (for example, if the destination IP address is ours. */ + update_arp_entry(netif, &iphdr_src, &(ethhdr->src), ETHARP_FLAG_FIND_ONLY); +} +#endif /* ETHARP_TRUST_IP_MAC */ + +/** + * Responds to ARP requests to us. Upon ARP replies to us, add entry to cache + * send out queued IP packets. Updates cache with snooped address pairs. + * + * Should be called for incoming ARP packets. The pbuf in the argument + * is freed by this function. + * + * @param netif The lwIP network interface on which the ARP packet pbuf arrived. + * @param ethaddr Ethernet address of netif. + * @param p The ARP packet that arrived on netif. Is freed by this function. + * + * @return NULL + * + * @see pbuf_free() + */ +static void +etharp_arp_input(struct netif *netif, struct eth_addr *ethaddr, struct pbuf *p) +{ + struct etharp_hdr *hdr; + struct eth_hdr *ethhdr; + /* these are aligned properly, whereas the ARP header fields might not be */ + ip_addr_t sipaddr, dipaddr; + u8_t for_us; +#if LWIP_AUTOIP + const u8_t * ethdst_hwaddr; +#endif /* LWIP_AUTOIP */ + + LWIP_ERROR("netif != NULL", (netif != NULL), return;); + + /* drop short ARP packets: we have to check for p->len instead of p->tot_len here + since a struct etharp_hdr is pointed to p->payload, so it musn't be chained! */ + if (p->len < SIZEOF_ETHARP_PACKET) { + LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_WARNING, + ("etharp_arp_input: packet dropped, too short (%"S16_F"/%"S16_F")\n", p->tot_len, + (s16_t)SIZEOF_ETHARP_PACKET)); + ETHARP_STATS_INC(etharp.lenerr); + ETHARP_STATS_INC(etharp.drop); + pbuf_free(p); + return; + } + + ethhdr = (struct eth_hdr *)p->payload; + hdr = (struct etharp_hdr *)((u8_t*)ethhdr + SIZEOF_ETH_HDR); +#if ETHARP_SUPPORT_VLAN + if (ethhdr->type == PP_HTONS(ETHTYPE_VLAN)) { + hdr = (struct etharp_hdr *)(((u8_t*)ethhdr) + SIZEOF_ETH_HDR + SIZEOF_VLAN_HDR); + } +#endif /* ETHARP_SUPPORT_VLAN */ + + /* RFC 826 "Packet Reception": */ + if ((hdr->hwtype != PP_HTONS(HWTYPE_ETHERNET)) || + (hdr->hwlen != ETHARP_HWADDR_LEN) || + (hdr->protolen != sizeof(ip_addr_t)) || + (hdr->proto != PP_HTONS(ETHTYPE_IP))) { + LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_WARNING, + ("etharp_arp_input: packet dropped, wrong hw type, hwlen, proto, protolen or ethernet type (%"U16_F"/%"U16_F"/%"U16_F"/%"U16_F")\n", + hdr->hwtype, hdr->hwlen, hdr->proto, hdr->protolen)); + ETHARP_STATS_INC(etharp.proterr); + ETHARP_STATS_INC(etharp.drop); + pbuf_free(p); + return; + } + ETHARP_STATS_INC(etharp.recv); + +#if LWIP_AUTOIP + /* We have to check if a host already has configured our random + * created link local address and continously check if there is + * a host with this IP-address so we can detect collisions */ + autoip_arp_reply(netif, hdr); +#endif /* LWIP_AUTOIP */ + + /* Copy struct ip_addr2 to aligned ip_addr, to support compilers without + * structure packing (not using structure copy which breaks strict-aliasing rules). */ + IPADDR2_COPY(&sipaddr, &hdr->sipaddr); + IPADDR2_COPY(&dipaddr, &hdr->dipaddr); + + /* this interface is not configured? */ + if (ip_addr_isany(&netif->ip_addr)) { + for_us = 0; + } else { + /* ARP packet directed to us? */ + for_us = (u8_t)ip_addr_cmp(&dipaddr, &(netif->ip_addr)); + } + + /* ARP message directed to us? + -> add IP address in ARP cache; assume requester wants to talk to us, + can result in directly sending the queued packets for this host. + ARP message not directed to us? + -> update the source IP address in the cache, if present */ + update_arp_entry(netif, &sipaddr, &(hdr->shwaddr), + for_us ? ETHARP_FLAG_TRY_HARD : ETHARP_FLAG_FIND_ONLY); + + /* now act on the message itself */ + switch (hdr->opcode) { + /* ARP request? */ + case PP_HTONS(ARP_REQUEST): + /* ARP request. If it asked for our address, we send out a + * reply. In any case, we time-stamp any existing ARP entry, + * and possiby send out an IP packet that was queued on it. */ + + LWIP_DEBUGF (ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_arp_input: incoming ARP request\n")); + /* ARP request for our address? */ + if (for_us) { + + LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_arp_input: replying to ARP request for our IP address\n")); + /* Re-use pbuf to send ARP reply. + Since we are re-using an existing pbuf, we can't call etharp_raw since + that would allocate a new pbuf. */ + hdr->opcode = htons(ARP_REPLY); + + IPADDR2_COPY(&hdr->dipaddr, &hdr->sipaddr); + IPADDR2_COPY(&hdr->sipaddr, &netif->ip_addr); + + LWIP_ASSERT("netif->hwaddr_len must be the same as ETHARP_HWADDR_LEN for etharp!", + (netif->hwaddr_len == ETHARP_HWADDR_LEN)); +#if LWIP_AUTOIP + /* If we are using Link-Local, all ARP packets that contain a Link-Local + * 'sender IP address' MUST be sent using link-layer broadcast instead of + * link-layer unicast. (See RFC3927 Section 2.5, last paragraph) */ + ethdst_hwaddr = ip_addr_islinklocal(&netif->ip_addr) ? (u8_t*)(ethbroadcast.addr) : hdr->shwaddr.addr; +#endif /* LWIP_AUTOIP */ + + ETHADDR16_COPY(&hdr->dhwaddr, &hdr->shwaddr); +#if LWIP_AUTOIP + ETHADDR16_COPY(ðhdr->dest, ethdst_hwaddr); +#else /* LWIP_AUTOIP */ + ETHADDR16_COPY(ðhdr->dest, &hdr->shwaddr); +#endif /* LWIP_AUTOIP */ + ETHADDR16_COPY(&hdr->shwaddr, ethaddr); + ETHADDR16_COPY(ðhdr->src, ethaddr); + + /* hwtype, hwaddr_len, proto, protolen and the type in the ethernet header + are already correct, we tested that before */ + + /* return ARP reply */ + netif->linkoutput(netif, p); + /* we are not configured? */ + } else if (ip_addr_isany(&netif->ip_addr)) { + /* { for_us == 0 and netif->ip_addr.addr == 0 } */ + LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_arp_input: we are unconfigured, ARP request ignored.\n")); + /* request was not directed to us */ + } else { + /* { for_us == 0 and netif->ip_addr.addr != 0 } */ + LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_arp_input: ARP request was not for us.\n")); + } + break; + case PP_HTONS(ARP_REPLY): + /* ARP reply. We already updated the ARP cache earlier. */ + LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_arp_input: incoming ARP reply\n")); +#if (LWIP_DHCP && DHCP_DOES_ARP_CHECK) + /* DHCP wants to know about ARP replies from any host with an + * IP address also offered to us by the DHCP server. We do not + * want to take a duplicate IP address on a single network. + * @todo How should we handle redundant (fail-over) interfaces? */ + dhcp_arp_reply(netif, &sipaddr); +#endif /* (LWIP_DHCP && DHCP_DOES_ARP_CHECK) */ + break; + default: + LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_arp_input: ARP unknown opcode type %"S16_F"\n", htons(hdr->opcode))); + ETHARP_STATS_INC(etharp.err); + break; + } + /* free ARP packet */ + pbuf_free(p); +} + +/** + * Resolve and fill-in Ethernet address header for outgoing IP packet. + * + * For IP multicast and broadcast, corresponding Ethernet addresses + * are selected and the packet is transmitted on the link. + * + * For unicast addresses, the packet is submitted to etharp_query(). In + * case the IP address is outside the local network, the IP address of + * the gateway is used. + * + * @param netif The lwIP network interface which the IP packet will be sent on. + * @param q The pbuf(s) containing the IP packet to be sent. + * @param ipaddr The IP address of the packet destination. + * + * @return + * - ERR_RTE No route to destination (no gateway to external networks), + * or the return type of either etharp_query() or etharp_send_ip(). + */ +err_t +etharp_output(struct netif *netif, struct pbuf *q, ip_addr_t *ipaddr) +{ + struct eth_addr *dest, mcastaddr; + + /* make room for Ethernet header - should not fail */ + if (pbuf_header(q, sizeof(struct eth_hdr)) != 0) { + /* bail out */ + LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS, + ("etharp_output: could not allocate room for header.\n")); + LINK_STATS_INC(link.lenerr); + return ERR_BUF; + } + + /* assume unresolved Ethernet address */ + dest = NULL; + /* Determine on destination hardware address. Broadcasts and multicasts + * are special, other IP addresses are looked up in the ARP table. */ + + /* broadcast destination IP address? */ + if (ip_addr_isbroadcast(ipaddr, netif)) { + /* broadcast on Ethernet also */ + dest = (struct eth_addr *)ðbroadcast; + /* multicast destination IP address? */ + } else if (ip_addr_ismulticast(ipaddr)) { + /* Hash IP multicast address to MAC address.*/ + mcastaddr.addr[0] = 0x01; + mcastaddr.addr[1] = 0x00; + mcastaddr.addr[2] = 0x5e; + mcastaddr.addr[3] = ip4_addr2(ipaddr) & 0x7f; + mcastaddr.addr[4] = ip4_addr3(ipaddr); + mcastaddr.addr[5] = ip4_addr4(ipaddr); + /* destination Ethernet address is multicast */ + dest = &mcastaddr; + /* unicast destination IP address? */ + } else { + /* outside local network? */ + if (!ip_addr_netcmp(ipaddr, &(netif->ip_addr), &(netif->netmask)) && + !ip_addr_islinklocal(ipaddr)) { +#if LWIP_AUTOIP + struct ip_hdr *iphdr = (struct ip_hdr*)((u8_t*)q->payload + + sizeof(struct eth_hdr)); + /* According to RFC 3297, chapter 2.6.2 (Forwarding Rules), a packet with + a link-local source address must always be "directly to its destination + on the same physical link. The host MUST NOT send the packet to any + router for forwarding". */ + if (!ip_addr_islinklocal(&iphdr->src)) +#endif /* LWIP_AUTOIP */ + { + /* interface has default gateway? */ + if (!ip_addr_isany(&netif->gw)) { + /* send to hardware address of default gateway IP address */ + ipaddr = &(netif->gw); + /* no default gateway available */ + } else { + /* no route to destination error (default gateway missing) */ + return ERR_RTE; + } + } + } +#if LWIP_NETIF_HWADDRHINT + if (netif->addr_hint != NULL) { + /* per-pcb cached entry was given */ + u8_t etharp_cached_entry = *(netif->addr_hint); + if (etharp_cached_entry < ARP_TABLE_SIZE) { +#endif /* LWIP_NETIF_HWADDRHINT */ + if ((arp_table[etharp_cached_entry].state == ETHARP_STATE_STABLE) && + (ip_addr_cmp(ipaddr, &arp_table[etharp_cached_entry].ipaddr))) { + /* the per-pcb-cached entry is stable and the right one! */ + ETHARP_STATS_INC(etharp.cachehit); + return etharp_send_ip(netif, q, (struct eth_addr*)(netif->hwaddr), + &arp_table[etharp_cached_entry].ethaddr); + } +#if LWIP_NETIF_HWADDRHINT + } + } +#endif /* LWIP_NETIF_HWADDRHINT */ + /* queue on destination Ethernet address belonging to ipaddr */ + return etharp_query(netif, ipaddr, q); + } + + /* continuation for multicast/broadcast destinations */ + /* obtain source Ethernet address of the given interface */ + /* send packet directly on the link */ + return etharp_send_ip(netif, q, (struct eth_addr*)(netif->hwaddr), dest); +} + +/** + * Send an ARP request for the given IP address and/or queue a packet. + * + * If the IP address was not yet in the cache, a pending ARP cache entry + * is added and an ARP request is sent for the given address. The packet + * is queued on this entry. + * + * If the IP address was already pending in the cache, a new ARP request + * is sent for the given address. The packet is queued on this entry. + * + * If the IP address was already stable in the cache, and a packet is + * given, it is directly sent and no ARP request is sent out. + * + * If the IP address was already stable in the cache, and no packet is + * given, an ARP request is sent out. + * + * @param netif The lwIP network interface on which ipaddr + * must be queried for. + * @param ipaddr The IP address to be resolved. + * @param q If non-NULL, a pbuf that must be delivered to the IP address. + * q is not freed by this function. + * + * @note q must only be ONE packet, not a packet queue! + * + * @return + * - ERR_BUF Could not make room for Ethernet header. + * - ERR_MEM Hardware address unknown, and no more ARP entries available + * to query for address or queue the packet. + * - ERR_MEM Could not queue packet due to memory shortage. + * - ERR_RTE No route to destination (no gateway to external networks). + * - ERR_ARG Non-unicast address given, those will not appear in ARP cache. + * + */ +err_t +etharp_query(struct netif *netif, ip_addr_t *ipaddr, struct pbuf *q) +{ + struct eth_addr * srcaddr = (struct eth_addr *)netif->hwaddr; + err_t result = ERR_MEM; + s8_t i; /* ARP entry index */ + + /* non-unicast address? */ + if (ip_addr_isbroadcast(ipaddr, netif) || + ip_addr_ismulticast(ipaddr) || + ip_addr_isany(ipaddr)) { + LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_query: will not add non-unicast IP address to ARP cache\n")); + return ERR_ARG; + } + + /* find entry in ARP cache, ask to create entry if queueing packet */ + i = find_entry(ipaddr, ETHARP_FLAG_TRY_HARD); + + /* could not find or create entry? */ + if (i < 0) { + LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_query: could not create ARP entry\n")); + if (q) { + LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_query: packet dropped\n")); + ETHARP_STATS_INC(etharp.memerr); + } + return (err_t)i; + } + + /* mark a fresh entry as pending (we just sent a request) */ + if (arp_table[i].state == ETHARP_STATE_EMPTY) { + arp_table[i].state = ETHARP_STATE_PENDING; + } + + /* { i is either a STABLE or (new or existing) PENDING entry } */ + LWIP_ASSERT("arp_table[i].state == PENDING or STABLE", + ((arp_table[i].state == ETHARP_STATE_PENDING) || + (arp_table[i].state == ETHARP_STATE_STABLE))); + + /* do we have a pending entry? or an implicit query request? */ + if ((arp_table[i].state == ETHARP_STATE_PENDING) || (q == NULL)) { + /* try to resolve it; send out ARP request */ + result = etharp_request(netif, ipaddr); + if (result != ERR_OK) { + /* ARP request couldn't be sent */ + /* We don't re-send arp request in etharp_tmr, but we still queue packets, + since this failure could be temporary, and the next packet calling + etharp_query again could lead to sending the queued packets. */ + } + if (q == NULL) { + return result; + } + } + + /* packet given? */ + LWIP_ASSERT("q != NULL", q != NULL); + /* stable entry? */ + if (arp_table[i].state == ETHARP_STATE_STABLE) { + /* we have a valid IP->Ethernet address mapping */ + ETHARP_SET_HINT(netif, i); + /* send the packet */ + result = etharp_send_ip(netif, q, srcaddr, &(arp_table[i].ethaddr)); + /* pending entry? (either just created or already pending */ + } else if (arp_table[i].state == ETHARP_STATE_PENDING) { + /* entry is still pending, queue the given packet 'q' */ + struct pbuf *p; + int copy_needed = 0; + /* IF q includes a PBUF_REF, PBUF_POOL or PBUF_RAM, we have no choice but + * to copy the whole queue into a new PBUF_RAM (see bug #11400) + * PBUF_ROMs can be left as they are, since ROM must not get changed. */ + p = q; + while (p) { + LWIP_ASSERT("no packet queues allowed!", (p->len != p->tot_len) || (p->next == 0)); + if(p->type != PBUF_ROM) { + copy_needed = 1; + break; + } + p = p->next; + } + if(copy_needed) { + /* copy the whole packet into new pbufs */ + p = pbuf_alloc(PBUF_RAW, p->tot_len, PBUF_RAM); + if(p != NULL) { + if (pbuf_copy(p, q) != ERR_OK) { + pbuf_free(p); + p = NULL; + } + } + } else { + /* referencing the old pbuf is enough */ + p = q; + pbuf_ref(p); + } + /* packet could be taken over? */ + if (p != NULL) { + /* queue packet ... */ +#if ARP_QUEUEING + struct etharp_q_entry *new_entry; + /* allocate a new arp queue entry */ + new_entry = (struct etharp_q_entry *)memp_malloc(MEMP_ARP_QUEUE); + if (new_entry != NULL) { + new_entry->next = 0; + new_entry->p = p; + if(arp_table[i].q != NULL) { + /* queue was already existent, append the new entry to the end */ + struct etharp_q_entry *r; + r = arp_table[i].q; + while (r->next != NULL) { + r = r->next; + } + r->next = new_entry; + } else { + /* queue did not exist, first item in queue */ + arp_table[i].q = new_entry; + } + LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_query: queued packet %p on ARP entry %"S16_F"\n", (void *)q, (s16_t)i)); + result = ERR_OK; + } else { + /* the pool MEMP_ARP_QUEUE is empty */ + pbuf_free(p); + LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_query: could not queue a copy of PBUF_REF packet %p (out of memory)\n", (void *)q)); + result = ERR_MEM; + } +#else /* ARP_QUEUEING */ + /* always queue one packet per ARP request only, freeing a previously queued packet */ + if (arp_table[i].q != NULL) { + LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_query: dropped previously queued packet %p for ARP entry %"S16_F"\n", (void *)q, (s16_t)i)); + pbuf_free(arp_table[i].q); + } + arp_table[i].q = p; + result = ERR_OK; + LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_query: queued packet %p on ARP entry %"S16_F"\n", (void *)q, (s16_t)i)); +#endif /* ARP_QUEUEING */ + } else { + ETHARP_STATS_INC(etharp.memerr); + LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_query: could not queue a copy of PBUF_REF packet %p (out of memory)\n", (void *)q)); + result = ERR_MEM; + } + } + return result; +} + +/** + * Send a raw ARP packet (opcode and all addresses can be modified) + * + * @param netif the lwip network interface on which to send the ARP packet + * @param ethsrc_addr the source MAC address for the ethernet header + * @param ethdst_addr the destination MAC address for the ethernet header + * @param hwsrc_addr the source MAC address for the ARP protocol header + * @param ipsrc_addr the source IP address for the ARP protocol header + * @param hwdst_addr the destination MAC address for the ARP protocol header + * @param ipdst_addr the destination IP address for the ARP protocol header + * @param opcode the type of the ARP packet + * @return ERR_OK if the ARP packet has been sent + * ERR_MEM if the ARP packet couldn't be allocated + * any other err_t on failure + */ +#if !LWIP_AUTOIP +static +#endif /* LWIP_AUTOIP */ +err_t +etharp_raw(struct netif *netif, const struct eth_addr *ethsrc_addr, + const struct eth_addr *ethdst_addr, + const struct eth_addr *hwsrc_addr, const ip_addr_t *ipsrc_addr, + const struct eth_addr *hwdst_addr, const ip_addr_t *ipdst_addr, + const u16_t opcode) +{ + struct pbuf *p; + err_t result = ERR_OK; + struct eth_hdr *ethhdr; + struct etharp_hdr *hdr; +#if LWIP_AUTOIP + const u8_t * ethdst_hwaddr; +#endif /* LWIP_AUTOIP */ + + /* allocate a pbuf for the outgoing ARP request packet */ + p = pbuf_alloc(PBUF_RAW, SIZEOF_ETHARP_PACKET, PBUF_RAM); + /* could allocate a pbuf for an ARP request? */ + if (p == NULL) { + LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS, + ("etharp_raw: could not allocate pbuf for ARP request.\n")); + ETHARP_STATS_INC(etharp.memerr); + return ERR_MEM; + } + LWIP_ASSERT("check that first pbuf can hold struct etharp_hdr", + (p->len >= SIZEOF_ETHARP_PACKET)); + + ethhdr = (struct eth_hdr *)p->payload; + hdr = (struct etharp_hdr *)((u8_t*)ethhdr + SIZEOF_ETH_HDR); + LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_raw: sending raw ARP packet.\n")); + hdr->opcode = htons(opcode); + + LWIP_ASSERT("netif->hwaddr_len must be the same as ETHARP_HWADDR_LEN for etharp!", + (netif->hwaddr_len == ETHARP_HWADDR_LEN)); +#if LWIP_AUTOIP + /* If we are using Link-Local, all ARP packets that contain a Link-Local + * 'sender IP address' MUST be sent using link-layer broadcast instead of + * link-layer unicast. (See RFC3927 Section 2.5, last paragraph) */ + ethdst_hwaddr = ip_addr_islinklocal(ipsrc_addr) ? (u8_t*)(ethbroadcast.addr) : ethdst_addr->addr; +#endif /* LWIP_AUTOIP */ + /* Write the ARP MAC-Addresses */ + ETHADDR16_COPY(&hdr->shwaddr, hwsrc_addr); + ETHADDR16_COPY(&hdr->dhwaddr, hwdst_addr); + /* Write the Ethernet MAC-Addresses */ +#if LWIP_AUTOIP + ETHADDR16_COPY(ðhdr->dest, ethdst_hwaddr); +#else /* LWIP_AUTOIP */ + ETHADDR16_COPY(ðhdr->dest, ethdst_addr); +#endif /* LWIP_AUTOIP */ + ETHADDR16_COPY(ðhdr->src, ethsrc_addr); + /* Copy struct ip_addr2 to aligned ip_addr, to support compilers without + * structure packing. */ + IPADDR2_COPY(&hdr->sipaddr, ipsrc_addr); + IPADDR2_COPY(&hdr->dipaddr, ipdst_addr); + + hdr->hwtype = PP_HTONS(HWTYPE_ETHERNET); + hdr->proto = PP_HTONS(ETHTYPE_IP); + /* set hwlen and protolen */ + hdr->hwlen = ETHARP_HWADDR_LEN; + hdr->protolen = sizeof(ip_addr_t); + + ethhdr->type = PP_HTONS(ETHTYPE_ARP); + /* send ARP query */ + result = netif->linkoutput(netif, p); + ETHARP_STATS_INC(etharp.xmit); + /* free ARP query packet */ + pbuf_free(p); + p = NULL; + /* could not allocate pbuf for ARP request */ + + return result; +} + +/** + * Send an ARP request packet asking for ipaddr. + * + * @param netif the lwip network interface on which to send the request + * @param ipaddr the IP address for which to ask + * @return ERR_OK if the request has been sent + * ERR_MEM if the ARP packet couldn't be allocated + * any other err_t on failure + */ +err_t +etharp_request(struct netif *netif, ip_addr_t *ipaddr) +{ + LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_request: sending ARP request.\n")); + return etharp_raw(netif, (struct eth_addr *)netif->hwaddr, ðbroadcast, + (struct eth_addr *)netif->hwaddr, &netif->ip_addr, ðzero, + ipaddr, ARP_REQUEST); +} +#endif /* LWIP_ARP */ + +/** + * Process received ethernet frames. Using this function instead of directly + * calling ip_input and passing ARP frames through etharp in ethernetif_input, + * the ARP cache is protected from concurrent access. + * + * @param p the recevied packet, p->payload pointing to the ethernet header + * @param netif the network interface on which the packet was received + */ +err_t +ethernet_input(struct pbuf *p, struct netif *netif) +{ + struct eth_hdr* ethhdr; + u16_t type; + s16_t ip_hdr_offset = SIZEOF_ETH_HDR; + + if (p->len <= SIZEOF_ETH_HDR) { + /* a packet with only an ethernet header (or less) is not valid for us */ + ETHARP_STATS_INC(etharp.proterr); + ETHARP_STATS_INC(etharp.drop); + goto free_and_return; + } + + /* points to packet payload, which starts with an Ethernet header */ + ethhdr = (struct eth_hdr *)p->payload; + LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, + ("ethernet_input: dest:%"X8_F":%"X8_F":%"X8_F":%"X8_F":%"X8_F":%"X8_F", src:%"X8_F":%"X8_F":%"X8_F":%"X8_F":%"X8_F":%"X8_F", type:%"X16_F"\n", + (unsigned)ethhdr->dest.addr[0], (unsigned)ethhdr->dest.addr[1], (unsigned)ethhdr->dest.addr[2], + (unsigned)ethhdr->dest.addr[3], (unsigned)ethhdr->dest.addr[4], (unsigned)ethhdr->dest.addr[5], + (unsigned)ethhdr->src.addr[0], (unsigned)ethhdr->src.addr[1], (unsigned)ethhdr->src.addr[2], + (unsigned)ethhdr->src.addr[3], (unsigned)ethhdr->src.addr[4], (unsigned)ethhdr->src.addr[5], + (unsigned)htons(ethhdr->type))); + + type = ethhdr->type; +#if ETHARP_SUPPORT_VLAN + if (type == PP_HTONS(ETHTYPE_VLAN)) { + struct eth_vlan_hdr *vlan = (struct eth_vlan_hdr*)(((char*)ethhdr) + SIZEOF_ETH_HDR); + if (p->len <= SIZEOF_ETH_HDR + SIZEOF_VLAN_HDR) { + /* a packet with only an ethernet/vlan header (or less) is not valid for us */ + ETHARP_STATS_INC(etharp.proterr); + ETHARP_STATS_INC(etharp.drop); + goto free_and_return; + } +#ifdef ETHARP_VLAN_CHECK /* if not, allow all VLANs */ + if (VLAN_ID(vlan) != ETHARP_VLAN_CHECK) { + /* silently ignore this packet: not for our VLAN */ + pbuf_free(p); + return ERR_OK; + } +#endif /* ETHARP_VLAN_CHECK */ + type = vlan->tpid; + ip_hdr_offset = SIZEOF_ETH_HDR + SIZEOF_VLAN_HDR; + } +#endif /* ETHARP_SUPPORT_VLAN */ + +#if LWIP_ARP_FILTER_NETIF + netif = LWIP_ARP_FILTER_NETIF_FN(p, netif, htons(type)); +#endif /* LWIP_ARP_FILTER_NETIF*/ + + switch (type) { +#if LWIP_ARP + /* IP packet? */ + case PP_HTONS(ETHTYPE_IP): + if (!(netif->flags & NETIF_FLAG_ETHARP)) { + goto free_and_return; + } +#if ETHARP_TRUST_IP_MAC + /* update ARP table */ + etharp_ip_input(netif, p); +#endif /* ETHARP_TRUST_IP_MAC */ + /* skip Ethernet header */ + if(pbuf_header(p, -ip_hdr_offset)) { + LWIP_ASSERT("Can't move over header in packet", 0); + goto free_and_return; + } else { + /* pass to IP layer */ + ip_input(p, netif); + } + break; + + case PP_HTONS(ETHTYPE_ARP): + if (!(netif->flags & NETIF_FLAG_ETHARP)) { + goto free_and_return; + } + /* pass p to ARP module */ + etharp_arp_input(netif, (struct eth_addr*)(netif->hwaddr), p); + break; +#endif /* LWIP_ARP */ +#if PPPOE_SUPPORT + case PP_HTONS(ETHTYPE_PPPOEDISC): /* PPP Over Ethernet Discovery Stage */ + pppoe_disc_input(netif, p); + break; + + case PP_HTONS(ETHTYPE_PPPOE): /* PPP Over Ethernet Session Stage */ + pppoe_data_input(netif, p); + break; +#endif /* PPPOE_SUPPORT */ + + default: + ETHARP_STATS_INC(etharp.proterr); + ETHARP_STATS_INC(etharp.drop); + goto free_and_return; + } + + /* This means the pbuf is freed or consumed, + so the caller doesn't have to free it again */ + return ERR_OK; + +free_and_return: + pbuf_free(p); + return ERR_OK; +} +#endif /* LWIP_ARP || LWIP_ETHERNET */ diff --git a/features/unsupported/net/lwip/lwip/netif/ethernetif.c b/features/unsupported/net/lwip/lwip/netif/ethernetif.c new file mode 100644 index 00000000000..a5b7d990b11 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/netif/ethernetif.c @@ -0,0 +1,318 @@ +/** + * @file + * Ethernet Interface Skeleton + * + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ + +/* + * This file is a skeleton for developing Ethernet network interface + * drivers for lwIP. Add code to the low_level functions and do a + * search-and-replace for the word "ethernetif" to replace it with + * something that better describes your network interface. + */ + +#include "lwip/opt.h" + +#if 0 /* don't build, this is only a skeleton, see previous comment */ + +#include "lwip/def.h" +#include "lwip/mem.h" +#include "lwip/pbuf.h" +#include "lwip/sys.h" +#include +#include +#include "netif/etharp.h" +#include "netif/ppp_oe.h" + +/* Define those to better describe your network interface. */ +#define IFNAME0 'e' +#define IFNAME1 'n' + +/** + * Helper struct to hold private data used to operate your ethernet interface. + * Keeping the ethernet address of the MAC in this struct is not necessary + * as it is already kept in the struct netif. + * But this is only an example, anyway... + */ +struct ethernetif { + struct eth_addr *ethaddr; + /* Add whatever per-interface state that is needed here. */ +}; + +/* Forward declarations. */ +static void ethernetif_input(struct netif *netif); + +/** + * In this function, the hardware should be initialized. + * Called from ethernetif_init(). + * + * @param netif the already initialized lwip network interface structure + * for this ethernetif + */ +static void +low_level_init(struct netif *netif) +{ + struct ethernetif *ethernetif = netif->state; + + /* set MAC hardware address length */ + netif->hwaddr_len = ETHARP_HWADDR_LEN; + + /* set MAC hardware address */ + netif->hwaddr[0] = ; + ... + netif->hwaddr[5] = ; + + /* maximum transfer unit */ + netif->mtu = 1500; + + /* device capabilities */ + /* don't set NETIF_FLAG_ETHARP if this device is not an ethernet one */ + netif->flags = NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP | NETIF_FLAG_LINK_UP; + + /* Do whatever else is needed to initialize interface. */ +} + +/** + * This function should do the actual transmission of the packet. The packet is + * contained in the pbuf that is passed to the function. This pbuf + * might be chained. + * + * @param netif the lwip network interface structure for this ethernetif + * @param p the MAC packet to send (e.g. IP packet including MAC addresses and type) + * @return ERR_OK if the packet could be sent + * an err_t value if the packet couldn't be sent + * + * @note Returning ERR_MEM here if a DMA queue of your MAC is full can lead to + * strange results. You might consider waiting for space in the DMA queue + * to become availale since the stack doesn't retry to send a packet + * dropped because of memory failure (except for the TCP timers). + */ + +static err_t +low_level_output(struct netif *netif, struct pbuf *p) +{ + struct ethernetif *ethernetif = netif->state; + struct pbuf *q; + + initiate transfer(); + +#if ETH_PAD_SIZE + pbuf_header(p, -ETH_PAD_SIZE); /* drop the padding word */ +#endif + + for(q = p; q != NULL; q = q->next) { + /* Send the data from the pbuf to the interface, one pbuf at a + time. The size of the data in each pbuf is kept in the ->len + variable. */ + send data from(q->payload, q->len); + } + + signal that packet should be sent(); + +#if ETH_PAD_SIZE + pbuf_header(p, ETH_PAD_SIZE); /* reclaim the padding word */ +#endif + + LINK_STATS_INC(link.xmit); + + return ERR_OK; +} + +/** + * Should allocate a pbuf and transfer the bytes of the incoming + * packet from the interface into the pbuf. + * + * @param netif the lwip network interface structure for this ethernetif + * @return a pbuf filled with the received packet (including MAC header) + * NULL on memory error + */ +static struct pbuf * +low_level_input(struct netif *netif) +{ + struct ethernetif *ethernetif = netif->state; + struct pbuf *p, *q; + u16_t len; + + /* Obtain the size of the packet and put it into the "len" + variable. */ + len = ; + +#if ETH_PAD_SIZE + len += ETH_PAD_SIZE; /* allow room for Ethernet padding */ +#endif + + /* We allocate a pbuf chain of pbufs from the pool. */ + p = pbuf_alloc(PBUF_RAW, len, PBUF_POOL); + + if (p != NULL) { + +#if ETH_PAD_SIZE + pbuf_header(p, -ETH_PAD_SIZE); /* drop the padding word */ +#endif + + /* We iterate over the pbuf chain until we have read the entire + * packet into the pbuf. */ + for(q = p; q != NULL; q = q->next) { + /* Read enough bytes to fill this pbuf in the chain. The + * available data in the pbuf is given by the q->len + * variable. + * This does not necessarily have to be a memcpy, you can also preallocate + * pbufs for a DMA-enabled MAC and after receiving truncate it to the + * actually received size. In this case, ensure the tot_len member of the + * pbuf is the sum of the chained pbuf len members. + */ + read data into(q->payload, q->len); + } + acknowledge that packet has been read(); + +#if ETH_PAD_SIZE + pbuf_header(p, ETH_PAD_SIZE); /* reclaim the padding word */ +#endif + + LINK_STATS_INC(link.recv); + } else { + drop packet(); + LINK_STATS_INC(link.memerr); + LINK_STATS_INC(link.drop); + } + + return p; +} + +/** + * This function should be called when a packet is ready to be read + * from the interface. It uses the function low_level_input() that + * should handle the actual reception of bytes from the network + * interface. Then the type of the received packet is determined and + * the appropriate input function is called. + * + * @param netif the lwip network interface structure for this ethernetif + */ +static void +ethernetif_input(struct netif *netif) +{ + struct ethernetif *ethernetif; + struct eth_hdr *ethhdr; + struct pbuf *p; + + ethernetif = netif->state; + + /* move received packet into a new pbuf */ + p = low_level_input(netif); + /* no packet could be read, silently ignore this */ + if (p == NULL) return; + /* points to packet payload, which starts with an Ethernet header */ + ethhdr = p->payload; + + switch (htons(ethhdr->type)) { + /* IP or ARP packet? */ + case ETHTYPE_IP: + case ETHTYPE_ARP: +#if PPPOE_SUPPORT + /* PPPoE packet? */ + case ETHTYPE_PPPOEDISC: + case ETHTYPE_PPPOE: +#endif /* PPPOE_SUPPORT */ + /* full packet send to tcpip_thread to process */ + if (netif->input(p, netif)!=ERR_OK) + { LWIP_DEBUGF(NETIF_DEBUG, ("ethernetif_input: IP input error\n")); + pbuf_free(p); + p = NULL; + } + break; + + default: + pbuf_free(p); + p = NULL; + break; + } +} + +/** + * Should be called at the beginning of the program to set up the + * network interface. It calls the function low_level_init() to do the + * actual setup of the hardware. + * + * This function should be passed as a parameter to netif_add(). + * + * @param netif the lwip network interface structure for this ethernetif + * @return ERR_OK if the loopif is initialized + * ERR_MEM if private data couldn't be allocated + * any other err_t on error + */ +err_t +ethernetif_init(struct netif *netif) +{ + struct ethernetif *ethernetif; + + LWIP_ASSERT("netif != NULL", (netif != NULL)); + + ethernetif = mem_malloc(sizeof(struct ethernetif)); + if (ethernetif == NULL) { + LWIP_DEBUGF(NETIF_DEBUG, ("ethernetif_init: out of memory\n")); + return ERR_MEM; + } + +#if LWIP_NETIF_HOSTNAME + /* Initialize interface hostname */ + netif->hostname = "lwip"; +#endif /* LWIP_NETIF_HOSTNAME */ + + /* + * Initialize the snmp variables and counters inside the struct netif. + * The last argument should be replaced with your link speed, in units + * of bits per second. + */ + NETIF_INIT_SNMP(netif, snmp_ifType_ethernet_csmacd, LINK_SPEED_OF_YOUR_NETIF_IN_BPS); + + netif->state = ethernetif; + netif->name[0] = IFNAME0; + netif->name[1] = IFNAME1; + /* We directly use etharp_output() here to save a function call. + * You can instead declare your own function an call etharp_output() + * from it if you have to do some checks before sending (e.g. if link + * is available...) */ + netif->output = etharp_output; + netif->linkoutput = low_level_output; + + ethernetif->ethaddr = (struct eth_addr *)&(netif->hwaddr[0]); + + /* initialize the hardware */ + low_level_init(netif); + + return ERR_OK; +} + +#endif /* 0 */ diff --git a/features/unsupported/net/lwip/lwip/netif/ppp/auth.c b/features/unsupported/net/lwip/lwip/netif/ppp/auth.c new file mode 100644 index 00000000000..c3c49d22a25 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/netif/ppp/auth.c @@ -0,0 +1,1334 @@ +/***************************************************************************** +* auth.c - Network Authentication and Phase Control program file. +* +* Copyright (c) 2003 by Marc Boucher, Services Informatiques (MBSI) inc. +* Copyright (c) 1997 by Global Election Systems Inc. All rights reserved. +* +* The authors hereby grant permission to use, copy, modify, distribute, +* and license this software and its documentation for any purpose, provided +* that existing copyright notices are retained in all copies and that this +* notice and the following disclaimer are included verbatim in any +* distributions. No written agreement, license, or royalty fee is required +* for any of the authorized uses. +* +* THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS *AS IS* AND ANY EXPRESS OR +* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +* IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT +* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +****************************************************************************** +* REVISION HISTORY +* +* 03-01-01 Marc Boucher +* Ported to lwIP. +* 97-12-08 Guy Lancaster , Global Election Systems Inc. +* Ported from public pppd code. +*****************************************************************************/ +/* + * auth.c - PPP authentication and phase control. + * + * Copyright (c) 1993 The Australian National University. + * All rights reserved. + * + * Redistribution and use in source and binary forms are permitted + * provided that the above copyright notice and this paragraph are + * duplicated in all such forms and that any documentation, + * advertising materials, and other materials related to such + * distribution and use acknowledge that the software was developed + * by the Australian National University. The name of the University + * may not be used to endorse or promote products derived from this + * software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED + * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. + * + * Copyright (c) 1989 Carnegie Mellon University. + * All rights reserved. + * + * Redistribution and use in source and binary forms are permitted + * provided that the above copyright notice and this paragraph are + * duplicated in all such forms and that any documentation, + * advertising materials, and other materials related to such + * distribution and use acknowledge that the software was developed + * by Carnegie Mellon University. The name of the + * University may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED + * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. + */ + +#include "lwip/opt.h" + +#if PPP_SUPPORT /* don't build if not configured for use in lwipopts.h */ + +#include "ppp.h" +#include "pppdebug.h" + +#include "fsm.h" +#include "lcp.h" +#include "pap.h" +#include "chap.h" +#include "auth.h" +#include "ipcp.h" + +#if CBCP_SUPPORT +#include "cbcp.h" +#endif /* CBCP_SUPPORT */ + +#include "lwip/inet.h" + +#include + +#if 0 /* UNUSED */ +/* Bits in scan_authfile return value */ +#define NONWILD_SERVER 1 +#define NONWILD_CLIENT 2 + +#define ISWILD(word) (word[0] == '*' && word[1] == 0) +#endif /* UNUSED */ + +#if PAP_SUPPORT || CHAP_SUPPORT +/* The name by which the peer authenticated itself to us. */ +static char peer_authname[MAXNAMELEN]; +#endif /* PAP_SUPPORT || CHAP_SUPPORT */ + +/* Records which authentication operations haven't completed yet. */ +static int auth_pending[NUM_PPP]; + +/* Set if we have successfully called plogin() */ +static int logged_in; + +/* Set if we have run the /etc/ppp/auth-up script. */ +static int did_authup; /* @todo, we don't need this in lwip*/ + +/* List of addresses which the peer may use. */ +static struct wordlist *addresses[NUM_PPP]; + +#if 0 /* UNUSED */ +/* Wordlist giving addresses which the peer may use + without authenticating itself. */ +static struct wordlist *noauth_addrs; + +/* Extra options to apply, from the secrets file entry for the peer. */ +static struct wordlist *extra_options; +#endif /* UNUSED */ + +/* Number of network protocols which we have opened. */ +static int num_np_open; + +/* Number of network protocols which have come up. */ +static int num_np_up; + +#if PAP_SUPPORT || CHAP_SUPPORT +/* Set if we got the contents of passwd[] from the pap-secrets file. */ +static int passwd_from_file; +#endif /* PAP_SUPPORT || CHAP_SUPPORT */ + +#if 0 /* UNUSED */ +/* Set if we require authentication only because we have a default route. */ +static bool default_auth; + +/* Hook to enable a plugin to control the idle time limit */ +int (*idle_time_hook) __P((struct ppp_idle *)) = NULL; + +/* Hook for a plugin to say whether we can possibly authenticate any peer */ +int (*pap_check_hook) __P((void)) = NULL; + +/* Hook for a plugin to check the PAP user and password */ +int (*pap_auth_hook) __P((char *user, char *passwd, char **msgp, + struct wordlist **paddrs, + struct wordlist **popts)) = NULL; + +/* Hook for a plugin to know about the PAP user logout */ +void (*pap_logout_hook) __P((void)) = NULL; + +/* Hook for a plugin to get the PAP password for authenticating us */ +int (*pap_passwd_hook) __P((char *user, char *passwd)) = NULL; + +/* + * This is used to ensure that we don't start an auth-up/down + * script while one is already running. + */ +enum script_state { + s_down, + s_up +}; + +static enum script_state auth_state = s_down; +static enum script_state auth_script_state = s_down; +static pid_t auth_script_pid = 0; + +/* + * Option variables. + * lwip: some of these are present in the ppp_settings structure + */ +bool uselogin = 0; /* Use /etc/passwd for checking PAP */ +bool cryptpap = 0; /* Passwords in pap-secrets are encrypted */ +bool refuse_pap = 0; /* Don't wanna auth. ourselves with PAP */ +bool refuse_chap = 0; /* Don't wanna auth. ourselves with CHAP */ +bool usehostname = 0; /* Use hostname for our_name */ +bool auth_required = 0; /* Always require authentication from peer */ +bool allow_any_ip = 0; /* Allow peer to use any IP address */ +bool explicit_remote = 0; /* User specified explicit remote name */ +char remote_name[MAXNAMELEN]; /* Peer's name for authentication */ + +#endif /* UNUSED */ + +/* Bits in auth_pending[] */ +#define PAP_WITHPEER 1 +#define PAP_PEER 2 +#define CHAP_WITHPEER 4 +#define CHAP_PEER 8 + +/* @todo, move this somewhere */ +/* Used for storing a sequence of words. Usually malloced. */ +struct wordlist { + struct wordlist *next; + char word[1]; +}; + + +extern char *crypt (const char *, const char *); + +/* Prototypes for procedures local to this file. */ + +static void network_phase (int); +static void check_idle (void *); +static void connect_time_expired (void *); +#if 0 +static int plogin (char *, char *, char **, int *); +#endif +static void plogout (void); +static int null_login (int); +static int get_pap_passwd (int, char *, char *); +static int have_pap_secret (void); +static int have_chap_secret (char *, char *, u32_t); +static int ip_addr_check (u32_t, struct wordlist *); + +#if 0 /* PAP_SUPPORT || CHAP_SUPPORT */ +static int scan_authfile (FILE *, char *, char *, char *, + struct wordlist **, struct wordlist **, + char *); +static void free_wordlist (struct wordlist *); +static void auth_script (char *); +static void auth_script_done (void *); +static void set_allowed_addrs (int unit, struct wordlist *addrs); +static int some_ip_ok (struct wordlist *); +static int setupapfile (char **); +static int privgroup (char **); +static int set_noauth_addr (char **); +static void check_access (FILE *, char *); +#endif /* 0 */ /* PAP_SUPPORT || CHAP_SUPPORT */ + +#if 0 /* UNUSED */ +/* + * Authentication-related options. + */ +option_t auth_options[] = { + { "require-pap", o_bool, &lcp_wantoptions[0].neg_upap, + "Require PAP authentication from peer", 1, &auth_required }, + { "+pap", o_bool, &lcp_wantoptions[0].neg_upap, + "Require PAP authentication from peer", 1, &auth_required }, + { "refuse-pap", o_bool, &refuse_pap, + "Don't agree to auth to peer with PAP", 1 }, + { "-pap", o_bool, &refuse_pap, + "Don't allow PAP authentication with peer", 1 }, + { "require-chap", o_bool, &lcp_wantoptions[0].neg_chap, + "Require CHAP authentication from peer", 1, &auth_required }, + { "+chap", o_bool, &lcp_wantoptions[0].neg_chap, + "Require CHAP authentication from peer", 1, &auth_required }, + { "refuse-chap", o_bool, &refuse_chap, + "Don't agree to auth to peer with CHAP", 1 }, + { "-chap", o_bool, &refuse_chap, + "Don't allow CHAP authentication with peer", 1 }, + { "name", o_string, our_name, + "Set local name for authentication", + OPT_PRIV|OPT_STATIC, NULL, MAXNAMELEN }, + { "user", o_string, user, + "Set name for auth with peer", OPT_STATIC, NULL, MAXNAMELEN }, + { "usehostname", o_bool, &usehostname, + "Must use hostname for authentication", 1 }, + { "remotename", o_string, remote_name, + "Set remote name for authentication", OPT_STATIC, + &explicit_remote, MAXNAMELEN }, + { "auth", o_bool, &auth_required, + "Require authentication from peer", 1 }, + { "noauth", o_bool, &auth_required, + "Don't require peer to authenticate", OPT_PRIV, &allow_any_ip }, + { "login", o_bool, &uselogin, + "Use system password database for PAP", 1 }, + { "papcrypt", o_bool, &cryptpap, + "PAP passwords are encrypted", 1 }, + { "+ua", o_special, (void *)setupapfile, + "Get PAP user and password from file" }, + { "password", o_string, passwd, + "Password for authenticating us to the peer", OPT_STATIC, + NULL, MAXSECRETLEN }, + { "privgroup", o_special, (void *)privgroup, + "Allow group members to use privileged options", OPT_PRIV }, + { "allow-ip", o_special, (void *)set_noauth_addr, + "Set IP address(es) which can be used without authentication", + OPT_PRIV }, + { NULL } +}; +#endif /* UNUSED */ +#if 0 /* UNUSED */ +/* + * setupapfile - specifies UPAP info for authenticating with peer. + */ +static int +setupapfile(char **argv) +{ + FILE * ufile; + int l; + + lcp_allowoptions[0].neg_upap = 1; + + /* open user info file */ + seteuid(getuid()); + ufile = fopen(*argv, "r"); + seteuid(0); + if (ufile == NULL) { + option_error("unable to open user login data file %s", *argv); + return 0; + } + check_access(ufile, *argv); + + /* get username */ + if (fgets(user, MAXNAMELEN - 1, ufile) == NULL + || fgets(passwd, MAXSECRETLEN - 1, ufile) == NULL){ + option_error("unable to read user login data file %s", *argv); + return 0; + } + fclose(ufile); + + /* get rid of newlines */ + l = strlen(user); + if (l > 0 && user[l-1] == '\n') + user[l-1] = 0; + l = strlen(passwd); + if (l > 0 && passwd[l-1] == '\n') + passwd[l-1] = 0; + + return (1); +} +#endif /* UNUSED */ + +#if 0 /* UNUSED */ +/* + * privgroup - allow members of the group to have privileged access. + */ +static int +privgroup(char **argv) +{ + struct group *g; + int i; + + g = getgrnam(*argv); + if (g == 0) { + option_error("group %s is unknown", *argv); + return 0; + } + for (i = 0; i < ngroups; ++i) { + if (groups[i] == g->gr_gid) { + privileged = 1; + break; + } + } + return 1; +} +#endif + +#if 0 /* UNUSED */ +/* + * set_noauth_addr - set address(es) that can be used without authentication. + * Equivalent to specifying an entry like `"" * "" addr' in pap-secrets. + */ +static int +set_noauth_addr(char **argv) +{ + char *addr = *argv; + int l = strlen(addr); + struct wordlist *wp; + + wp = (struct wordlist *) malloc(sizeof(struct wordlist) + l + 1); + if (wp == NULL) + novm("allow-ip argument"); + wp->word = (char *) (wp + 1); + wp->next = noauth_addrs; + BCOPY(addr, wp->word, l); + noauth_addrs = wp; + return 1; +} +#endif /* UNUSED */ + +/* + * An Open on LCP has requested a change from Dead to Establish phase. + * Do what's necessary to bring the physical layer up. + */ +void +link_required(int unit) +{ + LWIP_UNUSED_ARG(unit); + + AUTHDEBUG(LOG_INFO, ("link_required: %d\n", unit)); +} + +/* + * LCP has terminated the link; go to the Dead phase and take the + * physical layer down. + */ +void +link_terminated(int unit) +{ + AUTHDEBUG(LOG_INFO, ("link_terminated: %d\n", unit)); + if (lcp_phase[unit] == PHASE_DEAD) { + return; + } + if (logged_in) { + plogout(); + } + lcp_phase[unit] = PHASE_DEAD; + AUTHDEBUG(LOG_NOTICE, ("Connection terminated.\n")); + pppLinkTerminated(unit); +} + +/* + * LCP has gone down; it will either die or try to re-establish. + */ +void +link_down(int unit) +{ + int i; + struct protent *protp; + + AUTHDEBUG(LOG_INFO, ("link_down: %d\n", unit)); + + if (did_authup) { + /* XXX Do link down processing. */ + did_authup = 0; + } + for (i = 0; (protp = ppp_protocols[i]) != NULL; ++i) { + if (!protp->enabled_flag) { + continue; + } + if (protp->protocol != PPP_LCP && protp->lowerdown != NULL) { + (*protp->lowerdown)(unit); + } + if (protp->protocol < 0xC000 && protp->close != NULL) { + (*protp->close)(unit, "LCP down"); + } + } + num_np_open = 0; /* number of network protocols we have opened */ + num_np_up = 0; /* Number of network protocols which have come up */ + + if (lcp_phase[unit] != PHASE_DEAD) { + lcp_phase[unit] = PHASE_TERMINATE; + } + pppLinkDown(unit); +} + +/* + * The link is established. + * Proceed to the Dead, Authenticate or Network phase as appropriate. + */ +void +link_established(int unit) +{ + int auth; + int i; + struct protent *protp; + lcp_options *wo = &lcp_wantoptions[unit]; + lcp_options *go = &lcp_gotoptions[unit]; +#if PAP_SUPPORT || CHAP_SUPPORT + lcp_options *ho = &lcp_hisoptions[unit]; +#endif /* PAP_SUPPORT || CHAP_SUPPORT */ + + AUTHDEBUG(LOG_INFO, ("link_established: unit %d; Lowering up all protocols...\n", unit)); + /* + * Tell higher-level protocols that LCP is up. + */ + for (i = 0; (protp = ppp_protocols[i]) != NULL; ++i) { + if (protp->protocol != PPP_LCP && protp->enabled_flag && protp->lowerup != NULL) { + (*protp->lowerup)(unit); + } + } + if (ppp_settings.auth_required && !(go->neg_chap || go->neg_upap)) { + /* + * We wanted the peer to authenticate itself, and it refused: + * treat it as though it authenticated with PAP using a username + * of "" and a password of "". If that's not OK, boot it out. + */ + if (!wo->neg_upap || !null_login(unit)) { + AUTHDEBUG(LOG_WARNING, ("peer refused to authenticate\n")); + lcp_close(unit, "peer refused to authenticate"); + return; + } + } + + lcp_phase[unit] = PHASE_AUTHENTICATE; + auth = 0; +#if CHAP_SUPPORT + if (go->neg_chap) { + ChapAuthPeer(unit, ppp_settings.our_name, go->chap_mdtype); + auth |= CHAP_PEER; + } +#endif /* CHAP_SUPPORT */ +#if PAP_SUPPORT && CHAP_SUPPORT + else +#endif /* PAP_SUPPORT && CHAP_SUPPORT */ +#if PAP_SUPPORT + if (go->neg_upap) { + upap_authpeer(unit); + auth |= PAP_PEER; + } +#endif /* PAP_SUPPORT */ +#if CHAP_SUPPORT + if (ho->neg_chap) { + ChapAuthWithPeer(unit, ppp_settings.user, ho->chap_mdtype); + auth |= CHAP_WITHPEER; + } +#endif /* CHAP_SUPPORT */ +#if PAP_SUPPORT && CHAP_SUPPORT + else +#endif /* PAP_SUPPORT && CHAP_SUPPORT */ +#if PAP_SUPPORT + if (ho->neg_upap) { + if (ppp_settings.passwd[0] == 0) { + passwd_from_file = 1; + if (!get_pap_passwd(unit, ppp_settings.user, ppp_settings.passwd)) { + AUTHDEBUG(LOG_ERR, ("No secret found for PAP login\n")); + } + } + upap_authwithpeer(unit, ppp_settings.user, ppp_settings.passwd); + auth |= PAP_WITHPEER; + } +#endif /* PAP_SUPPORT */ + auth_pending[unit] = auth; + + if (!auth) { + network_phase(unit); + } +} + +/* + * Proceed to the network phase. + */ +static void +network_phase(int unit) +{ + int i; + struct protent *protp; + lcp_options *go = &lcp_gotoptions[unit]; + + /* + * If the peer had to authenticate, run the auth-up script now. + */ + if ((go->neg_chap || go->neg_upap) && !did_authup) { + /* XXX Do setup for peer authentication. */ + did_authup = 1; + } + +#if CBCP_SUPPORT + /* + * If we negotiated callback, do it now. + */ + if (go->neg_cbcp) { + lcp_phase[unit] = PHASE_CALLBACK; + (*cbcp_protent.open)(unit); + return; + } +#endif /* CBCP_SUPPORT */ + + lcp_phase[unit] = PHASE_NETWORK; + for (i = 0; (protp = ppp_protocols[i]) != NULL; ++i) { + if (protp->protocol < 0xC000 && protp->enabled_flag && protp->open != NULL) { + (*protp->open)(unit); + if (protp->protocol != PPP_CCP) { + ++num_np_open; + } + } + } + + if (num_np_open == 0) { + /* nothing to do */ + lcp_close(0, "No network protocols running"); + } +} +/* @todo: add void start_networks(void) here (pppd 2.3.11) */ + +/* + * The peer has failed to authenticate himself using `protocol'. + */ +void +auth_peer_fail(int unit, u16_t protocol) +{ + LWIP_UNUSED_ARG(protocol); + + AUTHDEBUG(LOG_INFO, ("auth_peer_fail: %d proto=%X\n", unit, protocol)); + /* + * Authentication failure: take the link down + */ + lcp_close(unit, "Authentication failed"); +} + + +#if PAP_SUPPORT || CHAP_SUPPORT +/* + * The peer has been successfully authenticated using `protocol'. + */ +void +auth_peer_success(int unit, u16_t protocol, char *name, int namelen) +{ + int pbit; + + AUTHDEBUG(LOG_INFO, ("auth_peer_success: %d proto=%X\n", unit, protocol)); + switch (protocol) { + case PPP_CHAP: + pbit = CHAP_PEER; + break; + case PPP_PAP: + pbit = PAP_PEER; + break; + default: + AUTHDEBUG(LOG_WARNING, ("auth_peer_success: unknown protocol %x\n", protocol)); + return; + } + + /* + * Save the authenticated name of the peer for later. + */ + if (namelen > (int)sizeof(peer_authname) - 1) { + namelen = sizeof(peer_authname) - 1; + } + BCOPY(name, peer_authname, namelen); + peer_authname[namelen] = 0; + + /* + * If there is no more authentication still to be done, + * proceed to the network (or callback) phase. + */ + if ((auth_pending[unit] &= ~pbit) == 0) { + network_phase(unit); + } +} + +/* + * We have failed to authenticate ourselves to the peer using `protocol'. + */ +void +auth_withpeer_fail(int unit, u16_t protocol) +{ + int errCode = PPPERR_AUTHFAIL; + + LWIP_UNUSED_ARG(protocol); + + AUTHDEBUG(LOG_INFO, ("auth_withpeer_fail: %d proto=%X\n", unit, protocol)); + if (passwd_from_file) { + BZERO(ppp_settings.passwd, MAXSECRETLEN); + } + + /* + * We've failed to authenticate ourselves to our peer. + * He'll probably take the link down, and there's not much + * we can do except wait for that. + */ + pppIOCtl(unit, PPPCTLS_ERRCODE, &errCode); + lcp_close(unit, "Failed to authenticate ourselves to peer"); +} + +/* + * We have successfully authenticated ourselves with the peer using `protocol'. + */ +void +auth_withpeer_success(int unit, u16_t protocol) +{ + int pbit; + + AUTHDEBUG(LOG_INFO, ("auth_withpeer_success: %d proto=%X\n", unit, protocol)); + switch (protocol) { + case PPP_CHAP: + pbit = CHAP_WITHPEER; + break; + case PPP_PAP: + if (passwd_from_file) { + BZERO(ppp_settings.passwd, MAXSECRETLEN); + } + pbit = PAP_WITHPEER; + break; + default: + AUTHDEBUG(LOG_WARNING, ("auth_peer_success: unknown protocol %x\n", protocol)); + pbit = 0; + } + + /* + * If there is no more authentication still being done, + * proceed to the network (or callback) phase. + */ + if ((auth_pending[unit] &= ~pbit) == 0) { + network_phase(unit); + } +} +#endif /* PAP_SUPPORT || CHAP_SUPPORT */ + + +/* + * np_up - a network protocol has come up. + */ +void +np_up(int unit, u16_t proto) +{ + LWIP_UNUSED_ARG(unit); + LWIP_UNUSED_ARG(proto); + + AUTHDEBUG(LOG_INFO, ("np_up: %d proto=%X\n", unit, proto)); + if (num_np_up == 0) { + AUTHDEBUG(LOG_INFO, ("np_up: maxconnect=%d idle_time_limit=%d\n",ppp_settings.maxconnect,ppp_settings.idle_time_limit)); + /* + * At this point we consider that the link has come up successfully. + */ + if (ppp_settings.idle_time_limit > 0) { + TIMEOUT(check_idle, NULL, ppp_settings.idle_time_limit); + } + + /* + * Set a timeout to close the connection once the maximum + * connect time has expired. + */ + if (ppp_settings.maxconnect > 0) { + TIMEOUT(connect_time_expired, 0, ppp_settings.maxconnect); + } + } + ++num_np_up; +} + +/* + * np_down - a network protocol has gone down. + */ +void +np_down(int unit, u16_t proto) +{ + LWIP_UNUSED_ARG(unit); + LWIP_UNUSED_ARG(proto); + + AUTHDEBUG(LOG_INFO, ("np_down: %d proto=%X\n", unit, proto)); + if (--num_np_up == 0 && ppp_settings.idle_time_limit > 0) { + UNTIMEOUT(check_idle, NULL); + } +} + +/* + * np_finished - a network protocol has finished using the link. + */ +void +np_finished(int unit, u16_t proto) +{ + LWIP_UNUSED_ARG(unit); + LWIP_UNUSED_ARG(proto); + + AUTHDEBUG(LOG_INFO, ("np_finished: %d proto=%X\n", unit, proto)); + if (--num_np_open <= 0) { + /* no further use for the link: shut up shop. */ + lcp_close(0, "No network protocols running"); + } +} + +/* + * check_idle - check whether the link has been idle for long + * enough that we can shut it down. + */ +static void +check_idle(void *arg) +{ + struct ppp_idle idle; + u_short itime; + + LWIP_UNUSED_ARG(arg); + if (!get_idle_time(0, &idle)) { + return; + } + itime = LWIP_MIN(idle.xmit_idle, idle.recv_idle); + if (itime >= ppp_settings.idle_time_limit) { + /* link is idle: shut it down. */ + AUTHDEBUG(LOG_INFO, ("Terminating connection due to lack of activity.\n")); + lcp_close(0, "Link inactive"); + } else { + TIMEOUT(check_idle, NULL, ppp_settings.idle_time_limit - itime); + } +} + +/* + * connect_time_expired - log a message and close the connection. + */ +static void +connect_time_expired(void *arg) +{ + LWIP_UNUSED_ARG(arg); + + AUTHDEBUG(LOG_INFO, ("Connect time expired\n")); + lcp_close(0, "Connect time expired"); /* Close connection */ +} + +#if 0 /* UNUSED */ +/* + * auth_check_options - called to check authentication options. + */ +void +auth_check_options(void) +{ + lcp_options *wo = &lcp_wantoptions[0]; + int can_auth; + ipcp_options *ipwo = &ipcp_wantoptions[0]; + u32_t remote; + + /* Default our_name to hostname, and user to our_name */ + if (ppp_settings.our_name[0] == 0 || ppp_settings.usehostname) { + strcpy(ppp_settings.our_name, ppp_settings.hostname); + } + + if (ppp_settings.user[0] == 0) { + strcpy(ppp_settings.user, ppp_settings.our_name); + } + + /* If authentication is required, ask peer for CHAP or PAP. */ + if (ppp_settings.auth_required && !wo->neg_chap && !wo->neg_upap) { + wo->neg_chap = 1; + wo->neg_upap = 1; + } + + /* + * Check whether we have appropriate secrets to use + * to authenticate the peer. + */ + can_auth = wo->neg_upap && have_pap_secret(); + if (!can_auth && wo->neg_chap) { + remote = ipwo->accept_remote? 0: ipwo->hisaddr; + can_auth = have_chap_secret(ppp_settings.remote_name, ppp_settings.our_name, remote); + } + + if (ppp_settings.auth_required && !can_auth) { + ppp_panic("No auth secret"); + } +} +#endif /* UNUSED */ + +/* + * auth_reset - called when LCP is starting negotiations to recheck + * authentication options, i.e. whether we have appropriate secrets + * to use for authenticating ourselves and/or the peer. + */ +void +auth_reset(int unit) +{ + lcp_options *go = &lcp_gotoptions[unit]; + lcp_options *ao = &lcp_allowoptions[0]; + ipcp_options *ipwo = &ipcp_wantoptions[0]; + u32_t remote; + + AUTHDEBUG(LOG_INFO, ("auth_reset: %d\n", unit)); + ao->neg_upap = !ppp_settings.refuse_pap && (ppp_settings.passwd[0] != 0 || get_pap_passwd(unit, NULL, NULL)); + ao->neg_chap = !ppp_settings.refuse_chap && ppp_settings.passwd[0] != 0 /*have_chap_secret(ppp_settings.user, ppp_settings.remote_name, (u32_t)0)*/; + + if (go->neg_upap && !have_pap_secret()) { + go->neg_upap = 0; + } + if (go->neg_chap) { + remote = ipwo->accept_remote? 0: ipwo->hisaddr; + if (!have_chap_secret(ppp_settings.remote_name, ppp_settings.our_name, remote)) { + go->neg_chap = 0; + } + } +} + +#if PAP_SUPPORT +/* + * check_passwd - Check the user name and passwd against the PAP secrets + * file. If requested, also check against the system password database, + * and login the user if OK. + * + * returns: + * UPAP_AUTHNAK: Authentication failed. + * UPAP_AUTHACK: Authentication succeeded. + * In either case, msg points to an appropriate message. + */ +u_char +check_passwd( int unit, char *auser, int userlen, char *apasswd, int passwdlen, char **msg, int *msglen) +{ +#if 1 /* XXX Assume all entries OK. */ + LWIP_UNUSED_ARG(unit); + LWIP_UNUSED_ARG(auser); + LWIP_UNUSED_ARG(userlen); + LWIP_UNUSED_ARG(apasswd); + LWIP_UNUSED_ARG(passwdlen); + LWIP_UNUSED_ARG(msglen); + *msg = (char *) 0; + return UPAP_AUTHACK; /* XXX Assume all entries OK. */ +#else + u_char ret = 0; + struct wordlist *addrs = NULL; + char passwd[256], user[256]; + char secret[MAXWORDLEN]; + static u_short attempts = 0; + + /* + * Make copies of apasswd and auser, then null-terminate them. + */ + BCOPY(apasswd, passwd, passwdlen); + passwd[passwdlen] = '\0'; + BCOPY(auser, user, userlen); + user[userlen] = '\0'; + *msg = (char *) 0; + + /* XXX Validate user name and password. */ + ret = UPAP_AUTHACK; /* XXX Assume all entries OK. */ + + if (ret == UPAP_AUTHNAK) { + if (*msg == (char *) 0) { + *msg = "Login incorrect"; + } + *msglen = strlen(*msg); + /* + * Frustrate passwd stealer programs. + * Allow 10 tries, but start backing off after 3 (stolen from login). + * On 10'th, drop the connection. + */ + if (attempts++ >= 10) { + AUTHDEBUG(LOG_WARNING, ("%d LOGIN FAILURES BY %s\n", attempts, user)); + /*ppp_panic("Excess Bad Logins");*/ + } + if (attempts > 3) { + /* @todo: this was sleep(), i.e. seconds, not milliseconds + * I don't think we really need this in lwIP - we would block tcpip_thread! + */ + /*sys_msleep((attempts - 3) * 5);*/ + } + if (addrs != NULL) { + free_wordlist(addrs); + } + } else { + attempts = 0; /* Reset count */ + if (*msg == (char *) 0) { + *msg = "Login ok"; + } + *msglen = strlen(*msg); + set_allowed_addrs(unit, addrs); + } + + BZERO(passwd, sizeof(passwd)); + BZERO(secret, sizeof(secret)); + + return ret; +#endif +} +#endif /* PAP_SUPPORT */ + +#if 0 /* UNUSED */ +/* + * This function is needed for PAM. + */ + +#ifdef USE_PAM + +/* lwip does not support PAM*/ + +#endif /* USE_PAM */ + +#endif /* UNUSED */ + + +#if 0 /* UNUSED */ +/* + * plogin - Check the user name and password against the system + * password database, and login the user if OK. + * + * returns: + * UPAP_AUTHNAK: Login failed. + * UPAP_AUTHACK: Login succeeded. + * In either case, msg points to an appropriate message. + */ +static int +plogin(char *user, char *passwd, char **msg, int *msglen) +{ + + LWIP_UNUSED_ARG(user); + LWIP_UNUSED_ARG(passwd); + LWIP_UNUSED_ARG(msg); + LWIP_UNUSED_ARG(msglen); + + + /* The new lines are here align the file when + * compared against the pppd 2.3.11 code */ + + + + + + + + + + + + + + + + + /* XXX Fail until we decide that we want to support logins. */ + return (UPAP_AUTHNAK); +} +#endif + + + +/* + * plogout - Logout the user. + */ +static void +plogout(void) +{ + logged_in = 0; +} + +/* + * null_login - Check if a username of "" and a password of "" are + * acceptable, and iff so, set the list of acceptable IP addresses + * and return 1. + */ +static int +null_login(int unit) +{ + LWIP_UNUSED_ARG(unit); + /* XXX Fail until we decide that we want to support logins. */ + return 0; +} + + +/* + * get_pap_passwd - get a password for authenticating ourselves with + * our peer using PAP. Returns 1 on success, 0 if no suitable password + * could be found. + */ +static int +get_pap_passwd(int unit, char *user, char *passwd) +{ + LWIP_UNUSED_ARG(unit); +/* normally we would reject PAP if no password is provided, + but this causes problems with some providers (like CHT in Taiwan) + who incorrectly request PAP and expect a bogus/empty password, so + always provide a default user/passwd of "none"/"none" + + @todo: This should be configured by the user, instead of being hardcoded here! +*/ + if(user) { + strcpy(user, "none"); + } + if(passwd) { + strcpy(passwd, "none"); + } + return 1; +} + +/* + * have_pap_secret - check whether we have a PAP file with any + * secrets that we could possibly use for authenticating the peer. + */ +static int +have_pap_secret(void) +{ + /* XXX Fail until we set up our passwords. */ + return 0; +} + +/* + * have_chap_secret - check whether we have a CHAP file with a + * secret that we could possibly use for authenticating `client' + * on `server'. Either can be the null string, meaning we don't + * know the identity yet. + */ +static int +have_chap_secret(char *client, char *server, u32_t remote) +{ + LWIP_UNUSED_ARG(client); + LWIP_UNUSED_ARG(server); + LWIP_UNUSED_ARG(remote); + + /* XXX Fail until we set up our passwords. */ + return 0; +} +#if CHAP_SUPPORT + +/* + * get_secret - open the CHAP secret file and return the secret + * for authenticating the given client on the given server. + * (We could be either client or server). + */ +int +get_secret(int unit, char *client, char *server, char *secret, int *secret_len, int save_addrs) +{ +#if 1 + int len; + struct wordlist *addrs; + + LWIP_UNUSED_ARG(unit); + LWIP_UNUSED_ARG(server); + LWIP_UNUSED_ARG(save_addrs); + + addrs = NULL; + + if(!client || !client[0] || strcmp(client, ppp_settings.user)) { + return 0; + } + + len = (int)strlen(ppp_settings.passwd); + if (len > MAXSECRETLEN) { + AUTHDEBUG(LOG_ERR, ("Secret for %s on %s is too long\n", client, server)); + len = MAXSECRETLEN; + } + + BCOPY(ppp_settings.passwd, secret, len); + *secret_len = len; + + return 1; +#else + int ret = 0, len; + struct wordlist *addrs; + char secbuf[MAXWORDLEN]; + + addrs = NULL; + secbuf[0] = 0; + + /* XXX Find secret. */ + if (ret < 0) { + return 0; + } + + if (save_addrs) { + set_allowed_addrs(unit, addrs); + } + + len = strlen(secbuf); + if (len > MAXSECRETLEN) { + AUTHDEBUG(LOG_ERR, ("Secret for %s on %s is too long\n", client, server)); + len = MAXSECRETLEN; + } + + BCOPY(secbuf, secret, len); + BZERO(secbuf, sizeof(secbuf)); + *secret_len = len; + + return 1; +#endif +} +#endif /* CHAP_SUPPORT */ + + +#if 0 /* PAP_SUPPORT || CHAP_SUPPORT */ +/* + * set_allowed_addrs() - set the list of allowed addresses. + */ +static void +set_allowed_addrs(int unit, struct wordlist *addrs) +{ + if (addresses[unit] != NULL) { + free_wordlist(addresses[unit]); + } + addresses[unit] = addrs; + +#if 0 + /* + * If there's only one authorized address we might as well + * ask our peer for that one right away + */ + if (addrs != NULL && addrs->next == NULL) { + char *p = addrs->word; + struct ipcp_options *wo = &ipcp_wantoptions[unit]; + u32_t a; + struct hostent *hp; + + if (wo->hisaddr == 0 && *p != '!' && *p != '-' && strchr(p, '/') == NULL) { + hp = gethostbyname(p); + if (hp != NULL && hp->h_addrtype == AF_INET) { + a = *(u32_t *)hp->h_addr; + } else { + a = inet_addr(p); + } + if (a != (u32_t) -1) { + wo->hisaddr = a; + } + } + } +#endif +} +#endif /* 0 */ /* PAP_SUPPORT || CHAP_SUPPORT */ + +/* + * auth_ip_addr - check whether the peer is authorized to use + * a given IP address. Returns 1 if authorized, 0 otherwise. + */ +int +auth_ip_addr(int unit, u32_t addr) +{ + return ip_addr_check(addr, addresses[unit]); +} + +static int /* @todo: integrate this funtion into auth_ip_addr()*/ +ip_addr_check(u32_t addr, struct wordlist *addrs) +{ + /* don't allow loopback or multicast address */ + if (bad_ip_adrs(addr)) { + return 0; + } + + if (addrs == NULL) { + return !ppp_settings.auth_required; /* no addresses authorized */ + } + + /* XXX All other addresses allowed. */ + return 1; +} + +/* + * bad_ip_adrs - return 1 if the IP address is one we don't want + * to use, such as an address in the loopback net or a multicast address. + * addr is in network byte order. + */ +int +bad_ip_adrs(u32_t addr) +{ + addr = ntohl(addr); + return (addr >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET + || IN_MULTICAST(addr) || IN_BADCLASS(addr); +} + +#if 0 /* UNUSED */ /* PAP_SUPPORT || CHAP_SUPPORT */ +/* + * some_ip_ok - check a wordlist to see if it authorizes any + * IP address(es). + */ +static int +some_ip_ok(struct wordlist *addrs) +{ + for (; addrs != 0; addrs = addrs->next) { + if (addrs->word[0] == '-') + break; + if (addrs->word[0] != '!') + return 1; /* some IP address is allowed */ + } + return 0; +} + +/* + * check_access - complain if a secret file has too-liberal permissions. + */ +static void +check_access(FILE *f, char *filename) +{ + struct stat sbuf; + + if (fstat(fileno(f), &sbuf) < 0) { + warn("cannot stat secret file %s: %m", filename); + } else if ((sbuf.st_mode & (S_IRWXG | S_IRWXO)) != 0) { + warn("Warning - secret file %s has world and/or group access", + filename); + } +} + + +/* + * scan_authfile - Scan an authorization file for a secret suitable + * for authenticating `client' on `server'. The return value is -1 + * if no secret is found, otherwise >= 0. The return value has + * NONWILD_CLIENT set if the secret didn't have "*" for the client, and + * NONWILD_SERVER set if the secret didn't have "*" for the server. + * Any following words on the line up to a "--" (i.e. address authorization + * info) are placed in a wordlist and returned in *addrs. Any + * following words (extra options) are placed in a wordlist and + * returned in *opts. + * We assume secret is NULL or points to MAXWORDLEN bytes of space. + */ +static int +scan_authfile(FILE *f, char *client, char *server, char *secret, struct wordlist **addrs, struct wordlist **opts, char *filename) +{ + /* We do not (currently) need this in lwip */ + return 0; /* dummy */ +} +/* + * free_wordlist - release memory allocated for a wordlist. + */ +static void +free_wordlist(struct wordlist *wp) +{ + struct wordlist *next; + + while (wp != NULL) { + next = wp->next; + free(wp); + wp = next; + } +} + +/* + * auth_script_done - called when the auth-up or auth-down script + * has finished. + */ +static void +auth_script_done(void *arg) +{ + auth_script_pid = 0; + switch (auth_script_state) { + case s_up: + if (auth_state == s_down) { + auth_script_state = s_down; + auth_script(_PATH_AUTHDOWN); + } + break; + case s_down: + if (auth_state == s_up) { + auth_script_state = s_up; + auth_script(_PATH_AUTHUP); + } + break; + } +} + +/* + * auth_script - execute a script with arguments + * interface-name peer-name real-user tty speed + */ +static void +auth_script(char *script) +{ + char strspeed[32]; + struct passwd *pw; + char struid[32]; + char *user_name; + char *argv[8]; + + if ((pw = getpwuid(getuid())) != NULL && pw->pw_name != NULL) + user_name = pw->pw_name; + else { + slprintf(struid, sizeof(struid), "%d", getuid()); + user_name = struid; + } + slprintf(strspeed, sizeof(strspeed), "%d", baud_rate); + + argv[0] = script; + argv[1] = ifname; + argv[2] = peer_authname; + argv[3] = user_name; + argv[4] = devnam; + argv[5] = strspeed; + argv[6] = NULL; + + auth_script_pid = run_program(script, argv, 0, auth_script_done, NULL); +} +#endif /* 0 */ /* PAP_SUPPORT || CHAP_SUPPORT */ +#endif /* PPP_SUPPORT */ diff --git a/features/unsupported/net/lwip/lwip/netif/ppp/auth.h b/features/unsupported/net/lwip/lwip/netif/ppp/auth.h new file mode 100644 index 00000000000..a8069ec4640 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/netif/ppp/auth.h @@ -0,0 +1,111 @@ +/***************************************************************************** +* auth.h - PPP Authentication and phase control header file. +* +* Copyright (c) 2003 by Marc Boucher, Services Informatiques (MBSI) inc. +* portions Copyright (c) 1998 Global Election Systems Inc. +* +* The authors hereby grant permission to use, copy, modify, distribute, +* and license this software and its documentation for any purpose, provided +* that existing copyright notices are retained in all copies and that this +* notice and the following disclaimer are included verbatim in any +* distributions. No written agreement, license, or royalty fee is required +* for any of the authorized uses. +* +* THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS *AS IS* AND ANY EXPRESS OR +* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +* IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT +* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +****************************************************************************** +* REVISION HISTORY +* +* 03-01-01 Marc Boucher +* Ported to lwIP. +* 97-12-04 Guy Lancaster , Global Election Systems Inc. +* Original derived from BSD pppd.h. +*****************************************************************************/ +/* + * pppd.h - PPP daemon global declarations. + * + * Copyright (c) 1989 Carnegie Mellon University. + * All rights reserved. + * + * Redistribution and use in source and binary forms are permitted + * provided that the above copyright notice and this paragraph are + * duplicated in all such forms and that any documentation, + * advertising materials, and other materials related to such + * distribution and use acknowledge that the software was developed + * by Carnegie Mellon University. The name of the + * University may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED + * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. + * + */ + +#ifndef AUTH_H +#define AUTH_H + +/*********************** +*** PUBLIC FUNCTIONS *** +***********************/ + +/* we are starting to use the link */ +void link_required (int); + +/* we are finished with the link */ +void link_terminated (int); + +/* the LCP layer has left the Opened state */ +void link_down (int); + +/* the link is up; authenticate now */ +void link_established (int); + +/* a network protocol has come up */ +void np_up (int, u16_t); + +/* a network protocol has gone down */ +void np_down (int, u16_t); + +/* a network protocol no longer needs link */ +void np_finished (int, u16_t); + +/* peer failed to authenticate itself */ +void auth_peer_fail (int, u16_t); + +/* peer successfully authenticated itself */ +void auth_peer_success (int, u16_t, char *, int); + +/* we failed to authenticate ourselves */ +void auth_withpeer_fail (int, u16_t); + +/* we successfully authenticated ourselves */ +void auth_withpeer_success (int, u16_t); + +/* check authentication options supplied */ +void auth_check_options (void); + +/* check what secrets we have */ +void auth_reset (int); + +/* Check peer-supplied username/password */ +u_char check_passwd (int, char *, int, char *, int, char **, int *); + +/* get "secret" for chap */ +int get_secret (int, char *, char *, char *, int *, int); + +/* check if IP address is authorized */ +int auth_ip_addr (int, u32_t); + +/* check if IP address is unreasonable */ +int bad_ip_adrs (u32_t); + +#endif /* AUTH_H */ diff --git a/features/unsupported/net/lwip/lwip/netif/ppp/chap.c b/features/unsupported/net/lwip/lwip/netif/ppp/chap.c new file mode 100644 index 00000000000..3a49ff8a5e4 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/netif/ppp/chap.c @@ -0,0 +1,908 @@ +/*** WARNING - THIS HAS NEVER BEEN FINISHED ***/ +/***************************************************************************** +* chap.c - Network Challenge Handshake Authentication Protocol program file. +* +* Copyright (c) 2003 by Marc Boucher, Services Informatiques (MBSI) inc. +* portions Copyright (c) 1997 by Global Election Systems Inc. +* +* The authors hereby grant permission to use, copy, modify, distribute, +* and license this software and its documentation for any purpose, provided +* that existing copyright notices are retained in all copies and that this +* notice and the following disclaimer are included verbatim in any +* distributions. No written agreement, license, or royalty fee is required +* for any of the authorized uses. +* +* THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS *AS IS* AND ANY EXPRESS OR +* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +* IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT +* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +****************************************************************************** +* REVISION HISTORY +* +* 03-01-01 Marc Boucher +* Ported to lwIP. +* 97-12-04 Guy Lancaster , Global Election Systems Inc. +* Original based on BSD chap.c. +*****************************************************************************/ +/* + * chap.c - Challenge Handshake Authentication Protocol. + * + * Copyright (c) 1993 The Australian National University. + * All rights reserved. + * + * Redistribution and use in source and binary forms are permitted + * provided that the above copyright notice and this paragraph are + * duplicated in all such forms and that any documentation, + * advertising materials, and other materials related to such + * distribution and use acknowledge that the software was developed + * by the Australian National University. The name of the University + * may not be used to endorse or promote products derived from this + * software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED + * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. + * + * Copyright (c) 1991 Gregory M. Christy. + * All rights reserved. + * + * Redistribution and use in source and binary forms are permitted + * provided that the above copyright notice and this paragraph are + * duplicated in all such forms and that any documentation, + * advertising materials, and other materials related to such + * distribution and use acknowledge that the software was developed + * by Gregory M. Christy. The name of the author may not be used to + * endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED + * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. + */ + +#include "lwip/opt.h" + +#if PPP_SUPPORT /* don't build if not configured for use in lwipopts.h */ + +#if CHAP_SUPPORT /* don't build if not configured for use in lwipopts.h */ + +#include "ppp.h" +#include "pppdebug.h" + +#include "magic.h" +#include "randm.h" +#include "auth.h" +#include "md5.h" +#include "chap.h" +#include "chpms.h" + +#include + +#if 0 /* UNUSED */ +/* + * Command-line options. + */ +static option_t chap_option_list[] = { + { "chap-restart", o_int, &chap[0].timeouttime, + "Set timeout for CHAP" }, + { "chap-max-challenge", o_int, &chap[0].max_transmits, + "Set max #xmits for challenge" }, + { "chap-interval", o_int, &chap[0].chal_interval, + "Set interval for rechallenge" }, +#ifdef MSLANMAN + { "ms-lanman", o_bool, &ms_lanman, + "Use LanMan passwd when using MS-CHAP", 1 }, +#endif + { NULL } +}; +#endif /* UNUSED */ + +/* + * Protocol entry points. + */ +static void ChapInit (int); +static void ChapLowerUp (int); +static void ChapLowerDown (int); +static void ChapInput (int, u_char *, int); +static void ChapProtocolReject (int); +#if PPP_ADDITIONAL_CALLBACKS +static int ChapPrintPkt (u_char *, int, void (*) (void *, char *, ...), void *); +#endif + +struct protent chap_protent = { + PPP_CHAP, + ChapInit, + ChapInput, + ChapProtocolReject, + ChapLowerUp, + ChapLowerDown, + NULL, + NULL, +#if PPP_ADDITIONAL_CALLBACKS + ChapPrintPkt, + NULL, +#endif /* PPP_ADDITIONAL_CALLBACKS */ + 1, + "CHAP", +#if PPP_ADDITIONAL_CALLBACKS + NULL, + NULL, + NULL +#endif /* PPP_ADDITIONAL_CALLBACKS */ +}; + +chap_state chap[NUM_PPP]; /* CHAP state; one for each unit */ + +static void ChapChallengeTimeout (void *); +static void ChapResponseTimeout (void *); +static void ChapReceiveChallenge (chap_state *, u_char *, u_char, int); +static void ChapRechallenge (void *); +static void ChapReceiveResponse (chap_state *, u_char *, int, int); +static void ChapReceiveSuccess(chap_state *cstate, u_char *inp, u_char id, int len); +static void ChapReceiveFailure(chap_state *cstate, u_char *inp, u_char id, int len); +static void ChapSendStatus (chap_state *, int); +static void ChapSendChallenge (chap_state *); +static void ChapSendResponse (chap_state *); +static void ChapGenChallenge (chap_state *); + +/* + * ChapInit - Initialize a CHAP unit. + */ +static void +ChapInit(int unit) +{ + chap_state *cstate = &chap[unit]; + + BZERO(cstate, sizeof(*cstate)); + cstate->unit = unit; + cstate->clientstate = CHAPCS_INITIAL; + cstate->serverstate = CHAPSS_INITIAL; + cstate->timeouttime = CHAP_DEFTIMEOUT; + cstate->max_transmits = CHAP_DEFTRANSMITS; + /* random number generator is initialized in magic_init */ +} + + +/* + * ChapAuthWithPeer - Authenticate us with our peer (start client). + * + */ +void +ChapAuthWithPeer(int unit, char *our_name, u_char digest) +{ + chap_state *cstate = &chap[unit]; + + cstate->resp_name = our_name; + cstate->resp_type = digest; + + if (cstate->clientstate == CHAPCS_INITIAL || + cstate->clientstate == CHAPCS_PENDING) { + /* lower layer isn't up - wait until later */ + cstate->clientstate = CHAPCS_PENDING; + return; + } + + /* + * We get here as a result of LCP coming up. + * So even if CHAP was open before, we will + * have to re-authenticate ourselves. + */ + cstate->clientstate = CHAPCS_LISTEN; +} + + +/* + * ChapAuthPeer - Authenticate our peer (start server). + */ +void +ChapAuthPeer(int unit, char *our_name, u_char digest) +{ + chap_state *cstate = &chap[unit]; + + cstate->chal_name = our_name; + cstate->chal_type = digest; + + if (cstate->serverstate == CHAPSS_INITIAL || + cstate->serverstate == CHAPSS_PENDING) { + /* lower layer isn't up - wait until later */ + cstate->serverstate = CHAPSS_PENDING; + return; + } + + ChapGenChallenge(cstate); + ChapSendChallenge(cstate); /* crank it up dude! */ + cstate->serverstate = CHAPSS_INITIAL_CHAL; +} + + +/* + * ChapChallengeTimeout - Timeout expired on sending challenge. + */ +static void +ChapChallengeTimeout(void *arg) +{ + chap_state *cstate = (chap_state *) arg; + + /* if we aren't sending challenges, don't worry. then again we */ + /* probably shouldn't be here either */ + if (cstate->serverstate != CHAPSS_INITIAL_CHAL && + cstate->serverstate != CHAPSS_RECHALLENGE) { + return; + } + + if (cstate->chal_transmits >= cstate->max_transmits) { + /* give up on peer */ + CHAPDEBUG(LOG_ERR, ("Peer failed to respond to CHAP challenge\n")); + cstate->serverstate = CHAPSS_BADAUTH; + auth_peer_fail(cstate->unit, PPP_CHAP); + return; + } + + ChapSendChallenge(cstate); /* Re-send challenge */ +} + + +/* + * ChapResponseTimeout - Timeout expired on sending response. + */ +static void +ChapResponseTimeout(void *arg) +{ + chap_state *cstate = (chap_state *) arg; + + /* if we aren't sending a response, don't worry. */ + if (cstate->clientstate != CHAPCS_RESPONSE) { + return; + } + + ChapSendResponse(cstate); /* re-send response */ +} + + +/* + * ChapRechallenge - Time to challenge the peer again. + */ +static void +ChapRechallenge(void *arg) +{ + chap_state *cstate = (chap_state *) arg; + + /* if we aren't sending a response, don't worry. */ + if (cstate->serverstate != CHAPSS_OPEN) { + return; + } + + ChapGenChallenge(cstate); + ChapSendChallenge(cstate); + cstate->serverstate = CHAPSS_RECHALLENGE; +} + + +/* + * ChapLowerUp - The lower layer is up. + * + * Start up if we have pending requests. + */ +static void +ChapLowerUp(int unit) +{ + chap_state *cstate = &chap[unit]; + + if (cstate->clientstate == CHAPCS_INITIAL) { + cstate->clientstate = CHAPCS_CLOSED; + } else if (cstate->clientstate == CHAPCS_PENDING) { + cstate->clientstate = CHAPCS_LISTEN; + } + + if (cstate->serverstate == CHAPSS_INITIAL) { + cstate->serverstate = CHAPSS_CLOSED; + } else if (cstate->serverstate == CHAPSS_PENDING) { + ChapGenChallenge(cstate); + ChapSendChallenge(cstate); + cstate->serverstate = CHAPSS_INITIAL_CHAL; + } +} + + +/* + * ChapLowerDown - The lower layer is down. + * + * Cancel all timeouts. + */ +static void +ChapLowerDown(int unit) +{ + chap_state *cstate = &chap[unit]; + + /* Timeout(s) pending? Cancel if so. */ + if (cstate->serverstate == CHAPSS_INITIAL_CHAL || + cstate->serverstate == CHAPSS_RECHALLENGE) { + UNTIMEOUT(ChapChallengeTimeout, cstate); + } else if (cstate->serverstate == CHAPSS_OPEN + && cstate->chal_interval != 0) { + UNTIMEOUT(ChapRechallenge, cstate); + } + if (cstate->clientstate == CHAPCS_RESPONSE) { + UNTIMEOUT(ChapResponseTimeout, cstate); + } + cstate->clientstate = CHAPCS_INITIAL; + cstate->serverstate = CHAPSS_INITIAL; +} + + +/* + * ChapProtocolReject - Peer doesn't grok CHAP. + */ +static void +ChapProtocolReject(int unit) +{ + chap_state *cstate = &chap[unit]; + + if (cstate->serverstate != CHAPSS_INITIAL && + cstate->serverstate != CHAPSS_CLOSED) { + auth_peer_fail(unit, PPP_CHAP); + } + if (cstate->clientstate != CHAPCS_INITIAL && + cstate->clientstate != CHAPCS_CLOSED) { + auth_withpeer_fail(unit, PPP_CHAP); /* lwip: just sets the PPP error code on this unit to PPPERR_AUTHFAIL */ + } + ChapLowerDown(unit); /* shutdown chap */ +} + + +/* + * ChapInput - Input CHAP packet. + */ +static void +ChapInput(int unit, u_char *inpacket, int packet_len) +{ + chap_state *cstate = &chap[unit]; + u_char *inp; + u_char code, id; + int len; + + /* + * Parse header (code, id and length). + * If packet too short, drop it. + */ + inp = inpacket; + if (packet_len < CHAP_HEADERLEN) { + CHAPDEBUG(LOG_INFO, ("ChapInput: rcvd short header.\n")); + return; + } + GETCHAR(code, inp); + GETCHAR(id, inp); + GETSHORT(len, inp); + if (len < CHAP_HEADERLEN) { + CHAPDEBUG(LOG_INFO, ("ChapInput: rcvd illegal length.\n")); + return; + } + if (len > packet_len) { + CHAPDEBUG(LOG_INFO, ("ChapInput: rcvd short packet.\n")); + return; + } + len -= CHAP_HEADERLEN; + + /* + * Action depends on code (as in fact it usually does :-). + */ + switch (code) { + case CHAP_CHALLENGE: + ChapReceiveChallenge(cstate, inp, id, len); + break; + + case CHAP_RESPONSE: + ChapReceiveResponse(cstate, inp, id, len); + break; + + case CHAP_FAILURE: + ChapReceiveFailure(cstate, inp, id, len); + break; + + case CHAP_SUCCESS: + ChapReceiveSuccess(cstate, inp, id, len); + break; + + default: /* Need code reject? */ + CHAPDEBUG(LOG_WARNING, ("Unknown CHAP code (%d) received.\n", code)); + break; + } +} + + +/* + * ChapReceiveChallenge - Receive Challenge and send Response. + */ +static void +ChapReceiveChallenge(chap_state *cstate, u_char *inp, u_char id, int len) +{ + int rchallenge_len; + u_char *rchallenge; + int secret_len; + char secret[MAXSECRETLEN]; + char rhostname[256]; + MD5_CTX mdContext; + u_char hash[MD5_SIGNATURE_SIZE]; + + CHAPDEBUG(LOG_INFO, ("ChapReceiveChallenge: Rcvd id %d.\n", id)); + if (cstate->clientstate == CHAPCS_CLOSED || + cstate->clientstate == CHAPCS_PENDING) { + CHAPDEBUG(LOG_INFO, ("ChapReceiveChallenge: in state %d\n", + cstate->clientstate)); + return; + } + + if (len < 2) { + CHAPDEBUG(LOG_INFO, ("ChapReceiveChallenge: rcvd short packet.\n")); + return; + } + + GETCHAR(rchallenge_len, inp); + len -= sizeof (u_char) + rchallenge_len; /* now name field length */ + if (len < 0) { + CHAPDEBUG(LOG_INFO, ("ChapReceiveChallenge: rcvd short packet.\n")); + return; + } + rchallenge = inp; + INCPTR(rchallenge_len, inp); + + if (len >= (int)sizeof(rhostname)) { + len = sizeof(rhostname) - 1; + } + BCOPY(inp, rhostname, len); + rhostname[len] = '\000'; + + CHAPDEBUG(LOG_INFO, ("ChapReceiveChallenge: received name field '%s'\n", + rhostname)); + + /* Microsoft doesn't send their name back in the PPP packet */ + if (ppp_settings.remote_name[0] != 0 && (ppp_settings.explicit_remote || rhostname[0] == 0)) { + strncpy(rhostname, ppp_settings.remote_name, sizeof(rhostname)); + rhostname[sizeof(rhostname) - 1] = 0; + CHAPDEBUG(LOG_INFO, ("ChapReceiveChallenge: using '%s' as remote name\n", + rhostname)); + } + + /* get secret for authenticating ourselves with the specified host */ + if (!get_secret(cstate->unit, cstate->resp_name, rhostname, + secret, &secret_len, 0)) { + secret_len = 0; /* assume null secret if can't find one */ + CHAPDEBUG(LOG_WARNING, ("No CHAP secret found for authenticating us to %s\n", + rhostname)); + } + + /* cancel response send timeout if necessary */ + if (cstate->clientstate == CHAPCS_RESPONSE) { + UNTIMEOUT(ChapResponseTimeout, cstate); + } + + cstate->resp_id = id; + cstate->resp_transmits = 0; + + /* generate MD based on negotiated type */ + switch (cstate->resp_type) { + + case CHAP_DIGEST_MD5: + MD5Init(&mdContext); + MD5Update(&mdContext, &cstate->resp_id, 1); + MD5Update(&mdContext, (u_char*)secret, secret_len); + MD5Update(&mdContext, rchallenge, rchallenge_len); + MD5Final(hash, &mdContext); + BCOPY(hash, cstate->response, MD5_SIGNATURE_SIZE); + cstate->resp_length = MD5_SIGNATURE_SIZE; + break; + +#if MSCHAP_SUPPORT + case CHAP_MICROSOFT: + ChapMS(cstate, rchallenge, rchallenge_len, secret, secret_len); + break; +#endif + + default: + CHAPDEBUG(LOG_INFO, ("unknown digest type %d\n", cstate->resp_type)); + return; + } + + BZERO(secret, sizeof(secret)); + ChapSendResponse(cstate); +} + + +/* + * ChapReceiveResponse - Receive and process response. + */ +static void +ChapReceiveResponse(chap_state *cstate, u_char *inp, int id, int len) +{ + u_char *remmd, remmd_len; + int secret_len, old_state; + int code; + char rhostname[256]; + MD5_CTX mdContext; + char secret[MAXSECRETLEN]; + u_char hash[MD5_SIGNATURE_SIZE]; + + CHAPDEBUG(LOG_INFO, ("ChapReceiveResponse: Rcvd id %d.\n", id)); + + if (cstate->serverstate == CHAPSS_CLOSED || + cstate->serverstate == CHAPSS_PENDING) { + CHAPDEBUG(LOG_INFO, ("ChapReceiveResponse: in state %d\n", + cstate->serverstate)); + return; + } + + if (id != cstate->chal_id) { + return; /* doesn't match ID of last challenge */ + } + + /* + * If we have received a duplicate or bogus Response, + * we have to send the same answer (Success/Failure) + * as we did for the first Response we saw. + */ + if (cstate->serverstate == CHAPSS_OPEN) { + ChapSendStatus(cstate, CHAP_SUCCESS); + return; + } + if (cstate->serverstate == CHAPSS_BADAUTH) { + ChapSendStatus(cstate, CHAP_FAILURE); + return; + } + + if (len < 2) { + CHAPDEBUG(LOG_INFO, ("ChapReceiveResponse: rcvd short packet.\n")); + return; + } + GETCHAR(remmd_len, inp); /* get length of MD */ + remmd = inp; /* get pointer to MD */ + INCPTR(remmd_len, inp); + + len -= sizeof (u_char) + remmd_len; + if (len < 0) { + CHAPDEBUG(LOG_INFO, ("ChapReceiveResponse: rcvd short packet.\n")); + return; + } + + UNTIMEOUT(ChapChallengeTimeout, cstate); + + if (len >= (int)sizeof(rhostname)) { + len = sizeof(rhostname) - 1; + } + BCOPY(inp, rhostname, len); + rhostname[len] = '\000'; + + CHAPDEBUG(LOG_INFO, ("ChapReceiveResponse: received name field: %s\n", + rhostname)); + + /* + * Get secret for authenticating them with us, + * do the hash ourselves, and compare the result. + */ + code = CHAP_FAILURE; + if (!get_secret(cstate->unit, rhostname, cstate->chal_name, + secret, &secret_len, 1)) { + CHAPDEBUG(LOG_WARNING, ("No CHAP secret found for authenticating %s\n", + rhostname)); + } else { + /* generate MD based on negotiated type */ + switch (cstate->chal_type) { + + case CHAP_DIGEST_MD5: /* only MD5 is defined for now */ + if (remmd_len != MD5_SIGNATURE_SIZE) { + break; /* it's not even the right length */ + } + MD5Init(&mdContext); + MD5Update(&mdContext, &cstate->chal_id, 1); + MD5Update(&mdContext, (u_char*)secret, secret_len); + MD5Update(&mdContext, cstate->challenge, cstate->chal_len); + MD5Final(hash, &mdContext); + + /* compare local and remote MDs and send the appropriate status */ + if (memcmp (hash, remmd, MD5_SIGNATURE_SIZE) == 0) { + code = CHAP_SUCCESS; /* they are the same! */ + } + break; + + default: + CHAPDEBUG(LOG_INFO, ("unknown digest type %d\n", cstate->chal_type)); + } + } + + BZERO(secret, sizeof(secret)); + ChapSendStatus(cstate, code); + + if (code == CHAP_SUCCESS) { + old_state = cstate->serverstate; + cstate->serverstate = CHAPSS_OPEN; + if (old_state == CHAPSS_INITIAL_CHAL) { + auth_peer_success(cstate->unit, PPP_CHAP, rhostname, len); + } + if (cstate->chal_interval != 0) { + TIMEOUT(ChapRechallenge, cstate, cstate->chal_interval); + } + } else { + CHAPDEBUG(LOG_ERR, ("CHAP peer authentication failed\n")); + cstate->serverstate = CHAPSS_BADAUTH; + auth_peer_fail(cstate->unit, PPP_CHAP); + } +} + +/* + * ChapReceiveSuccess - Receive Success + */ +static void +ChapReceiveSuccess(chap_state *cstate, u_char *inp, u_char id, int len) +{ + LWIP_UNUSED_ARG(id); + LWIP_UNUSED_ARG(inp); + + CHAPDEBUG(LOG_INFO, ("ChapReceiveSuccess: Rcvd id %d.\n", id)); + + if (cstate->clientstate == CHAPCS_OPEN) { + /* presumably an answer to a duplicate response */ + return; + } + + if (cstate->clientstate != CHAPCS_RESPONSE) { + /* don't know what this is */ + CHAPDEBUG(LOG_INFO, ("ChapReceiveSuccess: in state %d\n", + cstate->clientstate)); + return; + } + + UNTIMEOUT(ChapResponseTimeout, cstate); + + /* + * Print message. + */ + if (len > 0) { + PRINTMSG(inp, len); + } + + cstate->clientstate = CHAPCS_OPEN; + + auth_withpeer_success(cstate->unit, PPP_CHAP); +} + + +/* + * ChapReceiveFailure - Receive failure. + */ +static void +ChapReceiveFailure(chap_state *cstate, u_char *inp, u_char id, int len) +{ + LWIP_UNUSED_ARG(id); + LWIP_UNUSED_ARG(inp); + + CHAPDEBUG(LOG_INFO, ("ChapReceiveFailure: Rcvd id %d.\n", id)); + + if (cstate->clientstate != CHAPCS_RESPONSE) { + /* don't know what this is */ + CHAPDEBUG(LOG_INFO, ("ChapReceiveFailure: in state %d\n", + cstate->clientstate)); + return; + } + + UNTIMEOUT(ChapResponseTimeout, cstate); + + /* + * Print message. + */ + if (len > 0) { + PRINTMSG(inp, len); + } + + CHAPDEBUG(LOG_ERR, ("CHAP authentication failed\n")); + auth_withpeer_fail(cstate->unit, PPP_CHAP); /* lwip: just sets the PPP error code on this unit to PPPERR_AUTHFAIL */ +} + + +/* + * ChapSendChallenge - Send an Authenticate challenge. + */ +static void +ChapSendChallenge(chap_state *cstate) +{ + u_char *outp; + int chal_len, name_len; + int outlen; + + chal_len = cstate->chal_len; + name_len = (int)strlen(cstate->chal_name); + outlen = CHAP_HEADERLEN + sizeof (u_char) + chal_len + name_len; + outp = outpacket_buf[cstate->unit]; + + MAKEHEADER(outp, PPP_CHAP); /* paste in a CHAP header */ + + PUTCHAR(CHAP_CHALLENGE, outp); + PUTCHAR(cstate->chal_id, outp); + PUTSHORT(outlen, outp); + + PUTCHAR(chal_len, outp); /* put length of challenge */ + BCOPY(cstate->challenge, outp, chal_len); + INCPTR(chal_len, outp); + + BCOPY(cstate->chal_name, outp, name_len); /* append hostname */ + + pppWrite(cstate->unit, outpacket_buf[cstate->unit], outlen + PPP_HDRLEN); + + CHAPDEBUG(LOG_INFO, ("ChapSendChallenge: Sent id %d.\n", cstate->chal_id)); + + TIMEOUT(ChapChallengeTimeout, cstate, cstate->timeouttime); + ++cstate->chal_transmits; +} + + +/* + * ChapSendStatus - Send a status response (ack or nak). + */ +static void +ChapSendStatus(chap_state *cstate, int code) +{ + u_char *outp; + int outlen, msglen; + char msg[256]; /* @todo: this can be a char*, no strcpy needed */ + + if (code == CHAP_SUCCESS) { + strcpy(msg, "Welcome!"); + } else { + strcpy(msg, "I don't like you. Go 'way."); + } + msglen = (int)strlen(msg); + + outlen = CHAP_HEADERLEN + msglen; + outp = outpacket_buf[cstate->unit]; + + MAKEHEADER(outp, PPP_CHAP); /* paste in a header */ + + PUTCHAR(code, outp); + PUTCHAR(cstate->chal_id, outp); + PUTSHORT(outlen, outp); + BCOPY(msg, outp, msglen); + pppWrite(cstate->unit, outpacket_buf[cstate->unit], outlen + PPP_HDRLEN); + + CHAPDEBUG(LOG_INFO, ("ChapSendStatus: Sent code %d, id %d.\n", code, + cstate->chal_id)); +} + +/* + * ChapGenChallenge is used to generate a pseudo-random challenge string of + * a pseudo-random length between min_len and max_len. The challenge + * string and its length are stored in *cstate, and various other fields of + * *cstate are initialized. + */ + +static void +ChapGenChallenge(chap_state *cstate) +{ + int chal_len; + u_char *ptr = cstate->challenge; + int i; + + /* pick a random challenge length between MIN_CHALLENGE_LENGTH and + MAX_CHALLENGE_LENGTH */ + chal_len = (unsigned) + ((((magic() >> 16) * + (MAX_CHALLENGE_LENGTH - MIN_CHALLENGE_LENGTH)) >> 16) + + MIN_CHALLENGE_LENGTH); + LWIP_ASSERT("chal_len <= 0xff", chal_len <= 0xffff); + cstate->chal_len = (u_char)chal_len; + cstate->chal_id = ++cstate->id; + cstate->chal_transmits = 0; + + /* generate a random string */ + for (i = 0; i < chal_len; i++ ) { + *ptr++ = (char) (magic() & 0xff); + } +} + +/* + * ChapSendResponse - send a response packet with values as specified + * in *cstate. + */ +/* ARGSUSED */ +static void +ChapSendResponse(chap_state *cstate) +{ + u_char *outp; + int outlen, md_len, name_len; + + md_len = cstate->resp_length; + name_len = (int)strlen(cstate->resp_name); + outlen = CHAP_HEADERLEN + sizeof (u_char) + md_len + name_len; + outp = outpacket_buf[cstate->unit]; + + MAKEHEADER(outp, PPP_CHAP); + + PUTCHAR(CHAP_RESPONSE, outp); /* we are a response */ + PUTCHAR(cstate->resp_id, outp); /* copy id from challenge packet */ + PUTSHORT(outlen, outp); /* packet length */ + + PUTCHAR(md_len, outp); /* length of MD */ + BCOPY(cstate->response, outp, md_len); /* copy MD to buffer */ + INCPTR(md_len, outp); + + BCOPY(cstate->resp_name, outp, name_len); /* append our name */ + + /* send the packet */ + pppWrite(cstate->unit, outpacket_buf[cstate->unit], outlen + PPP_HDRLEN); + + cstate->clientstate = CHAPCS_RESPONSE; + TIMEOUT(ChapResponseTimeout, cstate, cstate->timeouttime); + ++cstate->resp_transmits; +} + +#if PPP_ADDITIONAL_CALLBACKS +static char *ChapCodenames[] = { + "Challenge", "Response", "Success", "Failure" +}; +/* + * ChapPrintPkt - print the contents of a CHAP packet. + */ +static int +ChapPrintPkt( u_char *p, int plen, void (*printer) (void *, char *, ...), void *arg) +{ + int code, id, len; + int clen, nlen; + u_char x; + + if (plen < CHAP_HEADERLEN) { + return 0; + } + GETCHAR(code, p); + GETCHAR(id, p); + GETSHORT(len, p); + if (len < CHAP_HEADERLEN || len > plen) { + return 0; + } + + if (code >= 1 && code <= sizeof(ChapCodenames) / sizeof(char *)) { + printer(arg, " %s", ChapCodenames[code-1]); + } else { + printer(arg, " code=0x%x", code); + } + printer(arg, " id=0x%x", id); + len -= CHAP_HEADERLEN; + switch (code) { + case CHAP_CHALLENGE: + case CHAP_RESPONSE: + if (len < 1) { + break; + } + clen = p[0]; + if (len < clen + 1) { + break; + } + ++p; + nlen = len - clen - 1; + printer(arg, " <"); + for (; clen > 0; --clen) { + GETCHAR(x, p); + printer(arg, "%.2x", x); + } + printer(arg, ">, name = %.*Z", nlen, p); + break; + case CHAP_FAILURE: + case CHAP_SUCCESS: + printer(arg, " %.*Z", len, p); + break; + default: + for (clen = len; clen > 0; --clen) { + GETCHAR(x, p); + printer(arg, " %.2x", x); + } + } + + return len + CHAP_HEADERLEN; +} +#endif /* PPP_ADDITIONAL_CALLBACKS */ + +#endif /* CHAP_SUPPORT */ + +#endif /* PPP_SUPPORT */ diff --git a/features/unsupported/net/lwip/lwip/netif/ppp/chap.h b/features/unsupported/net/lwip/lwip/netif/ppp/chap.h new file mode 100644 index 00000000000..fedcab8da1a --- /dev/null +++ b/features/unsupported/net/lwip/lwip/netif/ppp/chap.h @@ -0,0 +1,150 @@ +/***************************************************************************** +* chap.h - Network Challenge Handshake Authentication Protocol header file. +* +* Copyright (c) 2003 by Marc Boucher, Services Informatiques (MBSI) inc. +* portions Copyright (c) 1998 Global Election Systems Inc. +* +* The authors hereby grant permission to use, copy, modify, distribute, +* and license this software and its documentation for any purpose, provided +* that existing copyright notices are retained in all copies and that this +* notice and the following disclaimer are included verbatim in any +* distributions. No written agreement, license, or royalty fee is required +* for any of the authorized uses. +* +* THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS *AS IS* AND ANY EXPRESS OR +* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +* IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT +* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +****************************************************************************** +* REVISION HISTORY +* +* 03-01-01 Marc Boucher +* Ported to lwIP. +* 97-12-03 Guy Lancaster , Global Election Systems Inc. +* Original built from BSD network code. +******************************************************************************/ +/* + * chap.h - Challenge Handshake Authentication Protocol definitions. + * + * Copyright (c) 1993 The Australian National University. + * All rights reserved. + * + * Redistribution and use in source and binary forms are permitted + * provided that the above copyright notice and this paragraph are + * duplicated in all such forms and that any documentation, + * advertising materials, and other materials related to such + * distribution and use acknowledge that the software was developed + * by the Australian National University. The name of the University + * may not be used to endorse or promote products derived from this + * software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED + * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. + * + * Copyright (c) 1991 Gregory M. Christy + * All rights reserved. + * + * Redistribution and use in source and binary forms are permitted + * provided that the above copyright notice and this paragraph are + * duplicated in all such forms and that any documentation, + * advertising materials, and other materials related to such + * distribution and use acknowledge that the software was developed + * by the author. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED + * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. + * + * $Id: chap.h,v 1.6 2010/01/24 13:19:34 goldsimon Exp $ + */ + +#ifndef CHAP_H +#define CHAP_H + +/* Code + ID + length */ +#define CHAP_HEADERLEN 4 + +/* + * CHAP codes. + */ + +#define CHAP_DIGEST_MD5 5 /* use MD5 algorithm */ +#define MD5_SIGNATURE_SIZE 16 /* 16 bytes in a MD5 message digest */ +#define CHAP_MICROSOFT 0x80 /* use Microsoft-compatible alg. */ +#define MS_CHAP_RESPONSE_LEN 49 /* Response length for MS-CHAP */ + +#define CHAP_CHALLENGE 1 +#define CHAP_RESPONSE 2 +#define CHAP_SUCCESS 3 +#define CHAP_FAILURE 4 + +/* + * Challenge lengths (for challenges we send) and other limits. + */ +#define MIN_CHALLENGE_LENGTH 32 +#define MAX_CHALLENGE_LENGTH 64 +#define MAX_RESPONSE_LENGTH 64 /* sufficient for MD5 or MS-CHAP */ + +/* + * Each interface is described by a chap structure. + */ + +typedef struct chap_state { + int unit; /* Interface unit number */ + int clientstate; /* Client state */ + int serverstate; /* Server state */ + u_char challenge[MAX_CHALLENGE_LENGTH]; /* last challenge string sent */ + u_char chal_len; /* challenge length */ + u_char chal_id; /* ID of last challenge */ + u_char chal_type; /* hash algorithm for challenges */ + u_char id; /* Current id */ + char *chal_name; /* Our name to use with challenge */ + int chal_interval; /* Time until we challenge peer again */ + int timeouttime; /* Timeout time in seconds */ + int max_transmits; /* Maximum # of challenge transmissions */ + int chal_transmits; /* Number of transmissions of challenge */ + int resp_transmits; /* Number of transmissions of response */ + u_char response[MAX_RESPONSE_LENGTH]; /* Response to send */ + u_char resp_length; /* length of response */ + u_char resp_id; /* ID for response messages */ + u_char resp_type; /* hash algorithm for responses */ + char *resp_name; /* Our name to send with response */ +} chap_state; + + +/* + * Client (peer) states. + */ +#define CHAPCS_INITIAL 0 /* Lower layer down, not opened */ +#define CHAPCS_CLOSED 1 /* Lower layer up, not opened */ +#define CHAPCS_PENDING 2 /* Auth us to peer when lower up */ +#define CHAPCS_LISTEN 3 /* Listening for a challenge */ +#define CHAPCS_RESPONSE 4 /* Sent response, waiting for status */ +#define CHAPCS_OPEN 5 /* We've received Success */ + +/* + * Server (authenticator) states. + */ +#define CHAPSS_INITIAL 0 /* Lower layer down, not opened */ +#define CHAPSS_CLOSED 1 /* Lower layer up, not opened */ +#define CHAPSS_PENDING 2 /* Auth peer when lower up */ +#define CHAPSS_INITIAL_CHAL 3 /* We've sent the first challenge */ +#define CHAPSS_OPEN 4 /* We've sent a Success msg */ +#define CHAPSS_RECHALLENGE 5 /* We've sent another challenge */ +#define CHAPSS_BADAUTH 6 /* We've sent a Failure msg */ + +extern chap_state chap[]; + +void ChapAuthWithPeer (int, char *, u_char); +void ChapAuthPeer (int, char *, u_char); + +extern struct protent chap_protent; + +#endif /* CHAP_H */ diff --git a/features/unsupported/net/lwip/lwip/netif/ppp/chpms.c b/features/unsupported/net/lwip/lwip/netif/ppp/chpms.c new file mode 100644 index 00000000000..83acefcec6d --- /dev/null +++ b/features/unsupported/net/lwip/lwip/netif/ppp/chpms.c @@ -0,0 +1,396 @@ +/*** WARNING - THIS CODE HAS NOT BEEN FINISHED! ***/ +/*** The original PPPD code is written in a way to require either the UNIX DES + encryption functions encrypt(3) and setkey(3) or the DES library libdes. + Since both is not included in lwIP, MSCHAP currently does not work! */ +/***************************************************************************** +* chpms.c - Network MicroSoft Challenge Handshake Authentication Protocol program file. +* +* Copyright (c) 2003 by Marc Boucher, Services Informatiques (MBSI) inc. +* Copyright (c) 1997 by Global Election Systems Inc. All rights reserved. +* +* The authors hereby grant permission to use, copy, modify, distribute, +* and license this software and its documentation for any purpose, provided +* that existing copyright notices are retained in all copies and that this +* notice and the following disclaimer are included verbatim in any +* distributions. No written agreement, license, or royalty fee is required +* for any of the authorized uses. +* +* THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS *AS IS* AND ANY EXPRESS OR +* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +* IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT +* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +****************************************************************************** +* REVISION HISTORY +* +* 03-01-01 Marc Boucher +* Ported to lwIP. +* 97-12-08 Guy Lancaster , Global Election Systems Inc. +* Original based on BSD chap_ms.c. +*****************************************************************************/ +/* + * chap_ms.c - Microsoft MS-CHAP compatible implementation. + * + * Copyright (c) 1995 Eric Rosenquist, Strata Software Limited. + * http://www.strataware.com/ + * + * All rights reserved. + * + * Redistribution and use in source and binary forms are permitted + * provided that the above copyright notice and this paragraph are + * duplicated in all such forms and that any documentation, + * advertising materials, and other materials related to such + * distribution and use acknowledge that the software was developed + * by Eric Rosenquist. The name of the author may not be used to + * endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED + * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. + */ + +/* + * Modifications by Lauri Pesonen / lpesonen@clinet.fi, april 1997 + * + * Implemented LANManager type password response to MS-CHAP challenges. + * Now pppd provides both NT style and LANMan style blocks, and the + * prefered is set by option "ms-lanman". Default is to use NT. + * The hash text (StdText) was taken from Win95 RASAPI32.DLL. + * + * You should also use DOMAIN\\USERNAME as described in README.MSCHAP80 + */ + +#define USE_CRYPT + +#include "lwip/opt.h" + +#if PPP_SUPPORT /* don't build if not configured for use in lwipopts.h */ + +#if MSCHAP_SUPPORT /* don't build if not configured for use in lwipopts.h */ + +#include "ppp.h" +#include "pppdebug.h" + +#include "md4.h" +#ifndef USE_CRYPT +#include "des.h" +#endif +#include "chap.h" +#include "chpms.h" + +#include + + +/*************************/ +/*** LOCAL DEFINITIONS ***/ +/*************************/ + + +/************************/ +/*** LOCAL DATA TYPES ***/ +/************************/ +typedef struct { + u_char LANManResp[24]; + u_char NTResp[24]; + u_char UseNT; /* If 1, ignore the LANMan response field */ +} MS_ChapResponse; +/* We use MS_CHAP_RESPONSE_LEN, rather than sizeof(MS_ChapResponse), + in case this struct gets padded. */ + + + +/***********************************/ +/*** LOCAL FUNCTION DECLARATIONS ***/ +/***********************************/ + +/* XXX Don't know what to do with these. */ +extern void setkey(const char *); +extern void encrypt(char *, int); + +static void DesEncrypt (u_char *, u_char *, u_char *); +static void MakeKey (u_char *, u_char *); + +#ifdef USE_CRYPT +static void Expand (u_char *, u_char *); +static void Collapse (u_char *, u_char *); +#endif + +static void ChallengeResponse( + u_char *challenge, /* IN 8 octets */ + u_char *pwHash, /* IN 16 octets */ + u_char *response /* OUT 24 octets */ +); +static void ChapMS_NT( + char *rchallenge, + int rchallenge_len, + char *secret, + int secret_len, + MS_ChapResponse *response +); +static u_char Get7Bits( + u_char *input, + int startBit +); + +static void +ChallengeResponse( u_char *challenge, /* IN 8 octets */ + u_char *pwHash, /* IN 16 octets */ + u_char *response /* OUT 24 octets */) +{ + u_char ZPasswordHash[21]; + + BZERO(ZPasswordHash, sizeof(ZPasswordHash)); + BCOPY(pwHash, ZPasswordHash, 16); + +#if 0 + log_packet(ZPasswordHash, sizeof(ZPasswordHash), "ChallengeResponse - ZPasswordHash", LOG_DEBUG); +#endif + + DesEncrypt(challenge, ZPasswordHash + 0, response + 0); + DesEncrypt(challenge, ZPasswordHash + 7, response + 8); + DesEncrypt(challenge, ZPasswordHash + 14, response + 16); + +#if 0 + log_packet(response, 24, "ChallengeResponse - response", LOG_DEBUG); +#endif +} + + +#ifdef USE_CRYPT +static void +DesEncrypt( u_char *clear, /* IN 8 octets */ + u_char *key, /* IN 7 octets */ + u_char *cipher /* OUT 8 octets */) +{ + u_char des_key[8]; + u_char crypt_key[66]; + u_char des_input[66]; + + MakeKey(key, des_key); + + Expand(des_key, crypt_key); + setkey((char*)crypt_key); + +#if 0 + CHAPDEBUG(LOG_INFO, ("DesEncrypt: 8 octet input : %02X%02X%02X%02X%02X%02X%02X%02X\n", + clear[0], clear[1], clear[2], clear[3], clear[4], clear[5], clear[6], clear[7])); +#endif + + Expand(clear, des_input); + encrypt((char*)des_input, 0); + Collapse(des_input, cipher); + +#if 0 + CHAPDEBUG(LOG_INFO, ("DesEncrypt: 8 octet output: %02X%02X%02X%02X%02X%02X%02X%02X\n", + cipher[0], cipher[1], cipher[2], cipher[3], cipher[4], cipher[5], cipher[6], cipher[7])); +#endif +} + +#else /* USE_CRYPT */ + +static void +DesEncrypt( u_char *clear, /* IN 8 octets */ + u_char *key, /* IN 7 octets */ + u_char *cipher /* OUT 8 octets */) +{ + des_cblock des_key; + des_key_schedule key_schedule; + + MakeKey(key, des_key); + + des_set_key(&des_key, key_schedule); + +#if 0 + CHAPDEBUG(LOG_INFO, ("DesEncrypt: 8 octet input : %02X%02X%02X%02X%02X%02X%02X%02X\n", + clear[0], clear[1], clear[2], clear[3], clear[4], clear[5], clear[6], clear[7])); +#endif + + des_ecb_encrypt((des_cblock *)clear, (des_cblock *)cipher, key_schedule, 1); + +#if 0 + CHAPDEBUG(LOG_INFO, ("DesEncrypt: 8 octet output: %02X%02X%02X%02X%02X%02X%02X%02X\n", + cipher[0], cipher[1], cipher[2], cipher[3], cipher[4], cipher[5], cipher[6], cipher[7])); +#endif +} + +#endif /* USE_CRYPT */ + + +static u_char +Get7Bits( u_char *input, int startBit) +{ + register unsigned int word; + + word = (unsigned)input[startBit / 8] << 8; + word |= (unsigned)input[startBit / 8 + 1]; + + word >>= 15 - (startBit % 8 + 7); + + return word & 0xFE; +} + +#ifdef USE_CRYPT + +/* in == 8-byte string (expanded version of the 56-bit key) + * out == 64-byte string where each byte is either 1 or 0 + * Note that the low-order "bit" is always ignored by by setkey() + */ +static void +Expand(u_char *in, u_char *out) +{ + int j, c; + int i; + + for(i = 0; i < 64; in++){ + c = *in; + for(j = 7; j >= 0; j--) { + *out++ = (c >> j) & 01; + } + i += 8; + } +} + +/* The inverse of Expand + */ +static void +Collapse(u_char *in, u_char *out) +{ + int j; + int i; + unsigned int c; + + for (i = 0; i < 64; i += 8, out++) { + c = 0; + for (j = 7; j >= 0; j--, in++) { + c |= *in << j; + } + *out = c & 0xff; + } +} +#endif + +static void +MakeKey( u_char *key, /* IN 56 bit DES key missing parity bits */ + u_char *des_key /* OUT 64 bit DES key with parity bits added */) +{ + des_key[0] = Get7Bits(key, 0); + des_key[1] = Get7Bits(key, 7); + des_key[2] = Get7Bits(key, 14); + des_key[3] = Get7Bits(key, 21); + des_key[4] = Get7Bits(key, 28); + des_key[5] = Get7Bits(key, 35); + des_key[6] = Get7Bits(key, 42); + des_key[7] = Get7Bits(key, 49); + +#ifndef USE_CRYPT + des_set_odd_parity((des_cblock *)des_key); +#endif + +#if 0 + CHAPDEBUG(LOG_INFO, ("MakeKey: 56-bit input : %02X%02X%02X%02X%02X%02X%02X\n", + key[0], key[1], key[2], key[3], key[4], key[5], key[6])); + CHAPDEBUG(LOG_INFO, ("MakeKey: 64-bit output: %02X%02X%02X%02X%02X%02X%02X%02X\n", + des_key[0], des_key[1], des_key[2], des_key[3], des_key[4], des_key[5], des_key[6], des_key[7])); +#endif +} + +static void +ChapMS_NT( char *rchallenge, + int rchallenge_len, + char *secret, + int secret_len, + MS_ChapResponse *response) +{ + int i; + MDstruct md4Context; + u_char unicodePassword[MAX_NT_PASSWORD * 2]; + static int low_byte_first = -1; + + LWIP_UNUSED_ARG(rchallenge_len); + + /* Initialize the Unicode version of the secret (== password). */ + /* This implicitly supports 8-bit ISO8859/1 characters. */ + BZERO(unicodePassword, sizeof(unicodePassword)); + for (i = 0; i < secret_len; i++) { + unicodePassword[i * 2] = (u_char)secret[i]; + } + MDbegin(&md4Context); + MDupdate(&md4Context, unicodePassword, secret_len * 2 * 8); /* Unicode is 2 bytes/char, *8 for bit count */ + + if (low_byte_first == -1) { + low_byte_first = (PP_HTONS((unsigned short int)1) != 1); + } + if (low_byte_first == 0) { + /* @todo: arg type - u_long* or u_int* ? */ + MDreverse((unsigned int*)&md4Context); /* sfb 961105 */ + } + + MDupdate(&md4Context, NULL, 0); /* Tell MD4 we're done */ + + ChallengeResponse((u_char*)rchallenge, (u_char*)md4Context.buffer, response->NTResp); +} + +#ifdef MSLANMAN +static u_char *StdText = (u_char *)"KGS!@#$%"; /* key from rasapi32.dll */ + +static void +ChapMS_LANMan( char *rchallenge, + int rchallenge_len, + char *secret, + int secret_len, + MS_ChapResponse *response) +{ + int i; + u_char UcasePassword[MAX_NT_PASSWORD]; /* max is actually 14 */ + u_char PasswordHash[16]; + + /* LANMan password is case insensitive */ + BZERO(UcasePassword, sizeof(UcasePassword)); + for (i = 0; i < secret_len; i++) { + UcasePassword[i] = (u_char)toupper(secret[i]); + } + DesEncrypt( StdText, UcasePassword + 0, PasswordHash + 0 ); + DesEncrypt( StdText, UcasePassword + 7, PasswordHash + 8 ); + ChallengeResponse(rchallenge, PasswordHash, response->LANManResp); +} +#endif + +void +ChapMS( chap_state *cstate, char *rchallenge, int rchallenge_len, char *secret, int secret_len) +{ + MS_ChapResponse response; +#ifdef MSLANMAN + extern int ms_lanman; +#endif + +#if 0 + CHAPDEBUG(LOG_INFO, ("ChapMS: secret is '%.*s'\n", secret_len, secret)); +#endif + BZERO(&response, sizeof(response)); + + /* Calculate both always */ + ChapMS_NT(rchallenge, rchallenge_len, secret, secret_len, &response); + +#ifdef MSLANMAN + ChapMS_LANMan(rchallenge, rchallenge_len, secret, secret_len, &response); + + /* prefered method is set by option */ + response.UseNT = !ms_lanman; +#else + response.UseNT = 1; +#endif + + BCOPY(&response, cstate->response, MS_CHAP_RESPONSE_LEN); + cstate->resp_length = MS_CHAP_RESPONSE_LEN; +} + +#endif /* MSCHAP_SUPPORT */ + +#endif /* PPP_SUPPORT */ diff --git a/features/unsupported/net/lwip/lwip/netif/ppp/chpms.h b/features/unsupported/net/lwip/lwip/netif/ppp/chpms.h new file mode 100644 index 00000000000..df070fb356b --- /dev/null +++ b/features/unsupported/net/lwip/lwip/netif/ppp/chpms.h @@ -0,0 +1,64 @@ +/***************************************************************************** +* chpms.h - Network Microsoft Challenge Handshake Protocol header file. +* +* Copyright (c) 2003 by Marc Boucher, Services Informatiques (MBSI) inc. +* portions Copyright (c) 1998 Global Election Systems Inc. +* +* The authors hereby grant permission to use, copy, modify, distribute, +* and license this software and its documentation for any purpose, provided +* that existing copyright notices are retained in all copies and that this +* notice and the following disclaimer are included verbatim in any +* distributions. No written agreement, license, or royalty fee is required +* for any of the authorized uses. +* +* THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS *AS IS* AND ANY EXPRESS OR +* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +* IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT +* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +****************************************************************************** +* REVISION HISTORY +* +* 03-01-01 Marc Boucher +* Ported to lwIP. +* 98-01-30 Guy Lancaster , Global Election Systems Inc. +* Original built from BSD network code. +******************************************************************************/ +/* + * chap.h - Challenge Handshake Authentication Protocol definitions. + * + * Copyright (c) 1995 Eric Rosenquist, Strata Software Limited. + * http://www.strataware.com/ + * + * All rights reserved. + * + * Redistribution and use in source and binary forms are permitted + * provided that the above copyright notice and this paragraph are + * duplicated in all such forms and that any documentation, + * advertising materials, and other materials related to such + * distribution and use acknowledge that the software was developed + * by Eric Rosenquist. The name of the author may not be used to + * endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED + * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. + * + * $Id: chpms.h,v 1.5 2007/12/19 20:47:23 fbernon Exp $ + */ + +#ifndef CHPMS_H +#define CHPMS_H + +#define MAX_NT_PASSWORD 256 /* Maximum number of (Unicode) chars in an NT password */ + +void ChapMS (chap_state *, char *, int, char *, int); + +#endif /* CHPMS_H */ diff --git a/features/unsupported/net/lwip/lwip/netif/ppp/fsm.c b/features/unsupported/net/lwip/lwip/netif/ppp/fsm.c new file mode 100644 index 00000000000..2e73c5af8ff --- /dev/null +++ b/features/unsupported/net/lwip/lwip/netif/ppp/fsm.c @@ -0,0 +1,890 @@ +/***************************************************************************** +* fsm.c - Network Control Protocol Finite State Machine program file. +* +* Copyright (c) 2003 by Marc Boucher, Services Informatiques (MBSI) inc. +* portions Copyright (c) 1997 by Global Election Systems Inc. +* +* The authors hereby grant permission to use, copy, modify, distribute, +* and license this software and its documentation for any purpose, provided +* that existing copyright notices are retained in all copies and that this +* notice and the following disclaimer are included verbatim in any +* distributions. No written agreement, license, or royalty fee is required +* for any of the authorized uses. +* +* THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS *AS IS* AND ANY EXPRESS OR +* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +* IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT +* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +****************************************************************************** +* REVISION HISTORY +* +* 03-01-01 Marc Boucher +* Ported to lwIP. +* 97-12-01 Guy Lancaster , Global Election Systems Inc. +* Original based on BSD fsm.c. +*****************************************************************************/ +/* + * fsm.c - {Link, IP} Control Protocol Finite State Machine. + * + * Copyright (c) 1989 Carnegie Mellon University. + * All rights reserved. + * + * Redistribution and use in source and binary forms are permitted + * provided that the above copyright notice and this paragraph are + * duplicated in all such forms and that any documentation, + * advertising materials, and other materials related to such + * distribution and use acknowledge that the software was developed + * by Carnegie Mellon University. The name of the + * University may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED + * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. + */ + +/* + * TODO: + * Randomize fsm id on link/init. + * Deal with variable outgoing MTU. + */ + +#include "lwip/opt.h" + +#if PPP_SUPPORT /* don't build if not configured for use in lwipopts.h */ + +#include "ppp.h" +#include "pppdebug.h" + +#include "fsm.h" + +#include + +#if PPP_DEBUG +static const char *ppperr_strerr[] = { + "LS_INITIAL", /* LS_INITIAL 0 */ + "LS_STARTING", /* LS_STARTING 1 */ + "LS_CLOSED", /* LS_CLOSED 2 */ + "LS_STOPPED", /* LS_STOPPED 3 */ + "LS_CLOSING", /* LS_CLOSING 4 */ + "LS_STOPPING", /* LS_STOPPING 5 */ + "LS_REQSENT", /* LS_REQSENT 6 */ + "LS_ACKRCVD", /* LS_ACKRCVD 7 */ + "LS_ACKSENT", /* LS_ACKSENT 8 */ + "LS_OPENED" /* LS_OPENED 9 */ +}; +#endif /* PPP_DEBUG */ + +static void fsm_timeout (void *); +static void fsm_rconfreq (fsm *, u_char, u_char *, int); +static void fsm_rconfack (fsm *, int, u_char *, int); +static void fsm_rconfnakrej (fsm *, int, int, u_char *, int); +static void fsm_rtermreq (fsm *, int, u_char *, int); +static void fsm_rtermack (fsm *); +static void fsm_rcoderej (fsm *, u_char *, int); +static void fsm_sconfreq (fsm *, int); + +#define PROTO_NAME(f) ((f)->callbacks->proto_name) + +int peer_mru[NUM_PPP]; + + +/* + * fsm_init - Initialize fsm. + * + * Initialize fsm state. + */ +void +fsm_init(fsm *f) +{ + f->state = LS_INITIAL; + f->flags = 0; + f->id = 0; /* XXX Start with random id? */ + f->timeouttime = FSM_DEFTIMEOUT; + f->maxconfreqtransmits = FSM_DEFMAXCONFREQS; + f->maxtermtransmits = FSM_DEFMAXTERMREQS; + f->maxnakloops = FSM_DEFMAXNAKLOOPS; + f->term_reason_len = 0; +} + + +/* + * fsm_lowerup - The lower layer is up. + */ +void +fsm_lowerup(fsm *f) +{ + int oldState = f->state; + + LWIP_UNUSED_ARG(oldState); + + switch( f->state ) { + case LS_INITIAL: + f->state = LS_CLOSED; + break; + + case LS_STARTING: + if( f->flags & OPT_SILENT ) { + f->state = LS_STOPPED; + } else { + /* Send an initial configure-request */ + fsm_sconfreq(f, 0); + f->state = LS_REQSENT; + } + break; + + default: + FSMDEBUG(LOG_INFO, ("%s: Up event in state %d (%s)!\n", + PROTO_NAME(f), f->state, ppperr_strerr[f->state])); + } + + FSMDEBUG(LOG_INFO, ("%s: lowerup state %d (%s) -> %d (%s)\n", + PROTO_NAME(f), oldState, ppperr_strerr[oldState], f->state, ppperr_strerr[f->state])); +} + + +/* + * fsm_lowerdown - The lower layer is down. + * + * Cancel all timeouts and inform upper layers. + */ +void +fsm_lowerdown(fsm *f) +{ + int oldState = f->state; + + LWIP_UNUSED_ARG(oldState); + + switch( f->state ) { + case LS_CLOSED: + f->state = LS_INITIAL; + break; + + case LS_STOPPED: + f->state = LS_STARTING; + if( f->callbacks->starting ) { + (*f->callbacks->starting)(f); + } + break; + + case LS_CLOSING: + f->state = LS_INITIAL; + UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */ + break; + + case LS_STOPPING: + case LS_REQSENT: + case LS_ACKRCVD: + case LS_ACKSENT: + f->state = LS_STARTING; + UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */ + break; + + case LS_OPENED: + if( f->callbacks->down ) { + (*f->callbacks->down)(f); + } + f->state = LS_STARTING; + break; + + default: + FSMDEBUG(LOG_INFO, ("%s: Down event in state %d (%s)!\n", + PROTO_NAME(f), f->state, ppperr_strerr[f->state])); + } + + FSMDEBUG(LOG_INFO, ("%s: lowerdown state %d (%s) -> %d (%s)\n", + PROTO_NAME(f), oldState, ppperr_strerr[oldState], f->state, ppperr_strerr[f->state])); +} + + +/* + * fsm_open - Link is allowed to come up. + */ +void +fsm_open(fsm *f) +{ + int oldState = f->state; + + LWIP_UNUSED_ARG(oldState); + + switch( f->state ) { + case LS_INITIAL: + f->state = LS_STARTING; + if( f->callbacks->starting ) { + (*f->callbacks->starting)(f); + } + break; + + case LS_CLOSED: + if( f->flags & OPT_SILENT ) { + f->state = LS_STOPPED; + } else { + /* Send an initial configure-request */ + fsm_sconfreq(f, 0); + f->state = LS_REQSENT; + } + break; + + case LS_CLOSING: + f->state = LS_STOPPING; + /* fall through */ + case LS_STOPPED: + case LS_OPENED: + if( f->flags & OPT_RESTART ) { + fsm_lowerdown(f); + fsm_lowerup(f); + } + break; + } + + FSMDEBUG(LOG_INFO, ("%s: open state %d (%s) -> %d (%s)\n", + PROTO_NAME(f), oldState, ppperr_strerr[oldState], f->state, ppperr_strerr[f->state])); +} + +#if 0 /* backport pppd 2.4.4b1; */ +/* + * terminate_layer - Start process of shutting down the FSM + * + * Cancel any timeout running, notify upper layers we're done, and + * send a terminate-request message as configured. + */ +static void +terminate_layer(fsm *f, int nextstate) +{ + /* @todo */ +} +#endif + +/* + * fsm_close - Start closing connection. + * + * Cancel timeouts and either initiate close or possibly go directly to + * the LS_CLOSED state. + */ +void +fsm_close(fsm *f, char *reason) +{ + int oldState = f->state; + + LWIP_UNUSED_ARG(oldState); + + f->term_reason = reason; + f->term_reason_len = (reason == NULL ? 0 : (int)strlen(reason)); + switch( f->state ) { + case LS_STARTING: + f->state = LS_INITIAL; + break; + case LS_STOPPED: + f->state = LS_CLOSED; + break; + case LS_STOPPING: + f->state = LS_CLOSING; + break; + + case LS_REQSENT: + case LS_ACKRCVD: + case LS_ACKSENT: + case LS_OPENED: + if( f->state != LS_OPENED ) { + UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */ + } else if( f->callbacks->down ) { + (*f->callbacks->down)(f); /* Inform upper layers we're down */ + } + /* Init restart counter, send Terminate-Request */ + f->retransmits = f->maxtermtransmits; + fsm_sdata(f, TERMREQ, f->reqid = ++f->id, + (u_char *) f->term_reason, f->term_reason_len); + TIMEOUT(fsm_timeout, f, f->timeouttime); + --f->retransmits; + + f->state = LS_CLOSING; + break; + } + + FSMDEBUG(LOG_INFO, ("%s: close reason=%s state %d (%s) -> %d (%s)\n", + PROTO_NAME(f), reason, oldState, ppperr_strerr[oldState], f->state, ppperr_strerr[f->state])); +} + + +/* + * fsm_timeout - Timeout expired. + */ +static void +fsm_timeout(void *arg) +{ + fsm *f = (fsm *) arg; + + switch (f->state) { + case LS_CLOSING: + case LS_STOPPING: + if( f->retransmits <= 0 ) { + FSMDEBUG(LOG_WARNING, ("%s: timeout sending Terminate-Request state=%d (%s)\n", + PROTO_NAME(f), f->state, ppperr_strerr[f->state])); + /* + * We've waited for an ack long enough. Peer probably heard us. + */ + f->state = (f->state == LS_CLOSING)? LS_CLOSED: LS_STOPPED; + if( f->callbacks->finished ) { + (*f->callbacks->finished)(f); + } + } else { + FSMDEBUG(LOG_WARNING, ("%s: timeout resending Terminate-Requests state=%d (%s)\n", + PROTO_NAME(f), f->state, ppperr_strerr[f->state])); + /* Send Terminate-Request */ + fsm_sdata(f, TERMREQ, f->reqid = ++f->id, + (u_char *) f->term_reason, f->term_reason_len); + TIMEOUT(fsm_timeout, f, f->timeouttime); + --f->retransmits; + } + break; + + case LS_REQSENT: + case LS_ACKRCVD: + case LS_ACKSENT: + if (f->retransmits <= 0) { + FSMDEBUG(LOG_WARNING, ("%s: timeout sending Config-Requests state=%d (%s)\n", + PROTO_NAME(f), f->state, ppperr_strerr[f->state])); + f->state = LS_STOPPED; + if( (f->flags & OPT_PASSIVE) == 0 && f->callbacks->finished ) { + (*f->callbacks->finished)(f); + } + } else { + FSMDEBUG(LOG_WARNING, ("%s: timeout resending Config-Request state=%d (%s)\n", + PROTO_NAME(f), f->state, ppperr_strerr[f->state])); + /* Retransmit the configure-request */ + if (f->callbacks->retransmit) { + (*f->callbacks->retransmit)(f); + } + fsm_sconfreq(f, 1); /* Re-send Configure-Request */ + if( f->state == LS_ACKRCVD ) { + f->state = LS_REQSENT; + } + } + break; + + default: + FSMDEBUG(LOG_INFO, ("%s: UNHANDLED timeout event in state %d (%s)!\n", + PROTO_NAME(f), f->state, ppperr_strerr[f->state])); + } +} + + +/* + * fsm_input - Input packet. + */ +void +fsm_input(fsm *f, u_char *inpacket, int l) +{ + u_char *inp = inpacket; + u_char code, id; + int len; + + /* + * Parse header (code, id and length). + * If packet too short, drop it. + */ + if (l < HEADERLEN) { + FSMDEBUG(LOG_WARNING, ("fsm_input(%x): Rcvd short header.\n", + f->protocol)); + return; + } + GETCHAR(code, inp); + GETCHAR(id, inp); + GETSHORT(len, inp); + if (len < HEADERLEN) { + FSMDEBUG(LOG_INFO, ("fsm_input(%x): Rcvd illegal length.\n", + f->protocol)); + return; + } + if (len > l) { + FSMDEBUG(LOG_INFO, ("fsm_input(%x): Rcvd short packet.\n", + f->protocol)); + return; + } + len -= HEADERLEN; /* subtract header length */ + + if( f->state == LS_INITIAL || f->state == LS_STARTING ) { + FSMDEBUG(LOG_INFO, ("fsm_input(%x): Rcvd packet in state %d (%s).\n", + f->protocol, f->state, ppperr_strerr[f->state])); + return; + } + FSMDEBUG(LOG_INFO, ("fsm_input(%s):%d,%d,%d\n", PROTO_NAME(f), code, id, l)); + /* + * Action depends on code. + */ + switch (code) { + case CONFREQ: + fsm_rconfreq(f, id, inp, len); + break; + + case CONFACK: + fsm_rconfack(f, id, inp, len); + break; + + case CONFNAK: + case CONFREJ: + fsm_rconfnakrej(f, code, id, inp, len); + break; + + case TERMREQ: + fsm_rtermreq(f, id, inp, len); + break; + + case TERMACK: + fsm_rtermack(f); + break; + + case CODEREJ: + fsm_rcoderej(f, inp, len); + break; + + default: + FSMDEBUG(LOG_INFO, ("fsm_input(%s): default: \n", PROTO_NAME(f))); + if( !f->callbacks->extcode || + !(*f->callbacks->extcode)(f, code, id, inp, len) ) { + fsm_sdata(f, CODEREJ, ++f->id, inpacket, len + HEADERLEN); + } + break; + } +} + + +/* + * fsm_rconfreq - Receive Configure-Request. + */ +static void +fsm_rconfreq(fsm *f, u_char id, u_char *inp, int len) +{ + int code, reject_if_disagree; + + FSMDEBUG(LOG_INFO, ("fsm_rconfreq(%s): Rcvd id %d state=%d (%s)\n", + PROTO_NAME(f), id, f->state, ppperr_strerr[f->state])); + switch( f->state ) { + case LS_CLOSED: + /* Go away, we're closed */ + fsm_sdata(f, TERMACK, id, NULL, 0); + return; + case LS_CLOSING: + case LS_STOPPING: + return; + + case LS_OPENED: + /* Go down and restart negotiation */ + if( f->callbacks->down ) { + (*f->callbacks->down)(f); /* Inform upper layers */ + } + fsm_sconfreq(f, 0); /* Send initial Configure-Request */ + break; + + case LS_STOPPED: + /* Negotiation started by our peer */ + fsm_sconfreq(f, 0); /* Send initial Configure-Request */ + f->state = LS_REQSENT; + break; + } + + /* + * Pass the requested configuration options + * to protocol-specific code for checking. + */ + if (f->callbacks->reqci) { /* Check CI */ + reject_if_disagree = (f->nakloops >= f->maxnakloops); + code = (*f->callbacks->reqci)(f, inp, &len, reject_if_disagree); + } else if (len) { + code = CONFREJ; /* Reject all CI */ + } else { + code = CONFACK; + } + + /* send the Ack, Nak or Rej to the peer */ + fsm_sdata(f, (u_char)code, id, inp, len); + + if (code == CONFACK) { + if (f->state == LS_ACKRCVD) { + UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */ + f->state = LS_OPENED; + if (f->callbacks->up) { + (*f->callbacks->up)(f); /* Inform upper layers */ + } + } else { + f->state = LS_ACKSENT; + } + f->nakloops = 0; + } else { + /* we sent CONFACK or CONFREJ */ + if (f->state != LS_ACKRCVD) { + f->state = LS_REQSENT; + } + if( code == CONFNAK ) { + ++f->nakloops; + } + } +} + + +/* + * fsm_rconfack - Receive Configure-Ack. + */ +static void +fsm_rconfack(fsm *f, int id, u_char *inp, int len) +{ + FSMDEBUG(LOG_INFO, ("fsm_rconfack(%s): Rcvd id %d state=%d (%s)\n", + PROTO_NAME(f), id, f->state, ppperr_strerr[f->state])); + + if (id != f->reqid || f->seen_ack) { /* Expected id? */ + return; /* Nope, toss... */ + } + if( !(f->callbacks->ackci? (*f->callbacks->ackci)(f, inp, len): (len == 0)) ) { + /* Ack is bad - ignore it */ + FSMDEBUG(LOG_INFO, ("%s: received bad Ack (length %d)\n", + PROTO_NAME(f), len)); + return; + } + f->seen_ack = 1; + + switch (f->state) { + case LS_CLOSED: + case LS_STOPPED: + fsm_sdata(f, TERMACK, (u_char)id, NULL, 0); + break; + + case LS_REQSENT: + f->state = LS_ACKRCVD; + f->retransmits = f->maxconfreqtransmits; + break; + + case LS_ACKRCVD: + /* Huh? an extra valid Ack? oh well... */ + UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */ + fsm_sconfreq(f, 0); + f->state = LS_REQSENT; + break; + + case LS_ACKSENT: + UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */ + f->state = LS_OPENED; + f->retransmits = f->maxconfreqtransmits; + if (f->callbacks->up) { + (*f->callbacks->up)(f); /* Inform upper layers */ + } + break; + + case LS_OPENED: + /* Go down and restart negotiation */ + if (f->callbacks->down) { + (*f->callbacks->down)(f); /* Inform upper layers */ + } + fsm_sconfreq(f, 0); /* Send initial Configure-Request */ + f->state = LS_REQSENT; + break; + } +} + + +/* + * fsm_rconfnakrej - Receive Configure-Nak or Configure-Reject. + */ +static void +fsm_rconfnakrej(fsm *f, int code, int id, u_char *inp, int len) +{ + int (*proc) (fsm *, u_char *, int); + int ret; + + FSMDEBUG(LOG_INFO, ("fsm_rconfnakrej(%s): Rcvd id %d state=%d (%s)\n", + PROTO_NAME(f), id, f->state, ppperr_strerr[f->state])); + + if (id != f->reqid || f->seen_ack) { /* Expected id? */ + return; /* Nope, toss... */ + } + proc = (code == CONFNAK)? f->callbacks->nakci: f->callbacks->rejci; + if (!proc || !((ret = proc(f, inp, len)))) { + /* Nak/reject is bad - ignore it */ + FSMDEBUG(LOG_INFO, ("%s: received bad %s (length %d)\n", + PROTO_NAME(f), (code==CONFNAK? "Nak": "reject"), len)); + return; + } + f->seen_ack = 1; + + switch (f->state) { + case LS_CLOSED: + case LS_STOPPED: + fsm_sdata(f, TERMACK, (u_char)id, NULL, 0); + break; + + case LS_REQSENT: + case LS_ACKSENT: + /* They didn't agree to what we wanted - try another request */ + UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */ + if (ret < 0) { + f->state = LS_STOPPED; /* kludge for stopping CCP */ + } else { + fsm_sconfreq(f, 0); /* Send Configure-Request */ + } + break; + + case LS_ACKRCVD: + /* Got a Nak/reject when we had already had an Ack?? oh well... */ + UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */ + fsm_sconfreq(f, 0); + f->state = LS_REQSENT; + break; + + case LS_OPENED: + /* Go down and restart negotiation */ + if (f->callbacks->down) { + (*f->callbacks->down)(f); /* Inform upper layers */ + } + fsm_sconfreq(f, 0); /* Send initial Configure-Request */ + f->state = LS_REQSENT; + break; + } +} + + +/* + * fsm_rtermreq - Receive Terminate-Req. + */ +static void +fsm_rtermreq(fsm *f, int id, u_char *p, int len) +{ + LWIP_UNUSED_ARG(p); + + FSMDEBUG(LOG_INFO, ("fsm_rtermreq(%s): Rcvd id %d state=%d (%s)\n", + PROTO_NAME(f), id, f->state, ppperr_strerr[f->state])); + + switch (f->state) { + case LS_ACKRCVD: + case LS_ACKSENT: + f->state = LS_REQSENT; /* Start over but keep trying */ + break; + + case LS_OPENED: + if (len > 0) { + FSMDEBUG(LOG_INFO, ("%s terminated by peer (%p)\n", PROTO_NAME(f), p)); + } else { + FSMDEBUG(LOG_INFO, ("%s terminated by peer\n", PROTO_NAME(f))); + } + if (f->callbacks->down) { + (*f->callbacks->down)(f); /* Inform upper layers */ + } + f->retransmits = 0; + f->state = LS_STOPPING; + TIMEOUT(fsm_timeout, f, f->timeouttime); + break; + } + + fsm_sdata(f, TERMACK, (u_char)id, NULL, 0); +} + + +/* + * fsm_rtermack - Receive Terminate-Ack. + */ +static void +fsm_rtermack(fsm *f) +{ + FSMDEBUG(LOG_INFO, ("fsm_rtermack(%s): state=%d (%s)\n", + PROTO_NAME(f), f->state, ppperr_strerr[f->state])); + + switch (f->state) { + case LS_CLOSING: + UNTIMEOUT(fsm_timeout, f); + f->state = LS_CLOSED; + if( f->callbacks->finished ) { + (*f->callbacks->finished)(f); + } + break; + + case LS_STOPPING: + UNTIMEOUT(fsm_timeout, f); + f->state = LS_STOPPED; + if( f->callbacks->finished ) { + (*f->callbacks->finished)(f); + } + break; + + case LS_ACKRCVD: + f->state = LS_REQSENT; + break; + + case LS_OPENED: + if (f->callbacks->down) { + (*f->callbacks->down)(f); /* Inform upper layers */ + } + fsm_sconfreq(f, 0); + break; + default: + FSMDEBUG(LOG_INFO, ("fsm_rtermack(%s): UNHANDLED state=%d (%s)!!!\n", + PROTO_NAME(f), f->state, ppperr_strerr[f->state])); + } +} + + +/* + * fsm_rcoderej - Receive an Code-Reject. + */ +static void +fsm_rcoderej(fsm *f, u_char *inp, int len) +{ + u_char code, id; + + FSMDEBUG(LOG_INFO, ("fsm_rcoderej(%s): state=%d (%s)\n", + PROTO_NAME(f), f->state, ppperr_strerr[f->state])); + + if (len < HEADERLEN) { + FSMDEBUG(LOG_INFO, ("fsm_rcoderej: Rcvd short Code-Reject packet!\n")); + return; + } + GETCHAR(code, inp); + GETCHAR(id, inp); + FSMDEBUG(LOG_WARNING, ("%s: Rcvd Code-Reject for code %d, id %d\n", + PROTO_NAME(f), code, id)); + + if( f->state == LS_ACKRCVD ) { + f->state = LS_REQSENT; + } +} + + +/* + * fsm_protreject - Peer doesn't speak this protocol. + * + * Treat this as a catastrophic error (RXJ-). + */ +void +fsm_protreject(fsm *f) +{ + switch( f->state ) { + case LS_CLOSING: + UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */ + /* fall through */ + case LS_CLOSED: + f->state = LS_CLOSED; + if( f->callbacks->finished ) { + (*f->callbacks->finished)(f); + } + break; + + case LS_STOPPING: + case LS_REQSENT: + case LS_ACKRCVD: + case LS_ACKSENT: + UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */ + /* fall through */ + case LS_STOPPED: + f->state = LS_STOPPED; + if( f->callbacks->finished ) { + (*f->callbacks->finished)(f); + } + break; + + case LS_OPENED: + if( f->callbacks->down ) { + (*f->callbacks->down)(f); + } + /* Init restart counter, send Terminate-Request */ + f->retransmits = f->maxtermtransmits; + fsm_sdata(f, TERMREQ, f->reqid = ++f->id, + (u_char *) f->term_reason, f->term_reason_len); + TIMEOUT(fsm_timeout, f, f->timeouttime); + --f->retransmits; + + f->state = LS_STOPPING; + break; + + default: + FSMDEBUG(LOG_INFO, ("%s: Protocol-reject event in state %d (%s)!\n", + PROTO_NAME(f), f->state, ppperr_strerr[f->state])); + } +} + + +/* + * fsm_sconfreq - Send a Configure-Request. + */ +static void +fsm_sconfreq(fsm *f, int retransmit) +{ + u_char *outp; + int cilen; + + if( f->state != LS_REQSENT && f->state != LS_ACKRCVD && f->state != LS_ACKSENT ) { + /* Not currently negotiating - reset options */ + if( f->callbacks->resetci ) { + (*f->callbacks->resetci)(f); + } + f->nakloops = 0; + } + + if( !retransmit ) { + /* New request - reset retransmission counter, use new ID */ + f->retransmits = f->maxconfreqtransmits; + f->reqid = ++f->id; + } + + f->seen_ack = 0; + + /* + * Make up the request packet + */ + outp = outpacket_buf[f->unit] + PPP_HDRLEN + HEADERLEN; + if( f->callbacks->cilen && f->callbacks->addci ) { + cilen = (*f->callbacks->cilen)(f); + if( cilen > peer_mru[f->unit] - (int)HEADERLEN ) { + cilen = peer_mru[f->unit] - HEADERLEN; + } + if (f->callbacks->addci) { + (*f->callbacks->addci)(f, outp, &cilen); + } + } else { + cilen = 0; + } + + /* send the request to our peer */ + fsm_sdata(f, CONFREQ, f->reqid, outp, cilen); + + /* start the retransmit timer */ + --f->retransmits; + TIMEOUT(fsm_timeout, f, f->timeouttime); + + FSMDEBUG(LOG_INFO, ("%s: sending Configure-Request, id %d\n", + PROTO_NAME(f), f->reqid)); +} + + +/* + * fsm_sdata - Send some data. + * + * Used for all packets sent to our peer by this module. + */ +void +fsm_sdata( fsm *f, u_char code, u_char id, u_char *data, int datalen) +{ + u_char *outp; + int outlen; + + /* Adjust length to be smaller than MTU */ + outp = outpacket_buf[f->unit]; + if (datalen > peer_mru[f->unit] - (int)HEADERLEN) { + datalen = peer_mru[f->unit] - HEADERLEN; + } + if (datalen && data != outp + PPP_HDRLEN + HEADERLEN) { + BCOPY(data, outp + PPP_HDRLEN + HEADERLEN, datalen); + } + outlen = datalen + HEADERLEN; + MAKEHEADER(outp, f->protocol); + PUTCHAR(code, outp); + PUTCHAR(id, outp); + PUTSHORT(outlen, outp); + pppWrite(f->unit, outpacket_buf[f->unit], outlen + PPP_HDRLEN); + FSMDEBUG(LOG_INFO, ("fsm_sdata(%s): Sent code %d,%d,%d.\n", + PROTO_NAME(f), code, id, outlen)); +} + +#endif /* PPP_SUPPORT */ diff --git a/features/unsupported/net/lwip/lwip/netif/ppp/fsm.h b/features/unsupported/net/lwip/lwip/netif/ppp/fsm.h new file mode 100644 index 00000000000..8d41b5f511c --- /dev/null +++ b/features/unsupported/net/lwip/lwip/netif/ppp/fsm.h @@ -0,0 +1,157 @@ +/***************************************************************************** +* fsm.h - Network Control Protocol Finite State Machine header file. +* +* Copyright (c) 2003 by Marc Boucher, Services Informatiques (MBSI) inc. +* Copyright (c) 1997 Global Election Systems Inc. +* +* The authors hereby grant permission to use, copy, modify, distribute, +* and license this software and its documentation for any purpose, provided +* that existing copyright notices are retained in all copies and that this +* notice and the following disclaimer are included verbatim in any +* distributions. No written agreement, license, or royalty fee is required +* for any of the authorized uses. +* +* THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS *AS IS* AND ANY EXPRESS OR +* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +* IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT +* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +****************************************************************************** +* REVISION HISTORY +* +* 03-01-01 Marc Boucher +* Ported to lwIP. +* 97-11-05 Guy Lancaster , Global Election Systems Inc. +* Original based on BSD code. +*****************************************************************************/ +/* + * fsm.h - {Link, IP} Control Protocol Finite State Machine definitions. + * + * Copyright (c) 1989 Carnegie Mellon University. + * All rights reserved. + * + * Redistribution and use in source and binary forms are permitted + * provided that the above copyright notice and this paragraph are + * duplicated in all such forms and that any documentation, + * advertising materials, and other materials related to such + * distribution and use acknowledge that the software was developed + * by Carnegie Mellon University. The name of the + * University may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED + * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. + * + * $Id: fsm.h,v 1.5 2009/12/31 17:08:08 goldsimon Exp $ + */ + +#ifndef FSM_H +#define FSM_H + +/* + * LCP Packet header = Code, id, length. + */ +#define HEADERLEN (sizeof (u_char) + sizeof (u_char) + sizeof (u_short)) + + +/* + * CP (LCP, IPCP, etc.) codes. + */ +#define CONFREQ 1 /* Configuration Request */ +#define CONFACK 2 /* Configuration Ack */ +#define CONFNAK 3 /* Configuration Nak */ +#define CONFREJ 4 /* Configuration Reject */ +#define TERMREQ 5 /* Termination Request */ +#define TERMACK 6 /* Termination Ack */ +#define CODEREJ 7 /* Code Reject */ + + +/* + * Each FSM is described by an fsm structure and fsm callbacks. + */ +typedef struct fsm { + int unit; /* Interface unit number */ + u_short protocol; /* Data Link Layer Protocol field value */ + int state; /* State */ + int flags; /* Contains option bits */ + u_char id; /* Current id */ + u_char reqid; /* Current request id */ + u_char seen_ack; /* Have received valid Ack/Nak/Rej to Req */ + int timeouttime; /* Timeout time in milliseconds */ + int maxconfreqtransmits; /* Maximum Configure-Request transmissions */ + int retransmits; /* Number of retransmissions left */ + int maxtermtransmits; /* Maximum Terminate-Request transmissions */ + int nakloops; /* Number of nak loops since last ack */ + int maxnakloops; /* Maximum number of nak loops tolerated */ + struct fsm_callbacks* callbacks; /* Callback routines */ + char* term_reason; /* Reason for closing protocol */ + int term_reason_len; /* Length of term_reason */ +} fsm; + + +typedef struct fsm_callbacks { + void (*resetci)(fsm*); /* Reset our Configuration Information */ + int (*cilen)(fsm*); /* Length of our Configuration Information */ + void (*addci)(fsm*, u_char*, int*); /* Add our Configuration Information */ + int (*ackci)(fsm*, u_char*, int); /* ACK our Configuration Information */ + int (*nakci)(fsm*, u_char*, int); /* NAK our Configuration Information */ + int (*rejci)(fsm*, u_char*, int); /* Reject our Configuration Information */ + int (*reqci)(fsm*, u_char*, int*, int); /* Request peer's Configuration Information */ + void (*up)(fsm*); /* Called when fsm reaches LS_OPENED state */ + void (*down)(fsm*); /* Called when fsm leaves LS_OPENED state */ + void (*starting)(fsm*); /* Called when we want the lower layer */ + void (*finished)(fsm*); /* Called when we don't want the lower layer */ + void (*protreject)(int); /* Called when Protocol-Reject received */ + void (*retransmit)(fsm*); /* Retransmission is necessary */ + int (*extcode)(fsm*, int, u_char, u_char*, int); /* Called when unknown code received */ + char *proto_name; /* String name for protocol (for messages) */ +} fsm_callbacks; + + +/* + * Link states. + */ +#define LS_INITIAL 0 /* Down, hasn't been opened */ +#define LS_STARTING 1 /* Down, been opened */ +#define LS_CLOSED 2 /* Up, hasn't been opened */ +#define LS_STOPPED 3 /* Open, waiting for down event */ +#define LS_CLOSING 4 /* Terminating the connection, not open */ +#define LS_STOPPING 5 /* Terminating, but open */ +#define LS_REQSENT 6 /* We've sent a Config Request */ +#define LS_ACKRCVD 7 /* We've received a Config Ack */ +#define LS_ACKSENT 8 /* We've sent a Config Ack */ +#define LS_OPENED 9 /* Connection available */ + +/* + * Flags - indicate options controlling FSM operation + */ +#define OPT_PASSIVE 1 /* Don't die if we don't get a response */ +#define OPT_RESTART 2 /* Treat 2nd OPEN as DOWN, UP */ +#define OPT_SILENT 4 /* Wait for peer to speak first */ + + +/* + * Prototypes + */ +void fsm_init (fsm*); +void fsm_lowerup (fsm*); +void fsm_lowerdown (fsm*); +void fsm_open (fsm*); +void fsm_close (fsm*, char*); +void fsm_input (fsm*, u_char*, int); +void fsm_protreject (fsm*); +void fsm_sdata (fsm*, u_char, u_char, u_char*, int); + + +/* + * Variables + */ +extern int peer_mru[]; /* currently negotiated peer MRU (per unit) */ + +#endif /* FSM_H */ diff --git a/features/unsupported/net/lwip/lwip/netif/ppp/ipcp.c b/features/unsupported/net/lwip/lwip/netif/ppp/ipcp.c new file mode 100644 index 00000000000..655f949dad8 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/netif/ppp/ipcp.c @@ -0,0 +1,1415 @@ +/** In contrast to pppd 2.3.1, DNS support has been added, proxy-ARP and + dial-on-demand has been stripped. */ +/***************************************************************************** +* ipcp.c - Network PPP IP Control Protocol program file. +* +* Copyright (c) 2003 by Marc Boucher, Services Informatiques (MBSI) inc. +* portions Copyright (c) 1997 by Global Election Systems Inc. +* +* The authors hereby grant permission to use, copy, modify, distribute, +* and license this software and its documentation for any purpose, provided +* that existing copyright notices are retained in all copies and that this +* notice and the following disclaimer are included verbatim in any +* distributions. No written agreement, license, or royalty fee is required +* for any of the authorized uses. +* +* THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS *AS IS* AND ANY EXPRESS OR +* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +* IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT +* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +****************************************************************************** +* REVISION HISTORY +* +* 03-01-01 Marc Boucher +* Ported to lwIP. +* 97-12-08 Guy Lancaster , Global Election Systems Inc. +* Original. +*****************************************************************************/ +/* + * ipcp.c - PPP IP Control Protocol. + * + * Copyright (c) 1989 Carnegie Mellon University. + * All rights reserved. + * + * Redistribution and use in source and binary forms are permitted + * provided that the above copyright notice and this paragraph are + * duplicated in all such forms and that any documentation, + * advertising materials, and other materials related to such + * distribution and use acknowledge that the software was developed + * by Carnegie Mellon University. The name of the + * University may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED + * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. + */ + +#include "lwip/opt.h" + +#if PPP_SUPPORT /* don't build if not configured for use in lwipopts.h */ + +#include "ppp.h" +#include "pppdebug.h" + +#include "auth.h" +#include "fsm.h" +#include "vj.h" +#include "ipcp.h" + +#include "lwip/inet.h" + +#include + +/* #define OLD_CI_ADDRS 1 */ /* Support deprecated address negotiation. */ + +/* global vars */ +ipcp_options ipcp_wantoptions[NUM_PPP]; /* Options that we want to request */ +ipcp_options ipcp_gotoptions[NUM_PPP]; /* Options that peer ack'd */ +ipcp_options ipcp_allowoptions[NUM_PPP]; /* Options we allow peer to request */ +ipcp_options ipcp_hisoptions[NUM_PPP]; /* Options that we ack'd */ + +/* local vars */ +static int default_route_set[NUM_PPP]; /* Have set up a default route */ +static int cis_received[NUM_PPP]; /* # Conf-Reqs received */ + + +/* + * Callbacks for fsm code. (CI = Configuration Information) + */ +static void ipcp_resetci (fsm *); /* Reset our CI */ +static int ipcp_cilen (fsm *); /* Return length of our CI */ +static void ipcp_addci (fsm *, u_char *, int *); /* Add our CI */ +static int ipcp_ackci (fsm *, u_char *, int); /* Peer ack'd our CI */ +static int ipcp_nakci (fsm *, u_char *, int); /* Peer nak'd our CI */ +static int ipcp_rejci (fsm *, u_char *, int); /* Peer rej'd our CI */ +static int ipcp_reqci (fsm *, u_char *, int *, int); /* Rcv CI */ +static void ipcp_up (fsm *); /* We're UP */ +static void ipcp_down (fsm *); /* We're DOWN */ +#if PPP_ADDITIONAL_CALLBACKS +static void ipcp_script (fsm *, char *); /* Run an up/down script */ +#endif +static void ipcp_finished (fsm *); /* Don't need lower layer */ + + +fsm ipcp_fsm[NUM_PPP]; /* IPCP fsm structure */ + + +static fsm_callbacks ipcp_callbacks = { /* IPCP callback routines */ + ipcp_resetci, /* Reset our Configuration Information */ + ipcp_cilen, /* Length of our Configuration Information */ + ipcp_addci, /* Add our Configuration Information */ + ipcp_ackci, /* ACK our Configuration Information */ + ipcp_nakci, /* NAK our Configuration Information */ + ipcp_rejci, /* Reject our Configuration Information */ + ipcp_reqci, /* Request peer's Configuration Information */ + ipcp_up, /* Called when fsm reaches LS_OPENED state */ + ipcp_down, /* Called when fsm leaves LS_OPENED state */ + NULL, /* Called when we want the lower layer up */ + ipcp_finished, /* Called when we want the lower layer down */ + NULL, /* Called when Protocol-Reject received */ + NULL, /* Retransmission is necessary */ + NULL, /* Called to handle protocol-specific codes */ + "IPCP" /* String name of protocol */ +}; + +/* + * Protocol entry points from main code. + */ +static void ipcp_init (int); +static void ipcp_open (int); +static void ipcp_close (int, char *); +static void ipcp_lowerup (int); +static void ipcp_lowerdown (int); +static void ipcp_input (int, u_char *, int); +static void ipcp_protrej (int); + + +struct protent ipcp_protent = { + PPP_IPCP, + ipcp_init, + ipcp_input, + ipcp_protrej, + ipcp_lowerup, + ipcp_lowerdown, + ipcp_open, + ipcp_close, +#if PPP_ADDITIONAL_CALLBACKS + ipcp_printpkt, + NULL, +#endif /* PPP_ADDITIONAL_CALLBACKS */ + 1, + "IPCP", +#if PPP_ADDITIONAL_CALLBACKS + ip_check_options, + NULL, + ip_active_pkt +#endif /* PPP_ADDITIONAL_CALLBACKS */ +}; + +static void ipcp_clear_addrs (int); + +/* + * Lengths of configuration options. + */ +#define CILEN_VOID 2 +#define CILEN_COMPRESS 4 /* min length for compression protocol opt. */ +#define CILEN_VJ 6 /* length for RFC1332 Van-Jacobson opt. */ +#define CILEN_ADDR 6 /* new-style single address option */ +#define CILEN_ADDRS 10 /* old-style dual address option */ + + +#define CODENAME(x) ((x) == CONFACK ? "ACK" : \ + (x) == CONFNAK ? "NAK" : "REJ") + + +/* + * ipcp_init - Initialize IPCP. + */ +static void +ipcp_init(int unit) +{ + fsm *f = &ipcp_fsm[unit]; + ipcp_options *wo = &ipcp_wantoptions[unit]; + ipcp_options *ao = &ipcp_allowoptions[unit]; + + f->unit = unit; + f->protocol = PPP_IPCP; + f->callbacks = &ipcp_callbacks; + fsm_init(&ipcp_fsm[unit]); + + memset(wo, 0, sizeof(*wo)); + memset(ao, 0, sizeof(*ao)); + + wo->neg_addr = 1; + wo->ouraddr = 0; +#if VJ_SUPPORT + wo->neg_vj = 1; +#else /* VJ_SUPPORT */ + wo->neg_vj = 0; +#endif /* VJ_SUPPORT */ + wo->vj_protocol = IPCP_VJ_COMP; + wo->maxslotindex = MAX_SLOTS - 1; + wo->cflag = 0; + wo->default_route = 1; + + ao->neg_addr = 1; +#if VJ_SUPPORT + ao->neg_vj = 1; +#else /* VJ_SUPPORT */ + ao->neg_vj = 0; +#endif /* VJ_SUPPORT */ + ao->maxslotindex = MAX_SLOTS - 1; + ao->cflag = 1; + ao->default_route = 1; +} + + +/* + * ipcp_open - IPCP is allowed to come up. + */ +static void +ipcp_open(int unit) +{ + fsm_open(&ipcp_fsm[unit]); +} + + +/* + * ipcp_close - Take IPCP down. + */ +static void +ipcp_close(int unit, char *reason) +{ + fsm_close(&ipcp_fsm[unit], reason); +} + + +/* + * ipcp_lowerup - The lower layer is up. + */ +static void +ipcp_lowerup(int unit) +{ + fsm_lowerup(&ipcp_fsm[unit]); +} + + +/* + * ipcp_lowerdown - The lower layer is down. + */ +static void +ipcp_lowerdown(int unit) +{ + fsm_lowerdown(&ipcp_fsm[unit]); +} + + +/* + * ipcp_input - Input IPCP packet. + */ +static void +ipcp_input(int unit, u_char *p, int len) +{ + fsm_input(&ipcp_fsm[unit], p, len); +} + + +/* + * ipcp_protrej - A Protocol-Reject was received for IPCP. + * + * Pretend the lower layer went down, so we shut up. + */ +static void +ipcp_protrej(int unit) +{ + fsm_lowerdown(&ipcp_fsm[unit]); +} + + +/* + * ipcp_resetci - Reset our CI. + */ +static void +ipcp_resetci(fsm *f) +{ + ipcp_options *wo = &ipcp_wantoptions[f->unit]; + + wo->req_addr = wo->neg_addr && ipcp_allowoptions[f->unit].neg_addr; + if (wo->ouraddr == 0) { + wo->accept_local = 1; + } + if (wo->hisaddr == 0) { + wo->accept_remote = 1; + } + /* Request DNS addresses from the peer */ + wo->req_dns1 = ppp_settings.usepeerdns; + wo->req_dns2 = ppp_settings.usepeerdns; + ipcp_gotoptions[f->unit] = *wo; + cis_received[f->unit] = 0; +} + + +/* + * ipcp_cilen - Return length of our CI. + */ +static int +ipcp_cilen(fsm *f) +{ + ipcp_options *go = &ipcp_gotoptions[f->unit]; + ipcp_options *wo = &ipcp_wantoptions[f->unit]; + ipcp_options *ho = &ipcp_hisoptions[f->unit]; + +#define LENCIVJ(neg, old) (neg ? (old? CILEN_COMPRESS : CILEN_VJ) : 0) +#define LENCIADDR(neg, old) (neg ? (old? CILEN_ADDRS : CILEN_ADDR) : 0) +#define LENCIDNS(neg) (neg ? (CILEN_ADDR) : 0) + + /* + * First see if we want to change our options to the old + * forms because we have received old forms from the peer. + */ + if (wo->neg_addr && !go->neg_addr && !go->old_addrs) { + /* use the old style of address negotiation */ + go->neg_addr = 1; + go->old_addrs = 1; + } + if (wo->neg_vj && !go->neg_vj && !go->old_vj) { + /* try an older style of VJ negotiation */ + if (cis_received[f->unit] == 0) { + /* keep trying the new style until we see some CI from the peer */ + go->neg_vj = 1; + } else { + /* use the old style only if the peer did */ + if (ho->neg_vj && ho->old_vj) { + go->neg_vj = 1; + go->old_vj = 1; + go->vj_protocol = ho->vj_protocol; + } + } + } + + return (LENCIADDR(go->neg_addr, go->old_addrs) + + LENCIVJ(go->neg_vj, go->old_vj) + + LENCIDNS(go->req_dns1) + + LENCIDNS(go->req_dns2)); +} + + +/* + * ipcp_addci - Add our desired CIs to a packet. + */ +static void +ipcp_addci(fsm *f, u_char *ucp, int *lenp) +{ + ipcp_options *go = &ipcp_gotoptions[f->unit]; + int len = *lenp; + +#define ADDCIVJ(opt, neg, val, old, maxslotindex, cflag) \ + if (neg) { \ + int vjlen = old? CILEN_COMPRESS : CILEN_VJ; \ + if (len >= vjlen) { \ + PUTCHAR(opt, ucp); \ + PUTCHAR(vjlen, ucp); \ + PUTSHORT(val, ucp); \ + if (!old) { \ + PUTCHAR(maxslotindex, ucp); \ + PUTCHAR(cflag, ucp); \ + } \ + len -= vjlen; \ + } else { \ + neg = 0; \ + } \ + } + +#define ADDCIADDR(opt, neg, old, val1, val2) \ + if (neg) { \ + int addrlen = (old? CILEN_ADDRS: CILEN_ADDR); \ + if (len >= addrlen) { \ + u32_t l; \ + PUTCHAR(opt, ucp); \ + PUTCHAR(addrlen, ucp); \ + l = ntohl(val1); \ + PUTLONG(l, ucp); \ + if (old) { \ + l = ntohl(val2); \ + PUTLONG(l, ucp); \ + } \ + len -= addrlen; \ + } else { \ + neg = 0; \ + } \ + } + +#define ADDCIDNS(opt, neg, addr) \ + if (neg) { \ + if (len >= CILEN_ADDR) { \ + u32_t l; \ + PUTCHAR(opt, ucp); \ + PUTCHAR(CILEN_ADDR, ucp); \ + l = ntohl(addr); \ + PUTLONG(l, ucp); \ + len -= CILEN_ADDR; \ + } else { \ + neg = 0; \ + } \ + } + + ADDCIADDR((go->old_addrs? CI_ADDRS: CI_ADDR), go->neg_addr, + go->old_addrs, go->ouraddr, go->hisaddr); + + ADDCIVJ(CI_COMPRESSTYPE, go->neg_vj, go->vj_protocol, go->old_vj, + go->maxslotindex, go->cflag); + + ADDCIDNS(CI_MS_DNS1, go->req_dns1, go->dnsaddr[0]); + + ADDCIDNS(CI_MS_DNS2, go->req_dns2, go->dnsaddr[1]); + + *lenp -= len; +} + + +/* + * ipcp_ackci - Ack our CIs. + * + * Returns: + * 0 - Ack was bad. + * 1 - Ack was good. + */ +static int +ipcp_ackci(fsm *f, u_char *p, int len) +{ + ipcp_options *go = &ipcp_gotoptions[f->unit]; + u_short cilen, citype, cishort; + u32_t cilong; + u_char cimaxslotindex, cicflag; + + /* + * CIs must be in exactly the same order that we sent... + * Check packet length and CI length at each step. + * If we find any deviations, then this packet is bad. + */ + +#define ACKCIVJ(opt, neg, val, old, maxslotindex, cflag) \ + if (neg) { \ + int vjlen = old? CILEN_COMPRESS : CILEN_VJ; \ + if ((len -= vjlen) < 0) { \ + goto bad; \ + } \ + GETCHAR(citype, p); \ + GETCHAR(cilen, p); \ + if (cilen != vjlen || \ + citype != opt) { \ + goto bad; \ + } \ + GETSHORT(cishort, p); \ + if (cishort != val) { \ + goto bad; \ + } \ + if (!old) { \ + GETCHAR(cimaxslotindex, p); \ + if (cimaxslotindex != maxslotindex) { \ + goto bad; \ + } \ + GETCHAR(cicflag, p); \ + if (cicflag != cflag) { \ + goto bad; \ + } \ + } \ + } + +#define ACKCIADDR(opt, neg, old, val1, val2) \ + if (neg) { \ + int addrlen = (old? CILEN_ADDRS: CILEN_ADDR); \ + u32_t l; \ + if ((len -= addrlen) < 0) { \ + goto bad; \ + } \ + GETCHAR(citype, p); \ + GETCHAR(cilen, p); \ + if (cilen != addrlen || \ + citype != opt) { \ + goto bad; \ + } \ + GETLONG(l, p); \ + cilong = htonl(l); \ + if (val1 != cilong) { \ + goto bad; \ + } \ + if (old) { \ + GETLONG(l, p); \ + cilong = htonl(l); \ + if (val2 != cilong) { \ + goto bad; \ + } \ + } \ + } + +#define ACKCIDNS(opt, neg, addr) \ + if (neg) { \ + u32_t l; \ + if ((len -= CILEN_ADDR) < 0) { \ + goto bad; \ + } \ + GETCHAR(citype, p); \ + GETCHAR(cilen, p); \ + if (cilen != CILEN_ADDR || \ + citype != opt) { \ + goto bad; \ + } \ + GETLONG(l, p); \ + cilong = htonl(l); \ + if (addr != cilong) { \ + goto bad; \ + } \ + } + + ACKCIADDR((go->old_addrs? CI_ADDRS: CI_ADDR), go->neg_addr, + go->old_addrs, go->ouraddr, go->hisaddr); + + ACKCIVJ(CI_COMPRESSTYPE, go->neg_vj, go->vj_protocol, go->old_vj, + go->maxslotindex, go->cflag); + + ACKCIDNS(CI_MS_DNS1, go->req_dns1, go->dnsaddr[0]); + + ACKCIDNS(CI_MS_DNS2, go->req_dns2, go->dnsaddr[1]); + + /* + * If there are any remaining CIs, then this packet is bad. + */ + if (len != 0) { + goto bad; + } + return (1); + +bad: + IPCPDEBUG(LOG_INFO, ("ipcp_ackci: received bad Ack!\n")); + return (0); +} + +/* + * ipcp_nakci - Peer has sent a NAK for some of our CIs. + * This should not modify any state if the Nak is bad + * or if IPCP is in the LS_OPENED state. + * + * Returns: + * 0 - Nak was bad. + * 1 - Nak was good. + */ +static int +ipcp_nakci(fsm *f, u_char *p, int len) +{ + ipcp_options *go = &ipcp_gotoptions[f->unit]; + u_char cimaxslotindex, cicflag; + u_char citype, cilen, *next; + u_short cishort; + u32_t ciaddr1, ciaddr2, l, cidnsaddr; + ipcp_options no; /* options we've seen Naks for */ + ipcp_options try; /* options to request next time */ + + BZERO(&no, sizeof(no)); + try = *go; + + /* + * Any Nak'd CIs must be in exactly the same order that we sent. + * Check packet length and CI length at each step. + * If we find any deviations, then this packet is bad. + */ +#define NAKCIADDR(opt, neg, old, code) \ + if (go->neg && \ + len >= (cilen = (old? CILEN_ADDRS: CILEN_ADDR)) && \ + p[1] == cilen && \ + p[0] == opt) { \ + len -= cilen; \ + INCPTR(2, p); \ + GETLONG(l, p); \ + ciaddr1 = htonl(l); \ + if (old) { \ + GETLONG(l, p); \ + ciaddr2 = htonl(l); \ + no.old_addrs = 1; \ + } else { \ + ciaddr2 = 0; \ + } \ + no.neg = 1; \ + code \ + } + +#define NAKCIVJ(opt, neg, code) \ + if (go->neg && \ + ((cilen = p[1]) == CILEN_COMPRESS || cilen == CILEN_VJ) && \ + len >= cilen && \ + p[0] == opt) { \ + len -= cilen; \ + INCPTR(2, p); \ + GETSHORT(cishort, p); \ + no.neg = 1; \ + code \ + } + +#define NAKCIDNS(opt, neg, code) \ + if (go->neg && \ + ((cilen = p[1]) == CILEN_ADDR) && \ + len >= cilen && \ + p[0] == opt) { \ + len -= cilen; \ + INCPTR(2, p); \ + GETLONG(l, p); \ + cidnsaddr = htonl(l); \ + no.neg = 1; \ + code \ + } + + /* + * Accept the peer's idea of {our,his} address, if different + * from our idea, only if the accept_{local,remote} flag is set. + */ + NAKCIADDR((go->old_addrs? CI_ADDRS: CI_ADDR), neg_addr, go->old_addrs, + if (go->accept_local && ciaddr1) { /* Do we know our address? */ + try.ouraddr = ciaddr1; + IPCPDEBUG(LOG_INFO, ("local IP address %s\n", + inet_ntoa(ciaddr1))); + } + if (go->accept_remote && ciaddr2) { /* Does he know his? */ + try.hisaddr = ciaddr2; + IPCPDEBUG(LOG_INFO, ("remote IP address %s\n", + inet_ntoa(ciaddr2))); + } + ); + + /* + * Accept the peer's value of maxslotindex provided that it + * is less than what we asked for. Turn off slot-ID compression + * if the peer wants. Send old-style compress-type option if + * the peer wants. + */ + NAKCIVJ(CI_COMPRESSTYPE, neg_vj, + if (cilen == CILEN_VJ) { + GETCHAR(cimaxslotindex, p); + GETCHAR(cicflag, p); + if (cishort == IPCP_VJ_COMP) { + try.old_vj = 0; + if (cimaxslotindex < go->maxslotindex) { + try.maxslotindex = cimaxslotindex; + } + if (!cicflag) { + try.cflag = 0; + } + } else { + try.neg_vj = 0; + } + } else { + if (cishort == IPCP_VJ_COMP || cishort == IPCP_VJ_COMP_OLD) { + try.old_vj = 1; + try.vj_protocol = cishort; + } else { + try.neg_vj = 0; + } + } + ); + + NAKCIDNS(CI_MS_DNS1, req_dns1, + try.dnsaddr[0] = cidnsaddr; + IPCPDEBUG(LOG_INFO, ("primary DNS address %s\n", inet_ntoa(cidnsaddr))); + ); + + NAKCIDNS(CI_MS_DNS2, req_dns2, + try.dnsaddr[1] = cidnsaddr; + IPCPDEBUG(LOG_INFO, ("secondary DNS address %s\n", inet_ntoa(cidnsaddr))); + ); + + /* + * There may be remaining CIs, if the peer is requesting negotiation + * on an option that we didn't include in our request packet. + * If they want to negotiate about IP addresses, we comply. + * If they want us to ask for compression, we refuse. + */ + while (len > CILEN_VOID) { + GETCHAR(citype, p); + GETCHAR(cilen, p); + if( (len -= cilen) < 0 ) { + goto bad; + } + next = p + cilen - 2; + + switch (citype) { + case CI_COMPRESSTYPE: + if (go->neg_vj || no.neg_vj || + (cilen != CILEN_VJ && cilen != CILEN_COMPRESS)) { + goto bad; + } + no.neg_vj = 1; + break; + case CI_ADDRS: + if ((go->neg_addr && go->old_addrs) || no.old_addrs + || cilen != CILEN_ADDRS) { + goto bad; + } + try.neg_addr = 1; + try.old_addrs = 1; + GETLONG(l, p); + ciaddr1 = htonl(l); + if (ciaddr1 && go->accept_local) { + try.ouraddr = ciaddr1; + } + GETLONG(l, p); + ciaddr2 = htonl(l); + if (ciaddr2 && go->accept_remote) { + try.hisaddr = ciaddr2; + } + no.old_addrs = 1; + break; + case CI_ADDR: + if (go->neg_addr || no.neg_addr || cilen != CILEN_ADDR) { + goto bad; + } + try.old_addrs = 0; + GETLONG(l, p); + ciaddr1 = htonl(l); + if (ciaddr1 && go->accept_local) { + try.ouraddr = ciaddr1; + } + if (try.ouraddr != 0) { + try.neg_addr = 1; + } + no.neg_addr = 1; + break; + } + p = next; + } + + /* If there is still anything left, this packet is bad. */ + if (len != 0) { + goto bad; + } + + /* + * OK, the Nak is good. Now we can update state. + */ + if (f->state != LS_OPENED) { + *go = try; + } + + return 1; + +bad: + IPCPDEBUG(LOG_INFO, ("ipcp_nakci: received bad Nak!\n")); + return 0; +} + + +/* + * ipcp_rejci - Reject some of our CIs. + */ +static int +ipcp_rejci(fsm *f, u_char *p, int len) +{ + ipcp_options *go = &ipcp_gotoptions[f->unit]; + u_char cimaxslotindex, ciflag, cilen; + u_short cishort; + u32_t cilong; + ipcp_options try; /* options to request next time */ + + try = *go; + /* + * Any Rejected CIs must be in exactly the same order that we sent. + * Check packet length and CI length at each step. + * If we find any deviations, then this packet is bad. + */ +#define REJCIADDR(opt, neg, old, val1, val2) \ + if (go->neg && \ + len >= (cilen = old? CILEN_ADDRS: CILEN_ADDR) && \ + p[1] == cilen && \ + p[0] == opt) { \ + u32_t l; \ + len -= cilen; \ + INCPTR(2, p); \ + GETLONG(l, p); \ + cilong = htonl(l); \ + /* Check rejected value. */ \ + if (cilong != val1) { \ + goto bad; \ + } \ + if (old) { \ + GETLONG(l, p); \ + cilong = htonl(l); \ + /* Check rejected value. */ \ + if (cilong != val2) { \ + goto bad; \ + } \ + } \ + try.neg = 0; \ + } + +#define REJCIVJ(opt, neg, val, old, maxslot, cflag) \ + if (go->neg && \ + p[1] == (old? CILEN_COMPRESS : CILEN_VJ) && \ + len >= p[1] && \ + p[0] == opt) { \ + len -= p[1]; \ + INCPTR(2, p); \ + GETSHORT(cishort, p); \ + /* Check rejected value. */ \ + if (cishort != val) { \ + goto bad; \ + } \ + if (!old) { \ + GETCHAR(cimaxslotindex, p); \ + if (cimaxslotindex != maxslot) { \ + goto bad; \ + } \ + GETCHAR(ciflag, p); \ + if (ciflag != cflag) { \ + goto bad; \ + } \ + } \ + try.neg = 0; \ + } + +#define REJCIDNS(opt, neg, dnsaddr) \ + if (go->neg && \ + ((cilen = p[1]) == CILEN_ADDR) && \ + len >= cilen && \ + p[0] == opt) { \ + u32_t l; \ + len -= cilen; \ + INCPTR(2, p); \ + GETLONG(l, p); \ + cilong = htonl(l); \ + /* Check rejected value. */ \ + if (cilong != dnsaddr) { \ + goto bad; \ + } \ + try.neg = 0; \ + } + + REJCIADDR((go->old_addrs? CI_ADDRS: CI_ADDR), neg_addr, + go->old_addrs, go->ouraddr, go->hisaddr); + + REJCIVJ(CI_COMPRESSTYPE, neg_vj, go->vj_protocol, go->old_vj, + go->maxslotindex, go->cflag); + + REJCIDNS(CI_MS_DNS1, req_dns1, go->dnsaddr[0]); + + REJCIDNS(CI_MS_DNS2, req_dns2, go->dnsaddr[1]); + + /* + * If there are any remaining CIs, then this packet is bad. + */ + if (len != 0) { + goto bad; + } + /* + * Now we can update state. + */ + if (f->state != LS_OPENED) { + *go = try; + } + return 1; + +bad: + IPCPDEBUG(LOG_INFO, ("ipcp_rejci: received bad Reject!\n")); + return 0; +} + + +/* + * ipcp_reqci - Check the peer's requested CIs and send appropriate response. + * + * Returns: CONFACK, CONFNAK or CONFREJ and input packet modified + * appropriately. If reject_if_disagree is non-zero, doesn't return + * CONFNAK; returns CONFREJ if it can't return CONFACK. + */ +static int +ipcp_reqci(fsm *f, u_char *inp/* Requested CIs */,int *len/* Length of requested CIs */,int reject_if_disagree) +{ + ipcp_options *wo = &ipcp_wantoptions[f->unit]; + ipcp_options *ho = &ipcp_hisoptions[f->unit]; + ipcp_options *ao = &ipcp_allowoptions[f->unit]; +#ifdef OLD_CI_ADDRS + ipcp_options *go = &ipcp_gotoptions[f->unit]; +#endif + u_char *cip, *next; /* Pointer to current and next CIs */ + u_short cilen, citype; /* Parsed len, type */ + u_short cishort; /* Parsed short value */ + u32_t tl, ciaddr1; /* Parsed address values */ +#ifdef OLD_CI_ADDRS + u32_t ciaddr2; /* Parsed address values */ +#endif + int rc = CONFACK; /* Final packet return code */ + int orc; /* Individual option return code */ + u_char *p; /* Pointer to next char to parse */ + u_char *ucp = inp; /* Pointer to current output char */ + int l = *len; /* Length left */ + u_char maxslotindex, cflag; + int d; + + cis_received[f->unit] = 1; + + /* + * Reset all his options. + */ + BZERO(ho, sizeof(*ho)); + + /* + * Process all his options. + */ + next = inp; + while (l) { + orc = CONFACK; /* Assume success */ + cip = p = next; /* Remember begining of CI */ + if (l < 2 || /* Not enough data for CI header or */ + p[1] < 2 || /* CI length too small or */ + p[1] > l) { /* CI length too big? */ + IPCPDEBUG(LOG_INFO, ("ipcp_reqci: bad CI length!\n")); + orc = CONFREJ; /* Reject bad CI */ + cilen = (u_short)l;/* Reject till end of packet */ + l = 0; /* Don't loop again */ + goto endswitch; + } + GETCHAR(citype, p); /* Parse CI type */ + GETCHAR(cilen, p); /* Parse CI length */ + l -= cilen; /* Adjust remaining length */ + next += cilen; /* Step to next CI */ + + switch (citype) { /* Check CI type */ +#ifdef OLD_CI_ADDRS /* Need to save space... */ + case CI_ADDRS: + IPCPDEBUG(LOG_INFO, ("ipcp_reqci: received ADDRS\n")); + if (!ao->neg_addr || + cilen != CILEN_ADDRS) { /* Check CI length */ + orc = CONFREJ; /* Reject CI */ + break; + } + + /* + * If he has no address, or if we both have his address but + * disagree about it, then NAK it with our idea. + * In particular, if we don't know his address, but he does, + * then accept it. + */ + GETLONG(tl, p); /* Parse source address (his) */ + ciaddr1 = htonl(tl); + IPCPDEBUG(LOG_INFO, ("his addr %s\n", inet_ntoa(ciaddr1))); + if (ciaddr1 != wo->hisaddr + && (ciaddr1 == 0 || !wo->accept_remote)) { + orc = CONFNAK; + if (!reject_if_disagree) { + DECPTR(sizeof(u32_t), p); + tl = ntohl(wo->hisaddr); + PUTLONG(tl, p); + } + } else if (ciaddr1 == 0 && wo->hisaddr == 0) { + /* + * If neither we nor he knows his address, reject the option. + */ + orc = CONFREJ; + wo->req_addr = 0; /* don't NAK with 0.0.0.0 later */ + break; + } + + /* + * If he doesn't know our address, or if we both have our address + * but disagree about it, then NAK it with our idea. + */ + GETLONG(tl, p); /* Parse desination address (ours) */ + ciaddr2 = htonl(tl); + IPCPDEBUG(LOG_INFO, ("our addr %s\n", inet_ntoa(ciaddr2))); + if (ciaddr2 != wo->ouraddr) { + if (ciaddr2 == 0 || !wo->accept_local) { + orc = CONFNAK; + if (!reject_if_disagree) { + DECPTR(sizeof(u32_t), p); + tl = ntohl(wo->ouraddr); + PUTLONG(tl, p); + } + } else { + go->ouraddr = ciaddr2; /* accept peer's idea */ + } + } + + ho->neg_addr = 1; + ho->old_addrs = 1; + ho->hisaddr = ciaddr1; + ho->ouraddr = ciaddr2; + break; +#endif + + case CI_ADDR: + if (!ao->neg_addr) { + IPCPDEBUG(LOG_INFO, ("ipcp_reqci: Reject ADDR not allowed\n")); + orc = CONFREJ; /* Reject CI */ + break; + } else if (cilen != CILEN_ADDR) { /* Check CI length */ + IPCPDEBUG(LOG_INFO, ("ipcp_reqci: Reject ADDR bad len\n")); + orc = CONFREJ; /* Reject CI */ + break; + } + + /* + * If he has no address, or if we both have his address but + * disagree about it, then NAK it with our idea. + * In particular, if we don't know his address, but he does, + * then accept it. + */ + GETLONG(tl, p); /* Parse source address (his) */ + ciaddr1 = htonl(tl); + if (ciaddr1 != wo->hisaddr + && (ciaddr1 == 0 || !wo->accept_remote)) { + orc = CONFNAK; + if (!reject_if_disagree) { + DECPTR(sizeof(u32_t), p); + tl = ntohl(wo->hisaddr); + PUTLONG(tl, p); + } + IPCPDEBUG(LOG_INFO, ("ipcp_reqci: Nak ADDR %s\n", inet_ntoa(ciaddr1))); + } else if (ciaddr1 == 0 && wo->hisaddr == 0) { + /* + * Don't ACK an address of 0.0.0.0 - reject it instead. + */ + IPCPDEBUG(LOG_INFO, ("ipcp_reqci: Reject ADDR %s\n", inet_ntoa(ciaddr1))); + orc = CONFREJ; + wo->req_addr = 0; /* don't NAK with 0.0.0.0 later */ + break; + } + + ho->neg_addr = 1; + ho->hisaddr = ciaddr1; + IPCPDEBUG(LOG_INFO, ("ipcp_reqci: ADDR %s\n", inet_ntoa(ciaddr1))); + break; + + case CI_MS_DNS1: + case CI_MS_DNS2: + /* Microsoft primary or secondary DNS request */ + d = citype == CI_MS_DNS2; + + /* If we do not have a DNS address then we cannot send it */ + if (ao->dnsaddr[d] == 0 || + cilen != CILEN_ADDR) { /* Check CI length */ + IPCPDEBUG(LOG_INFO, ("ipcp_reqci: Rejecting DNS%d Request\n", d+1)); + orc = CONFREJ; /* Reject CI */ + break; + } + GETLONG(tl, p); + if (htonl(tl) != ao->dnsaddr[d]) { + IPCPDEBUG(LOG_INFO, ("ipcp_reqci: Naking DNS%d Request %s\n", + d+1, inet_ntoa(tl))); + DECPTR(sizeof(u32_t), p); + tl = ntohl(ao->dnsaddr[d]); + PUTLONG(tl, p); + orc = CONFNAK; + } + IPCPDEBUG(LOG_INFO, ("ipcp_reqci: received DNS%d Request\n", d+1)); + break; + + case CI_MS_WINS1: + case CI_MS_WINS2: + /* Microsoft primary or secondary WINS request */ + d = citype == CI_MS_WINS2; + IPCPDEBUG(LOG_INFO, ("ipcp_reqci: received WINS%d Request\n", d+1)); + + /* If we do not have a DNS address then we cannot send it */ + if (ao->winsaddr[d] == 0 || + cilen != CILEN_ADDR) { /* Check CI length */ + orc = CONFREJ; /* Reject CI */ + break; + } + GETLONG(tl, p); + if (htonl(tl) != ao->winsaddr[d]) { + DECPTR(sizeof(u32_t), p); + tl = ntohl(ao->winsaddr[d]); + PUTLONG(tl, p); + orc = CONFNAK; + } + break; + + case CI_COMPRESSTYPE: + if (!ao->neg_vj) { + IPCPDEBUG(LOG_INFO, ("ipcp_reqci: Rejecting COMPRESSTYPE not allowed\n")); + orc = CONFREJ; + break; + } else if (cilen != CILEN_VJ && cilen != CILEN_COMPRESS) { + IPCPDEBUG(LOG_INFO, ("ipcp_reqci: Rejecting COMPRESSTYPE len=%d\n", cilen)); + orc = CONFREJ; + break; + } + GETSHORT(cishort, p); + + if (!(cishort == IPCP_VJ_COMP || + (cishort == IPCP_VJ_COMP_OLD && cilen == CILEN_COMPRESS))) { + IPCPDEBUG(LOG_INFO, ("ipcp_reqci: Rejecting COMPRESSTYPE %d\n", cishort)); + orc = CONFREJ; + break; + } + + ho->neg_vj = 1; + ho->vj_protocol = cishort; + if (cilen == CILEN_VJ) { + GETCHAR(maxslotindex, p); + if (maxslotindex > ao->maxslotindex) { + IPCPDEBUG(LOG_INFO, ("ipcp_reqci: Naking VJ max slot %d\n", maxslotindex)); + orc = CONFNAK; + if (!reject_if_disagree) { + DECPTR(1, p); + PUTCHAR(ao->maxslotindex, p); + } + } + GETCHAR(cflag, p); + if (cflag && !ao->cflag) { + IPCPDEBUG(LOG_INFO, ("ipcp_reqci: Naking VJ cflag %d\n", cflag)); + orc = CONFNAK; + if (!reject_if_disagree) { + DECPTR(1, p); + PUTCHAR(wo->cflag, p); + } + } + ho->maxslotindex = maxslotindex; + ho->cflag = cflag; + } else { + ho->old_vj = 1; + ho->maxslotindex = MAX_SLOTS - 1; + ho->cflag = 1; + } + IPCPDEBUG(LOG_INFO, ( + "ipcp_reqci: received COMPRESSTYPE p=%d old=%d maxslot=%d cflag=%d\n", + ho->vj_protocol, ho->old_vj, ho->maxslotindex, ho->cflag)); + break; + + default: + IPCPDEBUG(LOG_INFO, ("ipcp_reqci: Rejecting unknown CI type %d\n", citype)); + orc = CONFREJ; + break; + } + +endswitch: + if (orc == CONFACK && /* Good CI */ + rc != CONFACK) { /* but prior CI wasnt? */ + continue; /* Don't send this one */ + } + + if (orc == CONFNAK) { /* Nak this CI? */ + if (reject_if_disagree) { /* Getting fed up with sending NAKs? */ + IPCPDEBUG(LOG_INFO, ("ipcp_reqci: Rejecting too many naks\n")); + orc = CONFREJ; /* Get tough if so */ + } else { + if (rc == CONFREJ) { /* Rejecting prior CI? */ + continue; /* Don't send this one */ + } + if (rc == CONFACK) { /* Ack'd all prior CIs? */ + rc = CONFNAK; /* Not anymore... */ + ucp = inp; /* Backup */ + } + } + } + + if (orc == CONFREJ && /* Reject this CI */ + rc != CONFREJ) { /* but no prior ones? */ + rc = CONFREJ; + ucp = inp; /* Backup */ + } + + /* Need to move CI? */ + if (ucp != cip) { + BCOPY(cip, ucp, cilen); /* Move it */ + } + + /* Update output pointer */ + INCPTR(cilen, ucp); + } + + /* + * If we aren't rejecting this packet, and we want to negotiate + * their address, and they didn't send their address, then we + * send a NAK with a CI_ADDR option appended. We assume the + * input buffer is long enough that we can append the extra + * option safely. + */ + if (rc != CONFREJ && !ho->neg_addr && + wo->req_addr && !reject_if_disagree) { + IPCPDEBUG(LOG_INFO, ("ipcp_reqci: Requesting peer address\n")); + if (rc == CONFACK) { + rc = CONFNAK; + ucp = inp; /* reset pointer */ + wo->req_addr = 0; /* don't ask again */ + } + PUTCHAR(CI_ADDR, ucp); + PUTCHAR(CILEN_ADDR, ucp); + tl = ntohl(wo->hisaddr); + PUTLONG(tl, ucp); + } + + *len = (int)(ucp - inp); /* Compute output length */ + IPCPDEBUG(LOG_INFO, ("ipcp_reqci: returning Configure-%s\n", CODENAME(rc))); + return (rc); /* Return final code */ +} + + +#if 0 +/* + * ip_check_options - check that any IP-related options are OK, + * and assign appropriate defaults. + */ +static void +ip_check_options(u_long localAddr) +{ + ipcp_options *wo = &ipcp_wantoptions[0]; + + /* + * Load our default IP address but allow the remote host to give us + * a new address. + */ + if (wo->ouraddr == 0 && !ppp_settings.disable_defaultip) { + wo->accept_local = 1; /* don't insist on this default value */ + wo->ouraddr = htonl(localAddr); + } +} +#endif + + +/* + * ipcp_up - IPCP has come UP. + * + * Configure the IP network interface appropriately and bring it up. + */ +static void +ipcp_up(fsm *f) +{ + u32_t mask; + ipcp_options *ho = &ipcp_hisoptions[f->unit]; + ipcp_options *go = &ipcp_gotoptions[f->unit]; + ipcp_options *wo = &ipcp_wantoptions[f->unit]; + + np_up(f->unit, PPP_IP); + IPCPDEBUG(LOG_INFO, ("ipcp: up\n")); + + /* + * We must have a non-zero IP address for both ends of the link. + */ + if (!ho->neg_addr) { + ho->hisaddr = wo->hisaddr; + } + + if (ho->hisaddr == 0) { +#if 0 + IPCPDEBUG(LOG_ERR, ("Could not determine remote IP address\n")); + ipcp_close(f->unit, "Could not determine remote IP address"); + return; +#else //Kludge + ho->hisaddr = 0; //Set remote IP to 0.0.0.0, this is needed as most 3g providers do not advertise the remote IP to the user +#endif + } + if (go->ouraddr == 0) { + IPCPDEBUG(LOG_ERR, ("Could not determine local IP address\n")); + ipcp_close(f->unit, "Could not determine local IP address"); + return; + } + + if (ppp_settings.usepeerdns && (go->dnsaddr[0] || go->dnsaddr[1])) { + /*pppGotDNSAddrs(go->dnsaddr[0], go->dnsaddr[1]);*/ + } + + /* + * Check that the peer is allowed to use the IP address it wants. + */ + if (!auth_ip_addr(f->unit, ho->hisaddr)) { + IPCPDEBUG(LOG_ERR, ("Peer is not authorized to use remote address %s\n", + inet_ntoa(ho->hisaddr))); + ipcp_close(f->unit, "Unauthorized remote IP address"); + return; + } + + /* set tcp compression */ + sifvjcomp(f->unit, ho->neg_vj, ho->cflag, ho->maxslotindex); + + /* + * Set IP addresses and (if specified) netmask. + */ + mask = GetMask(go->ouraddr); + + if (!sifaddr(f->unit, go->ouraddr, ho->hisaddr, mask, go->dnsaddr[0], go->dnsaddr[1])) { + IPCPDEBUG(LOG_WARNING, ("sifaddr failed\n")); + ipcp_close(f->unit, "Interface configuration failed"); + return; + } + + /* bring the interface up for IP */ + if (!sifup(f->unit)) { + IPCPDEBUG(LOG_WARNING, ("sifup failed\n")); + ipcp_close(f->unit, "Interface configuration failed"); + return; + } + + sifnpmode(f->unit, PPP_IP, NPMODE_PASS); + + /* assign a default route through the interface if required */ + if (ipcp_wantoptions[f->unit].default_route) { + if (sifdefaultroute(f->unit, go->ouraddr, ho->hisaddr)) { + default_route_set[f->unit] = 1; + } + } + + IPCPDEBUG(LOG_NOTICE, ("local IP address %s\n", inet_ntoa(go->ouraddr))); + IPCPDEBUG(LOG_NOTICE, ("remote IP address %s\n", inet_ntoa(ho->hisaddr))); + if (go->dnsaddr[0]) { + IPCPDEBUG(LOG_NOTICE, ("primary DNS address %s\n", inet_ntoa(go->dnsaddr[0]))); + } + if (go->dnsaddr[1]) { + IPCPDEBUG(LOG_NOTICE, ("secondary DNS address %s\n", inet_ntoa(go->dnsaddr[1]))); + } +} + + +/* + * ipcp_down - IPCP has gone DOWN. + * + * Take the IP network interface down, clear its addresses + * and delete routes through it. + */ +static void +ipcp_down(fsm *f) +{ + IPCPDEBUG(LOG_INFO, ("ipcp: down\n")); + np_down(f->unit, PPP_IP); + sifvjcomp(f->unit, 0, 0, 0); + + sifdown(f->unit); + ipcp_clear_addrs(f->unit); +} + + +/* + * ipcp_clear_addrs() - clear the interface addresses, routes, etc. + */ +static void +ipcp_clear_addrs(int unit) +{ + u32_t ouraddr, hisaddr; + + ouraddr = ipcp_gotoptions[unit].ouraddr; + hisaddr = ipcp_hisoptions[unit].hisaddr; + if (default_route_set[unit]) { + cifdefaultroute(unit, ouraddr, hisaddr); + default_route_set[unit] = 0; + } + cifaddr(unit, ouraddr, hisaddr); +} + + +/* + * ipcp_finished - possibly shut down the lower layers. + */ +static void +ipcp_finished(fsm *f) +{ + np_finished(f->unit, PPP_IP); +} + +#if PPP_ADDITIONAL_CALLBACKS +static int +ipcp_printpkt(u_char *p, int plen, void (*printer) (void *, char *, ...), void *arg) +{ + LWIP_UNUSED_ARG(p); + LWIP_UNUSED_ARG(plen); + LWIP_UNUSED_ARG(printer); + LWIP_UNUSED_ARG(arg); + return 0; +} + +/* + * ip_active_pkt - see if this IP packet is worth bringing the link up for. + * We don't bring the link up for IP fragments or for TCP FIN packets + * with no data. + */ +#define IP_HDRLEN 20 /* bytes */ +#define IP_OFFMASK 0x1fff +#define IPPROTO_TCP 6 +#define TCP_HDRLEN 20 +#define TH_FIN 0x01 + +/* + * We use these macros because the IP header may be at an odd address, + * and some compilers might use word loads to get th_off or ip_hl. + */ + +#define net_short(x) (((x)[0] << 8) + (x)[1]) +#define get_iphl(x) (((unsigned char *)(x))[0] & 0xF) +#define get_ipoff(x) net_short((unsigned char *)(x) + 6) +#define get_ipproto(x) (((unsigned char *)(x))[9]) +#define get_tcpoff(x) (((unsigned char *)(x))[12] >> 4) +#define get_tcpflags(x) (((unsigned char *)(x))[13]) + +static int +ip_active_pkt(u_char *pkt, int len) +{ + u_char *tcp; + int hlen; + + len -= PPP_HDRLEN; + pkt += PPP_HDRLEN; + if (len < IP_HDRLEN) { + return 0; + } + if ((get_ipoff(pkt) & IP_OFFMASK) != 0) { + return 0; + } + if (get_ipproto(pkt) != IPPROTO_TCP) { + return 1; + } + hlen = get_iphl(pkt) * 4; + if (len < hlen + TCP_HDRLEN) { + return 0; + } + tcp = pkt + hlen; + if ((get_tcpflags(tcp) & TH_FIN) != 0 && len == hlen + get_tcpoff(tcp) * 4) { + return 0; + } + return 1; +} +#endif /* PPP_ADDITIONAL_CALLBACKS */ + +#endif /* PPP_SUPPORT */ diff --git a/features/unsupported/net/lwip/lwip/netif/ppp/ipcp.h b/features/unsupported/net/lwip/lwip/netif/ppp/ipcp.h new file mode 100644 index 00000000000..de03f460ecb --- /dev/null +++ b/features/unsupported/net/lwip/lwip/netif/ppp/ipcp.h @@ -0,0 +1,106 @@ +/***************************************************************************** +* ipcp.h - PPP IP NCP: Internet Protocol Network Control Protocol header file. +* +* Copyright (c) 2003 by Marc Boucher, Services Informatiques (MBSI) inc. +* portions Copyright (c) 1997 Global Election Systems Inc. +* +* The authors hereby grant permission to use, copy, modify, distribute, +* and license this software and its documentation for any purpose, provided +* that existing copyright notices are retained in all copies and that this +* notice and the following disclaimer are included verbatim in any +* distributions. No written agreement, license, or royalty fee is required +* for any of the authorized uses. +* +* THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS *AS IS* AND ANY EXPRESS OR +* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +* IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT +* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +****************************************************************************** +* REVISION HISTORY +* +* 03-01-01 Marc Boucher +* Ported to lwIP. +* 97-12-04 Guy Lancaster , Global Election Systems Inc. +* Original derived from BSD codes. +*****************************************************************************/ +/* + * ipcp.h - IP Control Protocol definitions. + * + * Copyright (c) 1989 Carnegie Mellon University. + * All rights reserved. + * + * Redistribution and use in source and binary forms are permitted + * provided that the above copyright notice and this paragraph are + * duplicated in all such forms and that any documentation, + * advertising materials, and other materials related to such + * distribution and use acknowledge that the software was developed + * by Carnegie Mellon University. The name of the + * University may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED + * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. + * + * $Id: ipcp.h,v 1.4 2010/01/18 20:49:43 goldsimon Exp $ + */ + +#ifndef IPCP_H +#define IPCP_H + +/* + * Options. + */ +#define CI_ADDRS 1 /* IP Addresses */ +#define CI_COMPRESSTYPE 2 /* Compression Type */ +#define CI_ADDR 3 + +#define CI_MS_DNS1 129 /* Primary DNS value */ +#define CI_MS_WINS1 128 /* Primary WINS value */ +#define CI_MS_DNS2 131 /* Secondary DNS value */ +#define CI_MS_WINS2 130 /* Secondary WINS value */ + +#define IPCP_VJMODE_OLD 1 /* "old" mode (option # = 0x0037) */ +#define IPCP_VJMODE_RFC1172 2 /* "old-rfc"mode (option # = 0x002d) */ +#define IPCP_VJMODE_RFC1332 3 /* "new-rfc"mode (option # = 0x002d, */ + /* maxslot and slot number compression) */ + +#define IPCP_VJ_COMP 0x002d /* current value for VJ compression option */ +#define IPCP_VJ_COMP_OLD 0x0037 /* "old" (i.e, broken) value for VJ */ + /* compression option */ + +typedef struct ipcp_options { + u_int neg_addr : 1; /* Negotiate IP Address? */ + u_int old_addrs : 1; /* Use old (IP-Addresses) option? */ + u_int req_addr : 1; /* Ask peer to send IP address? */ + u_int default_route : 1; /* Assign default route through interface? */ + u_int proxy_arp : 1; /* Make proxy ARP entry for peer? */ + u_int neg_vj : 1; /* Van Jacobson Compression? */ + u_int old_vj : 1; /* use old (short) form of VJ option? */ + u_int accept_local : 1; /* accept peer's value for ouraddr */ + u_int accept_remote : 1; /* accept peer's value for hisaddr */ + u_int req_dns1 : 1; /* Ask peer to send primary DNS address? */ + u_int req_dns2 : 1; /* Ask peer to send secondary DNS address? */ + u_short vj_protocol; /* protocol value to use in VJ option */ + u_char maxslotindex; /* VJ slots - 1. */ + u_char cflag; /* VJ slot compression flag. */ + u32_t ouraddr, hisaddr; /* Addresses in NETWORK BYTE ORDER */ + u32_t dnsaddr[2]; /* Primary and secondary MS DNS entries */ + u32_t winsaddr[2]; /* Primary and secondary MS WINS entries */ +} ipcp_options; + +extern fsm ipcp_fsm[]; +extern ipcp_options ipcp_wantoptions[]; +extern ipcp_options ipcp_gotoptions[]; +extern ipcp_options ipcp_allowoptions[]; +extern ipcp_options ipcp_hisoptions[]; + +extern struct protent ipcp_protent; + +#endif /* IPCP_H */ diff --git a/features/unsupported/net/lwip/lwip/netif/ppp/lcp.c b/features/unsupported/net/lwip/lwip/netif/ppp/lcp.c new file mode 100644 index 00000000000..95d54849b9a --- /dev/null +++ b/features/unsupported/net/lwip/lwip/netif/ppp/lcp.c @@ -0,0 +1,2066 @@ +/***************************************************************************** +* lcp.c - Network Link Control Protocol program file. +* +* Copyright (c) 2003 by Marc Boucher, Services Informatiques (MBSI) inc. +* portions Copyright (c) 1997 by Global Election Systems Inc. +* +* The authors hereby grant permission to use, copy, modify, distribute, +* and license this software and its documentation for any purpose, provided +* that existing copyright notices are retained in all copies and that this +* notice and the following disclaimer are included verbatim in any +* distributions. No written agreement, license, or royalty fee is required +* for any of the authorized uses. +* +* THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS *AS IS* AND ANY EXPRESS OR +* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +* IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT +* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +****************************************************************************** +* REVISION HISTORY +* +* 03-01-01 Marc Boucher +* Ported to lwIP. +* 97-12-01 Guy Lancaster , Global Election Systems Inc. +* Original. +*****************************************************************************/ + +/* + * lcp.c - PPP Link Control Protocol. + * + * Copyright (c) 1989 Carnegie Mellon University. + * All rights reserved. + * + * Redistribution and use in source and binary forms are permitted + * provided that the above copyright notice and this paragraph are + * duplicated in all such forms and that any documentation, + * advertising materials, and other materials related to such + * distribution and use acknowledge that the software was developed + * by Carnegie Mellon University. The name of the + * University may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED + * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. + */ + + +#include "lwip/opt.h" + +#if PPP_SUPPORT /* don't build if not configured for use in lwipopts.h */ + +#include "ppp.h" +#include "pppdebug.h" + +#include "fsm.h" +#include "chap.h" +#include "magic.h" +#include "auth.h" +#include "lcp.h" + +#include + +#if PPPOE_SUPPORT +#include "netif/ppp_oe.h" +#else +#define PPPOE_MAXMTU PPP_MAXMRU +#endif + +#if 0 /* UNUSED */ +/* + * LCP-related command-line options. + */ +int lcp_echo_interval = 0; /* Interval between LCP echo-requests */ +int lcp_echo_fails = 0; /* Tolerance to unanswered echo-requests */ +bool lax_recv = 0; /* accept control chars in asyncmap */ + +static int setescape (char **); + +static option_t lcp_option_list[] = { + /* LCP options */ + /* list stripped for simplicity */ + {NULL} +}; +#endif /* UNUSED */ + +/* options */ +LinkPhase lcp_phase[NUM_PPP]; /* Phase of link session (RFC 1661) */ +static u_int lcp_echo_interval = LCP_ECHOINTERVAL; /* Interval between LCP echo-requests */ +static u_int lcp_echo_fails = LCP_MAXECHOFAILS; /* Tolerance to unanswered echo-requests */ + +/* global vars */ +static fsm lcp_fsm[NUM_PPP]; /* LCP fsm structure (global)*/ +lcp_options lcp_wantoptions[NUM_PPP]; /* Options that we want to request */ +lcp_options lcp_gotoptions[NUM_PPP]; /* Options that peer ack'd */ +lcp_options lcp_allowoptions[NUM_PPP]; /* Options we allow peer to request */ +lcp_options lcp_hisoptions[NUM_PPP]; /* Options that we ack'd */ +ext_accm xmit_accm[NUM_PPP]; /* extended transmit ACCM */ + +static u32_t lcp_echos_pending = 0; /* Number of outstanding echo msgs */ +static u32_t lcp_echo_number = 0; /* ID number of next echo frame */ +static u32_t lcp_echo_timer_running = 0; /* TRUE if a timer is running */ + +/* @todo: do we really need such a large buffer? The typical 1500 bytes seem too much. */ +static u_char nak_buffer[PPP_MRU] __attribute((section("AHBSRAM1"))); /* where we construct a nak packet */ + +/* + * Callbacks for fsm code. (CI = Configuration Information) + */ +static void lcp_resetci (fsm*); /* Reset our CI */ +static int lcp_cilen (fsm*); /* Return length of our CI */ +static void lcp_addci (fsm*, u_char*, int*); /* Add our CI to pkt */ +static int lcp_ackci (fsm*, u_char*, int); /* Peer ack'd our CI */ +static int lcp_nakci (fsm*, u_char*, int); /* Peer nak'd our CI */ +static int lcp_rejci (fsm*, u_char*, int); /* Peer rej'd our CI */ +static int lcp_reqci (fsm*, u_char*, int*, int); /* Rcv peer CI */ +static void lcp_up (fsm*); /* We're UP */ +static void lcp_down (fsm*); /* We're DOWN */ +static void lcp_starting (fsm*); /* We need lower layer up */ +static void lcp_finished (fsm*); /* We need lower layer down */ +static int lcp_extcode (fsm*, int, u_char, u_char*, int); +static void lcp_rprotrej (fsm*, u_char*, int); + +/* + * routines to send LCP echos to peer + */ + +static void lcp_echo_lowerup (int); +static void lcp_echo_lowerdown (int); +static void LcpEchoTimeout (void*); +static void lcp_received_echo_reply (fsm*, int, u_char*, int); +static void LcpSendEchoRequest (fsm*); +static void LcpLinkFailure (fsm*); +static void LcpEchoCheck (fsm*); + +static fsm_callbacks lcp_callbacks = { /* LCP callback routines */ + lcp_resetci, /* Reset our Configuration Information */ + lcp_cilen, /* Length of our Configuration Information */ + lcp_addci, /* Add our Configuration Information */ + lcp_ackci, /* ACK our Configuration Information */ + lcp_nakci, /* NAK our Configuration Information */ + lcp_rejci, /* Reject our Configuration Information */ + lcp_reqci, /* Request peer's Configuration Information */ + lcp_up, /* Called when fsm reaches LS_OPENED state */ + lcp_down, /* Called when fsm leaves LS_OPENED state */ + lcp_starting, /* Called when we want the lower layer up */ + lcp_finished, /* Called when we want the lower layer down */ + NULL, /* Called when Protocol-Reject received */ + NULL, /* Retransmission is necessary */ + lcp_extcode, /* Called to handle LCP-specific codes */ + "LCP" /* String name of protocol */ +}; + +/* + * Protocol entry points. + * Some of these are called directly. + */ + +static void lcp_input (int, u_char *, int); +static void lcp_protrej (int); + +struct protent lcp_protent = { + PPP_LCP, + lcp_init, + lcp_input, + lcp_protrej, + lcp_lowerup, + lcp_lowerdown, + lcp_open, + lcp_close, +#if PPP_ADDITIONAL_CALLBACKS + lcp_printpkt, + NULL, +#endif /* PPP_ADDITIONAL_CALLBACKS */ + 1, + "LCP", +#if PPP_ADDITIONAL_CALLBACKS + NULL, + NULL, + NULL +#endif /* PPP_ADDITIONAL_CALLBACKS */ +}; + +int lcp_loopbackfail = DEFLOOPBACKFAIL; + +/* + * Length of each type of configuration option (in octets) + */ +#define CILEN_VOID 2 +#define CILEN_CHAR 3 +#define CILEN_SHORT 4 /* CILEN_VOID + sizeof(short) */ +#define CILEN_CHAP 5 /* CILEN_VOID + sizeof(short) + 1 */ +#define CILEN_LONG 6 /* CILEN_VOID + sizeof(long) */ +#define CILEN_LQR 8 /* CILEN_VOID + sizeof(short) + sizeof(long) */ +#define CILEN_CBCP 3 + +#define CODENAME(x) ((x) == CONFACK ? "ACK" : (x) == CONFNAK ? "NAK" : "REJ") + +#if 0 /* UNUSED */ +/* + * setescape - add chars to the set we escape on transmission. + */ +static int +setescape(argv) + char **argv; +{ + int n, ret; + char *p, *endp; + + p = *argv; + ret = 1; + while (*p) { + n = strtol(p, &endp, 16); + if (p == endp) { + option_error("escape parameter contains invalid hex number '%s'", p); + return 0; + } + p = endp; + if (n < 0 || n == 0x5E || n > 0xFF) { + option_error("can't escape character 0x%x", n); + ret = 0; + } else + xmit_accm[0][n >> 5] |= 1 << (n & 0x1F); + while (*p == ',' || *p == ' ') + ++p; + } + return ret; +} +#endif /* UNUSED */ + +/* + * lcp_init - Initialize LCP. + */ +void +lcp_init(int unit) +{ + fsm *f = &lcp_fsm[unit]; + lcp_options *wo = &lcp_wantoptions[unit]; + lcp_options *ao = &lcp_allowoptions[unit]; + + f->unit = unit; + f->protocol = PPP_LCP; + f->callbacks = &lcp_callbacks; + + fsm_init(f); + + wo->passive = 0; + wo->silent = 0; + wo->restart = 0; /* Set to 1 in kernels or multi-line implementations */ + wo->neg_mru = 1; + wo->mru = PPP_DEFMRU; + wo->neg_asyncmap = 1; + wo->asyncmap = 0x00000000l; /* Assume don't need to escape any ctl chars. */ + wo->neg_chap = 0; /* Set to 1 on server */ + wo->neg_upap = 0; /* Set to 1 on server */ + wo->chap_mdtype = CHAP_DIGEST_MD5; + wo->neg_magicnumber = 1; + wo->neg_pcompression = 1; + wo->neg_accompression = 1; + wo->neg_lqr = 0; /* no LQR implementation yet */ + wo->neg_cbcp = 0; + + ao->neg_mru = 1; + ao->mru = PPP_MAXMRU; + ao->neg_asyncmap = 1; + ao->asyncmap = 0x00000000l; /* Assume don't need to escape any ctl chars. */ + ao->neg_chap = (CHAP_SUPPORT != 0); + ao->chap_mdtype = CHAP_DIGEST_MD5; + ao->neg_upap = (PAP_SUPPORT != 0); + ao->neg_magicnumber = 1; + ao->neg_pcompression = 1; + ao->neg_accompression = 1; + ao->neg_lqr = 0; /* no LQR implementation yet */ + ao->neg_cbcp = (CBCP_SUPPORT != 0); + + /* + * Set transmit escape for the flag and escape characters plus anything + * set for the allowable options. + */ + memset(xmit_accm[unit], 0, sizeof(xmit_accm[0])); + xmit_accm[unit][15] = 0x60; + xmit_accm[unit][0] = (u_char)((ao->asyncmap & 0xFF)); + xmit_accm[unit][1] = (u_char)((ao->asyncmap >> 8) & 0xFF); + xmit_accm[unit][2] = (u_char)((ao->asyncmap >> 16) & 0xFF); + xmit_accm[unit][3] = (u_char)((ao->asyncmap >> 24) & 0xFF); + LCPDEBUG(LOG_INFO, ("lcp_init: xmit_accm=%X %X %X %X\n", + xmit_accm[unit][0], + xmit_accm[unit][1], + xmit_accm[unit][2], + xmit_accm[unit][3])); + + lcp_phase[unit] = PHASE_INITIALIZE; +} + + +/* + * lcp_open - LCP is allowed to come up. + */ +void +lcp_open(int unit) +{ + fsm *f = &lcp_fsm[unit]; + lcp_options *wo = &lcp_wantoptions[unit]; + + f->flags = 0; + if (wo->passive) { + f->flags |= OPT_PASSIVE; + } + if (wo->silent) { + f->flags |= OPT_SILENT; + } + fsm_open(f); + + lcp_phase[unit] = PHASE_ESTABLISH; +} + + +/* + * lcp_close - Take LCP down. + */ +void +lcp_close(int unit, char *reason) +{ + fsm *f = &lcp_fsm[unit]; + + if (lcp_phase[unit] != PHASE_DEAD) { + lcp_phase[unit] = PHASE_TERMINATE; + } + if (f->state == LS_STOPPED && f->flags & (OPT_PASSIVE|OPT_SILENT)) { + /* + * This action is not strictly according to the FSM in RFC1548, + * but it does mean that the program terminates if you do an + * lcp_close() in passive/silent mode when a connection hasn't + * been established. + */ + f->state = LS_CLOSED; + lcp_finished(f); + } else { + fsm_close(f, reason); + } +} + + +/* + * lcp_lowerup - The lower layer is up. + */ +void +lcp_lowerup(int unit) +{ + lcp_options *wo = &lcp_wantoptions[unit]; + + /* + * Don't use A/C or protocol compression on transmission, + * but accept A/C and protocol compressed packets + * if we are going to ask for A/C and protocol compression. + */ + ppp_set_xaccm(unit, &xmit_accm[unit]); + ppp_send_config(unit, PPP_MRU, 0xffffffffl, 0, 0); + ppp_recv_config(unit, PPP_MRU, 0x00000000l, + wo->neg_pcompression, wo->neg_accompression); + peer_mru[unit] = PPP_MRU; + lcp_allowoptions[unit].asyncmap = (u_long)xmit_accm[unit][0] + | ((u_long)xmit_accm[unit][1] << 8) + | ((u_long)xmit_accm[unit][2] << 16) + | ((u_long)xmit_accm[unit][3] << 24); + LCPDEBUG(LOG_INFO, ("lcp_lowerup: asyncmap=%X %X %X %X\n", + xmit_accm[unit][3], + xmit_accm[unit][2], + xmit_accm[unit][1], + xmit_accm[unit][0])); + + fsm_lowerup(&lcp_fsm[unit]); +} + + +/* + * lcp_lowerdown - The lower layer is down. + */ +void +lcp_lowerdown(int unit) +{ + fsm_lowerdown(&lcp_fsm[unit]); +} + + +/* + * lcp_input - Input LCP packet. + */ +static void +lcp_input(int unit, u_char *p, int len) +{ + fsm *f = &lcp_fsm[unit]; + + fsm_input(f, p, len); +} + + +/* + * lcp_extcode - Handle a LCP-specific code. + */ +static int +lcp_extcode(fsm *f, int code, u_char id, u_char *inp, int len) +{ + u_char *magp; + + switch( code ){ + case PROTREJ: + lcp_rprotrej(f, inp, len); + break; + + case ECHOREQ: + if (f->state != LS_OPENED) { + break; + } + LCPDEBUG(LOG_INFO, ("lcp: Echo-Request, Rcvd id %d\n", id)); + magp = inp; + PUTLONG(lcp_gotoptions[f->unit].magicnumber, magp); + fsm_sdata(f, ECHOREP, id, inp, len); + break; + + case ECHOREP: + lcp_received_echo_reply(f, id, inp, len); + break; + + case DISCREQ: + break; + + default: + return 0; + } + return 1; +} + + +/* + * lcp_rprotrej - Receive an Protocol-Reject. + * + * Figure out which protocol is rejected and inform it. + */ +static void +lcp_rprotrej(fsm *f, u_char *inp, int len) +{ + int i; + struct protent *protp; + u_short prot; + + if (len < (int)sizeof (u_short)) { + LCPDEBUG(LOG_INFO, ("lcp_rprotrej: Rcvd short Protocol-Reject packet!\n")); + return; + } + + GETSHORT(prot, inp); + + LCPDEBUG(LOG_INFO, ("lcp_rprotrej: Rcvd Protocol-Reject packet for %x!\n", prot)); + + /* + * Protocol-Reject packets received in any state other than the LCP + * LS_OPENED state SHOULD be silently discarded. + */ + if( f->state != LS_OPENED ) { + LCPDEBUG(LOG_INFO, ("Protocol-Reject discarded: LCP in state %d\n", f->state)); + return; + } + + /* + * Upcall the proper Protocol-Reject routine. + */ + for (i = 0; (protp = ppp_protocols[i]) != NULL; ++i) { + if (protp->protocol == prot && protp->enabled_flag) { + (*protp->protrej)(f->unit); + return; + } + } + + LCPDEBUG(LOG_WARNING, ("Protocol-Reject for unsupported protocol 0x%x\n", prot)); +} + + +/* + * lcp_protrej - A Protocol-Reject was received. + */ +static void +lcp_protrej(int unit) +{ + LWIP_UNUSED_ARG(unit); + /* + * Can't reject LCP! + */ + LCPDEBUG(LOG_WARNING, ("lcp_protrej: Received Protocol-Reject for LCP!\n")); + fsm_protreject(&lcp_fsm[unit]); +} + + +/* + * lcp_sprotrej - Send a Protocol-Reject for some protocol. + */ +void +lcp_sprotrej(int unit, u_char *p, int len) +{ + /* + * Send back the protocol and the information field of the + * rejected packet. We only get here if LCP is in the LS_OPENED state. + */ + + fsm_sdata(&lcp_fsm[unit], PROTREJ, ++lcp_fsm[unit].id, p, len); +} + + +/* + * lcp_resetci - Reset our CI. + */ +static void +lcp_resetci(fsm *f) +{ + lcp_wantoptions[f->unit].magicnumber = magic(); + lcp_wantoptions[f->unit].numloops = 0; + lcp_gotoptions[f->unit] = lcp_wantoptions[f->unit]; + peer_mru[f->unit] = PPP_MRU; + auth_reset(f->unit); +} + + +/* + * lcp_cilen - Return length of our CI. + */ +static int +lcp_cilen(fsm *f) +{ + lcp_options *go = &lcp_gotoptions[f->unit]; + +#define LENCIVOID(neg) ((neg) ? CILEN_VOID : 0) +#define LENCICHAP(neg) ((neg) ? CILEN_CHAP : 0) +#define LENCISHORT(neg) ((neg) ? CILEN_SHORT : 0) +#define LENCILONG(neg) ((neg) ? CILEN_LONG : 0) +#define LENCILQR(neg) ((neg) ? CILEN_LQR: 0) +#define LENCICBCP(neg) ((neg) ? CILEN_CBCP: 0) + /* + * NB: we only ask for one of CHAP and UPAP, even if we will + * accept either. + */ + return (LENCISHORT(go->neg_mru && go->mru != PPP_DEFMRU) + + LENCILONG(go->neg_asyncmap && go->asyncmap != 0xFFFFFFFFl) + + LENCICHAP(go->neg_chap) + + LENCISHORT(!go->neg_chap && go->neg_upap) + + LENCILQR(go->neg_lqr) + + LENCICBCP(go->neg_cbcp) + + LENCILONG(go->neg_magicnumber) + + LENCIVOID(go->neg_pcompression) + + LENCIVOID(go->neg_accompression)); +} + + +/* + * lcp_addci - Add our desired CIs to a packet. + */ +static void +lcp_addci(fsm *f, u_char *ucp, int *lenp) +{ + lcp_options *go = &lcp_gotoptions[f->unit]; + u_char *start_ucp = ucp; + +#define ADDCIVOID(opt, neg) \ + if (neg) { \ + LCPDEBUG(LOG_INFO, ("lcp_addci: opt=%d\n", opt)); \ + PUTCHAR(opt, ucp); \ + PUTCHAR(CILEN_VOID, ucp); \ + } +#define ADDCISHORT(opt, neg, val) \ + if (neg) { \ + LCPDEBUG(LOG_INFO, ("lcp_addci: INT opt=%d %X\n", opt, val)); \ + PUTCHAR(opt, ucp); \ + PUTCHAR(CILEN_SHORT, ucp); \ + PUTSHORT(val, ucp); \ + } +#define ADDCICHAP(opt, neg, val, digest) \ + if (neg) { \ + LCPDEBUG(LOG_INFO, ("lcp_addci: CHAP opt=%d %X\n", opt, val)); \ + PUTCHAR(opt, ucp); \ + PUTCHAR(CILEN_CHAP, ucp); \ + PUTSHORT(val, ucp); \ + PUTCHAR(digest, ucp); \ + } +#define ADDCILONG(opt, neg, val) \ + if (neg) { \ + LCPDEBUG(LOG_INFO, ("lcp_addci: L opt=%d %lX\n", opt, val)); \ + PUTCHAR(opt, ucp); \ + PUTCHAR(CILEN_LONG, ucp); \ + PUTLONG(val, ucp); \ + } +#define ADDCILQR(opt, neg, val) \ + if (neg) { \ + LCPDEBUG(LOG_INFO, ("lcp_addci: LQR opt=%d %lX\n", opt, val)); \ + PUTCHAR(opt, ucp); \ + PUTCHAR(CILEN_LQR, ucp); \ + PUTSHORT(PPP_LQR, ucp); \ + PUTLONG(val, ucp); \ + } +#define ADDCICHAR(opt, neg, val) \ + if (neg) { \ + LCPDEBUG(LOG_INFO, ("lcp_addci: CHAR opt=%d %X '%z'\n", opt, val, val)); \ + PUTCHAR(opt, ucp); \ + PUTCHAR(CILEN_CHAR, ucp); \ + PUTCHAR(val, ucp); \ + } + + ADDCISHORT(CI_MRU, go->neg_mru && go->mru != PPP_DEFMRU, go->mru); + ADDCILONG(CI_ASYNCMAP, go->neg_asyncmap && go->asyncmap != 0xFFFFFFFFl, go->asyncmap); + ADDCICHAP(CI_AUTHTYPE, go->neg_chap, PPP_CHAP, go->chap_mdtype); + ADDCISHORT(CI_AUTHTYPE, !go->neg_chap && go->neg_upap, PPP_PAP); + ADDCILQR(CI_QUALITY, go->neg_lqr, go->lqr_period); + ADDCICHAR(CI_CALLBACK, go->neg_cbcp, CBCP_OPT); + ADDCILONG(CI_MAGICNUMBER, go->neg_magicnumber, go->magicnumber); + ADDCIVOID(CI_PCOMPRESSION, go->neg_pcompression); + ADDCIVOID(CI_ACCOMPRESSION, go->neg_accompression); + + if (ucp - start_ucp != *lenp) { + /* this should never happen, because peer_mtu should be 1500 */ + LCPDEBUG(LOG_ERR, ("Bug in lcp_addci: wrong length\n")); + } +} + + +/* + * lcp_ackci - Ack our CIs. + * This should not modify any state if the Ack is bad. + * + * Returns: + * 0 - Ack was bad. + * 1 - Ack was good. + */ +static int +lcp_ackci(fsm *f, u_char *p, int len) +{ + lcp_options *go = &lcp_gotoptions[f->unit]; + u_char cilen, citype, cichar; + u_short cishort; + u32_t cilong; + + /* + * CIs must be in exactly the same order that we sent. + * Check packet length and CI length at each step. + * If we find any deviations, then this packet is bad. + */ +#define ACKCIVOID(opt, neg) \ + if (neg) { \ + if ((len -= CILEN_VOID) < 0) \ + goto bad; \ + GETCHAR(citype, p); \ + GETCHAR(cilen, p); \ + if (cilen != CILEN_VOID || citype != opt) \ + goto bad; \ + } +#define ACKCISHORT(opt, neg, val) \ + if (neg) { \ + if ((len -= CILEN_SHORT) < 0) \ + goto bad; \ + GETCHAR(citype, p); \ + GETCHAR(cilen, p); \ + if (cilen != CILEN_SHORT || citype != opt) \ + goto bad; \ + GETSHORT(cishort, p); \ + if (cishort != val) \ + goto bad; \ + } +#define ACKCICHAR(opt, neg, val) \ + if (neg) { \ + if ((len -= CILEN_CHAR) < 0) \ + goto bad; \ + GETCHAR(citype, p); \ + GETCHAR(cilen, p); \ + if (cilen != CILEN_CHAR || citype != opt) \ + goto bad; \ + GETCHAR(cichar, p); \ + if (cichar != val) \ + goto bad; \ + } +#define ACKCICHAP(opt, neg, val, digest) \ + if (neg) { \ + if ((len -= CILEN_CHAP) < 0) \ + goto bad; \ + GETCHAR(citype, p); \ + GETCHAR(cilen, p); \ + if (cilen != CILEN_CHAP || citype != opt) \ + goto bad; \ + GETSHORT(cishort, p); \ + if (cishort != val) \ + goto bad; \ + GETCHAR(cichar, p); \ + if (cichar != digest) \ + goto bad; \ + } +#define ACKCILONG(opt, neg, val) \ + if (neg) { \ + if ((len -= CILEN_LONG) < 0) \ + goto bad; \ + GETCHAR(citype, p); \ + GETCHAR(cilen, p); \ + if (cilen != CILEN_LONG || citype != opt) \ + goto bad; \ + GETLONG(cilong, p); \ + if (cilong != val) \ + goto bad; \ + } +#define ACKCILQR(opt, neg, val) \ + if (neg) { \ + if ((len -= CILEN_LQR) < 0) \ + goto bad; \ + GETCHAR(citype, p); \ + GETCHAR(cilen, p); \ + if (cilen != CILEN_LQR || citype != opt) \ + goto bad; \ + GETSHORT(cishort, p); \ + if (cishort != PPP_LQR) \ + goto bad; \ + GETLONG(cilong, p); \ + if (cilong != val) \ + goto bad; \ + } + + ACKCISHORT(CI_MRU, go->neg_mru && go->mru != PPP_DEFMRU, go->mru); + ACKCILONG(CI_ASYNCMAP, go->neg_asyncmap && go->asyncmap != 0xFFFFFFFFl, go->asyncmap); + ACKCICHAP(CI_AUTHTYPE, go->neg_chap, PPP_CHAP, go->chap_mdtype); + ACKCISHORT(CI_AUTHTYPE, !go->neg_chap && go->neg_upap, PPP_PAP); + ACKCILQR(CI_QUALITY, go->neg_lqr, go->lqr_period); + ACKCICHAR(CI_CALLBACK, go->neg_cbcp, CBCP_OPT); + ACKCILONG(CI_MAGICNUMBER, go->neg_magicnumber, go->magicnumber); + ACKCIVOID(CI_PCOMPRESSION, go->neg_pcompression); + ACKCIVOID(CI_ACCOMPRESSION, go->neg_accompression); + + /* + * If there are any remaining CIs, then this packet is bad. + */ + if (len != 0) { + goto bad; + } + LCPDEBUG(LOG_INFO, ("lcp_acki: Ack\n")); + return (1); +bad: + LCPDEBUG(LOG_WARNING, ("lcp_acki: received bad Ack!\n")); + return (0); +} + + +/* + * lcp_nakci - Peer has sent a NAK for some of our CIs. + * This should not modify any state if the Nak is bad + * or if LCP is in the LS_OPENED state. + * + * Returns: + * 0 - Nak was bad. + * 1 - Nak was good. + */ +static int +lcp_nakci(fsm *f, u_char *p, int len) +{ + lcp_options *go = &lcp_gotoptions[f->unit]; + lcp_options *wo = &lcp_wantoptions[f->unit]; + u_char citype, cichar, *next; + u_short cishort; + u32_t cilong; + lcp_options no; /* options we've seen Naks for */ + lcp_options try; /* options to request next time */ + int looped_back = 0; + int cilen; + + BZERO(&no, sizeof(no)); + try = *go; + + /* + * Any Nak'd CIs must be in exactly the same order that we sent. + * Check packet length and CI length at each step. + * If we find any deviations, then this packet is bad. + */ +#define NAKCIVOID(opt, neg, code) \ + if (go->neg && \ + len >= CILEN_VOID && \ + p[1] == CILEN_VOID && \ + p[0] == opt) { \ + len -= CILEN_VOID; \ + INCPTR(CILEN_VOID, p); \ + no.neg = 1; \ + code \ + } +#define NAKCICHAP(opt, neg, code) \ + if (go->neg && \ + len >= CILEN_CHAP && \ + p[1] == CILEN_CHAP && \ + p[0] == opt) { \ + len -= CILEN_CHAP; \ + INCPTR(2, p); \ + GETSHORT(cishort, p); \ + GETCHAR(cichar, p); \ + no.neg = 1; \ + code \ + } +#define NAKCICHAR(opt, neg, code) \ + if (go->neg && \ + len >= CILEN_CHAR && \ + p[1] == CILEN_CHAR && \ + p[0] == opt) { \ + len -= CILEN_CHAR; \ + INCPTR(2, p); \ + GETCHAR(cichar, p); \ + no.neg = 1; \ + code \ + } +#define NAKCISHORT(opt, neg, code) \ + if (go->neg && \ + len >= CILEN_SHORT && \ + p[1] == CILEN_SHORT && \ + p[0] == opt) { \ + len -= CILEN_SHORT; \ + INCPTR(2, p); \ + GETSHORT(cishort, p); \ + no.neg = 1; \ + code \ + } +#define NAKCILONG(opt, neg, code) \ + if (go->neg && \ + len >= CILEN_LONG && \ + p[1] == CILEN_LONG && \ + p[0] == opt) { \ + len -= CILEN_LONG; \ + INCPTR(2, p); \ + GETLONG(cilong, p); \ + no.neg = 1; \ + code \ + } +#define NAKCILQR(opt, neg, code) \ + if (go->neg && \ + len >= CILEN_LQR && \ + p[1] == CILEN_LQR && \ + p[0] == opt) { \ + len -= CILEN_LQR; \ + INCPTR(2, p); \ + GETSHORT(cishort, p); \ + GETLONG(cilong, p); \ + no.neg = 1; \ + code \ + } + + /* + * We don't care if they want to send us smaller packets than + * we want. Therefore, accept any MRU less than what we asked for, + * but then ignore the new value when setting the MRU in the kernel. + * If they send us a bigger MRU than what we asked, accept it, up to + * the limit of the default MRU we'd get if we didn't negotiate. + */ + if (go->neg_mru && go->mru != PPP_DEFMRU) { + NAKCISHORT(CI_MRU, neg_mru, + if (cishort <= wo->mru || cishort < PPP_DEFMRU) { + try.mru = cishort; + } + ); + } + + /* + * Add any characters they want to our (receive-side) asyncmap. + */ + if (go->neg_asyncmap && go->asyncmap != 0xFFFFFFFFl) { + NAKCILONG(CI_ASYNCMAP, neg_asyncmap, + try.asyncmap = go->asyncmap | cilong; + ); + } + + /* + * If they've nak'd our authentication-protocol, check whether + * they are proposing a different protocol, or a different + * hash algorithm for CHAP. + */ + if ((go->neg_chap || go->neg_upap) + && len >= CILEN_SHORT + && p[0] == CI_AUTHTYPE && p[1] >= CILEN_SHORT && p[1] <= len) { + cilen = p[1]; + len -= cilen; + no.neg_chap = go->neg_chap; + no.neg_upap = go->neg_upap; + INCPTR(2, p); + GETSHORT(cishort, p); + if (cishort == PPP_PAP && cilen == CILEN_SHORT) { + /* + * If we were asking for CHAP, they obviously don't want to do it. + * If we weren't asking for CHAP, then we were asking for PAP, + * in which case this Nak is bad. + */ + if (!go->neg_chap) { + goto bad; + } + try.neg_chap = 0; + + } else if (cishort == PPP_CHAP && cilen == CILEN_CHAP) { + GETCHAR(cichar, p); + if (go->neg_chap) { + /* + * We were asking for CHAP/MD5; they must want a different + * algorithm. If they can't do MD5, we'll have to stop + * asking for CHAP. + */ + if (cichar != go->chap_mdtype) { + try.neg_chap = 0; + } + } else { + /* + * Stop asking for PAP if we were asking for it. + */ + try.neg_upap = 0; + } + + } else { + /* + * We don't recognize what they're suggesting. + * Stop asking for what we were asking for. + */ + if (go->neg_chap) { + try.neg_chap = 0; + } else { + try.neg_upap = 0; + } + p += cilen - CILEN_SHORT; + } + } + + /* + * If they can't cope with our link quality protocol, we'll have + * to stop asking for LQR. We haven't got any other protocol. + * If they Nak the reporting period, take their value XXX ? + */ + NAKCILQR(CI_QUALITY, neg_lqr, + if (cishort != PPP_LQR) { + try.neg_lqr = 0; + } else { + try.lqr_period = cilong; + } + ); + + /* + * Only implementing CBCP...not the rest of the callback options + */ + NAKCICHAR(CI_CALLBACK, neg_cbcp, + try.neg_cbcp = 0; + ); + + /* + * Check for a looped-back line. + */ + NAKCILONG(CI_MAGICNUMBER, neg_magicnumber, + try.magicnumber = magic(); + looped_back = 1; + ); + + /* + * Peer shouldn't send Nak for protocol compression or + * address/control compression requests; they should send + * a Reject instead. If they send a Nak, treat it as a Reject. + */ + NAKCIVOID(CI_PCOMPRESSION, neg_pcompression, + try.neg_pcompression = 0; + ); + NAKCIVOID(CI_ACCOMPRESSION, neg_accompression, + try.neg_accompression = 0; + ); + + /* + * There may be remaining CIs, if the peer is requesting negotiation + * on an option that we didn't include in our request packet. + * If we see an option that we requested, or one we've already seen + * in this packet, then this packet is bad. + * If we wanted to respond by starting to negotiate on the requested + * option(s), we could, but we don't, because except for the + * authentication type and quality protocol, if we are not negotiating + * an option, it is because we were told not to. + * For the authentication type, the Nak from the peer means + * `let me authenticate myself with you' which is a bit pointless. + * For the quality protocol, the Nak means `ask me to send you quality + * reports', but if we didn't ask for them, we don't want them. + * An option we don't recognize represents the peer asking to + * negotiate some option we don't support, so ignore it. + */ + while (len > CILEN_VOID) { + GETCHAR(citype, p); + GETCHAR(cilen, p); + if (cilen < CILEN_VOID || (len -= cilen) < 0) { + goto bad; + } + next = p + cilen - 2; + + switch (citype) { + case CI_MRU: + if ((go->neg_mru && go->mru != PPP_DEFMRU) + || no.neg_mru || cilen != CILEN_SHORT) { + goto bad; + } + GETSHORT(cishort, p); + if (cishort < PPP_DEFMRU) { + try.mru = cishort; + } + break; + case CI_ASYNCMAP: + if ((go->neg_asyncmap && go->asyncmap != 0xFFFFFFFFl) + || no.neg_asyncmap || cilen != CILEN_LONG) { + goto bad; + } + break; + case CI_AUTHTYPE: + if (go->neg_chap || no.neg_chap || go->neg_upap || no.neg_upap) { + goto bad; + } + break; + case CI_MAGICNUMBER: + if (go->neg_magicnumber || no.neg_magicnumber || + cilen != CILEN_LONG) { + goto bad; + } + break; + case CI_PCOMPRESSION: + if (go->neg_pcompression || no.neg_pcompression + || cilen != CILEN_VOID) { + goto bad; + } + break; + case CI_ACCOMPRESSION: + if (go->neg_accompression || no.neg_accompression + || cilen != CILEN_VOID) { + goto bad; + } + break; + case CI_QUALITY: + if (go->neg_lqr || no.neg_lqr || cilen != CILEN_LQR) { + goto bad; + } + break; + } + p = next; + } + + /* If there is still anything left, this packet is bad. */ + if (len != 0) { + goto bad; + } + + /* + * OK, the Nak is good. Now we can update state. + */ + if (f->state != LS_OPENED) { + if (looped_back) { + if (++try.numloops >= lcp_loopbackfail) { + LCPDEBUG(LOG_NOTICE, ("Serial line is looped back.\n")); + lcp_close(f->unit, "Loopback detected"); + } + } else { + try.numloops = 0; + } + *go = try; + } + + return 1; + +bad: + LCPDEBUG(LOG_WARNING, ("lcp_nakci: received bad Nak!\n")); + return 0; +} + + +/* + * lcp_rejci - Peer has Rejected some of our CIs. + * This should not modify any state if the Reject is bad + * or if LCP is in the LS_OPENED state. + * + * Returns: + * 0 - Reject was bad. + * 1 - Reject was good. + */ +static int +lcp_rejci(fsm *f, u_char *p, int len) +{ + lcp_options *go = &lcp_gotoptions[f->unit]; + u_char cichar; + u_short cishort; + u32_t cilong; + lcp_options try; /* options to request next time */ + + try = *go; + + /* + * Any Rejected CIs must be in exactly the same order that we sent. + * Check packet length and CI length at each step. + * If we find any deviations, then this packet is bad. + */ +#define REJCIVOID(opt, neg) \ + if (go->neg && \ + len >= CILEN_VOID && \ + p[1] == CILEN_VOID && \ + p[0] == opt) { \ + len -= CILEN_VOID; \ + INCPTR(CILEN_VOID, p); \ + try.neg = 0; \ + LCPDEBUG(LOG_INFO, ("lcp_rejci: void opt %d rejected\n", opt)); \ + } +#define REJCISHORT(opt, neg, val) \ + if (go->neg && \ + len >= CILEN_SHORT && \ + p[1] == CILEN_SHORT && \ + p[0] == opt) { \ + len -= CILEN_SHORT; \ + INCPTR(2, p); \ + GETSHORT(cishort, p); \ + /* Check rejected value. */ \ + if (cishort != val) { \ + goto bad; \ + } \ + try.neg = 0; \ + LCPDEBUG(LOG_INFO, ("lcp_rejci: short opt %d rejected\n", opt)); \ + } +#define REJCICHAP(opt, neg, val, digest) \ + if (go->neg && \ + len >= CILEN_CHAP && \ + p[1] == CILEN_CHAP && \ + p[0] == opt) { \ + len -= CILEN_CHAP; \ + INCPTR(2, p); \ + GETSHORT(cishort, p); \ + GETCHAR(cichar, p); \ + /* Check rejected value. */ \ + if (cishort != val || cichar != digest) { \ + goto bad; \ + } \ + try.neg = 0; \ + try.neg_upap = 0; \ + LCPDEBUG(LOG_INFO, ("lcp_rejci: chap opt %d rejected\n", opt)); \ + } +#define REJCILONG(opt, neg, val) \ + if (go->neg && \ + len >= CILEN_LONG && \ + p[1] == CILEN_LONG && \ + p[0] == opt) { \ + len -= CILEN_LONG; \ + INCPTR(2, p); \ + GETLONG(cilong, p); \ + /* Check rejected value. */ \ + if (cilong != val) { \ + goto bad; \ + } \ + try.neg = 0; \ + LCPDEBUG(LOG_INFO, ("lcp_rejci: long opt %d rejected\n", opt)); \ + } +#define REJCILQR(opt, neg, val) \ + if (go->neg && \ + len >= CILEN_LQR && \ + p[1] == CILEN_LQR && \ + p[0] == opt) { \ + len -= CILEN_LQR; \ + INCPTR(2, p); \ + GETSHORT(cishort, p); \ + GETLONG(cilong, p); \ + /* Check rejected value. */ \ + if (cishort != PPP_LQR || cilong != val) { \ + goto bad; \ + } \ + try.neg = 0; \ + LCPDEBUG(LOG_INFO, ("lcp_rejci: LQR opt %d rejected\n", opt)); \ + } +#define REJCICBCP(opt, neg, val) \ + if (go->neg && \ + len >= CILEN_CBCP && \ + p[1] == CILEN_CBCP && \ + p[0] == opt) { \ + len -= CILEN_CBCP; \ + INCPTR(2, p); \ + GETCHAR(cichar, p); \ + /* Check rejected value. */ \ + if (cichar != val) { \ + goto bad; \ + } \ + try.neg = 0; \ + LCPDEBUG(LOG_INFO, ("lcp_rejci: Callback opt %d rejected\n", opt)); \ + } + + REJCISHORT(CI_MRU, neg_mru, go->mru); + REJCILONG(CI_ASYNCMAP, neg_asyncmap, go->asyncmap); + REJCICHAP(CI_AUTHTYPE, neg_chap, PPP_CHAP, go->chap_mdtype); + if (!go->neg_chap) { + REJCISHORT(CI_AUTHTYPE, neg_upap, PPP_PAP); + } + REJCILQR(CI_QUALITY, neg_lqr, go->lqr_period); + REJCICBCP(CI_CALLBACK, neg_cbcp, CBCP_OPT); + REJCILONG(CI_MAGICNUMBER, neg_magicnumber, go->magicnumber); + REJCIVOID(CI_PCOMPRESSION, neg_pcompression); + REJCIVOID(CI_ACCOMPRESSION, neg_accompression); + + /* + * If there are any remaining CIs, then this packet is bad. + */ + if (len != 0) { + goto bad; + } + /* + * Now we can update state. + */ + if (f->state != LS_OPENED) { + *go = try; + } + return 1; + +bad: + LCPDEBUG(LOG_WARNING, ("lcp_rejci: received bad Reject!\n")); + return 0; +} + + +/* + * lcp_reqci - Check the peer's requested CIs and send appropriate response. + * + * Returns: CONFACK, CONFNAK or CONFREJ and input packet modified + * appropriately. If reject_if_disagree is non-zero, doesn't return + * CONFNAK; returns CONFREJ if it can't return CONFACK. + */ +static int +lcp_reqci(fsm *f, + u_char *inp, /* Requested CIs */ + int *lenp, /* Length of requested CIs */ + int reject_if_disagree) +{ + lcp_options *go = &lcp_gotoptions[f->unit]; + lcp_options *ho = &lcp_hisoptions[f->unit]; + lcp_options *ao = &lcp_allowoptions[f->unit]; + u_char *cip, *next; /* Pointer to current and next CIs */ + int cilen, citype; /* Parsed len, type */ + u_char cichar; /* Parsed char value */ + u_short cishort; /* Parsed short value */ + u32_t cilong; /* Parse long value */ + int rc = CONFACK; /* Final packet return code */ + int orc; /* Individual option return code */ + u_char *p; /* Pointer to next char to parse */ + u_char *rejp; /* Pointer to next char in reject frame */ + u_char *nakp; /* Pointer to next char in Nak frame */ + int l = *lenp; /* Length left */ +#if TRACELCP > 0 + char traceBuf[80]; + size_t traceNdx = 0; +#endif + + /* + * Reset all his options. + */ + BZERO(ho, sizeof(*ho)); + + /* + * Process all his options. + */ + next = inp; + nakp = nak_buffer; + rejp = inp; + while (l) { + orc = CONFACK; /* Assume success */ + cip = p = next; /* Remember begining of CI */ + if (l < 2 || /* Not enough data for CI header or */ + p[1] < 2 || /* CI length too small or */ + p[1] > l) { /* CI length too big? */ + LCPDEBUG(LOG_WARNING, ("lcp_reqci: bad CI length!\n")); + orc = CONFREJ; /* Reject bad CI */ + cilen = l; /* Reject till end of packet */ + l = 0; /* Don't loop again */ + citype = 0; + goto endswitch; + } + GETCHAR(citype, p); /* Parse CI type */ + GETCHAR(cilen, p); /* Parse CI length */ + l -= cilen; /* Adjust remaining length */ + next += cilen; /* Step to next CI */ + + switch (citype) { /* Check CI type */ + case CI_MRU: + if (!ao->neg_mru) { /* Allow option? */ + LCPDEBUG(LOG_INFO, ("lcp_reqci: Reject MRU - not allowed\n")); + orc = CONFREJ; /* Reject CI */ + break; + } else if (cilen != CILEN_SHORT) { /* Check CI length */ + LCPDEBUG(LOG_INFO, ("lcp_reqci: Reject MRU - bad length\n")); + orc = CONFREJ; /* Reject CI */ + break; + } + GETSHORT(cishort, p); /* Parse MRU */ + + /* + * He must be able to receive at least our minimum. + * No need to check a maximum. If he sends a large number, + * we'll just ignore it. + */ + if (cishort < PPP_MINMRU) { + LCPDEBUG(LOG_INFO, ("lcp_reqci: Nak - MRU too small\n")); + orc = CONFNAK; /* Nak CI */ + PUTCHAR(CI_MRU, nakp); + PUTCHAR(CILEN_SHORT, nakp); + PUTSHORT(PPP_MINMRU, nakp); /* Give him a hint */ + break; + } + ho->neg_mru = 1; /* Remember he sent MRU */ + ho->mru = cishort; /* And remember value */ +#if TRACELCP > 0 + snprintf(&traceBuf[traceNdx], sizeof(traceBuf), " MRU %d", cishort); + traceNdx = strlen(traceBuf); +#endif + break; + + case CI_ASYNCMAP: + if (!ao->neg_asyncmap) { + LCPDEBUG(LOG_INFO, ("lcp_reqci: Reject ASYNCMAP not allowed\n")); + orc = CONFREJ; + break; + } else if (cilen != CILEN_LONG) { + LCPDEBUG(LOG_INFO, ("lcp_reqci: Reject ASYNCMAP bad length\n")); + orc = CONFREJ; + break; + } + GETLONG(cilong, p); + + /* + * Asyncmap must have set at least the bits + * which are set in lcp_allowoptions[unit].asyncmap. + */ + if ((ao->asyncmap & ~cilong) != 0) { + LCPDEBUG(LOG_INFO, ("lcp_reqci: Nak ASYNCMAP %lX missing %lX\n", + cilong, ao->asyncmap)); + orc = CONFNAK; + PUTCHAR(CI_ASYNCMAP, nakp); + PUTCHAR(CILEN_LONG, nakp); + PUTLONG(ao->asyncmap | cilong, nakp); + break; + } + ho->neg_asyncmap = 1; + ho->asyncmap = cilong; +#if TRACELCP > 0 + snprintf(&traceBuf[traceNdx], sizeof(traceBuf), " ASYNCMAP=%lX", cilong); + traceNdx = strlen(traceBuf); +#endif + break; + + case CI_AUTHTYPE: + if (cilen < CILEN_SHORT) { + LCPDEBUG(LOG_INFO, ("lcp_reqci: Reject AUTHTYPE missing arg\n")); + orc = CONFREJ; + break; + } else if (!(ao->neg_upap || ao->neg_chap)) { + /* + * Reject the option if we're not willing to authenticate. + */ + LCPDEBUG(LOG_INFO, ("lcp_reqci: Reject AUTHTYPE not allowed\n")); + orc = CONFREJ; + break; + } + GETSHORT(cishort, p); + + /* + * Authtype must be UPAP or CHAP. + * + * Note: if both ao->neg_upap and ao->neg_chap are set, + * and the peer sends a Configure-Request with two + * authenticate-protocol requests, one for CHAP and one + * for UPAP, then we will reject the second request. + * Whether we end up doing CHAP or UPAP depends then on + * the ordering of the CIs in the peer's Configure-Request. + */ + + if (cishort == PPP_PAP) { + if (ho->neg_chap) { /* we've already accepted CHAP */ + LCPDEBUG(LOG_WARNING, ("lcp_reqci: Reject AUTHTYPE PAP already accepted\n")); + orc = CONFREJ; + break; + } else if (cilen != CILEN_SHORT) { + LCPDEBUG(LOG_WARNING, ("lcp_reqci: Reject AUTHTYPE PAP bad len\n")); + orc = CONFREJ; + break; + } + if (!ao->neg_upap) { /* we don't want to do PAP */ + LCPDEBUG(LOG_WARNING, ("lcp_reqci: Nak AUTHTYPE PAP not allowed\n")); + orc = CONFNAK; /* NAK it and suggest CHAP */ + PUTCHAR(CI_AUTHTYPE, nakp); + PUTCHAR(CILEN_CHAP, nakp); + PUTSHORT(PPP_CHAP, nakp); + PUTCHAR(ao->chap_mdtype, nakp); + break; + } + ho->neg_upap = 1; +#if TRACELCP > 0 + snprintf(&traceBuf[traceNdx], sizeof(traceBuf), " PAP (%X)", cishort); + traceNdx = strlen(traceBuf); +#endif + break; + } + if (cishort == PPP_CHAP) { + if (ho->neg_upap) { /* we've already accepted PAP */ + LCPDEBUG(LOG_WARNING, ("lcp_reqci: Reject AUTHTYPE CHAP accepted PAP\n")); + orc = CONFREJ; + break; + } else if (cilen != CILEN_CHAP) { + LCPDEBUG(LOG_WARNING, ("lcp_reqci: Reject AUTHTYPE CHAP bad len\n")); + orc = CONFREJ; + break; + } + if (!ao->neg_chap) { /* we don't want to do CHAP */ + LCPDEBUG(LOG_WARNING, ("lcp_reqci: Nak AUTHTYPE CHAP not allowed\n")); + orc = CONFNAK; /* NAK it and suggest PAP */ + PUTCHAR(CI_AUTHTYPE, nakp); + PUTCHAR(CILEN_SHORT, nakp); + PUTSHORT(PPP_PAP, nakp); + break; + } + GETCHAR(cichar, p); /* get digest type*/ + if (cichar != CHAP_DIGEST_MD5 +#if MSCHAP_SUPPORT + && cichar != CHAP_MICROSOFT +#endif + ) { + LCPDEBUG(LOG_WARNING, ("lcp_reqci: Nak AUTHTYPE CHAP digest=%d\n", (int)cichar)); + orc = CONFNAK; + PUTCHAR(CI_AUTHTYPE, nakp); + PUTCHAR(CILEN_CHAP, nakp); + PUTSHORT(PPP_CHAP, nakp); + PUTCHAR(ao->chap_mdtype, nakp); + break; + } +#if TRACELCP > 0 + snprintf(&traceBuf[traceNdx], sizeof(traceBuf), " CHAP %X,%d", cishort, (int)cichar); + traceNdx = strlen(traceBuf); +#endif + ho->chap_mdtype = cichar; /* save md type */ + ho->neg_chap = 1; + break; + } + + /* + * We don't recognize the protocol they're asking for. + * Nak it with something we're willing to do. + * (At this point we know ao->neg_upap || ao->neg_chap.) + */ + orc = CONFNAK; + PUTCHAR(CI_AUTHTYPE, nakp); + if (ao->neg_chap) { + LCPDEBUG(LOG_WARNING, ("lcp_reqci: Nak AUTHTYPE %d req CHAP\n", cishort)); + PUTCHAR(CILEN_CHAP, nakp); + PUTSHORT(PPP_CHAP, nakp); + PUTCHAR(ao->chap_mdtype, nakp); + } else { + LCPDEBUG(LOG_WARNING, ("lcp_reqci: Nak AUTHTYPE %d req PAP\n", cishort)); + PUTCHAR(CILEN_SHORT, nakp); + PUTSHORT(PPP_PAP, nakp); + } + break; + + case CI_QUALITY: + GETSHORT(cishort, p); + GETLONG(cilong, p); +#if TRACELCP > 0 + snprintf(&traceBuf[traceNdx], sizeof(traceBuf), " QUALITY (%x %x)", cishort, (unsigned int) cilong); + traceNdx = strlen(traceBuf); +#endif + + if (!ao->neg_lqr || + cilen != CILEN_LQR) { + orc = CONFREJ; + break; + } + + /* + * Check the protocol and the reporting period. + * XXX When should we Nak this, and what with? + */ + if (cishort != PPP_LQR) { + orc = CONFNAK; + PUTCHAR(CI_QUALITY, nakp); + PUTCHAR(CILEN_LQR, nakp); + PUTSHORT(PPP_LQR, nakp); + PUTLONG(ao->lqr_period, nakp); + break; + } + break; + + case CI_MAGICNUMBER: + if (!(ao->neg_magicnumber || go->neg_magicnumber) || + cilen != CILEN_LONG) { + orc = CONFREJ; + break; + } + GETLONG(cilong, p); +#if TRACELCP > 0 + snprintf(&traceBuf[traceNdx], sizeof(traceBuf), " MAGICNUMBER (%lX)", cilong); + traceNdx = strlen(traceBuf); +#endif + + /* + * He must have a different magic number. + */ + if (go->neg_magicnumber && + cilong == go->magicnumber) { + cilong = magic(); /* Don't put magic() inside macro! */ + orc = CONFNAK; + PUTCHAR(CI_MAGICNUMBER, nakp); + PUTCHAR(CILEN_LONG, nakp); + PUTLONG(cilong, nakp); + break; + } + ho->neg_magicnumber = 1; + ho->magicnumber = cilong; + break; + + + case CI_PCOMPRESSION: +#if TRACELCP > 0 + snprintf(&traceBuf[traceNdx], sizeof(traceBuf), " PCOMPRESSION"); + traceNdx = strlen(traceBuf); +#endif + if (!ao->neg_pcompression || + cilen != CILEN_VOID) { + orc = CONFREJ; + break; + } + ho->neg_pcompression = 1; + break; + + case CI_ACCOMPRESSION: +#if TRACELCP > 0 + snprintf(&traceBuf[traceNdx], sizeof(traceBuf), " ACCOMPRESSION"); + traceNdx = strlen(traceBuf); +#endif + if (!ao->neg_accompression || + cilen != CILEN_VOID) { + orc = CONFREJ; + break; + } + ho->neg_accompression = 1; + break; + + case CI_MRRU: +#if TRACELCP > 0 + snprintf(&traceBuf[traceNdx], sizeof(traceBuf), " CI_MRRU"); + traceNdx = strlen(traceBuf); +#endif + orc = CONFREJ; + break; + + case CI_SSNHF: +#if TRACELCP > 0 + snprintf(&traceBuf[traceNdx], sizeof(traceBuf), " CI_SSNHF"); + traceNdx = strlen(traceBuf); +#endif + orc = CONFREJ; + break; + + case CI_EPDISC: +#if TRACELCP > 0 + snprintf(&traceBuf[traceNdx], sizeof(traceBuf), " CI_EPDISC"); + traceNdx = strlen(traceBuf); +#endif + orc = CONFREJ; + break; + + default: +#if TRACELCP + snprintf(&traceBuf[traceNdx], sizeof(traceBuf), " unknown %d", citype); + traceNdx = strlen(traceBuf); +#endif + orc = CONFREJ; + break; + } + + endswitch: +#if TRACELCP + if (traceNdx >= 80 - 32) { + LCPDEBUG(LOG_INFO, ("lcp_reqci: rcvd%s\n", traceBuf)); + traceNdx = 0; + } +#endif + if (orc == CONFACK && /* Good CI */ + rc != CONFACK) { /* but prior CI wasnt? */ + continue; /* Don't send this one */ + } + + if (orc == CONFNAK) { /* Nak this CI? */ + if (reject_if_disagree /* Getting fed up with sending NAKs? */ + && citype != CI_MAGICNUMBER) { + orc = CONFREJ; /* Get tough if so */ + } else { + if (rc == CONFREJ) { /* Rejecting prior CI? */ + continue; /* Don't send this one */ + } + rc = CONFNAK; + } + } + if (orc == CONFREJ) { /* Reject this CI */ + rc = CONFREJ; + if (cip != rejp) { /* Need to move rejected CI? */ + BCOPY(cip, rejp, cilen); /* Move it */ + } + INCPTR(cilen, rejp); /* Update output pointer */ + } + } + + /* + * If we wanted to send additional NAKs (for unsent CIs), the + * code would go here. The extra NAKs would go at *nakp. + * At present there are no cases where we want to ask the + * peer to negotiate an option. + */ + + switch (rc) { + case CONFACK: + *lenp = (int)(next - inp); + break; + case CONFNAK: + /* + * Copy the Nak'd options from the nak_buffer to the caller's buffer. + */ + *lenp = (int)(nakp - nak_buffer); + BCOPY(nak_buffer, inp, *lenp); + break; + case CONFREJ: + *lenp = (int)(rejp - inp); + break; + } + +#if TRACELCP > 0 + if (traceNdx > 0) { + LCPDEBUG(LOG_INFO, ("lcp_reqci: %s\n", traceBuf)); + } +#endif + LCPDEBUG(LOG_INFO, ("lcp_reqci: returning CONF%s.\n", CODENAME(rc))); + return (rc); /* Return final code */ +} + + +/* + * lcp_up - LCP has come UP. + */ +static void +lcp_up(fsm *f) +{ + lcp_options *wo = &lcp_wantoptions[f->unit]; + lcp_options *ho = &lcp_hisoptions[f->unit]; + lcp_options *go = &lcp_gotoptions[f->unit]; + lcp_options *ao = &lcp_allowoptions[f->unit]; + + if (!go->neg_magicnumber) { + go->magicnumber = 0; + } + if (!ho->neg_magicnumber) { + ho->magicnumber = 0; + } + + /* + * Set our MTU to the smaller of the MTU we wanted and + * the MRU our peer wanted. If we negotiated an MRU, + * set our MRU to the larger of value we wanted and + * the value we got in the negotiation. + */ + ppp_send_config(f->unit, LWIP_MIN(ao->mru, (ho->neg_mru? ho->mru: PPP_MRU)), + (ho->neg_asyncmap? ho->asyncmap: 0xffffffffl), + ho->neg_pcompression, ho->neg_accompression); + /* + * If the asyncmap hasn't been negotiated, we really should + * set the receive asyncmap to ffffffff, but we set it to 0 + * for backwards contemptibility. + */ + ppp_recv_config(f->unit, (go->neg_mru? LWIP_MAX(wo->mru, go->mru): PPP_MRU), + (go->neg_asyncmap? go->asyncmap: 0x00000000), + go->neg_pcompression, go->neg_accompression); + + if (ho->neg_mru) { + peer_mru[f->unit] = ho->mru; + } + + lcp_echo_lowerup(f->unit); /* Enable echo messages */ + + link_established(f->unit); /* The link is up; authenticate now */ +} + + +/* + * lcp_down - LCP has gone DOWN. + * + * Alert other protocols. + */ +static void +lcp_down(fsm *f) +{ + lcp_options *go = &lcp_gotoptions[f->unit]; + + lcp_echo_lowerdown(f->unit); + + link_down(f->unit); + + ppp_send_config(f->unit, PPP_MRU, 0xffffffffl, 0, 0); + ppp_recv_config(f->unit, PPP_MRU, + (go->neg_asyncmap? go->asyncmap: 0x00000000), + go->neg_pcompression, go->neg_accompression); + peer_mru[f->unit] = PPP_MRU; +} + + +/* + * lcp_starting - LCP needs the lower layer up. + */ +static void +lcp_starting(fsm *f) +{ + link_required(f->unit); /* lwip: currently does nothing */ +} + + +/* + * lcp_finished - LCP has finished with the lower layer. + */ +static void +lcp_finished(fsm *f) +{ + link_terminated(f->unit); /* we are finished with the link */ +} + + +#if PPP_ADDITIONAL_CALLBACKS +/* + * print_string - print a readable representation of a string using + * printer. + */ +static void +print_string( char *p, int len, void (*printer) (void *, char *, ...), void *arg) +{ + int c; + + printer(arg, "\""); + for (; len > 0; --len) { + c = *p++; + if (' ' <= c && c <= '~') { + if (c == '\\' || c == '"') { + printer(arg, "\\"); + } + printer(arg, "%c", c); + } else { + switch (c) { + case '\n': + printer(arg, "\\n"); + break; + case '\r': + printer(arg, "\\r"); + break; + case '\t': + printer(arg, "\\t"); + break; + default: + printer(arg, "\\%.3o", c); + } + } + } + printer(arg, "\""); +} + + +/* + * lcp_printpkt - print the contents of an LCP packet. + */ +static char *lcp_codenames[] = { + "ConfReq", "ConfAck", "ConfNak", "ConfRej", + "TermReq", "TermAck", "CodeRej", "ProtRej", + "EchoReq", "EchoRep", "DiscReq" +}; + +static int +lcp_printpkt( u_char *p, int plen, void (*printer) (void *, char *, ...), void *arg) +{ + int code, id, len, olen; + u_char *pstart, *optend; + u_short cishort; + u32_t cilong; + + if (plen < HEADERLEN) { + return 0; + } + pstart = p; + GETCHAR(code, p); + GETCHAR(id, p); + GETSHORT(len, p); + if (len < HEADERLEN || len > plen) { + return 0; + } + + if (code >= 1 && code <= sizeof(lcp_codenames) / sizeof(char *)) { + printer(arg, " %s", lcp_codenames[code-1]); + } else { + printer(arg, " code=0x%x", code); + } + printer(arg, " id=0x%x", id); + len -= HEADERLEN; + switch (code) { + case CONFREQ: + case CONFACK: + case CONFNAK: + case CONFREJ: + /* print option list */ + while (len >= 2) { + GETCHAR(code, p); + GETCHAR(olen, p); + p -= 2; + if (olen < 2 || olen > len) { + break; + } + printer(arg, " <"); + len -= olen; + optend = p + olen; + switch (code) { + case CI_MRU: + if (olen == CILEN_SHORT) { + p += 2; + GETSHORT(cishort, p); + printer(arg, "mru %d", cishort); + } + break; + case CI_ASYNCMAP: + if (olen == CILEN_LONG) { + p += 2; + GETLONG(cilong, p); + printer(arg, "asyncmap 0x%lx", cilong); + } + break; + case CI_AUTHTYPE: + if (olen >= CILEN_SHORT) { + p += 2; + printer(arg, "auth "); + GETSHORT(cishort, p); + switch (cishort) { + case PPP_PAP: + printer(arg, "pap"); + break; + case PPP_CHAP: + printer(arg, "chap"); + break; + default: + printer(arg, "0x%x", cishort); + } + } + break; + case CI_QUALITY: + if (olen >= CILEN_SHORT) { + p += 2; + printer(arg, "quality "); + GETSHORT(cishort, p); + switch (cishort) { + case PPP_LQR: + printer(arg, "lqr"); + break; + default: + printer(arg, "0x%x", cishort); + } + } + break; + case CI_CALLBACK: + if (olen >= CILEN_CHAR) { + p += 2; + printer(arg, "callback "); + GETSHORT(cishort, p); + switch (cishort) { + case CBCP_OPT: + printer(arg, "CBCP"); + break; + default: + printer(arg, "0x%x", cishort); + } + } + break; + case CI_MAGICNUMBER: + if (olen == CILEN_LONG) { + p += 2; + GETLONG(cilong, p); + printer(arg, "magic 0x%x", cilong); + } + break; + case CI_PCOMPRESSION: + if (olen == CILEN_VOID) { + p += 2; + printer(arg, "pcomp"); + } + break; + case CI_ACCOMPRESSION: + if (olen == CILEN_VOID) { + p += 2; + printer(arg, "accomp"); + } + break; + } + while (p < optend) { + GETCHAR(code, p); + printer(arg, " %.2x", code); + } + printer(arg, ">"); + } + break; + + case TERMACK: + case TERMREQ: + if (len > 0 && *p >= ' ' && *p < 0x7f) { + printer(arg, " "); + print_string((char*)p, len, printer, arg); + p += len; + len = 0; + } + break; + + case ECHOREQ: + case ECHOREP: + case DISCREQ: + if (len >= 4) { + GETLONG(cilong, p); + printer(arg, " magic=0x%x", cilong); + p += 4; + len -= 4; + } + break; + } + + /* print the rest of the bytes in the packet */ + for (; len > 0; --len) { + GETCHAR(code, p); + printer(arg, " %.2x", code); + } + + return (int)(p - pstart); +} +#endif /* PPP_ADDITIONAL_CALLBACKS */ + +/* + * Time to shut down the link because there is nothing out there. + */ +static void +LcpLinkFailure (fsm *f) +{ + if (f->state == LS_OPENED) { + LCPDEBUG(LOG_INFO, ("No response to %d echo-requests\n", lcp_echos_pending)); + LCPDEBUG(LOG_NOTICE, ("Serial link appears to be disconnected.\n")); + lcp_close(f->unit, "Peer not responding"); + } +} + +/* + * Timer expired for the LCP echo requests from this process. + */ +static void +LcpEchoCheck (fsm *f) +{ + LcpSendEchoRequest (f); + + /* + * Start the timer for the next interval. + */ + LWIP_ASSERT("lcp_echo_timer_running == 0", lcp_echo_timer_running == 0); + + TIMEOUT (LcpEchoTimeout, f, lcp_echo_interval); + lcp_echo_timer_running = 1; +} + +/* + * LcpEchoTimeout - Timer expired on the LCP echo + */ +static void +LcpEchoTimeout (void *arg) +{ + if (lcp_echo_timer_running != 0) { + lcp_echo_timer_running = 0; + LcpEchoCheck ((fsm *) arg); + } +} + +/* + * LcpEchoReply - LCP has received a reply to the echo + */ +static void +lcp_received_echo_reply (fsm *f, int id, u_char *inp, int len) +{ + u32_t magic; + + LWIP_UNUSED_ARG(id); + + /* Check the magic number - don't count replies from ourselves. */ + if (len < 4) { + LCPDEBUG(LOG_WARNING, ("lcp: received short Echo-Reply, length %d\n", len)); + return; + } + GETLONG(magic, inp); + if (lcp_gotoptions[f->unit].neg_magicnumber && magic == lcp_gotoptions[f->unit].magicnumber) { + LCPDEBUG(LOG_WARNING, ("appear to have received our own echo-reply!\n")); + return; + } + + /* Reset the number of outstanding echo frames */ + lcp_echos_pending = 0; +} + +/* + * LcpSendEchoRequest - Send an echo request frame to the peer + */ +static void +LcpSendEchoRequest (fsm *f) +{ + u32_t lcp_magic; + u_char pkt[4], *pktp; + + /* + * Detect the failure of the peer at this point. + */ + if (lcp_echo_fails != 0) { + if (lcp_echos_pending >= lcp_echo_fails) { + LcpLinkFailure(f); + lcp_echos_pending = 0; + } + } + + /* + * Make and send the echo request frame. + */ + if (f->state == LS_OPENED) { + lcp_magic = lcp_gotoptions[f->unit].magicnumber; + pktp = pkt; + PUTLONG(lcp_magic, pktp); + fsm_sdata(f, ECHOREQ, (u_char)(lcp_echo_number++ & 0xFF), pkt, (int)(pktp - pkt)); + ++lcp_echos_pending; + } +} + +/* + * lcp_echo_lowerup - Start the timer for the LCP frame + */ + +static void +lcp_echo_lowerup (int unit) +{ + fsm *f = &lcp_fsm[unit]; + + /* Clear the parameters for generating echo frames */ + lcp_echos_pending = 0; + lcp_echo_number = 0; + lcp_echo_timer_running = 0; + + /* If a timeout interval is specified then start the timer */ + if (lcp_echo_interval != 0) { + LcpEchoCheck (f); + } +} + +/* + * lcp_echo_lowerdown - Stop the timer for the LCP frame + */ + +static void +lcp_echo_lowerdown (int unit) +{ + fsm *f = &lcp_fsm[unit]; + + if (lcp_echo_timer_running != 0) { + UNTIMEOUT (LcpEchoTimeout, f); + lcp_echo_timer_running = 0; + } +} + +#endif /* PPP_SUPPORT */ diff --git a/features/unsupported/net/lwip/lwip/netif/ppp/lcp.h b/features/unsupported/net/lwip/lwip/netif/ppp/lcp.h new file mode 100644 index 00000000000..b9201eeb50b --- /dev/null +++ b/features/unsupported/net/lwip/lwip/netif/ppp/lcp.h @@ -0,0 +1,151 @@ +/***************************************************************************** +* lcp.h - Network Link Control Protocol header file. +* +* Copyright (c) 2003 by Marc Boucher, Services Informatiques (MBSI) inc. +* portions Copyright (c) 1997 Global Election Systems Inc. +* +* The authors hereby grant permission to use, copy, modify, distribute, +* and license this software and its documentation for any purpose, provided +* that existing copyright notices are retained in all copies and that this +* notice and the following disclaimer are included verbatim in any +* distributions. No written agreement, license, or royalty fee is required +* for any of the authorized uses. +* +* THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS *AS IS* AND ANY EXPRESS OR +* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +* IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT +* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +****************************************************************************** +* REVISION HISTORY +* +* 03-01-01 Marc Boucher +* Ported to lwIP. +* 97-11-05 Guy Lancaster , Global Election Systems Inc. +* Original derived from BSD codes. +*****************************************************************************/ +/* + * lcp.h - Link Control Protocol definitions. + * + * Copyright (c) 1989 Carnegie Mellon University. + * All rights reserved. + * + * Redistribution and use in source and binary forms are permitted + * provided that the above copyright notice and this paragraph are + * duplicated in all such forms and that any documentation, + * advertising materials, and other materials related to such + * distribution and use acknowledge that the software was developed + * by Carnegie Mellon University. The name of the + * University may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED + * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. + * + * $Id: lcp.h,v 1.4 2010/01/18 20:49:43 goldsimon Exp $ + */ + +#ifndef LCP_H +#define LCP_H +/* + * Options. + */ +#define CI_MRU 1 /* Maximum Receive Unit */ +#define CI_ASYNCMAP 2 /* Async Control Character Map */ +#define CI_AUTHTYPE 3 /* Authentication Type */ +#define CI_QUALITY 4 /* Quality Protocol */ +#define CI_MAGICNUMBER 5 /* Magic Number */ +#define CI_PCOMPRESSION 7 /* Protocol Field Compression */ +#define CI_ACCOMPRESSION 8 /* Address/Control Field Compression */ +#define CI_CALLBACK 13 /* callback */ +#define CI_MRRU 17 /* max reconstructed receive unit; multilink */ +#define CI_SSNHF 18 /* short sequence numbers for multilink */ +#define CI_EPDISC 19 /* endpoint discriminator */ + +/* + * LCP-specific packet types (code numbers). + */ +#define PROTREJ 8 /* Protocol Reject */ +#define ECHOREQ 9 /* Echo Request */ +#define ECHOREP 10 /* Echo Reply */ +#define DISCREQ 11 /* Discard Request */ +#define CBCP_OPT 6 /* Use callback control protocol */ + +/* + * The state of options is described by an lcp_options structure. + */ +typedef struct lcp_options { + u_int passive : 1; /* Don't die if we don't get a response */ + u_int silent : 1; /* Wait for the other end to start first */ + u_int restart : 1; /* Restart vs. exit after close */ + u_int neg_mru : 1; /* Negotiate the MRU? */ + u_int neg_asyncmap : 1; /* Negotiate the async map? */ + u_int neg_upap : 1; /* Ask for UPAP authentication? */ + u_int neg_chap : 1; /* Ask for CHAP authentication? */ + u_int neg_magicnumber : 1; /* Ask for magic number? */ + u_int neg_pcompression : 1; /* HDLC Protocol Field Compression? */ + u_int neg_accompression : 1; /* HDLC Address/Control Field Compression? */ + u_int neg_lqr : 1; /* Negotiate use of Link Quality Reports */ + u_int neg_cbcp : 1; /* Negotiate use of CBCP */ +#ifdef PPP_MULTILINK + u_int neg_mrru : 1; /* Negotiate multilink MRRU */ + u_int neg_ssnhf : 1; /* Negotiate short sequence numbers */ + u_int neg_endpoint : 1; /* Negotiate endpoint discriminator */ +#endif + u_short mru; /* Value of MRU */ +#ifdef PPP_MULTILINK + u_short mrru; /* Value of MRRU, and multilink enable */ +#endif + u_char chap_mdtype; /* which MD type (hashing algorithm) */ + u32_t asyncmap; /* Value of async map */ + u32_t magicnumber; + int numloops; /* Number of loops during magic number neg. */ + u32_t lqr_period; /* Reporting period for LQR 1/100ths second */ +#ifdef PPP_MULTILINK + struct epdisc endpoint; /* endpoint discriminator */ +#endif +} lcp_options; + +/* + * Values for phase from BSD pppd.h based on RFC 1661. + */ +typedef enum { + PHASE_DEAD = 0, + PHASE_INITIALIZE, + PHASE_ESTABLISH, + PHASE_AUTHENTICATE, + PHASE_CALLBACK, + PHASE_NETWORK, + PHASE_TERMINATE +} LinkPhase; + + + +extern LinkPhase lcp_phase[NUM_PPP]; /* Phase of link session (RFC 1661) */ +extern lcp_options lcp_wantoptions[]; +extern lcp_options lcp_gotoptions[]; +extern lcp_options lcp_allowoptions[]; +extern lcp_options lcp_hisoptions[]; +extern ext_accm xmit_accm[]; + + +void lcp_init (int); +void lcp_open (int); +void lcp_close (int, char *); +void lcp_lowerup (int); +void lcp_lowerdown(int); +void lcp_sprotrej (int, u_char *, int); /* send protocol reject */ + +extern struct protent lcp_protent; + +/* Default number of times we receive our magic number from the peer + before deciding the link is looped-back. */ +#define DEFLOOPBACKFAIL 10 + +#endif /* LCP_H */ diff --git a/features/unsupported/net/lwip/lwip/netif/ppp/magic.c b/features/unsupported/net/lwip/lwip/netif/ppp/magic.c new file mode 100644 index 00000000000..3901330895a --- /dev/null +++ b/features/unsupported/net/lwip/lwip/netif/ppp/magic.c @@ -0,0 +1,80 @@ +/***************************************************************************** +* magic.c - Network Random Number Generator program file. +* +* Copyright (c) 2003 by Marc Boucher, Services Informatiques (MBSI) inc. +* portions Copyright (c) 1997 by Global Election Systems Inc. +* +* The authors hereby grant permission to use, copy, modify, distribute, +* and license this software and its documentation for any purpose, provided +* that existing copyright notices are retained in all copies and that this +* notice and the following disclaimer are included verbatim in any +* distributions. No written agreement, license, or royalty fee is required +* for any of the authorized uses. +* +* THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS *AS IS* AND ANY EXPRESS OR +* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +* IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT +* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +****************************************************************************** +* REVISION HISTORY +* +* 03-01-01 Marc Boucher +* Ported to lwIP. +* 97-12-04 Guy Lancaster , Global Election Systems Inc. +* Original based on BSD magic.c. +*****************************************************************************/ +/* + * magic.c - PPP Magic Number routines. + * + * Copyright (c) 1989 Carnegie Mellon University. + * All rights reserved. + * + * Redistribution and use in source and binary forms are permitted + * provided that the above copyright notice and this paragraph are + * duplicated in all such forms and that any documentation, + * advertising materials, and other materials related to such + * distribution and use acknowledge that the software was developed + * by Carnegie Mellon University. The name of the + * University may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED + * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. + */ + +#include "lwip/opt.h" + +#if PPP_SUPPORT + +#include "ppp.h" +#include "randm.h" +#include "magic.h" + + +/* + * magicInit - Initialize the magic number generator. + * + * Since we use another random number generator that has its own + * initialization, we do nothing here. + */ +void magicInit() +{ + return; +} + +/* + * magic - Returns the next magic number. + */ +u32_t magic() +{ + return avRandom(); +} + +#endif /* PPP_SUPPORT */ diff --git a/features/unsupported/net/lwip/lwip/netif/ppp/magic.h b/features/unsupported/net/lwip/lwip/netif/ppp/magic.h new file mode 100644 index 00000000000..eba70d20b00 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/netif/ppp/magic.h @@ -0,0 +1,63 @@ +/***************************************************************************** +* magic.h - Network Random Number Generator header file. +* +* Copyright (c) 2003 by Marc Boucher, Services Informatiques (MBSI) inc. +* portions Copyright (c) 1997 Global Election Systems Inc. +* +* The authors hereby grant permission to use, copy, modify, distribute, +* and license this software and its documentation for any purpose, provided +* that existing copyright notices are retained in all copies and that this +* notice and the following disclaimer are included verbatim in any +* distributions. No written agreement, license, or royalty fee is required +* for any of the authorized uses. +* +* THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS *AS IS* AND ANY EXPRESS OR +* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +* IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT +* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +****************************************************************************** +* REVISION HISTORY +* +* 03-01-01 Marc Boucher +* Ported to lwIP. +* 97-12-04 Guy Lancaster , Global Election Systems Inc. +* Original derived from BSD codes. +*****************************************************************************/ +/* + * magic.h - PPP Magic Number definitions. + * + * Copyright (c) 1989 Carnegie Mellon University. + * All rights reserved. + * + * Redistribution and use in source and binary forms are permitted + * provided that the above copyright notice and this paragraph are + * duplicated in all such forms and that any documentation, + * advertising materials, and other materials related to such + * distribution and use acknowledge that the software was developed + * by Carnegie Mellon University. The name of the + * University may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED + * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. + * + * $Id: magic.h,v 1.3 2010/01/18 20:49:43 goldsimon Exp $ + */ + +#ifndef MAGIC_H +#define MAGIC_H + +/* Initialize the magic number generator */ +void magicInit(void); + +/* Returns the next magic number */ +u32_t magic(void); + +#endif /* MAGIC_H */ diff --git a/features/unsupported/net/lwip/lwip/netif/ppp/md5.c b/features/unsupported/net/lwip/lwip/netif/ppp/md5.c new file mode 100644 index 00000000000..3cb69e2b065 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/netif/ppp/md5.c @@ -0,0 +1,320 @@ +/* + *********************************************************************** + ** md5.c -- the source code for MD5 routines ** + ** RSA Data Security, Inc. MD5 Message-Digest Algorithm ** + ** Created: 2/17/90 RLR ** + ** Revised: 1/91 SRD,AJ,BSK,JT Reference C ver., 7/10 constant corr. ** + *********************************************************************** + */ + +/* + *********************************************************************** + ** Copyright (C) 1990, RSA Data Security, Inc. All rights reserved. ** + ** ** + ** License to copy and use this software is granted provided that ** + ** it is identified as the "RSA Data Security, Inc. MD5 Message- ** + ** Digest Algorithm" in all material mentioning or referencing this ** + ** software or this function. ** + ** ** + ** License is also granted to make and use derivative works ** + ** provided that such works are identified as "derived from the RSA ** + ** Data Security, Inc. MD5 Message-Digest Algorithm" in all ** + ** material mentioning or referencing the derived work. ** + ** ** + ** RSA Data Security, Inc. makes no representations concerning ** + ** either the merchantability of this software or the suitability ** + ** of this software for any particular purpose. It is provided "as ** + ** is" without express or implied warranty of any kind. ** + ** ** + ** These notices must be retained in any copies of any part of this ** + ** documentation and/or software. ** + *********************************************************************** + */ + +#include "lwip/opt.h" + +#if PPP_SUPPORT /* don't build if not configured for use in lwipopts.h */ + +#if CHAP_SUPPORT || MD5_SUPPORT + +#include "ppp.h" +#include "pppdebug.h" + +#include "md5.h" + +#include + +/* + *********************************************************************** + ** Message-digest routines: ** + ** To form the message digest for a message M ** + ** (1) Initialize a context buffer mdContext using MD5Init ** + ** (2) Call MD5Update on mdContext and M ** + ** (3) Call MD5Final on mdContext ** + ** The message digest is now in mdContext->digest[0...15] ** + *********************************************************************** + */ + +/* forward declaration */ +static void Transform (u32_t *buf, u32_t *in); + +static unsigned char PADDING[64] = { + 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +}; + +/* F, G, H and I are basic MD5 functions */ +#define F(x, y, z) (((x) & (y)) | ((~x) & (z))) +#define G(x, y, z) (((x) & (z)) | ((y) & (~z))) +#define H(x, y, z) ((x) ^ (y) ^ (z)) +#define I(x, y, z) ((y) ^ ((x) | (~z))) + +/* ROTATE_LEFT rotates x left n bits */ +#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32-(n)))) + +/* FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4 */ +/* Rotation is separate from addition to prevent recomputation */ +#define FF(a, b, c, d, x, s, ac) \ + {(a) += F ((b), (c), (d)) + (x) + (u32_t)(ac); \ + (a) = ROTATE_LEFT ((a), (s)); \ + (a) += (b); \ + } +#define GG(a, b, c, d, x, s, ac) \ + {(a) += G ((b), (c), (d)) + (x) + (u32_t)(ac); \ + (a) = ROTATE_LEFT ((a), (s)); \ + (a) += (b); \ + } +#define HH(a, b, c, d, x, s, ac) \ + {(a) += H ((b), (c), (d)) + (x) + (u32_t)(ac); \ + (a) = ROTATE_LEFT ((a), (s)); \ + (a) += (b); \ + } +#define II(a, b, c, d, x, s, ac) \ + {(a) += I ((b), (c), (d)) + (x) + (u32_t)(ac); \ + (a) = ROTATE_LEFT ((a), (s)); \ + (a) += (b); \ + } + +#ifdef __STDC__ +#define UL(x) x##UL +#else +#ifdef WIN32 +#define UL(x) x##UL +#else +#define UL(x) x +#endif +#endif + +/* The routine MD5Init initializes the message-digest context + mdContext. All fields are set to zero. + */ +void +MD5Init (MD5_CTX *mdContext) +{ + mdContext->i[0] = mdContext->i[1] = (u32_t)0; + + /* Load magic initialization constants. */ + mdContext->buf[0] = (u32_t)0x67452301UL; + mdContext->buf[1] = (u32_t)0xefcdab89UL; + mdContext->buf[2] = (u32_t)0x98badcfeUL; + mdContext->buf[3] = (u32_t)0x10325476UL; +} + +/* The routine MD5Update updates the message-digest context to + account for the presence of each of the characters inBuf[0..inLen-1] + in the message whose digest is being computed. + */ +void +MD5Update(MD5_CTX *mdContext, unsigned char *inBuf, unsigned int inLen) +{ + u32_t in[16]; + int mdi; + unsigned int i, ii; + +#if 0 + PPPDEBUG(LOG_INFO, ("MD5Update: %u:%.*H\n", inLen, LWIP_MIN(inLen, 20) * 2, inBuf)); + PPPDEBUG(LOG_INFO, ("MD5Update: %u:%s\n", inLen, inBuf)); +#endif + + /* compute number of bytes mod 64 */ + mdi = (int)((mdContext->i[0] >> 3) & 0x3F); + + /* update number of bits */ + if ((mdContext->i[0] + ((u32_t)inLen << 3)) < mdContext->i[0]) { + mdContext->i[1]++; + } + mdContext->i[0] += ((u32_t)inLen << 3); + mdContext->i[1] += ((u32_t)inLen >> 29); + + while (inLen--) { + /* add new character to buffer, increment mdi */ + mdContext->in[mdi++] = *inBuf++; + + /* transform if necessary */ + if (mdi == 0x40) { + for (i = 0, ii = 0; i < 16; i++, ii += 4) { + in[i] = (((u32_t)mdContext->in[ii+3]) << 24) | + (((u32_t)mdContext->in[ii+2]) << 16) | + (((u32_t)mdContext->in[ii+1]) << 8) | + ((u32_t)mdContext->in[ii]); + } + Transform (mdContext->buf, in); + mdi = 0; + } + } +} + +/* The routine MD5Final terminates the message-digest computation and + ends with the desired message digest in mdContext->digest[0...15]. + */ +void +MD5Final (unsigned char hash[], MD5_CTX *mdContext) +{ + u32_t in[16]; + int mdi; + unsigned int i, ii; + unsigned int padLen; + + /* save number of bits */ + in[14] = mdContext->i[0]; + in[15] = mdContext->i[1]; + + /* compute number of bytes mod 64 */ + mdi = (int)((mdContext->i[0] >> 3) & 0x3F); + + /* pad out to 56 mod 64 */ + padLen = (mdi < 56) ? (56 - mdi) : (120 - mdi); + MD5Update (mdContext, PADDING, padLen); + + /* append length in bits and transform */ + for (i = 0, ii = 0; i < 14; i++, ii += 4) { + in[i] = (((u32_t)mdContext->in[ii+3]) << 24) | + (((u32_t)mdContext->in[ii+2]) << 16) | + (((u32_t)mdContext->in[ii+1]) << 8) | + ((u32_t)mdContext->in[ii]); + } + Transform (mdContext->buf, in); + + /* store buffer in digest */ + for (i = 0, ii = 0; i < 4; i++, ii += 4) { + mdContext->digest[ii] = (unsigned char)(mdContext->buf[i] & 0xFF); + mdContext->digest[ii+1] = + (unsigned char)((mdContext->buf[i] >> 8) & 0xFF); + mdContext->digest[ii+2] = + (unsigned char)((mdContext->buf[i] >> 16) & 0xFF); + mdContext->digest[ii+3] = + (unsigned char)((mdContext->buf[i] >> 24) & 0xFF); + } + SMEMCPY(hash, mdContext->digest, 16); +} + +/* Basic MD5 step. Transforms buf based on in. + */ +static void +Transform (u32_t *buf, u32_t *in) +{ + u32_t a = buf[0], b = buf[1], c = buf[2], d = buf[3]; + + /* Round 1 */ +#define S11 7 +#define S12 12 +#define S13 17 +#define S14 22 + FF ( a, b, c, d, in[ 0], S11, UL(3614090360)); /* 1 */ + FF ( d, a, b, c, in[ 1], S12, UL(3905402710)); /* 2 */ + FF ( c, d, a, b, in[ 2], S13, UL( 606105819)); /* 3 */ + FF ( b, c, d, a, in[ 3], S14, UL(3250441966)); /* 4 */ + FF ( a, b, c, d, in[ 4], S11, UL(4118548399)); /* 5 */ + FF ( d, a, b, c, in[ 5], S12, UL(1200080426)); /* 6 */ + FF ( c, d, a, b, in[ 6], S13, UL(2821735955)); /* 7 */ + FF ( b, c, d, a, in[ 7], S14, UL(4249261313)); /* 8 */ + FF ( a, b, c, d, in[ 8], S11, UL(1770035416)); /* 9 */ + FF ( d, a, b, c, in[ 9], S12, UL(2336552879)); /* 10 */ + FF ( c, d, a, b, in[10], S13, UL(4294925233)); /* 11 */ + FF ( b, c, d, a, in[11], S14, UL(2304563134)); /* 12 */ + FF ( a, b, c, d, in[12], S11, UL(1804603682)); /* 13 */ + FF ( d, a, b, c, in[13], S12, UL(4254626195)); /* 14 */ + FF ( c, d, a, b, in[14], S13, UL(2792965006)); /* 15 */ + FF ( b, c, d, a, in[15], S14, UL(1236535329)); /* 16 */ + + /* Round 2 */ +#define S21 5 +#define S22 9 +#define S23 14 +#define S24 20 + GG ( a, b, c, d, in[ 1], S21, UL(4129170786)); /* 17 */ + GG ( d, a, b, c, in[ 6], S22, UL(3225465664)); /* 18 */ + GG ( c, d, a, b, in[11], S23, UL( 643717713)); /* 19 */ + GG ( b, c, d, a, in[ 0], S24, UL(3921069994)); /* 20 */ + GG ( a, b, c, d, in[ 5], S21, UL(3593408605)); /* 21 */ + GG ( d, a, b, c, in[10], S22, UL( 38016083)); /* 22 */ + GG ( c, d, a, b, in[15], S23, UL(3634488961)); /* 23 */ + GG ( b, c, d, a, in[ 4], S24, UL(3889429448)); /* 24 */ + GG ( a, b, c, d, in[ 9], S21, UL( 568446438)); /* 25 */ + GG ( d, a, b, c, in[14], S22, UL(3275163606)); /* 26 */ + GG ( c, d, a, b, in[ 3], S23, UL(4107603335)); /* 27 */ + GG ( b, c, d, a, in[ 8], S24, UL(1163531501)); /* 28 */ + GG ( a, b, c, d, in[13], S21, UL(2850285829)); /* 29 */ + GG ( d, a, b, c, in[ 2], S22, UL(4243563512)); /* 30 */ + GG ( c, d, a, b, in[ 7], S23, UL(1735328473)); /* 31 */ + GG ( b, c, d, a, in[12], S24, UL(2368359562)); /* 32 */ + + /* Round 3 */ +#define S31 4 +#define S32 11 +#define S33 16 +#define S34 23 + HH ( a, b, c, d, in[ 5], S31, UL(4294588738)); /* 33 */ + HH ( d, a, b, c, in[ 8], S32, UL(2272392833)); /* 34 */ + HH ( c, d, a, b, in[11], S33, UL(1839030562)); /* 35 */ + HH ( b, c, d, a, in[14], S34, UL(4259657740)); /* 36 */ + HH ( a, b, c, d, in[ 1], S31, UL(2763975236)); /* 37 */ + HH ( d, a, b, c, in[ 4], S32, UL(1272893353)); /* 38 */ + HH ( c, d, a, b, in[ 7], S33, UL(4139469664)); /* 39 */ + HH ( b, c, d, a, in[10], S34, UL(3200236656)); /* 40 */ + HH ( a, b, c, d, in[13], S31, UL( 681279174)); /* 41 */ + HH ( d, a, b, c, in[ 0], S32, UL(3936430074)); /* 42 */ + HH ( c, d, a, b, in[ 3], S33, UL(3572445317)); /* 43 */ + HH ( b, c, d, a, in[ 6], S34, UL( 76029189)); /* 44 */ + HH ( a, b, c, d, in[ 9], S31, UL(3654602809)); /* 45 */ + HH ( d, a, b, c, in[12], S32, UL(3873151461)); /* 46 */ + HH ( c, d, a, b, in[15], S33, UL( 530742520)); /* 47 */ + HH ( b, c, d, a, in[ 2], S34, UL(3299628645)); /* 48 */ + + /* Round 4 */ +#define S41 6 +#define S42 10 +#define S43 15 +#define S44 21 + II ( a, b, c, d, in[ 0], S41, UL(4096336452)); /* 49 */ + II ( d, a, b, c, in[ 7], S42, UL(1126891415)); /* 50 */ + II ( c, d, a, b, in[14], S43, UL(2878612391)); /* 51 */ + II ( b, c, d, a, in[ 5], S44, UL(4237533241)); /* 52 */ + II ( a, b, c, d, in[12], S41, UL(1700485571)); /* 53 */ + II ( d, a, b, c, in[ 3], S42, UL(2399980690)); /* 54 */ + II ( c, d, a, b, in[10], S43, UL(4293915773)); /* 55 */ + II ( b, c, d, a, in[ 1], S44, UL(2240044497)); /* 56 */ + II ( a, b, c, d, in[ 8], S41, UL(1873313359)); /* 57 */ + II ( d, a, b, c, in[15], S42, UL(4264355552)); /* 58 */ + II ( c, d, a, b, in[ 6], S43, UL(2734768916)); /* 59 */ + II ( b, c, d, a, in[13], S44, UL(1309151649)); /* 60 */ + II ( a, b, c, d, in[ 4], S41, UL(4149444226)); /* 61 */ + II ( d, a, b, c, in[11], S42, UL(3174756917)); /* 62 */ + II ( c, d, a, b, in[ 2], S43, UL( 718787259)); /* 63 */ + II ( b, c, d, a, in[ 9], S44, UL(3951481745)); /* 64 */ + + buf[0] += a; + buf[1] += b; + buf[2] += c; + buf[3] += d; +} + +#endif /* CHAP_SUPPORT || MD5_SUPPORT */ + +#endif /* PPP_SUPPORT */ diff --git a/features/unsupported/net/lwip/lwip/netif/ppp/md5.h b/features/unsupported/net/lwip/lwip/netif/ppp/md5.h new file mode 100644 index 00000000000..e129533f386 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/netif/ppp/md5.h @@ -0,0 +1,55 @@ +/* + *********************************************************************** + ** md5.h -- header file for implementation of MD5 ** + ** RSA Data Security, Inc. MD5 Message-Digest Algorithm ** + ** Created: 2/17/90 RLR ** + ** Revised: 12/27/90 SRD,AJ,BSK,JT Reference C version ** + ** Revised (for MD5): RLR 4/27/91 ** + ** -- G modified to have y&~z instead of y&z ** + ** -- FF, GG, HH modified to add in last register done ** + ** -- Access pattern: round 2 works mod 5, round 3 works mod 3 ** + ** -- distinct additive constant for each step ** + ** -- round 4 added, working mod 7 ** + *********************************************************************** + */ + +/* + *********************************************************************** + ** Copyright (C) 1990, RSA Data Security, Inc. All rights reserved. ** + ** ** + ** License to copy and use this software is granted provided that ** + ** it is identified as the "RSA Data Security, Inc. MD5 Message- ** + ** Digest Algorithm" in all material mentioning or referencing this ** + ** software or this function. ** + ** ** + ** License is also granted to make and use derivative works ** + ** provided that such works are identified as "derived from the RSA ** + ** Data Security, Inc. MD5 Message-Digest Algorithm" in all ** + ** material mentioning or referencing the derived work. ** + ** ** + ** RSA Data Security, Inc. makes no representations concerning ** + ** either the merchantability of this software or the suitability ** + ** of this software for any particular purpose. It is provided "as ** + ** is" without express or implied warranty of any kind. ** + ** ** + ** These notices must be retained in any copies of any part of this ** + ** documentation and/or software. ** + *********************************************************************** + */ + +#ifndef MD5_H +#define MD5_H + +/* Data structure for MD5 (Message-Digest) computation */ +typedef struct { + u32_t i[2]; /* number of _bits_ handled mod 2^64 */ + u32_t buf[4]; /* scratch buffer */ + unsigned char in[64]; /* input buffer */ + unsigned char digest[16]; /* actual digest after MD5Final call */ +} MD5_CTX; + +void MD5Init ( MD5_CTX *mdContext); +void MD5Update( MD5_CTX *mdContext, unsigned char *inBuf, unsigned int inLen); +void MD5Final ( unsigned char hash[], MD5_CTX *mdContext); + +#endif /* MD5_H */ diff --git a/features/unsupported/net/lwip/lwip/netif/ppp/pap.c b/features/unsupported/net/lwip/lwip/netif/ppp/pap.c new file mode 100644 index 00000000000..ac44e6464ce --- /dev/null +++ b/features/unsupported/net/lwip/lwip/netif/ppp/pap.c @@ -0,0 +1,628 @@ +/***************************************************************************** +* pap.c - Network Password Authentication Protocol program file. +* +* Copyright (c) 2003 by Marc Boucher, Services Informatiques (MBSI) inc. +* portions Copyright (c) 1997 by Global Election Systems Inc. +* +* The authors hereby grant permission to use, copy, modify, distribute, +* and license this software and its documentation for any purpose, provided +* that existing copyright notices are retained in all copies and that this +* notice and the following disclaimer are included verbatim in any +* distributions. No written agreement, license, or royalty fee is required +* for any of the authorized uses. +* +* THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS *AS IS* AND ANY EXPRESS OR +* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +* IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT +* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +****************************************************************************** +* REVISION HISTORY +* +* 03-01-01 Marc Boucher +* Ported to lwIP. +* 97-12-12 Guy Lancaster , Global Election Systems Inc. +* Original. +*****************************************************************************/ +/* + * upap.c - User/Password Authentication Protocol. + * + * Copyright (c) 1989 Carnegie Mellon University. + * All rights reserved. + * + * Redistribution and use in source and binary forms are permitted + * provided that the above copyright notice and this paragraph are + * duplicated in all such forms and that any documentation, + * advertising materials, and other materials related to such + * distribution and use acknowledge that the software was developed + * by Carnegie Mellon University. The name of the + * University may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED + * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. + */ + +#include "lwip/opt.h" + +#if PPP_SUPPORT /* don't build if not configured for use in lwipopts.h */ + +#if PAP_SUPPORT /* don't build if not configured for use in lwipopts.h */ + +#include "ppp.h" +#include "pppdebug.h" + +#include "auth.h" +#include "pap.h" + +#include + +#if 0 /* UNUSED */ +static bool hide_password = 1; + +/* + * Command-line options. + */ +static option_t pap_option_list[] = { + { "hide-password", o_bool, &hide_password, + "Don't output passwords to log", 1 }, + { "show-password", o_bool, &hide_password, + "Show password string in debug log messages", 0 }, + { "pap-restart", o_int, &upap[0].us_timeouttime, + "Set retransmit timeout for PAP" }, + { "pap-max-authreq", o_int, &upap[0].us_maxtransmits, + "Set max number of transmissions for auth-reqs" }, + { "pap-timeout", o_int, &upap[0].us_reqtimeout, + "Set time limit for peer PAP authentication" }, + { NULL } +}; +#endif + +/* + * Protocol entry points. + */ +static void upap_init (int); +static void upap_lowerup (int); +static void upap_lowerdown (int); +static void upap_input (int, u_char *, int); +static void upap_protrej (int); +#if PPP_ADDITIONAL_CALLBACKS +static int upap_printpkt (u_char *, int, void (*)(void *, char *, ...), void *); +#endif /* PPP_ADDITIONAL_CALLBACKS */ + +struct protent pap_protent = { + PPP_PAP, + upap_init, + upap_input, + upap_protrej, + upap_lowerup, + upap_lowerdown, + NULL, + NULL, +#if PPP_ADDITIONAL_CALLBACKS + upap_printpkt, + NULL, +#endif /* PPP_ADDITIONAL_CALLBACKS */ + 1, + "PAP", +#if PPP_ADDITIONAL_CALLBACKS + NULL, + NULL, + NULL +#endif /* PPP_ADDITIONAL_CALLBACKS */ +}; + +upap_state upap[NUM_PPP]; /* UPAP state; one for each unit */ + +static void upap_timeout (void *); +static void upap_reqtimeout(void *); +static void upap_rauthreq (upap_state *, u_char *, u_char, int); +static void upap_rauthack (upap_state *, u_char *, int, int); +static void upap_rauthnak (upap_state *, u_char *, int, int); +static void upap_sauthreq (upap_state *); +static void upap_sresp (upap_state *, u_char, u_char, char *, int); + + +/* + * upap_init - Initialize a UPAP unit. + */ +static void +upap_init(int unit) +{ + upap_state *u = &upap[unit]; + + UPAPDEBUG(LOG_INFO, ("upap_init: %d\n", unit)); + u->us_unit = unit; + u->us_user = NULL; + u->us_userlen = 0; + u->us_passwd = NULL; + u->us_passwdlen = 0; + u->us_clientstate = UPAPCS_INITIAL; + u->us_serverstate = UPAPSS_INITIAL; + u->us_id = 0; + u->us_timeouttime = UPAP_DEFTIMEOUT; + u->us_maxtransmits = 10; + u->us_reqtimeout = UPAP_DEFREQTIME; +} + +/* + * upap_authwithpeer - Authenticate us with our peer (start client). + * + * Set new state and send authenticate's. + */ +void +upap_authwithpeer(int unit, char *user, char *password) +{ + upap_state *u = &upap[unit]; + + UPAPDEBUG(LOG_INFO, ("upap_authwithpeer: %d user=%s password=%s s=%d\n", + unit, user, password, u->us_clientstate)); + + /* Save the username and password we're given */ + u->us_user = user; + u->us_userlen = (int)strlen(user); + u->us_passwd = password; + u->us_passwdlen = (int)strlen(password); + + u->us_transmits = 0; + + /* Lower layer up yet? */ + if (u->us_clientstate == UPAPCS_INITIAL || + u->us_clientstate == UPAPCS_PENDING) { + u->us_clientstate = UPAPCS_PENDING; + return; + } + + upap_sauthreq(u); /* Start protocol */ +} + + +/* + * upap_authpeer - Authenticate our peer (start server). + * + * Set new state. + */ +void +upap_authpeer(int unit) +{ + upap_state *u = &upap[unit]; + + /* Lower layer up yet? */ + if (u->us_serverstate == UPAPSS_INITIAL || + u->us_serverstate == UPAPSS_PENDING) { + u->us_serverstate = UPAPSS_PENDING; + return; + } + + u->us_serverstate = UPAPSS_LISTEN; + if (u->us_reqtimeout > 0) { + TIMEOUT(upap_reqtimeout, u, u->us_reqtimeout); + } +} + +/* + * upap_timeout - Retransmission timer for sending auth-reqs expired. + */ +static void +upap_timeout(void *arg) +{ + upap_state *u = (upap_state *) arg; + + UPAPDEBUG(LOG_INFO, ("upap_timeout: %d timeout %d expired s=%d\n", + u->us_unit, u->us_timeouttime, u->us_clientstate)); + + if (u->us_clientstate != UPAPCS_AUTHREQ) { + UPAPDEBUG(LOG_INFO, ("upap_timeout: not in AUTHREQ state!\n")); + return; + } + + if (u->us_transmits >= u->us_maxtransmits) { + /* give up in disgust */ + UPAPDEBUG(LOG_ERR, ("No response to PAP authenticate-requests\n")); + u->us_clientstate = UPAPCS_BADAUTH; + auth_withpeer_fail(u->us_unit, PPP_PAP); + return; + } + + upap_sauthreq(u); /* Send Authenticate-Request and set upap timeout*/ +} + + +/* + * upap_reqtimeout - Give up waiting for the peer to send an auth-req. + */ +static void +upap_reqtimeout(void *arg) +{ + upap_state *u = (upap_state *) arg; + + if (u->us_serverstate != UPAPSS_LISTEN) { + return; /* huh?? */ + } + + auth_peer_fail(u->us_unit, PPP_PAP); + u->us_serverstate = UPAPSS_BADAUTH; +} + + +/* + * upap_lowerup - The lower layer is up. + * + * Start authenticating if pending. + */ +static void +upap_lowerup(int unit) +{ + upap_state *u = &upap[unit]; + + UPAPDEBUG(LOG_INFO, ("upap_lowerup: init %d clientstate s=%d\n", unit, u->us_clientstate)); + + if (u->us_clientstate == UPAPCS_INITIAL) { + u->us_clientstate = UPAPCS_CLOSED; + } else if (u->us_clientstate == UPAPCS_PENDING) { + upap_sauthreq(u); /* send an auth-request */ + /* now client state is UPAPCS__AUTHREQ */ + } + + if (u->us_serverstate == UPAPSS_INITIAL) { + u->us_serverstate = UPAPSS_CLOSED; + } else if (u->us_serverstate == UPAPSS_PENDING) { + u->us_serverstate = UPAPSS_LISTEN; + if (u->us_reqtimeout > 0) { + TIMEOUT(upap_reqtimeout, u, u->us_reqtimeout); + } + } +} + + +/* + * upap_lowerdown - The lower layer is down. + * + * Cancel all timeouts. + */ +static void +upap_lowerdown(int unit) +{ + upap_state *u = &upap[unit]; + + UPAPDEBUG(LOG_INFO, ("upap_lowerdown: %d s=%d\n", unit, u->us_clientstate)); + + if (u->us_clientstate == UPAPCS_AUTHREQ) { /* Timeout pending? */ + UNTIMEOUT(upap_timeout, u); /* Cancel timeout */ + } + if (u->us_serverstate == UPAPSS_LISTEN && u->us_reqtimeout > 0) { + UNTIMEOUT(upap_reqtimeout, u); + } + + u->us_clientstate = UPAPCS_INITIAL; + u->us_serverstate = UPAPSS_INITIAL; +} + + +/* + * upap_protrej - Peer doesn't speak this protocol. + * + * This shouldn't happen. In any case, pretend lower layer went down. + */ +static void +upap_protrej(int unit) +{ + upap_state *u = &upap[unit]; + + if (u->us_clientstate == UPAPCS_AUTHREQ) { + UPAPDEBUG(LOG_ERR, ("PAP authentication failed due to protocol-reject\n")); + auth_withpeer_fail(unit, PPP_PAP); + } + if (u->us_serverstate == UPAPSS_LISTEN) { + UPAPDEBUG(LOG_ERR, ("PAP authentication of peer failed (protocol-reject)\n")); + auth_peer_fail(unit, PPP_PAP); + } + upap_lowerdown(unit); +} + + +/* + * upap_input - Input UPAP packet. + */ +static void +upap_input(int unit, u_char *inpacket, int l) +{ + upap_state *u = &upap[unit]; + u_char *inp; + u_char code, id; + int len; + + /* + * Parse header (code, id and length). + * If packet too short, drop it. + */ + inp = inpacket; + if (l < (int)UPAP_HEADERLEN) { + UPAPDEBUG(LOG_INFO, ("pap_input: rcvd short header.\n")); + return; + } + GETCHAR(code, inp); + GETCHAR(id, inp); + GETSHORT(len, inp); + if (len < (int)UPAP_HEADERLEN) { + UPAPDEBUG(LOG_INFO, ("pap_input: rcvd illegal length.\n")); + return; + } + if (len > l) { + UPAPDEBUG(LOG_INFO, ("pap_input: rcvd short packet.\n")); + return; + } + len -= UPAP_HEADERLEN; + + /* + * Action depends on code. + */ + switch (code) { + case UPAP_AUTHREQ: + upap_rauthreq(u, inp, id, len); + break; + + case UPAP_AUTHACK: + upap_rauthack(u, inp, id, len); + break; + + case UPAP_AUTHNAK: + upap_rauthnak(u, inp, id, len); + break; + + default: /* XXX Need code reject */ + UPAPDEBUG(LOG_INFO, ("pap_input: UNHANDLED default: code: %d, id: %d, len: %d.\n", code, id, len)); + break; + } +} + + +/* + * upap_rauth - Receive Authenticate. + */ +static void +upap_rauthreq(upap_state *u, u_char *inp, u_char id, int len) +{ + u_char ruserlen, rpasswdlen; + char *ruser, *rpasswd; + u_char retcode; + char *msg; + int msglen; + + UPAPDEBUG(LOG_INFO, ("pap_rauth: Rcvd id %d.\n", id)); + + if (u->us_serverstate < UPAPSS_LISTEN) { + return; + } + + /* + * If we receive a duplicate authenticate-request, we are + * supposed to return the same status as for the first request. + */ + if (u->us_serverstate == UPAPSS_OPEN) { + upap_sresp(u, UPAP_AUTHACK, id, "", 0); /* return auth-ack */ + return; + } + if (u->us_serverstate == UPAPSS_BADAUTH) { + upap_sresp(u, UPAP_AUTHNAK, id, "", 0); /* return auth-nak */ + return; + } + + /* + * Parse user/passwd. + */ + if (len < (int)sizeof (u_char)) { + UPAPDEBUG(LOG_INFO, ("pap_rauth: rcvd short packet.\n")); + return; + } + GETCHAR(ruserlen, inp); + len -= sizeof (u_char) + ruserlen + sizeof (u_char); + if (len < 0) { + UPAPDEBUG(LOG_INFO, ("pap_rauth: rcvd short packet.\n")); + return; + } + ruser = (char *) inp; + INCPTR(ruserlen, inp); + GETCHAR(rpasswdlen, inp); + if (len < rpasswdlen) { + UPAPDEBUG(LOG_INFO, ("pap_rauth: rcvd short packet.\n")); + return; + } + rpasswd = (char *) inp; + + /* + * Check the username and password given. + */ + retcode = check_passwd(u->us_unit, ruser, ruserlen, rpasswd, rpasswdlen, &msg, &msglen); + /* lwip: currently retcode is always UPAP_AUTHACK */ + BZERO(rpasswd, rpasswdlen); + + upap_sresp(u, retcode, id, msg, msglen); + + if (retcode == UPAP_AUTHACK) { + u->us_serverstate = UPAPSS_OPEN; + auth_peer_success(u->us_unit, PPP_PAP, ruser, ruserlen); + } else { + u->us_serverstate = UPAPSS_BADAUTH; + auth_peer_fail(u->us_unit, PPP_PAP); + } + + if (u->us_reqtimeout > 0) { + UNTIMEOUT(upap_reqtimeout, u); + } +} + + +/* + * upap_rauthack - Receive Authenticate-Ack. + */ +static void +upap_rauthack(upap_state *u, u_char *inp, int id, int len) +{ + u_char msglen; + char *msg; + + LWIP_UNUSED_ARG(id); + + UPAPDEBUG(LOG_INFO, ("pap_rauthack: Rcvd id %d s=%d\n", id, u->us_clientstate)); + + if (u->us_clientstate != UPAPCS_AUTHREQ) { /* XXX */ + UPAPDEBUG(LOG_INFO, ("pap_rauthack: us_clientstate != UPAPCS_AUTHREQ\n")); + return; + } + + /* + * Parse message. + */ + if (len < (int)sizeof (u_char)) { + UPAPDEBUG(LOG_INFO, ("pap_rauthack: ignoring missing msg-length.\n")); + } else { + GETCHAR(msglen, inp); + if (msglen > 0) { + len -= sizeof (u_char); + if (len < msglen) { + UPAPDEBUG(LOG_INFO, ("pap_rauthack: rcvd short packet.\n")); + return; + } + msg = (char *) inp; + PRINTMSG(msg, msglen); + } + } + UNTIMEOUT(upap_timeout, u); /* Cancel timeout */ + u->us_clientstate = UPAPCS_OPEN; + + auth_withpeer_success(u->us_unit, PPP_PAP); +} + + +/* + * upap_rauthnak - Receive Authenticate-Nak. + */ +static void +upap_rauthnak(upap_state *u, u_char *inp, int id, int len) +{ + u_char msglen; + char *msg; + + LWIP_UNUSED_ARG(id); + + UPAPDEBUG(LOG_INFO, ("pap_rauthnak: Rcvd id %d s=%d\n", id, u->us_clientstate)); + + if (u->us_clientstate != UPAPCS_AUTHREQ) { /* XXX */ + return; + } + + /* + * Parse message. + */ + if (len < sizeof (u_char)) { + UPAPDEBUG(LOG_INFO, ("pap_rauthnak: ignoring missing msg-length.\n")); + } else { + GETCHAR(msglen, inp); + if(msglen > 0) { + len -= sizeof (u_char); + if (len < msglen) { + UPAPDEBUG(LOG_INFO, ("pap_rauthnak: rcvd short packet.\n")); + return; + } + msg = (char *) inp; + PRINTMSG(msg, msglen); + } + } + + u->us_clientstate = UPAPCS_BADAUTH; + + UPAPDEBUG(LOG_ERR, ("PAP authentication failed\n")); + auth_withpeer_fail(u->us_unit, PPP_PAP); +} + + +/* + * upap_sauthreq - Send an Authenticate-Request. + */ +static void +upap_sauthreq(upap_state *u) +{ + u_char *outp; + int outlen; + + outlen = UPAP_HEADERLEN + 2 * sizeof (u_char) + + u->us_userlen + u->us_passwdlen; + outp = outpacket_buf[u->us_unit]; + + MAKEHEADER(outp, PPP_PAP); + + PUTCHAR(UPAP_AUTHREQ, outp); + PUTCHAR(++u->us_id, outp); + PUTSHORT(outlen, outp); + PUTCHAR(u->us_userlen, outp); + BCOPY(u->us_user, outp, u->us_userlen); + INCPTR(u->us_userlen, outp); + PUTCHAR(u->us_passwdlen, outp); + BCOPY(u->us_passwd, outp, u->us_passwdlen); + + pppWrite(u->us_unit, outpacket_buf[u->us_unit], outlen + PPP_HDRLEN); + + UPAPDEBUG(LOG_INFO, ("pap_sauth: Sent id %d\n", u->us_id)); + + TIMEOUT(upap_timeout, u, u->us_timeouttime); + ++u->us_transmits; + u->us_clientstate = UPAPCS_AUTHREQ; +} + + +/* + * upap_sresp - Send a response (ack or nak). + */ +static void +upap_sresp(upap_state *u, u_char code, u_char id, char *msg, int msglen) +{ + u_char *outp; + int outlen; + + outlen = UPAP_HEADERLEN + sizeof (u_char) + msglen; + outp = outpacket_buf[u->us_unit]; + MAKEHEADER(outp, PPP_PAP); + + PUTCHAR(code, outp); + PUTCHAR(id, outp); + PUTSHORT(outlen, outp); + PUTCHAR(msglen, outp); + BCOPY(msg, outp, msglen); + pppWrite(u->us_unit, outpacket_buf[u->us_unit], outlen + PPP_HDRLEN); + + UPAPDEBUG(LOG_INFO, ("pap_sresp: Sent code %d, id %d s=%d\n", code, id, u->us_clientstate)); +} + +#if PPP_ADDITIONAL_CALLBACKS +static char *upap_codenames[] = { + "AuthReq", "AuthAck", "AuthNak" +}; + +/* + * upap_printpkt - print the contents of a PAP packet. + */ +static int upap_printpkt( + u_char *p, + int plen, + void (*printer) (void *, char *, ...), + void *arg +) +{ + LWIP_UNUSED_ARG(p); + LWIP_UNUSED_ARG(plen); + LWIP_UNUSED_ARG(printer); + LWIP_UNUSED_ARG(arg); + return 0; +} +#endif /* PPP_ADDITIONAL_CALLBACKS */ + +#endif /* PAP_SUPPORT */ + +#endif /* PPP_SUPPORT */ diff --git a/features/unsupported/net/lwip/lwip/netif/ppp/pap.h b/features/unsupported/net/lwip/lwip/netif/ppp/pap.h new file mode 100644 index 00000000000..c99a2040196 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/netif/ppp/pap.h @@ -0,0 +1,118 @@ +/***************************************************************************** +* pap.h - PPP Password Authentication Protocol header file. +* +* Copyright (c) 2003 by Marc Boucher, Services Informatiques (MBSI) inc. +* portions Copyright (c) 1997 Global Election Systems Inc. +* +* The authors hereby grant permission to use, copy, modify, distribute, +* and license this software and its documentation for any purpose, provided +* that existing copyright notices are retained in all copies and that this +* notice and the following disclaimer are included verbatim in any +* distributions. No written agreement, license, or royalty fee is required +* for any of the authorized uses. +* +* THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS *AS IS* AND ANY EXPRESS OR +* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +* IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT +* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +****************************************************************************** +* REVISION HISTORY +* +* 03-01-01 Marc Boucher +* Ported to lwIP. +* 97-12-04 Guy Lancaster , Global Election Systems Inc. +* Original derived from BSD codes. +*****************************************************************************/ +/* + * upap.h - User/Password Authentication Protocol definitions. + * + * Copyright (c) 1989 Carnegie Mellon University. + * All rights reserved. + * + * Redistribution and use in source and binary forms are permitted + * provided that the above copyright notice and this paragraph are + * duplicated in all such forms and that any documentation, + * advertising materials, and other materials related to such + * distribution and use acknowledge that the software was developed + * by Carnegie Mellon University. The name of the + * University may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED + * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. + */ + +#ifndef PAP_H +#define PAP_H + +#if PAP_SUPPORT /* don't build if not configured for use in lwipopts.h */ + +/* + * Packet header = Code, id, length. + */ +#define UPAP_HEADERLEN (sizeof (u_char) + sizeof (u_char) + sizeof (u_short)) + + +/* + * UPAP codes. + */ +#define UPAP_AUTHREQ 1 /* Authenticate-Request */ +#define UPAP_AUTHACK 2 /* Authenticate-Ack */ +#define UPAP_AUTHNAK 3 /* Authenticate-Nak */ + +/* + * Each interface is described by upap structure. + */ +typedef struct upap_state { + int us_unit; /* Interface unit number */ + const char *us_user; /* User */ + int us_userlen; /* User length */ + const char *us_passwd; /* Password */ + int us_passwdlen; /* Password length */ + int us_clientstate; /* Client state */ + int us_serverstate; /* Server state */ + u_char us_id; /* Current id */ + int us_timeouttime; /* Timeout (seconds) for auth-req retrans. */ + int us_transmits; /* Number of auth-reqs sent */ + int us_maxtransmits; /* Maximum number of auth-reqs to send */ + int us_reqtimeout; /* Time to wait for auth-req from peer */ +} upap_state; + +/* + * Client states. + */ +#define UPAPCS_INITIAL 0 /* Connection down */ +#define UPAPCS_CLOSED 1 /* Connection up, haven't requested auth */ +#define UPAPCS_PENDING 2 /* Connection down, have requested auth */ +#define UPAPCS_AUTHREQ 3 /* We've sent an Authenticate-Request */ +#define UPAPCS_OPEN 4 /* We've received an Ack */ +#define UPAPCS_BADAUTH 5 /* We've received a Nak */ + +/* + * Server states. + */ +#define UPAPSS_INITIAL 0 /* Connection down */ +#define UPAPSS_CLOSED 1 /* Connection up, haven't requested auth */ +#define UPAPSS_PENDING 2 /* Connection down, have requested auth */ +#define UPAPSS_LISTEN 3 /* Listening for an Authenticate */ +#define UPAPSS_OPEN 4 /* We've sent an Ack */ +#define UPAPSS_BADAUTH 5 /* We've sent a Nak */ + + +extern upap_state upap[]; + +void upap_authwithpeer (int, char *, char *); +void upap_authpeer (int); + +extern struct protent pap_protent; + +#endif /* PAP_SUPPORT */ + +#endif /* PAP_H */ diff --git a/features/unsupported/net/lwip/lwip/netif/ppp/ppp.c b/features/unsupported/net/lwip/lwip/netif/ppp/ppp.c new file mode 100644 index 00000000000..fd35689734c --- /dev/null +++ b/features/unsupported/net/lwip/lwip/netif/ppp/ppp.c @@ -0,0 +1,2030 @@ +/***************************************************************************** +* ppp.c - Network Point to Point Protocol program file. +* +* Copyright (c) 2003 by Marc Boucher, Services Informatiques (MBSI) inc. +* portions Copyright (c) 1997 by Global Election Systems Inc. +* +* The authors hereby grant permission to use, copy, modify, distribute, +* and license this software and its documentation for any purpose, provided +* that existing copyright notices are retained in all copies and that this +* notice and the following disclaimer are included verbatim in any +* distributions. No written agreement, license, or royalty fee is required +* for any of the authorized uses. +* +* THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS *AS IS* AND ANY EXPRESS OR +* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +* IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT +* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +****************************************************************************** +* REVISION HISTORY +* +* 03-01-01 Marc Boucher +* Ported to lwIP. +* 97-11-05 Guy Lancaster , Global Election Systems Inc. +* Original. +*****************************************************************************/ + +/* + * ppp_defs.h - PPP definitions. + * + * if_pppvar.h - private structures and declarations for PPP. + * + * Copyright (c) 1994 The Australian National University. + * All rights reserved. + * + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, provided that the above copyright + * notice appears in all copies. This software is provided without any + * warranty, express or implied. The Australian National University + * makes no representations about the suitability of this software for + * any purpose. + * + * IN NO EVENT SHALL THE AUSTRALIAN NATIONAL UNIVERSITY BE LIABLE TO ANY + * PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES + * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF + * THE AUSTRALIAN NATIONAL UNIVERSITY HAVE BEEN ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * THE AUSTRALIAN NATIONAL UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + * AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS + * ON AN "AS IS" BASIS, AND THE AUSTRALIAN NATIONAL UNIVERSITY HAS NO + * OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, + * OR MODIFICATIONS. + */ + +/* + * if_ppp.h - Point-to-Point Protocol definitions. + * + * Copyright (c) 1989 Carnegie Mellon University. + * All rights reserved. + * + * Redistribution and use in source and binary forms are permitted + * provided that the above copyright notice and this paragraph are + * duplicated in all such forms and that any documentation, + * advertising materials, and other materials related to such + * distribution and use acknowledge that the software was developed + * by Carnegie Mellon University. The name of the + * University may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. + */ + +#include "lwip/opt.h" + +#if PPP_SUPPORT /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/ip.h" /* for ip_input() */ + +#include "ppp.h" +#include "pppdebug.h" + +#include "randm.h" +#include "fsm.h" +#if PAP_SUPPORT +#include "pap.h" +#endif /* PAP_SUPPORT */ +#if CHAP_SUPPORT +#include "chap.h" +#endif /* CHAP_SUPPORT */ +#include "ipcp.h" +#include "lcp.h" +#include "magic.h" +#include "auth.h" +#if VJ_SUPPORT +#include "vj.h" +#endif /* VJ_SUPPORT */ +#if PPPOE_SUPPORT +#include "netif/ppp_oe.h" +#endif /* PPPOE_SUPPORT */ + +#include "lwip/tcpip.h" +#include "lwip/api.h" +#include "lwip/snmp.h" + +#include + +/*************************/ +/*** LOCAL DEFINITIONS ***/ +/*************************/ + +/** PPP_INPROC_MULTITHREADED==1 call pppInput using tcpip_callback(). + * Set this to 0 if pppInProc is called inside tcpip_thread or with NO_SYS==1. + * Default is 1 for NO_SYS==0 (multithreaded) and 0 for NO_SYS==1 (single-threaded). + */ +#ifndef PPP_INPROC_MULTITHREADED +#define PPP_INPROC_MULTITHREADED (NO_SYS==0) +#endif + +/** PPP_INPROC_OWNTHREAD==1: start a dedicated RX thread per PPP session. + * Default is 0: call pppos_input() for received raw characters, charcater + * reception is up to the port */ +#ifndef PPP_INPROC_OWNTHREAD +#define PPP_INPROC_OWNTHREAD PPP_INPROC_MULTITHREADED +#endif + +#if PPP_INPROC_OWNTHREAD && !PPP_INPROC_MULTITHREADED + #error "PPP_INPROC_OWNTHREAD needs PPP_INPROC_MULTITHREADED==1" +#endif + +/* + * The basic PPP frame. + */ +#define PPP_ADDRESS(p) (((u_char *)(p))[0]) +#define PPP_CONTROL(p) (((u_char *)(p))[1]) +#define PPP_PROTOCOL(p) ((((u_char *)(p))[2] << 8) + ((u_char *)(p))[3]) + +/* PPP packet parser states. Current state indicates operation yet to be + * completed. */ +typedef enum { + PDIDLE = 0, /* Idle state - waiting. */ + PDSTART, /* Process start flag. */ + PDADDRESS, /* Process address field. */ + PDCONTROL, /* Process control field. */ + PDPROTOCOL1, /* Process protocol field 1. */ + PDPROTOCOL2, /* Process protocol field 2. */ + PDDATA /* Process data byte. */ +} PPPDevStates; + +#define ESCAPE_P(accm, c) ((accm)[(c) >> 3] & pppACCMMask[c & 0x07]) + +/************************/ +/*** LOCAL DATA TYPES ***/ +/************************/ + +/** RX buffer size: this may be configured smaller! */ +#ifndef PPPOS_RX_BUFSIZE +#define PPPOS_RX_BUFSIZE (PPP_MRU + PPP_HDRLEN) +#endif + +typedef struct PPPControlRx_s { + /** unit number / ppp descriptor */ + int pd; + /** the rx file descriptor */ + sio_fd_t fd; + /** receive buffer - encoded data is stored here */ + u_char rxbuf[PPPOS_RX_BUFSIZE]; + + /* The input packet. */ + struct pbuf *inHead, *inTail; + +#if PPPOS_SUPPORT + u16_t inProtocol; /* The input protocol code. */ + u16_t inFCS; /* Input Frame Check Sequence value. */ +#endif /* PPPOS_SUPPORT */ + PPPDevStates inState; /* The input process state. */ + char inEscaped; /* Escape next character. */ + ext_accm inACCM; /* Async-Ctl-Char-Map for input. */ +} PPPControlRx; + +/* + * PPP interface control block. + */ +typedef struct PPPControl_s { + PPPControlRx rx; + char openFlag; /* True when in use. */ +#if PPPOE_SUPPORT + struct netif *ethif; + struct pppoe_softc *pppoe_sc; +#endif /* PPPOE_SUPPORT */ + int if_up; /* True when the interface is up. */ + int errCode; /* Code indicating why interface is down. */ +#if PPPOS_SUPPORT + sio_fd_t fd; /* File device ID of port. */ +#endif /* PPPOS_SUPPORT */ + u16_t mtu; /* Peer's mru */ + int pcomp; /* Does peer accept protocol compression? */ + int accomp; /* Does peer accept addr/ctl compression? */ + u_long lastXMit; /* Time of last transmission. */ + ext_accm outACCM; /* Async-Ctl-Char-Map for output. */ +#if PPPOS_SUPPORT && VJ_SUPPORT + int vjEnabled; /* Flag indicating VJ compression enabled. */ + struct vjcompress vjComp; /* Van Jacobson compression header. */ +#endif /* PPPOS_SUPPORT && VJ_SUPPORT */ + + struct netif netif; + + struct ppp_addrs addrs; + + void (*linkStatusCB)(void *ctx, int errCode, void *arg); + void *linkStatusCtx; + +} PPPControl; + + +/* + * Ioctl definitions. + */ + +struct npioctl { + int protocol; /* PPP procotol, e.g. PPP_IP */ + enum NPmode mode; +}; + + + +/***********************************/ +/*** LOCAL FUNCTION DECLARATIONS ***/ +/***********************************/ +#if PPPOS_SUPPORT +#if PPP_INPROC_OWNTHREAD +static void pppInputThread(void *arg); +#endif /* PPP_INPROC_OWNTHREAD */ +static void pppDrop(PPPControlRx *pcrx); +static void pppInProc(PPPControlRx *pcrx, u_char *s, int l); +#endif /* PPPOS_SUPPORT */ + + +/******************************/ +/*** PUBLIC DATA STRUCTURES ***/ +/******************************/ +u_long subnetMask; + +static PPPControl pppControl[NUM_PPP] __attribute((section("AHBSRAM1"))); /* The PPP interface control blocks. */ + +sys_mbox_t pppMbox; //Used to signal PPP thread that a PPP session begins + +/* + * PPP Data Link Layer "protocol" table. + * One entry per supported protocol. + * The last entry must be NULL. + */ +struct protent *ppp_protocols[] = { + &lcp_protent, +#if PAP_SUPPORT + &pap_protent, +#endif /* PAP_SUPPORT */ +#if CHAP_SUPPORT + &chap_protent, +#endif /* CHAP_SUPPORT */ +#if CBCP_SUPPORT + &cbcp_protent, +#endif /* CBCP_SUPPORT */ + &ipcp_protent, +#if CCP_SUPPORT + &ccp_protent, +#endif /* CCP_SUPPORT */ + NULL +}; + + +/* + * Buffers for outgoing packets. This must be accessed only from the appropriate + * PPP task so that it doesn't need to be protected to avoid collisions. + */ +u_char outpacket_buf[NUM_PPP][PPP_MRU+PPP_HDRLEN] __attribute((section("AHBSRAM1"))); + + +/*****************************/ +/*** LOCAL DATA STRUCTURES ***/ +/*****************************/ + +#if PPPOS_SUPPORT +/* + * FCS lookup table as calculated by genfcstab. + * @todo: smaller, slower implementation for lower memory footprint? + */ +static const u_short fcstab[256] = { + 0x0000, 0x1189, 0x2312, 0x329b, 0x4624, 0x57ad, 0x6536, 0x74bf, + 0x8c48, 0x9dc1, 0xaf5a, 0xbed3, 0xca6c, 0xdbe5, 0xe97e, 0xf8f7, + 0x1081, 0x0108, 0x3393, 0x221a, 0x56a5, 0x472c, 0x75b7, 0x643e, + 0x9cc9, 0x8d40, 0xbfdb, 0xae52, 0xdaed, 0xcb64, 0xf9ff, 0xe876, + 0x2102, 0x308b, 0x0210, 0x1399, 0x6726, 0x76af, 0x4434, 0x55bd, + 0xad4a, 0xbcc3, 0x8e58, 0x9fd1, 0xeb6e, 0xfae7, 0xc87c, 0xd9f5, + 0x3183, 0x200a, 0x1291, 0x0318, 0x77a7, 0x662e, 0x54b5, 0x453c, + 0xbdcb, 0xac42, 0x9ed9, 0x8f50, 0xfbef, 0xea66, 0xd8fd, 0xc974, + 0x4204, 0x538d, 0x6116, 0x709f, 0x0420, 0x15a9, 0x2732, 0x36bb, + 0xce4c, 0xdfc5, 0xed5e, 0xfcd7, 0x8868, 0x99e1, 0xab7a, 0xbaf3, + 0x5285, 0x430c, 0x7197, 0x601e, 0x14a1, 0x0528, 0x37b3, 0x263a, + 0xdecd, 0xcf44, 0xfddf, 0xec56, 0x98e9, 0x8960, 0xbbfb, 0xaa72, + 0x6306, 0x728f, 0x4014, 0x519d, 0x2522, 0x34ab, 0x0630, 0x17b9, + 0xef4e, 0xfec7, 0xcc5c, 0xddd5, 0xa96a, 0xb8e3, 0x8a78, 0x9bf1, + 0x7387, 0x620e, 0x5095, 0x411c, 0x35a3, 0x242a, 0x16b1, 0x0738, + 0xffcf, 0xee46, 0xdcdd, 0xcd54, 0xb9eb, 0xa862, 0x9af9, 0x8b70, + 0x8408, 0x9581, 0xa71a, 0xb693, 0xc22c, 0xd3a5, 0xe13e, 0xf0b7, + 0x0840, 0x19c9, 0x2b52, 0x3adb, 0x4e64, 0x5fed, 0x6d76, 0x7cff, + 0x9489, 0x8500, 0xb79b, 0xa612, 0xd2ad, 0xc324, 0xf1bf, 0xe036, + 0x18c1, 0x0948, 0x3bd3, 0x2a5a, 0x5ee5, 0x4f6c, 0x7df7, 0x6c7e, + 0xa50a, 0xb483, 0x8618, 0x9791, 0xe32e, 0xf2a7, 0xc03c, 0xd1b5, + 0x2942, 0x38cb, 0x0a50, 0x1bd9, 0x6f66, 0x7eef, 0x4c74, 0x5dfd, + 0xb58b, 0xa402, 0x9699, 0x8710, 0xf3af, 0xe226, 0xd0bd, 0xc134, + 0x39c3, 0x284a, 0x1ad1, 0x0b58, 0x7fe7, 0x6e6e, 0x5cf5, 0x4d7c, + 0xc60c, 0xd785, 0xe51e, 0xf497, 0x8028, 0x91a1, 0xa33a, 0xb2b3, + 0x4a44, 0x5bcd, 0x6956, 0x78df, 0x0c60, 0x1de9, 0x2f72, 0x3efb, + 0xd68d, 0xc704, 0xf59f, 0xe416, 0x90a9, 0x8120, 0xb3bb, 0xa232, + 0x5ac5, 0x4b4c, 0x79d7, 0x685e, 0x1ce1, 0x0d68, 0x3ff3, 0x2e7a, + 0xe70e, 0xf687, 0xc41c, 0xd595, 0xa12a, 0xb0a3, 0x8238, 0x93b1, + 0x6b46, 0x7acf, 0x4854, 0x59dd, 0x2d62, 0x3ceb, 0x0e70, 0x1ff9, + 0xf78f, 0xe606, 0xd49d, 0xc514, 0xb1ab, 0xa022, 0x92b9, 0x8330, + 0x7bc7, 0x6a4e, 0x58d5, 0x495c, 0x3de3, 0x2c6a, 0x1ef1, 0x0f78 +}; + +/* PPP's Asynchronous-Control-Character-Map. The mask array is used + * to select the specific bit for a character. */ +static u_char pppACCMMask[] = { + 0x01, + 0x02, + 0x04, + 0x08, + 0x10, + 0x20, + 0x40, + 0x80 +}; + +/** Wake up the task blocked in reading from serial line (if any) */ +static void +pppRecvWakeup(int pd) +{ + PPPDEBUG(LOG_DEBUG, ("pppRecvWakeup: unit %d\n", pd)); + if (pppControl[pd].openFlag != 0) { + sio_read_abort(pppControl[pd].fd); + } +} +#endif /* PPPOS_SUPPORT */ + +void +pppLinkTerminated(int pd) +{ + PPPDEBUG(LOG_DEBUG, ("pppLinkTerminated: unit %d\n", pd)); + +#if PPPOE_SUPPORT + if (pppControl[pd].ethif) { + pppoe_disconnect(pppControl[pd].pppoe_sc); + } else +#endif /* PPPOE_SUPPORT */ + { +#if PPPOS_SUPPORT + PPPControl* pc; + pppRecvWakeup(pd); + pc = &pppControl[pd]; + + PPPDEBUG(LOG_DEBUG, ("pppLinkTerminated: unit %d: linkStatusCB=%p errCode=%d\n", pd, pc->linkStatusCB, pc->errCode)); + if (pc->linkStatusCB) { + pc->linkStatusCB(pc->linkStatusCtx, pc->errCode ? pc->errCode : PPPERR_PROTOCOL, NULL); + } + + pc->openFlag = 0;/**/ +#endif /* PPPOS_SUPPORT */ + } + PPPDEBUG(LOG_DEBUG, ("pppLinkTerminated: finished.\n")); +} + +void +pppLinkDown(int pd) +{ + PPPDEBUG(LOG_DEBUG, ("pppLinkDown: unit %d\n", pd)); + +#if PPPOE_SUPPORT + if (pppControl[pd].ethif) { + pppoe_disconnect(pppControl[pd].pppoe_sc); + } else +#endif /* PPPOE_SUPPORT */ + { +#if PPPOS_SUPPORT + pppRecvWakeup(pd); +#endif /* PPPOS_SUPPORT */ + } +} + +/** Initiate LCP open request */ +static void +pppStart(int pd) +{ + PPPDEBUG(LOG_DEBUG, ("pppStart: unit %d\n", pd)); + lcp_lowerup(pd); + lcp_open(pd); /* Start protocol */ + PPPDEBUG(LOG_DEBUG, ("pppStart: finished\n")); +} + +/** LCP close request */ +static void +pppStop(int pd) +{ + PPPDEBUG(LOG_DEBUG, ("pppStop: unit %d\n", pd)); + lcp_close(pd, "User request"); +} + +/** Called when carrier/link is lost */ +static void +pppHup(int pd) +{ + PPPDEBUG(LOG_DEBUG, ("pppHupCB: unit %d\n", pd)); + lcp_lowerdown(pd); + link_terminated(pd); +} + +/***********************************/ +/*** PUBLIC FUNCTION DEFINITIONS ***/ +/***********************************/ +/* Initialize the PPP subsystem. */ + +struct ppp_settings ppp_settings; + +void +pppInit(void) +{ + struct protent *protp; + int i, j; + + memset(&ppp_settings, 0, sizeof(ppp_settings)); + ppp_settings.usepeerdns = 1; + pppSetAuth(PPPAUTHTYPE_NONE, NULL, NULL); + + magicInit(); + + subnetMask = PP_HTONL(0xffffff00UL); + + for (i = 0; i < NUM_PPP; i++) { + /* Initialize each protocol to the standard option set. */ + for (j = 0; (protp = ppp_protocols[j]) != NULL; ++j) { + (*protp->init)(i); + } + } + + sys_mbox_new(&pppMbox, 1); + sys_thread_new(PPP_THREAD_NAME, pppInputThread, (void*)NULL, PPP_THREAD_STACKSIZE, PPP_THREAD_PRIO); //Create PPP thread here +} + +void +pppSetAuth(enum pppAuthType authType, const char *user, const char *passwd) +{ + switch(authType) { + case PPPAUTHTYPE_NONE: + default: +#ifdef LWIP_PPP_STRICT_PAP_REJECT + ppp_settings.refuse_pap = 1; +#else /* LWIP_PPP_STRICT_PAP_REJECT */ + /* some providers request pap and accept an empty login/pw */ + ppp_settings.refuse_pap = 0; +#endif /* LWIP_PPP_STRICT_PAP_REJECT */ + ppp_settings.refuse_chap = 1; + break; + + case PPPAUTHTYPE_ANY: + /* Warning: Using PPPAUTHTYPE_ANY might have security consequences. + * RFC 1994 says: + * + * In practice, within or associated with each PPP server, there is a + * database which associates "user" names with authentication + * information ("secrets"). It is not anticipated that a particular + * named user would be authenticated by multiple methods. This would + * make the user vulnerable to attacks which negotiate the least secure + * method from among a set (such as PAP rather than CHAP). If the same + * secret was used, PAP would reveal the secret to be used later with + * CHAP. + * + * Instead, for each user name there should be an indication of exactly + * one method used to authenticate that user name. If a user needs to + * make use of different authentication methods under different + * circumstances, then distinct user names SHOULD be employed, each of + * which identifies exactly one authentication method. + * + */ + ppp_settings.refuse_pap = 0; + ppp_settings.refuse_chap = 0; + break; + + case PPPAUTHTYPE_PAP: + ppp_settings.refuse_pap = 0; + ppp_settings.refuse_chap = 1; + break; + + case PPPAUTHTYPE_CHAP: + ppp_settings.refuse_pap = 1; + ppp_settings.refuse_chap = 0; + break; + } + + if(user) { + strncpy(ppp_settings.user, user, sizeof(ppp_settings.user)-1); + ppp_settings.user[sizeof(ppp_settings.user)-1] = '\0'; + } else { + ppp_settings.user[0] = '\0'; + } + + if(passwd) { + strncpy(ppp_settings.passwd, passwd, sizeof(ppp_settings.passwd)-1); + ppp_settings.passwd[sizeof(ppp_settings.passwd)-1] = '\0'; + } else { + ppp_settings.passwd[0] = '\0'; + } +} + +#if PPPOS_SUPPORT +/** Open a new PPP connection using the given I/O device. + * This initializes the PPP control block but does not + * attempt to negotiate the LCP session. If this port + * connects to a modem, the modem connection must be + * established before calling this. + * Return a new PPP connection descriptor on success or + * an error code (negative) on failure. + * + * pppOpen() is directly defined to this function. + */ +int +pppOverSerialOpen(sio_fd_t fd, void (*linkStatusCB)(void *ctx, int errCode, void *arg), void *linkStatusCtx) +{ + PPPControl *pc; + int pd; + + if (linkStatusCB == NULL) { + /* PPP is single-threaded: without a callback, + * there is no way to know when the link is up. */ + return PPPERR_PARAM; + } + + /* Find a free PPP session descriptor. */ + for (pd = 0; pd < NUM_PPP && pppControl[pd].openFlag != 0; pd++); + + if (pd >= NUM_PPP) { + pd = PPPERR_OPEN; + } else { + pc = &pppControl[pd]; + /* @todo: is this correct or do I overwrite something? */ + memset(pc, 0, sizeof(PPPControl)); + pc->rx.pd = pd; + pc->rx.fd = fd; + + pc->openFlag = 1; + pc->fd = fd; + +#if VJ_SUPPORT + vj_compress_init(&pc->vjComp); +#endif /* VJ_SUPPORT */ + + /* + * Default the in and out accm so that escape and flag characters + * are always escaped. + */ + pc->rx.inACCM[15] = 0x60; /* no need to protect since RX is not running */ + pc->outACCM[15] = 0x60; + + pc->linkStatusCB = linkStatusCB; + pc->linkStatusCtx = linkStatusCtx; + + /* + * Start the connection and handle incoming events (packet or timeout). + */ + PPPDEBUG(LOG_INFO, ("pppOverSerialOpen: unit %d: Connecting\n", pd)); + pppStart(pd); +#if PPP_INPROC_OWNTHREAD + sys_mbox_post(&pppMbox, (void*)&pc->rx); +#endif + } + + return pd; +} +#endif /* PPPOS_SUPPORT */ + +#if PPPOE_SUPPORT +static void pppOverEthernetLinkStatusCB(int pd, int up); + +void +pppOverEthernetClose(int pd) +{ + PPPControl* pc = &pppControl[pd]; + + /* *TJL* There's no lcp_deinit */ + lcp_close(pd, NULL); + + pppoe_destroy(&pc->netif); +} + +int pppOverEthernetOpen(struct netif *ethif, const char *service_name, const char *concentrator_name, void (*linkStatusCB)(void *ctx, int errCode, void *arg), void *linkStatusCtx) +{ + PPPControl *pc; + int pd; + + LWIP_UNUSED_ARG(service_name); + LWIP_UNUSED_ARG(concentrator_name); + + if (linkStatusCB == NULL) { + /* PPP is single-threaded: without a callback, + * there is no way to know when the link is up. */ + return PPPERR_PARAM; + } + + /* Find a free PPP session descriptor. Critical region? */ + for (pd = 0; pd < NUM_PPP && pppControl[pd].openFlag != 0; pd++); + if (pd >= NUM_PPP) { + pd = PPPERR_OPEN; + } else { + pc = &pppControl[pd]; + memset(pc, 0, sizeof(PPPControl)); + pc->openFlag = 1; + pc->ethif = ethif; + + pc->linkStatusCB = linkStatusCB; + pc->linkStatusCtx = linkStatusCtx; + + lcp_wantoptions[pd].mru = PPPOE_MAXMTU; + lcp_wantoptions[pd].neg_asyncmap = 0; + lcp_wantoptions[pd].neg_pcompression = 0; + lcp_wantoptions[pd].neg_accompression = 0; + + lcp_allowoptions[pd].mru = PPPOE_MAXMTU; + lcp_allowoptions[pd].neg_asyncmap = 0; + lcp_allowoptions[pd].neg_pcompression = 0; + lcp_allowoptions[pd].neg_accompression = 0; + + if(pppoe_create(ethif, pd, pppOverEthernetLinkStatusCB, &pc->pppoe_sc) != ERR_OK) { + pc->openFlag = 0; + return PPPERR_OPEN; + } + + pppoe_connect(pc->pppoe_sc); + } + + return pd; +} +#endif /* PPPOE_SUPPORT */ + + +/* Close a PPP connection and release the descriptor. + * Any outstanding packets in the queues are dropped. + * Return 0 on success, an error code on failure. */ +int +pppClose(int pd) +{ + PPPControl *pc = &pppControl[pd]; + int st = 0; + + PPPDEBUG(LOG_DEBUG, ("pppClose() called\n")); + + /* Disconnect */ +#if PPPOE_SUPPORT + if(pc->ethif) { + PPPDEBUG(LOG_DEBUG, ("pppClose: unit %d kill_link -> pppStop\n", pd)); + pc->errCode = PPPERR_USER; + /* This will leave us at PHASE_DEAD. */ + pppStop(pd); + } else +#endif /* PPPOE_SUPPORT */ + { +#if PPPOS_SUPPORT + PPPDEBUG(LOG_DEBUG, ("pppClose: unit %d kill_link -> pppStop\n", pd)); + pc->errCode = PPPERR_USER; + /* This will leave us at PHASE_DEAD. */ + pppStop(pd); + pppRecvWakeup(pd); +#endif /* PPPOS_SUPPORT */ + } + + return st; +} + +/* This function is called when carrier is lost on the PPP channel. */ +void +pppSigHUP(int pd) +{ + PPPDEBUG(LOG_DEBUG, ("pppSigHUP: unit %d sig_hup -> pppHupCB\n", pd)); + pppHup(pd); +} + +#if PPPOS_SUPPORT +static void +nPut(PPPControl *pc, struct pbuf *nb) +{ + struct pbuf *b; + int c; + + for(b = nb; b != NULL; b = b->next) { + if((c = sio_write(pc->fd, b->payload, b->len)) != b->len) { + PPPDEBUG(LOG_WARNING, + ("PPP nPut: incomplete sio_write(fd:%"SZT_F", len:%d, c: 0x%"X8_F") c = %d\n", (size_t)pc->fd, b->len, c, c)); + LINK_STATS_INC(link.err); + pc->lastXMit = 0; /* prepend PPP_FLAG to next packet */ + snmp_inc_ifoutdiscards(&pc->netif); + pbuf_free(nb); + return; + } + } + + snmp_add_ifoutoctets(&pc->netif, nb->tot_len); + snmp_inc_ifoutucastpkts(&pc->netif); + pbuf_free(nb); + LINK_STATS_INC(link.xmit); +} + +/* + * pppAppend - append given character to end of given pbuf. If outACCM + * is not NULL and the character needs to be escaped, do so. + * If pbuf is full, append another. + * Return the current pbuf. + */ +static struct pbuf * +pppAppend(u_char c, struct pbuf *nb, ext_accm *outACCM) +{ + struct pbuf *tb = nb; + + /* Make sure there is room for the character and an escape code. + * Sure we don't quite fill the buffer if the character doesn't + * get escaped but is one character worth complicating this? */ + /* Note: We assume no packet header. */ + if (nb && (PBUF_POOL_BUFSIZE - nb->len) < 2) { + tb = pbuf_alloc(PBUF_RAW, 0, PBUF_POOL); + if (tb) { + nb->next = tb; + } else { + LINK_STATS_INC(link.memerr); + } + nb = tb; + } + + if (nb) { + if (outACCM && ESCAPE_P(*outACCM, c)) { + *((u_char*)nb->payload + nb->len++) = PPP_ESCAPE; + *((u_char*)nb->payload + nb->len++) = c ^ PPP_TRANS; + } else { + *((u_char*)nb->payload + nb->len++) = c; + } + } + + return tb; +} +#endif /* PPPOS_SUPPORT */ + +#if PPPOE_SUPPORT +static err_t +pppifOutputOverEthernet(int pd, struct pbuf *p) +{ + PPPControl *pc = &pppControl[pd]; + struct pbuf *pb; + u_short protocol = PPP_IP; + int i=0; + u16_t tot_len; + + /* @todo: try to use pbuf_header() here! */ + pb = pbuf_alloc(PBUF_LINK, PPPOE_HDRLEN + sizeof(protocol), PBUF_RAM); + if(!pb) { + LINK_STATS_INC(link.memerr); + LINK_STATS_INC(link.proterr); + snmp_inc_ifoutdiscards(&pc->netif); + return ERR_MEM; + } + + pbuf_header(pb, -(s16_t)PPPOE_HDRLEN); + + pc->lastXMit = sys_jiffies(); + + if (!pc->pcomp || protocol > 0xFF) { + *((u_char*)pb->payload + i++) = (protocol >> 8) & 0xFF; + } + *((u_char*)pb->payload + i) = protocol & 0xFF; + + pbuf_chain(pb, p); + tot_len = pb->tot_len; + + if(pppoe_xmit(pc->pppoe_sc, pb) != ERR_OK) { + LINK_STATS_INC(link.err); + snmp_inc_ifoutdiscards(&pc->netif); + return PPPERR_DEVICE; + } + + snmp_add_ifoutoctets(&pc->netif, tot_len); + snmp_inc_ifoutucastpkts(&pc->netif); + LINK_STATS_INC(link.xmit); + return ERR_OK; +} +#endif /* PPPOE_SUPPORT */ + +/* Send a packet on the given connection. */ +static err_t +pppifOutput(struct netif *netif, struct pbuf *pb, ip_addr_t *ipaddr) +{ + int pd = (int)(size_t)netif->state; + PPPControl *pc = &pppControl[pd]; +#if PPPOS_SUPPORT + u_short protocol = PPP_IP; + u_int fcsOut = PPP_INITFCS; + struct pbuf *headMB = NULL, *tailMB = NULL, *p; + u_char c; +#endif /* PPPOS_SUPPORT */ + + LWIP_UNUSED_ARG(ipaddr); + + /* Validate parameters. */ + /* We let any protocol value go through - it can't hurt us + * and the peer will just drop it if it's not accepting it. */ + if (pd < 0 || pd >= NUM_PPP || !pc->openFlag || !pb) { + PPPDEBUG(LOG_WARNING, ("pppifOutput[%d]: bad parms prot=%d pb=%p\n", + pd, PPP_IP, pb)); + LINK_STATS_INC(link.opterr); + LINK_STATS_INC(link.drop); + snmp_inc_ifoutdiscards(netif); + return ERR_ARG; + } + + /* Check that the link is up. */ + if (lcp_phase[pd] == PHASE_DEAD) { + PPPDEBUG(LOG_ERR, ("pppifOutput[%d]: link not up\n", pd)); + LINK_STATS_INC(link.rterr); + LINK_STATS_INC(link.drop); + snmp_inc_ifoutdiscards(netif); + return ERR_RTE; + } + +#if PPPOE_SUPPORT + if(pc->ethif) { + return pppifOutputOverEthernet(pd, pb); + } +#endif /* PPPOE_SUPPORT */ + +#if PPPOS_SUPPORT + /* Grab an output buffer. */ + headMB = pbuf_alloc(PBUF_RAW, 0, PBUF_POOL); + if (headMB == NULL) { + PPPDEBUG(LOG_WARNING, ("pppifOutput[%d]: first alloc fail\n", pd)); + LINK_STATS_INC(link.memerr); + LINK_STATS_INC(link.drop); + snmp_inc_ifoutdiscards(netif); + return ERR_MEM; + } + +#if VJ_SUPPORT + /* + * Attempt Van Jacobson header compression if VJ is configured and + * this is an IP packet. + */ + if (protocol == PPP_IP && pc->vjEnabled) { + switch (vj_compress_tcp(&pc->vjComp, pb)) { + case TYPE_IP: + /* No change... + protocol = PPP_IP_PROTOCOL; */ + break; + case TYPE_COMPRESSED_TCP: + protocol = PPP_VJC_COMP; + break; + case TYPE_UNCOMPRESSED_TCP: + protocol = PPP_VJC_UNCOMP; + break; + default: + PPPDEBUG(LOG_WARNING, ("pppifOutput[%d]: bad IP packet\n", pd)); + LINK_STATS_INC(link.proterr); + LINK_STATS_INC(link.drop); + snmp_inc_ifoutdiscards(netif); + pbuf_free(headMB); + return ERR_VAL; + } + } +#endif /* VJ_SUPPORT */ + + tailMB = headMB; + + /* Build the PPP header. */ + if ((sys_jiffies() - pc->lastXMit) >= PPP_MAXIDLEFLAG) { + tailMB = pppAppend(PPP_FLAG, tailMB, NULL); + } + + pc->lastXMit = sys_jiffies(); + if (!pc->accomp) { + fcsOut = PPP_FCS(fcsOut, PPP_ALLSTATIONS); + tailMB = pppAppend(PPP_ALLSTATIONS, tailMB, &pc->outACCM); + fcsOut = PPP_FCS(fcsOut, PPP_UI); + tailMB = pppAppend(PPP_UI, tailMB, &pc->outACCM); + } + if (!pc->pcomp || protocol > 0xFF) { + c = (protocol >> 8) & 0xFF; + fcsOut = PPP_FCS(fcsOut, c); + tailMB = pppAppend(c, tailMB, &pc->outACCM); + } + c = protocol & 0xFF; + fcsOut = PPP_FCS(fcsOut, c); + tailMB = pppAppend(c, tailMB, &pc->outACCM); + + /* Load packet. */ + for(p = pb; p; p = p->next) { + int n; + u_char *sPtr; + + sPtr = (u_char*)p->payload; + n = p->len; + while (n-- > 0) { + c = *sPtr++; + + /* Update FCS before checking for special characters. */ + fcsOut = PPP_FCS(fcsOut, c); + + /* Copy to output buffer escaping special characters. */ + tailMB = pppAppend(c, tailMB, &pc->outACCM); + } + } + + /* Add FCS and trailing flag. */ + c = ~fcsOut & 0xFF; + tailMB = pppAppend(c, tailMB, &pc->outACCM); + c = (~fcsOut >> 8) & 0xFF; + tailMB = pppAppend(c, tailMB, &pc->outACCM); + tailMB = pppAppend(PPP_FLAG, tailMB, NULL); + + /* If we failed to complete the packet, throw it away. */ + if (!tailMB) { + PPPDEBUG(LOG_WARNING, + ("pppifOutput[%d]: Alloc err - dropping proto=%d\n", + pd, protocol)); + pbuf_free(headMB); + LINK_STATS_INC(link.memerr); + LINK_STATS_INC(link.drop); + snmp_inc_ifoutdiscards(netif); + return ERR_MEM; + } + + /* Send it. */ + PPPDEBUG(LOG_INFO, ("pppifOutput[%d]: proto=0x%"X16_F"\n", pd, protocol)); + + nPut(pc, headMB); +#endif /* PPPOS_SUPPORT */ + + return ERR_OK; +} + +/* Get and set parameters for the given connection. + * Return 0 on success, an error code on failure. */ +int +pppIOCtl(int pd, int cmd, void *arg) +{ + PPPControl *pc = &pppControl[pd]; + int st = 0; + + if (pd < 0 || pd >= NUM_PPP) { + st = PPPERR_PARAM; + } else { + switch(cmd) { + case PPPCTLG_UPSTATUS: /* Get the PPP up status. */ + if (arg) { + *(int *)arg = (int)(pc->if_up); + } else { + st = PPPERR_PARAM; + } + break; + case PPPCTLS_ERRCODE: /* Set the PPP error code. */ + if (arg) { + pc->errCode = *(int *)arg; + } else { + st = PPPERR_PARAM; + } + break; + case PPPCTLG_ERRCODE: /* Get the PPP error code. */ + if (arg) { + *(int *)arg = (int)(pc->errCode); + } else { + st = PPPERR_PARAM; + } + break; +#if PPPOS_SUPPORT + case PPPCTLG_FD: /* Get the fd associated with the ppp */ + if (arg) { + *(sio_fd_t *)arg = pc->fd; + } else { + st = PPPERR_PARAM; + } + break; +#endif /* PPPOS_SUPPORT */ + default: + st = PPPERR_PARAM; + break; + } + } + + return st; +} + +/* + * Return the Maximum Transmission Unit for the given PPP connection. + */ +u_short +pppMTU(int pd) +{ + PPPControl *pc = &pppControl[pd]; + u_short st; + + /* Validate parameters. */ + if (pd < 0 || pd >= NUM_PPP || !pc->openFlag) { + st = 0; + } else { + st = pc->mtu; + } + + return st; +} + +#if PPPOE_SUPPORT +int +pppWriteOverEthernet(int pd, const u_char *s, int n) +{ + PPPControl *pc = &pppControl[pd]; + struct pbuf *pb; + + /* skip address & flags */ + s += 2; + n -= 2; + + LWIP_ASSERT("PPPOE_HDRLEN + n <= 0xffff", PPPOE_HDRLEN + n <= 0xffff); + pb = pbuf_alloc(PBUF_LINK, (u16_t)(PPPOE_HDRLEN + n), PBUF_RAM); + if(!pb) { + LINK_STATS_INC(link.memerr); + LINK_STATS_INC(link.proterr); + snmp_inc_ifoutdiscards(&pc->netif); + return PPPERR_ALLOC; + } + + pbuf_header(pb, -(s16_t)PPPOE_HDRLEN); + + pc->lastXMit = sys_jiffies(); + + MEMCPY(pb->payload, s, n); + + if(pppoe_xmit(pc->pppoe_sc, pb) != ERR_OK) { + LINK_STATS_INC(link.err); + snmp_inc_ifoutdiscards(&pc->netif); + return PPPERR_DEVICE; + } + + snmp_add_ifoutoctets(&pc->netif, (u16_t)n); + snmp_inc_ifoutucastpkts(&pc->netif); + LINK_STATS_INC(link.xmit); + return PPPERR_NONE; +} +#endif /* PPPOE_SUPPORT */ + +/* + * Write n characters to a ppp link. + * RETURN: >= 0 Number of characters written + * -1 Failed to write to device + */ +int +pppWrite(int pd, const u_char *s, int n) +{ + PPPControl *pc = &pppControl[pd]; +#if PPPOS_SUPPORT + u_char c; + u_int fcsOut; + struct pbuf *headMB, *tailMB; +#endif /* PPPOS_SUPPORT */ + +#if PPPOE_SUPPORT + if(pc->ethif) { + return pppWriteOverEthernet(pd, s, n); + } +#endif /* PPPOE_SUPPORT */ + +#if PPPOS_SUPPORT + headMB = pbuf_alloc(PBUF_RAW, 0, PBUF_POOL); + if (headMB == NULL) { + LINK_STATS_INC(link.memerr); + LINK_STATS_INC(link.proterr); + snmp_inc_ifoutdiscards(&pc->netif); + return PPPERR_ALLOC; + } + + tailMB = headMB; + + /* If the link has been idle, we'll send a fresh flag character to + * flush any noise. */ + if ((sys_jiffies() - pc->lastXMit) >= PPP_MAXIDLEFLAG) { + tailMB = pppAppend(PPP_FLAG, tailMB, NULL); + } + pc->lastXMit = sys_jiffies(); + + fcsOut = PPP_INITFCS; + /* Load output buffer. */ + while (n-- > 0) { + c = *s++; + + /* Update FCS before checking for special characters. */ + fcsOut = PPP_FCS(fcsOut, c); + + /* Copy to output buffer escaping special characters. */ + tailMB = pppAppend(c, tailMB, &pc->outACCM); + } + + /* Add FCS and trailing flag. */ + c = ~fcsOut & 0xFF; + tailMB = pppAppend(c, tailMB, &pc->outACCM); + c = (~fcsOut >> 8) & 0xFF; + tailMB = pppAppend(c, tailMB, &pc->outACCM); + tailMB = pppAppend(PPP_FLAG, tailMB, NULL); + + /* If we failed to complete the packet, throw it away. + * Otherwise send it. */ + if (!tailMB) { + PPPDEBUG(LOG_WARNING, + ("pppWrite[%d]: Alloc err - dropping pbuf len=%d\n", pd, headMB->len)); + /*"pppWrite[%d]: Alloc err - dropping %d:%.*H", pd, headMB->len, LWIP_MIN(headMB->len * 2, 40), headMB->payload)); */ + pbuf_free(headMB); + LINK_STATS_INC(link.memerr); + LINK_STATS_INC(link.proterr); + snmp_inc_ifoutdiscards(&pc->netif); + return PPPERR_ALLOC; + } + + PPPDEBUG(LOG_INFO, ("pppWrite[%d]: len=%d\n", pd, headMB->len)); + /* "pppWrite[%d]: %d:%.*H", pd, headMB->len, LWIP_MIN(headMB->len * 2, 40), headMB->payload)); */ + nPut(pc, headMB); +#endif /* PPPOS_SUPPORT */ + + return PPPERR_NONE; +} + +/* + * ppp_send_config - configure the transmit characteristics of + * the ppp interface. + */ +void +ppp_send_config( int unit, u16_t mtu, u32_t asyncmap, int pcomp, int accomp) +{ + PPPControl *pc = &pppControl[unit]; + int i; + + pc->mtu = mtu; + pc->pcomp = pcomp; + pc->accomp = accomp; + + /* Load the ACCM bits for the 32 control codes. */ + for (i = 0; i < 32/8; i++) { + pc->outACCM[i] = (u_char)((asyncmap >> (8 * i)) & 0xFF); + } + PPPDEBUG(LOG_INFO, ("ppp_send_config[%d]: outACCM=%X %X %X %X\n", + unit, + pc->outACCM[0], pc->outACCM[1], pc->outACCM[2], pc->outACCM[3])); +} + + +/* + * ppp_set_xaccm - set the extended transmit ACCM for the interface. + */ +void +ppp_set_xaccm(int unit, ext_accm *accm) +{ + SMEMCPY(pppControl[unit].outACCM, accm, sizeof(ext_accm)); + PPPDEBUG(LOG_INFO, ("ppp_set_xaccm[%d]: outACCM=%X %X %X %X\n", + unit, + pppControl[unit].outACCM[0], + pppControl[unit].outACCM[1], + pppControl[unit].outACCM[2], + pppControl[unit].outACCM[3])); +} + + +/* + * ppp_recv_config - configure the receive-side characteristics of + * the ppp interface. + */ +void +ppp_recv_config( int unit, int mru, u32_t asyncmap, int pcomp, int accomp) +{ + PPPControl *pc = &pppControl[unit]; + int i; + SYS_ARCH_DECL_PROTECT(lev); + + LWIP_UNUSED_ARG(accomp); + LWIP_UNUSED_ARG(pcomp); + LWIP_UNUSED_ARG(mru); + + /* Load the ACCM bits for the 32 control codes. */ + SYS_ARCH_PROTECT(lev); + for (i = 0; i < 32 / 8; i++) { + /* @todo: does this work? ext_accm has been modified from pppd! */ + pc->rx.inACCM[i] = (u_char)(asyncmap >> (i * 8)); + } + SYS_ARCH_UNPROTECT(lev); + PPPDEBUG(LOG_INFO, ("ppp_recv_config[%d]: inACCM=%X %X %X %X\n", + unit, + pc->rx.inACCM[0], pc->rx.inACCM[1], pc->rx.inACCM[2], pc->rx.inACCM[3])); +} + +#if 0 +/* + * ccp_test - ask kernel whether a given compression method + * is acceptable for use. Returns 1 if the method and parameters + * are OK, 0 if the method is known but the parameters are not OK + * (e.g. code size should be reduced), or -1 if the method is unknown. + */ +int +ccp_test( int unit, int opt_len, int for_transmit, u_char *opt_ptr) +{ + return 0; /* XXX Currently no compression. */ +} + +/* + * ccp_flags_set - inform kernel about the current state of CCP. + */ +void +ccp_flags_set(int unit, int isopen, int isup) +{ + /* XXX */ +} + +/* + * ccp_fatal_error - returns 1 if decompression was disabled as a + * result of an error detected after decompression of a packet, + * 0 otherwise. This is necessary because of patent nonsense. + */ +int +ccp_fatal_error(int unit) +{ + /* XXX */ + return 0; +} +#endif + +/* + * get_idle_time - return how long the link has been idle. + */ +int +get_idle_time(int u, struct ppp_idle *ip) +{ + /* XXX */ + LWIP_UNUSED_ARG(u); + LWIP_UNUSED_ARG(ip); + + return 0; +} + + +/* + * Return user specified netmask, modified by any mask we might determine + * for address `addr' (in network byte order). + * Here we scan through the system's list of interfaces, looking for + * any non-point-to-point interfaces which might appear to be on the same + * network as `addr'. If we find any, we OR in their netmask to the + * user-specified netmask. + */ +u32_t +GetMask(u32_t addr) +{ + u32_t mask, nmask; + + htonl(addr); + if (IP_CLASSA(addr)) { /* determine network mask for address class */ + nmask = IP_CLASSA_NET; + } else if (IP_CLASSB(addr)) { + nmask = IP_CLASSB_NET; + } else { + nmask = IP_CLASSC_NET; + } + + /* class D nets are disallowed by bad_ip_adrs */ + mask = subnetMask | htonl(nmask); + + /* XXX + * Scan through the system's network interfaces. + * Get each netmask and OR them into our mask. + */ + + return mask; +} + +/* + * sifvjcomp - config tcp header compression + */ +int +sifvjcomp(int pd, int vjcomp, u8_t cidcomp, u8_t maxcid) +{ +#if PPPOS_SUPPORT && VJ_SUPPORT + PPPControl *pc = &pppControl[pd]; + + pc->vjEnabled = vjcomp; + pc->vjComp.compressSlot = cidcomp; + pc->vjComp.maxSlotIndex = maxcid; + PPPDEBUG(LOG_INFO, ("sifvjcomp: VJ compress enable=%d slot=%d max slot=%d\n", + vjcomp, cidcomp, maxcid)); +#else /* PPPOS_SUPPORT && VJ_SUPPORT */ + LWIP_UNUSED_ARG(pd); + LWIP_UNUSED_ARG(vjcomp); + LWIP_UNUSED_ARG(cidcomp); + LWIP_UNUSED_ARG(maxcid); +#endif /* PPPOS_SUPPORT && VJ_SUPPORT */ + + return 0; +} + +/* + * pppifNetifInit - netif init callback + */ +static err_t +pppifNetifInit(struct netif *netif) +{ + netif->name[0] = 'p'; + netif->name[1] = 'p'; + netif->output = pppifOutput; + netif->mtu = pppMTU((int)(size_t)netif->state); + netif->flags = NETIF_FLAG_POINTTOPOINT | NETIF_FLAG_LINK_UP; +#if LWIP_NETIF_HOSTNAME + /* @todo: Initialize interface hostname */ + /* netif_set_hostname(netif, "lwip"); */ +#endif /* LWIP_NETIF_HOSTNAME */ + return ERR_OK; +} + + +/* + * sifup - Config the interface up and enable IP packets to pass. + */ +int +sifup(int pd) +{ + PPPControl *pc = &pppControl[pd]; + int st = 1; + + if (pd < 0 || pd >= NUM_PPP || !pc->openFlag) { + st = 0; + PPPDEBUG(LOG_WARNING, ("sifup[%d]: bad parms\n", pd)); + } else { + netif_remove(&pc->netif); + if (netif_add(&pc->netif, &pc->addrs.our_ipaddr, &pc->addrs.netmask, + &pc->addrs.his_ipaddr, (void *)(size_t)pd, pppifNetifInit, ip_input)) { + netif_set_up(&pc->netif); + pc->if_up = 1; + pc->errCode = PPPERR_NONE; + + PPPDEBUG(LOG_DEBUG, ("sifup: unit %d: linkStatusCB=%p errCode=%d\n", pd, pc->linkStatusCB, pc->errCode)); + if (pc->linkStatusCB) { + pc->linkStatusCB(pc->linkStatusCtx, pc->errCode, &pc->addrs); + } + } else { + st = 0; + PPPDEBUG(LOG_ERR, ("sifup[%d]: netif_add failed\n", pd)); + } + } + + return st; +} + +/* + * sifnpmode - Set the mode for handling packets for a given NP. + */ +int +sifnpmode(int u, int proto, enum NPmode mode) +{ + LWIP_UNUSED_ARG(u); + LWIP_UNUSED_ARG(proto); + LWIP_UNUSED_ARG(mode); + return 0; +} + +/* + * sifdown - Config the interface down and disable IP. + */ +int +sifdown(int pd) +{ + PPPControl *pc = &pppControl[pd]; + int st = 1; + + if (pd < 0 || pd >= NUM_PPP || !pc->openFlag) { + st = 0; + PPPDEBUG(LOG_WARNING, ("sifdown[%d]: bad parms\n", pd)); + } else { + pc->if_up = 0; + /* make sure the netif status callback is called */ + netif_set_down(&pc->netif); + netif_remove(&pc->netif); + PPPDEBUG(LOG_DEBUG, ("sifdown: unit %d: linkStatusCB=%p errCode=%d\n", pd, pc->linkStatusCB, pc->errCode)); + if (pc->linkStatusCB) { + pc->linkStatusCB(pc->linkStatusCtx, PPPERR_CONNECT, NULL); + } + } + return st; +} + +/** + * sifaddr - Config the interface IP addresses and netmask. + * @param pd Interface unit ??? + * @param o Our IP address ??? + * @param h His IP address ??? + * @param m IP subnet mask ??? + * @param ns1 Primary DNS + * @param ns2 Secondary DNS + */ +int +sifaddr( int pd, u32_t o, u32_t h, u32_t m, u32_t ns1, u32_t ns2) +{ + PPPControl *pc = &pppControl[pd]; + int st = 1; + + if (pd < 0 || pd >= NUM_PPP || !pc->openFlag) { + st = 0; + PPPDEBUG(LOG_WARNING, ("sifup[%d]: bad parms\n", pd)); + } else { + SMEMCPY(&pc->addrs.our_ipaddr, &o, sizeof(o)); + SMEMCPY(&pc->addrs.his_ipaddr, &h, sizeof(h)); + SMEMCPY(&pc->addrs.netmask, &m, sizeof(m)); + SMEMCPY(&pc->addrs.dns1, &ns1, sizeof(ns1)); + SMEMCPY(&pc->addrs.dns2, &ns2, sizeof(ns2)); + } + return st; +} + +/** + * cifaddr - Clear the interface IP addresses, and delete routes + * through the interface if possible. + * @param pd Interface unit ??? + * @param o Our IP address ??? + * @param h IP broadcast address ??? + */ +int +cifaddr( int pd, u32_t o, u32_t h) +{ + PPPControl *pc = &pppControl[pd]; + int st = 1; + + LWIP_UNUSED_ARG(o); + LWIP_UNUSED_ARG(h); + if (pd < 0 || pd >= NUM_PPP || !pc->openFlag) { + st = 0; + PPPDEBUG(LOG_WARNING, ("sifup[%d]: bad parms\n", pd)); + } else { + IP4_ADDR(&pc->addrs.our_ipaddr, 0,0,0,0); + IP4_ADDR(&pc->addrs.his_ipaddr, 0,0,0,0); + IP4_ADDR(&pc->addrs.netmask, 255,255,255,0); + IP4_ADDR(&pc->addrs.dns1, 0,0,0,0); + IP4_ADDR(&pc->addrs.dns2, 0,0,0,0); + } + return st; +} + +/* + * sifdefaultroute - assign a default route through the address given. + */ +int +sifdefaultroute(int pd, u32_t l, u32_t g) +{ + PPPControl *pc = &pppControl[pd]; + int st = 1; + + LWIP_UNUSED_ARG(l); + LWIP_UNUSED_ARG(g); + + if (pd < 0 || pd >= NUM_PPP || !pc->openFlag) { + st = 0; + PPPDEBUG(LOG_WARNING, ("sifup[%d]: bad parms\n", pd)); + } else { + netif_set_default(&pc->netif); + } + + /* TODO: check how PPP handled the netMask, previously not set by ipSetDefault */ + + return st; +} + +/* + * cifdefaultroute - delete a default route through the address given. + */ +int +cifdefaultroute(int pd, u32_t l, u32_t g) +{ + PPPControl *pc = &pppControl[pd]; + int st = 1; + + LWIP_UNUSED_ARG(l); + LWIP_UNUSED_ARG(g); + + if (pd < 0 || pd >= NUM_PPP || !pc->openFlag) { + st = 0; + PPPDEBUG(LOG_WARNING, ("sifup[%d]: bad parms\n", pd)); + } else { + netif_set_default(NULL); + } + + return st; +} + +/**********************************/ +/*** LOCAL FUNCTION DEFINITIONS ***/ +/**********************************/ + +#if PPPOS_SUPPORT && PPP_INPROC_OWNTHREAD +/* The main PPP process function. This implements the state machine according + * to section 4 of RFC 1661: The Point-To-Point Protocol. */ +static void +pppInputThread(void *arg) +{ + int count; + PPPControlRx *pcrx = arg; + + do + { + sys_arch_mbox_fetch(&pppMbox, (void**)&pcrx, 0); //Wait indefinitely + + while (lcp_phase[pcrx->pd] != PHASE_DEAD) { + count = sio_read(pcrx->fd, pcrx->rxbuf, PPPOS_RX_BUFSIZE); + if(count > 0) { + pppInProc(pcrx, pcrx->rxbuf, count); + } else { + /* nothing received, give other tasks a chance to run */ + sys_msleep(1); + } + } + } while(1); //Never terminates +} +#endif /* PPPOS_SUPPORT && PPP_INPROC_OWNTHREAD */ + +#if PPPOE_SUPPORT + +void +pppOverEthernetInitFailed(int pd) +{ + PPPControl* pc; + + pppHup(pd); + pppStop(pd); + + pc = &pppControl[pd]; + pppoe_destroy(&pc->netif); + pc->openFlag = 0; + + if(pc->linkStatusCB) { + pc->linkStatusCB(pc->linkStatusCtx, pc->errCode ? pc->errCode : PPPERR_PROTOCOL, NULL); + } +} + +static void +pppOverEthernetLinkStatusCB(int pd, int up) +{ + if(up) { + PPPDEBUG(LOG_INFO, ("pppOverEthernetLinkStatusCB: unit %d: Connecting\n", pd)); + pppStart(pd); + } else { + pppOverEthernetInitFailed(pd); + } +} +#endif /* PPPOE_SUPPORT */ + +struct pbuf * +pppSingleBuf(struct pbuf *p) +{ + struct pbuf *q, *b; + u_char *pl; + + if(p->tot_len == p->len) { + return p; + } + + q = pbuf_alloc(PBUF_RAW, p->tot_len, PBUF_RAM); + if(!q) { + PPPDEBUG(LOG_ERR, + ("pppSingleBuf: unable to alloc new buf (%d)\n", p->tot_len)); + return p; /* live dangerously */ + } + + for(b = p, pl = q->payload; b != NULL; b = b->next) { + MEMCPY(pl, b->payload, b->len); + pl += b->len; + } + + pbuf_free(p); + + return q; +} + +struct pppInputHeader { + int unit; + u16_t proto; +}; + +/* + * Pass the processed input packet to the appropriate handler. + * This function and all handlers run in the context of the tcpip_thread + */ +static void +pppInput(void *arg) +{ + struct pbuf *nb = (struct pbuf *)arg; + u16_t protocol; + int pd; + + pd = ((struct pppInputHeader *)nb->payload)->unit; + protocol = ((struct pppInputHeader *)nb->payload)->proto; + + if(pbuf_header(nb, -(int)sizeof(struct pppInputHeader))) { + LWIP_ASSERT("pbuf_header failed\n", 0); + goto drop; + } + + LINK_STATS_INC(link.recv); + snmp_inc_ifinucastpkts(&pppControl[pd].netif); + snmp_add_ifinoctets(&pppControl[pd].netif, nb->tot_len); + + /* + * Toss all non-LCP packets unless LCP is OPEN. + * Until we get past the authentication phase, toss all packets + * except LCP, LQR and authentication packets. + */ + if((lcp_phase[pd] <= PHASE_AUTHENTICATE) && (protocol != PPP_LCP)) { + if(!((protocol == PPP_LQR) || (protocol == PPP_PAP) || (protocol == PPP_CHAP)) || + (lcp_phase[pd] != PHASE_AUTHENTICATE)) { + PPPDEBUG(LOG_INFO, ("pppInput: discarding proto 0x%"X16_F" in phase %d\n", protocol, lcp_phase[pd])); + goto drop; + } + } + + switch(protocol) { + case PPP_VJC_COMP: /* VJ compressed TCP */ +#if PPPOS_SUPPORT && VJ_SUPPORT + PPPDEBUG(LOG_INFO, ("pppInput[%d]: vj_comp in pbuf len=%d\n", pd, nb->len)); + /* + * Clip off the VJ header and prepend the rebuilt TCP/IP header and + * pass the result to IP. + */ + if ((vj_uncompress_tcp(&nb, &pppControl[pd].vjComp) >= 0) && (pppControl[pd].netif.input)) { + pppControl[pd].netif.input(nb, &pppControl[pd].netif); + return; + } + /* Something's wrong so drop it. */ + PPPDEBUG(LOG_WARNING, ("pppInput[%d]: Dropping VJ compressed\n", pd)); +#else /* PPPOS_SUPPORT && VJ_SUPPORT */ + /* No handler for this protocol so drop the packet. */ + PPPDEBUG(LOG_INFO, ("pppInput[%d]: drop VJ Comp in %d:%s\n", pd, nb->len, nb->payload)); +#endif /* PPPOS_SUPPORT && VJ_SUPPORT */ + break; + + case PPP_VJC_UNCOMP: /* VJ uncompressed TCP */ +#if PPPOS_SUPPORT && VJ_SUPPORT + PPPDEBUG(LOG_INFO, ("pppInput[%d]: vj_un in pbuf len=%d\n", pd, nb->len)); + /* + * Process the TCP/IP header for VJ header compression and then pass + * the packet to IP. + */ + if ((vj_uncompress_uncomp(nb, &pppControl[pd].vjComp) >= 0) && pppControl[pd].netif.input) { + pppControl[pd].netif.input(nb, &pppControl[pd].netif); + return; + } + /* Something's wrong so drop it. */ + PPPDEBUG(LOG_WARNING, ("pppInput[%d]: Dropping VJ uncompressed\n", pd)); +#else /* PPPOS_SUPPORT && VJ_SUPPORT */ + /* No handler for this protocol so drop the packet. */ + PPPDEBUG(LOG_INFO, + ("pppInput[%d]: drop VJ UnComp in %d:.*H\n", + pd, nb->len, LWIP_MIN(nb->len * 2, 40), nb->payload)); +#endif /* PPPOS_SUPPORT && VJ_SUPPORT */ + break; + + case PPP_IP: /* Internet Protocol */ + PPPDEBUG(LOG_INFO, ("pppInput[%d]: ip in pbuf len=%d\n", pd, nb->len)); + if (pppControl[pd].netif.input) { + pppControl[pd].netif.input(nb, &pppControl[pd].netif); + return; + } + break; + + default: { + struct protent *protp; + int i; + + /* + * Upcall the proper protocol input routine. + */ + for (i = 0; (protp = ppp_protocols[i]) != NULL; ++i) { + if (protp->protocol == protocol && protp->enabled_flag) { + PPPDEBUG(LOG_INFO, ("pppInput[%d]: %s len=%d\n", pd, protp->name, nb->len)); + nb = pppSingleBuf(nb); + (*protp->input)(pd, nb->payload, nb->len); + PPPDEBUG(LOG_DETAIL, ("pppInput[%d]: packet processed\n", pd)); + goto out; + } + } + + /* No handler for this protocol so reject the packet. */ + PPPDEBUG(LOG_INFO, ("pppInput[%d]: rejecting unsupported proto 0x%"X16_F" len=%d\n", pd, protocol, nb->len)); + if (pbuf_header(nb, sizeof(protocol))) { + LWIP_ASSERT("pbuf_header failed\n", 0); + goto drop; + } +#if BYTE_ORDER == LITTLE_ENDIAN + protocol = htons(protocol); +#endif /* BYTE_ORDER == LITTLE_ENDIAN */ + SMEMCPY(nb->payload, &protocol, sizeof(protocol)); + lcp_sprotrej(pd, nb->payload, nb->len); + } + break; + } + +drop: + LINK_STATS_INC(link.drop); + snmp_inc_ifindiscards(&pppControl[pd].netif); + +out: + pbuf_free(nb); + return; +} + +#if PPPOS_SUPPORT +/* + * Drop the input packet. + */ +static void +pppDrop(PPPControlRx *pcrx) +{ + if (pcrx->inHead != NULL) { +#if 0 + PPPDEBUG(LOG_INFO, ("pppDrop: %d:%.*H\n", pcrx->inHead->len, min(60, pcrx->inHead->len * 2), pcrx->inHead->payload)); +#endif + PPPDEBUG(LOG_INFO, ("pppDrop: pbuf len=%d, addr %p\n", pcrx->inHead->len, (void*)pcrx->inHead)); + if (pcrx->inTail && (pcrx->inTail != pcrx->inHead)) { + pbuf_free(pcrx->inTail); + } + pbuf_free(pcrx->inHead); + pcrx->inHead = NULL; + pcrx->inTail = NULL; + } +#if VJ_SUPPORT + vj_uncompress_err(&pppControl[pcrx->pd].vjComp); +#endif /* VJ_SUPPORT */ + + LINK_STATS_INC(link.drop); + snmp_inc_ifindiscards(&pppControl[pcrx->pd].netif); +} + +/** Pass received raw characters to PPPoS to be decoded. This function is + * thread-safe and can be called from a dedicated RX-thread or from a main-loop. + * + * @param pd PPP descriptor index, returned by pppOpen() + * @param data received data + * @param len length of received data + */ +void +pppos_input(int pd, u_char* data, int len) +{ + pppInProc(&pppControl[pd].rx, data, len); +} + +/** + * Process a received octet string. + */ +static void +pppInProc(PPPControlRx *pcrx, u_char *s, int l) +{ + struct pbuf *nextNBuf; + u_char curChar; + u_char escaped; + SYS_ARCH_DECL_PROTECT(lev); + + PPPDEBUG(LOG_DEBUG, ("pppInProc[%d]: got %d bytes\n", pcrx->pd, l)); + while (l-- > 0) { + curChar = *s++; + + SYS_ARCH_PROTECT(lev); + escaped = ESCAPE_P(pcrx->inACCM, curChar); + SYS_ARCH_UNPROTECT(lev); + /* Handle special characters. */ + if (escaped) { + /* Check for escape sequences. */ + /* XXX Note that this does not handle an escaped 0x5d character which + * would appear as an escape character. Since this is an ASCII ']' + * and there is no reason that I know of to escape it, I won't complicate + * the code to handle this case. GLL */ + if (curChar == PPP_ESCAPE) { + pcrx->inEscaped = 1; + /* Check for the flag character. */ + } else if (curChar == PPP_FLAG) { + /* If this is just an extra flag character, ignore it. */ + if (pcrx->inState <= PDADDRESS) { + /* ignore it */; + /* If we haven't received the packet header, drop what has come in. */ + } else if (pcrx->inState < PDDATA) { + PPPDEBUG(LOG_WARNING, + ("pppInProc[%d]: Dropping incomplete packet %d\n", + pcrx->pd, pcrx->inState)); + LINK_STATS_INC(link.lenerr); + pppDrop(pcrx); + /* If the fcs is invalid, drop the packet. */ + } else if (pcrx->inFCS != PPP_GOODFCS) { + PPPDEBUG(LOG_INFO, + ("pppInProc[%d]: Dropping bad fcs 0x%"X16_F" proto=0x%"X16_F"\n", + pcrx->pd, pcrx->inFCS, pcrx->inProtocol)); + /* Note: If you get lots of these, check for UART frame errors or try different baud rate */ + LINK_STATS_INC(link.chkerr); + pppDrop(pcrx); + /* Otherwise it's a good packet so pass it on. */ + } else { + struct pbuf *inp; + /* Trim off the checksum. */ + if(pcrx->inTail->len >= 2) { + pcrx->inTail->len -= 2; + + pcrx->inTail->tot_len = pcrx->inTail->len; + if (pcrx->inTail != pcrx->inHead) { + pbuf_cat(pcrx->inHead, pcrx->inTail); + } + } else { + pcrx->inTail->tot_len = pcrx->inTail->len; + if (pcrx->inTail != pcrx->inHead) { + pbuf_cat(pcrx->inHead, pcrx->inTail); + } + + pbuf_realloc(pcrx->inHead, pcrx->inHead->tot_len - 2); + } + + /* Dispatch the packet thereby consuming it. */ + inp = pcrx->inHead; + /* Packet consumed, release our references. */ + pcrx->inHead = NULL; + pcrx->inTail = NULL; +#if PPP_INPROC_MULTITHREADED + if(tcpip_callback_with_block(pppInput, inp, 0) != ERR_OK) { + PPPDEBUG(LOG_ERR, ("pppInProc[%d]: tcpip_callback() failed, dropping packet\n", pcrx->pd)); + pbuf_free(inp); + LINK_STATS_INC(link.drop); + snmp_inc_ifindiscards(&pppControl[pcrx->pd].netif); + } +#else /* PPP_INPROC_MULTITHREADED */ + pppInput(inp); +#endif /* PPP_INPROC_MULTITHREADED */ + } + + /* Prepare for a new packet. */ + pcrx->inFCS = PPP_INITFCS; + pcrx->inState = PDADDRESS; + pcrx->inEscaped = 0; + /* Other characters are usually control characters that may have + * been inserted by the physical layer so here we just drop them. */ + } else { + PPPDEBUG(LOG_WARNING, + ("pppInProc[%d]: Dropping ACCM char <%d>\n", pcrx->pd, curChar)); + } + /* Process other characters. */ + } else { + /* Unencode escaped characters. */ + if (pcrx->inEscaped) { + pcrx->inEscaped = 0; + curChar ^= PPP_TRANS; + } + + /* Process character relative to current state. */ + switch(pcrx->inState) { + case PDIDLE: /* Idle state - waiting. */ + /* Drop the character if it's not 0xff + * we would have processed a flag character above. */ + if (curChar != PPP_ALLSTATIONS) { + break; + } + + /* Fall through */ + case PDSTART: /* Process start flag. */ + /* Prepare for a new packet. */ + pcrx->inFCS = PPP_INITFCS; + + /* Fall through */ + case PDADDRESS: /* Process address field. */ + if (curChar == PPP_ALLSTATIONS) { + pcrx->inState = PDCONTROL; + break; + } + /* Else assume compressed address and control fields so + * fall through to get the protocol... */ + case PDCONTROL: /* Process control field. */ + /* If we don't get a valid control code, restart. */ + if (curChar == PPP_UI) { + pcrx->inState = PDPROTOCOL1; + break; + } +#if 0 + else { + PPPDEBUG(LOG_WARNING, + ("pppInProc[%d]: Invalid control <%d>\n", pcrx->pd, curChar)); + pcrx->inState = PDSTART; + } +#endif + case PDPROTOCOL1: /* Process protocol field 1. */ + /* If the lower bit is set, this is the end of the protocol + * field. */ + if (curChar & 1) { + pcrx->inProtocol = curChar; + pcrx->inState = PDDATA; + } else { + pcrx->inProtocol = (u_int)curChar << 8; + pcrx->inState = PDPROTOCOL2; + } + break; + case PDPROTOCOL2: /* Process protocol field 2. */ + pcrx->inProtocol |= curChar; + pcrx->inState = PDDATA; + break; + case PDDATA: /* Process data byte. */ + /* Make space to receive processed data. */ + if (pcrx->inTail == NULL || pcrx->inTail->len == PBUF_POOL_BUFSIZE) { + if (pcrx->inTail != NULL) { + pcrx->inTail->tot_len = pcrx->inTail->len; + if (pcrx->inTail != pcrx->inHead) { + pbuf_cat(pcrx->inHead, pcrx->inTail); + /* give up the inTail reference now */ + pcrx->inTail = NULL; + } + } + /* If we haven't started a packet, we need a packet header. */ + nextNBuf = pbuf_alloc(PBUF_RAW, 0, PBUF_POOL); + if (nextNBuf == NULL) { + /* No free buffers. Drop the input packet and let the + * higher layers deal with it. Continue processing + * the received pbuf chain in case a new packet starts. */ + PPPDEBUG(LOG_ERR, ("pppInProc[%d]: NO FREE MBUFS!\n", pcrx->pd)); + LINK_STATS_INC(link.memerr); + pppDrop(pcrx); + pcrx->inState = PDSTART; /* Wait for flag sequence. */ + break; + } + if (pcrx->inHead == NULL) { + struct pppInputHeader *pih = nextNBuf->payload; + + pih->unit = pcrx->pd; + pih->proto = pcrx->inProtocol; + + nextNBuf->len += sizeof(*pih); + + pcrx->inHead = nextNBuf; + } + pcrx->inTail = nextNBuf; + } + /* Load character into buffer. */ + ((u_char*)pcrx->inTail->payload)[pcrx->inTail->len++] = curChar; + break; + } + + /* update the frame check sequence number. */ + pcrx->inFCS = PPP_FCS(pcrx->inFCS, curChar); + } + } /* while (l-- > 0), all bytes processed */ + + avRandomize(); +} +#endif /* PPPOS_SUPPORT */ + +#if PPPOE_SUPPORT +void +pppInProcOverEthernet(int pd, struct pbuf *pb) +{ + struct pppInputHeader *pih; + u16_t inProtocol; + + if(pb->len < sizeof(inProtocol)) { + PPPDEBUG(LOG_ERR, ("pppInProcOverEthernet: too small for protocol field\n")); + goto drop; + } + + inProtocol = (((u8_t *)pb->payload)[0] << 8) | ((u8_t*)pb->payload)[1]; + + /* make room for pppInputHeader - should not fail */ + if (pbuf_header(pb, sizeof(*pih) - sizeof(inProtocol)) != 0) { + PPPDEBUG(LOG_ERR, ("pppInProcOverEthernet: could not allocate room for header\n")); + goto drop; + } + + pih = pb->payload; + + pih->unit = pd; + pih->proto = inProtocol; + + /* Dispatch the packet thereby consuming it. */ + pppInput(pb); + return; + +drop: + LINK_STATS_INC(link.drop); + snmp_inc_ifindiscards(&pppControl[pd].netif); + pbuf_free(pb); + return; +} +#endif /* PPPOE_SUPPORT */ + +#if LWIP_NETIF_STATUS_CALLBACK +/** Set the status callback of a PPP's netif + * + * @param pd The PPP descriptor returned by pppOpen() + * @param status_callback pointer to the status callback function + * + * @see netif_set_status_callback + */ +void +ppp_set_netif_statuscallback(int pd, netif_status_callback_fn status_callback) +{ + netif_set_status_callback(&pppControl[pd].netif, status_callback); +} +#endif /* LWIP_NETIF_STATUS_CALLBACK */ + +#if LWIP_NETIF_LINK_CALLBACK +/** Set the link callback of a PPP's netif + * + * @param pd The PPP descriptor returned by pppOpen() + * @param link_callback pointer to the link callback function + * + * @see netif_set_link_callback + */ +void +ppp_set_netif_linkcallback(int pd, netif_status_callback_fn link_callback) +{ + netif_set_link_callback(&pppControl[pd].netif, link_callback); +} +#endif /* LWIP_NETIF_LINK_CALLBACK */ + +#endif /* PPP_SUPPORT */ diff --git a/features/unsupported/net/lwip/lwip/netif/ppp/ppp.h b/features/unsupported/net/lwip/lwip/netif/ppp/ppp.h new file mode 100644 index 00000000000..a72ac9576ba --- /dev/null +++ b/features/unsupported/net/lwip/lwip/netif/ppp/ppp.h @@ -0,0 +1,483 @@ +/***************************************************************************** +* ppp.h - Network Point to Point Protocol header file. +* +* Copyright (c) 2003 by Marc Boucher, Services Informatiques (MBSI) inc. +* portions Copyright (c) 1997 Global Election Systems Inc. +* +* The authors hereby grant permission to use, copy, modify, distribute, +* and license this software and its documentation for any purpose, provided +* that existing copyright notices are retained in all copies and that this +* notice and the following disclaimer are included verbatim in any +* distributions. No written agreement, license, or royalty fee is required +* for any of the authorized uses. +* +* THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS *AS IS* AND ANY EXPRESS OR +* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +* IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT +* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +****************************************************************************** +* REVISION HISTORY +* +* 03-01-01 Marc Boucher +* Ported to lwIP. +* 97-11-05 Guy Lancaster , Global Election Systems Inc. +* Original derived from BSD codes. +*****************************************************************************/ + +#ifndef PPP_H +#define PPP_H + +#include "lwip/opt.h" + +#if PPP_SUPPORT /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/def.h" +#include "lwip/sio.h" +#include "lwip/stats.h" +#include "lwip/mem.h" +#include "lwip/netif.h" +#include "lwip/sys.h" +#include "lwip/timers.h" + +/** Some defines for code we skip compared to the original pppd. + * These are just here to minimise the use of the ugly "#if 0". */ +#define PPP_ADDITIONAL_CALLBACKS 0 + +/** Some error checks to test for unsupported code */ +#if CBCP_SUPPORT +#error "CBCP is not supported in lwIP PPP" +#endif +#if CCP_SUPPORT +#error "CCP is not supported in lwIP PPP" +#endif + +/* + * pppd.h - PPP daemon global declarations. + * + * Copyright (c) 1989 Carnegie Mellon University. + * All rights reserved. + * + * Redistribution and use in source and binary forms are permitted + * provided that the above copyright notice and this paragraph are + * duplicated in all such forms and that any documentation, + * advertising materials, and other materials related to such + * distribution and use acknowledge that the software was developed + * by Carnegie Mellon University. The name of the + * University may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED + * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. + * + */ +/* + * ppp_defs.h - PPP definitions. + * + * Copyright (c) 1994 The Australian National University. + * All rights reserved. + * + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, provided that the above copyright + * notice appears in all copies. This software is provided without any + * warranty, express or implied. The Australian National University + * makes no representations about the suitability of this software for + * any purpose. + * + * IN NO EVENT SHALL THE AUSTRALIAN NATIONAL UNIVERSITY BE LIABLE TO ANY + * PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES + * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF + * THE AUSTRALIAN NATIONAL UNIVERSITY HAVE BEEN ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * THE AUSTRALIAN NATIONAL UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + * AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS + * ON AN "AS IS" BASIS, AND THE AUSTRALIAN NATIONAL UNIVERSITY HAS NO + * OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, + * OR MODIFICATIONS. + */ + +#define TIMEOUT(f, a, t) do { sys_untimeout((f), (a)); sys_timeout((t)*1000, (f), (a)); } while(0) +#define UNTIMEOUT(f, a) sys_untimeout((f), (a)) + + +#ifndef __u_char_defined + +/* Type definitions for BSD code. */ +typedef unsigned long u_long; +typedef unsigned int u_int; +typedef unsigned short u_short; +typedef unsigned char u_char; + +#endif + +/* + * Constants and structures defined by the internet system, + * Per RFC 790, September 1981, and numerous additions. + */ + +/* + * The basic PPP frame. + */ +#define PPP_HDRLEN 4 /* octets for standard ppp header */ +#define PPP_FCSLEN 2 /* octets for FCS */ + + +/* + * Significant octet values. + */ +#define PPP_ALLSTATIONS 0xff /* All-Stations broadcast address */ +#define PPP_UI 0x03 /* Unnumbered Information */ +#define PPP_FLAG 0x7e /* Flag Sequence */ +#define PPP_ESCAPE 0x7d /* Asynchronous Control Escape */ +#define PPP_TRANS 0x20 /* Asynchronous transparency modifier */ + +/* + * Protocol field values. + */ +#define PPP_IP 0x21 /* Internet Protocol */ +#define PPP_AT 0x29 /* AppleTalk Protocol */ +#define PPP_VJC_COMP 0x2d /* VJ compressed TCP */ +#define PPP_VJC_UNCOMP 0x2f /* VJ uncompressed TCP */ +#define PPP_COMP 0xfd /* compressed packet */ +#define PPP_IPCP 0x8021 /* IP Control Protocol */ +#define PPP_ATCP 0x8029 /* AppleTalk Control Protocol */ +#define PPP_CCP 0x80fd /* Compression Control Protocol */ +#define PPP_LCP 0xc021 /* Link Control Protocol */ +#define PPP_PAP 0xc023 /* Password Authentication Protocol */ +#define PPP_LQR 0xc025 /* Link Quality Report protocol */ +#define PPP_CHAP 0xc223 /* Cryptographic Handshake Auth. Protocol */ +#define PPP_CBCP 0xc029 /* Callback Control Protocol */ + +/* + * Values for FCS calculations. + */ +#define PPP_INITFCS 0xffff /* Initial FCS value */ +#define PPP_GOODFCS 0xf0b8 /* Good final FCS value */ +#define PPP_FCS(fcs, c) (((fcs) >> 8) ^ fcstab[((fcs) ^ (c)) & 0xff]) + +/* + * Extended asyncmap - allows any character to be escaped. + */ +typedef u_char ext_accm[32]; + +/* + * What to do with network protocol (NP) packets. + */ +enum NPmode { + NPMODE_PASS, /* pass the packet through */ + NPMODE_DROP, /* silently drop the packet */ + NPMODE_ERROR, /* return an error */ + NPMODE_QUEUE /* save it up for later. */ +}; + +/* + * Inline versions of get/put char/short/long. + * Pointer is advanced; we assume that both arguments + * are lvalues and will already be in registers. + * cp MUST be u_char *. + */ +#define GETCHAR(c, cp) { \ + (c) = *(cp)++; \ +} +#define PUTCHAR(c, cp) { \ + *(cp)++ = (u_char) (c); \ +} + + +#define GETSHORT(s, cp) { \ + (s) = *(cp); (cp)++; (s) <<= 8; \ + (s) |= *(cp); (cp)++; \ +} +#define PUTSHORT(s, cp) { \ + *(cp)++ = (u_char) ((s) >> 8); \ + *(cp)++ = (u_char) (s & 0xff); \ +} + +#define GETLONG(l, cp) { \ + (l) = *(cp); (cp)++; (l) <<= 8; \ + (l) |= *(cp); (cp)++; (l) <<= 8; \ + (l) |= *(cp); (cp)++; (l) <<= 8; \ + (l) |= *(cp); (cp)++; \ +} +#define PUTLONG(l, cp) { \ + *(cp)++ = (u_char) ((l) >> 24); \ + *(cp)++ = (u_char) ((l) >> 16); \ + *(cp)++ = (u_char) ((l) >> 8); \ + *(cp)++ = (u_char) (l); \ +} + + +#define INCPTR(n, cp) ((cp) += (n)) +#define DECPTR(n, cp) ((cp) -= (n)) + +#define BCMP(s0, s1, l) memcmp((u_char *)(s0), (u_char *)(s1), (l)) +#define BCOPY(s, d, l) MEMCPY((d), (s), (l)) +#define BZERO(s, n) memset(s, 0, n) + +#if PPP_DEBUG +#define PRINTMSG(m, l) { m[l] = '\0'; LWIP_DEBUGF(LOG_INFO, ("Remote message: %s\n", m)); } +#else /* PPP_DEBUG */ +#define PRINTMSG(m, l) +#endif /* PPP_DEBUG */ + +/* + * MAKEHEADER - Add PPP Header fields to a packet. + */ +#define MAKEHEADER(p, t) { \ + PUTCHAR(PPP_ALLSTATIONS, p); \ + PUTCHAR(PPP_UI, p); \ + PUTSHORT(t, p); } + +/************************* +*** PUBLIC DEFINITIONS *** +*************************/ + +/* Error codes. */ +#define PPPERR_NONE 0 /* No error. */ +#define PPPERR_PARAM -1 /* Invalid parameter. */ +#define PPPERR_OPEN -2 /* Unable to open PPP session. */ +#define PPPERR_DEVICE -3 /* Invalid I/O device for PPP. */ +#define PPPERR_ALLOC -4 /* Unable to allocate resources. */ +#define PPPERR_USER -5 /* User interrupt. */ +#define PPPERR_CONNECT -6 /* Connection lost. */ +#define PPPERR_AUTHFAIL -7 /* Failed authentication challenge. */ +#define PPPERR_PROTOCOL -8 /* Failed to meet protocol. */ + +/* + * PPP IOCTL commands. + */ +/* + * Get the up status - 0 for down, non-zero for up. The argument must + * point to an int. + */ +#define PPPCTLG_UPSTATUS 100 /* Get the up status - 0 down else up */ +#define PPPCTLS_ERRCODE 101 /* Set the error code */ +#define PPPCTLG_ERRCODE 102 /* Get the error code */ +#define PPPCTLG_FD 103 /* Get the fd associated with the ppp */ + +/************************ +*** PUBLIC DATA TYPES *** +************************/ + +/* + * The following struct gives the addresses of procedures to call + * for a particular protocol. + */ +struct protent { + u_short protocol; /* PPP protocol number */ + /* Initialization procedure */ + void (*init) (int unit); + /* Process a received packet */ + void (*input) (int unit, u_char *pkt, int len); + /* Process a received protocol-reject */ + void (*protrej) (int unit); + /* Lower layer has come up */ + void (*lowerup) (int unit); + /* Lower layer has gone down */ + void (*lowerdown) (int unit); + /* Open the protocol */ + void (*open) (int unit); + /* Close the protocol */ + void (*close) (int unit, char *reason); +#if PPP_ADDITIONAL_CALLBACKS + /* Print a packet in readable form */ + int (*printpkt) (u_char *pkt, int len, + void (*printer) (void *, char *, ...), + void *arg); + /* Process a received data packet */ + void (*datainput) (int unit, u_char *pkt, int len); +#endif /* PPP_ADDITIONAL_CALLBACKS */ + int enabled_flag; /* 0 if protocol is disabled */ + char *name; /* Text name of protocol */ +#if PPP_ADDITIONAL_CALLBACKS + /* Check requested options, assign defaults */ + void (*check_options) (u_long); + /* Configure interface for demand-dial */ + int (*demand_conf) (int unit); + /* Say whether to bring up link for this pkt */ + int (*active_pkt) (u_char *pkt, int len); +#endif /* PPP_ADDITIONAL_CALLBACKS */ +}; + +/* + * The following structure records the time in seconds since + * the last NP packet was sent or received. + */ +struct ppp_idle { + u_short xmit_idle; /* seconds since last NP packet sent */ + u_short recv_idle; /* seconds since last NP packet received */ +}; + +struct ppp_settings { + + u_int disable_defaultip : 1; /* Don't use hostname for default IP addrs */ + u_int auth_required : 1; /* Peer is required to authenticate */ + u_int explicit_remote : 1; /* remote_name specified with remotename opt */ + u_int refuse_pap : 1; /* Don't wanna auth. ourselves with PAP */ + u_int refuse_chap : 1; /* Don't wanna auth. ourselves with CHAP */ + u_int usehostname : 1; /* Use hostname for our_name */ + u_int usepeerdns : 1; /* Ask peer for DNS adds */ + + u_short idle_time_limit; /* Shut down link if idle for this long */ + int maxconnect; /* Maximum connect time (seconds) */ + + char user [MAXNAMELEN + 1]; /* Username for PAP */ + char passwd [MAXSECRETLEN + 1]; /* Password for PAP, secret for CHAP */ + char our_name [MAXNAMELEN + 1]; /* Our name for authentication purposes */ + char remote_name[MAXNAMELEN + 1]; /* Peer's name for authentication */ +}; + +struct ppp_addrs { + ip_addr_t our_ipaddr, his_ipaddr, netmask, dns1, dns2; +}; + +/***************************** +*** PUBLIC DATA STRUCTURES *** +*****************************/ + +/* Buffers for outgoing packets. */ +extern u_char outpacket_buf[NUM_PPP][PPP_MRU+PPP_HDRLEN]; + +extern struct ppp_settings ppp_settings; + +extern struct protent *ppp_protocols[]; /* Table of pointers to supported protocols */ + + +/*********************** +*** PUBLIC FUNCTIONS *** +***********************/ + +/* Initialize the PPP subsystem. */ +void pppInit(void); + +/* Warning: Using PPPAUTHTYPE_ANY might have security consequences. + * RFC 1994 says: + * + * In practice, within or associated with each PPP server, there is a + * database which associates "user" names with authentication + * information ("secrets"). It is not anticipated that a particular + * named user would be authenticated by multiple methods. This would + * make the user vulnerable to attacks which negotiate the least secure + * method from among a set (such as PAP rather than CHAP). If the same + * secret was used, PAP would reveal the secret to be used later with + * CHAP. + * + * Instead, for each user name there should be an indication of exactly + * one method used to authenticate that user name. If a user needs to + * make use of different authentication methods under different + * circumstances, then distinct user names SHOULD be employed, each of + * which identifies exactly one authentication method. + * + */ +enum pppAuthType { + PPPAUTHTYPE_NONE, + PPPAUTHTYPE_ANY, + PPPAUTHTYPE_PAP, + PPPAUTHTYPE_CHAP +}; + +void pppSetAuth(enum pppAuthType authType, const char *user, const char *passwd); + +/* + * Open a new PPP connection using the given serial I/O device. + * This initializes the PPP control block but does not + * attempt to negotiate the LCP session. + * Return a new PPP connection descriptor on success or + * an error code (negative) on failure. + */ +int pppOverSerialOpen(sio_fd_t fd, void (*linkStatusCB)(void *ctx, int errCode, void *arg), void *linkStatusCtx); + +/* + * Open a new PPP Over Ethernet (PPPOE) connection. + */ +int pppOverEthernetOpen(struct netif *ethif, const char *service_name, const char *concentrator_name, void (*linkStatusCB)(void *ctx, int errCode, void *arg), void *linkStatusCtx); + +/* for source code compatibility */ +#define pppOpen(fd,cb,ls) pppOverSerialOpen(fd,cb,ls) + +/* + * Close a PPP connection and release the descriptor. + * Any outstanding packets in the queues are dropped. + * Return 0 on success, an error code on failure. + */ +int pppClose(int pd); + +/* + * Indicate to the PPP process that the line has disconnected. + */ +void pppSigHUP(int pd); + +/* + * Get and set parameters for the given connection. + * Return 0 on success, an error code on failure. + */ +int pppIOCtl(int pd, int cmd, void *arg); + +/* + * Return the Maximum Transmission Unit for the given PPP connection. + */ +u_short pppMTU(int pd); + +/* + * Write n characters to a ppp link. + * RETURN: >= 0 Number of characters written, -1 Failed to write to device. + */ +int pppWrite(int pd, const u_char *s, int n); + +void pppInProcOverEthernet(int pd, struct pbuf *pb); + +struct pbuf *pppSingleBuf(struct pbuf *p); + +void pppLinkTerminated(int pd); + +void pppLinkDown(int pd); + +void pppos_input(int pd, u_char* data, int len); + +/* Configure i/f transmit parameters */ +void ppp_send_config (int, u16_t, u32_t, int, int); +/* Set extended transmit ACCM */ +void ppp_set_xaccm (int, ext_accm *); +/* Configure i/f receive parameters */ +void ppp_recv_config (int, int, u32_t, int, int); +/* Find out how long link has been idle */ +int get_idle_time (int, struct ppp_idle *); + +/* Configure VJ TCP header compression */ +int sifvjcomp (int, int, u8_t, u8_t); +/* Configure i/f down (for IP) */ +int sifup (int); +/* Set mode for handling packets for proto */ +int sifnpmode (int u, int proto, enum NPmode mode); +/* Configure i/f down (for IP) */ +int sifdown (int); +/* Configure IP addresses for i/f */ +int sifaddr (int, u32_t, u32_t, u32_t, u32_t, u32_t); +/* Reset i/f IP addresses */ +int cifaddr (int, u32_t, u32_t); +/* Create default route through i/f */ +int sifdefaultroute (int, u32_t, u32_t); +/* Delete default route through i/f */ +int cifdefaultroute (int, u32_t, u32_t); + +/* Get appropriate netmask for address */ +u32_t GetMask (u32_t); + +#if LWIP_NETIF_STATUS_CALLBACK +void ppp_set_netif_statuscallback(int pd, netif_status_callback_fn status_callback); +#endif /* LWIP_NETIF_STATUS_CALLBACK */ +#if LWIP_NETIF_LINK_CALLBACK +void ppp_set_netif_linkcallback(int pd, netif_status_callback_fn link_callback); +#endif /* LWIP_NETIF_LINK_CALLBACK */ + +#endif /* PPP_SUPPORT */ + +#endif /* PPP_H */ diff --git a/features/unsupported/net/lwip/lwip/netif/ppp/ppp_oe.c b/features/unsupported/net/lwip/lwip/netif/ppp/ppp_oe.c new file mode 100644 index 00000000000..040a0bc93c9 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/netif/ppp/ppp_oe.c @@ -0,0 +1,1132 @@ +/***************************************************************************** +* ppp_oe.c - PPP Over Ethernet implementation for lwIP. +* +* Copyright (c) 2006 by Marc Boucher, Services Informatiques (MBSI) inc. +* +* The authors hereby grant permission to use, copy, modify, distribute, +* and license this software and its documentation for any purpose, provided +* that existing copyright notices are retained in all copies and that this +* notice and the following disclaimer are included verbatim in any +* distributions. No written agreement, license, or royalty fee is required +* for any of the authorized uses. +* +* THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS *AS IS* AND ANY EXPRESS OR +* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +* IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT +* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +****************************************************************************** +* REVISION HISTORY +* +* 06-01-01 Marc Boucher +* Ported to lwIP. +*****************************************************************************/ + + + +/* based on NetBSD: if_pppoe.c,v 1.64 2006/01/31 23:50:15 martin Exp */ + +/*- + * Copyright (c) 2002 The NetBSD Foundation, Inc. + * All rights reserved. + * + * This code is derived from software contributed to The NetBSD Foundation + * by Martin Husemann . + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the NetBSD + * Foundation, Inc. and its contributors. + * 4. Neither the name of The NetBSD Foundation nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS + * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#include "lwip/opt.h" + +#if PPPOE_SUPPORT /* don't build if not configured for use in lwipopts.h */ + +#include "netif/ppp_oe.h" + +#include "ppp.h" +#include "pppdebug.h" + +#include "lwip/timers.h" +#include "lwip/memp.h" + +#include +#include + + +/* Add a 16 bit unsigned value to a buffer pointed to by PTR */ +#define PPPOE_ADD_16(PTR, VAL) \ + *(PTR)++ = (u8_t)((VAL) / 256); \ + *(PTR)++ = (u8_t)((VAL) % 256) + +/* Add a complete PPPoE header to the buffer pointed to by PTR */ +#define PPPOE_ADD_HEADER(PTR, CODE, SESS, LEN) \ + *(PTR)++ = PPPOE_VERTYPE; \ + *(PTR)++ = (CODE); \ + PPPOE_ADD_16(PTR, SESS); \ + PPPOE_ADD_16(PTR, LEN) + +#define PPPOE_DISC_TIMEOUT (5*1000) /* base for quick timeout calculation */ +#define PPPOE_SLOW_RETRY (60*1000) /* persistent retry interval */ +#define PPPOE_DISC_MAXPADI 4 /* retry PADI four times (quickly) */ +#define PPPOE_DISC_MAXPADR 2 /* retry PADR twice */ + +#ifdef PPPOE_SERVER +#error "PPPOE_SERVER is not yet supported under lwIP!" +/* from if_spppsubr.c */ +#define IFF_PASSIVE IFF_LINK0 /* wait passively for connection */ +#endif + +#ifndef PPPOE_ERRORSTRING_LEN +#define PPPOE_ERRORSTRING_LEN 64 +#endif +static char pppoe_error_tmp[PPPOE_ERRORSTRING_LEN]; + + +/* input routines */ +static void pppoe_dispatch_disc_pkt(struct netif *, struct pbuf *); + +/* management routines */ +static int pppoe_do_disconnect(struct pppoe_softc *); +static void pppoe_abort_connect(struct pppoe_softc *); +static void pppoe_clear_softc(struct pppoe_softc *, const char *); + +/* internal timeout handling */ +static void pppoe_timeout(void *); + +/* sending actual protocol controll packets */ +static err_t pppoe_send_padi(struct pppoe_softc *); +static err_t pppoe_send_padr(struct pppoe_softc *); +#ifdef PPPOE_SERVER +static err_t pppoe_send_pado(struct pppoe_softc *); +static err_t pppoe_send_pads(struct pppoe_softc *); +#endif +static err_t pppoe_send_padt(struct netif *, u_int, const u8_t *); + +/* internal helper functions */ +static struct pppoe_softc * pppoe_find_softc_by_session(u_int, struct netif *); +static struct pppoe_softc * pppoe_find_softc_by_hunique(u8_t *, size_t, struct netif *); + +/** linked list of created pppoe interfaces */ +static struct pppoe_softc *pppoe_softc_list; + +err_t +pppoe_create(struct netif *ethif, int pd, void (*linkStatusCB)(int pd, int up), struct pppoe_softc **scptr) +{ + struct pppoe_softc *sc; + + sc = (struct pppoe_softc *)memp_malloc(MEMP_PPPOE_IF); + if (sc == NULL) { + *scptr = NULL; + return ERR_MEM; + } + memset(sc, 0, sizeof(struct pppoe_softc)); + + /* changed to real address later */ + MEMCPY(&sc->sc_dest, ethbroadcast.addr, sizeof(sc->sc_dest)); + + sc->sc_pd = pd; + sc->sc_linkStatusCB = linkStatusCB; + sc->sc_ethif = ethif; + + /* put the new interface at the head of the list */ + sc->next = pppoe_softc_list; + pppoe_softc_list = sc; + + *scptr = sc; + + return ERR_OK; +} + +err_t +pppoe_destroy(struct netif *ifp) +{ + struct pppoe_softc *sc, *prev = NULL; + + for (sc = pppoe_softc_list; sc != NULL; prev = sc, sc = sc->next) { + if (sc->sc_ethif == ifp) { + break; + } + } + + if(!(sc && (sc->sc_ethif == ifp))) { + return ERR_IF; + } + + sys_untimeout(pppoe_timeout, sc); + if (prev == NULL) { + /* remove sc from the head of the list */ + pppoe_softc_list = sc->next; + } else { + /* remove sc from the list */ + prev->next = sc->next; + } + +#ifdef PPPOE_TODO + if (sc->sc_concentrator_name) { + mem_free(sc->sc_concentrator_name); + } + if (sc->sc_service_name) { + mem_free(sc->sc_service_name); + } +#endif /* PPPOE_TODO */ + memp_free(MEMP_PPPOE_IF, sc); + + return ERR_OK; +} + +/* + * Find the interface handling the specified session. + * Note: O(number of sessions open), this is a client-side only, mean + * and lean implementation, so number of open sessions typically should + * be 1. + */ +static struct pppoe_softc * +pppoe_find_softc_by_session(u_int session, struct netif *rcvif) +{ + struct pppoe_softc *sc; + + if (session == 0) { + return NULL; + } + + for (sc = pppoe_softc_list; sc != NULL; sc = sc->next) { + if (sc->sc_state == PPPOE_STATE_SESSION + && sc->sc_session == session) { + if (sc->sc_ethif == rcvif) { + return sc; + } else { + return NULL; + } + } + } + return NULL; +} + +/* Check host unique token passed and return appropriate softc pointer, + * or NULL if token is bogus. */ +static struct pppoe_softc * +pppoe_find_softc_by_hunique(u8_t *token, size_t len, struct netif *rcvif) +{ + struct pppoe_softc *sc, *t; + + if (pppoe_softc_list == NULL) { + return NULL; + } + + if (len != sizeof sc) { + return NULL; + } + MEMCPY(&t, token, len); + + for (sc = pppoe_softc_list; sc != NULL; sc = sc->next) { + if (sc == t) { + break; + } + } + + if (sc == NULL) { + PPPDEBUG(LOG_DEBUG, ("pppoe: alien host unique tag, no session found\n")); + return NULL; + } + + /* should be safe to access *sc now */ + if (sc->sc_state < PPPOE_STATE_PADI_SENT || sc->sc_state >= PPPOE_STATE_SESSION) { + printf("%c%c%"U16_F": host unique tag found, but it belongs to a connection in state %d\n", + sc->sc_ethif->name[0], sc->sc_ethif->name[1], sc->sc_ethif->num, sc->sc_state); + return NULL; + } + if (sc->sc_ethif != rcvif) { + printf("%c%c%"U16_F": wrong interface, not accepting host unique\n", + sc->sc_ethif->name[0], sc->sc_ethif->name[1], sc->sc_ethif->num); + return NULL; + } + return sc; +} + +static void +pppoe_linkstatus_up(struct pppoe_softc *sc) +{ + sc->sc_linkStatusCB(sc->sc_pd, 1); +} + +/* analyze and handle a single received packet while not in session state */ +static void +pppoe_dispatch_disc_pkt(struct netif *netif, struct pbuf *pb) +{ + u16_t tag, len; + u16_t session, plen; + struct pppoe_softc *sc; + const char *err_msg; + char devname[6]; + u8_t *ac_cookie; + u16_t ac_cookie_len; +#ifdef PPPOE_SERVER + u8_t *hunique; + size_t hunique_len; +#endif + struct pppoehdr *ph; + struct pppoetag pt; + int off, err, errortag; + struct eth_hdr *ethhdr; + + pb = pppSingleBuf(pb); + + strcpy(devname, "pppoe"); /* as long as we don't know which instance */ + err_msg = NULL; + errortag = 0; + if (pb->len < sizeof(*ethhdr)) { + goto done; + } + ethhdr = (struct eth_hdr *)pb->payload; + off = sizeof(*ethhdr); + + ac_cookie = NULL; + ac_cookie_len = 0; +#ifdef PPPOE_SERVER + hunique = NULL; + hunique_len = 0; +#endif + session = 0; + if (pb->len - off < PPPOE_HEADERLEN) { + printf("pppoe: packet too short: %d\n", pb->len); + goto done; + } + + ph = (struct pppoehdr *) (ethhdr + 1); + if (ph->vertype != PPPOE_VERTYPE) { + printf("pppoe: unknown version/type packet: 0x%x\n", ph->vertype); + goto done; + } + session = ntohs(ph->session); + plen = ntohs(ph->plen); + off += sizeof(*ph); + + if (plen + off > pb->len) { + printf("pppoe: packet content does not fit: data available = %d, packet size = %u\n", + pb->len - off, plen); + goto done; + } + if(pb->tot_len == pb->len) { + pb->tot_len = pb->len = (u16_t)off + plen; /* ignore trailing garbage */ + } + tag = 0; + len = 0; + sc = NULL; + while (off + sizeof(pt) <= pb->len) { + MEMCPY(&pt, (u8_t*)pb->payload + off, sizeof(pt)); + tag = ntohs(pt.tag); + len = ntohs(pt.len); + if (off + sizeof(pt) + len > pb->len) { + printf("pppoe: tag 0x%x len 0x%x is too long\n", tag, len); + goto done; + } + switch (tag) { + case PPPOE_TAG_EOL: + goto breakbreak; + case PPPOE_TAG_SNAME: + break; /* ignored */ + case PPPOE_TAG_ACNAME: + break; /* ignored */ + case PPPOE_TAG_HUNIQUE: + if (sc != NULL) { + break; + } +#ifdef PPPOE_SERVER + hunique = (u8_t*)pb->payload + off + sizeof(pt); + hunique_len = len; +#endif + sc = pppoe_find_softc_by_hunique((u8_t*)pb->payload + off + sizeof(pt), len, netif); + if (sc != NULL) { + snprintf(devname, sizeof(devname), "%c%c%"U16_F, sc->sc_ethif->name[0], sc->sc_ethif->name[1], sc->sc_ethif->num); + } + break; + case PPPOE_TAG_ACCOOKIE: + if (ac_cookie == NULL) { + ac_cookie = (u8_t*)pb->payload + off + sizeof(pt); + ac_cookie_len = len; + } + break; + case PPPOE_TAG_SNAME_ERR: + err_msg = "SERVICE NAME ERROR"; + errortag = 1; + break; + case PPPOE_TAG_ACSYS_ERR: + err_msg = "AC SYSTEM ERROR"; + errortag = 1; + break; + case PPPOE_TAG_GENERIC_ERR: + err_msg = "GENERIC ERROR"; + errortag = 1; + break; + } + if (err_msg) { + if (errortag && len) { + u16_t error_len = LWIP_MIN(len, sizeof(pppoe_error_tmp)-1); + strncpy(pppoe_error_tmp, (char*)pb->payload + off + sizeof(pt), error_len); + pppoe_error_tmp[error_len-1] = '\0'; + printf("%s: %s: %s\n", devname, err_msg, pppoe_error_tmp); + } else { + printf("%s: %s\n", devname, err_msg); + } + if (errortag) { + goto done; + } + } + off += sizeof(pt) + len; + } + +breakbreak:; + switch (ph->code) { + case PPPOE_CODE_PADI: +#ifdef PPPOE_SERVER + /* + * got service name, concentrator name, and/or host unique. + * ignore if we have no interfaces with IFF_PASSIVE|IFF_UP. + */ + if (LIST_EMPTY(&pppoe_softc_list)) { + goto done; + } + LIST_FOREACH(sc, &pppoe_softc_list, sc_list) { + if (!(sc->sc_sppp.pp_if.if_flags & IFF_UP)) { + continue; + } + if (!(sc->sc_sppp.pp_if.if_flags & IFF_PASSIVE)) { + continue; + } + if (sc->sc_state == PPPOE_STATE_INITIAL) { + break; + } + } + if (sc == NULL) { + /* printf("pppoe: free passive interface is not found\n"); */ + goto done; + } + if (hunique) { + if (sc->sc_hunique) { + mem_free(sc->sc_hunique); + } + sc->sc_hunique = mem_malloc(hunique_len); + if (sc->sc_hunique == NULL) { + goto done; + } + sc->sc_hunique_len = hunique_len; + MEMCPY(sc->sc_hunique, hunique, hunique_len); + } + MEMCPY(&sc->sc_dest, eh->ether_shost, sizeof sc->sc_dest); + sc->sc_state = PPPOE_STATE_PADO_SENT; + pppoe_send_pado(sc); + break; +#endif /* PPPOE_SERVER */ + case PPPOE_CODE_PADR: +#ifdef PPPOE_SERVER + /* + * get sc from ac_cookie if IFF_PASSIVE + */ + if (ac_cookie == NULL) { + /* be quiet if there is not a single pppoe instance */ + printf("pppoe: received PADR but not includes ac_cookie\n"); + goto done; + } + sc = pppoe_find_softc_by_hunique(ac_cookie, ac_cookie_len, netif); + if (sc == NULL) { + /* be quiet if there is not a single pppoe instance */ + if (!LIST_EMPTY(&pppoe_softc_list)) { + printf("pppoe: received PADR but could not find request for it\n"); + } + goto done; + } + if (sc->sc_state != PPPOE_STATE_PADO_SENT) { + printf("%c%c%"U16_F": received unexpected PADR\n", sc->sc_ethif->name[0], sc->sc_ethif->name[1], sc->sc_ethif->num); + goto done; + } + if (hunique) { + if (sc->sc_hunique) { + mem_free(sc->sc_hunique); + } + sc->sc_hunique = mem_malloc(hunique_len); + if (sc->sc_hunique == NULL) { + goto done; + } + sc->sc_hunique_len = hunique_len; + MEMCPY(sc->sc_hunique, hunique, hunique_len); + } + pppoe_send_pads(sc); + sc->sc_state = PPPOE_STATE_SESSION; + pppoe_linkstatus_up(sc); /* notify upper layers */ + break; +#else + /* ignore, we are no access concentrator */ + goto done; +#endif /* PPPOE_SERVER */ + case PPPOE_CODE_PADO: + if (sc == NULL) { + /* be quiet if there is not a single pppoe instance */ + if (pppoe_softc_list != NULL) { + printf("pppoe: received PADO but could not find request for it\n"); + } + goto done; + } + if (sc->sc_state != PPPOE_STATE_PADI_SENT) { + printf("%c%c%"U16_F": received unexpected PADO\n", sc->sc_ethif->name[0], sc->sc_ethif->name[1], sc->sc_ethif->num); + goto done; + } + if (ac_cookie) { + sc->sc_ac_cookie_len = ac_cookie_len; + MEMCPY(sc->sc_ac_cookie, ac_cookie, ac_cookie_len); + } + MEMCPY(&sc->sc_dest, ethhdr->src.addr, sizeof(sc->sc_dest.addr)); + sys_untimeout(pppoe_timeout, sc); + sc->sc_padr_retried = 0; + sc->sc_state = PPPOE_STATE_PADR_SENT; + if ((err = pppoe_send_padr(sc)) != 0) { + PPPDEBUG(LOG_DEBUG, ("pppoe: %c%c%"U16_F": failed to send PADR, error=%d\n", sc->sc_ethif->name[0], sc->sc_ethif->name[1], sc->sc_ethif->num, err)); + } + sys_timeout(PPPOE_DISC_TIMEOUT * (1 + sc->sc_padr_retried), pppoe_timeout, sc); + break; + case PPPOE_CODE_PADS: + if (sc == NULL) { + goto done; + } + sc->sc_session = session; + sys_untimeout(pppoe_timeout, sc); + PPPDEBUG(LOG_DEBUG, ("pppoe: %c%c%"U16_F": session 0x%x connected\n", sc->sc_ethif->name[0], sc->sc_ethif->name[1], sc->sc_ethif->num, session)); + sc->sc_state = PPPOE_STATE_SESSION; + pppoe_linkstatus_up(sc); /* notify upper layers */ + break; + case PPPOE_CODE_PADT: + if (sc == NULL) { + goto done; + } + pppoe_clear_softc(sc, "received PADT"); + break; + default: + if(sc) { + printf("%c%c%"U16_F": unknown code (0x%"X16_F") session = 0x%"X16_F"\n", + sc->sc_ethif->name[0], sc->sc_ethif->name[1], sc->sc_ethif->num, + (u16_t)ph->code, session); + } else { + printf("pppoe: unknown code (0x%"X16_F") session = 0x%"X16_F"\n", (u16_t)ph->code, session); + } + break; + } + +done: + pbuf_free(pb); + return; +} + +void +pppoe_disc_input(struct netif *netif, struct pbuf *p) +{ + /* avoid error messages if there is not a single pppoe instance */ + if (pppoe_softc_list != NULL) { + pppoe_dispatch_disc_pkt(netif, p); + } else { + pbuf_free(p); + } +} + +void +pppoe_data_input(struct netif *netif, struct pbuf *pb) +{ + u16_t session, plen; + struct pppoe_softc *sc; + struct pppoehdr *ph; +#ifdef PPPOE_TERM_UNKNOWN_SESSIONS + u8_t shost[ETHER_ADDR_LEN]; +#endif + +#ifdef PPPOE_TERM_UNKNOWN_SESSIONS + MEMCPY(shost, ((struct eth_hdr *)pb->payload)->src.addr, sizeof(shost)); +#endif + if (pbuf_header(pb, -(int)sizeof(struct eth_hdr)) != 0) { + /* bail out */ + PPPDEBUG(LOG_ERR, ("pppoe_data_input: pbuf_header failed\n")); + LINK_STATS_INC(link.lenerr); + goto drop; + } + + pb = pppSingleBuf (pb); + + if (pb->len <= PPPOE_HEADERLEN) { + printf("pppoe (data): dropping too short packet: %d bytes\n", pb->len); + goto drop; + } + + if (pb->len < sizeof(*ph)) { + printf("pppoe_data_input: could not get PPPoE header\n"); + goto drop; + } + ph = (struct pppoehdr *)pb->payload; + + if (ph->vertype != PPPOE_VERTYPE) { + printf("pppoe (data): unknown version/type packet: 0x%x\n", ph->vertype); + goto drop; + } + if (ph->code != 0) { + goto drop; + } + + session = ntohs(ph->session); + sc = pppoe_find_softc_by_session(session, netif); + if (sc == NULL) { +#ifdef PPPOE_TERM_UNKNOWN_SESSIONS + printf("pppoe: input for unknown session 0x%x, sending PADT\n", session); + pppoe_send_padt(netif, session, shost); +#endif + goto drop; + } + + plen = ntohs(ph->plen); + + if (pbuf_header(pb, -(int)(PPPOE_HEADERLEN)) != 0) { + /* bail out */ + PPPDEBUG(LOG_ERR, ("pppoe_data_input: pbuf_header PPPOE_HEADERLEN failed\n")); + LINK_STATS_INC(link.lenerr); + goto drop; + } + + PPPDEBUG(LOG_DEBUG, ("pppoe_data_input: %c%c%"U16_F": pkthdr.len=%d, pppoe.len=%d\n", + sc->sc_ethif->name[0], sc->sc_ethif->name[1], sc->sc_ethif->num, + pb->len, plen)); + + if (pb->len < plen) { + goto drop; + } + + pppInProcOverEthernet(sc->sc_pd, pb); + + return; + +drop: + pbuf_free(pb); +} + +static err_t +pppoe_output(struct pppoe_softc *sc, struct pbuf *pb) +{ + struct eth_hdr *ethhdr; + u16_t etype; + err_t res; + + if (!sc->sc_ethif) { + pbuf_free(pb); + return ERR_IF; + } + + ethhdr = (struct eth_hdr *)pb->payload; + etype = sc->sc_state == PPPOE_STATE_SESSION ? ETHTYPE_PPPOE : ETHTYPE_PPPOEDISC; + ethhdr->type = htons(etype); + MEMCPY(ethhdr->dest.addr, sc->sc_dest.addr, sizeof(ethhdr->dest.addr)); + MEMCPY(ethhdr->src.addr, ((struct eth_addr *)sc->sc_ethif->hwaddr)->addr, sizeof(ethhdr->src.addr)); + + PPPDEBUG(LOG_DEBUG, ("pppoe: %c%c%"U16_F" (%x) state=%d, session=0x%x output -> %02"X16_F":%02"X16_F":%02"X16_F":%02"X16_F":%02"X16_F":%02"X16_F", len=%d\n", + sc->sc_ethif->name[0], sc->sc_ethif->name[1], sc->sc_ethif->num, etype, + sc->sc_state, sc->sc_session, + sc->sc_dest.addr[0], sc->sc_dest.addr[1], sc->sc_dest.addr[2], sc->sc_dest.addr[3], sc->sc_dest.addr[4], sc->sc_dest.addr[5], + pb->tot_len)); + + res = sc->sc_ethif->linkoutput(sc->sc_ethif, pb); + + pbuf_free(pb); + + return res; +} + +static err_t +pppoe_send_padi(struct pppoe_softc *sc) +{ + struct pbuf *pb; + u8_t *p; + int len; +#ifdef PPPOE_TODO + int l1 = 0, l2 = 0; /* XXX: gcc */ +#endif /* PPPOE_TODO */ + + if (sc->sc_state >PPPOE_STATE_PADI_SENT) { + PPPDEBUG(LOG_ERR, ("ERROR: pppoe_send_padi in state %d", sc->sc_state)); + } + + /* calculate length of frame (excluding ethernet header + pppoe header) */ + len = 2 + 2 + 2 + 2 + sizeof sc; /* service name tag is required, host unique is send too */ +#ifdef PPPOE_TODO + if (sc->sc_service_name != NULL) { + l1 = (int)strlen(sc->sc_service_name); + len += l1; + } + if (sc->sc_concentrator_name != NULL) { + l2 = (int)strlen(sc->sc_concentrator_name); + len += 2 + 2 + l2; + } +#endif /* PPPOE_TODO */ + LWIP_ASSERT("sizeof(struct eth_hdr) + PPPOE_HEADERLEN + len <= 0xffff", + sizeof(struct eth_hdr) + PPPOE_HEADERLEN + len <= 0xffff); + + /* allocate a buffer */ + pb = pbuf_alloc(PBUF_LINK, (u16_t)(sizeof(struct eth_hdr) + PPPOE_HEADERLEN + len), PBUF_RAM); + if (!pb) { + return ERR_MEM; + } + LWIP_ASSERT("pb->tot_len == pb->len", pb->tot_len == pb->len); + + p = (u8_t*)pb->payload + sizeof (struct eth_hdr); + /* fill in pkt */ + PPPOE_ADD_HEADER(p, PPPOE_CODE_PADI, 0, (u16_t)len); + PPPOE_ADD_16(p, PPPOE_TAG_SNAME); +#ifdef PPPOE_TODO + if (sc->sc_service_name != NULL) { + PPPOE_ADD_16(p, l1); + MEMCPY(p, sc->sc_service_name, l1); + p += l1; + } else +#endif /* PPPOE_TODO */ + { + PPPOE_ADD_16(p, 0); + } +#ifdef PPPOE_TODO + if (sc->sc_concentrator_name != NULL) { + PPPOE_ADD_16(p, PPPOE_TAG_ACNAME); + PPPOE_ADD_16(p, l2); + MEMCPY(p, sc->sc_concentrator_name, l2); + p += l2; + } +#endif /* PPPOE_TODO */ + PPPOE_ADD_16(p, PPPOE_TAG_HUNIQUE); + PPPOE_ADD_16(p, sizeof(sc)); + MEMCPY(p, &sc, sizeof sc); + + /* send pkt */ + return pppoe_output(sc, pb); +} + +static void +pppoe_timeout(void *arg) +{ + int retry_wait, err; + struct pppoe_softc *sc = (struct pppoe_softc*)arg; + + PPPDEBUG(LOG_DEBUG, ("pppoe: %c%c%"U16_F": timeout\n", sc->sc_ethif->name[0], sc->sc_ethif->name[1], sc->sc_ethif->num)); + + switch (sc->sc_state) { + case PPPOE_STATE_PADI_SENT: + /* + * We have two basic ways of retrying: + * - Quick retry mode: try a few times in short sequence + * - Slow retry mode: we already had a connection successfully + * established and will try infinitely (without user + * intervention) + * We only enter slow retry mode if IFF_LINK1 (aka autodial) + * is not set. + */ + + /* initialize for quick retry mode */ + retry_wait = PPPOE_DISC_TIMEOUT * (1 + sc->sc_padi_retried); + + sc->sc_padi_retried++; + if (sc->sc_padi_retried >= PPPOE_DISC_MAXPADI) { +#if 0 + if ((sc->sc_sppp.pp_if.if_flags & IFF_LINK1) == 0) { + /* slow retry mode */ + retry_wait = PPPOE_SLOW_RETRY; + } else +#endif + { + pppoe_abort_connect(sc); + return; + } + } + if ((err = pppoe_send_padi(sc)) != 0) { + sc->sc_padi_retried--; + PPPDEBUG(LOG_DEBUG, ("pppoe: %c%c%"U16_F": failed to transmit PADI, error=%d\n", sc->sc_ethif->name[0], sc->sc_ethif->name[1], sc->sc_ethif->num, err)); + } + sys_timeout(retry_wait, pppoe_timeout, sc); + break; + + case PPPOE_STATE_PADR_SENT: + sc->sc_padr_retried++; + if (sc->sc_padr_retried >= PPPOE_DISC_MAXPADR) { + MEMCPY(&sc->sc_dest, ethbroadcast.addr, sizeof(sc->sc_dest)); + sc->sc_state = PPPOE_STATE_PADI_SENT; + sc->sc_padr_retried = 0; + if ((err = pppoe_send_padi(sc)) != 0) { + PPPDEBUG(LOG_DEBUG, ("pppoe: %c%c%"U16_F": failed to send PADI, error=%d\n", sc->sc_ethif->name[0], sc->sc_ethif->name[1], sc->sc_ethif->num, err)); + } + sys_timeout(PPPOE_DISC_TIMEOUT * (1 + sc->sc_padi_retried), pppoe_timeout, sc); + return; + } + if ((err = pppoe_send_padr(sc)) != 0) { + sc->sc_padr_retried--; + PPPDEBUG(LOG_DEBUG, ("pppoe: %c%c%"U16_F": failed to send PADR, error=%d\n", sc->sc_ethif->name[0], sc->sc_ethif->name[1], sc->sc_ethif->num, err)); + } + sys_timeout(PPPOE_DISC_TIMEOUT * (1 + sc->sc_padr_retried), pppoe_timeout, sc); + break; + case PPPOE_STATE_CLOSING: + pppoe_do_disconnect(sc); + break; + default: + return; /* all done, work in peace */ + } +} + +/* Start a connection (i.e. initiate discovery phase) */ +int +pppoe_connect(struct pppoe_softc *sc) +{ + int err; + + if (sc->sc_state != PPPOE_STATE_INITIAL) { + return EBUSY; + } + +#ifdef PPPOE_SERVER + /* wait PADI if IFF_PASSIVE */ + if ((sc->sc_sppp.pp_if.if_flags & IFF_PASSIVE)) { + return 0; + } +#endif + /* save state, in case we fail to send PADI */ + sc->sc_state = PPPOE_STATE_PADI_SENT; + sc->sc_padr_retried = 0; + err = pppoe_send_padi(sc); + PPPDEBUG(LOG_DEBUG, ("pppoe: %c%c%"U16_F": failed to send PADI, error=%d\n", sc->sc_ethif->name[0], sc->sc_ethif->name[1], sc->sc_ethif->num, err)); + sys_timeout(PPPOE_DISC_TIMEOUT, pppoe_timeout, sc); + return err; +} + +/* disconnect */ +void +pppoe_disconnect(struct pppoe_softc *sc) +{ + if (sc->sc_state < PPPOE_STATE_SESSION) { + return; + } + /* + * Do not call pppoe_disconnect here, the upper layer state + * machine gets confused by this. We must return from this + * function and defer disconnecting to the timeout handler. + */ + sc->sc_state = PPPOE_STATE_CLOSING; + sys_timeout(20, pppoe_timeout, sc); +} + +static int +pppoe_do_disconnect(struct pppoe_softc *sc) +{ + int err; + + if (sc->sc_state < PPPOE_STATE_SESSION) { + err = EBUSY; + } else { + PPPDEBUG(LOG_DEBUG, ("pppoe: %c%c%"U16_F": disconnecting\n", sc->sc_ethif->name[0], sc->sc_ethif->name[1], sc->sc_ethif->num)); + err = pppoe_send_padt(sc->sc_ethif, sc->sc_session, (const u8_t *)&sc->sc_dest); + } + + /* cleanup softc */ + sc->sc_state = PPPOE_STATE_INITIAL; + MEMCPY(&sc->sc_dest, ethbroadcast.addr, sizeof(sc->sc_dest)); + sc->sc_ac_cookie_len = 0; +#ifdef PPPOE_SERVER + if (sc->sc_hunique) { + mem_free(sc->sc_hunique); + sc->sc_hunique = NULL; + } + sc->sc_hunique_len = 0; +#endif + sc->sc_session = 0; + + sc->sc_linkStatusCB(sc->sc_pd, 0); /* notify upper layers */ + + return err; +} + +/* Connection attempt aborted */ +static void +pppoe_abort_connect(struct pppoe_softc *sc) +{ + printf("%c%c%"U16_F": could not establish connection\n", sc->sc_ethif->name[0], sc->sc_ethif->name[1], sc->sc_ethif->num); + sc->sc_state = PPPOE_STATE_CLOSING; + + sc->sc_linkStatusCB(sc->sc_pd, 0); /* notify upper layers */ + + /* clear connection state */ + MEMCPY(&sc->sc_dest, ethbroadcast.addr, sizeof(sc->sc_dest)); + sc->sc_state = PPPOE_STATE_INITIAL; +} + +/* Send a PADR packet */ +static err_t +pppoe_send_padr(struct pppoe_softc *sc) +{ + struct pbuf *pb; + u8_t *p; + size_t len; +#ifdef PPPOE_TODO + size_t l1 = 0; /* XXX: gcc */ +#endif /* PPPOE_TODO */ + + if (sc->sc_state != PPPOE_STATE_PADR_SENT) { + return ERR_CONN; + } + + len = 2 + 2 + 2 + 2 + sizeof(sc); /* service name, host unique */ +#ifdef PPPOE_TODO + if (sc->sc_service_name != NULL) { /* service name tag maybe empty */ + l1 = strlen(sc->sc_service_name); + len += l1; + } +#endif /* PPPOE_TODO */ + if (sc->sc_ac_cookie_len > 0) { + len += 2 + 2 + sc->sc_ac_cookie_len; /* AC cookie */ + } + LWIP_ASSERT("sizeof(struct eth_hdr) + PPPOE_HEADERLEN + len <= 0xffff", + sizeof(struct eth_hdr) + PPPOE_HEADERLEN + len <= 0xffff); + pb = pbuf_alloc(PBUF_LINK, (u16_t)(sizeof(struct eth_hdr) + PPPOE_HEADERLEN + len), PBUF_RAM); + if (!pb) { + return ERR_MEM; + } + LWIP_ASSERT("pb->tot_len == pb->len", pb->tot_len == pb->len); + p = (u8_t*)pb->payload + sizeof (struct eth_hdr); + PPPOE_ADD_HEADER(p, PPPOE_CODE_PADR, 0, len); + PPPOE_ADD_16(p, PPPOE_TAG_SNAME); +#ifdef PPPOE_TODO + if (sc->sc_service_name != NULL) { + PPPOE_ADD_16(p, l1); + MEMCPY(p, sc->sc_service_name, l1); + p += l1; + } else +#endif /* PPPOE_TODO */ + { + PPPOE_ADD_16(p, 0); + } + if (sc->sc_ac_cookie_len > 0) { + PPPOE_ADD_16(p, PPPOE_TAG_ACCOOKIE); + PPPOE_ADD_16(p, sc->sc_ac_cookie_len); + MEMCPY(p, sc->sc_ac_cookie, sc->sc_ac_cookie_len); + p += sc->sc_ac_cookie_len; + } + PPPOE_ADD_16(p, PPPOE_TAG_HUNIQUE); + PPPOE_ADD_16(p, sizeof(sc)); + MEMCPY(p, &sc, sizeof sc); + + return pppoe_output(sc, pb); +} + +/* send a PADT packet */ +static err_t +pppoe_send_padt(struct netif *outgoing_if, u_int session, const u8_t *dest) +{ + struct pbuf *pb; + struct eth_hdr *ethhdr; + err_t res; + u8_t *p; + + pb = pbuf_alloc(PBUF_LINK, sizeof(struct eth_hdr) + PPPOE_HEADERLEN, PBUF_RAM); + if (!pb) { + return ERR_MEM; + } + LWIP_ASSERT("pb->tot_len == pb->len", pb->tot_len == pb->len); + + ethhdr = (struct eth_hdr *)pb->payload; + ethhdr->type = PP_HTONS(ETHTYPE_PPPOEDISC); + MEMCPY(ethhdr->dest.addr, dest, sizeof(ethhdr->dest.addr)); + MEMCPY(ethhdr->src.addr, ((struct eth_addr *)outgoing_if->hwaddr)->addr, sizeof(ethhdr->src.addr)); + + p = (u8_t*)(ethhdr + 1); + PPPOE_ADD_HEADER(p, PPPOE_CODE_PADT, session, 0); + + res = outgoing_if->linkoutput(outgoing_if, pb); + + pbuf_free(pb); + + return res; +} + +#ifdef PPPOE_SERVER +static err_t +pppoe_send_pado(struct pppoe_softc *sc) +{ + struct pbuf *pb; + u8_t *p; + size_t len; + + if (sc->sc_state != PPPOE_STATE_PADO_SENT) { + return ERR_CONN; + } + + /* calc length */ + len = 0; + /* include ac_cookie */ + len += 2 + 2 + sizeof(sc); + /* include hunique */ + len += 2 + 2 + sc->sc_hunique_len; + pb = pbuf_alloc(PBUF_LINK, sizeof(struct eth_hdr) + PPPOE_HEADERLEN + len, PBUF_RAM); + if (!pb) { + return ERR_MEM; + } + LWIP_ASSERT("pb->tot_len == pb->len", pb->tot_len == pb->len); + p = (u8_t*)pb->payload + sizeof (struct eth_hdr); + PPPOE_ADD_HEADER(p, PPPOE_CODE_PADO, 0, len); + PPPOE_ADD_16(p, PPPOE_TAG_ACCOOKIE); + PPPOE_ADD_16(p, sizeof(sc)); + MEMCPY(p, &sc, sizeof(sc)); + p += sizeof(sc); + PPPOE_ADD_16(p, PPPOE_TAG_HUNIQUE); + PPPOE_ADD_16(p, sc->sc_hunique_len); + MEMCPY(p, sc->sc_hunique, sc->sc_hunique_len); + return pppoe_output(sc, pb); +} + +static err_t +pppoe_send_pads(struct pppoe_softc *sc) +{ + struct pbuf *pb; + u8_t *p; + size_t len, l1 = 0; /* XXX: gcc */ + + if (sc->sc_state != PPPOE_STATE_PADO_SENT) { + return ERR_CONN; + } + + sc->sc_session = mono_time.tv_sec % 0xff + 1; + /* calc length */ + len = 0; + /* include hunique */ + len += 2 + 2 + 2 + 2 + sc->sc_hunique_len; /* service name, host unique*/ + if (sc->sc_service_name != NULL) { /* service name tag maybe empty */ + l1 = strlen(sc->sc_service_name); + len += l1; + } + pb = pbuf_alloc(PBUF_LINK, sizeof(struct eth_hdr) + PPPOE_HEADERLEN + len, PBUF_RAM); + if (!pb) { + return ERR_MEM; + } + LWIP_ASSERT("pb->tot_len == pb->len", pb->tot_len == pb->len); + p = (u8_t*)pb->payload + sizeof (struct eth_hdr); + PPPOE_ADD_HEADER(p, PPPOE_CODE_PADS, sc->sc_session, len); + PPPOE_ADD_16(p, PPPOE_TAG_SNAME); + if (sc->sc_service_name != NULL) { + PPPOE_ADD_16(p, l1); + MEMCPY(p, sc->sc_service_name, l1); + p += l1; + } else { + PPPOE_ADD_16(p, 0); + } + PPPOE_ADD_16(p, PPPOE_TAG_HUNIQUE); + PPPOE_ADD_16(p, sc->sc_hunique_len); + MEMCPY(p, sc->sc_hunique, sc->sc_hunique_len); + return pppoe_output(sc, pb); +} +#endif + +err_t +pppoe_xmit(struct pppoe_softc *sc, struct pbuf *pb) +{ + u8_t *p; + size_t len; + + /* are we ready to process data yet? */ + if (sc->sc_state < PPPOE_STATE_SESSION) { + /*sppp_flush(&sc->sc_sppp.pp_if);*/ + pbuf_free(pb); + return ERR_CONN; + } + + len = pb->tot_len; + + /* make room for Ethernet header - should not fail */ + if (pbuf_header(pb, sizeof(struct eth_hdr) + PPPOE_HEADERLEN) != 0) { + /* bail out */ + PPPDEBUG(LOG_ERR, ("pppoe: %c%c%"U16_F": pppoe_xmit: could not allocate room for header\n", sc->sc_ethif->name[0], sc->sc_ethif->name[1], sc->sc_ethif->num)); + LINK_STATS_INC(link.lenerr); + pbuf_free(pb); + return ERR_BUF; + } + + p = (u8_t*)pb->payload + sizeof(struct eth_hdr); + PPPOE_ADD_HEADER(p, 0, sc->sc_session, len); + + return pppoe_output(sc, pb); +} + +#if 0 /*def PFIL_HOOKS*/ +static int +pppoe_ifattach_hook(void *arg, struct pbuf **mp, struct netif *ifp, int dir) +{ + struct pppoe_softc *sc; + int s; + + if (mp != (struct pbuf **)PFIL_IFNET_DETACH) { + return 0; + } + + LIST_FOREACH(sc, &pppoe_softc_list, sc_list) { + if (sc->sc_ethif != ifp) { + continue; + } + if (sc->sc_sppp.pp_if.if_flags & IFF_UP) { + sc->sc_sppp.pp_if.if_flags &= ~(IFF_UP|IFF_RUNNING); + printf("%c%c%"U16_F": ethernet interface detached, going down\n", + sc->sc_ethif->name[0], sc->sc_ethif->name[1], sc->sc_ethif->num); + } + sc->sc_ethif = NULL; + pppoe_clear_softc(sc, "ethernet interface detached"); + } + + return 0; +} +#endif + +static void +pppoe_clear_softc(struct pppoe_softc *sc, const char *message) +{ + LWIP_UNUSED_ARG(message); + + /* stop timer */ + sys_untimeout(pppoe_timeout, sc); + PPPDEBUG(LOG_DEBUG, ("pppoe: %c%c%"U16_F": session 0x%x terminated, %s\n", sc->sc_ethif->name[0], sc->sc_ethif->name[1], sc->sc_ethif->num, sc->sc_session, message)); + + /* fix our state */ + sc->sc_state = PPPOE_STATE_INITIAL; + + /* notify upper layers */ + sc->sc_linkStatusCB(sc->sc_pd, 0); + + /* clean up softc */ + MEMCPY(&sc->sc_dest, ethbroadcast.addr, sizeof(sc->sc_dest)); + sc->sc_ac_cookie_len = 0; + sc->sc_session = 0; +} + +#endif /* PPPOE_SUPPORT */ + diff --git a/features/unsupported/net/lwip/lwip/netif/ppp/pppdebug.h b/features/unsupported/net/lwip/lwip/netif/ppp/pppdebug.h new file mode 100644 index 00000000000..81349971db6 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/netif/ppp/pppdebug.h @@ -0,0 +1,73 @@ +/***************************************************************************** +* pppdebug.h - System debugging utilities. +* +* Copyright (c) 2003 by Marc Boucher, Services Informatiques (MBSI) inc. +* portions Copyright (c) 1998 Global Election Systems Inc. +* portions Copyright (c) 2001 by Cognizant Pty Ltd. +* +* The authors hereby grant permission to use, copy, modify, distribute, +* and license this software and its documentation for any purpose, provided +* that existing copyright notices are retained in all copies and that this +* notice and the following disclaimer are included verbatim in any +* distributions. No written agreement, license, or royalty fee is required +* for any of the authorized uses. +* +* THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS *AS IS* AND ANY EXPRESS OR +* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +* IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT +* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +****************************************************************************** +* REVISION HISTORY (please don't use tabs!) +* +* 03-01-01 Marc Boucher +* Ported to lwIP. +* 98-07-29 Guy Lancaster , Global Election Systems Inc. +* Original. +* +***************************************************************************** +*/ +#ifndef PPPDEBUG_H +#define PPPDEBUG_H + +/* Trace levels. */ +#define LOG_CRITICAL (PPP_DEBUG | LWIP_DBG_LEVEL_SEVERE) +#define LOG_ERR (PPP_DEBUG | LWIP_DBG_LEVEL_SEVERE) +#define LOG_NOTICE (PPP_DEBUG | LWIP_DBG_LEVEL_WARNING) +#define LOG_WARNING (PPP_DEBUG | LWIP_DBG_LEVEL_WARNING) +#define LOG_INFO (PPP_DEBUG) +#define LOG_DETAIL (PPP_DEBUG) +#define LOG_DEBUG (PPP_DEBUG) + + +#define TRACELCP PPP_DEBUG + +#if PPP_DEBUG + +#define AUTHDEBUG(a, b) LWIP_DEBUGF(a, b) +#define IPCPDEBUG(a, b) LWIP_DEBUGF(a, b) +#define UPAPDEBUG(a, b) LWIP_DEBUGF(a, b) +#define LCPDEBUG(a, b) LWIP_DEBUGF(a, b) +#define FSMDEBUG(a, b) LWIP_DEBUGF(a, b) +#define CHAPDEBUG(a, b) LWIP_DEBUGF(a, b) +#define PPPDEBUG(a, b) LWIP_DEBUGF(a, b) + +#else /* PPP_DEBUG */ + +#define AUTHDEBUG(a, b) +#define IPCPDEBUG(a, b) +#define UPAPDEBUG(a, b) +#define LCPDEBUG(a, b) +#define FSMDEBUG(a, b) +#define CHAPDEBUG(a, b) +#define PPPDEBUG(a, b) + +#endif /* PPP_DEBUG */ + +#endif /* PPPDEBUG_H */ diff --git a/features/unsupported/net/lwip/lwip/netif/ppp/randm.c b/features/unsupported/net/lwip/lwip/netif/ppp/randm.c new file mode 100644 index 00000000000..2f35caf6a00 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/netif/ppp/randm.c @@ -0,0 +1,249 @@ +/***************************************************************************** +* randm.c - Random number generator program file. +* +* Copyright (c) 2003 by Marc Boucher, Services Informatiques (MBSI) inc. +* Copyright (c) 1998 by Global Election Systems Inc. +* +* The authors hereby grant permission to use, copy, modify, distribute, +* and license this software and its documentation for any purpose, provided +* that existing copyright notices are retained in all copies and that this +* notice and the following disclaimer are included verbatim in any +* distributions. No written agreement, license, or royalty fee is required +* for any of the authorized uses. +* +* THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS *AS IS* AND ANY EXPRESS OR +* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +* IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT +* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +****************************************************************************** +* REVISION HISTORY +* +* 03-01-01 Marc Boucher +* Ported to lwIP. +* 98-06-03 Guy Lancaster , Global Election Systems Inc. +* Extracted from avos. +*****************************************************************************/ + +#include "lwip/opt.h" + +#if PPP_SUPPORT /* don't build if not configured for use in lwipopts.h */ + +#include "md5.h" +#include "randm.h" + +#include "ppp.h" +#include "pppdebug.h" + +#include + +#if MD5_SUPPORT /* this module depends on MD5 */ +#define RANDPOOLSZ 16 /* Bytes stored in the pool of randomness. */ + +/*****************************/ +/*** LOCAL DATA STRUCTURES ***/ +/*****************************/ +static char randPool[RANDPOOLSZ]; /* Pool of randomness. */ +static long randCount = 0; /* Pseudo-random incrementer */ + + +/***********************************/ +/*** PUBLIC FUNCTION DEFINITIONS ***/ +/***********************************/ +/* + * Initialize the random number generator. + * + * Since this is to be called on power up, we don't have much + * system randomess to work with. Here all we use is the + * real-time clock. We'll accumulate more randomness as soon + * as things start happening. + */ +void +avRandomInit() +{ + avChurnRand(NULL, 0); +} + +/* + * Churn the randomness pool on a random event. Call this early and often + * on random and semi-random system events to build randomness in time for + * usage. For randomly timed events, pass a null pointer and a zero length + * and this will use the system timer and other sources to add randomness. + * If new random data is available, pass a pointer to that and it will be + * included. + * + * Ref: Applied Cryptography 2nd Ed. by Bruce Schneier p. 427 + */ +void +avChurnRand(char *randData, u32_t randLen) +{ + MD5_CTX md5; + + /* LWIP_DEBUGF(LOG_INFO, ("churnRand: %u@%P\n", randLen, randData)); */ + MD5Init(&md5); + MD5Update(&md5, (u_char *)randPool, sizeof(randPool)); + if (randData) { + MD5Update(&md5, (u_char *)randData, randLen); + } else { + struct { + /* INCLUDE fields for any system sources of randomness */ + char foobar; + } sysData; + + /* Load sysData fields here. */ + MD5Update(&md5, (u_char *)&sysData, sizeof(sysData)); + } + MD5Final((u_char *)randPool, &md5); +/* LWIP_DEBUGF(LOG_INFO, ("churnRand: -> 0\n")); */ +} + +/* + * Use the random pool to generate random data. This degrades to pseudo + * random when used faster than randomness is supplied using churnRand(). + * Note: It's important that there be sufficient randomness in randPool + * before this is called for otherwise the range of the result may be + * narrow enough to make a search feasible. + * + * Ref: Applied Cryptography 2nd Ed. by Bruce Schneier p. 427 + * + * XXX Why does he not just call churnRand() for each block? Probably + * so that you don't ever publish the seed which could possibly help + * predict future values. + * XXX Why don't we preserve md5 between blocks and just update it with + * randCount each time? Probably there is a weakness but I wish that + * it was documented. + */ +void +avGenRand(char *buf, u32_t bufLen) +{ + MD5_CTX md5; + u_char tmp[16]; + u32_t n; + + while (bufLen > 0) { + n = LWIP_MIN(bufLen, RANDPOOLSZ); + MD5Init(&md5); + MD5Update(&md5, (u_char *)randPool, sizeof(randPool)); + MD5Update(&md5, (u_char *)&randCount, sizeof(randCount)); + MD5Final(tmp, &md5); + randCount++; + MEMCPY(buf, tmp, n); + buf += n; + bufLen -= n; + } +} + +/* + * Return a new random number. + */ +u32_t +avRandom() +{ + u32_t newRand; + + avGenRand((char *)&newRand, sizeof(newRand)); + + return newRand; +} + +#else /* MD5_SUPPORT */ + +/*****************************/ +/*** LOCAL DATA STRUCTURES ***/ +/*****************************/ +static int avRandomized = 0; /* Set when truely randomized. */ +static u32_t avRandomSeed = 0; /* Seed used for random number generation. */ + + +/***********************************/ +/*** PUBLIC FUNCTION DEFINITIONS ***/ +/***********************************/ +/* + * Initialize the random number generator. + * + * Here we attempt to compute a random number seed but even if + * it isn't random, we'll randomize it later. + * + * The current method uses the fields from the real time clock, + * the idle process counter, the millisecond counter, and the + * hardware timer tick counter. When this is invoked + * in startup(), then the idle counter and timer values may + * repeat after each boot and the real time clock may not be + * operational. Thus we call it again on the first random + * event. + */ +void +avRandomInit() +{ +#if 0 + /* Get a pointer into the last 4 bytes of clockBuf. */ + u32_t *lptr1 = (u32_t *)((char *)&clockBuf[3]); + + /* + * Initialize our seed using the real-time clock, the idle + * counter, the millisecond timer, and the hardware timer + * tick counter. The real-time clock and the hardware + * tick counter are the best sources of randomness but + * since the tick counter is only 16 bit (and truncated + * at that), the idle counter and millisecond timer + * (which may be small values) are added to help + * randomize the lower 16 bits of the seed. + */ + readClk(); + avRandomSeed += *(u32_t *)clockBuf + *lptr1 + OSIdleCtr + + ppp_mtime() + ((u32_t)TM1 << 16) + TM1; +#else + avRandomSeed += sys_jiffies(); /* XXX */ +#endif + + /* Initialize the Borland random number generator. */ + srand((unsigned)avRandomSeed); +} + +/* + * Randomize our random seed value. Here we use the fact that + * this function is called at *truely random* times by the polling + * and network functions. Here we only get 16 bits of new random + * value but we use the previous value to randomize the other 16 + * bits. + */ +void +avRandomize(void) +{ + static u32_t last_jiffies; + + if (!avRandomized) { + avRandomized = !0; + avRandomInit(); + /* The initialization function also updates the seed. */ + } else { + /* avRandomSeed += (avRandomSeed << 16) + TM1; */ + avRandomSeed += (sys_jiffies() - last_jiffies); /* XXX */ + } + last_jiffies = sys_jiffies(); +} + +/* + * Return a new random number. + * Here we use the Borland rand() function to supply a pseudo random + * number which we make truely random by combining it with our own + * seed which is randomized by truely random events. + * Thus the numbers will be truely random unless there have been no + * operator or network events in which case it will be pseudo random + * seeded by the real time clock. + */ +u32_t +avRandom() +{ + return ((((u32_t)rand() << 16) + rand()) + avRandomSeed); +} + +#endif /* MD5_SUPPORT */ + +#endif /* PPP_SUPPORT */ diff --git a/features/unsupported/net/lwip/lwip/netif/ppp/randm.h b/features/unsupported/net/lwip/lwip/netif/ppp/randm.h new file mode 100644 index 00000000000..a0984b0202e --- /dev/null +++ b/features/unsupported/net/lwip/lwip/netif/ppp/randm.h @@ -0,0 +1,81 @@ +/***************************************************************************** +* randm.h - Random number generator header file. +* +* Copyright (c) 2003 by Marc Boucher, Services Informatiques (MBSI) inc. +* Copyright (c) 1998 Global Election Systems Inc. +* +* The authors hereby grant permission to use, copy, modify, distribute, +* and license this software and its documentation for any purpose, provided +* that existing copyright notices are retained in all copies and that this +* notice and the following disclaimer are included verbatim in any +* distributions. No written agreement, license, or royalty fee is required +* for any of the authorized uses. +* +* THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS *AS IS* AND ANY EXPRESS OR +* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +* IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT +* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +****************************************************************************** +* REVISION HISTORY +* +* 03-01-01 Marc Boucher +* Ported to lwIP. +* 98-05-29 Guy Lancaster , Global Election Systems Inc. +* Extracted from avos. +*****************************************************************************/ + +#ifndef RANDM_H +#define RANDM_H + +/*********************** +*** PUBLIC FUNCTIONS *** +***********************/ +/* + * Initialize the random number generator. + */ +void avRandomInit(void); + +/* + * Churn the randomness pool on a random event. Call this early and often + * on random and semi-random system events to build randomness in time for + * usage. For randomly timed events, pass a null pointer and a zero length + * and this will use the system timer and other sources to add randomness. + * If new random data is available, pass a pointer to that and it will be + * included. + */ +void avChurnRand(char *randData, u32_t randLen); + +/* + * Randomize our random seed value. To be called for truely random events + * such as user operations and network traffic. + */ +#if MD5_SUPPORT +#define avRandomize() avChurnRand(NULL, 0) +#else /* MD5_SUPPORT */ +void avRandomize(void); +#endif /* MD5_SUPPORT */ + +/* + * Use the random pool to generate random data. This degrades to pseudo + * random when used faster than randomness is supplied using churnRand(). + * Thus it's important to make sure that the results of this are not + * published directly because one could predict the next result to at + * least some degree. Also, it's important to get a good seed before + * the first use. + */ +void avGenRand(char *buf, u32_t bufLen); + +/* + * Return a new random number. + */ +u32_t avRandom(void); + + +#endif /* RANDM_H */ diff --git a/features/unsupported/net/lwip/lwip/netif/ppp/vj.c b/features/unsupported/net/lwip/lwip/netif/ppp/vj.c new file mode 100644 index 00000000000..b7f2d54c627 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/netif/ppp/vj.c @@ -0,0 +1,652 @@ +/* + * Routines to compress and uncompess tcp packets (for transmission + * over low speed serial lines. + * + * Copyright (c) 1989 Regents of the University of California. + * All rights reserved. + * + * Redistribution and use in source and binary forms are permitted + * provided that the above copyright notice and this paragraph are + * duplicated in all such forms and that any documentation, + * advertising materials, and other materials related to such + * distribution and use acknowledge that the software was developed + * by the University of California, Berkeley. The name of the + * University may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED + * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. + * + * Van Jacobson (van@helios.ee.lbl.gov), Dec 31, 1989: + * Initial distribution. + * + * Modified June 1993 by Paul Mackerras, paulus@cs.anu.edu.au, + * so that the entire packet being decompressed doesn't have + * to be in contiguous memory (just the compressed header). + * + * Modified March 1998 by Guy Lancaster, glanca@gesn.com, + * for a 16 bit processor. + */ + +#include "lwip/opt.h" + +#if PPP_SUPPORT /* don't build if not configured for use in lwipopts.h */ + +#include "ppp.h" +#include "pppdebug.h" + +#include "vj.h" + +#include + +#if VJ_SUPPORT + +#if LINK_STATS +#define INCR(counter) ++comp->stats.counter +#else +#define INCR(counter) +#endif + +void +vj_compress_init(struct vjcompress *comp) +{ + register u_char i; + register struct cstate *tstate = comp->tstate; + +#if MAX_SLOTS == 0 + memset((char *)comp, 0, sizeof(*comp)); +#endif + comp->maxSlotIndex = MAX_SLOTS - 1; + comp->compressSlot = 0; /* Disable slot ID compression by default. */ + for (i = MAX_SLOTS - 1; i > 0; --i) { + tstate[i].cs_id = i; + tstate[i].cs_next = &tstate[i - 1]; + } + tstate[0].cs_next = &tstate[MAX_SLOTS - 1]; + tstate[0].cs_id = 0; + comp->last_cs = &tstate[0]; + comp->last_recv = 255; + comp->last_xmit = 255; + comp->flags = VJF_TOSS; +} + + +/* ENCODE encodes a number that is known to be non-zero. ENCODEZ + * checks for zero (since zero has to be encoded in the long, 3 byte + * form). + */ +#define ENCODE(n) { \ + if ((u_short)(n) >= 256) { \ + *cp++ = 0; \ + cp[1] = (u_char)(n); \ + cp[0] = (u_char)((n) >> 8); \ + cp += 2; \ + } else { \ + *cp++ = (u_char)(n); \ + } \ +} +#define ENCODEZ(n) { \ + if ((u_short)(n) >= 256 || (u_short)(n) == 0) { \ + *cp++ = 0; \ + cp[1] = (u_char)(n); \ + cp[0] = (u_char)((n) >> 8); \ + cp += 2; \ + } else { \ + *cp++ = (u_char)(n); \ + } \ +} + +#define DECODEL(f) { \ + if (*cp == 0) {\ + u32_t tmp = ntohl(f) + ((cp[1] << 8) | cp[2]); \ + (f) = htonl(tmp); \ + cp += 3; \ + } else { \ + u32_t tmp = ntohl(f) + (u32_t)*cp++; \ + (f) = htonl(tmp); \ + } \ +} + +#define DECODES(f) { \ + if (*cp == 0) {\ + u_short tmp = ntohs(f) + (((u_short)cp[1] << 8) | cp[2]); \ + (f) = htons(tmp); \ + cp += 3; \ + } else { \ + u_short tmp = ntohs(f) + (u_short)*cp++; \ + (f) = htons(tmp); \ + } \ +} + +#define DECODEU(f) { \ + if (*cp == 0) {\ + (f) = htons(((u_short)cp[1] << 8) | cp[2]); \ + cp += 3; \ + } else { \ + (f) = htons((u_short)*cp++); \ + } \ +} + +/* + * vj_compress_tcp - Attempt to do Van Jacobson header compression on a + * packet. This assumes that nb and comp are not null and that the first + * buffer of the chain contains a valid IP header. + * Return the VJ type code indicating whether or not the packet was + * compressed. + */ +u_int +vj_compress_tcp(struct vjcompress *comp, struct pbuf *pb) +{ + register struct ip_hdr *ip = (struct ip_hdr *)pb->payload; + register struct cstate *cs = comp->last_cs->cs_next; + register u_short hlen = IPH_HL(ip); + register struct tcp_hdr *oth; + register struct tcp_hdr *th; + register u_short deltaS, deltaA; + register u_long deltaL; + register u_int changes = 0; + u_char new_seq[16]; + register u_char *cp = new_seq; + + /* + * Check that the packet is IP proto TCP. + */ + if (IPH_PROTO(ip) != IP_PROTO_TCP) { + return (TYPE_IP); + } + + /* + * Bail if this is an IP fragment or if the TCP packet isn't + * `compressible' (i.e., ACK isn't set or some other control bit is + * set). + */ + if ((IPH_OFFSET(ip) & PP_HTONS(0x3fff)) || pb->tot_len < 40) { + return (TYPE_IP); + } + th = (struct tcp_hdr *)&((long *)ip)[hlen]; + if ((TCPH_FLAGS(th) & (TCP_SYN|TCP_FIN|TCP_RST|TCP_ACK)) != TCP_ACK) { + return (TYPE_IP); + } + /* + * Packet is compressible -- we're going to send either a + * COMPRESSED_TCP or UNCOMPRESSED_TCP packet. Either way we need + * to locate (or create) the connection state. Special case the + * most recently used connection since it's most likely to be used + * again & we don't have to do any reordering if it's used. + */ + INCR(vjs_packets); + if (!ip_addr_cmp(&ip->src, &cs->cs_ip.src) + || !ip_addr_cmp(&ip->dest, &cs->cs_ip.dest) + || *(long *)th != ((long *)&cs->cs_ip)[IPH_HL(&cs->cs_ip)]) { + /* + * Wasn't the first -- search for it. + * + * States are kept in a circularly linked list with + * last_cs pointing to the end of the list. The + * list is kept in lru order by moving a state to the + * head of the list whenever it is referenced. Since + * the list is short and, empirically, the connection + * we want is almost always near the front, we locate + * states via linear search. If we don't find a state + * for the datagram, the oldest state is (re-)used. + */ + register struct cstate *lcs; + register struct cstate *lastcs = comp->last_cs; + + do { + lcs = cs; cs = cs->cs_next; + INCR(vjs_searches); + if (ip_addr_cmp(&ip->src, &cs->cs_ip.src) + && ip_addr_cmp(&ip->dest, &cs->cs_ip.dest) + && *(long *)th == ((long *)&cs->cs_ip)[IPH_HL(&cs->cs_ip)]) { + goto found; + } + } while (cs != lastcs); + + /* + * Didn't find it -- re-use oldest cstate. Send an + * uncompressed packet that tells the other side what + * connection number we're using for this conversation. + * Note that since the state list is circular, the oldest + * state points to the newest and we only need to set + * last_cs to update the lru linkage. + */ + INCR(vjs_misses); + comp->last_cs = lcs; + hlen += TCPH_OFFSET(th); + hlen <<= 2; + /* Check that the IP/TCP headers are contained in the first buffer. */ + if (hlen > pb->len) { + return (TYPE_IP); + } + goto uncompressed; + + found: + /* + * Found it -- move to the front on the connection list. + */ + if (cs == lastcs) { + comp->last_cs = lcs; + } else { + lcs->cs_next = cs->cs_next; + cs->cs_next = lastcs->cs_next; + lastcs->cs_next = cs; + } + } + + oth = (struct tcp_hdr *)&((long *)&cs->cs_ip)[hlen]; + deltaS = hlen; + hlen += TCPH_OFFSET(th); + hlen <<= 2; + /* Check that the IP/TCP headers are contained in the first buffer. */ + if (hlen > pb->len) { + PPPDEBUG(LOG_INFO, ("vj_compress_tcp: header len %d spans buffers\n", hlen)); + return (TYPE_IP); + } + + /* + * Make sure that only what we expect to change changed. The first + * line of the `if' checks the IP protocol version, header length & + * type of service. The 2nd line checks the "Don't fragment" bit. + * The 3rd line checks the time-to-live and protocol (the protocol + * check is unnecessary but costless). The 4th line checks the TCP + * header length. The 5th line checks IP options, if any. The 6th + * line checks TCP options, if any. If any of these things are + * different between the previous & current datagram, we send the + * current datagram `uncompressed'. + */ + if (((u_short *)ip)[0] != ((u_short *)&cs->cs_ip)[0] + || ((u_short *)ip)[3] != ((u_short *)&cs->cs_ip)[3] + || ((u_short *)ip)[4] != ((u_short *)&cs->cs_ip)[4] + || TCPH_OFFSET(th) != TCPH_OFFSET(oth) + || (deltaS > 5 && BCMP(ip + 1, &cs->cs_ip + 1, (deltaS - 5) << 2)) + || (TCPH_OFFSET(th) > 5 && BCMP(th + 1, oth + 1, (TCPH_OFFSET(th) - 5) << 2))) { + goto uncompressed; + } + + /* + * Figure out which of the changing fields changed. The + * receiver expects changes in the order: urgent, window, + * ack, seq (the order minimizes the number of temporaries + * needed in this section of code). + */ + if (TCPH_FLAGS(th) & TCP_URG) { + deltaS = ntohs(th->urgp); + ENCODEZ(deltaS); + changes |= NEW_U; + } else if (th->urgp != oth->urgp) { + /* argh! URG not set but urp changed -- a sensible + * implementation should never do this but RFC793 + * doesn't prohibit the change so we have to deal + * with it. */ + goto uncompressed; + } + + if ((deltaS = (u_short)(ntohs(th->wnd) - ntohs(oth->wnd))) != 0) { + ENCODE(deltaS); + changes |= NEW_W; + } + + if ((deltaL = ntohl(th->ackno) - ntohl(oth->ackno)) != 0) { + if (deltaL > 0xffff) { + goto uncompressed; + } + deltaA = (u_short)deltaL; + ENCODE(deltaA); + changes |= NEW_A; + } + + if ((deltaL = ntohl(th->seqno) - ntohl(oth->seqno)) != 0) { + if (deltaL > 0xffff) { + goto uncompressed; + } + deltaS = (u_short)deltaL; + ENCODE(deltaS); + changes |= NEW_S; + } + + switch(changes) { + case 0: + /* + * Nothing changed. If this packet contains data and the + * last one didn't, this is probably a data packet following + * an ack (normal on an interactive connection) and we send + * it compressed. Otherwise it's probably a retransmit, + * retransmitted ack or window probe. Send it uncompressed + * in case the other side missed the compressed version. + */ + if (IPH_LEN(ip) != IPH_LEN(&cs->cs_ip) && + ntohs(IPH_LEN(&cs->cs_ip)) == hlen) { + break; + } + + /* (fall through) */ + + case SPECIAL_I: + case SPECIAL_D: + /* + * actual changes match one of our special case encodings -- + * send packet uncompressed. + */ + goto uncompressed; + + case NEW_S|NEW_A: + if (deltaS == deltaA && deltaS == ntohs(IPH_LEN(&cs->cs_ip)) - hlen) { + /* special case for echoed terminal traffic */ + changes = SPECIAL_I; + cp = new_seq; + } + break; + + case NEW_S: + if (deltaS == ntohs(IPH_LEN(&cs->cs_ip)) - hlen) { + /* special case for data xfer */ + changes = SPECIAL_D; + cp = new_seq; + } + break; + } + + deltaS = (u_short)(ntohs(IPH_ID(ip)) - ntohs(IPH_ID(&cs->cs_ip))); + if (deltaS != 1) { + ENCODEZ(deltaS); + changes |= NEW_I; + } + if (TCPH_FLAGS(th) & TCP_PSH) { + changes |= TCP_PUSH_BIT; + } + /* + * Grab the cksum before we overwrite it below. Then update our + * state with this packet's header. + */ + deltaA = ntohs(th->chksum); + BCOPY(ip, &cs->cs_ip, hlen); + + /* + * We want to use the original packet as our compressed packet. + * (cp - new_seq) is the number of bytes we need for compressed + * sequence numbers. In addition we need one byte for the change + * mask, one for the connection id and two for the tcp checksum. + * So, (cp - new_seq) + 4 bytes of header are needed. hlen is how + * many bytes of the original packet to toss so subtract the two to + * get the new packet size. + */ + deltaS = (u_short)(cp - new_seq); + if (!comp->compressSlot || comp->last_xmit != cs->cs_id) { + comp->last_xmit = cs->cs_id; + hlen -= deltaS + 4; + if(pbuf_header(pb, -hlen)){ + /* Can we cope with this failing? Just assert for now */ + LWIP_ASSERT("pbuf_header failed\n", 0); + } + cp = (u_char *)pb->payload; + *cp++ = (u_char)(changes | NEW_C); + *cp++ = cs->cs_id; + } else { + hlen -= deltaS + 3; + if(pbuf_header(pb, -hlen)) { + /* Can we cope with this failing? Just assert for now */ + LWIP_ASSERT("pbuf_header failed\n", 0); + } + cp = (u_char *)pb->payload; + *cp++ = (u_char)changes; + } + *cp++ = (u_char)(deltaA >> 8); + *cp++ = (u_char)deltaA; + BCOPY(new_seq, cp, deltaS); + INCR(vjs_compressed); + return (TYPE_COMPRESSED_TCP); + + /* + * Update connection state cs & send uncompressed packet (that is, + * a regular ip/tcp packet but with the 'conversation id' we hope + * to use on future compressed packets in the protocol field). + */ +uncompressed: + BCOPY(ip, &cs->cs_ip, hlen); + IPH_PROTO_SET(ip, cs->cs_id); + comp->last_xmit = cs->cs_id; + return (TYPE_UNCOMPRESSED_TCP); +} + +/* + * Called when we may have missed a packet. + */ +void +vj_uncompress_err(struct vjcompress *comp) +{ + comp->flags |= VJF_TOSS; + INCR(vjs_errorin); +} + +/* + * "Uncompress" a packet of type TYPE_UNCOMPRESSED_TCP. + * Return 0 on success, -1 on failure. + */ +int +vj_uncompress_uncomp(struct pbuf *nb, struct vjcompress *comp) +{ + register u_int hlen; + register struct cstate *cs; + register struct ip_hdr *ip; + + ip = (struct ip_hdr *)nb->payload; + hlen = IPH_HL(ip) << 2; + if (IPH_PROTO(ip) >= MAX_SLOTS + || hlen + sizeof(struct tcp_hdr) > nb->len + || (hlen += TCPH_OFFSET(((struct tcp_hdr *)&((char *)ip)[hlen])) << 2) + > nb->len + || hlen > MAX_HDR) { + PPPDEBUG(LOG_INFO, ("vj_uncompress_uncomp: bad cid=%d, hlen=%d buflen=%d\n", + IPH_PROTO(ip), hlen, nb->len)); + comp->flags |= VJF_TOSS; + INCR(vjs_errorin); + return -1; + } + cs = &comp->rstate[comp->last_recv = IPH_PROTO(ip)]; + comp->flags &=~ VJF_TOSS; + IPH_PROTO_SET(ip, IP_PROTO_TCP); + BCOPY(ip, &cs->cs_ip, hlen); + cs->cs_hlen = (u_short)hlen; + INCR(vjs_uncompressedin); + return 0; +} + +/* + * Uncompress a packet of type TYPE_COMPRESSED_TCP. + * The packet is composed of a buffer chain and the first buffer + * must contain an accurate chain length. + * The first buffer must include the entire compressed TCP/IP header. + * This procedure replaces the compressed header with the uncompressed + * header and returns the length of the VJ header. + */ +int +vj_uncompress_tcp(struct pbuf **nb, struct vjcompress *comp) +{ + u_char *cp; + struct tcp_hdr *th; + struct cstate *cs; + u_short *bp; + struct pbuf *n0 = *nb; + u32_t tmp; + u_int vjlen, hlen, changes; + + INCR(vjs_compressedin); + cp = (u_char *)n0->payload; + changes = *cp++; + if (changes & NEW_C) { + /* + * Make sure the state index is in range, then grab the state. + * If we have a good state index, clear the 'discard' flag. + */ + if (*cp >= MAX_SLOTS) { + PPPDEBUG(LOG_INFO, ("vj_uncompress_tcp: bad cid=%d\n", *cp)); + goto bad; + } + + comp->flags &=~ VJF_TOSS; + comp->last_recv = *cp++; + } else { + /* + * this packet has an implicit state index. If we've + * had a line error since the last time we got an + * explicit state index, we have to toss the packet. + */ + if (comp->flags & VJF_TOSS) { + PPPDEBUG(LOG_INFO, ("vj_uncompress_tcp: tossing\n")); + INCR(vjs_tossed); + return (-1); + } + } + cs = &comp->rstate[comp->last_recv]; + hlen = IPH_HL(&cs->cs_ip) << 2; + th = (struct tcp_hdr *)&((u_char *)&cs->cs_ip)[hlen]; + th->chksum = htons((*cp << 8) | cp[1]); + cp += 2; + if (changes & TCP_PUSH_BIT) { + TCPH_SET_FLAG(th, TCP_PSH); + } else { + TCPH_UNSET_FLAG(th, TCP_PSH); + } + + switch (changes & SPECIALS_MASK) { + case SPECIAL_I: + { + register u32_t i = ntohs(IPH_LEN(&cs->cs_ip)) - cs->cs_hlen; + /* some compilers can't nest inline assembler.. */ + tmp = ntohl(th->ackno) + i; + th->ackno = htonl(tmp); + tmp = ntohl(th->seqno) + i; + th->seqno = htonl(tmp); + } + break; + + case SPECIAL_D: + /* some compilers can't nest inline assembler.. */ + tmp = ntohl(th->seqno) + ntohs(IPH_LEN(&cs->cs_ip)) - cs->cs_hlen; + th->seqno = htonl(tmp); + break; + + default: + if (changes & NEW_U) { + TCPH_SET_FLAG(th, TCP_URG); + DECODEU(th->urgp); + } else { + TCPH_UNSET_FLAG(th, TCP_URG); + } + if (changes & NEW_W) { + DECODES(th->wnd); + } + if (changes & NEW_A) { + DECODEL(th->ackno); + } + if (changes & NEW_S) { + DECODEL(th->seqno); + } + break; + } + if (changes & NEW_I) { + DECODES(cs->cs_ip._id); + } else { + IPH_ID_SET(&cs->cs_ip, ntohs(IPH_ID(&cs->cs_ip)) + 1); + IPH_ID_SET(&cs->cs_ip, htons(IPH_ID(&cs->cs_ip))); + } + + /* + * At this point, cp points to the first byte of data in the + * packet. Fill in the IP total length and update the IP + * header checksum. + */ + vjlen = (u_short)(cp - (u_char*)n0->payload); + if (n0->len < vjlen) { + /* + * We must have dropped some characters (crc should detect + * this but the old slip framing won't) + */ + PPPDEBUG(LOG_INFO, ("vj_uncompress_tcp: head buffer %d too short %d\n", + n0->len, vjlen)); + goto bad; + } + +#if BYTE_ORDER == LITTLE_ENDIAN + tmp = n0->tot_len - vjlen + cs->cs_hlen; + IPH_LEN_SET(&cs->cs_ip, htons((u_short)tmp)); +#else + IPH_LEN_SET(&cs->cs_ip, htons(n0->tot_len - vjlen + cs->cs_hlen)); +#endif + + /* recompute the ip header checksum */ + bp = (u_short *) &cs->cs_ip; + IPH_CHKSUM_SET(&cs->cs_ip, 0); + for (tmp = 0; hlen > 0; hlen -= 2) { + tmp += *bp++; + } + tmp = (tmp & 0xffff) + (tmp >> 16); + tmp = (tmp & 0xffff) + (tmp >> 16); + IPH_CHKSUM_SET(&cs->cs_ip, (u_short)(~tmp)); + + /* Remove the compressed header and prepend the uncompressed header. */ + if(pbuf_header(n0, -((s16_t)(vjlen)))) { + /* Can we cope with this failing? Just assert for now */ + LWIP_ASSERT("pbuf_header failed\n", 0); + goto bad; + } + + if(LWIP_MEM_ALIGN(n0->payload) != n0->payload) { + struct pbuf *np, *q; + u8_t *bufptr; + + np = pbuf_alloc(PBUF_RAW, n0->len + cs->cs_hlen, PBUF_POOL); + if(!np) { + PPPDEBUG(LOG_WARNING, ("vj_uncompress_tcp: realign failed\n")); + goto bad; + } + + if(pbuf_header(np, -cs->cs_hlen)) { + /* Can we cope with this failing? Just assert for now */ + LWIP_ASSERT("pbuf_header failed\n", 0); + goto bad; + } + + bufptr = n0->payload; + for(q = np; q != NULL; q = q->next) { + MEMCPY(q->payload, bufptr, q->len); + bufptr += q->len; + } + + if(n0->next) { + pbuf_chain(np, n0->next); + pbuf_dechain(n0); + } + pbuf_free(n0); + n0 = np; + } + + if(pbuf_header(n0, cs->cs_hlen)) { + struct pbuf *np; + + LWIP_ASSERT("vj_uncompress_tcp: cs->cs_hlen <= PBUF_POOL_BUFSIZE", cs->cs_hlen <= PBUF_POOL_BUFSIZE); + np = pbuf_alloc(PBUF_RAW, cs->cs_hlen, PBUF_POOL); + if(!np) { + PPPDEBUG(LOG_WARNING, ("vj_uncompress_tcp: prepend failed\n")); + goto bad; + } + pbuf_cat(np, n0); + n0 = np; + } + LWIP_ASSERT("n0->len >= cs->cs_hlen", n0->len >= cs->cs_hlen); + MEMCPY(n0->payload, &cs->cs_ip, cs->cs_hlen); + + *nb = n0; + + return vjlen; + +bad: + comp->flags |= VJF_TOSS; + INCR(vjs_errorin); + return (-1); +} + +#endif /* VJ_SUPPORT */ + +#endif /* PPP_SUPPORT */ diff --git a/features/unsupported/net/lwip/lwip/netif/ppp/vj.h b/features/unsupported/net/lwip/lwip/netif/ppp/vj.h new file mode 100644 index 00000000000..fad1213646a --- /dev/null +++ b/features/unsupported/net/lwip/lwip/netif/ppp/vj.h @@ -0,0 +1,156 @@ +/* + * Definitions for tcp compression routines. + * + * $Id: vj.h,v 1.7 2010/02/22 17:52:09 goldsimon Exp $ + * + * Copyright (c) 1989 Regents of the University of California. + * All rights reserved. + * + * Redistribution and use in source and binary forms are permitted + * provided that the above copyright notice and this paragraph are + * duplicated in all such forms and that any documentation, + * advertising materials, and other materials related to such + * distribution and use acknowledge that the software was developed + * by the University of California, Berkeley. The name of the + * University may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED + * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. + * + * Van Jacobson (van@helios.ee.lbl.gov), Dec 31, 1989: + * - Initial distribution. + */ + +#ifndef VJ_H +#define VJ_H + +#include "lwip/ip.h" +#include "lwip/tcp_impl.h" + +#define MAX_SLOTS 16 /* must be > 2 and < 256 */ +#define MAX_HDR 128 + +/* + * Compressed packet format: + * + * The first octet contains the packet type (top 3 bits), TCP + * 'push' bit, and flags that indicate which of the 4 TCP sequence + * numbers have changed (bottom 5 bits). The next octet is a + * conversation number that associates a saved IP/TCP header with + * the compressed packet. The next two octets are the TCP checksum + * from the original datagram. The next 0 to 15 octets are + * sequence number changes, one change per bit set in the header + * (there may be no changes and there are two special cases where + * the receiver implicitly knows what changed -- see below). + * + * There are 5 numbers which can change (they are always inserted + * in the following order): TCP urgent pointer, window, + * acknowlegement, sequence number and IP ID. (The urgent pointer + * is different from the others in that its value is sent, not the + * change in value.) Since typical use of SLIP links is biased + * toward small packets (see comments on MTU/MSS below), changes + * use a variable length coding with one octet for numbers in the + * range 1 - 255 and 3 octets (0, MSB, LSB) for numbers in the + * range 256 - 65535 or 0. (If the change in sequence number or + * ack is more than 65535, an uncompressed packet is sent.) + */ + +/* + * Packet types (must not conflict with IP protocol version) + * + * The top nibble of the first octet is the packet type. There are + * three possible types: IP (not proto TCP or tcp with one of the + * control flags set); uncompressed TCP (a normal IP/TCP packet but + * with the 8-bit protocol field replaced by an 8-bit connection id -- + * this type of packet syncs the sender & receiver); and compressed + * TCP (described above). + * + * LSB of 4-bit field is TCP "PUSH" bit (a worthless anachronism) and + * is logically part of the 4-bit "changes" field that follows. Top + * three bits are actual packet type. For backward compatibility + * and in the interest of conserving bits, numbers are chosen so the + * IP protocol version number (4) which normally appears in this nibble + * means "IP packet". + */ + +/* packet types */ +#define TYPE_IP 0x40 +#define TYPE_UNCOMPRESSED_TCP 0x70 +#define TYPE_COMPRESSED_TCP 0x80 +#define TYPE_ERROR 0x00 + +/* Bits in first octet of compressed packet */ +#define NEW_C 0x40 /* flag bits for what changed in a packet */ +#define NEW_I 0x20 +#define NEW_S 0x08 +#define NEW_A 0x04 +#define NEW_W 0x02 +#define NEW_U 0x01 + +/* reserved, special-case values of above */ +#define SPECIAL_I (NEW_S|NEW_W|NEW_U) /* echoed interactive traffic */ +#define SPECIAL_D (NEW_S|NEW_A|NEW_W|NEW_U) /* unidirectional data */ +#define SPECIALS_MASK (NEW_S|NEW_A|NEW_W|NEW_U) + +#define TCP_PUSH_BIT 0x10 + + +/* + * "state" data for each active tcp conversation on the wire. This is + * basically a copy of the entire IP/TCP header from the last packet + * we saw from the conversation together with a small identifier + * the transmit & receive ends of the line use to locate saved header. + */ +struct cstate { + struct cstate *cs_next; /* next most recently used state (xmit only) */ + u_short cs_hlen; /* size of hdr (receive only) */ + u_char cs_id; /* connection # associated with this state */ + u_char cs_filler; + union { + char csu_hdr[MAX_HDR]; + struct ip_hdr csu_ip; /* ip/tcp hdr from most recent packet */ + } vjcs_u; +}; +#define cs_ip vjcs_u.csu_ip +#define cs_hdr vjcs_u.csu_hdr + + +struct vjstat { + unsigned long vjs_packets; /* outbound packets */ + unsigned long vjs_compressed; /* outbound compressed packets */ + unsigned long vjs_searches; /* searches for connection state */ + unsigned long vjs_misses; /* times couldn't find conn. state */ + unsigned long vjs_uncompressedin; /* inbound uncompressed packets */ + unsigned long vjs_compressedin; /* inbound compressed packets */ + unsigned long vjs_errorin; /* inbound unknown type packets */ + unsigned long vjs_tossed; /* inbound packets tossed because of error */ +}; + +/* + * all the state data for one serial line (we need one of these per line). + */ +struct vjcompress { + struct cstate *last_cs; /* most recently used tstate */ + u_char last_recv; /* last rcvd conn. id */ + u_char last_xmit; /* last sent conn. id */ + u_short flags; + u_char maxSlotIndex; + u_char compressSlot; /* Flag indicating OK to compress slot ID. */ +#if LINK_STATS + struct vjstat stats; +#endif + struct cstate tstate[MAX_SLOTS]; /* xmit connection states */ + struct cstate rstate[MAX_SLOTS]; /* receive connection states */ +}; + +/* flag values */ +#define VJF_TOSS 1U /* tossing rcvd frames because of input err */ + +extern void vj_compress_init (struct vjcompress *comp); +extern u_int vj_compress_tcp (struct vjcompress *comp, struct pbuf *pb); +extern void vj_uncompress_err (struct vjcompress *comp); +extern int vj_uncompress_uncomp(struct pbuf *nb, struct vjcompress *comp); +extern int vj_uncompress_tcp (struct pbuf **nb, struct vjcompress *comp); + +#endif /* VJ_H */ diff --git a/features/unsupported/net/lwip/lwip/netif/slipif.c b/features/unsupported/net/lwip/lwip/netif/slipif.c new file mode 100644 index 00000000000..c19333dd704 --- /dev/null +++ b/features/unsupported/net/lwip/lwip/netif/slipif.c @@ -0,0 +1,367 @@ +/** + * @file + * SLIP Interface + * + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * This file is built upon the file: src/arch/rtxc/netif/sioslip.c + * + * Author: Magnus Ivarsson + */ + +/* + * This is an arch independent SLIP netif. The specific serial hooks must be + * provided by another file. They are sio_open, sio_read/sio_tryread and sio_send + */ + +#include "netif/slipif.h" +#include "lwip/opt.h" + +#if LWIP_HAVE_SLIPIF + +#include "lwip/def.h" +#include "lwip/pbuf.h" +#include "lwip/sys.h" +#include "lwip/stats.h" +#include "lwip/snmp.h" +#include "lwip/sio.h" + +#define SLIP_BLOCK 1 +#define SLIP_DONTBLOCK 0 + +#define SLIP_END 0300 /* 0xC0 */ +#define SLIP_ESC 0333 /* 0xDB */ +#define SLIP_ESC_END 0334 /* 0xDC */ +#define SLIP_ESC_ESC 0335 /* 0xDD */ + +#define SLIP_MAX_SIZE 1500 + +enum slipif_recv_state { + SLIP_RECV_NORMAL, + SLIP_RECV_ESCAPE, +}; + +struct slipif_priv { + sio_fd_t sd; + /* q is the whole pbuf chain for a packet, p is the current pbuf in the chain */ + struct pbuf *p, *q; + enum slipif_recv_state state; + u16_t i, recved; +}; + +/** + * Send a pbuf doing the necessary SLIP encapsulation + * + * Uses the serial layer's sio_send() + * + * @param netif the lwip network interface structure for this slipif + * @param p the pbuf chaing packet to send + * @param ipaddr the ip address to send the packet to (not used for slipif) + * @return always returns ERR_OK since the serial layer does not provide return values + */ +err_t +slipif_output(struct netif *netif, struct pbuf *p, ip_addr_t *ipaddr) +{ + struct slipif_priv *priv; + struct pbuf *q; + u16_t i; + u8_t c; + + LWIP_ASSERT("netif != NULL", (netif != NULL)); + LWIP_ASSERT("netif->state != NULL", (netif->state != NULL)); + LWIP_ASSERT("p != NULL", (p != NULL)); + + LWIP_UNUSED_ARG(ipaddr); + + priv = netif->state; + + /* Send pbuf out on the serial I/O device. */ + sio_send(SLIP_END, priv->sd); + + for (q = p; q != NULL; q = q->next) { + for (i = 0; i < q->len; i++) { + c = ((u8_t *)q->payload)[i]; + switch (c) { + case SLIP_END: + sio_send(SLIP_ESC, priv->sd); + sio_send(SLIP_ESC_END, priv->sd); + break; + case SLIP_ESC: + sio_send(SLIP_ESC, priv->sd); + sio_send(SLIP_ESC_ESC, priv->sd); + break; + default: + sio_send(c, priv->sd); + break; + } + } + } + sio_send(SLIP_END, priv->sd); + return ERR_OK; +} + +/** + * Static function for easy use of blockig or non-blocking + * sio_read + * + * @param fd serial device handle + * @param data pointer to data buffer for receiving + * @param len maximum length (in bytes) of data to receive + * @param block if 1, call sio_read; if 0, call sio_tryread + * @return return value of sio_read of sio_tryread + */ +static u32_t +slip_sio_read(sio_fd_t fd, u8_t* data, u32_t len, u8_t block) +{ + if (block) { + return sio_read(fd, data, len); + } else { + return sio_tryread(fd, data, len); + } +} + +/** + * Handle the incoming SLIP stream character by character + * + * Poll the serial layer by calling sio_read() or sio_tryread(). + * + * @param netif the lwip network interface structure for this slipif + * @param block if 1, block until data is received; if 0, return when all data + * from the buffer is received (multiple calls to this function will + * return a complete packet, NULL is returned before - used for polling) + * @return The IP packet when SLIP_END is received + */ +static struct pbuf * +slipif_input(struct netif *netif, u8_t block) +{ + struct slipif_priv *priv; + u8_t c; + struct pbuf *t; + + LWIP_ASSERT("netif != NULL", (netif != NULL)); + LWIP_ASSERT("netif->state != NULL", (netif->state != NULL)); + + priv = netif->state; + + while (slip_sio_read(priv->sd, &c, 1, block) > 0) { + switch (priv->state) { + case SLIP_RECV_NORMAL: + switch (c) { + case SLIP_END: + if (priv->recved > 0) { + /* Received whole packet. */ + /* Trim the pbuf to the size of the received packet. */ + pbuf_realloc(priv->q, priv->recved); + + LINK_STATS_INC(link.recv); + + LWIP_DEBUGF(SLIP_DEBUG, ("slipif: Got packet\n")); + t = priv->q; + priv->p = priv->q = NULL; + priv->i = priv->recved = 0; + return t; + } + continue; + case SLIP_ESC: + priv->state = SLIP_RECV_ESCAPE; + continue; + } + break; + case SLIP_RECV_ESCAPE: + switch (c) { + case SLIP_ESC_END: + c = SLIP_END; + break; + case SLIP_ESC_ESC: + c = SLIP_ESC; + break; + } + priv->state = SLIP_RECV_NORMAL; + /* FALLTHROUGH */ + } + + /* byte received, packet not yet completely received */ + if (priv->p == NULL) { + /* allocate a new pbuf */ + LWIP_DEBUGF(SLIP_DEBUG, ("slipif_input: alloc\n")); + priv->p = pbuf_alloc(PBUF_LINK, (PBUF_POOL_BUFSIZE - PBUF_LINK_HLEN), PBUF_POOL); + + if (priv->p == NULL) { + LINK_STATS_INC(link.drop); + LWIP_DEBUGF(SLIP_DEBUG, ("slipif_input: no new pbuf! (DROP)\n")); + /* don't process any further since we got no pbuf to receive to */ + break; + } + + if (priv->q != NULL) { + /* 'chain' the pbuf to the existing chain */ + pbuf_cat(priv->q, priv->p); + } else { + /* p is the first pbuf in the chain */ + priv->q = priv->p; + } + } + + /* this automatically drops bytes if > SLIP_MAX_SIZE */ + if ((priv->p != NULL) && (priv->recved <= SLIP_MAX_SIZE)) { + ((u8_t *)priv->p->payload)[priv->i] = c; + priv->recved++; + priv->i++; + if (priv->i >= priv->p->len) { + /* on to the next pbuf */ + priv->i = 0; + if (priv->p->next != NULL && priv->p->next->len > 0) { + /* p is a chain, on to the next in the chain */ + priv->p = priv->p->next; + } else { + /* p is a single pbuf, set it to NULL so next time a new + * pbuf is allocated */ + priv->p = NULL; + } + } + } + } + + return NULL; +} + +#if !NO_SYS +/** + * The SLIP input thread. + * + * Feed the IP layer with incoming packets + * + * @param nf the lwip network interface structure for this slipif + */ +static void +slipif_loop_thread(void *nf) +{ + struct pbuf *p; + struct netif *netif = (struct netif *)nf; + + while (1) { + p = slipif_input(netif, SLIP_BLOCK); + if (p != NULL) { + if (netif->input(p, netif) != ERR_OK) { + pbuf_free(p); + p = NULL; + } + } + } +} +#endif /* !NO_SYS */ + +/** + * SLIP netif initialization + * + * Call the arch specific sio_open and remember + * the opened device in the state field of the netif. + * + * @param netif the lwip network interface structure for this slipif + * @return ERR_OK if serial line could be opened, + * ERR_MEM if no memory could be allocated, + * ERR_IF is serial line couldn't be opened + * + * @note netif->num must contain the number of the serial port to open + * (0 by default) + */ +err_t +slipif_init(struct netif *netif) +{ + struct slipif_priv *priv; + + LWIP_DEBUGF(SLIP_DEBUG, ("slipif_init: netif->num=%"U16_F"\n", (u16_t)netif->num)); + + /* Allocate private data */ + priv = mem_malloc(sizeof(struct slipif_priv)); + if (!priv) { + return ERR_MEM; + } + + netif->name[0] = 's'; + netif->name[1] = 'l'; + netif->output = slipif_output; + netif->mtu = SLIP_MAX_SIZE; + netif->flags |= NETIF_FLAG_POINTTOPOINT; + + /* Try to open the serial port (netif->num contains the port number). */ + priv->sd = sio_open(netif->num); + if (!priv->sd) { + /* Opening the serial port failed. */ + mem_free(priv); + return ERR_IF; + } + + /* Initialize private data */ + priv->p = NULL; + priv->q = NULL; + priv->state = SLIP_RECV_NORMAL; + priv->i = 0; + priv->recved = 0; + + netif->state = priv; + + /* initialize the snmp variables and counters inside the struct netif + * ifSpeed: no assumption can be made without knowing more about the + * serial line! + */ + NETIF_INIT_SNMP(netif, snmp_ifType_slip, 0); + + /* Create a thread to poll the serial line. */ + sys_thread_new(SLIPIF_THREAD_NAME, slipif_loop_thread, netif, + SLIPIF_THREAD_STACKSIZE, SLIPIF_THREAD_PRIO); + return ERR_OK; +} + +/** + * Polls the serial device and feeds the IP layer with incoming packets. + * + * @param netif The lwip network interface structure for this slipif + */ +void +slipif_poll(struct netif *netif) +{ + struct pbuf *p; + struct slipif_priv *priv; + + LWIP_ASSERT("netif != NULL", (netif != NULL)); + LWIP_ASSERT("netif->state != NULL", (netif->state != NULL)); + + priv = netif->state; + + while ((p = slipif_input(netif, SLIP_DONTBLOCK)) != NULL) { + if (netif->input(p, netif) != ERR_OK) { + pbuf_free(p); + } + } +} + +#endif /* LWIP_HAVE_SLIPIF */ diff --git a/features/unsupported/tests/net/cellular/http/common/HTTPClient/HTTPClient.cpp b/features/unsupported/tests/net/cellular/http/common/HTTPClient/HTTPClient.cpp new file mode 100644 index 00000000000..ff367fb30a3 --- /dev/null +++ b/features/unsupported/tests/net/cellular/http/common/HTTPClient/HTTPClient.cpp @@ -0,0 +1,649 @@ +/* HTTPClient.cpp */ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +//Debug is disabled by default +#if 0 +//Enable debug +#include +#define DBG(x, ...) std::printf("[HTTPClient : DBG]"x"\r\n", ##__VA_ARGS__); +#define WARN(x, ...) std::printf("[HTTPClient : WARN]"x"\r\n", ##__VA_ARGS__); +#define ERR(x, ...) std::printf("[HTTPClient : ERR]"x"\r\n", ##__VA_ARGS__); + +#else +//Disable debug +#define DBG(x, ...) +#define WARN(x, ...) +#define ERR(x, ...) + +#endif + +#define HTTP_PORT 80 + +#define OK 0 + +#define MIN(x,y) (((x)<(y))?(x):(y)) +#define MAX(x,y) (((x)>(y))?(x):(y)) + +#define CHUNK_SIZE 256 + +#include + +#include "HTTPClient.h" + +HTTPClient::HTTPClient() : +m_sock(), m_basicAuthUser(NULL), m_basicAuthPassword(NULL), m_httpResponseCode(0) +{ + +} + +HTTPClient::~HTTPClient() +{ + +} + +#if 0 +void HTTPClient::basicAuth(const char* user, const char* password) //Basic Authentification +{ + m_basicAuthUser = user; + m_basicAuthPassword = password; +} +#endif + +HTTPResult HTTPClient::get(const char* url, IHTTPDataIn* pDataIn, int timeout /*= HTTP_CLIENT_DEFAULT_TIMEOUT*/) //Blocking +{ + return connect(url, HTTP_GET, NULL, pDataIn, timeout); +} + +HTTPResult HTTPClient::get(const char* url, char* result, size_t maxResultLen, int timeout /*= HTTP_CLIENT_DEFAULT_TIMEOUT*/) //Blocking +{ + HTTPText str(result, maxResultLen); + return get(url, &str, timeout); +} + +HTTPResult HTTPClient::post(const char* url, const IHTTPDataOut& dataOut, IHTTPDataIn* pDataIn, int timeout /*= HTTP_CLIENT_DEFAULT_TIMEOUT*/) //Blocking +{ + return connect(url, HTTP_POST, (IHTTPDataOut*)&dataOut, pDataIn, timeout); +} + +HTTPResult HTTPClient::put(const char* url, const IHTTPDataOut& dataOut, IHTTPDataIn* pDataIn, int timeout /*= HTTP_CLIENT_DEFAULT_TIMEOUT*/) //Blocking +{ + return connect(url, HTTP_PUT, (IHTTPDataOut*)&dataOut, pDataIn, timeout); +} + +HTTPResult HTTPClient::del(const char* url, IHTTPDataIn* pDataIn, int timeout /*= HTTP_CLIENT_DEFAULT_TIMEOUT*/) //Blocking +{ + return connect(url, HTTP_DELETE, NULL, pDataIn, timeout); +} + + +int HTTPClient::getHTTPResponseCode() +{ + return m_httpResponseCode; +} + +#define CHECK_CONN_ERR(ret) \ + do{ \ + if(ret) { \ + m_sock.close(); \ + ERR("Connection error (%d)", ret); \ + return HTTP_CONN; \ + } \ + } while(0) + +#define PRTCL_ERR() \ + do{ \ + m_sock.close(); \ + ERR("Protocol error"); \ + return HTTP_PRTCL; \ + } while(0) + +HTTPResult HTTPClient::connect(const char* url, HTTP_METH method, IHTTPDataOut* pDataOut, IHTTPDataIn* pDataIn, int timeout) //Execute request +{ + m_httpResponseCode = 0; //Invalidate code + m_timeout = timeout; + + pDataIn->writeReset(); + if( pDataOut ) + { + pDataOut->readReset(); + } + + char scheme[8]; + uint16_t port; + char host[32]; + char path[64]; + //First we need to parse the url (http[s]://host[:port][/[path]]) -- HTTPS not supported (yet?) + HTTPResult res = parseURL(url, scheme, sizeof(scheme), host, sizeof(host), &port, path, sizeof(path)); + if(res != HTTP_OK) + { + ERR("parseURL returned %d", res); + return res; + } + + if(port == 0) //TODO do handle HTTPS->443 + { + port = 80; + } + + DBG("Scheme: %s", scheme); + DBG("Host: %s", host); + DBG("Port: %d", port); + DBG("Path: %s", path); + + //Connect + DBG("Connecting socket to server"); + int ret = m_sock.connect(host, port); + if (ret < 0) + { + m_sock.close(); + ERR("Could not connect"); + return HTTP_CONN; + } + + //Send request + DBG("Sending request"); + char buf[CHUNK_SIZE]; + const char* meth = (method==HTTP_GET)?"GET":(method==HTTP_POST)?"POST":(method==HTTP_PUT)?"PUT":(method==HTTP_DELETE)?"DELETE":""; + snprintf(buf, sizeof(buf), "%s %s HTTP/1.1\r\nHost: %s\r\n", meth, path, host); //Write request + ret = send(buf); + if(ret) + { + m_sock.close(); + ERR("Could not write request"); + return HTTP_CONN; + } + + //Send all headers + + //Send default headers + DBG("Sending headers"); + if( pDataOut != NULL ) + { + if( pDataOut->getIsChunked() ) + { + ret = send("Transfer-Encoding: chunked\r\n"); + CHECK_CONN_ERR(ret); + } + else + { + snprintf(buf, sizeof(buf), "Content-Length: %d\r\n", pDataOut->getDataLen()); + ret = send(buf); + CHECK_CONN_ERR(ret); + } + char type[48]; + if( pDataOut->getDataType(type, 48) == HTTP_OK ) + { + snprintf(buf, sizeof(buf), "Content-Type: %s\r\n", type); + ret = send(buf); + CHECK_CONN_ERR(ret); + } + } + + //Close headers + DBG("Headers sent"); + ret = send("\r\n"); + CHECK_CONN_ERR(ret); + + size_t trfLen; + + //Send data (if available) + if( pDataOut != NULL ) + { + DBG("Sending data"); + while(true) + { + size_t writtenLen = 0; + pDataOut->read(buf, CHUNK_SIZE, &trfLen); + if( pDataOut->getIsChunked() ) + { + //Write chunk header + char chunkHeader[16]; + snprintf(chunkHeader, sizeof(chunkHeader), "%X\r\n", trfLen); //In hex encoding + ret = send(chunkHeader); + CHECK_CONN_ERR(ret); + } + else if( trfLen == 0 ) + { + break; + } + if( trfLen != 0 ) + { + ret = send(buf, trfLen); + CHECK_CONN_ERR(ret); + } + + if( pDataOut->getIsChunked() ) + { + ret = send("\r\n"); //Chunk-terminating CRLF + CHECK_CONN_ERR(ret); + } + else + { + writtenLen += trfLen; + if( writtenLen >= pDataOut->getDataLen() ) + { + break; + } + } + + if( trfLen == 0 ) + { + break; + } + } + + } + + //Receive response + DBG("Receiving response"); + ret = recv(buf, CHUNK_SIZE - 1, CHUNK_SIZE - 1, &trfLen); //Read n bytes + CHECK_CONN_ERR(ret); + + buf[trfLen] = '\0'; + + char* crlfPtr = strstr(buf, "\r\n"); + if(crlfPtr == NULL) + { + PRTCL_ERR(); + } + + int crlfPos = crlfPtr - buf; + buf[crlfPos] = '\0'; + + //Parse HTTP response + if( sscanf(buf, "HTTP/%*d.%*d %d %*[^\r\n]", &m_httpResponseCode) != 1 ) + { + //Cannot match string, error + ERR("Not a correct HTTP answer : %s\n", buf); + PRTCL_ERR(); + } + + if( (m_httpResponseCode < 200) || (m_httpResponseCode >= 300) ) + { + //Did not return a 2xx code; TODO fetch headers/(&data?) anyway and implement a mean of writing/reading headers + WARN("Response code %d", m_httpResponseCode); + PRTCL_ERR(); + } + + DBG("Reading headers"); + + memmove(buf, &buf[crlfPos+2], trfLen - (crlfPos + 2) + 1); //Be sure to move NULL-terminating char as well + trfLen -= (crlfPos + 2); + + size_t recvContentLength = 0; + bool recvChunked = false; + //Now get headers + while( true ) + { + crlfPtr = strstr(buf, "\r\n"); + if(crlfPtr == NULL) + { + if( trfLen < CHUNK_SIZE - 1 ) + { + size_t newTrfLen; + ret = recv(buf + trfLen, 1, CHUNK_SIZE - trfLen - 1, &newTrfLen); + trfLen += newTrfLen; + buf[trfLen] = '\0'; + DBG("Read %d chars; In buf: [%s]", newTrfLen, buf); + CHECK_CONN_ERR(ret); + continue; + } + else + { + PRTCL_ERR(); + } + } + + crlfPos = crlfPtr - buf; + + if(crlfPos == 0) //End of headers + { + DBG("Headers read"); + memmove(buf, &buf[2], trfLen - 2 + 1); //Be sure to move NULL-terminating char as well + trfLen -= 2; + break; + } + + buf[crlfPos] = '\0'; + + char key[32]; + char value[32]; + + key[31] = '\0'; + value[31] = '\0'; + + int n = sscanf(buf, "%31[^:]: %31[^\r\n]", key, value); + if ( n == 2 ) + { + DBG("Read header : %s: %s\n", key, value); + if( !strcmp(key, "Content-Length") ) + { + sscanf(value, "%d", &recvContentLength); + pDataIn->setDataLen(recvContentLength); + } + else if( !strcmp(key, "Transfer-Encoding") ) + { + if( !strcmp(value, "Chunked") || !strcmp(value, "chunked") ) + { + recvChunked = true; + pDataIn->setIsChunked(true); + } + } + else if( !strcmp(key, "Content-Type") ) + { + pDataIn->setDataType(value); + } + + memmove(buf, &buf[crlfPos+2], trfLen - (crlfPos + 2) + 1); //Be sure to move NULL-terminating char as well + trfLen -= (crlfPos + 2); + + } + else + { + ERR("Could not parse header"); + PRTCL_ERR(); + } + + } + + //Receive data + DBG("Receiving data"); + while(true) + { + size_t readLen = 0; + + if( recvChunked ) + { + //Read chunk header + bool foundCrlf; + do + { + foundCrlf = false; + crlfPos=0; + buf[trfLen]=0; + if(trfLen >= 2) + { + for(; crlfPos < trfLen - 2; crlfPos++) + { + if( buf[crlfPos] == '\r' && buf[crlfPos + 1] == '\n' ) + { + foundCrlf = true; + break; + } + } + } + if(!foundCrlf) //Try to read more + { + if( trfLen < CHUNK_SIZE ) + { + size_t newTrfLen; + ret = recv(buf + trfLen, 0, CHUNK_SIZE - trfLen - 1, &newTrfLen); + trfLen += newTrfLen; + CHECK_CONN_ERR(ret); + continue; + } + else + { + PRTCL_ERR(); + } + } + } while(!foundCrlf); + buf[crlfPos] = '\0'; + int n = sscanf(buf, "%x", &readLen); + if(n!=1) + { + ERR("Could not read chunk length"); + PRTCL_ERR(); + } + + memmove(buf, &buf[crlfPos+2], trfLen - (crlfPos + 2)); //Not need to move NULL-terminating char any more + trfLen -= (crlfPos + 2); + + if( readLen == 0 ) + { + //Last chunk + break; + } + } + else + { + readLen = recvContentLength; + } + + DBG("Retrieving %d bytes", readLen); + + do + { + pDataIn->write(buf, MIN(trfLen, readLen)); + if( trfLen > readLen ) + { + memmove(buf, &buf[readLen], trfLen - readLen); + trfLen -= readLen; + readLen = 0; + } + else + { + readLen -= trfLen; + } + + if(readLen) + { + ret = recv(buf, 1, CHUNK_SIZE - trfLen - 1, &trfLen); + CHECK_CONN_ERR(ret); + } + } while(readLen); + + if( recvChunked ) + { + if(trfLen < 2) + { + size_t newTrfLen; + //Read missing chars to find end of chunk + ret = recv(buf + trfLen, 2 - trfLen, CHUNK_SIZE - trfLen - 1, &newTrfLen); + CHECK_CONN_ERR(ret); + trfLen += newTrfLen; + } + if( (buf[0] != '\r') || (buf[1] != '\n') ) + { + ERR("Format error"); + PRTCL_ERR(); + } + memmove(buf, &buf[2], trfLen - 2); + trfLen -= 2; + } + else + { + break; + } + + } + + m_sock.close(); + DBG("Completed HTTP transaction"); + + return HTTP_OK; +} + +HTTPResult HTTPClient::recv(char* buf, size_t minLen, size_t maxLen, size_t* pReadLen) //0 on success, err code on failure +{ + DBG("Trying to read between %d and %d bytes", minLen, maxLen); + size_t readLen = 0; + + if(!m_sock.is_connected()) + { + WARN("Connection was closed by server"); + return HTTP_CLOSED; //Connection was closed by server + } + + int ret; + while(readLen < maxLen) + { + if(readLen < minLen) + { + DBG("Trying to read at most %d bytes [Blocking]", minLen - readLen); + m_sock.set_blocking(false, m_timeout); + ret = m_sock.receive_all(buf + readLen, minLen - readLen); + } + else + { + DBG("Trying to read at most %d bytes [Not blocking]", maxLen - readLen); + m_sock.set_blocking(false, 0); + ret = m_sock.receive(buf + readLen, maxLen - readLen); + } + + if( ret > 0) + { + readLen += ret; + } + else if( ret == 0 ) + { + break; + } + else + { + if(!m_sock.is_connected()) + { + ERR("Connection error (recv returned %d)", ret); + *pReadLen = readLen; + return HTTP_CONN; + } + else + { + break; + } + } + + if(!m_sock.is_connected()) + { + break; + } + } + DBG("Read %d bytes", readLen); + *pReadLen = readLen; + return HTTP_OK; +} + +HTTPResult HTTPClient::send(char* buf, size_t len) //0 on success, err code on failure +{ + if(len == 0) + { + len = strlen(buf); + } + DBG("Trying to write %d bytes", len); + size_t writtenLen = 0; + + if(!m_sock.is_connected()) + { + WARN("Connection was closed by server"); + return HTTP_CLOSED; //Connection was closed by server + } + + m_sock.set_blocking(false, m_timeout); + int ret = m_sock.send_all(buf, len); + if(ret > 0) + { + writtenLen += ret; + } + else if( ret == 0 ) + { + WARN("Connection was closed by server"); + return HTTP_CLOSED; //Connection was closed by server + } + else + { + ERR("Connection error (send returned %d)", ret); + return HTTP_CONN; + } + + DBG("Written %d bytes", writtenLen); + return HTTP_OK; +} + +HTTPResult HTTPClient::parseURL(const char* url, char* scheme, size_t maxSchemeLen, char* host, size_t maxHostLen, uint16_t* port, char* path, size_t maxPathLen) //Parse URL +{ + char* schemePtr = (char*) url; + char* hostPtr = (char*) strstr(url, "://"); + if(hostPtr == NULL) + { + WARN("Could not find host"); + return HTTP_PARSE; //URL is invalid + } + + if( maxSchemeLen < hostPtr - schemePtr + 1 ) //including NULL-terminating char + { + WARN("Scheme str is too small (%d >= %d)", maxSchemeLen, hostPtr - schemePtr + 1); + return HTTP_PARSE; + } + memcpy(scheme, schemePtr, hostPtr - schemePtr); + scheme[hostPtr - schemePtr] = '\0'; + + hostPtr+=3; + + size_t hostLen = 0; + + char* portPtr = strchr(hostPtr, ':'); + if( portPtr != NULL ) + { + hostLen = portPtr - hostPtr; + portPtr++; + if( sscanf(portPtr, "%hu", port) != 1) + { + WARN("Could not find port"); + return HTTP_PARSE; + } + } + else + { + *port=0; + } + char* pathPtr = strchr(hostPtr, '/'); + if( hostLen == 0 ) + { + hostLen = pathPtr - hostPtr; + } + + if( maxHostLen < hostLen + 1 ) //including NULL-terminating char + { + WARN("Host str is too small (%d >= %d)", maxHostLen, hostLen + 1); + return HTTP_PARSE; + } + memcpy(host, hostPtr, hostLen); + host[hostLen] = '\0'; + + size_t pathLen; + char* fragmentPtr = strchr(hostPtr, '#'); + if(fragmentPtr != NULL) + { + pathLen = fragmentPtr - pathPtr; + } + else + { + pathLen = strlen(pathPtr); + } + + if( maxPathLen < pathLen + 1 ) //including NULL-terminating char + { + WARN("Path str is too small (%d >= %d)", maxPathLen, pathLen + 1); + return HTTP_PARSE; + } + memcpy(path, pathPtr, pathLen); + path[pathLen] = '\0'; + + return HTTP_OK; +} diff --git a/features/unsupported/tests/net/cellular/http/common/HTTPClient/HTTPClient.h b/features/unsupported/tests/net/cellular/http/common/HTTPClient/HTTPClient.h new file mode 100644 index 00000000000..7cb30b03371 --- /dev/null +++ b/features/unsupported/tests/net/cellular/http/common/HTTPClient/HTTPClient.h @@ -0,0 +1,159 @@ +/* HTTPClient.h */ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/** \file +HTTP Client header file +*/ + +#ifndef HTTP_CLIENT_H +#define HTTP_CLIENT_H + +#include "TCPSocketConnection.h" + +#define HTTP_CLIENT_DEFAULT_TIMEOUT 15000 + +class HTTPData; + +#include "IHTTPData.h" +#include "mbed.h" + +///HTTP client results +enum HTTPResult +{ + HTTP_PROCESSING, /// + +using std::size_t; + +///This is a simple interface for HTTP data storage (impl examples are Key/Value Pairs, File, etc...) +class IHTTPDataOut +{ +protected: + friend class HTTPClient; + + /** Reset stream to its beginning + * Called by the HTTPClient on each new request + */ + virtual void readReset() = 0; + + /** Read a piece of data to be transmitted + * @param buf Pointer to the buffer on which to copy the data + * @param len Length of the buffer + * @param pReadLen Pointer to the variable on which the actual copied data length will be stored + */ + virtual int read(char* buf, size_t len, size_t* pReadLen) = 0; + + /** Get MIME type + * @param type Internet media type from Content-Type header + */ + virtual int getDataType(char* type, size_t maxTypeLen) = 0; //Internet media type for Content-Type header + + /** Determine whether the HTTP client should chunk the data + * Used for Transfer-Encoding header + */ + virtual bool getIsChunked() = 0; + + /** If the data is not chunked, get its size + * Used for Content-Length header + */ + virtual size_t getDataLen() = 0; + +}; + +///This is a simple interface for HTTP data storage (impl examples are Key/Value Pairs, File, etc...) +class IHTTPDataIn +{ +protected: + friend class HTTPClient; + + /** Reset stream to its beginning + * Called by the HTTPClient on each new request + */ + virtual void writeReset() = 0; + + /** Write a piece of data transmitted by the server + * @param buf Pointer to the buffer from which to copy the data + * @param len Length of the buffer + */ + virtual int write(const char* buf, size_t len) = 0; + + /** Set MIME type + * @param type Internet media type from Content-Type header + */ + virtual void setDataType(const char* type) = 0; + + /** Determine whether the data is chunked + * Recovered from Transfer-Encoding header + */ + virtual void setIsChunked(bool chunked) = 0; + + /** If the data is not chunked, set its size + * From Content-Length header + */ + virtual void setDataLen(size_t len) = 0; + +}; + +#endif diff --git a/features/unsupported/tests/net/cellular/http/common/HTTPClient/data/HTTPMap.cpp b/features/unsupported/tests/net/cellular/http/common/HTTPClient/data/HTTPMap.cpp new file mode 100644 index 00000000000..5eb4c52e6eb --- /dev/null +++ b/features/unsupported/tests/net/cellular/http/common/HTTPClient/data/HTTPMap.cpp @@ -0,0 +1,200 @@ +/* HTTPMap.cpp */ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#include "HTTPMap.h" + +#include + +#include + +#define OK 0 + +using std::strncpy; + +HTTPMap::HTTPMap() : m_pos(0), m_count(0) +{ + +} + +void HTTPMap::put(const char* key, const char* value) +{ + if(m_count >= HTTPMAP_TABLE_SIZE) + { + return; + } + m_keys[m_count] = key; + m_values[m_count] = value; + m_count++; +} + +void HTTPMap::clear() +{ + m_count = 0; + m_pos = 0; +} + +/*virtual*/ void HTTPMap::readReset() +{ + m_pos = 0; +} + +/*virtual*/ int HTTPMap::read(char* buf, size_t len, size_t* pReadLen) +{ + if(m_pos >= m_count) + { + *pReadLen = 0; + m_pos = 0; + return OK; + } + + //URL encode + char* out = buf; + const char* in = m_keys[m_pos]; + if( (m_pos != 0) && (out - buf < len - 1) ) + { + *out='&'; + out++; + } + + while( (*in != '\0') && (out - buf < len - 3) ) + { + if (std::isalnum(*in) || *in == '-' || *in == '_' || *in == '.' || *in == '~') + { + *out = *in; + out++; + } + else if( *in == ' ' ) + { + *out='+'; + out++; + } + else + { + char hex[] = "0123456789abcdef"; + *out='%'; + out++; + *out=hex[(*in>>4)&0xf]; + out++; + *out=hex[(*in)&0xf]; + out++; + } + in++; + } + + if( out - buf < len - 1 ) + { + *out='='; + out++; + } + + in = m_values[m_pos]; + while( (*in != '\0') && (out - buf < len - 3) ) + { + if (std::isalnum(*in) || *in == '-' || *in == '_' || *in == '.' || *in == '~') + { + *out = *in; + out++; + } + else if( *in == ' ' ) + { + *out='+'; + out++; + } + else + { + char hex[] = "0123456789abcdef"; + *out='%'; + out++; + *out=hex[(*in>>4)&0xf]; + out++; + *out=hex[(*in)&0xf]; + out++; + } + in++; + } + + *pReadLen = out - buf; + + m_pos++; + return OK; +} + +/*virtual*/ int HTTPMap::getDataType(char* type, size_t maxTypeLen) //Internet media type for Content-Type header +{ + strncpy(type, "application/x-www-form-urlencoded", maxTypeLen-1); + type[maxTypeLen-1] = '\0'; + return OK; +} + +/*virtual*/ bool HTTPMap::getIsChunked() //For Transfer-Encoding header +{ + return false; ////Data is computed one key/value pair at a time +} + +/*virtual*/ size_t HTTPMap::getDataLen() //For Content-Length header +{ + size_t count = 0; + for(size_t i = 0; i< m_count; i++) + { + //URL encode + const char* in = m_keys[i]; + if( i != 0 ) + { + count++; + } + + while( (*in != '\0') ) + { + if (std::isalnum(*in) || *in == '-' || *in == '_' || *in == '.' || *in == '~') + { + count++; + } + else if( *in == ' ' ) + { + count++; + } + else + { + count+=3; + } + in++; + } + + count ++; + + in = m_values[i]; + while( (*in != '\0') ) + { + if (std::isalnum(*in) || *in == '-' || *in == '_' || *in == '.' || *in == '~') + { + count++; + } + else if( *in == ' ' ) + { + count++; + } + else + { + count+=3; + } + in++; + } + } + return count; +} diff --git a/features/unsupported/tests/net/cellular/http/common/HTTPClient/data/HTTPMap.h b/features/unsupported/tests/net/cellular/http/common/HTTPClient/data/HTTPMap.h new file mode 100644 index 00000000000..c8433778ffb --- /dev/null +++ b/features/unsupported/tests/net/cellular/http/common/HTTPClient/data/HTTPMap.h @@ -0,0 +1,71 @@ +/* HTTPMap.h */ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + + +#ifndef HTTPMAP_H_ +#define HTTPMAP_H_ + +#include "../IHTTPData.h" + +#define HTTPMAP_TABLE_SIZE 32 + +/** Map of key/value pairs + * Used to transmit POST data using the application/x-www-form-urlencoded encoding + */ +class HTTPMap: public IHTTPDataOut +{ +public: + /** + Instantiates HTTPMap + It supports at most 32 key/values pairs + */ + HTTPMap(); + + /** Put Key/Value pair + The references to the parameters must remain valid as long as the clear() function is not called + @param key The key to use + @param value The corresponding value + */ + void put(const char* key, const char* value); + + /** Clear table + */ + void clear(); + +protected: + //IHTTPDataIn + virtual void readReset(); + + virtual int read(char* buf, size_t len, size_t* pReadLen); + + virtual int getDataType(char* type, size_t maxTypeLen); //Internet media type for Content-Type header + + virtual bool getIsChunked(); //For Transfer-Encoding header + + virtual size_t getDataLen(); //For Content-Length header + +private: + const char* m_keys[HTTPMAP_TABLE_SIZE]; + const char* m_values[HTTPMAP_TABLE_SIZE]; + + size_t m_pos; + size_t m_count; +}; + +#endif /* HTTPMAP_H_ */ diff --git a/features/unsupported/tests/net/cellular/http/common/HTTPClient/data/HTTPText.cpp b/features/unsupported/tests/net/cellular/http/common/HTTPClient/data/HTTPText.cpp new file mode 100644 index 00000000000..18cd42070fb --- /dev/null +++ b/features/unsupported/tests/net/cellular/http/common/HTTPClient/data/HTTPText.cpp @@ -0,0 +1,104 @@ +/* HTTPText.cpp */ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#include "HTTPText.h" + +#include + +#define OK 0 + +using std::memcpy; +using std::strncpy; +using std::strlen; + +#define MIN(x,y) (((x)<(y))?(x):(y)) + +HTTPText::HTTPText(char* str) : m_str(str), m_pos(0) +{ + m_size = strlen(str) + 1; +} + +HTTPText::HTTPText(char* str, size_t size) : m_str(str), m_size(size), m_pos(0) +{ + +} + +//IHTTPDataIn +/*virtual*/ void HTTPText::readReset() +{ + m_pos = 0; +} + +/*virtual*/ int HTTPText::read(char* buf, size_t len, size_t* pReadLen) +{ + *pReadLen = MIN(len, m_size - 1 - m_pos); + memcpy(buf, m_str + m_pos, *pReadLen); + m_pos += *pReadLen; + return OK; +} + +/*virtual*/ int HTTPText::getDataType(char* type, size_t maxTypeLen) //Internet media type for Content-Type header +{ + strncpy(type, "text/plain", maxTypeLen-1); + type[maxTypeLen-1] = '\0'; + return OK; +} + +/*virtual*/ bool HTTPText::getIsChunked() //For Transfer-Encoding header +{ + return false; +} + +/*virtual*/ size_t HTTPText::getDataLen() //For Content-Length header +{ + return m_size - 1; +} + +//IHTTPDataOut +/*virtual*/ void HTTPText::writeReset() +{ + m_pos = 0; +} + +/*virtual*/ int HTTPText::write(const char* buf, size_t len) +{ + size_t writeLen = MIN(len, m_size - 1 - m_pos); + memcpy(m_str + m_pos, buf, writeLen); + m_pos += writeLen; + m_str[m_pos] = '\0'; + return OK; +} + +/*virtual*/ void HTTPText::setDataType(const char* type) //Internet media type from Content-Type header +{ + +} + +/*virtual*/ void HTTPText::setIsChunked(bool chunked) //From Transfer-Encoding header +{ + +} + +/*virtual*/ void HTTPText::setDataLen(size_t len) //From Content-Length header, or if the transfer is chunked, next chunk length +{ + +} + + + diff --git a/features/unsupported/tests/net/cellular/http/common/HTTPClient/data/HTTPText.h b/features/unsupported/tests/net/cellular/http/common/HTTPClient/data/HTTPText.h new file mode 100644 index 00000000000..cb76c6fdac2 --- /dev/null +++ b/features/unsupported/tests/net/cellular/http/common/HTTPClient/data/HTTPText.h @@ -0,0 +1,72 @@ +/* HTTPText.h */ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + + +#ifndef HTTPTEXT_H_ +#define HTTPTEXT_H_ + +#include "../IHTTPData.h" + +/** A data endpoint to store text +*/ +class HTTPText : public IHTTPDataIn, public IHTTPDataOut +{ +public: + /** Create an HTTPText instance for output + * @param str String to be transmitted + */ + HTTPText(char* str); + + /** Create an HTTPText instance for input + * @param str Buffer to store the incoming string + * @param size Size of the buffer + */ + HTTPText(char* str, size_t size); + +protected: + //IHTTPDataIn + virtual void readReset(); + + virtual int read(char* buf, size_t len, size_t* pReadLen); + + virtual int getDataType(char* type, size_t maxTypeLen); //Internet media type for Content-Type header + + virtual bool getIsChunked(); //For Transfer-Encoding header + + virtual size_t getDataLen(); //For Content-Length header + + //IHTTPDataOut + virtual void writeReset(); + + virtual int write(const char* buf, size_t len); + + virtual void setDataType(const char* type); //Internet media type from Content-Type header + + virtual void setIsChunked(bool chunked); //From Transfer-Encoding header + + virtual void setDataLen(size_t len); //From Content-Length header, or if the transfer is chunked, next chunk length + +private: + char* m_str; + size_t m_size; + + size_t m_pos; +}; + +#endif /* HTTPTEXT_H_ */ diff --git a/features/unsupported/tests/net/cellular/http/common/httptest.cpp b/features/unsupported/tests/net/cellular/http/common/httptest.cpp new file mode 100644 index 00000000000..e3db1c826af --- /dev/null +++ b/features/unsupported/tests/net/cellular/http/common/httptest.cpp @@ -0,0 +1,58 @@ +#include "mbed.h" +#include "CellularModem.h" +#include "HTTPClient.h" +#include "httptest.h" + +int httptest(CellularModem& modem, const char* apn, const char* username, const char* password) +{ + printf("Connecting...\n"); + + HTTPClient http; + char str[512]; + + modem.power(true); + Thread::wait(1000); + int ret = modem.connect(apn, username, password); + if(ret) + { + printf("Could not connect\n"); + return false; + } + + //GET data + printf("Trying to fetch page...\n"); + ret = http.get("http://mbed.org/media/uploads/donatien/hello.txt", str, 128); + if (!ret) + { + printf("Page fetched successfully - read %d characters\n", strlen(str)); + printf("Result: %s\n", str); + } + else + { + printf("Error - ret = %d - HTTP return code = %d\n", ret, http.getHTTPResponseCode()); + modem.disconnect(); + return false; + } + + //POST data + HTTPMap map; + HTTPText text(str, 512); + map.put("Hello", "World"); + map.put("test", "1234"); + printf("Trying to post data...\n"); + ret = http.post("http://httpbin.org/post", map, &text); + if (!ret) + { + printf("Executed POST successfully - read %d characters\n", strlen(str)); + printf("Result: %s\n", str); + } + else + { + printf("Error - ret = %d - HTTP return code = %d\n", ret, http.getHTTPResponseCode()); + modem.disconnect(); + return false; + } + + modem.disconnect(); + return true; +} diff --git a/features/unsupported/tests/net/cellular/http/common/httptest.h b/features/unsupported/tests/net/cellular/http/common/httptest.h new file mode 100644 index 00000000000..affd6d23bee --- /dev/null +++ b/features/unsupported/tests/net/cellular/http/common/httptest.h @@ -0,0 +1,9 @@ +#ifndef HTTPTEST_H_ +#define HTTPTEST_H_ + +#include "CellularModem.h" + +int httptest(CellularModem& modem, const char* apn = NULL, const char* username = NULL, const char* password= NULL); + +#endif + diff --git a/features/unsupported/tests/net/cellular/http/ubloxusb/main.cpp b/features/unsupported/tests/net/cellular/http/ubloxusb/main.cpp new file mode 100644 index 00000000000..3454114579e --- /dev/null +++ b/features/unsupported/tests/net/cellular/http/ubloxusb/main.cpp @@ -0,0 +1,35 @@ +#include "UbloxUSBGSMModem.h" +#include "UbloxUSBCDMAModem.h" +#include "httptest.h" + +#if !defined(MODEM_UBLOX_GSM) && !defined(MODEM_UBLOX_CDMA) +#warning No modem defined, using GSM by default +#define MODEM_UBLOX_GSM +#endif + +#ifndef MODEM_APN +#warning APN not specified, using "internet" +#define MODEM_APN "internet" +#endif + +#ifndef MODEM_USERNAME +#warning username not specified +#define MODEM_USERNAME NULL +#endif + +#ifndef MODEM_PASSWORD +#warning password not specified +#define MODEM_PASSWORD NULL +#endif + +int main() +{ +#ifdef MODEM_UBLOX_GSM + UbloxUSBGSMModem modem; +#else + UbloxUSBCDMAModem modem(p18, true, 1); +#endif + httptest(modem, MODEM_APN, MODEM_USERNAME, MODEM_PASSWORD); + while (true); +} + diff --git a/features/unsupported/tests/net/cellular/sms/common/smstest.cpp b/features/unsupported/tests/net/cellular/sms/common/smstest.cpp new file mode 100644 index 00000000000..5a6393590f8 --- /dev/null +++ b/features/unsupported/tests/net/cellular/sms/common/smstest.cpp @@ -0,0 +1,41 @@ +#include "CellularModem.h" +#include "smstest.h" + +void smstest(CellularModem& modem) +{ + modem.power(true); + Thread::wait(1000); + +#ifdef DESTINATION_NUMBER + modem.sendSM(DESINATION_NUMBER, "Hello from mbed:)"); +#endif + + while(true) + { + char num[17]; + char msg[64]; + size_t count; + int ret = modem.getSMCount(&count); + if(ret) + { + printf("getSMCount returned %d\n", ret); + Thread::wait(3000); + continue; + } + if( count > 0) + { + printf("%d SMS to read\n", count); + ret = modem.getSM(num, msg, 64); + if(ret) + { + printf("getSM returned %d\n", ret); + Thread::wait(3000); + continue; + } + + printf("%s : %s\n", num, msg); + } + Thread::wait(3000); + } +} + diff --git a/features/unsupported/tests/net/cellular/sms/common/smstest.h b/features/unsupported/tests/net/cellular/sms/common/smstest.h new file mode 100644 index 00000000000..0d1ea80fc7d --- /dev/null +++ b/features/unsupported/tests/net/cellular/sms/common/smstest.h @@ -0,0 +1,9 @@ +#ifndef SMSTEST_H_ +#define SMSTEST_H_ + +#include "CellularModem.h" + +void smstest(CellularModem&); + +#endif + diff --git a/features/unsupported/tests/net/cellular/sms/ubloxusb/main.cpp b/features/unsupported/tests/net/cellular/sms/ubloxusb/main.cpp new file mode 100644 index 00000000000..a493be7bfe2 --- /dev/null +++ b/features/unsupported/tests/net/cellular/sms/ubloxusb/main.cpp @@ -0,0 +1,21 @@ +#include "UbloxUSBGSMModem.h" +#include "UbloxUSBCDMAModem.h" +#include "smstest.h" + +#if !defined(MODEM_UBLOX_GSM) && !defined(MODEM_UBLOX_CDMA) +#warning No modem defined, using GSM by default +#define MODEM_UBLOX_GSM +#endif + +int main() +{ +#ifdef MODEM_UBLOX_GSM + UbloxUSBGSMModem modem; +#else + UbloxUSBCDMAModem modem(p18, true, 1); +#endif + + smstest(modem); + while (true); +} + diff --git a/features/unsupported/tests/net/echo/tcp_client/main.cpp b/features/unsupported/tests/net/echo/tcp_client/main.cpp new file mode 100644 index 00000000000..17193f08d0f --- /dev/null +++ b/features/unsupported/tests/net/echo/tcp_client/main.cpp @@ -0,0 +1,59 @@ +#include "mbed.h" +#include "test_env.h" +#include "EthernetInterface.h" + +struct s_ip_address { + int ip_1; + int ip_2; + int ip_3; + int ip_4; +}; + +int main() { + MBED_HOSTTEST_TIMEOUT(20); + MBED_HOSTTEST_SELECT(tcpecho_client_auto); + MBED_HOSTTEST_DESCRIPTION(TCP echo client); + MBED_HOSTTEST_START("NET_4"); + + char buffer[256] = {0}; + char out_buffer[] = "Hello World\n"; + char out_success[] = "{{success}}\n{{end}}\n"; + char out_failure[] = "{{failure}}\n{{end}}\n"; + s_ip_address ip_addr = {0, 0, 0, 0}; + int port = 0; + + printf("TCPCllient waiting for server IP and port..." NL); + scanf("%d.%d.%d.%d:%d", &ip_addr.ip_1, &ip_addr.ip_2, &ip_addr.ip_3, &ip_addr.ip_4, &port); + printf("Address received:%d.%d.%d.%d:%d" NL, ip_addr.ip_1, ip_addr.ip_2, ip_addr.ip_3, ip_addr.ip_4, port); + + EthernetInterface eth; + eth.init(); //Use DHCP + eth.connect(); + + printf("TCPClient IP Address is %s" NL, eth.getIPAddress()); + sprintf(buffer, "%d.%d.%d.%d", ip_addr.ip_1, ip_addr.ip_2, ip_addr.ip_3, ip_addr.ip_4); + + TCPSocketConnection socket; + while (socket.connect(buffer, port) < 0) { + printf("TCPCllient unable to connect to %s:%d" NL, buffer, port); + wait(1); + } + + socket.send_all(out_buffer, sizeof(out_buffer) - 1); + + int n = socket.receive(buffer, sizeof(buffer)); + if (n > 0) + { + buffer[n] = '\0'; + printf("%s", buffer); + if (strncmp(out_buffer, buffer, sizeof(out_buffer) - 1) == 0) { + socket.send_all(out_success, sizeof(out_success) - 1); + } + } + + socket.send_all(out_failure, sizeof(out_failure) - 1); + + socket.close(); + eth.disconnect(); + return 0; +} diff --git a/features/unsupported/tests/net/echo/tcp_client_loop/main.cpp b/features/unsupported/tests/net/echo/tcp_client_loop/main.cpp new file mode 100644 index 00000000000..6c797e74439 --- /dev/null +++ b/features/unsupported/tests/net/echo/tcp_client_loop/main.cpp @@ -0,0 +1,78 @@ +#include "mbed.h" +#include "test_env.h" +#include "EthernetInterface.h" +#include + +namespace { + const int BUFFER_SIZE = 64; + const int MAX_ECHO_LOOPS = 1000; + const char ASCII_MAX = '~' - ' '; + + struct s_ip_address + { + int ip_1; + int ip_2; + int ip_3; + int ip_4; + }; +} + +char char_rand() { + return (rand() % ASCII_MAX) + ' '; +} + +int main() { + MBED_HOSTTEST_TIMEOUT(20); + MBED_HOSTTEST_SELECT(tcpecho_client_auto); + MBED_HOSTTEST_DESCRIPTION(TCP client echo loop); + MBED_HOSTTEST_START("NET_13"); + + char buffer[BUFFER_SIZE] = {0}; + char out_buffer[BUFFER_SIZE] = {0}; + s_ip_address ip_addr = {0, 0, 0, 0}; + int port = 0; + + printf("MBED: TCPCllient waiting for server IP and port...\r\n"); + scanf("%d.%d.%d.%d:%d", &ip_addr.ip_1, &ip_addr.ip_2, &ip_addr.ip_3, &ip_addr.ip_4, &port); + printf("MBED: Address received: %d.%d.%d.%d:%d\r\n", ip_addr.ip_1, ip_addr.ip_2, ip_addr.ip_3, ip_addr.ip_4, port); + + EthernetInterface eth; + eth.init(); //Use DHCP + eth.connect(); + + printf("MBED: TCPClient IP Address is %s\r\n", eth.getIPAddress()); + sprintf(buffer, "%d.%d.%d.%d", ip_addr.ip_1, ip_addr.ip_2, ip_addr.ip_3, ip_addr.ip_4); + + TCPSocketConnection socket; + while (socket.connect(buffer, port) < 0) { + printf("MBED: TCPCllient unable to connect to %s:%d\r\n", buffer, port); + wait(1); + } + + // Test loop for multiple client connections + bool result = true; + int count_error = 0; + for (int i = 0; i < MAX_ECHO_LOOPS; i++) { + std::generate(out_buffer, out_buffer + BUFFER_SIZE, char_rand); + socket.send_all(out_buffer, BUFFER_SIZE); + + int n = socket.receive(buffer, BUFFER_SIZE); + if (n > 0) + { + bool echoed = memcmp(out_buffer, buffer, BUFFER_SIZE) == 0; + result = result && echoed; + if (echoed == false) { + count_error++; // Count error messages + } + } + } + + printf("MBED: Loop messages passed: %d / %d\r\n", MAX_ECHO_LOOPS - count_error, MAX_ECHO_LOOPS); + + if (notify_completion_str(result, buffer)) { + socket.send_all(buffer, strlen(buffer)); + } + socket.close(); + eth.disconnect(); + MBED_HOSTTEST_RESULT(result); +} diff --git a/features/unsupported/tests/net/echo/tcp_server/main.cpp b/features/unsupported/tests/net/echo/tcp_server/main.cpp new file mode 100644 index 00000000000..421fb0dbecd --- /dev/null +++ b/features/unsupported/tests/net/echo/tcp_server/main.cpp @@ -0,0 +1,47 @@ +#include "mbed.h" +#include "test_env.h" +#include "EthernetInterface.h" + +namespace { + const int ECHO_SERVER_PORT = 7; + const int BUFFER_SIZE = 64; +} + +int main (void) { + MBED_HOSTTEST_TIMEOUT(20); + MBED_HOSTTEST_SELECT(tcpecho_server_auto); + MBED_HOSTTEST_DESCRIPTION(TCP echo server); + MBED_HOSTTEST_START("NET_3"); + + char buffer[BUFFER_SIZE] = {0}; + EthernetInterface eth; + eth.init(); //Use DHCP + eth.connect(); + printf("MBED: Server IP Address is %s:%d" NL, eth.getIPAddress(), ECHO_SERVER_PORT); + + TCPSocketServer server; + server.bind(ECHO_SERVER_PORT); + server.listen(); + + while (true) { + printf("MBED: Wait for new connection..." NL); + TCPSocketConnection client; + server.accept(client); + client.set_blocking(false, 1500); // Timeout after (1.5)s + printf("MBED: Connection from: %s" NL, client.get_address()); + + while (true) { + const int n = client.receive(buffer, sizeof(buffer)); + if (n <= 0) { + break; + } + const int buffer_string_end_index = n >= BUFFER_SIZE ? BUFFER_SIZE-1 : n; + buffer[buffer_string_end_index] = '\0'; + client.send_all(buffer, n); + if (n <= 0) { + break; + } + } + client.close(); + } +} diff --git a/features/unsupported/tests/net/echo/udp_client/main.cpp b/features/unsupported/tests/net/echo/udp_client/main.cpp new file mode 100644 index 00000000000..97f60505086 --- /dev/null +++ b/features/unsupported/tests/net/echo/udp_client/main.cpp @@ -0,0 +1,82 @@ +#include "mbed.h" +#include "rtos.h" +#include "test_env.h" +#include "EthernetInterface.h" +#include + +#define CHECK(RC, STEP) if (RC < 0) error(STEP": %d\r\n", RC) + +namespace { + const int BUFFER_SIZE = 64; + const int MAX_ECHO_LOOPS = 100; + const char ASCII_MAX = '~' - ' '; + + struct s_ip_address { + int ip_1; + int ip_2; + int ip_3; + int ip_4; + }; +} + +char char_rand() { + return (rand() % ASCII_MAX) + ' '; +} + +int main() { + MBED_HOSTTEST_TIMEOUT(20); + MBED_HOSTTEST_SELECT(udpecho_client_auto); + MBED_HOSTTEST_DESCRIPTION(UDP echo client); + MBED_HOSTTEST_START("NET_6"); + + char buffer[BUFFER_SIZE] = {0}; + char out_buffer[BUFFER_SIZE] = {0}; + s_ip_address ip_addr = {0, 0, 0, 0}; + int port = 0; + bool result = true; + + printf("MBED: UDPCllient waiting for server IP and port...\r\n"); + scanf("%d.%d.%d.%d:%d", &ip_addr.ip_1, &ip_addr.ip_2, &ip_addr.ip_3, &ip_addr.ip_4, &port); + printf("MBED: Address received: %d.%d.%d.%d:%d\r\n", ip_addr.ip_1, ip_addr.ip_2, ip_addr.ip_3, ip_addr.ip_4, port); + + EthernetInterface eth; + int rc = eth.init(); //Use DHCP + CHECK(rc, "eth init"); + + rc = eth.connect(); + CHECK(rc, "connect"); + printf("IP: %s\n", eth.getIPAddress()); + + UDPSocket socket; + rc = socket.init(); + CHECK(rc, "socket init"); + + printf("MBED: UDPClient IP Address is %s\r\n", eth.getIPAddress()); + sprintf(buffer, "%d.%d.%d.%d", ip_addr.ip_1, ip_addr.ip_2, ip_addr.ip_3, ip_addr.ip_4); + + Endpoint echo_server; + rc = echo_server.set_address(buffer, port); + CHECK(rc, "set_address"); + + for (int i =0; i < MAX_ECHO_LOOPS; i++) { + std::generate(out_buffer, out_buffer + BUFFER_SIZE, char_rand); + rc = socket.sendTo(echo_server, out_buffer, sizeof(out_buffer)); + CHECK(rc, "sendTo"); + + const int n = socket.receiveFrom(echo_server, buffer, sizeof(buffer)); + CHECK(n, "receiveFrom"); + + if (memcmp(buffer, out_buffer, BUFFER_SIZE) != 0) { + result = false; + break; + } + } + + if (notify_completion_str(result, buffer)) { + socket.sendTo(echo_server, buffer, strlen(buffer)); + } + + socket.close(); + eth.disconnect(); + MBED_HOSTTEST_RESULT(result); +} diff --git a/features/unsupported/tests/net/echo/udp_link_layer/main.cpp b/features/unsupported/tests/net/echo/udp_link_layer/main.cpp new file mode 100644 index 00000000000..3e40499dfab --- /dev/null +++ b/features/unsupported/tests/net/echo/udp_link_layer/main.cpp @@ -0,0 +1,151 @@ +#include "mbed.h" +#include "rtos.h" +#include "EthernetInterface.h" +#include +#include + +/** +* How to use: +* make.py -m LPC1768 -t ARM -d E:\ -n NET_14 +* udp_link_layer_auto.py -p COM20 -d E:\ -t 10 +*/ + +// Evil globals +namespace { + // IP and port used to store HOST address info + char host_address[32] = {0}; + volatile int host_port = 0; + + const int ECHO_SERVER_PORT = 7; + const int BUFFER_SIZE = 64; + + // Forwarding packet queue + std::list datagram_queue; + + // Statistics (mbed) + volatile int received_packets = 0; + volatile int forwarded_packets = 0; + volatile int max_queue_len = 0; + + Mutex cli_serv_mutex; + // cli_serv_mutex.lock(); // LOCK + // cli_serv_mutex.unlock(); // LOCK +} + +void udp_server_task(void const *argument) +{ + DigitalOut indicator(LED1); + UDPSocket server; + + server.bind(ECHO_SERVER_PORT); + // printf("[udp_server_task] Start\r\n"); + + Endpoint client; + char buffer[BUFFER_SIZE] = { 0 }; + while (true) { + //printf("[udp_server_task] Wait for packet...\r\n"); + int n = server.receiveFrom(client, buffer, sizeof(buffer)); + if (n > 0) { + //printf("[udp_server_task] Received packet from: %s\r\n", client.get_address()); + const int buffer_string_end_index = n >= BUFFER_SIZE ? BUFFER_SIZE - 1 : n; + buffer[buffer_string_end_index] = '\0'; + //printf("[udp_server_task] Server received: %s\r\n", buffer); + if (host_port == 0) { + strcpy(host_address, client.get_address()); + host_port = ECHO_SERVER_PORT + 1; + //printf("[udp_server_task] Set host address and port: %s:%d\r\n", host_address, host_port); + } + // Dispatch data to client for sending to test HOST + cli_serv_mutex.lock(); // LOCK + // Push to datagram queue + datagram_queue.push_front(std::string(buffer)); + max_queue_len = datagram_queue.size() > max_queue_len ? datagram_queue.size() : max_queue_len; + received_packets++; + cli_serv_mutex.unlock(); // LOCK + indicator = !indicator; + } + } +} + +void udp_client_task(void const *argument) +{ + while (host_port == 0) { + // Waiting for HOST port notification + } + + DigitalOut indicator(LED2); + UDPSocket socket; + socket.init(); + + Endpoint echo_server; + echo_server.set_address(host_address, host_port); + //printf("[udp_client_task] Start: %s:%d\r\n", host_address, host_port); + + while (1) { + std::string datagram; + bool sent_datagram = false; + cli_serv_mutex.lock(); // LOCK + if (datagram_queue.size() > 0) { + // POP from datagram queue + datagram = datagram_queue.back(); + datagram_queue.pop_back(); + sent_datagram = true; + } + cli_serv_mutex.unlock(); // LOCK + if (sent_datagram) { + //printf("[udp_client_task] Forwarded datagram: %s\r\n", datagram.c_str()); + socket.sendTo(echo_server, (char *)datagram.c_str(), datagram.length()); + forwarded_packets++; + indicator = !indicator; + } + } +} + +int main(void) +{ + EthernetInterface eth; + + eth.init(); //Use DHCP + eth.connect(); + printf("MBED: Server IP Address is %s:%d\r\n", eth.getIPAddress(), ECHO_SERVER_PORT); + + Thread UdpServerTask(udp_server_task, NULL, osPriorityNormal, DEFAULT_STACK_SIZE * 2.25); + Thread UdpClientTask(udp_client_task, NULL, osPriorityNormal, DEFAULT_STACK_SIZE * 2.25); + + // Control TCP server to get MBED statistics + { + char buffer[BUFFER_SIZE] = {0}; + const int TELNET_SERVER_PORT = 23; + const int BUFFER_SIZE = 256; + TCPSocketServer server; + server.bind(TELNET_SERVER_PORT); + server.listen(); + + while (true) { + printf("MBED: Wait for new connection...\r\n"); + TCPSocketConnection client; + server.accept(client); + client.set_blocking(false, 1500); // Timeout after (1.5)s + printf("MBED: Connection from: %s\r\n", client.get_address()); + + while (true) { + int n = client.receive(buffer, sizeof(buffer)); + //if (n <= 0) break; + if (n > 0) { + // printf("Recv %d chars\r\n", n); + const int buffer_string_end_index = n >= BUFFER_SIZE ? BUFFER_SIZE - 1 : n; + buffer[buffer_string_end_index] = '\0'; + // client.send_all(buffer, strlen(buffer)); + if (strncmp(buffer, "stat", 4) == 0) { + sprintf(buffer, "received_packets %d\nforwarded_packets %d\nmax_queue_len %d", + received_packets, forwarded_packets, max_queue_len); + client.send_all(buffer, strlen(buffer)); + // printf("%s", buffer); + } + } + //if (n <= 0) break; + } + client.close(); + } + } +} diff --git a/features/unsupported/tests/net/echo/udp_server/main.cpp b/features/unsupported/tests/net/echo/udp_server/main.cpp new file mode 100644 index 00000000000..ea90ff7d4a7 --- /dev/null +++ b/features/unsupported/tests/net/echo/udp_server/main.cpp @@ -0,0 +1,37 @@ +#include "mbed.h" +#include "test_env.h" +#include "EthernetInterface.h" + +namespace { + const int ECHO_SERVER_PORT = 7; + const int BUFFER_SIZE = 64; +} + +int main (void) { + MBED_HOSTTEST_TIMEOUT(20); + MBED_HOSTTEST_SELECT(udpecho_server_auto); + MBED_HOSTTEST_DESCRIPTION(UDP echo server); + MBED_HOSTTEST_START("NET_5"); + + EthernetInterface eth; + eth.init(); //Use DHCP + eth.connect(); + printf("MBED: Server IP Address is %s:%d\r\n", eth.getIPAddress(), ECHO_SERVER_PORT); + + UDPSocket server; + server.bind(ECHO_SERVER_PORT); + + Endpoint client; + char buffer[BUFFER_SIZE] = {0}; + printf("MBED: Waiting for packet...\r\n"); + while (true) { + int n = server.receiveFrom(client, buffer, sizeof(buffer)); + if (n > 0) { + //printf("Received packet from: %s\n", client.get_address()); + const int buffer_string_end_index = n >= BUFFER_SIZE ? BUFFER_SIZE-1 : n; + buffer[buffer_string_end_index] = '\0'; + //printf("Server received: %s\n", buffer); + server.sendTo(client, buffer, n); + } + } +} diff --git a/features/unsupported/tests/net/helloworld/broadcast_receive/main.cpp b/features/unsupported/tests/net/helloworld/broadcast_receive/main.cpp new file mode 100644 index 00000000000..9cee345519a --- /dev/null +++ b/features/unsupported/tests/net/helloworld/broadcast_receive/main.cpp @@ -0,0 +1,23 @@ +#include "mbed.h" +#include "EthernetInterface.h" + +const int BROADCAST_PORT = 58083; + +int main() { + EthernetInterface eth; + eth.init(); //Use DHCP + eth.connect(); + + UDPSocket socket; + socket.bind(BROADCAST_PORT); + socket.set_broadcasting(); + + Endpoint broadcaster; + char buffer[256]; + while (true) { + printf("\nWait for packet...\n"); + int n = socket.receiveFrom(broadcaster, buffer, sizeof(buffer)); + buffer[n] = '\0'; + printf("Packet from \"%s\": %s\n", broadcaster.get_address(), buffer); + } +} diff --git a/features/unsupported/tests/net/helloworld/broadcast_send/main.cpp b/features/unsupported/tests/net/helloworld/broadcast_send/main.cpp new file mode 100644 index 00000000000..4632c63ff02 --- /dev/null +++ b/features/unsupported/tests/net/helloworld/broadcast_send/main.cpp @@ -0,0 +1,25 @@ +#include "mbed.h" +#include "EthernetInterface.h" + +const int BROADCAST_PORT = 58083; + +int main() { + EthernetInterface eth; + eth.init(); //Use DHCP + eth.connect(); + + UDPSocket sock; + sock.init(); + sock.set_broadcasting(); + + Endpoint broadcast; + broadcast.set_address("255.255.255.255", BROADCAST_PORT); + + char out_buffer[] = "very important data"; + + while (true) { + printf("Broadcasting...\n"); + sock.sendTo(broadcast, out_buffer, sizeof(out_buffer)); + Thread::wait(1000); + } +} diff --git a/features/unsupported/tests/net/helloworld/multicast_receive/main.cpp b/features/unsupported/tests/net/helloworld/multicast_receive/main.cpp new file mode 100644 index 00000000000..0398bdd1fdb --- /dev/null +++ b/features/unsupported/tests/net/helloworld/multicast_receive/main.cpp @@ -0,0 +1,27 @@ +#include "mbed.h" +#include "EthernetInterface.h" + +const char* MCAST_GRP = "224.1.1.1"; +const int MCAST_PORT = 5007; + +int main() { + EthernetInterface eth; + eth.init(); //Use DHCP + eth.connect(); + + UDPSocket server; + server.bind(MCAST_PORT); + if (server.join_multicast_group(MCAST_GRP) != 0) { + printf("Error joining the multicast group\n"); + while (true) {} + } + + Endpoint client; + char buffer[256]; + while (true) { + printf("\nWait for packet...\n"); + int n = server.receiveFrom(client, buffer, sizeof(buffer)); + + printf("Packet from \"%s\": %s\n", client.get_address(), buffer); + } +} diff --git a/features/unsupported/tests/net/helloworld/multicast_send/main.cpp b/features/unsupported/tests/net/helloworld/multicast_send/main.cpp new file mode 100644 index 00000000000..df41c6d80a5 --- /dev/null +++ b/features/unsupported/tests/net/helloworld/multicast_send/main.cpp @@ -0,0 +1,24 @@ +#include "mbed.h" +#include "EthernetInterface.h" + +const char* MCAST_GRP = "224.1.1.1"; +const int MCAST_PORT = 5007; + +int main() { + EthernetInterface eth; + eth.init(); //Use DHCP + eth.connect(); + + UDPSocket sock; + sock.init(); + + Endpoint multicast_group; + multicast_group.set_address(MCAST_GRP, MCAST_PORT); + + char out_buffer[] = "very important data"; + while (true) { + printf("Multicast to group: %s\n", MCAST_GRP); + sock.sendTo(multicast_group, out_buffer, sizeof(out_buffer)); + Thread::wait(1000); + } +} diff --git a/features/unsupported/tests/net/helloworld/tcpclient/main.cpp b/features/unsupported/tests/net/helloworld/tcpclient/main.cpp new file mode 100644 index 00000000000..667041dcc77 --- /dev/null +++ b/features/unsupported/tests/net/helloworld/tcpclient/main.cpp @@ -0,0 +1,88 @@ +#include +#include "mbed.h" +#include "EthernetInterface.h" +#include "test_env.h" + +namespace { + // Test connection information + const char *HTTP_SERVER_NAME = "developer.mbed.org"; + const char *HTTP_SERVER_FILE_PATH = "/media/uploads/mbed_official/hello.txt"; + const int HTTP_SERVER_PORT = 80; +#if defined(TARGET_VK_RZ_A1H) + const int RECV_BUFFER_SIZE = 300; +#else + const int RECV_BUFFER_SIZE = 512; +#endif + // Test related data + const char *HTTP_OK_STR = "200 OK"; + const char *HTTP_HELLO_STR = "Hello world!"; + + // Test buffers + char buffer[RECV_BUFFER_SIZE] = {0}; +} + +bool find_substring(const char *first, const char *last, const char *s_first, const char *s_last) { + const char *f = std::search(first, last, s_first, s_last); + return (f != last); +} + +int main() { + MBED_HOSTTEST_TIMEOUT(20); + MBED_HOSTTEST_SELECT(default_auto); + MBED_HOSTTEST_DESCRIPTION(TCP client hello world); + MBED_HOSTTEST_START("NET_1"); + + bool result = false; + EthernetInterface eth; + eth.init(); //Use DHCP + eth.connect(); + printf("TCP client IP Address is %s\r\n", eth.getIPAddress()); + + TCPSocketConnection sock; + if (sock.connect(HTTP_SERVER_NAME, HTTP_SERVER_PORT) == 0) { + printf("HTTP: Connected to %s:%d\r\n", HTTP_SERVER_NAME, HTTP_SERVER_PORT); + + // We are constructing GET command like this: + // GET http://developer.mbed.org/media/uploads/mbed_official/hello.txt HTTP/1.0\n\n + strcpy(buffer, "GET http://"); + strcat(buffer, HTTP_SERVER_NAME); + strcat(buffer, HTTP_SERVER_FILE_PATH); + strcat(buffer, " HTTP/1.0\n\n"); + // Send GET command + sock.send_all(buffer, strlen(buffer)); + + // Server will respond with HTTP GET's success code + bool found_200_ok = false; + { + const int ret = sock.receive(buffer, sizeof(buffer) - 1); + buffer[ret] = '\0'; + // Find 200 OK HTTP status in reply + found_200_ok = find_substring(buffer, buffer + ret, HTTP_OK_STR, HTTP_OK_STR + strlen(HTTP_OK_STR)); + printf("HTTP: Received %d chars from server\r\n", ret); + printf("HTTP: Received 200 OK status ... %s\r\n", found_200_ok ? "[OK]" : "[FAIL]"); + printf("HTTP: Received massage:\r\n\r\n"); + printf("%s", buffer); + } + + // Server will respond with requested file content + bool found_hello = false; + { + const int ret = sock.receive(buffer, sizeof(buffer) - 1); + buffer[ret] = '\0'; + // Find Hello World! in reply + found_hello = find_substring(buffer, buffer + ret, HTTP_HELLO_STR, HTTP_HELLO_STR + strlen(HTTP_HELLO_STR)); + printf("HTTP: Received %d chars from server\r\n", ret); + printf("HTTP: Received '%s' status ... %s\r\n", HTTP_HELLO_STR, found_hello ? "[OK]" : "[FAIL]"); + printf("HTTP: Received massage:\r\n\r\n"); + printf("%s", buffer); + } + + if (found_200_ok && found_hello) { + result = true; + } + } + + sock.close(); + eth.disconnect(); + MBED_HOSTTEST_RESULT(result); +} \ No newline at end of file diff --git a/features/unsupported/tests/net/helloworld/udpclient/main.cpp b/features/unsupported/tests/net/helloworld/udpclient/main.cpp new file mode 100644 index 00000000000..59dad6db6ff --- /dev/null +++ b/features/unsupported/tests/net/helloworld/udpclient/main.cpp @@ -0,0 +1,56 @@ +#include "mbed.h" +#include "EthernetInterface.h" +#include "test_env.h" + +namespace { + const char *HTTP_SERVER_NAME = "utcnist.colorado.edu"; + const int HTTP_SERVER_PORT = 37; + const float YEARS_TO_PASS = 114.0; +} + + +int main() { + MBED_HOSTTEST_TIMEOUT(20); + MBED_HOSTTEST_SELECT(default_auto); + MBED_HOSTTEST_DESCRIPTION(NIST Internet Time Service); + MBED_HOSTTEST_START("NET_2"); + + bool result = false; + EthernetInterface eth; + eth.init(); //Use DHCP + eth.connect(); + printf("UDP client IP Address is %s\n", eth.getIPAddress()); + + UDPSocket sock; + sock.init(); + + Endpoint nist; + nist.set_address(HTTP_SERVER_NAME, HTTP_SERVER_PORT); + + char out_buffer[] = "plop"; // Does not matter + sock.sendTo(nist, out_buffer, sizeof(out_buffer)); + + union { + char in_buffer_tab[4]; + unsigned int in_buffer_uint; + }; + + const int n = sock.receiveFrom(nist, in_buffer_tab, sizeof(in_buffer_tab)); + if (n > 0) { + result = true; + const unsigned int timeRes = ntohl(in_buffer_uint); + const float years = timeRes / 60.0 / 60.0 / 24.0 / 365.0; + const float days = timeRes / 24.0 / 60.0 / 60.0; + printf("UDP: Received %d bytes from server %s on port %d\r\n", n, nist.get_address(), nist.get_port()); + printf("UDP: %u seconds since 01/01/1900 00:00 GMT ... %s\r\n", timeRes, timeRes > 0 ? "[OK]" : "[FAIL]"); + printf("UDP: %.2f days since 01/01/1900 00:00 GMT ... %s\r\n", days, timeRes > 0 ? "[OK]" : "[FAIL]"); + printf("UDP: %.2f years since 01/01/1900 00:00 GMT ... %s\r\n", years, timeRes > YEARS_TO_PASS ? "[OK]" : "[FAIL]"); + + if (years < YEARS_TO_PASS) { + result = false; + } + } + sock.close(); + eth.disconnect(); + MBED_HOSTTEST_RESULT(result); +} diff --git a/features/unsupported/tests/net/protocols/HTTPClient_HelloWorld/HTTPClient/HTTPClient.cpp b/features/unsupported/tests/net/protocols/HTTPClient_HelloWorld/HTTPClient/HTTPClient.cpp new file mode 100644 index 00000000000..263c928949e --- /dev/null +++ b/features/unsupported/tests/net/protocols/HTTPClient_HelloWorld/HTTPClient/HTTPClient.cpp @@ -0,0 +1,621 @@ +/* HTTPClient.cpp */ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +//Debug is disabled by default +#if 1 +//Enable debug +#include +//#define DBG(x, ...) std::printf("[HTTPClient : DBG]"x"\r\n", ##__VA_ARGS__); +#define DBG(x, ...) +#define WARN(x, ...) std::printf("[HTTPClient : WARN]"x"\r\n", ##__VA_ARGS__); +#define ERR(x, ...) std::printf("[HTTPClient : ERR]"x"\r\n", ##__VA_ARGS__); + +#else +//Disable debug +#define DBG(x, ...) +#define WARN(x, ...) +#define ERR(x, ...) + +#endif + +#define HTTP_PORT 80 + +#define OK 0 + +#define MIN(x,y) (((x)<(y))?(x):(y)) +#define MAX(x,y) (((x)>(y))?(x):(y)) + +#define CHUNK_SIZE 256 + +#include + +#include "HTTPClient.h" + +HTTPClient::HTTPClient() : +m_sock(), m_basicAuthUser(NULL), m_basicAuthPassword(NULL), m_httpResponseCode(0) +{ + +} + +HTTPClient::~HTTPClient() +{ + +} + +#if 0 +void HTTPClient::basicAuth(const char* user, const char* password) //Basic Authentification +{ + m_basicAuthUser = user; + m_basicAuthPassword = password; +} +#endif + +HTTPResult HTTPClient::get(const char* url, IHTTPDataIn* pDataIn, int timeout /*= HTTP_CLIENT_DEFAULT_TIMEOUT*/) //Blocking +{ + return connect(url, HTTP_GET, NULL, pDataIn, timeout); +} + +HTTPResult HTTPClient::get(const char* url, char* result, size_t maxResultLen, int timeout /*= HTTP_CLIENT_DEFAULT_TIMEOUT*/) //Blocking +{ + HTTPText str(result, maxResultLen); + return get(url, &str, timeout); +} + +HTTPResult HTTPClient::post(const char* url, const IHTTPDataOut& dataOut, IHTTPDataIn* pDataIn, int timeout /*= HTTP_CLIENT_DEFAULT_TIMEOUT*/) //Blocking +{ + return connect(url, HTTP_POST, (IHTTPDataOut*)&dataOut, pDataIn, timeout); +} + +int HTTPClient::getHTTPResponseCode() +{ + return m_httpResponseCode; +} + +#define CHECK_CONN_ERR(ret) \ + do{ \ + if(ret) { \ + m_sock.close(); \ + ERR("Connection error (%d)", ret); \ + return HTTP_CONN; \ + } \ + } while(0) + +#define PRTCL_ERR() \ + do{ \ + m_sock.close(); \ + ERR("Protocol error"); \ + return HTTP_PRTCL; \ + } while(0) + +HTTPResult HTTPClient::connect(const char* url, HTTP_METH method, IHTTPDataOut* pDataOut, IHTTPDataIn* pDataIn, int timeout) //Execute request +{ + m_httpResponseCode = 0; //Invalidate code + m_timeout = timeout; + + char scheme[8]; + uint16_t port; + char host[32]; + char path[64]; + //First we need to parse the url (http[s]://host[:port][/[path]]) -- HTTPS not supported (yet?) + HTTPResult res = parseURL(url, scheme, sizeof(scheme), host, sizeof(host), &port, path, sizeof(path)); + if(res != HTTP_OK) + { + ERR("parseURL returned %d", res); + return res; + } + + if(port == 0) //TODO do handle HTTPS->443 + { + port = 80; + } + + DBG("Scheme: %s", scheme); + DBG("Host: %s", host); + DBG("Port: %d", port); + DBG("Path: %s", path); + + //Connect + DBG("Connecting socket to server"); + int ret = m_sock.connect(host, port); + if (ret < 0) + { + m_sock.close(); + ERR("Could not connect"); + return HTTP_CONN; + } + + //Send request + DBG("Sending request"); + char buf[CHUNK_SIZE]; + const char* meth = (method==HTTP_GET)?"GET":(method==HTTP_POST)?"POST":""; + snprintf(buf, sizeof(buf), "%s %s HTTP/1.1\r\nHost: %s\r\n", meth, path, host); //Write request + ret = send(buf); + if(ret) + { + m_sock.close(); + ERR("Could not write request"); + return HTTP_CONN; + } + + //Send all headers + + //Send default headers + DBG("Sending headers"); + if( (method == HTTP_POST) && (pDataOut != NULL) ) + { + if( pDataOut->getIsChunked() ) + { + ret = send("Transfer-Encoding: chunked\r\n"); + CHECK_CONN_ERR(ret); + } + else + { + snprintf(buf, sizeof(buf), "Content-Length: %d\r\n", pDataOut->getDataLen()); + ret = send(buf); + CHECK_CONN_ERR(ret); + } + char type[48]; + if( pDataOut->getDataType(type, 48) == HTTP_OK ) + { + snprintf(buf, sizeof(buf), "Content-Type: %s\r\n", type); + ret = send(buf); + CHECK_CONN_ERR(ret); + } + } + + //Close headers + DBG("Headers sent"); + ret = send("\r\n"); + CHECK_CONN_ERR(ret); + + size_t trfLen; + + //Send data (if POST) + if( (method == HTTP_POST) && (pDataOut != NULL) ) + { + DBG("Sending data"); + while(true) + { + size_t writtenLen = 0; + pDataOut->read(buf, CHUNK_SIZE, &trfLen); + if( pDataOut->getIsChunked() ) + { + //Write chunk header + char chunkHeader[16]; + snprintf(chunkHeader, sizeof(chunkHeader), "%X\r\n", trfLen); //In hex encoding + ret = send(chunkHeader); + CHECK_CONN_ERR(ret); + } + else if( trfLen == 0 ) + { + break; + } + if( trfLen != 0 ) + { + ret = send(buf, trfLen); + CHECK_CONN_ERR(ret); + } + + if( pDataOut->getIsChunked() ) + { + ret = send("\r\n"); //Chunk-terminating CRLF + CHECK_CONN_ERR(ret); + } + else + { + writtenLen += trfLen; + if( writtenLen >= pDataOut->getDataLen() ) + { + break; + } + } + + if( trfLen == 0 ) + { + break; + } + } + + } + + //Receive response + DBG("Receiving response"); + ret = recv(buf, CHUNK_SIZE - 1, CHUNK_SIZE - 1, &trfLen); //Read n bytes + CHECK_CONN_ERR(ret); + + buf[trfLen] = '\0'; + + char* crlfPtr = strstr(buf, "\r\n"); + if(crlfPtr == NULL) + { + PRTCL_ERR(); + } + + int crlfPos = crlfPtr - buf; + buf[crlfPos] = '\0'; + + //Parse HTTP response + if( sscanf(buf, "HTTP/%*d.%*d %d %*[^\r\n]", &m_httpResponseCode) != 1 ) + { + //Cannot match string, error + ERR("Not a correct HTTP answer : %s\n", buf); + PRTCL_ERR(); + } + + if(m_httpResponseCode != 200) + { + //Cannot match string, error + WARN("Response code %d", m_httpResponseCode); + PRTCL_ERR(); + } + + DBG("Reading headers"); + + memmove(buf, &buf[crlfPos+2], trfLen - (crlfPos + 2) + 1); //Be sure to move NULL-terminating char as well + trfLen -= (crlfPos + 2); + + size_t recvContentLength = 0; + bool recvChunked = false; + //Now get headers + while( true ) + { + crlfPtr = strstr(buf, "\r\n"); + if(crlfPtr == NULL) + { + if( trfLen < CHUNK_SIZE - 1 ) + { + size_t newTrfLen; + ret = recv(buf + trfLen, 1, CHUNK_SIZE - trfLen - 1, &newTrfLen); + trfLen += newTrfLen; + buf[trfLen] = '\0'; + DBG("Read %d chars; In buf: [%s]", newTrfLen, buf); + CHECK_CONN_ERR(ret); + continue; + } + else + { + PRTCL_ERR(); + } + } + + crlfPos = crlfPtr - buf; + + if(crlfPos == 0) //End of headers + { + DBG("Headers read"); + memmove(buf, &buf[2], trfLen - 2 + 1); //Be sure to move NULL-terminating char as well + trfLen -= 2; + break; + } + + buf[crlfPos] = '\0'; + + char key[64] = {0}; + char value[32] = {0}; + + int n = sscanf(buf, "%63[^:]: %31[^\r\n]", key, value); + + if ( n == 2 ) + { + DBG("Read header : %s: %s\n", key, value); + if( !strcmp(key, "Content-Length") ) + { + sscanf(value, "%d", &recvContentLength); + pDataIn->setDataLen(recvContentLength); + } + else if( !strcmp(key, "Transfer-Encoding") ) + { + if( !strcmp(value, "Chunked") || !strcmp(value, "chunked") ) + { + recvChunked = true; + pDataIn->setIsChunked(true); + } + } + else if( !strcmp(key, "Content-Type") ) + { + pDataIn->setDataType(value); + } + + memmove(buf, &buf[crlfPos+2], trfLen - (crlfPos + 2) + 1); //Be sure to move NULL-terminating char as well + trfLen -= (crlfPos + 2); + + } + else + { + ERR("Could not parse header"); + PRTCL_ERR(); + } + + } + + //Receive data + DBG("Receiving data"); + while(true) + { + size_t readLen = 0; + + if( recvChunked ) + { + //Read chunk header + crlfPos=0; + for(crlfPos++; crlfPos < trfLen - 2; crlfPos++) + { + if( buf[crlfPos] == '\r' && buf[crlfPos + 1] == '\n' ) + { + break; + } + } + if(crlfPos >= trfLen - 2) //Try to read more + { + if( trfLen < CHUNK_SIZE ) + { + size_t newTrfLen; + ret = recv(buf + trfLen, 0, CHUNK_SIZE - trfLen - 1, &newTrfLen); + trfLen += newTrfLen; + CHECK_CONN_ERR(ret); + continue; + } + else + { + PRTCL_ERR(); + } + } + buf[crlfPos] = '\0'; + int n = sscanf(buf, "%x", &readLen); + if(n!=1) + { + ERR("Could not read chunk length"); + PRTCL_ERR(); + } + + memmove(buf, &buf[crlfPos+2], trfLen - (crlfPos + 2)); //Not need to move NULL-terminating char any more + trfLen -= (crlfPos + 2); + + if( readLen == 0 ) + { + //Last chunk + break; + } + } + else + { + readLen = recvContentLength; + } + + DBG("Retrieving %d bytes", readLen); + + do + { + pDataIn->write(buf, MIN(trfLen, readLen)); + if( trfLen > readLen ) + { + memmove(buf, &buf[readLen], trfLen - readLen); + trfLen -= readLen; + readLen = 0; + } + else + { + readLen -= trfLen; + } + + if(readLen) + { + ret = recv(buf, 1, CHUNK_SIZE - trfLen - 1, &trfLen); + CHECK_CONN_ERR(ret); + } + } while(readLen); + + if( recvChunked ) + { + if(trfLen < 2) + { + size_t newTrfLen; + //Read missing chars to find end of chunk + ret = recv(buf, 2 - trfLen, CHUNK_SIZE, &newTrfLen); + CHECK_CONN_ERR(ret); + trfLen += newTrfLen; + } + if( (buf[0] != '\r') || (buf[1] != '\n') ) + { + ERR("Format error"); + PRTCL_ERR(); + } + memmove(buf, &buf[2], trfLen - 2); + trfLen -= 2; + } + else + { + break; + } + + } + + m_sock.close(); + DBG("Completed HTTP transaction"); + + return HTTP_OK; +} + +HTTPResult HTTPClient::recv(char* buf, size_t minLen, size_t maxLen, size_t* pReadLen) //0 on success, err code on failure +{ + DBG("Trying to read between %d and %d bytes", minLen, maxLen); + size_t readLen = 0; + + if(!m_sock.is_connected()) + { + WARN("Connection was closed by server"); + return HTTP_CLOSED; //Connection was closed by server + } + + int ret; + while(readLen < maxLen) + { + if(readLen < minLen) + { + DBG("Trying to read at most %d bytes [Blocking]", minLen - readLen); + m_sock.set_blocking(false, m_timeout); + ret = m_sock.receive_all(buf + readLen, minLen - readLen); + } + else + { + DBG("Trying to read at most %d bytes [Not blocking]", maxLen - readLen); + m_sock.set_blocking(false, 0); + ret = m_sock.receive(buf + readLen, maxLen - readLen); + } + + if( ret > 0) + { + readLen += ret; + } + else if( ret == 0 ) + { + break; + } + else + { + if(!m_sock.is_connected()) + { + ERR("Connection error (recv returned %d)", ret); + *pReadLen = readLen; + return HTTP_CONN; + } + else + { + break; + } + } + + if(!m_sock.is_connected()) + { + break; + } + } + DBG("Read %d bytes", readLen); + *pReadLen = readLen; + return HTTP_OK; +} + +HTTPResult HTTPClient::send(char* buf, size_t len) //0 on success, err code on failure +{ + if(len == 0) + { + len = strlen(buf); + } + DBG("Trying to write %d bytes", len); + size_t writtenLen = 0; + + if(!m_sock.is_connected()) + { + WARN("Connection was closed by server"); + return HTTP_CLOSED; //Connection was closed by server + } + + m_sock.set_blocking(false, m_timeout); + int ret = m_sock.send_all(buf, len); + if(ret > 0) + { + writtenLen += ret; + } + else if( ret == 0 ) + { + WARN("Connection was closed by server"); + return HTTP_CLOSED; //Connection was closed by server + } + else + { + ERR("Connection error (send returned %d)", ret); + return HTTP_CONN; + } + + DBG("Written %d bytes", writtenLen); + return HTTP_OK; +} + +HTTPResult HTTPClient::parseURL(const char* url, char* scheme, size_t maxSchemeLen, char* host, size_t maxHostLen, uint16_t* port, char* path, size_t maxPathLen) //Parse URL +{ + char* schemePtr = (char*) url; + char* hostPtr = (char*) strstr(url, "://"); + if(hostPtr == NULL) + { + WARN("Could not find host"); + return HTTP_PARSE; //URL is invalid + } + + if( maxSchemeLen < hostPtr - schemePtr + 1 ) //including NULL-terminating char + { + WARN("Scheme str is too small (%d >= %d)", maxSchemeLen, hostPtr - schemePtr + 1); + return HTTP_PARSE; + } + memcpy(scheme, schemePtr, hostPtr - schemePtr); + scheme[hostPtr - schemePtr] = '\0'; + + hostPtr+=3; + + size_t hostLen = 0; + + char* portPtr = strchr(hostPtr, ':'); + if( portPtr != NULL ) + { + hostLen = portPtr - hostPtr; + portPtr++; + if( sscanf(portPtr, "%hu", port) != 1) + { + WARN("Could not find port"); + return HTTP_PARSE; + } + } + else + { + *port=0; + } + char* pathPtr = strchr(hostPtr, '/'); + if( hostLen == 0 ) + { + hostLen = pathPtr - hostPtr; + } + + if( maxHostLen < hostLen + 1 ) //including NULL-terminating char + { + WARN("Host str is too small (%d >= %d)", maxHostLen, hostLen + 1); + return HTTP_PARSE; + } + memcpy(host, hostPtr, hostLen); + host[hostLen] = '\0'; + + size_t pathLen; + char* fragmentPtr = strchr(hostPtr, '#'); + if(fragmentPtr != NULL) + { + pathLen = fragmentPtr - pathPtr; + } + else + { + pathLen = strlen(pathPtr); + } + + if( maxPathLen < pathLen + 1 ) //including NULL-terminating char + { + WARN("Path str is too small (%d >= %d)", maxPathLen, pathLen + 1); + return HTTP_PARSE; + } + memcpy(path, pathPtr, pathLen); + path[pathLen] = '\0'; + + return HTTP_OK; +} diff --git a/features/unsupported/tests/net/protocols/HTTPClient_HelloWorld/HTTPClient/HTTPClient.h b/features/unsupported/tests/net/protocols/HTTPClient_HelloWorld/HTTPClient/HTTPClient.h new file mode 100644 index 00000000000..e9ac860cabd --- /dev/null +++ b/features/unsupported/tests/net/protocols/HTTPClient_HelloWorld/HTTPClient/HTTPClient.h @@ -0,0 +1,138 @@ +/* HTTPClient.h */ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/** \file +HTTP Client header file +*/ + +#ifndef HTTP_CLIENT_H +#define HTTP_CLIENT_H + +#include "TCPSocketConnection.h" + +#define HTTP_CLIENT_DEFAULT_TIMEOUT 15000 + +class HTTPData; + +#include "IHTTPData.h" +#include "mbed.h" + +///HTTP client results +enum HTTPResult +{ + HTTP_PROCESSING, /// + +using std::size_t; + +///This is a simple interface for HTTP data storage (impl examples are Key/Value Pairs, File, etc...) +class IHTTPDataOut +{ +protected: + friend class HTTPClient; + + /** Read a piece of data to be transmitted + * @param buf Pointer to the buffer on which to copy the data + * @param len Length of the buffer + * @param pReadLen Pointer to the variable on which the actual copied data length will be stored + */ + virtual int read(char* buf, size_t len, size_t* pReadLen) = 0; + + /** Get MIME type + * @param type Internet media type from Content-Type header + */ + virtual int getDataType(char* type, size_t maxTypeLen) = 0; //Internet media type for Content-Type header + + /** Determine whether the HTTP client should chunk the data + * Used for Transfer-Encoding header + */ + virtual bool getIsChunked() = 0; + + /** If the data is not chunked, get its size + * Used for Content-Length header + */ + virtual size_t getDataLen() = 0; + +}; + +///This is a simple interface for HTTP data storage (impl examples are Key/Value Pairs, File, etc...) +class IHTTPDataIn +{ +protected: + friend class HTTPClient; + + /** Write a piece of data transmitted by the server + * @param buf Pointer to the buffer from which to copy the data + * @param len Length of the buffer + */ + virtual int write(const char* buf, size_t len) = 0; + + /** Set MIME type + * @param type Internet media type from Content-Type header + */ + virtual void setDataType(const char* type) = 0; + + /** Determine whether the data is chunked + * Recovered from Transfer-Encoding header + */ + virtual void setIsChunked(bool chunked) = 0; + + /** If the data is not chunked, set its size + * From Content-Length header + */ + virtual void setDataLen(size_t len) = 0; + +}; + +#endif diff --git a/features/unsupported/tests/net/protocols/HTTPClient_HelloWorld/HTTPClient/data/HTTPMap.cpp b/features/unsupported/tests/net/protocols/HTTPClient_HelloWorld/HTTPClient/data/HTTPMap.cpp new file mode 100644 index 00000000000..75ffd970e9b --- /dev/null +++ b/features/unsupported/tests/net/protocols/HTTPClient_HelloWorld/HTTPClient/data/HTTPMap.cpp @@ -0,0 +1,196 @@ +/* HTTPMap.cpp */ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#include "HTTPMap.h" + +#include + +#include + +#define OK 0 + +using std::strncpy; + +HTTPMap::HTTPMap() : m_pos(0), m_count(0) +{ + +} + +void HTTPMap::put(const char* key, const char* value) +{ + if(m_count >= HTTPMAP_TABLE_SIZE) + { + return; + } + m_keys[m_count] = key; + m_values[m_count] = value; + m_count++; +} + +void HTTPMap::clear() +{ + m_count = 0; + m_pos = 0; +} + + +/*virtual*/ int HTTPMap::read(char* buf, size_t len, size_t* pReadLen) +{ + if(m_pos >= m_count) + { + *pReadLen = 0; + m_pos = 0; + return OK; + } + + //URL encode + char* out = buf; + const char* in = m_keys[m_pos]; + if( (m_pos != 0) && (out - buf < len - 1) ) + { + *out='&'; + out++; + } + + while( (*in != '\0') && (out - buf < len - 3) ) + { + if (std::isalnum(*in) || *in == '-' || *in == '_' || *in == '.' || *in == '~') + { + *out = *in; + out++; + } + else if( *in == ' ' ) + { + *out='+'; + out++; + } + else + { + char hex[] = "0123456789abcdef"; + *out='%'; + out++; + *out=hex[(*in>>4)&0xf]; + out++; + *out=hex[(*in)&0xf]; + out++; + } + in++; + } + + if( out - buf < len - 1 ) + { + *out='='; + out++; + } + + in = m_values[m_pos]; + while( (*in != '\0') && (out - buf < len - 3) ) + { + if (std::isalnum(*in) || *in == '-' || *in == '_' || *in == '.' || *in == '~') + { + *out = *in; + out++; + } + else if( *in == ' ' ) + { + *out='+'; + out++; + } + else + { + char hex[] = "0123456789abcdef"; + *out='%'; + out++; + *out=hex[(*in>>4)&0xf]; + out++; + *out=hex[(*in)&0xf]; + out++; + } + in++; + } + + *pReadLen = out - buf; + + m_pos++; + return OK; +} + +/*virtual*/ int HTTPMap::getDataType(char* type, size_t maxTypeLen) //Internet media type for Content-Type header +{ + strncpy(type, "application/x-www-form-urlencoded", maxTypeLen-1); + type[maxTypeLen-1] = '\0'; + return OK; +} + +/*virtual*/ bool HTTPMap::getIsChunked() //For Transfer-Encoding header +{ + return false; ////Data is computed one key/value pair at a time +} + +/*virtual*/ size_t HTTPMap::getDataLen() //For Content-Length header +{ + size_t count = 0; + for(size_t i = 0; i< m_count; i++) + { + //URL encode + const char* in = m_keys[i]; + if( i != 0 ) + { + count++; + } + + while( (*in != '\0') ) + { + if (std::isalnum(*in) || *in == '-' || *in == '_' || *in == '.' || *in == '~') + { + count++; + } + else if( *in == ' ' ) + { + count++; + } + else + { + count+=3; + } + in++; + } + + count ++; + + in = m_values[i]; + while( (*in != '\0') ) + { + if (std::isalnum(*in) || *in == '-' || *in == '_' || *in == '.' || *in == '~') + { + count++; + } + else if( *in == ' ' ) + { + count++; + } + else + { + count+=3; + } + in++; + } + } + return count; +} diff --git a/features/unsupported/tests/net/protocols/HTTPClient_HelloWorld/HTTPClient/data/HTTPMap.h b/features/unsupported/tests/net/protocols/HTTPClient_HelloWorld/HTTPClient/data/HTTPMap.h new file mode 100644 index 00000000000..ad02211e9a1 --- /dev/null +++ b/features/unsupported/tests/net/protocols/HTTPClient_HelloWorld/HTTPClient/data/HTTPMap.h @@ -0,0 +1,69 @@ +/* HTTPMap.h */ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + + +#ifndef HTTPMAP_H_ +#define HTTPMAP_H_ + +#include "../IHTTPData.h" + +#define HTTPMAP_TABLE_SIZE 32 + +/** Map of key/value pairs + * Used to transmit POST data using the application/x-www-form-urlencoded encoding + */ +class HTTPMap: public IHTTPDataOut +{ +public: + /** + Instantiates HTTPMap + It supports at most 32 key/values pairs + */ + HTTPMap(); + + /** Put Key/Value pair + The references to the parameters must remain valid as long as the clear() function is not called + @param key The key to use + @param value The corresponding value + */ + void put(const char* key, const char* value); + + /** Clear table + */ + void clear(); + +protected: + //IHTTPDataIn + virtual int read(char* buf, size_t len, size_t* pReadLen); + + virtual int getDataType(char* type, size_t maxTypeLen); //Internet media type for Content-Type header + + virtual bool getIsChunked(); //For Transfer-Encoding header + + virtual size_t getDataLen(); //For Content-Length header + +private: + const char* m_keys[HTTPMAP_TABLE_SIZE]; + const char* m_values[HTTPMAP_TABLE_SIZE]; + + size_t m_pos; + size_t m_count; +}; + +#endif /* HTTPMAP_H_ */ diff --git a/features/unsupported/tests/net/protocols/HTTPClient_HelloWorld/HTTPClient/data/HTTPText.cpp b/features/unsupported/tests/net/protocols/HTTPClient_HelloWorld/HTTPClient/data/HTTPText.cpp new file mode 100644 index 00000000000..800532b0e26 --- /dev/null +++ b/features/unsupported/tests/net/protocols/HTTPClient_HelloWorld/HTTPClient/data/HTTPText.cpp @@ -0,0 +1,94 @@ +/* HTTPText.cpp */ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#include "HTTPText.h" + +#include + +#define OK 0 + +using std::memcpy; +using std::strncpy; +using std::strlen; + +#define MIN(x,y) (((x)<(y))?(x):(y)) + +HTTPText::HTTPText(char* str) : m_str(str), m_pos(0) +{ + m_size = strlen(str) + 1; +} + +HTTPText::HTTPText(char* str, size_t size) : m_str(str), m_size(size), m_pos(0) +{ + +} + +//IHTTPDataIn +/*virtual*/ int HTTPText::read(char* buf, size_t len, size_t* pReadLen) +{ + *pReadLen = MIN(len, m_size - 1 - m_pos); + memcpy(buf, m_str + m_pos, *pReadLen); + m_pos += *pReadLen; + return OK; +} + +/*virtual*/ int HTTPText::getDataType(char* type, size_t maxTypeLen) //Internet media type for Content-Type header +{ + strncpy(type, "text/plain", maxTypeLen-1); + type[maxTypeLen-1] = '\0'; + return OK; +} + +/*virtual*/ bool HTTPText::getIsChunked() //For Transfer-Encoding header +{ + return false; +} + +/*virtual*/ size_t HTTPText::getDataLen() //For Content-Length header +{ + return m_size - 1; +} + +//IHTTPDataOut +/*virtual*/ int HTTPText::write(const char* buf, size_t len) +{ + size_t writeLen = MIN(len, m_size - 1 - m_pos); + memcpy(m_str + m_pos, buf, writeLen); + m_pos += writeLen; + m_str[m_pos] = '\0'; + return OK; +} + +/*virtual*/ void HTTPText::setDataType(const char* type) //Internet media type from Content-Type header +{ + +} + +/*virtual*/ void HTTPText::setIsChunked(bool chunked) //From Transfer-Encoding header +{ + +} + +/*virtual*/ void HTTPText::setDataLen(size_t len) //From Content-Length header, or if the transfer is chunked, next chunk length +{ + +} + + + diff --git a/features/unsupported/tests/net/protocols/HTTPClient_HelloWorld/HTTPClient/data/HTTPText.h b/features/unsupported/tests/net/protocols/HTTPClient_HelloWorld/HTTPClient/data/HTTPText.h new file mode 100644 index 00000000000..224a9578789 --- /dev/null +++ b/features/unsupported/tests/net/protocols/HTTPClient_HelloWorld/HTTPClient/data/HTTPText.h @@ -0,0 +1,68 @@ +/* HTTPText.h */ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + + +#ifndef HTTPTEXT_H_ +#define HTTPTEXT_H_ + +#include "../IHTTPData.h" + +/** A data endpoint to store text +*/ +class HTTPText : public IHTTPDataIn, public IHTTPDataOut +{ +public: + /** Create an HTTPText instance for output + * @param str String to be transmitted + */ + HTTPText(char* str); + + /** Create an HTTPText instance for input + * @param str Buffer to store the incoming string + * @param size Size of the buffer + */ + HTTPText(char* str, size_t size); + +protected: + //IHTTPDataIn + virtual int read(char* buf, size_t len, size_t* pReadLen); + + virtual int getDataType(char* type, size_t maxTypeLen); //Internet media type for Content-Type header + + virtual bool getIsChunked(); //For Transfer-Encoding header + + virtual size_t getDataLen(); //For Content-Length header + + //IHTTPDataOut + virtual int write(const char* buf, size_t len); + + virtual void setDataType(const char* type); //Internet media type from Content-Type header + + virtual void setIsChunked(bool chunked); //From Transfer-Encoding header + + virtual void setDataLen(size_t len); //From Content-Length header, or if the transfer is chunked, next chunk length + +private: + char* m_str; + size_t m_size; + + size_t m_pos; +}; + +#endif /* HTTPTEXT_H_ */ diff --git a/features/unsupported/tests/net/protocols/HTTPClient_HelloWorld/main.cpp b/features/unsupported/tests/net/protocols/HTTPClient_HelloWorld/main.cpp new file mode 100644 index 00000000000..5ab616ea957 --- /dev/null +++ b/features/unsupported/tests/net/protocols/HTTPClient_HelloWorld/main.cpp @@ -0,0 +1,67 @@ +#include "mbed.h" +#include "test_env.h" +#include "EthernetInterface.h" +#include "HTTPClient.h" + + +namespace { + const int BUFFER_SIZE = 512; +} + +int main() { + MBED_HOSTTEST_TIMEOUT(15); + MBED_HOSTTEST_SELECT(default_auto); + MBED_HOSTTEST_DESCRIPTION(HTTP client hello world); + MBED_HOSTTEST_START("NET_7"); + + char http_request_buffer[BUFFER_SIZE + 1] = {0}; + HTTPClient http; + EthernetInterface eth; + eth.init(); //Use DHCP + eth.connect(); + + //GET data + { + bool result = true; + const char *url_hello_txt = "http://developer.mbed.org/media/uploads/donatien/hello.txt"; + printf("HTTP_GET: Trying to fetch page '%s'...\r\n", url_hello_txt); + HTTPResult ret = http.get(url_hello_txt, http_request_buffer, BUFFER_SIZE); + if (ret == HTTP_OK) { + printf("HTTP_GET: Read %d chars: '%s' ... [OK]\r\n", strlen(http_request_buffer), http_request_buffer); + } else { + printf("HTTP_GET: Error(%d). HTTP error(%d) ... [FAIL]\r\n", ret, http.getHTTPResponseCode()); + result = false; + } + + if (result == false) { + eth.disconnect(); + MBED_HOSTTEST_RESULT(false); + } + } + + //POST data + { + bool result = true; + const char *url_httpbin_post = "http://httpbin.org/post"; + HTTPText text(http_request_buffer, BUFFER_SIZE); + HTTPMap map; + map.put("Hello", "World"); + map.put("test", "1234"); + printf("HTTP_POST: Trying to post data to '%s' ...\r\n", url_httpbin_post); + HTTPResult ret = http.post(url_httpbin_post, map, &text); + if (ret == HTTP_OK) { + printf("HTTP_POST: Read %d chars ... [OK]\r\n", strlen(http_request_buffer)); + printf("HTTP_POST: %s\r\n", http_request_buffer); + } else { + printf("HTTP_GET: Error(%d). HTTP error(%d) ... [FAIL]\r\n", ret, http.getHTTPResponseCode()); + result = false; + } + + if (result == false) { + eth.disconnect(); + MBED_HOSTTEST_RESULT(false); + } + } + eth.disconnect(); + MBED_HOSTTEST_RESULT(true); +} diff --git a/features/unsupported/tests/net/protocols/NTPClient_HelloWorld/NTPClient/NTPClient.cpp b/features/unsupported/tests/net/protocols/NTPClient_HelloWorld/NTPClient/NTPClient.cpp new file mode 100644 index 00000000000..b049d300364 --- /dev/null +++ b/features/unsupported/tests/net/protocols/NTPClient_HelloWorld/NTPClient/NTPClient.cpp @@ -0,0 +1,163 @@ +/* NTPClient.cpp */ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +//Debug is disabled by default +#if 0 +//Enable debug +#define __DEBUG__ +#include +#define DBG(x, ...) std::printf("[NTPClient : DBG]"x"\r\n", ##__VA_ARGS__); +#define WARN(x, ...) std::printf("[NTPClient : WARN]"x"\r\n", ##__VA_ARGS__); +#define ERR(x, ...) std::printf("[NTPClient : ERR]"x"\r\n", ##__VA_ARGS__); + +#else +//Disable debug +#define DBG(x, ...) +#define WARN(x, ...) +#define ERR(x, ...) + +#endif + +#include "NTPClient.h" + +#include "UDPSocket.h" + +#include "mbed.h" //time() and set_time() + +#define NTP_PORT 123 +#define NTP_CLIENT_PORT 0 //Random port +#define NTP_TIMESTAMP_DELTA 2208988800ull //Diff btw a UNIX timestamp (Starting Jan, 1st 1970) and a NTP timestamp (Starting Jan, 1st 1900) + +NTPClient::NTPClient() : m_sock() +{ + + +} + +NTPResult NTPClient::setTime(const char* host, uint16_t port, uint32_t timeout) +{ +#ifdef __DEBUG__ + time_t ctTime; + ctTime = time(NULL); + DBG("Time is set to (UTC): %s", ctime(&ctTime)); +#endif + + //Create & bind socket + DBG("Binding socket"); + m_sock.bind(0); //Bind to a random port + + m_sock.set_blocking(false, timeout); //Set not blocking + + struct NTPPacket pkt; + + //Now ping the server and wait for response + DBG("Ping"); + //Prepare NTP Packet: + pkt.li = 0; //Leap Indicator : No warning + pkt.vn = 4; //Version Number : 4 + pkt.mode = 3; //Client mode + pkt.stratum = 0; //Not relevant here + pkt.poll = 0; //Not significant as well + pkt.precision = 0; //Neither this one is + + pkt.rootDelay = 0; //Or this one + pkt.rootDispersion = 0; //Or that one + pkt.refId = 0; //... + + pkt.refTm_s = 0; + pkt.origTm_s = 0; + pkt.rxTm_s = 0; + pkt.txTm_s = htonl( NTP_TIMESTAMP_DELTA + time(NULL) ); //WARN: We are in LE format, network byte order is BE + + pkt.refTm_f = pkt.origTm_f = pkt.rxTm_f = pkt.txTm_f = 0; + + Endpoint outEndpoint; + + if( outEndpoint.set_address(host, port) < 0) + { + m_sock.close(); + return NTP_DNS; + } + + //Set timeout, non-blocking and wait using select + int ret = m_sock.sendTo( outEndpoint, (char*)&pkt, sizeof(NTPPacket) ); + if (ret < 0 ) + { + ERR("Could not send packet"); + m_sock.close(); + return NTP_CONN; + } + + //Read response + Endpoint inEndpoint; + + DBG("Pong"); + do + { + ret = m_sock.receiveFrom( inEndpoint, (char*)&pkt, sizeof(NTPPacket) ); //FIXME need a DNS Resolver to actually compare the incoming address with the DNS name + if(ret < 0) + { + ERR("Could not receive packet"); + m_sock.close(); + return NTP_CONN; + } + } while( strcmp(outEndpoint.get_address(), inEndpoint.get_address()) != 0 ); + + if(ret < sizeof(NTPPacket)) //TODO: Accept chunks + { + ERR("Receive packet size does not match"); + m_sock.close(); + return NTP_PRTCL; + } + + if( pkt.stratum == 0) //Kiss of death message : Not good ! + { + ERR("Kissed to death!"); + m_sock.close(); + return NTP_PRTCL; + } + + //Correct Endianness + pkt.refTm_s = ntohl( pkt.refTm_s ); + pkt.refTm_f = ntohl( pkt.refTm_f ); + pkt.origTm_s = ntohl( pkt.origTm_s ); + pkt.origTm_f = ntohl( pkt.origTm_f ); + pkt.rxTm_s = ntohl( pkt.rxTm_s ); + pkt.rxTm_f = ntohl( pkt.rxTm_f ); + pkt.txTm_s = ntohl( pkt.txTm_s ); + pkt.txTm_f = ntohl( pkt.txTm_f ); + + //Compute offset, see RFC 4330 p.13 + uint32_t destTm_s = (NTP_TIMESTAMP_DELTA + time(NULL)); + int64_t offset = ( (int64_t)( pkt.rxTm_s - pkt.origTm_s ) + (int64_t) ( pkt.txTm_s - destTm_s ) ) / 2; //Avoid overflow + DBG("Sent @%ul", pkt.txTm_s); + DBG("Offset: %lld", offset); + //Set time accordingly + set_time( time(NULL) + offset ); + +#ifdef __DEBUG__ + ctTime = time(NULL); + DBG("Time is now (UTC): %s", ctime(&ctTime)); +#endif + + m_sock.close(); + + return NTP_OK; +} + diff --git a/features/unsupported/tests/net/protocols/NTPClient_HelloWorld/NTPClient/NTPClient.h b/features/unsupported/tests/net/protocols/NTPClient_HelloWorld/NTPClient/NTPClient.h new file mode 100644 index 00000000000..b7cf6ff1276 --- /dev/null +++ b/features/unsupported/tests/net/protocols/NTPClient_HelloWorld/NTPClient/NTPClient.h @@ -0,0 +1,101 @@ +/* NTPClient.h */ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/** \file +NTP Client header file +*/ + +#ifndef NTPCLIENT_H_ +#define NTPCLIENT_H_ + +#include "UDPSocket.h" + +#define NTP_DEFAULT_PORT 123 +#define NTP_DEFAULT_TIMEOUT 4000 + +///NTP client results +enum NTPResult +{ + NTP_DNS, ///next; } - - /* if we're at the end p will be NULL, which is correct */ - obj->next = p; - /* if prev is NULL we're at the head */ if (prev == NULL) { data->queue->head = obj; @@ -85,6 +81,8 @@ void ticker_insert_event(const ticker_data_t *const data, ticker_event_t *obj, t } else { prev->next = obj; } + /* if we're at the end p will be NULL, which is correct */ + obj->next = p; core_util_critical_section_exit(); } diff --git a/mbed.h b/mbed.h index b160a046cf7..9b1b01e8d6a 100644 --- a/mbed.h +++ b/mbed.h @@ -16,17 +16,13 @@ #ifndef MBED_H #define MBED_H - -/* mbed minor and patch versions for both mbed 2 and mbed OS 5 are 0 on master branch. They are set - to meaningful values for releases and release branches. - */ -#define MBED_LIBRARY_VERSION 0 +#define MBED_LIBRARY_VERSION 123 #if MBED_CONF_RTOS_PRESENT // RTOS present, this is valid only for mbed OS 5 #define MBED_MAJOR_VERSION 5 -#define MBED_MINOR_VERSION 0 -#define MBED_PATCH_VERSION 0 +#define MBED_MINOR_VERSION 2 +#define MBED_PATCH_VERSION 1 #else // mbed 2 @@ -67,7 +63,6 @@ #include "platform/mbed_error.h" #include "platform/mbed_interface.h" #include "platform/mbed_assert.h" -#include "platform/mbed_debug.h" // mbed Peripheral components #include "drivers/DigitalIn.h" diff --git a/platform/CThunk.h b/platform/CThunk.h index a1db2cf205f..1a9a17224b3 100644 --- a/platform/CThunk.h +++ b/platform/CThunk.h @@ -72,13 +72,11 @@ /* IRQ/Exception compatible thunk entry function */ typedef void (*CThunkEntry)(void); -/** @}*/ /** * Class for created a pointer with data bound to it * - * @note Synchronization level: Not protected - * @ingroup platform + * @Note Synchronization level: Not protected */ template class CThunk @@ -244,3 +242,4 @@ class CThunk #endif/*__CTHUNK_H__*/ +/** @}*/ diff --git a/platform/CallChain.h b/platform/CallChain.h index d702ec89c8f..0a36cfe5c27 100644 --- a/platform/CallChain.h +++ b/platform/CallChain.h @@ -22,12 +22,13 @@ namespace mbed { /** \addtogroup platform */ +/** @{*/ /** Group one or more functions in an instance of a CallChain, then call them in * sequence using CallChain::call(). Used mostly by the interrupt chaining code, * but can be used for other purposes. * - * @note Synchronization level: Not protected + * @Note Synchronization level: Not protected * * Example: * @code @@ -59,7 +60,6 @@ namespace mbed { * chain.call(); * } * @endcode - * @ingroup platform */ typedef Callback *pFunctionPointer_t; @@ -114,8 +114,8 @@ class CallChain { /** Add a function at the beginning of the chain * - * @param obj pointer to the object to call the member function on - * @param method pointer to the member function to be called + * @param tptr pointer to the object to call the member function on + * @param mptr pointer to the member function to be called * * @returns * The function object created for 'tptr' and 'mptr' @@ -189,3 +189,4 @@ class CallChain { #endif +/** @}*/ diff --git a/platform/Callback.h b/platform/Callback.h index b9fd21e90aa..e6462571a13 100644 --- a/platform/Callback.h +++ b/platform/Callback.h @@ -24,12 +24,12 @@ namespace mbed { /** \addtogroup platform */ +/** @{*/ /** Callback class based on template specialization * - * @note Synchronization level: Not protected - * @ingroup platform + * @Note Synchronization level: Not protected */ template class Callback; @@ -58,16 +58,9 @@ namespace detail { }; } -#define MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, M) \ - typename detail::enable_if< \ - detail::is_type::value && \ - sizeof(F) <= sizeof(uintptr_t) \ - >::type = detail::nil() - /** Callback class based on template specialization * - * @note Synchronization level: Not protected - * @ingroup platform + * @Note Synchronization level: Not protected */ template class Callback { @@ -166,38 +159,50 @@ class Callback { } /** Create a Callback with a function object - * @param f Function object to attach + * @param func Function object to attach * @note The function object is limited to a single word of storage */ template - Callback(F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)())) { + Callback(F f, typename detail::enable_if< + detail::is_type::value && + sizeof(F) <= sizeof(uintptr_t) + >::type = detail::nil()) { generate(f); } /** Create a Callback with a function object - * @param f Function object to attach + * @param func Function object to attach * @note The function object is limited to a single word of storage */ template - Callback(const F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)() const)) { + Callback(const F f, typename detail::enable_if< + detail::is_type::value && + sizeof(F) <= sizeof(uintptr_t) + >::type = detail::nil()) { generate(f); } /** Create a Callback with a function object - * @param f Function object to attach + * @param func Function object to attach * @note The function object is limited to a single word of storage */ template - Callback(volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)() volatile)) { + Callback(volatile F f, typename detail::enable_if< + detail::is_type::value && + sizeof(F) <= sizeof(uintptr_t) + >::type = detail::nil()) { generate(f); } /** Create a Callback with a function object - * @param f Function object to attach + * @param func Function object to attach * @note The function object is limited to a single word of storage */ template - Callback(const volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)() const volatile)) { + Callback(const volatile F f, typename detail::enable_if< + detail::is_type::value && + sizeof(F) <= sizeof(uintptr_t) + >::type = detail::nil()) { generate(f); } @@ -398,7 +403,7 @@ class Callback { } /** Attach a function object - * @param f Function object to attach + * @param func Function object to attach * @note The function object is limited to a single word of storage * @deprecated * Replaced by simple assignment 'Callback cb = func' @@ -406,13 +411,16 @@ class Callback { template MBED_DEPRECATED_SINCE("mbed-os-5.4", "Replaced by simple assignment 'Callback cb = func") - void attach(F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)())) { + void attach(F f, typename detail::enable_if< + detail::is_type::value && + sizeof(F) <= sizeof(uintptr_t) + >::type = detail::nil()) { this->~Callback(); new (this) Callback(f); } /** Attach a function object - * @param f Function object to attach + * @param func Function object to attach * @note The function object is limited to a single word of storage * @deprecated * Replaced by simple assignment 'Callback cb = func' @@ -420,13 +428,16 @@ class Callback { template MBED_DEPRECATED_SINCE("mbed-os-5.4", "Replaced by simple assignment 'Callback cb = func") - void attach(const F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)() const)) { + void attach(const F f, typename detail::enable_if< + detail::is_type::value && + sizeof(F) <= sizeof(uintptr_t) + >::type = detail::nil()) { this->~Callback(); new (this) Callback(f); } /** Attach a function object - * @param f Function object to attach + * @param func Function object to attach * @note The function object is limited to a single word of storage * @deprecated * Replaced by simple assignment 'Callback cb = func' @@ -434,13 +445,16 @@ class Callback { template MBED_DEPRECATED_SINCE("mbed-os-5.4", "Replaced by simple assignment 'Callback cb = func") - void attach(volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)() volatile)) { + void attach(volatile F f, typename detail::enable_if< + detail::is_type::value && + sizeof(F) <= sizeof(uintptr_t) + >::type = detail::nil()) { this->~Callback(); new (this) Callback(f); } /** Attach a function object - * @param f Function object to attach + * @param func Function object to attach * @note The function object is limited to a single word of storage * @deprecated * Replaced by simple assignment 'Callback cb = func' @@ -448,7 +462,10 @@ class Callback { template MBED_DEPRECATED_SINCE("mbed-os-5.4", "Replaced by simple assignment 'Callback cb = func") - void attach(const volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)() const volatile)) { + void attach(const volatile F f, typename detail::enable_if< + detail::is_type::value && + sizeof(F) <= sizeof(uintptr_t) + >::type = detail::nil()) { this->~Callback(); new (this) Callback(f); } @@ -553,8 +570,6 @@ class Callback { /** Static thunk for passing as C-style function * @param func Callback to call passed as void pointer - * @return the value as determined by func which is of - * type and determined by the signiture of func */ static R thunk(void *func) { return static_cast(func)->call(); @@ -640,8 +655,7 @@ class Callback { /** Callback class based on template specialization * - * @note Synchronization level: Not protected - * @ingroup platform + * @Note Synchronization level: Not protected */ template class Callback { @@ -740,38 +754,50 @@ class Callback { } /** Create a Callback with a function object - * @param f Function object to attach + * @param func Function object to attach * @note The function object is limited to a single word of storage */ template - Callback(F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0))) { + Callback(F f, typename detail::enable_if< + detail::is_type::value && + sizeof(F) <= sizeof(uintptr_t) + >::type = detail::nil()) { generate(f); } /** Create a Callback with a function object - * @param f Function object to attach + * @param func Function object to attach * @note The function object is limited to a single word of storage */ template - Callback(const F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0) const)) { + Callback(const F f, typename detail::enable_if< + detail::is_type::value && + sizeof(F) <= sizeof(uintptr_t) + >::type = detail::nil()) { generate(f); } /** Create a Callback with a function object - * @param f Function object to attach + * @param func Function object to attach * @note The function object is limited to a single word of storage */ template - Callback(volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0) volatile)) { + Callback(volatile F f, typename detail::enable_if< + detail::is_type::value && + sizeof(F) <= sizeof(uintptr_t) + >::type = detail::nil()) { generate(f); } /** Create a Callback with a function object - * @param f Function object to attach + * @param func Function object to attach * @note The function object is limited to a single word of storage */ template - Callback(const volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0) const volatile)) { + Callback(const volatile F f, typename detail::enable_if< + detail::is_type::value && + sizeof(F) <= sizeof(uintptr_t) + >::type = detail::nil()) { generate(f); } @@ -972,7 +998,7 @@ class Callback { } /** Attach a function object - * @param f Function object to attach + * @param func Function object to attach * @note The function object is limited to a single word of storage * @deprecated * Replaced by simple assignment 'Callback cb = func' @@ -980,13 +1006,16 @@ class Callback { template MBED_DEPRECATED_SINCE("mbed-os-5.4", "Replaced by simple assignment 'Callback cb = func") - void attach(F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0))) { + void attach(F f, typename detail::enable_if< + detail::is_type::value && + sizeof(F) <= sizeof(uintptr_t) + >::type = detail::nil()) { this->~Callback(); new (this) Callback(f); } /** Attach a function object - * @param f Function object to attach + * @param func Function object to attach * @note The function object is limited to a single word of storage * @deprecated * Replaced by simple assignment 'Callback cb = func' @@ -994,13 +1023,16 @@ class Callback { template MBED_DEPRECATED_SINCE("mbed-os-5.4", "Replaced by simple assignment 'Callback cb = func") - void attach(const F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0) const)) { + void attach(const F f, typename detail::enable_if< + detail::is_type::value && + sizeof(F) <= sizeof(uintptr_t) + >::type = detail::nil()) { this->~Callback(); new (this) Callback(f); } /** Attach a function object - * @param f Function object to attach + * @param func Function object to attach * @note The function object is limited to a single word of storage * @deprecated * Replaced by simple assignment 'Callback cb = func' @@ -1008,13 +1040,16 @@ class Callback { template MBED_DEPRECATED_SINCE("mbed-os-5.4", "Replaced by simple assignment 'Callback cb = func") - void attach(volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0) volatile)) { + void attach(volatile F f, typename detail::enable_if< + detail::is_type::value && + sizeof(F) <= sizeof(uintptr_t) + >::type = detail::nil()) { this->~Callback(); new (this) Callback(f); } /** Attach a function object - * @param f Function object to attach + * @param func Function object to attach * @note The function object is limited to a single word of storage * @deprecated * Replaced by simple assignment 'Callback cb = func' @@ -1022,7 +1057,10 @@ class Callback { template MBED_DEPRECATED_SINCE("mbed-os-5.4", "Replaced by simple assignment 'Callback cb = func") - void attach(const volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0) const volatile)) { + void attach(const volatile F f, typename detail::enable_if< + detail::is_type::value && + sizeof(F) <= sizeof(uintptr_t) + >::type = detail::nil()) { this->~Callback(); new (this) Callback(f); } @@ -1127,9 +1165,6 @@ class Callback { /** Static thunk for passing as C-style function * @param func Callback to call passed as void pointer - * @param a0 An argument to be called with function func - * @return the value as determined by func which is of - * type and determined by the signiture of func */ static R thunk(void *func, A0 a0) { return static_cast(func)->call(a0); @@ -1215,8 +1250,7 @@ class Callback { /** Callback class based on template specialization * - * @note Synchronization level: Not protected - * @ingroup platform + * @Note Synchronization level: Not protected */ template class Callback { @@ -1315,38 +1349,50 @@ class Callback { } /** Create a Callback with a function object - * @param f Function object to attach + * @param func Function object to attach * @note The function object is limited to a single word of storage */ template - Callback(F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1))) { + Callback(F f, typename detail::enable_if< + detail::is_type::value && + sizeof(F) <= sizeof(uintptr_t) + >::type = detail::nil()) { generate(f); } /** Create a Callback with a function object - * @param f Function object to attach + * @param func Function object to attach * @note The function object is limited to a single word of storage */ template - Callback(const F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1) const)) { + Callback(const F f, typename detail::enable_if< + detail::is_type::value && + sizeof(F) <= sizeof(uintptr_t) + >::type = detail::nil()) { generate(f); } /** Create a Callback with a function object - * @param f Function object to attach + * @param func Function object to attach * @note The function object is limited to a single word of storage */ template - Callback(volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1) volatile)) { + Callback(volatile F f, typename detail::enable_if< + detail::is_type::value && + sizeof(F) <= sizeof(uintptr_t) + >::type = detail::nil()) { generate(f); } /** Create a Callback with a function object - * @param f Function object to attach + * @param func Function object to attach * @note The function object is limited to a single word of storage */ template - Callback(const volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1) const volatile)) { + Callback(const volatile F f, typename detail::enable_if< + detail::is_type::value && + sizeof(F) <= sizeof(uintptr_t) + >::type = detail::nil()) { generate(f); } @@ -1547,7 +1593,7 @@ class Callback { } /** Attach a function object - * @param f Function object to attach + * @param func Function object to attach * @note The function object is limited to a single word of storage * @deprecated * Replaced by simple assignment 'Callback cb = func' @@ -1555,13 +1601,16 @@ class Callback { template MBED_DEPRECATED_SINCE("mbed-os-5.4", "Replaced by simple assignment 'Callback cb = func") - void attach(F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1))) { + void attach(F f, typename detail::enable_if< + detail::is_type::value && + sizeof(F) <= sizeof(uintptr_t) + >::type = detail::nil()) { this->~Callback(); new (this) Callback(f); } /** Attach a function object - * @param f Function object to attach + * @param func Function object to attach * @note The function object is limited to a single word of storage * @deprecated * Replaced by simple assignment 'Callback cb = func' @@ -1569,13 +1618,16 @@ class Callback { template MBED_DEPRECATED_SINCE("mbed-os-5.4", "Replaced by simple assignment 'Callback cb = func") - void attach(const F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1) const)) { + void attach(const F f, typename detail::enable_if< + detail::is_type::value && + sizeof(F) <= sizeof(uintptr_t) + >::type = detail::nil()) { this->~Callback(); new (this) Callback(f); } /** Attach a function object - * @param f Function object to attach + * @param func Function object to attach * @note The function object is limited to a single word of storage * @deprecated * Replaced by simple assignment 'Callback cb = func' @@ -1583,13 +1635,16 @@ class Callback { template MBED_DEPRECATED_SINCE("mbed-os-5.4", "Replaced by simple assignment 'Callback cb = func") - void attach(volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1) volatile)) { + void attach(volatile F f, typename detail::enable_if< + detail::is_type::value && + sizeof(F) <= sizeof(uintptr_t) + >::type = detail::nil()) { this->~Callback(); new (this) Callback(f); } /** Attach a function object - * @param f Function object to attach + * @param func Function object to attach * @note The function object is limited to a single word of storage * @deprecated * Replaced by simple assignment 'Callback cb = func' @@ -1597,7 +1652,10 @@ class Callback { template MBED_DEPRECATED_SINCE("mbed-os-5.4", "Replaced by simple assignment 'Callback cb = func") - void attach(const volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1) const volatile)) { + void attach(const volatile F f, typename detail::enable_if< + detail::is_type::value && + sizeof(F) <= sizeof(uintptr_t) + >::type = detail::nil()) { this->~Callback(); new (this) Callback(f); } @@ -1702,10 +1760,6 @@ class Callback { /** Static thunk for passing as C-style function * @param func Callback to call passed as void pointer - * @param a0 An argument to be called with function func - * @param a1 An argument to be called with function func - * @return the value as determined by func which is of - * type and determined by the signiture of func */ static R thunk(void *func, A0 a0, A1 a1) { return static_cast(func)->call(a0, a1); @@ -1791,8 +1845,7 @@ class Callback { /** Callback class based on template specialization * - * @note Synchronization level: Not protected - * @ingroup platform + * @Note Synchronization level: Not protected */ template class Callback { @@ -1891,38 +1944,50 @@ class Callback { } /** Create a Callback with a function object - * @param f Function object to attach + * @param func Function object to attach * @note The function object is limited to a single word of storage */ template - Callback(F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1, A2))) { + Callback(F f, typename detail::enable_if< + detail::is_type::value && + sizeof(F) <= sizeof(uintptr_t) + >::type = detail::nil()) { generate(f); } /** Create a Callback with a function object - * @param f Function object to attach + * @param func Function object to attach * @note The function object is limited to a single word of storage */ template - Callback(const F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1, A2) const)) { + Callback(const F f, typename detail::enable_if< + detail::is_type::value && + sizeof(F) <= sizeof(uintptr_t) + >::type = detail::nil()) { generate(f); } /** Create a Callback with a function object - * @param f Function object to attach + * @param func Function object to attach * @note The function object is limited to a single word of storage */ template - Callback(volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1, A2) volatile)) { + Callback(volatile F f, typename detail::enable_if< + detail::is_type::value && + sizeof(F) <= sizeof(uintptr_t) + >::type = detail::nil()) { generate(f); } /** Create a Callback with a function object - * @param f Function object to attach + * @param func Function object to attach * @note The function object is limited to a single word of storage */ template - Callback(const volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1, A2) const volatile)) { + Callback(const volatile F f, typename detail::enable_if< + detail::is_type::value && + sizeof(F) <= sizeof(uintptr_t) + >::type = detail::nil()) { generate(f); } @@ -2123,7 +2188,7 @@ class Callback { } /** Attach a function object - * @param f Function object to attach + * @param func Function object to attach * @note The function object is limited to a single word of storage * @deprecated * Replaced by simple assignment 'Callback cb = func' @@ -2131,13 +2196,16 @@ class Callback { template MBED_DEPRECATED_SINCE("mbed-os-5.4", "Replaced by simple assignment 'Callback cb = func") - void attach(F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1, A2))) { + void attach(F f, typename detail::enable_if< + detail::is_type::value && + sizeof(F) <= sizeof(uintptr_t) + >::type = detail::nil()) { this->~Callback(); new (this) Callback(f); } /** Attach a function object - * @param f Function object to attach + * @param func Function object to attach * @note The function object is limited to a single word of storage * @deprecated * Replaced by simple assignment 'Callback cb = func' @@ -2145,13 +2213,16 @@ class Callback { template MBED_DEPRECATED_SINCE("mbed-os-5.4", "Replaced by simple assignment 'Callback cb = func") - void attach(const F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1, A2) const)) { + void attach(const F f, typename detail::enable_if< + detail::is_type::value && + sizeof(F) <= sizeof(uintptr_t) + >::type = detail::nil()) { this->~Callback(); new (this) Callback(f); } /** Attach a function object - * @param f Function object to attach + * @param func Function object to attach * @note The function object is limited to a single word of storage * @deprecated * Replaced by simple assignment 'Callback cb = func' @@ -2159,13 +2230,16 @@ class Callback { template MBED_DEPRECATED_SINCE("mbed-os-5.4", "Replaced by simple assignment 'Callback cb = func") - void attach(volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1, A2) volatile)) { + void attach(volatile F f, typename detail::enable_if< + detail::is_type::value && + sizeof(F) <= sizeof(uintptr_t) + >::type = detail::nil()) { this->~Callback(); new (this) Callback(f); } /** Attach a function object - * @param f Function object to attach + * @param func Function object to attach * @note The function object is limited to a single word of storage * @deprecated * Replaced by simple assignment 'Callback cb = func' @@ -2173,7 +2247,10 @@ class Callback { template MBED_DEPRECATED_SINCE("mbed-os-5.4", "Replaced by simple assignment 'Callback cb = func") - void attach(const volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1, A2) const volatile)) { + void attach(const volatile F f, typename detail::enable_if< + detail::is_type::value && + sizeof(F) <= sizeof(uintptr_t) + >::type = detail::nil()) { this->~Callback(); new (this) Callback(f); } @@ -2278,11 +2355,6 @@ class Callback { /** Static thunk for passing as C-style function * @param func Callback to call passed as void pointer - * @param a0 An argument to be called with function func - * @param a1 An argument to be called with function func - * @param a2 An argument to be called with function func - * @return the value as determined by func which is of - * type and determined by the signiture of func */ static R thunk(void *func, A0 a0, A1 a1, A2 a2) { return static_cast(func)->call(a0, a1, a2); @@ -2368,8 +2440,7 @@ class Callback { /** Callback class based on template specialization * - * @note Synchronization level: Not protected - * @ingroup platform + * @Note Synchronization level: Not protected */ template class Callback { @@ -2468,38 +2539,50 @@ class Callback { } /** Create a Callback with a function object - * @param f Function object to attach + * @param func Function object to attach * @note The function object is limited to a single word of storage */ template - Callback(F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1, A2, A3))) { + Callback(F f, typename detail::enable_if< + detail::is_type::value && + sizeof(F) <= sizeof(uintptr_t) + >::type = detail::nil()) { generate(f); } /** Create a Callback with a function object - * @param f Function object to attach + * @param func Function object to attach * @note The function object is limited to a single word of storage */ template - Callback(const F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1, A2, A3) const)) { + Callback(const F f, typename detail::enable_if< + detail::is_type::value && + sizeof(F) <= sizeof(uintptr_t) + >::type = detail::nil()) { generate(f); } /** Create a Callback with a function object - * @param f Function object to attach + * @param func Function object to attach * @note The function object is limited to a single word of storage */ template - Callback(volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1, A2, A3) volatile)) { + Callback(volatile F f, typename detail::enable_if< + detail::is_type::value && + sizeof(F) <= sizeof(uintptr_t) + >::type = detail::nil()) { generate(f); } /** Create a Callback with a function object - * @param f Function object to attach + * @param func Function object to attach * @note The function object is limited to a single word of storage */ template - Callback(const volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1, A2, A3) const volatile)) { + Callback(const volatile F f, typename detail::enable_if< + detail::is_type::value && + sizeof(F) <= sizeof(uintptr_t) + >::type = detail::nil()) { generate(f); } @@ -2700,7 +2783,7 @@ class Callback { } /** Attach a function object - * @param f Function object to attach + * @param func Function object to attach * @note The function object is limited to a single word of storage * @deprecated * Replaced by simple assignment 'Callback cb = func' @@ -2708,13 +2791,16 @@ class Callback { template MBED_DEPRECATED_SINCE("mbed-os-5.4", "Replaced by simple assignment 'Callback cb = func") - void attach(F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1, A2, A3))) { + void attach(F f, typename detail::enable_if< + detail::is_type::value && + sizeof(F) <= sizeof(uintptr_t) + >::type = detail::nil()) { this->~Callback(); new (this) Callback(f); } /** Attach a function object - * @param f Function object to attach + * @param func Function object to attach * @note The function object is limited to a single word of storage * @deprecated * Replaced by simple assignment 'Callback cb = func' @@ -2722,13 +2808,16 @@ class Callback { template MBED_DEPRECATED_SINCE("mbed-os-5.4", "Replaced by simple assignment 'Callback cb = func") - void attach(const F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1, A2, A3) const)) { + void attach(const F f, typename detail::enable_if< + detail::is_type::value && + sizeof(F) <= sizeof(uintptr_t) + >::type = detail::nil()) { this->~Callback(); new (this) Callback(f); } /** Attach a function object - * @param f Function object to attach + * @param func Function object to attach * @note The function object is limited to a single word of storage * @deprecated * Replaced by simple assignment 'Callback cb = func' @@ -2736,13 +2825,16 @@ class Callback { template MBED_DEPRECATED_SINCE("mbed-os-5.4", "Replaced by simple assignment 'Callback cb = func") - void attach(volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1, A2, A3) volatile)) { + void attach(volatile F f, typename detail::enable_if< + detail::is_type::value && + sizeof(F) <= sizeof(uintptr_t) + >::type = detail::nil()) { this->~Callback(); new (this) Callback(f); } /** Attach a function object - * @param f Function object to attach + * @param func Function object to attach * @note The function object is limited to a single word of storage * @deprecated * Replaced by simple assignment 'Callback cb = func' @@ -2750,7 +2842,10 @@ class Callback { template MBED_DEPRECATED_SINCE("mbed-os-5.4", "Replaced by simple assignment 'Callback cb = func") - void attach(const volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1, A2, A3) const volatile)) { + void attach(const volatile F f, typename detail::enable_if< + detail::is_type::value && + sizeof(F) <= sizeof(uintptr_t) + >::type = detail::nil()) { this->~Callback(); new (this) Callback(f); } @@ -2855,12 +2950,6 @@ class Callback { /** Static thunk for passing as C-style function * @param func Callback to call passed as void pointer - * @param a0 An argument to be called with function func - * @param a1 An argument to be called with function func - * @param a2 An argument to be called with function func - * @param a3 An argument to be called with function func - * @return the value as determined by func which is of - * type and determined by the signiture of func */ static R thunk(void *func, A0 a0, A1 a1, A2 a2, A3 a3) { return static_cast(func)->call(a0, a1, a2, a3); @@ -2946,8 +3035,7 @@ class Callback { /** Callback class based on template specialization * - * @note Synchronization level: Not protected - * @ingroup platform + * @Note Synchronization level: Not protected */ template class Callback { @@ -3046,38 +3134,50 @@ class Callback { } /** Create a Callback with a function object - * @param f Function object to attach + * @param func Function object to attach * @note The function object is limited to a single word of storage */ template - Callback(F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1, A2, A3, A4))) { + Callback(F f, typename detail::enable_if< + detail::is_type::value && + sizeof(F) <= sizeof(uintptr_t) + >::type = detail::nil()) { generate(f); } /** Create a Callback with a function object - * @param f Function object to attach + * @param func Function object to attach * @note The function object is limited to a single word of storage */ template - Callback(const F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1, A2, A3, A4) const)) { + Callback(const F f, typename detail::enable_if< + detail::is_type::value && + sizeof(F) <= sizeof(uintptr_t) + >::type = detail::nil()) { generate(f); } /** Create a Callback with a function object - * @param f Function object to attach + * @param func Function object to attach * @note The function object is limited to a single word of storage */ template - Callback(volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1, A2, A3, A4) volatile)) { + Callback(volatile F f, typename detail::enable_if< + detail::is_type::value && + sizeof(F) <= sizeof(uintptr_t) + >::type = detail::nil()) { generate(f); } /** Create a Callback with a function object - * @param f Function object to attach + * @param func Function object to attach * @note The function object is limited to a single word of storage */ template - Callback(const volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1, A2, A3, A4) const volatile)) { + Callback(const volatile F f, typename detail::enable_if< + detail::is_type::value && + sizeof(F) <= sizeof(uintptr_t) + >::type = detail::nil()) { generate(f); } @@ -3278,7 +3378,7 @@ class Callback { } /** Attach a function object - * @param f Function object to attach + * @param func Function object to attach * @note The function object is limited to a single word of storage * @deprecated * Replaced by simple assignment 'Callback cb = func' @@ -3286,13 +3386,16 @@ class Callback { template MBED_DEPRECATED_SINCE("mbed-os-5.4", "Replaced by simple assignment 'Callback cb = func") - void attach(F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1, A2, A3, A4))) { + void attach(F f, typename detail::enable_if< + detail::is_type::value && + sizeof(F) <= sizeof(uintptr_t) + >::type = detail::nil()) { this->~Callback(); new (this) Callback(f); } /** Attach a function object - * @param f Function object to attach + * @param func Function object to attach * @note The function object is limited to a single word of storage * @deprecated * Replaced by simple assignment 'Callback cb = func' @@ -3300,13 +3403,16 @@ class Callback { template MBED_DEPRECATED_SINCE("mbed-os-5.4", "Replaced by simple assignment 'Callback cb = func") - void attach(const F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1, A2, A3, A4) const)) { + void attach(const F f, typename detail::enable_if< + detail::is_type::value && + sizeof(F) <= sizeof(uintptr_t) + >::type = detail::nil()) { this->~Callback(); new (this) Callback(f); } /** Attach a function object - * @param f Function object to attach + * @param func Function object to attach * @note The function object is limited to a single word of storage * @deprecated * Replaced by simple assignment 'Callback cb = func' @@ -3314,13 +3420,16 @@ class Callback { template MBED_DEPRECATED_SINCE("mbed-os-5.4", "Replaced by simple assignment 'Callback cb = func") - void attach(volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1, A2, A3, A4) volatile)) { + void attach(volatile F f, typename detail::enable_if< + detail::is_type::value && + sizeof(F) <= sizeof(uintptr_t) + >::type = detail::nil()) { this->~Callback(); new (this) Callback(f); } /** Attach a function object - * @param f Function object to attach + * @param func Function object to attach * @note The function object is limited to a single word of storage * @deprecated * Replaced by simple assignment 'Callback cb = func' @@ -3328,7 +3437,10 @@ class Callback { template MBED_DEPRECATED_SINCE("mbed-os-5.4", "Replaced by simple assignment 'Callback cb = func") - void attach(const volatile F f, MBED_ENABLE_IF_CALLBACK_COMPATIBLE(F, R (F::*)(A0, A1, A2, A3, A4) const volatile)) { + void attach(const volatile F f, typename detail::enable_if< + detail::is_type::value && + sizeof(F) <= sizeof(uintptr_t) + >::type = detail::nil()) { this->~Callback(); new (this) Callback(f); } @@ -3433,13 +3545,6 @@ class Callback { /** Static thunk for passing as C-style function * @param func Callback to call passed as void pointer - * @param a0 An argument to be called with function func - * @param a1 An argument to be called with function func - * @param a2 An argument to be called with function func - * @param a3 An argument to be called with function func - * @param a4 An argument to be called with function func - * @return the value as determined by func which is of - * type and determined by the signiture of func */ static R thunk(void *func, A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) { return static_cast(func)->call(a0, a1, a2, a3, a4); @@ -4544,3 +4649,6 @@ Callback callback(const volatile U *obj, R (*func)(const } // namespace mbed #endif + + +/** @}*/ diff --git a/platform/CircularBuffer.h b/platform/CircularBuffer.h index ef3fea7f658..c87c209101c 100644 --- a/platform/CircularBuffer.h +++ b/platform/CircularBuffer.h @@ -20,11 +20,11 @@ namespace mbed { /** \addtogroup platform */ +/** @{*/ /** Templated Circular buffer class * - * @note Synchronization level: Interrupt safe - * @ingroup platform + * @Note Synchronization level: Interrupt safe */ template class CircularBuffer { @@ -116,3 +116,4 @@ class CircularBuffer { #endif +/** @}*/ diff --git a/platform/DirHandle.h b/platform/DirHandle.h index f3b310ec0a2..7478b62b80e 100644 --- a/platform/DirHandle.h +++ b/platform/DirHandle.h @@ -21,7 +21,8 @@ #include "platform/FileHandle.h" namespace mbed { -/** \addtogroup platform */ +/** \addtogroup drivers */ +/** @{*/ /** Represents a directory stream. Objects of this type are returned @@ -38,8 +39,7 @@ namespace mbed { * reflect this. * * @note to create a directory, @see Dir - * @note Synchronization level: Set by subclass - * @ingroup platform + * @Note Synchronization level: Set by subclass */ class DirHandle { public: @@ -47,6 +47,7 @@ class DirHandle { /** Read the next directory entry * + * @param path The buffer to read the null terminated path name in to * @param ent The directory entry to fill out * @return 1 on reading a filename, 0 at end of directory, negative error on failure */ @@ -145,3 +146,5 @@ class DirHandle { } // namespace mbed #endif /* MBED_DIRHANDLE_H */ + +/** @}*/ diff --git a/platform/FileBase.h b/platform/FileBase.h index 9a451bb9bca..2101084cb74 100644 --- a/platform/FileBase.h +++ b/platform/FileBase.h @@ -26,19 +26,14 @@ typedef int FILEHANDLE; #include "platform/PlatformMutex.h" namespace mbed { -/** \addtogroup platform */ +/** \addtogroup drivers */ /** @{*/ typedef enum { FilePathType, FileSystemPathType } PathType; -/** @}*/ -/** - * @class FileBase - * @ingroup platform - */ class FileBase { public: FileBase(const char *name, PathType t); @@ -67,3 +62,4 @@ class FileBase { #endif +/** @}*/ diff --git a/platform/FileHandle.h b/platform/FileHandle.h index cf6e3eb7e29..e131599600a 100644 --- a/platform/FileHandle.h +++ b/platform/FileHandle.h @@ -22,7 +22,8 @@ typedef int FILEHANDLE; #include "platform/platform.h" namespace mbed { -/** \addtogroup platform */ +/** \addtogroup drivers */ +/** @{*/ /** Class FileHandle @@ -33,7 +34,6 @@ namespace mbed { * * @note to create a file, @see File * @note Synchronization level: Set by subclass - * @ingroup platform */ class FileHandle { public: @@ -155,6 +155,7 @@ class FileHandle { }; +/** @}*/ } // namespace mbed #endif diff --git a/platform/FileLike.h b/platform/FileLike.h index e65e611aa96..a249b68c905 100644 --- a/platform/FileLike.h +++ b/platform/FileLike.h @@ -21,15 +21,15 @@ #include "platform/FileHandle.h" namespace mbed { -/** \addtogroup platform */ +/** \addtogroup drivers */ +/** @{*/ /* Class FileLike * A file-like object is one that can be opened with fopen by * fopen("/name", mode). * - * @note Synchronization level: Set by subclass - * @ingroup platform + * @Note Synchronization level: Set by subclass */ class FileLike : public FileHandle, public FileBase { public: @@ -42,6 +42,7 @@ class FileLike : public FileHandle, public FileBase { }; +/** @}*/ } // namespace mbed #endif diff --git a/platform/FilePath.h b/platform/FilePath.h index 377e3b6f4c2..9daa1597c69 100644 --- a/platform/FilePath.h +++ b/platform/FilePath.h @@ -22,12 +22,9 @@ #include "platform/FileLike.h" namespace mbed { -/** \addtogroup platform */ +/** \addtogroup drivers */ +/** @{*/ -/** - * @class FileSystem - * @ingroup platform - */ class FileSystem; class FilePath { @@ -51,3 +48,5 @@ class FilePath { } // namespace mbed #endif + +/** @}*/ diff --git a/platform/FileSystemLike.h b/platform/FileSystemLike.h index 358b4ea6fc5..b9949c2a878 100644 --- a/platform/FileSystemLike.h +++ b/platform/FileSystemLike.h @@ -23,7 +23,8 @@ #include "platform/DirHandle.h" namespace mbed { -/** \addtogroup platform */ +/** \addtogroup drivers */ +/** @{*/ /** A filesystem-like object is one that can be used to open files * though it by fopen("/name/filename", mode) @@ -31,8 +32,7 @@ namespace mbed { * Implementations must define at least open (the default definitions * of the rest of the functions just return error values). * - * @note Synchronization level: Set by subclass - * @ingroup platform + * @Note Synchronization level: Set by subclass */ class FileSystemLike : public FileBase { @@ -69,7 +69,7 @@ class FileSystemLike : public FileBase { /** Remove a file from the filesystem. * * @param filename the name of the file to remove. - * @returns 0 on success, -1 on failure. + * @param returns 0 on success, -1 on failure. */ virtual int remove(const char *filename) { (void) filename; return -1; }; @@ -120,3 +120,5 @@ class FileSystemLike : public FileBase { } // namespace mbed #endif + +/** @}*/ diff --git a/platform/FunctionPointer.h b/platform/FunctionPointer.h index a57195f7a83..8d685479a1a 100644 --- a/platform/FunctionPointer.h +++ b/platform/FunctionPointer.h @@ -23,13 +23,11 @@ namespace mbed { /** \addtogroup platform */ +/** @{*/ // Declarations for backwards compatibility // To be foward compatible, code should adopt the Callback class -/** - * @ingroup platform - */ template class FunctionPointerArg1 : public Callback { public: @@ -61,9 +59,6 @@ class FunctionPointerArg1 : public Callback { } }; -/** - * @ingroup platform - */ template class FunctionPointerArg1 : public Callback { public: @@ -101,3 +96,5 @@ typedef FunctionPointerArg1 FunctionPointer; } // namespace mbed #endif + +/** @}*/ diff --git a/platform/LocalFileSystem.h b/platform/LocalFileSystem.h index 2aeb4f03c50..526c2d1f223 100644 --- a/platform/LocalFileSystem.h +++ b/platform/LocalFileSystem.h @@ -24,16 +24,11 @@ #include "platform/PlatformMutex.h" namespace mbed { -/** \addtogroup platform */ +/** \addtogroup drivers */ /** @{*/ FILEHANDLE local_file_open(const char* name, int flags); -/** @}*/ -/** - * @class LocalFileHandle - * @ingroup platform - */ class LocalFileHandle : public FileHandle { public: @@ -67,7 +62,7 @@ class LocalFileHandle : public FileHandle { * mbed Microcontroller. Once created, the standard C file access functions are used to open, * read and write files. * - * @note Synchronization level: Thread safe + * @Note Synchronization level: Thread safe * * Example: * @code @@ -96,7 +91,6 @@ class LocalFileHandle : public FileHandle { * * The drive will only re-appear when the microcontroller program exists. Note that if the program does * not exit, you will need to hold down reset on the mbed Microcontroller to be able to see the drive again! - * @ingroup platform */ class LocalFileSystem : public FileSystemLike { // No modifiable state @@ -117,3 +111,4 @@ class LocalFileSystem : public FileSystemLike { #endif +/** @}*/ diff --git a/platform/PlatformMutex.h b/platform/PlatformMutex.h index 3746ee80d76..19b0e7f7907 100644 --- a/platform/PlatformMutex.h +++ b/platform/PlatformMutex.h @@ -1,5 +1,6 @@ /** \addtogroup platform */ +/** @{*/ /* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * @@ -23,7 +24,6 @@ typedef rtos::Mutex PlatformMutex; #else /** A stub mutex for when an RTOS is not present - * @ingroup platform */ class PlatformMutex { public: @@ -48,3 +48,4 @@ class PlatformMutex { #endif +/** @}*/ diff --git a/platform/SingletonPtr.h b/platform/SingletonPtr.h index e576b2632d0..ea96b78917a 100644 --- a/platform/SingletonPtr.h +++ b/platform/SingletonPtr.h @@ -55,20 +55,18 @@ inline static void singleton_unlock(void) osMutexRelease (singleton_mutex_id); #endif } -/** @}*/ /** Utility class for creating an using a singleton * - * @note Synchronization level: Thread safe + * @Note Synchronization level: Thread safe * - * @note: This class must only be used in a static context - + * @Note: This class must only be used in a static context - * this class must never be allocated or created on the * stack. * - * @note: This class is lazily initialized on first use. + * @Note: This class is lazily initialized on first use. * This class is a POD type so if it is not used it will * be garbage collected. - * @ingroup platform */ template struct SingletonPtr { @@ -109,3 +107,4 @@ struct SingletonPtr { #endif +/** @}*/ diff --git a/platform/Stream.cpp b/platform/Stream.cpp index 299f9ae8ca0..76568712e78 100644 --- a/platform/Stream.cpp +++ b/platform/Stream.cpp @@ -14,8 +14,6 @@ * limitations under the License. */ #include "platform/Stream.h" -#include "platform/mbed_error.h" -#include namespace mbed { @@ -25,11 +23,7 @@ Stream::Stream(const char *name) : FileLike(name), _file(NULL) { char buf[12]; /* :0x12345678 + null byte */ std::sprintf(buf, ":%p", this); _file = std::fopen(buf, "w+"); - if (_file) { - mbed_set_unbuffered_stream(_file); - } else { - error("Stream obj failure, errno=%d\r\n", errno); - } + mbed_set_unbuffered_stream(_file); } Stream::~Stream() { diff --git a/platform/Stream.h b/platform/Stream.h index 9fe100a418f..cbb25a9c615 100644 --- a/platform/Stream.h +++ b/platform/Stream.h @@ -22,18 +22,16 @@ #include namespace mbed { -/** \addtogroup platform */ +/** \addtogroup drivers */ /** @{*/ extern void mbed_set_unbuffered_stream(FILE *_file); extern int mbed_getc(FILE *_file); extern char* mbed_gets(char *s, int size, FILE *_file); -/** @}*/ /** File stream * - * @note Synchronization level: Set by subclass - * @ingroup platform + * @Note Synchronization level: Set by subclass */ class Stream : public FileLike { @@ -90,3 +88,4 @@ class Stream : public FileLike { #endif +/** @}*/ diff --git a/platform/Transaction.h b/platform/Transaction.h index 8e262368800..f866c898208 100644 --- a/platform/Transaction.h +++ b/platform/Transaction.h @@ -21,9 +21,9 @@ namespace mbed { /** \addtogroup platform */ +/** @{*/ /** Transaction structure - * @ingroup platform */ typedef struct { void *tx_buffer; /**< Tx buffer */ @@ -37,8 +37,7 @@ typedef struct { /** Transaction class defines a transaction. * - * @note Synchronization level: Not protected - * @ingroup platform + * @Note Synchronization level: Not protected */ template class Transaction { @@ -76,3 +75,5 @@ class Transaction { } #endif + +/** @}*/ diff --git a/platform/mbed_application.h b/platform/mbed_application.h index 77a6c45cb38..6ee0bfd07d7 100644 --- a/platform/mbed_application.h +++ b/platform/mbed_application.h @@ -21,7 +21,7 @@ #include -#define MBED_APPLICATION_SUPPORT defined(__CORTEX_M3) || defined(__CORTEX_M4) || defined(__CORTEX_M7) +#define MBED_APPLICATION_SUPPORT (defined(__CORTEX_M3) || defined(__CORTEX_M4) || defined(__CORTEX_M7)) #if MBED_APPLICATION_SUPPORT #ifdef __cplusplus extern "C" { diff --git a/platform/mbed_board.c b/platform/mbed_board.c index 3444b8bd43a..16ca2944a6d 100644 --- a/platform/mbed_board.c +++ b/platform/mbed_board.c @@ -75,17 +75,20 @@ void mbed_error_printf(const char* format, ...) { void mbed_error_vfprintf(const char * format, va_list arg) { #if DEVICE_SERIAL -#define ERROR_BUF_SIZE (128) + +#if MBED_CONF_PLATFORM_STDIO_CONVERT_NEWLINES + char stdio_out_prev; +#endif + core_util_critical_section_enter(); - char buffer[ERROR_BUF_SIZE]; - int size = vsnprintf(buffer, ERROR_BUF_SIZE, format, arg); + char buffer[128]; + int size = vsprintf(buffer, format, arg); if (size > 0) { if (!stdio_uart_inited) { serial_init(&stdio_uart, STDIO_UART_TX, STDIO_UART_RX); } #if MBED_CONF_PLATFORM_STDIO_CONVERT_NEWLINES - char stdio_out_prev = '\0'; - for (int i = 0; i < size; i++) { + for (unsigned int i = 0; i < size; i++) { if (buffer[i] == '\n' && stdio_out_prev != '\r') { serial_putc(&stdio_uart, '\r'); } @@ -93,7 +96,7 @@ void mbed_error_vfprintf(const char * format, va_list arg) { stdio_out_prev = buffer[i]; } #else - for (int i = 0; i < size; i++) { + for (unsigned int i = 0; i < size; i++) { serial_putc(&stdio_uart, buffer[i]); } #endif diff --git a/platform/mbed_critical.h b/platform/mbed_critical.h index dd4cbe6fb33..57816d1cacf 100644 --- a/platform/mbed_critical.h +++ b/platform/mbed_critical.h @@ -33,7 +33,7 @@ extern "C" { /** Determine the current interrupts enabled state * * This function can be called to determine whether or not interrupts are currently enabled. - * @note + * \note * NOTE: * This function works for both cortex-A and cortex-M, although the underlyng implementation * differs. @@ -44,7 +44,7 @@ bool core_util_are_interrupts_enabled(void); /** Mark the start of a critical section * * This function should be called to mark the start of a critical section of code. - * @note + * \note * NOTES: * 1) The use of this style of critical section is targetted at C based implementations. * 2) These critical sections can be nested. @@ -57,7 +57,7 @@ void core_util_critical_section_enter(void); /** Mark the end of a critical section * * This function should be called to mark the end of a critical section of code. - * @note + * \note * NOTES: * 1) The use of this style of critical section is targetted at C based implementations. * 2) These critical sections can be nested. @@ -82,7 +82,7 @@ void core_util_critical_section_exit(void); * @param[in,out] expectedCurrentValue A pointer to some location holding the * expected current value of the data being set atomically. * The computed 'desiredValue' should be a function of this current value. - * @note: This is an in-out parameter. In the + * @Note: This is an in-out parameter. In the * failure case of atomic_cas (where the * destination isn't set), the pointee of expectedCurrentValue is * updated with the current value. @@ -105,7 +105,7 @@ void core_util_critical_section_exit(void); * return true * } * - * @note: In the failure case (where the destination isn't set), the value + * @Note: In the failure case (where the destination isn't set), the value * pointed to by expectedCurrentValue is still updated with the current value. * This property helps writing concise code for the following incr: * @@ -135,7 +135,7 @@ bool core_util_atomic_cas_u8(uint8_t *ptr, uint8_t *expectedCurrentValue, uint8_ * @param[in,out] expectedCurrentValue A pointer to some location holding the * expected current value of the data being set atomically. * The computed 'desiredValue' should be a function of this current value. - * @note: This is an in-out parameter. In the + * @Note: This is an in-out parameter. In the * failure case of atomic_cas (where the * destination isn't set), the pointee of expectedCurrentValue is * updated with the current value. @@ -158,7 +158,7 @@ bool core_util_atomic_cas_u8(uint8_t *ptr, uint8_t *expectedCurrentValue, uint8_ * return true * } * - * @note: In the failure case (where the destination isn't set), the value + * @Note: In the failure case (where the destination isn't set), the value * pointed to by expectedCurrentValue is still updated with the current value. * This property helps writing concise code for the following incr: * @@ -188,7 +188,7 @@ bool core_util_atomic_cas_u16(uint16_t *ptr, uint16_t *expectedCurrentValue, uin * @param[in,out] expectedCurrentValue A pointer to some location holding the * expected current value of the data being set atomically. * The computed 'desiredValue' should be a function of this current value. - * @note: This is an in-out parameter. In the + * @Note: This is an in-out parameter. In the * failure case of atomic_cas (where the * destination isn't set), the pointee of expectedCurrentValue is * updated with the current value. @@ -211,7 +211,7 @@ bool core_util_atomic_cas_u16(uint16_t *ptr, uint16_t *expectedCurrentValue, uin * return true * } * - * @note: In the failure case (where the destination isn't set), the value + * @Note: In the failure case (where the destination isn't set), the value * pointed to by expectedCurrentValue is still updated with the current value. * This property helps writing concise code for the following incr: * @@ -241,7 +241,7 @@ bool core_util_atomic_cas_u32(uint32_t *ptr, uint32_t *expectedCurrentValue, uin * @param[in,out] expectedCurrentValue A pointer to some location holding the * expected current value of the data being set atomically. * The computed 'desiredValue' should be a function of this current value. - * @note: This is an in-out parameter. In the + * @Note: This is an in-out parameter. In the * failure case of atomic_cas (where the * destination isn't set), the pointee of expectedCurrentValue is * updated with the current value. @@ -264,7 +264,7 @@ bool core_util_atomic_cas_u32(uint32_t *ptr, uint32_t *expectedCurrentValue, uin * return true * } * - * @note: In the failure case (where the destination isn't set), the value + * @Note: In the failure case (where the destination isn't set), the value * pointed to by expectedCurrentValue is still updated with the current value. * This property helps writing concise code for the following incr: * diff --git a/platform/mbed_debug.h b/platform/mbed_debug.h index 761c1eb99f6..392286a15e3 100644 --- a/platform/mbed_debug.h +++ b/platform/mbed_debug.h @@ -18,49 +18,49 @@ */ #ifndef MBED_DEBUG_H #define MBED_DEBUG_H -#if DEVICE_STDIO_MESSAGES -#include -#include -#endif +#include "device.h" #ifdef __cplusplus extern "C" { #endif +#if DEVICE_STDIO_MESSAGES +#include +#include /** Output a debug message * * @param format printf-style format string, followed by variables */ static inline void debug(const char *format, ...) { -#if DEVICE_STDIO_MESSAGES && !defined(NDEBUG) va_list args; va_start(args, format); vfprintf(stderr, format, args); va_end(args); -#endif } - /** Conditionally output a debug message * - * NOTE: If the condition is constant false (== 0) and the compiler optimization + * NOTE: If the condition is constant false (!= 1) and the compiler optimization * level is greater than 0, then the whole function will be compiled away. * - * @param condition output only if condition is true (!= 0) + * @param condition output only if condition is true (== 1) * @param format printf-style format string, followed by variables */ static inline void debug_if(int condition, const char *format, ...) { -#if DEVICE_STDIO_MESSAGES && !defined(NDEBUG) - if (condition) { + if (condition == 1) { va_list args; va_start(args, format); vfprintf(stderr, format, args); va_end(args); } -#endif } +#else +static inline void debug(const char *format, ...) {} +static inline void debug_if(int condition, const char *format, ...) {} + +#endif #ifdef __cplusplus } diff --git a/platform/mbed_error.h b/platform/mbed_error.h index 15fd5e80648..30643e118e4 100644 --- a/platform/mbed_error.h +++ b/platform/mbed_error.h @@ -53,7 +53,7 @@ * if(x >= 5) { * error("expected x to be less than 5, but got %d", x); * } - * @endcode + * #endcode */ #ifdef __cplusplus diff --git a/platform/mbed_interface.h b/platform/mbed_interface.h index bb3e2a34891..f39eb4724c8 100644 --- a/platform/mbed_interface.h +++ b/platform/mbed_interface.h @@ -115,14 +115,14 @@ void mbed_die(void); /** Print out an error message. This is typically called when * hanlding a crash. * - * @note Synchronization level: Interrupt safe + * @Note Synchronization level: Interrupt safe */ void mbed_error_printf(const char* format, ...); /** Print out an error message. Similar to mbed_error_printf * but uses a va_list. * - * @note Synchronization level: Interrupt safe + * @Note Synchronization level: Interrupt safe */ void mbed_error_vfprintf(const char * format, va_list arg); diff --git a/platform/mbed_mem_trace.h b/platform/mbed_mem_trace.h index 8efc05c7ca6..11610067432 100644 --- a/platform/mbed_mem_trace.h +++ b/platform/mbed_mem_trace.h @@ -80,7 +80,7 @@ void *mbed_mem_trace_malloc(void *res, size_t size, void *caller); * @param res the result of running 'realloc'. * @param ptr the 'ptr' argument given to 'realloc'. * @param size the 'size' argument given to 'realloc'. - * @param caller the caller of the memory operation. + * * @return 'res' (the first argument). */ void *mbed_mem_trace_realloc(void *res, void *ptr, size_t size, void *caller); @@ -88,10 +88,10 @@ void *mbed_mem_trace_realloc(void *res, void *ptr, size_t size, void *caller); /** * Trace a call to 'calloc'. * @param res the result of running 'calloc'. - * @param num the 'nmemb' argument given to 'calloc'. + * @param nmemb the 'nmemb' argument given to 'calloc'. * @param size the 'size' argument given to 'calloc'. * @param caller the caller of the memory operation. - * @return 'res' (the first argument). + * @Return 'res' (the first argument). */ void *mbed_mem_trace_calloc(void *res, size_t num, size_t size, void *caller); @@ -108,13 +108,13 @@ void mbed_mem_trace_free(void *ptr, void *caller); * * The default callback outputs trace data using 'printf', in a format that's * easily parsable by an external tool. For each memory operation, the callback - * outputs a line that begins with "#:<0xresult>;<0xcaller>-": + * outputs a line that begins with '#:<0xresult>;<0xcaller>-': * * - 'op' identifies the memory operation ('m' for 'malloc', 'r' for 'realloc', * 'c' for 'calloc' and 'f' for 'free'). * - 'result' (base 16) is the result of the memor operation. This is always NULL * for 'free', since 'free' doesn't return anything. - * - 'caller' (base 16) is the caller of the memory operation. Note that the value + * -'caller' (base 16) is the caller of the memory operation. Note that the value * of 'caller' might be unreliable. * * The rest of the output depends on the operation being traced: @@ -126,9 +126,9 @@ void mbed_mem_trace_free(void *ptr, void *caller); * * Examples: * - * - "#m:0x20003240;0x600d-50" encodes a 'malloc' that returned 0x20003240, was called + * - '#m:0x20003240;0x600d-50' encodes a 'malloc' that returned 0x20003240, was called * by the instruction at 0x600D with a the 'size' argument equal to 50. - * - "#f:0x0;0x602f-0x20003240" encodes a 'free' that was called by the instruction at + * - '#f:0x0;0x602f-0x20003240' encodes a 'free' that was called by the instruction at * 0x602f with the 'ptr' argument equal to 0x20003240. */ void mbed_mem_trace_default_callback(uint8_t op, void *res, void *caller, ...); diff --git a/platform/mbed_retarget.cpp b/platform/mbed_retarget.cpp index 33e02cbd6d3..3297fe1882b 100644 --- a/platform/mbed_retarget.cpp +++ b/platform/mbed_retarget.cpp @@ -120,7 +120,6 @@ static void init_serial() { #endif } -#if MBED_CONF_FILESYSTEM_PRESENT static inline int openmode_to_posix(int openmode) { int posix = openmode; #ifdef __ARMCC_VERSION @@ -155,7 +154,6 @@ static inline int openmode_to_posix(int openmode) { #endif return posix; } -#endif extern "C" WEAK void mbed_sdk_init(void); extern "C" WEAK void mbed_sdk_init(void) { @@ -766,6 +764,9 @@ extern "C" uint32_t __HeapLimit; #undef errno extern "C" int errno; +// For ARM7 only +register unsigned char * stack_ptr __asm ("sp"); + // Dynamic memory allocation related syscall. #if defined(TARGET_NUMAKER_PFM_NUC472) || defined(TARGET_NUMAKER_PFM_M453) // Overwrite _sbrk() to support two region model (heap and stack are two distinct regions). @@ -782,7 +783,9 @@ extern "C" caddr_t _sbrk(int incr) { unsigned char* prev_heap = heap; unsigned char* new_heap = heap + incr; -#if defined(TARGET_CORTEX_A) +#if defined(TARGET_ARM7) + if (new_heap >= stack_ptr) { +#elif defined(TARGET_CORTEX_A) if (new_heap >= (unsigned char*)&__HeapLimit) { /* __HeapLimit is end of heap section */ #else if (new_heap >= (unsigned char*)__get_MSP()) { diff --git a/platform/mbed_rtc_time.h b/platform/mbed_rtc_time.h index 84a3739ec32..fef0292f1c1 100644 --- a/platform/mbed_rtc_time.h +++ b/platform/mbed_rtc_time.h @@ -61,7 +61,7 @@ extern "C" { * * @param t Number of seconds since January 1, 1970 (the UNIX timestamp) * - * @note Synchronization level: Thread safe + * @Note Synchronization level: Thread safe * * Example: * @code @@ -76,7 +76,7 @@ void set_time(time_t t); /** Attach an external RTC to be used for the C time functions * - * @note Synchronization level: Thread safe + * @Note Synchronization level: Thread safe * * @param read_rtc pointer to function which returns current UNIX timestamp * @param write_rtc pointer to function which sets current UNIX timestamp, can be NULL diff --git a/platform/mbed_semihost_api.c b/platform/mbed_semihost_api.c index 06c6777ab8d..ff1c6172f66 100644 --- a/platform/mbed_semihost_api.c +++ b/platform/mbed_semihost_api.c @@ -152,11 +152,10 @@ int semihost_connected(void) { #endif int semihost_disabledebug(void) { - uint32_t args[1]; #if !(DEVICE_DEBUG_AWARENESS) is_debugger_attached = 0; #endif - return __semihost(USR_DISABLEDEBUG, &args); + return __semihost(USR_DISABLEDEBUG, NULL); } #endif diff --git a/platform/mbed_sleep.h b/platform/mbed_sleep.h index 91546259da2..013bef1db1f 100644 --- a/platform/mbed_sleep.h +++ b/platform/mbed_sleep.h @@ -28,8 +28,7 @@ extern "C" { /** Send the microcontroller to sleep * * @note This function can be a noop if not implemented by the platform. - * @note This function will be a noop in debug mode (debug build profile when MBED_DEBUG is defined). - * @note This function will be a noop while uVisor is in use. + * @note This function will only put device to sleep in release mode (small profile or when NDEBUG is defined). * * The processor is setup ready for sleep, and sent to sleep using __WFI(). In this mode, the * system clock to the core is stopped until a reset or an interrupt occurs. This eliminates @@ -45,20 +44,17 @@ extern "C" { */ __INLINE static void sleep(void) { -#if !(defined(FEATURE_UVISOR) && defined(TARGET_UVISOR_SUPPORTED)) -#ifndef MBED_DEBUG +#ifdef NDEBUG #if DEVICE_SLEEP hal_sleep(); #endif /* DEVICE_SLEEP */ -#endif /* MBED_DEBUG */ -#endif /* !(defined(FEATURE_UVISOR) && defined(TARGET_UVISOR_SUPPORTED)) */ +#endif /* NDEBUG */ } /** Send the microcontroller to deep sleep * * @note This function can be a noop if not implemented by the platform. - * @note This function will be a noop in debug mode (debug build profile when MBED_DEBUG is defined) - * @note This function will be a noop while uVisor is in use. + * @note This function will only put device to sleep in release mode (small profile or when NDEBUG is defined). * * This processor is setup ready for deep sleep, and sent to sleep using __WFI(). This mode * has the same sleep features as sleep plus it powers down peripherals and clocks. All state @@ -73,13 +69,11 @@ __INLINE static void sleep(void) */ __INLINE static void deepsleep(void) { -#if !(defined(FEATURE_UVISOR) && defined(TARGET_UVISOR_SUPPORTED)) -#ifndef MBED_DEBUG +#ifdef NDEBUG #if DEVICE_SLEEP hal_deepsleep(); #endif /* DEVICE_SLEEP */ -#endif /* MBED_DEBUG */ -#endif /* !(defined(FEATURE_UVISOR) && defined(TARGET_UVISOR_SUPPORTED)) */ +#endif /* NDEBUG */ } #ifdef __cplusplus diff --git a/platform/mbed_wait_api.h b/platform/mbed_wait_api.h index 91619def4ac..39f03bfb0f3 100644 --- a/platform/mbed_wait_api.h +++ b/platform/mbed_wait_api.h @@ -41,7 +41,6 @@ extern "C" { * wait(0.5); * } * } - * @endcode */ /** Waits for a number of seconds, with microsecond resolution (within diff --git a/platform/toolchain.h b/platform/toolchain.h index 6fbef808cab..5f1eafe2a9d 100644 --- a/platform/toolchain.h +++ b/platform/toolchain.h @@ -24,5 +24,3 @@ #include "platform/mbed_toolchain.h" #endif - -/** @}*/ diff --git a/rtos/rtos.h b/rtos/rtos.h index c3da7997cdd..54b31263d09 100644 --- a/rtos/rtos.h +++ b/rtos/rtos.h @@ -40,6 +40,10 @@ using namespace rtos; */ #include "mbed.h" +#if (MBED_LIBRARY_VERSION < 122) +#error "This version of RTOS requires mbed library version > 121" +#endif + #endif /** @}*/ diff --git a/rtos/rtx/TARGET_ARM7/ARM7/TOOLCHAIN_GCC/HAL_CM0.S b/rtos/rtx/TARGET_ARM7/ARM7/TOOLCHAIN_GCC/HAL_CM0.S new file mode 100644 index 00000000000..029de0f3729 --- /dev/null +++ b/rtos/rtx/TARGET_ARM7/ARM7/TOOLCHAIN_GCC/HAL_CM0.S @@ -0,0 +1,329 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: HAL_CM0.S + * Purpose: Hardware Abstraction Layer for ARM7TDMI + * Rev.: V1.0 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 ARM Germany GmbH + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + + .file "HAL_CM0.S" + .syntax unified + + .equ TCB_TSTACK, 40 + + +/*---------------------------------------------------------------------------- + * Functions + *---------------------------------------------------------------------------*/ + + .arm + + .section ".text" + .align 2 + +/*-------------------------- Save Context --------------------------------*/ +/* MUST be called the first */ +.macro SaveContext + + /* Push R0 as we are going to use the register. */ \ + STMDB SP!, {R0} + + /* Set R0 to SP(user) */ + STMDB SP,{SP}^ + NOP + SUB SP, SP, #4 + LDMIA SP!,{R0} + + /* Push the LR return address onto the user stack. */ + STMDB R0!, {LR} + + /* Now we have saved LR we can use it instead of R0. */ + MOV LR, R0 + + /* Pop R0 so we can save it onto the system mode stack. */ + LDMIA SP!, {R0} + + /* Push all the system mode registers onto the task stack. */ + STMDB LR,{R0-R12,LR}^ /* LR can not be changed because user's LR is used*/ + NOP /* pass 1 cycle before changing LR */ + SUB LR, LR, #14*4 /* change LR now -15 dwords (R0-R14)*/ + + /* Push the SPSR onto the task stack. */ + MRS R0, SPSR + STMDB LR!, {R0} + + /* Store the new top of stack for the task. */ + LDR R0,=os_tsk + LDR R0, [R0] /* R0 = (tcb) os_tsk.run */ + STR LR, [R0, TCB_TSTACK] /* tcb.tsk_stack = SP(user) */ +.endm + +/*-------------------------- Restore Context --------------------------------*/ + .type RestoreContext, %function + .global RestoreContext +RestoreContext: + .fnstart + .cantunwind + /* Set the LR to the task stack. */ + LDR R0,=os_tsk + LDR R1, [R0, 4] /* R1 = (tcb) os_tsk.new */ + STR R1, [R0] /* os_tsk.run = os_tsk_newk */ + LDR LR, [R1, TCB_TSTACK] /* LR = tcb.tsk_stack */ + + /* Get the SPSR from the stack. */ + LDMFD LR!, {R0} /* SPSR */ + MSR SPSR, R0 + + /* Restore all system mode registers for the task. */ + LDMFD LR, {R0-R12,LR}^ + NOP + + ADD LR, LR, 15*4 /* increase stack pointer */ + /* Set SP(user) to LR */ + STMDB SP!,{LR} + LDMIA SP,{SP}^ + NOP + ADD SP, SP, #4 + + /* Restore the return address. */ + LDR LR, [LR,#-4] /* last dword is task's PC register */ + + /* And return - correcting the offset in the LR to obtain the */ + /* correct address. */ + SUBS PC, LR, #4 + +/*-------------------------- End --------------------------------*/ + .fnend + .size RestoreContext, .-RestoreContext + + + +/*--------------------------- rt_set_PSP ------------------------------------*/ + +# void rt_set_PSP (U32 stack); + + .type rt_set_PSP, %function + .global rt_set_PSP +rt_set_PSP: + .fnstart + .cantunwind + + MOV SP,R0 + BX LR + + .fnend + .size rt_set_PSP, .-rt_set_PSP + + +/*--------------------------- rt_get_PSP ------------------------------------*/ + +# U32 rt_get_PSP (void); + + .type rt_get_PSP, %function + .global rt_get_PSP +rt_get_PSP: + .fnstart + .cantunwind + + MOV R0,SP + BX LR + + .fnend + .size rt_get_PSP, .-rt_get_PSP + + + +/*--------------------------- _alloc_box ------------------------------------*/ + +# void *_alloc_box (void *box_mem); + /* Function wrapper for Unprivileged/Privileged mode. */ + + .type _alloc_box, %function + .global _alloc_box +_alloc_box: + .fnstart + .cantunwind + + LDR R3,=rt_alloc_box + MOV R12, R3 + MRS R3, CPSR + AND R3, 0x1F + CMP R3, 0x12 /* IRQ mode*/ + BNE PrivilegedA + CMP R3, 0x1F /* System mode*/ + BNE PrivilegedA + SVC 0 + BX LR +PrivilegedA: + BX R12 + + .fnend + .size _alloc_box, .-_alloc_box + + +/*--------------------------- _free_box -------------------------------------*/ + +# int _free_box (void *box_mem, void *box); + /* Function wrapper for Unprivileged/Privileged mode. */ + + .type _free_box, %function + .global _free_box +_free_box: + .fnstart + .cantunwind + + LDR R3,=rt_free_box + MOV R12, R3 + MRS R3, CPSR + AND R3, 0x1F + CMP R3, 0x12 /* IRQ mode*/ + BNE PrivilegedA + CMP R3, 0x1F /* System mode*/ + BNE PrivilegedA + SVC 0 + BX LR +PrivilegedF: + BX R12 + + .fnend + .size _free_box, .-_free_box + + +/*-------------------------- SVC_Handler ------------------------------------*/ + +# void SVC_Handler (void); + + .type SVC_Handler, %function + .global SVC_Handler +SVC_Handler: + .fnstart + .cantunwind + /* Within an IRQ ISR the link register has an offset from the true return + address, but an SWI ISR does not. Add the offset manually so the same + ISR return code can be used in both cases. */ + + STMFD SP!, {R0,LR} /* Store registers. */ + ADD LR, LR, #4 /* Align LR with IRQ handler */ + SaveContext + MOV R11, LR /* Save Task Stack Pointer */ + LDMFD SP!, {R0,LR} /* Restore registers and return. */ + STMFD SP!, {R11} /* Save Task Stack Pointer */ + + LDR R5, [LR,#-4] /* Calculate address of SWI instruction and load it into r5. */ + BIC R5, R5,#0xff000000 /* Mask off top 8 bits of instruction to give SWI number. */ + + CMP R5, #0 + BNE SVC_User /* User SVC Number > 0 */ + MOV LR, PC /* set LR to return address */ + BX R12 /* Call SVC Function */ + + LDMFD SP!, {R11} /* Load Task Stack Pointer */ + STMIB R11!, {R0-R3} /* Store return values to Task stack */ + +SVC_Exit: + B RestoreContext /* return to the task */ + + /*------------------- User SVC ------------------------------*/ + +SVC_User: + LDR R6,=SVC_Count + LDR R6,[R6] + CMP R5,R6 + LDMFDHI SP!, {R11} + BHI SVC_Done /* Overflow */ + + LDR R4,=SVC_Table - 4 + LSLS R5,R5,#2 + LDR R4,[R4,R5] /* Load SVC Function Address */ + /* R0-R3,R12 are unchanged */ + MOV LR, PC /* set LR to return address */ + BX R4 /* Call SVC Function */ + + LDMFD SP!, {R11} /* Load Task Stack Pointer */ + BEQ SVC_Exit /* no need in return values */ + + STMIB R11!, {R0-R3} /* Store return values to Task stack */ +SVC_Done: + B RestoreContext /* return to the task */ + + .fnend + .size SVC_Handler, .-SVC_Handler + + +/*-------------------------- IRQ_Handler ---------------------------------*/ + +# void IRQ_Handler (void); + + .type IRQ_Handler, %function + .global IRQ_Handler +IRQ_Handler: + .fnstart + .cantunwind + + SaveContext + + MOV R0, #0xFFFFFF00 + LDR R0, [R0] /* Load address of raised IRQ handler*/ + + MOV LR, PC + BX R0 + + MOV R0, #0xFFFFFF00 + STR R0, [R0] /* Clear interrupt */ + + B RestoreContext + + .fnend + .size IRQ_Handler, .-IRQ_Handler + +/*-------------------------- SysTick_Handler --------------------------------*/ + +# void SysTick_Handler (void); + + .type SysTick_Handler, %function + .global SysTick_Handler +SysTick_Handler: + .fnstart + .cantunwind + + PUSH {LR} + BL rt_systick + POP {LR} + BX LR /* return to IRQ handler */ + +/*-------------------------- End --------------------------------*/ + .fnend + .size SysTick_Handler, .-SysTick_Handler + + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ + +.end \ No newline at end of file diff --git a/rtos/rtx/TARGET_ARM7/ARM7/TOOLCHAIN_GCC/SVC_Table.S b/rtos/rtx/TARGET_ARM7/ARM7/TOOLCHAIN_GCC/SVC_Table.S new file mode 100644 index 00000000000..1942f4c81f6 --- /dev/null +++ b/rtos/rtx/TARGET_ARM7/ARM7/TOOLCHAIN_GCC/SVC_Table.S @@ -0,0 +1,56 @@ +;/*---------------------------------------------------------------------------- +; * RL-ARM - RTX +; *---------------------------------------------------------------------------- +; * Name: SVC_TABLE.S +; * Purpose: Pre-defined SVC Table for Cortex-M +; * Rev.: V4.60 +; *---------------------------------------------------------------------------- +; * +; * Copyright (c) 1999-2009 KEIL, 2009-2015 ARM Germany GmbH +; * All rights reserved. +; * Redistribution and use in source and binary forms, with or without +; * modification, are permitted provided that the following conditions are met: +; * - Redistributions of source code must retain the above copyright +; * notice, this list of conditions and the following disclaimer. +; * - Redistributions in binary form must reproduce the above copyright +; * notice, this list of conditions and the following disclaimer in the +; * documentation and/or other materials provided with the distribution. +; * - Neither the name of ARM nor the names of its contributors may be used +; * to endorse or promote products derived from this software without +; * specific prior written permission. +; * +; * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +; * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +; * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +; * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE +; * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +; * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +; * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +; * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +; * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +; * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +; * POSSIBILITY OF SUCH DAMAGE. +; *---------------------------------------------------------------------------*/ + + + .file "SVC_Table.S" + + + .section ".svc_table" + + .global SVC_Table +SVC_Table: +/* Insert user SVC functions here. SVC 0 used by RTL Kernel. */ +# .long __SVC_1 /* user SVC function */ +SVC_End: + + .global SVC_Count +SVC_Count: + .long (SVC_End-SVC_Table)/4 + + + .end + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ diff --git a/rtos/rtx/TARGET_ARM7/HAL_CM.c b/rtos/rtx/TARGET_ARM7/HAL_CM.c new file mode 100644 index 00000000000..071fd73d838 --- /dev/null +++ b/rtos/rtx/TARGET_ARM7/HAL_CM.c @@ -0,0 +1,161 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: HAL_CM.C + * Purpose: Hardware Abstraction Layer for ARM7TDMI + * Rev.: V1.0 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 ARM Germany GmbH + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Conf.h" +#include "rt_HAL_CM.h" + + +/*---------------------------------------------------------------------------- + * Global Variables + *---------------------------------------------------------------------------*/ + +#ifdef DBG_MSG +BIT dbg_msg; +#endif + +/*---------------------------------------------------------------------------- + * Functions + *---------------------------------------------------------------------------*/ + + +/*--------------------------- rt_init_stack ---------------------------------*/ + +void rt_init_stack (P_TCB p_TCB, FUNCP task_body) { + /* Prepare TCB and saved context for a first time start of a task. */ + U32 *stk,i,size; + + /* Prepare a complete interrupt frame for first task start */ + size = p_TCB->priv_stack >> 2; + + /* Write to the top of stack. */ + stk = &p_TCB->stack[size]; + + /* Auto correct to 8-byte ARM stack alignment. */ + if ((U32)stk & 0x04) { + stk--; + } + + stk -= 16; + + /* Default xPSR and initial PC */ + stk[15] = (U32)task_body + 4; /* add 4 byte offset because SUB PC, LR - 4 */ + stk[0] = INITIAL_xPSR; + + /* Clear R0-R13/LR registers. */ + for (i = 1; i < 14; i++) { + stk[i] = 0; + } + + /* Assign a void pointer to R0. */ + stk[TCB_STACK_R0_OFFSET_DWORDS] = (U32)p_TCB->msg; + + /* Initial Task stack pointer. */ + p_TCB->tsk_stack = (U32)stk; + + /* Task entry point. */ + p_TCB->ptask = task_body; + + /* Set a magic word for checking of stack overflow. + For the main thread (ID: 0x01) the stack is in a memory area shared with the + heap, therefore the last word of the stack is a moving target. + We want to do stack/heap collision detection instead. + */ + if (p_TCB->task_id != 0x01) + p_TCB->stack[0] = MAGIC_WORD; +} + + +/*--------------------------- rt_ret_val ----------------------------------*/ + +static __inline U32 *rt_ret_regs (P_TCB p_TCB) { + /* Get pointer to task return value registers (R0..R3) in Stack */ + + /* Stack Frame: CPSR,R0-R13,PC */ + return (U32 *)(p_TCB->tsk_stack + TCB_STACK_R0_OFFSET_BYTES); +} + +void rt_ret_val (P_TCB p_TCB, U32 v0) { + U32 *ret; + + ret = rt_ret_regs(p_TCB); + ret[0] = v0; +} + +void rt_ret_val2(P_TCB p_TCB, U32 v0, U32 v1) { + U32 *ret; + + ret = rt_ret_regs(p_TCB); + ret[0] = v0; + ret[1] = v1; +} + + +/*--------------------------- dbg_init --------------------------------------*/ + +#ifdef DBG_MSG +void dbg_init (void) { + if ((DEMCR & DEMCR_TRCENA) && + (ITM_CONTROL & ITM_ITMENA) && + (ITM_ENABLE & (1UL << 31))) { + dbg_msg = __TRUE; + } +} +#endif + +/*--------------------------- dbg_task_notify -------------------------------*/ + +#ifdef DBG_MSG +void dbg_task_notify (P_TCB p_tcb, BOOL create) { + while (ITM_PORT31_U32 == 0); + ITM_PORT31_U32 = (U32)p_tcb->ptask; + while (ITM_PORT31_U32 == 0); + ITM_PORT31_U16 = (create << 8) | p_tcb->task_id; +} +#endif + +/*--------------------------- dbg_task_switch -------------------------------*/ + +#ifdef DBG_MSG +void dbg_task_switch (U32 task_id) { + while (ITM_PORT31_U32 == 0); + ITM_PORT31_U8 = task_id; +} +#endif + + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ + diff --git a/rtos/rtx/TARGET_ARM7/RTX_CM_lib.h b/rtos/rtx/TARGET_ARM7/RTX_CM_lib.h new file mode 100755 index 00000000000..3cde4b76d99 --- /dev/null +++ b/rtos/rtx/TARGET_ARM7/RTX_CM_lib.h @@ -0,0 +1,401 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RTX_CM_LIB.H + * Purpose: RTX Kernel System Configuration + * Rev.: V4.60 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 ARM Germany GmbH + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ +#include "mbed_error.h" + +#if defined (__CC_ARM) +#pragma O3 +#define __USED __attribute__((used)) +#elif defined (__GNUC__) +#pragma GCC optimize ("O3") +#define __USED __attribute__((used)) +#elif defined (__ICCARM__) +#define __USED __root +#endif + + +/*---------------------------------------------------------------------------- + * Definitions + *---------------------------------------------------------------------------*/ + +#define _declare_box(pool,size,cnt) uint32_t pool[(((size)+3)/4)*(cnt) + 3] +#define _declare_box8(pool,size,cnt) uint64_t pool[(((size)+7)/8)*(cnt) + 2] + +#define OS_TCB_SIZE 48 +#define OS_TMR_SIZE 8 + +#if defined (__CC_ARM) && !defined (__MICROLIB) + +typedef void *OS_ID; +typedef uint32_t OS_TID; +typedef uint32_t OS_MUT[3]; +typedef uint32_t OS_RESULT; + +#define runtask_id() rt_tsk_self() +#define mutex_init(m) rt_mut_init(m) +#define mutex_wait(m) os_mut_wait(m,0xFFFF) +#define mutex_rel(m) os_mut_release(m) + +extern OS_TID rt_tsk_self (void); +extern void rt_mut_init (OS_ID mutex); +extern OS_RESULT rt_mut_release (OS_ID mutex); +extern OS_RESULT rt_mut_wait (OS_ID mutex, uint16_t timeout); + +#define os_mut_wait(mutex,timeout) _os_mut_wait((uint32_t)rt_mut_wait,mutex,timeout) +#define os_mut_release(mutex) _os_mut_release((uint32_t)rt_mut_release,mutex) + +OS_RESULT _os_mut_release (uint32_t p, OS_ID mutex) __svc_indirect(0); +OS_RESULT _os_mut_wait (uint32_t p, OS_ID mutex, uint16_t timeout) __svc_indirect(0); + +#endif + + +/*---------------------------------------------------------------------------- + * Global Variables + *---------------------------------------------------------------------------*/ + +#if (OS_TIMERS != 0) +#define OS_TASK_CNT (OS_TASKCNT + 1) +#else +#define OS_TASK_CNT OS_TASKCNT +#endif + +uint16_t const os_maxtaskrun = OS_TASK_CNT; +uint32_t const os_rrobin = (OS_ROBIN << 16) | OS_ROBINTOUT; +uint32_t const os_trv = OS_TRV; +uint8_t const os_flags = OS_RUNPRIV; + +/* Export following defines to uVision debugger. */ +__USED uint32_t const os_clockrate = OS_TICK; +__USED uint32_t const os_timernum = 0; + +/* Stack for the os_idle_demon */ +unsigned int idle_task_stack[OS_IDLESTKSIZE]; +unsigned short const idle_task_stack_size = OS_IDLESTKSIZE; + +#ifndef OS_FIFOSZ + #define OS_FIFOSZ 16 +#endif + +/* Fifo Queue buffer for ISR requests.*/ +uint32_t os_fifo[OS_FIFOSZ*2+1]; +uint8_t const os_fifo_size = OS_FIFOSZ; + +/* An array of Active task pointers. */ +void *os_active_TCB[OS_TASK_CNT]; + +/* User Timers Resources */ +#if (OS_TIMERS != 0) +extern void osTimerThread (void const *argument); +osThreadDef(osTimerThread, (osPriority)(OS_TIMERPRIO-3), 4*OS_TIMERSTKSZ); +osThreadId osThreadId_osTimerThread; +osMessageQDef(osTimerMessageQ, OS_TIMERCBQS, void *); +osMessageQId osMessageQId_osTimerMessageQ; +#else +osThreadDef_t os_thread_def_osTimerThread = { NULL }; +osThreadId osThreadId_osTimerThread; +osMessageQDef(osTimerMessageQ, 0, void *); +osMessageQId osMessageQId_osTimerMessageQ; +#endif + + +/*---------------------------------------------------------------------------- + * RTX Optimizations (empty functions) + *---------------------------------------------------------------------------*/ + +#if OS_ROBIN == 0 + void rt_init_robin (void) {;} + void rt_chk_robin (void) {;} +#endif + +#if OS_STKCHECK == 0 + void rt_stk_check (void) {;} +#endif + + +/*---------------------------------------------------------------------------- + * Standard Library multithreading interface + *---------------------------------------------------------------------------*/ + +#if defined (__CC_ARM) && !defined (__MICROLIB) + static OS_MUT std_libmutex[OS_MUTEXCNT]; + static uint32_t nr_mutex; + + /*--------------------------- _mutex_initialize -----------------------------*/ + +int _mutex_initialize (OS_ID *mutex) { + /* Allocate and initialize a system mutex. */ + + if (nr_mutex >= OS_MUTEXCNT) { + /* If you are here, you need to increase the number OS_MUTEXCNT. */ + error("Not enough stdlib mutexes\n"); + } + *mutex = &std_libmutex[nr_mutex++]; + mutex_init (*mutex); + return (1); +} + + +/*--------------------------- _mutex_acquire --------------------------------*/ + +__attribute__((used)) void _mutex_acquire (OS_ID *mutex) { + /* Acquire a system mutex, lock stdlib resources. */ + if (runtask_id ()) { + /* RTX running, acquire a mutex. */ + mutex_wait (*mutex); + } +} + + +/*--------------------------- _mutex_release --------------------------------*/ + +__attribute__((used)) void _mutex_release (OS_ID *mutex) { + /* Release a system mutex, unlock stdlib resources. */ + if (runtask_id ()) { + /* RTX running, release a mutex. */ + mutex_rel (*mutex); + } +} + +#endif + + +/*---------------------------------------------------------------------------- + * RTX Startup + *---------------------------------------------------------------------------*/ + +/* Main Thread definition */ +extern void pre_main (void); +osThreadDef_t os_thread_def_main = {(os_pthread)pre_main, osPriorityNormal, 0, NULL}; + +#ifndef INITIAL_SP + #error "no target defined" +#endif + +#ifdef __CC_ARM +extern unsigned char Image$$RW_IRAM1$$ZI$$Limit[]; +#define HEAP_START (Image$$RW_IRAM1$$ZI$$Limit) +#elif defined(__GNUC__) +extern unsigned char __end__[]; +#define HEAP_START (__end__) +#elif defined(__ICCARM__) +#pragma section="HEAP" +#define HEAP_START (void *)__section_begin("HEAP") +#endif + +void set_main_stack(void) { + // That is the bottom of the main stack block: no collision detection + os_thread_def_main.stack_pointer = HEAP_START; + + // Leave OS_SCHEDULERSTKSIZE words for the scheduler and interrupts + os_thread_def_main.stacksize = (INITIAL_SP - (unsigned int)HEAP_START) - (OS_SCHEDULERSTKSIZE * 4); +} + +#if defined (__CC_ARM) +#ifdef __MICROLIB + +int main(void); +void _main_init (void) __attribute__((section(".ARM.Collect$$$$000000FF"))); +void $Super$$__cpp_initialize__aeabi_(void); + +void _main_init (void) { + osKernelInitialize(); + set_main_stack(); + osThreadCreate(&os_thread_def_main, NULL); + osKernelStart(); + for (;;); +} + +void $Sub$$__cpp_initialize__aeabi_(void) +{ + // this should invoke C++ initializers prior _main_init, we keep this empty and + // invoke them after _main_init (=starts RTX kernel) +} + +void pre_main() +{ + $Super$$__cpp_initialize__aeabi_(); + main(); +} + +#else + +void * armcc_heap_base; +void * armcc_heap_top; + +__asm void pre_main (void) +{ + IMPORT __rt_lib_init + IMPORT main + IMPORT armcc_heap_base + IMPORT armcc_heap_top + + LDR R0,=armcc_heap_base + LDR R1,=armcc_heap_top + LDR R0,[R0] + LDR R1,[R1] + /* Save link register (keep 8 byte alignment with dummy R4) */ + PUSH {R4, LR} + BL __rt_lib_init + BL main + /* Return to the thread destroy function. + */ + POP {R4, PC} + ALIGN +} + +/* The single memory model is checking for stack collision at run time, verifing + that the heap pointer is underneath the stack pointer. + + With the RTOS there is not only one stack above the heap, there are multiple + stacks and some of them are underneath the heap pointer. +*/ +#pragma import(__use_two_region_memory) + +__asm void __rt_entry (void) { + + IMPORT __user_setup_stackheap + IMPORT armcc_heap_base + IMPORT armcc_heap_top + IMPORT os_thread_def_main + IMPORT osKernelInitialize + IMPORT set_main_stack + IMPORT osKernelStart + IMPORT osThreadCreate + + /* __user_setup_stackheap returns: + * - Heap base in r0 (if the program uses the heap). + * - Stack base in sp. + * - Heap limit in r2 (if the program uses the heap and uses two-region memory). + * + * More info can be found in: + * ARM Compiler ARM C and C++ Libraries and Floating-Point Support User Guide + */ + BL __user_setup_stackheap + LDR R3,=armcc_heap_base + LDR R4,=armcc_heap_top + STR R0,[R3] + STR R2,[R4] + BL osKernelInitialize + BL set_main_stack + LDR R0,=os_thread_def_main + MOVS R1,#0 + BL osThreadCreate + BL osKernelStart + /* osKernelStart should not return */ + B . + + ALIGN +} + +#endif + +#elif defined (__GNUC__) + +extern int atexit(void (*func)(void)); +extern void __libc_fini_array(void); +extern void __libc_init_array (void); +extern int main(int argc, char **argv); + +void pre_main(void) { + atexit(__libc_fini_array); + __libc_init_array(); + main(0, NULL); +} + +__attribute__((naked)) void software_init_hook_rtos (void) { + __asm ( + ".syntax unified\n" + ".thumb\n" + "bl osKernelInitialize\n" + "bl set_main_stack\n" + "ldr r0,=os_thread_def_main\n" + "movs r1,#0\n" + "bl osThreadCreate\n" + "bl osKernelStart\n" + /* osKernelStart should not return */ + "B .\n" + ); +} + +#elif defined (__ICCARM__) + +extern void* __vector_table; +extern int __low_level_init(void); +extern void __iar_data_init3(void); +extern __weak void __iar_init_core( void ); +extern __weak void __iar_init_vfp( void ); +extern void __iar_dynamic_initialization(void); +extern void mbed_sdk_init(void); +extern void exit(int arg); + +static uint8_t low_level_init_needed; + +void pre_main(void) { + if (low_level_init_needed) { + __iar_dynamic_initialization(); + } + main(); +} + +#pragma required=__vector_table +void __iar_program_start( void ) +{ + __iar_init_core(); + __iar_init_vfp(); + + uint8_t low_level_init_needed_local; + + low_level_init_needed_local = __low_level_init(); + if (low_level_init_needed_local) { + __iar_data_init3(); + mbed_sdk_init(); + } + /* Store in a global variable after RAM has been initialized */ + low_level_init_needed = low_level_init_needed_local; + osKernelInitialize(); + set_main_stack(); + osThreadCreate(&os_thread_def_main, NULL); + osKernelStart(); + /* osKernelStart should not return */ + while (1); +} + +#endif + + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ + + diff --git a/rtos/rtx/TARGET_ARM7/RTX_Conf.h b/rtos/rtx/TARGET_ARM7/RTX_Conf.h new file mode 100644 index 00000000000..babf9c1a53c --- /dev/null +++ b/rtos/rtx/TARGET_ARM7/RTX_Conf.h @@ -0,0 +1,72 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RTX_CONFIG.H + * Purpose: Exported functions of RTX_Config.c + * Rev.: V4.60 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 ARM Germany GmbH + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + + +/* Error Codes */ +#define OS_ERR_STK_OVF 1 +#define OS_ERR_FIFO_OVF 2 +#define OS_ERR_MBX_OVF 3 + +/* Definitions */ +#define BOX_ALIGN_8 0x80000000 +#define _declare_box(pool,size,cnt) U32 pool[(((size)+3)/4)*(cnt) + 3] +#define _declare_box8(pool,size,cnt) U64 pool[(((size)+7)/8)*(cnt) + 2] +#define _init_box8(pool,size,bsize) _init_box (pool,size,(bsize) | BOX_ALIGN_8) + +/* Variables */ +extern U32 idle_task_stack[]; +extern U32 os_fifo[]; +extern void *os_active_TCB[]; + +/* Constants */ +extern U16 const os_maxtaskrun; +extern U32 const os_trv; +extern U8 const os_flags; +extern U32 const os_rrobin; +extern U32 const os_clockrate; +extern U32 const os_timernum; +extern U16 const idle_task_stack_size; + +extern U8 const os_fifo_size; + +/* Functions */ +extern void os_idle_demon (void); +extern int os_tick_init (void); +extern void os_tick_irqack (void); +extern void os_tmr_call (U16 info); +extern void os_error (U32 err_code); + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ diff --git a/rtos/rtx/TARGET_ARM7/RTX_Conf_CM.c b/rtos/rtx/TARGET_ARM7/RTX_Conf_CM.c new file mode 100755 index 00000000000..0e481f3d8e4 --- /dev/null +++ b/rtos/rtx/TARGET_ARM7/RTX_Conf_CM.c @@ -0,0 +1,228 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RTX_Conf_CM.C + * Purpose: Configuration of CMSIS RTX Kernel for ARM7TDMI + * Rev.: V1.0 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 ARM Germany GmbH + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + +#include "cmsis_os.h" + + +/*---------------------------------------------------------------------------- + * RTX User configuration part BEGIN + *---------------------------------------------------------------------------*/ + +// Include per-target RTX config file +#include "mbed_rtx.h" + +//-------- <<< Use Configuration Wizard in Context Menu >>> ----------------- +// +// Thread Configuration +// ======================= +// +// Number of concurrent running threads <0-250> +// Defines max. number of threads that will run at the same time. +// counting "main", but not counting "osTimerThread" +// Default: 6 +#ifndef OS_TASKCNT + #error "no target defined" +#endif + +// Scheduler (+ interrupts) stack size [bytes] <64-4096:8><#/4> +#ifndef OS_SCHEDULERSTKSIZE + #error "no target defined" +#endif + +// Idle stack size [bytes] <64-4096:8><#/4> +// Defines default stack size for the Idle thread. +#ifndef OS_IDLESTKSIZE + #define OS_IDLESTKSIZE 136 +#endif + +// Timer Thread stack size [bytes] <64-4096:8><#/4> +// Defines stack size for Timer thread. +// Default: 200 +#ifndef OS_TIMERSTKSZ + #define OS_TIMERSTKSZ WORDS_STACK_SIZE +#endif + +// Check for stack overflow +// Includes the stack checking code for stack overflow. +// Note that additional code reduces the Kernel performance. +#ifndef OS_STKCHECK + #define OS_STKCHECK 1 +#endif + +// Processor mode for thread execution +// <0=> Unprivileged mode +// <1=> Privileged mode +// Default: Privileged mode +#ifndef OS_RUNPRIV + #define OS_RUNPRIV 1 +#endif + +// +// SysTick Timer Configuration +// ============================== +// +// Timer clock value [Hz] <1-1000000000> +// Defines the timer clock value. +// Default: 6000000 (6MHz) +#ifndef OS_CLOCK + #error "no target defined" +#endif + +// Timer tick value [us] <1-1000000> +// Defines the timer tick value. +// Default: 1000 (1ms) +#ifndef OS_TICK + #define OS_TICK 1000 +#endif + +// + +// System Configuration +// ======================= +// +// Round-Robin Thread switching +// =============================== +// +// Enables Round-Robin Thread switching. +#ifndef OS_ROBIN + #define OS_ROBIN 1 +#endif + +// Round-Robin Timeout [ticks] <1-1000> +// Defines how long a thread will execute before a thread switch. +// Default: 5 +#ifndef OS_ROBINTOUT + #define OS_ROBINTOUT 5 +#endif + +// + +// User Timers +// ============== +// Enables user Timers +#ifndef OS_TIMERS + #define OS_TIMERS 1 +#endif + +// Timer Thread Priority +// <1=> Low +// <2=> Below Normal +// <3=> Normal +// <4=> Above Normal +// <5=> High +// <6=> Realtime (highest) +// Defines priority for Timer Thread +// Default: High +#ifndef OS_TIMERPRIO + #define OS_TIMERPRIO 5 +#endif + +// Timer Callback Queue size <1-32> +// Number of concurrent active timer callback functions. +// Default: 4 +#ifndef OS_TIMERCBQSZ + #define OS_TIMERCBQS 4 +#endif + +// + +// ISR FIFO Queue size<4=> 4 entries <8=> 8 entries +// <12=> 12 entries <16=> 16 entries +// <24=> 24 entries <32=> 32 entries +// <48=> 48 entries <64=> 64 entries +// <96=> 96 entries +// ISR functions store requests to this buffer, +// when they are called from the interrupt handler. +// Default: 16 entries +#ifndef OS_FIFOSZ + #define OS_FIFOSZ 16 +#endif + +// + +//------------- <<< end of configuration section >>> ----------------------- + +// Standard library system mutexes +// =============================== +// Define max. number system mutexes that are used to protect +// the arm standard runtime library. For microlib they are not used. +#ifndef OS_MUTEXCNT + #define OS_MUTEXCNT 12 +#endif + +/*---------------------------------------------------------------------------- + * RTX User configuration part END + *---------------------------------------------------------------------------*/ + +#define OS_TRV ((uint32_t)(((double)OS_CLOCK*(double)OS_TICK)/1E6)-1) + + +/*---------------------------------------------------------------------------- + * OS Idle daemon + *---------------------------------------------------------------------------*/ +extern void rtos_idle_loop(void); + +void os_idle_demon (void) { + /* The idle demon is a system thread, running when no other thread is */ + /* ready to run. */ + rtos_idle_loop(); +} + +/*---------------------------------------------------------------------------- + * RTX Errors + *---------------------------------------------------------------------------*/ +extern void mbed_die(void); + +void os_error (uint32_t err_code) { + /* This function is called when a runtime error is detected. Parameter */ + /* 'err_code' holds the runtime error code (defined in RTX_Conf.h). */ + mbed_die(); +} + +void sysThreadError(osStatus status) { + if (status != osOK) { + mbed_die(); + } +} + +/*---------------------------------------------------------------------------- + * RTX Configuration Functions + *---------------------------------------------------------------------------*/ + +#include "RTX_CM_lib.h" + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ + diff --git a/rtos/rtx/TARGET_ARM7/cmsis_os.h b/rtos/rtx/TARGET_ARM7/cmsis_os.h new file mode 100644 index 00000000000..9bfa1535cb8 --- /dev/null +++ b/rtos/rtx/TARGET_ARM7/cmsis_os.h @@ -0,0 +1,774 @@ +/* ---------------------------------------------------------------------- + * Copyright (C) 2015 ARM Limited. All rights reserved. + * + * $Date: 5. June 2012 + * $Revision: V1.01 + * + * Project: CMSIS-RTOS API + * Title: cmsis_os.h RTX header file + * + * Version 0.02 + * Initial Proposal Phase + * Version 0.03 + * osKernelStart added, optional feature: main started as thread + * osSemaphores have standard behavior + * osTimerCreate does not start the timer, added osTimerStart + * osThreadPass is renamed to osThreadYield + * Version 1.01 + * Support for C++ interface + * - const attribute removed from the osXxxxDef_t typedef's + * - const attribute added to the osXxxxDef macros + * Added: osTimerDelete, osMutexDelete, osSemaphoreDelete + * Added: osKernelInitialize + * -------------------------------------------------------------------- */ + +/** +\page cmsis_os_h Header File Template: cmsis_os.h + +The file \b cmsis_os.h is a template header file for a CMSIS-RTOS compliant Real-Time Operating System (RTOS). +Each RTOS that is compliant with CMSIS-RTOS shall provide a specific \b cmsis_os.h header file that represents +its implementation. + +The file cmsis_os.h contains: + - CMSIS-RTOS API function definitions + - struct definitions for parameters and return types + - status and priority values used by CMSIS-RTOS API functions + - macros for defining threads and other kernel objects + + +Name conventions and header file modifications + +All definitions are prefixed with \b os to give an unique name space for CMSIS-RTOS functions. +Definitions that are prefixed \b os_ are not used in the application code but local to this header file. +All definitions and functions that belong to a module are grouped and have a common prefix, i.e. \b osThread. + +Definitions that are marked with CAN BE CHANGED can be adapted towards the needs of the actual CMSIS-RTOS implementation. +These definitions can be specific to the underlying RTOS kernel. + +Definitions that are marked with MUST REMAIN UNCHANGED cannot be altered. Otherwise the CMSIS-RTOS implementation is no longer +compliant to the standard. Note that some functions are optional and need not to be provided by every CMSIS-RTOS implementation. + + +Function calls from interrupt service routines + +The following CMSIS-RTOS functions can be called from threads and interrupt service routines (ISR): + - \ref osSignalSet + - \ref osSemaphoreRelease + - \ref osPoolAlloc, \ref osPoolCAlloc, \ref osPoolFree + - \ref osMessagePut, \ref osMessageGet + - \ref osMailAlloc, \ref osMailCAlloc, \ref osMailGet, \ref osMailPut, \ref osMailFree + +Functions that cannot be called from an ISR are verifying the interrupt status and return in case that they are called +from an ISR context the status code \b osErrorISR. In some implementations this condition might be caught using the HARD FAULT vector. + +Some CMSIS-RTOS implementations support CMSIS-RTOS function calls from multiple ISR at the same time. +If this is impossible, the CMSIS-RTOS rejects calls by nested ISR functions with the status code \b osErrorISRRecursive. + + +Define and reference object definitions + +With \#define osObjectsExternal objects are defined as external symbols. This allows to create a consistent header file +that is used throughout a project as shown below: + +Header File +\code +#include // CMSIS RTOS header file + +// Thread definition +extern void thread_sample (void const *argument); // function prototype +osThreadDef (thread_sample, osPriorityBelowNormal, 1, 100); + +// Pool definition +osPoolDef(MyPool, 10, long); +\endcode + + +This header file defines all objects when included in a C/C++ source file. When \#define osObjectsExternal is +present before the header file, the objects are defined as external symbols. A single consistent header file can therefore be +used throughout the whole project. + +Example +\code +#include "osObjects.h" // Definition of the CMSIS-RTOS objects +\endcode + +\code +#define osObjectExternal // Objects will be defined as external symbols +#include "osObjects.h" // Reference to the CMSIS-RTOS objects +\endcode + +*/ + +#ifndef _CMSIS_OS_H +#define _CMSIS_OS_H + +/// \note MUST REMAIN UNCHANGED: \b osCMSIS identifies the CMSIS-RTOS API version. +#define osCMSIS 0x10001 ///< API version (main [31:16] .sub [15:0]) + +/// \note CAN BE CHANGED: \b osCMSIS_KERNEL identifies the underlying RTOS kernel and version number. +#define osCMSIS_RTX ((4<<16)|61) ///< RTOS identification and version (main [31:16] .sub [15:0]) + +/// \note MUST REMAIN UNCHANGED: \b osKernelSystemId shall be consistent in every CMSIS-RTOS. +#define osKernelSystemId "RTX V4.61" ///< RTOS identification string + + +#define CMSIS_OS_RTX + +// The stack space occupied is mainly dependent on the underling C standard library +#if defined(TOOLCHAIN_GCC) || defined(TOOLCHAIN_ARM_STD) || defined(TOOLCHAIN_IAR) +# define WORDS_STACK_SIZE 512 +#elif defined(TOOLCHAIN_ARM_MICRO) +# define WORDS_STACK_SIZE 128 +#endif + +#define DEFAULT_STACK_SIZE (WORDS_STACK_SIZE*4) + + +/// \note MUST REMAIN UNCHANGED: \b osFeature_xxx shall be consistent in every CMSIS-RTOS. +#define osFeature_MainThread 1 ///< main thread 1=main can be thread, 0=not available +#define osFeature_Pool 1 ///< Memory Pools: 1=available, 0=not available +#define osFeature_MailQ 1 ///< Mail Queues: 1=available, 0=not available +#define osFeature_MessageQ 1 ///< Message Queues: 1=available, 0=not available +#define osFeature_Signals 16 ///< maximum number of Signal Flags available per thread +#define osFeature_Semaphore 65535 ///< maximum count for \ref osSemaphoreCreate function +#define osFeature_Wait 0 ///< osWait function: 1=available, 0=not available + +#if defined (__CC_ARM) +#define os_InRegs __value_in_regs // Compiler specific: force struct in registers +#elif defined (__ICCARM__) +#define os_InRegs __value_in_regs // Compiler specific: force struct in registers +#else +#define os_InRegs +#endif + +#include +#include + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "os_tcb.h" + +// ==== Enumeration, structures, defines ==== + +/// Priority used for thread control. +/// \note MUST REMAIN UNCHANGED: \b osPriority shall be consistent in every CMSIS-RTOS. +typedef enum { + osPriorityIdle = -3, ///< priority: idle (lowest) + osPriorityLow = -2, ///< priority: low + osPriorityBelowNormal = -1, ///< priority: below normal + osPriorityNormal = 0, ///< priority: normal (default) + osPriorityAboveNormal = +1, ///< priority: above normal + osPriorityHigh = +2, ///< priority: high + osPriorityRealtime = +3, ///< priority: realtime (highest) + osPriorityError = 0x84 ///< system cannot determine priority or thread has illegal priority +} osPriority; + +/// Timeout value. +/// \note MUST REMAIN UNCHANGED: \b osWaitForever shall be consistent in every CMSIS-RTOS. +#define osWaitForever 0xFFFFFFFF ///< wait forever timeout value + +/// Status code values returned by CMSIS-RTOS functions. +/// \note MUST REMAIN UNCHANGED: \b osStatus shall be consistent in every CMSIS-RTOS. +typedef enum { + osOK = 0, ///< function completed; no error or event occurred. + osEventSignal = 0x08, ///< function completed; signal event occurred. + osEventMessage = 0x10, ///< function completed; message event occurred. + osEventMail = 0x20, ///< function completed; mail event occurred. + osEventTimeout = 0x40, ///< function completed; timeout occurred. + osErrorParameter = 0x80, ///< parameter error: a mandatory parameter was missing or specified an incorrect object. + osErrorResource = 0x81, ///< resource not available: a specified resource was not available. + osErrorTimeoutResource = 0xC1, ///< resource not available within given time: a specified resource was not available within the timeout period. + osErrorISR = 0x82, ///< not allowed in ISR context: the function cannot be called from interrupt service routines. + osErrorISRRecursive = 0x83, ///< function called multiple times from ISR with same object. + osErrorPriority = 0x84, ///< system cannot determine priority or thread has illegal priority. + osErrorNoMemory = 0x85, ///< system is out of memory: it was impossible to allocate or reserve memory for the operation. + osErrorValue = 0x86, ///< value of a parameter is out of range. + osErrorOS = 0xFF, ///< unspecified RTOS error: run-time error but no other error message fits. + os_status_reserved = 0x7FFFFFFF ///< prevent from enum down-size compiler optimization. +} osStatus; + + +/// Timer type value for the timer definition. +/// \note MUST REMAIN UNCHANGED: \b os_timer_type shall be consistent in every CMSIS-RTOS. +typedef enum { + osTimerOnce = 0, ///< one-shot timer + osTimerPeriodic = 1 ///< repeating timer +} os_timer_type; + +/// Entry point of a thread. +/// \note MUST REMAIN UNCHANGED: \b os_pthread shall be consistent in every CMSIS-RTOS. +typedef void (*os_pthread) (void const *argument); + +/// Entry point of a timer call back function. +/// \note MUST REMAIN UNCHANGED: \b os_ptimer shall be consistent in every CMSIS-RTOS. +typedef void (*os_ptimer) (void const *argument); + +// >>> the following data type definitions may shall adapted towards a specific RTOS + +/// Thread ID identifies the thread (pointer to a thread control block). +/// \note CAN BE CHANGED: \b os_thread_cb is implementation specific in every CMSIS-RTOS. +typedef struct os_thread_cb *osThreadId; + +/// Timer ID identifies the timer (pointer to a timer control block). +/// \note CAN BE CHANGED: \b os_timer_cb is implementation specific in every CMSIS-RTOS. +typedef struct os_timer_cb *osTimerId; + +/// Mutex ID identifies the mutex (pointer to a mutex control block). +/// \note CAN BE CHANGED: \b os_mutex_cb is implementation specific in every CMSIS-RTOS. +typedef struct os_mutex_cb *osMutexId; + +/// Semaphore ID identifies the semaphore (pointer to a semaphore control block). +/// \note CAN BE CHANGED: \b os_semaphore_cb is implementation specific in every CMSIS-RTOS. +typedef struct os_semaphore_cb *osSemaphoreId; + +/// Pool ID identifies the memory pool (pointer to a memory pool control block). +/// \note CAN BE CHANGED: \b os_pool_cb is implementation specific in every CMSIS-RTOS. +typedef struct os_pool_cb *osPoolId; + +/// Message ID identifies the message queue (pointer to a message queue control block). +/// \note CAN BE CHANGED: \b os_messageQ_cb is implementation specific in every CMSIS-RTOS. +typedef struct os_messageQ_cb *osMessageQId; + +/// Mail ID identifies the mail queue (pointer to a mail queue control block). +/// \note CAN BE CHANGED: \b os_mailQ_cb is implementation specific in every CMSIS-RTOS. +typedef struct os_mailQ_cb *osMailQId; + + +/// Thread Definition structure contains startup information of a thread. +/// \note CAN BE CHANGED: \b os_thread_def is implementation specific in every CMSIS-RTOS. +typedef struct os_thread_def { + os_pthread pthread; ///< start address of thread function + osPriority tpriority; ///< initial thread priority + uint32_t stacksize; ///< stack size requirements in bytes + uint32_t *stack_pointer; ///< pointer to the stack memory block + struct OS_TCB tcb; +} osThreadDef_t; + +/// Timer Definition structure contains timer parameters. +/// \note CAN BE CHANGED: \b os_timer_def is implementation specific in every CMSIS-RTOS. +typedef struct os_timer_def { + os_ptimer ptimer; ///< start address of a timer function + void *timer; ///< pointer to internal data +} osTimerDef_t; + +/// Mutex Definition structure contains setup information for a mutex. +/// \note CAN BE CHANGED: \b os_mutex_def is implementation specific in every CMSIS-RTOS. +typedef struct os_mutex_def { + void *mutex; ///< pointer to internal data +} osMutexDef_t; + +/// Semaphore Definition structure contains setup information for a semaphore. +/// \note CAN BE CHANGED: \b os_semaphore_def is implementation specific in every CMSIS-RTOS. +typedef struct os_semaphore_def { + void *semaphore; ///< pointer to internal data +} osSemaphoreDef_t; + +/// Definition structure for memory block allocation. +/// \note CAN BE CHANGED: \b os_pool_def is implementation specific in every CMSIS-RTOS. +typedef struct os_pool_def { + uint32_t pool_sz; ///< number of items (elements) in the pool + uint32_t item_sz; ///< size of an item + void *pool; ///< pointer to memory for pool +} osPoolDef_t; + +/// Definition structure for message queue. +/// \note CAN BE CHANGED: \b os_messageQ_def is implementation specific in every CMSIS-RTOS. +typedef struct os_messageQ_def { + uint32_t queue_sz; ///< number of elements in the queue + void *pool; ///< memory array for messages +} osMessageQDef_t; + +/// Definition structure for mail queue. +/// \note CAN BE CHANGED: \b os_mailQ_def is implementation specific in every CMSIS-RTOS. +typedef struct os_mailQ_def { + uint32_t queue_sz; ///< number of elements in the queue + uint32_t item_sz; ///< size of an item + void *pool; ///< memory array for mail +} osMailQDef_t; + +/// Event structure contains detailed information about an event. +/// \note MUST REMAIN UNCHANGED: \b os_event shall be consistent in every CMSIS-RTOS. +/// However the struct may be extended at the end. +typedef struct { + osStatus status; ///< status code: event or error information + union { + uint32_t v; ///< message as 32-bit value + void *p; ///< message or mail as void pointer + int32_t signals; ///< signal flags + } value; ///< event value + union { + osMailQId mail_id; ///< mail id obtained by \ref osMailCreate + osMessageQId message_id; ///< message id obtained by \ref osMessageCreate + } def; ///< event definition +} osEvent; + + +// ==== Kernel Control Functions ==== + +/// Initialize the RTOS Kernel for creating objects. +/// \return status code that indicates the execution status of the function. +/// \note MUST REMAIN UNCHANGED: \b osKernelInitialize shall be consistent in every CMSIS-RTOS. +osStatus osKernelInitialize (void); + +/// Start the RTOS Kernel. +/// \return status code that indicates the execution status of the function. +/// \note MUST REMAIN UNCHANGED: \b osKernelStart shall be consistent in every CMSIS-RTOS. +osStatus osKernelStart (void); + +/// Check if the RTOS kernel is already started. +/// \note MUST REMAIN UNCHANGED: \b osKernelRunning shall be consistent in every CMSIS-RTOS. +/// \return 0 RTOS is not started, 1 RTOS is started. +int32_t osKernelRunning(void); + + +// ==== Thread Management ==== + +/// Create a Thread Definition with function, priority, and stack requirements. +/// \param name name of the thread function. +/// \param priority initial priority of the thread function. +/// \param stacksz stack size (in bytes) requirements for the thread function. +/// \note CAN BE CHANGED: The parameters to \b osThreadDef shall be consistent but the +/// macro body is implementation specific in every CMSIS-RTOS. +#if defined (osObjectsExternal) // object is external +#define osThreadDef(name, priority, stacksz) \ +extern osThreadDef_t os_thread_def_##name +#else // define the object +#define osThreadDef(name, priority, stacksz) \ +uint32_t os_thread_def_stack_##name [stacksz / sizeof(uint32_t)]; \ +osThreadDef_t os_thread_def_##name = \ +{ (name), (priority), (stacksz), (os_thread_def_stack_##name)} +#endif + +/// Access a Thread definition. +/// \param name name of the thread definition object. +/// \note CAN BE CHANGED: The parameter to \b osThread shall be consistent but the +/// macro body is implementation specific in every CMSIS-RTOS. +#define osThread(name) \ +&os_thread_def_##name + +/// Create a thread and add it to Active Threads and set it to state READY. +/// \param[in] thread_def thread definition referenced with \ref osThread. +/// \param[in] argument pointer that is passed to the thread function as start argument. +/// \return thread ID for reference by other functions or NULL in case of error. +/// \note MUST REMAIN UNCHANGED: \b osThreadCreate shall be consistent in every CMSIS-RTOS. +osThreadId osThreadCreate (osThreadDef_t *thread_def, void *argument); + +/// Return the thread ID of the current running thread. +/// \return thread ID for reference by other functions or NULL in case of error. +/// \note MUST REMAIN UNCHANGED: \b osThreadGetId shall be consistent in every CMSIS-RTOS. +osThreadId osThreadGetId (void); + +/// Terminate execution of a thread and remove it from Active Threads. +/// \param[in] thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId. +/// \return status code that indicates the execution status of the function. +/// \note MUST REMAIN UNCHANGED: \b osThreadTerminate shall be consistent in every CMSIS-RTOS. +osStatus osThreadTerminate (osThreadId thread_id); + +/// Pass control to next thread that is in state \b READY. +/// \return status code that indicates the execution status of the function. +/// \note MUST REMAIN UNCHANGED: \b osThreadYield shall be consistent in every CMSIS-RTOS. +osStatus osThreadYield (void); + +/// Change priority of an active thread. +/// \param[in] thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId. +/// \param[in] priority new priority value for the thread function. +/// \return status code that indicates the execution status of the function. +/// \note MUST REMAIN UNCHANGED: \b osThreadSetPriority shall be consistent in every CMSIS-RTOS. +osStatus osThreadSetPriority (osThreadId thread_id, osPriority priority); + +/// Get current priority of an active thread. +/// \param[in] thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId. +/// \return current priority value of the thread function. +/// \note MUST REMAIN UNCHANGED: \b osThreadGetPriority shall be consistent in every CMSIS-RTOS. +osPriority osThreadGetPriority (osThreadId thread_id); + + +// ==== Generic Wait Functions ==== + +/// Wait for Timeout (Time Delay). +/// \param[in] millisec time delay value +/// \return status code that indicates the execution status of the function. +osStatus osDelay (uint32_t millisec); + +#if (defined (osFeature_Wait) && (osFeature_Wait != 0)) // Generic Wait available + +/// Wait for Signal, Message, Mail, or Timeout. +/// \param[in] millisec timeout value or 0 in case of no time-out +/// \return event that contains signal, message, or mail information or error code. +/// \note MUST REMAIN UNCHANGED: \b osWait shall be consistent in every CMSIS-RTOS. +os_InRegs osEvent osWait (uint32_t millisec); + +#endif // Generic Wait available + + +// ==== Timer Management Functions ==== +/// Define a Timer object. +/// \param name name of the timer object. +/// \param function name of the timer call back function. +/// \note CAN BE CHANGED: The parameter to \b osTimerDef shall be consistent but the +/// macro body is implementation specific in every CMSIS-RTOS. +#if defined (osObjectsExternal) // object is external +#define osTimerDef(name, function) \ +extern osTimerDef_t os_timer_def_##name +#else // define the object +#define osTimerDef(name, function) \ +uint32_t os_timer_cb_##name[5]; \ +osTimerDef_t os_timer_def_##name = \ +{ (function), (os_timer_cb_##name) } +#endif + +/// Access a Timer definition. +/// \param name name of the timer object. +/// \note CAN BE CHANGED: The parameter to \b osTimer shall be consistent but the +/// macro body is implementation specific in every CMSIS-RTOS. +#define osTimer(name) \ +&os_timer_def_##name + +/// Create a timer. +/// \param[in] timer_def timer object referenced with \ref osTimer. +/// \param[in] type osTimerOnce for one-shot or osTimerPeriodic for periodic behavior. +/// \param[in] argument argument to the timer call back function. +/// \return timer ID for reference by other functions or NULL in case of error. +/// \note MUST REMAIN UNCHANGED: \b osTimerCreate shall be consistent in every CMSIS-RTOS. +osTimerId osTimerCreate (osTimerDef_t *timer_def, os_timer_type type, void *argument); + +/// Start or restart a timer. +/// \param[in] timer_id timer ID obtained by \ref osTimerCreate. +/// \param[in] millisec time delay value of the timer. +/// \return status code that indicates the execution status of the function. +/// \note MUST REMAIN UNCHANGED: \b osTimerStart shall be consistent in every CMSIS-RTOS. +osStatus osTimerStart (osTimerId timer_id, uint32_t millisec); + +/// Stop the timer. +/// \param[in] timer_id timer ID obtained by \ref osTimerCreate. +/// \return status code that indicates the execution status of the function. +/// \note MUST REMAIN UNCHANGED: \b osTimerStop shall be consistent in every CMSIS-RTOS. +osStatus osTimerStop (osTimerId timer_id); + +/// Delete a timer that was created by \ref osTimerCreate. +/// \param[in] timer_id timer ID obtained by \ref osTimerCreate. +/// \return status code that indicates the execution status of the function. +/// \note MUST REMAIN UNCHANGED: \b osTimerDelete shall be consistent in every CMSIS-RTOS. +osStatus osTimerDelete (osTimerId timer_id); + + +// ==== Signal Management ==== + +/// Set the specified Signal Flags of an active thread. +/// \param[in] thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId. +/// \param[in] signals specifies the signal flags of the thread that should be set. +/// \return previous signal flags of the specified thread or 0x80000000 in case of incorrect parameters. +/// \note MUST REMAIN UNCHANGED: \b osSignalSet shall be consistent in every CMSIS-RTOS. +int32_t osSignalSet (osThreadId thread_id, int32_t signals); + +/// Clear the specified Signal Flags of an active thread. +/// \param[in] thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId. +/// \param[in] signals specifies the signal flags of the thread that shall be cleared. +/// \return previous signal flags of the specified thread or 0x80000000 in case of incorrect parameters. +/// \note MUST REMAIN UNCHANGED: \b osSignalClear shall be consistent in every CMSIS-RTOS. +int32_t osSignalClear (osThreadId thread_id, int32_t signals); + +/// Get Signal Flags status of an active thread. +/// \param[in] thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId. +/// \return previous signal flags of the specified thread or 0x80000000 in case of incorrect parameters. +/// \note MUST REMAIN UNCHANGED: \b osSignalGet shall be consistent in every CMSIS-RTOS. +int32_t osSignalGet (osThreadId thread_id); + +/// Wait for one or more Signal Flags to become signaled for the current \b RUNNING thread. +/// \param[in] signals wait until all specified signal flags set or 0 for any single signal flag. +/// \param[in] millisec timeout value or 0 in case of no time-out. +/// \return event flag information or error code. +/// \note MUST REMAIN UNCHANGED: \b osSignalWait shall be consistent in every CMSIS-RTOS. +os_InRegs osEvent osSignalWait (int32_t signals, uint32_t millisec); + + +// ==== Mutex Management ==== + +/// Define a Mutex. +/// \param name name of the mutex object. +/// \note CAN BE CHANGED: The parameter to \b osMutexDef shall be consistent but the +/// macro body is implementation specific in every CMSIS-RTOS. +#if defined (osObjectsExternal) // object is external +#define osMutexDef(name) \ +extern osMutexDef_t os_mutex_def_##name +#else // define the object +#define osMutexDef(name) \ +uint32_t os_mutex_cb_##name[3]; \ +osMutexDef_t os_mutex_def_##name = { (os_mutex_cb_##name) } +#endif + +/// Access a Mutex definition. +/// \param name name of the mutex object. +/// \note CAN BE CHANGED: The parameter to \b osMutex shall be consistent but the +/// macro body is implementation specific in every CMSIS-RTOS. +#define osMutex(name) \ +&os_mutex_def_##name + +/// Create and Initialize a Mutex object. +/// \param[in] mutex_def mutex definition referenced with \ref osMutex. +/// \return mutex ID for reference by other functions or NULL in case of error. +/// \note MUST REMAIN UNCHANGED: \b osMutexCreate shall be consistent in every CMSIS-RTOS. +osMutexId osMutexCreate (osMutexDef_t *mutex_def); + +/// Wait until a Mutex becomes available. +/// \param[in] mutex_id mutex ID obtained by \ref osMutexCreate. +/// \param[in] millisec timeout value or 0 in case of no time-out. +/// \return status code that indicates the execution status of the function. +/// \note MUST REMAIN UNCHANGED: \b osMutexWait shall be consistent in every CMSIS-RTOS. +osStatus osMutexWait (osMutexId mutex_id, uint32_t millisec); + +/// Release a Mutex that was obtained by \ref osMutexWait. +/// \param[in] mutex_id mutex ID obtained by \ref osMutexCreate. +/// \return status code that indicates the execution status of the function. +/// \note MUST REMAIN UNCHANGED: \b osMutexRelease shall be consistent in every CMSIS-RTOS. +osStatus osMutexRelease (osMutexId mutex_id); + +/// Delete a Mutex that was created by \ref osMutexCreate. +/// \param[in] mutex_id mutex ID obtained by \ref osMutexCreate. +/// \return status code that indicates the execution status of the function. +/// \note MUST REMAIN UNCHANGED: \b osMutexDelete shall be consistent in every CMSIS-RTOS. +osStatus osMutexDelete (osMutexId mutex_id); + + +// ==== Semaphore Management Functions ==== + +#if (defined (osFeature_Semaphore) && (osFeature_Semaphore != 0)) // Semaphore available + +/// Define a Semaphore object. +/// \param name name of the semaphore object. +/// \note CAN BE CHANGED: The parameter to \b osSemaphoreDef shall be consistent but the +/// macro body is implementation specific in every CMSIS-RTOS. +#if defined (osObjectsExternal) // object is external +#define osSemaphoreDef(name) \ +extern osSemaphoreDef_t os_semaphore_def_##name +#else // define the object +#define osSemaphoreDef(name) \ +uint32_t os_semaphore_cb_##name[2]; \ +osSemaphoreDef_t os_semaphore_def_##name = { (os_semaphore_cb_##name) } +#endif + +/// Access a Semaphore definition. +/// \param name name of the semaphore object. +/// \note CAN BE CHANGED: The parameter to \b osSemaphore shall be consistent but the +/// macro body is implementation specific in every CMSIS-RTOS. +#define osSemaphore(name) \ +&os_semaphore_def_##name + +/// Create and Initialize a Semaphore object used for managing resources. +/// \param[in] semaphore_def semaphore definition referenced with \ref osSemaphore. +/// \param[in] count number of available resources. +/// \return semaphore ID for reference by other functions or NULL in case of error. +/// \note MUST REMAIN UNCHANGED: \b osSemaphoreCreate shall be consistent in every CMSIS-RTOS. +osSemaphoreId osSemaphoreCreate (osSemaphoreDef_t *semaphore_def, int32_t count); + +/// Wait until a Semaphore token becomes available. +/// \param[in] semaphore_id semaphore object referenced with \ref osSemaphoreCreate. +/// \param[in] millisec timeout value or 0 in case of no time-out. +/// \return number of available tokens, or -1 in case of incorrect parameters. +/// \note MUST REMAIN UNCHANGED: \b osSemaphoreWait shall be consistent in every CMSIS-RTOS. +int32_t osSemaphoreWait (osSemaphoreId semaphore_id, uint32_t millisec); + +/// Release a Semaphore token. +/// \param[in] semaphore_id semaphore object referenced with \ref osSemaphoreCreate. +/// \return status code that indicates the execution status of the function. +/// \note MUST REMAIN UNCHANGED: \b osSemaphoreRelease shall be consistent in every CMSIS-RTOS. +osStatus osSemaphoreRelease (osSemaphoreId semaphore_id); + +/// Delete a Semaphore that was created by \ref osSemaphoreCreate. +/// \param[in] semaphore_id semaphore object referenced with \ref osSemaphoreCreate. +/// \return status code that indicates the execution status of the function. +/// \note MUST REMAIN UNCHANGED: \b osSemaphoreDelete shall be consistent in every CMSIS-RTOS. +osStatus osSemaphoreDelete (osSemaphoreId semaphore_id); + +#endif // Semaphore available + + +// ==== Memory Pool Management Functions ==== + +#if (defined (osFeature_Pool) && (osFeature_Pool != 0)) // Memory Pool Management available + +/// \brief Define a Memory Pool. +/// \param name name of the memory pool. +/// \param no maximum number of blocks (objects) in the memory pool. +/// \param type data type of a single block (object). +/// \note CAN BE CHANGED: The parameter to \b osPoolDef shall be consistent but the +/// macro body is implementation specific in every CMSIS-RTOS. +#if defined (osObjectsExternal) // object is external +#define osPoolDef(name, no, type) \ +extern osPoolDef_t os_pool_def_##name +#else // define the object +#define osPoolDef(name, no, type) \ +uint32_t os_pool_m_##name[3+((sizeof(type)+3)/4)*(no)]; \ +osPoolDef_t os_pool_def_##name = \ +{ (no), sizeof(type), (os_pool_m_##name) } +#endif + +/// \brief Access a Memory Pool definition. +/// \param name name of the memory pool +/// \note CAN BE CHANGED: The parameter to \b osPool shall be consistent but the +/// macro body is implementation specific in every CMSIS-RTOS. +#define osPool(name) \ +&os_pool_def_##name + +/// Create and Initialize a memory pool. +/// \param[in] pool_def memory pool definition referenced with \ref osPool. +/// \return memory pool ID for reference by other functions or NULL in case of error. +/// \note MUST REMAIN UNCHANGED: \b osPoolCreate shall be consistent in every CMSIS-RTOS. +osPoolId osPoolCreate (osPoolDef_t *pool_def); + +/// Allocate a memory block from a memory pool. +/// \param[in] pool_id memory pool ID obtain referenced with \ref osPoolCreate. +/// \return address of the allocated memory block or NULL in case of no memory available. +/// \note MUST REMAIN UNCHANGED: \b osPoolAlloc shall be consistent in every CMSIS-RTOS. +void *osPoolAlloc (osPoolId pool_id); + +/// Allocate a memory block from a memory pool and set memory block to zero. +/// \param[in] pool_id memory pool ID obtain referenced with \ref osPoolCreate. +/// \return address of the allocated memory block or NULL in case of no memory available. +/// \note MUST REMAIN UNCHANGED: \b osPoolCAlloc shall be consistent in every CMSIS-RTOS. +void *osPoolCAlloc (osPoolId pool_id); + +/// Return an allocated memory block back to a specific memory pool. +/// \param[in] pool_id memory pool ID obtain referenced with \ref osPoolCreate. +/// \param[in] block address of the allocated memory block that is returned to the memory pool. +/// \return status code that indicates the execution status of the function. +/// \note MUST REMAIN UNCHANGED: \b osPoolFree shall be consistent in every CMSIS-RTOS. +osStatus osPoolFree (osPoolId pool_id, void *block); + +#endif // Memory Pool Management available + + +// ==== Message Queue Management Functions ==== + +#if (defined (osFeature_MessageQ) && (osFeature_MessageQ != 0)) // Message Queues available + +/// \brief Create a Message Queue Definition. +/// \param name name of the queue. +/// \param queue_sz maximum number of messages in the queue. +/// \param type data type of a single message element (for debugger). +/// \note CAN BE CHANGED: The parameter to \b osMessageQDef shall be consistent but the +/// macro body is implementation specific in every CMSIS-RTOS. +#if defined (osObjectsExternal) // object is external +#define osMessageQDef(name, queue_sz, type) \ +extern osMessageQDef_t os_messageQ_def_##name +#else // define the object +#define osMessageQDef(name, queue_sz, type) \ +uint32_t os_messageQ_q_##name[4+(queue_sz)]; \ +osMessageQDef_t os_messageQ_def_##name = \ +{ (queue_sz), (os_messageQ_q_##name) } +#endif + +/// \brief Access a Message Queue Definition. +/// \param name name of the queue +/// \note CAN BE CHANGED: The parameter to \b osMessageQ shall be consistent but the +/// macro body is implementation specific in every CMSIS-RTOS. +#define osMessageQ(name) \ +&os_messageQ_def_##name + +/// Create and Initialize a Message Queue. +/// \param[in] queue_def queue definition referenced with \ref osMessageQ. +/// \param[in] thread_id thread ID (obtained by \ref osThreadCreate or \ref osThreadGetId) or NULL. +/// \return message queue ID for reference by other functions or NULL in case of error. +/// \note MUST REMAIN UNCHANGED: \b osMessageCreate shall be consistent in every CMSIS-RTOS. +osMessageQId osMessageCreate (osMessageQDef_t *queue_def, osThreadId thread_id); + +/// Put a Message to a Queue. +/// \param[in] queue_id message queue ID obtained with \ref osMessageCreate. +/// \param[in] info message information. +/// \param[in] millisec timeout value or 0 in case of no time-out. +/// \return status code that indicates the execution status of the function. +/// \note MUST REMAIN UNCHANGED: \b osMessagePut shall be consistent in every CMSIS-RTOS. +osStatus osMessagePut (osMessageQId queue_id, uint32_t info, uint32_t millisec); + +/// Get a Message or Wait for a Message from a Queue. +/// \param[in] queue_id message queue ID obtained with \ref osMessageCreate. +/// \param[in] millisec timeout value or 0 in case of no time-out. +/// \return event information that includes status code. +/// \note MUST REMAIN UNCHANGED: \b osMessageGet shall be consistent in every CMSIS-RTOS. +os_InRegs osEvent osMessageGet (osMessageQId queue_id, uint32_t millisec); + +#endif // Message Queues available + + +// ==== Mail Queue Management Functions ==== + +#if (defined (osFeature_MailQ) && (osFeature_MailQ != 0)) // Mail Queues available + +/// \brief Create a Mail Queue Definition. +/// \param name name of the queue +/// \param queue_sz maximum number of messages in queue +/// \param type data type of a single message element +/// \note CAN BE CHANGED: The parameter to \b osMailQDef shall be consistent but the +/// macro body is implementation specific in every CMSIS-RTOS. +#if defined (osObjectsExternal) // object is external +#define osMailQDef(name, queue_sz, type) \ +extern osMailQDef_t os_mailQ_def_##name +#else // define the object +#define osMailQDef(name, queue_sz, type) \ +uint32_t os_mailQ_q_##name[4+(queue_sz)]; \ +uint32_t os_mailQ_m_##name[3+((sizeof(type)+3)/4)*(queue_sz)]; \ +void * os_mailQ_p_##name[2] = { (os_mailQ_q_##name), os_mailQ_m_##name }; \ +osMailQDef_t os_mailQ_def_##name = \ +{ (queue_sz), sizeof(type), (os_mailQ_p_##name) } +#endif + +/// \brief Access a Mail Queue Definition. +/// \param name name of the queue +/// \note CAN BE CHANGED: The parameter to \b osMailQ shall be consistent but the +/// macro body is implementation specific in every CMSIS-RTOS. +#define osMailQ(name) \ +&os_mailQ_def_##name + +/// Create and Initialize mail queue. +/// \param[in] queue_def reference to the mail queue definition obtain with \ref osMailQ +/// \param[in] thread_id thread ID (obtained by \ref osThreadCreate or \ref osThreadGetId) or NULL. +/// \return mail queue ID for reference by other functions or NULL in case of error. +/// \note MUST REMAIN UNCHANGED: \b osMailCreate shall be consistent in every CMSIS-RTOS. +osMailQId osMailCreate (osMailQDef_t *queue_def, osThreadId thread_id); + +/// Allocate a memory block from a mail. +/// \param[in] queue_id mail queue ID obtained with \ref osMailCreate. +/// \param[in] millisec timeout value or 0 in case of no time-out +/// \return pointer to memory block that can be filled with mail or NULL in case of error. +/// \note MUST REMAIN UNCHANGED: \b osMailAlloc shall be consistent in every CMSIS-RTOS. +void *osMailAlloc (osMailQId queue_id, uint32_t millisec); + +/// Allocate a memory block from a mail and set memory block to zero. +/// \param[in] queue_id mail queue ID obtained with \ref osMailCreate. +/// \param[in] millisec timeout value or 0 in case of no time-out +/// \return pointer to memory block that can be filled with mail or NULL in case of error. +/// \note MUST REMAIN UNCHANGED: \b osMailCAlloc shall be consistent in every CMSIS-RTOS. +void *osMailCAlloc (osMailQId queue_id, uint32_t millisec); + +/// Put a mail to a queue. +/// \param[in] queue_id mail queue ID obtained with \ref osMailCreate. +/// \param[in] mail memory block previously allocated with \ref osMailAlloc or \ref osMailCAlloc. +/// \return status code that indicates the execution status of the function. +/// \note MUST REMAIN UNCHANGED: \b osMailPut shall be consistent in every CMSIS-RTOS. +osStatus osMailPut (osMailQId queue_id, void *mail); + +/// Get a mail from a queue. +/// \param[in] queue_id mail queue ID obtained with \ref osMailCreate. +/// \param[in] millisec timeout value or 0 in case of no time-out +/// \return event that contains mail information or error code. +/// \note MUST REMAIN UNCHANGED: \b osMailGet shall be consistent in every CMSIS-RTOS. +os_InRegs osEvent osMailGet (osMailQId queue_id, uint32_t millisec); + +/// Free a memory block from a mail. +/// \param[in] queue_id mail queue ID obtained with \ref osMailCreate. +/// \param[in] mail pointer to the memory block that was obtained with \ref osMailGet. +/// \return status code that indicates the execution status of the function. +/// \note MUST REMAIN UNCHANGED: \b osMailFree shall be consistent in every CMSIS-RTOS. +osStatus osMailFree (osMailQId queue_id, void *mail); + +#endif // Mail Queues available + + +#ifdef __cplusplus +} +#endif + +#endif // _CMSIS_OS_H diff --git a/rtos/rtx/TARGET_ARM7/os_tcb.h b/rtos/rtx/TARGET_ARM7/os_tcb.h new file mode 100644 index 00000000000..7a8c5c379e3 --- /dev/null +++ b/rtos/rtx/TARGET_ARM7/os_tcb.h @@ -0,0 +1,55 @@ +#ifndef OS_TCB_H +#define OS_TCB_H + +/* Types */ +typedef char S8; +typedef unsigned char U8; +typedef short S16; +typedef unsigned short U16; +typedef int S32; +typedef unsigned int U32; +typedef long long S64; +typedef unsigned long long U64; +typedef unsigned char BIT; +typedef unsigned int BOOL; +typedef void (*FUNCP)(void); +#define TCB_STACK_LR_OFFSET_BYTES (14*4) // prelast DWORD +#define TCB_STACK_LR_OFFSET_DWORDS (14) // prelast DWORD +#define TCB_STACK_R0_OFFSET_BYTES (1*4) // second DWORD +#define TCB_STACK_R0_OFFSET_DWORDS (1) // second DWORD + +typedef struct OS_TCB { + /* General part: identical for all implementations. */ + U8 cb_type; /* Control Block Type */ + U8 state; /* Task state */ + U8 prio; /* Execution priority */ + U8 task_id; /* Task ID value for optimized TCB access */ + struct OS_TCB *p_lnk; /* Link pointer for ready/sem. wait list */ + struct OS_TCB *p_rlnk; /* Link pointer for sem./mbx lst backwards */ + struct OS_TCB *p_dlnk; /* Link pointer for delay list */ + struct OS_TCB *p_blnk; /* Link pointer for delay list backwards */ + U16 delta_time; /* Time until time out */ + U16 interval_time; /* Time interval for periodic waits */ + U16 events; /* Event flags */ + U16 waits; /* Wait flags */ + void **msg; /* Direct message passing when task waits */ + + /* Hardware dependant part: specific for CM processor */ + U8 stack_frame; /* Stack frame: 0=Basic, 1=Extended */ + U8 reserved1; + U16 reserved2; + U32 priv_stack; /* Private stack size in bytes */ + U32 tsk_stack; /* Current task Stack pointer (R13) */ + U32 *stack; /* Pointer to Task Stack memory block */ + + /* Library dependant part */ +#if defined (__CC_ARM) && !defined (__MICROLIB) + /* A memory space for arm standard library. */ + U32 std_libspace[96/4]; +#endif + + /* Task entry point used for uVision debugger */ + FUNCP ptask; /* Task entry address */ +} *P_TCB; + +#endif diff --git a/rtos/rtx/TARGET_ARM7/rt_CMSIS.c b/rtos/rtx/TARGET_ARM7/rt_CMSIS.c new file mode 100644 index 00000000000..b2992c8050b --- /dev/null +++ b/rtos/rtx/TARGET_ARM7/rt_CMSIS.c @@ -0,0 +1,1853 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: rt_CMSIS.c + * Purpose: CMSIS RTOS API + * Rev.: V4.60 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 ARM Germany GmbH + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + +#define __CMSIS_GENERIC + +#include "core_arm7.h" + +#include "rt_TypeDef.h" +#include "RTX_Conf.h" +#include "rt_System.h" +#include "rt_Task.h" +#include "rt_Event.h" +#include "rt_List.h" +#include "rt_Time.h" +#include "rt_Mutex.h" +#include "rt_Semaphore.h" +#include "rt_Mailbox.h" +#include "rt_MemBox.h" +#include "rt_HAL_CM.h" + +#define os_thread_cb OS_TCB + +#include "cmsis_os.h" + +#if (osFeature_Signals != 16) +#error Invalid "osFeature_Signals" value! +#endif +#if (osFeature_Semaphore > 65535) +#error Invalid "osFeature_Semaphore" value! +#endif +#if (osFeature_Wait != 0) +#error osWait not supported! +#endif + + +// ==== Enumeration, structures, defines ==== + +// Service Calls defines + +#if defined (__CC_ARM) /* ARM Compiler */ + +#define __NO_RETURN __declspec(noreturn) + +#define osEvent_type osEvent +#define osEvent_ret_status ret +#define osEvent_ret_value ret +#define osEvent_ret_msg ret +#define osEvent_ret_mail ret + +#define osCallback_type osCallback +#define osCallback_ret ret + +#define SVC_0_1(f,t,...) \ +__svc_indirect(0) t _##f (t(*)()); \ + t f (void); \ +__attribute__((always_inline)) \ +static __inline t __##f (void) { \ + return _##f(f); \ +} + +#define SVC_1_1(f,t,t1,...) \ +__svc_indirect(0) t _##f (t(*)(t1),t1); \ + t f (t1 a1); \ +__attribute__((always_inline)) \ +static __inline t __##f (t1 a1) { \ + return _##f(f,a1); \ +} + +#define SVC_2_1(f,t,t1,t2,...) \ +__svc_indirect(0) t _##f (t(*)(t1,t2),t1,t2); \ + t f (t1 a1, t2 a2); \ +__attribute__((always_inline)) \ +static __inline t __##f (t1 a1, t2 a2) { \ + return _##f(f,a1,a2); \ +} + +#define SVC_3_1(f,t,t1,t2,t3,...) \ +__svc_indirect(0) t _##f (t(*)(t1,t2,t3),t1,t2,t3); \ + t f (t1 a1, t2 a2, t3 a3); \ +__attribute__((always_inline)) \ +static __inline t __##f (t1 a1, t2 a2, t3 a3) { \ + return _##f(f,a1,a2,a3); \ +} + +#define SVC_4_1(f,t,t1,t2,t3,t4,...) \ +__svc_indirect(0) t _##f (t(*)(t1,t2,t3,t4),t1,t2,t3,t4); \ + t f (t1 a1, t2 a2, t3 a3, t4 a4); \ +__attribute__((always_inline)) \ +static __inline t __##f (t1 a1, t2 a2, t3 a3, t4 a4) { \ + return _##f(f,a1,a2,a3,a4); \ +} + +#define SVC_1_2 SVC_1_1 +#define SVC_1_3 SVC_1_1 +#define SVC_2_3 SVC_2_1 + +#elif defined (__GNUC__) /* GNU Compiler */ + +#define __NO_RETURN __attribute__((noreturn)) + +typedef uint32_t __attribute__((vector_size(8))) ret64; +typedef uint32_t __attribute__((vector_size(16))) ret128; + +#define RET_pointer __r0 +#define RET_int32_t __r0 +#define RET_osStatus __r0 +#define RET_osPriority __r0 +#define RET_osEvent {(osStatus)__r0, {(uint32_t)__r1}, {(void *)__r2}} +#define RET_osCallback {(void *)__r0, (void *)__r1} + +#define osEvent_type ret128 +#define osEvent_ret_status (ret128){ret.status} +#define osEvent_ret_value (ret128){ret.status, ret.value.v} +#define osEvent_ret_msg (ret128){ret.status, ret.value.v, (uint32_t)ret.def.message_id} +#define osEvent_ret_mail (ret128){ret.status, ret.value.v, (uint32_t)ret.def.mail_id} + +#define osCallback_type ret64 +#define osCallback_ret (ret64) {(uint32_t)ret.fp, (uint32_t)ret.arg} + +#define SVC_ArgN(n) \ + register int __r##n __asm("r"#n); + +#define SVC_ArgR(n,t,a) \ + register t __r##n __asm("r"#n) = a; + +#define SVC_Arg0() \ + SVC_ArgN(0) \ + SVC_ArgN(1) \ + SVC_ArgN(2) \ + SVC_ArgN(3) + +#define SVC_Arg1(t1) \ + SVC_ArgR(0,t1,a1) \ + SVC_ArgN(1) \ + SVC_ArgN(2) \ + SVC_ArgN(3) + +#define SVC_Arg2(t1,t2) \ + SVC_ArgR(0,t1,a1) \ + SVC_ArgR(1,t2,a2) \ + SVC_ArgN(2) \ + SVC_ArgN(3) + +#define SVC_Arg3(t1,t2,t3) \ + SVC_ArgR(0,t1,a1) \ + SVC_ArgR(1,t2,a2) \ + SVC_ArgR(2,t3,a3) \ + SVC_ArgN(3) + +#define SVC_Arg4(t1,t2,t3,t4) \ + SVC_ArgR(0,t1,a1) \ + SVC_ArgR(1,t2,a2) \ + SVC_ArgR(2,t3,a3) \ + SVC_ArgR(3,t4,a4) + +#if (defined (__CORTEX_M0)) || defined (__CORTEX_M0PLUS) +#define SVC_Call(f) \ + __asm volatile \ + ( \ + "ldr r7,="#f"\n\t" \ + "mov r12,r7\n\t" \ + "svc 0" \ + : "=r" (__r0), "=r" (__r1), "=r" (__r2), "=r" (__r3) \ + : "r" (__r0), "r" (__r1), "r" (__r2), "r" (__r3) \ + : "r7", "r12", "lr", "cc" \ + ); +#else +#define SVC_Call(f) \ + __asm volatile \ + ( \ + "ldr r12,="#f"\n\t" \ + "svc 0" \ + : "=r" (__r0), "=r" (__r1), "=r" (__r2), "=r" (__r3) \ + : "r" (__r0), "r" (__r1), "r" (__r2), "r" (__r3) \ + : "r12", "lr", "cc" \ + ); +#endif + +#define SVC_0_1(f,t,rv) \ +__attribute__((always_inline)) \ +static inline t __##f (void) { \ + SVC_Arg0(); \ + SVC_Call(f); \ + return (t) rv; \ +} + +#define SVC_1_1(f,t,t1,rv) \ +__attribute__((always_inline)) \ +static inline t __##f (t1 a1) { \ + SVC_Arg1(t1); \ + SVC_Call(f); \ + return (t) rv; \ +} + +#define SVC_2_1(f,t,t1,t2,rv) \ +__attribute__((always_inline)) \ +static inline t __##f (t1 a1, t2 a2) { \ + SVC_Arg2(t1,t2); \ + SVC_Call(f); \ + return (t) rv; \ +} + +#define SVC_3_1(f,t,t1,t2,t3,rv) \ +__attribute__((always_inline)) \ +static inline t __##f (t1 a1, t2 a2, t3 a3) { \ + SVC_Arg3(t1,t2,t3); \ + SVC_Call(f); \ + return (t) rv; \ +} + +#define SVC_4_1(f,t,t1,t2,t3,t4,rv) \ +__attribute__((always_inline)) \ +static inline t __##f (t1 a1, t2 a2, t3 a3, t4 a4) { \ + SVC_Arg4(t1,t2,t3,t4); \ + SVC_Call(f); \ + return (t) rv; \ +} + +#define SVC_1_2 SVC_1_1 +#define SVC_1_3 SVC_1_1 +#define SVC_2_3 SVC_2_1 + +#elif defined (__ICCARM__) /* IAR Compiler */ + +#define __NO_RETURN __noreturn + +#define osEvent_type osEvent +#define osEvent_ret_status ret +#define osEvent_ret_value ret +#define osEvent_ret_msg ret +#define osEvent_ret_mail ret + +#define osCallback_type osCallback +#define osCallback_ret ret + +#define RET_osEvent osEvent +#define RET_osCallback osCallback + +#define SVC_Setup(f) \ + __asm( \ + "mov r12,%0\n" \ + :: "r"(&f): "r12" \ + ); + + +#define SVC_0_1(f,t,...) \ +t f (void); \ +_Pragma("swi_number=0") __swi t _##f (void); \ +static inline t __##f (void) { \ + SVC_Setup(f); \ + return _##f(); \ +} + +#define SVC_1_1(f,t,t1,...) \ +t f (t1 a1); \ +_Pragma("swi_number=0") __swi t _##f (t1 a1); \ +static inline t __##f (t1 a1) { \ + SVC_Setup(f); \ + return _##f(a1); \ +} + +#define SVC_2_1(f,t,t1,t2,...) \ +t f (t1 a1, t2 a2); \ +_Pragma("swi_number=0") __swi t _##f (t1 a1, t2 a2); \ +static inline t __##f (t1 a1, t2 a2) { \ + SVC_Setup(f); \ + return _##f(a1,a2); \ +} + +#define SVC_3_1(f,t,t1,t2,t3,...) \ +t f (t1 a1, t2 a2, t3 a3); \ +_Pragma("swi_number=0") __swi t _##f (t1 a1, t2 a2, t3 a3); \ +static inline t __##f (t1 a1, t2 a2, t3 a3) { \ + SVC_Setup(f); \ + return _##f(a1,a2,a3); \ +} + +#define SVC_4_1(f,t,t1,t2,t3,t4,...) \ +t f (t1 a1, t2 a2, t3 a3, t4 a4); \ +_Pragma("swi_number=0") __swi t _##f (t1 a1, t2 a2, t3 a3, t4 a4); \ +static inline t __##f (t1 a1, t2 a2, t3 a3, t4 a4) { \ + SVC_Setup(f); \ + return _##f(a1,a2,a3,a4); \ +} + +#define SVC_1_2 SVC_1_1 +#define SVC_1_3 SVC_1_1 +#define SVC_2_3 SVC_2_1 + +#endif + + +// Callback structure +typedef struct { + void *fp; // Function pointer + void *arg; // Function argument +} osCallback; + + +// OS Section definitions +#ifdef OS_SECTIONS_LINK_INFO +extern const uint32_t os_section_id$$Base; +extern const uint32_t os_section_id$$Limit; +#endif + +// OS Timers external resources +extern osThreadDef_t os_thread_def_osTimerThread; +extern osThreadId osThreadId_osTimerThread; +extern osMessageQDef_t os_messageQ_def_osTimerMessageQ; +extern osMessageQId osMessageQId_osTimerMessageQ; + + +// ==== Helper Functions ==== + +/// Convert timeout in millisec to system ticks +static uint32_t rt_ms2tick (uint32_t millisec) { + uint32_t tick; + + if (millisec == osWaitForever) return 0xFFFF; // Indefinite timeout + if (millisec > 4000000) return 0xFFFE; // Max ticks supported + + tick = ((1000 * millisec) + os_clockrate - 1) / os_clockrate; + if (tick > 0xFFFE) return 0xFFFE; + + return tick; +} + +/// Convert Thread ID to TCB pointer +static P_TCB rt_tid2ptcb (osThreadId thread_id) { + P_TCB ptcb; + + if (thread_id == NULL) return NULL; + + if ((uint32_t)thread_id & 3) return NULL; + +#ifdef OS_SECTIONS_LINK_INFO + if ((os_section_id$$Base != 0) && (os_section_id$$Limit != 0)) { + if (thread_id < (osThreadId)os_section_id$$Base) return NULL; + if (thread_id >= (osThreadId)os_section_id$$Limit) return NULL; + } +#endif + + ptcb = thread_id; + + if (ptcb->cb_type != TCB) return NULL; + + return ptcb; +} + +/// Convert ID pointer to Object pointer +static void *rt_id2obj (void *id) { + + if ((uint32_t)id & 3) return NULL; + +#ifdef OS_SECTIONS_LINK_INFO + if ((os_section_id$$Base != 0) && (os_section_id$$Limit != 0)) { + if (id < (void *)os_section_id$$Base) return NULL; + if (id >= (void *)os_section_id$$Limit) return NULL; + } +#endif + + return id; +} + + +// ==== Kernel Control ==== + +uint8_t os_initialized; // Kernel Initialized flag +uint8_t os_running; // Kernel Running flag + +// Kernel Control Service Calls declarations +SVC_0_1(svcKernelInitialize, osStatus, RET_osStatus) +SVC_0_1(svcKernelStart, osStatus, RET_osStatus) +SVC_0_1(svcKernelRunning, int32_t, RET_int32_t) + +extern void sysThreadError (osStatus status); +osThreadId svcThreadCreate (osThreadDef_t *thread_def, void *argument); +osMessageQId svcMessageCreate (osMessageQDef_t *queue_def, osThreadId thread_id); + +// Kernel Control Service Calls + +/// Initialize the RTOS Kernel for creating objects +osStatus svcKernelInitialize (void) { + if (os_initialized) return osOK; + + rt_sys_init(); // RTX System Initialization + os_tsk.run->prio = 255; // Highest priority + + sysThreadError(osOK); + + os_initialized = 1; + + return osOK; +} + +/// Start the RTOS Kernel +osStatus svcKernelStart (void) { + + if (os_running) return osOK; + + // Create OS Timers resources (Message Queue & Thread) + osMessageQId_osTimerMessageQ = svcMessageCreate (&os_messageQ_def_osTimerMessageQ, NULL); + osThreadId_osTimerThread = svcThreadCreate(&os_thread_def_osTimerThread, NULL); + + rt_tsk_prio(0, 0); // Lowest priority +// __set_SP(os_tsk.run->tsk_stack + 8*4); // New context + os_tsk.run = NULL; // Force context switch + + rt_sys_start(); + + os_running = 1; + + return osOK; +} + +/// Check if the RTOS kernel is already started +int32_t svcKernelRunning(void) { + return os_running; +} + +// Kernel Control Public API + +/// Initialize the RTOS Kernel for creating objects +osStatus osKernelInitialize (void) { + if (__get_CONTROL() == MODE_IRQ) return osErrorISR; // Not allowed in ISR + if (__get_CONTROL() == MODE_SUPERVISOR) { // Privileged mode + return svcKernelInitialize(); + } else { + return __svcKernelInitialize(); + } +} + +/// Start the RTOS Kernel +osStatus osKernelStart (void) { + + if (__get_CONTROL() == MODE_IRQ) return osErrorISR; // Not allowed in ISR + switch (__get_CONTROL()) { + case MODE_SUPERVISOR: // Privileged mode + break; + case MODE_USER: + case MODE_SYSTEM: // Unprivileged mode + return osErrorOS; + default: // Other invalid modes + return osErrorOS; + break; + } + return svcKernelStart(); +} + +/// Check if the RTOS kernel is already started +int32_t osKernelRunning(void) { + if ((__get_CONTROL() == MODE_IRQ) || (__get_CONTROL() == MODE_SUPERVISOR)) { + // in ISR or Privileged + return os_running; + } else { + return __svcKernelRunning(); + } +} + + +// ==== Thread Management ==== + +__NO_RETURN void osThreadExit (void); + +// Thread Service Calls declarations +SVC_2_1(svcThreadCreate, osThreadId, osThreadDef_t *, void *, RET_pointer) +SVC_0_1(svcThreadGetId, osThreadId, RET_pointer) +SVC_1_1(svcThreadTerminate, osStatus, osThreadId, RET_osStatus) +SVC_0_1(svcThreadYield, osStatus, RET_osStatus) +SVC_2_1(svcThreadSetPriority, osStatus, osThreadId, osPriority, RET_osStatus) +SVC_1_1(svcThreadGetPriority, osPriority, osThreadId, RET_osPriority) + +// Thread Service Calls +extern OS_TID rt_get_TID (void); +extern void rt_init_context (P_TCB p_TCB, U8 priority, FUNCP task_body); + +/// Create a thread and add it to Active Threads and set it to state READY +osThreadId svcThreadCreate (osThreadDef_t *thread_def, void *argument) { + P_TCB ptcb; + + if ((thread_def == NULL) || + (thread_def->pthread == NULL) || + (thread_def->tpriority < osPriorityIdle) || + (thread_def->tpriority > osPriorityRealtime) || + (thread_def->stacksize == 0) || + (thread_def->stack_pointer == NULL) ) { + sysThreadError(osErrorParameter); + return NULL; + } + + U8 priority = thread_def->tpriority - osPriorityIdle + 1; + P_TCB task_context = &thread_def->tcb; + + /* Utilize the user provided stack. */ + task_context->stack = (U32*)thread_def->stack_pointer; + task_context->priv_stack = thread_def->stacksize; + /* Find a free entry in 'os_active_TCB' table. */ + OS_TID tsk = rt_get_TID (); + os_active_TCB[tsk-1] = task_context; + task_context->task_id = tsk; + /* Pass parameter 'argv' to 'rt_init_context' */ + task_context->msg = argument; + /* For 'size == 0' system allocates the user stack from the memory pool. */ + rt_init_context (task_context, priority, (FUNCP)thread_def->pthread); + + /* Dispatch this task to the scheduler for execution. */ + DBG_TASK_NOTIFY(task_context, __TRUE); + rt_dispatch (task_context); + + ptcb = (P_TCB)os_active_TCB[tsk - 1]; // TCB pointer + + *((uint32_t *)ptcb->tsk_stack + TCB_STACK_LR_OFFSET_DWORDS) = (uint32_t)osThreadExit; /* LR = osThreadExit */ + + return ptcb; +} + +/// Return the thread ID of the current running thread +osThreadId svcThreadGetId (void) { + OS_TID tsk; + + tsk = rt_tsk_self(); + if (tsk == 0) return NULL; + return (P_TCB)os_active_TCB[tsk - 1]; +} + +/// Terminate execution of a thread and remove it from ActiveThreads +osStatus svcThreadTerminate (osThreadId thread_id) { + OS_RESULT res; + P_TCB ptcb; + + ptcb = rt_tid2ptcb(thread_id); // Get TCB pointer + if (ptcb == NULL) return osErrorParameter; + + res = rt_tsk_delete(ptcb->task_id); // Delete task + + if (res == OS_R_NOK) return osErrorResource; // Delete task failed + + return osOK; +} + +/// Pass control to next thread that is in state READY +osStatus svcThreadYield (void) { + rt_tsk_pass(); // Pass control to next task + return osOK; +} + +/// Change priority of an active thread +osStatus svcThreadSetPriority (osThreadId thread_id, osPriority priority) { + OS_RESULT res; + P_TCB ptcb; + + ptcb = rt_tid2ptcb(thread_id); // Get TCB pointer + if (ptcb == NULL) return osErrorParameter; + + if ((priority < osPriorityIdle) || (priority > osPriorityRealtime)) { + return osErrorValue; + } + + res = rt_tsk_prio( // Change task priority + ptcb->task_id, // Task ID + priority - osPriorityIdle + 1 // New task priority + ); + + if (res == OS_R_NOK) return osErrorResource; // Change task priority failed + + return osOK; +} + +/// Get current priority of an active thread +osPriority svcThreadGetPriority (osThreadId thread_id) { + P_TCB ptcb; + + ptcb = rt_tid2ptcb(thread_id); // Get TCB pointer + if (ptcb == NULL) return osPriorityError; + + return (osPriority)(ptcb->prio - 1 + osPriorityIdle); +} + + +// Thread Public API + +/// Create a thread and add it to Active Threads and set it to state READY +osThreadId osThreadCreate (osThreadDef_t *thread_def, void *argument) { + if (__get_CONTROL() == MODE_IRQ) return NULL; // Not allowed in ISR + if ((__get_CONTROL() == MODE_SUPERVISOR) && (os_running == 0)) { + // Privileged and not running + return svcThreadCreate(thread_def, argument); + } else { + return __svcThreadCreate(thread_def, argument); + } +} + +/// Return the thread ID of the current running thread +osThreadId osThreadGetId (void) { + if (__get_CONTROL() == MODE_IRQ) return NULL; // Not allowed in ISR + return __svcThreadGetId(); +} + +/// Terminate execution of a thread and remove it from ActiveThreads +osStatus osThreadTerminate (osThreadId thread_id) { + if (__get_CONTROL() == MODE_IRQ) return osErrorISR; // Not allowed in ISR + return __svcThreadTerminate(thread_id); +} + +/// Pass control to next thread that is in state READY +osStatus osThreadYield (void) { + if (__get_CONTROL() == MODE_IRQ) return osErrorISR; // Not allowed in ISR + return __svcThreadYield(); +} + +/// Change priority of an active thread +osStatus osThreadSetPriority (osThreadId thread_id, osPriority priority) { + if (__get_CONTROL() == MODE_IRQ) return osErrorISR; // Not allowed in ISR + return __svcThreadSetPriority(thread_id, priority); +} + +/// Get current priority of an active thread +osPriority osThreadGetPriority (osThreadId thread_id) { + if (__get_CONTROL() == MODE_IRQ) return osPriorityError;// Not allowed in ISR + return __svcThreadGetPriority(thread_id); +} + +/// INTERNAL - Not Public +/// Auto Terminate Thread on exit (used implicitly when thread exists) +__NO_RETURN void osThreadExit (void) { + __svcThreadTerminate(__svcThreadGetId()); + for (;;); // Should never come here +} + + +// ==== Generic Wait Functions ==== + +// Generic Wait Service Calls declarations +SVC_1_1(svcDelay, osStatus, uint32_t, RET_osStatus) +#if osFeature_Wait != 0 +SVC_1_3(svcWait, os_InRegs osEvent, uint32_t, RET_osEvent) +#endif + +// Generic Wait Service Calls + +/// Wait for Timeout (Time Delay) +osStatus svcDelay (uint32_t millisec) { + if (millisec == 0) return osOK; + rt_dly_wait(rt_ms2tick(millisec)); + return osEventTimeout; +} + +/// Wait for Signal, Message, Mail, or Timeout +#if osFeature_Wait != 0 +os_InRegs osEvent_type svcWait (uint32_t millisec) { + osEvent ret; + + if (millisec == 0) { + ret.status = osOK; + return osEvent_ret_status; + } + + /* To Do: osEventSignal, osEventMessage, osEventMail */ + rt_dly_wait(rt_ms2tick(millisec)); + ret.status = osEventTimeout; + + return osEvent_ret_status; +} +#endif + + +// Generic Wait API + +/// Wait for Timeout (Time Delay) +osStatus osDelay (uint32_t millisec) { + if (__get_CONTROL() == MODE_IRQ) return osErrorISR; // Not allowed in ISR + return __svcDelay(millisec); +} + +/// Wait for Signal, Message, Mail, or Timeout +os_InRegs osEvent osWait (uint32_t millisec) { + osEvent ret; + +#if osFeature_Wait == 0 + ret.status = osErrorOS; + return ret; +#else + if (__get_CONTROL() == MODE_IRQ) { // Not allowed in ISR + ret.status = osErrorISR; + return ret; + } + return __svcWait(millisec); +#endif +} + + +// ==== Timer Management ==== + +// Timer definitions +#define osTimerInvalid 0 +#define osTimerStopped 1 +#define osTimerRunning 2 + +// Timer structures + +typedef struct os_timer_cb_ { // Timer Control Block + struct os_timer_cb_ *next; // Pointer to next active Timer + uint8_t state; // Timer State + uint8_t type; // Timer Type (Periodic/One-shot) + uint16_t reserved; // Reserved + uint16_t tcnt; // Timer Delay Count + uint16_t icnt; // Timer Initial Count + void *arg; // Timer Function Argument + osTimerDef_t *timer; // Pointer to Timer definition +} os_timer_cb; + +// Timer variables +os_timer_cb *os_timer_head; // Pointer to first active Timer + + +// Timer Helper Functions + +// Insert Timer into the list sorted by time +static void rt_timer_insert (os_timer_cb *pt, uint32_t tcnt) { + os_timer_cb *p, *prev; + + prev = NULL; + p = os_timer_head; + while (p != NULL) { + if (tcnt < p->tcnt) break; + tcnt -= p->tcnt; + prev = p; + p = p->next; + } + pt->next = p; + pt->tcnt = (uint16_t)tcnt; + if (p != NULL) { + p->tcnt -= pt->tcnt; + } + if (prev != NULL) { + prev->next = pt; + } else { + os_timer_head = pt; + } +} + +// Remove Timer from the list +static int rt_timer_remove (os_timer_cb *pt) { + os_timer_cb *p, *prev; + + prev = NULL; + p = os_timer_head; + while (p != NULL) { + if (p == pt) break; + prev = p; + p = p->next; + } + if (p == NULL) return -1; + if (prev != NULL) { + prev->next = pt->next; + } else { + os_timer_head = pt->next; + } + if (pt->next != NULL) { + pt->next->tcnt += pt->tcnt; + } + + return 0; +} + + +// Timer Service Calls declarations +SVC_3_1(svcTimerCreate, osTimerId, osTimerDef_t *, os_timer_type, void *, RET_pointer) +SVC_2_1(svcTimerStart, osStatus, osTimerId, uint32_t, RET_osStatus) +SVC_1_1(svcTimerStop, osStatus, osTimerId, RET_osStatus) +SVC_1_1(svcTimerDelete, osStatus, osTimerId, RET_osStatus) +SVC_1_2(svcTimerCall, os_InRegs osCallback, osTimerId, RET_osCallback) + +// Timer Management Service Calls + +/// Create timer +osTimerId svcTimerCreate (osTimerDef_t *timer_def, os_timer_type type, void *argument) { + os_timer_cb *pt; + + if ((timer_def == NULL) || (timer_def->ptimer == NULL)) { + sysThreadError(osErrorParameter); + return NULL; + } + + pt = timer_def->timer; + if (pt == NULL) { + sysThreadError(osErrorParameter); + return NULL; + } + + if ((type != osTimerOnce) && (type != osTimerPeriodic)) { + sysThreadError(osErrorValue); + return NULL; + } + + if (osThreadId_osTimerThread == NULL) { + sysThreadError(osErrorResource); + return NULL; + } + + if (pt->state != osTimerInvalid){ + sysThreadError(osErrorResource); + return NULL; + } + + pt->state = osTimerStopped; + pt->type = (uint8_t)type; + pt->arg = argument; + pt->timer = timer_def; + + return (osTimerId)pt; +} + +/// Start or restart timer +osStatus svcTimerStart (osTimerId timer_id, uint32_t millisec) { + os_timer_cb *pt; + uint32_t tcnt; + + pt = rt_id2obj(timer_id); + if (pt == NULL) return osErrorParameter; + + tcnt = rt_ms2tick(millisec); + if (tcnt == 0) return osErrorValue; + + switch (pt->state) { + case osTimerRunning: + if (rt_timer_remove(pt) != 0) { + return osErrorResource; + } + break; + case osTimerStopped: + pt->state = osTimerRunning; + pt->icnt = (uint16_t)tcnt; + break; + default: + return osErrorResource; + } + + rt_timer_insert(pt, tcnt); + + return osOK; +} + +/// Stop timer +osStatus svcTimerStop (osTimerId timer_id) { + os_timer_cb *pt; + + pt = rt_id2obj(timer_id); + if (pt == NULL) return osErrorParameter; + + if (pt->state != osTimerRunning) return osErrorResource; + + pt->state = osTimerStopped; + + if (rt_timer_remove(pt) != 0) { + return osErrorResource; + } + + return osOK; +} + +/// Delete timer +osStatus svcTimerDelete (osTimerId timer_id) { + os_timer_cb *pt; + + pt = rt_id2obj(timer_id); + if (pt == NULL) return osErrorParameter; + + switch (pt->state) { + case osTimerRunning: + rt_timer_remove(pt); + break; + case osTimerStopped: + break; + default: + return osErrorResource; + } + + pt->state = osTimerInvalid; + + return osOK; +} + +/// Get timer callback parameters +os_InRegs osCallback_type svcTimerCall (osTimerId timer_id) { + os_timer_cb *pt; + osCallback ret; + + pt = rt_id2obj(timer_id); + if (pt == NULL) { + ret.fp = NULL; + ret.arg = NULL; + return osCallback_ret; + } + + ret.fp = (void *)pt->timer->ptimer; + ret.arg = pt->arg; + + return osCallback_ret; +} + +static __INLINE osStatus isrMessagePut (osMessageQId queue_id, uint32_t info, uint32_t millisec); + +/// Timer Tick (called each SysTick) +void sysTimerTick (void) { + os_timer_cb *pt, *p; + + p = os_timer_head; + if (p == NULL) return; + + p->tcnt--; + while ((p != NULL) && (p->tcnt == 0)) { + pt = p; + p = p->next; + os_timer_head = p; + isrMessagePut(osMessageQId_osTimerMessageQ, (uint32_t)pt, 0); + if (pt->type == osTimerPeriodic) { + rt_timer_insert(pt, pt->icnt); + } else { + pt->state = osTimerStopped; + } + } +} + + +// Timer Management Public API + +/// Create timer +osTimerId osTimerCreate (osTimerDef_t *timer_def, os_timer_type type, void *argument) { + if (__get_CONTROL() == MODE_IRQ) return NULL; // Not allowed in ISR + if ((__get_CONTROL() == MODE_SUPERVISOR) && (os_running == 0)) { + // Privileged and not running + return svcTimerCreate(timer_def, type, argument); + } else { + return __svcTimerCreate(timer_def, type, argument); + } +} + +/// Start or restart timer +osStatus osTimerStart (osTimerId timer_id, uint32_t millisec) { + if (__get_CONTROL() == MODE_IRQ) return osErrorISR; // Not allowed in ISR + return __svcTimerStart(timer_id, millisec); +} + +/// Stop timer +osStatus osTimerStop (osTimerId timer_id) { + if (__get_CONTROL() == MODE_IRQ) return osErrorISR; // Not allowed in ISR + return __svcTimerStop(timer_id); +} + +/// Delete timer +osStatus osTimerDelete (osTimerId timer_id) { + if (__get_CONTROL() == MODE_IRQ) return osErrorISR; // Not allowed in ISR + return __svcTimerDelete(timer_id); +} + +/// INTERNAL - Not Public +/// Get timer callback parameters (used by OS Timer Thread) +os_InRegs osCallback osTimerCall (osTimerId timer_id) { + return __svcTimerCall(timer_id); +} + + +// Timer Thread +__NO_RETURN void osTimerThread (void const *argument) { + osCallback cb; + osEvent evt; + + for (;;) { + evt = osMessageGet(osMessageQId_osTimerMessageQ, osWaitForever); + if (evt.status == osEventMessage) { + cb = osTimerCall(evt.value.p); + if (cb.fp != NULL) { + (*(os_ptimer)cb.fp)(cb.arg); + } + } + } +} + + +// ==== Signal Management ==== + +// Signal Service Calls declarations +SVC_2_1(svcSignalSet, int32_t, osThreadId, int32_t, RET_int32_t) +SVC_2_1(svcSignalClear, int32_t, osThreadId, int32_t, RET_int32_t) +SVC_1_1(svcSignalGet, int32_t, osThreadId, RET_int32_t) +SVC_2_3(svcSignalWait, os_InRegs osEvent, int32_t, uint32_t, RET_osEvent) + +// Signal Service Calls + +/// Set the specified Signal Flags of an active thread +int32_t svcSignalSet (osThreadId thread_id, int32_t signals) { + P_TCB ptcb; + int32_t sig; + + ptcb = rt_tid2ptcb(thread_id); // Get TCB pointer + if (ptcb == NULL) return 0x80000000; + + if (signals & (0xFFFFFFFF << osFeature_Signals)) return 0x80000000; + + sig = ptcb->events; // Previous signal flags + + rt_evt_set(signals, ptcb->task_id); // Set event flags + + return sig; +} + +/// Clear the specified Signal Flags of an active thread +int32_t svcSignalClear (osThreadId thread_id, int32_t signals) { + P_TCB ptcb; + int32_t sig; + + ptcb = rt_tid2ptcb(thread_id); // Get TCB pointer + if (ptcb == NULL) return 0x80000000; + + if (signals & (0xFFFFFFFF << osFeature_Signals)) return 0x80000000; + + sig = ptcb->events; // Previous signal flags + + rt_evt_clr(signals, ptcb->task_id); // Clear event flags + + return sig; +} + +/// Get Signal Flags status of an active thread +int32_t svcSignalGet (osThreadId thread_id) { + P_TCB ptcb; + + ptcb = rt_tid2ptcb(thread_id); // Get TCB pointer + if (ptcb == NULL) return 0x80000000; + + return ptcb->events; // Return event flags +} + +/// Wait for one or more Signal Flags to become signaled for the current RUNNING thread +os_InRegs osEvent_type svcSignalWait (int32_t signals, uint32_t millisec) { + OS_RESULT res; + osEvent ret; + + if (signals & (0xFFFFFFFF << osFeature_Signals)) { + ret.status = osErrorValue; + return osEvent_ret_status; + } + + if (signals != 0) { // Wait for all specified signals + res = rt_evt_wait(signals, rt_ms2tick(millisec), __TRUE); + } else { // Wait for any signal + res = rt_evt_wait(0xFFFF, rt_ms2tick(millisec), __FALSE); + } + + if (res == OS_R_EVT) { + ret.status = osEventSignal; + ret.value.signals = signals ? signals : os_tsk.run->waits; + } else { + ret.status = millisec ? osEventTimeout : osOK; + ret.value.signals = 0; + } + + return osEvent_ret_value; +} + + +// Signal ISR Calls + +/// Set the specified Signal Flags of an active thread +static __INLINE int32_t isrSignalSet (osThreadId thread_id, int32_t signals) { + P_TCB ptcb; + int32_t sig; + + ptcb = rt_tid2ptcb(thread_id); // Get TCB pointer + if (ptcb == NULL) return 0x80000000; + + if (signals & (0xFFFFFFFF << osFeature_Signals)) return 0x80000000; + + sig = ptcb->events; // Previous signal flags + + isr_evt_set(signals, ptcb->task_id); // Set event flags + + return sig; +} + + +// Signal Public API + +/// Set the specified Signal Flags of an active thread +int32_t osSignalSet (osThreadId thread_id, int32_t signals) { + if (__get_CONTROL() == MODE_IRQ) { // in ISR + return isrSignalSet(thread_id, signals); + } else { // in Thread + return __svcSignalSet(thread_id, signals); + } +} + +/// Clear the specified Signal Flags of an active thread +int32_t osSignalClear (osThreadId thread_id, int32_t signals) { + if (__get_CONTROL() == MODE_IRQ) return osErrorISR; // Not allowed in ISR + return __svcSignalClear(thread_id, signals); +} + +/// Get Signal Flags status of an active thread +int32_t osSignalGet (osThreadId thread_id) { + if (__get_CONTROL() == MODE_IRQ) return osErrorISR; // Not allowed in ISR + return __svcSignalGet(thread_id); +} + +/// Wait for one or more Signal Flags to become signaled for the current RUNNING thread +os_InRegs osEvent osSignalWait (int32_t signals, uint32_t millisec) { + osEvent ret; + + if (__get_CONTROL() == MODE_IRQ) { // Not allowed in ISR + ret.status = osErrorISR; + return ret; + } + return __svcSignalWait(signals, millisec); +} + + +// ==== Mutex Management ==== + +// Mutex Service Calls declarations +SVC_1_1(svcMutexCreate, osMutexId, osMutexDef_t *, RET_pointer) +SVC_2_1(svcMutexWait, osStatus, osMutexId, uint32_t, RET_osStatus) +SVC_1_1(svcMutexRelease, osStatus, osMutexId, RET_osStatus) +SVC_1_1(svcMutexDelete, osStatus, osMutexId, RET_osStatus) + +// Mutex Service Calls + +/// Create and Initialize a Mutex object +osMutexId svcMutexCreate (osMutexDef_t *mutex_def) { + OS_ID mut; + + if (mutex_def == NULL) { + sysThreadError(osErrorParameter); + return NULL; + } + + mut = mutex_def->mutex; + if (mut == NULL) { + sysThreadError(osErrorParameter); + return NULL; + } + + if (((P_MUCB)mut)->cb_type != 0) { + sysThreadError(osErrorParameter); + return NULL; + } + + rt_mut_init(mut); // Initialize Mutex + + return mut; +} + +/// Wait until a Mutex becomes available +osStatus svcMutexWait (osMutexId mutex_id, uint32_t millisec) { + OS_ID mut; + OS_RESULT res; + + mut = rt_id2obj(mutex_id); + if (mut == NULL) return osErrorParameter; + + if (((P_MUCB)mut)->cb_type != MUCB) return osErrorParameter; + + res = rt_mut_wait(mut, rt_ms2tick(millisec)); // Wait for Mutex + + if (res == OS_R_TMO) { + return (millisec ? osErrorTimeoutResource : osErrorResource); + } + + return osOK; +} + +/// Release a Mutex that was obtained with osMutexWait +osStatus svcMutexRelease (osMutexId mutex_id) { + OS_ID mut; + OS_RESULT res; + + mut = rt_id2obj(mutex_id); + if (mut == NULL) return osErrorParameter; + + if (((P_MUCB)mut)->cb_type != MUCB) return osErrorParameter; + + res = rt_mut_release(mut); // Release Mutex + + if (res == OS_R_NOK) return osErrorResource; // Thread not owner or Zero Counter + + return osOK; +} + +/// Delete a Mutex that was created by osMutexCreate +osStatus svcMutexDelete (osMutexId mutex_id) { + OS_ID mut; + + mut = rt_id2obj(mutex_id); + if (mut == NULL) return osErrorParameter; + + if (((P_MUCB)mut)->cb_type != MUCB) return osErrorParameter; + + rt_mut_delete(mut); // Release Mutex + + return osOK; +} + + +// Mutex Public API + +/// Create and Initialize a Mutex object +osMutexId osMutexCreate (osMutexDef_t *mutex_def) { + if (__get_CONTROL() == MODE_IRQ) return NULL; // Not allowed in ISR + if ((__get_CONTROL() == MODE_SUPERVISOR) && (os_running == 0)) { + // Privileged and not running + return svcMutexCreate(mutex_def); + } else { + return __svcMutexCreate(mutex_def); + } +} + +/// Wait until a Mutex becomes available +osStatus osMutexWait (osMutexId mutex_id, uint32_t millisec) { + if (__get_CONTROL() == MODE_IRQ) return osErrorISR; // Not allowed in ISR + return __svcMutexWait(mutex_id, millisec); +} + +/// Release a Mutex that was obtained with osMutexWait +osStatus osMutexRelease (osMutexId mutex_id) { + if (__get_CONTROL() == MODE_IRQ) return osErrorISR; // Not allowed in ISR + return __svcMutexRelease(mutex_id); +} + +/// Delete a Mutex that was created by osMutexCreate +osStatus osMutexDelete (osMutexId mutex_id) { + if (__get_CONTROL() == MODE_IRQ) return osErrorISR; // Not allowed in ISR + return __svcMutexDelete(mutex_id); +} + + +// ==== Semaphore Management ==== + +// Semaphore Service Calls declarations +SVC_2_1(svcSemaphoreCreate, osSemaphoreId, const osSemaphoreDef_t *, int32_t, RET_pointer) +SVC_2_1(svcSemaphoreWait, int32_t, osSemaphoreId, uint32_t, RET_int32_t) +SVC_1_1(svcSemaphoreRelease, osStatus, osSemaphoreId, RET_osStatus) +SVC_1_1(svcSemaphoreDelete, osStatus, osSemaphoreId, RET_osStatus) + +// Semaphore Service Calls + +/// Create and Initialize a Semaphore object +osSemaphoreId svcSemaphoreCreate (const osSemaphoreDef_t *semaphore_def, int32_t count) { + OS_ID sem; + + if (semaphore_def == NULL) { + sysThreadError(osErrorParameter); + return NULL; + } + + sem = semaphore_def->semaphore; + if (sem == NULL) { + sysThreadError(osErrorParameter); + return NULL; + } + + if (((P_SCB)sem)->cb_type != 0) { + sysThreadError(osErrorParameter); + return NULL; + } + + if (count > osFeature_Semaphore) { + sysThreadError(osErrorValue); + return NULL; + } + + rt_sem_init(sem, count); // Initialize Semaphore + + return sem; +} + +/// Wait until a Semaphore becomes available +int32_t svcSemaphoreWait (osSemaphoreId semaphore_id, uint32_t millisec) { + OS_ID sem; + OS_RESULT res; + + sem = rt_id2obj(semaphore_id); + if (sem == NULL) return -1; + + if (((P_SCB)sem)->cb_type != SCB) return -1; + + res = rt_sem_wait(sem, rt_ms2tick(millisec)); // Wait for Semaphore + + if (res == OS_R_TMO) return 0; // Timeout + + return (((P_SCB)sem)->tokens + 1); +} + +/// Release a Semaphore +osStatus svcSemaphoreRelease (osSemaphoreId semaphore_id) { + OS_ID sem; + + sem = rt_id2obj(semaphore_id); + if (sem == NULL) return osErrorParameter; + + if (((P_SCB)sem)->cb_type != SCB) return osErrorParameter; + + if (((P_SCB)sem)->tokens == osFeature_Semaphore) return osErrorResource; + + rt_sem_send(sem); // Release Semaphore + + return osOK; +} + +/// Delete a Semaphore that was created by osSemaphoreCreate +osStatus svcSemaphoreDelete (osSemaphoreId semaphore_id) { + OS_ID sem; + + sem = rt_id2obj(semaphore_id); + if (sem == NULL) return osErrorParameter; + + if (((P_SCB)sem)->cb_type != SCB) return osErrorParameter; + + rt_sem_delete(sem); // Delete Semaphore + + return osOK; +} + + +// Semaphore ISR Calls + +/// Release a Semaphore +static __INLINE osStatus isrSemaphoreRelease (osSemaphoreId semaphore_id) { + OS_ID sem; + + sem = rt_id2obj(semaphore_id); + if (sem == NULL) return osErrorParameter; + + if (((P_SCB)sem)->cb_type != SCB) return osErrorParameter; + + if (((P_SCB)sem)->tokens == osFeature_Semaphore) return osErrorResource; + + isr_sem_send(sem); // Release Semaphore + + return osOK; +} + + +// Semaphore Public API + +/// Create and Initialize a Semaphore object +osSemaphoreId osSemaphoreCreate (osSemaphoreDef_t *semaphore_def, int32_t count) { + if (__get_CONTROL() == MODE_IRQ) return NULL; // Not allowed in ISR + if ((__get_CONTROL() == MODE_SUPERVISOR) && (os_running == 0)) { + // Privileged and not running + return svcSemaphoreCreate(semaphore_def, count); + } else { + return __svcSemaphoreCreate(semaphore_def, count); + } +} + +/// Wait until a Semaphore becomes available +int32_t osSemaphoreWait (osSemaphoreId semaphore_id, uint32_t millisec) { + if (__get_CONTROL() == MODE_IRQ) return -1; // Not allowed in ISR + return __svcSemaphoreWait(semaphore_id, millisec); +} + +/// Release a Semaphore +osStatus osSemaphoreRelease (osSemaphoreId semaphore_id) { + if (__get_CONTROL() == MODE_IRQ) { // in ISR + return isrSemaphoreRelease(semaphore_id); + } else { // in Thread + return __svcSemaphoreRelease(semaphore_id); + } +} + +/// Delete a Semaphore that was created by osSemaphoreCreate +osStatus osSemaphoreDelete (osSemaphoreId semaphore_id) { + if (__get_CONTROL() == MODE_IRQ) return osErrorISR; // Not allowed in ISR + return __svcSemaphoreDelete(semaphore_id); +} + + +// ==== Memory Management Functions ==== + +// Memory Management Helper Functions + +// Clear Memory Box (Zero init) +static void rt_clr_box (void *box_mem, void *box) { + uint32_t *p, n; + + if (box) { + p = box; + for (n = ((P_BM)box_mem)->blk_size; n; n -= 4) { + *p++ = 0; + } + } +} + +// Memory Management Service Calls declarations +SVC_1_1(svcPoolCreate, osPoolId, const osPoolDef_t *, RET_pointer) +SVC_2_1(sysPoolAlloc, void *, osPoolId, uint32_t, RET_pointer) +SVC_2_1(sysPoolFree, osStatus, osPoolId, void *, RET_osStatus) + +// Memory Management Service & ISR Calls + +/// Create and Initialize memory pool +osPoolId svcPoolCreate (const osPoolDef_t *pool_def) { + uint32_t blk_sz; + + if ((pool_def == NULL) || + (pool_def->pool_sz == 0) || + (pool_def->item_sz == 0) || + (pool_def->pool == NULL)) { + sysThreadError(osErrorParameter); + return NULL; + } + + blk_sz = (pool_def->item_sz + 3) & ~3; + + _init_box(pool_def->pool, sizeof(struct OS_BM) + pool_def->pool_sz * blk_sz, blk_sz); + + return pool_def->pool; +} + +/// Allocate a memory block from a memory pool +void *sysPoolAlloc (osPoolId pool_id, uint32_t clr) { + void *ptr; + + if (pool_id == NULL) return NULL; + + ptr = rt_alloc_box(pool_id); + if (clr) { + rt_clr_box(pool_id, ptr); + } + + return ptr; +} + +/// Return an allocated memory block back to a specific memory pool +osStatus sysPoolFree (osPoolId pool_id, void *block) { + int32_t res; + + if (pool_id == NULL) return osErrorParameter; + + res = rt_free_box(pool_id, block); + if (res != 0) return osErrorValue; + + return osOK; +} + + +// Memory Management Public API + +/// Create and Initialize memory pool +osPoolId osPoolCreate (osPoolDef_t *pool_def) { + if (__get_CONTROL() == MODE_IRQ) return NULL; // Not allowed in ISR + if ((__get_CONTROL() == MODE_SUPERVISOR) && (os_running == 0)) { + // Privileged and not running + return svcPoolCreate(pool_def); + } else { + return __svcPoolCreate(pool_def); + } +} + +/// Allocate a memory block from a memory pool +void *osPoolAlloc (osPoolId pool_id) { + if ((__get_CONTROL() == MODE_IRQ) || (__get_CONTROL() == MODE_SUPERVISOR)) { // in ISR or Privileged + return sysPoolAlloc(pool_id, 0); + } else { // in Thread + return __sysPoolAlloc(pool_id, 0); + } +} + +/// Allocate a memory block from a memory pool and set memory block to zero +void *osPoolCAlloc (osPoolId pool_id) { + if ((__get_CONTROL() == MODE_IRQ) || (__get_CONTROL() == MODE_SUPERVISOR)) { // in ISR or Privileged + return sysPoolAlloc(pool_id, 1); + } else { // in Thread + return __sysPoolAlloc(pool_id, 1); + } +} + +/// Return an allocated memory block back to a specific memory pool +osStatus osPoolFree (osPoolId pool_id, void *block) { + if ((__get_CONTROL() == MODE_IRQ) || (__get_CONTROL() == MODE_SUPERVISOR)) { // in ISR or Privileged + return sysPoolFree(pool_id, block); + } else { // in Thread + return __sysPoolFree(pool_id, block); + } +} + + +// ==== Message Queue Management Functions ==== + +// Message Queue Management Service Calls declarations +SVC_2_1(svcMessageCreate, osMessageQId, osMessageQDef_t *, osThreadId, RET_pointer) +SVC_3_1(svcMessagePut, osStatus, osMessageQId, uint32_t, uint32_t, RET_osStatus) +SVC_2_3(svcMessageGet, os_InRegs osEvent, osMessageQId, uint32_t, RET_osEvent) + +// Message Queue Service Calls + +/// Create and Initialize Message Queue +osMessageQId svcMessageCreate (osMessageQDef_t *queue_def, osThreadId thread_id) { + + if ((queue_def == NULL) || + (queue_def->queue_sz == 0) || + (queue_def->pool == NULL)) { + sysThreadError(osErrorParameter); + return NULL; + } + + if (((P_MCB)queue_def->pool)->cb_type != 0) { + sysThreadError(osErrorParameter); + return NULL; + } + + rt_mbx_init(queue_def->pool, 4*(queue_def->queue_sz + 4)); + + return queue_def->pool; +} + +/// Put a Message to a Queue +osStatus svcMessagePut (osMessageQId queue_id, uint32_t info, uint32_t millisec) { + OS_RESULT res; + + if (queue_id == NULL) return osErrorParameter; + + if (((P_MCB)queue_id)->cb_type != MCB) return osErrorParameter; + + res = rt_mbx_send(queue_id, (void *)info, rt_ms2tick(millisec)); + + if (res == OS_R_TMO) { + return (millisec ? osErrorTimeoutResource : osErrorResource); + } + + return osOK; +} + +/// Get a Message or Wait for a Message from a Queue +os_InRegs osEvent_type svcMessageGet (osMessageQId queue_id, uint32_t millisec) { + OS_RESULT res; + osEvent ret; + + if (queue_id == NULL) { + ret.status = osErrorParameter; + return osEvent_ret_status; + } + + if (((P_MCB)queue_id)->cb_type != MCB) { + ret.status = osErrorParameter; + return osEvent_ret_status; + } + + res = rt_mbx_wait(queue_id, &ret.value.p, rt_ms2tick(millisec)); + + if (res == OS_R_TMO) { + ret.status = millisec ? osEventTimeout : osOK; + return osEvent_ret_value; + } + + ret.status = osEventMessage; + + return osEvent_ret_value; +} + + +// Message Queue ISR Calls + +/// Put a Message to a Queue +static __INLINE osStatus isrMessagePut (osMessageQId queue_id, uint32_t info, uint32_t millisec) { + + if ((queue_id == NULL) || (millisec != 0)) { + return osErrorParameter; + } + + if (((P_MCB)queue_id)->cb_type != MCB) return osErrorParameter; + + if (rt_mbx_check(queue_id) == 0) { // Check if Queue is full + return osErrorResource; + } + + isr_mbx_send(queue_id, (void *)info); + + return osOK; +} + +/// Get a Message or Wait for a Message from a Queue +static __INLINE os_InRegs osEvent isrMessageGet (osMessageQId queue_id, uint32_t millisec) { + OS_RESULT res; + osEvent ret; + + if ((queue_id == NULL) || (millisec != 0)) { + ret.status = osErrorParameter; + return ret; + } + + if (((P_MCB)queue_id)->cb_type != MCB) { + ret.status = osErrorParameter; + return ret; + } + + res = isr_mbx_receive(queue_id, &ret.value.p); + + if (res != OS_R_MBX) { + ret.status = osOK; + return ret; + } + + ret.status = osEventMessage; + + return ret; +} + + +// Message Queue Management Public API + +/// Create and Initialize Message Queue +osMessageQId osMessageCreate (osMessageQDef_t *queue_def, osThreadId thread_id) { + if (__get_CONTROL() == MODE_IRQ) return NULL; // Not allowed in ISR + if ((__get_CONTROL() == MODE_SUPERVISOR) && (os_running == 0)) { + // Privileged and not running + return svcMessageCreate(queue_def, thread_id); + } else { + return __svcMessageCreate(queue_def, thread_id); + } +} + +/// Put a Message to a Queue +osStatus osMessagePut (osMessageQId queue_id, uint32_t info, uint32_t millisec) { + if (__get_CONTROL() == MODE_IRQ) { // in ISR + return isrMessagePut(queue_id, info, millisec); + } else { // in Thread + return __svcMessagePut(queue_id, info, millisec); + } +} + +/// Get a Message or Wait for a Message from a Queue +os_InRegs osEvent osMessageGet (osMessageQId queue_id, uint32_t millisec) { + if (__get_CONTROL() == MODE_IRQ) { // in ISR + return isrMessageGet(queue_id, millisec); + } else { // in Thread + return __svcMessageGet(queue_id, millisec); + } +} + + +// ==== Mail Queue Management Functions ==== + +// Mail Queue Management Service Calls declarations +SVC_2_1(svcMailCreate, osMailQId, osMailQDef_t *, osThreadId, RET_pointer) +SVC_4_1(sysMailAlloc, void *, osMailQId, uint32_t, uint32_t, uint32_t, RET_pointer) +SVC_3_1(sysMailFree, osStatus, osMailQId, void *, uint32_t, RET_osStatus) + +// Mail Queue Management Service & ISR Calls + +/// Create and Initialize mail queue +osMailQId svcMailCreate (osMailQDef_t *queue_def, osThreadId thread_id) { + uint32_t blk_sz; + P_MCB pmcb; + void *pool; + + if ((queue_def == NULL) || + (queue_def->queue_sz == 0) || + (queue_def->item_sz == 0) || + (queue_def->pool == NULL)) { + sysThreadError(osErrorParameter); + return NULL; + } + + pmcb = *(((void **)queue_def->pool) + 0); + pool = *(((void **)queue_def->pool) + 1); + + if ((pool == NULL) || (pmcb == NULL) || (pmcb->cb_type != 0)) { + sysThreadError(osErrorParameter); + return NULL; + } + + blk_sz = (queue_def->item_sz + 3) & ~3; + + _init_box(pool, sizeof(struct OS_BM) + queue_def->queue_sz * blk_sz, blk_sz); + + rt_mbx_init(pmcb, 4*(queue_def->queue_sz + 4)); + + + return queue_def->pool; +} + +/// Allocate a memory block from a mail +void *sysMailAlloc (osMailQId queue_id, uint32_t millisec, uint32_t isr, uint32_t clr) { + P_MCB pmcb; + void *pool; + void *mem; + + if (queue_id == NULL) return NULL; + + pmcb = *(((void **)queue_id) + 0); + pool = *(((void **)queue_id) + 1); + + if ((pool == NULL) || (pmcb == NULL)) return NULL; + + if (isr && (millisec != 0)) return NULL; + + mem = rt_alloc_box(pool); + if (clr) { + rt_clr_box(pool, mem); + } + + if ((mem == NULL) && (millisec != 0)) { + // Put Task to sleep when Memory not available + if (pmcb->p_lnk != NULL) { + rt_put_prio((P_XCB)pmcb, os_tsk.run); + } else { + pmcb->p_lnk = os_tsk.run; + os_tsk.run->p_lnk = NULL; + os_tsk.run->p_rlnk = (P_TCB)pmcb; + // Task is waiting to allocate a message + pmcb->state = 3; + } + rt_block(rt_ms2tick(millisec), WAIT_MBX); + } + + return mem; +} + +/// Free a memory block from a mail +osStatus sysMailFree (osMailQId queue_id, void *mail, uint32_t isr) { + P_MCB pmcb; + P_TCB ptcb; + void *pool; + void *mem; + int32_t res; + + if (queue_id == NULL) return osErrorParameter; + + pmcb = *(((void **)queue_id) + 0); + pool = *(((void **)queue_id) + 1); + + if ((pmcb == NULL) || (pool == NULL)) return osErrorParameter; + + res = rt_free_box(pool, mail); + + if (res != 0) return osErrorValue; + + if (pmcb->state == 3) { + // Task is waiting to allocate a message + if (isr) { + rt_psq_enq (pmcb, (U32)pool); + rt_psh_req (); + } else { + mem = rt_alloc_box(pool); + if (mem != NULL) { + ptcb = rt_get_first((P_XCB)pmcb); + if (pmcb->p_lnk == NULL) { + pmcb->state = 0; + } + rt_ret_val(ptcb, (U32)mem); + rt_rmv_dly(ptcb); + rt_dispatch(ptcb); + } + } + } + + return osOK; +} + + +// Mail Queue Management Public API + +/// Create and Initialize mail queue +osMailQId osMailCreate (osMailQDef_t *queue_def, osThreadId thread_id) { + if (__get_CONTROL() == MODE_IRQ) return NULL; // Not allowed in ISR + if ((__get_CONTROL() == MODE_SUPERVISOR) && (os_running == 0)) { + // Privileged and not running + return svcMailCreate(queue_def, thread_id); + } else { + return __svcMailCreate(queue_def, thread_id); + } +} + +/// Allocate a memory block from a mail +void *osMailAlloc (osMailQId queue_id, uint32_t millisec) { + if (__get_CONTROL() == MODE_IRQ) { // in ISR + return sysMailAlloc(queue_id, millisec, 1, 0); + } else { // in Thread + return __sysMailAlloc(queue_id, millisec, 0, 0); + } +} + +/// Allocate a memory block from a mail and set memory block to zero +void *osMailCAlloc (osMailQId queue_id, uint32_t millisec) { + if (__get_CONTROL() == MODE_IRQ) { // in ISR + return sysMailAlloc(queue_id, millisec, 1, 1); + } else { // in Thread + return __sysMailAlloc(queue_id, millisec, 0, 1); + } +} + +/// Free a memory block from a mail +osStatus osMailFree (osMailQId queue_id, void *mail) { + if (__get_CONTROL() == MODE_IRQ) { // in ISR + return sysMailFree(queue_id, mail, 1); + } else { // in Thread + return __sysMailFree(queue_id, mail, 0); + } +} + +/// Put a mail to a queue +osStatus osMailPut (osMailQId queue_id, void *mail) { + if (queue_id == NULL) return osErrorParameter; + if (mail == NULL) return osErrorValue; + return osMessagePut(*((void **)queue_id), (uint32_t)mail, 0); +} + +/// Get a mail from a queue +os_InRegs osEvent osMailGet (osMailQId queue_id, uint32_t millisec) { + osEvent ret; + + if (queue_id == NULL) { + ret.status = osErrorParameter; + return ret; + } + + ret = osMessageGet(*((void **)queue_id), millisec); + if (ret.status == osEventMessage) ret.status = osEventMail; + + return ret; +} diff --git a/rtos/rtx/TARGET_ARM7/rt_Event.c b/rtos/rtx/TARGET_ARM7/rt_Event.c new file mode 100644 index 00000000000..871e4b0f8af --- /dev/null +++ b/rtos/rtx/TARGET_ARM7/rt_Event.c @@ -0,0 +1,190 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_EVENT.C + * Purpose: Implements waits and wake-ups for event flags + * Rev.: V4.60 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 ARM Germany GmbH + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Conf.h" +#include "rt_System.h" +#include "rt_Event.h" +#include "rt_List.h" +#include "rt_Task.h" +#include "rt_HAL_CM.h" + + +/*---------------------------------------------------------------------------- + * Functions + *---------------------------------------------------------------------------*/ + + +/*--------------------------- rt_evt_wait -----------------------------------*/ + +OS_RESULT rt_evt_wait (U16 wait_flags, U16 timeout, BOOL and_wait) { + /* Wait for one or more event flags with optional time-out. */ + /* "wait_flags" identifies the flags to wait for. */ + /* "timeout" is the time-out limit in system ticks (0xffff if no time-out) */ + /* "and_wait" specifies the AND-ing of "wait_flags" as condition to be met */ + /* to complete the wait. (OR-ing if set to 0). */ + U32 block_state; + + if (and_wait) { + /* Check for AND-connected events */ + if ((os_tsk.run->events & wait_flags) == wait_flags) { + os_tsk.run->events &= ~wait_flags; + return (OS_R_EVT); + } + block_state = WAIT_AND; + } + else { + /* Check for OR-connected events */ + if (os_tsk.run->events & wait_flags) { + os_tsk.run->waits = os_tsk.run->events & wait_flags; + os_tsk.run->events &= ~wait_flags; + return (OS_R_EVT); + } + block_state = WAIT_OR; + } + /* Task has to wait */ + os_tsk.run->waits = wait_flags; + rt_block (timeout, (U8)block_state); + return (OS_R_TMO); +} + + +/*--------------------------- rt_evt_set ------------------------------------*/ + +void rt_evt_set (U16 event_flags, OS_TID task_id) { + /* Set one or more event flags of a selectable task. */ + P_TCB p_tcb; + + p_tcb = os_active_TCB[task_id-1]; + if (p_tcb == NULL) { + return; + } + p_tcb->events |= event_flags; + event_flags = p_tcb->waits; + /* If the task is not waiting for an event, it should not be put */ + /* to ready state. */ + if (p_tcb->state == WAIT_AND) { + /* Check for AND-connected events */ + if ((p_tcb->events & event_flags) == event_flags) { + goto wkup; + } + } + if (p_tcb->state == WAIT_OR) { + /* Check for OR-connected events */ + if (p_tcb->events & event_flags) { + p_tcb->waits &= p_tcb->events; +wkup: p_tcb->events &= ~event_flags; + rt_rmv_dly (p_tcb); + p_tcb->state = READY; +#ifdef __CMSIS_RTOS + rt_ret_val2(p_tcb, 0x08/*osEventSignal*/, p_tcb->waits); +#else + rt_ret_val (p_tcb, OS_R_EVT); +#endif + rt_dispatch (p_tcb); + } + } +} + + +/*--------------------------- rt_evt_clr ------------------------------------*/ + +void rt_evt_clr (U16 clear_flags, OS_TID task_id) { + /* Clear one or more event flags (identified by "clear_flags") of a */ + /* selectable task (identified by "task"). */ + P_TCB task = os_active_TCB[task_id-1]; + + if (task == NULL) { + return; + } + task->events &= ~clear_flags; +} + + +/*--------------------------- isr_evt_set -----------------------------------*/ + +void isr_evt_set (U16 event_flags, OS_TID task_id) { + /* Same function as "os_evt_set", but to be called by ISRs. */ + P_TCB p_tcb = os_active_TCB[task_id-1]; + + if (p_tcb == NULL) { + return; + } + rt_psq_enq (p_tcb, event_flags); + rt_psh_req (); +} + + +/*--------------------------- rt_evt_get ------------------------------------*/ + +U16 rt_evt_get (void) { + /* Get events of a running task after waiting for OR connected events. */ + return (os_tsk.run->waits); +} + + +/*--------------------------- rt_evt_psh ------------------------------------*/ + +void rt_evt_psh (P_TCB p_CB, U16 set_flags) { + /* Check if task has to be waken up */ + U16 event_flags; + + p_CB->events |= set_flags; + event_flags = p_CB->waits; + if (p_CB->state == WAIT_AND) { + /* Check for AND-connected events */ + if ((p_CB->events & event_flags) == event_flags) { + goto rdy; + } + } + if (p_CB->state == WAIT_OR) { + /* Check for OR-connected events */ + if (p_CB->events & event_flags) { + p_CB->waits &= p_CB->events; +rdy: p_CB->events &= ~event_flags; + rt_rmv_dly (p_CB); + p_CB->state = READY; +#ifdef __CMSIS_RTOS + rt_ret_val2(p_CB, 0x08/*osEventSignal*/, p_CB->waits); +#else + rt_ret_val (p_CB, OS_R_EVT); +#endif + rt_put_prio (&os_rdy, p_CB); + } + } +} + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ diff --git a/rtos/rtx/TARGET_ARM7/rt_Event.h b/rtos/rtx/TARGET_ARM7/rt_Event.h new file mode 100644 index 00000000000..9118c4faac5 --- /dev/null +++ b/rtos/rtx/TARGET_ARM7/rt_Event.h @@ -0,0 +1,46 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_EVENT.H + * Purpose: Implements waits and wake-ups for event flags + * Rev.: V4.60 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 ARM Germany GmbH + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + +/* Functions */ +extern OS_RESULT rt_evt_wait (U16 wait_flags, U16 timeout, BOOL and_wait); +extern void rt_evt_set (U16 event_flags, OS_TID task_id); +extern void rt_evt_clr (U16 clear_flags, OS_TID task_id); +extern void isr_evt_set (U16 event_flags, OS_TID task_id); +extern U16 rt_evt_get (void); +extern void rt_evt_psh (P_TCB p_CB, U16 set_flags); + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ + diff --git a/rtos/rtx/TARGET_ARM7/rt_HAL_CM.h b/rtos/rtx/TARGET_ARM7/rt_HAL_CM.h new file mode 100644 index 00000000000..b6a1907eb5a --- /dev/null +++ b/rtos/rtx/TARGET_ARM7/rt_HAL_CM.h @@ -0,0 +1,216 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_HAL_CM.H + * Purpose: Hardware Abstraction Layer for Cortex-M definitions + * Rev.: V4.60 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 ARM Germany GmbH + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + +#include "cmsis.h" +/* Definitions */ +#define INITIAL_xPSR 0x10000000 +#define DEMCR_TRCENA 0x01000000 +#define ITM_ITMENA 0x00000001 +#define MAGIC_WORD 0xE25A2EA5 + +#define SYS_TICK_IRQn TIMER0_IRQn + +extern void rt_set_PSP (U32 stack); +extern U32 rt_get_PSP (void); +extern void os_set_env (void); +extern void SysTick_Handler (void); +extern void *_alloc_box (void *box_mem); +extern int _free_box (void *box_mem, void *box); + +extern void rt_init_stack (P_TCB p_TCB, FUNCP task_body); +extern void rt_ret_val (P_TCB p_TCB, U32 v0); +extern void rt_ret_val2 (P_TCB p_TCB, U32 v0, U32 v1); + +extern void dbg_init (void); +extern void dbg_task_notify (P_TCB p_tcb, BOOL create); +extern void dbg_task_switch (U32 task_id); + + +#if defined (__CC_ARM) /* ARM Compiler */ + +#if ((__TARGET_ARCH_7_M || __TARGET_ARCH_7E_M) && !NO_EXCLUSIVE_ACCESS) + #define __USE_EXCLUSIVE_ACCESS +#else + #undef __USE_EXCLUSIVE_ACCESS +#endif + +#elif defined (__GNUC__) /* GNU Compiler */ + +#undef __USE_EXCLUSIVE_ACCESS + +#if defined (__CORTEX_M0) || defined (__CORTEX_M0PLUS) +#define __TARGET_ARCH_6S_M 1 +#else +#define __TARGET_ARCH_6S_M 0 +#endif + +#if defined (__VFP_FP__) && !defined(__SOFTFP__) +#define __TARGET_FPU_VFP 1 +#else +#define __TARGET_FPU_VFP 0 +#endif + +#define __inline inline +#define __weak __attribute__((weak)) + + +#elif defined (__ICCARM__) /* IAR Compiler */ + +#undef __USE_EXCLUSIVE_ACCESS + +#if (__CORE__ == __ARM6M__) +#define __TARGET_ARCH_6S_M 1 +#else +#define __TARGET_ARCH_6S_M 0 +#endif + +#if defined __ARMVFP__ +#define __TARGET_FPU_VFP 1 +#else +#define __TARGET_FPU_VFP 0 +#endif + +#define __inline inline + +#endif + + +/* NVIC registers */ + +#define OS_PEND_IRQ() NVIC_PendIRQ(SYS_TICK_IRQn) +#define OS_PENDING NVIC_PendingIRQ(SYS_TICK_IRQn) +#define OS_UNPEND(fl) NVIC_UnpendIRQ(SYS_TICK_IRQn) +#define OS_PEND(fl,p) NVIC_PendIRQ(SYS_TICK_IRQn) +#define OS_LOCK() NVIC_DisableIRQ(SYS_TICK_IRQn) +#define OS_UNLOCK() NVIC_EnableIRQ(SYS_TICK_IRQn) + +#define OS_X_PENDING NVIC_PendingIRQ(SYS_TICK_IRQn) +#define OS_X_UNPEND(fl) NVIC_UnpendIRQ(SYS_TICK_IRQn) +#define OS_X_PEND(fl,p) NVIC_PendIRQ(SYS_TICK_IRQn) + +#define OS_X_INIT(n) NVIC_EnableIRQ(n) +#define OS_X_LOCK(n) NVIC_DisableIRQ(n) +#define OS_X_UNLOCK(n) NVIC_EnableIRQ(n) + +/* Variables */ +extern BIT dbg_msg; + +/* Functions */ +#ifdef __USE_EXCLUSIVE_ACCESS + #define rt_inc(p) while(__strex((__ldrex(p)+1),p)) + #define rt_dec(p) while(__strex((__ldrex(p)-1),p)) +#else + #define rt_inc(p) __disable_irq();(*p)++;__enable_irq(); + #define rt_dec(p) __disable_irq();(*p)--;__enable_irq(); +#endif + +__inline static U32 rt_inc_qi (U32 size, U8 *count, U8 *first) { + U32 cnt,c2; +#ifdef __USE_EXCLUSIVE_ACCESS + do { + if ((cnt = __ldrex(count)) == size) { + __clrex(); + return (cnt); } + } while (__strex(cnt+1, count)); + do { + c2 = (cnt = __ldrex(first)) + 1; + if (c2 == size) c2 = 0; + } while (__strex(c2, first)); +#else + __disable_irq(); + if ((cnt = *count) < size) { + *count = cnt+1; + c2 = (cnt = *first) + 1; + if (c2 == size) c2 = 0; + *first = c2; + } + __enable_irq (); +#endif + return (cnt); +} + +__inline static void rt_systick_init (void) { +#if SYS_TICK_IRQn == TIMER0_IRQn + #define SYS_TICK_TIMER LPC_TIM0 + LPC_SC->PCONP |= (1 << PCTIM0); + LPC_SC->PCLKSEL0 = (LPC_SC->PCLKSEL0 & (~(1<<3))) | (1<<2); //PCLK == CPUCLK +#elif SYS_TICK_IRQn == TIMER1_IRQn + #define SYS_TICK_TIMER LPC_TIM1 + LPC_SC->PCONP |= (1 << PCTIM1); + LPC_SC->PCLKSEL0 = (LPC_SC->PCLKSEL0 & (~(1<<5))) | (1<<4); //PCLK == CPUCLK +#elif SYS_TICK_IRQn == TIMER2_IRQn + #define SYS_TICK_TIMER LPC_TIM2 + LPC_SC->PCONP |= (1 << PCTIM2); + LPC_SC->PCLKSEL1 = (LPC_SC->PCLKSEL1 & (~(1<<13))) | (1<<12); //PCLK == CPUCLK +#else + #define SYS_TICK_TIMER LPC_TIM3 + LPC_SC->PCONP |= (1 << PCTIM3); + LPC_SC->PCLKSEL1 = (LPC_SC->PCLKSEL1 & (~(1<<15))) | (1<<14); //PCLK == CPUCLK +#endif + + // setup Timer to count forever + //interrupt_reg + SYS_TICK_TIMER->TCR = 2; // reset & disable timer 0 + SYS_TICK_TIMER->TC = os_trv; + SYS_TICK_TIMER->PR = 0; // set the prescale divider + //Reset of TC and Interrupt when MR3 MR2 matches TC + SYS_TICK_TIMER->MCR = (1 << 9) |(1 << 10); //TMCR_MR3_R_Msk | TMCR_MR3_I_Msk + SYS_TICK_TIMER->MR3 = os_trv; // match registers + SYS_TICK_TIMER->CCR = 0; // disable compare registers + SYS_TICK_TIMER->EMR = 0; // disable external match register + // initialize the interrupt vector + NVIC_SetVector(SYS_TICK_IRQn, (uint32_t)&SysTick_Handler); + SYS_TICK_TIMER->TCR = 1; // enable timer 0 +} + +__inline static void rt_svc_init (void) { +// TODO: add svcInit + +} + +#ifdef DBG_MSG +#define DBG_INIT() dbg_init() +#define DBG_TASK_NOTIFY(p_tcb,create) if (dbg_msg) dbg_task_notify(p_tcb,create) +#define DBG_TASK_SWITCH(task_id) if (dbg_msg && (os_tsk.new_tsk != os_tsk.run)) \ + dbg_task_switch(task_id) +#else +#define DBG_INIT() +#define DBG_TASK_NOTIFY(p_tcb,create) +#define DBG_TASK_SWITCH(task_id) +#endif + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ + diff --git a/rtos/rtx/TARGET_ARM7/rt_List.c b/rtos/rtx/TARGET_ARM7/rt_List.c new file mode 100644 index 00000000000..06b5a8928a8 --- /dev/null +++ b/rtos/rtx/TARGET_ARM7/rt_List.c @@ -0,0 +1,320 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_LIST.C + * Purpose: Functions for the management of different lists + * Rev.: V4.60 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 ARM Germany GmbH + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Conf.h" +#include "rt_System.h" +#include "rt_List.h" +#include "rt_Task.h" +#include "rt_Time.h" +#include "rt_HAL_CM.h" + +/*---------------------------------------------------------------------------- + * Global Variables + *---------------------------------------------------------------------------*/ + +/* List head of chained ready tasks */ +struct OS_XCB os_rdy; +/* List head of chained delay tasks */ +struct OS_XCB os_dly; + + +/*---------------------------------------------------------------------------- + * Functions + *---------------------------------------------------------------------------*/ + + +/*--------------------------- rt_put_prio -----------------------------------*/ + +void rt_put_prio (P_XCB p_CB, P_TCB p_task) { + /* Put task identified with "p_task" into list ordered by priority. */ + /* "p_CB" points to head of list; list has always an element at end with */ + /* a priority less than "p_task->prio". */ + P_TCB p_CB2; + U32 prio; + BOOL sem_mbx = __FALSE; + + if (p_CB->cb_type == SCB || p_CB->cb_type == MCB || p_CB->cb_type == MUCB) { + sem_mbx = __TRUE; + } + prio = p_task->prio; + p_CB2 = p_CB->p_lnk; + /* Search for an entry in the list */ + while (p_CB2 != NULL && prio <= p_CB2->prio) { + p_CB = (P_XCB)p_CB2; + p_CB2 = p_CB2->p_lnk; + } + /* Entry found, insert the task into the list */ + p_task->p_lnk = p_CB2; + p_CB->p_lnk = p_task; + if (sem_mbx) { + if (p_CB2 != NULL) { + p_CB2->p_rlnk = p_task; + } + p_task->p_rlnk = (P_TCB)p_CB; + } + else { + p_task->p_rlnk = NULL; + } +} + + +/*--------------------------- rt_get_first ----------------------------------*/ + +P_TCB rt_get_first (P_XCB p_CB) { + /* Get task at head of list: it is the task with highest priority. */ + /* "p_CB" points to head of list. */ + P_TCB p_first; + + p_first = p_CB->p_lnk; + p_CB->p_lnk = p_first->p_lnk; + if (p_CB->cb_type == SCB || p_CB->cb_type == MCB || p_CB->cb_type == MUCB) { + if (p_first->p_lnk != NULL) { + p_first->p_lnk->p_rlnk = (P_TCB)p_CB; + p_first->p_lnk = NULL; + } + p_first->p_rlnk = NULL; + } + else { + p_first->p_lnk = NULL; + } + return (p_first); +} + + +/*--------------------------- rt_put_rdy_first ------------------------------*/ + +void rt_put_rdy_first (P_TCB p_task) { + /* Put task identified with "p_task" at the head of the ready list. The */ + /* task must have at least a priority equal to highest priority in list. */ + p_task->p_lnk = os_rdy.p_lnk; + p_task->p_rlnk = NULL; + os_rdy.p_lnk = p_task; +} + + +/*--------------------------- rt_get_same_rdy_prio --------------------------*/ + +P_TCB rt_get_same_rdy_prio (void) { + /* Remove a task of same priority from ready list if any exists. Other- */ + /* wise return NULL. */ + P_TCB p_first; + + p_first = os_rdy.p_lnk; + if (p_first->prio == os_tsk.run->prio) { + os_rdy.p_lnk = os_rdy.p_lnk->p_lnk; + return (p_first); + } + return (NULL); +} + + +/*--------------------------- rt_resort_prio --------------------------------*/ + +void rt_resort_prio (P_TCB p_task) { + /* Re-sort ordered lists after the priority of 'p_task' has changed. */ + P_TCB p_CB; + + if (p_task->p_rlnk == NULL) { + if (p_task->state == READY) { + /* Task is chained into READY list. */ + p_CB = (P_TCB)&os_rdy; + goto res; + } + } + else { + p_CB = p_task->p_rlnk; + while (p_CB->cb_type == TCB) { + /* Find a header of this task chain list. */ + p_CB = p_CB->p_rlnk; + } +res:rt_rmv_list (p_task); + rt_put_prio ((P_XCB)p_CB, p_task); + } +} + + +/*--------------------------- rt_put_dly ------------------------------------*/ + +void rt_put_dly (P_TCB p_task, U16 delay) { + /* Put a task identified with "p_task" into chained delay wait list using */ + /* a delay value of "delay". */ + P_TCB p; + U32 delta,idelay = delay; + + p = (P_TCB)&os_dly; + if (p->p_dlnk == NULL) { + /* Delay list empty */ + delta = 0; + goto last; + } + delta = os_dly.delta_time; + while (delta < idelay) { + if (p->p_dlnk == NULL) { + /* End of list found */ +last: p_task->p_dlnk = NULL; + p->p_dlnk = p_task; + p_task->p_blnk = p; + p->delta_time = (U16)(idelay - delta); + p_task->delta_time = 0; + return; + } + p = p->p_dlnk; + delta += p->delta_time; + } + /* Right place found */ + p_task->p_dlnk = p->p_dlnk; + p->p_dlnk = p_task; + p_task->p_blnk = p; + if (p_task->p_dlnk != NULL) { + p_task->p_dlnk->p_blnk = p_task; + } + p_task->delta_time = (U16)(delta - idelay); + p->delta_time -= p_task->delta_time; +} + + +/*--------------------------- rt_dec_dly ------------------------------------*/ + +void rt_dec_dly (void) { + /* Decrement delta time of list head: remove tasks having a value of zero.*/ + P_TCB p_rdy; + + if (os_dly.p_dlnk == NULL) { + return; + } + os_dly.delta_time--; + while ((os_dly.delta_time == 0) && (os_dly.p_dlnk != NULL)) { + p_rdy = os_dly.p_dlnk; + if (p_rdy->p_rlnk != NULL) { + /* Task is really enqueued, remove task from semaphore/mailbox */ + /* timeout waiting list. */ + p_rdy->p_rlnk->p_lnk = p_rdy->p_lnk; + if (p_rdy->p_lnk != NULL) { + p_rdy->p_lnk->p_rlnk = p_rdy->p_rlnk; + p_rdy->p_lnk = NULL; + } + p_rdy->p_rlnk = NULL; + } + rt_put_prio (&os_rdy, p_rdy); + os_dly.delta_time = p_rdy->delta_time; + if (p_rdy->state == WAIT_ITV) { + /* Calculate the next time for interval wait. */ + p_rdy->delta_time = p_rdy->interval_time + (U16)os_time; + } + p_rdy->state = READY; + os_dly.p_dlnk = p_rdy->p_dlnk; + if (p_rdy->p_dlnk != NULL) { + p_rdy->p_dlnk->p_blnk = (P_TCB)&os_dly; + p_rdy->p_dlnk = NULL; + } + p_rdy->p_blnk = NULL; + } +} + + +/*--------------------------- rt_rmv_list -----------------------------------*/ + +void rt_rmv_list (P_TCB p_task) { + /* Remove task identified with "p_task" from ready, semaphore or mailbox */ + /* waiting list if enqueued. */ + P_TCB p_b; + + if (p_task->p_rlnk != NULL) { + /* A task is enqueued in semaphore / mailbox waiting list. */ + p_task->p_rlnk->p_lnk = p_task->p_lnk; + if (p_task->p_lnk != NULL) { + p_task->p_lnk->p_rlnk = p_task->p_rlnk; + } + return; + } + + p_b = (P_TCB)&os_rdy; + while (p_b != NULL) { + /* Search the ready list for task "p_task" */ + if (p_b->p_lnk == p_task) { + p_b->p_lnk = p_task->p_lnk; + return; + } + p_b = p_b->p_lnk; + } +} + + +/*--------------------------- rt_rmv_dly ------------------------------------*/ + +void rt_rmv_dly (P_TCB p_task) { + /* Remove task identified with "p_task" from delay list if enqueued. */ + P_TCB p_b; + + p_b = p_task->p_blnk; + if (p_b != NULL) { + /* Task is really enqueued */ + p_b->p_dlnk = p_task->p_dlnk; + if (p_task->p_dlnk != NULL) { + /* 'p_task' is in the middle of list */ + p_b->delta_time += p_task->delta_time; + p_task->p_dlnk->p_blnk = p_b; + p_task->p_dlnk = NULL; + } + else { + /* 'p_task' is at the end of list */ + p_b->delta_time = 0; + } + p_task->p_blnk = NULL; + } +} + + +/*--------------------------- rt_psq_enq ------------------------------------*/ + +void rt_psq_enq (OS_ID entry, U32 arg) { + /* Insert post service request "entry" into ps-queue. */ + U32 idx; + + idx = rt_inc_qi (os_psq->size, &os_psq->count, &os_psq->first); + if (idx < os_psq->size) { + os_psq->q[idx].id = entry; + os_psq->q[idx].arg = arg; + } + else { + os_error (OS_ERR_FIFO_OVF); + } +} + + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ + diff --git a/rtos/rtx/TARGET_ARM7/rt_List.h b/rtos/rtx/TARGET_ARM7/rt_List.h new file mode 100644 index 00000000000..385123b470d --- /dev/null +++ b/rtos/rtx/TARGET_ARM7/rt_List.h @@ -0,0 +1,67 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_LIST.H + * Purpose: Functions for the management of different lists + * Rev.: V4.60 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 ARM Germany GmbH + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + +/* Definitions */ + +/* Values for 'cb_type' */ +#define TCB 0 +#define MCB 1 +#define SCB 2 +#define MUCB 3 +#define HCB 4 + +/* Variables */ +extern struct OS_XCB os_rdy; +extern struct OS_XCB os_dly; + +/* Functions */ +extern void rt_put_prio (P_XCB p_CB, P_TCB p_task); +extern P_TCB rt_get_first (P_XCB p_CB); +extern void rt_put_rdy_first (P_TCB p_task); +extern P_TCB rt_get_same_rdy_prio (void); +extern void rt_resort_prio (P_TCB p_task); +extern void rt_put_dly (P_TCB p_task, U16 delay); +extern void rt_dec_dly (void); +extern void rt_rmv_list (P_TCB p_task); +extern void rt_rmv_dly (P_TCB p_task); +extern void rt_psq_enq (OS_ID entry, U32 arg); + +/* This is a fast macro generating in-line code */ +#define rt_rdy_prio(void) (os_rdy.p_lnk->prio) + + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ + diff --git a/rtos/rtx/TARGET_ARM7/rt_Mailbox.c b/rtos/rtx/TARGET_ARM7/rt_Mailbox.c new file mode 100644 index 00000000000..b351bd19511 --- /dev/null +++ b/rtos/rtx/TARGET_ARM7/rt_Mailbox.c @@ -0,0 +1,292 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_MAILBOX.C + * Purpose: Implements waits and wake-ups for mailbox messages + * Rev.: V4.60 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 ARM Germany GmbH + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Conf.h" +#include "rt_System.h" +#include "rt_List.h" +#include "rt_Mailbox.h" +#include "rt_MemBox.h" +#include "rt_Task.h" +#include "rt_HAL_CM.h" + + +/*---------------------------------------------------------------------------- + * Functions + *---------------------------------------------------------------------------*/ + + +/*--------------------------- rt_mbx_init -----------------------------------*/ + +void rt_mbx_init (OS_ID mailbox, U16 mbx_size) { + /* Initialize a mailbox */ + P_MCB p_MCB = mailbox; + + p_MCB->cb_type = MCB; + p_MCB->state = 0; + p_MCB->isr_st = 0; + p_MCB->p_lnk = NULL; + p_MCB->first = 0; + p_MCB->last = 0; + p_MCB->count = 0; + p_MCB->size = (mbx_size + sizeof(void *) - sizeof(struct OS_MCB)) / + (U32)sizeof (void *); +} + + +/*--------------------------- rt_mbx_send -----------------------------------*/ + +OS_RESULT rt_mbx_send (OS_ID mailbox, void *p_msg, U16 timeout) { + /* Send message to a mailbox */ + P_MCB p_MCB = mailbox; + P_TCB p_TCB; + + if ((p_MCB->p_lnk != NULL) && (p_MCB->state == 1)) { + /* A task is waiting for message */ + p_TCB = rt_get_first ((P_XCB)p_MCB); +#ifdef __CMSIS_RTOS + rt_ret_val2(p_TCB, 0x10/*osEventMessage*/, (U32)p_msg); +#else + *p_TCB->msg = p_msg; + rt_ret_val (p_TCB, OS_R_MBX); +#endif + rt_rmv_dly (p_TCB); + rt_dispatch (p_TCB); + } + else { + /* Store message in mailbox queue */ + if (p_MCB->count == p_MCB->size) { + /* No free message entry, wait for one. If message queue is full, */ + /* then no task is waiting for message. The 'p_MCB->p_lnk' list */ + /* pointer can now be reused for send message waits task list. */ + if (timeout == 0) { + return (OS_R_TMO); + } + if (p_MCB->p_lnk != NULL) { + rt_put_prio ((P_XCB)p_MCB, os_tsk.run); + } + else { + p_MCB->p_lnk = os_tsk.run; + os_tsk.run->p_lnk = NULL; + os_tsk.run->p_rlnk = (P_TCB)p_MCB; + /* Task is waiting to send a message */ + p_MCB->state = 2; + } + os_tsk.run->msg = p_msg; + rt_block (timeout, WAIT_MBX); + return (OS_R_TMO); + } + /* Yes, there is a free entry in a mailbox. */ + p_MCB->msg[p_MCB->first] = p_msg; + rt_inc (&p_MCB->count); + if (++p_MCB->first == p_MCB->size) { + p_MCB->first = 0; + } + } + return (OS_R_OK); +} + + +/*--------------------------- rt_mbx_wait -----------------------------------*/ + +OS_RESULT rt_mbx_wait (OS_ID mailbox, void **message, U16 timeout) { + /* Receive a message; possibly wait for it */ + P_MCB p_MCB = mailbox; + P_TCB p_TCB; + + /* If a message is available in the fifo buffer */ + /* remove it from the fifo buffer and return. */ + if (p_MCB->count) { + *message = p_MCB->msg[p_MCB->last]; + if (++p_MCB->last == p_MCB->size) { + p_MCB->last = 0; + } + if ((p_MCB->p_lnk != NULL) && (p_MCB->state == 2)) { + /* A task is waiting to send message */ + p_TCB = rt_get_first ((P_XCB)p_MCB); +#ifdef __CMSIS_RTOS + rt_ret_val(p_TCB, 0/*osOK*/); +#else + rt_ret_val(p_TCB, OS_R_OK); +#endif + p_MCB->msg[p_MCB->first] = p_TCB->msg; + if (++p_MCB->first == p_MCB->size) { + p_MCB->first = 0; + } + rt_rmv_dly (p_TCB); + rt_dispatch (p_TCB); + } + else { + rt_dec (&p_MCB->count); + } + return (OS_R_OK); + } + /* No message available: wait for one */ + if (timeout == 0) { + return (OS_R_TMO); + } + if (p_MCB->p_lnk != NULL) { + rt_put_prio ((P_XCB)p_MCB, os_tsk.run); + } + else { + p_MCB->p_lnk = os_tsk.run; + os_tsk.run->p_lnk = NULL; + os_tsk.run->p_rlnk = (P_TCB)p_MCB; + /* Task is waiting to receive a message */ + p_MCB->state = 1; + } + rt_block(timeout, WAIT_MBX); +#ifndef __CMSIS_RTOS + os_tsk.run->msg = message; +#endif + return (OS_R_TMO); +} + + +/*--------------------------- rt_mbx_check ----------------------------------*/ + +OS_RESULT rt_mbx_check (OS_ID mailbox) { + /* Check for free space in a mailbox. Returns the number of messages */ + /* that can be stored to a mailbox. It returns 0 when mailbox is full. */ + P_MCB p_MCB = mailbox; + + return (p_MCB->size - p_MCB->count); +} + + +/*--------------------------- isr_mbx_send ----------------------------------*/ + +void isr_mbx_send (OS_ID mailbox, void *p_msg) { + /* Same function as "os_mbx_send", but to be called by ISRs. */ + P_MCB p_MCB = mailbox; + + rt_psq_enq (p_MCB, (U32)p_msg); + rt_psh_req (); +} + + +/*--------------------------- isr_mbx_receive -------------------------------*/ + +OS_RESULT isr_mbx_receive (OS_ID mailbox, void **message) { + /* Receive a message in the interrupt function. The interrupt function */ + /* should not wait for a message since this would block the rtx os. */ + P_MCB p_MCB = mailbox; + + if (p_MCB->count) { + /* A message is available in the fifo buffer. */ + *message = p_MCB->msg[p_MCB->last]; + if (p_MCB->state == 2) { + /* A task is locked waiting to send message */ + rt_psq_enq (p_MCB, 0); + rt_psh_req (); + } + rt_dec (&p_MCB->count); + if (++p_MCB->last == p_MCB->size) { + p_MCB->last = 0; + } + return (OS_R_MBX); + } + return (OS_R_OK); +} + + +/*--------------------------- rt_mbx_psh ------------------------------------*/ + +void rt_mbx_psh (P_MCB p_CB, void *p_msg) { + /* Store the message to the mailbox queue or pass it to task directly. */ + P_TCB p_TCB; + void *mem; + + if (p_CB->p_lnk != NULL) switch (p_CB->state) { +#ifdef __CMSIS_RTOS + case 3: + /* Task is waiting to allocate memory, remove it from the waiting list */ + mem = rt_alloc_box(p_msg); + if (mem == NULL) break; + p_TCB = rt_get_first ((P_XCB)p_CB); + rt_ret_val(p_TCB, (U32)mem); + p_TCB->state = READY; + rt_rmv_dly (p_TCB); + rt_put_prio (&os_rdy, p_TCB); + break; +#endif + case 2: + /* Task is waiting to send a message, remove it from the waiting list */ + p_TCB = rt_get_first ((P_XCB)p_CB); +#ifdef __CMSIS_RTOS + rt_ret_val(p_TCB, 0/*osOK*/); +#else + rt_ret_val(p_TCB, OS_R_OK); +#endif + p_CB->msg[p_CB->first] = p_TCB->msg; + rt_inc (&p_CB->count); + if (++p_CB->first == p_CB->size) { + p_CB->first = 0; + } + p_TCB->state = READY; + rt_rmv_dly (p_TCB); + rt_put_prio (&os_rdy, p_TCB); + break; + case 1: + /* Task is waiting for a message, pass the message to the task directly */ + p_TCB = rt_get_first ((P_XCB)p_CB); +#ifdef __CMSIS_RTOS + rt_ret_val2(p_TCB, 0x10/*osEventMessage*/, (U32)p_msg); +#else + *p_TCB->msg = p_msg; + rt_ret_val (p_TCB, OS_R_MBX); +#endif + p_TCB->state = READY; + rt_rmv_dly (p_TCB); + rt_put_prio (&os_rdy, p_TCB); + break; + } else { + /* No task is waiting for a message, store it to the mailbox queue */ + if (p_CB->count < p_CB->size) { + p_CB->msg[p_CB->first] = p_msg; + rt_inc (&p_CB->count); + if (++p_CB->first == p_CB->size) { + p_CB->first = 0; + } + } + else { + os_error (OS_ERR_MBX_OVF); + } + } +} + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ + diff --git a/rtos/rtx/TARGET_ARM7/rt_Mailbox.h b/rtos/rtx/TARGET_ARM7/rt_Mailbox.h new file mode 100644 index 00000000000..4862f5e3c7a --- /dev/null +++ b/rtos/rtx/TARGET_ARM7/rt_Mailbox.h @@ -0,0 +1,48 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_MAILBOX.H + * Purpose: Implements waits and wake-ups for mailbox messages + * Rev.: V4.60 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 ARM Germany GmbH + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + +/* Functions */ +extern void rt_mbx_init (OS_ID mailbox, U16 mbx_size); +extern OS_RESULT rt_mbx_send (OS_ID mailbox, void *p_msg, U16 timeout); +extern OS_RESULT rt_mbx_wait (OS_ID mailbox, void **message, U16 timeout); +extern OS_RESULT rt_mbx_check (OS_ID mailbox); +extern void isr_mbx_send (OS_ID mailbox, void *p_msg); +extern OS_RESULT isr_mbx_receive (OS_ID mailbox, void **message); +extern void rt_mbx_psh (P_MCB p_CB, void *p_msg); + + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ + diff --git a/rtos/rtx/TARGET_ARM7/rt_MemBox.c b/rtos/rtx/TARGET_ARM7/rt_MemBox.c new file mode 100644 index 00000000000..9b5a00fb0a0 --- /dev/null +++ b/rtos/rtx/TARGET_ARM7/rt_MemBox.c @@ -0,0 +1,166 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_MEMBOX.C + * Purpose: Interface functions for fixed memory block management system + * Rev.: V4.60 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 ARM Germany GmbH + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Conf.h" +#include "rt_System.h" +#include "rt_MemBox.h" +#include "rt_HAL_CM.h" + +/*---------------------------------------------------------------------------- + * Global Functions + *---------------------------------------------------------------------------*/ + + +/*--------------------------- _init_box -------------------------------------*/ + +int _init_box (void *box_mem, U32 box_size, U32 blk_size) { + /* Initialize memory block system, returns 0 if OK, 1 if fails. */ + void *end; + void *blk; + void *next; + U32 sizeof_bm; + + /* Create memory structure. */ + if (blk_size & BOX_ALIGN_8) { + /* Memory blocks 8-byte aligned. */ + blk_size = ((blk_size & ~BOX_ALIGN_8) + 7) & ~7; + sizeof_bm = (sizeof (struct OS_BM) + 7) & ~7; + } + else { + /* Memory blocks 4-byte aligned. */ + blk_size = (blk_size + 3) & ~3; + sizeof_bm = sizeof (struct OS_BM); + } + if (blk_size == 0) { + return (1); + } + if ((blk_size + sizeof_bm) > box_size) { + return (1); + } + /* Create a Memory structure. */ + blk = ((U8 *) box_mem) + sizeof_bm; + ((P_BM) box_mem)->free = blk; + end = ((U8 *) box_mem) + box_size; + ((P_BM) box_mem)->end = end; + ((P_BM) box_mem)->blk_size = blk_size; + + /* Link all free blocks using offsets. */ + end = ((U8 *) end) - blk_size; + while (1) { + next = ((U8 *) blk) + blk_size; + if (next > end) break; + *((void **)blk) = next; + blk = next; + } + /* end marker */ + *((void **)blk) = 0; + return (0); +} + +/*--------------------------- rt_alloc_box ----------------------------------*/ + +void *rt_alloc_box (void *box_mem) { + /* Allocate a memory block and return start address. */ + void **free; +#ifndef __USE_EXCLUSIVE_ACCESS + int irq_dis; + + irq_dis = __disable_irq (); + free = ((P_BM) box_mem)->free; + if (free) { + ((P_BM) box_mem)->free = *free; + } + if (!irq_dis) __enable_irq (); +#else + do { + if ((free = (void **)__ldrex(&((P_BM) box_mem)->free)) == 0) { + __clrex(); + break; + } + } while (__strex((U32)*free, &((P_BM) box_mem)->free)); +#endif + return (free); +} + + +/*--------------------------- _calloc_box -----------------------------------*/ + +void *_calloc_box (void *box_mem) { + /* Allocate a 0-initialized memory block and return start address. */ + void *free; + U32 *p; + U32 i; + + free = _alloc_box (box_mem); + if (free) { + p = free; + for (i = ((P_BM) box_mem)->blk_size; i; i -= 4) { + *p = 0; + p++; + } + } + return (free); +} + + +/*--------------------------- rt_free_box -----------------------------------*/ + +int rt_free_box (void *box_mem, void *box) { + /* Free a memory block, returns 0 if OK, 1 if box does not belong to box_mem */ +#ifndef __USE_EXCLUSIVE_ACCESS + int irq_dis; +#endif + + if (box < box_mem || box >= ((P_BM) box_mem)->end) { + return (1); + } + +#ifndef __USE_EXCLUSIVE_ACCESS + irq_dis = __disable_irq (); + *((void **)box) = ((P_BM) box_mem)->free; + ((P_BM) box_mem)->free = box; + if (!irq_dis) __enable_irq (); +#else + do { + *((void **)box) = (void *)__ldrex(&((P_BM) box_mem)->free); + } while (__strex ((U32)box, &((P_BM) box_mem)->free)); +#endif + return (0); +} + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ + diff --git a/rtos/rtx/TARGET_ARM7/rt_MemBox.h b/rtos/rtx/TARGET_ARM7/rt_MemBox.h new file mode 100644 index 00000000000..d761c41aca5 --- /dev/null +++ b/rtos/rtx/TARGET_ARM7/rt_MemBox.h @@ -0,0 +1,46 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_MEMBOX.H + * Purpose: Interface functions for fixed memory block management system + * Rev.: V4.60 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 ARM Germany GmbH + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + +/* Functions */ +#define rt_init_box _init_box +#define rt_calloc_box _calloc_box +extern int _init_box (void *box_mem, U32 box_size, U32 blk_size); +extern void *rt_alloc_box (void *box_mem); +extern void * _calloc_box (void *box_mem); +extern int rt_free_box (void *box_mem, void *box); + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ + diff --git a/rtos/rtx/TARGET_ARM7/rt_Mutex.c b/rtos/rtx/TARGET_ARM7/rt_Mutex.c new file mode 100644 index 00000000000..87398adb1eb --- /dev/null +++ b/rtos/rtx/TARGET_ARM7/rt_Mutex.c @@ -0,0 +1,197 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_MUTEX.C + * Purpose: Implements mutex synchronization objects + * Rev.: V4.60 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 ARM Germany GmbH + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Conf.h" +#include "rt_List.h" +#include "rt_Task.h" +#include "rt_Mutex.h" +#include "rt_HAL_CM.h" + + +/*---------------------------------------------------------------------------- + * Functions + *---------------------------------------------------------------------------*/ + + +/*--------------------------- rt_mut_init -----------------------------------*/ + +void rt_mut_init (OS_ID mutex) { + /* Initialize a mutex object */ + P_MUCB p_MCB = mutex; + + p_MCB->cb_type = MUCB; + p_MCB->prio = 0; + p_MCB->level = 0; + p_MCB->p_lnk = NULL; + p_MCB->owner = NULL; +} + + +/*--------------------------- rt_mut_delete ---------------------------------*/ + +#ifdef __CMSIS_RTOS +OS_RESULT rt_mut_delete (OS_ID mutex) { + /* Delete a mutex object */ + P_MUCB p_MCB = mutex; + P_TCB p_TCB; + + /* Restore owner task's priority. */ + if (p_MCB->level != 0) { + p_MCB->owner->prio = p_MCB->prio; + if (p_MCB->owner != os_tsk.run) { + rt_resort_prio (p_MCB->owner); + } + } + + while (p_MCB->p_lnk != NULL) { + /* A task is waiting for mutex. */ + p_TCB = rt_get_first ((P_XCB)p_MCB); + rt_ret_val(p_TCB, 0/*osOK*/); + rt_rmv_dly(p_TCB); + p_TCB->state = READY; + rt_put_prio (&os_rdy, p_TCB); + } + + if (os_rdy.p_lnk && (os_rdy.p_lnk->prio > os_tsk.run->prio)) { + /* preempt running task */ + rt_put_prio (&os_rdy, os_tsk.run); + os_tsk.run->state = READY; + rt_dispatch (NULL); + } + + p_MCB->cb_type = 0; + + return (OS_R_OK); +} +#endif + + +/*--------------------------- rt_mut_release --------------------------------*/ + +OS_RESULT rt_mut_release (OS_ID mutex) { + /* Release a mutex object */ + P_MUCB p_MCB = mutex; + P_TCB p_TCB; + + if (p_MCB->level == 0 || p_MCB->owner != os_tsk.run) { + /* Unbalanced mutex release or task is not the owner */ + return (OS_R_NOK); + } + if (--p_MCB->level != 0) { + return (OS_R_OK); + } + /* Restore owner task's priority. */ + os_tsk.run->prio = p_MCB->prio; + if (p_MCB->p_lnk != NULL) { + /* A task is waiting for mutex. */ + p_TCB = rt_get_first ((P_XCB)p_MCB); +#ifdef __CMSIS_RTOS + rt_ret_val(p_TCB, 0/*osOK*/); +#else + rt_ret_val(p_TCB, OS_R_MUT); +#endif + rt_rmv_dly (p_TCB); + /* A waiting task becomes the owner of this mutex. */ + p_MCB->level = 1; + p_MCB->owner = p_TCB; + p_MCB->prio = p_TCB->prio; + /* Priority inversion, check which task continues. */ + if (os_tsk.run->prio >= rt_rdy_prio()) { + rt_dispatch (p_TCB); + } + else { + /* Ready task has higher priority than running task. */ + rt_put_prio (&os_rdy, os_tsk.run); + rt_put_prio (&os_rdy, p_TCB); + os_tsk.run->state = READY; + p_TCB->state = READY; + rt_dispatch (NULL); + } + } + else { + /* Check if own priority raised by priority inversion. */ + if (rt_rdy_prio() > os_tsk.run->prio) { + rt_put_prio (&os_rdy, os_tsk.run); + os_tsk.run->state = READY; + rt_dispatch (NULL); + } + } + return (OS_R_OK); +} + + +/*--------------------------- rt_mut_wait -----------------------------------*/ + +OS_RESULT rt_mut_wait (OS_ID mutex, U16 timeout) { + /* Wait for a mutex, continue when mutex is free. */ + P_MUCB p_MCB = mutex; + + if (p_MCB->level == 0) { + p_MCB->owner = os_tsk.run; + p_MCB->prio = os_tsk.run->prio; + goto inc; + } + if (p_MCB->owner == os_tsk.run) { + /* OK, running task is the owner of this mutex. */ +inc:p_MCB->level++; + return (OS_R_OK); + } + /* Mutex owned by another task, wait until released. */ + if (timeout == 0) { + return (OS_R_TMO); + } + /* Raise the owner task priority if lower than current priority. */ + /* This priority inversion is called priority inheritance. */ + if (p_MCB->prio < os_tsk.run->prio) { + p_MCB->owner->prio = os_tsk.run->prio; + rt_resort_prio (p_MCB->owner); + } + if (p_MCB->p_lnk != NULL) { + rt_put_prio ((P_XCB)p_MCB, os_tsk.run); + } + else { + p_MCB->p_lnk = os_tsk.run; + os_tsk.run->p_lnk = NULL; + os_tsk.run->p_rlnk = (P_TCB)p_MCB; + } + rt_block(timeout, WAIT_MUT); + return (OS_R_TMO); +} + + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ + diff --git a/rtos/rtx/TARGET_ARM7/rt_Mutex.h b/rtos/rtx/TARGET_ARM7/rt_Mutex.h new file mode 100644 index 00000000000..a2f8916edb5 --- /dev/null +++ b/rtos/rtx/TARGET_ARM7/rt_Mutex.h @@ -0,0 +1,44 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_MUTEX.H + * Purpose: Implements mutex synchronization objects + * Rev.: V4.60 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 ARM Germany GmbH + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + +/* Functions */ +extern void rt_mut_init (OS_ID mutex); +extern OS_RESULT rt_mut_delete (OS_ID mutex); +extern OS_RESULT rt_mut_release (OS_ID mutex); +extern OS_RESULT rt_mut_wait (OS_ID mutex, U16 timeout); + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ + diff --git a/rtos/rtx/TARGET_ARM7/rt_Robin.c b/rtos/rtx/TARGET_ARM7/rt_Robin.c new file mode 100644 index 00000000000..ed58ea06dcd --- /dev/null +++ b/rtos/rtx/TARGET_ARM7/rt_Robin.c @@ -0,0 +1,84 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_ROBIN.C + * Purpose: Round Robin Task switching + * Rev.: V4.60 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 ARM Germany GmbH + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Conf.h" +#include "rt_List.h" +#include "rt_Task.h" +#include "rt_Time.h" +#include "rt_Robin.h" +#include "rt_HAL_CM.h" + +/*---------------------------------------------------------------------------- + * Global Variables + *---------------------------------------------------------------------------*/ + +struct OS_ROBIN os_robin; + + +/*---------------------------------------------------------------------------- + * Global Functions + *---------------------------------------------------------------------------*/ + +/*--------------------------- rt_init_robin ---------------------------------*/ + +__weak void rt_init_robin (void) { + /* Initialize Round Robin variables. */ + os_robin.task = NULL; + os_robin.tout = (U16)os_rrobin; +} + +/*--------------------------- rt_chk_robin ----------------------------------*/ + +__weak void rt_chk_robin (void) { + /* Check if Round Robin timeout expired and switch to the next ready task.*/ + P_TCB p_new; + + if (os_robin.task != os_rdy.p_lnk) { + /* New task was suspended, reset Round Robin timeout. */ + os_robin.task = os_rdy.p_lnk; + os_robin.time = (U16)os_time + os_robin.tout - 1; + } + if (os_robin.time == (U16)os_time) { + /* Round Robin timeout has expired, swap Robin tasks. */ + os_robin.task = NULL; + p_new = rt_get_first (&os_rdy); + rt_put_prio ((P_XCB)&os_rdy, p_new); + } +} + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ + diff --git a/rtos/rtx/TARGET_ARM7/rt_Robin.h b/rtos/rtx/TARGET_ARM7/rt_Robin.h new file mode 100644 index 00000000000..9eebaf042d1 --- /dev/null +++ b/rtos/rtx/TARGET_ARM7/rt_Robin.h @@ -0,0 +1,45 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_ROBIN.H + * Purpose: Round Robin Task switching definitions + * Rev.: V4.60 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 ARM Germany GmbH + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + +/* Variables */ +extern struct OS_ROBIN os_robin; + +/* Functions */ +extern void rt_init_robin (void); +extern void rt_chk_robin (void); + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ + diff --git a/rtos/rtx/TARGET_ARM7/rt_Semaphore.c b/rtos/rtx/TARGET_ARM7/rt_Semaphore.c new file mode 100644 index 00000000000..5bf65258e92 --- /dev/null +++ b/rtos/rtx/TARGET_ARM7/rt_Semaphore.c @@ -0,0 +1,183 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_SEMAPHORE.C + * Purpose: Implements binary and counting semaphores + * Rev.: V4.60 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 ARM Germany GmbH + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Conf.h" +#include "rt_System.h" +#include "rt_List.h" +#include "rt_Task.h" +#include "rt_Semaphore.h" +#include "rt_HAL_CM.h" + + +/*---------------------------------------------------------------------------- + * Functions + *---------------------------------------------------------------------------*/ + + +/*--------------------------- rt_sem_init -----------------------------------*/ + +void rt_sem_init (OS_ID semaphore, U16 token_count) { + /* Initialize a semaphore */ + P_SCB p_SCB = semaphore; + + p_SCB->cb_type = SCB; + p_SCB->p_lnk = NULL; + p_SCB->tokens = token_count; +} + + +/*--------------------------- rt_sem_delete ---------------------------------*/ + +#ifdef __CMSIS_RTOS +OS_RESULT rt_sem_delete (OS_ID semaphore) { + /* Delete semaphore */ + P_SCB p_SCB = semaphore; + P_TCB p_TCB; + + while (p_SCB->p_lnk != NULL) { + /* A task is waiting for token */ + p_TCB = rt_get_first ((P_XCB)p_SCB); + rt_ret_val(p_TCB, 0); + rt_rmv_dly(p_TCB); + p_TCB->state = READY; + rt_put_prio (&os_rdy, p_TCB); + } + + if (os_rdy.p_lnk && (os_rdy.p_lnk->prio > os_tsk.run->prio)) { + /* preempt running task */ + rt_put_prio (&os_rdy, os_tsk.run); + os_tsk.run->state = READY; + rt_dispatch (NULL); + } + + p_SCB->cb_type = 0; + + return (OS_R_OK); +} +#endif + + +/*--------------------------- rt_sem_send -----------------------------------*/ + +OS_RESULT rt_sem_send (OS_ID semaphore) { + /* Return a token to semaphore */ + P_SCB p_SCB = semaphore; + P_TCB p_TCB; + + if (p_SCB->p_lnk != NULL) { + /* A task is waiting for token */ + p_TCB = rt_get_first ((P_XCB)p_SCB); +#ifdef __CMSIS_RTOS + rt_ret_val(p_TCB, 1); +#else + rt_ret_val(p_TCB, OS_R_SEM); +#endif + rt_rmv_dly (p_TCB); + rt_dispatch (p_TCB); + } + else { + /* Store token. */ + p_SCB->tokens++; + } + return (OS_R_OK); +} + + +/*--------------------------- rt_sem_wait -----------------------------------*/ + +OS_RESULT rt_sem_wait (OS_ID semaphore, U16 timeout) { + /* Obtain a token; possibly wait for it */ + P_SCB p_SCB = semaphore; + + if (p_SCB->tokens) { + p_SCB->tokens--; + return (OS_R_OK); + } + /* No token available: wait for one */ + if (timeout == 0) { + return (OS_R_TMO); + } + if (p_SCB->p_lnk != NULL) { + rt_put_prio ((P_XCB)p_SCB, os_tsk.run); + } + else { + p_SCB->p_lnk = os_tsk.run; + os_tsk.run->p_lnk = NULL; + os_tsk.run->p_rlnk = (P_TCB)p_SCB; + } + rt_block(timeout, WAIT_SEM); + return (OS_R_TMO); +} + + +/*--------------------------- isr_sem_send ----------------------------------*/ + +void isr_sem_send (OS_ID semaphore) { + /* Same function as "os_sem"send", but to be called by ISRs */ + P_SCB p_SCB = semaphore; + + rt_psq_enq (p_SCB, 0); + rt_psh_req (); +} + + +/*--------------------------- rt_sem_psh ------------------------------------*/ + +void rt_sem_psh (P_SCB p_CB) { + /* Check if task has to be waken up */ + P_TCB p_TCB; + + if (p_CB->p_lnk != NULL) { + /* A task is waiting for token */ + p_TCB = rt_get_first ((P_XCB)p_CB); + rt_rmv_dly (p_TCB); + p_TCB->state = READY; +#ifdef __CMSIS_RTOS + rt_ret_val(p_TCB, 1); +#else + rt_ret_val(p_TCB, OS_R_SEM); +#endif + rt_put_prio (&os_rdy, p_TCB); + } + else { + /* Store token */ + p_CB->tokens++; + } +} + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ + diff --git a/rtos/rtx/TARGET_ARM7/rt_Semaphore.h b/rtos/rtx/TARGET_ARM7/rt_Semaphore.h new file mode 100644 index 00000000000..ed553a77017 --- /dev/null +++ b/rtos/rtx/TARGET_ARM7/rt_Semaphore.h @@ -0,0 +1,46 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_SEMAPHORE.H + * Purpose: Implements binary and counting semaphores + * Rev.: V4.60 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 ARM Germany GmbH + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + +/* Functions */ +extern void rt_sem_init (OS_ID semaphore, U16 token_count); +extern OS_RESULT rt_sem_delete(OS_ID semaphore); +extern OS_RESULT rt_sem_send (OS_ID semaphore); +extern OS_RESULT rt_sem_wait (OS_ID semaphore, U16 timeout); +extern void isr_sem_send (OS_ID semaphore); +extern void rt_sem_psh (P_SCB p_CB); + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ + diff --git a/rtos/rtx/TARGET_ARM7/rt_System.c b/rtos/rtx/TARGET_ARM7/rt_System.c new file mode 100644 index 00000000000..2482701b971 --- /dev/null +++ b/rtos/rtx/TARGET_ARM7/rt_System.c @@ -0,0 +1,293 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_SYSTEM.C + * Purpose: System Task Manager + * Rev.: V4.60 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 ARM Germany GmbH + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Conf.h" +#include "rt_Task.h" +#include "rt_System.h" +#include "rt_Event.h" +#include "rt_List.h" +#include "rt_Mailbox.h" +#include "rt_Semaphore.h" +#include "rt_Time.h" +#include "rt_Robin.h" +#include "rt_HAL_CM.h" + +/*---------------------------------------------------------------------------- + * Global Variables + *---------------------------------------------------------------------------*/ + +int os_tick_irqn; + +/*---------------------------------------------------------------------------- + * Local Variables + *---------------------------------------------------------------------------*/ + +static volatile BIT os_lock; +static volatile BIT os_psh_flag; +static U8 pend_flags; + +/*---------------------------------------------------------------------------- + * Global Functions + *---------------------------------------------------------------------------*/ + +#if defined (__CC_ARM) +__asm void $$RTX$$version (void) { + /* Export a version number symbol for a version control. */ + + EXPORT __RL_RTX_VER + +__RL_RTX_VER EQU 0x450 +} +#endif + + +/*--------------------------- rt_suspend ------------------------------------*/ +U32 rt_suspend (void) { + /* Suspend OS scheduler */ + U32 delta = 0xFFFF; + + rt_tsk_lock(); + + if (os_dly.p_dlnk) { + delta = os_dly.delta_time; + } +#ifndef __CMSIS_RTOS + if (os_tmr.next) { + if (os_tmr.tcnt < delta) delta = os_tmr.tcnt; + } +#endif + + return (delta); +} + + +/*--------------------------- rt_resume -------------------------------------*/ +void rt_resume (U32 sleep_time) { + /* Resume OS scheduler after suspend */ + P_TCB next; + U32 delta; + + os_tsk.run->state = READY; + rt_put_rdy_first (os_tsk.run); + + os_robin.task = NULL; + + /* Update delays. */ + if (os_dly.p_dlnk) { + delta = sleep_time; + if (delta >= os_dly.delta_time) { + delta -= os_dly.delta_time; + os_time += os_dly.delta_time; + os_dly.delta_time = 1; + while (os_dly.p_dlnk) { + rt_dec_dly(); + if (delta == 0) break; + delta--; + os_time++; + } + } else { + os_time += delta; + os_dly.delta_time -= delta; + } + } else { + os_time += sleep_time; + } + +#ifndef __CMSIS_RTOS + /* Check the user timers. */ + if (os_tmr.next) { + delta = sleep_time; + if (delta >= os_tmr.tcnt) { + delta -= os_tmr.tcnt; + os_tmr.tcnt = 1; + while (os_tmr.next) { + rt_tmr_tick(); + if (delta == 0) break; + delta--; + } + } else { + os_tmr.tcnt -= delta; + } + } +#endif + + /* Switch back to highest ready task */ + next = rt_get_first (&os_rdy); + rt_switch_req (next); + + rt_tsk_unlock(); +} + + +/*--------------------------- rt_tsk_lock -----------------------------------*/ + +void rt_tsk_lock (void) { + /* Prevent task switching by locking out scheduler */ + OS_X_LOCK(os_tick_irqn); + os_lock = __TRUE; + OS_X_UNPEND (&pend_flags); +} + + +/*--------------------------- rt_tsk_unlock ---------------------------------*/ + +void rt_tsk_unlock (void) { + /* Unlock scheduler and re-enable task switching */ + OS_X_UNLOCK(os_tick_irqn); + os_lock = __FALSE; + OS_X_PEND (pend_flags, os_psh_flag); + os_psh_flag = __FALSE; +} + + +/*--------------------------- rt_psh_req ------------------------------------*/ + +void rt_psh_req (void) { + /* Initiate a post service handling request if required. */ + if (os_lock == __FALSE) { + OS_PEND_IRQ (); + } + else { + os_psh_flag = __TRUE; + } +} + + +/*--------------------------- rt_pop_req ------------------------------------*/ + +void rt_pop_req (void) { + /* Process an ISR post service requests. */ + struct OS_XCB *p_CB; + P_TCB next; + U32 idx; + + os_tsk.run->state = READY; + rt_put_rdy_first (os_tsk.run); + + idx = os_psq->last; + while (os_psq->count) { + p_CB = os_psq->q[idx].id; + if (p_CB->cb_type == TCB) { + /* Is of TCB type */ + rt_evt_psh ((P_TCB)p_CB, (U16)os_psq->q[idx].arg); + } + else if (p_CB->cb_type == MCB) { + /* Is of MCB type */ + rt_mbx_psh ((P_MCB)p_CB, (void *)os_psq->q[idx].arg); + } + else { + /* Must be of SCB type */ + rt_sem_psh ((P_SCB)p_CB); + } + if (++idx == os_psq->size) idx = 0; + rt_dec (&os_psq->count); + } + os_psq->last = idx; + + next = rt_get_first (&os_rdy); + rt_switch_req (next); +} + + +/*--------------------------- os_tick_init ----------------------------------*/ + +__weak int os_tick_init (void) { + /* Initialize SysTick timer as system tick timer. */ + rt_systick_init (); + return (SYS_TICK_IRQn); /* Return IRQ number of SysTick timer */ +} + + +/*--------------------------- os_tick_irqack --------------------------------*/ + +__weak void os_tick_irqack (void) { + /* Acknowledge timer interrupt. */ +} + + +/*--------------------------- rt_systick ------------------------------------*/ + +extern void sysTimerTick(void); + +void rt_systick (void) { + if(NVIC_Pending(SYS_TICK_IRQn)){ + rt_pop_req(); + NVIC_UnpendIRQ(SYS_TICK_IRQn); + SYS_TICK_TIMER->IR = 0xF; // clear timer interrupt + return; + } + /* Check for system clock update, suspend running task. */ + P_TCB next; + + os_tsk.run->state = READY; + rt_put_rdy_first (os_tsk.run); + + /* Check Round Robin timeout. */ + rt_chk_robin (); + + /* Update delays. */ + os_time++; + rt_dec_dly (); + + /* Check the user timers. */ +#ifdef __CMSIS_RTOS + sysTimerTick(); +#else + rt_tmr_tick (); +#endif + + /* Switch back to highest ready task */ + next = rt_get_first (&os_rdy); + rt_switch_req (next); + SYS_TICK_TIMER->IR = 0xF; // clear timer interrupt +} + +/*--------------------------- rt_stk_check ----------------------------------*/ +__weak void rt_stk_check (void) { + /* Check for stack overflow. */ + if (os_tsk.run->task_id == 0x01) { + // TODO: For the main thread the check should be done against the main heap pointer + } else { + if ((os_tsk.run->tsk_stack < (U32)os_tsk.run->stack) || + (os_tsk.run->stack[0] != MAGIC_WORD)) { + os_error (OS_ERR_STK_OVF); + } + } +} + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ + diff --git a/rtos/rtx/TARGET_ARM7/rt_System.h b/rtos/rtx/TARGET_ARM7/rt_System.h new file mode 100644 index 00000000000..e73ef4d0b9c --- /dev/null +++ b/rtos/rtx/TARGET_ARM7/rt_System.h @@ -0,0 +1,52 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_SYSTEM.H + * Purpose: System Task Manager definitions + * Rev.: V4.60 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 ARM Germany GmbH + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + +/* Variables */ +#define os_psq ((P_PSQ)&os_fifo) +extern int os_tick_irqn; + +/* Functions */ +extern U32 rt_suspend (void); +extern void rt_resume (U32 sleep_time); +extern void rt_tsk_lock (void); +extern void rt_tsk_unlock (void); +extern void rt_psh_req (void); +extern void rt_pop_req (void); +extern void rt_systick (void); +extern void rt_stk_check (void); + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ + diff --git a/rtos/rtx/TARGET_ARM7/rt_Task.c b/rtos/rtx/TARGET_ARM7/rt_Task.c new file mode 100644 index 00000000000..d9e4d3ffad6 --- /dev/null +++ b/rtos/rtx/TARGET_ARM7/rt_Task.c @@ -0,0 +1,341 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_TASK.C + * Purpose: Task functions and system start up. + * Rev.: V4.60 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 ARM Germany GmbH + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Conf.h" +#include "rt_System.h" +#include "rt_Task.h" +#include "rt_List.h" +#include "rt_MemBox.h" +#include "rt_Robin.h" +#include "rt_HAL_CM.h" + +/*---------------------------------------------------------------------------- + * Global Variables + *---------------------------------------------------------------------------*/ + +/* Running and next task info. */ +struct OS_TSK os_tsk; + +/* Task Control Blocks of idle demon */ +struct OS_TCB os_idle_TCB; + + +/*---------------------------------------------------------------------------- + * Local Functions + *---------------------------------------------------------------------------*/ + +OS_TID rt_get_TID (void) { + U32 tid; + + for (tid = 1; tid <= os_maxtaskrun; tid++) { + if (os_active_TCB[tid-1] == NULL) { + return ((OS_TID)tid); + } + } + return (0); +} + +#if defined (__CC_ARM) && !defined (__MICROLIB) +/*--------------------------- __user_perthread_libspace ---------------------*/ +extern void *__libspace_start; + +void *__user_perthread_libspace (void) { + /* Provide a separate libspace for each task. */ + if (os_tsk.run == NULL) { + /* RTX not running yet. */ + return (&__libspace_start); + } + return (void *)(os_tsk.run->std_libspace); +} +#endif + +/*--------------------------- rt_init_context -------------------------------*/ + +void rt_init_context (P_TCB p_TCB, U8 priority, FUNCP task_body) { + /* Initialize general part of the Task Control Block. */ + p_TCB->cb_type = TCB; + p_TCB->state = READY; + p_TCB->prio = priority; + p_TCB->p_lnk = NULL; + p_TCB->p_rlnk = NULL; + p_TCB->p_dlnk = NULL; + p_TCB->p_blnk = NULL; + p_TCB->delta_time = 0; + p_TCB->interval_time = 0; + p_TCB->events = 0; + p_TCB->waits = 0; + p_TCB->stack_frame = 0; + + rt_init_stack (p_TCB, task_body); +} + + +/*--------------------------- rt_switch_req ---------------------------------*/ + +void rt_switch_req (P_TCB p_new) { + /* Switch to next task (identified by "p_new"). */ + os_tsk.new_tsk = p_new; + p_new->state = RUNNING; + DBG_TASK_SWITCH(p_new->task_id); +} + + +/*--------------------------- rt_dispatch -----------------------------------*/ + +void rt_dispatch (P_TCB next_TCB) { + /* Dispatch next task if any identified or dispatch highest ready task */ + /* "next_TCB" identifies a task to run or has value NULL (=no next task) */ + if (next_TCB == NULL) { + /* Running task was blocked: continue with highest ready task */ + next_TCB = rt_get_first (&os_rdy); + rt_switch_req (next_TCB); + } + else { + /* Check which task continues */ + if (next_TCB->prio > os_tsk.run->prio) { + /* preempt running task */ + rt_put_rdy_first (os_tsk.run); + os_tsk.run->state = READY; + rt_switch_req (next_TCB); + } + else { + /* put next task into ready list, no task switch takes place */ + next_TCB->state = READY; + rt_put_prio (&os_rdy, next_TCB); + } + } +} + + +/*--------------------------- rt_block --------------------------------------*/ + +void rt_block (U16 timeout, U8 block_state) { + /* Block running task and choose next ready task. */ + /* "timeout" sets a time-out value or is 0xffff (=no time-out). */ + /* "block_state" defines the appropriate task state */ + P_TCB next_TCB; + + if (timeout) { + if (timeout < 0xffff) { + rt_put_dly (os_tsk.run, timeout); + } + os_tsk.run->state = block_state; + next_TCB = rt_get_first (&os_rdy); + rt_switch_req (next_TCB); + } +} + + +/*--------------------------- rt_tsk_pass -----------------------------------*/ + +void rt_tsk_pass (void) { + /* Allow tasks of same priority level to run cooperatively.*/ + P_TCB p_new; + + p_new = rt_get_same_rdy_prio(); + if (p_new != NULL) { + rt_put_prio ((P_XCB)&os_rdy, os_tsk.run); + os_tsk.run->state = READY; + rt_switch_req (p_new); + } +} + + +/*--------------------------- rt_tsk_self -----------------------------------*/ + +OS_TID rt_tsk_self (void) { + /* Return own task identifier value. */ + if (os_tsk.run == NULL) { + return (0); + } + return (os_tsk.run->task_id); +} + + +/*--------------------------- rt_tsk_prio -----------------------------------*/ + +OS_RESULT rt_tsk_prio (OS_TID task_id, U8 new_prio) { + /* Change execution priority of a task to "new_prio". */ + P_TCB p_task; + + if (task_id == 0) { + /* Change execution priority of calling task. */ + os_tsk.run->prio = new_prio; +run:if (rt_rdy_prio() > new_prio) { + rt_put_prio (&os_rdy, os_tsk.run); + os_tsk.run->state = READY; + rt_dispatch (NULL); + } + return (OS_R_OK); + } + + /* Find the task in the "os_active_TCB" array. */ + if (task_id > os_maxtaskrun || os_active_TCB[task_id-1] == NULL) { + /* Task with "task_id" not found or not started. */ + return (OS_R_NOK); + } + p_task = os_active_TCB[task_id-1]; + p_task->prio = new_prio; + if (p_task == os_tsk.run) { + goto run; + } + rt_resort_prio (p_task); + if (p_task->state == READY) { + /* Task enqueued in a ready list. */ + p_task = rt_get_first (&os_rdy); + rt_dispatch (p_task); + } + return (OS_R_OK); +} + +/*--------------------------- rt_tsk_delete ---------------------------------*/ + +OS_RESULT rt_tsk_delete (OS_TID task_id) { + /* Terminate the task identified with "task_id". */ + P_TCB task_context; + + if (task_id == 0 || task_id == os_tsk.run->task_id) { + /* Terminate itself. */ + os_tsk.run->state = INACTIVE; + os_tsk.run->tsk_stack = 0; + rt_stk_check (); + os_active_TCB[os_tsk.run->task_id-1] = NULL; + + os_tsk.run->stack = NULL; + DBG_TASK_NOTIFY(os_tsk.run, __FALSE); + os_tsk.run = NULL; + rt_dispatch (NULL); + /* The program should never come to this point. */ + } + else { + /* Find the task in the "os_active_TCB" array. */ + if (task_id > os_maxtaskrun || os_active_TCB[task_id-1] == NULL) { + /* Task with "task_id" not found or not started. */ + return (OS_R_NOK); + } + task_context = os_active_TCB[task_id-1]; + rt_rmv_list (task_context); + rt_rmv_dly (task_context); + os_active_TCB[task_id-1] = NULL; + + task_context->stack = NULL; + DBG_TASK_NOTIFY(task_context, __FALSE); + } + return (OS_R_OK); +} + + +/*--------------------------- rt_sys_init -----------------------------------*/ + +#ifdef __CMSIS_RTOS +void rt_sys_init (void) { +#else +void rt_sys_init (FUNCP first_task, U32 prio_stksz, void *stk) { +#endif + /* Initialize system and start up task declared with "first_task". */ + U32 i; + + DBG_INIT(); + + /* Initialize dynamic memory and task TCB pointers to NULL. */ + for (i = 0; i < os_maxtaskrun; i++) { + os_active_TCB[i] = NULL; + } + + /* Set up TCB of idle demon */ + os_idle_TCB.task_id = 255; + os_idle_TCB.priv_stack = idle_task_stack_size; + os_idle_TCB.stack = idle_task_stack; + rt_init_context (&os_idle_TCB, 0, os_idle_demon); + + /* Set up ready list: initially empty */ + os_rdy.cb_type = HCB; + os_rdy.p_lnk = NULL; + /* Set up delay list: initially empty */ + os_dly.cb_type = HCB; + os_dly.p_dlnk = NULL; + os_dly.p_blnk = NULL; + os_dly.delta_time = 0; + + /* Fix SP and systemvariables to assume idle task is running */ + /* Transform main program into idle task by assuming idle TCB */ +#ifndef __CMSIS_RTOS + rt_set_PSP (os_idle_TCB.tsk_stack); +#endif + os_tsk.run = &os_idle_TCB; + os_tsk.run->state = RUNNING; + + /* Initialize ps queue */ + os_psq->first = 0; + os_psq->last = 0; + os_psq->size = os_fifo_size; + + rt_init_robin (); + + /* Intitialize SVC and PendSV */ + rt_svc_init (); + +#ifndef __CMSIS_RTOS + /* Intitialize and start system clock timer */ + os_tick_irqn = os_tick_init (); + if (os_tick_irqn >= 0) { + OS_X_INIT(os_tick_irqn); + } + + /* Start up first user task before entering the endless loop */ + rt_tsk_create (first_task, prio_stksz, stk, NULL); +#endif +} + + +/*--------------------------- rt_sys_start ----------------------------------*/ + +#ifdef __CMSIS_RTOS +void rt_sys_start (void) { + /* Start system */ + + /* Intitialize and start system clock timer */ + os_tick_irqn = os_tick_init (); + if (os_tick_irqn >= 0) { + OS_X_INIT(os_tick_irqn); + } + extern void RestoreContext(); + RestoreContext(); // Start the first task +} +#endif + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ diff --git a/rtos/rtx/TARGET_ARM7/rt_Task.h b/rtos/rtx/TARGET_ARM7/rt_Task.h new file mode 100644 index 00000000000..0e70c7844ab --- /dev/null +++ b/rtos/rtx/TARGET_ARM7/rt_Task.h @@ -0,0 +1,73 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_TASK.H + * Purpose: Task functions and system start up. + * Rev.: V4.60 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 ARM Germany GmbH + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + +/* Definitions */ +#define __CMSIS_RTOS 1 + +/* Values for 'state' */ +#define INACTIVE 0 +#define READY 1 +#define RUNNING 2 +#define WAIT_DLY 3 +#define WAIT_ITV 4 +#define WAIT_OR 5 +#define WAIT_AND 6 +#define WAIT_SEM 7 +#define WAIT_MBX 8 +#define WAIT_MUT 9 + +/* Return codes */ +#define OS_R_TMO 0x01 +#define OS_R_EVT 0x02 +#define OS_R_SEM 0x03 +#define OS_R_MBX 0x04 +#define OS_R_MUT 0x05 + +#define OS_R_OK 0x00 +#define OS_R_NOK 0xff + +/* Variables */ +extern struct OS_TSK os_tsk; +extern struct OS_TCB os_idle_TCB; + +/* Functions */ +extern void rt_switch_req (P_TCB p_new); +extern void rt_dispatch (P_TCB next_TCB); +extern void rt_block (U16 timeout, U8 block_state); +extern void rt_tsk_pass (void); +extern OS_TID rt_tsk_self (void); +extern OS_RESULT rt_tsk_prio (OS_TID task_id, U8 new_prio); +extern OS_RESULT rt_tsk_delete (OS_TID task_id); +extern void rt_sys_init (void); +extern void rt_sys_start (void); diff --git a/rtos/rtx/TARGET_ARM7/rt_Time.c b/rtos/rtx/TARGET_ARM7/rt_Time.c new file mode 100644 index 00000000000..075f2e51883 --- /dev/null +++ b/rtos/rtx/TARGET_ARM7/rt_Time.c @@ -0,0 +1,94 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_TIME.C + * Purpose: Delay and interval wait functions + * Rev.: V4.60 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 ARM Germany GmbH + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Conf.h" +#include "rt_Task.h" +#include "rt_Time.h" + +/*---------------------------------------------------------------------------- + * Global Variables + *---------------------------------------------------------------------------*/ + +/* Free running system tick counter */ +U32 os_time; + + +/*---------------------------------------------------------------------------- + * Functions + *---------------------------------------------------------------------------*/ + + +/*--------------------------- rt_time_get -----------------------------------*/ + +U32 rt_time_get (void) { + /* Get system time tick */ + return (os_time); +} + + +/*--------------------------- rt_dly_wait -----------------------------------*/ + +void rt_dly_wait (U16 delay_time) { + /* Delay task by "delay_time" */ + rt_block (delay_time, WAIT_DLY); +} + + +/*--------------------------- rt_itv_set ------------------------------------*/ + +void rt_itv_set (U16 interval_time) { + /* Set interval length and define start of first interval */ + os_tsk.run->interval_time = interval_time; + os_tsk.run->delta_time = interval_time + (U16)os_time; +} + + +/*--------------------------- rt_itv_wait -----------------------------------*/ + +void rt_itv_wait (void) { + /* Wait for interval end and define start of next one */ + U16 delta; + + delta = os_tsk.run->delta_time - (U16)os_time; + os_tsk.run->delta_time += os_tsk.run->interval_time; + if ((delta & 0x8000) == 0) { + rt_block (delta, WAIT_ITV); + } +} + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ + diff --git a/rtos/rtx/TARGET_ARM7/rt_Time.h b/rtos/rtx/TARGET_ARM7/rt_Time.h new file mode 100644 index 00000000000..addac58d245 --- /dev/null +++ b/rtos/rtx/TARGET_ARM7/rt_Time.h @@ -0,0 +1,47 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_TIME.H + * Purpose: Delay and interval wait functions definitions + * Rev.: V4.60 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 ARM Germany GmbH + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + +/* Variables */ +extern U32 os_time; + +/* Functions */ +extern U32 rt_time_get (void); +extern void rt_dly_wait (U16 delay_time); +extern void rt_itv_set (U16 interval_time); +extern void rt_itv_wait (void); + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ + diff --git a/rtos/rtx/TARGET_ARM7/rt_TypeDef.h b/rtos/rtx/TARGET_ARM7/rt_TypeDef.h new file mode 100644 index 00000000000..33ed7081639 --- /dev/null +++ b/rtos/rtx/TARGET_ARM7/rt_TypeDef.h @@ -0,0 +1,128 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_TYPEDEF.H + * Purpose: Type Definitions + * Rev.: V4.60 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 ARM Germany GmbH + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ +#ifndef RT_TYPE_DEF_H +#define RT_TYPE_DEF_H + +#include "os_tcb.h" + +typedef U32 OS_TID; +typedef void *OS_ID; +typedef U32 OS_RESULT; + +#define TCB_STACKF 32 /* 'stack_frame' offset */ +#define TCB_TSTACK 40 /* 'tsk_stack' offset */ + +typedef struct OS_PSFE { /* Post Service Fifo Entry */ + void *id; /* Object Identification */ + U32 arg; /* Object Argument */ +} *P_PSFE; + +typedef struct OS_PSQ { /* Post Service Queue */ + U8 first; /* FIFO Head Index */ + U8 last; /* FIFO Tail Index */ + U8 count; /* Number of stored items in FIFO */ + U8 size; /* FIFO Size */ + struct OS_PSFE q[1]; /* FIFO Content */ +} *P_PSQ; + +typedef struct OS_TSK { + P_TCB run; /* Current running task */ + P_TCB new_tsk; /* Scheduled task to run */ +} *P_TSK; + +typedef struct OS_ROBIN { /* Round Robin Control */ + P_TCB task; /* Round Robin task */ + U16 time; /* Round Robin switch time */ + U16 tout; /* Round Robin timeout */ +} *P_ROBIN; + +typedef struct OS_XCB { + U8 cb_type; /* Control Block Type */ + struct OS_TCB *p_lnk; /* Link pointer for ready/sem. wait list */ + struct OS_TCB *p_rlnk; /* Link pointer for sem./mbx lst backwards */ + struct OS_TCB *p_dlnk; /* Link pointer for delay list */ + struct OS_TCB *p_blnk; /* Link pointer for delay list backwards */ + U16 delta_time; /* Time until time out */ +} *P_XCB; + +typedef struct OS_MCB { + U8 cb_type; /* Control Block Type */ + U8 state; /* State flag variable */ + U8 isr_st; /* State flag variable for isr functions */ + struct OS_TCB *p_lnk; /* Chain of tasks waiting for message */ + U16 first; /* Index of the message list begin */ + U16 last; /* Index of the message list end */ + U16 count; /* Actual number of stored messages */ + U16 size; /* Maximum number of stored messages */ + void *msg[1]; /* FIFO for Message pointers 1st element */ +} *P_MCB; + +typedef struct OS_SCB { + U8 cb_type; /* Control Block Type */ + U8 mask; /* Semaphore token mask */ + U16 tokens; /* Semaphore tokens */ + struct OS_TCB *p_lnk; /* Chain of tasks waiting for tokens */ +} *P_SCB; + +typedef struct OS_MUCB { + U8 cb_type; /* Control Block Type */ + U8 prio; /* Owner task default priority */ + U16 level; /* Call nesting level */ + struct OS_TCB *p_lnk; /* Chain of tasks waiting for mutex */ + struct OS_TCB *owner; /* Mutex owner task */ +} *P_MUCB; + +typedef struct OS_XTMR { + struct OS_TMR *next; + U16 tcnt; +} *P_XTMR; + +typedef struct OS_TMR { + struct OS_TMR *next; /* Link pointer to Next timer */ + U16 tcnt; /* Timer delay count */ + U16 info; /* User defined call info */ +} *P_TMR; + +typedef struct OS_BM { + void *free; /* Pointer to first free memory block */ + void *end; /* Pointer to memory block end */ + U32 blk_size; /* Memory block size */ +} *P_BM; + +/* Definitions */ +#define __TRUE 1 +#define __FALSE 0 +#define NULL ((void *) 0) + +#endif diff --git a/rtos/rtx/TARGET_CORTEX_A/HAL_CA.c b/rtos/rtx/TARGET_CORTEX_A/HAL_CA.c new file mode 100644 index 00000000000..68852d439a4 --- /dev/null +++ b/rtos/rtx/TARGET_CORTEX_A/HAL_CA.c @@ -0,0 +1,138 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: HAL_CA.C + * Purpose: Hardware Abstraction Layer for Cortex-A + * Rev.: V4.77 plus changes for RTX-Ax + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2012 ARM Germany GmbH, 2012-2015 ARM Limited + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Config.h" +#include "rt_HAL_CA.h" + +/*--------------------------- os_init_context -------------------------------*/ + +void rt_init_stack (P_TCB p_TCB, FUNCP task_body) { + /* Prepare TCB and saved context for a first time start of a task. */ + U32 *stk,i,size; + + /* Prepare a complete interrupt frame for first task start */ + size = p_TCB->priv_stack >> 2; + if (size == 0U) { + size = (U16)os_stackinfo >> 2; + } + /* Write to the top of stack. */ + stk = &p_TCB->stack[size]; + + /* Auto correct to 8-byte ARM stack alignment. */ + if ((U32)stk & 0x04U) { + stk--; + } + + stk -= 16; + + /* Initial PC and default CPSR */ + stk[14] = (U32)task_body; + /* Task run mode is inherited from the startup file. */ + /* (non-privileged USER or privileged SYSTEM mode) */ + stk[15] = (os_flags & 1) ? INIT_CPSR_SYS : INIT_CPSR_USER; + /* Set T-bit if task function in Thumb mode. */ + if ((U32)task_body & 1) { + stk[15] |= CPSR_T_BIT; + } + /* Assign a void pointer to R0. */ + stk[8] = (U32)p_TCB->msg; + /* Clear R1-R12,LR registers. */ + for (i = 0U; i < 8U; i++) { + stk[i] = 0U; + } + for (i = 9U; i < 14U; i++) { + stk[i] = 0; + } + + /* Initial Task stack pointer. */ + p_TCB->tsk_stack = (U32)stk; + + /* Task entry point. */ + p_TCB->ptask = task_body; + + /* Initialize stack with magic pattern. */ + if (os_stackinfo & 0x10000000U) { + if (size > (16U+1U)) { + for (i = ((size - 16U)/2U) - 1U; i; i--) { + stk -= 2U; + stk[1] = MAGIC_PATTERN; + stk[0] = MAGIC_PATTERN; + } + if (--stk > p_TCB->stack) { + *stk = MAGIC_PATTERN; + } + } + } + + /* Set a magic word for checking of stack overflow. */ + p_TCB->stack[0] = MAGIC_WORD; +} + + +/*--------------------------- rt_ret_val ----------------------------------*/ + +static __inline U32 *rt_ret_regs (P_TCB p_TCB) { + /* Get pointer to task return value registers (R0..R3) in Stack */ + if (p_TCB->stack_frame & 0x4) { + /* NEON/D32 Stack Frame: D0-31,FPSCR,Reserved,R4-R11,R0-R3,R12,LR,PC,xPSR */ + return (U32 *)(p_TCB->tsk_stack + (8U*4U) + (2U*4U) + (32U*8U)); + } else if (p_TCB->stack_frame & 0x2) { + /* VFP/D16 Stack Frame: D0-D15/S0-31,FPSCR,Reserved,R4-R11,R0-R3,R12,LR,PC,xPSR */ + return (U32 *)(p_TCB->tsk_stack + (8U*4U) + (2U*4U) + (32U*4U)); + } else { + /* Basic Stack Frame: R4-R11,R0-R3,R12,LR,PC,xPSR */ + return (U32 *)(p_TCB->tsk_stack + (8U*4U)); + } +} + +void rt_ret_val (P_TCB p_TCB, U32 v0) { + U32 *ret; + + ret = rt_ret_regs(p_TCB); + ret[0] = v0; +} + +void rt_ret_val2(P_TCB p_TCB, U32 v0, U32 v1) { + U32 *ret; + + ret = rt_ret_regs(p_TCB); + ret[0] = v0; + ret[1] = v1; +} + + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ diff --git a/rtos/rtx/TARGET_CORTEX_A/RTX_CM_lib.h b/rtos/rtx/TARGET_CORTEX_A/RTX_CM_lib.h new file mode 100644 index 00000000000..ab4017dd111 --- /dev/null +++ b/rtos/rtx/TARGET_CORTEX_A/RTX_CM_lib.h @@ -0,0 +1,608 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: RTX_CM_LIB.H + * Purpose: RTX Kernel System Configuration + * Rev.: V4.79 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 ARM Germany GmbH + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + +#if defined (__CC_ARM) +#include +#pragma O3 +#define __USED __attribute__((used)) +#elif defined (__GNUC__) +#pragma GCC optimize ("O3") +#define __USED __attribute__((used)) +#elif defined (__ICCARM__) +#define __USED __root +#endif + + +/*---------------------------------------------------------------------------- + * Definitions + *---------------------------------------------------------------------------*/ + +#define _declare_box(pool,size,cnt) uint32_t pool[(((size)+3)/4)*(cnt) + 3] +#define _declare_box8(pool,size,cnt) uint64_t pool[(((size)+7)/8)*(cnt) + 2] + +#define OS_TCB_SIZE 64 +#define OS_TMR_SIZE 8 + +#if defined (__CC_ARM) && !defined (__MICROLIB) + +typedef void *OS_ID; +typedef uint32_t OS_TID; +typedef uint32_t OS_MUT[4]; +typedef uint32_t OS_RESULT; + +#define runtask_id() rt_tsk_self() +#define mutex_init(m) rt_mut_init(m) +#define mutex_wait(m) os_mut_wait(m,0xFFFFU) +#define mutex_rel(m) os_mut_release(m) + +extern uint8_t os_running; +extern OS_TID rt_tsk_self (void); +extern void rt_mut_init (OS_ID mutex); +extern OS_RESULT rt_mut_release (OS_ID mutex); +extern OS_RESULT rt_mut_wait (OS_ID mutex, uint16_t timeout); + +#define os_mut_wait(mutex,timeout) _os_mut_wait((uint32_t)rt_mut_wait,mutex,timeout) +#define os_mut_release(mutex) _os_mut_release((uint32_t)rt_mut_release,mutex) + +OS_RESULT _os_mut_release (uint32_t p, OS_ID mutex) __svc_indirect(0); +OS_RESULT _os_mut_wait (uint32_t p, OS_ID mutex, uint16_t timeout) __svc_indirect(0); + +#elif defined (__ICCARM__) + +typedef void *OS_ID; +typedef uint32_t OS_TID; +typedef uint32_t OS_MUT[4]; +typedef uint32_t OS_RESULT; + +#define runtask_id() rt_tsk_self() +#define mutex_init(m) rt_mut_init(m) +#define mutex_del(m) os_mut_delete(m) +#define mutex_wait(m) os_mut_wait(m,0xFFFF) +#define mutex_rel(m) os_mut_release(m) + +extern OS_TID rt_tsk_self (void); +extern void rt_mut_init (OS_ID mutex); +extern OS_RESULT rt_mut_delete (OS_ID mutex); +extern OS_RESULT rt_mut_release (OS_ID mutex); +extern OS_RESULT rt_mut_wait (OS_ID mutex, uint16_t timeout); + +#pragma swi_number=0 +__swi OS_RESULT _os_mut_delete (OS_ID mutex); + +static inline OS_RESULT os_mut_delete(OS_ID mutex) +{ + __asm("mov r12,%0\n" :: "r"(&rt_mut_delete) : "r12" ); + return _os_mut_delete(mutex); +} + +#pragma swi_number=0 +__swi OS_RESULT _os_mut_release (OS_ID mutex); + +static inline OS_RESULT os_mut_release(OS_ID mutex) +{ + __asm("mov r12,%0\n" :: "r"(&rt_mut_release) : "r12" ); + return _os_mut_release(mutex); +} + +#pragma swi_number=0 +__swi OS_RESULT _os_mut_wait (OS_ID mutex, uint16_t timeout); + +static inline OS_RESULT os_mut_wait(OS_ID mutex, uint16_t timeout) +{ + __asm("mov r12,%0\n" :: "r"(&rt_mut_wait) : "r12" ); + return _os_mut_wait(mutex, timeout); +} + +#include /* for include DLib_Thread.h */ + +void __iar_system_Mtxinit(__iar_Rmtx *); +void __iar_system_Mtxdst(__iar_Rmtx *); +void __iar_system_Mtxlock(__iar_Rmtx *); +void __iar_system_Mtxunlock(__iar_Rmtx *); + + + + +#endif + + +/*---------------------------------------------------------------------------- + * Global Variables + *---------------------------------------------------------------------------*/ + +#if (OS_TASKCNT == 0) +#error "Invalid number of concurrent running threads!" +#endif + +#if (OS_PRIVCNT >= OS_TASKCNT) +#error "Too many threads with user-provided stack size!" +#endif + +#if (OS_TIMERS != 0) +#define OS_TASK_CNT (OS_TASKCNT + 1) +#ifndef __MBED_CMSIS_RTOS_CA9 +#define OS_PRIV_CNT (OS_PRIVCNT + 2) +#define OS_STACK_SZ (4*(OS_PRIVSTKSIZE+OS_MAINSTKSIZE+OS_TIMERSTKSZ)) +#endif +#else +#define OS_TASK_CNT OS_TASKCNT +#ifndef __MBED_CMSIS_RTOS_CA9 +#define OS_PRIV_CNT (OS_PRIVCNT + 1) +#define OS_STACK_SZ (4*(OS_PRIVSTKSIZE+OS_MAINSTKSIZE)) +#endif +#endif + +#ifndef OS_STKINIT +#define OS_STKINIT 0 +#endif + +uint16_t const os_maxtaskrun = OS_TASK_CNT; +#ifdef __MBED_CMSIS_RTOS_CA9 +uint32_t const os_stackinfo = (OS_STKINIT<<28) | (OS_STKCHECK<<24) | (OS_IDLESTKSIZE*4); +#else +uint32_t const os_stackinfo = (OS_STKINIT<<28) | (OS_STKCHECK<<24) | (OS_PRIV_CNT<<16) | (OS_STKSIZE*4); +#endif +uint32_t const os_rrobin = (OS_ROBIN << 16) | OS_ROBINTOUT; +uint32_t const os_tickfreq = OS_CLOCK; +uint16_t const os_tickus_i = OS_CLOCK/1000000; +uint16_t const os_tickus_f = (((uint64_t)(OS_CLOCK-1000000*(OS_CLOCK/1000000)))<<16)/1000000; +uint32_t const os_trv = OS_TRV; +#if defined(FEATURE_UVISOR) && defined(TARGET_UVISOR_SUPPORTED) +uint8_t const os_flags = 0; +#else /* defined(FEATURE_UVISOR) && defined(TARGET_UVISOR_SUPPORTED) */ +uint8_t const os_flags = OS_RUNPRIV; +#endif /* defined(FEATURE_UVISOR) && defined(TARGET_UVISOR_SUPPORTED) */ + +/* Export following defines to uVision debugger. */ +__USED uint32_t const CMSIS_RTOS_API_Version = osCMSIS; +__USED uint32_t const CMSIS_RTOS_RTX_Version = osCMSIS_RTX; +__USED uint32_t const os_clockrate = OS_TICK; +__USED uint32_t const os_timernum = 0U; + +/* Memory pool for TCB allocation */ +_declare_box (mp_tcb, OS_TCB_SIZE, OS_TASK_CNT); +uint16_t const mp_tcb_size = sizeof(mp_tcb); + +#ifdef __MBED_CMSIS_RTOS_CA9 +/* Memory pool for os_idle_demon stack allocation. */ +_declare_box8 (mp_stk, OS_IDLESTKSIZE*4, 1); +uint32_t const mp_stk_size = sizeof(mp_stk); +#else +/* Memory pool for System stack allocation (+os_idle_demon). */ +_declare_box8 (mp_stk, OS_STKSIZE*4, OS_TASK_CNT-OS_PRIV_CNT+1); +uint32_t const mp_stk_size = sizeof(mp_stk); + +/* Memory pool for user specified stack allocation (+main, +timer) */ +uint64_t os_stack_mem[2+OS_PRIV_CNT+(OS_STACK_SZ/8)]; +uint32_t const os_stack_sz = sizeof(os_stack_mem); +#endif + +#ifndef OS_FIFOSZ + #define OS_FIFOSZ 16 +#endif + +/* Fifo Queue buffer for ISR requests.*/ +uint32_t os_fifo[OS_FIFOSZ*2+1]; +uint8_t const os_fifo_size = OS_FIFOSZ; + +/* An array of Active task pointers. */ +void *os_active_TCB[OS_TASK_CNT]; + +/* User Timers Resources */ +#if (OS_TIMERS != 0) +extern void osTimerThread (void const *argument); +#ifdef __MBED_CMSIS_RTOS_CA9 +osThreadDef(osTimerThread, (osPriority)(OS_TIMERPRIO-3), 4*OS_TIMERSTKSZ); +#else +osThreadDef(osTimerThread, (osPriority)(OS_TIMERPRIO-3), 1, 4*OS_TIMERSTKSZ); +#endif +osThreadId osThreadId_osTimerThread; +osMessageQDef(osTimerMessageQ, OS_TIMERCBQS, void *); +osMessageQId osMessageQId_osTimerMessageQ; +#else +osThreadDef_t os_thread_def_osTimerThread = { NULL }; +osThreadId osThreadId_osTimerThread; +osMessageQDef(osTimerMessageQ, 0U, void *); +osMessageQId osMessageQId_osTimerMessageQ; +#endif + +/* Legacy RTX User Timers not used */ +uint32_t os_tmr = 0U; +uint32_t const *m_tmr = NULL; +uint16_t const mp_tmr_size = 0U; + +/* singleton mutex */ +osMutexId singleton_mutex_id; +osMutexDef(singleton_mutex); + +#if defined (__CC_ARM) && !defined (__MICROLIB) + /* A memory space for arm standard library. */ + static uint32_t std_libspace[OS_TASK_CNT][96/4]; + static OS_MUT std_libmutex[OS_MUTEXCNT]; + static uint32_t nr_mutex; + extern void *__libspace_start; +#elif defined (__ICCARM__) +typedef struct os_mut_array { + OS_MUT mutex; + uint32_t used; +} os_mut_array_t; + +static os_mut_array_t std_libmutex[OS_MUTEXCNT];/* must be Zero clear */ +static uint32_t nr_mutex = 0; +#endif + + +/*---------------------------------------------------------------------------- + * RTX Optimizations (empty functions) + *---------------------------------------------------------------------------*/ + +#if OS_ROBIN == 0 + void rt_init_robin (void) {;} + void rt_chk_robin (void) {;} +#endif + +#if OS_STKCHECK == 0 + void rt_stk_check (void) {;} +#endif + + +/*---------------------------------------------------------------------------- + * Standard Library multithreading interface + *---------------------------------------------------------------------------*/ + +#if defined (__CC_ARM) && !defined (__MICROLIB) + +/*--------------------------- __user_perthread_libspace ---------------------*/ + +void *__user_perthread_libspace (void) { + /* Provide a separate libspace for each task. */ + uint32_t idx; + + idx = (os_running != 0U) ? runtask_id () : 0U; + if (idx == 0U) { + /* RTX not running yet. */ + return (&__libspace_start); + } + return ((void *)&std_libspace[idx-1]); +} + +/*--------------------------- _mutex_initialize -----------------------------*/ + +int _mutex_initialize (OS_ID *mutex) { + /* Allocate and initialize a system mutex. */ + + if (nr_mutex >= OS_MUTEXCNT) { + /* If you are here, you need to increase the number OS_MUTEXCNT. */ + for (;;); + } + *mutex = &std_libmutex[nr_mutex++]; + mutex_init (*mutex); + return (1); +} + + +/*--------------------------- _mutex_acquire --------------------------------*/ + +__attribute__((used)) void _mutex_acquire (OS_ID *mutex) { + /* Acquire a system mutex, lock stdlib resources. */ + if (os_running) { + /* RTX running, acquire a mutex. */ + mutex_wait (*mutex); + } +} + + +/*--------------------------- _mutex_release --------------------------------*/ + +__attribute__((used)) void _mutex_release (OS_ID *mutex) { + /* Release a system mutex, unlock stdlib resources. */ + if (os_running) { + /* RTX running, release a mutex. */ + mutex_rel (*mutex); + } +} + +#elif defined (__ICCARM__) + +/*--------------------------- __iar_system_Mtxinit --------------------------*/ + +void __iar_system_Mtxinit(__iar_Rmtx *mutex) +{ + /* Allocate and initialize a system mutex. */ + int32_t idx; + + for (idx = 0; idx < OS_MUTEXCNT; idx++) + { + if (std_libmutex[idx].used == 0) + { + std_libmutex[idx].used = 1; + *mutex = &std_libmutex[idx].mutex; + nr_mutex++; + break; + } + } + if (nr_mutex >= OS_MUTEXCNT) + { + /* If you are here, you need to increase the number OS_MUTEXCNT. */ + for (;;); + } + + mutex_init (*mutex); +} + +/*--------------------------- __iar_system_Mtxdst ---------------------------*/ + +void __iar_system_Mtxdst(__iar_Rmtx *mutex) +{ + /* Free a system mutex. */ + int32_t idx; + + if (nr_mutex == 0) + { + for (;;); + } + + idx = ((((uint32_t)mutex) - ((uint32_t)&std_libmutex[0].mutex)) + / sizeof(os_mut_array_t)); + + if (idx >= OS_MUTEXCNT) + { + for (;;); + } + + mutex_del (*mutex); + std_libmutex[idx].used = 0; +} + +/*--------------------------- __iar_system_Mtxlock --------------------------*/ + +void __iar_system_Mtxlock(__iar_Rmtx *mutex) +{ + /* Acquire a system mutex, lock stdlib resources. */ + if (runtask_id ()) + { + /* RTX running, acquire a mutex. */ + mutex_wait (*mutex); + } +} + +/*--------------------------- __iar_system_Mtxunlock ------------------------*/ + +void __iar_system_Mtxunlock(__iar_Rmtx *mutex) +{ + /* Release a system mutex, unlock stdlib resources. */ + if (runtask_id ()) + { + /* RTX running, release a mutex. */ + mutex_rel (*mutex); + } +} + +#endif + + +/*---------------------------------------------------------------------------- + * RTX Startup + *---------------------------------------------------------------------------*/ + +/* Main Thread definition */ +extern void pre_main (void); +#ifdef __MBED_CMSIS_RTOS_CA9 +uint32_t os_thread_def_stack_main [(4 * OS_MAINSTKSIZE) / sizeof(uint32_t)]; +osThreadDef_t os_thread_def_main = {(os_pthread)pre_main, osPriorityNormal, 1U, 4*OS_MAINSTKSIZE, os_thread_def_stack_main }; +#else +osThreadDef_t os_thread_def_main = {(os_pthread)pre_main, osPriorityNormal, 1U, 4*OS_MAINSTKSIZE }; +#endif + +#if defined (__CC_ARM) + +#ifdef __MICROLIB + +int main(void); +void _main_init (void) __attribute__((section(".ARM.Collect$$$$000000FF"))); +void $Super$$__cpp_initialize__aeabi_(void); + +#if __TARGET_ARCH_ARM +#pragma push +#pragma arm +#endif +void _main_init (void) { + osKernelInitialize(); + osThreadCreate(&os_thread_def_main, NULL); + osKernelStart(); + for (;;); +} +#if __TARGET_ARCH_ARM +#pragma pop +#endif + +void $Sub$$__cpp_initialize__aeabi_(void) +{ + // this should invoke C++ initializers prior _main_init, we keep this empty and + // invoke them after _main_init (=starts RTX kernel) +} + +void pre_main() +{ + singleton_mutex_id = osMutexCreate(osMutex(singleton_mutex)); + $Super$$__cpp_initialize__aeabi_(); + main(); +} + +#else + +void * armcc_heap_base; +void * armcc_heap_top; + +int main(void); + +void pre_main (void) +{ + singleton_mutex_id = osMutexCreate(osMutex(singleton_mutex)); + __rt_lib_init((unsigned)armcc_heap_base, (unsigned)armcc_heap_top); + main(); +} + +__asm void __rt_entry (void) { + + IMPORT __user_setup_stackheap + IMPORT os_thread_def_main + IMPORT armcc_heap_base + IMPORT armcc_heap_top + IMPORT osKernelInitialize + IMPORT osKernelStart + IMPORT osThreadCreate + + BL __user_setup_stackheap + LDR R3,=armcc_heap_base + LDR R4,=armcc_heap_top + STR R0,[R3] + STR R2,[R4] + BL osKernelInitialize + LDR R0,=os_thread_def_main + MOVS R1,#0 + BL osThreadCreate + BL osKernelStart + /* osKernelStart should not return */ + B . + + ALIGN +} +#endif + +#elif defined (__GNUC__) + +osMutexDef(malloc_mutex); +static osMutexId malloc_mutex_id; +osMutexDef(env_mutex); +static osMutexId env_mutex_id; + +extern int atexit(void (*func)(void)); +extern void __libc_fini_array(void); +extern void __libc_init_array (void); +extern int main(int argc, char **argv); + +void pre_main(void) { + singleton_mutex_id = osMutexCreate(osMutex(singleton_mutex)); + malloc_mutex_id = osMutexCreate(osMutex(malloc_mutex)); + env_mutex_id = osMutexCreate(osMutex(env_mutex)); + __libc_init_array(); + main(0, NULL); +} + +__attribute__((naked)) void software_init_hook_rtos (void) { + __asm ( + ".syntax unified\n" + ".arm\n" + "bl osKernelInitialize\n" + "ldr r0,=os_thread_def_main\n" + "movs r1,#0\n" + "bl osThreadCreate\n" + "bl osKernelStart\n" + /* osKernelStart should not return */ + "B .\n" + ); +} + +// Opaque declaration of _reent structure +struct _reent; + +void __rtos_malloc_lock( struct _reent *_r ) +{ + osMutexWait(malloc_mutex_id, osWaitForever); +} + +void __rtos_malloc_unlock( struct _reent *_r ) +{ + osMutexRelease(malloc_mutex_id); +} + +void __rtos_env_lock( struct _reent *_r ) +{ + osMutexWait(env_mutex_id, osWaitForever); +} + +void __rtos_env_unlock( struct _reent *_r ) +{ + osMutexRelease(env_mutex_id); +} + +#elif defined (__ICCARM__) +extern void* __vector_core_a9; +extern int __low_level_init(void); +extern void __iar_data_init3(void); +extern __weak void __iar_init_core( void ); +extern __weak void __iar_init_vfp( void ); +extern void __iar_dynamic_initialization(void); +extern void mbed_sdk_init(void); +extern void mbed_main(void); +extern int main(void); +static uint8_t low_level_init_needed; + +void pre_main(void) { + singleton_mutex_id = osMutexCreate(osMutex(singleton_mutex)); + if (low_level_init_needed) { + __iar_dynamic_initialization(); + } + mbed_main(); + main(); +} + +#pragma required=__vector_core_a9 +void __iar_program_start(void) +{ + __iar_init_core(); + __iar_init_vfp(); + + uint8_t low_level_init_needed_local; + + low_level_init_needed_local = __low_level_init(); + if (low_level_init_needed_local) { + __iar_data_init3(); + mbed_sdk_init(); + } + /* Store in a global variable after RAM has been initialized */ + low_level_init_needed = low_level_init_needed_local; + osKernelInitialize(); + osThreadCreate(&os_thread_def_main, NULL); + osKernelStart(); + /* osKernelStart should not return */ + while (1); +} + +#endif + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ diff --git a/rtos/rtx/TARGET_CORTEX_A/RTX_Conf_CA.c b/rtos/rtx/TARGET_CORTEX_A/RTX_Conf_CA.c new file mode 100644 index 00000000000..97b64a5ec5d --- /dev/null +++ b/rtos/rtx/TARGET_CORTEX_A/RTX_Conf_CA.c @@ -0,0 +1,353 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: RTX_Conf_CM.C + * Purpose: Configuration of CMSIS RTX Kernel + * Rev.: V4.80 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 ARM Germany GmbH + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + +#include "cmsis_os.h" + +/*---------------------------------------------------------------------------- + * RTX User configuration part BEGIN + *---------------------------------------------------------------------------*/ + +#if defined(MBED_RTOS_SINGLE_THREAD) +#define OS_TASKCNT 1 +#define OS_TIMERS 0 +#endif + +// Include per-target RTX config file +#include "mbed_rtx.h" + +//-------- <<< Use Configuration Wizard in Context Menu >>> ----------------- +// +// Thread Configuration +// ======================= +// +// Number of concurrent running user threads <1-250> +// Defines max. number of user threads that will run at the same time. +// Default: 6 +#ifndef OS_TASKCNT + #define OS_TASKCNT 25 +#endif + +#ifdef __MBED_CMSIS_RTOS_CA9 +// Idle stack size [bytes] <64-4096:8><#/4> +// Defines default stack size for the Idle thread. +#ifndef OS_IDLESTKSIZE + #define OS_IDLESTKSIZE 128 +#endif +#else // __MBED_CMSIS_RTOS_CA9 +// Default Thread stack size [bytes] <64-4096:8><#/4> +// Defines default stack size for threads with osThreadDef stacksz = 0 +// Default: 200 +#ifndef OS_STKSIZE + #define OS_STKSIZE 200 // this stack size value is in words +#endif +#endif // __MBED_CMSIS_RTOS_CA9 + +// Main Thread stack size [bytes] <64-4096:8><#/4> +// Defines stack size for main thread. +// Default: 4096 +#ifndef OS_MAINSTKSIZE + #define OS_MAINSTKSIZE 4096 // this stack size value is in words +#endif + +#ifndef __MBED_CMSIS_RTOS_CA9 +// Number of threads with user-provided stack size <0-250> +// Defines the number of threads with user-provided stack size. +// Default: 0 +#ifndef OS_PRIVCNT + #define OS_PRIVCNT 0 +#endif + +// Total stack size [bytes] for threads with user-provided stack size <0-4096:8><#/4> +// Defines the combined stack size for threads with user-provided stack size. +// Default: 0 +#ifndef OS_PRIVSTKSIZE + #define OS_PRIVSTKSIZE 0 // this stack size value is in words +#endif +#endif // __MBED_CMSIS_RTOS_CA9 + +// Stack overflow checking +// Enable stack overflow checks at thread switch. +// Enabling this option increases slightly the execution time of a thread switch. +#ifndef OS_STKCHECK + #define OS_STKCHECK 1 +#endif + +// Stack usage watermark +// Initialize thread stack with watermark pattern for analyzing stack usage (current/maximum) in System and Thread Viewer. +// Enabling this option increases significantly the execution time of osThreadCreate. +#ifndef OS_STKINIT + #if (defined(MBED_STACK_STATS_ENABLED) && MBED_STACK_STATS_ENABLED) + #define OS_STKINIT 1 + #else + #define OS_STKINIT 0 + #endif +#endif + +// Processor mode for thread execution +// <0=> Unprivileged mode +// <1=> Privileged mode +// Default: Privileged mode +#ifndef OS_RUNPRIV + #define OS_RUNPRIV 1 +#endif + +// + +// RTX Kernel Timer Tick Configuration +// ====================================== +// Use Cortex-M SysTick timer as RTX Kernel Timer +// Cortex-M processors provide in most cases a SysTick timer that can be used as +// as time-base for RTX. +#ifndef OS_SYSTICK + #define OS_SYSTICK 0 +#endif +// +// RTOS Kernel Timer input clock frequency [Hz] <1-1000000000> +// Defines the input frequency of the RTOS Kernel Timer. +// Default: 12000000 (12MHz) +// is on most systems identical with the core clock. +#ifndef OS_CLOCK + #error "no target defined" +#endif + +// RTX Timer tick interval value [us] <1-1000000> +// The RTX Timer tick interval value is used to calculate timeout values. +// Default: 1000 (1ms) +#ifndef OS_TICK + #define OS_TICK 1000 +#endif + +// + +// System Configuration +// ======================= +// +// Round-Robin Thread switching +// =============================== +// +// Enables Round-Robin Thread switching. +#ifndef OS_ROBIN + #define OS_ROBIN 1 +#endif + +// Round-Robin Timeout [ticks] <1-1000> +// Defines how long a thread will execute before a thread switch. +// Default: 5 +#ifndef OS_ROBINTOUT + #define OS_ROBINTOUT 5 +#endif + +// + +// User Timers +// ============== +// Enables user Timers +#ifndef OS_TIMERS + #define OS_TIMERS 1 +#endif + +// Timer Thread Priority +// <1=> Low +// <2=> Below Normal <3=> Normal <4=> Above Normal +// <5=> High +// <6=> Realtime (highest) +// Defines priority for Timer Thread +// Default: High +#ifndef OS_TIMERPRIO + #define OS_TIMERPRIO 5 +#endif + +// Timer Thread stack size [bytes] <64-4096:8><#/4> +// Defines stack size for Timer thread. +// Default: 200 +#ifndef OS_TIMERSTKSZ + #define OS_TIMERSTKSZ WORDS_STACK_SIZE // this stack size value is in words +#endif + +// Timer Callback Queue size <1-32> +// Number of concurrent active timer callback functions. +// Default: 4 +#ifndef OS_TIMERCBQS + #define OS_TIMERCBQS 4 +#endif + +// + +// ISR FIFO Queue size<4=> 4 entries <8=> 8 entries +// <12=> 12 entries <16=> 16 entries +// <24=> 24 entries <32=> 32 entries +// <48=> 48 entries <64=> 64 entries +// <96=> 96 entries +// ISR functions store requests to this buffer, +// when they are called from the interrupt handler. +// Default: 16 entries +#ifndef OS_FIFOSZ + #define OS_FIFOSZ 16 +#endif + +// + +//------------- <<< end of configuration section >>> ----------------------- + +// Standard library system mutexes +// =============================== +// Define max. number system mutexes that are used to protect +// the arm standard runtime library. For microlib they are not used. +#ifndef OS_MUTEXCNT + #define OS_MUTEXCNT 12 +#endif + +/*---------------------------------------------------------------------------- + * RTX User configuration part END + *---------------------------------------------------------------------------*/ + +#define OS_TRV ((uint32_t)(((double)OS_CLOCK*(double)OS_TICK)/1E6)-1) + + +/*---------------------------------------------------------------------------- + * Global Functions + *---------------------------------------------------------------------------*/ + +/*--------------------------- os_idle_demon ---------------------------------*/ +extern void rtos_idle_loop(void); + +/// \brief The idle demon is running when no other thread is ready to run +void os_idle_demon (void) { + rtos_idle_loop(); +} + +#if (OS_SYSTICK == 0) // Functions for alternative timer as RTX kernel timer + +/*--------------------------- os_tick_init ----------------------------------*/ +#if defined(TARGET_RZ_A1H) || defined(TARGET_VK_RZ_A1H) +#define OSTM0 (0xFCFEC000uL) /* OSTM0 */ +#define OSTM1 (0xFCFEC400uL) /* OSTM1 */ +#define CPG (0xFCFE0410uL) /* CPG */ + +#define CPGSTBCR5 (*((volatile unsigned char*)(CPG + 0x00000018uL))) + +#define OSTM0CMP (*((volatile unsigned long*)(OSTM0 + 0x00000000uL))) +#define OSTM0CNT (*((volatile unsigned long*)(OSTM0 + 0x00000004uL))) +#define OSTM0TE (*((volatile unsigned char*)(OSTM0 + 0x00000010uL))) +#define OSTM0TS (*((volatile unsigned char*)(OSTM0 + 0x00000014uL))) +#define OSTM0TT (*((volatile unsigned char*)(OSTM0 + 0x00000018uL))) +#define OSTM0CTL (*((volatile unsigned char*)(OSTM0 + 0x00000020uL))) + +#define OSTM1CMP (*((volatile unsigned long*)(OSTM1 + 0x00000000uL))) +#define OSTM1CNT (*((volatile unsigned long*)(OSTM1 + 0x00000004uL))) +#define OSTM1TE (*((volatile unsigned char*)(OSTM1 + 0x00000010uL))) +#define OSTM1TS (*((volatile unsigned char*)(OSTM1 + 0x00000014uL))) +#define OSTM1TT (*((volatile unsigned char*)(OSTM1 + 0x00000018uL))) +#define OSTM1CTL (*((volatile unsigned char*)(OSTM1 + 0x00000020uL))) + +#define CPG_STBCR5_BIT_MSTP51 (0x02u) /* OSTM0 */ +#define CM1_RENESAS_RZ_A1_P0_CLK ( 32000000u) +#define CM0_RENESAS_RZ_A1_P0_CLK ( 33333333u) + +typedef enum +{ + IRQ_SGI0 = 0, + IRQ_OSTMI0TINT = 134 +} IRQn_Type; + +typedef void(*IRQHandler)(); + +extern void PendSV_Handler(uint32_t); +extern void OS_Tick_Handler(uint32_t); +extern uint32_t InterruptHandlerRegister (IRQn_Type irq, IRQHandler handler); +#endif + +/// \brief Initializes an alternative hardware timer as RTX kernel timer +/// \return IRQ number of the alternative hardware timer +int os_tick_init (void) { +#if defined(TARGET_RZ_A1H) || defined(TARGET_VK_RZ_A1H) + CPGSTBCR5 &= ~(CPG_STBCR5_BIT_MSTP51); /* enable OSTM0 clock */ + + OSTM0TT = 0x1; /* Stop the counter and clears the OSTM0TE bit. */ + OSTM0CTL = 0x1; /* Interval timer mode. Interrupt enabled */ + + OSTM0CMP = (uint32_t)(((double)CM0_RENESAS_RZ_A1_P0_CLK*(double)OS_TICK)/1E6); + + OSTM0TS = 0x1; /* Start the counter and sets the OSTM0TE bit. */ + + InterruptHandlerRegister(IRQ_SGI0 , (IRQHandler)PendSV_Handler); + InterruptHandlerRegister(IRQ_OSTMI0TINT, (IRQHandler)OS_Tick_Handler); + + + return IRQ_OSTMI0TINT; /* Return IRQ number of timer (0..239) */ + /* RTX will set and configure the interrupt */ +#endif +} + +/*--------------------------- os_tick_irqack --------------------------------*/ + +/// \brief Acknowledge alternative hardware timer interrupt +void os_tick_irqack (void) { + /* ... */ +} + +#endif // (OS_SYSTICK == 0) + +/*--------------------------- os_error --------------------------------------*/ +extern void error(const char* format, ...); +extern osThreadId svcThreadGetId (void); + +void os_error (uint32_t err_code) { + /* This function is called when a runtime error is detected. Parameter */ + /* 'err_code' holds the runtime error code (defined in RTX_Config.h). */ + osThreadId err_task = svcThreadGetId(); + error("RTX error code: 0x%08X, task ID: 0x%08X\n", err_code, err_task); + + /* HERE: include optional code to be executed on runtime error. */ + for (;;); +} + +/*---------------------------------------------------------------------------- + * RTX Hooks + *---------------------------------------------------------------------------*/ +extern void thread_terminate_hook(osThreadId id); + +void sysThreadTerminate(osThreadId id) { + thread_terminate_hook(id); +} + +/*---------------------------------------------------------------------------- + * RTX Configuration Functions + *---------------------------------------------------------------------------*/ + +#include "RTX_CM_lib.h" + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ diff --git a/rtos/rtx/TARGET_CORTEX_A/RTX_Config.h b/rtos/rtx/TARGET_CORTEX_A/RTX_Config.h new file mode 100644 index 00000000000..d6f5161c474 --- /dev/null +++ b/rtos/rtx/TARGET_CORTEX_A/RTX_Config.h @@ -0,0 +1,79 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: RTX_CONFIG.H + * Purpose: Exported functions of RTX_Config.c + * Rev.: V4.79 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 ARM Germany GmbH + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + + +/* Error Codes */ +#define OS_ERR_STK_OVF 1U +#define OS_ERR_FIFO_OVF 2U +#define OS_ERR_MBX_OVF 3U +#define OS_ERR_TIMER_OVF 4U + +/* Definitions */ +#define BOX_ALIGN_8 0x80000000U +#define _declare_box(pool,size,cnt) U32 pool[(((size)+3)/4)*(cnt) + 3] +#define _declare_box8(pool,size,cnt) U64 pool[(((size)+7)/8)*(cnt) + 2] +#define _init_box8(pool,size,bsize) _init_box (pool,size,(bsize) | BOX_ALIGN_8) + +/* Variables */ +extern U32 mp_tcb[]; +extern U64 mp_stk[]; +extern U32 os_fifo[]; +extern void *os_active_TCB[]; + +/* Constants */ +extern U16 const os_maxtaskrun; +extern U32 const os_trv; +extern U8 const os_flags; +extern U32 const os_stackinfo; +extern U32 const os_rrobin; +extern U32 const os_clockrate; +extern U32 const os_timernum; +extern U16 const mp_tcb_size; +extern U32 const mp_stk_size; +extern U32 const *m_tmr; +extern U16 const mp_tmr_size; +extern U8 const os_fifo_size; + +/* Functions */ +extern void os_idle_demon (void); +extern S32 os_tick_init (void); +extern U32 os_tick_val (void); +extern U32 os_tick_ovf (void); +extern void os_tick_irqack (void); +extern void os_tmr_call (U16 info); +extern void os_error (U32 err_code); + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ diff --git a/rtos/rtx/TARGET_CORTEX_A/TOOLCHAIN_ARM/HAL_CA9.c b/rtos/rtx/TARGET_CORTEX_A/TOOLCHAIN_ARM/HAL_CA9.c new file mode 100644 index 00000000000..fad36ca440e --- /dev/null +++ b/rtos/rtx/TARGET_CORTEX_A/TOOLCHAIN_ARM/HAL_CA9.c @@ -0,0 +1,438 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: HAL_CA9.c + * Purpose: Hardware Abstraction Layer for Cortex-A9 (GICv1) + * Rev.: 28 April 2016 + *---------------------------------------------------------------------------- + * + * Copyright (c) 2012 - 2016 ARM Limited + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Config.h" +#include "rt_System.h" +#include "rt_Task.h" +#include "rt_List.h" +#include "rt_MemBox.h" +#include "rt_HAL_CA.h" + + +/*---------------------------------------------------------------------------- + * Functions + *---------------------------------------------------------------------------*/ + +//For A-class, set USR/SYS stack +__asm void rt_set_PSP (U32 stack) { + ARM + + MRS R1, CPSR + CPS #MODE_SYS ;no effect in USR mode + ISB + MOV SP, R0 + MSR CPSR_c, R1 ;no effect in USR mode + ISB + BX LR + +} + +//For A-class, get USR/SYS stack +__asm U32 rt_get_PSP (void) { + ARM + + MRS R1, CPSR + CPS #MODE_SYS ;no effect in USR mode + ISB + MOV R0, SP + MSR CPSR_c, R1 ;no effect in USR mode + ISB + BX LR +} + +/*--------------------------- _alloc_box ------------------------------------*/ +__asm void *_alloc_box (void *box_mem) { + /* Function wrapper for Unprivileged/Privileged mode. */ + ARM + + LDR R12,=__cpp(rt_alloc_box) + MRS R2, CPSR + LSLS R2, #28 + BXNE R12 + SVC 0 + BX LR +} + + +/*--------------------------- _free_box -------------------------------------*/ +__asm U32 _free_box (void *box_mem, void *box) { + /* Function wrapper for Unprivileged/Privileged mode. */ + ARM + + LDR R12,=__cpp(rt_free_box) + MRS R2, CPSR + LSLS R2, #28 + BXNE R12 + SVC 0 + BX LR + +} + +/*-------------------------- SVC_Handler -----------------------------------*/ + +#pragma push +#pragma arm +__asm void SVC_Handler (void) { + PRESERVE8 + ARM + + IMPORT rt_tsk_lock + IMPORT rt_tsk_unlock + IMPORT SVC_Count + IMPORT SVC_Table + IMPORT rt_stk_check + IMPORT FPUEnable + IMPORT scheduler_suspended ; Flag set by rt_suspend, cleared by rt_resume, read by SVC_Handler + +Mode_SVC EQU 0x13 + + SRSFD SP!, #Mode_SVC ; Push LR_SVC and SPRS_SVC onto SVC mode stack + PUSH {R4} ; Push R4 so we can use it as a temp + + MRS R4,SPSR ; Get SPSR + TST R4,#CPSR_T_BIT ; Check Thumb Bit + LDRNEH R4,[LR,#-2] ; Thumb: Load Halfword + BICNE R4,R4,#0xFF00 ; Extract SVC Number + LDREQ R4,[LR,#-4] ; ARM: Load Word + BICEQ R4,R4,#0xFF000000 ; Extract SVC Number + + /* Lock out systick and re-enable interrupts */ + PUSH {R0-R3,R12,LR} + + AND R12, SP, #4 ; Ensure stack is 8-byte aligned + SUB SP, SP, R12 ; Adjust stack + PUSH {R12, LR} ; Store stack adjustment and dummy LR to SVC stack + + BLX rt_tsk_lock + CPSIE i + + POP {R12, LR} ; Get stack adjustment & discard dummy LR + ADD SP, SP, R12 ; Unadjust stack + + POP {R0-R3,R12,LR} + + CMP R4,#0 + BNE SVC_User + + MRS R4,SPSR + PUSH {R4} ; Push R4 so we can use it as a temp + AND R4, SP, #4 ; Ensure stack is 8-byte aligned + SUB SP, SP, R4 ; Adjust stack + PUSH {R4, LR} ; Store stack adjustment and dummy LR + BLX R12 + POP {R4, LR} ; Get stack adjustment & discard dummy LR + ADD SP, SP, R4 ; Unadjust stack + POP {R4} ; Restore R4 + MSR SPSR_CXSF,R4 + + /* Here we will be in SVC mode (even if coming in from PendSV_Handler or OS_Tick_Handler) */ +Sys_Switch + LDR LR,=__cpp(&os_tsk) + LDM LR,{R4,LR} ; os_tsk.run, os_tsk.new_tsk + CMP R4,LR + BNE switching + + PUSH {R0-R3,R12,LR} + + AND R12, SP, #4 ; Ensure stack is 8-byte aligned + SUB SP, SP, R12 ; Adjust stack + PUSH {R12, LR} ; Store stack adjustment and dummy LR to SVC stack + + CPSID i + ; Do not unlock scheduler if it has just been suspended by rt_suspend() + LDR R1,=scheduler_suspended + LDRB R0, [R1] + CMP R0, #1 + BEQ dont_unlock + BLX rt_tsk_unlock +dont_unlock + + POP {R12, LR} ; Get stack adjustment & discard dummy LR + ADD SP, SP, R12 ; Unadjust stack + + POP {R0-R3,R12,LR} + POP {R4} + RFEFD SP! ; Return from exception, no task switch + +switching + CLREX + CMP R4,#0 + ADDEQ SP,SP,#12 ; Original R4, LR & SPSR do not need to be popped when we are paging in a different task + BEQ SVC_Next ; Runtask deleted? + + + PUSH {R8-R11} //R4 and LR already stacked + MOV R10,R4 ; Preserve os_tsk.run + MOV R11,LR ; Preserve os_tsk.new_tsk + + ADD R8,SP,#16 ; Unstack R4,LR + LDMIA R8,{R4,LR} + + SUB SP,SP,#4 ; Make space on the stack for the next instn + STMIA SP,{SP}^ ; Put User SP onto stack + POP {R8} ; Pop User SP into R8 + + MRS R9,SPSR + STMDB R8!,{R9} ; User CPSR + STMDB R8!,{LR} ; User PC + STMDB R8,{LR}^ ; User LR + SUB R8,R8,#4 ; No writeback for store of User LR + STMDB R8!,{R0-R3,R12} ; User R0-R3,R12 + MOV R3,R10 ; os_tsk.run + MOV LR,R11 ; os_tsk.new_tsk + POP {R9-R12} + ADD SP,SP,#12 ; Fix up SP for unstack of R4, LR & SPSR + STMDB R8!,{R4-R7,R9-R12} ; User R4-R11 + + //If applicable, stack VFP/NEON state + MRC p15,0,R1,c1,c0,2 ; VFP/NEON access enabled? (CPACR) + AND R2,R1,#0x00F00000 + CMP R2,#0x00F00000 + BNE no_outgoing_vfp + VMRS R2,FPSCR + STMDB R8!,{R2,R4} ; Push FPSCR, maintain 8-byte alignment + VSTMDB R8!,{D0-D15} + VSTMDB R8!,{D16-D31} + LDRB R2,[R3,#TCB_STACKF] ; Record in TCB that NEON/D32 state is stacked + ORR R2,#4 + STRB R2,[R3,#TCB_STACKF] + +no_outgoing_vfp + STR R8,[R3,#TCB_TSTACK] + MOV R4,LR + + PUSH {R4} ; Push R4 so we can use it as a temp + AND R4, SP, #4 ; Ensure stack is 8-byte aligned + SUB SP, SP, R4 ; Adjust stack + PUSH {R4, LR} ; Store stack adjustment and dummy LR to SVC stack + + BLX rt_stk_check + + POP {R4, LR} ; Get stack adjustment & discard dummy LR + ADD SP, SP, R4 ; Unadjust stack + POP {R4} ; Restore R4 + + MOV LR,R4 + +SVC_Next //R4 == os_tsk.run, LR == os_tsk.new_tsk, R0-R3, R5-R12 corruptible + LDR R1,=__cpp(&os_tsk) ; os_tsk.run = os_tsk.new_tsk + STR LR,[R1] + LDRB R1,[LR,#TCB_TID] ; os_tsk.run->task_id + LSL R1,#8 ; Store PROCID + MCR p15,0,R1,c13,c0,1 ; Write CONTEXTIDR + + LDR R0,[LR,#TCB_TSTACK] ; os_tsk.run->tsk_stack + + //Does incoming task have VFP/NEON state in stack? + LDRB R3,[LR,#TCB_STACKF] + ANDS R3, R3, #0x6 + MRC p15,0,R1,c1,c0,2 ; Read CPACR + ANDEQ R1,R1,#0xFF0FFFFF ; Disable VFP/NEON access if incoming task does not have stacked VFP/NEON state + ORRNE R1,R1,#0x00F00000 ; Enable VFP/NEON access if incoming task does have stacked VFP/NEON state + MCR p15,0,R1,c1,c0,2 ; Write CPACR + BEQ no_incoming_vfp + ISB ; We only need the sync if we enabled, otherwise we will context switch before next VFP/NEON instruction anyway + VLDMIA R0!,{D16-D31} + VLDMIA R0!,{D0-D15} + LDR R2,[R0] + VMSR FPSCR,R2 + ADD R0,R0,#8 + +no_incoming_vfp + LDR R1,[R0,#60] ; Restore User CPSR + MSR SPSR_CXSF,R1 + LDMIA R0!,{R4-R11} ; Restore User R4-R11 + ADD R0,R0,#4 ; Restore User R1-R3,R12 + LDMIA R0!,{R1-R3,R12} + LDMIA R0,{LR}^ ; Restore User LR + ADD R0,R0,#4 ; No writeback for load to user LR + LDMIA R0!,{LR} ; Restore User PC + ADD R0,R0,#4 ; Correct User SP for unstacked user CPSR + + PUSH {R0} ; Push R0 onto stack + LDMIA SP,{SP}^ ; Get R0 off stack into User SP + ADD SP,SP,#4 ; Put SP back + + LDR R0,[R0,#-32] ; Restore R0 + + PUSH {R0-R3,R12,LR} + + AND R12, SP, #4 ; Ensure stack is 8-byte aligned + SUB SP, SP, R12 ; Adjust stack + PUSH {R12, LR} ; Store stack adjustment and dummy LR to SVC stack + + CPSID i + BLX rt_tsk_unlock + + POP {R12, LR} ; Get stack adjustment & discard dummy LR + ADD SP, SP, R12 ; Unadjust stack + + POP {R0-R3,R12,LR} + + MOVS PC,LR ; Return from exception + + + /*------------------- User SVC -------------------------------*/ + +SVC_User + LDR R12,=SVC_Count + LDR R12,[R12] + CMP R4,R12 ; Check for overflow + BHI SVC_Done + + LDR R12,=SVC_Table-4 + LDR R12,[R12,R4,LSL #2] ; Load SVC Function Address + MRS R4,SPSR ; Save SPSR + PUSH {R4} ; Push R4 so we can use it as a temp + AND R4, SP, #4 ; Ensure stack is 8-byte aligned + SUB SP, SP, R4 ; Adjust stack + PUSH {R4, LR} ; Store stack adjustment and dummy LR + BLX R12 ; Call SVC Function + POP {R4, LR} ; Get stack adjustment & discard dummy LR + ADD SP, SP, R4 ; Unadjust stack + POP {R4} ; Restore R4 + MSR SPSR_CXSF,R4 ; Restore SPSR + +SVC_Done + PUSH {R0-R3,R12,LR} + + PUSH {R4} ; Push R4 so we can use it as a temp + AND R4, SP, #4 ; Ensure stack is 8-byte aligned + SUB SP, SP, R4 ; Adjust stack + PUSH {R4, LR} ; Store stack adjustment and dummy LR + + CPSID i + BLX rt_tsk_unlock + + POP {R4, LR} ; Get stack adjustment & discard dummy LR + ADD SP, SP, R4 ; Unadjust stack + POP {R4} ; Restore R4 + + POP {R0-R3,R12,LR} + POP {R4} + RFEFD SP! ; Return from exception +} +#pragma pop + +#pragma push +#pragma arm +__asm void PendSV_Handler (U32 IRQn) { + ARM + + IMPORT rt_tsk_lock + IMPORT IRQNestLevel ; Flag indicates whether inside an ISR, and the depth of nesting. 0 = not in ISR. + IMPORT seen_id0_active ; Flag used to workaround GIC 390 errata 733075 (set in startup_.s) + + ADD SP,SP,#8 //fix up stack pointer (R0 has been pushed and will never be popped, R1 was pushed for stack alignment) + + //Disable systick interrupts, then write EOIR. We want interrupts disabled before we enter the context switcher. + PUSH {R0, R1} + BLX rt_tsk_lock + POP {R0, R1} + LDR R1, =__cpp(&GICInterface_BASE) + LDR R1, [R1, #0] + STR R0, [R1, #0x10] ; Write End Of Interrupt ID to GICC_EOIR + + ; If it was interrupt ID0, clear the seen flag, otherwise return as normal + CMP R0, #0 + LDREQ R1, =seen_id0_active + STRBEQ R0, [R1] ; Clear the seen flag, using R0 (which is 0), to save loading another register + + LDR R0, =IRQNestLevel ; Get address of nesting counter + LDR R1, [R0] + SUB R1, R1, #1 ; Decrement nesting counter + STR R1, [R0] + + BLX __cpp(rt_pop_req) + + POP {R1, LR} ; Get stack adjustment & discard dummy LR + ADD SP, SP, R1 ; Unadjust stack + + LDR R0,[SP,#24] + MSR SPSR_CXSF,R0 + POP {R0-R3,R12} ; Leave SPSR & LR on the stack + PUSH {R4} + B Sys_Switch +} +#pragma pop + + +#pragma push +#pragma arm +__asm void OS_Tick_Handler (U32 IRQn) { + ARM + + IMPORT rt_tsk_lock + IMPORT IRQNestLevel ; Flag indicates whether inside an ISR, and the depth of nesting. 0 = not in ISR. + IMPORT seen_id0_active ; Flag used to workaround GIC 390 errata 733075 (set in startup_.s) + + ADD SP,SP,#8 //fix up stack pointer (R0 has been pushed and will never be popped, R1 was pushed for stack alignment) + + //Disable systick interrupts, then write EOIR. We want interrupts disabled before we enter the context switcher. + PUSH {R0, R1} + BLX rt_tsk_lock + POP {R0, R1} + LDR R1, =__cpp(&GICInterface_BASE) + LDR R1, [R1, #0] + STR R0, [R1, #0x10] ; Write End Of Interrupt ID to GICC_EOIR + + ; If it was interrupt ID0, clear the seen flag, otherwise return as normal + CMP R0, #0 + LDREQ R1, =seen_id0_active + STRBEQ R0, [R1] ; Clear the seen flag, using R0 (which is 0), to save loading another register + + LDR R0, =IRQNestLevel ; Get address of nesting counter + LDR R1, [R0] + SUB R1, R1, #1 ; Decrement nesting counter + STR R1, [R0] + + BLX __cpp(os_tick_irqack) + BLX __cpp(rt_systick) + + POP {R1, LR} ; Get stack adjustment & discard dummy LR + ADD SP, SP, R1 ; Unadjust stack + + LDR R0,[SP,#24] + MSR SPSR_CXSF,R0 + POP {R0-R3,R12} ; Leave SPSR & LR on the stack + PUSH {R4} + B Sys_Switch +} +#pragma pop + + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ diff --git a/rtos/rtx/TARGET_CORTEX_A/TOOLCHAIN_ARM/SVC_Table.S b/rtos/rtx/TARGET_CORTEX_A/TOOLCHAIN_ARM/SVC_Table.S new file mode 100644 index 00000000000..37e84290808 --- /dev/null +++ b/rtos/rtx/TARGET_CORTEX_A/TOOLCHAIN_ARM/SVC_Table.S @@ -0,0 +1,57 @@ +;/*---------------------------------------------------------------------------- +; * CMSIS-RTOS - RTX +; *---------------------------------------------------------------------------- +; * Name: SVC_TABLE.S +; * Purpose: Pre-defined SVC Table +; * Rev.: V4.70, with additions for Cortex-A +; *---------------------------------------------------------------------------- +; * +; * Copyright (c) 1999-2009 KEIL, 2009-2013 ARM Germany GmbH, 2014-2015 ARM Ltd +; * All rights reserved. +; * Redistribution and use in source and binary forms, with or without +; * modification, are permitted provided that the following conditions are met: +; * - Redistributions of source code must retain the above copyright +; * notice, this list of conditions and the following disclaimer. +; * - Redistributions in binary form must reproduce the above copyright +; * notice, this list of conditions and the following disclaimer in the +; * documentation and/or other materials provided with the distribution. +; * - Neither the name of ARM nor the names of its contributors may be used +; * to endorse or promote products derived from this software without +; * specific prior written permission. +; * +; * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +; * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +; * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +; * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE +; * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +; * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +; * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +; * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +; * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +; * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +; * POSSIBILITY OF SUCH DAMAGE. +; *---------------------------------------------------------------------------*/ + + + AREA SVC_TABLE, CODE, READONLY + + EXPORT SVC_Count + +SVC_Cnt EQU (SVC_End-SVC_Table)/4 +SVC_Count DCD SVC_Cnt + +; Import user SVC functions here. +; IMPORT __SVC_1 + + EXPORT SVC_Table +SVC_Table +; Insert user SVC functions here. SVC 0 used by RTX Kernel. +; DCD __SVC_1 ; EnableCaches + +SVC_End + + END + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ diff --git a/rtos/rtx/TARGET_CORTEX_A/TOOLCHAIN_GCC/HAL_CA9.S b/rtos/rtx/TARGET_CORTEX_A/TOOLCHAIN_GCC/HAL_CA9.S new file mode 100644 index 00000000000..17cd8e28975 --- /dev/null +++ b/rtos/rtx/TARGET_CORTEX_A/TOOLCHAIN_GCC/HAL_CA9.S @@ -0,0 +1,473 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: HAL_CA9.c + * Purpose: Hardware Abstraction Layer for Cortex-A9 (GICv1) + * Rev.: 28 April 2016 + *---------------------------------------------------------------------------- + * + * Copyright (c) 2012 - 2016 ARM Limited + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + + .global rt_set_PSP + .global rt_get_PSP + .global _alloc_box + .global _free_box + .global SVC_Handler + .global PendSV_Handler + .global OS_Tick_Handler + +/* macro defines form rt_HAL_CA.h */ + .EQU CPSR_T_BIT, 0x20 + .EQU CPSR_I_BIT, 0x80 + .EQU CPSR_F_BIT, 0x40 + + .EQU MODE_USR, 0x10 + .EQU MODE_FIQ, 0x11 + .EQU MODE_IRQ, 0x12 + .EQU MODE_SVC, 0x13 + .EQU MODE_ABT, 0x17 + .EQU MODE_UND, 0x1B + .EQU MODE_SYS, 0x1F + +/* macro defines form rt_TypeDef.h */ + .EQU TCB_TID, 3 /* 'task id' offset */ + .EQU TCB_STACKF, 37 /* 'stack_frame' offset */ + .EQU TCB_TSTACK, 44 /* 'tsk_stack' offset for LARGE_STACK */ + + + .extern rt_alloc_box + .extern os_tsk + .extern GICInterface_BASE + .extern rt_pop_req + .extern os_tick_irqack + .extern rt_systick + + .text + +/*---------------------------------------------------------------------------- + * Functions + *---------------------------------------------------------------------------*/ + +@ For A-class, set USR/SYS stack +@ __asm void rt_set_PSP (U32 stack) { +rt_set_PSP: + .ARM + + MRS R1, CPSR + CPS #MODE_SYS @no effect in USR mode + ISB + MOV SP, R0 + MSR CPSR_c, R1 @no effect in USR mode + ISB + BX LR + +@ } + +@ For A-class, get USR/SYS stack +@ __asm U32 rt_get_PSP (void) { +rt_get_PSP: + .ARM + + MRS R1, CPSR + CPS #MODE_SYS @no effect in USR mode + ISB + MOV R0, SP + MSR CPSR_c, R1 @no effect in USR mode + ISB + BX LR +@ } + +/*--------------------------- _alloc_box ------------------------------------*/ +@ __asm void *_alloc_box (void *box_mem) { +_alloc_box: + /* Function wrapper for Unprivileged/Privileged mode. */ + .ARM + + LDR R12,=rt_alloc_box + MRS R2, CPSR + LSLS R2, #28 + BXNE R12 + SVC 0 + BX LR +@ } + + +/*--------------------------- _free_box -------------------------------------*/ +@ __asm U32 _free_box (void *box_mem, void *box) { +_free_box: + /* Function wrapper for Unprivileged/Privileged mode. */ + .ARM + + LDR R12,=rt_free_box + MRS R2, CPSR + LSLS R2, #28 + BXNE R12 + SVC 0 + BX LR + +@ } + +/*-------------------------- SVC_Handler -----------------------------------*/ + +@ #pragma push +@ #pragma arm +@ __asm void SVC_Handler (void) { +SVC_Handler: + .eabi_attribute Tag_ABI_align8_preserved,1 + .ARM + + .extern rt_tsk_lock + .extern rt_tsk_unlock + .extern SVC_Count + .extern SVC_Table + .extern rt_stk_check + .extern FPUEnable + .extern scheduler_suspended @ flag set by rt_suspend, cleared by rt_resume, read by SVC_Handler + + .EQU Mode_SVC, 0x13 + + SRSDB SP!, #Mode_SVC @ Push LR_SVC and SPRS_SVC onto SVC mode stack @ Use SRSDB because SRSFD isn't supported by GCC-ARM. + PUSH {R4} @ Push R4 so we can use it as a temp + + MRS R4,SPSR @ Get SPSR + TST R4,#CPSR_T_BIT @ Check Thumb Bit + LDRNEH R4,[LR,#-2] @ Thumb: Load Halfword + BICNE R4,R4,#0xFF00 @ Extract SVC Number + LDREQ R4,[LR,#-4] @ ARM: Load Word + BICEQ R4,R4,#0xFF000000 @ Extract SVC Number + + /* Lock out systick and re-enable interrupts */ + PUSH {R0-R3,R12,LR} + + AND R12, SP, #4 @ Ensure stack is 8-byte aligned + SUB SP, SP, R12 @ Adjust stack + PUSH {R12, LR} @ Store stack adjustment and dummy LR to SVC stack + + BLX rt_tsk_lock + CPSIE i + + POP {R12, LR} @ Get stack adjustment & discard dummy LR + ADD SP, SP, R12 @ Unadjust stack + + POP {R0-R3,R12,LR} + + CMP R4,#0 + BNE SVC_User + + MRS R4,SPSR + PUSH {R4} @ Push R4 so we can use it as a temp + AND R4, SP, #4 @ Ensure stack is 8-byte aligned + SUB SP, SP, R4 @ Adjust stack + PUSH {R4, LR} @ Store stack adjustment and dummy LR + BLX R12 + POP {R4, LR} @ Get stack adjustment & discard dummy LR + ADD SP, SP, R4 @ Unadjust stack + POP {R4} @ Restore R4 + MSR SPSR_cxsf,R4 + + /* Here we will be in SVC mode (even if coming in from PendSV_Handler or OS_Tick_Handler) */ +Sys_Switch: + LDR LR,=os_tsk + LDM LR,{R4,LR} @ os_tsk.run, os_tsk.new_tsk + CMP R4,LR + BNE switching + + PUSH {R0-R3,R12,LR} + + AND R12, SP, #4 @ Ensure stack is 8-byte aligned + SUB SP, SP, R12 @ Adjust stack + PUSH {R12, LR} @ Store stack adjustment and dummy LR to SVC stack + + CPSID i + @ Do not unlock scheduler if it has just been suspended by rt_suspend() + LDR R1,=scheduler_suspended + LDRB R0, [R1] + CMP R0, #1 + BEQ dont_unlock + BLX rt_tsk_unlock +dont_unlock: + + POP {R12, LR} @ Get stack adjustment & discard dummy LR + ADD SP, SP, R12 @ Unadjust stack + + POP {R0-R3,R12,LR} + POP {R4} + RFEFD SP! @ Return from exception, no task switch + +switching: + CLREX + CMP R4,#0 + ADDEQ SP,SP,#12 @ Original R4, LR & SPSR do not need to be popped when we are paging in a different task + BEQ SVC_Next @ Runtask deleted? + + + PUSH {R8-R11} @ R4 and LR already stacked + MOV R10,R4 @ Preserve os_tsk.run + MOV R11,LR @ Preserve os_tsk.new_tsk + + ADD R8,SP,#16 @ Unstack R4,LR + LDMIA R8,{R4,LR} + + SUB SP,SP,#4 @ Make space on the stack for the next instn + STMIA SP,{SP}^ @ Put User SP onto stack + POP {R8} @ Pop User SP into R8 + + MRS R9,SPSR + STMDB R8!,{R9} @ User CPSR + STMDB R8!,{LR} @ User PC + STMDB R8,{LR}^ @ User LR + SUB R8,R8,#4 @ No writeback for store of User LR + STMDB R8!,{R0-R3,R12} @ User R0-R3,R12 + MOV R3,R10 @ os_tsk.run + MOV LR,R11 @ os_tsk.new_tsk + POP {R9-R12} + ADD SP,SP,#12 @ Fix up SP for unstack of R4, LR & SPSR + STMDB R8!,{R4-R7,R9-R12} @ User R4-R11 + + @ If applicable, stack VFP/NEON state + MRC p15,0,R1,c1,c0,2 @ VFP/NEON access enabled? (CPACR) + AND R2,R1,#0x00F00000 + CMP R2,#0x00F00000 + BNE no_outgoing_vfp + VMRS R2,FPSCR + STMDB R8!,{R2,R4} @ Push FPSCR, maintain 8-byte alignment + VSTMDB R8!,{D0-D15} + VSTMDB R8!,{D16-D31} + LDRB R2,[R3,#TCB_STACKF] @ Record in TCB that NEON/D32 state is stacked + ORR R2,#4 + STRB R2,[R3,#TCB_STACKF] + +no_outgoing_vfp: + STR R8,[R3,#TCB_TSTACK] + MOV R4,LR + + PUSH {R4} @ Push R4 so we can use it as a temp + AND R4, SP, #4 @ Ensure stack is 8-byte aligned + SUB SP, SP, R4 @ Adjust stack + PUSH {R4, LR} @ Store stack adjustment and dummy LR to SVC stack + + BLX rt_stk_check + + POP {R4, LR} @ Get stack adjustment & discard dummy LR + ADD SP, SP, R4 @ Unadjust stack + POP {R4} @ Restore R4 + + MOV LR,R4 + +SVC_Next: @ R4 == os_tsk.run, LR == os_tsk.new_tsk, R0-R3, R5-R12 corruptible + LDR R1,=os_tsk @ os_tsk.run = os_tsk.new_tsk + STR LR,[R1] + LDRB R1,[LR,#TCB_TID] @ os_tsk.run->task_id + LSL R1,#8 @ Store PROCID + MCR p15,0,R1,c13,c0,1 @ Write CONTEXTIDR + + LDR R0,[LR,#TCB_TSTACK] @ os_tsk.run->tsk_stack + + @ Does incoming task have VFP/NEON state in stack? + LDRB R3,[LR,#TCB_STACKF] + ANDS R3, R3, #0x6 + MRC p15,0,R1,c1,c0,2 @ Read CPACR + ANDEQ R1,R1,#0xFF0FFFFF @ Disable VFP/NEON access if incoming task does not have stacked VFP/NEON state + ORRNE R1,R1,#0x00F00000 @ Enable VFP/NEON access if incoming task does have stacked VFP/NEON state + MCR p15,0,R1,c1,c0,2 @ Write CPACR + BEQ no_incoming_vfp + ISB @ We only need the sync if we enabled, otherwise we will context switch before next VFP/NEON instruction anyway + VLDMIA R0!,{D16-D31} + VLDMIA R0!,{D0-D15} + LDR R2,[R0] + VMSR FPSCR,R2 + ADD R0,R0,#8 + +no_incoming_vfp: + LDR R1,[R0,#60] @ Restore User CPSR + MSR SPSR_cxsf,R1 + LDMIA R0!,{R4-R11} @ Restore User R4-R11 + ADD R0,R0,#4 @ Restore User R1-R3,R12 + LDMIA R0!,{R1-R3,R12} + LDMIA R0,{LR}^ @ Restore User LR + ADD R0,R0,#4 @ No writeback for load to user LR + LDMIA R0!,{LR} @ Restore User PC + ADD R0,R0,#4 @ Correct User SP for unstacked user CPSR + + PUSH {R0} @ Push R0 onto stack + LDMIA SP,{SP}^ @ Get R0 off stack into User SP + ADD SP,SP,#4 @ Put SP back + + LDR R0,[R0,#-32] @ Restore R0 + + PUSH {R0-R3,R12,LR} + + AND R12, SP, #4 @ Ensure stack is 8-byte aligned + SUB SP, SP, R12 @ Adjust stack + PUSH {R12, LR} @ Store stack adjustment and dummy LR to SVC stack + + CPSID i + BLX rt_tsk_unlock + + POP {R12, LR} @ Get stack adjustment & discard dummy LR + ADD SP, SP, R12 @ Unadjust stack + + POP {R0-R3,R12,LR} + + MOVS PC,LR @ Return from exception + + + /*------------------- User SVC -------------------------------*/ + +SVC_User: + LDR R12,=SVC_Count + LDR R12,[R12] + CMP R4,R12 @ Check for overflow + BHI SVC_Done + + LDR R12,=SVC_Table-4 + LDR R12,[R12,R4,LSL #2] @ Load SVC Function Address + MRS R4,SPSR @ Save SPSR + PUSH {R4} @ Push R4 so we can use it as a temp + AND R4, SP, #4 @ Ensure stack is 8-byte aligned + SUB SP, SP, R4 @ Adjust stack + PUSH {R4, LR} @ Store stack adjustment and dummy LR + BLX R12 @ Call SVC Function + POP {R4, LR} @ Get stack adjustment & discard dummy LR + ADD SP, SP, R4 @ Unadjust stack + POP {R4} @ Restore R4 + MSR SPSR_cxsf,R4 @ Restore SPSR + +SVC_Done: + PUSH {R0-R3,R12,LR} + + PUSH {R4} @ Push R4 so we can use it as a temp + AND R4, SP, #4 @ Ensure stack is 8-byte aligned + SUB SP, SP, R4 @ Adjust stack + PUSH {R4, LR} @ Store stack adjustment and dummy LR + + CPSID i + BLX rt_tsk_unlock + + POP {R4, LR} @ Get stack adjustment & discard dummy LR + ADD SP, SP, R4 @ Unadjust stack + POP {R4} @ Restore R4 + + POP {R0-R3,R12,LR} + POP {R4} + RFEFD SP! @ Return from exception +@ } +@ #pragma pop + +@ #pragma push +@ #pragma arm +@ __asm void PendSV_Handler (U32 IRQn) { +PendSV_Handler: + .ARM + + .extern rt_tsk_lock + .extern IRQNestLevel @ Flag indicates whether inside an ISR, and the depth of nesting. 0 = not in ISR. + .extern seen_id0_active @ Flag used to workaround GIC 390 errata 733075 (set in startup_.s) + + ADD SP,SP,#8 @ fix up stack pointer (R0 has been pushed and will never be popped, R1 was pushed for stack alignment) + + @ Disable systick interrupts, then write EOIR. We want interrupts disabled before we enter the context switcher. + PUSH {R0, R1} + BLX rt_tsk_lock + POP {R0, R1} + LDR R1, =GICInterface_BASE + LDR R1, [R1, #0] + STR R0, [R1, #0x10] @ Write End Of Interrupt ID to GICC_EOIR + + @ If it was interrupt ID0, clear the seen flag, otherwise return as normal + CMP R0, #0 + LDREQ R1, =seen_id0_active + STREQB R0, [R1] @ Clear the seen flag, using R0 (which is 0), to save loading another register + + LDR R0, =IRQNestLevel @ Get address of nesting counter + LDR R1, [R0] + SUB R1, R1, #1 @ Decrement nesting counter + STR R1, [R0] + + BLX rt_pop_req + + POP {R1, LR} @ Get stack adjustment & discard dummy LR + ADD SP, SP, R1 @ Unadjust stack + + LDR R0,[SP,#24] + MSR SPSR_cxsf,R0 + POP {R0-R3,R12} @ Leave SPSR & LR on the stack + PUSH {R4} + B Sys_Switch +@ } +@ #pragma pop + + +@ #pragma push +@ #pragma arm +@ __asm void OS_Tick_Handler (U32 IRQn) { +OS_Tick_Handler: + .ARM + + .extern rt_tsk_lock + .extern IRQNestLevel @ Flag indicates whether inside an ISR, and the depth of nesting. 0 = not in ISR. + .extern seen_id0_active @ Flag used to workaround GIC 390 errata 733075 (set in startup_.s) + + ADD SP,SP,#8 @ fix up stack pointer (R0 has been pushed and will never be popped, R1 was pushed for stack alignment) + + @ Disable systick interrupts, then write EOIR. We want interrupts disabled before we enter the context switcher. + PUSH {R0, R1} + BLX rt_tsk_lock + POP {R0, R1} + LDR R1, =GICInterface_BASE + LDR R1, [R1, #0] + STR R0, [R1, #0x10] @ Write End Of Interrupt ID to GICC_EOIR + + @ If it was interrupt ID0, clear the seen flag, otherwise return as normal + CMP R0, #0 + LDREQ R1, =seen_id0_active + STREQB R0, [R1] @ Clear the seen flag, using R0 (which is 0), to save loading another register + + LDR R0, =IRQNestLevel @ Get address of nesting counter + LDR R1, [R0] + SUB R1, R1, #1 @ Decrement nesting counter + STR R1, [R0] + + BLX os_tick_irqack + BLX rt_systick + + POP {R1, LR} @ Get stack adjustment & discard dummy LR + ADD SP, SP, R1 @ Unadjust stack + + LDR R0,[SP,#24] + MSR SPSR_cxsf,R0 + POP {R0-R3,R12} @ Leave SPSR & LR on the stack + PUSH {R4} + B Sys_Switch +@ } +@ #pragma pop + + + .END +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ diff --git a/rtos/rtx/TARGET_CORTEX_A/TOOLCHAIN_GCC/SVC_Table.S b/rtos/rtx/TARGET_CORTEX_A/TOOLCHAIN_GCC/SVC_Table.S new file mode 100644 index 00000000000..d6962e16e03 --- /dev/null +++ b/rtos/rtx/TARGET_CORTEX_A/TOOLCHAIN_GCC/SVC_Table.S @@ -0,0 +1,57 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: SVC_TABLE.S + * Purpose: Pre-defined SVC Table + * Rev.: V4.70, with additions for Cortex-A + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2013 ARM Germany GmbH, 2014-2015 ARM Ltd + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + + + .section SVC_TABLE @, CODE, READONLY + + .global SVC_Count + +.EQU SVC_Cnt, (SVC_End-SVC_Table)/4 +SVC_Count: .word SVC_Cnt + +@ Import user SVC functions here. +@ .extern __SVC_1 + + .global SVC_Table +SVC_Table: +@ Insert user SVC functions here. SVC 0 used by RTX Kernel. +@ .word __SVC_1 @ EnableCaches + +SVC_End: + + .END + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ diff --git a/rtos/rtx/TARGET_CORTEX_A/TOOLCHAIN_IAR/HAL_CA9.c b/rtos/rtx/TARGET_CORTEX_A/TOOLCHAIN_IAR/HAL_CA9.c new file mode 100644 index 00000000000..b12326ab231 --- /dev/null +++ b/rtos/rtx/TARGET_CORTEX_A/TOOLCHAIN_IAR/HAL_CA9.c @@ -0,0 +1,46 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: HAL_CA9.c + * Purpose: Hardware Abstraction Layer for Cortex-A9 + * Rev.: 23 March 2015 + *---------------------------------------------------------------------------- + * + * Copyright (c) 2012 - 2015 ARM Limited + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + +//unsigned char seen_id0_active = 0; // single byte to hold a flag used in the workaround for GIC errata 733075 + + +/*---------------------------------------------------------------------------- + * Functions + *---------------------------------------------------------------------------*/ + +/* Functions move to HAL_CA9_asm.S */ + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ diff --git a/rtos/rtx/TARGET_CORTEX_A/TOOLCHAIN_IAR/HAL_CA9_asm.s b/rtos/rtx/TARGET_CORTEX_A/TOOLCHAIN_IAR/HAL_CA9_asm.s new file mode 100644 index 00000000000..74b6398fcaf --- /dev/null +++ b/rtos/rtx/TARGET_CORTEX_A/TOOLCHAIN_IAR/HAL_CA9_asm.s @@ -0,0 +1,480 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: HAL_CA9.c + * Purpose: Hardware Abstraction Layer for Cortex-A9 + * Rev.: 8 April 2015 + *---------------------------------------------------------------------------- + * + * Copyright (c) 2012 - 2015 ARM Limited + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + + PUBLIC rt_set_PSP + PUBLIC rt_get_PSP + PUBLIC _alloc_box + PUBLIC _free_box + PUBLIC SWI_Handler + PUBLIC PendSV_Handler + PUBLIC OS_Tick_Handler + +/* macro defines form rt_HAL_CA.h */ +#define CPSR_T_BIT 0x20 +#define CPSR_I_BIT 0x80 +#define CPSR_F_BIT 0x40 + +#define MODE_USR 0x10 +#define MODE_FIQ 0x11 +#define MODE_IRQ 0x12 +#define MODE_SVC 0x13 +#define MODE_ABT 0x17 +#define MODE_UND 0x1B +#define MODE_SYS 0x1F + +/* macro defines form rt_TypeDef.h */ +#define TCB_TID 3 /* 'task id' offset */ +#define TCB_STACKF 37 /* 'stack_frame' offset */ +#ifndef __LARGE_PRIV_STACK +#define TCB_TSTACK 40 /* 'tsk_stack' offset */ +#else +#define TCB_TSTACK 44 /* 'tsk_stack' offset for LARGE_STACK */ +#endif + + + IMPORT rt_alloc_box + IMPORT rt_free_box + IMPORT os_tsk + IMPORT GICInterface_BASE + IMPORT rt_pop_req + IMPORT os_tick_irqack + IMPORT rt_systick + + SECTION `.text`:CODE:ROOT(2) + +/*---------------------------------------------------------------------------- + * Functions + *---------------------------------------------------------------------------*/ + +//For A-class, set USR/SYS stack +//__asm void rt_set_PSP (U32 stack) { +rt_set_PSP: + ARM + + MRS R1, CPSR + CPS #MODE_SYS ;no effect in USR mode + ISB + MOV SP, R0 + MSR CPSR_c, R1 ;no effect in USR mode + ISB + BX LR + +//} + +//For A-class, get USR/SYS stack +//__asm U32 rt_get_PSP (void) { +rt_get_PSP: + ARM + + MRS R1, CPSR + CPS #MODE_SYS ;no effect in USR mode + ISB + MOV R0, SP + MSR CPSR_c, R1 ;no effect in USR mode + ISB + BX LR +//} + +/*--------------------------- _alloc_box ------------------------------------*/ +//__asm void *_alloc_box (void *box_mem) { +_alloc_box: + /* Function wrapper for Unprivileged/Privileged mode. */ + ARM + + LDR R12,=(rt_alloc_box) + MRS R2, CPSR + LSLS R2, R2,#28 + BXNE R12 + SVC 0 + BX LR +//} + + +/*--------------------------- _free_box -------------------------------------*/ +//__asm U32 _free_box (void *box_mem, void *box) { +_free_box: + /* Function wrapper for Unprivileged/Privileged mode. */ + + LDR R12,=(rt_free_box) + MRS R2, CPSR + LSLS R2, R2,#28 + BXNE R12 + SVC 0 + BX LR + +//} + +/*-------------------------- SWI_Handler -----------------------------------*/ + +//#pragma push +//#pragma arm +//__asm void SWI_Handler (void) { +SWI_Handler: + PRESERVE8 + ARM + + IMPORT rt_tsk_lock + IMPORT rt_tsk_unlock + IMPORT SVC_Count + IMPORT SVC_Table + IMPORT rt_stk_check + IMPORT FPUEnable + IMPORT scheduler_suspended ; flag set by rt_suspend, cleared by rt_resume, read by SWI_Handler + +Mode_SVC EQU 0x13 + + SRSDB #Mode_SVC! ; Push LR_SVC and SPRS_SVC onto SVC mode stack + STR R4,[SP,#-0x4]! ; Push R4 so we can use it as a temp + + MRS R4,SPSR ; Get SPSR + TST R4,#CPSR_T_BIT ; Check Thumb Bit + LDRNEH R4,[LR,#-2] ; Thumb: Load Halfword + BICNE R4,R4,#0xFF00 ; Extract SVC Number + LDREQ R4,[LR,#-4] ; ARM: Load Word + BICEQ R4,R4,#0xFF000000 ; Extract SVC Number + + /* Lock out systick and re-enable interrupts */ + STMDB SP!,{R0-R3,R12,LR} + + AND R12, SP, #4 ; Ensure stack is 8-byte aligned + SUB SP, SP, R12 ; Adjust stack + STMDB SP!,{R12, LR} ; Store stack adjustment and dummy LR to SVC stack + + BLX rt_tsk_lock + CPSIE i + + LDMIA SP!,{R12,LR} ; Get stack adjustment & discard dummy LR + ADD SP, SP, R12 ; Unadjust stack + + LDMIA SP!,{R0-R3,R12,LR} + + CMP R4,#0 + BNE SVC_User + + MRS R4,SPSR + STR R4,[SP,#-0x4]! ; Push R4 so we can use it as a temp + AND R4, SP, #4 ; Ensure stack is 8-byte aligned + SUB SP, SP, R4 ; Adjust stack + STMDB SP!,{R4, LR} ; Store stack adjustment and dummy LR + BLX R12 + LDMIA SP!,{R4, LR} ; Get stack adjustment & discard dummy LR + ADD SP, SP, R4 ; Unadjust stack + LDR R4,[SP],#0x4 ; Restore R4 + MSR SPSR_CXSF,R4 + + /* Here we will be in SVC mode (even if coming in from PendSV_Handler or OS_Tick_Handler) */ +Sys_Switch: + LDR LR,=(os_tsk) + LDMIA LR,{R4,LR} ; os_tsk.run, os_tsk.new + CMP R4,LR + BNE switching + + STMDB SP!,{R0-R3,R12,LR} + + AND R12, SP, #4 ; Ensure stack is 8-byte aligned + SUB SP, SP, R12 ; Adjust stack + STMDB SP!,{R12,LR} ; Store stack adjustment and dummy LR to SVC stack + + CPSID i + ; Do not unlock scheduler if it has just been suspended by rt_suspend() + LDR R1,=scheduler_suspended + LDRB R0, [R1] + CMP R0, #1 + BEQ dont_unlock + BLX rt_tsk_unlock +dont_unlock: + + LDMIA SP!,{R12,LR} ; Get stack adjustment & discard dummy LR + ADD SP, SP, R12 ; Unadjust stack + + LDMIA SP!,{R0-R3,R12,LR} + LDR R4,[SP],#0x4 + RFEFD SP! ; Return from exception, no task switch + +switching: + CLREX + CMP R4,#0 + ADDEQ SP,SP,#12 ; Original R4, LR & SPSR do not need to be popped when we are paging in a different task + BEQ SVC_Next ; Runtask deleted? + + + STMDB SP!,{R8-R11} //R4 and LR already stacked + MOV R10,R4 ; Preserve os_tsk.run + MOV R11,LR ; Preserve os_tsk.new + + ADD R8,SP,#16 ; Unstack R4,LR + LDMIA R8,{R4,LR} + + SUB SP,SP,#4 ; Make space on the stack for the next instn + STMIA SP,{SP}^ ; Put User SP onto stack + LDR R8,[SP],#0x4 ; Pop User SP into R8 + + MRS R9,SPSR + STMDB R8!,{R9} ; User CPSR + STMDB R8!,{LR} ; User PC + STMDB R8,{LR}^ ; User LR + SUB R8,R8,#4 ; No writeback for store of User LR + STMDB R8!,{R0-R3,R12} ; User R0-R3,R12 + MOV R3,R10 ; os_tsk.run + MOV LR,R11 ; os_tsk.new + LDMIA SP!,{R9-R12} + ADD SP,SP,#12 ; Fix up SP for unstack of R4, LR & SPSR + STMDB R8!,{R4-R7,R9-R12} ; User R4-R11 + + //If applicable, stack VFP/NEON state + MRC p15,0,R1,c1,c0,2 ; VFP/NEON access enabled? (CPACR) + AND R2,R1,#0x00F00000 + CMP R2,#0x00F00000 + BNE no_outgoing_vfp + VMRS R2,FPSCR + STMDB R8!,{R2,R4} ; Push FPSCR, maintain 8-byte alignment + //IF {TARGET_FEATURE_EXTENSION_REGISTER_COUNT} == 32 + VSTMDB R8!,{D0-D15} + VSTMDB R8!,{D16-D31} + LDRB R2,[R3,#TCB_STACKF] ; Record in TCB that NEON/D32 state is stacked + ORR R2,R2,#4 + STRB R2,[R3,#TCB_STACKF] + //ENDIF + +no_outgoing_vfp: + STR R8,[R3,#TCB_TSTACK] + MOV R4,LR + + STR R4,[SP,#-0x4]! ; Push R4 so we can use it as a temp + AND R4, SP, #4 ; Ensure stack is 8-byte aligned + SUB SP, SP, R4 ; Adjust stack + STMDB SP!,{R4, LR} ; Store stack adjustment and dummy LR to SVC stack + + BLX rt_stk_check + + LDMIA SP!,{R4, LR} ; Get stack adjustment & discard dummy LR + ADD SP, SP, R4 ; Unadjust stack + LDR R4,[SP],#0x4 ; Restore R4 + + MOV LR,R4 + +SVC_Next: //R4 == os_tsk.run, LR == os_tsk.new, R0-R3, R5-R12 corruptible + LDR R1,=(os_tsk) ; os_tsk.run = os_tsk.new + STR LR,[R1] + LDRB R1,[LR,#TCB_TID] ; os_tsk.run->task_id + LSL R1,R1,#8 ; Store PROCID + MCR p15,0,R1,c13,c0,1 ; Write CONTEXTIDR + + LDR R0,[LR,#TCB_TSTACK] ; os_tsk.run->tsk_stack + + //Does incoming task have VFP/NEON state in stack? + LDRB R3,[LR,#TCB_STACKF] + ANDS R3, R3, #0x6 + MRC p15,0,R1,c1,c0,2 ; Read CPACR + BICEQ R1,R1,#0x00F00000 ; Disable VFP/NEON access if incoming task does not have stacked VFP/NEON state + ORRNE R1,R1,#0x00F00000 ; Enable VFP/NEON access if incoming task does have stacked VFP/NEON state + MCR p15,0,R1,c1,c0,2 ; Write CPACR + BEQ no_incoming_vfp + ISB ; We only need the sync if we enabled, otherwise we will context switch before next VFP/NEON instruction anyway + //IF {TARGET_FEATURE_EXTENSION_REGISTER_COUNT} == 32 + VLDMIA R0!,{D16-D31} + //ENDIF + VLDMIA R0!,{D0-D15} + LDR R2,[R0] + VMSR FPSCR,R2 + ADD R0,R0,#8 + +no_incoming_vfp: + LDR R1,[R0,#60] ; Restore User CPSR + MSR SPSR_CXSF,R1 + LDMIA R0!,{R4-R11} ; Restore User R4-R11 + ADD R0,R0,#4 ; Restore User R1-R3,R12 + LDMIA R0!,{R1-R3,R12} + LDMIA R0,{LR}^ ; Restore User LR + ADD R0,R0,#4 ; No writeback for load to user LR + LDMIA R0!,{LR} ; Restore User PC + ADD R0,R0,#4 ; Correct User SP for unstacked user CPSR + + STR R0,[SP,#-0x4]! ; Push R0 onto stack + LDMIA SP,{SP}^ ; Get R0 off stack into User SP + ADD SP,SP,#4 ; Put SP back + + LDR R0,[R0,#-32] ; Restore R0 + + STMDB SP!,{R0-R3,R12,LR} + + AND R12, SP, #4 ; Ensure stack is 8-byte aligned + SUB SP, SP, R12 ; Adjust stack + STMDB sp!,{R12, LR} ; Store stack adjustment and dummy LR to SVC stack + + CPSID i + BLX rt_tsk_unlock + + LDMIA sp!,{R12, LR} ; Get stack adjustment & discard dummy LR + ADD SP, SP, R12 ; Unadjust stack + + LDMIA SP!,{R0-R3,R12,LR} + + MOVS PC,LR ; Return from exception + + + /*------------------- User SVC -------------------------------*/ + +SVC_User: + LDR R12,=SVC_Count + LDR R12,[R12] + CMP R4,R12 ; Check for overflow + BHI SVC_Done + + LDR R12,=SVC_Table-4 + LDR R12,[R12,R4,LSL #2] ; Load SVC Function Address + MRS R4,SPSR ; Save SPSR + STR R4,[SP,#-0x4]! ; Push R4 so we can use it as a temp + AND R4, SP, #4 ; Ensure stack is 8-byte aligned + SUB SP, SP, R4 ; Adjust stack + STMDB SP!,{R4, LR} ; Store stack adjustment and dummy LR + BLX R12 ; Call SVC Function + LDMIA SP!,{R4, LR} ; Get stack adjustment & discard dummy LR + ADD SP, SP, R4 ; Unadjust stack + LDR R4,[SP],#0x4 ; Restore R4 + MSR SPSR_CXSF,R4 ; Restore SPSR + +SVC_Done: + STMDB sp!,{R0-R3,R12,LR} + + STR R4,[sp,#-0x4]! ; Push R4 so we can use it as a temp + AND R4, SP, #4 ; Ensure stack is 8-byte aligned + SUB SP, SP, R4 ; Adjust stack + STMDB SP!,{R4, LR} ; Store stack adjustment and dummy LR + + CPSID i + BLX rt_tsk_unlock + + LDMIA SP!,{R4, LR} ; Get stack adjustment & discard dummy LR + ADD SP, SP, R4 ; Unadjust stack + LDR R4,[SP],#0x4 ; Restore R4 + + LDMIA SP!,{R0-R3,R12,LR} + LDR R4,[SP],#0x4 + RFEFD SP! ; Return from exception +//} +//#pragma pop + +//#pragma push +//#pragma arm +//__asm void PendSV_Handler (U32 IRQn) { +PendSV_Handler: + ARM + + IMPORT rt_tsk_lock + IMPORT IRQNestLevel ; Flag indicates whether inside an ISR, and the depth of nesting. 0 = not in ISR. + IMPORT seen_id0_active ; Flag used to workaround GIC 390 errata 733075 - set in startup_Renesas_RZ_A1.s + + ADD SP,SP,#8 //fix up stack pointer (R0 has been pushed and will never be popped, R1 was pushed for stack alignment) + + //Disable systick interrupts, then write EOIR. We want interrupts disabled before we enter the context switcher. + STMDB SP!,{R0, R1} + BLX rt_tsk_lock + LDMIA SP!,{R0, R1} + LDR R1,=(GICInterface_BASE) + LDR R1, [R1, #0] + STR R0, [R1, #0x10] + + ; If it was interrupt ID0, clear the seen flag, otherwise return as normal + CMP R0, #0 + LDREQ R1, =seen_id0_active + STRBEQ R0, [R1] ; Clear the seen flag, using R0 (which is 0), to save loading another register + + LDR R0, =IRQNestLevel ; Get address of nesting counter + LDR R1, [R0] + SUB R1, R1, #1 ; Decrement nesting counter + STR R1, [R0] + + BLX (rt_pop_req) + + LDMIA SP!,{R1, LR} ; Get stack adjustment & discard dummy LR + ADD SP, SP, R1 ; Unadjust stack + + LDR R0,[SP,#24] + MSR SPSR_CXSF,R0 + LDMIA SP!,{R0-R3,R12} ; Leave SPSR & LR on the stack + STR R4,[SP,#-0x4]! + B Sys_Switch +//} +//#pragma pop + + +//#pragma push +//#pragma arm +//__asm void OS_Tick_Handler (U32 IRQn) { +OS_Tick_Handler: + ARM + + IMPORT rt_tsk_lock + IMPORT IRQNestLevel ; Flag indicates whether inside an ISR, and the depth of nesting. 0 = not in ISR. + IMPORT seen_id0_active ; Flag used to workaround GIC 390 errata 733075 - set in startup_Renesas_RZ_A1.s + + ADD SP,SP,#8 //fix up stack pointer (R0 has been pushed and will never be popped, R1 was pushed for stack alignment) + + STMDB SP!,{R0, R1} + BLX rt_tsk_lock + LDMIA SP!,{R0, R1} + LDR R1, =(GICInterface_BASE) + LDR R1, [R1, #0] + STR R0, [R1, #0x10] + + ; If it was interrupt ID0, clear the seen flag, otherwise return as normal + CMP R0, #0 + LDREQ R1, =seen_id0_active + STRBEQ R0, [R1] ; Clear the seen flag, using R0 (which is 0), to save loading another register + + LDR R0, =IRQNestLevel ; Get address of nesting counter + LDR R1, [R0] + SUB R1, R1, #1 ; Decrement nesting counter + STR R1, [R0] + + BLX (os_tick_irqack) + BLX (rt_systick) + + LDMIA SP!,{R1, LR} ; Get stack adjustment & discard dummy LR + ADD SP, SP, R1 ; Unadjust stack + + LDR R0,[SP,#24] + MSR SPSR_CXSF,R0 + LDMIA SP!,{R0-R3,R12} ; Leave SPSR & LR on the stack + STR R4,[SP,#-0x4]! + B Sys_Switch +//} +//#pragma pop + + + END +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ diff --git a/rtos/rtx/TARGET_CORTEX_A/TOOLCHAIN_IAR/SVC_Table.S b/rtos/rtx/TARGET_CORTEX_A/TOOLCHAIN_IAR/SVC_Table.S new file mode 100644 index 00000000000..b7f2cc8bdb6 --- /dev/null +++ b/rtos/rtx/TARGET_CORTEX_A/TOOLCHAIN_IAR/SVC_Table.S @@ -0,0 +1,57 @@ +;/*---------------------------------------------------------------------------- +; * RL-ARM - RTX +; *---------------------------------------------------------------------------- +; * Name: SVC_TABLE.S +; * Purpose: Pre-defined SVC Table for Cortex-M +; * Rev.: V4.70 +; *---------------------------------------------------------------------------- +; * +; * Copyright (c) 1999-2009 KEIL, 2009-2013 ARM Germany GmbH +; * All rights reserved. +; * Redistribution and use in source and binary forms, with or without +; * modification, are permitted provided that the following conditions are met: +; * - Redistributions of source code must retain the above copyright +; * notice, this list of conditions and the following disclaimer. +; * - Redistributions in binary form must reproduce the above copyright +; * notice, this list of conditions and the following disclaimer in the +; * documentation and/or other materials provided with the distribution. +; * - Neither the name of ARM nor the names of its contributors may be used +; * to endorse or promote products derived from this software without +; * specific prior written permission. +; * +; * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +; * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +; * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +; * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE +; * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +; * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +; * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +; * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +; * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +; * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +; * POSSIBILITY OF SUCH DAMAGE. +; *---------------------------------------------------------------------------*/ + + + SECTION SVC_TABLE:CODE:ROOT(2) + + EXPORT SVC_Count + +SVC_Cnt EQU (SVC_End-SVC_Table)/4 +SVC_Count DCD SVC_Cnt + +; Import user SVC functions here. +; IMPORT __SVC_1 + + EXPORT SVC_Table +SVC_Table +; Insert user SVC functions here. SVC 0 used by RTL Kernel. +; DCD __SVC_1 ; InitMemorySubsystem + +SVC_End + + END + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ diff --git a/rtos/rtx/TARGET_CORTEX_A/cmsis_os.h b/rtos/rtx/TARGET_CORTEX_A/cmsis_os.h new file mode 100644 index 00000000000..f4a4bb3b255 --- /dev/null +++ b/rtos/rtx/TARGET_CORTEX_A/cmsis_os.h @@ -0,0 +1,716 @@ +/* ---------------------------------------------------------------------- + * $Date: 5. February 2013 + * $Revision: V1.02 + * + * Project: CMSIS-RTOS API + * Title: cmsis_os.h RTX header file + * + * Version 0.02 + * Initial Proposal Phase + * Version 0.03 + * osKernelStart added, optional feature: main started as thread + * osSemaphores have standard behavior + * osTimerCreate does not start the timer, added osTimerStart + * osThreadPass is renamed to osThreadYield + * Version 1.01 + * Support for C++ interface + * - const attribute removed from the osXxxxDef_t typedef's + * - const attribute added to the osXxxxDef macros + * Added: osTimerDelete, osMutexDelete, osSemaphoreDelete + * Added: osKernelInitialize + * Version 1.02 + * Control functions for short timeouts in microsecond resolution: + * Added: osKernelSysTick, osKernelSysTickFrequency, osKernelSysTickMicroSec + * Removed: osSignalGet + *---------------------------------------------------------------------------- + * + * Copyright (c) 2013 ARM LIMITED + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + + +#ifndef _CMSIS_OS_H +#define _CMSIS_OS_H + +#define osCMSIS 0x10002U ///< CMSIS-RTOS API version (main [31:16] .sub [15:0]) + +#define osCMSIS_RTX ((4<<16)|80) ///< RTOS identification and version (main [31:16] .sub [15:0]) + +#define osKernelSystemId "RTX V4.80" ///< RTOS identification string + +#define CMSIS_OS_RTX +#define CMSIS_OS_RTX_CA /* new define for Coretex-A */ + +// The stack space occupied is mainly dependent on the underling C standard library +#if defined(TOOLCHAIN_GCC) || defined(TOOLCHAIN_ARM_STD) || defined(TOOLCHAIN_IAR) +# define WORDS_STACK_SIZE 512 +#elif defined(TOOLCHAIN_ARM_MICRO) +# define WORDS_STACK_SIZE 128 +#endif + +#define DEFAULT_STACK_SIZE (WORDS_STACK_SIZE*4) + +#define osFeature_MainThread 1 ///< main can be thread +#define osFeature_Pool 1 ///< Memory Pools available +#define osFeature_MailQ 1 ///< Mail Queues available +#define osFeature_MessageQ 1 ///< Message Queues available +#define osFeature_Signals 16 ///< 16 Signal Flags available per thread +#define osFeature_Semaphore 65535 ///< Maximum count for \ref osSemaphoreCreate function +#define osFeature_Wait 0 ///< osWait not available +#define osFeature_SysTick 1 ///< osKernelSysTick functions available +#define osFeature_ThreadEnum 1 ///< Thread enumeration available + +#if defined (__CC_ARM) +#define os_InRegs __value_in_regs // Compiler specific: force struct in registers +#else +#define os_InRegs +#endif + +#include +#include + +#ifdef __cplusplus +extern "C" +{ +#endif + + +// ==== Enumeration, structures, defines ==== + +/// Priority used for thread control. +typedef enum { + osPriorityIdle = -3, ///< priority: idle (lowest) + osPriorityLow = -2, ///< priority: low + osPriorityBelowNormal = -1, ///< priority: below normal + osPriorityNormal = 0, ///< priority: normal (default) + osPriorityAboveNormal = +1, ///< priority: above normal + osPriorityHigh = +2, ///< priority: high + osPriorityRealtime = +3, ///< priority: realtime (highest) + osPriorityError = 0x84 ///< system cannot determine priority or thread has illegal priority +} osPriority; + +/// Timeout value. +#define osWaitForever 0xFFFFFFFFU ///< wait forever timeout value + +/// Status code values returned by CMSIS-RTOS functions. +typedef enum { + osOK = 0, ///< function completed; no error or event occurred. + osEventSignal = 0x08, ///< function completed; signal event occurred. + osEventMessage = 0x10, ///< function completed; message event occurred. + osEventMail = 0x20, ///< function completed; mail event occurred. + osEventTimeout = 0x40, ///< function completed; timeout occurred. + osErrorParameter = 0x80, ///< parameter error: a mandatory parameter was missing or specified an incorrect object. + osErrorResource = 0x81, ///< resource not available: a specified resource was not available. + osErrorTimeoutResource = 0xC1, ///< resource not available within given time: a specified resource was not available within the timeout period. + osErrorISR = 0x82, ///< not allowed in ISR context: the function cannot be called from interrupt service routines. + osErrorISRRecursive = 0x83, ///< function called multiple times from ISR with same object. + osErrorPriority = 0x84, ///< system cannot determine priority or thread has illegal priority. + osErrorNoMemory = 0x85, ///< system is out of memory: it was impossible to allocate or reserve memory for the operation. + osErrorValue = 0x86, ///< value of a parameter is out of range. + osErrorOS = 0xFF, ///< unspecified RTOS error: run-time error but no other error message fits. + os_status_reserved = 0x7FFFFFFF ///< prevent from enum down-size compiler optimization. +} osStatus; + + +/// Timer type value for the timer definition. +typedef enum { + osTimerOnce = 0, ///< one-shot timer + osTimerPeriodic = 1 ///< repeating timer +} os_timer_type; + +typedef enum { + osThreadInfoState, + osThreadInfoStackSize, + osThreadInfoStackMax, + osThreadInfoEntry, + osThreadInfoArg, + + osThreadInfo_reserved = 0x7FFFFFFF ///< prevent from enum down-size compiler optimization. +} osThreadInfo; + +/// Entry point of a thread. +typedef void (*os_pthread) (void const *argument); + +/// Entry point of a timer call back function. +typedef void (*os_ptimer) (void const *argument); + +// >>> the following data type definitions may shall adapted towards a specific RTOS + +/// Thread ID identifies the thread (pointer to a thread control block). +typedef struct os_thread_cb *osThreadId; + +/// Timer ID identifies the timer (pointer to a timer control block). +typedef struct os_timer_cb *osTimerId; + +/// Mutex ID identifies the mutex (pointer to a mutex control block). +typedef struct os_mutex_cb *osMutexId; + +/// Semaphore ID identifies the semaphore (pointer to a semaphore control block). +typedef struct os_semaphore_cb *osSemaphoreId; + +/// Pool ID identifies the memory pool (pointer to a memory pool control block). +typedef struct os_pool_cb *osPoolId; + +/// Message ID identifies the message queue (pointer to a message queue control block). +typedef struct os_messageQ_cb *osMessageQId; + +/// Mail ID identifies the mail queue (pointer to a mail queue control block). +typedef struct os_mailQ_cb *osMailQId; + +/// Thread enumeration ID identifies the enumeration (pointer to a thread enumeration control block). +typedef uint32_t *osThreadEnumId; + +/// Thread Definition structure contains startup information of a thread. +typedef struct os_thread_def { + os_pthread pthread; ///< start address of thread function + osPriority tpriority; ///< initial thread priority + uint32_t instances; ///< maximum number of instances of that thread function + uint32_t stacksize; ///< stack size requirements in bytes; 0 is default stack size +#ifdef __MBED_CMSIS_RTOS_CA9 + uint32_t *stack_pointer; ///< pointer to the stack memory block +#endif +} osThreadDef_t; + +/// Timer Definition structure contains timer parameters. +typedef struct os_timer_def { + os_ptimer ptimer; ///< start address of a timer function + void *timer; ///< pointer to internal data +} osTimerDef_t; + +/// Mutex Definition structure contains setup information for a mutex. +typedef struct os_mutex_def { + void *mutex; ///< pointer to internal data +} osMutexDef_t; + +/// Semaphore Definition structure contains setup information for a semaphore. +typedef struct os_semaphore_def { + void *semaphore; ///< pointer to internal data +} osSemaphoreDef_t; + +/// Definition structure for memory block allocation. +typedef struct os_pool_def { + uint32_t pool_sz; ///< number of items (elements) in the pool + uint32_t item_sz; ///< size of an item + void *pool; ///< pointer to memory for pool +} osPoolDef_t; + +/// Definition structure for message queue. +typedef struct os_messageQ_def { + uint32_t queue_sz; ///< number of elements in the queue + void *pool; ///< memory array for messages +} osMessageQDef_t; + +/// Definition structure for mail queue. +typedef struct os_mailQ_def { + uint32_t queue_sz; ///< number of elements in the queue + uint32_t item_sz; ///< size of an item + void *pool; ///< memory array for mail +} osMailQDef_t; + +/// Event structure contains detailed information about an event. +typedef struct { + osStatus status; ///< status code: event or error information + union { + uint32_t v; ///< message as 32-bit value + void *p; ///< message or mail as void pointer + int32_t signals; ///< signal flags + } value; ///< event value + union { + osMailQId mail_id; ///< mail id obtained by \ref osMailCreate + osMessageQId message_id; ///< message id obtained by \ref osMessageCreate + } def; ///< event definition +} osEvent; + + +// ==== Kernel Control Functions ==== + +/// Initialize the RTOS Kernel for creating objects. +/// \return status code that indicates the execution status of the function. +osStatus osKernelInitialize (void); + +/// Start the RTOS Kernel. +/// \return status code that indicates the execution status of the function. +osStatus osKernelStart (void); + +/// Check if the RTOS kernel is already started. +/// \return 0 RTOS is not started, 1 RTOS is started. +int32_t osKernelRunning(void); + +#if (defined (osFeature_SysTick) && (osFeature_SysTick != 0)) // System Timer available + +/// \cond INTERNAL_VARIABLES +extern uint32_t const os_tickfreq; +extern uint16_t const os_tickus_i; +extern uint16_t const os_tickus_f; +/// \endcond + +/// Get the RTOS kernel system timer counter. +/// \return RTOS kernel system timer as 32-bit value +uint32_t osKernelSysTick (void); + +/// The RTOS kernel system timer frequency in Hz. +/// \note Reflects the system timer setting and is typically defined in a configuration file. +#define osKernelSysTickFrequency os_tickfreq + +/// Convert a microseconds value to a RTOS kernel system timer value. +/// \param microsec time value in microseconds. +/// \return time value normalized to the \ref osKernelSysTickFrequency +/* +#define osKernelSysTickMicroSec(microsec) (((uint64_t)microsec * (osKernelSysTickFrequency)) / 1000000) +*/ +#define osKernelSysTickMicroSec(microsec) ((microsec * os_tickus_i) + ((microsec * os_tickus_f) >> 16)) + +#endif // System Timer available + +// ==== Thread Management ==== + +/// Create a Thread Definition with function, priority, and stack requirements. +/// \param name name of the thread function. +/// \param priority initial priority of the thread function. +/// \param instances number of possible thread instances. +/// \param stacksz stack size (in bytes) requirements for the thread function. +/// macro body is implementation specific in every CMSIS-RTOS. +#if defined (osObjectsExternal) // object is external +#define osThreadDef(name, priority, instances, stacksz) \ +extern const osThreadDef_t os_thread_def_##name +#else // define the object +#ifdef __MBED_CMSIS_RTOS_CA9 +#define osThreadDef(name, priority, stacksz) \ +uint32_t os_thread_def_stack_##name [stacksz / sizeof(uint32_t)]; \ +const osThreadDef_t os_thread_def_##name = \ +{ (name), (priority), 1, (stacksz), (os_thread_def_stack_##name) } +#else +#define osThreadDef(name, priority, instances, stacksz) \ +const osThreadDef_t os_thread_def_##name = \ +{ (name), (priority), (instances), (stacksz) } +#endif +#endif + +/// Access a Thread definition. +/// \param name name of the thread definition object. +/// macro body is implementation specific in every CMSIS-RTOS. +#define osThread(name) \ +&os_thread_def_##name + +/// Create a thread and add it to Active Threads and set it to state READY. +/// \param[in] thread_def thread definition referenced with \ref osThread. +/// \param[in] argument pointer that is passed to the thread function as start argument. +/// \return thread ID for reference by other functions or NULL in case of error. +osThreadId osThreadCreate (const osThreadDef_t *thread_def, void *argument); + +/// Return the thread ID of the current running thread. +/// \return thread ID for reference by other functions or NULL in case of error. +osThreadId osThreadGetId (void); + +/// Terminate execution of a thread and remove it from Active Threads. +/// \param[in] thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId. +/// \return status code that indicates the execution status of the function. +osStatus osThreadTerminate (osThreadId thread_id); + +/// Pass control to next thread that is in state \b READY. +/// \return status code that indicates the execution status of the function. +osStatus osThreadYield (void); + +/// Change priority of an active thread. +/// \param[in] thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId. +/// \param[in] priority new priority value for the thread function. +/// \return status code that indicates the execution status of the function. +osStatus osThreadSetPriority (osThreadId thread_id, osPriority priority); + +/// Get current priority of an active thread. +/// \param[in] thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId. +/// \return current priority value of the thread function. +osPriority osThreadGetPriority (osThreadId thread_id); + +#ifdef __MBED_CMSIS_RTOS_CA9 +/// Get current thread state. +uint8_t osThreadGetState (osThreadId thread_id); +#endif + +/// Get into from an active thread. +/// \param[in] thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId. +/// \param[in] info information to read. +/// \return current state of the thread function. +/// \return requested info that includes the status code. +os_InRegs osEvent _osThreadGetInfo(osThreadId thread_id, osThreadInfo info); + +// ==== Generic Wait Functions ==== + +/// Wait for Timeout (Time Delay). +/// \param[in] millisec \ref CMSIS_RTOS_TimeOutValue "Time delay" value +/// \return status code that indicates the execution status of the function. +osStatus osDelay (uint32_t millisec); + +#if (defined (osFeature_Wait) && (osFeature_Wait != 0)) // Generic Wait available + +/// Wait for Signal, Message, Mail, or Timeout. +/// \param[in] millisec \ref CMSIS_RTOS_TimeOutValue or 0 in case of no time-out +/// \return event that contains signal, message, or mail information or error code. +os_InRegs osEvent osWait (uint32_t millisec); + +#endif // Generic Wait available + + +// ==== Timer Management Functions ==== +/// Define a Timer object. +/// \param name name of the timer object. +/// \param function name of the timer call back function. +#if defined (osObjectsExternal) // object is external +#define osTimerDef(name, function) \ +extern const osTimerDef_t os_timer_def_##name +#else // define the object +#define osTimerDef(name, function) \ +uint32_t os_timer_cb_##name[6]; \ +const osTimerDef_t os_timer_def_##name = \ +{ (function), (os_timer_cb_##name) } +#endif + +/// Access a Timer definition. +/// \param name name of the timer object. +#define osTimer(name) \ +&os_timer_def_##name + +/// Create a timer. +/// \param[in] timer_def timer object referenced with \ref osTimer. +/// \param[in] type osTimerOnce for one-shot or osTimerPeriodic for periodic behavior. +/// \param[in] argument argument to the timer call back function. +/// \return timer ID for reference by other functions or NULL in case of error. +osTimerId osTimerCreate (const osTimerDef_t *timer_def, os_timer_type type, void *argument); + +/// Start or restart a timer. +/// \param[in] timer_id timer ID obtained by \ref osTimerCreate. +/// \param[in] millisec \ref CMSIS_RTOS_TimeOutValue "Time delay" value of the timer. +/// \return status code that indicates the execution status of the function. +osStatus osTimerStart (osTimerId timer_id, uint32_t millisec); + +/// Stop the timer. +/// \param[in] timer_id timer ID obtained by \ref osTimerCreate. +/// \return status code that indicates the execution status of the function. +osStatus osTimerStop (osTimerId timer_id); + +/// Delete a timer that was created by \ref osTimerCreate. +/// \param[in] timer_id timer ID obtained by \ref osTimerCreate. +/// \return status code that indicates the execution status of the function. +osStatus osTimerDelete (osTimerId timer_id); + + +// ==== Signal Management ==== + +/// Set the specified Signal Flags of an active thread. +/// \param[in] thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId. +/// \param[in] signals specifies the signal flags of the thread that should be set. +/// \return previous signal flags of the specified thread or 0x80000000 in case of incorrect parameters. +int32_t osSignalSet (osThreadId thread_id, int32_t signals); + +/// Clear the specified Signal Flags of an active thread. +/// \param[in] thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId. +/// \param[in] signals specifies the signal flags of the thread that shall be cleared. +/// \return previous signal flags of the specified thread or 0x80000000 in case of incorrect parameters or call from ISR. +int32_t osSignalClear (osThreadId thread_id, int32_t signals); + +/// Wait for one or more Signal Flags to become signaled for the current \b RUNNING thread. +/// \param[in] signals wait until all specified signal flags set or 0 for any single signal flag. +/// \param[in] millisec \ref CMSIS_RTOS_TimeOutValue or 0 in case of no time-out. +/// \return event flag information or error code. +os_InRegs osEvent osSignalWait (int32_t signals, uint32_t millisec); + + +// ==== Mutex Management ==== + +/// Define a Mutex. +/// \param name name of the mutex object. +#if defined (osObjectsExternal) // object is external +#define osMutexDef(name) \ +extern const osMutexDef_t os_mutex_def_##name +#else // define the object +#define osMutexDef(name) \ +uint32_t os_mutex_cb_##name[4] = { 0 }; \ +const osMutexDef_t os_mutex_def_##name = { (os_mutex_cb_##name) } +#endif + +/// Access a Mutex definition. +/// \param name name of the mutex object. +#define osMutex(name) \ +&os_mutex_def_##name + +/// Create and Initialize a Mutex object. +/// \param[in] mutex_def mutex definition referenced with \ref osMutex. +/// \return mutex ID for reference by other functions or NULL in case of error. +osMutexId osMutexCreate (const osMutexDef_t *mutex_def); + +/// Wait until a Mutex becomes available. +/// \param[in] mutex_id mutex ID obtained by \ref osMutexCreate. +/// \param[in] millisec \ref CMSIS_RTOS_TimeOutValue or 0 in case of no time-out. +/// \return status code that indicates the execution status of the function. +osStatus osMutexWait (osMutexId mutex_id, uint32_t millisec); + +/// Release a Mutex that was obtained by \ref osMutexWait. +/// \param[in] mutex_id mutex ID obtained by \ref osMutexCreate. +/// \return status code that indicates the execution status of the function. +osStatus osMutexRelease (osMutexId mutex_id); + +/// Delete a Mutex that was created by \ref osMutexCreate. +/// \param[in] mutex_id mutex ID obtained by \ref osMutexCreate. +/// \return status code that indicates the execution status of the function. +osStatus osMutexDelete (osMutexId mutex_id); + + +// ==== Semaphore Management Functions ==== + +#if (defined (osFeature_Semaphore) && (osFeature_Semaphore != 0)) // Semaphore available + +/// Define a Semaphore object. +/// \param name name of the semaphore object. +#if defined (osObjectsExternal) // object is external +#define osSemaphoreDef(name) \ +extern const osSemaphoreDef_t os_semaphore_def_##name +#else // define the object +#define osSemaphoreDef(name) \ +uint32_t os_semaphore_cb_##name[2] = { 0 }; \ +const osSemaphoreDef_t os_semaphore_def_##name = { (os_semaphore_cb_##name) } +#endif + +/// Access a Semaphore definition. +/// \param name name of the semaphore object. +#define osSemaphore(name) \ +&os_semaphore_def_##name + +/// Create and Initialize a Semaphore object used for managing resources. +/// \param[in] semaphore_def semaphore definition referenced with \ref osSemaphore. +/// \param[in] count number of available resources. +/// \return semaphore ID for reference by other functions or NULL in case of error. +osSemaphoreId osSemaphoreCreate (const osSemaphoreDef_t *semaphore_def, int32_t count); + +/// Wait until a Semaphore token becomes available. +/// \param[in] semaphore_id semaphore object referenced with \ref osSemaphoreCreate. +/// \param[in] millisec \ref CMSIS_RTOS_TimeOutValue or 0 in case of no time-out. +/// \return number of available tokens, or -1 in case of incorrect parameters. +int32_t osSemaphoreWait (osSemaphoreId semaphore_id, uint32_t millisec); + +/// Release a Semaphore token. +/// \param[in] semaphore_id semaphore object referenced with \ref osSemaphoreCreate. +/// \return status code that indicates the execution status of the function. +osStatus osSemaphoreRelease (osSemaphoreId semaphore_id); + +/// Delete a Semaphore that was created by \ref osSemaphoreCreate. +/// \param[in] semaphore_id semaphore object referenced with \ref osSemaphoreCreate. +/// \return status code that indicates the execution status of the function. +osStatus osSemaphoreDelete (osSemaphoreId semaphore_id); + +#endif // Semaphore available + + +// ==== Memory Pool Management Functions ==== + +#if (defined (osFeature_Pool) && (osFeature_Pool != 0)) // Memory Pool Management available + +/// \brief Define a Memory Pool. +/// \param name name of the memory pool. +/// \param no maximum number of blocks (objects) in the memory pool. +/// \param type data type of a single block (object). +#if defined (osObjectsExternal) // object is external +#define osPoolDef(name, no, type) \ +extern const osPoolDef_t os_pool_def_##name +#else // define the object +#define osPoolDef(name, no, type) \ +uint32_t os_pool_m_##name[3+((sizeof(type)+3)/4)*(no)]; \ +const osPoolDef_t os_pool_def_##name = \ +{ (no), sizeof(type), (os_pool_m_##name) } +#endif + +/// \brief Access a Memory Pool definition. +/// \param name name of the memory pool +#define osPool(name) \ +&os_pool_def_##name + +/// Create and Initialize a memory pool. +/// \param[in] pool_def memory pool definition referenced with \ref osPool. +/// \return memory pool ID for reference by other functions or NULL in case of error. +osPoolId osPoolCreate (const osPoolDef_t *pool_def); + +/// Allocate a memory block from a memory pool. +/// \param[in] pool_id memory pool ID obtain referenced with \ref osPoolCreate. +/// \return address of the allocated memory block or NULL in case of no memory available. +void *osPoolAlloc (osPoolId pool_id); + +/// Allocate a memory block from a memory pool and set memory block to zero. +/// \param[in] pool_id memory pool ID obtain referenced with \ref osPoolCreate. +/// \return address of the allocated memory block or NULL in case of no memory available. +void *osPoolCAlloc (osPoolId pool_id); + +/// Return an allocated memory block back to a specific memory pool. +/// \param[in] pool_id memory pool ID obtain referenced with \ref osPoolCreate. +/// \param[in] block address of the allocated memory block that is returned to the memory pool. +/// \return status code that indicates the execution status of the function. +osStatus osPoolFree (osPoolId pool_id, void *block); + +#endif // Memory Pool Management available + + +// ==== Message Queue Management Functions ==== + +#if (defined (osFeature_MessageQ) && (osFeature_MessageQ != 0)) // Message Queues available + +/// \brief Create a Message Queue Definition. +/// \param name name of the queue. +/// \param queue_sz maximum number of messages in the queue. +/// \param type data type of a single message element (for debugger). +#if defined (osObjectsExternal) // object is external +#define osMessageQDef(name, queue_sz, type) \ +extern const osMessageQDef_t os_messageQ_def_##name +#else // define the object +#define osMessageQDef(name, queue_sz, type) \ +uint32_t os_messageQ_q_##name[4+(queue_sz)] = { 0 }; \ +const osMessageQDef_t os_messageQ_def_##name = \ +{ (queue_sz), (os_messageQ_q_##name) } +#endif + +/// \brief Access a Message Queue Definition. +/// \param name name of the queue +#define osMessageQ(name) \ +&os_messageQ_def_##name + +/// Create and Initialize a Message Queue. +/// \param[in] queue_def queue definition referenced with \ref osMessageQ. +/// \param[in] thread_id thread ID (obtained by \ref osThreadCreate or \ref osThreadGetId) or NULL. +/// \return message queue ID for reference by other functions or NULL in case of error. +osMessageQId osMessageCreate (const osMessageQDef_t *queue_def, osThreadId thread_id); + +/// Put a Message to a Queue. +/// \param[in] queue_id message queue ID obtained with \ref osMessageCreate. +/// \param[in] info message information. +/// \param[in] millisec \ref CMSIS_RTOS_TimeOutValue or 0 in case of no time-out. +/// \return status code that indicates the execution status of the function. +osStatus osMessagePut (osMessageQId queue_id, uint32_t info, uint32_t millisec); + +/// Get a Message or Wait for a Message from a Queue. +/// \param[in] queue_id message queue ID obtained with \ref osMessageCreate. +/// \param[in] millisec \ref CMSIS_RTOS_TimeOutValue or 0 in case of no time-out. +/// \return event information that includes status code. +os_InRegs osEvent osMessageGet (osMessageQId queue_id, uint32_t millisec); + +#endif // Message Queues available + + +// ==== Mail Queue Management Functions ==== + +#if (defined (osFeature_MailQ) && (osFeature_MailQ != 0)) // Mail Queues available + +/// \brief Create a Mail Queue Definition. +/// \param name name of the queue +/// \param queue_sz maximum number of messages in queue +/// \param type data type of a single message element +#if defined (osObjectsExternal) // object is external +#define osMailQDef(name, queue_sz, type) \ +extern const osMailQDef_t os_mailQ_def_##name +#else // define the object +#define osMailQDef(name, queue_sz, type) \ +uint32_t os_mailQ_q_##name[4+(queue_sz)] = { 0 }; \ +uint32_t os_mailQ_m_##name[3+((sizeof(type)+3)/4)*(queue_sz)]; \ +void * os_mailQ_p_##name[2] = { (os_mailQ_q_##name), os_mailQ_m_##name }; \ +const osMailQDef_t os_mailQ_def_##name = \ +{ (queue_sz), sizeof(type), (os_mailQ_p_##name) } +#endif + +/// \brief Access a Mail Queue Definition. +/// \param name name of the queue +#define osMailQ(name) \ +&os_mailQ_def_##name + +/// Create and Initialize mail queue. +/// \param[in] queue_def reference to the mail queue definition obtain with \ref osMailQ +/// \param[in] thread_id thread ID (obtained by \ref osThreadCreate or \ref osThreadGetId) or NULL. +/// \return mail queue ID for reference by other functions or NULL in case of error. +osMailQId osMailCreate (const osMailQDef_t *queue_def, osThreadId thread_id); + +/// Allocate a memory block from a mail. +/// \param[in] queue_id mail queue ID obtained with \ref osMailCreate. +/// \param[in] millisec \ref CMSIS_RTOS_TimeOutValue or 0 in case of no time-out +/// \return pointer to memory block that can be filled with mail or NULL in case of error. +void *osMailAlloc (osMailQId queue_id, uint32_t millisec); + +/// Allocate a memory block from a mail and set memory block to zero. +/// \param[in] queue_id mail queue ID obtained with \ref osMailCreate. +/// \param[in] millisec \ref CMSIS_RTOS_TimeOutValue or 0 in case of no time-out +/// \return pointer to memory block that can be filled with mail or NULL in case of error. +void *osMailCAlloc (osMailQId queue_id, uint32_t millisec); + +/// Put a mail to a queue. +/// \param[in] queue_id mail queue ID obtained with \ref osMailCreate. +/// \param[in] mail memory block previously allocated with \ref osMailAlloc or \ref osMailCAlloc. +/// \return status code that indicates the execution status of the function. +osStatus osMailPut (osMailQId queue_id, void *mail); + +/// Get a mail from a queue. +/// \param[in] queue_id mail queue ID obtained with \ref osMailCreate. +/// \param[in] millisec \ref CMSIS_RTOS_TimeOutValue or 0 in case of no time-out +/// \return event that contains mail information or error code. +os_InRegs osEvent osMailGet (osMailQId queue_id, uint32_t millisec); + +/// Free a memory block from a mail. +/// \param[in] queue_id mail queue ID obtained with \ref osMailCreate. +/// \param[in] mail pointer to the memory block that was obtained with \ref osMailGet. +/// \return status code that indicates the execution status of the function. +osStatus osMailFree (osMailQId queue_id, void *mail); + +#endif // Mail Queues available + + +// ==== Thread Enumeration Functions ==== + +#if (defined (osFeature_ThreadEnum) && (osFeature_ThreadEnum != 0)) // Thread enumeration available + +/// Start a thread enumeration. +/// \return an enumeration ID or NULL on error. +osThreadEnumId _osThreadsEnumStart(void); + +/// Get the next task ID in the enumeration. +/// \return a thread ID or NULL on if the end of the enumeration has been reached. +osThreadId _osThreadEnumNext(osThreadEnumId enum_id); + +/// Free the enumeration structure. +/// \param[in] enum_id pointer to the enumeration ID that was obtained with \ref _osThreadsEnumStart. +/// \return status code that indicates the execution status of the function. +osStatus _osThreadEnumFree(osThreadEnumId enum_id); + +#endif // Thread Enumeration available + + +// ==== RTX Extensions ==== + +/// Suspend the RTX task scheduler. +/// \return number of ticks, for how long the system can sleep or power-down. +uint32_t os_suspend (void); + +/// Resume the RTX task scheduler +/// \param[in] sleep_time specifies how long the system was in sleep or power-down mode. +void os_resume (uint32_t sleep_time); + + +#ifdef __cplusplus +} +#endif + +#endif // _CMSIS_OS_H diff --git a/rtos/rtx/TARGET_CORTEX_A/rt_CMSIS.c b/rtos/rtx/TARGET_CORTEX_A/rt_CMSIS.c new file mode 100644 index 00000000000..82c7619dd87 --- /dev/null +++ b/rtos/rtx/TARGET_CORTEX_A/rt_CMSIS.c @@ -0,0 +1,2372 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: rt_CMSIS.c + * Purpose: CMSIS RTOS API + * Rev.: V4.80 plus changes for RTX-Ax + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 ARM Germany GmbH, 2012-2016 ARM Limited + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + +#define __CMSIS_GENERIC + +#if defined (__CORTEX_M4) || defined (__CORTEX_M4F) + #include "core_cm4.h" +#elif defined (__CORTEX_M3) + #include "core_cm3.h" +#elif defined (__CORTEX_M0) + #include "core_cm0.h" +#elif defined (__CORTEX_A9) + #include "core_ca9.h" +#else + #error "Missing __CORTEX_xx definition" +#endif + +#include "rt_TypeDef.h" +#include "RTX_Config.h" +#include "rt_System.h" +#include "rt_Task.h" +#include "rt_Event.h" +#include "rt_List.h" +#include "rt_Time.h" +#include "rt_Mutex.h" +#include "rt_Semaphore.h" +#include "rt_Mailbox.h" +#include "rt_MemBox.h" +#include "rt_Memory.h" +#include "rt_HAL_CM.h" + +#define os_thread_cb OS_TCB + +#include "cmsis_os.h" + +#if (osFeature_Signals != 16) +#error Invalid "osFeature_Signals" value! +#endif +#if (osFeature_Semaphore > 65535) +#error Invalid "osFeature_Semaphore" value! +#endif +#if (osFeature_Wait != 0) +#error osWait not supported! +#endif + + +// ==== Enumeration, structures, defines ==== + +// Service Calls defines + +#if defined (__CC_ARM) /* ARM Compiler */ + +#define __NO_RETURN __declspec(noreturn) + +#define osEvent_type osEvent +#define osEvent_ret_status ret +#define osEvent_ret_value ret +#define osEvent_ret_msg ret +#define osEvent_ret_mail ret + +#define osCallback_type osCallback +#define osCallback_ret ret + +#define SVC_0_1(f,t,...) \ +__svc_indirect(0) t _##f (t(*)()); \ + t f (void); \ +__attribute__((always_inline)) \ +static __inline t __##f (void) { \ + return _##f(f); \ +} + +#define SVC_1_0(f,t,t1,...) \ +__svc_indirect(0) t _##f (t(*)(t1),t1); \ + t f (t1 a1); \ +__attribute__((always_inline)) \ +static __inline t __##f (t1 a1) { \ + _##f(f,a1); \ +} + +#define SVC_1_1(f,t,t1,...) \ +__svc_indirect(0) t _##f (t(*)(t1),t1); \ + t f (t1 a1); \ +__attribute__((always_inline)) \ +static __inline t __##f (t1 a1) { \ + return _##f(f,a1); \ +} + +#define SVC_2_1(f,t,t1,t2,...) \ +__svc_indirect(0) t _##f (t(*)(t1,t2),t1,t2); \ + t f (t1 a1, t2 a2); \ +__attribute__((always_inline)) \ +static __inline t __##f (t1 a1, t2 a2) { \ + return _##f(f,a1,a2); \ +} + +#define SVC_3_1(f,t,t1,t2,t3,...) \ +__svc_indirect(0) t _##f (t(*)(t1,t2,t3),t1,t2,t3); \ + t f (t1 a1, t2 a2, t3 a3); \ +__attribute__((always_inline)) \ +static __inline t __##f (t1 a1, t2 a2, t3 a3) { \ + return _##f(f,a1,a2,a3); \ +} + +#define SVC_4_1(f,t,t1,t2,t3,t4,...) \ +__svc_indirect(0) t _##f (t(*)(t1,t2,t3,t4),t1,t2,t3,t4); \ + t f (t1 a1, t2 a2, t3 a3, t4 a4); \ +__attribute__((always_inline)) \ +static __inline t __##f (t1 a1, t2 a2, t3 a3, t4 a4) { \ + return _##f(f,a1,a2,a3,a4); \ +} + +#define SVC_1_2 SVC_1_1 +#define SVC_1_3 SVC_1_1 +#define SVC_2_3 SVC_2_1 + +#elif defined (__GNUC__) /* GNU Compiler */ + +#define __NO_RETURN __attribute__((noreturn)) + +typedef uint32_t __attribute__((vector_size(8))) ret64; +typedef uint32_t __attribute__((vector_size(16))) ret128; + +#define RET_pointer __r0 +#define RET_int32_t __r0 +#define RET_uint32_t __r0 +#define RET_osStatus __r0 +#define RET_osPriority __r0 +#define RET_osEvent {(osStatus)__r0, {(uint32_t)__r1}, {(void *)__r2}} +#define RET_osCallback {(void *)__r0, (void *)__r1} + +#define osEvent_type __attribute__((pcs("aapcs"))) ret128 +#define osEvent_ret_status (ret128){ret.status} +#define osEvent_ret_value (ret128){ret.status, ret.value.v} +#define osEvent_ret_msg (ret128){ret.status, ret.value.v, (uint32_t)ret.def.message_id} +#define osEvent_ret_mail (ret128){ret.status, ret.value.v, (uint32_t)ret.def.mail_id} + +#define osCallback_type __attribute__((pcs("aapcs"))) ret64 +#define osCallback_ret (ret64) {(uint32_t)ret.fp, (uint32_t)ret.arg} + +#define SVC_ArgN(n) \ + register int __r##n __asm("r"#n); + +#define SVC_ArgR(n,t,a) \ + register t __r##n __asm("r"#n) = a; + +#define SVC_Arg0() \ + SVC_ArgN(0) \ + SVC_ArgN(1) \ + SVC_ArgN(2) \ + SVC_ArgN(3) + +#define SVC_Arg1(t1) \ + SVC_ArgR(0,t1,a1) \ + SVC_ArgN(1) \ + SVC_ArgN(2) \ + SVC_ArgN(3) + +#define SVC_Arg2(t1,t2) \ + SVC_ArgR(0,t1,a1) \ + SVC_ArgR(1,t2,a2) \ + SVC_ArgN(2) \ + SVC_ArgN(3) + +#define SVC_Arg3(t1,t2,t3) \ + SVC_ArgR(0,t1,a1) \ + SVC_ArgR(1,t2,a2) \ + SVC_ArgR(2,t3,a3) \ + SVC_ArgN(3) + +#define SVC_Arg4(t1,t2,t3,t4) \ + SVC_ArgR(0,t1,a1) \ + SVC_ArgR(1,t2,a2) \ + SVC_ArgR(2,t3,a3) \ + SVC_ArgR(3,t4,a4) + +#if (defined (__CORTEX_M0)) +#define SVC_Call(f) \ + __asm volatile \ + ( \ + "ldr r7,="#f"\n\t" \ + "mov r12,r7\n\t" \ + "svc 0" \ + : "=r" (__r0), "=r" (__r1), "=r" (__r2), "=r" (__r3) \ + : "r" (__r0), "r" (__r1), "r" (__r2), "r" (__r3) \ + : "r7", "r12", "lr", "cc" \ + ); +#else +#define SVC_Call(f) \ + __asm volatile \ + ( \ + "ldr r12,="#f"\n\t" \ + "svc 0" \ + : "=r" (__r0), "=r" (__r1), "=r" (__r2), "=r" (__r3) \ + : "r" (__r0), "r" (__r1), "r" (__r2), "r" (__r3) \ + : "r12", "lr", "cc" \ + ); +#endif + +#define SVC_0_1(f,t,rv) \ +__attribute__((always_inline)) \ +static inline t __##f (void) { \ + SVC_Arg0(); \ + SVC_Call(f); \ + return (t) rv; \ +} + +#define SVC_1_0(f,t,t1) \ +__attribute__((always_inline)) \ +static inline t __##f (t1 a1) { \ + SVC_Arg1(t1); \ + SVC_Call(f); \ +} + +#define SVC_1_1(f,t,t1,rv) \ +__attribute__((always_inline)) \ +static inline t __##f (t1 a1) { \ + SVC_Arg1(t1); \ + SVC_Call(f); \ + return (t) rv; \ +} + +#define SVC_2_1(f,t,t1,t2,rv) \ +__attribute__((always_inline)) \ +static inline t __##f (t1 a1, t2 a2) { \ + SVC_Arg2(t1,t2); \ + SVC_Call(f); \ + return (t) rv; \ +} + +#define SVC_3_1(f,t,t1,t2,t3,rv) \ +__attribute__((always_inline)) \ +static inline t __##f (t1 a1, t2 a2, t3 a3) { \ + SVC_Arg3(t1,t2,t3); \ + SVC_Call(f); \ + return (t) rv; \ +} + +#define SVC_4_1(f,t,t1,t2,t3,t4,rv) \ +__attribute__((always_inline)) \ +static inline t __##f (t1 a1, t2 a2, t3 a3, t4 a4) { \ + SVC_Arg4(t1,t2,t3,t4); \ + SVC_Call(f); \ + return (t) rv; \ +} + +#define SVC_1_2 SVC_1_1 +#define SVC_1_3 SVC_1_1 +#define SVC_2_3 SVC_2_1 + +#elif defined (__ICCARM__) /* IAR Compiler */ + +#define __NO_RETURN __noreturn + +#define RET_osEvent "=r"(ret.status), "=r"(ret.value), "=r"(ret.def) +#define RET_osCallback "=r"(ret.fp), "=r"(ret.arg) + +#define osEvent_type osEvent +#define osEvent_ret_status ret +#define osEvent_ret_value ret +#define osEvent_ret_msg ret +#define osEvent_ret_mail ret + +#define osCallback_type uint64_t +#define osCallback_ret ((uint64_t)ret.fp | ((uint64_t)ret.arg)<<32) + +#define SVC_Setup(f) \ + __asm( \ + "mov r12,%0\n" \ + :: "r"(&f): "r12" \ + ); + +#define SVC_Ret3() \ + __asm( \ + "ldr r0,[sp,#0]\n" \ + "ldr r1,[sp,#4]\n" \ + "ldr r2,[sp,#8]\n" \ + ); + +#define SVC_0_1(f,t,...) \ +t f (void); \ +_Pragma("swi_number=0") __swi t _##f (void); \ +static inline t __##f (void) { \ + SVC_Setup(f); \ + return _##f(); \ +} + +#define SVC_1_0(f,t,t1,...) \ +t f (t1 a1); \ +_Pragma("swi_number=0") __swi t _##f (t1 a1); \ +static inline t __##f (t1 a1) { \ + SVC_Setup(f); \ + _##f(a1); \ +} + +#define SVC_1_1(f,t,t1,...) \ +t f (t1 a1); \ +_Pragma("swi_number=0") __swi t _##f (t1 a1); \ +static inline t __##f (t1 a1) { \ + SVC_Setup(f); \ + return _##f(a1); \ +} + +#define SVC_2_1(f,t,t1,t2,...) \ +t f (t1 a1, t2 a2); \ +_Pragma("swi_number=0") __swi t _##f (t1 a1, t2 a2); \ +static inline t __##f (t1 a1, t2 a2) { \ + SVC_Setup(f); \ + return _##f(a1,a2); \ +} + +#define SVC_3_1(f,t,t1,t2,t3,...) \ +t f (t1 a1, t2 a2, t3 a3); \ +_Pragma("swi_number=0") __swi t _##f (t1 a1, t2 a2, t3 a3); \ +static inline t __##f (t1 a1, t2 a2, t3 a3) { \ + SVC_Setup(f); \ + return _##f(a1,a2,a3); \ +} + +#define SVC_4_1(f,t,t1,t2,t3,t4,...) \ +t f (t1 a1, t2 a2, t3 a3, t4 a4); \ +_Pragma("swi_number=0") __swi t _##f (t1 a1, t2 a2, t3 a3, t4 a4); \ +static inline t __##f (t1 a1, t2 a2, t3 a3, t4 a4) { \ + SVC_Setup(f); \ + return _##f(a1,a2,a3,a4); \ +} + +#define SVC_1_2(f,t,t1,rr) \ +uint64_t f (t1 a1); \ +_Pragma("swi_number=0") __swi uint64_t _##f (t1 a1); \ +static inline t __##f (t1 a1) { \ + t ret; \ + SVC_Setup(f); \ + _##f(a1); \ + __asm("" : rr : :); \ + return ret; \ +} + +#define SVC_1_3(f,t,t1,rr) \ +t f (t1 a1); \ +void f##_ (t1 a1) { \ + f(a1); \ + SVC_Ret3(); \ +} \ +_Pragma("swi_number=0") __swi void _##f (t1 a1); \ +static inline t __##f (t1 a1) { \ + t ret; \ + SVC_Setup(f##_); \ + _##f(a1); \ + __asm("" : rr : :); \ + return ret; \ +} + +#define SVC_2_3(f,t,t1,t2,rr) \ +t f (t1 a1, t2 a2); \ +void f##_ (t1 a1, t2 a2) { \ + f(a1,a2); \ + SVC_Ret3(); \ +} \ +_Pragma("swi_number=0") __swi void _##f (t1 a1, t2 a2); \ +static inline t __##f (t1 a1, t2 a2) { \ + t ret; \ + SVC_Setup(f##_); \ + _##f(a1,a2); \ + __asm("" : rr : :); \ + return ret; \ +} + +#endif + + +// Callback structure +typedef struct { + void *fp; // Function pointer + void *arg; // Function argument +} osCallback; + + +// OS Section definitions +#ifdef OS_SECTIONS_LINK_INFO +extern const uint32_t os_section_id$$Base; +extern const uint32_t os_section_id$$Limit; +#endif + +#ifndef __MBED_CMSIS_RTOS_CA9 +// OS Stack Memory for Threads definitions +extern uint64_t os_stack_mem[]; +extern const uint32_t os_stack_sz; +#endif + +// OS Timers external resources +extern const osThreadDef_t os_thread_def_osTimerThread; +extern osThreadId osThreadId_osTimerThread; +extern const osMessageQDef_t os_messageQ_def_osTimerMessageQ; +extern osMessageQId osMessageQId_osTimerMessageQ; + +extern U32 IRQNestLevel; /* Indicates whether inside an ISR, and the depth of nesting. 0 = not in ISR. */ + +// Thread creation and destruction +osMutexDef(osThreadMutex); +osMutexId osMutexId_osThreadMutex; +void sysThreadTerminate(osThreadId id); + +// ==== Helper Functions ==== + +/// Convert timeout in millisec to system ticks +static uint16_t rt_ms2tick (uint32_t millisec) { + uint32_t tick; + + if (millisec == 0U) { return 0x0U; } // No timeout + if (millisec == osWaitForever) { return 0xFFFFU; } // Indefinite timeout + if (millisec > 4000000U) { return 0xFFFEU; } // Max ticks supported + + tick = ((1000U * millisec) + os_clockrate - 1U) / os_clockrate; + if (tick > 0xFFFEU) { return 0xFFFEU; } + + return (uint16_t)tick; +} + +/// Convert Thread ID to TCB pointer +P_TCB rt_tid2ptcb (osThreadId thread_id) { + P_TCB ptcb; + + if (thread_id == NULL) { return NULL; } + + if ((uint32_t)thread_id & 3U) { return NULL; } + +#ifdef OS_SECTIONS_LINK_INFO + if ((os_section_id$$Base != 0U) && (os_section_id$$Limit != 0U)) { + if (thread_id < (osThreadId)os_section_id$$Base) { return NULL; } + if (thread_id >= (osThreadId)os_section_id$$Limit) { return NULL; } + } +#endif + + ptcb = thread_id; + + if (ptcb->cb_type != TCB) { return NULL; } + + return ptcb; +} + +/// Convert ID pointer to Object pointer +static void *rt_id2obj (void *id) { + + if ((uint32_t)id & 3U) { return NULL; } + +#ifdef OS_SECTIONS_LINK_INFO + if ((os_section_id$$Base != 0U) && (os_section_id$$Limit != 0U)) { + if (id < (void *)os_section_id$$Base) { return NULL; } + if (id >= (void *)os_section_id$$Limit) { return NULL; } + } +#endif + + return id; +} + +// === Helper functions for system call interface === + +static __inline char __get_mode(void) { + return (char)(__get_CPSR() & 0x1FU); +} + +static __inline char __exceptional_mode(void) { + // Interrupts disabled + if (__get_CPSR() & 0x80) { + return 1; + } + + switch(__get_mode()) { + case MODE_USR: + case MODE_SYS: + return 0U; + case MODE_SVC: + if (IRQNestLevel == 0U) + return 0U; /* handling a regular service call */ + else + return 1U; /* handling an ISR in SVC mode */ + default: + return 1U; + } +} + +// ==== Kernel Control ==== + +uint8_t os_initialized; // Kernel Initialized flag +uint8_t os_running; // Kernel Running flag + +// Kernel Control Service Calls declarations +SVC_0_1(svcKernelInitialize, osStatus, RET_osStatus) +SVC_0_1(svcKernelStart, osStatus, RET_osStatus) +SVC_0_1(svcKernelRunning, int32_t, RET_int32_t) +SVC_0_1(svcKernelSysTick, uint32_t, RET_uint32_t) + +static void sysThreadError (osStatus status); +osThreadId svcThreadCreate (const osThreadDef_t *thread_def, void *argument); +osMessageQId svcMessageCreate (const osMessageQDef_t *queue_def, osThreadId thread_id); + +// Kernel Control Service Calls + +/// Initialize the RTOS Kernel for creating objects +osStatus svcKernelInitialize (void) { +#ifdef __MBED_CMSIS_RTOS_CA9 + if (!os_initialized) { + rt_sys_init(); // RTX System Initialization + } +#else + uint32_t ret; + + if (os_initialized == 0U) { + + // Init Thread Stack Memory (must be 8-byte aligned) + if (((uint32_t)os_stack_mem & 7U) != 0U) { return osErrorNoMemory; } + ret = rt_init_mem(os_stack_mem, os_stack_sz); + if (ret != 0U) { return osErrorNoMemory; } + + rt_sys_init(); // RTX System Initialization + } +#endif + + os_tsk.run->prio = 255U; // Highest priority + + if (os_initialized == 0U) { + // Create OS Timers resources (Message Queue & Thread) + osMessageQId_osTimerMessageQ = svcMessageCreate (&os_messageQ_def_osTimerMessageQ, NULL); + osThreadId_osTimerThread = svcThreadCreate(&os_thread_def_osTimerThread, NULL); + // Initialize thread mutex + osMutexId_osThreadMutex = osMutexCreate(osMutex(osThreadMutex)); + } + + sysThreadError(osOK); + + os_initialized = 1U; + os_running = 0U; + + return osOK; +} + +/// Start the RTOS Kernel +osStatus svcKernelStart (void) { + + if (os_running) { return osOK; } + + rt_tsk_prio(0U, os_tsk.run->prio_base); // Restore priority + if (os_tsk.run->task_id == 0xFFU) { // Idle Thread + __set_PSP(os_tsk.run->tsk_stack + (8U*4U)); // Setup PSP + } + os_tsk.run = NULL; // Force context switch + + rt_sys_start(); + + os_running = 1U; + + return osOK; +} + +/// Check if the RTOS kernel is already started +int32_t svcKernelRunning (void) { + return (int32_t)os_running; +} + +/// Get the RTOS kernel system timer counter +uint32_t svcKernelSysTick (void) { + uint32_t tick, tick0; + + tick = os_tick_val(); + if (os_tick_ovf()) { + tick0 = os_tick_val(); + if (tick0 < tick) { tick = tick0; } + tick += (os_trv + 1U) * (os_time + 1U); + } else { + tick += (os_trv + 1U) * os_time; + } + + return tick; +} + +// Kernel Control Public API + +/// Initialize the RTOS Kernel for creating objects +osStatus osKernelInitialize (void) { + if (__exceptional_mode()) { + return osErrorISR; // Not allowed in ISR + } + if (__get_mode() != MODE_USR) { + return svcKernelInitialize(); + } else { + return __svcKernelInitialize(); + } +} + +/// Start the RTOS Kernel +osStatus osKernelStart (void) { + char mode = __get_mode(); + + switch(mode) { + case MODE_USR: + if (os_flags & 1U) return osErrorOS; // Privileged Thread mode requested from Unprivileged + break; + case MODE_SYS: + if (!(os_flags & 1U)) { + __set_CPS_USR(); + } + break; + default: + return osErrorISR; // Not allowed in ISR + } + return __svcKernelStart(); +} + +/// Check if the RTOS kernel is already started +int32_t osKernelRunning (void) { + if(__get_mode() != MODE_USR) { + return os_running; + } else { + return __svcKernelRunning(); + } +} + +/// Get the RTOS kernel system timer counter +uint32_t osKernelSysTick (void) { + if (__exceptional_mode()) { return 0U; } // Not allowed in ISR + return __svcKernelSysTick(); +} + + +// ==== Thread Management ==== + +/// Set Thread Error (for Create functions which return IDs) +static void sysThreadError (osStatus status) { + // To Do +} + +__NO_RETURN void osThreadExit (void); + +// Thread Service Calls declarations +SVC_2_1(svcThreadCreate, osThreadId, const osThreadDef_t *, void *, RET_pointer) +SVC_0_1(svcThreadGetId, osThreadId, RET_pointer) +SVC_1_1(svcThreadTerminate, osStatus, osThreadId, RET_osStatus) +SVC_0_1(svcThreadYield, osStatus, RET_osStatus) +SVC_2_1(svcThreadSetPriority, osStatus, osThreadId, osPriority, RET_osStatus) +SVC_1_1(svcThreadGetPriority, osPriority, osThreadId, RET_osPriority) +SVC_2_3(svcThreadGetInfo, os_InRegs osEvent, osThreadId, osThreadInfo, RET_osEvent) + +// Thread Service Calls + +/// Create a thread and add it to Active Threads and set it to state READY +osThreadId svcThreadCreate (const osThreadDef_t *thread_def, void *argument) { + P_TCB ptcb; + OS_TID tsk; + void *stk; + + if ((thread_def == NULL) || + (thread_def->pthread == NULL) || + (thread_def->tpriority < osPriorityIdle) || + (thread_def->tpriority > osPriorityRealtime)) { + sysThreadError(osErrorParameter); + return NULL; + } + +#ifdef __MBED_CMSIS_RTOS_CA9 + if (thread_def->stacksize != 0U) { // Custom stack size + stk = (void *)thread_def->stack_pointer; + } else { // Default stack size + stk = NULL; + } +#else + if (thread_def->stacksize != 0U) { // Custom stack size + stk = rt_alloc_mem( // Allocate stack + os_stack_mem, + thread_def->stacksize + ); + if (stk == NULL) { + sysThreadError(osErrorNoMemory); // Out of memory + return NULL; + } + } else { // Default stack size + stk = NULL; + } +#endif + + tsk = rt_tsk_create( // Create task + (FUNCP)thread_def->pthread, // Task function pointer + (uint32_t) + (thread_def->tpriority-osPriorityIdle+1) | // Task priority + (thread_def->stacksize << 8), // Task stack size in bytes + stk, // Pointer to task's stack + argument // Argument to the task + ); + + if (tsk == 0U) { // Invalid task ID +#ifndef __MBED_CMSIS_RTOS_CA9 + if (stk != NULL) { + rt_free_mem(os_stack_mem, stk); // Free allocated stack + } +#endif + sysThreadError(osErrorNoMemory); // Create task failed (Out of memory) + return NULL; + } + + ptcb = (P_TCB)os_active_TCB[tsk - 1U]; // TCB pointer + + *((uint32_t *)ptcb->tsk_stack + 13) = (uint32_t)osThreadExit; + + return ptcb; +} + +/// Return the thread ID of the current running thread +osThreadId svcThreadGetId (void) { + OS_TID tsk; + + tsk = rt_tsk_self(); + if (tsk == 0U) { return NULL; } + return (P_TCB)os_active_TCB[tsk - 1U]; +} + +/// Terminate execution of a thread and remove it from ActiveThreads +osStatus svcThreadTerminate (osThreadId thread_id) { + OS_RESULT res; + P_TCB ptcb; +#ifndef __MBED_CMSIS_RTOS_CA9 + void *stk; +#endif + + ptcb = rt_tid2ptcb(thread_id); // Get TCB pointer + if (ptcb == NULL) { + return osErrorParameter; + } + +#ifndef __MBED_CMSIS_RTOS_CA9 + stk = ptcb->priv_stack ? ptcb->stack : NULL; // Private stack +#endif + + res = rt_tsk_delete(ptcb->task_id); // Delete task + + if (res == OS_R_NOK) { + return osErrorResource; // Delete task failed + } + +#ifndef __MBED_CMSIS_RTOS_CA9 + if (stk != NULL) { + rt_free_mem(os_stack_mem, stk); // Free private stack + } +#endif + + return osOK; +} + +/// Pass control to next thread that is in state READY +osStatus svcThreadYield (void) { + rt_tsk_pass(); // Pass control to next task + return osOK; +} + +/// Change priority of an active thread +osStatus svcThreadSetPriority (osThreadId thread_id, osPriority priority) { + OS_RESULT res; + P_TCB ptcb; + + ptcb = rt_tid2ptcb(thread_id); // Get TCB pointer + if (ptcb == NULL) { + return osErrorParameter; + } + + if ((priority < osPriorityIdle) || (priority > osPriorityRealtime)) { + return osErrorValue; + } + + res = rt_tsk_prio( // Change task priority + ptcb->task_id, // Task ID + (uint8_t)(priority - osPriorityIdle + 1) // New task priority + ); + + if (res == OS_R_NOK) { + return osErrorResource; // Change task priority failed + } + + return osOK; +} + +/// Get current priority of an active thread +osPriority svcThreadGetPriority (osThreadId thread_id) { + P_TCB ptcb; + + ptcb = rt_tid2ptcb(thread_id); // Get TCB pointer + if (ptcb == NULL) { + return osPriorityError; + } + + return (osPriority)(ptcb->prio - 1 + osPriorityIdle); +} + +/// Get info from an active thread +os_InRegs osEvent_type svcThreadGetInfo (osThreadId thread_id, osThreadInfo info) { + P_TCB ptcb; + osEvent ret; + ret.status = osOK; + + ptcb = rt_tid2ptcb(thread_id); // Get TCB pointer + if (ptcb == NULL) { + ret.status = osErrorValue; + return osEvent_ret_status; + } + + if (osThreadInfoStackSize == info) { + uint32_t size; + size = ptcb->priv_stack; + if (0U == size) { + // This is an OS task - always a fixed size + size = os_stackinfo & 0x3FFFFU; + } + ret.value.v = size; + return osEvent_ret_value; + } + + if (osThreadInfoStackMax == info) { + uint32_t i; + uint32_t *stack_ptr; + uint32_t stack_size; + if (!(os_stackinfo & (1 << 28))) { + // Stack init must be turned on for max stack usage + ret.status = osErrorResource; + return osEvent_ret_status; + } + stack_ptr = (uint32_t*)ptcb->stack; + stack_size = ptcb->priv_stack; + if (0 == stack_size) { + // This is an OS task - always a fixed size + stack_size = os_stackinfo & 0x3FFFF; + } + for (i = 1; i ptask; + return osEvent_ret_value; + } + + if (osThreadInfoArg == info) { + ret.value.p = (void*)ptcb->argv; + return osEvent_ret_value; + } + + // Unsupported option so return error + ret.status = osErrorParameter; + return osEvent_ret_status; +} + +// Thread Public API + +/// Create a thread and add it to Active Threads and set it to state READY +osThreadId osThreadCreate (const osThreadDef_t *thread_def, void *argument) { + if (__exceptional_mode()) { + return NULL; // Not allowed in ISR + } + if ((__get_mode() != MODE_USR) && (os_running == 0U)) { + // Privileged and not running + return svcThreadCreate(thread_def, argument); + } else { + osThreadId id; + osMutexWait(osMutexId_osThreadMutex, osWaitForever); + // Thread mutex must be held when a thread is created or terminated + id = __svcThreadCreate(thread_def, argument); + osMutexRelease(osMutexId_osThreadMutex); + return id; + } +} + +/// Return the thread ID of the current running thread +osThreadId osThreadGetId (void) { + if (__exceptional_mode()) { + return NULL; // Not allowed in ISR + } + return __svcThreadGetId(); +} + +/// Terminate execution of a thread and remove it from ActiveThreads +osStatus osThreadTerminate (osThreadId thread_id) { + osStatus status; + if (__exceptional_mode()) { + return osErrorISR; // Not allowed in ISR + } + osMutexWait(osMutexId_osThreadMutex, osWaitForever); + sysThreadTerminate(thread_id); + // Thread mutex must be held when a thread is created or terminated + status = __svcThreadTerminate(thread_id); + osMutexRelease(osMutexId_osThreadMutex); + return status; +} + +/// Pass control to next thread that is in state READY +osStatus osThreadYield (void) { + if (__exceptional_mode()) { + return osErrorISR; // Not allowed in ISR + } + return __svcThreadYield(); +} + +/// Change priority of an active thread +osStatus osThreadSetPriority (osThreadId thread_id, osPriority priority) { + if (__exceptional_mode()) { + return osErrorISR; // Not allowed in ISR + } + return __svcThreadSetPriority(thread_id, priority); +} + +/// Get current priority of an active thread +osPriority osThreadGetPriority (osThreadId thread_id) { + if (__exceptional_mode()) { + return osPriorityError;// Not allowed in ISR + } + return __svcThreadGetPriority(thread_id); +} + +/// INTERNAL - Not Public +/// Auto Terminate Thread on exit (used implicitly when thread exists) +__NO_RETURN void osThreadExit (void) { + osThreadId id; + // Thread mutex must be held when a thread is created or terminated + // Note - the mutex will be released automatically by the os when + // the thread is terminated + osMutexWait(osMutexId_osThreadMutex, osWaitForever); + id = __svcThreadGetId(); + sysThreadTerminate(id); + __svcThreadTerminate(id); + for (;;); // Should never come here +} + +#ifdef __MBED_CMSIS_RTOS_CA9 +/// Get current thread state +uint8_t osThreadGetState (osThreadId thread_id) { + P_TCB ptcb; + + if (__exceptional_mode()) { + return osErrorISR; // Not allowed in ISR + } + + ptcb = rt_tid2ptcb(thread_id); // Get TCB pointer + if (ptcb == NULL) { + return INACTIVE; + } + + return ptcb->state; +} +#endif + +/// Get the requested info from the specified active thread +os_InRegs osEvent _osThreadGetInfo(osThreadId thread_id, osThreadInfo info) { + osEvent ret; + if (__exceptional_mode()) { + ret.status = osErrorISR; + return ret; // Not allowed in ISR + } + return __svcThreadGetInfo(thread_id, info); +} + +osThreadEnumId _osThreadsEnumStart() { + static uint32_t thread_enum_index; + osMutexWait(osMutexId_osThreadMutex, osWaitForever); + thread_enum_index = 0; + return &thread_enum_index; +} + +osThreadId _osThreadEnumNext(osThreadEnumId enum_id) { + uint32_t i; + osThreadId id = NULL; + uint32_t *index = (uint32_t*)enum_id; + for (i = *index; i < os_maxtaskrun; i++) { + if (os_active_TCB[i] != NULL) { + id = (osThreadId)os_active_TCB[i]; + break; + } + } + if (i == os_maxtaskrun) { + // Include the idle task at the end of the enumeration + id = &os_idle_TCB; + } + *index = i + 1U; + return id; +} + +osStatus _osThreadEnumFree(osThreadEnumId enum_id) { + uint32_t *index = (uint32_t*)enum_id; + *index = 0U; + osMutexRelease(osMutexId_osThreadMutex); + return osOK; +} + +// ==== Generic Wait Functions ==== + +// Generic Wait Service Calls declarations +SVC_1_1(svcDelay, osStatus, uint32_t, RET_osStatus) +#if osFeature_Wait != 0 +SVC_1_3(svcWait, os_InRegs osEvent, uint32_t, RET_osEvent) +#endif + +// Generic Wait Service Calls + +/// Wait for Timeout (Time Delay) +osStatus svcDelay (uint32_t millisec) { + if (millisec == 0U) { return osOK; } + rt_dly_wait(rt_ms2tick(millisec)); + return osEventTimeout; +} + +/// Wait for Signal, Message, Mail, or Timeout +#if osFeature_Wait != 0 +os_InRegs osEvent_type svcWait (uint32_t millisec) { + osEvent ret; + + if (millisec == 0U) { + ret.status = osOK; + return osEvent_ret_status; + } + + /* To Do: osEventSignal, osEventMessage, osEventMail */ + rt_dly_wait(rt_ms2tick(millisec)); + ret.status = osEventTimeout; + + return osEvent_ret_status; +} +#endif + + +// Generic Wait API + +/// Wait for Timeout (Time Delay) +osStatus osDelay (uint32_t millisec) { + if (__exceptional_mode()) { + return osErrorISR; // Not allowed in ISR + } + return __svcDelay(millisec); +} + +/// Wait for Signal, Message, Mail, or Timeout +os_InRegs osEvent osWait (uint32_t millisec) { + osEvent ret; + +#if osFeature_Wait == 0 + ret.status = osErrorOS; + return ret; +#else + if (__exceptional_mode()) { // Not allowed in ISR + ret.status = osErrorISR; + return ret; + } + return __svcWait(millisec); +#endif +} + + +// ==== Timer Management ==== + +// Timer definitions +#define osTimerInvalid 0U +#define osTimerStopped 1U +#define osTimerRunning 2U + +// Timer structures + +typedef struct os_timer_cb_ { // Timer Control Block + struct os_timer_cb_ *next; // Pointer to next active Timer + uint8_t state; // Timer State + uint8_t type; // Timer Type (Periodic/One-shot) + uint16_t reserved; // Reserved + uint32_t tcnt; // Timer Delay Count + uint32_t icnt; // Timer Initial Count + void *arg; // Timer Function Argument + const osTimerDef_t *timer; // Pointer to Timer definition +} os_timer_cb; + +// Timer variables +os_timer_cb *os_timer_head; // Pointer to first active Timer + + +// Timer Helper Functions + +// Insert Timer into the list sorted by time +static void rt_timer_insert (os_timer_cb *pt, uint32_t tcnt) { + os_timer_cb *p, *prev; + + prev = NULL; + p = os_timer_head; + while (p != NULL) { + if (tcnt < p->tcnt) { break; } + tcnt -= p->tcnt; + prev = p; + p = p->next; + } + pt->next = p; + pt->tcnt = tcnt; + if (p != NULL) { + p->tcnt -= pt->tcnt; + } + if (prev != NULL) { + prev->next = pt; + } else { + os_timer_head = pt; + } +} + +// Remove Timer from the list +static int32_t rt_timer_remove (os_timer_cb *pt) { + os_timer_cb *p, *prev; + + prev = NULL; + p = os_timer_head; + while (p != NULL) { + if (p == pt) { break; } + prev = p; + p = p->next; + } + if (p == NULL) { return -1; } + if (prev != NULL) { + prev->next = pt->next; + } else { + os_timer_head = pt->next; + } + if (pt->next != NULL) { + pt->next->tcnt += pt->tcnt; + } + + return 0; +} + + +// Timer Service Calls declarations +SVC_3_1(svcTimerCreate, osTimerId, const osTimerDef_t *, os_timer_type, void *, RET_pointer) +SVC_2_1(svcTimerStart, osStatus, osTimerId, uint32_t, RET_osStatus) +SVC_1_1(svcTimerStop, osStatus, osTimerId, RET_osStatus) +SVC_1_1(svcTimerDelete, osStatus, osTimerId, RET_osStatus) +SVC_1_2(svcTimerCall, os_InRegs osCallback, osTimerId, RET_osCallback) + +// Timer Management Service Calls + +/// Create timer +osTimerId svcTimerCreate (const osTimerDef_t *timer_def, os_timer_type type, void *argument) { + os_timer_cb *pt; + + if ((timer_def == NULL) || (timer_def->ptimer == NULL)) { + sysThreadError(osErrorParameter); + return NULL; + } + + pt = timer_def->timer; + if (pt == NULL) { + sysThreadError(osErrorParameter); + return NULL; + } + + if ((type != osTimerOnce) && (type != osTimerPeriodic)) { + sysThreadError(osErrorValue); + return NULL; + } + + if (osThreadId_osTimerThread == NULL) { + sysThreadError(osErrorResource); + return NULL; + } + + if (pt->state != osTimerInvalid){ + sysThreadError(osErrorResource); + return NULL; + } + + pt->next = NULL; + pt->state = osTimerStopped; + pt->type = (uint8_t)type; + pt->arg = argument; + pt->timer = timer_def; + + return (osTimerId)pt; +} + +/// Start or restart timer +osStatus svcTimerStart (osTimerId timer_id, uint32_t millisec) { + os_timer_cb *pt; + uint32_t tcnt; + + pt = rt_id2obj(timer_id); + if (pt == NULL) { + return osErrorParameter; + } + + if (millisec == 0U) { return osErrorValue; } + + tcnt = (uint32_t)(((1000U * (uint64_t)millisec) + os_clockrate - 1U) / os_clockrate); + + switch (pt->state) { + case osTimerRunning: + if (rt_timer_remove(pt) != 0) { + return osErrorResource; + } + break; + case osTimerStopped: + pt->state = osTimerRunning; + pt->icnt = tcnt; + break; + default: + return osErrorResource; + } + + rt_timer_insert(pt, tcnt); + + return osOK; +} + +/// Stop timer +osStatus svcTimerStop (osTimerId timer_id) { + os_timer_cb *pt; + + pt = rt_id2obj(timer_id); + if (pt == NULL) { + return osErrorParameter; + } + + if (pt->state != osTimerRunning) { return osErrorResource; } + + pt->state = osTimerStopped; + + if (rt_timer_remove(pt) != 0) { + return osErrorResource; + } + + return osOK; +} + +/// Delete timer +osStatus svcTimerDelete (osTimerId timer_id) { + os_timer_cb *pt; + + pt = rt_id2obj(timer_id); + if (pt == NULL) { + return osErrorParameter; + } + + switch (pt->state) { + case osTimerRunning: + rt_timer_remove(pt); + break; + case osTimerStopped: + break; + default: + return osErrorResource; + } + + pt->state = osTimerInvalid; + + return osOK; +} + +/// Get timer callback parameters +os_InRegs osCallback_type svcTimerCall (osTimerId timer_id) { + os_timer_cb *pt; + osCallback ret; + + pt = rt_id2obj(timer_id); + if (pt == NULL) { + ret.fp = NULL; + ret.arg = NULL; + return osCallback_ret; + } + + ret.fp = (void *)pt->timer->ptimer; + ret.arg = pt->arg; + + return osCallback_ret; +} + +osStatus isrMessagePut (osMessageQId queue_id, uint32_t info, uint32_t millisec); + +/// Timer Tick (called each SysTick) +void sysTimerTick (void) { + os_timer_cb *pt, *p; + osStatus status; + + p = os_timer_head; + if (p == NULL) { return; } + + p->tcnt--; + while ((p != NULL) && (p->tcnt == 0U)) { + pt = p; + p = p->next; + os_timer_head = p; + status = isrMessagePut(osMessageQId_osTimerMessageQ, (uint32_t)pt, 0U); + if (status != osOK) { + os_error(OS_ERR_TIMER_OVF); + } + if (pt->type == (uint8_t)osTimerPeriodic) { + rt_timer_insert(pt, pt->icnt); + } else { + pt->state = osTimerStopped; + } + } +} + +/// Get user timers wake-up time +uint32_t sysUserTimerWakeupTime (void) { + + if (os_timer_head) { + return os_timer_head->tcnt; + } + return 0xFFFFFFFFU; +} + +/// Update user timers on resume +void sysUserTimerUpdate (uint32_t sleep_time) { + + while ((os_timer_head != NULL) && (sleep_time != 0U)) { + if (sleep_time >= os_timer_head->tcnt) { + sleep_time -= os_timer_head->tcnt; + os_timer_head->tcnt = 1U; + sysTimerTick(); + } else { + os_timer_head->tcnt -= sleep_time; + break; + } + } +} + + +// Timer Management Public API + +/// Create timer +osTimerId osTimerCreate (const osTimerDef_t *timer_def, os_timer_type type, void *argument) { + if (__exceptional_mode()) { + return NULL; // Not allowed in ISR + } + if ((__get_mode() != MODE_USR) && (os_running == 0U)) { + // Privileged and not running + return svcTimerCreate(timer_def, type, argument); + } else { + return __svcTimerCreate(timer_def, type, argument); + } +} + +/// Start or restart timer +osStatus osTimerStart (osTimerId timer_id, uint32_t millisec) { + if (__exceptional_mode()) { + return osErrorISR; // Not allowed in ISR + } + return __svcTimerStart(timer_id, millisec); +} + +/// Stop timer +osStatus osTimerStop (osTimerId timer_id) { + if (__exceptional_mode()) { + return osErrorISR; // Not allowed in ISR + } + return __svcTimerStop(timer_id); +} + +/// Delete timer +osStatus osTimerDelete (osTimerId timer_id) { + if (__exceptional_mode()) { + return osErrorISR; // Not allowed in ISR + } + return __svcTimerDelete(timer_id); +} + +/// INTERNAL - Not Public +/// Get timer callback parameters (used by OS Timer Thread) +os_InRegs osCallback osTimerCall (osTimerId timer_id) { + return __svcTimerCall(timer_id); +} + + +// Timer Thread +__NO_RETURN void osTimerThread (void const *argument) { + osCallback cb; + osEvent evt; + + for (;;) { + evt = osMessageGet(osMessageQId_osTimerMessageQ, osWaitForever); + if (evt.status == osEventMessage) { + cb = osTimerCall(evt.value.p); + if (cb.fp != NULL) { + (*(os_ptimer)cb.fp)(cb.arg); + } + } + } +} + + +// ==== Signal Management ==== + +// Signal Service Calls declarations +SVC_2_1(svcSignalSet, int32_t, osThreadId, int32_t, RET_int32_t) +SVC_2_1(svcSignalClear, int32_t, osThreadId, int32_t, RET_int32_t) +SVC_2_3(svcSignalWait, os_InRegs osEvent, int32_t, uint32_t, RET_osEvent) + +// Signal Service Calls + +/// Set the specified Signal Flags of an active thread +int32_t svcSignalSet (osThreadId thread_id, int32_t signals) { + P_TCB ptcb; + int32_t sig; + + ptcb = rt_tid2ptcb(thread_id); // Get TCB pointer + if (ptcb == NULL) { + return (int32_t)0x80000000U; + } + + if ((uint32_t)signals & (0xFFFFFFFFU << osFeature_Signals)) { + return (int32_t)0x80000000U; + } + + sig = (int32_t)ptcb->events; // Previous signal flags + + rt_evt_set((uint16_t)signals, ptcb->task_id); // Set event flags + + return sig; +} + +/// Clear the specified Signal Flags of an active thread +int32_t svcSignalClear (osThreadId thread_id, int32_t signals) { + P_TCB ptcb; + int32_t sig; + + ptcb = rt_tid2ptcb(thread_id); // Get TCB pointer + if (ptcb == NULL) { + return (int32_t)0x80000000U; + } + + if ((uint32_t)signals & (0xFFFFFFFFU << osFeature_Signals)) { + return (int32_t)0x80000000U; + } + + sig = (int32_t)ptcb->events; // Previous signal flags + + rt_evt_clr((uint16_t)signals, ptcb->task_id); // Clear event flags + + return sig; +} + +/// Wait for one or more Signal Flags to become signaled for the current RUNNING thread +os_InRegs osEvent_type svcSignalWait (int32_t signals, uint32_t millisec) { + OS_RESULT res; + osEvent ret; + + if ((uint32_t)signals & (0xFFFFFFFFU << osFeature_Signals)) { + ret.status = osErrorValue; + return osEvent_ret_status; + } + + if (signals != 0) { // Wait for all specified signals + res = rt_evt_wait((uint16_t)signals, rt_ms2tick(millisec), __TRUE); + } else { // Wait for any signal + res = rt_evt_wait(0xFFFFU, rt_ms2tick(millisec), __FALSE); + } + + if (res == OS_R_EVT) { + ret.status = osEventSignal; + ret.value.signals = (signals != 0) ? signals : (int32_t)os_tsk.run->waits; + } else { + ret.status = (millisec != 0U) ? osEventTimeout : osOK; + ret.value.signals = 0; + } + + return osEvent_ret_value; +} + + +// Signal ISR Calls + +/// Set the specified Signal Flags of an active thread +int32_t isrSignalSet (osThreadId thread_id, int32_t signals) { + P_TCB ptcb; + int32_t sig; + + ptcb = rt_tid2ptcb(thread_id); // Get TCB pointer + if (ptcb == NULL) { + return (int32_t)0x80000000U; + } + + if ((uint32_t)signals & (0xFFFFFFFFU << osFeature_Signals)) { + return (int32_t)0x80000000U; + } + + sig = (int32_t)ptcb->events; // Previous signal flags + + isr_evt_set((uint16_t)signals, ptcb->task_id);// Set event flags + + return sig; +} + + +// Signal Public API + +/// Set the specified Signal Flags of an active thread +int32_t osSignalSet (osThreadId thread_id, int32_t signals) { + if (__exceptional_mode()) { // in ISR + return isrSignalSet(thread_id, signals); + } else { // in Thread + return __svcSignalSet(thread_id, signals); + } +} + +/// Clear the specified Signal Flags of an active thread +int32_t osSignalClear (osThreadId thread_id, int32_t signals) { + if (__exceptional_mode()) { + return (int32_t)0x80000000U; // Not allowed in ISR + } + return __svcSignalClear(thread_id, signals); +} + +/// Wait for one or more Signal Flags to become signaled for the current RUNNING thread +os_InRegs osEvent osSignalWait (int32_t signals, uint32_t millisec) { + osEvent ret; + + if (__exceptional_mode()) { // Not allowed in ISR + ret.status = osErrorISR; + return ret; + } + return __svcSignalWait(signals, millisec); +} + + +// ==== Mutex Management ==== + +// Mutex Service Calls declarations +SVC_1_1(svcMutexCreate, osMutexId, const osMutexDef_t *, RET_pointer) +SVC_2_1(svcMutexWait, osStatus, osMutexId, uint32_t, RET_osStatus) +SVC_1_1(svcMutexRelease, osStatus, osMutexId, RET_osStatus) +SVC_1_1(svcMutexDelete, osStatus, osMutexId, RET_osStatus) + +// Mutex Service Calls + +/// Create and Initialize a Mutex object +osMutexId svcMutexCreate (const osMutexDef_t *mutex_def) { + OS_ID mut; + + if (mutex_def == NULL) { + sysThreadError(osErrorParameter); + return NULL; + } + + mut = mutex_def->mutex; + if (mut == NULL) { + sysThreadError(osErrorParameter); + return NULL; + } + + if (((P_MUCB)mut)->cb_type != 0U) { + sysThreadError(osErrorParameter); + return NULL; + } + + rt_mut_init(mut); // Initialize Mutex + + return mut; +} + +/// Wait until a Mutex becomes available +osStatus svcMutexWait (osMutexId mutex_id, uint32_t millisec) { + OS_ID mut; + OS_RESULT res; + + mut = rt_id2obj(mutex_id); + if (mut == NULL) { + return osErrorParameter; + } + + if (((P_MUCB)mut)->cb_type != MUCB) { + return osErrorParameter; + } + + res = rt_mut_wait(mut, rt_ms2tick(millisec)); // Wait for Mutex + + if (res == OS_R_TMO) { + return ((millisec != 0U) ? osErrorTimeoutResource : osErrorResource); + } + + return osOK; +} + +/// Release a Mutex that was obtained with osMutexWait +osStatus svcMutexRelease (osMutexId mutex_id) { + OS_ID mut; + OS_RESULT res; + + mut = rt_id2obj(mutex_id); + if (mut == NULL) { + return osErrorParameter; + } + + if (((P_MUCB)mut)->cb_type != MUCB) { + return osErrorParameter; + } + + res = rt_mut_release(mut); // Release Mutex + + if (res == OS_R_NOK) { + return osErrorResource; // Thread not owner or Zero Counter + } + + return osOK; +} + +/// Delete a Mutex that was created by osMutexCreate +osStatus svcMutexDelete (osMutexId mutex_id) { + OS_ID mut; + + mut = rt_id2obj(mutex_id); + if (mut == NULL) { + return osErrorParameter; + } + + if (((P_MUCB)mut)->cb_type != MUCB) { + return osErrorParameter; + } + + rt_mut_delete(mut); // Release Mutex + + return osOK; +} + + +// Mutex Public API + +/// Create and Initialize a Mutex object +osMutexId osMutexCreate (const osMutexDef_t *mutex_def) { + if (__exceptional_mode()) { + return NULL; // Not allowed in ISR + } + if ((__get_mode() != MODE_USR) && (os_running == 0U)) { + // Privileged and not running + return svcMutexCreate(mutex_def); + } else { + return __svcMutexCreate(mutex_def); + } +} + +/// Wait until a Mutex becomes available +osStatus osMutexWait (osMutexId mutex_id, uint32_t millisec) { + if (__exceptional_mode()) { + return osErrorISR; // Not allowed in ISR + } + return __svcMutexWait(mutex_id, millisec); +} + +/// Release a Mutex that was obtained with osMutexWait +osStatus osMutexRelease (osMutexId mutex_id) { + if (__exceptional_mode()) { + return osErrorISR; // Not allowed in ISR + } + return __svcMutexRelease(mutex_id); +} + +/// Delete a Mutex that was created by osMutexCreate +osStatus osMutexDelete (osMutexId mutex_id) { + if (__exceptional_mode()) { + return osErrorISR; // Not allowed in ISR + } + return __svcMutexDelete(mutex_id); +} + + +// ==== Semaphore Management ==== + +// Semaphore Service Calls declarations +SVC_2_1(svcSemaphoreCreate, osSemaphoreId, const osSemaphoreDef_t *, int32_t, RET_pointer) +SVC_2_1(svcSemaphoreWait, int32_t, osSemaphoreId, uint32_t, RET_int32_t) +SVC_1_1(svcSemaphoreRelease, osStatus, osSemaphoreId, RET_osStatus) +SVC_1_1(svcSemaphoreDelete, osStatus, osSemaphoreId, RET_osStatus) + +// Semaphore Service Calls + +/// Create and Initialize a Semaphore object +osSemaphoreId svcSemaphoreCreate (const osSemaphoreDef_t *semaphore_def, int32_t count) { + OS_ID sem; + + if (semaphore_def == NULL) { + sysThreadError(osErrorParameter); + return NULL; + } + + sem = semaphore_def->semaphore; + if (sem == NULL) { + sysThreadError(osErrorParameter); + return NULL; + } + + if (((P_SCB)sem)->cb_type != 0U) { + sysThreadError(osErrorParameter); + return NULL; + } + + if (count > osFeature_Semaphore) { + sysThreadError(osErrorValue); + return NULL; + } + + rt_sem_init(sem, (uint16_t)count); // Initialize Semaphore + + return sem; +} + +/// Wait until a Semaphore becomes available +int32_t svcSemaphoreWait (osSemaphoreId semaphore_id, uint32_t millisec) { + OS_ID sem; + OS_RESULT res; + + sem = rt_id2obj(semaphore_id); + if (sem == NULL) { + return -1; + } + + if (((P_SCB)sem)->cb_type != SCB) { + return -1; + } + + res = rt_sem_wait(sem, rt_ms2tick(millisec)); // Wait for Semaphore + + if (res == OS_R_TMO) { return 0; } // Timeout + + return (int32_t)(((P_SCB)sem)->tokens + 1U); +} + +/// Release a Semaphore +osStatus svcSemaphoreRelease (osSemaphoreId semaphore_id) { + OS_ID sem; + + sem = rt_id2obj(semaphore_id); + if (sem == NULL) { + return osErrorParameter; + } + + if (((P_SCB)sem)->cb_type != SCB) { + return osErrorParameter; + } + + if ((int32_t)((P_SCB)sem)->tokens == osFeature_Semaphore) { + return osErrorResource; + } + + rt_sem_send(sem); // Release Semaphore + + return osOK; +} + +/// Delete a Semaphore that was created by osSemaphoreCreate +osStatus svcSemaphoreDelete (osSemaphoreId semaphore_id) { + OS_ID sem; + + sem = rt_id2obj(semaphore_id); + if (sem == NULL) { + return osErrorParameter; + } + + if (((P_SCB)sem)->cb_type != SCB) { + return osErrorParameter; + } + + rt_sem_delete(sem); // Delete Semaphore + + return osOK; +} + + +// Semaphore ISR Calls + +/// Release a Semaphore +osStatus isrSemaphoreRelease (osSemaphoreId semaphore_id) { + OS_ID sem; + + sem = rt_id2obj(semaphore_id); + if (sem == NULL) { + return osErrorParameter; + } + + if (((P_SCB)sem)->cb_type != SCB) { + return osErrorParameter; + } + + if ((int32_t)((P_SCB)sem)->tokens == osFeature_Semaphore) { + return osErrorResource; + } + + isr_sem_send(sem); // Release Semaphore + + return osOK; +} + + +// Semaphore Public API + +/// Create and Initialize a Semaphore object +osSemaphoreId osSemaphoreCreate (const osSemaphoreDef_t *semaphore_def, int32_t count) { + if (__exceptional_mode()) { + return NULL; // Not allowed in ISR + } + if ((__get_mode() != MODE_USR) && (os_running == 0U)) { + // Privileged and not running + return svcSemaphoreCreate(semaphore_def, count); + } else { + return __svcSemaphoreCreate(semaphore_def, count); + } +} + +/// Wait until a Semaphore becomes available +int32_t osSemaphoreWait (osSemaphoreId semaphore_id, uint32_t millisec) { + if (__exceptional_mode()) { + return -1; // Not allowed in ISR + } + return __svcSemaphoreWait(semaphore_id, millisec); +} + +/// Release a Semaphore +osStatus osSemaphoreRelease (osSemaphoreId semaphore_id) { + if (__exceptional_mode()) { // in ISR + return isrSemaphoreRelease(semaphore_id); + } else { // in Thread + return __svcSemaphoreRelease(semaphore_id); + } +} + +/// Delete a Semaphore that was created by osSemaphoreCreate +osStatus osSemaphoreDelete (osSemaphoreId semaphore_id) { + if (__exceptional_mode()) { + return osErrorISR; // Not allowed in ISR + } + return __svcSemaphoreDelete(semaphore_id); +} + + +// ==== Memory Management Functions ==== + +// Memory Management Helper Functions + +// Clear Memory Box (Zero init) +static void rt_clr_box (void *box_mem, void *box) { + uint32_t *p, n; + + if ((box_mem != NULL) && (box != NULL)) { + p = box; + for (n = ((P_BM)box_mem)->blk_size; n; n -= 4U) { + *p++ = 0U; + } + } +} + +// Memory Management Service Calls declarations +SVC_1_1(svcPoolCreate, osPoolId, const osPoolDef_t *, RET_pointer) +SVC_1_1(sysPoolAlloc, void *, osPoolId, RET_pointer) +SVC_2_1(sysPoolFree, osStatus, osPoolId, void *, RET_osStatus) + +// Memory Management Service & ISR Calls + +/// Create and Initialize memory pool +osPoolId svcPoolCreate (const osPoolDef_t *pool_def) { + uint32_t blk_sz; + + if ((pool_def == NULL) || + (pool_def->pool_sz == 0U) || + (pool_def->item_sz == 0U) || + (pool_def->pool == NULL)) { + sysThreadError(osErrorParameter); + return NULL; + } + + blk_sz = (pool_def->item_sz + 3U) & (uint32_t)~3U; + + _init_box(pool_def->pool, sizeof(struct OS_BM) + (pool_def->pool_sz * blk_sz), blk_sz); + + return pool_def->pool; +} + +/// Allocate a memory block from a memory pool +void *sysPoolAlloc (osPoolId pool_id) { + void *mem; + + if (pool_id == NULL) { + return NULL; + } + + mem = rt_alloc_box(pool_id); + + return mem; +} + +/// Return an allocated memory block back to a specific memory pool +osStatus sysPoolFree (osPoolId pool_id, void *block) { + uint32_t res; + + if (pool_id == NULL) { + return osErrorParameter; + } + + res = rt_free_box(pool_id, block); + if (res != 0) { + return osErrorValue; + } + + return osOK; +} + + +// Memory Management Public API + +/// Create and Initialize memory pool +osPoolId osPoolCreate (const osPoolDef_t *pool_def) { + if (__exceptional_mode()) { + return NULL; // Not allowed in ISR + } + if ((__get_mode() != MODE_USR) && (os_running == 0U)) { + // Privileged and not running + return svcPoolCreate(pool_def); + } else { + return __svcPoolCreate(pool_def); + } +} + +/// Allocate a memory block from a memory pool +void *osPoolAlloc (osPoolId pool_id) { + if (__get_mode() != MODE_USR) { // in ISR or Privileged + return sysPoolAlloc(pool_id); + } else { // in Thread + return __sysPoolAlloc(pool_id); + } +} + +/// Allocate a memory block from a memory pool and set memory block to zero +void *osPoolCAlloc (osPoolId pool_id) { + void *mem; + + if (__get_mode() != MODE_USR) { // in ISR or Privileged + mem = sysPoolAlloc(pool_id); + } else { // in Thread + mem = __sysPoolAlloc(pool_id); + } + + rt_clr_box(pool_id, mem); + + return mem; +} + +/// Return an allocated memory block back to a specific memory pool +osStatus osPoolFree (osPoolId pool_id, void *block) { + if (__get_mode() != MODE_USR) { // in ISR or Privileged + return sysPoolFree(pool_id, block); + } else { // in Thread + return __sysPoolFree(pool_id, block); + } +} + + +// ==== Message Queue Management Functions ==== + +// Message Queue Management Service Calls declarations +SVC_2_1(svcMessageCreate, osMessageQId, const osMessageQDef_t *, osThreadId, RET_pointer) +SVC_3_1(svcMessagePut, osStatus, osMessageQId, uint32_t, uint32_t, RET_osStatus) +SVC_2_3(svcMessageGet, os_InRegs osEvent, osMessageQId, uint32_t, RET_osEvent) + +// Message Queue Service Calls + +/// Create and Initialize Message Queue +osMessageQId svcMessageCreate (const osMessageQDef_t *queue_def, osThreadId thread_id) { + + if ((queue_def == NULL) || + (queue_def->queue_sz == 0U) || + (queue_def->pool == NULL)) { + sysThreadError(osErrorParameter); + return NULL; + } + + if (((P_MCB)queue_def->pool)->cb_type != 0U) { + sysThreadError(osErrorParameter); + return NULL; + } + + rt_mbx_init(queue_def->pool, (uint16_t)(4U*(queue_def->queue_sz + 4U))); + + return queue_def->pool; +} + +/// Put a Message to a Queue +osStatus svcMessagePut (osMessageQId queue_id, uint32_t info, uint32_t millisec) { + OS_RESULT res; + + if (queue_id == NULL) { + return osErrorParameter; + } + + if (((P_MCB)queue_id)->cb_type != MCB) { + return osErrorParameter; + } + + res = rt_mbx_send(queue_id, (void *)info, rt_ms2tick(millisec)); + + if (res == OS_R_TMO) { + return ((millisec != 0U) ? osErrorTimeoutResource : osErrorResource); + } + + return osOK; +} + +/// Get a Message or Wait for a Message from a Queue +os_InRegs osEvent_type svcMessageGet (osMessageQId queue_id, uint32_t millisec) { + OS_RESULT res; + osEvent ret; + + if (queue_id == NULL) { + ret.status = osErrorParameter; + return osEvent_ret_status; + } + + if (((P_MCB)queue_id)->cb_type != MCB) { + ret.status = osErrorParameter; + return osEvent_ret_status; + } + + res = rt_mbx_wait(queue_id, &ret.value.p, rt_ms2tick(millisec)); + + if (res == OS_R_TMO) { + ret.status = (millisec != 0U) ? osEventTimeout : osOK; + return osEvent_ret_value; + } + + ret.status = osEventMessage; + + return osEvent_ret_value; +} + + +// Message Queue ISR Calls + +/// Put a Message to a Queue +osStatus isrMessagePut (osMessageQId queue_id, uint32_t info, uint32_t millisec) { + + if ((queue_id == NULL) || (millisec != 0U)) { + return osErrorParameter; + } + + if (((P_MCB)queue_id)->cb_type != MCB) { + return osErrorParameter; + } + + if (rt_mbx_check(queue_id) == 0U) { // Check if Queue is full + return osErrorResource; + } + + isr_mbx_send(queue_id, (void *)info); + + return osOK; +} + +/// Get a Message or Wait for a Message from a Queue +os_InRegs osEvent isrMessageGet (osMessageQId queue_id, uint32_t millisec) { + OS_RESULT res; + osEvent ret; + + if ((queue_id == NULL) || (millisec != 0U)) { + ret.status = osErrorParameter; + return ret; + } + + if (((P_MCB)queue_id)->cb_type != MCB) { + ret.status = osErrorParameter; + return ret; + } + + res = isr_mbx_receive(queue_id, &ret.value.p); + + if (res != OS_R_MBX) { + ret.status = osOK; + return ret; + } + + ret.status = osEventMessage; + + return ret; +} + + +// Message Queue Management Public API + +/// Create and Initialize Message Queue +osMessageQId osMessageCreate (const osMessageQDef_t *queue_def, osThreadId thread_id) { + if (__exceptional_mode()) { + return NULL; // Not allowed in ISR + } + if ((__get_mode() != MODE_USR) && (os_running == 0U)) { + // Privileged and not running + return svcMessageCreate(queue_def, thread_id); + } else { + return __svcMessageCreate(queue_def, thread_id); + } +} + +/// Put a Message to a Queue +osStatus osMessagePut (osMessageQId queue_id, uint32_t info, uint32_t millisec) { + if (__exceptional_mode()) { // in ISR + return isrMessagePut(queue_id, info, millisec); + } else { // in Thread + return __svcMessagePut(queue_id, info, millisec); + } +} + +/// Get a Message or Wait for a Message from a Queue +os_InRegs osEvent osMessageGet (osMessageQId queue_id, uint32_t millisec) { + if (__exceptional_mode()) { // in ISR + return isrMessageGet(queue_id, millisec); + } else { // in Thread + return __svcMessageGet(queue_id, millisec); + } +} + + +// ==== Mail Queue Management Functions ==== + +// Mail Queue Management Service Calls declarations +SVC_2_1(svcMailCreate, osMailQId, const osMailQDef_t *, osThreadId, RET_pointer) +SVC_3_1(sysMailAlloc, void *, osMailQId, uint32_t, uint32_t, RET_pointer) +SVC_3_1(sysMailFree, osStatus, osMailQId, void *, uint32_t, RET_osStatus) + +// Mail Queue Management Service & ISR Calls + +/// Create and Initialize mail queue +osMailQId svcMailCreate (const osMailQDef_t *queue_def, osThreadId thread_id) { + uint32_t blk_sz; + P_MCB pmcb; + void *pool; + + if ((queue_def == NULL) || + (queue_def->queue_sz == 0U) || + (queue_def->item_sz == 0U) || + (queue_def->pool == NULL)) { + sysThreadError(osErrorParameter); + return NULL; + } + + pmcb = *(((void **)queue_def->pool) + 0); + pool = *(((void **)queue_def->pool) + 1); + + if ((pool == NULL) || (pmcb == NULL) || (pmcb->cb_type != 0U)) { + sysThreadError(osErrorParameter); + return NULL; + } + + blk_sz = (queue_def->item_sz + 3U) & (uint32_t)~3U; + + _init_box(pool, sizeof(struct OS_BM) + (queue_def->queue_sz * blk_sz), blk_sz); + + rt_mbx_init(pmcb, (uint16_t)(4U*(queue_def->queue_sz + 4U))); + + return queue_def->pool; +} + +/// Allocate a memory block from a mail +void *sysMailAlloc (osMailQId queue_id, uint32_t millisec, uint32_t isr) { + P_MCB pmcb; + void *pool; + void *mem; + + if (queue_id == NULL) { + return NULL; + } + + pmcb = *(((void **)queue_id) + 0); + pool = *(((void **)queue_id) + 1); + + if ((pool == NULL) || (pmcb == NULL)) { + return NULL; + } + + if ((isr != 0U) && (millisec != 0U)) { + return NULL; + } + + mem = rt_alloc_box(pool); + + if ((mem == NULL) && (millisec != 0U)) { + // Put Task to sleep when Memory not available + if (pmcb->p_lnk != NULL) { + rt_put_prio((P_XCB)pmcb, os_tsk.run); + } else { + pmcb->p_lnk = os_tsk.run; + os_tsk.run->p_lnk = NULL; + os_tsk.run->p_rlnk = (P_TCB)pmcb; + // Task is waiting to allocate a message + pmcb->state = 3U; + } + rt_block(rt_ms2tick(millisec), WAIT_MBX); + } + + return mem; +} + +/// Free a memory block from a mail +osStatus sysMailFree (osMailQId queue_id, void *mail, uint32_t isr) { + P_MCB pmcb; + P_TCB ptcb; + void *pool; + void *mem; + uint32_t res; + + if (queue_id == NULL) { + return osErrorParameter; + } + + pmcb = *(((void **)queue_id) + 0); + pool = *(((void **)queue_id) + 1); + + if ((pmcb == NULL) || (pool == NULL)) { + return osErrorParameter; + } + + res = rt_free_box(pool, mail); + + if (res != 0U) { + return osErrorValue; + } + + if ((pmcb->p_lnk != NULL) && (pmcb->state == 3U)) { + // Task is waiting to allocate a message + if (isr != 0U) { + rt_psq_enq (pmcb, (U32)pool); + rt_psh_req (); + } else { + mem = rt_alloc_box(pool); + if (mem != NULL) { + ptcb = rt_get_first((P_XCB)pmcb); + rt_ret_val(ptcb, (U32)mem); + rt_rmv_dly(ptcb); + rt_dispatch(ptcb); + } + } + } + + return osOK; +} + + +// Mail Queue Management Public API + +/// Create and Initialize mail queue +osMailQId osMailCreate (const osMailQDef_t *queue_def, osThreadId thread_id) { + if (__exceptional_mode()) { + return NULL; // Not allowed in ISR + } + if ((__get_mode() != MODE_USR) && (os_running == 0U)) { + // Privileged and not running + return svcMailCreate(queue_def, thread_id); + } else { + return __svcMailCreate(queue_def, thread_id); + } +} + +/// Allocate a memory block from a mail +void *osMailAlloc (osMailQId queue_id, uint32_t millisec) { + if (__exceptional_mode()) { // in ISR + return sysMailAlloc(queue_id, millisec, 1U); + } else { // in Thread + return __sysMailAlloc(queue_id, millisec, 0U); + } +} + +/// Allocate a memory block from a mail and set memory block to zero +void *osMailCAlloc (osMailQId queue_id, uint32_t millisec) { + void *pool; + void *mem; + + if (__exceptional_mode()) { // in ISR + mem = sysMailAlloc(queue_id, millisec, 1U); + } else { // in Thread + mem = __sysMailAlloc(queue_id, millisec, 0U); + } + + pool = *(((void **)queue_id) + 1); + + rt_clr_box(pool, mem); + + return mem; +} + +/// Free a memory block from a mail +osStatus osMailFree (osMailQId queue_id, void *mail) { + if (__exceptional_mode()) { // in ISR + return sysMailFree(queue_id, mail, 1U); + } else { // in Thread + return __sysMailFree(queue_id, mail, 0U); + } +} + +/// Put a mail to a queue +osStatus osMailPut (osMailQId queue_id, void *mail) { + if (queue_id == NULL) { + return osErrorParameter; + } + if (mail == NULL) { + return osErrorValue; + } + return osMessagePut(*((void **)queue_id), (uint32_t)mail, 0U); +} + +#ifdef __CC_ARM +#pragma push +#pragma Ospace +#endif // __arm__ +/// Get a mail from a queue +os_InRegs osEvent osMailGet (osMailQId queue_id, uint32_t millisec) { + osEvent ret; + + if (queue_id == NULL) { + ret.status = osErrorParameter; + return ret; + } + + ret = osMessageGet(*((void **)queue_id), millisec); + if (ret.status == osEventMessage) ret.status = osEventMail; + + return ret; +} +#ifdef __CC_ARM +#pragma pop +#endif // __arm__ + + +// ==== RTX Extensions ==== + +// Service Calls declarations +SVC_0_1(rt_suspend, uint32_t, RET_uint32_t) +SVC_1_0(rt_resume, void, uint32_t) + + +// Public API + +/// Suspends the OS task scheduler +uint32_t os_suspend (void) { + return __rt_suspend(); +} + +/// Resumes the OS task scheduler +void os_resume (uint32_t sleep_time) { + __rt_resume(sleep_time); +} diff --git a/rtos/rtx/TARGET_CORTEX_A/rt_Event.c b/rtos/rtx/TARGET_CORTEX_A/rt_Event.c new file mode 100644 index 00000000000..e1a55410ce0 --- /dev/null +++ b/rtos/rtx/TARGET_CORTEX_A/rt_Event.c @@ -0,0 +1,194 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: RT_EVENT.C + * Purpose: Implements waits and wake-ups for event flags + * Rev.: V4.79 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 ARM Germany GmbH + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Config.h" +#include "rt_System.h" +#include "rt_Event.h" +#include "rt_List.h" +#include "rt_Task.h" +#ifdef __CORTEX_A9 +#include "rt_HAL_CA.h" +#else +#include "rt_HAL_CM.h" +#endif + + +/*---------------------------------------------------------------------------- + * Functions + *---------------------------------------------------------------------------*/ + + +/*--------------------------- rt_evt_wait -----------------------------------*/ + +OS_RESULT rt_evt_wait (U16 wait_flags, U16 timeout, BOOL and_wait) { + /* Wait for one or more event flags with optional time-out. */ + /* "wait_flags" identifies the flags to wait for. */ + /* "timeout" is the time-out limit in system ticks (0xffff if no time-out) */ + /* "and_wait" specifies the AND-ing of "wait_flags" as condition to be met */ + /* to complete the wait. (OR-ing if set to 0). */ + U32 block_state; + + if (and_wait) { + /* Check for AND-connected events */ + if ((os_tsk.run->events & wait_flags) == wait_flags) { + os_tsk.run->events &= ~wait_flags; + return (OS_R_EVT); + } + block_state = WAIT_AND; + } + else { + /* Check for OR-connected events */ + if (os_tsk.run->events & wait_flags) { + os_tsk.run->waits = os_tsk.run->events & wait_flags; + os_tsk.run->events &= ~wait_flags; + return (OS_R_EVT); + } + block_state = WAIT_OR; + } + /* Task has to wait */ + os_tsk.run->waits = wait_flags; + rt_block (timeout, (U8)block_state); + return (OS_R_TMO); +} + + +/*--------------------------- rt_evt_set ------------------------------------*/ + +void rt_evt_set (U16 event_flags, OS_TID task_id) { + /* Set one or more event flags of a selectable task. */ + P_TCB p_tcb; + + p_tcb = os_active_TCB[task_id-1U]; + if (p_tcb == NULL) { + return; + } + p_tcb->events |= event_flags; + event_flags = p_tcb->waits; + /* If the task is not waiting for an event, it should not be put */ + /* to ready state. */ + if (p_tcb->state == WAIT_AND) { + /* Check for AND-connected events */ + if ((p_tcb->events & event_flags) == event_flags) { + goto wkup; + } + } + if (p_tcb->state == WAIT_OR) { + /* Check for OR-connected events */ + if (p_tcb->events & event_flags) { + p_tcb->waits &= p_tcb->events; +wkup: p_tcb->events &= ~event_flags; + rt_rmv_dly (p_tcb); + p_tcb->state = READY; +#ifdef __CMSIS_RTOS + rt_ret_val2(p_tcb, 0x08U/*osEventSignal*/, p_tcb->waits); +#else + rt_ret_val (p_tcb, OS_R_EVT); +#endif + rt_dispatch (p_tcb); + } + } +} + + +/*--------------------------- rt_evt_clr ------------------------------------*/ + +void rt_evt_clr (U16 clear_flags, OS_TID task_id) { + /* Clear one or more event flags (identified by "clear_flags") of a */ + /* selectable task (identified by "task"). */ + P_TCB task = os_active_TCB[task_id-1U]; + + if (task == NULL) { + return; + } + task->events &= ~clear_flags; +} + + +/*--------------------------- isr_evt_set -----------------------------------*/ + +void isr_evt_set (U16 event_flags, OS_TID task_id) { + /* Same function as "os_evt_set", but to be called by ISRs. */ + P_TCB p_tcb = os_active_TCB[task_id-1U]; + + if (p_tcb == NULL) { + return; + } + rt_psq_enq (p_tcb, event_flags); + rt_psh_req (); +} + + +/*--------------------------- rt_evt_get ------------------------------------*/ + +U16 rt_evt_get (void) { + /* Get events of a running task after waiting for OR connected events. */ + return (os_tsk.run->waits); +} + + +/*--------------------------- rt_evt_psh ------------------------------------*/ + +void rt_evt_psh (P_TCB p_CB, U16 set_flags) { + /* Check if task has to be waken up */ + U16 event_flags; + + p_CB->events |= set_flags; + event_flags = p_CB->waits; + if (p_CB->state == WAIT_AND) { + /* Check for AND-connected events */ + if ((p_CB->events & event_flags) == event_flags) { + goto rdy; + } + } + if (p_CB->state == WAIT_OR) { + /* Check for OR-connected events */ + if (p_CB->events & event_flags) { + p_CB->waits &= p_CB->events; +rdy: p_CB->events &= ~event_flags; + rt_rmv_dly (p_CB); + p_CB->state = READY; +#ifdef __CMSIS_RTOS + rt_ret_val2(p_CB, 0x08U/*osEventSignal*/, p_CB->waits); +#else + rt_ret_val (p_CB, OS_R_EVT); +#endif + rt_put_prio (&os_rdy, p_CB); + } + } +} + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ diff --git a/rtos/rtx/TARGET_CORTEX_A/rt_Event.h b/rtos/rtx/TARGET_CORTEX_A/rt_Event.h new file mode 100644 index 00000000000..b3c4e597bd1 --- /dev/null +++ b/rtos/rtx/TARGET_CORTEX_A/rt_Event.h @@ -0,0 +1,45 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: RT_EVENT.H + * Purpose: Implements waits and wake-ups for event flags + * Rev.: V4.70 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2013 ARM Germany GmbH + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + +/* Functions */ +extern OS_RESULT rt_evt_wait (U16 wait_flags, U16 timeout, BOOL and_wait); +extern void rt_evt_set (U16 event_flags, OS_TID task_id); +extern void rt_evt_clr (U16 clear_flags, OS_TID task_id); +extern void isr_evt_set (U16 event_flags, OS_TID task_id); +extern U16 rt_evt_get (void); +extern void rt_evt_psh (P_TCB p_CB, U16 set_flags); + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ diff --git a/rtos/rtx/TARGET_CORTEX_A/rt_HAL_CA.h b/rtos/rtx/TARGET_CORTEX_A/rt_HAL_CA.h new file mode 100644 index 00000000000..a5176662627 --- /dev/null +++ b/rtos/rtx/TARGET_CORTEX_A/rt_HAL_CA.h @@ -0,0 +1,251 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: RT_HAL_CA.H + * Purpose: Hardware Abstraction Layer for Cortex-A definitions + * Rev.: V4.79 plus changes for RTX-Ax + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 ARM Germany GmbH, 2012-2016 ARM Limited + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + +/* Definitions */ +#define INIT_CPSR_SYS 0x4000001F +#define INIT_CPSR_USER 0x40000010 + +#define CPSR_T_BIT 0x20 +#define CPSR_I_BIT 0x80 +#define CPSR_F_BIT 0x40 + +#define MODE_USR 0x10 +#define MODE_FIQ 0x11 +#define MODE_IRQ 0x12 +#define MODE_SVC 0x13 +#define MODE_ABT 0x17 +#define MODE_UND 0x1B +#define MODE_SYS 0x1F + +#define MAGIC_WORD 0xE25A2EA5 +#define MAGIC_PATTERN 0xCCCCCCCC + +#include "core_ca9.h" + +#if defined (__CC_ARM) /* ARM Compiler */ + +#if ((defined(__TARGET_ARCH_7_M) || defined(__TARGET_ARCH_7E_M) || defined(__TARGET_ARCH_7_A)) && !defined(NO_EXCLUSIVE_ACCESS)) + #define __USE_EXCLUSIVE_ACCESS +#else + #undef __USE_EXCLUSIVE_ACCESS +#endif + +/* Supress __ldrex and __strex deprecated warnings - "#3731-D: intrinsic is deprecated" */ +#ifdef __USE_EXCLUSIVE_ACCESS +#pragma diag_suppress 3731 +#endif + +#elif defined (__GNUC__) /* GNU Compiler */ + +#undef __USE_EXCLUSIVE_ACCESS + +#if defined (__VFP_FP__) && !defined(__SOFTFP__) +#define __TARGET_FPU_VFP 1 +#else +#define __TARGET_FPU_VFP 0 +#endif + +#define __inline inline +#define __weak __attribute__((weak)) + +#elif defined (__ICCARM__) /* IAR Compiler */ + +//#error IAR Compiler support not implemented for Cortex-A + +#endif + +static U8 priority = 0xffU; + +extern const U32 GICDistributor_BASE; +extern const U32 GICInterface_BASE; + +/* GIC registers - Distributor */ +#define GICD_ICDICER0 (*((volatile U32 *)(GICDistributor_BASE + 0x180))) /* - RW - Interrupt Clear-Enable Registers */ +#define GICD_ICDISER0 (*((volatile U32 *)(GICDistributor_BASE + 0x100))) /* - RW - Interrupt Set-Enable Registers */ +#define GICD_ICDIPR0 (*((volatile U32 *)(GICDistributor_BASE + 0x400))) /* - RW - Interrupt Priority Registers */ +#define GICD_ICDSGIR (*((volatile U32 *)(GICDistributor_BASE + 0xf00))) /* - RW - Interrupt Software Interrupt Register */ +#define GICD_ICDICERx(irq) *(volatile U32 *)(&GICD_ICDICER0 + irq/32) +#define GICD_ICDISERx(irq) *(volatile U32 *)(&GICD_ICDISER0 + irq/32) + +/* GIC register - CPU Interface */ +#define GICI_ICCPMR (*((volatile U32 *)(GICInterface_BASE + 0x004))) /* - RW - Interrupt Priority Mask Register */ + +#define SGI_PENDSV 0U /* SGI0 */ +#define SGI_PENDSV_BIT ((U32)(1U << (SGI_PENDSV & 0xfU))) + +//Increase priority filter to prevent timer and PendSV interrupts signaling. Guarantees that interrupts will not be forwarded. +#if defined (__ICCARM__) +#define OS_LOCK() int irq_dis = __disable_irq_iar();\ + priority = GICI_ICCPMR; \ + GICI_ICCPMR = 0xff; \ + GICI_ICCPMR = GICI_ICCPMR - 1; \ + __DSB();\ + if(!irq_dis) __enable_irq(); \ + +#else +#define OS_LOCK() int irq_dis = __disable_irq();\ + priority = GICI_ICCPMR; \ + GICI_ICCPMR = 0xff; \ + GICI_ICCPMR = GICI_ICCPMR - 1; \ + __DSB();\ + if(!irq_dis) __enable_irq(); \ + +#endif + +//Restore priority filter. Re-enable timer and PendSV signaling +#define OS_UNLOCK() __DSB(); \ + GICI_ICCPMR = priority; \ + +#define OS_PEND_IRQ() GICD_ICDSGIR = 0x0010000 | SGI_PENDSV +#define OS_PEND(fl,p) if(p) OS_PEND_IRQ(); +#define OS_UNPEND(fl) + +/* HW initialization needs to be done in os_tick_init() in RTX_Conf_CM.c + * OS_X_INIT enables the IRQ n in the GIC */ +#define OS_X_INIT(n) volatile char *reg; \ + reg = (char *)(&GICD_ICDIPR0 + n / 4); \ + reg += n % 4; \ + *reg = (char)0xff; \ + *reg = *reg - 1; \ + GICD_ICDISERx(n) = (U32)(1U << n % 32); +#define OS_X_LOCK(n) OS_LOCK() +#define OS_X_UNLOCK(n) OS_UNLOCK() +#define OS_X_PEND_IRQ() OS_PEND_IRQ() +#define OS_X_PEND(fl,p) if(p) OS_X_PEND_IRQ(); +#define OS_X_UNPEND(fl) + + +/* Functions */ +#ifdef __USE_EXCLUSIVE_ACCESS + #define rt_inc(p) while(__strex((__ldrex(p)+1U),p)) + #define rt_dec(p) while(__strex((__ldrex(p)-1U),p)) +#else +#if defined (__ICCARM__) + #define rt_inc(p) { int irq_dis = __disable_irq_iar();(*p)++;if(!irq_dis) __enable_irq(); } + #define rt_dec(p) { int irq_dis = __disable_irq_iar();(*p)--;if(!irq_dis) __enable_irq(); } +#else + #define rt_inc(p) { int irq_dis = __disable_irq();(*p)++;if(!irq_dis) __enable_irq(); } + #define rt_dec(p) { int irq_dis = __disable_irq();(*p)--;if(!irq_dis) __enable_irq(); } +#endif /* __ICCARM__ */ +#endif /* __USE_EXCLUSIVE_ACCESS */ + +__inline static U32 rt_inc_qi (U32 size, U8 *count, U8 *first) { + U32 cnt,c2; +#ifdef __USE_EXCLUSIVE_ACCESS + do { + if ((cnt = __ldrex(count)) == size) { + __clrex(); + return (cnt); } + } while (__strex(cnt+1U, count)); + do { + c2 = (cnt = __ldrex(first)) + 1U; + if (c2 == size) { c2 = 0U; } + } while (__strex(c2, first)); +#else + int irq_dis; + #if defined (__ICCARM__) + irq_dis = __disable_irq_iar(); + #else + irq_dis = __disable_irq(); + #endif /* __ICCARM__ */ + if ((cnt = *count) < size) { + *count = (U8)(cnt+1U); + c2 = (cnt = *first) + 1U; + if (c2 == size) { c2 = 0U; } + *first = (U8)c2; + } + if(!irq_dis) __enable_irq (); +#endif + return (cnt); +} + +__inline static void rt_systick_init (void) { + /* Cortex-A doesn't have a Systick. User needs to provide an alternative timer using RTX_Conf_CM configuration */ + /* HW initialization needs to be done in os_tick_init() in RTX_Conf_CM.c */ +} + +__inline static U32 rt_systick_val (void) { + /* Cortex-A doesn't have a Systick. User needs to provide an alternative timer using RTX_Conf_CM configuration */ + /* HW initialization needs to be done in os_tick_init() in RTX_Conf_CM.c */ + return 0U; +} + +__inline static U32 rt_systick_ovf (void) { + /* Cortex-A doesn't have a Systick. User needs to provide an alternative timer using RTX_Conf_CM configuration */ + /* HW initialization needs to be done in os_tick_init() in RTX_Conf_CM.c */ + return 0U; +} + +__inline static void rt_svc_init (void) { + /* Register pendSV - through SGI */ + volatile char *reg; + + reg = (char *)(&GICD_ICDIPR0 + SGI_PENDSV/4); + reg += SGI_PENDSV % 4U; + /* Write 0xff to read priority level */ + *reg = (char)0xff; + /* Read priority level and set the lowest possible*/ + *reg = *reg - 1; + + GICD_ICDISERx(SGI_PENDSV) = (U32)SGI_PENDSV_BIT; +} + +extern void rt_set_PSP (U32 stack); +extern U32 rt_get_PSP (void); +extern void os_set_env (P_TCB p_TCB); +extern void *_alloc_box (void *box_mem); +extern U32 _free_box (void *box_mem, void *box); + +extern void rt_init_stack (P_TCB p_TCB, FUNCP task_body); +extern void rt_ret_val (P_TCB p_TCB, U32 v0); +extern void rt_ret_val2 (P_TCB p_TCB, U32 v0, U32 v1); + +extern void dbg_init (void); +extern void dbg_task_notify (P_TCB p_tcb, BOOL create); +extern void dbg_task_switch (U32 task_id); + +#ifdef DBG_MSG +#define DBG_INIT() dbg_init() +#define DBG_TASK_NOTIFY(p_tcb,create) if (dbg_msg) dbg_task_notify(p_tcb,create) +#define DBG_TASK_SWITCH(task_id) if (dbg_msg && (os_tsk.new!=os_tsk.run)) \ + dbg_task_switch(task_id) +#else +#define DBG_INIT() +#define DBG_TASK_NOTIFY(p_tcb,create) +#define DBG_TASK_SWITCH(task_id) +#endif + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ diff --git a/rtos/rtx/TARGET_CORTEX_A/rt_HAL_CM.h b/rtos/rtx/TARGET_CORTEX_A/rt_HAL_CM.h new file mode 100644 index 00000000000..e3aefae22d6 --- /dev/null +++ b/rtos/rtx/TARGET_CORTEX_A/rt_HAL_CM.h @@ -0,0 +1,298 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: RT_HAL_CM.H + * Purpose: Hardware Abstraction Layer for Cortex-M definitions + * Rev.: V4.79 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 ARM Germany GmbH + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + +/* Definitions */ +#define INITIAL_xPSR 0x01000000U +#define DEMCR_TRCENA 0x01000000U +#define ITM_ITMENA 0x00000001U +#define MAGIC_WORD 0xE25A2EA5U +#define MAGIC_PATTERN 0xCCCCCCCCU + +#if defined (__CC_ARM) /* ARM Compiler */ + +#if ((defined(__TARGET_ARCH_7_M) || defined(__TARGET_ARCH_7E_M)) && !defined(NO_EXCLUSIVE_ACCESS)) + #define __USE_EXCLUSIVE_ACCESS +#else + #undef __USE_EXCLUSIVE_ACCESS +#endif + +/* Supress __ldrex and __strex deprecated warnings - "#3731-D: intrinsic is deprecated" */ +#ifdef __USE_EXCLUSIVE_ACCESS +#pragma diag_suppress 3731 +#endif + +#ifndef __CMSIS_GENERIC +#define __DMB() do {\ + __schedule_barrier();\ + __dmb(0xF);\ + __schedule_barrier();\ + } while (0) +#endif + +#elif defined (__GNUC__) /* GNU Compiler */ + +#undef __USE_EXCLUSIVE_ACCESS + +#if defined (__CORTEX_M0) +#define __TARGET_ARCH_6S_M +#endif + +#if defined (__VFP_FP__) && !defined(__SOFTFP__) +#define __TARGET_FPU_VFP +#endif + +#define __inline inline +#define __weak __attribute__((weak)) + +#ifndef __CMSIS_GENERIC + +__attribute__((always_inline)) static inline void __enable_irq(void) +{ + __asm volatile ("cpsie i"); +} + +__attribute__((always_inline)) static inline U32 __disable_irq(void) +{ + U32 result; + + __asm volatile ("mrs %0, primask" : "=r" (result)); + __asm volatile ("cpsid i"); + return(result & 1); +} + +__attribute__((always_inline)) static inline void __DMB(void) +{ + __asm volatile ("dmb 0xF":::"memory"); +} + +#endif + +__attribute__(( always_inline)) static inline U8 __clz(U32 value) +{ + U8 result; + + __asm volatile ("clz %0, %1" : "=r" (result) : "r" (value)); + return(result); +} + +#elif defined (__ICCARM__) /* IAR Compiler */ + +#undef __USE_EXCLUSIVE_ACCESS + +#if (__CORE__ == __ARM6M__) +#define __TARGET_ARCH_6S_M 1 +#endif + +#if defined __ARMVFP__ +#define __TARGET_FPU_VFP 1 +#endif + +#define __inline inline + +#ifndef __CMSIS_GENERIC + +static inline void __enable_irq(void) +{ + __asm volatile ("cpsie i"); +} + +static inline U32 __disable_irq(void) +{ + U32 result; + + __asm volatile ("mrs %0, primask" : "=r" (result)); + __asm volatile ("cpsid i"); + return(result & 1); +} + +#endif + +static inline U8 __clz(U32 value) +{ + U8 result; + + __asm volatile ("clz %0, %1" : "=r" (result) : "r" (value)); + return(result); +} + +#endif + +/* NVIC registers */ +#define NVIC_ST_CTRL (*((volatile U32 *)0xE000E010U)) +#define NVIC_ST_RELOAD (*((volatile U32 *)0xE000E014U)) +#define NVIC_ST_CURRENT (*((volatile U32 *)0xE000E018U)) +#define NVIC_ISER ((volatile U32 *)0xE000E100U) +#define NVIC_ICER ((volatile U32 *)0xE000E180U) +#if defined(__TARGET_ARCH_6S_M) +#define NVIC_IP ((volatile U32 *)0xE000E400U) +#else +#define NVIC_IP ((volatile U8 *)0xE000E400U) +#endif +#define NVIC_INT_CTRL (*((volatile U32 *)0xE000ED04U)) +#define NVIC_AIR_CTRL (*((volatile U32 *)0xE000ED0CU)) +#define NVIC_SYS_PRI2 (*((volatile U32 *)0xE000ED1CU)) +#define NVIC_SYS_PRI3 (*((volatile U32 *)0xE000ED20U)) + +#define OS_PEND_IRQ() NVIC_INT_CTRL = (1UL<<28) +#define OS_PENDING ((NVIC_INT_CTRL >> 26) & 5U) +#define OS_UNPEND(fl) NVIC_INT_CTRL = (U32)(fl = (U8)OS_PENDING) << 25 +#define OS_PEND(fl,p) NVIC_INT_CTRL = (U32)(fl | (U8)(p<<2)) << 26 +#define OS_LOCK() NVIC_ST_CTRL = 0x0005U +#define OS_UNLOCK() NVIC_ST_CTRL = 0x0007U + +#define OS_X_PENDING ((NVIC_INT_CTRL >> 28) & 1U) +#define OS_X_UNPEND(fl) NVIC_INT_CTRL = (U32)(fl = (U8)OS_X_PENDING) << 27 +#define OS_X_PEND(fl,p) NVIC_INT_CTRL = (U32)(fl | p) << 28 +#if defined(__TARGET_ARCH_6S_M) +#define OS_X_INIT(n) NVIC_IP[n>>2] |= (U32)0xFFU << ((n & 0x03U) << 3); \ + NVIC_ISER[n>>5] = (U32)1U << (n & 0x1FU) +#else +#define OS_X_INIT(n) NVIC_IP[n] = 0xFFU; \ + NVIC_ISER[n>>5] = (U32)1U << (n & 0x1FU) +#endif +#define OS_X_LOCK(n) NVIC_ICER[n>>5] = (U32)1U << (n & 0x1FU) +#define OS_X_UNLOCK(n) NVIC_ISER[n>>5] = (U32)1U << (n & 0x1FU) + +/* Core Debug registers */ +#define DEMCR (*((volatile U32 *)0xE000EDFCU)) + +/* ITM registers */ +#define ITM_CONTROL (*((volatile U32 *)0xE0000E80U)) +#define ITM_ENABLE (*((volatile U32 *)0xE0000E00U)) +#define ITM_PORT30_U32 (*((volatile U32 *)0xE0000078U)) +#define ITM_PORT31_U32 (*((volatile U32 *)0xE000007CU)) +#define ITM_PORT31_U16 (*((volatile U16 *)0xE000007CU)) +#define ITM_PORT31_U8 (*((volatile U8 *)0xE000007CU)) + +/* Variables */ +extern BIT dbg_msg; + +/* Functions */ +#ifdef __USE_EXCLUSIVE_ACCESS + #define rt_inc(p) while(__strex((__ldrex(p)+1U),p)) + #define rt_dec(p) while(__strex((__ldrex(p)-1U),p)) +#else + #define rt_inc(p) __disable_irq();(*p)++;__enable_irq(); + #define rt_dec(p) __disable_irq();(*p)--;__enable_irq(); +#endif + +__inline static U32 rt_inc_qi (U32 size, U8 *count, U8 *first) { + U32 cnt,c2; +#ifdef __USE_EXCLUSIVE_ACCESS + do { + if ((cnt = __ldrex(count)) == size) { + __clrex(); + return (cnt); } + } while (__strex(cnt+1U, count)); + do { + c2 = (cnt = __ldrex(first)) + 1U; + if (c2 == size) { c2 = 0U; } + } while (__strex(c2, first)); +#else + __disable_irq(); + if ((cnt = *count) < size) { + *count = (U8)(cnt+1U); + c2 = (cnt = *first) + 1U; + if (c2 == size) { c2 = 0U; } + *first = (U8)c2; + } + __enable_irq (); +#endif + return (cnt); +} + +__inline static void rt_systick_init (void) { + NVIC_ST_RELOAD = os_trv; + NVIC_ST_CURRENT = 0U; + NVIC_ST_CTRL = 0x0007U; + NVIC_SYS_PRI3 |= 0xFF000000U; +} + +__inline static U32 rt_systick_val (void) { + return (os_trv - NVIC_ST_CURRENT); +} + +__inline static U32 rt_systick_ovf (void) { + return ((NVIC_INT_CTRL >> 26) & 1U); +} + +__inline static void rt_svc_init (void) { +#if !defined(__TARGET_ARCH_6S_M) + U32 sh,prigroup; +#endif + NVIC_SYS_PRI3 |= 0x00FF0000U; +#if defined(__TARGET_ARCH_6S_M) + NVIC_SYS_PRI2 |= (NVIC_SYS_PRI3<<(8+1)) & 0xFC000000U; +#else + sh = 8U - __clz(~((NVIC_SYS_PRI3 << 8) & 0xFF000000U)); + prigroup = ((NVIC_AIR_CTRL >> 8) & 0x07U); + if (prigroup >= sh) { + sh = prigroup + 1U; + } + +/* Only change the SVCall priority if uVisor is not present. */ +#if !(defined(FEATURE_UVISOR) && defined(TARGET_UVISOR_SUPPORTED)) + NVIC_SYS_PRI2 = ((0xFEFFFFFFU << sh) & 0xFF000000U) | (NVIC_SYS_PRI2 & 0x00FFFFFFU); +#endif /* !(defined(FEATURE_UVISOR) && defined(TARGET_UVISOR_SUPPORTED)) */ +#endif +} + +extern void rt_set_PSP (U32 stack); +extern U32 rt_get_PSP (void); +extern void os_set_env (void); +extern void *_alloc_box (void *box_mem); +extern U32 _free_box (void *box_mem, void *box); + +extern void rt_init_stack (P_TCB p_TCB, FUNCP task_body); +extern void rt_ret_val (P_TCB p_TCB, U32 v0); +extern void rt_ret_val2 (P_TCB p_TCB, U32 v0, U32 v1); + +extern void dbg_init (void); +extern void dbg_task_notify (P_TCB p_tcb, BOOL create); +extern void dbg_task_switch (U32 task_id); + +#ifdef DBG_MSG +#define DBG_INIT() dbg_init() +#define DBG_TASK_NOTIFY(p_tcb,create) if (dbg_msg) dbg_task_notify(p_tcb,create) +#define DBG_TASK_SWITCH(task_id) if (dbg_msg && (os_tsk.new_tsk!=os_tsk.run)) \ + dbg_task_switch(task_id) +#else +#define DBG_INIT() +#define DBG_TASK_NOTIFY(p_tcb,create) +#define DBG_TASK_SWITCH(task_id) +#endif + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ diff --git a/rtos/rtx/TARGET_CORTEX_A/rt_List.c b/rtos/rtx/TARGET_CORTEX_A/rt_List.c new file mode 100644 index 00000000000..0868b6cc6bf --- /dev/null +++ b/rtos/rtx/TARGET_CORTEX_A/rt_List.c @@ -0,0 +1,322 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: RT_LIST.C + * Purpose: Functions for the management of different lists + * Rev.: V4.79 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 ARM Germany GmbH + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Config.h" +#include "rt_System.h" +#include "rt_List.h" +#include "rt_Task.h" +#include "rt_Time.h" +#ifdef __CORTEX_A9 +#include "rt_HAL_CA.h" +#else +#include "rt_HAL_CM.h" +#endif + +/*---------------------------------------------------------------------------- + * Global Variables + *---------------------------------------------------------------------------*/ + +/* List head of chained ready tasks */ +struct OS_XCB os_rdy; +/* List head of chained delay tasks */ +struct OS_XCB os_dly; + + +/*---------------------------------------------------------------------------- + * Functions + *---------------------------------------------------------------------------*/ + + +/*--------------------------- rt_put_prio -----------------------------------*/ + +void rt_put_prio (P_XCB p_CB, P_TCB p_task) { + /* Put task identified with "p_task" into list ordered by priority. */ + /* "p_CB" points to head of list; list has always an element at end with */ + /* a priority less than "p_task->prio". */ + P_TCB p_CB2; + U32 prio; + BOOL sem_mbx = __FALSE; + + if ((p_CB->cb_type == SCB) || (p_CB->cb_type == MCB) || (p_CB->cb_type == MUCB)) { + sem_mbx = __TRUE; + } + prio = p_task->prio; + p_CB2 = p_CB->p_lnk; + /* Search for an entry in the list */ + while ((p_CB2 != NULL) && (prio <= p_CB2->prio)) { + p_CB = (P_XCB)p_CB2; + p_CB2 = p_CB2->p_lnk; + } + /* Entry found, insert the task into the list */ + p_task->p_lnk = p_CB2; + p_CB->p_lnk = p_task; + if (sem_mbx) { + if (p_CB2 != NULL) { + p_CB2->p_rlnk = p_task; + } + p_task->p_rlnk = (P_TCB)p_CB; + } + else { + p_task->p_rlnk = NULL; + } +} + + +/*--------------------------- rt_get_first ----------------------------------*/ + +P_TCB rt_get_first (P_XCB p_CB) { + /* Get task at head of list: it is the task with highest priority. */ + /* "p_CB" points to head of list. */ + P_TCB p_first; + + p_first = p_CB->p_lnk; + p_CB->p_lnk = p_first->p_lnk; + if ((p_CB->cb_type == SCB) || (p_CB->cb_type == MCB) || (p_CB->cb_type == MUCB)) { + if (p_first->p_lnk != NULL) { + p_first->p_lnk->p_rlnk = (P_TCB)p_CB; + p_first->p_lnk = NULL; + } + p_first->p_rlnk = NULL; + } + else { + p_first->p_lnk = NULL; + } + return (p_first); +} + + +/*--------------------------- rt_put_rdy_first ------------------------------*/ + +void rt_put_rdy_first (P_TCB p_task) { + /* Put task identified with "p_task" at the head of the ready list. The */ + /* task must have at least a priority equal to highest priority in list. */ + p_task->p_lnk = os_rdy.p_lnk; + p_task->p_rlnk = NULL; + os_rdy.p_lnk = p_task; +} + + +/*--------------------------- rt_get_same_rdy_prio --------------------------*/ + +P_TCB rt_get_same_rdy_prio (void) { + /* Remove a task of same priority from ready list if any exists. Other- */ + /* wise return NULL. */ + P_TCB p_first; + + p_first = os_rdy.p_lnk; + if (p_first->prio == os_tsk.run->prio) { + os_rdy.p_lnk = os_rdy.p_lnk->p_lnk; + return (p_first); + } + return (NULL); +} + + +/*--------------------------- rt_resort_prio --------------------------------*/ + +void rt_resort_prio (P_TCB p_task) { + /* Re-sort ordered lists after the priority of 'p_task' has changed. */ + P_TCB p_CB; + + if (p_task->p_rlnk == NULL) { + if (p_task->state == READY) { + /* Task is chained into READY list. */ + p_CB = (P_TCB)&os_rdy; + goto res; + } + } + else { + p_CB = p_task->p_rlnk; + while (p_CB->cb_type == TCB) { + /* Find a header of this task chain list. */ + p_CB = p_CB->p_rlnk; + } +res:rt_rmv_list (p_task); + rt_put_prio ((P_XCB)p_CB, p_task); + } +} + + +/*--------------------------- rt_put_dly ------------------------------------*/ + +void rt_put_dly (P_TCB p_task, U16 delay) { + /* Put a task identified with "p_task" into chained delay wait list using */ + /* a delay value of "delay". */ + P_TCB p; + U32 delta,idelay = delay; + + p = (P_TCB)&os_dly; + if (p->p_dlnk == NULL) { + /* Delay list empty */ + delta = 0U; + goto last; + } + delta = os_dly.delta_time; + while (delta < idelay) { + if (p->p_dlnk == NULL) { + /* End of list found */ +last: p_task->p_dlnk = NULL; + p->p_dlnk = p_task; + p_task->p_blnk = p; + p->delta_time = (U16)(idelay - delta); + p_task->delta_time = 0U; + return; + } + p = p->p_dlnk; + delta += p->delta_time; + } + /* Right place found */ + p_task->p_dlnk = p->p_dlnk; + p->p_dlnk = p_task; + p_task->p_blnk = p; + if (p_task->p_dlnk != NULL) { + p_task->p_dlnk->p_blnk = p_task; + } + p_task->delta_time = (U16)(delta - idelay); + p->delta_time -= p_task->delta_time; +} + + +/*--------------------------- rt_dec_dly ------------------------------------*/ + +void rt_dec_dly (void) { + /* Decrement delta time of list head: remove tasks having a value of zero.*/ + P_TCB p_rdy; + + if (os_dly.p_dlnk == NULL) { + return; + } + os_dly.delta_time--; + while ((os_dly.delta_time == 0U) && (os_dly.p_dlnk != NULL)) { + p_rdy = os_dly.p_dlnk; + if (p_rdy->p_rlnk != NULL) { + /* Task is really enqueued, remove task from semaphore/mailbox */ + /* timeout waiting list. */ + p_rdy->p_rlnk->p_lnk = p_rdy->p_lnk; + if (p_rdy->p_lnk != NULL) { + p_rdy->p_lnk->p_rlnk = p_rdy->p_rlnk; + p_rdy->p_lnk = NULL; + } + p_rdy->p_rlnk = NULL; + } + rt_put_prio (&os_rdy, p_rdy); + os_dly.delta_time = p_rdy->delta_time; + if (p_rdy->state == WAIT_ITV) { + /* Calculate the next time for interval wait. */ + p_rdy->delta_time = p_rdy->interval_time + (U16)os_time; + } + p_rdy->state = READY; + os_dly.p_dlnk = p_rdy->p_dlnk; + if (p_rdy->p_dlnk != NULL) { + p_rdy->p_dlnk->p_blnk = (P_TCB)&os_dly; + p_rdy->p_dlnk = NULL; + } + p_rdy->p_blnk = NULL; + } +} + + +/*--------------------------- rt_rmv_list -----------------------------------*/ + +void rt_rmv_list (P_TCB p_task) { + /* Remove task identified with "p_task" from ready, semaphore or mailbox */ + /* waiting list if enqueued. */ + P_TCB p_b; + + if (p_task->p_rlnk != NULL) { + /* A task is enqueued in semaphore / mailbox waiting list. */ + p_task->p_rlnk->p_lnk = p_task->p_lnk; + if (p_task->p_lnk != NULL) { + p_task->p_lnk->p_rlnk = p_task->p_rlnk; + } + return; + } + + p_b = (P_TCB)&os_rdy; + while (p_b != NULL) { + /* Search the ready list for task "p_task" */ + if (p_b->p_lnk == p_task) { + p_b->p_lnk = p_task->p_lnk; + return; + } + p_b = p_b->p_lnk; + } +} + + +/*--------------------------- rt_rmv_dly ------------------------------------*/ + +void rt_rmv_dly (P_TCB p_task) { + /* Remove task identified with "p_task" from delay list if enqueued. */ + P_TCB p_b; + + p_b = p_task->p_blnk; + if (p_b != NULL) { + /* Task is really enqueued */ + p_b->p_dlnk = p_task->p_dlnk; + if (p_task->p_dlnk != NULL) { + /* 'p_task' is in the middle of list */ + p_b->delta_time += p_task->delta_time; + p_task->p_dlnk->p_blnk = p_b; + p_task->p_dlnk = NULL; + } + else { + /* 'p_task' is at the end of list */ + p_b->delta_time = 0U; + } + p_task->p_blnk = NULL; + } +} + + +/*--------------------------- rt_psq_enq ------------------------------------*/ + +void rt_psq_enq (OS_ID entry, U32 arg) { + /* Insert post service request "entry" into ps-queue. */ + U32 idx; + + idx = rt_inc_qi (os_psq->size, &os_psq->count, &os_psq->first); + if (idx < os_psq->size) { + os_psq->q[idx].id = entry; + os_psq->q[idx].arg = arg; + } + else { + os_error (OS_ERR_FIFO_OVF); + } +} + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ diff --git a/rtos/rtx/TARGET_CORTEX_A/rt_List.h b/rtos/rtx/TARGET_CORTEX_A/rt_List.h new file mode 100644 index 00000000000..4d8b51a9f06 --- /dev/null +++ b/rtos/rtx/TARGET_CORTEX_A/rt_List.h @@ -0,0 +1,65 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: RT_LIST.H + * Purpose: Functions for the management of different lists + * Rev.: V4.79 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 ARM Germany GmbH + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + +/* Definitions */ + +/* Values for 'cb_type' */ +#define TCB 0U +#define MCB 1U +#define SCB 2U +#define MUCB 3U +#define HCB 4U + +/* Variables */ +extern struct OS_XCB os_rdy; +extern struct OS_XCB os_dly; + +/* Functions */ +extern void rt_put_prio (P_XCB p_CB, P_TCB p_task); +extern P_TCB rt_get_first (P_XCB p_CB); +extern void rt_put_rdy_first (P_TCB p_task); +extern P_TCB rt_get_same_rdy_prio (void); +extern void rt_resort_prio (P_TCB p_task); +extern void rt_put_dly (P_TCB p_task, U16 delay); +extern void rt_dec_dly (void); +extern void rt_rmv_list (P_TCB p_task); +extern void rt_rmv_dly (P_TCB p_task); +extern void rt_psq_enq (OS_ID entry, U32 arg); + +/* This is a fast macro generating in-line code */ +#define rt_rdy_prio(void) (os_rdy.p_lnk->prio) + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ diff --git a/rtos/rtx/TARGET_CORTEX_A/rt_Mailbox.c b/rtos/rtx/TARGET_CORTEX_A/rt_Mailbox.c new file mode 100644 index 00000000000..480b7809d6a --- /dev/null +++ b/rtos/rtx/TARGET_CORTEX_A/rt_Mailbox.c @@ -0,0 +1,297 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: RT_MAILBOX.C + * Purpose: Implements waits and wake-ups for mailbox messages + * Rev.: V4.79 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 ARM Germany GmbH + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Config.h" +#include "rt_System.h" +#include "rt_List.h" +#include "rt_Mailbox.h" +#include "rt_MemBox.h" +#include "rt_Task.h" +#ifdef __CORTEX_A9 +#include "rt_HAL_CA.h" +#else +#include "rt_HAL_CM.h" +#endif + + +/*---------------------------------------------------------------------------- + * Functions + *---------------------------------------------------------------------------*/ + + +/*--------------------------- rt_mbx_init -----------------------------------*/ + +void rt_mbx_init (OS_ID mailbox, U16 mbx_size) { + /* Initialize a mailbox */ + P_MCB p_MCB = mailbox; + + p_MCB->cb_type = MCB; + p_MCB->state = 0U; + p_MCB->isr_st = 0U; + p_MCB->p_lnk = NULL; + p_MCB->first = 0U; + p_MCB->last = 0U; + p_MCB->count = 0U; + p_MCB->size = (U16)((mbx_size - (sizeof(struct OS_MCB) - (sizeof(void *)))) + / sizeof(void *)); +} + + +/*--------------------------- rt_mbx_send -----------------------------------*/ + +OS_RESULT rt_mbx_send (OS_ID mailbox, void *p_msg, U16 timeout) { + /* Send message to a mailbox */ + P_MCB p_MCB = mailbox; + P_TCB p_TCB; + + if ((p_MCB->p_lnk != NULL) && (p_MCB->state == 1U)) { + /* A task is waiting for message */ + p_TCB = rt_get_first ((P_XCB)p_MCB); +#ifdef __CMSIS_RTOS + rt_ret_val2(p_TCB, 0x10U/*osEventMessage*/, (U32)p_msg); +#else + *p_TCB->msg = p_msg; + rt_ret_val (p_TCB, OS_R_MBX); +#endif + rt_rmv_dly (p_TCB); + rt_dispatch (p_TCB); + } + else { + /* Store message in mailbox queue */ + if (p_MCB->count == p_MCB->size) { + /* No free message entry, wait for one. If message queue is full, */ + /* then no task is waiting for message. The 'p_MCB->p_lnk' list */ + /* pointer can now be reused for send message waits task list. */ + if (timeout == 0U) { + return (OS_R_TMO); + } + if (p_MCB->p_lnk != NULL) { + rt_put_prio ((P_XCB)p_MCB, os_tsk.run); + } + else { + p_MCB->p_lnk = os_tsk.run; + os_tsk.run->p_lnk = NULL; + os_tsk.run->p_rlnk = (P_TCB)p_MCB; + /* Task is waiting to send a message */ + p_MCB->state = 2U; + } + os_tsk.run->msg = p_msg; + rt_block (timeout, WAIT_MBX); + return (OS_R_TMO); + } + /* Yes, there is a free entry in a mailbox. */ + p_MCB->msg[p_MCB->first] = p_msg; + rt_inc (&p_MCB->count); + if (++p_MCB->first == p_MCB->size) { + p_MCB->first = 0U; + } + } + return (OS_R_OK); +} + + +/*--------------------------- rt_mbx_wait -----------------------------------*/ + +OS_RESULT rt_mbx_wait (OS_ID mailbox, void **message, U16 timeout) { + /* Receive a message; possibly wait for it */ + P_MCB p_MCB = mailbox; + P_TCB p_TCB; + + /* If a message is available in the fifo buffer */ + /* remove it from the fifo buffer and return. */ + if (p_MCB->count) { + *message = p_MCB->msg[p_MCB->last]; + if (++p_MCB->last == p_MCB->size) { + p_MCB->last = 0U; + } + if ((p_MCB->p_lnk != NULL) && (p_MCB->state == 2U)) { + /* A task is waiting to send message */ + p_TCB = rt_get_first ((P_XCB)p_MCB); +#ifdef __CMSIS_RTOS + rt_ret_val(p_TCB, 0U/*osOK*/); +#else + rt_ret_val(p_TCB, OS_R_OK); +#endif + p_MCB->msg[p_MCB->first] = p_TCB->msg; + if (++p_MCB->first == p_MCB->size) { + p_MCB->first = 0U; + } + rt_rmv_dly (p_TCB); + rt_dispatch (p_TCB); + } + else { + rt_dec (&p_MCB->count); + } + return (OS_R_OK); + } + /* No message available: wait for one */ + if (timeout == 0U) { + return (OS_R_TMO); + } + if (p_MCB->p_lnk != NULL) { + rt_put_prio ((P_XCB)p_MCB, os_tsk.run); + } + else { + p_MCB->p_lnk = os_tsk.run; + os_tsk.run->p_lnk = NULL; + os_tsk.run->p_rlnk = (P_TCB)p_MCB; + /* Task is waiting to receive a message */ + p_MCB->state = 1U; + } + rt_block(timeout, WAIT_MBX); +#ifndef __CMSIS_RTOS + os_tsk.run->msg = message; +#endif + return (OS_R_TMO); +} + + +/*--------------------------- rt_mbx_check ----------------------------------*/ + +OS_RESULT rt_mbx_check (OS_ID mailbox) { + /* Check for free space in a mailbox. Returns the number of messages */ + /* that can be stored to a mailbox. It returns 0 when mailbox is full. */ + P_MCB p_MCB = mailbox; + + return ((U32)(p_MCB->size - p_MCB->count)); +} + + +/*--------------------------- isr_mbx_send ----------------------------------*/ + +void isr_mbx_send (OS_ID mailbox, void *p_msg) { + /* Same function as "os_mbx_send", but to be called by ISRs. */ + P_MCB p_MCB = mailbox; + + rt_psq_enq (p_MCB, (U32)p_msg); + rt_psh_req (); +} + + +/*--------------------------- isr_mbx_receive -------------------------------*/ + +OS_RESULT isr_mbx_receive (OS_ID mailbox, void **message) { + /* Receive a message in the interrupt function. The interrupt function */ + /* should not wait for a message since this would block the rtx os. */ + P_MCB p_MCB = mailbox; + + if (p_MCB->count) { + /* A message is available in the fifo buffer. */ + *message = p_MCB->msg[p_MCB->last]; + if (p_MCB->state == 2U) { + /* A task is locked waiting to send message */ + rt_psq_enq (p_MCB, 0U); + rt_psh_req (); + } + rt_dec (&p_MCB->count); + if (++p_MCB->last == p_MCB->size) { + p_MCB->last = 0U; + } + return (OS_R_MBX); + } + return (OS_R_OK); +} + + +/*--------------------------- rt_mbx_psh ------------------------------------*/ + +void rt_mbx_psh (P_MCB p_CB, void *p_msg) { + /* Store the message to the mailbox queue or pass it to task directly. */ + P_TCB p_TCB; + void *mem; + + if (p_CB->p_lnk != NULL) switch (p_CB->state) { +#ifdef __CMSIS_RTOS + case 3: + /* Task is waiting to allocate memory, remove it from the waiting list */ + mem = rt_alloc_box(p_msg); + if (mem == NULL) { break; } + p_TCB = rt_get_first ((P_XCB)p_CB); + rt_ret_val(p_TCB, (U32)mem); + p_TCB->state = READY; + rt_rmv_dly (p_TCB); + rt_put_prio (&os_rdy, p_TCB); + break; +#endif + case 2: + /* Task is waiting to send a message, remove it from the waiting list */ + p_TCB = rt_get_first ((P_XCB)p_CB); +#ifdef __CMSIS_RTOS + rt_ret_val(p_TCB, 0U/*osOK*/); +#else + rt_ret_val(p_TCB, OS_R_OK); +#endif + p_CB->msg[p_CB->first] = p_TCB->msg; + rt_inc (&p_CB->count); + if (++p_CB->first == p_CB->size) { + p_CB->first = 0U; + } + p_TCB->state = READY; + rt_rmv_dly (p_TCB); + rt_put_prio (&os_rdy, p_TCB); + break; + case 1: + /* Task is waiting for a message, pass the message to the task directly */ + p_TCB = rt_get_first ((P_XCB)p_CB); +#ifdef __CMSIS_RTOS + rt_ret_val2(p_TCB, 0x10U/*osEventMessage*/, (U32)p_msg); +#else + *p_TCB->msg = p_msg; + rt_ret_val (p_TCB, OS_R_MBX); +#endif + p_TCB->state = READY; + rt_rmv_dly (p_TCB); + rt_put_prio (&os_rdy, p_TCB); + break; + default: + break; + } else { + /* No task is waiting for a message, store it to the mailbox queue */ + if (p_CB->count < p_CB->size) { + p_CB->msg[p_CB->first] = p_msg; + rt_inc (&p_CB->count); + if (++p_CB->first == p_CB->size) { + p_CB->first = 0U; + } + } + else { + os_error (OS_ERR_MBX_OVF); + } + } +} + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ diff --git a/rtos/rtx/TARGET_CORTEX_A/rt_Mailbox.h b/rtos/rtx/TARGET_CORTEX_A/rt_Mailbox.h new file mode 100644 index 00000000000..4ce48bef354 --- /dev/null +++ b/rtos/rtx/TARGET_CORTEX_A/rt_Mailbox.h @@ -0,0 +1,46 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: RT_MAILBOX.H + * Purpose: Implements waits and wake-ups for mailbox messages + * Rev.: V4.70 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2013 ARM Germany GmbH + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + +/* Functions */ +extern void rt_mbx_init (OS_ID mailbox, U16 mbx_size); +extern OS_RESULT rt_mbx_send (OS_ID mailbox, void *p_msg, U16 timeout); +extern OS_RESULT rt_mbx_wait (OS_ID mailbox, void **message, U16 timeout); +extern OS_RESULT rt_mbx_check (OS_ID mailbox); +extern void isr_mbx_send (OS_ID mailbox, void *p_msg); +extern OS_RESULT isr_mbx_receive (OS_ID mailbox, void **message); +extern void rt_mbx_psh (P_MCB p_CB, void *p_msg); + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ diff --git a/rtos/rtx/TARGET_CORTEX_A/rt_MemBox.c b/rtos/rtx/TARGET_CORTEX_A/rt_MemBox.c new file mode 100644 index 00000000000..049438e79ef --- /dev/null +++ b/rtos/rtx/TARGET_CORTEX_A/rt_MemBox.c @@ -0,0 +1,181 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: RT_MEMBOX.C + * Purpose: Interface functions for fixed memory block management system + * Rev.: V4.79 plus changes for RTX-Ax + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 ARM Germany GmbH, 2015 ARM Limited + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Config.h" +#include "rt_System.h" +#include "rt_MemBox.h" +#ifdef __CORTEX_A9 +#include "rt_HAL_CA.h" +#else +#include "rt_HAL_CM.h" +#endif + +/*---------------------------------------------------------------------------- + * Global Functions + *---------------------------------------------------------------------------*/ + + +/*--------------------------- _init_box -------------------------------------*/ + +U32 _init_box (void *box_mem, U32 box_size, U32 blk_size) { + /* Initialize memory block system, returns 0 if OK, 1 if fails. */ + void *end; + void *blk; + void *next; + U32 sizeof_bm; + + /* Create memory structure. */ + if (blk_size & BOX_ALIGN_8) { + /* Memory blocks 8-byte aligned. */ + blk_size = ((blk_size & ~BOX_ALIGN_8) + 7U) & ~(U32)7U; + sizeof_bm = (sizeof (struct OS_BM) + 7U) & ~(U32)7U; + } + else { + /* Memory blocks 4-byte aligned. */ + blk_size = (blk_size + 3U) & ~(U32)3U; + sizeof_bm = sizeof (struct OS_BM); + } + if (blk_size == 0U) { + return (1U); + } + if ((blk_size + sizeof_bm) > box_size) { + return (1U); + } + /* Create a Memory structure. */ + blk = ((U8 *) box_mem) + sizeof_bm; + ((P_BM) box_mem)->free = blk; + end = ((U8 *) box_mem) + box_size; + ((P_BM) box_mem)->end = end; + ((P_BM) box_mem)->blk_size = blk_size; + + /* Link all free blocks using offsets. */ + end = ((U8 *) end) - blk_size; + while (1) { + next = ((U8 *) blk) + blk_size; + if (next > end) { break; } + *((void **)blk) = next; + blk = next; + } + /* end marker */ + *((void **)blk) = 0U; + return (0U); +} + +/*--------------------------- rt_alloc_box ----------------------------------*/ + +void *rt_alloc_box (void *box_mem) { + /* Allocate a memory block and return start address. */ + void **free; +#ifndef __USE_EXCLUSIVE_ACCESS + U32 irq_mask; + + +#if defined (__ICCARM__) + irq_mask = (U32)__disable_irq_iar(); +#else + irq_mask = (U32)__disable_irq (); +#endif /* __ICCARM__ */ + free = ((P_BM) box_mem)->free; + if (free) { + ((P_BM) box_mem)->free = *free; + } + if (irq_mask == 0U) { __enable_irq (); } +#else + do { + if ((free = (void **)__ldrex(&((P_BM) box_mem)->free)) == 0U) { + __clrex(); + break; + } + } while (__strex((U32)*free, &((P_BM) box_mem)->free)); +#endif + return (free); +} + + +/*--------------------------- _calloc_box -----------------------------------*/ + +void *_calloc_box (void *box_mem) { + /* Allocate a 0-initialized memory block and return start address. */ + void *free; + U32 *p; + U32 i; + + free = _alloc_box (box_mem); + if (free) { + p = free; + for (i = ((P_BM) box_mem)->blk_size; i; i -= 4U) { + *p = 0U; + p++; + } + } + return (free); +} + + +/*--------------------------- rt_free_box -----------------------------------*/ + +U32 rt_free_box (void *box_mem, void *box) { + /* Free a memory block, returns 0 if OK, 1 if box does not belong to box_mem */ +#ifndef __USE_EXCLUSIVE_ACCESS + U32 irq_mask; +#endif + + if ((box < box_mem) || (box >= ((P_BM) box_mem)->end)) { + return (1U); + } + +#ifndef __USE_EXCLUSIVE_ACCESS +#if defined (__ICCARM__) + irq_mask = (U32)__disable_irq_iar(); +#else + irq_mask = (U32)__disable_irq (); +#endif /* __ICCARM__ */ + *((void **)box) = ((P_BM) box_mem)->free; + ((P_BM) box_mem)->free = box; + if (irq_mask == 0U) { __enable_irq (); } +#else + do { + do { + *((void **)box) = ((P_BM) box_mem)->free; + __DMB(); + } while (*(void**)box != (void *)__ldrex(&((P_BM) box_mem)->free)); + } while (__strex ((U32)box, &((P_BM) box_mem)->free)); +#endif + return (0U); +} + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ diff --git a/rtos/rtx/TARGET_CORTEX_A/rt_MemBox.h b/rtos/rtx/TARGET_CORTEX_A/rt_MemBox.h new file mode 100644 index 00000000000..14e7df6cd93 --- /dev/null +++ b/rtos/rtx/TARGET_CORTEX_A/rt_MemBox.h @@ -0,0 +1,45 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: RT_MEMBOX.H + * Purpose: Interface functions for fixed memory block management system + * Rev.: V4.79 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 ARM Germany GmbH + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + +/* Functions */ +#define rt_init_box _init_box +#define rt_calloc_box _calloc_box +extern U32 _init_box (void *box_mem, U32 box_size, U32 blk_size); +extern void *rt_alloc_box (void *box_mem); +extern void * _calloc_box (void *box_mem); +extern U32 rt_free_box (void *box_mem, void *box); + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ diff --git a/rtos/rtx/TARGET_CORTEX_A/rt_Memory.c b/rtos/rtx/TARGET_CORTEX_A/rt_Memory.c new file mode 100644 index 00000000000..7ade9e1c0e5 --- /dev/null +++ b/rtos/rtx/TARGET_CORTEX_A/rt_Memory.c @@ -0,0 +1,140 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: RT_MEMORY.C + * Purpose: Interface functions for Dynamic Memory Management System + * Rev.: V4.79 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 ARM Germany GmbH + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "rt_Memory.h" + + +/* Functions */ + +// Initialize Dynamic Memory pool +// Parameters: +// pool: Pointer to memory pool +// size: Size of memory pool in bytes +// Return: 0 - OK, 1 - Error + +U32 rt_init_mem (void *pool, U32 size) { + MEMP *ptr; + + if ((pool == NULL) || (size < sizeof(MEMP))) { return (1U); } + + ptr = (MEMP *)pool; + ptr->next = (MEMP *)((U32)pool + size - sizeof(MEMP *)); + ptr->next->next = NULL; + ptr->len = 0U; + + return (0U); +} + +// Allocate Memory from Memory pool +// Parameters: +// pool: Pointer to memory pool +// size: Size of memory in bytes to allocate +// Return: Pointer to allocated memory + +void *rt_alloc_mem (void *pool, U32 size) { + MEMP *p, *p_search, *p_new; + U32 hole_size; + + if ((pool == NULL) || (size == 0U)) { return NULL; } + + /* Add header offset to 'size' */ + size += sizeof(MEMP); + /* Make sure that block is 4-byte aligned */ + size = (size + 3U) & ~(U32)3U; + + p_search = (MEMP *)pool; + while (1) { + hole_size = (U32)p_search->next - (U32)p_search; + hole_size -= p_search->len; + /* Check if hole size is big enough */ + if (hole_size >= size) { break; } + p_search = p_search->next; + if (p_search->next == NULL) { + /* Failed, we are at the end of the list */ + return NULL; + } + } + + if (p_search->len == 0U) { + /* No block is allocated, set the Length of the first element */ + p_search->len = size; + p = (MEMP *)(((U32)p_search) + sizeof(MEMP)); + } else { + /* Insert new list element into the memory list */ + p_new = (MEMP *)((U32)p_search + p_search->len); + p_new->next = p_search->next; + p_new->len = size; + p_search->next = p_new; + p = (MEMP *)(((U32)p_new) + sizeof(MEMP)); + } + + return (p); +} + +// Free Memory and return it to Memory pool +// Parameters: +// pool: Pointer to memory pool +// mem: Pointer to memory to free +// Return: 0 - OK, 1 - Error + +U32 rt_free_mem (void *pool, void *mem) { + MEMP *p_search, *p_prev, *p_return; + + if ((pool == NULL) || (mem == NULL)) { return (1U); } + + p_return = (MEMP *)((U32)mem - sizeof(MEMP)); + + /* Set list header */ + p_prev = NULL; + p_search = (MEMP *)pool; + while (p_search != p_return) { + p_prev = p_search; + p_search = p_search->next; + if (p_search == NULL) { + /* Valid Memory block not found */ + return (1U); + } + } + + if (p_prev == NULL) { + /* First block to be released, only set length to 0 */ + p_search->len = 0U; + } else { + /* Discard block from chain list */ + p_prev->next = p_search->next; + } + + return (0U); +} diff --git a/rtos/rtx/TARGET_CORTEX_A/rt_Memory.h b/rtos/rtx/TARGET_CORTEX_A/rt_Memory.h new file mode 100644 index 00000000000..26780a4ad38 --- /dev/null +++ b/rtos/rtx/TARGET_CORTEX_A/rt_Memory.h @@ -0,0 +1,44 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: RT_MEMORY.H + * Purpose: Interface functions for Dynamic Memory Management System + * Rev.: V4.79 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 ARM Germany GmbH + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + +/* Types */ +typedef struct mem { /* << Memory Pool management struct >> */ + struct mem *next; /* Next Memory Block in the list */ + U32 len; /* Length of data block */ +} MEMP; + +/* Functions */ +extern U32 rt_init_mem (void *pool, U32 size); +extern void *rt_alloc_mem (void *pool, U32 size); +extern U32 rt_free_mem (void *pool, void *mem); diff --git a/rtos/rtx/TARGET_CORTEX_A/rt_Mutex.c b/rtos/rtx/TARGET_CORTEX_A/rt_Mutex.c new file mode 100644 index 00000000000..e9eec52bc74 --- /dev/null +++ b/rtos/rtx/TARGET_CORTEX_A/rt_Mutex.c @@ -0,0 +1,265 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: RT_MUTEX.C + * Purpose: Implements mutex synchronization objects + * Rev.: V4.79 plus changes for RTX-Ax + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 ARM Germany GmbH, 2012-2016 ARM Limited + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Config.h" +#include "rt_List.h" +#include "rt_Task.h" +#include "rt_Mutex.h" +#ifdef __CORTEX_A9 +#include "rt_HAL_CA.h" +#else +#include "rt_HAL_CM.h" +#endif + + +/*---------------------------------------------------------------------------- + * Functions + *---------------------------------------------------------------------------*/ + + +/*--------------------------- rt_mut_init -----------------------------------*/ + +void rt_mut_init (OS_ID mutex) { + /* Initialize a mutex object */ + P_MUCB p_MCB = mutex; + + p_MCB->cb_type = MUCB; + p_MCB->level = 0U; + p_MCB->p_lnk = NULL; + p_MCB->owner = NULL; + p_MCB->p_mlnk = NULL; +} + + +/*--------------------------- rt_mut_delete ---------------------------------*/ + +#ifdef __CMSIS_RTOS +OS_RESULT rt_mut_delete (OS_ID mutex) { + /* Delete a mutex object */ + P_MUCB p_MCB = mutex; + P_TCB p_TCB; + P_MUCB p_mlnk; + U8 prio; + + __DMB(); + /* Restore owner task's priority. */ + if (p_MCB->level != 0U) { + + p_TCB = p_MCB->owner; + + /* Remove mutex from task mutex owner list. */ + p_mlnk = p_TCB->p_mlnk; + if (p_mlnk == p_MCB) { + p_TCB->p_mlnk = p_MCB->p_mlnk; + } + else { + while (p_mlnk) { + if (p_mlnk->p_mlnk == p_MCB) { + p_mlnk->p_mlnk = p_MCB->p_mlnk; + break; + } + p_mlnk = p_mlnk->p_mlnk; + } + } + + /* Restore owner task's priority. */ + prio = p_TCB->prio_base; + p_mlnk = p_TCB->p_mlnk; + while (p_mlnk) { + if ((p_mlnk->p_lnk != NULL) && (p_mlnk->p_lnk->prio > prio)) { + /* A task with higher priority is waiting for mutex. */ + prio = p_mlnk->p_lnk->prio; + } + p_mlnk = p_mlnk->p_mlnk; + } + if (p_TCB->prio != prio) { + p_TCB->prio = prio; + if (p_TCB != os_tsk.run) { + rt_resort_prio (p_TCB); + } + } + + } + + while (p_MCB->p_lnk != NULL) { + /* A task is waiting for mutex. */ + p_TCB = rt_get_first ((P_XCB)p_MCB); + rt_ret_val(p_TCB, 0U/*osOK*/); + rt_rmv_dly(p_TCB); + p_TCB->state = READY; + rt_put_prio (&os_rdy, p_TCB); + } + + if ((os_rdy.p_lnk != NULL) && (os_rdy.p_lnk->prio > os_tsk.run->prio)) { + /* preempt running task */ + rt_put_prio (&os_rdy, os_tsk.run); + os_tsk.run->state = READY; + rt_dispatch (NULL); + } + + p_MCB->cb_type = 0U; + + return (OS_R_OK); +} +#endif + + +/*--------------------------- rt_mut_release --------------------------------*/ + +OS_RESULT rt_mut_release (OS_ID mutex) { + /* Release a mutex object */ + P_MUCB p_MCB = mutex; + P_TCB p_TCB; + P_MUCB p_mlnk; + U8 prio; + + if ((p_MCB->level == 0U) || (p_MCB->owner != os_tsk.run)) { + /* Unbalanced mutex release or task is not the owner */ + return (OS_R_NOK); + } + __DMB(); + if (--p_MCB->level != 0U) { + return (OS_R_OK); + } + + /* Remove mutex from task mutex owner list. */ + p_mlnk = os_tsk.run->p_mlnk; + if (p_mlnk == p_MCB) { + os_tsk.run->p_mlnk = p_MCB->p_mlnk; + } + else { + while (p_mlnk) { + if (p_mlnk->p_mlnk == p_MCB) { + p_mlnk->p_mlnk = p_MCB->p_mlnk; + break; + } + p_mlnk = p_mlnk->p_mlnk; + } + } + + /* Restore owner task's priority. */ + prio = os_tsk.run->prio_base; + p_mlnk = os_tsk.run->p_mlnk; + while (p_mlnk) { + if ((p_mlnk->p_lnk != NULL) && (p_mlnk->p_lnk->prio > prio)) { + /* A task with higher priority is waiting for mutex. */ + prio = p_mlnk->p_lnk->prio; + } + p_mlnk = p_mlnk->p_mlnk; + } + os_tsk.run->prio = prio; + + if (p_MCB->p_lnk != NULL) { + /* A task is waiting for mutex. */ + p_TCB = rt_get_first ((P_XCB)p_MCB); +#ifdef __CMSIS_RTOS + rt_ret_val(p_TCB, 0U/*osOK*/); +#else + rt_ret_val(p_TCB, OS_R_MUT); +#endif + rt_rmv_dly (p_TCB); + /* A waiting task becomes the owner of this mutex. */ + p_MCB->level = 1U; + p_MCB->owner = p_TCB; + p_MCB->p_mlnk = p_TCB->p_mlnk; + p_TCB->p_mlnk = p_MCB; + /* Priority inversion, check which task continues. */ + if (os_tsk.run->prio >= rt_rdy_prio()) { + rt_dispatch (p_TCB); + } + else { + /* Ready task has higher priority than running task. */ + rt_put_prio (&os_rdy, os_tsk.run); + rt_put_prio (&os_rdy, p_TCB); + os_tsk.run->state = READY; + p_TCB->state = READY; + rt_dispatch (NULL); + } + } + else { + /* Check if own priority lowered by priority inversion. */ + if (rt_rdy_prio() > os_tsk.run->prio) { + rt_put_prio (&os_rdy, os_tsk.run); + os_tsk.run->state = READY; + rt_dispatch (NULL); + } + } + return (OS_R_OK); +} + + +/*--------------------------- rt_mut_wait -----------------------------------*/ + +OS_RESULT rt_mut_wait (OS_ID mutex, U16 timeout) { + /* Wait for a mutex, continue when mutex is free. */ + P_MUCB p_MCB = mutex; + + if (p_MCB->level == 0U) { + p_MCB->owner = os_tsk.run; + p_MCB->p_mlnk = os_tsk.run->p_mlnk; + os_tsk.run->p_mlnk = p_MCB; + goto inc; + } + if (p_MCB->owner == os_tsk.run) { + /* OK, running task is the owner of this mutex. */ +inc:p_MCB->level++; + __DMB(); + return (OS_R_OK); + } + /* Mutex owned by another task, wait until released. */ + if (timeout == 0U) { + return (OS_R_TMO); + } + /* Raise the owner task priority if lower than current priority. */ + /* This priority inversion is called priority inheritance. */ + if (p_MCB->owner->prio < os_tsk.run->prio) { + p_MCB->owner->prio = os_tsk.run->prio; + rt_resort_prio (p_MCB->owner); + } + if (p_MCB->p_lnk != NULL) { + rt_put_prio ((P_XCB)p_MCB, os_tsk.run); + } + else { + p_MCB->p_lnk = os_tsk.run; + os_tsk.run->p_lnk = NULL; + os_tsk.run->p_rlnk = (P_TCB)p_MCB; + } + rt_block(timeout, WAIT_MUT); + return (OS_R_TMO); +} + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ diff --git a/rtos/rtx/TARGET_CORTEX_A/rt_Mutex.h b/rtos/rtx/TARGET_CORTEX_A/rt_Mutex.h new file mode 100644 index 00000000000..75a22584202 --- /dev/null +++ b/rtos/rtx/TARGET_CORTEX_A/rt_Mutex.h @@ -0,0 +1,43 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: RT_MUTEX.H + * Purpose: Implements mutex synchronization objects + * Rev.: V4.70 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2013 ARM Germany GmbH + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + +/* Functions */ +extern void rt_mut_init (OS_ID mutex); +extern OS_RESULT rt_mut_delete (OS_ID mutex); +extern OS_RESULT rt_mut_release (OS_ID mutex); +extern OS_RESULT rt_mut_wait (OS_ID mutex, U16 timeout); + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ diff --git a/rtos/rtx/TARGET_CORTEX_A/rt_Robin.c b/rtos/rtx/TARGET_CORTEX_A/rt_Robin.c new file mode 100644 index 00000000000..92eb480cfd8 --- /dev/null +++ b/rtos/rtx/TARGET_CORTEX_A/rt_Robin.c @@ -0,0 +1,87 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: RT_ROBIN.C + * Purpose: Round Robin Task switching + * Rev.: V4.79 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 ARM Germany GmbH + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Config.h" +#include "rt_List.h" +#include "rt_Task.h" +#include "rt_Time.h" +#include "rt_Robin.h" +#ifdef __CORTEX_A9 +#include "rt_HAL_CA.h" +#else +#include "rt_HAL_CM.h" +#endif + +/*---------------------------------------------------------------------------- + * Global Variables + *---------------------------------------------------------------------------*/ + +struct OS_ROBIN os_robin; + + +/*---------------------------------------------------------------------------- + * Global Functions + *---------------------------------------------------------------------------*/ + +/*--------------------------- rt_init_robin ---------------------------------*/ + +__weak void rt_init_robin (void) { + /* Initialize Round Robin variables. */ + os_robin.task = NULL; + os_robin.tout = (U16)os_rrobin; +} + +/*--------------------------- rt_chk_robin ----------------------------------*/ + +__weak void rt_chk_robin (void) { + /* Check if Round Robin timeout expired and switch to the next ready task.*/ + P_TCB p_new; + + if (os_robin.task != os_rdy.p_lnk) { + /* New task was suspended, reset Round Robin timeout. */ + os_robin.task = os_rdy.p_lnk; + os_robin.time = (U16)os_time + os_robin.tout - 1U; + } + if (os_robin.time == (U16)os_time) { + /* Round Robin timeout has expired, swap Robin tasks. */ + os_robin.task = NULL; + p_new = rt_get_first (&os_rdy); + rt_put_prio ((P_XCB)&os_rdy, p_new); + } +} + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ diff --git a/rtos/rtx/TARGET_CORTEX_A/rt_Robin.h b/rtos/rtx/TARGET_CORTEX_A/rt_Robin.h new file mode 100644 index 00000000000..4bdf81a8df0 --- /dev/null +++ b/rtos/rtx/TARGET_CORTEX_A/rt_Robin.h @@ -0,0 +1,44 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: RT_ROBIN.H + * Purpose: Round Robin Task switching definitions + * Rev.: V4.70 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2013 ARM Germany GmbH + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + +/* Variables */ +extern struct OS_ROBIN os_robin; + +/* Functions */ +extern void rt_init_robin (void); +extern void rt_chk_robin (void); + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ diff --git a/rtos/rtx/TARGET_CORTEX_A/rt_Semaphore.c b/rtos/rtx/TARGET_CORTEX_A/rt_Semaphore.c new file mode 100644 index 00000000000..65ba4c62607 --- /dev/null +++ b/rtos/rtx/TARGET_CORTEX_A/rt_Semaphore.c @@ -0,0 +1,190 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: RT_SEMAPHORE.C + * Purpose: Implements binary and counting semaphores + * Rev.: V4.79 plus changes for RTX-Ax + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 ARM Germany GmbH, 2012-2016 ARM Limited + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Config.h" +#include "rt_System.h" +#include "rt_List.h" +#include "rt_Task.h" +#include "rt_Semaphore.h" +#ifdef __CORTEX_A9 +#include "rt_HAL_CA.h" +#else +#include "rt_HAL_CM.h" +#endif + + +/*---------------------------------------------------------------------------- + * Functions + *---------------------------------------------------------------------------*/ + + +/*--------------------------- rt_sem_init -----------------------------------*/ + +void rt_sem_init (OS_ID semaphore, U16 token_count) { + /* Initialize a semaphore */ + P_SCB p_SCB = semaphore; + + p_SCB->cb_type = SCB; + p_SCB->p_lnk = NULL; + p_SCB->tokens = token_count; +} + + +/*--------------------------- rt_sem_delete ---------------------------------*/ + +#ifdef __CMSIS_RTOS +OS_RESULT rt_sem_delete (OS_ID semaphore) { + /* Delete semaphore */ + P_SCB p_SCB = semaphore; + P_TCB p_TCB; + + __DMB(); + while (p_SCB->p_lnk != NULL) { + /* A task is waiting for token */ + p_TCB = rt_get_first ((P_XCB)p_SCB); + rt_ret_val(p_TCB, 0U); + rt_rmv_dly(p_TCB); + p_TCB->state = READY; + rt_put_prio (&os_rdy, p_TCB); + } + + if ((os_rdy.p_lnk != NULL) && (os_rdy.p_lnk->prio > os_tsk.run->prio)) { + /* preempt running task */ + rt_put_prio (&os_rdy, os_tsk.run); + os_tsk.run->state = READY; + rt_dispatch (NULL); + } + + p_SCB->cb_type = 0U; + + return (OS_R_OK); +} +#endif + + +/*--------------------------- rt_sem_send -----------------------------------*/ + +OS_RESULT rt_sem_send (OS_ID semaphore) { + /* Return a token to semaphore */ + P_SCB p_SCB = semaphore; + P_TCB p_TCB; + + __DMB(); + if (p_SCB->p_lnk != NULL) { + /* A task is waiting for token */ + p_TCB = rt_get_first ((P_XCB)p_SCB); +#ifdef __CMSIS_RTOS + rt_ret_val(p_TCB, 1U); +#else + rt_ret_val(p_TCB, OS_R_SEM); +#endif + rt_rmv_dly (p_TCB); + rt_dispatch (p_TCB); + } + else { + /* Store token. */ + p_SCB->tokens++; + } + return (OS_R_OK); +} + + +/*--------------------------- rt_sem_wait -----------------------------------*/ + +OS_RESULT rt_sem_wait (OS_ID semaphore, U16 timeout) { + /* Obtain a token; possibly wait for it */ + P_SCB p_SCB = semaphore; + + if (p_SCB->tokens) { + p_SCB->tokens--; + __DMB(); + return (OS_R_OK); + } + /* No token available: wait for one */ + if (timeout == 0U) { + return (OS_R_TMO); + } + if (p_SCB->p_lnk != NULL) { + rt_put_prio ((P_XCB)p_SCB, os_tsk.run); + } + else { + p_SCB->p_lnk = os_tsk.run; + os_tsk.run->p_lnk = NULL; + os_tsk.run->p_rlnk = (P_TCB)p_SCB; + } + rt_block(timeout, WAIT_SEM); + return (OS_R_TMO); +} + + +/*--------------------------- isr_sem_send ----------------------------------*/ + +void isr_sem_send (OS_ID semaphore) { + /* Same function as "os_sem_send", but to be called by ISRs */ + P_SCB p_SCB = semaphore; + + rt_psq_enq (p_SCB, 0U); + rt_psh_req (); +} + + +/*--------------------------- rt_sem_psh ------------------------------------*/ + +void rt_sem_psh (P_SCB p_CB) { + /* Check if task has to be waken up */ + P_TCB p_TCB; + + __DMB(); + if (p_CB->p_lnk != NULL) { + /* A task is waiting for token */ + p_TCB = rt_get_first ((P_XCB)p_CB); + rt_rmv_dly (p_TCB); + p_TCB->state = READY; +#ifdef __CMSIS_RTOS + rt_ret_val(p_TCB, 1U); +#else + rt_ret_val(p_TCB, OS_R_SEM); +#endif + rt_put_prio (&os_rdy, p_TCB); + } + else { + /* Store token */ + p_CB->tokens++; + } +} + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ diff --git a/rtos/rtx/TARGET_CORTEX_A/rt_Semaphore.h b/rtos/rtx/TARGET_CORTEX_A/rt_Semaphore.h new file mode 100644 index 00000000000..00c7de49d67 --- /dev/null +++ b/rtos/rtx/TARGET_CORTEX_A/rt_Semaphore.h @@ -0,0 +1,45 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: RT_SEMAPHORE.H + * Purpose: Implements binary and counting semaphores + * Rev.: V4.70 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2013 ARM Germany GmbH + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + +/* Functions */ +extern void rt_sem_init (OS_ID semaphore, U16 token_count); +extern OS_RESULT rt_sem_delete(OS_ID semaphore); +extern OS_RESULT rt_sem_send (OS_ID semaphore); +extern OS_RESULT rt_sem_wait (OS_ID semaphore, U16 timeout); +extern void isr_sem_send (OS_ID semaphore); +extern void rt_sem_psh (P_SCB p_CB); + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ diff --git a/rtos/rtx/TARGET_CORTEX_A/rt_System.c b/rtos/rtx/TARGET_CORTEX_A/rt_System.c new file mode 100644 index 00000000000..60d35fedee9 --- /dev/null +++ b/rtos/rtx/TARGET_CORTEX_A/rt_System.c @@ -0,0 +1,336 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: RT_SYSTEM.C + * Purpose: System Task Manager + * Rev.: V4.80 plus changes for RTX-Ax + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 ARM Germany GmbH, 2012-2016 ARM Limited + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Config.h" +#include "rt_Task.h" +#include "rt_System.h" +#include "rt_Event.h" +#include "rt_List.h" +#include "rt_Mailbox.h" +#include "rt_Semaphore.h" +#include "rt_Time.h" +#include "rt_Timer.h" +#include "rt_Robin.h" +#ifdef __CORTEX_A9 +#include "rt_HAL_CA.h" +#else +#include "rt_HAL_CM.h" +#endif + +/*---------------------------------------------------------------------------- + * Global Variables + *---------------------------------------------------------------------------*/ + +S32 os_tick_irqn; +U8 scheduler_suspended = 0; // flag set by rt_suspend, cleared by rt_resume, read by SVC_Handler + +/*---------------------------------------------------------------------------- + * Local Variables + *---------------------------------------------------------------------------*/ + +static volatile BIT os_lock; +static volatile BIT os_psh_flag; +#ifndef __CORTEX_A9 +static U8 pend_flags; +#endif +/*---------------------------------------------------------------------------- + * Global Functions + *---------------------------------------------------------------------------*/ + +#define RL_RTX_VER 0x480 + +#if defined (__CC_ARM) +__asm void $$RTX$$version (void) { + /* Export a version number symbol for a version control. */ + + EXPORT __RL_RTX_VER + +__RL_RTX_VER EQU RL_RTX_VER +} +#endif + + +/*--------------------------- rt_suspend ------------------------------------*/ + +extern U32 sysUserTimerWakeupTime(void); + +U32 rt_suspend (void) { + /* Suspend OS scheduler */ + U32 delta = 0xFFFFU; +#ifdef __CMSIS_RTOS + U32 sleep; +#endif + + rt_tsk_lock(); + scheduler_suspended = 1; + + if (os_dly.p_dlnk) { + delta = os_dly.delta_time; + } +#ifdef __CMSIS_RTOS + sleep = sysUserTimerWakeupTime(); + if (sleep < delta) { delta = sleep; } +#else + if (os_tmr.next) { + if (os_tmr.tcnt < delta) delta = os_tmr.tcnt; + } +#endif + + return (delta); +} + + +/*--------------------------- rt_resume -------------------------------------*/ + +extern void sysUserTimerUpdate (U32 sleep_time); + +void rt_resume (U32 sleep_time) { + /* Resume OS scheduler after suspend */ + P_TCB next; + U32 delta; + + os_tsk.run->state = READY; + rt_put_rdy_first (os_tsk.run); + + os_robin.task = NULL; + + /* Update delays. */ + if (os_dly.p_dlnk) { + delta = sleep_time; + if (delta >= os_dly.delta_time) { + delta -= os_dly.delta_time; + os_time += os_dly.delta_time; + os_dly.delta_time = 1U; + while (os_dly.p_dlnk) { + rt_dec_dly(); + if (delta == 0U) { break; } + delta--; + os_time++; + } + } else { + os_time += delta; + os_dly.delta_time -= (U16)delta; + } + } else { + os_time += sleep_time; + } + + /* Check the user timers. */ +#ifdef __CMSIS_RTOS + sysUserTimerUpdate(sleep_time); +#else + if (os_tmr.next) { + delta = sleep_time; + if (delta >= os_tmr.tcnt) { + delta -= os_tmr.tcnt; + os_tmr.tcnt = 1U; + while (os_tmr.next) { + rt_tmr_tick(); + if (delta == 0U) { break; } + delta--; + } + } else { + os_tmr.tcnt -= delta; + } + } +#endif + + /* Switch back to highest ready task */ + next = rt_get_first (&os_rdy); + rt_switch_req (next); + + scheduler_suspended = 0; + rt_tsk_unlock(); +} + + +/*--------------------------- rt_tsk_lock -----------------------------------*/ + +void rt_tsk_lock (void) { + /* Prevent task switching by locking out scheduler */ + if (os_lock == __TRUE) // don't lock again if already locked + return; + + if (os_tick_irqn < 0) { + OS_LOCK(); + os_lock = __TRUE; + OS_UNPEND(pend_flags); + } else { + OS_X_LOCK((U32)os_tick_irqn); + os_lock = __TRUE; + OS_X_UNPEND(pend_flags); + } +} + + +/*--------------------------- rt_tsk_unlock ---------------------------------*/ + +void rt_tsk_unlock (void) { + /* Unlock scheduler and re-enable task switching */ + if (os_tick_irqn < 0) { + OS_UNLOCK(); + os_lock = __FALSE; + OS_PEND(pend_flags, os_psh_flag); + os_psh_flag = __FALSE; + } else { + OS_X_UNLOCK((U32)os_tick_irqn); + os_lock = __FALSE; + OS_X_PEND(pend_flags, os_psh_flag); + os_psh_flag = __FALSE; + } +} + + +/*--------------------------- rt_psh_req ------------------------------------*/ + +void rt_psh_req (void) { + /* Initiate a post service handling request if required. */ + if (os_lock == __FALSE) { + OS_PEND_IRQ(); + } + else { + os_psh_flag = __TRUE; + } +} + + +/*--------------------------- rt_pop_req ------------------------------------*/ + +void rt_pop_req (void) { + /* Process an ISR post service requests. */ + struct OS_XCB *p_CB; + P_TCB next; + U32 idx; + + os_tsk.run->state = READY; + rt_put_rdy_first (os_tsk.run); + + idx = os_psq->last; + while (os_psq->count) { + p_CB = os_psq->q[idx].id; + if (p_CB->cb_type == TCB) { + /* Is of TCB type */ + rt_evt_psh ((P_TCB)p_CB, (U16)os_psq->q[idx].arg); + } + else if (p_CB->cb_type == MCB) { + /* Is of MCB type */ + rt_mbx_psh ((P_MCB)p_CB, (void *)os_psq->q[idx].arg); + } + else { + /* Must be of SCB type */ + rt_sem_psh ((P_SCB)p_CB); + } + if (++idx == os_psq->size) { idx = 0U; } + rt_dec (&os_psq->count); + } + os_psq->last = (U8)idx; + + next = rt_get_first (&os_rdy); + rt_switch_req (next); +} + + +/*--------------------------- os_tick_init ----------------------------------*/ + +__weak S32 os_tick_init (void) { + /* Initialize SysTick timer as system tick timer. */ + rt_systick_init(); + return (-1); /* Return IRQ number of SysTick timer */ +} + +/*--------------------------- os_tick_val -----------------------------------*/ + +__weak U32 os_tick_val (void) { + /* Get SysTick timer current value (0 .. OS_TRV). */ + return rt_systick_val(); +} + +/*--------------------------- os_tick_ovf -----------------------------------*/ + +__weak U32 os_tick_ovf (void) { + /* Get SysTick timer overflow flag */ + return rt_systick_ovf(); +} + +/*--------------------------- os_tick_irqack --------------------------------*/ + +__weak void os_tick_irqack (void) { + /* Acknowledge timer interrupt. */ +} + + +/*--------------------------- rt_systick ------------------------------------*/ + +extern void sysTimerTick(void); + +void rt_systick (void) { + /* Check for system clock update, suspend running task. */ + P_TCB next; + + os_tsk.run->state = READY; + rt_put_rdy_first (os_tsk.run); + + /* Check Round Robin timeout. */ + rt_chk_robin (); + + /* Update delays. */ + os_time++; + rt_dec_dly (); + + /* Check the user timers. */ +#ifdef __CMSIS_RTOS + sysTimerTick(); +#else + rt_tmr_tick (); +#endif + + /* Switch back to highest ready task */ + next = rt_get_first (&os_rdy); + rt_switch_req (next); +} + +/*--------------------------- rt_stk_check ----------------------------------*/ + +__weak void rt_stk_check (void) { + /* Check for stack overflow. */ + if ((os_tsk.run->tsk_stack < (U32)os_tsk.run->stack) || + (os_tsk.run->stack[0] != MAGIC_WORD)) { + os_error (OS_ERR_STK_OVF); + } +} + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ diff --git a/rtos/rtx/TARGET_CORTEX_A/rt_System.h b/rtos/rtx/TARGET_CORTEX_A/rt_System.h new file mode 100644 index 00000000000..fa02d2b905b --- /dev/null +++ b/rtos/rtx/TARGET_CORTEX_A/rt_System.h @@ -0,0 +1,51 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: RT_SYSTEM.H + * Purpose: System Task Manager definitions + * Rev.: V4.79 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 ARM Germany GmbH + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + +/* Variables */ +#define os_psq ((P_PSQ)&os_fifo) +extern S32 os_tick_irqn; + +/* Functions */ +extern U32 rt_suspend (void); +extern void rt_resume (U32 sleep_time); +extern void rt_tsk_lock (void); +extern void rt_tsk_unlock (void); +extern void rt_psh_req (void); +extern void rt_pop_req (void); +extern void rt_systick (void); +extern void rt_stk_check (void); + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ diff --git a/rtos/rtx/TARGET_CORTEX_A/rt_Task.c b/rtos/rtx/TARGET_CORTEX_A/rt_Task.c new file mode 100644 index 00000000000..836a88d82cf --- /dev/null +++ b/rtos/rtx/TARGET_CORTEX_A/rt_Task.c @@ -0,0 +1,452 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: RT_TASK.C + * Purpose: Task functions and system start up. + * Rev.: V4.80 plus changes for RTX-Ax + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 ARM Germany GmbH, 2012-2016 ARM Limited + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Config.h" +#include "rt_System.h" +#include "rt_Task.h" +#include "rt_List.h" +#include "rt_MemBox.h" +#include "rt_Robin.h" +#ifdef __CORTEX_A9 +#include "rt_HAL_CA.h" +#else +#include "rt_HAL_CM.h" +#endif + +/*---------------------------------------------------------------------------- + * Global Variables + *---------------------------------------------------------------------------*/ + +/* Running and next task info. */ +struct OS_TSK os_tsk; + +/* Task Control Blocks of idle demon */ +struct OS_TCB os_idle_TCB; + + +/*---------------------------------------------------------------------------- + * Local Functions + *---------------------------------------------------------------------------*/ + +static OS_TID rt_get_TID (void) { + U32 tid; + + for (tid = 1U; tid <= os_maxtaskrun; tid++) { + if (os_active_TCB[tid-1U] == NULL) { + return ((OS_TID)tid); + } + } + return (0U); +} + + +/*--------------------------- rt_init_context -------------------------------*/ + +static void rt_init_context (P_TCB p_TCB, U8 priority, FUNCP task_body) { + /* Initialize general part of the Task Control Block. */ + p_TCB->cb_type = TCB; + p_TCB->state = READY; + p_TCB->prio = priority; + p_TCB->prio_base = priority; + p_TCB->p_lnk = NULL; + p_TCB->p_rlnk = NULL; + p_TCB->p_dlnk = NULL; + p_TCB->p_blnk = NULL; + p_TCB->p_mlnk = NULL; + p_TCB->delta_time = 0U; + p_TCB->interval_time = 0U; + p_TCB->events = 0U; + p_TCB->waits = 0U; + p_TCB->stack_frame = 0U; + + if (p_TCB->priv_stack == 0U) { + /* Allocate the memory space for the stack. */ + p_TCB->stack = rt_alloc_box (mp_stk); + } + rt_init_stack (p_TCB, task_body); +} + + +/*--------------------------- rt_switch_req ---------------------------------*/ + +void rt_switch_req (P_TCB p_new) { + /* Switch to next task (identified by "p_new"). */ + os_tsk.new_tsk = p_new; + p_new->state = RUNNING; + DBG_TASK_SWITCH(p_new->task_id); +} + + +/*--------------------------- rt_dispatch -----------------------------------*/ + +void rt_dispatch (P_TCB next_TCB) { + /* Dispatch next task if any identified or dispatch highest ready task */ + /* "next_TCB" identifies a task to run or has value NULL (=no next task) */ + if (next_TCB == NULL) { + /* Running task was blocked: continue with highest ready task */ + next_TCB = rt_get_first (&os_rdy); + rt_switch_req (next_TCB); + } + else { + /* Check which task continues */ + if (next_TCB->prio > os_tsk.run->prio) { + /* preempt running task */ + rt_put_rdy_first (os_tsk.run); + os_tsk.run->state = READY; + rt_switch_req (next_TCB); + } + else { + /* put next task into ready list, no task switch takes place */ + next_TCB->state = READY; + rt_put_prio (&os_rdy, next_TCB); + } + } +} + + +/*--------------------------- rt_block --------------------------------------*/ + +void rt_block (U16 timeout, U8 block_state) { + /* Block running task and choose next ready task. */ + /* "timeout" sets a time-out value or is 0xffff (=no time-out). */ + /* "block_state" defines the appropriate task state */ + P_TCB next_TCB; + + if (timeout) { + if (timeout < 0xFFFFU) { + rt_put_dly (os_tsk.run, timeout); + } + os_tsk.run->state = block_state; + next_TCB = rt_get_first (&os_rdy); + rt_switch_req (next_TCB); + } +} + + +/*--------------------------- rt_tsk_pass -----------------------------------*/ + +void rt_tsk_pass (void) { + /* Allow tasks of same priority level to run cooperatively.*/ + P_TCB p_new; + + p_new = rt_get_same_rdy_prio(); + if (p_new != NULL) { + rt_put_prio ((P_XCB)&os_rdy, os_tsk.run); + os_tsk.run->state = READY; + rt_switch_req (p_new); + } +} + + +/*--------------------------- rt_tsk_self -----------------------------------*/ + +OS_TID rt_tsk_self (void) { + /* Return own task identifier value. */ + if (os_tsk.run == NULL) { + return (0U); + } + return ((OS_TID)os_tsk.run->task_id); +} + + +/*--------------------------- rt_tsk_prio -----------------------------------*/ + +OS_RESULT rt_tsk_prio (OS_TID task_id, U8 new_prio) { + /* Change execution priority of a task to "new_prio". */ + P_TCB p_task; + + if (task_id == 0U) { + /* Change execution priority of calling task. */ + os_tsk.run->prio = new_prio; + os_tsk.run->prio_base = new_prio; +run:if (rt_rdy_prio() > new_prio) { + rt_put_prio (&os_rdy, os_tsk.run); + os_tsk.run->state = READY; + rt_dispatch (NULL); + } + return (OS_R_OK); + } + + /* Find the task in the "os_active_TCB" array. */ + if ((task_id > os_maxtaskrun) || (os_active_TCB[task_id-1U] == NULL)) { + /* Task with "task_id" not found or not started. */ + return (OS_R_NOK); + } + p_task = os_active_TCB[task_id-1U]; + p_task->prio = new_prio; + p_task->prio_base = new_prio; + if (p_task == os_tsk.run) { + goto run; + } + rt_resort_prio (p_task); + if (p_task->state == READY) { + /* Task enqueued in a ready list. */ + p_task = rt_get_first (&os_rdy); + rt_dispatch (p_task); + } + return (OS_R_OK); +} + + +/*--------------------------- rt_tsk_create ---------------------------------*/ + +OS_TID rt_tsk_create (FUNCP task, U32 prio_stksz, void *stk, void *argv) { + /* Start a new task declared with "task". */ + P_TCB task_context; + U32 i; + + /* Priority 0 is reserved for idle task! */ + if ((prio_stksz & 0xFFU) == 0U) { + prio_stksz += 1U; + } + task_context = rt_alloc_box (mp_tcb); + if (task_context == NULL) { + return (0U); + } + /* If "size != 0" use a private user provided stack. */ + task_context->stack = stk; + task_context->priv_stack = (U16)(prio_stksz >> 8); + + /* Find a free entry in 'os_active_TCB' table. */ + i = rt_get_TID (); + if (i == 0U) { + return (0U); + } + task_context->task_id = (U8)i; + /* Pass parameter 'argv' to 'rt_init_context' */ + task_context->msg = argv; + task_context->argv = argv; + /* For 'size == 0' system allocates the user stack from the memory pool. */ + rt_init_context (task_context, (U8)(prio_stksz & 0xFFU), task); + + os_active_TCB[i-1U] = task_context; + DBG_TASK_NOTIFY(task_context, __TRUE); + rt_dispatch (task_context); + return ((OS_TID)i); +} + + +/*--------------------------- rt_tsk_delete ---------------------------------*/ + +OS_RESULT rt_tsk_delete (OS_TID task_id) { + /* Terminate the task identified with "task_id". */ + P_TCB task_context; + P_TCB p_TCB; + P_MUCB p_MCB, p_MCB0; + + if ((task_id == 0U) || (task_id == os_tsk.run->task_id)) { + /* Terminate itself. */ + os_tsk.run->state = INACTIVE; + os_tsk.run->tsk_stack = rt_get_PSP (); + rt_stk_check (); + p_MCB = os_tsk.run->p_mlnk; + while (p_MCB) { + /* Release mutexes owned by this task */ + if (p_MCB->p_lnk) { + /* A task is waiting for mutex. */ + p_TCB = rt_get_first ((P_XCB)p_MCB); +#ifdef __CMSIS_RTOS + rt_ret_val (p_TCB, 0U/*osOK*/); +#else + rt_ret_val (p_TCB, OS_R_MUT); +#endif + rt_rmv_dly (p_TCB); + p_TCB->state = READY; + rt_put_prio (&os_rdy, p_TCB); + /* A waiting task becomes the owner of this mutex. */ + p_MCB0 = p_MCB->p_mlnk; + p_MCB->level = 1U; + p_MCB->owner = p_TCB; + p_MCB->p_mlnk = p_TCB->p_mlnk; + p_TCB->p_mlnk = p_MCB; + p_MCB = p_MCB0; + } + else { + p_MCB0 = p_MCB->p_mlnk; + p_MCB->level = 0U; + p_MCB->owner = NULL; + p_MCB->p_mlnk = NULL; + p_MCB = p_MCB0; + } + } + os_active_TCB[os_tsk.run->task_id-1U] = NULL; + rt_free_box (mp_stk, os_tsk.run->stack); + os_tsk.run->stack = NULL; + DBG_TASK_NOTIFY(os_tsk.run, __FALSE); + rt_free_box (mp_tcb, os_tsk.run); + os_tsk.run = NULL; + rt_dispatch (NULL); + /* The program should never come to this point. */ + } + else { + /* Find the task in the "os_active_TCB" array. */ + if ((task_id > os_maxtaskrun) || (os_active_TCB[task_id-1U] == NULL)) { + /* Task with "task_id" not found or not started. */ + return (OS_R_NOK); + } + task_context = os_active_TCB[task_id-1U]; + rt_rmv_list (task_context); + rt_rmv_dly (task_context); + p_MCB = task_context->p_mlnk; + while (p_MCB) { + /* Release mutexes owned by this task */ + if (p_MCB->p_lnk) { + /* A task is waiting for mutex. */ + p_TCB = rt_get_first ((P_XCB)p_MCB); +#ifdef __CMSIS_RTOS + rt_ret_val (p_TCB, 0U/*osOK*/); +#else + rt_ret_val (p_TCB, OS_R_MUT); +#endif + rt_rmv_dly (p_TCB); + p_TCB->state = READY; + rt_put_prio (&os_rdy, p_TCB); + /* A waiting task becomes the owner of this mutex. */ + p_MCB0 = p_MCB->p_mlnk; + p_MCB->level = 1U; + p_MCB->owner = p_TCB; + p_MCB->p_mlnk = p_TCB->p_mlnk; + p_TCB->p_mlnk = p_MCB; + p_MCB = p_MCB0; + } + else { + p_MCB0 = p_MCB->p_mlnk; + p_MCB->level = 0U; + p_MCB->owner = NULL; + p_MCB->p_mlnk = NULL; + p_MCB = p_MCB0; + } + } + os_active_TCB[task_id-1U] = NULL; + rt_free_box (mp_stk, task_context->stack); + task_context->stack = NULL; + DBG_TASK_NOTIFY(task_context, __FALSE); + rt_free_box (mp_tcb, task_context); + if (rt_rdy_prio() > os_tsk.run->prio) { + /* Ready task has higher priority than running task. */ + os_tsk.run->state = READY; + rt_put_prio (&os_rdy, os_tsk.run); + rt_dispatch (NULL); + } + } + return (OS_R_OK); +} + + +/*--------------------------- rt_sys_init -----------------------------------*/ + +#ifdef __CMSIS_RTOS +void rt_sys_init (void) { +#else +void rt_sys_init (FUNCP first_task, U32 prio_stksz, void *stk) { +#endif + /* Initialize system and start up task declared with "first_task". */ + U32 i; + + DBG_INIT(); + + /* Initialize dynamic memory and task TCB pointers to NULL. */ + for (i = 0U; i < os_maxtaskrun; i++) { + os_active_TCB[i] = NULL; + } + rt_init_box (mp_tcb, (U32)mp_tcb_size, sizeof(struct OS_TCB)); + rt_init_box (mp_stk, mp_stk_size, BOX_ALIGN_8 | (U16)(os_stackinfo)); + rt_init_box ((U32 *)m_tmr, (U32)mp_tmr_size, sizeof(struct OS_TMR)); + + /* Set up TCB of idle demon */ + os_idle_TCB.task_id = 255U; + os_idle_TCB.priv_stack = 0U; + rt_init_context (&os_idle_TCB, 0U, os_idle_demon); + + /* Set up ready list: initially empty */ + os_rdy.cb_type = HCB; + os_rdy.p_lnk = NULL; + /* Set up delay list: initially empty */ + os_dly.cb_type = HCB; + os_dly.p_dlnk = NULL; + os_dly.p_blnk = NULL; + os_dly.delta_time = 0U; + + /* Fix SP and system variables to assume idle task is running */ + /* Transform main program into idle task by assuming idle TCB */ +#ifndef __CMSIS_RTOS + rt_set_PSP (os_idle_TCB.tsk_stack+32U); +#endif + os_tsk.run = &os_idle_TCB; + os_tsk.run->state = RUNNING; + + /* Initialize ps queue */ + os_psq->first = 0U; + os_psq->last = 0U; + os_psq->size = os_fifo_size; + + rt_init_robin (); + +#ifndef __CMSIS_RTOS + /* Initialize SVC and PendSV */ + rt_svc_init (); + + /* Initialize and start system clock timer */ + os_tick_irqn = os_tick_init (); + if (os_tick_irqn >= 0) { + OS_X_INIT((U32)os_tick_irqn); + } + + /* Start up first user task before entering the endless loop */ + rt_tsk_create (first_task, prio_stksz, stk, NULL); +#endif +} + + +/*--------------------------- rt_sys_start ----------------------------------*/ + +#ifdef __CMSIS_RTOS +void rt_sys_start (void) { + /* Start system */ + + /* Initialize SVC and PendSV */ + rt_svc_init (); + + /* Initialize and start system clock timer */ + os_tick_irqn = os_tick_init (); + if (os_tick_irqn >= 0) { + OS_X_INIT((U32)os_tick_irqn); + } +} +#endif + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ diff --git a/rtos/rtx/TARGET_CORTEX_A/rt_Task.h b/rtos/rtx/TARGET_CORTEX_A/rt_Task.h new file mode 100644 index 00000000000..b44ab55c0d7 --- /dev/null +++ b/rtos/rtx/TARGET_CORTEX_A/rt_Task.h @@ -0,0 +1,81 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: RT_TASK.H + * Purpose: Task functions and system start up. + * Rev.: V4.79 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 ARM Germany GmbH + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + +/* Definitions */ + +/* Values for 'state' */ +#define INACTIVE 0U +#define READY 1U +#define RUNNING 2U +#define WAIT_DLY 3U +#define WAIT_ITV 4U +#define WAIT_OR 5U +#define WAIT_AND 6U +#define WAIT_SEM 7U +#define WAIT_MBX 8U +#define WAIT_MUT 9U + +/* Return codes */ +#define OS_R_TMO 0x01U +#define OS_R_EVT 0x02U +#define OS_R_SEM 0x03U +#define OS_R_MBX 0x04U +#define OS_R_MUT 0x05U + +#define OS_R_OK 0x00U +#define OS_R_NOK 0xFFU + +/* Variables */ +extern struct OS_TSK os_tsk; +extern struct OS_TCB os_idle_TCB; + +/* Functions */ +extern void rt_switch_req (P_TCB p_new); +extern void rt_dispatch (P_TCB next_TCB); +extern void rt_block (U16 timeout, U8 block_state); +extern void rt_tsk_pass (void); +extern OS_TID rt_tsk_self (void); +extern OS_RESULT rt_tsk_prio (OS_TID task_id, U8 new_prio); +extern OS_TID rt_tsk_create (FUNCP task, U32 prio_stksz, void *stk, void *argv); +extern OS_RESULT rt_tsk_delete (OS_TID task_id); +#ifdef __CMSIS_RTOS +extern void rt_sys_init (void); +extern void rt_sys_start (void); +#else +extern void rt_sys_init (FUNCP first_task, U32 prio_stksz, void *stk); +#endif + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ diff --git a/rtos/rtx/TARGET_CORTEX_A/rt_Time.c b/rtos/rtx/TARGET_CORTEX_A/rt_Time.c new file mode 100644 index 00000000000..9b02dd5d26b --- /dev/null +++ b/rtos/rtx/TARGET_CORTEX_A/rt_Time.c @@ -0,0 +1,93 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: RT_TIME.C + * Purpose: Delay and interval wait functions + * Rev.: V4.79 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 ARM Germany GmbH + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Config.h" +#include "rt_Task.h" +#include "rt_Time.h" + +/*---------------------------------------------------------------------------- + * Global Variables + *---------------------------------------------------------------------------*/ + +/* Free running system tick counter */ +U32 os_time; + + +/*---------------------------------------------------------------------------- + * Functions + *---------------------------------------------------------------------------*/ + + +/*--------------------------- rt_time_get -----------------------------------*/ + +U32 rt_time_get (void) { + /* Get system time tick */ + return (os_time); +} + + +/*--------------------------- rt_dly_wait -----------------------------------*/ + +void rt_dly_wait (U16 delay_time) { + /* Delay task by "delay_time" */ + rt_block (delay_time, WAIT_DLY); +} + + +/*--------------------------- rt_itv_set ------------------------------------*/ + +void rt_itv_set (U16 interval_time) { + /* Set interval length and define start of first interval */ + os_tsk.run->interval_time = interval_time; + os_tsk.run->delta_time = interval_time + (U16)os_time; +} + + +/*--------------------------- rt_itv_wait -----------------------------------*/ + +void rt_itv_wait (void) { + /* Wait for interval end and define start of next one */ + U16 delta; + + delta = os_tsk.run->delta_time - (U16)os_time; + os_tsk.run->delta_time += os_tsk.run->interval_time; + if ((delta & 0x8000U) == 0U) { + rt_block (delta, WAIT_ITV); + } +} + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ diff --git a/rtos/rtx/TARGET_CORTEX_A/rt_Time.h b/rtos/rtx/TARGET_CORTEX_A/rt_Time.h new file mode 100644 index 00000000000..e02983d3ce1 --- /dev/null +++ b/rtos/rtx/TARGET_CORTEX_A/rt_Time.h @@ -0,0 +1,46 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: RT_TIME.H + * Purpose: Delay and interval wait functions definitions + * Rev.: V4.70 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2013 ARM Germany GmbH + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + +/* Variables */ +extern U32 os_time; + +/* Functions */ +extern U32 rt_time_get (void); +extern void rt_dly_wait (U16 delay_time); +extern void rt_itv_set (U16 interval_time); +extern void rt_itv_wait (void); + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ diff --git a/rtos/rtx/TARGET_CORTEX_A/rt_Timer.h b/rtos/rtx/TARGET_CORTEX_A/rt_Timer.h new file mode 100644 index 00000000000..3db3e0a67f0 --- /dev/null +++ b/rtos/rtx/TARGET_CORTEX_A/rt_Timer.h @@ -0,0 +1,45 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: RT_TIMER.H + * Purpose: User timer functions + * Rev.: V4.70 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2013 ARM Germany GmbH + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + +/* Variables */ +extern struct OS_XTMR os_tmr; + +/* Functions */ +extern void rt_tmr_tick (void); +extern OS_ID rt_tmr_create (U16 tcnt, U16 info); +extern OS_ID rt_tmr_kill (OS_ID timer); + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ diff --git a/rtos/rtx/TARGET_CORTEX_A/rt_TypeDef.h b/rtos/rtx/TARGET_CORTEX_A/rt_TypeDef.h new file mode 100644 index 00000000000..09f3e0369c1 --- /dev/null +++ b/rtos/rtx/TARGET_CORTEX_A/rt_TypeDef.h @@ -0,0 +1,186 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: RT_TYPEDEF.H + * Purpose: Type Definitions + * Rev.: V4.79 (plus large stack) + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 ARM Germany GmbH + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + *---------------------------------------------------------------------------*/ + +/* Types */ +typedef char S8; +typedef unsigned char U8; +typedef short S16; +typedef unsigned short U16; +typedef int S32; +typedef unsigned int U32; +typedef long long S64; +typedef unsigned long long U64; +typedef unsigned char BIT; +typedef unsigned int BOOL; +typedef void (*FUNCP)(void); + +typedef U32 OS_TID; +typedef void *OS_ID; +typedef U32 OS_RESULT; + +typedef struct OS_TCB { + /* General part: identical for all implementations. */ + U8 cb_type; /* Control Block Type */ + U8 state; /* Task state */ + U8 prio; /* Execution priority */ + U8 task_id; /* Task ID value for optimized TCB access */ + struct OS_TCB *p_lnk; /* Link pointer for ready/sem. wait list */ + struct OS_TCB *p_rlnk; /* Link pointer for sem./mbx lst backwards */ + struct OS_TCB *p_dlnk; /* Link pointer for delay list */ + struct OS_TCB *p_blnk; /* Link pointer for delay list backwards */ + U16 delta_time; /* Time until time out */ + U16 interval_time; /* Time interval for periodic waits */ + U16 events; /* Event flags */ + U16 waits; /* Wait flags */ + void **msg; /* Direct message passing when task waits */ + struct OS_MUCB *p_mlnk; /* Link pointer for mutex owner list */ + U8 prio_base; /* Base priority */ + + /* Hardware dependant part: specific for Cortex processor */ + U8 stack_frame; /* Stack frame: 0x0 Basic, 0x1 Extended, 0x2 VFP/D16 stacked, 0x4 NEON/D32 stacked */ +#if defined (__ICCARM__) +#ifndef __LARGE_PRIV_STACK + U16 priv_stack; /* Private stack size, 0= system assigned */ +#else + U16 reserved; /* Reserved (padding) */ + U32 priv_stack; /* Private stack size for LARGE_STACK, 0= system assigned */ +#endif /* __LARGE_PRIV_STACK */ +#else + U16 reserved; /* Reserved (padding) */ + U32 priv_stack; /* Private stack size for LARGE_STACK, 0= system assigned */ +#endif + U32 tsk_stack; /* Current task Stack pointer (R13) */ + U32 *stack; /* Pointer to Task Stack memory block */ + + /* Task entry point used for uVision debugger */ + FUNCP ptask; /* Task entry address */ + void *argv; /* Task argument */ +} *P_TCB; +#define TCB_TID 3 /* 'task id' offset */ +#define TCB_STACKF 37 /* 'stack_frame' offset */ +#if defined (__ICCARM__) +#ifndef __LARGE_PRIV_STACK +#define TCB_TSTACK 40 /* 'tsk_stack' offset */ +#else +#define TCB_TSTACK 44 /* 'tsk_stack' offset for LARGE_STACK */ +#endif /* __LARGE_PRIV_STACK */ +#else +#define TCB_TSTACK 44 /* 'tsk_stack' offset for LARGE_STACK */ +#endif + +typedef struct OS_PSFE { /* Post Service Fifo Entry */ + void *id; /* Object Identification */ + U32 arg; /* Object Argument */ +} *P_PSFE; + +typedef struct OS_PSQ { /* Post Service Queue */ + U8 first; /* FIFO Head Index */ + U8 last; /* FIFO Tail Index */ + U8 count; /* Number of stored items in FIFO */ + U8 size; /* FIFO Size */ + struct OS_PSFE q[1]; /* FIFO Content */ +} *P_PSQ; + +typedef struct OS_TSK { + P_TCB run; /* Current running task */ + P_TCB new_tsk; /* Scheduled task to run */ +} *P_TSK; + +typedef struct OS_ROBIN { /* Round Robin Control */ + P_TCB task; /* Round Robin task */ + U16 time; /* Round Robin switch time */ + U16 tout; /* Round Robin timeout */ +} *P_ROBIN; + +typedef struct OS_XCB { + U8 cb_type; /* Control Block Type */ + struct OS_TCB *p_lnk; /* Link pointer for ready/sem. wait list */ + struct OS_TCB *p_rlnk; /* Link pointer for sem./mbx lst backwards */ + struct OS_TCB *p_dlnk; /* Link pointer for delay list */ + struct OS_TCB *p_blnk; /* Link pointer for delay list backwards */ + U16 delta_time; /* Time until time out */ +} *P_XCB; + +typedef struct OS_MCB { + U8 cb_type; /* Control Block Type */ + U8 state; /* State flag variable */ + U8 isr_st; /* State flag variable for isr functions */ + struct OS_TCB *p_lnk; /* Chain of tasks waiting for message */ + U16 first; /* Index of the message list begin */ + U16 last; /* Index of the message list end */ + U16 count; /* Actual number of stored messages */ + U16 size; /* Maximum number of stored messages */ + void *msg[1]; /* FIFO for Message pointers 1st element */ +} *P_MCB; + +typedef struct OS_SCB { + U8 cb_type; /* Control Block Type */ + U8 mask; /* Semaphore token mask */ + U16 tokens; /* Semaphore tokens */ + struct OS_TCB *p_lnk; /* Chain of tasks waiting for tokens */ +} *P_SCB; + +typedef struct OS_MUCB { + U8 cb_type; /* Control Block Type */ + U16 level; /* Call nesting level */ + struct OS_TCB *p_lnk; /* Chain of tasks waiting for mutex */ + struct OS_TCB *owner; /* Mutex owner task */ + struct OS_MUCB *p_mlnk; /* Chain of mutexes by owner task */ +} *P_MUCB; + +typedef struct OS_XTMR { + struct OS_TMR *next; + U16 tcnt; +} *P_XTMR; + +typedef struct OS_TMR { + struct OS_TMR *next; /* Link pointer to Next timer */ + U16 tcnt; /* Timer delay count */ + U16 info; /* User defined call info */ +} *P_TMR; + +typedef struct OS_BM { + void *free; /* Pointer to first free memory block */ + void *end; /* Pointer to memory block end */ + U32 blk_size; /* Memory block size */ +} *P_BM; + +/* Definitions */ +#define __TRUE 1U +#define __FALSE 0U +#define NULL ((void *) 0) + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ diff --git a/rtos/rtx/TARGET_CORTEX_M/RTX_Conf_CM.c b/rtos/rtx/TARGET_CORTEX_M/RTX_Conf_CM.c index 206e6813c50..e23e3e54a17 100755 --- a/rtos/rtx/TARGET_CORTEX_M/RTX_Conf_CM.c +++ b/rtos/rtx/TARGET_CORTEX_M/RTX_Conf_CM.c @@ -33,7 +33,6 @@ *---------------------------------------------------------------------------*/ #include "cmsis_os.h" -#include "mbed_error.h" /*---------------------------------------------------------------------------- @@ -245,6 +244,7 @@ void os_idle_demon (void) { /*---------------------------------------------------------------------------- * RTX Errors *---------------------------------------------------------------------------*/ +extern void error(const char* format, ...); extern osThreadId svcThreadGetId (void); void os_error (uint32_t err_code) { diff --git a/targets/TARGET_ARM_SSG/TARGET_BEETLE/device/cmsis.h b/targets/TARGET_ARM_SSG/TARGET_BEETLE/device/cmsis.h index 2b1a266dbfa..df172235201 100644 --- a/targets/TARGET_ARM_SSG/TARGET_BEETLE/device/cmsis.h +++ b/targets/TARGET_ARM_SSG/TARGET_BEETLE/device/cmsis.h @@ -30,6 +30,8 @@ #include "apb_dualtimer.h" /* APB Timer */ #include "apb_timer.h" +/* Cortex M3 SysTick Driver */ +#include "systick_timer.h" /* Flash Cache Driver */ #include "fcache_api.h" /* Embedded Flash Driver */ diff --git a/targets/TARGET_ARM_SSG/TARGET_BEETLE/device/systick_timer.c b/targets/TARGET_ARM_SSG/TARGET_BEETLE/device/systick_timer.c new file mode 100644 index 00000000000..d992553c5f6 --- /dev/null +++ b/targets/TARGET_ARM_SSG/TARGET_BEETLE/device/systick_timer.c @@ -0,0 +1,94 @@ +/* + * PackageLicenseDeclared: Apache-2.0 + * Copyright (c) 2015 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * 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. + */ + +#include "cmsis.h" +#include "systick_timer.h" + +volatile uint32_t MyTicks; + +/* Private Data SysTick */ +static uint32_t clock; + +/* + * This Timer is written for MBED OS so the interrupt + * is used to keep track of the overflow. + */ +#define SYSTICK_MAX_RELOAD 0xFFFFFFFF +#define SYSTICK_DIVIDER_US (SystemCoreClock/1000000) + +void SysTick_IRQ_Handler(void) +{ + MyTicks++; +#if 0 + printf("System Tick Interrupt: %u\n\r", MyTicks); +#endif +} + +/* + * SysTick_Initialize(): Initializes the SysTick timer + */ +void SysTick_Initialize(void) +{ + clock = SYSTICK_MAX_RELOAD; +#if 0 + printf("\n\rEnable System Tick Interrupt...\n\r"); +#endif + MyTicks=0; + + /* SysTick Reload Value Register */ + SysTick->LOAD = clock; + + /* + * SysTick_CTRL_CLKSOURCE_Msk : Use core's clock + * SysTick_CTRL_ENABLE_Msk : Enable SysTick + * SysTick_CTRL_TICKINT_Msk : Active the SysTick interrupt on the NVIC + */ + SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk + | SysTick_CTRL_ENABLE_Msk + | SysTick_CTRL_TICKINT_Msk; + + /* Register the Interrupt */ + NVIC_SetVector(SysTick_IRQn, (uint32_t)SysTick_IRQ_Handler); + NVIC_EnableIRQ(SysTick_IRQn); +} + +/* + * SysTick_Disable(): Disables the SysTick timer + */ +void SysTick_Disable(void) +{ + /* Disable SysTick */ + SysTick->CTRL = 0; +} + +/* + * SysTick_Read(): Read SysTick Value + * @return: the SysTick VALUE + */ +uint32_t SysTick_Read(void) +{ + return ((clock - (SysTick->VAL)) / SYSTICK_DIVIDER_US); +} + +/* + * SysTick_Overflow(): Read SysTick Overflow Value + * @return: the SysTick Overflow VALUE + */ +uint32_t SysTick_Overflow(void) +{ + return MyTicks; +} diff --git a/targets/TARGET_ARM_SSG/TARGET_BEETLE/device/systick_timer.h b/targets/TARGET_ARM_SSG/TARGET_BEETLE/device/systick_timer.h new file mode 100644 index 00000000000..0d214c757b2 --- /dev/null +++ b/targets/TARGET_ARM_SSG/TARGET_BEETLE/device/systick_timer.h @@ -0,0 +1,51 @@ +/* + * PackageLicenseDeclared: Apache-2.0 + * Copyright (c) 2015 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * 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. + */ + +#ifndef _SYSTICK_TIMER_H +#define _SYSTICK_TIMER_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * SysTick_Initialize(): Initializes the SysTick timer + */ +void SysTick_Initialize(void); + +/* + * SysTick_Disable(): Disables the SysTick timer + */ +void SysTick_Disable(void); + +/* + * SysTick_Read(): Read SysTick Value + * @return: the SysTick VALUE + */ +uint32_t SysTick_Read(void); + +/* + * SysTick_Overflow(): Read SysTick Overflow Value + * @return: the SysTick Overflow VALUE + */ +uint32_t SysTick_Overflow(void); + +#ifdef __cplusplus +} +#endif + +#endif /* _SYSTICK_TIMER_H */ diff --git a/targets/TARGET_ARM_SSG/mbed_rtx.h b/targets/TARGET_ARM_SSG/mbed_rtx.h index 31c789d9265..f88e05e44af 100644 --- a/targets/TARGET_ARM_SSG/mbed_rtx.h +++ b/targets/TARGET_ARM_SSG/mbed_rtx.h @@ -23,7 +23,7 @@ #define INITIAL_SP (0x20020000UL) #endif #ifndef OS_TASKCNT -#define OS_TASKCNT 7 +#define OS_TASKCNT 6 #endif #ifndef OS_MAINSTKSIZE #define OS_MAINSTKSIZE 112 diff --git a/targets/TARGET_Freescale/TARGET_KLXX/TARGET_KL46Z/PinNames.h b/targets/TARGET_Freescale/TARGET_KLXX/TARGET_KL46Z/PinNames.h index 83b2dae7b93..d5bb7bded87 100644 --- a/targets/TARGET_Freescale/TARGET_KLXX/TARGET_KL46Z/PinNames.h +++ b/targets/TARGET_Freescale/TARGET_KLXX/TARGET_KL46Z/PinNames.h @@ -203,9 +203,6 @@ typedef enum { //Push buttons SW1 = PTC3, SW3 = PTC12, - // Standardized button names - BUTTON1 = SW1, - BUTTON2 = SW3, // USB Pins USBTX = PTA2, diff --git a/targets/TARGET_Freescale/TARGET_KLXX/us_ticker.c b/targets/TARGET_Freescale/TARGET_KLXX/us_ticker.c index 8aee691985c..c29c624552f 100644 --- a/targets/TARGET_Freescale/TARGET_KLXX/us_ticker.c +++ b/targets/TARGET_Freescale/TARGET_KLXX/us_ticker.c @@ -187,11 +187,11 @@ static void lptmr_isr(void) { void us_ticker_set_interrupt(timestamp_t timestamp) { int delta = (int)((uint32_t)timestamp - us_ticker_read()); if (delta <= 0) { - // This event was in the past. Force it into the very near - // future instead. - delta = 1; - } - + // This event was in the past: + us_ticker_irq_handler(); + return; + } + us_ticker_int_counter = (uint32_t)(delta >> 16); us_ticker_int_remainder = (uint16_t)(0xFFFF & delta); if (us_ticker_int_counter > 0) { diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_K66F/TARGET_FRDM/PinNames.h b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_K66F/TARGET_FRDM/PinNames.h index 7ff8b86d758..6f461543047 100644 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_K66F/TARGET_FRDM/PinNames.h +++ b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_K66F/TARGET_FRDM/PinNames.h @@ -204,9 +204,6 @@ typedef enum { //Push buttons SW2 = PTD11, SW3 = PTA10, - // Standardized button names - BUTTON1 = SW2, - BUTTON2 = SW3, // USB Pins USBTX = PTB17, diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_K66F/device/TOOLCHAIN_ARM_STD/MK66FN2M0xxx18.sct b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_K66F/device/TOOLCHAIN_ARM_STD/MK66FN2M0xxx18.sct index c19ce975ff1..d619a559784 100644 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_K66F/device/TOOLCHAIN_ARM_STD/MK66FN2M0xxx18.sct +++ b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_K66F/device/TOOLCHAIN_ARM_STD/MK66FN2M0xxx18.sct @@ -47,6 +47,10 @@ */ #define __ram_vector_table__ 1 +/* Heap 1/4 of ram and stack 1/8 */ +#define __stack_size__ 0x8000 +#define __heap_size__ 0x10000 + #if (defined(__ram_vector_table__)) #define __ram_vector_table_size__ 0x00000400 #else diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_K66F/device/TOOLCHAIN_GCC_ARM/MK66FN2M0xxx18.ld b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_K66F/device/TOOLCHAIN_GCC_ARM/MK66FN2M0xxx18.ld index 4145ee2c690..5adafcfdae8 100644 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_K66F/device/TOOLCHAIN_GCC_ARM/MK66FN2M0xxx18.ld +++ b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_K66F/device/TOOLCHAIN_GCC_ARM/MK66FN2M0xxx18.ld @@ -50,15 +50,9 @@ ENTRY(Reset_Handler) __ram_vector_table__ = 1; -/* With the RTOS in use, this does not affect the main stack size. The size of - * the stack where main runs is determined via the RTOS. */ -__stack_size__ = 0x400; - -/* This is the guaranteed minimum available heap size for an application. When - * uVisor is enabled, this is also the maximum available heap size. The - * HEAP_SIZE value is set by uVisor porters to balance the size of the legacy - * heap and the page heap in uVisor applications. */ -__heap_size__ = 0x6000; +/* Heap 1/4 of ram and stack 1/8 */ +__stack_size__ = 0x8000; +__heap_size__ = 0x10000; HEAP_SIZE = DEFINED(__heap_size__) ? __heap_size__ : 0x0400; STACK_SIZE = DEFINED(__stack_size__) ? __stack_size__ : 0x0400; diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_K82F/TARGET_FRDM/PinNames.h b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_K82F/TARGET_FRDM/PinNames.h index 30f5d2d5c42..9e88d8e830f 100644 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_K82F/TARGET_FRDM/PinNames.h +++ b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_K82F/TARGET_FRDM/PinNames.h @@ -134,9 +134,6 @@ typedef enum { //Push buttons SW2 = PTA4, SW3 = PTC6, - // Standardized button names - BUTTON1 = SW2, - BUTTON2 = SW3, // USB Pins USBTX = PTC15, diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_K82F/device/TOOLCHAIN_ARM_STD/MK82FN256xxx15.sct b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_K82F/device/TOOLCHAIN_ARM_STD/MK82FN256xxx15.sct index 59981df3c12..60da5f63a51 100644 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_K82F/device/TOOLCHAIN_ARM_STD/MK82FN256xxx15.sct +++ b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_K82F/device/TOOLCHAIN_ARM_STD/MK82FN256xxx15.sct @@ -49,6 +49,10 @@ */ #define __ram_vector_table__ 1 + +/* Heap 1/4 of ram and stack 1/8 */ +#define __stack_size__ 0x8000 +#define __heap_size__ 0x10000 #if (defined(__ram_vector_table__)) #define __ram_vector_table_size__ 0x000003C0 diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_K82F/device/TOOLCHAIN_GCC_ARM/MK82FN256xxx15.ld b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_K82F/device/TOOLCHAIN_GCC_ARM/MK82FN256xxx15.ld index 329f63e36e0..982f9a5528b 100644 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_K82F/device/TOOLCHAIN_GCC_ARM/MK82FN256xxx15.ld +++ b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_K82F/device/TOOLCHAIN_GCC_ARM/MK82FN256xxx15.ld @@ -52,15 +52,9 @@ ENTRY(Reset_Handler) __ram_vector_table__ = 1; -/* With the RTOS in use, this does not affect the main stack size. The size of - * the stack where main runs is determined via the RTOS. */ -__stack_size__ = 0x400; - -/* This is the guaranteed minimum available heap size for an application. When - * uVisor is enabled, this is also the maximum available heap size. The - * HEAP_SIZE value is set by uVisor porters to balance the size of the legacy - * heap and the page heap in uVisor applications. */ -__heap_size__ = 0x6000; +/* Heap 1/4 of ram and stack 1/8 */ +__stack_size__ = 0x8000; +__heap_size__ = 0x10000; HEAP_SIZE = DEFINED(__heap_size__) ? __heap_size__ : 0x0400; STACK_SIZE = DEFINED(__stack_size__) ? __stack_size__ : 0x0400; diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KL27Z/TARGET_FRDM/PinNames.h b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KL27Z/TARGET_FRDM/PinNames.h index 37ddd837fdd..dab9a16ce70 100644 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KL27Z/TARGET_FRDM/PinNames.h +++ b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KL27Z/TARGET_FRDM/PinNames.h @@ -98,9 +98,6 @@ typedef enum { //Push buttons SW1 = PTA4, SW3 = PTC1, - // Standardized button names - BUTTON1 = SW1, - BUTTON2 = SW3, // USB Pins USBTX = PTA2, diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KL27Z/device/TOOLCHAIN_ARM_STD/MKL27Z64xxx4.sct b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KL27Z/device/TOOLCHAIN_ARM_STD/MKL27Z64xxx4.sct index 193fe919489..0d6631943eb 100644 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KL27Z/device/TOOLCHAIN_ARM_STD/MKL27Z64xxx4.sct +++ b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KL27Z/device/TOOLCHAIN_ARM_STD/MKL27Z64xxx4.sct @@ -50,6 +50,10 @@ */ #define __ram_vector_table__ 1 +/* Heap 1/4 of ram and stack 1/8 */ +#define __stack_size__ 0x800 +#define __heap_size__ 0x1000 + #if (defined(__ram_vector_table__)) #define __ram_vector_table_size__ 0x00000200 #else diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KL27Z/device/TOOLCHAIN_GCC_ARM/MKL27Z64xxx4.ld b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KL27Z/device/TOOLCHAIN_GCC_ARM/MKL27Z64xxx4.ld index d07efd1a041..10d3cc4bdcb 100644 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KL27Z/device/TOOLCHAIN_GCC_ARM/MKL27Z64xxx4.ld +++ b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KL27Z/device/TOOLCHAIN_GCC_ARM/MKL27Z64xxx4.ld @@ -53,11 +53,9 @@ ENTRY(Reset_Handler) __ram_vector_table__ = 1; -/* With the RTOS in use, this does not affect the main stack size. The size of - * the stack where main runs is determined via the RTOS. */ -__stack_size__ = 0x400; -/* With the RTOS in use, this does not affect the main heap size. */ -__heap_size__ = 0x0; +/* Heap 1/4 of ram and stack 1/8 */ +__stack_size__ = 0x800; +__heap_size__ = 0x1000; HEAP_SIZE = DEFINED(__heap_size__) ? __heap_size__ : 0x0400; STACK_SIZE = DEFINED(__stack_size__) ? __stack_size__ : 0x0400; diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KL43Z/TARGET_FRDM/PinNames.h b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KL43Z/TARGET_FRDM/PinNames.h index 081010164cf..a767b72c21a 100644 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KL43Z/TARGET_FRDM/PinNames.h +++ b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KL43Z/TARGET_FRDM/PinNames.h @@ -97,9 +97,6 @@ typedef enum { //Push buttons SW1 = PTA4, SW3 = PTC3, - // Standardized button names - BUTTON1 = SW1, - BUTTON2 = SW3, // USB Pins USBTX = PTA2, diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KL43Z/device/TOOLCHAIN_ARM_STD/MKL43Z256xxx4.sct b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KL43Z/device/TOOLCHAIN_ARM_STD/MKL43Z256xxx4.sct index 77eaca6db54..5dcedd1a0a2 100644 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KL43Z/device/TOOLCHAIN_ARM_STD/MKL43Z256xxx4.sct +++ b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KL43Z/device/TOOLCHAIN_ARM_STD/MKL43Z256xxx4.sct @@ -47,6 +47,10 @@ */ #define __ram_vector_table__ 1 +/* Heap 1/4 of ram and stack 1/8 */ +#define __stack_size__ 0x1000 +#define __heap_size__ 0x2800 + #if (defined(__ram_vector_table__)) #define __ram_vector_table_size__ 0x00000200 #else diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KL43Z/device/TOOLCHAIN_GCC_ARM/MKL43Z256xxx4.ld b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KL43Z/device/TOOLCHAIN_GCC_ARM/MKL43Z256xxx4.ld index d5390db1b72..08920c6e252 100644 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KL43Z/device/TOOLCHAIN_GCC_ARM/MKL43Z256xxx4.ld +++ b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KL43Z/device/TOOLCHAIN_GCC_ARM/MKL43Z256xxx4.ld @@ -50,14 +50,8 @@ ENTRY(Reset_Handler) __ram_vector_table__ = 1; -/* With the RTOS in use, this does not affect the main stack size. The size of - * the stack where main runs is determined via the RTOS. */ -__stack_size__ = 0x400; - -/* This is the guaranteed minimum available heap size for an application. When - * uVisor is enabled, this is also the maximum available heap size. The - * HEAP_SIZE value is set by uVisor porters to balance the size of the legacy - * heap and the page heap in uVisor applications. */ +/* Heap 1/4 of ram and stack 1/8 */ +__stack_size__ = 0x1000; __heap_size__ = 0x2800; HEAP_SIZE = DEFINED(__heap_size__) ? __heap_size__ : 0x0400; diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KL82Z/TARGET_FRDM/PinNames.h b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KL82Z/TARGET_FRDM/PinNames.h index 45b4a118e7b..55ad0cf4f5a 100644 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KL82Z/TARGET_FRDM/PinNames.h +++ b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KL82Z/TARGET_FRDM/PinNames.h @@ -118,9 +118,6 @@ typedef enum { //Push buttons SW2 = PTA4, SW3 = PTD0, - // Standardized button names - BUTTON1 = SW2, - BUTTON2 = SW3, // USB Pins USBTX = PTB17, diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KL82Z/device/TOOLCHAIN_ARM_STD/MKL82Z128xxx7.sct b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KL82Z/device/TOOLCHAIN_ARM_STD/MKL82Z128xxx7.sct index 47cc83fdbe2..a7fd0ecc526 100644 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KL82Z/device/TOOLCHAIN_ARM_STD/MKL82Z128xxx7.sct +++ b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KL82Z/device/TOOLCHAIN_ARM_STD/MKL82Z128xxx7.sct @@ -50,6 +50,10 @@ */ #define __ram_vector_table__ 1 +/* Heap 1/4 of ram and stack 1/8 */ +#define __stack_size__ 0x3000 +#define __heap_size__ 0x6000 + #if (defined(__ram_vector_table__)) #define __ram_vector_table_size__ 0x00000140 #else diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KL82Z/device/TOOLCHAIN_GCC_ARM/MKL82Z128xxx7.ld b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KL82Z/device/TOOLCHAIN_GCC_ARM/MKL82Z128xxx7.ld index 7c88f8dc8b1..53fa9d29a46 100644 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KL82Z/device/TOOLCHAIN_GCC_ARM/MKL82Z128xxx7.ld +++ b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KL82Z/device/TOOLCHAIN_GCC_ARM/MKL82Z128xxx7.ld @@ -53,14 +53,8 @@ ENTRY(Reset_Handler) __ram_vector_table__ = 1; -/* With the RTOS in use, this does not affect the main stack size. The size of - * the stack where main runs is determined via the RTOS. */ -__stack_size__ = 0x400; - -/* This is the guaranteed minimum available heap size for an application. When - * uVisor is enabled, this is also the maximum available heap size. The - * HEAP_SIZE value is set by uVisor porters to balance the size of the legacy - * heap and the page heap in uVisor applications. */ +/* Heap 1/4 of ram and stack 1/8 */ +__stack_size__ = 0x3000; __heap_size__ = 0x6000; HEAP_SIZE = DEFINED(__heap_size__) ? __heap_size__ : 0x0400; diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KW24D/TARGET_FRDM/PinNames.h b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KW24D/TARGET_FRDM/PinNames.h index 534e1d841d9..41a1af824fb 100644 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KW24D/TARGET_FRDM/PinNames.h +++ b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KW24D/TARGET_FRDM/PinNames.h @@ -82,11 +82,6 @@ typedef enum { SW2 = PTE3, SW3 = PTD1, SW4 = PTA19, - // Standardized button names - BUTTON1 = SW1, - BUTTON2 = SW2, - BUTTON3 = SW3, - BUTTON4 = SW4, // USB Pins USBTX = PTE0, 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 0cee6416439..b58b770e09c 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 @@ -45,6 +45,10 @@ */ #define __ram_vector_table__ 1 +/* Heap 1/4 of ram and stack 1/8 */ +#define __stack_size__ 0x2000 +#define __heap_size__ 0x4000 + #if (defined(__ram_vector_table__)) #define __ram_vector_table_size__ 0x00000400 #else 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 3ee0095bd31..a5a078e418d 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 @@ -48,14 +48,8 @@ ENTRY(Reset_Handler) __ram_vector_table__ = 1; -/* With the RTOS in use, this does not affect the main stack size. The size of - * the stack where main runs is determined via the RTOS. */ -__stack_size__ = 0x400; - -/* This is the guaranteed minimum available heap size for an application. When - * uVisor is enabled, this is also the maximum available heap size. The - * HEAP_SIZE value is set by uVisor porters to balance the size of the legacy - * heap and the page heap in uVisor applications. */ +/* Heap 1/4 of ram and stack 1/8 */ +__stack_size__ = 0x2000; __heap_size__ = 0x4000; HEAP_SIZE = DEFINED(__heap_size__) ? __heap_size__ : 0x0400; diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KW41Z/TARGET_FRDM/PinNames.h b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KW41Z/TARGET_FRDM/PinNames.h index 445bf59d9e9..125b90c5504 100644 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KW41Z/TARGET_FRDM/PinNames.h +++ b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KW41Z/TARGET_FRDM/PinNames.h @@ -69,9 +69,6 @@ typedef enum { //Push buttons SW3 = PTC4, SW4 = PTC5, - // Standardized button names - BUTTON1 = SW3, - BUTTON2 = SW4, // USB Pins USBTX = PTC7, diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KW41Z/device/TOOLCHAIN_ARM_STD/MKW41Z512xxx4.sct b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KW41Z/device/TOOLCHAIN_ARM_STD/MKW41Z512xxx4.sct index f1a9b291208..ece95f74cd9 100644 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KW41Z/device/TOOLCHAIN_ARM_STD/MKW41Z512xxx4.sct +++ b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KW41Z/device/TOOLCHAIN_ARM_STD/MKW41Z512xxx4.sct @@ -45,6 +45,10 @@ */ #define __ram_vector_table__ 1 +/* Heap 1/4 of ram and stack 1/8 */ +#define __stack_size__ 0x4000 +#define __heap_size__ 0x8000 + #if (defined(__ram_vector_table__)) #define __ram_vector_table_size__ 0x00000200 #else diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KW41Z/device/TOOLCHAIN_GCC_ARM/MKW41Z512xxx4.ld b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KW41Z/device/TOOLCHAIN_GCC_ARM/MKW41Z512xxx4.ld index 69f56747fc3..5d6da3d5ae3 100644 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KW41Z/device/TOOLCHAIN_GCC_ARM/MKW41Z512xxx4.ld +++ b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KW41Z/device/TOOLCHAIN_GCC_ARM/MKW41Z512xxx4.ld @@ -48,15 +48,9 @@ ENTRY(Reset_Handler) __ram_vector_table__ = 1; -/* With the RTOS in use, this does not affect the main stack size. The size of - * the stack where main runs is determined via the RTOS. */ -__stack_size__ = 0x400; - -/* This is the guaranteed minimum available heap size for an application. When - * uVisor is enabled, this is also the maximum available heap size. The - * HEAP_SIZE value is set by uVisor porters to balance the size of the legacy - * heap and the page heap in uVisor applications. */ -__heap_size__ = 0x6000; +/* Heap 1/4 of ram and stack 1/8 */ +__stack_size__ = 0x4000; +__heap_size__ = 0x8000; HEAP_SIZE = DEFINED(__heap_size__) ? __heap_size__ : 0x0400; STACK_SIZE = DEFINED(__stack_size__) ? __stack_size__ : 0x0400; diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K22F/TARGET_MCU_K22F512/TARGET_FRDM/PinNames.h b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K22F/TARGET_MCU_K22F512/TARGET_FRDM/PinNames.h index 3533d831c7d..c18628ff11a 100644 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K22F/TARGET_MCU_K22F512/TARGET_FRDM/PinNames.h +++ b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K22F/TARGET_MCU_K22F512/TARGET_FRDM/PinNames.h @@ -204,9 +204,6 @@ typedef enum { //Push buttons SW2 = PTC1, SW3 = PTB17, - // Standardized button names - BUTTON1 = SW2, - BUTTON2 = SW3, // USB Pins USBTX = PTE0, diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K22F/TARGET_MCU_K22F512/device/TOOLCHAIN_ARM_STD/MK22FN512xxx12.sct b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K22F/TARGET_MCU_K22F512/device/TOOLCHAIN_ARM_STD/MK22FN512xxx12.sct index 24f0ad79717..c02dadd688e 100644 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K22F/TARGET_MCU_K22F512/device/TOOLCHAIN_ARM_STD/MK22FN512xxx12.sct +++ b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K22F/TARGET_MCU_K22F512/device/TOOLCHAIN_ARM_STD/MK22FN512xxx12.sct @@ -51,6 +51,10 @@ */ #define __ram_vector_table__ 1 +/* Heap 1/4 of ram and stack 1/8 */ +#define __stack_size__ 0x4000 +#define __heap_size__ 0x8000 + #if (defined(__ram_vector_table__)) #define __ram_vector_table_size__ 0x00000400 #else diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/TARGET_RO359B/PeripheralNames.h b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/TARGET_RO359B/PeripheralNames.h deleted file mode 100644 index 752684c7e98..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/TARGET_RO359B/PeripheralNames.h +++ /dev/null @@ -1,137 +0,0 @@ -/* mbed Microcontroller Library - * Copyright (c) 2006-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. - * You may obtain a copy of the License at - * - * 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, - * 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. - */ -#ifndef MBED_PERIPHERALNAMES_H -#define MBED_PERIPHERALNAMES_H - -#include "cmsis.h" - -#ifdef __cplusplus -extern "C" { -#endif - -typedef enum { - OSC32KCLK = 1, -} RTCName; - -typedef enum { - UART_0 = 0, - UART_1 = 1, - UART_2 = 2, - UART_3 = 3, - UART_4 = 4, -} UARTName; - -#define STDIO_UART_TX USBTX -#define STDIO_UART_RX USBRX -#define STDIO_UART UART_0 - -typedef enum { - I2C_0 = 0, - I2C_1 = 1, - I2C_2 = 2, -} I2CName; - -#define TPM_SHIFT 8 -typedef enum { - PWM_1 = (0 << TPM_SHIFT) | (0), // FTM0 CH0 - PWM_2 = (0 << TPM_SHIFT) | (1), // FTM0 CH1 - PWM_3 = (0 << TPM_SHIFT) | (2), // FTM0 CH2 - PWM_4 = (0 << TPM_SHIFT) | (3), // FTM0 CH3 - PWM_5 = (0 << TPM_SHIFT) | (4), // FTM0 CH4 - PWM_6 = (0 << TPM_SHIFT) | (5), // FTM0 CH5 - PWM_7 = (0 << TPM_SHIFT) | (6), // FTM0 CH6 - PWM_8 = (0 << TPM_SHIFT) | (7), // FTM0 CH7 - PWM_9 = (1 << TPM_SHIFT) | (0), // FTM1 CH0 - PWM_10 = (1 << TPM_SHIFT) | (1), // FTM1 CH1 - PWM_11 = (1 << TPM_SHIFT) | (2), // FTM1 CH2 - PWM_12 = (1 << TPM_SHIFT) | (3), // FTM1 CH3 - PWM_13 = (1 << TPM_SHIFT) | (4), // FTM1 CH4 - PWM_14 = (1 << TPM_SHIFT) | (5), // FTM1 CH5 - PWM_15 = (1 << TPM_SHIFT) | (6), // FTM1 CH6 - PWM_16 = (1 << TPM_SHIFT) | (7), // FTM1 CH7 - PWM_17 = (2 << TPM_SHIFT) | (0), // FTM2 CH0 - PWM_18 = (2 << TPM_SHIFT) | (1), // FTM2 CH1 - PWM_19 = (2 << TPM_SHIFT) | (2), // FTM2 CH2 - PWM_20 = (2 << TPM_SHIFT) | (3), // FTM2 CH3 - PWM_21 = (2 << TPM_SHIFT) | (4), // FTM2 CH4 - PWM_22 = (2 << TPM_SHIFT) | (5), // FTM2 CH5 - PWM_23 = (2 << TPM_SHIFT) | (6), // FTM2 CH6 - PWM_24 = (2 << TPM_SHIFT) | (7), // FTM2 CH7 - PWM_25 = (3 << TPM_SHIFT) | (0), // FTM3 CH0 - PWM_26 = (3 << TPM_SHIFT) | (1), // FTM3 CH1 - PWM_27 = (3 << TPM_SHIFT) | (2), // FTM3 CH2 - PWM_28 = (3 << TPM_SHIFT) | (3), // FTM3 CH3 - PWM_29 = (3 << TPM_SHIFT) | (4), // FTM3 CH4 - PWM_30 = (3 << TPM_SHIFT) | (5), // FTM3 CH5 - PWM_31 = (3 << TPM_SHIFT) | (6), // FTM3 CH6 - PWM_32 = (3 << TPM_SHIFT) | (7), // FTM3 CH7 -} PWMName; - -#define ADC_INSTANCE_SHIFT 8 -#define ADC_B_CHANNEL_SHIFT 5 -typedef enum { - ADC0_SE4b = (0 << ADC_INSTANCE_SHIFT) | (1 << ADC_B_CHANNEL_SHIFT) | 4, - ADC0_SE5b = (0 << ADC_INSTANCE_SHIFT) | (1 << ADC_B_CHANNEL_SHIFT) | 5, - ADC0_SE6b = (0 << ADC_INSTANCE_SHIFT) | (1 << ADC_B_CHANNEL_SHIFT) | 6, - ADC0_SE7b = (0 << ADC_INSTANCE_SHIFT) | (1 << ADC_B_CHANNEL_SHIFT) | 7, - ADC0_SE8 = (0 << ADC_INSTANCE_SHIFT) | 8, - ADC0_SE9 = (0 << ADC_INSTANCE_SHIFT) | 9, - ADC0_SE12 = (0 << ADC_INSTANCE_SHIFT) | 12, - ADC0_SE13 = (0 << ADC_INSTANCE_SHIFT) | 13, - ADC0_SE14 = (0 << ADC_INSTANCE_SHIFT) | 14, - ADC0_SE15 = (0 << ADC_INSTANCE_SHIFT) | 15, - ADC0_SE16 = (0 << ADC_INSTANCE_SHIFT) | 16, - ADC0_SE17 = (0 << ADC_INSTANCE_SHIFT) | 17, - ADC0_SE18 = (0 << ADC_INSTANCE_SHIFT) | 18, - ADC0_SE21 = (0 << ADC_INSTANCE_SHIFT) | 21, - ADC0_SE22 = (0 << ADC_INSTANCE_SHIFT) | 22, - ADC0_SE23 = (0 << ADC_INSTANCE_SHIFT) | 23, - ADC1_SE4a = (1 << ADC_INSTANCE_SHIFT) | 4, - ADC1_SE5a = (1 << ADC_INSTANCE_SHIFT) | 5, - ADC1_SE6a = (1 << ADC_INSTANCE_SHIFT) | 6, - ADC1_SE7a = (1 << ADC_INSTANCE_SHIFT) | 7, - ADC1_SE4b = (1 << ADC_INSTANCE_SHIFT) | (1 << ADC_B_CHANNEL_SHIFT) | 4, - ADC1_SE5b = (1 << ADC_INSTANCE_SHIFT) | (1 << ADC_B_CHANNEL_SHIFT) | 5, - ADC1_SE6b = (1 << ADC_INSTANCE_SHIFT) | (1 << ADC_B_CHANNEL_SHIFT) | 6, - ADC1_SE7b = (1 << ADC_INSTANCE_SHIFT) | (1 << ADC_B_CHANNEL_SHIFT) | 7, - ADC1_SE8 = (1 << ADC_INSTANCE_SHIFT) | 8, - ADC1_SE9 = (1 << ADC_INSTANCE_SHIFT) | 9, - ADC1_SE12 = (1 << ADC_INSTANCE_SHIFT) | 12, - ADC1_SE13 = (1 << ADC_INSTANCE_SHIFT) | 13, - ADC1_SE14 = (1 << ADC_INSTANCE_SHIFT) | 14, - ADC1_SE15 = (1 << ADC_INSTANCE_SHIFT) | 15, - ADC1_SE16 = (1 << ADC_INSTANCE_SHIFT) | 16, - ADC1_SE17 = (1 << ADC_INSTANCE_SHIFT) | 17, - ADC1_SE18 = (1 << ADC_INSTANCE_SHIFT) | 18, - ADC1_SE23 = (1 << ADC_INSTANCE_SHIFT) | 23, -} ADCName; - -typedef enum { - DAC_0 = 0 -} DACName; - - -typedef enum { - SPI_0 = 0, - SPI_1 = 1, - SPI_2 = 2, -} SPIName; - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/TARGET_RO359B/PeripheralPins.c b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/TARGET_RO359B/PeripheralPins.c deleted file mode 100644 index c28829cd108..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/TARGET_RO359B/PeripheralPins.c +++ /dev/null @@ -1,242 +0,0 @@ -/* mbed Microcontroller Library - * Copyright (c) 2006-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. - * You may obtain a copy of the License at - * - * 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, - * 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. - */ - -#include "PeripheralPins.h" - -/************RTC***************/ -const PinMap PinMap_RTC[] = { - {NC, OSC32KCLK, 0}, -}; - -/************ADC***************/ -const PinMap PinMap_ADC[] = { - {PTA17, ADC1_SE17, 0}, - {PTB0 , ADC0_SE8 , 0}, - {PTB1 , ADC0_SE9 , 0}, - {PTB2 , ADC0_SE12, 0}, - {PTB3 , ADC0_SE13, 0}, - {PTB6 , ADC1_SE12, 0}, - {PTB7 , ADC1_SE13, 0}, - {PTB10, ADC1_SE14, 0}, - {PTB11, ADC1_SE15, 0}, - {PTC0 , ADC0_SE14, 0}, - {PTC1 , ADC0_SE15, 0}, - {PTC2, ADC0_SE4b, 0}, - {PTC8, ADC1_SE4b, 0}, - {PTC9, ADC1_SE5b, 0}, - {PTC10, ADC1_SE6b, 0}, - {PTC11, ADC1_SE7b, 0}, - {PTD1, ADC0_SE5b, 0}, - {PTD5, ADC0_SE6b, 0}, - {PTD6, ADC0_SE7b, 0}, - {PTE0, ADC1_SE4a, 0}, - {PTE1, ADC1_SE5a, 0}, - {PTE2, ADC1_SE6a, 0}, - {PTE3, ADC1_SE7a, 0}, - //{PTE24, ADC0_SE17, 0}, //I2C pull up - //{PTE25, ADC0_SE18, 0}, //I2C pull up - {NC , NC , 0} -}; - -/************DAC***************/ -const PinMap PinMap_DAC[] = { - {DAC0_OUT, DAC_0, 0}, - {NC , NC , 0} -}; - -/************I2C***************/ -const PinMap PinMap_I2C_SDA[] = { - {PTE25, I2C_0, 5}, - {PTB1 , I2C_0, 2}, - {PTB3 , I2C_0, 2}, - {PTC11, I2C_1, 2}, - {PTA13, I2C_2, 5}, - {PTD3 , I2C_0, 7}, - {PTE0 , I2C_1, 6}, - {NC , NC , 0} -}; - -const PinMap PinMap_I2C_SCL[] = { - {PTE24, I2C_0, 5}, - {PTB0 , I2C_0, 2}, - {PTB2 , I2C_0, 2}, - {PTC10, I2C_1, 2}, - {PTA12, I2C_2, 5}, - {PTA14, I2C_2, 5}, - {PTD2 , I2C_0, 7}, - {PTE1 , I2C_1, 6}, - {NC , NC , 0} -}; - -/************UART***************/ -const PinMap PinMap_UART_TX[] = { - {PTB17, UART_0, 3}, - {PTC17, UART_3, 3}, - {PTD7 , UART_0, 3}, - {PTD3 , UART_2, 3}, - {PTC4 , UART_1, 3}, - {PTC15, UART_4, 3}, - {PTB11, UART_3, 3}, - {PTA14, UART_0, 3}, - {PTE24, UART_4, 3}, - {PTE4 , UART_3, 3}, - {PTE0, UART_1, 3}, - {NC , NC , 0} -}; - -const PinMap PinMap_UART_RX[] = { - {PTB16, UART_0, 3}, - {PTE1 , UART_1, 3}, - {PTE5 , UART_3, 3}, - {PTE25, UART_4, 3}, - {PTA15, UART_0, 3}, - {PTC16, UART_3, 3}, - {PTB10, UART_3, 3}, - {PTC3 , UART_1, 3}, - {PTC14, UART_4, 3}, - {PTD2 , UART_2, 3}, - {PTD6 , UART_0, 3}, - {NC , NC , 0} -}; - -const PinMap PinMap_UART_CTS[] = { - {PTB13, UART_3, 2}, - {PTE2 , UART_1, 3}, - {PTE6 , UART_3, 3}, - {PTE26, UART_4, 3}, - {PTA0 , UART_0, 2}, - {PTA16, UART_0, 3}, - {PTB3 , UART_0, 3}, - {PTB9 , UART_3, 3}, - {PTC2 , UART_1, 3}, - {PTC13, UART_4, 3}, - {PTC19, UART_3, 3}, - {PTD1 , UART_2, 3}, - {PTD5 , UART_0, 3}, - {NC , NC , 0} -}; - -const PinMap PinMap_UART_RTS[] = { - {PTB12, UART_3, 2}, - {PTE3 , UART_1, 3}, - {PTE7 , UART_3, 3}, - {PTE27, UART_4, 3}, - {PTA17, UART_0, 3}, - {PTB8 , UART_3, 3}, - {PTC1 , UART_1, 3}, - {PTC12, UART_4, 3}, - {PTC18, UART_3, 3}, - {PTD0 , UART_2, 3}, - {PTD4 , UART_0, 3}, - {PTA3 , UART_0, 2}, - {PTB2 , UART_0, 3}, - {NC , NC , 0} -}; - -/************SPI***************/ -const PinMap PinMap_SPI_SCLK[] = { - {PTD1 , SPI_0, 2}, - {PTE2 , SPI_1, 2}, - {PTA15, SPI_0, 2}, - {PTB11, SPI_1, 2}, - {PTB21, SPI_2, 2}, - {PTC5 , SPI_0, 2}, - {PTD5 , SPI_1, 7}, - {NC , NC , 0} -}; - -const PinMap PinMap_SPI_MOSI[] = { - {PTD2 , SPI_0, 2}, - {PTE1 , SPI_1, 2}, - {PTE3 , SPI_1, 7}, - {PTA16, SPI_0, 2}, - {PTB16, SPI_1, 2}, - {PTB22, SPI_2, 2}, - {PTC6 , SPI_0, 2}, - {PTD6 , SPI_1, 7}, - {NC , NC , 0} -}; - -const PinMap PinMap_SPI_MISO[] = { - {PTD3 , SPI_0, 2}, - {PTE1 , SPI_1, 7}, - {PTE3 , SPI_1, 2}, - {PTA17, SPI_0, 2}, - {PTB17, SPI_1, 2}, - {PTB23, SPI_2, 2}, - {PTC7 , SPI_0, 2}, - {PTD7 , SPI_1, 7}, - {NC , NC , 0} -}; - -const PinMap PinMap_SPI_SSEL[] = { - {PTD0 , SPI_0, 2}, - {PTE4 , SPI_1, 2}, - {PTA14, SPI_0, 2}, - {PTB10, SPI_1, 2}, - {PTB20, SPI_2, 2}, - {PTC4 , SPI_0, 2}, - {PTD4 , SPI_1, 7}, - {NC , NC , 0} -}; - -/************PWM***************/ -const PinMap PinMap_PWM[] = { - {PTA0 , PWM_6 , 3}, - {PTA1 , PWM_7 , 3}, - {PTA2 , PWM_8 , 3}, - {PTA3 , PWM_1 , 3}, - {PTA4 , PWM_2 , 3}, - {PTA5 , PWM_3 , 3}, - {PTA6 , PWM_4 , 3}, - {PTA7 , PWM_5 , 3}, - {PTA8 , PWM_9 , 3}, - {PTA9 , PWM_10, 3}, - {PTA10, PWM_17, 3}, - {PTA11, PWM_18, 3}, - {PTA12, PWM_9 , 3}, - {PTA13, PWM_10, 3}, - - {PTB0 , PWM_9 , 3}, - {PTB1 , PWM_10, 3}, - {PTB18, PWM_17, 3}, - {PTB19, PWM_18, 3}, - - {PTC1 , PWM_1 , 4}, - {PTC2 , PWM_2 , 4}, - {PTC3 , PWM_3 , 4}, - {PTC4 , PWM_4 , 4}, - {PTC5 , PWM_3 , 7}, - {PTC8 , PWM_29, 3}, - {PTC9 , PWM_30, 3}, - {PTC10, PWM_31, 3}, - {PTC11, PWM_32, 3}, - - {PTD0 , PWM_25, 4}, - {PTD1 , PWM_26, 4}, - {PTD2 , PWM_27, 4}, - {PTD3 , PWM_28, 4}, - {PTD4 , PWM_5 , 4}, - {PTD5 , PWM_6 , 4}, - {PTD6 , PWM_7 , 4}, - {PTD4 , PWM_5 , 4}, - {PTD7 , PWM_8 , 4}, - - {PTE5 , PWM_25, 6}, - {PTE6 , PWM_26, 6}, - - {NC , NC , 0} -}; diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/TARGET_RO359B/PinNames.h b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/TARGET_RO359B/PinNames.h deleted file mode 100644 index e1d7a2b6fa0..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/TARGET_RO359B/PinNames.h +++ /dev/null @@ -1,259 +0,0 @@ -/* mbed Microcontroller Library - * Copyright (c) 2006-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. - * You may obtain a copy of the License at - * - * 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, - * 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. - */ -#ifndef MBED_PINNAMES_H -#define MBED_PINNAMES_H - -#include "cmsis.h" - -#ifdef __cplusplus -extern "C" { -#endif - -typedef enum { - PIN_INPUT, - PIN_OUTPUT -} PinDirection; - -#define GPIO_PORT_SHIFT 12 - -typedef enum { - PTA0 = (0 << GPIO_PORT_SHIFT | 0 ), - PTA1 = (0 << GPIO_PORT_SHIFT | 1 ), - PTA2 = (0 << GPIO_PORT_SHIFT | 2 ), - PTA3 = (0 << GPIO_PORT_SHIFT | 3 ), - PTA4 = (0 << GPIO_PORT_SHIFT | 4 ), - PTA5 = (0 << GPIO_PORT_SHIFT | 5 ), - PTA6 = (0 << GPIO_PORT_SHIFT | 6 ), - PTA7 = (0 << GPIO_PORT_SHIFT | 7 ), - PTA8 = (0 << GPIO_PORT_SHIFT | 8 ), - PTA9 = (0 << GPIO_PORT_SHIFT | 9 ), - PTA10 = (0 << GPIO_PORT_SHIFT | 10), - PTA11 = (0 << GPIO_PORT_SHIFT | 11), - PTA12 = (0 << GPIO_PORT_SHIFT | 12), - PTA13 = (0 << GPIO_PORT_SHIFT | 13), - PTA14 = (0 << GPIO_PORT_SHIFT | 14), - PTA15 = (0 << GPIO_PORT_SHIFT | 15), - PTA16 = (0 << GPIO_PORT_SHIFT | 16), - PTA17 = (0 << GPIO_PORT_SHIFT | 17), - PTA18 = (0 << GPIO_PORT_SHIFT | 18), - PTA19 = (0 << GPIO_PORT_SHIFT | 19), - PTA20 = (0 << GPIO_PORT_SHIFT | 20), - PTA21 = (0 << GPIO_PORT_SHIFT | 21), - PTA22 = (0 << GPIO_PORT_SHIFT | 22), - PTA23 = (0 << GPIO_PORT_SHIFT | 23), - PTA24 = (0 << GPIO_PORT_SHIFT | 24), - PTA25 = (0 << GPIO_PORT_SHIFT | 25), - PTA26 = (0 << GPIO_PORT_SHIFT | 26), - PTA27 = (0 << GPIO_PORT_SHIFT | 27), - PTA28 = (0 << GPIO_PORT_SHIFT | 28), - PTA29 = (0 << GPIO_PORT_SHIFT | 29), - PTA30 = (0 << GPIO_PORT_SHIFT | 30), - PTA31 = (0 << GPIO_PORT_SHIFT | 31), - PTB0 = (1 << GPIO_PORT_SHIFT | 0 ), - PTB1 = (1 << GPIO_PORT_SHIFT | 1 ), - PTB2 = (1 << GPIO_PORT_SHIFT | 2 ), - PTB3 = (1 << GPIO_PORT_SHIFT | 3 ), - PTB4 = (1 << GPIO_PORT_SHIFT | 4 ), - PTB5 = (1 << GPIO_PORT_SHIFT | 5 ), - PTB6 = (1 << GPIO_PORT_SHIFT | 6 ), - PTB7 = (1 << GPIO_PORT_SHIFT | 7 ), - PTB8 = (1 << GPIO_PORT_SHIFT | 8 ), - PTB9 = (1 << GPIO_PORT_SHIFT | 9 ), - PTB10 = (1 << GPIO_PORT_SHIFT | 10), - PTB11 = (1 << GPIO_PORT_SHIFT | 11), - PTB12 = (1 << GPIO_PORT_SHIFT | 12), - PTB13 = (1 << GPIO_PORT_SHIFT | 13), - PTB14 = (1 << GPIO_PORT_SHIFT | 14), - PTB15 = (1 << GPIO_PORT_SHIFT | 15), - PTB16 = (1 << GPIO_PORT_SHIFT | 16), - PTB17 = (1 << GPIO_PORT_SHIFT | 17), - PTB18 = (1 << GPIO_PORT_SHIFT | 18), - PTB19 = (1 << GPIO_PORT_SHIFT | 19), - PTB20 = (1 << GPIO_PORT_SHIFT | 20), - PTB21 = (1 << GPIO_PORT_SHIFT | 21), - PTB22 = (1 << GPIO_PORT_SHIFT | 22), - PTB23 = (1 << GPIO_PORT_SHIFT | 23), - PTB24 = (1 << GPIO_PORT_SHIFT | 24), - PTB25 = (1 << GPIO_PORT_SHIFT | 25), - PTB26 = (1 << GPIO_PORT_SHIFT | 26), - PTB27 = (1 << GPIO_PORT_SHIFT | 27), - PTB28 = (1 << GPIO_PORT_SHIFT | 28), - PTB29 = (1 << GPIO_PORT_SHIFT | 29), - PTB30 = (1 << GPIO_PORT_SHIFT | 30), - PTB31 = (1 << GPIO_PORT_SHIFT | 31), - PTC0 = (2 << GPIO_PORT_SHIFT | 0 ), - PTC1 = (2 << GPIO_PORT_SHIFT | 1 ), - PTC2 = (2 << GPIO_PORT_SHIFT | 2 ), - PTC3 = (2 << GPIO_PORT_SHIFT | 3 ), - PTC4 = (2 << GPIO_PORT_SHIFT | 4 ), - PTC5 = (2 << GPIO_PORT_SHIFT | 5 ), - PTC6 = (2 << GPIO_PORT_SHIFT | 6 ), - PTC7 = (2 << GPIO_PORT_SHIFT | 7 ), - PTC8 = (2 << GPIO_PORT_SHIFT | 8 ), - PTC9 = (2 << GPIO_PORT_SHIFT | 9 ), - PTC10 = (2 << GPIO_PORT_SHIFT | 10), - PTC11 = (2 << GPIO_PORT_SHIFT | 11), - PTC12 = (2 << GPIO_PORT_SHIFT | 12), - PTC13 = (2 << GPIO_PORT_SHIFT | 13), - PTC14 = (2 << GPIO_PORT_SHIFT | 14), - PTC15 = (2 << GPIO_PORT_SHIFT | 15), - PTC16 = (2 << GPIO_PORT_SHIFT | 16), - PTC17 = (2 << GPIO_PORT_SHIFT | 17), - PTC18 = (2 << GPIO_PORT_SHIFT | 18), - PTC19 = (2 << GPIO_PORT_SHIFT | 19), - PTC20 = (2 << GPIO_PORT_SHIFT | 20), - PTC21 = (2 << GPIO_PORT_SHIFT | 21), - PTC22 = (2 << GPIO_PORT_SHIFT | 22), - PTC23 = (2 << GPIO_PORT_SHIFT | 23), - PTC24 = (2 << GPIO_PORT_SHIFT | 24), - PTC25 = (2 << GPIO_PORT_SHIFT | 25), - PTC26 = (2 << GPIO_PORT_SHIFT | 26), - PTC27 = (2 << GPIO_PORT_SHIFT | 27), - PTC28 = (2 << GPIO_PORT_SHIFT | 28), - PTC29 = (2 << GPIO_PORT_SHIFT | 29), - PTC30 = (2 << GPIO_PORT_SHIFT | 30), - PTC31 = (2 << GPIO_PORT_SHIFT | 31), - PTD0 = (3 << GPIO_PORT_SHIFT | 0 ), - PTD1 = (3 << GPIO_PORT_SHIFT | 1 ), - PTD2 = (3 << GPIO_PORT_SHIFT | 2 ), - PTD3 = (3 << GPIO_PORT_SHIFT | 3 ), - PTD4 = (3 << GPIO_PORT_SHIFT | 4 ), - PTD5 = (3 << GPIO_PORT_SHIFT | 5 ), - PTD6 = (3 << GPIO_PORT_SHIFT | 6 ), - PTD7 = (3 << GPIO_PORT_SHIFT | 7 ), - PTD8 = (3 << GPIO_PORT_SHIFT | 8 ), - PTD9 = (3 << GPIO_PORT_SHIFT | 9 ), - PTD10 = (3 << GPIO_PORT_SHIFT | 10), - PTD11 = (3 << GPIO_PORT_SHIFT | 11), - PTD12 = (3 << GPIO_PORT_SHIFT | 12), - PTD13 = (3 << GPIO_PORT_SHIFT | 13), - PTD14 = (3 << GPIO_PORT_SHIFT | 14), - PTD15 = (3 << GPIO_PORT_SHIFT | 15), - PTD16 = (3 << GPIO_PORT_SHIFT | 16), - PTD17 = (3 << GPIO_PORT_SHIFT | 17), - PTD18 = (3 << GPIO_PORT_SHIFT | 18), - PTD19 = (3 << GPIO_PORT_SHIFT | 19), - PTD20 = (3 << GPIO_PORT_SHIFT | 20), - PTD21 = (3 << GPIO_PORT_SHIFT | 21), - PTD22 = (3 << GPIO_PORT_SHIFT | 22), - PTD23 = (3 << GPIO_PORT_SHIFT | 23), - PTD24 = (3 << GPIO_PORT_SHIFT | 24), - PTD25 = (3 << GPIO_PORT_SHIFT | 25), - PTD26 = (3 << GPIO_PORT_SHIFT | 26), - PTD27 = (3 << GPIO_PORT_SHIFT | 27), - PTD28 = (3 << GPIO_PORT_SHIFT | 28), - PTD29 = (3 << GPIO_PORT_SHIFT | 29), - PTD30 = (3 << GPIO_PORT_SHIFT | 30), - PTD31 = (3 << GPIO_PORT_SHIFT | 31), - PTE0 = (4 << GPIO_PORT_SHIFT | 0 ), - PTE1 = (4 << GPIO_PORT_SHIFT | 1 ), - PTE2 = (4 << GPIO_PORT_SHIFT | 2 ), - PTE3 = (4 << GPIO_PORT_SHIFT | 3 ), - PTE4 = (4 << GPIO_PORT_SHIFT | 4 ), - PTE5 = (4 << GPIO_PORT_SHIFT | 5 ), - PTE6 = (4 << GPIO_PORT_SHIFT | 6 ), - PTE7 = (4 << GPIO_PORT_SHIFT | 7 ), - PTE8 = (4 << GPIO_PORT_SHIFT | 8 ), - PTE9 = (4 << GPIO_PORT_SHIFT | 9 ), - PTE10 = (4 << GPIO_PORT_SHIFT | 10), - PTE11 = (4 << GPIO_PORT_SHIFT | 11), - PTE12 = (4 << GPIO_PORT_SHIFT | 12), - PTE13 = (4 << GPIO_PORT_SHIFT | 13), - PTE14 = (4 << GPIO_PORT_SHIFT | 14), - PTE15 = (4 << GPIO_PORT_SHIFT | 15), - PTE16 = (4 << GPIO_PORT_SHIFT | 16), - PTE17 = (4 << GPIO_PORT_SHIFT | 17), - PTE18 = (4 << GPIO_PORT_SHIFT | 18), - PTE19 = (4 << GPIO_PORT_SHIFT | 19), - PTE20 = (4 << GPIO_PORT_SHIFT | 20), - PTE21 = (4 << GPIO_PORT_SHIFT | 21), - PTE22 = (4 << GPIO_PORT_SHIFT | 22), - PTE23 = (4 << GPIO_PORT_SHIFT | 23), - PTE24 = (4 << GPIO_PORT_SHIFT | 24), - PTE25 = (4 << GPIO_PORT_SHIFT | 25), - PTE26 = (4 << GPIO_PORT_SHIFT | 26), - PTE27 = (4 << GPIO_PORT_SHIFT | 27), - PTE28 = (4 << GPIO_PORT_SHIFT | 28), - PTE29 = (4 << GPIO_PORT_SHIFT | 29), - PTE30 = (4 << GPIO_PORT_SHIFT | 30), - PTE31 = (4 << GPIO_PORT_SHIFT | 31), - - LED_RED = PTB22, - LED_GREEN = PTE26, - LED_BLUE = PTB2, // GPIO2 - - // mbed original LED naming - LED1 = LED_RED, - LED2 = LED_GREEN, - LED3 = LED_BLUE, - LED4 = LED_RED, - - // USB Pins - USBTX = PTA14, - USBRX = PTA15, - - // Module Pins - MODTX = PTC4, - MODRX = PTC3, - - // Arduino Headers - D0 = PTC14, - D1 = PTC15, - D2 = PTA1, - D3 = PTA2, - D4 = PTA5, - D5 = PTC12, - D6 = PTC13, - D7 = PTB20, - - D8 = PTB18, - D9 = PTB19, - D10 = PTB10, - D11 = PTB16, - D12 = PTB17, - D13 = PTB11, - D14 = PTA13, - D15 = PTA12, - - I2C_SCL = D15, - I2C_SDA = D14, - - A0 = PTA16, - A1 = PTA17, - A2 = PTE26, - A3 = PTB2, - A4 = PTB1, - A5 = PTB0, - - DAC0_OUT = 0xFEFE, /* DAC does not have Pin Name in RM */ - - // Not connected - NC = (int)0xFFFFFFFF -} PinName; - - -typedef enum { - PullNone = 0, - PullDown = 1, - PullUp = 2, - PullDefault = PullUp -} PinMode; - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/TARGET_RO359B/crc.c b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/TARGET_RO359B/crc.c deleted file mode 100644 index 7e2d7e7c516..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/TARGET_RO359B/crc.c +++ /dev/null @@ -1,234 +0,0 @@ -/********************************************************************** - * - * Filename: crc.c - * - * Description: Slow and fast implementations of the CRC standards. - * - * Notes: The parameters for each supported CRC standard are - * defined in the header file crc.h. The implementations - * here should stand up to further additions to that list. - * - * - * Copyright (c) 2000 by Michael Barr. This software is placed into - * the public domain and may be used for any purpose. However, this - * notice must not be changed or removed and no warranty is either - * expressed or implied by its publication or distribution. - **********************************************************************/ - -#include "crc.h" - - -/* - * Derive parameters from the standard-specific parameters in crc.h. - */ -#define WIDTH (8 * sizeof(crc)) -#define TOPBIT (1 << (WIDTH - 1)) - -#if (REFLECT_DATA == TRUE) -#undef REFLECT_DATA -#define REFLECT_DATA(X) ((unsigned char) reflect((X), 8)) -#else -#undef REFLECT_DATA -#define REFLECT_DATA(X) (X) -#endif - -#if (REFLECT_REMAINDER == TRUE) -#undef REFLECT_REMAINDER -#define REFLECT_REMAINDER(X) ((crc) reflect((X), WIDTH)) -#else -#undef REFLECT_REMAINDER -#define REFLECT_REMAINDER(X) (X) -#endif - - -/********************************************************************* - * - * Function: reflect() - * - * Description: Reorder the bits of a binary sequence, by reflecting - * them about the middle position. - * - * Notes: No checking is done that nBits <= 32. - * - * Returns: The reflection of the original data. - * - *********************************************************************/ -static unsigned long -reflect(unsigned long data, unsigned char nBits) -{ - unsigned long reflection = 0x00000000; - unsigned char bit; - - /* - * Reflect the data about the center bit. - */ - for (bit = 0; bit < nBits; ++bit) - { - /* - * If the LSB bit is set, set the reflection of it. - */ - if (data & 0x01) - { - reflection |= (1 << ((nBits - 1) - bit)); - } - - data = (data >> 1); - } - - return (reflection); - -} /* reflect() */ - - -/********************************************************************* - * - * Function: crcSlow() - * - * Description: Compute the CRC of a given message. - * - * Notes: - * - * Returns: The CRC of the message. - * - *********************************************************************/ -crc -crcSlow(unsigned char const message[], int nBytes) -{ - crc remainder = INITIAL_REMAINDER; - int byte; - unsigned char bit; - - - /* - * Perform modulo-2 division, a byte at a time. - */ - for (byte = 0; byte < nBytes; ++byte) - { - /* - * Bring the next byte into the remainder. - */ - remainder ^= (REFLECT_DATA(message[byte]) << (WIDTH - 8)); - - /* - * Perform modulo-2 division, a bit at a time. - */ - for (bit = 8; bit > 0; --bit) - { - /* - * Try to divide the current data bit. - */ - if (remainder & TOPBIT) - { - remainder = (remainder << 1) ^ POLYNOMIAL; - } - else - { - remainder = (remainder << 1); - } - } - } - - /* - * The final remainder is the CRC result. - */ - return (REFLECT_REMAINDER(remainder) ^ FINAL_XOR_VALUE); - -} /* crcSlow() */ - - -crc crcTable[256]; - - -/********************************************************************* - * - * Function: crcInit() - * - * Description: Populate the partial CRC lookup table. - * - * Notes: This function must be rerun any time the CRC standard - * is changed. If desired, it can be run "offline" and - * the table results stored in an embedded system's ROM. - * - * Returns: None defined. - * - *********************************************************************/ -void -crcInit(void) -{ - crc remainder; - int dividend; - unsigned char bit; - - - /* - * Compute the remainder of each possible dividend. - */ - for (dividend = 0; dividend < 256; ++dividend) - { - /* - * Start with the dividend followed by zeros. - */ - remainder = dividend << (WIDTH - 8); - - /* - * Perform modulo-2 division, a bit at a time. - */ - for (bit = 8; bit > 0; --bit) - { - /* - * Try to divide the current data bit. - */ - if (remainder & TOPBIT) - { - remainder = (remainder << 1) ^ POLYNOMIAL; - } - else - { - remainder = (remainder << 1); - } - } - - /* - * Store the result into the table. - */ - crcTable[dividend] = remainder; - } - -} /* crcInit() */ - - -/********************************************************************* - * - * Function: crcFast() - * - * Description: Compute the CRC of a given message. - * - * Notes: crcInit() must be called first. - * - * Returns: The CRC of the message. - * - *********************************************************************/ -crc -crcFast(unsigned char const message[], int nBytes) -{ - crc remainder = INITIAL_REMAINDER; - unsigned char data; - int byte; - - - /* - * Divide the message by the polynomial, a byte at a time. - */ - for (byte = 0; byte < nBytes; ++byte) - { - data = REFLECT_DATA(message[byte]) ^ (remainder >> (WIDTH - 8)); - remainder = crcTable[data] ^ (remainder << 8); - } - - /* - * The final remainder is the CRC. - */ - return (REFLECT_REMAINDER(remainder) ^ FINAL_XOR_VALUE); - -} /* crcFast() */ - diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/TARGET_RO359B/crc.h b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/TARGET_RO359B/crc.h deleted file mode 100644 index fae66ae4bcc..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/TARGET_RO359B/crc.h +++ /dev/null @@ -1,77 +0,0 @@ -/********************************************************************** - * - * Filename: crc.h - * - * Description: A header file describing the various CRC standards. - * - * Notes: - * - * - * Copyright (c) 2000 by Michael Barr. This software is placed into - * the public domain and may be used for any purpose. However, this - * notice must not be changed or removed and no warranty is either - * expressed or implied by its publication or distribution. - **********************************************************************/ - -#ifndef _crc_h -#define _crc_h - - -#define FALSE 0 -#define TRUE !FALSE - -/* - * Select the CRC standard from the list that follows. - */ -#define CRC16 - - -#if defined(CRC_CCITT) - -typedef unsigned short crc; - -#define CRC_NAME "CRC-CCITT" -#define POLYNOMIAL 0x1021 -#define INITIAL_REMAINDER 0xFFFF -#define FINAL_XOR_VALUE 0x0000 -#define REFLECT_DATA FALSE -#define REFLECT_REMAINDER FALSE -#define CHECK_VALUE 0x29B1 - -#elif defined(CRC16) - -typedef unsigned short crc; - -#define CRC_NAME "CRC-16" -#define POLYNOMIAL 0x8005 -#define INITIAL_REMAINDER 0x0000 -#define FINAL_XOR_VALUE 0x0000 -#define REFLECT_DATA TRUE -#define REFLECT_REMAINDER TRUE -#define CHECK_VALUE 0xBB3D - -#elif defined(CRC32) - -typedef unsigned long crc; - -#define CRC_NAME "CRC-32" -#define POLYNOMIAL 0x04C11DB7 -#define INITIAL_REMAINDER 0xFFFFFFFF -#define FINAL_XOR_VALUE 0xFFFFFFFF -#define REFLECT_DATA TRUE -#define REFLECT_REMAINDER TRUE -#define CHECK_VALUE 0xCBF43926 - -#else - -#error "One of CRC_CCITT, CRC16, or CRC32 must be #define'd." - -#endif - - -void crcInit(void); -crc crcSlow(unsigned char const message[], int nBytes); -crc crcFast(unsigned char const message[], int nBytes); - - -#endif /* _crc_h */ diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/TARGET_RO359B/fsl_clock_config.c b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/TARGET_RO359B/fsl_clock_config.c deleted file mode 100644 index a3398b49fcf..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/TARGET_RO359B/fsl_clock_config.c +++ /dev/null @@ -1,266 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of Freescale Semiconductor, Inc. nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "fsl_common.h" -#include "fsl_smc.h" -#include "fsl_rtc.h" -#include "fsl_clock_config.h" - -#define MCG_IRCLK_DISABLE 0U /*!< MCGIRCLK disabled */ -#define MCG_PLL_DISABLE 0U /*!< MCGPLLCLK disabled */ -#define OSC_CAP0P 0U /*!< Oscillator 0pF capacitor load */ -#define RTC_OSC_CAP_LOAD_0PF 0x0U /*!< RTC oscillator capacity load: 0pF */ -#define RTC_RTC32KCLK_PERIPHERALS_ENABLED 1U /*!< RTC32KCLK to other peripherals: enabled */ -#define SIM_CLKOUT_SEL_FLEXBUS_CLK 0U /*!< CLKOUT pin clock select: FlexBus clock */ -#define SIM_OSC32KSEL_RTC32KCLK_CLK 2U /*!< OSC32KSEL select: RTC32KCLK clock (32.768kHz) */ -#define SIM_PLLFLLSEL_MCGFLLCLK_CLK 0U /*!< PLLFLL select: MCGFLLCLK clock */ - -static void CLOCK_CONFIG_SetRtcClock(uint32_t capLoad, uint8_t enableOutPeriph) -{ - /* RTC clock gate enable */ - CLOCK_EnableClock(kCLOCK_Rtc0); - if ((RTC->CR & RTC_CR_OSCE_MASK) == 0u) { /* Only if the Rtc oscillator is not already enabled */ - /* Set the specified capacitor configuration for the RTC oscillator */ - RTC_SetOscCapLoad(RTC, capLoad); - /* Enable the RTC 32KHz oscillator */ - RTC->CR |= RTC_CR_OSCE_MASK; - } - /* Output to other peripherals */ - if (enableOutPeriph) { - RTC->CR &= ~RTC_CR_CLKO_MASK; - } - else { - RTC->CR |= RTC_CR_CLKO_MASK; - } - /* Set the XTAL32/RTC_CLKIN frequency based on board setting. */ - CLOCK_SetXtal32Freq(BOARD_XTAL32K_CLK_HZ); - /* Set RTC_TSR if there is fault value in RTC */ - if (RTC->SR & RTC_SR_TIF_MASK) { - RTC -> TSR = RTC -> TSR; - } - /* RTC clock gate disable */ - CLOCK_DisableClock(kCLOCK_Rtc0); -} - -static void CLOCK_CONFIG_EnableIrc48MOsc() -{ - /* USB clock gate enable */ - CLOCK_EnableClock(kCLOCK_Usbfs0); - /* IRC48M oscillator enable */ - USB0->CLK_RECOVER_IRC_EN = USB_CLK_RECOVER_IRC_EN_IRC_EN_MASK | USB_CLK_RECOVER_IRC_EN_REG_EN_MASK; - /* USB clock gate disable */ - CLOCK_DisableClock(kCLOCK_Usbfs0); -} - -static void CLOCK_CONFIG_SetFllExtRefDiv(uint8_t frdiv) -{ - MCG->C1 = ((MCG->C1 & ~MCG_C1_FRDIV_MASK) | MCG_C1_FRDIV(frdiv)); -} - -/******************************************************************************* - * Definitions - ******************************************************************************/ -/*! @brief Clock configuration structure. */ -typedef struct _clock_config -{ - mcg_config_t mcgConfig; /*!< MCG configuration. */ - sim_clock_config_t simConfig; /*!< SIM configuration. */ - osc_config_t oscConfig; /*!< OSC configuration. */ - uint32_t coreClock; /*!< core clock frequency. */ -} clock_config_t; - -/******************************************************************************* - * Variables - ******************************************************************************/ -/* System clock frequency. */ -extern uint32_t SystemCoreClock; - -/* Configuration for enter VLPR mode. Core clock = 4MHz. */ -const clock_config_t g_defaultClockConfigVlpr = { - .mcgConfig = - { - .mcgMode = kMCG_ModeBLPI, /* Work in BLPI mode. */ - .irclkEnableMode = kMCG_IrclkEnable, /* MCGIRCLK enable. */ - .ircs = kMCG_IrcFast, /* Select IRC4M. */ - .fcrdiv = 0U, /* FCRDIV is 0. */ - - .frdiv = 0U, - .drs = kMCG_DrsLow, /* Low frequency range. */ - .dmx32 = kMCG_Dmx32Default, /* DCO has a default range of 25%. */ - .oscsel = kMCG_OscselOsc, /* Select OSC. */ - - .pll0Config = - { - .enableMode = 0U, /* Don't eanble PLL. */ - .prdiv = 0U, - .vdiv = 0U, - }, - }, - .simConfig = - { - .pllFllSel = 3U, /* PLLFLLSEL select IRC48MCLK. */ - .er32kSrc = 2U, /* ERCLK32K selection, use RTC. */ - .clkdiv1 = 0x00040000U, /* SIM_CLKDIV1. */ - }, - .oscConfig = {.freq = BOARD_XTAL0_CLK_HZ, - .capLoad = 0, - .workMode = kOSC_ModeExt, - .oscerConfig = - { - .enableMode = kOSC_ErClkEnable, -#if (defined(FSL_FEATURE_OSC_HAS_EXT_REF_CLOCK_DIVIDER) && FSL_FEATURE_OSC_HAS_EXT_REF_CLOCK_DIVIDER) - .erclkDiv = 0U, -#endif - }}, - .coreClock = 4000000U, /* Core clock frequency */ -}; - -/* Configuration for enter RUN mode. Core clock = 95.977472 MHz. */ -const clock_config_t g_defaultClockConfigRun = { - .mcgConfig = - { - .mcgMode = kMCG_ModePEE, /* PEE - PLL Engaged External */ - .irclkEnableMode = MCG_IRCLK_DISABLE, /* MCGIRCLK disabled */ - .ircs = kMCG_IrcSlow, /* Slow internal reference clock selected */ - .fcrdiv = 0x0U, /* Fast IRC divider: divided by 1 */ - .frdiv = 0x2U, /* FLL reference clock divider: divided by 4 */ - .drs = kMCG_DrsLow, /* Low frequency range */ - .dmx32 = kMCG_Dmx32Default, /* DCO has a default range of 25% */ - .oscsel = kMCG_OscselIrc, /* Selects 48 MHz IRC Oscillator */ - .pll0Config = - { - .enableMode = MCG_PLL_DISABLE, /* MCGPLLCLK disabled */ - .prdiv = 0xbU, /* PLL Reference divider: divided by 12 */ - .vdiv = 0x0U, /* VCO divider: multiplied by 24 */ - }, - }, - .simConfig = //OK - { - .pllFllSel = SIM_PLLFLLSEL_MCGFLLCLK_CLK, /* PLLFLL select: MCGFLLCLK clock */ - .er32kSrc = SIM_OSC32KSEL_RTC32KCLK_CLK, /* OSC32KSEL select: RTC32KCLK clock (32.768kHz) */ - .clkdiv1 = 0x1240000U, /* SIM_CLKDIV1 - OUTDIV1: /1, OUTDIV2: /2, OUTDIV3: /3, OUTDIV4: /5 */ - }, - .oscConfig = - { - .freq = 0U, /* Oscillator frequency: 0Hz */ - .capLoad = (OSC_CAP0P), /* Oscillator capacity load: 0pF */ - .workMode = kOSC_ModeExt, /* Use external clock */ - .oscerConfig = - { - .enableMode = kOSC_ErClkEnable, /* Enable external reference clock, disable external reference clock in STOP mode */ - - } - }, - .coreClock = 96000000U, /* Core clock frequency */ -}; - -/******************************************************************************* - * Code - ******************************************************************************/ -/* - * How to setup clock using clock driver functions: - * - * 1. CLOCK_SetSimSafeDivs, to make sure core clock, bus clock, flexbus clock - * and flash clock are in allowed range during clock mode switch. - * - * 2. Call CLOCK_Osc0Init to setup OSC clock, if it is used in target mode. - * - * 3. Set MCG configuration, MCG includes three parts: FLL clock, PLL clock and - * internal reference clock(MCGIRCLK). Follow the steps to setup: - * - * 1). Call CLOCK_BootToXxxMode to set MCG to target mode. - * - * 2). If target mode is FBI/BLPI/PBI mode, the MCGIRCLK has been configured - * correctly. For other modes, need to call CLOCK_SetInternalRefClkConfig - * explicitly to setup MCGIRCLK. - * - * 3). Don't need to configure FLL explicitly, because if target mode is FLL - * mode, then FLL has been configured by the function CLOCK_BootToXxxMode, - * if the target mode is not FLL mode, the FLL is disabled. - * - * 4). If target mode is PEE/PBE/PEI/PBI mode, then the related PLL has been - * setup by CLOCK_BootToXxxMode. In FBE/FBI/FEE/FBE mode, the PLL could - * be enabled independently, call CLOCK_EnablePll0 explicitly in this case. - * - * 4. Call CLOCK_SetSimConfig to set the clock configuration in SIM. - */ - -static void fllStableDelay(void) -{ - /* - Should wait at least 1ms. Because in these modes, the core clock is 100MHz - at most, so this function could obtain the 1ms delay. - */ - volatile uint32_t i = 30000U; - while (i--) - { - __NOP(); - } -} - -void BOARD_BootClockVLPR(void) -{ - CLOCK_SetSimSafeDivs(); - - CLOCK_BootToBlpiMode(g_defaultClockConfigVlpr.mcgConfig.fcrdiv, g_defaultClockConfigVlpr.mcgConfig.ircs, - g_defaultClockConfigVlpr.mcgConfig.irclkEnableMode); - - CLOCK_SetSimConfig(&g_defaultClockConfigVlpr.simConfig); - - SystemCoreClock = g_defaultClockConfigVlpr.coreClock; - - SMC_SetPowerModeProtection(SMC, kSMC_AllowPowerModeAll); - SMC_SetPowerModeVlpr(SMC, false); - while (SMC_GetPowerModeState(SMC) != kSMC_PowerStateVlpr) - { - } -} - -void BOARD_BootClockRUN(void) -{ - /* Set the system clock dividers in SIM to safe value. */ - CLOCK_SetSimSafeDivs(); - /* Configure RTC clock including enabling RTC oscillator. */ - CLOCK_CONFIG_SetRtcClock(RTC_OSC_CAP_LOAD_0PF, RTC_RTC32KCLK_PERIPHERALS_ENABLED); - /* Enable IRC48M oscillator for K24 as workaround because there is not enabled the oscillator automatically. */ - CLOCK_CONFIG_EnableIrc48MOsc(); - /* Configure FLL external reference divider (FRDIV). */ - CLOCK_CONFIG_SetFllExtRefDiv(g_defaultClockConfigRun.mcgConfig.frdiv); - /* Set MCG to PEE mode. */ - CLOCK_BootToPeeMode(g_defaultClockConfigRun.mcgConfig.oscsel, - kMCG_PllClkSelPll0, - &g_defaultClockConfigRun.mcgConfig.pll0Config); - /* Set the clock configuration in SIM module. */ - CLOCK_SetSimConfig(&g_defaultClockConfigRun.simConfig); - /* Set SystemCoreClock variable. */ - SystemCoreClock = g_defaultClockConfigRun.coreClock; - /* Set CLKOUT source. */ - CLOCK_SetClkOutClock(SIM_CLKOUT_SEL_FLEXBUS_CLK); -} diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/TARGET_RO359B/mbed_overrides.c b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/TARGET_RO359B/mbed_overrides.c deleted file mode 100644 index 0fa409f8c75..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/TARGET_RO359B/mbed_overrides.c +++ /dev/null @@ -1,43 +0,0 @@ -/* mbed Microcontroller Library - * Copyright (c) 2006-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. - * You may obtain a copy of the License at - * - * 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, - * 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. - */ -#include "gpio_api.h" - -#define CRC16 -#include "crc.h" -#include "fsl_clock_config.h" - -// called before main -void mbed_sdk_init() -{ - BOARD_BootClockRUN(); -} - -// Change the NMI pin to an input. This allows NMI pin to -// be used as a low power mode wakeup. The application will -// need to change the pin back to NMI_b or wakeup only occurs once! -void NMI_Handler(void) -{ - gpio_t gpio; - gpio_init_in(&gpio, PTA4); -} - -// Enable the RTC oscillator if available on the board -void rtc_setup_oscillator(RTC_Type *base) -{ - /* Enable the RTC oscillator */ - RTC->CR |= RTC_CR_OSCE_MASK; -} - diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/device/MK24F12.h b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/device/MK24F12.h deleted file mode 100644 index a057d576175..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/device/MK24F12.h +++ /dev/null @@ -1,11819 +0,0 @@ -/* -** ################################################################### -** Processors: MK24FN1M0CAJ12 -** MK24FN1M0VDC12 -** MK24FN1M0VLL12 -** MK24FN1M0VLQ12 -** -** Compilers: Keil ARM C/C++ Compiler -** Freescale C/C++ for Embedded ARM -** GNU C Compiler -** IAR ANSI C/C++ Compiler for ARM -** MCUXpresso Compiler -** -** Reference manual: K24P144M120SF5RM, Rev.2, January 2014 -** Version: rev. 2.8, 2016-03-21 -** Build: b170112 -** -** Abstract: -** CMSIS Peripheral Access Layer for MK24F12 -** -** Copyright (c) 1997 - 2016 Freescale Semiconductor, Inc. -** Copyright 2016 - 2017 NXP -** Redistribution and use in source and binary forms, with or without modification, -** are permitted provided that the following conditions are met: -** -** o Redistributions of source code must retain the above copyright notice, this list -** of conditions and the following disclaimer. -** -** o Redistributions in binary form must reproduce the above copyright notice, this -** list of conditions and the following disclaimer in the documentation and/or -** other materials provided with the distribution. -** -** o Neither the name of the copyright holder nor the names of its -** contributors may be used to endorse or promote products derived from this -** software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -** ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -** LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -** ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -** -** http: www.nxp.com -** mail: support@nxp.com -** -** Revisions: -** - rev. 1.0 (2013-08-12) -** Initial version. -** - rev. 2.0 (2013-10-29) -** Register accessor macros added to the memory map. -** Symbols for Processor Expert memory map compatibility added to the memory map. -** Startup file for gcc has been updated according to CMSIS 3.2. -** System initialization updated. -** MCG - registers updated. -** PORTA, PORTB, PORTC, PORTE - registers for digital filter removed. -** - rev. 2.1 (2013-10-30) -** Definition of BITBAND macros updated to support peripherals with 32-bit acces disabled. -** - rev. 2.2 (2013-12-09) -** DMA - EARS register removed. -** AIPS0, AIPS1 - MPRA register updated. -** - rev. 2.3 (2014-01-24) -** Update according to reference manual rev. 2 -** ENET, MCG, MCM, SIM, USB - registers updated -** - rev. 2.4 (2014-02-10) -** The declaration of clock configurations has been moved to separate header file system_MK24F12.h -** Update of SystemInit() and SystemCoreClockUpdate() functions. -** Module access macro module_BASES replaced by module_BASE_PTRS. -** - rev. 2.5 (2014-08-28) -** Update of system files - default clock configuration changed. -** Update of startup files - possibility to override DefaultISR added. -** - rev. 2.6 (2014-10-14) -** Interrupt INT_LPTimer renamed to INT_LPTMR0, interrupt INT_Watchdog renamed to INT_WDOG_EWM. -** - rev. 2.7 (2015-02-19) -** Renamed interrupt vector LLW to LLWU. -** - rev. 2.8 (2016-03-21) -** Added MK24FN1M0CAJ12 part. -** GPIO - renamed port instances: PTx -> GPIOx. -** -** ################################################################### -*/ - -/*! - * @file MK24F12.h - * @version 2.8 - * @date 2016-03-21 - * @brief CMSIS Peripheral Access Layer for MK24F12 - * - * CMSIS Peripheral Access Layer for MK24F12 - */ - -#ifndef _MK24F12_H_ -#define _MK24F12_H_ /**< Symbol preventing repeated inclusion */ - -/** Memory map major version (memory maps with equal major version number are - * compatible) */ -#define MCU_MEM_MAP_VERSION 0x0200U -/** Memory map minor version */ -#define MCU_MEM_MAP_VERSION_MINOR 0x0008U - -/** - * @brief Macro to calculate address of an aliased word in the peripheral - * bitband area for a peripheral register and bit (bit band region 0x40000000 to - * 0x400FFFFF). - * @param Reg Register to access. - * @param Bit Bit number to access. - * @return Address of the aliased word in the peripheral bitband area. - */ -#define BITBAND_REGADDR(Reg,Bit) (0x42000000u + (32u*((uint32_t)&(Reg) - (uint32_t)0x40000000u)) + (4u*((uint32_t)(Bit)))) -/** - * @brief Macro to access a single bit of a peripheral register (bit band region - * 0x40000000 to 0x400FFFFF) using the bit-band alias region access. Can - * be used for peripherals with 32bit access allowed. - * @param Reg Register to access. - * @param Bit Bit number to access. - * @return Value of the targeted bit in the bit band region. - */ -#define BITBAND_REG32(Reg,Bit) (*((uint32_t volatile*)(BITBAND_REGADDR((Reg),(Bit))))) -#define BITBAND_REG(Reg,Bit) (BITBAND_REG32((Reg),(Bit))) -/** - * @brief Macro to access a single bit of a peripheral register (bit band region - * 0x40000000 to 0x400FFFFF) using the bit-band alias region access. Can - * be used for peripherals with 16bit access allowed. - * @param Reg Register to access. - * @param Bit Bit number to access. - * @return Value of the targeted bit in the bit band region. - */ -#define BITBAND_REG16(Reg,Bit) (*((uint16_t volatile*)(BITBAND_REGADDR((Reg),(Bit))))) -/** - * @brief Macro to access a single bit of a peripheral register (bit band region - * 0x40000000 to 0x400FFFFF) using the bit-band alias region access. Can - * be used for peripherals with 8bit access allowed. - * @param Reg Register to access. - * @param Bit Bit number to access. - * @return Value of the targeted bit in the bit band region. - */ -#define BITBAND_REG8(Reg,Bit) (*((uint8_t volatile*)(BITBAND_REGADDR((Reg),(Bit))))) - -/* ---------------------------------------------------------------------------- - -- Interrupt vector numbers - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup Interrupt_vector_numbers Interrupt vector numbers - * @{ - */ - -/** Interrupt Number Definitions */ -#define NUMBER_OF_INT_VECTORS 102 /**< Number of interrupts in the Vector table */ - -typedef enum IRQn { - /* Auxiliary constants */ - NotAvail_IRQn = -128, /**< Not available device specific interrupt */ - - /* Core interrupts */ - NonMaskableInt_IRQn = -14, /**< Non Maskable Interrupt */ - HardFault_IRQn = -13, /**< Cortex-M4 SV Hard Fault Interrupt */ - MemoryManagement_IRQn = -12, /**< Cortex-M4 Memory Management Interrupt */ - BusFault_IRQn = -11, /**< Cortex-M4 Bus Fault Interrupt */ - UsageFault_IRQn = -10, /**< Cortex-M4 Usage Fault Interrupt */ - SVCall_IRQn = -5, /**< Cortex-M4 SV Call Interrupt */ - DebugMonitor_IRQn = -4, /**< Cortex-M4 Debug Monitor Interrupt */ - PendSV_IRQn = -2, /**< Cortex-M4 Pend SV Interrupt */ - SysTick_IRQn = -1, /**< Cortex-M4 System Tick Interrupt */ - - /* Device specific interrupts */ - DMA0_IRQn = 0, /**< DMA Channel 0 Transfer Complete */ - DMA1_IRQn = 1, /**< DMA Channel 1 Transfer Complete */ - DMA2_IRQn = 2, /**< DMA Channel 2 Transfer Complete */ - DMA3_IRQn = 3, /**< DMA Channel 3 Transfer Complete */ - DMA4_IRQn = 4, /**< DMA Channel 4 Transfer Complete */ - DMA5_IRQn = 5, /**< DMA Channel 5 Transfer Complete */ - DMA6_IRQn = 6, /**< DMA Channel 6 Transfer Complete */ - DMA7_IRQn = 7, /**< DMA Channel 7 Transfer Complete */ - DMA8_IRQn = 8, /**< DMA Channel 8 Transfer Complete */ - DMA9_IRQn = 9, /**< DMA Channel 9 Transfer Complete */ - DMA10_IRQn = 10, /**< DMA Channel 10 Transfer Complete */ - DMA11_IRQn = 11, /**< DMA Channel 11 Transfer Complete */ - DMA12_IRQn = 12, /**< DMA Channel 12 Transfer Complete */ - DMA13_IRQn = 13, /**< DMA Channel 13 Transfer Complete */ - DMA14_IRQn = 14, /**< DMA Channel 14 Transfer Complete */ - DMA15_IRQn = 15, /**< DMA Channel 15 Transfer Complete */ - DMA_Error_IRQn = 16, /**< DMA Error Interrupt */ - MCM_IRQn = 17, /**< Normal Interrupt */ - FTFE_IRQn = 18, /**< FTFE Command complete interrupt */ - Read_Collision_IRQn = 19, /**< Read Collision Interrupt */ - LVD_LVW_IRQn = 20, /**< Low Voltage Detect, Low Voltage Warning */ - LLWU_IRQn = 21, /**< Low Leakage Wakeup Unit */ - WDOG_EWM_IRQn = 22, /**< WDOG Interrupt */ - RNG_IRQn = 23, /**< RNG Interrupt */ - I2C0_IRQn = 24, /**< I2C0 interrupt */ - I2C1_IRQn = 25, /**< I2C1 interrupt */ - SPI0_IRQn = 26, /**< SPI0 Interrupt */ - SPI1_IRQn = 27, /**< SPI1 Interrupt */ - I2S0_Tx_IRQn = 28, /**< I2S0 transmit interrupt */ - I2S0_Rx_IRQn = 29, /**< I2S0 receive interrupt */ - UART0_LON_IRQn = 30, /**< UART0 LON interrupt */ - UART0_RX_TX_IRQn = 31, /**< UART0 Receive/Transmit interrupt */ - UART0_ERR_IRQn = 32, /**< UART0 Error interrupt */ - UART1_RX_TX_IRQn = 33, /**< UART1 Receive/Transmit interrupt */ - UART1_ERR_IRQn = 34, /**< UART1 Error interrupt */ - UART2_RX_TX_IRQn = 35, /**< UART2 Receive/Transmit interrupt */ - UART2_ERR_IRQn = 36, /**< UART2 Error interrupt */ - UART3_RX_TX_IRQn = 37, /**< UART3 Receive/Transmit interrupt */ - UART3_ERR_IRQn = 38, /**< UART3 Error interrupt */ - ADC0_IRQn = 39, /**< ADC0 interrupt */ - CMP0_IRQn = 40, /**< CMP0 interrupt */ - CMP1_IRQn = 41, /**< CMP1 interrupt */ - FTM0_IRQn = 42, /**< FTM0 fault, overflow and channels interrupt */ - FTM1_IRQn = 43, /**< FTM1 fault, overflow and channels interrupt */ - FTM2_IRQn = 44, /**< FTM2 fault, overflow and channels interrupt */ - CMT_IRQn = 45, /**< CMT interrupt */ - RTC_IRQn = 46, /**< RTC interrupt */ - RTC_Seconds_IRQn = 47, /**< RTC seconds interrupt */ - PIT0_IRQn = 48, /**< PIT timer channel 0 interrupt */ - PIT1_IRQn = 49, /**< PIT timer channel 1 interrupt */ - PIT2_IRQn = 50, /**< PIT timer channel 2 interrupt */ - PIT3_IRQn = 51, /**< PIT timer channel 3 interrupt */ - PDB0_IRQn = 52, /**< PDB0 Interrupt */ - USB0_IRQn = 53, /**< USB0 interrupt */ - USBDCD_IRQn = 54, /**< USBDCD Interrupt */ - Reserved71_IRQn = 55, /**< Reserved interrupt 71 */ - DAC0_IRQn = 56, /**< DAC0 interrupt */ - MCG_IRQn = 57, /**< MCG Interrupt */ - LPTMR0_IRQn = 58, /**< LPTimer interrupt */ - PORTA_IRQn = 59, /**< Port A interrupt */ - PORTB_IRQn = 60, /**< Port B interrupt */ - PORTC_IRQn = 61, /**< Port C interrupt */ - PORTD_IRQn = 62, /**< Port D interrupt */ - PORTE_IRQn = 63, /**< Port E interrupt */ - SWI_IRQn = 64, /**< Software interrupt */ - SPI2_IRQn = 65, /**< SPI2 Interrupt */ - UART4_RX_TX_IRQn = 66, /**< UART4 Receive/Transmit interrupt */ - UART4_ERR_IRQn = 67, /**< UART4 Error interrupt */ - UART5_RX_TX_IRQn = 68, /**< UART5 Receive/Transmit interrupt */ - UART5_ERR_IRQn = 69, /**< UART5 Error interrupt */ - CMP2_IRQn = 70, /**< CMP2 interrupt */ - FTM3_IRQn = 71, /**< FTM3 fault, overflow and channels interrupt */ - DAC1_IRQn = 72, /**< DAC1 interrupt */ - ADC1_IRQn = 73, /**< ADC1 interrupt */ - I2C2_IRQn = 74, /**< I2C2 interrupt */ - CAN0_ORed_Message_buffer_IRQn = 75, /**< CAN0 OR'd message buffers interrupt */ - CAN0_Bus_Off_IRQn = 76, /**< CAN0 bus off interrupt */ - CAN0_Error_IRQn = 77, /**< CAN0 error interrupt */ - CAN0_Tx_Warning_IRQn = 78, /**< CAN0 Tx warning interrupt */ - CAN0_Rx_Warning_IRQn = 79, /**< CAN0 Rx warning interrupt */ - CAN0_Wake_Up_IRQn = 80, /**< CAN0 wake up interrupt */ - SDHC_IRQn = 81, /**< SDHC interrupt */ - Reserved98_IRQn = 82, /**< Reserved interrupt 98 */ - Reserved99_IRQn = 83, /**< Reserved interrupt 99 */ - Reserved100_IRQn = 84, /**< Reserved interrupt 100 */ - Reserved101_IRQn = 85 /**< Reserved interrupt 101 */ -} IRQn_Type; - -/*! - * @} - */ /* end of group Interrupt_vector_numbers */ - - -/* ---------------------------------------------------------------------------- - -- Cortex M4 Core Configuration - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup Cortex_Core_Configuration Cortex M4 Core Configuration - * @{ - */ - -#define __MPU_PRESENT 0 /**< Defines if an MPU is present or not */ -#define __NVIC_PRIO_BITS 4 /**< Number of priority bits implemented in the NVIC */ -#define __Vendor_SysTickConfig 0 /**< Vendor specific implementation of SysTickConfig is defined */ -#define __FPU_PRESENT 1 /**< Defines if an FPU is present or not */ - -#include "core_cm4.h" /* Core Peripheral Access Layer */ -#include "system_MK24F12.h" /* Device specific configuration file */ - -/*! - * @} - */ /* end of group Cortex_Core_Configuration */ - - -/* ---------------------------------------------------------------------------- - -- Mapping Information - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup Mapping_Information Mapping Information - * @{ - */ - -/** Mapping Information */ -/*! - * @addtogroup edma_request - * @{ - */ - -/******************************************************************************* - * Definitions - ******************************************************************************/ - -/*! - * @brief Structure for the DMA hardware request - * - * Defines the structure for the DMA hardware request collections. The user can configure the - * hardware request into DMAMUX to trigger the DMA transfer accordingly. The index - * of the hardware request varies according to the to SoC. - */ -typedef enum _dma_request_source -{ - kDmaRequestMux0Disable = 0|0x100U, /**< DMAMUX TriggerDisabled. */ - kDmaRequestMux0Reserved1 = 1|0x100U, /**< Reserved1 */ - kDmaRequestMux0UART0Rx = 2|0x100U, /**< UART0 Receive. */ - kDmaRequestMux0UART0Tx = 3|0x100U, /**< UART0 Transmit. */ - kDmaRequestMux0UART1Rx = 4|0x100U, /**< UART1 Receive. */ - kDmaRequestMux0UART1Tx = 5|0x100U, /**< UART1 Transmit. */ - kDmaRequestMux0UART2Rx = 6|0x100U, /**< UART2 Receive. */ - kDmaRequestMux0UART2Tx = 7|0x100U, /**< UART2 Transmit. */ - kDmaRequestMux0UART3Rx = 8|0x100U, /**< UART3 Receive. */ - kDmaRequestMux0UART3Tx = 9|0x100U, /**< UART3 Transmit. */ - kDmaRequestMux0UART4 = 10|0x100U, /**< UART4 Transmit or Receive. */ - kDmaRequestMux0UART5 = 11|0x100U, /**< UART5 Transmit or Receive. */ - kDmaRequestMux0I2S0Rx = 12|0x100U, /**< I2S0 Receive. */ - kDmaRequestMux0I2S0Tx = 13|0x100U, /**< I2S0 Transmit. */ - kDmaRequestMux0SPI0Rx = 14|0x100U, /**< SPI0 Receive. */ - kDmaRequestMux0SPI0Tx = 15|0x100U, /**< SPI0 Transmit. */ - kDmaRequestMux0SPI1 = 16|0x100U, /**< SPI1 Transmit or Receive. */ - kDmaRequestMux0SPI2 = 17|0x100U, /**< SPI2 Transmit or Receive. */ - kDmaRequestMux0I2C0 = 18|0x100U, /**< I2C0. */ - kDmaRequestMux0I2C1I2C2 = 19|0x100U, /**< I2C1 and I2C2. */ - kDmaRequestMux0I2C1 = 19|0x100U, /**< I2C1 and I2C2. */ - kDmaRequestMux0I2C2 = 19|0x100U, /**< I2C1 and I2C2. */ - kDmaRequestMux0FTM0Channel0 = 20|0x100U, /**< FTM0 C0V. */ - kDmaRequestMux0FTM0Channel1 = 21|0x100U, /**< FTM0 C1V. */ - kDmaRequestMux0FTM0Channel2 = 22|0x100U, /**< FTM0 C2V. */ - kDmaRequestMux0FTM0Channel3 = 23|0x100U, /**< FTM0 C3V. */ - kDmaRequestMux0FTM0Channel4 = 24|0x100U, /**< FTM0 C4V. */ - kDmaRequestMux0FTM0Channel5 = 25|0x100U, /**< FTM0 C5V. */ - kDmaRequestMux0FTM0Channel6 = 26|0x100U, /**< FTM0 C6V. */ - kDmaRequestMux0FTM0Channel7 = 27|0x100U, /**< FTM0 C7V. */ - kDmaRequestMux0FTM1Channel0 = 28|0x100U, /**< FTM1 C0V. */ - kDmaRequestMux0FTM1Channel1 = 29|0x100U, /**< FTM1 C1V. */ - kDmaRequestMux0FTM2Channel0 = 30|0x100U, /**< FTM2 C0V. */ - kDmaRequestMux0FTM2Channel1 = 31|0x100U, /**< FTM2 C1V. */ - kDmaRequestMux0FTM3Channel0 = 32|0x100U, /**< FTM3 C0V. */ - kDmaRequestMux0FTM3Channel1 = 33|0x100U, /**< FTM3 C1V. */ - kDmaRequestMux0FTM3Channel2 = 34|0x100U, /**< FTM3 C2V. */ - kDmaRequestMux0FTM3Channel3 = 35|0x100U, /**< FTM3 C3V. */ - kDmaRequestMux0FTM3Channel4 = 36|0x100U, /**< FTM3 C4V. */ - kDmaRequestMux0FTM3Channel5 = 37|0x100U, /**< FTM3 C5V. */ - kDmaRequestMux0FTM3Channel6 = 38|0x100U, /**< FTM3 C6V. */ - kDmaRequestMux0FTM3Channel7 = 39|0x100U, /**< FTM3 C7V. */ - kDmaRequestMux0ADC0 = 40|0x100U, /**< ADC0. */ - kDmaRequestMux0ADC1 = 41|0x100U, /**< ADC1. */ - kDmaRequestMux0CMP0 = 42|0x100U, /**< CMP0. */ - kDmaRequestMux0CMP1 = 43|0x100U, /**< CMP1. */ - kDmaRequestMux0CMP2 = 44|0x100U, /**< CMP2. */ - kDmaRequestMux0DAC0 = 45|0x100U, /**< DAC0. */ - kDmaRequestMux0DAC1 = 46|0x100U, /**< DAC1. */ - kDmaRequestMux0CMT = 47|0x100U, /**< CMT. */ - kDmaRequestMux0PDB = 48|0x100U, /**< PDB0. */ - kDmaRequestMux0PortA = 49|0x100U, /**< PTA. */ - kDmaRequestMux0PortB = 50|0x100U, /**< PTB. */ - kDmaRequestMux0PortC = 51|0x100U, /**< PTC. */ - kDmaRequestMux0PortD = 52|0x100U, /**< PTD. */ - kDmaRequestMux0PortE = 53|0x100U, /**< PTE. */ - kDmaRequestMux0Reserved54 = 54|0x100U, /**< Reserved54 */ - kDmaRequestMux0Reserved55 = 55|0x100U, /**< Reserved55 */ - kDmaRequestMux0Reserved56 = 56|0x100U, /**< Reserved56 */ - kDmaRequestMux0Reserved57 = 57|0x100U, /**< Reserved57 */ - kDmaRequestMux0AlwaysOn58 = 58|0x100U, /**< DMAMUX Always Enabled slot. */ - kDmaRequestMux0AlwaysOn59 = 59|0x100U, /**< DMAMUX Always Enabled slot. */ - kDmaRequestMux0AlwaysOn60 = 60|0x100U, /**< DMAMUX Always Enabled slot. */ - kDmaRequestMux0AlwaysOn61 = 61|0x100U, /**< DMAMUX Always Enabled slot. */ - kDmaRequestMux0AlwaysOn62 = 62|0x100U, /**< DMAMUX Always Enabled slot. */ - kDmaRequestMux0AlwaysOn63 = 63|0x100U, /**< DMAMUX Always Enabled slot. */ -} dma_request_source_t; - -/* @} */ - - -/*! - * @} - */ /* end of group Mapping_Information */ - - -/* ---------------------------------------------------------------------------- - -- Device Peripheral Access Layer - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup Peripheral_access_layer Device Peripheral Access Layer - * @{ - */ - - -/* -** Start of section using anonymous unions -*/ - -#if defined(__ARMCC_VERSION) - #pragma push - #pragma anon_unions -#elif defined(__CWCC__) - #pragma push - #pragma cpp_extensions on -#elif defined(__GNUC__) - /* anonymous unions are enabled by default */ -#elif defined(__IAR_SYSTEMS_ICC__) - #pragma language=extended -#else - #error Not supported compiler type -#endif - -/* ---------------------------------------------------------------------------- - -- ADC Peripheral Access Layer - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup ADC_Peripheral_Access_Layer ADC Peripheral Access Layer - * @{ - */ - -/** ADC - Register Layout Typedef */ -typedef struct { - __IO uint32_t SC1[2]; /**< ADC Status and Control Registers 1, array offset: 0x0, array step: 0x4 */ - __IO uint32_t CFG1; /**< ADC Configuration Register 1, offset: 0x8 */ - __IO uint32_t CFG2; /**< ADC Configuration Register 2, offset: 0xC */ - __I uint32_t R[2]; /**< ADC Data Result Register, array offset: 0x10, array step: 0x4 */ - __IO uint32_t CV1; /**< Compare Value Registers, offset: 0x18 */ - __IO uint32_t CV2; /**< Compare Value Registers, offset: 0x1C */ - __IO uint32_t SC2; /**< Status and Control Register 2, offset: 0x20 */ - __IO uint32_t SC3; /**< Status and Control Register 3, offset: 0x24 */ - __IO uint32_t OFS; /**< ADC Offset Correction Register, offset: 0x28 */ - __IO uint32_t PG; /**< ADC Plus-Side Gain Register, offset: 0x2C */ - __IO uint32_t MG; /**< ADC Minus-Side Gain Register, offset: 0x30 */ - __IO uint32_t CLPD; /**< ADC Plus-Side General Calibration Value Register, offset: 0x34 */ - __IO uint32_t CLPS; /**< ADC Plus-Side General Calibration Value Register, offset: 0x38 */ - __IO uint32_t CLP4; /**< ADC Plus-Side General Calibration Value Register, offset: 0x3C */ - __IO uint32_t CLP3; /**< ADC Plus-Side General Calibration Value Register, offset: 0x40 */ - __IO uint32_t CLP2; /**< ADC Plus-Side General Calibration Value Register, offset: 0x44 */ - __IO uint32_t CLP1; /**< ADC Plus-Side General Calibration Value Register, offset: 0x48 */ - __IO uint32_t CLP0; /**< ADC Plus-Side General Calibration Value Register, offset: 0x4C */ - uint8_t RESERVED_0[4]; - __IO uint32_t CLMD; /**< ADC Minus-Side General Calibration Value Register, offset: 0x54 */ - __IO uint32_t CLMS; /**< ADC Minus-Side General Calibration Value Register, offset: 0x58 */ - __IO uint32_t CLM4; /**< ADC Minus-Side General Calibration Value Register, offset: 0x5C */ - __IO uint32_t CLM3; /**< ADC Minus-Side General Calibration Value Register, offset: 0x60 */ - __IO uint32_t CLM2; /**< ADC Minus-Side General Calibration Value Register, offset: 0x64 */ - __IO uint32_t CLM1; /**< ADC Minus-Side General Calibration Value Register, offset: 0x68 */ - __IO uint32_t CLM0; /**< ADC Minus-Side General Calibration Value Register, offset: 0x6C */ -} ADC_Type; - -/* ---------------------------------------------------------------------------- - -- ADC Register Masks - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup ADC_Register_Masks ADC Register Masks - * @{ - */ - -/*! @name SC1 - ADC Status and Control Registers 1 */ -#define ADC_SC1_ADCH_MASK (0x1FU) -#define ADC_SC1_ADCH_SHIFT (0U) -#define ADC_SC1_ADCH(x) (((uint32_t)(((uint32_t)(x)) << ADC_SC1_ADCH_SHIFT)) & ADC_SC1_ADCH_MASK) -#define ADC_SC1_DIFF_MASK (0x20U) -#define ADC_SC1_DIFF_SHIFT (5U) -#define ADC_SC1_DIFF(x) (((uint32_t)(((uint32_t)(x)) << ADC_SC1_DIFF_SHIFT)) & ADC_SC1_DIFF_MASK) -#define ADC_SC1_AIEN_MASK (0x40U) -#define ADC_SC1_AIEN_SHIFT (6U) -#define ADC_SC1_AIEN(x) (((uint32_t)(((uint32_t)(x)) << ADC_SC1_AIEN_SHIFT)) & ADC_SC1_AIEN_MASK) -#define ADC_SC1_COCO_MASK (0x80U) -#define ADC_SC1_COCO_SHIFT (7U) -#define ADC_SC1_COCO(x) (((uint32_t)(((uint32_t)(x)) << ADC_SC1_COCO_SHIFT)) & ADC_SC1_COCO_MASK) - -/* The count of ADC_SC1 */ -#define ADC_SC1_COUNT (2U) - -/*! @name CFG1 - ADC Configuration Register 1 */ -#define ADC_CFG1_ADICLK_MASK (0x3U) -#define ADC_CFG1_ADICLK_SHIFT (0U) -#define ADC_CFG1_ADICLK(x) (((uint32_t)(((uint32_t)(x)) << ADC_CFG1_ADICLK_SHIFT)) & ADC_CFG1_ADICLK_MASK) -#define ADC_CFG1_MODE_MASK (0xCU) -#define ADC_CFG1_MODE_SHIFT (2U) -#define ADC_CFG1_MODE(x) (((uint32_t)(((uint32_t)(x)) << ADC_CFG1_MODE_SHIFT)) & ADC_CFG1_MODE_MASK) -#define ADC_CFG1_ADLSMP_MASK (0x10U) -#define ADC_CFG1_ADLSMP_SHIFT (4U) -#define ADC_CFG1_ADLSMP(x) (((uint32_t)(((uint32_t)(x)) << ADC_CFG1_ADLSMP_SHIFT)) & ADC_CFG1_ADLSMP_MASK) -#define ADC_CFG1_ADIV_MASK (0x60U) -#define ADC_CFG1_ADIV_SHIFT (5U) -#define ADC_CFG1_ADIV(x) (((uint32_t)(((uint32_t)(x)) << ADC_CFG1_ADIV_SHIFT)) & ADC_CFG1_ADIV_MASK) -#define ADC_CFG1_ADLPC_MASK (0x80U) -#define ADC_CFG1_ADLPC_SHIFT (7U) -#define ADC_CFG1_ADLPC(x) (((uint32_t)(((uint32_t)(x)) << ADC_CFG1_ADLPC_SHIFT)) & ADC_CFG1_ADLPC_MASK) - -/*! @name CFG2 - ADC Configuration Register 2 */ -#define ADC_CFG2_ADLSTS_MASK (0x3U) -#define ADC_CFG2_ADLSTS_SHIFT (0U) -#define ADC_CFG2_ADLSTS(x) (((uint32_t)(((uint32_t)(x)) << ADC_CFG2_ADLSTS_SHIFT)) & ADC_CFG2_ADLSTS_MASK) -#define ADC_CFG2_ADHSC_MASK (0x4U) -#define ADC_CFG2_ADHSC_SHIFT (2U) -#define ADC_CFG2_ADHSC(x) (((uint32_t)(((uint32_t)(x)) << ADC_CFG2_ADHSC_SHIFT)) & ADC_CFG2_ADHSC_MASK) -#define ADC_CFG2_ADACKEN_MASK (0x8U) -#define ADC_CFG2_ADACKEN_SHIFT (3U) -#define ADC_CFG2_ADACKEN(x) (((uint32_t)(((uint32_t)(x)) << ADC_CFG2_ADACKEN_SHIFT)) & ADC_CFG2_ADACKEN_MASK) -#define ADC_CFG2_MUXSEL_MASK (0x10U) -#define ADC_CFG2_MUXSEL_SHIFT (4U) -#define ADC_CFG2_MUXSEL(x) (((uint32_t)(((uint32_t)(x)) << ADC_CFG2_MUXSEL_SHIFT)) & ADC_CFG2_MUXSEL_MASK) - -/*! @name R - ADC Data Result Register */ -#define ADC_R_D_MASK (0xFFFFU) -#define ADC_R_D_SHIFT (0U) -#define ADC_R_D(x) (((uint32_t)(((uint32_t)(x)) << ADC_R_D_SHIFT)) & ADC_R_D_MASK) - -/* The count of ADC_R */ -#define ADC_R_COUNT (2U) - -/*! @name CV1 - Compare Value Registers */ -#define ADC_CV1_CV_MASK (0xFFFFU) -#define ADC_CV1_CV_SHIFT (0U) -#define ADC_CV1_CV(x) (((uint32_t)(((uint32_t)(x)) << ADC_CV1_CV_SHIFT)) & ADC_CV1_CV_MASK) - -/*! @name CV2 - Compare Value Registers */ -#define ADC_CV2_CV_MASK (0xFFFFU) -#define ADC_CV2_CV_SHIFT (0U) -#define ADC_CV2_CV(x) (((uint32_t)(((uint32_t)(x)) << ADC_CV2_CV_SHIFT)) & ADC_CV2_CV_MASK) - -/*! @name SC2 - Status and Control Register 2 */ -#define ADC_SC2_REFSEL_MASK (0x3U) -#define ADC_SC2_REFSEL_SHIFT (0U) -#define ADC_SC2_REFSEL(x) (((uint32_t)(((uint32_t)(x)) << ADC_SC2_REFSEL_SHIFT)) & ADC_SC2_REFSEL_MASK) -#define ADC_SC2_DMAEN_MASK (0x4U) -#define ADC_SC2_DMAEN_SHIFT (2U) -#define ADC_SC2_DMAEN(x) (((uint32_t)(((uint32_t)(x)) << ADC_SC2_DMAEN_SHIFT)) & ADC_SC2_DMAEN_MASK) -#define ADC_SC2_ACREN_MASK (0x8U) -#define ADC_SC2_ACREN_SHIFT (3U) -#define ADC_SC2_ACREN(x) (((uint32_t)(((uint32_t)(x)) << ADC_SC2_ACREN_SHIFT)) & ADC_SC2_ACREN_MASK) -#define ADC_SC2_ACFGT_MASK (0x10U) -#define ADC_SC2_ACFGT_SHIFT (4U) -#define ADC_SC2_ACFGT(x) (((uint32_t)(((uint32_t)(x)) << ADC_SC2_ACFGT_SHIFT)) & ADC_SC2_ACFGT_MASK) -#define ADC_SC2_ACFE_MASK (0x20U) -#define ADC_SC2_ACFE_SHIFT (5U) -#define ADC_SC2_ACFE(x) (((uint32_t)(((uint32_t)(x)) << ADC_SC2_ACFE_SHIFT)) & ADC_SC2_ACFE_MASK) -#define ADC_SC2_ADTRG_MASK (0x40U) -#define ADC_SC2_ADTRG_SHIFT (6U) -#define ADC_SC2_ADTRG(x) (((uint32_t)(((uint32_t)(x)) << ADC_SC2_ADTRG_SHIFT)) & ADC_SC2_ADTRG_MASK) -#define ADC_SC2_ADACT_MASK (0x80U) -#define ADC_SC2_ADACT_SHIFT (7U) -#define ADC_SC2_ADACT(x) (((uint32_t)(((uint32_t)(x)) << ADC_SC2_ADACT_SHIFT)) & ADC_SC2_ADACT_MASK) - -/*! @name SC3 - Status and Control Register 3 */ -#define ADC_SC3_AVGS_MASK (0x3U) -#define ADC_SC3_AVGS_SHIFT (0U) -#define ADC_SC3_AVGS(x) (((uint32_t)(((uint32_t)(x)) << ADC_SC3_AVGS_SHIFT)) & ADC_SC3_AVGS_MASK) -#define ADC_SC3_AVGE_MASK (0x4U) -#define ADC_SC3_AVGE_SHIFT (2U) -#define ADC_SC3_AVGE(x) (((uint32_t)(((uint32_t)(x)) << ADC_SC3_AVGE_SHIFT)) & ADC_SC3_AVGE_MASK) -#define ADC_SC3_ADCO_MASK (0x8U) -#define ADC_SC3_ADCO_SHIFT (3U) -#define ADC_SC3_ADCO(x) (((uint32_t)(((uint32_t)(x)) << ADC_SC3_ADCO_SHIFT)) & ADC_SC3_ADCO_MASK) -#define ADC_SC3_CALF_MASK (0x40U) -#define ADC_SC3_CALF_SHIFT (6U) -#define ADC_SC3_CALF(x) (((uint32_t)(((uint32_t)(x)) << ADC_SC3_CALF_SHIFT)) & ADC_SC3_CALF_MASK) -#define ADC_SC3_CAL_MASK (0x80U) -#define ADC_SC3_CAL_SHIFT (7U) -#define ADC_SC3_CAL(x) (((uint32_t)(((uint32_t)(x)) << ADC_SC3_CAL_SHIFT)) & ADC_SC3_CAL_MASK) - -/*! @name OFS - ADC Offset Correction Register */ -#define ADC_OFS_OFS_MASK (0xFFFFU) -#define ADC_OFS_OFS_SHIFT (0U) -#define ADC_OFS_OFS(x) (((uint32_t)(((uint32_t)(x)) << ADC_OFS_OFS_SHIFT)) & ADC_OFS_OFS_MASK) - -/*! @name PG - ADC Plus-Side Gain Register */ -#define ADC_PG_PG_MASK (0xFFFFU) -#define ADC_PG_PG_SHIFT (0U) -#define ADC_PG_PG(x) (((uint32_t)(((uint32_t)(x)) << ADC_PG_PG_SHIFT)) & ADC_PG_PG_MASK) - -/*! @name MG - ADC Minus-Side Gain Register */ -#define ADC_MG_MG_MASK (0xFFFFU) -#define ADC_MG_MG_SHIFT (0U) -#define ADC_MG_MG(x) (((uint32_t)(((uint32_t)(x)) << ADC_MG_MG_SHIFT)) & ADC_MG_MG_MASK) - -/*! @name CLPD - ADC Plus-Side General Calibration Value Register */ -#define ADC_CLPD_CLPD_MASK (0x3FU) -#define ADC_CLPD_CLPD_SHIFT (0U) -#define ADC_CLPD_CLPD(x) (((uint32_t)(((uint32_t)(x)) << ADC_CLPD_CLPD_SHIFT)) & ADC_CLPD_CLPD_MASK) - -/*! @name CLPS - ADC Plus-Side General Calibration Value Register */ -#define ADC_CLPS_CLPS_MASK (0x3FU) -#define ADC_CLPS_CLPS_SHIFT (0U) -#define ADC_CLPS_CLPS(x) (((uint32_t)(((uint32_t)(x)) << ADC_CLPS_CLPS_SHIFT)) & ADC_CLPS_CLPS_MASK) - -/*! @name CLP4 - ADC Plus-Side General Calibration Value Register */ -#define ADC_CLP4_CLP4_MASK (0x3FFU) -#define ADC_CLP4_CLP4_SHIFT (0U) -#define ADC_CLP4_CLP4(x) (((uint32_t)(((uint32_t)(x)) << ADC_CLP4_CLP4_SHIFT)) & ADC_CLP4_CLP4_MASK) - -/*! @name CLP3 - ADC Plus-Side General Calibration Value Register */ -#define ADC_CLP3_CLP3_MASK (0x1FFU) -#define ADC_CLP3_CLP3_SHIFT (0U) -#define ADC_CLP3_CLP3(x) (((uint32_t)(((uint32_t)(x)) << ADC_CLP3_CLP3_SHIFT)) & ADC_CLP3_CLP3_MASK) - -/*! @name CLP2 - ADC Plus-Side General Calibration Value Register */ -#define ADC_CLP2_CLP2_MASK (0xFFU) -#define ADC_CLP2_CLP2_SHIFT (0U) -#define ADC_CLP2_CLP2(x) (((uint32_t)(((uint32_t)(x)) << ADC_CLP2_CLP2_SHIFT)) & ADC_CLP2_CLP2_MASK) - -/*! @name CLP1 - ADC Plus-Side General Calibration Value Register */ -#define ADC_CLP1_CLP1_MASK (0x7FU) -#define ADC_CLP1_CLP1_SHIFT (0U) -#define ADC_CLP1_CLP1(x) (((uint32_t)(((uint32_t)(x)) << ADC_CLP1_CLP1_SHIFT)) & ADC_CLP1_CLP1_MASK) - -/*! @name CLP0 - ADC Plus-Side General Calibration Value Register */ -#define ADC_CLP0_CLP0_MASK (0x3FU) -#define ADC_CLP0_CLP0_SHIFT (0U) -#define ADC_CLP0_CLP0(x) (((uint32_t)(((uint32_t)(x)) << ADC_CLP0_CLP0_SHIFT)) & ADC_CLP0_CLP0_MASK) - -/*! @name CLMD - ADC Minus-Side General Calibration Value Register */ -#define ADC_CLMD_CLMD_MASK (0x3FU) -#define ADC_CLMD_CLMD_SHIFT (0U) -#define ADC_CLMD_CLMD(x) (((uint32_t)(((uint32_t)(x)) << ADC_CLMD_CLMD_SHIFT)) & ADC_CLMD_CLMD_MASK) - -/*! @name CLMS - ADC Minus-Side General Calibration Value Register */ -#define ADC_CLMS_CLMS_MASK (0x3FU) -#define ADC_CLMS_CLMS_SHIFT (0U) -#define ADC_CLMS_CLMS(x) (((uint32_t)(((uint32_t)(x)) << ADC_CLMS_CLMS_SHIFT)) & ADC_CLMS_CLMS_MASK) - -/*! @name CLM4 - ADC Minus-Side General Calibration Value Register */ -#define ADC_CLM4_CLM4_MASK (0x3FFU) -#define ADC_CLM4_CLM4_SHIFT (0U) -#define ADC_CLM4_CLM4(x) (((uint32_t)(((uint32_t)(x)) << ADC_CLM4_CLM4_SHIFT)) & ADC_CLM4_CLM4_MASK) - -/*! @name CLM3 - ADC Minus-Side General Calibration Value Register */ -#define ADC_CLM3_CLM3_MASK (0x1FFU) -#define ADC_CLM3_CLM3_SHIFT (0U) -#define ADC_CLM3_CLM3(x) (((uint32_t)(((uint32_t)(x)) << ADC_CLM3_CLM3_SHIFT)) & ADC_CLM3_CLM3_MASK) - -/*! @name CLM2 - ADC Minus-Side General Calibration Value Register */ -#define ADC_CLM2_CLM2_MASK (0xFFU) -#define ADC_CLM2_CLM2_SHIFT (0U) -#define ADC_CLM2_CLM2(x) (((uint32_t)(((uint32_t)(x)) << ADC_CLM2_CLM2_SHIFT)) & ADC_CLM2_CLM2_MASK) - -/*! @name CLM1 - ADC Minus-Side General Calibration Value Register */ -#define ADC_CLM1_CLM1_MASK (0x7FU) -#define ADC_CLM1_CLM1_SHIFT (0U) -#define ADC_CLM1_CLM1(x) (((uint32_t)(((uint32_t)(x)) << ADC_CLM1_CLM1_SHIFT)) & ADC_CLM1_CLM1_MASK) - -/*! @name CLM0 - ADC Minus-Side General Calibration Value Register */ -#define ADC_CLM0_CLM0_MASK (0x3FU) -#define ADC_CLM0_CLM0_SHIFT (0U) -#define ADC_CLM0_CLM0(x) (((uint32_t)(((uint32_t)(x)) << ADC_CLM0_CLM0_SHIFT)) & ADC_CLM0_CLM0_MASK) - - -/*! - * @} - */ /* end of group ADC_Register_Masks */ - - -/* ADC - Peripheral instance base addresses */ -/** Peripheral ADC0 base address */ -#define ADC0_BASE (0x4003B000u) -/** Peripheral ADC0 base pointer */ -#define ADC0 ((ADC_Type *)ADC0_BASE) -/** Peripheral ADC1 base address */ -#define ADC1_BASE (0x400BB000u) -/** Peripheral ADC1 base pointer */ -#define ADC1 ((ADC_Type *)ADC1_BASE) -/** Array initializer of ADC peripheral base addresses */ -#define ADC_BASE_ADDRS { ADC0_BASE, ADC1_BASE } -/** Array initializer of ADC peripheral base pointers */ -#define ADC_BASE_PTRS { ADC0, ADC1 } -/** Interrupt vectors for the ADC peripheral type */ -#define ADC_IRQS { ADC0_IRQn, ADC1_IRQn } - -/*! - * @} - */ /* end of group ADC_Peripheral_Access_Layer */ - - -/* ---------------------------------------------------------------------------- - -- AIPS Peripheral Access Layer - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup AIPS_Peripheral_Access_Layer AIPS Peripheral Access Layer - * @{ - */ - -/** AIPS - Register Layout Typedef */ -typedef struct { - __IO uint32_t MPRA; /**< Master Privilege Register A, offset: 0x0 */ - uint8_t RESERVED_0[28]; - __IO uint32_t PACRA; /**< Peripheral Access Control Register, offset: 0x20 */ - __IO uint32_t PACRB; /**< Peripheral Access Control Register, offset: 0x24 */ - __IO uint32_t PACRC; /**< Peripheral Access Control Register, offset: 0x28 */ - __IO uint32_t PACRD; /**< Peripheral Access Control Register, offset: 0x2C */ - uint8_t RESERVED_1[16]; - __IO uint32_t PACRE; /**< Peripheral Access Control Register, offset: 0x40 */ - __IO uint32_t PACRF; /**< Peripheral Access Control Register, offset: 0x44 */ - __IO uint32_t PACRG; /**< Peripheral Access Control Register, offset: 0x48 */ - __IO uint32_t PACRH; /**< Peripheral Access Control Register, offset: 0x4C */ - __IO uint32_t PACRI; /**< Peripheral Access Control Register, offset: 0x50 */ - __IO uint32_t PACRJ; /**< Peripheral Access Control Register, offset: 0x54 */ - __IO uint32_t PACRK; /**< Peripheral Access Control Register, offset: 0x58 */ - __IO uint32_t PACRL; /**< Peripheral Access Control Register, offset: 0x5C */ - __IO uint32_t PACRM; /**< Peripheral Access Control Register, offset: 0x60 */ - __IO uint32_t PACRN; /**< Peripheral Access Control Register, offset: 0x64 */ - __IO uint32_t PACRO; /**< Peripheral Access Control Register, offset: 0x68 */ - __IO uint32_t PACRP; /**< Peripheral Access Control Register, offset: 0x6C */ - uint8_t RESERVED_2[16]; - __IO uint32_t PACRU; /**< Peripheral Access Control Register, offset: 0x80 */ -} AIPS_Type; - -/* ---------------------------------------------------------------------------- - -- AIPS Register Masks - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup AIPS_Register_Masks AIPS Register Masks - * @{ - */ - -/*! @name MPRA - Master Privilege Register A */ -#define AIPS_MPRA_MPL5_MASK (0x100U) -#define AIPS_MPRA_MPL5_SHIFT (8U) -#define AIPS_MPRA_MPL5(x) (((uint32_t)(((uint32_t)(x)) << AIPS_MPRA_MPL5_SHIFT)) & AIPS_MPRA_MPL5_MASK) -#define AIPS_MPRA_MTW5_MASK (0x200U) -#define AIPS_MPRA_MTW5_SHIFT (9U) -#define AIPS_MPRA_MTW5(x) (((uint32_t)(((uint32_t)(x)) << AIPS_MPRA_MTW5_SHIFT)) & AIPS_MPRA_MTW5_MASK) -#define AIPS_MPRA_MTR5_MASK (0x400U) -#define AIPS_MPRA_MTR5_SHIFT (10U) -#define AIPS_MPRA_MTR5(x) (((uint32_t)(((uint32_t)(x)) << AIPS_MPRA_MTR5_SHIFT)) & AIPS_MPRA_MTR5_MASK) -#define AIPS_MPRA_MPL4_MASK (0x1000U) -#define AIPS_MPRA_MPL4_SHIFT (12U) -#define AIPS_MPRA_MPL4(x) (((uint32_t)(((uint32_t)(x)) << AIPS_MPRA_MPL4_SHIFT)) & AIPS_MPRA_MPL4_MASK) -#define AIPS_MPRA_MTW4_MASK (0x2000U) -#define AIPS_MPRA_MTW4_SHIFT (13U) -#define AIPS_MPRA_MTW4(x) (((uint32_t)(((uint32_t)(x)) << AIPS_MPRA_MTW4_SHIFT)) & AIPS_MPRA_MTW4_MASK) -#define AIPS_MPRA_MTR4_MASK (0x4000U) -#define AIPS_MPRA_MTR4_SHIFT (14U) -#define AIPS_MPRA_MTR4(x) (((uint32_t)(((uint32_t)(x)) << AIPS_MPRA_MTR4_SHIFT)) & AIPS_MPRA_MTR4_MASK) -#define AIPS_MPRA_MPL3_MASK (0x10000U) -#define AIPS_MPRA_MPL3_SHIFT (16U) -#define AIPS_MPRA_MPL3(x) (((uint32_t)(((uint32_t)(x)) << AIPS_MPRA_MPL3_SHIFT)) & AIPS_MPRA_MPL3_MASK) -#define AIPS_MPRA_MTW3_MASK (0x20000U) -#define AIPS_MPRA_MTW3_SHIFT (17U) -#define AIPS_MPRA_MTW3(x) (((uint32_t)(((uint32_t)(x)) << AIPS_MPRA_MTW3_SHIFT)) & AIPS_MPRA_MTW3_MASK) -#define AIPS_MPRA_MTR3_MASK (0x40000U) -#define AIPS_MPRA_MTR3_SHIFT (18U) -#define AIPS_MPRA_MTR3(x) (((uint32_t)(((uint32_t)(x)) << AIPS_MPRA_MTR3_SHIFT)) & AIPS_MPRA_MTR3_MASK) -#define AIPS_MPRA_MPL2_MASK (0x100000U) -#define AIPS_MPRA_MPL2_SHIFT (20U) -#define AIPS_MPRA_MPL2(x) (((uint32_t)(((uint32_t)(x)) << AIPS_MPRA_MPL2_SHIFT)) & AIPS_MPRA_MPL2_MASK) -#define AIPS_MPRA_MTW2_MASK (0x200000U) -#define AIPS_MPRA_MTW2_SHIFT (21U) -#define AIPS_MPRA_MTW2(x) (((uint32_t)(((uint32_t)(x)) << AIPS_MPRA_MTW2_SHIFT)) & AIPS_MPRA_MTW2_MASK) -#define AIPS_MPRA_MTR2_MASK (0x400000U) -#define AIPS_MPRA_MTR2_SHIFT (22U) -#define AIPS_MPRA_MTR2(x) (((uint32_t)(((uint32_t)(x)) << AIPS_MPRA_MTR2_SHIFT)) & AIPS_MPRA_MTR2_MASK) -#define AIPS_MPRA_MPL1_MASK (0x1000000U) -#define AIPS_MPRA_MPL1_SHIFT (24U) -#define AIPS_MPRA_MPL1(x) (((uint32_t)(((uint32_t)(x)) << AIPS_MPRA_MPL1_SHIFT)) & AIPS_MPRA_MPL1_MASK) -#define AIPS_MPRA_MTW1_MASK (0x2000000U) -#define AIPS_MPRA_MTW1_SHIFT (25U) -#define AIPS_MPRA_MTW1(x) (((uint32_t)(((uint32_t)(x)) << AIPS_MPRA_MTW1_SHIFT)) & AIPS_MPRA_MTW1_MASK) -#define AIPS_MPRA_MTR1_MASK (0x4000000U) -#define AIPS_MPRA_MTR1_SHIFT (26U) -#define AIPS_MPRA_MTR1(x) (((uint32_t)(((uint32_t)(x)) << AIPS_MPRA_MTR1_SHIFT)) & AIPS_MPRA_MTR1_MASK) -#define AIPS_MPRA_MPL0_MASK (0x10000000U) -#define AIPS_MPRA_MPL0_SHIFT (28U) -#define AIPS_MPRA_MPL0(x) (((uint32_t)(((uint32_t)(x)) << AIPS_MPRA_MPL0_SHIFT)) & AIPS_MPRA_MPL0_MASK) -#define AIPS_MPRA_MTW0_MASK (0x20000000U) -#define AIPS_MPRA_MTW0_SHIFT (29U) -#define AIPS_MPRA_MTW0(x) (((uint32_t)(((uint32_t)(x)) << AIPS_MPRA_MTW0_SHIFT)) & AIPS_MPRA_MTW0_MASK) -#define AIPS_MPRA_MTR0_MASK (0x40000000U) -#define AIPS_MPRA_MTR0_SHIFT (30U) -#define AIPS_MPRA_MTR0(x) (((uint32_t)(((uint32_t)(x)) << AIPS_MPRA_MTR0_SHIFT)) & AIPS_MPRA_MTR0_MASK) - -/*! @name PACRA - Peripheral Access Control Register */ -#define AIPS_PACRA_TP7_MASK (0x1U) -#define AIPS_PACRA_TP7_SHIFT (0U) -#define AIPS_PACRA_TP7(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRA_TP7_SHIFT)) & AIPS_PACRA_TP7_MASK) -#define AIPS_PACRA_WP7_MASK (0x2U) -#define AIPS_PACRA_WP7_SHIFT (1U) -#define AIPS_PACRA_WP7(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRA_WP7_SHIFT)) & AIPS_PACRA_WP7_MASK) -#define AIPS_PACRA_SP7_MASK (0x4U) -#define AIPS_PACRA_SP7_SHIFT (2U) -#define AIPS_PACRA_SP7(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRA_SP7_SHIFT)) & AIPS_PACRA_SP7_MASK) -#define AIPS_PACRA_TP6_MASK (0x10U) -#define AIPS_PACRA_TP6_SHIFT (4U) -#define AIPS_PACRA_TP6(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRA_TP6_SHIFT)) & AIPS_PACRA_TP6_MASK) -#define AIPS_PACRA_WP6_MASK (0x20U) -#define AIPS_PACRA_WP6_SHIFT (5U) -#define AIPS_PACRA_WP6(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRA_WP6_SHIFT)) & AIPS_PACRA_WP6_MASK) -#define AIPS_PACRA_SP6_MASK (0x40U) -#define AIPS_PACRA_SP6_SHIFT (6U) -#define AIPS_PACRA_SP6(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRA_SP6_SHIFT)) & AIPS_PACRA_SP6_MASK) -#define AIPS_PACRA_TP5_MASK (0x100U) -#define AIPS_PACRA_TP5_SHIFT (8U) -#define AIPS_PACRA_TP5(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRA_TP5_SHIFT)) & AIPS_PACRA_TP5_MASK) -#define AIPS_PACRA_WP5_MASK (0x200U) -#define AIPS_PACRA_WP5_SHIFT (9U) -#define AIPS_PACRA_WP5(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRA_WP5_SHIFT)) & AIPS_PACRA_WP5_MASK) -#define AIPS_PACRA_SP5_MASK (0x400U) -#define AIPS_PACRA_SP5_SHIFT (10U) -#define AIPS_PACRA_SP5(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRA_SP5_SHIFT)) & AIPS_PACRA_SP5_MASK) -#define AIPS_PACRA_TP4_MASK (0x1000U) -#define AIPS_PACRA_TP4_SHIFT (12U) -#define AIPS_PACRA_TP4(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRA_TP4_SHIFT)) & AIPS_PACRA_TP4_MASK) -#define AIPS_PACRA_WP4_MASK (0x2000U) -#define AIPS_PACRA_WP4_SHIFT (13U) -#define AIPS_PACRA_WP4(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRA_WP4_SHIFT)) & AIPS_PACRA_WP4_MASK) -#define AIPS_PACRA_SP4_MASK (0x4000U) -#define AIPS_PACRA_SP4_SHIFT (14U) -#define AIPS_PACRA_SP4(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRA_SP4_SHIFT)) & AIPS_PACRA_SP4_MASK) -#define AIPS_PACRA_TP3_MASK (0x10000U) -#define AIPS_PACRA_TP3_SHIFT (16U) -#define AIPS_PACRA_TP3(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRA_TP3_SHIFT)) & AIPS_PACRA_TP3_MASK) -#define AIPS_PACRA_WP3_MASK (0x20000U) -#define AIPS_PACRA_WP3_SHIFT (17U) -#define AIPS_PACRA_WP3(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRA_WP3_SHIFT)) & AIPS_PACRA_WP3_MASK) -#define AIPS_PACRA_SP3_MASK (0x40000U) -#define AIPS_PACRA_SP3_SHIFT (18U) -#define AIPS_PACRA_SP3(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRA_SP3_SHIFT)) & AIPS_PACRA_SP3_MASK) -#define AIPS_PACRA_TP2_MASK (0x100000U) -#define AIPS_PACRA_TP2_SHIFT (20U) -#define AIPS_PACRA_TP2(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRA_TP2_SHIFT)) & AIPS_PACRA_TP2_MASK) -#define AIPS_PACRA_WP2_MASK (0x200000U) -#define AIPS_PACRA_WP2_SHIFT (21U) -#define AIPS_PACRA_WP2(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRA_WP2_SHIFT)) & AIPS_PACRA_WP2_MASK) -#define AIPS_PACRA_SP2_MASK (0x400000U) -#define AIPS_PACRA_SP2_SHIFT (22U) -#define AIPS_PACRA_SP2(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRA_SP2_SHIFT)) & AIPS_PACRA_SP2_MASK) -#define AIPS_PACRA_TP1_MASK (0x1000000U) -#define AIPS_PACRA_TP1_SHIFT (24U) -#define AIPS_PACRA_TP1(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRA_TP1_SHIFT)) & AIPS_PACRA_TP1_MASK) -#define AIPS_PACRA_WP1_MASK (0x2000000U) -#define AIPS_PACRA_WP1_SHIFT (25U) -#define AIPS_PACRA_WP1(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRA_WP1_SHIFT)) & AIPS_PACRA_WP1_MASK) -#define AIPS_PACRA_SP1_MASK (0x4000000U) -#define AIPS_PACRA_SP1_SHIFT (26U) -#define AIPS_PACRA_SP1(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRA_SP1_SHIFT)) & AIPS_PACRA_SP1_MASK) -#define AIPS_PACRA_TP0_MASK (0x10000000U) -#define AIPS_PACRA_TP0_SHIFT (28U) -#define AIPS_PACRA_TP0(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRA_TP0_SHIFT)) & AIPS_PACRA_TP0_MASK) -#define AIPS_PACRA_WP0_MASK (0x20000000U) -#define AIPS_PACRA_WP0_SHIFT (29U) -#define AIPS_PACRA_WP0(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRA_WP0_SHIFT)) & AIPS_PACRA_WP0_MASK) -#define AIPS_PACRA_SP0_MASK (0x40000000U) -#define AIPS_PACRA_SP0_SHIFT (30U) -#define AIPS_PACRA_SP0(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRA_SP0_SHIFT)) & AIPS_PACRA_SP0_MASK) - -/*! @name PACRB - Peripheral Access Control Register */ -#define AIPS_PACRB_TP7_MASK (0x1U) -#define AIPS_PACRB_TP7_SHIFT (0U) -#define AIPS_PACRB_TP7(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRB_TP7_SHIFT)) & AIPS_PACRB_TP7_MASK) -#define AIPS_PACRB_WP7_MASK (0x2U) -#define AIPS_PACRB_WP7_SHIFT (1U) -#define AIPS_PACRB_WP7(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRB_WP7_SHIFT)) & AIPS_PACRB_WP7_MASK) -#define AIPS_PACRB_SP7_MASK (0x4U) -#define AIPS_PACRB_SP7_SHIFT (2U) -#define AIPS_PACRB_SP7(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRB_SP7_SHIFT)) & AIPS_PACRB_SP7_MASK) -#define AIPS_PACRB_TP6_MASK (0x10U) -#define AIPS_PACRB_TP6_SHIFT (4U) -#define AIPS_PACRB_TP6(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRB_TP6_SHIFT)) & AIPS_PACRB_TP6_MASK) -#define AIPS_PACRB_WP6_MASK (0x20U) -#define AIPS_PACRB_WP6_SHIFT (5U) -#define AIPS_PACRB_WP6(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRB_WP6_SHIFT)) & AIPS_PACRB_WP6_MASK) -#define AIPS_PACRB_SP6_MASK (0x40U) -#define AIPS_PACRB_SP6_SHIFT (6U) -#define AIPS_PACRB_SP6(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRB_SP6_SHIFT)) & AIPS_PACRB_SP6_MASK) -#define AIPS_PACRB_TP5_MASK (0x100U) -#define AIPS_PACRB_TP5_SHIFT (8U) -#define AIPS_PACRB_TP5(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRB_TP5_SHIFT)) & AIPS_PACRB_TP5_MASK) -#define AIPS_PACRB_WP5_MASK (0x200U) -#define AIPS_PACRB_WP5_SHIFT (9U) -#define AIPS_PACRB_WP5(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRB_WP5_SHIFT)) & AIPS_PACRB_WP5_MASK) -#define AIPS_PACRB_SP5_MASK (0x400U) -#define AIPS_PACRB_SP5_SHIFT (10U) -#define AIPS_PACRB_SP5(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRB_SP5_SHIFT)) & AIPS_PACRB_SP5_MASK) -#define AIPS_PACRB_TP4_MASK (0x1000U) -#define AIPS_PACRB_TP4_SHIFT (12U) -#define AIPS_PACRB_TP4(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRB_TP4_SHIFT)) & AIPS_PACRB_TP4_MASK) -#define AIPS_PACRB_WP4_MASK (0x2000U) -#define AIPS_PACRB_WP4_SHIFT (13U) -#define AIPS_PACRB_WP4(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRB_WP4_SHIFT)) & AIPS_PACRB_WP4_MASK) -#define AIPS_PACRB_SP4_MASK (0x4000U) -#define AIPS_PACRB_SP4_SHIFT (14U) -#define AIPS_PACRB_SP4(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRB_SP4_SHIFT)) & AIPS_PACRB_SP4_MASK) -#define AIPS_PACRB_TP3_MASK (0x10000U) -#define AIPS_PACRB_TP3_SHIFT (16U) -#define AIPS_PACRB_TP3(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRB_TP3_SHIFT)) & AIPS_PACRB_TP3_MASK) -#define AIPS_PACRB_WP3_MASK (0x20000U) -#define AIPS_PACRB_WP3_SHIFT (17U) -#define AIPS_PACRB_WP3(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRB_WP3_SHIFT)) & AIPS_PACRB_WP3_MASK) -#define AIPS_PACRB_SP3_MASK (0x40000U) -#define AIPS_PACRB_SP3_SHIFT (18U) -#define AIPS_PACRB_SP3(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRB_SP3_SHIFT)) & AIPS_PACRB_SP3_MASK) -#define AIPS_PACRB_TP2_MASK (0x100000U) -#define AIPS_PACRB_TP2_SHIFT (20U) -#define AIPS_PACRB_TP2(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRB_TP2_SHIFT)) & AIPS_PACRB_TP2_MASK) -#define AIPS_PACRB_WP2_MASK (0x200000U) -#define AIPS_PACRB_WP2_SHIFT (21U) -#define AIPS_PACRB_WP2(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRB_WP2_SHIFT)) & AIPS_PACRB_WP2_MASK) -#define AIPS_PACRB_SP2_MASK (0x400000U) -#define AIPS_PACRB_SP2_SHIFT (22U) -#define AIPS_PACRB_SP2(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRB_SP2_SHIFT)) & AIPS_PACRB_SP2_MASK) -#define AIPS_PACRB_TP1_MASK (0x1000000U) -#define AIPS_PACRB_TP1_SHIFT (24U) -#define AIPS_PACRB_TP1(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRB_TP1_SHIFT)) & AIPS_PACRB_TP1_MASK) -#define AIPS_PACRB_WP1_MASK (0x2000000U) -#define AIPS_PACRB_WP1_SHIFT (25U) -#define AIPS_PACRB_WP1(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRB_WP1_SHIFT)) & AIPS_PACRB_WP1_MASK) -#define AIPS_PACRB_SP1_MASK (0x4000000U) -#define AIPS_PACRB_SP1_SHIFT (26U) -#define AIPS_PACRB_SP1(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRB_SP1_SHIFT)) & AIPS_PACRB_SP1_MASK) -#define AIPS_PACRB_TP0_MASK (0x10000000U) -#define AIPS_PACRB_TP0_SHIFT (28U) -#define AIPS_PACRB_TP0(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRB_TP0_SHIFT)) & AIPS_PACRB_TP0_MASK) -#define AIPS_PACRB_WP0_MASK (0x20000000U) -#define AIPS_PACRB_WP0_SHIFT (29U) -#define AIPS_PACRB_WP0(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRB_WP0_SHIFT)) & AIPS_PACRB_WP0_MASK) -#define AIPS_PACRB_SP0_MASK (0x40000000U) -#define AIPS_PACRB_SP0_SHIFT (30U) -#define AIPS_PACRB_SP0(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRB_SP0_SHIFT)) & AIPS_PACRB_SP0_MASK) - -/*! @name PACRC - Peripheral Access Control Register */ -#define AIPS_PACRC_TP7_MASK (0x1U) -#define AIPS_PACRC_TP7_SHIFT (0U) -#define AIPS_PACRC_TP7(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRC_TP7_SHIFT)) & AIPS_PACRC_TP7_MASK) -#define AIPS_PACRC_WP7_MASK (0x2U) -#define AIPS_PACRC_WP7_SHIFT (1U) -#define AIPS_PACRC_WP7(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRC_WP7_SHIFT)) & AIPS_PACRC_WP7_MASK) -#define AIPS_PACRC_SP7_MASK (0x4U) -#define AIPS_PACRC_SP7_SHIFT (2U) -#define AIPS_PACRC_SP7(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRC_SP7_SHIFT)) & AIPS_PACRC_SP7_MASK) -#define AIPS_PACRC_TP6_MASK (0x10U) -#define AIPS_PACRC_TP6_SHIFT (4U) -#define AIPS_PACRC_TP6(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRC_TP6_SHIFT)) & AIPS_PACRC_TP6_MASK) -#define AIPS_PACRC_WP6_MASK (0x20U) -#define AIPS_PACRC_WP6_SHIFT (5U) -#define AIPS_PACRC_WP6(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRC_WP6_SHIFT)) & AIPS_PACRC_WP6_MASK) -#define AIPS_PACRC_SP6_MASK (0x40U) -#define AIPS_PACRC_SP6_SHIFT (6U) -#define AIPS_PACRC_SP6(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRC_SP6_SHIFT)) & AIPS_PACRC_SP6_MASK) -#define AIPS_PACRC_TP5_MASK (0x100U) -#define AIPS_PACRC_TP5_SHIFT (8U) -#define AIPS_PACRC_TP5(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRC_TP5_SHIFT)) & AIPS_PACRC_TP5_MASK) -#define AIPS_PACRC_WP5_MASK (0x200U) -#define AIPS_PACRC_WP5_SHIFT (9U) -#define AIPS_PACRC_WP5(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRC_WP5_SHIFT)) & AIPS_PACRC_WP5_MASK) -#define AIPS_PACRC_SP5_MASK (0x400U) -#define AIPS_PACRC_SP5_SHIFT (10U) -#define AIPS_PACRC_SP5(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRC_SP5_SHIFT)) & AIPS_PACRC_SP5_MASK) -#define AIPS_PACRC_TP4_MASK (0x1000U) -#define AIPS_PACRC_TP4_SHIFT (12U) -#define AIPS_PACRC_TP4(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRC_TP4_SHIFT)) & AIPS_PACRC_TP4_MASK) -#define AIPS_PACRC_WP4_MASK (0x2000U) -#define AIPS_PACRC_WP4_SHIFT (13U) -#define AIPS_PACRC_WP4(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRC_WP4_SHIFT)) & AIPS_PACRC_WP4_MASK) -#define AIPS_PACRC_SP4_MASK (0x4000U) -#define AIPS_PACRC_SP4_SHIFT (14U) -#define AIPS_PACRC_SP4(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRC_SP4_SHIFT)) & AIPS_PACRC_SP4_MASK) -#define AIPS_PACRC_TP3_MASK (0x10000U) -#define AIPS_PACRC_TP3_SHIFT (16U) -#define AIPS_PACRC_TP3(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRC_TP3_SHIFT)) & AIPS_PACRC_TP3_MASK) -#define AIPS_PACRC_WP3_MASK (0x20000U) -#define AIPS_PACRC_WP3_SHIFT (17U) -#define AIPS_PACRC_WP3(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRC_WP3_SHIFT)) & AIPS_PACRC_WP3_MASK) -#define AIPS_PACRC_SP3_MASK (0x40000U) -#define AIPS_PACRC_SP3_SHIFT (18U) -#define AIPS_PACRC_SP3(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRC_SP3_SHIFT)) & AIPS_PACRC_SP3_MASK) -#define AIPS_PACRC_TP2_MASK (0x100000U) -#define AIPS_PACRC_TP2_SHIFT (20U) -#define AIPS_PACRC_TP2(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRC_TP2_SHIFT)) & AIPS_PACRC_TP2_MASK) -#define AIPS_PACRC_WP2_MASK (0x200000U) -#define AIPS_PACRC_WP2_SHIFT (21U) -#define AIPS_PACRC_WP2(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRC_WP2_SHIFT)) & AIPS_PACRC_WP2_MASK) -#define AIPS_PACRC_SP2_MASK (0x400000U) -#define AIPS_PACRC_SP2_SHIFT (22U) -#define AIPS_PACRC_SP2(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRC_SP2_SHIFT)) & AIPS_PACRC_SP2_MASK) -#define AIPS_PACRC_TP1_MASK (0x1000000U) -#define AIPS_PACRC_TP1_SHIFT (24U) -#define AIPS_PACRC_TP1(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRC_TP1_SHIFT)) & AIPS_PACRC_TP1_MASK) -#define AIPS_PACRC_WP1_MASK (0x2000000U) -#define AIPS_PACRC_WP1_SHIFT (25U) -#define AIPS_PACRC_WP1(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRC_WP1_SHIFT)) & AIPS_PACRC_WP1_MASK) -#define AIPS_PACRC_SP1_MASK (0x4000000U) -#define AIPS_PACRC_SP1_SHIFT (26U) -#define AIPS_PACRC_SP1(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRC_SP1_SHIFT)) & AIPS_PACRC_SP1_MASK) -#define AIPS_PACRC_TP0_MASK (0x10000000U) -#define AIPS_PACRC_TP0_SHIFT (28U) -#define AIPS_PACRC_TP0(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRC_TP0_SHIFT)) & AIPS_PACRC_TP0_MASK) -#define AIPS_PACRC_WP0_MASK (0x20000000U) -#define AIPS_PACRC_WP0_SHIFT (29U) -#define AIPS_PACRC_WP0(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRC_WP0_SHIFT)) & AIPS_PACRC_WP0_MASK) -#define AIPS_PACRC_SP0_MASK (0x40000000U) -#define AIPS_PACRC_SP0_SHIFT (30U) -#define AIPS_PACRC_SP0(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRC_SP0_SHIFT)) & AIPS_PACRC_SP0_MASK) - -/*! @name PACRD - Peripheral Access Control Register */ -#define AIPS_PACRD_TP7_MASK (0x1U) -#define AIPS_PACRD_TP7_SHIFT (0U) -#define AIPS_PACRD_TP7(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRD_TP7_SHIFT)) & AIPS_PACRD_TP7_MASK) -#define AIPS_PACRD_WP7_MASK (0x2U) -#define AIPS_PACRD_WP7_SHIFT (1U) -#define AIPS_PACRD_WP7(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRD_WP7_SHIFT)) & AIPS_PACRD_WP7_MASK) -#define AIPS_PACRD_SP7_MASK (0x4U) -#define AIPS_PACRD_SP7_SHIFT (2U) -#define AIPS_PACRD_SP7(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRD_SP7_SHIFT)) & AIPS_PACRD_SP7_MASK) -#define AIPS_PACRD_TP6_MASK (0x10U) -#define AIPS_PACRD_TP6_SHIFT (4U) -#define AIPS_PACRD_TP6(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRD_TP6_SHIFT)) & AIPS_PACRD_TP6_MASK) -#define AIPS_PACRD_WP6_MASK (0x20U) -#define AIPS_PACRD_WP6_SHIFT (5U) -#define AIPS_PACRD_WP6(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRD_WP6_SHIFT)) & AIPS_PACRD_WP6_MASK) -#define AIPS_PACRD_SP6_MASK (0x40U) -#define AIPS_PACRD_SP6_SHIFT (6U) -#define AIPS_PACRD_SP6(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRD_SP6_SHIFT)) & AIPS_PACRD_SP6_MASK) -#define AIPS_PACRD_TP5_MASK (0x100U) -#define AIPS_PACRD_TP5_SHIFT (8U) -#define AIPS_PACRD_TP5(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRD_TP5_SHIFT)) & AIPS_PACRD_TP5_MASK) -#define AIPS_PACRD_WP5_MASK (0x200U) -#define AIPS_PACRD_WP5_SHIFT (9U) -#define AIPS_PACRD_WP5(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRD_WP5_SHIFT)) & AIPS_PACRD_WP5_MASK) -#define AIPS_PACRD_SP5_MASK (0x400U) -#define AIPS_PACRD_SP5_SHIFT (10U) -#define AIPS_PACRD_SP5(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRD_SP5_SHIFT)) & AIPS_PACRD_SP5_MASK) -#define AIPS_PACRD_TP4_MASK (0x1000U) -#define AIPS_PACRD_TP4_SHIFT (12U) -#define AIPS_PACRD_TP4(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRD_TP4_SHIFT)) & AIPS_PACRD_TP4_MASK) -#define AIPS_PACRD_WP4_MASK (0x2000U) -#define AIPS_PACRD_WP4_SHIFT (13U) -#define AIPS_PACRD_WP4(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRD_WP4_SHIFT)) & AIPS_PACRD_WP4_MASK) -#define AIPS_PACRD_SP4_MASK (0x4000U) -#define AIPS_PACRD_SP4_SHIFT (14U) -#define AIPS_PACRD_SP4(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRD_SP4_SHIFT)) & AIPS_PACRD_SP4_MASK) -#define AIPS_PACRD_TP3_MASK (0x10000U) -#define AIPS_PACRD_TP3_SHIFT (16U) -#define AIPS_PACRD_TP3(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRD_TP3_SHIFT)) & AIPS_PACRD_TP3_MASK) -#define AIPS_PACRD_WP3_MASK (0x20000U) -#define AIPS_PACRD_WP3_SHIFT (17U) -#define AIPS_PACRD_WP3(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRD_WP3_SHIFT)) & AIPS_PACRD_WP3_MASK) -#define AIPS_PACRD_SP3_MASK (0x40000U) -#define AIPS_PACRD_SP3_SHIFT (18U) -#define AIPS_PACRD_SP3(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRD_SP3_SHIFT)) & AIPS_PACRD_SP3_MASK) -#define AIPS_PACRD_TP2_MASK (0x100000U) -#define AIPS_PACRD_TP2_SHIFT (20U) -#define AIPS_PACRD_TP2(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRD_TP2_SHIFT)) & AIPS_PACRD_TP2_MASK) -#define AIPS_PACRD_WP2_MASK (0x200000U) -#define AIPS_PACRD_WP2_SHIFT (21U) -#define AIPS_PACRD_WP2(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRD_WP2_SHIFT)) & AIPS_PACRD_WP2_MASK) -#define AIPS_PACRD_SP2_MASK (0x400000U) -#define AIPS_PACRD_SP2_SHIFT (22U) -#define AIPS_PACRD_SP2(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRD_SP2_SHIFT)) & AIPS_PACRD_SP2_MASK) -#define AIPS_PACRD_TP1_MASK (0x1000000U) -#define AIPS_PACRD_TP1_SHIFT (24U) -#define AIPS_PACRD_TP1(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRD_TP1_SHIFT)) & AIPS_PACRD_TP1_MASK) -#define AIPS_PACRD_WP1_MASK (0x2000000U) -#define AIPS_PACRD_WP1_SHIFT (25U) -#define AIPS_PACRD_WP1(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRD_WP1_SHIFT)) & AIPS_PACRD_WP1_MASK) -#define AIPS_PACRD_SP1_MASK (0x4000000U) -#define AIPS_PACRD_SP1_SHIFT (26U) -#define AIPS_PACRD_SP1(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRD_SP1_SHIFT)) & AIPS_PACRD_SP1_MASK) -#define AIPS_PACRD_TP0_MASK (0x10000000U) -#define AIPS_PACRD_TP0_SHIFT (28U) -#define AIPS_PACRD_TP0(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRD_TP0_SHIFT)) & AIPS_PACRD_TP0_MASK) -#define AIPS_PACRD_WP0_MASK (0x20000000U) -#define AIPS_PACRD_WP0_SHIFT (29U) -#define AIPS_PACRD_WP0(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRD_WP0_SHIFT)) & AIPS_PACRD_WP0_MASK) -#define AIPS_PACRD_SP0_MASK (0x40000000U) -#define AIPS_PACRD_SP0_SHIFT (30U) -#define AIPS_PACRD_SP0(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRD_SP0_SHIFT)) & AIPS_PACRD_SP0_MASK) - -/*! @name PACRE - Peripheral Access Control Register */ -#define AIPS_PACRE_TP7_MASK (0x1U) -#define AIPS_PACRE_TP7_SHIFT (0U) -#define AIPS_PACRE_TP7(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRE_TP7_SHIFT)) & AIPS_PACRE_TP7_MASK) -#define AIPS_PACRE_WP7_MASK (0x2U) -#define AIPS_PACRE_WP7_SHIFT (1U) -#define AIPS_PACRE_WP7(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRE_WP7_SHIFT)) & AIPS_PACRE_WP7_MASK) -#define AIPS_PACRE_SP7_MASK (0x4U) -#define AIPS_PACRE_SP7_SHIFT (2U) -#define AIPS_PACRE_SP7(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRE_SP7_SHIFT)) & AIPS_PACRE_SP7_MASK) -#define AIPS_PACRE_TP6_MASK (0x10U) -#define AIPS_PACRE_TP6_SHIFT (4U) -#define AIPS_PACRE_TP6(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRE_TP6_SHIFT)) & AIPS_PACRE_TP6_MASK) -#define AIPS_PACRE_WP6_MASK (0x20U) -#define AIPS_PACRE_WP6_SHIFT (5U) -#define AIPS_PACRE_WP6(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRE_WP6_SHIFT)) & AIPS_PACRE_WP6_MASK) -#define AIPS_PACRE_SP6_MASK (0x40U) -#define AIPS_PACRE_SP6_SHIFT (6U) -#define AIPS_PACRE_SP6(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRE_SP6_SHIFT)) & AIPS_PACRE_SP6_MASK) -#define AIPS_PACRE_TP5_MASK (0x100U) -#define AIPS_PACRE_TP5_SHIFT (8U) -#define AIPS_PACRE_TP5(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRE_TP5_SHIFT)) & AIPS_PACRE_TP5_MASK) -#define AIPS_PACRE_WP5_MASK (0x200U) -#define AIPS_PACRE_WP5_SHIFT (9U) -#define AIPS_PACRE_WP5(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRE_WP5_SHIFT)) & AIPS_PACRE_WP5_MASK) -#define AIPS_PACRE_SP5_MASK (0x400U) -#define AIPS_PACRE_SP5_SHIFT (10U) -#define AIPS_PACRE_SP5(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRE_SP5_SHIFT)) & AIPS_PACRE_SP5_MASK) -#define AIPS_PACRE_TP4_MASK (0x1000U) -#define AIPS_PACRE_TP4_SHIFT (12U) -#define AIPS_PACRE_TP4(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRE_TP4_SHIFT)) & AIPS_PACRE_TP4_MASK) -#define AIPS_PACRE_WP4_MASK (0x2000U) -#define AIPS_PACRE_WP4_SHIFT (13U) -#define AIPS_PACRE_WP4(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRE_WP4_SHIFT)) & AIPS_PACRE_WP4_MASK) -#define AIPS_PACRE_SP4_MASK (0x4000U) -#define AIPS_PACRE_SP4_SHIFT (14U) -#define AIPS_PACRE_SP4(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRE_SP4_SHIFT)) & AIPS_PACRE_SP4_MASK) -#define AIPS_PACRE_TP3_MASK (0x10000U) -#define AIPS_PACRE_TP3_SHIFT (16U) -#define AIPS_PACRE_TP3(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRE_TP3_SHIFT)) & AIPS_PACRE_TP3_MASK) -#define AIPS_PACRE_WP3_MASK (0x20000U) -#define AIPS_PACRE_WP3_SHIFT (17U) -#define AIPS_PACRE_WP3(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRE_WP3_SHIFT)) & AIPS_PACRE_WP3_MASK) -#define AIPS_PACRE_SP3_MASK (0x40000U) -#define AIPS_PACRE_SP3_SHIFT (18U) -#define AIPS_PACRE_SP3(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRE_SP3_SHIFT)) & AIPS_PACRE_SP3_MASK) -#define AIPS_PACRE_TP2_MASK (0x100000U) -#define AIPS_PACRE_TP2_SHIFT (20U) -#define AIPS_PACRE_TP2(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRE_TP2_SHIFT)) & AIPS_PACRE_TP2_MASK) -#define AIPS_PACRE_WP2_MASK (0x200000U) -#define AIPS_PACRE_WP2_SHIFT (21U) -#define AIPS_PACRE_WP2(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRE_WP2_SHIFT)) & AIPS_PACRE_WP2_MASK) -#define AIPS_PACRE_SP2_MASK (0x400000U) -#define AIPS_PACRE_SP2_SHIFT (22U) -#define AIPS_PACRE_SP2(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRE_SP2_SHIFT)) & AIPS_PACRE_SP2_MASK) -#define AIPS_PACRE_TP1_MASK (0x1000000U) -#define AIPS_PACRE_TP1_SHIFT (24U) -#define AIPS_PACRE_TP1(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRE_TP1_SHIFT)) & AIPS_PACRE_TP1_MASK) -#define AIPS_PACRE_WP1_MASK (0x2000000U) -#define AIPS_PACRE_WP1_SHIFT (25U) -#define AIPS_PACRE_WP1(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRE_WP1_SHIFT)) & AIPS_PACRE_WP1_MASK) -#define AIPS_PACRE_SP1_MASK (0x4000000U) -#define AIPS_PACRE_SP1_SHIFT (26U) -#define AIPS_PACRE_SP1(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRE_SP1_SHIFT)) & AIPS_PACRE_SP1_MASK) -#define AIPS_PACRE_TP0_MASK (0x10000000U) -#define AIPS_PACRE_TP0_SHIFT (28U) -#define AIPS_PACRE_TP0(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRE_TP0_SHIFT)) & AIPS_PACRE_TP0_MASK) -#define AIPS_PACRE_WP0_MASK (0x20000000U) -#define AIPS_PACRE_WP0_SHIFT (29U) -#define AIPS_PACRE_WP0(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRE_WP0_SHIFT)) & AIPS_PACRE_WP0_MASK) -#define AIPS_PACRE_SP0_MASK (0x40000000U) -#define AIPS_PACRE_SP0_SHIFT (30U) -#define AIPS_PACRE_SP0(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRE_SP0_SHIFT)) & AIPS_PACRE_SP0_MASK) - -/*! @name PACRF - Peripheral Access Control Register */ -#define AIPS_PACRF_TP7_MASK (0x1U) -#define AIPS_PACRF_TP7_SHIFT (0U) -#define AIPS_PACRF_TP7(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRF_TP7_SHIFT)) & AIPS_PACRF_TP7_MASK) -#define AIPS_PACRF_WP7_MASK (0x2U) -#define AIPS_PACRF_WP7_SHIFT (1U) -#define AIPS_PACRF_WP7(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRF_WP7_SHIFT)) & AIPS_PACRF_WP7_MASK) -#define AIPS_PACRF_SP7_MASK (0x4U) -#define AIPS_PACRF_SP7_SHIFT (2U) -#define AIPS_PACRF_SP7(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRF_SP7_SHIFT)) & AIPS_PACRF_SP7_MASK) -#define AIPS_PACRF_TP6_MASK (0x10U) -#define AIPS_PACRF_TP6_SHIFT (4U) -#define AIPS_PACRF_TP6(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRF_TP6_SHIFT)) & AIPS_PACRF_TP6_MASK) -#define AIPS_PACRF_WP6_MASK (0x20U) -#define AIPS_PACRF_WP6_SHIFT (5U) -#define AIPS_PACRF_WP6(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRF_WP6_SHIFT)) & AIPS_PACRF_WP6_MASK) -#define AIPS_PACRF_SP6_MASK (0x40U) -#define AIPS_PACRF_SP6_SHIFT (6U) -#define AIPS_PACRF_SP6(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRF_SP6_SHIFT)) & AIPS_PACRF_SP6_MASK) -#define AIPS_PACRF_TP5_MASK (0x100U) -#define AIPS_PACRF_TP5_SHIFT (8U) -#define AIPS_PACRF_TP5(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRF_TP5_SHIFT)) & AIPS_PACRF_TP5_MASK) -#define AIPS_PACRF_WP5_MASK (0x200U) -#define AIPS_PACRF_WP5_SHIFT (9U) -#define AIPS_PACRF_WP5(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRF_WP5_SHIFT)) & AIPS_PACRF_WP5_MASK) -#define AIPS_PACRF_SP5_MASK (0x400U) -#define AIPS_PACRF_SP5_SHIFT (10U) -#define AIPS_PACRF_SP5(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRF_SP5_SHIFT)) & AIPS_PACRF_SP5_MASK) -#define AIPS_PACRF_TP4_MASK (0x1000U) -#define AIPS_PACRF_TP4_SHIFT (12U) -#define AIPS_PACRF_TP4(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRF_TP4_SHIFT)) & AIPS_PACRF_TP4_MASK) -#define AIPS_PACRF_WP4_MASK (0x2000U) -#define AIPS_PACRF_WP4_SHIFT (13U) -#define AIPS_PACRF_WP4(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRF_WP4_SHIFT)) & AIPS_PACRF_WP4_MASK) -#define AIPS_PACRF_SP4_MASK (0x4000U) -#define AIPS_PACRF_SP4_SHIFT (14U) -#define AIPS_PACRF_SP4(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRF_SP4_SHIFT)) & AIPS_PACRF_SP4_MASK) -#define AIPS_PACRF_TP3_MASK (0x10000U) -#define AIPS_PACRF_TP3_SHIFT (16U) -#define AIPS_PACRF_TP3(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRF_TP3_SHIFT)) & AIPS_PACRF_TP3_MASK) -#define AIPS_PACRF_WP3_MASK (0x20000U) -#define AIPS_PACRF_WP3_SHIFT (17U) -#define AIPS_PACRF_WP3(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRF_WP3_SHIFT)) & AIPS_PACRF_WP3_MASK) -#define AIPS_PACRF_SP3_MASK (0x40000U) -#define AIPS_PACRF_SP3_SHIFT (18U) -#define AIPS_PACRF_SP3(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRF_SP3_SHIFT)) & AIPS_PACRF_SP3_MASK) -#define AIPS_PACRF_TP2_MASK (0x100000U) -#define AIPS_PACRF_TP2_SHIFT (20U) -#define AIPS_PACRF_TP2(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRF_TP2_SHIFT)) & AIPS_PACRF_TP2_MASK) -#define AIPS_PACRF_WP2_MASK (0x200000U) -#define AIPS_PACRF_WP2_SHIFT (21U) -#define AIPS_PACRF_WP2(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRF_WP2_SHIFT)) & AIPS_PACRF_WP2_MASK) -#define AIPS_PACRF_SP2_MASK (0x400000U) -#define AIPS_PACRF_SP2_SHIFT (22U) -#define AIPS_PACRF_SP2(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRF_SP2_SHIFT)) & AIPS_PACRF_SP2_MASK) -#define AIPS_PACRF_TP1_MASK (0x1000000U) -#define AIPS_PACRF_TP1_SHIFT (24U) -#define AIPS_PACRF_TP1(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRF_TP1_SHIFT)) & AIPS_PACRF_TP1_MASK) -#define AIPS_PACRF_WP1_MASK (0x2000000U) -#define AIPS_PACRF_WP1_SHIFT (25U) -#define AIPS_PACRF_WP1(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRF_WP1_SHIFT)) & AIPS_PACRF_WP1_MASK) -#define AIPS_PACRF_SP1_MASK (0x4000000U) -#define AIPS_PACRF_SP1_SHIFT (26U) -#define AIPS_PACRF_SP1(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRF_SP1_SHIFT)) & AIPS_PACRF_SP1_MASK) -#define AIPS_PACRF_TP0_MASK (0x10000000U) -#define AIPS_PACRF_TP0_SHIFT (28U) -#define AIPS_PACRF_TP0(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRF_TP0_SHIFT)) & AIPS_PACRF_TP0_MASK) -#define AIPS_PACRF_WP0_MASK (0x20000000U) -#define AIPS_PACRF_WP0_SHIFT (29U) -#define AIPS_PACRF_WP0(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRF_WP0_SHIFT)) & AIPS_PACRF_WP0_MASK) -#define AIPS_PACRF_SP0_MASK (0x40000000U) -#define AIPS_PACRF_SP0_SHIFT (30U) -#define AIPS_PACRF_SP0(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRF_SP0_SHIFT)) & AIPS_PACRF_SP0_MASK) - -/*! @name PACRG - Peripheral Access Control Register */ -#define AIPS_PACRG_TP7_MASK (0x1U) -#define AIPS_PACRG_TP7_SHIFT (0U) -#define AIPS_PACRG_TP7(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRG_TP7_SHIFT)) & AIPS_PACRG_TP7_MASK) -#define AIPS_PACRG_WP7_MASK (0x2U) -#define AIPS_PACRG_WP7_SHIFT (1U) -#define AIPS_PACRG_WP7(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRG_WP7_SHIFT)) & AIPS_PACRG_WP7_MASK) -#define AIPS_PACRG_SP7_MASK (0x4U) -#define AIPS_PACRG_SP7_SHIFT (2U) -#define AIPS_PACRG_SP7(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRG_SP7_SHIFT)) & AIPS_PACRG_SP7_MASK) -#define AIPS_PACRG_TP6_MASK (0x10U) -#define AIPS_PACRG_TP6_SHIFT (4U) -#define AIPS_PACRG_TP6(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRG_TP6_SHIFT)) & AIPS_PACRG_TP6_MASK) -#define AIPS_PACRG_WP6_MASK (0x20U) -#define AIPS_PACRG_WP6_SHIFT (5U) -#define AIPS_PACRG_WP6(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRG_WP6_SHIFT)) & AIPS_PACRG_WP6_MASK) -#define AIPS_PACRG_SP6_MASK (0x40U) -#define AIPS_PACRG_SP6_SHIFT (6U) -#define AIPS_PACRG_SP6(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRG_SP6_SHIFT)) & AIPS_PACRG_SP6_MASK) -#define AIPS_PACRG_TP5_MASK (0x100U) -#define AIPS_PACRG_TP5_SHIFT (8U) -#define AIPS_PACRG_TP5(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRG_TP5_SHIFT)) & AIPS_PACRG_TP5_MASK) -#define AIPS_PACRG_WP5_MASK (0x200U) -#define AIPS_PACRG_WP5_SHIFT (9U) -#define AIPS_PACRG_WP5(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRG_WP5_SHIFT)) & AIPS_PACRG_WP5_MASK) -#define AIPS_PACRG_SP5_MASK (0x400U) -#define AIPS_PACRG_SP5_SHIFT (10U) -#define AIPS_PACRG_SP5(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRG_SP5_SHIFT)) & AIPS_PACRG_SP5_MASK) -#define AIPS_PACRG_TP4_MASK (0x1000U) -#define AIPS_PACRG_TP4_SHIFT (12U) -#define AIPS_PACRG_TP4(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRG_TP4_SHIFT)) & AIPS_PACRG_TP4_MASK) -#define AIPS_PACRG_WP4_MASK (0x2000U) -#define AIPS_PACRG_WP4_SHIFT (13U) -#define AIPS_PACRG_WP4(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRG_WP4_SHIFT)) & AIPS_PACRG_WP4_MASK) -#define AIPS_PACRG_SP4_MASK (0x4000U) -#define AIPS_PACRG_SP4_SHIFT (14U) -#define AIPS_PACRG_SP4(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRG_SP4_SHIFT)) & AIPS_PACRG_SP4_MASK) -#define AIPS_PACRG_TP3_MASK (0x10000U) -#define AIPS_PACRG_TP3_SHIFT (16U) -#define AIPS_PACRG_TP3(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRG_TP3_SHIFT)) & AIPS_PACRG_TP3_MASK) -#define AIPS_PACRG_WP3_MASK (0x20000U) -#define AIPS_PACRG_WP3_SHIFT (17U) -#define AIPS_PACRG_WP3(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRG_WP3_SHIFT)) & AIPS_PACRG_WP3_MASK) -#define AIPS_PACRG_SP3_MASK (0x40000U) -#define AIPS_PACRG_SP3_SHIFT (18U) -#define AIPS_PACRG_SP3(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRG_SP3_SHIFT)) & AIPS_PACRG_SP3_MASK) -#define AIPS_PACRG_TP2_MASK (0x100000U) -#define AIPS_PACRG_TP2_SHIFT (20U) -#define AIPS_PACRG_TP2(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRG_TP2_SHIFT)) & AIPS_PACRG_TP2_MASK) -#define AIPS_PACRG_WP2_MASK (0x200000U) -#define AIPS_PACRG_WP2_SHIFT (21U) -#define AIPS_PACRG_WP2(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRG_WP2_SHIFT)) & AIPS_PACRG_WP2_MASK) -#define AIPS_PACRG_SP2_MASK (0x400000U) -#define AIPS_PACRG_SP2_SHIFT (22U) -#define AIPS_PACRG_SP2(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRG_SP2_SHIFT)) & AIPS_PACRG_SP2_MASK) -#define AIPS_PACRG_TP1_MASK (0x1000000U) -#define AIPS_PACRG_TP1_SHIFT (24U) -#define AIPS_PACRG_TP1(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRG_TP1_SHIFT)) & AIPS_PACRG_TP1_MASK) -#define AIPS_PACRG_WP1_MASK (0x2000000U) -#define AIPS_PACRG_WP1_SHIFT (25U) -#define AIPS_PACRG_WP1(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRG_WP1_SHIFT)) & AIPS_PACRG_WP1_MASK) -#define AIPS_PACRG_SP1_MASK (0x4000000U) -#define AIPS_PACRG_SP1_SHIFT (26U) -#define AIPS_PACRG_SP1(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRG_SP1_SHIFT)) & AIPS_PACRG_SP1_MASK) -#define AIPS_PACRG_TP0_MASK (0x10000000U) -#define AIPS_PACRG_TP0_SHIFT (28U) -#define AIPS_PACRG_TP0(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRG_TP0_SHIFT)) & AIPS_PACRG_TP0_MASK) -#define AIPS_PACRG_WP0_MASK (0x20000000U) -#define AIPS_PACRG_WP0_SHIFT (29U) -#define AIPS_PACRG_WP0(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRG_WP0_SHIFT)) & AIPS_PACRG_WP0_MASK) -#define AIPS_PACRG_SP0_MASK (0x40000000U) -#define AIPS_PACRG_SP0_SHIFT (30U) -#define AIPS_PACRG_SP0(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRG_SP0_SHIFT)) & AIPS_PACRG_SP0_MASK) - -/*! @name PACRH - Peripheral Access Control Register */ -#define AIPS_PACRH_TP7_MASK (0x1U) -#define AIPS_PACRH_TP7_SHIFT (0U) -#define AIPS_PACRH_TP7(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRH_TP7_SHIFT)) & AIPS_PACRH_TP7_MASK) -#define AIPS_PACRH_WP7_MASK (0x2U) -#define AIPS_PACRH_WP7_SHIFT (1U) -#define AIPS_PACRH_WP7(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRH_WP7_SHIFT)) & AIPS_PACRH_WP7_MASK) -#define AIPS_PACRH_SP7_MASK (0x4U) -#define AIPS_PACRH_SP7_SHIFT (2U) -#define AIPS_PACRH_SP7(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRH_SP7_SHIFT)) & AIPS_PACRH_SP7_MASK) -#define AIPS_PACRH_TP6_MASK (0x10U) -#define AIPS_PACRH_TP6_SHIFT (4U) -#define AIPS_PACRH_TP6(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRH_TP6_SHIFT)) & AIPS_PACRH_TP6_MASK) -#define AIPS_PACRH_WP6_MASK (0x20U) -#define AIPS_PACRH_WP6_SHIFT (5U) -#define AIPS_PACRH_WP6(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRH_WP6_SHIFT)) & AIPS_PACRH_WP6_MASK) -#define AIPS_PACRH_SP6_MASK (0x40U) -#define AIPS_PACRH_SP6_SHIFT (6U) -#define AIPS_PACRH_SP6(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRH_SP6_SHIFT)) & AIPS_PACRH_SP6_MASK) -#define AIPS_PACRH_TP5_MASK (0x100U) -#define AIPS_PACRH_TP5_SHIFT (8U) -#define AIPS_PACRH_TP5(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRH_TP5_SHIFT)) & AIPS_PACRH_TP5_MASK) -#define AIPS_PACRH_WP5_MASK (0x200U) -#define AIPS_PACRH_WP5_SHIFT (9U) -#define AIPS_PACRH_WP5(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRH_WP5_SHIFT)) & AIPS_PACRH_WP5_MASK) -#define AIPS_PACRH_SP5_MASK (0x400U) -#define AIPS_PACRH_SP5_SHIFT (10U) -#define AIPS_PACRH_SP5(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRH_SP5_SHIFT)) & AIPS_PACRH_SP5_MASK) -#define AIPS_PACRH_TP4_MASK (0x1000U) -#define AIPS_PACRH_TP4_SHIFT (12U) -#define AIPS_PACRH_TP4(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRH_TP4_SHIFT)) & AIPS_PACRH_TP4_MASK) -#define AIPS_PACRH_WP4_MASK (0x2000U) -#define AIPS_PACRH_WP4_SHIFT (13U) -#define AIPS_PACRH_WP4(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRH_WP4_SHIFT)) & AIPS_PACRH_WP4_MASK) -#define AIPS_PACRH_SP4_MASK (0x4000U) -#define AIPS_PACRH_SP4_SHIFT (14U) -#define AIPS_PACRH_SP4(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRH_SP4_SHIFT)) & AIPS_PACRH_SP4_MASK) -#define AIPS_PACRH_TP3_MASK (0x10000U) -#define AIPS_PACRH_TP3_SHIFT (16U) -#define AIPS_PACRH_TP3(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRH_TP3_SHIFT)) & AIPS_PACRH_TP3_MASK) -#define AIPS_PACRH_WP3_MASK (0x20000U) -#define AIPS_PACRH_WP3_SHIFT (17U) -#define AIPS_PACRH_WP3(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRH_WP3_SHIFT)) & AIPS_PACRH_WP3_MASK) -#define AIPS_PACRH_SP3_MASK (0x40000U) -#define AIPS_PACRH_SP3_SHIFT (18U) -#define AIPS_PACRH_SP3(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRH_SP3_SHIFT)) & AIPS_PACRH_SP3_MASK) -#define AIPS_PACRH_TP2_MASK (0x100000U) -#define AIPS_PACRH_TP2_SHIFT (20U) -#define AIPS_PACRH_TP2(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRH_TP2_SHIFT)) & AIPS_PACRH_TP2_MASK) -#define AIPS_PACRH_WP2_MASK (0x200000U) -#define AIPS_PACRH_WP2_SHIFT (21U) -#define AIPS_PACRH_WP2(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRH_WP2_SHIFT)) & AIPS_PACRH_WP2_MASK) -#define AIPS_PACRH_SP2_MASK (0x400000U) -#define AIPS_PACRH_SP2_SHIFT (22U) -#define AIPS_PACRH_SP2(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRH_SP2_SHIFT)) & AIPS_PACRH_SP2_MASK) -#define AIPS_PACRH_TP1_MASK (0x1000000U) -#define AIPS_PACRH_TP1_SHIFT (24U) -#define AIPS_PACRH_TP1(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRH_TP1_SHIFT)) & AIPS_PACRH_TP1_MASK) -#define AIPS_PACRH_WP1_MASK (0x2000000U) -#define AIPS_PACRH_WP1_SHIFT (25U) -#define AIPS_PACRH_WP1(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRH_WP1_SHIFT)) & AIPS_PACRH_WP1_MASK) -#define AIPS_PACRH_SP1_MASK (0x4000000U) -#define AIPS_PACRH_SP1_SHIFT (26U) -#define AIPS_PACRH_SP1(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRH_SP1_SHIFT)) & AIPS_PACRH_SP1_MASK) -#define AIPS_PACRH_TP0_MASK (0x10000000U) -#define AIPS_PACRH_TP0_SHIFT (28U) -#define AIPS_PACRH_TP0(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRH_TP0_SHIFT)) & AIPS_PACRH_TP0_MASK) -#define AIPS_PACRH_WP0_MASK (0x20000000U) -#define AIPS_PACRH_WP0_SHIFT (29U) -#define AIPS_PACRH_WP0(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRH_WP0_SHIFT)) & AIPS_PACRH_WP0_MASK) -#define AIPS_PACRH_SP0_MASK (0x40000000U) -#define AIPS_PACRH_SP0_SHIFT (30U) -#define AIPS_PACRH_SP0(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRH_SP0_SHIFT)) & AIPS_PACRH_SP0_MASK) - -/*! @name PACRI - Peripheral Access Control Register */ -#define AIPS_PACRI_TP7_MASK (0x1U) -#define AIPS_PACRI_TP7_SHIFT (0U) -#define AIPS_PACRI_TP7(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRI_TP7_SHIFT)) & AIPS_PACRI_TP7_MASK) -#define AIPS_PACRI_WP7_MASK (0x2U) -#define AIPS_PACRI_WP7_SHIFT (1U) -#define AIPS_PACRI_WP7(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRI_WP7_SHIFT)) & AIPS_PACRI_WP7_MASK) -#define AIPS_PACRI_SP7_MASK (0x4U) -#define AIPS_PACRI_SP7_SHIFT (2U) -#define AIPS_PACRI_SP7(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRI_SP7_SHIFT)) & AIPS_PACRI_SP7_MASK) -#define AIPS_PACRI_TP6_MASK (0x10U) -#define AIPS_PACRI_TP6_SHIFT (4U) -#define AIPS_PACRI_TP6(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRI_TP6_SHIFT)) & AIPS_PACRI_TP6_MASK) -#define AIPS_PACRI_WP6_MASK (0x20U) -#define AIPS_PACRI_WP6_SHIFT (5U) -#define AIPS_PACRI_WP6(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRI_WP6_SHIFT)) & AIPS_PACRI_WP6_MASK) -#define AIPS_PACRI_SP6_MASK (0x40U) -#define AIPS_PACRI_SP6_SHIFT (6U) -#define AIPS_PACRI_SP6(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRI_SP6_SHIFT)) & AIPS_PACRI_SP6_MASK) -#define AIPS_PACRI_TP5_MASK (0x100U) -#define AIPS_PACRI_TP5_SHIFT (8U) -#define AIPS_PACRI_TP5(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRI_TP5_SHIFT)) & AIPS_PACRI_TP5_MASK) -#define AIPS_PACRI_WP5_MASK (0x200U) -#define AIPS_PACRI_WP5_SHIFT (9U) -#define AIPS_PACRI_WP5(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRI_WP5_SHIFT)) & AIPS_PACRI_WP5_MASK) -#define AIPS_PACRI_SP5_MASK (0x400U) -#define AIPS_PACRI_SP5_SHIFT (10U) -#define AIPS_PACRI_SP5(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRI_SP5_SHIFT)) & AIPS_PACRI_SP5_MASK) -#define AIPS_PACRI_TP4_MASK (0x1000U) -#define AIPS_PACRI_TP4_SHIFT (12U) -#define AIPS_PACRI_TP4(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRI_TP4_SHIFT)) & AIPS_PACRI_TP4_MASK) -#define AIPS_PACRI_WP4_MASK (0x2000U) -#define AIPS_PACRI_WP4_SHIFT (13U) -#define AIPS_PACRI_WP4(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRI_WP4_SHIFT)) & AIPS_PACRI_WP4_MASK) -#define AIPS_PACRI_SP4_MASK (0x4000U) -#define AIPS_PACRI_SP4_SHIFT (14U) -#define AIPS_PACRI_SP4(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRI_SP4_SHIFT)) & AIPS_PACRI_SP4_MASK) -#define AIPS_PACRI_TP3_MASK (0x10000U) -#define AIPS_PACRI_TP3_SHIFT (16U) -#define AIPS_PACRI_TP3(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRI_TP3_SHIFT)) & AIPS_PACRI_TP3_MASK) -#define AIPS_PACRI_WP3_MASK (0x20000U) -#define AIPS_PACRI_WP3_SHIFT (17U) -#define AIPS_PACRI_WP3(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRI_WP3_SHIFT)) & AIPS_PACRI_WP3_MASK) -#define AIPS_PACRI_SP3_MASK (0x40000U) -#define AIPS_PACRI_SP3_SHIFT (18U) -#define AIPS_PACRI_SP3(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRI_SP3_SHIFT)) & AIPS_PACRI_SP3_MASK) -#define AIPS_PACRI_TP2_MASK (0x100000U) -#define AIPS_PACRI_TP2_SHIFT (20U) -#define AIPS_PACRI_TP2(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRI_TP2_SHIFT)) & AIPS_PACRI_TP2_MASK) -#define AIPS_PACRI_WP2_MASK (0x200000U) -#define AIPS_PACRI_WP2_SHIFT (21U) -#define AIPS_PACRI_WP2(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRI_WP2_SHIFT)) & AIPS_PACRI_WP2_MASK) -#define AIPS_PACRI_SP2_MASK (0x400000U) -#define AIPS_PACRI_SP2_SHIFT (22U) -#define AIPS_PACRI_SP2(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRI_SP2_SHIFT)) & AIPS_PACRI_SP2_MASK) -#define AIPS_PACRI_TP1_MASK (0x1000000U) -#define AIPS_PACRI_TP1_SHIFT (24U) -#define AIPS_PACRI_TP1(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRI_TP1_SHIFT)) & AIPS_PACRI_TP1_MASK) -#define AIPS_PACRI_WP1_MASK (0x2000000U) -#define AIPS_PACRI_WP1_SHIFT (25U) -#define AIPS_PACRI_WP1(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRI_WP1_SHIFT)) & AIPS_PACRI_WP1_MASK) -#define AIPS_PACRI_SP1_MASK (0x4000000U) -#define AIPS_PACRI_SP1_SHIFT (26U) -#define AIPS_PACRI_SP1(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRI_SP1_SHIFT)) & AIPS_PACRI_SP1_MASK) -#define AIPS_PACRI_TP0_MASK (0x10000000U) -#define AIPS_PACRI_TP0_SHIFT (28U) -#define AIPS_PACRI_TP0(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRI_TP0_SHIFT)) & AIPS_PACRI_TP0_MASK) -#define AIPS_PACRI_WP0_MASK (0x20000000U) -#define AIPS_PACRI_WP0_SHIFT (29U) -#define AIPS_PACRI_WP0(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRI_WP0_SHIFT)) & AIPS_PACRI_WP0_MASK) -#define AIPS_PACRI_SP0_MASK (0x40000000U) -#define AIPS_PACRI_SP0_SHIFT (30U) -#define AIPS_PACRI_SP0(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRI_SP0_SHIFT)) & AIPS_PACRI_SP0_MASK) - -/*! @name PACRJ - Peripheral Access Control Register */ -#define AIPS_PACRJ_TP7_MASK (0x1U) -#define AIPS_PACRJ_TP7_SHIFT (0U) -#define AIPS_PACRJ_TP7(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRJ_TP7_SHIFT)) & AIPS_PACRJ_TP7_MASK) -#define AIPS_PACRJ_WP7_MASK (0x2U) -#define AIPS_PACRJ_WP7_SHIFT (1U) -#define AIPS_PACRJ_WP7(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRJ_WP7_SHIFT)) & AIPS_PACRJ_WP7_MASK) -#define AIPS_PACRJ_SP7_MASK (0x4U) -#define AIPS_PACRJ_SP7_SHIFT (2U) -#define AIPS_PACRJ_SP7(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRJ_SP7_SHIFT)) & AIPS_PACRJ_SP7_MASK) -#define AIPS_PACRJ_TP6_MASK (0x10U) -#define AIPS_PACRJ_TP6_SHIFT (4U) -#define AIPS_PACRJ_TP6(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRJ_TP6_SHIFT)) & AIPS_PACRJ_TP6_MASK) -#define AIPS_PACRJ_WP6_MASK (0x20U) -#define AIPS_PACRJ_WP6_SHIFT (5U) -#define AIPS_PACRJ_WP6(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRJ_WP6_SHIFT)) & AIPS_PACRJ_WP6_MASK) -#define AIPS_PACRJ_SP6_MASK (0x40U) -#define AIPS_PACRJ_SP6_SHIFT (6U) -#define AIPS_PACRJ_SP6(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRJ_SP6_SHIFT)) & AIPS_PACRJ_SP6_MASK) -#define AIPS_PACRJ_TP5_MASK (0x100U) -#define AIPS_PACRJ_TP5_SHIFT (8U) -#define AIPS_PACRJ_TP5(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRJ_TP5_SHIFT)) & AIPS_PACRJ_TP5_MASK) -#define AIPS_PACRJ_WP5_MASK (0x200U) -#define AIPS_PACRJ_WP5_SHIFT (9U) -#define AIPS_PACRJ_WP5(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRJ_WP5_SHIFT)) & AIPS_PACRJ_WP5_MASK) -#define AIPS_PACRJ_SP5_MASK (0x400U) -#define AIPS_PACRJ_SP5_SHIFT (10U) -#define AIPS_PACRJ_SP5(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRJ_SP5_SHIFT)) & AIPS_PACRJ_SP5_MASK) -#define AIPS_PACRJ_TP4_MASK (0x1000U) -#define AIPS_PACRJ_TP4_SHIFT (12U) -#define AIPS_PACRJ_TP4(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRJ_TP4_SHIFT)) & AIPS_PACRJ_TP4_MASK) -#define AIPS_PACRJ_WP4_MASK (0x2000U) -#define AIPS_PACRJ_WP4_SHIFT (13U) -#define AIPS_PACRJ_WP4(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRJ_WP4_SHIFT)) & AIPS_PACRJ_WP4_MASK) -#define AIPS_PACRJ_SP4_MASK (0x4000U) -#define AIPS_PACRJ_SP4_SHIFT (14U) -#define AIPS_PACRJ_SP4(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRJ_SP4_SHIFT)) & AIPS_PACRJ_SP4_MASK) -#define AIPS_PACRJ_TP3_MASK (0x10000U) -#define AIPS_PACRJ_TP3_SHIFT (16U) -#define AIPS_PACRJ_TP3(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRJ_TP3_SHIFT)) & AIPS_PACRJ_TP3_MASK) -#define AIPS_PACRJ_WP3_MASK (0x20000U) -#define AIPS_PACRJ_WP3_SHIFT (17U) -#define AIPS_PACRJ_WP3(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRJ_WP3_SHIFT)) & AIPS_PACRJ_WP3_MASK) -#define AIPS_PACRJ_SP3_MASK (0x40000U) -#define AIPS_PACRJ_SP3_SHIFT (18U) -#define AIPS_PACRJ_SP3(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRJ_SP3_SHIFT)) & AIPS_PACRJ_SP3_MASK) -#define AIPS_PACRJ_TP2_MASK (0x100000U) -#define AIPS_PACRJ_TP2_SHIFT (20U) -#define AIPS_PACRJ_TP2(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRJ_TP2_SHIFT)) & AIPS_PACRJ_TP2_MASK) -#define AIPS_PACRJ_WP2_MASK (0x200000U) -#define AIPS_PACRJ_WP2_SHIFT (21U) -#define AIPS_PACRJ_WP2(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRJ_WP2_SHIFT)) & AIPS_PACRJ_WP2_MASK) -#define AIPS_PACRJ_SP2_MASK (0x400000U) -#define AIPS_PACRJ_SP2_SHIFT (22U) -#define AIPS_PACRJ_SP2(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRJ_SP2_SHIFT)) & AIPS_PACRJ_SP2_MASK) -#define AIPS_PACRJ_TP1_MASK (0x1000000U) -#define AIPS_PACRJ_TP1_SHIFT (24U) -#define AIPS_PACRJ_TP1(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRJ_TP1_SHIFT)) & AIPS_PACRJ_TP1_MASK) -#define AIPS_PACRJ_WP1_MASK (0x2000000U) -#define AIPS_PACRJ_WP1_SHIFT (25U) -#define AIPS_PACRJ_WP1(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRJ_WP1_SHIFT)) & AIPS_PACRJ_WP1_MASK) -#define AIPS_PACRJ_SP1_MASK (0x4000000U) -#define AIPS_PACRJ_SP1_SHIFT (26U) -#define AIPS_PACRJ_SP1(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRJ_SP1_SHIFT)) & AIPS_PACRJ_SP1_MASK) -#define AIPS_PACRJ_TP0_MASK (0x10000000U) -#define AIPS_PACRJ_TP0_SHIFT (28U) -#define AIPS_PACRJ_TP0(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRJ_TP0_SHIFT)) & AIPS_PACRJ_TP0_MASK) -#define AIPS_PACRJ_WP0_MASK (0x20000000U) -#define AIPS_PACRJ_WP0_SHIFT (29U) -#define AIPS_PACRJ_WP0(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRJ_WP0_SHIFT)) & AIPS_PACRJ_WP0_MASK) -#define AIPS_PACRJ_SP0_MASK (0x40000000U) -#define AIPS_PACRJ_SP0_SHIFT (30U) -#define AIPS_PACRJ_SP0(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRJ_SP0_SHIFT)) & AIPS_PACRJ_SP0_MASK) - -/*! @name PACRK - Peripheral Access Control Register */ -#define AIPS_PACRK_TP7_MASK (0x1U) -#define AIPS_PACRK_TP7_SHIFT (0U) -#define AIPS_PACRK_TP7(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRK_TP7_SHIFT)) & AIPS_PACRK_TP7_MASK) -#define AIPS_PACRK_WP7_MASK (0x2U) -#define AIPS_PACRK_WP7_SHIFT (1U) -#define AIPS_PACRK_WP7(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRK_WP7_SHIFT)) & AIPS_PACRK_WP7_MASK) -#define AIPS_PACRK_SP7_MASK (0x4U) -#define AIPS_PACRK_SP7_SHIFT (2U) -#define AIPS_PACRK_SP7(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRK_SP7_SHIFT)) & AIPS_PACRK_SP7_MASK) -#define AIPS_PACRK_TP6_MASK (0x10U) -#define AIPS_PACRK_TP6_SHIFT (4U) -#define AIPS_PACRK_TP6(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRK_TP6_SHIFT)) & AIPS_PACRK_TP6_MASK) -#define AIPS_PACRK_WP6_MASK (0x20U) -#define AIPS_PACRK_WP6_SHIFT (5U) -#define AIPS_PACRK_WP6(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRK_WP6_SHIFT)) & AIPS_PACRK_WP6_MASK) -#define AIPS_PACRK_SP6_MASK (0x40U) -#define AIPS_PACRK_SP6_SHIFT (6U) -#define AIPS_PACRK_SP6(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRK_SP6_SHIFT)) & AIPS_PACRK_SP6_MASK) -#define AIPS_PACRK_TP5_MASK (0x100U) -#define AIPS_PACRK_TP5_SHIFT (8U) -#define AIPS_PACRK_TP5(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRK_TP5_SHIFT)) & AIPS_PACRK_TP5_MASK) -#define AIPS_PACRK_WP5_MASK (0x200U) -#define AIPS_PACRK_WP5_SHIFT (9U) -#define AIPS_PACRK_WP5(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRK_WP5_SHIFT)) & AIPS_PACRK_WP5_MASK) -#define AIPS_PACRK_SP5_MASK (0x400U) -#define AIPS_PACRK_SP5_SHIFT (10U) -#define AIPS_PACRK_SP5(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRK_SP5_SHIFT)) & AIPS_PACRK_SP5_MASK) -#define AIPS_PACRK_TP4_MASK (0x1000U) -#define AIPS_PACRK_TP4_SHIFT (12U) -#define AIPS_PACRK_TP4(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRK_TP4_SHIFT)) & AIPS_PACRK_TP4_MASK) -#define AIPS_PACRK_WP4_MASK (0x2000U) -#define AIPS_PACRK_WP4_SHIFT (13U) -#define AIPS_PACRK_WP4(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRK_WP4_SHIFT)) & AIPS_PACRK_WP4_MASK) -#define AIPS_PACRK_SP4_MASK (0x4000U) -#define AIPS_PACRK_SP4_SHIFT (14U) -#define AIPS_PACRK_SP4(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRK_SP4_SHIFT)) & AIPS_PACRK_SP4_MASK) -#define AIPS_PACRK_TP3_MASK (0x10000U) -#define AIPS_PACRK_TP3_SHIFT (16U) -#define AIPS_PACRK_TP3(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRK_TP3_SHIFT)) & AIPS_PACRK_TP3_MASK) -#define AIPS_PACRK_WP3_MASK (0x20000U) -#define AIPS_PACRK_WP3_SHIFT (17U) -#define AIPS_PACRK_WP3(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRK_WP3_SHIFT)) & AIPS_PACRK_WP3_MASK) -#define AIPS_PACRK_SP3_MASK (0x40000U) -#define AIPS_PACRK_SP3_SHIFT (18U) -#define AIPS_PACRK_SP3(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRK_SP3_SHIFT)) & AIPS_PACRK_SP3_MASK) -#define AIPS_PACRK_TP2_MASK (0x100000U) -#define AIPS_PACRK_TP2_SHIFT (20U) -#define AIPS_PACRK_TP2(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRK_TP2_SHIFT)) & AIPS_PACRK_TP2_MASK) -#define AIPS_PACRK_WP2_MASK (0x200000U) -#define AIPS_PACRK_WP2_SHIFT (21U) -#define AIPS_PACRK_WP2(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRK_WP2_SHIFT)) & AIPS_PACRK_WP2_MASK) -#define AIPS_PACRK_SP2_MASK (0x400000U) -#define AIPS_PACRK_SP2_SHIFT (22U) -#define AIPS_PACRK_SP2(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRK_SP2_SHIFT)) & AIPS_PACRK_SP2_MASK) -#define AIPS_PACRK_TP1_MASK (0x1000000U) -#define AIPS_PACRK_TP1_SHIFT (24U) -#define AIPS_PACRK_TP1(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRK_TP1_SHIFT)) & AIPS_PACRK_TP1_MASK) -#define AIPS_PACRK_WP1_MASK (0x2000000U) -#define AIPS_PACRK_WP1_SHIFT (25U) -#define AIPS_PACRK_WP1(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRK_WP1_SHIFT)) & AIPS_PACRK_WP1_MASK) -#define AIPS_PACRK_SP1_MASK (0x4000000U) -#define AIPS_PACRK_SP1_SHIFT (26U) -#define AIPS_PACRK_SP1(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRK_SP1_SHIFT)) & AIPS_PACRK_SP1_MASK) -#define AIPS_PACRK_TP0_MASK (0x10000000U) -#define AIPS_PACRK_TP0_SHIFT (28U) -#define AIPS_PACRK_TP0(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRK_TP0_SHIFT)) & AIPS_PACRK_TP0_MASK) -#define AIPS_PACRK_WP0_MASK (0x20000000U) -#define AIPS_PACRK_WP0_SHIFT (29U) -#define AIPS_PACRK_WP0(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRK_WP0_SHIFT)) & AIPS_PACRK_WP0_MASK) -#define AIPS_PACRK_SP0_MASK (0x40000000U) -#define AIPS_PACRK_SP0_SHIFT (30U) -#define AIPS_PACRK_SP0(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRK_SP0_SHIFT)) & AIPS_PACRK_SP0_MASK) - -/*! @name PACRL - Peripheral Access Control Register */ -#define AIPS_PACRL_TP7_MASK (0x1U) -#define AIPS_PACRL_TP7_SHIFT (0U) -#define AIPS_PACRL_TP7(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRL_TP7_SHIFT)) & AIPS_PACRL_TP7_MASK) -#define AIPS_PACRL_WP7_MASK (0x2U) -#define AIPS_PACRL_WP7_SHIFT (1U) -#define AIPS_PACRL_WP7(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRL_WP7_SHIFT)) & AIPS_PACRL_WP7_MASK) -#define AIPS_PACRL_SP7_MASK (0x4U) -#define AIPS_PACRL_SP7_SHIFT (2U) -#define AIPS_PACRL_SP7(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRL_SP7_SHIFT)) & AIPS_PACRL_SP7_MASK) -#define AIPS_PACRL_TP6_MASK (0x10U) -#define AIPS_PACRL_TP6_SHIFT (4U) -#define AIPS_PACRL_TP6(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRL_TP6_SHIFT)) & AIPS_PACRL_TP6_MASK) -#define AIPS_PACRL_WP6_MASK (0x20U) -#define AIPS_PACRL_WP6_SHIFT (5U) -#define AIPS_PACRL_WP6(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRL_WP6_SHIFT)) & AIPS_PACRL_WP6_MASK) -#define AIPS_PACRL_SP6_MASK (0x40U) -#define AIPS_PACRL_SP6_SHIFT (6U) -#define AIPS_PACRL_SP6(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRL_SP6_SHIFT)) & AIPS_PACRL_SP6_MASK) -#define AIPS_PACRL_TP5_MASK (0x100U) -#define AIPS_PACRL_TP5_SHIFT (8U) -#define AIPS_PACRL_TP5(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRL_TP5_SHIFT)) & AIPS_PACRL_TP5_MASK) -#define AIPS_PACRL_WP5_MASK (0x200U) -#define AIPS_PACRL_WP5_SHIFT (9U) -#define AIPS_PACRL_WP5(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRL_WP5_SHIFT)) & AIPS_PACRL_WP5_MASK) -#define AIPS_PACRL_SP5_MASK (0x400U) -#define AIPS_PACRL_SP5_SHIFT (10U) -#define AIPS_PACRL_SP5(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRL_SP5_SHIFT)) & AIPS_PACRL_SP5_MASK) -#define AIPS_PACRL_TP4_MASK (0x1000U) -#define AIPS_PACRL_TP4_SHIFT (12U) -#define AIPS_PACRL_TP4(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRL_TP4_SHIFT)) & AIPS_PACRL_TP4_MASK) -#define AIPS_PACRL_WP4_MASK (0x2000U) -#define AIPS_PACRL_WP4_SHIFT (13U) -#define AIPS_PACRL_WP4(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRL_WP4_SHIFT)) & AIPS_PACRL_WP4_MASK) -#define AIPS_PACRL_SP4_MASK (0x4000U) -#define AIPS_PACRL_SP4_SHIFT (14U) -#define AIPS_PACRL_SP4(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRL_SP4_SHIFT)) & AIPS_PACRL_SP4_MASK) -#define AIPS_PACRL_TP3_MASK (0x10000U) -#define AIPS_PACRL_TP3_SHIFT (16U) -#define AIPS_PACRL_TP3(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRL_TP3_SHIFT)) & AIPS_PACRL_TP3_MASK) -#define AIPS_PACRL_WP3_MASK (0x20000U) -#define AIPS_PACRL_WP3_SHIFT (17U) -#define AIPS_PACRL_WP3(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRL_WP3_SHIFT)) & AIPS_PACRL_WP3_MASK) -#define AIPS_PACRL_SP3_MASK (0x40000U) -#define AIPS_PACRL_SP3_SHIFT (18U) -#define AIPS_PACRL_SP3(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRL_SP3_SHIFT)) & AIPS_PACRL_SP3_MASK) -#define AIPS_PACRL_TP2_MASK (0x100000U) -#define AIPS_PACRL_TP2_SHIFT (20U) -#define AIPS_PACRL_TP2(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRL_TP2_SHIFT)) & AIPS_PACRL_TP2_MASK) -#define AIPS_PACRL_WP2_MASK (0x200000U) -#define AIPS_PACRL_WP2_SHIFT (21U) -#define AIPS_PACRL_WP2(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRL_WP2_SHIFT)) & AIPS_PACRL_WP2_MASK) -#define AIPS_PACRL_SP2_MASK (0x400000U) -#define AIPS_PACRL_SP2_SHIFT (22U) -#define AIPS_PACRL_SP2(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRL_SP2_SHIFT)) & AIPS_PACRL_SP2_MASK) -#define AIPS_PACRL_TP1_MASK (0x1000000U) -#define AIPS_PACRL_TP1_SHIFT (24U) -#define AIPS_PACRL_TP1(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRL_TP1_SHIFT)) & AIPS_PACRL_TP1_MASK) -#define AIPS_PACRL_WP1_MASK (0x2000000U) -#define AIPS_PACRL_WP1_SHIFT (25U) -#define AIPS_PACRL_WP1(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRL_WP1_SHIFT)) & AIPS_PACRL_WP1_MASK) -#define AIPS_PACRL_SP1_MASK (0x4000000U) -#define AIPS_PACRL_SP1_SHIFT (26U) -#define AIPS_PACRL_SP1(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRL_SP1_SHIFT)) & AIPS_PACRL_SP1_MASK) -#define AIPS_PACRL_TP0_MASK (0x10000000U) -#define AIPS_PACRL_TP0_SHIFT (28U) -#define AIPS_PACRL_TP0(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRL_TP0_SHIFT)) & AIPS_PACRL_TP0_MASK) -#define AIPS_PACRL_WP0_MASK (0x20000000U) -#define AIPS_PACRL_WP0_SHIFT (29U) -#define AIPS_PACRL_WP0(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRL_WP0_SHIFT)) & AIPS_PACRL_WP0_MASK) -#define AIPS_PACRL_SP0_MASK (0x40000000U) -#define AIPS_PACRL_SP0_SHIFT (30U) -#define AIPS_PACRL_SP0(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRL_SP0_SHIFT)) & AIPS_PACRL_SP0_MASK) - -/*! @name PACRM - Peripheral Access Control Register */ -#define AIPS_PACRM_TP7_MASK (0x1U) -#define AIPS_PACRM_TP7_SHIFT (0U) -#define AIPS_PACRM_TP7(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRM_TP7_SHIFT)) & AIPS_PACRM_TP7_MASK) -#define AIPS_PACRM_WP7_MASK (0x2U) -#define AIPS_PACRM_WP7_SHIFT (1U) -#define AIPS_PACRM_WP7(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRM_WP7_SHIFT)) & AIPS_PACRM_WP7_MASK) -#define AIPS_PACRM_SP7_MASK (0x4U) -#define AIPS_PACRM_SP7_SHIFT (2U) -#define AIPS_PACRM_SP7(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRM_SP7_SHIFT)) & AIPS_PACRM_SP7_MASK) -#define AIPS_PACRM_TP6_MASK (0x10U) -#define AIPS_PACRM_TP6_SHIFT (4U) -#define AIPS_PACRM_TP6(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRM_TP6_SHIFT)) & AIPS_PACRM_TP6_MASK) -#define AIPS_PACRM_WP6_MASK (0x20U) -#define AIPS_PACRM_WP6_SHIFT (5U) -#define AIPS_PACRM_WP6(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRM_WP6_SHIFT)) & AIPS_PACRM_WP6_MASK) -#define AIPS_PACRM_SP6_MASK (0x40U) -#define AIPS_PACRM_SP6_SHIFT (6U) -#define AIPS_PACRM_SP6(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRM_SP6_SHIFT)) & AIPS_PACRM_SP6_MASK) -#define AIPS_PACRM_TP5_MASK (0x100U) -#define AIPS_PACRM_TP5_SHIFT (8U) -#define AIPS_PACRM_TP5(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRM_TP5_SHIFT)) & AIPS_PACRM_TP5_MASK) -#define AIPS_PACRM_WP5_MASK (0x200U) -#define AIPS_PACRM_WP5_SHIFT (9U) -#define AIPS_PACRM_WP5(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRM_WP5_SHIFT)) & AIPS_PACRM_WP5_MASK) -#define AIPS_PACRM_SP5_MASK (0x400U) -#define AIPS_PACRM_SP5_SHIFT (10U) -#define AIPS_PACRM_SP5(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRM_SP5_SHIFT)) & AIPS_PACRM_SP5_MASK) -#define AIPS_PACRM_TP4_MASK (0x1000U) -#define AIPS_PACRM_TP4_SHIFT (12U) -#define AIPS_PACRM_TP4(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRM_TP4_SHIFT)) & AIPS_PACRM_TP4_MASK) -#define AIPS_PACRM_WP4_MASK (0x2000U) -#define AIPS_PACRM_WP4_SHIFT (13U) -#define AIPS_PACRM_WP4(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRM_WP4_SHIFT)) & AIPS_PACRM_WP4_MASK) -#define AIPS_PACRM_SP4_MASK (0x4000U) -#define AIPS_PACRM_SP4_SHIFT (14U) -#define AIPS_PACRM_SP4(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRM_SP4_SHIFT)) & AIPS_PACRM_SP4_MASK) -#define AIPS_PACRM_TP3_MASK (0x10000U) -#define AIPS_PACRM_TP3_SHIFT (16U) -#define AIPS_PACRM_TP3(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRM_TP3_SHIFT)) & AIPS_PACRM_TP3_MASK) -#define AIPS_PACRM_WP3_MASK (0x20000U) -#define AIPS_PACRM_WP3_SHIFT (17U) -#define AIPS_PACRM_WP3(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRM_WP3_SHIFT)) & AIPS_PACRM_WP3_MASK) -#define AIPS_PACRM_SP3_MASK (0x40000U) -#define AIPS_PACRM_SP3_SHIFT (18U) -#define AIPS_PACRM_SP3(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRM_SP3_SHIFT)) & AIPS_PACRM_SP3_MASK) -#define AIPS_PACRM_TP2_MASK (0x100000U) -#define AIPS_PACRM_TP2_SHIFT (20U) -#define AIPS_PACRM_TP2(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRM_TP2_SHIFT)) & AIPS_PACRM_TP2_MASK) -#define AIPS_PACRM_WP2_MASK (0x200000U) -#define AIPS_PACRM_WP2_SHIFT (21U) -#define AIPS_PACRM_WP2(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRM_WP2_SHIFT)) & AIPS_PACRM_WP2_MASK) -#define AIPS_PACRM_SP2_MASK (0x400000U) -#define AIPS_PACRM_SP2_SHIFT (22U) -#define AIPS_PACRM_SP2(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRM_SP2_SHIFT)) & AIPS_PACRM_SP2_MASK) -#define AIPS_PACRM_TP1_MASK (0x1000000U) -#define AIPS_PACRM_TP1_SHIFT (24U) -#define AIPS_PACRM_TP1(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRM_TP1_SHIFT)) & AIPS_PACRM_TP1_MASK) -#define AIPS_PACRM_WP1_MASK (0x2000000U) -#define AIPS_PACRM_WP1_SHIFT (25U) -#define AIPS_PACRM_WP1(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRM_WP1_SHIFT)) & AIPS_PACRM_WP1_MASK) -#define AIPS_PACRM_SP1_MASK (0x4000000U) -#define AIPS_PACRM_SP1_SHIFT (26U) -#define AIPS_PACRM_SP1(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRM_SP1_SHIFT)) & AIPS_PACRM_SP1_MASK) -#define AIPS_PACRM_TP0_MASK (0x10000000U) -#define AIPS_PACRM_TP0_SHIFT (28U) -#define AIPS_PACRM_TP0(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRM_TP0_SHIFT)) & AIPS_PACRM_TP0_MASK) -#define AIPS_PACRM_WP0_MASK (0x20000000U) -#define AIPS_PACRM_WP0_SHIFT (29U) -#define AIPS_PACRM_WP0(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRM_WP0_SHIFT)) & AIPS_PACRM_WP0_MASK) -#define AIPS_PACRM_SP0_MASK (0x40000000U) -#define AIPS_PACRM_SP0_SHIFT (30U) -#define AIPS_PACRM_SP0(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRM_SP0_SHIFT)) & AIPS_PACRM_SP0_MASK) - -/*! @name PACRN - Peripheral Access Control Register */ -#define AIPS_PACRN_TP7_MASK (0x1U) -#define AIPS_PACRN_TP7_SHIFT (0U) -#define AIPS_PACRN_TP7(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRN_TP7_SHIFT)) & AIPS_PACRN_TP7_MASK) -#define AIPS_PACRN_WP7_MASK (0x2U) -#define AIPS_PACRN_WP7_SHIFT (1U) -#define AIPS_PACRN_WP7(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRN_WP7_SHIFT)) & AIPS_PACRN_WP7_MASK) -#define AIPS_PACRN_SP7_MASK (0x4U) -#define AIPS_PACRN_SP7_SHIFT (2U) -#define AIPS_PACRN_SP7(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRN_SP7_SHIFT)) & AIPS_PACRN_SP7_MASK) -#define AIPS_PACRN_TP6_MASK (0x10U) -#define AIPS_PACRN_TP6_SHIFT (4U) -#define AIPS_PACRN_TP6(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRN_TP6_SHIFT)) & AIPS_PACRN_TP6_MASK) -#define AIPS_PACRN_WP6_MASK (0x20U) -#define AIPS_PACRN_WP6_SHIFT (5U) -#define AIPS_PACRN_WP6(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRN_WP6_SHIFT)) & AIPS_PACRN_WP6_MASK) -#define AIPS_PACRN_SP6_MASK (0x40U) -#define AIPS_PACRN_SP6_SHIFT (6U) -#define AIPS_PACRN_SP6(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRN_SP6_SHIFT)) & AIPS_PACRN_SP6_MASK) -#define AIPS_PACRN_TP5_MASK (0x100U) -#define AIPS_PACRN_TP5_SHIFT (8U) -#define AIPS_PACRN_TP5(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRN_TP5_SHIFT)) & AIPS_PACRN_TP5_MASK) -#define AIPS_PACRN_WP5_MASK (0x200U) -#define AIPS_PACRN_WP5_SHIFT (9U) -#define AIPS_PACRN_WP5(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRN_WP5_SHIFT)) & AIPS_PACRN_WP5_MASK) -#define AIPS_PACRN_SP5_MASK (0x400U) -#define AIPS_PACRN_SP5_SHIFT (10U) -#define AIPS_PACRN_SP5(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRN_SP5_SHIFT)) & AIPS_PACRN_SP5_MASK) -#define AIPS_PACRN_TP4_MASK (0x1000U) -#define AIPS_PACRN_TP4_SHIFT (12U) -#define AIPS_PACRN_TP4(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRN_TP4_SHIFT)) & AIPS_PACRN_TP4_MASK) -#define AIPS_PACRN_WP4_MASK (0x2000U) -#define AIPS_PACRN_WP4_SHIFT (13U) -#define AIPS_PACRN_WP4(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRN_WP4_SHIFT)) & AIPS_PACRN_WP4_MASK) -#define AIPS_PACRN_SP4_MASK (0x4000U) -#define AIPS_PACRN_SP4_SHIFT (14U) -#define AIPS_PACRN_SP4(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRN_SP4_SHIFT)) & AIPS_PACRN_SP4_MASK) -#define AIPS_PACRN_TP3_MASK (0x10000U) -#define AIPS_PACRN_TP3_SHIFT (16U) -#define AIPS_PACRN_TP3(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRN_TP3_SHIFT)) & AIPS_PACRN_TP3_MASK) -#define AIPS_PACRN_WP3_MASK (0x20000U) -#define AIPS_PACRN_WP3_SHIFT (17U) -#define AIPS_PACRN_WP3(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRN_WP3_SHIFT)) & AIPS_PACRN_WP3_MASK) -#define AIPS_PACRN_SP3_MASK (0x40000U) -#define AIPS_PACRN_SP3_SHIFT (18U) -#define AIPS_PACRN_SP3(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRN_SP3_SHIFT)) & AIPS_PACRN_SP3_MASK) -#define AIPS_PACRN_TP2_MASK (0x100000U) -#define AIPS_PACRN_TP2_SHIFT (20U) -#define AIPS_PACRN_TP2(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRN_TP2_SHIFT)) & AIPS_PACRN_TP2_MASK) -#define AIPS_PACRN_WP2_MASK (0x200000U) -#define AIPS_PACRN_WP2_SHIFT (21U) -#define AIPS_PACRN_WP2(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRN_WP2_SHIFT)) & AIPS_PACRN_WP2_MASK) -#define AIPS_PACRN_SP2_MASK (0x400000U) -#define AIPS_PACRN_SP2_SHIFT (22U) -#define AIPS_PACRN_SP2(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRN_SP2_SHIFT)) & AIPS_PACRN_SP2_MASK) -#define AIPS_PACRN_TP1_MASK (0x1000000U) -#define AIPS_PACRN_TP1_SHIFT (24U) -#define AIPS_PACRN_TP1(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRN_TP1_SHIFT)) & AIPS_PACRN_TP1_MASK) -#define AIPS_PACRN_WP1_MASK (0x2000000U) -#define AIPS_PACRN_WP1_SHIFT (25U) -#define AIPS_PACRN_WP1(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRN_WP1_SHIFT)) & AIPS_PACRN_WP1_MASK) -#define AIPS_PACRN_SP1_MASK (0x4000000U) -#define AIPS_PACRN_SP1_SHIFT (26U) -#define AIPS_PACRN_SP1(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRN_SP1_SHIFT)) & AIPS_PACRN_SP1_MASK) -#define AIPS_PACRN_TP0_MASK (0x10000000U) -#define AIPS_PACRN_TP0_SHIFT (28U) -#define AIPS_PACRN_TP0(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRN_TP0_SHIFT)) & AIPS_PACRN_TP0_MASK) -#define AIPS_PACRN_WP0_MASK (0x20000000U) -#define AIPS_PACRN_WP0_SHIFT (29U) -#define AIPS_PACRN_WP0(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRN_WP0_SHIFT)) & AIPS_PACRN_WP0_MASK) -#define AIPS_PACRN_SP0_MASK (0x40000000U) -#define AIPS_PACRN_SP0_SHIFT (30U) -#define AIPS_PACRN_SP0(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRN_SP0_SHIFT)) & AIPS_PACRN_SP0_MASK) - -/*! @name PACRO - Peripheral Access Control Register */ -#define AIPS_PACRO_TP7_MASK (0x1U) -#define AIPS_PACRO_TP7_SHIFT (0U) -#define AIPS_PACRO_TP7(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRO_TP7_SHIFT)) & AIPS_PACRO_TP7_MASK) -#define AIPS_PACRO_WP7_MASK (0x2U) -#define AIPS_PACRO_WP7_SHIFT (1U) -#define AIPS_PACRO_WP7(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRO_WP7_SHIFT)) & AIPS_PACRO_WP7_MASK) -#define AIPS_PACRO_SP7_MASK (0x4U) -#define AIPS_PACRO_SP7_SHIFT (2U) -#define AIPS_PACRO_SP7(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRO_SP7_SHIFT)) & AIPS_PACRO_SP7_MASK) -#define AIPS_PACRO_TP6_MASK (0x10U) -#define AIPS_PACRO_TP6_SHIFT (4U) -#define AIPS_PACRO_TP6(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRO_TP6_SHIFT)) & AIPS_PACRO_TP6_MASK) -#define AIPS_PACRO_WP6_MASK (0x20U) -#define AIPS_PACRO_WP6_SHIFT (5U) -#define AIPS_PACRO_WP6(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRO_WP6_SHIFT)) & AIPS_PACRO_WP6_MASK) -#define AIPS_PACRO_SP6_MASK (0x40U) -#define AIPS_PACRO_SP6_SHIFT (6U) -#define AIPS_PACRO_SP6(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRO_SP6_SHIFT)) & AIPS_PACRO_SP6_MASK) -#define AIPS_PACRO_TP5_MASK (0x100U) -#define AIPS_PACRO_TP5_SHIFT (8U) -#define AIPS_PACRO_TP5(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRO_TP5_SHIFT)) & AIPS_PACRO_TP5_MASK) -#define AIPS_PACRO_WP5_MASK (0x200U) -#define AIPS_PACRO_WP5_SHIFT (9U) -#define AIPS_PACRO_WP5(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRO_WP5_SHIFT)) & AIPS_PACRO_WP5_MASK) -#define AIPS_PACRO_SP5_MASK (0x400U) -#define AIPS_PACRO_SP5_SHIFT (10U) -#define AIPS_PACRO_SP5(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRO_SP5_SHIFT)) & AIPS_PACRO_SP5_MASK) -#define AIPS_PACRO_TP4_MASK (0x1000U) -#define AIPS_PACRO_TP4_SHIFT (12U) -#define AIPS_PACRO_TP4(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRO_TP4_SHIFT)) & AIPS_PACRO_TP4_MASK) -#define AIPS_PACRO_WP4_MASK (0x2000U) -#define AIPS_PACRO_WP4_SHIFT (13U) -#define AIPS_PACRO_WP4(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRO_WP4_SHIFT)) & AIPS_PACRO_WP4_MASK) -#define AIPS_PACRO_SP4_MASK (0x4000U) -#define AIPS_PACRO_SP4_SHIFT (14U) -#define AIPS_PACRO_SP4(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRO_SP4_SHIFT)) & AIPS_PACRO_SP4_MASK) -#define AIPS_PACRO_TP3_MASK (0x10000U) -#define AIPS_PACRO_TP3_SHIFT (16U) -#define AIPS_PACRO_TP3(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRO_TP3_SHIFT)) & AIPS_PACRO_TP3_MASK) -#define AIPS_PACRO_WP3_MASK (0x20000U) -#define AIPS_PACRO_WP3_SHIFT (17U) -#define AIPS_PACRO_WP3(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRO_WP3_SHIFT)) & AIPS_PACRO_WP3_MASK) -#define AIPS_PACRO_SP3_MASK (0x40000U) -#define AIPS_PACRO_SP3_SHIFT (18U) -#define AIPS_PACRO_SP3(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRO_SP3_SHIFT)) & AIPS_PACRO_SP3_MASK) -#define AIPS_PACRO_TP2_MASK (0x100000U) -#define AIPS_PACRO_TP2_SHIFT (20U) -#define AIPS_PACRO_TP2(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRO_TP2_SHIFT)) & AIPS_PACRO_TP2_MASK) -#define AIPS_PACRO_WP2_MASK (0x200000U) -#define AIPS_PACRO_WP2_SHIFT (21U) -#define AIPS_PACRO_WP2(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRO_WP2_SHIFT)) & AIPS_PACRO_WP2_MASK) -#define AIPS_PACRO_SP2_MASK (0x400000U) -#define AIPS_PACRO_SP2_SHIFT (22U) -#define AIPS_PACRO_SP2(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRO_SP2_SHIFT)) & AIPS_PACRO_SP2_MASK) -#define AIPS_PACRO_TP1_MASK (0x1000000U) -#define AIPS_PACRO_TP1_SHIFT (24U) -#define AIPS_PACRO_TP1(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRO_TP1_SHIFT)) & AIPS_PACRO_TP1_MASK) -#define AIPS_PACRO_WP1_MASK (0x2000000U) -#define AIPS_PACRO_WP1_SHIFT (25U) -#define AIPS_PACRO_WP1(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRO_WP1_SHIFT)) & AIPS_PACRO_WP1_MASK) -#define AIPS_PACRO_SP1_MASK (0x4000000U) -#define AIPS_PACRO_SP1_SHIFT (26U) -#define AIPS_PACRO_SP1(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRO_SP1_SHIFT)) & AIPS_PACRO_SP1_MASK) -#define AIPS_PACRO_TP0_MASK (0x10000000U) -#define AIPS_PACRO_TP0_SHIFT (28U) -#define AIPS_PACRO_TP0(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRO_TP0_SHIFT)) & AIPS_PACRO_TP0_MASK) -#define AIPS_PACRO_WP0_MASK (0x20000000U) -#define AIPS_PACRO_WP0_SHIFT (29U) -#define AIPS_PACRO_WP0(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRO_WP0_SHIFT)) & AIPS_PACRO_WP0_MASK) -#define AIPS_PACRO_SP0_MASK (0x40000000U) -#define AIPS_PACRO_SP0_SHIFT (30U) -#define AIPS_PACRO_SP0(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRO_SP0_SHIFT)) & AIPS_PACRO_SP0_MASK) - -/*! @name PACRP - Peripheral Access Control Register */ -#define AIPS_PACRP_TP7_MASK (0x1U) -#define AIPS_PACRP_TP7_SHIFT (0U) -#define AIPS_PACRP_TP7(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRP_TP7_SHIFT)) & AIPS_PACRP_TP7_MASK) -#define AIPS_PACRP_WP7_MASK (0x2U) -#define AIPS_PACRP_WP7_SHIFT (1U) -#define AIPS_PACRP_WP7(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRP_WP7_SHIFT)) & AIPS_PACRP_WP7_MASK) -#define AIPS_PACRP_SP7_MASK (0x4U) -#define AIPS_PACRP_SP7_SHIFT (2U) -#define AIPS_PACRP_SP7(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRP_SP7_SHIFT)) & AIPS_PACRP_SP7_MASK) -#define AIPS_PACRP_TP6_MASK (0x10U) -#define AIPS_PACRP_TP6_SHIFT (4U) -#define AIPS_PACRP_TP6(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRP_TP6_SHIFT)) & AIPS_PACRP_TP6_MASK) -#define AIPS_PACRP_WP6_MASK (0x20U) -#define AIPS_PACRP_WP6_SHIFT (5U) -#define AIPS_PACRP_WP6(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRP_WP6_SHIFT)) & AIPS_PACRP_WP6_MASK) -#define AIPS_PACRP_SP6_MASK (0x40U) -#define AIPS_PACRP_SP6_SHIFT (6U) -#define AIPS_PACRP_SP6(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRP_SP6_SHIFT)) & AIPS_PACRP_SP6_MASK) -#define AIPS_PACRP_TP5_MASK (0x100U) -#define AIPS_PACRP_TP5_SHIFT (8U) -#define AIPS_PACRP_TP5(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRP_TP5_SHIFT)) & AIPS_PACRP_TP5_MASK) -#define AIPS_PACRP_WP5_MASK (0x200U) -#define AIPS_PACRP_WP5_SHIFT (9U) -#define AIPS_PACRP_WP5(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRP_WP5_SHIFT)) & AIPS_PACRP_WP5_MASK) -#define AIPS_PACRP_SP5_MASK (0x400U) -#define AIPS_PACRP_SP5_SHIFT (10U) -#define AIPS_PACRP_SP5(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRP_SP5_SHIFT)) & AIPS_PACRP_SP5_MASK) -#define AIPS_PACRP_TP4_MASK (0x1000U) -#define AIPS_PACRP_TP4_SHIFT (12U) -#define AIPS_PACRP_TP4(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRP_TP4_SHIFT)) & AIPS_PACRP_TP4_MASK) -#define AIPS_PACRP_WP4_MASK (0x2000U) -#define AIPS_PACRP_WP4_SHIFT (13U) -#define AIPS_PACRP_WP4(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRP_WP4_SHIFT)) & AIPS_PACRP_WP4_MASK) -#define AIPS_PACRP_SP4_MASK (0x4000U) -#define AIPS_PACRP_SP4_SHIFT (14U) -#define AIPS_PACRP_SP4(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRP_SP4_SHIFT)) & AIPS_PACRP_SP4_MASK) -#define AIPS_PACRP_TP3_MASK (0x10000U) -#define AIPS_PACRP_TP3_SHIFT (16U) -#define AIPS_PACRP_TP3(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRP_TP3_SHIFT)) & AIPS_PACRP_TP3_MASK) -#define AIPS_PACRP_WP3_MASK (0x20000U) -#define AIPS_PACRP_WP3_SHIFT (17U) -#define AIPS_PACRP_WP3(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRP_WP3_SHIFT)) & AIPS_PACRP_WP3_MASK) -#define AIPS_PACRP_SP3_MASK (0x40000U) -#define AIPS_PACRP_SP3_SHIFT (18U) -#define AIPS_PACRP_SP3(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRP_SP3_SHIFT)) & AIPS_PACRP_SP3_MASK) -#define AIPS_PACRP_TP2_MASK (0x100000U) -#define AIPS_PACRP_TP2_SHIFT (20U) -#define AIPS_PACRP_TP2(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRP_TP2_SHIFT)) & AIPS_PACRP_TP2_MASK) -#define AIPS_PACRP_WP2_MASK (0x200000U) -#define AIPS_PACRP_WP2_SHIFT (21U) -#define AIPS_PACRP_WP2(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRP_WP2_SHIFT)) & AIPS_PACRP_WP2_MASK) -#define AIPS_PACRP_SP2_MASK (0x400000U) -#define AIPS_PACRP_SP2_SHIFT (22U) -#define AIPS_PACRP_SP2(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRP_SP2_SHIFT)) & AIPS_PACRP_SP2_MASK) -#define AIPS_PACRP_TP1_MASK (0x1000000U) -#define AIPS_PACRP_TP1_SHIFT (24U) -#define AIPS_PACRP_TP1(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRP_TP1_SHIFT)) & AIPS_PACRP_TP1_MASK) -#define AIPS_PACRP_WP1_MASK (0x2000000U) -#define AIPS_PACRP_WP1_SHIFT (25U) -#define AIPS_PACRP_WP1(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRP_WP1_SHIFT)) & AIPS_PACRP_WP1_MASK) -#define AIPS_PACRP_SP1_MASK (0x4000000U) -#define AIPS_PACRP_SP1_SHIFT (26U) -#define AIPS_PACRP_SP1(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRP_SP1_SHIFT)) & AIPS_PACRP_SP1_MASK) -#define AIPS_PACRP_TP0_MASK (0x10000000U) -#define AIPS_PACRP_TP0_SHIFT (28U) -#define AIPS_PACRP_TP0(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRP_TP0_SHIFT)) & AIPS_PACRP_TP0_MASK) -#define AIPS_PACRP_WP0_MASK (0x20000000U) -#define AIPS_PACRP_WP0_SHIFT (29U) -#define AIPS_PACRP_WP0(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRP_WP0_SHIFT)) & AIPS_PACRP_WP0_MASK) -#define AIPS_PACRP_SP0_MASK (0x40000000U) -#define AIPS_PACRP_SP0_SHIFT (30U) -#define AIPS_PACRP_SP0(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRP_SP0_SHIFT)) & AIPS_PACRP_SP0_MASK) - -/*! @name PACRU - Peripheral Access Control Register */ -#define AIPS_PACRU_TP1_MASK (0x1000000U) -#define AIPS_PACRU_TP1_SHIFT (24U) -#define AIPS_PACRU_TP1(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRU_TP1_SHIFT)) & AIPS_PACRU_TP1_MASK) -#define AIPS_PACRU_WP1_MASK (0x2000000U) -#define AIPS_PACRU_WP1_SHIFT (25U) -#define AIPS_PACRU_WP1(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRU_WP1_SHIFT)) & AIPS_PACRU_WP1_MASK) -#define AIPS_PACRU_SP1_MASK (0x4000000U) -#define AIPS_PACRU_SP1_SHIFT (26U) -#define AIPS_PACRU_SP1(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRU_SP1_SHIFT)) & AIPS_PACRU_SP1_MASK) -#define AIPS_PACRU_TP0_MASK (0x10000000U) -#define AIPS_PACRU_TP0_SHIFT (28U) -#define AIPS_PACRU_TP0(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRU_TP0_SHIFT)) & AIPS_PACRU_TP0_MASK) -#define AIPS_PACRU_WP0_MASK (0x20000000U) -#define AIPS_PACRU_WP0_SHIFT (29U) -#define AIPS_PACRU_WP0(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRU_WP0_SHIFT)) & AIPS_PACRU_WP0_MASK) -#define AIPS_PACRU_SP0_MASK (0x40000000U) -#define AIPS_PACRU_SP0_SHIFT (30U) -#define AIPS_PACRU_SP0(x) (((uint32_t)(((uint32_t)(x)) << AIPS_PACRU_SP0_SHIFT)) & AIPS_PACRU_SP0_MASK) - - -/*! - * @} - */ /* end of group AIPS_Register_Masks */ - - -/* AIPS - Peripheral instance base addresses */ -/** Peripheral AIPS0 base address */ -#define AIPS0_BASE (0x40000000u) -/** Peripheral AIPS0 base pointer */ -#define AIPS0 ((AIPS_Type *)AIPS0_BASE) -/** Peripheral AIPS1 base address */ -#define AIPS1_BASE (0x40080000u) -/** Peripheral AIPS1 base pointer */ -#define AIPS1 ((AIPS_Type *)AIPS1_BASE) -/** Array initializer of AIPS peripheral base addresses */ -#define AIPS_BASE_ADDRS { AIPS0_BASE, AIPS1_BASE } -/** Array initializer of AIPS peripheral base pointers */ -#define AIPS_BASE_PTRS { AIPS0, AIPS1 } - -/*! - * @} - */ /* end of group AIPS_Peripheral_Access_Layer */ - - -/* ---------------------------------------------------------------------------- - -- AXBS Peripheral Access Layer - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup AXBS_Peripheral_Access_Layer AXBS Peripheral Access Layer - * @{ - */ - -/** AXBS - Register Layout Typedef */ -typedef struct { - struct { /* offset: 0x0, array step: 0x100 */ - __IO uint32_t PRS; /**< Priority Registers Slave, array offset: 0x0, array step: 0x100 */ - uint8_t RESERVED_0[12]; - __IO uint32_t CRS; /**< Control Register, array offset: 0x10, array step: 0x100 */ - uint8_t RESERVED_1[236]; - } SLAVE[5]; - uint8_t RESERVED_0[768]; - __IO uint32_t MGPCR0; /**< Master General Purpose Control Register, offset: 0x800 */ - uint8_t RESERVED_1[252]; - __IO uint32_t MGPCR1; /**< Master General Purpose Control Register, offset: 0x900 */ - uint8_t RESERVED_2[252]; - __IO uint32_t MGPCR2; /**< Master General Purpose Control Register, offset: 0xA00 */ - uint8_t RESERVED_3[508]; - __IO uint32_t MGPCR4; /**< Master General Purpose Control Register, offset: 0xC00 */ - uint8_t RESERVED_4[252]; - __IO uint32_t MGPCR5; /**< Master General Purpose Control Register, offset: 0xD00 */ -} AXBS_Type; - -/* ---------------------------------------------------------------------------- - -- AXBS Register Masks - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup AXBS_Register_Masks AXBS Register Masks - * @{ - */ - -/*! @name PRS - Priority Registers Slave */ -#define AXBS_PRS_M0_MASK (0x7U) -#define AXBS_PRS_M0_SHIFT (0U) -#define AXBS_PRS_M0(x) (((uint32_t)(((uint32_t)(x)) << AXBS_PRS_M0_SHIFT)) & AXBS_PRS_M0_MASK) -#define AXBS_PRS_M1_MASK (0x70U) -#define AXBS_PRS_M1_SHIFT (4U) -#define AXBS_PRS_M1(x) (((uint32_t)(((uint32_t)(x)) << AXBS_PRS_M1_SHIFT)) & AXBS_PRS_M1_MASK) -#define AXBS_PRS_M2_MASK (0x700U) -#define AXBS_PRS_M2_SHIFT (8U) -#define AXBS_PRS_M2(x) (((uint32_t)(((uint32_t)(x)) << AXBS_PRS_M2_SHIFT)) & AXBS_PRS_M2_MASK) -#define AXBS_PRS_M4_MASK (0x70000U) -#define AXBS_PRS_M4_SHIFT (16U) -#define AXBS_PRS_M4(x) (((uint32_t)(((uint32_t)(x)) << AXBS_PRS_M4_SHIFT)) & AXBS_PRS_M4_MASK) -#define AXBS_PRS_M5_MASK (0x700000U) -#define AXBS_PRS_M5_SHIFT (20U) -#define AXBS_PRS_M5(x) (((uint32_t)(((uint32_t)(x)) << AXBS_PRS_M5_SHIFT)) & AXBS_PRS_M5_MASK) - -/* The count of AXBS_PRS */ -#define AXBS_PRS_COUNT (5U) - -/*! @name CRS - Control Register */ -#define AXBS_CRS_PARK_MASK (0x7U) -#define AXBS_CRS_PARK_SHIFT (0U) -#define AXBS_CRS_PARK(x) (((uint32_t)(((uint32_t)(x)) << AXBS_CRS_PARK_SHIFT)) & AXBS_CRS_PARK_MASK) -#define AXBS_CRS_PCTL_MASK (0x30U) -#define AXBS_CRS_PCTL_SHIFT (4U) -#define AXBS_CRS_PCTL(x) (((uint32_t)(((uint32_t)(x)) << AXBS_CRS_PCTL_SHIFT)) & AXBS_CRS_PCTL_MASK) -#define AXBS_CRS_ARB_MASK (0x300U) -#define AXBS_CRS_ARB_SHIFT (8U) -#define AXBS_CRS_ARB(x) (((uint32_t)(((uint32_t)(x)) << AXBS_CRS_ARB_SHIFT)) & AXBS_CRS_ARB_MASK) -#define AXBS_CRS_HLP_MASK (0x40000000U) -#define AXBS_CRS_HLP_SHIFT (30U) -#define AXBS_CRS_HLP(x) (((uint32_t)(((uint32_t)(x)) << AXBS_CRS_HLP_SHIFT)) & AXBS_CRS_HLP_MASK) -#define AXBS_CRS_RO_MASK (0x80000000U) -#define AXBS_CRS_RO_SHIFT (31U) -#define AXBS_CRS_RO(x) (((uint32_t)(((uint32_t)(x)) << AXBS_CRS_RO_SHIFT)) & AXBS_CRS_RO_MASK) - -/* The count of AXBS_CRS */ -#define AXBS_CRS_COUNT (5U) - -/*! @name MGPCR0 - Master General Purpose Control Register */ -#define AXBS_MGPCR0_AULB_MASK (0x7U) -#define AXBS_MGPCR0_AULB_SHIFT (0U) -#define AXBS_MGPCR0_AULB(x) (((uint32_t)(((uint32_t)(x)) << AXBS_MGPCR0_AULB_SHIFT)) & AXBS_MGPCR0_AULB_MASK) - -/*! @name MGPCR1 - Master General Purpose Control Register */ -#define AXBS_MGPCR1_AULB_MASK (0x7U) -#define AXBS_MGPCR1_AULB_SHIFT (0U) -#define AXBS_MGPCR1_AULB(x) (((uint32_t)(((uint32_t)(x)) << AXBS_MGPCR1_AULB_SHIFT)) & AXBS_MGPCR1_AULB_MASK) - -/*! @name MGPCR2 - Master General Purpose Control Register */ -#define AXBS_MGPCR2_AULB_MASK (0x7U) -#define AXBS_MGPCR2_AULB_SHIFT (0U) -#define AXBS_MGPCR2_AULB(x) (((uint32_t)(((uint32_t)(x)) << AXBS_MGPCR2_AULB_SHIFT)) & AXBS_MGPCR2_AULB_MASK) - -/*! @name MGPCR4 - Master General Purpose Control Register */ -#define AXBS_MGPCR4_AULB_MASK (0x7U) -#define AXBS_MGPCR4_AULB_SHIFT (0U) -#define AXBS_MGPCR4_AULB(x) (((uint32_t)(((uint32_t)(x)) << AXBS_MGPCR4_AULB_SHIFT)) & AXBS_MGPCR4_AULB_MASK) - -/*! @name MGPCR5 - Master General Purpose Control Register */ -#define AXBS_MGPCR5_AULB_MASK (0x7U) -#define AXBS_MGPCR5_AULB_SHIFT (0U) -#define AXBS_MGPCR5_AULB(x) (((uint32_t)(((uint32_t)(x)) << AXBS_MGPCR5_AULB_SHIFT)) & AXBS_MGPCR5_AULB_MASK) - - -/*! - * @} - */ /* end of group AXBS_Register_Masks */ - - -/* AXBS - Peripheral instance base addresses */ -/** Peripheral AXBS base address */ -#define AXBS_BASE (0x40004000u) -/** Peripheral AXBS base pointer */ -#define AXBS ((AXBS_Type *)AXBS_BASE) -/** Array initializer of AXBS peripheral base addresses */ -#define AXBS_BASE_ADDRS { AXBS_BASE } -/** Array initializer of AXBS peripheral base pointers */ -#define AXBS_BASE_PTRS { AXBS } - -/*! - * @} - */ /* end of group AXBS_Peripheral_Access_Layer */ - - -/* ---------------------------------------------------------------------------- - -- CAN Peripheral Access Layer - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup CAN_Peripheral_Access_Layer CAN Peripheral Access Layer - * @{ - */ - -/** CAN - Register Layout Typedef */ -typedef struct { - __IO uint32_t MCR; /**< Module Configuration Register, offset: 0x0 */ - __IO uint32_t CTRL1; /**< Control 1 register, offset: 0x4 */ - __IO uint32_t TIMER; /**< Free Running Timer, offset: 0x8 */ - uint8_t RESERVED_0[4]; - __IO uint32_t RXMGMASK; /**< Rx Mailboxes Global Mask Register, offset: 0x10 */ - __IO uint32_t RX14MASK; /**< Rx 14 Mask register, offset: 0x14 */ - __IO uint32_t RX15MASK; /**< Rx 15 Mask register, offset: 0x18 */ - __IO uint32_t ECR; /**< Error Counter, offset: 0x1C */ - __IO uint32_t ESR1; /**< Error and Status 1 register, offset: 0x20 */ - uint8_t RESERVED_1[4]; - __IO uint32_t IMASK1; /**< Interrupt Masks 1 register, offset: 0x28 */ - uint8_t RESERVED_2[4]; - __IO uint32_t IFLAG1; /**< Interrupt Flags 1 register, offset: 0x30 */ - __IO uint32_t CTRL2; /**< Control 2 register, offset: 0x34 */ - __I uint32_t ESR2; /**< Error and Status 2 register, offset: 0x38 */ - uint8_t RESERVED_3[8]; - __I uint32_t CRCR; /**< CRC Register, offset: 0x44 */ - __IO uint32_t RXFGMASK; /**< Rx FIFO Global Mask register, offset: 0x48 */ - __I uint32_t RXFIR; /**< Rx FIFO Information Register, offset: 0x4C */ - uint8_t RESERVED_4[48]; - struct { /* offset: 0x80, array step: 0x10 */ - __IO uint32_t CS; /**< Message Buffer 0 CS Register..Message Buffer 15 CS Register, array offset: 0x80, array step: 0x10 */ - __IO uint32_t ID; /**< Message Buffer 0 ID Register..Message Buffer 15 ID Register, array offset: 0x84, array step: 0x10 */ - __IO uint32_t WORD0; /**< Message Buffer 0 WORD0 Register..Message Buffer 15 WORD0 Register, array offset: 0x88, array step: 0x10 */ - __IO uint32_t WORD1; /**< Message Buffer 0 WORD1 Register..Message Buffer 15 WORD1 Register, array offset: 0x8C, array step: 0x10 */ - } MB[16]; - uint8_t RESERVED_5[1792]; - __IO uint32_t RXIMR[16]; /**< Rx Individual Mask Registers, array offset: 0x880, array step: 0x4 */ -} CAN_Type; - -/* ---------------------------------------------------------------------------- - -- CAN Register Masks - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup CAN_Register_Masks CAN Register Masks - * @{ - */ - -/*! @name MCR - Module Configuration Register */ -#define CAN_MCR_MAXMB_MASK (0x7FU) -#define CAN_MCR_MAXMB_SHIFT (0U) -#define CAN_MCR_MAXMB(x) (((uint32_t)(((uint32_t)(x)) << CAN_MCR_MAXMB_SHIFT)) & CAN_MCR_MAXMB_MASK) -#define CAN_MCR_IDAM_MASK (0x300U) -#define CAN_MCR_IDAM_SHIFT (8U) -#define CAN_MCR_IDAM(x) (((uint32_t)(((uint32_t)(x)) << CAN_MCR_IDAM_SHIFT)) & CAN_MCR_IDAM_MASK) -#define CAN_MCR_AEN_MASK (0x1000U) -#define CAN_MCR_AEN_SHIFT (12U) -#define CAN_MCR_AEN(x) (((uint32_t)(((uint32_t)(x)) << CAN_MCR_AEN_SHIFT)) & CAN_MCR_AEN_MASK) -#define CAN_MCR_LPRIOEN_MASK (0x2000U) -#define CAN_MCR_LPRIOEN_SHIFT (13U) -#define CAN_MCR_LPRIOEN(x) (((uint32_t)(((uint32_t)(x)) << CAN_MCR_LPRIOEN_SHIFT)) & CAN_MCR_LPRIOEN_MASK) -#define CAN_MCR_IRMQ_MASK (0x10000U) -#define CAN_MCR_IRMQ_SHIFT (16U) -#define CAN_MCR_IRMQ(x) (((uint32_t)(((uint32_t)(x)) << CAN_MCR_IRMQ_SHIFT)) & CAN_MCR_IRMQ_MASK) -#define CAN_MCR_SRXDIS_MASK (0x20000U) -#define CAN_MCR_SRXDIS_SHIFT (17U) -#define CAN_MCR_SRXDIS(x) (((uint32_t)(((uint32_t)(x)) << CAN_MCR_SRXDIS_SHIFT)) & CAN_MCR_SRXDIS_MASK) -#define CAN_MCR_WAKSRC_MASK (0x80000U) -#define CAN_MCR_WAKSRC_SHIFT (19U) -#define CAN_MCR_WAKSRC(x) (((uint32_t)(((uint32_t)(x)) << CAN_MCR_WAKSRC_SHIFT)) & CAN_MCR_WAKSRC_MASK) -#define CAN_MCR_LPMACK_MASK (0x100000U) -#define CAN_MCR_LPMACK_SHIFT (20U) -#define CAN_MCR_LPMACK(x) (((uint32_t)(((uint32_t)(x)) << CAN_MCR_LPMACK_SHIFT)) & CAN_MCR_LPMACK_MASK) -#define CAN_MCR_WRNEN_MASK (0x200000U) -#define CAN_MCR_WRNEN_SHIFT (21U) -#define CAN_MCR_WRNEN(x) (((uint32_t)(((uint32_t)(x)) << CAN_MCR_WRNEN_SHIFT)) & CAN_MCR_WRNEN_MASK) -#define CAN_MCR_SLFWAK_MASK (0x400000U) -#define CAN_MCR_SLFWAK_SHIFT (22U) -#define CAN_MCR_SLFWAK(x) (((uint32_t)(((uint32_t)(x)) << CAN_MCR_SLFWAK_SHIFT)) & CAN_MCR_SLFWAK_MASK) -#define CAN_MCR_SUPV_MASK (0x800000U) -#define CAN_MCR_SUPV_SHIFT (23U) -#define CAN_MCR_SUPV(x) (((uint32_t)(((uint32_t)(x)) << CAN_MCR_SUPV_SHIFT)) & CAN_MCR_SUPV_MASK) -#define CAN_MCR_FRZACK_MASK (0x1000000U) -#define CAN_MCR_FRZACK_SHIFT (24U) -#define CAN_MCR_FRZACK(x) (((uint32_t)(((uint32_t)(x)) << CAN_MCR_FRZACK_SHIFT)) & CAN_MCR_FRZACK_MASK) -#define CAN_MCR_SOFTRST_MASK (0x2000000U) -#define CAN_MCR_SOFTRST_SHIFT (25U) -#define CAN_MCR_SOFTRST(x) (((uint32_t)(((uint32_t)(x)) << CAN_MCR_SOFTRST_SHIFT)) & CAN_MCR_SOFTRST_MASK) -#define CAN_MCR_WAKMSK_MASK (0x4000000U) -#define CAN_MCR_WAKMSK_SHIFT (26U) -#define CAN_MCR_WAKMSK(x) (((uint32_t)(((uint32_t)(x)) << CAN_MCR_WAKMSK_SHIFT)) & CAN_MCR_WAKMSK_MASK) -#define CAN_MCR_NOTRDY_MASK (0x8000000U) -#define CAN_MCR_NOTRDY_SHIFT (27U) -#define CAN_MCR_NOTRDY(x) (((uint32_t)(((uint32_t)(x)) << CAN_MCR_NOTRDY_SHIFT)) & CAN_MCR_NOTRDY_MASK) -#define CAN_MCR_HALT_MASK (0x10000000U) -#define CAN_MCR_HALT_SHIFT (28U) -#define CAN_MCR_HALT(x) (((uint32_t)(((uint32_t)(x)) << CAN_MCR_HALT_SHIFT)) & CAN_MCR_HALT_MASK) -#define CAN_MCR_RFEN_MASK (0x20000000U) -#define CAN_MCR_RFEN_SHIFT (29U) -#define CAN_MCR_RFEN(x) (((uint32_t)(((uint32_t)(x)) << CAN_MCR_RFEN_SHIFT)) & CAN_MCR_RFEN_MASK) -#define CAN_MCR_FRZ_MASK (0x40000000U) -#define CAN_MCR_FRZ_SHIFT (30U) -#define CAN_MCR_FRZ(x) (((uint32_t)(((uint32_t)(x)) << CAN_MCR_FRZ_SHIFT)) & CAN_MCR_FRZ_MASK) -#define CAN_MCR_MDIS_MASK (0x80000000U) -#define CAN_MCR_MDIS_SHIFT (31U) -#define CAN_MCR_MDIS(x) (((uint32_t)(((uint32_t)(x)) << CAN_MCR_MDIS_SHIFT)) & CAN_MCR_MDIS_MASK) - -/*! @name CTRL1 - Control 1 register */ -#define CAN_CTRL1_PROPSEG_MASK (0x7U) -#define CAN_CTRL1_PROPSEG_SHIFT (0U) -#define CAN_CTRL1_PROPSEG(x) (((uint32_t)(((uint32_t)(x)) << CAN_CTRL1_PROPSEG_SHIFT)) & CAN_CTRL1_PROPSEG_MASK) -#define CAN_CTRL1_LOM_MASK (0x8U) -#define CAN_CTRL1_LOM_SHIFT (3U) -#define CAN_CTRL1_LOM(x) (((uint32_t)(((uint32_t)(x)) << CAN_CTRL1_LOM_SHIFT)) & CAN_CTRL1_LOM_MASK) -#define CAN_CTRL1_LBUF_MASK (0x10U) -#define CAN_CTRL1_LBUF_SHIFT (4U) -#define CAN_CTRL1_LBUF(x) (((uint32_t)(((uint32_t)(x)) << CAN_CTRL1_LBUF_SHIFT)) & CAN_CTRL1_LBUF_MASK) -#define CAN_CTRL1_TSYN_MASK (0x20U) -#define CAN_CTRL1_TSYN_SHIFT (5U) -#define CAN_CTRL1_TSYN(x) (((uint32_t)(((uint32_t)(x)) << CAN_CTRL1_TSYN_SHIFT)) & CAN_CTRL1_TSYN_MASK) -#define CAN_CTRL1_BOFFREC_MASK (0x40U) -#define CAN_CTRL1_BOFFREC_SHIFT (6U) -#define CAN_CTRL1_BOFFREC(x) (((uint32_t)(((uint32_t)(x)) << CAN_CTRL1_BOFFREC_SHIFT)) & CAN_CTRL1_BOFFREC_MASK) -#define CAN_CTRL1_SMP_MASK (0x80U) -#define CAN_CTRL1_SMP_SHIFT (7U) -#define CAN_CTRL1_SMP(x) (((uint32_t)(((uint32_t)(x)) << CAN_CTRL1_SMP_SHIFT)) & CAN_CTRL1_SMP_MASK) -#define CAN_CTRL1_RWRNMSK_MASK (0x400U) -#define CAN_CTRL1_RWRNMSK_SHIFT (10U) -#define CAN_CTRL1_RWRNMSK(x) (((uint32_t)(((uint32_t)(x)) << CAN_CTRL1_RWRNMSK_SHIFT)) & CAN_CTRL1_RWRNMSK_MASK) -#define CAN_CTRL1_TWRNMSK_MASK (0x800U) -#define CAN_CTRL1_TWRNMSK_SHIFT (11U) -#define CAN_CTRL1_TWRNMSK(x) (((uint32_t)(((uint32_t)(x)) << CAN_CTRL1_TWRNMSK_SHIFT)) & CAN_CTRL1_TWRNMSK_MASK) -#define CAN_CTRL1_LPB_MASK (0x1000U) -#define CAN_CTRL1_LPB_SHIFT (12U) -#define CAN_CTRL1_LPB(x) (((uint32_t)(((uint32_t)(x)) << CAN_CTRL1_LPB_SHIFT)) & CAN_CTRL1_LPB_MASK) -#define CAN_CTRL1_CLKSRC_MASK (0x2000U) -#define CAN_CTRL1_CLKSRC_SHIFT (13U) -#define CAN_CTRL1_CLKSRC(x) (((uint32_t)(((uint32_t)(x)) << CAN_CTRL1_CLKSRC_SHIFT)) & CAN_CTRL1_CLKSRC_MASK) -#define CAN_CTRL1_ERRMSK_MASK (0x4000U) -#define CAN_CTRL1_ERRMSK_SHIFT (14U) -#define CAN_CTRL1_ERRMSK(x) (((uint32_t)(((uint32_t)(x)) << CAN_CTRL1_ERRMSK_SHIFT)) & CAN_CTRL1_ERRMSK_MASK) -#define CAN_CTRL1_BOFFMSK_MASK (0x8000U) -#define CAN_CTRL1_BOFFMSK_SHIFT (15U) -#define CAN_CTRL1_BOFFMSK(x) (((uint32_t)(((uint32_t)(x)) << CAN_CTRL1_BOFFMSK_SHIFT)) & CAN_CTRL1_BOFFMSK_MASK) -#define CAN_CTRL1_PSEG2_MASK (0x70000U) -#define CAN_CTRL1_PSEG2_SHIFT (16U) -#define CAN_CTRL1_PSEG2(x) (((uint32_t)(((uint32_t)(x)) << CAN_CTRL1_PSEG2_SHIFT)) & CAN_CTRL1_PSEG2_MASK) -#define CAN_CTRL1_PSEG1_MASK (0x380000U) -#define CAN_CTRL1_PSEG1_SHIFT (19U) -#define CAN_CTRL1_PSEG1(x) (((uint32_t)(((uint32_t)(x)) << CAN_CTRL1_PSEG1_SHIFT)) & CAN_CTRL1_PSEG1_MASK) -#define CAN_CTRL1_RJW_MASK (0xC00000U) -#define CAN_CTRL1_RJW_SHIFT (22U) -#define CAN_CTRL1_RJW(x) (((uint32_t)(((uint32_t)(x)) << CAN_CTRL1_RJW_SHIFT)) & CAN_CTRL1_RJW_MASK) -#define CAN_CTRL1_PRESDIV_MASK (0xFF000000U) -#define CAN_CTRL1_PRESDIV_SHIFT (24U) -#define CAN_CTRL1_PRESDIV(x) (((uint32_t)(((uint32_t)(x)) << CAN_CTRL1_PRESDIV_SHIFT)) & CAN_CTRL1_PRESDIV_MASK) - -/*! @name TIMER - Free Running Timer */ -#define CAN_TIMER_TIMER_MASK (0xFFFFU) -#define CAN_TIMER_TIMER_SHIFT (0U) -#define CAN_TIMER_TIMER(x) (((uint32_t)(((uint32_t)(x)) << CAN_TIMER_TIMER_SHIFT)) & CAN_TIMER_TIMER_MASK) - -/*! @name RXMGMASK - Rx Mailboxes Global Mask Register */ -#define CAN_RXMGMASK_MG_MASK (0xFFFFFFFFU) -#define CAN_RXMGMASK_MG_SHIFT (0U) -#define CAN_RXMGMASK_MG(x) (((uint32_t)(((uint32_t)(x)) << CAN_RXMGMASK_MG_SHIFT)) & CAN_RXMGMASK_MG_MASK) - -/*! @name RX14MASK - Rx 14 Mask register */ -#define CAN_RX14MASK_RX14M_MASK (0xFFFFFFFFU) -#define CAN_RX14MASK_RX14M_SHIFT (0U) -#define CAN_RX14MASK_RX14M(x) (((uint32_t)(((uint32_t)(x)) << CAN_RX14MASK_RX14M_SHIFT)) & CAN_RX14MASK_RX14M_MASK) - -/*! @name RX15MASK - Rx 15 Mask register */ -#define CAN_RX15MASK_RX15M_MASK (0xFFFFFFFFU) -#define CAN_RX15MASK_RX15M_SHIFT (0U) -#define CAN_RX15MASK_RX15M(x) (((uint32_t)(((uint32_t)(x)) << CAN_RX15MASK_RX15M_SHIFT)) & CAN_RX15MASK_RX15M_MASK) - -/*! @name ECR - Error Counter */ -#define CAN_ECR_TXERRCNT_MASK (0xFFU) -#define CAN_ECR_TXERRCNT_SHIFT (0U) -#define CAN_ECR_TXERRCNT(x) (((uint32_t)(((uint32_t)(x)) << CAN_ECR_TXERRCNT_SHIFT)) & CAN_ECR_TXERRCNT_MASK) -#define CAN_ECR_RXERRCNT_MASK (0xFF00U) -#define CAN_ECR_RXERRCNT_SHIFT (8U) -#define CAN_ECR_RXERRCNT(x) (((uint32_t)(((uint32_t)(x)) << CAN_ECR_RXERRCNT_SHIFT)) & CAN_ECR_RXERRCNT_MASK) - -/*! @name ESR1 - Error and Status 1 register */ -#define CAN_ESR1_WAKINT_MASK (0x1U) -#define CAN_ESR1_WAKINT_SHIFT (0U) -#define CAN_ESR1_WAKINT(x) (((uint32_t)(((uint32_t)(x)) << CAN_ESR1_WAKINT_SHIFT)) & CAN_ESR1_WAKINT_MASK) -#define CAN_ESR1_ERRINT_MASK (0x2U) -#define CAN_ESR1_ERRINT_SHIFT (1U) -#define CAN_ESR1_ERRINT(x) (((uint32_t)(((uint32_t)(x)) << CAN_ESR1_ERRINT_SHIFT)) & CAN_ESR1_ERRINT_MASK) -#define CAN_ESR1_BOFFINT_MASK (0x4U) -#define CAN_ESR1_BOFFINT_SHIFT (2U) -#define CAN_ESR1_BOFFINT(x) (((uint32_t)(((uint32_t)(x)) << CAN_ESR1_BOFFINT_SHIFT)) & CAN_ESR1_BOFFINT_MASK) -#define CAN_ESR1_RX_MASK (0x8U) -#define CAN_ESR1_RX_SHIFT (3U) -#define CAN_ESR1_RX(x) (((uint32_t)(((uint32_t)(x)) << CAN_ESR1_RX_SHIFT)) & CAN_ESR1_RX_MASK) -#define CAN_ESR1_FLTCONF_MASK (0x30U) -#define CAN_ESR1_FLTCONF_SHIFT (4U) -#define CAN_ESR1_FLTCONF(x) (((uint32_t)(((uint32_t)(x)) << CAN_ESR1_FLTCONF_SHIFT)) & CAN_ESR1_FLTCONF_MASK) -#define CAN_ESR1_TX_MASK (0x40U) -#define CAN_ESR1_TX_SHIFT (6U) -#define CAN_ESR1_TX(x) (((uint32_t)(((uint32_t)(x)) << CAN_ESR1_TX_SHIFT)) & CAN_ESR1_TX_MASK) -#define CAN_ESR1_IDLE_MASK (0x80U) -#define CAN_ESR1_IDLE_SHIFT (7U) -#define CAN_ESR1_IDLE(x) (((uint32_t)(((uint32_t)(x)) << CAN_ESR1_IDLE_SHIFT)) & CAN_ESR1_IDLE_MASK) -#define CAN_ESR1_RXWRN_MASK (0x100U) -#define CAN_ESR1_RXWRN_SHIFT (8U) -#define CAN_ESR1_RXWRN(x) (((uint32_t)(((uint32_t)(x)) << CAN_ESR1_RXWRN_SHIFT)) & CAN_ESR1_RXWRN_MASK) -#define CAN_ESR1_TXWRN_MASK (0x200U) -#define CAN_ESR1_TXWRN_SHIFT (9U) -#define CAN_ESR1_TXWRN(x) (((uint32_t)(((uint32_t)(x)) << CAN_ESR1_TXWRN_SHIFT)) & CAN_ESR1_TXWRN_MASK) -#define CAN_ESR1_STFERR_MASK (0x400U) -#define CAN_ESR1_STFERR_SHIFT (10U) -#define CAN_ESR1_STFERR(x) (((uint32_t)(((uint32_t)(x)) << CAN_ESR1_STFERR_SHIFT)) & CAN_ESR1_STFERR_MASK) -#define CAN_ESR1_FRMERR_MASK (0x800U) -#define CAN_ESR1_FRMERR_SHIFT (11U) -#define CAN_ESR1_FRMERR(x) (((uint32_t)(((uint32_t)(x)) << CAN_ESR1_FRMERR_SHIFT)) & CAN_ESR1_FRMERR_MASK) -#define CAN_ESR1_CRCERR_MASK (0x1000U) -#define CAN_ESR1_CRCERR_SHIFT (12U) -#define CAN_ESR1_CRCERR(x) (((uint32_t)(((uint32_t)(x)) << CAN_ESR1_CRCERR_SHIFT)) & CAN_ESR1_CRCERR_MASK) -#define CAN_ESR1_ACKERR_MASK (0x2000U) -#define CAN_ESR1_ACKERR_SHIFT (13U) -#define CAN_ESR1_ACKERR(x) (((uint32_t)(((uint32_t)(x)) << CAN_ESR1_ACKERR_SHIFT)) & CAN_ESR1_ACKERR_MASK) -#define CAN_ESR1_BIT0ERR_MASK (0x4000U) -#define CAN_ESR1_BIT0ERR_SHIFT (14U) -#define CAN_ESR1_BIT0ERR(x) (((uint32_t)(((uint32_t)(x)) << CAN_ESR1_BIT0ERR_SHIFT)) & CAN_ESR1_BIT0ERR_MASK) -#define CAN_ESR1_BIT1ERR_MASK (0x8000U) -#define CAN_ESR1_BIT1ERR_SHIFT (15U) -#define CAN_ESR1_BIT1ERR(x) (((uint32_t)(((uint32_t)(x)) << CAN_ESR1_BIT1ERR_SHIFT)) & CAN_ESR1_BIT1ERR_MASK) -#define CAN_ESR1_RWRNINT_MASK (0x10000U) -#define CAN_ESR1_RWRNINT_SHIFT (16U) -#define CAN_ESR1_RWRNINT(x) (((uint32_t)(((uint32_t)(x)) << CAN_ESR1_RWRNINT_SHIFT)) & CAN_ESR1_RWRNINT_MASK) -#define CAN_ESR1_TWRNINT_MASK (0x20000U) -#define CAN_ESR1_TWRNINT_SHIFT (17U) -#define CAN_ESR1_TWRNINT(x) (((uint32_t)(((uint32_t)(x)) << CAN_ESR1_TWRNINT_SHIFT)) & CAN_ESR1_TWRNINT_MASK) -#define CAN_ESR1_SYNCH_MASK (0x40000U) -#define CAN_ESR1_SYNCH_SHIFT (18U) -#define CAN_ESR1_SYNCH(x) (((uint32_t)(((uint32_t)(x)) << CAN_ESR1_SYNCH_SHIFT)) & CAN_ESR1_SYNCH_MASK) - -/*! @name IMASK1 - Interrupt Masks 1 register */ -#define CAN_IMASK1_BUFLM_MASK (0xFFFFFFFFU) -#define CAN_IMASK1_BUFLM_SHIFT (0U) -#define CAN_IMASK1_BUFLM(x) (((uint32_t)(((uint32_t)(x)) << CAN_IMASK1_BUFLM_SHIFT)) & CAN_IMASK1_BUFLM_MASK) - -/*! @name IFLAG1 - Interrupt Flags 1 register */ -#define CAN_IFLAG1_BUF0I_MASK (0x1U) -#define CAN_IFLAG1_BUF0I_SHIFT (0U) -#define CAN_IFLAG1_BUF0I(x) (((uint32_t)(((uint32_t)(x)) << CAN_IFLAG1_BUF0I_SHIFT)) & CAN_IFLAG1_BUF0I_MASK) -#define CAN_IFLAG1_BUF4TO1I_MASK (0x1EU) -#define CAN_IFLAG1_BUF4TO1I_SHIFT (1U) -#define CAN_IFLAG1_BUF4TO1I(x) (((uint32_t)(((uint32_t)(x)) << CAN_IFLAG1_BUF4TO1I_SHIFT)) & CAN_IFLAG1_BUF4TO1I_MASK) -#define CAN_IFLAG1_BUF5I_MASK (0x20U) -#define CAN_IFLAG1_BUF5I_SHIFT (5U) -#define CAN_IFLAG1_BUF5I(x) (((uint32_t)(((uint32_t)(x)) << CAN_IFLAG1_BUF5I_SHIFT)) & CAN_IFLAG1_BUF5I_MASK) -#define CAN_IFLAG1_BUF6I_MASK (0x40U) -#define CAN_IFLAG1_BUF6I_SHIFT (6U) -#define CAN_IFLAG1_BUF6I(x) (((uint32_t)(((uint32_t)(x)) << CAN_IFLAG1_BUF6I_SHIFT)) & CAN_IFLAG1_BUF6I_MASK) -#define CAN_IFLAG1_BUF7I_MASK (0x80U) -#define CAN_IFLAG1_BUF7I_SHIFT (7U) -#define CAN_IFLAG1_BUF7I(x) (((uint32_t)(((uint32_t)(x)) << CAN_IFLAG1_BUF7I_SHIFT)) & CAN_IFLAG1_BUF7I_MASK) -#define CAN_IFLAG1_BUF31TO8I_MASK (0xFFFFFF00U) -#define CAN_IFLAG1_BUF31TO8I_SHIFT (8U) -#define CAN_IFLAG1_BUF31TO8I(x) (((uint32_t)(((uint32_t)(x)) << CAN_IFLAG1_BUF31TO8I_SHIFT)) & CAN_IFLAG1_BUF31TO8I_MASK) - -/*! @name CTRL2 - Control 2 register */ -#define CAN_CTRL2_EACEN_MASK (0x10000U) -#define CAN_CTRL2_EACEN_SHIFT (16U) -#define CAN_CTRL2_EACEN(x) (((uint32_t)(((uint32_t)(x)) << CAN_CTRL2_EACEN_SHIFT)) & CAN_CTRL2_EACEN_MASK) -#define CAN_CTRL2_RRS_MASK (0x20000U) -#define CAN_CTRL2_RRS_SHIFT (17U) -#define CAN_CTRL2_RRS(x) (((uint32_t)(((uint32_t)(x)) << CAN_CTRL2_RRS_SHIFT)) & CAN_CTRL2_RRS_MASK) -#define CAN_CTRL2_MRP_MASK (0x40000U) -#define CAN_CTRL2_MRP_SHIFT (18U) -#define CAN_CTRL2_MRP(x) (((uint32_t)(((uint32_t)(x)) << CAN_CTRL2_MRP_SHIFT)) & CAN_CTRL2_MRP_MASK) -#define CAN_CTRL2_TASD_MASK (0xF80000U) -#define CAN_CTRL2_TASD_SHIFT (19U) -#define CAN_CTRL2_TASD(x) (((uint32_t)(((uint32_t)(x)) << CAN_CTRL2_TASD_SHIFT)) & CAN_CTRL2_TASD_MASK) -#define CAN_CTRL2_RFFN_MASK (0xF000000U) -#define CAN_CTRL2_RFFN_SHIFT (24U) -#define CAN_CTRL2_RFFN(x) (((uint32_t)(((uint32_t)(x)) << CAN_CTRL2_RFFN_SHIFT)) & CAN_CTRL2_RFFN_MASK) -#define CAN_CTRL2_WRMFRZ_MASK (0x10000000U) -#define CAN_CTRL2_WRMFRZ_SHIFT (28U) -#define CAN_CTRL2_WRMFRZ(x) (((uint32_t)(((uint32_t)(x)) << CAN_CTRL2_WRMFRZ_SHIFT)) & CAN_CTRL2_WRMFRZ_MASK) - -/*! @name ESR2 - Error and Status 2 register */ -#define CAN_ESR2_IMB_MASK (0x2000U) -#define CAN_ESR2_IMB_SHIFT (13U) -#define CAN_ESR2_IMB(x) (((uint32_t)(((uint32_t)(x)) << CAN_ESR2_IMB_SHIFT)) & CAN_ESR2_IMB_MASK) -#define CAN_ESR2_VPS_MASK (0x4000U) -#define CAN_ESR2_VPS_SHIFT (14U) -#define CAN_ESR2_VPS(x) (((uint32_t)(((uint32_t)(x)) << CAN_ESR2_VPS_SHIFT)) & CAN_ESR2_VPS_MASK) -#define CAN_ESR2_LPTM_MASK (0x7F0000U) -#define CAN_ESR2_LPTM_SHIFT (16U) -#define CAN_ESR2_LPTM(x) (((uint32_t)(((uint32_t)(x)) << CAN_ESR2_LPTM_SHIFT)) & CAN_ESR2_LPTM_MASK) - -/*! @name CRCR - CRC Register */ -#define CAN_CRCR_TXCRC_MASK (0x7FFFU) -#define CAN_CRCR_TXCRC_SHIFT (0U) -#define CAN_CRCR_TXCRC(x) (((uint32_t)(((uint32_t)(x)) << CAN_CRCR_TXCRC_SHIFT)) & CAN_CRCR_TXCRC_MASK) -#define CAN_CRCR_MBCRC_MASK (0x7F0000U) -#define CAN_CRCR_MBCRC_SHIFT (16U) -#define CAN_CRCR_MBCRC(x) (((uint32_t)(((uint32_t)(x)) << CAN_CRCR_MBCRC_SHIFT)) & CAN_CRCR_MBCRC_MASK) - -/*! @name RXFGMASK - Rx FIFO Global Mask register */ -#define CAN_RXFGMASK_FGM_MASK (0xFFFFFFFFU) -#define CAN_RXFGMASK_FGM_SHIFT (0U) -#define CAN_RXFGMASK_FGM(x) (((uint32_t)(((uint32_t)(x)) << CAN_RXFGMASK_FGM_SHIFT)) & CAN_RXFGMASK_FGM_MASK) - -/*! @name RXFIR - Rx FIFO Information Register */ -#define CAN_RXFIR_IDHIT_MASK (0x1FFU) -#define CAN_RXFIR_IDHIT_SHIFT (0U) -#define CAN_RXFIR_IDHIT(x) (((uint32_t)(((uint32_t)(x)) << CAN_RXFIR_IDHIT_SHIFT)) & CAN_RXFIR_IDHIT_MASK) - -/*! @name CS - Message Buffer 0 CS Register..Message Buffer 15 CS Register */ -#define CAN_CS_TIME_STAMP_MASK (0xFFFFU) -#define CAN_CS_TIME_STAMP_SHIFT (0U) -#define CAN_CS_TIME_STAMP(x) (((uint32_t)(((uint32_t)(x)) << CAN_CS_TIME_STAMP_SHIFT)) & CAN_CS_TIME_STAMP_MASK) -#define CAN_CS_DLC_MASK (0xF0000U) -#define CAN_CS_DLC_SHIFT (16U) -#define CAN_CS_DLC(x) (((uint32_t)(((uint32_t)(x)) << CAN_CS_DLC_SHIFT)) & CAN_CS_DLC_MASK) -#define CAN_CS_RTR_MASK (0x100000U) -#define CAN_CS_RTR_SHIFT (20U) -#define CAN_CS_RTR(x) (((uint32_t)(((uint32_t)(x)) << CAN_CS_RTR_SHIFT)) & CAN_CS_RTR_MASK) -#define CAN_CS_IDE_MASK (0x200000U) -#define CAN_CS_IDE_SHIFT (21U) -#define CAN_CS_IDE(x) (((uint32_t)(((uint32_t)(x)) << CAN_CS_IDE_SHIFT)) & CAN_CS_IDE_MASK) -#define CAN_CS_SRR_MASK (0x400000U) -#define CAN_CS_SRR_SHIFT (22U) -#define CAN_CS_SRR(x) (((uint32_t)(((uint32_t)(x)) << CAN_CS_SRR_SHIFT)) & CAN_CS_SRR_MASK) -#define CAN_CS_CODE_MASK (0xF000000U) -#define CAN_CS_CODE_SHIFT (24U) -#define CAN_CS_CODE(x) (((uint32_t)(((uint32_t)(x)) << CAN_CS_CODE_SHIFT)) & CAN_CS_CODE_MASK) - -/* The count of CAN_CS */ -#define CAN_CS_COUNT (16U) - -/*! @name ID - Message Buffer 0 ID Register..Message Buffer 15 ID Register */ -#define CAN_ID_EXT_MASK (0x3FFFFU) -#define CAN_ID_EXT_SHIFT (0U) -#define CAN_ID_EXT(x) (((uint32_t)(((uint32_t)(x)) << CAN_ID_EXT_SHIFT)) & CAN_ID_EXT_MASK) -#define CAN_ID_STD_MASK (0x1FFC0000U) -#define CAN_ID_STD_SHIFT (18U) -#define CAN_ID_STD(x) (((uint32_t)(((uint32_t)(x)) << CAN_ID_STD_SHIFT)) & CAN_ID_STD_MASK) -#define CAN_ID_PRIO_MASK (0xE0000000U) -#define CAN_ID_PRIO_SHIFT (29U) -#define CAN_ID_PRIO(x) (((uint32_t)(((uint32_t)(x)) << CAN_ID_PRIO_SHIFT)) & CAN_ID_PRIO_MASK) - -/* The count of CAN_ID */ -#define CAN_ID_COUNT (16U) - -/*! @name WORD0 - Message Buffer 0 WORD0 Register..Message Buffer 15 WORD0 Register */ -#define CAN_WORD0_DATA_BYTE_3_MASK (0xFFU) -#define CAN_WORD0_DATA_BYTE_3_SHIFT (0U) -#define CAN_WORD0_DATA_BYTE_3(x) (((uint32_t)(((uint32_t)(x)) << CAN_WORD0_DATA_BYTE_3_SHIFT)) & CAN_WORD0_DATA_BYTE_3_MASK) -#define CAN_WORD0_DATA_BYTE_2_MASK (0xFF00U) -#define CAN_WORD0_DATA_BYTE_2_SHIFT (8U) -#define CAN_WORD0_DATA_BYTE_2(x) (((uint32_t)(((uint32_t)(x)) << CAN_WORD0_DATA_BYTE_2_SHIFT)) & CAN_WORD0_DATA_BYTE_2_MASK) -#define CAN_WORD0_DATA_BYTE_1_MASK (0xFF0000U) -#define CAN_WORD0_DATA_BYTE_1_SHIFT (16U) -#define CAN_WORD0_DATA_BYTE_1(x) (((uint32_t)(((uint32_t)(x)) << CAN_WORD0_DATA_BYTE_1_SHIFT)) & CAN_WORD0_DATA_BYTE_1_MASK) -#define CAN_WORD0_DATA_BYTE_0_MASK (0xFF000000U) -#define CAN_WORD0_DATA_BYTE_0_SHIFT (24U) -#define CAN_WORD0_DATA_BYTE_0(x) (((uint32_t)(((uint32_t)(x)) << CAN_WORD0_DATA_BYTE_0_SHIFT)) & CAN_WORD0_DATA_BYTE_0_MASK) - -/* The count of CAN_WORD0 */ -#define CAN_WORD0_COUNT (16U) - -/*! @name WORD1 - Message Buffer 0 WORD1 Register..Message Buffer 15 WORD1 Register */ -#define CAN_WORD1_DATA_BYTE_7_MASK (0xFFU) -#define CAN_WORD1_DATA_BYTE_7_SHIFT (0U) -#define CAN_WORD1_DATA_BYTE_7(x) (((uint32_t)(((uint32_t)(x)) << CAN_WORD1_DATA_BYTE_7_SHIFT)) & CAN_WORD1_DATA_BYTE_7_MASK) -#define CAN_WORD1_DATA_BYTE_6_MASK (0xFF00U) -#define CAN_WORD1_DATA_BYTE_6_SHIFT (8U) -#define CAN_WORD1_DATA_BYTE_6(x) (((uint32_t)(((uint32_t)(x)) << CAN_WORD1_DATA_BYTE_6_SHIFT)) & CAN_WORD1_DATA_BYTE_6_MASK) -#define CAN_WORD1_DATA_BYTE_5_MASK (0xFF0000U) -#define CAN_WORD1_DATA_BYTE_5_SHIFT (16U) -#define CAN_WORD1_DATA_BYTE_5(x) (((uint32_t)(((uint32_t)(x)) << CAN_WORD1_DATA_BYTE_5_SHIFT)) & CAN_WORD1_DATA_BYTE_5_MASK) -#define CAN_WORD1_DATA_BYTE_4_MASK (0xFF000000U) -#define CAN_WORD1_DATA_BYTE_4_SHIFT (24U) -#define CAN_WORD1_DATA_BYTE_4(x) (((uint32_t)(((uint32_t)(x)) << CAN_WORD1_DATA_BYTE_4_SHIFT)) & CAN_WORD1_DATA_BYTE_4_MASK) - -/* The count of CAN_WORD1 */ -#define CAN_WORD1_COUNT (16U) - -/*! @name RXIMR - Rx Individual Mask Registers */ -#define CAN_RXIMR_MI_MASK (0xFFFFFFFFU) -#define CAN_RXIMR_MI_SHIFT (0U) -#define CAN_RXIMR_MI(x) (((uint32_t)(((uint32_t)(x)) << CAN_RXIMR_MI_SHIFT)) & CAN_RXIMR_MI_MASK) - -/* The count of CAN_RXIMR */ -#define CAN_RXIMR_COUNT (16U) - - -/*! - * @} - */ /* end of group CAN_Register_Masks */ - - -/* CAN - Peripheral instance base addresses */ -/** Peripheral CAN0 base address */ -#define CAN0_BASE (0x40024000u) -/** Peripheral CAN0 base pointer */ -#define CAN0 ((CAN_Type *)CAN0_BASE) -/** Array initializer of CAN peripheral base addresses */ -#define CAN_BASE_ADDRS { CAN0_BASE } -/** Array initializer of CAN peripheral base pointers */ -#define CAN_BASE_PTRS { CAN0 } -/** Interrupt vectors for the CAN peripheral type */ -#define CAN_Rx_Warning_IRQS { CAN0_Rx_Warning_IRQn } -#define CAN_Tx_Warning_IRQS { CAN0_Tx_Warning_IRQn } -#define CAN_Wake_Up_IRQS { CAN0_Wake_Up_IRQn } -#define CAN_Error_IRQS { CAN0_Error_IRQn } -#define CAN_Bus_Off_IRQS { CAN0_Bus_Off_IRQn } -#define CAN_ORed_Message_buffer_IRQS { CAN0_ORed_Message_buffer_IRQn } - -/*! - * @} - */ /* end of group CAN_Peripheral_Access_Layer */ - - -/* ---------------------------------------------------------------------------- - -- CAU Peripheral Access Layer - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup CAU_Peripheral_Access_Layer CAU Peripheral Access Layer - * @{ - */ - -/** CAU - Register Layout Typedef */ -typedef struct { - __O uint32_t DIRECT[16]; /**< Direct access register 0..Direct access register 15, array offset: 0x0, array step: 0x4 */ - uint8_t RESERVED_0[2048]; - __O uint32_t LDR_CASR; /**< Status register - Load Register command, offset: 0x840 */ - __O uint32_t LDR_CAA; /**< Accumulator register - Load Register command, offset: 0x844 */ - __O uint32_t LDR_CA[9]; /**< General Purpose Register 0 - Load Register command..General Purpose Register 8 - Load Register command, array offset: 0x848, array step: 0x4 */ - uint8_t RESERVED_1[20]; - __I uint32_t STR_CASR; /**< Status register - Store Register command, offset: 0x880 */ - __I uint32_t STR_CAA; /**< Accumulator register - Store Register command, offset: 0x884 */ - __I uint32_t STR_CA[9]; /**< General Purpose Register 0 - Store Register command..General Purpose Register 8 - Store Register command, array offset: 0x888, array step: 0x4 */ - uint8_t RESERVED_2[20]; - __O uint32_t ADR_CASR; /**< Status register - Add Register command, offset: 0x8C0 */ - __O uint32_t ADR_CAA; /**< Accumulator register - Add to register command, offset: 0x8C4 */ - __O uint32_t ADR_CA[9]; /**< General Purpose Register 0 - Add to register command..General Purpose Register 8 - Add to register command, array offset: 0x8C8, array step: 0x4 */ - uint8_t RESERVED_3[20]; - __O uint32_t RADR_CASR; /**< Status register - Reverse and Add to Register command, offset: 0x900 */ - __O uint32_t RADR_CAA; /**< Accumulator register - Reverse and Add to Register command, offset: 0x904 */ - __O uint32_t RADR_CA[9]; /**< General Purpose Register 0 - Reverse and Add to Register command..General Purpose Register 8 - Reverse and Add to Register command, array offset: 0x908, array step: 0x4 */ - uint8_t RESERVED_4[84]; - __O uint32_t XOR_CASR; /**< Status register - Exclusive Or command, offset: 0x980 */ - __O uint32_t XOR_CAA; /**< Accumulator register - Exclusive Or command, offset: 0x984 */ - __O uint32_t XOR_CA[9]; /**< General Purpose Register 0 - Exclusive Or command..General Purpose Register 8 - Exclusive Or command, array offset: 0x988, array step: 0x4 */ - uint8_t RESERVED_5[20]; - __O uint32_t ROTL_CASR; /**< Status register - Rotate Left command, offset: 0x9C0 */ - __O uint32_t ROTL_CAA; /**< Accumulator register - Rotate Left command, offset: 0x9C4 */ - __O uint32_t ROTL_CA[9]; /**< General Purpose Register 0 - Rotate Left command..General Purpose Register 8 - Rotate Left command, array offset: 0x9C8, array step: 0x4 */ - uint8_t RESERVED_6[276]; - __O uint32_t AESC_CASR; /**< Status register - AES Column Operation command, offset: 0xB00 */ - __O uint32_t AESC_CAA; /**< Accumulator register - AES Column Operation command, offset: 0xB04 */ - __O uint32_t AESC_CA[9]; /**< General Purpose Register 0 - AES Column Operation command..General Purpose Register 8 - AES Column Operation command, array offset: 0xB08, array step: 0x4 */ - uint8_t RESERVED_7[20]; - __O uint32_t AESIC_CASR; /**< Status register - AES Inverse Column Operation command, offset: 0xB40 */ - __O uint32_t AESIC_CAA; /**< Accumulator register - AES Inverse Column Operation command, offset: 0xB44 */ - __O uint32_t AESIC_CA[9]; /**< General Purpose Register 0 - AES Inverse Column Operation command..General Purpose Register 8 - AES Inverse Column Operation command, array offset: 0xB48, array step: 0x4 */ -} CAU_Type; - -/* ---------------------------------------------------------------------------- - -- CAU Register Masks - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup CAU_Register_Masks CAU Register Masks - * @{ - */ - -/*! @name DIRECT - Direct access register 0..Direct access register 15 */ -#define CAU_DIRECT_CAU_DIRECT0_MASK (0xFFFFFFFFU) -#define CAU_DIRECT_CAU_DIRECT0_SHIFT (0U) -#define CAU_DIRECT_CAU_DIRECT0(x) (((uint32_t)(((uint32_t)(x)) << CAU_DIRECT_CAU_DIRECT0_SHIFT)) & CAU_DIRECT_CAU_DIRECT0_MASK) -#define CAU_DIRECT_CAU_DIRECT1_MASK (0xFFFFFFFFU) -#define CAU_DIRECT_CAU_DIRECT1_SHIFT (0U) -#define CAU_DIRECT_CAU_DIRECT1(x) (((uint32_t)(((uint32_t)(x)) << CAU_DIRECT_CAU_DIRECT1_SHIFT)) & CAU_DIRECT_CAU_DIRECT1_MASK) -#define CAU_DIRECT_CAU_DIRECT2_MASK (0xFFFFFFFFU) -#define CAU_DIRECT_CAU_DIRECT2_SHIFT (0U) -#define CAU_DIRECT_CAU_DIRECT2(x) (((uint32_t)(((uint32_t)(x)) << CAU_DIRECT_CAU_DIRECT2_SHIFT)) & CAU_DIRECT_CAU_DIRECT2_MASK) -#define CAU_DIRECT_CAU_DIRECT3_MASK (0xFFFFFFFFU) -#define CAU_DIRECT_CAU_DIRECT3_SHIFT (0U) -#define CAU_DIRECT_CAU_DIRECT3(x) (((uint32_t)(((uint32_t)(x)) << CAU_DIRECT_CAU_DIRECT3_SHIFT)) & CAU_DIRECT_CAU_DIRECT3_MASK) -#define CAU_DIRECT_CAU_DIRECT4_MASK (0xFFFFFFFFU) -#define CAU_DIRECT_CAU_DIRECT4_SHIFT (0U) -#define CAU_DIRECT_CAU_DIRECT4(x) (((uint32_t)(((uint32_t)(x)) << CAU_DIRECT_CAU_DIRECT4_SHIFT)) & CAU_DIRECT_CAU_DIRECT4_MASK) -#define CAU_DIRECT_CAU_DIRECT5_MASK (0xFFFFFFFFU) -#define CAU_DIRECT_CAU_DIRECT5_SHIFT (0U) -#define CAU_DIRECT_CAU_DIRECT5(x) (((uint32_t)(((uint32_t)(x)) << CAU_DIRECT_CAU_DIRECT5_SHIFT)) & CAU_DIRECT_CAU_DIRECT5_MASK) -#define CAU_DIRECT_CAU_DIRECT6_MASK (0xFFFFFFFFU) -#define CAU_DIRECT_CAU_DIRECT6_SHIFT (0U) -#define CAU_DIRECT_CAU_DIRECT6(x) (((uint32_t)(((uint32_t)(x)) << CAU_DIRECT_CAU_DIRECT6_SHIFT)) & CAU_DIRECT_CAU_DIRECT6_MASK) -#define CAU_DIRECT_CAU_DIRECT7_MASK (0xFFFFFFFFU) -#define CAU_DIRECT_CAU_DIRECT7_SHIFT (0U) -#define CAU_DIRECT_CAU_DIRECT7(x) (((uint32_t)(((uint32_t)(x)) << CAU_DIRECT_CAU_DIRECT7_SHIFT)) & CAU_DIRECT_CAU_DIRECT7_MASK) -#define CAU_DIRECT_CAU_DIRECT8_MASK (0xFFFFFFFFU) -#define CAU_DIRECT_CAU_DIRECT8_SHIFT (0U) -#define CAU_DIRECT_CAU_DIRECT8(x) (((uint32_t)(((uint32_t)(x)) << CAU_DIRECT_CAU_DIRECT8_SHIFT)) & CAU_DIRECT_CAU_DIRECT8_MASK) -#define CAU_DIRECT_CAU_DIRECT9_MASK (0xFFFFFFFFU) -#define CAU_DIRECT_CAU_DIRECT9_SHIFT (0U) -#define CAU_DIRECT_CAU_DIRECT9(x) (((uint32_t)(((uint32_t)(x)) << CAU_DIRECT_CAU_DIRECT9_SHIFT)) & CAU_DIRECT_CAU_DIRECT9_MASK) -#define CAU_DIRECT_CAU_DIRECT10_MASK (0xFFFFFFFFU) -#define CAU_DIRECT_CAU_DIRECT10_SHIFT (0U) -#define CAU_DIRECT_CAU_DIRECT10(x) (((uint32_t)(((uint32_t)(x)) << CAU_DIRECT_CAU_DIRECT10_SHIFT)) & CAU_DIRECT_CAU_DIRECT10_MASK) -#define CAU_DIRECT_CAU_DIRECT11_MASK (0xFFFFFFFFU) -#define CAU_DIRECT_CAU_DIRECT11_SHIFT (0U) -#define CAU_DIRECT_CAU_DIRECT11(x) (((uint32_t)(((uint32_t)(x)) << CAU_DIRECT_CAU_DIRECT11_SHIFT)) & CAU_DIRECT_CAU_DIRECT11_MASK) -#define CAU_DIRECT_CAU_DIRECT12_MASK (0xFFFFFFFFU) -#define CAU_DIRECT_CAU_DIRECT12_SHIFT (0U) -#define CAU_DIRECT_CAU_DIRECT12(x) (((uint32_t)(((uint32_t)(x)) << CAU_DIRECT_CAU_DIRECT12_SHIFT)) & CAU_DIRECT_CAU_DIRECT12_MASK) -#define CAU_DIRECT_CAU_DIRECT13_MASK (0xFFFFFFFFU) -#define CAU_DIRECT_CAU_DIRECT13_SHIFT (0U) -#define CAU_DIRECT_CAU_DIRECT13(x) (((uint32_t)(((uint32_t)(x)) << CAU_DIRECT_CAU_DIRECT13_SHIFT)) & CAU_DIRECT_CAU_DIRECT13_MASK) -#define CAU_DIRECT_CAU_DIRECT14_MASK (0xFFFFFFFFU) -#define CAU_DIRECT_CAU_DIRECT14_SHIFT (0U) -#define CAU_DIRECT_CAU_DIRECT14(x) (((uint32_t)(((uint32_t)(x)) << CAU_DIRECT_CAU_DIRECT14_SHIFT)) & CAU_DIRECT_CAU_DIRECT14_MASK) -#define CAU_DIRECT_CAU_DIRECT15_MASK (0xFFFFFFFFU) -#define CAU_DIRECT_CAU_DIRECT15_SHIFT (0U) -#define CAU_DIRECT_CAU_DIRECT15(x) (((uint32_t)(((uint32_t)(x)) << CAU_DIRECT_CAU_DIRECT15_SHIFT)) & CAU_DIRECT_CAU_DIRECT15_MASK) - -/* The count of CAU_DIRECT */ -#define CAU_DIRECT_COUNT (16U) - -/*! @name LDR_CASR - Status register - Load Register command */ -#define CAU_LDR_CASR_IC_MASK (0x1U) -#define CAU_LDR_CASR_IC_SHIFT (0U) -#define CAU_LDR_CASR_IC(x) (((uint32_t)(((uint32_t)(x)) << CAU_LDR_CASR_IC_SHIFT)) & CAU_LDR_CASR_IC_MASK) -#define CAU_LDR_CASR_DPE_MASK (0x2U) -#define CAU_LDR_CASR_DPE_SHIFT (1U) -#define CAU_LDR_CASR_DPE(x) (((uint32_t)(((uint32_t)(x)) << CAU_LDR_CASR_DPE_SHIFT)) & CAU_LDR_CASR_DPE_MASK) -#define CAU_LDR_CASR_VER_MASK (0xF0000000U) -#define CAU_LDR_CASR_VER_SHIFT (28U) -#define CAU_LDR_CASR_VER(x) (((uint32_t)(((uint32_t)(x)) << CAU_LDR_CASR_VER_SHIFT)) & CAU_LDR_CASR_VER_MASK) - -/*! @name LDR_CAA - Accumulator register - Load Register command */ -#define CAU_LDR_CAA_ACC_MASK (0xFFFFFFFFU) -#define CAU_LDR_CAA_ACC_SHIFT (0U) -#define CAU_LDR_CAA_ACC(x) (((uint32_t)(((uint32_t)(x)) << CAU_LDR_CAA_ACC_SHIFT)) & CAU_LDR_CAA_ACC_MASK) - -/*! @name LDR_CA - General Purpose Register 0 - Load Register command..General Purpose Register 8 - Load Register command */ -#define CAU_LDR_CA_CA0_MASK (0xFFFFFFFFU) -#define CAU_LDR_CA_CA0_SHIFT (0U) -#define CAU_LDR_CA_CA0(x) (((uint32_t)(((uint32_t)(x)) << CAU_LDR_CA_CA0_SHIFT)) & CAU_LDR_CA_CA0_MASK) -#define CAU_LDR_CA_CA1_MASK (0xFFFFFFFFU) -#define CAU_LDR_CA_CA1_SHIFT (0U) -#define CAU_LDR_CA_CA1(x) (((uint32_t)(((uint32_t)(x)) << CAU_LDR_CA_CA1_SHIFT)) & CAU_LDR_CA_CA1_MASK) -#define CAU_LDR_CA_CA2_MASK (0xFFFFFFFFU) -#define CAU_LDR_CA_CA2_SHIFT (0U) -#define CAU_LDR_CA_CA2(x) (((uint32_t)(((uint32_t)(x)) << CAU_LDR_CA_CA2_SHIFT)) & CAU_LDR_CA_CA2_MASK) -#define CAU_LDR_CA_CA3_MASK (0xFFFFFFFFU) -#define CAU_LDR_CA_CA3_SHIFT (0U) -#define CAU_LDR_CA_CA3(x) (((uint32_t)(((uint32_t)(x)) << CAU_LDR_CA_CA3_SHIFT)) & CAU_LDR_CA_CA3_MASK) -#define CAU_LDR_CA_CA4_MASK (0xFFFFFFFFU) -#define CAU_LDR_CA_CA4_SHIFT (0U) -#define CAU_LDR_CA_CA4(x) (((uint32_t)(((uint32_t)(x)) << CAU_LDR_CA_CA4_SHIFT)) & CAU_LDR_CA_CA4_MASK) -#define CAU_LDR_CA_CA5_MASK (0xFFFFFFFFU) -#define CAU_LDR_CA_CA5_SHIFT (0U) -#define CAU_LDR_CA_CA5(x) (((uint32_t)(((uint32_t)(x)) << CAU_LDR_CA_CA5_SHIFT)) & CAU_LDR_CA_CA5_MASK) -#define CAU_LDR_CA_CA6_MASK (0xFFFFFFFFU) -#define CAU_LDR_CA_CA6_SHIFT (0U) -#define CAU_LDR_CA_CA6(x) (((uint32_t)(((uint32_t)(x)) << CAU_LDR_CA_CA6_SHIFT)) & CAU_LDR_CA_CA6_MASK) -#define CAU_LDR_CA_CA7_MASK (0xFFFFFFFFU) -#define CAU_LDR_CA_CA7_SHIFT (0U) -#define CAU_LDR_CA_CA7(x) (((uint32_t)(((uint32_t)(x)) << CAU_LDR_CA_CA7_SHIFT)) & CAU_LDR_CA_CA7_MASK) -#define CAU_LDR_CA_CA8_MASK (0xFFFFFFFFU) -#define CAU_LDR_CA_CA8_SHIFT (0U) -#define CAU_LDR_CA_CA8(x) (((uint32_t)(((uint32_t)(x)) << CAU_LDR_CA_CA8_SHIFT)) & CAU_LDR_CA_CA8_MASK) - -/* The count of CAU_LDR_CA */ -#define CAU_LDR_CA_COUNT (9U) - -/*! @name STR_CASR - Status register - Store Register command */ -#define CAU_STR_CASR_IC_MASK (0x1U) -#define CAU_STR_CASR_IC_SHIFT (0U) -#define CAU_STR_CASR_IC(x) (((uint32_t)(((uint32_t)(x)) << CAU_STR_CASR_IC_SHIFT)) & CAU_STR_CASR_IC_MASK) -#define CAU_STR_CASR_DPE_MASK (0x2U) -#define CAU_STR_CASR_DPE_SHIFT (1U) -#define CAU_STR_CASR_DPE(x) (((uint32_t)(((uint32_t)(x)) << CAU_STR_CASR_DPE_SHIFT)) & CAU_STR_CASR_DPE_MASK) -#define CAU_STR_CASR_VER_MASK (0xF0000000U) -#define CAU_STR_CASR_VER_SHIFT (28U) -#define CAU_STR_CASR_VER(x) (((uint32_t)(((uint32_t)(x)) << CAU_STR_CASR_VER_SHIFT)) & CAU_STR_CASR_VER_MASK) - -/*! @name STR_CAA - Accumulator register - Store Register command */ -#define CAU_STR_CAA_ACC_MASK (0xFFFFFFFFU) -#define CAU_STR_CAA_ACC_SHIFT (0U) -#define CAU_STR_CAA_ACC(x) (((uint32_t)(((uint32_t)(x)) << CAU_STR_CAA_ACC_SHIFT)) & CAU_STR_CAA_ACC_MASK) - -/*! @name STR_CA - General Purpose Register 0 - Store Register command..General Purpose Register 8 - Store Register command */ -#define CAU_STR_CA_CA0_MASK (0xFFFFFFFFU) -#define CAU_STR_CA_CA0_SHIFT (0U) -#define CAU_STR_CA_CA0(x) (((uint32_t)(((uint32_t)(x)) << CAU_STR_CA_CA0_SHIFT)) & CAU_STR_CA_CA0_MASK) -#define CAU_STR_CA_CA1_MASK (0xFFFFFFFFU) -#define CAU_STR_CA_CA1_SHIFT (0U) -#define CAU_STR_CA_CA1(x) (((uint32_t)(((uint32_t)(x)) << CAU_STR_CA_CA1_SHIFT)) & CAU_STR_CA_CA1_MASK) -#define CAU_STR_CA_CA2_MASK (0xFFFFFFFFU) -#define CAU_STR_CA_CA2_SHIFT (0U) -#define CAU_STR_CA_CA2(x) (((uint32_t)(((uint32_t)(x)) << CAU_STR_CA_CA2_SHIFT)) & CAU_STR_CA_CA2_MASK) -#define CAU_STR_CA_CA3_MASK (0xFFFFFFFFU) -#define CAU_STR_CA_CA3_SHIFT (0U) -#define CAU_STR_CA_CA3(x) (((uint32_t)(((uint32_t)(x)) << CAU_STR_CA_CA3_SHIFT)) & CAU_STR_CA_CA3_MASK) -#define CAU_STR_CA_CA4_MASK (0xFFFFFFFFU) -#define CAU_STR_CA_CA4_SHIFT (0U) -#define CAU_STR_CA_CA4(x) (((uint32_t)(((uint32_t)(x)) << CAU_STR_CA_CA4_SHIFT)) & CAU_STR_CA_CA4_MASK) -#define CAU_STR_CA_CA5_MASK (0xFFFFFFFFU) -#define CAU_STR_CA_CA5_SHIFT (0U) -#define CAU_STR_CA_CA5(x) (((uint32_t)(((uint32_t)(x)) << CAU_STR_CA_CA5_SHIFT)) & CAU_STR_CA_CA5_MASK) -#define CAU_STR_CA_CA6_MASK (0xFFFFFFFFU) -#define CAU_STR_CA_CA6_SHIFT (0U) -#define CAU_STR_CA_CA6(x) (((uint32_t)(((uint32_t)(x)) << CAU_STR_CA_CA6_SHIFT)) & CAU_STR_CA_CA6_MASK) -#define CAU_STR_CA_CA7_MASK (0xFFFFFFFFU) -#define CAU_STR_CA_CA7_SHIFT (0U) -#define CAU_STR_CA_CA7(x) (((uint32_t)(((uint32_t)(x)) << CAU_STR_CA_CA7_SHIFT)) & CAU_STR_CA_CA7_MASK) -#define CAU_STR_CA_CA8_MASK (0xFFFFFFFFU) -#define CAU_STR_CA_CA8_SHIFT (0U) -#define CAU_STR_CA_CA8(x) (((uint32_t)(((uint32_t)(x)) << CAU_STR_CA_CA8_SHIFT)) & CAU_STR_CA_CA8_MASK) - -/* The count of CAU_STR_CA */ -#define CAU_STR_CA_COUNT (9U) - -/*! @name ADR_CASR - Status register - Add Register command */ -#define CAU_ADR_CASR_IC_MASK (0x1U) -#define CAU_ADR_CASR_IC_SHIFT (0U) -#define CAU_ADR_CASR_IC(x) (((uint32_t)(((uint32_t)(x)) << CAU_ADR_CASR_IC_SHIFT)) & CAU_ADR_CASR_IC_MASK) -#define CAU_ADR_CASR_DPE_MASK (0x2U) -#define CAU_ADR_CASR_DPE_SHIFT (1U) -#define CAU_ADR_CASR_DPE(x) (((uint32_t)(((uint32_t)(x)) << CAU_ADR_CASR_DPE_SHIFT)) & CAU_ADR_CASR_DPE_MASK) -#define CAU_ADR_CASR_VER_MASK (0xF0000000U) -#define CAU_ADR_CASR_VER_SHIFT (28U) -#define CAU_ADR_CASR_VER(x) (((uint32_t)(((uint32_t)(x)) << CAU_ADR_CASR_VER_SHIFT)) & CAU_ADR_CASR_VER_MASK) - -/*! @name ADR_CAA - Accumulator register - Add to register command */ -#define CAU_ADR_CAA_ACC_MASK (0xFFFFFFFFU) -#define CAU_ADR_CAA_ACC_SHIFT (0U) -#define CAU_ADR_CAA_ACC(x) (((uint32_t)(((uint32_t)(x)) << CAU_ADR_CAA_ACC_SHIFT)) & CAU_ADR_CAA_ACC_MASK) - -/*! @name ADR_CA - General Purpose Register 0 - Add to register command..General Purpose Register 8 - Add to register command */ -#define CAU_ADR_CA_CA0_MASK (0xFFFFFFFFU) -#define CAU_ADR_CA_CA0_SHIFT (0U) -#define CAU_ADR_CA_CA0(x) (((uint32_t)(((uint32_t)(x)) << CAU_ADR_CA_CA0_SHIFT)) & CAU_ADR_CA_CA0_MASK) -#define CAU_ADR_CA_CA1_MASK (0xFFFFFFFFU) -#define CAU_ADR_CA_CA1_SHIFT (0U) -#define CAU_ADR_CA_CA1(x) (((uint32_t)(((uint32_t)(x)) << CAU_ADR_CA_CA1_SHIFT)) & CAU_ADR_CA_CA1_MASK) -#define CAU_ADR_CA_CA2_MASK (0xFFFFFFFFU) -#define CAU_ADR_CA_CA2_SHIFT (0U) -#define CAU_ADR_CA_CA2(x) (((uint32_t)(((uint32_t)(x)) << CAU_ADR_CA_CA2_SHIFT)) & CAU_ADR_CA_CA2_MASK) -#define CAU_ADR_CA_CA3_MASK (0xFFFFFFFFU) -#define CAU_ADR_CA_CA3_SHIFT (0U) -#define CAU_ADR_CA_CA3(x) (((uint32_t)(((uint32_t)(x)) << CAU_ADR_CA_CA3_SHIFT)) & CAU_ADR_CA_CA3_MASK) -#define CAU_ADR_CA_CA4_MASK (0xFFFFFFFFU) -#define CAU_ADR_CA_CA4_SHIFT (0U) -#define CAU_ADR_CA_CA4(x) (((uint32_t)(((uint32_t)(x)) << CAU_ADR_CA_CA4_SHIFT)) & CAU_ADR_CA_CA4_MASK) -#define CAU_ADR_CA_CA5_MASK (0xFFFFFFFFU) -#define CAU_ADR_CA_CA5_SHIFT (0U) -#define CAU_ADR_CA_CA5(x) (((uint32_t)(((uint32_t)(x)) << CAU_ADR_CA_CA5_SHIFT)) & CAU_ADR_CA_CA5_MASK) -#define CAU_ADR_CA_CA6_MASK (0xFFFFFFFFU) -#define CAU_ADR_CA_CA6_SHIFT (0U) -#define CAU_ADR_CA_CA6(x) (((uint32_t)(((uint32_t)(x)) << CAU_ADR_CA_CA6_SHIFT)) & CAU_ADR_CA_CA6_MASK) -#define CAU_ADR_CA_CA7_MASK (0xFFFFFFFFU) -#define CAU_ADR_CA_CA7_SHIFT (0U) -#define CAU_ADR_CA_CA7(x) (((uint32_t)(((uint32_t)(x)) << CAU_ADR_CA_CA7_SHIFT)) & CAU_ADR_CA_CA7_MASK) -#define CAU_ADR_CA_CA8_MASK (0xFFFFFFFFU) -#define CAU_ADR_CA_CA8_SHIFT (0U) -#define CAU_ADR_CA_CA8(x) (((uint32_t)(((uint32_t)(x)) << CAU_ADR_CA_CA8_SHIFT)) & CAU_ADR_CA_CA8_MASK) - -/* The count of CAU_ADR_CA */ -#define CAU_ADR_CA_COUNT (9U) - -/*! @name RADR_CASR - Status register - Reverse and Add to Register command */ -#define CAU_RADR_CASR_IC_MASK (0x1U) -#define CAU_RADR_CASR_IC_SHIFT (0U) -#define CAU_RADR_CASR_IC(x) (((uint32_t)(((uint32_t)(x)) << CAU_RADR_CASR_IC_SHIFT)) & CAU_RADR_CASR_IC_MASK) -#define CAU_RADR_CASR_DPE_MASK (0x2U) -#define CAU_RADR_CASR_DPE_SHIFT (1U) -#define CAU_RADR_CASR_DPE(x) (((uint32_t)(((uint32_t)(x)) << CAU_RADR_CASR_DPE_SHIFT)) & CAU_RADR_CASR_DPE_MASK) -#define CAU_RADR_CASR_VER_MASK (0xF0000000U) -#define CAU_RADR_CASR_VER_SHIFT (28U) -#define CAU_RADR_CASR_VER(x) (((uint32_t)(((uint32_t)(x)) << CAU_RADR_CASR_VER_SHIFT)) & CAU_RADR_CASR_VER_MASK) - -/*! @name RADR_CAA - Accumulator register - Reverse and Add to Register command */ -#define CAU_RADR_CAA_ACC_MASK (0xFFFFFFFFU) -#define CAU_RADR_CAA_ACC_SHIFT (0U) -#define CAU_RADR_CAA_ACC(x) (((uint32_t)(((uint32_t)(x)) << CAU_RADR_CAA_ACC_SHIFT)) & CAU_RADR_CAA_ACC_MASK) - -/*! @name RADR_CA - General Purpose Register 0 - Reverse and Add to Register command..General Purpose Register 8 - Reverse and Add to Register command */ -#define CAU_RADR_CA_CA0_MASK (0xFFFFFFFFU) -#define CAU_RADR_CA_CA0_SHIFT (0U) -#define CAU_RADR_CA_CA0(x) (((uint32_t)(((uint32_t)(x)) << CAU_RADR_CA_CA0_SHIFT)) & CAU_RADR_CA_CA0_MASK) -#define CAU_RADR_CA_CA1_MASK (0xFFFFFFFFU) -#define CAU_RADR_CA_CA1_SHIFT (0U) -#define CAU_RADR_CA_CA1(x) (((uint32_t)(((uint32_t)(x)) << CAU_RADR_CA_CA1_SHIFT)) & CAU_RADR_CA_CA1_MASK) -#define CAU_RADR_CA_CA2_MASK (0xFFFFFFFFU) -#define CAU_RADR_CA_CA2_SHIFT (0U) -#define CAU_RADR_CA_CA2(x) (((uint32_t)(((uint32_t)(x)) << CAU_RADR_CA_CA2_SHIFT)) & CAU_RADR_CA_CA2_MASK) -#define CAU_RADR_CA_CA3_MASK (0xFFFFFFFFU) -#define CAU_RADR_CA_CA3_SHIFT (0U) -#define CAU_RADR_CA_CA3(x) (((uint32_t)(((uint32_t)(x)) << CAU_RADR_CA_CA3_SHIFT)) & CAU_RADR_CA_CA3_MASK) -#define CAU_RADR_CA_CA4_MASK (0xFFFFFFFFU) -#define CAU_RADR_CA_CA4_SHIFT (0U) -#define CAU_RADR_CA_CA4(x) (((uint32_t)(((uint32_t)(x)) << CAU_RADR_CA_CA4_SHIFT)) & CAU_RADR_CA_CA4_MASK) -#define CAU_RADR_CA_CA5_MASK (0xFFFFFFFFU) -#define CAU_RADR_CA_CA5_SHIFT (0U) -#define CAU_RADR_CA_CA5(x) (((uint32_t)(((uint32_t)(x)) << CAU_RADR_CA_CA5_SHIFT)) & CAU_RADR_CA_CA5_MASK) -#define CAU_RADR_CA_CA6_MASK (0xFFFFFFFFU) -#define CAU_RADR_CA_CA6_SHIFT (0U) -#define CAU_RADR_CA_CA6(x) (((uint32_t)(((uint32_t)(x)) << CAU_RADR_CA_CA6_SHIFT)) & CAU_RADR_CA_CA6_MASK) -#define CAU_RADR_CA_CA7_MASK (0xFFFFFFFFU) -#define CAU_RADR_CA_CA7_SHIFT (0U) -#define CAU_RADR_CA_CA7(x) (((uint32_t)(((uint32_t)(x)) << CAU_RADR_CA_CA7_SHIFT)) & CAU_RADR_CA_CA7_MASK) -#define CAU_RADR_CA_CA8_MASK (0xFFFFFFFFU) -#define CAU_RADR_CA_CA8_SHIFT (0U) -#define CAU_RADR_CA_CA8(x) (((uint32_t)(((uint32_t)(x)) << CAU_RADR_CA_CA8_SHIFT)) & CAU_RADR_CA_CA8_MASK) - -/* The count of CAU_RADR_CA */ -#define CAU_RADR_CA_COUNT (9U) - -/*! @name XOR_CASR - Status register - Exclusive Or command */ -#define CAU_XOR_CASR_IC_MASK (0x1U) -#define CAU_XOR_CASR_IC_SHIFT (0U) -#define CAU_XOR_CASR_IC(x) (((uint32_t)(((uint32_t)(x)) << CAU_XOR_CASR_IC_SHIFT)) & CAU_XOR_CASR_IC_MASK) -#define CAU_XOR_CASR_DPE_MASK (0x2U) -#define CAU_XOR_CASR_DPE_SHIFT (1U) -#define CAU_XOR_CASR_DPE(x) (((uint32_t)(((uint32_t)(x)) << CAU_XOR_CASR_DPE_SHIFT)) & CAU_XOR_CASR_DPE_MASK) -#define CAU_XOR_CASR_VER_MASK (0xF0000000U) -#define CAU_XOR_CASR_VER_SHIFT (28U) -#define CAU_XOR_CASR_VER(x) (((uint32_t)(((uint32_t)(x)) << CAU_XOR_CASR_VER_SHIFT)) & CAU_XOR_CASR_VER_MASK) - -/*! @name XOR_CAA - Accumulator register - Exclusive Or command */ -#define CAU_XOR_CAA_ACC_MASK (0xFFFFFFFFU) -#define CAU_XOR_CAA_ACC_SHIFT (0U) -#define CAU_XOR_CAA_ACC(x) (((uint32_t)(((uint32_t)(x)) << CAU_XOR_CAA_ACC_SHIFT)) & CAU_XOR_CAA_ACC_MASK) - -/*! @name XOR_CA - General Purpose Register 0 - Exclusive Or command..General Purpose Register 8 - Exclusive Or command */ -#define CAU_XOR_CA_CA0_MASK (0xFFFFFFFFU) -#define CAU_XOR_CA_CA0_SHIFT (0U) -#define CAU_XOR_CA_CA0(x) (((uint32_t)(((uint32_t)(x)) << CAU_XOR_CA_CA0_SHIFT)) & CAU_XOR_CA_CA0_MASK) -#define CAU_XOR_CA_CA1_MASK (0xFFFFFFFFU) -#define CAU_XOR_CA_CA1_SHIFT (0U) -#define CAU_XOR_CA_CA1(x) (((uint32_t)(((uint32_t)(x)) << CAU_XOR_CA_CA1_SHIFT)) & CAU_XOR_CA_CA1_MASK) -#define CAU_XOR_CA_CA2_MASK (0xFFFFFFFFU) -#define CAU_XOR_CA_CA2_SHIFT (0U) -#define CAU_XOR_CA_CA2(x) (((uint32_t)(((uint32_t)(x)) << CAU_XOR_CA_CA2_SHIFT)) & CAU_XOR_CA_CA2_MASK) -#define CAU_XOR_CA_CA3_MASK (0xFFFFFFFFU) -#define CAU_XOR_CA_CA3_SHIFT (0U) -#define CAU_XOR_CA_CA3(x) (((uint32_t)(((uint32_t)(x)) << CAU_XOR_CA_CA3_SHIFT)) & CAU_XOR_CA_CA3_MASK) -#define CAU_XOR_CA_CA4_MASK (0xFFFFFFFFU) -#define CAU_XOR_CA_CA4_SHIFT (0U) -#define CAU_XOR_CA_CA4(x) (((uint32_t)(((uint32_t)(x)) << CAU_XOR_CA_CA4_SHIFT)) & CAU_XOR_CA_CA4_MASK) -#define CAU_XOR_CA_CA5_MASK (0xFFFFFFFFU) -#define CAU_XOR_CA_CA5_SHIFT (0U) -#define CAU_XOR_CA_CA5(x) (((uint32_t)(((uint32_t)(x)) << CAU_XOR_CA_CA5_SHIFT)) & CAU_XOR_CA_CA5_MASK) -#define CAU_XOR_CA_CA6_MASK (0xFFFFFFFFU) -#define CAU_XOR_CA_CA6_SHIFT (0U) -#define CAU_XOR_CA_CA6(x) (((uint32_t)(((uint32_t)(x)) << CAU_XOR_CA_CA6_SHIFT)) & CAU_XOR_CA_CA6_MASK) -#define CAU_XOR_CA_CA7_MASK (0xFFFFFFFFU) -#define CAU_XOR_CA_CA7_SHIFT (0U) -#define CAU_XOR_CA_CA7(x) (((uint32_t)(((uint32_t)(x)) << CAU_XOR_CA_CA7_SHIFT)) & CAU_XOR_CA_CA7_MASK) -#define CAU_XOR_CA_CA8_MASK (0xFFFFFFFFU) -#define CAU_XOR_CA_CA8_SHIFT (0U) -#define CAU_XOR_CA_CA8(x) (((uint32_t)(((uint32_t)(x)) << CAU_XOR_CA_CA8_SHIFT)) & CAU_XOR_CA_CA8_MASK) - -/* The count of CAU_XOR_CA */ -#define CAU_XOR_CA_COUNT (9U) - -/*! @name ROTL_CASR - Status register - Rotate Left command */ -#define CAU_ROTL_CASR_IC_MASK (0x1U) -#define CAU_ROTL_CASR_IC_SHIFT (0U) -#define CAU_ROTL_CASR_IC(x) (((uint32_t)(((uint32_t)(x)) << CAU_ROTL_CASR_IC_SHIFT)) & CAU_ROTL_CASR_IC_MASK) -#define CAU_ROTL_CASR_DPE_MASK (0x2U) -#define CAU_ROTL_CASR_DPE_SHIFT (1U) -#define CAU_ROTL_CASR_DPE(x) (((uint32_t)(((uint32_t)(x)) << CAU_ROTL_CASR_DPE_SHIFT)) & CAU_ROTL_CASR_DPE_MASK) -#define CAU_ROTL_CASR_VER_MASK (0xF0000000U) -#define CAU_ROTL_CASR_VER_SHIFT (28U) -#define CAU_ROTL_CASR_VER(x) (((uint32_t)(((uint32_t)(x)) << CAU_ROTL_CASR_VER_SHIFT)) & CAU_ROTL_CASR_VER_MASK) - -/*! @name ROTL_CAA - Accumulator register - Rotate Left command */ -#define CAU_ROTL_CAA_ACC_MASK (0xFFFFFFFFU) -#define CAU_ROTL_CAA_ACC_SHIFT (0U) -#define CAU_ROTL_CAA_ACC(x) (((uint32_t)(((uint32_t)(x)) << CAU_ROTL_CAA_ACC_SHIFT)) & CAU_ROTL_CAA_ACC_MASK) - -/*! @name ROTL_CA - General Purpose Register 0 - Rotate Left command..General Purpose Register 8 - Rotate Left command */ -#define CAU_ROTL_CA_CA0_MASK (0xFFFFFFFFU) -#define CAU_ROTL_CA_CA0_SHIFT (0U) -#define CAU_ROTL_CA_CA0(x) (((uint32_t)(((uint32_t)(x)) << CAU_ROTL_CA_CA0_SHIFT)) & CAU_ROTL_CA_CA0_MASK) -#define CAU_ROTL_CA_CA1_MASK (0xFFFFFFFFU) -#define CAU_ROTL_CA_CA1_SHIFT (0U) -#define CAU_ROTL_CA_CA1(x) (((uint32_t)(((uint32_t)(x)) << CAU_ROTL_CA_CA1_SHIFT)) & CAU_ROTL_CA_CA1_MASK) -#define CAU_ROTL_CA_CA2_MASK (0xFFFFFFFFU) -#define CAU_ROTL_CA_CA2_SHIFT (0U) -#define CAU_ROTL_CA_CA2(x) (((uint32_t)(((uint32_t)(x)) << CAU_ROTL_CA_CA2_SHIFT)) & CAU_ROTL_CA_CA2_MASK) -#define CAU_ROTL_CA_CA3_MASK (0xFFFFFFFFU) -#define CAU_ROTL_CA_CA3_SHIFT (0U) -#define CAU_ROTL_CA_CA3(x) (((uint32_t)(((uint32_t)(x)) << CAU_ROTL_CA_CA3_SHIFT)) & CAU_ROTL_CA_CA3_MASK) -#define CAU_ROTL_CA_CA4_MASK (0xFFFFFFFFU) -#define CAU_ROTL_CA_CA4_SHIFT (0U) -#define CAU_ROTL_CA_CA4(x) (((uint32_t)(((uint32_t)(x)) << CAU_ROTL_CA_CA4_SHIFT)) & CAU_ROTL_CA_CA4_MASK) -#define CAU_ROTL_CA_CA5_MASK (0xFFFFFFFFU) -#define CAU_ROTL_CA_CA5_SHIFT (0U) -#define CAU_ROTL_CA_CA5(x) (((uint32_t)(((uint32_t)(x)) << CAU_ROTL_CA_CA5_SHIFT)) & CAU_ROTL_CA_CA5_MASK) -#define CAU_ROTL_CA_CA6_MASK (0xFFFFFFFFU) -#define CAU_ROTL_CA_CA6_SHIFT (0U) -#define CAU_ROTL_CA_CA6(x) (((uint32_t)(((uint32_t)(x)) << CAU_ROTL_CA_CA6_SHIFT)) & CAU_ROTL_CA_CA6_MASK) -#define CAU_ROTL_CA_CA7_MASK (0xFFFFFFFFU) -#define CAU_ROTL_CA_CA7_SHIFT (0U) -#define CAU_ROTL_CA_CA7(x) (((uint32_t)(((uint32_t)(x)) << CAU_ROTL_CA_CA7_SHIFT)) & CAU_ROTL_CA_CA7_MASK) -#define CAU_ROTL_CA_CA8_MASK (0xFFFFFFFFU) -#define CAU_ROTL_CA_CA8_SHIFT (0U) -#define CAU_ROTL_CA_CA8(x) (((uint32_t)(((uint32_t)(x)) << CAU_ROTL_CA_CA8_SHIFT)) & CAU_ROTL_CA_CA8_MASK) - -/* The count of CAU_ROTL_CA */ -#define CAU_ROTL_CA_COUNT (9U) - -/*! @name AESC_CASR - Status register - AES Column Operation command */ -#define CAU_AESC_CASR_IC_MASK (0x1U) -#define CAU_AESC_CASR_IC_SHIFT (0U) -#define CAU_AESC_CASR_IC(x) (((uint32_t)(((uint32_t)(x)) << CAU_AESC_CASR_IC_SHIFT)) & CAU_AESC_CASR_IC_MASK) -#define CAU_AESC_CASR_DPE_MASK (0x2U) -#define CAU_AESC_CASR_DPE_SHIFT (1U) -#define CAU_AESC_CASR_DPE(x) (((uint32_t)(((uint32_t)(x)) << CAU_AESC_CASR_DPE_SHIFT)) & CAU_AESC_CASR_DPE_MASK) -#define CAU_AESC_CASR_VER_MASK (0xF0000000U) -#define CAU_AESC_CASR_VER_SHIFT (28U) -#define CAU_AESC_CASR_VER(x) (((uint32_t)(((uint32_t)(x)) << CAU_AESC_CASR_VER_SHIFT)) & CAU_AESC_CASR_VER_MASK) - -/*! @name AESC_CAA - Accumulator register - AES Column Operation command */ -#define CAU_AESC_CAA_ACC_MASK (0xFFFFFFFFU) -#define CAU_AESC_CAA_ACC_SHIFT (0U) -#define CAU_AESC_CAA_ACC(x) (((uint32_t)(((uint32_t)(x)) << CAU_AESC_CAA_ACC_SHIFT)) & CAU_AESC_CAA_ACC_MASK) - -/*! @name AESC_CA - General Purpose Register 0 - AES Column Operation command..General Purpose Register 8 - AES Column Operation command */ -#define CAU_AESC_CA_CA0_MASK (0xFFFFFFFFU) -#define CAU_AESC_CA_CA0_SHIFT (0U) -#define CAU_AESC_CA_CA0(x) (((uint32_t)(((uint32_t)(x)) << CAU_AESC_CA_CA0_SHIFT)) & CAU_AESC_CA_CA0_MASK) -#define CAU_AESC_CA_CA1_MASK (0xFFFFFFFFU) -#define CAU_AESC_CA_CA1_SHIFT (0U) -#define CAU_AESC_CA_CA1(x) (((uint32_t)(((uint32_t)(x)) << CAU_AESC_CA_CA1_SHIFT)) & CAU_AESC_CA_CA1_MASK) -#define CAU_AESC_CA_CA2_MASK (0xFFFFFFFFU) -#define CAU_AESC_CA_CA2_SHIFT (0U) -#define CAU_AESC_CA_CA2(x) (((uint32_t)(((uint32_t)(x)) << CAU_AESC_CA_CA2_SHIFT)) & CAU_AESC_CA_CA2_MASK) -#define CAU_AESC_CA_CA3_MASK (0xFFFFFFFFU) -#define CAU_AESC_CA_CA3_SHIFT (0U) -#define CAU_AESC_CA_CA3(x) (((uint32_t)(((uint32_t)(x)) << CAU_AESC_CA_CA3_SHIFT)) & CAU_AESC_CA_CA3_MASK) -#define CAU_AESC_CA_CA4_MASK (0xFFFFFFFFU) -#define CAU_AESC_CA_CA4_SHIFT (0U) -#define CAU_AESC_CA_CA4(x) (((uint32_t)(((uint32_t)(x)) << CAU_AESC_CA_CA4_SHIFT)) & CAU_AESC_CA_CA4_MASK) -#define CAU_AESC_CA_CA5_MASK (0xFFFFFFFFU) -#define CAU_AESC_CA_CA5_SHIFT (0U) -#define CAU_AESC_CA_CA5(x) (((uint32_t)(((uint32_t)(x)) << CAU_AESC_CA_CA5_SHIFT)) & CAU_AESC_CA_CA5_MASK) -#define CAU_AESC_CA_CA6_MASK (0xFFFFFFFFU) -#define CAU_AESC_CA_CA6_SHIFT (0U) -#define CAU_AESC_CA_CA6(x) (((uint32_t)(((uint32_t)(x)) << CAU_AESC_CA_CA6_SHIFT)) & CAU_AESC_CA_CA6_MASK) -#define CAU_AESC_CA_CA7_MASK (0xFFFFFFFFU) -#define CAU_AESC_CA_CA7_SHIFT (0U) -#define CAU_AESC_CA_CA7(x) (((uint32_t)(((uint32_t)(x)) << CAU_AESC_CA_CA7_SHIFT)) & CAU_AESC_CA_CA7_MASK) -#define CAU_AESC_CA_CA8_MASK (0xFFFFFFFFU) -#define CAU_AESC_CA_CA8_SHIFT (0U) -#define CAU_AESC_CA_CA8(x) (((uint32_t)(((uint32_t)(x)) << CAU_AESC_CA_CA8_SHIFT)) & CAU_AESC_CA_CA8_MASK) - -/* The count of CAU_AESC_CA */ -#define CAU_AESC_CA_COUNT (9U) - -/*! @name AESIC_CASR - Status register - AES Inverse Column Operation command */ -#define CAU_AESIC_CASR_IC_MASK (0x1U) -#define CAU_AESIC_CASR_IC_SHIFT (0U) -#define CAU_AESIC_CASR_IC(x) (((uint32_t)(((uint32_t)(x)) << CAU_AESIC_CASR_IC_SHIFT)) & CAU_AESIC_CASR_IC_MASK) -#define CAU_AESIC_CASR_DPE_MASK (0x2U) -#define CAU_AESIC_CASR_DPE_SHIFT (1U) -#define CAU_AESIC_CASR_DPE(x) (((uint32_t)(((uint32_t)(x)) << CAU_AESIC_CASR_DPE_SHIFT)) & CAU_AESIC_CASR_DPE_MASK) -#define CAU_AESIC_CASR_VER_MASK (0xF0000000U) -#define CAU_AESIC_CASR_VER_SHIFT (28U) -#define CAU_AESIC_CASR_VER(x) (((uint32_t)(((uint32_t)(x)) << CAU_AESIC_CASR_VER_SHIFT)) & CAU_AESIC_CASR_VER_MASK) - -/*! @name AESIC_CAA - Accumulator register - AES Inverse Column Operation command */ -#define CAU_AESIC_CAA_ACC_MASK (0xFFFFFFFFU) -#define CAU_AESIC_CAA_ACC_SHIFT (0U) -#define CAU_AESIC_CAA_ACC(x) (((uint32_t)(((uint32_t)(x)) << CAU_AESIC_CAA_ACC_SHIFT)) & CAU_AESIC_CAA_ACC_MASK) - -/*! @name AESIC_CA - General Purpose Register 0 - AES Inverse Column Operation command..General Purpose Register 8 - AES Inverse Column Operation command */ -#define CAU_AESIC_CA_CA0_MASK (0xFFFFFFFFU) -#define CAU_AESIC_CA_CA0_SHIFT (0U) -#define CAU_AESIC_CA_CA0(x) (((uint32_t)(((uint32_t)(x)) << CAU_AESIC_CA_CA0_SHIFT)) & CAU_AESIC_CA_CA0_MASK) -#define CAU_AESIC_CA_CA1_MASK (0xFFFFFFFFU) -#define CAU_AESIC_CA_CA1_SHIFT (0U) -#define CAU_AESIC_CA_CA1(x) (((uint32_t)(((uint32_t)(x)) << CAU_AESIC_CA_CA1_SHIFT)) & CAU_AESIC_CA_CA1_MASK) -#define CAU_AESIC_CA_CA2_MASK (0xFFFFFFFFU) -#define CAU_AESIC_CA_CA2_SHIFT (0U) -#define CAU_AESIC_CA_CA2(x) (((uint32_t)(((uint32_t)(x)) << CAU_AESIC_CA_CA2_SHIFT)) & CAU_AESIC_CA_CA2_MASK) -#define CAU_AESIC_CA_CA3_MASK (0xFFFFFFFFU) -#define CAU_AESIC_CA_CA3_SHIFT (0U) -#define CAU_AESIC_CA_CA3(x) (((uint32_t)(((uint32_t)(x)) << CAU_AESIC_CA_CA3_SHIFT)) & CAU_AESIC_CA_CA3_MASK) -#define CAU_AESIC_CA_CA4_MASK (0xFFFFFFFFU) -#define CAU_AESIC_CA_CA4_SHIFT (0U) -#define CAU_AESIC_CA_CA4(x) (((uint32_t)(((uint32_t)(x)) << CAU_AESIC_CA_CA4_SHIFT)) & CAU_AESIC_CA_CA4_MASK) -#define CAU_AESIC_CA_CA5_MASK (0xFFFFFFFFU) -#define CAU_AESIC_CA_CA5_SHIFT (0U) -#define CAU_AESIC_CA_CA5(x) (((uint32_t)(((uint32_t)(x)) << CAU_AESIC_CA_CA5_SHIFT)) & CAU_AESIC_CA_CA5_MASK) -#define CAU_AESIC_CA_CA6_MASK (0xFFFFFFFFU) -#define CAU_AESIC_CA_CA6_SHIFT (0U) -#define CAU_AESIC_CA_CA6(x) (((uint32_t)(((uint32_t)(x)) << CAU_AESIC_CA_CA6_SHIFT)) & CAU_AESIC_CA_CA6_MASK) -#define CAU_AESIC_CA_CA7_MASK (0xFFFFFFFFU) -#define CAU_AESIC_CA_CA7_SHIFT (0U) -#define CAU_AESIC_CA_CA7(x) (((uint32_t)(((uint32_t)(x)) << CAU_AESIC_CA_CA7_SHIFT)) & CAU_AESIC_CA_CA7_MASK) -#define CAU_AESIC_CA_CA8_MASK (0xFFFFFFFFU) -#define CAU_AESIC_CA_CA8_SHIFT (0U) -#define CAU_AESIC_CA_CA8(x) (((uint32_t)(((uint32_t)(x)) << CAU_AESIC_CA_CA8_SHIFT)) & CAU_AESIC_CA_CA8_MASK) - -/* The count of CAU_AESIC_CA */ -#define CAU_AESIC_CA_COUNT (9U) - - -/*! - * @} - */ /* end of group CAU_Register_Masks */ - - -/* CAU - Peripheral instance base addresses */ -/** Peripheral CAU base address */ -#define CAU_BASE (0xE0081000u) -/** Peripheral CAU base pointer */ -#define CAU ((CAU_Type *)CAU_BASE) -/** Array initializer of CAU peripheral base addresses */ -#define CAU_BASE_ADDRS { CAU_BASE } -/** Array initializer of CAU peripheral base pointers */ -#define CAU_BASE_PTRS { CAU } - -/*! - * @} - */ /* end of group CAU_Peripheral_Access_Layer */ - - -/* ---------------------------------------------------------------------------- - -- CMP Peripheral Access Layer - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup CMP_Peripheral_Access_Layer CMP Peripheral Access Layer - * @{ - */ - -/** CMP - Register Layout Typedef */ -typedef struct { - __IO uint8_t CR0; /**< CMP Control Register 0, offset: 0x0 */ - __IO uint8_t CR1; /**< CMP Control Register 1, offset: 0x1 */ - __IO uint8_t FPR; /**< CMP Filter Period Register, offset: 0x2 */ - __IO uint8_t SCR; /**< CMP Status and Control Register, offset: 0x3 */ - __IO uint8_t DACCR; /**< DAC Control Register, offset: 0x4 */ - __IO uint8_t MUXCR; /**< MUX Control Register, offset: 0x5 */ -} CMP_Type; - -/* ---------------------------------------------------------------------------- - -- CMP Register Masks - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup CMP_Register_Masks CMP Register Masks - * @{ - */ - -/*! @name CR0 - CMP Control Register 0 */ -#define CMP_CR0_HYSTCTR_MASK (0x3U) -#define CMP_CR0_HYSTCTR_SHIFT (0U) -#define CMP_CR0_HYSTCTR(x) (((uint8_t)(((uint8_t)(x)) << CMP_CR0_HYSTCTR_SHIFT)) & CMP_CR0_HYSTCTR_MASK) -#define CMP_CR0_FILTER_CNT_MASK (0x70U) -#define CMP_CR0_FILTER_CNT_SHIFT (4U) -#define CMP_CR0_FILTER_CNT(x) (((uint8_t)(((uint8_t)(x)) << CMP_CR0_FILTER_CNT_SHIFT)) & CMP_CR0_FILTER_CNT_MASK) - -/*! @name CR1 - CMP Control Register 1 */ -#define CMP_CR1_EN_MASK (0x1U) -#define CMP_CR1_EN_SHIFT (0U) -#define CMP_CR1_EN(x) (((uint8_t)(((uint8_t)(x)) << CMP_CR1_EN_SHIFT)) & CMP_CR1_EN_MASK) -#define CMP_CR1_OPE_MASK (0x2U) -#define CMP_CR1_OPE_SHIFT (1U) -#define CMP_CR1_OPE(x) (((uint8_t)(((uint8_t)(x)) << CMP_CR1_OPE_SHIFT)) & CMP_CR1_OPE_MASK) -#define CMP_CR1_COS_MASK (0x4U) -#define CMP_CR1_COS_SHIFT (2U) -#define CMP_CR1_COS(x) (((uint8_t)(((uint8_t)(x)) << CMP_CR1_COS_SHIFT)) & CMP_CR1_COS_MASK) -#define CMP_CR1_INV_MASK (0x8U) -#define CMP_CR1_INV_SHIFT (3U) -#define CMP_CR1_INV(x) (((uint8_t)(((uint8_t)(x)) << CMP_CR1_INV_SHIFT)) & CMP_CR1_INV_MASK) -#define CMP_CR1_PMODE_MASK (0x10U) -#define CMP_CR1_PMODE_SHIFT (4U) -#define CMP_CR1_PMODE(x) (((uint8_t)(((uint8_t)(x)) << CMP_CR1_PMODE_SHIFT)) & CMP_CR1_PMODE_MASK) -#define CMP_CR1_WE_MASK (0x40U) -#define CMP_CR1_WE_SHIFT (6U) -#define CMP_CR1_WE(x) (((uint8_t)(((uint8_t)(x)) << CMP_CR1_WE_SHIFT)) & CMP_CR1_WE_MASK) -#define CMP_CR1_SE_MASK (0x80U) -#define CMP_CR1_SE_SHIFT (7U) -#define CMP_CR1_SE(x) (((uint8_t)(((uint8_t)(x)) << CMP_CR1_SE_SHIFT)) & CMP_CR1_SE_MASK) - -/*! @name FPR - CMP Filter Period Register */ -#define CMP_FPR_FILT_PER_MASK (0xFFU) -#define CMP_FPR_FILT_PER_SHIFT (0U) -#define CMP_FPR_FILT_PER(x) (((uint8_t)(((uint8_t)(x)) << CMP_FPR_FILT_PER_SHIFT)) & CMP_FPR_FILT_PER_MASK) - -/*! @name SCR - CMP Status and Control Register */ -#define CMP_SCR_COUT_MASK (0x1U) -#define CMP_SCR_COUT_SHIFT (0U) -#define CMP_SCR_COUT(x) (((uint8_t)(((uint8_t)(x)) << CMP_SCR_COUT_SHIFT)) & CMP_SCR_COUT_MASK) -#define CMP_SCR_CFF_MASK (0x2U) -#define CMP_SCR_CFF_SHIFT (1U) -#define CMP_SCR_CFF(x) (((uint8_t)(((uint8_t)(x)) << CMP_SCR_CFF_SHIFT)) & CMP_SCR_CFF_MASK) -#define CMP_SCR_CFR_MASK (0x4U) -#define CMP_SCR_CFR_SHIFT (2U) -#define CMP_SCR_CFR(x) (((uint8_t)(((uint8_t)(x)) << CMP_SCR_CFR_SHIFT)) & CMP_SCR_CFR_MASK) -#define CMP_SCR_IEF_MASK (0x8U) -#define CMP_SCR_IEF_SHIFT (3U) -#define CMP_SCR_IEF(x) (((uint8_t)(((uint8_t)(x)) << CMP_SCR_IEF_SHIFT)) & CMP_SCR_IEF_MASK) -#define CMP_SCR_IER_MASK (0x10U) -#define CMP_SCR_IER_SHIFT (4U) -#define CMP_SCR_IER(x) (((uint8_t)(((uint8_t)(x)) << CMP_SCR_IER_SHIFT)) & CMP_SCR_IER_MASK) -#define CMP_SCR_DMAEN_MASK (0x40U) -#define CMP_SCR_DMAEN_SHIFT (6U) -#define CMP_SCR_DMAEN(x) (((uint8_t)(((uint8_t)(x)) << CMP_SCR_DMAEN_SHIFT)) & CMP_SCR_DMAEN_MASK) - -/*! @name DACCR - DAC Control Register */ -#define CMP_DACCR_VOSEL_MASK (0x3FU) -#define CMP_DACCR_VOSEL_SHIFT (0U) -#define CMP_DACCR_VOSEL(x) (((uint8_t)(((uint8_t)(x)) << CMP_DACCR_VOSEL_SHIFT)) & CMP_DACCR_VOSEL_MASK) -#define CMP_DACCR_VRSEL_MASK (0x40U) -#define CMP_DACCR_VRSEL_SHIFT (6U) -#define CMP_DACCR_VRSEL(x) (((uint8_t)(((uint8_t)(x)) << CMP_DACCR_VRSEL_SHIFT)) & CMP_DACCR_VRSEL_MASK) -#define CMP_DACCR_DACEN_MASK (0x80U) -#define CMP_DACCR_DACEN_SHIFT (7U) -#define CMP_DACCR_DACEN(x) (((uint8_t)(((uint8_t)(x)) << CMP_DACCR_DACEN_SHIFT)) & CMP_DACCR_DACEN_MASK) - -/*! @name MUXCR - MUX Control Register */ -#define CMP_MUXCR_MSEL_MASK (0x7U) -#define CMP_MUXCR_MSEL_SHIFT (0U) -#define CMP_MUXCR_MSEL(x) (((uint8_t)(((uint8_t)(x)) << CMP_MUXCR_MSEL_SHIFT)) & CMP_MUXCR_MSEL_MASK) -#define CMP_MUXCR_PSEL_MASK (0x38U) -#define CMP_MUXCR_PSEL_SHIFT (3U) -#define CMP_MUXCR_PSEL(x) (((uint8_t)(((uint8_t)(x)) << CMP_MUXCR_PSEL_SHIFT)) & CMP_MUXCR_PSEL_MASK) -#define CMP_MUXCR_PSTM_MASK (0x80U) -#define CMP_MUXCR_PSTM_SHIFT (7U) -#define CMP_MUXCR_PSTM(x) (((uint8_t)(((uint8_t)(x)) << CMP_MUXCR_PSTM_SHIFT)) & CMP_MUXCR_PSTM_MASK) - - -/*! - * @} - */ /* end of group CMP_Register_Masks */ - - -/* CMP - Peripheral instance base addresses */ -/** Peripheral CMP0 base address */ -#define CMP0_BASE (0x40073000u) -/** Peripheral CMP0 base pointer */ -#define CMP0 ((CMP_Type *)CMP0_BASE) -/** Peripheral CMP1 base address */ -#define CMP1_BASE (0x40073008u) -/** Peripheral CMP1 base pointer */ -#define CMP1 ((CMP_Type *)CMP1_BASE) -/** Peripheral CMP2 base address */ -#define CMP2_BASE (0x40073010u) -/** Peripheral CMP2 base pointer */ -#define CMP2 ((CMP_Type *)CMP2_BASE) -/** Array initializer of CMP peripheral base addresses */ -#define CMP_BASE_ADDRS { CMP0_BASE, CMP1_BASE, CMP2_BASE } -/** Array initializer of CMP peripheral base pointers */ -#define CMP_BASE_PTRS { CMP0, CMP1, CMP2 } -/** Interrupt vectors for the CMP peripheral type */ -#define CMP_IRQS { CMP0_IRQn, CMP1_IRQn, CMP2_IRQn } - -/*! - * @} - */ /* end of group CMP_Peripheral_Access_Layer */ - - -/* ---------------------------------------------------------------------------- - -- CMT Peripheral Access Layer - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup CMT_Peripheral_Access_Layer CMT Peripheral Access Layer - * @{ - */ - -/** CMT - Register Layout Typedef */ -typedef struct { - __IO uint8_t CGH1; /**< CMT Carrier Generator High Data Register 1, offset: 0x0 */ - __IO uint8_t CGL1; /**< CMT Carrier Generator Low Data Register 1, offset: 0x1 */ - __IO uint8_t CGH2; /**< CMT Carrier Generator High Data Register 2, offset: 0x2 */ - __IO uint8_t CGL2; /**< CMT Carrier Generator Low Data Register 2, offset: 0x3 */ - __IO uint8_t OC; /**< CMT Output Control Register, offset: 0x4 */ - __IO uint8_t MSC; /**< CMT Modulator Status and Control Register, offset: 0x5 */ - __IO uint8_t CMD1; /**< CMT Modulator Data Register Mark High, offset: 0x6 */ - __IO uint8_t CMD2; /**< CMT Modulator Data Register Mark Low, offset: 0x7 */ - __IO uint8_t CMD3; /**< CMT Modulator Data Register Space High, offset: 0x8 */ - __IO uint8_t CMD4; /**< CMT Modulator Data Register Space Low, offset: 0x9 */ - __IO uint8_t PPS; /**< CMT Primary Prescaler Register, offset: 0xA */ - __IO uint8_t DMA; /**< CMT Direct Memory Access Register, offset: 0xB */ -} CMT_Type; - -/* ---------------------------------------------------------------------------- - -- CMT Register Masks - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup CMT_Register_Masks CMT Register Masks - * @{ - */ - -/*! @name CGH1 - CMT Carrier Generator High Data Register 1 */ -#define CMT_CGH1_PH_MASK (0xFFU) -#define CMT_CGH1_PH_SHIFT (0U) -#define CMT_CGH1_PH(x) (((uint8_t)(((uint8_t)(x)) << CMT_CGH1_PH_SHIFT)) & CMT_CGH1_PH_MASK) - -/*! @name CGL1 - CMT Carrier Generator Low Data Register 1 */ -#define CMT_CGL1_PL_MASK (0xFFU) -#define CMT_CGL1_PL_SHIFT (0U) -#define CMT_CGL1_PL(x) (((uint8_t)(((uint8_t)(x)) << CMT_CGL1_PL_SHIFT)) & CMT_CGL1_PL_MASK) - -/*! @name CGH2 - CMT Carrier Generator High Data Register 2 */ -#define CMT_CGH2_SH_MASK (0xFFU) -#define CMT_CGH2_SH_SHIFT (0U) -#define CMT_CGH2_SH(x) (((uint8_t)(((uint8_t)(x)) << CMT_CGH2_SH_SHIFT)) & CMT_CGH2_SH_MASK) - -/*! @name CGL2 - CMT Carrier Generator Low Data Register 2 */ -#define CMT_CGL2_SL_MASK (0xFFU) -#define CMT_CGL2_SL_SHIFT (0U) -#define CMT_CGL2_SL(x) (((uint8_t)(((uint8_t)(x)) << CMT_CGL2_SL_SHIFT)) & CMT_CGL2_SL_MASK) - -/*! @name OC - CMT Output Control Register */ -#define CMT_OC_IROPEN_MASK (0x20U) -#define CMT_OC_IROPEN_SHIFT (5U) -#define CMT_OC_IROPEN(x) (((uint8_t)(((uint8_t)(x)) << CMT_OC_IROPEN_SHIFT)) & CMT_OC_IROPEN_MASK) -#define CMT_OC_CMTPOL_MASK (0x40U) -#define CMT_OC_CMTPOL_SHIFT (6U) -#define CMT_OC_CMTPOL(x) (((uint8_t)(((uint8_t)(x)) << CMT_OC_CMTPOL_SHIFT)) & CMT_OC_CMTPOL_MASK) -#define CMT_OC_IROL_MASK (0x80U) -#define CMT_OC_IROL_SHIFT (7U) -#define CMT_OC_IROL(x) (((uint8_t)(((uint8_t)(x)) << CMT_OC_IROL_SHIFT)) & CMT_OC_IROL_MASK) - -/*! @name MSC - CMT Modulator Status and Control Register */ -#define CMT_MSC_MCGEN_MASK (0x1U) -#define CMT_MSC_MCGEN_SHIFT (0U) -#define CMT_MSC_MCGEN(x) (((uint8_t)(((uint8_t)(x)) << CMT_MSC_MCGEN_SHIFT)) & CMT_MSC_MCGEN_MASK) -#define CMT_MSC_EOCIE_MASK (0x2U) -#define CMT_MSC_EOCIE_SHIFT (1U) -#define CMT_MSC_EOCIE(x) (((uint8_t)(((uint8_t)(x)) << CMT_MSC_EOCIE_SHIFT)) & CMT_MSC_EOCIE_MASK) -#define CMT_MSC_FSK_MASK (0x4U) -#define CMT_MSC_FSK_SHIFT (2U) -#define CMT_MSC_FSK(x) (((uint8_t)(((uint8_t)(x)) << CMT_MSC_FSK_SHIFT)) & CMT_MSC_FSK_MASK) -#define CMT_MSC_BASE_MASK (0x8U) -#define CMT_MSC_BASE_SHIFT (3U) -#define CMT_MSC_BASE(x) (((uint8_t)(((uint8_t)(x)) << CMT_MSC_BASE_SHIFT)) & CMT_MSC_BASE_MASK) -#define CMT_MSC_EXSPC_MASK (0x10U) -#define CMT_MSC_EXSPC_SHIFT (4U) -#define CMT_MSC_EXSPC(x) (((uint8_t)(((uint8_t)(x)) << CMT_MSC_EXSPC_SHIFT)) & CMT_MSC_EXSPC_MASK) -#define CMT_MSC_CMTDIV_MASK (0x60U) -#define CMT_MSC_CMTDIV_SHIFT (5U) -#define CMT_MSC_CMTDIV(x) (((uint8_t)(((uint8_t)(x)) << CMT_MSC_CMTDIV_SHIFT)) & CMT_MSC_CMTDIV_MASK) -#define CMT_MSC_EOCF_MASK (0x80U) -#define CMT_MSC_EOCF_SHIFT (7U) -#define CMT_MSC_EOCF(x) (((uint8_t)(((uint8_t)(x)) << CMT_MSC_EOCF_SHIFT)) & CMT_MSC_EOCF_MASK) - -/*! @name CMD1 - CMT Modulator Data Register Mark High */ -#define CMT_CMD1_MB_MASK (0xFFU) -#define CMT_CMD1_MB_SHIFT (0U) -#define CMT_CMD1_MB(x) (((uint8_t)(((uint8_t)(x)) << CMT_CMD1_MB_SHIFT)) & CMT_CMD1_MB_MASK) - -/*! @name CMD2 - CMT Modulator Data Register Mark Low */ -#define CMT_CMD2_MB_MASK (0xFFU) -#define CMT_CMD2_MB_SHIFT (0U) -#define CMT_CMD2_MB(x) (((uint8_t)(((uint8_t)(x)) << CMT_CMD2_MB_SHIFT)) & CMT_CMD2_MB_MASK) - -/*! @name CMD3 - CMT Modulator Data Register Space High */ -#define CMT_CMD3_SB_MASK (0xFFU) -#define CMT_CMD3_SB_SHIFT (0U) -#define CMT_CMD3_SB(x) (((uint8_t)(((uint8_t)(x)) << CMT_CMD3_SB_SHIFT)) & CMT_CMD3_SB_MASK) - -/*! @name CMD4 - CMT Modulator Data Register Space Low */ -#define CMT_CMD4_SB_MASK (0xFFU) -#define CMT_CMD4_SB_SHIFT (0U) -#define CMT_CMD4_SB(x) (((uint8_t)(((uint8_t)(x)) << CMT_CMD4_SB_SHIFT)) & CMT_CMD4_SB_MASK) - -/*! @name PPS - CMT Primary Prescaler Register */ -#define CMT_PPS_PPSDIV_MASK (0xFU) -#define CMT_PPS_PPSDIV_SHIFT (0U) -#define CMT_PPS_PPSDIV(x) (((uint8_t)(((uint8_t)(x)) << CMT_PPS_PPSDIV_SHIFT)) & CMT_PPS_PPSDIV_MASK) - -/*! @name DMA - CMT Direct Memory Access Register */ -#define CMT_DMA_DMA_MASK (0x1U) -#define CMT_DMA_DMA_SHIFT (0U) -#define CMT_DMA_DMA(x) (((uint8_t)(((uint8_t)(x)) << CMT_DMA_DMA_SHIFT)) & CMT_DMA_DMA_MASK) - - -/*! - * @} - */ /* end of group CMT_Register_Masks */ - - -/* CMT - Peripheral instance base addresses */ -/** Peripheral CMT base address */ -#define CMT_BASE (0x40062000u) -/** Peripheral CMT base pointer */ -#define CMT ((CMT_Type *)CMT_BASE) -/** Array initializer of CMT peripheral base addresses */ -#define CMT_BASE_ADDRS { CMT_BASE } -/** Array initializer of CMT peripheral base pointers */ -#define CMT_BASE_PTRS { CMT } -/** Interrupt vectors for the CMT peripheral type */ -#define CMT_IRQS { CMT_IRQn } - -/*! - * @} - */ /* end of group CMT_Peripheral_Access_Layer */ - - -/* ---------------------------------------------------------------------------- - -- CRC Peripheral Access Layer - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup CRC_Peripheral_Access_Layer CRC Peripheral Access Layer - * @{ - */ - -/** CRC - Register Layout Typedef */ -typedef struct { - union { /* offset: 0x0 */ - struct { /* offset: 0x0 */ - __IO uint16_t DATAL; /**< CRC_DATAL register., offset: 0x0 */ - __IO uint16_t DATAH; /**< CRC_DATAH register., offset: 0x2 */ - } ACCESS16BIT; - __IO uint32_t DATA; /**< CRC Data register, offset: 0x0 */ - struct { /* offset: 0x0 */ - __IO uint8_t DATALL; /**< CRC_DATALL register., offset: 0x0 */ - __IO uint8_t DATALU; /**< CRC_DATALU register., offset: 0x1 */ - __IO uint8_t DATAHL; /**< CRC_DATAHL register., offset: 0x2 */ - __IO uint8_t DATAHU; /**< CRC_DATAHU register., offset: 0x3 */ - } ACCESS8BIT; - }; - union { /* offset: 0x4 */ - struct { /* offset: 0x4 */ - __IO uint16_t GPOLYL; /**< CRC_GPOLYL register., offset: 0x4 */ - __IO uint16_t GPOLYH; /**< CRC_GPOLYH register., offset: 0x6 */ - } GPOLY_ACCESS16BIT; - __IO uint32_t GPOLY; /**< CRC Polynomial register, offset: 0x4 */ - struct { /* offset: 0x4 */ - __IO uint8_t GPOLYLL; /**< CRC_GPOLYLL register., offset: 0x4 */ - __IO uint8_t GPOLYLU; /**< CRC_GPOLYLU register., offset: 0x5 */ - __IO uint8_t GPOLYHL; /**< CRC_GPOLYHL register., offset: 0x6 */ - __IO uint8_t GPOLYHU; /**< CRC_GPOLYHU register., offset: 0x7 */ - } GPOLY_ACCESS8BIT; - }; - union { /* offset: 0x8 */ - __IO uint32_t CTRL; /**< CRC Control register, offset: 0x8 */ - struct { /* offset: 0x8 */ - uint8_t RESERVED_0[3]; - __IO uint8_t CTRLHU; /**< CRC_CTRLHU register., offset: 0xB */ - } CTRL_ACCESS8BIT; - }; -} CRC_Type; - -/* ---------------------------------------------------------------------------- - -- CRC Register Masks - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup CRC_Register_Masks CRC Register Masks - * @{ - */ - -/*! @name DATAL - CRC_DATAL register. */ -#define CRC_DATAL_DATAL_MASK (0xFFFFU) -#define CRC_DATAL_DATAL_SHIFT (0U) -#define CRC_DATAL_DATAL(x) (((uint16_t)(((uint16_t)(x)) << CRC_DATAL_DATAL_SHIFT)) & CRC_DATAL_DATAL_MASK) - -/*! @name DATAH - CRC_DATAH register. */ -#define CRC_DATAH_DATAH_MASK (0xFFFFU) -#define CRC_DATAH_DATAH_SHIFT (0U) -#define CRC_DATAH_DATAH(x) (((uint16_t)(((uint16_t)(x)) << CRC_DATAH_DATAH_SHIFT)) & CRC_DATAH_DATAH_MASK) - -/*! @name DATA - CRC Data register */ -#define CRC_DATA_LL_MASK (0xFFU) -#define CRC_DATA_LL_SHIFT (0U) -#define CRC_DATA_LL(x) (((uint32_t)(((uint32_t)(x)) << CRC_DATA_LL_SHIFT)) & CRC_DATA_LL_MASK) -#define CRC_DATA_LU_MASK (0xFF00U) -#define CRC_DATA_LU_SHIFT (8U) -#define CRC_DATA_LU(x) (((uint32_t)(((uint32_t)(x)) << CRC_DATA_LU_SHIFT)) & CRC_DATA_LU_MASK) -#define CRC_DATA_HL_MASK (0xFF0000U) -#define CRC_DATA_HL_SHIFT (16U) -#define CRC_DATA_HL(x) (((uint32_t)(((uint32_t)(x)) << CRC_DATA_HL_SHIFT)) & CRC_DATA_HL_MASK) -#define CRC_DATA_HU_MASK (0xFF000000U) -#define CRC_DATA_HU_SHIFT (24U) -#define CRC_DATA_HU(x) (((uint32_t)(((uint32_t)(x)) << CRC_DATA_HU_SHIFT)) & CRC_DATA_HU_MASK) - -/*! @name DATALL - CRC_DATALL register. */ -#define CRC_DATALL_DATALL_MASK (0xFFU) -#define CRC_DATALL_DATALL_SHIFT (0U) -#define CRC_DATALL_DATALL(x) (((uint8_t)(((uint8_t)(x)) << CRC_DATALL_DATALL_SHIFT)) & CRC_DATALL_DATALL_MASK) - -/*! @name DATALU - CRC_DATALU register. */ -#define CRC_DATALU_DATALU_MASK (0xFFU) -#define CRC_DATALU_DATALU_SHIFT (0U) -#define CRC_DATALU_DATALU(x) (((uint8_t)(((uint8_t)(x)) << CRC_DATALU_DATALU_SHIFT)) & CRC_DATALU_DATALU_MASK) - -/*! @name DATAHL - CRC_DATAHL register. */ -#define CRC_DATAHL_DATAHL_MASK (0xFFU) -#define CRC_DATAHL_DATAHL_SHIFT (0U) -#define CRC_DATAHL_DATAHL(x) (((uint8_t)(((uint8_t)(x)) << CRC_DATAHL_DATAHL_SHIFT)) & CRC_DATAHL_DATAHL_MASK) - -/*! @name DATAHU - CRC_DATAHU register. */ -#define CRC_DATAHU_DATAHU_MASK (0xFFU) -#define CRC_DATAHU_DATAHU_SHIFT (0U) -#define CRC_DATAHU_DATAHU(x) (((uint8_t)(((uint8_t)(x)) << CRC_DATAHU_DATAHU_SHIFT)) & CRC_DATAHU_DATAHU_MASK) - -/*! @name GPOLYL - CRC_GPOLYL register. */ -#define CRC_GPOLYL_GPOLYL_MASK (0xFFFFU) -#define CRC_GPOLYL_GPOLYL_SHIFT (0U) -#define CRC_GPOLYL_GPOLYL(x) (((uint16_t)(((uint16_t)(x)) << CRC_GPOLYL_GPOLYL_SHIFT)) & CRC_GPOLYL_GPOLYL_MASK) - -/*! @name GPOLYH - CRC_GPOLYH register. */ -#define CRC_GPOLYH_GPOLYH_MASK (0xFFFFU) -#define CRC_GPOLYH_GPOLYH_SHIFT (0U) -#define CRC_GPOLYH_GPOLYH(x) (((uint16_t)(((uint16_t)(x)) << CRC_GPOLYH_GPOLYH_SHIFT)) & CRC_GPOLYH_GPOLYH_MASK) - -/*! @name GPOLY - CRC Polynomial register */ -#define CRC_GPOLY_LOW_MASK (0xFFFFU) -#define CRC_GPOLY_LOW_SHIFT (0U) -#define CRC_GPOLY_LOW(x) (((uint32_t)(((uint32_t)(x)) << CRC_GPOLY_LOW_SHIFT)) & CRC_GPOLY_LOW_MASK) -#define CRC_GPOLY_HIGH_MASK (0xFFFF0000U) -#define CRC_GPOLY_HIGH_SHIFT (16U) -#define CRC_GPOLY_HIGH(x) (((uint32_t)(((uint32_t)(x)) << CRC_GPOLY_HIGH_SHIFT)) & CRC_GPOLY_HIGH_MASK) - -/*! @name GPOLYLL - CRC_GPOLYLL register. */ -#define CRC_GPOLYLL_GPOLYLL_MASK (0xFFU) -#define CRC_GPOLYLL_GPOLYLL_SHIFT (0U) -#define CRC_GPOLYLL_GPOLYLL(x) (((uint8_t)(((uint8_t)(x)) << CRC_GPOLYLL_GPOLYLL_SHIFT)) & CRC_GPOLYLL_GPOLYLL_MASK) - -/*! @name GPOLYLU - CRC_GPOLYLU register. */ -#define CRC_GPOLYLU_GPOLYLU_MASK (0xFFU) -#define CRC_GPOLYLU_GPOLYLU_SHIFT (0U) -#define CRC_GPOLYLU_GPOLYLU(x) (((uint8_t)(((uint8_t)(x)) << CRC_GPOLYLU_GPOLYLU_SHIFT)) & CRC_GPOLYLU_GPOLYLU_MASK) - -/*! @name GPOLYHL - CRC_GPOLYHL register. */ -#define CRC_GPOLYHL_GPOLYHL_MASK (0xFFU) -#define CRC_GPOLYHL_GPOLYHL_SHIFT (0U) -#define CRC_GPOLYHL_GPOLYHL(x) (((uint8_t)(((uint8_t)(x)) << CRC_GPOLYHL_GPOLYHL_SHIFT)) & CRC_GPOLYHL_GPOLYHL_MASK) - -/*! @name GPOLYHU - CRC_GPOLYHU register. */ -#define CRC_GPOLYHU_GPOLYHU_MASK (0xFFU) -#define CRC_GPOLYHU_GPOLYHU_SHIFT (0U) -#define CRC_GPOLYHU_GPOLYHU(x) (((uint8_t)(((uint8_t)(x)) << CRC_GPOLYHU_GPOLYHU_SHIFT)) & CRC_GPOLYHU_GPOLYHU_MASK) - -/*! @name CTRL - CRC Control register */ -#define CRC_CTRL_TCRC_MASK (0x1000000U) -#define CRC_CTRL_TCRC_SHIFT (24U) -#define CRC_CTRL_TCRC(x) (((uint32_t)(((uint32_t)(x)) << CRC_CTRL_TCRC_SHIFT)) & CRC_CTRL_TCRC_MASK) -#define CRC_CTRL_WAS_MASK (0x2000000U) -#define CRC_CTRL_WAS_SHIFT (25U) -#define CRC_CTRL_WAS(x) (((uint32_t)(((uint32_t)(x)) << CRC_CTRL_WAS_SHIFT)) & CRC_CTRL_WAS_MASK) -#define CRC_CTRL_FXOR_MASK (0x4000000U) -#define CRC_CTRL_FXOR_SHIFT (26U) -#define CRC_CTRL_FXOR(x) (((uint32_t)(((uint32_t)(x)) << CRC_CTRL_FXOR_SHIFT)) & CRC_CTRL_FXOR_MASK) -#define CRC_CTRL_TOTR_MASK (0x30000000U) -#define CRC_CTRL_TOTR_SHIFT (28U) -#define CRC_CTRL_TOTR(x) (((uint32_t)(((uint32_t)(x)) << CRC_CTRL_TOTR_SHIFT)) & CRC_CTRL_TOTR_MASK) -#define CRC_CTRL_TOT_MASK (0xC0000000U) -#define CRC_CTRL_TOT_SHIFT (30U) -#define CRC_CTRL_TOT(x) (((uint32_t)(((uint32_t)(x)) << CRC_CTRL_TOT_SHIFT)) & CRC_CTRL_TOT_MASK) - -/*! @name CTRLHU - CRC_CTRLHU register. */ -#define CRC_CTRLHU_TCRC_MASK (0x1U) -#define CRC_CTRLHU_TCRC_SHIFT (0U) -#define CRC_CTRLHU_TCRC(x) (((uint8_t)(((uint8_t)(x)) << CRC_CTRLHU_TCRC_SHIFT)) & CRC_CTRLHU_TCRC_MASK) -#define CRC_CTRLHU_WAS_MASK (0x2U) -#define CRC_CTRLHU_WAS_SHIFT (1U) -#define CRC_CTRLHU_WAS(x) (((uint8_t)(((uint8_t)(x)) << CRC_CTRLHU_WAS_SHIFT)) & CRC_CTRLHU_WAS_MASK) -#define CRC_CTRLHU_FXOR_MASK (0x4U) -#define CRC_CTRLHU_FXOR_SHIFT (2U) -#define CRC_CTRLHU_FXOR(x) (((uint8_t)(((uint8_t)(x)) << CRC_CTRLHU_FXOR_SHIFT)) & CRC_CTRLHU_FXOR_MASK) -#define CRC_CTRLHU_TOTR_MASK (0x30U) -#define CRC_CTRLHU_TOTR_SHIFT (4U) -#define CRC_CTRLHU_TOTR(x) (((uint8_t)(((uint8_t)(x)) << CRC_CTRLHU_TOTR_SHIFT)) & CRC_CTRLHU_TOTR_MASK) -#define CRC_CTRLHU_TOT_MASK (0xC0U) -#define CRC_CTRLHU_TOT_SHIFT (6U) -#define CRC_CTRLHU_TOT(x) (((uint8_t)(((uint8_t)(x)) << CRC_CTRLHU_TOT_SHIFT)) & CRC_CTRLHU_TOT_MASK) - - -/*! - * @} - */ /* end of group CRC_Register_Masks */ - - -/* CRC - Peripheral instance base addresses */ -/** Peripheral CRC base address */ -#define CRC_BASE (0x40032000u) -/** Peripheral CRC base pointer */ -#define CRC0 ((CRC_Type *)CRC_BASE) -/** Array initializer of CRC peripheral base addresses */ -#define CRC_BASE_ADDRS { CRC_BASE } -/** Array initializer of CRC peripheral base pointers */ -#define CRC_BASE_PTRS { CRC0 } - -/*! - * @} - */ /* end of group CRC_Peripheral_Access_Layer */ - - -/* ---------------------------------------------------------------------------- - -- DAC Peripheral Access Layer - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup DAC_Peripheral_Access_Layer DAC Peripheral Access Layer - * @{ - */ - -/** DAC - Register Layout Typedef */ -typedef struct { - struct { /* offset: 0x0, array step: 0x2 */ - __IO uint8_t DATL; /**< DAC Data Low Register, array offset: 0x0, array step: 0x2 */ - __IO uint8_t DATH; /**< DAC Data High Register, array offset: 0x1, array step: 0x2 */ - } DAT[16]; - __IO uint8_t SR; /**< DAC Status Register, offset: 0x20 */ - __IO uint8_t C0; /**< DAC Control Register, offset: 0x21 */ - __IO uint8_t C1; /**< DAC Control Register 1, offset: 0x22 */ - __IO uint8_t C2; /**< DAC Control Register 2, offset: 0x23 */ -} DAC_Type; - -/* ---------------------------------------------------------------------------- - -- DAC Register Masks - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup DAC_Register_Masks DAC Register Masks - * @{ - */ - -/*! @name DATL - DAC Data Low Register */ -#define DAC_DATL_DATA0_MASK (0xFFU) -#define DAC_DATL_DATA0_SHIFT (0U) -#define DAC_DATL_DATA0(x) (((uint8_t)(((uint8_t)(x)) << DAC_DATL_DATA0_SHIFT)) & DAC_DATL_DATA0_MASK) - -/* The count of DAC_DATL */ -#define DAC_DATL_COUNT (16U) - -/*! @name DATH - DAC Data High Register */ -#define DAC_DATH_DATA1_MASK (0xFU) -#define DAC_DATH_DATA1_SHIFT (0U) -#define DAC_DATH_DATA1(x) (((uint8_t)(((uint8_t)(x)) << DAC_DATH_DATA1_SHIFT)) & DAC_DATH_DATA1_MASK) - -/* The count of DAC_DATH */ -#define DAC_DATH_COUNT (16U) - -/*! @name SR - DAC Status Register */ -#define DAC_SR_DACBFRPBF_MASK (0x1U) -#define DAC_SR_DACBFRPBF_SHIFT (0U) -#define DAC_SR_DACBFRPBF(x) (((uint8_t)(((uint8_t)(x)) << DAC_SR_DACBFRPBF_SHIFT)) & DAC_SR_DACBFRPBF_MASK) -#define DAC_SR_DACBFRPTF_MASK (0x2U) -#define DAC_SR_DACBFRPTF_SHIFT (1U) -#define DAC_SR_DACBFRPTF(x) (((uint8_t)(((uint8_t)(x)) << DAC_SR_DACBFRPTF_SHIFT)) & DAC_SR_DACBFRPTF_MASK) -#define DAC_SR_DACBFWMF_MASK (0x4U) -#define DAC_SR_DACBFWMF_SHIFT (2U) -#define DAC_SR_DACBFWMF(x) (((uint8_t)(((uint8_t)(x)) << DAC_SR_DACBFWMF_SHIFT)) & DAC_SR_DACBFWMF_MASK) - -/*! @name C0 - DAC Control Register */ -#define DAC_C0_DACBBIEN_MASK (0x1U) -#define DAC_C0_DACBBIEN_SHIFT (0U) -#define DAC_C0_DACBBIEN(x) (((uint8_t)(((uint8_t)(x)) << DAC_C0_DACBBIEN_SHIFT)) & DAC_C0_DACBBIEN_MASK) -#define DAC_C0_DACBTIEN_MASK (0x2U) -#define DAC_C0_DACBTIEN_SHIFT (1U) -#define DAC_C0_DACBTIEN(x) (((uint8_t)(((uint8_t)(x)) << DAC_C0_DACBTIEN_SHIFT)) & DAC_C0_DACBTIEN_MASK) -#define DAC_C0_DACBWIEN_MASK (0x4U) -#define DAC_C0_DACBWIEN_SHIFT (2U) -#define DAC_C0_DACBWIEN(x) (((uint8_t)(((uint8_t)(x)) << DAC_C0_DACBWIEN_SHIFT)) & DAC_C0_DACBWIEN_MASK) -#define DAC_C0_LPEN_MASK (0x8U) -#define DAC_C0_LPEN_SHIFT (3U) -#define DAC_C0_LPEN(x) (((uint8_t)(((uint8_t)(x)) << DAC_C0_LPEN_SHIFT)) & DAC_C0_LPEN_MASK) -#define DAC_C0_DACSWTRG_MASK (0x10U) -#define DAC_C0_DACSWTRG_SHIFT (4U) -#define DAC_C0_DACSWTRG(x) (((uint8_t)(((uint8_t)(x)) << DAC_C0_DACSWTRG_SHIFT)) & DAC_C0_DACSWTRG_MASK) -#define DAC_C0_DACTRGSEL_MASK (0x20U) -#define DAC_C0_DACTRGSEL_SHIFT (5U) -#define DAC_C0_DACTRGSEL(x) (((uint8_t)(((uint8_t)(x)) << DAC_C0_DACTRGSEL_SHIFT)) & DAC_C0_DACTRGSEL_MASK) -#define DAC_C0_DACRFS_MASK (0x40U) -#define DAC_C0_DACRFS_SHIFT (6U) -#define DAC_C0_DACRFS(x) (((uint8_t)(((uint8_t)(x)) << DAC_C0_DACRFS_SHIFT)) & DAC_C0_DACRFS_MASK) -#define DAC_C0_DACEN_MASK (0x80U) -#define DAC_C0_DACEN_SHIFT (7U) -#define DAC_C0_DACEN(x) (((uint8_t)(((uint8_t)(x)) << DAC_C0_DACEN_SHIFT)) & DAC_C0_DACEN_MASK) - -/*! @name C1 - DAC Control Register 1 */ -#define DAC_C1_DACBFEN_MASK (0x1U) -#define DAC_C1_DACBFEN_SHIFT (0U) -#define DAC_C1_DACBFEN(x) (((uint8_t)(((uint8_t)(x)) << DAC_C1_DACBFEN_SHIFT)) & DAC_C1_DACBFEN_MASK) -#define DAC_C1_DACBFMD_MASK (0x6U) -#define DAC_C1_DACBFMD_SHIFT (1U) -#define DAC_C1_DACBFMD(x) (((uint8_t)(((uint8_t)(x)) << DAC_C1_DACBFMD_SHIFT)) & DAC_C1_DACBFMD_MASK) -#define DAC_C1_DACBFWM_MASK (0x18U) -#define DAC_C1_DACBFWM_SHIFT (3U) -#define DAC_C1_DACBFWM(x) (((uint8_t)(((uint8_t)(x)) << DAC_C1_DACBFWM_SHIFT)) & DAC_C1_DACBFWM_MASK) -#define DAC_C1_DMAEN_MASK (0x80U) -#define DAC_C1_DMAEN_SHIFT (7U) -#define DAC_C1_DMAEN(x) (((uint8_t)(((uint8_t)(x)) << DAC_C1_DMAEN_SHIFT)) & DAC_C1_DMAEN_MASK) - -/*! @name C2 - DAC Control Register 2 */ -#define DAC_C2_DACBFUP_MASK (0xFU) -#define DAC_C2_DACBFUP_SHIFT (0U) -#define DAC_C2_DACBFUP(x) (((uint8_t)(((uint8_t)(x)) << DAC_C2_DACBFUP_SHIFT)) & DAC_C2_DACBFUP_MASK) -#define DAC_C2_DACBFRP_MASK (0xF0U) -#define DAC_C2_DACBFRP_SHIFT (4U) -#define DAC_C2_DACBFRP(x) (((uint8_t)(((uint8_t)(x)) << DAC_C2_DACBFRP_SHIFT)) & DAC_C2_DACBFRP_MASK) - - -/*! - * @} - */ /* end of group DAC_Register_Masks */ - - -/* DAC - Peripheral instance base addresses */ -/** Peripheral DAC0 base address */ -#define DAC0_BASE (0x400CC000u) -/** Peripheral DAC0 base pointer */ -#define DAC0 ((DAC_Type *)DAC0_BASE) -/** Peripheral DAC1 base address */ -#define DAC1_BASE (0x400CD000u) -/** Peripheral DAC1 base pointer */ -#define DAC1 ((DAC_Type *)DAC1_BASE) -/** Array initializer of DAC peripheral base addresses */ -#define DAC_BASE_ADDRS { DAC0_BASE, DAC1_BASE } -/** Array initializer of DAC peripheral base pointers */ -#define DAC_BASE_PTRS { DAC0, DAC1 } -/** Interrupt vectors for the DAC peripheral type */ -#define DAC_IRQS { DAC0_IRQn, DAC1_IRQn } - -/*! - * @} - */ /* end of group DAC_Peripheral_Access_Layer */ - - -/* ---------------------------------------------------------------------------- - -- DMA Peripheral Access Layer - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup DMA_Peripheral_Access_Layer DMA Peripheral Access Layer - * @{ - */ - -/** DMA - Register Layout Typedef */ -typedef struct { - __IO uint32_t CR; /**< Control Register, offset: 0x0 */ - __I uint32_t ES; /**< Error Status Register, offset: 0x4 */ - uint8_t RESERVED_0[4]; - __IO uint32_t ERQ; /**< Enable Request Register, offset: 0xC */ - uint8_t RESERVED_1[4]; - __IO uint32_t EEI; /**< Enable Error Interrupt Register, offset: 0x14 */ - __O uint8_t CEEI; /**< Clear Enable Error Interrupt Register, offset: 0x18 */ - __O uint8_t SEEI; /**< Set Enable Error Interrupt Register, offset: 0x19 */ - __O uint8_t CERQ; /**< Clear Enable Request Register, offset: 0x1A */ - __O uint8_t SERQ; /**< Set Enable Request Register, offset: 0x1B */ - __O uint8_t CDNE; /**< Clear DONE Status Bit Register, offset: 0x1C */ - __O uint8_t SSRT; /**< Set START Bit Register, offset: 0x1D */ - __O uint8_t CERR; /**< Clear Error Register, offset: 0x1E */ - __O uint8_t CINT; /**< Clear Interrupt Request Register, offset: 0x1F */ - uint8_t RESERVED_2[4]; - __IO uint32_t INT; /**< Interrupt Request Register, offset: 0x24 */ - uint8_t RESERVED_3[4]; - __IO uint32_t ERR; /**< Error Register, offset: 0x2C */ - uint8_t RESERVED_4[4]; - __I uint32_t HRS; /**< Hardware Request Status Register, offset: 0x34 */ - uint8_t RESERVED_5[200]; - __IO uint8_t DCHPRI3; /**< Channel n Priority Register, offset: 0x100 */ - __IO uint8_t DCHPRI2; /**< Channel n Priority Register, offset: 0x101 */ - __IO uint8_t DCHPRI1; /**< Channel n Priority Register, offset: 0x102 */ - __IO uint8_t DCHPRI0; /**< Channel n Priority Register, offset: 0x103 */ - __IO uint8_t DCHPRI7; /**< Channel n Priority Register, offset: 0x104 */ - __IO uint8_t DCHPRI6; /**< Channel n Priority Register, offset: 0x105 */ - __IO uint8_t DCHPRI5; /**< Channel n Priority Register, offset: 0x106 */ - __IO uint8_t DCHPRI4; /**< Channel n Priority Register, offset: 0x107 */ - __IO uint8_t DCHPRI11; /**< Channel n Priority Register, offset: 0x108 */ - __IO uint8_t DCHPRI10; /**< Channel n Priority Register, offset: 0x109 */ - __IO uint8_t DCHPRI9; /**< Channel n Priority Register, offset: 0x10A */ - __IO uint8_t DCHPRI8; /**< Channel n Priority Register, offset: 0x10B */ - __IO uint8_t DCHPRI15; /**< Channel n Priority Register, offset: 0x10C */ - __IO uint8_t DCHPRI14; /**< Channel n Priority Register, offset: 0x10D */ - __IO uint8_t DCHPRI13; /**< Channel n Priority Register, offset: 0x10E */ - __IO uint8_t DCHPRI12; /**< Channel n Priority Register, offset: 0x10F */ - uint8_t RESERVED_6[3824]; - struct { /* offset: 0x1000, array step: 0x20 */ - __IO uint32_t SADDR; /**< TCD Source Address, array offset: 0x1000, array step: 0x20 */ - __IO uint16_t SOFF; /**< TCD Signed Source Address Offset, array offset: 0x1004, array step: 0x20 */ - __IO uint16_t ATTR; /**< TCD Transfer Attributes, array offset: 0x1006, array step: 0x20 */ - union { /* offset: 0x1008, array step: 0x20 */ - __IO uint32_t NBYTES_MLNO; /**< TCD Minor Byte Count (Minor Loop Disabled), array offset: 0x1008, array step: 0x20 */ - __IO uint32_t NBYTES_MLOFFNO; /**< TCD Signed Minor Loop Offset (Minor Loop Enabled and Offset Disabled), array offset: 0x1008, array step: 0x20 */ - __IO uint32_t NBYTES_MLOFFYES; /**< TCD Signed Minor Loop Offset (Minor Loop and Offset Enabled), array offset: 0x1008, array step: 0x20 */ - }; - __IO uint32_t SLAST; /**< TCD Last Source Address Adjustment, array offset: 0x100C, array step: 0x20 */ - __IO uint32_t DADDR; /**< TCD Destination Address, array offset: 0x1010, array step: 0x20 */ - __IO uint16_t DOFF; /**< TCD Signed Destination Address Offset, array offset: 0x1014, array step: 0x20 */ - union { /* offset: 0x1016, array step: 0x20 */ - __IO uint16_t CITER_ELINKNO; /**< TCD Current Minor Loop Link, Major Loop Count (Channel Linking Disabled), array offset: 0x1016, array step: 0x20 */ - __IO uint16_t CITER_ELINKYES; /**< TCD Current Minor Loop Link, Major Loop Count (Channel Linking Enabled), array offset: 0x1016, array step: 0x20 */ - }; - __IO uint32_t DLAST_SGA; /**< TCD Last Destination Address Adjustment/Scatter Gather Address, array offset: 0x1018, array step: 0x20 */ - __IO uint16_t CSR; /**< TCD Control and Status, array offset: 0x101C, array step: 0x20 */ - union { /* offset: 0x101E, array step: 0x20 */ - __IO uint16_t BITER_ELINKNO; /**< TCD Beginning Minor Loop Link, Major Loop Count (Channel Linking Disabled), array offset: 0x101E, array step: 0x20 */ - __IO uint16_t BITER_ELINKYES; /**< TCD Beginning Minor Loop Link, Major Loop Count (Channel Linking Enabled), array offset: 0x101E, array step: 0x20 */ - }; - } TCD[16]; -} DMA_Type; - -/* ---------------------------------------------------------------------------- - -- DMA Register Masks - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup DMA_Register_Masks DMA Register Masks - * @{ - */ - -/*! @name CR - Control Register */ -#define DMA_CR_EDBG_MASK (0x2U) -#define DMA_CR_EDBG_SHIFT (1U) -#define DMA_CR_EDBG(x) (((uint32_t)(((uint32_t)(x)) << DMA_CR_EDBG_SHIFT)) & DMA_CR_EDBG_MASK) -#define DMA_CR_ERCA_MASK (0x4U) -#define DMA_CR_ERCA_SHIFT (2U) -#define DMA_CR_ERCA(x) (((uint32_t)(((uint32_t)(x)) << DMA_CR_ERCA_SHIFT)) & DMA_CR_ERCA_MASK) -#define DMA_CR_HOE_MASK (0x10U) -#define DMA_CR_HOE_SHIFT (4U) -#define DMA_CR_HOE(x) (((uint32_t)(((uint32_t)(x)) << DMA_CR_HOE_SHIFT)) & DMA_CR_HOE_MASK) -#define DMA_CR_HALT_MASK (0x20U) -#define DMA_CR_HALT_SHIFT (5U) -#define DMA_CR_HALT(x) (((uint32_t)(((uint32_t)(x)) << DMA_CR_HALT_SHIFT)) & DMA_CR_HALT_MASK) -#define DMA_CR_CLM_MASK (0x40U) -#define DMA_CR_CLM_SHIFT (6U) -#define DMA_CR_CLM(x) (((uint32_t)(((uint32_t)(x)) << DMA_CR_CLM_SHIFT)) & DMA_CR_CLM_MASK) -#define DMA_CR_EMLM_MASK (0x80U) -#define DMA_CR_EMLM_SHIFT (7U) -#define DMA_CR_EMLM(x) (((uint32_t)(((uint32_t)(x)) << DMA_CR_EMLM_SHIFT)) & DMA_CR_EMLM_MASK) -#define DMA_CR_ECX_MASK (0x10000U) -#define DMA_CR_ECX_SHIFT (16U) -#define DMA_CR_ECX(x) (((uint32_t)(((uint32_t)(x)) << DMA_CR_ECX_SHIFT)) & DMA_CR_ECX_MASK) -#define DMA_CR_CX_MASK (0x20000U) -#define DMA_CR_CX_SHIFT (17U) -#define DMA_CR_CX(x) (((uint32_t)(((uint32_t)(x)) << DMA_CR_CX_SHIFT)) & DMA_CR_CX_MASK) - -/*! @name ES - Error Status Register */ -#define DMA_ES_DBE_MASK (0x1U) -#define DMA_ES_DBE_SHIFT (0U) -#define DMA_ES_DBE(x) (((uint32_t)(((uint32_t)(x)) << DMA_ES_DBE_SHIFT)) & DMA_ES_DBE_MASK) -#define DMA_ES_SBE_MASK (0x2U) -#define DMA_ES_SBE_SHIFT (1U) -#define DMA_ES_SBE(x) (((uint32_t)(((uint32_t)(x)) << DMA_ES_SBE_SHIFT)) & DMA_ES_SBE_MASK) -#define DMA_ES_SGE_MASK (0x4U) -#define DMA_ES_SGE_SHIFT (2U) -#define DMA_ES_SGE(x) (((uint32_t)(((uint32_t)(x)) << DMA_ES_SGE_SHIFT)) & DMA_ES_SGE_MASK) -#define DMA_ES_NCE_MASK (0x8U) -#define DMA_ES_NCE_SHIFT (3U) -#define DMA_ES_NCE(x) (((uint32_t)(((uint32_t)(x)) << DMA_ES_NCE_SHIFT)) & DMA_ES_NCE_MASK) -#define DMA_ES_DOE_MASK (0x10U) -#define DMA_ES_DOE_SHIFT (4U) -#define DMA_ES_DOE(x) (((uint32_t)(((uint32_t)(x)) << DMA_ES_DOE_SHIFT)) & DMA_ES_DOE_MASK) -#define DMA_ES_DAE_MASK (0x20U) -#define DMA_ES_DAE_SHIFT (5U) -#define DMA_ES_DAE(x) (((uint32_t)(((uint32_t)(x)) << DMA_ES_DAE_SHIFT)) & DMA_ES_DAE_MASK) -#define DMA_ES_SOE_MASK (0x40U) -#define DMA_ES_SOE_SHIFT (6U) -#define DMA_ES_SOE(x) (((uint32_t)(((uint32_t)(x)) << DMA_ES_SOE_SHIFT)) & DMA_ES_SOE_MASK) -#define DMA_ES_SAE_MASK (0x80U) -#define DMA_ES_SAE_SHIFT (7U) -#define DMA_ES_SAE(x) (((uint32_t)(((uint32_t)(x)) << DMA_ES_SAE_SHIFT)) & DMA_ES_SAE_MASK) -#define DMA_ES_ERRCHN_MASK (0xF00U) -#define DMA_ES_ERRCHN_SHIFT (8U) -#define DMA_ES_ERRCHN(x) (((uint32_t)(((uint32_t)(x)) << DMA_ES_ERRCHN_SHIFT)) & DMA_ES_ERRCHN_MASK) -#define DMA_ES_CPE_MASK (0x4000U) -#define DMA_ES_CPE_SHIFT (14U) -#define DMA_ES_CPE(x) (((uint32_t)(((uint32_t)(x)) << DMA_ES_CPE_SHIFT)) & DMA_ES_CPE_MASK) -#define DMA_ES_ECX_MASK (0x10000U) -#define DMA_ES_ECX_SHIFT (16U) -#define DMA_ES_ECX(x) (((uint32_t)(((uint32_t)(x)) << DMA_ES_ECX_SHIFT)) & DMA_ES_ECX_MASK) -#define DMA_ES_VLD_MASK (0x80000000U) -#define DMA_ES_VLD_SHIFT (31U) -#define DMA_ES_VLD(x) (((uint32_t)(((uint32_t)(x)) << DMA_ES_VLD_SHIFT)) & DMA_ES_VLD_MASK) - -/*! @name ERQ - Enable Request Register */ -#define DMA_ERQ_ERQ0_MASK (0x1U) -#define DMA_ERQ_ERQ0_SHIFT (0U) -#define DMA_ERQ_ERQ0(x) (((uint32_t)(((uint32_t)(x)) << DMA_ERQ_ERQ0_SHIFT)) & DMA_ERQ_ERQ0_MASK) -#define DMA_ERQ_ERQ1_MASK (0x2U) -#define DMA_ERQ_ERQ1_SHIFT (1U) -#define DMA_ERQ_ERQ1(x) (((uint32_t)(((uint32_t)(x)) << DMA_ERQ_ERQ1_SHIFT)) & DMA_ERQ_ERQ1_MASK) -#define DMA_ERQ_ERQ2_MASK (0x4U) -#define DMA_ERQ_ERQ2_SHIFT (2U) -#define DMA_ERQ_ERQ2(x) (((uint32_t)(((uint32_t)(x)) << DMA_ERQ_ERQ2_SHIFT)) & DMA_ERQ_ERQ2_MASK) -#define DMA_ERQ_ERQ3_MASK (0x8U) -#define DMA_ERQ_ERQ3_SHIFT (3U) -#define DMA_ERQ_ERQ3(x) (((uint32_t)(((uint32_t)(x)) << DMA_ERQ_ERQ3_SHIFT)) & DMA_ERQ_ERQ3_MASK) -#define DMA_ERQ_ERQ4_MASK (0x10U) -#define DMA_ERQ_ERQ4_SHIFT (4U) -#define DMA_ERQ_ERQ4(x) (((uint32_t)(((uint32_t)(x)) << DMA_ERQ_ERQ4_SHIFT)) & DMA_ERQ_ERQ4_MASK) -#define DMA_ERQ_ERQ5_MASK (0x20U) -#define DMA_ERQ_ERQ5_SHIFT (5U) -#define DMA_ERQ_ERQ5(x) (((uint32_t)(((uint32_t)(x)) << DMA_ERQ_ERQ5_SHIFT)) & DMA_ERQ_ERQ5_MASK) -#define DMA_ERQ_ERQ6_MASK (0x40U) -#define DMA_ERQ_ERQ6_SHIFT (6U) -#define DMA_ERQ_ERQ6(x) (((uint32_t)(((uint32_t)(x)) << DMA_ERQ_ERQ6_SHIFT)) & DMA_ERQ_ERQ6_MASK) -#define DMA_ERQ_ERQ7_MASK (0x80U) -#define DMA_ERQ_ERQ7_SHIFT (7U) -#define DMA_ERQ_ERQ7(x) (((uint32_t)(((uint32_t)(x)) << DMA_ERQ_ERQ7_SHIFT)) & DMA_ERQ_ERQ7_MASK) -#define DMA_ERQ_ERQ8_MASK (0x100U) -#define DMA_ERQ_ERQ8_SHIFT (8U) -#define DMA_ERQ_ERQ8(x) (((uint32_t)(((uint32_t)(x)) << DMA_ERQ_ERQ8_SHIFT)) & DMA_ERQ_ERQ8_MASK) -#define DMA_ERQ_ERQ9_MASK (0x200U) -#define DMA_ERQ_ERQ9_SHIFT (9U) -#define DMA_ERQ_ERQ9(x) (((uint32_t)(((uint32_t)(x)) << DMA_ERQ_ERQ9_SHIFT)) & DMA_ERQ_ERQ9_MASK) -#define DMA_ERQ_ERQ10_MASK (0x400U) -#define DMA_ERQ_ERQ10_SHIFT (10U) -#define DMA_ERQ_ERQ10(x) (((uint32_t)(((uint32_t)(x)) << DMA_ERQ_ERQ10_SHIFT)) & DMA_ERQ_ERQ10_MASK) -#define DMA_ERQ_ERQ11_MASK (0x800U) -#define DMA_ERQ_ERQ11_SHIFT (11U) -#define DMA_ERQ_ERQ11(x) (((uint32_t)(((uint32_t)(x)) << DMA_ERQ_ERQ11_SHIFT)) & DMA_ERQ_ERQ11_MASK) -#define DMA_ERQ_ERQ12_MASK (0x1000U) -#define DMA_ERQ_ERQ12_SHIFT (12U) -#define DMA_ERQ_ERQ12(x) (((uint32_t)(((uint32_t)(x)) << DMA_ERQ_ERQ12_SHIFT)) & DMA_ERQ_ERQ12_MASK) -#define DMA_ERQ_ERQ13_MASK (0x2000U) -#define DMA_ERQ_ERQ13_SHIFT (13U) -#define DMA_ERQ_ERQ13(x) (((uint32_t)(((uint32_t)(x)) << DMA_ERQ_ERQ13_SHIFT)) & DMA_ERQ_ERQ13_MASK) -#define DMA_ERQ_ERQ14_MASK (0x4000U) -#define DMA_ERQ_ERQ14_SHIFT (14U) -#define DMA_ERQ_ERQ14(x) (((uint32_t)(((uint32_t)(x)) << DMA_ERQ_ERQ14_SHIFT)) & DMA_ERQ_ERQ14_MASK) -#define DMA_ERQ_ERQ15_MASK (0x8000U) -#define DMA_ERQ_ERQ15_SHIFT (15U) -#define DMA_ERQ_ERQ15(x) (((uint32_t)(((uint32_t)(x)) << DMA_ERQ_ERQ15_SHIFT)) & DMA_ERQ_ERQ15_MASK) - -/*! @name EEI - Enable Error Interrupt Register */ -#define DMA_EEI_EEI0_MASK (0x1U) -#define DMA_EEI_EEI0_SHIFT (0U) -#define DMA_EEI_EEI0(x) (((uint32_t)(((uint32_t)(x)) << DMA_EEI_EEI0_SHIFT)) & DMA_EEI_EEI0_MASK) -#define DMA_EEI_EEI1_MASK (0x2U) -#define DMA_EEI_EEI1_SHIFT (1U) -#define DMA_EEI_EEI1(x) (((uint32_t)(((uint32_t)(x)) << DMA_EEI_EEI1_SHIFT)) & DMA_EEI_EEI1_MASK) -#define DMA_EEI_EEI2_MASK (0x4U) -#define DMA_EEI_EEI2_SHIFT (2U) -#define DMA_EEI_EEI2(x) (((uint32_t)(((uint32_t)(x)) << DMA_EEI_EEI2_SHIFT)) & DMA_EEI_EEI2_MASK) -#define DMA_EEI_EEI3_MASK (0x8U) -#define DMA_EEI_EEI3_SHIFT (3U) -#define DMA_EEI_EEI3(x) (((uint32_t)(((uint32_t)(x)) << DMA_EEI_EEI3_SHIFT)) & DMA_EEI_EEI3_MASK) -#define DMA_EEI_EEI4_MASK (0x10U) -#define DMA_EEI_EEI4_SHIFT (4U) -#define DMA_EEI_EEI4(x) (((uint32_t)(((uint32_t)(x)) << DMA_EEI_EEI4_SHIFT)) & DMA_EEI_EEI4_MASK) -#define DMA_EEI_EEI5_MASK (0x20U) -#define DMA_EEI_EEI5_SHIFT (5U) -#define DMA_EEI_EEI5(x) (((uint32_t)(((uint32_t)(x)) << DMA_EEI_EEI5_SHIFT)) & DMA_EEI_EEI5_MASK) -#define DMA_EEI_EEI6_MASK (0x40U) -#define DMA_EEI_EEI6_SHIFT (6U) -#define DMA_EEI_EEI6(x) (((uint32_t)(((uint32_t)(x)) << DMA_EEI_EEI6_SHIFT)) & DMA_EEI_EEI6_MASK) -#define DMA_EEI_EEI7_MASK (0x80U) -#define DMA_EEI_EEI7_SHIFT (7U) -#define DMA_EEI_EEI7(x) (((uint32_t)(((uint32_t)(x)) << DMA_EEI_EEI7_SHIFT)) & DMA_EEI_EEI7_MASK) -#define DMA_EEI_EEI8_MASK (0x100U) -#define DMA_EEI_EEI8_SHIFT (8U) -#define DMA_EEI_EEI8(x) (((uint32_t)(((uint32_t)(x)) << DMA_EEI_EEI8_SHIFT)) & DMA_EEI_EEI8_MASK) -#define DMA_EEI_EEI9_MASK (0x200U) -#define DMA_EEI_EEI9_SHIFT (9U) -#define DMA_EEI_EEI9(x) (((uint32_t)(((uint32_t)(x)) << DMA_EEI_EEI9_SHIFT)) & DMA_EEI_EEI9_MASK) -#define DMA_EEI_EEI10_MASK (0x400U) -#define DMA_EEI_EEI10_SHIFT (10U) -#define DMA_EEI_EEI10(x) (((uint32_t)(((uint32_t)(x)) << DMA_EEI_EEI10_SHIFT)) & DMA_EEI_EEI10_MASK) -#define DMA_EEI_EEI11_MASK (0x800U) -#define DMA_EEI_EEI11_SHIFT (11U) -#define DMA_EEI_EEI11(x) (((uint32_t)(((uint32_t)(x)) << DMA_EEI_EEI11_SHIFT)) & DMA_EEI_EEI11_MASK) -#define DMA_EEI_EEI12_MASK (0x1000U) -#define DMA_EEI_EEI12_SHIFT (12U) -#define DMA_EEI_EEI12(x) (((uint32_t)(((uint32_t)(x)) << DMA_EEI_EEI12_SHIFT)) & DMA_EEI_EEI12_MASK) -#define DMA_EEI_EEI13_MASK (0x2000U) -#define DMA_EEI_EEI13_SHIFT (13U) -#define DMA_EEI_EEI13(x) (((uint32_t)(((uint32_t)(x)) << DMA_EEI_EEI13_SHIFT)) & DMA_EEI_EEI13_MASK) -#define DMA_EEI_EEI14_MASK (0x4000U) -#define DMA_EEI_EEI14_SHIFT (14U) -#define DMA_EEI_EEI14(x) (((uint32_t)(((uint32_t)(x)) << DMA_EEI_EEI14_SHIFT)) & DMA_EEI_EEI14_MASK) -#define DMA_EEI_EEI15_MASK (0x8000U) -#define DMA_EEI_EEI15_SHIFT (15U) -#define DMA_EEI_EEI15(x) (((uint32_t)(((uint32_t)(x)) << DMA_EEI_EEI15_SHIFT)) & DMA_EEI_EEI15_MASK) - -/*! @name CEEI - Clear Enable Error Interrupt Register */ -#define DMA_CEEI_CEEI_MASK (0xFU) -#define DMA_CEEI_CEEI_SHIFT (0U) -#define DMA_CEEI_CEEI(x) (((uint8_t)(((uint8_t)(x)) << DMA_CEEI_CEEI_SHIFT)) & DMA_CEEI_CEEI_MASK) -#define DMA_CEEI_CAEE_MASK (0x40U) -#define DMA_CEEI_CAEE_SHIFT (6U) -#define DMA_CEEI_CAEE(x) (((uint8_t)(((uint8_t)(x)) << DMA_CEEI_CAEE_SHIFT)) & DMA_CEEI_CAEE_MASK) -#define DMA_CEEI_NOP_MASK (0x80U) -#define DMA_CEEI_NOP_SHIFT (7U) -#define DMA_CEEI_NOP(x) (((uint8_t)(((uint8_t)(x)) << DMA_CEEI_NOP_SHIFT)) & DMA_CEEI_NOP_MASK) - -/*! @name SEEI - Set Enable Error Interrupt Register */ -#define DMA_SEEI_SEEI_MASK (0xFU) -#define DMA_SEEI_SEEI_SHIFT (0U) -#define DMA_SEEI_SEEI(x) (((uint8_t)(((uint8_t)(x)) << DMA_SEEI_SEEI_SHIFT)) & DMA_SEEI_SEEI_MASK) -#define DMA_SEEI_SAEE_MASK (0x40U) -#define DMA_SEEI_SAEE_SHIFT (6U) -#define DMA_SEEI_SAEE(x) (((uint8_t)(((uint8_t)(x)) << DMA_SEEI_SAEE_SHIFT)) & DMA_SEEI_SAEE_MASK) -#define DMA_SEEI_NOP_MASK (0x80U) -#define DMA_SEEI_NOP_SHIFT (7U) -#define DMA_SEEI_NOP(x) (((uint8_t)(((uint8_t)(x)) << DMA_SEEI_NOP_SHIFT)) & DMA_SEEI_NOP_MASK) - -/*! @name CERQ - Clear Enable Request Register */ -#define DMA_CERQ_CERQ_MASK (0xFU) -#define DMA_CERQ_CERQ_SHIFT (0U) -#define DMA_CERQ_CERQ(x) (((uint8_t)(((uint8_t)(x)) << DMA_CERQ_CERQ_SHIFT)) & DMA_CERQ_CERQ_MASK) -#define DMA_CERQ_CAER_MASK (0x40U) -#define DMA_CERQ_CAER_SHIFT (6U) -#define DMA_CERQ_CAER(x) (((uint8_t)(((uint8_t)(x)) << DMA_CERQ_CAER_SHIFT)) & DMA_CERQ_CAER_MASK) -#define DMA_CERQ_NOP_MASK (0x80U) -#define DMA_CERQ_NOP_SHIFT (7U) -#define DMA_CERQ_NOP(x) (((uint8_t)(((uint8_t)(x)) << DMA_CERQ_NOP_SHIFT)) & DMA_CERQ_NOP_MASK) - -/*! @name SERQ - Set Enable Request Register */ -#define DMA_SERQ_SERQ_MASK (0xFU) -#define DMA_SERQ_SERQ_SHIFT (0U) -#define DMA_SERQ_SERQ(x) (((uint8_t)(((uint8_t)(x)) << DMA_SERQ_SERQ_SHIFT)) & DMA_SERQ_SERQ_MASK) -#define DMA_SERQ_SAER_MASK (0x40U) -#define DMA_SERQ_SAER_SHIFT (6U) -#define DMA_SERQ_SAER(x) (((uint8_t)(((uint8_t)(x)) << DMA_SERQ_SAER_SHIFT)) & DMA_SERQ_SAER_MASK) -#define DMA_SERQ_NOP_MASK (0x80U) -#define DMA_SERQ_NOP_SHIFT (7U) -#define DMA_SERQ_NOP(x) (((uint8_t)(((uint8_t)(x)) << DMA_SERQ_NOP_SHIFT)) & DMA_SERQ_NOP_MASK) - -/*! @name CDNE - Clear DONE Status Bit Register */ -#define DMA_CDNE_CDNE_MASK (0xFU) -#define DMA_CDNE_CDNE_SHIFT (0U) -#define DMA_CDNE_CDNE(x) (((uint8_t)(((uint8_t)(x)) << DMA_CDNE_CDNE_SHIFT)) & DMA_CDNE_CDNE_MASK) -#define DMA_CDNE_CADN_MASK (0x40U) -#define DMA_CDNE_CADN_SHIFT (6U) -#define DMA_CDNE_CADN(x) (((uint8_t)(((uint8_t)(x)) << DMA_CDNE_CADN_SHIFT)) & DMA_CDNE_CADN_MASK) -#define DMA_CDNE_NOP_MASK (0x80U) -#define DMA_CDNE_NOP_SHIFT (7U) -#define DMA_CDNE_NOP(x) (((uint8_t)(((uint8_t)(x)) << DMA_CDNE_NOP_SHIFT)) & DMA_CDNE_NOP_MASK) - -/*! @name SSRT - Set START Bit Register */ -#define DMA_SSRT_SSRT_MASK (0xFU) -#define DMA_SSRT_SSRT_SHIFT (0U) -#define DMA_SSRT_SSRT(x) (((uint8_t)(((uint8_t)(x)) << DMA_SSRT_SSRT_SHIFT)) & DMA_SSRT_SSRT_MASK) -#define DMA_SSRT_SAST_MASK (0x40U) -#define DMA_SSRT_SAST_SHIFT (6U) -#define DMA_SSRT_SAST(x) (((uint8_t)(((uint8_t)(x)) << DMA_SSRT_SAST_SHIFT)) & DMA_SSRT_SAST_MASK) -#define DMA_SSRT_NOP_MASK (0x80U) -#define DMA_SSRT_NOP_SHIFT (7U) -#define DMA_SSRT_NOP(x) (((uint8_t)(((uint8_t)(x)) << DMA_SSRT_NOP_SHIFT)) & DMA_SSRT_NOP_MASK) - -/*! @name CERR - Clear Error Register */ -#define DMA_CERR_CERR_MASK (0xFU) -#define DMA_CERR_CERR_SHIFT (0U) -#define DMA_CERR_CERR(x) (((uint8_t)(((uint8_t)(x)) << DMA_CERR_CERR_SHIFT)) & DMA_CERR_CERR_MASK) -#define DMA_CERR_CAEI_MASK (0x40U) -#define DMA_CERR_CAEI_SHIFT (6U) -#define DMA_CERR_CAEI(x) (((uint8_t)(((uint8_t)(x)) << DMA_CERR_CAEI_SHIFT)) & DMA_CERR_CAEI_MASK) -#define DMA_CERR_NOP_MASK (0x80U) -#define DMA_CERR_NOP_SHIFT (7U) -#define DMA_CERR_NOP(x) (((uint8_t)(((uint8_t)(x)) << DMA_CERR_NOP_SHIFT)) & DMA_CERR_NOP_MASK) - -/*! @name CINT - Clear Interrupt Request Register */ -#define DMA_CINT_CINT_MASK (0xFU) -#define DMA_CINT_CINT_SHIFT (0U) -#define DMA_CINT_CINT(x) (((uint8_t)(((uint8_t)(x)) << DMA_CINT_CINT_SHIFT)) & DMA_CINT_CINT_MASK) -#define DMA_CINT_CAIR_MASK (0x40U) -#define DMA_CINT_CAIR_SHIFT (6U) -#define DMA_CINT_CAIR(x) (((uint8_t)(((uint8_t)(x)) << DMA_CINT_CAIR_SHIFT)) & DMA_CINT_CAIR_MASK) -#define DMA_CINT_NOP_MASK (0x80U) -#define DMA_CINT_NOP_SHIFT (7U) -#define DMA_CINT_NOP(x) (((uint8_t)(((uint8_t)(x)) << DMA_CINT_NOP_SHIFT)) & DMA_CINT_NOP_MASK) - -/*! @name INT - Interrupt Request Register */ -#define DMA_INT_INT0_MASK (0x1U) -#define DMA_INT_INT0_SHIFT (0U) -#define DMA_INT_INT0(x) (((uint32_t)(((uint32_t)(x)) << DMA_INT_INT0_SHIFT)) & DMA_INT_INT0_MASK) -#define DMA_INT_INT1_MASK (0x2U) -#define DMA_INT_INT1_SHIFT (1U) -#define DMA_INT_INT1(x) (((uint32_t)(((uint32_t)(x)) << DMA_INT_INT1_SHIFT)) & DMA_INT_INT1_MASK) -#define DMA_INT_INT2_MASK (0x4U) -#define DMA_INT_INT2_SHIFT (2U) -#define DMA_INT_INT2(x) (((uint32_t)(((uint32_t)(x)) << DMA_INT_INT2_SHIFT)) & DMA_INT_INT2_MASK) -#define DMA_INT_INT3_MASK (0x8U) -#define DMA_INT_INT3_SHIFT (3U) -#define DMA_INT_INT3(x) (((uint32_t)(((uint32_t)(x)) << DMA_INT_INT3_SHIFT)) & DMA_INT_INT3_MASK) -#define DMA_INT_INT4_MASK (0x10U) -#define DMA_INT_INT4_SHIFT (4U) -#define DMA_INT_INT4(x) (((uint32_t)(((uint32_t)(x)) << DMA_INT_INT4_SHIFT)) & DMA_INT_INT4_MASK) -#define DMA_INT_INT5_MASK (0x20U) -#define DMA_INT_INT5_SHIFT (5U) -#define DMA_INT_INT5(x) (((uint32_t)(((uint32_t)(x)) << DMA_INT_INT5_SHIFT)) & DMA_INT_INT5_MASK) -#define DMA_INT_INT6_MASK (0x40U) -#define DMA_INT_INT6_SHIFT (6U) -#define DMA_INT_INT6(x) (((uint32_t)(((uint32_t)(x)) << DMA_INT_INT6_SHIFT)) & DMA_INT_INT6_MASK) -#define DMA_INT_INT7_MASK (0x80U) -#define DMA_INT_INT7_SHIFT (7U) -#define DMA_INT_INT7(x) (((uint32_t)(((uint32_t)(x)) << DMA_INT_INT7_SHIFT)) & DMA_INT_INT7_MASK) -#define DMA_INT_INT8_MASK (0x100U) -#define DMA_INT_INT8_SHIFT (8U) -#define DMA_INT_INT8(x) (((uint32_t)(((uint32_t)(x)) << DMA_INT_INT8_SHIFT)) & DMA_INT_INT8_MASK) -#define DMA_INT_INT9_MASK (0x200U) -#define DMA_INT_INT9_SHIFT (9U) -#define DMA_INT_INT9(x) (((uint32_t)(((uint32_t)(x)) << DMA_INT_INT9_SHIFT)) & DMA_INT_INT9_MASK) -#define DMA_INT_INT10_MASK (0x400U) -#define DMA_INT_INT10_SHIFT (10U) -#define DMA_INT_INT10(x) (((uint32_t)(((uint32_t)(x)) << DMA_INT_INT10_SHIFT)) & DMA_INT_INT10_MASK) -#define DMA_INT_INT11_MASK (0x800U) -#define DMA_INT_INT11_SHIFT (11U) -#define DMA_INT_INT11(x) (((uint32_t)(((uint32_t)(x)) << DMA_INT_INT11_SHIFT)) & DMA_INT_INT11_MASK) -#define DMA_INT_INT12_MASK (0x1000U) -#define DMA_INT_INT12_SHIFT (12U) -#define DMA_INT_INT12(x) (((uint32_t)(((uint32_t)(x)) << DMA_INT_INT12_SHIFT)) & DMA_INT_INT12_MASK) -#define DMA_INT_INT13_MASK (0x2000U) -#define DMA_INT_INT13_SHIFT (13U) -#define DMA_INT_INT13(x) (((uint32_t)(((uint32_t)(x)) << DMA_INT_INT13_SHIFT)) & DMA_INT_INT13_MASK) -#define DMA_INT_INT14_MASK (0x4000U) -#define DMA_INT_INT14_SHIFT (14U) -#define DMA_INT_INT14(x) (((uint32_t)(((uint32_t)(x)) << DMA_INT_INT14_SHIFT)) & DMA_INT_INT14_MASK) -#define DMA_INT_INT15_MASK (0x8000U) -#define DMA_INT_INT15_SHIFT (15U) -#define DMA_INT_INT15(x) (((uint32_t)(((uint32_t)(x)) << DMA_INT_INT15_SHIFT)) & DMA_INT_INT15_MASK) - -/*! @name ERR - Error Register */ -#define DMA_ERR_ERR0_MASK (0x1U) -#define DMA_ERR_ERR0_SHIFT (0U) -#define DMA_ERR_ERR0(x) (((uint32_t)(((uint32_t)(x)) << DMA_ERR_ERR0_SHIFT)) & DMA_ERR_ERR0_MASK) -#define DMA_ERR_ERR1_MASK (0x2U) -#define DMA_ERR_ERR1_SHIFT (1U) -#define DMA_ERR_ERR1(x) (((uint32_t)(((uint32_t)(x)) << DMA_ERR_ERR1_SHIFT)) & DMA_ERR_ERR1_MASK) -#define DMA_ERR_ERR2_MASK (0x4U) -#define DMA_ERR_ERR2_SHIFT (2U) -#define DMA_ERR_ERR2(x) (((uint32_t)(((uint32_t)(x)) << DMA_ERR_ERR2_SHIFT)) & DMA_ERR_ERR2_MASK) -#define DMA_ERR_ERR3_MASK (0x8U) -#define DMA_ERR_ERR3_SHIFT (3U) -#define DMA_ERR_ERR3(x) (((uint32_t)(((uint32_t)(x)) << DMA_ERR_ERR3_SHIFT)) & DMA_ERR_ERR3_MASK) -#define DMA_ERR_ERR4_MASK (0x10U) -#define DMA_ERR_ERR4_SHIFT (4U) -#define DMA_ERR_ERR4(x) (((uint32_t)(((uint32_t)(x)) << DMA_ERR_ERR4_SHIFT)) & DMA_ERR_ERR4_MASK) -#define DMA_ERR_ERR5_MASK (0x20U) -#define DMA_ERR_ERR5_SHIFT (5U) -#define DMA_ERR_ERR5(x) (((uint32_t)(((uint32_t)(x)) << DMA_ERR_ERR5_SHIFT)) & DMA_ERR_ERR5_MASK) -#define DMA_ERR_ERR6_MASK (0x40U) -#define DMA_ERR_ERR6_SHIFT (6U) -#define DMA_ERR_ERR6(x) (((uint32_t)(((uint32_t)(x)) << DMA_ERR_ERR6_SHIFT)) & DMA_ERR_ERR6_MASK) -#define DMA_ERR_ERR7_MASK (0x80U) -#define DMA_ERR_ERR7_SHIFT (7U) -#define DMA_ERR_ERR7(x) (((uint32_t)(((uint32_t)(x)) << DMA_ERR_ERR7_SHIFT)) & DMA_ERR_ERR7_MASK) -#define DMA_ERR_ERR8_MASK (0x100U) -#define DMA_ERR_ERR8_SHIFT (8U) -#define DMA_ERR_ERR8(x) (((uint32_t)(((uint32_t)(x)) << DMA_ERR_ERR8_SHIFT)) & DMA_ERR_ERR8_MASK) -#define DMA_ERR_ERR9_MASK (0x200U) -#define DMA_ERR_ERR9_SHIFT (9U) -#define DMA_ERR_ERR9(x) (((uint32_t)(((uint32_t)(x)) << DMA_ERR_ERR9_SHIFT)) & DMA_ERR_ERR9_MASK) -#define DMA_ERR_ERR10_MASK (0x400U) -#define DMA_ERR_ERR10_SHIFT (10U) -#define DMA_ERR_ERR10(x) (((uint32_t)(((uint32_t)(x)) << DMA_ERR_ERR10_SHIFT)) & DMA_ERR_ERR10_MASK) -#define DMA_ERR_ERR11_MASK (0x800U) -#define DMA_ERR_ERR11_SHIFT (11U) -#define DMA_ERR_ERR11(x) (((uint32_t)(((uint32_t)(x)) << DMA_ERR_ERR11_SHIFT)) & DMA_ERR_ERR11_MASK) -#define DMA_ERR_ERR12_MASK (0x1000U) -#define DMA_ERR_ERR12_SHIFT (12U) -#define DMA_ERR_ERR12(x) (((uint32_t)(((uint32_t)(x)) << DMA_ERR_ERR12_SHIFT)) & DMA_ERR_ERR12_MASK) -#define DMA_ERR_ERR13_MASK (0x2000U) -#define DMA_ERR_ERR13_SHIFT (13U) -#define DMA_ERR_ERR13(x) (((uint32_t)(((uint32_t)(x)) << DMA_ERR_ERR13_SHIFT)) & DMA_ERR_ERR13_MASK) -#define DMA_ERR_ERR14_MASK (0x4000U) -#define DMA_ERR_ERR14_SHIFT (14U) -#define DMA_ERR_ERR14(x) (((uint32_t)(((uint32_t)(x)) << DMA_ERR_ERR14_SHIFT)) & DMA_ERR_ERR14_MASK) -#define DMA_ERR_ERR15_MASK (0x8000U) -#define DMA_ERR_ERR15_SHIFT (15U) -#define DMA_ERR_ERR15(x) (((uint32_t)(((uint32_t)(x)) << DMA_ERR_ERR15_SHIFT)) & DMA_ERR_ERR15_MASK) - -/*! @name HRS - Hardware Request Status Register */ -#define DMA_HRS_HRS0_MASK (0x1U) -#define DMA_HRS_HRS0_SHIFT (0U) -#define DMA_HRS_HRS0(x) (((uint32_t)(((uint32_t)(x)) << DMA_HRS_HRS0_SHIFT)) & DMA_HRS_HRS0_MASK) -#define DMA_HRS_HRS1_MASK (0x2U) -#define DMA_HRS_HRS1_SHIFT (1U) -#define DMA_HRS_HRS1(x) (((uint32_t)(((uint32_t)(x)) << DMA_HRS_HRS1_SHIFT)) & DMA_HRS_HRS1_MASK) -#define DMA_HRS_HRS2_MASK (0x4U) -#define DMA_HRS_HRS2_SHIFT (2U) -#define DMA_HRS_HRS2(x) (((uint32_t)(((uint32_t)(x)) << DMA_HRS_HRS2_SHIFT)) & DMA_HRS_HRS2_MASK) -#define DMA_HRS_HRS3_MASK (0x8U) -#define DMA_HRS_HRS3_SHIFT (3U) -#define DMA_HRS_HRS3(x) (((uint32_t)(((uint32_t)(x)) << DMA_HRS_HRS3_SHIFT)) & DMA_HRS_HRS3_MASK) -#define DMA_HRS_HRS4_MASK (0x10U) -#define DMA_HRS_HRS4_SHIFT (4U) -#define DMA_HRS_HRS4(x) (((uint32_t)(((uint32_t)(x)) << DMA_HRS_HRS4_SHIFT)) & DMA_HRS_HRS4_MASK) -#define DMA_HRS_HRS5_MASK (0x20U) -#define DMA_HRS_HRS5_SHIFT (5U) -#define DMA_HRS_HRS5(x) (((uint32_t)(((uint32_t)(x)) << DMA_HRS_HRS5_SHIFT)) & DMA_HRS_HRS5_MASK) -#define DMA_HRS_HRS6_MASK (0x40U) -#define DMA_HRS_HRS6_SHIFT (6U) -#define DMA_HRS_HRS6(x) (((uint32_t)(((uint32_t)(x)) << DMA_HRS_HRS6_SHIFT)) & DMA_HRS_HRS6_MASK) -#define DMA_HRS_HRS7_MASK (0x80U) -#define DMA_HRS_HRS7_SHIFT (7U) -#define DMA_HRS_HRS7(x) (((uint32_t)(((uint32_t)(x)) << DMA_HRS_HRS7_SHIFT)) & DMA_HRS_HRS7_MASK) -#define DMA_HRS_HRS8_MASK (0x100U) -#define DMA_HRS_HRS8_SHIFT (8U) -#define DMA_HRS_HRS8(x) (((uint32_t)(((uint32_t)(x)) << DMA_HRS_HRS8_SHIFT)) & DMA_HRS_HRS8_MASK) -#define DMA_HRS_HRS9_MASK (0x200U) -#define DMA_HRS_HRS9_SHIFT (9U) -#define DMA_HRS_HRS9(x) (((uint32_t)(((uint32_t)(x)) << DMA_HRS_HRS9_SHIFT)) & DMA_HRS_HRS9_MASK) -#define DMA_HRS_HRS10_MASK (0x400U) -#define DMA_HRS_HRS10_SHIFT (10U) -#define DMA_HRS_HRS10(x) (((uint32_t)(((uint32_t)(x)) << DMA_HRS_HRS10_SHIFT)) & DMA_HRS_HRS10_MASK) -#define DMA_HRS_HRS11_MASK (0x800U) -#define DMA_HRS_HRS11_SHIFT (11U) -#define DMA_HRS_HRS11(x) (((uint32_t)(((uint32_t)(x)) << DMA_HRS_HRS11_SHIFT)) & DMA_HRS_HRS11_MASK) -#define DMA_HRS_HRS12_MASK (0x1000U) -#define DMA_HRS_HRS12_SHIFT (12U) -#define DMA_HRS_HRS12(x) (((uint32_t)(((uint32_t)(x)) << DMA_HRS_HRS12_SHIFT)) & DMA_HRS_HRS12_MASK) -#define DMA_HRS_HRS13_MASK (0x2000U) -#define DMA_HRS_HRS13_SHIFT (13U) -#define DMA_HRS_HRS13(x) (((uint32_t)(((uint32_t)(x)) << DMA_HRS_HRS13_SHIFT)) & DMA_HRS_HRS13_MASK) -#define DMA_HRS_HRS14_MASK (0x4000U) -#define DMA_HRS_HRS14_SHIFT (14U) -#define DMA_HRS_HRS14(x) (((uint32_t)(((uint32_t)(x)) << DMA_HRS_HRS14_SHIFT)) & DMA_HRS_HRS14_MASK) -#define DMA_HRS_HRS15_MASK (0x8000U) -#define DMA_HRS_HRS15_SHIFT (15U) -#define DMA_HRS_HRS15(x) (((uint32_t)(((uint32_t)(x)) << DMA_HRS_HRS15_SHIFT)) & DMA_HRS_HRS15_MASK) - -/*! @name DCHPRI3 - Channel n Priority Register */ -#define DMA_DCHPRI3_CHPRI_MASK (0xFU) -#define DMA_DCHPRI3_CHPRI_SHIFT (0U) -#define DMA_DCHPRI3_CHPRI(x) (((uint8_t)(((uint8_t)(x)) << DMA_DCHPRI3_CHPRI_SHIFT)) & DMA_DCHPRI3_CHPRI_MASK) -#define DMA_DCHPRI3_DPA_MASK (0x40U) -#define DMA_DCHPRI3_DPA_SHIFT (6U) -#define DMA_DCHPRI3_DPA(x) (((uint8_t)(((uint8_t)(x)) << DMA_DCHPRI3_DPA_SHIFT)) & DMA_DCHPRI3_DPA_MASK) -#define DMA_DCHPRI3_ECP_MASK (0x80U) -#define DMA_DCHPRI3_ECP_SHIFT (7U) -#define DMA_DCHPRI3_ECP(x) (((uint8_t)(((uint8_t)(x)) << DMA_DCHPRI3_ECP_SHIFT)) & DMA_DCHPRI3_ECP_MASK) - -/*! @name DCHPRI2 - Channel n Priority Register */ -#define DMA_DCHPRI2_CHPRI_MASK (0xFU) -#define DMA_DCHPRI2_CHPRI_SHIFT (0U) -#define DMA_DCHPRI2_CHPRI(x) (((uint8_t)(((uint8_t)(x)) << DMA_DCHPRI2_CHPRI_SHIFT)) & DMA_DCHPRI2_CHPRI_MASK) -#define DMA_DCHPRI2_DPA_MASK (0x40U) -#define DMA_DCHPRI2_DPA_SHIFT (6U) -#define DMA_DCHPRI2_DPA(x) (((uint8_t)(((uint8_t)(x)) << DMA_DCHPRI2_DPA_SHIFT)) & DMA_DCHPRI2_DPA_MASK) -#define DMA_DCHPRI2_ECP_MASK (0x80U) -#define DMA_DCHPRI2_ECP_SHIFT (7U) -#define DMA_DCHPRI2_ECP(x) (((uint8_t)(((uint8_t)(x)) << DMA_DCHPRI2_ECP_SHIFT)) & DMA_DCHPRI2_ECP_MASK) - -/*! @name DCHPRI1 - Channel n Priority Register */ -#define DMA_DCHPRI1_CHPRI_MASK (0xFU) -#define DMA_DCHPRI1_CHPRI_SHIFT (0U) -#define DMA_DCHPRI1_CHPRI(x) (((uint8_t)(((uint8_t)(x)) << DMA_DCHPRI1_CHPRI_SHIFT)) & DMA_DCHPRI1_CHPRI_MASK) -#define DMA_DCHPRI1_DPA_MASK (0x40U) -#define DMA_DCHPRI1_DPA_SHIFT (6U) -#define DMA_DCHPRI1_DPA(x) (((uint8_t)(((uint8_t)(x)) << DMA_DCHPRI1_DPA_SHIFT)) & DMA_DCHPRI1_DPA_MASK) -#define DMA_DCHPRI1_ECP_MASK (0x80U) -#define DMA_DCHPRI1_ECP_SHIFT (7U) -#define DMA_DCHPRI1_ECP(x) (((uint8_t)(((uint8_t)(x)) << DMA_DCHPRI1_ECP_SHIFT)) & DMA_DCHPRI1_ECP_MASK) - -/*! @name DCHPRI0 - Channel n Priority Register */ -#define DMA_DCHPRI0_CHPRI_MASK (0xFU) -#define DMA_DCHPRI0_CHPRI_SHIFT (0U) -#define DMA_DCHPRI0_CHPRI(x) (((uint8_t)(((uint8_t)(x)) << DMA_DCHPRI0_CHPRI_SHIFT)) & DMA_DCHPRI0_CHPRI_MASK) -#define DMA_DCHPRI0_DPA_MASK (0x40U) -#define DMA_DCHPRI0_DPA_SHIFT (6U) -#define DMA_DCHPRI0_DPA(x) (((uint8_t)(((uint8_t)(x)) << DMA_DCHPRI0_DPA_SHIFT)) & DMA_DCHPRI0_DPA_MASK) -#define DMA_DCHPRI0_ECP_MASK (0x80U) -#define DMA_DCHPRI0_ECP_SHIFT (7U) -#define DMA_DCHPRI0_ECP(x) (((uint8_t)(((uint8_t)(x)) << DMA_DCHPRI0_ECP_SHIFT)) & DMA_DCHPRI0_ECP_MASK) - -/*! @name DCHPRI7 - Channel n Priority Register */ -#define DMA_DCHPRI7_CHPRI_MASK (0xFU) -#define DMA_DCHPRI7_CHPRI_SHIFT (0U) -#define DMA_DCHPRI7_CHPRI(x) (((uint8_t)(((uint8_t)(x)) << DMA_DCHPRI7_CHPRI_SHIFT)) & DMA_DCHPRI7_CHPRI_MASK) -#define DMA_DCHPRI7_DPA_MASK (0x40U) -#define DMA_DCHPRI7_DPA_SHIFT (6U) -#define DMA_DCHPRI7_DPA(x) (((uint8_t)(((uint8_t)(x)) << DMA_DCHPRI7_DPA_SHIFT)) & DMA_DCHPRI7_DPA_MASK) -#define DMA_DCHPRI7_ECP_MASK (0x80U) -#define DMA_DCHPRI7_ECP_SHIFT (7U) -#define DMA_DCHPRI7_ECP(x) (((uint8_t)(((uint8_t)(x)) << DMA_DCHPRI7_ECP_SHIFT)) & DMA_DCHPRI7_ECP_MASK) - -/*! @name DCHPRI6 - Channel n Priority Register */ -#define DMA_DCHPRI6_CHPRI_MASK (0xFU) -#define DMA_DCHPRI6_CHPRI_SHIFT (0U) -#define DMA_DCHPRI6_CHPRI(x) (((uint8_t)(((uint8_t)(x)) << DMA_DCHPRI6_CHPRI_SHIFT)) & DMA_DCHPRI6_CHPRI_MASK) -#define DMA_DCHPRI6_DPA_MASK (0x40U) -#define DMA_DCHPRI6_DPA_SHIFT (6U) -#define DMA_DCHPRI6_DPA(x) (((uint8_t)(((uint8_t)(x)) << DMA_DCHPRI6_DPA_SHIFT)) & DMA_DCHPRI6_DPA_MASK) -#define DMA_DCHPRI6_ECP_MASK (0x80U) -#define DMA_DCHPRI6_ECP_SHIFT (7U) -#define DMA_DCHPRI6_ECP(x) (((uint8_t)(((uint8_t)(x)) << DMA_DCHPRI6_ECP_SHIFT)) & DMA_DCHPRI6_ECP_MASK) - -/*! @name DCHPRI5 - Channel n Priority Register */ -#define DMA_DCHPRI5_CHPRI_MASK (0xFU) -#define DMA_DCHPRI5_CHPRI_SHIFT (0U) -#define DMA_DCHPRI5_CHPRI(x) (((uint8_t)(((uint8_t)(x)) << DMA_DCHPRI5_CHPRI_SHIFT)) & DMA_DCHPRI5_CHPRI_MASK) -#define DMA_DCHPRI5_DPA_MASK (0x40U) -#define DMA_DCHPRI5_DPA_SHIFT (6U) -#define DMA_DCHPRI5_DPA(x) (((uint8_t)(((uint8_t)(x)) << DMA_DCHPRI5_DPA_SHIFT)) & DMA_DCHPRI5_DPA_MASK) -#define DMA_DCHPRI5_ECP_MASK (0x80U) -#define DMA_DCHPRI5_ECP_SHIFT (7U) -#define DMA_DCHPRI5_ECP(x) (((uint8_t)(((uint8_t)(x)) << DMA_DCHPRI5_ECP_SHIFT)) & DMA_DCHPRI5_ECP_MASK) - -/*! @name DCHPRI4 - Channel n Priority Register */ -#define DMA_DCHPRI4_CHPRI_MASK (0xFU) -#define DMA_DCHPRI4_CHPRI_SHIFT (0U) -#define DMA_DCHPRI4_CHPRI(x) (((uint8_t)(((uint8_t)(x)) << DMA_DCHPRI4_CHPRI_SHIFT)) & DMA_DCHPRI4_CHPRI_MASK) -#define DMA_DCHPRI4_DPA_MASK (0x40U) -#define DMA_DCHPRI4_DPA_SHIFT (6U) -#define DMA_DCHPRI4_DPA(x) (((uint8_t)(((uint8_t)(x)) << DMA_DCHPRI4_DPA_SHIFT)) & DMA_DCHPRI4_DPA_MASK) -#define DMA_DCHPRI4_ECP_MASK (0x80U) -#define DMA_DCHPRI4_ECP_SHIFT (7U) -#define DMA_DCHPRI4_ECP(x) (((uint8_t)(((uint8_t)(x)) << DMA_DCHPRI4_ECP_SHIFT)) & DMA_DCHPRI4_ECP_MASK) - -/*! @name DCHPRI11 - Channel n Priority Register */ -#define DMA_DCHPRI11_CHPRI_MASK (0xFU) -#define DMA_DCHPRI11_CHPRI_SHIFT (0U) -#define DMA_DCHPRI11_CHPRI(x) (((uint8_t)(((uint8_t)(x)) << DMA_DCHPRI11_CHPRI_SHIFT)) & DMA_DCHPRI11_CHPRI_MASK) -#define DMA_DCHPRI11_DPA_MASK (0x40U) -#define DMA_DCHPRI11_DPA_SHIFT (6U) -#define DMA_DCHPRI11_DPA(x) (((uint8_t)(((uint8_t)(x)) << DMA_DCHPRI11_DPA_SHIFT)) & DMA_DCHPRI11_DPA_MASK) -#define DMA_DCHPRI11_ECP_MASK (0x80U) -#define DMA_DCHPRI11_ECP_SHIFT (7U) -#define DMA_DCHPRI11_ECP(x) (((uint8_t)(((uint8_t)(x)) << DMA_DCHPRI11_ECP_SHIFT)) & DMA_DCHPRI11_ECP_MASK) - -/*! @name DCHPRI10 - Channel n Priority Register */ -#define DMA_DCHPRI10_CHPRI_MASK (0xFU) -#define DMA_DCHPRI10_CHPRI_SHIFT (0U) -#define DMA_DCHPRI10_CHPRI(x) (((uint8_t)(((uint8_t)(x)) << DMA_DCHPRI10_CHPRI_SHIFT)) & DMA_DCHPRI10_CHPRI_MASK) -#define DMA_DCHPRI10_DPA_MASK (0x40U) -#define DMA_DCHPRI10_DPA_SHIFT (6U) -#define DMA_DCHPRI10_DPA(x) (((uint8_t)(((uint8_t)(x)) << DMA_DCHPRI10_DPA_SHIFT)) & DMA_DCHPRI10_DPA_MASK) -#define DMA_DCHPRI10_ECP_MASK (0x80U) -#define DMA_DCHPRI10_ECP_SHIFT (7U) -#define DMA_DCHPRI10_ECP(x) (((uint8_t)(((uint8_t)(x)) << DMA_DCHPRI10_ECP_SHIFT)) & DMA_DCHPRI10_ECP_MASK) - -/*! @name DCHPRI9 - Channel n Priority Register */ -#define DMA_DCHPRI9_CHPRI_MASK (0xFU) -#define DMA_DCHPRI9_CHPRI_SHIFT (0U) -#define DMA_DCHPRI9_CHPRI(x) (((uint8_t)(((uint8_t)(x)) << DMA_DCHPRI9_CHPRI_SHIFT)) & DMA_DCHPRI9_CHPRI_MASK) -#define DMA_DCHPRI9_DPA_MASK (0x40U) -#define DMA_DCHPRI9_DPA_SHIFT (6U) -#define DMA_DCHPRI9_DPA(x) (((uint8_t)(((uint8_t)(x)) << DMA_DCHPRI9_DPA_SHIFT)) & DMA_DCHPRI9_DPA_MASK) -#define DMA_DCHPRI9_ECP_MASK (0x80U) -#define DMA_DCHPRI9_ECP_SHIFT (7U) -#define DMA_DCHPRI9_ECP(x) (((uint8_t)(((uint8_t)(x)) << DMA_DCHPRI9_ECP_SHIFT)) & DMA_DCHPRI9_ECP_MASK) - -/*! @name DCHPRI8 - Channel n Priority Register */ -#define DMA_DCHPRI8_CHPRI_MASK (0xFU) -#define DMA_DCHPRI8_CHPRI_SHIFT (0U) -#define DMA_DCHPRI8_CHPRI(x) (((uint8_t)(((uint8_t)(x)) << DMA_DCHPRI8_CHPRI_SHIFT)) & DMA_DCHPRI8_CHPRI_MASK) -#define DMA_DCHPRI8_DPA_MASK (0x40U) -#define DMA_DCHPRI8_DPA_SHIFT (6U) -#define DMA_DCHPRI8_DPA(x) (((uint8_t)(((uint8_t)(x)) << DMA_DCHPRI8_DPA_SHIFT)) & DMA_DCHPRI8_DPA_MASK) -#define DMA_DCHPRI8_ECP_MASK (0x80U) -#define DMA_DCHPRI8_ECP_SHIFT (7U) -#define DMA_DCHPRI8_ECP(x) (((uint8_t)(((uint8_t)(x)) << DMA_DCHPRI8_ECP_SHIFT)) & DMA_DCHPRI8_ECP_MASK) - -/*! @name DCHPRI15 - Channel n Priority Register */ -#define DMA_DCHPRI15_CHPRI_MASK (0xFU) -#define DMA_DCHPRI15_CHPRI_SHIFT (0U) -#define DMA_DCHPRI15_CHPRI(x) (((uint8_t)(((uint8_t)(x)) << DMA_DCHPRI15_CHPRI_SHIFT)) & DMA_DCHPRI15_CHPRI_MASK) -#define DMA_DCHPRI15_DPA_MASK (0x40U) -#define DMA_DCHPRI15_DPA_SHIFT (6U) -#define DMA_DCHPRI15_DPA(x) (((uint8_t)(((uint8_t)(x)) << DMA_DCHPRI15_DPA_SHIFT)) & DMA_DCHPRI15_DPA_MASK) -#define DMA_DCHPRI15_ECP_MASK (0x80U) -#define DMA_DCHPRI15_ECP_SHIFT (7U) -#define DMA_DCHPRI15_ECP(x) (((uint8_t)(((uint8_t)(x)) << DMA_DCHPRI15_ECP_SHIFT)) & DMA_DCHPRI15_ECP_MASK) - -/*! @name DCHPRI14 - Channel n Priority Register */ -#define DMA_DCHPRI14_CHPRI_MASK (0xFU) -#define DMA_DCHPRI14_CHPRI_SHIFT (0U) -#define DMA_DCHPRI14_CHPRI(x) (((uint8_t)(((uint8_t)(x)) << DMA_DCHPRI14_CHPRI_SHIFT)) & DMA_DCHPRI14_CHPRI_MASK) -#define DMA_DCHPRI14_DPA_MASK (0x40U) -#define DMA_DCHPRI14_DPA_SHIFT (6U) -#define DMA_DCHPRI14_DPA(x) (((uint8_t)(((uint8_t)(x)) << DMA_DCHPRI14_DPA_SHIFT)) & DMA_DCHPRI14_DPA_MASK) -#define DMA_DCHPRI14_ECP_MASK (0x80U) -#define DMA_DCHPRI14_ECP_SHIFT (7U) -#define DMA_DCHPRI14_ECP(x) (((uint8_t)(((uint8_t)(x)) << DMA_DCHPRI14_ECP_SHIFT)) & DMA_DCHPRI14_ECP_MASK) - -/*! @name DCHPRI13 - Channel n Priority Register */ -#define DMA_DCHPRI13_CHPRI_MASK (0xFU) -#define DMA_DCHPRI13_CHPRI_SHIFT (0U) -#define DMA_DCHPRI13_CHPRI(x) (((uint8_t)(((uint8_t)(x)) << DMA_DCHPRI13_CHPRI_SHIFT)) & DMA_DCHPRI13_CHPRI_MASK) -#define DMA_DCHPRI13_DPA_MASK (0x40U) -#define DMA_DCHPRI13_DPA_SHIFT (6U) -#define DMA_DCHPRI13_DPA(x) (((uint8_t)(((uint8_t)(x)) << DMA_DCHPRI13_DPA_SHIFT)) & DMA_DCHPRI13_DPA_MASK) -#define DMA_DCHPRI13_ECP_MASK (0x80U) -#define DMA_DCHPRI13_ECP_SHIFT (7U) -#define DMA_DCHPRI13_ECP(x) (((uint8_t)(((uint8_t)(x)) << DMA_DCHPRI13_ECP_SHIFT)) & DMA_DCHPRI13_ECP_MASK) - -/*! @name DCHPRI12 - Channel n Priority Register */ -#define DMA_DCHPRI12_CHPRI_MASK (0xFU) -#define DMA_DCHPRI12_CHPRI_SHIFT (0U) -#define DMA_DCHPRI12_CHPRI(x) (((uint8_t)(((uint8_t)(x)) << DMA_DCHPRI12_CHPRI_SHIFT)) & DMA_DCHPRI12_CHPRI_MASK) -#define DMA_DCHPRI12_DPA_MASK (0x40U) -#define DMA_DCHPRI12_DPA_SHIFT (6U) -#define DMA_DCHPRI12_DPA(x) (((uint8_t)(((uint8_t)(x)) << DMA_DCHPRI12_DPA_SHIFT)) & DMA_DCHPRI12_DPA_MASK) -#define DMA_DCHPRI12_ECP_MASK (0x80U) -#define DMA_DCHPRI12_ECP_SHIFT (7U) -#define DMA_DCHPRI12_ECP(x) (((uint8_t)(((uint8_t)(x)) << DMA_DCHPRI12_ECP_SHIFT)) & DMA_DCHPRI12_ECP_MASK) - -/*! @name SADDR - TCD Source Address */ -#define DMA_SADDR_SADDR_MASK (0xFFFFFFFFU) -#define DMA_SADDR_SADDR_SHIFT (0U) -#define DMA_SADDR_SADDR(x) (((uint32_t)(((uint32_t)(x)) << DMA_SADDR_SADDR_SHIFT)) & DMA_SADDR_SADDR_MASK) - -/* The count of DMA_SADDR */ -#define DMA_SADDR_COUNT (16U) - -/*! @name SOFF - TCD Signed Source Address Offset */ -#define DMA_SOFF_SOFF_MASK (0xFFFFU) -#define DMA_SOFF_SOFF_SHIFT (0U) -#define DMA_SOFF_SOFF(x) (((uint16_t)(((uint16_t)(x)) << DMA_SOFF_SOFF_SHIFT)) & DMA_SOFF_SOFF_MASK) - -/* The count of DMA_SOFF */ -#define DMA_SOFF_COUNT (16U) - -/*! @name ATTR - TCD Transfer Attributes */ -#define DMA_ATTR_DSIZE_MASK (0x7U) -#define DMA_ATTR_DSIZE_SHIFT (0U) -#define DMA_ATTR_DSIZE(x) (((uint16_t)(((uint16_t)(x)) << DMA_ATTR_DSIZE_SHIFT)) & DMA_ATTR_DSIZE_MASK) -#define DMA_ATTR_DMOD_MASK (0xF8U) -#define DMA_ATTR_DMOD_SHIFT (3U) -#define DMA_ATTR_DMOD(x) (((uint16_t)(((uint16_t)(x)) << DMA_ATTR_DMOD_SHIFT)) & DMA_ATTR_DMOD_MASK) -#define DMA_ATTR_SSIZE_MASK (0x700U) -#define DMA_ATTR_SSIZE_SHIFT (8U) -#define DMA_ATTR_SSIZE(x) (((uint16_t)(((uint16_t)(x)) << DMA_ATTR_SSIZE_SHIFT)) & DMA_ATTR_SSIZE_MASK) -#define DMA_ATTR_SMOD_MASK (0xF800U) -#define DMA_ATTR_SMOD_SHIFT (11U) -#define DMA_ATTR_SMOD(x) (((uint16_t)(((uint16_t)(x)) << DMA_ATTR_SMOD_SHIFT)) & DMA_ATTR_SMOD_MASK) - -/* The count of DMA_ATTR */ -#define DMA_ATTR_COUNT (16U) - -/*! @name NBYTES_MLNO - TCD Minor Byte Count (Minor Loop Disabled) */ -#define DMA_NBYTES_MLNO_NBYTES_MASK (0xFFFFFFFFU) -#define DMA_NBYTES_MLNO_NBYTES_SHIFT (0U) -#define DMA_NBYTES_MLNO_NBYTES(x) (((uint32_t)(((uint32_t)(x)) << DMA_NBYTES_MLNO_NBYTES_SHIFT)) & DMA_NBYTES_MLNO_NBYTES_MASK) - -/* The count of DMA_NBYTES_MLNO */ -#define DMA_NBYTES_MLNO_COUNT (16U) - -/*! @name NBYTES_MLOFFNO - TCD Signed Minor Loop Offset (Minor Loop Enabled and Offset Disabled) */ -#define DMA_NBYTES_MLOFFNO_NBYTES_MASK (0x3FFFFFFFU) -#define DMA_NBYTES_MLOFFNO_NBYTES_SHIFT (0U) -#define DMA_NBYTES_MLOFFNO_NBYTES(x) (((uint32_t)(((uint32_t)(x)) << DMA_NBYTES_MLOFFNO_NBYTES_SHIFT)) & DMA_NBYTES_MLOFFNO_NBYTES_MASK) -#define DMA_NBYTES_MLOFFNO_DMLOE_MASK (0x40000000U) -#define DMA_NBYTES_MLOFFNO_DMLOE_SHIFT (30U) -#define DMA_NBYTES_MLOFFNO_DMLOE(x) (((uint32_t)(((uint32_t)(x)) << DMA_NBYTES_MLOFFNO_DMLOE_SHIFT)) & DMA_NBYTES_MLOFFNO_DMLOE_MASK) -#define DMA_NBYTES_MLOFFNO_SMLOE_MASK (0x80000000U) -#define DMA_NBYTES_MLOFFNO_SMLOE_SHIFT (31U) -#define DMA_NBYTES_MLOFFNO_SMLOE(x) (((uint32_t)(((uint32_t)(x)) << DMA_NBYTES_MLOFFNO_SMLOE_SHIFT)) & DMA_NBYTES_MLOFFNO_SMLOE_MASK) - -/* The count of DMA_NBYTES_MLOFFNO */ -#define DMA_NBYTES_MLOFFNO_COUNT (16U) - -/*! @name NBYTES_MLOFFYES - TCD Signed Minor Loop Offset (Minor Loop and Offset Enabled) */ -#define DMA_NBYTES_MLOFFYES_NBYTES_MASK (0x3FFU) -#define DMA_NBYTES_MLOFFYES_NBYTES_SHIFT (0U) -#define DMA_NBYTES_MLOFFYES_NBYTES(x) (((uint32_t)(((uint32_t)(x)) << DMA_NBYTES_MLOFFYES_NBYTES_SHIFT)) & DMA_NBYTES_MLOFFYES_NBYTES_MASK) -#define DMA_NBYTES_MLOFFYES_MLOFF_MASK (0x3FFFFC00U) -#define DMA_NBYTES_MLOFFYES_MLOFF_SHIFT (10U) -#define DMA_NBYTES_MLOFFYES_MLOFF(x) (((uint32_t)(((uint32_t)(x)) << DMA_NBYTES_MLOFFYES_MLOFF_SHIFT)) & DMA_NBYTES_MLOFFYES_MLOFF_MASK) -#define DMA_NBYTES_MLOFFYES_DMLOE_MASK (0x40000000U) -#define DMA_NBYTES_MLOFFYES_DMLOE_SHIFT (30U) -#define DMA_NBYTES_MLOFFYES_DMLOE(x) (((uint32_t)(((uint32_t)(x)) << DMA_NBYTES_MLOFFYES_DMLOE_SHIFT)) & DMA_NBYTES_MLOFFYES_DMLOE_MASK) -#define DMA_NBYTES_MLOFFYES_SMLOE_MASK (0x80000000U) -#define DMA_NBYTES_MLOFFYES_SMLOE_SHIFT (31U) -#define DMA_NBYTES_MLOFFYES_SMLOE(x) (((uint32_t)(((uint32_t)(x)) << DMA_NBYTES_MLOFFYES_SMLOE_SHIFT)) & DMA_NBYTES_MLOFFYES_SMLOE_MASK) - -/* The count of DMA_NBYTES_MLOFFYES */ -#define DMA_NBYTES_MLOFFYES_COUNT (16U) - -/*! @name SLAST - TCD Last Source Address Adjustment */ -#define DMA_SLAST_SLAST_MASK (0xFFFFFFFFU) -#define DMA_SLAST_SLAST_SHIFT (0U) -#define DMA_SLAST_SLAST(x) (((uint32_t)(((uint32_t)(x)) << DMA_SLAST_SLAST_SHIFT)) & DMA_SLAST_SLAST_MASK) - -/* The count of DMA_SLAST */ -#define DMA_SLAST_COUNT (16U) - -/*! @name DADDR - TCD Destination Address */ -#define DMA_DADDR_DADDR_MASK (0xFFFFFFFFU) -#define DMA_DADDR_DADDR_SHIFT (0U) -#define DMA_DADDR_DADDR(x) (((uint32_t)(((uint32_t)(x)) << DMA_DADDR_DADDR_SHIFT)) & DMA_DADDR_DADDR_MASK) - -/* The count of DMA_DADDR */ -#define DMA_DADDR_COUNT (16U) - -/*! @name DOFF - TCD Signed Destination Address Offset */ -#define DMA_DOFF_DOFF_MASK (0xFFFFU) -#define DMA_DOFF_DOFF_SHIFT (0U) -#define DMA_DOFF_DOFF(x) (((uint16_t)(((uint16_t)(x)) << DMA_DOFF_DOFF_SHIFT)) & DMA_DOFF_DOFF_MASK) - -/* The count of DMA_DOFF */ -#define DMA_DOFF_COUNT (16U) - -/*! @name CITER_ELINKNO - TCD Current Minor Loop Link, Major Loop Count (Channel Linking Disabled) */ -#define DMA_CITER_ELINKNO_CITER_MASK (0x7FFFU) -#define DMA_CITER_ELINKNO_CITER_SHIFT (0U) -#define DMA_CITER_ELINKNO_CITER(x) (((uint16_t)(((uint16_t)(x)) << DMA_CITER_ELINKNO_CITER_SHIFT)) & DMA_CITER_ELINKNO_CITER_MASK) -#define DMA_CITER_ELINKNO_ELINK_MASK (0x8000U) -#define DMA_CITER_ELINKNO_ELINK_SHIFT (15U) -#define DMA_CITER_ELINKNO_ELINK(x) (((uint16_t)(((uint16_t)(x)) << DMA_CITER_ELINKNO_ELINK_SHIFT)) & DMA_CITER_ELINKNO_ELINK_MASK) - -/* The count of DMA_CITER_ELINKNO */ -#define DMA_CITER_ELINKNO_COUNT (16U) - -/*! @name CITER_ELINKYES - TCD Current Minor Loop Link, Major Loop Count (Channel Linking Enabled) */ -#define DMA_CITER_ELINKYES_CITER_MASK (0x1FFU) -#define DMA_CITER_ELINKYES_CITER_SHIFT (0U) -#define DMA_CITER_ELINKYES_CITER(x) (((uint16_t)(((uint16_t)(x)) << DMA_CITER_ELINKYES_CITER_SHIFT)) & DMA_CITER_ELINKYES_CITER_MASK) -#define DMA_CITER_ELINKYES_LINKCH_MASK (0x1E00U) -#define DMA_CITER_ELINKYES_LINKCH_SHIFT (9U) -#define DMA_CITER_ELINKYES_LINKCH(x) (((uint16_t)(((uint16_t)(x)) << DMA_CITER_ELINKYES_LINKCH_SHIFT)) & DMA_CITER_ELINKYES_LINKCH_MASK) -#define DMA_CITER_ELINKYES_ELINK_MASK (0x8000U) -#define DMA_CITER_ELINKYES_ELINK_SHIFT (15U) -#define DMA_CITER_ELINKYES_ELINK(x) (((uint16_t)(((uint16_t)(x)) << DMA_CITER_ELINKYES_ELINK_SHIFT)) & DMA_CITER_ELINKYES_ELINK_MASK) - -/* The count of DMA_CITER_ELINKYES */ -#define DMA_CITER_ELINKYES_COUNT (16U) - -/*! @name DLAST_SGA - TCD Last Destination Address Adjustment/Scatter Gather Address */ -#define DMA_DLAST_SGA_DLASTSGA_MASK (0xFFFFFFFFU) -#define DMA_DLAST_SGA_DLASTSGA_SHIFT (0U) -#define DMA_DLAST_SGA_DLASTSGA(x) (((uint32_t)(((uint32_t)(x)) << DMA_DLAST_SGA_DLASTSGA_SHIFT)) & DMA_DLAST_SGA_DLASTSGA_MASK) - -/* The count of DMA_DLAST_SGA */ -#define DMA_DLAST_SGA_COUNT (16U) - -/*! @name CSR - TCD Control and Status */ -#define DMA_CSR_START_MASK (0x1U) -#define DMA_CSR_START_SHIFT (0U) -#define DMA_CSR_START(x) (((uint16_t)(((uint16_t)(x)) << DMA_CSR_START_SHIFT)) & DMA_CSR_START_MASK) -#define DMA_CSR_INTMAJOR_MASK (0x2U) -#define DMA_CSR_INTMAJOR_SHIFT (1U) -#define DMA_CSR_INTMAJOR(x) (((uint16_t)(((uint16_t)(x)) << DMA_CSR_INTMAJOR_SHIFT)) & DMA_CSR_INTMAJOR_MASK) -#define DMA_CSR_INTHALF_MASK (0x4U) -#define DMA_CSR_INTHALF_SHIFT (2U) -#define DMA_CSR_INTHALF(x) (((uint16_t)(((uint16_t)(x)) << DMA_CSR_INTHALF_SHIFT)) & DMA_CSR_INTHALF_MASK) -#define DMA_CSR_DREQ_MASK (0x8U) -#define DMA_CSR_DREQ_SHIFT (3U) -#define DMA_CSR_DREQ(x) (((uint16_t)(((uint16_t)(x)) << DMA_CSR_DREQ_SHIFT)) & DMA_CSR_DREQ_MASK) -#define DMA_CSR_ESG_MASK (0x10U) -#define DMA_CSR_ESG_SHIFT (4U) -#define DMA_CSR_ESG(x) (((uint16_t)(((uint16_t)(x)) << DMA_CSR_ESG_SHIFT)) & DMA_CSR_ESG_MASK) -#define DMA_CSR_MAJORELINK_MASK (0x20U) -#define DMA_CSR_MAJORELINK_SHIFT (5U) -#define DMA_CSR_MAJORELINK(x) (((uint16_t)(((uint16_t)(x)) << DMA_CSR_MAJORELINK_SHIFT)) & DMA_CSR_MAJORELINK_MASK) -#define DMA_CSR_ACTIVE_MASK (0x40U) -#define DMA_CSR_ACTIVE_SHIFT (6U) -#define DMA_CSR_ACTIVE(x) (((uint16_t)(((uint16_t)(x)) << DMA_CSR_ACTIVE_SHIFT)) & DMA_CSR_ACTIVE_MASK) -#define DMA_CSR_DONE_MASK (0x80U) -#define DMA_CSR_DONE_SHIFT (7U) -#define DMA_CSR_DONE(x) (((uint16_t)(((uint16_t)(x)) << DMA_CSR_DONE_SHIFT)) & DMA_CSR_DONE_MASK) -#define DMA_CSR_MAJORLINKCH_MASK (0xF00U) -#define DMA_CSR_MAJORLINKCH_SHIFT (8U) -#define DMA_CSR_MAJORLINKCH(x) (((uint16_t)(((uint16_t)(x)) << DMA_CSR_MAJORLINKCH_SHIFT)) & DMA_CSR_MAJORLINKCH_MASK) -#define DMA_CSR_BWC_MASK (0xC000U) -#define DMA_CSR_BWC_SHIFT (14U) -#define DMA_CSR_BWC(x) (((uint16_t)(((uint16_t)(x)) << DMA_CSR_BWC_SHIFT)) & DMA_CSR_BWC_MASK) - -/* The count of DMA_CSR */ -#define DMA_CSR_COUNT (16U) - -/*! @name BITER_ELINKNO - TCD Beginning Minor Loop Link, Major Loop Count (Channel Linking Disabled) */ -#define DMA_BITER_ELINKNO_BITER_MASK (0x7FFFU) -#define DMA_BITER_ELINKNO_BITER_SHIFT (0U) -#define DMA_BITER_ELINKNO_BITER(x) (((uint16_t)(((uint16_t)(x)) << DMA_BITER_ELINKNO_BITER_SHIFT)) & DMA_BITER_ELINKNO_BITER_MASK) -#define DMA_BITER_ELINKNO_ELINK_MASK (0x8000U) -#define DMA_BITER_ELINKNO_ELINK_SHIFT (15U) -#define DMA_BITER_ELINKNO_ELINK(x) (((uint16_t)(((uint16_t)(x)) << DMA_BITER_ELINKNO_ELINK_SHIFT)) & DMA_BITER_ELINKNO_ELINK_MASK) - -/* The count of DMA_BITER_ELINKNO */ -#define DMA_BITER_ELINKNO_COUNT (16U) - -/*! @name BITER_ELINKYES - TCD Beginning Minor Loop Link, Major Loop Count (Channel Linking Enabled) */ -#define DMA_BITER_ELINKYES_BITER_MASK (0x1FFU) -#define DMA_BITER_ELINKYES_BITER_SHIFT (0U) -#define DMA_BITER_ELINKYES_BITER(x) (((uint16_t)(((uint16_t)(x)) << DMA_BITER_ELINKYES_BITER_SHIFT)) & DMA_BITER_ELINKYES_BITER_MASK) -#define DMA_BITER_ELINKYES_LINKCH_MASK (0x1E00U) -#define DMA_BITER_ELINKYES_LINKCH_SHIFT (9U) -#define DMA_BITER_ELINKYES_LINKCH(x) (((uint16_t)(((uint16_t)(x)) << DMA_BITER_ELINKYES_LINKCH_SHIFT)) & DMA_BITER_ELINKYES_LINKCH_MASK) -#define DMA_BITER_ELINKYES_ELINK_MASK (0x8000U) -#define DMA_BITER_ELINKYES_ELINK_SHIFT (15U) -#define DMA_BITER_ELINKYES_ELINK(x) (((uint16_t)(((uint16_t)(x)) << DMA_BITER_ELINKYES_ELINK_SHIFT)) & DMA_BITER_ELINKYES_ELINK_MASK) - -/* The count of DMA_BITER_ELINKYES */ -#define DMA_BITER_ELINKYES_COUNT (16U) - - -/*! - * @} - */ /* end of group DMA_Register_Masks */ - - -/* DMA - Peripheral instance base addresses */ -/** Peripheral DMA base address */ -#define DMA_BASE (0x40008000u) -/** Peripheral DMA base pointer */ -#define DMA0 ((DMA_Type *)DMA_BASE) -/** Array initializer of DMA peripheral base addresses */ -#define DMA_BASE_ADDRS { DMA_BASE } -/** Array initializer of DMA peripheral base pointers */ -#define DMA_BASE_PTRS { DMA0 } -/** Interrupt vectors for the DMA peripheral type */ -#define DMA_CHN_IRQS { { DMA0_IRQn, DMA1_IRQn, DMA2_IRQn, DMA3_IRQn, DMA4_IRQn, DMA5_IRQn, DMA6_IRQn, DMA7_IRQn, DMA8_IRQn, DMA9_IRQn, DMA10_IRQn, DMA11_IRQn, DMA12_IRQn, DMA13_IRQn, DMA14_IRQn, DMA15_IRQn } } -#define DMA_ERROR_IRQS { DMA_Error_IRQn } - -/*! - * @} - */ /* end of group DMA_Peripheral_Access_Layer */ - - -/* ---------------------------------------------------------------------------- - -- DMAMUX Peripheral Access Layer - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup DMAMUX_Peripheral_Access_Layer DMAMUX Peripheral Access Layer - * @{ - */ - -/** DMAMUX - Register Layout Typedef */ -typedef struct { - __IO uint8_t CHCFG[16]; /**< Channel Configuration register, array offset: 0x0, array step: 0x1 */ -} DMAMUX_Type; - -/* ---------------------------------------------------------------------------- - -- DMAMUX Register Masks - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup DMAMUX_Register_Masks DMAMUX Register Masks - * @{ - */ - -/*! @name CHCFG - Channel Configuration register */ -#define DMAMUX_CHCFG_SOURCE_MASK (0x3FU) -#define DMAMUX_CHCFG_SOURCE_SHIFT (0U) -#define DMAMUX_CHCFG_SOURCE(x) (((uint8_t)(((uint8_t)(x)) << DMAMUX_CHCFG_SOURCE_SHIFT)) & DMAMUX_CHCFG_SOURCE_MASK) -#define DMAMUX_CHCFG_TRIG_MASK (0x40U) -#define DMAMUX_CHCFG_TRIG_SHIFT (6U) -#define DMAMUX_CHCFG_TRIG(x) (((uint8_t)(((uint8_t)(x)) << DMAMUX_CHCFG_TRIG_SHIFT)) & DMAMUX_CHCFG_TRIG_MASK) -#define DMAMUX_CHCFG_ENBL_MASK (0x80U) -#define DMAMUX_CHCFG_ENBL_SHIFT (7U) -#define DMAMUX_CHCFG_ENBL(x) (((uint8_t)(((uint8_t)(x)) << DMAMUX_CHCFG_ENBL_SHIFT)) & DMAMUX_CHCFG_ENBL_MASK) - -/* The count of DMAMUX_CHCFG */ -#define DMAMUX_CHCFG_COUNT (16U) - - -/*! - * @} - */ /* end of group DMAMUX_Register_Masks */ - - -/* DMAMUX - Peripheral instance base addresses */ -/** Peripheral DMAMUX base address */ -#define DMAMUX_BASE (0x40021000u) -/** Peripheral DMAMUX base pointer */ -#define DMAMUX ((DMAMUX_Type *)DMAMUX_BASE) -/** Array initializer of DMAMUX peripheral base addresses */ -#define DMAMUX_BASE_ADDRS { DMAMUX_BASE } -/** Array initializer of DMAMUX peripheral base pointers */ -#define DMAMUX_BASE_PTRS { DMAMUX } - -/*! - * @} - */ /* end of group DMAMUX_Peripheral_Access_Layer */ - - -/* ---------------------------------------------------------------------------- - -- EWM Peripheral Access Layer - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup EWM_Peripheral_Access_Layer EWM Peripheral Access Layer - * @{ - */ - -/** EWM - Register Layout Typedef */ -typedef struct { - __IO uint8_t CTRL; /**< Control Register, offset: 0x0 */ - __O uint8_t SERV; /**< Service Register, offset: 0x1 */ - __IO uint8_t CMPL; /**< Compare Low Register, offset: 0x2 */ - __IO uint8_t CMPH; /**< Compare High Register, offset: 0x3 */ -} EWM_Type; - -/* ---------------------------------------------------------------------------- - -- EWM Register Masks - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup EWM_Register_Masks EWM Register Masks - * @{ - */ - -/*! @name CTRL - Control Register */ -#define EWM_CTRL_EWMEN_MASK (0x1U) -#define EWM_CTRL_EWMEN_SHIFT (0U) -#define EWM_CTRL_EWMEN(x) (((uint8_t)(((uint8_t)(x)) << EWM_CTRL_EWMEN_SHIFT)) & EWM_CTRL_EWMEN_MASK) -#define EWM_CTRL_ASSIN_MASK (0x2U) -#define EWM_CTRL_ASSIN_SHIFT (1U) -#define EWM_CTRL_ASSIN(x) (((uint8_t)(((uint8_t)(x)) << EWM_CTRL_ASSIN_SHIFT)) & EWM_CTRL_ASSIN_MASK) -#define EWM_CTRL_INEN_MASK (0x4U) -#define EWM_CTRL_INEN_SHIFT (2U) -#define EWM_CTRL_INEN(x) (((uint8_t)(((uint8_t)(x)) << EWM_CTRL_INEN_SHIFT)) & EWM_CTRL_INEN_MASK) -#define EWM_CTRL_INTEN_MASK (0x8U) -#define EWM_CTRL_INTEN_SHIFT (3U) -#define EWM_CTRL_INTEN(x) (((uint8_t)(((uint8_t)(x)) << EWM_CTRL_INTEN_SHIFT)) & EWM_CTRL_INTEN_MASK) - -/*! @name SERV - Service Register */ -#define EWM_SERV_SERVICE_MASK (0xFFU) -#define EWM_SERV_SERVICE_SHIFT (0U) -#define EWM_SERV_SERVICE(x) (((uint8_t)(((uint8_t)(x)) << EWM_SERV_SERVICE_SHIFT)) & EWM_SERV_SERVICE_MASK) - -/*! @name CMPL - Compare Low Register */ -#define EWM_CMPL_COMPAREL_MASK (0xFFU) -#define EWM_CMPL_COMPAREL_SHIFT (0U) -#define EWM_CMPL_COMPAREL(x) (((uint8_t)(((uint8_t)(x)) << EWM_CMPL_COMPAREL_SHIFT)) & EWM_CMPL_COMPAREL_MASK) - -/*! @name CMPH - Compare High Register */ -#define EWM_CMPH_COMPAREH_MASK (0xFFU) -#define EWM_CMPH_COMPAREH_SHIFT (0U) -#define EWM_CMPH_COMPAREH(x) (((uint8_t)(((uint8_t)(x)) << EWM_CMPH_COMPAREH_SHIFT)) & EWM_CMPH_COMPAREH_MASK) - - -/*! - * @} - */ /* end of group EWM_Register_Masks */ - - -/* EWM - Peripheral instance base addresses */ -/** Peripheral EWM base address */ -#define EWM_BASE (0x40061000u) -/** Peripheral EWM base pointer */ -#define EWM ((EWM_Type *)EWM_BASE) -/** Array initializer of EWM peripheral base addresses */ -#define EWM_BASE_ADDRS { EWM_BASE } -/** Array initializer of EWM peripheral base pointers */ -#define EWM_BASE_PTRS { EWM } -/** Interrupt vectors for the EWM peripheral type */ -#define EWM_IRQS { WDOG_EWM_IRQn } - -/*! - * @} - */ /* end of group EWM_Peripheral_Access_Layer */ - - -/* ---------------------------------------------------------------------------- - -- FB Peripheral Access Layer - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup FB_Peripheral_Access_Layer FB Peripheral Access Layer - * @{ - */ - -/** FB - Register Layout Typedef */ -typedef struct { - struct { /* offset: 0x0, array step: 0xC */ - __IO uint32_t CSAR; /**< Chip Select Address Register, array offset: 0x0, array step: 0xC */ - __IO uint32_t CSMR; /**< Chip Select Mask Register, array offset: 0x4, array step: 0xC */ - __IO uint32_t CSCR; /**< Chip Select Control Register, array offset: 0x8, array step: 0xC */ - } CS[6]; - uint8_t RESERVED_0[24]; - __IO uint32_t CSPMCR; /**< Chip Select port Multiplexing Control Register, offset: 0x60 */ -} FB_Type; - -/* ---------------------------------------------------------------------------- - -- FB Register Masks - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup FB_Register_Masks FB Register Masks - * @{ - */ - -/*! @name CSAR - Chip Select Address Register */ -#define FB_CSAR_BA_MASK (0xFFFF0000U) -#define FB_CSAR_BA_SHIFT (16U) -#define FB_CSAR_BA(x) (((uint32_t)(((uint32_t)(x)) << FB_CSAR_BA_SHIFT)) & FB_CSAR_BA_MASK) - -/* The count of FB_CSAR */ -#define FB_CSAR_COUNT (6U) - -/*! @name CSMR - Chip Select Mask Register */ -#define FB_CSMR_V_MASK (0x1U) -#define FB_CSMR_V_SHIFT (0U) -#define FB_CSMR_V(x) (((uint32_t)(((uint32_t)(x)) << FB_CSMR_V_SHIFT)) & FB_CSMR_V_MASK) -#define FB_CSMR_WP_MASK (0x100U) -#define FB_CSMR_WP_SHIFT (8U) -#define FB_CSMR_WP(x) (((uint32_t)(((uint32_t)(x)) << FB_CSMR_WP_SHIFT)) & FB_CSMR_WP_MASK) -#define FB_CSMR_BAM_MASK (0xFFFF0000U) -#define FB_CSMR_BAM_SHIFT (16U) -#define FB_CSMR_BAM(x) (((uint32_t)(((uint32_t)(x)) << FB_CSMR_BAM_SHIFT)) & FB_CSMR_BAM_MASK) - -/* The count of FB_CSMR */ -#define FB_CSMR_COUNT (6U) - -/*! @name CSCR - Chip Select Control Register */ -#define FB_CSCR_BSTW_MASK (0x8U) -#define FB_CSCR_BSTW_SHIFT (3U) -#define FB_CSCR_BSTW(x) (((uint32_t)(((uint32_t)(x)) << FB_CSCR_BSTW_SHIFT)) & FB_CSCR_BSTW_MASK) -#define FB_CSCR_BSTR_MASK (0x10U) -#define FB_CSCR_BSTR_SHIFT (4U) -#define FB_CSCR_BSTR(x) (((uint32_t)(((uint32_t)(x)) << FB_CSCR_BSTR_SHIFT)) & FB_CSCR_BSTR_MASK) -#define FB_CSCR_BEM_MASK (0x20U) -#define FB_CSCR_BEM_SHIFT (5U) -#define FB_CSCR_BEM(x) (((uint32_t)(((uint32_t)(x)) << FB_CSCR_BEM_SHIFT)) & FB_CSCR_BEM_MASK) -#define FB_CSCR_PS_MASK (0xC0U) -#define FB_CSCR_PS_SHIFT (6U) -#define FB_CSCR_PS(x) (((uint32_t)(((uint32_t)(x)) << FB_CSCR_PS_SHIFT)) & FB_CSCR_PS_MASK) -#define FB_CSCR_AA_MASK (0x100U) -#define FB_CSCR_AA_SHIFT (8U) -#define FB_CSCR_AA(x) (((uint32_t)(((uint32_t)(x)) << FB_CSCR_AA_SHIFT)) & FB_CSCR_AA_MASK) -#define FB_CSCR_BLS_MASK (0x200U) -#define FB_CSCR_BLS_SHIFT (9U) -#define FB_CSCR_BLS(x) (((uint32_t)(((uint32_t)(x)) << FB_CSCR_BLS_SHIFT)) & FB_CSCR_BLS_MASK) -#define FB_CSCR_WS_MASK (0xFC00U) -#define FB_CSCR_WS_SHIFT (10U) -#define FB_CSCR_WS(x) (((uint32_t)(((uint32_t)(x)) << FB_CSCR_WS_SHIFT)) & FB_CSCR_WS_MASK) -#define FB_CSCR_WRAH_MASK (0x30000U) -#define FB_CSCR_WRAH_SHIFT (16U) -#define FB_CSCR_WRAH(x) (((uint32_t)(((uint32_t)(x)) << FB_CSCR_WRAH_SHIFT)) & FB_CSCR_WRAH_MASK) -#define FB_CSCR_RDAH_MASK (0xC0000U) -#define FB_CSCR_RDAH_SHIFT (18U) -#define FB_CSCR_RDAH(x) (((uint32_t)(((uint32_t)(x)) << FB_CSCR_RDAH_SHIFT)) & FB_CSCR_RDAH_MASK) -#define FB_CSCR_ASET_MASK (0x300000U) -#define FB_CSCR_ASET_SHIFT (20U) -#define FB_CSCR_ASET(x) (((uint32_t)(((uint32_t)(x)) << FB_CSCR_ASET_SHIFT)) & FB_CSCR_ASET_MASK) -#define FB_CSCR_EXTS_MASK (0x400000U) -#define FB_CSCR_EXTS_SHIFT (22U) -#define FB_CSCR_EXTS(x) (((uint32_t)(((uint32_t)(x)) << FB_CSCR_EXTS_SHIFT)) & FB_CSCR_EXTS_MASK) -#define FB_CSCR_SWSEN_MASK (0x800000U) -#define FB_CSCR_SWSEN_SHIFT (23U) -#define FB_CSCR_SWSEN(x) (((uint32_t)(((uint32_t)(x)) << FB_CSCR_SWSEN_SHIFT)) & FB_CSCR_SWSEN_MASK) -#define FB_CSCR_SWS_MASK (0xFC000000U) -#define FB_CSCR_SWS_SHIFT (26U) -#define FB_CSCR_SWS(x) (((uint32_t)(((uint32_t)(x)) << FB_CSCR_SWS_SHIFT)) & FB_CSCR_SWS_MASK) - -/* The count of FB_CSCR */ -#define FB_CSCR_COUNT (6U) - -/*! @name CSPMCR - Chip Select port Multiplexing Control Register */ -#define FB_CSPMCR_GROUP5_MASK (0xF000U) -#define FB_CSPMCR_GROUP5_SHIFT (12U) -#define FB_CSPMCR_GROUP5(x) (((uint32_t)(((uint32_t)(x)) << FB_CSPMCR_GROUP5_SHIFT)) & FB_CSPMCR_GROUP5_MASK) -#define FB_CSPMCR_GROUP4_MASK (0xF0000U) -#define FB_CSPMCR_GROUP4_SHIFT (16U) -#define FB_CSPMCR_GROUP4(x) (((uint32_t)(((uint32_t)(x)) << FB_CSPMCR_GROUP4_SHIFT)) & FB_CSPMCR_GROUP4_MASK) -#define FB_CSPMCR_GROUP3_MASK (0xF00000U) -#define FB_CSPMCR_GROUP3_SHIFT (20U) -#define FB_CSPMCR_GROUP3(x) (((uint32_t)(((uint32_t)(x)) << FB_CSPMCR_GROUP3_SHIFT)) & FB_CSPMCR_GROUP3_MASK) -#define FB_CSPMCR_GROUP2_MASK (0xF000000U) -#define FB_CSPMCR_GROUP2_SHIFT (24U) -#define FB_CSPMCR_GROUP2(x) (((uint32_t)(((uint32_t)(x)) << FB_CSPMCR_GROUP2_SHIFT)) & FB_CSPMCR_GROUP2_MASK) -#define FB_CSPMCR_GROUP1_MASK (0xF0000000U) -#define FB_CSPMCR_GROUP1_SHIFT (28U) -#define FB_CSPMCR_GROUP1(x) (((uint32_t)(((uint32_t)(x)) << FB_CSPMCR_GROUP1_SHIFT)) & FB_CSPMCR_GROUP1_MASK) - - -/*! - * @} - */ /* end of group FB_Register_Masks */ - - -/* FB - Peripheral instance base addresses */ -/** Peripheral FB base address */ -#define FB_BASE (0x4000C000u) -/** Peripheral FB base pointer */ -#define FB ((FB_Type *)FB_BASE) -/** Array initializer of FB peripheral base addresses */ -#define FB_BASE_ADDRS { FB_BASE } -/** Array initializer of FB peripheral base pointers */ -#define FB_BASE_PTRS { FB } - -/*! - * @} - */ /* end of group FB_Peripheral_Access_Layer */ - - -/* ---------------------------------------------------------------------------- - -- FMC Peripheral Access Layer - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup FMC_Peripheral_Access_Layer FMC Peripheral Access Layer - * @{ - */ - -/** FMC - Register Layout Typedef */ -typedef struct { - __IO uint32_t PFAPR; /**< Flash Access Protection Register, offset: 0x0 */ - __IO uint32_t PFB0CR; /**< Flash Bank 0 Control Register, offset: 0x4 */ - __IO uint32_t PFB1CR; /**< Flash Bank 1 Control Register, offset: 0x8 */ - uint8_t RESERVED_0[244]; - __IO uint32_t TAGVDW0S[4]; /**< Cache Tag Storage, array offset: 0x100, array step: 0x4 */ - __IO uint32_t TAGVDW1S[4]; /**< Cache Tag Storage, array offset: 0x110, array step: 0x4 */ - __IO uint32_t TAGVDW2S[4]; /**< Cache Tag Storage, array offset: 0x120, array step: 0x4 */ - __IO uint32_t TAGVDW3S[4]; /**< Cache Tag Storage, array offset: 0x130, array step: 0x4 */ - uint8_t RESERVED_1[192]; - struct { /* offset: 0x200, array step: index*0x20, index2*0x8 */ - __IO uint32_t DATA_U; /**< Cache Data Storage (upper word), array offset: 0x200, array step: index*0x20, index2*0x8 */ - __IO uint32_t DATA_L; /**< Cache Data Storage (lower word), array offset: 0x204, array step: index*0x20, index2*0x8 */ - } SET[4][4]; -} FMC_Type; - -/* ---------------------------------------------------------------------------- - -- FMC Register Masks - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup FMC_Register_Masks FMC Register Masks - * @{ - */ - -/*! @name PFAPR - Flash Access Protection Register */ -#define FMC_PFAPR_M0AP_MASK (0x3U) -#define FMC_PFAPR_M0AP_SHIFT (0U) -#define FMC_PFAPR_M0AP(x) (((uint32_t)(((uint32_t)(x)) << FMC_PFAPR_M0AP_SHIFT)) & FMC_PFAPR_M0AP_MASK) -#define FMC_PFAPR_M1AP_MASK (0xCU) -#define FMC_PFAPR_M1AP_SHIFT (2U) -#define FMC_PFAPR_M1AP(x) (((uint32_t)(((uint32_t)(x)) << FMC_PFAPR_M1AP_SHIFT)) & FMC_PFAPR_M1AP_MASK) -#define FMC_PFAPR_M2AP_MASK (0x30U) -#define FMC_PFAPR_M2AP_SHIFT (4U) -#define FMC_PFAPR_M2AP(x) (((uint32_t)(((uint32_t)(x)) << FMC_PFAPR_M2AP_SHIFT)) & FMC_PFAPR_M2AP_MASK) -#define FMC_PFAPR_M3AP_MASK (0xC0U) -#define FMC_PFAPR_M3AP_SHIFT (6U) -#define FMC_PFAPR_M3AP(x) (((uint32_t)(((uint32_t)(x)) << FMC_PFAPR_M3AP_SHIFT)) & FMC_PFAPR_M3AP_MASK) -#define FMC_PFAPR_M4AP_MASK (0x300U) -#define FMC_PFAPR_M4AP_SHIFT (8U) -#define FMC_PFAPR_M4AP(x) (((uint32_t)(((uint32_t)(x)) << FMC_PFAPR_M4AP_SHIFT)) & FMC_PFAPR_M4AP_MASK) -#define FMC_PFAPR_M5AP_MASK (0xC00U) -#define FMC_PFAPR_M5AP_SHIFT (10U) -#define FMC_PFAPR_M5AP(x) (((uint32_t)(((uint32_t)(x)) << FMC_PFAPR_M5AP_SHIFT)) & FMC_PFAPR_M5AP_MASK) -#define FMC_PFAPR_M6AP_MASK (0x3000U) -#define FMC_PFAPR_M6AP_SHIFT (12U) -#define FMC_PFAPR_M6AP(x) (((uint32_t)(((uint32_t)(x)) << FMC_PFAPR_M6AP_SHIFT)) & FMC_PFAPR_M6AP_MASK) -#define FMC_PFAPR_M7AP_MASK (0xC000U) -#define FMC_PFAPR_M7AP_SHIFT (14U) -#define FMC_PFAPR_M7AP(x) (((uint32_t)(((uint32_t)(x)) << FMC_PFAPR_M7AP_SHIFT)) & FMC_PFAPR_M7AP_MASK) -#define FMC_PFAPR_M0PFD_MASK (0x10000U) -#define FMC_PFAPR_M0PFD_SHIFT (16U) -#define FMC_PFAPR_M0PFD(x) (((uint32_t)(((uint32_t)(x)) << FMC_PFAPR_M0PFD_SHIFT)) & FMC_PFAPR_M0PFD_MASK) -#define FMC_PFAPR_M1PFD_MASK (0x20000U) -#define FMC_PFAPR_M1PFD_SHIFT (17U) -#define FMC_PFAPR_M1PFD(x) (((uint32_t)(((uint32_t)(x)) << FMC_PFAPR_M1PFD_SHIFT)) & FMC_PFAPR_M1PFD_MASK) -#define FMC_PFAPR_M2PFD_MASK (0x40000U) -#define FMC_PFAPR_M2PFD_SHIFT (18U) -#define FMC_PFAPR_M2PFD(x) (((uint32_t)(((uint32_t)(x)) << FMC_PFAPR_M2PFD_SHIFT)) & FMC_PFAPR_M2PFD_MASK) -#define FMC_PFAPR_M3PFD_MASK (0x80000U) -#define FMC_PFAPR_M3PFD_SHIFT (19U) -#define FMC_PFAPR_M3PFD(x) (((uint32_t)(((uint32_t)(x)) << FMC_PFAPR_M3PFD_SHIFT)) & FMC_PFAPR_M3PFD_MASK) -#define FMC_PFAPR_M4PFD_MASK (0x100000U) -#define FMC_PFAPR_M4PFD_SHIFT (20U) -#define FMC_PFAPR_M4PFD(x) (((uint32_t)(((uint32_t)(x)) << FMC_PFAPR_M4PFD_SHIFT)) & FMC_PFAPR_M4PFD_MASK) -#define FMC_PFAPR_M5PFD_MASK (0x200000U) -#define FMC_PFAPR_M5PFD_SHIFT (21U) -#define FMC_PFAPR_M5PFD(x) (((uint32_t)(((uint32_t)(x)) << FMC_PFAPR_M5PFD_SHIFT)) & FMC_PFAPR_M5PFD_MASK) -#define FMC_PFAPR_M6PFD_MASK (0x400000U) -#define FMC_PFAPR_M6PFD_SHIFT (22U) -#define FMC_PFAPR_M6PFD(x) (((uint32_t)(((uint32_t)(x)) << FMC_PFAPR_M6PFD_SHIFT)) & FMC_PFAPR_M6PFD_MASK) -#define FMC_PFAPR_M7PFD_MASK (0x800000U) -#define FMC_PFAPR_M7PFD_SHIFT (23U) -#define FMC_PFAPR_M7PFD(x) (((uint32_t)(((uint32_t)(x)) << FMC_PFAPR_M7PFD_SHIFT)) & FMC_PFAPR_M7PFD_MASK) - -/*! @name PFB0CR - Flash Bank 0 Control Register */ -#define FMC_PFB0CR_B0SEBE_MASK (0x1U) -#define FMC_PFB0CR_B0SEBE_SHIFT (0U) -#define FMC_PFB0CR_B0SEBE(x) (((uint32_t)(((uint32_t)(x)) << FMC_PFB0CR_B0SEBE_SHIFT)) & FMC_PFB0CR_B0SEBE_MASK) -#define FMC_PFB0CR_B0IPE_MASK (0x2U) -#define FMC_PFB0CR_B0IPE_SHIFT (1U) -#define FMC_PFB0CR_B0IPE(x) (((uint32_t)(((uint32_t)(x)) << FMC_PFB0CR_B0IPE_SHIFT)) & FMC_PFB0CR_B0IPE_MASK) -#define FMC_PFB0CR_B0DPE_MASK (0x4U) -#define FMC_PFB0CR_B0DPE_SHIFT (2U) -#define FMC_PFB0CR_B0DPE(x) (((uint32_t)(((uint32_t)(x)) << FMC_PFB0CR_B0DPE_SHIFT)) & FMC_PFB0CR_B0DPE_MASK) -#define FMC_PFB0CR_B0ICE_MASK (0x8U) -#define FMC_PFB0CR_B0ICE_SHIFT (3U) -#define FMC_PFB0CR_B0ICE(x) (((uint32_t)(((uint32_t)(x)) << FMC_PFB0CR_B0ICE_SHIFT)) & FMC_PFB0CR_B0ICE_MASK) -#define FMC_PFB0CR_B0DCE_MASK (0x10U) -#define FMC_PFB0CR_B0DCE_SHIFT (4U) -#define FMC_PFB0CR_B0DCE(x) (((uint32_t)(((uint32_t)(x)) << FMC_PFB0CR_B0DCE_SHIFT)) & FMC_PFB0CR_B0DCE_MASK) -#define FMC_PFB0CR_CRC_MASK (0xE0U) -#define FMC_PFB0CR_CRC_SHIFT (5U) -#define FMC_PFB0CR_CRC(x) (((uint32_t)(((uint32_t)(x)) << FMC_PFB0CR_CRC_SHIFT)) & FMC_PFB0CR_CRC_MASK) -#define FMC_PFB0CR_B0MW_MASK (0x60000U) -#define FMC_PFB0CR_B0MW_SHIFT (17U) -#define FMC_PFB0CR_B0MW(x) (((uint32_t)(((uint32_t)(x)) << FMC_PFB0CR_B0MW_SHIFT)) & FMC_PFB0CR_B0MW_MASK) -#define FMC_PFB0CR_S_B_INV_MASK (0x80000U) -#define FMC_PFB0CR_S_B_INV_SHIFT (19U) -#define FMC_PFB0CR_S_B_INV(x) (((uint32_t)(((uint32_t)(x)) << FMC_PFB0CR_S_B_INV_SHIFT)) & FMC_PFB0CR_S_B_INV_MASK) -#define FMC_PFB0CR_CINV_WAY_MASK (0xF00000U) -#define FMC_PFB0CR_CINV_WAY_SHIFT (20U) -#define FMC_PFB0CR_CINV_WAY(x) (((uint32_t)(((uint32_t)(x)) << FMC_PFB0CR_CINV_WAY_SHIFT)) & FMC_PFB0CR_CINV_WAY_MASK) -#define FMC_PFB0CR_CLCK_WAY_MASK (0xF000000U) -#define FMC_PFB0CR_CLCK_WAY_SHIFT (24U) -#define FMC_PFB0CR_CLCK_WAY(x) (((uint32_t)(((uint32_t)(x)) << FMC_PFB0CR_CLCK_WAY_SHIFT)) & FMC_PFB0CR_CLCK_WAY_MASK) -#define FMC_PFB0CR_B0RWSC_MASK (0xF0000000U) -#define FMC_PFB0CR_B0RWSC_SHIFT (28U) -#define FMC_PFB0CR_B0RWSC(x) (((uint32_t)(((uint32_t)(x)) << FMC_PFB0CR_B0RWSC_SHIFT)) & FMC_PFB0CR_B0RWSC_MASK) - -/*! @name PFB1CR - Flash Bank 1 Control Register */ -#define FMC_PFB1CR_B1SEBE_MASK (0x1U) -#define FMC_PFB1CR_B1SEBE_SHIFT (0U) -#define FMC_PFB1CR_B1SEBE(x) (((uint32_t)(((uint32_t)(x)) << FMC_PFB1CR_B1SEBE_SHIFT)) & FMC_PFB1CR_B1SEBE_MASK) -#define FMC_PFB1CR_B1IPE_MASK (0x2U) -#define FMC_PFB1CR_B1IPE_SHIFT (1U) -#define FMC_PFB1CR_B1IPE(x) (((uint32_t)(((uint32_t)(x)) << FMC_PFB1CR_B1IPE_SHIFT)) & FMC_PFB1CR_B1IPE_MASK) -#define FMC_PFB1CR_B1DPE_MASK (0x4U) -#define FMC_PFB1CR_B1DPE_SHIFT (2U) -#define FMC_PFB1CR_B1DPE(x) (((uint32_t)(((uint32_t)(x)) << FMC_PFB1CR_B1DPE_SHIFT)) & FMC_PFB1CR_B1DPE_MASK) -#define FMC_PFB1CR_B1ICE_MASK (0x8U) -#define FMC_PFB1CR_B1ICE_SHIFT (3U) -#define FMC_PFB1CR_B1ICE(x) (((uint32_t)(((uint32_t)(x)) << FMC_PFB1CR_B1ICE_SHIFT)) & FMC_PFB1CR_B1ICE_MASK) -#define FMC_PFB1CR_B1DCE_MASK (0x10U) -#define FMC_PFB1CR_B1DCE_SHIFT (4U) -#define FMC_PFB1CR_B1DCE(x) (((uint32_t)(((uint32_t)(x)) << FMC_PFB1CR_B1DCE_SHIFT)) & FMC_PFB1CR_B1DCE_MASK) -#define FMC_PFB1CR_B1MW_MASK (0x60000U) -#define FMC_PFB1CR_B1MW_SHIFT (17U) -#define FMC_PFB1CR_B1MW(x) (((uint32_t)(((uint32_t)(x)) << FMC_PFB1CR_B1MW_SHIFT)) & FMC_PFB1CR_B1MW_MASK) -#define FMC_PFB1CR_B1RWSC_MASK (0xF0000000U) -#define FMC_PFB1CR_B1RWSC_SHIFT (28U) -#define FMC_PFB1CR_B1RWSC(x) (((uint32_t)(((uint32_t)(x)) << FMC_PFB1CR_B1RWSC_SHIFT)) & FMC_PFB1CR_B1RWSC_MASK) - -/*! @name TAGVDW0S - Cache Tag Storage */ -#define FMC_TAGVDW0S_valid_MASK (0x1U) -#define FMC_TAGVDW0S_valid_SHIFT (0U) -#define FMC_TAGVDW0S_valid(x) (((uint32_t)(((uint32_t)(x)) << FMC_TAGVDW0S_valid_SHIFT)) & FMC_TAGVDW0S_valid_MASK) -#define FMC_TAGVDW0S_tag_MASK (0x7FFE0U) -#define FMC_TAGVDW0S_tag_SHIFT (5U) -#define FMC_TAGVDW0S_tag(x) (((uint32_t)(((uint32_t)(x)) << FMC_TAGVDW0S_tag_SHIFT)) & FMC_TAGVDW0S_tag_MASK) - -/* The count of FMC_TAGVDW0S */ -#define FMC_TAGVDW0S_COUNT (4U) - -/*! @name TAGVDW1S - Cache Tag Storage */ -#define FMC_TAGVDW1S_valid_MASK (0x1U) -#define FMC_TAGVDW1S_valid_SHIFT (0U) -#define FMC_TAGVDW1S_valid(x) (((uint32_t)(((uint32_t)(x)) << FMC_TAGVDW1S_valid_SHIFT)) & FMC_TAGVDW1S_valid_MASK) -#define FMC_TAGVDW1S_tag_MASK (0x7FFE0U) -#define FMC_TAGVDW1S_tag_SHIFT (5U) -#define FMC_TAGVDW1S_tag(x) (((uint32_t)(((uint32_t)(x)) << FMC_TAGVDW1S_tag_SHIFT)) & FMC_TAGVDW1S_tag_MASK) - -/* The count of FMC_TAGVDW1S */ -#define FMC_TAGVDW1S_COUNT (4U) - -/*! @name TAGVDW2S - Cache Tag Storage */ -#define FMC_TAGVDW2S_valid_MASK (0x1U) -#define FMC_TAGVDW2S_valid_SHIFT (0U) -#define FMC_TAGVDW2S_valid(x) (((uint32_t)(((uint32_t)(x)) << FMC_TAGVDW2S_valid_SHIFT)) & FMC_TAGVDW2S_valid_MASK) -#define FMC_TAGVDW2S_tag_MASK (0x7FFE0U) -#define FMC_TAGVDW2S_tag_SHIFT (5U) -#define FMC_TAGVDW2S_tag(x) (((uint32_t)(((uint32_t)(x)) << FMC_TAGVDW2S_tag_SHIFT)) & FMC_TAGVDW2S_tag_MASK) - -/* The count of FMC_TAGVDW2S */ -#define FMC_TAGVDW2S_COUNT (4U) - -/*! @name TAGVDW3S - Cache Tag Storage */ -#define FMC_TAGVDW3S_valid_MASK (0x1U) -#define FMC_TAGVDW3S_valid_SHIFT (0U) -#define FMC_TAGVDW3S_valid(x) (((uint32_t)(((uint32_t)(x)) << FMC_TAGVDW3S_valid_SHIFT)) & FMC_TAGVDW3S_valid_MASK) -#define FMC_TAGVDW3S_tag_MASK (0x7FFE0U) -#define FMC_TAGVDW3S_tag_SHIFT (5U) -#define FMC_TAGVDW3S_tag(x) (((uint32_t)(((uint32_t)(x)) << FMC_TAGVDW3S_tag_SHIFT)) & FMC_TAGVDW3S_tag_MASK) - -/* The count of FMC_TAGVDW3S */ -#define FMC_TAGVDW3S_COUNT (4U) - -/*! @name DATA_U - Cache Data Storage (upper word) */ -#define FMC_DATA_U_data_MASK (0xFFFFFFFFU) -#define FMC_DATA_U_data_SHIFT (0U) -#define FMC_DATA_U_data(x) (((uint32_t)(((uint32_t)(x)) << FMC_DATA_U_data_SHIFT)) & FMC_DATA_U_data_MASK) - -/* The count of FMC_DATA_U */ -#define FMC_DATA_U_COUNT (4U) - -/* The count of FMC_DATA_U */ -#define FMC_DATA_U_COUNT2 (4U) - -/*! @name DATA_L - Cache Data Storage (lower word) */ -#define FMC_DATA_L_data_MASK (0xFFFFFFFFU) -#define FMC_DATA_L_data_SHIFT (0U) -#define FMC_DATA_L_data(x) (((uint32_t)(((uint32_t)(x)) << FMC_DATA_L_data_SHIFT)) & FMC_DATA_L_data_MASK) - -/* The count of FMC_DATA_L */ -#define FMC_DATA_L_COUNT (4U) - -/* The count of FMC_DATA_L */ -#define FMC_DATA_L_COUNT2 (4U) - - -/*! - * @} - */ /* end of group FMC_Register_Masks */ - - -/* FMC - Peripheral instance base addresses */ -/** Peripheral FMC base address */ -#define FMC_BASE (0x4001F000u) -/** Peripheral FMC base pointer */ -#define FMC ((FMC_Type *)FMC_BASE) -/** Array initializer of FMC peripheral base addresses */ -#define FMC_BASE_ADDRS { FMC_BASE } -/** Array initializer of FMC peripheral base pointers */ -#define FMC_BASE_PTRS { FMC } - -/*! - * @} - */ /* end of group FMC_Peripheral_Access_Layer */ - - -/* ---------------------------------------------------------------------------- - -- FTFE Peripheral Access Layer - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup FTFE_Peripheral_Access_Layer FTFE Peripheral Access Layer - * @{ - */ - -/** FTFE - Register Layout Typedef */ -typedef struct { - __IO uint8_t FSTAT; /**< Flash Status Register, offset: 0x0 */ - __IO uint8_t FCNFG; /**< Flash Configuration Register, offset: 0x1 */ - __I uint8_t FSEC; /**< Flash Security Register, offset: 0x2 */ - __I uint8_t FOPT; /**< Flash Option Register, offset: 0x3 */ - __IO uint8_t FCCOB3; /**< Flash Common Command Object Registers, offset: 0x4 */ - __IO uint8_t FCCOB2; /**< Flash Common Command Object Registers, offset: 0x5 */ - __IO uint8_t FCCOB1; /**< Flash Common Command Object Registers, offset: 0x6 */ - __IO uint8_t FCCOB0; /**< Flash Common Command Object Registers, offset: 0x7 */ - __IO uint8_t FCCOB7; /**< Flash Common Command Object Registers, offset: 0x8 */ - __IO uint8_t FCCOB6; /**< Flash Common Command Object Registers, offset: 0x9 */ - __IO uint8_t FCCOB5; /**< Flash Common Command Object Registers, offset: 0xA */ - __IO uint8_t FCCOB4; /**< Flash Common Command Object Registers, offset: 0xB */ - __IO uint8_t FCCOBB; /**< Flash Common Command Object Registers, offset: 0xC */ - __IO uint8_t FCCOBA; /**< Flash Common Command Object Registers, offset: 0xD */ - __IO uint8_t FCCOB9; /**< Flash Common Command Object Registers, offset: 0xE */ - __IO uint8_t FCCOB8; /**< Flash Common Command Object Registers, offset: 0xF */ - __IO uint8_t FPROT3; /**< Program Flash Protection Registers, offset: 0x10 */ - __IO uint8_t FPROT2; /**< Program Flash Protection Registers, offset: 0x11 */ - __IO uint8_t FPROT1; /**< Program Flash Protection Registers, offset: 0x12 */ - __IO uint8_t FPROT0; /**< Program Flash Protection Registers, offset: 0x13 */ -} FTFE_Type; - -/* ---------------------------------------------------------------------------- - -- FTFE Register Masks - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup FTFE_Register_Masks FTFE Register Masks - * @{ - */ - -/*! @name FSTAT - Flash Status Register */ -#define FTFE_FSTAT_MGSTAT0_MASK (0x1U) -#define FTFE_FSTAT_MGSTAT0_SHIFT (0U) -#define FTFE_FSTAT_MGSTAT0(x) (((uint8_t)(((uint8_t)(x)) << FTFE_FSTAT_MGSTAT0_SHIFT)) & FTFE_FSTAT_MGSTAT0_MASK) -#define FTFE_FSTAT_FPVIOL_MASK (0x10U) -#define FTFE_FSTAT_FPVIOL_SHIFT (4U) -#define FTFE_FSTAT_FPVIOL(x) (((uint8_t)(((uint8_t)(x)) << FTFE_FSTAT_FPVIOL_SHIFT)) & FTFE_FSTAT_FPVIOL_MASK) -#define FTFE_FSTAT_ACCERR_MASK (0x20U) -#define FTFE_FSTAT_ACCERR_SHIFT (5U) -#define FTFE_FSTAT_ACCERR(x) (((uint8_t)(((uint8_t)(x)) << FTFE_FSTAT_ACCERR_SHIFT)) & FTFE_FSTAT_ACCERR_MASK) -#define FTFE_FSTAT_RDCOLERR_MASK (0x40U) -#define FTFE_FSTAT_RDCOLERR_SHIFT (6U) -#define FTFE_FSTAT_RDCOLERR(x) (((uint8_t)(((uint8_t)(x)) << FTFE_FSTAT_RDCOLERR_SHIFT)) & FTFE_FSTAT_RDCOLERR_MASK) -#define FTFE_FSTAT_CCIF_MASK (0x80U) -#define FTFE_FSTAT_CCIF_SHIFT (7U) -#define FTFE_FSTAT_CCIF(x) (((uint8_t)(((uint8_t)(x)) << FTFE_FSTAT_CCIF_SHIFT)) & FTFE_FSTAT_CCIF_MASK) - -/*! @name FCNFG - Flash Configuration Register */ -#define FTFE_FCNFG_EEERDY_MASK (0x1U) -#define FTFE_FCNFG_EEERDY_SHIFT (0U) -#define FTFE_FCNFG_EEERDY(x) (((uint8_t)(((uint8_t)(x)) << FTFE_FCNFG_EEERDY_SHIFT)) & FTFE_FCNFG_EEERDY_MASK) -#define FTFE_FCNFG_RAMRDY_MASK (0x2U) -#define FTFE_FCNFG_RAMRDY_SHIFT (1U) -#define FTFE_FCNFG_RAMRDY(x) (((uint8_t)(((uint8_t)(x)) << FTFE_FCNFG_RAMRDY_SHIFT)) & FTFE_FCNFG_RAMRDY_MASK) -#define FTFE_FCNFG_PFLSH_MASK (0x4U) -#define FTFE_FCNFG_PFLSH_SHIFT (2U) -#define FTFE_FCNFG_PFLSH(x) (((uint8_t)(((uint8_t)(x)) << FTFE_FCNFG_PFLSH_SHIFT)) & FTFE_FCNFG_PFLSH_MASK) -#define FTFE_FCNFG_SWAP_MASK (0x8U) -#define FTFE_FCNFG_SWAP_SHIFT (3U) -#define FTFE_FCNFG_SWAP(x) (((uint8_t)(((uint8_t)(x)) << FTFE_FCNFG_SWAP_SHIFT)) & FTFE_FCNFG_SWAP_MASK) -#define FTFE_FCNFG_ERSSUSP_MASK (0x10U) -#define FTFE_FCNFG_ERSSUSP_SHIFT (4U) -#define FTFE_FCNFG_ERSSUSP(x) (((uint8_t)(((uint8_t)(x)) << FTFE_FCNFG_ERSSUSP_SHIFT)) & FTFE_FCNFG_ERSSUSP_MASK) -#define FTFE_FCNFG_ERSAREQ_MASK (0x20U) -#define FTFE_FCNFG_ERSAREQ_SHIFT (5U) -#define FTFE_FCNFG_ERSAREQ(x) (((uint8_t)(((uint8_t)(x)) << FTFE_FCNFG_ERSAREQ_SHIFT)) & FTFE_FCNFG_ERSAREQ_MASK) -#define FTFE_FCNFG_RDCOLLIE_MASK (0x40U) -#define FTFE_FCNFG_RDCOLLIE_SHIFT (6U) -#define FTFE_FCNFG_RDCOLLIE(x) (((uint8_t)(((uint8_t)(x)) << FTFE_FCNFG_RDCOLLIE_SHIFT)) & FTFE_FCNFG_RDCOLLIE_MASK) -#define FTFE_FCNFG_CCIE_MASK (0x80U) -#define FTFE_FCNFG_CCIE_SHIFT (7U) -#define FTFE_FCNFG_CCIE(x) (((uint8_t)(((uint8_t)(x)) << FTFE_FCNFG_CCIE_SHIFT)) & FTFE_FCNFG_CCIE_MASK) - -/*! @name FSEC - Flash Security Register */ -#define FTFE_FSEC_SEC_MASK (0x3U) -#define FTFE_FSEC_SEC_SHIFT (0U) -#define FTFE_FSEC_SEC(x) (((uint8_t)(((uint8_t)(x)) << FTFE_FSEC_SEC_SHIFT)) & FTFE_FSEC_SEC_MASK) -#define FTFE_FSEC_FSLACC_MASK (0xCU) -#define FTFE_FSEC_FSLACC_SHIFT (2U) -#define FTFE_FSEC_FSLACC(x) (((uint8_t)(((uint8_t)(x)) << FTFE_FSEC_FSLACC_SHIFT)) & FTFE_FSEC_FSLACC_MASK) -#define FTFE_FSEC_MEEN_MASK (0x30U) -#define FTFE_FSEC_MEEN_SHIFT (4U) -#define FTFE_FSEC_MEEN(x) (((uint8_t)(((uint8_t)(x)) << FTFE_FSEC_MEEN_SHIFT)) & FTFE_FSEC_MEEN_MASK) -#define FTFE_FSEC_KEYEN_MASK (0xC0U) -#define FTFE_FSEC_KEYEN_SHIFT (6U) -#define FTFE_FSEC_KEYEN(x) (((uint8_t)(((uint8_t)(x)) << FTFE_FSEC_KEYEN_SHIFT)) & FTFE_FSEC_KEYEN_MASK) - -/*! @name FOPT - Flash Option Register */ -#define FTFE_FOPT_OPT_MASK (0xFFU) -#define FTFE_FOPT_OPT_SHIFT (0U) -#define FTFE_FOPT_OPT(x) (((uint8_t)(((uint8_t)(x)) << FTFE_FOPT_OPT_SHIFT)) & FTFE_FOPT_OPT_MASK) - -/*! @name FCCOB3 - Flash Common Command Object Registers */ -#define FTFE_FCCOB3_CCOBn_MASK (0xFFU) -#define FTFE_FCCOB3_CCOBn_SHIFT (0U) -#define FTFE_FCCOB3_CCOBn(x) (((uint8_t)(((uint8_t)(x)) << FTFE_FCCOB3_CCOBn_SHIFT)) & FTFE_FCCOB3_CCOBn_MASK) - -/*! @name FCCOB2 - Flash Common Command Object Registers */ -#define FTFE_FCCOB2_CCOBn_MASK (0xFFU) -#define FTFE_FCCOB2_CCOBn_SHIFT (0U) -#define FTFE_FCCOB2_CCOBn(x) (((uint8_t)(((uint8_t)(x)) << FTFE_FCCOB2_CCOBn_SHIFT)) & FTFE_FCCOB2_CCOBn_MASK) - -/*! @name FCCOB1 - Flash Common Command Object Registers */ -#define FTFE_FCCOB1_CCOBn_MASK (0xFFU) -#define FTFE_FCCOB1_CCOBn_SHIFT (0U) -#define FTFE_FCCOB1_CCOBn(x) (((uint8_t)(((uint8_t)(x)) << FTFE_FCCOB1_CCOBn_SHIFT)) & FTFE_FCCOB1_CCOBn_MASK) - -/*! @name FCCOB0 - Flash Common Command Object Registers */ -#define FTFE_FCCOB0_CCOBn_MASK (0xFFU) -#define FTFE_FCCOB0_CCOBn_SHIFT (0U) -#define FTFE_FCCOB0_CCOBn(x) (((uint8_t)(((uint8_t)(x)) << FTFE_FCCOB0_CCOBn_SHIFT)) & FTFE_FCCOB0_CCOBn_MASK) - -/*! @name FCCOB7 - Flash Common Command Object Registers */ -#define FTFE_FCCOB7_CCOBn_MASK (0xFFU) -#define FTFE_FCCOB7_CCOBn_SHIFT (0U) -#define FTFE_FCCOB7_CCOBn(x) (((uint8_t)(((uint8_t)(x)) << FTFE_FCCOB7_CCOBn_SHIFT)) & FTFE_FCCOB7_CCOBn_MASK) - -/*! @name FCCOB6 - Flash Common Command Object Registers */ -#define FTFE_FCCOB6_CCOBn_MASK (0xFFU) -#define FTFE_FCCOB6_CCOBn_SHIFT (0U) -#define FTFE_FCCOB6_CCOBn(x) (((uint8_t)(((uint8_t)(x)) << FTFE_FCCOB6_CCOBn_SHIFT)) & FTFE_FCCOB6_CCOBn_MASK) - -/*! @name FCCOB5 - Flash Common Command Object Registers */ -#define FTFE_FCCOB5_CCOBn_MASK (0xFFU) -#define FTFE_FCCOB5_CCOBn_SHIFT (0U) -#define FTFE_FCCOB5_CCOBn(x) (((uint8_t)(((uint8_t)(x)) << FTFE_FCCOB5_CCOBn_SHIFT)) & FTFE_FCCOB5_CCOBn_MASK) - -/*! @name FCCOB4 - Flash Common Command Object Registers */ -#define FTFE_FCCOB4_CCOBn_MASK (0xFFU) -#define FTFE_FCCOB4_CCOBn_SHIFT (0U) -#define FTFE_FCCOB4_CCOBn(x) (((uint8_t)(((uint8_t)(x)) << FTFE_FCCOB4_CCOBn_SHIFT)) & FTFE_FCCOB4_CCOBn_MASK) - -/*! @name FCCOBB - Flash Common Command Object Registers */ -#define FTFE_FCCOBB_CCOBn_MASK (0xFFU) -#define FTFE_FCCOBB_CCOBn_SHIFT (0U) -#define FTFE_FCCOBB_CCOBn(x) (((uint8_t)(((uint8_t)(x)) << FTFE_FCCOBB_CCOBn_SHIFT)) & FTFE_FCCOBB_CCOBn_MASK) - -/*! @name FCCOBA - Flash Common Command Object Registers */ -#define FTFE_FCCOBA_CCOBn_MASK (0xFFU) -#define FTFE_FCCOBA_CCOBn_SHIFT (0U) -#define FTFE_FCCOBA_CCOBn(x) (((uint8_t)(((uint8_t)(x)) << FTFE_FCCOBA_CCOBn_SHIFT)) & FTFE_FCCOBA_CCOBn_MASK) - -/*! @name FCCOB9 - Flash Common Command Object Registers */ -#define FTFE_FCCOB9_CCOBn_MASK (0xFFU) -#define FTFE_FCCOB9_CCOBn_SHIFT (0U) -#define FTFE_FCCOB9_CCOBn(x) (((uint8_t)(((uint8_t)(x)) << FTFE_FCCOB9_CCOBn_SHIFT)) & FTFE_FCCOB9_CCOBn_MASK) - -/*! @name FCCOB8 - Flash Common Command Object Registers */ -#define FTFE_FCCOB8_CCOBn_MASK (0xFFU) -#define FTFE_FCCOB8_CCOBn_SHIFT (0U) -#define FTFE_FCCOB8_CCOBn(x) (((uint8_t)(((uint8_t)(x)) << FTFE_FCCOB8_CCOBn_SHIFT)) & FTFE_FCCOB8_CCOBn_MASK) - -/*! @name FPROT3 - Program Flash Protection Registers */ -#define FTFE_FPROT3_PROT_MASK (0xFFU) -#define FTFE_FPROT3_PROT_SHIFT (0U) -#define FTFE_FPROT3_PROT(x) (((uint8_t)(((uint8_t)(x)) << FTFE_FPROT3_PROT_SHIFT)) & FTFE_FPROT3_PROT_MASK) - -/*! @name FPROT2 - Program Flash Protection Registers */ -#define FTFE_FPROT2_PROT_MASK (0xFFU) -#define FTFE_FPROT2_PROT_SHIFT (0U) -#define FTFE_FPROT2_PROT(x) (((uint8_t)(((uint8_t)(x)) << FTFE_FPROT2_PROT_SHIFT)) & FTFE_FPROT2_PROT_MASK) - -/*! @name FPROT1 - Program Flash Protection Registers */ -#define FTFE_FPROT1_PROT_MASK (0xFFU) -#define FTFE_FPROT1_PROT_SHIFT (0U) -#define FTFE_FPROT1_PROT(x) (((uint8_t)(((uint8_t)(x)) << FTFE_FPROT1_PROT_SHIFT)) & FTFE_FPROT1_PROT_MASK) - -/*! @name FPROT0 - Program Flash Protection Registers */ -#define FTFE_FPROT0_PROT_MASK (0xFFU) -#define FTFE_FPROT0_PROT_SHIFT (0U) -#define FTFE_FPROT0_PROT(x) (((uint8_t)(((uint8_t)(x)) << FTFE_FPROT0_PROT_SHIFT)) & FTFE_FPROT0_PROT_MASK) - - -/*! - * @} - */ /* end of group FTFE_Register_Masks */ - - -/* FTFE - Peripheral instance base addresses */ -/** Peripheral FTFE base address */ -#define FTFE_BASE (0x40020000u) -/** Peripheral FTFE base pointer */ -#define FTFE ((FTFE_Type *)FTFE_BASE) -/** Array initializer of FTFE peripheral base addresses */ -#define FTFE_BASE_ADDRS { FTFE_BASE } -/** Array initializer of FTFE peripheral base pointers */ -#define FTFE_BASE_PTRS { FTFE } -/** Interrupt vectors for the FTFE peripheral type */ -#define FTFE_COMMAND_COMPLETE_IRQS { FTFE_IRQn } -#define FTFE_READ_COLLISION_IRQS { Read_Collision_IRQn } - -/*! - * @} - */ /* end of group FTFE_Peripheral_Access_Layer */ - - -/* ---------------------------------------------------------------------------- - -- FTM Peripheral Access Layer - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup FTM_Peripheral_Access_Layer FTM Peripheral Access Layer - * @{ - */ - -/** FTM - Register Layout Typedef */ -typedef struct { - __IO uint32_t SC; /**< Status And Control, offset: 0x0 */ - __IO uint32_t CNT; /**< Counter, offset: 0x4 */ - __IO uint32_t MOD; /**< Modulo, offset: 0x8 */ - struct { /* offset: 0xC, array step: 0x8 */ - __IO uint32_t CnSC; /**< Channel (n) Status And Control, array offset: 0xC, array step: 0x8 */ - __IO uint32_t CnV; /**< Channel (n) Value, array offset: 0x10, array step: 0x8 */ - } CONTROLS[8]; - __IO uint32_t CNTIN; /**< Counter Initial Value, offset: 0x4C */ - __IO uint32_t STATUS; /**< Capture And Compare Status, offset: 0x50 */ - __IO uint32_t MODE; /**< Features Mode Selection, offset: 0x54 */ - __IO uint32_t SYNC; /**< Synchronization, offset: 0x58 */ - __IO uint32_t OUTINIT; /**< Initial State For Channels Output, offset: 0x5C */ - __IO uint32_t OUTMASK; /**< Output Mask, offset: 0x60 */ - __IO uint32_t COMBINE; /**< Function For Linked Channels, offset: 0x64 */ - __IO uint32_t DEADTIME; /**< Deadtime Insertion Control, offset: 0x68 */ - __IO uint32_t EXTTRIG; /**< FTM External Trigger, offset: 0x6C */ - __IO uint32_t POL; /**< Channels Polarity, offset: 0x70 */ - __IO uint32_t FMS; /**< Fault Mode Status, offset: 0x74 */ - __IO uint32_t FILTER; /**< Input Capture Filter Control, offset: 0x78 */ - __IO uint32_t FLTCTRL; /**< Fault Control, offset: 0x7C */ - __IO uint32_t QDCTRL; /**< Quadrature Decoder Control And Status, offset: 0x80 */ - __IO uint32_t CONF; /**< Configuration, offset: 0x84 */ - __IO uint32_t FLTPOL; /**< FTM Fault Input Polarity, offset: 0x88 */ - __IO uint32_t SYNCONF; /**< Synchronization Configuration, offset: 0x8C */ - __IO uint32_t INVCTRL; /**< FTM Inverting Control, offset: 0x90 */ - __IO uint32_t SWOCTRL; /**< FTM Software Output Control, offset: 0x94 */ - __IO uint32_t PWMLOAD; /**< FTM PWM Load, offset: 0x98 */ -} FTM_Type; - -/* ---------------------------------------------------------------------------- - -- FTM Register Masks - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup FTM_Register_Masks FTM Register Masks - * @{ - */ - -/*! @name SC - Status And Control */ -#define FTM_SC_PS_MASK (0x7U) -#define FTM_SC_PS_SHIFT (0U) -#define FTM_SC_PS(x) (((uint32_t)(((uint32_t)(x)) << FTM_SC_PS_SHIFT)) & FTM_SC_PS_MASK) -#define FTM_SC_CLKS_MASK (0x18U) -#define FTM_SC_CLKS_SHIFT (3U) -#define FTM_SC_CLKS(x) (((uint32_t)(((uint32_t)(x)) << FTM_SC_CLKS_SHIFT)) & FTM_SC_CLKS_MASK) -#define FTM_SC_CPWMS_MASK (0x20U) -#define FTM_SC_CPWMS_SHIFT (5U) -#define FTM_SC_CPWMS(x) (((uint32_t)(((uint32_t)(x)) << FTM_SC_CPWMS_SHIFT)) & FTM_SC_CPWMS_MASK) -#define FTM_SC_TOIE_MASK (0x40U) -#define FTM_SC_TOIE_SHIFT (6U) -#define FTM_SC_TOIE(x) (((uint32_t)(((uint32_t)(x)) << FTM_SC_TOIE_SHIFT)) & FTM_SC_TOIE_MASK) -#define FTM_SC_TOF_MASK (0x80U) -#define FTM_SC_TOF_SHIFT (7U) -#define FTM_SC_TOF(x) (((uint32_t)(((uint32_t)(x)) << FTM_SC_TOF_SHIFT)) & FTM_SC_TOF_MASK) - -/*! @name CNT - Counter */ -#define FTM_CNT_COUNT_MASK (0xFFFFU) -#define FTM_CNT_COUNT_SHIFT (0U) -#define FTM_CNT_COUNT(x) (((uint32_t)(((uint32_t)(x)) << FTM_CNT_COUNT_SHIFT)) & FTM_CNT_COUNT_MASK) - -/*! @name MOD - Modulo */ -#define FTM_MOD_MOD_MASK (0xFFFFU) -#define FTM_MOD_MOD_SHIFT (0U) -#define FTM_MOD_MOD(x) (((uint32_t)(((uint32_t)(x)) << FTM_MOD_MOD_SHIFT)) & FTM_MOD_MOD_MASK) - -/*! @name CnSC - Channel (n) Status And Control */ -#define FTM_CnSC_DMA_MASK (0x1U) -#define FTM_CnSC_DMA_SHIFT (0U) -#define FTM_CnSC_DMA(x) (((uint32_t)(((uint32_t)(x)) << FTM_CnSC_DMA_SHIFT)) & FTM_CnSC_DMA_MASK) -#define FTM_CnSC_ELSA_MASK (0x4U) -#define FTM_CnSC_ELSA_SHIFT (2U) -#define FTM_CnSC_ELSA(x) (((uint32_t)(((uint32_t)(x)) << FTM_CnSC_ELSA_SHIFT)) & FTM_CnSC_ELSA_MASK) -#define FTM_CnSC_ELSB_MASK (0x8U) -#define FTM_CnSC_ELSB_SHIFT (3U) -#define FTM_CnSC_ELSB(x) (((uint32_t)(((uint32_t)(x)) << FTM_CnSC_ELSB_SHIFT)) & FTM_CnSC_ELSB_MASK) -#define FTM_CnSC_MSA_MASK (0x10U) -#define FTM_CnSC_MSA_SHIFT (4U) -#define FTM_CnSC_MSA(x) (((uint32_t)(((uint32_t)(x)) << FTM_CnSC_MSA_SHIFT)) & FTM_CnSC_MSA_MASK) -#define FTM_CnSC_MSB_MASK (0x20U) -#define FTM_CnSC_MSB_SHIFT (5U) -#define FTM_CnSC_MSB(x) (((uint32_t)(((uint32_t)(x)) << FTM_CnSC_MSB_SHIFT)) & FTM_CnSC_MSB_MASK) -#define FTM_CnSC_CHIE_MASK (0x40U) -#define FTM_CnSC_CHIE_SHIFT (6U) -#define FTM_CnSC_CHIE(x) (((uint32_t)(((uint32_t)(x)) << FTM_CnSC_CHIE_SHIFT)) & FTM_CnSC_CHIE_MASK) -#define FTM_CnSC_CHF_MASK (0x80U) -#define FTM_CnSC_CHF_SHIFT (7U) -#define FTM_CnSC_CHF(x) (((uint32_t)(((uint32_t)(x)) << FTM_CnSC_CHF_SHIFT)) & FTM_CnSC_CHF_MASK) - -/* The count of FTM_CnSC */ -#define FTM_CnSC_COUNT (8U) - -/*! @name CnV - Channel (n) Value */ -#define FTM_CnV_VAL_MASK (0xFFFFU) -#define FTM_CnV_VAL_SHIFT (0U) -#define FTM_CnV_VAL(x) (((uint32_t)(((uint32_t)(x)) << FTM_CnV_VAL_SHIFT)) & FTM_CnV_VAL_MASK) - -/* The count of FTM_CnV */ -#define FTM_CnV_COUNT (8U) - -/*! @name CNTIN - Counter Initial Value */ -#define FTM_CNTIN_INIT_MASK (0xFFFFU) -#define FTM_CNTIN_INIT_SHIFT (0U) -#define FTM_CNTIN_INIT(x) (((uint32_t)(((uint32_t)(x)) << FTM_CNTIN_INIT_SHIFT)) & FTM_CNTIN_INIT_MASK) - -/*! @name STATUS - Capture And Compare Status */ -#define FTM_STATUS_CH0F_MASK (0x1U) -#define FTM_STATUS_CH0F_SHIFT (0U) -#define FTM_STATUS_CH0F(x) (((uint32_t)(((uint32_t)(x)) << FTM_STATUS_CH0F_SHIFT)) & FTM_STATUS_CH0F_MASK) -#define FTM_STATUS_CH1F_MASK (0x2U) -#define FTM_STATUS_CH1F_SHIFT (1U) -#define FTM_STATUS_CH1F(x) (((uint32_t)(((uint32_t)(x)) << FTM_STATUS_CH1F_SHIFT)) & FTM_STATUS_CH1F_MASK) -#define FTM_STATUS_CH2F_MASK (0x4U) -#define FTM_STATUS_CH2F_SHIFT (2U) -#define FTM_STATUS_CH2F(x) (((uint32_t)(((uint32_t)(x)) << FTM_STATUS_CH2F_SHIFT)) & FTM_STATUS_CH2F_MASK) -#define FTM_STATUS_CH3F_MASK (0x8U) -#define FTM_STATUS_CH3F_SHIFT (3U) -#define FTM_STATUS_CH3F(x) (((uint32_t)(((uint32_t)(x)) << FTM_STATUS_CH3F_SHIFT)) & FTM_STATUS_CH3F_MASK) -#define FTM_STATUS_CH4F_MASK (0x10U) -#define FTM_STATUS_CH4F_SHIFT (4U) -#define FTM_STATUS_CH4F(x) (((uint32_t)(((uint32_t)(x)) << FTM_STATUS_CH4F_SHIFT)) & FTM_STATUS_CH4F_MASK) -#define FTM_STATUS_CH5F_MASK (0x20U) -#define FTM_STATUS_CH5F_SHIFT (5U) -#define FTM_STATUS_CH5F(x) (((uint32_t)(((uint32_t)(x)) << FTM_STATUS_CH5F_SHIFT)) & FTM_STATUS_CH5F_MASK) -#define FTM_STATUS_CH6F_MASK (0x40U) -#define FTM_STATUS_CH6F_SHIFT (6U) -#define FTM_STATUS_CH6F(x) (((uint32_t)(((uint32_t)(x)) << FTM_STATUS_CH6F_SHIFT)) & FTM_STATUS_CH6F_MASK) -#define FTM_STATUS_CH7F_MASK (0x80U) -#define FTM_STATUS_CH7F_SHIFT (7U) -#define FTM_STATUS_CH7F(x) (((uint32_t)(((uint32_t)(x)) << FTM_STATUS_CH7F_SHIFT)) & FTM_STATUS_CH7F_MASK) - -/*! @name MODE - Features Mode Selection */ -#define FTM_MODE_FTMEN_MASK (0x1U) -#define FTM_MODE_FTMEN_SHIFT (0U) -#define FTM_MODE_FTMEN(x) (((uint32_t)(((uint32_t)(x)) << FTM_MODE_FTMEN_SHIFT)) & FTM_MODE_FTMEN_MASK) -#define FTM_MODE_INIT_MASK (0x2U) -#define FTM_MODE_INIT_SHIFT (1U) -#define FTM_MODE_INIT(x) (((uint32_t)(((uint32_t)(x)) << FTM_MODE_INIT_SHIFT)) & FTM_MODE_INIT_MASK) -#define FTM_MODE_WPDIS_MASK (0x4U) -#define FTM_MODE_WPDIS_SHIFT (2U) -#define FTM_MODE_WPDIS(x) (((uint32_t)(((uint32_t)(x)) << FTM_MODE_WPDIS_SHIFT)) & FTM_MODE_WPDIS_MASK) -#define FTM_MODE_PWMSYNC_MASK (0x8U) -#define FTM_MODE_PWMSYNC_SHIFT (3U) -#define FTM_MODE_PWMSYNC(x) (((uint32_t)(((uint32_t)(x)) << FTM_MODE_PWMSYNC_SHIFT)) & FTM_MODE_PWMSYNC_MASK) -#define FTM_MODE_CAPTEST_MASK (0x10U) -#define FTM_MODE_CAPTEST_SHIFT (4U) -#define FTM_MODE_CAPTEST(x) (((uint32_t)(((uint32_t)(x)) << FTM_MODE_CAPTEST_SHIFT)) & FTM_MODE_CAPTEST_MASK) -#define FTM_MODE_FAULTM_MASK (0x60U) -#define FTM_MODE_FAULTM_SHIFT (5U) -#define FTM_MODE_FAULTM(x) (((uint32_t)(((uint32_t)(x)) << FTM_MODE_FAULTM_SHIFT)) & FTM_MODE_FAULTM_MASK) -#define FTM_MODE_FAULTIE_MASK (0x80U) -#define FTM_MODE_FAULTIE_SHIFT (7U) -#define FTM_MODE_FAULTIE(x) (((uint32_t)(((uint32_t)(x)) << FTM_MODE_FAULTIE_SHIFT)) & FTM_MODE_FAULTIE_MASK) - -/*! @name SYNC - Synchronization */ -#define FTM_SYNC_CNTMIN_MASK (0x1U) -#define FTM_SYNC_CNTMIN_SHIFT (0U) -#define FTM_SYNC_CNTMIN(x) (((uint32_t)(((uint32_t)(x)) << FTM_SYNC_CNTMIN_SHIFT)) & FTM_SYNC_CNTMIN_MASK) -#define FTM_SYNC_CNTMAX_MASK (0x2U) -#define FTM_SYNC_CNTMAX_SHIFT (1U) -#define FTM_SYNC_CNTMAX(x) (((uint32_t)(((uint32_t)(x)) << FTM_SYNC_CNTMAX_SHIFT)) & FTM_SYNC_CNTMAX_MASK) -#define FTM_SYNC_REINIT_MASK (0x4U) -#define FTM_SYNC_REINIT_SHIFT (2U) -#define FTM_SYNC_REINIT(x) (((uint32_t)(((uint32_t)(x)) << FTM_SYNC_REINIT_SHIFT)) & FTM_SYNC_REINIT_MASK) -#define FTM_SYNC_SYNCHOM_MASK (0x8U) -#define FTM_SYNC_SYNCHOM_SHIFT (3U) -#define FTM_SYNC_SYNCHOM(x) (((uint32_t)(((uint32_t)(x)) << FTM_SYNC_SYNCHOM_SHIFT)) & FTM_SYNC_SYNCHOM_MASK) -#define FTM_SYNC_TRIG0_MASK (0x10U) -#define FTM_SYNC_TRIG0_SHIFT (4U) -#define FTM_SYNC_TRIG0(x) (((uint32_t)(((uint32_t)(x)) << FTM_SYNC_TRIG0_SHIFT)) & FTM_SYNC_TRIG0_MASK) -#define FTM_SYNC_TRIG1_MASK (0x20U) -#define FTM_SYNC_TRIG1_SHIFT (5U) -#define FTM_SYNC_TRIG1(x) (((uint32_t)(((uint32_t)(x)) << FTM_SYNC_TRIG1_SHIFT)) & FTM_SYNC_TRIG1_MASK) -#define FTM_SYNC_TRIG2_MASK (0x40U) -#define FTM_SYNC_TRIG2_SHIFT (6U) -#define FTM_SYNC_TRIG2(x) (((uint32_t)(((uint32_t)(x)) << FTM_SYNC_TRIG2_SHIFT)) & FTM_SYNC_TRIG2_MASK) -#define FTM_SYNC_SWSYNC_MASK (0x80U) -#define FTM_SYNC_SWSYNC_SHIFT (7U) -#define FTM_SYNC_SWSYNC(x) (((uint32_t)(((uint32_t)(x)) << FTM_SYNC_SWSYNC_SHIFT)) & FTM_SYNC_SWSYNC_MASK) - -/*! @name OUTINIT - Initial State For Channels Output */ -#define FTM_OUTINIT_CH0OI_MASK (0x1U) -#define FTM_OUTINIT_CH0OI_SHIFT (0U) -#define FTM_OUTINIT_CH0OI(x) (((uint32_t)(((uint32_t)(x)) << FTM_OUTINIT_CH0OI_SHIFT)) & FTM_OUTINIT_CH0OI_MASK) -#define FTM_OUTINIT_CH1OI_MASK (0x2U) -#define FTM_OUTINIT_CH1OI_SHIFT (1U) -#define FTM_OUTINIT_CH1OI(x) (((uint32_t)(((uint32_t)(x)) << FTM_OUTINIT_CH1OI_SHIFT)) & FTM_OUTINIT_CH1OI_MASK) -#define FTM_OUTINIT_CH2OI_MASK (0x4U) -#define FTM_OUTINIT_CH2OI_SHIFT (2U) -#define FTM_OUTINIT_CH2OI(x) (((uint32_t)(((uint32_t)(x)) << FTM_OUTINIT_CH2OI_SHIFT)) & FTM_OUTINIT_CH2OI_MASK) -#define FTM_OUTINIT_CH3OI_MASK (0x8U) -#define FTM_OUTINIT_CH3OI_SHIFT (3U) -#define FTM_OUTINIT_CH3OI(x) (((uint32_t)(((uint32_t)(x)) << FTM_OUTINIT_CH3OI_SHIFT)) & FTM_OUTINIT_CH3OI_MASK) -#define FTM_OUTINIT_CH4OI_MASK (0x10U) -#define FTM_OUTINIT_CH4OI_SHIFT (4U) -#define FTM_OUTINIT_CH4OI(x) (((uint32_t)(((uint32_t)(x)) << FTM_OUTINIT_CH4OI_SHIFT)) & FTM_OUTINIT_CH4OI_MASK) -#define FTM_OUTINIT_CH5OI_MASK (0x20U) -#define FTM_OUTINIT_CH5OI_SHIFT (5U) -#define FTM_OUTINIT_CH5OI(x) (((uint32_t)(((uint32_t)(x)) << FTM_OUTINIT_CH5OI_SHIFT)) & FTM_OUTINIT_CH5OI_MASK) -#define FTM_OUTINIT_CH6OI_MASK (0x40U) -#define FTM_OUTINIT_CH6OI_SHIFT (6U) -#define FTM_OUTINIT_CH6OI(x) (((uint32_t)(((uint32_t)(x)) << FTM_OUTINIT_CH6OI_SHIFT)) & FTM_OUTINIT_CH6OI_MASK) -#define FTM_OUTINIT_CH7OI_MASK (0x80U) -#define FTM_OUTINIT_CH7OI_SHIFT (7U) -#define FTM_OUTINIT_CH7OI(x) (((uint32_t)(((uint32_t)(x)) << FTM_OUTINIT_CH7OI_SHIFT)) & FTM_OUTINIT_CH7OI_MASK) - -/*! @name OUTMASK - Output Mask */ -#define FTM_OUTMASK_CH0OM_MASK (0x1U) -#define FTM_OUTMASK_CH0OM_SHIFT (0U) -#define FTM_OUTMASK_CH0OM(x) (((uint32_t)(((uint32_t)(x)) << FTM_OUTMASK_CH0OM_SHIFT)) & FTM_OUTMASK_CH0OM_MASK) -#define FTM_OUTMASK_CH1OM_MASK (0x2U) -#define FTM_OUTMASK_CH1OM_SHIFT (1U) -#define FTM_OUTMASK_CH1OM(x) (((uint32_t)(((uint32_t)(x)) << FTM_OUTMASK_CH1OM_SHIFT)) & FTM_OUTMASK_CH1OM_MASK) -#define FTM_OUTMASK_CH2OM_MASK (0x4U) -#define FTM_OUTMASK_CH2OM_SHIFT (2U) -#define FTM_OUTMASK_CH2OM(x) (((uint32_t)(((uint32_t)(x)) << FTM_OUTMASK_CH2OM_SHIFT)) & FTM_OUTMASK_CH2OM_MASK) -#define FTM_OUTMASK_CH3OM_MASK (0x8U) -#define FTM_OUTMASK_CH3OM_SHIFT (3U) -#define FTM_OUTMASK_CH3OM(x) (((uint32_t)(((uint32_t)(x)) << FTM_OUTMASK_CH3OM_SHIFT)) & FTM_OUTMASK_CH3OM_MASK) -#define FTM_OUTMASK_CH4OM_MASK (0x10U) -#define FTM_OUTMASK_CH4OM_SHIFT (4U) -#define FTM_OUTMASK_CH4OM(x) (((uint32_t)(((uint32_t)(x)) << FTM_OUTMASK_CH4OM_SHIFT)) & FTM_OUTMASK_CH4OM_MASK) -#define FTM_OUTMASK_CH5OM_MASK (0x20U) -#define FTM_OUTMASK_CH5OM_SHIFT (5U) -#define FTM_OUTMASK_CH5OM(x) (((uint32_t)(((uint32_t)(x)) << FTM_OUTMASK_CH5OM_SHIFT)) & FTM_OUTMASK_CH5OM_MASK) -#define FTM_OUTMASK_CH6OM_MASK (0x40U) -#define FTM_OUTMASK_CH6OM_SHIFT (6U) -#define FTM_OUTMASK_CH6OM(x) (((uint32_t)(((uint32_t)(x)) << FTM_OUTMASK_CH6OM_SHIFT)) & FTM_OUTMASK_CH6OM_MASK) -#define FTM_OUTMASK_CH7OM_MASK (0x80U) -#define FTM_OUTMASK_CH7OM_SHIFT (7U) -#define FTM_OUTMASK_CH7OM(x) (((uint32_t)(((uint32_t)(x)) << FTM_OUTMASK_CH7OM_SHIFT)) & FTM_OUTMASK_CH7OM_MASK) - -/*! @name COMBINE - Function For Linked Channels */ -#define FTM_COMBINE_COMBINE0_MASK (0x1U) -#define FTM_COMBINE_COMBINE0_SHIFT (0U) -#define FTM_COMBINE_COMBINE0(x) (((uint32_t)(((uint32_t)(x)) << FTM_COMBINE_COMBINE0_SHIFT)) & FTM_COMBINE_COMBINE0_MASK) -#define FTM_COMBINE_COMP0_MASK (0x2U) -#define FTM_COMBINE_COMP0_SHIFT (1U) -#define FTM_COMBINE_COMP0(x) (((uint32_t)(((uint32_t)(x)) << FTM_COMBINE_COMP0_SHIFT)) & FTM_COMBINE_COMP0_MASK) -#define FTM_COMBINE_DECAPEN0_MASK (0x4U) -#define FTM_COMBINE_DECAPEN0_SHIFT (2U) -#define FTM_COMBINE_DECAPEN0(x) (((uint32_t)(((uint32_t)(x)) << FTM_COMBINE_DECAPEN0_SHIFT)) & FTM_COMBINE_DECAPEN0_MASK) -#define FTM_COMBINE_DECAP0_MASK (0x8U) -#define FTM_COMBINE_DECAP0_SHIFT (3U) -#define FTM_COMBINE_DECAP0(x) (((uint32_t)(((uint32_t)(x)) << FTM_COMBINE_DECAP0_SHIFT)) & FTM_COMBINE_DECAP0_MASK) -#define FTM_COMBINE_DTEN0_MASK (0x10U) -#define FTM_COMBINE_DTEN0_SHIFT (4U) -#define FTM_COMBINE_DTEN0(x) (((uint32_t)(((uint32_t)(x)) << FTM_COMBINE_DTEN0_SHIFT)) & FTM_COMBINE_DTEN0_MASK) -#define FTM_COMBINE_SYNCEN0_MASK (0x20U) -#define FTM_COMBINE_SYNCEN0_SHIFT (5U) -#define FTM_COMBINE_SYNCEN0(x) (((uint32_t)(((uint32_t)(x)) << FTM_COMBINE_SYNCEN0_SHIFT)) & FTM_COMBINE_SYNCEN0_MASK) -#define FTM_COMBINE_FAULTEN0_MASK (0x40U) -#define FTM_COMBINE_FAULTEN0_SHIFT (6U) -#define FTM_COMBINE_FAULTEN0(x) (((uint32_t)(((uint32_t)(x)) << FTM_COMBINE_FAULTEN0_SHIFT)) & FTM_COMBINE_FAULTEN0_MASK) -#define FTM_COMBINE_COMBINE1_MASK (0x100U) -#define FTM_COMBINE_COMBINE1_SHIFT (8U) -#define FTM_COMBINE_COMBINE1(x) (((uint32_t)(((uint32_t)(x)) << FTM_COMBINE_COMBINE1_SHIFT)) & FTM_COMBINE_COMBINE1_MASK) -#define FTM_COMBINE_COMP1_MASK (0x200U) -#define FTM_COMBINE_COMP1_SHIFT (9U) -#define FTM_COMBINE_COMP1(x) (((uint32_t)(((uint32_t)(x)) << FTM_COMBINE_COMP1_SHIFT)) & FTM_COMBINE_COMP1_MASK) -#define FTM_COMBINE_DECAPEN1_MASK (0x400U) -#define FTM_COMBINE_DECAPEN1_SHIFT (10U) -#define FTM_COMBINE_DECAPEN1(x) (((uint32_t)(((uint32_t)(x)) << FTM_COMBINE_DECAPEN1_SHIFT)) & FTM_COMBINE_DECAPEN1_MASK) -#define FTM_COMBINE_DECAP1_MASK (0x800U) -#define FTM_COMBINE_DECAP1_SHIFT (11U) -#define FTM_COMBINE_DECAP1(x) (((uint32_t)(((uint32_t)(x)) << FTM_COMBINE_DECAP1_SHIFT)) & FTM_COMBINE_DECAP1_MASK) -#define FTM_COMBINE_DTEN1_MASK (0x1000U) -#define FTM_COMBINE_DTEN1_SHIFT (12U) -#define FTM_COMBINE_DTEN1(x) (((uint32_t)(((uint32_t)(x)) << FTM_COMBINE_DTEN1_SHIFT)) & FTM_COMBINE_DTEN1_MASK) -#define FTM_COMBINE_SYNCEN1_MASK (0x2000U) -#define FTM_COMBINE_SYNCEN1_SHIFT (13U) -#define FTM_COMBINE_SYNCEN1(x) (((uint32_t)(((uint32_t)(x)) << FTM_COMBINE_SYNCEN1_SHIFT)) & FTM_COMBINE_SYNCEN1_MASK) -#define FTM_COMBINE_FAULTEN1_MASK (0x4000U) -#define FTM_COMBINE_FAULTEN1_SHIFT (14U) -#define FTM_COMBINE_FAULTEN1(x) (((uint32_t)(((uint32_t)(x)) << FTM_COMBINE_FAULTEN1_SHIFT)) & FTM_COMBINE_FAULTEN1_MASK) -#define FTM_COMBINE_COMBINE2_MASK (0x10000U) -#define FTM_COMBINE_COMBINE2_SHIFT (16U) -#define FTM_COMBINE_COMBINE2(x) (((uint32_t)(((uint32_t)(x)) << FTM_COMBINE_COMBINE2_SHIFT)) & FTM_COMBINE_COMBINE2_MASK) -#define FTM_COMBINE_COMP2_MASK (0x20000U) -#define FTM_COMBINE_COMP2_SHIFT (17U) -#define FTM_COMBINE_COMP2(x) (((uint32_t)(((uint32_t)(x)) << FTM_COMBINE_COMP2_SHIFT)) & FTM_COMBINE_COMP2_MASK) -#define FTM_COMBINE_DECAPEN2_MASK (0x40000U) -#define FTM_COMBINE_DECAPEN2_SHIFT (18U) -#define FTM_COMBINE_DECAPEN2(x) (((uint32_t)(((uint32_t)(x)) << FTM_COMBINE_DECAPEN2_SHIFT)) & FTM_COMBINE_DECAPEN2_MASK) -#define FTM_COMBINE_DECAP2_MASK (0x80000U) -#define FTM_COMBINE_DECAP2_SHIFT (19U) -#define FTM_COMBINE_DECAP2(x) (((uint32_t)(((uint32_t)(x)) << FTM_COMBINE_DECAP2_SHIFT)) & FTM_COMBINE_DECAP2_MASK) -#define FTM_COMBINE_DTEN2_MASK (0x100000U) -#define FTM_COMBINE_DTEN2_SHIFT (20U) -#define FTM_COMBINE_DTEN2(x) (((uint32_t)(((uint32_t)(x)) << FTM_COMBINE_DTEN2_SHIFT)) & FTM_COMBINE_DTEN2_MASK) -#define FTM_COMBINE_SYNCEN2_MASK (0x200000U) -#define FTM_COMBINE_SYNCEN2_SHIFT (21U) -#define FTM_COMBINE_SYNCEN2(x) (((uint32_t)(((uint32_t)(x)) << FTM_COMBINE_SYNCEN2_SHIFT)) & FTM_COMBINE_SYNCEN2_MASK) -#define FTM_COMBINE_FAULTEN2_MASK (0x400000U) -#define FTM_COMBINE_FAULTEN2_SHIFT (22U) -#define FTM_COMBINE_FAULTEN2(x) (((uint32_t)(((uint32_t)(x)) << FTM_COMBINE_FAULTEN2_SHIFT)) & FTM_COMBINE_FAULTEN2_MASK) -#define FTM_COMBINE_COMBINE3_MASK (0x1000000U) -#define FTM_COMBINE_COMBINE3_SHIFT (24U) -#define FTM_COMBINE_COMBINE3(x) (((uint32_t)(((uint32_t)(x)) << FTM_COMBINE_COMBINE3_SHIFT)) & FTM_COMBINE_COMBINE3_MASK) -#define FTM_COMBINE_COMP3_MASK (0x2000000U) -#define FTM_COMBINE_COMP3_SHIFT (25U) -#define FTM_COMBINE_COMP3(x) (((uint32_t)(((uint32_t)(x)) << FTM_COMBINE_COMP3_SHIFT)) & FTM_COMBINE_COMP3_MASK) -#define FTM_COMBINE_DECAPEN3_MASK (0x4000000U) -#define FTM_COMBINE_DECAPEN3_SHIFT (26U) -#define FTM_COMBINE_DECAPEN3(x) (((uint32_t)(((uint32_t)(x)) << FTM_COMBINE_DECAPEN3_SHIFT)) & FTM_COMBINE_DECAPEN3_MASK) -#define FTM_COMBINE_DECAP3_MASK (0x8000000U) -#define FTM_COMBINE_DECAP3_SHIFT (27U) -#define FTM_COMBINE_DECAP3(x) (((uint32_t)(((uint32_t)(x)) << FTM_COMBINE_DECAP3_SHIFT)) & FTM_COMBINE_DECAP3_MASK) -#define FTM_COMBINE_DTEN3_MASK (0x10000000U) -#define FTM_COMBINE_DTEN3_SHIFT (28U) -#define FTM_COMBINE_DTEN3(x) (((uint32_t)(((uint32_t)(x)) << FTM_COMBINE_DTEN3_SHIFT)) & FTM_COMBINE_DTEN3_MASK) -#define FTM_COMBINE_SYNCEN3_MASK (0x20000000U) -#define FTM_COMBINE_SYNCEN3_SHIFT (29U) -#define FTM_COMBINE_SYNCEN3(x) (((uint32_t)(((uint32_t)(x)) << FTM_COMBINE_SYNCEN3_SHIFT)) & FTM_COMBINE_SYNCEN3_MASK) -#define FTM_COMBINE_FAULTEN3_MASK (0x40000000U) -#define FTM_COMBINE_FAULTEN3_SHIFT (30U) -#define FTM_COMBINE_FAULTEN3(x) (((uint32_t)(((uint32_t)(x)) << FTM_COMBINE_FAULTEN3_SHIFT)) & FTM_COMBINE_FAULTEN3_MASK) - -/*! @name DEADTIME - Deadtime Insertion Control */ -#define FTM_DEADTIME_DTVAL_MASK (0x3FU) -#define FTM_DEADTIME_DTVAL_SHIFT (0U) -#define FTM_DEADTIME_DTVAL(x) (((uint32_t)(((uint32_t)(x)) << FTM_DEADTIME_DTVAL_SHIFT)) & FTM_DEADTIME_DTVAL_MASK) -#define FTM_DEADTIME_DTPS_MASK (0xC0U) -#define FTM_DEADTIME_DTPS_SHIFT (6U) -#define FTM_DEADTIME_DTPS(x) (((uint32_t)(((uint32_t)(x)) << FTM_DEADTIME_DTPS_SHIFT)) & FTM_DEADTIME_DTPS_MASK) - -/*! @name EXTTRIG - FTM External Trigger */ -#define FTM_EXTTRIG_CH2TRIG_MASK (0x1U) -#define FTM_EXTTRIG_CH2TRIG_SHIFT (0U) -#define FTM_EXTTRIG_CH2TRIG(x) (((uint32_t)(((uint32_t)(x)) << FTM_EXTTRIG_CH2TRIG_SHIFT)) & FTM_EXTTRIG_CH2TRIG_MASK) -#define FTM_EXTTRIG_CH3TRIG_MASK (0x2U) -#define FTM_EXTTRIG_CH3TRIG_SHIFT (1U) -#define FTM_EXTTRIG_CH3TRIG(x) (((uint32_t)(((uint32_t)(x)) << FTM_EXTTRIG_CH3TRIG_SHIFT)) & FTM_EXTTRIG_CH3TRIG_MASK) -#define FTM_EXTTRIG_CH4TRIG_MASK (0x4U) -#define FTM_EXTTRIG_CH4TRIG_SHIFT (2U) -#define FTM_EXTTRIG_CH4TRIG(x) (((uint32_t)(((uint32_t)(x)) << FTM_EXTTRIG_CH4TRIG_SHIFT)) & FTM_EXTTRIG_CH4TRIG_MASK) -#define FTM_EXTTRIG_CH5TRIG_MASK (0x8U) -#define FTM_EXTTRIG_CH5TRIG_SHIFT (3U) -#define FTM_EXTTRIG_CH5TRIG(x) (((uint32_t)(((uint32_t)(x)) << FTM_EXTTRIG_CH5TRIG_SHIFT)) & FTM_EXTTRIG_CH5TRIG_MASK) -#define FTM_EXTTRIG_CH0TRIG_MASK (0x10U) -#define FTM_EXTTRIG_CH0TRIG_SHIFT (4U) -#define FTM_EXTTRIG_CH0TRIG(x) (((uint32_t)(((uint32_t)(x)) << FTM_EXTTRIG_CH0TRIG_SHIFT)) & FTM_EXTTRIG_CH0TRIG_MASK) -#define FTM_EXTTRIG_CH1TRIG_MASK (0x20U) -#define FTM_EXTTRIG_CH1TRIG_SHIFT (5U) -#define FTM_EXTTRIG_CH1TRIG(x) (((uint32_t)(((uint32_t)(x)) << FTM_EXTTRIG_CH1TRIG_SHIFT)) & FTM_EXTTRIG_CH1TRIG_MASK) -#define FTM_EXTTRIG_INITTRIGEN_MASK (0x40U) -#define FTM_EXTTRIG_INITTRIGEN_SHIFT (6U) -#define FTM_EXTTRIG_INITTRIGEN(x) (((uint32_t)(((uint32_t)(x)) << FTM_EXTTRIG_INITTRIGEN_SHIFT)) & FTM_EXTTRIG_INITTRIGEN_MASK) -#define FTM_EXTTRIG_TRIGF_MASK (0x80U) -#define FTM_EXTTRIG_TRIGF_SHIFT (7U) -#define FTM_EXTTRIG_TRIGF(x) (((uint32_t)(((uint32_t)(x)) << FTM_EXTTRIG_TRIGF_SHIFT)) & FTM_EXTTRIG_TRIGF_MASK) - -/*! @name POL - Channels Polarity */ -#define FTM_POL_POL0_MASK (0x1U) -#define FTM_POL_POL0_SHIFT (0U) -#define FTM_POL_POL0(x) (((uint32_t)(((uint32_t)(x)) << FTM_POL_POL0_SHIFT)) & FTM_POL_POL0_MASK) -#define FTM_POL_POL1_MASK (0x2U) -#define FTM_POL_POL1_SHIFT (1U) -#define FTM_POL_POL1(x) (((uint32_t)(((uint32_t)(x)) << FTM_POL_POL1_SHIFT)) & FTM_POL_POL1_MASK) -#define FTM_POL_POL2_MASK (0x4U) -#define FTM_POL_POL2_SHIFT (2U) -#define FTM_POL_POL2(x) (((uint32_t)(((uint32_t)(x)) << FTM_POL_POL2_SHIFT)) & FTM_POL_POL2_MASK) -#define FTM_POL_POL3_MASK (0x8U) -#define FTM_POL_POL3_SHIFT (3U) -#define FTM_POL_POL3(x) (((uint32_t)(((uint32_t)(x)) << FTM_POL_POL3_SHIFT)) & FTM_POL_POL3_MASK) -#define FTM_POL_POL4_MASK (0x10U) -#define FTM_POL_POL4_SHIFT (4U) -#define FTM_POL_POL4(x) (((uint32_t)(((uint32_t)(x)) << FTM_POL_POL4_SHIFT)) & FTM_POL_POL4_MASK) -#define FTM_POL_POL5_MASK (0x20U) -#define FTM_POL_POL5_SHIFT (5U) -#define FTM_POL_POL5(x) (((uint32_t)(((uint32_t)(x)) << FTM_POL_POL5_SHIFT)) & FTM_POL_POL5_MASK) -#define FTM_POL_POL6_MASK (0x40U) -#define FTM_POL_POL6_SHIFT (6U) -#define FTM_POL_POL6(x) (((uint32_t)(((uint32_t)(x)) << FTM_POL_POL6_SHIFT)) & FTM_POL_POL6_MASK) -#define FTM_POL_POL7_MASK (0x80U) -#define FTM_POL_POL7_SHIFT (7U) -#define FTM_POL_POL7(x) (((uint32_t)(((uint32_t)(x)) << FTM_POL_POL7_SHIFT)) & FTM_POL_POL7_MASK) - -/*! @name FMS - Fault Mode Status */ -#define FTM_FMS_FAULTF0_MASK (0x1U) -#define FTM_FMS_FAULTF0_SHIFT (0U) -#define FTM_FMS_FAULTF0(x) (((uint32_t)(((uint32_t)(x)) << FTM_FMS_FAULTF0_SHIFT)) & FTM_FMS_FAULTF0_MASK) -#define FTM_FMS_FAULTF1_MASK (0x2U) -#define FTM_FMS_FAULTF1_SHIFT (1U) -#define FTM_FMS_FAULTF1(x) (((uint32_t)(((uint32_t)(x)) << FTM_FMS_FAULTF1_SHIFT)) & FTM_FMS_FAULTF1_MASK) -#define FTM_FMS_FAULTF2_MASK (0x4U) -#define FTM_FMS_FAULTF2_SHIFT (2U) -#define FTM_FMS_FAULTF2(x) (((uint32_t)(((uint32_t)(x)) << FTM_FMS_FAULTF2_SHIFT)) & FTM_FMS_FAULTF2_MASK) -#define FTM_FMS_FAULTF3_MASK (0x8U) -#define FTM_FMS_FAULTF3_SHIFT (3U) -#define FTM_FMS_FAULTF3(x) (((uint32_t)(((uint32_t)(x)) << FTM_FMS_FAULTF3_SHIFT)) & FTM_FMS_FAULTF3_MASK) -#define FTM_FMS_FAULTIN_MASK (0x20U) -#define FTM_FMS_FAULTIN_SHIFT (5U) -#define FTM_FMS_FAULTIN(x) (((uint32_t)(((uint32_t)(x)) << FTM_FMS_FAULTIN_SHIFT)) & FTM_FMS_FAULTIN_MASK) -#define FTM_FMS_WPEN_MASK (0x40U) -#define FTM_FMS_WPEN_SHIFT (6U) -#define FTM_FMS_WPEN(x) (((uint32_t)(((uint32_t)(x)) << FTM_FMS_WPEN_SHIFT)) & FTM_FMS_WPEN_MASK) -#define FTM_FMS_FAULTF_MASK (0x80U) -#define FTM_FMS_FAULTF_SHIFT (7U) -#define FTM_FMS_FAULTF(x) (((uint32_t)(((uint32_t)(x)) << FTM_FMS_FAULTF_SHIFT)) & FTM_FMS_FAULTF_MASK) - -/*! @name FILTER - Input Capture Filter Control */ -#define FTM_FILTER_CH0FVAL_MASK (0xFU) -#define FTM_FILTER_CH0FVAL_SHIFT (0U) -#define FTM_FILTER_CH0FVAL(x) (((uint32_t)(((uint32_t)(x)) << FTM_FILTER_CH0FVAL_SHIFT)) & FTM_FILTER_CH0FVAL_MASK) -#define FTM_FILTER_CH1FVAL_MASK (0xF0U) -#define FTM_FILTER_CH1FVAL_SHIFT (4U) -#define FTM_FILTER_CH1FVAL(x) (((uint32_t)(((uint32_t)(x)) << FTM_FILTER_CH1FVAL_SHIFT)) & FTM_FILTER_CH1FVAL_MASK) -#define FTM_FILTER_CH2FVAL_MASK (0xF00U) -#define FTM_FILTER_CH2FVAL_SHIFT (8U) -#define FTM_FILTER_CH2FVAL(x) (((uint32_t)(((uint32_t)(x)) << FTM_FILTER_CH2FVAL_SHIFT)) & FTM_FILTER_CH2FVAL_MASK) -#define FTM_FILTER_CH3FVAL_MASK (0xF000U) -#define FTM_FILTER_CH3FVAL_SHIFT (12U) -#define FTM_FILTER_CH3FVAL(x) (((uint32_t)(((uint32_t)(x)) << FTM_FILTER_CH3FVAL_SHIFT)) & FTM_FILTER_CH3FVAL_MASK) - -/*! @name FLTCTRL - Fault Control */ -#define FTM_FLTCTRL_FAULT0EN_MASK (0x1U) -#define FTM_FLTCTRL_FAULT0EN_SHIFT (0U) -#define FTM_FLTCTRL_FAULT0EN(x) (((uint32_t)(((uint32_t)(x)) << FTM_FLTCTRL_FAULT0EN_SHIFT)) & FTM_FLTCTRL_FAULT0EN_MASK) -#define FTM_FLTCTRL_FAULT1EN_MASK (0x2U) -#define FTM_FLTCTRL_FAULT1EN_SHIFT (1U) -#define FTM_FLTCTRL_FAULT1EN(x) (((uint32_t)(((uint32_t)(x)) << FTM_FLTCTRL_FAULT1EN_SHIFT)) & FTM_FLTCTRL_FAULT1EN_MASK) -#define FTM_FLTCTRL_FAULT2EN_MASK (0x4U) -#define FTM_FLTCTRL_FAULT2EN_SHIFT (2U) -#define FTM_FLTCTRL_FAULT2EN(x) (((uint32_t)(((uint32_t)(x)) << FTM_FLTCTRL_FAULT2EN_SHIFT)) & FTM_FLTCTRL_FAULT2EN_MASK) -#define FTM_FLTCTRL_FAULT3EN_MASK (0x8U) -#define FTM_FLTCTRL_FAULT3EN_SHIFT (3U) -#define FTM_FLTCTRL_FAULT3EN(x) (((uint32_t)(((uint32_t)(x)) << FTM_FLTCTRL_FAULT3EN_SHIFT)) & FTM_FLTCTRL_FAULT3EN_MASK) -#define FTM_FLTCTRL_FFLTR0EN_MASK (0x10U) -#define FTM_FLTCTRL_FFLTR0EN_SHIFT (4U) -#define FTM_FLTCTRL_FFLTR0EN(x) (((uint32_t)(((uint32_t)(x)) << FTM_FLTCTRL_FFLTR0EN_SHIFT)) & FTM_FLTCTRL_FFLTR0EN_MASK) -#define FTM_FLTCTRL_FFLTR1EN_MASK (0x20U) -#define FTM_FLTCTRL_FFLTR1EN_SHIFT (5U) -#define FTM_FLTCTRL_FFLTR1EN(x) (((uint32_t)(((uint32_t)(x)) << FTM_FLTCTRL_FFLTR1EN_SHIFT)) & FTM_FLTCTRL_FFLTR1EN_MASK) -#define FTM_FLTCTRL_FFLTR2EN_MASK (0x40U) -#define FTM_FLTCTRL_FFLTR2EN_SHIFT (6U) -#define FTM_FLTCTRL_FFLTR2EN(x) (((uint32_t)(((uint32_t)(x)) << FTM_FLTCTRL_FFLTR2EN_SHIFT)) & FTM_FLTCTRL_FFLTR2EN_MASK) -#define FTM_FLTCTRL_FFLTR3EN_MASK (0x80U) -#define FTM_FLTCTRL_FFLTR3EN_SHIFT (7U) -#define FTM_FLTCTRL_FFLTR3EN(x) (((uint32_t)(((uint32_t)(x)) << FTM_FLTCTRL_FFLTR3EN_SHIFT)) & FTM_FLTCTRL_FFLTR3EN_MASK) -#define FTM_FLTCTRL_FFVAL_MASK (0xF00U) -#define FTM_FLTCTRL_FFVAL_SHIFT (8U) -#define FTM_FLTCTRL_FFVAL(x) (((uint32_t)(((uint32_t)(x)) << FTM_FLTCTRL_FFVAL_SHIFT)) & FTM_FLTCTRL_FFVAL_MASK) - -/*! @name QDCTRL - Quadrature Decoder Control And Status */ -#define FTM_QDCTRL_QUADEN_MASK (0x1U) -#define FTM_QDCTRL_QUADEN_SHIFT (0U) -#define FTM_QDCTRL_QUADEN(x) (((uint32_t)(((uint32_t)(x)) << FTM_QDCTRL_QUADEN_SHIFT)) & FTM_QDCTRL_QUADEN_MASK) -#define FTM_QDCTRL_TOFDIR_MASK (0x2U) -#define FTM_QDCTRL_TOFDIR_SHIFT (1U) -#define FTM_QDCTRL_TOFDIR(x) (((uint32_t)(((uint32_t)(x)) << FTM_QDCTRL_TOFDIR_SHIFT)) & FTM_QDCTRL_TOFDIR_MASK) -#define FTM_QDCTRL_QUADIR_MASK (0x4U) -#define FTM_QDCTRL_QUADIR_SHIFT (2U) -#define FTM_QDCTRL_QUADIR(x) (((uint32_t)(((uint32_t)(x)) << FTM_QDCTRL_QUADIR_SHIFT)) & FTM_QDCTRL_QUADIR_MASK) -#define FTM_QDCTRL_QUADMODE_MASK (0x8U) -#define FTM_QDCTRL_QUADMODE_SHIFT (3U) -#define FTM_QDCTRL_QUADMODE(x) (((uint32_t)(((uint32_t)(x)) << FTM_QDCTRL_QUADMODE_SHIFT)) & FTM_QDCTRL_QUADMODE_MASK) -#define FTM_QDCTRL_PHBPOL_MASK (0x10U) -#define FTM_QDCTRL_PHBPOL_SHIFT (4U) -#define FTM_QDCTRL_PHBPOL(x) (((uint32_t)(((uint32_t)(x)) << FTM_QDCTRL_PHBPOL_SHIFT)) & FTM_QDCTRL_PHBPOL_MASK) -#define FTM_QDCTRL_PHAPOL_MASK (0x20U) -#define FTM_QDCTRL_PHAPOL_SHIFT (5U) -#define FTM_QDCTRL_PHAPOL(x) (((uint32_t)(((uint32_t)(x)) << FTM_QDCTRL_PHAPOL_SHIFT)) & FTM_QDCTRL_PHAPOL_MASK) -#define FTM_QDCTRL_PHBFLTREN_MASK (0x40U) -#define FTM_QDCTRL_PHBFLTREN_SHIFT (6U) -#define FTM_QDCTRL_PHBFLTREN(x) (((uint32_t)(((uint32_t)(x)) << FTM_QDCTRL_PHBFLTREN_SHIFT)) & FTM_QDCTRL_PHBFLTREN_MASK) -#define FTM_QDCTRL_PHAFLTREN_MASK (0x80U) -#define FTM_QDCTRL_PHAFLTREN_SHIFT (7U) -#define FTM_QDCTRL_PHAFLTREN(x) (((uint32_t)(((uint32_t)(x)) << FTM_QDCTRL_PHAFLTREN_SHIFT)) & FTM_QDCTRL_PHAFLTREN_MASK) - -/*! @name CONF - Configuration */ -#define FTM_CONF_NUMTOF_MASK (0x1FU) -#define FTM_CONF_NUMTOF_SHIFT (0U) -#define FTM_CONF_NUMTOF(x) (((uint32_t)(((uint32_t)(x)) << FTM_CONF_NUMTOF_SHIFT)) & FTM_CONF_NUMTOF_MASK) -#define FTM_CONF_BDMMODE_MASK (0xC0U) -#define FTM_CONF_BDMMODE_SHIFT (6U) -#define FTM_CONF_BDMMODE(x) (((uint32_t)(((uint32_t)(x)) << FTM_CONF_BDMMODE_SHIFT)) & FTM_CONF_BDMMODE_MASK) -#define FTM_CONF_GTBEEN_MASK (0x200U) -#define FTM_CONF_GTBEEN_SHIFT (9U) -#define FTM_CONF_GTBEEN(x) (((uint32_t)(((uint32_t)(x)) << FTM_CONF_GTBEEN_SHIFT)) & FTM_CONF_GTBEEN_MASK) -#define FTM_CONF_GTBEOUT_MASK (0x400U) -#define FTM_CONF_GTBEOUT_SHIFT (10U) -#define FTM_CONF_GTBEOUT(x) (((uint32_t)(((uint32_t)(x)) << FTM_CONF_GTBEOUT_SHIFT)) & FTM_CONF_GTBEOUT_MASK) - -/*! @name FLTPOL - FTM Fault Input Polarity */ -#define FTM_FLTPOL_FLT0POL_MASK (0x1U) -#define FTM_FLTPOL_FLT0POL_SHIFT (0U) -#define FTM_FLTPOL_FLT0POL(x) (((uint32_t)(((uint32_t)(x)) << FTM_FLTPOL_FLT0POL_SHIFT)) & FTM_FLTPOL_FLT0POL_MASK) -#define FTM_FLTPOL_FLT1POL_MASK (0x2U) -#define FTM_FLTPOL_FLT1POL_SHIFT (1U) -#define FTM_FLTPOL_FLT1POL(x) (((uint32_t)(((uint32_t)(x)) << FTM_FLTPOL_FLT1POL_SHIFT)) & FTM_FLTPOL_FLT1POL_MASK) -#define FTM_FLTPOL_FLT2POL_MASK (0x4U) -#define FTM_FLTPOL_FLT2POL_SHIFT (2U) -#define FTM_FLTPOL_FLT2POL(x) (((uint32_t)(((uint32_t)(x)) << FTM_FLTPOL_FLT2POL_SHIFT)) & FTM_FLTPOL_FLT2POL_MASK) -#define FTM_FLTPOL_FLT3POL_MASK (0x8U) -#define FTM_FLTPOL_FLT3POL_SHIFT (3U) -#define FTM_FLTPOL_FLT3POL(x) (((uint32_t)(((uint32_t)(x)) << FTM_FLTPOL_FLT3POL_SHIFT)) & FTM_FLTPOL_FLT3POL_MASK) - -/*! @name SYNCONF - Synchronization Configuration */ -#define FTM_SYNCONF_HWTRIGMODE_MASK (0x1U) -#define FTM_SYNCONF_HWTRIGMODE_SHIFT (0U) -#define FTM_SYNCONF_HWTRIGMODE(x) (((uint32_t)(((uint32_t)(x)) << FTM_SYNCONF_HWTRIGMODE_SHIFT)) & FTM_SYNCONF_HWTRIGMODE_MASK) -#define FTM_SYNCONF_CNTINC_MASK (0x4U) -#define FTM_SYNCONF_CNTINC_SHIFT (2U) -#define FTM_SYNCONF_CNTINC(x) (((uint32_t)(((uint32_t)(x)) << FTM_SYNCONF_CNTINC_SHIFT)) & FTM_SYNCONF_CNTINC_MASK) -#define FTM_SYNCONF_INVC_MASK (0x10U) -#define FTM_SYNCONF_INVC_SHIFT (4U) -#define FTM_SYNCONF_INVC(x) (((uint32_t)(((uint32_t)(x)) << FTM_SYNCONF_INVC_SHIFT)) & FTM_SYNCONF_INVC_MASK) -#define FTM_SYNCONF_SWOC_MASK (0x20U) -#define FTM_SYNCONF_SWOC_SHIFT (5U) -#define FTM_SYNCONF_SWOC(x) (((uint32_t)(((uint32_t)(x)) << FTM_SYNCONF_SWOC_SHIFT)) & FTM_SYNCONF_SWOC_MASK) -#define FTM_SYNCONF_SYNCMODE_MASK (0x80U) -#define FTM_SYNCONF_SYNCMODE_SHIFT (7U) -#define FTM_SYNCONF_SYNCMODE(x) (((uint32_t)(((uint32_t)(x)) << FTM_SYNCONF_SYNCMODE_SHIFT)) & FTM_SYNCONF_SYNCMODE_MASK) -#define FTM_SYNCONF_SWRSTCNT_MASK (0x100U) -#define FTM_SYNCONF_SWRSTCNT_SHIFT (8U) -#define FTM_SYNCONF_SWRSTCNT(x) (((uint32_t)(((uint32_t)(x)) << FTM_SYNCONF_SWRSTCNT_SHIFT)) & FTM_SYNCONF_SWRSTCNT_MASK) -#define FTM_SYNCONF_SWWRBUF_MASK (0x200U) -#define FTM_SYNCONF_SWWRBUF_SHIFT (9U) -#define FTM_SYNCONF_SWWRBUF(x) (((uint32_t)(((uint32_t)(x)) << FTM_SYNCONF_SWWRBUF_SHIFT)) & FTM_SYNCONF_SWWRBUF_MASK) -#define FTM_SYNCONF_SWOM_MASK (0x400U) -#define FTM_SYNCONF_SWOM_SHIFT (10U) -#define FTM_SYNCONF_SWOM(x) (((uint32_t)(((uint32_t)(x)) << FTM_SYNCONF_SWOM_SHIFT)) & FTM_SYNCONF_SWOM_MASK) -#define FTM_SYNCONF_SWINVC_MASK (0x800U) -#define FTM_SYNCONF_SWINVC_SHIFT (11U) -#define FTM_SYNCONF_SWINVC(x) (((uint32_t)(((uint32_t)(x)) << FTM_SYNCONF_SWINVC_SHIFT)) & FTM_SYNCONF_SWINVC_MASK) -#define FTM_SYNCONF_SWSOC_MASK (0x1000U) -#define FTM_SYNCONF_SWSOC_SHIFT (12U) -#define FTM_SYNCONF_SWSOC(x) (((uint32_t)(((uint32_t)(x)) << FTM_SYNCONF_SWSOC_SHIFT)) & FTM_SYNCONF_SWSOC_MASK) -#define FTM_SYNCONF_HWRSTCNT_MASK (0x10000U) -#define FTM_SYNCONF_HWRSTCNT_SHIFT (16U) -#define FTM_SYNCONF_HWRSTCNT(x) (((uint32_t)(((uint32_t)(x)) << FTM_SYNCONF_HWRSTCNT_SHIFT)) & FTM_SYNCONF_HWRSTCNT_MASK) -#define FTM_SYNCONF_HWWRBUF_MASK (0x20000U) -#define FTM_SYNCONF_HWWRBUF_SHIFT (17U) -#define FTM_SYNCONF_HWWRBUF(x) (((uint32_t)(((uint32_t)(x)) << FTM_SYNCONF_HWWRBUF_SHIFT)) & FTM_SYNCONF_HWWRBUF_MASK) -#define FTM_SYNCONF_HWOM_MASK (0x40000U) -#define FTM_SYNCONF_HWOM_SHIFT (18U) -#define FTM_SYNCONF_HWOM(x) (((uint32_t)(((uint32_t)(x)) << FTM_SYNCONF_HWOM_SHIFT)) & FTM_SYNCONF_HWOM_MASK) -#define FTM_SYNCONF_HWINVC_MASK (0x80000U) -#define FTM_SYNCONF_HWINVC_SHIFT (19U) -#define FTM_SYNCONF_HWINVC(x) (((uint32_t)(((uint32_t)(x)) << FTM_SYNCONF_HWINVC_SHIFT)) & FTM_SYNCONF_HWINVC_MASK) -#define FTM_SYNCONF_HWSOC_MASK (0x100000U) -#define FTM_SYNCONF_HWSOC_SHIFT (20U) -#define FTM_SYNCONF_HWSOC(x) (((uint32_t)(((uint32_t)(x)) << FTM_SYNCONF_HWSOC_SHIFT)) & FTM_SYNCONF_HWSOC_MASK) - -/*! @name INVCTRL - FTM Inverting Control */ -#define FTM_INVCTRL_INV0EN_MASK (0x1U) -#define FTM_INVCTRL_INV0EN_SHIFT (0U) -#define FTM_INVCTRL_INV0EN(x) (((uint32_t)(((uint32_t)(x)) << FTM_INVCTRL_INV0EN_SHIFT)) & FTM_INVCTRL_INV0EN_MASK) -#define FTM_INVCTRL_INV1EN_MASK (0x2U) -#define FTM_INVCTRL_INV1EN_SHIFT (1U) -#define FTM_INVCTRL_INV1EN(x) (((uint32_t)(((uint32_t)(x)) << FTM_INVCTRL_INV1EN_SHIFT)) & FTM_INVCTRL_INV1EN_MASK) -#define FTM_INVCTRL_INV2EN_MASK (0x4U) -#define FTM_INVCTRL_INV2EN_SHIFT (2U) -#define FTM_INVCTRL_INV2EN(x) (((uint32_t)(((uint32_t)(x)) << FTM_INVCTRL_INV2EN_SHIFT)) & FTM_INVCTRL_INV2EN_MASK) -#define FTM_INVCTRL_INV3EN_MASK (0x8U) -#define FTM_INVCTRL_INV3EN_SHIFT (3U) -#define FTM_INVCTRL_INV3EN(x) (((uint32_t)(((uint32_t)(x)) << FTM_INVCTRL_INV3EN_SHIFT)) & FTM_INVCTRL_INV3EN_MASK) - -/*! @name SWOCTRL - FTM Software Output Control */ -#define FTM_SWOCTRL_CH0OC_MASK (0x1U) -#define FTM_SWOCTRL_CH0OC_SHIFT (0U) -#define FTM_SWOCTRL_CH0OC(x) (((uint32_t)(((uint32_t)(x)) << FTM_SWOCTRL_CH0OC_SHIFT)) & FTM_SWOCTRL_CH0OC_MASK) -#define FTM_SWOCTRL_CH1OC_MASK (0x2U) -#define FTM_SWOCTRL_CH1OC_SHIFT (1U) -#define FTM_SWOCTRL_CH1OC(x) (((uint32_t)(((uint32_t)(x)) << FTM_SWOCTRL_CH1OC_SHIFT)) & FTM_SWOCTRL_CH1OC_MASK) -#define FTM_SWOCTRL_CH2OC_MASK (0x4U) -#define FTM_SWOCTRL_CH2OC_SHIFT (2U) -#define FTM_SWOCTRL_CH2OC(x) (((uint32_t)(((uint32_t)(x)) << FTM_SWOCTRL_CH2OC_SHIFT)) & FTM_SWOCTRL_CH2OC_MASK) -#define FTM_SWOCTRL_CH3OC_MASK (0x8U) -#define FTM_SWOCTRL_CH3OC_SHIFT (3U) -#define FTM_SWOCTRL_CH3OC(x) (((uint32_t)(((uint32_t)(x)) << FTM_SWOCTRL_CH3OC_SHIFT)) & FTM_SWOCTRL_CH3OC_MASK) -#define FTM_SWOCTRL_CH4OC_MASK (0x10U) -#define FTM_SWOCTRL_CH4OC_SHIFT (4U) -#define FTM_SWOCTRL_CH4OC(x) (((uint32_t)(((uint32_t)(x)) << FTM_SWOCTRL_CH4OC_SHIFT)) & FTM_SWOCTRL_CH4OC_MASK) -#define FTM_SWOCTRL_CH5OC_MASK (0x20U) -#define FTM_SWOCTRL_CH5OC_SHIFT (5U) -#define FTM_SWOCTRL_CH5OC(x) (((uint32_t)(((uint32_t)(x)) << FTM_SWOCTRL_CH5OC_SHIFT)) & FTM_SWOCTRL_CH5OC_MASK) -#define FTM_SWOCTRL_CH6OC_MASK (0x40U) -#define FTM_SWOCTRL_CH6OC_SHIFT (6U) -#define FTM_SWOCTRL_CH6OC(x) (((uint32_t)(((uint32_t)(x)) << FTM_SWOCTRL_CH6OC_SHIFT)) & FTM_SWOCTRL_CH6OC_MASK) -#define FTM_SWOCTRL_CH7OC_MASK (0x80U) -#define FTM_SWOCTRL_CH7OC_SHIFT (7U) -#define FTM_SWOCTRL_CH7OC(x) (((uint32_t)(((uint32_t)(x)) << FTM_SWOCTRL_CH7OC_SHIFT)) & FTM_SWOCTRL_CH7OC_MASK) -#define FTM_SWOCTRL_CH0OCV_MASK (0x100U) -#define FTM_SWOCTRL_CH0OCV_SHIFT (8U) -#define FTM_SWOCTRL_CH0OCV(x) (((uint32_t)(((uint32_t)(x)) << FTM_SWOCTRL_CH0OCV_SHIFT)) & FTM_SWOCTRL_CH0OCV_MASK) -#define FTM_SWOCTRL_CH1OCV_MASK (0x200U) -#define FTM_SWOCTRL_CH1OCV_SHIFT (9U) -#define FTM_SWOCTRL_CH1OCV(x) (((uint32_t)(((uint32_t)(x)) << FTM_SWOCTRL_CH1OCV_SHIFT)) & FTM_SWOCTRL_CH1OCV_MASK) -#define FTM_SWOCTRL_CH2OCV_MASK (0x400U) -#define FTM_SWOCTRL_CH2OCV_SHIFT (10U) -#define FTM_SWOCTRL_CH2OCV(x) (((uint32_t)(((uint32_t)(x)) << FTM_SWOCTRL_CH2OCV_SHIFT)) & FTM_SWOCTRL_CH2OCV_MASK) -#define FTM_SWOCTRL_CH3OCV_MASK (0x800U) -#define FTM_SWOCTRL_CH3OCV_SHIFT (11U) -#define FTM_SWOCTRL_CH3OCV(x) (((uint32_t)(((uint32_t)(x)) << FTM_SWOCTRL_CH3OCV_SHIFT)) & FTM_SWOCTRL_CH3OCV_MASK) -#define FTM_SWOCTRL_CH4OCV_MASK (0x1000U) -#define FTM_SWOCTRL_CH4OCV_SHIFT (12U) -#define FTM_SWOCTRL_CH4OCV(x) (((uint32_t)(((uint32_t)(x)) << FTM_SWOCTRL_CH4OCV_SHIFT)) & FTM_SWOCTRL_CH4OCV_MASK) -#define FTM_SWOCTRL_CH5OCV_MASK (0x2000U) -#define FTM_SWOCTRL_CH5OCV_SHIFT (13U) -#define FTM_SWOCTRL_CH5OCV(x) (((uint32_t)(((uint32_t)(x)) << FTM_SWOCTRL_CH5OCV_SHIFT)) & FTM_SWOCTRL_CH5OCV_MASK) -#define FTM_SWOCTRL_CH6OCV_MASK (0x4000U) -#define FTM_SWOCTRL_CH6OCV_SHIFT (14U) -#define FTM_SWOCTRL_CH6OCV(x) (((uint32_t)(((uint32_t)(x)) << FTM_SWOCTRL_CH6OCV_SHIFT)) & FTM_SWOCTRL_CH6OCV_MASK) -#define FTM_SWOCTRL_CH7OCV_MASK (0x8000U) -#define FTM_SWOCTRL_CH7OCV_SHIFT (15U) -#define FTM_SWOCTRL_CH7OCV(x) (((uint32_t)(((uint32_t)(x)) << FTM_SWOCTRL_CH7OCV_SHIFT)) & FTM_SWOCTRL_CH7OCV_MASK) - -/*! @name PWMLOAD - FTM PWM Load */ -#define FTM_PWMLOAD_CH0SEL_MASK (0x1U) -#define FTM_PWMLOAD_CH0SEL_SHIFT (0U) -#define FTM_PWMLOAD_CH0SEL(x) (((uint32_t)(((uint32_t)(x)) << FTM_PWMLOAD_CH0SEL_SHIFT)) & FTM_PWMLOAD_CH0SEL_MASK) -#define FTM_PWMLOAD_CH1SEL_MASK (0x2U) -#define FTM_PWMLOAD_CH1SEL_SHIFT (1U) -#define FTM_PWMLOAD_CH1SEL(x) (((uint32_t)(((uint32_t)(x)) << FTM_PWMLOAD_CH1SEL_SHIFT)) & FTM_PWMLOAD_CH1SEL_MASK) -#define FTM_PWMLOAD_CH2SEL_MASK (0x4U) -#define FTM_PWMLOAD_CH2SEL_SHIFT (2U) -#define FTM_PWMLOAD_CH2SEL(x) (((uint32_t)(((uint32_t)(x)) << FTM_PWMLOAD_CH2SEL_SHIFT)) & FTM_PWMLOAD_CH2SEL_MASK) -#define FTM_PWMLOAD_CH3SEL_MASK (0x8U) -#define FTM_PWMLOAD_CH3SEL_SHIFT (3U) -#define FTM_PWMLOAD_CH3SEL(x) (((uint32_t)(((uint32_t)(x)) << FTM_PWMLOAD_CH3SEL_SHIFT)) & FTM_PWMLOAD_CH3SEL_MASK) -#define FTM_PWMLOAD_CH4SEL_MASK (0x10U) -#define FTM_PWMLOAD_CH4SEL_SHIFT (4U) -#define FTM_PWMLOAD_CH4SEL(x) (((uint32_t)(((uint32_t)(x)) << FTM_PWMLOAD_CH4SEL_SHIFT)) & FTM_PWMLOAD_CH4SEL_MASK) -#define FTM_PWMLOAD_CH5SEL_MASK (0x20U) -#define FTM_PWMLOAD_CH5SEL_SHIFT (5U) -#define FTM_PWMLOAD_CH5SEL(x) (((uint32_t)(((uint32_t)(x)) << FTM_PWMLOAD_CH5SEL_SHIFT)) & FTM_PWMLOAD_CH5SEL_MASK) -#define FTM_PWMLOAD_CH6SEL_MASK (0x40U) -#define FTM_PWMLOAD_CH6SEL_SHIFT (6U) -#define FTM_PWMLOAD_CH6SEL(x) (((uint32_t)(((uint32_t)(x)) << FTM_PWMLOAD_CH6SEL_SHIFT)) & FTM_PWMLOAD_CH6SEL_MASK) -#define FTM_PWMLOAD_CH7SEL_MASK (0x80U) -#define FTM_PWMLOAD_CH7SEL_SHIFT (7U) -#define FTM_PWMLOAD_CH7SEL(x) (((uint32_t)(((uint32_t)(x)) << FTM_PWMLOAD_CH7SEL_SHIFT)) & FTM_PWMLOAD_CH7SEL_MASK) -#define FTM_PWMLOAD_LDOK_MASK (0x200U) -#define FTM_PWMLOAD_LDOK_SHIFT (9U) -#define FTM_PWMLOAD_LDOK(x) (((uint32_t)(((uint32_t)(x)) << FTM_PWMLOAD_LDOK_SHIFT)) & FTM_PWMLOAD_LDOK_MASK) - - -/*! - * @} - */ /* end of group FTM_Register_Masks */ - - -/* FTM - Peripheral instance base addresses */ -/** Peripheral FTM0 base address */ -#define FTM0_BASE (0x40038000u) -/** Peripheral FTM0 base pointer */ -#define FTM0 ((FTM_Type *)FTM0_BASE) -/** Peripheral FTM1 base address */ -#define FTM1_BASE (0x40039000u) -/** Peripheral FTM1 base pointer */ -#define FTM1 ((FTM_Type *)FTM1_BASE) -/** Peripheral FTM2 base address */ -#define FTM2_BASE (0x4003A000u) -/** Peripheral FTM2 base pointer */ -#define FTM2 ((FTM_Type *)FTM2_BASE) -/** Peripheral FTM3 base address */ -#define FTM3_BASE (0x400B9000u) -/** Peripheral FTM3 base pointer */ -#define FTM3 ((FTM_Type *)FTM3_BASE) -/** Array initializer of FTM peripheral base addresses */ -#define FTM_BASE_ADDRS { FTM0_BASE, FTM1_BASE, FTM2_BASE, FTM3_BASE } -/** Array initializer of FTM peripheral base pointers */ -#define FTM_BASE_PTRS { FTM0, FTM1, FTM2, FTM3 } -/** Interrupt vectors for the FTM peripheral type */ -#define FTM_IRQS { FTM0_IRQn, FTM1_IRQn, FTM2_IRQn, FTM3_IRQn } - -/*! - * @} - */ /* end of group FTM_Peripheral_Access_Layer */ - - -/* ---------------------------------------------------------------------------- - -- GPIO Peripheral Access Layer - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup GPIO_Peripheral_Access_Layer GPIO Peripheral Access Layer - * @{ - */ - -/** GPIO - Register Layout Typedef */ -typedef struct { - __IO uint32_t PDOR; /**< Port Data Output Register, offset: 0x0 */ - __O uint32_t PSOR; /**< Port Set Output Register, offset: 0x4 */ - __O uint32_t PCOR; /**< Port Clear Output Register, offset: 0x8 */ - __O uint32_t PTOR; /**< Port Toggle Output Register, offset: 0xC */ - __I uint32_t PDIR; /**< Port Data Input Register, offset: 0x10 */ - __IO uint32_t PDDR; /**< Port Data Direction Register, offset: 0x14 */ -} GPIO_Type; - -/* ---------------------------------------------------------------------------- - -- GPIO Register Masks - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup GPIO_Register_Masks GPIO Register Masks - * @{ - */ - -/*! @name PDOR - Port Data Output Register */ -#define GPIO_PDOR_PDO_MASK (0xFFFFFFFFU) -#define GPIO_PDOR_PDO_SHIFT (0U) -#define GPIO_PDOR_PDO(x) (((uint32_t)(((uint32_t)(x)) << GPIO_PDOR_PDO_SHIFT)) & GPIO_PDOR_PDO_MASK) - -/*! @name PSOR - Port Set Output Register */ -#define GPIO_PSOR_PTSO_MASK (0xFFFFFFFFU) -#define GPIO_PSOR_PTSO_SHIFT (0U) -#define GPIO_PSOR_PTSO(x) (((uint32_t)(((uint32_t)(x)) << GPIO_PSOR_PTSO_SHIFT)) & GPIO_PSOR_PTSO_MASK) - -/*! @name PCOR - Port Clear Output Register */ -#define GPIO_PCOR_PTCO_MASK (0xFFFFFFFFU) -#define GPIO_PCOR_PTCO_SHIFT (0U) -#define GPIO_PCOR_PTCO(x) (((uint32_t)(((uint32_t)(x)) << GPIO_PCOR_PTCO_SHIFT)) & GPIO_PCOR_PTCO_MASK) - -/*! @name PTOR - Port Toggle Output Register */ -#define GPIO_PTOR_PTTO_MASK (0xFFFFFFFFU) -#define GPIO_PTOR_PTTO_SHIFT (0U) -#define GPIO_PTOR_PTTO(x) (((uint32_t)(((uint32_t)(x)) << GPIO_PTOR_PTTO_SHIFT)) & GPIO_PTOR_PTTO_MASK) - -/*! @name PDIR - Port Data Input Register */ -#define GPIO_PDIR_PDI_MASK (0xFFFFFFFFU) -#define GPIO_PDIR_PDI_SHIFT (0U) -#define GPIO_PDIR_PDI(x) (((uint32_t)(((uint32_t)(x)) << GPIO_PDIR_PDI_SHIFT)) & GPIO_PDIR_PDI_MASK) - -/*! @name PDDR - Port Data Direction Register */ -#define GPIO_PDDR_PDD_MASK (0xFFFFFFFFU) -#define GPIO_PDDR_PDD_SHIFT (0U) -#define GPIO_PDDR_PDD(x) (((uint32_t)(((uint32_t)(x)) << GPIO_PDDR_PDD_SHIFT)) & GPIO_PDDR_PDD_MASK) - - -/*! - * @} - */ /* end of group GPIO_Register_Masks */ - - -/* GPIO - Peripheral instance base addresses */ -/** Peripheral GPIOA base address */ -#define GPIOA_BASE (0x400FF000u) -/** Peripheral GPIOA base pointer */ -#define GPIOA ((GPIO_Type *)GPIOA_BASE) -/** Peripheral GPIOB base address */ -#define GPIOB_BASE (0x400FF040u) -/** Peripheral GPIOB base pointer */ -#define GPIOB ((GPIO_Type *)GPIOB_BASE) -/** Peripheral GPIOC base address */ -#define GPIOC_BASE (0x400FF080u) -/** Peripheral GPIOC base pointer */ -#define GPIOC ((GPIO_Type *)GPIOC_BASE) -/** Peripheral GPIOD base address */ -#define GPIOD_BASE (0x400FF0C0u) -/** Peripheral GPIOD base pointer */ -#define GPIOD ((GPIO_Type *)GPIOD_BASE) -/** Peripheral GPIOE base address */ -#define GPIOE_BASE (0x400FF100u) -/** Peripheral GPIOE base pointer */ -#define GPIOE ((GPIO_Type *)GPIOE_BASE) -/** Array initializer of GPIO peripheral base addresses */ -#define GPIO_BASE_ADDRS { GPIOA_BASE, GPIOB_BASE, GPIOC_BASE, GPIOD_BASE, GPIOE_BASE } -/** Array initializer of GPIO peripheral base pointers */ -#define GPIO_BASE_PTRS { GPIOA, GPIOB, GPIOC, GPIOD, GPIOE } - -/*! - * @} - */ /* end of group GPIO_Peripheral_Access_Layer */ - - -/* ---------------------------------------------------------------------------- - -- I2C Peripheral Access Layer - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup I2C_Peripheral_Access_Layer I2C Peripheral Access Layer - * @{ - */ - -/** I2C - Register Layout Typedef */ -typedef struct { - __IO uint8_t A1; /**< I2C Address Register 1, offset: 0x0 */ - __IO uint8_t F; /**< I2C Frequency Divider register, offset: 0x1 */ - __IO uint8_t C1; /**< I2C Control Register 1, offset: 0x2 */ - __IO uint8_t S; /**< I2C Status register, offset: 0x3 */ - __IO uint8_t D; /**< I2C Data I/O register, offset: 0x4 */ - __IO uint8_t C2; /**< I2C Control Register 2, offset: 0x5 */ - __IO uint8_t FLT; /**< I2C Programmable Input Glitch Filter register, offset: 0x6 */ - __IO uint8_t RA; /**< I2C Range Address register, offset: 0x7 */ - __IO uint8_t SMB; /**< I2C SMBus Control and Status register, offset: 0x8 */ - __IO uint8_t A2; /**< I2C Address Register 2, offset: 0x9 */ - __IO uint8_t SLTH; /**< I2C SCL Low Timeout Register High, offset: 0xA */ - __IO uint8_t SLTL; /**< I2C SCL Low Timeout Register Low, offset: 0xB */ -} I2C_Type; - -/* ---------------------------------------------------------------------------- - -- I2C Register Masks - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup I2C_Register_Masks I2C Register Masks - * @{ - */ - -/*! @name A1 - I2C Address Register 1 */ -#define I2C_A1_AD_MASK (0xFEU) -#define I2C_A1_AD_SHIFT (1U) -#define I2C_A1_AD(x) (((uint8_t)(((uint8_t)(x)) << I2C_A1_AD_SHIFT)) & I2C_A1_AD_MASK) - -/*! @name F - I2C Frequency Divider register */ -#define I2C_F_ICR_MASK (0x3FU) -#define I2C_F_ICR_SHIFT (0U) -#define I2C_F_ICR(x) (((uint8_t)(((uint8_t)(x)) << I2C_F_ICR_SHIFT)) & I2C_F_ICR_MASK) -#define I2C_F_MULT_MASK (0xC0U) -#define I2C_F_MULT_SHIFT (6U) -#define I2C_F_MULT(x) (((uint8_t)(((uint8_t)(x)) << I2C_F_MULT_SHIFT)) & I2C_F_MULT_MASK) - -/*! @name C1 - I2C Control Register 1 */ -#define I2C_C1_DMAEN_MASK (0x1U) -#define I2C_C1_DMAEN_SHIFT (0U) -#define I2C_C1_DMAEN(x) (((uint8_t)(((uint8_t)(x)) << I2C_C1_DMAEN_SHIFT)) & I2C_C1_DMAEN_MASK) -#define I2C_C1_WUEN_MASK (0x2U) -#define I2C_C1_WUEN_SHIFT (1U) -#define I2C_C1_WUEN(x) (((uint8_t)(((uint8_t)(x)) << I2C_C1_WUEN_SHIFT)) & I2C_C1_WUEN_MASK) -#define I2C_C1_RSTA_MASK (0x4U) -#define I2C_C1_RSTA_SHIFT (2U) -#define I2C_C1_RSTA(x) (((uint8_t)(((uint8_t)(x)) << I2C_C1_RSTA_SHIFT)) & I2C_C1_RSTA_MASK) -#define I2C_C1_TXAK_MASK (0x8U) -#define I2C_C1_TXAK_SHIFT (3U) -#define I2C_C1_TXAK(x) (((uint8_t)(((uint8_t)(x)) << I2C_C1_TXAK_SHIFT)) & I2C_C1_TXAK_MASK) -#define I2C_C1_TX_MASK (0x10U) -#define I2C_C1_TX_SHIFT (4U) -#define I2C_C1_TX(x) (((uint8_t)(((uint8_t)(x)) << I2C_C1_TX_SHIFT)) & I2C_C1_TX_MASK) -#define I2C_C1_MST_MASK (0x20U) -#define I2C_C1_MST_SHIFT (5U) -#define I2C_C1_MST(x) (((uint8_t)(((uint8_t)(x)) << I2C_C1_MST_SHIFT)) & I2C_C1_MST_MASK) -#define I2C_C1_IICIE_MASK (0x40U) -#define I2C_C1_IICIE_SHIFT (6U) -#define I2C_C1_IICIE(x) (((uint8_t)(((uint8_t)(x)) << I2C_C1_IICIE_SHIFT)) & I2C_C1_IICIE_MASK) -#define I2C_C1_IICEN_MASK (0x80U) -#define I2C_C1_IICEN_SHIFT (7U) -#define I2C_C1_IICEN(x) (((uint8_t)(((uint8_t)(x)) << I2C_C1_IICEN_SHIFT)) & I2C_C1_IICEN_MASK) - -/*! @name S - I2C Status register */ -#define I2C_S_RXAK_MASK (0x1U) -#define I2C_S_RXAK_SHIFT (0U) -#define I2C_S_RXAK(x) (((uint8_t)(((uint8_t)(x)) << I2C_S_RXAK_SHIFT)) & I2C_S_RXAK_MASK) -#define I2C_S_IICIF_MASK (0x2U) -#define I2C_S_IICIF_SHIFT (1U) -#define I2C_S_IICIF(x) (((uint8_t)(((uint8_t)(x)) << I2C_S_IICIF_SHIFT)) & I2C_S_IICIF_MASK) -#define I2C_S_SRW_MASK (0x4U) -#define I2C_S_SRW_SHIFT (2U) -#define I2C_S_SRW(x) (((uint8_t)(((uint8_t)(x)) << I2C_S_SRW_SHIFT)) & I2C_S_SRW_MASK) -#define I2C_S_RAM_MASK (0x8U) -#define I2C_S_RAM_SHIFT (3U) -#define I2C_S_RAM(x) (((uint8_t)(((uint8_t)(x)) << I2C_S_RAM_SHIFT)) & I2C_S_RAM_MASK) -#define I2C_S_ARBL_MASK (0x10U) -#define I2C_S_ARBL_SHIFT (4U) -#define I2C_S_ARBL(x) (((uint8_t)(((uint8_t)(x)) << I2C_S_ARBL_SHIFT)) & I2C_S_ARBL_MASK) -#define I2C_S_BUSY_MASK (0x20U) -#define I2C_S_BUSY_SHIFT (5U) -#define I2C_S_BUSY(x) (((uint8_t)(((uint8_t)(x)) << I2C_S_BUSY_SHIFT)) & I2C_S_BUSY_MASK) -#define I2C_S_IAAS_MASK (0x40U) -#define I2C_S_IAAS_SHIFT (6U) -#define I2C_S_IAAS(x) (((uint8_t)(((uint8_t)(x)) << I2C_S_IAAS_SHIFT)) & I2C_S_IAAS_MASK) -#define I2C_S_TCF_MASK (0x80U) -#define I2C_S_TCF_SHIFT (7U) -#define I2C_S_TCF(x) (((uint8_t)(((uint8_t)(x)) << I2C_S_TCF_SHIFT)) & I2C_S_TCF_MASK) - -/*! @name D - I2C Data I/O register */ -#define I2C_D_DATA_MASK (0xFFU) -#define I2C_D_DATA_SHIFT (0U) -#define I2C_D_DATA(x) (((uint8_t)(((uint8_t)(x)) << I2C_D_DATA_SHIFT)) & I2C_D_DATA_MASK) - -/*! @name C2 - I2C Control Register 2 */ -#define I2C_C2_AD_MASK (0x7U) -#define I2C_C2_AD_SHIFT (0U) -#define I2C_C2_AD(x) (((uint8_t)(((uint8_t)(x)) << I2C_C2_AD_SHIFT)) & I2C_C2_AD_MASK) -#define I2C_C2_RMEN_MASK (0x8U) -#define I2C_C2_RMEN_SHIFT (3U) -#define I2C_C2_RMEN(x) (((uint8_t)(((uint8_t)(x)) << I2C_C2_RMEN_SHIFT)) & I2C_C2_RMEN_MASK) -#define I2C_C2_SBRC_MASK (0x10U) -#define I2C_C2_SBRC_SHIFT (4U) -#define I2C_C2_SBRC(x) (((uint8_t)(((uint8_t)(x)) << I2C_C2_SBRC_SHIFT)) & I2C_C2_SBRC_MASK) -#define I2C_C2_HDRS_MASK (0x20U) -#define I2C_C2_HDRS_SHIFT (5U) -#define I2C_C2_HDRS(x) (((uint8_t)(((uint8_t)(x)) << I2C_C2_HDRS_SHIFT)) & I2C_C2_HDRS_MASK) -#define I2C_C2_ADEXT_MASK (0x40U) -#define I2C_C2_ADEXT_SHIFT (6U) -#define I2C_C2_ADEXT(x) (((uint8_t)(((uint8_t)(x)) << I2C_C2_ADEXT_SHIFT)) & I2C_C2_ADEXT_MASK) -#define I2C_C2_GCAEN_MASK (0x80U) -#define I2C_C2_GCAEN_SHIFT (7U) -#define I2C_C2_GCAEN(x) (((uint8_t)(((uint8_t)(x)) << I2C_C2_GCAEN_SHIFT)) & I2C_C2_GCAEN_MASK) - -/*! @name FLT - I2C Programmable Input Glitch Filter register */ -#define I2C_FLT_FLT_MASK (0xFU) -#define I2C_FLT_FLT_SHIFT (0U) -#define I2C_FLT_FLT(x) (((uint8_t)(((uint8_t)(x)) << I2C_FLT_FLT_SHIFT)) & I2C_FLT_FLT_MASK) -#define I2C_FLT_STARTF_MASK (0x10U) -#define I2C_FLT_STARTF_SHIFT (4U) -#define I2C_FLT_STARTF(x) (((uint8_t)(((uint8_t)(x)) << I2C_FLT_STARTF_SHIFT)) & I2C_FLT_STARTF_MASK) -#define I2C_FLT_SSIE_MASK (0x20U) -#define I2C_FLT_SSIE_SHIFT (5U) -#define I2C_FLT_SSIE(x) (((uint8_t)(((uint8_t)(x)) << I2C_FLT_SSIE_SHIFT)) & I2C_FLT_SSIE_MASK) -#define I2C_FLT_STOPF_MASK (0x40U) -#define I2C_FLT_STOPF_SHIFT (6U) -#define I2C_FLT_STOPF(x) (((uint8_t)(((uint8_t)(x)) << I2C_FLT_STOPF_SHIFT)) & I2C_FLT_STOPF_MASK) -#define I2C_FLT_SHEN_MASK (0x80U) -#define I2C_FLT_SHEN_SHIFT (7U) -#define I2C_FLT_SHEN(x) (((uint8_t)(((uint8_t)(x)) << I2C_FLT_SHEN_SHIFT)) & I2C_FLT_SHEN_MASK) - -/*! @name RA - I2C Range Address register */ -#define I2C_RA_RAD_MASK (0xFEU) -#define I2C_RA_RAD_SHIFT (1U) -#define I2C_RA_RAD(x) (((uint8_t)(((uint8_t)(x)) << I2C_RA_RAD_SHIFT)) & I2C_RA_RAD_MASK) - -/*! @name SMB - I2C SMBus Control and Status register */ -#define I2C_SMB_SHTF2IE_MASK (0x1U) -#define I2C_SMB_SHTF2IE_SHIFT (0U) -#define I2C_SMB_SHTF2IE(x) (((uint8_t)(((uint8_t)(x)) << I2C_SMB_SHTF2IE_SHIFT)) & I2C_SMB_SHTF2IE_MASK) -#define I2C_SMB_SHTF2_MASK (0x2U) -#define I2C_SMB_SHTF2_SHIFT (1U) -#define I2C_SMB_SHTF2(x) (((uint8_t)(((uint8_t)(x)) << I2C_SMB_SHTF2_SHIFT)) & I2C_SMB_SHTF2_MASK) -#define I2C_SMB_SHTF1_MASK (0x4U) -#define I2C_SMB_SHTF1_SHIFT (2U) -#define I2C_SMB_SHTF1(x) (((uint8_t)(((uint8_t)(x)) << I2C_SMB_SHTF1_SHIFT)) & I2C_SMB_SHTF1_MASK) -#define I2C_SMB_SLTF_MASK (0x8U) -#define I2C_SMB_SLTF_SHIFT (3U) -#define I2C_SMB_SLTF(x) (((uint8_t)(((uint8_t)(x)) << I2C_SMB_SLTF_SHIFT)) & I2C_SMB_SLTF_MASK) -#define I2C_SMB_TCKSEL_MASK (0x10U) -#define I2C_SMB_TCKSEL_SHIFT (4U) -#define I2C_SMB_TCKSEL(x) (((uint8_t)(((uint8_t)(x)) << I2C_SMB_TCKSEL_SHIFT)) & I2C_SMB_TCKSEL_MASK) -#define I2C_SMB_SIICAEN_MASK (0x20U) -#define I2C_SMB_SIICAEN_SHIFT (5U) -#define I2C_SMB_SIICAEN(x) (((uint8_t)(((uint8_t)(x)) << I2C_SMB_SIICAEN_SHIFT)) & I2C_SMB_SIICAEN_MASK) -#define I2C_SMB_ALERTEN_MASK (0x40U) -#define I2C_SMB_ALERTEN_SHIFT (6U) -#define I2C_SMB_ALERTEN(x) (((uint8_t)(((uint8_t)(x)) << I2C_SMB_ALERTEN_SHIFT)) & I2C_SMB_ALERTEN_MASK) -#define I2C_SMB_FACK_MASK (0x80U) -#define I2C_SMB_FACK_SHIFT (7U) -#define I2C_SMB_FACK(x) (((uint8_t)(((uint8_t)(x)) << I2C_SMB_FACK_SHIFT)) & I2C_SMB_FACK_MASK) - -/*! @name A2 - I2C Address Register 2 */ -#define I2C_A2_SAD_MASK (0xFEU) -#define I2C_A2_SAD_SHIFT (1U) -#define I2C_A2_SAD(x) (((uint8_t)(((uint8_t)(x)) << I2C_A2_SAD_SHIFT)) & I2C_A2_SAD_MASK) - -/*! @name SLTH - I2C SCL Low Timeout Register High */ -#define I2C_SLTH_SSLT_MASK (0xFFU) -#define I2C_SLTH_SSLT_SHIFT (0U) -#define I2C_SLTH_SSLT(x) (((uint8_t)(((uint8_t)(x)) << I2C_SLTH_SSLT_SHIFT)) & I2C_SLTH_SSLT_MASK) - -/*! @name SLTL - I2C SCL Low Timeout Register Low */ -#define I2C_SLTL_SSLT_MASK (0xFFU) -#define I2C_SLTL_SSLT_SHIFT (0U) -#define I2C_SLTL_SSLT(x) (((uint8_t)(((uint8_t)(x)) << I2C_SLTL_SSLT_SHIFT)) & I2C_SLTL_SSLT_MASK) - - -/*! - * @} - */ /* end of group I2C_Register_Masks */ - - -/* I2C - Peripheral instance base addresses */ -/** Peripheral I2C0 base address */ -#define I2C0_BASE (0x40066000u) -/** Peripheral I2C0 base pointer */ -#define I2C0 ((I2C_Type *)I2C0_BASE) -/** Peripheral I2C1 base address */ -#define I2C1_BASE (0x40067000u) -/** Peripheral I2C1 base pointer */ -#define I2C1 ((I2C_Type *)I2C1_BASE) -/** Peripheral I2C2 base address */ -#define I2C2_BASE (0x400E6000u) -/** Peripheral I2C2 base pointer */ -#define I2C2 ((I2C_Type *)I2C2_BASE) -/** Array initializer of I2C peripheral base addresses */ -#define I2C_BASE_ADDRS { I2C0_BASE, I2C1_BASE, I2C2_BASE } -/** Array initializer of I2C peripheral base pointers */ -#define I2C_BASE_PTRS { I2C0, I2C1, I2C2 } -/** Interrupt vectors for the I2C peripheral type */ -#define I2C_IRQS { I2C0_IRQn, I2C1_IRQn, I2C2_IRQn } - -/*! - * @} - */ /* end of group I2C_Peripheral_Access_Layer */ - - -/* ---------------------------------------------------------------------------- - -- I2S Peripheral Access Layer - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup I2S_Peripheral_Access_Layer I2S Peripheral Access Layer - * @{ - */ - -/** I2S - Register Layout Typedef */ -typedef struct { - __IO uint32_t TCSR; /**< SAI Transmit Control Register, offset: 0x0 */ - __IO uint32_t TCR1; /**< SAI Transmit Configuration 1 Register, offset: 0x4 */ - __IO uint32_t TCR2; /**< SAI Transmit Configuration 2 Register, offset: 0x8 */ - __IO uint32_t TCR3; /**< SAI Transmit Configuration 3 Register, offset: 0xC */ - __IO uint32_t TCR4; /**< SAI Transmit Configuration 4 Register, offset: 0x10 */ - __IO uint32_t TCR5; /**< SAI Transmit Configuration 5 Register, offset: 0x14 */ - uint8_t RESERVED_0[8]; - __O uint32_t TDR[2]; /**< SAI Transmit Data Register, array offset: 0x20, array step: 0x4 */ - uint8_t RESERVED_1[24]; - __I uint32_t TFR[2]; /**< SAI Transmit FIFO Register, array offset: 0x40, array step: 0x4 */ - uint8_t RESERVED_2[24]; - __IO uint32_t TMR; /**< SAI Transmit Mask Register, offset: 0x60 */ - uint8_t RESERVED_3[28]; - __IO uint32_t RCSR; /**< SAI Receive Control Register, offset: 0x80 */ - __IO uint32_t RCR1; /**< SAI Receive Configuration 1 Register, offset: 0x84 */ - __IO uint32_t RCR2; /**< SAI Receive Configuration 2 Register, offset: 0x88 */ - __IO uint32_t RCR3; /**< SAI Receive Configuration 3 Register, offset: 0x8C */ - __IO uint32_t RCR4; /**< SAI Receive Configuration 4 Register, offset: 0x90 */ - __IO uint32_t RCR5; /**< SAI Receive Configuration 5 Register, offset: 0x94 */ - uint8_t RESERVED_4[8]; - __I uint32_t RDR[2]; /**< SAI Receive Data Register, array offset: 0xA0, array step: 0x4 */ - uint8_t RESERVED_5[24]; - __I uint32_t RFR[2]; /**< SAI Receive FIFO Register, array offset: 0xC0, array step: 0x4 */ - uint8_t RESERVED_6[24]; - __IO uint32_t RMR; /**< SAI Receive Mask Register, offset: 0xE0 */ - uint8_t RESERVED_7[28]; - __IO uint32_t MCR; /**< SAI MCLK Control Register, offset: 0x100 */ - __IO uint32_t MDR; /**< SAI MCLK Divide Register, offset: 0x104 */ -} I2S_Type; - -/* ---------------------------------------------------------------------------- - -- I2S Register Masks - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup I2S_Register_Masks I2S Register Masks - * @{ - */ - -/*! @name TCSR - SAI Transmit Control Register */ -#define I2S_TCSR_FRDE_MASK (0x1U) -#define I2S_TCSR_FRDE_SHIFT (0U) -#define I2S_TCSR_FRDE(x) (((uint32_t)(((uint32_t)(x)) << I2S_TCSR_FRDE_SHIFT)) & I2S_TCSR_FRDE_MASK) -#define I2S_TCSR_FWDE_MASK (0x2U) -#define I2S_TCSR_FWDE_SHIFT (1U) -#define I2S_TCSR_FWDE(x) (((uint32_t)(((uint32_t)(x)) << I2S_TCSR_FWDE_SHIFT)) & I2S_TCSR_FWDE_MASK) -#define I2S_TCSR_FRIE_MASK (0x100U) -#define I2S_TCSR_FRIE_SHIFT (8U) -#define I2S_TCSR_FRIE(x) (((uint32_t)(((uint32_t)(x)) << I2S_TCSR_FRIE_SHIFT)) & I2S_TCSR_FRIE_MASK) -#define I2S_TCSR_FWIE_MASK (0x200U) -#define I2S_TCSR_FWIE_SHIFT (9U) -#define I2S_TCSR_FWIE(x) (((uint32_t)(((uint32_t)(x)) << I2S_TCSR_FWIE_SHIFT)) & I2S_TCSR_FWIE_MASK) -#define I2S_TCSR_FEIE_MASK (0x400U) -#define I2S_TCSR_FEIE_SHIFT (10U) -#define I2S_TCSR_FEIE(x) (((uint32_t)(((uint32_t)(x)) << I2S_TCSR_FEIE_SHIFT)) & I2S_TCSR_FEIE_MASK) -#define I2S_TCSR_SEIE_MASK (0x800U) -#define I2S_TCSR_SEIE_SHIFT (11U) -#define I2S_TCSR_SEIE(x) (((uint32_t)(((uint32_t)(x)) << I2S_TCSR_SEIE_SHIFT)) & I2S_TCSR_SEIE_MASK) -#define I2S_TCSR_WSIE_MASK (0x1000U) -#define I2S_TCSR_WSIE_SHIFT (12U) -#define I2S_TCSR_WSIE(x) (((uint32_t)(((uint32_t)(x)) << I2S_TCSR_WSIE_SHIFT)) & I2S_TCSR_WSIE_MASK) -#define I2S_TCSR_FRF_MASK (0x10000U) -#define I2S_TCSR_FRF_SHIFT (16U) -#define I2S_TCSR_FRF(x) (((uint32_t)(((uint32_t)(x)) << I2S_TCSR_FRF_SHIFT)) & I2S_TCSR_FRF_MASK) -#define I2S_TCSR_FWF_MASK (0x20000U) -#define I2S_TCSR_FWF_SHIFT (17U) -#define I2S_TCSR_FWF(x) (((uint32_t)(((uint32_t)(x)) << I2S_TCSR_FWF_SHIFT)) & I2S_TCSR_FWF_MASK) -#define I2S_TCSR_FEF_MASK (0x40000U) -#define I2S_TCSR_FEF_SHIFT (18U) -#define I2S_TCSR_FEF(x) (((uint32_t)(((uint32_t)(x)) << I2S_TCSR_FEF_SHIFT)) & I2S_TCSR_FEF_MASK) -#define I2S_TCSR_SEF_MASK (0x80000U) -#define I2S_TCSR_SEF_SHIFT (19U) -#define I2S_TCSR_SEF(x) (((uint32_t)(((uint32_t)(x)) << I2S_TCSR_SEF_SHIFT)) & I2S_TCSR_SEF_MASK) -#define I2S_TCSR_WSF_MASK (0x100000U) -#define I2S_TCSR_WSF_SHIFT (20U) -#define I2S_TCSR_WSF(x) (((uint32_t)(((uint32_t)(x)) << I2S_TCSR_WSF_SHIFT)) & I2S_TCSR_WSF_MASK) -#define I2S_TCSR_SR_MASK (0x1000000U) -#define I2S_TCSR_SR_SHIFT (24U) -#define I2S_TCSR_SR(x) (((uint32_t)(((uint32_t)(x)) << I2S_TCSR_SR_SHIFT)) & I2S_TCSR_SR_MASK) -#define I2S_TCSR_FR_MASK (0x2000000U) -#define I2S_TCSR_FR_SHIFT (25U) -#define I2S_TCSR_FR(x) (((uint32_t)(((uint32_t)(x)) << I2S_TCSR_FR_SHIFT)) & I2S_TCSR_FR_MASK) -#define I2S_TCSR_BCE_MASK (0x10000000U) -#define I2S_TCSR_BCE_SHIFT (28U) -#define I2S_TCSR_BCE(x) (((uint32_t)(((uint32_t)(x)) << I2S_TCSR_BCE_SHIFT)) & I2S_TCSR_BCE_MASK) -#define I2S_TCSR_DBGE_MASK (0x20000000U) -#define I2S_TCSR_DBGE_SHIFT (29U) -#define I2S_TCSR_DBGE(x) (((uint32_t)(((uint32_t)(x)) << I2S_TCSR_DBGE_SHIFT)) & I2S_TCSR_DBGE_MASK) -#define I2S_TCSR_STOPE_MASK (0x40000000U) -#define I2S_TCSR_STOPE_SHIFT (30U) -#define I2S_TCSR_STOPE(x) (((uint32_t)(((uint32_t)(x)) << I2S_TCSR_STOPE_SHIFT)) & I2S_TCSR_STOPE_MASK) -#define I2S_TCSR_TE_MASK (0x80000000U) -#define I2S_TCSR_TE_SHIFT (31U) -#define I2S_TCSR_TE(x) (((uint32_t)(((uint32_t)(x)) << I2S_TCSR_TE_SHIFT)) & I2S_TCSR_TE_MASK) - -/*! @name TCR1 - SAI Transmit Configuration 1 Register */ -#define I2S_TCR1_TFW_MASK (0x7U) -#define I2S_TCR1_TFW_SHIFT (0U) -#define I2S_TCR1_TFW(x) (((uint32_t)(((uint32_t)(x)) << I2S_TCR1_TFW_SHIFT)) & I2S_TCR1_TFW_MASK) - -/*! @name TCR2 - SAI Transmit Configuration 2 Register */ -#define I2S_TCR2_DIV_MASK (0xFFU) -#define I2S_TCR2_DIV_SHIFT (0U) -#define I2S_TCR2_DIV(x) (((uint32_t)(((uint32_t)(x)) << I2S_TCR2_DIV_SHIFT)) & I2S_TCR2_DIV_MASK) -#define I2S_TCR2_BCD_MASK (0x1000000U) -#define I2S_TCR2_BCD_SHIFT (24U) -#define I2S_TCR2_BCD(x) (((uint32_t)(((uint32_t)(x)) << I2S_TCR2_BCD_SHIFT)) & I2S_TCR2_BCD_MASK) -#define I2S_TCR2_BCP_MASK (0x2000000U) -#define I2S_TCR2_BCP_SHIFT (25U) -#define I2S_TCR2_BCP(x) (((uint32_t)(((uint32_t)(x)) << I2S_TCR2_BCP_SHIFT)) & I2S_TCR2_BCP_MASK) -#define I2S_TCR2_MSEL_MASK (0xC000000U) -#define I2S_TCR2_MSEL_SHIFT (26U) -#define I2S_TCR2_MSEL(x) (((uint32_t)(((uint32_t)(x)) << I2S_TCR2_MSEL_SHIFT)) & I2S_TCR2_MSEL_MASK) -#define I2S_TCR2_BCI_MASK (0x10000000U) -#define I2S_TCR2_BCI_SHIFT (28U) -#define I2S_TCR2_BCI(x) (((uint32_t)(((uint32_t)(x)) << I2S_TCR2_BCI_SHIFT)) & I2S_TCR2_BCI_MASK) -#define I2S_TCR2_BCS_MASK (0x20000000U) -#define I2S_TCR2_BCS_SHIFT (29U) -#define I2S_TCR2_BCS(x) (((uint32_t)(((uint32_t)(x)) << I2S_TCR2_BCS_SHIFT)) & I2S_TCR2_BCS_MASK) -#define I2S_TCR2_SYNC_MASK (0xC0000000U) -#define I2S_TCR2_SYNC_SHIFT (30U) -#define I2S_TCR2_SYNC(x) (((uint32_t)(((uint32_t)(x)) << I2S_TCR2_SYNC_SHIFT)) & I2S_TCR2_SYNC_MASK) - -/*! @name TCR3 - SAI Transmit Configuration 3 Register */ -#define I2S_TCR3_WDFL_MASK (0x1FU) -#define I2S_TCR3_WDFL_SHIFT (0U) -#define I2S_TCR3_WDFL(x) (((uint32_t)(((uint32_t)(x)) << I2S_TCR3_WDFL_SHIFT)) & I2S_TCR3_WDFL_MASK) -#define I2S_TCR3_TCE_MASK (0x30000U) -#define I2S_TCR3_TCE_SHIFT (16U) -#define I2S_TCR3_TCE(x) (((uint32_t)(((uint32_t)(x)) << I2S_TCR3_TCE_SHIFT)) & I2S_TCR3_TCE_MASK) - -/*! @name TCR4 - SAI Transmit Configuration 4 Register */ -#define I2S_TCR4_FSD_MASK (0x1U) -#define I2S_TCR4_FSD_SHIFT (0U) -#define I2S_TCR4_FSD(x) (((uint32_t)(((uint32_t)(x)) << I2S_TCR4_FSD_SHIFT)) & I2S_TCR4_FSD_MASK) -#define I2S_TCR4_FSP_MASK (0x2U) -#define I2S_TCR4_FSP_SHIFT (1U) -#define I2S_TCR4_FSP(x) (((uint32_t)(((uint32_t)(x)) << I2S_TCR4_FSP_SHIFT)) & I2S_TCR4_FSP_MASK) -#define I2S_TCR4_FSE_MASK (0x8U) -#define I2S_TCR4_FSE_SHIFT (3U) -#define I2S_TCR4_FSE(x) (((uint32_t)(((uint32_t)(x)) << I2S_TCR4_FSE_SHIFT)) & I2S_TCR4_FSE_MASK) -#define I2S_TCR4_MF_MASK (0x10U) -#define I2S_TCR4_MF_SHIFT (4U) -#define I2S_TCR4_MF(x) (((uint32_t)(((uint32_t)(x)) << I2S_TCR4_MF_SHIFT)) & I2S_TCR4_MF_MASK) -#define I2S_TCR4_SYWD_MASK (0x1F00U) -#define I2S_TCR4_SYWD_SHIFT (8U) -#define I2S_TCR4_SYWD(x) (((uint32_t)(((uint32_t)(x)) << I2S_TCR4_SYWD_SHIFT)) & I2S_TCR4_SYWD_MASK) -#define I2S_TCR4_FRSZ_MASK (0x1F0000U) -#define I2S_TCR4_FRSZ_SHIFT (16U) -#define I2S_TCR4_FRSZ(x) (((uint32_t)(((uint32_t)(x)) << I2S_TCR4_FRSZ_SHIFT)) & I2S_TCR4_FRSZ_MASK) - -/*! @name TCR5 - SAI Transmit Configuration 5 Register */ -#define I2S_TCR5_FBT_MASK (0x1F00U) -#define I2S_TCR5_FBT_SHIFT (8U) -#define I2S_TCR5_FBT(x) (((uint32_t)(((uint32_t)(x)) << I2S_TCR5_FBT_SHIFT)) & I2S_TCR5_FBT_MASK) -#define I2S_TCR5_W0W_MASK (0x1F0000U) -#define I2S_TCR5_W0W_SHIFT (16U) -#define I2S_TCR5_W0W(x) (((uint32_t)(((uint32_t)(x)) << I2S_TCR5_W0W_SHIFT)) & I2S_TCR5_W0W_MASK) -#define I2S_TCR5_WNW_MASK (0x1F000000U) -#define I2S_TCR5_WNW_SHIFT (24U) -#define I2S_TCR5_WNW(x) (((uint32_t)(((uint32_t)(x)) << I2S_TCR5_WNW_SHIFT)) & I2S_TCR5_WNW_MASK) - -/*! @name TDR - SAI Transmit Data Register */ -#define I2S_TDR_TDR_MASK (0xFFFFFFFFU) -#define I2S_TDR_TDR_SHIFT (0U) -#define I2S_TDR_TDR(x) (((uint32_t)(((uint32_t)(x)) << I2S_TDR_TDR_SHIFT)) & I2S_TDR_TDR_MASK) - -/* The count of I2S_TDR */ -#define I2S_TDR_COUNT (2U) - -/*! @name TFR - SAI Transmit FIFO Register */ -#define I2S_TFR_RFP_MASK (0xFU) -#define I2S_TFR_RFP_SHIFT (0U) -#define I2S_TFR_RFP(x) (((uint32_t)(((uint32_t)(x)) << I2S_TFR_RFP_SHIFT)) & I2S_TFR_RFP_MASK) -#define I2S_TFR_WFP_MASK (0xF0000U) -#define I2S_TFR_WFP_SHIFT (16U) -#define I2S_TFR_WFP(x) (((uint32_t)(((uint32_t)(x)) << I2S_TFR_WFP_SHIFT)) & I2S_TFR_WFP_MASK) - -/* The count of I2S_TFR */ -#define I2S_TFR_COUNT (2U) - -/*! @name TMR - SAI Transmit Mask Register */ -#define I2S_TMR_TWM_MASK (0xFFFFFFFFU) -#define I2S_TMR_TWM_SHIFT (0U) -#define I2S_TMR_TWM(x) (((uint32_t)(((uint32_t)(x)) << I2S_TMR_TWM_SHIFT)) & I2S_TMR_TWM_MASK) - -/*! @name RCSR - SAI Receive Control Register */ -#define I2S_RCSR_FRDE_MASK (0x1U) -#define I2S_RCSR_FRDE_SHIFT (0U) -#define I2S_RCSR_FRDE(x) (((uint32_t)(((uint32_t)(x)) << I2S_RCSR_FRDE_SHIFT)) & I2S_RCSR_FRDE_MASK) -#define I2S_RCSR_FWDE_MASK (0x2U) -#define I2S_RCSR_FWDE_SHIFT (1U) -#define I2S_RCSR_FWDE(x) (((uint32_t)(((uint32_t)(x)) << I2S_RCSR_FWDE_SHIFT)) & I2S_RCSR_FWDE_MASK) -#define I2S_RCSR_FRIE_MASK (0x100U) -#define I2S_RCSR_FRIE_SHIFT (8U) -#define I2S_RCSR_FRIE(x) (((uint32_t)(((uint32_t)(x)) << I2S_RCSR_FRIE_SHIFT)) & I2S_RCSR_FRIE_MASK) -#define I2S_RCSR_FWIE_MASK (0x200U) -#define I2S_RCSR_FWIE_SHIFT (9U) -#define I2S_RCSR_FWIE(x) (((uint32_t)(((uint32_t)(x)) << I2S_RCSR_FWIE_SHIFT)) & I2S_RCSR_FWIE_MASK) -#define I2S_RCSR_FEIE_MASK (0x400U) -#define I2S_RCSR_FEIE_SHIFT (10U) -#define I2S_RCSR_FEIE(x) (((uint32_t)(((uint32_t)(x)) << I2S_RCSR_FEIE_SHIFT)) & I2S_RCSR_FEIE_MASK) -#define I2S_RCSR_SEIE_MASK (0x800U) -#define I2S_RCSR_SEIE_SHIFT (11U) -#define I2S_RCSR_SEIE(x) (((uint32_t)(((uint32_t)(x)) << I2S_RCSR_SEIE_SHIFT)) & I2S_RCSR_SEIE_MASK) -#define I2S_RCSR_WSIE_MASK (0x1000U) -#define I2S_RCSR_WSIE_SHIFT (12U) -#define I2S_RCSR_WSIE(x) (((uint32_t)(((uint32_t)(x)) << I2S_RCSR_WSIE_SHIFT)) & I2S_RCSR_WSIE_MASK) -#define I2S_RCSR_FRF_MASK (0x10000U) -#define I2S_RCSR_FRF_SHIFT (16U) -#define I2S_RCSR_FRF(x) (((uint32_t)(((uint32_t)(x)) << I2S_RCSR_FRF_SHIFT)) & I2S_RCSR_FRF_MASK) -#define I2S_RCSR_FWF_MASK (0x20000U) -#define I2S_RCSR_FWF_SHIFT (17U) -#define I2S_RCSR_FWF(x) (((uint32_t)(((uint32_t)(x)) << I2S_RCSR_FWF_SHIFT)) & I2S_RCSR_FWF_MASK) -#define I2S_RCSR_FEF_MASK (0x40000U) -#define I2S_RCSR_FEF_SHIFT (18U) -#define I2S_RCSR_FEF(x) (((uint32_t)(((uint32_t)(x)) << I2S_RCSR_FEF_SHIFT)) & I2S_RCSR_FEF_MASK) -#define I2S_RCSR_SEF_MASK (0x80000U) -#define I2S_RCSR_SEF_SHIFT (19U) -#define I2S_RCSR_SEF(x) (((uint32_t)(((uint32_t)(x)) << I2S_RCSR_SEF_SHIFT)) & I2S_RCSR_SEF_MASK) -#define I2S_RCSR_WSF_MASK (0x100000U) -#define I2S_RCSR_WSF_SHIFT (20U) -#define I2S_RCSR_WSF(x) (((uint32_t)(((uint32_t)(x)) << I2S_RCSR_WSF_SHIFT)) & I2S_RCSR_WSF_MASK) -#define I2S_RCSR_SR_MASK (0x1000000U) -#define I2S_RCSR_SR_SHIFT (24U) -#define I2S_RCSR_SR(x) (((uint32_t)(((uint32_t)(x)) << I2S_RCSR_SR_SHIFT)) & I2S_RCSR_SR_MASK) -#define I2S_RCSR_FR_MASK (0x2000000U) -#define I2S_RCSR_FR_SHIFT (25U) -#define I2S_RCSR_FR(x) (((uint32_t)(((uint32_t)(x)) << I2S_RCSR_FR_SHIFT)) & I2S_RCSR_FR_MASK) -#define I2S_RCSR_BCE_MASK (0x10000000U) -#define I2S_RCSR_BCE_SHIFT (28U) -#define I2S_RCSR_BCE(x) (((uint32_t)(((uint32_t)(x)) << I2S_RCSR_BCE_SHIFT)) & I2S_RCSR_BCE_MASK) -#define I2S_RCSR_DBGE_MASK (0x20000000U) -#define I2S_RCSR_DBGE_SHIFT (29U) -#define I2S_RCSR_DBGE(x) (((uint32_t)(((uint32_t)(x)) << I2S_RCSR_DBGE_SHIFT)) & I2S_RCSR_DBGE_MASK) -#define I2S_RCSR_STOPE_MASK (0x40000000U) -#define I2S_RCSR_STOPE_SHIFT (30U) -#define I2S_RCSR_STOPE(x) (((uint32_t)(((uint32_t)(x)) << I2S_RCSR_STOPE_SHIFT)) & I2S_RCSR_STOPE_MASK) -#define I2S_RCSR_RE_MASK (0x80000000U) -#define I2S_RCSR_RE_SHIFT (31U) -#define I2S_RCSR_RE(x) (((uint32_t)(((uint32_t)(x)) << I2S_RCSR_RE_SHIFT)) & I2S_RCSR_RE_MASK) - -/*! @name RCR1 - SAI Receive Configuration 1 Register */ -#define I2S_RCR1_RFW_MASK (0x7U) -#define I2S_RCR1_RFW_SHIFT (0U) -#define I2S_RCR1_RFW(x) (((uint32_t)(((uint32_t)(x)) << I2S_RCR1_RFW_SHIFT)) & I2S_RCR1_RFW_MASK) - -/*! @name RCR2 - SAI Receive Configuration 2 Register */ -#define I2S_RCR2_DIV_MASK (0xFFU) -#define I2S_RCR2_DIV_SHIFT (0U) -#define I2S_RCR2_DIV(x) (((uint32_t)(((uint32_t)(x)) << I2S_RCR2_DIV_SHIFT)) & I2S_RCR2_DIV_MASK) -#define I2S_RCR2_BCD_MASK (0x1000000U) -#define I2S_RCR2_BCD_SHIFT (24U) -#define I2S_RCR2_BCD(x) (((uint32_t)(((uint32_t)(x)) << I2S_RCR2_BCD_SHIFT)) & I2S_RCR2_BCD_MASK) -#define I2S_RCR2_BCP_MASK (0x2000000U) -#define I2S_RCR2_BCP_SHIFT (25U) -#define I2S_RCR2_BCP(x) (((uint32_t)(((uint32_t)(x)) << I2S_RCR2_BCP_SHIFT)) & I2S_RCR2_BCP_MASK) -#define I2S_RCR2_MSEL_MASK (0xC000000U) -#define I2S_RCR2_MSEL_SHIFT (26U) -#define I2S_RCR2_MSEL(x) (((uint32_t)(((uint32_t)(x)) << I2S_RCR2_MSEL_SHIFT)) & I2S_RCR2_MSEL_MASK) -#define I2S_RCR2_BCI_MASK (0x10000000U) -#define I2S_RCR2_BCI_SHIFT (28U) -#define I2S_RCR2_BCI(x) (((uint32_t)(((uint32_t)(x)) << I2S_RCR2_BCI_SHIFT)) & I2S_RCR2_BCI_MASK) -#define I2S_RCR2_BCS_MASK (0x20000000U) -#define I2S_RCR2_BCS_SHIFT (29U) -#define I2S_RCR2_BCS(x) (((uint32_t)(((uint32_t)(x)) << I2S_RCR2_BCS_SHIFT)) & I2S_RCR2_BCS_MASK) -#define I2S_RCR2_SYNC_MASK (0xC0000000U) -#define I2S_RCR2_SYNC_SHIFT (30U) -#define I2S_RCR2_SYNC(x) (((uint32_t)(((uint32_t)(x)) << I2S_RCR2_SYNC_SHIFT)) & I2S_RCR2_SYNC_MASK) - -/*! @name RCR3 - SAI Receive Configuration 3 Register */ -#define I2S_RCR3_WDFL_MASK (0x1FU) -#define I2S_RCR3_WDFL_SHIFT (0U) -#define I2S_RCR3_WDFL(x) (((uint32_t)(((uint32_t)(x)) << I2S_RCR3_WDFL_SHIFT)) & I2S_RCR3_WDFL_MASK) -#define I2S_RCR3_RCE_MASK (0x30000U) -#define I2S_RCR3_RCE_SHIFT (16U) -#define I2S_RCR3_RCE(x) (((uint32_t)(((uint32_t)(x)) << I2S_RCR3_RCE_SHIFT)) & I2S_RCR3_RCE_MASK) - -/*! @name RCR4 - SAI Receive Configuration 4 Register */ -#define I2S_RCR4_FSD_MASK (0x1U) -#define I2S_RCR4_FSD_SHIFT (0U) -#define I2S_RCR4_FSD(x) (((uint32_t)(((uint32_t)(x)) << I2S_RCR4_FSD_SHIFT)) & I2S_RCR4_FSD_MASK) -#define I2S_RCR4_FSP_MASK (0x2U) -#define I2S_RCR4_FSP_SHIFT (1U) -#define I2S_RCR4_FSP(x) (((uint32_t)(((uint32_t)(x)) << I2S_RCR4_FSP_SHIFT)) & I2S_RCR4_FSP_MASK) -#define I2S_RCR4_FSE_MASK (0x8U) -#define I2S_RCR4_FSE_SHIFT (3U) -#define I2S_RCR4_FSE(x) (((uint32_t)(((uint32_t)(x)) << I2S_RCR4_FSE_SHIFT)) & I2S_RCR4_FSE_MASK) -#define I2S_RCR4_MF_MASK (0x10U) -#define I2S_RCR4_MF_SHIFT (4U) -#define I2S_RCR4_MF(x) (((uint32_t)(((uint32_t)(x)) << I2S_RCR4_MF_SHIFT)) & I2S_RCR4_MF_MASK) -#define I2S_RCR4_SYWD_MASK (0x1F00U) -#define I2S_RCR4_SYWD_SHIFT (8U) -#define I2S_RCR4_SYWD(x) (((uint32_t)(((uint32_t)(x)) << I2S_RCR4_SYWD_SHIFT)) & I2S_RCR4_SYWD_MASK) -#define I2S_RCR4_FRSZ_MASK (0x1F0000U) -#define I2S_RCR4_FRSZ_SHIFT (16U) -#define I2S_RCR4_FRSZ(x) (((uint32_t)(((uint32_t)(x)) << I2S_RCR4_FRSZ_SHIFT)) & I2S_RCR4_FRSZ_MASK) - -/*! @name RCR5 - SAI Receive Configuration 5 Register */ -#define I2S_RCR5_FBT_MASK (0x1F00U) -#define I2S_RCR5_FBT_SHIFT (8U) -#define I2S_RCR5_FBT(x) (((uint32_t)(((uint32_t)(x)) << I2S_RCR5_FBT_SHIFT)) & I2S_RCR5_FBT_MASK) -#define I2S_RCR5_W0W_MASK (0x1F0000U) -#define I2S_RCR5_W0W_SHIFT (16U) -#define I2S_RCR5_W0W(x) (((uint32_t)(((uint32_t)(x)) << I2S_RCR5_W0W_SHIFT)) & I2S_RCR5_W0W_MASK) -#define I2S_RCR5_WNW_MASK (0x1F000000U) -#define I2S_RCR5_WNW_SHIFT (24U) -#define I2S_RCR5_WNW(x) (((uint32_t)(((uint32_t)(x)) << I2S_RCR5_WNW_SHIFT)) & I2S_RCR5_WNW_MASK) - -/*! @name RDR - SAI Receive Data Register */ -#define I2S_RDR_RDR_MASK (0xFFFFFFFFU) -#define I2S_RDR_RDR_SHIFT (0U) -#define I2S_RDR_RDR(x) (((uint32_t)(((uint32_t)(x)) << I2S_RDR_RDR_SHIFT)) & I2S_RDR_RDR_MASK) - -/* The count of I2S_RDR */ -#define I2S_RDR_COUNT (2U) - -/*! @name RFR - SAI Receive FIFO Register */ -#define I2S_RFR_RFP_MASK (0xFU) -#define I2S_RFR_RFP_SHIFT (0U) -#define I2S_RFR_RFP(x) (((uint32_t)(((uint32_t)(x)) << I2S_RFR_RFP_SHIFT)) & I2S_RFR_RFP_MASK) -#define I2S_RFR_WFP_MASK (0xF0000U) -#define I2S_RFR_WFP_SHIFT (16U) -#define I2S_RFR_WFP(x) (((uint32_t)(((uint32_t)(x)) << I2S_RFR_WFP_SHIFT)) & I2S_RFR_WFP_MASK) - -/* The count of I2S_RFR */ -#define I2S_RFR_COUNT (2U) - -/*! @name RMR - SAI Receive Mask Register */ -#define I2S_RMR_RWM_MASK (0xFFFFFFFFU) -#define I2S_RMR_RWM_SHIFT (0U) -#define I2S_RMR_RWM(x) (((uint32_t)(((uint32_t)(x)) << I2S_RMR_RWM_SHIFT)) & I2S_RMR_RWM_MASK) - -/*! @name MCR - SAI MCLK Control Register */ -#define I2S_MCR_MICS_MASK (0x3000000U) -#define I2S_MCR_MICS_SHIFT (24U) -#define I2S_MCR_MICS(x) (((uint32_t)(((uint32_t)(x)) << I2S_MCR_MICS_SHIFT)) & I2S_MCR_MICS_MASK) -#define I2S_MCR_MOE_MASK (0x40000000U) -#define I2S_MCR_MOE_SHIFT (30U) -#define I2S_MCR_MOE(x) (((uint32_t)(((uint32_t)(x)) << I2S_MCR_MOE_SHIFT)) & I2S_MCR_MOE_MASK) -#define I2S_MCR_DUF_MASK (0x80000000U) -#define I2S_MCR_DUF_SHIFT (31U) -#define I2S_MCR_DUF(x) (((uint32_t)(((uint32_t)(x)) << I2S_MCR_DUF_SHIFT)) & I2S_MCR_DUF_MASK) - -/*! @name MDR - SAI MCLK Divide Register */ -#define I2S_MDR_DIVIDE_MASK (0xFFFU) -#define I2S_MDR_DIVIDE_SHIFT (0U) -#define I2S_MDR_DIVIDE(x) (((uint32_t)(((uint32_t)(x)) << I2S_MDR_DIVIDE_SHIFT)) & I2S_MDR_DIVIDE_MASK) -#define I2S_MDR_FRACT_MASK (0xFF000U) -#define I2S_MDR_FRACT_SHIFT (12U) -#define I2S_MDR_FRACT(x) (((uint32_t)(((uint32_t)(x)) << I2S_MDR_FRACT_SHIFT)) & I2S_MDR_FRACT_MASK) - - -/*! - * @} - */ /* end of group I2S_Register_Masks */ - - -/* I2S - Peripheral instance base addresses */ -/** Peripheral I2S0 base address */ -#define I2S0_BASE (0x4002F000u) -/** Peripheral I2S0 base pointer */ -#define I2S0 ((I2S_Type *)I2S0_BASE) -/** Array initializer of I2S peripheral base addresses */ -#define I2S_BASE_ADDRS { I2S0_BASE } -/** Array initializer of I2S peripheral base pointers */ -#define I2S_BASE_PTRS { I2S0 } -/** Interrupt vectors for the I2S peripheral type */ -#define I2S_RX_IRQS { I2S0_Rx_IRQn } -#define I2S_TX_IRQS { I2S0_Tx_IRQn } - -/*! - * @} - */ /* end of group I2S_Peripheral_Access_Layer */ - - -/* ---------------------------------------------------------------------------- - -- LLWU Peripheral Access Layer - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup LLWU_Peripheral_Access_Layer LLWU Peripheral Access Layer - * @{ - */ - -/** LLWU - Register Layout Typedef */ -typedef struct { - __IO uint8_t PE1; /**< LLWU Pin Enable 1 register, offset: 0x0 */ - __IO uint8_t PE2; /**< LLWU Pin Enable 2 register, offset: 0x1 */ - __IO uint8_t PE3; /**< LLWU Pin Enable 3 register, offset: 0x2 */ - __IO uint8_t PE4; /**< LLWU Pin Enable 4 register, offset: 0x3 */ - __IO uint8_t ME; /**< LLWU Module Enable register, offset: 0x4 */ - __IO uint8_t F1; /**< LLWU Flag 1 register, offset: 0x5 */ - __IO uint8_t F2; /**< LLWU Flag 2 register, offset: 0x6 */ - __I uint8_t F3; /**< LLWU Flag 3 register, offset: 0x7 */ - __IO uint8_t FILT1; /**< LLWU Pin Filter 1 register, offset: 0x8 */ - __IO uint8_t FILT2; /**< LLWU Pin Filter 2 register, offset: 0x9 */ - __IO uint8_t RST; /**< LLWU Reset Enable register, offset: 0xA */ -} LLWU_Type; - -/* ---------------------------------------------------------------------------- - -- LLWU Register Masks - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup LLWU_Register_Masks LLWU Register Masks - * @{ - */ - -/*! @name PE1 - LLWU Pin Enable 1 register */ -#define LLWU_PE1_WUPE0_MASK (0x3U) -#define LLWU_PE1_WUPE0_SHIFT (0U) -#define LLWU_PE1_WUPE0(x) (((uint8_t)(((uint8_t)(x)) << LLWU_PE1_WUPE0_SHIFT)) & LLWU_PE1_WUPE0_MASK) -#define LLWU_PE1_WUPE1_MASK (0xCU) -#define LLWU_PE1_WUPE1_SHIFT (2U) -#define LLWU_PE1_WUPE1(x) (((uint8_t)(((uint8_t)(x)) << LLWU_PE1_WUPE1_SHIFT)) & LLWU_PE1_WUPE1_MASK) -#define LLWU_PE1_WUPE2_MASK (0x30U) -#define LLWU_PE1_WUPE2_SHIFT (4U) -#define LLWU_PE1_WUPE2(x) (((uint8_t)(((uint8_t)(x)) << LLWU_PE1_WUPE2_SHIFT)) & LLWU_PE1_WUPE2_MASK) -#define LLWU_PE1_WUPE3_MASK (0xC0U) -#define LLWU_PE1_WUPE3_SHIFT (6U) -#define LLWU_PE1_WUPE3(x) (((uint8_t)(((uint8_t)(x)) << LLWU_PE1_WUPE3_SHIFT)) & LLWU_PE1_WUPE3_MASK) - -/*! @name PE2 - LLWU Pin Enable 2 register */ -#define LLWU_PE2_WUPE4_MASK (0x3U) -#define LLWU_PE2_WUPE4_SHIFT (0U) -#define LLWU_PE2_WUPE4(x) (((uint8_t)(((uint8_t)(x)) << LLWU_PE2_WUPE4_SHIFT)) & LLWU_PE2_WUPE4_MASK) -#define LLWU_PE2_WUPE5_MASK (0xCU) -#define LLWU_PE2_WUPE5_SHIFT (2U) -#define LLWU_PE2_WUPE5(x) (((uint8_t)(((uint8_t)(x)) << LLWU_PE2_WUPE5_SHIFT)) & LLWU_PE2_WUPE5_MASK) -#define LLWU_PE2_WUPE6_MASK (0x30U) -#define LLWU_PE2_WUPE6_SHIFT (4U) -#define LLWU_PE2_WUPE6(x) (((uint8_t)(((uint8_t)(x)) << LLWU_PE2_WUPE6_SHIFT)) & LLWU_PE2_WUPE6_MASK) -#define LLWU_PE2_WUPE7_MASK (0xC0U) -#define LLWU_PE2_WUPE7_SHIFT (6U) -#define LLWU_PE2_WUPE7(x) (((uint8_t)(((uint8_t)(x)) << LLWU_PE2_WUPE7_SHIFT)) & LLWU_PE2_WUPE7_MASK) - -/*! @name PE3 - LLWU Pin Enable 3 register */ -#define LLWU_PE3_WUPE8_MASK (0x3U) -#define LLWU_PE3_WUPE8_SHIFT (0U) -#define LLWU_PE3_WUPE8(x) (((uint8_t)(((uint8_t)(x)) << LLWU_PE3_WUPE8_SHIFT)) & LLWU_PE3_WUPE8_MASK) -#define LLWU_PE3_WUPE9_MASK (0xCU) -#define LLWU_PE3_WUPE9_SHIFT (2U) -#define LLWU_PE3_WUPE9(x) (((uint8_t)(((uint8_t)(x)) << LLWU_PE3_WUPE9_SHIFT)) & LLWU_PE3_WUPE9_MASK) -#define LLWU_PE3_WUPE10_MASK (0x30U) -#define LLWU_PE3_WUPE10_SHIFT (4U) -#define LLWU_PE3_WUPE10(x) (((uint8_t)(((uint8_t)(x)) << LLWU_PE3_WUPE10_SHIFT)) & LLWU_PE3_WUPE10_MASK) -#define LLWU_PE3_WUPE11_MASK (0xC0U) -#define LLWU_PE3_WUPE11_SHIFT (6U) -#define LLWU_PE3_WUPE11(x) (((uint8_t)(((uint8_t)(x)) << LLWU_PE3_WUPE11_SHIFT)) & LLWU_PE3_WUPE11_MASK) - -/*! @name PE4 - LLWU Pin Enable 4 register */ -#define LLWU_PE4_WUPE12_MASK (0x3U) -#define LLWU_PE4_WUPE12_SHIFT (0U) -#define LLWU_PE4_WUPE12(x) (((uint8_t)(((uint8_t)(x)) << LLWU_PE4_WUPE12_SHIFT)) & LLWU_PE4_WUPE12_MASK) -#define LLWU_PE4_WUPE13_MASK (0xCU) -#define LLWU_PE4_WUPE13_SHIFT (2U) -#define LLWU_PE4_WUPE13(x) (((uint8_t)(((uint8_t)(x)) << LLWU_PE4_WUPE13_SHIFT)) & LLWU_PE4_WUPE13_MASK) -#define LLWU_PE4_WUPE14_MASK (0x30U) -#define LLWU_PE4_WUPE14_SHIFT (4U) -#define LLWU_PE4_WUPE14(x) (((uint8_t)(((uint8_t)(x)) << LLWU_PE4_WUPE14_SHIFT)) & LLWU_PE4_WUPE14_MASK) -#define LLWU_PE4_WUPE15_MASK (0xC0U) -#define LLWU_PE4_WUPE15_SHIFT (6U) -#define LLWU_PE4_WUPE15(x) (((uint8_t)(((uint8_t)(x)) << LLWU_PE4_WUPE15_SHIFT)) & LLWU_PE4_WUPE15_MASK) - -/*! @name ME - LLWU Module Enable register */ -#define LLWU_ME_WUME0_MASK (0x1U) -#define LLWU_ME_WUME0_SHIFT (0U) -#define LLWU_ME_WUME0(x) (((uint8_t)(((uint8_t)(x)) << LLWU_ME_WUME0_SHIFT)) & LLWU_ME_WUME0_MASK) -#define LLWU_ME_WUME1_MASK (0x2U) -#define LLWU_ME_WUME1_SHIFT (1U) -#define LLWU_ME_WUME1(x) (((uint8_t)(((uint8_t)(x)) << LLWU_ME_WUME1_SHIFT)) & LLWU_ME_WUME1_MASK) -#define LLWU_ME_WUME2_MASK (0x4U) -#define LLWU_ME_WUME2_SHIFT (2U) -#define LLWU_ME_WUME2(x) (((uint8_t)(((uint8_t)(x)) << LLWU_ME_WUME2_SHIFT)) & LLWU_ME_WUME2_MASK) -#define LLWU_ME_WUME3_MASK (0x8U) -#define LLWU_ME_WUME3_SHIFT (3U) -#define LLWU_ME_WUME3(x) (((uint8_t)(((uint8_t)(x)) << LLWU_ME_WUME3_SHIFT)) & LLWU_ME_WUME3_MASK) -#define LLWU_ME_WUME4_MASK (0x10U) -#define LLWU_ME_WUME4_SHIFT (4U) -#define LLWU_ME_WUME4(x) (((uint8_t)(((uint8_t)(x)) << LLWU_ME_WUME4_SHIFT)) & LLWU_ME_WUME4_MASK) -#define LLWU_ME_WUME5_MASK (0x20U) -#define LLWU_ME_WUME5_SHIFT (5U) -#define LLWU_ME_WUME5(x) (((uint8_t)(((uint8_t)(x)) << LLWU_ME_WUME5_SHIFT)) & LLWU_ME_WUME5_MASK) -#define LLWU_ME_WUME6_MASK (0x40U) -#define LLWU_ME_WUME6_SHIFT (6U) -#define LLWU_ME_WUME6(x) (((uint8_t)(((uint8_t)(x)) << LLWU_ME_WUME6_SHIFT)) & LLWU_ME_WUME6_MASK) -#define LLWU_ME_WUME7_MASK (0x80U) -#define LLWU_ME_WUME7_SHIFT (7U) -#define LLWU_ME_WUME7(x) (((uint8_t)(((uint8_t)(x)) << LLWU_ME_WUME7_SHIFT)) & LLWU_ME_WUME7_MASK) - -/*! @name F1 - LLWU Flag 1 register */ -#define LLWU_F1_WUF0_MASK (0x1U) -#define LLWU_F1_WUF0_SHIFT (0U) -#define LLWU_F1_WUF0(x) (((uint8_t)(((uint8_t)(x)) << LLWU_F1_WUF0_SHIFT)) & LLWU_F1_WUF0_MASK) -#define LLWU_F1_WUF1_MASK (0x2U) -#define LLWU_F1_WUF1_SHIFT (1U) -#define LLWU_F1_WUF1(x) (((uint8_t)(((uint8_t)(x)) << LLWU_F1_WUF1_SHIFT)) & LLWU_F1_WUF1_MASK) -#define LLWU_F1_WUF2_MASK (0x4U) -#define LLWU_F1_WUF2_SHIFT (2U) -#define LLWU_F1_WUF2(x) (((uint8_t)(((uint8_t)(x)) << LLWU_F1_WUF2_SHIFT)) & LLWU_F1_WUF2_MASK) -#define LLWU_F1_WUF3_MASK (0x8U) -#define LLWU_F1_WUF3_SHIFT (3U) -#define LLWU_F1_WUF3(x) (((uint8_t)(((uint8_t)(x)) << LLWU_F1_WUF3_SHIFT)) & LLWU_F1_WUF3_MASK) -#define LLWU_F1_WUF4_MASK (0x10U) -#define LLWU_F1_WUF4_SHIFT (4U) -#define LLWU_F1_WUF4(x) (((uint8_t)(((uint8_t)(x)) << LLWU_F1_WUF4_SHIFT)) & LLWU_F1_WUF4_MASK) -#define LLWU_F1_WUF5_MASK (0x20U) -#define LLWU_F1_WUF5_SHIFT (5U) -#define LLWU_F1_WUF5(x) (((uint8_t)(((uint8_t)(x)) << LLWU_F1_WUF5_SHIFT)) & LLWU_F1_WUF5_MASK) -#define LLWU_F1_WUF6_MASK (0x40U) -#define LLWU_F1_WUF6_SHIFT (6U) -#define LLWU_F1_WUF6(x) (((uint8_t)(((uint8_t)(x)) << LLWU_F1_WUF6_SHIFT)) & LLWU_F1_WUF6_MASK) -#define LLWU_F1_WUF7_MASK (0x80U) -#define LLWU_F1_WUF7_SHIFT (7U) -#define LLWU_F1_WUF7(x) (((uint8_t)(((uint8_t)(x)) << LLWU_F1_WUF7_SHIFT)) & LLWU_F1_WUF7_MASK) - -/*! @name F2 - LLWU Flag 2 register */ -#define LLWU_F2_WUF8_MASK (0x1U) -#define LLWU_F2_WUF8_SHIFT (0U) -#define LLWU_F2_WUF8(x) (((uint8_t)(((uint8_t)(x)) << LLWU_F2_WUF8_SHIFT)) & LLWU_F2_WUF8_MASK) -#define LLWU_F2_WUF9_MASK (0x2U) -#define LLWU_F2_WUF9_SHIFT (1U) -#define LLWU_F2_WUF9(x) (((uint8_t)(((uint8_t)(x)) << LLWU_F2_WUF9_SHIFT)) & LLWU_F2_WUF9_MASK) -#define LLWU_F2_WUF10_MASK (0x4U) -#define LLWU_F2_WUF10_SHIFT (2U) -#define LLWU_F2_WUF10(x) (((uint8_t)(((uint8_t)(x)) << LLWU_F2_WUF10_SHIFT)) & LLWU_F2_WUF10_MASK) -#define LLWU_F2_WUF11_MASK (0x8U) -#define LLWU_F2_WUF11_SHIFT (3U) -#define LLWU_F2_WUF11(x) (((uint8_t)(((uint8_t)(x)) << LLWU_F2_WUF11_SHIFT)) & LLWU_F2_WUF11_MASK) -#define LLWU_F2_WUF12_MASK (0x10U) -#define LLWU_F2_WUF12_SHIFT (4U) -#define LLWU_F2_WUF12(x) (((uint8_t)(((uint8_t)(x)) << LLWU_F2_WUF12_SHIFT)) & LLWU_F2_WUF12_MASK) -#define LLWU_F2_WUF13_MASK (0x20U) -#define LLWU_F2_WUF13_SHIFT (5U) -#define LLWU_F2_WUF13(x) (((uint8_t)(((uint8_t)(x)) << LLWU_F2_WUF13_SHIFT)) & LLWU_F2_WUF13_MASK) -#define LLWU_F2_WUF14_MASK (0x40U) -#define LLWU_F2_WUF14_SHIFT (6U) -#define LLWU_F2_WUF14(x) (((uint8_t)(((uint8_t)(x)) << LLWU_F2_WUF14_SHIFT)) & LLWU_F2_WUF14_MASK) -#define LLWU_F2_WUF15_MASK (0x80U) -#define LLWU_F2_WUF15_SHIFT (7U) -#define LLWU_F2_WUF15(x) (((uint8_t)(((uint8_t)(x)) << LLWU_F2_WUF15_SHIFT)) & LLWU_F2_WUF15_MASK) - -/*! @name F3 - LLWU Flag 3 register */ -#define LLWU_F3_MWUF0_MASK (0x1U) -#define LLWU_F3_MWUF0_SHIFT (0U) -#define LLWU_F3_MWUF0(x) (((uint8_t)(((uint8_t)(x)) << LLWU_F3_MWUF0_SHIFT)) & LLWU_F3_MWUF0_MASK) -#define LLWU_F3_MWUF1_MASK (0x2U) -#define LLWU_F3_MWUF1_SHIFT (1U) -#define LLWU_F3_MWUF1(x) (((uint8_t)(((uint8_t)(x)) << LLWU_F3_MWUF1_SHIFT)) & LLWU_F3_MWUF1_MASK) -#define LLWU_F3_MWUF2_MASK (0x4U) -#define LLWU_F3_MWUF2_SHIFT (2U) -#define LLWU_F3_MWUF2(x) (((uint8_t)(((uint8_t)(x)) << LLWU_F3_MWUF2_SHIFT)) & LLWU_F3_MWUF2_MASK) -#define LLWU_F3_MWUF3_MASK (0x8U) -#define LLWU_F3_MWUF3_SHIFT (3U) -#define LLWU_F3_MWUF3(x) (((uint8_t)(((uint8_t)(x)) << LLWU_F3_MWUF3_SHIFT)) & LLWU_F3_MWUF3_MASK) -#define LLWU_F3_MWUF4_MASK (0x10U) -#define LLWU_F3_MWUF4_SHIFT (4U) -#define LLWU_F3_MWUF4(x) (((uint8_t)(((uint8_t)(x)) << LLWU_F3_MWUF4_SHIFT)) & LLWU_F3_MWUF4_MASK) -#define LLWU_F3_MWUF5_MASK (0x20U) -#define LLWU_F3_MWUF5_SHIFT (5U) -#define LLWU_F3_MWUF5(x) (((uint8_t)(((uint8_t)(x)) << LLWU_F3_MWUF5_SHIFT)) & LLWU_F3_MWUF5_MASK) -#define LLWU_F3_MWUF6_MASK (0x40U) -#define LLWU_F3_MWUF6_SHIFT (6U) -#define LLWU_F3_MWUF6(x) (((uint8_t)(((uint8_t)(x)) << LLWU_F3_MWUF6_SHIFT)) & LLWU_F3_MWUF6_MASK) -#define LLWU_F3_MWUF7_MASK (0x80U) -#define LLWU_F3_MWUF7_SHIFT (7U) -#define LLWU_F3_MWUF7(x) (((uint8_t)(((uint8_t)(x)) << LLWU_F3_MWUF7_SHIFT)) & LLWU_F3_MWUF7_MASK) - -/*! @name FILT1 - LLWU Pin Filter 1 register */ -#define LLWU_FILT1_FILTSEL_MASK (0xFU) -#define LLWU_FILT1_FILTSEL_SHIFT (0U) -#define LLWU_FILT1_FILTSEL(x) (((uint8_t)(((uint8_t)(x)) << LLWU_FILT1_FILTSEL_SHIFT)) & LLWU_FILT1_FILTSEL_MASK) -#define LLWU_FILT1_FILTE_MASK (0x60U) -#define LLWU_FILT1_FILTE_SHIFT (5U) -#define LLWU_FILT1_FILTE(x) (((uint8_t)(((uint8_t)(x)) << LLWU_FILT1_FILTE_SHIFT)) & LLWU_FILT1_FILTE_MASK) -#define LLWU_FILT1_FILTF_MASK (0x80U) -#define LLWU_FILT1_FILTF_SHIFT (7U) -#define LLWU_FILT1_FILTF(x) (((uint8_t)(((uint8_t)(x)) << LLWU_FILT1_FILTF_SHIFT)) & LLWU_FILT1_FILTF_MASK) - -/*! @name FILT2 - LLWU Pin Filter 2 register */ -#define LLWU_FILT2_FILTSEL_MASK (0xFU) -#define LLWU_FILT2_FILTSEL_SHIFT (0U) -#define LLWU_FILT2_FILTSEL(x) (((uint8_t)(((uint8_t)(x)) << LLWU_FILT2_FILTSEL_SHIFT)) & LLWU_FILT2_FILTSEL_MASK) -#define LLWU_FILT2_FILTE_MASK (0x60U) -#define LLWU_FILT2_FILTE_SHIFT (5U) -#define LLWU_FILT2_FILTE(x) (((uint8_t)(((uint8_t)(x)) << LLWU_FILT2_FILTE_SHIFT)) & LLWU_FILT2_FILTE_MASK) -#define LLWU_FILT2_FILTF_MASK (0x80U) -#define LLWU_FILT2_FILTF_SHIFT (7U) -#define LLWU_FILT2_FILTF(x) (((uint8_t)(((uint8_t)(x)) << LLWU_FILT2_FILTF_SHIFT)) & LLWU_FILT2_FILTF_MASK) - -/*! @name RST - LLWU Reset Enable register */ -#define LLWU_RST_RSTFILT_MASK (0x1U) -#define LLWU_RST_RSTFILT_SHIFT (0U) -#define LLWU_RST_RSTFILT(x) (((uint8_t)(((uint8_t)(x)) << LLWU_RST_RSTFILT_SHIFT)) & LLWU_RST_RSTFILT_MASK) -#define LLWU_RST_LLRSTE_MASK (0x2U) -#define LLWU_RST_LLRSTE_SHIFT (1U) -#define LLWU_RST_LLRSTE(x) (((uint8_t)(((uint8_t)(x)) << LLWU_RST_LLRSTE_SHIFT)) & LLWU_RST_LLRSTE_MASK) - - -/*! - * @} - */ /* end of group LLWU_Register_Masks */ - - -/* LLWU - Peripheral instance base addresses */ -/** Peripheral LLWU base address */ -#define LLWU_BASE (0x4007C000u) -/** Peripheral LLWU base pointer */ -#define LLWU ((LLWU_Type *)LLWU_BASE) -/** Array initializer of LLWU peripheral base addresses */ -#define LLWU_BASE_ADDRS { LLWU_BASE } -/** Array initializer of LLWU peripheral base pointers */ -#define LLWU_BASE_PTRS { LLWU } -/** Interrupt vectors for the LLWU peripheral type */ -#define LLWU_IRQS { LLWU_IRQn } - -/*! - * @} - */ /* end of group LLWU_Peripheral_Access_Layer */ - - -/* ---------------------------------------------------------------------------- - -- LPTMR Peripheral Access Layer - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup LPTMR_Peripheral_Access_Layer LPTMR Peripheral Access Layer - * @{ - */ - -/** LPTMR - Register Layout Typedef */ -typedef struct { - __IO uint32_t CSR; /**< Low Power Timer Control Status Register, offset: 0x0 */ - __IO uint32_t PSR; /**< Low Power Timer Prescale Register, offset: 0x4 */ - __IO uint32_t CMR; /**< Low Power Timer Compare Register, offset: 0x8 */ - __IO uint32_t CNR; /**< Low Power Timer Counter Register, offset: 0xC */ -} LPTMR_Type; - -/* ---------------------------------------------------------------------------- - -- LPTMR Register Masks - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup LPTMR_Register_Masks LPTMR Register Masks - * @{ - */ - -/*! @name CSR - Low Power Timer Control Status Register */ -#define LPTMR_CSR_TEN_MASK (0x1U) -#define LPTMR_CSR_TEN_SHIFT (0U) -#define LPTMR_CSR_TEN(x) (((uint32_t)(((uint32_t)(x)) << LPTMR_CSR_TEN_SHIFT)) & LPTMR_CSR_TEN_MASK) -#define LPTMR_CSR_TMS_MASK (0x2U) -#define LPTMR_CSR_TMS_SHIFT (1U) -#define LPTMR_CSR_TMS(x) (((uint32_t)(((uint32_t)(x)) << LPTMR_CSR_TMS_SHIFT)) & LPTMR_CSR_TMS_MASK) -#define LPTMR_CSR_TFC_MASK (0x4U) -#define LPTMR_CSR_TFC_SHIFT (2U) -#define LPTMR_CSR_TFC(x) (((uint32_t)(((uint32_t)(x)) << LPTMR_CSR_TFC_SHIFT)) & LPTMR_CSR_TFC_MASK) -#define LPTMR_CSR_TPP_MASK (0x8U) -#define LPTMR_CSR_TPP_SHIFT (3U) -#define LPTMR_CSR_TPP(x) (((uint32_t)(((uint32_t)(x)) << LPTMR_CSR_TPP_SHIFT)) & LPTMR_CSR_TPP_MASK) -#define LPTMR_CSR_TPS_MASK (0x30U) -#define LPTMR_CSR_TPS_SHIFT (4U) -#define LPTMR_CSR_TPS(x) (((uint32_t)(((uint32_t)(x)) << LPTMR_CSR_TPS_SHIFT)) & LPTMR_CSR_TPS_MASK) -#define LPTMR_CSR_TIE_MASK (0x40U) -#define LPTMR_CSR_TIE_SHIFT (6U) -#define LPTMR_CSR_TIE(x) (((uint32_t)(((uint32_t)(x)) << LPTMR_CSR_TIE_SHIFT)) & LPTMR_CSR_TIE_MASK) -#define LPTMR_CSR_TCF_MASK (0x80U) -#define LPTMR_CSR_TCF_SHIFT (7U) -#define LPTMR_CSR_TCF(x) (((uint32_t)(((uint32_t)(x)) << LPTMR_CSR_TCF_SHIFT)) & LPTMR_CSR_TCF_MASK) - -/*! @name PSR - Low Power Timer Prescale Register */ -#define LPTMR_PSR_PCS_MASK (0x3U) -#define LPTMR_PSR_PCS_SHIFT (0U) -#define LPTMR_PSR_PCS(x) (((uint32_t)(((uint32_t)(x)) << LPTMR_PSR_PCS_SHIFT)) & LPTMR_PSR_PCS_MASK) -#define LPTMR_PSR_PBYP_MASK (0x4U) -#define LPTMR_PSR_PBYP_SHIFT (2U) -#define LPTMR_PSR_PBYP(x) (((uint32_t)(((uint32_t)(x)) << LPTMR_PSR_PBYP_SHIFT)) & LPTMR_PSR_PBYP_MASK) -#define LPTMR_PSR_PRESCALE_MASK (0x78U) -#define LPTMR_PSR_PRESCALE_SHIFT (3U) -#define LPTMR_PSR_PRESCALE(x) (((uint32_t)(((uint32_t)(x)) << LPTMR_PSR_PRESCALE_SHIFT)) & LPTMR_PSR_PRESCALE_MASK) - -/*! @name CMR - Low Power Timer Compare Register */ -#define LPTMR_CMR_COMPARE_MASK (0xFFFFU) -#define LPTMR_CMR_COMPARE_SHIFT (0U) -#define LPTMR_CMR_COMPARE(x) (((uint32_t)(((uint32_t)(x)) << LPTMR_CMR_COMPARE_SHIFT)) & LPTMR_CMR_COMPARE_MASK) - -/*! @name CNR - Low Power Timer Counter Register */ -#define LPTMR_CNR_COUNTER_MASK (0xFFFFU) -#define LPTMR_CNR_COUNTER_SHIFT (0U) -#define LPTMR_CNR_COUNTER(x) (((uint32_t)(((uint32_t)(x)) << LPTMR_CNR_COUNTER_SHIFT)) & LPTMR_CNR_COUNTER_MASK) - - -/*! - * @} - */ /* end of group LPTMR_Register_Masks */ - - -/* LPTMR - Peripheral instance base addresses */ -/** Peripheral LPTMR0 base address */ -#define LPTMR0_BASE (0x40040000u) -/** Peripheral LPTMR0 base pointer */ -#define LPTMR0 ((LPTMR_Type *)LPTMR0_BASE) -/** Array initializer of LPTMR peripheral base addresses */ -#define LPTMR_BASE_ADDRS { LPTMR0_BASE } -/** Array initializer of LPTMR peripheral base pointers */ -#define LPTMR_BASE_PTRS { LPTMR0 } -/** Interrupt vectors for the LPTMR peripheral type */ -#define LPTMR_IRQS { LPTMR0_IRQn } - -/*! - * @} - */ /* end of group LPTMR_Peripheral_Access_Layer */ - - -/* ---------------------------------------------------------------------------- - -- MCG Peripheral Access Layer - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup MCG_Peripheral_Access_Layer MCG Peripheral Access Layer - * @{ - */ - -/** MCG - Register Layout Typedef */ -typedef struct { - __IO uint8_t C1; /**< MCG Control 1 Register, offset: 0x0 */ - __IO uint8_t C2; /**< MCG Control 2 Register, offset: 0x1 */ - __IO uint8_t C3; /**< MCG Control 3 Register, offset: 0x2 */ - __IO uint8_t C4; /**< MCG Control 4 Register, offset: 0x3 */ - __IO uint8_t C5; /**< MCG Control 5 Register, offset: 0x4 */ - __IO uint8_t C6; /**< MCG Control 6 Register, offset: 0x5 */ - __IO uint8_t S; /**< MCG Status Register, offset: 0x6 */ - uint8_t RESERVED_0[1]; - __IO uint8_t SC; /**< MCG Status and Control Register, offset: 0x8 */ - uint8_t RESERVED_1[1]; - __IO uint8_t ATCVH; /**< MCG Auto Trim Compare Value High Register, offset: 0xA */ - __IO uint8_t ATCVL; /**< MCG Auto Trim Compare Value Low Register, offset: 0xB */ - __IO uint8_t C7; /**< MCG Control 7 Register, offset: 0xC */ - __IO uint8_t C8; /**< MCG Control 8 Register, offset: 0xD */ -} MCG_Type; - -/* ---------------------------------------------------------------------------- - -- MCG Register Masks - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup MCG_Register_Masks MCG Register Masks - * @{ - */ - -/*! @name C1 - MCG Control 1 Register */ -#define MCG_C1_IREFSTEN_MASK (0x1U) -#define MCG_C1_IREFSTEN_SHIFT (0U) -#define MCG_C1_IREFSTEN(x) (((uint8_t)(((uint8_t)(x)) << MCG_C1_IREFSTEN_SHIFT)) & MCG_C1_IREFSTEN_MASK) -#define MCG_C1_IRCLKEN_MASK (0x2U) -#define MCG_C1_IRCLKEN_SHIFT (1U) -#define MCG_C1_IRCLKEN(x) (((uint8_t)(((uint8_t)(x)) << MCG_C1_IRCLKEN_SHIFT)) & MCG_C1_IRCLKEN_MASK) -#define MCG_C1_IREFS_MASK (0x4U) -#define MCG_C1_IREFS_SHIFT (2U) -#define MCG_C1_IREFS(x) (((uint8_t)(((uint8_t)(x)) << MCG_C1_IREFS_SHIFT)) & MCG_C1_IREFS_MASK) -#define MCG_C1_FRDIV_MASK (0x38U) -#define MCG_C1_FRDIV_SHIFT (3U) -#define MCG_C1_FRDIV(x) (((uint8_t)(((uint8_t)(x)) << MCG_C1_FRDIV_SHIFT)) & MCG_C1_FRDIV_MASK) -#define MCG_C1_CLKS_MASK (0xC0U) -#define MCG_C1_CLKS_SHIFT (6U) -#define MCG_C1_CLKS(x) (((uint8_t)(((uint8_t)(x)) << MCG_C1_CLKS_SHIFT)) & MCG_C1_CLKS_MASK) - -/*! @name C2 - MCG Control 2 Register */ -#define MCG_C2_IRCS_MASK (0x1U) -#define MCG_C2_IRCS_SHIFT (0U) -#define MCG_C2_IRCS(x) (((uint8_t)(((uint8_t)(x)) << MCG_C2_IRCS_SHIFT)) & MCG_C2_IRCS_MASK) -#define MCG_C2_LP_MASK (0x2U) -#define MCG_C2_LP_SHIFT (1U) -#define MCG_C2_LP(x) (((uint8_t)(((uint8_t)(x)) << MCG_C2_LP_SHIFT)) & MCG_C2_LP_MASK) -#define MCG_C2_EREFS_MASK (0x4U) -#define MCG_C2_EREFS_SHIFT (2U) -#define MCG_C2_EREFS(x) (((uint8_t)(((uint8_t)(x)) << MCG_C2_EREFS_SHIFT)) & MCG_C2_EREFS_MASK) -#define MCG_C2_HGO_MASK (0x8U) -#define MCG_C2_HGO_SHIFT (3U) -#define MCG_C2_HGO(x) (((uint8_t)(((uint8_t)(x)) << MCG_C2_HGO_SHIFT)) & MCG_C2_HGO_MASK) -#define MCG_C2_RANGE_MASK (0x30U) -#define MCG_C2_RANGE_SHIFT (4U) -#define MCG_C2_RANGE(x) (((uint8_t)(((uint8_t)(x)) << MCG_C2_RANGE_SHIFT)) & MCG_C2_RANGE_MASK) -#define MCG_C2_FCFTRIM_MASK (0x40U) -#define MCG_C2_FCFTRIM_SHIFT (6U) -#define MCG_C2_FCFTRIM(x) (((uint8_t)(((uint8_t)(x)) << MCG_C2_FCFTRIM_SHIFT)) & MCG_C2_FCFTRIM_MASK) -#define MCG_C2_LOCRE0_MASK (0x80U) -#define MCG_C2_LOCRE0_SHIFT (7U) -#define MCG_C2_LOCRE0(x) (((uint8_t)(((uint8_t)(x)) << MCG_C2_LOCRE0_SHIFT)) & MCG_C2_LOCRE0_MASK) - -/*! @name C3 - MCG Control 3 Register */ -#define MCG_C3_SCTRIM_MASK (0xFFU) -#define MCG_C3_SCTRIM_SHIFT (0U) -#define MCG_C3_SCTRIM(x) (((uint8_t)(((uint8_t)(x)) << MCG_C3_SCTRIM_SHIFT)) & MCG_C3_SCTRIM_MASK) - -/*! @name C4 - MCG Control 4 Register */ -#define MCG_C4_SCFTRIM_MASK (0x1U) -#define MCG_C4_SCFTRIM_SHIFT (0U) -#define MCG_C4_SCFTRIM(x) (((uint8_t)(((uint8_t)(x)) << MCG_C4_SCFTRIM_SHIFT)) & MCG_C4_SCFTRIM_MASK) -#define MCG_C4_FCTRIM_MASK (0x1EU) -#define MCG_C4_FCTRIM_SHIFT (1U) -#define MCG_C4_FCTRIM(x) (((uint8_t)(((uint8_t)(x)) << MCG_C4_FCTRIM_SHIFT)) & MCG_C4_FCTRIM_MASK) -#define MCG_C4_DRST_DRS_MASK (0x60U) -#define MCG_C4_DRST_DRS_SHIFT (5U) -#define MCG_C4_DRST_DRS(x) (((uint8_t)(((uint8_t)(x)) << MCG_C4_DRST_DRS_SHIFT)) & MCG_C4_DRST_DRS_MASK) -#define MCG_C4_DMX32_MASK (0x80U) -#define MCG_C4_DMX32_SHIFT (7U) -#define MCG_C4_DMX32(x) (((uint8_t)(((uint8_t)(x)) << MCG_C4_DMX32_SHIFT)) & MCG_C4_DMX32_MASK) - -/*! @name C5 - MCG Control 5 Register */ -#define MCG_C5_PRDIV0_MASK (0x1FU) -#define MCG_C5_PRDIV0_SHIFT (0U) -#define MCG_C5_PRDIV0(x) (((uint8_t)(((uint8_t)(x)) << MCG_C5_PRDIV0_SHIFT)) & MCG_C5_PRDIV0_MASK) -#define MCG_C5_PLLSTEN0_MASK (0x20U) -#define MCG_C5_PLLSTEN0_SHIFT (5U) -#define MCG_C5_PLLSTEN0(x) (((uint8_t)(((uint8_t)(x)) << MCG_C5_PLLSTEN0_SHIFT)) & MCG_C5_PLLSTEN0_MASK) -#define MCG_C5_PLLCLKEN0_MASK (0x40U) -#define MCG_C5_PLLCLKEN0_SHIFT (6U) -#define MCG_C5_PLLCLKEN0(x) (((uint8_t)(((uint8_t)(x)) << MCG_C5_PLLCLKEN0_SHIFT)) & MCG_C5_PLLCLKEN0_MASK) - -/*! @name C6 - MCG Control 6 Register */ -#define MCG_C6_VDIV0_MASK (0x1FU) -#define MCG_C6_VDIV0_SHIFT (0U) -#define MCG_C6_VDIV0(x) (((uint8_t)(((uint8_t)(x)) << MCG_C6_VDIV0_SHIFT)) & MCG_C6_VDIV0_MASK) -#define MCG_C6_CME0_MASK (0x20U) -#define MCG_C6_CME0_SHIFT (5U) -#define MCG_C6_CME0(x) (((uint8_t)(((uint8_t)(x)) << MCG_C6_CME0_SHIFT)) & MCG_C6_CME0_MASK) -#define MCG_C6_PLLS_MASK (0x40U) -#define MCG_C6_PLLS_SHIFT (6U) -#define MCG_C6_PLLS(x) (((uint8_t)(((uint8_t)(x)) << MCG_C6_PLLS_SHIFT)) & MCG_C6_PLLS_MASK) -#define MCG_C6_LOLIE0_MASK (0x80U) -#define MCG_C6_LOLIE0_SHIFT (7U) -#define MCG_C6_LOLIE0(x) (((uint8_t)(((uint8_t)(x)) << MCG_C6_LOLIE0_SHIFT)) & MCG_C6_LOLIE0_MASK) - -/*! @name S - MCG Status Register */ -#define MCG_S_IRCST_MASK (0x1U) -#define MCG_S_IRCST_SHIFT (0U) -#define MCG_S_IRCST(x) (((uint8_t)(((uint8_t)(x)) << MCG_S_IRCST_SHIFT)) & MCG_S_IRCST_MASK) -#define MCG_S_OSCINIT0_MASK (0x2U) -#define MCG_S_OSCINIT0_SHIFT (1U) -#define MCG_S_OSCINIT0(x) (((uint8_t)(((uint8_t)(x)) << MCG_S_OSCINIT0_SHIFT)) & MCG_S_OSCINIT0_MASK) -#define MCG_S_CLKST_MASK (0xCU) -#define MCG_S_CLKST_SHIFT (2U) -#define MCG_S_CLKST(x) (((uint8_t)(((uint8_t)(x)) << MCG_S_CLKST_SHIFT)) & MCG_S_CLKST_MASK) -#define MCG_S_IREFST_MASK (0x10U) -#define MCG_S_IREFST_SHIFT (4U) -#define MCG_S_IREFST(x) (((uint8_t)(((uint8_t)(x)) << MCG_S_IREFST_SHIFT)) & MCG_S_IREFST_MASK) -#define MCG_S_PLLST_MASK (0x20U) -#define MCG_S_PLLST_SHIFT (5U) -#define MCG_S_PLLST(x) (((uint8_t)(((uint8_t)(x)) << MCG_S_PLLST_SHIFT)) & MCG_S_PLLST_MASK) -#define MCG_S_LOCK0_MASK (0x40U) -#define MCG_S_LOCK0_SHIFT (6U) -#define MCG_S_LOCK0(x) (((uint8_t)(((uint8_t)(x)) << MCG_S_LOCK0_SHIFT)) & MCG_S_LOCK0_MASK) -#define MCG_S_LOLS0_MASK (0x80U) -#define MCG_S_LOLS0_SHIFT (7U) -#define MCG_S_LOLS0(x) (((uint8_t)(((uint8_t)(x)) << MCG_S_LOLS0_SHIFT)) & MCG_S_LOLS0_MASK) - -/*! @name SC - MCG Status and Control Register */ -#define MCG_SC_LOCS0_MASK (0x1U) -#define MCG_SC_LOCS0_SHIFT (0U) -#define MCG_SC_LOCS0(x) (((uint8_t)(((uint8_t)(x)) << MCG_SC_LOCS0_SHIFT)) & MCG_SC_LOCS0_MASK) -#define MCG_SC_FCRDIV_MASK (0xEU) -#define MCG_SC_FCRDIV_SHIFT (1U) -#define MCG_SC_FCRDIV(x) (((uint8_t)(((uint8_t)(x)) << MCG_SC_FCRDIV_SHIFT)) & MCG_SC_FCRDIV_MASK) -#define MCG_SC_FLTPRSRV_MASK (0x10U) -#define MCG_SC_FLTPRSRV_SHIFT (4U) -#define MCG_SC_FLTPRSRV(x) (((uint8_t)(((uint8_t)(x)) << MCG_SC_FLTPRSRV_SHIFT)) & MCG_SC_FLTPRSRV_MASK) -#define MCG_SC_ATMF_MASK (0x20U) -#define MCG_SC_ATMF_SHIFT (5U) -#define MCG_SC_ATMF(x) (((uint8_t)(((uint8_t)(x)) << MCG_SC_ATMF_SHIFT)) & MCG_SC_ATMF_MASK) -#define MCG_SC_ATMS_MASK (0x40U) -#define MCG_SC_ATMS_SHIFT (6U) -#define MCG_SC_ATMS(x) (((uint8_t)(((uint8_t)(x)) << MCG_SC_ATMS_SHIFT)) & MCG_SC_ATMS_MASK) -#define MCG_SC_ATME_MASK (0x80U) -#define MCG_SC_ATME_SHIFT (7U) -#define MCG_SC_ATME(x) (((uint8_t)(((uint8_t)(x)) << MCG_SC_ATME_SHIFT)) & MCG_SC_ATME_MASK) - -/*! @name ATCVH - MCG Auto Trim Compare Value High Register */ -#define MCG_ATCVH_ATCVH_MASK (0xFFU) -#define MCG_ATCVH_ATCVH_SHIFT (0U) -#define MCG_ATCVH_ATCVH(x) (((uint8_t)(((uint8_t)(x)) << MCG_ATCVH_ATCVH_SHIFT)) & MCG_ATCVH_ATCVH_MASK) - -/*! @name ATCVL - MCG Auto Trim Compare Value Low Register */ -#define MCG_ATCVL_ATCVL_MASK (0xFFU) -#define MCG_ATCVL_ATCVL_SHIFT (0U) -#define MCG_ATCVL_ATCVL(x) (((uint8_t)(((uint8_t)(x)) << MCG_ATCVL_ATCVL_SHIFT)) & MCG_ATCVL_ATCVL_MASK) - -/*! @name C7 - MCG Control 7 Register */ -#define MCG_C7_OSCSEL_MASK (0x3U) -#define MCG_C7_OSCSEL_SHIFT (0U) -#define MCG_C7_OSCSEL(x) (((uint8_t)(((uint8_t)(x)) << MCG_C7_OSCSEL_SHIFT)) & MCG_C7_OSCSEL_MASK) - -/*! @name C8 - MCG Control 8 Register */ -#define MCG_C8_LOCS1_MASK (0x1U) -#define MCG_C8_LOCS1_SHIFT (0U) -#define MCG_C8_LOCS1(x) (((uint8_t)(((uint8_t)(x)) << MCG_C8_LOCS1_SHIFT)) & MCG_C8_LOCS1_MASK) -#define MCG_C8_CME1_MASK (0x20U) -#define MCG_C8_CME1_SHIFT (5U) -#define MCG_C8_CME1(x) (((uint8_t)(((uint8_t)(x)) << MCG_C8_CME1_SHIFT)) & MCG_C8_CME1_MASK) -#define MCG_C8_LOLRE_MASK (0x40U) -#define MCG_C8_LOLRE_SHIFT (6U) -#define MCG_C8_LOLRE(x) (((uint8_t)(((uint8_t)(x)) << MCG_C8_LOLRE_SHIFT)) & MCG_C8_LOLRE_MASK) -#define MCG_C8_LOCRE1_MASK (0x80U) -#define MCG_C8_LOCRE1_SHIFT (7U) -#define MCG_C8_LOCRE1(x) (((uint8_t)(((uint8_t)(x)) << MCG_C8_LOCRE1_SHIFT)) & MCG_C8_LOCRE1_MASK) - - -/*! - * @} - */ /* end of group MCG_Register_Masks */ - - -/* MCG - Peripheral instance base addresses */ -/** Peripheral MCG base address */ -#define MCG_BASE (0x40064000u) -/** Peripheral MCG base pointer */ -#define MCG ((MCG_Type *)MCG_BASE) -/** Array initializer of MCG peripheral base addresses */ -#define MCG_BASE_ADDRS { MCG_BASE } -/** Array initializer of MCG peripheral base pointers */ -#define MCG_BASE_PTRS { MCG } - -/*! - * @} - */ /* end of group MCG_Peripheral_Access_Layer */ - - -/* ---------------------------------------------------------------------------- - -- MCM Peripheral Access Layer - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup MCM_Peripheral_Access_Layer MCM Peripheral Access Layer - * @{ - */ - -/** MCM - Register Layout Typedef */ -typedef struct { - uint8_t RESERVED_0[8]; - __I uint16_t PLASC; /**< Crossbar Switch (AXBS) Slave Configuration, offset: 0x8 */ - __I uint16_t PLAMC; /**< Crossbar Switch (AXBS) Master Configuration, offset: 0xA */ - __IO uint32_t CR; /**< Control Register, offset: 0xC */ - __IO uint32_t ISCR; /**< Interrupt Status Register, offset: 0x10 */ - __IO uint32_t ETBCC; /**< ETB Counter Control register, offset: 0x14 */ - __IO uint32_t ETBRL; /**< ETB Reload register, offset: 0x18 */ - __I uint32_t ETBCNT; /**< ETB Counter Value register, offset: 0x1C */ - uint8_t RESERVED_1[16]; - __IO uint32_t PID; /**< Process ID register, offset: 0x30 */ -} MCM_Type; - -/* ---------------------------------------------------------------------------- - -- MCM Register Masks - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup MCM_Register_Masks MCM Register Masks - * @{ - */ - -/*! @name PLASC - Crossbar Switch (AXBS) Slave Configuration */ -#define MCM_PLASC_ASC_MASK (0xFFU) -#define MCM_PLASC_ASC_SHIFT (0U) -#define MCM_PLASC_ASC(x) (((uint16_t)(((uint16_t)(x)) << MCM_PLASC_ASC_SHIFT)) & MCM_PLASC_ASC_MASK) - -/*! @name PLAMC - Crossbar Switch (AXBS) Master Configuration */ -#define MCM_PLAMC_AMC_MASK (0xFFU) -#define MCM_PLAMC_AMC_SHIFT (0U) -#define MCM_PLAMC_AMC(x) (((uint16_t)(((uint16_t)(x)) << MCM_PLAMC_AMC_SHIFT)) & MCM_PLAMC_AMC_MASK) - -/*! @name CR - Control Register */ -#define MCM_CR_SRAMUAP_MASK (0x3000000U) -#define MCM_CR_SRAMUAP_SHIFT (24U) -#define MCM_CR_SRAMUAP(x) (((uint32_t)(((uint32_t)(x)) << MCM_CR_SRAMUAP_SHIFT)) & MCM_CR_SRAMUAP_MASK) -#define MCM_CR_SRAMUWP_MASK (0x4000000U) -#define MCM_CR_SRAMUWP_SHIFT (26U) -#define MCM_CR_SRAMUWP(x) (((uint32_t)(((uint32_t)(x)) << MCM_CR_SRAMUWP_SHIFT)) & MCM_CR_SRAMUWP_MASK) -#define MCM_CR_SRAMLAP_MASK (0x30000000U) -#define MCM_CR_SRAMLAP_SHIFT (28U) -#define MCM_CR_SRAMLAP(x) (((uint32_t)(((uint32_t)(x)) << MCM_CR_SRAMLAP_SHIFT)) & MCM_CR_SRAMLAP_MASK) -#define MCM_CR_SRAMLWP_MASK (0x40000000U) -#define MCM_CR_SRAMLWP_SHIFT (30U) -#define MCM_CR_SRAMLWP(x) (((uint32_t)(((uint32_t)(x)) << MCM_CR_SRAMLWP_SHIFT)) & MCM_CR_SRAMLWP_MASK) - -/*! @name ISCR - Interrupt Status Register */ -#define MCM_ISCR_IRQ_MASK (0x2U) -#define MCM_ISCR_IRQ_SHIFT (1U) -#define MCM_ISCR_IRQ(x) (((uint32_t)(((uint32_t)(x)) << MCM_ISCR_IRQ_SHIFT)) & MCM_ISCR_IRQ_MASK) -#define MCM_ISCR_NMI_MASK (0x4U) -#define MCM_ISCR_NMI_SHIFT (2U) -#define MCM_ISCR_NMI(x) (((uint32_t)(((uint32_t)(x)) << MCM_ISCR_NMI_SHIFT)) & MCM_ISCR_NMI_MASK) -#define MCM_ISCR_DHREQ_MASK (0x8U) -#define MCM_ISCR_DHREQ_SHIFT (3U) -#define MCM_ISCR_DHREQ(x) (((uint32_t)(((uint32_t)(x)) << MCM_ISCR_DHREQ_SHIFT)) & MCM_ISCR_DHREQ_MASK) -#define MCM_ISCR_FIOC_MASK (0x100U) -#define MCM_ISCR_FIOC_SHIFT (8U) -#define MCM_ISCR_FIOC(x) (((uint32_t)(((uint32_t)(x)) << MCM_ISCR_FIOC_SHIFT)) & MCM_ISCR_FIOC_MASK) -#define MCM_ISCR_FDZC_MASK (0x200U) -#define MCM_ISCR_FDZC_SHIFT (9U) -#define MCM_ISCR_FDZC(x) (((uint32_t)(((uint32_t)(x)) << MCM_ISCR_FDZC_SHIFT)) & MCM_ISCR_FDZC_MASK) -#define MCM_ISCR_FOFC_MASK (0x400U) -#define MCM_ISCR_FOFC_SHIFT (10U) -#define MCM_ISCR_FOFC(x) (((uint32_t)(((uint32_t)(x)) << MCM_ISCR_FOFC_SHIFT)) & MCM_ISCR_FOFC_MASK) -#define MCM_ISCR_FUFC_MASK (0x800U) -#define MCM_ISCR_FUFC_SHIFT (11U) -#define MCM_ISCR_FUFC(x) (((uint32_t)(((uint32_t)(x)) << MCM_ISCR_FUFC_SHIFT)) & MCM_ISCR_FUFC_MASK) -#define MCM_ISCR_FIXC_MASK (0x1000U) -#define MCM_ISCR_FIXC_SHIFT (12U) -#define MCM_ISCR_FIXC(x) (((uint32_t)(((uint32_t)(x)) << MCM_ISCR_FIXC_SHIFT)) & MCM_ISCR_FIXC_MASK) -#define MCM_ISCR_FIDC_MASK (0x8000U) -#define MCM_ISCR_FIDC_SHIFT (15U) -#define MCM_ISCR_FIDC(x) (((uint32_t)(((uint32_t)(x)) << MCM_ISCR_FIDC_SHIFT)) & MCM_ISCR_FIDC_MASK) -#define MCM_ISCR_FIOCE_MASK (0x1000000U) -#define MCM_ISCR_FIOCE_SHIFT (24U) -#define MCM_ISCR_FIOCE(x) (((uint32_t)(((uint32_t)(x)) << MCM_ISCR_FIOCE_SHIFT)) & MCM_ISCR_FIOCE_MASK) -#define MCM_ISCR_FDZCE_MASK (0x2000000U) -#define MCM_ISCR_FDZCE_SHIFT (25U) -#define MCM_ISCR_FDZCE(x) (((uint32_t)(((uint32_t)(x)) << MCM_ISCR_FDZCE_SHIFT)) & MCM_ISCR_FDZCE_MASK) -#define MCM_ISCR_FOFCE_MASK (0x4000000U) -#define MCM_ISCR_FOFCE_SHIFT (26U) -#define MCM_ISCR_FOFCE(x) (((uint32_t)(((uint32_t)(x)) << MCM_ISCR_FOFCE_SHIFT)) & MCM_ISCR_FOFCE_MASK) -#define MCM_ISCR_FUFCE_MASK (0x8000000U) -#define MCM_ISCR_FUFCE_SHIFT (27U) -#define MCM_ISCR_FUFCE(x) (((uint32_t)(((uint32_t)(x)) << MCM_ISCR_FUFCE_SHIFT)) & MCM_ISCR_FUFCE_MASK) -#define MCM_ISCR_FIXCE_MASK (0x10000000U) -#define MCM_ISCR_FIXCE_SHIFT (28U) -#define MCM_ISCR_FIXCE(x) (((uint32_t)(((uint32_t)(x)) << MCM_ISCR_FIXCE_SHIFT)) & MCM_ISCR_FIXCE_MASK) -#define MCM_ISCR_FIDCE_MASK (0x80000000U) -#define MCM_ISCR_FIDCE_SHIFT (31U) -#define MCM_ISCR_FIDCE(x) (((uint32_t)(((uint32_t)(x)) << MCM_ISCR_FIDCE_SHIFT)) & MCM_ISCR_FIDCE_MASK) - -/*! @name ETBCC - ETB Counter Control register */ -#define MCM_ETBCC_CNTEN_MASK (0x1U) -#define MCM_ETBCC_CNTEN_SHIFT (0U) -#define MCM_ETBCC_CNTEN(x) (((uint32_t)(((uint32_t)(x)) << MCM_ETBCC_CNTEN_SHIFT)) & MCM_ETBCC_CNTEN_MASK) -#define MCM_ETBCC_RSPT_MASK (0x6U) -#define MCM_ETBCC_RSPT_SHIFT (1U) -#define MCM_ETBCC_RSPT(x) (((uint32_t)(((uint32_t)(x)) << MCM_ETBCC_RSPT_SHIFT)) & MCM_ETBCC_RSPT_MASK) -#define MCM_ETBCC_RLRQ_MASK (0x8U) -#define MCM_ETBCC_RLRQ_SHIFT (3U) -#define MCM_ETBCC_RLRQ(x) (((uint32_t)(((uint32_t)(x)) << MCM_ETBCC_RLRQ_SHIFT)) & MCM_ETBCC_RLRQ_MASK) -#define MCM_ETBCC_ETDIS_MASK (0x10U) -#define MCM_ETBCC_ETDIS_SHIFT (4U) -#define MCM_ETBCC_ETDIS(x) (((uint32_t)(((uint32_t)(x)) << MCM_ETBCC_ETDIS_SHIFT)) & MCM_ETBCC_ETDIS_MASK) -#define MCM_ETBCC_ITDIS_MASK (0x20U) -#define MCM_ETBCC_ITDIS_SHIFT (5U) -#define MCM_ETBCC_ITDIS(x) (((uint32_t)(((uint32_t)(x)) << MCM_ETBCC_ITDIS_SHIFT)) & MCM_ETBCC_ITDIS_MASK) - -/*! @name ETBRL - ETB Reload register */ -#define MCM_ETBRL_RELOAD_MASK (0x7FFU) -#define MCM_ETBRL_RELOAD_SHIFT (0U) -#define MCM_ETBRL_RELOAD(x) (((uint32_t)(((uint32_t)(x)) << MCM_ETBRL_RELOAD_SHIFT)) & MCM_ETBRL_RELOAD_MASK) - -/*! @name ETBCNT - ETB Counter Value register */ -#define MCM_ETBCNT_COUNTER_MASK (0x7FFU) -#define MCM_ETBCNT_COUNTER_SHIFT (0U) -#define MCM_ETBCNT_COUNTER(x) (((uint32_t)(((uint32_t)(x)) << MCM_ETBCNT_COUNTER_SHIFT)) & MCM_ETBCNT_COUNTER_MASK) - -/*! @name PID - Process ID register */ -#define MCM_PID_PID_MASK (0xFFU) -#define MCM_PID_PID_SHIFT (0U) -#define MCM_PID_PID(x) (((uint32_t)(((uint32_t)(x)) << MCM_PID_PID_SHIFT)) & MCM_PID_PID_MASK) - - -/*! - * @} - */ /* end of group MCM_Register_Masks */ - - -/* MCM - Peripheral instance base addresses */ -/** Peripheral MCM base address */ -#define MCM_BASE (0xE0080000u) -/** Peripheral MCM base pointer */ -#define MCM ((MCM_Type *)MCM_BASE) -/** Array initializer of MCM peripheral base addresses */ -#define MCM_BASE_ADDRS { MCM_BASE } -/** Array initializer of MCM peripheral base pointers */ -#define MCM_BASE_PTRS { MCM } -/** Interrupt vectors for the MCM peripheral type */ -#define MCM_IRQS { MCM_IRQn } - -/*! - * @} - */ /* end of group MCM_Peripheral_Access_Layer */ - - -/* ---------------------------------------------------------------------------- - -- NV Peripheral Access Layer - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup NV_Peripheral_Access_Layer NV Peripheral Access Layer - * @{ - */ - -/** NV - Register Layout Typedef */ -typedef struct { - __I uint8_t BACKKEY3; /**< Backdoor Comparison Key 3., offset: 0x0 */ - __I uint8_t BACKKEY2; /**< Backdoor Comparison Key 2., offset: 0x1 */ - __I uint8_t BACKKEY1; /**< Backdoor Comparison Key 1., offset: 0x2 */ - __I uint8_t BACKKEY0; /**< Backdoor Comparison Key 0., offset: 0x3 */ - __I uint8_t BACKKEY7; /**< Backdoor Comparison Key 7., offset: 0x4 */ - __I uint8_t BACKKEY6; /**< Backdoor Comparison Key 6., offset: 0x5 */ - __I uint8_t BACKKEY5; /**< Backdoor Comparison Key 5., offset: 0x6 */ - __I uint8_t BACKKEY4; /**< Backdoor Comparison Key 4., offset: 0x7 */ - __I uint8_t FPROT3; /**< Non-volatile P-Flash Protection 1 - Low Register, offset: 0x8 */ - __I uint8_t FPROT2; /**< Non-volatile P-Flash Protection 1 - High Register, offset: 0x9 */ - __I uint8_t FPROT1; /**< Non-volatile P-Flash Protection 0 - Low Register, offset: 0xA */ - __I uint8_t FPROT0; /**< Non-volatile P-Flash Protection 0 - High Register, offset: 0xB */ - __I uint8_t FSEC; /**< Non-volatile Flash Security Register, offset: 0xC */ - __I uint8_t FOPT; /**< Non-volatile Flash Option Register, offset: 0xD */ - __I uint8_t FEPROT; /**< Non-volatile EERAM Protection Register, offset: 0xE */ - __I uint8_t FDPROT; /**< Non-volatile D-Flash Protection Register, offset: 0xF */ -} NV_Type; - -/* ---------------------------------------------------------------------------- - -- NV Register Masks - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup NV_Register_Masks NV Register Masks - * @{ - */ - -/*! @name BACKKEY3 - Backdoor Comparison Key 3. */ -#define NV_BACKKEY3_KEY_MASK (0xFFU) -#define NV_BACKKEY3_KEY_SHIFT (0U) -#define NV_BACKKEY3_KEY(x) (((uint8_t)(((uint8_t)(x)) << NV_BACKKEY3_KEY_SHIFT)) & NV_BACKKEY3_KEY_MASK) - -/*! @name BACKKEY2 - Backdoor Comparison Key 2. */ -#define NV_BACKKEY2_KEY_MASK (0xFFU) -#define NV_BACKKEY2_KEY_SHIFT (0U) -#define NV_BACKKEY2_KEY(x) (((uint8_t)(((uint8_t)(x)) << NV_BACKKEY2_KEY_SHIFT)) & NV_BACKKEY2_KEY_MASK) - -/*! @name BACKKEY1 - Backdoor Comparison Key 1. */ -#define NV_BACKKEY1_KEY_MASK (0xFFU) -#define NV_BACKKEY1_KEY_SHIFT (0U) -#define NV_BACKKEY1_KEY(x) (((uint8_t)(((uint8_t)(x)) << NV_BACKKEY1_KEY_SHIFT)) & NV_BACKKEY1_KEY_MASK) - -/*! @name BACKKEY0 - Backdoor Comparison Key 0. */ -#define NV_BACKKEY0_KEY_MASK (0xFFU) -#define NV_BACKKEY0_KEY_SHIFT (0U) -#define NV_BACKKEY0_KEY(x) (((uint8_t)(((uint8_t)(x)) << NV_BACKKEY0_KEY_SHIFT)) & NV_BACKKEY0_KEY_MASK) - -/*! @name BACKKEY7 - Backdoor Comparison Key 7. */ -#define NV_BACKKEY7_KEY_MASK (0xFFU) -#define NV_BACKKEY7_KEY_SHIFT (0U) -#define NV_BACKKEY7_KEY(x) (((uint8_t)(((uint8_t)(x)) << NV_BACKKEY7_KEY_SHIFT)) & NV_BACKKEY7_KEY_MASK) - -/*! @name BACKKEY6 - Backdoor Comparison Key 6. */ -#define NV_BACKKEY6_KEY_MASK (0xFFU) -#define NV_BACKKEY6_KEY_SHIFT (0U) -#define NV_BACKKEY6_KEY(x) (((uint8_t)(((uint8_t)(x)) << NV_BACKKEY6_KEY_SHIFT)) & NV_BACKKEY6_KEY_MASK) - -/*! @name BACKKEY5 - Backdoor Comparison Key 5. */ -#define NV_BACKKEY5_KEY_MASK (0xFFU) -#define NV_BACKKEY5_KEY_SHIFT (0U) -#define NV_BACKKEY5_KEY(x) (((uint8_t)(((uint8_t)(x)) << NV_BACKKEY5_KEY_SHIFT)) & NV_BACKKEY5_KEY_MASK) - -/*! @name BACKKEY4 - Backdoor Comparison Key 4. */ -#define NV_BACKKEY4_KEY_MASK (0xFFU) -#define NV_BACKKEY4_KEY_SHIFT (0U) -#define NV_BACKKEY4_KEY(x) (((uint8_t)(((uint8_t)(x)) << NV_BACKKEY4_KEY_SHIFT)) & NV_BACKKEY4_KEY_MASK) - -/*! @name FPROT3 - Non-volatile P-Flash Protection 1 - Low Register */ -#define NV_FPROT3_PROT_MASK (0xFFU) -#define NV_FPROT3_PROT_SHIFT (0U) -#define NV_FPROT3_PROT(x) (((uint8_t)(((uint8_t)(x)) << NV_FPROT3_PROT_SHIFT)) & NV_FPROT3_PROT_MASK) - -/*! @name FPROT2 - Non-volatile P-Flash Protection 1 - High Register */ -#define NV_FPROT2_PROT_MASK (0xFFU) -#define NV_FPROT2_PROT_SHIFT (0U) -#define NV_FPROT2_PROT(x) (((uint8_t)(((uint8_t)(x)) << NV_FPROT2_PROT_SHIFT)) & NV_FPROT2_PROT_MASK) - -/*! @name FPROT1 - Non-volatile P-Flash Protection 0 - Low Register */ -#define NV_FPROT1_PROT_MASK (0xFFU) -#define NV_FPROT1_PROT_SHIFT (0U) -#define NV_FPROT1_PROT(x) (((uint8_t)(((uint8_t)(x)) << NV_FPROT1_PROT_SHIFT)) & NV_FPROT1_PROT_MASK) - -/*! @name FPROT0 - Non-volatile P-Flash Protection 0 - High Register */ -#define NV_FPROT0_PROT_MASK (0xFFU) -#define NV_FPROT0_PROT_SHIFT (0U) -#define NV_FPROT0_PROT(x) (((uint8_t)(((uint8_t)(x)) << NV_FPROT0_PROT_SHIFT)) & NV_FPROT0_PROT_MASK) - -/*! @name FSEC - Non-volatile Flash Security Register */ -#define NV_FSEC_SEC_MASK (0x3U) -#define NV_FSEC_SEC_SHIFT (0U) -#define NV_FSEC_SEC(x) (((uint8_t)(((uint8_t)(x)) << NV_FSEC_SEC_SHIFT)) & NV_FSEC_SEC_MASK) -#define NV_FSEC_FSLACC_MASK (0xCU) -#define NV_FSEC_FSLACC_SHIFT (2U) -#define NV_FSEC_FSLACC(x) (((uint8_t)(((uint8_t)(x)) << NV_FSEC_FSLACC_SHIFT)) & NV_FSEC_FSLACC_MASK) -#define NV_FSEC_MEEN_MASK (0x30U) -#define NV_FSEC_MEEN_SHIFT (4U) -#define NV_FSEC_MEEN(x) (((uint8_t)(((uint8_t)(x)) << NV_FSEC_MEEN_SHIFT)) & NV_FSEC_MEEN_MASK) -#define NV_FSEC_KEYEN_MASK (0xC0U) -#define NV_FSEC_KEYEN_SHIFT (6U) -#define NV_FSEC_KEYEN(x) (((uint8_t)(((uint8_t)(x)) << NV_FSEC_KEYEN_SHIFT)) & NV_FSEC_KEYEN_MASK) - -/*! @name FOPT - Non-volatile Flash Option Register */ -#define NV_FOPT_LPBOOT_MASK (0x1U) -#define NV_FOPT_LPBOOT_SHIFT (0U) -#define NV_FOPT_LPBOOT(x) (((uint8_t)(((uint8_t)(x)) << NV_FOPT_LPBOOT_SHIFT)) & NV_FOPT_LPBOOT_MASK) -#define NV_FOPT_EZPORT_DIS_MASK (0x2U) -#define NV_FOPT_EZPORT_DIS_SHIFT (1U) -#define NV_FOPT_EZPORT_DIS(x) (((uint8_t)(((uint8_t)(x)) << NV_FOPT_EZPORT_DIS_SHIFT)) & NV_FOPT_EZPORT_DIS_MASK) - -/*! @name FEPROT - Non-volatile EERAM Protection Register */ -#define NV_FEPROT_EPROT_MASK (0xFFU) -#define NV_FEPROT_EPROT_SHIFT (0U) -#define NV_FEPROT_EPROT(x) (((uint8_t)(((uint8_t)(x)) << NV_FEPROT_EPROT_SHIFT)) & NV_FEPROT_EPROT_MASK) - -/*! @name FDPROT - Non-volatile D-Flash Protection Register */ -#define NV_FDPROT_DPROT_MASK (0xFFU) -#define NV_FDPROT_DPROT_SHIFT (0U) -#define NV_FDPROT_DPROT(x) (((uint8_t)(((uint8_t)(x)) << NV_FDPROT_DPROT_SHIFT)) & NV_FDPROT_DPROT_MASK) - - -/*! - * @} - */ /* end of group NV_Register_Masks */ - - -/* NV - Peripheral instance base addresses */ -/** Peripheral FTFE_FlashConfig base address */ -#define FTFE_FlashConfig_BASE (0x400u) -/** Peripheral FTFE_FlashConfig base pointer */ -#define FTFE_FlashConfig ((NV_Type *)FTFE_FlashConfig_BASE) -/** Array initializer of NV peripheral base addresses */ -#define NV_BASE_ADDRS { FTFE_FlashConfig_BASE } -/** Array initializer of NV peripheral base pointers */ -#define NV_BASE_PTRS { FTFE_FlashConfig } - -/*! - * @} - */ /* end of group NV_Peripheral_Access_Layer */ - - -/* ---------------------------------------------------------------------------- - -- OSC Peripheral Access Layer - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup OSC_Peripheral_Access_Layer OSC Peripheral Access Layer - * @{ - */ - -/** OSC - Register Layout Typedef */ -typedef struct { - __IO uint8_t CR; /**< OSC Control Register, offset: 0x0 */ -} OSC_Type; - -/* ---------------------------------------------------------------------------- - -- OSC Register Masks - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup OSC_Register_Masks OSC Register Masks - * @{ - */ - -/*! @name CR - OSC Control Register */ -#define OSC_CR_SC16P_MASK (0x1U) -#define OSC_CR_SC16P_SHIFT (0U) -#define OSC_CR_SC16P(x) (((uint8_t)(((uint8_t)(x)) << OSC_CR_SC16P_SHIFT)) & OSC_CR_SC16P_MASK) -#define OSC_CR_SC8P_MASK (0x2U) -#define OSC_CR_SC8P_SHIFT (1U) -#define OSC_CR_SC8P(x) (((uint8_t)(((uint8_t)(x)) << OSC_CR_SC8P_SHIFT)) & OSC_CR_SC8P_MASK) -#define OSC_CR_SC4P_MASK (0x4U) -#define OSC_CR_SC4P_SHIFT (2U) -#define OSC_CR_SC4P(x) (((uint8_t)(((uint8_t)(x)) << OSC_CR_SC4P_SHIFT)) & OSC_CR_SC4P_MASK) -#define OSC_CR_SC2P_MASK (0x8U) -#define OSC_CR_SC2P_SHIFT (3U) -#define OSC_CR_SC2P(x) (((uint8_t)(((uint8_t)(x)) << OSC_CR_SC2P_SHIFT)) & OSC_CR_SC2P_MASK) -#define OSC_CR_EREFSTEN_MASK (0x20U) -#define OSC_CR_EREFSTEN_SHIFT (5U) -#define OSC_CR_EREFSTEN(x) (((uint8_t)(((uint8_t)(x)) << OSC_CR_EREFSTEN_SHIFT)) & OSC_CR_EREFSTEN_MASK) -#define OSC_CR_ERCLKEN_MASK (0x80U) -#define OSC_CR_ERCLKEN_SHIFT (7U) -#define OSC_CR_ERCLKEN(x) (((uint8_t)(((uint8_t)(x)) << OSC_CR_ERCLKEN_SHIFT)) & OSC_CR_ERCLKEN_MASK) - - -/*! - * @} - */ /* end of group OSC_Register_Masks */ - - -/* OSC - Peripheral instance base addresses */ -/** Peripheral OSC base address */ -#define OSC_BASE (0x40065000u) -/** Peripheral OSC base pointer */ -#define OSC ((OSC_Type *)OSC_BASE) -/** Array initializer of OSC peripheral base addresses */ -#define OSC_BASE_ADDRS { OSC_BASE } -/** Array initializer of OSC peripheral base pointers */ -#define OSC_BASE_PTRS { OSC } - -/*! - * @} - */ /* end of group OSC_Peripheral_Access_Layer */ - - -/* ---------------------------------------------------------------------------- - -- PDB Peripheral Access Layer - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup PDB_Peripheral_Access_Layer PDB Peripheral Access Layer - * @{ - */ - -/** PDB - Register Layout Typedef */ -typedef struct { - __IO uint32_t SC; /**< Status and Control register, offset: 0x0 */ - __IO uint32_t MOD; /**< Modulus register, offset: 0x4 */ - __I uint32_t CNT; /**< Counter register, offset: 0x8 */ - __IO uint32_t IDLY; /**< Interrupt Delay register, offset: 0xC */ - struct { /* offset: 0x10, array step: 0x28 */ - __IO uint32_t C1; /**< Channel n Control register 1, array offset: 0x10, array step: 0x28 */ - __IO uint32_t S; /**< Channel n Status register, array offset: 0x14, array step: 0x28 */ - __IO uint32_t DLY[2]; /**< Channel n Delay 0 register..Channel n Delay 1 register, array offset: 0x18, array step: index*0x28, index2*0x4 */ - uint8_t RESERVED_0[24]; - } CH[2]; - uint8_t RESERVED_0[240]; - struct { /* offset: 0x150, array step: 0x8 */ - __IO uint32_t INTC; /**< DAC Interval Trigger n Control register, array offset: 0x150, array step: 0x8 */ - __IO uint32_t INT; /**< DAC Interval n register, array offset: 0x154, array step: 0x8 */ - } DAC[2]; - uint8_t RESERVED_1[48]; - __IO uint32_t POEN; /**< Pulse-Out n Enable register, offset: 0x190 */ - __IO uint32_t PODLY[3]; /**< Pulse-Out n Delay register, array offset: 0x194, array step: 0x4 */ -} PDB_Type; - -/* ---------------------------------------------------------------------------- - -- PDB Register Masks - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup PDB_Register_Masks PDB Register Masks - * @{ - */ - -/*! @name SC - Status and Control register */ -#define PDB_SC_LDOK_MASK (0x1U) -#define PDB_SC_LDOK_SHIFT (0U) -#define PDB_SC_LDOK(x) (((uint32_t)(((uint32_t)(x)) << PDB_SC_LDOK_SHIFT)) & PDB_SC_LDOK_MASK) -#define PDB_SC_CONT_MASK (0x2U) -#define PDB_SC_CONT_SHIFT (1U) -#define PDB_SC_CONT(x) (((uint32_t)(((uint32_t)(x)) << PDB_SC_CONT_SHIFT)) & PDB_SC_CONT_MASK) -#define PDB_SC_MULT_MASK (0xCU) -#define PDB_SC_MULT_SHIFT (2U) -#define PDB_SC_MULT(x) (((uint32_t)(((uint32_t)(x)) << PDB_SC_MULT_SHIFT)) & PDB_SC_MULT_MASK) -#define PDB_SC_PDBIE_MASK (0x20U) -#define PDB_SC_PDBIE_SHIFT (5U) -#define PDB_SC_PDBIE(x) (((uint32_t)(((uint32_t)(x)) << PDB_SC_PDBIE_SHIFT)) & PDB_SC_PDBIE_MASK) -#define PDB_SC_PDBIF_MASK (0x40U) -#define PDB_SC_PDBIF_SHIFT (6U) -#define PDB_SC_PDBIF(x) (((uint32_t)(((uint32_t)(x)) << PDB_SC_PDBIF_SHIFT)) & PDB_SC_PDBIF_MASK) -#define PDB_SC_PDBEN_MASK (0x80U) -#define PDB_SC_PDBEN_SHIFT (7U) -#define PDB_SC_PDBEN(x) (((uint32_t)(((uint32_t)(x)) << PDB_SC_PDBEN_SHIFT)) & PDB_SC_PDBEN_MASK) -#define PDB_SC_TRGSEL_MASK (0xF00U) -#define PDB_SC_TRGSEL_SHIFT (8U) -#define PDB_SC_TRGSEL(x) (((uint32_t)(((uint32_t)(x)) << PDB_SC_TRGSEL_SHIFT)) & PDB_SC_TRGSEL_MASK) -#define PDB_SC_PRESCALER_MASK (0x7000U) -#define PDB_SC_PRESCALER_SHIFT (12U) -#define PDB_SC_PRESCALER(x) (((uint32_t)(((uint32_t)(x)) << PDB_SC_PRESCALER_SHIFT)) & PDB_SC_PRESCALER_MASK) -#define PDB_SC_DMAEN_MASK (0x8000U) -#define PDB_SC_DMAEN_SHIFT (15U) -#define PDB_SC_DMAEN(x) (((uint32_t)(((uint32_t)(x)) << PDB_SC_DMAEN_SHIFT)) & PDB_SC_DMAEN_MASK) -#define PDB_SC_SWTRIG_MASK (0x10000U) -#define PDB_SC_SWTRIG_SHIFT (16U) -#define PDB_SC_SWTRIG(x) (((uint32_t)(((uint32_t)(x)) << PDB_SC_SWTRIG_SHIFT)) & PDB_SC_SWTRIG_MASK) -#define PDB_SC_PDBEIE_MASK (0x20000U) -#define PDB_SC_PDBEIE_SHIFT (17U) -#define PDB_SC_PDBEIE(x) (((uint32_t)(((uint32_t)(x)) << PDB_SC_PDBEIE_SHIFT)) & PDB_SC_PDBEIE_MASK) -#define PDB_SC_LDMOD_MASK (0xC0000U) -#define PDB_SC_LDMOD_SHIFT (18U) -#define PDB_SC_LDMOD(x) (((uint32_t)(((uint32_t)(x)) << PDB_SC_LDMOD_SHIFT)) & PDB_SC_LDMOD_MASK) - -/*! @name MOD - Modulus register */ -#define PDB_MOD_MOD_MASK (0xFFFFU) -#define PDB_MOD_MOD_SHIFT (0U) -#define PDB_MOD_MOD(x) (((uint32_t)(((uint32_t)(x)) << PDB_MOD_MOD_SHIFT)) & PDB_MOD_MOD_MASK) - -/*! @name CNT - Counter register */ -#define PDB_CNT_CNT_MASK (0xFFFFU) -#define PDB_CNT_CNT_SHIFT (0U) -#define PDB_CNT_CNT(x) (((uint32_t)(((uint32_t)(x)) << PDB_CNT_CNT_SHIFT)) & PDB_CNT_CNT_MASK) - -/*! @name IDLY - Interrupt Delay register */ -#define PDB_IDLY_IDLY_MASK (0xFFFFU) -#define PDB_IDLY_IDLY_SHIFT (0U) -#define PDB_IDLY_IDLY(x) (((uint32_t)(((uint32_t)(x)) << PDB_IDLY_IDLY_SHIFT)) & PDB_IDLY_IDLY_MASK) - -/*! @name C1 - Channel n Control register 1 */ -#define PDB_C1_EN_MASK (0xFFU) -#define PDB_C1_EN_SHIFT (0U) -#define PDB_C1_EN(x) (((uint32_t)(((uint32_t)(x)) << PDB_C1_EN_SHIFT)) & PDB_C1_EN_MASK) -#define PDB_C1_TOS_MASK (0xFF00U) -#define PDB_C1_TOS_SHIFT (8U) -#define PDB_C1_TOS(x) (((uint32_t)(((uint32_t)(x)) << PDB_C1_TOS_SHIFT)) & PDB_C1_TOS_MASK) -#define PDB_C1_BB_MASK (0xFF0000U) -#define PDB_C1_BB_SHIFT (16U) -#define PDB_C1_BB(x) (((uint32_t)(((uint32_t)(x)) << PDB_C1_BB_SHIFT)) & PDB_C1_BB_MASK) - -/* The count of PDB_C1 */ -#define PDB_C1_COUNT (2U) - -/*! @name S - Channel n Status register */ -#define PDB_S_ERR_MASK (0xFFU) -#define PDB_S_ERR_SHIFT (0U) -#define PDB_S_ERR(x) (((uint32_t)(((uint32_t)(x)) << PDB_S_ERR_SHIFT)) & PDB_S_ERR_MASK) -#define PDB_S_CF_MASK (0xFF0000U) -#define PDB_S_CF_SHIFT (16U) -#define PDB_S_CF(x) (((uint32_t)(((uint32_t)(x)) << PDB_S_CF_SHIFT)) & PDB_S_CF_MASK) - -/* The count of PDB_S */ -#define PDB_S_COUNT (2U) - -/*! @name DLY - Channel n Delay 0 register..Channel n Delay 1 register */ -#define PDB_DLY_DLY_MASK (0xFFFFU) -#define PDB_DLY_DLY_SHIFT (0U) -#define PDB_DLY_DLY(x) (((uint32_t)(((uint32_t)(x)) << PDB_DLY_DLY_SHIFT)) & PDB_DLY_DLY_MASK) - -/* The count of PDB_DLY */ -#define PDB_DLY_COUNT (2U) - -/* The count of PDB_DLY */ -#define PDB_DLY_COUNT2 (2U) - -/*! @name INTC - DAC Interval Trigger n Control register */ -#define PDB_INTC_TOE_MASK (0x1U) -#define PDB_INTC_TOE_SHIFT (0U) -#define PDB_INTC_TOE(x) (((uint32_t)(((uint32_t)(x)) << PDB_INTC_TOE_SHIFT)) & PDB_INTC_TOE_MASK) -#define PDB_INTC_EXT_MASK (0x2U) -#define PDB_INTC_EXT_SHIFT (1U) -#define PDB_INTC_EXT(x) (((uint32_t)(((uint32_t)(x)) << PDB_INTC_EXT_SHIFT)) & PDB_INTC_EXT_MASK) - -/* The count of PDB_INTC */ -#define PDB_INTC_COUNT (2U) - -/*! @name INT - DAC Interval n register */ -#define PDB_INT_INT_MASK (0xFFFFU) -#define PDB_INT_INT_SHIFT (0U) -#define PDB_INT_INT(x) (((uint32_t)(((uint32_t)(x)) << PDB_INT_INT_SHIFT)) & PDB_INT_INT_MASK) - -/* The count of PDB_INT */ -#define PDB_INT_COUNT (2U) - -/*! @name POEN - Pulse-Out n Enable register */ -#define PDB_POEN_POEN_MASK (0xFFU) -#define PDB_POEN_POEN_SHIFT (0U) -#define PDB_POEN_POEN(x) (((uint32_t)(((uint32_t)(x)) << PDB_POEN_POEN_SHIFT)) & PDB_POEN_POEN_MASK) - -/*! @name PODLY - Pulse-Out n Delay register */ -#define PDB_PODLY_DLY2_MASK (0xFFFFU) -#define PDB_PODLY_DLY2_SHIFT (0U) -#define PDB_PODLY_DLY2(x) (((uint32_t)(((uint32_t)(x)) << PDB_PODLY_DLY2_SHIFT)) & PDB_PODLY_DLY2_MASK) -#define PDB_PODLY_DLY1_MASK (0xFFFF0000U) -#define PDB_PODLY_DLY1_SHIFT (16U) -#define PDB_PODLY_DLY1(x) (((uint32_t)(((uint32_t)(x)) << PDB_PODLY_DLY1_SHIFT)) & PDB_PODLY_DLY1_MASK) - -/* The count of PDB_PODLY */ -#define PDB_PODLY_COUNT (3U) - - -/*! - * @} - */ /* end of group PDB_Register_Masks */ - - -/* PDB - Peripheral instance base addresses */ -/** Peripheral PDB0 base address */ -#define PDB0_BASE (0x40036000u) -/** Peripheral PDB0 base pointer */ -#define PDB0 ((PDB_Type *)PDB0_BASE) -/** Array initializer of PDB peripheral base addresses */ -#define PDB_BASE_ADDRS { PDB0_BASE } -/** Array initializer of PDB peripheral base pointers */ -#define PDB_BASE_PTRS { PDB0 } -/** Interrupt vectors for the PDB peripheral type */ -#define PDB_IRQS { PDB0_IRQn } - -/*! - * @} - */ /* end of group PDB_Peripheral_Access_Layer */ - - -/* ---------------------------------------------------------------------------- - -- PIT Peripheral Access Layer - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup PIT_Peripheral_Access_Layer PIT Peripheral Access Layer - * @{ - */ - -/** PIT - Register Layout Typedef */ -typedef struct { - __IO uint32_t MCR; /**< PIT Module Control Register, offset: 0x0 */ - uint8_t RESERVED_0[252]; - struct { /* offset: 0x100, array step: 0x10 */ - __IO uint32_t LDVAL; /**< Timer Load Value Register, array offset: 0x100, array step: 0x10 */ - __I uint32_t CVAL; /**< Current Timer Value Register, array offset: 0x104, array step: 0x10 */ - __IO uint32_t TCTRL; /**< Timer Control Register, array offset: 0x108, array step: 0x10 */ - __IO uint32_t TFLG; /**< Timer Flag Register, array offset: 0x10C, array step: 0x10 */ - } CHANNEL[4]; -} PIT_Type; - -/* ---------------------------------------------------------------------------- - -- PIT Register Masks - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup PIT_Register_Masks PIT Register Masks - * @{ - */ - -/*! @name MCR - PIT Module Control Register */ -#define PIT_MCR_FRZ_MASK (0x1U) -#define PIT_MCR_FRZ_SHIFT (0U) -#define PIT_MCR_FRZ(x) (((uint32_t)(((uint32_t)(x)) << PIT_MCR_FRZ_SHIFT)) & PIT_MCR_FRZ_MASK) -#define PIT_MCR_MDIS_MASK (0x2U) -#define PIT_MCR_MDIS_SHIFT (1U) -#define PIT_MCR_MDIS(x) (((uint32_t)(((uint32_t)(x)) << PIT_MCR_MDIS_SHIFT)) & PIT_MCR_MDIS_MASK) - -/*! @name LDVAL - Timer Load Value Register */ -#define PIT_LDVAL_TSV_MASK (0xFFFFFFFFU) -#define PIT_LDVAL_TSV_SHIFT (0U) -#define PIT_LDVAL_TSV(x) (((uint32_t)(((uint32_t)(x)) << PIT_LDVAL_TSV_SHIFT)) & PIT_LDVAL_TSV_MASK) - -/* The count of PIT_LDVAL */ -#define PIT_LDVAL_COUNT (4U) - -/*! @name CVAL - Current Timer Value Register */ -#define PIT_CVAL_TVL_MASK (0xFFFFFFFFU) -#define PIT_CVAL_TVL_SHIFT (0U) -#define PIT_CVAL_TVL(x) (((uint32_t)(((uint32_t)(x)) << PIT_CVAL_TVL_SHIFT)) & PIT_CVAL_TVL_MASK) - -/* The count of PIT_CVAL */ -#define PIT_CVAL_COUNT (4U) - -/*! @name TCTRL - Timer Control Register */ -#define PIT_TCTRL_TEN_MASK (0x1U) -#define PIT_TCTRL_TEN_SHIFT (0U) -#define PIT_TCTRL_TEN(x) (((uint32_t)(((uint32_t)(x)) << PIT_TCTRL_TEN_SHIFT)) & PIT_TCTRL_TEN_MASK) -#define PIT_TCTRL_TIE_MASK (0x2U) -#define PIT_TCTRL_TIE_SHIFT (1U) -#define PIT_TCTRL_TIE(x) (((uint32_t)(((uint32_t)(x)) << PIT_TCTRL_TIE_SHIFT)) & PIT_TCTRL_TIE_MASK) -#define PIT_TCTRL_CHN_MASK (0x4U) -#define PIT_TCTRL_CHN_SHIFT (2U) -#define PIT_TCTRL_CHN(x) (((uint32_t)(((uint32_t)(x)) << PIT_TCTRL_CHN_SHIFT)) & PIT_TCTRL_CHN_MASK) - -/* The count of PIT_TCTRL */ -#define PIT_TCTRL_COUNT (4U) - -/*! @name TFLG - Timer Flag Register */ -#define PIT_TFLG_TIF_MASK (0x1U) -#define PIT_TFLG_TIF_SHIFT (0U) -#define PIT_TFLG_TIF(x) (((uint32_t)(((uint32_t)(x)) << PIT_TFLG_TIF_SHIFT)) & PIT_TFLG_TIF_MASK) - -/* The count of PIT_TFLG */ -#define PIT_TFLG_COUNT (4U) - - -/*! - * @} - */ /* end of group PIT_Register_Masks */ - - -/* PIT - Peripheral instance base addresses */ -/** Peripheral PIT base address */ -#define PIT_BASE (0x40037000u) -/** Peripheral PIT base pointer */ -#define PIT ((PIT_Type *)PIT_BASE) -/** Array initializer of PIT peripheral base addresses */ -#define PIT_BASE_ADDRS { PIT_BASE } -/** Array initializer of PIT peripheral base pointers */ -#define PIT_BASE_PTRS { PIT } -/** Interrupt vectors for the PIT peripheral type */ -#define PIT_IRQS { { PIT0_IRQn, PIT1_IRQn, PIT2_IRQn, PIT3_IRQn } } - -/*! - * @} - */ /* end of group PIT_Peripheral_Access_Layer */ - - -/* ---------------------------------------------------------------------------- - -- PMC Peripheral Access Layer - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup PMC_Peripheral_Access_Layer PMC Peripheral Access Layer - * @{ - */ - -/** PMC - Register Layout Typedef */ -typedef struct { - __IO uint8_t LVDSC1; /**< Low Voltage Detect Status And Control 1 register, offset: 0x0 */ - __IO uint8_t LVDSC2; /**< Low Voltage Detect Status And Control 2 register, offset: 0x1 */ - __IO uint8_t REGSC; /**< Regulator Status And Control register, offset: 0x2 */ -} PMC_Type; - -/* ---------------------------------------------------------------------------- - -- PMC Register Masks - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup PMC_Register_Masks PMC Register Masks - * @{ - */ - -/*! @name LVDSC1 - Low Voltage Detect Status And Control 1 register */ -#define PMC_LVDSC1_LVDV_MASK (0x3U) -#define PMC_LVDSC1_LVDV_SHIFT (0U) -#define PMC_LVDSC1_LVDV(x) (((uint8_t)(((uint8_t)(x)) << PMC_LVDSC1_LVDV_SHIFT)) & PMC_LVDSC1_LVDV_MASK) -#define PMC_LVDSC1_LVDRE_MASK (0x10U) -#define PMC_LVDSC1_LVDRE_SHIFT (4U) -#define PMC_LVDSC1_LVDRE(x) (((uint8_t)(((uint8_t)(x)) << PMC_LVDSC1_LVDRE_SHIFT)) & PMC_LVDSC1_LVDRE_MASK) -#define PMC_LVDSC1_LVDIE_MASK (0x20U) -#define PMC_LVDSC1_LVDIE_SHIFT (5U) -#define PMC_LVDSC1_LVDIE(x) (((uint8_t)(((uint8_t)(x)) << PMC_LVDSC1_LVDIE_SHIFT)) & PMC_LVDSC1_LVDIE_MASK) -#define PMC_LVDSC1_LVDACK_MASK (0x40U) -#define PMC_LVDSC1_LVDACK_SHIFT (6U) -#define PMC_LVDSC1_LVDACK(x) (((uint8_t)(((uint8_t)(x)) << PMC_LVDSC1_LVDACK_SHIFT)) & PMC_LVDSC1_LVDACK_MASK) -#define PMC_LVDSC1_LVDF_MASK (0x80U) -#define PMC_LVDSC1_LVDF_SHIFT (7U) -#define PMC_LVDSC1_LVDF(x) (((uint8_t)(((uint8_t)(x)) << PMC_LVDSC1_LVDF_SHIFT)) & PMC_LVDSC1_LVDF_MASK) - -/*! @name LVDSC2 - Low Voltage Detect Status And Control 2 register */ -#define PMC_LVDSC2_LVWV_MASK (0x3U) -#define PMC_LVDSC2_LVWV_SHIFT (0U) -#define PMC_LVDSC2_LVWV(x) (((uint8_t)(((uint8_t)(x)) << PMC_LVDSC2_LVWV_SHIFT)) & PMC_LVDSC2_LVWV_MASK) -#define PMC_LVDSC2_LVWIE_MASK (0x20U) -#define PMC_LVDSC2_LVWIE_SHIFT (5U) -#define PMC_LVDSC2_LVWIE(x) (((uint8_t)(((uint8_t)(x)) << PMC_LVDSC2_LVWIE_SHIFT)) & PMC_LVDSC2_LVWIE_MASK) -#define PMC_LVDSC2_LVWACK_MASK (0x40U) -#define PMC_LVDSC2_LVWACK_SHIFT (6U) -#define PMC_LVDSC2_LVWACK(x) (((uint8_t)(((uint8_t)(x)) << PMC_LVDSC2_LVWACK_SHIFT)) & PMC_LVDSC2_LVWACK_MASK) -#define PMC_LVDSC2_LVWF_MASK (0x80U) -#define PMC_LVDSC2_LVWF_SHIFT (7U) -#define PMC_LVDSC2_LVWF(x) (((uint8_t)(((uint8_t)(x)) << PMC_LVDSC2_LVWF_SHIFT)) & PMC_LVDSC2_LVWF_MASK) - -/*! @name REGSC - Regulator Status And Control register */ -#define PMC_REGSC_BGBE_MASK (0x1U) -#define PMC_REGSC_BGBE_SHIFT (0U) -#define PMC_REGSC_BGBE(x) (((uint8_t)(((uint8_t)(x)) << PMC_REGSC_BGBE_SHIFT)) & PMC_REGSC_BGBE_MASK) -#define PMC_REGSC_REGONS_MASK (0x4U) -#define PMC_REGSC_REGONS_SHIFT (2U) -#define PMC_REGSC_REGONS(x) (((uint8_t)(((uint8_t)(x)) << PMC_REGSC_REGONS_SHIFT)) & PMC_REGSC_REGONS_MASK) -#define PMC_REGSC_ACKISO_MASK (0x8U) -#define PMC_REGSC_ACKISO_SHIFT (3U) -#define PMC_REGSC_ACKISO(x) (((uint8_t)(((uint8_t)(x)) << PMC_REGSC_ACKISO_SHIFT)) & PMC_REGSC_ACKISO_MASK) -#define PMC_REGSC_BGEN_MASK (0x10U) -#define PMC_REGSC_BGEN_SHIFT (4U) -#define PMC_REGSC_BGEN(x) (((uint8_t)(((uint8_t)(x)) << PMC_REGSC_BGEN_SHIFT)) & PMC_REGSC_BGEN_MASK) - - -/*! - * @} - */ /* end of group PMC_Register_Masks */ - - -/* PMC - Peripheral instance base addresses */ -/** Peripheral PMC base address */ -#define PMC_BASE (0x4007D000u) -/** Peripheral PMC base pointer */ -#define PMC ((PMC_Type *)PMC_BASE) -/** Array initializer of PMC peripheral base addresses */ -#define PMC_BASE_ADDRS { PMC_BASE } -/** Array initializer of PMC peripheral base pointers */ -#define PMC_BASE_PTRS { PMC } -/** Interrupt vectors for the PMC peripheral type */ -#define PMC_IRQS { LVD_LVW_IRQn } - -/*! - * @} - */ /* end of group PMC_Peripheral_Access_Layer */ - - -/* ---------------------------------------------------------------------------- - -- PORT Peripheral Access Layer - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup PORT_Peripheral_Access_Layer PORT Peripheral Access Layer - * @{ - */ - -/** PORT - Register Layout Typedef */ -typedef struct { - __IO uint32_t PCR[32]; /**< Pin Control Register n, array offset: 0x0, array step: 0x4 */ - __O uint32_t GPCLR; /**< Global Pin Control Low Register, offset: 0x80 */ - __O uint32_t GPCHR; /**< Global Pin Control High Register, offset: 0x84 */ - uint8_t RESERVED_0[24]; - __IO uint32_t ISFR; /**< Interrupt Status Flag Register, offset: 0xA0 */ - uint8_t RESERVED_1[28]; - __IO uint32_t DFER; /**< Digital Filter Enable Register, offset: 0xC0 */ - __IO uint32_t DFCR; /**< Digital Filter Clock Register, offset: 0xC4 */ - __IO uint32_t DFWR; /**< Digital Filter Width Register, offset: 0xC8 */ -} PORT_Type; - -/* ---------------------------------------------------------------------------- - -- PORT Register Masks - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup PORT_Register_Masks PORT Register Masks - * @{ - */ - -/*! @name PCR - Pin Control Register n */ -#define PORT_PCR_PS_MASK (0x1U) -#define PORT_PCR_PS_SHIFT (0U) -#define PORT_PCR_PS(x) (((uint32_t)(((uint32_t)(x)) << PORT_PCR_PS_SHIFT)) & PORT_PCR_PS_MASK) -#define PORT_PCR_PE_MASK (0x2U) -#define PORT_PCR_PE_SHIFT (1U) -#define PORT_PCR_PE(x) (((uint32_t)(((uint32_t)(x)) << PORT_PCR_PE_SHIFT)) & PORT_PCR_PE_MASK) -#define PORT_PCR_SRE_MASK (0x4U) -#define PORT_PCR_SRE_SHIFT (2U) -#define PORT_PCR_SRE(x) (((uint32_t)(((uint32_t)(x)) << PORT_PCR_SRE_SHIFT)) & PORT_PCR_SRE_MASK) -#define PORT_PCR_PFE_MASK (0x10U) -#define PORT_PCR_PFE_SHIFT (4U) -#define PORT_PCR_PFE(x) (((uint32_t)(((uint32_t)(x)) << PORT_PCR_PFE_SHIFT)) & PORT_PCR_PFE_MASK) -#define PORT_PCR_ODE_MASK (0x20U) -#define PORT_PCR_ODE_SHIFT (5U) -#define PORT_PCR_ODE(x) (((uint32_t)(((uint32_t)(x)) << PORT_PCR_ODE_SHIFT)) & PORT_PCR_ODE_MASK) -#define PORT_PCR_DSE_MASK (0x40U) -#define PORT_PCR_DSE_SHIFT (6U) -#define PORT_PCR_DSE(x) (((uint32_t)(((uint32_t)(x)) << PORT_PCR_DSE_SHIFT)) & PORT_PCR_DSE_MASK) -#define PORT_PCR_MUX_MASK (0x700U) -#define PORT_PCR_MUX_SHIFT (8U) -#define PORT_PCR_MUX(x) (((uint32_t)(((uint32_t)(x)) << PORT_PCR_MUX_SHIFT)) & PORT_PCR_MUX_MASK) -#define PORT_PCR_LK_MASK (0x8000U) -#define PORT_PCR_LK_SHIFT (15U) -#define PORT_PCR_LK(x) (((uint32_t)(((uint32_t)(x)) << PORT_PCR_LK_SHIFT)) & PORT_PCR_LK_MASK) -#define PORT_PCR_IRQC_MASK (0xF0000U) -#define PORT_PCR_IRQC_SHIFT (16U) -#define PORT_PCR_IRQC(x) (((uint32_t)(((uint32_t)(x)) << PORT_PCR_IRQC_SHIFT)) & PORT_PCR_IRQC_MASK) -#define PORT_PCR_ISF_MASK (0x1000000U) -#define PORT_PCR_ISF_SHIFT (24U) -#define PORT_PCR_ISF(x) (((uint32_t)(((uint32_t)(x)) << PORT_PCR_ISF_SHIFT)) & PORT_PCR_ISF_MASK) - -/* The count of PORT_PCR */ -#define PORT_PCR_COUNT (32U) - -/*! @name GPCLR - Global Pin Control Low Register */ -#define PORT_GPCLR_GPWD_MASK (0xFFFFU) -#define PORT_GPCLR_GPWD_SHIFT (0U) -#define PORT_GPCLR_GPWD(x) (((uint32_t)(((uint32_t)(x)) << PORT_GPCLR_GPWD_SHIFT)) & PORT_GPCLR_GPWD_MASK) -#define PORT_GPCLR_GPWE_MASK (0xFFFF0000U) -#define PORT_GPCLR_GPWE_SHIFT (16U) -#define PORT_GPCLR_GPWE(x) (((uint32_t)(((uint32_t)(x)) << PORT_GPCLR_GPWE_SHIFT)) & PORT_GPCLR_GPWE_MASK) - -/*! @name GPCHR - Global Pin Control High Register */ -#define PORT_GPCHR_GPWD_MASK (0xFFFFU) -#define PORT_GPCHR_GPWD_SHIFT (0U) -#define PORT_GPCHR_GPWD(x) (((uint32_t)(((uint32_t)(x)) << PORT_GPCHR_GPWD_SHIFT)) & PORT_GPCHR_GPWD_MASK) -#define PORT_GPCHR_GPWE_MASK (0xFFFF0000U) -#define PORT_GPCHR_GPWE_SHIFT (16U) -#define PORT_GPCHR_GPWE(x) (((uint32_t)(((uint32_t)(x)) << PORT_GPCHR_GPWE_SHIFT)) & PORT_GPCHR_GPWE_MASK) - -/*! @name ISFR - Interrupt Status Flag Register */ -#define PORT_ISFR_ISF_MASK (0xFFFFFFFFU) -#define PORT_ISFR_ISF_SHIFT (0U) -#define PORT_ISFR_ISF(x) (((uint32_t)(((uint32_t)(x)) << PORT_ISFR_ISF_SHIFT)) & PORT_ISFR_ISF_MASK) - -/*! @name DFER - Digital Filter Enable Register */ -#define PORT_DFER_DFE_MASK (0xFFFFFFFFU) -#define PORT_DFER_DFE_SHIFT (0U) -#define PORT_DFER_DFE(x) (((uint32_t)(((uint32_t)(x)) << PORT_DFER_DFE_SHIFT)) & PORT_DFER_DFE_MASK) - -/*! @name DFCR - Digital Filter Clock Register */ -#define PORT_DFCR_CS_MASK (0x1U) -#define PORT_DFCR_CS_SHIFT (0U) -#define PORT_DFCR_CS(x) (((uint32_t)(((uint32_t)(x)) << PORT_DFCR_CS_SHIFT)) & PORT_DFCR_CS_MASK) - -/*! @name DFWR - Digital Filter Width Register */ -#define PORT_DFWR_FILT_MASK (0x1FU) -#define PORT_DFWR_FILT_SHIFT (0U) -#define PORT_DFWR_FILT(x) (((uint32_t)(((uint32_t)(x)) << PORT_DFWR_FILT_SHIFT)) & PORT_DFWR_FILT_MASK) - - -/*! - * @} - */ /* end of group PORT_Register_Masks */ - - -/* PORT - Peripheral instance base addresses */ -/** Peripheral PORTA base address */ -#define PORTA_BASE (0x40049000u) -/** Peripheral PORTA base pointer */ -#define PORTA ((PORT_Type *)PORTA_BASE) -/** Peripheral PORTB base address */ -#define PORTB_BASE (0x4004A000u) -/** Peripheral PORTB base pointer */ -#define PORTB ((PORT_Type *)PORTB_BASE) -/** Peripheral PORTC base address */ -#define PORTC_BASE (0x4004B000u) -/** Peripheral PORTC base pointer */ -#define PORTC ((PORT_Type *)PORTC_BASE) -/** Peripheral PORTD base address */ -#define PORTD_BASE (0x4004C000u) -/** Peripheral PORTD base pointer */ -#define PORTD ((PORT_Type *)PORTD_BASE) -/** Peripheral PORTE base address */ -#define PORTE_BASE (0x4004D000u) -/** Peripheral PORTE base pointer */ -#define PORTE ((PORT_Type *)PORTE_BASE) -/** Array initializer of PORT peripheral base addresses */ -#define PORT_BASE_ADDRS { PORTA_BASE, PORTB_BASE, PORTC_BASE, PORTD_BASE, PORTE_BASE } -/** Array initializer of PORT peripheral base pointers */ -#define PORT_BASE_PTRS { PORTA, PORTB, PORTC, PORTD, PORTE } -/** Interrupt vectors for the PORT peripheral type */ -#define PORT_IRQS { PORTA_IRQn, PORTB_IRQn, PORTC_IRQn, PORTD_IRQn, PORTE_IRQn } - -/*! - * @} - */ /* end of group PORT_Peripheral_Access_Layer */ - - -/* ---------------------------------------------------------------------------- - -- RCM Peripheral Access Layer - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup RCM_Peripheral_Access_Layer RCM Peripheral Access Layer - * @{ - */ - -/** RCM - Register Layout Typedef */ -typedef struct { - __I uint8_t SRS0; /**< System Reset Status Register 0, offset: 0x0 */ - __I uint8_t SRS1; /**< System Reset Status Register 1, offset: 0x1 */ - uint8_t RESERVED_0[2]; - __IO uint8_t RPFC; /**< Reset Pin Filter Control register, offset: 0x4 */ - __IO uint8_t RPFW; /**< Reset Pin Filter Width register, offset: 0x5 */ - uint8_t RESERVED_1[1]; - __I uint8_t MR; /**< Mode Register, offset: 0x7 */ -} RCM_Type; - -/* ---------------------------------------------------------------------------- - -- RCM Register Masks - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup RCM_Register_Masks RCM Register Masks - * @{ - */ - -/*! @name SRS0 - System Reset Status Register 0 */ -#define RCM_SRS0_WAKEUP_MASK (0x1U) -#define RCM_SRS0_WAKEUP_SHIFT (0U) -#define RCM_SRS0_WAKEUP(x) (((uint8_t)(((uint8_t)(x)) << RCM_SRS0_WAKEUP_SHIFT)) & RCM_SRS0_WAKEUP_MASK) -#define RCM_SRS0_LVD_MASK (0x2U) -#define RCM_SRS0_LVD_SHIFT (1U) -#define RCM_SRS0_LVD(x) (((uint8_t)(((uint8_t)(x)) << RCM_SRS0_LVD_SHIFT)) & RCM_SRS0_LVD_MASK) -#define RCM_SRS0_LOC_MASK (0x4U) -#define RCM_SRS0_LOC_SHIFT (2U) -#define RCM_SRS0_LOC(x) (((uint8_t)(((uint8_t)(x)) << RCM_SRS0_LOC_SHIFT)) & RCM_SRS0_LOC_MASK) -#define RCM_SRS0_LOL_MASK (0x8U) -#define RCM_SRS0_LOL_SHIFT (3U) -#define RCM_SRS0_LOL(x) (((uint8_t)(((uint8_t)(x)) << RCM_SRS0_LOL_SHIFT)) & RCM_SRS0_LOL_MASK) -#define RCM_SRS0_WDOG_MASK (0x20U) -#define RCM_SRS0_WDOG_SHIFT (5U) -#define RCM_SRS0_WDOG(x) (((uint8_t)(((uint8_t)(x)) << RCM_SRS0_WDOG_SHIFT)) & RCM_SRS0_WDOG_MASK) -#define RCM_SRS0_PIN_MASK (0x40U) -#define RCM_SRS0_PIN_SHIFT (6U) -#define RCM_SRS0_PIN(x) (((uint8_t)(((uint8_t)(x)) << RCM_SRS0_PIN_SHIFT)) & RCM_SRS0_PIN_MASK) -#define RCM_SRS0_POR_MASK (0x80U) -#define RCM_SRS0_POR_SHIFT (7U) -#define RCM_SRS0_POR(x) (((uint8_t)(((uint8_t)(x)) << RCM_SRS0_POR_SHIFT)) & RCM_SRS0_POR_MASK) - -/*! @name SRS1 - System Reset Status Register 1 */ -#define RCM_SRS1_JTAG_MASK (0x1U) -#define RCM_SRS1_JTAG_SHIFT (0U) -#define RCM_SRS1_JTAG(x) (((uint8_t)(((uint8_t)(x)) << RCM_SRS1_JTAG_SHIFT)) & RCM_SRS1_JTAG_MASK) -#define RCM_SRS1_LOCKUP_MASK (0x2U) -#define RCM_SRS1_LOCKUP_SHIFT (1U) -#define RCM_SRS1_LOCKUP(x) (((uint8_t)(((uint8_t)(x)) << RCM_SRS1_LOCKUP_SHIFT)) & RCM_SRS1_LOCKUP_MASK) -#define RCM_SRS1_SW_MASK (0x4U) -#define RCM_SRS1_SW_SHIFT (2U) -#define RCM_SRS1_SW(x) (((uint8_t)(((uint8_t)(x)) << RCM_SRS1_SW_SHIFT)) & RCM_SRS1_SW_MASK) -#define RCM_SRS1_MDM_AP_MASK (0x8U) -#define RCM_SRS1_MDM_AP_SHIFT (3U) -#define RCM_SRS1_MDM_AP(x) (((uint8_t)(((uint8_t)(x)) << RCM_SRS1_MDM_AP_SHIFT)) & RCM_SRS1_MDM_AP_MASK) -#define RCM_SRS1_EZPT_MASK (0x10U) -#define RCM_SRS1_EZPT_SHIFT (4U) -#define RCM_SRS1_EZPT(x) (((uint8_t)(((uint8_t)(x)) << RCM_SRS1_EZPT_SHIFT)) & RCM_SRS1_EZPT_MASK) -#define RCM_SRS1_SACKERR_MASK (0x20U) -#define RCM_SRS1_SACKERR_SHIFT (5U) -#define RCM_SRS1_SACKERR(x) (((uint8_t)(((uint8_t)(x)) << RCM_SRS1_SACKERR_SHIFT)) & RCM_SRS1_SACKERR_MASK) - -/*! @name RPFC - Reset Pin Filter Control register */ -#define RCM_RPFC_RSTFLTSRW_MASK (0x3U) -#define RCM_RPFC_RSTFLTSRW_SHIFT (0U) -#define RCM_RPFC_RSTFLTSRW(x) (((uint8_t)(((uint8_t)(x)) << RCM_RPFC_RSTFLTSRW_SHIFT)) & RCM_RPFC_RSTFLTSRW_MASK) -#define RCM_RPFC_RSTFLTSS_MASK (0x4U) -#define RCM_RPFC_RSTFLTSS_SHIFT (2U) -#define RCM_RPFC_RSTFLTSS(x) (((uint8_t)(((uint8_t)(x)) << RCM_RPFC_RSTFLTSS_SHIFT)) & RCM_RPFC_RSTFLTSS_MASK) - -/*! @name RPFW - Reset Pin Filter Width register */ -#define RCM_RPFW_RSTFLTSEL_MASK (0x1FU) -#define RCM_RPFW_RSTFLTSEL_SHIFT (0U) -#define RCM_RPFW_RSTFLTSEL(x) (((uint8_t)(((uint8_t)(x)) << RCM_RPFW_RSTFLTSEL_SHIFT)) & RCM_RPFW_RSTFLTSEL_MASK) - -/*! @name MR - Mode Register */ -#define RCM_MR_EZP_MS_MASK (0x2U) -#define RCM_MR_EZP_MS_SHIFT (1U) -#define RCM_MR_EZP_MS(x) (((uint8_t)(((uint8_t)(x)) << RCM_MR_EZP_MS_SHIFT)) & RCM_MR_EZP_MS_MASK) - - -/*! - * @} - */ /* end of group RCM_Register_Masks */ - - -/* RCM - Peripheral instance base addresses */ -/** Peripheral RCM base address */ -#define RCM_BASE (0x4007F000u) -/** Peripheral RCM base pointer */ -#define RCM ((RCM_Type *)RCM_BASE) -/** Array initializer of RCM peripheral base addresses */ -#define RCM_BASE_ADDRS { RCM_BASE } -/** Array initializer of RCM peripheral base pointers */ -#define RCM_BASE_PTRS { RCM } - -/*! - * @} - */ /* end of group RCM_Peripheral_Access_Layer */ - - -/* ---------------------------------------------------------------------------- - -- RFSYS Peripheral Access Layer - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup RFSYS_Peripheral_Access_Layer RFSYS Peripheral Access Layer - * @{ - */ - -/** RFSYS - Register Layout Typedef */ -typedef struct { - __IO uint32_t REG[8]; /**< Register file register, array offset: 0x0, array step: 0x4 */ -} RFSYS_Type; - -/* ---------------------------------------------------------------------------- - -- RFSYS Register Masks - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup RFSYS_Register_Masks RFSYS Register Masks - * @{ - */ - -/*! @name REG - Register file register */ -#define RFSYS_REG_LL_MASK (0xFFU) -#define RFSYS_REG_LL_SHIFT (0U) -#define RFSYS_REG_LL(x) (((uint32_t)(((uint32_t)(x)) << RFSYS_REG_LL_SHIFT)) & RFSYS_REG_LL_MASK) -#define RFSYS_REG_LH_MASK (0xFF00U) -#define RFSYS_REG_LH_SHIFT (8U) -#define RFSYS_REG_LH(x) (((uint32_t)(((uint32_t)(x)) << RFSYS_REG_LH_SHIFT)) & RFSYS_REG_LH_MASK) -#define RFSYS_REG_HL_MASK (0xFF0000U) -#define RFSYS_REG_HL_SHIFT (16U) -#define RFSYS_REG_HL(x) (((uint32_t)(((uint32_t)(x)) << RFSYS_REG_HL_SHIFT)) & RFSYS_REG_HL_MASK) -#define RFSYS_REG_HH_MASK (0xFF000000U) -#define RFSYS_REG_HH_SHIFT (24U) -#define RFSYS_REG_HH(x) (((uint32_t)(((uint32_t)(x)) << RFSYS_REG_HH_SHIFT)) & RFSYS_REG_HH_MASK) - -/* The count of RFSYS_REG */ -#define RFSYS_REG_COUNT (8U) - - -/*! - * @} - */ /* end of group RFSYS_Register_Masks */ - - -/* RFSYS - Peripheral instance base addresses */ -/** Peripheral RFSYS base address */ -#define RFSYS_BASE (0x40041000u) -/** Peripheral RFSYS base pointer */ -#define RFSYS ((RFSYS_Type *)RFSYS_BASE) -/** Array initializer of RFSYS peripheral base addresses */ -#define RFSYS_BASE_ADDRS { RFSYS_BASE } -/** Array initializer of RFSYS peripheral base pointers */ -#define RFSYS_BASE_PTRS { RFSYS } - -/*! - * @} - */ /* end of group RFSYS_Peripheral_Access_Layer */ - - -/* ---------------------------------------------------------------------------- - -- RFVBAT Peripheral Access Layer - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup RFVBAT_Peripheral_Access_Layer RFVBAT Peripheral Access Layer - * @{ - */ - -/** RFVBAT - Register Layout Typedef */ -typedef struct { - __IO uint32_t REG[8]; /**< VBAT register file register, array offset: 0x0, array step: 0x4 */ -} RFVBAT_Type; - -/* ---------------------------------------------------------------------------- - -- RFVBAT Register Masks - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup RFVBAT_Register_Masks RFVBAT Register Masks - * @{ - */ - -/*! @name REG - VBAT register file register */ -#define RFVBAT_REG_LL_MASK (0xFFU) -#define RFVBAT_REG_LL_SHIFT (0U) -#define RFVBAT_REG_LL(x) (((uint32_t)(((uint32_t)(x)) << RFVBAT_REG_LL_SHIFT)) & RFVBAT_REG_LL_MASK) -#define RFVBAT_REG_LH_MASK (0xFF00U) -#define RFVBAT_REG_LH_SHIFT (8U) -#define RFVBAT_REG_LH(x) (((uint32_t)(((uint32_t)(x)) << RFVBAT_REG_LH_SHIFT)) & RFVBAT_REG_LH_MASK) -#define RFVBAT_REG_HL_MASK (0xFF0000U) -#define RFVBAT_REG_HL_SHIFT (16U) -#define RFVBAT_REG_HL(x) (((uint32_t)(((uint32_t)(x)) << RFVBAT_REG_HL_SHIFT)) & RFVBAT_REG_HL_MASK) -#define RFVBAT_REG_HH_MASK (0xFF000000U) -#define RFVBAT_REG_HH_SHIFT (24U) -#define RFVBAT_REG_HH(x) (((uint32_t)(((uint32_t)(x)) << RFVBAT_REG_HH_SHIFT)) & RFVBAT_REG_HH_MASK) - -/* The count of RFVBAT_REG */ -#define RFVBAT_REG_COUNT (8U) - - -/*! - * @} - */ /* end of group RFVBAT_Register_Masks */ - - -/* RFVBAT - Peripheral instance base addresses */ -/** Peripheral RFVBAT base address */ -#define RFVBAT_BASE (0x4003E000u) -/** Peripheral RFVBAT base pointer */ -#define RFVBAT ((RFVBAT_Type *)RFVBAT_BASE) -/** Array initializer of RFVBAT peripheral base addresses */ -#define RFVBAT_BASE_ADDRS { RFVBAT_BASE } -/** Array initializer of RFVBAT peripheral base pointers */ -#define RFVBAT_BASE_PTRS { RFVBAT } - -/*! - * @} - */ /* end of group RFVBAT_Peripheral_Access_Layer */ - - -/* ---------------------------------------------------------------------------- - -- RNG Peripheral Access Layer - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup RNG_Peripheral_Access_Layer RNG Peripheral Access Layer - * @{ - */ - -/** RNG - Register Layout Typedef */ -typedef struct { - __IO uint32_t CR; /**< RNGA Control Register, offset: 0x0 */ - __I uint32_t SR; /**< RNGA Status Register, offset: 0x4 */ - __O uint32_t ER; /**< RNGA Entropy Register, offset: 0x8 */ - __I uint32_t OR; /**< RNGA Output Register, offset: 0xC */ -} RNG_Type; - -/* ---------------------------------------------------------------------------- - -- RNG Register Masks - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup RNG_Register_Masks RNG Register Masks - * @{ - */ - -/*! @name CR - RNGA Control Register */ -#define RNG_CR_GO_MASK (0x1U) -#define RNG_CR_GO_SHIFT (0U) -#define RNG_CR_GO(x) (((uint32_t)(((uint32_t)(x)) << RNG_CR_GO_SHIFT)) & RNG_CR_GO_MASK) -#define RNG_CR_HA_MASK (0x2U) -#define RNG_CR_HA_SHIFT (1U) -#define RNG_CR_HA(x) (((uint32_t)(((uint32_t)(x)) << RNG_CR_HA_SHIFT)) & RNG_CR_HA_MASK) -#define RNG_CR_INTM_MASK (0x4U) -#define RNG_CR_INTM_SHIFT (2U) -#define RNG_CR_INTM(x) (((uint32_t)(((uint32_t)(x)) << RNG_CR_INTM_SHIFT)) & RNG_CR_INTM_MASK) -#define RNG_CR_CLRI_MASK (0x8U) -#define RNG_CR_CLRI_SHIFT (3U) -#define RNG_CR_CLRI(x) (((uint32_t)(((uint32_t)(x)) << RNG_CR_CLRI_SHIFT)) & RNG_CR_CLRI_MASK) -#define RNG_CR_SLP_MASK (0x10U) -#define RNG_CR_SLP_SHIFT (4U) -#define RNG_CR_SLP(x) (((uint32_t)(((uint32_t)(x)) << RNG_CR_SLP_SHIFT)) & RNG_CR_SLP_MASK) - -/*! @name SR - RNGA Status Register */ -#define RNG_SR_SECV_MASK (0x1U) -#define RNG_SR_SECV_SHIFT (0U) -#define RNG_SR_SECV(x) (((uint32_t)(((uint32_t)(x)) << RNG_SR_SECV_SHIFT)) & RNG_SR_SECV_MASK) -#define RNG_SR_LRS_MASK (0x2U) -#define RNG_SR_LRS_SHIFT (1U) -#define RNG_SR_LRS(x) (((uint32_t)(((uint32_t)(x)) << RNG_SR_LRS_SHIFT)) & RNG_SR_LRS_MASK) -#define RNG_SR_ORU_MASK (0x4U) -#define RNG_SR_ORU_SHIFT (2U) -#define RNG_SR_ORU(x) (((uint32_t)(((uint32_t)(x)) << RNG_SR_ORU_SHIFT)) & RNG_SR_ORU_MASK) -#define RNG_SR_ERRI_MASK (0x8U) -#define RNG_SR_ERRI_SHIFT (3U) -#define RNG_SR_ERRI(x) (((uint32_t)(((uint32_t)(x)) << RNG_SR_ERRI_SHIFT)) & RNG_SR_ERRI_MASK) -#define RNG_SR_SLP_MASK (0x10U) -#define RNG_SR_SLP_SHIFT (4U) -#define RNG_SR_SLP(x) (((uint32_t)(((uint32_t)(x)) << RNG_SR_SLP_SHIFT)) & RNG_SR_SLP_MASK) -#define RNG_SR_OREG_LVL_MASK (0xFF00U) -#define RNG_SR_OREG_LVL_SHIFT (8U) -#define RNG_SR_OREG_LVL(x) (((uint32_t)(((uint32_t)(x)) << RNG_SR_OREG_LVL_SHIFT)) & RNG_SR_OREG_LVL_MASK) -#define RNG_SR_OREG_SIZE_MASK (0xFF0000U) -#define RNG_SR_OREG_SIZE_SHIFT (16U) -#define RNG_SR_OREG_SIZE(x) (((uint32_t)(((uint32_t)(x)) << RNG_SR_OREG_SIZE_SHIFT)) & RNG_SR_OREG_SIZE_MASK) - -/*! @name ER - RNGA Entropy Register */ -#define RNG_ER_EXT_ENT_MASK (0xFFFFFFFFU) -#define RNG_ER_EXT_ENT_SHIFT (0U) -#define RNG_ER_EXT_ENT(x) (((uint32_t)(((uint32_t)(x)) << RNG_ER_EXT_ENT_SHIFT)) & RNG_ER_EXT_ENT_MASK) - -/*! @name OR - RNGA Output Register */ -#define RNG_OR_RANDOUT_MASK (0xFFFFFFFFU) -#define RNG_OR_RANDOUT_SHIFT (0U) -#define RNG_OR_RANDOUT(x) (((uint32_t)(((uint32_t)(x)) << RNG_OR_RANDOUT_SHIFT)) & RNG_OR_RANDOUT_MASK) - - -/*! - * @} - */ /* end of group RNG_Register_Masks */ - - -/* RNG - Peripheral instance base addresses */ -/** Peripheral RNG base address */ -#define RNG_BASE (0x40029000u) -/** Peripheral RNG base pointer */ -#define RNG ((RNG_Type *)RNG_BASE) -/** Array initializer of RNG peripheral base addresses */ -#define RNG_BASE_ADDRS { RNG_BASE } -/** Array initializer of RNG peripheral base pointers */ -#define RNG_BASE_PTRS { RNG } -/** Interrupt vectors for the RNG peripheral type */ -#define RNG_IRQS { RNG_IRQn } - -/*! - * @} - */ /* end of group RNG_Peripheral_Access_Layer */ - - -/* ---------------------------------------------------------------------------- - -- RTC Peripheral Access Layer - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup RTC_Peripheral_Access_Layer RTC Peripheral Access Layer - * @{ - */ - -/** RTC - Register Layout Typedef */ -typedef struct { - __IO uint32_t TSR; /**< RTC Time Seconds Register, offset: 0x0 */ - __IO uint32_t TPR; /**< RTC Time Prescaler Register, offset: 0x4 */ - __IO uint32_t TAR; /**< RTC Time Alarm Register, offset: 0x8 */ - __IO uint32_t TCR; /**< RTC Time Compensation Register, offset: 0xC */ - __IO uint32_t CR; /**< RTC Control Register, offset: 0x10 */ - __IO uint32_t SR; /**< RTC Status Register, offset: 0x14 */ - __IO uint32_t LR; /**< RTC Lock Register, offset: 0x18 */ - __IO uint32_t IER; /**< RTC Interrupt Enable Register, offset: 0x1C */ - uint8_t RESERVED_0[2016]; - __IO uint32_t WAR; /**< RTC Write Access Register, offset: 0x800 */ - __IO uint32_t RAR; /**< RTC Read Access Register, offset: 0x804 */ -} RTC_Type; - -/* ---------------------------------------------------------------------------- - -- RTC Register Masks - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup RTC_Register_Masks RTC Register Masks - * @{ - */ - -/*! @name TSR - RTC Time Seconds Register */ -#define RTC_TSR_TSR_MASK (0xFFFFFFFFU) -#define RTC_TSR_TSR_SHIFT (0U) -#define RTC_TSR_TSR(x) (((uint32_t)(((uint32_t)(x)) << RTC_TSR_TSR_SHIFT)) & RTC_TSR_TSR_MASK) - -/*! @name TPR - RTC Time Prescaler Register */ -#define RTC_TPR_TPR_MASK (0xFFFFU) -#define RTC_TPR_TPR_SHIFT (0U) -#define RTC_TPR_TPR(x) (((uint32_t)(((uint32_t)(x)) << RTC_TPR_TPR_SHIFT)) & RTC_TPR_TPR_MASK) - -/*! @name TAR - RTC Time Alarm Register */ -#define RTC_TAR_TAR_MASK (0xFFFFFFFFU) -#define RTC_TAR_TAR_SHIFT (0U) -#define RTC_TAR_TAR(x) (((uint32_t)(((uint32_t)(x)) << RTC_TAR_TAR_SHIFT)) & RTC_TAR_TAR_MASK) - -/*! @name TCR - RTC Time Compensation Register */ -#define RTC_TCR_TCR_MASK (0xFFU) -#define RTC_TCR_TCR_SHIFT (0U) -#define RTC_TCR_TCR(x) (((uint32_t)(((uint32_t)(x)) << RTC_TCR_TCR_SHIFT)) & RTC_TCR_TCR_MASK) -#define RTC_TCR_CIR_MASK (0xFF00U) -#define RTC_TCR_CIR_SHIFT (8U) -#define RTC_TCR_CIR(x) (((uint32_t)(((uint32_t)(x)) << RTC_TCR_CIR_SHIFT)) & RTC_TCR_CIR_MASK) -#define RTC_TCR_TCV_MASK (0xFF0000U) -#define RTC_TCR_TCV_SHIFT (16U) -#define RTC_TCR_TCV(x) (((uint32_t)(((uint32_t)(x)) << RTC_TCR_TCV_SHIFT)) & RTC_TCR_TCV_MASK) -#define RTC_TCR_CIC_MASK (0xFF000000U) -#define RTC_TCR_CIC_SHIFT (24U) -#define RTC_TCR_CIC(x) (((uint32_t)(((uint32_t)(x)) << RTC_TCR_CIC_SHIFT)) & RTC_TCR_CIC_MASK) - -/*! @name CR - RTC Control Register */ -#define RTC_CR_SWR_MASK (0x1U) -#define RTC_CR_SWR_SHIFT (0U) -#define RTC_CR_SWR(x) (((uint32_t)(((uint32_t)(x)) << RTC_CR_SWR_SHIFT)) & RTC_CR_SWR_MASK) -#define RTC_CR_WPE_MASK (0x2U) -#define RTC_CR_WPE_SHIFT (1U) -#define RTC_CR_WPE(x) (((uint32_t)(((uint32_t)(x)) << RTC_CR_WPE_SHIFT)) & RTC_CR_WPE_MASK) -#define RTC_CR_SUP_MASK (0x4U) -#define RTC_CR_SUP_SHIFT (2U) -#define RTC_CR_SUP(x) (((uint32_t)(((uint32_t)(x)) << RTC_CR_SUP_SHIFT)) & RTC_CR_SUP_MASK) -#define RTC_CR_UM_MASK (0x8U) -#define RTC_CR_UM_SHIFT (3U) -#define RTC_CR_UM(x) (((uint32_t)(((uint32_t)(x)) << RTC_CR_UM_SHIFT)) & RTC_CR_UM_MASK) -#define RTC_CR_WPS_MASK (0x10U) -#define RTC_CR_WPS_SHIFT (4U) -#define RTC_CR_WPS(x) (((uint32_t)(((uint32_t)(x)) << RTC_CR_WPS_SHIFT)) & RTC_CR_WPS_MASK) -#define RTC_CR_OSCE_MASK (0x100U) -#define RTC_CR_OSCE_SHIFT (8U) -#define RTC_CR_OSCE(x) (((uint32_t)(((uint32_t)(x)) << RTC_CR_OSCE_SHIFT)) & RTC_CR_OSCE_MASK) -#define RTC_CR_CLKO_MASK (0x200U) -#define RTC_CR_CLKO_SHIFT (9U) -#define RTC_CR_CLKO(x) (((uint32_t)(((uint32_t)(x)) << RTC_CR_CLKO_SHIFT)) & RTC_CR_CLKO_MASK) -#define RTC_CR_SC16P_MASK (0x400U) -#define RTC_CR_SC16P_SHIFT (10U) -#define RTC_CR_SC16P(x) (((uint32_t)(((uint32_t)(x)) << RTC_CR_SC16P_SHIFT)) & RTC_CR_SC16P_MASK) -#define RTC_CR_SC8P_MASK (0x800U) -#define RTC_CR_SC8P_SHIFT (11U) -#define RTC_CR_SC8P(x) (((uint32_t)(((uint32_t)(x)) << RTC_CR_SC8P_SHIFT)) & RTC_CR_SC8P_MASK) -#define RTC_CR_SC4P_MASK (0x1000U) -#define RTC_CR_SC4P_SHIFT (12U) -#define RTC_CR_SC4P(x) (((uint32_t)(((uint32_t)(x)) << RTC_CR_SC4P_SHIFT)) & RTC_CR_SC4P_MASK) -#define RTC_CR_SC2P_MASK (0x2000U) -#define RTC_CR_SC2P_SHIFT (13U) -#define RTC_CR_SC2P(x) (((uint32_t)(((uint32_t)(x)) << RTC_CR_SC2P_SHIFT)) & RTC_CR_SC2P_MASK) - -/*! @name SR - RTC Status Register */ -#define RTC_SR_TIF_MASK (0x1U) -#define RTC_SR_TIF_SHIFT (0U) -#define RTC_SR_TIF(x) (((uint32_t)(((uint32_t)(x)) << RTC_SR_TIF_SHIFT)) & RTC_SR_TIF_MASK) -#define RTC_SR_TOF_MASK (0x2U) -#define RTC_SR_TOF_SHIFT (1U) -#define RTC_SR_TOF(x) (((uint32_t)(((uint32_t)(x)) << RTC_SR_TOF_SHIFT)) & RTC_SR_TOF_MASK) -#define RTC_SR_TAF_MASK (0x4U) -#define RTC_SR_TAF_SHIFT (2U) -#define RTC_SR_TAF(x) (((uint32_t)(((uint32_t)(x)) << RTC_SR_TAF_SHIFT)) & RTC_SR_TAF_MASK) -#define RTC_SR_TCE_MASK (0x10U) -#define RTC_SR_TCE_SHIFT (4U) -#define RTC_SR_TCE(x) (((uint32_t)(((uint32_t)(x)) << RTC_SR_TCE_SHIFT)) & RTC_SR_TCE_MASK) - -/*! @name LR - RTC Lock Register */ -#define RTC_LR_TCL_MASK (0x8U) -#define RTC_LR_TCL_SHIFT (3U) -#define RTC_LR_TCL(x) (((uint32_t)(((uint32_t)(x)) << RTC_LR_TCL_SHIFT)) & RTC_LR_TCL_MASK) -#define RTC_LR_CRL_MASK (0x10U) -#define RTC_LR_CRL_SHIFT (4U) -#define RTC_LR_CRL(x) (((uint32_t)(((uint32_t)(x)) << RTC_LR_CRL_SHIFT)) & RTC_LR_CRL_MASK) -#define RTC_LR_SRL_MASK (0x20U) -#define RTC_LR_SRL_SHIFT (5U) -#define RTC_LR_SRL(x) (((uint32_t)(((uint32_t)(x)) << RTC_LR_SRL_SHIFT)) & RTC_LR_SRL_MASK) -#define RTC_LR_LRL_MASK (0x40U) -#define RTC_LR_LRL_SHIFT (6U) -#define RTC_LR_LRL(x) (((uint32_t)(((uint32_t)(x)) << RTC_LR_LRL_SHIFT)) & RTC_LR_LRL_MASK) - -/*! @name IER - RTC Interrupt Enable Register */ -#define RTC_IER_TIIE_MASK (0x1U) -#define RTC_IER_TIIE_SHIFT (0U) -#define RTC_IER_TIIE(x) (((uint32_t)(((uint32_t)(x)) << RTC_IER_TIIE_SHIFT)) & RTC_IER_TIIE_MASK) -#define RTC_IER_TOIE_MASK (0x2U) -#define RTC_IER_TOIE_SHIFT (1U) -#define RTC_IER_TOIE(x) (((uint32_t)(((uint32_t)(x)) << RTC_IER_TOIE_SHIFT)) & RTC_IER_TOIE_MASK) -#define RTC_IER_TAIE_MASK (0x4U) -#define RTC_IER_TAIE_SHIFT (2U) -#define RTC_IER_TAIE(x) (((uint32_t)(((uint32_t)(x)) << RTC_IER_TAIE_SHIFT)) & RTC_IER_TAIE_MASK) -#define RTC_IER_TSIE_MASK (0x10U) -#define RTC_IER_TSIE_SHIFT (4U) -#define RTC_IER_TSIE(x) (((uint32_t)(((uint32_t)(x)) << RTC_IER_TSIE_SHIFT)) & RTC_IER_TSIE_MASK) -#define RTC_IER_WPON_MASK (0x80U) -#define RTC_IER_WPON_SHIFT (7U) -#define RTC_IER_WPON(x) (((uint32_t)(((uint32_t)(x)) << RTC_IER_WPON_SHIFT)) & RTC_IER_WPON_MASK) - -/*! @name WAR - RTC Write Access Register */ -#define RTC_WAR_TSRW_MASK (0x1U) -#define RTC_WAR_TSRW_SHIFT (0U) -#define RTC_WAR_TSRW(x) (((uint32_t)(((uint32_t)(x)) << RTC_WAR_TSRW_SHIFT)) & RTC_WAR_TSRW_MASK) -#define RTC_WAR_TPRW_MASK (0x2U) -#define RTC_WAR_TPRW_SHIFT (1U) -#define RTC_WAR_TPRW(x) (((uint32_t)(((uint32_t)(x)) << RTC_WAR_TPRW_SHIFT)) & RTC_WAR_TPRW_MASK) -#define RTC_WAR_TARW_MASK (0x4U) -#define RTC_WAR_TARW_SHIFT (2U) -#define RTC_WAR_TARW(x) (((uint32_t)(((uint32_t)(x)) << RTC_WAR_TARW_SHIFT)) & RTC_WAR_TARW_MASK) -#define RTC_WAR_TCRW_MASK (0x8U) -#define RTC_WAR_TCRW_SHIFT (3U) -#define RTC_WAR_TCRW(x) (((uint32_t)(((uint32_t)(x)) << RTC_WAR_TCRW_SHIFT)) & RTC_WAR_TCRW_MASK) -#define RTC_WAR_CRW_MASK (0x10U) -#define RTC_WAR_CRW_SHIFT (4U) -#define RTC_WAR_CRW(x) (((uint32_t)(((uint32_t)(x)) << RTC_WAR_CRW_SHIFT)) & RTC_WAR_CRW_MASK) -#define RTC_WAR_SRW_MASK (0x20U) -#define RTC_WAR_SRW_SHIFT (5U) -#define RTC_WAR_SRW(x) (((uint32_t)(((uint32_t)(x)) << RTC_WAR_SRW_SHIFT)) & RTC_WAR_SRW_MASK) -#define RTC_WAR_LRW_MASK (0x40U) -#define RTC_WAR_LRW_SHIFT (6U) -#define RTC_WAR_LRW(x) (((uint32_t)(((uint32_t)(x)) << RTC_WAR_LRW_SHIFT)) & RTC_WAR_LRW_MASK) -#define RTC_WAR_IERW_MASK (0x80U) -#define RTC_WAR_IERW_SHIFT (7U) -#define RTC_WAR_IERW(x) (((uint32_t)(((uint32_t)(x)) << RTC_WAR_IERW_SHIFT)) & RTC_WAR_IERW_MASK) - -/*! @name RAR - RTC Read Access Register */ -#define RTC_RAR_TSRR_MASK (0x1U) -#define RTC_RAR_TSRR_SHIFT (0U) -#define RTC_RAR_TSRR(x) (((uint32_t)(((uint32_t)(x)) << RTC_RAR_TSRR_SHIFT)) & RTC_RAR_TSRR_MASK) -#define RTC_RAR_TPRR_MASK (0x2U) -#define RTC_RAR_TPRR_SHIFT (1U) -#define RTC_RAR_TPRR(x) (((uint32_t)(((uint32_t)(x)) << RTC_RAR_TPRR_SHIFT)) & RTC_RAR_TPRR_MASK) -#define RTC_RAR_TARR_MASK (0x4U) -#define RTC_RAR_TARR_SHIFT (2U) -#define RTC_RAR_TARR(x) (((uint32_t)(((uint32_t)(x)) << RTC_RAR_TARR_SHIFT)) & RTC_RAR_TARR_MASK) -#define RTC_RAR_TCRR_MASK (0x8U) -#define RTC_RAR_TCRR_SHIFT (3U) -#define RTC_RAR_TCRR(x) (((uint32_t)(((uint32_t)(x)) << RTC_RAR_TCRR_SHIFT)) & RTC_RAR_TCRR_MASK) -#define RTC_RAR_CRR_MASK (0x10U) -#define RTC_RAR_CRR_SHIFT (4U) -#define RTC_RAR_CRR(x) (((uint32_t)(((uint32_t)(x)) << RTC_RAR_CRR_SHIFT)) & RTC_RAR_CRR_MASK) -#define RTC_RAR_SRR_MASK (0x20U) -#define RTC_RAR_SRR_SHIFT (5U) -#define RTC_RAR_SRR(x) (((uint32_t)(((uint32_t)(x)) << RTC_RAR_SRR_SHIFT)) & RTC_RAR_SRR_MASK) -#define RTC_RAR_LRR_MASK (0x40U) -#define RTC_RAR_LRR_SHIFT (6U) -#define RTC_RAR_LRR(x) (((uint32_t)(((uint32_t)(x)) << RTC_RAR_LRR_SHIFT)) & RTC_RAR_LRR_MASK) -#define RTC_RAR_IERR_MASK (0x80U) -#define RTC_RAR_IERR_SHIFT (7U) -#define RTC_RAR_IERR(x) (((uint32_t)(((uint32_t)(x)) << RTC_RAR_IERR_SHIFT)) & RTC_RAR_IERR_MASK) - - -/*! - * @} - */ /* end of group RTC_Register_Masks */ - - -/* RTC - Peripheral instance base addresses */ -/** Peripheral RTC base address */ -#define RTC_BASE (0x4003D000u) -/** Peripheral RTC base pointer */ -#define RTC ((RTC_Type *)RTC_BASE) -/** Array initializer of RTC peripheral base addresses */ -#define RTC_BASE_ADDRS { RTC_BASE } -/** Array initializer of RTC peripheral base pointers */ -#define RTC_BASE_PTRS { RTC } -/** Interrupt vectors for the RTC peripheral type */ -#define RTC_IRQS { RTC_IRQn } -#define RTC_SECONDS_IRQS { RTC_Seconds_IRQn } - -/*! - * @} - */ /* end of group RTC_Peripheral_Access_Layer */ - - -/* ---------------------------------------------------------------------------- - -- SDHC Peripheral Access Layer - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup SDHC_Peripheral_Access_Layer SDHC Peripheral Access Layer - * @{ - */ - -/** SDHC - Register Layout Typedef */ -typedef struct { - __IO uint32_t DSADDR; /**< DMA System Address register, offset: 0x0 */ - __IO uint32_t BLKATTR; /**< Block Attributes register, offset: 0x4 */ - __IO uint32_t CMDARG; /**< Command Argument register, offset: 0x8 */ - __IO uint32_t XFERTYP; /**< Transfer Type register, offset: 0xC */ - __I uint32_t CMDRSP[4]; /**< Command Response 0..Command Response 3, array offset: 0x10, array step: 0x4 */ - __IO uint32_t DATPORT; /**< Buffer Data Port register, offset: 0x20 */ - __I uint32_t PRSSTAT; /**< Present State register, offset: 0x24 */ - __IO uint32_t PROCTL; /**< Protocol Control register, offset: 0x28 */ - __IO uint32_t SYSCTL; /**< System Control register, offset: 0x2C */ - __IO uint32_t IRQSTAT; /**< Interrupt Status register, offset: 0x30 */ - __IO uint32_t IRQSTATEN; /**< Interrupt Status Enable register, offset: 0x34 */ - __IO uint32_t IRQSIGEN; /**< Interrupt Signal Enable register, offset: 0x38 */ - __I uint32_t AC12ERR; /**< Auto CMD12 Error Status Register, offset: 0x3C */ - __I uint32_t HTCAPBLT; /**< Host Controller Capabilities, offset: 0x40 */ - __IO uint32_t WML; /**< Watermark Level Register, offset: 0x44 */ - uint8_t RESERVED_0[8]; - __O uint32_t FEVT; /**< Force Event register, offset: 0x50 */ - __I uint32_t ADMAES; /**< ADMA Error Status register, offset: 0x54 */ - __IO uint32_t ADSADDR; /**< ADMA System Addressregister, offset: 0x58 */ - uint8_t RESERVED_1[100]; - __IO uint32_t VENDOR; /**< Vendor Specific register, offset: 0xC0 */ - __IO uint32_t MMCBOOT; /**< MMC Boot register, offset: 0xC4 */ - uint8_t RESERVED_2[52]; - __I uint32_t HOSTVER; /**< Host Controller Version, offset: 0xFC */ -} SDHC_Type; - -/* ---------------------------------------------------------------------------- - -- SDHC Register Masks - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup SDHC_Register_Masks SDHC Register Masks - * @{ - */ - -/*! @name DSADDR - DMA System Address register */ -#define SDHC_DSADDR_DSADDR_MASK (0xFFFFFFFCU) -#define SDHC_DSADDR_DSADDR_SHIFT (2U) -#define SDHC_DSADDR_DSADDR(x) (((uint32_t)(((uint32_t)(x)) << SDHC_DSADDR_DSADDR_SHIFT)) & SDHC_DSADDR_DSADDR_MASK) - -/*! @name BLKATTR - Block Attributes register */ -#define SDHC_BLKATTR_BLKSIZE_MASK (0x1FFFU) -#define SDHC_BLKATTR_BLKSIZE_SHIFT (0U) -#define SDHC_BLKATTR_BLKSIZE(x) (((uint32_t)(((uint32_t)(x)) << SDHC_BLKATTR_BLKSIZE_SHIFT)) & SDHC_BLKATTR_BLKSIZE_MASK) -#define SDHC_BLKATTR_BLKCNT_MASK (0xFFFF0000U) -#define SDHC_BLKATTR_BLKCNT_SHIFT (16U) -#define SDHC_BLKATTR_BLKCNT(x) (((uint32_t)(((uint32_t)(x)) << SDHC_BLKATTR_BLKCNT_SHIFT)) & SDHC_BLKATTR_BLKCNT_MASK) - -/*! @name CMDARG - Command Argument register */ -#define SDHC_CMDARG_CMDARG_MASK (0xFFFFFFFFU) -#define SDHC_CMDARG_CMDARG_SHIFT (0U) -#define SDHC_CMDARG_CMDARG(x) (((uint32_t)(((uint32_t)(x)) << SDHC_CMDARG_CMDARG_SHIFT)) & SDHC_CMDARG_CMDARG_MASK) - -/*! @name XFERTYP - Transfer Type register */ -#define SDHC_XFERTYP_DMAEN_MASK (0x1U) -#define SDHC_XFERTYP_DMAEN_SHIFT (0U) -#define SDHC_XFERTYP_DMAEN(x) (((uint32_t)(((uint32_t)(x)) << SDHC_XFERTYP_DMAEN_SHIFT)) & SDHC_XFERTYP_DMAEN_MASK) -#define SDHC_XFERTYP_BCEN_MASK (0x2U) -#define SDHC_XFERTYP_BCEN_SHIFT (1U) -#define SDHC_XFERTYP_BCEN(x) (((uint32_t)(((uint32_t)(x)) << SDHC_XFERTYP_BCEN_SHIFT)) & SDHC_XFERTYP_BCEN_MASK) -#define SDHC_XFERTYP_AC12EN_MASK (0x4U) -#define SDHC_XFERTYP_AC12EN_SHIFT (2U) -#define SDHC_XFERTYP_AC12EN(x) (((uint32_t)(((uint32_t)(x)) << SDHC_XFERTYP_AC12EN_SHIFT)) & SDHC_XFERTYP_AC12EN_MASK) -#define SDHC_XFERTYP_DTDSEL_MASK (0x10U) -#define SDHC_XFERTYP_DTDSEL_SHIFT (4U) -#define SDHC_XFERTYP_DTDSEL(x) (((uint32_t)(((uint32_t)(x)) << SDHC_XFERTYP_DTDSEL_SHIFT)) & SDHC_XFERTYP_DTDSEL_MASK) -#define SDHC_XFERTYP_MSBSEL_MASK (0x20U) -#define SDHC_XFERTYP_MSBSEL_SHIFT (5U) -#define SDHC_XFERTYP_MSBSEL(x) (((uint32_t)(((uint32_t)(x)) << SDHC_XFERTYP_MSBSEL_SHIFT)) & SDHC_XFERTYP_MSBSEL_MASK) -#define SDHC_XFERTYP_RSPTYP_MASK (0x30000U) -#define SDHC_XFERTYP_RSPTYP_SHIFT (16U) -#define SDHC_XFERTYP_RSPTYP(x) (((uint32_t)(((uint32_t)(x)) << SDHC_XFERTYP_RSPTYP_SHIFT)) & SDHC_XFERTYP_RSPTYP_MASK) -#define SDHC_XFERTYP_CCCEN_MASK (0x80000U) -#define SDHC_XFERTYP_CCCEN_SHIFT (19U) -#define SDHC_XFERTYP_CCCEN(x) (((uint32_t)(((uint32_t)(x)) << SDHC_XFERTYP_CCCEN_SHIFT)) & SDHC_XFERTYP_CCCEN_MASK) -#define SDHC_XFERTYP_CICEN_MASK (0x100000U) -#define SDHC_XFERTYP_CICEN_SHIFT (20U) -#define SDHC_XFERTYP_CICEN(x) (((uint32_t)(((uint32_t)(x)) << SDHC_XFERTYP_CICEN_SHIFT)) & SDHC_XFERTYP_CICEN_MASK) -#define SDHC_XFERTYP_DPSEL_MASK (0x200000U) -#define SDHC_XFERTYP_DPSEL_SHIFT (21U) -#define SDHC_XFERTYP_DPSEL(x) (((uint32_t)(((uint32_t)(x)) << SDHC_XFERTYP_DPSEL_SHIFT)) & SDHC_XFERTYP_DPSEL_MASK) -#define SDHC_XFERTYP_CMDTYP_MASK (0xC00000U) -#define SDHC_XFERTYP_CMDTYP_SHIFT (22U) -#define SDHC_XFERTYP_CMDTYP(x) (((uint32_t)(((uint32_t)(x)) << SDHC_XFERTYP_CMDTYP_SHIFT)) & SDHC_XFERTYP_CMDTYP_MASK) -#define SDHC_XFERTYP_CMDINX_MASK (0x3F000000U) -#define SDHC_XFERTYP_CMDINX_SHIFT (24U) -#define SDHC_XFERTYP_CMDINX(x) (((uint32_t)(((uint32_t)(x)) << SDHC_XFERTYP_CMDINX_SHIFT)) & SDHC_XFERTYP_CMDINX_MASK) - -/*! @name CMDRSP - Command Response 0..Command Response 3 */ -#define SDHC_CMDRSP_CMDRSP0_MASK (0xFFFFFFFFU) -#define SDHC_CMDRSP_CMDRSP0_SHIFT (0U) -#define SDHC_CMDRSP_CMDRSP0(x) (((uint32_t)(((uint32_t)(x)) << SDHC_CMDRSP_CMDRSP0_SHIFT)) & SDHC_CMDRSP_CMDRSP0_MASK) -#define SDHC_CMDRSP_CMDRSP1_MASK (0xFFFFFFFFU) -#define SDHC_CMDRSP_CMDRSP1_SHIFT (0U) -#define SDHC_CMDRSP_CMDRSP1(x) (((uint32_t)(((uint32_t)(x)) << SDHC_CMDRSP_CMDRSP1_SHIFT)) & SDHC_CMDRSP_CMDRSP1_MASK) -#define SDHC_CMDRSP_CMDRSP2_MASK (0xFFFFFFFFU) -#define SDHC_CMDRSP_CMDRSP2_SHIFT (0U) -#define SDHC_CMDRSP_CMDRSP2(x) (((uint32_t)(((uint32_t)(x)) << SDHC_CMDRSP_CMDRSP2_SHIFT)) & SDHC_CMDRSP_CMDRSP2_MASK) -#define SDHC_CMDRSP_CMDRSP3_MASK (0xFFFFFFFFU) -#define SDHC_CMDRSP_CMDRSP3_SHIFT (0U) -#define SDHC_CMDRSP_CMDRSP3(x) (((uint32_t)(((uint32_t)(x)) << SDHC_CMDRSP_CMDRSP3_SHIFT)) & SDHC_CMDRSP_CMDRSP3_MASK) - -/* The count of SDHC_CMDRSP */ -#define SDHC_CMDRSP_COUNT (4U) - -/*! @name DATPORT - Buffer Data Port register */ -#define SDHC_DATPORT_DATCONT_MASK (0xFFFFFFFFU) -#define SDHC_DATPORT_DATCONT_SHIFT (0U) -#define SDHC_DATPORT_DATCONT(x) (((uint32_t)(((uint32_t)(x)) << SDHC_DATPORT_DATCONT_SHIFT)) & SDHC_DATPORT_DATCONT_MASK) - -/*! @name PRSSTAT - Present State register */ -#define SDHC_PRSSTAT_CIHB_MASK (0x1U) -#define SDHC_PRSSTAT_CIHB_SHIFT (0U) -#define SDHC_PRSSTAT_CIHB(x) (((uint32_t)(((uint32_t)(x)) << SDHC_PRSSTAT_CIHB_SHIFT)) & SDHC_PRSSTAT_CIHB_MASK) -#define SDHC_PRSSTAT_CDIHB_MASK (0x2U) -#define SDHC_PRSSTAT_CDIHB_SHIFT (1U) -#define SDHC_PRSSTAT_CDIHB(x) (((uint32_t)(((uint32_t)(x)) << SDHC_PRSSTAT_CDIHB_SHIFT)) & SDHC_PRSSTAT_CDIHB_MASK) -#define SDHC_PRSSTAT_DLA_MASK (0x4U) -#define SDHC_PRSSTAT_DLA_SHIFT (2U) -#define SDHC_PRSSTAT_DLA(x) (((uint32_t)(((uint32_t)(x)) << SDHC_PRSSTAT_DLA_SHIFT)) & SDHC_PRSSTAT_DLA_MASK) -#define SDHC_PRSSTAT_SDSTB_MASK (0x8U) -#define SDHC_PRSSTAT_SDSTB_SHIFT (3U) -#define SDHC_PRSSTAT_SDSTB(x) (((uint32_t)(((uint32_t)(x)) << SDHC_PRSSTAT_SDSTB_SHIFT)) & SDHC_PRSSTAT_SDSTB_MASK) -#define SDHC_PRSSTAT_IPGOFF_MASK (0x10U) -#define SDHC_PRSSTAT_IPGOFF_SHIFT (4U) -#define SDHC_PRSSTAT_IPGOFF(x) (((uint32_t)(((uint32_t)(x)) << SDHC_PRSSTAT_IPGOFF_SHIFT)) & SDHC_PRSSTAT_IPGOFF_MASK) -#define SDHC_PRSSTAT_HCKOFF_MASK (0x20U) -#define SDHC_PRSSTAT_HCKOFF_SHIFT (5U) -#define SDHC_PRSSTAT_HCKOFF(x) (((uint32_t)(((uint32_t)(x)) << SDHC_PRSSTAT_HCKOFF_SHIFT)) & SDHC_PRSSTAT_HCKOFF_MASK) -#define SDHC_PRSSTAT_PEROFF_MASK (0x40U) -#define SDHC_PRSSTAT_PEROFF_SHIFT (6U) -#define SDHC_PRSSTAT_PEROFF(x) (((uint32_t)(((uint32_t)(x)) << SDHC_PRSSTAT_PEROFF_SHIFT)) & SDHC_PRSSTAT_PEROFF_MASK) -#define SDHC_PRSSTAT_SDOFF_MASK (0x80U) -#define SDHC_PRSSTAT_SDOFF_SHIFT (7U) -#define SDHC_PRSSTAT_SDOFF(x) (((uint32_t)(((uint32_t)(x)) << SDHC_PRSSTAT_SDOFF_SHIFT)) & SDHC_PRSSTAT_SDOFF_MASK) -#define SDHC_PRSSTAT_WTA_MASK (0x100U) -#define SDHC_PRSSTAT_WTA_SHIFT (8U) -#define SDHC_PRSSTAT_WTA(x) (((uint32_t)(((uint32_t)(x)) << SDHC_PRSSTAT_WTA_SHIFT)) & SDHC_PRSSTAT_WTA_MASK) -#define SDHC_PRSSTAT_RTA_MASK (0x200U) -#define SDHC_PRSSTAT_RTA_SHIFT (9U) -#define SDHC_PRSSTAT_RTA(x) (((uint32_t)(((uint32_t)(x)) << SDHC_PRSSTAT_RTA_SHIFT)) & SDHC_PRSSTAT_RTA_MASK) -#define SDHC_PRSSTAT_BWEN_MASK (0x400U) -#define SDHC_PRSSTAT_BWEN_SHIFT (10U) -#define SDHC_PRSSTAT_BWEN(x) (((uint32_t)(((uint32_t)(x)) << SDHC_PRSSTAT_BWEN_SHIFT)) & SDHC_PRSSTAT_BWEN_MASK) -#define SDHC_PRSSTAT_BREN_MASK (0x800U) -#define SDHC_PRSSTAT_BREN_SHIFT (11U) -#define SDHC_PRSSTAT_BREN(x) (((uint32_t)(((uint32_t)(x)) << SDHC_PRSSTAT_BREN_SHIFT)) & SDHC_PRSSTAT_BREN_MASK) -#define SDHC_PRSSTAT_CINS_MASK (0x10000U) -#define SDHC_PRSSTAT_CINS_SHIFT (16U) -#define SDHC_PRSSTAT_CINS(x) (((uint32_t)(((uint32_t)(x)) << SDHC_PRSSTAT_CINS_SHIFT)) & SDHC_PRSSTAT_CINS_MASK) -#define SDHC_PRSSTAT_CLSL_MASK (0x800000U) -#define SDHC_PRSSTAT_CLSL_SHIFT (23U) -#define SDHC_PRSSTAT_CLSL(x) (((uint32_t)(((uint32_t)(x)) << SDHC_PRSSTAT_CLSL_SHIFT)) & SDHC_PRSSTAT_CLSL_MASK) -#define SDHC_PRSSTAT_DLSL_MASK (0xFF000000U) -#define SDHC_PRSSTAT_DLSL_SHIFT (24U) -#define SDHC_PRSSTAT_DLSL(x) (((uint32_t)(((uint32_t)(x)) << SDHC_PRSSTAT_DLSL_SHIFT)) & SDHC_PRSSTAT_DLSL_MASK) - -/*! @name PROCTL - Protocol Control register */ -#define SDHC_PROCTL_LCTL_MASK (0x1U) -#define SDHC_PROCTL_LCTL_SHIFT (0U) -#define SDHC_PROCTL_LCTL(x) (((uint32_t)(((uint32_t)(x)) << SDHC_PROCTL_LCTL_SHIFT)) & SDHC_PROCTL_LCTL_MASK) -#define SDHC_PROCTL_DTW_MASK (0x6U) -#define SDHC_PROCTL_DTW_SHIFT (1U) -#define SDHC_PROCTL_DTW(x) (((uint32_t)(((uint32_t)(x)) << SDHC_PROCTL_DTW_SHIFT)) & SDHC_PROCTL_DTW_MASK) -#define SDHC_PROCTL_D3CD_MASK (0x8U) -#define SDHC_PROCTL_D3CD_SHIFT (3U) -#define SDHC_PROCTL_D3CD(x) (((uint32_t)(((uint32_t)(x)) << SDHC_PROCTL_D3CD_SHIFT)) & SDHC_PROCTL_D3CD_MASK) -#define SDHC_PROCTL_EMODE_MASK (0x30U) -#define SDHC_PROCTL_EMODE_SHIFT (4U) -#define SDHC_PROCTL_EMODE(x) (((uint32_t)(((uint32_t)(x)) << SDHC_PROCTL_EMODE_SHIFT)) & SDHC_PROCTL_EMODE_MASK) -#define SDHC_PROCTL_CDTL_MASK (0x40U) -#define SDHC_PROCTL_CDTL_SHIFT (6U) -#define SDHC_PROCTL_CDTL(x) (((uint32_t)(((uint32_t)(x)) << SDHC_PROCTL_CDTL_SHIFT)) & SDHC_PROCTL_CDTL_MASK) -#define SDHC_PROCTL_CDSS_MASK (0x80U) -#define SDHC_PROCTL_CDSS_SHIFT (7U) -#define SDHC_PROCTL_CDSS(x) (((uint32_t)(((uint32_t)(x)) << SDHC_PROCTL_CDSS_SHIFT)) & SDHC_PROCTL_CDSS_MASK) -#define SDHC_PROCTL_DMAS_MASK (0x300U) -#define SDHC_PROCTL_DMAS_SHIFT (8U) -#define SDHC_PROCTL_DMAS(x) (((uint32_t)(((uint32_t)(x)) << SDHC_PROCTL_DMAS_SHIFT)) & SDHC_PROCTL_DMAS_MASK) -#define SDHC_PROCTL_SABGREQ_MASK (0x10000U) -#define SDHC_PROCTL_SABGREQ_SHIFT (16U) -#define SDHC_PROCTL_SABGREQ(x) (((uint32_t)(((uint32_t)(x)) << SDHC_PROCTL_SABGREQ_SHIFT)) & SDHC_PROCTL_SABGREQ_MASK) -#define SDHC_PROCTL_CREQ_MASK (0x20000U) -#define SDHC_PROCTL_CREQ_SHIFT (17U) -#define SDHC_PROCTL_CREQ(x) (((uint32_t)(((uint32_t)(x)) << SDHC_PROCTL_CREQ_SHIFT)) & SDHC_PROCTL_CREQ_MASK) -#define SDHC_PROCTL_RWCTL_MASK (0x40000U) -#define SDHC_PROCTL_RWCTL_SHIFT (18U) -#define SDHC_PROCTL_RWCTL(x) (((uint32_t)(((uint32_t)(x)) << SDHC_PROCTL_RWCTL_SHIFT)) & SDHC_PROCTL_RWCTL_MASK) -#define SDHC_PROCTL_IABG_MASK (0x80000U) -#define SDHC_PROCTL_IABG_SHIFT (19U) -#define SDHC_PROCTL_IABG(x) (((uint32_t)(((uint32_t)(x)) << SDHC_PROCTL_IABG_SHIFT)) & SDHC_PROCTL_IABG_MASK) -#define SDHC_PROCTL_WECINT_MASK (0x1000000U) -#define SDHC_PROCTL_WECINT_SHIFT (24U) -#define SDHC_PROCTL_WECINT(x) (((uint32_t)(((uint32_t)(x)) << SDHC_PROCTL_WECINT_SHIFT)) & SDHC_PROCTL_WECINT_MASK) -#define SDHC_PROCTL_WECINS_MASK (0x2000000U) -#define SDHC_PROCTL_WECINS_SHIFT (25U) -#define SDHC_PROCTL_WECINS(x) (((uint32_t)(((uint32_t)(x)) << SDHC_PROCTL_WECINS_SHIFT)) & SDHC_PROCTL_WECINS_MASK) -#define SDHC_PROCTL_WECRM_MASK (0x4000000U) -#define SDHC_PROCTL_WECRM_SHIFT (26U) -#define SDHC_PROCTL_WECRM(x) (((uint32_t)(((uint32_t)(x)) << SDHC_PROCTL_WECRM_SHIFT)) & SDHC_PROCTL_WECRM_MASK) - -/*! @name SYSCTL - System Control register */ -#define SDHC_SYSCTL_IPGEN_MASK (0x1U) -#define SDHC_SYSCTL_IPGEN_SHIFT (0U) -#define SDHC_SYSCTL_IPGEN(x) (((uint32_t)(((uint32_t)(x)) << SDHC_SYSCTL_IPGEN_SHIFT)) & SDHC_SYSCTL_IPGEN_MASK) -#define SDHC_SYSCTL_HCKEN_MASK (0x2U) -#define SDHC_SYSCTL_HCKEN_SHIFT (1U) -#define SDHC_SYSCTL_HCKEN(x) (((uint32_t)(((uint32_t)(x)) << SDHC_SYSCTL_HCKEN_SHIFT)) & SDHC_SYSCTL_HCKEN_MASK) -#define SDHC_SYSCTL_PEREN_MASK (0x4U) -#define SDHC_SYSCTL_PEREN_SHIFT (2U) -#define SDHC_SYSCTL_PEREN(x) (((uint32_t)(((uint32_t)(x)) << SDHC_SYSCTL_PEREN_SHIFT)) & SDHC_SYSCTL_PEREN_MASK) -#define SDHC_SYSCTL_SDCLKEN_MASK (0x8U) -#define SDHC_SYSCTL_SDCLKEN_SHIFT (3U) -#define SDHC_SYSCTL_SDCLKEN(x) (((uint32_t)(((uint32_t)(x)) << SDHC_SYSCTL_SDCLKEN_SHIFT)) & SDHC_SYSCTL_SDCLKEN_MASK) -#define SDHC_SYSCTL_DVS_MASK (0xF0U) -#define SDHC_SYSCTL_DVS_SHIFT (4U) -#define SDHC_SYSCTL_DVS(x) (((uint32_t)(((uint32_t)(x)) << SDHC_SYSCTL_DVS_SHIFT)) & SDHC_SYSCTL_DVS_MASK) -#define SDHC_SYSCTL_SDCLKFS_MASK (0xFF00U) -#define SDHC_SYSCTL_SDCLKFS_SHIFT (8U) -#define SDHC_SYSCTL_SDCLKFS(x) (((uint32_t)(((uint32_t)(x)) << SDHC_SYSCTL_SDCLKFS_SHIFT)) & SDHC_SYSCTL_SDCLKFS_MASK) -#define SDHC_SYSCTL_DTOCV_MASK (0xF0000U) -#define SDHC_SYSCTL_DTOCV_SHIFT (16U) -#define SDHC_SYSCTL_DTOCV(x) (((uint32_t)(((uint32_t)(x)) << SDHC_SYSCTL_DTOCV_SHIFT)) & SDHC_SYSCTL_DTOCV_MASK) -#define SDHC_SYSCTL_RSTA_MASK (0x1000000U) -#define SDHC_SYSCTL_RSTA_SHIFT (24U) -#define SDHC_SYSCTL_RSTA(x) (((uint32_t)(((uint32_t)(x)) << SDHC_SYSCTL_RSTA_SHIFT)) & SDHC_SYSCTL_RSTA_MASK) -#define SDHC_SYSCTL_RSTC_MASK (0x2000000U) -#define SDHC_SYSCTL_RSTC_SHIFT (25U) -#define SDHC_SYSCTL_RSTC(x) (((uint32_t)(((uint32_t)(x)) << SDHC_SYSCTL_RSTC_SHIFT)) & SDHC_SYSCTL_RSTC_MASK) -#define SDHC_SYSCTL_RSTD_MASK (0x4000000U) -#define SDHC_SYSCTL_RSTD_SHIFT (26U) -#define SDHC_SYSCTL_RSTD(x) (((uint32_t)(((uint32_t)(x)) << SDHC_SYSCTL_RSTD_SHIFT)) & SDHC_SYSCTL_RSTD_MASK) -#define SDHC_SYSCTL_INITA_MASK (0x8000000U) -#define SDHC_SYSCTL_INITA_SHIFT (27U) -#define SDHC_SYSCTL_INITA(x) (((uint32_t)(((uint32_t)(x)) << SDHC_SYSCTL_INITA_SHIFT)) & SDHC_SYSCTL_INITA_MASK) - -/*! @name IRQSTAT - Interrupt Status register */ -#define SDHC_IRQSTAT_CC_MASK (0x1U) -#define SDHC_IRQSTAT_CC_SHIFT (0U) -#define SDHC_IRQSTAT_CC(x) (((uint32_t)(((uint32_t)(x)) << SDHC_IRQSTAT_CC_SHIFT)) & SDHC_IRQSTAT_CC_MASK) -#define SDHC_IRQSTAT_TC_MASK (0x2U) -#define SDHC_IRQSTAT_TC_SHIFT (1U) -#define SDHC_IRQSTAT_TC(x) (((uint32_t)(((uint32_t)(x)) << SDHC_IRQSTAT_TC_SHIFT)) & SDHC_IRQSTAT_TC_MASK) -#define SDHC_IRQSTAT_BGE_MASK (0x4U) -#define SDHC_IRQSTAT_BGE_SHIFT (2U) -#define SDHC_IRQSTAT_BGE(x) (((uint32_t)(((uint32_t)(x)) << SDHC_IRQSTAT_BGE_SHIFT)) & SDHC_IRQSTAT_BGE_MASK) -#define SDHC_IRQSTAT_DINT_MASK (0x8U) -#define SDHC_IRQSTAT_DINT_SHIFT (3U) -#define SDHC_IRQSTAT_DINT(x) (((uint32_t)(((uint32_t)(x)) << SDHC_IRQSTAT_DINT_SHIFT)) & SDHC_IRQSTAT_DINT_MASK) -#define SDHC_IRQSTAT_BWR_MASK (0x10U) -#define SDHC_IRQSTAT_BWR_SHIFT (4U) -#define SDHC_IRQSTAT_BWR(x) (((uint32_t)(((uint32_t)(x)) << SDHC_IRQSTAT_BWR_SHIFT)) & SDHC_IRQSTAT_BWR_MASK) -#define SDHC_IRQSTAT_BRR_MASK (0x20U) -#define SDHC_IRQSTAT_BRR_SHIFT (5U) -#define SDHC_IRQSTAT_BRR(x) (((uint32_t)(((uint32_t)(x)) << SDHC_IRQSTAT_BRR_SHIFT)) & SDHC_IRQSTAT_BRR_MASK) -#define SDHC_IRQSTAT_CINS_MASK (0x40U) -#define SDHC_IRQSTAT_CINS_SHIFT (6U) -#define SDHC_IRQSTAT_CINS(x) (((uint32_t)(((uint32_t)(x)) << SDHC_IRQSTAT_CINS_SHIFT)) & SDHC_IRQSTAT_CINS_MASK) -#define SDHC_IRQSTAT_CRM_MASK (0x80U) -#define SDHC_IRQSTAT_CRM_SHIFT (7U) -#define SDHC_IRQSTAT_CRM(x) (((uint32_t)(((uint32_t)(x)) << SDHC_IRQSTAT_CRM_SHIFT)) & SDHC_IRQSTAT_CRM_MASK) -#define SDHC_IRQSTAT_CINT_MASK (0x100U) -#define SDHC_IRQSTAT_CINT_SHIFT (8U) -#define SDHC_IRQSTAT_CINT(x) (((uint32_t)(((uint32_t)(x)) << SDHC_IRQSTAT_CINT_SHIFT)) & SDHC_IRQSTAT_CINT_MASK) -#define SDHC_IRQSTAT_CTOE_MASK (0x10000U) -#define SDHC_IRQSTAT_CTOE_SHIFT (16U) -#define SDHC_IRQSTAT_CTOE(x) (((uint32_t)(((uint32_t)(x)) << SDHC_IRQSTAT_CTOE_SHIFT)) & SDHC_IRQSTAT_CTOE_MASK) -#define SDHC_IRQSTAT_CCE_MASK (0x20000U) -#define SDHC_IRQSTAT_CCE_SHIFT (17U) -#define SDHC_IRQSTAT_CCE(x) (((uint32_t)(((uint32_t)(x)) << SDHC_IRQSTAT_CCE_SHIFT)) & SDHC_IRQSTAT_CCE_MASK) -#define SDHC_IRQSTAT_CEBE_MASK (0x40000U) -#define SDHC_IRQSTAT_CEBE_SHIFT (18U) -#define SDHC_IRQSTAT_CEBE(x) (((uint32_t)(((uint32_t)(x)) << SDHC_IRQSTAT_CEBE_SHIFT)) & SDHC_IRQSTAT_CEBE_MASK) -#define SDHC_IRQSTAT_CIE_MASK (0x80000U) -#define SDHC_IRQSTAT_CIE_SHIFT (19U) -#define SDHC_IRQSTAT_CIE(x) (((uint32_t)(((uint32_t)(x)) << SDHC_IRQSTAT_CIE_SHIFT)) & SDHC_IRQSTAT_CIE_MASK) -#define SDHC_IRQSTAT_DTOE_MASK (0x100000U) -#define SDHC_IRQSTAT_DTOE_SHIFT (20U) -#define SDHC_IRQSTAT_DTOE(x) (((uint32_t)(((uint32_t)(x)) << SDHC_IRQSTAT_DTOE_SHIFT)) & SDHC_IRQSTAT_DTOE_MASK) -#define SDHC_IRQSTAT_DCE_MASK (0x200000U) -#define SDHC_IRQSTAT_DCE_SHIFT (21U) -#define SDHC_IRQSTAT_DCE(x) (((uint32_t)(((uint32_t)(x)) << SDHC_IRQSTAT_DCE_SHIFT)) & SDHC_IRQSTAT_DCE_MASK) -#define SDHC_IRQSTAT_DEBE_MASK (0x400000U) -#define SDHC_IRQSTAT_DEBE_SHIFT (22U) -#define SDHC_IRQSTAT_DEBE(x) (((uint32_t)(((uint32_t)(x)) << SDHC_IRQSTAT_DEBE_SHIFT)) & SDHC_IRQSTAT_DEBE_MASK) -#define SDHC_IRQSTAT_AC12E_MASK (0x1000000U) -#define SDHC_IRQSTAT_AC12E_SHIFT (24U) -#define SDHC_IRQSTAT_AC12E(x) (((uint32_t)(((uint32_t)(x)) << SDHC_IRQSTAT_AC12E_SHIFT)) & SDHC_IRQSTAT_AC12E_MASK) -#define SDHC_IRQSTAT_DMAE_MASK (0x10000000U) -#define SDHC_IRQSTAT_DMAE_SHIFT (28U) -#define SDHC_IRQSTAT_DMAE(x) (((uint32_t)(((uint32_t)(x)) << SDHC_IRQSTAT_DMAE_SHIFT)) & SDHC_IRQSTAT_DMAE_MASK) - -/*! @name IRQSTATEN - Interrupt Status Enable register */ -#define SDHC_IRQSTATEN_CCSEN_MASK (0x1U) -#define SDHC_IRQSTATEN_CCSEN_SHIFT (0U) -#define SDHC_IRQSTATEN_CCSEN(x) (((uint32_t)(((uint32_t)(x)) << SDHC_IRQSTATEN_CCSEN_SHIFT)) & SDHC_IRQSTATEN_CCSEN_MASK) -#define SDHC_IRQSTATEN_TCSEN_MASK (0x2U) -#define SDHC_IRQSTATEN_TCSEN_SHIFT (1U) -#define SDHC_IRQSTATEN_TCSEN(x) (((uint32_t)(((uint32_t)(x)) << SDHC_IRQSTATEN_TCSEN_SHIFT)) & SDHC_IRQSTATEN_TCSEN_MASK) -#define SDHC_IRQSTATEN_BGESEN_MASK (0x4U) -#define SDHC_IRQSTATEN_BGESEN_SHIFT (2U) -#define SDHC_IRQSTATEN_BGESEN(x) (((uint32_t)(((uint32_t)(x)) << SDHC_IRQSTATEN_BGESEN_SHIFT)) & SDHC_IRQSTATEN_BGESEN_MASK) -#define SDHC_IRQSTATEN_DINTSEN_MASK (0x8U) -#define SDHC_IRQSTATEN_DINTSEN_SHIFT (3U) -#define SDHC_IRQSTATEN_DINTSEN(x) (((uint32_t)(((uint32_t)(x)) << SDHC_IRQSTATEN_DINTSEN_SHIFT)) & SDHC_IRQSTATEN_DINTSEN_MASK) -#define SDHC_IRQSTATEN_BWRSEN_MASK (0x10U) -#define SDHC_IRQSTATEN_BWRSEN_SHIFT (4U) -#define SDHC_IRQSTATEN_BWRSEN(x) (((uint32_t)(((uint32_t)(x)) << SDHC_IRQSTATEN_BWRSEN_SHIFT)) & SDHC_IRQSTATEN_BWRSEN_MASK) -#define SDHC_IRQSTATEN_BRRSEN_MASK (0x20U) -#define SDHC_IRQSTATEN_BRRSEN_SHIFT (5U) -#define SDHC_IRQSTATEN_BRRSEN(x) (((uint32_t)(((uint32_t)(x)) << SDHC_IRQSTATEN_BRRSEN_SHIFT)) & SDHC_IRQSTATEN_BRRSEN_MASK) -#define SDHC_IRQSTATEN_CINSEN_MASK (0x40U) -#define SDHC_IRQSTATEN_CINSEN_SHIFT (6U) -#define SDHC_IRQSTATEN_CINSEN(x) (((uint32_t)(((uint32_t)(x)) << SDHC_IRQSTATEN_CINSEN_SHIFT)) & SDHC_IRQSTATEN_CINSEN_MASK) -#define SDHC_IRQSTATEN_CRMSEN_MASK (0x80U) -#define SDHC_IRQSTATEN_CRMSEN_SHIFT (7U) -#define SDHC_IRQSTATEN_CRMSEN(x) (((uint32_t)(((uint32_t)(x)) << SDHC_IRQSTATEN_CRMSEN_SHIFT)) & SDHC_IRQSTATEN_CRMSEN_MASK) -#define SDHC_IRQSTATEN_CINTSEN_MASK (0x100U) -#define SDHC_IRQSTATEN_CINTSEN_SHIFT (8U) -#define SDHC_IRQSTATEN_CINTSEN(x) (((uint32_t)(((uint32_t)(x)) << SDHC_IRQSTATEN_CINTSEN_SHIFT)) & SDHC_IRQSTATEN_CINTSEN_MASK) -#define SDHC_IRQSTATEN_CTOESEN_MASK (0x10000U) -#define SDHC_IRQSTATEN_CTOESEN_SHIFT (16U) -#define SDHC_IRQSTATEN_CTOESEN(x) (((uint32_t)(((uint32_t)(x)) << SDHC_IRQSTATEN_CTOESEN_SHIFT)) & SDHC_IRQSTATEN_CTOESEN_MASK) -#define SDHC_IRQSTATEN_CCESEN_MASK (0x20000U) -#define SDHC_IRQSTATEN_CCESEN_SHIFT (17U) -#define SDHC_IRQSTATEN_CCESEN(x) (((uint32_t)(((uint32_t)(x)) << SDHC_IRQSTATEN_CCESEN_SHIFT)) & SDHC_IRQSTATEN_CCESEN_MASK) -#define SDHC_IRQSTATEN_CEBESEN_MASK (0x40000U) -#define SDHC_IRQSTATEN_CEBESEN_SHIFT (18U) -#define SDHC_IRQSTATEN_CEBESEN(x) (((uint32_t)(((uint32_t)(x)) << SDHC_IRQSTATEN_CEBESEN_SHIFT)) & SDHC_IRQSTATEN_CEBESEN_MASK) -#define SDHC_IRQSTATEN_CIESEN_MASK (0x80000U) -#define SDHC_IRQSTATEN_CIESEN_SHIFT (19U) -#define SDHC_IRQSTATEN_CIESEN(x) (((uint32_t)(((uint32_t)(x)) << SDHC_IRQSTATEN_CIESEN_SHIFT)) & SDHC_IRQSTATEN_CIESEN_MASK) -#define SDHC_IRQSTATEN_DTOESEN_MASK (0x100000U) -#define SDHC_IRQSTATEN_DTOESEN_SHIFT (20U) -#define SDHC_IRQSTATEN_DTOESEN(x) (((uint32_t)(((uint32_t)(x)) << SDHC_IRQSTATEN_DTOESEN_SHIFT)) & SDHC_IRQSTATEN_DTOESEN_MASK) -#define SDHC_IRQSTATEN_DCESEN_MASK (0x200000U) -#define SDHC_IRQSTATEN_DCESEN_SHIFT (21U) -#define SDHC_IRQSTATEN_DCESEN(x) (((uint32_t)(((uint32_t)(x)) << SDHC_IRQSTATEN_DCESEN_SHIFT)) & SDHC_IRQSTATEN_DCESEN_MASK) -#define SDHC_IRQSTATEN_DEBESEN_MASK (0x400000U) -#define SDHC_IRQSTATEN_DEBESEN_SHIFT (22U) -#define SDHC_IRQSTATEN_DEBESEN(x) (((uint32_t)(((uint32_t)(x)) << SDHC_IRQSTATEN_DEBESEN_SHIFT)) & SDHC_IRQSTATEN_DEBESEN_MASK) -#define SDHC_IRQSTATEN_AC12ESEN_MASK (0x1000000U) -#define SDHC_IRQSTATEN_AC12ESEN_SHIFT (24U) -#define SDHC_IRQSTATEN_AC12ESEN(x) (((uint32_t)(((uint32_t)(x)) << SDHC_IRQSTATEN_AC12ESEN_SHIFT)) & SDHC_IRQSTATEN_AC12ESEN_MASK) -#define SDHC_IRQSTATEN_DMAESEN_MASK (0x10000000U) -#define SDHC_IRQSTATEN_DMAESEN_SHIFT (28U) -#define SDHC_IRQSTATEN_DMAESEN(x) (((uint32_t)(((uint32_t)(x)) << SDHC_IRQSTATEN_DMAESEN_SHIFT)) & SDHC_IRQSTATEN_DMAESEN_MASK) - -/*! @name IRQSIGEN - Interrupt Signal Enable register */ -#define SDHC_IRQSIGEN_CCIEN_MASK (0x1U) -#define SDHC_IRQSIGEN_CCIEN_SHIFT (0U) -#define SDHC_IRQSIGEN_CCIEN(x) (((uint32_t)(((uint32_t)(x)) << SDHC_IRQSIGEN_CCIEN_SHIFT)) & SDHC_IRQSIGEN_CCIEN_MASK) -#define SDHC_IRQSIGEN_TCIEN_MASK (0x2U) -#define SDHC_IRQSIGEN_TCIEN_SHIFT (1U) -#define SDHC_IRQSIGEN_TCIEN(x) (((uint32_t)(((uint32_t)(x)) << SDHC_IRQSIGEN_TCIEN_SHIFT)) & SDHC_IRQSIGEN_TCIEN_MASK) -#define SDHC_IRQSIGEN_BGEIEN_MASK (0x4U) -#define SDHC_IRQSIGEN_BGEIEN_SHIFT (2U) -#define SDHC_IRQSIGEN_BGEIEN(x) (((uint32_t)(((uint32_t)(x)) << SDHC_IRQSIGEN_BGEIEN_SHIFT)) & SDHC_IRQSIGEN_BGEIEN_MASK) -#define SDHC_IRQSIGEN_DINTIEN_MASK (0x8U) -#define SDHC_IRQSIGEN_DINTIEN_SHIFT (3U) -#define SDHC_IRQSIGEN_DINTIEN(x) (((uint32_t)(((uint32_t)(x)) << SDHC_IRQSIGEN_DINTIEN_SHIFT)) & SDHC_IRQSIGEN_DINTIEN_MASK) -#define SDHC_IRQSIGEN_BWRIEN_MASK (0x10U) -#define SDHC_IRQSIGEN_BWRIEN_SHIFT (4U) -#define SDHC_IRQSIGEN_BWRIEN(x) (((uint32_t)(((uint32_t)(x)) << SDHC_IRQSIGEN_BWRIEN_SHIFT)) & SDHC_IRQSIGEN_BWRIEN_MASK) -#define SDHC_IRQSIGEN_BRRIEN_MASK (0x20U) -#define SDHC_IRQSIGEN_BRRIEN_SHIFT (5U) -#define SDHC_IRQSIGEN_BRRIEN(x) (((uint32_t)(((uint32_t)(x)) << SDHC_IRQSIGEN_BRRIEN_SHIFT)) & SDHC_IRQSIGEN_BRRIEN_MASK) -#define SDHC_IRQSIGEN_CINSIEN_MASK (0x40U) -#define SDHC_IRQSIGEN_CINSIEN_SHIFT (6U) -#define SDHC_IRQSIGEN_CINSIEN(x) (((uint32_t)(((uint32_t)(x)) << SDHC_IRQSIGEN_CINSIEN_SHIFT)) & SDHC_IRQSIGEN_CINSIEN_MASK) -#define SDHC_IRQSIGEN_CRMIEN_MASK (0x80U) -#define SDHC_IRQSIGEN_CRMIEN_SHIFT (7U) -#define SDHC_IRQSIGEN_CRMIEN(x) (((uint32_t)(((uint32_t)(x)) << SDHC_IRQSIGEN_CRMIEN_SHIFT)) & SDHC_IRQSIGEN_CRMIEN_MASK) -#define SDHC_IRQSIGEN_CINTIEN_MASK (0x100U) -#define SDHC_IRQSIGEN_CINTIEN_SHIFT (8U) -#define SDHC_IRQSIGEN_CINTIEN(x) (((uint32_t)(((uint32_t)(x)) << SDHC_IRQSIGEN_CINTIEN_SHIFT)) & SDHC_IRQSIGEN_CINTIEN_MASK) -#define SDHC_IRQSIGEN_CTOEIEN_MASK (0x10000U) -#define SDHC_IRQSIGEN_CTOEIEN_SHIFT (16U) -#define SDHC_IRQSIGEN_CTOEIEN(x) (((uint32_t)(((uint32_t)(x)) << SDHC_IRQSIGEN_CTOEIEN_SHIFT)) & SDHC_IRQSIGEN_CTOEIEN_MASK) -#define SDHC_IRQSIGEN_CCEIEN_MASK (0x20000U) -#define SDHC_IRQSIGEN_CCEIEN_SHIFT (17U) -#define SDHC_IRQSIGEN_CCEIEN(x) (((uint32_t)(((uint32_t)(x)) << SDHC_IRQSIGEN_CCEIEN_SHIFT)) & SDHC_IRQSIGEN_CCEIEN_MASK) -#define SDHC_IRQSIGEN_CEBEIEN_MASK (0x40000U) -#define SDHC_IRQSIGEN_CEBEIEN_SHIFT (18U) -#define SDHC_IRQSIGEN_CEBEIEN(x) (((uint32_t)(((uint32_t)(x)) << SDHC_IRQSIGEN_CEBEIEN_SHIFT)) & SDHC_IRQSIGEN_CEBEIEN_MASK) -#define SDHC_IRQSIGEN_CIEIEN_MASK (0x80000U) -#define SDHC_IRQSIGEN_CIEIEN_SHIFT (19U) -#define SDHC_IRQSIGEN_CIEIEN(x) (((uint32_t)(((uint32_t)(x)) << SDHC_IRQSIGEN_CIEIEN_SHIFT)) & SDHC_IRQSIGEN_CIEIEN_MASK) -#define SDHC_IRQSIGEN_DTOEIEN_MASK (0x100000U) -#define SDHC_IRQSIGEN_DTOEIEN_SHIFT (20U) -#define SDHC_IRQSIGEN_DTOEIEN(x) (((uint32_t)(((uint32_t)(x)) << SDHC_IRQSIGEN_DTOEIEN_SHIFT)) & SDHC_IRQSIGEN_DTOEIEN_MASK) -#define SDHC_IRQSIGEN_DCEIEN_MASK (0x200000U) -#define SDHC_IRQSIGEN_DCEIEN_SHIFT (21U) -#define SDHC_IRQSIGEN_DCEIEN(x) (((uint32_t)(((uint32_t)(x)) << SDHC_IRQSIGEN_DCEIEN_SHIFT)) & SDHC_IRQSIGEN_DCEIEN_MASK) -#define SDHC_IRQSIGEN_DEBEIEN_MASK (0x400000U) -#define SDHC_IRQSIGEN_DEBEIEN_SHIFT (22U) -#define SDHC_IRQSIGEN_DEBEIEN(x) (((uint32_t)(((uint32_t)(x)) << SDHC_IRQSIGEN_DEBEIEN_SHIFT)) & SDHC_IRQSIGEN_DEBEIEN_MASK) -#define SDHC_IRQSIGEN_AC12EIEN_MASK (0x1000000U) -#define SDHC_IRQSIGEN_AC12EIEN_SHIFT (24U) -#define SDHC_IRQSIGEN_AC12EIEN(x) (((uint32_t)(((uint32_t)(x)) << SDHC_IRQSIGEN_AC12EIEN_SHIFT)) & SDHC_IRQSIGEN_AC12EIEN_MASK) -#define SDHC_IRQSIGEN_DMAEIEN_MASK (0x10000000U) -#define SDHC_IRQSIGEN_DMAEIEN_SHIFT (28U) -#define SDHC_IRQSIGEN_DMAEIEN(x) (((uint32_t)(((uint32_t)(x)) << SDHC_IRQSIGEN_DMAEIEN_SHIFT)) & SDHC_IRQSIGEN_DMAEIEN_MASK) - -/*! @name AC12ERR - Auto CMD12 Error Status Register */ -#define SDHC_AC12ERR_AC12NE_MASK (0x1U) -#define SDHC_AC12ERR_AC12NE_SHIFT (0U) -#define SDHC_AC12ERR_AC12NE(x) (((uint32_t)(((uint32_t)(x)) << SDHC_AC12ERR_AC12NE_SHIFT)) & SDHC_AC12ERR_AC12NE_MASK) -#define SDHC_AC12ERR_AC12TOE_MASK (0x2U) -#define SDHC_AC12ERR_AC12TOE_SHIFT (1U) -#define SDHC_AC12ERR_AC12TOE(x) (((uint32_t)(((uint32_t)(x)) << SDHC_AC12ERR_AC12TOE_SHIFT)) & SDHC_AC12ERR_AC12TOE_MASK) -#define SDHC_AC12ERR_AC12EBE_MASK (0x4U) -#define SDHC_AC12ERR_AC12EBE_SHIFT (2U) -#define SDHC_AC12ERR_AC12EBE(x) (((uint32_t)(((uint32_t)(x)) << SDHC_AC12ERR_AC12EBE_SHIFT)) & SDHC_AC12ERR_AC12EBE_MASK) -#define SDHC_AC12ERR_AC12CE_MASK (0x8U) -#define SDHC_AC12ERR_AC12CE_SHIFT (3U) -#define SDHC_AC12ERR_AC12CE(x) (((uint32_t)(((uint32_t)(x)) << SDHC_AC12ERR_AC12CE_SHIFT)) & SDHC_AC12ERR_AC12CE_MASK) -#define SDHC_AC12ERR_AC12IE_MASK (0x10U) -#define SDHC_AC12ERR_AC12IE_SHIFT (4U) -#define SDHC_AC12ERR_AC12IE(x) (((uint32_t)(((uint32_t)(x)) << SDHC_AC12ERR_AC12IE_SHIFT)) & SDHC_AC12ERR_AC12IE_MASK) -#define SDHC_AC12ERR_CNIBAC12E_MASK (0x80U) -#define SDHC_AC12ERR_CNIBAC12E_SHIFT (7U) -#define SDHC_AC12ERR_CNIBAC12E(x) (((uint32_t)(((uint32_t)(x)) << SDHC_AC12ERR_CNIBAC12E_SHIFT)) & SDHC_AC12ERR_CNIBAC12E_MASK) - -/*! @name HTCAPBLT - Host Controller Capabilities */ -#define SDHC_HTCAPBLT_MBL_MASK (0x70000U) -#define SDHC_HTCAPBLT_MBL_SHIFT (16U) -#define SDHC_HTCAPBLT_MBL(x) (((uint32_t)(((uint32_t)(x)) << SDHC_HTCAPBLT_MBL_SHIFT)) & SDHC_HTCAPBLT_MBL_MASK) -#define SDHC_HTCAPBLT_ADMAS_MASK (0x100000U) -#define SDHC_HTCAPBLT_ADMAS_SHIFT (20U) -#define SDHC_HTCAPBLT_ADMAS(x) (((uint32_t)(((uint32_t)(x)) << SDHC_HTCAPBLT_ADMAS_SHIFT)) & SDHC_HTCAPBLT_ADMAS_MASK) -#define SDHC_HTCAPBLT_HSS_MASK (0x200000U) -#define SDHC_HTCAPBLT_HSS_SHIFT (21U) -#define SDHC_HTCAPBLT_HSS(x) (((uint32_t)(((uint32_t)(x)) << SDHC_HTCAPBLT_HSS_SHIFT)) & SDHC_HTCAPBLT_HSS_MASK) -#define SDHC_HTCAPBLT_DMAS_MASK (0x400000U) -#define SDHC_HTCAPBLT_DMAS_SHIFT (22U) -#define SDHC_HTCAPBLT_DMAS(x) (((uint32_t)(((uint32_t)(x)) << SDHC_HTCAPBLT_DMAS_SHIFT)) & SDHC_HTCAPBLT_DMAS_MASK) -#define SDHC_HTCAPBLT_SRS_MASK (0x800000U) -#define SDHC_HTCAPBLT_SRS_SHIFT (23U) -#define SDHC_HTCAPBLT_SRS(x) (((uint32_t)(((uint32_t)(x)) << SDHC_HTCAPBLT_SRS_SHIFT)) & SDHC_HTCAPBLT_SRS_MASK) -#define SDHC_HTCAPBLT_VS33_MASK (0x1000000U) -#define SDHC_HTCAPBLT_VS33_SHIFT (24U) -#define SDHC_HTCAPBLT_VS33(x) (((uint32_t)(((uint32_t)(x)) << SDHC_HTCAPBLT_VS33_SHIFT)) & SDHC_HTCAPBLT_VS33_MASK) - -/*! @name WML - Watermark Level Register */ -#define SDHC_WML_RDWML_MASK (0xFFU) -#define SDHC_WML_RDWML_SHIFT (0U) -#define SDHC_WML_RDWML(x) (((uint32_t)(((uint32_t)(x)) << SDHC_WML_RDWML_SHIFT)) & SDHC_WML_RDWML_MASK) -#define SDHC_WML_WRWML_MASK (0xFF0000U) -#define SDHC_WML_WRWML_SHIFT (16U) -#define SDHC_WML_WRWML(x) (((uint32_t)(((uint32_t)(x)) << SDHC_WML_WRWML_SHIFT)) & SDHC_WML_WRWML_MASK) - -/*! @name FEVT - Force Event register */ -#define SDHC_FEVT_AC12NE_MASK (0x1U) -#define SDHC_FEVT_AC12NE_SHIFT (0U) -#define SDHC_FEVT_AC12NE(x) (((uint32_t)(((uint32_t)(x)) << SDHC_FEVT_AC12NE_SHIFT)) & SDHC_FEVT_AC12NE_MASK) -#define SDHC_FEVT_AC12TOE_MASK (0x2U) -#define SDHC_FEVT_AC12TOE_SHIFT (1U) -#define SDHC_FEVT_AC12TOE(x) (((uint32_t)(((uint32_t)(x)) << SDHC_FEVT_AC12TOE_SHIFT)) & SDHC_FEVT_AC12TOE_MASK) -#define SDHC_FEVT_AC12CE_MASK (0x4U) -#define SDHC_FEVT_AC12CE_SHIFT (2U) -#define SDHC_FEVT_AC12CE(x) (((uint32_t)(((uint32_t)(x)) << SDHC_FEVT_AC12CE_SHIFT)) & SDHC_FEVT_AC12CE_MASK) -#define SDHC_FEVT_AC12EBE_MASK (0x8U) -#define SDHC_FEVT_AC12EBE_SHIFT (3U) -#define SDHC_FEVT_AC12EBE(x) (((uint32_t)(((uint32_t)(x)) << SDHC_FEVT_AC12EBE_SHIFT)) & SDHC_FEVT_AC12EBE_MASK) -#define SDHC_FEVT_AC12IE_MASK (0x10U) -#define SDHC_FEVT_AC12IE_SHIFT (4U) -#define SDHC_FEVT_AC12IE(x) (((uint32_t)(((uint32_t)(x)) << SDHC_FEVT_AC12IE_SHIFT)) & SDHC_FEVT_AC12IE_MASK) -#define SDHC_FEVT_CNIBAC12E_MASK (0x80U) -#define SDHC_FEVT_CNIBAC12E_SHIFT (7U) -#define SDHC_FEVT_CNIBAC12E(x) (((uint32_t)(((uint32_t)(x)) << SDHC_FEVT_CNIBAC12E_SHIFT)) & SDHC_FEVT_CNIBAC12E_MASK) -#define SDHC_FEVT_CTOE_MASK (0x10000U) -#define SDHC_FEVT_CTOE_SHIFT (16U) -#define SDHC_FEVT_CTOE(x) (((uint32_t)(((uint32_t)(x)) << SDHC_FEVT_CTOE_SHIFT)) & SDHC_FEVT_CTOE_MASK) -#define SDHC_FEVT_CCE_MASK (0x20000U) -#define SDHC_FEVT_CCE_SHIFT (17U) -#define SDHC_FEVT_CCE(x) (((uint32_t)(((uint32_t)(x)) << SDHC_FEVT_CCE_SHIFT)) & SDHC_FEVT_CCE_MASK) -#define SDHC_FEVT_CEBE_MASK (0x40000U) -#define SDHC_FEVT_CEBE_SHIFT (18U) -#define SDHC_FEVT_CEBE(x) (((uint32_t)(((uint32_t)(x)) << SDHC_FEVT_CEBE_SHIFT)) & SDHC_FEVT_CEBE_MASK) -#define SDHC_FEVT_CIE_MASK (0x80000U) -#define SDHC_FEVT_CIE_SHIFT (19U) -#define SDHC_FEVT_CIE(x) (((uint32_t)(((uint32_t)(x)) << SDHC_FEVT_CIE_SHIFT)) & SDHC_FEVT_CIE_MASK) -#define SDHC_FEVT_DTOE_MASK (0x100000U) -#define SDHC_FEVT_DTOE_SHIFT (20U) -#define SDHC_FEVT_DTOE(x) (((uint32_t)(((uint32_t)(x)) << SDHC_FEVT_DTOE_SHIFT)) & SDHC_FEVT_DTOE_MASK) -#define SDHC_FEVT_DCE_MASK (0x200000U) -#define SDHC_FEVT_DCE_SHIFT (21U) -#define SDHC_FEVT_DCE(x) (((uint32_t)(((uint32_t)(x)) << SDHC_FEVT_DCE_SHIFT)) & SDHC_FEVT_DCE_MASK) -#define SDHC_FEVT_DEBE_MASK (0x400000U) -#define SDHC_FEVT_DEBE_SHIFT (22U) -#define SDHC_FEVT_DEBE(x) (((uint32_t)(((uint32_t)(x)) << SDHC_FEVT_DEBE_SHIFT)) & SDHC_FEVT_DEBE_MASK) -#define SDHC_FEVT_AC12E_MASK (0x1000000U) -#define SDHC_FEVT_AC12E_SHIFT (24U) -#define SDHC_FEVT_AC12E(x) (((uint32_t)(((uint32_t)(x)) << SDHC_FEVT_AC12E_SHIFT)) & SDHC_FEVT_AC12E_MASK) -#define SDHC_FEVT_DMAE_MASK (0x10000000U) -#define SDHC_FEVT_DMAE_SHIFT (28U) -#define SDHC_FEVT_DMAE(x) (((uint32_t)(((uint32_t)(x)) << SDHC_FEVT_DMAE_SHIFT)) & SDHC_FEVT_DMAE_MASK) -#define SDHC_FEVT_CINT_MASK (0x80000000U) -#define SDHC_FEVT_CINT_SHIFT (31U) -#define SDHC_FEVT_CINT(x) (((uint32_t)(((uint32_t)(x)) << SDHC_FEVT_CINT_SHIFT)) & SDHC_FEVT_CINT_MASK) - -/*! @name ADMAES - ADMA Error Status register */ -#define SDHC_ADMAES_ADMAES_MASK (0x3U) -#define SDHC_ADMAES_ADMAES_SHIFT (0U) -#define SDHC_ADMAES_ADMAES(x) (((uint32_t)(((uint32_t)(x)) << SDHC_ADMAES_ADMAES_SHIFT)) & SDHC_ADMAES_ADMAES_MASK) -#define SDHC_ADMAES_ADMALME_MASK (0x4U) -#define SDHC_ADMAES_ADMALME_SHIFT (2U) -#define SDHC_ADMAES_ADMALME(x) (((uint32_t)(((uint32_t)(x)) << SDHC_ADMAES_ADMALME_SHIFT)) & SDHC_ADMAES_ADMALME_MASK) -#define SDHC_ADMAES_ADMADCE_MASK (0x8U) -#define SDHC_ADMAES_ADMADCE_SHIFT (3U) -#define SDHC_ADMAES_ADMADCE(x) (((uint32_t)(((uint32_t)(x)) << SDHC_ADMAES_ADMADCE_SHIFT)) & SDHC_ADMAES_ADMADCE_MASK) - -/*! @name ADSADDR - ADMA System Addressregister */ -#define SDHC_ADSADDR_ADSADDR_MASK (0xFFFFFFFCU) -#define SDHC_ADSADDR_ADSADDR_SHIFT (2U) -#define SDHC_ADSADDR_ADSADDR(x) (((uint32_t)(((uint32_t)(x)) << SDHC_ADSADDR_ADSADDR_SHIFT)) & SDHC_ADSADDR_ADSADDR_MASK) - -/*! @name VENDOR - Vendor Specific register */ -#define SDHC_VENDOR_EXTDMAEN_MASK (0x1U) -#define SDHC_VENDOR_EXTDMAEN_SHIFT (0U) -#define SDHC_VENDOR_EXTDMAEN(x) (((uint32_t)(((uint32_t)(x)) << SDHC_VENDOR_EXTDMAEN_SHIFT)) & SDHC_VENDOR_EXTDMAEN_MASK) -#define SDHC_VENDOR_EXBLKNU_MASK (0x2U) -#define SDHC_VENDOR_EXBLKNU_SHIFT (1U) -#define SDHC_VENDOR_EXBLKNU(x) (((uint32_t)(((uint32_t)(x)) << SDHC_VENDOR_EXBLKNU_SHIFT)) & SDHC_VENDOR_EXBLKNU_MASK) -#define SDHC_VENDOR_INTSTVAL_MASK (0xFF0000U) -#define SDHC_VENDOR_INTSTVAL_SHIFT (16U) -#define SDHC_VENDOR_INTSTVAL(x) (((uint32_t)(((uint32_t)(x)) << SDHC_VENDOR_INTSTVAL_SHIFT)) & SDHC_VENDOR_INTSTVAL_MASK) - -/*! @name MMCBOOT - MMC Boot register */ -#define SDHC_MMCBOOT_DTOCVACK_MASK (0xFU) -#define SDHC_MMCBOOT_DTOCVACK_SHIFT (0U) -#define SDHC_MMCBOOT_DTOCVACK(x) (((uint32_t)(((uint32_t)(x)) << SDHC_MMCBOOT_DTOCVACK_SHIFT)) & SDHC_MMCBOOT_DTOCVACK_MASK) -#define SDHC_MMCBOOT_BOOTACK_MASK (0x10U) -#define SDHC_MMCBOOT_BOOTACK_SHIFT (4U) -#define SDHC_MMCBOOT_BOOTACK(x) (((uint32_t)(((uint32_t)(x)) << SDHC_MMCBOOT_BOOTACK_SHIFT)) & SDHC_MMCBOOT_BOOTACK_MASK) -#define SDHC_MMCBOOT_BOOTMODE_MASK (0x20U) -#define SDHC_MMCBOOT_BOOTMODE_SHIFT (5U) -#define SDHC_MMCBOOT_BOOTMODE(x) (((uint32_t)(((uint32_t)(x)) << SDHC_MMCBOOT_BOOTMODE_SHIFT)) & SDHC_MMCBOOT_BOOTMODE_MASK) -#define SDHC_MMCBOOT_BOOTEN_MASK (0x40U) -#define SDHC_MMCBOOT_BOOTEN_SHIFT (6U) -#define SDHC_MMCBOOT_BOOTEN(x) (((uint32_t)(((uint32_t)(x)) << SDHC_MMCBOOT_BOOTEN_SHIFT)) & SDHC_MMCBOOT_BOOTEN_MASK) -#define SDHC_MMCBOOT_AUTOSABGEN_MASK (0x80U) -#define SDHC_MMCBOOT_AUTOSABGEN_SHIFT (7U) -#define SDHC_MMCBOOT_AUTOSABGEN(x) (((uint32_t)(((uint32_t)(x)) << SDHC_MMCBOOT_AUTOSABGEN_SHIFT)) & SDHC_MMCBOOT_AUTOSABGEN_MASK) -#define SDHC_MMCBOOT_BOOTBLKCNT_MASK (0xFFFF0000U) -#define SDHC_MMCBOOT_BOOTBLKCNT_SHIFT (16U) -#define SDHC_MMCBOOT_BOOTBLKCNT(x) (((uint32_t)(((uint32_t)(x)) << SDHC_MMCBOOT_BOOTBLKCNT_SHIFT)) & SDHC_MMCBOOT_BOOTBLKCNT_MASK) - -/*! @name HOSTVER - Host Controller Version */ -#define SDHC_HOSTVER_SVN_MASK (0xFFU) -#define SDHC_HOSTVER_SVN_SHIFT (0U) -#define SDHC_HOSTVER_SVN(x) (((uint32_t)(((uint32_t)(x)) << SDHC_HOSTVER_SVN_SHIFT)) & SDHC_HOSTVER_SVN_MASK) -#define SDHC_HOSTVER_VVN_MASK (0xFF00U) -#define SDHC_HOSTVER_VVN_SHIFT (8U) -#define SDHC_HOSTVER_VVN(x) (((uint32_t)(((uint32_t)(x)) << SDHC_HOSTVER_VVN_SHIFT)) & SDHC_HOSTVER_VVN_MASK) - - -/*! - * @} - */ /* end of group SDHC_Register_Masks */ - - -/* SDHC - Peripheral instance base addresses */ -/** Peripheral SDHC base address */ -#define SDHC_BASE (0x400B1000u) -/** Peripheral SDHC base pointer */ -#define SDHC ((SDHC_Type *)SDHC_BASE) -/** Array initializer of SDHC peripheral base addresses */ -#define SDHC_BASE_ADDRS { SDHC_BASE } -/** Array initializer of SDHC peripheral base pointers */ -#define SDHC_BASE_PTRS { SDHC } -/** Interrupt vectors for the SDHC peripheral type */ -#define SDHC_IRQS { SDHC_IRQn } - -/*! - * @} - */ /* end of group SDHC_Peripheral_Access_Layer */ - - -/* ---------------------------------------------------------------------------- - -- SIM Peripheral Access Layer - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup SIM_Peripheral_Access_Layer SIM Peripheral Access Layer - * @{ - */ - -/** SIM - Register Layout Typedef */ -typedef struct { - __IO uint32_t SOPT1; /**< System Options Register 1, offset: 0x0 */ - __IO uint32_t SOPT1CFG; /**< SOPT1 Configuration Register, offset: 0x4 */ - uint8_t RESERVED_0[4092]; - __IO uint32_t SOPT2; /**< System Options Register 2, offset: 0x1004 */ - uint8_t RESERVED_1[4]; - __IO uint32_t SOPT4; /**< System Options Register 4, offset: 0x100C */ - __IO uint32_t SOPT5; /**< System Options Register 5, offset: 0x1010 */ - uint8_t RESERVED_2[4]; - __IO uint32_t SOPT7; /**< System Options Register 7, offset: 0x1018 */ - uint8_t RESERVED_3[8]; - __I uint32_t SDID; /**< System Device Identification Register, offset: 0x1024 */ - __IO uint32_t SCGC1; /**< System Clock Gating Control Register 1, offset: 0x1028 */ - __IO uint32_t SCGC2; /**< System Clock Gating Control Register 2, offset: 0x102C */ - __IO uint32_t SCGC3; /**< System Clock Gating Control Register 3, offset: 0x1030 */ - __IO uint32_t SCGC4; /**< System Clock Gating Control Register 4, offset: 0x1034 */ - __IO uint32_t SCGC5; /**< System Clock Gating Control Register 5, offset: 0x1038 */ - __IO uint32_t SCGC6; /**< System Clock Gating Control Register 6, offset: 0x103C */ - __IO uint32_t SCGC7; /**< System Clock Gating Control Register 7, offset: 0x1040 */ - __IO uint32_t CLKDIV1; /**< System Clock Divider Register 1, offset: 0x1044 */ - __IO uint32_t CLKDIV2; /**< System Clock Divider Register 2, offset: 0x1048 */ - __IO uint32_t FCFG1; /**< Flash Configuration Register 1, offset: 0x104C */ - __I uint32_t FCFG2; /**< Flash Configuration Register 2, offset: 0x1050 */ - __I uint32_t UIDH; /**< Unique Identification Register High, offset: 0x1054 */ - __I uint32_t UIDMH; /**< Unique Identification Register Mid-High, offset: 0x1058 */ - __I uint32_t UIDML; /**< Unique Identification Register Mid Low, offset: 0x105C */ - __I uint32_t UIDL; /**< Unique Identification Register Low, offset: 0x1060 */ -} SIM_Type; - -/* ---------------------------------------------------------------------------- - -- SIM Register Masks - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup SIM_Register_Masks SIM Register Masks - * @{ - */ - -/*! @name SOPT1 - System Options Register 1 */ -#define SIM_SOPT1_RAMSIZE_MASK (0xF000U) -#define SIM_SOPT1_RAMSIZE_SHIFT (12U) -#define SIM_SOPT1_RAMSIZE(x) (((uint32_t)(((uint32_t)(x)) << SIM_SOPT1_RAMSIZE_SHIFT)) & SIM_SOPT1_RAMSIZE_MASK) -#define SIM_SOPT1_OSC32KSEL_MASK (0xC0000U) -#define SIM_SOPT1_OSC32KSEL_SHIFT (18U) -#define SIM_SOPT1_OSC32KSEL(x) (((uint32_t)(((uint32_t)(x)) << SIM_SOPT1_OSC32KSEL_SHIFT)) & SIM_SOPT1_OSC32KSEL_MASK) -#define SIM_SOPT1_USBVSTBY_MASK (0x20000000U) -#define SIM_SOPT1_USBVSTBY_SHIFT (29U) -#define SIM_SOPT1_USBVSTBY(x) (((uint32_t)(((uint32_t)(x)) << SIM_SOPT1_USBVSTBY_SHIFT)) & SIM_SOPT1_USBVSTBY_MASK) -#define SIM_SOPT1_USBSSTBY_MASK (0x40000000U) -#define SIM_SOPT1_USBSSTBY_SHIFT (30U) -#define SIM_SOPT1_USBSSTBY(x) (((uint32_t)(((uint32_t)(x)) << SIM_SOPT1_USBSSTBY_SHIFT)) & SIM_SOPT1_USBSSTBY_MASK) -#define SIM_SOPT1_USBREGEN_MASK (0x80000000U) -#define SIM_SOPT1_USBREGEN_SHIFT (31U) -#define SIM_SOPT1_USBREGEN(x) (((uint32_t)(((uint32_t)(x)) << SIM_SOPT1_USBREGEN_SHIFT)) & SIM_SOPT1_USBREGEN_MASK) - -/*! @name SOPT1CFG - SOPT1 Configuration Register */ -#define SIM_SOPT1CFG_URWE_MASK (0x1000000U) -#define SIM_SOPT1CFG_URWE_SHIFT (24U) -#define SIM_SOPT1CFG_URWE(x) (((uint32_t)(((uint32_t)(x)) << SIM_SOPT1CFG_URWE_SHIFT)) & SIM_SOPT1CFG_URWE_MASK) -#define SIM_SOPT1CFG_UVSWE_MASK (0x2000000U) -#define SIM_SOPT1CFG_UVSWE_SHIFT (25U) -#define SIM_SOPT1CFG_UVSWE(x) (((uint32_t)(((uint32_t)(x)) << SIM_SOPT1CFG_UVSWE_SHIFT)) & SIM_SOPT1CFG_UVSWE_MASK) -#define SIM_SOPT1CFG_USSWE_MASK (0x4000000U) -#define SIM_SOPT1CFG_USSWE_SHIFT (26U) -#define SIM_SOPT1CFG_USSWE(x) (((uint32_t)(((uint32_t)(x)) << SIM_SOPT1CFG_USSWE_SHIFT)) & SIM_SOPT1CFG_USSWE_MASK) - -/*! @name SOPT2 - System Options Register 2 */ -#define SIM_SOPT2_RTCCLKOUTSEL_MASK (0x10U) -#define SIM_SOPT2_RTCCLKOUTSEL_SHIFT (4U) -#define SIM_SOPT2_RTCCLKOUTSEL(x) (((uint32_t)(((uint32_t)(x)) << SIM_SOPT2_RTCCLKOUTSEL_SHIFT)) & SIM_SOPT2_RTCCLKOUTSEL_MASK) -#define SIM_SOPT2_CLKOUTSEL_MASK (0xE0U) -#define SIM_SOPT2_CLKOUTSEL_SHIFT (5U) -#define SIM_SOPT2_CLKOUTSEL(x) (((uint32_t)(((uint32_t)(x)) << SIM_SOPT2_CLKOUTSEL_SHIFT)) & SIM_SOPT2_CLKOUTSEL_MASK) -#define SIM_SOPT2_FBSL_MASK (0x300U) -#define SIM_SOPT2_FBSL_SHIFT (8U) -#define SIM_SOPT2_FBSL(x) (((uint32_t)(((uint32_t)(x)) << SIM_SOPT2_FBSL_SHIFT)) & SIM_SOPT2_FBSL_MASK) -#define SIM_SOPT2_PTD7PAD_MASK (0x800U) -#define SIM_SOPT2_PTD7PAD_SHIFT (11U) -#define SIM_SOPT2_PTD7PAD(x) (((uint32_t)(((uint32_t)(x)) << SIM_SOPT2_PTD7PAD_SHIFT)) & SIM_SOPT2_PTD7PAD_MASK) -#define SIM_SOPT2_TRACECLKSEL_MASK (0x1000U) -#define SIM_SOPT2_TRACECLKSEL_SHIFT (12U) -#define SIM_SOPT2_TRACECLKSEL(x) (((uint32_t)(((uint32_t)(x)) << SIM_SOPT2_TRACECLKSEL_SHIFT)) & SIM_SOPT2_TRACECLKSEL_MASK) -#define SIM_SOPT2_PLLFLLSEL_MASK (0x30000U) -#define SIM_SOPT2_PLLFLLSEL_SHIFT (16U) -#define SIM_SOPT2_PLLFLLSEL(x) (((uint32_t)(((uint32_t)(x)) << SIM_SOPT2_PLLFLLSEL_SHIFT)) & SIM_SOPT2_PLLFLLSEL_MASK) -#define SIM_SOPT2_USBSRC_MASK (0x40000U) -#define SIM_SOPT2_USBSRC_SHIFT (18U) -#define SIM_SOPT2_USBSRC(x) (((uint32_t)(((uint32_t)(x)) << SIM_SOPT2_USBSRC_SHIFT)) & SIM_SOPT2_USBSRC_MASK) -#define SIM_SOPT2_SDHCSRC_MASK (0x30000000U) -#define SIM_SOPT2_SDHCSRC_SHIFT (28U) -#define SIM_SOPT2_SDHCSRC(x) (((uint32_t)(((uint32_t)(x)) << SIM_SOPT2_SDHCSRC_SHIFT)) & SIM_SOPT2_SDHCSRC_MASK) - -/*! @name SOPT4 - System Options Register 4 */ -#define SIM_SOPT4_FTM0FLT0_MASK (0x1U) -#define SIM_SOPT4_FTM0FLT0_SHIFT (0U) -#define SIM_SOPT4_FTM0FLT0(x) (((uint32_t)(((uint32_t)(x)) << SIM_SOPT4_FTM0FLT0_SHIFT)) & SIM_SOPT4_FTM0FLT0_MASK) -#define SIM_SOPT4_FTM0FLT1_MASK (0x2U) -#define SIM_SOPT4_FTM0FLT1_SHIFT (1U) -#define SIM_SOPT4_FTM0FLT1(x) (((uint32_t)(((uint32_t)(x)) << SIM_SOPT4_FTM0FLT1_SHIFT)) & SIM_SOPT4_FTM0FLT1_MASK) -#define SIM_SOPT4_FTM0FLT2_MASK (0x4U) -#define SIM_SOPT4_FTM0FLT2_SHIFT (2U) -#define SIM_SOPT4_FTM0FLT2(x) (((uint32_t)(((uint32_t)(x)) << SIM_SOPT4_FTM0FLT2_SHIFT)) & SIM_SOPT4_FTM0FLT2_MASK) -#define SIM_SOPT4_FTM1FLT0_MASK (0x10U) -#define SIM_SOPT4_FTM1FLT0_SHIFT (4U) -#define SIM_SOPT4_FTM1FLT0(x) (((uint32_t)(((uint32_t)(x)) << SIM_SOPT4_FTM1FLT0_SHIFT)) & SIM_SOPT4_FTM1FLT0_MASK) -#define SIM_SOPT4_FTM2FLT0_MASK (0x100U) -#define SIM_SOPT4_FTM2FLT0_SHIFT (8U) -#define SIM_SOPT4_FTM2FLT0(x) (((uint32_t)(((uint32_t)(x)) << SIM_SOPT4_FTM2FLT0_SHIFT)) & SIM_SOPT4_FTM2FLT0_MASK) -#define SIM_SOPT4_FTM3FLT0_MASK (0x1000U) -#define SIM_SOPT4_FTM3FLT0_SHIFT (12U) -#define SIM_SOPT4_FTM3FLT0(x) (((uint32_t)(((uint32_t)(x)) << SIM_SOPT4_FTM3FLT0_SHIFT)) & SIM_SOPT4_FTM3FLT0_MASK) -#define SIM_SOPT4_FTM1CH0SRC_MASK (0xC0000U) -#define SIM_SOPT4_FTM1CH0SRC_SHIFT (18U) -#define SIM_SOPT4_FTM1CH0SRC(x) (((uint32_t)(((uint32_t)(x)) << SIM_SOPT4_FTM1CH0SRC_SHIFT)) & SIM_SOPT4_FTM1CH0SRC_MASK) -#define SIM_SOPT4_FTM2CH0SRC_MASK (0x300000U) -#define SIM_SOPT4_FTM2CH0SRC_SHIFT (20U) -#define SIM_SOPT4_FTM2CH0SRC(x) (((uint32_t)(((uint32_t)(x)) << SIM_SOPT4_FTM2CH0SRC_SHIFT)) & SIM_SOPT4_FTM2CH0SRC_MASK) -#define SIM_SOPT4_FTM0CLKSEL_MASK (0x1000000U) -#define SIM_SOPT4_FTM0CLKSEL_SHIFT (24U) -#define SIM_SOPT4_FTM0CLKSEL(x) (((uint32_t)(((uint32_t)(x)) << SIM_SOPT4_FTM0CLKSEL_SHIFT)) & SIM_SOPT4_FTM0CLKSEL_MASK) -#define SIM_SOPT4_FTM1CLKSEL_MASK (0x2000000U) -#define SIM_SOPT4_FTM1CLKSEL_SHIFT (25U) -#define SIM_SOPT4_FTM1CLKSEL(x) (((uint32_t)(((uint32_t)(x)) << SIM_SOPT4_FTM1CLKSEL_SHIFT)) & SIM_SOPT4_FTM1CLKSEL_MASK) -#define SIM_SOPT4_FTM2CLKSEL_MASK (0x4000000U) -#define SIM_SOPT4_FTM2CLKSEL_SHIFT (26U) -#define SIM_SOPT4_FTM2CLKSEL(x) (((uint32_t)(((uint32_t)(x)) << SIM_SOPT4_FTM2CLKSEL_SHIFT)) & SIM_SOPT4_FTM2CLKSEL_MASK) -#define SIM_SOPT4_FTM3CLKSEL_MASK (0x8000000U) -#define SIM_SOPT4_FTM3CLKSEL_SHIFT (27U) -#define SIM_SOPT4_FTM3CLKSEL(x) (((uint32_t)(((uint32_t)(x)) << SIM_SOPT4_FTM3CLKSEL_SHIFT)) & SIM_SOPT4_FTM3CLKSEL_MASK) -#define SIM_SOPT4_FTM0TRG0SRC_MASK (0x10000000U) -#define SIM_SOPT4_FTM0TRG0SRC_SHIFT (28U) -#define SIM_SOPT4_FTM0TRG0SRC(x) (((uint32_t)(((uint32_t)(x)) << SIM_SOPT4_FTM0TRG0SRC_SHIFT)) & SIM_SOPT4_FTM0TRG0SRC_MASK) -#define SIM_SOPT4_FTM0TRG1SRC_MASK (0x20000000U) -#define SIM_SOPT4_FTM0TRG1SRC_SHIFT (29U) -#define SIM_SOPT4_FTM0TRG1SRC(x) (((uint32_t)(((uint32_t)(x)) << SIM_SOPT4_FTM0TRG1SRC_SHIFT)) & SIM_SOPT4_FTM0TRG1SRC_MASK) -#define SIM_SOPT4_FTM3TRG0SRC_MASK (0x40000000U) -#define SIM_SOPT4_FTM3TRG0SRC_SHIFT (30U) -#define SIM_SOPT4_FTM3TRG0SRC(x) (((uint32_t)(((uint32_t)(x)) << SIM_SOPT4_FTM3TRG0SRC_SHIFT)) & SIM_SOPT4_FTM3TRG0SRC_MASK) -#define SIM_SOPT4_FTM3TRG1SRC_MASK (0x80000000U) -#define SIM_SOPT4_FTM3TRG1SRC_SHIFT (31U) -#define SIM_SOPT4_FTM3TRG1SRC(x) (((uint32_t)(((uint32_t)(x)) << SIM_SOPT4_FTM3TRG1SRC_SHIFT)) & SIM_SOPT4_FTM3TRG1SRC_MASK) - -/*! @name SOPT5 - System Options Register 5 */ -#define SIM_SOPT5_UART0TXSRC_MASK (0x3U) -#define SIM_SOPT5_UART0TXSRC_SHIFT (0U) -#define SIM_SOPT5_UART0TXSRC(x) (((uint32_t)(((uint32_t)(x)) << SIM_SOPT5_UART0TXSRC_SHIFT)) & SIM_SOPT5_UART0TXSRC_MASK) -#define SIM_SOPT5_UART0RXSRC_MASK (0xCU) -#define SIM_SOPT5_UART0RXSRC_SHIFT (2U) -#define SIM_SOPT5_UART0RXSRC(x) (((uint32_t)(((uint32_t)(x)) << SIM_SOPT5_UART0RXSRC_SHIFT)) & SIM_SOPT5_UART0RXSRC_MASK) -#define SIM_SOPT5_UART1TXSRC_MASK (0x30U) -#define SIM_SOPT5_UART1TXSRC_SHIFT (4U) -#define SIM_SOPT5_UART1TXSRC(x) (((uint32_t)(((uint32_t)(x)) << SIM_SOPT5_UART1TXSRC_SHIFT)) & SIM_SOPT5_UART1TXSRC_MASK) -#define SIM_SOPT5_UART1RXSRC_MASK (0xC0U) -#define SIM_SOPT5_UART1RXSRC_SHIFT (6U) -#define SIM_SOPT5_UART1RXSRC(x) (((uint32_t)(((uint32_t)(x)) << SIM_SOPT5_UART1RXSRC_SHIFT)) & SIM_SOPT5_UART1RXSRC_MASK) - -/*! @name SOPT7 - System Options Register 7 */ -#define SIM_SOPT7_ADC0TRGSEL_MASK (0xFU) -#define SIM_SOPT7_ADC0TRGSEL_SHIFT (0U) -#define SIM_SOPT7_ADC0TRGSEL(x) (((uint32_t)(((uint32_t)(x)) << SIM_SOPT7_ADC0TRGSEL_SHIFT)) & SIM_SOPT7_ADC0TRGSEL_MASK) -#define SIM_SOPT7_ADC0PRETRGSEL_MASK (0x10U) -#define SIM_SOPT7_ADC0PRETRGSEL_SHIFT (4U) -#define SIM_SOPT7_ADC0PRETRGSEL(x) (((uint32_t)(((uint32_t)(x)) << SIM_SOPT7_ADC0PRETRGSEL_SHIFT)) & SIM_SOPT7_ADC0PRETRGSEL_MASK) -#define SIM_SOPT7_ADC0ALTTRGEN_MASK (0x80U) -#define SIM_SOPT7_ADC0ALTTRGEN_SHIFT (7U) -#define SIM_SOPT7_ADC0ALTTRGEN(x) (((uint32_t)(((uint32_t)(x)) << SIM_SOPT7_ADC0ALTTRGEN_SHIFT)) & SIM_SOPT7_ADC0ALTTRGEN_MASK) -#define SIM_SOPT7_ADC1TRGSEL_MASK (0xF00U) -#define SIM_SOPT7_ADC1TRGSEL_SHIFT (8U) -#define SIM_SOPT7_ADC1TRGSEL(x) (((uint32_t)(((uint32_t)(x)) << SIM_SOPT7_ADC1TRGSEL_SHIFT)) & SIM_SOPT7_ADC1TRGSEL_MASK) -#define SIM_SOPT7_ADC1PRETRGSEL_MASK (0x1000U) -#define SIM_SOPT7_ADC1PRETRGSEL_SHIFT (12U) -#define SIM_SOPT7_ADC1PRETRGSEL(x) (((uint32_t)(((uint32_t)(x)) << SIM_SOPT7_ADC1PRETRGSEL_SHIFT)) & SIM_SOPT7_ADC1PRETRGSEL_MASK) -#define SIM_SOPT7_ADC1ALTTRGEN_MASK (0x8000U) -#define SIM_SOPT7_ADC1ALTTRGEN_SHIFT (15U) -#define SIM_SOPT7_ADC1ALTTRGEN(x) (((uint32_t)(((uint32_t)(x)) << SIM_SOPT7_ADC1ALTTRGEN_SHIFT)) & SIM_SOPT7_ADC1ALTTRGEN_MASK) - -/*! @name SDID - System Device Identification Register */ -#define SIM_SDID_PINID_MASK (0xFU) -#define SIM_SDID_PINID_SHIFT (0U) -#define SIM_SDID_PINID(x) (((uint32_t)(((uint32_t)(x)) << SIM_SDID_PINID_SHIFT)) & SIM_SDID_PINID_MASK) -#define SIM_SDID_FAMID_MASK (0x70U) -#define SIM_SDID_FAMID_SHIFT (4U) -#define SIM_SDID_FAMID(x) (((uint32_t)(((uint32_t)(x)) << SIM_SDID_FAMID_SHIFT)) & SIM_SDID_FAMID_MASK) -#define SIM_SDID_DIEID_MASK (0xF80U) -#define SIM_SDID_DIEID_SHIFT (7U) -#define SIM_SDID_DIEID(x) (((uint32_t)(((uint32_t)(x)) << SIM_SDID_DIEID_SHIFT)) & SIM_SDID_DIEID_MASK) -#define SIM_SDID_REVID_MASK (0xF000U) -#define SIM_SDID_REVID_SHIFT (12U) -#define SIM_SDID_REVID(x) (((uint32_t)(((uint32_t)(x)) << SIM_SDID_REVID_SHIFT)) & SIM_SDID_REVID_MASK) -#define SIM_SDID_SERIESID_MASK (0xF00000U) -#define SIM_SDID_SERIESID_SHIFT (20U) -#define SIM_SDID_SERIESID(x) (((uint32_t)(((uint32_t)(x)) << SIM_SDID_SERIESID_SHIFT)) & SIM_SDID_SERIESID_MASK) -#define SIM_SDID_SUBFAMID_MASK (0xF000000U) -#define SIM_SDID_SUBFAMID_SHIFT (24U) -#define SIM_SDID_SUBFAMID(x) (((uint32_t)(((uint32_t)(x)) << SIM_SDID_SUBFAMID_SHIFT)) & SIM_SDID_SUBFAMID_MASK) -#define SIM_SDID_FAMILYID_MASK (0xF0000000U) -#define SIM_SDID_FAMILYID_SHIFT (28U) -#define SIM_SDID_FAMILYID(x) (((uint32_t)(((uint32_t)(x)) << SIM_SDID_FAMILYID_SHIFT)) & SIM_SDID_FAMILYID_MASK) - -/*! @name SCGC1 - System Clock Gating Control Register 1 */ -#define SIM_SCGC1_I2C2_MASK (0x40U) -#define SIM_SCGC1_I2C2_SHIFT (6U) -#define SIM_SCGC1_I2C2(x) (((uint32_t)(((uint32_t)(x)) << SIM_SCGC1_I2C2_SHIFT)) & SIM_SCGC1_I2C2_MASK) -#define SIM_SCGC1_UART4_MASK (0x400U) -#define SIM_SCGC1_UART4_SHIFT (10U) -#define SIM_SCGC1_UART4(x) (((uint32_t)(((uint32_t)(x)) << SIM_SCGC1_UART4_SHIFT)) & SIM_SCGC1_UART4_MASK) -#define SIM_SCGC1_UART5_MASK (0x800U) -#define SIM_SCGC1_UART5_SHIFT (11U) -#define SIM_SCGC1_UART5(x) (((uint32_t)(((uint32_t)(x)) << SIM_SCGC1_UART5_SHIFT)) & SIM_SCGC1_UART5_MASK) - -/*! @name SCGC2 - System Clock Gating Control Register 2 */ -#define SIM_SCGC2_DAC0_MASK (0x1000U) -#define SIM_SCGC2_DAC0_SHIFT (12U) -#define SIM_SCGC2_DAC0(x) (((uint32_t)(((uint32_t)(x)) << SIM_SCGC2_DAC0_SHIFT)) & SIM_SCGC2_DAC0_MASK) -#define SIM_SCGC2_DAC1_MASK (0x2000U) -#define SIM_SCGC2_DAC1_SHIFT (13U) -#define SIM_SCGC2_DAC1(x) (((uint32_t)(((uint32_t)(x)) << SIM_SCGC2_DAC1_SHIFT)) & SIM_SCGC2_DAC1_MASK) - -/*! @name SCGC3 - System Clock Gating Control Register 3 */ -#define SIM_SCGC3_RNGA_MASK (0x1U) -#define SIM_SCGC3_RNGA_SHIFT (0U) -#define SIM_SCGC3_RNGA(x) (((uint32_t)(((uint32_t)(x)) << SIM_SCGC3_RNGA_SHIFT)) & SIM_SCGC3_RNGA_MASK) -#define SIM_SCGC3_SPI2_MASK (0x1000U) -#define SIM_SCGC3_SPI2_SHIFT (12U) -#define SIM_SCGC3_SPI2(x) (((uint32_t)(((uint32_t)(x)) << SIM_SCGC3_SPI2_SHIFT)) & SIM_SCGC3_SPI2_MASK) -#define SIM_SCGC3_SDHC_MASK (0x20000U) -#define SIM_SCGC3_SDHC_SHIFT (17U) -#define SIM_SCGC3_SDHC(x) (((uint32_t)(((uint32_t)(x)) << SIM_SCGC3_SDHC_SHIFT)) & SIM_SCGC3_SDHC_MASK) -#define SIM_SCGC3_FTM2_MASK (0x1000000U) -#define SIM_SCGC3_FTM2_SHIFT (24U) -#define SIM_SCGC3_FTM2(x) (((uint32_t)(((uint32_t)(x)) << SIM_SCGC3_FTM2_SHIFT)) & SIM_SCGC3_FTM2_MASK) -#define SIM_SCGC3_FTM3_MASK (0x2000000U) -#define SIM_SCGC3_FTM3_SHIFT (25U) -#define SIM_SCGC3_FTM3(x) (((uint32_t)(((uint32_t)(x)) << SIM_SCGC3_FTM3_SHIFT)) & SIM_SCGC3_FTM3_MASK) -#define SIM_SCGC3_ADC1_MASK (0x8000000U) -#define SIM_SCGC3_ADC1_SHIFT (27U) -#define SIM_SCGC3_ADC1(x) (((uint32_t)(((uint32_t)(x)) << SIM_SCGC3_ADC1_SHIFT)) & SIM_SCGC3_ADC1_MASK) - -/*! @name SCGC4 - System Clock Gating Control Register 4 */ -#define SIM_SCGC4_EWM_MASK (0x2U) -#define SIM_SCGC4_EWM_SHIFT (1U) -#define SIM_SCGC4_EWM(x) (((uint32_t)(((uint32_t)(x)) << SIM_SCGC4_EWM_SHIFT)) & SIM_SCGC4_EWM_MASK) -#define SIM_SCGC4_CMT_MASK (0x4U) -#define SIM_SCGC4_CMT_SHIFT (2U) -#define SIM_SCGC4_CMT(x) (((uint32_t)(((uint32_t)(x)) << SIM_SCGC4_CMT_SHIFT)) & SIM_SCGC4_CMT_MASK) -#define SIM_SCGC4_I2C0_MASK (0x40U) -#define SIM_SCGC4_I2C0_SHIFT (6U) -#define SIM_SCGC4_I2C0(x) (((uint32_t)(((uint32_t)(x)) << SIM_SCGC4_I2C0_SHIFT)) & SIM_SCGC4_I2C0_MASK) -#define SIM_SCGC4_I2C1_MASK (0x80U) -#define SIM_SCGC4_I2C1_SHIFT (7U) -#define SIM_SCGC4_I2C1(x) (((uint32_t)(((uint32_t)(x)) << SIM_SCGC4_I2C1_SHIFT)) & SIM_SCGC4_I2C1_MASK) -#define SIM_SCGC4_UART0_MASK (0x400U) -#define SIM_SCGC4_UART0_SHIFT (10U) -#define SIM_SCGC4_UART0(x) (((uint32_t)(((uint32_t)(x)) << SIM_SCGC4_UART0_SHIFT)) & SIM_SCGC4_UART0_MASK) -#define SIM_SCGC4_UART1_MASK (0x800U) -#define SIM_SCGC4_UART1_SHIFT (11U) -#define SIM_SCGC4_UART1(x) (((uint32_t)(((uint32_t)(x)) << SIM_SCGC4_UART1_SHIFT)) & SIM_SCGC4_UART1_MASK) -#define SIM_SCGC4_UART2_MASK (0x1000U) -#define SIM_SCGC4_UART2_SHIFT (12U) -#define SIM_SCGC4_UART2(x) (((uint32_t)(((uint32_t)(x)) << SIM_SCGC4_UART2_SHIFT)) & SIM_SCGC4_UART2_MASK) -#define SIM_SCGC4_UART3_MASK (0x2000U) -#define SIM_SCGC4_UART3_SHIFT (13U) -#define SIM_SCGC4_UART3(x) (((uint32_t)(((uint32_t)(x)) << SIM_SCGC4_UART3_SHIFT)) & SIM_SCGC4_UART3_MASK) -#define SIM_SCGC4_USBOTG_MASK (0x40000U) -#define SIM_SCGC4_USBOTG_SHIFT (18U) -#define SIM_SCGC4_USBOTG(x) (((uint32_t)(((uint32_t)(x)) << SIM_SCGC4_USBOTG_SHIFT)) & SIM_SCGC4_USBOTG_MASK) -#define SIM_SCGC4_CMP_MASK (0x80000U) -#define SIM_SCGC4_CMP_SHIFT (19U) -#define SIM_SCGC4_CMP(x) (((uint32_t)(((uint32_t)(x)) << SIM_SCGC4_CMP_SHIFT)) & SIM_SCGC4_CMP_MASK) -#define SIM_SCGC4_VREF_MASK (0x100000U) -#define SIM_SCGC4_VREF_SHIFT (20U) -#define SIM_SCGC4_VREF(x) (((uint32_t)(((uint32_t)(x)) << SIM_SCGC4_VREF_SHIFT)) & SIM_SCGC4_VREF_MASK) - -/*! @name SCGC5 - System Clock Gating Control Register 5 */ -#define SIM_SCGC5_LPTMR_MASK (0x1U) -#define SIM_SCGC5_LPTMR_SHIFT (0U) -#define SIM_SCGC5_LPTMR(x) (((uint32_t)(((uint32_t)(x)) << SIM_SCGC5_LPTMR_SHIFT)) & SIM_SCGC5_LPTMR_MASK) -#define SIM_SCGC5_PORTA_MASK (0x200U) -#define SIM_SCGC5_PORTA_SHIFT (9U) -#define SIM_SCGC5_PORTA(x) (((uint32_t)(((uint32_t)(x)) << SIM_SCGC5_PORTA_SHIFT)) & SIM_SCGC5_PORTA_MASK) -#define SIM_SCGC5_PORTB_MASK (0x400U) -#define SIM_SCGC5_PORTB_SHIFT (10U) -#define SIM_SCGC5_PORTB(x) (((uint32_t)(((uint32_t)(x)) << SIM_SCGC5_PORTB_SHIFT)) & SIM_SCGC5_PORTB_MASK) -#define SIM_SCGC5_PORTC_MASK (0x800U) -#define SIM_SCGC5_PORTC_SHIFT (11U) -#define SIM_SCGC5_PORTC(x) (((uint32_t)(((uint32_t)(x)) << SIM_SCGC5_PORTC_SHIFT)) & SIM_SCGC5_PORTC_MASK) -#define SIM_SCGC5_PORTD_MASK (0x1000U) -#define SIM_SCGC5_PORTD_SHIFT (12U) -#define SIM_SCGC5_PORTD(x) (((uint32_t)(((uint32_t)(x)) << SIM_SCGC5_PORTD_SHIFT)) & SIM_SCGC5_PORTD_MASK) -#define SIM_SCGC5_PORTE_MASK (0x2000U) -#define SIM_SCGC5_PORTE_SHIFT (13U) -#define SIM_SCGC5_PORTE(x) (((uint32_t)(((uint32_t)(x)) << SIM_SCGC5_PORTE_SHIFT)) & SIM_SCGC5_PORTE_MASK) - -/*! @name SCGC6 - System Clock Gating Control Register 6 */ -#define SIM_SCGC6_FTF_MASK (0x1U) -#define SIM_SCGC6_FTF_SHIFT (0U) -#define SIM_SCGC6_FTF(x) (((uint32_t)(((uint32_t)(x)) << SIM_SCGC6_FTF_SHIFT)) & SIM_SCGC6_FTF_MASK) -#define SIM_SCGC6_DMAMUX_MASK (0x2U) -#define SIM_SCGC6_DMAMUX_SHIFT (1U) -#define SIM_SCGC6_DMAMUX(x) (((uint32_t)(((uint32_t)(x)) << SIM_SCGC6_DMAMUX_SHIFT)) & SIM_SCGC6_DMAMUX_MASK) -#define SIM_SCGC6_FLEXCAN0_MASK (0x10U) -#define SIM_SCGC6_FLEXCAN0_SHIFT (4U) -#define SIM_SCGC6_FLEXCAN0(x) (((uint32_t)(((uint32_t)(x)) << SIM_SCGC6_FLEXCAN0_SHIFT)) & SIM_SCGC6_FLEXCAN0_MASK) -#define SIM_SCGC6_RNGA_MASK (0x200U) -#define SIM_SCGC6_RNGA_SHIFT (9U) -#define SIM_SCGC6_RNGA(x) (((uint32_t)(((uint32_t)(x)) << SIM_SCGC6_RNGA_SHIFT)) & SIM_SCGC6_RNGA_MASK) -#define SIM_SCGC6_SPI0_MASK (0x1000U) -#define SIM_SCGC6_SPI0_SHIFT (12U) -#define SIM_SCGC6_SPI0(x) (((uint32_t)(((uint32_t)(x)) << SIM_SCGC6_SPI0_SHIFT)) & SIM_SCGC6_SPI0_MASK) -#define SIM_SCGC6_SPI1_MASK (0x2000U) -#define SIM_SCGC6_SPI1_SHIFT (13U) -#define SIM_SCGC6_SPI1(x) (((uint32_t)(((uint32_t)(x)) << SIM_SCGC6_SPI1_SHIFT)) & SIM_SCGC6_SPI1_MASK) -#define SIM_SCGC6_I2S_MASK (0x8000U) -#define SIM_SCGC6_I2S_SHIFT (15U) -#define SIM_SCGC6_I2S(x) (((uint32_t)(((uint32_t)(x)) << SIM_SCGC6_I2S_SHIFT)) & SIM_SCGC6_I2S_MASK) -#define SIM_SCGC6_CRC_MASK (0x40000U) -#define SIM_SCGC6_CRC_SHIFT (18U) -#define SIM_SCGC6_CRC(x) (((uint32_t)(((uint32_t)(x)) << SIM_SCGC6_CRC_SHIFT)) & SIM_SCGC6_CRC_MASK) -#define SIM_SCGC6_USBDCD_MASK (0x200000U) -#define SIM_SCGC6_USBDCD_SHIFT (21U) -#define SIM_SCGC6_USBDCD(x) (((uint32_t)(((uint32_t)(x)) << SIM_SCGC6_USBDCD_SHIFT)) & SIM_SCGC6_USBDCD_MASK) -#define SIM_SCGC6_PDB_MASK (0x400000U) -#define SIM_SCGC6_PDB_SHIFT (22U) -#define SIM_SCGC6_PDB(x) (((uint32_t)(((uint32_t)(x)) << SIM_SCGC6_PDB_SHIFT)) & SIM_SCGC6_PDB_MASK) -#define SIM_SCGC6_PIT_MASK (0x800000U) -#define SIM_SCGC6_PIT_SHIFT (23U) -#define SIM_SCGC6_PIT(x) (((uint32_t)(((uint32_t)(x)) << SIM_SCGC6_PIT_SHIFT)) & SIM_SCGC6_PIT_MASK) -#define SIM_SCGC6_FTM0_MASK (0x1000000U) -#define SIM_SCGC6_FTM0_SHIFT (24U) -#define SIM_SCGC6_FTM0(x) (((uint32_t)(((uint32_t)(x)) << SIM_SCGC6_FTM0_SHIFT)) & SIM_SCGC6_FTM0_MASK) -#define SIM_SCGC6_FTM1_MASK (0x2000000U) -#define SIM_SCGC6_FTM1_SHIFT (25U) -#define SIM_SCGC6_FTM1(x) (((uint32_t)(((uint32_t)(x)) << SIM_SCGC6_FTM1_SHIFT)) & SIM_SCGC6_FTM1_MASK) -#define SIM_SCGC6_FTM2_MASK (0x4000000U) -#define SIM_SCGC6_FTM2_SHIFT (26U) -#define SIM_SCGC6_FTM2(x) (((uint32_t)(((uint32_t)(x)) << SIM_SCGC6_FTM2_SHIFT)) & SIM_SCGC6_FTM2_MASK) -#define SIM_SCGC6_ADC0_MASK (0x8000000U) -#define SIM_SCGC6_ADC0_SHIFT (27U) -#define SIM_SCGC6_ADC0(x) (((uint32_t)(((uint32_t)(x)) << SIM_SCGC6_ADC0_SHIFT)) & SIM_SCGC6_ADC0_MASK) -#define SIM_SCGC6_RTC_MASK (0x20000000U) -#define SIM_SCGC6_RTC_SHIFT (29U) -#define SIM_SCGC6_RTC(x) (((uint32_t)(((uint32_t)(x)) << SIM_SCGC6_RTC_SHIFT)) & SIM_SCGC6_RTC_MASK) -#define SIM_SCGC6_DAC0_MASK (0x80000000U) -#define SIM_SCGC6_DAC0_SHIFT (31U) -#define SIM_SCGC6_DAC0(x) (((uint32_t)(((uint32_t)(x)) << SIM_SCGC6_DAC0_SHIFT)) & SIM_SCGC6_DAC0_MASK) - -/*! @name SCGC7 - System Clock Gating Control Register 7 */ -#define SIM_SCGC7_FLEXBUS_MASK (0x1U) -#define SIM_SCGC7_FLEXBUS_SHIFT (0U) -#define SIM_SCGC7_FLEXBUS(x) (((uint32_t)(((uint32_t)(x)) << SIM_SCGC7_FLEXBUS_SHIFT)) & SIM_SCGC7_FLEXBUS_MASK) -#define SIM_SCGC7_DMA_MASK (0x2U) -#define SIM_SCGC7_DMA_SHIFT (1U) -#define SIM_SCGC7_DMA(x) (((uint32_t)(((uint32_t)(x)) << SIM_SCGC7_DMA_SHIFT)) & SIM_SCGC7_DMA_MASK) -#define SIM_SCGC7_MPU_MASK (0x4U) -#define SIM_SCGC7_MPU_SHIFT (2U) -#define SIM_SCGC7_MPU(x) (((uint32_t)(((uint32_t)(x)) << SIM_SCGC7_MPU_SHIFT)) & SIM_SCGC7_MPU_MASK) - -/*! @name CLKDIV1 - System Clock Divider Register 1 */ -#define SIM_CLKDIV1_OUTDIV4_MASK (0xF0000U) -#define SIM_CLKDIV1_OUTDIV4_SHIFT (16U) -#define SIM_CLKDIV1_OUTDIV4(x) (((uint32_t)(((uint32_t)(x)) << SIM_CLKDIV1_OUTDIV4_SHIFT)) & SIM_CLKDIV1_OUTDIV4_MASK) -#define SIM_CLKDIV1_OUTDIV3_MASK (0xF00000U) -#define SIM_CLKDIV1_OUTDIV3_SHIFT (20U) -#define SIM_CLKDIV1_OUTDIV3(x) (((uint32_t)(((uint32_t)(x)) << SIM_CLKDIV1_OUTDIV3_SHIFT)) & SIM_CLKDIV1_OUTDIV3_MASK) -#define SIM_CLKDIV1_OUTDIV2_MASK (0xF000000U) -#define SIM_CLKDIV1_OUTDIV2_SHIFT (24U) -#define SIM_CLKDIV1_OUTDIV2(x) (((uint32_t)(((uint32_t)(x)) << SIM_CLKDIV1_OUTDIV2_SHIFT)) & SIM_CLKDIV1_OUTDIV2_MASK) -#define SIM_CLKDIV1_OUTDIV1_MASK (0xF0000000U) -#define SIM_CLKDIV1_OUTDIV1_SHIFT (28U) -#define SIM_CLKDIV1_OUTDIV1(x) (((uint32_t)(((uint32_t)(x)) << SIM_CLKDIV1_OUTDIV1_SHIFT)) & SIM_CLKDIV1_OUTDIV1_MASK) - -/*! @name CLKDIV2 - System Clock Divider Register 2 */ -#define SIM_CLKDIV2_USBFRAC_MASK (0x1U) -#define SIM_CLKDIV2_USBFRAC_SHIFT (0U) -#define SIM_CLKDIV2_USBFRAC(x) (((uint32_t)(((uint32_t)(x)) << SIM_CLKDIV2_USBFRAC_SHIFT)) & SIM_CLKDIV2_USBFRAC_MASK) -#define SIM_CLKDIV2_USBDIV_MASK (0xEU) -#define SIM_CLKDIV2_USBDIV_SHIFT (1U) -#define SIM_CLKDIV2_USBDIV(x) (((uint32_t)(((uint32_t)(x)) << SIM_CLKDIV2_USBDIV_SHIFT)) & SIM_CLKDIV2_USBDIV_MASK) - -/*! @name FCFG1 - Flash Configuration Register 1 */ -#define SIM_FCFG1_FLASHDIS_MASK (0x1U) -#define SIM_FCFG1_FLASHDIS_SHIFT (0U) -#define SIM_FCFG1_FLASHDIS(x) (((uint32_t)(((uint32_t)(x)) << SIM_FCFG1_FLASHDIS_SHIFT)) & SIM_FCFG1_FLASHDIS_MASK) -#define SIM_FCFG1_FLASHDOZE_MASK (0x2U) -#define SIM_FCFG1_FLASHDOZE_SHIFT (1U) -#define SIM_FCFG1_FLASHDOZE(x) (((uint32_t)(((uint32_t)(x)) << SIM_FCFG1_FLASHDOZE_SHIFT)) & SIM_FCFG1_FLASHDOZE_MASK) -#define SIM_FCFG1_DEPART_MASK (0xF00U) -#define SIM_FCFG1_DEPART_SHIFT (8U) -#define SIM_FCFG1_DEPART(x) (((uint32_t)(((uint32_t)(x)) << SIM_FCFG1_DEPART_SHIFT)) & SIM_FCFG1_DEPART_MASK) -#define SIM_FCFG1_EESIZE_MASK (0xF0000U) -#define SIM_FCFG1_EESIZE_SHIFT (16U) -#define SIM_FCFG1_EESIZE(x) (((uint32_t)(((uint32_t)(x)) << SIM_FCFG1_EESIZE_SHIFT)) & SIM_FCFG1_EESIZE_MASK) -#define SIM_FCFG1_PFSIZE_MASK (0xF000000U) -#define SIM_FCFG1_PFSIZE_SHIFT (24U) -#define SIM_FCFG1_PFSIZE(x) (((uint32_t)(((uint32_t)(x)) << SIM_FCFG1_PFSIZE_SHIFT)) & SIM_FCFG1_PFSIZE_MASK) -#define SIM_FCFG1_NVMSIZE_MASK (0xF0000000U) -#define SIM_FCFG1_NVMSIZE_SHIFT (28U) -#define SIM_FCFG1_NVMSIZE(x) (((uint32_t)(((uint32_t)(x)) << SIM_FCFG1_NVMSIZE_SHIFT)) & SIM_FCFG1_NVMSIZE_MASK) - -/*! @name FCFG2 - Flash Configuration Register 2 */ -#define SIM_FCFG2_MAXADDR1_MASK (0x7F0000U) -#define SIM_FCFG2_MAXADDR1_SHIFT (16U) -#define SIM_FCFG2_MAXADDR1(x) (((uint32_t)(((uint32_t)(x)) << SIM_FCFG2_MAXADDR1_SHIFT)) & SIM_FCFG2_MAXADDR1_MASK) -#define SIM_FCFG2_PFLSH_MASK (0x800000U) -#define SIM_FCFG2_PFLSH_SHIFT (23U) -#define SIM_FCFG2_PFLSH(x) (((uint32_t)(((uint32_t)(x)) << SIM_FCFG2_PFLSH_SHIFT)) & SIM_FCFG2_PFLSH_MASK) -#define SIM_FCFG2_MAXADDR0_MASK (0x7F000000U) -#define SIM_FCFG2_MAXADDR0_SHIFT (24U) -#define SIM_FCFG2_MAXADDR0(x) (((uint32_t)(((uint32_t)(x)) << SIM_FCFG2_MAXADDR0_SHIFT)) & SIM_FCFG2_MAXADDR0_MASK) - -/*! @name UIDH - Unique Identification Register High */ -#define SIM_UIDH_UID_MASK (0xFFFFFFFFU) -#define SIM_UIDH_UID_SHIFT (0U) -#define SIM_UIDH_UID(x) (((uint32_t)(((uint32_t)(x)) << SIM_UIDH_UID_SHIFT)) & SIM_UIDH_UID_MASK) - -/*! @name UIDMH - Unique Identification Register Mid-High */ -#define SIM_UIDMH_UID_MASK (0xFFFFFFFFU) -#define SIM_UIDMH_UID_SHIFT (0U) -#define SIM_UIDMH_UID(x) (((uint32_t)(((uint32_t)(x)) << SIM_UIDMH_UID_SHIFT)) & SIM_UIDMH_UID_MASK) - -/*! @name UIDML - Unique Identification Register Mid Low */ -#define SIM_UIDML_UID_MASK (0xFFFFFFFFU) -#define SIM_UIDML_UID_SHIFT (0U) -#define SIM_UIDML_UID(x) (((uint32_t)(((uint32_t)(x)) << SIM_UIDML_UID_SHIFT)) & SIM_UIDML_UID_MASK) - -/*! @name UIDL - Unique Identification Register Low */ -#define SIM_UIDL_UID_MASK (0xFFFFFFFFU) -#define SIM_UIDL_UID_SHIFT (0U) -#define SIM_UIDL_UID(x) (((uint32_t)(((uint32_t)(x)) << SIM_UIDL_UID_SHIFT)) & SIM_UIDL_UID_MASK) - - -/*! - * @} - */ /* end of group SIM_Register_Masks */ - - -/* SIM - Peripheral instance base addresses */ -/** Peripheral SIM base address */ -#define SIM_BASE (0x40047000u) -/** Peripheral SIM base pointer */ -#define SIM ((SIM_Type *)SIM_BASE) -/** Array initializer of SIM peripheral base addresses */ -#define SIM_BASE_ADDRS { SIM_BASE } -/** Array initializer of SIM peripheral base pointers */ -#define SIM_BASE_PTRS { SIM } - -/*! - * @} - */ /* end of group SIM_Peripheral_Access_Layer */ - - -/* ---------------------------------------------------------------------------- - -- SMC Peripheral Access Layer - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup SMC_Peripheral_Access_Layer SMC Peripheral Access Layer - * @{ - */ - -/** SMC - Register Layout Typedef */ -typedef struct { - __IO uint8_t PMPROT; /**< Power Mode Protection register, offset: 0x0 */ - __IO uint8_t PMCTRL; /**< Power Mode Control register, offset: 0x1 */ - __IO uint8_t VLLSCTRL; /**< VLLS Control register, offset: 0x2 */ - __I uint8_t PMSTAT; /**< Power Mode Status register, offset: 0x3 */ -} SMC_Type; - -/* ---------------------------------------------------------------------------- - -- SMC Register Masks - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup SMC_Register_Masks SMC Register Masks - * @{ - */ - -/*! @name PMPROT - Power Mode Protection register */ -#define SMC_PMPROT_AVLLS_MASK (0x2U) -#define SMC_PMPROT_AVLLS_SHIFT (1U) -#define SMC_PMPROT_AVLLS(x) (((uint8_t)(((uint8_t)(x)) << SMC_PMPROT_AVLLS_SHIFT)) & SMC_PMPROT_AVLLS_MASK) -#define SMC_PMPROT_ALLS_MASK (0x8U) -#define SMC_PMPROT_ALLS_SHIFT (3U) -#define SMC_PMPROT_ALLS(x) (((uint8_t)(((uint8_t)(x)) << SMC_PMPROT_ALLS_SHIFT)) & SMC_PMPROT_ALLS_MASK) -#define SMC_PMPROT_AVLP_MASK (0x20U) -#define SMC_PMPROT_AVLP_SHIFT (5U) -#define SMC_PMPROT_AVLP(x) (((uint8_t)(((uint8_t)(x)) << SMC_PMPROT_AVLP_SHIFT)) & SMC_PMPROT_AVLP_MASK) - -/*! @name PMCTRL - Power Mode Control register */ -#define SMC_PMCTRL_STOPM_MASK (0x7U) -#define SMC_PMCTRL_STOPM_SHIFT (0U) -#define SMC_PMCTRL_STOPM(x) (((uint8_t)(((uint8_t)(x)) << SMC_PMCTRL_STOPM_SHIFT)) & SMC_PMCTRL_STOPM_MASK) -#define SMC_PMCTRL_STOPA_MASK (0x8U) -#define SMC_PMCTRL_STOPA_SHIFT (3U) -#define SMC_PMCTRL_STOPA(x) (((uint8_t)(((uint8_t)(x)) << SMC_PMCTRL_STOPA_SHIFT)) & SMC_PMCTRL_STOPA_MASK) -#define SMC_PMCTRL_RUNM_MASK (0x60U) -#define SMC_PMCTRL_RUNM_SHIFT (5U) -#define SMC_PMCTRL_RUNM(x) (((uint8_t)(((uint8_t)(x)) << SMC_PMCTRL_RUNM_SHIFT)) & SMC_PMCTRL_RUNM_MASK) -#define SMC_PMCTRL_LPWUI_MASK (0x80U) -#define SMC_PMCTRL_LPWUI_SHIFT (7U) -#define SMC_PMCTRL_LPWUI(x) (((uint8_t)(((uint8_t)(x)) << SMC_PMCTRL_LPWUI_SHIFT)) & SMC_PMCTRL_LPWUI_MASK) - -/*! @name VLLSCTRL - VLLS Control register */ -#define SMC_VLLSCTRL_VLLSM_MASK (0x7U) -#define SMC_VLLSCTRL_VLLSM_SHIFT (0U) -#define SMC_VLLSCTRL_VLLSM(x) (((uint8_t)(((uint8_t)(x)) << SMC_VLLSCTRL_VLLSM_SHIFT)) & SMC_VLLSCTRL_VLLSM_MASK) -#define SMC_VLLSCTRL_PORPO_MASK (0x20U) -#define SMC_VLLSCTRL_PORPO_SHIFT (5U) -#define SMC_VLLSCTRL_PORPO(x) (((uint8_t)(((uint8_t)(x)) << SMC_VLLSCTRL_PORPO_SHIFT)) & SMC_VLLSCTRL_PORPO_MASK) - -/*! @name PMSTAT - Power Mode Status register */ -#define SMC_PMSTAT_PMSTAT_MASK (0x7FU) -#define SMC_PMSTAT_PMSTAT_SHIFT (0U) -#define SMC_PMSTAT_PMSTAT(x) (((uint8_t)(((uint8_t)(x)) << SMC_PMSTAT_PMSTAT_SHIFT)) & SMC_PMSTAT_PMSTAT_MASK) - - -/*! - * @} - */ /* end of group SMC_Register_Masks */ - - -/* SMC - Peripheral instance base addresses */ -/** Peripheral SMC base address */ -#define SMC_BASE (0x4007E000u) -/** Peripheral SMC base pointer */ -#define SMC ((SMC_Type *)SMC_BASE) -/** Array initializer of SMC peripheral base addresses */ -#define SMC_BASE_ADDRS { SMC_BASE } -/** Array initializer of SMC peripheral base pointers */ -#define SMC_BASE_PTRS { SMC } - -/*! - * @} - */ /* end of group SMC_Peripheral_Access_Layer */ - - -/* ---------------------------------------------------------------------------- - -- SPI Peripheral Access Layer - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup SPI_Peripheral_Access_Layer SPI Peripheral Access Layer - * @{ - */ - -/** SPI - Register Layout Typedef */ -typedef struct { - __IO uint32_t MCR; /**< Module Configuration Register, offset: 0x0 */ - uint8_t RESERVED_0[4]; - __IO uint32_t TCR; /**< Transfer Count Register, offset: 0x8 */ - union { /* offset: 0xC */ - __IO uint32_t CTAR[2]; /**< Clock and Transfer Attributes Register (In Master Mode), array offset: 0xC, array step: 0x4 */ - __IO uint32_t CTAR_SLAVE[1]; /**< Clock and Transfer Attributes Register (In Slave Mode), array offset: 0xC, array step: 0x4 */ - }; - uint8_t RESERVED_1[24]; - __IO uint32_t SR; /**< Status Register, offset: 0x2C */ - __IO uint32_t RSER; /**< DMA/Interrupt Request Select and Enable Register, offset: 0x30 */ - union { /* offset: 0x34 */ - __IO uint32_t PUSHR; /**< PUSH TX FIFO Register In Master Mode, offset: 0x34 */ - __IO uint32_t PUSHR_SLAVE; /**< PUSH TX FIFO Register In Slave Mode, offset: 0x34 */ - }; - __I uint32_t POPR; /**< POP RX FIFO Register, offset: 0x38 */ - __I uint32_t TXFR0; /**< Transmit FIFO Registers, offset: 0x3C */ - __I uint32_t TXFR1; /**< Transmit FIFO Registers, offset: 0x40 */ - __I uint32_t TXFR2; /**< Transmit FIFO Registers, offset: 0x44 */ - __I uint32_t TXFR3; /**< Transmit FIFO Registers, offset: 0x48 */ - uint8_t RESERVED_2[48]; - __I uint32_t RXFR0; /**< Receive FIFO Registers, offset: 0x7C */ - __I uint32_t RXFR1; /**< Receive FIFO Registers, offset: 0x80 */ - __I uint32_t RXFR2; /**< Receive FIFO Registers, offset: 0x84 */ - __I uint32_t RXFR3; /**< Receive FIFO Registers, offset: 0x88 */ -} SPI_Type; - -/* ---------------------------------------------------------------------------- - -- SPI Register Masks - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup SPI_Register_Masks SPI Register Masks - * @{ - */ - -/*! @name MCR - Module Configuration Register */ -#define SPI_MCR_HALT_MASK (0x1U) -#define SPI_MCR_HALT_SHIFT (0U) -#define SPI_MCR_HALT(x) (((uint32_t)(((uint32_t)(x)) << SPI_MCR_HALT_SHIFT)) & SPI_MCR_HALT_MASK) -#define SPI_MCR_SMPL_PT_MASK (0x300U) -#define SPI_MCR_SMPL_PT_SHIFT (8U) -#define SPI_MCR_SMPL_PT(x) (((uint32_t)(((uint32_t)(x)) << SPI_MCR_SMPL_PT_SHIFT)) & SPI_MCR_SMPL_PT_MASK) -#define SPI_MCR_CLR_RXF_MASK (0x400U) -#define SPI_MCR_CLR_RXF_SHIFT (10U) -#define SPI_MCR_CLR_RXF(x) (((uint32_t)(((uint32_t)(x)) << SPI_MCR_CLR_RXF_SHIFT)) & SPI_MCR_CLR_RXF_MASK) -#define SPI_MCR_CLR_TXF_MASK (0x800U) -#define SPI_MCR_CLR_TXF_SHIFT (11U) -#define SPI_MCR_CLR_TXF(x) (((uint32_t)(((uint32_t)(x)) << SPI_MCR_CLR_TXF_SHIFT)) & SPI_MCR_CLR_TXF_MASK) -#define SPI_MCR_DIS_RXF_MASK (0x1000U) -#define SPI_MCR_DIS_RXF_SHIFT (12U) -#define SPI_MCR_DIS_RXF(x) (((uint32_t)(((uint32_t)(x)) << SPI_MCR_DIS_RXF_SHIFT)) & SPI_MCR_DIS_RXF_MASK) -#define SPI_MCR_DIS_TXF_MASK (0x2000U) -#define SPI_MCR_DIS_TXF_SHIFT (13U) -#define SPI_MCR_DIS_TXF(x) (((uint32_t)(((uint32_t)(x)) << SPI_MCR_DIS_TXF_SHIFT)) & SPI_MCR_DIS_TXF_MASK) -#define SPI_MCR_MDIS_MASK (0x4000U) -#define SPI_MCR_MDIS_SHIFT (14U) -#define SPI_MCR_MDIS(x) (((uint32_t)(((uint32_t)(x)) << SPI_MCR_MDIS_SHIFT)) & SPI_MCR_MDIS_MASK) -#define SPI_MCR_DOZE_MASK (0x8000U) -#define SPI_MCR_DOZE_SHIFT (15U) -#define SPI_MCR_DOZE(x) (((uint32_t)(((uint32_t)(x)) << SPI_MCR_DOZE_SHIFT)) & SPI_MCR_DOZE_MASK) -#define SPI_MCR_PCSIS_MASK (0x3F0000U) -#define SPI_MCR_PCSIS_SHIFT (16U) -#define SPI_MCR_PCSIS(x) (((uint32_t)(((uint32_t)(x)) << SPI_MCR_PCSIS_SHIFT)) & SPI_MCR_PCSIS_MASK) -#define SPI_MCR_ROOE_MASK (0x1000000U) -#define SPI_MCR_ROOE_SHIFT (24U) -#define SPI_MCR_ROOE(x) (((uint32_t)(((uint32_t)(x)) << SPI_MCR_ROOE_SHIFT)) & SPI_MCR_ROOE_MASK) -#define SPI_MCR_PCSSE_MASK (0x2000000U) -#define SPI_MCR_PCSSE_SHIFT (25U) -#define SPI_MCR_PCSSE(x) (((uint32_t)(((uint32_t)(x)) << SPI_MCR_PCSSE_SHIFT)) & SPI_MCR_PCSSE_MASK) -#define SPI_MCR_MTFE_MASK (0x4000000U) -#define SPI_MCR_MTFE_SHIFT (26U) -#define SPI_MCR_MTFE(x) (((uint32_t)(((uint32_t)(x)) << SPI_MCR_MTFE_SHIFT)) & SPI_MCR_MTFE_MASK) -#define SPI_MCR_FRZ_MASK (0x8000000U) -#define SPI_MCR_FRZ_SHIFT (27U) -#define SPI_MCR_FRZ(x) (((uint32_t)(((uint32_t)(x)) << SPI_MCR_FRZ_SHIFT)) & SPI_MCR_FRZ_MASK) -#define SPI_MCR_DCONF_MASK (0x30000000U) -#define SPI_MCR_DCONF_SHIFT (28U) -#define SPI_MCR_DCONF(x) (((uint32_t)(((uint32_t)(x)) << SPI_MCR_DCONF_SHIFT)) & SPI_MCR_DCONF_MASK) -#define SPI_MCR_CONT_SCKE_MASK (0x40000000U) -#define SPI_MCR_CONT_SCKE_SHIFT (30U) -#define SPI_MCR_CONT_SCKE(x) (((uint32_t)(((uint32_t)(x)) << SPI_MCR_CONT_SCKE_SHIFT)) & SPI_MCR_CONT_SCKE_MASK) -#define SPI_MCR_MSTR_MASK (0x80000000U) -#define SPI_MCR_MSTR_SHIFT (31U) -#define SPI_MCR_MSTR(x) (((uint32_t)(((uint32_t)(x)) << SPI_MCR_MSTR_SHIFT)) & SPI_MCR_MSTR_MASK) - -/*! @name TCR - Transfer Count Register */ -#define SPI_TCR_SPI_TCNT_MASK (0xFFFF0000U) -#define SPI_TCR_SPI_TCNT_SHIFT (16U) -#define SPI_TCR_SPI_TCNT(x) (((uint32_t)(((uint32_t)(x)) << SPI_TCR_SPI_TCNT_SHIFT)) & SPI_TCR_SPI_TCNT_MASK) - -/*! @name CTAR - Clock and Transfer Attributes Register (In Master Mode) */ -#define SPI_CTAR_BR_MASK (0xFU) -#define SPI_CTAR_BR_SHIFT (0U) -#define SPI_CTAR_BR(x) (((uint32_t)(((uint32_t)(x)) << SPI_CTAR_BR_SHIFT)) & SPI_CTAR_BR_MASK) -#define SPI_CTAR_DT_MASK (0xF0U) -#define SPI_CTAR_DT_SHIFT (4U) -#define SPI_CTAR_DT(x) (((uint32_t)(((uint32_t)(x)) << SPI_CTAR_DT_SHIFT)) & SPI_CTAR_DT_MASK) -#define SPI_CTAR_ASC_MASK (0xF00U) -#define SPI_CTAR_ASC_SHIFT (8U) -#define SPI_CTAR_ASC(x) (((uint32_t)(((uint32_t)(x)) << SPI_CTAR_ASC_SHIFT)) & SPI_CTAR_ASC_MASK) -#define SPI_CTAR_CSSCK_MASK (0xF000U) -#define SPI_CTAR_CSSCK_SHIFT (12U) -#define SPI_CTAR_CSSCK(x) (((uint32_t)(((uint32_t)(x)) << SPI_CTAR_CSSCK_SHIFT)) & SPI_CTAR_CSSCK_MASK) -#define SPI_CTAR_PBR_MASK (0x30000U) -#define SPI_CTAR_PBR_SHIFT (16U) -#define SPI_CTAR_PBR(x) (((uint32_t)(((uint32_t)(x)) << SPI_CTAR_PBR_SHIFT)) & SPI_CTAR_PBR_MASK) -#define SPI_CTAR_PDT_MASK (0xC0000U) -#define SPI_CTAR_PDT_SHIFT (18U) -#define SPI_CTAR_PDT(x) (((uint32_t)(((uint32_t)(x)) << SPI_CTAR_PDT_SHIFT)) & SPI_CTAR_PDT_MASK) -#define SPI_CTAR_PASC_MASK (0x300000U) -#define SPI_CTAR_PASC_SHIFT (20U) -#define SPI_CTAR_PASC(x) (((uint32_t)(((uint32_t)(x)) << SPI_CTAR_PASC_SHIFT)) & SPI_CTAR_PASC_MASK) -#define SPI_CTAR_PCSSCK_MASK (0xC00000U) -#define SPI_CTAR_PCSSCK_SHIFT (22U) -#define SPI_CTAR_PCSSCK(x) (((uint32_t)(((uint32_t)(x)) << SPI_CTAR_PCSSCK_SHIFT)) & SPI_CTAR_PCSSCK_MASK) -#define SPI_CTAR_LSBFE_MASK (0x1000000U) -#define SPI_CTAR_LSBFE_SHIFT (24U) -#define SPI_CTAR_LSBFE(x) (((uint32_t)(((uint32_t)(x)) << SPI_CTAR_LSBFE_SHIFT)) & SPI_CTAR_LSBFE_MASK) -#define SPI_CTAR_CPHA_MASK (0x2000000U) -#define SPI_CTAR_CPHA_SHIFT (25U) -#define SPI_CTAR_CPHA(x) (((uint32_t)(((uint32_t)(x)) << SPI_CTAR_CPHA_SHIFT)) & SPI_CTAR_CPHA_MASK) -#define SPI_CTAR_CPOL_MASK (0x4000000U) -#define SPI_CTAR_CPOL_SHIFT (26U) -#define SPI_CTAR_CPOL(x) (((uint32_t)(((uint32_t)(x)) << SPI_CTAR_CPOL_SHIFT)) & SPI_CTAR_CPOL_MASK) -#define SPI_CTAR_FMSZ_MASK (0x78000000U) -#define SPI_CTAR_FMSZ_SHIFT (27U) -#define SPI_CTAR_FMSZ(x) (((uint32_t)(((uint32_t)(x)) << SPI_CTAR_FMSZ_SHIFT)) & SPI_CTAR_FMSZ_MASK) -#define SPI_CTAR_DBR_MASK (0x80000000U) -#define SPI_CTAR_DBR_SHIFT (31U) -#define SPI_CTAR_DBR(x) (((uint32_t)(((uint32_t)(x)) << SPI_CTAR_DBR_SHIFT)) & SPI_CTAR_DBR_MASK) - -/* The count of SPI_CTAR */ -#define SPI_CTAR_COUNT (2U) - -/*! @name CTAR_SLAVE - Clock and Transfer Attributes Register (In Slave Mode) */ -#define SPI_CTAR_SLAVE_CPHA_MASK (0x2000000U) -#define SPI_CTAR_SLAVE_CPHA_SHIFT (25U) -#define SPI_CTAR_SLAVE_CPHA(x) (((uint32_t)(((uint32_t)(x)) << SPI_CTAR_SLAVE_CPHA_SHIFT)) & SPI_CTAR_SLAVE_CPHA_MASK) -#define SPI_CTAR_SLAVE_CPOL_MASK (0x4000000U) -#define SPI_CTAR_SLAVE_CPOL_SHIFT (26U) -#define SPI_CTAR_SLAVE_CPOL(x) (((uint32_t)(((uint32_t)(x)) << SPI_CTAR_SLAVE_CPOL_SHIFT)) & SPI_CTAR_SLAVE_CPOL_MASK) -#define SPI_CTAR_SLAVE_FMSZ_MASK (0xF8000000U) -#define SPI_CTAR_SLAVE_FMSZ_SHIFT (27U) -#define SPI_CTAR_SLAVE_FMSZ(x) (((uint32_t)(((uint32_t)(x)) << SPI_CTAR_SLAVE_FMSZ_SHIFT)) & SPI_CTAR_SLAVE_FMSZ_MASK) - -/* The count of SPI_CTAR_SLAVE */ -#define SPI_CTAR_SLAVE_COUNT (1U) - -/*! @name SR - Status Register */ -#define SPI_SR_POPNXTPTR_MASK (0xFU) -#define SPI_SR_POPNXTPTR_SHIFT (0U) -#define SPI_SR_POPNXTPTR(x) (((uint32_t)(((uint32_t)(x)) << SPI_SR_POPNXTPTR_SHIFT)) & SPI_SR_POPNXTPTR_MASK) -#define SPI_SR_RXCTR_MASK (0xF0U) -#define SPI_SR_RXCTR_SHIFT (4U) -#define SPI_SR_RXCTR(x) (((uint32_t)(((uint32_t)(x)) << SPI_SR_RXCTR_SHIFT)) & SPI_SR_RXCTR_MASK) -#define SPI_SR_TXNXTPTR_MASK (0xF00U) -#define SPI_SR_TXNXTPTR_SHIFT (8U) -#define SPI_SR_TXNXTPTR(x) (((uint32_t)(((uint32_t)(x)) << SPI_SR_TXNXTPTR_SHIFT)) & SPI_SR_TXNXTPTR_MASK) -#define SPI_SR_TXCTR_MASK (0xF000U) -#define SPI_SR_TXCTR_SHIFT (12U) -#define SPI_SR_TXCTR(x) (((uint32_t)(((uint32_t)(x)) << SPI_SR_TXCTR_SHIFT)) & SPI_SR_TXCTR_MASK) -#define SPI_SR_RFDF_MASK (0x20000U) -#define SPI_SR_RFDF_SHIFT (17U) -#define SPI_SR_RFDF(x) (((uint32_t)(((uint32_t)(x)) << SPI_SR_RFDF_SHIFT)) & SPI_SR_RFDF_MASK) -#define SPI_SR_RFOF_MASK (0x80000U) -#define SPI_SR_RFOF_SHIFT (19U) -#define SPI_SR_RFOF(x) (((uint32_t)(((uint32_t)(x)) << SPI_SR_RFOF_SHIFT)) & SPI_SR_RFOF_MASK) -#define SPI_SR_TFFF_MASK (0x2000000U) -#define SPI_SR_TFFF_SHIFT (25U) -#define SPI_SR_TFFF(x) (((uint32_t)(((uint32_t)(x)) << SPI_SR_TFFF_SHIFT)) & SPI_SR_TFFF_MASK) -#define SPI_SR_TFUF_MASK (0x8000000U) -#define SPI_SR_TFUF_SHIFT (27U) -#define SPI_SR_TFUF(x) (((uint32_t)(((uint32_t)(x)) << SPI_SR_TFUF_SHIFT)) & SPI_SR_TFUF_MASK) -#define SPI_SR_EOQF_MASK (0x10000000U) -#define SPI_SR_EOQF_SHIFT (28U) -#define SPI_SR_EOQF(x) (((uint32_t)(((uint32_t)(x)) << SPI_SR_EOQF_SHIFT)) & SPI_SR_EOQF_MASK) -#define SPI_SR_TXRXS_MASK (0x40000000U) -#define SPI_SR_TXRXS_SHIFT (30U) -#define SPI_SR_TXRXS(x) (((uint32_t)(((uint32_t)(x)) << SPI_SR_TXRXS_SHIFT)) & SPI_SR_TXRXS_MASK) -#define SPI_SR_TCF_MASK (0x80000000U) -#define SPI_SR_TCF_SHIFT (31U) -#define SPI_SR_TCF(x) (((uint32_t)(((uint32_t)(x)) << SPI_SR_TCF_SHIFT)) & SPI_SR_TCF_MASK) - -/*! @name RSER - DMA/Interrupt Request Select and Enable Register */ -#define SPI_RSER_RFDF_DIRS_MASK (0x10000U) -#define SPI_RSER_RFDF_DIRS_SHIFT (16U) -#define SPI_RSER_RFDF_DIRS(x) (((uint32_t)(((uint32_t)(x)) << SPI_RSER_RFDF_DIRS_SHIFT)) & SPI_RSER_RFDF_DIRS_MASK) -#define SPI_RSER_RFDF_RE_MASK (0x20000U) -#define SPI_RSER_RFDF_RE_SHIFT (17U) -#define SPI_RSER_RFDF_RE(x) (((uint32_t)(((uint32_t)(x)) << SPI_RSER_RFDF_RE_SHIFT)) & SPI_RSER_RFDF_RE_MASK) -#define SPI_RSER_RFOF_RE_MASK (0x80000U) -#define SPI_RSER_RFOF_RE_SHIFT (19U) -#define SPI_RSER_RFOF_RE(x) (((uint32_t)(((uint32_t)(x)) << SPI_RSER_RFOF_RE_SHIFT)) & SPI_RSER_RFOF_RE_MASK) -#define SPI_RSER_TFFF_DIRS_MASK (0x1000000U) -#define SPI_RSER_TFFF_DIRS_SHIFT (24U) -#define SPI_RSER_TFFF_DIRS(x) (((uint32_t)(((uint32_t)(x)) << SPI_RSER_TFFF_DIRS_SHIFT)) & SPI_RSER_TFFF_DIRS_MASK) -#define SPI_RSER_TFFF_RE_MASK (0x2000000U) -#define SPI_RSER_TFFF_RE_SHIFT (25U) -#define SPI_RSER_TFFF_RE(x) (((uint32_t)(((uint32_t)(x)) << SPI_RSER_TFFF_RE_SHIFT)) & SPI_RSER_TFFF_RE_MASK) -#define SPI_RSER_TFUF_RE_MASK (0x8000000U) -#define SPI_RSER_TFUF_RE_SHIFT (27U) -#define SPI_RSER_TFUF_RE(x) (((uint32_t)(((uint32_t)(x)) << SPI_RSER_TFUF_RE_SHIFT)) & SPI_RSER_TFUF_RE_MASK) -#define SPI_RSER_EOQF_RE_MASK (0x10000000U) -#define SPI_RSER_EOQF_RE_SHIFT (28U) -#define SPI_RSER_EOQF_RE(x) (((uint32_t)(((uint32_t)(x)) << SPI_RSER_EOQF_RE_SHIFT)) & SPI_RSER_EOQF_RE_MASK) -#define SPI_RSER_TCF_RE_MASK (0x80000000U) -#define SPI_RSER_TCF_RE_SHIFT (31U) -#define SPI_RSER_TCF_RE(x) (((uint32_t)(((uint32_t)(x)) << SPI_RSER_TCF_RE_SHIFT)) & SPI_RSER_TCF_RE_MASK) - -/*! @name PUSHR - PUSH TX FIFO Register In Master Mode */ -#define SPI_PUSHR_TXDATA_MASK (0xFFFFU) -#define SPI_PUSHR_TXDATA_SHIFT (0U) -#define SPI_PUSHR_TXDATA(x) (((uint32_t)(((uint32_t)(x)) << SPI_PUSHR_TXDATA_SHIFT)) & SPI_PUSHR_TXDATA_MASK) -#define SPI_PUSHR_PCS_MASK (0x3F0000U) -#define SPI_PUSHR_PCS_SHIFT (16U) -#define SPI_PUSHR_PCS(x) (((uint32_t)(((uint32_t)(x)) << SPI_PUSHR_PCS_SHIFT)) & SPI_PUSHR_PCS_MASK) -#define SPI_PUSHR_CTCNT_MASK (0x4000000U) -#define SPI_PUSHR_CTCNT_SHIFT (26U) -#define SPI_PUSHR_CTCNT(x) (((uint32_t)(((uint32_t)(x)) << SPI_PUSHR_CTCNT_SHIFT)) & SPI_PUSHR_CTCNT_MASK) -#define SPI_PUSHR_EOQ_MASK (0x8000000U) -#define SPI_PUSHR_EOQ_SHIFT (27U) -#define SPI_PUSHR_EOQ(x) (((uint32_t)(((uint32_t)(x)) << SPI_PUSHR_EOQ_SHIFT)) & SPI_PUSHR_EOQ_MASK) -#define SPI_PUSHR_CTAS_MASK (0x70000000U) -#define SPI_PUSHR_CTAS_SHIFT (28U) -#define SPI_PUSHR_CTAS(x) (((uint32_t)(((uint32_t)(x)) << SPI_PUSHR_CTAS_SHIFT)) & SPI_PUSHR_CTAS_MASK) -#define SPI_PUSHR_CONT_MASK (0x80000000U) -#define SPI_PUSHR_CONT_SHIFT (31U) -#define SPI_PUSHR_CONT(x) (((uint32_t)(((uint32_t)(x)) << SPI_PUSHR_CONT_SHIFT)) & SPI_PUSHR_CONT_MASK) - -/*! @name PUSHR_SLAVE - PUSH TX FIFO Register In Slave Mode */ -#define SPI_PUSHR_SLAVE_TXDATA_MASK (0xFFFFFFFFU) -#define SPI_PUSHR_SLAVE_TXDATA_SHIFT (0U) -#define SPI_PUSHR_SLAVE_TXDATA(x) (((uint32_t)(((uint32_t)(x)) << SPI_PUSHR_SLAVE_TXDATA_SHIFT)) & SPI_PUSHR_SLAVE_TXDATA_MASK) - -/*! @name POPR - POP RX FIFO Register */ -#define SPI_POPR_RXDATA_MASK (0xFFFFFFFFU) -#define SPI_POPR_RXDATA_SHIFT (0U) -#define SPI_POPR_RXDATA(x) (((uint32_t)(((uint32_t)(x)) << SPI_POPR_RXDATA_SHIFT)) & SPI_POPR_RXDATA_MASK) - -/*! @name TXFR0 - Transmit FIFO Registers */ -#define SPI_TXFR0_TXDATA_MASK (0xFFFFU) -#define SPI_TXFR0_TXDATA_SHIFT (0U) -#define SPI_TXFR0_TXDATA(x) (((uint32_t)(((uint32_t)(x)) << SPI_TXFR0_TXDATA_SHIFT)) & SPI_TXFR0_TXDATA_MASK) -#define SPI_TXFR0_TXCMD_TXDATA_MASK (0xFFFF0000U) -#define SPI_TXFR0_TXCMD_TXDATA_SHIFT (16U) -#define SPI_TXFR0_TXCMD_TXDATA(x) (((uint32_t)(((uint32_t)(x)) << SPI_TXFR0_TXCMD_TXDATA_SHIFT)) & SPI_TXFR0_TXCMD_TXDATA_MASK) - -/*! @name TXFR1 - Transmit FIFO Registers */ -#define SPI_TXFR1_TXDATA_MASK (0xFFFFU) -#define SPI_TXFR1_TXDATA_SHIFT (0U) -#define SPI_TXFR1_TXDATA(x) (((uint32_t)(((uint32_t)(x)) << SPI_TXFR1_TXDATA_SHIFT)) & SPI_TXFR1_TXDATA_MASK) -#define SPI_TXFR1_TXCMD_TXDATA_MASK (0xFFFF0000U) -#define SPI_TXFR1_TXCMD_TXDATA_SHIFT (16U) -#define SPI_TXFR1_TXCMD_TXDATA(x) (((uint32_t)(((uint32_t)(x)) << SPI_TXFR1_TXCMD_TXDATA_SHIFT)) & SPI_TXFR1_TXCMD_TXDATA_MASK) - -/*! @name TXFR2 - Transmit FIFO Registers */ -#define SPI_TXFR2_TXDATA_MASK (0xFFFFU) -#define SPI_TXFR2_TXDATA_SHIFT (0U) -#define SPI_TXFR2_TXDATA(x) (((uint32_t)(((uint32_t)(x)) << SPI_TXFR2_TXDATA_SHIFT)) & SPI_TXFR2_TXDATA_MASK) -#define SPI_TXFR2_TXCMD_TXDATA_MASK (0xFFFF0000U) -#define SPI_TXFR2_TXCMD_TXDATA_SHIFT (16U) -#define SPI_TXFR2_TXCMD_TXDATA(x) (((uint32_t)(((uint32_t)(x)) << SPI_TXFR2_TXCMD_TXDATA_SHIFT)) & SPI_TXFR2_TXCMD_TXDATA_MASK) - -/*! @name TXFR3 - Transmit FIFO Registers */ -#define SPI_TXFR3_TXDATA_MASK (0xFFFFU) -#define SPI_TXFR3_TXDATA_SHIFT (0U) -#define SPI_TXFR3_TXDATA(x) (((uint32_t)(((uint32_t)(x)) << SPI_TXFR3_TXDATA_SHIFT)) & SPI_TXFR3_TXDATA_MASK) -#define SPI_TXFR3_TXCMD_TXDATA_MASK (0xFFFF0000U) -#define SPI_TXFR3_TXCMD_TXDATA_SHIFT (16U) -#define SPI_TXFR3_TXCMD_TXDATA(x) (((uint32_t)(((uint32_t)(x)) << SPI_TXFR3_TXCMD_TXDATA_SHIFT)) & SPI_TXFR3_TXCMD_TXDATA_MASK) - -/*! @name RXFR0 - Receive FIFO Registers */ -#define SPI_RXFR0_RXDATA_MASK (0xFFFFFFFFU) -#define SPI_RXFR0_RXDATA_SHIFT (0U) -#define SPI_RXFR0_RXDATA(x) (((uint32_t)(((uint32_t)(x)) << SPI_RXFR0_RXDATA_SHIFT)) & SPI_RXFR0_RXDATA_MASK) - -/*! @name RXFR1 - Receive FIFO Registers */ -#define SPI_RXFR1_RXDATA_MASK (0xFFFFFFFFU) -#define SPI_RXFR1_RXDATA_SHIFT (0U) -#define SPI_RXFR1_RXDATA(x) (((uint32_t)(((uint32_t)(x)) << SPI_RXFR1_RXDATA_SHIFT)) & SPI_RXFR1_RXDATA_MASK) - -/*! @name RXFR2 - Receive FIFO Registers */ -#define SPI_RXFR2_RXDATA_MASK (0xFFFFFFFFU) -#define SPI_RXFR2_RXDATA_SHIFT (0U) -#define SPI_RXFR2_RXDATA(x) (((uint32_t)(((uint32_t)(x)) << SPI_RXFR2_RXDATA_SHIFT)) & SPI_RXFR2_RXDATA_MASK) - -/*! @name RXFR3 - Receive FIFO Registers */ -#define SPI_RXFR3_RXDATA_MASK (0xFFFFFFFFU) -#define SPI_RXFR3_RXDATA_SHIFT (0U) -#define SPI_RXFR3_RXDATA(x) (((uint32_t)(((uint32_t)(x)) << SPI_RXFR3_RXDATA_SHIFT)) & SPI_RXFR3_RXDATA_MASK) - - -/*! - * @} - */ /* end of group SPI_Register_Masks */ - - -/* SPI - Peripheral instance base addresses */ -/** Peripheral SPI0 base address */ -#define SPI0_BASE (0x4002C000u) -/** Peripheral SPI0 base pointer */ -#define SPI0 ((SPI_Type *)SPI0_BASE) -/** Peripheral SPI1 base address */ -#define SPI1_BASE (0x4002D000u) -/** Peripheral SPI1 base pointer */ -#define SPI1 ((SPI_Type *)SPI1_BASE) -/** Peripheral SPI2 base address */ -#define SPI2_BASE (0x400AC000u) -/** Peripheral SPI2 base pointer */ -#define SPI2 ((SPI_Type *)SPI2_BASE) -/** Array initializer of SPI peripheral base addresses */ -#define SPI_BASE_ADDRS { SPI0_BASE, SPI1_BASE, SPI2_BASE } -/** Array initializer of SPI peripheral base pointers */ -#define SPI_BASE_PTRS { SPI0, SPI1, SPI2 } -/** Interrupt vectors for the SPI peripheral type */ -#define SPI_IRQS { SPI0_IRQn, SPI1_IRQn, SPI2_IRQn } - -/*! - * @} - */ /* end of group SPI_Peripheral_Access_Layer */ - - -/* ---------------------------------------------------------------------------- - -- SYSMPU Peripheral Access Layer - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup SYSMPU_Peripheral_Access_Layer SYSMPU Peripheral Access Layer - * @{ - */ - -/** SYSMPU - Register Layout Typedef */ -typedef struct { - __IO uint32_t CESR; /**< Control/Error Status Register, offset: 0x0 */ - uint8_t RESERVED_0[12]; - struct { /* offset: 0x10, array step: 0x8 */ - __I uint32_t EAR; /**< Error Address Register, slave port n, array offset: 0x10, array step: 0x8 */ - __I uint32_t EDR; /**< Error Detail Register, slave port n, array offset: 0x14, array step: 0x8 */ - } SP[5]; - uint8_t RESERVED_1[968]; - __IO uint32_t WORD[12][4]; /**< Region Descriptor n, Word 0..Region Descriptor n, Word 3, array offset: 0x400, array step: index*0x10, index2*0x4 */ - uint8_t RESERVED_2[832]; - __IO uint32_t RGDAAC[12]; /**< Region Descriptor Alternate Access Control n, array offset: 0x800, array step: 0x4 */ -} SYSMPU_Type; - -/* ---------------------------------------------------------------------------- - -- SYSMPU Register Masks - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup SYSMPU_Register_Masks SYSMPU Register Masks - * @{ - */ - -/*! @name CESR - Control/Error Status Register */ -#define SYSMPU_CESR_VLD_MASK (0x1U) -#define SYSMPU_CESR_VLD_SHIFT (0U) -#define SYSMPU_CESR_VLD(x) (((uint32_t)(((uint32_t)(x)) << SYSMPU_CESR_VLD_SHIFT)) & SYSMPU_CESR_VLD_MASK) -#define SYSMPU_CESR_NRGD_MASK (0xF00U) -#define SYSMPU_CESR_NRGD_SHIFT (8U) -#define SYSMPU_CESR_NRGD(x) (((uint32_t)(((uint32_t)(x)) << SYSMPU_CESR_NRGD_SHIFT)) & SYSMPU_CESR_NRGD_MASK) -#define SYSMPU_CESR_NSP_MASK (0xF000U) -#define SYSMPU_CESR_NSP_SHIFT (12U) -#define SYSMPU_CESR_NSP(x) (((uint32_t)(((uint32_t)(x)) << SYSMPU_CESR_NSP_SHIFT)) & SYSMPU_CESR_NSP_MASK) -#define SYSMPU_CESR_HRL_MASK (0xF0000U) -#define SYSMPU_CESR_HRL_SHIFT (16U) -#define SYSMPU_CESR_HRL(x) (((uint32_t)(((uint32_t)(x)) << SYSMPU_CESR_HRL_SHIFT)) & SYSMPU_CESR_HRL_MASK) -#define SYSMPU_CESR_SPERR_MASK (0xF8000000U) -#define SYSMPU_CESR_SPERR_SHIFT (27U) -#define SYSMPU_CESR_SPERR(x) (((uint32_t)(((uint32_t)(x)) << SYSMPU_CESR_SPERR_SHIFT)) & SYSMPU_CESR_SPERR_MASK) - -/*! @name EAR - Error Address Register, slave port n */ -#define SYSMPU_EAR_EADDR_MASK (0xFFFFFFFFU) -#define SYSMPU_EAR_EADDR_SHIFT (0U) -#define SYSMPU_EAR_EADDR(x) (((uint32_t)(((uint32_t)(x)) << SYSMPU_EAR_EADDR_SHIFT)) & SYSMPU_EAR_EADDR_MASK) - -/* The count of SYSMPU_EAR */ -#define SYSMPU_EAR_COUNT (5U) - -/*! @name EDR - Error Detail Register, slave port n */ -#define SYSMPU_EDR_ERW_MASK (0x1U) -#define SYSMPU_EDR_ERW_SHIFT (0U) -#define SYSMPU_EDR_ERW(x) (((uint32_t)(((uint32_t)(x)) << SYSMPU_EDR_ERW_SHIFT)) & SYSMPU_EDR_ERW_MASK) -#define SYSMPU_EDR_EATTR_MASK (0xEU) -#define SYSMPU_EDR_EATTR_SHIFT (1U) -#define SYSMPU_EDR_EATTR(x) (((uint32_t)(((uint32_t)(x)) << SYSMPU_EDR_EATTR_SHIFT)) & SYSMPU_EDR_EATTR_MASK) -#define SYSMPU_EDR_EMN_MASK (0xF0U) -#define SYSMPU_EDR_EMN_SHIFT (4U) -#define SYSMPU_EDR_EMN(x) (((uint32_t)(((uint32_t)(x)) << SYSMPU_EDR_EMN_SHIFT)) & SYSMPU_EDR_EMN_MASK) -#define SYSMPU_EDR_EPID_MASK (0xFF00U) -#define SYSMPU_EDR_EPID_SHIFT (8U) -#define SYSMPU_EDR_EPID(x) (((uint32_t)(((uint32_t)(x)) << SYSMPU_EDR_EPID_SHIFT)) & SYSMPU_EDR_EPID_MASK) -#define SYSMPU_EDR_EACD_MASK (0xFFFF0000U) -#define SYSMPU_EDR_EACD_SHIFT (16U) -#define SYSMPU_EDR_EACD(x) (((uint32_t)(((uint32_t)(x)) << SYSMPU_EDR_EACD_SHIFT)) & SYSMPU_EDR_EACD_MASK) - -/* The count of SYSMPU_EDR */ -#define SYSMPU_EDR_COUNT (5U) - -/*! @name WORD - Region Descriptor n, Word 0..Region Descriptor n, Word 3 */ -#define SYSMPU_WORD_VLD_MASK (0x1U) -#define SYSMPU_WORD_VLD_SHIFT (0U) -#define SYSMPU_WORD_VLD(x) (((uint32_t)(((uint32_t)(x)) << SYSMPU_WORD_VLD_SHIFT)) & SYSMPU_WORD_VLD_MASK) -#define SYSMPU_WORD_M0UM_MASK (0x7U) -#define SYSMPU_WORD_M0UM_SHIFT (0U) -#define SYSMPU_WORD_M0UM(x) (((uint32_t)(((uint32_t)(x)) << SYSMPU_WORD_M0UM_SHIFT)) & SYSMPU_WORD_M0UM_MASK) -#define SYSMPU_WORD_M0SM_MASK (0x18U) -#define SYSMPU_WORD_M0SM_SHIFT (3U) -#define SYSMPU_WORD_M0SM(x) (((uint32_t)(((uint32_t)(x)) << SYSMPU_WORD_M0SM_SHIFT)) & SYSMPU_WORD_M0SM_MASK) -#define SYSMPU_WORD_M0PE_MASK (0x20U) -#define SYSMPU_WORD_M0PE_SHIFT (5U) -#define SYSMPU_WORD_M0PE(x) (((uint32_t)(((uint32_t)(x)) << SYSMPU_WORD_M0PE_SHIFT)) & SYSMPU_WORD_M0PE_MASK) -#define SYSMPU_WORD_ENDADDR_MASK (0xFFFFFFE0U) -#define SYSMPU_WORD_ENDADDR_SHIFT (5U) -#define SYSMPU_WORD_ENDADDR(x) (((uint32_t)(((uint32_t)(x)) << SYSMPU_WORD_ENDADDR_SHIFT)) & SYSMPU_WORD_ENDADDR_MASK) -#define SYSMPU_WORD_SRTADDR_MASK (0xFFFFFFE0U) -#define SYSMPU_WORD_SRTADDR_SHIFT (5U) -#define SYSMPU_WORD_SRTADDR(x) (((uint32_t)(((uint32_t)(x)) << SYSMPU_WORD_SRTADDR_SHIFT)) & SYSMPU_WORD_SRTADDR_MASK) -#define SYSMPU_WORD_M1UM_MASK (0x1C0U) -#define SYSMPU_WORD_M1UM_SHIFT (6U) -#define SYSMPU_WORD_M1UM(x) (((uint32_t)(((uint32_t)(x)) << SYSMPU_WORD_M1UM_SHIFT)) & SYSMPU_WORD_M1UM_MASK) -#define SYSMPU_WORD_M1SM_MASK (0x600U) -#define SYSMPU_WORD_M1SM_SHIFT (9U) -#define SYSMPU_WORD_M1SM(x) (((uint32_t)(((uint32_t)(x)) << SYSMPU_WORD_M1SM_SHIFT)) & SYSMPU_WORD_M1SM_MASK) -#define SYSMPU_WORD_M1PE_MASK (0x800U) -#define SYSMPU_WORD_M1PE_SHIFT (11U) -#define SYSMPU_WORD_M1PE(x) (((uint32_t)(((uint32_t)(x)) << SYSMPU_WORD_M1PE_SHIFT)) & SYSMPU_WORD_M1PE_MASK) -#define SYSMPU_WORD_M2UM_MASK (0x7000U) -#define SYSMPU_WORD_M2UM_SHIFT (12U) -#define SYSMPU_WORD_M2UM(x) (((uint32_t)(((uint32_t)(x)) << SYSMPU_WORD_M2UM_SHIFT)) & SYSMPU_WORD_M2UM_MASK) -#define SYSMPU_WORD_M2SM_MASK (0x18000U) -#define SYSMPU_WORD_M2SM_SHIFT (15U) -#define SYSMPU_WORD_M2SM(x) (((uint32_t)(((uint32_t)(x)) << SYSMPU_WORD_M2SM_SHIFT)) & SYSMPU_WORD_M2SM_MASK) -#define SYSMPU_WORD_PIDMASK_MASK (0xFF0000U) -#define SYSMPU_WORD_PIDMASK_SHIFT (16U) -#define SYSMPU_WORD_PIDMASK(x) (((uint32_t)(((uint32_t)(x)) << SYSMPU_WORD_PIDMASK_SHIFT)) & SYSMPU_WORD_PIDMASK_MASK) -#define SYSMPU_WORD_M2PE_MASK (0x20000U) -#define SYSMPU_WORD_M2PE_SHIFT (17U) -#define SYSMPU_WORD_M2PE(x) (((uint32_t)(((uint32_t)(x)) << SYSMPU_WORD_M2PE_SHIFT)) & SYSMPU_WORD_M2PE_MASK) -#define SYSMPU_WORD_M3UM_MASK (0x1C0000U) -#define SYSMPU_WORD_M3UM_SHIFT (18U) -#define SYSMPU_WORD_M3UM(x) (((uint32_t)(((uint32_t)(x)) << SYSMPU_WORD_M3UM_SHIFT)) & SYSMPU_WORD_M3UM_MASK) -#define SYSMPU_WORD_M3SM_MASK (0x600000U) -#define SYSMPU_WORD_M3SM_SHIFT (21U) -#define SYSMPU_WORD_M3SM(x) (((uint32_t)(((uint32_t)(x)) << SYSMPU_WORD_M3SM_SHIFT)) & SYSMPU_WORD_M3SM_MASK) -#define SYSMPU_WORD_M3PE_MASK (0x800000U) -#define SYSMPU_WORD_M3PE_SHIFT (23U) -#define SYSMPU_WORD_M3PE(x) (((uint32_t)(((uint32_t)(x)) << SYSMPU_WORD_M3PE_SHIFT)) & SYSMPU_WORD_M3PE_MASK) -#define SYSMPU_WORD_PID_MASK (0xFF000000U) -#define SYSMPU_WORD_PID_SHIFT (24U) -#define SYSMPU_WORD_PID(x) (((uint32_t)(((uint32_t)(x)) << SYSMPU_WORD_PID_SHIFT)) & SYSMPU_WORD_PID_MASK) -#define SYSMPU_WORD_M4WE_MASK (0x1000000U) -#define SYSMPU_WORD_M4WE_SHIFT (24U) -#define SYSMPU_WORD_M4WE(x) (((uint32_t)(((uint32_t)(x)) << SYSMPU_WORD_M4WE_SHIFT)) & SYSMPU_WORD_M4WE_MASK) -#define SYSMPU_WORD_M4RE_MASK (0x2000000U) -#define SYSMPU_WORD_M4RE_SHIFT (25U) -#define SYSMPU_WORD_M4RE(x) (((uint32_t)(((uint32_t)(x)) << SYSMPU_WORD_M4RE_SHIFT)) & SYSMPU_WORD_M4RE_MASK) -#define SYSMPU_WORD_M5WE_MASK (0x4000000U) -#define SYSMPU_WORD_M5WE_SHIFT (26U) -#define SYSMPU_WORD_M5WE(x) (((uint32_t)(((uint32_t)(x)) << SYSMPU_WORD_M5WE_SHIFT)) & SYSMPU_WORD_M5WE_MASK) -#define SYSMPU_WORD_M5RE_MASK (0x8000000U) -#define SYSMPU_WORD_M5RE_SHIFT (27U) -#define SYSMPU_WORD_M5RE(x) (((uint32_t)(((uint32_t)(x)) << SYSMPU_WORD_M5RE_SHIFT)) & SYSMPU_WORD_M5RE_MASK) -#define SYSMPU_WORD_M6WE_MASK (0x10000000U) -#define SYSMPU_WORD_M6WE_SHIFT (28U) -#define SYSMPU_WORD_M6WE(x) (((uint32_t)(((uint32_t)(x)) << SYSMPU_WORD_M6WE_SHIFT)) & SYSMPU_WORD_M6WE_MASK) -#define SYSMPU_WORD_M6RE_MASK (0x20000000U) -#define SYSMPU_WORD_M6RE_SHIFT (29U) -#define SYSMPU_WORD_M6RE(x) (((uint32_t)(((uint32_t)(x)) << SYSMPU_WORD_M6RE_SHIFT)) & SYSMPU_WORD_M6RE_MASK) -#define SYSMPU_WORD_M7WE_MASK (0x40000000U) -#define SYSMPU_WORD_M7WE_SHIFT (30U) -#define SYSMPU_WORD_M7WE(x) (((uint32_t)(((uint32_t)(x)) << SYSMPU_WORD_M7WE_SHIFT)) & SYSMPU_WORD_M7WE_MASK) -#define SYSMPU_WORD_M7RE_MASK (0x80000000U) -#define SYSMPU_WORD_M7RE_SHIFT (31U) -#define SYSMPU_WORD_M7RE(x) (((uint32_t)(((uint32_t)(x)) << SYSMPU_WORD_M7RE_SHIFT)) & SYSMPU_WORD_M7RE_MASK) - -/* The count of SYSMPU_WORD */ -#define SYSMPU_WORD_COUNT (12U) - -/* The count of SYSMPU_WORD */ -#define SYSMPU_WORD_COUNT2 (4U) - -/*! @name RGDAAC - Region Descriptor Alternate Access Control n */ -#define SYSMPU_RGDAAC_M0UM_MASK (0x7U) -#define SYSMPU_RGDAAC_M0UM_SHIFT (0U) -#define SYSMPU_RGDAAC_M0UM(x) (((uint32_t)(((uint32_t)(x)) << SYSMPU_RGDAAC_M0UM_SHIFT)) & SYSMPU_RGDAAC_M0UM_MASK) -#define SYSMPU_RGDAAC_M0SM_MASK (0x18U) -#define SYSMPU_RGDAAC_M0SM_SHIFT (3U) -#define SYSMPU_RGDAAC_M0SM(x) (((uint32_t)(((uint32_t)(x)) << SYSMPU_RGDAAC_M0SM_SHIFT)) & SYSMPU_RGDAAC_M0SM_MASK) -#define SYSMPU_RGDAAC_M0PE_MASK (0x20U) -#define SYSMPU_RGDAAC_M0PE_SHIFT (5U) -#define SYSMPU_RGDAAC_M0PE(x) (((uint32_t)(((uint32_t)(x)) << SYSMPU_RGDAAC_M0PE_SHIFT)) & SYSMPU_RGDAAC_M0PE_MASK) -#define SYSMPU_RGDAAC_M1UM_MASK (0x1C0U) -#define SYSMPU_RGDAAC_M1UM_SHIFT (6U) -#define SYSMPU_RGDAAC_M1UM(x) (((uint32_t)(((uint32_t)(x)) << SYSMPU_RGDAAC_M1UM_SHIFT)) & SYSMPU_RGDAAC_M1UM_MASK) -#define SYSMPU_RGDAAC_M1SM_MASK (0x600U) -#define SYSMPU_RGDAAC_M1SM_SHIFT (9U) -#define SYSMPU_RGDAAC_M1SM(x) (((uint32_t)(((uint32_t)(x)) << SYSMPU_RGDAAC_M1SM_SHIFT)) & SYSMPU_RGDAAC_M1SM_MASK) -#define SYSMPU_RGDAAC_M1PE_MASK (0x800U) -#define SYSMPU_RGDAAC_M1PE_SHIFT (11U) -#define SYSMPU_RGDAAC_M1PE(x) (((uint32_t)(((uint32_t)(x)) << SYSMPU_RGDAAC_M1PE_SHIFT)) & SYSMPU_RGDAAC_M1PE_MASK) -#define SYSMPU_RGDAAC_M2UM_MASK (0x7000U) -#define SYSMPU_RGDAAC_M2UM_SHIFT (12U) -#define SYSMPU_RGDAAC_M2UM(x) (((uint32_t)(((uint32_t)(x)) << SYSMPU_RGDAAC_M2UM_SHIFT)) & SYSMPU_RGDAAC_M2UM_MASK) -#define SYSMPU_RGDAAC_M2SM_MASK (0x18000U) -#define SYSMPU_RGDAAC_M2SM_SHIFT (15U) -#define SYSMPU_RGDAAC_M2SM(x) (((uint32_t)(((uint32_t)(x)) << SYSMPU_RGDAAC_M2SM_SHIFT)) & SYSMPU_RGDAAC_M2SM_MASK) -#define SYSMPU_RGDAAC_M2PE_MASK (0x20000U) -#define SYSMPU_RGDAAC_M2PE_SHIFT (17U) -#define SYSMPU_RGDAAC_M2PE(x) (((uint32_t)(((uint32_t)(x)) << SYSMPU_RGDAAC_M2PE_SHIFT)) & SYSMPU_RGDAAC_M2PE_MASK) -#define SYSMPU_RGDAAC_M3UM_MASK (0x1C0000U) -#define SYSMPU_RGDAAC_M3UM_SHIFT (18U) -#define SYSMPU_RGDAAC_M3UM(x) (((uint32_t)(((uint32_t)(x)) << SYSMPU_RGDAAC_M3UM_SHIFT)) & SYSMPU_RGDAAC_M3UM_MASK) -#define SYSMPU_RGDAAC_M3SM_MASK (0x600000U) -#define SYSMPU_RGDAAC_M3SM_SHIFT (21U) -#define SYSMPU_RGDAAC_M3SM(x) (((uint32_t)(((uint32_t)(x)) << SYSMPU_RGDAAC_M3SM_SHIFT)) & SYSMPU_RGDAAC_M3SM_MASK) -#define SYSMPU_RGDAAC_M3PE_MASK (0x800000U) -#define SYSMPU_RGDAAC_M3PE_SHIFT (23U) -#define SYSMPU_RGDAAC_M3PE(x) (((uint32_t)(((uint32_t)(x)) << SYSMPU_RGDAAC_M3PE_SHIFT)) & SYSMPU_RGDAAC_M3PE_MASK) -#define SYSMPU_RGDAAC_M4WE_MASK (0x1000000U) -#define SYSMPU_RGDAAC_M4WE_SHIFT (24U) -#define SYSMPU_RGDAAC_M4WE(x) (((uint32_t)(((uint32_t)(x)) << SYSMPU_RGDAAC_M4WE_SHIFT)) & SYSMPU_RGDAAC_M4WE_MASK) -#define SYSMPU_RGDAAC_M4RE_MASK (0x2000000U) -#define SYSMPU_RGDAAC_M4RE_SHIFT (25U) -#define SYSMPU_RGDAAC_M4RE(x) (((uint32_t)(((uint32_t)(x)) << SYSMPU_RGDAAC_M4RE_SHIFT)) & SYSMPU_RGDAAC_M4RE_MASK) -#define SYSMPU_RGDAAC_M5WE_MASK (0x4000000U) -#define SYSMPU_RGDAAC_M5WE_SHIFT (26U) -#define SYSMPU_RGDAAC_M5WE(x) (((uint32_t)(((uint32_t)(x)) << SYSMPU_RGDAAC_M5WE_SHIFT)) & SYSMPU_RGDAAC_M5WE_MASK) -#define SYSMPU_RGDAAC_M5RE_MASK (0x8000000U) -#define SYSMPU_RGDAAC_M5RE_SHIFT (27U) -#define SYSMPU_RGDAAC_M5RE(x) (((uint32_t)(((uint32_t)(x)) << SYSMPU_RGDAAC_M5RE_SHIFT)) & SYSMPU_RGDAAC_M5RE_MASK) -#define SYSMPU_RGDAAC_M6WE_MASK (0x10000000U) -#define SYSMPU_RGDAAC_M6WE_SHIFT (28U) -#define SYSMPU_RGDAAC_M6WE(x) (((uint32_t)(((uint32_t)(x)) << SYSMPU_RGDAAC_M6WE_SHIFT)) & SYSMPU_RGDAAC_M6WE_MASK) -#define SYSMPU_RGDAAC_M6RE_MASK (0x20000000U) -#define SYSMPU_RGDAAC_M6RE_SHIFT (29U) -#define SYSMPU_RGDAAC_M6RE(x) (((uint32_t)(((uint32_t)(x)) << SYSMPU_RGDAAC_M6RE_SHIFT)) & SYSMPU_RGDAAC_M6RE_MASK) -#define SYSMPU_RGDAAC_M7WE_MASK (0x40000000U) -#define SYSMPU_RGDAAC_M7WE_SHIFT (30U) -#define SYSMPU_RGDAAC_M7WE(x) (((uint32_t)(((uint32_t)(x)) << SYSMPU_RGDAAC_M7WE_SHIFT)) & SYSMPU_RGDAAC_M7WE_MASK) -#define SYSMPU_RGDAAC_M7RE_MASK (0x80000000U) -#define SYSMPU_RGDAAC_M7RE_SHIFT (31U) -#define SYSMPU_RGDAAC_M7RE(x) (((uint32_t)(((uint32_t)(x)) << SYSMPU_RGDAAC_M7RE_SHIFT)) & SYSMPU_RGDAAC_M7RE_MASK) - -/* The count of SYSMPU_RGDAAC */ -#define SYSMPU_RGDAAC_COUNT (12U) - - -/*! - * @} - */ /* end of group SYSMPU_Register_Masks */ - - -/* SYSMPU - Peripheral instance base addresses */ -/** Peripheral SYSMPU base address */ -#define SYSMPU_BASE (0x4000D000u) -/** Peripheral SYSMPU base pointer */ -#define SYSMPU ((SYSMPU_Type *)SYSMPU_BASE) -/** Array initializer of SYSMPU peripheral base addresses */ -#define SYSMPU_BASE_ADDRS { SYSMPU_BASE } -/** Array initializer of SYSMPU peripheral base pointers */ -#define SYSMPU_BASE_PTRS { SYSMPU } - -/*! - * @} - */ /* end of group SYSMPU_Peripheral_Access_Layer */ - - -/* ---------------------------------------------------------------------------- - -- UART Peripheral Access Layer - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup UART_Peripheral_Access_Layer UART Peripheral Access Layer - * @{ - */ - -/** UART - Register Layout Typedef */ -typedef struct { - __IO uint8_t BDH; /**< UART Baud Rate Registers: High, offset: 0x0 */ - __IO uint8_t BDL; /**< UART Baud Rate Registers: Low, offset: 0x1 */ - __IO uint8_t C1; /**< UART Control Register 1, offset: 0x2 */ - __IO uint8_t C2; /**< UART Control Register 2, offset: 0x3 */ - __I uint8_t S1; /**< UART Status Register 1, offset: 0x4 */ - __IO uint8_t S2; /**< UART Status Register 2, offset: 0x5 */ - __IO uint8_t C3; /**< UART Control Register 3, offset: 0x6 */ - __IO uint8_t D; /**< UART Data Register, offset: 0x7 */ - __IO uint8_t MA1; /**< UART Match Address Registers 1, offset: 0x8 */ - __IO uint8_t MA2; /**< UART Match Address Registers 2, offset: 0x9 */ - __IO uint8_t C4; /**< UART Control Register 4, offset: 0xA */ - __IO uint8_t C5; /**< UART Control Register 5, offset: 0xB */ - __I uint8_t ED; /**< UART Extended Data Register, offset: 0xC */ - __IO uint8_t MODEM; /**< UART Modem Register, offset: 0xD */ - __IO uint8_t IR; /**< UART Infrared Register, offset: 0xE */ - uint8_t RESERVED_0[1]; - __IO uint8_t PFIFO; /**< UART FIFO Parameters, offset: 0x10 */ - __IO uint8_t CFIFO; /**< UART FIFO Control Register, offset: 0x11 */ - __IO uint8_t SFIFO; /**< UART FIFO Status Register, offset: 0x12 */ - __IO uint8_t TWFIFO; /**< UART FIFO Transmit Watermark, offset: 0x13 */ - __I uint8_t TCFIFO; /**< UART FIFO Transmit Count, offset: 0x14 */ - __IO uint8_t RWFIFO; /**< UART FIFO Receive Watermark, offset: 0x15 */ - __I uint8_t RCFIFO; /**< UART FIFO Receive Count, offset: 0x16 */ - uint8_t RESERVED_1[1]; - __IO uint8_t C7816; /**< UART 7816 Control Register, offset: 0x18 */ - __IO uint8_t IE7816; /**< UART 7816 Interrupt Enable Register, offset: 0x19 */ - __IO uint8_t IS7816; /**< UART 7816 Interrupt Status Register, offset: 0x1A */ - union { /* offset: 0x1B */ - __IO uint8_t WP7816T0; /**< UART 7816 Wait Parameter Register, offset: 0x1B */ - __IO uint8_t WP7816T1; /**< UART 7816 Wait Parameter Register, offset: 0x1B */ - }; - __IO uint8_t WN7816; /**< UART 7816 Wait N Register, offset: 0x1C */ - __IO uint8_t WF7816; /**< UART 7816 Wait FD Register, offset: 0x1D */ - __IO uint8_t ET7816; /**< UART 7816 Error Threshold Register, offset: 0x1E */ - __IO uint8_t TL7816; /**< UART 7816 Transmit Length Register, offset: 0x1F */ -} UART_Type; - -/* ---------------------------------------------------------------------------- - -- UART Register Masks - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup UART_Register_Masks UART Register Masks - * @{ - */ - -/*! @name BDH - UART Baud Rate Registers: High */ -#define UART_BDH_SBR_MASK (0x1FU) -#define UART_BDH_SBR_SHIFT (0U) -#define UART_BDH_SBR(x) (((uint8_t)(((uint8_t)(x)) << UART_BDH_SBR_SHIFT)) & UART_BDH_SBR_MASK) -#define UART_BDH_SBNS_MASK (0x20U) -#define UART_BDH_SBNS_SHIFT (5U) -#define UART_BDH_SBNS(x) (((uint8_t)(((uint8_t)(x)) << UART_BDH_SBNS_SHIFT)) & UART_BDH_SBNS_MASK) -#define UART_BDH_RXEDGIE_MASK (0x40U) -#define UART_BDH_RXEDGIE_SHIFT (6U) -#define UART_BDH_RXEDGIE(x) (((uint8_t)(((uint8_t)(x)) << UART_BDH_RXEDGIE_SHIFT)) & UART_BDH_RXEDGIE_MASK) -#define UART_BDH_LBKDIE_MASK (0x80U) -#define UART_BDH_LBKDIE_SHIFT (7U) -#define UART_BDH_LBKDIE(x) (((uint8_t)(((uint8_t)(x)) << UART_BDH_LBKDIE_SHIFT)) & UART_BDH_LBKDIE_MASK) - -/*! @name BDL - UART Baud Rate Registers: Low */ -#define UART_BDL_SBR_MASK (0xFFU) -#define UART_BDL_SBR_SHIFT (0U) -#define UART_BDL_SBR(x) (((uint8_t)(((uint8_t)(x)) << UART_BDL_SBR_SHIFT)) & UART_BDL_SBR_MASK) - -/*! @name C1 - UART Control Register 1 */ -#define UART_C1_PT_MASK (0x1U) -#define UART_C1_PT_SHIFT (0U) -#define UART_C1_PT(x) (((uint8_t)(((uint8_t)(x)) << UART_C1_PT_SHIFT)) & UART_C1_PT_MASK) -#define UART_C1_PE_MASK (0x2U) -#define UART_C1_PE_SHIFT (1U) -#define UART_C1_PE(x) (((uint8_t)(((uint8_t)(x)) << UART_C1_PE_SHIFT)) & UART_C1_PE_MASK) -#define UART_C1_ILT_MASK (0x4U) -#define UART_C1_ILT_SHIFT (2U) -#define UART_C1_ILT(x) (((uint8_t)(((uint8_t)(x)) << UART_C1_ILT_SHIFT)) & UART_C1_ILT_MASK) -#define UART_C1_WAKE_MASK (0x8U) -#define UART_C1_WAKE_SHIFT (3U) -#define UART_C1_WAKE(x) (((uint8_t)(((uint8_t)(x)) << UART_C1_WAKE_SHIFT)) & UART_C1_WAKE_MASK) -#define UART_C1_M_MASK (0x10U) -#define UART_C1_M_SHIFT (4U) -#define UART_C1_M(x) (((uint8_t)(((uint8_t)(x)) << UART_C1_M_SHIFT)) & UART_C1_M_MASK) -#define UART_C1_RSRC_MASK (0x20U) -#define UART_C1_RSRC_SHIFT (5U) -#define UART_C1_RSRC(x) (((uint8_t)(((uint8_t)(x)) << UART_C1_RSRC_SHIFT)) & UART_C1_RSRC_MASK) -#define UART_C1_UARTSWAI_MASK (0x40U) -#define UART_C1_UARTSWAI_SHIFT (6U) -#define UART_C1_UARTSWAI(x) (((uint8_t)(((uint8_t)(x)) << UART_C1_UARTSWAI_SHIFT)) & UART_C1_UARTSWAI_MASK) -#define UART_C1_LOOPS_MASK (0x80U) -#define UART_C1_LOOPS_SHIFT (7U) -#define UART_C1_LOOPS(x) (((uint8_t)(((uint8_t)(x)) << UART_C1_LOOPS_SHIFT)) & UART_C1_LOOPS_MASK) - -/*! @name C2 - UART Control Register 2 */ -#define UART_C2_SBK_MASK (0x1U) -#define UART_C2_SBK_SHIFT (0U) -#define UART_C2_SBK(x) (((uint8_t)(((uint8_t)(x)) << UART_C2_SBK_SHIFT)) & UART_C2_SBK_MASK) -#define UART_C2_RWU_MASK (0x2U) -#define UART_C2_RWU_SHIFT (1U) -#define UART_C2_RWU(x) (((uint8_t)(((uint8_t)(x)) << UART_C2_RWU_SHIFT)) & UART_C2_RWU_MASK) -#define UART_C2_RE_MASK (0x4U) -#define UART_C2_RE_SHIFT (2U) -#define UART_C2_RE(x) (((uint8_t)(((uint8_t)(x)) << UART_C2_RE_SHIFT)) & UART_C2_RE_MASK) -#define UART_C2_TE_MASK (0x8U) -#define UART_C2_TE_SHIFT (3U) -#define UART_C2_TE(x) (((uint8_t)(((uint8_t)(x)) << UART_C2_TE_SHIFT)) & UART_C2_TE_MASK) -#define UART_C2_ILIE_MASK (0x10U) -#define UART_C2_ILIE_SHIFT (4U) -#define UART_C2_ILIE(x) (((uint8_t)(((uint8_t)(x)) << UART_C2_ILIE_SHIFT)) & UART_C2_ILIE_MASK) -#define UART_C2_RIE_MASK (0x20U) -#define UART_C2_RIE_SHIFT (5U) -#define UART_C2_RIE(x) (((uint8_t)(((uint8_t)(x)) << UART_C2_RIE_SHIFT)) & UART_C2_RIE_MASK) -#define UART_C2_TCIE_MASK (0x40U) -#define UART_C2_TCIE_SHIFT (6U) -#define UART_C2_TCIE(x) (((uint8_t)(((uint8_t)(x)) << UART_C2_TCIE_SHIFT)) & UART_C2_TCIE_MASK) -#define UART_C2_TIE_MASK (0x80U) -#define UART_C2_TIE_SHIFT (7U) -#define UART_C2_TIE(x) (((uint8_t)(((uint8_t)(x)) << UART_C2_TIE_SHIFT)) & UART_C2_TIE_MASK) - -/*! @name S1 - UART Status Register 1 */ -#define UART_S1_PF_MASK (0x1U) -#define UART_S1_PF_SHIFT (0U) -#define UART_S1_PF(x) (((uint8_t)(((uint8_t)(x)) << UART_S1_PF_SHIFT)) & UART_S1_PF_MASK) -#define UART_S1_FE_MASK (0x2U) -#define UART_S1_FE_SHIFT (1U) -#define UART_S1_FE(x) (((uint8_t)(((uint8_t)(x)) << UART_S1_FE_SHIFT)) & UART_S1_FE_MASK) -#define UART_S1_NF_MASK (0x4U) -#define UART_S1_NF_SHIFT (2U) -#define UART_S1_NF(x) (((uint8_t)(((uint8_t)(x)) << UART_S1_NF_SHIFT)) & UART_S1_NF_MASK) -#define UART_S1_OR_MASK (0x8U) -#define UART_S1_OR_SHIFT (3U) -#define UART_S1_OR(x) (((uint8_t)(((uint8_t)(x)) << UART_S1_OR_SHIFT)) & UART_S1_OR_MASK) -#define UART_S1_IDLE_MASK (0x10U) -#define UART_S1_IDLE_SHIFT (4U) -#define UART_S1_IDLE(x) (((uint8_t)(((uint8_t)(x)) << UART_S1_IDLE_SHIFT)) & UART_S1_IDLE_MASK) -#define UART_S1_RDRF_MASK (0x20U) -#define UART_S1_RDRF_SHIFT (5U) -#define UART_S1_RDRF(x) (((uint8_t)(((uint8_t)(x)) << UART_S1_RDRF_SHIFT)) & UART_S1_RDRF_MASK) -#define UART_S1_TC_MASK (0x40U) -#define UART_S1_TC_SHIFT (6U) -#define UART_S1_TC(x) (((uint8_t)(((uint8_t)(x)) << UART_S1_TC_SHIFT)) & UART_S1_TC_MASK) -#define UART_S1_TDRE_MASK (0x80U) -#define UART_S1_TDRE_SHIFT (7U) -#define UART_S1_TDRE(x) (((uint8_t)(((uint8_t)(x)) << UART_S1_TDRE_SHIFT)) & UART_S1_TDRE_MASK) - -/*! @name S2 - UART Status Register 2 */ -#define UART_S2_RAF_MASK (0x1U) -#define UART_S2_RAF_SHIFT (0U) -#define UART_S2_RAF(x) (((uint8_t)(((uint8_t)(x)) << UART_S2_RAF_SHIFT)) & UART_S2_RAF_MASK) -#define UART_S2_LBKDE_MASK (0x2U) -#define UART_S2_LBKDE_SHIFT (1U) -#define UART_S2_LBKDE(x) (((uint8_t)(((uint8_t)(x)) << UART_S2_LBKDE_SHIFT)) & UART_S2_LBKDE_MASK) -#define UART_S2_BRK13_MASK (0x4U) -#define UART_S2_BRK13_SHIFT (2U) -#define UART_S2_BRK13(x) (((uint8_t)(((uint8_t)(x)) << UART_S2_BRK13_SHIFT)) & UART_S2_BRK13_MASK) -#define UART_S2_RWUID_MASK (0x8U) -#define UART_S2_RWUID_SHIFT (3U) -#define UART_S2_RWUID(x) (((uint8_t)(((uint8_t)(x)) << UART_S2_RWUID_SHIFT)) & UART_S2_RWUID_MASK) -#define UART_S2_RXINV_MASK (0x10U) -#define UART_S2_RXINV_SHIFT (4U) -#define UART_S2_RXINV(x) (((uint8_t)(((uint8_t)(x)) << UART_S2_RXINV_SHIFT)) & UART_S2_RXINV_MASK) -#define UART_S2_MSBF_MASK (0x20U) -#define UART_S2_MSBF_SHIFT (5U) -#define UART_S2_MSBF(x) (((uint8_t)(((uint8_t)(x)) << UART_S2_MSBF_SHIFT)) & UART_S2_MSBF_MASK) -#define UART_S2_RXEDGIF_MASK (0x40U) -#define UART_S2_RXEDGIF_SHIFT (6U) -#define UART_S2_RXEDGIF(x) (((uint8_t)(((uint8_t)(x)) << UART_S2_RXEDGIF_SHIFT)) & UART_S2_RXEDGIF_MASK) -#define UART_S2_LBKDIF_MASK (0x80U) -#define UART_S2_LBKDIF_SHIFT (7U) -#define UART_S2_LBKDIF(x) (((uint8_t)(((uint8_t)(x)) << UART_S2_LBKDIF_SHIFT)) & UART_S2_LBKDIF_MASK) - -/*! @name C3 - UART Control Register 3 */ -#define UART_C3_PEIE_MASK (0x1U) -#define UART_C3_PEIE_SHIFT (0U) -#define UART_C3_PEIE(x) (((uint8_t)(((uint8_t)(x)) << UART_C3_PEIE_SHIFT)) & UART_C3_PEIE_MASK) -#define UART_C3_FEIE_MASK (0x2U) -#define UART_C3_FEIE_SHIFT (1U) -#define UART_C3_FEIE(x) (((uint8_t)(((uint8_t)(x)) << UART_C3_FEIE_SHIFT)) & UART_C3_FEIE_MASK) -#define UART_C3_NEIE_MASK (0x4U) -#define UART_C3_NEIE_SHIFT (2U) -#define UART_C3_NEIE(x) (((uint8_t)(((uint8_t)(x)) << UART_C3_NEIE_SHIFT)) & UART_C3_NEIE_MASK) -#define UART_C3_ORIE_MASK (0x8U) -#define UART_C3_ORIE_SHIFT (3U) -#define UART_C3_ORIE(x) (((uint8_t)(((uint8_t)(x)) << UART_C3_ORIE_SHIFT)) & UART_C3_ORIE_MASK) -#define UART_C3_TXINV_MASK (0x10U) -#define UART_C3_TXINV_SHIFT (4U) -#define UART_C3_TXINV(x) (((uint8_t)(((uint8_t)(x)) << UART_C3_TXINV_SHIFT)) & UART_C3_TXINV_MASK) -#define UART_C3_TXDIR_MASK (0x20U) -#define UART_C3_TXDIR_SHIFT (5U) -#define UART_C3_TXDIR(x) (((uint8_t)(((uint8_t)(x)) << UART_C3_TXDIR_SHIFT)) & UART_C3_TXDIR_MASK) -#define UART_C3_T8_MASK (0x40U) -#define UART_C3_T8_SHIFT (6U) -#define UART_C3_T8(x) (((uint8_t)(((uint8_t)(x)) << UART_C3_T8_SHIFT)) & UART_C3_T8_MASK) -#define UART_C3_R8_MASK (0x80U) -#define UART_C3_R8_SHIFT (7U) -#define UART_C3_R8(x) (((uint8_t)(((uint8_t)(x)) << UART_C3_R8_SHIFT)) & UART_C3_R8_MASK) - -/*! @name D - UART Data Register */ -#define UART_D_RT_MASK (0xFFU) -#define UART_D_RT_SHIFT (0U) -#define UART_D_RT(x) (((uint8_t)(((uint8_t)(x)) << UART_D_RT_SHIFT)) & UART_D_RT_MASK) - -/*! @name MA1 - UART Match Address Registers 1 */ -#define UART_MA1_MA_MASK (0xFFU) -#define UART_MA1_MA_SHIFT (0U) -#define UART_MA1_MA(x) (((uint8_t)(((uint8_t)(x)) << UART_MA1_MA_SHIFT)) & UART_MA1_MA_MASK) - -/*! @name MA2 - UART Match Address Registers 2 */ -#define UART_MA2_MA_MASK (0xFFU) -#define UART_MA2_MA_SHIFT (0U) -#define UART_MA2_MA(x) (((uint8_t)(((uint8_t)(x)) << UART_MA2_MA_SHIFT)) & UART_MA2_MA_MASK) - -/*! @name C4 - UART Control Register 4 */ -#define UART_C4_BRFA_MASK (0x1FU) -#define UART_C4_BRFA_SHIFT (0U) -#define UART_C4_BRFA(x) (((uint8_t)(((uint8_t)(x)) << UART_C4_BRFA_SHIFT)) & UART_C4_BRFA_MASK) -#define UART_C4_M10_MASK (0x20U) -#define UART_C4_M10_SHIFT (5U) -#define UART_C4_M10(x) (((uint8_t)(((uint8_t)(x)) << UART_C4_M10_SHIFT)) & UART_C4_M10_MASK) -#define UART_C4_MAEN2_MASK (0x40U) -#define UART_C4_MAEN2_SHIFT (6U) -#define UART_C4_MAEN2(x) (((uint8_t)(((uint8_t)(x)) << UART_C4_MAEN2_SHIFT)) & UART_C4_MAEN2_MASK) -#define UART_C4_MAEN1_MASK (0x80U) -#define UART_C4_MAEN1_SHIFT (7U) -#define UART_C4_MAEN1(x) (((uint8_t)(((uint8_t)(x)) << UART_C4_MAEN1_SHIFT)) & UART_C4_MAEN1_MASK) - -/*! @name C5 - UART Control Register 5 */ -#define UART_C5_LBKDDMAS_MASK (0x8U) -#define UART_C5_LBKDDMAS_SHIFT (3U) -#define UART_C5_LBKDDMAS(x) (((uint8_t)(((uint8_t)(x)) << UART_C5_LBKDDMAS_SHIFT)) & UART_C5_LBKDDMAS_MASK) -#define UART_C5_ILDMAS_MASK (0x10U) -#define UART_C5_ILDMAS_SHIFT (4U) -#define UART_C5_ILDMAS(x) (((uint8_t)(((uint8_t)(x)) << UART_C5_ILDMAS_SHIFT)) & UART_C5_ILDMAS_MASK) -#define UART_C5_RDMAS_MASK (0x20U) -#define UART_C5_RDMAS_SHIFT (5U) -#define UART_C5_RDMAS(x) (((uint8_t)(((uint8_t)(x)) << UART_C5_RDMAS_SHIFT)) & UART_C5_RDMAS_MASK) -#define UART_C5_TCDMAS_MASK (0x40U) -#define UART_C5_TCDMAS_SHIFT (6U) -#define UART_C5_TCDMAS(x) (((uint8_t)(((uint8_t)(x)) << UART_C5_TCDMAS_SHIFT)) & UART_C5_TCDMAS_MASK) -#define UART_C5_TDMAS_MASK (0x80U) -#define UART_C5_TDMAS_SHIFT (7U) -#define UART_C5_TDMAS(x) (((uint8_t)(((uint8_t)(x)) << UART_C5_TDMAS_SHIFT)) & UART_C5_TDMAS_MASK) - -/*! @name ED - UART Extended Data Register */ -#define UART_ED_PARITYE_MASK (0x40U) -#define UART_ED_PARITYE_SHIFT (6U) -#define UART_ED_PARITYE(x) (((uint8_t)(((uint8_t)(x)) << UART_ED_PARITYE_SHIFT)) & UART_ED_PARITYE_MASK) -#define UART_ED_NOISY_MASK (0x80U) -#define UART_ED_NOISY_SHIFT (7U) -#define UART_ED_NOISY(x) (((uint8_t)(((uint8_t)(x)) << UART_ED_NOISY_SHIFT)) & UART_ED_NOISY_MASK) - -/*! @name MODEM - UART Modem Register */ -#define UART_MODEM_TXCTSE_MASK (0x1U) -#define UART_MODEM_TXCTSE_SHIFT (0U) -#define UART_MODEM_TXCTSE(x) (((uint8_t)(((uint8_t)(x)) << UART_MODEM_TXCTSE_SHIFT)) & UART_MODEM_TXCTSE_MASK) -#define UART_MODEM_TXRTSE_MASK (0x2U) -#define UART_MODEM_TXRTSE_SHIFT (1U) -#define UART_MODEM_TXRTSE(x) (((uint8_t)(((uint8_t)(x)) << UART_MODEM_TXRTSE_SHIFT)) & UART_MODEM_TXRTSE_MASK) -#define UART_MODEM_TXRTSPOL_MASK (0x4U) -#define UART_MODEM_TXRTSPOL_SHIFT (2U) -#define UART_MODEM_TXRTSPOL(x) (((uint8_t)(((uint8_t)(x)) << UART_MODEM_TXRTSPOL_SHIFT)) & UART_MODEM_TXRTSPOL_MASK) -#define UART_MODEM_RXRTSE_MASK (0x8U) -#define UART_MODEM_RXRTSE_SHIFT (3U) -#define UART_MODEM_RXRTSE(x) (((uint8_t)(((uint8_t)(x)) << UART_MODEM_RXRTSE_SHIFT)) & UART_MODEM_RXRTSE_MASK) - -/*! @name IR - UART Infrared Register */ -#define UART_IR_TNP_MASK (0x3U) -#define UART_IR_TNP_SHIFT (0U) -#define UART_IR_TNP(x) (((uint8_t)(((uint8_t)(x)) << UART_IR_TNP_SHIFT)) & UART_IR_TNP_MASK) -#define UART_IR_IREN_MASK (0x4U) -#define UART_IR_IREN_SHIFT (2U) -#define UART_IR_IREN(x) (((uint8_t)(((uint8_t)(x)) << UART_IR_IREN_SHIFT)) & UART_IR_IREN_MASK) - -/*! @name PFIFO - UART FIFO Parameters */ -#define UART_PFIFO_RXFIFOSIZE_MASK (0x7U) -#define UART_PFIFO_RXFIFOSIZE_SHIFT (0U) -#define UART_PFIFO_RXFIFOSIZE(x) (((uint8_t)(((uint8_t)(x)) << UART_PFIFO_RXFIFOSIZE_SHIFT)) & UART_PFIFO_RXFIFOSIZE_MASK) -#define UART_PFIFO_RXFE_MASK (0x8U) -#define UART_PFIFO_RXFE_SHIFT (3U) -#define UART_PFIFO_RXFE(x) (((uint8_t)(((uint8_t)(x)) << UART_PFIFO_RXFE_SHIFT)) & UART_PFIFO_RXFE_MASK) -#define UART_PFIFO_TXFIFOSIZE_MASK (0x70U) -#define UART_PFIFO_TXFIFOSIZE_SHIFT (4U) -#define UART_PFIFO_TXFIFOSIZE(x) (((uint8_t)(((uint8_t)(x)) << UART_PFIFO_TXFIFOSIZE_SHIFT)) & UART_PFIFO_TXFIFOSIZE_MASK) -#define UART_PFIFO_TXFE_MASK (0x80U) -#define UART_PFIFO_TXFE_SHIFT (7U) -#define UART_PFIFO_TXFE(x) (((uint8_t)(((uint8_t)(x)) << UART_PFIFO_TXFE_SHIFT)) & UART_PFIFO_TXFE_MASK) - -/*! @name CFIFO - UART FIFO Control Register */ -#define UART_CFIFO_RXUFE_MASK (0x1U) -#define UART_CFIFO_RXUFE_SHIFT (0U) -#define UART_CFIFO_RXUFE(x) (((uint8_t)(((uint8_t)(x)) << UART_CFIFO_RXUFE_SHIFT)) & UART_CFIFO_RXUFE_MASK) -#define UART_CFIFO_TXOFE_MASK (0x2U) -#define UART_CFIFO_TXOFE_SHIFT (1U) -#define UART_CFIFO_TXOFE(x) (((uint8_t)(((uint8_t)(x)) << UART_CFIFO_TXOFE_SHIFT)) & UART_CFIFO_TXOFE_MASK) -#define UART_CFIFO_RXOFE_MASK (0x4U) -#define UART_CFIFO_RXOFE_SHIFT (2U) -#define UART_CFIFO_RXOFE(x) (((uint8_t)(((uint8_t)(x)) << UART_CFIFO_RXOFE_SHIFT)) & UART_CFIFO_RXOFE_MASK) -#define UART_CFIFO_RXFLUSH_MASK (0x40U) -#define UART_CFIFO_RXFLUSH_SHIFT (6U) -#define UART_CFIFO_RXFLUSH(x) (((uint8_t)(((uint8_t)(x)) << UART_CFIFO_RXFLUSH_SHIFT)) & UART_CFIFO_RXFLUSH_MASK) -#define UART_CFIFO_TXFLUSH_MASK (0x80U) -#define UART_CFIFO_TXFLUSH_SHIFT (7U) -#define UART_CFIFO_TXFLUSH(x) (((uint8_t)(((uint8_t)(x)) << UART_CFIFO_TXFLUSH_SHIFT)) & UART_CFIFO_TXFLUSH_MASK) - -/*! @name SFIFO - UART FIFO Status Register */ -#define UART_SFIFO_RXUF_MASK (0x1U) -#define UART_SFIFO_RXUF_SHIFT (0U) -#define UART_SFIFO_RXUF(x) (((uint8_t)(((uint8_t)(x)) << UART_SFIFO_RXUF_SHIFT)) & UART_SFIFO_RXUF_MASK) -#define UART_SFIFO_TXOF_MASK (0x2U) -#define UART_SFIFO_TXOF_SHIFT (1U) -#define UART_SFIFO_TXOF(x) (((uint8_t)(((uint8_t)(x)) << UART_SFIFO_TXOF_SHIFT)) & UART_SFIFO_TXOF_MASK) -#define UART_SFIFO_RXOF_MASK (0x4U) -#define UART_SFIFO_RXOF_SHIFT (2U) -#define UART_SFIFO_RXOF(x) (((uint8_t)(((uint8_t)(x)) << UART_SFIFO_RXOF_SHIFT)) & UART_SFIFO_RXOF_MASK) -#define UART_SFIFO_RXEMPT_MASK (0x40U) -#define UART_SFIFO_RXEMPT_SHIFT (6U) -#define UART_SFIFO_RXEMPT(x) (((uint8_t)(((uint8_t)(x)) << UART_SFIFO_RXEMPT_SHIFT)) & UART_SFIFO_RXEMPT_MASK) -#define UART_SFIFO_TXEMPT_MASK (0x80U) -#define UART_SFIFO_TXEMPT_SHIFT (7U) -#define UART_SFIFO_TXEMPT(x) (((uint8_t)(((uint8_t)(x)) << UART_SFIFO_TXEMPT_SHIFT)) & UART_SFIFO_TXEMPT_MASK) - -/*! @name TWFIFO - UART FIFO Transmit Watermark */ -#define UART_TWFIFO_TXWATER_MASK (0xFFU) -#define UART_TWFIFO_TXWATER_SHIFT (0U) -#define UART_TWFIFO_TXWATER(x) (((uint8_t)(((uint8_t)(x)) << UART_TWFIFO_TXWATER_SHIFT)) & UART_TWFIFO_TXWATER_MASK) - -/*! @name TCFIFO - UART FIFO Transmit Count */ -#define UART_TCFIFO_TXCOUNT_MASK (0xFFU) -#define UART_TCFIFO_TXCOUNT_SHIFT (0U) -#define UART_TCFIFO_TXCOUNT(x) (((uint8_t)(((uint8_t)(x)) << UART_TCFIFO_TXCOUNT_SHIFT)) & UART_TCFIFO_TXCOUNT_MASK) - -/*! @name RWFIFO - UART FIFO Receive Watermark */ -#define UART_RWFIFO_RXWATER_MASK (0xFFU) -#define UART_RWFIFO_RXWATER_SHIFT (0U) -#define UART_RWFIFO_RXWATER(x) (((uint8_t)(((uint8_t)(x)) << UART_RWFIFO_RXWATER_SHIFT)) & UART_RWFIFO_RXWATER_MASK) - -/*! @name RCFIFO - UART FIFO Receive Count */ -#define UART_RCFIFO_RXCOUNT_MASK (0xFFU) -#define UART_RCFIFO_RXCOUNT_SHIFT (0U) -#define UART_RCFIFO_RXCOUNT(x) (((uint8_t)(((uint8_t)(x)) << UART_RCFIFO_RXCOUNT_SHIFT)) & UART_RCFIFO_RXCOUNT_MASK) - -/*! @name C7816 - UART 7816 Control Register */ -#define UART_C7816_ISO_7816E_MASK (0x1U) -#define UART_C7816_ISO_7816E_SHIFT (0U) -#define UART_C7816_ISO_7816E(x) (((uint8_t)(((uint8_t)(x)) << UART_C7816_ISO_7816E_SHIFT)) & UART_C7816_ISO_7816E_MASK) -#define UART_C7816_TTYPE_MASK (0x2U) -#define UART_C7816_TTYPE_SHIFT (1U) -#define UART_C7816_TTYPE(x) (((uint8_t)(((uint8_t)(x)) << UART_C7816_TTYPE_SHIFT)) & UART_C7816_TTYPE_MASK) -#define UART_C7816_INIT_MASK (0x4U) -#define UART_C7816_INIT_SHIFT (2U) -#define UART_C7816_INIT(x) (((uint8_t)(((uint8_t)(x)) << UART_C7816_INIT_SHIFT)) & UART_C7816_INIT_MASK) -#define UART_C7816_ANACK_MASK (0x8U) -#define UART_C7816_ANACK_SHIFT (3U) -#define UART_C7816_ANACK(x) (((uint8_t)(((uint8_t)(x)) << UART_C7816_ANACK_SHIFT)) & UART_C7816_ANACK_MASK) -#define UART_C7816_ONACK_MASK (0x10U) -#define UART_C7816_ONACK_SHIFT (4U) -#define UART_C7816_ONACK(x) (((uint8_t)(((uint8_t)(x)) << UART_C7816_ONACK_SHIFT)) & UART_C7816_ONACK_MASK) - -/*! @name IE7816 - UART 7816 Interrupt Enable Register */ -#define UART_IE7816_RXTE_MASK (0x1U) -#define UART_IE7816_RXTE_SHIFT (0U) -#define UART_IE7816_RXTE(x) (((uint8_t)(((uint8_t)(x)) << UART_IE7816_RXTE_SHIFT)) & UART_IE7816_RXTE_MASK) -#define UART_IE7816_TXTE_MASK (0x2U) -#define UART_IE7816_TXTE_SHIFT (1U) -#define UART_IE7816_TXTE(x) (((uint8_t)(((uint8_t)(x)) << UART_IE7816_TXTE_SHIFT)) & UART_IE7816_TXTE_MASK) -#define UART_IE7816_GTVE_MASK (0x4U) -#define UART_IE7816_GTVE_SHIFT (2U) -#define UART_IE7816_GTVE(x) (((uint8_t)(((uint8_t)(x)) << UART_IE7816_GTVE_SHIFT)) & UART_IE7816_GTVE_MASK) -#define UART_IE7816_INITDE_MASK (0x10U) -#define UART_IE7816_INITDE_SHIFT (4U) -#define UART_IE7816_INITDE(x) (((uint8_t)(((uint8_t)(x)) << UART_IE7816_INITDE_SHIFT)) & UART_IE7816_INITDE_MASK) -#define UART_IE7816_BWTE_MASK (0x20U) -#define UART_IE7816_BWTE_SHIFT (5U) -#define UART_IE7816_BWTE(x) (((uint8_t)(((uint8_t)(x)) << UART_IE7816_BWTE_SHIFT)) & UART_IE7816_BWTE_MASK) -#define UART_IE7816_CWTE_MASK (0x40U) -#define UART_IE7816_CWTE_SHIFT (6U) -#define UART_IE7816_CWTE(x) (((uint8_t)(((uint8_t)(x)) << UART_IE7816_CWTE_SHIFT)) & UART_IE7816_CWTE_MASK) -#define UART_IE7816_WTE_MASK (0x80U) -#define UART_IE7816_WTE_SHIFT (7U) -#define UART_IE7816_WTE(x) (((uint8_t)(((uint8_t)(x)) << UART_IE7816_WTE_SHIFT)) & UART_IE7816_WTE_MASK) - -/*! @name IS7816 - UART 7816 Interrupt Status Register */ -#define UART_IS7816_RXT_MASK (0x1U) -#define UART_IS7816_RXT_SHIFT (0U) -#define UART_IS7816_RXT(x) (((uint8_t)(((uint8_t)(x)) << UART_IS7816_RXT_SHIFT)) & UART_IS7816_RXT_MASK) -#define UART_IS7816_TXT_MASK (0x2U) -#define UART_IS7816_TXT_SHIFT (1U) -#define UART_IS7816_TXT(x) (((uint8_t)(((uint8_t)(x)) << UART_IS7816_TXT_SHIFT)) & UART_IS7816_TXT_MASK) -#define UART_IS7816_GTV_MASK (0x4U) -#define UART_IS7816_GTV_SHIFT (2U) -#define UART_IS7816_GTV(x) (((uint8_t)(((uint8_t)(x)) << UART_IS7816_GTV_SHIFT)) & UART_IS7816_GTV_MASK) -#define UART_IS7816_INITD_MASK (0x10U) -#define UART_IS7816_INITD_SHIFT (4U) -#define UART_IS7816_INITD(x) (((uint8_t)(((uint8_t)(x)) << UART_IS7816_INITD_SHIFT)) & UART_IS7816_INITD_MASK) -#define UART_IS7816_BWT_MASK (0x20U) -#define UART_IS7816_BWT_SHIFT (5U) -#define UART_IS7816_BWT(x) (((uint8_t)(((uint8_t)(x)) << UART_IS7816_BWT_SHIFT)) & UART_IS7816_BWT_MASK) -#define UART_IS7816_CWT_MASK (0x40U) -#define UART_IS7816_CWT_SHIFT (6U) -#define UART_IS7816_CWT(x) (((uint8_t)(((uint8_t)(x)) << UART_IS7816_CWT_SHIFT)) & UART_IS7816_CWT_MASK) -#define UART_IS7816_WT_MASK (0x80U) -#define UART_IS7816_WT_SHIFT (7U) -#define UART_IS7816_WT(x) (((uint8_t)(((uint8_t)(x)) << UART_IS7816_WT_SHIFT)) & UART_IS7816_WT_MASK) - -/*! @name WP7816T0 - UART 7816 Wait Parameter Register */ -#define UART_WP7816T0_WI_MASK (0xFFU) -#define UART_WP7816T0_WI_SHIFT (0U) -#define UART_WP7816T0_WI(x) (((uint8_t)(((uint8_t)(x)) << UART_WP7816T0_WI_SHIFT)) & UART_WP7816T0_WI_MASK) - -/*! @name WP7816T1 - UART 7816 Wait Parameter Register */ -#define UART_WP7816T1_BWI_MASK (0xFU) -#define UART_WP7816T1_BWI_SHIFT (0U) -#define UART_WP7816T1_BWI(x) (((uint8_t)(((uint8_t)(x)) << UART_WP7816T1_BWI_SHIFT)) & UART_WP7816T1_BWI_MASK) -#define UART_WP7816T1_CWI_MASK (0xF0U) -#define UART_WP7816T1_CWI_SHIFT (4U) -#define UART_WP7816T1_CWI(x) (((uint8_t)(((uint8_t)(x)) << UART_WP7816T1_CWI_SHIFT)) & UART_WP7816T1_CWI_MASK) - -/*! @name WN7816 - UART 7816 Wait N Register */ -#define UART_WN7816_GTN_MASK (0xFFU) -#define UART_WN7816_GTN_SHIFT (0U) -#define UART_WN7816_GTN(x) (((uint8_t)(((uint8_t)(x)) << UART_WN7816_GTN_SHIFT)) & UART_WN7816_GTN_MASK) - -/*! @name WF7816 - UART 7816 Wait FD Register */ -#define UART_WF7816_GTFD_MASK (0xFFU) -#define UART_WF7816_GTFD_SHIFT (0U) -#define UART_WF7816_GTFD(x) (((uint8_t)(((uint8_t)(x)) << UART_WF7816_GTFD_SHIFT)) & UART_WF7816_GTFD_MASK) - -/*! @name ET7816 - UART 7816 Error Threshold Register */ -#define UART_ET7816_RXTHRESHOLD_MASK (0xFU) -#define UART_ET7816_RXTHRESHOLD_SHIFT (0U) -#define UART_ET7816_RXTHRESHOLD(x) (((uint8_t)(((uint8_t)(x)) << UART_ET7816_RXTHRESHOLD_SHIFT)) & UART_ET7816_RXTHRESHOLD_MASK) -#define UART_ET7816_TXTHRESHOLD_MASK (0xF0U) -#define UART_ET7816_TXTHRESHOLD_SHIFT (4U) -#define UART_ET7816_TXTHRESHOLD(x) (((uint8_t)(((uint8_t)(x)) << UART_ET7816_TXTHRESHOLD_SHIFT)) & UART_ET7816_TXTHRESHOLD_MASK) - -/*! @name TL7816 - UART 7816 Transmit Length Register */ -#define UART_TL7816_TLEN_MASK (0xFFU) -#define UART_TL7816_TLEN_SHIFT (0U) -#define UART_TL7816_TLEN(x) (((uint8_t)(((uint8_t)(x)) << UART_TL7816_TLEN_SHIFT)) & UART_TL7816_TLEN_MASK) - - -/*! - * @} - */ /* end of group UART_Register_Masks */ - - -/* UART - Peripheral instance base addresses */ -/** Peripheral UART0 base address */ -#define UART0_BASE (0x4006A000u) -/** Peripheral UART0 base pointer */ -#define UART0 ((UART_Type *)UART0_BASE) -/** Peripheral UART1 base address */ -#define UART1_BASE (0x4006B000u) -/** Peripheral UART1 base pointer */ -#define UART1 ((UART_Type *)UART1_BASE) -/** Peripheral UART2 base address */ -#define UART2_BASE (0x4006C000u) -/** Peripheral UART2 base pointer */ -#define UART2 ((UART_Type *)UART2_BASE) -/** Peripheral UART3 base address */ -#define UART3_BASE (0x4006D000u) -/** Peripheral UART3 base pointer */ -#define UART3 ((UART_Type *)UART3_BASE) -/** Peripheral UART4 base address */ -#define UART4_BASE (0x400EA000u) -/** Peripheral UART4 base pointer */ -#define UART4 ((UART_Type *)UART4_BASE) -/** Peripheral UART5 base address */ -#define UART5_BASE (0x400EB000u) -/** Peripheral UART5 base pointer */ -#define UART5 ((UART_Type *)UART5_BASE) -/** Array initializer of UART peripheral base addresses */ -#define UART_BASE_ADDRS { UART0_BASE, UART1_BASE, UART2_BASE, UART3_BASE, UART4_BASE, UART5_BASE } -/** Array initializer of UART peripheral base pointers */ -#define UART_BASE_PTRS { UART0, UART1, UART2, UART3, UART4, UART5 } -/** Interrupt vectors for the UART peripheral type */ -#define UART_RX_TX_IRQS { UART0_RX_TX_IRQn, UART1_RX_TX_IRQn, UART2_RX_TX_IRQn, UART3_RX_TX_IRQn, UART4_RX_TX_IRQn, UART5_RX_TX_IRQn } -#define UART_ERR_IRQS { UART0_ERR_IRQn, UART1_ERR_IRQn, UART2_ERR_IRQn, UART3_ERR_IRQn, UART4_ERR_IRQn, UART5_ERR_IRQn } -#define UART_LON_IRQS { UART0_LON_IRQn, NotAvail_IRQn, NotAvail_IRQn, NotAvail_IRQn, NotAvail_IRQn, NotAvail_IRQn } - -/*! - * @} - */ /* end of group UART_Peripheral_Access_Layer */ - - -/* ---------------------------------------------------------------------------- - -- USB Peripheral Access Layer - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup USB_Peripheral_Access_Layer USB Peripheral Access Layer - * @{ - */ - -/** USB - Register Layout Typedef */ -typedef struct { - __I uint8_t PERID; /**< Peripheral ID register, offset: 0x0 */ - uint8_t RESERVED_0[3]; - __I uint8_t IDCOMP; /**< Peripheral ID Complement register, offset: 0x4 */ - uint8_t RESERVED_1[3]; - __I uint8_t REV; /**< Peripheral Revision register, offset: 0x8 */ - uint8_t RESERVED_2[3]; - __I uint8_t ADDINFO; /**< Peripheral Additional Info register, offset: 0xC */ - uint8_t RESERVED_3[3]; - __IO uint8_t OTGISTAT; /**< OTG Interrupt Status register, offset: 0x10 */ - uint8_t RESERVED_4[3]; - __IO uint8_t OTGICR; /**< OTG Interrupt Control register, offset: 0x14 */ - uint8_t RESERVED_5[3]; - __IO uint8_t OTGSTAT; /**< OTG Status register, offset: 0x18 */ - uint8_t RESERVED_6[3]; - __IO uint8_t OTGCTL; /**< OTG Control register, offset: 0x1C */ - uint8_t RESERVED_7[99]; - __IO uint8_t ISTAT; /**< Interrupt Status register, offset: 0x80 */ - uint8_t RESERVED_8[3]; - __IO uint8_t INTEN; /**< Interrupt Enable register, offset: 0x84 */ - uint8_t RESERVED_9[3]; - __IO uint8_t ERRSTAT; /**< Error Interrupt Status register, offset: 0x88 */ - uint8_t RESERVED_10[3]; - __IO uint8_t ERREN; /**< Error Interrupt Enable register, offset: 0x8C */ - uint8_t RESERVED_11[3]; - __I uint8_t STAT; /**< Status register, offset: 0x90 */ - uint8_t RESERVED_12[3]; - __IO uint8_t CTL; /**< Control register, offset: 0x94 */ - uint8_t RESERVED_13[3]; - __IO uint8_t ADDR; /**< Address register, offset: 0x98 */ - uint8_t RESERVED_14[3]; - __IO uint8_t BDTPAGE1; /**< BDT Page register 1, offset: 0x9C */ - uint8_t RESERVED_15[3]; - __IO uint8_t FRMNUML; /**< Frame Number register Low, offset: 0xA0 */ - uint8_t RESERVED_16[3]; - __IO uint8_t FRMNUMH; /**< Frame Number register High, offset: 0xA4 */ - uint8_t RESERVED_17[3]; - __IO uint8_t TOKEN; /**< Token register, offset: 0xA8 */ - uint8_t RESERVED_18[3]; - __IO uint8_t SOFTHLD; /**< SOF Threshold register, offset: 0xAC */ - uint8_t RESERVED_19[3]; - __IO uint8_t BDTPAGE2; /**< BDT Page Register 2, offset: 0xB0 */ - uint8_t RESERVED_20[3]; - __IO uint8_t BDTPAGE3; /**< BDT Page Register 3, offset: 0xB4 */ - uint8_t RESERVED_21[11]; - struct { /* offset: 0xC0, array step: 0x4 */ - __IO uint8_t ENDPT; /**< Endpoint Control register, array offset: 0xC0, array step: 0x4 */ - uint8_t RESERVED_0[3]; - } ENDPOINT[16]; - __IO uint8_t USBCTRL; /**< USB Control register, offset: 0x100 */ - uint8_t RESERVED_22[3]; - __I uint8_t OBSERVE; /**< USB OTG Observe register, offset: 0x104 */ - uint8_t RESERVED_23[3]; - __IO uint8_t CONTROL; /**< USB OTG Control register, offset: 0x108 */ - uint8_t RESERVED_24[3]; - __IO uint8_t USBTRC0; /**< USB Transceiver Control register 0, offset: 0x10C */ - uint8_t RESERVED_25[7]; - __IO uint8_t USBFRMADJUST; /**< Frame Adjust Register, offset: 0x114 */ - uint8_t RESERVED_26[43]; - __IO uint8_t CLK_RECOVER_CTRL; /**< USB Clock recovery control, offset: 0x140 */ - uint8_t RESERVED_27[3]; - __IO uint8_t CLK_RECOVER_IRC_EN; /**< IRC48M oscillator enable register, offset: 0x144 */ - uint8_t RESERVED_28[23]; - __IO uint8_t CLK_RECOVER_INT_STATUS; /**< Clock recovery separated interrupt status, offset: 0x15C */ -} USB_Type; - -/* ---------------------------------------------------------------------------- - -- USB Register Masks - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup USB_Register_Masks USB Register Masks - * @{ - */ - -/*! @name PERID - Peripheral ID register */ -#define USB_PERID_ID_MASK (0x3FU) -#define USB_PERID_ID_SHIFT (0U) -#define USB_PERID_ID(x) (((uint8_t)(((uint8_t)(x)) << USB_PERID_ID_SHIFT)) & USB_PERID_ID_MASK) - -/*! @name IDCOMP - Peripheral ID Complement register */ -#define USB_IDCOMP_NID_MASK (0x3FU) -#define USB_IDCOMP_NID_SHIFT (0U) -#define USB_IDCOMP_NID(x) (((uint8_t)(((uint8_t)(x)) << USB_IDCOMP_NID_SHIFT)) & USB_IDCOMP_NID_MASK) - -/*! @name REV - Peripheral Revision register */ -#define USB_REV_REV_MASK (0xFFU) -#define USB_REV_REV_SHIFT (0U) -#define USB_REV_REV(x) (((uint8_t)(((uint8_t)(x)) << USB_REV_REV_SHIFT)) & USB_REV_REV_MASK) - -/*! @name ADDINFO - Peripheral Additional Info register */ -#define USB_ADDINFO_IEHOST_MASK (0x1U) -#define USB_ADDINFO_IEHOST_SHIFT (0U) -#define USB_ADDINFO_IEHOST(x) (((uint8_t)(((uint8_t)(x)) << USB_ADDINFO_IEHOST_SHIFT)) & USB_ADDINFO_IEHOST_MASK) -#define USB_ADDINFO_IRQNUM_MASK (0xF8U) -#define USB_ADDINFO_IRQNUM_SHIFT (3U) -#define USB_ADDINFO_IRQNUM(x) (((uint8_t)(((uint8_t)(x)) << USB_ADDINFO_IRQNUM_SHIFT)) & USB_ADDINFO_IRQNUM_MASK) - -/*! @name OTGISTAT - OTG Interrupt Status register */ -#define USB_OTGISTAT_AVBUSCHG_MASK (0x1U) -#define USB_OTGISTAT_AVBUSCHG_SHIFT (0U) -#define USB_OTGISTAT_AVBUSCHG(x) (((uint8_t)(((uint8_t)(x)) << USB_OTGISTAT_AVBUSCHG_SHIFT)) & USB_OTGISTAT_AVBUSCHG_MASK) -#define USB_OTGISTAT_B_SESS_CHG_MASK (0x4U) -#define USB_OTGISTAT_B_SESS_CHG_SHIFT (2U) -#define USB_OTGISTAT_B_SESS_CHG(x) (((uint8_t)(((uint8_t)(x)) << USB_OTGISTAT_B_SESS_CHG_SHIFT)) & USB_OTGISTAT_B_SESS_CHG_MASK) -#define USB_OTGISTAT_SESSVLDCHG_MASK (0x8U) -#define USB_OTGISTAT_SESSVLDCHG_SHIFT (3U) -#define USB_OTGISTAT_SESSVLDCHG(x) (((uint8_t)(((uint8_t)(x)) << USB_OTGISTAT_SESSVLDCHG_SHIFT)) & USB_OTGISTAT_SESSVLDCHG_MASK) -#define USB_OTGISTAT_LINE_STATE_CHG_MASK (0x20U) -#define USB_OTGISTAT_LINE_STATE_CHG_SHIFT (5U) -#define USB_OTGISTAT_LINE_STATE_CHG(x) (((uint8_t)(((uint8_t)(x)) << USB_OTGISTAT_LINE_STATE_CHG_SHIFT)) & USB_OTGISTAT_LINE_STATE_CHG_MASK) -#define USB_OTGISTAT_ONEMSEC_MASK (0x40U) -#define USB_OTGISTAT_ONEMSEC_SHIFT (6U) -#define USB_OTGISTAT_ONEMSEC(x) (((uint8_t)(((uint8_t)(x)) << USB_OTGISTAT_ONEMSEC_SHIFT)) & USB_OTGISTAT_ONEMSEC_MASK) -#define USB_OTGISTAT_IDCHG_MASK (0x80U) -#define USB_OTGISTAT_IDCHG_SHIFT (7U) -#define USB_OTGISTAT_IDCHG(x) (((uint8_t)(((uint8_t)(x)) << USB_OTGISTAT_IDCHG_SHIFT)) & USB_OTGISTAT_IDCHG_MASK) - -/*! @name OTGICR - OTG Interrupt Control register */ -#define USB_OTGICR_AVBUSEN_MASK (0x1U) -#define USB_OTGICR_AVBUSEN_SHIFT (0U) -#define USB_OTGICR_AVBUSEN(x) (((uint8_t)(((uint8_t)(x)) << USB_OTGICR_AVBUSEN_SHIFT)) & USB_OTGICR_AVBUSEN_MASK) -#define USB_OTGICR_BSESSEN_MASK (0x4U) -#define USB_OTGICR_BSESSEN_SHIFT (2U) -#define USB_OTGICR_BSESSEN(x) (((uint8_t)(((uint8_t)(x)) << USB_OTGICR_BSESSEN_SHIFT)) & USB_OTGICR_BSESSEN_MASK) -#define USB_OTGICR_SESSVLDEN_MASK (0x8U) -#define USB_OTGICR_SESSVLDEN_SHIFT (3U) -#define USB_OTGICR_SESSVLDEN(x) (((uint8_t)(((uint8_t)(x)) << USB_OTGICR_SESSVLDEN_SHIFT)) & USB_OTGICR_SESSVLDEN_MASK) -#define USB_OTGICR_LINESTATEEN_MASK (0x20U) -#define USB_OTGICR_LINESTATEEN_SHIFT (5U) -#define USB_OTGICR_LINESTATEEN(x) (((uint8_t)(((uint8_t)(x)) << USB_OTGICR_LINESTATEEN_SHIFT)) & USB_OTGICR_LINESTATEEN_MASK) -#define USB_OTGICR_ONEMSECEN_MASK (0x40U) -#define USB_OTGICR_ONEMSECEN_SHIFT (6U) -#define USB_OTGICR_ONEMSECEN(x) (((uint8_t)(((uint8_t)(x)) << USB_OTGICR_ONEMSECEN_SHIFT)) & USB_OTGICR_ONEMSECEN_MASK) -#define USB_OTGICR_IDEN_MASK (0x80U) -#define USB_OTGICR_IDEN_SHIFT (7U) -#define USB_OTGICR_IDEN(x) (((uint8_t)(((uint8_t)(x)) << USB_OTGICR_IDEN_SHIFT)) & USB_OTGICR_IDEN_MASK) - -/*! @name OTGSTAT - OTG Status register */ -#define USB_OTGSTAT_AVBUSVLD_MASK (0x1U) -#define USB_OTGSTAT_AVBUSVLD_SHIFT (0U) -#define USB_OTGSTAT_AVBUSVLD(x) (((uint8_t)(((uint8_t)(x)) << USB_OTGSTAT_AVBUSVLD_SHIFT)) & USB_OTGSTAT_AVBUSVLD_MASK) -#define USB_OTGSTAT_BSESSEND_MASK (0x4U) -#define USB_OTGSTAT_BSESSEND_SHIFT (2U) -#define USB_OTGSTAT_BSESSEND(x) (((uint8_t)(((uint8_t)(x)) << USB_OTGSTAT_BSESSEND_SHIFT)) & USB_OTGSTAT_BSESSEND_MASK) -#define USB_OTGSTAT_SESS_VLD_MASK (0x8U) -#define USB_OTGSTAT_SESS_VLD_SHIFT (3U) -#define USB_OTGSTAT_SESS_VLD(x) (((uint8_t)(((uint8_t)(x)) << USB_OTGSTAT_SESS_VLD_SHIFT)) & USB_OTGSTAT_SESS_VLD_MASK) -#define USB_OTGSTAT_LINESTATESTABLE_MASK (0x20U) -#define USB_OTGSTAT_LINESTATESTABLE_SHIFT (5U) -#define USB_OTGSTAT_LINESTATESTABLE(x) (((uint8_t)(((uint8_t)(x)) << USB_OTGSTAT_LINESTATESTABLE_SHIFT)) & USB_OTGSTAT_LINESTATESTABLE_MASK) -#define USB_OTGSTAT_ONEMSECEN_MASK (0x40U) -#define USB_OTGSTAT_ONEMSECEN_SHIFT (6U) -#define USB_OTGSTAT_ONEMSECEN(x) (((uint8_t)(((uint8_t)(x)) << USB_OTGSTAT_ONEMSECEN_SHIFT)) & USB_OTGSTAT_ONEMSECEN_MASK) -#define USB_OTGSTAT_ID_MASK (0x80U) -#define USB_OTGSTAT_ID_SHIFT (7U) -#define USB_OTGSTAT_ID(x) (((uint8_t)(((uint8_t)(x)) << USB_OTGSTAT_ID_SHIFT)) & USB_OTGSTAT_ID_MASK) - -/*! @name OTGCTL - OTG Control register */ -#define USB_OTGCTL_OTGEN_MASK (0x4U) -#define USB_OTGCTL_OTGEN_SHIFT (2U) -#define USB_OTGCTL_OTGEN(x) (((uint8_t)(((uint8_t)(x)) << USB_OTGCTL_OTGEN_SHIFT)) & USB_OTGCTL_OTGEN_MASK) -#define USB_OTGCTL_DMLOW_MASK (0x10U) -#define USB_OTGCTL_DMLOW_SHIFT (4U) -#define USB_OTGCTL_DMLOW(x) (((uint8_t)(((uint8_t)(x)) << USB_OTGCTL_DMLOW_SHIFT)) & USB_OTGCTL_DMLOW_MASK) -#define USB_OTGCTL_DPLOW_MASK (0x20U) -#define USB_OTGCTL_DPLOW_SHIFT (5U) -#define USB_OTGCTL_DPLOW(x) (((uint8_t)(((uint8_t)(x)) << USB_OTGCTL_DPLOW_SHIFT)) & USB_OTGCTL_DPLOW_MASK) -#define USB_OTGCTL_DPHIGH_MASK (0x80U) -#define USB_OTGCTL_DPHIGH_SHIFT (7U) -#define USB_OTGCTL_DPHIGH(x) (((uint8_t)(((uint8_t)(x)) << USB_OTGCTL_DPHIGH_SHIFT)) & USB_OTGCTL_DPHIGH_MASK) - -/*! @name ISTAT - Interrupt Status register */ -#define USB_ISTAT_USBRST_MASK (0x1U) -#define USB_ISTAT_USBRST_SHIFT (0U) -#define USB_ISTAT_USBRST(x) (((uint8_t)(((uint8_t)(x)) << USB_ISTAT_USBRST_SHIFT)) & USB_ISTAT_USBRST_MASK) -#define USB_ISTAT_ERROR_MASK (0x2U) -#define USB_ISTAT_ERROR_SHIFT (1U) -#define USB_ISTAT_ERROR(x) (((uint8_t)(((uint8_t)(x)) << USB_ISTAT_ERROR_SHIFT)) & USB_ISTAT_ERROR_MASK) -#define USB_ISTAT_SOFTOK_MASK (0x4U) -#define USB_ISTAT_SOFTOK_SHIFT (2U) -#define USB_ISTAT_SOFTOK(x) (((uint8_t)(((uint8_t)(x)) << USB_ISTAT_SOFTOK_SHIFT)) & USB_ISTAT_SOFTOK_MASK) -#define USB_ISTAT_TOKDNE_MASK (0x8U) -#define USB_ISTAT_TOKDNE_SHIFT (3U) -#define USB_ISTAT_TOKDNE(x) (((uint8_t)(((uint8_t)(x)) << USB_ISTAT_TOKDNE_SHIFT)) & USB_ISTAT_TOKDNE_MASK) -#define USB_ISTAT_SLEEP_MASK (0x10U) -#define USB_ISTAT_SLEEP_SHIFT (4U) -#define USB_ISTAT_SLEEP(x) (((uint8_t)(((uint8_t)(x)) << USB_ISTAT_SLEEP_SHIFT)) & USB_ISTAT_SLEEP_MASK) -#define USB_ISTAT_RESUME_MASK (0x20U) -#define USB_ISTAT_RESUME_SHIFT (5U) -#define USB_ISTAT_RESUME(x) (((uint8_t)(((uint8_t)(x)) << USB_ISTAT_RESUME_SHIFT)) & USB_ISTAT_RESUME_MASK) -#define USB_ISTAT_ATTACH_MASK (0x40U) -#define USB_ISTAT_ATTACH_SHIFT (6U) -#define USB_ISTAT_ATTACH(x) (((uint8_t)(((uint8_t)(x)) << USB_ISTAT_ATTACH_SHIFT)) & USB_ISTAT_ATTACH_MASK) -#define USB_ISTAT_STALL_MASK (0x80U) -#define USB_ISTAT_STALL_SHIFT (7U) -#define USB_ISTAT_STALL(x) (((uint8_t)(((uint8_t)(x)) << USB_ISTAT_STALL_SHIFT)) & USB_ISTAT_STALL_MASK) - -/*! @name INTEN - Interrupt Enable register */ -#define USB_INTEN_USBRSTEN_MASK (0x1U) -#define USB_INTEN_USBRSTEN_SHIFT (0U) -#define USB_INTEN_USBRSTEN(x) (((uint8_t)(((uint8_t)(x)) << USB_INTEN_USBRSTEN_SHIFT)) & USB_INTEN_USBRSTEN_MASK) -#define USB_INTEN_ERROREN_MASK (0x2U) -#define USB_INTEN_ERROREN_SHIFT (1U) -#define USB_INTEN_ERROREN(x) (((uint8_t)(((uint8_t)(x)) << USB_INTEN_ERROREN_SHIFT)) & USB_INTEN_ERROREN_MASK) -#define USB_INTEN_SOFTOKEN_MASK (0x4U) -#define USB_INTEN_SOFTOKEN_SHIFT (2U) -#define USB_INTEN_SOFTOKEN(x) (((uint8_t)(((uint8_t)(x)) << USB_INTEN_SOFTOKEN_SHIFT)) & USB_INTEN_SOFTOKEN_MASK) -#define USB_INTEN_TOKDNEEN_MASK (0x8U) -#define USB_INTEN_TOKDNEEN_SHIFT (3U) -#define USB_INTEN_TOKDNEEN(x) (((uint8_t)(((uint8_t)(x)) << USB_INTEN_TOKDNEEN_SHIFT)) & USB_INTEN_TOKDNEEN_MASK) -#define USB_INTEN_SLEEPEN_MASK (0x10U) -#define USB_INTEN_SLEEPEN_SHIFT (4U) -#define USB_INTEN_SLEEPEN(x) (((uint8_t)(((uint8_t)(x)) << USB_INTEN_SLEEPEN_SHIFT)) & USB_INTEN_SLEEPEN_MASK) -#define USB_INTEN_RESUMEEN_MASK (0x20U) -#define USB_INTEN_RESUMEEN_SHIFT (5U) -#define USB_INTEN_RESUMEEN(x) (((uint8_t)(((uint8_t)(x)) << USB_INTEN_RESUMEEN_SHIFT)) & USB_INTEN_RESUMEEN_MASK) -#define USB_INTEN_ATTACHEN_MASK (0x40U) -#define USB_INTEN_ATTACHEN_SHIFT (6U) -#define USB_INTEN_ATTACHEN(x) (((uint8_t)(((uint8_t)(x)) << USB_INTEN_ATTACHEN_SHIFT)) & USB_INTEN_ATTACHEN_MASK) -#define USB_INTEN_STALLEN_MASK (0x80U) -#define USB_INTEN_STALLEN_SHIFT (7U) -#define USB_INTEN_STALLEN(x) (((uint8_t)(((uint8_t)(x)) << USB_INTEN_STALLEN_SHIFT)) & USB_INTEN_STALLEN_MASK) - -/*! @name ERRSTAT - Error Interrupt Status register */ -#define USB_ERRSTAT_PIDERR_MASK (0x1U) -#define USB_ERRSTAT_PIDERR_SHIFT (0U) -#define USB_ERRSTAT_PIDERR(x) (((uint8_t)(((uint8_t)(x)) << USB_ERRSTAT_PIDERR_SHIFT)) & USB_ERRSTAT_PIDERR_MASK) -#define USB_ERRSTAT_CRC5EOF_MASK (0x2U) -#define USB_ERRSTAT_CRC5EOF_SHIFT (1U) -#define USB_ERRSTAT_CRC5EOF(x) (((uint8_t)(((uint8_t)(x)) << USB_ERRSTAT_CRC5EOF_SHIFT)) & USB_ERRSTAT_CRC5EOF_MASK) -#define USB_ERRSTAT_CRC16_MASK (0x4U) -#define USB_ERRSTAT_CRC16_SHIFT (2U) -#define USB_ERRSTAT_CRC16(x) (((uint8_t)(((uint8_t)(x)) << USB_ERRSTAT_CRC16_SHIFT)) & USB_ERRSTAT_CRC16_MASK) -#define USB_ERRSTAT_DFN8_MASK (0x8U) -#define USB_ERRSTAT_DFN8_SHIFT (3U) -#define USB_ERRSTAT_DFN8(x) (((uint8_t)(((uint8_t)(x)) << USB_ERRSTAT_DFN8_SHIFT)) & USB_ERRSTAT_DFN8_MASK) -#define USB_ERRSTAT_BTOERR_MASK (0x10U) -#define USB_ERRSTAT_BTOERR_SHIFT (4U) -#define USB_ERRSTAT_BTOERR(x) (((uint8_t)(((uint8_t)(x)) << USB_ERRSTAT_BTOERR_SHIFT)) & USB_ERRSTAT_BTOERR_MASK) -#define USB_ERRSTAT_DMAERR_MASK (0x20U) -#define USB_ERRSTAT_DMAERR_SHIFT (5U) -#define USB_ERRSTAT_DMAERR(x) (((uint8_t)(((uint8_t)(x)) << USB_ERRSTAT_DMAERR_SHIFT)) & USB_ERRSTAT_DMAERR_MASK) -#define USB_ERRSTAT_BTSERR_MASK (0x80U) -#define USB_ERRSTAT_BTSERR_SHIFT (7U) -#define USB_ERRSTAT_BTSERR(x) (((uint8_t)(((uint8_t)(x)) << USB_ERRSTAT_BTSERR_SHIFT)) & USB_ERRSTAT_BTSERR_MASK) - -/*! @name ERREN - Error Interrupt Enable register */ -#define USB_ERREN_PIDERREN_MASK (0x1U) -#define USB_ERREN_PIDERREN_SHIFT (0U) -#define USB_ERREN_PIDERREN(x) (((uint8_t)(((uint8_t)(x)) << USB_ERREN_PIDERREN_SHIFT)) & USB_ERREN_PIDERREN_MASK) -#define USB_ERREN_CRC5EOFEN_MASK (0x2U) -#define USB_ERREN_CRC5EOFEN_SHIFT (1U) -#define USB_ERREN_CRC5EOFEN(x) (((uint8_t)(((uint8_t)(x)) << USB_ERREN_CRC5EOFEN_SHIFT)) & USB_ERREN_CRC5EOFEN_MASK) -#define USB_ERREN_CRC16EN_MASK (0x4U) -#define USB_ERREN_CRC16EN_SHIFT (2U) -#define USB_ERREN_CRC16EN(x) (((uint8_t)(((uint8_t)(x)) << USB_ERREN_CRC16EN_SHIFT)) & USB_ERREN_CRC16EN_MASK) -#define USB_ERREN_DFN8EN_MASK (0x8U) -#define USB_ERREN_DFN8EN_SHIFT (3U) -#define USB_ERREN_DFN8EN(x) (((uint8_t)(((uint8_t)(x)) << USB_ERREN_DFN8EN_SHIFT)) & USB_ERREN_DFN8EN_MASK) -#define USB_ERREN_BTOERREN_MASK (0x10U) -#define USB_ERREN_BTOERREN_SHIFT (4U) -#define USB_ERREN_BTOERREN(x) (((uint8_t)(((uint8_t)(x)) << USB_ERREN_BTOERREN_SHIFT)) & USB_ERREN_BTOERREN_MASK) -#define USB_ERREN_DMAERREN_MASK (0x20U) -#define USB_ERREN_DMAERREN_SHIFT (5U) -#define USB_ERREN_DMAERREN(x) (((uint8_t)(((uint8_t)(x)) << USB_ERREN_DMAERREN_SHIFT)) & USB_ERREN_DMAERREN_MASK) -#define USB_ERREN_BTSERREN_MASK (0x80U) -#define USB_ERREN_BTSERREN_SHIFT (7U) -#define USB_ERREN_BTSERREN(x) (((uint8_t)(((uint8_t)(x)) << USB_ERREN_BTSERREN_SHIFT)) & USB_ERREN_BTSERREN_MASK) - -/*! @name STAT - Status register */ -#define USB_STAT_ODD_MASK (0x4U) -#define USB_STAT_ODD_SHIFT (2U) -#define USB_STAT_ODD(x) (((uint8_t)(((uint8_t)(x)) << USB_STAT_ODD_SHIFT)) & USB_STAT_ODD_MASK) -#define USB_STAT_TX_MASK (0x8U) -#define USB_STAT_TX_SHIFT (3U) -#define USB_STAT_TX(x) (((uint8_t)(((uint8_t)(x)) << USB_STAT_TX_SHIFT)) & USB_STAT_TX_MASK) -#define USB_STAT_ENDP_MASK (0xF0U) -#define USB_STAT_ENDP_SHIFT (4U) -#define USB_STAT_ENDP(x) (((uint8_t)(((uint8_t)(x)) << USB_STAT_ENDP_SHIFT)) & USB_STAT_ENDP_MASK) - -/*! @name CTL - Control register */ -#define USB_CTL_USBENSOFEN_MASK (0x1U) -#define USB_CTL_USBENSOFEN_SHIFT (0U) -#define USB_CTL_USBENSOFEN(x) (((uint8_t)(((uint8_t)(x)) << USB_CTL_USBENSOFEN_SHIFT)) & USB_CTL_USBENSOFEN_MASK) -#define USB_CTL_ODDRST_MASK (0x2U) -#define USB_CTL_ODDRST_SHIFT (1U) -#define USB_CTL_ODDRST(x) (((uint8_t)(((uint8_t)(x)) << USB_CTL_ODDRST_SHIFT)) & USB_CTL_ODDRST_MASK) -#define USB_CTL_RESUME_MASK (0x4U) -#define USB_CTL_RESUME_SHIFT (2U) -#define USB_CTL_RESUME(x) (((uint8_t)(((uint8_t)(x)) << USB_CTL_RESUME_SHIFT)) & USB_CTL_RESUME_MASK) -#define USB_CTL_HOSTMODEEN_MASK (0x8U) -#define USB_CTL_HOSTMODEEN_SHIFT (3U) -#define USB_CTL_HOSTMODEEN(x) (((uint8_t)(((uint8_t)(x)) << USB_CTL_HOSTMODEEN_SHIFT)) & USB_CTL_HOSTMODEEN_MASK) -#define USB_CTL_RESET_MASK (0x10U) -#define USB_CTL_RESET_SHIFT (4U) -#define USB_CTL_RESET(x) (((uint8_t)(((uint8_t)(x)) << USB_CTL_RESET_SHIFT)) & USB_CTL_RESET_MASK) -#define USB_CTL_TXSUSPENDTOKENBUSY_MASK (0x20U) -#define USB_CTL_TXSUSPENDTOKENBUSY_SHIFT (5U) -#define USB_CTL_TXSUSPENDTOKENBUSY(x) (((uint8_t)(((uint8_t)(x)) << USB_CTL_TXSUSPENDTOKENBUSY_SHIFT)) & USB_CTL_TXSUSPENDTOKENBUSY_MASK) -#define USB_CTL_SE0_MASK (0x40U) -#define USB_CTL_SE0_SHIFT (6U) -#define USB_CTL_SE0(x) (((uint8_t)(((uint8_t)(x)) << USB_CTL_SE0_SHIFT)) & USB_CTL_SE0_MASK) -#define USB_CTL_JSTATE_MASK (0x80U) -#define USB_CTL_JSTATE_SHIFT (7U) -#define USB_CTL_JSTATE(x) (((uint8_t)(((uint8_t)(x)) << USB_CTL_JSTATE_SHIFT)) & USB_CTL_JSTATE_MASK) - -/*! @name ADDR - Address register */ -#define USB_ADDR_ADDR_MASK (0x7FU) -#define USB_ADDR_ADDR_SHIFT (0U) -#define USB_ADDR_ADDR(x) (((uint8_t)(((uint8_t)(x)) << USB_ADDR_ADDR_SHIFT)) & USB_ADDR_ADDR_MASK) -#define USB_ADDR_LSEN_MASK (0x80U) -#define USB_ADDR_LSEN_SHIFT (7U) -#define USB_ADDR_LSEN(x) (((uint8_t)(((uint8_t)(x)) << USB_ADDR_LSEN_SHIFT)) & USB_ADDR_LSEN_MASK) - -/*! @name BDTPAGE1 - BDT Page register 1 */ -#define USB_BDTPAGE1_BDTBA_MASK (0xFEU) -#define USB_BDTPAGE1_BDTBA_SHIFT (1U) -#define USB_BDTPAGE1_BDTBA(x) (((uint8_t)(((uint8_t)(x)) << USB_BDTPAGE1_BDTBA_SHIFT)) & USB_BDTPAGE1_BDTBA_MASK) - -/*! @name FRMNUML - Frame Number register Low */ -#define USB_FRMNUML_FRM_MASK (0xFFU) -#define USB_FRMNUML_FRM_SHIFT (0U) -#define USB_FRMNUML_FRM(x) (((uint8_t)(((uint8_t)(x)) << USB_FRMNUML_FRM_SHIFT)) & USB_FRMNUML_FRM_MASK) - -/*! @name FRMNUMH - Frame Number register High */ -#define USB_FRMNUMH_FRM_MASK (0x7U) -#define USB_FRMNUMH_FRM_SHIFT (0U) -#define USB_FRMNUMH_FRM(x) (((uint8_t)(((uint8_t)(x)) << USB_FRMNUMH_FRM_SHIFT)) & USB_FRMNUMH_FRM_MASK) - -/*! @name TOKEN - Token register */ -#define USB_TOKEN_TOKENENDPT_MASK (0xFU) -#define USB_TOKEN_TOKENENDPT_SHIFT (0U) -#define USB_TOKEN_TOKENENDPT(x) (((uint8_t)(((uint8_t)(x)) << USB_TOKEN_TOKENENDPT_SHIFT)) & USB_TOKEN_TOKENENDPT_MASK) -#define USB_TOKEN_TOKENPID_MASK (0xF0U) -#define USB_TOKEN_TOKENPID_SHIFT (4U) -#define USB_TOKEN_TOKENPID(x) (((uint8_t)(((uint8_t)(x)) << USB_TOKEN_TOKENPID_SHIFT)) & USB_TOKEN_TOKENPID_MASK) - -/*! @name SOFTHLD - SOF Threshold register */ -#define USB_SOFTHLD_CNT_MASK (0xFFU) -#define USB_SOFTHLD_CNT_SHIFT (0U) -#define USB_SOFTHLD_CNT(x) (((uint8_t)(((uint8_t)(x)) << USB_SOFTHLD_CNT_SHIFT)) & USB_SOFTHLD_CNT_MASK) - -/*! @name BDTPAGE2 - BDT Page Register 2 */ -#define USB_BDTPAGE2_BDTBA_MASK (0xFFU) -#define USB_BDTPAGE2_BDTBA_SHIFT (0U) -#define USB_BDTPAGE2_BDTBA(x) (((uint8_t)(((uint8_t)(x)) << USB_BDTPAGE2_BDTBA_SHIFT)) & USB_BDTPAGE2_BDTBA_MASK) - -/*! @name BDTPAGE3 - BDT Page Register 3 */ -#define USB_BDTPAGE3_BDTBA_MASK (0xFFU) -#define USB_BDTPAGE3_BDTBA_SHIFT (0U) -#define USB_BDTPAGE3_BDTBA(x) (((uint8_t)(((uint8_t)(x)) << USB_BDTPAGE3_BDTBA_SHIFT)) & USB_BDTPAGE3_BDTBA_MASK) - -/*! @name ENDPT - Endpoint Control register */ -#define USB_ENDPT_EPHSHK_MASK (0x1U) -#define USB_ENDPT_EPHSHK_SHIFT (0U) -#define USB_ENDPT_EPHSHK(x) (((uint8_t)(((uint8_t)(x)) << USB_ENDPT_EPHSHK_SHIFT)) & USB_ENDPT_EPHSHK_MASK) -#define USB_ENDPT_EPSTALL_MASK (0x2U) -#define USB_ENDPT_EPSTALL_SHIFT (1U) -#define USB_ENDPT_EPSTALL(x) (((uint8_t)(((uint8_t)(x)) << USB_ENDPT_EPSTALL_SHIFT)) & USB_ENDPT_EPSTALL_MASK) -#define USB_ENDPT_EPTXEN_MASK (0x4U) -#define USB_ENDPT_EPTXEN_SHIFT (2U) -#define USB_ENDPT_EPTXEN(x) (((uint8_t)(((uint8_t)(x)) << USB_ENDPT_EPTXEN_SHIFT)) & USB_ENDPT_EPTXEN_MASK) -#define USB_ENDPT_EPRXEN_MASK (0x8U) -#define USB_ENDPT_EPRXEN_SHIFT (3U) -#define USB_ENDPT_EPRXEN(x) (((uint8_t)(((uint8_t)(x)) << USB_ENDPT_EPRXEN_SHIFT)) & USB_ENDPT_EPRXEN_MASK) -#define USB_ENDPT_EPCTLDIS_MASK (0x10U) -#define USB_ENDPT_EPCTLDIS_SHIFT (4U) -#define USB_ENDPT_EPCTLDIS(x) (((uint8_t)(((uint8_t)(x)) << USB_ENDPT_EPCTLDIS_SHIFT)) & USB_ENDPT_EPCTLDIS_MASK) -#define USB_ENDPT_RETRYDIS_MASK (0x40U) -#define USB_ENDPT_RETRYDIS_SHIFT (6U) -#define USB_ENDPT_RETRYDIS(x) (((uint8_t)(((uint8_t)(x)) << USB_ENDPT_RETRYDIS_SHIFT)) & USB_ENDPT_RETRYDIS_MASK) -#define USB_ENDPT_HOSTWOHUB_MASK (0x80U) -#define USB_ENDPT_HOSTWOHUB_SHIFT (7U) -#define USB_ENDPT_HOSTWOHUB(x) (((uint8_t)(((uint8_t)(x)) << USB_ENDPT_HOSTWOHUB_SHIFT)) & USB_ENDPT_HOSTWOHUB_MASK) - -/* The count of USB_ENDPT */ -#define USB_ENDPT_COUNT (16U) - -/*! @name USBCTRL - USB Control register */ -#define USB_USBCTRL_PDE_MASK (0x40U) -#define USB_USBCTRL_PDE_SHIFT (6U) -#define USB_USBCTRL_PDE(x) (((uint8_t)(((uint8_t)(x)) << USB_USBCTRL_PDE_SHIFT)) & USB_USBCTRL_PDE_MASK) -#define USB_USBCTRL_SUSP_MASK (0x80U) -#define USB_USBCTRL_SUSP_SHIFT (7U) -#define USB_USBCTRL_SUSP(x) (((uint8_t)(((uint8_t)(x)) << USB_USBCTRL_SUSP_SHIFT)) & USB_USBCTRL_SUSP_MASK) - -/*! @name OBSERVE - USB OTG Observe register */ -#define USB_OBSERVE_DMPD_MASK (0x10U) -#define USB_OBSERVE_DMPD_SHIFT (4U) -#define USB_OBSERVE_DMPD(x) (((uint8_t)(((uint8_t)(x)) << USB_OBSERVE_DMPD_SHIFT)) & USB_OBSERVE_DMPD_MASK) -#define USB_OBSERVE_DPPD_MASK (0x40U) -#define USB_OBSERVE_DPPD_SHIFT (6U) -#define USB_OBSERVE_DPPD(x) (((uint8_t)(((uint8_t)(x)) << USB_OBSERVE_DPPD_SHIFT)) & USB_OBSERVE_DPPD_MASK) -#define USB_OBSERVE_DPPU_MASK (0x80U) -#define USB_OBSERVE_DPPU_SHIFT (7U) -#define USB_OBSERVE_DPPU(x) (((uint8_t)(((uint8_t)(x)) << USB_OBSERVE_DPPU_SHIFT)) & USB_OBSERVE_DPPU_MASK) - -/*! @name CONTROL - USB OTG Control register */ -#define USB_CONTROL_DPPULLUPNONOTG_MASK (0x10U) -#define USB_CONTROL_DPPULLUPNONOTG_SHIFT (4U) -#define USB_CONTROL_DPPULLUPNONOTG(x) (((uint8_t)(((uint8_t)(x)) << USB_CONTROL_DPPULLUPNONOTG_SHIFT)) & USB_CONTROL_DPPULLUPNONOTG_MASK) - -/*! @name USBTRC0 - USB Transceiver Control register 0 */ -#define USB_USBTRC0_USB_RESUME_INT_MASK (0x1U) -#define USB_USBTRC0_USB_RESUME_INT_SHIFT (0U) -#define USB_USBTRC0_USB_RESUME_INT(x) (((uint8_t)(((uint8_t)(x)) << USB_USBTRC0_USB_RESUME_INT_SHIFT)) & USB_USBTRC0_USB_RESUME_INT_MASK) -#define USB_USBTRC0_SYNC_DET_MASK (0x2U) -#define USB_USBTRC0_SYNC_DET_SHIFT (1U) -#define USB_USBTRC0_SYNC_DET(x) (((uint8_t)(((uint8_t)(x)) << USB_USBTRC0_SYNC_DET_SHIFT)) & USB_USBTRC0_SYNC_DET_MASK) -#define USB_USBTRC0_USB_CLK_RECOVERY_INT_MASK (0x4U) -#define USB_USBTRC0_USB_CLK_RECOVERY_INT_SHIFT (2U) -#define USB_USBTRC0_USB_CLK_RECOVERY_INT(x) (((uint8_t)(((uint8_t)(x)) << USB_USBTRC0_USB_CLK_RECOVERY_INT_SHIFT)) & USB_USBTRC0_USB_CLK_RECOVERY_INT_MASK) -#define USB_USBTRC0_USBRESMEN_MASK (0x20U) -#define USB_USBTRC0_USBRESMEN_SHIFT (5U) -#define USB_USBTRC0_USBRESMEN(x) (((uint8_t)(((uint8_t)(x)) << USB_USBTRC0_USBRESMEN_SHIFT)) & USB_USBTRC0_USBRESMEN_MASK) -#define USB_USBTRC0_USBRESET_MASK (0x80U) -#define USB_USBTRC0_USBRESET_SHIFT (7U) -#define USB_USBTRC0_USBRESET(x) (((uint8_t)(((uint8_t)(x)) << USB_USBTRC0_USBRESET_SHIFT)) & USB_USBTRC0_USBRESET_MASK) - -/*! @name USBFRMADJUST - Frame Adjust Register */ -#define USB_USBFRMADJUST_ADJ_MASK (0xFFU) -#define USB_USBFRMADJUST_ADJ_SHIFT (0U) -#define USB_USBFRMADJUST_ADJ(x) (((uint8_t)(((uint8_t)(x)) << USB_USBFRMADJUST_ADJ_SHIFT)) & USB_USBFRMADJUST_ADJ_MASK) - -/*! @name CLK_RECOVER_CTRL - USB Clock recovery control */ -#define USB_CLK_RECOVER_CTRL_RESTART_IFRTRIM_EN_MASK (0x20U) -#define USB_CLK_RECOVER_CTRL_RESTART_IFRTRIM_EN_SHIFT (5U) -#define USB_CLK_RECOVER_CTRL_RESTART_IFRTRIM_EN(x) (((uint8_t)(((uint8_t)(x)) << USB_CLK_RECOVER_CTRL_RESTART_IFRTRIM_EN_SHIFT)) & USB_CLK_RECOVER_CTRL_RESTART_IFRTRIM_EN_MASK) -#define USB_CLK_RECOVER_CTRL_RESET_RESUME_ROUGH_EN_MASK (0x40U) -#define USB_CLK_RECOVER_CTRL_RESET_RESUME_ROUGH_EN_SHIFT (6U) -#define USB_CLK_RECOVER_CTRL_RESET_RESUME_ROUGH_EN(x) (((uint8_t)(((uint8_t)(x)) << USB_CLK_RECOVER_CTRL_RESET_RESUME_ROUGH_EN_SHIFT)) & USB_CLK_RECOVER_CTRL_RESET_RESUME_ROUGH_EN_MASK) -#define USB_CLK_RECOVER_CTRL_CLOCK_RECOVER_EN_MASK (0x80U) -#define USB_CLK_RECOVER_CTRL_CLOCK_RECOVER_EN_SHIFT (7U) -#define USB_CLK_RECOVER_CTRL_CLOCK_RECOVER_EN(x) (((uint8_t)(((uint8_t)(x)) << USB_CLK_RECOVER_CTRL_CLOCK_RECOVER_EN_SHIFT)) & USB_CLK_RECOVER_CTRL_CLOCK_RECOVER_EN_MASK) - -/*! @name CLK_RECOVER_IRC_EN - IRC48M oscillator enable register */ -#define USB_CLK_RECOVER_IRC_EN_REG_EN_MASK (0x1U) -#define USB_CLK_RECOVER_IRC_EN_REG_EN_SHIFT (0U) -#define USB_CLK_RECOVER_IRC_EN_REG_EN(x) (((uint8_t)(((uint8_t)(x)) << USB_CLK_RECOVER_IRC_EN_REG_EN_SHIFT)) & USB_CLK_RECOVER_IRC_EN_REG_EN_MASK) -#define USB_CLK_RECOVER_IRC_EN_IRC_EN_MASK (0x2U) -#define USB_CLK_RECOVER_IRC_EN_IRC_EN_SHIFT (1U) -#define USB_CLK_RECOVER_IRC_EN_IRC_EN(x) (((uint8_t)(((uint8_t)(x)) << USB_CLK_RECOVER_IRC_EN_IRC_EN_SHIFT)) & USB_CLK_RECOVER_IRC_EN_IRC_EN_MASK) - -/*! @name CLK_RECOVER_INT_STATUS - Clock recovery separated interrupt status */ -#define USB_CLK_RECOVER_INT_STATUS_OVF_ERROR_MASK (0x10U) -#define USB_CLK_RECOVER_INT_STATUS_OVF_ERROR_SHIFT (4U) -#define USB_CLK_RECOVER_INT_STATUS_OVF_ERROR(x) (((uint8_t)(((uint8_t)(x)) << USB_CLK_RECOVER_INT_STATUS_OVF_ERROR_SHIFT)) & USB_CLK_RECOVER_INT_STATUS_OVF_ERROR_MASK) - - -/*! - * @} - */ /* end of group USB_Register_Masks */ - - -/* USB - Peripheral instance base addresses */ -/** Peripheral USB0 base address */ -#define USB0_BASE (0x40072000u) -/** Peripheral USB0 base pointer */ -#define USB0 ((USB_Type *)USB0_BASE) -/** Array initializer of USB peripheral base addresses */ -#define USB_BASE_ADDRS { USB0_BASE } -/** Array initializer of USB peripheral base pointers */ -#define USB_BASE_PTRS { USB0 } -/** Interrupt vectors for the USB peripheral type */ -#define USB_IRQS { USB0_IRQn } - -/*! - * @} - */ /* end of group USB_Peripheral_Access_Layer */ - - -/* ---------------------------------------------------------------------------- - -- USBDCD Peripheral Access Layer - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup USBDCD_Peripheral_Access_Layer USBDCD Peripheral Access Layer - * @{ - */ - -/** USBDCD - Register Layout Typedef */ -typedef struct { - __IO uint32_t CONTROL; /**< Control register, offset: 0x0 */ - __IO uint32_t CLOCK; /**< Clock register, offset: 0x4 */ - __I uint32_t STATUS; /**< Status register, offset: 0x8 */ - uint8_t RESERVED_0[4]; - __IO uint32_t TIMER0; /**< TIMER0 register, offset: 0x10 */ - __IO uint32_t TIMER1; /**< TIMER1 register, offset: 0x14 */ - union { /* offset: 0x18 */ - __IO uint32_t TIMER2_BC11; /**< TIMER2_BC11 register, offset: 0x18 */ - __IO uint32_t TIMER2_BC12; /**< TIMER2_BC12 register, offset: 0x18 */ - }; -} USBDCD_Type; - -/* ---------------------------------------------------------------------------- - -- USBDCD Register Masks - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup USBDCD_Register_Masks USBDCD Register Masks - * @{ - */ - -/*! @name CONTROL - Control register */ -#define USBDCD_CONTROL_IACK_MASK (0x1U) -#define USBDCD_CONTROL_IACK_SHIFT (0U) -#define USBDCD_CONTROL_IACK(x) (((uint32_t)(((uint32_t)(x)) << USBDCD_CONTROL_IACK_SHIFT)) & USBDCD_CONTROL_IACK_MASK) -#define USBDCD_CONTROL_IF_MASK (0x100U) -#define USBDCD_CONTROL_IF_SHIFT (8U) -#define USBDCD_CONTROL_IF(x) (((uint32_t)(((uint32_t)(x)) << USBDCD_CONTROL_IF_SHIFT)) & USBDCD_CONTROL_IF_MASK) -#define USBDCD_CONTROL_IE_MASK (0x10000U) -#define USBDCD_CONTROL_IE_SHIFT (16U) -#define USBDCD_CONTROL_IE(x) (((uint32_t)(((uint32_t)(x)) << USBDCD_CONTROL_IE_SHIFT)) & USBDCD_CONTROL_IE_MASK) -#define USBDCD_CONTROL_BC12_MASK (0x20000U) -#define USBDCD_CONTROL_BC12_SHIFT (17U) -#define USBDCD_CONTROL_BC12(x) (((uint32_t)(((uint32_t)(x)) << USBDCD_CONTROL_BC12_SHIFT)) & USBDCD_CONTROL_BC12_MASK) -#define USBDCD_CONTROL_START_MASK (0x1000000U) -#define USBDCD_CONTROL_START_SHIFT (24U) -#define USBDCD_CONTROL_START(x) (((uint32_t)(((uint32_t)(x)) << USBDCD_CONTROL_START_SHIFT)) & USBDCD_CONTROL_START_MASK) -#define USBDCD_CONTROL_SR_MASK (0x2000000U) -#define USBDCD_CONTROL_SR_SHIFT (25U) -#define USBDCD_CONTROL_SR(x) (((uint32_t)(((uint32_t)(x)) << USBDCD_CONTROL_SR_SHIFT)) & USBDCD_CONTROL_SR_MASK) - -/*! @name CLOCK - Clock register */ -#define USBDCD_CLOCK_CLOCK_UNIT_MASK (0x1U) -#define USBDCD_CLOCK_CLOCK_UNIT_SHIFT (0U) -#define USBDCD_CLOCK_CLOCK_UNIT(x) (((uint32_t)(((uint32_t)(x)) << USBDCD_CLOCK_CLOCK_UNIT_SHIFT)) & USBDCD_CLOCK_CLOCK_UNIT_MASK) -#define USBDCD_CLOCK_CLOCK_SPEED_MASK (0xFFCU) -#define USBDCD_CLOCK_CLOCK_SPEED_SHIFT (2U) -#define USBDCD_CLOCK_CLOCK_SPEED(x) (((uint32_t)(((uint32_t)(x)) << USBDCD_CLOCK_CLOCK_SPEED_SHIFT)) & USBDCD_CLOCK_CLOCK_SPEED_MASK) - -/*! @name STATUS - Status register */ -#define USBDCD_STATUS_SEQ_RES_MASK (0x30000U) -#define USBDCD_STATUS_SEQ_RES_SHIFT (16U) -#define USBDCD_STATUS_SEQ_RES(x) (((uint32_t)(((uint32_t)(x)) << USBDCD_STATUS_SEQ_RES_SHIFT)) & USBDCD_STATUS_SEQ_RES_MASK) -#define USBDCD_STATUS_SEQ_STAT_MASK (0xC0000U) -#define USBDCD_STATUS_SEQ_STAT_SHIFT (18U) -#define USBDCD_STATUS_SEQ_STAT(x) (((uint32_t)(((uint32_t)(x)) << USBDCD_STATUS_SEQ_STAT_SHIFT)) & USBDCD_STATUS_SEQ_STAT_MASK) -#define USBDCD_STATUS_ERR_MASK (0x100000U) -#define USBDCD_STATUS_ERR_SHIFT (20U) -#define USBDCD_STATUS_ERR(x) (((uint32_t)(((uint32_t)(x)) << USBDCD_STATUS_ERR_SHIFT)) & USBDCD_STATUS_ERR_MASK) -#define USBDCD_STATUS_TO_MASK (0x200000U) -#define USBDCD_STATUS_TO_SHIFT (21U) -#define USBDCD_STATUS_TO(x) (((uint32_t)(((uint32_t)(x)) << USBDCD_STATUS_TO_SHIFT)) & USBDCD_STATUS_TO_MASK) -#define USBDCD_STATUS_ACTIVE_MASK (0x400000U) -#define USBDCD_STATUS_ACTIVE_SHIFT (22U) -#define USBDCD_STATUS_ACTIVE(x) (((uint32_t)(((uint32_t)(x)) << USBDCD_STATUS_ACTIVE_SHIFT)) & USBDCD_STATUS_ACTIVE_MASK) - -/*! @name TIMER0 - TIMER0 register */ -#define USBDCD_TIMER0_TUNITCON_MASK (0xFFFU) -#define USBDCD_TIMER0_TUNITCON_SHIFT (0U) -#define USBDCD_TIMER0_TUNITCON(x) (((uint32_t)(((uint32_t)(x)) << USBDCD_TIMER0_TUNITCON_SHIFT)) & USBDCD_TIMER0_TUNITCON_MASK) -#define USBDCD_TIMER0_TSEQ_INIT_MASK (0x3FF0000U) -#define USBDCD_TIMER0_TSEQ_INIT_SHIFT (16U) -#define USBDCD_TIMER0_TSEQ_INIT(x) (((uint32_t)(((uint32_t)(x)) << USBDCD_TIMER0_TSEQ_INIT_SHIFT)) & USBDCD_TIMER0_TSEQ_INIT_MASK) - -/*! @name TIMER1 - TIMER1 register */ -#define USBDCD_TIMER1_TVDPSRC_ON_MASK (0x3FFU) -#define USBDCD_TIMER1_TVDPSRC_ON_SHIFT (0U) -#define USBDCD_TIMER1_TVDPSRC_ON(x) (((uint32_t)(((uint32_t)(x)) << USBDCD_TIMER1_TVDPSRC_ON_SHIFT)) & USBDCD_TIMER1_TVDPSRC_ON_MASK) -#define USBDCD_TIMER1_TDCD_DBNC_MASK (0x3FF0000U) -#define USBDCD_TIMER1_TDCD_DBNC_SHIFT (16U) -#define USBDCD_TIMER1_TDCD_DBNC(x) (((uint32_t)(((uint32_t)(x)) << USBDCD_TIMER1_TDCD_DBNC_SHIFT)) & USBDCD_TIMER1_TDCD_DBNC_MASK) - -/*! @name TIMER2_BC11 - TIMER2_BC11 register */ -#define USBDCD_TIMER2_BC11_CHECK_DM_MASK (0xFU) -#define USBDCD_TIMER2_BC11_CHECK_DM_SHIFT (0U) -#define USBDCD_TIMER2_BC11_CHECK_DM(x) (((uint32_t)(((uint32_t)(x)) << USBDCD_TIMER2_BC11_CHECK_DM_SHIFT)) & USBDCD_TIMER2_BC11_CHECK_DM_MASK) -#define USBDCD_TIMER2_BC11_TVDPSRC_CON_MASK (0x3FF0000U) -#define USBDCD_TIMER2_BC11_TVDPSRC_CON_SHIFT (16U) -#define USBDCD_TIMER2_BC11_TVDPSRC_CON(x) (((uint32_t)(((uint32_t)(x)) << USBDCD_TIMER2_BC11_TVDPSRC_CON_SHIFT)) & USBDCD_TIMER2_BC11_TVDPSRC_CON_MASK) - -/*! @name TIMER2_BC12 - TIMER2_BC12 register */ -#define USBDCD_TIMER2_BC12_TVDMSRC_ON_MASK (0x3FFU) -#define USBDCD_TIMER2_BC12_TVDMSRC_ON_SHIFT (0U) -#define USBDCD_TIMER2_BC12_TVDMSRC_ON(x) (((uint32_t)(((uint32_t)(x)) << USBDCD_TIMER2_BC12_TVDMSRC_ON_SHIFT)) & USBDCD_TIMER2_BC12_TVDMSRC_ON_MASK) -#define USBDCD_TIMER2_BC12_TWAIT_AFTER_PRD_MASK (0x3FF0000U) -#define USBDCD_TIMER2_BC12_TWAIT_AFTER_PRD_SHIFT (16U) -#define USBDCD_TIMER2_BC12_TWAIT_AFTER_PRD(x) (((uint32_t)(((uint32_t)(x)) << USBDCD_TIMER2_BC12_TWAIT_AFTER_PRD_SHIFT)) & USBDCD_TIMER2_BC12_TWAIT_AFTER_PRD_MASK) - - -/*! - * @} - */ /* end of group USBDCD_Register_Masks */ - - -/* USBDCD - Peripheral instance base addresses */ -/** Peripheral USBDCD base address */ -#define USBDCD_BASE (0x40035000u) -/** Peripheral USBDCD base pointer */ -#define USBDCD ((USBDCD_Type *)USBDCD_BASE) -/** Array initializer of USBDCD peripheral base addresses */ -#define USBDCD_BASE_ADDRS { USBDCD_BASE } -/** Array initializer of USBDCD peripheral base pointers */ -#define USBDCD_BASE_PTRS { USBDCD } -/** Interrupt vectors for the USBDCD peripheral type */ -#define USBDCD_IRQS { USBDCD_IRQn } - -/*! - * @} - */ /* end of group USBDCD_Peripheral_Access_Layer */ - - -/* ---------------------------------------------------------------------------- - -- VREF Peripheral Access Layer - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup VREF_Peripheral_Access_Layer VREF Peripheral Access Layer - * @{ - */ - -/** VREF - Register Layout Typedef */ -typedef struct { - __IO uint8_t TRM; /**< VREF Trim Register, offset: 0x0 */ - __IO uint8_t SC; /**< VREF Status and Control Register, offset: 0x1 */ -} VREF_Type; - -/* ---------------------------------------------------------------------------- - -- VREF Register Masks - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup VREF_Register_Masks VREF Register Masks - * @{ - */ - -/*! @name TRM - VREF Trim Register */ -#define VREF_TRM_TRIM_MASK (0x3FU) -#define VREF_TRM_TRIM_SHIFT (0U) -#define VREF_TRM_TRIM(x) (((uint8_t)(((uint8_t)(x)) << VREF_TRM_TRIM_SHIFT)) & VREF_TRM_TRIM_MASK) -#define VREF_TRM_CHOPEN_MASK (0x40U) -#define VREF_TRM_CHOPEN_SHIFT (6U) -#define VREF_TRM_CHOPEN(x) (((uint8_t)(((uint8_t)(x)) << VREF_TRM_CHOPEN_SHIFT)) & VREF_TRM_CHOPEN_MASK) - -/*! @name SC - VREF Status and Control Register */ -#define VREF_SC_MODE_LV_MASK (0x3U) -#define VREF_SC_MODE_LV_SHIFT (0U) -#define VREF_SC_MODE_LV(x) (((uint8_t)(((uint8_t)(x)) << VREF_SC_MODE_LV_SHIFT)) & VREF_SC_MODE_LV_MASK) -#define VREF_SC_VREFST_MASK (0x4U) -#define VREF_SC_VREFST_SHIFT (2U) -#define VREF_SC_VREFST(x) (((uint8_t)(((uint8_t)(x)) << VREF_SC_VREFST_SHIFT)) & VREF_SC_VREFST_MASK) -#define VREF_SC_ICOMPEN_MASK (0x20U) -#define VREF_SC_ICOMPEN_SHIFT (5U) -#define VREF_SC_ICOMPEN(x) (((uint8_t)(((uint8_t)(x)) << VREF_SC_ICOMPEN_SHIFT)) & VREF_SC_ICOMPEN_MASK) -#define VREF_SC_REGEN_MASK (0x40U) -#define VREF_SC_REGEN_SHIFT (6U) -#define VREF_SC_REGEN(x) (((uint8_t)(((uint8_t)(x)) << VREF_SC_REGEN_SHIFT)) & VREF_SC_REGEN_MASK) -#define VREF_SC_VREFEN_MASK (0x80U) -#define VREF_SC_VREFEN_SHIFT (7U) -#define VREF_SC_VREFEN(x) (((uint8_t)(((uint8_t)(x)) << VREF_SC_VREFEN_SHIFT)) & VREF_SC_VREFEN_MASK) - - -/*! - * @} - */ /* end of group VREF_Register_Masks */ - - -/* VREF - Peripheral instance base addresses */ -/** Peripheral VREF base address */ -#define VREF_BASE (0x40074000u) -/** Peripheral VREF base pointer */ -#define VREF ((VREF_Type *)VREF_BASE) -/** Array initializer of VREF peripheral base addresses */ -#define VREF_BASE_ADDRS { VREF_BASE } -/** Array initializer of VREF peripheral base pointers */ -#define VREF_BASE_PTRS { VREF } - -/*! - * @} - */ /* end of group VREF_Peripheral_Access_Layer */ - - -/* ---------------------------------------------------------------------------- - -- WDOG Peripheral Access Layer - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup WDOG_Peripheral_Access_Layer WDOG Peripheral Access Layer - * @{ - */ - -/** WDOG - Register Layout Typedef */ -typedef struct { - __IO uint16_t STCTRLH; /**< Watchdog Status and Control Register High, offset: 0x0 */ - __IO uint16_t STCTRLL; /**< Watchdog Status and Control Register Low, offset: 0x2 */ - __IO uint16_t TOVALH; /**< Watchdog Time-out Value Register High, offset: 0x4 */ - __IO uint16_t TOVALL; /**< Watchdog Time-out Value Register Low, offset: 0x6 */ - __IO uint16_t WINH; /**< Watchdog Window Register High, offset: 0x8 */ - __IO uint16_t WINL; /**< Watchdog Window Register Low, offset: 0xA */ - __IO uint16_t REFRESH; /**< Watchdog Refresh register, offset: 0xC */ - __IO uint16_t UNLOCK; /**< Watchdog Unlock register, offset: 0xE */ - __IO uint16_t TMROUTH; /**< Watchdog Timer Output Register High, offset: 0x10 */ - __IO uint16_t TMROUTL; /**< Watchdog Timer Output Register Low, offset: 0x12 */ - __IO uint16_t RSTCNT; /**< Watchdog Reset Count register, offset: 0x14 */ - __IO uint16_t PRESC; /**< Watchdog Prescaler register, offset: 0x16 */ -} WDOG_Type; - -/* ---------------------------------------------------------------------------- - -- WDOG Register Masks - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup WDOG_Register_Masks WDOG Register Masks - * @{ - */ - -/*! @name STCTRLH - Watchdog Status and Control Register High */ -#define WDOG_STCTRLH_WDOGEN_MASK (0x1U) -#define WDOG_STCTRLH_WDOGEN_SHIFT (0U) -#define WDOG_STCTRLH_WDOGEN(x) (((uint16_t)(((uint16_t)(x)) << WDOG_STCTRLH_WDOGEN_SHIFT)) & WDOG_STCTRLH_WDOGEN_MASK) -#define WDOG_STCTRLH_CLKSRC_MASK (0x2U) -#define WDOG_STCTRLH_CLKSRC_SHIFT (1U) -#define WDOG_STCTRLH_CLKSRC(x) (((uint16_t)(((uint16_t)(x)) << WDOG_STCTRLH_CLKSRC_SHIFT)) & WDOG_STCTRLH_CLKSRC_MASK) -#define WDOG_STCTRLH_IRQRSTEN_MASK (0x4U) -#define WDOG_STCTRLH_IRQRSTEN_SHIFT (2U) -#define WDOG_STCTRLH_IRQRSTEN(x) (((uint16_t)(((uint16_t)(x)) << WDOG_STCTRLH_IRQRSTEN_SHIFT)) & WDOG_STCTRLH_IRQRSTEN_MASK) -#define WDOG_STCTRLH_WINEN_MASK (0x8U) -#define WDOG_STCTRLH_WINEN_SHIFT (3U) -#define WDOG_STCTRLH_WINEN(x) (((uint16_t)(((uint16_t)(x)) << WDOG_STCTRLH_WINEN_SHIFT)) & WDOG_STCTRLH_WINEN_MASK) -#define WDOG_STCTRLH_ALLOWUPDATE_MASK (0x10U) -#define WDOG_STCTRLH_ALLOWUPDATE_SHIFT (4U) -#define WDOG_STCTRLH_ALLOWUPDATE(x) (((uint16_t)(((uint16_t)(x)) << WDOG_STCTRLH_ALLOWUPDATE_SHIFT)) & WDOG_STCTRLH_ALLOWUPDATE_MASK) -#define WDOG_STCTRLH_DBGEN_MASK (0x20U) -#define WDOG_STCTRLH_DBGEN_SHIFT (5U) -#define WDOG_STCTRLH_DBGEN(x) (((uint16_t)(((uint16_t)(x)) << WDOG_STCTRLH_DBGEN_SHIFT)) & WDOG_STCTRLH_DBGEN_MASK) -#define WDOG_STCTRLH_STOPEN_MASK (0x40U) -#define WDOG_STCTRLH_STOPEN_SHIFT (6U) -#define WDOG_STCTRLH_STOPEN(x) (((uint16_t)(((uint16_t)(x)) << WDOG_STCTRLH_STOPEN_SHIFT)) & WDOG_STCTRLH_STOPEN_MASK) -#define WDOG_STCTRLH_WAITEN_MASK (0x80U) -#define WDOG_STCTRLH_WAITEN_SHIFT (7U) -#define WDOG_STCTRLH_WAITEN(x) (((uint16_t)(((uint16_t)(x)) << WDOG_STCTRLH_WAITEN_SHIFT)) & WDOG_STCTRLH_WAITEN_MASK) -#define WDOG_STCTRLH_TESTWDOG_MASK (0x400U) -#define WDOG_STCTRLH_TESTWDOG_SHIFT (10U) -#define WDOG_STCTRLH_TESTWDOG(x) (((uint16_t)(((uint16_t)(x)) << WDOG_STCTRLH_TESTWDOG_SHIFT)) & WDOG_STCTRLH_TESTWDOG_MASK) -#define WDOG_STCTRLH_TESTSEL_MASK (0x800U) -#define WDOG_STCTRLH_TESTSEL_SHIFT (11U) -#define WDOG_STCTRLH_TESTSEL(x) (((uint16_t)(((uint16_t)(x)) << WDOG_STCTRLH_TESTSEL_SHIFT)) & WDOG_STCTRLH_TESTSEL_MASK) -#define WDOG_STCTRLH_BYTESEL_MASK (0x3000U) -#define WDOG_STCTRLH_BYTESEL_SHIFT (12U) -#define WDOG_STCTRLH_BYTESEL(x) (((uint16_t)(((uint16_t)(x)) << WDOG_STCTRLH_BYTESEL_SHIFT)) & WDOG_STCTRLH_BYTESEL_MASK) -#define WDOG_STCTRLH_DISTESTWDOG_MASK (0x4000U) -#define WDOG_STCTRLH_DISTESTWDOG_SHIFT (14U) -#define WDOG_STCTRLH_DISTESTWDOG(x) (((uint16_t)(((uint16_t)(x)) << WDOG_STCTRLH_DISTESTWDOG_SHIFT)) & WDOG_STCTRLH_DISTESTWDOG_MASK) - -/*! @name STCTRLL - Watchdog Status and Control Register Low */ -#define WDOG_STCTRLL_INTFLG_MASK (0x8000U) -#define WDOG_STCTRLL_INTFLG_SHIFT (15U) -#define WDOG_STCTRLL_INTFLG(x) (((uint16_t)(((uint16_t)(x)) << WDOG_STCTRLL_INTFLG_SHIFT)) & WDOG_STCTRLL_INTFLG_MASK) - -/*! @name TOVALH - Watchdog Time-out Value Register High */ -#define WDOG_TOVALH_TOVALHIGH_MASK (0xFFFFU) -#define WDOG_TOVALH_TOVALHIGH_SHIFT (0U) -#define WDOG_TOVALH_TOVALHIGH(x) (((uint16_t)(((uint16_t)(x)) << WDOG_TOVALH_TOVALHIGH_SHIFT)) & WDOG_TOVALH_TOVALHIGH_MASK) - -/*! @name TOVALL - Watchdog Time-out Value Register Low */ -#define WDOG_TOVALL_TOVALLOW_MASK (0xFFFFU) -#define WDOG_TOVALL_TOVALLOW_SHIFT (0U) -#define WDOG_TOVALL_TOVALLOW(x) (((uint16_t)(((uint16_t)(x)) << WDOG_TOVALL_TOVALLOW_SHIFT)) & WDOG_TOVALL_TOVALLOW_MASK) - -/*! @name WINH - Watchdog Window Register High */ -#define WDOG_WINH_WINHIGH_MASK (0xFFFFU) -#define WDOG_WINH_WINHIGH_SHIFT (0U) -#define WDOG_WINH_WINHIGH(x) (((uint16_t)(((uint16_t)(x)) << WDOG_WINH_WINHIGH_SHIFT)) & WDOG_WINH_WINHIGH_MASK) - -/*! @name WINL - Watchdog Window Register Low */ -#define WDOG_WINL_WINLOW_MASK (0xFFFFU) -#define WDOG_WINL_WINLOW_SHIFT (0U) -#define WDOG_WINL_WINLOW(x) (((uint16_t)(((uint16_t)(x)) << WDOG_WINL_WINLOW_SHIFT)) & WDOG_WINL_WINLOW_MASK) - -/*! @name REFRESH - Watchdog Refresh register */ -#define WDOG_REFRESH_WDOGREFRESH_MASK (0xFFFFU) -#define WDOG_REFRESH_WDOGREFRESH_SHIFT (0U) -#define WDOG_REFRESH_WDOGREFRESH(x) (((uint16_t)(((uint16_t)(x)) << WDOG_REFRESH_WDOGREFRESH_SHIFT)) & WDOG_REFRESH_WDOGREFRESH_MASK) - -/*! @name UNLOCK - Watchdog Unlock register */ -#define WDOG_UNLOCK_WDOGUNLOCK_MASK (0xFFFFU) -#define WDOG_UNLOCK_WDOGUNLOCK_SHIFT (0U) -#define WDOG_UNLOCK_WDOGUNLOCK(x) (((uint16_t)(((uint16_t)(x)) << WDOG_UNLOCK_WDOGUNLOCK_SHIFT)) & WDOG_UNLOCK_WDOGUNLOCK_MASK) - -/*! @name TMROUTH - Watchdog Timer Output Register High */ -#define WDOG_TMROUTH_TIMEROUTHIGH_MASK (0xFFFFU) -#define WDOG_TMROUTH_TIMEROUTHIGH_SHIFT (0U) -#define WDOG_TMROUTH_TIMEROUTHIGH(x) (((uint16_t)(((uint16_t)(x)) << WDOG_TMROUTH_TIMEROUTHIGH_SHIFT)) & WDOG_TMROUTH_TIMEROUTHIGH_MASK) - -/*! @name TMROUTL - Watchdog Timer Output Register Low */ -#define WDOG_TMROUTL_TIMEROUTLOW_MASK (0xFFFFU) -#define WDOG_TMROUTL_TIMEROUTLOW_SHIFT (0U) -#define WDOG_TMROUTL_TIMEROUTLOW(x) (((uint16_t)(((uint16_t)(x)) << WDOG_TMROUTL_TIMEROUTLOW_SHIFT)) & WDOG_TMROUTL_TIMEROUTLOW_MASK) - -/*! @name RSTCNT - Watchdog Reset Count register */ -#define WDOG_RSTCNT_RSTCNT_MASK (0xFFFFU) -#define WDOG_RSTCNT_RSTCNT_SHIFT (0U) -#define WDOG_RSTCNT_RSTCNT(x) (((uint16_t)(((uint16_t)(x)) << WDOG_RSTCNT_RSTCNT_SHIFT)) & WDOG_RSTCNT_RSTCNT_MASK) - -/*! @name PRESC - Watchdog Prescaler register */ -#define WDOG_PRESC_PRESCVAL_MASK (0x700U) -#define WDOG_PRESC_PRESCVAL_SHIFT (8U) -#define WDOG_PRESC_PRESCVAL(x) (((uint16_t)(((uint16_t)(x)) << WDOG_PRESC_PRESCVAL_SHIFT)) & WDOG_PRESC_PRESCVAL_MASK) - - -/*! - * @} - */ /* end of group WDOG_Register_Masks */ - - -/* WDOG - Peripheral instance base addresses */ -/** Peripheral WDOG base address */ -#define WDOG_BASE (0x40052000u) -/** Peripheral WDOG base pointer */ -#define WDOG ((WDOG_Type *)WDOG_BASE) -/** Array initializer of WDOG peripheral base addresses */ -#define WDOG_BASE_ADDRS { WDOG_BASE } -/** Array initializer of WDOG peripheral base pointers */ -#define WDOG_BASE_PTRS { WDOG } -/** Interrupt vectors for the WDOG peripheral type */ -#define WDOG_IRQS { WDOG_EWM_IRQn } - -/*! - * @} - */ /* end of group WDOG_Peripheral_Access_Layer */ - - -/* -** End of section using anonymous unions -*/ - -#if defined(__ARMCC_VERSION) - #pragma pop -#elif defined(__CWCC__) - #pragma pop -#elif defined(__GNUC__) - /* leave anonymous unions enabled */ -#elif defined(__IAR_SYSTEMS_ICC__) - #pragma language=default -#else - #error Not supported compiler type -#endif - -/*! - * @} - */ /* end of group Peripheral_access_layer */ - - -/* ---------------------------------------------------------------------------- - -- Macros for use with bit field definitions (xxx_SHIFT, xxx_MASK). - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup Bit_Field_Generic_Macros Macros for use with bit field definitions (xxx_SHIFT, xxx_MASK). - * @{ - */ - -#if defined(__ARMCC_VERSION) - #if (__ARMCC_VERSION >= 6010050) - #pragma clang system_header - #endif -#elif defined(__IAR_SYSTEMS_ICC__) - #pragma system_include -#endif - -/** - * @brief Mask and left-shift a bit field value for use in a register bit range. - * @param field Name of the register bit field. - * @param value Value of the bit field. - * @return Masked and shifted value. - */ -#define NXP_VAL2FLD(field, value) (((value) << (field ## _SHIFT)) & (field ## _MASK)) -/** - * @brief Mask and right-shift a register value to extract a bit field value. - * @param field Name of the register bit field. - * @param value Value of the register. - * @return Masked and shifted bit field value. - */ -#define NXP_FLD2VAL(field, value) (((value) & (field ## _MASK)) >> (field ## _SHIFT)) - -/*! - * @} - */ /* end of group Bit_Field_Generic_Macros */ - - -/* ---------------------------------------------------------------------------- - -- SDK Compatibility - ---------------------------------------------------------------------------- */ - -/*! - * @addtogroup SDK_Compatibility_Symbols SDK Compatibility - * @{ - */ - -#define MCG_C2_EREFS0_MASK MCG_C2_EREFS_MASK -#define MCG_C2_EREFS0_SHIFT MCG_C2_EREFS_SHIFT -#define MCG_C2_HGO0_MASK MCG_C2_HGO_MASK -#define MCG_C2_HGO0_SHIFT MCG_C2_HGO_SHIFT -#define MCG_C2_RANGE0_MASK MCG_C2_RANGE_MASK -#define MCG_C2_RANGE0_SHIFT MCG_C2_RANGE_SHIFT -#define MCG_C2_RANGE0(x) MCG_C2_RANGE(x) -#define MCM_ISR_REG(base) MCM_ISCR_REG(base) -#define MCM_ISR_FIOC_MASK MCM_ISCR_FIOC_MASK -#define MCM_ISR_FIOC_SHIFT MCM_ISCR_FIOC_SHIFT -#define MCM_ISR_FDZC_MASK MCM_ISCR_FDZC_MASK -#define MCM_ISR_FDZC_SHIFT MCM_ISCR_FDZC_SHIFT -#define MCM_ISR_FOFC_MASK MCM_ISCR_FOFC_MASK -#define MCM_ISR_FOFC_SHIFT MCM_ISCR_FOFC_SHIFT -#define MCM_ISR_FUFC_MASK MCM_ISCR_FUFC_MASK -#define MCM_ISR_FUFC_SHIFT MCM_ISCR_FUFC_SHIFT -#define MCM_ISR_FIXC_MASK MCM_ISCR_FIXC_MASK -#define MCM_ISR_FIXC_SHIFT MCM_ISCR_FIXC_SHIFT -#define MCM_ISR_FIDC_MASK MCM_ISCR_FIDC_MASK -#define MCM_ISR_FIDC_SHIFT MCM_ISCR_FIDC_SHIFT -#define MCM_ISR_FIOCE_MASK MCM_ISCR_FIOCE_MASK -#define MCM_ISR_FIOCE_SHIFT MCM_ISCR_FIOCE_SHIFT -#define MCM_ISR_FDZCE_MASK MCM_ISCR_FDZCE_MASK -#define MCM_ISR_FDZCE_SHIFT MCM_ISCR_FDZCE_SHIFT -#define MCM_ISR_FOFCE_MASK MCM_ISCR_FOFCE_MASK -#define MCM_ISR_FOFCE_SHIFT MCM_ISCR_FOFCE_SHIFT -#define MCM_ISR_FUFCE_MASK MCM_ISCR_FUFCE_MASK -#define MCM_ISR_FUFCE_SHIFT MCM_ISCR_FUFCE_SHIFT -#define MCM_ISR_FIXCE_MASK MCM_ISCR_FIXCE_MASK -#define MCM_ISR_FIXCE_SHIFT MCM_ISCR_FIXCE_SHIFT -#define MCM_ISR_FIDCE_MASK MCM_ISCR_FIDCE_MASK -#define MCM_ISR_FIDCE_SHIFT MCM_ISCR_FIDCE_SHIFT -#define DSPI0 SPI0 -#define DSPI1 SPI1 -#define DSPI2 SPI2 -#define FLEXCAN0 CAN0 -#define PTA_BASE GPIOA_BASE -#define PTA GPIOA -#define PTB_BASE GPIOB_BASE -#define PTB GPIOB -#define PTC_BASE GPIOC_BASE -#define PTC GPIOC -#define PTD_BASE GPIOD_BASE -#define PTD GPIOD -#define PTE_BASE GPIOE_BASE -#define PTE GPIOE -#define UART_WP7816_T_TYPE0_REG(base) UART_WP7816T0_REG(base) -#define UART_WP7816_T_TYPE1_REG(base) UART_WP7816T1_REG(base) -#define UART_WP7816_T_TYPE0_WI_MASK UART_WP7816T0_WI_MASK -#define UART_WP7816_T_TYPE0_WI_SHIFT UART_WP7816T0_WI_SHIFT -#define UART_WP7816_T_TYPE0_WI(x) UART_WP7816T0_WI(x) -#define UART_WP7816_T_TYPE1_BWI_MASK UART_WP7816T1_BWI_MASK -#define UART_WP7816_T_TYPE1_BWI_SHIFT UART_WP7816T1_BWI_SHIFT -#define UART_WP7816_T_TYPE1_BWI(x) UART_WP7816T1_BWI(x) -#define UART_WP7816_T_TYPE1_CWI_MASK UART_WP7816T1_CWI_MASK -#define UART_WP7816_T_TYPE1_CWI_SHIFT UART_WP7816T1_CWI_SHIFT -#define UART_WP7816_T_TYPE1_CWI(x) UART_WP7816T1_CWI(x) -#define Watchdog_IRQn WDOG_EWM_IRQn -#define Watchdog_IRQHandler WDOG_EWM_IRQHandler -#define LPTimer_IRQn LPTMR0_IRQn -#define LPTimer_IRQHandler LPTMR0_IRQHandler -#define LLW_IRQn LLWU_IRQn -#define LLW_IRQHandler LLWU_IRQHandler -#define DMAMUX0 DMAMUX -#define WDOG0 WDOG -#define MCM0 MCM -#define RTC0 RTC - -/*! - * @} - */ /* end of group SDK_Compatibility_Symbols */ - - -#endif /* _MK24F12_H_ */ - diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/device/MK24F12_features.h b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/device/MK24F12_features.h deleted file mode 100644 index 723d7e27a05..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/device/MK24F12_features.h +++ /dev/null @@ -1,1981 +0,0 @@ -/* -** ################################################################### -** Version: rev. 2.14, 2016-03-21 -** Build: b170228 -** -** Abstract: -** Chip specific module features. -** -** Copyright 2016 Freescale Semiconductor, Inc. -** Copyright 2016-2017 NXP -** Redistribution and use in source and binary forms, with or without modification, -** are permitted provided that the following conditions are met: -** -** o Redistributions of source code must retain the above copyright notice, this list -** of conditions and the following disclaimer. -** -** o Redistributions in binary form must reproduce the above copyright notice, this -** list of conditions and the following disclaimer in the documentation and/or -** other materials provided with the distribution. -** -** o Neither the name of the copyright holder nor the names of its -** contributors may be used to endorse or promote products derived from this -** software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -** ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -** LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -** ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -** -** http: www.nxp.com -** mail: support@nxp.com -** -** Revisions: -** - rev. 1.0 (2013-08-12) -** Initial version. -** - rev. 2.0 (2013-10-29) -** Register accessor macros added to the memory map. -** Symbols for Processor Expert memory map compatibility added to the memory map. -** Startup file for gcc has been updated according to CMSIS 3.2. -** System initialization updated. -** MCG - registers updated. -** PORTA, PORTB, PORTC, PORTE - registers for digital filter removed. -** - rev. 2.1 (2013-10-30) -** Definition of BITBAND macros updated to support peripherals with 32-bit acces disabled. -** - rev. 2.2 (2013-12-09) -** DMA - EARS register removed. -** AIPS0, AIPS1 - MPRA register updated. -** - rev. 2.3 (2014-01-24) -** Update according to reference manual rev. 2 -** ENET, MCG, MCM, SIM, USB - registers updated -** - rev. 2.4 (2014-01-30) -** Added single maximum value generation and a constrain to varying feature values that only numbers can have maximum. -** - rev. 2.5 (2014-02-10) -** The declaration of clock configurations has been moved to separate header file system_MK24F12.h -** Update of SystemInit() and SystemCoreClockUpdate() functions. -** Module access macro module_BASES replaced by module_BASE_PTRS. -** - rev. 2.6 (2014-08-28) -** Update of system files - default clock configuration changed. -** Update of startup files - possibility to override DefaultISR added. -** - rev. 2.7 (2014-10-14) -** Interrupt INT_LPTimer renamed to INT_LPTMR0, interrupt INT_Watchdog renamed to INT_WDOG_EWM. -** - rev. 2.8 (2015-01-21) -** Added FSL_FEATURE_SOC_peripheral_COUNT with number of peripheral instances -** - rev. 2.9 (2015-02-19) -** Renamed interrupt vector LLW to LLWU. -** - rev. 2.10 (2015-05-19) -** FSL_FEATURE_SOC_CAU_COUNT remamed to FSL_FEATURE_SOC_MMCAU_COUNT. -** Added FSL_FEATURE_SOC_peripheral_COUNT for TRNG and HSADC. -** Added features for PDB and PORT. -** - rev. 2.11 (2015-05-25) -** Added FSL_FEATURE_FLASH_PFLASH_START_ADDRESS -** - rev. 2.12 (2015-05-27) -** Several USB features added. -** - rev. 2.13 (2015-06-08) -** FTM features BUS_CLOCK and FAST_CLOCK removed. -** - rev. 2.14 (2016-03-21) -** Added MK24FN1M0CAJ12 part. -** -** ################################################################### -*/ - -#ifndef _MK24F12_FEATURES_H_ -#define _MK24F12_FEATURES_H_ - -/* SOC module features */ - -#if defined(CPU_MK24FN1M0CAJ12) || defined(CPU_MK24FN1M0VDC12) || defined(CPU_MK24FN1M0VLQ12) - /* @brief ACMP availability on the SoC. */ - #define FSL_FEATURE_SOC_ACMP_COUNT (0) - /* @brief ADC16 availability on the SoC. */ - #define FSL_FEATURE_SOC_ADC16_COUNT (2) - /* @brief ADC12 availability on the SoC. */ - #define FSL_FEATURE_SOC_ADC12_COUNT (0) - /* @brief AFE availability on the SoC. */ - #define FSL_FEATURE_SOC_AFE_COUNT (0) - /* @brief AIPS availability on the SoC. */ - #define FSL_FEATURE_SOC_AIPS_COUNT (2) - /* @brief AOI availability on the SoC. */ - #define FSL_FEATURE_SOC_AOI_COUNT (0) - /* @brief AXBS availability on the SoC. */ - #define FSL_FEATURE_SOC_AXBS_COUNT (1) - /* @brief ASMC availability on the SoC. */ - #define FSL_FEATURE_SOC_ASMC_COUNT (0) - /* @brief CADC availability on the SoC. */ - #define FSL_FEATURE_SOC_CADC_COUNT (0) - /* @brief FLEXCAN availability on the SoC. */ - #define FSL_FEATURE_SOC_FLEXCAN_COUNT (1) - /* @brief MMCAU availability on the SoC. */ - #define FSL_FEATURE_SOC_MMCAU_COUNT (1) - /* @brief CMP availability on the SoC. */ - #define FSL_FEATURE_SOC_CMP_COUNT (3) - /* @brief CMT availability on the SoC. */ - #define FSL_FEATURE_SOC_CMT_COUNT (1) - /* @brief CNC availability on the SoC. */ - #define FSL_FEATURE_SOC_CNC_COUNT (0) - /* @brief CRC availability on the SoC. */ - #define FSL_FEATURE_SOC_CRC_COUNT (1) - /* @brief DAC availability on the SoC. */ - #define FSL_FEATURE_SOC_DAC_COUNT (2) - /* @brief DAC32 availability on the SoC. */ - #define FSL_FEATURE_SOC_DAC32_COUNT (0) - /* @brief DCDC availability on the SoC. */ - #define FSL_FEATURE_SOC_DCDC_COUNT (0) - /* @brief DDR availability on the SoC. */ - #define FSL_FEATURE_SOC_DDR_COUNT (0) - /* @brief DMA availability on the SoC. */ - #define FSL_FEATURE_SOC_DMA_COUNT (0) - /* @brief EDMA availability on the SoC. */ - #define FSL_FEATURE_SOC_EDMA_COUNT (1) - /* @brief DMAMUX availability on the SoC. */ - #define FSL_FEATURE_SOC_DMAMUX_COUNT (1) - /* @brief DRY availability on the SoC. */ - #define FSL_FEATURE_SOC_DRY_COUNT (0) - /* @brief DSPI availability on the SoC. */ - #define FSL_FEATURE_SOC_DSPI_COUNT (3) - /* @brief EMVSIM availability on the SoC. */ - #define FSL_FEATURE_SOC_EMVSIM_COUNT (0) - /* @brief ENC availability on the SoC. */ - #define FSL_FEATURE_SOC_ENC_COUNT (0) - /* @brief ENET availability on the SoC. */ - #define FSL_FEATURE_SOC_ENET_COUNT (0) - /* @brief EWM availability on the SoC. */ - #define FSL_FEATURE_SOC_EWM_COUNT (1) - /* @brief FB availability on the SoC. */ - #define FSL_FEATURE_SOC_FB_COUNT (1) - /* @brief FGPIO availability on the SoC. */ - #define FSL_FEATURE_SOC_FGPIO_COUNT (0) - /* @brief FLEXIO availability on the SoC. */ - #define FSL_FEATURE_SOC_FLEXIO_COUNT (0) - /* @brief FMC availability on the SoC. */ - #define FSL_FEATURE_SOC_FMC_COUNT (1) - /* @brief FSKDT availability on the SoC. */ - #define FSL_FEATURE_SOC_FSKDT_COUNT (0) - /* @brief FTFA availability on the SoC. */ - #define FSL_FEATURE_SOC_FTFA_COUNT (0) - /* @brief FTFE availability on the SoC. */ - #define FSL_FEATURE_SOC_FTFE_COUNT (1) - /* @brief FTFL availability on the SoC. */ - #define FSL_FEATURE_SOC_FTFL_COUNT (0) - /* @brief FTM availability on the SoC. */ - #define FSL_FEATURE_SOC_FTM_COUNT (4) - /* @brief FTMRA availability on the SoC. */ - #define FSL_FEATURE_SOC_FTMRA_COUNT (0) - /* @brief FTMRE availability on the SoC. */ - #define FSL_FEATURE_SOC_FTMRE_COUNT (0) - /* @brief FTMRH availability on the SoC. */ - #define FSL_FEATURE_SOC_FTMRH_COUNT (0) - /* @brief GPIO availability on the SoC. */ - #define FSL_FEATURE_SOC_GPIO_COUNT (5) - /* @brief HSADC availability on the SoC. */ - #define FSL_FEATURE_SOC_HSADC_COUNT (0) - /* @brief I2C availability on the SoC. */ - #define FSL_FEATURE_SOC_I2C_COUNT (3) - /* @brief I2S availability on the SoC. */ - #define FSL_FEATURE_SOC_I2S_COUNT (1) - /* @brief ICS availability on the SoC. */ - #define FSL_FEATURE_SOC_ICS_COUNT (0) - /* @brief INTMUX availability on the SoC. */ - #define FSL_FEATURE_SOC_INTMUX_COUNT (0) - /* @brief IRQ availability on the SoC. */ - #define FSL_FEATURE_SOC_IRQ_COUNT (0) - /* @brief KBI availability on the SoC. */ - #define FSL_FEATURE_SOC_KBI_COUNT (0) - /* @brief SLCD availability on the SoC. */ - #define FSL_FEATURE_SOC_SLCD_COUNT (0) - /* @brief LCDC availability on the SoC. */ - #define FSL_FEATURE_SOC_LCDC_COUNT (0) - /* @brief LDO availability on the SoC. */ - #define FSL_FEATURE_SOC_LDO_COUNT (0) - /* @brief LLWU availability on the SoC. */ - #define FSL_FEATURE_SOC_LLWU_COUNT (1) - /* @brief LMEM availability on the SoC. */ - #define FSL_FEATURE_SOC_LMEM_COUNT (0) - /* @brief LPI2C availability on the SoC. */ - #define FSL_FEATURE_SOC_LPI2C_COUNT (0) - /* @brief LPIT availability on the SoC. */ - #define FSL_FEATURE_SOC_LPIT_COUNT (0) - /* @brief LPSCI availability on the SoC. */ - #define FSL_FEATURE_SOC_LPSCI_COUNT (0) - /* @brief LPSPI availability on the SoC. */ - #define FSL_FEATURE_SOC_LPSPI_COUNT (0) - /* @brief LPTMR availability on the SoC. */ - #define FSL_FEATURE_SOC_LPTMR_COUNT (1) - /* @brief LPTPM availability on the SoC. */ - #define FSL_FEATURE_SOC_LPTPM_COUNT (0) - /* @brief LPUART availability on the SoC. */ - #define FSL_FEATURE_SOC_LPUART_COUNT (0) - /* @brief LTC availability on the SoC. */ - #define FSL_FEATURE_SOC_LTC_COUNT (0) - /* @brief MC availability on the SoC. */ - #define FSL_FEATURE_SOC_MC_COUNT (0) - /* @brief MCG availability on the SoC. */ - #define FSL_FEATURE_SOC_MCG_COUNT (1) - /* @brief MCGLITE availability on the SoC. */ - #define FSL_FEATURE_SOC_MCGLITE_COUNT (0) - /* @brief MCM availability on the SoC. */ - #define FSL_FEATURE_SOC_MCM_COUNT (1) - /* @brief MMAU availability on the SoC. */ - #define FSL_FEATURE_SOC_MMAU_COUNT (0) - /* @brief MMDVSQ availability on the SoC. */ - #define FSL_FEATURE_SOC_MMDVSQ_COUNT (0) - /* @brief SYSMPU availability on the SoC. */ - #define FSL_FEATURE_SOC_SYSMPU_COUNT (1) - /* @brief MSCAN availability on the SoC. */ - #define FSL_FEATURE_SOC_MSCAN_COUNT (0) - /* @brief MSCM availability on the SoC. */ - #define FSL_FEATURE_SOC_MSCM_COUNT (0) - /* @brief MTB availability on the SoC. */ - #define FSL_FEATURE_SOC_MTB_COUNT (0) - /* @brief MTBDWT availability on the SoC. */ - #define FSL_FEATURE_SOC_MTBDWT_COUNT (0) - /* @brief MU availability on the SoC. */ - #define FSL_FEATURE_SOC_MU_COUNT (0) - /* @brief NFC availability on the SoC. */ - #define FSL_FEATURE_SOC_NFC_COUNT (0) - /* @brief OPAMP availability on the SoC. */ - #define FSL_FEATURE_SOC_OPAMP_COUNT (0) - /* @brief OSC availability on the SoC. */ - #define FSL_FEATURE_SOC_OSC_COUNT (1) - /* @brief OSC32 availability on the SoC. */ - #define FSL_FEATURE_SOC_OSC32_COUNT (0) - /* @brief OTFAD availability on the SoC. */ - #define FSL_FEATURE_SOC_OTFAD_COUNT (0) - /* @brief PDB availability on the SoC. */ - #define FSL_FEATURE_SOC_PDB_COUNT (1) - /* @brief PCC availability on the SoC. */ - #define FSL_FEATURE_SOC_PCC_COUNT (0) - /* @brief PGA availability on the SoC. */ - #define FSL_FEATURE_SOC_PGA_COUNT (0) - /* @brief PIT availability on the SoC. */ - #define FSL_FEATURE_SOC_PIT_COUNT (1) - /* @brief PMC availability on the SoC. */ - #define FSL_FEATURE_SOC_PMC_COUNT (1) - /* @brief PORT availability on the SoC. */ - #define FSL_FEATURE_SOC_PORT_COUNT (5) - /* @brief PWM availability on the SoC. */ - #define FSL_FEATURE_SOC_PWM_COUNT (0) - /* @brief PWT availability on the SoC. */ - #define FSL_FEATURE_SOC_PWT_COUNT (0) - /* @brief QuadSPI availability on the SoC. */ - #define FSL_FEATURE_SOC_QuadSPI_COUNT (0) - /* @brief RCM availability on the SoC. */ - #define FSL_FEATURE_SOC_RCM_COUNT (1) - /* @brief RFSYS availability on the SoC. */ - #define FSL_FEATURE_SOC_RFSYS_COUNT (1) - /* @brief RFVBAT availability on the SoC. */ - #define FSL_FEATURE_SOC_RFVBAT_COUNT (1) - /* @brief RNG availability on the SoC. */ - #define FSL_FEATURE_SOC_RNG_COUNT (1) - /* @brief RNGB availability on the SoC. */ - #define FSL_FEATURE_SOC_RNGB_COUNT (0) - /* @brief ROM availability on the SoC. */ - #define FSL_FEATURE_SOC_ROM_COUNT (0) - /* @brief RSIM availability on the SoC. */ - #define FSL_FEATURE_SOC_RSIM_COUNT (0) - /* @brief RTC availability on the SoC. */ - #define FSL_FEATURE_SOC_RTC_COUNT (1) - /* @brief SCG availability on the SoC. */ - #define FSL_FEATURE_SOC_SCG_COUNT (0) - /* @brief SCI availability on the SoC. */ - #define FSL_FEATURE_SOC_SCI_COUNT (0) - /* @brief SDHC availability on the SoC. */ - #define FSL_FEATURE_SOC_SDHC_COUNT (1) - /* @brief SDRAM availability on the SoC. */ - #define FSL_FEATURE_SOC_SDRAM_COUNT (0) - /* @brief SEMA42 availability on the SoC. */ - #define FSL_FEATURE_SOC_SEMA42_COUNT (0) - /* @brief SIM availability on the SoC. */ - #define FSL_FEATURE_SOC_SIM_COUNT (1) - /* @brief SMC availability on the SoC. */ - #define FSL_FEATURE_SOC_SMC_COUNT (1) - /* @brief SPI availability on the SoC. */ - #define FSL_FEATURE_SOC_SPI_COUNT (0) - /* @brief TMR availability on the SoC. */ - #define FSL_FEATURE_SOC_TMR_COUNT (0) - /* @brief TPM availability on the SoC. */ - #define FSL_FEATURE_SOC_TPM_COUNT (0) - /* @brief TRGMUX availability on the SoC. */ - #define FSL_FEATURE_SOC_TRGMUX_COUNT (0) - /* @brief TRIAMP availability on the SoC. */ - #define FSL_FEATURE_SOC_TRIAMP_COUNT (0) - /* @brief TRNG availability on the SoC. */ - #define FSL_FEATURE_SOC_TRNG_COUNT (0) - /* @brief TSI availability on the SoC. */ - #define FSL_FEATURE_SOC_TSI_COUNT (0) - /* @brief TSTMR availability on the SoC. */ - #define FSL_FEATURE_SOC_TSTMR_COUNT (0) - /* @brief UART availability on the SoC. */ - #define FSL_FEATURE_SOC_UART_COUNT (6) - /* @brief USB availability on the SoC. */ - #define FSL_FEATURE_SOC_USB_COUNT (1) - /* @brief USBDCD availability on the SoC. */ - #define FSL_FEATURE_SOC_USBDCD_COUNT (1) - /* @brief USBHS availability on the SoC. */ - #define FSL_FEATURE_SOC_USBHS_COUNT (0) - /* @brief USBHSDCD availability on the SoC. */ - #define FSL_FEATURE_SOC_USBHSDCD_COUNT (0) - /* @brief USBPHY availability on the SoC. */ - #define FSL_FEATURE_SOC_USBPHY_COUNT (0) - /* @brief VREF availability on the SoC. */ - #define FSL_FEATURE_SOC_VREF_COUNT (1) - /* @brief WDOG availability on the SoC. */ - #define FSL_FEATURE_SOC_WDOG_COUNT (1) - /* @brief XBAR availability on the SoC. */ - #define FSL_FEATURE_SOC_XBAR_COUNT (0) - /* @brief XBARA availability on the SoC. */ - #define FSL_FEATURE_SOC_XBARA_COUNT (0) - /* @brief XBARB availability on the SoC. */ - #define FSL_FEATURE_SOC_XBARB_COUNT (0) - /* @brief XCVR availability on the SoC. */ - #define FSL_FEATURE_SOC_XCVR_COUNT (0) - /* @brief XRDC availability on the SoC. */ - #define FSL_FEATURE_SOC_XRDC_COUNT (0) - /* @brief ZLL availability on the SoC. */ - #define FSL_FEATURE_SOC_ZLL_COUNT (0) -#elif defined(CPU_MK24FN1M0VLL12) - /* @brief ACMP availability on the SoC. */ - #define FSL_FEATURE_SOC_ACMP_COUNT (0) - /* @brief ADC16 availability on the SoC. */ - #define FSL_FEATURE_SOC_ADC16_COUNT (2) - /* @brief ADC12 availability on the SoC. */ - #define FSL_FEATURE_SOC_ADC12_COUNT (0) - /* @brief AFE availability on the SoC. */ - #define FSL_FEATURE_SOC_AFE_COUNT (0) - /* @brief AIPS availability on the SoC. */ - #define FSL_FEATURE_SOC_AIPS_COUNT (2) - /* @brief AOI availability on the SoC. */ - #define FSL_FEATURE_SOC_AOI_COUNT (0) - /* @brief AXBS availability on the SoC. */ - #define FSL_FEATURE_SOC_AXBS_COUNT (1) - /* @brief ASMC availability on the SoC. */ - #define FSL_FEATURE_SOC_ASMC_COUNT (0) - /* @brief CADC availability on the SoC. */ - #define FSL_FEATURE_SOC_CADC_COUNT (0) - /* @brief FLEXCAN availability on the SoC. */ - #define FSL_FEATURE_SOC_FLEXCAN_COUNT (1) - /* @brief MMCAU availability on the SoC. */ - #define FSL_FEATURE_SOC_MMCAU_COUNT (1) - /* @brief CMP availability on the SoC. */ - #define FSL_FEATURE_SOC_CMP_COUNT (3) - /* @brief CMT availability on the SoC. */ - #define FSL_FEATURE_SOC_CMT_COUNT (1) - /* @brief CNC availability on the SoC. */ - #define FSL_FEATURE_SOC_CNC_COUNT (0) - /* @brief CRC availability on the SoC. */ - #define FSL_FEATURE_SOC_CRC_COUNT (1) - /* @brief DAC availability on the SoC. */ - #define FSL_FEATURE_SOC_DAC_COUNT (1) - /* @brief DAC32 availability on the SoC. */ - #define FSL_FEATURE_SOC_DAC32_COUNT (0) - /* @brief DCDC availability on the SoC. */ - #define FSL_FEATURE_SOC_DCDC_COUNT (0) - /* @brief DDR availability on the SoC. */ - #define FSL_FEATURE_SOC_DDR_COUNT (0) - /* @brief DMA availability on the SoC. */ - #define FSL_FEATURE_SOC_DMA_COUNT (0) - /* @brief EDMA availability on the SoC. */ - #define FSL_FEATURE_SOC_EDMA_COUNT (1) - /* @brief DMAMUX availability on the SoC. */ - #define FSL_FEATURE_SOC_DMAMUX_COUNT (1) - /* @brief DRY availability on the SoC. */ - #define FSL_FEATURE_SOC_DRY_COUNT (0) - /* @brief DSPI availability on the SoC. */ - #define FSL_FEATURE_SOC_DSPI_COUNT (3) - /* @brief EMVSIM availability on the SoC. */ - #define FSL_FEATURE_SOC_EMVSIM_COUNT (0) - /* @brief ENC availability on the SoC. */ - #define FSL_FEATURE_SOC_ENC_COUNT (0) - /* @brief ENET availability on the SoC. */ - #define FSL_FEATURE_SOC_ENET_COUNT (0) - /* @brief EWM availability on the SoC. */ - #define FSL_FEATURE_SOC_EWM_COUNT (1) - /* @brief FB availability on the SoC. */ - #define FSL_FEATURE_SOC_FB_COUNT (1) - /* @brief FGPIO availability on the SoC. */ - #define FSL_FEATURE_SOC_FGPIO_COUNT (0) - /* @brief FLEXIO availability on the SoC. */ - #define FSL_FEATURE_SOC_FLEXIO_COUNT (0) - /* @brief FMC availability on the SoC. */ - #define FSL_FEATURE_SOC_FMC_COUNT (1) - /* @brief FSKDT availability on the SoC. */ - #define FSL_FEATURE_SOC_FSKDT_COUNT (0) - /* @brief FTFA availability on the SoC. */ - #define FSL_FEATURE_SOC_FTFA_COUNT (0) - /* @brief FTFE availability on the SoC. */ - #define FSL_FEATURE_SOC_FTFE_COUNT (1) - /* @brief FTFL availability on the SoC. */ - #define FSL_FEATURE_SOC_FTFL_COUNT (0) - /* @brief FTM availability on the SoC. */ - #define FSL_FEATURE_SOC_FTM_COUNT (4) - /* @brief FTMRA availability on the SoC. */ - #define FSL_FEATURE_SOC_FTMRA_COUNT (0) - /* @brief FTMRE availability on the SoC. */ - #define FSL_FEATURE_SOC_FTMRE_COUNT (0) - /* @brief FTMRH availability on the SoC. */ - #define FSL_FEATURE_SOC_FTMRH_COUNT (0) - /* @brief GPIO availability on the SoC. */ - #define FSL_FEATURE_SOC_GPIO_COUNT (5) - /* @brief HSADC availability on the SoC. */ - #define FSL_FEATURE_SOC_HSADC_COUNT (0) - /* @brief I2C availability on the SoC. */ - #define FSL_FEATURE_SOC_I2C_COUNT (3) - /* @brief I2S availability on the SoC. */ - #define FSL_FEATURE_SOC_I2S_COUNT (1) - /* @brief ICS availability on the SoC. */ - #define FSL_FEATURE_SOC_ICS_COUNT (0) - /* @brief INTMUX availability on the SoC. */ - #define FSL_FEATURE_SOC_INTMUX_COUNT (0) - /* @brief IRQ availability on the SoC. */ - #define FSL_FEATURE_SOC_IRQ_COUNT (0) - /* @brief KBI availability on the SoC. */ - #define FSL_FEATURE_SOC_KBI_COUNT (0) - /* @brief SLCD availability on the SoC. */ - #define FSL_FEATURE_SOC_SLCD_COUNT (0) - /* @brief LCDC availability on the SoC. */ - #define FSL_FEATURE_SOC_LCDC_COUNT (0) - /* @brief LDO availability on the SoC. */ - #define FSL_FEATURE_SOC_LDO_COUNT (0) - /* @brief LLWU availability on the SoC. */ - #define FSL_FEATURE_SOC_LLWU_COUNT (1) - /* @brief LMEM availability on the SoC. */ - #define FSL_FEATURE_SOC_LMEM_COUNT (0) - /* @brief LPI2C availability on the SoC. */ - #define FSL_FEATURE_SOC_LPI2C_COUNT (0) - /* @brief LPIT availability on the SoC. */ - #define FSL_FEATURE_SOC_LPIT_COUNT (0) - /* @brief LPSCI availability on the SoC. */ - #define FSL_FEATURE_SOC_LPSCI_COUNT (0) - /* @brief LPSPI availability on the SoC. */ - #define FSL_FEATURE_SOC_LPSPI_COUNT (0) - /* @brief LPTMR availability on the SoC. */ - #define FSL_FEATURE_SOC_LPTMR_COUNT (1) - /* @brief LPTPM availability on the SoC. */ - #define FSL_FEATURE_SOC_LPTPM_COUNT (0) - /* @brief LPUART availability on the SoC. */ - #define FSL_FEATURE_SOC_LPUART_COUNT (0) - /* @brief LTC availability on the SoC. */ - #define FSL_FEATURE_SOC_LTC_COUNT (0) - /* @brief MC availability on the SoC. */ - #define FSL_FEATURE_SOC_MC_COUNT (0) - /* @brief MCG availability on the SoC. */ - #define FSL_FEATURE_SOC_MCG_COUNT (1) - /* @brief MCGLITE availability on the SoC. */ - #define FSL_FEATURE_SOC_MCGLITE_COUNT (0) - /* @brief MCM availability on the SoC. */ - #define FSL_FEATURE_SOC_MCM_COUNT (1) - /* @brief MMAU availability on the SoC. */ - #define FSL_FEATURE_SOC_MMAU_COUNT (0) - /* @brief MMDVSQ availability on the SoC. */ - #define FSL_FEATURE_SOC_MMDVSQ_COUNT (0) - /* @brief SYSMPU availability on the SoC. */ - #define FSL_FEATURE_SOC_SYSMPU_COUNT (1) - /* @brief MSCAN availability on the SoC. */ - #define FSL_FEATURE_SOC_MSCAN_COUNT (0) - /* @brief MSCM availability on the SoC. */ - #define FSL_FEATURE_SOC_MSCM_COUNT (0) - /* @brief MTB availability on the SoC. */ - #define FSL_FEATURE_SOC_MTB_COUNT (0) - /* @brief MTBDWT availability on the SoC. */ - #define FSL_FEATURE_SOC_MTBDWT_COUNT (0) - /* @brief MU availability on the SoC. */ - #define FSL_FEATURE_SOC_MU_COUNT (0) - /* @brief NFC availability on the SoC. */ - #define FSL_FEATURE_SOC_NFC_COUNT (0) - /* @brief OPAMP availability on the SoC. */ - #define FSL_FEATURE_SOC_OPAMP_COUNT (0) - /* @brief OSC availability on the SoC. */ - #define FSL_FEATURE_SOC_OSC_COUNT (1) - /* @brief OSC32 availability on the SoC. */ - #define FSL_FEATURE_SOC_OSC32_COUNT (0) - /* @brief OTFAD availability on the SoC. */ - #define FSL_FEATURE_SOC_OTFAD_COUNT (0) - /* @brief PDB availability on the SoC. */ - #define FSL_FEATURE_SOC_PDB_COUNT (1) - /* @brief PCC availability on the SoC. */ - #define FSL_FEATURE_SOC_PCC_COUNT (0) - /* @brief PGA availability on the SoC. */ - #define FSL_FEATURE_SOC_PGA_COUNT (0) - /* @brief PIT availability on the SoC. */ - #define FSL_FEATURE_SOC_PIT_COUNT (1) - /* @brief PMC availability on the SoC. */ - #define FSL_FEATURE_SOC_PMC_COUNT (1) - /* @brief PORT availability on the SoC. */ - #define FSL_FEATURE_SOC_PORT_COUNT (5) - /* @brief PWM availability on the SoC. */ - #define FSL_FEATURE_SOC_PWM_COUNT (0) - /* @brief PWT availability on the SoC. */ - #define FSL_FEATURE_SOC_PWT_COUNT (0) - /* @brief QuadSPI availability on the SoC. */ - #define FSL_FEATURE_SOC_QuadSPI_COUNT (0) - /* @brief RCM availability on the SoC. */ - #define FSL_FEATURE_SOC_RCM_COUNT (1) - /* @brief RFSYS availability on the SoC. */ - #define FSL_FEATURE_SOC_RFSYS_COUNT (1) - /* @brief RFVBAT availability on the SoC. */ - #define FSL_FEATURE_SOC_RFVBAT_COUNT (1) - /* @brief RNG availability on the SoC. */ - #define FSL_FEATURE_SOC_RNG_COUNT (1) - /* @brief RNGB availability on the SoC. */ - #define FSL_FEATURE_SOC_RNGB_COUNT (0) - /* @brief ROM availability on the SoC. */ - #define FSL_FEATURE_SOC_ROM_COUNT (0) - /* @brief RSIM availability on the SoC. */ - #define FSL_FEATURE_SOC_RSIM_COUNT (0) - /* @brief RTC availability on the SoC. */ - #define FSL_FEATURE_SOC_RTC_COUNT (1) - /* @brief SCG availability on the SoC. */ - #define FSL_FEATURE_SOC_SCG_COUNT (0) - /* @brief SCI availability on the SoC. */ - #define FSL_FEATURE_SOC_SCI_COUNT (0) - /* @brief SDHC availability on the SoC. */ - #define FSL_FEATURE_SOC_SDHC_COUNT (1) - /* @brief SDRAM availability on the SoC. */ - #define FSL_FEATURE_SOC_SDRAM_COUNT (0) - /* @brief SEMA42 availability on the SoC. */ - #define FSL_FEATURE_SOC_SEMA42_COUNT (0) - /* @brief SIM availability on the SoC. */ - #define FSL_FEATURE_SOC_SIM_COUNT (1) - /* @brief SMC availability on the SoC. */ - #define FSL_FEATURE_SOC_SMC_COUNT (1) - /* @brief SPI availability on the SoC. */ - #define FSL_FEATURE_SOC_SPI_COUNT (0) - /* @brief TMR availability on the SoC. */ - #define FSL_FEATURE_SOC_TMR_COUNT (0) - /* @brief TPM availability on the SoC. */ - #define FSL_FEATURE_SOC_TPM_COUNT (0) - /* @brief TRGMUX availability on the SoC. */ - #define FSL_FEATURE_SOC_TRGMUX_COUNT (0) - /* @brief TRIAMP availability on the SoC. */ - #define FSL_FEATURE_SOC_TRIAMP_COUNT (0) - /* @brief TRNG availability on the SoC. */ - #define FSL_FEATURE_SOC_TRNG_COUNT (0) - /* @brief TSI availability on the SoC. */ - #define FSL_FEATURE_SOC_TSI_COUNT (0) - /* @brief TSTMR availability on the SoC. */ - #define FSL_FEATURE_SOC_TSTMR_COUNT (0) - /* @brief UART availability on the SoC. */ - #define FSL_FEATURE_SOC_UART_COUNT (5) - /* @brief USB availability on the SoC. */ - #define FSL_FEATURE_SOC_USB_COUNT (1) - /* @brief USBDCD availability on the SoC. */ - #define FSL_FEATURE_SOC_USBDCD_COUNT (1) - /* @brief USBHS availability on the SoC. */ - #define FSL_FEATURE_SOC_USBHS_COUNT (0) - /* @brief USBHSDCD availability on the SoC. */ - #define FSL_FEATURE_SOC_USBHSDCD_COUNT (0) - /* @brief USBPHY availability on the SoC. */ - #define FSL_FEATURE_SOC_USBPHY_COUNT (0) - /* @brief VREF availability on the SoC. */ - #define FSL_FEATURE_SOC_VREF_COUNT (1) - /* @brief WDOG availability on the SoC. */ - #define FSL_FEATURE_SOC_WDOG_COUNT (1) - /* @brief XBAR availability on the SoC. */ - #define FSL_FEATURE_SOC_XBAR_COUNT (0) - /* @brief XBARA availability on the SoC. */ - #define FSL_FEATURE_SOC_XBARA_COUNT (0) - /* @brief XBARB availability on the SoC. */ - #define FSL_FEATURE_SOC_XBARB_COUNT (0) - /* @brief XCVR availability on the SoC. */ - #define FSL_FEATURE_SOC_XCVR_COUNT (0) - /* @brief XRDC availability on the SoC. */ - #define FSL_FEATURE_SOC_XRDC_COUNT (0) - /* @brief ZLL availability on the SoC. */ - #define FSL_FEATURE_SOC_ZLL_COUNT (0) -#endif - -/* ADC16 module features */ - -/* @brief Has Programmable Gain Amplifier (PGA) in ADC (register PGA). */ -#define FSL_FEATURE_ADC16_HAS_PGA (0) -/* @brief Has PGA chopping control in ADC (bit PGA[PGACHPb] or PGA[PGACHP]). */ -#define FSL_FEATURE_ADC16_HAS_PGA_CHOPPING (0) -/* @brief Has PGA offset measurement mode in ADC (bit PGA[PGAOFSM]). */ -#define FSL_FEATURE_ADC16_HAS_PGA_OFFSET_MEASUREMENT (0) -/* @brief Has DMA support (bit SC2[DMAEN] or SC4[DMAEN]). */ -#define FSL_FEATURE_ADC16_HAS_DMA (1) -/* @brief Has differential mode (bitfield SC1x[DIFF]). */ -#define FSL_FEATURE_ADC16_HAS_DIFF_MODE (1) -/* @brief Has FIFO (bit SC4[AFDEP]). */ -#define FSL_FEATURE_ADC16_HAS_FIFO (0) -/* @brief FIFO size if available (bitfield SC4[AFDEP]). */ -#define FSL_FEATURE_ADC16_FIFO_SIZE (0) -/* @brief Has channel set a/b multiplexor (bitfield CFG2[MUXSEL]). */ -#define FSL_FEATURE_ADC16_HAS_MUX_SELECT (1) -/* @brief Has HW trigger masking (bitfield SC5[HTRGMASKE]. */ -#define FSL_FEATURE_ADC16_HAS_HW_TRIGGER_MASK (0) -/* @brief Has calibration feature (bit SC3[CAL] and registers CLPx, CLMx). */ -#define FSL_FEATURE_ADC16_HAS_CALIBRATION (1) -/* @brief Has HW averaging (bit SC3[AVGE]). */ -#define FSL_FEATURE_ADC16_HAS_HW_AVERAGE (1) -/* @brief Has offset correction (register OFS). */ -#define FSL_FEATURE_ADC16_HAS_OFFSET_CORRECTION (1) -/* @brief Maximum ADC resolution. */ -#define FSL_FEATURE_ADC16_MAX_RESOLUTION (16) -/* @brief Number of SC1x and Rx register pairs (conversion control and result registers). */ -#define FSL_FEATURE_ADC16_CONVERSION_CONTROL_COUNT (2) - -/* FLEXCAN module features */ - -/* @brief Message buffer size */ -#define FSL_FEATURE_FLEXCAN_HAS_MESSAGE_BUFFER_MAX_NUMBERn(x) (16) -/* @brief Has doze mode support (register bit field MCR[DOZE]). */ -#define FSL_FEATURE_FLEXCAN_HAS_DOZE_MODE_SUPPORT (0) -/* @brief Has a glitch filter on the receive pin (register bit field MCR[WAKSRC]). */ -#define FSL_FEATURE_FLEXCAN_HAS_GLITCH_FILTER (1) -/* @brief Has extended interrupt mask and flag register (register IMASK2, IFLAG2). */ -#define FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER (0) -/* @brief Has extended bit timing register (register CBT). */ -#define FSL_FEATURE_FLEXCAN_HAS_EXTENDED_TIMING_REGISTER (0) -/* @brief Has a receive FIFO DMA feature (register bit field MCR[DMA]). */ -#define FSL_FEATURE_FLEXCAN_HAS_RX_FIFO_DMA (0) -/* @brief Has separate message buffer 0 interrupt flag (register bit field IFLAG1[BUF0I]). */ -#define FSL_FEATURE_FLEXCAN_HAS_SEPARATE_BUFFER_0_FLAG (1) -/* @brief Has bitfield name BUF31TO0M. */ -#define FSL_FEATURE_FLEXCAN_HAS_BUF31TO0M (0) -/* @brief Number of interrupt vectors. */ -#define FSL_FEATURE_FLEXCAN_INTERRUPT_COUNT (6) -/* @brief Is affected by errata with ID 5641 (Module does not transmit a message that is enabled to be transmitted at a specific moment during the arbitration process). */ -#define FSL_FEATURE_FLEXCAN_HAS_ERRATA_5641 (0) - -/* CMP module features */ - -/* @brief Has Trigger mode in CMP (register bit field CR1[TRIGM]). */ -#define FSL_FEATURE_CMP_HAS_TRIGGER_MODE (0) -/* @brief Has Window mode in CMP (register bit field CR1[WE]). */ -#define FSL_FEATURE_CMP_HAS_WINDOW_MODE (1) -/* @brief Has External sample supported in CMP (register bit field CR1[SE]). */ -#define FSL_FEATURE_CMP_HAS_EXTERNAL_SAMPLE_SUPPORT (1) -/* @brief Has DMA support in CMP (register bit field SCR[DMAEN]). */ -#define FSL_FEATURE_CMP_HAS_DMA (1) -/* @brief Has Pass Through mode in CMP (register bit field MUXCR[PSTM]). */ -#define FSL_FEATURE_CMP_HAS_PASS_THROUGH_MODE (1) -/* @brief Has DAC Test function in CMP (register DACTEST). */ -#define FSL_FEATURE_CMP_HAS_DAC_TEST (0) - -/* CRC module features */ - -/* @brief Has data register with name CRC */ -#define FSL_FEATURE_CRC_HAS_CRC_REG (0) - -/* DAC module features */ - -/* @brief Define the size of hardware buffer */ -#define FSL_FEATURE_DAC_BUFFER_SIZE (16) -/* @brief Define whether the buffer supports watermark event detection or not. */ -#define FSL_FEATURE_DAC_HAS_WATERMARK_DETECTION (1) -/* @brief Define whether the buffer supports watermark selection detection or not. */ -#define FSL_FEATURE_DAC_HAS_WATERMARK_SELECTION (1) -/* @brief Define whether the buffer supports watermark event 1 word before buffer upper limit. */ -#define FSL_FEATURE_DAC_HAS_WATERMARK_1_WORD (1) -/* @brief Define whether the buffer supports watermark event 2 words before buffer upper limit. */ -#define FSL_FEATURE_DAC_HAS_WATERMARK_2_WORDS (1) -/* @brief Define whether the buffer supports watermark event 3 words before buffer upper limit. */ -#define FSL_FEATURE_DAC_HAS_WATERMARK_3_WORDS (1) -/* @brief Define whether the buffer supports watermark event 4 words before buffer upper limit. */ -#define FSL_FEATURE_DAC_HAS_WATERMARK_4_WORDS (1) -/* @brief Define whether FIFO buffer mode is available or not. */ -#define FSL_FEATURE_DAC_HAS_BUFFER_FIFO_MODE (0) -/* @brief Define whether swing buffer mode is available or not.. */ -#define FSL_FEATURE_DAC_HAS_BUFFER_SWING_MODE (1) - -/* EDMA module features */ - -/* @brief Number of DMA channels (related to number of registers TCD, DCHPRI, bit fields ERQ[ERQn], EEI[EEIn], INT[INTn], ERR[ERRn], HRS[HRSn] and bit field widths ES[ERRCHN], CEEI[CEEI], SEEI[SEEI], CERQ[CERQ], SERQ[SERQ], CDNE[CDNE], SSRT[SSRT], CERR[CERR], CINT[CINT], TCDn_CITER_ELINKYES[LINKCH], TCDn_CSR[MAJORLINKCH], TCDn_BITER_ELINKYES[LINKCH]). (Valid only for eDMA modules.) */ -#define FSL_FEATURE_EDMA_MODULE_CHANNEL (16) -/* @brief Total number of DMA channels on all modules. */ -#define FSL_FEATURE_EDMA_DMAMUX_CHANNELS (FSL_FEATURE_SOC_EDMA_COUNT * 16) -/* @brief Number of DMA channel groups (register bit fields CR[ERGA], CR[GRPnPRI], ES[GPE], DCHPRIn[GRPPRI]). (Valid only for eDMA modules.) */ -#define FSL_FEATURE_EDMA_CHANNEL_GROUP_COUNT (1) -/* @brief Has DMA_Error interrupt vector. */ -#define FSL_FEATURE_EDMA_HAS_ERROR_IRQ (1) -/* @brief Number of DMA channels with asynchronous request capability (register EARS). (Valid only for eDMA modules.) */ -#define FSL_FEATURE_EDMA_ASYNCHRO_REQUEST_CHANNEL_COUNT (0) - -/* DMAMUX module features */ - -/* @brief Number of DMA channels (related to number of register CHCFGn). */ -#define FSL_FEATURE_DMAMUX_MODULE_CHANNEL (16) -/* @brief Total number of DMA channels on all modules. */ -#define FSL_FEATURE_DMAMUX_DMAMUX_CHANNELS (FSL_FEATURE_SOC_DMAMUX_COUNT * 16) -/* @brief Has the periodic trigger capability for the triggered DMA channel (register bit CHCFG0[TRIG]). */ -#define FSL_FEATURE_DMAMUX_HAS_TRIG (1) - -/* EWM module features */ - -/* @brief Has clock select (register CLKCTRL). */ -#define FSL_FEATURE_EWM_HAS_CLOCK_SELECT (0) -/* @brief Has clock prescaler (register CLKPRESCALER). */ -#define FSL_FEATURE_EWM_HAS_PRESCALER (0) - -/* FLEXBUS module features */ - -/* No feature definitions */ - -/* FLASH module features */ - -/* @brief Is of type FTFA. */ -#define FSL_FEATURE_FLASH_IS_FTFA (0) -/* @brief Is of type FTFE. */ -#define FSL_FEATURE_FLASH_IS_FTFE (1) -/* @brief Is of type FTFL. */ -#define FSL_FEATURE_FLASH_IS_FTFL (0) -/* @brief Has flags indicating the status of the FlexRAM (register bits FCNFG[EEERDY], FCNFG[RAMRDY] and FCNFG[PFLSH]). */ -#define FSL_FEATURE_FLASH_HAS_FLEX_RAM_FLAGS (1) -/* @brief Has program flash swapping status flag (register bit FCNFG[SWAP]). */ -#define FSL_FEATURE_FLASH_HAS_PFLASH_SWAPPING_STATUS_FLAG (1) -/* @brief Has EEPROM region protection (register FEPROT). */ -#define FSL_FEATURE_FLASH_HAS_EEROM_REGION_PROTECTION (0) -/* @brief Has data flash region protection (register FDPROT). */ -#define FSL_FEATURE_FLASH_HAS_DATA_FLASH_REGION_PROTECTION (0) -/* @brief Has flash access control (registers XACCHn, SACCHn, where n is a number, FACSS and FACSN). */ -#define FSL_FEATURE_FLASH_HAS_ACCESS_CONTROL (0) -/* @brief Has flash cache control in FMC module. */ -#define FSL_FEATURE_FLASH_HAS_FMC_FLASH_CACHE_CONTROLS (1) -/* @brief Has flash cache control in MCM module. */ -#define FSL_FEATURE_FLASH_HAS_MCM_FLASH_CACHE_CONTROLS (0) -/* @brief Has flash cache control in MSCM module. */ -#define FSL_FEATURE_FLASH_HAS_MSCM_FLASH_CACHE_CONTROLS (0) -/* @brief Has prefetch speculation control in flash, such as kv5x. */ -#define FSL_FEATURE_FLASH_PREFETCH_SPECULATION_CONTROL_IN_FLASH (0) -/* @brief P-Flash start address. */ -#define FSL_FEATURE_FLASH_PFLASH_START_ADDRESS (0x00000000) -/* @brief P-Flash block count. */ -#define FSL_FEATURE_FLASH_PFLASH_BLOCK_COUNT (2) -/* @brief P-Flash block size. */ -#define FSL_FEATURE_FLASH_PFLASH_BLOCK_SIZE (524288) -/* @brief P-Flash sector size. */ -#define FSL_FEATURE_FLASH_PFLASH_BLOCK_SECTOR_SIZE (4096) -/* @brief P-Flash write unit size. */ -#define FSL_FEATURE_FLASH_PFLASH_BLOCK_WRITE_UNIT_SIZE (8) -/* @brief P-Flash data path width. */ -#define FSL_FEATURE_FLASH_PFLASH_BLOCK_DATA_PATH_WIDTH (16) -/* @brief P-Flash block swap feature. */ -#define FSL_FEATURE_FLASH_HAS_PFLASH_BLOCK_SWAP (1) -/* @brief P-Flash protection region count. */ -#define FSL_FEATURE_FLASH_PFLASH_PROTECTION_REGION_COUNT (32) -/* @brief Has FlexNVM memory. */ -#define FSL_FEATURE_FLASH_HAS_FLEX_NVM (0) -/* @brief FlexNVM start address. (Valid only if FlexNVM is available.) */ -#define FSL_FEATURE_FLASH_FLEX_NVM_START_ADDRESS (0x00000000) -/* @brief FlexNVM block count. */ -#define FSL_FEATURE_FLASH_FLEX_NVM_BLOCK_COUNT (0) -/* @brief FlexNVM block size. */ -#define FSL_FEATURE_FLASH_FLEX_NVM_BLOCK_SIZE (0) -/* @brief FlexNVM sector size. */ -#define FSL_FEATURE_FLASH_FLEX_NVM_BLOCK_SECTOR_SIZE (0) -/* @brief FlexNVM write unit size. */ -#define FSL_FEATURE_FLASH_FLEX_NVM_BLOCK_WRITE_UNIT_SIZE (0) -/* @brief FlexNVM data path width. */ -#define FSL_FEATURE_FLASH_FLEX_BLOCK_DATA_PATH_WIDTH (0) -/* @brief Has FlexRAM memory. */ -#define FSL_FEATURE_FLASH_HAS_FLEX_RAM (1) -/* @brief FlexRAM start address. (Valid only if FlexRAM is available.) */ -#define FSL_FEATURE_FLASH_FLEX_RAM_START_ADDRESS (0x14000000) -/* @brief FlexRAM size. */ -#define FSL_FEATURE_FLASH_FLEX_RAM_SIZE (4096) -/* @brief Has 0x00 Read 1s Block command. */ -#define FSL_FEATURE_FLASH_HAS_READ_1S_BLOCK_CMD (1) -/* @brief Has 0x01 Read 1s Section command. */ -#define FSL_FEATURE_FLASH_HAS_READ_1S_SECTION_CMD (1) -/* @brief Has 0x02 Program Check command. */ -#define FSL_FEATURE_FLASH_HAS_PROGRAM_CHECK_CMD (1) -/* @brief Has 0x03 Read Resource command. */ -#define FSL_FEATURE_FLASH_HAS_READ_RESOURCE_CMD (1) -/* @brief Has 0x06 Program Longword command. */ -#define FSL_FEATURE_FLASH_HAS_PROGRAM_LONGWORD_CMD (0) -/* @brief Has 0x07 Program Phrase command. */ -#define FSL_FEATURE_FLASH_HAS_PROGRAM_PHRASE_CMD (1) -/* @brief Has 0x08 Erase Flash Block command. */ -#define FSL_FEATURE_FLASH_HAS_ERASE_FLASH_BLOCK_CMD (1) -/* @brief Has 0x09 Erase Flash Sector command. */ -#define FSL_FEATURE_FLASH_HAS_ERASE_FLASH_SECTOR_CMD (1) -/* @brief Has 0x0B Program Section command. */ -#define FSL_FEATURE_FLASH_HAS_PROGRAM_SECTION_CMD (1) -/* @brief Has 0x40 Read 1s All Blocks command. */ -#define FSL_FEATURE_FLASH_HAS_READ_1S_ALL_BLOCKS_CMD (1) -/* @brief Has 0x41 Read Once command. */ -#define FSL_FEATURE_FLASH_HAS_READ_ONCE_CMD (1) -/* @brief Has 0x43 Program Once command. */ -#define FSL_FEATURE_FLASH_HAS_PROGRAM_ONCE_CMD (1) -/* @brief Has 0x44 Erase All Blocks command. */ -#define FSL_FEATURE_FLASH_HAS_ERASE_ALL_BLOCKS_CMD (1) -/* @brief Has 0x45 Verify Backdoor Access Key command. */ -#define FSL_FEATURE_FLASH_HAS_VERIFY_BACKDOOR_ACCESS_KEY_CMD (1) -/* @brief Has 0x46 Swap Control command. */ -#define FSL_FEATURE_FLASH_HAS_SWAP_CONTROL_CMD (1) -/* @brief Has 0x49 Erase All Blocks Unsecure command. */ -#define FSL_FEATURE_FLASH_HAS_ERASE_ALL_BLOCKS_UNSECURE_CMD (0) -/* @brief Has 0x4A Read 1s All Execute-only Segments command. */ -#define FSL_FEATURE_FLASH_HAS_READ_1S_ALL_EXECUTE_ONLY_SEGMENTS_CMD (0) -/* @brief Has 0x4B Erase All Execute-only Segments command. */ -#define FSL_FEATURE_FLASH_HAS_ERASE_ALL_EXECUTE_ONLY_SEGMENTS_CMD (0) -/* @brief Has 0x80 Program Partition command. */ -#define FSL_FEATURE_FLASH_HAS_PROGRAM_PARTITION_CMD (0) -/* @brief Has 0x81 Set FlexRAM Function command. */ -#define FSL_FEATURE_FLASH_HAS_SET_FLEXRAM_FUNCTION_CMD (0) -/* @brief P-Flash Erase/Read 1st all block command address alignment. */ -#define FSL_FEATURE_FLASH_PFLASH_BLOCK_CMD_ADDRESS_ALIGMENT (16) -/* @brief P-Flash Erase sector command address alignment. */ -#define FSL_FEATURE_FLASH_PFLASH_SECTOR_CMD_ADDRESS_ALIGMENT (16) -/* @brief P-Flash Rrogram/Verify section command address alignment. */ -#define FSL_FEATURE_FLASH_PFLASH_SECTION_CMD_ADDRESS_ALIGMENT (16) -/* @brief P-Flash Read resource command address alignment. */ -#define FSL_FEATURE_FLASH_PFLASH_RESOURCE_CMD_ADDRESS_ALIGMENT (8) -/* @brief P-Flash Program check command address alignment. */ -#define FSL_FEATURE_FLASH_PFLASH_CHECK_CMD_ADDRESS_ALIGMENT (4) -/* @brief P-Flash Program check command address alignment. */ -#define FSL_FEATURE_FLASH_PFLASH_SWAP_CONTROL_CMD_ADDRESS_ALIGMENT (16) -/* @brief FlexNVM Erase/Read 1st all block command address alignment. */ -#define FSL_FEATURE_FLASH_FLEX_NVM_BLOCK_CMD_ADDRESS_ALIGMENT (0) -/* @brief FlexNVM Erase sector command address alignment. */ -#define FSL_FEATURE_FLASH_FLEX_NVM_SECTOR_CMD_ADDRESS_ALIGMENT (0) -/* @brief FlexNVM Rrogram/Verify section command address alignment. */ -#define FSL_FEATURE_FLASH_FLEX_NVM_SECTION_CMD_ADDRESS_ALIGMENT (0) -/* @brief FlexNVM Read resource command address alignment. */ -#define FSL_FEATURE_FLASH_FLEX_NVM_RESOURCE_CMD_ADDRESS_ALIGMENT (0) -/* @brief FlexNVM Program check command address alignment. */ -#define FSL_FEATURE_FLASH_FLEX_NVM_CHECK_CMD_ADDRESS_ALIGMENT (0) -/* @brief FlexNVM partition code 0000 mapping to data flash size in bytes (0xFFFFFFFF = reserved). */ -#define FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_0000 (0xFFFFFFFF) -/* @brief FlexNVM partition code 0001 mapping to data flash size in bytes (0xFFFFFFFF = reserved). */ -#define FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_0001 (0xFFFFFFFF) -/* @brief FlexNVM partition code 0010 mapping to data flash size in bytes (0xFFFFFFFF = reserved). */ -#define FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_0010 (0xFFFFFFFF) -/* @brief FlexNVM partition code 0011 mapping to data flash size in bytes (0xFFFFFFFF = reserved). */ -#define FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_0011 (0xFFFFFFFF) -/* @brief FlexNVM partition code 0100 mapping to data flash size in bytes (0xFFFFFFFF = reserved). */ -#define FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_0100 (0xFFFFFFFF) -/* @brief FlexNVM partition code 0101 mapping to data flash size in bytes (0xFFFFFFFF = reserved). */ -#define FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_0101 (0xFFFFFFFF) -/* @brief FlexNVM partition code 0110 mapping to data flash size in bytes (0xFFFFFFFF = reserved). */ -#define FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_0110 (0xFFFFFFFF) -/* @brief FlexNVM partition code 0111 mapping to data flash size in bytes (0xFFFFFFFF = reserved). */ -#define FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_0111 (0xFFFFFFFF) -/* @brief FlexNVM partition code 1000 mapping to data flash size in bytes (0xFFFFFFFF = reserved). */ -#define FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_1000 (0xFFFFFFFF) -/* @brief FlexNVM partition code 1001 mapping to data flash size in bytes (0xFFFFFFFF = reserved). */ -#define FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_1001 (0xFFFFFFFF) -/* @brief FlexNVM partition code 1010 mapping to data flash size in bytes (0xFFFFFFFF = reserved). */ -#define FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_1010 (0xFFFFFFFF) -/* @brief FlexNVM partition code 1011 mapping to data flash size in bytes (0xFFFFFFFF = reserved). */ -#define FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_1011 (0xFFFFFFFF) -/* @brief FlexNVM partition code 1100 mapping to data flash size in bytes (0xFFFFFFFF = reserved). */ -#define FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_1100 (0xFFFFFFFF) -/* @brief FlexNVM partition code 1101 mapping to data flash size in bytes (0xFFFFFFFF = reserved). */ -#define FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_1101 (0xFFFFFFFF) -/* @brief FlexNVM partition code 1110 mapping to data flash size in bytes (0xFFFFFFFF = reserved). */ -#define FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_1110 (0xFFFFFFFF) -/* @brief FlexNVM partition code 1111 mapping to data flash size in bytes (0xFFFFFFFF = reserved). */ -#define FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_1111 (0xFFFFFFFF) -/* @brief Emulated eeprom size code 0000 mapping to emulated eeprom size in bytes (0xFFFF = reserved). */ -#define FSL_FEATURE_FLASH_FLEX_NVM_EEPROM_SIZE_FOR_EEESIZE_0000 (0xFFFF) -/* @brief Emulated eeprom size code 0001 mapping to emulated eeprom size in bytes (0xFFFF = reserved). */ -#define FSL_FEATURE_FLASH_FLEX_NVM_EEPROM_SIZE_FOR_EEESIZE_0001 (0xFFFF) -/* @brief Emulated eeprom size code 0010 mapping to emulated eeprom size in bytes (0xFFFF = reserved). */ -#define FSL_FEATURE_FLASH_FLEX_NVM_EEPROM_SIZE_FOR_EEESIZE_0010 (0x1000) -/* @brief Emulated eeprom size code 0011 mapping to emulated eeprom size in bytes (0xFFFF = reserved). */ -#define FSL_FEATURE_FLASH_FLEX_NVM_EEPROM_SIZE_FOR_EEESIZE_0011 (0x0800) -/* @brief Emulated eeprom size code 0100 mapping to emulated eeprom size in bytes (0xFFFF = reserved). */ -#define FSL_FEATURE_FLASH_FLEX_NVM_EEPROM_SIZE_FOR_EEESIZE_0100 (0x0400) -/* @brief Emulated eeprom size code 0101 mapping to emulated eeprom size in bytes (0xFFFF = reserved). */ -#define FSL_FEATURE_FLASH_FLEX_NVM_EEPROM_SIZE_FOR_EEESIZE_0101 (0x0200) -/* @brief Emulated eeprom size code 0110 mapping to emulated eeprom size in bytes (0xFFFF = reserved). */ -#define FSL_FEATURE_FLASH_FLEX_NVM_EEPROM_SIZE_FOR_EEESIZE_0110 (0x0100) -/* @brief Emulated eeprom size code 0111 mapping to emulated eeprom size in bytes (0xFFFF = reserved). */ -#define FSL_FEATURE_FLASH_FLEX_NVM_EEPROM_SIZE_FOR_EEESIZE_0111 (0x0080) -/* @brief Emulated eeprom size code 1000 mapping to emulated eeprom size in bytes (0xFFFF = reserved). */ -#define FSL_FEATURE_FLASH_FLEX_NVM_EEPROM_SIZE_FOR_EEESIZE_1000 (0x0040) -/* @brief Emulated eeprom size code 1001 mapping to emulated eeprom size in bytes (0xFFFF = reserved). */ -#define FSL_FEATURE_FLASH_FLEX_NVM_EEPROM_SIZE_FOR_EEESIZE_1001 (0x0020) -/* @brief Emulated eeprom size code 1010 mapping to emulated eeprom size in bytes (0xFFFF = reserved). */ -#define FSL_FEATURE_FLASH_FLEX_NVM_EEPROM_SIZE_FOR_EEESIZE_1010 (0xFFFF) -/* @brief Emulated eeprom size code 1011 mapping to emulated eeprom size in bytes (0xFFFF = reserved). */ -#define FSL_FEATURE_FLASH_FLEX_NVM_EEPROM_SIZE_FOR_EEESIZE_1011 (0xFFFF) -/* @brief Emulated eeprom size code 1100 mapping to emulated eeprom size in bytes (0xFFFF = reserved). */ -#define FSL_FEATURE_FLASH_FLEX_NVM_EEPROM_SIZE_FOR_EEESIZE_1100 (0xFFFF) -/* @brief Emulated eeprom size code 1101 mapping to emulated eeprom size in bytes (0xFFFF = reserved). */ -#define FSL_FEATURE_FLASH_FLEX_NVM_EEPROM_SIZE_FOR_EEESIZE_1101 (0xFFFF) -/* @brief Emulated eeprom size code 1110 mapping to emulated eeprom size in bytes (0xFFFF = reserved). */ -#define FSL_FEATURE_FLASH_FLEX_NVM_EEPROM_SIZE_FOR_EEESIZE_1110 (0xFFFF) -/* @brief Emulated eeprom size code 1111 mapping to emulated eeprom size in bytes (0xFFFF = reserved). */ -#define FSL_FEATURE_FLASH_FLEX_NVM_EEPROM_SIZE_FOR_EEESIZE_1111 (0x0000) - -/* FTM module features */ - -/* @brief Number of channels. */ -#define FSL_FEATURE_FTM_CHANNEL_COUNTn(x) \ - ((x) == FTM0 ? (8) : \ - ((x) == FTM1 ? (2) : \ - ((x) == FTM2 ? (2) : \ - ((x) == FTM3 ? (8) : (-1))))) -/* @brief Has counter reset by the selected input capture event (register bits C0SC[ICRST], C1SC[ICRST], ...). */ -#define FSL_FEATURE_FTM_HAS_COUNTER_RESET_BY_CAPTURE_EVENT (0) -/* @brief Has extended deadtime value. */ -#define FSL_FEATURE_FTM_HAS_EXTENDED_DEADTIME_VALUE (0) -/* @brief Enable pwm output for the module. */ -#define FSL_FEATURE_FTM_HAS_ENABLE_PWM_OUTPUT (0) -/* @brief Has half-cycle reload for the module. */ -#define FSL_FEATURE_FTM_HAS_HALFCYCLE_RELOAD (0) -/* @brief Has reload interrupt. */ -#define FSL_FEATURE_FTM_HAS_RELOAD_INTERRUPT (0) -/* @brief Has reload initialization trigger. */ -#define FSL_FEATURE_FTM_HAS_RELOAD_INITIALIZATION_TRIGGER (0) - -/* GPIO module features */ - -/* @brief Has fast (single cycle) access capability via a dedicated memory region. */ -#define FSL_FEATURE_GPIO_HAS_FAST_GPIO (0) -/* @brief Has port input disable register (PIDR). */ -#define FSL_FEATURE_GPIO_HAS_INPUT_DISABLE (0) -/* @brief Has dedicated interrupt vector. */ -#define FSL_FEATURE_GPIO_HAS_PORT_INTERRUPT_VECTOR (1) - -/* I2C module features */ - -/* @brief Has System Management Bus support (registers SMB, A2, SLTL and SLTH). */ -#define FSL_FEATURE_I2C_HAS_SMBUS (1) -/* @brief Maximum supported baud rate in kilobit per second. */ -#define FSL_FEATURE_I2C_MAX_BAUD_KBPS (400) -/* @brief Is affected by errata with ID 6070 (repeat start cannot be generated if the F[MULT] bit field is set to a non-zero value). */ -#define FSL_FEATURE_I2C_HAS_ERRATA_6070 (0) -/* @brief Has DMA support (register bit C1[DMAEN]). */ -#define FSL_FEATURE_I2C_HAS_DMA_SUPPORT (1) -/* @brief Has I2C bus start and stop detection (register bits FLT[SSIE], FLT[STARTF] and FLT[STOPF]). */ -#define FSL_FEATURE_I2C_HAS_START_STOP_DETECT (1) -/* @brief Has I2C bus stop detection (register bits FLT[STOPIE] and FLT[STOPF]). */ -#define FSL_FEATURE_I2C_HAS_STOP_DETECT (0) -/* @brief Has I2C bus stop hold off (register bit FLT[SHEN]). */ -#define FSL_FEATURE_I2C_HAS_STOP_HOLD_OFF (1) -/* @brief Maximum width of the glitch filter in number of bus clocks. */ -#define FSL_FEATURE_I2C_MAX_GLITCH_FILTER_WIDTH (15) -/* @brief Has control of the drive capability of the I2C pins. */ -#define FSL_FEATURE_I2C_HAS_HIGH_DRIVE_SELECTION (1) -/* @brief Has double buffering support (register S2). */ -#define FSL_FEATURE_I2C_HAS_DOUBLE_BUFFERING (0) -/* @brief Has double buffer enable. */ -#define FSL_FEATURE_I2C_HAS_DOUBLE_BUFFER_ENABLE (0) - -/* SAI module features */ - -/* @brief Receive/transmit FIFO size in item count (register bit fields TCSR[FRDE], TCSR[FRIE], TCSR[FRF], TCR1[TFW], RCSR[FRDE], RCSR[FRIE], RCSR[FRF], RCR1[RFW], registers TFRn, RFRn). */ -#define FSL_FEATURE_SAI_FIFO_COUNT (8) -/* @brief Receive/transmit channel number (register bit fields TCR3[TCE], RCR3[RCE], registers TDRn and RDRn). */ -#define FSL_FEATURE_SAI_CHANNEL_COUNT (2) -/* @brief Maximum words per frame (register bit fields TCR3[WDFL], TCR4[FRSZ], TMR[TWM], RCR3[WDFL], RCR4[FRSZ], RMR[RWM]). */ -#define FSL_FEATURE_SAI_MAX_WORDS_PER_FRAME (32) -/* @brief Has support of combining multiple data channel FIFOs into single channel FIFO (register bit fields TCR3[CFR], TCR4[FCOMB], TFR0[WCP], TFR1[WCP], RCR3[CFR], RCR4[FCOMB], RFR0[RCP], RFR1[RCP]). */ -#define FSL_FEATURE_SAI_HAS_FIFO_COMBINE_MODE (0) -/* @brief Has packing of 8-bit and 16-bit data into each 32-bit FIFO word (register bit fields TCR4[FPACK], RCR4[FPACK]). */ -#define FSL_FEATURE_SAI_HAS_FIFO_PACKING (0) -/* @brief Configures when the SAI will continue transmitting after a FIFO error has been detected (register bit fields TCR4[FCONT], RCR4[FCONT]). */ -#define FSL_FEATURE_SAI_HAS_FIFO_FUNCTION_AFTER_ERROR (0) -/* @brief Configures if the frame sync is generated internally, a frame sync is only generated when the FIFO warning flag is clear or continuously (register bit fields TCR4[ONDEM], RCR4[ONDEM]). */ -#define FSL_FEATURE_SAI_HAS_ON_DEMAND_MODE (0) -/* @brief Simplified bit clock source and asynchronous/synchronous mode selection (register bit fields TCR2[CLKMODE], RCR2[CLKMODE]), in comparison with the exclusively implemented TCR2[SYNC,BCS,BCI,MSEL], RCR2[SYNC,BCS,BCI,MSEL]. */ -#define FSL_FEATURE_SAI_HAS_CLOCKING_MODE (0) -/* @brief Has register for configuration of the MCLK divide ratio (register bit fields MDR[FRACT], MDR[DIVIDE]). */ -#define FSL_FEATURE_SAI_HAS_MCLKDIV_REGISTER (1) -/* @brief Ihe interrupt source number */ -#define FSL_FEATURE_SAI_INT_SOURCE_NUM (2) -/* @brief Has register of MCR. */ -#define FSL_FEATURE_SAI_HAS_MCR (1) -/* @brief Has register of MDR */ -#define FSL_FEATURE_SAI_HAS_MDR (1) - -/* LLWU module features */ - -/* @brief Maximum number of pins (maximal index plus one) connected to LLWU device. */ -#define FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN (16) -/* @brief Has pins 8-15 connected to LLWU device. */ -#define FSL_FEATURE_LLWU_EXTERNAL_PIN_GROUP2 (1) -/* @brief Maximum number of internal modules connected to LLWU device. */ -#define FSL_FEATURE_LLWU_HAS_INTERNAL_MODULE (8) -/* @brief Number of digital filters. */ -#define FSL_FEATURE_LLWU_HAS_PIN_FILTER (2) -/* @brief Has MF register. */ -#define FSL_FEATURE_LLWU_HAS_MF (0) -/* @brief Has PF register. */ -#define FSL_FEATURE_LLWU_HAS_PF (0) -/* @brief Has possibility to enable reset in low leakage power mode and enable digital filter for RESET pin (register LLWU_RST). */ -#define FSL_FEATURE_LLWU_HAS_RESET_ENABLE (1) -/* @brief Has no internal module wakeup flag register. */ -#define FSL_FEATURE_LLWU_HAS_NO_INTERNAL_MODULE_WAKEUP_FLAG_REG (0) -/* @brief Has external pin 0 connected to LLWU device. */ -#define FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN0 (1) -/* @brief Index of port of external pin. */ -#define FSL_FEATURE_LLWU_PIN0_GPIO_IDX (GPIOE_IDX) -/* @brief Number of external pin port on specified port. */ -#define FSL_FEATURE_LLWU_PIN0_GPIO_PIN (1) -/* @brief Has external pin 1 connected to LLWU device. */ -#define FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN1 (1) -/* @brief Index of port of external pin. */ -#define FSL_FEATURE_LLWU_PIN1_GPIO_IDX (GPIOE_IDX) -/* @brief Number of external pin port on specified port. */ -#define FSL_FEATURE_LLWU_PIN1_GPIO_PIN (2) -/* @brief Has external pin 2 connected to LLWU device. */ -#define FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN2 (1) -/* @brief Index of port of external pin. */ -#define FSL_FEATURE_LLWU_PIN2_GPIO_IDX (GPIOE_IDX) -/* @brief Number of external pin port on specified port. */ -#define FSL_FEATURE_LLWU_PIN2_GPIO_PIN (4) -/* @brief Has external pin 3 connected to LLWU device. */ -#define FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN3 (1) -/* @brief Index of port of external pin. */ -#define FSL_FEATURE_LLWU_PIN3_GPIO_IDX (GPIOA_IDX) -/* @brief Number of external pin port on specified port. */ -#define FSL_FEATURE_LLWU_PIN3_GPIO_PIN (4) -/* @brief Has external pin 4 connected to LLWU device. */ -#define FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN4 (1) -/* @brief Index of port of external pin. */ -#define FSL_FEATURE_LLWU_PIN4_GPIO_IDX (GPIOA_IDX) -/* @brief Number of external pin port on specified port. */ -#define FSL_FEATURE_LLWU_PIN4_GPIO_PIN (13) -/* @brief Has external pin 5 connected to LLWU device. */ -#define FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN5 (1) -/* @brief Index of port of external pin. */ -#define FSL_FEATURE_LLWU_PIN5_GPIO_IDX (GPIOB_IDX) -/* @brief Number of external pin port on specified port. */ -#define FSL_FEATURE_LLWU_PIN5_GPIO_PIN (0) -/* @brief Has external pin 6 connected to LLWU device. */ -#define FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN6 (1) -/* @brief Index of port of external pin. */ -#define FSL_FEATURE_LLWU_PIN6_GPIO_IDX (GPIOC_IDX) -/* @brief Number of external pin port on specified port. */ -#define FSL_FEATURE_LLWU_PIN6_GPIO_PIN (1) -/* @brief Has external pin 7 connected to LLWU device. */ -#define FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN7 (1) -/* @brief Index of port of external pin. */ -#define FSL_FEATURE_LLWU_PIN7_GPIO_IDX (GPIOC_IDX) -/* @brief Number of external pin port on specified port. */ -#define FSL_FEATURE_LLWU_PIN7_GPIO_PIN (3) -/* @brief Has external pin 8 connected to LLWU device. */ -#define FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN8 (1) -/* @brief Index of port of external pin. */ -#define FSL_FEATURE_LLWU_PIN8_GPIO_IDX (GPIOC_IDX) -/* @brief Number of external pin port on specified port. */ -#define FSL_FEATURE_LLWU_PIN8_GPIO_PIN (4) -/* @brief Has external pin 9 connected to LLWU device. */ -#define FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN9 (1) -/* @brief Index of port of external pin. */ -#define FSL_FEATURE_LLWU_PIN9_GPIO_IDX (GPIOC_IDX) -/* @brief Number of external pin port on specified port. */ -#define FSL_FEATURE_LLWU_PIN9_GPIO_PIN (5) -/* @brief Has external pin 10 connected to LLWU device. */ -#define FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN10 (1) -/* @brief Index of port of external pin. */ -#define FSL_FEATURE_LLWU_PIN10_GPIO_IDX (GPIOC_IDX) -/* @brief Number of external pin port on specified port. */ -#define FSL_FEATURE_LLWU_PIN10_GPIO_PIN (6) -/* @brief Has external pin 11 connected to LLWU device. */ -#define FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN11 (1) -/* @brief Index of port of external pin. */ -#define FSL_FEATURE_LLWU_PIN11_GPIO_IDX (GPIOC_IDX) -/* @brief Number of external pin port on specified port. */ -#define FSL_FEATURE_LLWU_PIN11_GPIO_PIN (11) -/* @brief Has external pin 12 connected to LLWU device. */ -#define FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN12 (1) -/* @brief Index of port of external pin. */ -#define FSL_FEATURE_LLWU_PIN12_GPIO_IDX (GPIOD_IDX) -/* @brief Number of external pin port on specified port. */ -#define FSL_FEATURE_LLWU_PIN12_GPIO_PIN (0) -/* @brief Has external pin 13 connected to LLWU device. */ -#define FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN13 (1) -/* @brief Index of port of external pin. */ -#define FSL_FEATURE_LLWU_PIN13_GPIO_IDX (GPIOD_IDX) -/* @brief Number of external pin port on specified port. */ -#define FSL_FEATURE_LLWU_PIN13_GPIO_PIN (2) -/* @brief Has external pin 14 connected to LLWU device. */ -#define FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN14 (1) -/* @brief Index of port of external pin. */ -#define FSL_FEATURE_LLWU_PIN14_GPIO_IDX (GPIOD_IDX) -/* @brief Number of external pin port on specified port. */ -#define FSL_FEATURE_LLWU_PIN14_GPIO_PIN (4) -/* @brief Has external pin 15 connected to LLWU device. */ -#define FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN15 (1) -/* @brief Index of port of external pin. */ -#define FSL_FEATURE_LLWU_PIN15_GPIO_IDX (GPIOD_IDX) -/* @brief Number of external pin port on specified port. */ -#define FSL_FEATURE_LLWU_PIN15_GPIO_PIN (6) -/* @brief Has external pin 16 connected to LLWU device. */ -#define FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN16 (0) -/* @brief Index of port of external pin. */ -#define FSL_FEATURE_LLWU_PIN16_GPIO_IDX (0) -/* @brief Number of external pin port on specified port. */ -#define FSL_FEATURE_LLWU_PIN16_GPIO_PIN (0) -/* @brief Has external pin 17 connected to LLWU device. */ -#define FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN17 (0) -/* @brief Index of port of external pin. */ -#define FSL_FEATURE_LLWU_PIN17_GPIO_IDX (0) -/* @brief Number of external pin port on specified port. */ -#define FSL_FEATURE_LLWU_PIN17_GPIO_PIN (0) -/* @brief Has external pin 18 connected to LLWU device. */ -#define FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN18 (0) -/* @brief Index of port of external pin. */ -#define FSL_FEATURE_LLWU_PIN18_GPIO_IDX (0) -/* @brief Number of external pin port on specified port. */ -#define FSL_FEATURE_LLWU_PIN18_GPIO_PIN (0) -/* @brief Has external pin 19 connected to LLWU device. */ -#define FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN19 (0) -/* @brief Index of port of external pin. */ -#define FSL_FEATURE_LLWU_PIN19_GPIO_IDX (0) -/* @brief Number of external pin port on specified port. */ -#define FSL_FEATURE_LLWU_PIN19_GPIO_PIN (0) -/* @brief Has external pin 20 connected to LLWU device. */ -#define FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN20 (0) -/* @brief Index of port of external pin. */ -#define FSL_FEATURE_LLWU_PIN20_GPIO_IDX (0) -/* @brief Number of external pin port on specified port. */ -#define FSL_FEATURE_LLWU_PIN20_GPIO_PIN (0) -/* @brief Has external pin 21 connected to LLWU device. */ -#define FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN21 (0) -/* @brief Index of port of external pin. */ -#define FSL_FEATURE_LLWU_PIN21_GPIO_IDX (0) -/* @brief Number of external pin port on specified port. */ -#define FSL_FEATURE_LLWU_PIN21_GPIO_PIN (0) -/* @brief Has external pin 22 connected to LLWU device. */ -#define FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN22 (0) -/* @brief Index of port of external pin. */ -#define FSL_FEATURE_LLWU_PIN22_GPIO_IDX (0) -/* @brief Number of external pin port on specified port. */ -#define FSL_FEATURE_LLWU_PIN22_GPIO_PIN (0) -/* @brief Has external pin 23 connected to LLWU device. */ -#define FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN23 (0) -/* @brief Index of port of external pin. */ -#define FSL_FEATURE_LLWU_PIN23_GPIO_IDX (0) -/* @brief Number of external pin port on specified port. */ -#define FSL_FEATURE_LLWU_PIN23_GPIO_PIN (0) -/* @brief Has external pin 24 connected to LLWU device. */ -#define FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN24 (0) -/* @brief Index of port of external pin. */ -#define FSL_FEATURE_LLWU_PIN24_GPIO_IDX (0) -/* @brief Number of external pin port on specified port. */ -#define FSL_FEATURE_LLWU_PIN24_GPIO_PIN (0) -/* @brief Has external pin 25 connected to LLWU device. */ -#define FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN25 (0) -/* @brief Index of port of external pin. */ -#define FSL_FEATURE_LLWU_PIN25_GPIO_IDX (0) -/* @brief Number of external pin port on specified port. */ -#define FSL_FEATURE_LLWU_PIN25_GPIO_PIN (0) -/* @brief Has external pin 26 connected to LLWU device. */ -#define FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN26 (0) -/* @brief Index of port of external pin. */ -#define FSL_FEATURE_LLWU_PIN26_GPIO_IDX (0) -/* @brief Number of external pin port on specified port. */ -#define FSL_FEATURE_LLWU_PIN26_GPIO_PIN (0) -/* @brief Has external pin 27 connected to LLWU device. */ -#define FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN27 (0) -/* @brief Index of port of external pin. */ -#define FSL_FEATURE_LLWU_PIN27_GPIO_IDX (0) -/* @brief Number of external pin port on specified port. */ -#define FSL_FEATURE_LLWU_PIN27_GPIO_PIN (0) -/* @brief Has external pin 28 connected to LLWU device. */ -#define FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN28 (0) -/* @brief Index of port of external pin. */ -#define FSL_FEATURE_LLWU_PIN28_GPIO_IDX (0) -/* @brief Number of external pin port on specified port. */ -#define FSL_FEATURE_LLWU_PIN28_GPIO_PIN (0) -/* @brief Has external pin 29 connected to LLWU device. */ -#define FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN29 (0) -/* @brief Index of port of external pin. */ -#define FSL_FEATURE_LLWU_PIN29_GPIO_IDX (0) -/* @brief Number of external pin port on specified port. */ -#define FSL_FEATURE_LLWU_PIN29_GPIO_PIN (0) -/* @brief Has external pin 30 connected to LLWU device. */ -#define FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN30 (0) -/* @brief Index of port of external pin. */ -#define FSL_FEATURE_LLWU_PIN30_GPIO_IDX (0) -/* @brief Number of external pin port on specified port. */ -#define FSL_FEATURE_LLWU_PIN30_GPIO_PIN (0) -/* @brief Has external pin 31 connected to LLWU device. */ -#define FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN31 (0) -/* @brief Index of port of external pin. */ -#define FSL_FEATURE_LLWU_PIN31_GPIO_IDX (0) -/* @brief Number of external pin port on specified port. */ -#define FSL_FEATURE_LLWU_PIN31_GPIO_PIN (0) -/* @brief Has internal module 0 connected to LLWU device. */ -#define FSL_FEATURE_LLWU_HAS_INTERNAL_MODULE0 (1) -/* @brief Has internal module 1 connected to LLWU device. */ -#define FSL_FEATURE_LLWU_HAS_INTERNAL_MODULE1 (1) -/* @brief Has internal module 2 connected to LLWU device. */ -#define FSL_FEATURE_LLWU_HAS_INTERNAL_MODULE2 (1) -/* @brief Has internal module 3 connected to LLWU device. */ -#define FSL_FEATURE_LLWU_HAS_INTERNAL_MODULE3 (1) -/* @brief Has internal module 4 connected to LLWU device. */ -#define FSL_FEATURE_LLWU_HAS_INTERNAL_MODULE4 (0) -/* @brief Has internal module 5 connected to LLWU device. */ -#define FSL_FEATURE_LLWU_HAS_INTERNAL_MODULE5 (1) -/* @brief Has internal module 6 connected to LLWU device. */ -#define FSL_FEATURE_LLWU_HAS_INTERNAL_MODULE6 (0) -/* @brief Has internal module 7 connected to LLWU device. */ -#define FSL_FEATURE_LLWU_HAS_INTERNAL_MODULE7 (1) -/* @brief Has Version ID Register (LLWU_VERID). */ -#define FSL_FEATURE_LLWU_HAS_VERID (0) -/* @brief Has Parameter Register (LLWU_PARAM). */ -#define FSL_FEATURE_LLWU_HAS_PARAM (0) -/* @brief Width of registers of the LLWU. */ -#define FSL_FEATURE_LLWU_REG_BITWIDTH (8) -/* @brief Has DMA Enable register (LLWU_DE). */ -#define FSL_FEATURE_LLWU_HAS_DMA_ENABLE_REG (0) - -/* LPTMR module features */ - -/* @brief Has shared interrupt handler with another LPTMR module. */ -#define FSL_FEATURE_LPTMR_HAS_SHARED_IRQ_HANDLER (0) -/* @brief Whether LPTMR counter is 32 bits width. */ -#define FSL_FEATURE_LPTMR_CNR_WIDTH_IS_32B (0) -/* @brief Has timer DMA request enable (register bit CSR[TDRE]). */ -#define FSL_FEATURE_LPTMR_HAS_CSR_TDRE (0) - -/* MCG module features */ - -/* @brief PRDIV base value (divider of register bit field [PRDIV] zero value). */ -#define FSL_FEATURE_MCG_PLL_PRDIV_BASE (1) -/* @brief Maximum PLL external reference divider value (max. value of register bit field C5[PRVDIV]). */ -#define FSL_FEATURE_MCG_PLL_PRDIV_MAX (24) -/* @brief VCO divider base value (multiply factor of register bit field C6[VDIV] zero value). */ -#define FSL_FEATURE_MCG_PLL_VDIV_BASE (24) -/* @brief PLL reference clock low range. OSCCLK/PLL_R. */ -#define FSL_FEATURE_MCG_PLL_REF_MIN (2000000) -/* @brief PLL reference clock high range. OSCCLK/PLL_R. */ -#define FSL_FEATURE_MCG_PLL_REF_MAX (4000000) -/* @brief The PLL clock is divided by 2 before VCO divider. */ -#define FSL_FEATURE_MCG_HAS_PLL_INTERNAL_DIV (0) -/* @brief FRDIV supports 1280. */ -#define FSL_FEATURE_MCG_FRDIV_SUPPORT_1280 (1) -/* @brief FRDIV supports 1536. */ -#define FSL_FEATURE_MCG_FRDIV_SUPPORT_1536 (1) -/* @brief MCGFFCLK divider. */ -#define FSL_FEATURE_MCG_FFCLK_DIV (1) -/* @brief Is PLL clock divided by 2 before MCG PLL/FLL clock selection in the SIM module. */ -#define FSL_FEATURE_MCG_HAS_PLL_EXTRA_DIV (0) -/* @brief Has 32kHz RTC external reference clock (register bits C8[LOCS1], C8[CME1], C8[LOCRE1] and RTC module are present). */ -#define FSL_FEATURE_MCG_HAS_RTC_32K (1) -/* @brief Has PLL1 external reference clock (registers C10, C11, C12, S2). */ -#define FSL_FEATURE_MCG_HAS_PLL1 (0) -/* @brief Has 48MHz internal oscillator. */ -#define FSL_FEATURE_MCG_HAS_IRC_48M (1) -/* @brief Has OSC1 external oscillator (registers C10, C11, C12, S2). */ -#define FSL_FEATURE_MCG_HAS_OSC1 (0) -/* @brief Has fast internal reference clock fine trim (register bit C2[FCFTRIM]). */ -#define FSL_FEATURE_MCG_HAS_FCFTRIM (1) -/* @brief Has PLL loss of lock reset (register bit C8[LOLRE]). */ -#define FSL_FEATURE_MCG_HAS_LOLRE (1) -/* @brief Has MCG OSC clock selection (register bit C7[OSCSEL]). */ -#define FSL_FEATURE_MCG_USE_OSCSEL (1) -/* @brief Has PLL external reference selection (register bits C5[PLLREFSEL0] and C11[PLLREFSEL1]). */ -#define FSL_FEATURE_MCG_USE_PLLREFSEL (0) -/* @brief TBD */ -#define FSL_FEATURE_MCG_USE_SYSTEM_CLOCK (0) -/* @brief Has phase-locked loop (PLL) (register C5 and bits C6[VDIV], C6[PLLS], C6[LOLIE0], S[PLLST], S[LOCK0], S[LOLS0]). */ -#define FSL_FEATURE_MCG_HAS_PLL (1) -/* @brief Has phase-locked loop (PLL) PRDIV (register C5[PRDIV]. */ -#define FSL_FEATURE_MCG_HAS_PLL_PRDIV (1) -/* @brief Has phase-locked loop (PLL) VDIV (register C6[VDIV]. */ -#define FSL_FEATURE_MCG_HAS_PLL_VDIV (1) -/* @brief PLL/OSC related register bit fields have PLL/OSC index in their name. */ -#define FSL_FEATURE_MCG_HAS_PLL_OSC_INDEX (0) -/* @brief Has frequency-locked loop (FLL) (register ATCVH, ATCVL and bits C1[IREFS], C1[FRDIV]). */ -#define FSL_FEATURE_MCG_HAS_FLL (1) -/* @brief Has PLL external to MCG (C9[PLL_CME], C9[PLL_LOCRE], C9[EXT_PLL_LOCS]). */ -#define FSL_FEATURE_MCG_HAS_EXTERNAL_PLL (0) -/* @brief Has crystal oscillator or external reference clock low power controls (register bits C2[HGO], C2[RANGE]). */ -#define FSL_FEATURE_MCG_HAS_EXT_REF_LOW_POWER_CONTROL (1) -/* @brief Has PLL/FLL selection as MCG output (register bit C6[PLLS]). */ -#define FSL_FEATURE_MCG_HAS_PLL_FLL_SELECTION (1) -/* @brief Has PLL output selection (PLL0/PLL1, PLL/external PLL) (register bit C11[PLLCS]). */ -#define FSL_FEATURE_MCG_HAS_PLL_OUTPUT_SELECTION (0) -/* @brief Has automatic trim machine (registers ATCVH, ATCVL and bits SC[ATMF], SC[ATMS], SC[ATME]). */ -#define FSL_FEATURE_MCG_HAS_AUTO_TRIM_MACHINE (1) -/* @brief Has external clock monitor (register bit C6[CME]). */ -#define FSL_FEATURE_MCG_HAS_EXTERNAL_CLOCK_MONITOR (1) -/* @brief Has low frequency internal reference clock (IRC) (registers LTRIMRNG, LFRIM, LSTRIM and bit MC[LIRC_DIV2]). */ -#define FSL_FEATURE_MCG_HAS_LOW_FREQ_IRC (0) -/* @brief Has high frequency internal reference clock (IRC) (registers HCTRIM, HTTRIM, HFTRIM and bit MC[HIRCEN]). */ -#define FSL_FEATURE_MCG_HAS_HIGH_FREQ_IRC (0) -/* @brief Has PEI mode or PBI mode. */ -#define FSL_FEATURE_MCG_HAS_PLL_INTERNAL_MODE (0) -/* @brief Reset clock mode is BLPI. */ -#define FSL_FEATURE_MCG_RESET_IS_BLPI (0) - -/* interrupt module features */ - -/* @brief Lowest interrupt request number. */ -#define FSL_FEATURE_INTERRUPT_IRQ_MIN (-14) -/* @brief Highest interrupt request number. */ -#define FSL_FEATURE_INTERRUPT_IRQ_MAX (85) - -/* OSC module features */ - -/* @brief Has OSC1 external oscillator. */ -#define FSL_FEATURE_OSC_HAS_OSC1 (0) -/* @brief Has OSC0 external oscillator. */ -#define FSL_FEATURE_OSC_HAS_OSC0 (0) -/* @brief Has OSC external oscillator (without index). */ -#define FSL_FEATURE_OSC_HAS_OSC (1) -/* @brief Number of OSC external oscillators. */ -#define FSL_FEATURE_OSC_OSC_COUNT (1) -/* @brief Has external reference clock divider (register bit field DIV[ERPS]). */ -#define FSL_FEATURE_OSC_HAS_EXT_REF_CLOCK_DIVIDER (0) - -/* PDB module features */ - -/* @brief Define the count of supporting ADC pre-trigger for each channel. */ -#define FSL_FEATURE_PDB_ADC_PRE_CHANNEL_COUNT (2) -/* @brief Has DAC support. */ -#define FSL_FEATURE_PDB_HAS_DAC (1) -/* @brief Has shared interrupt handler (has not individual interrupt handler for each channel). */ -#define FSL_FEATURE_PDB_HAS_SHARED_IRQ_HANDLER (0) - -/* PIT module features */ - -/* @brief Number of channels (related to number of registers LDVALn, CVALn, TCTRLn, TFLGn). */ -#define FSL_FEATURE_PIT_TIMER_COUNT (4) -/* @brief Has lifetime timer (related to existence of registers LTMR64L and LTMR64H). */ -#define FSL_FEATURE_PIT_HAS_LIFETIME_TIMER (0) -/* @brief Has chain mode (related to existence of register bit field TCTRLn[CHN]). */ -#define FSL_FEATURE_PIT_HAS_CHAIN_MODE (1) -/* @brief Has shared interrupt handler (has not individual interrupt handler for each channel). */ -#define FSL_FEATURE_PIT_HAS_SHARED_IRQ_HANDLER (0) - -/* PMC module features */ - -/* @brief Has Bandgap Enable In VLPx Operation support. */ -#define FSL_FEATURE_PMC_HAS_BGEN (1) -/* @brief Has Bandgap Buffer Enable. */ -#define FSL_FEATURE_PMC_HAS_BGBE (1) -/* @brief Has Bandgap Buffer Drive Select. */ -#define FSL_FEATURE_PMC_HAS_BGBDS (0) -/* @brief Has Low-Voltage Detect Voltage Select support. */ -#define FSL_FEATURE_PMC_HAS_LVDV (1) -/* @brief Has Low-Voltage Warning Voltage Select support. */ -#define FSL_FEATURE_PMC_HAS_LVWV (1) -/* @brief Has LPO. */ -#define FSL_FEATURE_PMC_HAS_LPO (0) -/* @brief Has VLPx option PMC_REGSC[VLPO]. */ -#define FSL_FEATURE_PMC_HAS_VLPO (0) -/* @brief Has acknowledge isolation support. */ -#define FSL_FEATURE_PMC_HAS_ACKISO (1) -/* @brief Has Regulator In Full Performance Mode Status Bit PMC_REGSC[REGFPM]. */ -#define FSL_FEATURE_PMC_HAS_REGFPM (0) -/* @brief Has Regulator In Run Regulation Status Bit PMC_REGSC[REGONS]. */ -#define FSL_FEATURE_PMC_HAS_REGONS (1) -/* @brief Has PMC_HVDSC1. */ -#define FSL_FEATURE_PMC_HAS_HVDSC1 (0) -/* @brief Has PMC_PARAM. */ -#define FSL_FEATURE_PMC_HAS_PARAM (0) -/* @brief Has PMC_VERID. */ -#define FSL_FEATURE_PMC_HAS_VERID (0) - -/* PORT module features */ - -/* @brief Has control lock (register bit PCR[LK]). */ -#define FSL_FEATURE_PORT_HAS_PIN_CONTROL_LOCK (1) -/* @brief Has open drain control (register bit PCR[ODE]). */ -#define FSL_FEATURE_PORT_HAS_OPEN_DRAIN (1) -/* @brief Has digital filter (registers DFER, DFCR and DFWR). */ -#define FSL_FEATURE_PORT_HAS_DIGITAL_FILTER (1) -/* @brief Has DMA request (register bit field PCR[IRQC] values). */ -#define FSL_FEATURE_PORT_HAS_DMA_REQUEST (1) -/* @brief Has pull resistor selection available. */ -#define FSL_FEATURE_PORT_HAS_PULL_SELECTION (1) -/* @brief Has pull resistor enable (register bit PCR[PE]). */ -#define FSL_FEATURE_PORT_HAS_PULL_ENABLE (1) -/* @brief Has slew rate control (register bit PCR[SRE]). */ -#define FSL_FEATURE_PORT_HAS_SLEW_RATE (1) -/* @brief Has passive filter (register bit field PCR[PFE]). */ -#define FSL_FEATURE_PORT_HAS_PASSIVE_FILTER (1) -/* @brief Has drive strength control (register bit PCR[DSE]). */ -#define FSL_FEATURE_PORT_HAS_DRIVE_STRENGTH (1) -/* @brief Has separate drive strength register (HDRVE). */ -#define FSL_FEATURE_PORT_HAS_DRIVE_STRENGTH_REGISTER (0) -/* @brief Has glitch filter (register IOFLT). */ -#define FSL_FEATURE_PORT_HAS_GLITCH_FILTER (0) -/* @brief Defines width of PCR[MUX] field. */ -#define FSL_FEATURE_PORT_PCR_MUX_WIDTH (3) -/* @brief Has dedicated interrupt vector. */ -#define FSL_FEATURE_PORT_HAS_INTERRUPT_VECTOR (1) -/* @brief Has multiple pin IRQ configuration (register GICLR and GICHR). */ -#define FSL_FEATURE_PORT_HAS_MULTIPLE_IRQ_CONFIG (0) -/* @brief Defines whether PCR[IRQC] bit-field has flag states. */ -#define FSL_FEATURE_PORT_HAS_IRQC_FLAG (0) -/* @brief Defines whether PCR[IRQC] bit-field has trigger states. */ -#define FSL_FEATURE_PORT_HAS_IRQC_TRIGGER (0) - -/* RCM module features */ - -/* @brief Has Loss-of-Lock Reset support. */ -#define FSL_FEATURE_RCM_HAS_LOL (1) -/* @brief Has Loss-of-Clock Reset support. */ -#define FSL_FEATURE_RCM_HAS_LOC (1) -/* @brief Has JTAG generated Reset support. */ -#define FSL_FEATURE_RCM_HAS_JTAG (1) -/* @brief Has EzPort generated Reset support. */ -#define FSL_FEATURE_RCM_HAS_EZPORT (1) -/* @brief Has bit-field indicating EZP_MS_B pin state during last reset. */ -#define FSL_FEATURE_RCM_HAS_EZPMS (1) -/* @brief Has boot ROM configuration, MR[BOOTROM], FM[FORCEROM] */ -#define FSL_FEATURE_RCM_HAS_BOOTROM (0) -/* @brief Has sticky system reset status register RCM_SSRS0 and RCM_SSRS1. */ -#define FSL_FEATURE_RCM_HAS_SSRS (0) -/* @brief Has Version ID Register (RCM_VERID). */ -#define FSL_FEATURE_RCM_HAS_VERID (0) -/* @brief Has Parameter Register (RCM_PARAM). */ -#define FSL_FEATURE_RCM_HAS_PARAM (0) -/* @brief Has Reset Interrupt Enable Register RCM_SRIE. */ -#define FSL_FEATURE_RCM_HAS_SRIE (0) -/* @brief Width of registers of the RCM. */ -#define FSL_FEATURE_RCM_REG_WIDTH (8) -/* @brief Has Core 1 generated Reset support RCM_SRS[CORE1] */ -#define FSL_FEATURE_RCM_HAS_CORE1 (0) -/* @brief Has MDM-AP system reset support RCM_SRS1[MDM_AP] */ -#define FSL_FEATURE_RCM_HAS_MDM_AP (1) -/* @brief Has wakeup reset feature. Register bit SRS[WAKEUP]. */ -#define FSL_FEATURE_RCM_HAS_WAKEUP (1) - -/* RTC module features */ - -/* @brief Has wakeup pin. */ -#define FSL_FEATURE_RTC_HAS_WAKEUP_PIN (1) -/* @brief Has wakeup pin selection (bit field CR[WPS]). */ -#define FSL_FEATURE_RTC_HAS_WAKEUP_PIN_SELECTION (1) -/* @brief Has low power features (registers MER, MCLR and MCHR). */ -#define FSL_FEATURE_RTC_HAS_MONOTONIC (0) -/* @brief Has read/write access control (registers WAR and RAR). */ -#define FSL_FEATURE_RTC_HAS_ACCESS_CONTROL (1) -/* @brief Has security features (registers TTSR, MER, MCLR and MCHR). */ -#define FSL_FEATURE_RTC_HAS_SECURITY (0) -/* @brief Has RTC_CLKIN available. */ -#define FSL_FEATURE_RTC_HAS_RTC_CLKIN (0) -/* @brief Has prescaler adjust for LPO. */ -#define FSL_FEATURE_RTC_HAS_LPO_ADJUST (0) -/* @brief Has Clock Pin Enable field. */ -#define FSL_FEATURE_RTC_HAS_CPE (0) -/* @brief Has Timer Seconds Interrupt Configuration field. */ -#define FSL_FEATURE_RTC_HAS_TSIC (0) -/* @brief Has OSC capacitor setting RTC_CR[SC2P ~ SC16P] */ -#define FSL_FEATURE_RTC_HAS_OSC_SCXP (1) - -/* SDHC module features */ - -/* @brief Has external DMA support (register bit VENDOR[EXTDMAEN]). */ -#define FSL_FEATURE_SDHC_HAS_EXTERNAL_DMA_SUPPORT (1) -/* @brief Has support of 3.0V voltage (register bit HTCAPBLT[VS30]). */ -#define FSL_FEATURE_SDHC_HAS_V300_SUPPORT (0) -/* @brief Has support of 1.8V voltage (register bit HTCAPBLT[VS18]). */ -#define FSL_FEATURE_SDHC_HAS_V180_SUPPORT (0) - -/* SIM module features */ - -/* @brief Has USB FS divider. */ -#define FSL_FEATURE_SIM_USBFS_USE_SPECIAL_DIVIDER (0) -/* @brief Is PLL clock divided by 2 before MCG PLL/FLL clock selection. */ -#define FSL_FEATURE_SIM_PLLCLK_USE_SPECIAL_DIVIDER (0) -/* @brief Has RAM size specification (register bit field SOPT1[RAMSIZE]). */ -#define FSL_FEATURE_SIM_OPT_HAS_RAMSIZE (1) -/* @brief Has 32k oscillator clock output (register bit SOPT1[OSC32KOUT]). */ -#define FSL_FEATURE_SIM_OPT_HAS_OSC32K_OUT (0) -/* @brief Has 32k oscillator clock selection (register bit field SOPT1[OSC32KSEL]). */ -#define FSL_FEATURE_SIM_OPT_HAS_OSC32K_SELECTION (1) -/* @brief 32k oscillator clock selection width (width of register bit field SOPT1[OSC32KSEL]). */ -#define FSL_FEATURE_SIM_OPT_OSC32K_SELECTION_WIDTH (2) -/* @brief Has RTC clock output selection (register bit SOPT2[RTCCLKOUTSEL]). */ -#define FSL_FEATURE_SIM_OPT_HAS_RTC_CLOCK_OUT_SELECTION (1) -/* @brief Has USB voltage regulator (register bits SOPT1[USBVSTBY], SOPT1[USBSSTBY], SOPT1[USBREGEN], SOPT1CFG[URWE], SOPT1CFG[UVSWE], SOPT1CFG[USSWE]). */ -#define FSL_FEATURE_SIM_OPT_HAS_USB_VOLTAGE_REGULATOR (1) -/* @brief USB has integrated PHY (register bits USBPHYCTL[USBVREGSEL], USBPHYCTL[USBVREGPD], USBPHYCTL[USB3VOUTTRG], USBPHYCTL[USBDISILIM], SOPT2[USBSLSRC], SOPT2[USBREGEN]). */ -#define FSL_FEATURE_SIM_OPT_HAS_USB_PHY (0) -/* @brief Has PTD7 pad drive strength control (register bit SOPT2[PTD7PAD]). */ -#define FSL_FEATURE_SIM_OPT_HAS_PTD7PAD (1) -/* @brief Has FlexBus security level selection (register bit SOPT2[FBSL]). */ -#define FSL_FEATURE_SIM_OPT_HAS_FBSL (1) -/* @brief Has number of FlexBus hold cycle before FlexBus can release bus (register bit SOPT6[PCR]). */ -#define FSL_FEATURE_SIM_OPT_HAS_PCR (0) -/* @brief Has number of NFC hold cycle in case of FlexBus request (register bit SOPT6[MCC]). */ -#define FSL_FEATURE_SIM_OPT_HAS_MCC (0) -/* @brief Has UART open drain enable (register bits UARTnODE, where n is a number, in register SOPT5). */ -#define FSL_FEATURE_SIM_OPT_HAS_ODE (0) -/* @brief Number of LPUART modules (number of register bits LPUARTn, where n is a number, in register SCGC5). */ -#define FSL_FEATURE_SIM_OPT_LPUART_COUNT (0) -/* @brief Number of UART modules (number of register bits UARTn, where n is a number, in register SCGC4). */ -#define FSL_FEATURE_SIM_OPT_UART_COUNT (4) -/* @brief Has UART0 open drain enable (register bit SOPT5[UART0ODE]). */ -#define FSL_FEATURE_SIM_OPT_HAS_UART0_ODE (0) -/* @brief Has UART1 open drain enable (register bit SOPT5[UART1ODE]). */ -#define FSL_FEATURE_SIM_OPT_HAS_UART1_ODE (0) -/* @brief Has UART2 open drain enable (register bit SOPT5[UART2ODE]). */ -#define FSL_FEATURE_SIM_OPT_HAS_UART2_ODE (0) -/* @brief Has LPUART0 open drain enable (register bit SOPT5[LPUART0ODE]). */ -#define FSL_FEATURE_SIM_OPT_HAS_LPUART0_ODE (0) -/* @brief Has LPUART1 open drain enable (register bit SOPT5[LPUART1ODE]). */ -#define FSL_FEATURE_SIM_OPT_HAS_LPUART1_ODE (0) -/* @brief Has CMT/UART pad drive strength control (register bit SOPT2[CMTUARTPAD]). */ -#define FSL_FEATURE_SIM_OPT_HAS_CMTUARTPAD (0) -/* @brief Has LPUART0 transmit data source selection (register bit SOPT5[LPUART0TXSRC]). */ -#define FSL_FEATURE_SIM_OPT_HAS_LPUART0_TX_SRC (0) -/* @brief Has LPUART0 receive data source selection (register bit SOPT5[LPUART0RXSRC]). */ -#define FSL_FEATURE_SIM_OPT_HAS_LPUART0_RX_SRC (0) -/* @brief Has LPUART1 transmit data source selection (register bit SOPT5[LPUART1TXSRC]). */ -#define FSL_FEATURE_SIM_OPT_HAS_LPUART1_TX_SRC (0) -/* @brief Has LPUART1 receive data source selection (register bit SOPT5[LPUART1RXSRC]). */ -#define FSL_FEATURE_SIM_OPT_HAS_LPUART1_RX_SRC (0) -/* @brief Has UART0 transmit data source selection (register bit SOPT5[UART0TXSRC]). */ -#define FSL_FEATURE_SIM_OPT_HAS_UART0_TX_SRC (1) -/* @brief UART0 transmit data source selection width (width of register bit SOPT5[UART0TXSRC]). */ -#define FSL_FEATURE_SIM_OPT_UART0_TX_SRC_WIDTH (2) -/* @brief Has UART0 receive data source selection (register bit SOPT5[UART0RXSRC]). */ -#define FSL_FEATURE_SIM_OPT_HAS_UART0_RX_SRC (1) -/* @brief UART0 receive data source selection width (width of register bit SOPT5[UART0RXSRC]). */ -#define FSL_FEATURE_SIM_OPT_UART0_RX_SRC_WIDTH (2) -/* @brief Has UART1 transmit data source selection (register bit SOPT5[UART1TXSRC]). */ -#define FSL_FEATURE_SIM_OPT_HAS_UART1_TX_SRC (1) -/* @brief Has UART1 receive data source selection (register bit SOPT5[UART1RXSRC]). */ -#define FSL_FEATURE_SIM_OPT_HAS_UART1_RX_SRC (1) -/* @brief UART1 receive data source selection width (width of register bit SOPT5[UART1RXSRC]). */ -#define FSL_FEATURE_SIM_OPT_UART1_RX_SRC_WIDTH (2) -/* @brief Has FTM module(s) configuration. */ -#define FSL_FEATURE_SIM_OPT_HAS_FTM (1) -/* @brief Number of FTM modules. */ -#define FSL_FEATURE_SIM_OPT_FTM_COUNT (4) -/* @brief Number of FTM triggers with selectable source. */ -#define FSL_FEATURE_SIM_OPT_FTM_TRIGGER_COUNT (2) -/* @brief Has FTM0 triggers source selection (register bits SOPT4[FTM0TRGnSRC], where n is a number). */ -#define FSL_FEATURE_SIM_OPT_HAS_FTM0_TRIGGER (1) -/* @brief Has FTM3 triggers source selection (register bits SOPT4[FTM3TRGnSRC], where n is a number). */ -#define FSL_FEATURE_SIM_OPT_HAS_FTM3_TRIGGER (1) -/* @brief Has FTM1 channel 0 input capture source selection (register bit SOPT4[FTM1CH0SRC]). */ -#define FSL_FEATURE_SIM_OPT_HAS_FTM1_CHANNELS (1) -/* @brief Has FTM2 channel 0 input capture source selection (register bit SOPT4[FTM2CH0SRC]). */ -#define FSL_FEATURE_SIM_OPT_HAS_FTM2_CHANNELS (1) -/* @brief Has FTM3 channel 0 input capture source selection (register bit SOPT4[FTM3CH0SRC]). */ -#define FSL_FEATURE_SIM_OPT_HAS_FTM3_CHANNELS (0) -/* @brief Has FTM2 channel 1 input capture source selection (register bit SOPT4[FTM2CH1SRC]). */ -#define FSL_FEATURE_SIM_OPT_HAS_FTM2_CHANNEL1 (0) -/* @brief Number of configurable FTM0 fault detection input (number of register bits SOPT4[FTM0FLTn], where n is a number starting from zero). */ -#define FSL_FEATURE_SIM_OPT_FTM0_FAULT_COUNT (3) -/* @brief Number of configurable FTM1 fault detection input (number of register bits SOPT4[FTM1FLTn], where n is a number starting from zero). */ -#define FSL_FEATURE_SIM_OPT_FTM1_FAULT_COUNT (1) -/* @brief Number of configurable FTM2 fault detection input (number of register bits SOPT4[FTM2FLTn], where n is a number starting from zero). */ -#define FSL_FEATURE_SIM_OPT_FTM2_FAULT_COUNT (1) -/* @brief Number of configurable FTM3 fault detection input (number of register bits SOPT4[FTM3FLTn], where n is a number starting from zero). */ -#define FSL_FEATURE_SIM_OPT_FTM3_FAULT_COUNT (1) -/* @brief Has FTM hardware trigger 0 software synchronization (register bit SOPT8[FTMnSYNCBIT], where n is a module instance index). */ -#define FSL_FEATURE_SIM_OPT_HAS_FTM_TRIGGER_SYNC (0) -/* @brief Has FTM channels output source selection (register bit SOPT8[FTMxOCHnSRC], where x is a module instance index and n is a channel index). */ -#define FSL_FEATURE_SIM_OPT_HAS_FTM_CHANNELS_OUTPUT_SRC (0) -/* @brief Has TPM module(s) configuration. */ -#define FSL_FEATURE_SIM_OPT_HAS_TPM (0) -/* @brief The highest TPM module index. */ -#define FSL_FEATURE_SIM_OPT_MAX_TPM_INDEX (0) -/* @brief Has TPM module with index 0. */ -#define FSL_FEATURE_SIM_OPT_HAS_TPM0 (0) -/* @brief Has TPM0 clock selection (register bit field SOPT4[TPM0CLKSEL]). */ -#define FSL_FEATURE_SIM_OPT_HAS_TPM0_CLK_SEL (0) -/* @brief Is TPM channels configuration in the SOPT4 (not SOPT9) register (register bits TPMnCH0SRC, TPMnCLKSEL, where n is a module instance index). */ -#define FSL_FEATURE_SIM_OPT_HAS_TPM_CHANNELS_CONFIG_IN_SOPT4_REG (0) -/* @brief Has TPM1 channel 0 input capture source selection (register bit field SOPT4[TPM1CH0SRC] or SOPT9[TPM1CH0SRC]). */ -#define FSL_FEATURE_SIM_OPT_HAS_TPM1_CH0_SRC_SELECTION (0) -/* @brief Has TPM1 clock selection (register bit field SOPT4[TPM1CLKSEL]). */ -#define FSL_FEATURE_SIM_OPT_HAS_TPM1_CLK_SEL (0) -/* @brief TPM1 channel 0 input capture source selection width (width of register bit field SOPT4[TPM1CH0SRC] or SOPT9[TPM1CH0SRC]). */ -#define FSL_FEATURE_SIM_OPT_TPM1_CH0_SRC_SELECTION_WIDTH (0) -/* @brief Has TPM2 channel 0 input capture source selection (register bit field SOPT4[TPM2CH0SRC]). */ -#define FSL_FEATURE_SIM_OPT_HAS_TPM2_CH0_SRC_SELECTION (0) -/* @brief Has TPM2 clock selection (register bit field SOPT4[TPM2CLKSEL]). */ -#define FSL_FEATURE_SIM_OPT_HAS_TPM2_CLK_SEL (0) -/* @brief Has PLL/FLL clock selection (register bit field SOPT2[PLLFLLSEL]). */ -#define FSL_FEATURE_SIM_OPT_HAS_PLL_FLL_SELECTION (1) -/* @brief PLL/FLL clock selection width (width of register bit field SOPT2[PLLFLLSEL]). */ -#define FSL_FEATURE_SIM_OPT_PLL_FLL_SELECTION_WIDTH (1) -/* @brief Has NFC clock source selection (register bit SOPT2[NFCSRC]). */ -#define FSL_FEATURE_SIM_OPT_HAS_NFCSRC (0) -/* @brief Has eSDHC clock source selection (register bit SOPT2[ESDHCSRC]). */ -#define FSL_FEATURE_SIM_OPT_HAS_ESDHCSRC (0) -/* @brief Has SDHC clock source selection (register bit SOPT2[SDHCSRC]). */ -#define FSL_FEATURE_SIM_OPT_HAS_SDHCSRC (1) -/* @brief Has LCDC clock source selection (register bits SOPT2[LCDCSRC], SOPT2[LCDC_CLKSEL]). */ -#define FSL_FEATURE_SIM_OPT_HAS_LCDCSRC (0) -/* @brief Has ENET timestamp clock source selection (register bit SOPT2[TIMESRC]). */ -#define FSL_FEATURE_SIM_OPT_HAS_TIMESRC (0) -/* @brief Has ENET RMII clock source selection (register bit SOPT2[RMIISRC]). */ -#define FSL_FEATURE_SIM_OPT_HAS_RMIISRC (0) -/* @brief Has USB clock source selection (register bit SOPT2[USBSRC]). */ -#define FSL_FEATURE_SIM_OPT_HAS_USBSRC (1) -/* @brief Has USB FS clock source selection (register bit SOPT2[USBFSRC]). */ -#define FSL_FEATURE_SIM_OPT_HAS_USBFSRC (0) -/* @brief Has USB HS clock source selection (register bit SOPT2[USBHSRC]). */ -#define FSL_FEATURE_SIM_OPT_HAS_USBHSRC (0) -/* @brief Has LPUART clock source selection (register bit SOPT2[LPUARTSRC]). */ -#define FSL_FEATURE_SIM_OPT_HAS_LPUARTSRC (0) -/* @brief Has LPUART0 clock source selection (register bit SOPT2[LPUART0SRC]). */ -#define FSL_FEATURE_SIM_OPT_HAS_LPUART0SRC (0) -/* @brief Has LPUART1 clock source selection (register bit SOPT2[LPUART1SRC]). */ -#define FSL_FEATURE_SIM_OPT_HAS_LPUART1SRC (0) -/* @brief Has FLEXIOSRC clock source selection (register bit SOPT2[FLEXIOSRC]). */ -#define FSL_FEATURE_SIM_OPT_HAS_FLEXIOSRC (0) -/* @brief Has UART0 clock source selection (register bit SOPT2[UART0SRC]). */ -#define FSL_FEATURE_SIM_OPT_HAS_UART0SRC (0) -/* @brief Has TPM clock source selection (register bit SOPT2[TPMSRC]). */ -#define FSL_FEATURE_SIM_OPT_HAS_TPMSRC (0) -/* @brief Has debug trace clock selection (register bit SOPT2[TRACECLKSEL]). */ -#define FSL_FEATURE_SIM_OPT_HAS_TRACE_CLKSEL (1) -/* @brief Number of ADC modules (register bits SOPT7[ADCnTRGSEL], SOPT7[ADCnPRETRGSEL], SOPT7[ADCnALTTRGSEL], where n is a module instance index). */ -#define FSL_FEATURE_SIM_OPT_ADC_COUNT (2) -/* @brief ADC0 alternate trigger enable width (width of bit field ADC0ALTTRGEN of register SOPT7). */ -#define FSL_FEATURE_SIM_OPT_ADC0ALTTRGEN_WIDTH (1) -/* @brief ADC1 alternate trigger enable width (width of bit field ADC1ALTTRGEN of register SOPT7). */ -#define FSL_FEATURE_SIM_OPT_ADC1ALTTRGEN_WIDTH (1) -/* @brief ADC2 alternate trigger enable width (width of bit field ADC2ALTTRGEN of register SOPT7). */ -#define FSL_FEATURE_SIM_OPT_ADC2ALTTRGEN_WIDTH (0) -/* @brief ADC3 alternate trigger enable width (width of bit field ADC3ALTTRGEN of register SOPT7). */ -#define FSL_FEATURE_SIM_OPT_ADC3ALTTRGEN_WIDTH (0) -/* @brief HSADC0 converter A alternate trigger enable width (width of bit field HSADC0AALTTRGEN of register SOPT7). */ -#define FSL_FEATURE_SIM_OPT_HSADC0AALTTRGEN_WIDTH (0) -/* @brief HSADC1 converter A alternate trigger enable width (width of bit field HSADC1AALTTRGEN of register SOPT7). */ -#define FSL_FEATURE_SIM_OPT_HSADC1AALTTRGEN_WIDTH (0) -/* @brief ADC converter A alternate trigger enable width (width of bit field ADCAALTTRGEN of register SOPT7). */ -#define FSL_FEATURE_SIM_OPT_ADCAALTTRGEN_WIDTH (0) -/* @brief HSADC0 converter B alternate trigger enable width (width of bit field HSADC0BALTTRGEN of register SOPT7). */ -#define FSL_FEATURE_SIM_OPT_HSADC0BALTTRGEN_WIDTH (0) -/* @brief HSADC1 converter B alternate trigger enable width (width of bit field HSADC1BALTTRGEN of register SOPT7). */ -#define FSL_FEATURE_SIM_OPT_HSADC1BALTTRGEN_WIDTH (0) -/* @brief ADC converter B alternate trigger enable width (width of bit field ADCBALTTRGEN of register SOPT7). */ -#define FSL_FEATURE_SIM_OPT_ADCBALTTRGEN_WIDTH (0) -/* @brief Has clock 2 output divider (register bit field CLKDIV1[OUTDIV2]). */ -#define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV2 (1) -/* @brief Has clock 3 output divider (register bit field CLKDIV1[OUTDIV3]). */ -#define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV3 (1) -/* @brief Has clock 4 output divider (register bit field CLKDIV1[OUTDIV4]). */ -#define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV4 (1) -/* @brief Clock 4 output divider width (width of register bit field CLKDIV1[OUTDIV4]). */ -#define FSL_FEATURE_SIM_DIVIDER_OUTDIV4_WIDTH (4) -/* @brief Has clock 5 output divider (register bit field CLKDIV1[OUTDIV5]). */ -#define FSL_FEATURE_SIM_DIVIDER_HAS_OUTDIV5 (0) -/* @brief Has USB clock divider (register bit field CLKDIV2[USBDIV] and CLKDIV2[USBFRAC]). */ -#define FSL_FEATURE_SIM_DIVIDER_HAS_USBDIV (1) -/* @brief Has USB FS clock divider (register bit field CLKDIV2[USBFSDIV] and CLKDIV2[USBFSFRAC]). */ -#define FSL_FEATURE_SIM_DIVIDER_HAS_USBFSDIV (0) -/* @brief Has USB HS clock divider (register bit field CLKDIV2[USBHSDIV] and CLKDIV2[USBHSFRAC]). */ -#define FSL_FEATURE_SIM_DIVIDER_HAS_USBHSDIV (0) -/* @brief Has PLL/FLL clock divider (register bit field CLKDIV3[PLLFLLDIV] and CLKDIV3[PLLFLLFRAC]). */ -#define FSL_FEATURE_SIM_DIVIDER_HAS_PLLFLLDIV (0) -/* @brief Has LCDC clock divider (register bit field CLKDIV3[LCDCDIV] and CLKDIV3[LCDCFRAC]). */ -#define FSL_FEATURE_SIM_DIVIDER_HAS_LCDCDIV (0) -/* @brief Has trace clock divider (register bit field CLKDIV4[TRACEDIV] and CLKDIV4[TRACEFRAC]). */ -#define FSL_FEATURE_SIM_DIVIDER_HAS_TRACEDIV (0) -/* @brief Has NFC clock divider (register bit field CLKDIV4[NFCDIV] and CLKDIV4[NFCFRAC]). */ -#define FSL_FEATURE_SIM_DIVIDER_HAS_NFCDIV (0) -/* @brief Has Kinetis family ID (register bit field SDID[FAMILYID]). */ -#define FSL_FEATURE_SIM_SDID_HAS_FAMILYID (1) -/* @brief Has Kinetis family ID (register bit field SDID[FAMID]). */ -#define FSL_FEATURE_SIM_SDID_HAS_FAMID (1) -/* @brief Has Kinetis sub-family ID (register bit field SDID[SUBFAMID]). */ -#define FSL_FEATURE_SIM_SDID_HAS_SUBFAMID (1) -/* @brief Has Kinetis series ID (register bit field SDID[SERIESID]). */ -#define FSL_FEATURE_SIM_SDID_HAS_SERIESID (1) -/* @brief Has device die ID (register bit field SDID[DIEID]). */ -#define FSL_FEATURE_SIM_SDID_HAS_DIEID (1) -/* @brief Has system SRAM size specifier (register bit field SDID[SRAMSIZE]). */ -#define FSL_FEATURE_SIM_SDID_HAS_SRAMSIZE (0) -/* @brief Has flash mode (register bit FCFG1[FLASHDOZE]). */ -#define FSL_FEATURE_SIM_FCFG_HAS_FLASHDOZE (1) -/* @brief Has flash disable (register bit FCFG1[FLASHDIS]). */ -#define FSL_FEATURE_SIM_FCFG_HAS_FLASHDIS (1) -/* @brief Has FTFE disable (register bit FCFG1[FTFDIS]). */ -#define FSL_FEATURE_SIM_FCFG_HAS_FTFDIS (0) -/* @brief Has FlexNVM size specifier (register bit field FCFG1[NVMSIZE]). */ -#define FSL_FEATURE_SIM_FCFG_HAS_NVMSIZE (1) -/* @brief Has EEPROM size specifier (register bit field FCFG1[EESIZE]). */ -#define FSL_FEATURE_SIM_FCFG_HAS_EESIZE (1) -/* @brief Has FlexNVM partition (register bit field FCFG1[DEPART]). */ -#define FSL_FEATURE_SIM_FCFG_HAS_DEPART (1) -/* @brief Maximum flash address block 0 address specifier (register bit field FCFG2[MAXADDR0]). */ -#define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR0 (1) -/* @brief Maximum flash address block 1 address specifier (register bit field FCFG2[MAXADDR1]). */ -#define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR1 (1) -/* @brief Maximum flash address block 0 or 1 address specifier (register bit field FCFG2[MAXADDR01]). */ -#define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR01 (0) -/* @brief Maximum flash address block 2 or 3 address specifier (register bit field FCFG2[MAXADDR23]). */ -#define FSL_FEATURE_SIM_FCFG_HAS_MAXADDR23 (0) -/* @brief Has program flash availability specifier (register bit FCFG2[PFLSH]). */ -#define FSL_FEATURE_SIM_FCFG_HAS_PFLSH (1) -/* @brief Has program flash swapping (register bit FCFG2[SWAPPFLSH]). */ -#define FSL_FEATURE_SIM_FCFG_HAS_PFLSH_SWAP (0) -/* @brief Has miscellanious control register (register MCR). */ -#define FSL_FEATURE_SIM_HAS_MISC_CONTROLS (0) -/* @brief Has COP watchdog (registers COPC and SRVCOP). */ -#define FSL_FEATURE_SIM_HAS_COP_WATCHDOG (0) -/* @brief Has COP watchdog stop (register bits COPC[COPSTPEN], COPC[COPDBGEN] and COPC[COPCLKSEL]). */ -#define FSL_FEATURE_SIM_HAS_COP_STOP (0) -/* @brief Has LLWU clock gate bit (e.g SIM_SCGC4). */ -#define FSL_FEATURE_SIM_HAS_SCGC_LLWU (0) - -/* SMC module features */ - -/* @brief Has partial stop option (register bit STOPCTRL[PSTOPO]). */ -#define FSL_FEATURE_SMC_HAS_PSTOPO (0) -/* @brief Has LPO power option (register bit STOPCTRL[LPOPO]). */ -#define FSL_FEATURE_SMC_HAS_LPOPO (0) -/* @brief Has POR power option (register bit STOPCTRL[PORPO] or VLLSCTRL[PORPO]). */ -#define FSL_FEATURE_SMC_HAS_PORPO (1) -/* @brief Has low power wakeup on interrupt (register bit PMCTRL[LPWUI]). */ -#define FSL_FEATURE_SMC_HAS_LPWUI (1) -/* @brief Has LLS or VLLS mode control (register bit STOPCTRL[LLSM]). */ -#define FSL_FEATURE_SMC_HAS_LLS_SUBMODE (0) -/* @brief Has VLLS mode control (register bit VLLSCTRL[VLLSM]). */ -#define FSL_FEATURE_SMC_USE_VLLSCTRL_REG (1) -/* @brief Has VLLS mode control (register bit STOPCTRL[VLLSM]). */ -#define FSL_FEATURE_SMC_USE_STOPCTRL_VLLSM (0) -/* @brief Has RAM partition 2 power option (register bit STOPCTRL[RAM2PO]). */ -#define FSL_FEATURE_SMC_HAS_RAM2_POWER_OPTION (0) -/* @brief Has high speed run mode (register bit PMPROT[AHSRUN]). */ -#define FSL_FEATURE_SMC_HAS_HIGH_SPEED_RUN_MODE (0) -/* @brief Has low leakage stop mode (register bit PMPROT[ALLS]). */ -#define FSL_FEATURE_SMC_HAS_LOW_LEAKAGE_STOP_MODE (1) -/* @brief Has very low leakage stop mode (register bit PMPROT[AVLLS]). */ -#define FSL_FEATURE_SMC_HAS_VERY_LOW_LEAKAGE_STOP_MODE (1) -/* @brief Has stop submode. */ -#define FSL_FEATURE_SMC_HAS_SUB_STOP_MODE (1) -/* @brief Has stop submode 0(VLLS0). */ -#define FSL_FEATURE_SMC_HAS_STOP_SUBMODE0 (1) -/* @brief Has stop submode 2(VLLS2). */ -#define FSL_FEATURE_SMC_HAS_STOP_SUBMODE2 (1) -/* @brief Has SMC_PARAM. */ -#define FSL_FEATURE_SMC_HAS_PARAM (0) -/* @brief Has SMC_VERID. */ -#define FSL_FEATURE_SMC_HAS_VERID (0) -/* @brief Has stop abort flag (register bit PMCTRL[STOPA]). */ -#define FSL_FEATURE_SMC_HAS_PMCTRL_STOPA (1) -/* @brief Has tamper reset (register bit SRS[TAMPER]). */ -#define FSL_FEATURE_SMC_HAS_SRS_TAMPER (0) -/* @brief Has security violation reset (register bit SRS[SECVIO]). */ -#define FSL_FEATURE_SMC_HAS_SRS_SECVIO (0) - -/* DSPI module features */ - -/* @brief Receive/transmit FIFO size in number of items. */ -#define FSL_FEATURE_DSPI_FIFO_SIZEn(x) \ - ((x) == DSPI0 ? (4) : \ - ((x) == DSPI1 ? (1) : \ - ((x) == DSPI2 ? (1) : (-1)))) -/* @brief Maximum transfer data width in bits. */ -#define FSL_FEATURE_DSPI_MAX_DATA_WIDTH (16) -/* @brief Maximum number of chip select pins. (Reflects the width of register bit field PUSHR[PCS].) */ -#define FSL_FEATURE_DSPI_MAX_CHIP_SELECT_COUNT (6) -/* @brief Number of chip select pins. */ -#define FSL_FEATURE_DSPI_CHIP_SELECT_COUNT (6) -/* @brief Has chip select strobe capability on the PCS5 pin. */ -#define FSL_FEATURE_DSPI_HAS_CHIP_SELECT_STROBE (1) -/* @brief Has separated TXDATA and CMD FIFOs (register SREX). */ -#define FSL_FEATURE_DSPI_HAS_SEPARATE_TXDATA_CMD_FIFO (0) -/* @brief Has 16-bit data transfer support. */ -#define FSL_FEATURE_DSPI_16BIT_TRANSFERS (1) -/* @brief Has separate DMA RX and TX requests. */ -#define FSL_FEATURE_DSPI_HAS_SEPARATE_DMA_RX_TX_REQn(x) \ - ((x) == DSPI0 ? (1) : \ - ((x) == DSPI1 ? (0) : \ - ((x) == DSPI2 ? (0) : (-1)))) - -/* SYSMPU module features */ - -/* @brief Specifies number of descriptors available. */ -#define FSL_FEATURE_SYSMPU_DESCRIPTOR_COUNT (12) -/* @brief Has process identifier support. */ -#define FSL_FEATURE_SYSMPU_HAS_PROCESS_IDENTIFIER (1) -/* @brief Total number of MPU slave. */ -#define FSL_FEATURE_SYSMPU_SLAVE_COUNT (5) -/* @brief Total number of MPU master. */ -#define FSL_FEATURE_SYSMPU_MASTER_COUNT (6) - -/* SysTick module features */ - -/* @brief Systick has external reference clock. */ -#define FSL_FEATURE_SYSTICK_HAS_EXT_REF (0) -/* @brief Systick external reference clock is core clock divided by this value. */ -#define FSL_FEATURE_SYSTICK_EXT_REF_CORE_DIV (0) - -/* UART module features */ - -#if defined(CPU_MK24FN1M0CAJ12) || defined(CPU_MK24FN1M0VDC12) || defined(CPU_MK24FN1M0VLQ12) - /* @brief Has receive FIFO overflow detection (bit field CFIFO[RXOFE]). */ - #define FSL_FEATURE_UART_HAS_IRQ_EXTENDED_FUNCTIONS (1) - /* @brief Has low power features (can be enabled in wait mode via register bit C1[DOZEEN] or CTRL[DOZEEN] if the registers are 32-bit wide). */ - #define FSL_FEATURE_UART_HAS_LOW_POWER_UART_SUPPORT (0) - /* @brief Has extended data register ED (or extra flags in the DATA register if the registers are 32-bit wide). */ - #define FSL_FEATURE_UART_HAS_EXTENDED_DATA_REGISTER_FLAGS (1) - /* @brief Capacity (number of entries) of the transmit/receive FIFO (or zero if no FIFO is available). */ - #define FSL_FEATURE_UART_HAS_FIFO (1) - /* @brief Hardware flow control (RTS, CTS) is supported. */ - #define FSL_FEATURE_UART_HAS_MODEM_SUPPORT (1) - /* @brief Infrared (modulation) is supported. */ - #define FSL_FEATURE_UART_HAS_IR_SUPPORT (1) - /* @brief 2 bits long stop bit is available. */ - #define FSL_FEATURE_UART_HAS_STOP_BIT_CONFIG_SUPPORT (1) - /* @brief If 10-bit mode is supported. */ - #define FSL_FEATURE_UART_HAS_10BIT_DATA_SUPPORT (1) - /* @brief Baud rate fine adjustment is available. */ - #define FSL_FEATURE_UART_HAS_BAUD_RATE_FINE_ADJUST_SUPPORT (1) - /* @brief Baud rate oversampling is available (has bit fields C4[OSR], C5[BOTHEDGE], C5[RESYNCDIS] or BAUD[OSR], BAUD[BOTHEDGE], BAUD[RESYNCDIS] if the registers are 32-bit wide). */ - #define FSL_FEATURE_UART_HAS_BAUD_RATE_OVER_SAMPLING_SUPPORT (0) - /* @brief Baud rate oversampling is available. */ - #define FSL_FEATURE_UART_HAS_RX_RESYNC_SUPPORT (0) - /* @brief Baud rate oversampling is available. */ - #define FSL_FEATURE_UART_HAS_BOTH_EDGE_SAMPLING_SUPPORT (0) - /* @brief Peripheral type. */ - #define FSL_FEATURE_UART_IS_SCI (0) - /* @brief Capacity (number of entries) of the transmit/receive FIFO (or zero if no FIFO is available). */ - #define FSL_FEATURE_UART_FIFO_SIZEn(x) \ - ((x) == UART0 ? (8) : \ - ((x) == UART1 ? (8) : \ - ((x) == UART2 ? (1) : \ - ((x) == UART3 ? (1) : \ - ((x) == UART4 ? (1) : \ - ((x) == UART5 ? (1) : (-1))))))) - /* @brief Maximal data width without parity bit. */ - #define FSL_FEATURE_UART_MAX_DATA_WIDTH_WITH_NO_PARITY (9) - /* @brief Maximal data width with parity bit. */ - #define FSL_FEATURE_UART_MAX_DATA_WIDTH_WITH_PARITY (10) - /* @brief Supports two match addresses to filter incoming frames. */ - #define FSL_FEATURE_UART_HAS_ADDRESS_MATCHING (1) - /* @brief Has transmitter/receiver DMA enable bits C5[TDMAE]/C5[RDMAE] (or BAUD[TDMAE]/BAUD[RDMAE] if the registers are 32-bit wide). */ - #define FSL_FEATURE_UART_HAS_DMA_ENABLE (0) - /* @brief Has transmitter/receiver DMA select bits C4[TDMAS]/C4[RDMAS], resp. C5[TDMAS]/C5[RDMAS] if IS_SCI = 0. */ - #define FSL_FEATURE_UART_HAS_DMA_SELECT (1) - /* @brief Data character bit order selection is supported (bit field S2[MSBF] or STAT[MSBF] if the registers are 32-bit wide). */ - #define FSL_FEATURE_UART_HAS_BIT_ORDER_SELECT (1) - /* @brief Has smart card (ISO7816 protocol) support and no improved smart card support. */ - #define FSL_FEATURE_UART_HAS_SMART_CARD_SUPPORT (1) - /* @brief Has improved smart card (ISO7816 protocol) support. */ - #define FSL_FEATURE_UART_HAS_IMPROVED_SMART_CARD_SUPPORT (0) - /* @brief Has local operation network (CEA709.1-B protocol) support. */ - #define FSL_FEATURE_UART_HAS_LOCAL_OPERATION_NETWORK_SUPPORT (0) - /* @brief Has 32-bit registers (BAUD, STAT, CTRL, DATA, MATCH, MODIR) instead of 8-bit (BDH, BDL, C1, S1, D, etc.). */ - #define FSL_FEATURE_UART_HAS_32BIT_REGISTERS (0) - /* @brief Lin break detect available (has bit BDH[LBKDIE]). */ - #define FSL_FEATURE_UART_HAS_LIN_BREAK_DETECT (1) - /* @brief UART stops in Wait mode available (has bit C1[UARTSWAI]). */ - #define FSL_FEATURE_UART_HAS_WAIT_MODE_OPERATION (1) - /* @brief Has separate DMA RX and TX requests. */ - #define FSL_FEATURE_UART_HAS_SEPARATE_DMA_RX_TX_REQn(x) \ - ((x) == UART0 ? (1) : \ - ((x) == UART1 ? (1) : \ - ((x) == UART2 ? (1) : \ - ((x) == UART3 ? (1) : \ - ((x) == UART4 ? (0) : \ - ((x) == UART5 ? (0) : (-1))))))) -#elif defined(CPU_MK24FN1M0VLL12) - /* @brief Has receive FIFO overflow detection (bit field CFIFO[RXOFE]). */ - #define FSL_FEATURE_UART_HAS_IRQ_EXTENDED_FUNCTIONS (1) - /* @brief Has low power features (can be enabled in wait mode via register bit C1[DOZEEN] or CTRL[DOZEEN] if the registers are 32-bit wide). */ - #define FSL_FEATURE_UART_HAS_LOW_POWER_UART_SUPPORT (0) - /* @brief Has extended data register ED (or extra flags in the DATA register if the registers are 32-bit wide). */ - #define FSL_FEATURE_UART_HAS_EXTENDED_DATA_REGISTER_FLAGS (1) - /* @brief Capacity (number of entries) of the transmit/receive FIFO (or zero if no FIFO is available). */ - #define FSL_FEATURE_UART_HAS_FIFO (1) - /* @brief Hardware flow control (RTS, CTS) is supported. */ - #define FSL_FEATURE_UART_HAS_MODEM_SUPPORT (1) - /* @brief Infrared (modulation) is supported. */ - #define FSL_FEATURE_UART_HAS_IR_SUPPORT (1) - /* @brief 2 bits long stop bit is available. */ - #define FSL_FEATURE_UART_HAS_STOP_BIT_CONFIG_SUPPORT (1) - /* @brief If 10-bit mode is supported. */ - #define FSL_FEATURE_UART_HAS_10BIT_DATA_SUPPORT (1) - /* @brief Baud rate fine adjustment is available. */ - #define FSL_FEATURE_UART_HAS_BAUD_RATE_FINE_ADJUST_SUPPORT (1) - /* @brief Baud rate oversampling is available (has bit fields C4[OSR], C5[BOTHEDGE], C5[RESYNCDIS] or BAUD[OSR], BAUD[BOTHEDGE], BAUD[RESYNCDIS] if the registers are 32-bit wide). */ - #define FSL_FEATURE_UART_HAS_BAUD_RATE_OVER_SAMPLING_SUPPORT (0) - /* @brief Baud rate oversampling is available. */ - #define FSL_FEATURE_UART_HAS_RX_RESYNC_SUPPORT (0) - /* @brief Baud rate oversampling is available. */ - #define FSL_FEATURE_UART_HAS_BOTH_EDGE_SAMPLING_SUPPORT (0) - /* @brief Peripheral type. */ - #define FSL_FEATURE_UART_IS_SCI (0) - /* @brief Capacity (number of entries) of the transmit/receive FIFO (or zero if no FIFO is available). */ - #define FSL_FEATURE_UART_FIFO_SIZEn(x) \ - ((x) == UART0 ? (8) : \ - ((x) == UART1 ? (8) : \ - ((x) == UART2 ? (1) : \ - ((x) == UART3 ? (1) : \ - ((x) == UART4 ? (1) : (-1)))))) - /* @brief Maximal data width without parity bit. */ - #define FSL_FEATURE_UART_MAX_DATA_WIDTH_WITH_NO_PARITY (9) - /* @brief Maximal data width with parity bit. */ - #define FSL_FEATURE_UART_MAX_DATA_WIDTH_WITH_PARITY (10) - /* @brief Supports two match addresses to filter incoming frames. */ - #define FSL_FEATURE_UART_HAS_ADDRESS_MATCHING (1) - /* @brief Has transmitter/receiver DMA enable bits C5[TDMAE]/C5[RDMAE] (or BAUD[TDMAE]/BAUD[RDMAE] if the registers are 32-bit wide). */ - #define FSL_FEATURE_UART_HAS_DMA_ENABLE (0) - /* @brief Has transmitter/receiver DMA select bits C4[TDMAS]/C4[RDMAS], resp. C5[TDMAS]/C5[RDMAS] if IS_SCI = 0. */ - #define FSL_FEATURE_UART_HAS_DMA_SELECT (1) - /* @brief Data character bit order selection is supported (bit field S2[MSBF] or STAT[MSBF] if the registers are 32-bit wide). */ - #define FSL_FEATURE_UART_HAS_BIT_ORDER_SELECT (1) - /* @brief Has smart card (ISO7816 protocol) support and no improved smart card support. */ - #define FSL_FEATURE_UART_HAS_SMART_CARD_SUPPORT (1) - /* @brief Has improved smart card (ISO7816 protocol) support. */ - #define FSL_FEATURE_UART_HAS_IMPROVED_SMART_CARD_SUPPORT (0) - /* @brief Has local operation network (CEA709.1-B protocol) support. */ - #define FSL_FEATURE_UART_HAS_LOCAL_OPERATION_NETWORK_SUPPORT (0) - /* @brief Has 32-bit registers (BAUD, STAT, CTRL, DATA, MATCH, MODIR) instead of 8-bit (BDH, BDL, C1, S1, D, etc.). */ - #define FSL_FEATURE_UART_HAS_32BIT_REGISTERS (0) - /* @brief Lin break detect available (has bit BDH[LBKDIE]). */ - #define FSL_FEATURE_UART_HAS_LIN_BREAK_DETECT (1) - /* @brief UART stops in Wait mode available (has bit C1[UARTSWAI]). */ - #define FSL_FEATURE_UART_HAS_WAIT_MODE_OPERATION (1) - /* @brief Has separate DMA RX and TX requests. */ - #define FSL_FEATURE_UART_HAS_SEPARATE_DMA_RX_TX_REQn(x) \ - ((x) == UART0 ? (1) : \ - ((x) == UART1 ? (1) : \ - ((x) == UART2 ? (1) : \ - ((x) == UART3 ? (1) : \ - ((x) == UART4 ? (0) : (-1)))))) -#endif /* defined(CPU_MK24FN1M0CAJ12) || defined(CPU_MK24FN1M0VDC12) || defined(CPU_MK24FN1M0VLQ12) */ - -/* USB module features */ - -/* @brief KHCI module instance count */ -#define FSL_FEATURE_USB_KHCI_COUNT (1) -/* @brief HOST mode enabled */ -#define FSL_FEATURE_USB_KHCI_HOST_ENABLED (1) -/* @brief OTG mode enabled */ -#define FSL_FEATURE_USB_KHCI_OTG_ENABLED (1) -/* @brief Size of the USB dedicated RAM */ -#define FSL_FEATURE_USB_KHCI_USB_RAM (0) -/* @brief Has KEEP_ALIVE_CTRL register */ -#define FSL_FEATURE_USB_KHCI_KEEP_ALIVE_ENABLED (0) -/* @brief Has the Dynamic SOF threshold compare support */ -#define FSL_FEATURE_USB_KHCI_DYNAMIC_SOF_THRESHOLD_COMPARE_ENABLED (0) -/* @brief Has the VBUS detect support */ -#define FSL_FEATURE_USB_KHCI_VBUS_DETECT_ENABLED (0) -/* @brief Has the IRC48M module clock support */ -#define FSL_FEATURE_USB_KHCI_IRC48M_MODULE_CLOCK_ENABLED (1) -/* @brief Number of endpoints supported */ -#define FSL_FEATURE_USB_ENDPT_COUNT (16) - -/* VREF module features */ - -/* @brief Has chop oscillator (bit TRM[CHOPEN]) */ -#define FSL_FEATURE_VREF_HAS_CHOP_OSC (1) -/* @brief Has second order curvature compensation (bit SC[ICOMPEN]) */ -#define FSL_FEATURE_VREF_HAS_COMPENSATION (1) -/* @brief If high/low buffer mode supported */ -#define FSL_FEATURE_VREF_MODE_LV_TYPE (1) -/* @brief Module has also low reference (registers VREFL/VREFH) */ -#define FSL_FEATURE_VREF_HAS_LOW_REFERENCE (0) -/* @brief Has VREF_TRM4. */ -#define FSL_FEATURE_VREF_HAS_TRM4 (0) - -/* WDOG module features */ - -/* @brief Watchdog is available. */ -#define FSL_FEATURE_WDOG_HAS_WATCHDOG (1) -/* @brief Has Wait mode support. */ -#define FSL_FEATURE_WDOG_HAS_WAITEN (1) - -#endif /* _MK24F12_FEATURES_H_ */ - diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/device/RTE_Device.h b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/device/RTE_Device.h deleted file mode 100644 index 5905d52a7aa..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/device/RTE_Device.h +++ /dev/null @@ -1,191 +0,0 @@ -/* - * Copyright (c) 2016, Freescale Semiconductor, Inc. - * Copyright (c) 2016 - 2017 , NXP - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef __RTE_DEVICE_H -#define __RTE_DEVICE_H - -/* UART select, UART0-UART5 */ -#define RTE_USART0 0 -#define RTE_USART0_DMA_EN 0 -#define RTE_USART1 0 -#define RTE_USART1_DMA_EN 0 -#define RTE_USART2 0 -#define RTE_USART2_DMA_EN 0 -#define RTE_USART3 0 -#define RTE_USART3_DMA_EN 0 -#define RTE_USART4 0 -#define RTE_USART4_DMA_EN 0 -#define RTE_USART5 0 -#define RTE_USART5_DMA_EN 0 - -/* UART RX Buffer configuration. */ -#define USART_RX_BUFFER_LEN 64 -#define USART0_RX_BUFFER_ENABLE 0 -#define USART1_RX_BUFFER_ENABLE 0 -#define USART2_RX_BUFFER_ENABLE 0 -#define USART3_RX_BUFFER_ENABLE 0 -#define USART4_RX_BUFFER_ENABLE 0 -#define USART5_RX_BUFFER_ENABLE 0 - -#define RTE_USART0_DMA_TX_CH 0 -#define RTE_USART0_DMA_TX_PERI_SEL (uint8_t) kDmaRequestMux0UART0Tx -#define RTE_USART0_DMA_TX_DMAMUX_BASE DMAMUX0 -#define RTE_USART0_DMA_TX_DMA_BASE DMA0 -#define RTE_USART0_DMA_RX_CH 1 -#define RTE_USART0_DMA_RX_PERI_SEL (uint8_t) kDmaRequestMux0UART0Rx -#define RTE_USART0_DMA_RX_DMAMUX_BASE DMAMUX0 -#define RTE_USART0_DMA_RX_DMA_BASE DMA0 - -#define RTE_USART1_DMA_TX_CH 0 -#define RTE_USART1_DMA_TX_PERI_SEL (uint8_t) kDmaRequestMux0UART1Tx -#define RTE_USART1_DMA_TX_DMAMUX_BASE DMAMUX0 -#define RTE_USART1_DMA_TX_DMA_BASE DMA0 -#define RTE_USART1_DMA_RX_CH 1 -#define RTE_USART1_DMA_RX_PERI_SEL (uint8_t) kDmaRequestMux0UART1Rx -#define RTE_USART1_DMA_RX_DMAMUX_BASE DMAMUX0 -#define RTE_USART1_DMA_RX_DMA_BASE DMA0 - -#define RTE_USART2_DMA_TX_CH 0 -#define RTE_USART2_DMA_TX_PERI_SEL (uint8_t) kDmaRequestMux0UART2Tx -#define RTE_USART2_DMA_TX_DMAMUX_BASE DMAMUX0 -#define RTE_USART2_DMA_TX_DMA_BASE DMA0 -#define RTE_USART2_DMA_RX_CH 1 -#define RTE_USART2_DMA_RX_PERI_SEL (uint8_t) kDmaRequestMux0UART2Rx -#define RTE_USART2_DMA_RX_DMAMUX_BASE DMAMUX0 -#define RTE_USART2_DMA_RX_DMA_BASE DMA0 - -#define RTE_USART3_DMA_TX_CH 0 -#define RTE_USART3_DMA_TX_PERI_SEL (uint8_t) kDmaRequestMux0UART3Tx -#define RTE_USART3_DMA_TX_DMAMUX_BASE DMAMUX0 -#define RTE_USART3_DMA_TX_DMA_BASE DMA0 -#define RTE_USART3_DMA_RX_CH 1 -#define RTE_USART3_DMA_RX_PERI_SEL (uint8_t) kDmaRequestMux0UART3Rx -#define RTE_USART3_DMA_RX_DMAMUX_BASE DMAMUX0 -#define RTE_USART3_DMA_RX_DMA_BASE DMA0 - -#define RTE_USART4_DMA_TX_CH 0 -#define RTE_USART4_DMA_TX_PERI_SEL (uint8_t) kDmaRequestMux0UART4 -#define RTE_USART4_DMA_TX_DMAMUX_BASE DMAMUX0 -#define RTE_USART4_DMA_TX_DMA_BASE DMA0 -#define RTE_USART4_DMA_RX_CH 1 -#define RTE_USART4_DMA_RX_PERI_SEL (uint8_t) kDmaRequestMux0UART4 -#define RTE_USART4_DMA_RX_DMAMUX_BASE DMAMUX0 -#define RTE_USART4_DMA_RX_DMA_BASE DMA0 - -#define RTE_USART5_DMA_TX_CH 0 -#define RTE_USART5_DMA_TX_PERI_SEL (uint8_t) kDmaRequestMux0UART5 -#define RTE_USART5_DMA_TX_DMAMUX_BASE DMAMUX0 -#define RTE_USART5_DMA_TX_DMA_BASE DMA0 -#define RTE_USART5_DMA_RX_CH 1 -#define RTE_USART5_DMA_RX_PERI_SEL (uint8_t) kDmaRequestMux0UART5 -#define RTE_USART5_DMA_RX_DMAMUX_BASE DMAMUX0 -#define RTE_USART5_DMA_RX_DMA_BASE DMA0 - - -/* I2C select, I2C0 - I2C2. */ -#define RTE_I2C0 0 -#define RTE_I2C0_DMA_EN 0 -#define RTE_I2C1 0 -#define RTE_I2C1_DMA_EN 0 -#define RTE_I2C2 0 -#define RTE_I2C2_DMA_EN 0 - -/*I2C configuration*/ -#define RTE_I2C0_Master_DMA_BASE DMA0 -#define RTE_I2C0_Master_DMA_CH 0 -#define RTE_I2C0_Master_DMAMUX_BASE DMAMUX0 -#define RTE_I2C0_Master_PERI_SEL kDmaRequestMux0I2C0 - -#define RTE_I2C1_Master_DMA_BASE DMA0 -#define RTE_I2C1_Master_DMA_CH 1 -#define RTE_I2C1_Master_DMAMUX_BASE DMAMUX0 -#define RTE_I2C1_Master_PERI_SEL kDmaRequestMux0I2C1 - -#define RTE_I2C2_Master_DMA_BASE DMA0 -#define RTE_I2C2_Master_DMA_CH 2 -#define RTE_I2C2_Master_DMAMUX_BASE DMAMUX0 -#define RTE_I2C2_Master_PERI_SEL kDmaRequestMux0I2C2 - -/* SPI select, DSPI0 - DSPI2. */ -#define RTE_SPI0 0 -#define RTE_SPI0_DMA_EN 0 -#define RTE_SPI1 0 -#define RTE_SPI1_DMA_EN 0 -#define RTE_SPI2 0 -#define RTE_SPI2_DMA_EN 0 - -/* DSPI configuration. */ -#define RTE_SPI0_PCS_TO_SCK_DELAY 1000 -#define RTE_SPI0_SCK_TO_PSC_DELAY 1000 -#define RTE_SPI0_BETWEEN_TRANSFER_DELAY 1000 -#define RTE_SPI0_MASTER_PCS_PIN_SEL kDSPI_MasterPcs0 -#define RTE_SPI0_DMA_TX_CH 0 -#define RTE_SPI0_DMA_TX_PERI_SEL (uint8_t) kDmaRequestMux0SPI0Tx -#define RTE_SPI0_DMA_TX_DMAMUX_BASE DMAMUX0 -#define RTE_SPI0_DMA_TX_DMA_BASE DMA0 -#define RTE_SPI0_DMA_RX_CH 1 -#define RTE_SPI0_DMA_RX_PERI_SEL (uint8_t) kDmaRequestMux0SPI0Rx -#define RTE_SPI0_DMA_RX_DMAMUX_BASE DMAMUX0 -#define RTE_SPI0_DMA_RX_DMA_BASE DMA0 -#define RTE_SPI0_DMA_LINK_DMA_BASE DMA0 -#define RTE_SPI0_DMA_LINK_CH 2 - -#define RTE_SPI1_PCS_TO_SCK_DELAY 1000 -#define RTE_SPI1_SCK_TO_PSC_DELAY 1000 -#define RTE_SPI1_BETWEEN_TRANSFER_DELAY 1000 -#define RTE_SPI1_MASTER_PCS_PIN_SEL kDSPI_MasterPcs0 -#define RTE_SPI1_DMA_TX_CH 4 -#define RTE_SPI1_DMA_TX_PERI_SEL (uint8_t) kDmaRequestMux0SPI1 -#define RTE_SPI1_DMA_TX_DMAMUX_BASE DMAMUX0 -#define RTE_SPI1_DMA_TX_DMA_BASE DMA0 -#define RTE_SPI1_DMA_RX_CH 3 -#define RTE_SPI1_DMA_RX_PERI_SEL (uint8_t) kDmaRequestMux0SPI1 -#define RTE_SPI1_DMA_RX_DMAMUX_BASE DMAMUX0 -#define RTE_SPI1_DMA_RX_DMA_BASE DMA0 -#define RTE_SPI1_DMA_LINK_DMA_BASE DMA0 -#define RTE_SPI1_DMA_LINK_CH 2 - -#define RTE_SPI2_PCS_TO_SCK_DELAY 1000 -#define RTE_SPI2_SCK_TO_PSC_DELAY 1000 -#define RTE_SPI2_BETWEEN_TRANSFER_DELAY 1000 -#define RTE_SPI2_MASTER_PCS_PIN_SEL kDSPI_MasterPcs0 -#define RTE_SPI2_DMA_TX_CH 6 -#define RTE_SPI2_DMA_TX_PERI_SEL (uint8_t) kDmaRequestMux0SPI2 -#define RTE_SPI2_DMA_TX_DMAMUX_BASE DMAMUX0 -#define RTE_SPI2_DMA_TX_DMA_BASE DMA0 -#define RTE_SPI2_DMA_RX_CH 7 -#define RTE_SPI2_DMA_RX_PERI_SEL (uint8_t) kDmaRequestMux0SPI2 -#define RTE_SPI2_DMA_RX_DMAMUX_BASE DMAMUX0 -#define RTE_SPI2_DMA_RX_DMA_BASE DMA0 -#define RTE_SPI2_DMA_LINK_DMA_BASE DMA0 -#define RTE_SPI2_DMA_LINK_CH 8 - -#endif /* __RTE_DEVICE_H */ diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/device/TOOLCHAIN_ARM_STD/MK24FN1M0xxx12.sct b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/device/TOOLCHAIN_ARM_STD/MK24FN1M0xxx12.sct deleted file mode 100644 index 7cee92692d5..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/device/TOOLCHAIN_ARM_STD/MK24FN1M0xxx12.sct +++ /dev/null @@ -1,96 +0,0 @@ -#! armcc -E -/* -** ################################################################### -** Processors: MK24FN1M0CAJ12 -** MK24FN1M0VDC12 -** MK24FN1M0VLL12 -** MK24FN1M0VLQ12 -** -** Compiler: Keil ARM C/C++ Compiler -** Reference manual: K24P144M120SF5RM, Rev.2, January 2014 -** Version: rev. 2.8, 2016-03-21 -** Build: b160321 -** -** Abstract: -** Linker file for the Keil ARM C/C++ Compiler -** -** Copyright (c) 2016 Freescale Semiconductor, Inc. -** All rights reserved. -** -** Redistribution and use in source and binary forms, with or without modification, -** are permitted provided that the following conditions are met: -** -** o Redistributions of source code must retain the above copyright notice, this list -** of conditions and the following disclaimer. -** -** o Redistributions in binary form must reproduce the above copyright notice, this -** list of conditions and the following disclaimer in the documentation and/or -** other materials provided with the distribution. -** -** o Neither the name of Freescale Semiconductor, Inc. nor the names of its -** contributors may be used to endorse or promote products derived from this -** software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -** ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -** LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -** ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -** -** http: www.freescale.com -** mail: support@freescale.com -** -** ################################################################### -*/ -#define __ram_vector_table__ 1 - -#if (defined(__ram_vector_table__)) - #define __ram_vector_table_size__ 0x00000400 -#else - #define __ram_vector_table_size__ 0x00000000 -#endif - -#define m_interrupts_start 0x00000000 -#define m_interrupts_size 0x00000400 - -#define m_flash_config_start 0x00000400 -#define m_flash_config_size 0x00000010 - -#define m_text_start 0x00000410 -#define m_text_size 0x000FFBF0 - -#define m_interrupts_ram_start 0x1FFF0000 -#define m_interrupts_ram_size __ram_vector_table_size__ - -#define m_data_start (m_interrupts_ram_start + m_interrupts_ram_size) -#define m_data_size (0x00010000 - m_interrupts_ram_size) - -#define m_data_2_start 0x20000000 -#define m_data_2_size 0x00030000 - - -LR_m_text m_interrupts_start m_text_size+m_interrupts_size+m_flash_config_size { ; load region size_region - VECTOR_ROM m_interrupts_start m_interrupts_size { ; load address = execution address - * (RESET,+FIRST) - } - ER_m_flash_config m_flash_config_start m_flash_config_size { ; load address = execution address - * (FlashConfig) - } - ER_m_text m_text_start m_text_size { ; load address = execution address - * (InRoot$$Sections) - .ANY (+RO) - } - RW_m_data m_data_start m_data_size { ; RW data - .ANY (+RW +ZI) - } - RW_IRAM1 m_data_2_start m_data_2_size { ; RW data - .ANY (+RW +ZI) - } - VECTOR_RAM m_interrupts_ram_start EMPTY m_interrupts_ram_size { - } -} diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/device/TOOLCHAIN_ARM_STD/startup_MK24F12.s b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/device/TOOLCHAIN_ARM_STD/startup_MK24F12.s deleted file mode 100644 index ddfb954790a..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/device/TOOLCHAIN_ARM_STD/startup_MK24F12.s +++ /dev/null @@ -1,1023 +0,0 @@ -; * --------------------------------------------------------------------------------------- -; * @file: startup_MK24F12.s -; * @purpose: CMSIS Cortex-M4 Core Device Startup File -; * MK24F12 -; * @version: 2.8 -; * @date: 2016-3-21 -; * @build: b160321 -; * --------------------------------------------------------------------------------------- -; * -; * Copyright (c) 1997 - 2016 , Freescale Semiconductor, Inc. -; * All rights reserved. -; * -; * Redistribution and use in source and binary forms, with or without modification, -; * are permitted provided that the following conditions are met: -; * -; * o Redistributions of source code must retain the above copyright notice, this list -; * of conditions and the following disclaimer. -; * -; * o Redistributions in binary form must reproduce the above copyright notice, this -; * list of conditions and the following disclaimer in the documentation and/or -; * other materials provided with the distribution. -; * -; * o Neither the name of Freescale Semiconductor, Inc. nor the names of its -; * contributors may be used to endorse or promote products derived from this -; * software without specific prior written permission. -; * -; * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -; * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -; * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -; * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -; * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -; * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -; * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -; * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -; * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -; * -; *------- <<< Use Configuration Wizard in Context Menu >>> ------------------ -; * -; *****************************************************************************/ - -__initial_sp EQU 0x20030000 ; Top of RAM - PRESERVE8 - THUMB - - -; Vector Table Mapped to Address 0 at Reset - - AREA RESET, DATA, READONLY - EXPORT __Vectors - EXPORT __Vectors_End - EXPORT __Vectors_Size - -__Vectors DCD __initial_sp ; Top of Stack - DCD Reset_Handler ; Reset Handler - DCD NMI_Handler ;NMI Handler - DCD HardFault_Handler ;Hard Fault Handler - DCD MemManage_Handler ;MPU Fault Handler - DCD BusFault_Handler ;Bus Fault Handler - DCD UsageFault_Handler ;Usage Fault Handler - DCD 0 ;Reserved - DCD 0 ;Reserved - DCD 0 ;Reserved - DCD 0 ;Reserved - DCD SVC_Handler ;SVCall Handler - DCD DebugMon_Handler ;Debug Monitor Handler - DCD 0 ;Reserved - DCD PendSV_Handler ;PendSV Handler - DCD SysTick_Handler ;SysTick Handler - - ;External Interrupts - DCD DMA0_IRQHandler ;DMA Channel 0 Transfer Complete - DCD DMA1_IRQHandler ;DMA Channel 1 Transfer Complete - DCD DMA2_IRQHandler ;DMA Channel 2 Transfer Complete - DCD DMA3_IRQHandler ;DMA Channel 3 Transfer Complete - DCD DMA4_IRQHandler ;DMA Channel 4 Transfer Complete - DCD DMA5_IRQHandler ;DMA Channel 5 Transfer Complete - DCD DMA6_IRQHandler ;DMA Channel 6 Transfer Complete - DCD DMA7_IRQHandler ;DMA Channel 7 Transfer Complete - DCD DMA8_IRQHandler ;DMA Channel 8 Transfer Complete - DCD DMA9_IRQHandler ;DMA Channel 9 Transfer Complete - DCD DMA10_IRQHandler ;DMA Channel 10 Transfer Complete - DCD DMA11_IRQHandler ;DMA Channel 11 Transfer Complete - DCD DMA12_IRQHandler ;DMA Channel 12 Transfer Complete - DCD DMA13_IRQHandler ;DMA Channel 13 Transfer Complete - DCD DMA14_IRQHandler ;DMA Channel 14 Transfer Complete - DCD DMA15_IRQHandler ;DMA Channel 15 Transfer Complete - DCD DMA_Error_IRQHandler ;DMA Error Interrupt - DCD MCM_IRQHandler ;Normal Interrupt - DCD FTFE_IRQHandler ;FTFE Command complete interrupt - DCD Read_Collision_IRQHandler ;Read Collision Interrupt - DCD LVD_LVW_IRQHandler ;Low Voltage Detect, Low Voltage Warning - DCD LLWU_IRQHandler ;Low Leakage Wakeup Unit - DCD WDOG_EWM_IRQHandler ;WDOG Interrupt - DCD RNG_IRQHandler ;RNG Interrupt - DCD I2C0_IRQHandler ;I2C0 interrupt - DCD I2C1_IRQHandler ;I2C1 interrupt - DCD SPI0_IRQHandler ;SPI0 Interrupt - DCD SPI1_IRQHandler ;SPI1 Interrupt - DCD I2S0_Tx_IRQHandler ;I2S0 transmit interrupt - DCD I2S0_Rx_IRQHandler ;I2S0 receive interrupt - DCD UART0_LON_IRQHandler ;UART0 LON interrupt - DCD UART0_RX_TX_IRQHandler ;UART0 Receive/Transmit interrupt - DCD UART0_ERR_IRQHandler ;UART0 Error interrupt - DCD UART1_RX_TX_IRQHandler ;UART1 Receive/Transmit interrupt - DCD UART1_ERR_IRQHandler ;UART1 Error interrupt - DCD UART2_RX_TX_IRQHandler ;UART2 Receive/Transmit interrupt - DCD UART2_ERR_IRQHandler ;UART2 Error interrupt - DCD UART3_RX_TX_IRQHandler ;UART3 Receive/Transmit interrupt - DCD UART3_ERR_IRQHandler ;UART3 Error interrupt - DCD ADC0_IRQHandler ;ADC0 interrupt - DCD CMP0_IRQHandler ;CMP0 interrupt - DCD CMP1_IRQHandler ;CMP1 interrupt - DCD FTM0_IRQHandler ;FTM0 fault, overflow and channels interrupt - DCD FTM1_IRQHandler ;FTM1 fault, overflow and channels interrupt - DCD FTM2_IRQHandler ;FTM2 fault, overflow and channels interrupt - DCD CMT_IRQHandler ;CMT interrupt - DCD RTC_IRQHandler ;RTC interrupt - DCD RTC_Seconds_IRQHandler ;RTC seconds interrupt - DCD PIT0_IRQHandler ;PIT timer channel 0 interrupt - DCD PIT1_IRQHandler ;PIT timer channel 1 interrupt - DCD PIT2_IRQHandler ;PIT timer channel 2 interrupt - DCD PIT3_IRQHandler ;PIT timer channel 3 interrupt - DCD PDB0_IRQHandler ;PDB0 Interrupt - DCD USB0_IRQHandler ;USB0 interrupt - DCD USBDCD_IRQHandler ;USBDCD Interrupt - DCD Reserved71_IRQHandler ;Reserved interrupt 71 - DCD DAC0_IRQHandler ;DAC0 interrupt - DCD MCG_IRQHandler ;MCG Interrupt - DCD LPTMR0_IRQHandler ;LPTimer interrupt - DCD PORTA_IRQHandler ;Port A interrupt - DCD PORTB_IRQHandler ;Port B interrupt - DCD PORTC_IRQHandler ;Port C interrupt - DCD PORTD_IRQHandler ;Port D interrupt - DCD PORTE_IRQHandler ;Port E interrupt - DCD SWI_IRQHandler ;Software interrupt - DCD SPI2_IRQHandler ;SPI2 Interrupt - DCD UART4_RX_TX_IRQHandler ;UART4 Receive/Transmit interrupt - DCD UART4_ERR_IRQHandler ;UART4 Error interrupt - DCD UART5_RX_TX_IRQHandler ;UART5 Receive/Transmit interrupt - DCD UART5_ERR_IRQHandler ;UART5 Error interrupt - DCD CMP2_IRQHandler ;CMP2 interrupt - DCD FTM3_IRQHandler ;FTM3 fault, overflow and channels interrupt - DCD DAC1_IRQHandler ;DAC1 interrupt - DCD ADC1_IRQHandler ;ADC1 interrupt - DCD I2C2_IRQHandler ;I2C2 interrupt - DCD CAN0_ORed_Message_buffer_IRQHandler ;CAN0 OR'd message buffers interrupt - DCD CAN0_Bus_Off_IRQHandler ;CAN0 bus off interrupt - DCD CAN0_Error_IRQHandler ;CAN0 error interrupt - DCD CAN0_Tx_Warning_IRQHandler ;CAN0 Tx warning interrupt - DCD CAN0_Rx_Warning_IRQHandler ;CAN0 Rx warning interrupt - DCD CAN0_Wake_Up_IRQHandler ;CAN0 wake up interrupt - DCD SDHC_IRQHandler ;SDHC interrupt - DCD Reserved98_IRQHandler ;Reserved interrupt 98 - DCD Reserved99_IRQHandler ;Reserved interrupt 99 - DCD Reserved100_IRQHandler ;Reserved interrupt 100 - DCD Reserved101_IRQHandler ;Reserved interrupt 101 - DCD DefaultISR ;102 - DCD DefaultISR ;103 - DCD DefaultISR ;104 - DCD DefaultISR ;105 - DCD DefaultISR ;106 - DCD DefaultISR ;107 - DCD DefaultISR ;108 - DCD DefaultISR ;109 - DCD DefaultISR ;110 - DCD DefaultISR ;111 - DCD DefaultISR ;112 - DCD DefaultISR ;113 - DCD DefaultISR ;114 - DCD DefaultISR ;115 - DCD DefaultISR ;116 - DCD DefaultISR ;117 - DCD DefaultISR ;118 - DCD DefaultISR ;119 - DCD DefaultISR ;120 - DCD DefaultISR ;121 - DCD DefaultISR ;122 - DCD DefaultISR ;123 - DCD DefaultISR ;124 - DCD DefaultISR ;125 - DCD DefaultISR ;126 - DCD DefaultISR ;127 - DCD DefaultISR ;128 - DCD DefaultISR ;129 - DCD DefaultISR ;130 - DCD DefaultISR ;131 - DCD DefaultISR ;132 - DCD DefaultISR ;133 - DCD DefaultISR ;134 - DCD DefaultISR ;135 - DCD DefaultISR ;136 - DCD DefaultISR ;137 - DCD DefaultISR ;138 - DCD DefaultISR ;139 - DCD DefaultISR ;140 - DCD DefaultISR ;141 - DCD DefaultISR ;142 - DCD DefaultISR ;143 - DCD DefaultISR ;144 - DCD DefaultISR ;145 - DCD DefaultISR ;146 - DCD DefaultISR ;147 - DCD DefaultISR ;148 - DCD DefaultISR ;149 - DCD DefaultISR ;150 - DCD DefaultISR ;151 - DCD DefaultISR ;152 - DCD DefaultISR ;153 - DCD DefaultISR ;154 - DCD DefaultISR ;155 - DCD DefaultISR ;156 - DCD DefaultISR ;157 - DCD DefaultISR ;158 - DCD DefaultISR ;159 - DCD DefaultISR ;160 - DCD DefaultISR ;161 - DCD DefaultISR ;162 - DCD DefaultISR ;163 - DCD DefaultISR ;164 - DCD DefaultISR ;165 - DCD DefaultISR ;166 - DCD DefaultISR ;167 - DCD DefaultISR ;168 - DCD DefaultISR ;169 - DCD DefaultISR ;170 - DCD DefaultISR ;171 - DCD DefaultISR ;172 - DCD DefaultISR ;173 - DCD DefaultISR ;174 - DCD DefaultISR ;175 - DCD DefaultISR ;176 - DCD DefaultISR ;177 - DCD DefaultISR ;178 - DCD DefaultISR ;179 - DCD DefaultISR ;180 - DCD DefaultISR ;181 - DCD DefaultISR ;182 - DCD DefaultISR ;183 - DCD DefaultISR ;184 - DCD DefaultISR ;185 - DCD DefaultISR ;186 - DCD DefaultISR ;187 - DCD DefaultISR ;188 - DCD DefaultISR ;189 - DCD DefaultISR ;190 - DCD DefaultISR ;191 - DCD DefaultISR ;192 - DCD DefaultISR ;193 - DCD DefaultISR ;194 - DCD DefaultISR ;195 - DCD DefaultISR ;196 - DCD DefaultISR ;197 - DCD DefaultISR ;198 - DCD DefaultISR ;199 - DCD DefaultISR ;200 - DCD DefaultISR ;201 - DCD DefaultISR ;202 - DCD DefaultISR ;203 - DCD DefaultISR ;204 - DCD DefaultISR ;205 - DCD DefaultISR ;206 - DCD DefaultISR ;207 - DCD DefaultISR ;208 - DCD DefaultISR ;209 - DCD DefaultISR ;210 - DCD DefaultISR ;211 - DCD DefaultISR ;212 - DCD DefaultISR ;213 - DCD DefaultISR ;214 - DCD DefaultISR ;215 - DCD DefaultISR ;216 - DCD DefaultISR ;217 - DCD DefaultISR ;218 - DCD DefaultISR ;219 - DCD DefaultISR ;220 - DCD DefaultISR ;221 - DCD DefaultISR ;222 - DCD DefaultISR ;223 - DCD DefaultISR ;224 - DCD DefaultISR ;225 - DCD DefaultISR ;226 - DCD DefaultISR ;227 - DCD DefaultISR ;228 - DCD DefaultISR ;229 - DCD DefaultISR ;230 - DCD DefaultISR ;231 - DCD DefaultISR ;232 - DCD DefaultISR ;233 - DCD DefaultISR ;234 - DCD DefaultISR ;235 - DCD DefaultISR ;236 - DCD DefaultISR ;237 - DCD DefaultISR ;238 - DCD DefaultISR ;239 - DCD DefaultISR ;240 - DCD DefaultISR ;241 - DCD DefaultISR ;242 - DCD DefaultISR ;243 - DCD DefaultISR ;244 - DCD DefaultISR ;245 - DCD DefaultISR ;246 - DCD DefaultISR ;247 - DCD DefaultISR ;248 - DCD DefaultISR ;249 - DCD DefaultISR ;250 - DCD DefaultISR ;251 - DCD DefaultISR ;252 - DCD DefaultISR ;253 - DCD DefaultISR ;254 - DCD 0xFFFFFFFF ; Reserved for user TRIM value -__Vectors_End - -__Vectors_Size EQU __Vectors_End - __Vectors - -; Flash Configuration -; 16-byte flash configuration field that stores default protection settings (loaded on reset) -; and security information that allows the MCU to restrict access to the FTFL module. -; Backdoor Comparison Key -; Backdoor Comparison Key 0. <0x0-0xFF:2> -; Backdoor Comparison Key 1. <0x0-0xFF:2> -; Backdoor Comparison Key 2. <0x0-0xFF:2> -; Backdoor Comparison Key 3. <0x0-0xFF:2> -; Backdoor Comparison Key 4. <0x0-0xFF:2> -; Backdoor Comparison Key 5. <0x0-0xFF:2> -; Backdoor Comparison Key 6. <0x0-0xFF:2> -; Backdoor Comparison Key 7. <0x0-0xFF:2> -BackDoorK0 EQU 0xFF -BackDoorK1 EQU 0xFF -BackDoorK2 EQU 0xFF -BackDoorK3 EQU 0xFF -BackDoorK4 EQU 0xFF -BackDoorK5 EQU 0xFF -BackDoorK6 EQU 0xFF -BackDoorK7 EQU 0xFF -; -; Program flash protection bytes (FPROT) -; Each program flash region can be protected from program and erase operation by setting the associated PROT bit. -; Each bit protects a 1/32 region of the program flash memory. -; FPROT0 -; Program Flash Region Protect Register 0 -; 1/32 - 8/32 region -; FPROT0.0 -; FPROT0.1 -; FPROT0.2 -; FPROT0.3 -; FPROT0.4 -; FPROT0.5 -; FPROT0.6 -; FPROT0.7 -nFPROT0 EQU 0x00 -FPROT0 EQU nFPROT0:EOR:0xFF -; -; FPROT1 -; Program Flash Region Protect Register 1 -; 9/32 - 16/32 region -; FPROT1.0 -; FPROT1.1 -; FPROT1.2 -; FPROT1.3 -; FPROT1.4 -; FPROT1.5 -; FPROT1.6 -; FPROT1.7 -nFPROT1 EQU 0x00 -FPROT1 EQU nFPROT1:EOR:0xFF -; -; FPROT2 -; Program Flash Region Protect Register 2 -; 17/32 - 24/32 region -; FPROT2.0 -; FPROT2.1 -; FPROT2.2 -; FPROT2.3 -; FPROT2.4 -; FPROT2.5 -; FPROT2.6 -; FPROT2.7 -nFPROT2 EQU 0x00 -FPROT2 EQU nFPROT2:EOR:0xFF -; -; FPROT3 -; Program Flash Region Protect Register 3 -; 25/32 - 32/32 region -; FPROT3.0 -; FPROT3.1 -; FPROT3.2 -; FPROT3.3 -; FPROT3.4 -; FPROT3.5 -; FPROT3.6 -; FPROT3.7 -nFPROT3 EQU 0x00 -FPROT3 EQU nFPROT3:EOR:0xFF -; -; -; Data flash protection byte (FDPROT) -; Each bit protects a 1/8 region of the data flash memory. -; (Program flash only devices: Reserved) -; FDPROT.0 -; FDPROT.1 -; FDPROT.2 -; FDPROT.3 -; FDPROT.4 -; FDPROT.5 -; FDPROT.6 -; FDPROT.7 -nFDPROT EQU 0x00 -FDPROT EQU nFDPROT:EOR:0xFF -; -; EEPROM protection byte (FEPROT) -; FlexNVM devices: Each bit protects a 1/8 region of the EEPROM. -; (Program flash only devices: Reserved) -; FEPROT.0 -; FEPROT.1 -; FEPROT.2 -; FEPROT.3 -; FEPROT.4 -; FEPROT.5 -; FEPROT.6 -; FEPROT.7 -nFEPROT EQU 0x00 -FEPROT EQU nFEPROT:EOR:0xFF -; -; Flash nonvolatile option byte (FOPT) -; Allows the user to customize the operation of the MCU at boot time. -; LPBOOT -; <0=> Low-power boot -; <1=> Normal boot -; EZPORT_DIS -; <0=> EzPort operation is disabled -; <1=> EzPort operation is enabled -FOPT EQU 0xFF -; -; Flash security byte (FSEC) -; WARNING: If SEC field is configured as "MCU security status is secure" and MEEN field is configured as "Mass erase is disabled", -; MCU's security status cannot be set back to unsecure state since Mass erase via the debugger is blocked !!! -; SEC -; <2=> MCU security status is unsecure -; <3=> MCU security status is secure -; Flash Security -; FSLACC -; <2=> Freescale factory access denied -; <3=> Freescale factory access granted -; Freescale Failure Analysis Access Code -; MEEN -; <2=> Mass erase is disabled -; <3=> Mass erase is enabled -; KEYEN -; <2=> Backdoor key access enabled -; <3=> Backdoor key access disabled -; Backdoor Key Security Enable -FSEC EQU 0xFE -; -; - IF :LNOT::DEF:RAM_TARGET - AREA FlashConfig, DATA, READONLY -__FlashConfig - DCB BackDoorK0, BackDoorK1, BackDoorK2, BackDoorK3 - DCB BackDoorK4, BackDoorK5, BackDoorK6, BackDoorK7 - DCB FPROT0 , FPROT1 , FPROT2 , FPROT3 - DCB FSEC , FOPT , FEPROT , FDPROT - ENDIF - - - AREA |.text|, CODE, READONLY - -; Reset Handler - -Reset_Handler PROC - EXPORT Reset_Handler [WEAK] - IMPORT SystemInit - IMPORT __main - - IF :LNOT::DEF:RAM_TARGET - REQUIRE FlashConfig - ENDIF - - CPSID I ; Mask interrupts - LDR R0, =0xE000ED08 - LDR R1, =__Vectors - STR R1, [R0] - LDR R0, =SystemInit - BLX R0 - CPSIE i ; Unmask interrupts - LDR R0, =__main - BX R0 - ENDP - - -; Dummy Exception Handlers (infinite loops which can be modified) -NMI_Handler\ - PROC - EXPORT NMI_Handler [WEAK] - B . - ENDP -HardFault_Handler\ - PROC - EXPORT HardFault_Handler [WEAK] - B . - ENDP -MemManage_Handler\ - PROC - EXPORT MemManage_Handler [WEAK] - B . - ENDP -BusFault_Handler\ - PROC - EXPORT BusFault_Handler [WEAK] - B . - ENDP -UsageFault_Handler\ - PROC - EXPORT UsageFault_Handler [WEAK] - B . - ENDP -SVC_Handler\ - PROC - EXPORT SVC_Handler [WEAK] - B . - ENDP -DebugMon_Handler\ - PROC - EXPORT DebugMon_Handler [WEAK] - B . - ENDP -PendSV_Handler\ - PROC - EXPORT PendSV_Handler [WEAK] - B . - ENDP -SysTick_Handler\ - PROC - EXPORT SysTick_Handler [WEAK] - B . - ENDP -DMA0_IRQHandler\ - PROC - EXPORT DMA0_IRQHandler [WEAK] - LDR R0, =DMA0_DriverIRQHandler - BX R0 - ENDP - -DMA1_IRQHandler\ - PROC - EXPORT DMA1_IRQHandler [WEAK] - LDR R0, =DMA1_DriverIRQHandler - BX R0 - ENDP - -DMA2_IRQHandler\ - PROC - EXPORT DMA2_IRQHandler [WEAK] - LDR R0, =DMA2_DriverIRQHandler - BX R0 - ENDP - -DMA3_IRQHandler\ - PROC - EXPORT DMA3_IRQHandler [WEAK] - LDR R0, =DMA3_DriverIRQHandler - BX R0 - ENDP - -DMA4_IRQHandler\ - PROC - EXPORT DMA4_IRQHandler [WEAK] - LDR R0, =DMA4_DriverIRQHandler - BX R0 - ENDP - -DMA5_IRQHandler\ - PROC - EXPORT DMA5_IRQHandler [WEAK] - LDR R0, =DMA5_DriverIRQHandler - BX R0 - ENDP - -DMA6_IRQHandler\ - PROC - EXPORT DMA6_IRQHandler [WEAK] - LDR R0, =DMA6_DriverIRQHandler - BX R0 - ENDP - -DMA7_IRQHandler\ - PROC - EXPORT DMA7_IRQHandler [WEAK] - LDR R0, =DMA7_DriverIRQHandler - BX R0 - ENDP - -DMA8_IRQHandler\ - PROC - EXPORT DMA8_IRQHandler [WEAK] - LDR R0, =DMA8_DriverIRQHandler - BX R0 - ENDP - -DMA9_IRQHandler\ - PROC - EXPORT DMA9_IRQHandler [WEAK] - LDR R0, =DMA9_DriverIRQHandler - BX R0 - ENDP - -DMA10_IRQHandler\ - PROC - EXPORT DMA10_IRQHandler [WEAK] - LDR R0, =DMA10_DriverIRQHandler - BX R0 - ENDP - -DMA11_IRQHandler\ - PROC - EXPORT DMA11_IRQHandler [WEAK] - LDR R0, =DMA11_DriverIRQHandler - BX R0 - ENDP - -DMA12_IRQHandler\ - PROC - EXPORT DMA12_IRQHandler [WEAK] - LDR R0, =DMA12_DriverIRQHandler - BX R0 - ENDP - -DMA13_IRQHandler\ - PROC - EXPORT DMA13_IRQHandler [WEAK] - LDR R0, =DMA13_DriverIRQHandler - BX R0 - ENDP - -DMA14_IRQHandler\ - PROC - EXPORT DMA14_IRQHandler [WEAK] - LDR R0, =DMA14_DriverIRQHandler - BX R0 - ENDP - -DMA15_IRQHandler\ - PROC - EXPORT DMA15_IRQHandler [WEAK] - LDR R0, =DMA15_DriverIRQHandler - BX R0 - ENDP - -DMA_Error_IRQHandler\ - PROC - EXPORT DMA_Error_IRQHandler [WEAK] - LDR R0, =DMA_Error_DriverIRQHandler - BX R0 - ENDP - -I2C0_IRQHandler\ - PROC - EXPORT I2C0_IRQHandler [WEAK] - LDR R0, =I2C0_DriverIRQHandler - BX R0 - ENDP - -I2C1_IRQHandler\ - PROC - EXPORT I2C1_IRQHandler [WEAK] - LDR R0, =I2C1_DriverIRQHandler - BX R0 - ENDP - -SPI0_IRQHandler\ - PROC - EXPORT SPI0_IRQHandler [WEAK] - LDR R0, =SPI0_DriverIRQHandler - BX R0 - ENDP - -SPI1_IRQHandler\ - PROC - EXPORT SPI1_IRQHandler [WEAK] - LDR R0, =SPI1_DriverIRQHandler - BX R0 - ENDP - -I2S0_Tx_IRQHandler\ - PROC - EXPORT I2S0_Tx_IRQHandler [WEAK] - LDR R0, =I2S0_Tx_DriverIRQHandler - BX R0 - ENDP - -I2S0_Rx_IRQHandler\ - PROC - EXPORT I2S0_Rx_IRQHandler [WEAK] - LDR R0, =I2S0_Rx_DriverIRQHandler - BX R0 - ENDP - -UART0_LON_IRQHandler\ - PROC - EXPORT UART0_LON_IRQHandler [WEAK] - LDR R0, =UART0_LON_DriverIRQHandler - BX R0 - ENDP - -UART0_RX_TX_IRQHandler\ - PROC - EXPORT UART0_RX_TX_IRQHandler [WEAK] - LDR R0, =UART0_RX_TX_DriverIRQHandler - BX R0 - ENDP - -UART0_ERR_IRQHandler\ - PROC - EXPORT UART0_ERR_IRQHandler [WEAK] - LDR R0, =UART0_ERR_DriverIRQHandler - BX R0 - ENDP - -UART1_RX_TX_IRQHandler\ - PROC - EXPORT UART1_RX_TX_IRQHandler [WEAK] - LDR R0, =UART1_RX_TX_DriverIRQHandler - BX R0 - ENDP - -UART1_ERR_IRQHandler\ - PROC - EXPORT UART1_ERR_IRQHandler [WEAK] - LDR R0, =UART1_ERR_DriverIRQHandler - BX R0 - ENDP - -UART2_RX_TX_IRQHandler\ - PROC - EXPORT UART2_RX_TX_IRQHandler [WEAK] - LDR R0, =UART2_RX_TX_DriverIRQHandler - BX R0 - ENDP - -UART2_ERR_IRQHandler\ - PROC - EXPORT UART2_ERR_IRQHandler [WEAK] - LDR R0, =UART2_ERR_DriverIRQHandler - BX R0 - ENDP - -UART3_RX_TX_IRQHandler\ - PROC - EXPORT UART3_RX_TX_IRQHandler [WEAK] - LDR R0, =UART3_RX_TX_DriverIRQHandler - BX R0 - ENDP - -UART3_ERR_IRQHandler\ - PROC - EXPORT UART3_ERR_IRQHandler [WEAK] - LDR R0, =UART3_ERR_DriverIRQHandler - BX R0 - ENDP - -SPI2_IRQHandler\ - PROC - EXPORT SPI2_IRQHandler [WEAK] - LDR R0, =SPI2_DriverIRQHandler - BX R0 - ENDP - -UART4_RX_TX_IRQHandler\ - PROC - EXPORT UART4_RX_TX_IRQHandler [WEAK] - LDR R0, =UART4_RX_TX_DriverIRQHandler - BX R0 - ENDP - -UART4_ERR_IRQHandler\ - PROC - EXPORT UART4_ERR_IRQHandler [WEAK] - LDR R0, =UART4_ERR_DriverIRQHandler - BX R0 - ENDP - -UART5_RX_TX_IRQHandler\ - PROC - EXPORT UART5_RX_TX_IRQHandler [WEAK] - LDR R0, =UART5_RX_TX_DriverIRQHandler - BX R0 - ENDP - -UART5_ERR_IRQHandler\ - PROC - EXPORT UART5_ERR_IRQHandler [WEAK] - LDR R0, =UART5_ERR_DriverIRQHandler - BX R0 - ENDP - -I2C2_IRQHandler\ - PROC - EXPORT I2C2_IRQHandler [WEAK] - LDR R0, =I2C2_DriverIRQHandler - BX R0 - ENDP - -CAN0_ORed_Message_buffer_IRQHandler\ - PROC - EXPORT CAN0_ORed_Message_buffer_IRQHandler [WEAK] - LDR R0, =CAN0_DriverIRQHandler - BX R0 - ENDP - -CAN0_Bus_Off_IRQHandler\ - PROC - EXPORT CAN0_Bus_Off_IRQHandler [WEAK] - LDR R0, =CAN0_DriverIRQHandler - BX R0 - ENDP - -CAN0_Error_IRQHandler\ - PROC - EXPORT CAN0_Error_IRQHandler [WEAK] - LDR R0, =CAN0_DriverIRQHandler - BX R0 - ENDP - -CAN0_Tx_Warning_IRQHandler\ - PROC - EXPORT CAN0_Tx_Warning_IRQHandler [WEAK] - LDR R0, =CAN0_DriverIRQHandler - BX R0 - ENDP - -CAN0_Rx_Warning_IRQHandler\ - PROC - EXPORT CAN0_Rx_Warning_IRQHandler [WEAK] - LDR R0, =CAN0_DriverIRQHandler - BX R0 - ENDP - -CAN0_Wake_Up_IRQHandler\ - PROC - EXPORT CAN0_Wake_Up_IRQHandler [WEAK] - LDR R0, =CAN0_DriverIRQHandler - BX R0 - ENDP - -SDHC_IRQHandler\ - PROC - EXPORT SDHC_IRQHandler [WEAK] - LDR R0, =SDHC_DriverIRQHandler - BX R0 - ENDP - -Default_Handler\ - PROC - EXPORT DMA0_DriverIRQHandler [WEAK] - EXPORT DMA1_DriverIRQHandler [WEAK] - EXPORT DMA2_DriverIRQHandler [WEAK] - EXPORT DMA3_DriverIRQHandler [WEAK] - EXPORT DMA4_DriverIRQHandler [WEAK] - EXPORT DMA5_DriverIRQHandler [WEAK] - EXPORT DMA6_DriverIRQHandler [WEAK] - EXPORT DMA7_DriverIRQHandler [WEAK] - EXPORT DMA8_DriverIRQHandler [WEAK] - EXPORT DMA9_DriverIRQHandler [WEAK] - EXPORT DMA10_DriverIRQHandler [WEAK] - EXPORT DMA11_DriverIRQHandler [WEAK] - EXPORT DMA12_DriverIRQHandler [WEAK] - EXPORT DMA13_DriverIRQHandler [WEAK] - EXPORT DMA14_DriverIRQHandler [WEAK] - EXPORT DMA15_DriverIRQHandler [WEAK] - EXPORT DMA_Error_DriverIRQHandler [WEAK] - EXPORT MCM_IRQHandler [WEAK] - EXPORT FTFE_IRQHandler [WEAK] - EXPORT Read_Collision_IRQHandler [WEAK] - EXPORT LVD_LVW_IRQHandler [WEAK] - EXPORT LLWU_IRQHandler [WEAK] - EXPORT WDOG_EWM_IRQHandler [WEAK] - EXPORT RNG_IRQHandler [WEAK] - EXPORT I2C0_DriverIRQHandler [WEAK] - EXPORT I2C1_DriverIRQHandler [WEAK] - EXPORT SPI0_DriverIRQHandler [WEAK] - EXPORT SPI1_DriverIRQHandler [WEAK] - EXPORT I2S0_Tx_DriverIRQHandler [WEAK] - EXPORT I2S0_Rx_DriverIRQHandler [WEAK] - EXPORT UART0_LON_DriverIRQHandler [WEAK] - EXPORT UART0_RX_TX_DriverIRQHandler [WEAK] - EXPORT UART0_ERR_DriverIRQHandler [WEAK] - EXPORT UART1_RX_TX_DriverIRQHandler [WEAK] - EXPORT UART1_ERR_DriverIRQHandler [WEAK] - EXPORT UART2_RX_TX_DriverIRQHandler [WEAK] - EXPORT UART2_ERR_DriverIRQHandler [WEAK] - EXPORT UART3_RX_TX_DriverIRQHandler [WEAK] - EXPORT UART3_ERR_DriverIRQHandler [WEAK] - EXPORT ADC0_IRQHandler [WEAK] - EXPORT CMP0_IRQHandler [WEAK] - EXPORT CMP1_IRQHandler [WEAK] - EXPORT FTM0_IRQHandler [WEAK] - EXPORT FTM1_IRQHandler [WEAK] - EXPORT FTM2_IRQHandler [WEAK] - EXPORT CMT_IRQHandler [WEAK] - EXPORT RTC_IRQHandler [WEAK] - EXPORT RTC_Seconds_IRQHandler [WEAK] - EXPORT PIT0_IRQHandler [WEAK] - EXPORT PIT1_IRQHandler [WEAK] - EXPORT PIT2_IRQHandler [WEAK] - EXPORT PIT3_IRQHandler [WEAK] - EXPORT PDB0_IRQHandler [WEAK] - EXPORT USB0_IRQHandler [WEAK] - EXPORT USBDCD_IRQHandler [WEAK] - EXPORT Reserved71_IRQHandler [WEAK] - EXPORT DAC0_IRQHandler [WEAK] - EXPORT MCG_IRQHandler [WEAK] - EXPORT LPTMR0_IRQHandler [WEAK] - EXPORT PORTA_IRQHandler [WEAK] - EXPORT PORTB_IRQHandler [WEAK] - EXPORT PORTC_IRQHandler [WEAK] - EXPORT PORTD_IRQHandler [WEAK] - EXPORT PORTE_IRQHandler [WEAK] - EXPORT SWI_IRQHandler [WEAK] - EXPORT SPI2_DriverIRQHandler [WEAK] - EXPORT UART4_RX_TX_DriverIRQHandler [WEAK] - EXPORT UART4_ERR_DriverIRQHandler [WEAK] - EXPORT UART5_RX_TX_DriverIRQHandler [WEAK] - EXPORT UART5_ERR_DriverIRQHandler [WEAK] - EXPORT CMP2_IRQHandler [WEAK] - EXPORT FTM3_IRQHandler [WEAK] - EXPORT DAC1_IRQHandler [WEAK] - EXPORT ADC1_IRQHandler [WEAK] - EXPORT I2C2_DriverIRQHandler [WEAK] - EXPORT CAN0_DriverIRQHandler [WEAK] - EXPORT SDHC_DriverIRQHandler [WEAK] - EXPORT Reserved98_IRQHandler [WEAK] - EXPORT Reserved99_IRQHandler [WEAK] - EXPORT Reserved100_IRQHandler [WEAK] - EXPORT Reserved101_IRQHandler [WEAK] - EXPORT DefaultISR [WEAK] -DMA0_DriverIRQHandler -DMA1_DriverIRQHandler -DMA2_DriverIRQHandler -DMA3_DriverIRQHandler -DMA4_DriverIRQHandler -DMA5_DriverIRQHandler -DMA6_DriverIRQHandler -DMA7_DriverIRQHandler -DMA8_DriverIRQHandler -DMA9_DriverIRQHandler -DMA10_DriverIRQHandler -DMA11_DriverIRQHandler -DMA12_DriverIRQHandler -DMA13_DriverIRQHandler -DMA14_DriverIRQHandler -DMA15_DriverIRQHandler -DMA_Error_DriverIRQHandler -MCM_IRQHandler -FTFE_IRQHandler -Read_Collision_IRQHandler -LVD_LVW_IRQHandler -LLWU_IRQHandler -WDOG_EWM_IRQHandler -RNG_IRQHandler -I2C0_DriverIRQHandler -I2C1_DriverIRQHandler -SPI0_DriverIRQHandler -SPI1_DriverIRQHandler -I2S0_Tx_DriverIRQHandler -I2S0_Rx_DriverIRQHandler -UART0_LON_DriverIRQHandler -UART0_RX_TX_DriverIRQHandler -UART0_ERR_DriverIRQHandler -UART1_RX_TX_DriverIRQHandler -UART1_ERR_DriverIRQHandler -UART2_RX_TX_DriverIRQHandler -UART2_ERR_DriverIRQHandler -UART3_RX_TX_DriverIRQHandler -UART3_ERR_DriverIRQHandler -ADC0_IRQHandler -CMP0_IRQHandler -CMP1_IRQHandler -FTM0_IRQHandler -FTM1_IRQHandler -FTM2_IRQHandler -CMT_IRQHandler -RTC_IRQHandler -RTC_Seconds_IRQHandler -PIT0_IRQHandler -PIT1_IRQHandler -PIT2_IRQHandler -PIT3_IRQHandler -PDB0_IRQHandler -USB0_IRQHandler -USBDCD_IRQHandler -Reserved71_IRQHandler -DAC0_IRQHandler -MCG_IRQHandler -LPTMR0_IRQHandler -PORTA_IRQHandler -PORTB_IRQHandler -PORTC_IRQHandler -PORTD_IRQHandler -PORTE_IRQHandler -SWI_IRQHandler -SPI2_DriverIRQHandler -UART4_RX_TX_DriverIRQHandler -UART4_ERR_DriverIRQHandler -UART5_RX_TX_DriverIRQHandler -UART5_ERR_DriverIRQHandler -CMP2_IRQHandler -FTM3_IRQHandler -DAC1_IRQHandler -ADC1_IRQHandler -I2C2_DriverIRQHandler -CAN0_DriverIRQHandler -SDHC_DriverIRQHandler -Reserved98_IRQHandler -Reserved99_IRQHandler -Reserved100_IRQHandler -Reserved101_IRQHandler -DefaultISR - B DefaultISR - ENDP - ALIGN - - - END diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/device/TOOLCHAIN_GCC_ARM/MK24FN1M0xxx12.ld b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/device/TOOLCHAIN_GCC_ARM/MK24FN1M0xxx12.ld deleted file mode 100644 index 4847b765165..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/device/TOOLCHAIN_GCC_ARM/MK24FN1M0xxx12.ld +++ /dev/null @@ -1,363 +0,0 @@ -/* -** ################################################################### -** Processors: MK64FN1M0VDC12 -** MK64FN1M0VLL12 -** MK64FN1M0VLQ12 -** MK64FN1M0VMD12 -** -** Compiler: GNU C Compiler -** Reference manual: K64P144M120SF5RM, Rev.2, January 2014 -** Version: rev. 2.8, 2015-02-19 -** Build: b151217 -** -** Abstract: -** Linker file for the GNU C Compiler -** -** Copyright (c) 2015 Freescale Semiconductor, Inc. -** All rights reserved. -** -** Redistribution and use in source and binary forms, with or without modification, -** are permitted provided that the following conditions are met: -** -** o Redistributions of source code must retain the above copyright notice, this list -** of conditions and the following disclaimer. -** -** o Redistributions in binary form must reproduce the above copyright notice, this -** list of conditions and the following disclaimer in the documentation and/or -** other materials provided with the distribution. -** -** o Neither the name of Freescale Semiconductor, Inc. nor the names of its -** contributors may be used to endorse or promote products derived from this -** software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -** ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -** LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -** ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -** -** http: www.freescale.com -** mail: support@freescale.com -** -** ################################################################### -*/ - -/* Entry Point */ -ENTRY(Reset_Handler) - -__ram_vector_table__ = 1; - -/* Heap 1/4 of ram and stack 1/8 */ -__stack_size__ = 0x8000; -__heap_size__ = 0x10000; - -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; - -/* 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 = 0x000FFBF0 - m_data (RW) : ORIGIN = 0x1FFF0000, LENGTH = 0x00010000 - m_data_2 (RW) : ORIGIN = 0x20000000, LENGTH = 0x00030000 -} - -/* Define output sections */ -SECTIONS -{ - /* The startup code goes first into internal flash */ - .interrupts : - { - __VECTOR_TABLE = .; - . = ALIGN(4); - KEEP(*(.isr_vector)) /* Startup code */ - . = ALIGN(4); - } > m_interrupts - - .flash_config : - { - . = ALIGN(4); - KEEP(*(.FlashConfig)) /* Flash Configuration Field (FCF) */ - . = ALIGN(4); - } > m_flash_config - - /* The program code and other data goes into internal flash */ - /* Note: The uVisor expects this section at a fixed location, as specified by - * the porting process configuration parameter: FLASH_OFFSET. */ - __UVISOR_TEXT_OFFSET = 0x410; - __UVISOR_TEXT_START = ORIGIN(m_interrupts) + __UVISOR_TEXT_OFFSET; - .text __UVISOR_TEXT_START : - { - /* uVisor code and data */ - . = ALIGN(4); - __uvisor_main_start = .; - *(.uvisor.main) - __uvisor_main_end = .; - - . = ALIGN(4); - *(.text) /* .text sections (code) */ - *(.text*) /* .text* sections (code) */ - *(.rodata) /* .rodata sections (constants, strings, etc.) */ - *(.rodata*) /* .rodata* sections (constants, strings, etc.) */ - *(.glue_7) /* glue arm to thumb code */ - *(.glue_7t) /* glue thumb to arm code */ - *(.eh_frame) - KEEP (*(.init)) - KEEP (*(.fini)) - . = ALIGN(4); - } > m_text - - .ARM.extab : - { - *(.ARM.extab* .gnu.linkonce.armextab.*) - } > m_text - - .ARM : - { - __exidx_start = .; - *(.ARM.exidx*) - __exidx_end = .; - } > m_text - - .ctors : - { - __CTOR_LIST__ = .; - /* gcc uses crtbegin.o to find the start of - the constructors, so we make sure it is - first. Because this is a wildcard, it - doesn't matter if the user does not - actually link against crtbegin.o; the - linker won't look for a file to match a - wildcard. The wildcard also means that it - doesn't matter which directory crtbegin.o - is in. */ - KEEP (*crtbegin.o(.ctors)) - KEEP (*crtbegin?.o(.ctors)) - /* We don't want to include the .ctor section from - from the crtend.o file until after the sorted ctors. - The .ctor section from the crtend file contains the - end of ctors marker and it must be last */ - KEEP (*(EXCLUDE_FILE(*crtend?.o *crtend.o) .ctors)) - KEEP (*(SORT(.ctors.*))) - KEEP (*(.ctors)) - __CTOR_END__ = .; - } > m_text - - .dtors : - { - __DTOR_LIST__ = .; - KEEP (*crtbegin.o(.dtors)) - KEEP (*crtbegin?.o(.dtors)) - KEEP (*(EXCLUDE_FILE(*crtend?.o *crtend.o) .dtors)) - KEEP (*(SORT(.dtors.*))) - KEEP (*(.dtors)) - __DTOR_END__ = .; - } > m_text - - .preinit_array : - { - PROVIDE_HIDDEN (__preinit_array_start = .); - KEEP (*(.preinit_array*)) - PROVIDE_HIDDEN (__preinit_array_end = .); - } > m_text - - .init_array : - { - PROVIDE_HIDDEN (__init_array_start = .); - KEEP (*(SORT(.init_array.*))) - KEEP (*(.init_array*)) - PROVIDE_HIDDEN (__init_array_end = .); - } > m_text - - .fini_array : - { - PROVIDE_HIDDEN (__fini_array_start = .); - KEEP (*(SORT(.fini_array.*))) - KEEP (*(.fini_array*)) - PROVIDE_HIDDEN (__fini_array_end = .); - } > m_text - - .interrupts_ram : - { - . = ALIGN(4); - __VECTOR_RAM__ = .; - __interrupts_ram_start__ = .; /* Create a global symbol at data start */ - *(.m_interrupts_ram) /* This is a user defined section */ - . += M_VECTOR_RAM_SIZE; - . = ALIGN(4); - __interrupts_ram_end__ = .; /* Define a global symbol at data end */ - } > m_data - - /* Ensure that the uVisor BSS section is put first after the relocated - * interrupt table in SRAM. */ - /* Note: The uVisor expects this section at a fixed location, as specified by - * the porting process configuration parameter: SRAM_OFFSET. */ - __UVISOR_SRAM_OFFSET = 0x400; - __UVISOR_BSS_START = ORIGIN(m_data) + __UVISOR_SRAM_OFFSET; - ASSERT(__interrupts_ram_end__ <= __UVISOR_BSS_START, - "The ISR relocation region overlaps with the uVisor BSS section.") - .uvisor.bss __UVISOR_BSS_START (NOLOAD): - { - . = ALIGN(32); - __uvisor_bss_start = .; - - /* protected uvisor main bss */ - . = ALIGN(32); - __uvisor_bss_main_start = .; - KEEP(*(.keep.uvisor.bss.main)) - . = ALIGN(32); - __uvisor_bss_main_end = .; - - /* protected uvisor secure boxes bss */ - . = ALIGN(32); - __uvisor_bss_boxes_start = .; - KEEP(*(.keep.uvisor.bss.boxes)) - . = ALIGN(32); - __uvisor_bss_boxes_end = .; - - . = ALIGN(32); - __uvisor_bss_end = .; - } > m_data - - /* Heap space for the page allocator */ - .page_heap (NOLOAD) : - { - . = ALIGN(32); - __uvisor_page_start = .; - KEEP(*(.keep.uvisor.page_heap)) - . = ALIGN(32); - __uvisor_page_end = .; - } > m_data_2 - - __VECTOR_RAM = DEFINED(__ram_vector_table__) ? __VECTOR_RAM__ : ORIGIN(m_interrupts); - __RAM_VECTOR_TABLE_SIZE_BYTES = DEFINED(__ram_vector_table__) ? (__interrupts_ram_end__ - __interrupts_ram_start__) : 0x0; - - .data : - { - PROVIDE(__etext = LOADADDR(.data)); /* Define a global symbol at end of code, */ - PROVIDE(__DATA_ROM = LOADADDR(.data)); /* Symbol is used by startup for data initialization. */ - . = ALIGN(4); - __DATA_RAM = .; - __data_start__ = .; /* create a global symbol at data start */ - *(.data) /* .data sections */ - *(.data*) /* .data* sections */ - KEEP(*(.jcr*)) - . = ALIGN(4); - __data_end__ = .; /* define a global symbol at data end */ - } > m_data_2 AT > m_text - - __DATA_END = __DATA_ROM + (__data_end__ - __data_start__); - text_end = ORIGIN(m_text) + LENGTH(m_text); - ASSERT(__DATA_END <= text_end, "region m_text overflowed with text and data") - - /* uVisor configuration section - * This section must be located after all other flash regions. */ - .uvisor.secure : - { - . = ALIGN(32); - __uvisor_secure_start = .; - - /* uVisor secure boxes configuration tables */ - . = ALIGN(32); - __uvisor_cfgtbl_start = .; - KEEP(*(.keep.uvisor.cfgtbl)) - . = ALIGN(32); - __uvisor_cfgtbl_end = .; - - /* Pointers to the uVisor secure boxes configuration tables */ - /* Note: Do not add any further alignment here, as uVisor will need to have - * access to the exact list of pointers. */ - __uvisor_cfgtbl_ptr_start = .; - KEEP(*(.keep.uvisor.cfgtbl_ptr_first)) - KEEP(*(.keep.uvisor.cfgtbl_ptr)) - __uvisor_cfgtbl_ptr_end = .; - - /* Pointers to all boxes register gateways. These are grouped here to allow - * discoverability and firmware verification. */ - __uvisor_register_gateway_ptr_start = .; - KEEP(*(.keep.uvisor.register_gateway_ptr)) - __uvisor_register_gateway_ptr_end = .; - - . = ALIGN(32); - __uvisor_secure_end = .; - } > m_text - - /* Uninitialized data section - * This region is not initialized by the C/C++ library and can be used to - * store state across soft reboots. */ - .uninitialized (NOLOAD): - { - . = ALIGN(32); - __uninitialized_start = .; - *(.uninitialized) - KEEP(*(.keep.uninitialized)) - . = ALIGN(32); - __uninitialized_end = .; - } > m_data_2 - - USB_RAM_GAP = DEFINED(__usb_ram_size__) ? __usb_ram_size__ : 0x800; - /* Uninitialized data section */ - .bss : - { - /* This is used by the startup in order to initialize the .bss section */ - . = ALIGN(4); - __START_BSS = .; - __bss_start__ = .; - *(.bss) - *(.bss*) - . = ALIGN(512); - USB_RAM_START = .; - . += USB_RAM_GAP; - *(COMMON) - . = ALIGN(4); - __bss_end__ = .; - __END_BSS = .; - } > m_data_2 - - .heap : - { - . = ALIGN(8); - __uvisor_heap_start = .; - __end__ = .; - PROVIDE(end = .); - __HeapBase = .; - . += HEAP_SIZE; - __HeapLimit = .; - __heap_limit = .; /* Add for _sbrk */ - __uvisor_heap_end = .; - } > m_data_2 - - m_usb_bdt USB_RAM_START (NOLOAD) : - { - *(m_usb_bdt) - USB_RAM_BDT_END = .; - } - - m_usb_global USB_RAM_BDT_END (NOLOAD) : - { - *(m_usb_global) - } - - /* Initializes stack on the end of block */ - __StackTop = ORIGIN(m_data_2) + LENGTH(m_data_2); - __StackLimit = __StackTop - STACK_SIZE; - PROVIDE(__stack = __StackTop); - - .ARM.attributes 0 : { *(.ARM.attributes) } - - ASSERT(__StackLimit >= __HeapLimit, "region m_data_2 overflowed with stack and heap") - - /* Provide the physical memory boundaries for uVisor. */ - __uvisor_flash_start = ORIGIN(m_interrupts); - __uvisor_flash_end = ORIGIN(m_text) + LENGTH(m_text); - __uvisor_sram_start = ORIGIN(m_data); - __uvisor_sram_end = ORIGIN(m_data_2) + LENGTH(m_data_2); -} diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/device/TOOLCHAIN_GCC_ARM/startup_MK24F12.S b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/device/TOOLCHAIN_GCC_ARM/startup_MK24F12.S deleted file mode 100644 index d9e1c5b92ba..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/device/TOOLCHAIN_GCC_ARM/startup_MK24F12.S +++ /dev/null @@ -1,958 +0,0 @@ -/* ---------------------------------------------------------------------------------------*/ -/* @file: startup_MK24F12.s */ -/* @purpose: CMSIS Cortex-M4 Core Device Startup File */ -/* MK24F12 */ -/* @version: 2.8 */ -/* @date: 2016-3-21 */ -/* @build: b170112 */ -/* ---------------------------------------------------------------------------------------*/ -/* */ -/* Copyright (c) 1997 - 2016, Freescale Semiconductor, Inc. */ -/* Copyright 2016 - 2017 NXP */ -/* Redistribution and use in source and binary forms, with or without modification, */ -/* are permitted provided that the following conditions are met: */ -/* */ -/* o Redistributions of source code must retain the above copyright notice, this list */ -/* of conditions and the following disclaimer. */ -/* */ -/* o Redistributions in binary form must reproduce the above copyright notice, this */ -/* list of conditions and the following disclaimer in the documentation and/or */ -/* other materials provided with the distribution. */ -/* */ -/* o Neither the name of the copyright holder nor the names of its */ -/* contributors may be used to endorse or promote products derived from this */ -/* software without specific prior written permission. */ -/* */ -/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND */ -/* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED */ -/* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */ -/* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR */ -/* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES */ -/* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; */ -/* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON */ -/* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT */ -/* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS */ -/* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/*****************************************************************************/ -/* Version: GCC for ARM Embedded Processors */ -/*****************************************************************************/ - .syntax unified - .arch armv7-m - - .section .isr_vector, "a" - .align 2 - .globl __isr_vector -__isr_vector: - .long __StackTop /* Top of Stack */ - .long Reset_Handler /* Reset Handler */ - .long NMI_Handler /* NMI Handler*/ - .long HardFault_Handler /* Hard Fault Handler*/ - .long MemManage_Handler /* MPU Fault Handler*/ - .long BusFault_Handler /* Bus Fault Handler*/ - .long UsageFault_Handler /* Usage Fault Handler*/ - .long 0 /* Reserved*/ - .long 0 /* Reserved*/ - .long 0 /* Reserved*/ - .long 0 /* Reserved*/ - .long SVC_Handler /* SVCall Handler*/ - .long DebugMon_Handler /* Debug Monitor Handler*/ - .long 0 /* Reserved*/ - .long PendSV_Handler /* PendSV Handler*/ - .long SysTick_Handler /* SysTick Handler*/ - - /* External Interrupts*/ - .long DMA0_IRQHandler /* DMA Channel 0 Transfer Complete*/ - .long DMA1_IRQHandler /* DMA Channel 1 Transfer Complete*/ - .long DMA2_IRQHandler /* DMA Channel 2 Transfer Complete*/ - .long DMA3_IRQHandler /* DMA Channel 3 Transfer Complete*/ - .long DMA4_IRQHandler /* DMA Channel 4 Transfer Complete*/ - .long DMA5_IRQHandler /* DMA Channel 5 Transfer Complete*/ - .long DMA6_IRQHandler /* DMA Channel 6 Transfer Complete*/ - .long DMA7_IRQHandler /* DMA Channel 7 Transfer Complete*/ - .long DMA8_IRQHandler /* DMA Channel 8 Transfer Complete*/ - .long DMA9_IRQHandler /* DMA Channel 9 Transfer Complete*/ - .long DMA10_IRQHandler /* DMA Channel 10 Transfer Complete*/ - .long DMA11_IRQHandler /* DMA Channel 11 Transfer Complete*/ - .long DMA12_IRQHandler /* DMA Channel 12 Transfer Complete*/ - .long DMA13_IRQHandler /* DMA Channel 13 Transfer Complete*/ - .long DMA14_IRQHandler /* DMA Channel 14 Transfer Complete*/ - .long DMA15_IRQHandler /* DMA Channel 15 Transfer Complete*/ - .long DMA_Error_IRQHandler /* DMA Error Interrupt*/ - .long MCM_IRQHandler /* Normal Interrupt*/ - .long FTFE_IRQHandler /* FTFE Command complete interrupt*/ - .long Read_Collision_IRQHandler /* Read Collision Interrupt*/ - .long LVD_LVW_IRQHandler /* Low Voltage Detect, Low Voltage Warning*/ - .long LLWU_IRQHandler /* Low Leakage Wakeup Unit*/ - .long WDOG_EWM_IRQHandler /* WDOG Interrupt*/ - .long RNG_IRQHandler /* RNG Interrupt*/ - .long I2C0_IRQHandler /* I2C0 interrupt*/ - .long I2C1_IRQHandler /* I2C1 interrupt*/ - .long SPI0_IRQHandler /* SPI0 Interrupt*/ - .long SPI1_IRQHandler /* SPI1 Interrupt*/ - .long I2S0_Tx_IRQHandler /* I2S0 transmit interrupt*/ - .long I2S0_Rx_IRQHandler /* I2S0 receive interrupt*/ - .long UART0_LON_IRQHandler /* UART0 LON interrupt*/ - .long UART0_RX_TX_IRQHandler /* UART0 Receive/Transmit interrupt*/ - .long UART0_ERR_IRQHandler /* UART0 Error interrupt*/ - .long UART1_RX_TX_IRQHandler /* UART1 Receive/Transmit interrupt*/ - .long UART1_ERR_IRQHandler /* UART1 Error interrupt*/ - .long UART2_RX_TX_IRQHandler /* UART2 Receive/Transmit interrupt*/ - .long UART2_ERR_IRQHandler /* UART2 Error interrupt*/ - .long UART3_RX_TX_IRQHandler /* UART3 Receive/Transmit interrupt*/ - .long UART3_ERR_IRQHandler /* UART3 Error interrupt*/ - .long ADC0_IRQHandler /* ADC0 interrupt*/ - .long CMP0_IRQHandler /* CMP0 interrupt*/ - .long CMP1_IRQHandler /* CMP1 interrupt*/ - .long FTM0_IRQHandler /* FTM0 fault, overflow and channels interrupt*/ - .long FTM1_IRQHandler /* FTM1 fault, overflow and channels interrupt*/ - .long FTM2_IRQHandler /* FTM2 fault, overflow and channels interrupt*/ - .long CMT_IRQHandler /* CMT interrupt*/ - .long RTC_IRQHandler /* RTC interrupt*/ - .long RTC_Seconds_IRQHandler /* RTC seconds interrupt*/ - .long PIT0_IRQHandler /* PIT timer channel 0 interrupt*/ - .long PIT1_IRQHandler /* PIT timer channel 1 interrupt*/ - .long PIT2_IRQHandler /* PIT timer channel 2 interrupt*/ - .long PIT3_IRQHandler /* PIT timer channel 3 interrupt*/ - .long PDB0_IRQHandler /* PDB0 Interrupt*/ - .long USB0_IRQHandler /* USB0 interrupt*/ - .long USBDCD_IRQHandler /* USBDCD Interrupt*/ - .long Reserved71_IRQHandler /* Reserved interrupt 71*/ - .long DAC0_IRQHandler /* DAC0 interrupt*/ - .long MCG_IRQHandler /* MCG Interrupt*/ - .long LPTMR0_IRQHandler /* LPTimer interrupt*/ - .long PORTA_IRQHandler /* Port A interrupt*/ - .long PORTB_IRQHandler /* Port B interrupt*/ - .long PORTC_IRQHandler /* Port C interrupt*/ - .long PORTD_IRQHandler /* Port D interrupt*/ - .long PORTE_IRQHandler /* Port E interrupt*/ - .long SWI_IRQHandler /* Software interrupt*/ - .long SPI2_IRQHandler /* SPI2 Interrupt*/ - .long UART4_RX_TX_IRQHandler /* UART4 Receive/Transmit interrupt*/ - .long UART4_ERR_IRQHandler /* UART4 Error interrupt*/ - .long UART5_RX_TX_IRQHandler /* UART5 Receive/Transmit interrupt*/ - .long UART5_ERR_IRQHandler /* UART5 Error interrupt*/ - .long CMP2_IRQHandler /* CMP2 interrupt*/ - .long FTM3_IRQHandler /* FTM3 fault, overflow and channels interrupt*/ - .long DAC1_IRQHandler /* DAC1 interrupt*/ - .long ADC1_IRQHandler /* ADC1 interrupt*/ - .long I2C2_IRQHandler /* I2C2 interrupt*/ - .long CAN0_ORed_Message_buffer_IRQHandler /* CAN0 OR'd message buffers interrupt*/ - .long CAN0_Bus_Off_IRQHandler /* CAN0 bus off interrupt*/ - .long CAN0_Error_IRQHandler /* CAN0 error interrupt*/ - .long CAN0_Tx_Warning_IRQHandler /* CAN0 Tx warning interrupt*/ - .long CAN0_Rx_Warning_IRQHandler /* CAN0 Rx warning interrupt*/ - .long CAN0_Wake_Up_IRQHandler /* CAN0 wake up interrupt*/ - .long SDHC_IRQHandler /* SDHC interrupt*/ - .long Reserved98_IRQHandler /* Reserved interrupt 98*/ - .long Reserved99_IRQHandler /* Reserved interrupt 99*/ - .long Reserved100_IRQHandler /* Reserved interrupt 100*/ - .long Reserved101_IRQHandler /* Reserved interrupt 101*/ - .long DefaultISR /* 102*/ - .long DefaultISR /* 103*/ - .long DefaultISR /* 104*/ - .long DefaultISR /* 105*/ - .long DefaultISR /* 106*/ - .long DefaultISR /* 107*/ - .long DefaultISR /* 108*/ - .long DefaultISR /* 109*/ - .long DefaultISR /* 110*/ - .long DefaultISR /* 111*/ - .long DefaultISR /* 112*/ - .long DefaultISR /* 113*/ - .long DefaultISR /* 114*/ - .long DefaultISR /* 115*/ - .long DefaultISR /* 116*/ - .long DefaultISR /* 117*/ - .long DefaultISR /* 118*/ - .long DefaultISR /* 119*/ - .long DefaultISR /* 120*/ - .long DefaultISR /* 121*/ - .long DefaultISR /* 122*/ - .long DefaultISR /* 123*/ - .long DefaultISR /* 124*/ - .long DefaultISR /* 125*/ - .long DefaultISR /* 126*/ - .long DefaultISR /* 127*/ - .long DefaultISR /* 128*/ - .long DefaultISR /* 129*/ - .long DefaultISR /* 130*/ - .long DefaultISR /* 131*/ - .long DefaultISR /* 132*/ - .long DefaultISR /* 133*/ - .long DefaultISR /* 134*/ - .long DefaultISR /* 135*/ - .long DefaultISR /* 136*/ - .long DefaultISR /* 137*/ - .long DefaultISR /* 138*/ - .long DefaultISR /* 139*/ - .long DefaultISR /* 140*/ - .long DefaultISR /* 141*/ - .long DefaultISR /* 142*/ - .long DefaultISR /* 143*/ - .long DefaultISR /* 144*/ - .long DefaultISR /* 145*/ - .long DefaultISR /* 146*/ - .long DefaultISR /* 147*/ - .long DefaultISR /* 148*/ - .long DefaultISR /* 149*/ - .long DefaultISR /* 150*/ - .long DefaultISR /* 151*/ - .long DefaultISR /* 152*/ - .long DefaultISR /* 153*/ - .long DefaultISR /* 154*/ - .long DefaultISR /* 155*/ - .long DefaultISR /* 156*/ - .long DefaultISR /* 157*/ - .long DefaultISR /* 158*/ - .long DefaultISR /* 159*/ - .long DefaultISR /* 160*/ - .long DefaultISR /* 161*/ - .long DefaultISR /* 162*/ - .long DefaultISR /* 163*/ - .long DefaultISR /* 164*/ - .long DefaultISR /* 165*/ - .long DefaultISR /* 166*/ - .long DefaultISR /* 167*/ - .long DefaultISR /* 168*/ - .long DefaultISR /* 169*/ - .long DefaultISR /* 170*/ - .long DefaultISR /* 171*/ - .long DefaultISR /* 172*/ - .long DefaultISR /* 173*/ - .long DefaultISR /* 174*/ - .long DefaultISR /* 175*/ - .long DefaultISR /* 176*/ - .long DefaultISR /* 177*/ - .long DefaultISR /* 178*/ - .long DefaultISR /* 179*/ - .long DefaultISR /* 180*/ - .long DefaultISR /* 181*/ - .long DefaultISR /* 182*/ - .long DefaultISR /* 183*/ - .long DefaultISR /* 184*/ - .long DefaultISR /* 185*/ - .long DefaultISR /* 186*/ - .long DefaultISR /* 187*/ - .long DefaultISR /* 188*/ - .long DefaultISR /* 189*/ - .long DefaultISR /* 190*/ - .long DefaultISR /* 191*/ - .long DefaultISR /* 192*/ - .long DefaultISR /* 193*/ - .long DefaultISR /* 194*/ - .long DefaultISR /* 195*/ - .long DefaultISR /* 196*/ - .long DefaultISR /* 197*/ - .long DefaultISR /* 198*/ - .long DefaultISR /* 199*/ - .long DefaultISR /* 200*/ - .long DefaultISR /* 201*/ - .long DefaultISR /* 202*/ - .long DefaultISR /* 203*/ - .long DefaultISR /* 204*/ - .long DefaultISR /* 205*/ - .long DefaultISR /* 206*/ - .long DefaultISR /* 207*/ - .long DefaultISR /* 208*/ - .long DefaultISR /* 209*/ - .long DefaultISR /* 210*/ - .long DefaultISR /* 211*/ - .long DefaultISR /* 212*/ - .long DefaultISR /* 213*/ - .long DefaultISR /* 214*/ - .long DefaultISR /* 215*/ - .long DefaultISR /* 216*/ - .long DefaultISR /* 217*/ - .long DefaultISR /* 218*/ - .long DefaultISR /* 219*/ - .long DefaultISR /* 220*/ - .long DefaultISR /* 221*/ - .long DefaultISR /* 222*/ - .long DefaultISR /* 223*/ - .long DefaultISR /* 224*/ - .long DefaultISR /* 225*/ - .long DefaultISR /* 226*/ - .long DefaultISR /* 227*/ - .long DefaultISR /* 228*/ - .long DefaultISR /* 229*/ - .long DefaultISR /* 230*/ - .long DefaultISR /* 231*/ - .long DefaultISR /* 232*/ - .long DefaultISR /* 233*/ - .long DefaultISR /* 234*/ - .long DefaultISR /* 235*/ - .long DefaultISR /* 236*/ - .long DefaultISR /* 237*/ - .long DefaultISR /* 238*/ - .long DefaultISR /* 239*/ - .long DefaultISR /* 240*/ - .long DefaultISR /* 241*/ - .long DefaultISR /* 242*/ - .long DefaultISR /* 243*/ - .long DefaultISR /* 244*/ - .long DefaultISR /* 245*/ - .long DefaultISR /* 246*/ - .long DefaultISR /* 247*/ - .long DefaultISR /* 248*/ - .long DefaultISR /* 249*/ - .long DefaultISR /* 250*/ - .long DefaultISR /* 251*/ - .long DefaultISR /* 252*/ - .long DefaultISR /* 253*/ - .long DefaultISR /* 254*/ - .long 0xFFFFFFFF /* Reserved for user TRIM value*/ - - .size __isr_vector, . - __isr_vector - -/* Flash Configuration */ - .section .FlashConfig, "a" - .long 0xFFFFFFFF - .long 0xFFFFFFFF - .long 0xFFFFFFFF - .long 0xFFFFFFFE - - .text - .thumb - -/* Reset Handler */ - - .thumb_func - .align 2 - .globl Reset_Handler - .weak Reset_Handler - .type Reset_Handler, %function -Reset_Handler: - cpsid i /* Mask interrupts */ - .equ VTOR, 0xE000ED08 - ldr r0, =VTOR - ldr r1, =__isr_vector - str r1, [r0] - ldr r2, [r1] - msr msp, r2 -#ifndef __NO_SYSTEM_INIT - ldr r0,=SystemInit - blx r0 -#endif -/* Loop to copy data from read only memory to RAM. The ranges - * of copy from/to are specified by following symbols evaluated in - * linker script. - * __etext: End of code section, i.e., begin of data sections to copy from. - * __data_start__/__data_end__: RAM address range that data should be - * copied to. Both must be aligned to 4 bytes boundary. */ - - ldr r1, =__etext - ldr r2, =__data_start__ - ldr r3, =__data_end__ - -#if 1 -/* Here are two copies of loop implemenations. First one favors code size - * and the second one favors performance. Default uses the first one. - * Change to "#if 0" to use the second one */ -.LC0: - cmp r2, r3 - ittt lt - ldrlt r0, [r1], #4 - strlt r0, [r2], #4 - blt .LC0 -#else - subs r3, r2 - ble .LC1 -.LC0: - subs r3, #4 - ldr r0, [r1, r3] - str r0, [r2, r3] - bgt .LC0 -.LC1: -#endif - -#ifdef __STARTUP_CLEAR_BSS -/* This part of work usually is done in C library startup code. Otherwise, - * define this macro to enable it in this startup. - * - * Loop to zero out BSS section, which uses following symbols - * in linker script: - * __bss_start__: start of BSS section. Must align to 4 - * __bss_end__: end of BSS section. Must align to 4 - */ - ldr r1, =__bss_start__ - ldr r2, =__bss_end__ - - movs r0, 0 -.LC2: - cmp r1, r2 - itt lt - strlt r0, [r1], #4 - blt .LC2 -#endif /* __STARTUP_CLEAR_BSS */ - - cpsie i /* Unmask interrupts */ -#ifndef __START -#define __START _start -#endif -#ifndef __ATOLLIC__ - ldr r0,=__START - blx r0 -#else - ldr r0,=__libc_init_array - blx r0 - ldr r0,=main - bx r0 -#endif - .pool - .size Reset_Handler, . - Reset_Handler - - .align 1 - .thumb_func - .weak DefaultISR - .type DefaultISR, %function -DefaultISR: - b DefaultISR - .size DefaultISR, . - DefaultISR - - .align 1 - .thumb_func - .weak NMI_Handler - .type NMI_Handler, %function -NMI_Handler: - ldr r0,=NMI_Handler - bx r0 - .size NMI_Handler, . - NMI_Handler - - .align 1 - .thumb_func - .weak HardFault_Handler - .type HardFault_Handler, %function -HardFault_Handler: - ldr r0,=HardFault_Handler - bx r0 - .size HardFault_Handler, . - HardFault_Handler - - .align 1 - .thumb_func - .weak SVC_Handler - .type SVC_Handler, %function -SVC_Handler: - ldr r0,=SVC_Handler - bx r0 - .size SVC_Handler, . - SVC_Handler - - .align 1 - .thumb_func - .weak PendSV_Handler - .type PendSV_Handler, %function -PendSV_Handler: - ldr r0,=PendSV_Handler - bx r0 - .size PendSV_Handler, . - PendSV_Handler - - .align 1 - .thumb_func - .weak SysTick_Handler - .type SysTick_Handler, %function -SysTick_Handler: - ldr r0,=SysTick_Handler - bx r0 - .size SysTick_Handler, . - SysTick_Handler - - .align 1 - .thumb_func - .weak DMA0_IRQHandler - .type DMA0_IRQHandler, %function -DMA0_IRQHandler: - ldr r0,=DMA0_DriverIRQHandler - bx r0 - .size DMA0_IRQHandler, . - DMA0_IRQHandler - - .align 1 - .thumb_func - .weak DMA1_IRQHandler - .type DMA1_IRQHandler, %function -DMA1_IRQHandler: - ldr r0,=DMA1_DriverIRQHandler - bx r0 - .size DMA1_IRQHandler, . - DMA1_IRQHandler - - .align 1 - .thumb_func - .weak DMA2_IRQHandler - .type DMA2_IRQHandler, %function -DMA2_IRQHandler: - ldr r0,=DMA2_DriverIRQHandler - bx r0 - .size DMA2_IRQHandler, . - DMA2_IRQHandler - - .align 1 - .thumb_func - .weak DMA3_IRQHandler - .type DMA3_IRQHandler, %function -DMA3_IRQHandler: - ldr r0,=DMA3_DriverIRQHandler - bx r0 - .size DMA3_IRQHandler, . - DMA3_IRQHandler - - .align 1 - .thumb_func - .weak DMA4_IRQHandler - .type DMA4_IRQHandler, %function -DMA4_IRQHandler: - ldr r0,=DMA4_DriverIRQHandler - bx r0 - .size DMA4_IRQHandler, . - DMA4_IRQHandler - - .align 1 - .thumb_func - .weak DMA5_IRQHandler - .type DMA5_IRQHandler, %function -DMA5_IRQHandler: - ldr r0,=DMA5_DriverIRQHandler - bx r0 - .size DMA5_IRQHandler, . - DMA5_IRQHandler - - .align 1 - .thumb_func - .weak DMA6_IRQHandler - .type DMA6_IRQHandler, %function -DMA6_IRQHandler: - ldr r0,=DMA6_DriverIRQHandler - bx r0 - .size DMA6_IRQHandler, . - DMA6_IRQHandler - - .align 1 - .thumb_func - .weak DMA7_IRQHandler - .type DMA7_IRQHandler, %function -DMA7_IRQHandler: - ldr r0,=DMA7_DriverIRQHandler - bx r0 - .size DMA7_IRQHandler, . - DMA7_IRQHandler - - .align 1 - .thumb_func - .weak DMA8_IRQHandler - .type DMA8_IRQHandler, %function -DMA8_IRQHandler: - ldr r0,=DMA8_DriverIRQHandler - bx r0 - .size DMA8_IRQHandler, . - DMA8_IRQHandler - - .align 1 - .thumb_func - .weak DMA9_IRQHandler - .type DMA9_IRQHandler, %function -DMA9_IRQHandler: - ldr r0,=DMA9_DriverIRQHandler - bx r0 - .size DMA9_IRQHandler, . - DMA9_IRQHandler - - .align 1 - .thumb_func - .weak DMA10_IRQHandler - .type DMA10_IRQHandler, %function -DMA10_IRQHandler: - ldr r0,=DMA10_DriverIRQHandler - bx r0 - .size DMA10_IRQHandler, . - DMA10_IRQHandler - - .align 1 - .thumb_func - .weak DMA11_IRQHandler - .type DMA11_IRQHandler, %function -DMA11_IRQHandler: - ldr r0,=DMA11_DriverIRQHandler - bx r0 - .size DMA11_IRQHandler, . - DMA11_IRQHandler - - .align 1 - .thumb_func - .weak DMA12_IRQHandler - .type DMA12_IRQHandler, %function -DMA12_IRQHandler: - ldr r0,=DMA12_DriverIRQHandler - bx r0 - .size DMA12_IRQHandler, . - DMA12_IRQHandler - - .align 1 - .thumb_func - .weak DMA13_IRQHandler - .type DMA13_IRQHandler, %function -DMA13_IRQHandler: - ldr r0,=DMA13_DriverIRQHandler - bx r0 - .size DMA13_IRQHandler, . - DMA13_IRQHandler - - .align 1 - .thumb_func - .weak DMA14_IRQHandler - .type DMA14_IRQHandler, %function -DMA14_IRQHandler: - ldr r0,=DMA14_DriverIRQHandler - bx r0 - .size DMA14_IRQHandler, . - DMA14_IRQHandler - - .align 1 - .thumb_func - .weak DMA15_IRQHandler - .type DMA15_IRQHandler, %function -DMA15_IRQHandler: - ldr r0,=DMA15_DriverIRQHandler - bx r0 - .size DMA15_IRQHandler, . - DMA15_IRQHandler - - .align 1 - .thumb_func - .weak DMA_Error_IRQHandler - .type DMA_Error_IRQHandler, %function -DMA_Error_IRQHandler: - ldr r0,=DMA_Error_DriverIRQHandler - bx r0 - .size DMA_Error_IRQHandler, . - DMA_Error_IRQHandler - - .align 1 - .thumb_func - .weak I2C0_IRQHandler - .type I2C0_IRQHandler, %function -I2C0_IRQHandler: - ldr r0,=I2C0_DriverIRQHandler - bx r0 - .size I2C0_IRQHandler, . - I2C0_IRQHandler - - .align 1 - .thumb_func - .weak I2C1_IRQHandler - .type I2C1_IRQHandler, %function -I2C1_IRQHandler: - ldr r0,=I2C1_DriverIRQHandler - bx r0 - .size I2C1_IRQHandler, . - I2C1_IRQHandler - - .align 1 - .thumb_func - .weak SPI0_IRQHandler - .type SPI0_IRQHandler, %function -SPI0_IRQHandler: - ldr r0,=SPI0_DriverIRQHandler - bx r0 - .size SPI0_IRQHandler, . - SPI0_IRQHandler - - .align 1 - .thumb_func - .weak SPI1_IRQHandler - .type SPI1_IRQHandler, %function -SPI1_IRQHandler: - ldr r0,=SPI1_DriverIRQHandler - bx r0 - .size SPI1_IRQHandler, . - SPI1_IRQHandler - - .align 1 - .thumb_func - .weak I2S0_Tx_IRQHandler - .type I2S0_Tx_IRQHandler, %function -I2S0_Tx_IRQHandler: - ldr r0,=I2S0_Tx_DriverIRQHandler - bx r0 - .size I2S0_Tx_IRQHandler, . - I2S0_Tx_IRQHandler - - .align 1 - .thumb_func - .weak I2S0_Rx_IRQHandler - .type I2S0_Rx_IRQHandler, %function -I2S0_Rx_IRQHandler: - ldr r0,=I2S0_Rx_DriverIRQHandler - bx r0 - .size I2S0_Rx_IRQHandler, . - I2S0_Rx_IRQHandler - - .align 1 - .thumb_func - .weak UART0_LON_IRQHandler - .type UART0_LON_IRQHandler, %function -UART0_LON_IRQHandler: - ldr r0,=UART0_LON_DriverIRQHandler - bx r0 - .size UART0_LON_IRQHandler, . - UART0_LON_IRQHandler - - .align 1 - .thumb_func - .weak UART0_RX_TX_IRQHandler - .type UART0_RX_TX_IRQHandler, %function -UART0_RX_TX_IRQHandler: - ldr r0,=UART0_RX_TX_DriverIRQHandler - bx r0 - .size UART0_RX_TX_IRQHandler, . - UART0_RX_TX_IRQHandler - - .align 1 - .thumb_func - .weak UART0_ERR_IRQHandler - .type UART0_ERR_IRQHandler, %function -UART0_ERR_IRQHandler: - ldr r0,=UART0_ERR_DriverIRQHandler - bx r0 - .size UART0_ERR_IRQHandler, . - UART0_ERR_IRQHandler - - .align 1 - .thumb_func - .weak UART1_RX_TX_IRQHandler - .type UART1_RX_TX_IRQHandler, %function -UART1_RX_TX_IRQHandler: - ldr r0,=UART1_RX_TX_DriverIRQHandler - bx r0 - .size UART1_RX_TX_IRQHandler, . - UART1_RX_TX_IRQHandler - - .align 1 - .thumb_func - .weak UART1_ERR_IRQHandler - .type UART1_ERR_IRQHandler, %function -UART1_ERR_IRQHandler: - ldr r0,=UART1_ERR_DriverIRQHandler - bx r0 - .size UART1_ERR_IRQHandler, . - UART1_ERR_IRQHandler - - .align 1 - .thumb_func - .weak UART2_RX_TX_IRQHandler - .type UART2_RX_TX_IRQHandler, %function -UART2_RX_TX_IRQHandler: - ldr r0,=UART2_RX_TX_DriverIRQHandler - bx r0 - .size UART2_RX_TX_IRQHandler, . - UART2_RX_TX_IRQHandler - - .align 1 - .thumb_func - .weak UART2_ERR_IRQHandler - .type UART2_ERR_IRQHandler, %function -UART2_ERR_IRQHandler: - ldr r0,=UART2_ERR_DriverIRQHandler - bx r0 - .size UART2_ERR_IRQHandler, . - UART2_ERR_IRQHandler - - .align 1 - .thumb_func - .weak UART3_RX_TX_IRQHandler - .type UART3_RX_TX_IRQHandler, %function -UART3_RX_TX_IRQHandler: - ldr r0,=UART3_RX_TX_DriverIRQHandler - bx r0 - .size UART3_RX_TX_IRQHandler, . - UART3_RX_TX_IRQHandler - - .align 1 - .thumb_func - .weak UART3_ERR_IRQHandler - .type UART3_ERR_IRQHandler, %function -UART3_ERR_IRQHandler: - ldr r0,=UART3_ERR_DriverIRQHandler - bx r0 - .size UART3_ERR_IRQHandler, . - UART3_ERR_IRQHandler - - .align 1 - .thumb_func - .weak SPI2_IRQHandler - .type SPI2_IRQHandler, %function -SPI2_IRQHandler: - ldr r0,=SPI2_DriverIRQHandler - bx r0 - .size SPI2_IRQHandler, . - SPI2_IRQHandler - - .align 1 - .thumb_func - .weak UART4_RX_TX_IRQHandler - .type UART4_RX_TX_IRQHandler, %function -UART4_RX_TX_IRQHandler: - ldr r0,=UART4_RX_TX_DriverIRQHandler - bx r0 - .size UART4_RX_TX_IRQHandler, . - UART4_RX_TX_IRQHandler - - .align 1 - .thumb_func - .weak UART4_ERR_IRQHandler - .type UART4_ERR_IRQHandler, %function -UART4_ERR_IRQHandler: - ldr r0,=UART4_ERR_DriverIRQHandler - bx r0 - .size UART4_ERR_IRQHandler, . - UART4_ERR_IRQHandler - - .align 1 - .thumb_func - .weak UART5_RX_TX_IRQHandler - .type UART5_RX_TX_IRQHandler, %function -UART5_RX_TX_IRQHandler: - ldr r0,=UART5_RX_TX_DriverIRQHandler - bx r0 - .size UART5_RX_TX_IRQHandler, . - UART5_RX_TX_IRQHandler - - .align 1 - .thumb_func - .weak UART5_ERR_IRQHandler - .type UART5_ERR_IRQHandler, %function -UART5_ERR_IRQHandler: - ldr r0,=UART5_ERR_DriverIRQHandler - bx r0 - .size UART5_ERR_IRQHandler, . - UART5_ERR_IRQHandler - - .align 1 - .thumb_func - .weak I2C2_IRQHandler - .type I2C2_IRQHandler, %function -I2C2_IRQHandler: - ldr r0,=I2C2_DriverIRQHandler - bx r0 - .size I2C2_IRQHandler, . - I2C2_IRQHandler - - .align 1 - .thumb_func - .weak CAN0_ORed_Message_buffer_IRQHandler - .type CAN0_ORed_Message_buffer_IRQHandler, %function -CAN0_ORed_Message_buffer_IRQHandler: - ldr r0,=CAN0_DriverIRQHandler - bx r0 - .size CAN0_ORed_Message_buffer_IRQHandler, . - CAN0_ORed_Message_buffer_IRQHandler - - .align 1 - .thumb_func - .weak CAN0_Bus_Off_IRQHandler - .type CAN0_Bus_Off_IRQHandler, %function -CAN0_Bus_Off_IRQHandler: - ldr r0,=CAN0_DriverIRQHandler - bx r0 - .size CAN0_Bus_Off_IRQHandler, . - CAN0_Bus_Off_IRQHandler - - .align 1 - .thumb_func - .weak CAN0_Error_IRQHandler - .type CAN0_Error_IRQHandler, %function -CAN0_Error_IRQHandler: - ldr r0,=CAN0_DriverIRQHandler - bx r0 - .size CAN0_Error_IRQHandler, . - CAN0_Error_IRQHandler - - .align 1 - .thumb_func - .weak CAN0_Tx_Warning_IRQHandler - .type CAN0_Tx_Warning_IRQHandler, %function -CAN0_Tx_Warning_IRQHandler: - ldr r0,=CAN0_DriverIRQHandler - bx r0 - .size CAN0_Tx_Warning_IRQHandler, . - CAN0_Tx_Warning_IRQHandler - - .align 1 - .thumb_func - .weak CAN0_Rx_Warning_IRQHandler - .type CAN0_Rx_Warning_IRQHandler, %function -CAN0_Rx_Warning_IRQHandler: - ldr r0,=CAN0_DriverIRQHandler - bx r0 - .size CAN0_Rx_Warning_IRQHandler, . - CAN0_Rx_Warning_IRQHandler - - .align 1 - .thumb_func - .weak CAN0_Wake_Up_IRQHandler - .type CAN0_Wake_Up_IRQHandler, %function -CAN0_Wake_Up_IRQHandler: - ldr r0,=CAN0_DriverIRQHandler - bx r0 - .size CAN0_Wake_Up_IRQHandler, . - CAN0_Wake_Up_IRQHandler - - .align 1 - .thumb_func - .weak SDHC_IRQHandler - .type SDHC_IRQHandler, %function -SDHC_IRQHandler: - ldr r0,=SDHC_DriverIRQHandler - bx r0 - .size SDHC_IRQHandler, . - SDHC_IRQHandler - - -/* Macro to define default handlers. Default handler - * will be weak symbol and just dead loops. They can be - * overwritten by other handlers */ - .macro def_irq_handler handler_name - .weak \handler_name - .set \handler_name, DefaultISR - .endm - -/* Exception Handlers */ - def_irq_handler MemManage_Handler - def_irq_handler BusFault_Handler - def_irq_handler UsageFault_Handler - def_irq_handler DebugMon_Handler - def_irq_handler DMA0_DriverIRQHandler - def_irq_handler DMA1_DriverIRQHandler - def_irq_handler DMA2_DriverIRQHandler - def_irq_handler DMA3_DriverIRQHandler - def_irq_handler DMA4_DriverIRQHandler - def_irq_handler DMA5_DriverIRQHandler - def_irq_handler DMA6_DriverIRQHandler - def_irq_handler DMA7_DriverIRQHandler - def_irq_handler DMA8_DriverIRQHandler - def_irq_handler DMA9_DriverIRQHandler - def_irq_handler DMA10_DriverIRQHandler - def_irq_handler DMA11_DriverIRQHandler - def_irq_handler DMA12_DriverIRQHandler - def_irq_handler DMA13_DriverIRQHandler - def_irq_handler DMA14_DriverIRQHandler - def_irq_handler DMA15_DriverIRQHandler - def_irq_handler DMA_Error_DriverIRQHandler - def_irq_handler MCM_IRQHandler - def_irq_handler FTFE_IRQHandler - def_irq_handler Read_Collision_IRQHandler - def_irq_handler LVD_LVW_IRQHandler - def_irq_handler LLWU_IRQHandler - def_irq_handler WDOG_EWM_IRQHandler - def_irq_handler RNG_IRQHandler - def_irq_handler I2C0_DriverIRQHandler - def_irq_handler I2C1_DriverIRQHandler - def_irq_handler SPI0_DriverIRQHandler - def_irq_handler SPI1_DriverIRQHandler - def_irq_handler I2S0_Tx_DriverIRQHandler - def_irq_handler I2S0_Rx_DriverIRQHandler - def_irq_handler UART0_LON_DriverIRQHandler - def_irq_handler UART0_RX_TX_DriverIRQHandler - def_irq_handler UART0_ERR_DriverIRQHandler - def_irq_handler UART1_RX_TX_DriverIRQHandler - def_irq_handler UART1_ERR_DriverIRQHandler - def_irq_handler UART2_RX_TX_DriverIRQHandler - def_irq_handler UART2_ERR_DriverIRQHandler - def_irq_handler UART3_RX_TX_DriverIRQHandler - def_irq_handler UART3_ERR_DriverIRQHandler - def_irq_handler ADC0_IRQHandler - def_irq_handler CMP0_IRQHandler - def_irq_handler CMP1_IRQHandler - def_irq_handler FTM0_IRQHandler - def_irq_handler FTM1_IRQHandler - def_irq_handler FTM2_IRQHandler - def_irq_handler CMT_IRQHandler - def_irq_handler RTC_IRQHandler - def_irq_handler RTC_Seconds_IRQHandler - def_irq_handler PIT0_IRQHandler - def_irq_handler PIT1_IRQHandler - def_irq_handler PIT2_IRQHandler - def_irq_handler PIT3_IRQHandler - def_irq_handler PDB0_IRQHandler - def_irq_handler USB0_IRQHandler - def_irq_handler USBDCD_IRQHandler - def_irq_handler Reserved71_IRQHandler - def_irq_handler DAC0_IRQHandler - def_irq_handler MCG_IRQHandler - def_irq_handler LPTMR0_IRQHandler - def_irq_handler PORTA_IRQHandler - def_irq_handler PORTB_IRQHandler - def_irq_handler PORTC_IRQHandler - def_irq_handler PORTD_IRQHandler - def_irq_handler PORTE_IRQHandler - def_irq_handler SWI_IRQHandler - def_irq_handler SPI2_DriverIRQHandler - def_irq_handler UART4_RX_TX_DriverIRQHandler - def_irq_handler UART4_ERR_DriverIRQHandler - def_irq_handler UART5_RX_TX_DriverIRQHandler - def_irq_handler UART5_ERR_DriverIRQHandler - def_irq_handler CMP2_IRQHandler - def_irq_handler FTM3_IRQHandler - def_irq_handler DAC1_IRQHandler - def_irq_handler ADC1_IRQHandler - def_irq_handler I2C2_DriverIRQHandler - def_irq_handler CAN0_DriverIRQHandler - def_irq_handler SDHC_DriverIRQHandler - def_irq_handler Reserved98_IRQHandler - def_irq_handler Reserved99_IRQHandler - def_irq_handler Reserved100_IRQHandler - def_irq_handler Reserved101_IRQHandler - - .end diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/device/TOOLCHAIN_IAR/MK24FN1M0xxx12.icf b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/device/TOOLCHAIN_IAR/MK24FN1M0xxx12.icf deleted file mode 100644 index 4b753e15d1b..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/device/TOOLCHAIN_IAR/MK24FN1M0xxx12.icf +++ /dev/null @@ -1,118 +0,0 @@ -/* -** ################################################################### -** Processors: MK64FN1M0VDC12 -** MK64FN1M0VLL12 -** MK64FN1M0VLQ12 -** MK64FN1M0VMD12 -** -** Compiler: IAR ANSI C/C++ Compiler for ARM -** Reference manual: K64P144M120SF5RM, Rev.2, January 2014 -** Version: rev. 2.8, 2015-02-19 -** Build: b151009 -** -** Abstract: -** Linker file for the IAR ANSI C/C++ Compiler for ARM -** -** Copyright (c) 2015 Freescale Semiconductor, Inc. -** All rights reserved. -** -** Redistribution and use in source and binary forms, with or without modification, -** are permitted provided that the following conditions are met: -** -** o Redistributions of source code must retain the above copyright notice, this list -** of conditions and the following disclaimer. -** -** o Redistributions in binary form must reproduce the above copyright notice, this -** list of conditions and the following disclaimer in the documentation and/or -** other materials provided with the distribution. -** -** o Neither the name of Freescale Semiconductor, Inc. nor the names of its -** contributors may be used to endorse or promote products derived from this -** software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -** ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -** LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -** ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -** -** http: www.freescale.com -** mail: support@freescale.com -** -** ################################################################### -*/ -define symbol __ram_vector_table__ = 1; - -/* Heap 1/4 of ram and stack 1/8 */ -define symbol __stack_size__=0x8000; -define symbol __heap_size__=0x10000; - -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_flash_config_start = 0x00000400; -define symbol m_flash_config_end = 0x0000040F; - -define symbol m_text_start = 0x00000410; -define symbol m_text_end = 0x000FFFFF; - -define symbol m_interrupts_ram_start = 0x1FFF0000; -define symbol m_interrupts_ram_end = 0x1FFF0000 + __ram_vector_table_offset__; - -define symbol m_data_start = m_interrupts_ram_start + __ram_vector_table_size__; -define symbol m_data_end = 0x1FFFFFFF; - -define symbol m_data_2_start = 0x20000000; -define symbol m_data_2_end = 0x2002FFFF; - -/* Sizes */ -if (isdefinedsymbol(__stack_size__)) { - define symbol __size_cstack__ = __stack_size__; -} else { - define symbol __size_cstack__ = 0x0400; -} - -if (isdefinedsymbol(__heap_size__)) { - define symbol __size_heap__ = __heap_size__; -} else { - define symbol __size_heap__ = 0x0400; -} - -define exported symbol __VECTOR_TABLE = m_interrupts_start; -define exported symbol __VECTOR_RAM = isdefinedsymbol(__ram_vector_table__) ? m_interrupts_ram_start : m_interrupts_start; -define exported symbol __RAM_VECTOR_TABLE_SIZE = __ram_vector_table_size__; - -define memory mem with size = 4G; -define region m_flash_config_region = mem:[from m_flash_config_start to m_flash_config_end]; -define region TEXT_region = mem:[from m_interrupts_start to m_interrupts_end] - | mem:[from m_text_start to m_text_end]; -define region DATA_region = mem:[from m_data_start to m_data_end] - | mem:[from m_data_2_start to m_data_2_end-__size_cstack__]; -define region CSTACK_region = mem:[from m_data_2_end-__size_cstack__+1 to m_data_2_end]; -define region m_interrupts_ram_region = mem:[from m_interrupts_ram_start to m_interrupts_ram_end]; - -define block CSTACK with alignment = 8, size = __size_cstack__ { }; -define block HEAP with alignment = 8, size = __size_heap__ { }; -define block RW { readwrite }; -define block ZI { zi }; - -initialize by copy { readwrite, section .textrw }; -do not initialize { section .noinit }; - -place at address mem: m_interrupts_start { readonly section .intvec }; -place in m_flash_config_region { section FlashConfig }; -place in TEXT_region { readonly }; -place in DATA_region { block RW }; -place in DATA_region { block ZI }; -place in DATA_region { last block HEAP }; -place in CSTACK_region { block CSTACK }; -place in m_interrupts_ram_region { section m_interrupts_ram }; - diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/device/TOOLCHAIN_IAR/startup_MK24F12.S b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/device/TOOLCHAIN_IAR/startup_MK24F12.S deleted file mode 100644 index f55ac1d7f93..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/device/TOOLCHAIN_IAR/startup_MK24F12.S +++ /dev/null @@ -1,847 +0,0 @@ -; --------------------------------------------------------------------------------------- -; @file: startup_MK24F12.s -; @purpose: CMSIS Cortex-M4 Core Device Startup File -; MK24F12 -; @version: 2.8 -; @date: 2016-3-21 -; @build: b170112 -; --------------------------------------------------------------------------------------- -; -; Copyright (c) 1997 - 2016, Freescale Semiconductor, Inc. -; Copyright 2016 - 2017 NXP -; Redistribution and use in source and binary forms, with or without modification, -; are permitted provided that the following conditions are met: -; -; o Redistributions of source code must retain the above copyright notice, this list -; of conditions and the following disclaimer. -; -; o Redistributions in binary form must reproduce the above copyright notice, this -; list of conditions and the following disclaimer in the documentation and/or -; other materials provided with the distribution. -; -; o Neither the name of the copyright holder nor the names of its -; contributors may be used to endorse or promote products derived from this -; software without specific prior written permission. -; -; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -; ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -; ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -; (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -; ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -; -; The modules in this file are included in the libraries, and may be replaced -; by any user-defined modules that define the PUBLIC symbol _program_start or -; a user defined start symbol. -; To override the cstartup defined in the library, simply add your modified -; version to the workbench project. -; -; The vector table is normally located at address 0. -; When debugging in RAM, it can be located in RAM, aligned to at least 2^6. -; The name "__vector_table" has special meaning for C-SPY: -; it is where the SP start value is found, and the NVIC vector -; table register (VTOR) is initialized to this address if != 0. -; -; Cortex-M version -; - - MODULE ?cstartup - - ;; Forward declaration of sections. - SECTION CSTACK:DATA:NOROOT(3) - - SECTION .intvec:CODE:NOROOT(2) - - EXTERN __iar_program_start - EXTERN SystemInit - PUBLIC __vector_table - PUBLIC __vector_table_0x1c - PUBLIC __Vectors - PUBLIC __Vectors_End - PUBLIC __Vectors_Size - - DATA - -__vector_table - DCD sfe(CSTACK) - DCD Reset_Handler - - DCD NMI_Handler ;NMI Handler - DCD HardFault_Handler ;Hard Fault Handler - DCD MemManage_Handler ;MPU Fault Handler - DCD BusFault_Handler ;Bus Fault Handler - DCD UsageFault_Handler ;Usage Fault Handler -__vector_table_0x1c - DCD 0 ;Reserved - DCD 0 ;Reserved - DCD 0 ;Reserved - DCD 0 ;Reserved - DCD SVC_Handler ;SVCall Handler - DCD DebugMon_Handler ;Debug Monitor Handler - DCD 0 ;Reserved - DCD PendSV_Handler ;PendSV Handler - DCD SysTick_Handler ;SysTick Handler - - ;External Interrupts - DCD DMA0_IRQHandler ;DMA Channel 0 Transfer Complete - DCD DMA1_IRQHandler ;DMA Channel 1 Transfer Complete - DCD DMA2_IRQHandler ;DMA Channel 2 Transfer Complete - DCD DMA3_IRQHandler ;DMA Channel 3 Transfer Complete - DCD DMA4_IRQHandler ;DMA Channel 4 Transfer Complete - DCD DMA5_IRQHandler ;DMA Channel 5 Transfer Complete - DCD DMA6_IRQHandler ;DMA Channel 6 Transfer Complete - DCD DMA7_IRQHandler ;DMA Channel 7 Transfer Complete - DCD DMA8_IRQHandler ;DMA Channel 8 Transfer Complete - DCD DMA9_IRQHandler ;DMA Channel 9 Transfer Complete - DCD DMA10_IRQHandler ;DMA Channel 10 Transfer Complete - DCD DMA11_IRQHandler ;DMA Channel 11 Transfer Complete - DCD DMA12_IRQHandler ;DMA Channel 12 Transfer Complete - DCD DMA13_IRQHandler ;DMA Channel 13 Transfer Complete - DCD DMA14_IRQHandler ;DMA Channel 14 Transfer Complete - DCD DMA15_IRQHandler ;DMA Channel 15 Transfer Complete - DCD DMA_Error_IRQHandler ;DMA Error Interrupt - DCD MCM_IRQHandler ;Normal Interrupt - DCD FTFE_IRQHandler ;FTFE Command complete interrupt - DCD Read_Collision_IRQHandler ;Read Collision Interrupt - DCD LVD_LVW_IRQHandler ;Low Voltage Detect, Low Voltage Warning - DCD LLWU_IRQHandler ;Low Leakage Wakeup Unit - DCD WDOG_EWM_IRQHandler ;WDOG Interrupt - DCD RNG_IRQHandler ;RNG Interrupt - DCD I2C0_IRQHandler ;I2C0 interrupt - DCD I2C1_IRQHandler ;I2C1 interrupt - DCD SPI0_IRQHandler ;SPI0 Interrupt - DCD SPI1_IRQHandler ;SPI1 Interrupt - DCD I2S0_Tx_IRQHandler ;I2S0 transmit interrupt - DCD I2S0_Rx_IRQHandler ;I2S0 receive interrupt - DCD UART0_LON_IRQHandler ;UART0 LON interrupt - DCD UART0_RX_TX_IRQHandler ;UART0 Receive/Transmit interrupt - DCD UART0_ERR_IRQHandler ;UART0 Error interrupt - DCD UART1_RX_TX_IRQHandler ;UART1 Receive/Transmit interrupt - DCD UART1_ERR_IRQHandler ;UART1 Error interrupt - DCD UART2_RX_TX_IRQHandler ;UART2 Receive/Transmit interrupt - DCD UART2_ERR_IRQHandler ;UART2 Error interrupt - DCD UART3_RX_TX_IRQHandler ;UART3 Receive/Transmit interrupt - DCD UART3_ERR_IRQHandler ;UART3 Error interrupt - DCD ADC0_IRQHandler ;ADC0 interrupt - DCD CMP0_IRQHandler ;CMP0 interrupt - DCD CMP1_IRQHandler ;CMP1 interrupt - DCD FTM0_IRQHandler ;FTM0 fault, overflow and channels interrupt - DCD FTM1_IRQHandler ;FTM1 fault, overflow and channels interrupt - DCD FTM2_IRQHandler ;FTM2 fault, overflow and channels interrupt - DCD CMT_IRQHandler ;CMT interrupt - DCD RTC_IRQHandler ;RTC interrupt - DCD RTC_Seconds_IRQHandler ;RTC seconds interrupt - DCD PIT0_IRQHandler ;PIT timer channel 0 interrupt - DCD PIT1_IRQHandler ;PIT timer channel 1 interrupt - DCD PIT2_IRQHandler ;PIT timer channel 2 interrupt - DCD PIT3_IRQHandler ;PIT timer channel 3 interrupt - DCD PDB0_IRQHandler ;PDB0 Interrupt - DCD USB0_IRQHandler ;USB0 interrupt - DCD USBDCD_IRQHandler ;USBDCD Interrupt - DCD Reserved71_IRQHandler ;Reserved interrupt 71 - DCD DAC0_IRQHandler ;DAC0 interrupt - DCD MCG_IRQHandler ;MCG Interrupt - DCD LPTMR0_IRQHandler ;LPTimer interrupt - DCD PORTA_IRQHandler ;Port A interrupt - DCD PORTB_IRQHandler ;Port B interrupt - DCD PORTC_IRQHandler ;Port C interrupt - DCD PORTD_IRQHandler ;Port D interrupt - DCD PORTE_IRQHandler ;Port E interrupt - DCD SWI_IRQHandler ;Software interrupt - DCD SPI2_IRQHandler ;SPI2 Interrupt - DCD UART4_RX_TX_IRQHandler ;UART4 Receive/Transmit interrupt - DCD UART4_ERR_IRQHandler ;UART4 Error interrupt - DCD UART5_RX_TX_IRQHandler ;UART5 Receive/Transmit interrupt - DCD UART5_ERR_IRQHandler ;UART5 Error interrupt - DCD CMP2_IRQHandler ;CMP2 interrupt - DCD FTM3_IRQHandler ;FTM3 fault, overflow and channels interrupt - DCD DAC1_IRQHandler ;DAC1 interrupt - DCD ADC1_IRQHandler ;ADC1 interrupt - DCD I2C2_IRQHandler ;I2C2 interrupt - DCD CAN0_ORed_Message_buffer_IRQHandler ;CAN0 OR'd message buffers interrupt - DCD CAN0_Bus_Off_IRQHandler ;CAN0 bus off interrupt - DCD CAN0_Error_IRQHandler ;CAN0 error interrupt - DCD CAN0_Tx_Warning_IRQHandler ;CAN0 Tx warning interrupt - DCD CAN0_Rx_Warning_IRQHandler ;CAN0 Rx warning interrupt - DCD CAN0_Wake_Up_IRQHandler ;CAN0 wake up interrupt - DCD SDHC_IRQHandler ;SDHC interrupt - DCD Reserved98_IRQHandler ;Reserved interrupt 98 - DCD Reserved99_IRQHandler ;Reserved interrupt 99 - DCD Reserved100_IRQHandler ;Reserved interrupt 100 - DCD Reserved101_IRQHandler ;Reserved interrupt 101 - DCD DefaultISR ;102 - DCD DefaultISR ;103 - DCD DefaultISR ;104 - DCD DefaultISR ;105 - DCD DefaultISR ;106 - DCD DefaultISR ;107 - DCD DefaultISR ;108 - DCD DefaultISR ;109 - DCD DefaultISR ;110 - DCD DefaultISR ;111 - DCD DefaultISR ;112 - DCD DefaultISR ;113 - DCD DefaultISR ;114 - DCD DefaultISR ;115 - DCD DefaultISR ;116 - DCD DefaultISR ;117 - DCD DefaultISR ;118 - DCD DefaultISR ;119 - DCD DefaultISR ;120 - DCD DefaultISR ;121 - DCD DefaultISR ;122 - DCD DefaultISR ;123 - DCD DefaultISR ;124 - DCD DefaultISR ;125 - DCD DefaultISR ;126 - DCD DefaultISR ;127 - DCD DefaultISR ;128 - DCD DefaultISR ;129 - DCD DefaultISR ;130 - DCD DefaultISR ;131 - DCD DefaultISR ;132 - DCD DefaultISR ;133 - DCD DefaultISR ;134 - DCD DefaultISR ;135 - DCD DefaultISR ;136 - DCD DefaultISR ;137 - DCD DefaultISR ;138 - DCD DefaultISR ;139 - DCD DefaultISR ;140 - DCD DefaultISR ;141 - DCD DefaultISR ;142 - DCD DefaultISR ;143 - DCD DefaultISR ;144 - DCD DefaultISR ;145 - DCD DefaultISR ;146 - DCD DefaultISR ;147 - DCD DefaultISR ;148 - DCD DefaultISR ;149 - DCD DefaultISR ;150 - DCD DefaultISR ;151 - DCD DefaultISR ;152 - DCD DefaultISR ;153 - DCD DefaultISR ;154 - DCD DefaultISR ;155 - DCD DefaultISR ;156 - DCD DefaultISR ;157 - DCD DefaultISR ;158 - DCD DefaultISR ;159 - DCD DefaultISR ;160 - DCD DefaultISR ;161 - DCD DefaultISR ;162 - DCD DefaultISR ;163 - DCD DefaultISR ;164 - DCD DefaultISR ;165 - DCD DefaultISR ;166 - DCD DefaultISR ;167 - DCD DefaultISR ;168 - DCD DefaultISR ;169 - DCD DefaultISR ;170 - DCD DefaultISR ;171 - DCD DefaultISR ;172 - DCD DefaultISR ;173 - DCD DefaultISR ;174 - DCD DefaultISR ;175 - DCD DefaultISR ;176 - DCD DefaultISR ;177 - DCD DefaultISR ;178 - DCD DefaultISR ;179 - DCD DefaultISR ;180 - DCD DefaultISR ;181 - DCD DefaultISR ;182 - DCD DefaultISR ;183 - DCD DefaultISR ;184 - DCD DefaultISR ;185 - DCD DefaultISR ;186 - DCD DefaultISR ;187 - DCD DefaultISR ;188 - DCD DefaultISR ;189 - DCD DefaultISR ;190 - DCD DefaultISR ;191 - DCD DefaultISR ;192 - DCD DefaultISR ;193 - DCD DefaultISR ;194 - DCD DefaultISR ;195 - DCD DefaultISR ;196 - DCD DefaultISR ;197 - DCD DefaultISR ;198 - DCD DefaultISR ;199 - DCD DefaultISR ;200 - DCD DefaultISR ;201 - DCD DefaultISR ;202 - DCD DefaultISR ;203 - DCD DefaultISR ;204 - DCD DefaultISR ;205 - DCD DefaultISR ;206 - DCD DefaultISR ;207 - DCD DefaultISR ;208 - DCD DefaultISR ;209 - DCD DefaultISR ;210 - DCD DefaultISR ;211 - DCD DefaultISR ;212 - DCD DefaultISR ;213 - DCD DefaultISR ;214 - DCD DefaultISR ;215 - DCD DefaultISR ;216 - DCD DefaultISR ;217 - DCD DefaultISR ;218 - DCD DefaultISR ;219 - DCD DefaultISR ;220 - DCD DefaultISR ;221 - DCD DefaultISR ;222 - DCD DefaultISR ;223 - DCD DefaultISR ;224 - DCD DefaultISR ;225 - DCD DefaultISR ;226 - DCD DefaultISR ;227 - DCD DefaultISR ;228 - DCD DefaultISR ;229 - DCD DefaultISR ;230 - DCD DefaultISR ;231 - DCD DefaultISR ;232 - DCD DefaultISR ;233 - DCD DefaultISR ;234 - DCD DefaultISR ;235 - DCD DefaultISR ;236 - DCD DefaultISR ;237 - DCD DefaultISR ;238 - DCD DefaultISR ;239 - DCD DefaultISR ;240 - DCD DefaultISR ;241 - DCD DefaultISR ;242 - DCD DefaultISR ;243 - DCD DefaultISR ;244 - DCD DefaultISR ;245 - DCD DefaultISR ;246 - DCD DefaultISR ;247 - DCD DefaultISR ;248 - DCD DefaultISR ;249 - DCD DefaultISR ;250 - DCD DefaultISR ;251 - DCD DefaultISR ;252 - DCD DefaultISR ;253 - DCD DefaultISR ;254 - DCD 0xFFFFFFFF ; Reserved for user TRIM value -__Vectors_End - - SECTION FlashConfig:CODE -__FlashConfig - DCD 0xFFFFFFFF - DCD 0xFFFFFFFF - DCD 0xFFFFFFFF - DCD 0xFFFFFFFE -__FlashConfig_End - -__Vectors EQU __vector_table -__Vectors_Size EQU __Vectors_End - __Vectors - - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; -;; Default interrupt handlers. -;; - THUMB - - PUBWEAK Reset_Handler - SECTION .text:CODE:REORDER:NOROOT(2) -Reset_Handler - CPSID I ; Mask interrupts - LDR R0, =0xE000ED08 - LDR R1, =__vector_table - STR R1, [R0] - LDR R2, [R1] - MSR MSP, R2 - LDR R0, =SystemInit - BLX R0 - CPSIE I ; Unmask interrupts - LDR R0, =__iar_program_start - BX R0 - - PUBWEAK NMI_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -NMI_Handler - B . - - PUBWEAK HardFault_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -HardFault_Handler - B . - - PUBWEAK MemManage_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -MemManage_Handler - B . - - PUBWEAK BusFault_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -BusFault_Handler - B . - - PUBWEAK UsageFault_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -UsageFault_Handler - B . - - PUBWEAK SVC_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -SVC_Handler - B . - - PUBWEAK DebugMon_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -DebugMon_Handler - B . - - PUBWEAK PendSV_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -PendSV_Handler - B . - - PUBWEAK SysTick_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -SysTick_Handler - B . - - PUBWEAK DMA0_IRQHandler - PUBWEAK DMA0_DriverIRQHandler - SECTION .text:CODE:REORDER:NOROOT(2) -DMA0_IRQHandler - LDR R0, =DMA0_DriverIRQHandler - BX R0 - - PUBWEAK DMA1_IRQHandler - PUBWEAK DMA1_DriverIRQHandler - SECTION .text:CODE:REORDER:NOROOT(2) -DMA1_IRQHandler - LDR R0, =DMA1_DriverIRQHandler - BX R0 - - PUBWEAK DMA2_IRQHandler - PUBWEAK DMA2_DriverIRQHandler - SECTION .text:CODE:REORDER:NOROOT(2) -DMA2_IRQHandler - LDR R0, =DMA2_DriverIRQHandler - BX R0 - - PUBWEAK DMA3_IRQHandler - PUBWEAK DMA3_DriverIRQHandler - SECTION .text:CODE:REORDER:NOROOT(2) -DMA3_IRQHandler - LDR R0, =DMA3_DriverIRQHandler - BX R0 - - PUBWEAK DMA4_IRQHandler - PUBWEAK DMA4_DriverIRQHandler - SECTION .text:CODE:REORDER:NOROOT(2) -DMA4_IRQHandler - LDR R0, =DMA4_DriverIRQHandler - BX R0 - - PUBWEAK DMA5_IRQHandler - PUBWEAK DMA5_DriverIRQHandler - SECTION .text:CODE:REORDER:NOROOT(2) -DMA5_IRQHandler - LDR R0, =DMA5_DriverIRQHandler - BX R0 - - PUBWEAK DMA6_IRQHandler - PUBWEAK DMA6_DriverIRQHandler - SECTION .text:CODE:REORDER:NOROOT(2) -DMA6_IRQHandler - LDR R0, =DMA6_DriverIRQHandler - BX R0 - - PUBWEAK DMA7_IRQHandler - PUBWEAK DMA7_DriverIRQHandler - SECTION .text:CODE:REORDER:NOROOT(2) -DMA7_IRQHandler - LDR R0, =DMA7_DriverIRQHandler - BX R0 - - PUBWEAK DMA8_IRQHandler - PUBWEAK DMA8_DriverIRQHandler - SECTION .text:CODE:REORDER:NOROOT(2) -DMA8_IRQHandler - LDR R0, =DMA8_DriverIRQHandler - BX R0 - - PUBWEAK DMA9_IRQHandler - PUBWEAK DMA9_DriverIRQHandler - SECTION .text:CODE:REORDER:NOROOT(2) -DMA9_IRQHandler - LDR R0, =DMA9_DriverIRQHandler - BX R0 - - PUBWEAK DMA10_IRQHandler - PUBWEAK DMA10_DriverIRQHandler - SECTION .text:CODE:REORDER:NOROOT(2) -DMA10_IRQHandler - LDR R0, =DMA10_DriverIRQHandler - BX R0 - - PUBWEAK DMA11_IRQHandler - PUBWEAK DMA11_DriverIRQHandler - SECTION .text:CODE:REORDER:NOROOT(2) -DMA11_IRQHandler - LDR R0, =DMA11_DriverIRQHandler - BX R0 - - PUBWEAK DMA12_IRQHandler - PUBWEAK DMA12_DriverIRQHandler - SECTION .text:CODE:REORDER:NOROOT(2) -DMA12_IRQHandler - LDR R0, =DMA12_DriverIRQHandler - BX R0 - - PUBWEAK DMA13_IRQHandler - PUBWEAK DMA13_DriverIRQHandler - SECTION .text:CODE:REORDER:NOROOT(2) -DMA13_IRQHandler - LDR R0, =DMA13_DriverIRQHandler - BX R0 - - PUBWEAK DMA14_IRQHandler - PUBWEAK DMA14_DriverIRQHandler - SECTION .text:CODE:REORDER:NOROOT(2) -DMA14_IRQHandler - LDR R0, =DMA14_DriverIRQHandler - BX R0 - - PUBWEAK DMA15_IRQHandler - PUBWEAK DMA15_DriverIRQHandler - SECTION .text:CODE:REORDER:NOROOT(2) -DMA15_IRQHandler - LDR R0, =DMA15_DriverIRQHandler - BX R0 - - PUBWEAK DMA_Error_IRQHandler - PUBWEAK DMA_Error_DriverIRQHandler - SECTION .text:CODE:REORDER:NOROOT(2) -DMA_Error_IRQHandler - LDR R0, =DMA_Error_DriverIRQHandler - BX R0 - - PUBWEAK MCM_IRQHandler - PUBWEAK FTFE_IRQHandler - PUBWEAK Read_Collision_IRQHandler - PUBWEAK LVD_LVW_IRQHandler - PUBWEAK LLWU_IRQHandler - PUBWEAK WDOG_EWM_IRQHandler - PUBWEAK RNG_IRQHandler - PUBWEAK I2C0_IRQHandler - PUBWEAK I2C0_DriverIRQHandler - SECTION .text:CODE:REORDER:NOROOT(2) -I2C0_IRQHandler - LDR R0, =I2C0_DriverIRQHandler - BX R0 - - PUBWEAK I2C1_IRQHandler - PUBWEAK I2C1_DriverIRQHandler - SECTION .text:CODE:REORDER:NOROOT(2) -I2C1_IRQHandler - LDR R0, =I2C1_DriverIRQHandler - BX R0 - - PUBWEAK SPI0_IRQHandler - PUBWEAK SPI0_DriverIRQHandler - SECTION .text:CODE:REORDER:NOROOT(2) -SPI0_IRQHandler - LDR R0, =SPI0_DriverIRQHandler - BX R0 - - PUBWEAK SPI1_IRQHandler - PUBWEAK SPI1_DriverIRQHandler - SECTION .text:CODE:REORDER:NOROOT(2) -SPI1_IRQHandler - LDR R0, =SPI1_DriverIRQHandler - BX R0 - - PUBWEAK I2S0_Tx_IRQHandler - PUBWEAK I2S0_Tx_DriverIRQHandler - SECTION .text:CODE:REORDER:NOROOT(2) -I2S0_Tx_IRQHandler - LDR R0, =I2S0_Tx_DriverIRQHandler - BX R0 - - PUBWEAK I2S0_Rx_IRQHandler - PUBWEAK I2S0_Rx_DriverIRQHandler - SECTION .text:CODE:REORDER:NOROOT(2) -I2S0_Rx_IRQHandler - LDR R0, =I2S0_Rx_DriverIRQHandler - BX R0 - - PUBWEAK UART0_LON_IRQHandler - PUBWEAK UART0_LON_DriverIRQHandler - SECTION .text:CODE:REORDER:NOROOT(2) -UART0_LON_IRQHandler - LDR R0, =UART0_LON_DriverIRQHandler - BX R0 - - PUBWEAK UART0_RX_TX_IRQHandler - PUBWEAK UART0_RX_TX_DriverIRQHandler - SECTION .text:CODE:REORDER:NOROOT(2) -UART0_RX_TX_IRQHandler - LDR R0, =UART0_RX_TX_DriverIRQHandler - BX R0 - - PUBWEAK UART0_ERR_IRQHandler - PUBWEAK UART0_ERR_DriverIRQHandler - SECTION .text:CODE:REORDER:NOROOT(2) -UART0_ERR_IRQHandler - LDR R0, =UART0_ERR_DriverIRQHandler - BX R0 - - PUBWEAK UART1_RX_TX_IRQHandler - PUBWEAK UART1_RX_TX_DriverIRQHandler - SECTION .text:CODE:REORDER:NOROOT(2) -UART1_RX_TX_IRQHandler - LDR R0, =UART1_RX_TX_DriverIRQHandler - BX R0 - - PUBWEAK UART1_ERR_IRQHandler - PUBWEAK UART1_ERR_DriverIRQHandler - SECTION .text:CODE:REORDER:NOROOT(2) -UART1_ERR_IRQHandler - LDR R0, =UART1_ERR_DriverIRQHandler - BX R0 - - PUBWEAK UART2_RX_TX_IRQHandler - PUBWEAK UART2_RX_TX_DriverIRQHandler - SECTION .text:CODE:REORDER:NOROOT(2) -UART2_RX_TX_IRQHandler - LDR R0, =UART2_RX_TX_DriverIRQHandler - BX R0 - - PUBWEAK UART2_ERR_IRQHandler - PUBWEAK UART2_ERR_DriverIRQHandler - SECTION .text:CODE:REORDER:NOROOT(2) -UART2_ERR_IRQHandler - LDR R0, =UART2_ERR_DriverIRQHandler - BX R0 - - PUBWEAK UART3_RX_TX_IRQHandler - PUBWEAK UART3_RX_TX_DriverIRQHandler - SECTION .text:CODE:REORDER:NOROOT(2) -UART3_RX_TX_IRQHandler - LDR R0, =UART3_RX_TX_DriverIRQHandler - BX R0 - - PUBWEAK UART3_ERR_IRQHandler - PUBWEAK UART3_ERR_DriverIRQHandler - SECTION .text:CODE:REORDER:NOROOT(2) -UART3_ERR_IRQHandler - LDR R0, =UART3_ERR_DriverIRQHandler - BX R0 - - PUBWEAK ADC0_IRQHandler - PUBWEAK CMP0_IRQHandler - PUBWEAK CMP1_IRQHandler - PUBWEAK FTM0_IRQHandler - PUBWEAK FTM1_IRQHandler - PUBWEAK FTM2_IRQHandler - PUBWEAK CMT_IRQHandler - PUBWEAK RTC_IRQHandler - PUBWEAK RTC_Seconds_IRQHandler - PUBWEAK PIT0_IRQHandler - PUBWEAK PIT1_IRQHandler - PUBWEAK PIT2_IRQHandler - PUBWEAK PIT3_IRQHandler - PUBWEAK PDB0_IRQHandler - PUBWEAK USB0_IRQHandler - PUBWEAK USBDCD_IRQHandler - PUBWEAK Reserved71_IRQHandler - PUBWEAK DAC0_IRQHandler - PUBWEAK MCG_IRQHandler - PUBWEAK LPTMR0_IRQHandler - PUBWEAK PORTA_IRQHandler - PUBWEAK PORTB_IRQHandler - PUBWEAK PORTC_IRQHandler - PUBWEAK PORTD_IRQHandler - PUBWEAK PORTE_IRQHandler - PUBWEAK SWI_IRQHandler - PUBWEAK SPI2_IRQHandler - PUBWEAK SPI2_DriverIRQHandler - SECTION .text:CODE:REORDER:NOROOT(2) -SPI2_IRQHandler - LDR R0, =SPI2_DriverIRQHandler - BX R0 - - PUBWEAK UART4_RX_TX_IRQHandler - PUBWEAK UART4_RX_TX_DriverIRQHandler - SECTION .text:CODE:REORDER:NOROOT(2) -UART4_RX_TX_IRQHandler - LDR R0, =UART4_RX_TX_DriverIRQHandler - BX R0 - - PUBWEAK UART4_ERR_IRQHandler - PUBWEAK UART4_ERR_DriverIRQHandler - SECTION .text:CODE:REORDER:NOROOT(2) -UART4_ERR_IRQHandler - LDR R0, =UART4_ERR_DriverIRQHandler - BX R0 - - PUBWEAK UART5_RX_TX_IRQHandler - PUBWEAK UART5_RX_TX_DriverIRQHandler - SECTION .text:CODE:REORDER:NOROOT(2) -UART5_RX_TX_IRQHandler - LDR R0, =UART5_RX_TX_DriverIRQHandler - BX R0 - - PUBWEAK UART5_ERR_IRQHandler - PUBWEAK UART5_ERR_DriverIRQHandler - SECTION .text:CODE:REORDER:NOROOT(2) -UART5_ERR_IRQHandler - LDR R0, =UART5_ERR_DriverIRQHandler - BX R0 - - PUBWEAK CMP2_IRQHandler - PUBWEAK FTM3_IRQHandler - PUBWEAK DAC1_IRQHandler - PUBWEAK ADC1_IRQHandler - PUBWEAK I2C2_IRQHandler - PUBWEAK I2C2_DriverIRQHandler - SECTION .text:CODE:REORDER:NOROOT(2) -I2C2_IRQHandler - LDR R0, =I2C2_DriverIRQHandler - BX R0 - - PUBWEAK CAN0_ORed_Message_buffer_IRQHandler - PUBWEAK CAN0_DriverIRQHandler - SECTION .text:CODE:REORDER:NOROOT(2) -CAN0_ORed_Message_buffer_IRQHandler - LDR R0, =CAN0_DriverIRQHandler - BX R0 - - PUBWEAK CAN0_Bus_Off_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(2) -CAN0_Bus_Off_IRQHandler - LDR R0, =CAN0_DriverIRQHandler - BX R0 - - PUBWEAK CAN0_Error_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(2) -CAN0_Error_IRQHandler - LDR R0, =CAN0_DriverIRQHandler - BX R0 - - PUBWEAK CAN0_Tx_Warning_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(2) -CAN0_Tx_Warning_IRQHandler - LDR R0, =CAN0_DriverIRQHandler - BX R0 - - PUBWEAK CAN0_Rx_Warning_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(2) -CAN0_Rx_Warning_IRQHandler - LDR R0, =CAN0_DriverIRQHandler - BX R0 - - PUBWEAK CAN0_Wake_Up_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(2) -CAN0_Wake_Up_IRQHandler - LDR R0, =CAN0_DriverIRQHandler - BX R0 - - PUBWEAK SDHC_IRQHandler - PUBWEAK SDHC_DriverIRQHandler - SECTION .text:CODE:REORDER:NOROOT(2) -SDHC_IRQHandler - LDR R0, =SDHC_DriverIRQHandler - BX R0 - - PUBWEAK Reserved98_IRQHandler - PUBWEAK Reserved99_IRQHandler - PUBWEAK Reserved100_IRQHandler - PUBWEAK Reserved101_IRQHandler - PUBWEAK DefaultISR - SECTION .text:CODE:REORDER:NOROOT(1) -DMA0_DriverIRQHandler -DMA1_DriverIRQHandler -DMA2_DriverIRQHandler -DMA3_DriverIRQHandler -DMA4_DriverIRQHandler -DMA5_DriverIRQHandler -DMA6_DriverIRQHandler -DMA7_DriverIRQHandler -DMA8_DriverIRQHandler -DMA9_DriverIRQHandler -DMA10_DriverIRQHandler -DMA11_DriverIRQHandler -DMA12_DriverIRQHandler -DMA13_DriverIRQHandler -DMA14_DriverIRQHandler -DMA15_DriverIRQHandler -DMA_Error_DriverIRQHandler -MCM_IRQHandler -FTFE_IRQHandler -Read_Collision_IRQHandler -LVD_LVW_IRQHandler -LLWU_IRQHandler -WDOG_EWM_IRQHandler -RNG_IRQHandler -I2C0_DriverIRQHandler -I2C1_DriverIRQHandler -SPI0_DriverIRQHandler -SPI1_DriverIRQHandler -I2S0_Tx_DriverIRQHandler -I2S0_Rx_DriverIRQHandler -UART0_LON_DriverIRQHandler -UART0_RX_TX_DriverIRQHandler -UART0_ERR_DriverIRQHandler -UART1_RX_TX_DriverIRQHandler -UART1_ERR_DriverIRQHandler -UART2_RX_TX_DriverIRQHandler -UART2_ERR_DriverIRQHandler -UART3_RX_TX_DriverIRQHandler -UART3_ERR_DriverIRQHandler -ADC0_IRQHandler -CMP0_IRQHandler -CMP1_IRQHandler -FTM0_IRQHandler -FTM1_IRQHandler -FTM2_IRQHandler -CMT_IRQHandler -RTC_IRQHandler -RTC_Seconds_IRQHandler -PIT0_IRQHandler -PIT1_IRQHandler -PIT2_IRQHandler -PIT3_IRQHandler -PDB0_IRQHandler -USB0_IRQHandler -USBDCD_IRQHandler -Reserved71_IRQHandler -DAC0_IRQHandler -MCG_IRQHandler -LPTMR0_IRQHandler -PORTA_IRQHandler -PORTB_IRQHandler -PORTC_IRQHandler -PORTD_IRQHandler -PORTE_IRQHandler -SWI_IRQHandler -SPI2_DriverIRQHandler -UART4_RX_TX_DriverIRQHandler -UART4_ERR_DriverIRQHandler -UART5_RX_TX_DriverIRQHandler -UART5_ERR_DriverIRQHandler -CMP2_IRQHandler -FTM3_IRQHandler -DAC1_IRQHandler -ADC1_IRQHandler -I2C2_DriverIRQHandler -CAN0_DriverIRQHandler -SDHC_DriverIRQHandler -Reserved98_IRQHandler -Reserved99_IRQHandler -Reserved100_IRQHandler -Reserved101_IRQHandler -DefaultISR - B DefaultISR - - END diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/device/cmsis.h b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/device/cmsis.h deleted file mode 100644 index b8ebe562ff9..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/device/cmsis.h +++ /dev/null @@ -1,13 +0,0 @@ -/* mbed Microcontroller Library - CMSIS - * Copyright (C) 2009-2017 ARM Limited. All rights reserved. - * - * A generic CMSIS include header, pulling in LPC11U24 specifics - */ - -#ifndef MBED_CMSIS_H -#define MBED_CMSIS_H - -#include "fsl_device_registers.h" -#include "cmsis_nvic.h" - -#endif diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/device/fsl_device_registers.h b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/device/fsl_device_registers.h deleted file mode 100644 index 585944e07ce..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/device/fsl_device_registers.h +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (c) 2014 - 2016, Freescale Semiconductor, Inc. - * Copyright 2016 - 2017 NXP - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - */ - -#ifndef __FSL_DEVICE_REGISTERS_H__ -#define __FSL_DEVICE_REGISTERS_H__ - -/* - * Include the cpu specific register header files. - * - * The CPU macro should be declared in the project or makefile. - */ -#if (defined(CPU_MK24FN1M0CAJ12) || defined(CPU_MK24FN1M0VDC12) || defined(CPU_MK24FN1M0VLL12) || \ - defined(CPU_MK24FN1M0VLQ12)) - -#define K24F12_SERIES - -/* CMSIS-style register definitions */ -#include "MK24F12.h" -/* CPU specific feature definitions */ -#include "MK24F12_features.h" - -#else - #error "No valid CPU defined!" -#endif - -#endif /* __FSL_DEVICE_REGISTERS_H__ */ - -/******************************************************************************* - * EOF - ******************************************************************************/ diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/device/system_MK24F12.c b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/device/system_MK24F12.c deleted file mode 100644 index fc8c34c77ff..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/device/system_MK24F12.c +++ /dev/null @@ -1,243 +0,0 @@ -/* -** ################################################################### -** Processors: MK24FN1M0CAJ12 -** MK24FN1M0VDC12 -** MK24FN1M0VLL12 -** MK24FN1M0VLQ12 -** -** Compilers: Keil ARM C/C++ Compiler -** Freescale C/C++ for Embedded ARM -** GNU C Compiler -** IAR ANSI C/C++ Compiler for ARM -** MCUXpresso Compiler -** -** Reference manual: K24P144M120SF5RM, Rev.2, January 2014 -** Version: rev. 2.8, 2016-03-21 -** Build: b170112 -** -** Abstract: -** Provides a system configuration function and a global variable that -** contains the system frequency. It configures the device and initializes -** the oscillator (PLL) that is part of the microcontroller device. -** -** Copyright (c) 2016 Freescale Semiconductor, Inc. -** Copyright 2016 - 2017 NXP -** Redistribution and use in source and binary forms, with or without modification, -** are permitted provided that the following conditions are met: -** -** o Redistributions of source code must retain the above copyright notice, this list -** of conditions and the following disclaimer. -** -** o Redistributions in binary form must reproduce the above copyright notice, this -** list of conditions and the following disclaimer in the documentation and/or -** other materials provided with the distribution. -** -** o Neither the name of the copyright holder nor the names of its -** contributors may be used to endorse or promote products derived from this -** software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -** ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -** LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -** ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -** -** http: www.nxp.com -** mail: support@nxp.com -** -** Revisions: -** - rev. 1.0 (2013-08-12) -** Initial version. -** - rev. 2.0 (2013-10-29) -** Register accessor macros added to the memory map. -** Symbols for Processor Expert memory map compatibility added to the memory map. -** Startup file for gcc has been updated according to CMSIS 3.2. -** System initialization updated. -** MCG - registers updated. -** PORTA, PORTB, PORTC, PORTE - registers for digital filter removed. -** - rev. 2.1 (2013-10-30) -** Definition of BITBAND macros updated to support peripherals with 32-bit acces disabled. -** - rev. 2.2 (2013-12-09) -** DMA - EARS register removed. -** AIPS0, AIPS1 - MPRA register updated. -** - rev. 2.3 (2014-01-24) -** Update according to reference manual rev. 2 -** ENET, MCG, MCM, SIM, USB - registers updated -** - rev. 2.4 (2014-02-10) -** The declaration of clock configurations has been moved to separate header file system_MK24F12.h -** Update of SystemInit() and SystemCoreClockUpdate() functions. -** Module access macro module_BASES replaced by module_BASE_PTRS. -** - rev. 2.5 (2014-08-28) -** Update of system files - default clock configuration changed. -** Update of startup files - possibility to override DefaultISR added. -** - rev. 2.6 (2014-10-14) -** Interrupt INT_LPTimer renamed to INT_LPTMR0, interrupt INT_Watchdog renamed to INT_WDOG_EWM. -** - rev. 2.7 (2015-02-19) -** Renamed interrupt vector LLW to LLWU. -** - rev. 2.8 (2016-03-21) -** Added MK24FN1M0CAJ12 part. -** GPIO - renamed port instances: PTx -> GPIOx. -** -** ################################################################### -*/ - -/*! - * @file MK24F12 - * @version 2.8 - * @date 2016-03-21 - * @brief Device specific configuration file for MK24F12 (implementation file) - * - * Provides a system configuration function and a global variable that contains - * the system frequency. It configures the device and initializes the oscillator - * (PLL) that is part of the microcontroller device. - */ - -#include -#include "fsl_device_registers.h" - - - -/* ---------------------------------------------------------------------------- - -- Core clock - ---------------------------------------------------------------------------- */ - -uint32_t SystemCoreClock = DEFAULT_SYSTEM_CLOCK; - -/* ---------------------------------------------------------------------------- - -- SystemInit() - ---------------------------------------------------------------------------- */ - -void SystemInit (void) { -#if ((__FPU_PRESENT == 1) && (__FPU_USED == 1)) - SCB->CPACR |= ((3UL << 10*2) | (3UL << 11*2)); /* set CP10, CP11 Full Access */ -#endif /* ((__FPU_PRESENT == 1) && (__FPU_USED == 1)) */ -#if (DISABLE_WDOG) - /* WDOG->UNLOCK: WDOGUNLOCK=0xC520 */ - WDOG->UNLOCK = WDOG_UNLOCK_WDOGUNLOCK(0xC520); /* Key 1 */ - /* WDOG->UNLOCK: WDOGUNLOCK=0xD928 */ - WDOG->UNLOCK = WDOG_UNLOCK_WDOGUNLOCK(0xD928); /* Key 2 */ - /* WDOG->STCTRLH: ?=0,DISTESTWDOG=0,BYTESEL=0,TESTSEL=0,TESTWDOG=0,?=0,?=1,WAITEN=1,STOPEN=1,DBGEN=0,ALLOWUPDATE=1,WINEN=0,IRQRSTEN=0,CLKSRC=1,WDOGEN=0 */ - WDOG->STCTRLH = WDOG_STCTRLH_BYTESEL(0x00) | - WDOG_STCTRLH_WAITEN_MASK | - WDOG_STCTRLH_STOPEN_MASK | - WDOG_STCTRLH_ALLOWUPDATE_MASK | - WDOG_STCTRLH_CLKSRC_MASK | - 0x0100U; -#endif /* (DISABLE_WDOG) */ - -} - -/* ---------------------------------------------------------------------------- - -- SystemCoreClockUpdate() - ---------------------------------------------------------------------------- */ - -void SystemCoreClockUpdate (void) { - uint32_t MCGOUTClock; /* Variable to store output clock frequency of the MCG module */ - uint16_t Divider; - - if ((MCG->C1 & MCG_C1_CLKS_MASK) == 0x00U) { - /* Output of FLL or PLL is selected */ - if ((MCG->C6 & MCG_C6_PLLS_MASK) == 0x00U) { - /* FLL is selected */ - if ((MCG->C1 & MCG_C1_IREFS_MASK) == 0x00U) { - /* External reference clock is selected */ - switch (MCG->C7 & MCG_C7_OSCSEL_MASK) { - case 0x00U: - MCGOUTClock = CPU_XTAL_CLK_HZ; /* System oscillator drives MCG clock */ - break; - case 0x01U: - MCGOUTClock = CPU_XTAL32k_CLK_HZ; /* RTC 32 kHz oscillator drives MCG clock */ - break; - case 0x02U: - default: - MCGOUTClock = CPU_INT_IRC_CLK_HZ; /* IRC 48MHz oscillator drives MCG clock */ - break; - } - if (((MCG->C2 & MCG_C2_RANGE_MASK) != 0x00U) && ((MCG->C7 & MCG_C7_OSCSEL_MASK) != 0x01U)) { - switch (MCG->C1 & MCG_C1_FRDIV_MASK) { - case 0x38U: - Divider = 1536U; - break; - case 0x30U: - Divider = 1280U; - break; - default: - Divider = (uint16_t)(32LU << ((MCG->C1 & MCG_C1_FRDIV_MASK) >> MCG_C1_FRDIV_SHIFT)); - break; - } - } else {/* ((MCG->C2 & MCG_C2_RANGE_MASK) != 0x00U) */ - Divider = (uint16_t)(1LU << ((MCG->C1 & MCG_C1_FRDIV_MASK) >> MCG_C1_FRDIV_SHIFT)); - } - MCGOUTClock = (MCGOUTClock / Divider); /* Calculate the divided FLL reference clock */ - } else { /* (!((MCG->C1 & MCG_C1_IREFS_MASK) == 0x00U)) */ - MCGOUTClock = CPU_INT_SLOW_CLK_HZ; /* The slow internal reference clock is selected */ - } /* (!((MCG->C1 & MCG_C1_IREFS_MASK) == 0x00U)) */ - /* Select correct multiplier to calculate the MCG output clock */ - switch (MCG->C4 & (MCG_C4_DMX32_MASK | MCG_C4_DRST_DRS_MASK)) { - case 0x00U: - MCGOUTClock *= 640U; - break; - case 0x20U: - MCGOUTClock *= 1280U; - break; - case 0x40U: - MCGOUTClock *= 1920U; - break; - case 0x60U: - MCGOUTClock *= 2560U; - break; - case 0x80U: - MCGOUTClock *= 732U; - break; - case 0xA0U: - MCGOUTClock *= 1464U; - break; - case 0xC0U: - MCGOUTClock *= 2197U; - break; - case 0xE0U: - MCGOUTClock *= 2929U; - break; - default: - break; - } - } else { /* (!((MCG->C6 & MCG_C6_PLLS_MASK) == 0x00U)) */ - /* PLL is selected */ - Divider = (((uint16_t)MCG->C5 & MCG_C5_PRDIV0_MASK) + 0x01U); - MCGOUTClock = (uint32_t)(CPU_XTAL_CLK_HZ / Divider); /* Calculate the PLL reference clock */ - Divider = (((uint16_t)MCG->C6 & MCG_C6_VDIV0_MASK) + 24U); - MCGOUTClock *= Divider; /* Calculate the MCG output clock */ - } /* (!((MCG->C6 & MCG_C6_PLLS_MASK) == 0x00U)) */ - } else if ((MCG->C1 & MCG_C1_CLKS_MASK) == 0x40U) { - /* Internal reference clock is selected */ - if ((MCG->C2 & MCG_C2_IRCS_MASK) == 0x00U) { - MCGOUTClock = CPU_INT_SLOW_CLK_HZ; /* Slow internal reference clock selected */ - } else { /* (!((MCG->C2 & MCG_C2_IRCS_MASK) == 0x00U)) */ - Divider = (uint16_t)(0x01LU << ((MCG->SC & MCG_SC_FCRDIV_MASK) >> MCG_SC_FCRDIV_SHIFT)); - MCGOUTClock = (uint32_t) (CPU_INT_FAST_CLK_HZ / Divider); /* Fast internal reference clock selected */ - } /* (!((MCG->C2 & MCG_C2_IRCS_MASK) == 0x00U)) */ - } else if ((MCG->C1 & MCG_C1_CLKS_MASK) == 0x80U) { - /* External reference clock is selected */ - switch (MCG->C7 & MCG_C7_OSCSEL_MASK) { - case 0x00U: - MCGOUTClock = CPU_XTAL_CLK_HZ; /* System oscillator drives MCG clock */ - break; - case 0x01U: - MCGOUTClock = CPU_XTAL32k_CLK_HZ; /* RTC 32 kHz oscillator drives MCG clock */ - break; - case 0x02U: - default: - MCGOUTClock = CPU_INT_IRC_CLK_HZ; /* IRC 48MHz oscillator drives MCG clock */ - break; - } - } else { /* (!((MCG->C1 & MCG_C1_CLKS_MASK) == 0x80U)) */ - /* Reserved value */ - return; - } /* (!((MCG->C1 & MCG_C1_CLKS_MASK) == 0x80U)) */ - SystemCoreClock = (MCGOUTClock / (0x01U + ((SIM->CLKDIV1 & SIM_CLKDIV1_OUTDIV1_MASK) >> SIM_CLKDIV1_OUTDIV1_SHIFT))); -} diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/device/system_MK24F12.h b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/device/system_MK24F12.h deleted file mode 100644 index 6ce1ded2adb..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/device/system_MK24F12.h +++ /dev/null @@ -1,166 +0,0 @@ -/* -** ################################################################### -** Processors: MK24FN1M0CAJ12 -** MK24FN1M0VDC12 -** MK24FN1M0VLL12 -** MK24FN1M0VLQ12 -** -** Compilers: Keil ARM C/C++ Compiler -** Freescale C/C++ for Embedded ARM -** GNU C Compiler -** IAR ANSI C/C++ Compiler for ARM -** MCUXpresso Compiler -** -** Reference manual: K24P144M120SF5RM, Rev.2, January 2014 -** Version: rev. 2.8, 2016-03-21 -** Build: b170112 -** -** Abstract: -** Provides a system configuration function and a global variable that -** contains the system frequency. It configures the device and initializes -** the oscillator (PLL) that is part of the microcontroller device. -** -** Copyright (c) 2016 Freescale Semiconductor, Inc. -** Copyright 2016 - 2017 NXP -** Redistribution and use in source and binary forms, with or without modification, -** are permitted provided that the following conditions are met: -** -** o Redistributions of source code must retain the above copyright notice, this list -** of conditions and the following disclaimer. -** -** o Redistributions in binary form must reproduce the above copyright notice, this -** list of conditions and the following disclaimer in the documentation and/or -** other materials provided with the distribution. -** -** o Neither the name of the copyright holder nor the names of its -** contributors may be used to endorse or promote products derived from this -** software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -** ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -** LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -** ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -** -** http: www.nxp.com -** mail: support@nxp.com -** -** Revisions: -** - rev. 1.0 (2013-08-12) -** Initial version. -** - rev. 2.0 (2013-10-29) -** Register accessor macros added to the memory map. -** Symbols for Processor Expert memory map compatibility added to the memory map. -** Startup file for gcc has been updated according to CMSIS 3.2. -** System initialization updated. -** MCG - registers updated. -** PORTA, PORTB, PORTC, PORTE - registers for digital filter removed. -** - rev. 2.1 (2013-10-30) -** Definition of BITBAND macros updated to support peripherals with 32-bit acces disabled. -** - rev. 2.2 (2013-12-09) -** DMA - EARS register removed. -** AIPS0, AIPS1 - MPRA register updated. -** - rev. 2.3 (2014-01-24) -** Update according to reference manual rev. 2 -** ENET, MCG, MCM, SIM, USB - registers updated -** - rev. 2.4 (2014-02-10) -** The declaration of clock configurations has been moved to separate header file system_MK24F12.h -** Update of SystemInit() and SystemCoreClockUpdate() functions. -** Module access macro module_BASES replaced by module_BASE_PTRS. -** - rev. 2.5 (2014-08-28) -** Update of system files - default clock configuration changed. -** Update of startup files - possibility to override DefaultISR added. -** - rev. 2.6 (2014-10-14) -** Interrupt INT_LPTimer renamed to INT_LPTMR0, interrupt INT_Watchdog renamed to INT_WDOG_EWM. -** - rev. 2.7 (2015-02-19) -** Renamed interrupt vector LLW to LLWU. -** - rev. 2.8 (2016-03-21) -** Added MK24FN1M0CAJ12 part. -** GPIO - renamed port instances: PTx -> GPIOx. -** -** ################################################################### -*/ - -/*! - * @file MK24F12 - * @version 2.8 - * @date 2016-03-21 - * @brief Device specific configuration file for MK24F12 (header file) - * - * Provides a system configuration function and a global variable that contains - * the system frequency. It configures the device and initializes the oscillator - * (PLL) that is part of the microcontroller device. - */ - -#ifndef _SYSTEM_MK24F12_H_ -#define _SYSTEM_MK24F12_H_ /**< Symbol preventing repeated inclusion */ - -#ifdef __cplusplus -extern "C" { -#endif - -#include - - -#ifndef DISABLE_WDOG - #define DISABLE_WDOG 1 -#endif - -/* Define clock source values */ - -#define CPU_XTAL_CLK_HZ 50000000u /* Value of the external crystal or oscillator clock frequency in Hz */ -#define CPU_XTAL32k_CLK_HZ 32768u /* Value of the external 32k crystal or oscillator clock frequency in Hz */ -#define CPU_INT_SLOW_CLK_HZ 32768u /* Value of the slow internal oscillator clock frequency in Hz */ -#define CPU_INT_FAST_CLK_HZ 4000000u /* Value of the fast internal oscillator clock frequency in Hz */ -#define CPU_INT_IRC_CLK_HZ 48000000u /* Value of the 48M internal oscillator clock frequency in Hz */ - -/* RTC oscillator setting */ -/* RTC_CR: SC2P=0,SC4P=0,SC8P=0,SC16P=0,CLKO=1,OSCE=1,WPS=0,UM=0,SUP=0,WPE=0,SWR=0 */ -#define SYSTEM_RTC_CR_VALUE 0x0300U /* RTC_CR */ - -/* Low power mode enable */ -/* SMC_PMPROT: AVLP=1,ALLS=1,AVLLS=1 */ -#define SYSTEM_SMC_PMPROT_VALUE 0x2AU /* SMC_PMPROT */ - -#define DEFAULT_SYSTEM_CLOCK 20971520u /* Default System clock value */ - - -/** - * @brief System clock frequency (core clock) - * - * The system clock frequency supplied to the SysTick timer and the processor - * core clock. This variable can be used by the user application to setup the - * SysTick timer or configure other parameters. It may also be used by debugger to - * query the frequency of the debug timer or configure the trace clock speed - * SystemCoreClock is initialized with a correct predefined value. - */ -extern uint32_t SystemCoreClock; - -/** - * @brief Setup the microcontroller system. - * - * Typically this function configures the oscillator (PLL) that is part of the - * microcontroller device. For systems with variable clock speed it also updates - * the variable SystemCoreClock. SystemInit is called from startup_device file. - */ -void SystemInit (void); - -/** - * @brief Updates the SystemCoreClock variable. - * - * It must be called whenever the core clock is changed during program - * execution. SystemCoreClockUpdate() evaluates the clock register settings and calculates - * the current core clock. - */ -void SystemCoreClockUpdate (void); - -#ifdef __cplusplus -} -#endif - -#endif /* _SYSTEM_MK24F12_H_ */ diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/dma_reqs.h b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/dma_reqs.h deleted file mode 100644 index 13fbaf19528..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/dma_reqs.h +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (c) 2016, Freescale Semiconductor, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of Freescale Semiconductor, Inc. nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef _FSL_DMA_REQS_H_ -#define _FSL_DMA_REQS_H_ - -#include "fsl_common.h" - -/* Array for DSPI DMA TX requests */ -#define SPI_DMA_TX_REQUEST_NUMBERS \ - { \ - kDmaRequestMux0SPI0Tx, kDmaRequestMux0SPI1, kDmaRequestMux0SPI2 \ - } - -/* Array for DSPI DMA RX requests */ -#define SPI_DMA_RX_REQUEST_NUMBERS \ - { \ - kDmaRequestMux0SPI0Rx, kDmaRequestMux0SPI1, kDmaRequestMux0SPI2 \ - } - -/* Array for UART DMA TX requests */ -#define UART_DMA_TX_REQUEST_NUMBERS \ - { \ - kDmaRequestMux0UART0Tx, kDmaRequestMux0UART1Tx, kDmaRequestMux0UART2Tx, \ - kDmaRequestMux0UART3Tx, kDmaRequestMux0UART4, kDmaRequestMux0UART5 \ - } - -/* Array for UART DMA RX requests */ -#define UART_DMA_RX_REQUEST_NUMBERS \ - { \ - kDmaRequestMux0UART0Rx, kDmaRequestMux0UART1Rx, kDmaRequestMux0UART2Rx, \ - kDmaRequestMux0UART3Rx, kDmaRequestMux0UART4, kDmaRequestMux0UART5 \ - } - -#endif /* _FSL_DMA_REQS_H_ */ diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_adc16.c b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_adc16.c deleted file mode 100644 index 0af6a4443e9..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_adc16.c +++ /dev/null @@ -1,370 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "fsl_adc16.h" - -/******************************************************************************* - * Prototypes - ******************************************************************************/ -/*! - * @brief Get instance number for ADC16 module. - * - * @param base ADC16 peripheral base address - */ -static uint32_t ADC16_GetInstance(ADC_Type *base); - -/******************************************************************************* - * Variables - ******************************************************************************/ -/*! @brief Pointers to ADC16 bases for each instance. */ -static ADC_Type *const s_adc16Bases[] = ADC_BASE_PTRS; - -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) -/*! @brief Pointers to ADC16 clocks for each instance. */ -static const clock_ip_name_t s_adc16Clocks[] = ADC16_CLOCKS; -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ - -/******************************************************************************* - * Code - ******************************************************************************/ -static uint32_t ADC16_GetInstance(ADC_Type *base) -{ - uint32_t instance; - - /* Find the instance index from base address mappings. */ - for (instance = 0; instance < ARRAY_SIZE(s_adc16Bases); instance++) - { - if (s_adc16Bases[instance] == base) - { - break; - } - } - - assert(instance < ARRAY_SIZE(s_adc16Bases)); - - return instance; -} - -void ADC16_Init(ADC_Type *base, const adc16_config_t *config) -{ - assert(NULL != config); - - uint32_t tmp32; - -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) - /* Enable the clock. */ - CLOCK_EnableClock(s_adc16Clocks[ADC16_GetInstance(base)]); -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ - - /* ADCx_CFG1. */ - tmp32 = ADC_CFG1_ADICLK(config->clockSource) | ADC_CFG1_MODE(config->resolution); - if (kADC16_LongSampleDisabled != config->longSampleMode) - { - tmp32 |= ADC_CFG1_ADLSMP_MASK; - } - tmp32 |= ADC_CFG1_ADIV(config->clockDivider); - if (config->enableLowPower) - { - tmp32 |= ADC_CFG1_ADLPC_MASK; - } - base->CFG1 = tmp32; - - /* ADCx_CFG2. */ - tmp32 = base->CFG2 & ~(ADC_CFG2_ADACKEN_MASK | ADC_CFG2_ADHSC_MASK | ADC_CFG2_ADLSTS_MASK); - if (kADC16_LongSampleDisabled != config->longSampleMode) - { - tmp32 |= ADC_CFG2_ADLSTS(config->longSampleMode); - } - if (config->enableHighSpeed) - { - tmp32 |= ADC_CFG2_ADHSC_MASK; - } - if (config->enableAsynchronousClock) - { - tmp32 |= ADC_CFG2_ADACKEN_MASK; - } - base->CFG2 = tmp32; - - /* ADCx_SC2. */ - tmp32 = base->SC2 & ~(ADC_SC2_REFSEL_MASK); - tmp32 |= ADC_SC2_REFSEL(config->referenceVoltageSource); - base->SC2 = tmp32; - - /* ADCx_SC3. */ - if (config->enableContinuousConversion) - { - base->SC3 |= ADC_SC3_ADCO_MASK; - } - else - { - base->SC3 &= ~ADC_SC3_ADCO_MASK; - } -} - -void ADC16_Deinit(ADC_Type *base) -{ -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) - /* Disable the clock. */ - CLOCK_DisableClock(s_adc16Clocks[ADC16_GetInstance(base)]); -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ -} - -void ADC16_GetDefaultConfig(adc16_config_t *config) -{ - assert(NULL != config); - - config->referenceVoltageSource = kADC16_ReferenceVoltageSourceVref; - config->clockSource = kADC16_ClockSourceAsynchronousClock; - config->enableAsynchronousClock = true; - config->clockDivider = kADC16_ClockDivider8; - config->resolution = kADC16_ResolutionSE12Bit; - config->longSampleMode = kADC16_LongSampleDisabled; - config->enableHighSpeed = false; - config->enableLowPower = false; - config->enableContinuousConversion = false; -} - -#if defined(FSL_FEATURE_ADC16_HAS_CALIBRATION) && FSL_FEATURE_ADC16_HAS_CALIBRATION -status_t ADC16_DoAutoCalibration(ADC_Type *base) -{ - bool bHWTrigger = false; - volatile uint32_t tmp32; /* 'volatile' here is for the dummy read of ADCx_R[0] register. */ - status_t status = kStatus_Success; - - /* The calibration would be failed when in hardwar mode. - * Remember the hardware trigger state here and restore it later if the hardware trigger is enabled.*/ - if (0U != (ADC_SC2_ADTRG_MASK & base->SC2)) - { - bHWTrigger = true; - base->SC2 &= ~ADC_SC2_ADTRG_MASK; - } - - /* Clear the CALF and launch the calibration. */ - base->SC3 |= ADC_SC3_CAL_MASK | ADC_SC3_CALF_MASK; - while (0U == (kADC16_ChannelConversionDoneFlag & ADC16_GetChannelStatusFlags(base, 0U))) - { - /* Check the CALF when the calibration is active. */ - if (0U != (kADC16_CalibrationFailedFlag & ADC16_GetStatusFlags(base))) - { - status = kStatus_Fail; - break; - } - } - tmp32 = base->R[0]; /* Dummy read to clear COCO caused by calibration. */ - - /* Restore the hardware trigger setting if it was enabled before. */ - if (bHWTrigger) - { - base->SC2 |= ADC_SC2_ADTRG_MASK; - } - /* Check the CALF at the end of calibration. */ - if (0U != (kADC16_CalibrationFailedFlag & ADC16_GetStatusFlags(base))) - { - status = kStatus_Fail; - } - if (kStatus_Success != status) /* Check if the calibration process is succeed. */ - { - return status; - } - - /* Calculate the calibration values. */ - tmp32 = base->CLP0 + base->CLP1 + base->CLP2 + base->CLP3 + base->CLP4 + base->CLPS; - tmp32 = 0x8000U | (tmp32 >> 1U); - base->PG = tmp32; - -#if defined(FSL_FEATURE_ADC16_HAS_DIFF_MODE) && FSL_FEATURE_ADC16_HAS_DIFF_MODE - tmp32 = base->CLM0 + base->CLM1 + base->CLM2 + base->CLM3 + base->CLM4 + base->CLMS; - tmp32 = 0x8000U | (tmp32 >> 1U); - base->MG = tmp32; -#endif /* FSL_FEATURE_ADC16_HAS_DIFF_MODE */ - - return kStatus_Success; -} -#endif /* FSL_FEATURE_ADC16_HAS_CALIBRATION */ - -#if defined(FSL_FEATURE_ADC16_HAS_MUX_SELECT) && FSL_FEATURE_ADC16_HAS_MUX_SELECT -void ADC16_SetChannelMuxMode(ADC_Type *base, adc16_channel_mux_mode_t mode) -{ - if (kADC16_ChannelMuxA == mode) - { - base->CFG2 &= ~ADC_CFG2_MUXSEL_MASK; - } - else /* kADC16_ChannelMuxB. */ - { - base->CFG2 |= ADC_CFG2_MUXSEL_MASK; - } -} -#endif /* FSL_FEATURE_ADC16_HAS_MUX_SELECT */ - -void ADC16_SetHardwareCompareConfig(ADC_Type *base, const adc16_hardware_compare_config_t *config) -{ - uint32_t tmp32 = base->SC2 & ~(ADC_SC2_ACFE_MASK | ADC_SC2_ACFGT_MASK | ADC_SC2_ACREN_MASK); - - if (!config) /* Pass "NULL" to disable the feature. */ - { - base->SC2 = tmp32; - return; - } - /* Enable the feature. */ - tmp32 |= ADC_SC2_ACFE_MASK; - - /* Select the hardware compare working mode. */ - switch (config->hardwareCompareMode) - { - case kADC16_HardwareCompareMode0: - break; - case kADC16_HardwareCompareMode1: - tmp32 |= ADC_SC2_ACFGT_MASK; - break; - case kADC16_HardwareCompareMode2: - tmp32 |= ADC_SC2_ACREN_MASK; - break; - case kADC16_HardwareCompareMode3: - tmp32 |= ADC_SC2_ACFGT_MASK | ADC_SC2_ACREN_MASK; - break; - default: - break; - } - base->SC2 = tmp32; - - /* Load the compare values. */ - base->CV1 = ADC_CV1_CV(config->value1); - base->CV2 = ADC_CV2_CV(config->value2); -} - -#if defined(FSL_FEATURE_ADC16_HAS_HW_AVERAGE) && FSL_FEATURE_ADC16_HAS_HW_AVERAGE -void ADC16_SetHardwareAverage(ADC_Type *base, adc16_hardware_average_mode_t mode) -{ - uint32_t tmp32 = base->SC3 & ~(ADC_SC3_AVGE_MASK | ADC_SC3_AVGS_MASK); - - if (kADC16_HardwareAverageDisabled != mode) - { - tmp32 |= ADC_SC3_AVGE_MASK | ADC_SC3_AVGS(mode); - } - base->SC3 = tmp32; -} -#endif /* FSL_FEATURE_ADC16_HAS_HW_AVERAGE */ - -#if defined(FSL_FEATURE_ADC16_HAS_PGA) && FSL_FEATURE_ADC16_HAS_PGA -void ADC16_SetPGAConfig(ADC_Type *base, const adc16_pga_config_t *config) -{ - uint32_t tmp32; - - if (!config) /* Passing "NULL" is to disable the feature. */ - { - base->PGA = 0U; - return; - } - - /* Enable the PGA and set the gain value. */ - tmp32 = ADC_PGA_PGAEN_MASK | ADC_PGA_PGAG(config->pgaGain); - - /* Configure the misc features for PGA. */ - if (config->enableRunInNormalMode) - { - tmp32 |= ADC_PGA_PGALPb_MASK; - } -#if defined(FSL_FEATURE_ADC16_HAS_PGA_CHOPPING) && FSL_FEATURE_ADC16_HAS_PGA_CHOPPING - if (config->disablePgaChopping) - { - tmp32 |= ADC_PGA_PGACHPb_MASK; - } -#endif /* FSL_FEATURE_ADC16_HAS_PGA_CHOPPING */ -#if defined(FSL_FEATURE_ADC16_HAS_PGA_OFFSET_MEASUREMENT) && FSL_FEATURE_ADC16_HAS_PGA_OFFSET_MEASUREMENT - if (config->enableRunInOffsetMeasurement) - { - tmp32 |= ADC_PGA_PGAOFSM_MASK; - } -#endif /* FSL_FEATURE_ADC16_HAS_PGA_OFFSET_MEASUREMENT */ - base->PGA = tmp32; -} -#endif /* FSL_FEATURE_ADC16_HAS_PGA */ - -uint32_t ADC16_GetStatusFlags(ADC_Type *base) -{ - uint32_t ret = 0; - - if (0U != (base->SC2 & ADC_SC2_ADACT_MASK)) - { - ret |= kADC16_ActiveFlag; - } -#if defined(FSL_FEATURE_ADC16_HAS_CALIBRATION) && FSL_FEATURE_ADC16_HAS_CALIBRATION - if (0U != (base->SC3 & ADC_SC3_CALF_MASK)) - { - ret |= kADC16_CalibrationFailedFlag; - } -#endif /* FSL_FEATURE_ADC16_HAS_CALIBRATION */ - return ret; -} - -void ADC16_ClearStatusFlags(ADC_Type *base, uint32_t mask) -{ -#if defined(FSL_FEATURE_ADC16_HAS_CALIBRATION) && FSL_FEATURE_ADC16_HAS_CALIBRATION - if (0U != (mask & kADC16_CalibrationFailedFlag)) - { - base->SC3 |= ADC_SC3_CALF_MASK; - } -#endif /* FSL_FEATURE_ADC16_HAS_CALIBRATION */ -} - -void ADC16_SetChannelConfig(ADC_Type *base, uint32_t channelGroup, const adc16_channel_config_t *config) -{ - assert(channelGroup < ADC_SC1_COUNT); - assert(NULL != config); - - uint32_t sc1 = ADC_SC1_ADCH(config->channelNumber); /* Set the channel number. */ - -#if defined(FSL_FEATURE_ADC16_HAS_DIFF_MODE) && FSL_FEATURE_ADC16_HAS_DIFF_MODE - /* Enable the differential conversion. */ - if (config->enableDifferentialConversion) - { - sc1 |= ADC_SC1_DIFF_MASK; - } -#endif /* FSL_FEATURE_ADC16_HAS_DIFF_MODE */ - /* Enable the interrupt when the conversion is done. */ - if (config->enableInterruptOnConversionCompleted) - { - sc1 |= ADC_SC1_AIEN_MASK; - } - base->SC1[channelGroup] = sc1; -} - -uint32_t ADC16_GetChannelStatusFlags(ADC_Type *base, uint32_t channelGroup) -{ - assert(channelGroup < ADC_SC1_COUNT); - - uint32_t ret = 0U; - - if (0U != (base->SC1[channelGroup] & ADC_SC1_COCO_MASK)) - { - ret |= kADC16_ChannelConversionDoneFlag; - } - return ret; -} diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_adc16.h b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_adc16.h deleted file mode 100644 index ea62c55fee6..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_adc16.h +++ /dev/null @@ -1,525 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef _FSL_ADC16_H_ -#define _FSL_ADC16_H_ - -#include "fsl_common.h" - -/*! - * @addtogroup adc16 - * @{ - */ - - -/******************************************************************************* - * Definitions - ******************************************************************************/ - -/*! @name Driver version */ -/*@{*/ -/*! @brief ADC16 driver version 2.0.0. */ -#define FSL_ADC16_DRIVER_VERSION (MAKE_VERSION(2, 0, 0)) -/*@}*/ - -/*! - * @brief Channel status flags. - */ -enum _adc16_channel_status_flags -{ - kADC16_ChannelConversionDoneFlag = ADC_SC1_COCO_MASK, /*!< Conversion done. */ -}; - -/*! - * @brief Converter status flags. - */ -enum _adc16_status_flags -{ - kADC16_ActiveFlag = ADC_SC2_ADACT_MASK, /*!< Converter is active. */ -#if defined(FSL_FEATURE_ADC16_HAS_CALIBRATION) && FSL_FEATURE_ADC16_HAS_CALIBRATION - kADC16_CalibrationFailedFlag = ADC_SC3_CALF_MASK, /*!< Calibration is failed. */ -#endif /* FSL_FEATURE_ADC16_HAS_CALIBRATION */ -}; - -#if defined(FSL_FEATURE_ADC16_HAS_MUX_SELECT) && FSL_FEATURE_ADC16_HAS_MUX_SELECT -/*! - * @brief Channel multiplexer mode for each channel. - * - * For some ADC16 channels, there are two pin selections in channel multiplexer. For example, ADC0_SE4a and ADC0_SE4b - * are the different channels that share the same channel number. - */ -typedef enum _adc_channel_mux_mode -{ - kADC16_ChannelMuxA = 0U, /*!< For channel with channel mux a. */ - kADC16_ChannelMuxB = 1U, /*!< For channel with channel mux b. */ -} adc16_channel_mux_mode_t; -#endif /* FSL_FEATURE_ADC16_HAS_MUX_SELECT */ - -/*! - * @brief Clock divider for the converter. - */ -typedef enum _adc16_clock_divider -{ - kADC16_ClockDivider1 = 0U, /*!< For divider 1 from the input clock to the module. */ - kADC16_ClockDivider2 = 1U, /*!< For divider 2 from the input clock to the module. */ - kADC16_ClockDivider4 = 2U, /*!< For divider 4 from the input clock to the module. */ - kADC16_ClockDivider8 = 3U, /*!< For divider 8 from the input clock to the module. */ -} adc16_clock_divider_t; - -/*! - *@brief Converter's resolution. - */ -typedef enum _adc16_resolution -{ - /* This group of enumeration is for internal use which is related to register setting. */ - kADC16_Resolution8or9Bit = 0U, /*!< Single End 8-bit or Differential Sample 9-bit. */ - kADC16_Resolution12or13Bit = 1U, /*!< Single End 12-bit or Differential Sample 13-bit. */ - kADC16_Resolution10or11Bit = 2U, /*!< Single End 10-bit or Differential Sample 11-bit. */ - - /* This group of enumeration is for a public user. */ - kADC16_ResolutionSE8Bit = kADC16_Resolution8or9Bit, /*!< Single End 8-bit. */ - kADC16_ResolutionSE12Bit = kADC16_Resolution12or13Bit, /*!< Single End 12-bit. */ - kADC16_ResolutionSE10Bit = kADC16_Resolution10or11Bit, /*!< Single End 10-bit. */ -#if defined(FSL_FEATURE_ADC16_HAS_DIFF_MODE) && FSL_FEATURE_ADC16_HAS_DIFF_MODE - kADC16_ResolutionDF9Bit = kADC16_Resolution8or9Bit, /*!< Differential Sample 9-bit. */ - kADC16_ResolutionDF13Bit = kADC16_Resolution12or13Bit, /*!< Differential Sample 13-bit. */ - kADC16_ResolutionDF11Bit = kADC16_Resolution10or11Bit, /*!< Differential Sample 11-bit. */ -#endif /* FSL_FEATURE_ADC16_HAS_DIFF_MODE */ - -#if defined(FSL_FEATURE_ADC16_MAX_RESOLUTION) && (FSL_FEATURE_ADC16_MAX_RESOLUTION >= 16U) - /* 16-bit is supported by default. */ - kADC16_Resolution16Bit = 3U, /*!< Single End 16-bit or Differential Sample 16-bit. */ - kADC16_ResolutionSE16Bit = kADC16_Resolution16Bit, /*!< Single End 16-bit. */ -#if defined(FSL_FEATURE_ADC16_HAS_DIFF_MODE) && FSL_FEATURE_ADC16_HAS_DIFF_MODE - kADC16_ResolutionDF16Bit = kADC16_Resolution16Bit, /*!< Differential Sample 16-bit. */ -#endif /* FSL_FEATURE_ADC16_HAS_DIFF_MODE */ -#endif /* FSL_FEATURE_ADC16_MAX_RESOLUTION >= 16U */ -} adc16_resolution_t; - -/*! - * @brief Clock source. - */ -typedef enum _adc16_clock_source -{ - kADC16_ClockSourceAlt0 = 0U, /*!< Selection 0 of the clock source. */ - kADC16_ClockSourceAlt1 = 1U, /*!< Selection 1 of the clock source. */ - kADC16_ClockSourceAlt2 = 2U, /*!< Selection 2 of the clock source. */ - kADC16_ClockSourceAlt3 = 3U, /*!< Selection 3 of the clock source. */ - - /* Chip defined clock source */ - kADC16_ClockSourceAsynchronousClock = kADC16_ClockSourceAlt3, /*!< Using internal asynchronous clock. */ -} adc16_clock_source_t; - -/*! - * @brief Long sample mode. - */ -typedef enum _adc16_long_sample_mode -{ - kADC16_LongSampleCycle24 = 0U, /*!< 20 extra ADCK cycles, 24 ADCK cycles total. */ - kADC16_LongSampleCycle16 = 1U, /*!< 12 extra ADCK cycles, 16 ADCK cycles total. */ - kADC16_LongSampleCycle10 = 2U, /*!< 6 extra ADCK cycles, 10 ADCK cycles total. */ - kADC16_LongSampleCycle6 = 3U, /*!< 2 extra ADCK cycles, 6 ADCK cycles total. */ - kADC16_LongSampleDisabled = 4U, /*!< Disable the long sample feature. */ -} adc16_long_sample_mode_t; - -/*! - * @brief Reference voltage source. - */ -typedef enum _adc16_reference_voltage_source -{ - kADC16_ReferenceVoltageSourceVref = 0U, /*!< For external pins pair of VrefH and VrefL. */ - kADC16_ReferenceVoltageSourceValt = 1U, /*!< For alternate reference pair of ValtH and ValtL. */ -} adc16_reference_voltage_source_t; - -#if defined(FSL_FEATURE_ADC16_HAS_HW_AVERAGE) && FSL_FEATURE_ADC16_HAS_HW_AVERAGE -/*! - * @brief Hardware average mode. - */ -typedef enum _adc16_hardware_average_mode -{ - kADC16_HardwareAverageCount4 = 0U, /*!< For hardware average with 4 samples. */ - kADC16_HardwareAverageCount8 = 1U, /*!< For hardware average with 8 samples. */ - kADC16_HardwareAverageCount16 = 2U, /*!< For hardware average with 16 samples. */ - kADC16_HardwareAverageCount32 = 3U, /*!< For hardware average with 32 samples. */ - kADC16_HardwareAverageDisabled = 4U, /*!< Disable the hardware average feature.*/ -} adc16_hardware_average_mode_t; -#endif /* FSL_FEATURE_ADC16_HAS_HW_AVERAGE */ - -/*! - * @brief Hardware compare mode. - */ -typedef enum _adc16_hardware_compare_mode -{ - kADC16_HardwareCompareMode0 = 0U, /*!< x < value1. */ - kADC16_HardwareCompareMode1 = 1U, /*!< x > value1. */ - kADC16_HardwareCompareMode2 = 2U, /*!< if value1 <= value2, then x < value1 || x > value2; - else, value1 > x > value2. */ - kADC16_HardwareCompareMode3 = 3U, /*!< if value1 <= value2, then value1 <= x <= value2; - else x >= value1 || x <= value2. */ -} adc16_hardware_compare_mode_t; - -#if defined(FSL_FEATURE_ADC16_HAS_PGA) && FSL_FEATURE_ADC16_HAS_PGA -/*! - * @brief PGA's Gain mode. - */ -typedef enum _adc16_pga_gain -{ - kADC16_PGAGainValueOf1 = 0U, /*!< For amplifier gain of 1. */ - kADC16_PGAGainValueOf2 = 1U, /*!< For amplifier gain of 2. */ - kADC16_PGAGainValueOf4 = 2U, /*!< For amplifier gain of 4. */ - kADC16_PGAGainValueOf8 = 3U, /*!< For amplifier gain of 8. */ - kADC16_PGAGainValueOf16 = 4U, /*!< For amplifier gain of 16. */ - kADC16_PGAGainValueOf32 = 5U, /*!< For amplifier gain of 32. */ - kADC16_PGAGainValueOf64 = 6U, /*!< For amplifier gain of 64. */ -} adc16_pga_gain_t; -#endif /* FSL_FEATURE_ADC16_HAS_PGA */ - -/*! - * @brief ADC16 converter configuration. - */ -typedef struct _adc16_config -{ - adc16_reference_voltage_source_t referenceVoltageSource; /*!< Select the reference voltage source. */ - adc16_clock_source_t clockSource; /*!< Select the input clock source to converter. */ - bool enableAsynchronousClock; /*!< Enable the asynchronous clock output. */ - adc16_clock_divider_t clockDivider; /*!< Select the divider of input clock source. */ - adc16_resolution_t resolution; /*!< Select the sample resolution mode. */ - adc16_long_sample_mode_t longSampleMode; /*!< Select the long sample mode. */ - bool enableHighSpeed; /*!< Enable the high-speed mode. */ - bool enableLowPower; /*!< Enable low power. */ - bool enableContinuousConversion; /*!< Enable continuous conversion mode. */ -} adc16_config_t; - -/*! - * @brief ADC16 Hardware comparison configuration. - */ -typedef struct _adc16_hardware_compare_config -{ - adc16_hardware_compare_mode_t hardwareCompareMode; /*!< Select the hardware compare mode. - See "adc16_hardware_compare_mode_t". */ - int16_t value1; /*!< Setting value1 for hardware compare mode. */ - int16_t value2; /*!< Setting value2 for hardware compare mode. */ -} adc16_hardware_compare_config_t; - -/*! - * @brief ADC16 channel conversion configuration. - */ -typedef struct _adc16_channel_config -{ - uint32_t channelNumber; /*!< Setting the conversion channel number. The available range is 0-31. - See channel connection information for each chip in Reference - Manual document. */ - bool enableInterruptOnConversionCompleted; /*!< Generate an interrupt request once the conversion is completed. */ -#if defined(FSL_FEATURE_ADC16_HAS_DIFF_MODE) && FSL_FEATURE_ADC16_HAS_DIFF_MODE - bool enableDifferentialConversion; /*!< Using Differential sample mode. */ -#endif /* FSL_FEATURE_ADC16_HAS_DIFF_MODE */ -} adc16_channel_config_t; - -#if defined(FSL_FEATURE_ADC16_HAS_PGA) && FSL_FEATURE_ADC16_HAS_PGA -/*! - * @brief ADC16 programmable gain amplifier configuration. - */ -typedef struct _adc16_pga_config -{ - adc16_pga_gain_t pgaGain; /*!< Setting PGA gain. */ - bool enableRunInNormalMode; /*!< Enable PGA working in normal mode, or low power mode by default. */ -#if defined(FSL_FEATURE_ADC16_HAS_PGA_CHOPPING) && FSL_FEATURE_ADC16_HAS_PGA_CHOPPING - bool disablePgaChopping; /*!< Disable the PGA chopping function. - The PGA employs chopping to remove/reduce offset and 1/f noise and offers - an offset measurement configuration that aids the offset calibration. */ -#endif /* FSL_FEATURE_ADC16_HAS_PGA_CHOPPING */ -#if defined(FSL_FEATURE_ADC16_HAS_PGA_OFFSET_MEASUREMENT) && FSL_FEATURE_ADC16_HAS_PGA_OFFSET_MEASUREMENT - bool enableRunInOffsetMeasurement; /*!< Enable the PGA working in offset measurement mode. - When this feature is enabled, the PGA disconnects itself from the external - inputs and auto-configures into offset measurement mode. With this field - set, run the ADC in the recommended settings and enable the maximum hardware - averaging to get the PGA offset number. The output is the - (PGA offset * (64+1)) for the given PGA setting. */ -#endif /* FSL_FEATURE_ADC16_HAS_PGA_OFFSET_MEASUREMENT */ -} adc16_pga_config_t; -#endif /* FSL_FEATURE_ADC16_HAS_PGA */ - -#if defined(__cplusplus) -extern "C" { -#endif - -/******************************************************************************* - * API - ******************************************************************************/ - -/*! - * @name Initialization - * @{ - */ - -/*! - * @brief Initializes the ADC16 module. - * - * @param base ADC16 peripheral base address. - * @param config Pointer to configuration structure. See "adc16_config_t". - */ -void ADC16_Init(ADC_Type *base, const adc16_config_t *config); - -/*! - * @brief De-initializes the ADC16 module. - * - * @param base ADC16 peripheral base address. - */ -void ADC16_Deinit(ADC_Type *base); - -/*! - * @brief Gets an available pre-defined settings for the converter's configuration. - * - * This function initializes the converter configuration structure with available settings. The default values are as follows. - * @code - * config->referenceVoltageSource = kADC16_ReferenceVoltageSourceVref; - * config->clockSource = kADC16_ClockSourceAsynchronousClock; - * config->enableAsynchronousClock = true; - * config->clockDivider = kADC16_ClockDivider8; - * config->resolution = kADC16_ResolutionSE12Bit; - * config->longSampleMode = kADC16_LongSampleDisabled; - * config->enableHighSpeed = false; - * config->enableLowPower = false; - * config->enableContinuousConversion = false; - * @endcode - * @param config Pointer to the configuration structure. - */ -void ADC16_GetDefaultConfig(adc16_config_t *config); - -#if defined(FSL_FEATURE_ADC16_HAS_CALIBRATION) && FSL_FEATURE_ADC16_HAS_CALIBRATION -/*! - * @brief Automates the hardware calibration. - * - * This auto calibration helps to adjust the plus/minus side gain automatically. - * Execute the calibration before using the converter. Note that the hardware trigger should be used - * during the calibration. - * - * @param base ADC16 peripheral base address. - * - * @return Execution status. - * @retval kStatus_Success Calibration is done successfully. - * @retval kStatus_Fail Calibration has failed. - */ -status_t ADC16_DoAutoCalibration(ADC_Type *base); -#endif /* FSL_FEATURE_ADC16_HAS_CALIBRATION */ - -#if defined(FSL_FEATURE_ADC16_HAS_OFFSET_CORRECTION) && FSL_FEATURE_ADC16_HAS_OFFSET_CORRECTION -/*! - * @brief Sets the offset value for the conversion result. - * - * This offset value takes effect on the conversion result. If the offset value is not zero, the reading result - * is subtracted by it. Note, the hardware calibration fills the offset value automatically. - * - * @param base ADC16 peripheral base address. - * @param value Setting offset value. - */ -static inline void ADC16_SetOffsetValue(ADC_Type *base, int16_t value) -{ - base->OFS = (uint32_t)(value); -} -#endif /* FSL_FEATURE_ADC16_HAS_OFFSET_CORRECTION */ - -/* @} */ - -/*! - * @name Advanced Features - * @{ - */ - -#if defined(FSL_FEATURE_ADC16_HAS_DMA) && FSL_FEATURE_ADC16_HAS_DMA -/*! - * @brief Enables generating the DMA trigger when the conversion is complete. - * - * @param base ADC16 peripheral base address. - * @param enable Switcher of the DMA feature. "true" means enabled, "false" means not enabled. - */ -static inline void ADC16_EnableDMA(ADC_Type *base, bool enable) -{ - if (enable) - { - base->SC2 |= ADC_SC2_DMAEN_MASK; - } - else - { - base->SC2 &= ~ADC_SC2_DMAEN_MASK; - } -} -#endif /* FSL_FEATURE_ADC16_HAS_DMA */ - -/*! - * @brief Enables the hardware trigger mode. - * - * @param base ADC16 peripheral base address. - * @param enable Switcher of the hardware trigger feature. "true" means enabled, "false" means not enabled. - */ -static inline void ADC16_EnableHardwareTrigger(ADC_Type *base, bool enable) -{ - if (enable) - { - base->SC2 |= ADC_SC2_ADTRG_MASK; - } - else - { - base->SC2 &= ~ADC_SC2_ADTRG_MASK; - } -} - -#if defined(FSL_FEATURE_ADC16_HAS_MUX_SELECT) && FSL_FEATURE_ADC16_HAS_MUX_SELECT -/*! - * @brief Sets the channel mux mode. - * - * Some sample pins share the same channel index. The channel mux mode decides which pin is used for an - * indicated channel. - * - * @param base ADC16 peripheral base address. - * @param mode Setting channel mux mode. See "adc16_channel_mux_mode_t". - */ -void ADC16_SetChannelMuxMode(ADC_Type *base, adc16_channel_mux_mode_t mode); -#endif /* FSL_FEATURE_ADC16_HAS_MUX_SELECT */ - -/*! - * @brief Configures the hardware compare mode. - * - * The hardware compare mode provides a way to process the conversion result automatically by using hardware. Only the result - * in the compare range is available. To compare the range, see "adc16_hardware_compare_mode_t" or the appopriate reference - * manual for more information. - * - * @param base ADC16 peripheral base address. - * @param config Pointer to the "adc16_hardware_compare_config_t" structure. Passing "NULL" disables the feature. - */ -void ADC16_SetHardwareCompareConfig(ADC_Type *base, const adc16_hardware_compare_config_t *config); - -#if defined(FSL_FEATURE_ADC16_HAS_HW_AVERAGE) && FSL_FEATURE_ADC16_HAS_HW_AVERAGE -/*! - * @brief Sets the hardware average mode. - * - * The hardware average mode provides a way to process the conversion result automatically by using hardware. The multiple - * conversion results are accumulated and averaged internally making them easier to read. - * - * @param base ADC16 peripheral base address. - * @param mode Setting the hardware average mode. See "adc16_hardware_average_mode_t". - */ -void ADC16_SetHardwareAverage(ADC_Type *base, adc16_hardware_average_mode_t mode); -#endif /* FSL_FEATURE_ADC16_HAS_HW_AVERAGE */ - -#if defined(FSL_FEATURE_ADC16_HAS_PGA) && FSL_FEATURE_ADC16_HAS_PGA -/*! - * @brief Configures the PGA for the converter's front end. - * - * @param base ADC16 peripheral base address. - * @param config Pointer to the "adc16_pga_config_t" structure. Passing "NULL" disables the feature. - */ -void ADC16_SetPGAConfig(ADC_Type *base, const adc16_pga_config_t *config); -#endif /* FSL_FEATURE_ADC16_HAS_PGA */ - -/*! - * @brief Gets the status flags of the converter. - * - * @param base ADC16 peripheral base address. - * - * @return Flags' mask if indicated flags are asserted. See "_adc16_status_flags". - */ -uint32_t ADC16_GetStatusFlags(ADC_Type *base); - -/*! - * @brief Clears the status flags of the converter. - * - * @param base ADC16 peripheral base address. - * @param mask Mask value for the cleared flags. See "_adc16_status_flags". - */ -void ADC16_ClearStatusFlags(ADC_Type *base, uint32_t mask); - -/* @} */ - -/*! - * @name Conversion Channel - * @{ - */ - -/*! - * @brief Configures the conversion channel. - * - * This operation triggers the conversion when in software trigger mode. When in hardware trigger mode, this API - * configures the channel while the external trigger source helps to trigger the conversion. - * - * Note that the "Channel Group" has a detailed description. - * To allow sequential conversions of the ADC to be triggered by internal peripherals, the ADC has more than one - * group of status and control registers, one for each conversion. The channel group parameter indicates which group of - * registers are used, for example, channel group 0 is for Group A registers and channel group 1 is for Group B registers. The - * channel groups are used in a "ping-pong" approach to control the ADC operation. At any point, only one of - * the channel groups is actively controlling ADC conversions. The channel group 0 is used for both software and hardware - * trigger modes. Channel group 1 and greater indicates multiple channel group registers for - * use only in hardware trigger mode. See the chip configuration information in the appropriate MCU reference manual for the - * number of SC1n registers (channel groups) specific to this device. Channel group 1 or greater are not used - * for software trigger operation. Therefore, writing to these channel groups does not initiate a new conversion. - * Updating the channel group 0 while a different channel group is actively controlling a conversion is allowed and - * vice versa. Writing any of the channel group registers while that specific channel group is actively controlling a - * conversion aborts the current conversion. - * - * @param base ADC16 peripheral base address. - * @param channelGroup Channel group index. - * @param config Pointer to the "adc16_channel_config_t" structure for the conversion channel. - */ -void ADC16_SetChannelConfig(ADC_Type *base, uint32_t channelGroup, const adc16_channel_config_t *config); - -/*! - * @brief Gets the conversion value. - * - * @param base ADC16 peripheral base address. - * @param channelGroup Channel group index. - * - * @return Conversion value. - */ -static inline uint32_t ADC16_GetChannelConversionValue(ADC_Type *base, uint32_t channelGroup) -{ - assert(channelGroup < ADC_R_COUNT); - - return base->R[channelGroup]; -} - -/*! - * @brief Gets the status flags of channel. - * - * @param base ADC16 peripheral base address. - * @param channelGroup Channel group index. - * - * @return Flags' mask if indicated flags are asserted. See "_adc16_channel_status_flags". - */ -uint32_t ADC16_GetChannelStatusFlags(ADC_Type *base, uint32_t channelGroup); - -/* @} */ - -#if defined(__cplusplus) -} -#endif -/*! - * @} - */ -#endif /* _FSL_ADC16_H_ */ diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_clock.c b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_clock.c deleted file mode 100644 index 12048524dd9..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_clock.c +++ /dev/null @@ -1,1793 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright (c) 2016 - 2017 , NXP - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "fsl_clock.h" - -/******************************************************************************* - * Definitions - ******************************************************************************/ - -/* Macro definition remap workaround. */ -#if (defined(MCG_C2_EREFS_MASK) && !(defined(MCG_C2_EREFS0_MASK))) -#define MCG_C2_EREFS0_MASK MCG_C2_EREFS_MASK -#endif -#if (defined(MCG_C2_HGO_MASK) && !(defined(MCG_C2_HGO0_MASK))) -#define MCG_C2_HGO0_MASK MCG_C2_HGO_MASK -#endif -#if (defined(MCG_C2_RANGE_MASK) && !(defined(MCG_C2_RANGE0_MASK))) -#define MCG_C2_RANGE0_MASK MCG_C2_RANGE_MASK -#endif -#if (defined(MCG_C6_CME_MASK) && !(defined(MCG_C6_CME0_MASK))) -#define MCG_C6_CME0_MASK MCG_C6_CME_MASK -#endif - -/* PLL fixed multiplier when there is not PRDIV and VDIV. */ -#define PLL_FIXED_MULT (375U) -/* Max frequency of the reference clock used for internal clock trim. */ -#define TRIM_REF_CLK_MIN (8000000U) -/* Min frequency of the reference clock used for internal clock trim. */ -#define TRIM_REF_CLK_MAX (16000000U) -/* Max trim value of fast internal reference clock. */ -#define TRIM_FIRC_MAX (5000000U) -/* Min trim value of fast internal reference clock. */ -#define TRIM_FIRC_MIN (3000000U) -/* Max trim value of fast internal reference clock. */ -#define TRIM_SIRC_MAX (39063U) -/* Min trim value of fast internal reference clock. */ -#define TRIM_SIRC_MIN (31250U) - -#define MCG_S_IRCST_VAL ((MCG->S & MCG_S_IRCST_MASK) >> MCG_S_IRCST_SHIFT) -#define MCG_S_CLKST_VAL ((MCG->S & MCG_S_CLKST_MASK) >> MCG_S_CLKST_SHIFT) -#define MCG_S_IREFST_VAL ((MCG->S & MCG_S_IREFST_MASK) >> MCG_S_IREFST_SHIFT) -#define MCG_S_PLLST_VAL ((MCG->S & MCG_S_PLLST_MASK) >> MCG_S_PLLST_SHIFT) -#define MCG_C1_FRDIV_VAL ((MCG->C1 & MCG_C1_FRDIV_MASK) >> MCG_C1_FRDIV_SHIFT) -#define MCG_C2_LP_VAL ((MCG->C2 & MCG_C2_LP_MASK) >> MCG_C2_LP_SHIFT) -#define MCG_C2_RANGE_VAL ((MCG->C2 & MCG_C2_RANGE_MASK) >> MCG_C2_RANGE_SHIFT) -#define MCG_SC_FCRDIV_VAL ((MCG->SC & MCG_SC_FCRDIV_MASK) >> MCG_SC_FCRDIV_SHIFT) -#define MCG_S2_PLLCST_VAL ((MCG->S2 & MCG_S2_PLLCST_MASK) >> MCG_S2_PLLCST_SHIFT) -#define MCG_C7_OSCSEL_VAL ((MCG->C7 & MCG_C7_OSCSEL_MASK) >> MCG_C7_OSCSEL_SHIFT) -#define MCG_C4_DMX32_VAL ((MCG->C4 & MCG_C4_DMX32_MASK) >> MCG_C4_DMX32_SHIFT) -#define MCG_C4_DRST_DRS_VAL ((MCG->C4 & MCG_C4_DRST_DRS_MASK) >> MCG_C4_DRST_DRS_SHIFT) -#define MCG_C7_PLL32KREFSEL_VAL ((MCG->C7 & MCG_C7_PLL32KREFSEL_MASK) >> MCG_C7_PLL32KREFSEL_SHIFT) -#define MCG_C5_PLLREFSEL0_VAL ((MCG->C5 & MCG_C5_PLLREFSEL0_MASK) >> MCG_C5_PLLREFSEL0_SHIFT) -#define MCG_C11_PLLREFSEL1_VAL ((MCG->C11 & MCG_C11_PLLREFSEL1_MASK) >> MCG_C11_PLLREFSEL1_SHIFT) -#define MCG_C11_PRDIV1_VAL ((MCG->C11 & MCG_C11_PRDIV1_MASK) >> MCG_C11_PRDIV1_SHIFT) -#define MCG_C12_VDIV1_VAL ((MCG->C12 & MCG_C12_VDIV1_MASK) >> MCG_C12_VDIV1_SHIFT) -#define MCG_C5_PRDIV0_VAL ((MCG->C5 & MCG_C5_PRDIV0_MASK) >> MCG_C5_PRDIV0_SHIFT) -#define MCG_C6_VDIV0_VAL ((MCG->C6 & MCG_C6_VDIV0_MASK) >> MCG_C6_VDIV0_SHIFT) - -#define OSC_MODE_MASK (MCG_C2_EREFS0_MASK | MCG_C2_HGO0_MASK | MCG_C2_RANGE0_MASK) - -#define SIM_CLKDIV1_OUTDIV1_VAL ((SIM->CLKDIV1 & SIM_CLKDIV1_OUTDIV1_MASK) >> SIM_CLKDIV1_OUTDIV1_SHIFT) -#define SIM_CLKDIV1_OUTDIV2_VAL ((SIM->CLKDIV1 & SIM_CLKDIV1_OUTDIV2_MASK) >> SIM_CLKDIV1_OUTDIV2_SHIFT) -#define SIM_CLKDIV1_OUTDIV3_VAL ((SIM->CLKDIV1 & SIM_CLKDIV1_OUTDIV3_MASK) >> SIM_CLKDIV1_OUTDIV3_SHIFT) -#define SIM_CLKDIV1_OUTDIV4_VAL ((SIM->CLKDIV1 & SIM_CLKDIV1_OUTDIV4_MASK) >> SIM_CLKDIV1_OUTDIV4_SHIFT) -#define SIM_SOPT1_OSC32KSEL_VAL ((SIM->SOPT1 & SIM_SOPT1_OSC32KSEL_MASK) >> SIM_SOPT1_OSC32KSEL_SHIFT) -#define SIM_SOPT2_PLLFLLSEL_VAL ((SIM->SOPT2 & SIM_SOPT2_PLLFLLSEL_MASK) >> SIM_SOPT2_PLLFLLSEL_SHIFT) - -/* MCG_S_CLKST definition. */ -enum _mcg_clkout_stat -{ - kMCG_ClkOutStatFll, /* FLL. */ - kMCG_ClkOutStatInt, /* Internal clock. */ - kMCG_ClkOutStatExt, /* External clock. */ - kMCG_ClkOutStatPll /* PLL. */ -}; - -/* MCG_S_PLLST definition. */ -enum _mcg_pllst -{ - kMCG_PllstFll, /* FLL is used. */ - kMCG_PllstPll /* PLL is used. */ -}; - -/******************************************************************************* - * Variables - ******************************************************************************/ - -/* Slow internal reference clock frequency. */ -static uint32_t s_slowIrcFreq = 32768U; -/* Fast internal reference clock frequency. */ -static uint32_t s_fastIrcFreq = 4000000U; - -/* External XTAL0 (OSC0) clock frequency. */ -uint32_t g_xtal0Freq; -/* External XTAL32K clock frequency. */ -uint32_t g_xtal32Freq; - -/******************************************************************************* - * Prototypes - ******************************************************************************/ - -/*! - * @brief Get the MCG external reference clock frequency. - * - * Get the current MCG external reference clock frequency in Hz. It is - * the frequency select by MCG_C7[OSCSEL]. This is an internal function. - * - * @return MCG external reference clock frequency in Hz. - */ -static uint32_t CLOCK_GetMcgExtClkFreq(void); - -/*! - * @brief Get the MCG FLL external reference clock frequency. - * - * Get the current MCG FLL external reference clock frequency in Hz. It is - * the frequency after by MCG_C1[FRDIV]. This is an internal function. - * - * @return MCG FLL external reference clock frequency in Hz. - */ -static uint32_t CLOCK_GetFllExtRefClkFreq(void); - -/*! - * @brief Get the MCG FLL reference clock frequency. - * - * Get the current MCG FLL reference clock frequency in Hz. It is - * the frequency select by MCG_C1[IREFS]. This is an internal function. - * - * @return MCG FLL reference clock frequency in Hz. - */ -static uint32_t CLOCK_GetFllRefClkFreq(void); - -/*! - * @brief Get the frequency of clock selected by MCG_C2[IRCS]. - * - * This clock's two output: - * 1. MCGOUTCLK when MCG_S[CLKST]=0. - * 2. MCGIRCLK when MCG_C1[IRCLKEN]=1. - * - * @return The frequency in Hz. - */ -static uint32_t CLOCK_GetInternalRefClkSelectFreq(void); - -/*! - * @brief Get the MCG PLL/PLL0 reference clock frequency. - * - * Get the current MCG PLL/PLL0 reference clock frequency in Hz. - * This is an internal function. - * - * @return MCG PLL/PLL0 reference clock frequency in Hz. - */ -static uint32_t CLOCK_GetPll0RefFreq(void); - -/*! - * @brief Calculate the RANGE value base on crystal frequency. - * - * To setup external crystal oscillator, must set the register bits RANGE - * base on the crystal frequency. This function returns the RANGE base on the - * input frequency. This is an internal function. - * - * @param freq Crystal frequency in Hz. - * @return The RANGE value. - */ -static uint8_t CLOCK_GetOscRangeFromFreq(uint32_t freq); - -/******************************************************************************* - * Code - ******************************************************************************/ - -#ifndef MCG_USER_CONFIG_FLL_STABLE_DELAY_EN -/*! - * @brief Delay function to wait FLL stable. - * - * Delay function to wait FLL stable in FEI mode or FEE mode, should wait at least - * 1ms. Every time changes FLL setting, should wait this time for FLL stable. - */ -void CLOCK_FllStableDelay(void) -{ - /* - Should wait at least 1ms. Because in these modes, the core clock is 100MHz - at most, so this function could obtain the 1ms delay. - */ - volatile uint32_t i = 30000U; - while (i--) - { - __NOP(); - } -} -#else /* With MCG_USER_CONFIG_FLL_STABLE_DELAY_EN defined. */ -/* Once user defines the MCG_USER_CONFIG_FLL_STABLE_DELAY_EN to use their own delay function, he has to - * create his own CLOCK_FllStableDelay() function in application code. Since the clock functions in this - * file would call the CLOCK_FllStableDelay() regardness how it is defined. - */ -extern void CLOCK_FllStableDelay(void); -#endif /* MCG_USER_CONFIG_FLL_STABLE_DELAY_EN */ - -static uint32_t CLOCK_GetMcgExtClkFreq(void) -{ - uint32_t freq; - - switch (MCG_C7_OSCSEL_VAL) - { - case 0U: - /* Please call CLOCK_SetXtal0Freq base on board setting before using OSC0 clock. */ - assert(g_xtal0Freq); - freq = g_xtal0Freq; - break; - case 1U: - /* Please call CLOCK_SetXtal32Freq base on board setting before using XTAL32K/RTC_CLKIN clock. */ - assert(g_xtal32Freq); - freq = g_xtal32Freq; - break; - case 2U: - freq = MCG_INTERNAL_IRC_48M; - break; - default: - freq = 0U; - break; - } - - return freq; -} - -static uint32_t CLOCK_GetFllExtRefClkFreq(void) -{ - /* FllExtRef = McgExtRef / FllExtRefDiv */ - uint8_t frdiv; - uint8_t range; - uint8_t oscsel; - - uint32_t freq = CLOCK_GetMcgExtClkFreq(); - - if (!freq) - { - return freq; - } - - frdiv = MCG_C1_FRDIV_VAL; - freq >>= frdiv; - - range = MCG_C2_RANGE_VAL; - oscsel = MCG_C7_OSCSEL_VAL; - - /* - When should use divider 32, 64, 128, 256, 512, 1024, 1280, 1536. - 1. MCG_C7[OSCSEL] selects IRC48M. - 2. MCG_C7[OSCSEL] selects OSC0 and MCG_C2[RANGE] is not 0. - */ - if (((0U != range) && (kMCG_OscselOsc == oscsel)) || (kMCG_OscselIrc == oscsel)) - { - switch (frdiv) - { - case 0: - case 1: - case 2: - case 3: - case 4: - case 5: - freq >>= 5u; - break; - case 6: - /* 64*20=1280 */ - freq /= 20u; - break; - case 7: - /* 128*12=1536 */ - freq /= 12u; - break; - default: - freq = 0u; - break; - } - } - - return freq; -} - -static uint32_t CLOCK_GetInternalRefClkSelectFreq(void) -{ - if (kMCG_IrcSlow == MCG_S_IRCST_VAL) - { - /* Slow internal reference clock selected*/ - return s_slowIrcFreq; - } - else - { - /* Fast internal reference clock selected*/ - return s_fastIrcFreq >> MCG_SC_FCRDIV_VAL; - } -} - -static uint32_t CLOCK_GetFllRefClkFreq(void) -{ - /* If use external reference clock. */ - if (kMCG_FllSrcExternal == MCG_S_IREFST_VAL) - { - return CLOCK_GetFllExtRefClkFreq(); - } - /* If use internal reference clock. */ - else - { - return s_slowIrcFreq; - } -} - -static uint32_t CLOCK_GetPll0RefFreq(void) -{ - /* MCG external reference clock. */ - return CLOCK_GetMcgExtClkFreq(); -} - -static uint8_t CLOCK_GetOscRangeFromFreq(uint32_t freq) -{ - uint8_t range; - - if (freq <= 39063U) - { - range = 0U; - } - else if (freq <= 8000000U) - { - range = 1U; - } - else - { - range = 2U; - } - - return range; -} - -uint32_t CLOCK_GetOsc0ErClkFreq(void) -{ - if (OSC0->CR & OSC_CR_ERCLKEN_MASK) - { - /* Please call CLOCK_SetXtal0Freq base on board setting before using OSC0 clock. */ - assert(g_xtal0Freq); - return g_xtal0Freq; - } - else - { - return 0U; - } -} - -/* Function Name : CLOCK_GetEr32kClkFreq */ -uint32_t CLOCK_GetEr32kClkFreq(void) -{ - uint32_t freq; - - switch (SIM_SOPT1_OSC32KSEL_VAL) - { - case 0U: /* OSC 32k clock */ - freq = (CLOCK_GetOsc0ErClkFreq() == 32768U) ? 32768U : 0U; - break; - case 2U: /* RTC 32k clock */ - /* Please call CLOCK_SetXtal32Freq base on board setting before using XTAL32K/RTC_CLKIN clock. */ - assert(g_xtal32Freq); - freq = g_xtal32Freq; - break; - case 3U: /* LPO clock */ - freq = LPO_CLK_FREQ; - break; - default: - freq = 0U; - break; - } - return freq; -} - -uint32_t CLOCK_GetPllFllSelClkFreq(void) -{ - uint32_t freq; - - switch (SIM_SOPT2_PLLFLLSEL_VAL) - { - case 0U: /* FLL. */ - freq = CLOCK_GetFllFreq(); - break; - case 1U: /* PLL. */ - freq = CLOCK_GetPll0Freq(); - break; - case 3U: /* MCG IRC48M. */ - freq = MCG_INTERNAL_IRC_48M; - break; - default: - freq = 0U; - break; - } - - return freq; -} - -uint32_t CLOCK_GetFlashClkFreq(void) -{ - return CLOCK_GetOutClkFreq() / (SIM_CLKDIV1_OUTDIV4_VAL + 1); -} - -uint32_t CLOCK_GetFlexBusClkFreq(void) -{ - return CLOCK_GetOutClkFreq() / (SIM_CLKDIV1_OUTDIV3_VAL + 1); -} - -uint32_t CLOCK_GetBusClkFreq(void) -{ - return CLOCK_GetOutClkFreq() / (SIM_CLKDIV1_OUTDIV2_VAL + 1); -} - -uint32_t CLOCK_GetCoreSysClkFreq(void) -{ - return CLOCK_GetOutClkFreq() / (SIM_CLKDIV1_OUTDIV1_VAL + 1); -} - -uint32_t CLOCK_GetFreq(clock_name_t clockName) -{ - uint32_t freq; - - switch (clockName) - { - case kCLOCK_CoreSysClk: - freq = CLOCK_GetOutClkFreq() / (SIM_CLKDIV1_OUTDIV1_VAL + 1); - break; - case kCLOCK_BusClk: - freq = CLOCK_GetOutClkFreq() / (SIM_CLKDIV1_OUTDIV2_VAL + 1); - break; - case kCLOCK_FlexBusClk: - freq = CLOCK_GetOutClkFreq() / (SIM_CLKDIV1_OUTDIV3_VAL + 1); - break; - case kCLOCK_FlashClk: - freq = CLOCK_GetOutClkFreq() / (SIM_CLKDIV1_OUTDIV4_VAL + 1); - break; - case kCLOCK_PllFllSelClk: - freq = CLOCK_GetPllFllSelClkFreq(); - break; - case kCLOCK_Er32kClk: - freq = CLOCK_GetEr32kClkFreq(); - break; - case kCLOCK_McgFixedFreqClk: - freq = CLOCK_GetFixedFreqClkFreq(); - break; - case kCLOCK_McgInternalRefClk: - freq = CLOCK_GetInternalRefClkFreq(); - break; - case kCLOCK_McgFllClk: - freq = CLOCK_GetFllFreq(); - break; - case kCLOCK_McgPll0Clk: - freq = CLOCK_GetPll0Freq(); - break; - case kCLOCK_McgIrc48MClk: - freq = MCG_INTERNAL_IRC_48M; - break; - case kCLOCK_LpoClk: - freq = LPO_CLK_FREQ; - break; - case kCLOCK_Osc0ErClk: - freq = CLOCK_GetOsc0ErClkFreq(); - break; - default: - freq = 0U; - break; - } - - return freq; -} - -void CLOCK_SetSimConfig(sim_clock_config_t const *config) -{ - SIM->CLKDIV1 = config->clkdiv1; - CLOCK_SetPllFllSelClock(config->pllFllSel); - CLOCK_SetEr32kClock(config->er32kSrc); -} - -bool CLOCK_EnableUsbfs0Clock(clock_usb_src_t src, uint32_t freq) -{ - bool ret = true; - - CLOCK_DisableClock(kCLOCK_Usbfs0); - - if (kCLOCK_UsbSrcExt == src) - { - SIM->SOPT2 &= ~SIM_SOPT2_USBSRC_MASK; - } - else - { - switch (freq) - { - case 120000000U: - SIM->CLKDIV2 = SIM_CLKDIV2_USBDIV(4) | SIM_CLKDIV2_USBFRAC(1); - break; - case 96000000U: - SIM->CLKDIV2 = SIM_CLKDIV2_USBDIV(1) | SIM_CLKDIV2_USBFRAC(0); - break; - case 72000000U: - SIM->CLKDIV2 = SIM_CLKDIV2_USBDIV(2) | SIM_CLKDIV2_USBFRAC(1); - break; - case 48000000U: - SIM->CLKDIV2 = SIM_CLKDIV2_USBDIV(0) | SIM_CLKDIV2_USBFRAC(0); - break; - default: - ret = false; - break; - } - - SIM->SOPT2 = ((SIM->SOPT2 & ~(SIM_SOPT2_PLLFLLSEL_MASK | SIM_SOPT2_USBSRC_MASK)) | (uint32_t)src); - } - - CLOCK_EnableClock(kCLOCK_Usbfs0); - - if (kCLOCK_UsbSrcIrc48M == src) - { - USB0->CLK_RECOVER_IRC_EN = 0x03U; - USB0->CLK_RECOVER_CTRL |= USB_CLK_RECOVER_CTRL_CLOCK_RECOVER_EN_MASK; - } - return ret; -} - -uint32_t CLOCK_GetOutClkFreq(void) -{ - uint32_t mcgoutclk; - uint32_t clkst = MCG_S_CLKST_VAL; - - switch (clkst) - { - case kMCG_ClkOutStatPll: - mcgoutclk = CLOCK_GetPll0Freq(); - break; - case kMCG_ClkOutStatFll: - mcgoutclk = CLOCK_GetFllFreq(); - break; - case kMCG_ClkOutStatInt: - mcgoutclk = CLOCK_GetInternalRefClkSelectFreq(); - break; - case kMCG_ClkOutStatExt: - mcgoutclk = CLOCK_GetMcgExtClkFreq(); - break; - default: - mcgoutclk = 0U; - break; - } - return mcgoutclk; -} - -uint32_t CLOCK_GetFllFreq(void) -{ - static const uint16_t fllFactorTable[4][2] = {{640, 732}, {1280, 1464}, {1920, 2197}, {2560, 2929}}; - - uint8_t drs, dmx32; - uint32_t freq; - - /* If FLL is not enabled currently, then return 0U. */ - if ((MCG->C2 & MCG_C2_LP_MASK) || (MCG->S & MCG_S_PLLST_MASK)) - { - return 0U; - } - - /* Get FLL reference clock frequency. */ - freq = CLOCK_GetFllRefClkFreq(); - if (!freq) - { - return freq; - } - - drs = MCG_C4_DRST_DRS_VAL; - dmx32 = MCG_C4_DMX32_VAL; - - return freq * fllFactorTable[drs][dmx32]; -} - -uint32_t CLOCK_GetInternalRefClkFreq(void) -{ - /* If MCGIRCLK is gated. */ - if (!(MCG->C1 & MCG_C1_IRCLKEN_MASK)) - { - return 0U; - } - - return CLOCK_GetInternalRefClkSelectFreq(); -} - -uint32_t CLOCK_GetFixedFreqClkFreq(void) -{ - uint32_t freq = CLOCK_GetFllRefClkFreq(); - - /* MCGFFCLK must be no more than MCGOUTCLK/8. */ - if ((freq) && (freq <= (CLOCK_GetOutClkFreq() / 8U))) - { - return freq; - } - else - { - return 0U; - } -} - -uint32_t CLOCK_GetPll0Freq(void) -{ - uint32_t mcgpll0clk; - - /* If PLL0 is not enabled, return 0. */ - if (!(MCG->S & MCG_S_LOCK0_MASK)) - { - return 0U; - } - - mcgpll0clk = CLOCK_GetPll0RefFreq(); - - /* - * Please call CLOCK_SetXtal0Freq base on board setting before using OSC0 clock. - * Please call CLOCK_SetXtal1Freq base on board setting before using OSC1 clock. - */ - assert(mcgpll0clk); - - mcgpll0clk /= (FSL_FEATURE_MCG_PLL_PRDIV_BASE + MCG_C5_PRDIV0_VAL); - mcgpll0clk *= (FSL_FEATURE_MCG_PLL_VDIV_BASE + MCG_C6_VDIV0_VAL); - - return mcgpll0clk; -} - -status_t CLOCK_SetExternalRefClkConfig(mcg_oscsel_t oscsel) -{ - bool needDelay; - uint32_t i; - -#if (defined(MCG_CONFIG_CHECK_PARAM) && MCG_CONFIG_CHECK_PARAM) - /* If change MCG_C7[OSCSEL] and external reference clock is system clock source, return error. */ - if ((MCG_C7_OSCSEL_VAL != oscsel) && (!(MCG->S & MCG_S_IREFST_MASK))) - { - return kStatus_MCG_SourceUsed; - } -#endif /* MCG_CONFIG_CHECK_PARAM */ - - if (MCG_C7_OSCSEL_VAL != oscsel) - { - /* If change OSCSEL, need to delay, ERR009878. */ - needDelay = true; - } - else - { - needDelay = false; - } - - MCG->C7 = (MCG->C7 & ~MCG_C7_OSCSEL_MASK) | MCG_C7_OSCSEL(oscsel); - if (needDelay) - { - /* ERR009878 Delay at least 50 micro-seconds for external clock change valid. */ - i = 1500U; - while (i--) - { - __NOP(); - } - } - - return kStatus_Success; -} - -status_t CLOCK_SetInternalRefClkConfig(uint8_t enableMode, mcg_irc_mode_t ircs, uint8_t fcrdiv) -{ - uint32_t mcgOutClkState = MCG_S_CLKST_VAL; - mcg_irc_mode_t curIrcs = (mcg_irc_mode_t)MCG_S_IRCST_VAL; - uint8_t curFcrdiv = MCG_SC_FCRDIV_VAL; - -#if (defined(MCG_CONFIG_CHECK_PARAM) && MCG_CONFIG_CHECK_PARAM) - /* If MCGIRCLK is used as system clock source. */ - if (kMCG_ClkOutStatInt == mcgOutClkState) - { - /* If need to change MCGIRCLK source or driver, return error. */ - if (((kMCG_IrcFast == curIrcs) && (fcrdiv != curFcrdiv)) || (ircs != curIrcs)) - { - return kStatus_MCG_SourceUsed; - } - } -#endif - - /* If need to update the FCRDIV. */ - if (fcrdiv != curFcrdiv) - { - /* If fast IRC is in use currently, change to slow IRC. */ - if ((kMCG_IrcFast == curIrcs) && ((mcgOutClkState == kMCG_ClkOutStatInt) || (MCG->C1 & MCG_C1_IRCLKEN_MASK))) - { - MCG->C2 = ((MCG->C2 & ~MCG_C2_IRCS_MASK) | (MCG_C2_IRCS(kMCG_IrcSlow))); - while (MCG_S_IRCST_VAL != kMCG_IrcSlow) - { - } - } - /* Update FCRDIV. */ - MCG->SC = (MCG->SC & ~(MCG_SC_FCRDIV_MASK | MCG_SC_ATMF_MASK | MCG_SC_LOCS0_MASK)) | MCG_SC_FCRDIV(fcrdiv); - } - - /* Set internal reference clock selection. */ - MCG->C2 = (MCG->C2 & ~MCG_C2_IRCS_MASK) | (MCG_C2_IRCS(ircs)); - MCG->C1 = (MCG->C1 & ~(MCG_C1_IRCLKEN_MASK | MCG_C1_IREFSTEN_MASK)) | (uint8_t)enableMode; - - /* If MCGIRCLK is used, need to wait for MCG_S_IRCST. */ - if ((mcgOutClkState == kMCG_ClkOutStatInt) || (enableMode & kMCG_IrclkEnable)) - { - while (MCG_S_IRCST_VAL != ircs) - { - } - } - - return kStatus_Success; -} - -uint32_t CLOCK_CalcPllDiv(uint32_t refFreq, uint32_t desireFreq, uint8_t *prdiv, uint8_t *vdiv) -{ - uint8_t ret_prdiv; /* PRDIV to return. */ - uint8_t ret_vdiv; /* VDIV to return. */ - uint8_t prdiv_min; /* Min PRDIV value to make reference clock in allowed range. */ - uint8_t prdiv_max; /* Max PRDIV value to make reference clock in allowed range. */ - uint8_t prdiv_cur; /* PRDIV value for iteration. */ - uint8_t vdiv_cur; /* VDIV value for iteration. */ - uint32_t ret_freq = 0U; /* PLL output fequency to return. */ - uint32_t diff = 0xFFFFFFFFU; /* Difference between desireFreq and return frequency. */ - uint32_t ref_div; /* Reference frequency after PRDIV. */ - - /* - Steps: - 1. Get allowed prdiv with such rules: - 1). refFreq / prdiv >= FSL_FEATURE_MCG_PLL_REF_MIN. - 2). refFreq / prdiv <= FSL_FEATURE_MCG_PLL_REF_MAX. - 2. For each allowed prdiv, there are two candidate vdiv values: - 1). (desireFreq / (refFreq / prdiv)). - 2). (desireFreq / (refFreq / prdiv)) + 1. - If could get the precise desired frequency, return current prdiv and - vdiv directly. Otherwise choose the one which is closer to desired - frequency. - */ - - /* Reference frequency is out of range. */ - if ((refFreq < FSL_FEATURE_MCG_PLL_REF_MIN) || - (refFreq > (FSL_FEATURE_MCG_PLL_REF_MAX * (FSL_FEATURE_MCG_PLL_PRDIV_MAX + FSL_FEATURE_MCG_PLL_PRDIV_BASE)))) - { - return 0U; - } - - /* refFreq/PRDIV must in a range. First get the allowed PRDIV range. */ - prdiv_max = refFreq / FSL_FEATURE_MCG_PLL_REF_MIN; - prdiv_min = (refFreq + FSL_FEATURE_MCG_PLL_REF_MAX - 1U) / FSL_FEATURE_MCG_PLL_REF_MAX; - - /* PRDIV traversal. */ - for (prdiv_cur = prdiv_max; prdiv_cur >= prdiv_min; prdiv_cur--) - { - /* Reference frequency after PRDIV. */ - ref_div = refFreq / prdiv_cur; - - vdiv_cur = desireFreq / ref_div; - - if ((vdiv_cur < FSL_FEATURE_MCG_PLL_VDIV_BASE - 1U) || (vdiv_cur > FSL_FEATURE_MCG_PLL_VDIV_BASE + 31U)) - { - /* No VDIV is available with this PRDIV. */ - continue; - } - - ret_freq = vdiv_cur * ref_div; - - if (vdiv_cur >= FSL_FEATURE_MCG_PLL_VDIV_BASE) - { - if (ret_freq == desireFreq) /* If desire frequency is got. */ - { - *prdiv = prdiv_cur - FSL_FEATURE_MCG_PLL_PRDIV_BASE; - *vdiv = vdiv_cur - FSL_FEATURE_MCG_PLL_VDIV_BASE; - return ret_freq; - } - /* New PRDIV/VDIV is closer. */ - if (diff > desireFreq - ret_freq) - { - diff = desireFreq - ret_freq; - ret_prdiv = prdiv_cur; - ret_vdiv = vdiv_cur; - } - } - vdiv_cur++; - if (vdiv_cur <= (FSL_FEATURE_MCG_PLL_VDIV_BASE + 31U)) - { - ret_freq += ref_div; - /* New PRDIV/VDIV is closer. */ - if (diff > ret_freq - desireFreq) - { - diff = ret_freq - desireFreq; - ret_prdiv = prdiv_cur; - ret_vdiv = vdiv_cur; - } - } - } - - if (0xFFFFFFFFU != diff) - { - /* PRDIV/VDIV found. */ - *prdiv = ret_prdiv - FSL_FEATURE_MCG_PLL_PRDIV_BASE; - *vdiv = ret_vdiv - FSL_FEATURE_MCG_PLL_VDIV_BASE; - ret_freq = (refFreq / ret_prdiv) * ret_vdiv; - return ret_freq; - } - else - { - /* No proper PRDIV/VDIV found. */ - return 0U; - } -} - -void CLOCK_EnablePll0(mcg_pll_config_t const *config) -{ - assert(config); - - uint8_t mcg_c5 = 0U; - - mcg_c5 |= MCG_C5_PRDIV0(config->prdiv); - MCG->C5 = mcg_c5; /* Disable the PLL first. */ - - MCG->C6 = (MCG->C6 & ~MCG_C6_VDIV0_MASK) | MCG_C6_VDIV0(config->vdiv); - - /* Set enable mode. */ - MCG->C5 |= ((uint32_t)kMCG_PllEnableIndependent | (uint32_t)config->enableMode); - - /* Wait for PLL lock. */ - while (!(MCG->S & MCG_S_LOCK0_MASK)) - { - } -} - -void CLOCK_SetOsc0MonitorMode(mcg_monitor_mode_t mode) -{ - /* Clear the previous flag, MCG_SC[LOCS0]. */ - MCG->SC &= ~MCG_SC_ATMF_MASK; - - if (kMCG_MonitorNone == mode) - { - MCG->C6 &= ~MCG_C6_CME0_MASK; - } - else - { - if (kMCG_MonitorInt == mode) - { - MCG->C2 &= ~MCG_C2_LOCRE0_MASK; - } - else - { - MCG->C2 |= MCG_C2_LOCRE0_MASK; - } - MCG->C6 |= MCG_C6_CME0_MASK; - } -} - -void CLOCK_SetRtcOscMonitorMode(mcg_monitor_mode_t mode) -{ - uint8_t mcg_c8 = MCG->C8; - - mcg_c8 &= ~(MCG_C8_CME1_MASK | MCG_C8_LOCRE1_MASK); - - if (kMCG_MonitorNone != mode) - { - if (kMCG_MonitorReset == mode) - { - mcg_c8 |= MCG_C8_LOCRE1_MASK; - } - mcg_c8 |= MCG_C8_CME1_MASK; - } - MCG->C8 = mcg_c8; -} - -void CLOCK_SetPll0MonitorMode(mcg_monitor_mode_t mode) -{ - uint8_t mcg_c8; - - /* Clear previous flag. */ - MCG->S = MCG_S_LOLS0_MASK; - - if (kMCG_MonitorNone == mode) - { - MCG->C6 &= ~MCG_C6_LOLIE0_MASK; - } - else - { - mcg_c8 = MCG->C8; - - mcg_c8 &= ~MCG_C8_LOCS1_MASK; - - if (kMCG_MonitorInt == mode) - { - mcg_c8 &= ~MCG_C8_LOLRE_MASK; - } - else - { - mcg_c8 |= MCG_C8_LOLRE_MASK; - } - MCG->C8 = mcg_c8; - MCG->C6 |= MCG_C6_LOLIE0_MASK; - } -} - -uint32_t CLOCK_GetStatusFlags(void) -{ - uint32_t ret = 0U; - uint8_t mcg_s = MCG->S; - - if (MCG->SC & MCG_SC_LOCS0_MASK) - { - ret |= kMCG_Osc0LostFlag; - } - if (mcg_s & MCG_S_OSCINIT0_MASK) - { - ret |= kMCG_Osc0InitFlag; - } - if (MCG->C8 & MCG_C8_LOCS1_MASK) - { - ret |= kMCG_RtcOscLostFlag; - } - if (mcg_s & MCG_S_LOLS0_MASK) - { - ret |= kMCG_Pll0LostFlag; - } - if (mcg_s & MCG_S_LOCK0_MASK) - { - ret |= kMCG_Pll0LockFlag; - } - return ret; -} - -void CLOCK_ClearStatusFlags(uint32_t mask) -{ - uint8_t reg; - - if (mask & kMCG_Osc0LostFlag) - { - MCG->SC &= ~MCG_SC_ATMF_MASK; - } - if (mask & kMCG_RtcOscLostFlag) - { - reg = MCG->C8; - MCG->C8 = reg; - } - if (mask & kMCG_Pll0LostFlag) - { - MCG->S = MCG_S_LOLS0_MASK; - } -} - -void CLOCK_InitOsc0(osc_config_t const *config) -{ - uint8_t range = CLOCK_GetOscRangeFromFreq(config->freq); - - OSC_SetCapLoad(OSC0, config->capLoad); - OSC_SetExtRefClkConfig(OSC0, &config->oscerConfig); - - MCG->C2 = ((MCG->C2 & ~OSC_MODE_MASK) | MCG_C2_RANGE(range) | (uint8_t)config->workMode); - - if ((kOSC_ModeExt != config->workMode) && (OSC0->CR & OSC_CR_ERCLKEN_MASK)) - { - /* Wait for stable. */ - while (!(MCG->S & MCG_S_OSCINIT0_MASK)) - { - } - } -} - -void CLOCK_DeinitOsc0(void) -{ - OSC0->CR = 0U; - MCG->C2 &= ~OSC_MODE_MASK; -} - -status_t CLOCK_TrimInternalRefClk(uint32_t extFreq, uint32_t desireFreq, uint32_t *actualFreq, mcg_atm_select_t atms) -{ - uint32_t multi; /* extFreq / desireFreq */ - uint32_t actv; /* Auto trim value. */ - uint8_t mcg_sc; - - static const uint32_t trimRange[2][2] = { - /* Min Max */ - {TRIM_SIRC_MIN, TRIM_SIRC_MAX}, /* Slow IRC. */ - {TRIM_FIRC_MIN, TRIM_FIRC_MAX} /* Fast IRC. */ - }; - - if ((extFreq > TRIM_REF_CLK_MAX) || (extFreq < TRIM_REF_CLK_MIN)) - { - return kStatus_MCG_AtmBusClockInvalid; - } - - /* Check desired frequency range. */ - if ((desireFreq < trimRange[atms][0]) || (desireFreq > trimRange[atms][1])) - { - return kStatus_MCG_AtmDesiredFreqInvalid; - } - - /* - Make sure internal reference clock is not used to generate bus clock. - Here only need to check (MCG_S_IREFST == 1). - */ - if (MCG_S_IREFST(kMCG_FllSrcInternal) == (MCG->S & MCG_S_IREFST_MASK)) - { - return kStatus_MCG_AtmIrcUsed; - } - - multi = extFreq / desireFreq; - actv = multi * 21U; - - if (kMCG_AtmSel4m == atms) - { - actv *= 128U; - } - - /* Now begin to start trim. */ - MCG->ATCVL = (uint8_t)actv; - MCG->ATCVH = (uint8_t)(actv >> 8U); - - mcg_sc = MCG->SC; - mcg_sc &= ~(MCG_SC_ATMS_MASK | MCG_SC_LOCS0_MASK); - mcg_sc |= (MCG_SC_ATMF_MASK | MCG_SC_ATMS(atms)); - MCG->SC = (mcg_sc | MCG_SC_ATME_MASK); - - /* Wait for finished. */ - while (MCG->SC & MCG_SC_ATME_MASK) - { - } - - /* Error occurs? */ - if (MCG->SC & MCG_SC_ATMF_MASK) - { - /* Clear the failed flag. */ - MCG->SC = mcg_sc; - return kStatus_MCG_AtmHardwareFail; - } - - *actualFreq = extFreq / multi; - - if (kMCG_AtmSel4m == atms) - { - s_fastIrcFreq = *actualFreq; - } - else - { - s_slowIrcFreq = *actualFreq; - } - - return kStatus_Success; -} - -mcg_mode_t CLOCK_GetMode(void) -{ - mcg_mode_t mode = kMCG_ModeError; - uint32_t clkst = MCG_S_CLKST_VAL; - uint32_t irefst = MCG_S_IREFST_VAL; - uint32_t lp = MCG_C2_LP_VAL; - uint32_t pllst = MCG_S_PLLST_VAL; - - /*------------------------------------------------------------------ - Mode and Registers - ____________________________________________________________________ - - Mode | CLKST | IREFST | PLLST | LP - ____________________________________________________________________ - - FEI | 00(FLL) | 1(INT) | 0(FLL) | X - ____________________________________________________________________ - - FEE | 00(FLL) | 0(EXT) | 0(FLL) | X - ____________________________________________________________________ - - FBE | 10(EXT) | 0(EXT) | 0(FLL) | 0(NORMAL) - ____________________________________________________________________ - - FBI | 01(INT) | 1(INT) | 0(FLL) | 0(NORMAL) - ____________________________________________________________________ - - BLPI | 01(INT) | 1(INT) | 0(FLL) | 1(LOW POWER) - ____________________________________________________________________ - - BLPE | 10(EXT) | 0(EXT) | X | 1(LOW POWER) - ____________________________________________________________________ - - PEE | 11(PLL) | 0(EXT) | 1(PLL) | X - ____________________________________________________________________ - - PBE | 10(EXT) | 0(EXT) | 1(PLL) | O(NORMAL) - ____________________________________________________________________ - - PBI | 01(INT) | 1(INT) | 1(PLL) | 0(NORMAL) - ____________________________________________________________________ - - PEI | 11(PLL) | 1(INT) | 1(PLL) | X - ____________________________________________________________________ - - ----------------------------------------------------------------------*/ - - switch (clkst) - { - case kMCG_ClkOutStatFll: - if (kMCG_FllSrcExternal == irefst) - { - mode = kMCG_ModeFEE; - } - else - { - mode = kMCG_ModeFEI; - } - break; - case kMCG_ClkOutStatInt: - if (lp) - { - mode = kMCG_ModeBLPI; - } - else - { - { - mode = kMCG_ModeFBI; - } - } - break; - case kMCG_ClkOutStatExt: - if (lp) - { - mode = kMCG_ModeBLPE; - } - else - { - if (kMCG_PllstPll == pllst) - { - mode = kMCG_ModePBE; - } - else - { - mode = kMCG_ModeFBE; - } - } - break; - case kMCG_ClkOutStatPll: - { - mode = kMCG_ModePEE; - } - break; - default: - break; - } - - return mode; -} - -status_t CLOCK_SetFeiMode(mcg_dmx32_t dmx32, mcg_drs_t drs, void (*fllStableDelay)(void)) -{ - uint8_t mcg_c4; - bool change_drs = false; - -#if (defined(MCG_CONFIG_CHECK_PARAM) && MCG_CONFIG_CHECK_PARAM) - mcg_mode_t mode = CLOCK_GetMode(); - if (!((kMCG_ModeFEI == mode) || (kMCG_ModeFBI == mode) || (kMCG_ModeFBE == mode) || (kMCG_ModeFEE == mode))) - { - return kStatus_MCG_ModeUnreachable; - } -#endif - mcg_c4 = MCG->C4; - - /* - Errata: ERR007993 - Workaround: Invert MCG_C4[DMX32] or change MCG_C4[DRST_DRS] before - reference clock source changes, then reset to previous value after - reference clock changes. - */ - if (kMCG_FllSrcExternal == MCG_S_IREFST_VAL) - { - change_drs = true; - /* Change the LSB of DRST_DRS. */ - MCG->C4 ^= (1U << MCG_C4_DRST_DRS_SHIFT); - } - - /* Set CLKS and IREFS. */ - MCG->C1 = - ((MCG->C1 & ~(MCG_C1_CLKS_MASK | MCG_C1_IREFS_MASK))) | (MCG_C1_CLKS(kMCG_ClkOutSrcOut) /* CLKS = 0 */ - | MCG_C1_IREFS(kMCG_FllSrcInternal)); /* IREFS = 1 */ - - /* Wait and check status. */ - while (kMCG_FllSrcInternal != MCG_S_IREFST_VAL) - { - } - - /* Errata: ERR007993 */ - if (change_drs) - { - MCG->C4 = mcg_c4; - } - - /* In FEI mode, the MCG_C4[DMX32] is set to 0U. */ - MCG->C4 = (mcg_c4 & ~(MCG_C4_DMX32_MASK | MCG_C4_DRST_DRS_MASK)) | (MCG_C4_DMX32(dmx32) | MCG_C4_DRST_DRS(drs)); - - /* Check MCG_S[CLKST] */ - while (kMCG_ClkOutStatFll != MCG_S_CLKST_VAL) - { - } - - /* Wait for FLL stable time. */ - if (fllStableDelay) - { - fllStableDelay(); - } - - return kStatus_Success; -} - -status_t CLOCK_SetFeeMode(uint8_t frdiv, mcg_dmx32_t dmx32, mcg_drs_t drs, void (*fllStableDelay)(void)) -{ - uint8_t mcg_c4; - bool change_drs = false; - -#if (defined(MCG_CONFIG_CHECK_PARAM) && MCG_CONFIG_CHECK_PARAM) - mcg_mode_t mode = CLOCK_GetMode(); - if (!((kMCG_ModeFEE == mode) || (kMCG_ModeFBI == mode) || (kMCG_ModeFBE == mode) || (kMCG_ModeFEI == mode))) - { - return kStatus_MCG_ModeUnreachable; - } -#endif - mcg_c4 = MCG->C4; - - /* - Errata: ERR007993 - Workaround: Invert MCG_C4[DMX32] or change MCG_C4[DRST_DRS] before - reference clock source changes, then reset to previous value after - reference clock changes. - */ - if (kMCG_FllSrcInternal == MCG_S_IREFST_VAL) - { - change_drs = true; - /* Change the LSB of DRST_DRS. */ - MCG->C4 ^= (1U << MCG_C4_DRST_DRS_SHIFT); - } - - /* Set CLKS and IREFS. */ - MCG->C1 = ((MCG->C1 & ~(MCG_C1_CLKS_MASK | MCG_C1_FRDIV_MASK | MCG_C1_IREFS_MASK)) | - (MCG_C1_CLKS(kMCG_ClkOutSrcOut) /* CLKS = 0 */ - | MCG_C1_FRDIV(frdiv) /* FRDIV */ - | MCG_C1_IREFS(kMCG_FllSrcExternal))); /* IREFS = 0 */ - - /* If use external crystal as clock source, wait for it stable. */ - if (MCG_C7_OSCSEL(kMCG_OscselOsc) == (MCG->C7 & MCG_C7_OSCSEL_MASK)) - { - if (MCG->C2 & MCG_C2_EREFS_MASK) - { - while (!(MCG->S & MCG_S_OSCINIT0_MASK)) - { - } - } - } - - /* Wait and check status. */ - while (kMCG_FllSrcExternal != MCG_S_IREFST_VAL) - { - } - - /* Errata: ERR007993 */ - if (change_drs) - { - MCG->C4 = mcg_c4; - } - - /* Set DRS and DMX32. */ - mcg_c4 = ((mcg_c4 & ~(MCG_C4_DMX32_MASK | MCG_C4_DRST_DRS_MASK)) | (MCG_C4_DMX32(dmx32) | MCG_C4_DRST_DRS(drs))); - MCG->C4 = mcg_c4; - - /* Wait for DRST_DRS update. */ - while (MCG->C4 != mcg_c4) - { - } - - /* Check MCG_S[CLKST] */ - while (kMCG_ClkOutStatFll != MCG_S_CLKST_VAL) - { - } - - /* Wait for FLL stable time. */ - if (fllStableDelay) - { - fllStableDelay(); - } - - return kStatus_Success; -} - -status_t CLOCK_SetFbiMode(mcg_dmx32_t dmx32, mcg_drs_t drs, void (*fllStableDelay)(void)) -{ - uint8_t mcg_c4; - bool change_drs = false; - -#if (defined(MCG_CONFIG_CHECK_PARAM) && MCG_CONFIG_CHECK_PARAM) - mcg_mode_t mode = CLOCK_GetMode(); - - if (!((kMCG_ModeFEE == mode) || (kMCG_ModeFBI == mode) || (kMCG_ModeFBE == mode) || (kMCG_ModeFEI == mode) || - (kMCG_ModeBLPI == mode))) - - { - return kStatus_MCG_ModeUnreachable; - } -#endif - - mcg_c4 = MCG->C4; - - MCG->C2 &= ~MCG_C2_LP_MASK; /* Disable lowpower. */ - - /* - Errata: ERR007993 - Workaround: Invert MCG_C4[DMX32] or change MCG_C4[DRST_DRS] before - reference clock source changes, then reset to previous value after - reference clock changes. - */ - if (kMCG_FllSrcExternal == MCG_S_IREFST_VAL) - { - change_drs = true; - /* Change the LSB of DRST_DRS. */ - MCG->C4 ^= (1U << MCG_C4_DRST_DRS_SHIFT); - } - - /* Set CLKS and IREFS. */ - MCG->C1 = - ((MCG->C1 & ~(MCG_C1_CLKS_MASK | MCG_C1_IREFS_MASK)) | (MCG_C1_CLKS(kMCG_ClkOutSrcInternal) /* CLKS = 1 */ - | MCG_C1_IREFS(kMCG_FllSrcInternal))); /* IREFS = 1 */ - - /* Wait and check status. */ - while (kMCG_FllSrcInternal != MCG_S_IREFST_VAL) - { - } - - /* Errata: ERR007993 */ - if (change_drs) - { - MCG->C4 = mcg_c4; - } - - while (kMCG_ClkOutStatInt != MCG_S_CLKST_VAL) - { - } - - MCG->C4 = (mcg_c4 & ~(MCG_C4_DMX32_MASK | MCG_C4_DRST_DRS_MASK)) | (MCG_C4_DMX32(dmx32) | MCG_C4_DRST_DRS(drs)); - - /* Wait for FLL stable time. */ - if (fllStableDelay) - { - fllStableDelay(); - } - - return kStatus_Success; -} - -status_t CLOCK_SetFbeMode(uint8_t frdiv, mcg_dmx32_t dmx32, mcg_drs_t drs, void (*fllStableDelay)(void)) -{ - uint8_t mcg_c4; - bool change_drs = false; - -#if (defined(MCG_CONFIG_CHECK_PARAM) && MCG_CONFIG_CHECK_PARAM) - mcg_mode_t mode = CLOCK_GetMode(); - if (!((kMCG_ModeFEE == mode) || (kMCG_ModeFBI == mode) || (kMCG_ModeFBE == mode) || (kMCG_ModeFEI == mode) || - (kMCG_ModePBE == mode) || (kMCG_ModeBLPE == mode))) - { - return kStatus_MCG_ModeUnreachable; - } -#endif - - /* Change to FLL mode. */ - MCG->C6 &= ~MCG_C6_PLLS_MASK; - while (MCG->S & MCG_S_PLLST_MASK) - { - } - - /* Set LP bit to enable the FLL */ - MCG->C2 &= ~MCG_C2_LP_MASK; - - mcg_c4 = MCG->C4; - - /* - Errata: ERR007993 - Workaround: Invert MCG_C4[DMX32] or change MCG_C4[DRST_DRS] before - reference clock source changes, then reset to previous value after - reference clock changes. - */ - if (kMCG_FllSrcInternal == MCG_S_IREFST_VAL) - { - change_drs = true; - /* Change the LSB of DRST_DRS. */ - MCG->C4 ^= (1U << MCG_C4_DRST_DRS_SHIFT); - } - - /* Set CLKS and IREFS. */ - MCG->C1 = ((MCG->C1 & ~(MCG_C1_CLKS_MASK | MCG_C1_FRDIV_MASK | MCG_C1_IREFS_MASK)) | - (MCG_C1_CLKS(kMCG_ClkOutSrcExternal) /* CLKS = 2 */ - | MCG_C1_FRDIV(frdiv) /* FRDIV = frdiv */ - | MCG_C1_IREFS(kMCG_FllSrcExternal))); /* IREFS = 0 */ - - /* If use external crystal as clock source, wait for it stable. */ - if (MCG_C7_OSCSEL(kMCG_OscselOsc) == (MCG->C7 & MCG_C7_OSCSEL_MASK)) - { - if (MCG->C2 & MCG_C2_EREFS_MASK) - { - while (!(MCG->S & MCG_S_OSCINIT0_MASK)) - { - } - } - } - - /* Wait for Reference clock Status bit to clear */ - while (kMCG_FllSrcExternal != MCG_S_IREFST_VAL) - { - } - - /* Errata: ERR007993 */ - if (change_drs) - { - MCG->C4 = mcg_c4; - } - - /* Set DRST_DRS and DMX32. */ - mcg_c4 = ((mcg_c4 & ~(MCG_C4_DMX32_MASK | MCG_C4_DRST_DRS_MASK)) | (MCG_C4_DMX32(dmx32) | MCG_C4_DRST_DRS(drs))); - - /* Wait for clock status bits to show clock source is ext ref clk */ - while (kMCG_ClkOutStatExt != MCG_S_CLKST_VAL) - { - } - - /* Wait for fll stable time. */ - if (fllStableDelay) - { - fllStableDelay(); - } - - return kStatus_Success; -} - -status_t CLOCK_SetBlpiMode(void) -{ -#if (defined(MCG_CONFIG_CHECK_PARAM) && MCG_CONFIG_CHECK_PARAM) - if (MCG_S_CLKST_VAL != kMCG_ClkOutStatInt) - { - return kStatus_MCG_ModeUnreachable; - } -#endif /* MCG_CONFIG_CHECK_PARAM */ - - /* Set LP. */ - MCG->C2 |= MCG_C2_LP_MASK; - - return kStatus_Success; -} - -status_t CLOCK_SetBlpeMode(void) -{ -#if (defined(MCG_CONFIG_CHECK_PARAM) && MCG_CONFIG_CHECK_PARAM) - if (MCG_S_CLKST_VAL != kMCG_ClkOutStatExt) - { - return kStatus_MCG_ModeUnreachable; - } -#endif - - /* Set LP bit to enter BLPE mode. */ - MCG->C2 |= MCG_C2_LP_MASK; - - return kStatus_Success; -} - -status_t CLOCK_SetPbeMode(mcg_pll_clk_select_t pllcs, mcg_pll_config_t const *config) -{ - assert(config); - - /* - This function is designed to change MCG to PBE mode from PEE/BLPE/FBE, - but with this workflow, the source mode could be all modes except PEI/PBI. - */ - MCG->C2 &= ~MCG_C2_LP_MASK; /* Disable lowpower. */ - - /* Change to use external clock first. */ - MCG->C1 = ((MCG->C1 & ~(MCG_C1_CLKS_MASK | MCG_C1_IREFS_MASK)) | MCG_C1_CLKS(kMCG_ClkOutSrcExternal)); - - /* Wait for CLKST clock status bits to show clock source is ext ref clk */ - while ((MCG->S & (MCG_S_IREFST_MASK | MCG_S_CLKST_MASK)) != - (MCG_S_IREFST(kMCG_FllSrcExternal) | MCG_S_CLKST(kMCG_ClkOutStatExt))) - { - } - - /* Disable PLL first, then configure PLL. */ - MCG->C6 &= ~MCG_C6_PLLS_MASK; - while (MCG->S & MCG_S_PLLST_MASK) - { - } - - /* Configure the PLL. */ - { - CLOCK_EnablePll0(config); - } - - /* Change to PLL mode. */ - MCG->C6 |= MCG_C6_PLLS_MASK; - - /* Wait for PLL mode changed. */ - while (!(MCG->S & MCG_S_PLLST_MASK)) - { - } - - return kStatus_Success; -} - -status_t CLOCK_SetPeeMode(void) -{ -#if (defined(MCG_CONFIG_CHECK_PARAM) && MCG_CONFIG_CHECK_PARAM) - mcg_mode_t mode = CLOCK_GetMode(); - if (kMCG_ModePBE != mode) - { - return kStatus_MCG_ModeUnreachable; - } -#endif - - /* Change to use PLL/FLL output clock first. */ - MCG->C1 = (MCG->C1 & ~MCG_C1_CLKS_MASK) | MCG_C1_CLKS(kMCG_ClkOutSrcOut); - - /* Wait for clock status bits to update */ - while (MCG_S_CLKST_VAL != kMCG_ClkOutStatPll) - { - } - - return kStatus_Success; -} - -status_t CLOCK_ExternalModeToFbeModeQuick(void) -{ -#if (defined(MCG_CONFIG_CHECK_PARAM) && MCG_CONFIG_CHECK_PARAM) - if (MCG->S & MCG_S_IREFST_MASK) - { - return kStatus_MCG_ModeInvalid; - } -#endif /* MCG_CONFIG_CHECK_PARAM */ - - /* Disable low power */ - MCG->C2 &= ~MCG_C2_LP_MASK; - - MCG->C1 = ((MCG->C1 & ~MCG_C1_CLKS_MASK) | MCG_C1_CLKS(kMCG_ClkOutSrcExternal)); - while (MCG_S_CLKST_VAL != kMCG_ClkOutStatExt) - { - } - - /* Disable PLL. */ - MCG->C6 &= ~MCG_C6_PLLS_MASK; - while (MCG->S & MCG_S_PLLST_MASK) - { - } - - return kStatus_Success; -} - -status_t CLOCK_InternalModeToFbiModeQuick(void) -{ -#if (defined(MCG_CONFIG_CHECK_PARAM) && MCG_CONFIG_CHECK_PARAM) - if (!(MCG->S & MCG_S_IREFST_MASK)) - { - return kStatus_MCG_ModeInvalid; - } -#endif - - /* Disable low power */ - MCG->C2 &= ~MCG_C2_LP_MASK; - - MCG->C1 = ((MCG->C1 & ~MCG_C1_CLKS_MASK) | MCG_C1_CLKS(kMCG_ClkOutSrcInternal)); - while (MCG_S_CLKST_VAL != kMCG_ClkOutStatInt) - { - } - - return kStatus_Success; -} - -status_t CLOCK_BootToFeiMode(mcg_dmx32_t dmx32, mcg_drs_t drs, void (*fllStableDelay)(void)) -{ - return CLOCK_SetFeiMode(dmx32, drs, fllStableDelay); -} - -status_t CLOCK_BootToFeeMode( - mcg_oscsel_t oscsel, uint8_t frdiv, mcg_dmx32_t dmx32, mcg_drs_t drs, void (*fllStableDelay)(void)) -{ - CLOCK_SetExternalRefClkConfig(oscsel); - - return CLOCK_SetFeeMode(frdiv, dmx32, drs, fllStableDelay); -} - -status_t CLOCK_BootToBlpiMode(uint8_t fcrdiv, mcg_irc_mode_t ircs, uint8_t ircEnableMode) -{ - /* If reset mode is FEI mode, set MCGIRCLK and always success. */ - CLOCK_SetInternalRefClkConfig(ircEnableMode, ircs, fcrdiv); - - /* If reset mode is not BLPI, first enter FBI mode. */ - MCG->C1 = (MCG->C1 & ~MCG_C1_CLKS_MASK) | MCG_C1_CLKS(kMCG_ClkOutSrcInternal); - while (MCG_S_CLKST_VAL != kMCG_ClkOutStatInt) - { - } - - /* Enter BLPI mode. */ - MCG->C2 |= MCG_C2_LP_MASK; - - return kStatus_Success; -} - -status_t CLOCK_BootToBlpeMode(mcg_oscsel_t oscsel) -{ - CLOCK_SetExternalRefClkConfig(oscsel); - - /* Set to FBE mode. */ - MCG->C1 = - ((MCG->C1 & ~(MCG_C1_CLKS_MASK | MCG_C1_IREFS_MASK)) | (MCG_C1_CLKS(kMCG_ClkOutSrcExternal) /* CLKS = 2 */ - | MCG_C1_IREFS(kMCG_FllSrcExternal))); /* IREFS = 0 */ - - /* If use external crystal as clock source, wait for it stable. */ - if (MCG_C7_OSCSEL(kMCG_OscselOsc) == (MCG->C7 & MCG_C7_OSCSEL_MASK)) - { - if (MCG->C2 & MCG_C2_EREFS_MASK) - { - while (!(MCG->S & MCG_S_OSCINIT0_MASK)) - { - } - } - } - - /* Wait for MCG_S[CLKST] and MCG_S[IREFST]. */ - while ((MCG->S & (MCG_S_IREFST_MASK | MCG_S_CLKST_MASK)) != - (MCG_S_IREFST(kMCG_FllSrcExternal) | MCG_S_CLKST(kMCG_ClkOutStatExt))) - { - } - - /* In FBE now, start to enter BLPE. */ - MCG->C2 |= MCG_C2_LP_MASK; - - return kStatus_Success; -} - -status_t CLOCK_BootToPeeMode(mcg_oscsel_t oscsel, mcg_pll_clk_select_t pllcs, mcg_pll_config_t const *config) -{ - assert(config); - - CLOCK_SetExternalRefClkConfig(oscsel); - - CLOCK_SetPbeMode(pllcs, config); - - /* Change to use PLL output clock. */ - MCG->C1 = (MCG->C1 & ~MCG_C1_CLKS_MASK) | MCG_C1_CLKS(kMCG_ClkOutSrcOut); - while (MCG_S_CLKST_VAL != kMCG_ClkOutStatPll) - { - } - - return kStatus_Success; -} - -/* - The transaction matrix. It defines the path for mode switch, the row is for - current mode and the column is target mode. - For example, switch from FEI to PEE: - 1. Current mode FEI, next mode is mcgModeMatrix[FEI][PEE] = FBE, so swith to FBE. - 2. Current mode FBE, next mode is mcgModeMatrix[FBE][PEE] = PBE, so swith to PBE. - 3. Current mode PBE, next mode is mcgModeMatrix[PBE][PEE] = PEE, so swith to PEE. - Thus the MCG mode has changed from FEI to PEE. - */ -static const mcg_mode_t mcgModeMatrix[8][8] = { - {kMCG_ModeFEI, kMCG_ModeFBI, kMCG_ModeFBI, kMCG_ModeFEE, kMCG_ModeFBE, kMCG_ModeFBE, kMCG_ModeFBE, - kMCG_ModeFBE}, /* FEI */ - {kMCG_ModeFEI, kMCG_ModeFBI, kMCG_ModeBLPI, kMCG_ModeFEE, kMCG_ModeFBE, kMCG_ModeFBE, kMCG_ModeFBE, - kMCG_ModeFBE}, /* FBI */ - {kMCG_ModeFBI, kMCG_ModeFBI, kMCG_ModeBLPI, kMCG_ModeFBI, kMCG_ModeFBI, kMCG_ModeFBI, kMCG_ModeFBI, - kMCG_ModeFBI}, /* BLPI */ - {kMCG_ModeFEI, kMCG_ModeFBI, kMCG_ModeFBI, kMCG_ModeFEE, kMCG_ModeFBE, kMCG_ModeFBE, kMCG_ModeFBE, - kMCG_ModeFBE}, /* FEE */ - {kMCG_ModeFEI, kMCG_ModeFBI, kMCG_ModeFBI, kMCG_ModeFEE, kMCG_ModeFBE, kMCG_ModeBLPE, kMCG_ModePBE, - kMCG_ModePBE}, /* FBE */ - {kMCG_ModeFBE, kMCG_ModeFBE, kMCG_ModeFBE, kMCG_ModeFBE, kMCG_ModeFBE, kMCG_ModeBLPE, kMCG_ModePBE, - kMCG_ModePBE}, /* BLPE */ - {kMCG_ModeFBE, kMCG_ModeFBE, kMCG_ModeFBE, kMCG_ModeFBE, kMCG_ModeFBE, kMCG_ModeBLPE, kMCG_ModePBE, - kMCG_ModePEE}, /* PBE */ - {kMCG_ModePBE, kMCG_ModePBE, kMCG_ModePBE, kMCG_ModePBE, kMCG_ModePBE, kMCG_ModePBE, kMCG_ModePBE, - kMCG_ModePBE} /* PEE */ - /* FEI FBI BLPI FEE FBE BLPE PBE PEE */ -}; - -status_t CLOCK_SetMcgConfig(const mcg_config_t *config) -{ - mcg_mode_t next_mode; - status_t status = kStatus_Success; - - mcg_pll_clk_select_t pllcs = kMCG_PllClkSelPll0; - - /* If need to change external clock, MCG_C7[OSCSEL]. */ - if (MCG_C7_OSCSEL_VAL != config->oscsel) - { - /* If external clock is in use, change to FEI first. */ - if (!(MCG->S & MCG_S_IRCST_MASK)) - { - CLOCK_ExternalModeToFbeModeQuick(); - CLOCK_SetFeiMode(config->dmx32, config->drs, (void (*)(void))0); - } - - CLOCK_SetExternalRefClkConfig(config->oscsel); - } - - /* Re-configure MCGIRCLK, if MCGIRCLK is used as system clock source, then change to FEI/PEI first. */ - if (MCG_S_CLKST_VAL == kMCG_ClkOutStatInt) - { - MCG->C2 &= ~MCG_C2_LP_MASK; /* Disable lowpower. */ - - { - CLOCK_SetFeiMode(config->dmx32, config->drs, CLOCK_FllStableDelay); - } - } - - /* Configure MCGIRCLK. */ - CLOCK_SetInternalRefClkConfig(config->irclkEnableMode, config->ircs, config->fcrdiv); - - next_mode = CLOCK_GetMode(); - - do - { - next_mode = mcgModeMatrix[next_mode][config->mcgMode]; - - switch (next_mode) - { - case kMCG_ModeFEI: - status = CLOCK_SetFeiMode(config->dmx32, config->drs, CLOCK_FllStableDelay); - break; - case kMCG_ModeFEE: - status = CLOCK_SetFeeMode(config->frdiv, config->dmx32, config->drs, CLOCK_FllStableDelay); - break; - case kMCG_ModeFBI: - status = CLOCK_SetFbiMode(config->dmx32, config->drs, (void (*)(void))0); - break; - case kMCG_ModeFBE: - status = CLOCK_SetFbeMode(config->frdiv, config->dmx32, config->drs, (void (*)(void))0); - break; - case kMCG_ModeBLPI: - status = CLOCK_SetBlpiMode(); - break; - case kMCG_ModeBLPE: - status = CLOCK_SetBlpeMode(); - break; - case kMCG_ModePBE: - /* If target mode is not PBE or PEE, then only need to set CLKS = EXT here. */ - if ((kMCG_ModePEE == config->mcgMode) || (kMCG_ModePBE == config->mcgMode)) - { - { - status = CLOCK_SetPbeMode(pllcs, &config->pll0Config); - } - } - else - { - MCG->C1 = ((MCG->C1 & ~MCG_C1_CLKS_MASK) | MCG_C1_CLKS(kMCG_ClkOutSrcExternal)); - while (MCG_S_CLKST_VAL != kMCG_ClkOutStatExt) - { - } - } - break; - case kMCG_ModePEE: - status = CLOCK_SetPeeMode(); - break; - default: - break; - } - if (kStatus_Success != status) - { - return status; - } - } while (next_mode != config->mcgMode); - - if (config->pll0Config.enableMode & kMCG_PllEnableIndependent) - { - CLOCK_EnablePll0(&config->pll0Config); - } - else - { - MCG->C5 &= ~(uint32_t)kMCG_PllEnableIndependent; - } - return kStatus_Success; -} diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_clock.h b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_clock.h deleted file mode 100644 index f08000c33f5..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_clock.h +++ /dev/null @@ -1,1533 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright (c) 2016 - 2017 , NXP - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef _FSL_CLOCK_H_ -#define _FSL_CLOCK_H_ - -#include "fsl_common.h" - -/*! @addtogroup clock */ -/*! @{ */ - -/*! @file */ - -/******************************************************************************* - * Configurations - ******************************************************************************/ - -/*! @brief Configures whether to check a parameter in a function. - * - * Some MCG settings must be changed with conditions, for example: - * 1. MCGIRCLK settings, such as the source, divider, and the trim value should not change when - * MCGIRCLK is used as a system clock source. - * 2. MCG_C7[OSCSEL] should not be changed when the external reference clock is used - * as a system clock source. For example, in FBE/BLPE/PBE modes. - * 3. The users should only switch between the supported clock modes. - * - * MCG functions check the parameter and MCG status before setting, if not allowed - * to change, the functions return error. The parameter checking increases code size, - * if code size is a critical requirement, change #MCG_CONFIG_CHECK_PARAM to 0 to - * disable parameter checking. - */ -#ifndef MCG_CONFIG_CHECK_PARAM -#define MCG_CONFIG_CHECK_PARAM 0U -#endif - -/*! @brief Configure whether driver controls clock - * - * When set to 0, peripheral drivers will enable clock in initialize function - * and disable clock in de-initialize function. When set to 1, peripheral - * driver will not control the clock, application could contol the clock out of - * the driver. - * - * @note All drivers share this feature switcher. If it is set to 1, application - * should handle clock enable and disable for all drivers. - */ -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL)) -#define FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL 0 -#endif - -/******************************************************************************* - * Definitions - ******************************************************************************/ - -/*! @name Driver version */ -/*@{*/ -/*! @brief CLOCK driver version 2.2.1. */ -#define FSL_CLOCK_DRIVER_VERSION (MAKE_VERSION(2, 2, 1)) -/*@}*/ - -/*! @brief External XTAL0 (OSC0) clock frequency. - * - * The XTAL0/EXTAL0 (OSC0) clock frequency in Hz. When the clock is set up, use the - * function CLOCK_SetXtal0Freq to set the value in the clock driver. For example, - * if XTAL0 is 8 MHz: - * @code - * CLOCK_InitOsc0(...); // Set up the OSC0 - * CLOCK_SetXtal0Freq(80000000); // Set the XTAL0 value to the clock driver. - * @endcode - * - * This is important for the multicore platforms where only one core needs to set up the - * OSC0 using the CLOCK_InitOsc0. All other cores need to call the CLOCK_SetXtal0Freq - * to get a valid clock frequency. - */ -extern uint32_t g_xtal0Freq; - -/*! @brief External XTAL32/EXTAL32/RTC_CLKIN clock frequency. - * - * The XTAL32/EXTAL32/RTC_CLKIN clock frequency in Hz. When the clock is set up, use the - * function CLOCK_SetXtal32Freq to set the value in the clock driver. - * - * This is important for the multicore platforms where only one core needs to set up - * the clock. All other cores need to call the CLOCK_SetXtal32Freq - * to get a valid clock frequency. - */ -extern uint32_t g_xtal32Freq; - -/*! @brief IRC48M clock frequency in Hz. */ -#define MCG_INTERNAL_IRC_48M 48000000U - -#if (defined(OSC) && !(defined(OSC0))) -#define OSC0 OSC -#endif - -/*! @brief Clock ip name array for DMAMUX. */ -#define DMAMUX_CLOCKS \ - { \ - kCLOCK_Dmamux0 \ - } - -/*! @brief Clock ip name array for RTC. */ -#define RTC_CLOCKS \ - { \ - kCLOCK_Rtc0 \ - } - -/*! @brief Clock ip name array for SAI. */ -#define SAI_CLOCKS \ - { \ - kCLOCK_Sai0 \ - } - -/*! @brief Clock ip name array for FLEXBUS. */ -#define FLEXBUS_CLOCKS \ - { \ - kCLOCK_Flexbus0 \ - } - -/*! @brief Clock ip name array for PORT. */ -#define PORT_CLOCKS \ - { \ - kCLOCK_PortA, kCLOCK_PortB, kCLOCK_PortC, kCLOCK_PortD, kCLOCK_PortE \ - } - -/*! @brief Clock ip name array for EWM. */ -#define EWM_CLOCKS \ - { \ - kCLOCK_Ewm0 \ - } - -/*! @brief Clock ip name array for PIT. */ -#define PIT_CLOCKS \ - { \ - kCLOCK_Pit0 \ - } - -/*! @brief Clock ip name array for SDHC. */ -#define SDHC_CLOCKS \ - { \ - kCLOCK_Sdhc0 \ - } - -/*! @brief Clock ip name array for DSPI. */ -#define DSPI_CLOCKS \ - { \ - kCLOCK_Spi0, kCLOCK_Spi1, kCLOCK_Spi2 \ - } - -/*! @brief Clock ip name array for LPTMR. */ -#define LPTMR_CLOCKS \ - { \ - kCLOCK_Lptmr0 \ - } - -/*! @brief Clock ip name array for FTM. */ -#define FTM_CLOCKS \ - { \ - kCLOCK_Ftm0, kCLOCK_Ftm1, kCLOCK_Ftm2, kCLOCK_Ftm3 \ - } - -/*! @brief Clock ip name array for EDMA. */ -#define EDMA_CLOCKS \ - { \ - kCLOCK_Dma0 \ - } - -/*! @brief Clock ip name array for MPU. */ -#define SYSMPU_CLOCKS \ - { \ - kCLOCK_Sysmpu0 \ - } - -/*! @brief Clock ip name array for DAC. */ -#define DAC_CLOCKS \ - { \ - kCLOCK_Dac0, kCLOCK_Dac1 \ - } - -/*! @brief Clock ip name array for ADC16. */ -#define ADC16_CLOCKS \ - { \ - kCLOCK_Adc0, kCLOCK_Adc1 \ - } - -/*! @brief Clock ip name array for VREF. */ -#define VREF_CLOCKS \ - { \ - kCLOCK_Vref0 \ - } - -/*! @brief Clock ip name array for CMT. */ -#define CMT_CLOCKS \ - { \ - kCLOCK_Cmt0 \ - } - -/*! @brief Clock ip name array for UART. */ -#define UART_CLOCKS \ - { \ - kCLOCK_Uart0, kCLOCK_Uart1, kCLOCK_Uart2, kCLOCK_Uart3, kCLOCK_Uart4, kCLOCK_Uart5 \ - } - -/*! @brief Clock ip name array for RNGA. */ -#define RNGA_CLOCKS \ - { \ - kCLOCK_Rnga0 \ - } - -/*! @brief Clock ip name array for CRC. */ -#define CRC_CLOCKS \ - { \ - kCLOCK_Crc0 \ - } - -/*! @brief Clock ip name array for I2C. */ -#define I2C_CLOCKS \ - { \ - kCLOCK_I2c0, kCLOCK_I2c1, kCLOCK_I2c2 \ - } - -/*! @brief Clock ip name array for PDB. */ -#define PDB_CLOCKS \ - { \ - kCLOCK_Pdb0 \ - } - -/*! @brief Clock ip name array for FLEXCAN. */ -#define FLEXCAN_CLOCKS \ - { \ - kCLOCK_Flexcan0 \ - } - -/*! @brief Clock ip name array for FTF. */ -#define FTF_CLOCKS \ - { \ - kCLOCK_Ftf0 \ - } - -/*! @brief Clock ip name array for CMP. */ -#define CMP_CLOCKS \ - { \ - kCLOCK_Cmp0, kCLOCK_Cmp1, kCLOCK_Cmp2 \ - } - -/*! - * @brief LPO clock frequency. - */ -#define LPO_CLK_FREQ 1000U - -/*! @brief Peripherals clock source definition. */ -#define SYS_CLK kCLOCK_CoreSysClk -#define BUS_CLK kCLOCK_BusClk - -#define I2C0_CLK_SRC BUS_CLK -#define I2C1_CLK_SRC BUS_CLK -#define I2C2_CLK_SRC BUS_CLK -#define DSPI0_CLK_SRC BUS_CLK -#define DSPI1_CLK_SRC BUS_CLK -#define DSPI2_CLK_SRC BUS_CLK -#define UART0_CLK_SRC SYS_CLK -#define UART1_CLK_SRC SYS_CLK -#define UART2_CLK_SRC BUS_CLK -#define UART3_CLK_SRC BUS_CLK -#define UART4_CLK_SRC BUS_CLK -#define UART5_CLK_SRC BUS_CLK - -/*! @brief Clock name used to get clock frequency. */ -typedef enum _clock_name -{ - - /* ----------------------------- System layer clock -------------------------------*/ - kCLOCK_CoreSysClk, /*!< Core/system clock */ - kCLOCK_PlatClk, /*!< Platform clock */ - kCLOCK_BusClk, /*!< Bus clock */ - kCLOCK_FlexBusClk, /*!< FlexBus clock */ - kCLOCK_FlashClk, /*!< Flash clock */ - kCLOCK_FastPeriphClk, /*!< Fast peripheral clock */ - kCLOCK_PllFllSelClk, /*!< The clock after SIM[PLLFLLSEL]. */ - - /* ---------------------------------- OSC clock -----------------------------------*/ - kCLOCK_Er32kClk, /*!< External reference 32K clock (ERCLK32K) */ - kCLOCK_Osc0ErClk, /*!< OSC0 external reference clock (OSC0ERCLK) */ - kCLOCK_Osc1ErClk, /*!< OSC1 external reference clock (OSC1ERCLK) */ - kCLOCK_Osc0ErClkUndiv, /*!< OSC0 external reference undivided clock(OSC0ERCLK_UNDIV). */ - - /* ----------------------------- MCG and MCG-Lite clock ---------------------------*/ - kCLOCK_McgFixedFreqClk, /*!< MCG fixed frequency clock (MCGFFCLK) */ - kCLOCK_McgInternalRefClk, /*!< MCG internal reference clock (MCGIRCLK) */ - kCLOCK_McgFllClk, /*!< MCGFLLCLK */ - kCLOCK_McgPll0Clk, /*!< MCGPLL0CLK */ - kCLOCK_McgPll1Clk, /*!< MCGPLL1CLK */ - kCLOCK_McgExtPllClk, /*!< EXT_PLLCLK */ - kCLOCK_McgPeriphClk, /*!< MCG peripheral clock (MCGPCLK) */ - kCLOCK_McgIrc48MClk, /*!< MCG IRC48M clock */ - - /* --------------------------------- Other clock ----------------------------------*/ - kCLOCK_LpoClk, /*!< LPO clock */ - -} clock_name_t; - -/*! @brief USB clock source definition. */ -typedef enum _clock_usb_src -{ - kCLOCK_UsbSrcPll0 = SIM_SOPT2_USBSRC(1U) | SIM_SOPT2_PLLFLLSEL(1U), /*!< Use PLL0. */ - kCLOCK_UsbSrcIrc48M = SIM_SOPT2_USBSRC(1U) | SIM_SOPT2_PLLFLLSEL(3U), /*!< Use IRC48M. */ - kCLOCK_UsbSrcExt = SIM_SOPT2_USBSRC(0U) /*!< Use USB_CLKIN. */ -} clock_usb_src_t; -/*------------------------------------------------------------------------------ - - clock_gate_t definition: - - 31 16 0 - ----------------------------------------------------------------- - | SIM_SCGC register offset | control bit offset in SCGC | - ----------------------------------------------------------------- - - For example, the SDHC clock gate is controlled by SIM_SCGC3[17], the - SIM_SCGC3 offset in SIM is 0x1030, then kCLOCK_GateSdhc0 is defined as - - kCLOCK_GateSdhc0 = (0x1030 << 16) | 17; - -------------------------------------------------------------------------------*/ - -#define CLK_GATE_REG_OFFSET_SHIFT 16U -#define CLK_GATE_REG_OFFSET_MASK 0xFFFF0000U -#define CLK_GATE_BIT_SHIFT_SHIFT 0U -#define CLK_GATE_BIT_SHIFT_MASK 0x0000FFFFU - -#define CLK_GATE_DEFINE(reg_offset, bit_shift) \ - ((((reg_offset) << CLK_GATE_REG_OFFSET_SHIFT) & CLK_GATE_REG_OFFSET_MASK) | \ - (((bit_shift) << CLK_GATE_BIT_SHIFT_SHIFT) & CLK_GATE_BIT_SHIFT_MASK)) - -#define CLK_GATE_ABSTRACT_REG_OFFSET(x) (((x)&CLK_GATE_REG_OFFSET_MASK) >> CLK_GATE_REG_OFFSET_SHIFT) -#define CLK_GATE_ABSTRACT_BITS_SHIFT(x) (((x)&CLK_GATE_BIT_SHIFT_MASK) >> CLK_GATE_BIT_SHIFT_SHIFT) - -/*! @brief Clock gate name used for CLOCK_EnableClock/CLOCK_DisableClock. */ -typedef enum _clock_ip_name -{ - kCLOCK_IpInvalid = 0U, - kCLOCK_I2c2 = CLK_GATE_DEFINE(0x1028U, 6U), - kCLOCK_Uart4 = CLK_GATE_DEFINE(0x1028U, 10U), - kCLOCK_Uart5 = CLK_GATE_DEFINE(0x1028U, 11U), - - kCLOCK_Dac0 = CLK_GATE_DEFINE(0x102CU, 12U), - kCLOCK_Dac1 = CLK_GATE_DEFINE(0x102CU, 13U), - - kCLOCK_Spi2 = CLK_GATE_DEFINE(0x1030U, 12U), - kCLOCK_Sdhc0 = CLK_GATE_DEFINE(0x1030U, 17U), - kCLOCK_Ftm3 = CLK_GATE_DEFINE(0x1030U, 25U), - kCLOCK_Adc1 = CLK_GATE_DEFINE(0x1030U, 27U), - - kCLOCK_Ewm0 = CLK_GATE_DEFINE(0x1034U, 1U), - kCLOCK_Cmt0 = CLK_GATE_DEFINE(0x1034U, 2U), - kCLOCK_I2c0 = CLK_GATE_DEFINE(0x1034U, 6U), - kCLOCK_I2c1 = CLK_GATE_DEFINE(0x1034U, 7U), - kCLOCK_Uart0 = CLK_GATE_DEFINE(0x1034U, 10U), - kCLOCK_Uart1 = CLK_GATE_DEFINE(0x1034U, 11U), - kCLOCK_Uart2 = CLK_GATE_DEFINE(0x1034U, 12U), - kCLOCK_Uart3 = CLK_GATE_DEFINE(0x1034U, 13U), - kCLOCK_Usbfs0 = CLK_GATE_DEFINE(0x1034U, 18U), - kCLOCK_Cmp0 = CLK_GATE_DEFINE(0x1034U, 19U), - kCLOCK_Cmp1 = CLK_GATE_DEFINE(0x1034U, 19U), - kCLOCK_Cmp2 = CLK_GATE_DEFINE(0x1034U, 19U), - kCLOCK_Vref0 = CLK_GATE_DEFINE(0x1034U, 20U), - - kCLOCK_Lptmr0 = CLK_GATE_DEFINE(0x1038U, 0U), - kCLOCK_PortA = CLK_GATE_DEFINE(0x1038U, 9U), - kCLOCK_PortB = CLK_GATE_DEFINE(0x1038U, 10U), - kCLOCK_PortC = CLK_GATE_DEFINE(0x1038U, 11U), - kCLOCK_PortD = CLK_GATE_DEFINE(0x1038U, 12U), - kCLOCK_PortE = CLK_GATE_DEFINE(0x1038U, 13U), - - kCLOCK_Ftf0 = CLK_GATE_DEFINE(0x103CU, 0U), - kCLOCK_Dmamux0 = CLK_GATE_DEFINE(0x103CU, 1U), - kCLOCK_Flexcan0 = CLK_GATE_DEFINE(0x103CU, 4U), - kCLOCK_Rnga0 = CLK_GATE_DEFINE(0x103CU, 9U), - kCLOCK_Spi0 = CLK_GATE_DEFINE(0x103CU, 12U), - kCLOCK_Spi1 = CLK_GATE_DEFINE(0x103CU, 13U), - kCLOCK_Sai0 = CLK_GATE_DEFINE(0x103CU, 15U), - kCLOCK_Crc0 = CLK_GATE_DEFINE(0x103CU, 18U), - kCLOCK_Usbdcd0 = CLK_GATE_DEFINE(0x103CU, 21U), - kCLOCK_Pdb0 = CLK_GATE_DEFINE(0x103CU, 22U), - kCLOCK_Pit0 = CLK_GATE_DEFINE(0x103CU, 23U), - kCLOCK_Ftm0 = CLK_GATE_DEFINE(0x103CU, 24U), - kCLOCK_Ftm1 = CLK_GATE_DEFINE(0x103CU, 25U), - kCLOCK_Ftm2 = CLK_GATE_DEFINE(0x103CU, 26U), - kCLOCK_Adc0 = CLK_GATE_DEFINE(0x103CU, 27U), - kCLOCK_Rtc0 = CLK_GATE_DEFINE(0x103CU, 29U), - - kCLOCK_Flexbus0 = CLK_GATE_DEFINE(0x1040U, 0U), - kCLOCK_Dma0 = CLK_GATE_DEFINE(0x1040U, 1U), - kCLOCK_Sysmpu0 = CLK_GATE_DEFINE(0x1040U, 2U), -} clock_ip_name_t; - -/*!@brief SIM configuration structure for clock setting. */ -typedef struct _sim_clock_config -{ - uint8_t pllFllSel; /*!< PLL/FLL/IRC48M selection. */ - uint8_t er32kSrc; /*!< ERCLK32K source selection. */ - uint32_t clkdiv1; /*!< SIM_CLKDIV1. */ -} sim_clock_config_t; - -/*! @brief OSC work mode. */ -typedef enum _osc_mode -{ - kOSC_ModeExt = 0U, /*!< Use an external clock. */ -#if (defined(MCG_C2_EREFS_MASK) && !(defined(MCG_C2_EREFS0_MASK))) - kOSC_ModeOscLowPower = MCG_C2_EREFS_MASK, /*!< Oscillator low power. */ -#else - kOSC_ModeOscLowPower = MCG_C2_EREFS0_MASK, /*!< Oscillator low power. */ -#endif - kOSC_ModeOscHighGain = 0U -#if (defined(MCG_C2_EREFS_MASK) && !(defined(MCG_C2_EREFS0_MASK))) - | - MCG_C2_EREFS_MASK -#else - | - MCG_C2_EREFS0_MASK -#endif -#if (defined(MCG_C2_HGO_MASK) && !(defined(MCG_C2_HGO0_MASK))) - | - MCG_C2_HGO_MASK, /*!< Oscillator high gain. */ -#else - | - MCG_C2_HGO0_MASK, /*!< Oscillator high gain. */ -#endif -} osc_mode_t; - -/*! @brief Oscillator capacitor load setting.*/ -enum _osc_cap_load -{ - kOSC_Cap2P = OSC_CR_SC2P_MASK, /*!< 2 pF capacitor load */ - kOSC_Cap4P = OSC_CR_SC4P_MASK, /*!< 4 pF capacitor load */ - kOSC_Cap8P = OSC_CR_SC8P_MASK, /*!< 8 pF capacitor load */ - kOSC_Cap16P = OSC_CR_SC16P_MASK /*!< 16 pF capacitor load */ -}; - -/*! @brief OSCERCLK enable mode. */ -enum _oscer_enable_mode -{ - kOSC_ErClkEnable = OSC_CR_ERCLKEN_MASK, /*!< Enable. */ - kOSC_ErClkEnableInStop = OSC_CR_EREFSTEN_MASK /*!< Enable in stop mode. */ -}; - -/*! @brief OSC configuration for OSCERCLK. */ -typedef struct _oscer_config -{ - uint8_t enableMode; /*!< OSCERCLK enable mode. OR'ed value of @ref _oscer_enable_mode. */ - -} oscer_config_t; - -/*! - * @brief OSC Initialization Configuration Structure - * - * Defines the configuration data structure to initialize the OSC. - * When porting to a new board, set the following members - * according to the board setting: - * 1. freq: The external frequency. - * 2. workMode: The OSC module mode. - */ -typedef struct _osc_config -{ - uint32_t freq; /*!< External clock frequency. */ - uint8_t capLoad; /*!< Capacitor load setting. */ - osc_mode_t workMode; /*!< OSC work mode setting. */ - oscer_config_t oscerConfig; /*!< Configuration for OSCERCLK. */ -} osc_config_t; - -/*! @brief MCG FLL reference clock source select. */ -typedef enum _mcg_fll_src -{ - kMCG_FllSrcExternal, /*!< External reference clock is selected */ - kMCG_FllSrcInternal /*!< The slow internal reference clock is selected */ -} mcg_fll_src_t; - -/*! @brief MCG internal reference clock select */ -typedef enum _mcg_irc_mode -{ - kMCG_IrcSlow, /*!< Slow internal reference clock selected */ - kMCG_IrcFast /*!< Fast internal reference clock selected */ -} mcg_irc_mode_t; - -/*! @brief MCG DCO Maximum Frequency with 32.768 kHz Reference */ -typedef enum _mcg_dmx32 -{ - kMCG_Dmx32Default, /*!< DCO has a default range of 25% */ - kMCG_Dmx32Fine /*!< DCO is fine-tuned for maximum frequency with 32.768 kHz reference */ -} mcg_dmx32_t; - -/*! @brief MCG DCO range select */ -typedef enum _mcg_drs -{ - kMCG_DrsLow, /*!< Low frequency range */ - kMCG_DrsMid, /*!< Mid frequency range */ - kMCG_DrsMidHigh, /*!< Mid-High frequency range */ - kMCG_DrsHigh /*!< High frequency range */ -} mcg_drs_t; - -/*! @brief MCG PLL reference clock select */ -typedef enum _mcg_pll_ref_src -{ - kMCG_PllRefOsc0, /*!< Selects OSC0 as PLL reference clock */ - kMCG_PllRefOsc1 /*!< Selects OSC1 as PLL reference clock */ -} mcg_pll_ref_src_t; - -/*! @brief MCGOUT clock source. */ -typedef enum _mcg_clkout_src -{ - kMCG_ClkOutSrcOut, /*!< Output of the FLL is selected (reset default) */ - kMCG_ClkOutSrcInternal, /*!< Internal reference clock is selected */ - kMCG_ClkOutSrcExternal, /*!< External reference clock is selected */ -} mcg_clkout_src_t; - -/*! @brief MCG Automatic Trim Machine Select */ -typedef enum _mcg_atm_select -{ - kMCG_AtmSel32k, /*!< 32 kHz Internal Reference Clock selected */ - kMCG_AtmSel4m /*!< 4 MHz Internal Reference Clock selected */ -} mcg_atm_select_t; - -/*! @brief MCG OSC Clock Select */ -typedef enum _mcg_oscsel -{ - kMCG_OscselOsc, /*!< Selects System Oscillator (OSCCLK) */ - kMCG_OscselRtc, /*!< Selects 32 kHz RTC Oscillator */ - kMCG_OscselIrc /*!< Selects 48 MHz IRC Oscillator */ -} mcg_oscsel_t; - -/*! @brief MCG PLLCS select */ -typedef enum _mcg_pll_clk_select -{ - kMCG_PllClkSelPll0, /*!< PLL0 output clock is selected */ - kMCG_PllClkSelPll1 /* PLL1 output clock is selected */ -} mcg_pll_clk_select_t; - -/*! @brief MCG clock monitor mode. */ -typedef enum _mcg_monitor_mode -{ - kMCG_MonitorNone, /*!< Clock monitor is disabled. */ - kMCG_MonitorInt, /*!< Trigger interrupt when clock lost. */ - kMCG_MonitorReset /*!< System reset when clock lost. */ -} mcg_monitor_mode_t; - -/*! @brief MCG status. */ -enum _mcg_status -{ - kStatus_MCG_ModeUnreachable = MAKE_STATUS(kStatusGroup_MCG, 0), /*!< Can't switch to target mode. */ - kStatus_MCG_ModeInvalid = MAKE_STATUS(kStatusGroup_MCG, 1), /*!< Current mode invalid for the specific - function. */ - kStatus_MCG_AtmBusClockInvalid = MAKE_STATUS(kStatusGroup_MCG, 2), /*!< Invalid bus clock for ATM. */ - kStatus_MCG_AtmDesiredFreqInvalid = MAKE_STATUS(kStatusGroup_MCG, 3), /*!< Invalid desired frequency for ATM. */ - kStatus_MCG_AtmIrcUsed = MAKE_STATUS(kStatusGroup_MCG, 4), /*!< IRC is used when using ATM. */ - kStatus_MCG_AtmHardwareFail = MAKE_STATUS(kStatusGroup_MCG, 5), /*!< Hardware fail occurs during ATM. */ - kStatus_MCG_SourceUsed = MAKE_STATUS(kStatusGroup_MCG, 6) /*!< Can't change the clock source because - it is in use. */ -}; - -/*! @brief MCG status flags. */ -enum _mcg_status_flags_t -{ - kMCG_Osc0LostFlag = (1U << 0U), /*!< OSC0 lost. */ - kMCG_Osc0InitFlag = (1U << 1U), /*!< OSC0 crystal initialized. */ - kMCG_RtcOscLostFlag = (1U << 4U), /*!< RTC OSC lost. */ - kMCG_Pll0LostFlag = (1U << 5U), /*!< PLL0 lost. */ - kMCG_Pll0LockFlag = (1U << 6U), /*!< PLL0 locked. */ -}; - -/*! @brief MCG internal reference clock (MCGIRCLK) enable mode definition. */ -enum _mcg_irclk_enable_mode -{ - kMCG_IrclkEnable = MCG_C1_IRCLKEN_MASK, /*!< MCGIRCLK enable. */ - kMCG_IrclkEnableInStop = MCG_C1_IREFSTEN_MASK /*!< MCGIRCLK enable in stop mode. */ -}; - -/*! @brief MCG PLL clock enable mode definition. */ -enum _mcg_pll_enable_mode -{ - kMCG_PllEnableIndependent = MCG_C5_PLLCLKEN0_MASK, /*!< MCGPLLCLK enable independent of the - MCG clock mode. Generally, the PLL - is disabled in FLL modes - (FEI/FBI/FEE/FBE). Setting the PLL clock - enable independent, enables the - PLL in the FLL modes. */ - kMCG_PllEnableInStop = MCG_C5_PLLSTEN0_MASK /*!< MCGPLLCLK enable in STOP mode. */ -}; - -/*! @brief MCG mode definitions */ -typedef enum _mcg_mode -{ - kMCG_ModeFEI = 0U, /*!< FEI - FLL Engaged Internal */ - kMCG_ModeFBI, /*!< FBI - FLL Bypassed Internal */ - kMCG_ModeBLPI, /*!< BLPI - Bypassed Low Power Internal */ - kMCG_ModeFEE, /*!< FEE - FLL Engaged External */ - kMCG_ModeFBE, /*!< FBE - FLL Bypassed External */ - kMCG_ModeBLPE, /*!< BLPE - Bypassed Low Power External */ - kMCG_ModePBE, /*!< PBE - PLL Bypassed External */ - kMCG_ModePEE, /*!< PEE - PLL Engaged External */ - kMCG_ModeError /*!< Unknown mode */ -} mcg_mode_t; - -/*! @brief MCG PLL configuration. */ -typedef struct _mcg_pll_config -{ - uint8_t enableMode; /*!< Enable mode. OR'ed value of @ref _mcg_pll_enable_mode. */ - uint8_t prdiv; /*!< Reference divider PRDIV. */ - uint8_t vdiv; /*!< VCO divider VDIV. */ -} mcg_pll_config_t; - -/*! @brief MCG mode change configuration structure - * - * When porting to a new board, set the following members - * according to the board setting: - * 1. frdiv: If the FLL uses the external reference clock, set this - * value to ensure that the external reference clock divided by frdiv is - * in the 31.25 kHz to 39.0625 kHz range. - * 2. The PLL reference clock divider PRDIV: PLL reference clock frequency after - * PRDIV should be in the FSL_FEATURE_MCG_PLL_REF_MIN to - * FSL_FEATURE_MCG_PLL_REF_MAX range. - */ -typedef struct _mcg_config -{ - mcg_mode_t mcgMode; /*!< MCG mode. */ - - /* ----------------------- MCGIRCCLK settings ------------------------ */ - uint8_t irclkEnableMode; /*!< MCGIRCLK enable mode. */ - mcg_irc_mode_t ircs; /*!< Source, MCG_C2[IRCS]. */ - uint8_t fcrdiv; /*!< Divider, MCG_SC[FCRDIV]. */ - - /* ------------------------ MCG FLL settings ------------------------- */ - uint8_t frdiv; /*!< Divider MCG_C1[FRDIV]. */ - mcg_drs_t drs; /*!< DCO range MCG_C4[DRST_DRS]. */ - mcg_dmx32_t dmx32; /*!< MCG_C4[DMX32]. */ - mcg_oscsel_t oscsel; /*!< OSC select MCG_C7[OSCSEL]. */ - - /* ------------------------ MCG PLL settings ------------------------- */ - mcg_pll_config_t pll0Config; /*!< MCGPLL0CLK configuration. */ - -} mcg_config_t; - -/******************************************************************************* - * API - ******************************************************************************/ - -#if defined(__cplusplus) -extern "C" { -#endif /* __cplusplus */ - -/*! - * @brief Enable the clock for specific IP. - * - * @param name Which clock to enable, see \ref clock_ip_name_t. - */ -static inline void CLOCK_EnableClock(clock_ip_name_t name) -{ - uint32_t regAddr = SIM_BASE + CLK_GATE_ABSTRACT_REG_OFFSET((uint32_t)name); - (*(volatile uint32_t *)regAddr) |= (1U << CLK_GATE_ABSTRACT_BITS_SHIFT((uint32_t)name)); -} - -/*! - * @brief Disable the clock for specific IP. - * - * @param name Which clock to disable, see \ref clock_ip_name_t. - */ -static inline void CLOCK_DisableClock(clock_ip_name_t name) -{ - uint32_t regAddr = SIM_BASE + CLK_GATE_ABSTRACT_REG_OFFSET((uint32_t)name); - (*(volatile uint32_t *)regAddr) &= ~(1U << CLK_GATE_ABSTRACT_BITS_SHIFT((uint32_t)name)); -} - -/*! - * @brief Set ERCLK32K source. - * - * @param src The value to set ERCLK32K clock source. - */ -static inline void CLOCK_SetEr32kClock(uint32_t src) -{ - SIM->SOPT1 = ((SIM->SOPT1 & ~SIM_SOPT1_OSC32KSEL_MASK) | SIM_SOPT1_OSC32KSEL(src)); -} - -/*! - * @brief Set debug trace clock source. - * - * @param src The value to set debug trace clock source. - */ -static inline void CLOCK_SetTraceClock(uint32_t src) -{ - SIM->SOPT2 = ((SIM->SOPT2 & ~SIM_SOPT2_TRACECLKSEL_MASK) | SIM_SOPT2_TRACECLKSEL(src)); -} - -/*! - * @brief Set SDHC0 clock source. - * - * @param src The value to set SDHC0 clock source. - */ -static inline void CLOCK_SetSdhc0Clock(uint32_t src) -{ - SIM->SOPT2 = ((SIM->SOPT2 & ~SIM_SOPT2_SDHCSRC_MASK) | SIM_SOPT2_SDHCSRC(src)); -} - -/*! - * @brief Set PLLFLLSEL clock source. - * - * @param src The value to set PLLFLLSEL clock source. - */ -static inline void CLOCK_SetPllFllSelClock(uint32_t src) -{ - SIM->SOPT2 = ((SIM->SOPT2 & ~SIM_SOPT2_PLLFLLSEL_MASK) | SIM_SOPT2_PLLFLLSEL(src)); -} - -/*! - * @brief Set CLKOUT source. - * - * @param src The value to set CLKOUT source. - */ -static inline void CLOCK_SetClkOutClock(uint32_t src) -{ - SIM->SOPT2 = ((SIM->SOPT2 & ~SIM_SOPT2_CLKOUTSEL_MASK) | SIM_SOPT2_CLKOUTSEL(src)); -} - -/*! - * @brief Set RTC_CLKOUT source. - * - * @param src The value to set RTC_CLKOUT source. - */ -static inline void CLOCK_SetRtcClkOutClock(uint32_t src) -{ - SIM->SOPT2 = ((SIM->SOPT2 & ~SIM_SOPT2_RTCCLKOUTSEL_MASK) | SIM_SOPT2_RTCCLKOUTSEL(src)); -} - -/*! @brief Enable USB FS clock. - * - * @param src USB FS clock source. - * @param freq The frequency specified by src. - * @retval true The clock is set successfully. - * @retval false The clock source is invalid to get proper USB FS clock. - */ -bool CLOCK_EnableUsbfs0Clock(clock_usb_src_t src, uint32_t freq); - -/*! @brief Disable USB FS clock. - * - * Disable USB FS clock. - */ -static inline void CLOCK_DisableUsbfs0Clock(void) -{ - CLOCK_DisableClock(kCLOCK_Usbfs0); -} - -/*! - * @brief System clock divider - * - * Set the SIM_CLKDIV1[OUTDIV1], SIM_CLKDIV1[OUTDIV2], SIM_CLKDIV1[OUTDIV3], SIM_CLKDIV1[OUTDIV4]. - * - * @param outdiv1 Clock 1 output divider value. - * - * @param outdiv2 Clock 2 output divider value. - * - * @param outdiv3 Clock 3 output divider value. - * - * @param outdiv4 Clock 4 output divider value. - */ -static inline void CLOCK_SetOutDiv(uint32_t outdiv1, uint32_t outdiv2, uint32_t outdiv3, uint32_t outdiv4) -{ - SIM->CLKDIV1 = SIM_CLKDIV1_OUTDIV1(outdiv1) | SIM_CLKDIV1_OUTDIV2(outdiv2) | SIM_CLKDIV1_OUTDIV3(outdiv3) | - SIM_CLKDIV1_OUTDIV4(outdiv4); -} - -/*! - * @brief Gets the clock frequency for a specific clock name. - * - * This function checks the current clock configurations and then calculates - * the clock frequency for a specific clock name defined in clock_name_t. - * The MCG must be properly configured before using this function. - * - * @param clockName Clock names defined in clock_name_t - * @return Clock frequency value in Hertz - */ -uint32_t CLOCK_GetFreq(clock_name_t clockName); - -/*! - * @brief Get the core clock or system clock frequency. - * - * @return Clock frequency in Hz. - */ -uint32_t CLOCK_GetCoreSysClkFreq(void); - -/*! - * @brief Get the bus clock frequency. - * - * @return Clock frequency in Hz. - */ -uint32_t CLOCK_GetBusClkFreq(void); - -/*! - * @brief Get the flexbus clock frequency. - * - * @return Clock frequency in Hz. - */ -uint32_t CLOCK_GetFlexBusClkFreq(void); - -/*! - * @brief Get the flash clock frequency. - * - * @return Clock frequency in Hz. - */ -uint32_t CLOCK_GetFlashClkFreq(void); - -/*! - * @brief Get the output clock frequency selected by SIM[PLLFLLSEL]. - * - * @return Clock frequency in Hz. - */ -uint32_t CLOCK_GetPllFllSelClkFreq(void); - -/*! - * @brief Get the external reference 32K clock frequency (ERCLK32K). - * - * @return Clock frequency in Hz. - */ -uint32_t CLOCK_GetEr32kClkFreq(void); - -/*! - * @brief Get the OSC0 external reference clock frequency (OSC0ERCLK). - * - * @return Clock frequency in Hz. - */ -uint32_t CLOCK_GetOsc0ErClkFreq(void); - -/*! - * @brief Set the clock configure in SIM module. - * - * This function sets system layer clock settings in SIM module. - * - * @param config Pointer to the configure structure. - */ -void CLOCK_SetSimConfig(sim_clock_config_t const *config); - -/*! - * @brief Set the system clock dividers in SIM to safe value. - * - * The system level clocks (core clock, bus clock, flexbus clock and flash clock) - * must be in allowed ranges. During MCG clock mode switch, the MCG output clock - * changes then the system level clocks may be out of range. This function could - * be used before MCG mode change, to make sure system level clocks are in allowed - * range. - * - * @param config Pointer to the configure structure. - */ -static inline void CLOCK_SetSimSafeDivs(void) -{ - SIM->CLKDIV1 = 0x01040000U; -} - -/*! @name MCG frequency functions. */ -/*@{*/ - -/*! - * @brief Gets the MCG output clock (MCGOUTCLK) frequency. - * - * This function gets the MCG output clock frequency in Hz based on the current MCG - * register value. - * - * @return The frequency of MCGOUTCLK. - */ -uint32_t CLOCK_GetOutClkFreq(void); - -/*! - * @brief Gets the MCG FLL clock (MCGFLLCLK) frequency. - * - * This function gets the MCG FLL clock frequency in Hz based on the current MCG - * register value. The FLL is enabled in FEI/FBI/FEE/FBE mode and - * disabled in low power state in other modes. - * - * @return The frequency of MCGFLLCLK. - */ -uint32_t CLOCK_GetFllFreq(void); - -/*! - * @brief Gets the MCG internal reference clock (MCGIRCLK) frequency. - * - * This function gets the MCG internal reference clock frequency in Hz based - * on the current MCG register value. - * - * @return The frequency of MCGIRCLK. - */ -uint32_t CLOCK_GetInternalRefClkFreq(void); - -/*! - * @brief Gets the MCG fixed frequency clock (MCGFFCLK) frequency. - * - * This function gets the MCG fixed frequency clock frequency in Hz based - * on the current MCG register value. - * - * @return The frequency of MCGFFCLK. - */ -uint32_t CLOCK_GetFixedFreqClkFreq(void); - -/*! - * @brief Gets the MCG PLL0 clock (MCGPLL0CLK) frequency. - * - * This function gets the MCG PLL0 clock frequency in Hz based on the current MCG - * register value. - * - * @return The frequency of MCGPLL0CLK. - */ -uint32_t CLOCK_GetPll0Freq(void); - -/*@}*/ - -/*! @name MCG clock configuration. */ -/*@{*/ - -/*! - * @brief Enables or disables the MCG low power. - * - * Enabling the MCG low power disables the PLL and FLL in bypass modes. In other words, - * in FBE and PBE modes, enabling low power sets the MCG to BLPE mode. In FBI and - * PBI modes, enabling low power sets the MCG to BLPI mode. - * When disabling the MCG low power, the PLL or FLL are enabled based on MCG settings. - * - * @param enable True to enable MCG low power, false to disable MCG low power. - */ -static inline void CLOCK_SetLowPowerEnable(bool enable) -{ - if (enable) - { - MCG->C2 |= MCG_C2_LP_MASK; - } - else - { - MCG->C2 &= ~MCG_C2_LP_MASK; - } -} - -/*! - * @brief Configures the Internal Reference clock (MCGIRCLK). - * - * This function sets the \c MCGIRCLK base on parameters. It also selects the IRC - * source. If the fast IRC is used, this function sets the fast IRC divider. - * This function also sets whether the \c MCGIRCLK is enabled in stop mode. - * Calling this function in FBI/PBI/BLPI modes may change the system clock. As a result, - * using the function in these modes it is not allowed. - * - * @param enableMode MCGIRCLK enable mode, OR'ed value of @ref _mcg_irclk_enable_mode. - * @param ircs MCGIRCLK clock source, choose fast or slow. - * @param fcrdiv Fast IRC divider setting (\c FCRDIV). - * @retval kStatus_MCG_SourceUsed Because the internall reference clock is used as a clock source, - * the confuration should not be changed. Otherwise, a glitch occurs. - * @retval kStatus_Success MCGIRCLK configuration finished successfully. - */ -status_t CLOCK_SetInternalRefClkConfig(uint8_t enableMode, mcg_irc_mode_t ircs, uint8_t fcrdiv); - -/*! - * @brief Selects the MCG external reference clock. - * - * Selects the MCG external reference clock source, changes the MCG_C7[OSCSEL], - * and waits for the clock source to be stable. Because the external reference - * clock should not be changed in FEE/FBE/BLPE/PBE/PEE modes, do not call this function in these modes. - * - * @param oscsel MCG external reference clock source, MCG_C7[OSCSEL]. - * @retval kStatus_MCG_SourceUsed Because the external reference clock is used as a clock source, - * the confuration should not be changed. Otherwise, a glitch occurs. - * @retval kStatus_Success External reference clock set successfully. - */ -status_t CLOCK_SetExternalRefClkConfig(mcg_oscsel_t oscsel); - -/*! - * @brief Set the FLL external reference clock divider value. - * - * Sets the FLL external reference clock divider value, the register MCG_C1[FRDIV]. - * - * @param frdiv The FLL external reference clock divider value, MCG_C1[FRDIV]. - */ -static inline void CLOCK_SetFllExtRefDiv(uint8_t frdiv) -{ - MCG->C1 = (MCG->C1 & ~MCG_C1_FRDIV_MASK) | MCG_C1_FRDIV(frdiv); -} - -/*! - * @brief Enables the PLL0 in FLL mode. - * - * This function sets us the PLL0 in FLL mode and reconfigures - * the PLL0. Ensure that the PLL reference - * clock is enabled before calling this function and that the PLL0 is not used as a clock source. - * The function CLOCK_CalcPllDiv gets the correct PLL - * divider values. - * - * @param config Pointer to the configuration structure. - */ -void CLOCK_EnablePll0(mcg_pll_config_t const *config); - -/*! - * @brief Disables the PLL0 in FLL mode. - * - * This function disables the PLL0 in FLL mode. It should be used together with the - * @ref CLOCK_EnablePll0. - */ -static inline void CLOCK_DisablePll0(void) -{ - MCG->C5 &= ~(MCG_C5_PLLCLKEN0_MASK | MCG_C5_PLLSTEN0_MASK); -} - -/*! - * @brief Calculates the PLL divider setting for a desired output frequency. - * - * This function calculates the correct reference clock divider (\c PRDIV) and - * VCO divider (\c VDIV) to generate a desired PLL output frequency. It returns the - * closest frequency match with the corresponding \c PRDIV/VDIV - * returned from parameters. If a desired frequency is not valid, this function - * returns 0. - * - * @param refFreq PLL reference clock frequency. - * @param desireFreq Desired PLL output frequency. - * @param prdiv PRDIV value to generate desired PLL frequency. - * @param vdiv VDIV value to generate desired PLL frequency. - * @return Closest frequency match that the PLL was able generate. - */ -uint32_t CLOCK_CalcPllDiv(uint32_t refFreq, uint32_t desireFreq, uint8_t *prdiv, uint8_t *vdiv); - -/*@}*/ - -/*! @name MCG clock lock monitor functions. */ -/*@{*/ - -/*! - * @brief Sets the OSC0 clock monitor mode. - * - * This function sets the OSC0 clock monitor mode. See @ref mcg_monitor_mode_t for details. - * - * @param mode Monitor mode to set. - */ -void CLOCK_SetOsc0MonitorMode(mcg_monitor_mode_t mode); - -/*! - * @brief Sets the RTC OSC clock monitor mode. - * - * This function sets the RTC OSC clock monitor mode. See @ref mcg_monitor_mode_t for details. - * - * @param mode Monitor mode to set. - */ -void CLOCK_SetRtcOscMonitorMode(mcg_monitor_mode_t mode); - -/*! - * @brief Sets the PLL0 clock monitor mode. - * - * This function sets the PLL0 clock monitor mode. See @ref mcg_monitor_mode_t for details. - * - * @param mode Monitor mode to set. - */ -void CLOCK_SetPll0MonitorMode(mcg_monitor_mode_t mode); - -/*! - * @brief Gets the MCG status flags. - * - * This function gets the MCG clock status flags. All status flags are - * returned as a logical OR of the enumeration @ref _mcg_status_flags_t. To - * check a specific flag, compare the return value with the flag. - * - * Example: - * @code - // To check the clock lost lock status of OSC0 and PLL0. - uint32_t mcgFlags; - - mcgFlags = CLOCK_GetStatusFlags(); - - if (mcgFlags & kMCG_Osc0LostFlag) - { - // OSC0 clock lock lost. Do something. - } - if (mcgFlags & kMCG_Pll0LostFlag) - { - // PLL0 clock lock lost. Do something. - } - @endcode - * - * @return Logical OR value of the @ref _mcg_status_flags_t. - */ -uint32_t CLOCK_GetStatusFlags(void); - -/*! - * @brief Clears the MCG status flags. - * - * This function clears the MCG clock lock lost status. The parameter is a logical - * OR value of the flags to clear. See @ref _mcg_status_flags_t. - * - * Example: - * @code - // To clear the clock lost lock status flags of OSC0 and PLL0. - - CLOCK_ClearStatusFlags(kMCG_Osc0LostFlag | kMCG_Pll0LostFlag); - @endcode - * - * @param mask The status flags to clear. This is a logical OR of members of the - * enumeration @ref _mcg_status_flags_t. - */ -void CLOCK_ClearStatusFlags(uint32_t mask); - -/*@}*/ - -/*! - * @name OSC configuration - * @{ - */ - -/*! - * @brief Configures the OSC external reference clock (OSCERCLK). - * - * This function configures the OSC external reference clock (OSCERCLK). - * This is an example to enable the OSCERCLK in normal and stop modes and also set - * the output divider to 1: - * - @code - oscer_config_t config = - { - .enableMode = kOSC_ErClkEnable | kOSC_ErClkEnableInStop, - .erclkDiv = 1U, - }; - - OSC_SetExtRefClkConfig(OSC, &config); - @endcode - * - * @param base OSC peripheral address. - * @param config Pointer to the configuration structure. - */ -static inline void OSC_SetExtRefClkConfig(OSC_Type *base, oscer_config_t const *config) -{ - uint8_t reg = base->CR; - - reg &= ~(OSC_CR_ERCLKEN_MASK | OSC_CR_EREFSTEN_MASK); - reg |= config->enableMode; - - base->CR = reg; -} - -/*! - * @brief Sets the capacitor load configuration for the oscillator. - * - * This function sets the specified capacitors configuration for the oscillator. - * This should be done in the early system level initialization function call - * based on the system configuration. - * - * @param base OSC peripheral address. - * @param capLoad OR'ed value for the capacitor load option, see \ref _osc_cap_load. - * - * Example: - @code - // To enable only 2 pF and 8 pF capacitor load, please use like this. - OSC_SetCapLoad(OSC, kOSC_Cap2P | kOSC_Cap8P); - @endcode - */ -static inline void OSC_SetCapLoad(OSC_Type *base, uint8_t capLoad) -{ - uint8_t reg = base->CR; - - reg &= ~(OSC_CR_SC2P_MASK | OSC_CR_SC4P_MASK | OSC_CR_SC8P_MASK | OSC_CR_SC16P_MASK); - reg |= capLoad; - - base->CR = reg; -} - -/*! - * @brief Initializes the OSC0. - * - * This function initializes the OSC0 according to the board configuration. - * - * @param config Pointer to the OSC0 configuration structure. - */ -void CLOCK_InitOsc0(osc_config_t const *config); - -/*! - * @brief Deinitializes the OSC0. - * - * This function deinitializes the OSC0. - */ -void CLOCK_DeinitOsc0(void); - -/* @} */ - -/*! - * @name External clock frequency - * @{ - */ - -/*! - * @brief Sets the XTAL0 frequency based on board settings. - * - * @param freq The XTAL0/EXTAL0 input clock frequency in Hz. - */ -static inline void CLOCK_SetXtal0Freq(uint32_t freq) -{ - g_xtal0Freq = freq; -} - -/*! - * @brief Sets the XTAL32/RTC_CLKIN frequency based on board settings. - * - * @param freq The XTAL32/EXTAL32/RTC_CLKIN input clock frequency in Hz. - */ -static inline void CLOCK_SetXtal32Freq(uint32_t freq) -{ - g_xtal32Freq = freq; -} -/* @} */ - -/*! - * @name MCG auto-trim machine. - * @{ - */ - -/*! - * @brief Auto trims the internal reference clock. - * - * This function trims the internal reference clock by using the external clock. If - * successful, it returns the kStatus_Success and the frequency after - * trimming is received in the parameter @p actualFreq. If an error occurs, - * the error code is returned. - * - * @param extFreq External clock frequency, which should be a bus clock. - * @param desireFreq Frequency to trim to. - * @param actualFreq Actual frequency after trimming. - * @param atms Trim fast or slow internal reference clock. - * @retval kStatus_Success ATM success. - * @retval kStatus_MCG_AtmBusClockInvalid The bus clock is not in allowed range for the ATM. - * @retval kStatus_MCG_AtmDesiredFreqInvalid MCGIRCLK could not be trimmed to the desired frequency. - * @retval kStatus_MCG_AtmIrcUsed Could not trim because MCGIRCLK is used as a bus clock source. - * @retval kStatus_MCG_AtmHardwareFail Hardware fails while trimming. - */ -status_t CLOCK_TrimInternalRefClk(uint32_t extFreq, uint32_t desireFreq, uint32_t *actualFreq, mcg_atm_select_t atms); -/* @} */ - -/*! @name MCG mode functions. */ -/*@{*/ - -/*! - * @brief Gets the current MCG mode. - * - * This function checks the MCG registers and determines the current MCG mode. - * - * @return Current MCG mode or error code; See @ref mcg_mode_t. - */ -mcg_mode_t CLOCK_GetMode(void); - -/*! - * @brief Sets the MCG to FEI mode. - * - * This function sets the MCG to FEI mode. If setting to FEI mode fails - * from the current mode, this function returns an error. - * - * @param dmx32 DMX32 in FEI mode. - * @param drs The DCO range selection. - * @param fllStableDelay Delay function to ensure that the FLL is stable. Passing - * NULL does not cause a delay. - * @retval kStatus_MCG_ModeUnreachable Could not switch to the target mode. - * @retval kStatus_Success Switched to the target mode successfully. - * @note If @p dmx32 is set to kMCG_Dmx32Fine, the slow IRC must not be trimmed - * to a frequency above 32768 Hz. - */ -status_t CLOCK_SetFeiMode(mcg_dmx32_t dmx32, mcg_drs_t drs, void (*fllStableDelay)(void)); - -/*! - * @brief Sets the MCG to FEE mode. - * - * This function sets the MCG to FEE mode. If setting to FEE mode fails - * from the current mode, this function returns an error. - * - * @param frdiv FLL reference clock divider setting, FRDIV. - * @param dmx32 DMX32 in FEE mode. - * @param drs The DCO range selection. - * @param fllStableDelay Delay function to make sure FLL is stable. Passing - * NULL does not cause a delay. - * - * @retval kStatus_MCG_ModeUnreachable Could not switch to the target mode. - * @retval kStatus_Success Switched to the target mode successfully. - */ -status_t CLOCK_SetFeeMode(uint8_t frdiv, mcg_dmx32_t dmx32, mcg_drs_t drs, void (*fllStableDelay)(void)); - -/*! - * @brief Sets the MCG to FBI mode. - * - * This function sets the MCG to FBI mode. If setting to FBI mode fails - * from the current mode, this function returns an error. - * - * @param dmx32 DMX32 in FBI mode. - * @param drs The DCO range selection. - * @param fllStableDelay Delay function to make sure FLL is stable. If the FLL - * is not used in FBI mode, this parameter can be NULL. Passing - * NULL does not cause a delay. - * @retval kStatus_MCG_ModeUnreachable Could not switch to the target mode. - * @retval kStatus_Success Switched to the target mode successfully. - * @note If @p dmx32 is set to kMCG_Dmx32Fine, the slow IRC must not be trimmed - * to frequency above 32768 Hz. - */ -status_t CLOCK_SetFbiMode(mcg_dmx32_t dmx32, mcg_drs_t drs, void (*fllStableDelay)(void)); - -/*! - * @brief Sets the MCG to FBE mode. - * - * This function sets the MCG to FBE mode. If setting to FBE mode fails - * from the current mode, this function returns an error. - * - * @param frdiv FLL reference clock divider setting, FRDIV. - * @param dmx32 DMX32 in FBE mode. - * @param drs The DCO range selection. - * @param fllStableDelay Delay function to make sure FLL is stable. If the FLL - * is not used in FBE mode, this parameter can be NULL. Passing NULL - * does not cause a delay. - * @retval kStatus_MCG_ModeUnreachable Could not switch to the target mode. - * @retval kStatus_Success Switched to the target mode successfully. - */ -status_t CLOCK_SetFbeMode(uint8_t frdiv, mcg_dmx32_t dmx32, mcg_drs_t drs, void (*fllStableDelay)(void)); - -/*! - * @brief Sets the MCG to BLPI mode. - * - * This function sets the MCG to BLPI mode. If setting to BLPI mode fails - * from the current mode, this function returns an error. - * - * @retval kStatus_MCG_ModeUnreachable Could not switch to the target mode. - * @retval kStatus_Success Switched to the target mode successfully. - */ -status_t CLOCK_SetBlpiMode(void); - -/*! - * @brief Sets the MCG to BLPE mode. - * - * This function sets the MCG to BLPE mode. If setting to BLPE mode fails - * from the current mode, this function returns an error. - * - * @retval kStatus_MCG_ModeUnreachable Could not switch to the target mode. - * @retval kStatus_Success Switched to the target mode successfully. - */ -status_t CLOCK_SetBlpeMode(void); - -/*! - * @brief Sets the MCG to PBE mode. - * - * This function sets the MCG to PBE mode. If setting to PBE mode fails - * from the current mode, this function returns an error. - * - * @param pllcs The PLL selection, PLLCS. - * @param config Pointer to the PLL configuration. - * @retval kStatus_MCG_ModeUnreachable Could not switch to the target mode. - * @retval kStatus_Success Switched to the target mode successfully. - * - * @note - * 1. The parameter \c pllcs selects the PLL. For platforms with - * only one PLL, the parameter pllcs is kept for interface compatibility. - * 2. The parameter \c config is the PLL configuration structure. On some - * platforms, it is possible to choose the external PLL directly, which renders the - * configuration structure not necessary. In this case, pass in NULL. - * For example: CLOCK_SetPbeMode(kMCG_OscselOsc, kMCG_PllClkSelExtPll, NULL); - */ -status_t CLOCK_SetPbeMode(mcg_pll_clk_select_t pllcs, mcg_pll_config_t const *config); - -/*! - * @brief Sets the MCG to PEE mode. - * - * This function sets the MCG to PEE mode. - * - * @retval kStatus_MCG_ModeUnreachable Could not switch to the target mode. - * @retval kStatus_Success Switched to the target mode successfully. - * - * @note This function only changes the CLKS to use the PLL/FLL output. If the - * PRDIV/VDIV are different than in the PBE mode, set them up - * in PBE mode and wait. When the clock is stable, switch to PEE mode. - */ -status_t CLOCK_SetPeeMode(void); - -/*! - * @brief Switches the MCG to FBE mode from the external mode. - * - * This function switches the MCG from external modes (PEE/PBE/BLPE/FEE) to the FBE mode quickly. - * The external clock is used as the system clock souce and PLL is disabled. However, - * the FLL settings are not configured. This is a lite function with a small code size, which is useful - * during the mode switch. For example, to switch from PEE mode to FEI mode: - * - * @code - * CLOCK_ExternalModeToFbeModeQuick(); - * CLOCK_SetFeiMode(...); - * @endcode - * - * @retval kStatus_Success Switched successfully. - * @retval kStatus_MCG_ModeInvalid If the current mode is not an external mode, do not call this function. - */ -status_t CLOCK_ExternalModeToFbeModeQuick(void); - -/*! - * @brief Switches the MCG to FBI mode from internal modes. - * - * This function switches the MCG from internal modes (PEI/PBI/BLPI/FEI) to the FBI mode quickly. - * The MCGIRCLK is used as the system clock souce and PLL is disabled. However, - * FLL settings are not configured. This is a lite function with a small code size, which is useful - * during the mode switch. For example, to switch from PEI mode to FEE mode: - * - * @code - * CLOCK_InternalModeToFbiModeQuick(); - * CLOCK_SetFeeMode(...); - * @endcode - * - * @retval kStatus_Success Switched successfully. - * @retval kStatus_MCG_ModeInvalid If the current mode is not an internal mode, do not call this function. - */ -status_t CLOCK_InternalModeToFbiModeQuick(void); - -/*! - * @brief Sets the MCG to FEI mode during system boot up. - * - * This function sets the MCG to FEI mode from the reset mode. It can also be used to - * set up MCG during system boot up. - * - * @param dmx32 DMX32 in FEI mode. - * @param drs The DCO range selection. - * @param fllStableDelay Delay function to ensure that the FLL is stable. - * - * @retval kStatus_MCG_ModeUnreachable Could not switch to the target mode. - * @retval kStatus_Success Switched to the target mode successfully. - * @note If @p dmx32 is set to kMCG_Dmx32Fine, the slow IRC must not be trimmed - * to frequency above 32768 Hz. - */ -status_t CLOCK_BootToFeiMode(mcg_dmx32_t dmx32, mcg_drs_t drs, void (*fllStableDelay)(void)); - -/*! - * @brief Sets the MCG to FEE mode during system bootup. - * - * This function sets MCG to FEE mode from the reset mode. It can also be used to - * set up the MCG during system boot up. - * - * @param oscsel OSC clock select, OSCSEL. - * @param frdiv FLL reference clock divider setting, FRDIV. - * @param dmx32 DMX32 in FEE mode. - * @param drs The DCO range selection. - * @param fllStableDelay Delay function to ensure that the FLL is stable. - * - * @retval kStatus_MCG_ModeUnreachable Could not switch to the target mode. - * @retval kStatus_Success Switched to the target mode successfully. - */ -status_t CLOCK_BootToFeeMode( - mcg_oscsel_t oscsel, uint8_t frdiv, mcg_dmx32_t dmx32, mcg_drs_t drs, void (*fllStableDelay)(void)); - -/*! - * @brief Sets the MCG to BLPI mode during system boot up. - * - * This function sets the MCG to BLPI mode from the reset mode. It can also be used to - * set up the MCG during sytem boot up. - * - * @param fcrdiv Fast IRC divider, FCRDIV. - * @param ircs The internal reference clock to select, IRCS. - * @param ircEnableMode The MCGIRCLK enable mode, OR'ed value of @ref _mcg_irclk_enable_mode. - * - * @retval kStatus_MCG_SourceUsed Could not change MCGIRCLK setting. - * @retval kStatus_Success Switched to the target mode successfully. - */ -status_t CLOCK_BootToBlpiMode(uint8_t fcrdiv, mcg_irc_mode_t ircs, uint8_t ircEnableMode); - -/*! - * @brief Sets the MCG to BLPE mode during sytem boot up. - * - * This function sets the MCG to BLPE mode from the reset mode. It can also be used to - * set up the MCG during sytem boot up. - * - * @param oscsel OSC clock select, MCG_C7[OSCSEL]. - * - * @retval kStatus_MCG_ModeUnreachable Could not switch to the target mode. - * @retval kStatus_Success Switched to the target mode successfully. - */ -status_t CLOCK_BootToBlpeMode(mcg_oscsel_t oscsel); - -/*! - * @brief Sets the MCG to PEE mode during system boot up. - * - * This function sets the MCG to PEE mode from reset mode. It can also be used to - * set up the MCG during system boot up. - * - * @param oscsel OSC clock select, MCG_C7[OSCSEL]. - * @param pllcs The PLL selection, PLLCS. - * @param config Pointer to the PLL configuration. - * - * @retval kStatus_MCG_ModeUnreachable Could not switch to the target mode. - * @retval kStatus_Success Switched to the target mode successfully. - */ -status_t CLOCK_BootToPeeMode(mcg_oscsel_t oscsel, mcg_pll_clk_select_t pllcs, mcg_pll_config_t const *config); - -/*! - * @brief Sets the MCG to a target mode. - * - * This function sets MCG to a target mode defined by the configuration - * structure. If switching to the target mode fails, this function - * chooses the correct path. - * - * @param config Pointer to the target MCG mode configuration structure. - * @return Return kStatus_Success if switched successfully; Otherwise, it returns an error code #_mcg_status. - * - * @note If the external clock is used in the target mode, ensure that it is - * enabled. For example, if the OSC0 is used, set up OSC0 correctly before calling this - * function. - */ -status_t CLOCK_SetMcgConfig(mcg_config_t const *config); - -/*@}*/ - -#if defined(__cplusplus) -} -#endif /* __cplusplus */ - -/*! @} */ - -#endif /* _FSL_CLOCK_H_ */ diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_cmp.c b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_cmp.c deleted file mode 100644 index 6a5f15a75b1..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_cmp.c +++ /dev/null @@ -1,285 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "fsl_cmp.h" - -/******************************************************************************* - * Prototypes - ******************************************************************************/ -/*! - * @brief Get instance number for CMP module. - * - * @param base CMP peripheral base address - */ -static uint32_t CMP_GetInstance(CMP_Type *base); - -/******************************************************************************* - * Variables - ******************************************************************************/ -/*! @brief Pointers to CMP bases for each instance. */ -static CMP_Type *const s_cmpBases[] = CMP_BASE_PTRS; -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) -/*! @brief Pointers to CMP clocks for each instance. */ -static const clock_ip_name_t s_cmpClocks[] = CMP_CLOCKS; -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ - -/******************************************************************************* - * Codes - ******************************************************************************/ -static uint32_t CMP_GetInstance(CMP_Type *base) -{ - uint32_t instance; - - /* Find the instance index from base address mappings. */ - for (instance = 0; instance < ARRAY_SIZE(s_cmpBases); instance++) - { - if (s_cmpBases[instance] == base) - { - break; - } - } - - assert(instance < ARRAY_SIZE(s_cmpBases)); - - return instance; -} - -void CMP_Init(CMP_Type *base, const cmp_config_t *config) -{ - assert(NULL != config); - - uint8_t tmp8; - -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) - /* Enable the clock. */ - CLOCK_EnableClock(s_cmpClocks[CMP_GetInstance(base)]); -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ - - /* Configure. */ - CMP_Enable(base, false); /* Disable the CMP module during configuring. */ - /* CMPx_CR1. */ - tmp8 = base->CR1 & ~(CMP_CR1_PMODE_MASK | CMP_CR1_INV_MASK | CMP_CR1_COS_MASK | CMP_CR1_OPE_MASK); - if (config->enableHighSpeed) - { - tmp8 |= CMP_CR1_PMODE_MASK; - } - if (config->enableInvertOutput) - { - tmp8 |= CMP_CR1_INV_MASK; - } - if (config->useUnfilteredOutput) - { - tmp8 |= CMP_CR1_COS_MASK; - } - if (config->enablePinOut) - { - tmp8 |= CMP_CR1_OPE_MASK; - } -#if defined(FSL_FEATURE_CMP_HAS_TRIGGER_MODE) && FSL_FEATURE_CMP_HAS_TRIGGER_MODE - if (config->enableTriggerMode) - { - tmp8 |= CMP_CR1_TRIGM_MASK; - } - else - { - tmp8 &= ~CMP_CR1_TRIGM_MASK; - } -#endif /* FSL_FEATURE_CMP_HAS_TRIGGER_MODE */ - base->CR1 = tmp8; - - /* CMPx_CR0. */ - tmp8 = base->CR0 & ~CMP_CR0_HYSTCTR_MASK; - tmp8 |= CMP_CR0_HYSTCTR(config->hysteresisMode); - base->CR0 = tmp8; - - CMP_Enable(base, config->enableCmp); /* Enable the CMP module after configured or not. */ -} - -void CMP_Deinit(CMP_Type *base) -{ - /* Disable the CMP module. */ - CMP_Enable(base, false); - -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) - /* Disable the clock. */ - CLOCK_DisableClock(s_cmpClocks[CMP_GetInstance(base)]); -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ -} - -void CMP_GetDefaultConfig(cmp_config_t *config) -{ - assert(NULL != config); - - config->enableCmp = true; /* Enable the CMP module after initialization. */ - config->hysteresisMode = kCMP_HysteresisLevel0; - config->enableHighSpeed = false; - config->enableInvertOutput = false; - config->useUnfilteredOutput = false; - config->enablePinOut = false; -#if defined(FSL_FEATURE_CMP_HAS_TRIGGER_MODE) && FSL_FEATURE_CMP_HAS_TRIGGER_MODE - config->enableTriggerMode = false; -#endif /* FSL_FEATURE_CMP_HAS_TRIGGER_MODE */ -} - -void CMP_SetInputChannels(CMP_Type *base, uint8_t positiveChannel, uint8_t negativeChannel) -{ - uint8_t tmp8 = base->MUXCR; - - tmp8 &= ~(CMP_MUXCR_PSEL_MASK | CMP_MUXCR_MSEL_MASK); - tmp8 |= CMP_MUXCR_PSEL(positiveChannel) | CMP_MUXCR_MSEL(negativeChannel); - base->MUXCR = tmp8; -} - -#if defined(FSL_FEATURE_CMP_HAS_DMA) && FSL_FEATURE_CMP_HAS_DMA -void CMP_EnableDMA(CMP_Type *base, bool enable) -{ - uint8_t tmp8 = base->SCR & ~(CMP_SCR_CFR_MASK | CMP_SCR_CFF_MASK); /* To avoid change the w1c bits. */ - - if (enable) - { - tmp8 |= CMP_SCR_DMAEN_MASK; - } - else - { - tmp8 &= ~CMP_SCR_DMAEN_MASK; - } - base->SCR = tmp8; -} -#endif /* FSL_FEATURE_CMP_HAS_DMA */ - -void CMP_SetFilterConfig(CMP_Type *base, const cmp_filter_config_t *config) -{ - assert(NULL != config); - - uint8_t tmp8; - -#if defined(FSL_FEATURE_CMP_HAS_EXTERNAL_SAMPLE_SUPPORT) && FSL_FEATURE_CMP_HAS_EXTERNAL_SAMPLE_SUPPORT - /* Choose the clock source for sampling. */ - if (config->enableSample) - { - base->CR1 |= CMP_CR1_SE_MASK; /* Choose the external SAMPLE clock. */ - } - else - { - base->CR1 &= ~CMP_CR1_SE_MASK; /* Choose the internal divided bus clock. */ - } -#endif /* FSL_FEATURE_CMP_HAS_EXTERNAL_SAMPLE_SUPPORT */ - /* Set the filter count. */ - tmp8 = base->CR0 & ~CMP_CR0_FILTER_CNT_MASK; - tmp8 |= CMP_CR0_FILTER_CNT(config->filterCount); - base->CR0 = tmp8; - /* Set the filter period. It is used as the divider to bus clock. */ - base->FPR = CMP_FPR_FILT_PER(config->filterPeriod); -} - -void CMP_SetDACConfig(CMP_Type *base, const cmp_dac_config_t *config) -{ - uint8_t tmp8 = 0U; - - if (NULL == config) - { - /* Passing "NULL" as input parameter means no available configuration. So the DAC feature is disabled.*/ - base->DACCR = 0U; - return; - } - /* CMPx_DACCR. */ - tmp8 |= CMP_DACCR_DACEN_MASK; /* Enable the internal DAC. */ - if (kCMP_VrefSourceVin2 == config->referenceVoltageSource) - { - tmp8 |= CMP_DACCR_VRSEL_MASK; - } - tmp8 |= CMP_DACCR_VOSEL(config->DACValue); - - base->DACCR = tmp8; -} - -void CMP_EnableInterrupts(CMP_Type *base, uint32_t mask) -{ - uint8_t tmp8 = base->SCR & ~(CMP_SCR_CFR_MASK | CMP_SCR_CFF_MASK); /* To avoid change the w1c bits. */ - - if (0U != (kCMP_OutputRisingInterruptEnable & mask)) - { - tmp8 |= CMP_SCR_IER_MASK; - } - if (0U != (kCMP_OutputFallingInterruptEnable & mask)) - { - tmp8 |= CMP_SCR_IEF_MASK; - } - base->SCR = tmp8; -} - -void CMP_DisableInterrupts(CMP_Type *base, uint32_t mask) -{ - uint8_t tmp8 = base->SCR & ~(CMP_SCR_CFR_MASK | CMP_SCR_CFF_MASK); /* To avoid change the w1c bits. */ - - if (0U != (kCMP_OutputRisingInterruptEnable & mask)) - { - tmp8 &= ~CMP_SCR_IER_MASK; - } - if (0U != (kCMP_OutputFallingInterruptEnable & mask)) - { - tmp8 &= ~CMP_SCR_IEF_MASK; - } - base->SCR = tmp8; -} - -uint32_t CMP_GetStatusFlags(CMP_Type *base) -{ - uint32_t ret32 = 0U; - - if (0U != (CMP_SCR_CFR_MASK & base->SCR)) - { - ret32 |= kCMP_OutputRisingEventFlag; - } - if (0U != (CMP_SCR_CFF_MASK & base->SCR)) - { - ret32 |= kCMP_OutputFallingEventFlag; - } - if (0U != (CMP_SCR_COUT_MASK & base->SCR)) - { - ret32 |= kCMP_OutputAssertEventFlag; - } - return ret32; -} - -void CMP_ClearStatusFlags(CMP_Type *base, uint32_t mask) -{ - uint8_t tmp8 = base->SCR & ~(CMP_SCR_CFR_MASK | CMP_SCR_CFF_MASK); /* To avoid change the w1c bits. */ - - if (0U != (kCMP_OutputRisingEventFlag & mask)) - { - tmp8 |= CMP_SCR_CFR_MASK; - } - if (0U != (kCMP_OutputFallingEventFlag & mask)) - { - tmp8 |= CMP_SCR_CFF_MASK; - } - base->SCR = tmp8; -} diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_cmp.h b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_cmp.h deleted file mode 100644 index 5d16bf08de4..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_cmp.h +++ /dev/null @@ -1,343 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef _FSL_CMP_H_ -#define _FSL_CMP_H_ - -#include "fsl_common.h" - -/*! - * @addtogroup cmp - * @{ - */ - - -/******************************************************************************* - * Definitions - ******************************************************************************/ - -/*! @name Driver version */ -/*@{*/ -/*! @brief CMP driver version 2.0.0. */ -#define FSL_CMP_DRIVER_VERSION (MAKE_VERSION(2, 0, 0)) -/*@}*/ - -/*! -* @brief Interrupt enable/disable mask. -*/ -enum _cmp_interrupt_enable -{ - kCMP_OutputRisingInterruptEnable = CMP_SCR_IER_MASK, /*!< Comparator interrupt enable rising. */ - kCMP_OutputFallingInterruptEnable = CMP_SCR_IEF_MASK, /*!< Comparator interrupt enable falling. */ -}; - -/*! - * @brief Status flags' mask. - */ -enum _cmp_status_flags -{ - kCMP_OutputRisingEventFlag = CMP_SCR_CFR_MASK, /*!< Rising-edge on the comparison output has occurred. */ - kCMP_OutputFallingEventFlag = CMP_SCR_CFF_MASK, /*!< Falling-edge on the comparison output has occurred. */ - kCMP_OutputAssertEventFlag = CMP_SCR_COUT_MASK, /*!< Return the current value of the analog comparator output. */ -}; - -/*! - * @brief CMP Hysteresis mode. - */ -typedef enum _cmp_hysteresis_mode -{ - kCMP_HysteresisLevel0 = 0U, /*!< Hysteresis level 0. */ - kCMP_HysteresisLevel1 = 1U, /*!< Hysteresis level 1. */ - kCMP_HysteresisLevel2 = 2U, /*!< Hysteresis level 2. */ - kCMP_HysteresisLevel3 = 3U, /*!< Hysteresis level 3. */ -} cmp_hysteresis_mode_t; - -/*! - * @brief CMP Voltage Reference source. - */ -typedef enum _cmp_reference_voltage_source -{ - kCMP_VrefSourceVin1 = 0U, /*!< Vin1 is selected as a resistor ladder network supply reference Vin. */ - kCMP_VrefSourceVin2 = 1U, /*!< Vin2 is selected as a resistor ladder network supply reference Vin. */ -} cmp_reference_voltage_source_t; - -/*! - * @brief Configures the comparator. - */ -typedef struct _cmp_config -{ - bool enableCmp; /*!< Enable the CMP module. */ - cmp_hysteresis_mode_t hysteresisMode; /*!< CMP Hysteresis mode. */ - bool enableHighSpeed; /*!< Enable High-speed (HS) comparison mode. */ - bool enableInvertOutput; /*!< Enable the inverted comparator output. */ - bool useUnfilteredOutput; /*!< Set the compare output(COUT) to equal COUTA(true) or COUT(false). */ - bool enablePinOut; /*!< The comparator output is available on the associated pin. */ -#if defined(FSL_FEATURE_CMP_HAS_TRIGGER_MODE) && FSL_FEATURE_CMP_HAS_TRIGGER_MODE - bool enableTriggerMode; /*!< Enable the trigger mode. */ -#endif /* FSL_FEATURE_CMP_HAS_TRIGGER_MODE */ -} cmp_config_t; - -/*! - * @brief Configures the filter. - */ -typedef struct _cmp_filter_config -{ -#if defined(FSL_FEATURE_CMP_HAS_EXTERNAL_SAMPLE_SUPPORT) && FSL_FEATURE_CMP_HAS_EXTERNAL_SAMPLE_SUPPORT - bool enableSample; /*!< Using the external SAMPLE as a sampling clock input or using a divided bus clock. */ -#endif /* FSL_FEATURE_CMP_HAS_EXTERNAL_SAMPLE_SUPPORT */ - uint8_t filterCount; /*!< Filter Sample Count. Available range is 1-7; 0 disables the filter.*/ - uint8_t filterPeriod; /*!< Filter Sample Period. The divider to the bus clock. Available range is 0-255. */ -} cmp_filter_config_t; - -/*! - * @brief Configures the internal DAC. - */ -typedef struct _cmp_dac_config -{ - cmp_reference_voltage_source_t referenceVoltageSource; /*!< Supply voltage reference source. */ - uint8_t DACValue; /*!< Value for the DAC Output Voltage. Available range is 0-63.*/ -} cmp_dac_config_t; - -#if defined(__cplusplus) -extern "C" { -#endif - -/******************************************************************************* - * API - ******************************************************************************/ - -/*! - * @name Initialization - * @{ - */ - -/*! - * @brief Initializes the CMP. - * - * This function initializes the CMP module. The operations included are as follows. - * - Enabling the clock for CMP module. - * - Configuring the comparator. - * - Enabling the CMP module. - * Note that for some devices, multiple CMP instances share the same clock gate. In this case, to enable the clock for - * any instance enables all CMPs. See the appropriate MCU reference manual for the clock assignment of the CMP. - * - * @param base CMP peripheral base address. - * @param config Pointer to the configuration structure. - */ -void CMP_Init(CMP_Type *base, const cmp_config_t *config); - -/*! - * @brief De-initializes the CMP module. - * - * This function de-initializes the CMP module. The operations included are as follows. - * - Disabling the CMP module. - * - Disabling the clock for CMP module. - * - * This function disables the clock for the CMP. - * Note that for some devices, multiple CMP instances share the same clock gate. In this case, before disabling the - * clock for the CMP, ensure that all the CMP instances are not used. - * - * @param base CMP peripheral base address. - */ -void CMP_Deinit(CMP_Type *base); - -/*! - * @brief Enables/disables the CMP module. - * - * @param base CMP peripheral base address. - * @param enable Enables or disables the module. - */ -static inline void CMP_Enable(CMP_Type *base, bool enable) -{ - if (enable) - { - base->CR1 |= CMP_CR1_EN_MASK; - } - else - { - base->CR1 &= ~CMP_CR1_EN_MASK; - } -} - -/*! -* @brief Initializes the CMP user configuration structure. -* -* This function initializes the user configuration structure to these default values. -* @code -* config->enableCmp = true; -* config->hysteresisMode = kCMP_HysteresisLevel0; -* config->enableHighSpeed = false; -* config->enableInvertOutput = false; -* config->useUnfilteredOutput = false; -* config->enablePinOut = false; -* config->enableTriggerMode = false; -* @endcode -* @param config Pointer to the configuration structure. -*/ -void CMP_GetDefaultConfig(cmp_config_t *config); - -/*! - * @brief Sets the input channels for the comparator. - * - * This function sets the input channels for the comparator. - * Note that two input channels cannot be set the same way in the application. When the user selects the same input - * from the analog mux to the positive and negative port, the comparator is disabled automatically. - * - * @param base CMP peripheral base address. - * @param positiveChannel Positive side input channel number. Available range is 0-7. - * @param negativeChannel Negative side input channel number. Available range is 0-7. - */ -void CMP_SetInputChannels(CMP_Type *base, uint8_t positiveChannel, uint8_t negativeChannel); - -/* @} */ - -/*! - * @name Advanced Features - * @{ - */ - -#if defined(FSL_FEATURE_CMP_HAS_DMA) && FSL_FEATURE_CMP_HAS_DMA -/*! - * @brief Enables/disables the DMA request for rising/falling events. - * - * This function enables/disables the DMA request for rising/falling events. Either event triggers the generation of - * the DMA request from CMP if the DMA feature is enabled. Both events are ignored for generating the DMA request from the CMP - * if the DMA is disabled. - * - * @param base CMP peripheral base address. - * @param enable Enables or disables the feature. - */ -void CMP_EnableDMA(CMP_Type *base, bool enable); -#endif /* FSL_FEATURE_CMP_HAS_DMA */ - -#if defined(FSL_FEATURE_CMP_HAS_WINDOW_MODE) && FSL_FEATURE_CMP_HAS_WINDOW_MODE -/*! - * @brief Enables/disables the window mode. - * - * @param base CMP peripheral base address. - * @param enable Enables or disables the feature. - */ -static inline void CMP_EnableWindowMode(CMP_Type *base, bool enable) -{ - if (enable) - { - base->CR1 |= CMP_CR1_WE_MASK; - } - else - { - base->CR1 &= ~CMP_CR1_WE_MASK; - } -} -#endif /* FSL_FEATURE_CMP_HAS_WINDOW_MODE */ - -#if defined(FSL_FEATURE_CMP_HAS_PASS_THROUGH_MODE) && FSL_FEATURE_CMP_HAS_PASS_THROUGH_MODE -/*! - * @brief Enables/disables the pass through mode. - * - * @param base CMP peripheral base address. - * @param enable Enables or disables the feature. - */ -static inline void CMP_EnablePassThroughMode(CMP_Type *base, bool enable) -{ - if (enable) - { - base->MUXCR |= CMP_MUXCR_PSTM_MASK; - } - else - { - base->MUXCR &= ~CMP_MUXCR_PSTM_MASK; - } -} -#endif /* FSL_FEATURE_CMP_HAS_PASS_THROUGH_MODE */ - -/*! - * @brief Configures the filter. - * - * @param base CMP peripheral base address. - * @param config Pointer to the configuration structure. - */ -void CMP_SetFilterConfig(CMP_Type *base, const cmp_filter_config_t *config); - -/*! - * @brief Configures the internal DAC. - * - * @param base CMP peripheral base address. - * @param config Pointer to the configuration structure. "NULL" disables the feature. - */ -void CMP_SetDACConfig(CMP_Type *base, const cmp_dac_config_t *config); - -/*! - * @brief Enables the interrupts. - * - * @param base CMP peripheral base address. - * @param mask Mask value for interrupts. See "_cmp_interrupt_enable". - */ -void CMP_EnableInterrupts(CMP_Type *base, uint32_t mask); - -/*! - * @brief Disables the interrupts. - * - * @param base CMP peripheral base address. - * @param mask Mask value for interrupts. See "_cmp_interrupt_enable". - */ -void CMP_DisableInterrupts(CMP_Type *base, uint32_t mask); - -/* @} */ - -/*! - * @name Results - * @{ - */ - -/*! - * @brief Gets the status flags. - * - * @param base CMP peripheral base address. - * - * @return Mask value for the asserted flags. See "_cmp_status_flags". - */ -uint32_t CMP_GetStatusFlags(CMP_Type *base); - -/*! - * @brief Clears the status flags. - * - * @param base CMP peripheral base address. - * @param mask Mask value for the flags. See "_cmp_status_flags". - */ -void CMP_ClearStatusFlags(CMP_Type *base, uint32_t mask); - -/* @} */ -#if defined(__cplusplus) -} -#endif -/*! - * @} - */ -#endif /* _FSL_CMP_H_ */ diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_cmt.c b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_cmt.c deleted file mode 100644 index 8cf72bc7e7d..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_cmt.c +++ /dev/null @@ -1,265 +0,0 @@ -/* - * Copyright (c) 2016, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "fsl_cmt.h" - -/******************************************************************************* - * Definitions - ******************************************************************************/ - -/* The standard intermediate frequency (IF). */ -#define CMT_INTERMEDIATEFREQUENCY_8MHZ (8000000U) -/* CMT data modulate mask. */ -#define CMT_MODULATE_COUNT_WIDTH (8U) -/* CMT diver 1. */ -#define CMT_CMTDIV_ONE (1) -/* CMT diver 2. */ -#define CMT_CMTDIV_TWO (2) -/* CMT diver 4. */ -#define CMT_CMTDIV_FOUR (4) -/* CMT diver 8. */ -#define CMT_CMTDIV_EIGHT (8) - -/******************************************************************************* - * Prototypes - ******************************************************************************/ - -/*! - * @brief Get instance number for CMT module. - * - * @param base CMT peripheral base address. - */ -static uint32_t CMT_GetInstance(CMT_Type *base); - -/******************************************************************************* - * Variables - ******************************************************************************/ - -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) -/*! @brief Pointers to cmt clocks for each instance. */ -static const clock_ip_name_t s_cmtClock[FSL_FEATURE_SOC_CMT_COUNT] = CMT_CLOCKS; -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ - -/*! @brief Pointers to cmt bases for each instance. */ -static CMT_Type *const s_cmtBases[] = CMT_BASE_PTRS; - -/*! @brief Pointers to cmt IRQ number for each instance. */ -static const IRQn_Type s_cmtIrqs[] = CMT_IRQS; - -/******************************************************************************* - * Codes - ******************************************************************************/ - -static uint32_t CMT_GetInstance(CMT_Type *base) -{ - uint32_t instance; - - /* Find the instance index from base address mappings. */ - for (instance = 0; instance < ARRAY_SIZE(s_cmtBases); instance++) - { - if (s_cmtBases[instance] == base) - { - break; - } - } - - assert(instance < ARRAY_SIZE(s_cmtBases)); - - return instance; -} - -void CMT_GetDefaultConfig(cmt_config_t *config) -{ - assert(config); - - /* Default infrared output is enabled and set with high active, the divider is set to 1. */ - config->isInterruptEnabled = false; - config->isIroEnabled = true; - config->iroPolarity = kCMT_IROActiveHigh; - config->divider = kCMT_SecondClkDiv1; -} - -void CMT_Init(CMT_Type *base, const cmt_config_t *config, uint32_t busClock_Hz) -{ - assert(config); - assert(busClock_Hz >= CMT_INTERMEDIATEFREQUENCY_8MHZ); - - uint8_t divider; - -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) - /* Ungate clock. */ - CLOCK_EnableClock(s_cmtClock[CMT_GetInstance(base)]); -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ - - /* Sets clock divider. The divider set in pps should be set - to make sycClock_Hz/divder = 8MHz */ - base->PPS = CMT_PPS_PPSDIV(busClock_Hz / CMT_INTERMEDIATEFREQUENCY_8MHZ - 1); - divider = base->MSC; - divider &= ~CMT_MSC_CMTDIV_MASK; - divider |= CMT_MSC_CMTDIV(config->divider); - base->MSC = divider; - - /* Set the IRO signal. */ - base->OC = CMT_OC_CMTPOL(config->iroPolarity) | CMT_OC_IROPEN(config->isIroEnabled); - - /* Set interrupt. */ - if (config->isInterruptEnabled) - { - CMT_EnableInterrupts(base, kCMT_EndOfCycleInterruptEnable); - EnableIRQ(s_cmtIrqs[CMT_GetInstance(base)]); - } -} - -void CMT_Deinit(CMT_Type *base) -{ - /*Disable the CMT modulator. */ - base->MSC = 0; - - /* Disable the interrupt. */ - CMT_DisableInterrupts(base, kCMT_EndOfCycleInterruptEnable); - DisableIRQ(s_cmtIrqs[CMT_GetInstance(base)]); - -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) - /* Gate the clock. */ - CLOCK_DisableClock(s_cmtClock[CMT_GetInstance(base)]); -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ -} - -void CMT_SetMode(CMT_Type *base, cmt_mode_t mode, cmt_modulate_config_t *modulateConfig) -{ - uint8_t mscReg = base->MSC; - - /* Judge the mode. */ - if (mode != kCMT_DirectIROCtl) - { - assert(modulateConfig); - - /* Set carrier generator. */ - CMT_SetCarrirGenerateCountOne(base, modulateConfig->highCount1, modulateConfig->lowCount1); - if (mode == kCMT_FSKMode) - { - CMT_SetCarrirGenerateCountTwo(base, modulateConfig->highCount2, modulateConfig->lowCount2); - } - - /* Set carrier modulator. */ - CMT_SetModulateMarkSpace(base, modulateConfig->markCount, modulateConfig->spaceCount); - mscReg &= ~ (CMT_MSC_FSK_MASK | CMT_MSC_BASE_MASK); - mscReg |= mode; - } - else - { - mscReg &= ~CMT_MSC_MCGEN_MASK; - } - /* Set the CMT mode. */ - base->MSC = mscReg; -} - -cmt_mode_t CMT_GetMode(CMT_Type *base) -{ - uint8_t mode = base->MSC; - - if (!(mode & CMT_MSC_MCGEN_MASK)) - { /* Carrier modulator disabled and the IRO signal is in direct software control. */ - return kCMT_DirectIROCtl; - } - else - { - /* Carrier modulator is enabled. */ - if (mode & CMT_MSC_BASE_MASK) - { - /* Base band mode. */ - return kCMT_BasebandMode; - } - else if (mode & CMT_MSC_FSK_MASK) - { - /* FSK mode. */ - return kCMT_FSKMode; - } - else - { - /* Time mode. */ - return kCMT_TimeMode; - } - } -} - -uint32_t CMT_GetCMTFrequency(CMT_Type *base, uint32_t busClock_Hz) -{ - uint32_t frequency; - uint32_t divider; - - /* Get intermediate frequency. */ - frequency = busClock_Hz / ((base->PPS & CMT_PPS_PPSDIV_MASK) + 1); - - /* Get the second divider. */ - divider = ((base->MSC & CMT_MSC_CMTDIV_MASK) >> CMT_MSC_CMTDIV_SHIFT); - /* Get CMT frequency. */ - switch ((cmt_second_clkdiv_t)divider) - { - case kCMT_SecondClkDiv1: - frequency = frequency / CMT_CMTDIV_ONE; - break; - case kCMT_SecondClkDiv2: - frequency = frequency / CMT_CMTDIV_TWO; - break; - case kCMT_SecondClkDiv4: - frequency = frequency / CMT_CMTDIV_FOUR; - break; - case kCMT_SecondClkDiv8: - frequency = frequency / CMT_CMTDIV_EIGHT; - break; - default: - frequency = frequency / CMT_CMTDIV_ONE; - break; - } - - return frequency; -} - -void CMT_SetModulateMarkSpace(CMT_Type *base, uint32_t markCount, uint32_t spaceCount) -{ - /* Set modulate mark. */ - base->CMD1 = (markCount >> CMT_MODULATE_COUNT_WIDTH) & CMT_CMD1_MB_MASK; - base->CMD2 = (markCount & CMT_CMD2_MB_MASK); - /* Set modulate space. */ - base->CMD3 = (spaceCount >> CMT_MODULATE_COUNT_WIDTH) & CMT_CMD3_SB_MASK; - base->CMD4 = spaceCount & CMT_CMD4_SB_MASK; -} - -void CMT_SetIroState(CMT_Type *base, cmt_infrared_output_state_t state) -{ - uint8_t ocReg = base->OC; - - ocReg &= ~CMT_OC_IROL_MASK; - ocReg |= CMT_OC_IROL(state); - - /* Set the infrared output signal control. */ - base->OC = ocReg; -} diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_cmt.h b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_cmt.h deleted file mode 100644 index 3d81f8a9a4a..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_cmt.h +++ /dev/null @@ -1,401 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -#ifndef _FSL_CMT_H_ -#define _FSL_CMT_H_ - -#include "fsl_common.h" - -/*! - * @addtogroup cmt - * @{ - */ - - -/******************************************************************************* - * Definitions - ******************************************************************************/ - -/*! @name Driver version */ -/*@{*/ -/*! @brief CMT driver version 2.0.1. */ -#define FSL_CMT_DRIVER_VERSION (MAKE_VERSION(2, 0, 1)) -/*@}*/ - -/*! - * @brief The modes of CMT. - */ -typedef enum _cmt_mode -{ - kCMT_DirectIROCtl = 0x00U, /*!< Carrier modulator is disabled and the IRO signal is directly in software control */ - kCMT_TimeMode = 0x01U, /*!< Carrier modulator is enabled in time mode. */ - kCMT_FSKMode = 0x05U, /*!< Carrier modulator is enabled in FSK mode. */ - kCMT_BasebandMode = 0x09U /*!< Carrier modulator is enabled in baseband mode. */ -} cmt_mode_t; - -/*! - * @brief The CMT clock divide primary prescaler. - * The primary clock divider is used to divider the bus clock to - * get the intermediate frequency to approximately equal to 8 MHZ. - * When the bus clock is 8 MHZ, set primary prescaler to "kCMT_PrimaryClkDiv1". - */ -typedef enum _cmt_primary_clkdiv -{ - kCMT_PrimaryClkDiv1 = 0U, /*!< The intermediate frequency is the bus clock divided by 1. */ - kCMT_PrimaryClkDiv2 = 1U, /*!< The intermediate frequency is the bus clock divided by 2. */ - kCMT_PrimaryClkDiv3 = 2U, /*!< The intermediate frequency is the bus clock divided by 3. */ - kCMT_PrimaryClkDiv4 = 3U, /*!< The intermediate frequency is the bus clock divided by 4. */ - kCMT_PrimaryClkDiv5 = 4U, /*!< The intermediate frequency is the bus clock divided by 5. */ - kCMT_PrimaryClkDiv6 = 5U, /*!< The intermediate frequency is the bus clock divided by 6. */ - kCMT_PrimaryClkDiv7 = 6U, /*!< The intermediate frequency is the bus clock divided by 7. */ - kCMT_PrimaryClkDiv8 = 7U, /*!< The intermediate frequency is the bus clock divided by 8. */ - kCMT_PrimaryClkDiv9 = 8U, /*!< The intermediate frequency is the bus clock divided by 9. */ - kCMT_PrimaryClkDiv10 = 9U, /*!< The intermediate frequency is the bus clock divided by 10. */ - kCMT_PrimaryClkDiv11 = 10U, /*!< The intermediate frequency is the bus clock divided by 11. */ - kCMT_PrimaryClkDiv12 = 11U, /*!< The intermediate frequency is the bus clock divided by 12. */ - kCMT_PrimaryClkDiv13 = 12U, /*!< The intermediate frequency is the bus clock divided by 13. */ - kCMT_PrimaryClkDiv14 = 13U, /*!< The intermediate frequency is the bus clock divided by 14. */ - kCMT_PrimaryClkDiv15 = 14U, /*!< The intermediate frequency is the bus clock divided by 15. */ - kCMT_PrimaryClkDiv16 = 15U /*!< The intermediate frequency is the bus clock divided by 16. */ -} cmt_primary_clkdiv_t; - -/*! - * @brief The CMT clock divide secondary prescaler. - * The second prescaler can be used to divide the 8 MHZ CMT clock - * by 1, 2, 4, or 8 according to the specification. - */ -typedef enum _cmt_second_clkdiv -{ - kCMT_SecondClkDiv1 = 0U, /*!< The CMT clock is the intermediate frequency frequency divided by 1. */ - kCMT_SecondClkDiv2 = 1U, /*!< The CMT clock is the intermediate frequency frequency divided by 2. */ - kCMT_SecondClkDiv4 = 2U, /*!< The CMT clock is the intermediate frequency frequency divided by 4. */ - kCMT_SecondClkDiv8 = 3U /*!< The CMT clock is the intermediate frequency frequency divided by 8. */ -} cmt_second_clkdiv_t; - -/*! - * @brief The CMT infrared output polarity. - */ -typedef enum _cmt_infrared_output_polarity -{ - kCMT_IROActiveLow = 0U, /*!< The CMT infrared output signal polarity is active-low. */ - kCMT_IROActiveHigh = 1U /*!< The CMT infrared output signal polarity is active-high. */ -} cmt_infrared_output_polarity_t; - -/*! - * @brief The CMT infrared output signal state control. - */ -typedef enum _cmt_infrared_output_state -{ - kCMT_IROCtlLow = 0U, /*!< The CMT Infrared output signal state is controlled to low. */ - kCMT_IROCtlHigh = 1U /*!< The CMT Infrared output signal state is controlled to high. */ -} cmt_infrared_output_state_t; - -/*! - * @brief CMT interrupt configuration structure, default settings all disabled. - * - * This structure contains the settings for all of the CMT interrupt configurations. - */ -enum _cmt_interrupt_enable -{ - kCMT_EndOfCycleInterruptEnable = CMT_MSC_EOCIE_MASK, /*!< CMT end of cycle interrupt. */ -}; - -/*! - * @brief CMT carrier generator and modulator configuration structure - * - */ -typedef struct _cmt_modulate_config -{ - uint8_t highCount1; /*!< The high-time for carrier generator first register. */ - uint8_t lowCount1; /*!< The low-time for carrier generator first register. */ - uint8_t highCount2; /*!< The high-time for carrier generator second register for FSK mode. */ - uint8_t lowCount2; /*!< The low-time for carrier generator second register for FSK mode. */ - uint16_t markCount; /*!< The mark time for the modulator gate. */ - uint16_t spaceCount; /*!< The space time for the modulator gate. */ -} cmt_modulate_config_t; - -/*! @brief CMT basic configuration structure. */ -typedef struct _cmt_config -{ - bool isInterruptEnabled; /*!< Timer interrupt 0-disable, 1-enable. */ - bool isIroEnabled; /*!< The IRO output 0-disabled, 1-enabled. */ - cmt_infrared_output_polarity_t iroPolarity; /*!< The IRO polarity. */ - cmt_second_clkdiv_t divider; /*!< The CMT clock divide prescaler. */ -} cmt_config_t; - -/******************************************************************************* - * API - ******************************************************************************/ - -#if defined(__cplusplus) -extern "C" { -#endif - -/*! - * @name Initialization and deinitialization - * @{ - */ - -/*! - * @brief Gets the CMT default configuration structure. This API - * gets the default configuration structure for the CMT_Init(). - * Use the initialized structure unchanged in CMT_Init() or modify - * fields of the structure before calling the CMT_Init(). - * - * @param config The CMT configuration structure pointer. - */ -void CMT_GetDefaultConfig(cmt_config_t *config); - -/*! - * @brief Initializes the CMT module. - * - * This function ungates the module clock and sets the CMT internal clock, - * interrupt, and infrared output signal for the CMT module. - * - * @param base CMT peripheral base address. - * @param config The CMT basic configuration structure. - * @param busClock_Hz The CMT module input clock - bus clock frequency. - */ -void CMT_Init(CMT_Type *base, const cmt_config_t *config, uint32_t busClock_Hz); - -/*! - * @brief Disables the CMT module and gate control. - * - * This function disables CMT modulator, interrupts, and gates the - * CMT clock control. CMT_Init must be called to use the CMT again. - * - * @param base CMT peripheral base address. - */ -void CMT_Deinit(CMT_Type *base); - -/*! @}*/ - -/*! - * @name Basic Control Operations - * @{ - */ - -/*! - * @brief Selects the mode for CMT. - * - * @param base CMT peripheral base address. - * @param mode The CMT feature mode enumeration. See "cmt_mode_t". - * @param modulateConfig The carrier generation and modulator configuration. - */ -void CMT_SetMode(CMT_Type *base, cmt_mode_t mode, cmt_modulate_config_t *modulateConfig); - -/*! - * @brief Gets the mode of the CMT module. - * - * @param base CMT peripheral base address. - * @return The CMT mode. - * kCMT_DirectIROCtl Carrier modulator is disabled; the IRO signal is directly in software control. - * kCMT_TimeMode Carrier modulator is enabled in time mode. - * kCMT_FSKMode Carrier modulator is enabled in FSK mode. - * kCMT_BasebandMode Carrier modulator is enabled in baseband mode. - */ -cmt_mode_t CMT_GetMode(CMT_Type *base); - -/*! - * @brief Gets the actual CMT clock frequency. - * - * @param base CMT peripheral base address. - * @param busClock_Hz CMT module input clock - bus clock frequency. - * @return The CMT clock frequency. - */ -uint32_t CMT_GetCMTFrequency(CMT_Type *base, uint32_t busClock_Hz); - -/*! - * @brief Sets the primary data set for the CMT carrier generator counter. - * - * This function sets the high-time and low-time of the primary data set for the - * CMT carrier generator counter to control the period and the duty cycle of the - * output carrier signal. - * If the CMT clock period is Tcmt, the period of the carrier generator signal equals - * (highCount + lowCount) * Tcmt. The duty cycle equals to highCount / (highCount + lowCount). - * - * @param base CMT peripheral base address. - * @param highCount The number of CMT clocks for carrier generator signal high time, - * integer in the range of 1 ~ 0xFF. - * @param lowCount The number of CMT clocks for carrier generator signal low time, - * integer in the range of 1 ~ 0xFF. - */ -static inline void CMT_SetCarrirGenerateCountOne(CMT_Type *base, uint32_t highCount, uint32_t lowCount) -{ - assert(highCount <= CMT_CGH1_PH_MASK); - assert(highCount); - assert(lowCount <= CMT_CGL1_PL_MASK); - assert(lowCount); - - base->CGH1 = highCount; - base->CGL1 = lowCount; -} - -/*! - * @brief Sets the secondary data set for the CMT carrier generator counter. - * - * This function is used for FSK mode setting the high-time and low-time of the secondary - * data set CMT carrier generator counter to control the period and the duty cycle - * of the output carrier signal. - * If the CMT clock period is Tcmt, the period of the carrier generator signal equals - * (highCount + lowCount) * Tcmt. The duty cycle equals highCount / (highCount + lowCount). - * - * @param base CMT peripheral base address. - * @param highCount The number of CMT clocks for carrier generator signal high time, - * integer in the range of 1 ~ 0xFF. - * @param lowCount The number of CMT clocks for carrier generator signal low time, - * integer in the range of 1 ~ 0xFF. - */ -static inline void CMT_SetCarrirGenerateCountTwo(CMT_Type *base, uint32_t highCount, uint32_t lowCount) -{ - assert(highCount <= CMT_CGH2_SH_MASK); - assert(highCount); - assert(lowCount <= CMT_CGL2_SL_MASK); - assert(lowCount); - - base->CGH2 = highCount; - base->CGL2 = lowCount; -} - -/*! - * @brief Sets the modulation mark and space time period for the CMT modulator. - * - * This function sets the mark time period of the CMT modulator counter - * to control the mark time of the output modulated signal from the carrier generator output signal. - * If the CMT clock frequency is Fcmt and the carrier out signal frequency is fcg: - * - In Time and Baseband mode: The mark period of the generated signal equals (markCount + 1) / (Fcmt/8). - * The space period of the generated signal equals spaceCount / (Fcmt/8). - * - In FSK mode: The mark period of the generated signal equals (markCount + 1)/fcg. - * The space period of the generated signal equals spaceCount / fcg. - * - * @param base Base address for current CMT instance. - * @param markCount The number of clock period for CMT modulator signal mark period, - * in the range of 0 ~ 0xFFFF. - * @param spaceCount The number of clock period for CMT modulator signal space period, - * in the range of the 0 ~ 0xFFFF. - */ -void CMT_SetModulateMarkSpace(CMT_Type *base, uint32_t markCount, uint32_t spaceCount); - -/*! - * @brief Enables or disables the extended space operation. - * - * This function is used to make the space period longer - * for time, baseband, and FSK modes. - * - * @param base CMT peripheral base address. - * @param enable True enable the extended space, false disable the extended space. - */ -static inline void CMT_EnableExtendedSpace(CMT_Type *base, bool enable) -{ - if (enable) - { - base->MSC |= CMT_MSC_EXSPC_MASK; - } - else - { - base->MSC &= ~CMT_MSC_EXSPC_MASK; - } -} - -/*! - * @brief Sets the IRO (infrared output) signal state. - * - * Changes the states of the IRO signal when the kCMT_DirectIROMode mode is set - * and the IRO signal is enabled. - * - * @param base CMT peripheral base address. - * @param state The control of the IRO signal. See "cmt_infrared_output_state_t" - */ -void CMT_SetIroState(CMT_Type *base, cmt_infrared_output_state_t state); - -/*! - * @brief Enables the CMT interrupt. - * - * This function enables the CMT interrupts according to the provided mask if enabled. - * The CMT only has the end of the cycle interrupt - an interrupt occurs at the end - * of the modulator cycle. This interrupt provides a means for the user - * to reload the new mark/space values into the CMT modulator data registers - * and verify the modulator mark and space. - * For example, to enable the end of cycle, do the following. - * @code - * CMT_EnableInterrupts(CMT, kCMT_EndOfCycleInterruptEnable); - * @endcode - * @param base CMT peripheral base address. - * @param mask The interrupts to enable. Logical OR of @ref _cmt_interrupt_enable. - */ -static inline void CMT_EnableInterrupts(CMT_Type *base, uint32_t mask) -{ - base->MSC |= mask; -} - -/*! - * @brief Disables the CMT interrupt. - * - * This function disables the CMT interrupts according to the provided maskIf enabled. - * The CMT only has the end of the cycle interrupt. - * For example, to disable the end of cycle, do the following. - * @code - * CMT_DisableInterrupts(CMT, kCMT_EndOfCycleInterruptEnable); - * @endcode - * - * @param base CMT peripheral base address. - * @param mask The interrupts to enable. Logical OR of @ref _cmt_interrupt_enable. - */ -static inline void CMT_DisableInterrupts(CMT_Type *base, uint32_t mask) -{ - base->MSC &= ~mask; -} - -/*! - * @brief Gets the end of the cycle status flag. - * - * The flag is set: - * - When the modulator is not currently active and carrier and modulator - * are set to start the initial CMT transmission. - * - At the end of each modulation cycle when the counter is reloaded and - * the carrier and modulator are enabled. - * @param base CMT peripheral base address. - * @return Current status of the end of cycle status flag - * @arg non-zero: End-of-cycle has occurred. - * @arg zero: End-of-cycle has not yet occurred since the flag last cleared. - */ -static inline uint32_t CMT_GetStatusFlags(CMT_Type *base) -{ - return base->MSC & CMT_MSC_EOCF_MASK; -} - -/*! @}*/ - -#if defined(__cplusplus) -} -#endif - -/*! @}*/ - -#endif /* _FSL_CMT_H_*/ diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_common.c b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_common.c deleted file mode 100644 index b719fafbc04..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_common.c +++ /dev/null @@ -1,179 +0,0 @@ -/* - * Copyright (c) 2015-2016, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "fsl_common.h" -/* This is not needed for mbed */ -#if 0 -#include "fsl_debug_console.h" - -#ifndef NDEBUG -#if (defined(__CC_ARM)) || (defined(__ICCARM__)) -void __aeabi_assert(const char *failedExpr, const char *file, int line) -{ - PRINTF("ASSERT ERROR \" %s \": file \"%s\" Line \"%d\" \n", failedExpr, file, line); - for (;;) - { - __BKPT(0); - } -} -#elif(defined(__REDLIB__)) - -#if SDK_DEBUGCONSOLE -void __assertion_failed(char *_Expr) -{ - PRINTF("%s\n", _Expr); - for (;;) - { - __asm("bkpt #0"); - } -} -#endif - -#elif(defined(__GNUC__)) -void __assert_func(const char *file, int line, const char *func, const char *failedExpr) -{ - PRINTF("ASSERT ERROR \" %s \": file \"%s\" Line \"%d\" function name \"%s\" \n", failedExpr, file, line, func); - for (;;) - { - __BKPT(0); - } -} -#endif /* (defined(__CC_ARM)) || (defined (__ICCARM__)) */ -#endif /* NDEBUG */ -#endif /* This was not needed for mbed */ - -#ifndef __GIC_PRIO_BITS -uint32_t InstallIRQHandler(IRQn_Type irq, uint32_t irqHandler) -{ -/* Addresses for VECTOR_TABLE and VECTOR_RAM come from the linker file */ -#if defined(__CC_ARM) - extern uint32_t Image$$VECTOR_ROM$$Base[]; - extern uint32_t Image$$VECTOR_RAM$$Base[]; - extern uint32_t Image$$RW_m_data$$Base[]; - -#define __VECTOR_TABLE Image$$VECTOR_ROM$$Base -#define __VECTOR_RAM Image$$VECTOR_RAM$$Base -#define __RAM_VECTOR_TABLE_SIZE (((uint32_t)Image$$RW_m_data$$Base - (uint32_t)Image$$VECTOR_RAM$$Base)) -#elif defined(__ICCARM__) - extern uint32_t __RAM_VECTOR_TABLE_SIZE[]; - extern uint32_t __VECTOR_TABLE[]; - extern uint32_t __VECTOR_RAM[]; -#elif defined(__GNUC__) - extern uint32_t __VECTOR_TABLE[]; - extern uint32_t __VECTOR_RAM[]; - extern uint32_t __RAM_VECTOR_TABLE_SIZE_BYTES[]; - uint32_t __RAM_VECTOR_TABLE_SIZE = (uint32_t)(__RAM_VECTOR_TABLE_SIZE_BYTES); -#endif /* defined(__CC_ARM) */ - uint32_t n; - uint32_t ret; - uint32_t irqMaskValue; - - irqMaskValue = DisableGlobalIRQ(); - if (SCB->VTOR != (uint32_t)__VECTOR_RAM) - { - /* Copy the vector table from ROM to RAM */ - for (n = 0; n < ((uint32_t)__RAM_VECTOR_TABLE_SIZE) / sizeof(uint32_t); n++) - { - __VECTOR_RAM[n] = __VECTOR_TABLE[n]; - } - /* Point the VTOR to the position of vector table */ - SCB->VTOR = (uint32_t)__VECTOR_RAM; - } - - ret = __VECTOR_RAM[irq + 16]; - /* make sure the __VECTOR_RAM is noncachable */ - __VECTOR_RAM[irq + 16] = irqHandler; - - EnableGlobalIRQ(irqMaskValue); - - return ret; -} -#endif - -#ifndef CPU_QN908X -#if (defined(FSL_FEATURE_SOC_SYSCON_COUNT) && (FSL_FEATURE_SOC_SYSCON_COUNT > 0)) - -void EnableDeepSleepIRQ(IRQn_Type interrupt) -{ - uint32_t index = 0; - uint32_t intNumber = (uint32_t)interrupt; - while (intNumber >= 32u) - { - index++; - intNumber -= 32u; - } - - SYSCON->STARTERSET[index] = 1u << intNumber; - EnableIRQ(interrupt); /* also enable interrupt at NVIC */ -} - -void DisableDeepSleepIRQ(IRQn_Type interrupt) -{ - uint32_t index = 0; - uint32_t intNumber = (uint32_t)interrupt; - while (intNumber >= 32u) - { - index++; - intNumber -= 32u; - } - - DisableIRQ(interrupt); /* also disable interrupt at NVIC */ - SYSCON->STARTERCLR[index] = 1u << intNumber; -} -#endif /* FSL_FEATURE_SOC_SYSCON_COUNT */ -#else -void EnableDeepSleepIRQ(IRQn_Type interrupt) -{ - uint32_t index = 0; - uint32_t intNumber = (uint32_t)interrupt; - while (intNumber >= 32u) - { - index++; - intNumber -= 32u; - } - - /* SYSCON->STARTERSET[index] = 1u << intNumber; */ - EnableIRQ(interrupt); /* also enable interrupt at NVIC */ -} - -void DisableDeepSleepIRQ(IRQn_Type interrupt) -{ - uint32_t index = 0; - uint32_t intNumber = (uint32_t)interrupt; - while (intNumber >= 32u) - { - index++; - intNumber -= 32u; - } - - DisableIRQ(interrupt); /* also disable interrupt at NVIC */ - /* SYSCON->STARTERCLR[index] = 1u << intNumber; */ -} -#endif /*CPU_QN908X */ diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_common.h b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_common.h deleted file mode 100644 index f20c09027e9..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_common.h +++ /dev/null @@ -1,348 +0,0 @@ -/* - * Copyright (c) 2015-2016, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef _FSL_COMMON_H_ -#define _FSL_COMMON_H_ - -#include -#include -#include -#include - -#if defined(__ICCARM__) -#include -#endif - -#include "fsl_device_registers.h" - -/*! - * @addtogroup ksdk_common - * @{ - */ - -/******************************************************************************* - * Definitions - ******************************************************************************/ - -/*! @brief Construct a status code value from a group and code number. */ -#define MAKE_STATUS(group, code) ((((group)*100) + (code))) - -/*! @brief Construct the version number for drivers. */ -#define MAKE_VERSION(major, minor, bugfix) (((major) << 16) | ((minor) << 8) | (bugfix)) - -/* Debug console type definition. */ -#define DEBUG_CONSOLE_DEVICE_TYPE_NONE 0U /*!< No debug console. */ -#define DEBUG_CONSOLE_DEVICE_TYPE_UART 1U /*!< Debug console base on UART. */ -#define DEBUG_CONSOLE_DEVICE_TYPE_LPUART 2U /*!< Debug console base on LPUART. */ -#define DEBUG_CONSOLE_DEVICE_TYPE_LPSCI 3U /*!< Debug console base on LPSCI. */ -#define DEBUG_CONSOLE_DEVICE_TYPE_USBCDC 4U /*!< Debug console base on USBCDC. */ -#define DEBUG_CONSOLE_DEVICE_TYPE_FLEXCOMM 5U /*!< Debug console base on USBCDC. */ -#define DEBUG_CONSOLE_DEVICE_TYPE_IUART 6U /*!< Debug console base on i.MX UART. */ - -/*! @brief Status group numbers. */ -enum _status_groups -{ - kStatusGroup_Generic = 0, /*!< Group number for generic status codes. */ - kStatusGroup_FLASH = 1, /*!< Group number for FLASH status codes. */ - kStatusGroup_LPSPI = 4, /*!< Group number for LPSPI status codes. */ - kStatusGroup_FLEXIO_SPI = 5, /*!< Group number for FLEXIO SPI status codes. */ - kStatusGroup_DSPI = 6, /*!< Group number for DSPI status codes. */ - kStatusGroup_FLEXIO_UART = 7, /*!< Group number for FLEXIO UART status codes. */ - kStatusGroup_FLEXIO_I2C = 8, /*!< Group number for FLEXIO I2C status codes. */ - kStatusGroup_LPI2C = 9, /*!< Group number for LPI2C status codes. */ - kStatusGroup_UART = 10, /*!< Group number for UART status codes. */ - kStatusGroup_I2C = 11, /*!< Group number for UART status codes. */ - kStatusGroup_LPSCI = 12, /*!< Group number for LPSCI status codes. */ - kStatusGroup_LPUART = 13, /*!< Group number for LPUART status codes. */ - kStatusGroup_SPI = 14, /*!< Group number for SPI status code.*/ - kStatusGroup_XRDC = 15, /*!< Group number for XRDC status code.*/ - kStatusGroup_SEMA42 = 16, /*!< Group number for SEMA42 status code.*/ - kStatusGroup_SDHC = 17, /*!< Group number for SDHC status code */ - kStatusGroup_SDMMC = 18, /*!< Group number for SDMMC status code */ - kStatusGroup_SAI = 19, /*!< Group number for SAI status code */ - kStatusGroup_MCG = 20, /*!< Group number for MCG status codes. */ - kStatusGroup_SCG = 21, /*!< Group number for SCG status codes. */ - kStatusGroup_SDSPI = 22, /*!< Group number for SDSPI status codes. */ - kStatusGroup_FLEXIO_I2S = 23, /*!< Group number for FLEXIO I2S status codes */ - kStatusGroup_FLEXIO_MCULCD = 24, /*!< Group number for FLEXIO LCD status codes */ - kStatusGroup_FLASHIAP = 25, /*!< Group number for FLASHIAP status codes */ - kStatusGroup_FLEXCOMM_I2C = 26, /*!< Group number for FLEXCOMM I2C status codes */ - kStatusGroup_I2S = 27, /*!< Group number for I2S status codes */ - kStatusGroup_IUART = 28, /*!< Group number for IUART status codes */ - kStatusGroup_SDRAMC = 35, /*!< Group number for SDRAMC status codes. */ - kStatusGroup_POWER = 39, /*!< Group number for POWER status codes. */ - kStatusGroup_ENET = 40, /*!< Group number for ENET status codes. */ - kStatusGroup_PHY = 41, /*!< Group number for PHY status codes. */ - kStatusGroup_TRGMUX = 42, /*!< Group number for TRGMUX status codes. */ - kStatusGroup_SMARTCARD = 43, /*!< Group number for SMARTCARD status codes. */ - kStatusGroup_LMEM = 44, /*!< Group number for LMEM status codes. */ - kStatusGroup_QSPI = 45, /*!< Group number for QSPI status codes. */ - kStatusGroup_DMA = 50, /*!< Group number for DMA status codes. */ - kStatusGroup_EDMA = 51, /*!< Group number for EDMA status codes. */ - kStatusGroup_DMAMGR = 52, /*!< Group number for DMAMGR status codes. */ - kStatusGroup_FLEXCAN = 53, /*!< Group number for FlexCAN status codes. */ - kStatusGroup_LTC = 54, /*!< Group number for LTC status codes. */ - kStatusGroup_FLEXIO_CAMERA = 55, /*!< Group number for FLEXIO CAMERA status codes. */ - kStatusGroup_LPC_SPI = 56, /*!< Group number for LPC_SPI status codes. */ - kStatusGroup_LPC_USART = 57, /*!< Group number for LPC_USART status codes. */ - kStatusGroup_DMIC = 58, /*!< Group number for DMIC status codes. */ - kStatusGroup_SDIF = 59, /*!< Group number for SDIF status codes.*/ - kStatusGroup_SPIFI = 60, /*!< Group number for SPIFI status codes. */ - kStatusGroup_OTP = 61, /*!< Group number for OTP status codes. */ - kStatusGroup_MCAN = 62, /*!< Group number for MCAN status codes. */ - kStatusGroup_CAAM = 63, /*!< Group number for CAAM status codes. */ - kStatusGroup_ECSPI = 64, /*!< Group number for ECSPI status codes. */ - kStatusGroup_USDHC = 65, /*!< Group number for USDHC status codes.*/ - kStatusGroup_ESAI = 69, /*!< Group number for ESAI status codes. */ - kStatusGroup_FLEXSPI = 70, /*!< Group number for FLEXSPI status codes. */ - kStatusGroup_NOTIFIER = 98, /*!< Group number for NOTIFIER status codes. */ - kStatusGroup_DebugConsole = 99, /*!< Group number for debug console status codes. */ - kStatusGroup_ApplicationRangeStart = 100, /*!< Starting number for application groups. */ -}; - -/*! @brief Generic status return codes. */ -enum _generic_status -{ - kStatus_Success = MAKE_STATUS(kStatusGroup_Generic, 0), - kStatus_Fail = MAKE_STATUS(kStatusGroup_Generic, 1), - kStatus_ReadOnly = MAKE_STATUS(kStatusGroup_Generic, 2), - kStatus_OutOfRange = MAKE_STATUS(kStatusGroup_Generic, 3), - kStatus_InvalidArgument = MAKE_STATUS(kStatusGroup_Generic, 4), - kStatus_Timeout = MAKE_STATUS(kStatusGroup_Generic, 5), - kStatus_NoTransferInProgress = MAKE_STATUS(kStatusGroup_Generic, 6), -}; - -/*! @brief Type used for all status and error return values. */ -typedef int32_t status_t; - -/* - * The fsl_clock.h is included here because it needs MAKE_VERSION/MAKE_STATUS/status_t - * defined in previous of this file. - */ -#include "fsl_clock.h" - -/* - * Chip level peripheral reset API, for MCUs that implement peripheral reset control external to a peripheral - */ -#if ((defined(FSL_FEATURE_SOC_SYSCON_COUNT) && (FSL_FEATURE_SOC_SYSCON_COUNT > 0)) || \ - (defined(FSL_FEATURE_SOC_ASYNC_SYSCON_COUNT) && (FSL_FEATURE_SOC_ASYNC_SYSCON_COUNT > 0))) -#include "fsl_reset.h" -#endif - -/*! @name Min/max macros */ -/* @{ */ -#if !defined(MIN) -#define MIN(a, b) ((a) < (b) ? (a) : (b)) -#endif - -#if !defined(MAX) -#define MAX(a, b) ((a) > (b) ? (a) : (b)) -#endif -/* @} */ - -/*! @brief Computes the number of elements in an array. */ -#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0])) - -/*! @name UINT16_MAX/UINT32_MAX value */ -/* @{ */ -#if !defined(UINT16_MAX) -#define UINT16_MAX ((uint16_t)-1) -#endif - -#if !defined(UINT32_MAX) -#define UINT32_MAX ((uint32_t)-1) -#endif -/* @} */ - -/*! @name Timer utilities */ -/* @{ */ -/*! Macro to convert a microsecond period to raw count value */ -#define USEC_TO_COUNT(us, clockFreqInHz) (uint64_t)((uint64_t)us * clockFreqInHz / 1000000U) -/*! Macro to convert a raw count value to microsecond */ -#define COUNT_TO_USEC(count, clockFreqInHz) (uint64_t)((uint64_t)count * 1000000U / clockFreqInHz) - -/*! Macro to convert a millisecond period to raw count value */ -#define MSEC_TO_COUNT(ms, clockFreqInHz) (uint64_t)((uint64_t)ms * clockFreqInHz / 1000U) -/*! Macro to convert a raw count value to millisecond */ -#define COUNT_TO_MSEC(count, clockFreqInHz) (uint64_t)((uint64_t)count * 1000U / clockFreqInHz) -/* @} */ - -/******************************************************************************* - * API - ******************************************************************************/ - -#if defined(__cplusplus) -extern "C" { -#endif - -/*! - * @brief Enable specific interrupt. - * - * Enable the interrupt not routed from intmux. - * - * @param interrupt The IRQ number. - */ -static inline void EnableIRQ(IRQn_Type interrupt) -{ - if (NotAvail_IRQn == interrupt) - { - return; - } - -#if defined(FSL_FEATURE_SOC_INTMUX_COUNT) && (FSL_FEATURE_SOC_INTMUX_COUNT > 0) - if (interrupt < FSL_FEATURE_INTMUX_IRQ_START_INDEX) -#endif - { -#if defined(__GIC_PRIO_BITS) - GIC_EnableIRQ(interrupt); -#else - NVIC_EnableIRQ(interrupt); -#endif - } -} - -/*! - * @brief Disable specific interrupt. - * - * Disable the interrupt not routed from intmux. - * - * @param interrupt The IRQ number. - */ -static inline void DisableIRQ(IRQn_Type interrupt) -{ - if (NotAvail_IRQn == interrupt) - { - return; - } - -#if defined(FSL_FEATURE_SOC_INTMUX_COUNT) && (FSL_FEATURE_SOC_INTMUX_COUNT > 0) - if (interrupt < FSL_FEATURE_INTMUX_IRQ_START_INDEX) -#endif - { -#if defined(__GIC_PRIO_BITS) - GIC_DisableIRQ(interrupt); -#else - NVIC_DisableIRQ(interrupt); -#endif - } -} - -/*! - * @brief Disable the global IRQ - * - * Disable the global interrupt and return the current primask register. User is required to provided the primask - * register for the EnableGlobalIRQ(). - * - * @return Current primask value. - */ -static inline uint32_t DisableGlobalIRQ(void) -{ -#if defined(CPSR_I_Msk) - uint32_t cpsr = __get_CPSR() & CPSR_I_Msk; - - __disable_irq(); - - return cpsr; -#else - uint32_t regPrimask = __get_PRIMASK(); - - __disable_irq(); - - return regPrimask; -#endif -} - -/*! - * @brief Enaable the global IRQ - * - * Set the primask register with the provided primask value but not just enable the primask. The idea is for the - * convinience of integration of RTOS. some RTOS get its own management mechanism of primask. User is required to - * use the EnableGlobalIRQ() and DisableGlobalIRQ() in pair. - * - * @param primask value of primask register to be restored. The primask value is supposed to be provided by the - * DisableGlobalIRQ(). - */ -static inline void EnableGlobalIRQ(uint32_t primask) -{ -#if defined(CPSR_I_Msk) - __set_CPSR((__get_CPSR() & ~CPSR_I_Msk) | primask); -#else - __set_PRIMASK(primask); -#endif -} - -/*! - * @brief install IRQ handler - * - * @param irq IRQ number - * @param irqHandler IRQ handler address - * @return The old IRQ handler address - */ -uint32_t InstallIRQHandler(IRQn_Type irq, uint32_t irqHandler); - -#if (defined(FSL_FEATURE_SOC_SYSCON_COUNT) && (FSL_FEATURE_SOC_SYSCON_COUNT > 0)) -/*! - * @brief Enable specific interrupt for wake-up from deep-sleep mode. - * - * Enable the interrupt for wake-up from deep sleep mode. - * Some interrupts are typically used in sleep mode only and will not occur during - * deep-sleep mode because relevant clocks are stopped. However, it is possible to enable - * those clocks (significantly increasing power consumption in the reduced power mode), - * making these wake-ups possible. - * - * @note This function also enables the interrupt in the NVIC (EnableIRQ() is called internally). - * - * @param interrupt The IRQ number. - */ -void EnableDeepSleepIRQ(IRQn_Type interrupt); - -/*! - * @brief Disable specific interrupt for wake-up from deep-sleep mode. - * - * Disable the interrupt for wake-up from deep sleep mode. - * Some interrupts are typically used in sleep mode only and will not occur during - * deep-sleep mode because relevant clocks are stopped. However, it is possible to enable - * those clocks (significantly increasing power consumption in the reduced power mode), - * making these wake-ups possible. - * - * @note This function also disables the interrupt in the NVIC (DisableIRQ() is called internally). - * - * @param interrupt The IRQ number. - */ -void DisableDeepSleepIRQ(IRQn_Type interrupt); -#endif /* FSL_FEATURE_SOC_SYSCON_COUNT */ - -#if defined(__cplusplus) -} -#endif - -/*! @} */ - -#endif /* _FSL_COMMON_H_ */ diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_crc.c b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_crc.c deleted file mode 100644 index dba1db8c463..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_crc.c +++ /dev/null @@ -1,282 +0,0 @@ -/* - * Copyright (c) 2015-2016, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -#include "fsl_crc.h" - -/******************************************************************************* - * Definitions - ******************************************************************************/ -/*! @internal @brief Has data register with name CRC. */ -#if defined(FSL_FEATURE_CRC_HAS_CRC_REG) && FSL_FEATURE_CRC_HAS_CRC_REG -#define DATA CRC -#define DATALL CRCLL -#endif - -#if defined(CRC_DRIVER_USE_CRC16_CCIT_FALSE_AS_DEFAULT) && CRC_DRIVER_USE_CRC16_CCIT_FALSE_AS_DEFAULT -/* @brief Default user configuration structure for CRC-16-CCITT */ -#define CRC_DRIVER_DEFAULT_POLYNOMIAL 0x1021U -/*< CRC-16-CCIT polynomial x**16 + x**12 + x**5 + x**0 */ -#define CRC_DRIVER_DEFAULT_SEED 0xFFFFU -/*< Default initial checksum */ -#define CRC_DRIVER_DEFAULT_REFLECT_IN false -/*< Default is no transpose */ -#define CRC_DRIVER_DEFAULT_REFLECT_OUT false -/*< Default is transpose bytes */ -#define CRC_DRIVER_DEFAULT_COMPLEMENT_CHECKSUM false -/*< Default is without complement of CRC data register read data */ -#define CRC_DRIVER_DEFAULT_CRC_BITS kCrcBits16 -/*< Default is 16-bit CRC protocol */ -#define CRC_DRIVER_DEFAULT_CRC_RESULT kCrcFinalChecksum -/*< Default is resutl type is final checksum */ -#endif /* CRC_DRIVER_USE_CRC16_CCIT_FALSE_AS_DEFAULT */ - -/*! @brief CRC type of transpose of read write data */ -typedef enum _crc_transpose_type -{ - kCrcTransposeNone = 0U, /*! No transpose */ - kCrcTransposeBits = 1U, /*! Tranpose bits in bytes */ - kCrcTransposeBitsAndBytes = 2U, /*! Transpose bytes and bits in bytes */ - kCrcTransposeBytes = 3U, /*! Transpose bytes */ -} crc_transpose_type_t; - -/*! -* @brief CRC module configuration. -* -* This structure holds the configuration for the CRC module. -*/ -typedef struct _crc_module_config -{ - uint32_t polynomial; /*!< CRC Polynomial, MSBit first.@n - Example polynomial: 0x1021 = 1_0000_0010_0001 = x^12+x^5+1 */ - uint32_t seed; /*!< Starting checksum value */ - crc_transpose_type_t readTranspose; /*!< Type of transpose when reading CRC result. */ - crc_transpose_type_t writeTranspose; /*!< Type of transpose when writing CRC input data. */ - bool complementChecksum; /*!< True if the result shall be complement of the actual checksum. */ - crc_bits_t crcBits; /*!< Selects 16- or 32- bit CRC protocol. */ -} crc_module_config_t; - -/******************************************************************************* - * Code - ******************************************************************************/ - -/*! - * @brief Returns transpose type for CRC protocol reflect in parameter. - * - * This functions helps to set writeTranspose member of crc_config_t structure. Reflect in is CRC protocol parameter. - * - * @param enable True or false for the selected CRC protocol Reflect In (refin) parameter. - */ -static inline crc_transpose_type_t CRC_GetTransposeTypeFromReflectIn(bool enable) -{ - return ((enable) ? kCrcTransposeBitsAndBytes : kCrcTransposeBytes); -} - -/*! - * @brief Returns transpose type for CRC protocol reflect out parameter. - * - * This functions helps to set readTranspose member of crc_config_t structure. Reflect out is CRC protocol parameter. - * - * @param enable True or false for the selected CRC protocol Reflect Out (refout) parameter. - */ -static inline crc_transpose_type_t CRC_GetTransposeTypeFromReflectOut(bool enable) -{ - return ((enable) ? kCrcTransposeBitsAndBytes : kCrcTransposeNone); -} - -/*! - * @brief Starts checksum computation. - * - * Configures the CRC module for the specified CRC protocol. @n - * Starts the checksum computation by writing the seed value - * - * @param base CRC peripheral address. - * @param config Pointer to protocol configuration structure. - */ -static void CRC_ConfigureAndStart(CRC_Type *base, const crc_module_config_t *config) -{ - uint32_t crcControl; - - /* pre-compute value for CRC control registger based on user configuraton without WAS field */ - crcControl = 0 | CRC_CTRL_TOT(config->writeTranspose) | CRC_CTRL_TOTR(config->readTranspose) | - CRC_CTRL_FXOR(config->complementChecksum) | CRC_CTRL_TCRC(config->crcBits); - - /* make sure the control register is clear - WAS is deasserted, and protocol is set */ - base->CTRL = crcControl; - - /* write polynomial register */ - base->GPOLY = config->polynomial; - - /* write pre-computed control register value along with WAS to start checksum computation */ - base->CTRL = crcControl | CRC_CTRL_WAS(true); - - /* write seed (initial checksum) */ - base->DATA = config->seed; - - /* deassert WAS by writing pre-computed CRC control register value */ - base->CTRL = crcControl; -} - -/*! - * @brief Starts final checksum computation. - * - * Configures the CRC module for the specified CRC protocol. @n - * Starts final checksum computation by writing the seed value. - * @note CRC_Get16bitResult() or CRC_Get32bitResult() return final checksum - * (output reflection and xor functions are applied). - * - * @param base CRC peripheral address. - * @param protocolConfig Pointer to protocol configuration structure. - */ -static void CRC_SetProtocolConfig(CRC_Type *base, const crc_config_t *protocolConfig) -{ - crc_module_config_t moduleConfig; - /* convert protocol to CRC peripheral module configuration, prepare for final checksum */ - moduleConfig.polynomial = protocolConfig->polynomial; - moduleConfig.seed = protocolConfig->seed; - moduleConfig.readTranspose = CRC_GetTransposeTypeFromReflectOut(protocolConfig->reflectOut); - moduleConfig.writeTranspose = CRC_GetTransposeTypeFromReflectIn(protocolConfig->reflectIn); - moduleConfig.complementChecksum = protocolConfig->complementChecksum; - moduleConfig.crcBits = protocolConfig->crcBits; - - CRC_ConfigureAndStart(base, &moduleConfig); -} - -/*! - * @brief Starts intermediate checksum computation. - * - * Configures the CRC module for the specified CRC protocol. @n - * Starts intermediate checksum computation by writing the seed value. - * @note CRC_Get16bitResult() or CRC_Get32bitResult() return intermediate checksum (raw data register value). - * - * @param base CRC peripheral address. - * @param protocolConfig Pointer to protocol configuration structure. - */ -static void CRC_SetRawProtocolConfig(CRC_Type *base, const crc_config_t *protocolConfig) -{ - crc_module_config_t moduleConfig; - /* convert protocol to CRC peripheral module configuration, prepare for intermediate checksum */ - moduleConfig.polynomial = protocolConfig->polynomial; - moduleConfig.seed = protocolConfig->seed; - moduleConfig.readTranspose = - kCrcTransposeNone; /* intermediate checksum does no transpose of data register read value */ - moduleConfig.writeTranspose = CRC_GetTransposeTypeFromReflectIn(protocolConfig->reflectIn); - moduleConfig.complementChecksum = false; /* intermediate checksum does no xor of data register read value */ - moduleConfig.crcBits = protocolConfig->crcBits; - - CRC_ConfigureAndStart(base, &moduleConfig); -} - -void CRC_Init(CRC_Type *base, const crc_config_t *config) -{ -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) - /* ungate clock */ - CLOCK_EnableClock(kCLOCK_Crc0); -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ - /* configure CRC module and write the seed */ - if (config->crcResult == kCrcFinalChecksum) - { - CRC_SetProtocolConfig(base, config); - } - else - { - CRC_SetRawProtocolConfig(base, config); - } -} - -void CRC_GetDefaultConfig(crc_config_t *config) -{ - static const crc_config_t crc16ccit = { - CRC_DRIVER_DEFAULT_POLYNOMIAL, CRC_DRIVER_DEFAULT_SEED, - CRC_DRIVER_DEFAULT_REFLECT_IN, CRC_DRIVER_DEFAULT_REFLECT_OUT, - CRC_DRIVER_DEFAULT_COMPLEMENT_CHECKSUM, CRC_DRIVER_DEFAULT_CRC_BITS, - CRC_DRIVER_DEFAULT_CRC_RESULT, - }; - - *config = crc16ccit; -} - -void CRC_WriteData(CRC_Type *base, const uint8_t *data, size_t dataSize) -{ - const uint32_t *data32; - - /* 8-bit reads and writes till source address is aligned 4 bytes */ - while ((dataSize) && ((uint32_t)data & 3U)) - { - base->ACCESS8BIT.DATALL = *data; - data++; - dataSize--; - } - - /* use 32-bit reads and writes as long as possible */ - data32 = (const uint32_t *)data; - while (dataSize >= sizeof(uint32_t)) - { - base->DATA = *data32; - data32++; - dataSize -= sizeof(uint32_t); - } - - data = (const uint8_t *)data32; - - /* 8-bit reads and writes till end of data buffer */ - while (dataSize) - { - base->ACCESS8BIT.DATALL = *data; - data++; - dataSize--; - } -} - -uint32_t CRC_Get32bitResult(CRC_Type *base) -{ - return base->DATA; -} - -uint16_t CRC_Get16bitResult(CRC_Type *base) -{ - uint32_t retval; - uint32_t totr; /* type of transpose read bitfield */ - - retval = base->DATA; - totr = (base->CTRL & CRC_CTRL_TOTR_MASK) >> CRC_CTRL_TOTR_SHIFT; - - /* check transpose type to get 16-bit out of 32-bit register */ - if (totr >= 2U) - { - /* transpose of bytes for read is set, the result CRC is in CRC_DATA[HU:HL] */ - retval &= 0xFFFF0000U; - retval = retval >> 16U; - } - else - { - /* no transpose of bytes for read, the result CRC is in CRC_DATA[LU:LL] */ - retval &= 0x0000FFFFU; - } - return (uint16_t)retval; -} diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_crc.h b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_crc.h deleted file mode 100644 index 247a9bac781..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_crc.h +++ /dev/null @@ -1,193 +0,0 @@ -/* - * Copyright (c) 2015-2016, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef _FSL_CRC_H_ -#define _FSL_CRC_H_ - -#include "fsl_common.h" - -/*! - * @addtogroup crc - * @{ - */ - -/******************************************************************************* - * Definitions - ******************************************************************************/ - -/*! @name Driver version */ -/*@{*/ -/*! @brief CRC driver version. Version 2.0.1. - * - * Current version: 2.0.1 - * - * Change log: - * - Version 2.0.1 - * - move DATA and DATALL macro definition from header file to source file - */ -#define FSL_CRC_DRIVER_VERSION (MAKE_VERSION(2, 0, 1)) -/*@}*/ - -#ifndef CRC_DRIVER_CUSTOM_DEFAULTS -/*! @brief Default configuration structure filled by CRC_GetDefaultConfig(). Use CRC16-CCIT-FALSE as defeault. */ -#define CRC_DRIVER_USE_CRC16_CCIT_FALSE_AS_DEFAULT 1 -#endif - -/*! @brief CRC bit width */ -typedef enum _crc_bits -{ - kCrcBits16 = 0U, /*!< Generate 16-bit CRC code */ - kCrcBits32 = 1U /*!< Generate 32-bit CRC code */ -} crc_bits_t; - -/*! @brief CRC result type */ -typedef enum _crc_result -{ - kCrcFinalChecksum = 0U, /*!< CRC data register read value is the final checksum. - Reflect out and final xor protocol features are applied. */ - kCrcIntermediateChecksum = 1U /*!< CRC data register read value is intermediate checksum (raw value). - Reflect out and final xor protocol feature are not applied. - Intermediate checksum can be used as a seed for CRC_Init() - to continue adding data to this checksum. */ -} crc_result_t; - -/*! -* @brief CRC protocol configuration. -* -* This structure holds the configuration for the CRC protocol. -* -*/ -typedef struct _crc_config -{ - uint32_t polynomial; /*!< CRC Polynomial, MSBit first. - Example polynomial: 0x1021 = 1_0000_0010_0001 = x^12+x^5+1 */ - uint32_t seed; /*!< Starting checksum value */ - bool reflectIn; /*!< Reflect bits on input. */ - bool reflectOut; /*!< Reflect bits on output. */ - bool complementChecksum; /*!< True if the result shall be complement of the actual checksum. */ - crc_bits_t crcBits; /*!< Selects 16- or 32- bit CRC protocol. */ - crc_result_t crcResult; /*!< Selects final or intermediate checksum return from CRC_Get16bitResult() or - CRC_Get32bitResult() */ -} crc_config_t; - -/******************************************************************************* - * API - ******************************************************************************/ -#if defined(__cplusplus) -extern "C" { -#endif - -/*! - * @brief Enables and configures the CRC peripheral module. - * - * This function enables the clock gate in the SIM module for the CRC peripheral. - * It also configures the CRC module and starts a checksum computation by writing the seed. - * - * @param base CRC peripheral address. - * @param config CRC module configuration structure. - */ -void CRC_Init(CRC_Type *base, const crc_config_t *config); - -/*! - * @brief Disables the CRC peripheral module. - * - * This function disables the clock gate in the SIM module for the CRC peripheral. - * - * @param base CRC peripheral address. - */ -static inline void CRC_Deinit(CRC_Type *base) -{ -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) - /* gate clock */ - CLOCK_DisableClock(kCLOCK_Crc0); -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ -} - -/*! - * @brief Loads default values to the CRC protocol configuration structure. - * - * Loads default values to the CRC protocol configuration structure. The default values are as follows. - * @code - * config->polynomial = 0x1021; - * config->seed = 0xFFFF; - * config->reflectIn = false; - * config->reflectOut = false; - * config->complementChecksum = false; - * config->crcBits = kCrcBits16; - * config->crcResult = kCrcFinalChecksum; - * @endcode - * - * @param config CRC protocol configuration structure. - */ -void CRC_GetDefaultConfig(crc_config_t *config); - -/*! - * @brief Writes data to the CRC module. - * - * Writes input data buffer bytes to the CRC data register. - * The configured type of transpose is applied. - * - * @param base CRC peripheral address. - * @param data Input data stream, MSByte in data[0]. - * @param dataSize Size in bytes of the input data buffer. - */ -void CRC_WriteData(CRC_Type *base, const uint8_t *data, size_t dataSize); - -/*! - * @brief Reads the 32-bit checksum from the CRC module. - * - * Reads the CRC data register (either an intermediate or the final checksum). - * The configured type of transpose and complement is applied. - * - * @param base CRC peripheral address. - * @return An intermediate or the final 32-bit checksum, after configured transpose and complement operations. - */ -uint32_t CRC_Get32bitResult(CRC_Type *base); - -/*! - * @brief Reads a 16-bit checksum from the CRC module. - * - * Reads the CRC data register (either an intermediate or the final checksum). - * The configured type of transpose and complement is applied. - * - * @param base CRC peripheral address. - * @return An intermediate or the final 16-bit checksum, after configured transpose and complement operations. - */ -uint16_t CRC_Get16bitResult(CRC_Type *base); - -#if defined(__cplusplus) -} -#endif - -/*! - *@} - */ - -#endif /* _FSL_CRC_H_ */ diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_dac.c b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_dac.c deleted file mode 100644 index 8d13d622835..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_dac.c +++ /dev/null @@ -1,220 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "fsl_dac.h" - -/******************************************************************************* - * Prototypes - ******************************************************************************/ -/*! - * @brief Get instance number for DAC module. - * - * @param base DAC peripheral base address - */ -static uint32_t DAC_GetInstance(DAC_Type *base); - -/******************************************************************************* - * Variables - ******************************************************************************/ -/*! @brief Pointers to DAC bases for each instance. */ -static DAC_Type *const s_dacBases[] = DAC_BASE_PTRS; -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) -/*! @brief Pointers to DAC clocks for each instance. */ -static const clock_ip_name_t s_dacClocks[] = DAC_CLOCKS; -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ - -/******************************************************************************* - * Codes - ******************************************************************************/ -static uint32_t DAC_GetInstance(DAC_Type *base) -{ - uint32_t instance; - - /* Find the instance index from base address mappings. */ - for (instance = 0; instance < ARRAY_SIZE(s_dacBases); instance++) - { - if (s_dacBases[instance] == base) - { - break; - } - } - - assert(instance < ARRAY_SIZE(s_dacBases)); - - return instance; -} - -void DAC_Init(DAC_Type *base, const dac_config_t *config) -{ - assert(NULL != config); - - uint8_t tmp8; - -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) - /* Enable the clock. */ - CLOCK_EnableClock(s_dacClocks[DAC_GetInstance(base)]); -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ - - /* Configure. */ - /* DACx_C0. */ - tmp8 = base->C0 & ~(DAC_C0_DACRFS_MASK | DAC_C0_LPEN_MASK); - if (kDAC_ReferenceVoltageSourceVref2 == config->referenceVoltageSource) - { - tmp8 |= DAC_C0_DACRFS_MASK; - } - if (config->enableLowPowerMode) - { - tmp8 |= DAC_C0_LPEN_MASK; - } - base->C0 = tmp8; - - /* DAC_Enable(base, true); */ - /* Tip: The DAC output can be enabled till then after user sets their own available data in application. */ -} - -void DAC_Deinit(DAC_Type *base) -{ - DAC_Enable(base, false); - -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) - /* Disable the clock. */ - CLOCK_DisableClock(s_dacClocks[DAC_GetInstance(base)]); -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ -} - -void DAC_GetDefaultConfig(dac_config_t *config) -{ - assert(NULL != config); - - config->referenceVoltageSource = kDAC_ReferenceVoltageSourceVref2; - config->enableLowPowerMode = false; -} - -void DAC_SetBufferConfig(DAC_Type *base, const dac_buffer_config_t *config) -{ - assert(NULL != config); - - uint8_t tmp8; - - /* DACx_C0. */ - tmp8 = base->C0 & ~(DAC_C0_DACTRGSEL_MASK); - if (kDAC_BufferTriggerBySoftwareMode == config->triggerMode) - { - tmp8 |= DAC_C0_DACTRGSEL_MASK; - } - base->C0 = tmp8; - - /* DACx_C1. */ - tmp8 = base->C1 & - ~( -#if defined(FSL_FEATURE_DAC_HAS_WATERMARK_SELECTION) && FSL_FEATURE_DAC_HAS_WATERMARK_SELECTION - DAC_C1_DACBFWM_MASK | -#endif /* FSL_FEATURE_DAC_HAS_WATERMARK_SELECTION */ - DAC_C1_DACBFMD_MASK); -#if defined(FSL_FEATURE_DAC_HAS_WATERMARK_SELECTION) && FSL_FEATURE_DAC_HAS_WATERMARK_SELECTION - tmp8 |= DAC_C1_DACBFWM(config->watermark); -#endif /* FSL_FEATURE_DAC_HAS_WATERMARK_SELECTION */ - tmp8 |= DAC_C1_DACBFMD(config->workMode); - base->C1 = tmp8; - - /* DACx_C2. */ - tmp8 = base->C2 & ~DAC_C2_DACBFUP_MASK; - tmp8 |= DAC_C2_DACBFUP(config->upperLimit); - base->C2 = tmp8; -} - -void DAC_GetDefaultBufferConfig(dac_buffer_config_t *config) -{ - assert(NULL != config); - - config->triggerMode = kDAC_BufferTriggerBySoftwareMode; -#if defined(FSL_FEATURE_DAC_HAS_WATERMARK_SELECTION) && FSL_FEATURE_DAC_HAS_WATERMARK_SELECTION - config->watermark = kDAC_BufferWatermark1Word; -#endif /* FSL_FEATURE_DAC_HAS_WATERMARK_SELECTION */ - config->workMode = kDAC_BufferWorkAsNormalMode; - config->upperLimit = DAC_DATL_COUNT - 1U; -} - -void DAC_SetBufferValue(DAC_Type *base, uint8_t index, uint16_t value) -{ - assert(index < DAC_DATL_COUNT); - - base->DAT[index].DATL = (uint8_t)(0xFFU & value); /* Low 8-bit. */ - base->DAT[index].DATH = (uint8_t)((0xF00U & value) >> 8); /* High 4-bit. */ -} - -void DAC_SetBufferReadPointer(DAC_Type *base, uint8_t index) -{ - assert(index < DAC_DATL_COUNT); - - uint8_t tmp8 = base->C2 & ~DAC_C2_DACBFRP_MASK; - - tmp8 |= DAC_C2_DACBFRP(index); - base->C2 = tmp8; -} - -void DAC_EnableBufferInterrupts(DAC_Type *base, uint32_t mask) -{ - mask &= ( -#if defined(FSL_FEATURE_DAC_HAS_WATERMARK_DETECTION) && FSL_FEATURE_DAC_HAS_WATERMARK_DETECTION - DAC_C0_DACBWIEN_MASK | -#endif /* FSL_FEATURE_DAC_HAS_WATERMARK_DETECTION */ - DAC_C0_DACBTIEN_MASK | DAC_C0_DACBBIEN_MASK); - base->C0 |= ((uint8_t)mask); /* Write 1 to enable. */ -} - -void DAC_DisableBufferInterrupts(DAC_Type *base, uint32_t mask) -{ - mask &= ( -#if defined(FSL_FEATURE_DAC_HAS_WATERMARK_DETECTION) && FSL_FEATURE_DAC_HAS_WATERMARK_DETECTION - DAC_C0_DACBWIEN_MASK | -#endif /* FSL_FEATURE_DAC_HAS_WATERMARK_DETECTION */ - DAC_C0_DACBTIEN_MASK | DAC_C0_DACBBIEN_MASK); - base->C0 &= (uint8_t)(~((uint8_t)mask)); /* Write 0 to disable. */ -} - -uint32_t DAC_GetBufferStatusFlags(DAC_Type *base) -{ - return (uint32_t)(base->SR & ( -#if defined(FSL_FEATURE_DAC_HAS_WATERMARK_DETECTION) && FSL_FEATURE_DAC_HAS_WATERMARK_DETECTION - DAC_SR_DACBFWMF_MASK | -#endif /* FSL_FEATURE_DAC_HAS_WATERMARK_DETECTION */ - DAC_SR_DACBFRPTF_MASK | DAC_SR_DACBFRPBF_MASK)); -} - -void DAC_ClearBufferStatusFlags(DAC_Type *base, uint32_t mask) -{ - mask &= ( -#if defined(FSL_FEATURE_DAC_HAS_WATERMARK_DETECTION) && FSL_FEATURE_DAC_HAS_WATERMARK_DETECTION - DAC_SR_DACBFWMF_MASK | -#endif /* FSL_FEATURE_DAC_HAS_WATERMARK_DETECTION */ - DAC_SR_DACBFRPTF_MASK | DAC_SR_DACBFRPBF_MASK); - base->SR &= (uint8_t)(~((uint8_t)mask)); /* Write 0 to clear flags. */ -} diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_dac.h b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_dac.h deleted file mode 100644 index b71febf3bc3..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_dac.h +++ /dev/null @@ -1,378 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef _FSL_DAC_H_ -#define _FSL_DAC_H_ - -#include "fsl_common.h" - -/*! - * @addtogroup dac - * @{ - */ - - -/******************************************************************************* - * Definitions - ******************************************************************************/ - -/*! @name Driver version */ -/*@{*/ -/*! @brief DAC driver version 2.0.1. */ -#define FSL_DAC_DRIVER_VERSION (MAKE_VERSION(2, 0, 1)) -/*@}*/ - -/*! - * @brief DAC buffer flags. - */ -enum _dac_buffer_status_flags -{ -#if defined(FSL_FEATURE_DAC_HAS_WATERMARK_DETECTION) && FSL_FEATURE_DAC_HAS_WATERMARK_DETECTION - kDAC_BufferWatermarkFlag = DAC_SR_DACBFWMF_MASK, /*!< DAC Buffer Watermark Flag. */ -#endif /* FSL_FEATURE_DAC_HAS_WATERMARK_DETECTION */ - kDAC_BufferReadPointerTopPositionFlag = DAC_SR_DACBFRPTF_MASK, /*!< DAC Buffer Read Pointer Top Position Flag. */ - kDAC_BufferReadPointerBottomPositionFlag = DAC_SR_DACBFRPBF_MASK, /*!< DAC Buffer Read Pointer Bottom Position - Flag. */ -}; - -/*! - * @brief DAC buffer interrupts. - */ -enum _dac_buffer_interrupt_enable -{ -#if defined(FSL_FEATURE_DAC_HAS_WATERMARK_DETECTION) && FSL_FEATURE_DAC_HAS_WATERMARK_DETECTION - kDAC_BufferWatermarkInterruptEnable = DAC_C0_DACBWIEN_MASK, /*!< DAC Buffer Watermark Interrupt Enable. */ -#endif /* FSL_FEATURE_DAC_HAS_WATERMARK_DETECTION */ - kDAC_BufferReadPointerTopInterruptEnable = DAC_C0_DACBTIEN_MASK, /*!< DAC Buffer Read Pointer Top Flag Interrupt - Enable. */ - kDAC_BufferReadPointerBottomInterruptEnable = DAC_C0_DACBBIEN_MASK, /*!< DAC Buffer Read Pointer Bottom Flag - Interrupt Enable */ -}; - -/*! - * @brief DAC reference voltage source. - */ -typedef enum _dac_reference_voltage_source -{ - kDAC_ReferenceVoltageSourceVref1 = 0U, /*!< The DAC selects DACREF_1 as the reference voltage. */ - kDAC_ReferenceVoltageSourceVref2 = 1U, /*!< The DAC selects DACREF_2 as the reference voltage. */ -} dac_reference_voltage_source_t; - -/*! - * @brief DAC buffer trigger mode. - */ -typedef enum _dac_buffer_trigger_mode -{ - kDAC_BufferTriggerByHardwareMode = 0U, /*!< The DAC hardware trigger is selected. */ - kDAC_BufferTriggerBySoftwareMode = 1U, /*!< The DAC software trigger is selected. */ -} dac_buffer_trigger_mode_t; - -#if defined(FSL_FEATURE_DAC_HAS_WATERMARK_SELECTION) && FSL_FEATURE_DAC_HAS_WATERMARK_SELECTION -/*! - * @brief DAC buffer watermark. - */ -typedef enum _dac_buffer_watermark -{ -#if defined(FSL_FEATURE_DAC_HAS_WATERMARK_1_WORD) && FSL_FEATURE_DAC_HAS_WATERMARK_1_WORD - kDAC_BufferWatermark1Word = 0U, /*!< 1 word away from the upper limit. */ -#endif /* FSL_FEATURE_DAC_HAS_WATERMARK_1_WORD */ -#if defined(FSL_FEATURE_DAC_HAS_WATERMARK_2_WORDS) && FSL_FEATURE_DAC_HAS_WATERMARK_2_WORDS - kDAC_BufferWatermark2Word = 1U, /*!< 2 words away from the upper limit. */ -#endif /* FSL_FEATURE_DAC_HAS_WATERMARK_2_WORDS */ -#if defined(FSL_FEATURE_DAC_HAS_WATERMARK_3_WORDS) && FSL_FEATURE_DAC_HAS_WATERMARK_3_WORDS - kDAC_BufferWatermark3Word = 2U, /*!< 3 words away from the upper limit. */ -#endif /* FSL_FEATURE_DAC_HAS_WATERMARK_3_WORDS */ -#if defined(FSL_FEATURE_DAC_HAS_WATERMARK_4_WORDS) && FSL_FEATURE_DAC_HAS_WATERMARK_4_WORDS - kDAC_BufferWatermark4Word = 3U, /*!< 4 words away from the upper limit. */ -#endif /* FSL_FEATURE_DAC_HAS_WATERMARK_4_WORDS */ -} dac_buffer_watermark_t; -#endif /* FSL_FEATURE_DAC_HAS_WATERMARK_SELECTION */ - -/*! - * @brief DAC buffer work mode. - */ -typedef enum _dac_buffer_work_mode -{ - kDAC_BufferWorkAsNormalMode = 0U, /*!< Normal mode. */ -#if defined(FSL_FEATURE_DAC_HAS_BUFFER_SWING_MODE) && FSL_FEATURE_DAC_HAS_BUFFER_SWING_MODE - kDAC_BufferWorkAsSwingMode, /*!< Swing mode. */ -#endif /* FSL_FEATURE_DAC_HAS_BUFFER_SWING_MODE */ - kDAC_BufferWorkAsOneTimeScanMode, /*!< One-Time Scan mode. */ -#if defined(FSL_FEATURE_DAC_HAS_BUFFER_FIFO_MODE) && FSL_FEATURE_DAC_HAS_BUFFER_FIFO_MODE - kDAC_BufferWorkAsFIFOMode, /*!< FIFO mode. */ -#endif /* FSL_FEATURE_DAC_HAS_BUFFER_FIFO_MODE */ -} dac_buffer_work_mode_t; - -/*! - * @brief DAC module configuration. - */ -typedef struct _dac_config -{ - dac_reference_voltage_source_t referenceVoltageSource; /*!< Select the DAC reference voltage source. */ - bool enableLowPowerMode; /*!< Enable the low-power mode. */ -} dac_config_t; - -/*! - * @brief DAC buffer configuration. - */ -typedef struct _dac_buffer_config -{ - dac_buffer_trigger_mode_t triggerMode; /*!< Select the buffer's trigger mode. */ -#if defined(FSL_FEATURE_DAC_HAS_WATERMARK_SELECTION) && FSL_FEATURE_DAC_HAS_WATERMARK_SELECTION - dac_buffer_watermark_t watermark; /*!< Select the buffer's watermark. */ -#endif /* FSL_FEATURE_DAC_HAS_WATERMARK_SELECTION */ - dac_buffer_work_mode_t workMode; /*!< Select the buffer's work mode. */ - uint8_t upperLimit; /*!< Set the upper limit for the buffer index. - Normally, 0-15 is available for a buffer with 16 items. */ -} dac_buffer_config_t; - -/******************************************************************************* - * API - ******************************************************************************/ -#if defined(__cplusplus) -extern "C" { -#endif - -/*! - * @name Initialization - * @{ - */ - -/*! - * @brief Initializes the DAC module. - * - * This function initializes the DAC module including the following operations. - * - Enabling the clock for DAC module. - * - Configuring the DAC converter with a user configuration. - * - Enabling the DAC module. - * - * @param base DAC peripheral base address. - * @param config Pointer to the configuration structure. See "dac_config_t". - */ -void DAC_Init(DAC_Type *base, const dac_config_t *config); - -/*! - * @brief De-initializes the DAC module. - * - * This function de-initializes the DAC module including the following operations. - * - Disabling the DAC module. - * - Disabling the clock for the DAC module. - * - * @param base DAC peripheral base address. - */ -void DAC_Deinit(DAC_Type *base); - -/*! - * @brief Initializes the DAC user configuration structure. - * - * This function initializes the user configuration structure to a default value. The default values are as follows. - * @code - * config->referenceVoltageSource = kDAC_ReferenceVoltageSourceVref2; - * config->enableLowPowerMode = false; - * @endcode - * @param config Pointer to the configuration structure. See "dac_config_t". - */ -void DAC_GetDefaultConfig(dac_config_t *config); - -/*! - * @brief Enables the DAC module. - * - * @param base DAC peripheral base address. - * @param enable Enables or disables the feature. - */ -static inline void DAC_Enable(DAC_Type *base, bool enable) -{ - if (enable) - { - base->C0 |= DAC_C0_DACEN_MASK; - } - else - { - base->C0 &= ~DAC_C0_DACEN_MASK; - } -} - -/* @} */ - -/*! - * @name Buffer - * @{ - */ - -/*! - * @brief Enables the DAC buffer. - * - * @param base DAC peripheral base address. - * @param enable Enables or disables the feature. - */ -static inline void DAC_EnableBuffer(DAC_Type *base, bool enable) -{ - if (enable) - { - base->C1 |= DAC_C1_DACBFEN_MASK; - } - else - { - base->C1 &= ~DAC_C1_DACBFEN_MASK; - } -} - -/*! - * @brief Configures the CMP buffer. - * - * @param base DAC peripheral base address. - * @param config Pointer to the configuration structure. See "dac_buffer_config_t". - */ -void DAC_SetBufferConfig(DAC_Type *base, const dac_buffer_config_t *config); - -/*! - * @brief Initializes the DAC buffer configuration structure. - * - * This function initializes the DAC buffer configuration structure to default values. The default values are as follows. - * @code - * config->triggerMode = kDAC_BufferTriggerBySoftwareMode; - * config->watermark = kDAC_BufferWatermark1Word; - * config->workMode = kDAC_BufferWorkAsNormalMode; - * config->upperLimit = DAC_DATL_COUNT - 1U; - * @endcode - * @param config Pointer to the configuration structure. See "dac_buffer_config_t". - */ -void DAC_GetDefaultBufferConfig(dac_buffer_config_t *config); - -/*! - * @brief Enables the DMA for DAC buffer. - * - * @param base DAC peripheral base address. - * @param enable Enables or disables the feature. - */ -static inline void DAC_EnableBufferDMA(DAC_Type *base, bool enable) -{ - if (enable) - { - base->C1 |= DAC_C1_DMAEN_MASK; - } - else - { - base->C1 &= ~DAC_C1_DMAEN_MASK; - } -} - -/*! - * @brief Sets the value for items in the buffer. - * - * @param base DAC peripheral base address. - * @param index Setting the index for items in the buffer. The available index should not exceed the size of the DAC buffer. - * @param value Setting the value for items in the buffer. 12-bits are available. - */ -void DAC_SetBufferValue(DAC_Type *base, uint8_t index, uint16_t value); - -/*! - * @brief Triggers the buffer using software and updates the read pointer of the DAC buffer. - * - * This function triggers the function using software. The read pointer of the DAC buffer is updated with one step - * after this function is called. Changing the read pointer depends on the buffer's work mode. - * - * @param base DAC peripheral base address. - */ -static inline void DAC_DoSoftwareTriggerBuffer(DAC_Type *base) -{ - base->C0 |= DAC_C0_DACSWTRG_MASK; -} - -/*! - * @brief Gets the current read pointer of the DAC buffer. - * - * This function gets the current read pointer of the DAC buffer. - * The current output value depends on the item indexed by the read pointer. It is updated either - * by a software trigger or a hardware trigger. - * - * @param base DAC peripheral base address. - * - * @return The current read pointer of the DAC buffer. - */ -static inline uint8_t DAC_GetBufferReadPointer(DAC_Type *base) -{ - return ((base->C2 & DAC_C2_DACBFRP_MASK) >> DAC_C2_DACBFRP_SHIFT); -} - -/*! - * @brief Sets the current read pointer of the DAC buffer. - * - * This function sets the current read pointer of the DAC buffer. - * The current output value depends on the item indexed by the read pointer. It is updated either by a - * software trigger or a hardware trigger. After the read pointer changes, the DAC output value also changes. - * - * @param base DAC peripheral base address. - * @param index Setting an index value for the pointer. - */ -void DAC_SetBufferReadPointer(DAC_Type *base, uint8_t index); - -/*! - * @brief Enables interrupts for the DAC buffer. - * - * @param base DAC peripheral base address. - * @param mask Mask value for interrupts. See "_dac_buffer_interrupt_enable". - */ -void DAC_EnableBufferInterrupts(DAC_Type *base, uint32_t mask); - -/*! - * @brief Disables interrupts for the DAC buffer. - * - * @param base DAC peripheral base address. - * @param mask Mask value for interrupts. See "_dac_buffer_interrupt_enable". - */ -void DAC_DisableBufferInterrupts(DAC_Type *base, uint32_t mask); - -/*! - * @brief Gets the flags of events for the DAC buffer. - * - * @param base DAC peripheral base address. - * - * @return Mask value for the asserted flags. See "_dac_buffer_status_flags". - */ -uint32_t DAC_GetBufferStatusFlags(DAC_Type *base); - -/*! - * @brief Clears the flags of events for the DAC buffer. - * - * @param base DAC peripheral base address. - * @param mask Mask value for flags. See "_dac_buffer_status_flags_t". - */ -void DAC_ClearBufferStatusFlags(DAC_Type *base, uint32_t mask); - -/* @} */ - -#if defined(__cplusplus) -} -#endif -/*! - * @} - */ -#endif /* _FSL_DAC_H_ */ diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_dmamux.c b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_dmamux.c deleted file mode 100644 index 39ce9cfbead..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_dmamux.c +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "fsl_dmamux.h" - -/******************************************************************************* - * Definitions - ******************************************************************************/ - -/******************************************************************************* - * Prototypes - ******************************************************************************/ - -/*! - * @brief Get instance number for DMAMUX. - * - * @param base DMAMUX peripheral base address. - */ -static uint32_t DMAMUX_GetInstance(DMAMUX_Type *base); - -/******************************************************************************* - * Variables - ******************************************************************************/ - -/*! @brief Array to map DMAMUX instance number to base pointer. */ -static DMAMUX_Type *const s_dmamuxBases[] = DMAMUX_BASE_PTRS; - -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) -/*! @brief Array to map DMAMUX instance number to clock name. */ -static const clock_ip_name_t s_dmamuxClockName[] = DMAMUX_CLOCKS; -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ - -/******************************************************************************* - * Code - ******************************************************************************/ -static uint32_t DMAMUX_GetInstance(DMAMUX_Type *base) -{ - uint32_t instance; - - /* Find the instance index from base address mappings. */ - for (instance = 0; instance < ARRAY_SIZE(s_dmamuxBases); instance++) - { - if (s_dmamuxBases[instance] == base) - { - break; - } - } - - assert(instance < ARRAY_SIZE(s_dmamuxBases)); - - return instance; -} - -void DMAMUX_Init(DMAMUX_Type *base) -{ -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) - CLOCK_EnableClock(s_dmamuxClockName[DMAMUX_GetInstance(base)]); -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ -} - -void DMAMUX_Deinit(DMAMUX_Type *base) -{ -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) - CLOCK_DisableClock(s_dmamuxClockName[DMAMUX_GetInstance(base)]); -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ -} diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_dmamux.h b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_dmamux.h deleted file mode 100644 index 071348b2c25..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_dmamux.h +++ /dev/null @@ -1,200 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef _FSL_DMAMUX_H_ -#define _FSL_DMAMUX_H_ - -#include "fsl_common.h" - -/*! - * @addtogroup dmamux - * @{ - */ - - -/******************************************************************************* - * Definitions - ******************************************************************************/ - -/*! @name Driver version */ -/*@{*/ -/*! @brief DMAMUX driver version 2.0.2. */ -#define FSL_DMAMUX_DRIVER_VERSION (MAKE_VERSION(2, 0, 2)) -/*@}*/ - -/******************************************************************************* - * API - ******************************************************************************/ - -#if defined(__cplusplus) -extern "C" { -#endif /* __cplusplus */ - -/*! - * @name DMAMUX Initialization and de-initialization - * @{ - */ - -/*! - * @brief Initializes the DMAMUX peripheral. - * - * This function ungates the DMAMUX clock. - * - * @param base DMAMUX peripheral base address. - * - */ -void DMAMUX_Init(DMAMUX_Type *base); - -/*! - * @brief Deinitializes the DMAMUX peripheral. - * - * This function gates the DMAMUX clock. - * - * @param base DMAMUX peripheral base address. - */ -void DMAMUX_Deinit(DMAMUX_Type *base); - -/* @} */ -/*! - * @name DMAMUX Channel Operation - * @{ - */ - -/*! - * @brief Enables the DMAMUX channel. - * - * This function enables the DMAMUX channel. - * - * @param base DMAMUX peripheral base address. - * @param channel DMAMUX channel number. - */ -static inline void DMAMUX_EnableChannel(DMAMUX_Type *base, uint32_t channel) -{ - assert(channel < FSL_FEATURE_DMAMUX_MODULE_CHANNEL); - - base->CHCFG[channel] |= DMAMUX_CHCFG_ENBL_MASK; -} - -/*! - * @brief Disables the DMAMUX channel. - * - * This function disables the DMAMUX channel. - * - * @note The user must disable the DMAMUX channel before configuring it. - * @param base DMAMUX peripheral base address. - * @param channel DMAMUX channel number. - */ -static inline void DMAMUX_DisableChannel(DMAMUX_Type *base, uint32_t channel) -{ - assert(channel < FSL_FEATURE_DMAMUX_MODULE_CHANNEL); - - base->CHCFG[channel] &= ~DMAMUX_CHCFG_ENBL_MASK; -} - -/*! - * @brief Configures the DMAMUX channel source. - * - * @param base DMAMUX peripheral base address. - * @param channel DMAMUX channel number. - * @param source Channel source, which is used to trigger the DMA transfer. - */ -static inline void DMAMUX_SetSource(DMAMUX_Type *base, uint32_t channel, uint32_t source) -{ - assert(channel < FSL_FEATURE_DMAMUX_MODULE_CHANNEL); - - base->CHCFG[channel] = ((base->CHCFG[channel] & ~DMAMUX_CHCFG_SOURCE_MASK) | DMAMUX_CHCFG_SOURCE(source)); -} - -#if defined(FSL_FEATURE_DMAMUX_HAS_TRIG) && FSL_FEATURE_DMAMUX_HAS_TRIG > 0U -/*! - * @brief Enables the DMAMUX period trigger. - * - * This function enables the DMAMUX period trigger feature. - * - * @param base DMAMUX peripheral base address. - * @param channel DMAMUX channel number. - */ -static inline void DMAMUX_EnablePeriodTrigger(DMAMUX_Type *base, uint32_t channel) -{ - assert(channel < FSL_FEATURE_DMAMUX_MODULE_CHANNEL); - - base->CHCFG[channel] |= DMAMUX_CHCFG_TRIG_MASK; -} - -/*! - * @brief Disables the DMAMUX period trigger. - * - * This function disables the DMAMUX period trigger. - * - * @param base DMAMUX peripheral base address. - * @param channel DMAMUX channel number. - */ -static inline void DMAMUX_DisablePeriodTrigger(DMAMUX_Type *base, uint32_t channel) -{ - assert(channel < FSL_FEATURE_DMAMUX_MODULE_CHANNEL); - - base->CHCFG[channel] &= ~DMAMUX_CHCFG_TRIG_MASK; -} -#endif /* FSL_FEATURE_DMAMUX_HAS_TRIG */ - -#if (defined(FSL_FEATURE_DMAMUX_HAS_A_ON) && FSL_FEATURE_DMAMUX_HAS_A_ON) -/*! - * @brief Enables the DMA channel to be always ON. - * - * This function enables the DMAMUX channel always ON feature. - * - * @param base DMAMUX peripheral base address. - * @param channel DMAMUX channel number. - * @param enable Switcher of the always ON feature. "true" means enabled, "false" means disabled. - */ -static inline void DMAMUX_EnableAlwaysOn(DMAMUX_Type *base, uint32_t channel, bool enable) -{ - assert(channel < FSL_FEATURE_DMAMUX_MODULE_CHANNEL); - - if (enable) - { - base->CHCFG[channel] |= DMAMUX_CHCFG_A_ON_MASK; - } - else - { - base->CHCFG[channel] &= ~DMAMUX_CHCFG_A_ON_MASK; - } -} -#endif /* FSL_FEATURE_DMAMUX_HAS_A_ON */ - -/* @} */ - -#if defined(__cplusplus) -} -#endif /* __cplusplus */ - -/* @} */ - -#endif /* _FSL_DMAMUX_H_ */ diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_dspi.c b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_dspi.c deleted file mode 100644 index e2b90ba56a9..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_dspi.c +++ /dev/null @@ -1,1669 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "fsl_dspi.h" - -/******************************************************************************* - * Definitions - ******************************************************************************/ -/*! @brief Typedef for master interrupt handler. */ -typedef void (*dspi_master_isr_t)(SPI_Type *base, dspi_master_handle_t *handle); - -/*! @brief Typedef for slave interrupt handler. */ -typedef void (*dspi_slave_isr_t)(SPI_Type *base, dspi_slave_handle_t *handle); - -/******************************************************************************* - * Prototypes - ******************************************************************************/ -/*! - * @brief Get instance number for DSPI module. - * - * @param base DSPI peripheral base address. - */ -uint32_t DSPI_GetInstance(SPI_Type *base); - -/*! - * @brief Configures the DSPI peripheral chip select polarity. - * - * This function takes in the desired peripheral chip select (Pcs) and it's corresponding desired polarity and - * configures the Pcs signal to operate with the desired characteristic. - * - * @param base DSPI peripheral address. - * @param pcs The particular peripheral chip select (parameter value is of type dspi_which_pcs_t) for which we wish to - * apply the active high or active low characteristic. - * @param activeLowOrHigh The setting for either "active high, inactive low (0)" or "active low, inactive high(1)" of - * type dspi_pcs_polarity_config_t. - */ -static void DSPI_SetOnePcsPolarity(SPI_Type *base, dspi_which_pcs_t pcs, dspi_pcs_polarity_config_t activeLowOrHigh); - -/*! - * @brief Master fill up the TX FIFO with data. - * This is not a public API. - */ -static void DSPI_MasterTransferFillUpTxFifo(SPI_Type *base, dspi_master_handle_t *handle); - -/*! - * @brief Master finish up a transfer. - * It would call back if there is callback function and set the state to idle. - * This is not a public API. - */ -static void DSPI_MasterTransferComplete(SPI_Type *base, dspi_master_handle_t *handle); - -/*! - * @brief Slave fill up the TX FIFO with data. - * This is not a public API. - */ -static void DSPI_SlaveTransferFillUpTxFifo(SPI_Type *base, dspi_slave_handle_t *handle); - -/*! - * @brief Slave finish up a transfer. - * It would call back if there is callback function and set the state to idle. - * This is not a public API. - */ -static void DSPI_SlaveTransferComplete(SPI_Type *base, dspi_slave_handle_t *handle); - -/*! - * @brief DSPI common interrupt handler. - * - * @param base DSPI peripheral address. - * @param handle pointer to g_dspiHandle which stores the transfer state. - */ -static void DSPI_CommonIRQHandler(SPI_Type *base, void *param); - -/*! - * @brief Master prepare the transfer. - * Basically it set up dspi_master_handle . - * This is not a public API. - */ -static void DSPI_MasterTransferPrepare(SPI_Type *base, dspi_master_handle_t *handle, dspi_transfer_t *transfer); - -/******************************************************************************* - * Variables - ******************************************************************************/ - -/* Defines constant value arrays for the baud rate pre-scalar and scalar divider values.*/ -static const uint32_t s_baudratePrescaler[] = {2, 3, 5, 7}; -static const uint32_t s_baudrateScaler[] = {2, 4, 6, 8, 16, 32, 64, 128, - 256, 512, 1024, 2048, 4096, 8192, 16384, 32768}; - -static const uint32_t s_delayPrescaler[] = {1, 3, 5, 7}; -static const uint32_t s_delayScaler[] = {2, 4, 8, 16, 32, 64, 128, 256, - 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536}; - -/*! @brief Pointers to dspi bases for each instance. */ -static SPI_Type *const s_dspiBases[] = SPI_BASE_PTRS; - -/*! @brief Pointers to dspi IRQ number for each instance. */ -static IRQn_Type const s_dspiIRQ[] = SPI_IRQS; - -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) -/*! @brief Pointers to dspi clocks for each instance. */ -static clock_ip_name_t const s_dspiClock[] = DSPI_CLOCKS; -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ - -/*! @brief Pointers to dspi handles for each instance. */ -static void *g_dspiHandle[ARRAY_SIZE(s_dspiBases)]; - -/*! @brief Pointer to master IRQ handler for each instance. */ -static dspi_master_isr_t s_dspiMasterIsr; - -/*! @brief Pointer to slave IRQ handler for each instance. */ -static dspi_slave_isr_t s_dspiSlaveIsr; - -/********************************************************************************************************************** -* Code -*********************************************************************************************************************/ -uint32_t DSPI_GetInstance(SPI_Type *base) -{ - uint32_t instance; - - /* Find the instance index from base address mappings. */ - for (instance = 0; instance < ARRAY_SIZE(s_dspiBases); instance++) - { - if (s_dspiBases[instance] == base) - { - break; - } - } - - assert(instance < ARRAY_SIZE(s_dspiBases)); - - return instance; -} - -void DSPI_MasterInit(SPI_Type *base, const dspi_master_config_t *masterConfig, uint32_t srcClock_Hz) -{ - assert(masterConfig); - - uint32_t temp; -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) - /* enable DSPI clock */ - CLOCK_EnableClock(s_dspiClock[DSPI_GetInstance(base)]); -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ - - DSPI_Enable(base, true); - DSPI_StopTransfer(base); - - DSPI_SetMasterSlaveMode(base, kDSPI_Master); - - temp = base->MCR & (~(SPI_MCR_CONT_SCKE_MASK | SPI_MCR_MTFE_MASK | SPI_MCR_ROOE_MASK | SPI_MCR_SMPL_PT_MASK | - SPI_MCR_DIS_TXF_MASK | SPI_MCR_DIS_RXF_MASK)); - - base->MCR = temp | SPI_MCR_CONT_SCKE(masterConfig->enableContinuousSCK) | - SPI_MCR_MTFE(masterConfig->enableModifiedTimingFormat) | - SPI_MCR_ROOE(masterConfig->enableRxFifoOverWrite) | SPI_MCR_SMPL_PT(masterConfig->samplePoint) | - SPI_MCR_DIS_TXF(false) | SPI_MCR_DIS_RXF(false); - - DSPI_SetOnePcsPolarity(base, masterConfig->whichPcs, masterConfig->pcsActiveHighOrLow); - - if (0 == DSPI_MasterSetBaudRate(base, masterConfig->whichCtar, masterConfig->ctarConfig.baudRate, srcClock_Hz)) - { - assert(false); - } - - temp = base->CTAR[masterConfig->whichCtar] & - ~(SPI_CTAR_FMSZ_MASK | SPI_CTAR_CPOL_MASK | SPI_CTAR_CPHA_MASK | SPI_CTAR_LSBFE_MASK); - - base->CTAR[masterConfig->whichCtar] = - temp | SPI_CTAR_FMSZ(masterConfig->ctarConfig.bitsPerFrame - 1) | SPI_CTAR_CPOL(masterConfig->ctarConfig.cpol) | - SPI_CTAR_CPHA(masterConfig->ctarConfig.cpha) | SPI_CTAR_LSBFE(masterConfig->ctarConfig.direction); - - DSPI_MasterSetDelayTimes(base, masterConfig->whichCtar, kDSPI_PcsToSck, srcClock_Hz, - masterConfig->ctarConfig.pcsToSckDelayInNanoSec); - DSPI_MasterSetDelayTimes(base, masterConfig->whichCtar, kDSPI_LastSckToPcs, srcClock_Hz, - masterConfig->ctarConfig.lastSckToPcsDelayInNanoSec); - DSPI_MasterSetDelayTimes(base, masterConfig->whichCtar, kDSPI_BetweenTransfer, srcClock_Hz, - masterConfig->ctarConfig.betweenTransferDelayInNanoSec); - - DSPI_StartTransfer(base); -} - -void DSPI_MasterGetDefaultConfig(dspi_master_config_t *masterConfig) -{ - assert(masterConfig); - - masterConfig->whichCtar = kDSPI_Ctar0; - masterConfig->ctarConfig.baudRate = 500000; - masterConfig->ctarConfig.bitsPerFrame = 8; - masterConfig->ctarConfig.cpol = kDSPI_ClockPolarityActiveHigh; - masterConfig->ctarConfig.cpha = kDSPI_ClockPhaseFirstEdge; - masterConfig->ctarConfig.direction = kDSPI_MsbFirst; - - masterConfig->ctarConfig.pcsToSckDelayInNanoSec = 1000; - masterConfig->ctarConfig.lastSckToPcsDelayInNanoSec = 1000; - masterConfig->ctarConfig.betweenTransferDelayInNanoSec = 1000; - - masterConfig->whichPcs = kDSPI_Pcs0; - masterConfig->pcsActiveHighOrLow = kDSPI_PcsActiveLow; - - masterConfig->enableContinuousSCK = false; - masterConfig->enableRxFifoOverWrite = false; - masterConfig->enableModifiedTimingFormat = false; - masterConfig->samplePoint = kDSPI_SckToSin0Clock; -} - -void DSPI_SlaveInit(SPI_Type *base, const dspi_slave_config_t *slaveConfig) -{ - assert(slaveConfig); - - uint32_t temp = 0; - -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) - /* enable DSPI clock */ - CLOCK_EnableClock(s_dspiClock[DSPI_GetInstance(base)]); -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ - - DSPI_Enable(base, true); - DSPI_StopTransfer(base); - - DSPI_SetMasterSlaveMode(base, kDSPI_Slave); - - temp = base->MCR & (~(SPI_MCR_CONT_SCKE_MASK | SPI_MCR_MTFE_MASK | SPI_MCR_ROOE_MASK | SPI_MCR_SMPL_PT_MASK | - SPI_MCR_DIS_TXF_MASK | SPI_MCR_DIS_RXF_MASK)); - - base->MCR = temp | SPI_MCR_CONT_SCKE(slaveConfig->enableContinuousSCK) | - SPI_MCR_MTFE(slaveConfig->enableModifiedTimingFormat) | - SPI_MCR_ROOE(slaveConfig->enableRxFifoOverWrite) | SPI_MCR_SMPL_PT(slaveConfig->samplePoint) | - SPI_MCR_DIS_TXF(false) | SPI_MCR_DIS_RXF(false); - - DSPI_SetOnePcsPolarity(base, kDSPI_Pcs0, kDSPI_PcsActiveLow); - - temp = base->CTAR[slaveConfig->whichCtar] & - ~(SPI_CTAR_FMSZ_MASK | SPI_CTAR_CPOL_MASK | SPI_CTAR_CPHA_MASK | SPI_CTAR_LSBFE_MASK); - - base->CTAR[slaveConfig->whichCtar] = temp | SPI_CTAR_SLAVE_FMSZ(slaveConfig->ctarConfig.bitsPerFrame - 1) | - SPI_CTAR_SLAVE_CPOL(slaveConfig->ctarConfig.cpol) | - SPI_CTAR_SLAVE_CPHA(slaveConfig->ctarConfig.cpha); - - DSPI_StartTransfer(base); -} - -void DSPI_SlaveGetDefaultConfig(dspi_slave_config_t *slaveConfig) -{ - assert(slaveConfig); - - slaveConfig->whichCtar = kDSPI_Ctar0; - slaveConfig->ctarConfig.bitsPerFrame = 8; - slaveConfig->ctarConfig.cpol = kDSPI_ClockPolarityActiveHigh; - slaveConfig->ctarConfig.cpha = kDSPI_ClockPhaseFirstEdge; - - slaveConfig->enableContinuousSCK = false; - slaveConfig->enableRxFifoOverWrite = false; - slaveConfig->enableModifiedTimingFormat = false; - slaveConfig->samplePoint = kDSPI_SckToSin0Clock; -} - -void DSPI_Deinit(SPI_Type *base) -{ - DSPI_StopTransfer(base); - DSPI_Enable(base, false); - -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) - /* disable DSPI clock */ - CLOCK_DisableClock(s_dspiClock[DSPI_GetInstance(base)]); -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ -} - -static void DSPI_SetOnePcsPolarity(SPI_Type *base, dspi_which_pcs_t pcs, dspi_pcs_polarity_config_t activeLowOrHigh) -{ - uint32_t temp; - - temp = base->MCR; - - if (activeLowOrHigh == kDSPI_PcsActiveLow) - { - temp |= SPI_MCR_PCSIS(pcs); - } - else - { - temp &= ~SPI_MCR_PCSIS(pcs); - } - - base->MCR = temp; -} - -uint32_t DSPI_MasterSetBaudRate(SPI_Type *base, - dspi_ctar_selection_t whichCtar, - uint32_t baudRate_Bps, - uint32_t srcClock_Hz) -{ - /* for master mode configuration, if slave mode detected, return 0*/ - if (!DSPI_IsMaster(base)) - { - return 0; - } - uint32_t temp; - uint32_t prescaler, bestPrescaler; - uint32_t scaler, bestScaler; - uint32_t dbr, bestDbr; - uint32_t realBaudrate, bestBaudrate; - uint32_t diff, min_diff; - uint32_t baudrate = baudRate_Bps; - - /* find combination of prescaler and scaler resulting in baudrate closest to the requested value */ - min_diff = 0xFFFFFFFFU; - bestPrescaler = 0; - bestScaler = 0; - bestDbr = 1; - bestBaudrate = 0; /* required to avoid compilation warning */ - - /* In all for loops, if min_diff = 0, the exit for loop*/ - for (prescaler = 0; (prescaler < 4) && min_diff; prescaler++) - { - for (scaler = 0; (scaler < 16) && min_diff; scaler++) - { - for (dbr = 1; (dbr < 3) && min_diff; dbr++) - { - realBaudrate = ((srcClock_Hz * dbr) / (s_baudratePrescaler[prescaler] * (s_baudrateScaler[scaler]))); - - /* calculate the baud rate difference based on the conditional statement that states that the calculated - * baud rate must not exceed the desired baud rate. - */ - if (baudrate >= realBaudrate) - { - diff = baudrate - realBaudrate; - if (min_diff > diff) - { - /* a better match found */ - min_diff = diff; - bestPrescaler = prescaler; - bestScaler = scaler; - bestBaudrate = realBaudrate; - bestDbr = dbr; - } - } - } - } - } - - /* write the best dbr, prescalar, and baud rate scalar to the CTAR */ - temp = base->CTAR[whichCtar] & ~(SPI_CTAR_DBR_MASK | SPI_CTAR_PBR_MASK | SPI_CTAR_BR_MASK); - - base->CTAR[whichCtar] = temp | ((bestDbr - 1) << SPI_CTAR_DBR_SHIFT) | (bestPrescaler << SPI_CTAR_PBR_SHIFT) | - (bestScaler << SPI_CTAR_BR_SHIFT); - - /* return the actual calculated baud rate */ - return bestBaudrate; -} - -void DSPI_MasterSetDelayScaler( - SPI_Type *base, dspi_ctar_selection_t whichCtar, uint32_t prescaler, uint32_t scaler, dspi_delay_type_t whichDelay) -{ - /* these settings are only relevant in master mode */ - if (DSPI_IsMaster(base)) - { - switch (whichDelay) - { - case kDSPI_PcsToSck: - base->CTAR[whichCtar] = (base->CTAR[whichCtar] & (~SPI_CTAR_PCSSCK_MASK) & (~SPI_CTAR_CSSCK_MASK)) | - SPI_CTAR_PCSSCK(prescaler) | SPI_CTAR_CSSCK(scaler); - break; - case kDSPI_LastSckToPcs: - base->CTAR[whichCtar] = (base->CTAR[whichCtar] & (~SPI_CTAR_PASC_MASK) & (~SPI_CTAR_ASC_MASK)) | - SPI_CTAR_PASC(prescaler) | SPI_CTAR_ASC(scaler); - break; - case kDSPI_BetweenTransfer: - base->CTAR[whichCtar] = (base->CTAR[whichCtar] & (~SPI_CTAR_PDT_MASK) & (~SPI_CTAR_DT_MASK)) | - SPI_CTAR_PDT(prescaler) | SPI_CTAR_DT(scaler); - break; - default: - break; - } - } -} - -uint32_t DSPI_MasterSetDelayTimes(SPI_Type *base, - dspi_ctar_selection_t whichCtar, - dspi_delay_type_t whichDelay, - uint32_t srcClock_Hz, - uint32_t delayTimeInNanoSec) -{ - /* for master mode configuration, if slave mode detected, return 0 */ - if (!DSPI_IsMaster(base)) - { - return 0; - } - - uint32_t prescaler, bestPrescaler; - uint32_t scaler, bestScaler; - uint32_t realDelay, bestDelay; - uint32_t diff, min_diff; - uint32_t initialDelayNanoSec; - - /* find combination of prescaler and scaler resulting in the delay closest to the - * requested value - */ - min_diff = 0xFFFFFFFFU; - /* Initialize prescaler and scaler to their max values to generate the max delay */ - bestPrescaler = 0x3; - bestScaler = 0xF; - bestDelay = (((1000000000U * 4) / srcClock_Hz) * s_delayPrescaler[bestPrescaler] * s_delayScaler[bestScaler]) / 4; - - /* First calculate the initial, default delay */ - initialDelayNanoSec = 1000000000U / srcClock_Hz * 2; - - /* If the initial, default delay is already greater than the desired delay, then - * set the delays to their initial value (0) and return the delay. In other words, - * there is no way to decrease the delay value further. - */ - if (initialDelayNanoSec >= delayTimeInNanoSec) - { - DSPI_MasterSetDelayScaler(base, whichCtar, 0, 0, whichDelay); - return initialDelayNanoSec; - } - - /* In all for loops, if min_diff = 0, the exit for loop */ - for (prescaler = 0; (prescaler < 4) && min_diff; prescaler++) - { - for (scaler = 0; (scaler < 16) && min_diff; scaler++) - { - realDelay = ((4000000000U / srcClock_Hz) * s_delayPrescaler[prescaler] * s_delayScaler[scaler]) / 4; - - /* calculate the delay difference based on the conditional statement - * that states that the calculated delay must not be less then the desired delay - */ - if (realDelay >= delayTimeInNanoSec) - { - diff = realDelay - delayTimeInNanoSec; - if (min_diff > diff) - { - /* a better match found */ - min_diff = diff; - bestPrescaler = prescaler; - bestScaler = scaler; - bestDelay = realDelay; - } - } - } - } - - /* write the best dbr, prescalar, and baud rate scalar to the CTAR */ - DSPI_MasterSetDelayScaler(base, whichCtar, bestPrescaler, bestScaler, whichDelay); - - /* return the actual calculated baud rate */ - return bestDelay; -} - -void DSPI_GetDefaultDataCommandConfig(dspi_command_data_config_t *command) -{ - assert(command); - - command->isPcsContinuous = false; - command->whichCtar = kDSPI_Ctar0; - command->whichPcs = kDSPI_Pcs0; - command->isEndOfQueue = false; - command->clearTransferCount = false; -} - -void DSPI_MasterWriteDataBlocking(SPI_Type *base, dspi_command_data_config_t *command, uint16_t data) -{ - assert(command); - - /* First, clear Transmit Complete Flag (TCF) */ - DSPI_ClearStatusFlags(base, kDSPI_TxCompleteFlag); - - while (!(DSPI_GetStatusFlags(base) & kDSPI_TxFifoFillRequestFlag)) - { - DSPI_ClearStatusFlags(base, kDSPI_TxFifoFillRequestFlag); - } - - base->PUSHR = SPI_PUSHR_CONT(command->isPcsContinuous) | SPI_PUSHR_CTAS(command->whichCtar) | - SPI_PUSHR_PCS(command->whichPcs) | SPI_PUSHR_EOQ(command->isEndOfQueue) | - SPI_PUSHR_CTCNT(command->clearTransferCount) | SPI_PUSHR_TXDATA(data); - DSPI_ClearStatusFlags(base, kDSPI_TxFifoFillRequestFlag); - - /* Wait till TCF sets */ - while (!(DSPI_GetStatusFlags(base) & kDSPI_TxCompleteFlag)) - { - } -} - -void DSPI_MasterWriteCommandDataBlocking(SPI_Type *base, uint32_t data) -{ - /* First, clear Transmit Complete Flag (TCF) */ - DSPI_ClearStatusFlags(base, kDSPI_TxCompleteFlag); - - while (!(DSPI_GetStatusFlags(base) & kDSPI_TxFifoFillRequestFlag)) - { - DSPI_ClearStatusFlags(base, kDSPI_TxFifoFillRequestFlag); - } - - base->PUSHR = data; - - DSPI_ClearStatusFlags(base, kDSPI_TxFifoFillRequestFlag); - - /* Wait till TCF sets */ - while (!(DSPI_GetStatusFlags(base) & kDSPI_TxCompleteFlag)) - { - } -} - -void DSPI_SlaveWriteDataBlocking(SPI_Type *base, uint32_t data) -{ - /* First, clear Transmit Complete Flag (TCF) */ - DSPI_ClearStatusFlags(base, kDSPI_TxCompleteFlag); - - while (!(DSPI_GetStatusFlags(base) & kDSPI_TxFifoFillRequestFlag)) - { - DSPI_ClearStatusFlags(base, kDSPI_TxFifoFillRequestFlag); - } - - base->PUSHR_SLAVE = data; - - DSPI_ClearStatusFlags(base, kDSPI_TxFifoFillRequestFlag); - - /* Wait till TCF sets */ - while (!(DSPI_GetStatusFlags(base) & kDSPI_TxCompleteFlag)) - { - } -} - -void DSPI_EnableInterrupts(SPI_Type *base, uint32_t mask) -{ - if (mask & SPI_RSER_TFFF_RE_MASK) - { - base->RSER &= ~SPI_RSER_TFFF_DIRS_MASK; - } - if (mask & SPI_RSER_RFDF_RE_MASK) - { - base->RSER &= ~SPI_RSER_RFDF_DIRS_MASK; - } - base->RSER |= mask; -} - -/*Transactional APIs -- Master*/ - -void DSPI_MasterTransferCreateHandle(SPI_Type *base, - dspi_master_handle_t *handle, - dspi_master_transfer_callback_t callback, - void *userData) -{ - assert(handle); - - /* Zero the handle. */ - memset(handle, 0, sizeof(*handle)); - - g_dspiHandle[DSPI_GetInstance(base)] = handle; - - handle->callback = callback; - handle->userData = userData; -} - -status_t DSPI_MasterTransferBlocking(SPI_Type *base, dspi_transfer_t *transfer) -{ - assert(transfer); - - uint16_t wordToSend = 0; - uint16_t wordReceived = 0; - uint8_t dummyData = DSPI_DUMMY_DATA; - uint8_t bitsPerFrame; - - uint32_t command; - uint32_t lastCommand; - - uint8_t *txData; - uint8_t *rxData; - uint32_t remainingSendByteCount; - uint32_t remainingReceiveByteCount; - - uint32_t fifoSize; - dspi_command_data_config_t commandStruct; - - /* If the transfer count is zero, then return immediately.*/ - if (transfer->dataSize == 0) - { - return kStatus_InvalidArgument; - } - - DSPI_StopTransfer(base); - DSPI_DisableInterrupts(base, kDSPI_AllInterruptEnable); - DSPI_FlushFifo(base, true, true); - DSPI_ClearStatusFlags(base, kDSPI_AllStatusFlag); - - /*Calculate the command and lastCommand*/ - commandStruct.whichPcs = - (dspi_which_pcs_t)(1U << ((transfer->configFlags & DSPI_MASTER_PCS_MASK) >> DSPI_MASTER_PCS_SHIFT)); - commandStruct.isEndOfQueue = false; - commandStruct.clearTransferCount = false; - commandStruct.whichCtar = - (dspi_ctar_selection_t)((transfer->configFlags & DSPI_MASTER_CTAR_MASK) >> DSPI_MASTER_CTAR_SHIFT); - commandStruct.isPcsContinuous = (bool)(transfer->configFlags & kDSPI_MasterPcsContinuous); - - command = DSPI_MasterGetFormattedCommand(&(commandStruct)); - - commandStruct.isEndOfQueue = true; - commandStruct.isPcsContinuous = (bool)(transfer->configFlags & kDSPI_MasterActiveAfterTransfer); - lastCommand = DSPI_MasterGetFormattedCommand(&(commandStruct)); - - /*Calculate the bitsPerFrame*/ - bitsPerFrame = ((base->CTAR[commandStruct.whichCtar] & SPI_CTAR_FMSZ_MASK) >> SPI_CTAR_FMSZ_SHIFT) + 1; - - txData = transfer->txData; - rxData = transfer->rxData; - remainingSendByteCount = transfer->dataSize; - remainingReceiveByteCount = transfer->dataSize; - - if ((base->MCR & SPI_MCR_DIS_RXF_MASK) || (base->MCR & SPI_MCR_DIS_TXF_MASK)) - { - fifoSize = 1; - } - else - { - fifoSize = FSL_FEATURE_DSPI_FIFO_SIZEn(base); - } - - DSPI_StartTransfer(base); - - if (bitsPerFrame <= 8) - { - while (remainingSendByteCount > 0) - { - if (remainingSendByteCount == 1) - { - while (!(DSPI_GetStatusFlags(base) & kDSPI_TxFifoFillRequestFlag)) - { - DSPI_ClearStatusFlags(base, kDSPI_TxFifoFillRequestFlag); - } - - if (txData != NULL) - { - base->PUSHR = (*txData) | (lastCommand); - txData++; - } - else - { - base->PUSHR = (lastCommand) | (dummyData); - } - DSPI_ClearStatusFlags(base, kDSPI_TxFifoFillRequestFlag); - remainingSendByteCount--; - - while (remainingReceiveByteCount > 0) - { - if (DSPI_GetStatusFlags(base) & kDSPI_RxFifoDrainRequestFlag) - { - if (rxData != NULL) - { - /* Read data from POPR*/ - *(rxData) = DSPI_ReadData(base); - rxData++; - } - else - { - DSPI_ReadData(base); - } - remainingReceiveByteCount--; - - DSPI_ClearStatusFlags(base, kDSPI_RxFifoDrainRequestFlag); - } - } - } - else - { - /*Wait until Tx Fifo is not full*/ - while (!(DSPI_GetStatusFlags(base) & kDSPI_TxFifoFillRequestFlag)) - { - DSPI_ClearStatusFlags(base, kDSPI_TxFifoFillRequestFlag); - } - if (txData != NULL) - { - base->PUSHR = command | (uint16_t)(*txData); - txData++; - } - else - { - base->PUSHR = command | dummyData; - } - remainingSendByteCount--; - - DSPI_ClearStatusFlags(base, kDSPI_TxFifoFillRequestFlag); - - while ((remainingReceiveByteCount - remainingSendByteCount) >= fifoSize) - { - if (DSPI_GetStatusFlags(base) & kDSPI_RxFifoDrainRequestFlag) - { - if (rxData != NULL) - { - *(rxData) = DSPI_ReadData(base); - rxData++; - } - else - { - DSPI_ReadData(base); - } - remainingReceiveByteCount--; - - DSPI_ClearStatusFlags(base, kDSPI_RxFifoDrainRequestFlag); - } - } - } - } - } - else - { - while (remainingSendByteCount > 0) - { - if (remainingSendByteCount <= 2) - { - while (!(DSPI_GetStatusFlags(base) & kDSPI_TxFifoFillRequestFlag)) - { - DSPI_ClearStatusFlags(base, kDSPI_TxFifoFillRequestFlag); - } - - if (txData != NULL) - { - wordToSend = *(txData); - ++txData; - - if (remainingSendByteCount > 1) - { - wordToSend |= (unsigned)(*(txData)) << 8U; - ++txData; - } - } - else - { - wordToSend = dummyData; - } - - base->PUSHR = lastCommand | wordToSend; - - DSPI_ClearStatusFlags(base, kDSPI_TxFifoFillRequestFlag); - remainingSendByteCount = 0; - - while (remainingReceiveByteCount > 0) - { - if (DSPI_GetStatusFlags(base) & kDSPI_RxFifoDrainRequestFlag) - { - wordReceived = DSPI_ReadData(base); - - if (remainingReceiveByteCount != 1) - { - if (rxData != NULL) - { - *(rxData) = wordReceived; - ++rxData; - *(rxData) = wordReceived >> 8; - ++rxData; - } - remainingReceiveByteCount -= 2; - } - else - { - if (rxData != NULL) - { - *(rxData) = wordReceived; - ++rxData; - } - remainingReceiveByteCount--; - } - DSPI_ClearStatusFlags(base, kDSPI_RxFifoDrainRequestFlag); - } - } - } - else - { - /*Wait until Tx Fifo is not full*/ - while (!(DSPI_GetStatusFlags(base) & kDSPI_TxFifoFillRequestFlag)) - { - DSPI_ClearStatusFlags(base, kDSPI_TxFifoFillRequestFlag); - } - - if (txData != NULL) - { - wordToSend = *(txData); - ++txData; - wordToSend |= (unsigned)(*(txData)) << 8U; - ++txData; - } - else - { - wordToSend = dummyData; - } - base->PUSHR = command | wordToSend; - remainingSendByteCount -= 2; - - DSPI_ClearStatusFlags(base, kDSPI_TxFifoFillRequestFlag); - - while (((remainingReceiveByteCount - remainingSendByteCount) / 2) >= fifoSize) - { - if (DSPI_GetStatusFlags(base) & kDSPI_RxFifoDrainRequestFlag) - { - wordReceived = DSPI_ReadData(base); - - if (rxData != NULL) - { - *rxData = wordReceived; - ++rxData; - *rxData = wordReceived >> 8; - ++rxData; - } - remainingReceiveByteCount -= 2; - - DSPI_ClearStatusFlags(base, kDSPI_RxFifoDrainRequestFlag); - } - } - } - } - } - - return kStatus_Success; -} - -static void DSPI_MasterTransferPrepare(SPI_Type *base, dspi_master_handle_t *handle, dspi_transfer_t *transfer) -{ - assert(handle); - assert(transfer); - - dspi_command_data_config_t commandStruct; - - DSPI_StopTransfer(base); - DSPI_FlushFifo(base, true, true); - DSPI_ClearStatusFlags(base, kDSPI_AllStatusFlag); - - commandStruct.whichPcs = - (dspi_which_pcs_t)(1U << ((transfer->configFlags & DSPI_MASTER_PCS_MASK) >> DSPI_MASTER_PCS_SHIFT)); - commandStruct.isEndOfQueue = false; - commandStruct.clearTransferCount = false; - commandStruct.whichCtar = - (dspi_ctar_selection_t)((transfer->configFlags & DSPI_MASTER_CTAR_MASK) >> DSPI_MASTER_CTAR_SHIFT); - commandStruct.isPcsContinuous = (bool)(transfer->configFlags & kDSPI_MasterPcsContinuous); - handle->command = DSPI_MasterGetFormattedCommand(&(commandStruct)); - - commandStruct.isEndOfQueue = true; - commandStruct.isPcsContinuous = (bool)(transfer->configFlags & kDSPI_MasterActiveAfterTransfer); - handle->lastCommand = DSPI_MasterGetFormattedCommand(&(commandStruct)); - - handle->bitsPerFrame = ((base->CTAR[commandStruct.whichCtar] & SPI_CTAR_FMSZ_MASK) >> SPI_CTAR_FMSZ_SHIFT) + 1; - - if ((base->MCR & SPI_MCR_DIS_RXF_MASK) || (base->MCR & SPI_MCR_DIS_TXF_MASK)) - { - handle->fifoSize = 1; - } - else - { - handle->fifoSize = FSL_FEATURE_DSPI_FIFO_SIZEn(base); - } - handle->txData = transfer->txData; - handle->rxData = transfer->rxData; - handle->remainingSendByteCount = transfer->dataSize; - handle->remainingReceiveByteCount = transfer->dataSize; - handle->totalByteCount = transfer->dataSize; -} - -status_t DSPI_MasterTransferNonBlocking(SPI_Type *base, dspi_master_handle_t *handle, dspi_transfer_t *transfer) -{ - assert(handle); - assert(transfer); - - /* If the transfer count is zero, then return immediately.*/ - if (transfer->dataSize == 0) - { - return kStatus_InvalidArgument; - } - - /* Check that we're not busy.*/ - if (handle->state == kDSPI_Busy) - { - return kStatus_DSPI_Busy; - } - - handle->state = kDSPI_Busy; - - DSPI_MasterTransferPrepare(base, handle, transfer); - DSPI_StartTransfer(base); - - /* Enable the NVIC for DSPI peripheral. */ - EnableIRQ(s_dspiIRQ[DSPI_GetInstance(base)]); - - DSPI_MasterTransferFillUpTxFifo(base, handle); - - /* RX FIFO Drain request: RFDF_RE to enable RFDF interrupt - * Since SPI is a synchronous interface, we only need to enable the RX interrupt. - * The IRQ handler will get the status of RX and TX interrupt flags. - */ - s_dspiMasterIsr = DSPI_MasterTransferHandleIRQ; - - DSPI_EnableInterrupts(base, kDSPI_RxFifoDrainRequestInterruptEnable); - - return kStatus_Success; -} - -status_t DSPI_MasterTransferGetCount(SPI_Type *base, dspi_master_handle_t *handle, size_t *count) -{ - assert(handle); - - if (!count) - { - return kStatus_InvalidArgument; - } - - /* Catch when there is not an active transfer. */ - if (handle->state != kDSPI_Busy) - { - *count = 0; - return kStatus_NoTransferInProgress; - } - - *count = handle->totalByteCount - handle->remainingReceiveByteCount; - return kStatus_Success; -} - -static void DSPI_MasterTransferComplete(SPI_Type *base, dspi_master_handle_t *handle) -{ - assert(handle); - - /* Disable interrupt requests*/ - DSPI_DisableInterrupts(base, kDSPI_RxFifoDrainRequestInterruptEnable | kDSPI_TxFifoFillRequestInterruptEnable); - - status_t status = 0; - if (handle->state == kDSPI_Error) - { - status = kStatus_DSPI_Error; - } - else - { - status = kStatus_Success; - } - - handle->state = kDSPI_Idle; - - if (handle->callback) - { - handle->callback(base, handle, status, handle->userData); - } -} - -static void DSPI_MasterTransferFillUpTxFifo(SPI_Type *base, dspi_master_handle_t *handle) -{ - assert(handle); - - uint16_t wordToSend = 0; - uint8_t dummyData = DSPI_DUMMY_DATA; - - /* If bits/frame is greater than one byte */ - if (handle->bitsPerFrame > 8) - { - /* Fill the fifo until it is full or until the send word count is 0 or until the difference - * between the remainingReceiveByteCount and remainingSendByteCount equals the FIFO depth. - * The reason for checking the difference is to ensure we only send as much as the - * RX FIFO can receive. - * For this case where bitsPerFrame > 8, each entry in the FIFO contains 2 bytes of the - * send data, hence the difference between the remainingReceiveByteCount and - * remainingSendByteCount must be divided by 2 to convert this difference into a - * 16-bit (2 byte) value. - */ - while ((DSPI_GetStatusFlags(base) & kDSPI_TxFifoFillRequestFlag) && - ((handle->remainingReceiveByteCount - handle->remainingSendByteCount) / 2 < handle->fifoSize)) - { - if (handle->remainingSendByteCount <= 2) - { - if (handle->txData) - { - if (handle->remainingSendByteCount == 1) - { - wordToSend = *(handle->txData); - } - else - { - wordToSend = *(handle->txData); - ++handle->txData; /* increment to next data byte */ - wordToSend |= (unsigned)(*(handle->txData)) << 8U; - } - } - else - { - wordToSend = dummyData; - } - handle->remainingSendByteCount = 0; - base->PUSHR = handle->lastCommand | wordToSend; - } - /* For all words except the last word */ - else - { - if (handle->txData) - { - wordToSend = *(handle->txData); - ++handle->txData; /* increment to next data byte */ - wordToSend |= (unsigned)(*(handle->txData)) << 8U; - ++handle->txData; /* increment to next data byte */ - } - else - { - wordToSend = dummyData; - } - handle->remainingSendByteCount -= 2; /* decrement remainingSendByteCount by 2 */ - base->PUSHR = handle->command | wordToSend; - } - - /* Try to clear the TFFF; if the TX FIFO is full this will clear */ - DSPI_ClearStatusFlags(base, kDSPI_TxFifoFillRequestFlag); - - /* exit loop if send count is zero, else update local variables for next loop */ - if (handle->remainingSendByteCount == 0) - { - break; - } - } /* End of TX FIFO fill while loop */ - } - /* Optimized for bits/frame less than or equal to one byte. */ - else - { - /* Fill the fifo until it is full or until the send word count is 0 or until the difference - * between the remainingReceiveByteCount and remainingSendByteCount equals the FIFO depth. - * The reason for checking the difference is to ensure we only send as much as the - * RX FIFO can receive. - */ - while ((DSPI_GetStatusFlags(base) & kDSPI_TxFifoFillRequestFlag) && - ((handle->remainingReceiveByteCount - handle->remainingSendByteCount) < handle->fifoSize)) - { - if (handle->txData) - { - wordToSend = *(handle->txData); - ++handle->txData; - } - else - { - wordToSend = dummyData; - } - - if (handle->remainingSendByteCount == 1) - { - base->PUSHR = handle->lastCommand | wordToSend; - } - else - { - base->PUSHR = handle->command | wordToSend; - } - - /* Try to clear the TFFF; if the TX FIFO is full this will clear */ - DSPI_ClearStatusFlags(base, kDSPI_TxFifoFillRequestFlag); - - --handle->remainingSendByteCount; - - /* exit loop if send count is zero, else update local variables for next loop */ - if (handle->remainingSendByteCount == 0) - { - break; - } - } - } -} - -void DSPI_MasterTransferAbort(SPI_Type *base, dspi_master_handle_t *handle) -{ - assert(handle); - - DSPI_StopTransfer(base); - - /* Disable interrupt requests*/ - DSPI_DisableInterrupts(base, kDSPI_RxFifoDrainRequestInterruptEnable | kDSPI_TxFifoFillRequestInterruptEnable); - - handle->state = kDSPI_Idle; -} - -void DSPI_MasterTransferHandleIRQ(SPI_Type *base, dspi_master_handle_t *handle) -{ - assert(handle); - - /* RECEIVE IRQ handler: Check read buffer only if there are remaining bytes to read. */ - if (handle->remainingReceiveByteCount) - { - /* Check read buffer.*/ - uint16_t wordReceived; /* Maximum supported data bit length in master mode is 16-bits */ - - /* If bits/frame is greater than one byte */ - if (handle->bitsPerFrame > 8) - { - while (DSPI_GetStatusFlags(base) & kDSPI_RxFifoDrainRequestFlag) - { - wordReceived = DSPI_ReadData(base); - /* clear the rx fifo drain request, needed for non-DMA applications as this flag - * will remain set even if the rx fifo is empty. By manually clearing this flag, it - * either remain clear if no more data is in the fifo, or it will set if there is - * more data in the fifo. - */ - DSPI_ClearStatusFlags(base, kDSPI_RxFifoDrainRequestFlag); - - /* Store read bytes into rx buffer only if a buffer pointer was provided */ - if (handle->rxData) - { - /* For the last word received, if there is an extra byte due to the odd transfer - * byte count, only save the the last byte and discard the upper byte - */ - if (handle->remainingReceiveByteCount == 1) - { - *handle->rxData = wordReceived; /* Write first data byte */ - --handle->remainingReceiveByteCount; - } - else - { - *handle->rxData = wordReceived; /* Write first data byte */ - ++handle->rxData; /* increment to next data byte */ - *handle->rxData = wordReceived >> 8; /* Write second data byte */ - ++handle->rxData; /* increment to next data byte */ - handle->remainingReceiveByteCount -= 2; - } - } - else - { - if (handle->remainingReceiveByteCount == 1) - { - --handle->remainingReceiveByteCount; - } - else - { - handle->remainingReceiveByteCount -= 2; - } - } - if (handle->remainingReceiveByteCount == 0) - { - break; - } - } /* End of RX FIFO drain while loop */ - } - /* Optimized for bits/frame less than or equal to one byte. */ - else - { - while (DSPI_GetStatusFlags(base) & kDSPI_RxFifoDrainRequestFlag) - { - wordReceived = DSPI_ReadData(base); - /* clear the rx fifo drain request, needed for non-DMA applications as this flag - * will remain set even if the rx fifo is empty. By manually clearing this flag, it - * either remain clear if no more data is in the fifo, or it will set if there is - * more data in the fifo. - */ - DSPI_ClearStatusFlags(base, kDSPI_RxFifoDrainRequestFlag); - - /* Store read bytes into rx buffer only if a buffer pointer was provided */ - if (handle->rxData) - { - *handle->rxData = wordReceived; - ++handle->rxData; - } - - --handle->remainingReceiveByteCount; - - if (handle->remainingReceiveByteCount == 0) - { - break; - } - } /* End of RX FIFO drain while loop */ - } - } - - /* Check write buffer. We always have to send a word in order to keep the transfer - * moving. So if the caller didn't provide a send buffer, we just send a zero. - */ - if (handle->remainingSendByteCount) - { - DSPI_MasterTransferFillUpTxFifo(base, handle); - } - - /* Check if we're done with this transfer.*/ - if ((handle->remainingSendByteCount == 0) && (handle->remainingReceiveByteCount == 0)) - { - /* Complete the transfer and disable the interrupts */ - DSPI_MasterTransferComplete(base, handle); - } -} - -/*Transactional APIs -- Slave*/ -void DSPI_SlaveTransferCreateHandle(SPI_Type *base, - dspi_slave_handle_t *handle, - dspi_slave_transfer_callback_t callback, - void *userData) -{ - assert(handle); - - /* Zero the handle. */ - memset(handle, 0, sizeof(*handle)); - - g_dspiHandle[DSPI_GetInstance(base)] = handle; - - handle->callback = callback; - handle->userData = userData; -} - -status_t DSPI_SlaveTransferNonBlocking(SPI_Type *base, dspi_slave_handle_t *handle, dspi_transfer_t *transfer) -{ - assert(handle); - assert(transfer); - - /* If receive length is zero */ - if (transfer->dataSize == 0) - { - return kStatus_InvalidArgument; - } - - /* If both send buffer and receive buffer is null */ - if ((!(transfer->txData)) && (!(transfer->rxData))) - { - return kStatus_InvalidArgument; - } - - /* Check that we're not busy.*/ - if (handle->state == kDSPI_Busy) - { - return kStatus_DSPI_Busy; - } - handle->state = kDSPI_Busy; - - /* Enable the NVIC for DSPI peripheral. */ - EnableIRQ(s_dspiIRQ[DSPI_GetInstance(base)]); - - /* Store transfer information */ - handle->txData = transfer->txData; - handle->rxData = transfer->rxData; - handle->remainingSendByteCount = transfer->dataSize; - handle->remainingReceiveByteCount = transfer->dataSize; - handle->totalByteCount = transfer->dataSize; - - handle->errorCount = 0; - - uint8_t whichCtar = (transfer->configFlags & DSPI_SLAVE_CTAR_MASK) >> DSPI_SLAVE_CTAR_SHIFT; - handle->bitsPerFrame = - (((base->CTAR_SLAVE[whichCtar]) & SPI_CTAR_SLAVE_FMSZ_MASK) >> SPI_CTAR_SLAVE_FMSZ_SHIFT) + 1; - - DSPI_StopTransfer(base); - - DSPI_FlushFifo(base, true, true); - DSPI_ClearStatusFlags(base, kDSPI_AllStatusFlag); - - DSPI_StartTransfer(base); - - /* Prepare data to transmit */ - DSPI_SlaveTransferFillUpTxFifo(base, handle); - - s_dspiSlaveIsr = DSPI_SlaveTransferHandleIRQ; - - /* Enable RX FIFO drain request, the slave only use this interrupt */ - DSPI_EnableInterrupts(base, kDSPI_RxFifoDrainRequestInterruptEnable); - - if (handle->rxData) - { - /* RX FIFO overflow request enable */ - DSPI_EnableInterrupts(base, kDSPI_RxFifoOverflowInterruptEnable); - } - if (handle->txData) - { - /* TX FIFO underflow request enable */ - DSPI_EnableInterrupts(base, kDSPI_TxFifoUnderflowInterruptEnable); - } - - return kStatus_Success; -} - -status_t DSPI_SlaveTransferGetCount(SPI_Type *base, dspi_slave_handle_t *handle, size_t *count) -{ - assert(handle); - - if (!count) - { - return kStatus_InvalidArgument; - } - - /* Catch when there is not an active transfer. */ - if (handle->state != kDSPI_Busy) - { - *count = 0; - return kStatus_NoTransferInProgress; - } - - *count = handle->totalByteCount - handle->remainingReceiveByteCount; - return kStatus_Success; -} - -static void DSPI_SlaveTransferFillUpTxFifo(SPI_Type *base, dspi_slave_handle_t *handle) -{ - assert(handle); - - uint16_t transmitData = 0; - uint8_t dummyPattern = DSPI_DUMMY_DATA; - - /* Service the transmitter, if transmit buffer provided, transmit the data, - * else transmit dummy pattern - */ - while (DSPI_GetStatusFlags(base) & kDSPI_TxFifoFillRequestFlag) - { - /* Transmit data */ - if (handle->remainingSendByteCount > 0) - { - /* Have data to transmit, update the transmit data and push to FIFO */ - if (handle->bitsPerFrame <= 8) - { - /* bits/frame is 1 byte */ - if (handle->txData) - { - /* Update transmit data and transmit pointer */ - transmitData = *handle->txData; - handle->txData++; - } - else - { - transmitData = dummyPattern; - } - - /* Decrease remaining dataSize */ - --handle->remainingSendByteCount; - } - /* bits/frame is 2 bytes */ - else - { - /* With multibytes per frame transmission, the transmit frame contains data from - * transmit buffer until sent dataSize matches user request. Other bytes will set to - * dummy pattern value. - */ - if (handle->txData) - { - /* Update first byte of transmit data and transmit pointer */ - transmitData = *handle->txData; - handle->txData++; - - if (handle->remainingSendByteCount == 1) - { - /* Decrease remaining dataSize */ - --handle->remainingSendByteCount; - /* Update second byte of transmit data to second byte of dummy pattern */ - transmitData = transmitData | (uint16_t)(((uint16_t)dummyPattern) << 8); - } - else - { - /* Update second byte of transmit data and transmit pointer */ - transmitData = transmitData | (uint16_t)((uint16_t)(*handle->txData) << 8); - handle->txData++; - handle->remainingSendByteCount -= 2; - } - } - else - { - if (handle->remainingSendByteCount == 1) - { - --handle->remainingSendByteCount; - } - else - { - handle->remainingSendByteCount -= 2; - } - transmitData = (uint16_t)((uint16_t)(dummyPattern) << 8) | dummyPattern; - } - } - } - else - { - break; - } - - /* Write the data to the DSPI data register */ - base->PUSHR_SLAVE = transmitData; - - /* Try to clear TFFF by writing a one to it; it will not clear if TX FIFO not full */ - DSPI_ClearStatusFlags(base, kDSPI_TxFifoFillRequestFlag); - } -} - -static void DSPI_SlaveTransferComplete(SPI_Type *base, dspi_slave_handle_t *handle) -{ - assert(handle); - - /* Disable interrupt requests */ - DSPI_DisableInterrupts(base, kDSPI_TxFifoUnderflowInterruptEnable | kDSPI_TxFifoFillRequestInterruptEnable | - kDSPI_RxFifoOverflowInterruptEnable | kDSPI_RxFifoDrainRequestInterruptEnable); - - /* The transfer is complete. */ - handle->txData = NULL; - handle->rxData = NULL; - handle->remainingReceiveByteCount = 0; - handle->remainingSendByteCount = 0; - - status_t status = 0; - if (handle->state == kDSPI_Error) - { - status = kStatus_DSPI_Error; - } - else - { - status = kStatus_Success; - } - - handle->state = kDSPI_Idle; - - if (handle->callback) - { - handle->callback(base, handle, status, handle->userData); - } -} - -void DSPI_SlaveTransferAbort(SPI_Type *base, dspi_slave_handle_t *handle) -{ - assert(handle); - - DSPI_StopTransfer(base); - - /* Disable interrupt requests */ - DSPI_DisableInterrupts(base, kDSPI_TxFifoUnderflowInterruptEnable | kDSPI_TxFifoFillRequestInterruptEnable | - kDSPI_RxFifoOverflowInterruptEnable | kDSPI_RxFifoDrainRequestInterruptEnable); - - handle->state = kDSPI_Idle; - handle->remainingSendByteCount = 0; - handle->remainingReceiveByteCount = 0; -} - -void DSPI_SlaveTransferHandleIRQ(SPI_Type *base, dspi_slave_handle_t *handle) -{ - assert(handle); - - uint8_t dummyPattern = DSPI_DUMMY_DATA; - uint32_t dataReceived; - uint32_t dataSend = 0; - - /* Because SPI protocol is synchronous, the number of bytes that that slave received from the - * master is the actual number of bytes that the slave transmitted to the master. So we only - * monitor the received dataSize to know when the transfer is complete. - */ - if (handle->remainingReceiveByteCount > 0) - { - while (DSPI_GetStatusFlags(base) & kDSPI_RxFifoDrainRequestFlag) - { - /* Have received data in the buffer. */ - dataReceived = base->POPR; - /*Clear the rx fifo drain request, needed for non-DMA applications as this flag - * will remain set even if the rx fifo is empty. By manually clearing this flag, it - * either remain clear if no more data is in the fifo, or it will set if there is - * more data in the fifo. - */ - DSPI_ClearStatusFlags(base, kDSPI_RxFifoDrainRequestFlag); - - /* If bits/frame is one byte */ - if (handle->bitsPerFrame <= 8) - { - if (handle->rxData) - { - /* Receive buffer is not null, store data into it */ - *handle->rxData = dataReceived; - ++handle->rxData; - } - /* Descrease remaining receive byte count */ - --handle->remainingReceiveByteCount; - - if (handle->remainingSendByteCount > 0) - { - if (handle->txData) - { - dataSend = *handle->txData; - ++handle->txData; - } - else - { - dataSend = dummyPattern; - } - - --handle->remainingSendByteCount; - /* Write the data to the DSPI data register */ - base->PUSHR_SLAVE = dataSend; - } - } - else /* If bits/frame is 2 bytes */ - { - /* With multibytes frame receiving, we only receive till the received dataSize - * matches user request. Other bytes will be ignored. - */ - if (handle->rxData) - { - /* Receive buffer is not null, store first byte into it */ - *handle->rxData = dataReceived; - ++handle->rxData; - - if (handle->remainingReceiveByteCount == 1) - { - /* Decrease remaining receive byte count */ - --handle->remainingReceiveByteCount; - } - else - { - /* Receive buffer is not null, store second byte into it */ - *handle->rxData = dataReceived >> 8; - ++handle->rxData; - handle->remainingReceiveByteCount -= 2; - } - } - /* If no handle->rxData*/ - else - { - if (handle->remainingReceiveByteCount == 1) - { - /* Decrease remaining receive byte count */ - --handle->remainingReceiveByteCount; - } - else - { - handle->remainingReceiveByteCount -= 2; - } - } - - if (handle->remainingSendByteCount > 0) - { - if (handle->txData) - { - dataSend = *handle->txData; - ++handle->txData; - - if (handle->remainingSendByteCount == 1) - { - --handle->remainingSendByteCount; - dataSend |= (uint16_t)((uint16_t)(dummyPattern) << 8); - } - else - { - dataSend |= (uint32_t)(*handle->txData) << 8; - ++handle->txData; - handle->remainingSendByteCount -= 2; - } - } - /* If no handle->txData*/ - else - { - if (handle->remainingSendByteCount == 1) - { - --handle->remainingSendByteCount; - } - else - { - handle->remainingSendByteCount -= 2; - } - dataSend = (uint16_t)((uint16_t)(dummyPattern) << 8) | dummyPattern; - } - /* Write the data to the DSPI data register */ - base->PUSHR_SLAVE = dataSend; - } - } - /* Try to clear TFFF by writing a one to it; it will not clear if TX FIFO not full */ - DSPI_ClearStatusFlags(base, kDSPI_TxFifoFillRequestFlag); - - if (handle->remainingReceiveByteCount == 0) - { - break; - } - } - } - /* Check if remaining receive byte count matches user request */ - if ((handle->remainingReceiveByteCount == 0) || (handle->state == kDSPI_Error)) - { - /* Other cases, stop the transfer. */ - DSPI_SlaveTransferComplete(base, handle); - return; - } - - /* Catch tx fifo underflow conditions, service only if tx under flow interrupt enabled */ - if ((DSPI_GetStatusFlags(base) & kDSPI_TxFifoUnderflowFlag) && (base->RSER & SPI_RSER_TFUF_RE_MASK)) - { - DSPI_ClearStatusFlags(base, kDSPI_TxFifoUnderflowFlag); - /* Change state to error and clear flag */ - if (handle->txData) - { - handle->state = kDSPI_Error; - } - handle->errorCount++; - } - /* Catch rx fifo overflow conditions, service only if rx over flow interrupt enabled */ - if ((DSPI_GetStatusFlags(base) & kDSPI_RxFifoOverflowFlag) && (base->RSER & SPI_RSER_RFOF_RE_MASK)) - { - DSPI_ClearStatusFlags(base, kDSPI_RxFifoOverflowFlag); - /* Change state to error and clear flag */ - if (handle->txData) - { - handle->state = kDSPI_Error; - } - handle->errorCount++; - } -} - -static void DSPI_CommonIRQHandler(SPI_Type *base, void *param) -{ - if (DSPI_IsMaster(base)) - { - s_dspiMasterIsr(base, (dspi_master_handle_t *)param); - } - else - { - s_dspiSlaveIsr(base, (dspi_slave_handle_t *)param); - } -} - -#if defined(SPI0) -void SPI0_DriverIRQHandler(void) -{ - assert(g_dspiHandle[0]); - DSPI_CommonIRQHandler(SPI0, g_dspiHandle[0]); -} -#endif - -#if defined(SPI1) -void SPI1_DriverIRQHandler(void) -{ - assert(g_dspiHandle[1]); - DSPI_CommonIRQHandler(SPI1, g_dspiHandle[1]); -} -#endif - -#if defined(SPI2) -void SPI2_DriverIRQHandler(void) -{ - assert(g_dspiHandle[2]); - DSPI_CommonIRQHandler(SPI2, g_dspiHandle[2]); -} -#endif - -#if defined(SPI3) -void SPI3_DriverIRQHandler(void) -{ - assert(g_dspiHandle[3]); - DSPI_CommonIRQHandler(SPI3, g_dspiHandle[3]); -} -#endif - -#if defined(SPI4) -void SPI4_DriverIRQHandler(void) -{ - assert(g_dspiHandle[4]); - DSPI_CommonIRQHandler(SPI4, g_dspiHandle[4]); -} -#endif - -#if defined(SPI5) -void SPI5_DriverIRQHandler(void) -{ - assert(g_dspiHandle[5]); - DSPI_CommonIRQHandler(SPI5, g_dspiHandle[5]); -} -#endif - -#if (FSL_FEATURE_SOC_DSPI_COUNT > 6) -#error "Should write the SPIx_DriverIRQHandler function that instance greater than 5 !" -#endif diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_dspi.h b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_dspi.h deleted file mode 100644 index 5dd96afcbe0..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_dspi.h +++ /dev/null @@ -1,1180 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -#ifndef _FSL_DSPI_H_ -#define _FSL_DSPI_H_ - -#include "fsl_common.h" - -/*! - * @addtogroup dspi_driver - * @{ - */ - - -/********************************************************************************************************************** - * Definitions - *********************************************************************************************************************/ - -/*! @name Driver version */ -/*@{*/ -/*! @brief DSPI driver version 2.1.4. */ -#define FSL_DSPI_DRIVER_VERSION (MAKE_VERSION(2, 1, 4)) -/*@}*/ - -#ifndef DSPI_DUMMY_DATA -/*! @brief DSPI dummy data if there is no Tx data.*/ -#define DSPI_DUMMY_DATA (0x00U) /*!< Dummy data used for Tx if there is no txData. */ -#endif - -/*! @brief Status for the DSPI driver.*/ -enum _dspi_status -{ - kStatus_DSPI_Busy = MAKE_STATUS(kStatusGroup_DSPI, 0), /*!< DSPI transfer is busy.*/ - kStatus_DSPI_Error = MAKE_STATUS(kStatusGroup_DSPI, 1), /*!< DSPI driver error. */ - kStatus_DSPI_Idle = MAKE_STATUS(kStatusGroup_DSPI, 2), /*!< DSPI is idle.*/ - kStatus_DSPI_OutOfRange = MAKE_STATUS(kStatusGroup_DSPI, 3) /*!< DSPI transfer out of range. */ -}; - -/*! @brief DSPI status flags in SPIx_SR register.*/ -enum _dspi_flags -{ - kDSPI_TxCompleteFlag = SPI_SR_TCF_MASK, /*!< Transfer Complete Flag. */ - kDSPI_EndOfQueueFlag = SPI_SR_EOQF_MASK, /*!< End of Queue Flag.*/ - kDSPI_TxFifoUnderflowFlag = SPI_SR_TFUF_MASK, /*!< Transmit FIFO Underflow Flag.*/ - kDSPI_TxFifoFillRequestFlag = SPI_SR_TFFF_MASK, /*!< Transmit FIFO Fill Flag.*/ - kDSPI_RxFifoOverflowFlag = SPI_SR_RFOF_MASK, /*!< Receive FIFO Overflow Flag.*/ - kDSPI_RxFifoDrainRequestFlag = SPI_SR_RFDF_MASK, /*!< Receive FIFO Drain Flag.*/ - kDSPI_TxAndRxStatusFlag = SPI_SR_TXRXS_MASK, /*!< The module is in Stopped/Running state.*/ - kDSPI_AllStatusFlag = SPI_SR_TCF_MASK | SPI_SR_EOQF_MASK | SPI_SR_TFUF_MASK | SPI_SR_TFFF_MASK | SPI_SR_RFOF_MASK | - SPI_SR_RFDF_MASK | SPI_SR_TXRXS_MASK /*!< All statuses above.*/ -}; - -/*! @brief DSPI interrupt source.*/ -enum _dspi_interrupt_enable -{ - kDSPI_TxCompleteInterruptEnable = SPI_RSER_TCF_RE_MASK, /*!< TCF interrupt enable.*/ - kDSPI_EndOfQueueInterruptEnable = SPI_RSER_EOQF_RE_MASK, /*!< EOQF interrupt enable.*/ - kDSPI_TxFifoUnderflowInterruptEnable = SPI_RSER_TFUF_RE_MASK, /*!< TFUF interrupt enable.*/ - kDSPI_TxFifoFillRequestInterruptEnable = SPI_RSER_TFFF_RE_MASK, /*!< TFFF interrupt enable, DMA disable.*/ - kDSPI_RxFifoOverflowInterruptEnable = SPI_RSER_RFOF_RE_MASK, /*!< RFOF interrupt enable.*/ - kDSPI_RxFifoDrainRequestInterruptEnable = SPI_RSER_RFDF_RE_MASK, /*!< RFDF interrupt enable, DMA disable.*/ - kDSPI_AllInterruptEnable = SPI_RSER_TCF_RE_MASK | SPI_RSER_EOQF_RE_MASK | SPI_RSER_TFUF_RE_MASK | - SPI_RSER_TFFF_RE_MASK | SPI_RSER_RFOF_RE_MASK | SPI_RSER_RFDF_RE_MASK - /*!< All above interrupts enable.*/ -}; - -/*! @brief DSPI DMA source.*/ -enum _dspi_dma_enable -{ - kDSPI_TxDmaEnable = (SPI_RSER_TFFF_RE_MASK | SPI_RSER_TFFF_DIRS_MASK), /*!< TFFF flag generates DMA requests. - No Tx interrupt request. */ - kDSPI_RxDmaEnable = (SPI_RSER_RFDF_RE_MASK | SPI_RSER_RFDF_DIRS_MASK) /*!< RFDF flag generates DMA requests. - No Rx interrupt request. */ -}; - -/*! @brief DSPI master or slave mode configuration.*/ -typedef enum _dspi_master_slave_mode -{ - kDSPI_Master = 1U, /*!< DSPI peripheral operates in master mode.*/ - kDSPI_Slave = 0U /*!< DSPI peripheral operates in slave mode.*/ -} dspi_master_slave_mode_t; - -/*! - * @brief DSPI Sample Point: Controls when the DSPI master samples SIN in the Modified Transfer Format. This field is valid - * only when the CPHA bit in the CTAR register is 0. - */ -typedef enum _dspi_master_sample_point -{ - kDSPI_SckToSin0Clock = 0U, /*!< 0 system clocks between SCK edge and SIN sample.*/ - kDSPI_SckToSin1Clock = 1U, /*!< 1 system clock between SCK edge and SIN sample.*/ - kDSPI_SckToSin2Clock = 2U /*!< 2 system clocks between SCK edge and SIN sample.*/ -} dspi_master_sample_point_t; - -/*! @brief DSPI Peripheral Chip Select (Pcs) configuration (which Pcs to configure).*/ -typedef enum _dspi_which_pcs_config -{ - kDSPI_Pcs0 = 1U << 0, /*!< Pcs[0] */ - kDSPI_Pcs1 = 1U << 1, /*!< Pcs[1] */ - kDSPI_Pcs2 = 1U << 2, /*!< Pcs[2] */ - kDSPI_Pcs3 = 1U << 3, /*!< Pcs[3] */ - kDSPI_Pcs4 = 1U << 4, /*!< Pcs[4] */ - kDSPI_Pcs5 = 1U << 5 /*!< Pcs[5] */ -} dspi_which_pcs_t; - -/*! @brief DSPI Peripheral Chip Select (Pcs) Polarity configuration.*/ -typedef enum _dspi_pcs_polarity_config -{ - kDSPI_PcsActiveHigh = 0U, /*!< Pcs Active High (idles low). */ - kDSPI_PcsActiveLow = 1U /*!< Pcs Active Low (idles high). */ -} dspi_pcs_polarity_config_t; - -/*! @brief DSPI Peripheral Chip Select (Pcs) Polarity.*/ -enum _dspi_pcs_polarity -{ - kDSPI_Pcs0ActiveLow = 1U << 0, /*!< Pcs0 Active Low (idles high). */ - kDSPI_Pcs1ActiveLow = 1U << 1, /*!< Pcs1 Active Low (idles high). */ - kDSPI_Pcs2ActiveLow = 1U << 2, /*!< Pcs2 Active Low (idles high). */ - kDSPI_Pcs3ActiveLow = 1U << 3, /*!< Pcs3 Active Low (idles high). */ - kDSPI_Pcs4ActiveLow = 1U << 4, /*!< Pcs4 Active Low (idles high). */ - kDSPI_Pcs5ActiveLow = 1U << 5, /*!< Pcs5 Active Low (idles high). */ - kDSPI_PcsAllActiveLow = 0xFFU /*!< Pcs0 to Pcs5 Active Low (idles high). */ -}; - -/*! @brief DSPI clock polarity configuration for a given CTAR.*/ -typedef enum _dspi_clock_polarity -{ - kDSPI_ClockPolarityActiveHigh = 0U, /*!< CPOL=0. Active-high DSPI clock (idles low).*/ - kDSPI_ClockPolarityActiveLow = 1U /*!< CPOL=1. Active-low DSPI clock (idles high).*/ -} dspi_clock_polarity_t; - -/*! @brief DSPI clock phase configuration for a given CTAR.*/ -typedef enum _dspi_clock_phase -{ - kDSPI_ClockPhaseFirstEdge = 0U, /*!< CPHA=0. Data is captured on the leading edge of the SCK and changed on the - following edge.*/ - kDSPI_ClockPhaseSecondEdge = 1U /*!< CPHA=1. Data is changed on the leading edge of the SCK and captured on the - following edge.*/ -} dspi_clock_phase_t; - -/*! @brief DSPI data shifter direction options for a given CTAR.*/ -typedef enum _dspi_shift_direction -{ - kDSPI_MsbFirst = 0U, /*!< Data transfers start with most significant bit.*/ - kDSPI_LsbFirst = 1U /*!< Data transfers start with least significant bit. - Shifting out of LSB is not supported for slave */ -} dspi_shift_direction_t; - -/*! @brief DSPI delay type selection.*/ -typedef enum _dspi_delay_type -{ - kDSPI_PcsToSck = 1U, /*!< Pcs-to-SCK delay. */ - kDSPI_LastSckToPcs, /*!< The last SCK edge to Pcs delay. */ - kDSPI_BetweenTransfer /*!< Delay between transfers. */ -} dspi_delay_type_t; - -/*! @brief DSPI Clock and Transfer Attributes Register (CTAR) selection.*/ -typedef enum _dspi_ctar_selection -{ - kDSPI_Ctar0 = 0U, /*!< CTAR0 selection option for master or slave mode; note that CTAR0 and CTAR0_SLAVE are the - same register address. */ - kDSPI_Ctar1 = 1U, /*!< CTAR1 selection option for master mode only. */ - kDSPI_Ctar2 = 2U, /*!< CTAR2 selection option for master mode only; note that some devices do not support CTAR2. */ - kDSPI_Ctar3 = 3U, /*!< CTAR3 selection option for master mode only; note that some devices do not support CTAR3. */ - kDSPI_Ctar4 = 4U, /*!< CTAR4 selection option for master mode only; note that some devices do not support CTAR4. */ - kDSPI_Ctar5 = 5U, /*!< CTAR5 selection option for master mode only; note that some devices do not support CTAR5. */ - kDSPI_Ctar6 = 6U, /*!< CTAR6 selection option for master mode only; note that some devices do not support CTAR6. */ - kDSPI_Ctar7 = 7U /*!< CTAR7 selection option for master mode only; note that some devices do not support CTAR7. */ -} dspi_ctar_selection_t; - -#define DSPI_MASTER_CTAR_SHIFT (0U) /*!< DSPI master CTAR shift macro; used internally. */ -#define DSPI_MASTER_CTAR_MASK (0x0FU) /*!< DSPI master CTAR mask macro; used internally. */ -#define DSPI_MASTER_PCS_SHIFT (4U) /*!< DSPI master PCS shift macro; used internally. */ -#define DSPI_MASTER_PCS_MASK (0xF0U) /*!< DSPI master PCS mask macro; used internally. */ -/*! @brief Use this enumeration for the DSPI master transfer configFlags. */ -enum _dspi_transfer_config_flag_for_master -{ - kDSPI_MasterCtar0 = 0U << DSPI_MASTER_CTAR_SHIFT, /*!< DSPI master transfer use CTAR0 setting. */ - kDSPI_MasterCtar1 = 1U << DSPI_MASTER_CTAR_SHIFT, /*!< DSPI master transfer use CTAR1 setting. */ - kDSPI_MasterCtar2 = 2U << DSPI_MASTER_CTAR_SHIFT, /*!< DSPI master transfer use CTAR2 setting. */ - kDSPI_MasterCtar3 = 3U << DSPI_MASTER_CTAR_SHIFT, /*!< DSPI master transfer use CTAR3 setting. */ - kDSPI_MasterCtar4 = 4U << DSPI_MASTER_CTAR_SHIFT, /*!< DSPI master transfer use CTAR4 setting. */ - kDSPI_MasterCtar5 = 5U << DSPI_MASTER_CTAR_SHIFT, /*!< DSPI master transfer use CTAR5 setting. */ - kDSPI_MasterCtar6 = 6U << DSPI_MASTER_CTAR_SHIFT, /*!< DSPI master transfer use CTAR6 setting. */ - kDSPI_MasterCtar7 = 7U << DSPI_MASTER_CTAR_SHIFT, /*!< DSPI master transfer use CTAR7 setting. */ - - kDSPI_MasterPcs0 = 0U << DSPI_MASTER_PCS_SHIFT, /*!< DSPI master transfer use PCS0 signal. */ - kDSPI_MasterPcs1 = 1U << DSPI_MASTER_PCS_SHIFT, /*!< DSPI master transfer use PCS1 signal. */ - kDSPI_MasterPcs2 = 2U << DSPI_MASTER_PCS_SHIFT, /*!< DSPI master transfer use PCS2 signal.*/ - kDSPI_MasterPcs3 = 3U << DSPI_MASTER_PCS_SHIFT, /*!< DSPI master transfer use PCS3 signal. */ - kDSPI_MasterPcs4 = 4U << DSPI_MASTER_PCS_SHIFT, /*!< DSPI master transfer use PCS4 signal. */ - kDSPI_MasterPcs5 = 5U << DSPI_MASTER_PCS_SHIFT, /*!< DSPI master transfer use PCS5 signal. */ - - kDSPI_MasterPcsContinuous = 1U << 20, /*!< Indicates whether the PCS signal is continuous. */ - kDSPI_MasterActiveAfterTransfer = 1U << 21, /*!< Indicates whether the PCS signal is active after the last frame transfer.*/ -}; - -#define DSPI_SLAVE_CTAR_SHIFT (0U) /*!< DSPI slave CTAR shift macro; used internally. */ -#define DSPI_SLAVE_CTAR_MASK (0x07U) /*!< DSPI slave CTAR mask macro; used internally. */ -/*! @brief Use this enumeration for the DSPI slave transfer configFlags. */ -enum _dspi_transfer_config_flag_for_slave -{ - kDSPI_SlaveCtar0 = 0U << DSPI_SLAVE_CTAR_SHIFT, /*!< DSPI slave transfer use CTAR0 setting. */ - /*!< DSPI slave can only use PCS0. */ -}; - -/*! @brief DSPI transfer state, which is used for DSPI transactional API state machine. */ -enum _dspi_transfer_state -{ - kDSPI_Idle = 0x0U, /*!< Nothing in the transmitter/receiver. */ - kDSPI_Busy, /*!< Transfer queue is not finished. */ - kDSPI_Error /*!< Transfer error. */ -}; - -/*! @brief DSPI master command date configuration used for the SPIx_PUSHR.*/ -typedef struct _dspi_command_data_config -{ - bool isPcsContinuous; /*!< Option to enable the continuous assertion of the chip select between transfers.*/ - dspi_ctar_selection_t whichCtar; /*!< The desired Clock and Transfer Attributes - Register (CTAR) to use for CTAS.*/ - dspi_which_pcs_t whichPcs; /*!< The desired PCS signal to use for the data transfer.*/ - bool isEndOfQueue; /*!< Signals that the current transfer is the last in the queue.*/ - bool clearTransferCount; /*!< Clears the SPI Transfer Counter (SPI_TCNT) before transmission starts.*/ -} dspi_command_data_config_t; - -/*! @brief DSPI master ctar configuration structure.*/ -typedef struct _dspi_master_ctar_config -{ - uint32_t baudRate; /*!< Baud Rate for DSPI. */ - uint32_t bitsPerFrame; /*!< Bits per frame, minimum 4, maximum 16.*/ - dspi_clock_polarity_t cpol; /*!< Clock polarity. */ - dspi_clock_phase_t cpha; /*!< Clock phase. */ - dspi_shift_direction_t direction; /*!< MSB or LSB data shift direction. */ - - uint32_t pcsToSckDelayInNanoSec; /*!< PCS to SCK delay time in nanoseconds; setting to 0 sets the minimum - delay. It also sets the boundary value if out of range.*/ - uint32_t lastSckToPcsDelayInNanoSec; /*!< The last SCK to PCS delay time in nanoseconds; setting to 0 sets the - minimum delay. It also sets the boundary value if out of range.*/ - - uint32_t betweenTransferDelayInNanoSec; /*!< After the SCK delay time in nanoseconds; setting to 0 sets the minimum - delay. It also sets the boundary value if out of range.*/ -} dspi_master_ctar_config_t; - -/*! @brief DSPI master configuration structure.*/ -typedef struct _dspi_master_config -{ - dspi_ctar_selection_t whichCtar; /*!< The desired CTAR to use. */ - dspi_master_ctar_config_t ctarConfig; /*!< Set the ctarConfig to the desired CTAR. */ - - dspi_which_pcs_t whichPcs; /*!< The desired Peripheral Chip Select (pcs). */ - dspi_pcs_polarity_config_t pcsActiveHighOrLow; /*!< The desired PCS active high or low. */ - - bool enableContinuousSCK; /*!< CONT_SCKE, continuous SCK enable. Note that the continuous SCK is only - supported for CPHA = 1.*/ - bool enableRxFifoOverWrite; /*!< ROOE, receive FIFO overflow overwrite enable. If ROOE = 0, the incoming - data is ignored and the data from the transfer that generated the overflow - is also ignored. If ROOE = 1, the incoming data is shifted to the - shift register. */ - - bool enableModifiedTimingFormat; /*!< Enables a modified transfer format to be used if true.*/ - dspi_master_sample_point_t samplePoint; /*!< Controls when the module master samples SIN in the Modified Transfer - Format. It's valid only when CPHA=0. */ -} dspi_master_config_t; - -/*! @brief DSPI slave ctar configuration structure.*/ -typedef struct _dspi_slave_ctar_config -{ - uint32_t bitsPerFrame; /*!< Bits per frame, minimum 4, maximum 16.*/ - dspi_clock_polarity_t cpol; /*!< Clock polarity. */ - dspi_clock_phase_t cpha; /*!< Clock phase. */ - /*!< Slave only supports MSB and does not support LSB.*/ -} dspi_slave_ctar_config_t; - -/*! @brief DSPI slave configuration structure.*/ -typedef struct _dspi_slave_config -{ - dspi_ctar_selection_t whichCtar; /*!< The desired CTAR to use. */ - dspi_slave_ctar_config_t ctarConfig; /*!< Set the ctarConfig to the desired CTAR. */ - - bool enableContinuousSCK; /*!< CONT_SCKE, continuous SCK enable. Note that the continuous SCK is only - supported for CPHA = 1.*/ - bool enableRxFifoOverWrite; /*!< ROOE, receive FIFO overflow overwrite enable. If ROOE = 0, the incoming - data is ignored and the data from the transfer that generated the overflow - is also ignored. If ROOE = 1, the incoming data is shifted to the - shift register. */ - bool enableModifiedTimingFormat; /*!< Enables a modified transfer format to be used if true.*/ - dspi_master_sample_point_t samplePoint; /*!< Controls when the module master samples SIN in the Modified Transfer - Format. It's valid only when CPHA=0. */ -} dspi_slave_config_t; - -/*! -* @brief Forward declaration of the _dspi_master_handle typedefs. -*/ -typedef struct _dspi_master_handle dspi_master_handle_t; - -/*! -* @brief Forward declaration of the _dspi_slave_handle typedefs. -*/ -typedef struct _dspi_slave_handle dspi_slave_handle_t; - -/*! - * @brief Completion callback function pointer type. - * - * @param base DSPI peripheral address. - * @param handle Pointer to the handle for the DSPI master. - * @param status Success or error code describing whether the transfer completed. - * @param userData Arbitrary pointer-dataSized value passed from the application. - */ -typedef void (*dspi_master_transfer_callback_t)(SPI_Type *base, - dspi_master_handle_t *handle, - status_t status, - void *userData); -/*! - * @brief Completion callback function pointer type. - * - * @param base DSPI peripheral address. - * @param handle Pointer to the handle for the DSPI slave. - * @param status Success or error code describing whether the transfer completed. - * @param userData Arbitrary pointer-dataSized value passed from the application. - */ -typedef void (*dspi_slave_transfer_callback_t)(SPI_Type *base, - dspi_slave_handle_t *handle, - status_t status, - void *userData); - -/*! @brief DSPI master/slave transfer structure.*/ -typedef struct _dspi_transfer -{ - uint8_t *txData; /*!< Send buffer. */ - uint8_t *rxData; /*!< Receive buffer. */ - volatile size_t dataSize; /*!< Transfer bytes. */ - - uint32_t - configFlags; /*!< Transfer transfer configuration flags; set from _dspi_transfer_config_flag_for_master if the - transfer is used for master or _dspi_transfer_config_flag_for_slave enumeration if the transfer - is used for slave.*/ -} dspi_transfer_t; - -/*! @brief DSPI master transfer handle structure used for transactional API. */ -struct _dspi_master_handle -{ - uint32_t bitsPerFrame; /*!< The desired number of bits per frame. */ - volatile uint32_t command; /*!< The desired data command. */ - volatile uint32_t lastCommand; /*!< The desired last data command. */ - - uint8_t fifoSize; /*!< FIFO dataSize. */ - - volatile bool isPcsActiveAfterTransfer; /*!< Indicates whether the PCS signal is active after the last frame transfer.*/ - volatile bool isThereExtraByte; /*!< Indicates whether there are extra bytes.*/ - - uint8_t *volatile txData; /*!< Send buffer. */ - uint8_t *volatile rxData; /*!< Receive buffer. */ - volatile size_t remainingSendByteCount; /*!< A number of bytes remaining to send.*/ - volatile size_t remainingReceiveByteCount; /*!< A number of bytes remaining to receive.*/ - size_t totalByteCount; /*!< A number of transfer bytes*/ - - volatile uint8_t state; /*!< DSPI transfer state, see _dspi_transfer_state.*/ - - dspi_master_transfer_callback_t callback; /*!< Completion callback. */ - void *userData; /*!< Callback user data. */ -}; - -/*! @brief DSPI slave transfer handle structure used for the transactional API. */ -struct _dspi_slave_handle -{ - uint32_t bitsPerFrame; /*!< The desired number of bits per frame. */ - volatile bool isThereExtraByte; /*!< Indicates whether there are extra bytes.*/ - - uint8_t *volatile txData; /*!< Send buffer. */ - uint8_t *volatile rxData; /*!< Receive buffer. */ - volatile size_t remainingSendByteCount; /*!< A number of bytes remaining to send.*/ - volatile size_t remainingReceiveByteCount; /*!< A number of bytes remaining to receive.*/ - size_t totalByteCount; /*!< A number of transfer bytes*/ - - volatile uint8_t state; /*!< DSPI transfer state.*/ - - volatile uint32_t errorCount; /*!< Error count for slave transfer.*/ - - dspi_slave_transfer_callback_t callback; /*!< Completion callback. */ - void *userData; /*!< Callback user data. */ -}; - -/********************************************************************************************************************** - * API - *********************************************************************************************************************/ -#if defined(__cplusplus) -extern "C" { -#endif /*_cplusplus*/ - -/*! - * @name Initialization and deinitialization - * @{ - */ - -/*! - * @brief Initializes the DSPI master. - * - * This function initializes the DSPI master configuration. This is an example use case. - * @code - * dspi_master_config_t masterConfig; - * masterConfig.whichCtar = kDSPI_Ctar0; - * masterConfig.ctarConfig.baudRate = 500000000U; - * masterConfig.ctarConfig.bitsPerFrame = 8; - * masterConfig.ctarConfig.cpol = kDSPI_ClockPolarityActiveHigh; - * masterConfig.ctarConfig.cpha = kDSPI_ClockPhaseFirstEdge; - * masterConfig.ctarConfig.direction = kDSPI_MsbFirst; - * masterConfig.ctarConfig.pcsToSckDelayInNanoSec = 1000000000U / masterConfig.ctarConfig.baudRate ; - * masterConfig.ctarConfig.lastSckToPcsDelayInNanoSec = 1000000000U / masterConfig.ctarConfig.baudRate ; - * masterConfig.ctarConfig.betweenTransferDelayInNanoSec = 1000000000U / masterConfig.ctarConfig.baudRate ; - * masterConfig.whichPcs = kDSPI_Pcs0; - * masterConfig.pcsActiveHighOrLow = kDSPI_PcsActiveLow; - * masterConfig.enableContinuousSCK = false; - * masterConfig.enableRxFifoOverWrite = false; - * masterConfig.enableModifiedTimingFormat = false; - * masterConfig.samplePoint = kDSPI_SckToSin0Clock; - * DSPI_MasterInit(base, &masterConfig, srcClock_Hz); - * @endcode - * - * @param base DSPI peripheral address. - * @param masterConfig Pointer to the structure dspi_master_config_t. - * @param srcClock_Hz Module source input clock in Hertz. - */ -void DSPI_MasterInit(SPI_Type *base, const dspi_master_config_t *masterConfig, uint32_t srcClock_Hz); - -/*! - * @brief Sets the dspi_master_config_t structure to default values. - * - * The purpose of this API is to get the configuration structure initialized for the DSPI_MasterInit(). - * Users may use the initialized structure unchanged in the DSPI_MasterInit() or modify the structure - * before calling the DSPI_MasterInit(). - * Example: - * @code - * dspi_master_config_t masterConfig; - * DSPI_MasterGetDefaultConfig(&masterConfig); - * @endcode - * @param masterConfig pointer to dspi_master_config_t structure - */ -void DSPI_MasterGetDefaultConfig(dspi_master_config_t *masterConfig); - -/*! - * @brief DSPI slave configuration. - * - * This function initializes the DSPI slave configuration. This is an example use case. - * @code - * dspi_slave_config_t slaveConfig; - * slaveConfig->whichCtar = kDSPI_Ctar0; - * slaveConfig->ctarConfig.bitsPerFrame = 8; - * slaveConfig->ctarConfig.cpol = kDSPI_ClockPolarityActiveHigh; - * slaveConfig->ctarConfig.cpha = kDSPI_ClockPhaseFirstEdge; - * slaveConfig->enableContinuousSCK = false; - * slaveConfig->enableRxFifoOverWrite = false; - * slaveConfig->enableModifiedTimingFormat = false; - * slaveConfig->samplePoint = kDSPI_SckToSin0Clock; - * DSPI_SlaveInit(base, &slaveConfig); - * @endcode - * - * @param base DSPI peripheral address. - * @param slaveConfig Pointer to the structure dspi_master_config_t. - */ -void DSPI_SlaveInit(SPI_Type *base, const dspi_slave_config_t *slaveConfig); - -/*! - * @brief Sets the dspi_slave_config_t structure to a default value. - * - * The purpose of this API is to get the configuration structure initialized for the DSPI_SlaveInit(). - * Users may use the initialized structure unchanged in the DSPI_SlaveInit() or modify the structure - * before calling the DSPI_SlaveInit(). - * This is an example. - * @code - * dspi_slave_config_t slaveConfig; - * DSPI_SlaveGetDefaultConfig(&slaveConfig); - * @endcode - * @param slaveConfig Pointer to the dspi_slave_config_t structure. - */ -void DSPI_SlaveGetDefaultConfig(dspi_slave_config_t *slaveConfig); - -/*! - * @brief De-initializes the DSPI peripheral. Call this API to disable the DSPI clock. - * @param base DSPI peripheral address. - */ -void DSPI_Deinit(SPI_Type *base); - -/*! - * @brief Enables the DSPI peripheral and sets the MCR MDIS to 0. - * - * @param base DSPI peripheral address. - * @param enable Pass true to enable module, false to disable module. - */ -static inline void DSPI_Enable(SPI_Type *base, bool enable) -{ - if (enable) - { - base->MCR &= ~SPI_MCR_MDIS_MASK; - } - else - { - base->MCR |= SPI_MCR_MDIS_MASK; - } -} - -/*! - *@} -*/ - -/*! - * @name Status - * @{ - */ - -/*! - * @brief Gets the DSPI status flag state. - * @param base DSPI peripheral address. - * @return DSPI status (in SR register). - */ -static inline uint32_t DSPI_GetStatusFlags(SPI_Type *base) -{ - return (base->SR); -} - -/*! - * @brief Clears the DSPI status flag. - * - * This function clears the desired status bit by using a write-1-to-clear. The user passes in the base and the - * desired status bit to clear. The list of status bits is defined in the dspi_status_and_interrupt_request_t. The - * function uses these bit positions in its algorithm to clear the desired flag state. - * This is an example. - * @code - * DSPI_ClearStatusFlags(base, kDSPI_TxCompleteFlag|kDSPI_EndOfQueueFlag); - * @endcode - * - * @param base DSPI peripheral address. - * @param statusFlags The status flag used from the type dspi_flags. - */ -static inline void DSPI_ClearStatusFlags(SPI_Type *base, uint32_t statusFlags) -{ - base->SR = statusFlags; /*!< The status flags are cleared by writing 1 (w1c).*/ -} - -/*! - *@} -*/ - -/*! - * @name Interrupts - * @{ - */ - -/*! - * @brief Enables the DSPI interrupts. - * - * This function configures the various interrupt masks of the DSPI. The parameters are a base and an interrupt mask. - * Note, for Tx Fill and Rx FIFO drain requests, enable the interrupt request and disable the DMA request. - * - * @code - * DSPI_EnableInterrupts(base, kDSPI_TxCompleteInterruptEnable | kDSPI_EndOfQueueInterruptEnable ); - * @endcode - * - * @param base DSPI peripheral address. - * @param mask The interrupt mask; use the enum _dspi_interrupt_enable. - */ -void DSPI_EnableInterrupts(SPI_Type *base, uint32_t mask); - -/*! - * @brief Disables the DSPI interrupts. - * - * @code - * DSPI_DisableInterrupts(base, kDSPI_TxCompleteInterruptEnable | kDSPI_EndOfQueueInterruptEnable ); - * @endcode - * - * @param base DSPI peripheral address. - * @param mask The interrupt mask; use the enum _dspi_interrupt_enable. - */ -static inline void DSPI_DisableInterrupts(SPI_Type *base, uint32_t mask) -{ - base->RSER &= ~mask; -} - -/*! - *@} -*/ - -/*! - * @name DMA Control - * @{ - */ - -/*! - * @brief Enables the DSPI DMA request. - * - * This function configures the Rx and Tx DMA mask of the DSPI. The parameters are a base and a DMA mask. - * @code - * DSPI_EnableDMA(base, kDSPI_TxDmaEnable | kDSPI_RxDmaEnable); - * @endcode - * - * @param base DSPI peripheral address. - * @param mask The interrupt mask; use the enum dspi_dma_enable. - */ -static inline void DSPI_EnableDMA(SPI_Type *base, uint32_t mask) -{ - base->RSER |= mask; -} - -/*! - * @brief Disables the DSPI DMA request. - * - * This function configures the Rx and Tx DMA mask of the DSPI. The parameters are a base and a DMA mask. - * @code - * SPI_DisableDMA(base, kDSPI_TxDmaEnable | kDSPI_RxDmaEnable); - * @endcode - * - * @param base DSPI peripheral address. - * @param mask The interrupt mask; use the enum dspi_dma_enable. - */ -static inline void DSPI_DisableDMA(SPI_Type *base, uint32_t mask) -{ - base->RSER &= ~mask; -} - -/*! - * @brief Gets the DSPI master PUSHR data register address for the DMA operation. - * - * This function gets the DSPI master PUSHR data register address because this value is needed for the DMA operation. - * - * @param base DSPI peripheral address. - * @return The DSPI master PUSHR data register address. - */ -static inline uint32_t DSPI_MasterGetTxRegisterAddress(SPI_Type *base) -{ - return (uint32_t) & (base->PUSHR); -} - -/*! - * @brief Gets the DSPI slave PUSHR data register address for the DMA operation. - * - * This function gets the DSPI slave PUSHR data register address as this value is needed for the DMA operation. - * - * @param base DSPI peripheral address. - * @return The DSPI slave PUSHR data register address. - */ -static inline uint32_t DSPI_SlaveGetTxRegisterAddress(SPI_Type *base) -{ - return (uint32_t) & (base->PUSHR_SLAVE); -} - -/*! - * @brief Gets the DSPI POPR data register address for the DMA operation. - * - * This function gets the DSPI POPR data register address as this value is needed for the DMA operation. - * - * @param base DSPI peripheral address. - * @return The DSPI POPR data register address. - */ -static inline uint32_t DSPI_GetRxRegisterAddress(SPI_Type *base) -{ - return (uint32_t) & (base->POPR); -} - -/*! - *@} -*/ - -/*! - * @name Bus Operations - * @{ - */ - -/*! - * @brief Configures the DSPI for master or slave. - * - * @param base DSPI peripheral address. - * @param mode Mode setting (master or slave) of type dspi_master_slave_mode_t. - */ -static inline void DSPI_SetMasterSlaveMode(SPI_Type *base, dspi_master_slave_mode_t mode) -{ - base->MCR = (base->MCR & (~SPI_MCR_MSTR_MASK)) | SPI_MCR_MSTR(mode); -} - -/*! - * @brief Returns whether the DSPI module is in master mode. - * - * @param base DSPI peripheral address. - * @return Returns true if the module is in master mode or false if the module is in slave mode. - */ -static inline bool DSPI_IsMaster(SPI_Type *base) -{ - return (bool)((base->MCR) & SPI_MCR_MSTR_MASK); -} -/*! - * @brief Starts the DSPI transfers and clears HALT bit in MCR. - * - * This function sets the module to start data transfer in either master or slave mode. - * - * @param base DSPI peripheral address. - */ -static inline void DSPI_StartTransfer(SPI_Type *base) -{ - base->MCR &= ~SPI_MCR_HALT_MASK; -} -/*! - * @brief Stops DSPI transfers and sets the HALT bit in MCR. - * - * This function stops data transfers in either master or slave modes. - * - * @param base DSPI peripheral address. - */ -static inline void DSPI_StopTransfer(SPI_Type *base) -{ - base->MCR |= SPI_MCR_HALT_MASK; -} - -/*! - * @brief Enables or disables the DSPI FIFOs. - * - * This function allows the caller to disable/enable the Tx and Rx FIFOs independently. - * Note that to disable, pass in a logic 0 (false) for the particular FIFO configuration. To enable, - * pass in a logic 1 (true). - * - * @param base DSPI peripheral address. - * @param enableTxFifo Disables (false) the TX FIFO; Otherwise, enables (true) the TX FIFO - * @param enableRxFifo Disables (false) the RX FIFO; Otherwise, enables (true) the RX FIFO - */ -static inline void DSPI_SetFifoEnable(SPI_Type *base, bool enableTxFifo, bool enableRxFifo) -{ - base->MCR = (base->MCR & (~(SPI_MCR_DIS_RXF_MASK | SPI_MCR_DIS_TXF_MASK))) | SPI_MCR_DIS_TXF(!enableTxFifo) | - SPI_MCR_DIS_RXF(!enableRxFifo); -} - -/*! - * @brief Flushes the DSPI FIFOs. - * - * @param base DSPI peripheral address. - * @param flushTxFifo Flushes (true) the Tx FIFO; Otherwise, does not flush (false) the Tx FIFO - * @param flushRxFifo Flushes (true) the Rx FIFO; Otherwise, does not flush (false) the Rx FIFO - */ -static inline void DSPI_FlushFifo(SPI_Type *base, bool flushTxFifo, bool flushRxFifo) -{ - base->MCR = (base->MCR & (~(SPI_MCR_CLR_TXF_MASK | SPI_MCR_CLR_RXF_MASK))) | SPI_MCR_CLR_TXF(flushTxFifo) | - SPI_MCR_CLR_RXF(flushRxFifo); -} - -/*! - * @brief Configures the DSPI peripheral chip select polarity simultaneously. - * For example, PCS0 and PCS1 are set to active low and other PCS is set to active high. Note that the number of - * PCSs is specific to the device. - * @code - * DSPI_SetAllPcsPolarity(base, kDSPI_Pcs0ActiveLow | kDSPI_Pcs1ActiveLow); - @endcode - * @param base DSPI peripheral address. - * @param mask The PCS polarity mask; use the enum _dspi_pcs_polarity. - */ -static inline void DSPI_SetAllPcsPolarity(SPI_Type *base, uint32_t mask) -{ - base->MCR = (base->MCR & ~SPI_MCR_PCSIS_MASK) | SPI_MCR_PCSIS(mask); -} - -/*! - * @brief Sets the DSPI baud rate in bits per second. - * - * This function takes in the desired baudRate_Bps (baud rate) and calculates the nearest possible baud rate without - * exceeding the desired baud rate, and returns the calculated baud rate in bits-per-second. It requires that the - * caller also provide the frequency of the module source clock (in Hertz). - * - * @param base DSPI peripheral address. - * @param whichCtar The desired Clock and Transfer Attributes Register (CTAR) of the type dspi_ctar_selection_t - * @param baudRate_Bps The desired baud rate in bits per second - * @param srcClock_Hz Module source input clock in Hertz - * @return The actual calculated baud rate - */ -uint32_t DSPI_MasterSetBaudRate(SPI_Type *base, - dspi_ctar_selection_t whichCtar, - uint32_t baudRate_Bps, - uint32_t srcClock_Hz); - -/*! - * @brief Manually configures the delay prescaler and scaler for a particular CTAR. - * - * This function configures the PCS to SCK delay pre-scalar (PcsSCK) and scalar (CSSCK), after SCK delay pre-scalar - * (PASC) and scalar (ASC), and the delay after transfer pre-scalar (PDT) and scalar (DT). - * - * These delay names are available in the type dspi_delay_type_t. - * - * The user passes the delay to the configuration along with the prescaler and scaler value. - * This allows the user to directly set the prescaler/scaler values if pre-calculated or - * to manually increment either value. - * - * @param base DSPI peripheral address. - * @param whichCtar The desired Clock and Transfer Attributes Register (CTAR) of type dspi_ctar_selection_t. - * @param prescaler The prescaler delay value (can be an integer 0, 1, 2, or 3). - * @param scaler The scaler delay value (can be any integer between 0 to 15). - * @param whichDelay The desired delay to configure; must be of type dspi_delay_type_t - */ -void DSPI_MasterSetDelayScaler( - SPI_Type *base, dspi_ctar_selection_t whichCtar, uint32_t prescaler, uint32_t scaler, dspi_delay_type_t whichDelay); - -/*! - * @brief Calculates the delay prescaler and scaler based on the desired delay input in nanoseconds. - * - * This function calculates the values for the following. - * PCS to SCK delay pre-scalar (PCSSCK) and scalar (CSSCK), or - * After SCK delay pre-scalar (PASC) and scalar (ASC), or - * Delay after transfer pre-scalar (PDT) and scalar (DT). - * - * These delay names are available in the type dspi_delay_type_t. - * - * The user passes which delay to configure along with the desired delay value in nanoseconds. The function - * calculates the values needed for the prescaler and scaler. Note that returning the calculated delay as an exact - * delay match may not be possible. In this case, the closest match is calculated without going below the desired - * delay value input. - * It is possible to input a very large delay value that exceeds the capability of the part, in which case the maximum - * supported delay is returned. The higher-level peripheral driver alerts the user of an out of range delay - * input. - * - * @param base DSPI peripheral address. - * @param whichCtar The desired Clock and Transfer Attributes Register (CTAR) of type dspi_ctar_selection_t. - * @param whichDelay The desired delay to configure, must be of type dspi_delay_type_t - * @param srcClock_Hz Module source input clock in Hertz - * @param delayTimeInNanoSec The desired delay value in nanoseconds. - * @return The actual calculated delay value. - */ -uint32_t DSPI_MasterSetDelayTimes(SPI_Type *base, - dspi_ctar_selection_t whichCtar, - dspi_delay_type_t whichDelay, - uint32_t srcClock_Hz, - uint32_t delayTimeInNanoSec); - -/*! - * @brief Writes data into the data buffer for master mode. - * - * In master mode, the 16-bit data is appended to the 16-bit command info. The command portion - * provides characteristics of the data, such as the optional continuous chip select - * operation between transfers, the desired Clock and Transfer Attributes register to use for the - * associated SPI frame, the desired PCS signal to use for the data transfer, whether the current - * transfer is the last in the queue, and whether to clear the transfer count (normally needed when - * sending the first frame of a data packet). This is an example. - * @code - * dspi_command_data_config_t commandConfig; - * commandConfig.isPcsContinuous = true; - * commandConfig.whichCtar = kDSPICtar0; - * commandConfig.whichPcs = kDSPIPcs0; - * commandConfig.clearTransferCount = false; - * commandConfig.isEndOfQueue = false; - * DSPI_MasterWriteData(base, &commandConfig, dataWord); - @endcode - * - * @param base DSPI peripheral address. - * @param command Pointer to the command structure. - * @param data The data word to be sent. - */ -static inline void DSPI_MasterWriteData(SPI_Type *base, dspi_command_data_config_t *command, uint16_t data) -{ - base->PUSHR = SPI_PUSHR_CONT(command->isPcsContinuous) | SPI_PUSHR_CTAS(command->whichCtar) | - SPI_PUSHR_PCS(command->whichPcs) | SPI_PUSHR_EOQ(command->isEndOfQueue) | - SPI_PUSHR_CTCNT(command->clearTransferCount) | SPI_PUSHR_TXDATA(data); -} - -/*! - * @brief Sets the dspi_command_data_config_t structure to default values. - * - * The purpose of this API is to get the configuration structure initialized for use in the DSPI_MasterWrite_xx(). - * Users may use the initialized structure unchanged in the DSPI_MasterWrite_xx() or modify the structure - * before calling the DSPI_MasterWrite_xx(). - * This is an example. - * @code - * dspi_command_data_config_t command; - * DSPI_GetDefaultDataCommandConfig(&command); - * @endcode - * @param command Pointer to the dspi_command_data_config_t structure. - */ -void DSPI_GetDefaultDataCommandConfig(dspi_command_data_config_t *command); - -/*! - * @brief Writes data into the data buffer master mode and waits till complete to return. - * - * In master mode, the 16-bit data is appended to the 16-bit command info. The command portion - * provides characteristics of the data, such as the optional continuous chip select - * operation between transfers, the desired Clock and Transfer Attributes register to use for the - * associated SPI frame, the desired PCS signal to use for the data transfer, whether the current - * transfer is the last in the queue, and whether to clear the transfer count (normally needed when - * sending the first frame of a data packet). This is an example. - * @code - * dspi_command_config_t commandConfig; - * commandConfig.isPcsContinuous = true; - * commandConfig.whichCtar = kDSPICtar0; - * commandConfig.whichPcs = kDSPIPcs1; - * commandConfig.clearTransferCount = false; - * commandConfig.isEndOfQueue = false; - * DSPI_MasterWriteDataBlocking(base, &commandConfig, dataWord); - * @endcode - * - * Note that this function does not return until after the transmit is complete. Also note that the DSPI must be - * enabled and running to transmit data (MCR[MDIS] & [HALT] = 0). Because the SPI is a synchronous protocol, - * the received data is available when the transmit completes. - * - * @param base DSPI peripheral address. - * @param command Pointer to the command structure. - * @param data The data word to be sent. - */ -void DSPI_MasterWriteDataBlocking(SPI_Type *base, dspi_command_data_config_t *command, uint16_t data); - -/*! - * @brief Returns the DSPI command word formatted to the PUSHR data register bit field. - * - * This function allows the caller to pass in the data command structure and returns the command word formatted - * according to the DSPI PUSHR register bit field placement. The user can then "OR" the returned command word with the - * desired data to send and use the function DSPI_HAL_WriteCommandDataMastermode or - * DSPI_HAL_WriteCommandDataMastermodeBlocking to write the entire 32-bit command data word to the PUSHR. This helps - * improve performance in cases where the command structure is constant. For example, the user calls this function - * before starting a transfer to generate the command word. When they are ready to transmit the data, they OR - * this formatted command word with the desired data to transmit. This process increases transmit performance when - * compared to calling send functions, such as DSPI_HAL_WriteDataMastermode, which format the command word each time a - * data word is to be sent. - * - * @param command Pointer to the command structure. - * @return The command word formatted to the PUSHR data register bit field. - */ -static inline uint32_t DSPI_MasterGetFormattedCommand(dspi_command_data_config_t *command) -{ - /* Format the 16-bit command word according to the PUSHR data register bit field*/ - return (uint32_t)(SPI_PUSHR_CONT(command->isPcsContinuous) | SPI_PUSHR_CTAS(command->whichCtar) | - SPI_PUSHR_PCS(command->whichPcs) | SPI_PUSHR_EOQ(command->isEndOfQueue) | - SPI_PUSHR_CTCNT(command->clearTransferCount)); -} - -/*! - * @brief Writes a 32-bit data word (16-bit command appended with 16-bit data) into the data - * buffer master mode and waits till complete to return. - * - * In this function, the user must append the 16-bit data to the 16-bit command information and then provide the total 32-bit word - * as the data to send. - * The command portion provides characteristics of the data, such as the optional continuous chip select operation - * between transfers, the desired Clock and Transfer Attributes register to use for the associated SPI frame, the desired PCS - * signal to use for the data transfer, whether the current transfer is the last in the queue, and whether to clear the - * transfer count (normally needed when sending the first frame of a data packet). The user is responsible for - * appending this command with the data to send. This is an example: - * @code - * dataWord = <16-bit command> | <16-bit data>; - * DSPI_MasterWriteCommandDataBlocking(base, dataWord); - * @endcode - * - * Note that this function does not return until after the transmit is complete. Also note that the DSPI must be - * enabled and running to transmit data (MCR[MDIS] & [HALT] = 0). - * Because the SPI is a synchronous protocol, the received data is available when the transmit completes. - * - * For a blocking polling transfer, see methods below. - * Option 1: -* uint32_t command_to_send = DSPI_MasterGetFormattedCommand(&command); -* uint32_t data0 = command_to_send | data_need_to_send_0; -* uint32_t data1 = command_to_send | data_need_to_send_1; -* uint32_t data2 = command_to_send | data_need_to_send_2; -* -* DSPI_MasterWriteCommandDataBlocking(base,data0); -* DSPI_MasterWriteCommandDataBlocking(base,data1); -* DSPI_MasterWriteCommandDataBlocking(base,data2); -* -* Option 2: -* DSPI_MasterWriteDataBlocking(base,&command,data_need_to_send_0); -* DSPI_MasterWriteDataBlocking(base,&command,data_need_to_send_1); -* DSPI_MasterWriteDataBlocking(base,&command,data_need_to_send_2); -* - * @param base DSPI peripheral address. - * @param data The data word (command and data combined) to be sent. - */ -void DSPI_MasterWriteCommandDataBlocking(SPI_Type *base, uint32_t data); - -/*! - * @brief Writes data into the data buffer in slave mode. - * - * In slave mode, up to 16-bit words may be written. - * - * @param base DSPI peripheral address. - * @param data The data to send. - */ -static inline void DSPI_SlaveWriteData(SPI_Type *base, uint32_t data) -{ - base->PUSHR_SLAVE = data; -} - -/*! - * @brief Writes data into the data buffer in slave mode, waits till data was transmitted, and returns. - * - * In slave mode, up to 16-bit words may be written. The function first clears the transmit complete flag, writes data - * into data register, and finally waits until the data is transmitted. - * - * @param base DSPI peripheral address. - * @param data The data to send. - */ -void DSPI_SlaveWriteDataBlocking(SPI_Type *base, uint32_t data); - -/*! - * @brief Reads data from the data buffer. - * - * @param base DSPI peripheral address. - * @return The data from the read data buffer. - */ -static inline uint32_t DSPI_ReadData(SPI_Type *base) -{ - return (base->POPR); -} - -/*! - *@} -*/ - -/*! - * @name Transactional - * @{ - */ -/*Transactional APIs*/ - -/*! - * @brief Initializes the DSPI master handle. - * - * This function initializes the DSPI handle, which can be used for other DSPI transactional APIs. Usually, for a - * specified DSPI instance, call this API once to get the initialized handle. - * - * @param base DSPI peripheral base address. - * @param handle DSPI handle pointer to dspi_master_handle_t. - * @param callback DSPI callback. - * @param userData Callback function parameter. - */ -void DSPI_MasterTransferCreateHandle(SPI_Type *base, - dspi_master_handle_t *handle, - dspi_master_transfer_callback_t callback, - void *userData); - -/*! - * @brief DSPI master transfer data using polling. - * - * This function transfers data using polling. This is a blocking function, which does not return until all transfers - * have been completed. - * - * @param base DSPI peripheral base address. - * @param transfer Pointer to the dspi_transfer_t structure. - * @return status of status_t. - */ -status_t DSPI_MasterTransferBlocking(SPI_Type *base, dspi_transfer_t *transfer); - -/*! - * @brief DSPI master transfer data using interrupts. - * - * This function transfers data using interrupts. This is a non-blocking function, which returns right away. When all - * data is transferred, the callback function is called. - - * @param base DSPI peripheral base address. - * @param handle Pointer to the dspi_master_handle_t structure which stores the transfer state. - * @param transfer Pointer to the dspi_transfer_t structure. - * @return status of status_t. - */ -status_t DSPI_MasterTransferNonBlocking(SPI_Type *base, dspi_master_handle_t *handle, dspi_transfer_t *transfer); - -/*! - * @brief Gets the master transfer count. - * - * This function gets the master transfer count. - * - * @param base DSPI peripheral base address. - * @param handle Pointer to the dspi_master_handle_t structure which stores the transfer state. - * @param count The number of bytes transferred by using the non-blocking transaction. - * @return status of status_t. - */ -status_t DSPI_MasterTransferGetCount(SPI_Type *base, dspi_master_handle_t *handle, size_t *count); - -/*! - * @brief DSPI master aborts a transfer using an interrupt. - * - * This function aborts a transfer using an interrupt. - * - * @param base DSPI peripheral base address. - * @param handle Pointer to the dspi_master_handle_t structure which stores the transfer state. - */ -void DSPI_MasterTransferAbort(SPI_Type *base, dspi_master_handle_t *handle); - -/*! - * @brief DSPI Master IRQ handler function. - * - * This function processes the DSPI transmit and receive IRQ. - - * @param base DSPI peripheral base address. - * @param handle Pointer to the dspi_master_handle_t structure which stores the transfer state. - */ -void DSPI_MasterTransferHandleIRQ(SPI_Type *base, dspi_master_handle_t *handle); - -/*! - * @brief Initializes the DSPI slave handle. - * - * This function initializes the DSPI handle, which can be used for other DSPI transactional APIs. Usually, for a - * specified DSPI instance, call this API once to get the initialized handle. - * - * @param handle DSPI handle pointer to the dspi_slave_handle_t. - * @param base DSPI peripheral base address. - * @param callback DSPI callback. - * @param userData Callback function parameter. - */ -void DSPI_SlaveTransferCreateHandle(SPI_Type *base, - dspi_slave_handle_t *handle, - dspi_slave_transfer_callback_t callback, - void *userData); - -/*! - * @brief DSPI slave transfers data using an interrupt. - * - * This function transfers data using an interrupt. This is a non-blocking function, which returns right away. When all - * data is transferred, the callback function is called. - * - * @param base DSPI peripheral base address. - * @param handle Pointer to the dspi_slave_handle_t structure which stores the transfer state. - * @param transfer Pointer to the dspi_transfer_t structure. - * @return status of status_t. - */ -status_t DSPI_SlaveTransferNonBlocking(SPI_Type *base, dspi_slave_handle_t *handle, dspi_transfer_t *transfer); - -/*! - * @brief Gets the slave transfer count. - * - * This function gets the slave transfer count. - * - * @param base DSPI peripheral base address. - * @param handle Pointer to the dspi_master_handle_t structure which stores the transfer state. - * @param count The number of bytes transferred by using the non-blocking transaction. - * @return status of status_t. - */ -status_t DSPI_SlaveTransferGetCount(SPI_Type *base, dspi_slave_handle_t *handle, size_t *count); - -/*! - * @brief DSPI slave aborts a transfer using an interrupt. - * - * This function aborts a transfer using an interrupt. - * - * @param base DSPI peripheral base address. - * @param handle Pointer to the dspi_slave_handle_t structure which stores the transfer state. - */ -void DSPI_SlaveTransferAbort(SPI_Type *base, dspi_slave_handle_t *handle); - -/*! - * @brief DSPI Master IRQ handler function. - * - * This function processes the DSPI transmit and receive IRQ. - * - * @param base DSPI peripheral base address. - * @param handle Pointer to the dspi_slave_handle_t structure which stores the transfer state. - */ -void DSPI_SlaveTransferHandleIRQ(SPI_Type *base, dspi_slave_handle_t *handle); - -/*! - *@} -*/ - -#if defined(__cplusplus) -} -#endif /*_cplusplus*/ - /*! - *@} - */ - -#endif /*_FSL_DSPI_H_*/ diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_dspi_edma.c b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_dspi_edma.c deleted file mode 100644 index ef0d15174f5..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_dspi_edma.c +++ /dev/null @@ -1,1248 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "fsl_dspi_edma.h" - -/*********************************************************************************************************************** -* Definitons -***********************************************************************************************************************/ - -/*! -* @brief Structure definition for dspi_master_edma_private_handle_t. The structure is private. -*/ -typedef struct _dspi_master_edma_private_handle -{ - SPI_Type *base; /*!< DSPI peripheral base address. */ - dspi_master_edma_handle_t *handle; /*!< dspi_master_edma_handle_t handle */ -} dspi_master_edma_private_handle_t; - -/*! -* @brief Structure definition for dspi_slave_edma_private_handle_t. The structure is private. -*/ -typedef struct _dspi_slave_edma_private_handle -{ - SPI_Type *base; /*!< DSPI peripheral base address. */ - dspi_slave_edma_handle_t *handle; /*!< dspi_master_edma_handle_t handle */ -} dspi_slave_edma_private_handle_t; - -/*********************************************************************************************************************** -* Prototypes -***********************************************************************************************************************/ -/*! -* @brief EDMA_DspiMasterCallback after the DSPI master transfer completed by using EDMA. -* This is not a public API. -*/ -static void EDMA_DspiMasterCallback(edma_handle_t *edmaHandle, - void *g_dspiEdmaPrivateHandle, - bool transferDone, - uint32_t tcds); - -/*! -* @brief EDMA_DspiSlaveCallback after the DSPI slave transfer completed by using EDMA. -* This is not a public API. -*/ -static void EDMA_DspiSlaveCallback(edma_handle_t *edmaHandle, - void *g_dspiEdmaPrivateHandle, - bool transferDone, - uint32_t tcds); -/*! -* @brief Get instance number for DSPI module. -* -* This is not a public API and it's extern from fsl_dspi.c. -* -* @param base DSPI peripheral base address -*/ -extern uint32_t DSPI_GetInstance(SPI_Type *base); - -/*********************************************************************************************************************** -* Variables -***********************************************************************************************************************/ - -/*! @brief Pointers to dspi edma handles for each instance. */ -static dspi_master_edma_private_handle_t s_dspiMasterEdmaPrivateHandle[FSL_FEATURE_SOC_DSPI_COUNT]; -static dspi_slave_edma_private_handle_t s_dspiSlaveEdmaPrivateHandle[FSL_FEATURE_SOC_DSPI_COUNT]; - -/*********************************************************************************************************************** -* Code -***********************************************************************************************************************/ - -void DSPI_MasterTransferCreateHandleEDMA(SPI_Type *base, - dspi_master_edma_handle_t *handle, - dspi_master_edma_transfer_callback_t callback, - void *userData, - edma_handle_t *edmaRxRegToRxDataHandle, - edma_handle_t *edmaTxDataToIntermediaryHandle, - edma_handle_t *edmaIntermediaryToTxRegHandle) -{ - assert(handle); - assert(edmaRxRegToRxDataHandle); - assert(edmaTxDataToIntermediaryHandle); - assert(edmaIntermediaryToTxRegHandle); - - /* Zero the handle. */ - memset(handle, 0, sizeof(*handle)); - - uint32_t instance = DSPI_GetInstance(base); - - s_dspiMasterEdmaPrivateHandle[instance].base = base; - s_dspiMasterEdmaPrivateHandle[instance].handle = handle; - - handle->callback = callback; - handle->userData = userData; - - handle->edmaRxRegToRxDataHandle = edmaRxRegToRxDataHandle; - handle->edmaTxDataToIntermediaryHandle = edmaTxDataToIntermediaryHandle; - handle->edmaIntermediaryToTxRegHandle = edmaIntermediaryToTxRegHandle; -} - -status_t DSPI_MasterTransferEDMA(SPI_Type *base, dspi_master_edma_handle_t *handle, dspi_transfer_t *transfer) -{ - assert(handle); - assert(transfer); - - /* If the transfer count is zero, then return immediately.*/ - if (transfer->dataSize == 0) - { - return kStatus_InvalidArgument; - } - - /* If both send buffer and receive buffer is null */ - if ((!(transfer->txData)) && (!(transfer->rxData))) - { - return kStatus_InvalidArgument; - } - - /* Check that we're not busy.*/ - if (handle->state == kDSPI_Busy) - { - return kStatus_DSPI_Busy; - } - - handle->state = kDSPI_Busy; - - uint32_t instance = DSPI_GetInstance(base); - uint16_t wordToSend = 0; - uint8_t dummyData = DSPI_DUMMY_DATA; - uint8_t dataAlreadyFed = 0; - uint8_t dataFedMax = 2; - - uint32_t rxAddr = DSPI_GetRxRegisterAddress(base); - uint32_t txAddr = DSPI_MasterGetTxRegisterAddress(base); - - edma_tcd_t *softwareTCD = (edma_tcd_t *)((uint32_t)(&handle->dspiSoftwareTCD[1]) & (~0x1FU)); - - edma_transfer_config_t transferConfigA; - edma_transfer_config_t transferConfigB; - edma_transfer_config_t transferConfigC; - - handle->txBuffIfNull = ((uint32_t)DSPI_DUMMY_DATA << 8) | DSPI_DUMMY_DATA; - - dspi_command_data_config_t commandStruct; - DSPI_StopTransfer(base); - DSPI_FlushFifo(base, true, true); - DSPI_ClearStatusFlags(base, kDSPI_AllStatusFlag); - - commandStruct.whichPcs = - (dspi_which_pcs_t)(1U << ((transfer->configFlags & DSPI_MASTER_PCS_MASK) >> DSPI_MASTER_PCS_SHIFT)); - commandStruct.isEndOfQueue = false; - commandStruct.clearTransferCount = false; - commandStruct.whichCtar = - (dspi_ctar_selection_t)((transfer->configFlags & DSPI_MASTER_CTAR_MASK) >> DSPI_MASTER_CTAR_SHIFT); - commandStruct.isPcsContinuous = (bool)(transfer->configFlags & kDSPI_MasterPcsContinuous); - handle->command = DSPI_MasterGetFormattedCommand(&(commandStruct)); - - commandStruct.isEndOfQueue = true; - commandStruct.isPcsContinuous = (bool)(transfer->configFlags & kDSPI_MasterActiveAfterTransfer); - handle->lastCommand = DSPI_MasterGetFormattedCommand(&(commandStruct)); - - handle->bitsPerFrame = ((base->CTAR[commandStruct.whichCtar] & SPI_CTAR_FMSZ_MASK) >> SPI_CTAR_FMSZ_SHIFT) + 1; - - if ((base->MCR & SPI_MCR_DIS_RXF_MASK) || (base->MCR & SPI_MCR_DIS_TXF_MASK)) - { - handle->fifoSize = 1; - } - else - { - handle->fifoSize = FSL_FEATURE_DSPI_FIFO_SIZEn(base); - } - handle->txData = transfer->txData; - handle->rxData = transfer->rxData; - handle->remainingSendByteCount = transfer->dataSize; - handle->remainingReceiveByteCount = transfer->dataSize; - handle->totalByteCount = transfer->dataSize; - - /* If using a shared RX/TX DMA request, then this limits the amount of data we can transfer - * due to the linked channel. The max bytes is 511 if 8-bit/frame or 1022 if 16-bit/frame - */ - uint32_t limited_size = 0; - if (1 == FSL_FEATURE_DSPI_HAS_SEPARATE_DMA_RX_TX_REQn(base)) - { - limited_size = 32767u; - } - else - { - limited_size = 511u; - } - - if (handle->bitsPerFrame > 8) - { - if (transfer->dataSize > (limited_size << 1u)) - { - handle->state = kDSPI_Idle; - return kStatus_DSPI_OutOfRange; - } - } - else - { - if (transfer->dataSize > limited_size) - { - handle->state = kDSPI_Idle; - return kStatus_DSPI_OutOfRange; - } - } - - /*The data size should be even if the bitsPerFrame is greater than 8 (that is 2 bytes per frame in dspi) */ - if ((handle->bitsPerFrame > 8) && (transfer->dataSize & 0x1)) - { - handle->state = kDSPI_Idle; - return kStatus_InvalidArgument; - } - - DSPI_DisableDMA(base, kDSPI_RxDmaEnable | kDSPI_TxDmaEnable); - - EDMA_SetCallback(handle->edmaRxRegToRxDataHandle, EDMA_DspiMasterCallback, - &s_dspiMasterEdmaPrivateHandle[instance]); - - /* - (1)For DSPI instances with shared RX/TX DMA requests: Rx DMA request -> channel_A -> channel_B-> channel_C. - channel_A minor link to channel_B , channel_B minor link to channel_C. - - Already pushed 1 or 2 data in SPI_PUSHR , then start the DMA tansfer. - channel_A:SPI_POPR to rxData, - channel_B:next txData to handle->command (low 16 bits), - channel_C:handle->command (32 bits) to SPI_PUSHR, and use the scatter/gather to transfer the last data - (handle->lastCommand to SPI_PUSHR). - - (2)For DSPI instances with separate RX and TX DMA requests: - Rx DMA request -> channel_A - Tx DMA request -> channel_C -> channel_B . - channel_C major link to channel_B. - So need prepare the first data in "intermediary" before the DMA - transfer and then channel_B is used to prepare the next data to "intermediary" - - channel_A:SPI_POPR to rxData, - channel_C: handle->command (32 bits) to SPI_PUSHR, - channel_B: next txData to handle->command (low 16 bits), and use the scatter/gather to prepare the last data - (handle->lastCommand to handle->Command). - */ - - /*If dspi has separate dma request , prepare the first data in "intermediary" . - else (dspi has shared dma request) , send first 2 data if there is fifo or send first 1 data if there is no fifo*/ - if (1 == FSL_FEATURE_DSPI_HAS_SEPARATE_DMA_RX_TX_REQn(base)) - { - /* For DSPI instances with separate RX/TX DMA requests, we'll use the TX DMA request to - * trigger the TX DMA channel and RX DMA request to trigger the RX DMA channel - */ - - /*Prepare the firt data*/ - if (handle->bitsPerFrame > 8) - { - /* If it's the last word */ - if (handle->remainingSendByteCount <= 2) - { - if (handle->txData) - { - wordToSend = *(handle->txData); - ++handle->txData; /* increment to next data byte */ - wordToSend |= (unsigned)(*(handle->txData)) << 8U; - } - else - { - wordToSend = ((uint32_t)dummyData << 8) | dummyData; - } - handle->lastCommand = (handle->lastCommand & 0xffff0000U) | wordToSend; - handle->command = handle->lastCommand; - } - else /* For all words except the last word , frame > 8bits */ - { - if (handle->txData) - { - wordToSend = *(handle->txData); - ++handle->txData; /* increment to next data byte */ - wordToSend |= (unsigned)(*(handle->txData)) << 8U; - ++handle->txData; /* increment to next data byte */ - } - else - { - wordToSend = ((uint32_t)dummyData << 8) | dummyData; - } - handle->command = (handle->command & 0xffff0000U) | wordToSend; - } - } - else /* Optimized for bits/frame less than or equal to one byte. */ - { - if (handle->txData) - { - wordToSend = *(handle->txData); - ++handle->txData; /* increment to next data word*/ - } - else - { - wordToSend = dummyData; - } - - if (handle->remainingSendByteCount == 1) - { - handle->lastCommand = (handle->lastCommand & 0xffff0000U) | wordToSend; - handle->command = handle->lastCommand; - } - else - { - handle->command = (handle->command & 0xffff0000U) | wordToSend; - } - } - } - - else /*dspi has shared dma request*/ - - { - /* For DSPI instances with shared RX/TX DMA requests, we'll use the RX DMA request to - * trigger ongoing transfers and will link to the TX DMA channel from the RX DMA channel. - */ - - /* If bits/frame is greater than one byte */ - if (handle->bitsPerFrame > 8) - { - while (DSPI_GetStatusFlags(base) & kDSPI_TxFifoFillRequestFlag) - { - if (handle->remainingSendByteCount <= 2) - { - if (handle->txData) - { - wordToSend = *(handle->txData); - ++handle->txData; - wordToSend |= (unsigned)(*(handle->txData)) << 8U; - } - else - { - wordToSend = ((uint32_t)dummyData << 8) | dummyData; - } - handle->remainingSendByteCount = 0; - base->PUSHR = (handle->lastCommand & 0xffff0000U) | wordToSend; - } - /* For all words except the last word */ - else - { - if (handle->txData) - { - wordToSend = *(handle->txData); - ++handle->txData; - wordToSend |= (unsigned)(*(handle->txData)) << 8U; - ++handle->txData; - } - else - { - wordToSend = ((uint32_t)dummyData << 8) | dummyData; - } - handle->remainingSendByteCount -= 2; - base->PUSHR = (handle->command & 0xffff0000U) | wordToSend; - } - - /* Try to clear the TFFF; if the TX FIFO is full this will clear */ - DSPI_ClearStatusFlags(base, kDSPI_TxFifoFillRequestFlag); - - dataAlreadyFed += 2; - - /* exit loop if send count is zero, else update local variables for next loop */ - if ((handle->remainingSendByteCount == 0) || (dataAlreadyFed == (dataFedMax * 2))) - { - break; - } - } /* End of TX FIFO fill while loop */ - } - else /* Optimized for bits/frame less than or equal to one byte. */ - { - while (DSPI_GetStatusFlags(base) & kDSPI_TxFifoFillRequestFlag) - { - if (handle->txData) - { - wordToSend = *(handle->txData); - ++handle->txData; - } - else - { - wordToSend = dummyData; - } - - if (handle->remainingSendByteCount == 1) - { - base->PUSHR = (handle->lastCommand & 0xffff0000U) | wordToSend; - } - else - { - base->PUSHR = (handle->command & 0xffff0000U) | wordToSend; - } - - /* Try to clear the TFFF; if the TX FIFO is full this will clear */ - DSPI_ClearStatusFlags(base, kDSPI_TxFifoFillRequestFlag); - - --handle->remainingSendByteCount; - - dataAlreadyFed++; - - /* exit loop if send count is zero, else update local variables for next loop */ - if ((handle->remainingSendByteCount == 0) || (dataAlreadyFed == dataFedMax)) - { - break; - } - } /* End of TX FIFO fill while loop */ - } - } - - /***channel_A *** used for carry the data from Rx_Data_Register(POPR) to User_Receive_Buffer(rxData)*/ - EDMA_ResetChannel(handle->edmaRxRegToRxDataHandle->base, handle->edmaRxRegToRxDataHandle->channel); - - transferConfigA.srcAddr = (uint32_t)rxAddr; - transferConfigA.srcOffset = 0; - - if (handle->rxData) - { - transferConfigA.destAddr = (uint32_t) & (handle->rxData[0]); - transferConfigA.destOffset = 1; - } - else - { - transferConfigA.destAddr = (uint32_t) & (handle->rxBuffIfNull); - transferConfigA.destOffset = 0; - } - - transferConfigA.destTransferSize = kEDMA_TransferSize1Bytes; - - if (handle->bitsPerFrame <= 8) - { - transferConfigA.srcTransferSize = kEDMA_TransferSize1Bytes; - transferConfigA.minorLoopBytes = 1; - transferConfigA.majorLoopCounts = handle->remainingReceiveByteCount; - } - else - { - transferConfigA.srcTransferSize = kEDMA_TransferSize2Bytes; - transferConfigA.minorLoopBytes = 2; - transferConfigA.majorLoopCounts = handle->remainingReceiveByteCount / 2; - } - - /* Store the initially configured eDMA minor byte transfer count into the DSPI handle */ - handle->nbytes = transferConfigA.minorLoopBytes; - - EDMA_SetTransferConfig(handle->edmaRxRegToRxDataHandle->base, handle->edmaRxRegToRxDataHandle->channel, - &transferConfigA, NULL); - EDMA_EnableChannelInterrupts(handle->edmaRxRegToRxDataHandle->base, handle->edmaRxRegToRxDataHandle->channel, - kEDMA_MajorInterruptEnable); - - /***channel_B *** used for carry the data from User_Send_Buffer to "intermediary" because the SPIx_PUSHR should - write the 32bits at once time . Then use channel_C to carry the "intermediary" to SPIx_PUSHR. Note that the - SPIx_PUSHR upper 16 bits are the "command" and the low 16bits are data */ - - EDMA_ResetChannel(handle->edmaTxDataToIntermediaryHandle->base, handle->edmaTxDataToIntermediaryHandle->channel); - - /*Calculate the last data : handle->lastCommand*/ - if (((handle->remainingSendByteCount > 0) && (1 != FSL_FEATURE_DSPI_HAS_SEPARATE_DMA_RX_TX_REQn(base))) || - ((((handle->remainingSendByteCount > 1) && (handle->bitsPerFrame <= 8)) || - ((handle->remainingSendByteCount > 2) && (handle->bitsPerFrame > 8))) && - (1 == FSL_FEATURE_DSPI_HAS_SEPARATE_DMA_RX_TX_REQn(base)))) - { - if (handle->txData) - { - uint32_t bufferIndex = 0; - - if (1 == FSL_FEATURE_DSPI_HAS_SEPARATE_DMA_RX_TX_REQn(base)) - { - if (handle->bitsPerFrame <= 8) - { - bufferIndex = handle->remainingSendByteCount - 1; - } - else - { - bufferIndex = handle->remainingSendByteCount - 2; - } - } - else - { - bufferIndex = handle->remainingSendByteCount; - } - - if (handle->bitsPerFrame <= 8) - { - handle->lastCommand = (handle->lastCommand & 0xffff0000U) | handle->txData[bufferIndex - 1]; - } - else - { - handle->lastCommand = (handle->lastCommand & 0xffff0000U) | - ((uint32_t)handle->txData[bufferIndex - 1] << 8) | - handle->txData[bufferIndex - 2]; - } - } - else - { - if (handle->bitsPerFrame <= 8) - { - wordToSend = dummyData; - } - else - { - wordToSend = ((uint32_t)dummyData << 8) | dummyData; - } - handle->lastCommand = (handle->lastCommand & 0xffff0000U) | wordToSend; - } - } - - /*For DSPI instances with separate RX and TX DMA requests: use the scatter/gather to prepare the last data - * (handle->lastCommand) to handle->Command*/ - if (1 == FSL_FEATURE_DSPI_HAS_SEPARATE_DMA_RX_TX_REQn(base)) - { - transferConfigB.srcAddr = (uint32_t) & (handle->lastCommand); - transferConfigB.destAddr = (uint32_t) & (handle->command); - transferConfigB.srcTransferSize = kEDMA_TransferSize4Bytes; - transferConfigB.destTransferSize = kEDMA_TransferSize4Bytes; - transferConfigB.srcOffset = 0; - transferConfigB.destOffset = 0; - transferConfigB.minorLoopBytes = 4; - transferConfigB.majorLoopCounts = 1; - - EDMA_TcdReset(softwareTCD); - EDMA_TcdSetTransferConfig(softwareTCD, &transferConfigB, NULL); - } - - /*User_Send_Buffer(txData) to intermediary(handle->command)*/ - if (((((handle->remainingSendByteCount > 2) && (handle->bitsPerFrame <= 8)) || - ((handle->remainingSendByteCount > 4) && (handle->bitsPerFrame > 8))) && - (1 == FSL_FEATURE_DSPI_HAS_SEPARATE_DMA_RX_TX_REQn(base))) || - (1 != FSL_FEATURE_DSPI_HAS_SEPARATE_DMA_RX_TX_REQn(base))) - { - if (handle->txData) - { - transferConfigB.srcAddr = (uint32_t)(handle->txData); - transferConfigB.srcOffset = 1; - } - else - { - transferConfigB.srcAddr = (uint32_t)(&handle->txBuffIfNull); - transferConfigB.srcOffset = 0; - } - - transferConfigB.destAddr = (uint32_t)(&handle->command); - transferConfigB.destOffset = 0; - - transferConfigB.srcTransferSize = kEDMA_TransferSize1Bytes; - - if (handle->bitsPerFrame <= 8) - { - transferConfigB.destTransferSize = kEDMA_TransferSize1Bytes; - transferConfigB.minorLoopBytes = 1; - - if (1 == FSL_FEATURE_DSPI_HAS_SEPARATE_DMA_RX_TX_REQn(base)) - { - transferConfigB.majorLoopCounts = handle->remainingSendByteCount - 2; - } - else - { - /*Only enable channel_B minorlink to channel_C , so need to add one count due to the last time is - majorlink , the majorlink would not trigger the channel_C*/ - transferConfigB.majorLoopCounts = handle->remainingSendByteCount + 1; - } - } - else - { - transferConfigB.destTransferSize = kEDMA_TransferSize2Bytes; - transferConfigB.minorLoopBytes = 2; - if (1 == FSL_FEATURE_DSPI_HAS_SEPARATE_DMA_RX_TX_REQn(base)) - { - transferConfigB.majorLoopCounts = handle->remainingSendByteCount / 2 - 2; - } - else - { - /*Only enable channel_B minorlink to channel_C , so need to add one count due to the last time is - * majorlink*/ - transferConfigB.majorLoopCounts = handle->remainingSendByteCount / 2 + 1; - } - } - - if (1 == FSL_FEATURE_DSPI_HAS_SEPARATE_DMA_RX_TX_REQn(base)) - { - EDMA_SetTransferConfig(handle->edmaTxDataToIntermediaryHandle->base, - handle->edmaTxDataToIntermediaryHandle->channel, &transferConfigB, softwareTCD); - EDMA_EnableAutoStopRequest(handle->edmaIntermediaryToTxRegHandle->base, - handle->edmaIntermediaryToTxRegHandle->channel, false); - } - else - { - EDMA_SetTransferConfig(handle->edmaTxDataToIntermediaryHandle->base, - handle->edmaTxDataToIntermediaryHandle->channel, &transferConfigB, NULL); - } - } - else - { - EDMA_SetTransferConfig(handle->edmaTxDataToIntermediaryHandle->base, - handle->edmaTxDataToIntermediaryHandle->channel, &transferConfigB, NULL); - } - - /***channel_C ***carry the "intermediary" to SPIx_PUSHR. used the edma Scatter Gather function on channel_C to - handle the last data */ - - EDMA_ResetChannel(handle->edmaIntermediaryToTxRegHandle->base, handle->edmaIntermediaryToTxRegHandle->channel); - - /*For DSPI instances with shared RX/TX DMA requests: use the scatter/gather to prepare the last data - * (handle->lastCommand) to SPI_PUSHR*/ - if (((1 != FSL_FEATURE_DSPI_HAS_SEPARATE_DMA_RX_TX_REQn(base)) && (handle->remainingSendByteCount > 0))) - { - transferConfigC.srcAddr = (uint32_t) & (handle->lastCommand); - transferConfigC.destAddr = (uint32_t)txAddr; - transferConfigC.srcTransferSize = kEDMA_TransferSize4Bytes; - transferConfigC.destTransferSize = kEDMA_TransferSize4Bytes; - transferConfigC.srcOffset = 0; - transferConfigC.destOffset = 0; - transferConfigC.minorLoopBytes = 4; - transferConfigC.majorLoopCounts = 1; - - EDMA_TcdReset(softwareTCD); - EDMA_TcdSetTransferConfig(softwareTCD, &transferConfigC, NULL); - } - - if (((handle->remainingSendByteCount > 1) && (handle->bitsPerFrame <= 8)) || - ((handle->remainingSendByteCount > 2) && (handle->bitsPerFrame > 8)) || - (1 == FSL_FEATURE_DSPI_HAS_SEPARATE_DMA_RX_TX_REQn(base))) - { - transferConfigC.srcAddr = (uint32_t)(&(handle->command)); - transferConfigC.destAddr = (uint32_t)txAddr; - - transferConfigC.srcTransferSize = kEDMA_TransferSize4Bytes; - transferConfigC.destTransferSize = kEDMA_TransferSize4Bytes; - transferConfigC.srcOffset = 0; - transferConfigC.destOffset = 0; - transferConfigC.minorLoopBytes = 4; - if (1 != FSL_FEATURE_DSPI_HAS_SEPARATE_DMA_RX_TX_REQn(base)) - { - if (handle->bitsPerFrame <= 8) - { - transferConfigC.majorLoopCounts = handle->remainingSendByteCount - 1; - } - else - { - transferConfigC.majorLoopCounts = handle->remainingSendByteCount / 2 - 1; - } - - EDMA_SetTransferConfig(handle->edmaIntermediaryToTxRegHandle->base, - handle->edmaIntermediaryToTxRegHandle->channel, &transferConfigC, softwareTCD); - } - else - { - transferConfigC.majorLoopCounts = 1; - - EDMA_SetTransferConfig(handle->edmaIntermediaryToTxRegHandle->base, - handle->edmaIntermediaryToTxRegHandle->channel, &transferConfigC, NULL); - } - - EDMA_EnableAutoStopRequest(handle->edmaIntermediaryToTxRegHandle->base, - handle->edmaIntermediaryToTxRegHandle->channel, false); - } - else - { - EDMA_SetTransferConfig(handle->edmaIntermediaryToTxRegHandle->base, - handle->edmaIntermediaryToTxRegHandle->channel, &transferConfigC, NULL); - } - - /*Start the EDMA channel_A , channel_B , channel_C transfer*/ - EDMA_StartTransfer(handle->edmaRxRegToRxDataHandle); - EDMA_StartTransfer(handle->edmaTxDataToIntermediaryHandle); - EDMA_StartTransfer(handle->edmaIntermediaryToTxRegHandle); - - /*Set channel priority*/ - uint8_t channelPriorityLow = handle->edmaRxRegToRxDataHandle->channel; - uint8_t channelPriorityMid = handle->edmaTxDataToIntermediaryHandle->channel; - uint8_t channelPriorityHigh = handle->edmaIntermediaryToTxRegHandle->channel; - uint8_t t = 0; - if (channelPriorityLow > channelPriorityMid) - { - t = channelPriorityLow; - channelPriorityLow = channelPriorityMid; - channelPriorityMid = t; - } - - if (channelPriorityLow > channelPriorityHigh) - { - t = channelPriorityLow; - channelPriorityLow = channelPriorityHigh; - channelPriorityHigh = t; - } - - if (channelPriorityMid > channelPriorityHigh) - { - t = channelPriorityMid; - channelPriorityMid = channelPriorityHigh; - channelPriorityHigh = t; - } - edma_channel_Preemption_config_t preemption_config_t; - preemption_config_t.enableChannelPreemption = true; - preemption_config_t.enablePreemptAbility = true; - preemption_config_t.channelPriority = channelPriorityLow; - - if (1 != FSL_FEATURE_DSPI_HAS_SEPARATE_DMA_RX_TX_REQn(base)) - { - EDMA_SetChannelPreemptionConfig(handle->edmaRxRegToRxDataHandle->base, handle->edmaRxRegToRxDataHandle->channel, - &preemption_config_t); - - preemption_config_t.channelPriority = channelPriorityMid; - EDMA_SetChannelPreemptionConfig(handle->edmaTxDataToIntermediaryHandle->base, - handle->edmaTxDataToIntermediaryHandle->channel, &preemption_config_t); - - preemption_config_t.channelPriority = channelPriorityHigh; - EDMA_SetChannelPreemptionConfig(handle->edmaIntermediaryToTxRegHandle->base, - handle->edmaIntermediaryToTxRegHandle->channel, &preemption_config_t); - } - else - { - EDMA_SetChannelPreemptionConfig(handle->edmaIntermediaryToTxRegHandle->base, - handle->edmaIntermediaryToTxRegHandle->channel, &preemption_config_t); - - preemption_config_t.channelPriority = channelPriorityMid; - EDMA_SetChannelPreemptionConfig(handle->edmaTxDataToIntermediaryHandle->base, - handle->edmaTxDataToIntermediaryHandle->channel, &preemption_config_t); - - preemption_config_t.channelPriority = channelPriorityHigh; - EDMA_SetChannelPreemptionConfig(handle->edmaRxRegToRxDataHandle->base, handle->edmaRxRegToRxDataHandle->channel, - &preemption_config_t); - } - - /*Set the channel link.*/ - if (1 == FSL_FEATURE_DSPI_HAS_SEPARATE_DMA_RX_TX_REQn(base)) - { - /*if there is Tx DMA request , carry the 32bits data (handle->command) to PUSHR first , then link to channelB - to prepare the next 32bits data (txData to handle->command) */ - if (handle->remainingSendByteCount > 1) - { - EDMA_SetChannelLink(handle->edmaIntermediaryToTxRegHandle->base, - handle->edmaIntermediaryToTxRegHandle->channel, kEDMA_MajorLink, - handle->edmaTxDataToIntermediaryHandle->channel); - } - - DSPI_EnableDMA(base, kDSPI_RxDmaEnable | kDSPI_TxDmaEnable); - } - else - { - if (handle->remainingSendByteCount > 0) - { - EDMA_SetChannelLink(handle->edmaRxRegToRxDataHandle->base, handle->edmaRxRegToRxDataHandle->channel, - kEDMA_MinorLink, handle->edmaTxDataToIntermediaryHandle->channel); - - EDMA_SetChannelLink(handle->edmaTxDataToIntermediaryHandle->base, - handle->edmaTxDataToIntermediaryHandle->channel, kEDMA_MinorLink, - handle->edmaIntermediaryToTxRegHandle->channel); - } - - DSPI_EnableDMA(base, kDSPI_RxDmaEnable); - } - - DSPI_StartTransfer(base); - - return kStatus_Success; -} - -static void EDMA_DspiMasterCallback(edma_handle_t *edmaHandle, - void *g_dspiEdmaPrivateHandle, - bool transferDone, - uint32_t tcds) -{ - assert(edmaHandle); - assert(g_dspiEdmaPrivateHandle); - - dspi_master_edma_private_handle_t *dspiEdmaPrivateHandle; - - dspiEdmaPrivateHandle = (dspi_master_edma_private_handle_t *)g_dspiEdmaPrivateHandle; - - DSPI_DisableDMA((dspiEdmaPrivateHandle->base), kDSPI_RxDmaEnable | kDSPI_TxDmaEnable); - - dspiEdmaPrivateHandle->handle->state = kDSPI_Idle; - - if (dspiEdmaPrivateHandle->handle->callback) - { - dspiEdmaPrivateHandle->handle->callback(dspiEdmaPrivateHandle->base, dspiEdmaPrivateHandle->handle, - kStatus_Success, dspiEdmaPrivateHandle->handle->userData); - } -} - -void DSPI_MasterTransferAbortEDMA(SPI_Type *base, dspi_master_edma_handle_t *handle) -{ - assert(handle); - - DSPI_StopTransfer(base); - - DSPI_DisableDMA(base, kDSPI_RxDmaEnable | kDSPI_TxDmaEnable); - - EDMA_AbortTransfer(handle->edmaRxRegToRxDataHandle); - EDMA_AbortTransfer(handle->edmaTxDataToIntermediaryHandle); - EDMA_AbortTransfer(handle->edmaIntermediaryToTxRegHandle); - - handle->state = kDSPI_Idle; -} - -status_t DSPI_MasterTransferGetCountEDMA(SPI_Type *base, dspi_master_edma_handle_t *handle, size_t *count) -{ - assert(handle); - - if (!count) - { - return kStatus_InvalidArgument; - } - - /* Catch when there is not an active transfer. */ - if (handle->state != kDSPI_Busy) - { - *count = 0; - return kStatus_NoTransferInProgress; - } - - size_t bytes; - - bytes = (uint32_t)handle->nbytes * EDMA_GetRemainingMajorLoopCount(handle->edmaRxRegToRxDataHandle->base, - handle->edmaRxRegToRxDataHandle->channel); - - *count = handle->totalByteCount - bytes; - - return kStatus_Success; -} - -void DSPI_SlaveTransferCreateHandleEDMA(SPI_Type *base, - dspi_slave_edma_handle_t *handle, - dspi_slave_edma_transfer_callback_t callback, - void *userData, - edma_handle_t *edmaRxRegToRxDataHandle, - edma_handle_t *edmaTxDataToTxRegHandle) -{ - assert(handle); - assert(edmaRxRegToRxDataHandle); - assert(edmaTxDataToTxRegHandle); - - /* Zero the handle. */ - memset(handle, 0, sizeof(*handle)); - - uint32_t instance = DSPI_GetInstance(base); - - s_dspiSlaveEdmaPrivateHandle[instance].base = base; - s_dspiSlaveEdmaPrivateHandle[instance].handle = handle; - - handle->callback = callback; - handle->userData = userData; - - handle->edmaRxRegToRxDataHandle = edmaRxRegToRxDataHandle; - handle->edmaTxDataToTxRegHandle = edmaTxDataToTxRegHandle; -} - -status_t DSPI_SlaveTransferEDMA(SPI_Type *base, dspi_slave_edma_handle_t *handle, dspi_transfer_t *transfer) -{ - assert(handle); - assert(transfer); - - /* If send/receive length is zero */ - if (transfer->dataSize == 0) - { - return kStatus_InvalidArgument; - } - - /* If both send buffer and receive buffer is null */ - if ((!(transfer->txData)) && (!(transfer->rxData))) - { - return kStatus_InvalidArgument; - } - - /* Check that we're not busy.*/ - if (handle->state == kDSPI_Busy) - { - return kStatus_DSPI_Busy; - } - - handle->state = kDSPI_Busy; - - uint32_t instance = DSPI_GetInstance(base); - uint8_t whichCtar = (transfer->configFlags & DSPI_SLAVE_CTAR_MASK) >> DSPI_SLAVE_CTAR_SHIFT; - handle->bitsPerFrame = - (((base->CTAR_SLAVE[whichCtar]) & SPI_CTAR_SLAVE_FMSZ_MASK) >> SPI_CTAR_SLAVE_FMSZ_SHIFT) + 1; - - /* If using a shared RX/TX DMA request, then this limits the amount of data we can transfer - * due to the linked channel. The max bytes is 511 if 8-bit/frame or 1022 if 16-bit/frame - */ - uint32_t limited_size = 0; - if (1 == FSL_FEATURE_DSPI_HAS_SEPARATE_DMA_RX_TX_REQn(base)) - { - limited_size = 32767u; - } - else - { - limited_size = 511u; - } - - if (handle->bitsPerFrame > 8) - { - if (transfer->dataSize > (limited_size << 1u)) - { - handle->state = kDSPI_Idle; - return kStatus_DSPI_OutOfRange; - } - } - else - { - if (transfer->dataSize > limited_size) - { - handle->state = kDSPI_Idle; - return kStatus_DSPI_OutOfRange; - } - } - - /*The data size should be even if the bitsPerFrame is greater than 8 (that is 2 bytes per frame in dspi) */ - if ((handle->bitsPerFrame > 8) && (transfer->dataSize & 0x1)) - { - handle->state = kDSPI_Idle; - return kStatus_InvalidArgument; - } - - EDMA_SetCallback(handle->edmaRxRegToRxDataHandle, EDMA_DspiSlaveCallback, &s_dspiSlaveEdmaPrivateHandle[instance]); - - /* Store transfer information */ - handle->txData = transfer->txData; - handle->rxData = transfer->rxData; - handle->remainingSendByteCount = transfer->dataSize; - handle->remainingReceiveByteCount = transfer->dataSize; - handle->totalByteCount = transfer->dataSize; - - uint16_t wordToSend = 0; - uint8_t dummyData = DSPI_DUMMY_DATA; - uint8_t dataAlreadyFed = 0; - uint8_t dataFedMax = 2; - - uint32_t rxAddr = DSPI_GetRxRegisterAddress(base); - uint32_t txAddr = DSPI_SlaveGetTxRegisterAddress(base); - - edma_transfer_config_t transferConfigA; - edma_transfer_config_t transferConfigC; - - DSPI_StopTransfer(base); - - DSPI_FlushFifo(base, true, true); - DSPI_ClearStatusFlags(base, kDSPI_AllStatusFlag); - - DSPI_DisableDMA(base, kDSPI_RxDmaEnable | kDSPI_TxDmaEnable); - - DSPI_StartTransfer(base); - - /*if dspi has separate dma request , need not prepare data first . - else (dspi has shared dma request) , send first 2 data into fifo if there is fifo or send first 1 data to - slaveGetTxRegister if there is no fifo*/ - if (1 != FSL_FEATURE_DSPI_HAS_SEPARATE_DMA_RX_TX_REQn(base)) - { - /* For DSPI instances with shared RX/TX DMA requests, we'll use the RX DMA request to - * trigger ongoing transfers and will link to the TX DMA channel from the RX DMA channel. - */ - /* If bits/frame is greater than one byte */ - if (handle->bitsPerFrame > 8) - { - while (DSPI_GetStatusFlags(base) & kDSPI_TxFifoFillRequestFlag) - { - if (handle->txData) - { - wordToSend = *(handle->txData); - ++handle->txData; /* Increment to next data byte */ - - wordToSend |= (unsigned)(*(handle->txData)) << 8U; - ++handle->txData; /* Increment to next data byte */ - } - else - { - wordToSend = ((uint32_t)dummyData << 8) | dummyData; - } - handle->remainingSendByteCount -= 2; /* decrement remainingSendByteCount by 2 */ - base->PUSHR_SLAVE = wordToSend; - - /* Try to clear the TFFF; if the TX FIFO is full this will clear */ - DSPI_ClearStatusFlags(base, kDSPI_TxFifoFillRequestFlag); - - dataAlreadyFed += 2; - - /* Exit loop if send count is zero, else update local variables for next loop */ - if ((handle->remainingSendByteCount == 0) || (dataAlreadyFed == (dataFedMax * 2))) - { - break; - } - } /* End of TX FIFO fill while loop */ - } - else /* Optimized for bits/frame less than or equal to one byte. */ - { - while (DSPI_GetStatusFlags(base) & kDSPI_TxFifoFillRequestFlag) - { - if (handle->txData) - { - wordToSend = *(handle->txData); - /* Increment to next data word*/ - ++handle->txData; - } - else - { - wordToSend = dummyData; - } - - base->PUSHR_SLAVE = wordToSend; - - /* Try to clear the TFFF; if the TX FIFO is full this will clear */ - DSPI_ClearStatusFlags(base, kDSPI_TxFifoFillRequestFlag); - /* Decrement remainingSendByteCount*/ - --handle->remainingSendByteCount; - - dataAlreadyFed++; - - /* Exit loop if send count is zero, else update local variables for next loop */ - if ((handle->remainingSendByteCount == 0) || (dataAlreadyFed == dataFedMax)) - { - break; - } - } /* End of TX FIFO fill while loop */ - } - } - - /***channel_A *** used for carry the data from Rx_Data_Register(POPR) to User_Receive_Buffer*/ - if (handle->remainingReceiveByteCount > 0) - { - EDMA_ResetChannel(handle->edmaRxRegToRxDataHandle->base, handle->edmaRxRegToRxDataHandle->channel); - - transferConfigA.srcAddr = (uint32_t)rxAddr; - transferConfigA.srcOffset = 0; - - if (handle->rxData) - { - transferConfigA.destAddr = (uint32_t) & (handle->rxData[0]); - transferConfigA.destOffset = 1; - } - else - { - transferConfigA.destAddr = (uint32_t) & (handle->rxBuffIfNull); - transferConfigA.destOffset = 0; - } - - transferConfigA.destTransferSize = kEDMA_TransferSize1Bytes; - - if (handle->bitsPerFrame <= 8) - { - transferConfigA.srcTransferSize = kEDMA_TransferSize1Bytes; - transferConfigA.minorLoopBytes = 1; - transferConfigA.majorLoopCounts = handle->remainingReceiveByteCount; - } - else - { - transferConfigA.srcTransferSize = kEDMA_TransferSize2Bytes; - transferConfigA.minorLoopBytes = 2; - transferConfigA.majorLoopCounts = handle->remainingReceiveByteCount / 2; - } - - /* Store the initially configured eDMA minor byte transfer count into the DSPI handle */ - handle->nbytes = transferConfigA.minorLoopBytes; - - EDMA_SetTransferConfig(handle->edmaRxRegToRxDataHandle->base, handle->edmaRxRegToRxDataHandle->channel, - &transferConfigA, NULL); - EDMA_EnableChannelInterrupts(handle->edmaRxRegToRxDataHandle->base, handle->edmaRxRegToRxDataHandle->channel, - kEDMA_MajorInterruptEnable); - } - - if (handle->remainingSendByteCount > 0) - { - /***channel_C *** used for carry the data from User_Send_Buffer to Tx_Data_Register(PUSHR_SLAVE)*/ - EDMA_ResetChannel(handle->edmaTxDataToTxRegHandle->base, handle->edmaTxDataToTxRegHandle->channel); - - transferConfigC.destAddr = (uint32_t)txAddr; - transferConfigC.destOffset = 0; - - if (handle->txData) - { - transferConfigC.srcAddr = (uint32_t)(&(handle->txData[0])); - transferConfigC.srcOffset = 1; - } - else - { - transferConfigC.srcAddr = (uint32_t)(&handle->txBuffIfNull); - transferConfigC.srcOffset = 0; - if (handle->bitsPerFrame <= 8) - { - handle->txBuffIfNull = DSPI_DUMMY_DATA; - } - else - { - handle->txBuffIfNull = (DSPI_DUMMY_DATA << 8) | DSPI_DUMMY_DATA; - } - } - - transferConfigC.srcTransferSize = kEDMA_TransferSize1Bytes; - - if (handle->bitsPerFrame <= 8) - { - transferConfigC.destTransferSize = kEDMA_TransferSize1Bytes; - transferConfigC.minorLoopBytes = 1; - transferConfigC.majorLoopCounts = handle->remainingSendByteCount; - } - else - { - transferConfigC.destTransferSize = kEDMA_TransferSize2Bytes; - transferConfigC.minorLoopBytes = 2; - transferConfigC.majorLoopCounts = handle->remainingSendByteCount / 2; - } - - EDMA_SetTransferConfig(handle->edmaTxDataToTxRegHandle->base, handle->edmaTxDataToTxRegHandle->channel, - &transferConfigC, NULL); - - EDMA_StartTransfer(handle->edmaTxDataToTxRegHandle); - } - - EDMA_StartTransfer(handle->edmaRxRegToRxDataHandle); - - /*Set channel priority*/ - uint8_t channelPriorityLow = handle->edmaRxRegToRxDataHandle->channel; - uint8_t channelPriorityHigh = handle->edmaTxDataToTxRegHandle->channel; - uint8_t t = 0; - - if (channelPriorityLow > channelPriorityHigh) - { - t = channelPriorityLow; - channelPriorityLow = channelPriorityHigh; - channelPriorityHigh = t; - } - - edma_channel_Preemption_config_t preemption_config_t; - preemption_config_t.enableChannelPreemption = true; - preemption_config_t.enablePreemptAbility = true; - preemption_config_t.channelPriority = channelPriorityLow; - - if (1 != FSL_FEATURE_DSPI_HAS_SEPARATE_DMA_RX_TX_REQn(base)) - { - EDMA_SetChannelPreemptionConfig(handle->edmaRxRegToRxDataHandle->base, handle->edmaRxRegToRxDataHandle->channel, - &preemption_config_t); - - preemption_config_t.channelPriority = channelPriorityHigh; - EDMA_SetChannelPreemptionConfig(handle->edmaTxDataToTxRegHandle->base, handle->edmaTxDataToTxRegHandle->channel, - &preemption_config_t); - } - else - { - EDMA_SetChannelPreemptionConfig(handle->edmaTxDataToTxRegHandle->base, handle->edmaTxDataToTxRegHandle->channel, - &preemption_config_t); - - preemption_config_t.channelPriority = channelPriorityHigh; - EDMA_SetChannelPreemptionConfig(handle->edmaRxRegToRxDataHandle->base, handle->edmaRxRegToRxDataHandle->channel, - &preemption_config_t); - } - - /*Set the channel link. - For DSPI instances with shared RX/TX DMA requests: Rx DMA request -> channel_A -> channel_C. - For DSPI instances with separate RX and TX DMA requests: - Rx DMA request -> channel_A - Tx DMA request -> channel_C */ - if (1 != FSL_FEATURE_DSPI_HAS_SEPARATE_DMA_RX_TX_REQn(base)) - { - if (handle->remainingSendByteCount > 0) - { - EDMA_SetChannelLink(handle->edmaRxRegToRxDataHandle->base, handle->edmaRxRegToRxDataHandle->channel, - kEDMA_MinorLink, handle->edmaTxDataToTxRegHandle->channel); - } - DSPI_EnableDMA(base, kDSPI_RxDmaEnable); - } - else - { - DSPI_EnableDMA(base, kDSPI_RxDmaEnable | kDSPI_TxDmaEnable); - } - - return kStatus_Success; -} - -static void EDMA_DspiSlaveCallback(edma_handle_t *edmaHandle, - void *g_dspiEdmaPrivateHandle, - bool transferDone, - uint32_t tcds) -{ - assert(edmaHandle); - assert(g_dspiEdmaPrivateHandle); - - dspi_slave_edma_private_handle_t *dspiEdmaPrivateHandle; - - dspiEdmaPrivateHandle = (dspi_slave_edma_private_handle_t *)g_dspiEdmaPrivateHandle; - - DSPI_DisableDMA((dspiEdmaPrivateHandle->base), kDSPI_RxDmaEnable | kDSPI_TxDmaEnable); - - dspiEdmaPrivateHandle->handle->state = kDSPI_Idle; - - if (dspiEdmaPrivateHandle->handle->callback) - { - dspiEdmaPrivateHandle->handle->callback(dspiEdmaPrivateHandle->base, dspiEdmaPrivateHandle->handle, - kStatus_Success, dspiEdmaPrivateHandle->handle->userData); - } -} - -void DSPI_SlaveTransferAbortEDMA(SPI_Type *base, dspi_slave_edma_handle_t *handle) -{ - assert(handle); - - DSPI_StopTransfer(base); - - DSPI_DisableDMA(base, kDSPI_RxDmaEnable | kDSPI_TxDmaEnable); - - EDMA_AbortTransfer(handle->edmaRxRegToRxDataHandle); - EDMA_AbortTransfer(handle->edmaTxDataToTxRegHandle); - - handle->state = kDSPI_Idle; -} - -status_t DSPI_SlaveTransferGetCountEDMA(SPI_Type *base, dspi_slave_edma_handle_t *handle, size_t *count) -{ - assert(handle); - - if (!count) - { - return kStatus_InvalidArgument; - } - - /* Catch when there is not an active transfer. */ - if (handle->state != kDSPI_Busy) - { - *count = 0; - return kStatus_NoTransferInProgress; - } - - size_t bytes; - - bytes = (uint32_t)handle->nbytes * EDMA_GetRemainingMajorLoopCount(handle->edmaRxRegToRxDataHandle->base, - handle->edmaRxRegToRxDataHandle->channel); - - *count = handle->totalByteCount - bytes; - - return kStatus_Success; -} diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_dspi_edma.h b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_dspi_edma.h deleted file mode 100644 index 23e29ce2983..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_dspi_edma.h +++ /dev/null @@ -1,281 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -#ifndef _FSL_DSPI_EDMA_H_ -#define _FSL_DSPI_EDMA_H_ - -#include "fsl_dspi.h" -#include "fsl_edma.h" -/*! - * @addtogroup dspi_edma_driver - * @{ - */ - -/*********************************************************************************************************************** - * Definitions - **********************************************************************************************************************/ - -/*! -* @brief Forward declaration of the DSPI eDMA master handle typedefs. -*/ -typedef struct _dspi_master_edma_handle dspi_master_edma_handle_t; - -/*! -* @brief Forward declaration of the DSPI eDMA slave handle typedefs. -*/ -typedef struct _dspi_slave_edma_handle dspi_slave_edma_handle_t; - -/*! - * @brief Completion callback function pointer type. - * - * @param base DSPI peripheral base address. - * @param handle A pointer to the handle for the DSPI master. - * @param status Success or error code describing whether the transfer completed. - * @param userData An arbitrary pointer-dataSized value passed from the application. - */ -typedef void (*dspi_master_edma_transfer_callback_t)(SPI_Type *base, - dspi_master_edma_handle_t *handle, - status_t status, - void *userData); -/*! - * @brief Completion callback function pointer type. - * - * @param base DSPI peripheral base address. - * @param handle A pointer to the handle for the DSPI slave. - * @param status Success or error code describing whether the transfer completed. - * @param userData An arbitrary pointer-dataSized value passed from the application. - */ -typedef void (*dspi_slave_edma_transfer_callback_t)(SPI_Type *base, - dspi_slave_edma_handle_t *handle, - status_t status, - void *userData); - -/*! @brief DSPI master eDMA transfer handle structure used for the transactional API. */ -struct _dspi_master_edma_handle -{ - uint32_t bitsPerFrame; /*!< The desired number of bits per frame. */ - volatile uint32_t command; /*!< The desired data command. */ - volatile uint32_t lastCommand; /*!< The desired last data command. */ - - uint8_t fifoSize; /*!< FIFO dataSize. */ - - volatile bool - isPcsActiveAfterTransfer; /*!< Indicates whether the PCS signal keeps active after the last frame transfer.*/ - - uint8_t nbytes; /*!< eDMA minor byte transfer count initially configured. */ - volatile uint8_t state; /*!< DSPI transfer state , _dspi_transfer_state.*/ - - uint8_t *volatile txData; /*!< Send buffer. */ - uint8_t *volatile rxData; /*!< Receive buffer. */ - volatile size_t remainingSendByteCount; /*!< A number of bytes remaining to send.*/ - volatile size_t remainingReceiveByteCount; /*!< A number of bytes remaining to receive.*/ - size_t totalByteCount; /*!< A number of transfer bytes*/ - - uint32_t rxBuffIfNull; /*!< Used if there is not rxData for DMA purpose.*/ - uint32_t txBuffIfNull; /*!< Used if there is not txData for DMA purpose.*/ - - dspi_master_edma_transfer_callback_t callback; /*!< Completion callback. */ - void *userData; /*!< Callback user data. */ - - edma_handle_t *edmaRxRegToRxDataHandle; /*!TCD[channel].SADDR = tcd->SADDR; - base->TCD[channel].SOFF = tcd->SOFF; - base->TCD[channel].ATTR = tcd->ATTR; - base->TCD[channel].NBYTES_MLNO = tcd->NBYTES; - base->TCD[channel].SLAST = tcd->SLAST; - base->TCD[channel].DADDR = tcd->DADDR; - base->TCD[channel].DOFF = tcd->DOFF; - base->TCD[channel].CITER_ELINKNO = tcd->CITER; - base->TCD[channel].DLAST_SGA = tcd->DLAST_SGA; - /* Clear DONE bit first, otherwise ESG cannot be set */ - base->TCD[channel].CSR = 0; - base->TCD[channel].CSR = tcd->CSR; - base->TCD[channel].BITER_ELINKNO = tcd->BITER; -} - -void EDMA_Init(DMA_Type *base, const edma_config_t *config) -{ - assert(config != NULL); - - uint32_t tmpreg; - -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) - /* Ungate EDMA periphral clock */ - CLOCK_EnableClock(s_edmaClockName[EDMA_GetInstance(base)]); -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ - /* Configure EDMA peripheral according to the configuration structure. */ - tmpreg = base->CR; - tmpreg &= ~(DMA_CR_ERCA_MASK | DMA_CR_HOE_MASK | DMA_CR_CLM_MASK | DMA_CR_EDBG_MASK); - tmpreg |= (DMA_CR_ERCA(config->enableRoundRobinArbitration) | DMA_CR_HOE(config->enableHaltOnError) | - DMA_CR_CLM(config->enableContinuousLinkMode) | DMA_CR_EDBG(config->enableDebugMode) | DMA_CR_EMLM(true)); - base->CR = tmpreg; -} - -void EDMA_Deinit(DMA_Type *base) -{ -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) - /* Gate EDMA periphral clock */ - CLOCK_DisableClock(s_edmaClockName[EDMA_GetInstance(base)]); -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ -} - -void EDMA_GetDefaultConfig(edma_config_t *config) -{ - assert(config != NULL); - - config->enableRoundRobinArbitration = false; - config->enableHaltOnError = true; - config->enableContinuousLinkMode = false; - config->enableDebugMode = false; -} - -void EDMA_ResetChannel(DMA_Type *base, uint32_t channel) -{ - assert(channel < FSL_FEATURE_EDMA_MODULE_CHANNEL); - - EDMA_TcdReset((edma_tcd_t *)&base->TCD[channel]); -} - -void EDMA_SetTransferConfig(DMA_Type *base, uint32_t channel, const edma_transfer_config_t *config, edma_tcd_t *nextTcd) -{ - assert(channel < FSL_FEATURE_EDMA_MODULE_CHANNEL); - assert(config != NULL); - assert(((uint32_t)nextTcd & 0x1FU) == 0); - - EDMA_TcdSetTransferConfig((edma_tcd_t *)&base->TCD[channel], config, nextTcd); -} - -void EDMA_SetMinorOffsetConfig(DMA_Type *base, uint32_t channel, const edma_minor_offset_config_t *config) -{ - assert(channel < FSL_FEATURE_EDMA_MODULE_CHANNEL); - assert(config != NULL); - - uint32_t tmpreg; - - tmpreg = base->TCD[channel].NBYTES_MLOFFYES; - tmpreg &= ~(DMA_NBYTES_MLOFFYES_SMLOE_MASK | DMA_NBYTES_MLOFFYES_DMLOE_MASK | DMA_NBYTES_MLOFFYES_MLOFF_MASK); - tmpreg |= - (DMA_NBYTES_MLOFFYES_SMLOE(config->enableSrcMinorOffset) | - DMA_NBYTES_MLOFFYES_DMLOE(config->enableDestMinorOffset) | DMA_NBYTES_MLOFFYES_MLOFF(config->minorOffset)); - base->TCD[channel].NBYTES_MLOFFYES = tmpreg; -} - -void EDMA_SetChannelLink(DMA_Type *base, uint32_t channel, edma_channel_link_type_t type, uint32_t linkedChannel) -{ - assert(channel < FSL_FEATURE_EDMA_MODULE_CHANNEL); - assert(linkedChannel < FSL_FEATURE_EDMA_MODULE_CHANNEL); - - EDMA_TcdSetChannelLink((edma_tcd_t *)&base->TCD[channel], type, linkedChannel); -} - -void EDMA_SetBandWidth(DMA_Type *base, uint32_t channel, edma_bandwidth_t bandWidth) -{ - assert(channel < FSL_FEATURE_EDMA_MODULE_CHANNEL); - - base->TCD[channel].CSR = (base->TCD[channel].CSR & (~DMA_CSR_BWC_MASK)) | DMA_CSR_BWC(bandWidth); -} - -void EDMA_SetModulo(DMA_Type *base, uint32_t channel, edma_modulo_t srcModulo, edma_modulo_t destModulo) -{ - assert(channel < FSL_FEATURE_EDMA_MODULE_CHANNEL); - - uint32_t tmpreg; - - tmpreg = base->TCD[channel].ATTR & (~(DMA_ATTR_SMOD_MASK | DMA_ATTR_DMOD_MASK)); - base->TCD[channel].ATTR = tmpreg | DMA_ATTR_DMOD(destModulo) | DMA_ATTR_SMOD(srcModulo); -} - -void EDMA_EnableChannelInterrupts(DMA_Type *base, uint32_t channel, uint32_t mask) -{ - assert(channel < FSL_FEATURE_EDMA_MODULE_CHANNEL); - - /* Enable error interrupt */ - if (mask & kEDMA_ErrorInterruptEnable) - { - base->EEI |= (0x1U << channel); - } - - /* Enable Major interrupt */ - if (mask & kEDMA_MajorInterruptEnable) - { - base->TCD[channel].CSR |= DMA_CSR_INTMAJOR_MASK; - } - - /* Enable Half major interrupt */ - if (mask & kEDMA_HalfInterruptEnable) - { - base->TCD[channel].CSR |= DMA_CSR_INTHALF_MASK; - } -} - -void EDMA_DisableChannelInterrupts(DMA_Type *base, uint32_t channel, uint32_t mask) -{ - assert(channel < FSL_FEATURE_EDMA_MODULE_CHANNEL); - - /* Disable error interrupt */ - if (mask & kEDMA_ErrorInterruptEnable) - { - base->EEI &= ~(0x1U << channel); - } - - /* Disable Major interrupt */ - if (mask & kEDMA_MajorInterruptEnable) - { - base->TCD[channel].CSR &= ~DMA_CSR_INTMAJOR_MASK; - } - - /* Disable Half major interrupt */ - if (mask & kEDMA_HalfInterruptEnable) - { - base->TCD[channel].CSR &= ~DMA_CSR_INTHALF_MASK; - } -} - -void EDMA_TcdReset(edma_tcd_t *tcd) -{ - assert(tcd != NULL); - assert(((uint32_t)tcd & 0x1FU) == 0); - - /* Reset channel TCD */ - tcd->SADDR = 0U; - tcd->SOFF = 0U; - tcd->ATTR = 0U; - tcd->NBYTES = 0U; - tcd->SLAST = 0U; - tcd->DADDR = 0U; - tcd->DOFF = 0U; - tcd->CITER = 0U; - tcd->DLAST_SGA = 0U; - /* Enable auto disable request feature */ - tcd->CSR = DMA_CSR_DREQ(true); - tcd->BITER = 0U; -} - -void EDMA_TcdSetTransferConfig(edma_tcd_t *tcd, const edma_transfer_config_t *config, edma_tcd_t *nextTcd) -{ - assert(tcd != NULL); - assert(((uint32_t)tcd & 0x1FU) == 0); - assert(config != NULL); - assert(((uint32_t)nextTcd & 0x1FU) == 0); - - /* source address */ - tcd->SADDR = config->srcAddr; - /* destination address */ - tcd->DADDR = config->destAddr; - /* Source data and destination data transfer size */ - tcd->ATTR = DMA_ATTR_SSIZE(config->srcTransferSize) | DMA_ATTR_DSIZE(config->destTransferSize); - /* Source address signed offset */ - tcd->SOFF = config->srcOffset; - /* Destination address signed offset */ - tcd->DOFF = config->destOffset; - /* Minor byte transfer count */ - tcd->NBYTES = config->minorLoopBytes; - /* Current major iteration count */ - tcd->CITER = config->majorLoopCounts; - /* Starting major iteration count */ - tcd->BITER = config->majorLoopCounts; - /* Enable scatter/gather processing */ - if (nextTcd != NULL) - { - tcd->DLAST_SGA = (uint32_t)nextTcd; - /* - Before call EDMA_TcdSetTransferConfig or EDMA_SetTransferConfig, - user must call EDMA_TcdReset or EDMA_ResetChannel which will set - DREQ, so must use "|" or "&" rather than "=". - - Clear the DREQ bit because scatter gather has been enabled, so the - previous transfer is not the last transfer, and channel request should - be enabled at the next transfer(the next TCD). - */ - tcd->CSR = (tcd->CSR | DMA_CSR_ESG_MASK) & ~DMA_CSR_DREQ_MASK; - } -} - -void EDMA_TcdSetMinorOffsetConfig(edma_tcd_t *tcd, const edma_minor_offset_config_t *config) -{ - assert(tcd != NULL); - assert(((uint32_t)tcd & 0x1FU) == 0); - - uint32_t tmpreg; - - tmpreg = tcd->NBYTES & - ~(DMA_NBYTES_MLOFFYES_SMLOE_MASK | DMA_NBYTES_MLOFFYES_DMLOE_MASK | DMA_NBYTES_MLOFFYES_MLOFF_MASK); - tmpreg |= - (DMA_NBYTES_MLOFFYES_SMLOE(config->enableSrcMinorOffset) | - DMA_NBYTES_MLOFFYES_DMLOE(config->enableDestMinorOffset) | DMA_NBYTES_MLOFFYES_MLOFF(config->minorOffset)); - tcd->NBYTES = tmpreg; -} - -void EDMA_TcdSetChannelLink(edma_tcd_t *tcd, edma_channel_link_type_t type, uint32_t linkedChannel) -{ - assert(tcd != NULL); - assert(((uint32_t)tcd & 0x1FU) == 0); - assert(linkedChannel < FSL_FEATURE_EDMA_MODULE_CHANNEL); - - if (type == kEDMA_MinorLink) /* Minor link config */ - { - uint32_t tmpreg; - - /* Enable minor link */ - tcd->CITER |= DMA_CITER_ELINKYES_ELINK_MASK; - tcd->BITER |= DMA_BITER_ELINKYES_ELINK_MASK; - /* Set likned channel */ - tmpreg = tcd->CITER & (~DMA_CITER_ELINKYES_LINKCH_MASK); - tmpreg |= DMA_CITER_ELINKYES_LINKCH(linkedChannel); - tcd->CITER = tmpreg; - tmpreg = tcd->BITER & (~DMA_BITER_ELINKYES_LINKCH_MASK); - tmpreg |= DMA_BITER_ELINKYES_LINKCH(linkedChannel); - tcd->BITER = tmpreg; - } - else if (type == kEDMA_MajorLink) /* Major link config */ - { - uint32_t tmpreg; - - /* Enable major link */ - tcd->CSR |= DMA_CSR_MAJORELINK_MASK; - /* Set major linked channel */ - tmpreg = tcd->CSR & (~DMA_CSR_MAJORLINKCH_MASK); - tcd->CSR = tmpreg | DMA_CSR_MAJORLINKCH(linkedChannel); - } - else /* Link none */ - { - tcd->CITER &= ~DMA_CITER_ELINKYES_ELINK_MASK; - tcd->BITER &= ~DMA_BITER_ELINKYES_ELINK_MASK; - tcd->CSR &= ~DMA_CSR_MAJORELINK_MASK; - } -} - -void EDMA_TcdSetModulo(edma_tcd_t *tcd, edma_modulo_t srcModulo, edma_modulo_t destModulo) -{ - assert(tcd != NULL); - assert(((uint32_t)tcd & 0x1FU) == 0); - - uint32_t tmpreg; - - tmpreg = tcd->ATTR & (~(DMA_ATTR_SMOD_MASK | DMA_ATTR_DMOD_MASK)); - tcd->ATTR = tmpreg | DMA_ATTR_DMOD(destModulo) | DMA_ATTR_SMOD(srcModulo); -} - -void EDMA_TcdEnableInterrupts(edma_tcd_t *tcd, uint32_t mask) -{ - assert(tcd != NULL); - - /* Enable Major interrupt */ - if (mask & kEDMA_MajorInterruptEnable) - { - tcd->CSR |= DMA_CSR_INTMAJOR_MASK; - } - - /* Enable Half major interrupt */ - if (mask & kEDMA_HalfInterruptEnable) - { - tcd->CSR |= DMA_CSR_INTHALF_MASK; - } -} - -void EDMA_TcdDisableInterrupts(edma_tcd_t *tcd, uint32_t mask) -{ - assert(tcd != NULL); - - /* Disable Major interrupt */ - if (mask & kEDMA_MajorInterruptEnable) - { - tcd->CSR &= ~DMA_CSR_INTMAJOR_MASK; - } - - /* Disable Half major interrupt */ - if (mask & kEDMA_HalfInterruptEnable) - { - tcd->CSR &= ~DMA_CSR_INTHALF_MASK; - } -} - -uint32_t EDMA_GetRemainingMajorLoopCount(DMA_Type *base, uint32_t channel) -{ - assert(channel < FSL_FEATURE_EDMA_MODULE_CHANNEL); - - uint32_t remainingCount = 0; - - if (DMA_CSR_DONE_MASK & base->TCD[channel].CSR) - { - remainingCount = 0; - } - else - { - /* Calculate the unfinished bytes */ - if (base->TCD[channel].CITER_ELINKNO & DMA_CITER_ELINKNO_ELINK_MASK) - { - remainingCount = - (base->TCD[channel].CITER_ELINKYES & DMA_CITER_ELINKYES_CITER_MASK) >> DMA_CITER_ELINKYES_CITER_SHIFT; - } - else - { - remainingCount = - (base->TCD[channel].CITER_ELINKNO & DMA_CITER_ELINKNO_CITER_MASK) >> DMA_CITER_ELINKNO_CITER_SHIFT; - } - } - - return remainingCount; -} - -uint32_t EDMA_GetChannelStatusFlags(DMA_Type *base, uint32_t channel) -{ - assert(channel < FSL_FEATURE_EDMA_MODULE_CHANNEL); - - uint32_t retval = 0; - - /* Get DONE bit flag */ - retval |= ((base->TCD[channel].CSR & DMA_CSR_DONE_MASK) >> DMA_CSR_DONE_SHIFT); - /* Get ERROR bit flag */ - retval |= (((base->ERR >> channel) & 0x1U) << 1U); - /* Get INT bit flag */ - retval |= (((base->INT >> channel) & 0x1U) << 2U); - - return retval; -} - -void EDMA_ClearChannelStatusFlags(DMA_Type *base, uint32_t channel, uint32_t mask) -{ - assert(channel < FSL_FEATURE_EDMA_MODULE_CHANNEL); - - /* Clear DONE bit flag */ - if (mask & kEDMA_DoneFlag) - { - base->CDNE = channel; - } - /* Clear ERROR bit flag */ - if (mask & kEDMA_ErrorFlag) - { - base->CERR = channel; - } - /* Clear INT bit flag */ - if (mask & kEDMA_InterruptFlag) - { - base->CINT = channel; - } -} - -void EDMA_CreateHandle(edma_handle_t *handle, DMA_Type *base, uint32_t channel) -{ - assert(handle != NULL); - assert(channel < FSL_FEATURE_EDMA_MODULE_CHANNEL); - - uint32_t edmaInstance; - uint32_t channelIndex; - edma_tcd_t *tcdRegs; - - /* Zero the handle */ - memset(handle, 0, sizeof(*handle)); - - handle->base = base; - handle->channel = channel; - /* Get the DMA instance number */ - edmaInstance = EDMA_GetInstance(base); - channelIndex = (edmaInstance * FSL_FEATURE_EDMA_MODULE_CHANNEL) + channel; - s_EDMAHandle[channelIndex] = handle; - - /* Enable NVIC interrupt */ - EnableIRQ(s_edmaIRQNumber[edmaInstance][channel]); - - /* - Reset TCD registers to zero. Unlike the EDMA_TcdReset(DREQ will be set), - CSR will be 0. Because in order to suit EDMA busy check mechanism in - EDMA_SubmitTransfer, CSR must be set 0. - */ - tcdRegs = (edma_tcd_t *)&handle->base->TCD[handle->channel]; - tcdRegs->SADDR = 0; - tcdRegs->SOFF = 0; - tcdRegs->ATTR = 0; - tcdRegs->NBYTES = 0; - tcdRegs->SLAST = 0; - tcdRegs->DADDR = 0; - tcdRegs->DOFF = 0; - tcdRegs->CITER = 0; - tcdRegs->DLAST_SGA = 0; - tcdRegs->CSR = 0; - tcdRegs->BITER = 0; -} - -void EDMA_InstallTCDMemory(edma_handle_t *handle, edma_tcd_t *tcdPool, uint32_t tcdSize) -{ - assert(handle != NULL); - assert(((uint32_t)tcdPool & 0x1FU) == 0); - - /* Initialize tcd queue attibute. */ - handle->header = 0; - handle->tail = 0; - handle->tcdUsed = 0; - handle->tcdSize = tcdSize; - handle->flags = 0; - handle->tcdPool = tcdPool; -} - -void EDMA_SetCallback(edma_handle_t *handle, edma_callback callback, void *userData) -{ - assert(handle != NULL); - - handle->callback = callback; - handle->userData = userData; -} - -void EDMA_PrepareTransfer(edma_transfer_config_t *config, - void *srcAddr, - uint32_t srcWidth, - void *destAddr, - uint32_t destWidth, - uint32_t bytesEachRequest, - uint32_t transferBytes, - edma_transfer_type_t type) -{ - assert(config != NULL); - assert(srcAddr != NULL); - assert(destAddr != NULL); - assert((srcWidth == 1U) || (srcWidth == 2U) || (srcWidth == 4U) || (srcWidth == 16U) || (srcWidth == 32U)); - assert((destWidth == 1U) || (destWidth == 2U) || (destWidth == 4U) || (destWidth == 16U) || (destWidth == 32U)); - assert(transferBytes % bytesEachRequest == 0); - - config->destAddr = (uint32_t)destAddr; - config->srcAddr = (uint32_t)srcAddr; - config->minorLoopBytes = bytesEachRequest; - config->majorLoopCounts = transferBytes / bytesEachRequest; - switch (srcWidth) - { - case 1U: - config->srcTransferSize = kEDMA_TransferSize1Bytes; - break; - case 2U: - config->srcTransferSize = kEDMA_TransferSize2Bytes; - break; - case 4U: - config->srcTransferSize = kEDMA_TransferSize4Bytes; - break; - case 16U: - config->srcTransferSize = kEDMA_TransferSize16Bytes; - break; - case 32U: - config->srcTransferSize = kEDMA_TransferSize32Bytes; - break; - default: - break; - } - switch (destWidth) - { - case 1U: - config->destTransferSize = kEDMA_TransferSize1Bytes; - break; - case 2U: - config->destTransferSize = kEDMA_TransferSize2Bytes; - break; - case 4U: - config->destTransferSize = kEDMA_TransferSize4Bytes; - break; - case 16U: - config->destTransferSize = kEDMA_TransferSize16Bytes; - break; - case 32U: - config->destTransferSize = kEDMA_TransferSize32Bytes; - break; - default: - break; - } - switch (type) - { - case kEDMA_MemoryToMemory: - config->destOffset = destWidth; - config->srcOffset = srcWidth; - break; - case kEDMA_MemoryToPeripheral: - config->destOffset = 0U; - config->srcOffset = srcWidth; - break; - case kEDMA_PeripheralToMemory: - config->destOffset = destWidth; - config->srcOffset = 0U; - break; - default: - break; - } -} - -status_t EDMA_SubmitTransfer(edma_handle_t *handle, const edma_transfer_config_t *config) -{ - assert(handle != NULL); - assert(config != NULL); - - edma_tcd_t *tcdRegs = (edma_tcd_t *)&handle->base->TCD[handle->channel]; - - if (handle->tcdPool == NULL) - { - /* - Check if EDMA is busy: if the given channel started transfer, CSR will be not zero. Because - if it is the last transfer, DREQ will be set. If not, ESG will be set. So in order to suit - this check mechanism, EDMA_CreatHandle will clear CSR register. - */ - if ((tcdRegs->CSR != 0) && ((tcdRegs->CSR & DMA_CSR_DONE_MASK) == 0)) - { - return kStatus_EDMA_Busy; - } - else - { - EDMA_SetTransferConfig(handle->base, handle->channel, config, NULL); - /* Enable auto disable request feature */ - handle->base->TCD[handle->channel].CSR |= DMA_CSR_DREQ_MASK; - /* Enable major interrupt */ - handle->base->TCD[handle->channel].CSR |= DMA_CSR_INTMAJOR_MASK; - - return kStatus_Success; - } - } - else /* Use the TCD queue. */ - { - uint32_t primask; - uint32_t csr; - int8_t currentTcd; - int8_t previousTcd; - int8_t nextTcd; - - /* Check if tcd pool is full. */ - primask = DisableGlobalIRQ(); - if (handle->tcdUsed >= handle->tcdSize) - { - EnableGlobalIRQ(primask); - - return kStatus_EDMA_QueueFull; - } - currentTcd = handle->tail; - handle->tcdUsed++; - /* Calculate index of next TCD */ - nextTcd = currentTcd + 1U; - if (nextTcd == handle->tcdSize) - { - nextTcd = 0U; - } - /* Advance queue tail index */ - handle->tail = nextTcd; - EnableGlobalIRQ(primask); - /* Calculate index of previous TCD */ - previousTcd = currentTcd ? currentTcd - 1U : handle->tcdSize - 1U; - /* Configure current TCD block. */ - EDMA_TcdReset(&handle->tcdPool[currentTcd]); - EDMA_TcdSetTransferConfig(&handle->tcdPool[currentTcd], config, NULL); - /* Enable major interrupt */ - handle->tcdPool[currentTcd].CSR |= DMA_CSR_INTMAJOR_MASK; - /* Link current TCD with next TCD for identification of current TCD */ - handle->tcdPool[currentTcd].DLAST_SGA = (uint32_t)&handle->tcdPool[nextTcd]; - /* Chain from previous descriptor unless tcd pool size is 1(this descriptor is its own predecessor). */ - if (currentTcd != previousTcd) - { - /* Enable scatter/gather feature in the previous TCD block. */ - csr = (handle->tcdPool[previousTcd].CSR | DMA_CSR_ESG_MASK) & ~DMA_CSR_DREQ_MASK; - handle->tcdPool[previousTcd].CSR = csr; - /* - Check if the TCD blcok in the registers is the previous one (points to current TCD block). It - is used to check if the previous TCD linked has been loaded in TCD register. If so, it need to - link the TCD register in case link the current TCD with the dead chain when TCD loading occurs - before link the previous TCD block. - */ - if (tcdRegs->DLAST_SGA == (uint32_t)&handle->tcdPool[currentTcd]) - { - /* Enable scatter/gather also in the TCD registers. */ - csr = (tcdRegs->CSR | DMA_CSR_ESG_MASK) & ~DMA_CSR_DREQ_MASK; - /* Must write the CSR register one-time, because the transfer maybe finished anytime. */ - tcdRegs->CSR = csr; - /* - It is very important to check the ESG bit! - Because this hardware design: if DONE bit is set, the ESG bit can not be set. So it can - be used to check if the dynamic TCD link operation is successful. If ESG bit is not set - and the DLAST_SGA is not the next TCD address(it means the dynamic TCD link succeed and - the current TCD block has been loaded into TCD registers), it means transfer finished - and TCD link operation fail, so must install TCD content into TCD registers and enable - transfer again. And if ESG is set, it means transfer has notfinished, so TCD dynamic - link succeed. - */ - if (tcdRegs->CSR & DMA_CSR_ESG_MASK) - { - return kStatus_Success; - } - /* - Check whether the current TCD block is already loaded in the TCD registers. It is another - condition when ESG bit is not set: it means the dynamic TCD link succeed and the current - TCD block has been loaded into TCD registers. - */ - if (tcdRegs->DLAST_SGA == (uint32_t)&handle->tcdPool[nextTcd]) - { - return kStatus_Success; - } - /* - If go to this, means the previous transfer finished, and the DONE bit is set. - So shall configure TCD registers. - */ - } - else if (tcdRegs->DLAST_SGA != 0) - { - /* The current TCD block has been linked successfully. */ - return kStatus_Success; - } - else - { - /* - DLAST_SGA is 0 and it means the first submit transfer, so shall configure - TCD registers. - */ - } - } - /* There is no live chain, TCD block need to be installed in TCD registers. */ - EDMA_InstallTCD(handle->base, handle->channel, &handle->tcdPool[currentTcd]); - /* Enable channel request again. */ - if (handle->flags & EDMA_TRANSFER_ENABLED_MASK) - { - handle->base->SERQ = DMA_SERQ_SERQ(handle->channel); - } - - return kStatus_Success; - } -} - -void EDMA_StartTransfer(edma_handle_t *handle) -{ - assert(handle != NULL); - - if (handle->tcdPool == NULL) - { - handle->base->SERQ = DMA_SERQ_SERQ(handle->channel); - } - else /* Use the TCD queue. */ - { - uint32_t primask; - edma_tcd_t *tcdRegs = (edma_tcd_t *)&handle->base->TCD[handle->channel]; - - handle->flags |= EDMA_TRANSFER_ENABLED_MASK; - - /* Check if there was at least one descriptor submitted since reset (TCD in registers is valid) */ - if (tcdRegs->DLAST_SGA != 0U) - { - primask = DisableGlobalIRQ(); - /* Check if channel request is actually disable. */ - if ((handle->base->ERQ & (1U << handle->channel)) == 0U) - { - /* Check if transfer is paused. */ - if ((!(tcdRegs->CSR & DMA_CSR_DONE_MASK)) || (tcdRegs->CSR & DMA_CSR_ESG_MASK)) - { - /* - Re-enable channel request must be as soon as possible, so must put it into - critical section to avoid task switching or interrupt service routine. - */ - handle->base->SERQ = DMA_SERQ_SERQ(handle->channel); - } - } - EnableGlobalIRQ(primask); - } - } -} - -void EDMA_StopTransfer(edma_handle_t *handle) -{ - assert(handle != NULL); - - handle->flags &= (~EDMA_TRANSFER_ENABLED_MASK); - handle->base->CERQ = DMA_CERQ_CERQ(handle->channel); -} - -void EDMA_AbortTransfer(edma_handle_t *handle) -{ - handle->base->CERQ = DMA_CERQ_CERQ(handle->channel); - /* - Clear CSR to release channel. Because if the given channel started transfer, - CSR will be not zero. Because if it is the last transfer, DREQ will be set. - If not, ESG will be set. - */ - handle->base->TCD[handle->channel].CSR = 0; - /* Cancel all next TCD transfer. */ - handle->base->TCD[handle->channel].DLAST_SGA = 0; -} - -void EDMA_HandleIRQ(edma_handle_t *handle) -{ - assert(handle != NULL); - - /* Clear EDMA interrupt flag */ - handle->base->CINT = handle->channel; - if ((handle->tcdPool == NULL) && (handle->callback != NULL)) - { - (handle->callback)(handle, handle->userData, true, 0); - } - else /* Use the TCD queue. Please refer to the API descriptions in the eDMA header file for detailed information. */ - { - uint32_t sga = handle->base->TCD[handle->channel].DLAST_SGA; - uint32_t sga_index; - int32_t tcds_done; - uint8_t new_header; - bool transfer_done; - - /* Check if transfer is already finished. */ - transfer_done = ((handle->base->TCD[handle->channel].CSR & DMA_CSR_DONE_MASK) != 0); - /* Get the offset of the next transfer TCD blcoks to be loaded into the eDMA engine. */ - sga -= (uint32_t)handle->tcdPool; - /* Get the index of the next transfer TCD blcoks to be loaded into the eDMA engine. */ - sga_index = sga / sizeof(edma_tcd_t); - /* Adjust header positions. */ - if (transfer_done) - { - /* New header shall point to the next TCD to be loaded (current one is already finished) */ - new_header = sga_index; - } - else - { - /* New header shall point to this descriptor currently loaded (not finished yet) */ - new_header = sga_index ? sga_index - 1U : handle->tcdSize - 1U; - } - /* Calculate the number of finished TCDs */ - if (new_header == handle->header) - { - if (handle->tcdUsed == handle->tcdSize) - { - tcds_done = handle->tcdUsed; - } - else - { - /* No TCD in the memory are going to be loaded or internal error occurs. */ - tcds_done = 0; - } - } - else - { - tcds_done = new_header - handle->header; - if (tcds_done < 0) - { - tcds_done += handle->tcdSize; - } - } - /* Advance header which points to the TCD to be loaded into the eDMA engine from memory. */ - handle->header = new_header; - /* Release TCD blocks. tcdUsed is the TCD number which can be used/loaded in the memory pool. */ - handle->tcdUsed -= tcds_done; - /* Invoke callback function. */ - if (handle->callback) - { - (handle->callback)(handle, handle->userData, transfer_done, tcds_done); - } - } -} - -/* 8 channels (Shared): kl28 */ -#if defined(FSL_FEATURE_EDMA_MODULE_CHANNEL) && FSL_FEATURE_EDMA_MODULE_CHANNEL == 8U - -void DMA0_04_DriverIRQHandler(void) -{ - if ((EDMA_GetChannelStatusFlags(DMA0, 0U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[0]); - } - if ((EDMA_GetChannelStatusFlags(DMA0, 4U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[4]); - } -} - -void DMA0_15_DriverIRQHandler(void) -{ - if ((EDMA_GetChannelStatusFlags(DMA0, 1U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[1]); - } - if ((EDMA_GetChannelStatusFlags(DMA0, 5U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[5]); - } -} - -void DMA0_26_DriverIRQHandler(void) -{ - if ((EDMA_GetChannelStatusFlags(DMA0, 2U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[2]); - } - if ((EDMA_GetChannelStatusFlags(DMA0, 6U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[6]); - } -} - -void DMA0_37_DriverIRQHandler(void) -{ - if ((EDMA_GetChannelStatusFlags(DMA0, 3U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[3]); - } - if ((EDMA_GetChannelStatusFlags(DMA0, 7U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[7]); - } -} - -#if defined(DMA1) -void DMA1_04_DriverIRQHandler(void) -{ - if ((EDMA_GetChannelStatusFlags(DMA1, 0U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[8]); - } - if ((EDMA_GetChannelStatusFlags(DMA1, 4U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[12]); - } -} - -void DMA1_15_DriverIRQHandler(void) -{ - if ((EDMA_GetChannelStatusFlags(DMA1, 1U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[9]); - } - if ((EDMA_GetChannelStatusFlags(DMA1, 5U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[13]); - } -} - -void DMA1_26_DriverIRQHandler(void) -{ - if ((EDMA_GetChannelStatusFlags(DMA1, 2U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[10]); - } - if ((EDMA_GetChannelStatusFlags(DMA1, 6U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[14]); - } -} - -void DMA1_37_DriverIRQHandler(void) -{ - if ((EDMA_GetChannelStatusFlags(DMA1, 3U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[11]); - } - if ((EDMA_GetChannelStatusFlags(DMA1, 7U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[15]); - } -} -#endif -#endif /* 8 channels (Shared) */ - -/* 16 channels (Shared): K32H844P */ -#if defined(FSL_FEATURE_EDMA_MODULE_CHANNEL) && FSL_FEATURE_EDMA_MODULE_CHANNEL == 16U - -void DMA0_08_DriverIRQHandler(void) -{ - if ((EDMA_GetChannelStatusFlags(DMA0, 0U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[0]); - } - if ((EDMA_GetChannelStatusFlags(DMA0, 8U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[8]); - } -} - -void DMA0_19_DriverIRQHandler(void) -{ - if ((EDMA_GetChannelStatusFlags(DMA0, 1U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[1]); - } - if ((EDMA_GetChannelStatusFlags(DMA0, 9U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[9]); - } -} - -void DMA0_210_DriverIRQHandler(void) -{ - if ((EDMA_GetChannelStatusFlags(DMA0, 2U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[2]); - } - if ((EDMA_GetChannelStatusFlags(DMA0, 10U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[10]); - } -} - -void DMA0_311_DriverIRQHandler(void) -{ - if ((EDMA_GetChannelStatusFlags(DMA0, 3U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[3]); - } - if ((EDMA_GetChannelStatusFlags(DMA0, 11U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[11]); - } -} - -void DMA0_412_DriverIRQHandler(void) -{ - if ((EDMA_GetChannelStatusFlags(DMA0, 4U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[4]); - } - if ((EDMA_GetChannelStatusFlags(DMA0, 12U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[12]); - } -} - -void DMA0_513_DriverIRQHandler(void) -{ - if ((EDMA_GetChannelStatusFlags(DMA0, 5U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[5]); - } - if ((EDMA_GetChannelStatusFlags(DMA0, 13U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[13]); - } -} - -void DMA0_614_DriverIRQHandler(void) -{ - if ((EDMA_GetChannelStatusFlags(DMA0, 6U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[6]); - } - if ((EDMA_GetChannelStatusFlags(DMA0, 14U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[14]); - } -} - -void DMA0_715_DriverIRQHandler(void) -{ - if ((EDMA_GetChannelStatusFlags(DMA0, 7U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[7]); - } - if ((EDMA_GetChannelStatusFlags(DMA0, 15U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[15]); - } -} - -#if defined(DMA1) -void DMA1_08_DriverIRQHandler(void) -{ - if ((EDMA_GetChannelStatusFlags(DMA1, 0U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[16]); - } - if ((EDMA_GetChannelStatusFlags(DMA1, 8U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[24]); - } -} - -void DMA1_19_DriverIRQHandler(void) -{ - if ((EDMA_GetChannelStatusFlags(DMA1, 1U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[17]); - } - if ((EDMA_GetChannelStatusFlags(DMA1, 9U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[25]); - } -} - -void DMA1_210_DriverIRQHandler(void) -{ - if ((EDMA_GetChannelStatusFlags(DMA1, 2U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[18]); - } - if ((EDMA_GetChannelStatusFlags(DMA1, 10U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[26]); - } -} - -void DMA1_311_DriverIRQHandler(void) -{ - if ((EDMA_GetChannelStatusFlags(DMA1, 3U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[19]); - } - if ((EDMA_GetChannelStatusFlags(DMA1, 11U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[27]); - } -} - -void DMA1_412_DriverIRQHandler(void) -{ - if ((EDMA_GetChannelStatusFlags(DMA1, 4U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[20]); - } - if ((EDMA_GetChannelStatusFlags(DMA1, 12U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[28]); - } -} - -void DMA1_513_DriverIRQHandler(void) -{ - if ((EDMA_GetChannelStatusFlags(DMA1, 5U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[21]); - } - if ((EDMA_GetChannelStatusFlags(DMA1, 13U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[29]); - } -} - -void DMA1_614_DriverIRQHandler(void) -{ - if ((EDMA_GetChannelStatusFlags(DMA1, 6U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[22]); - } - if ((EDMA_GetChannelStatusFlags(DMA1, 14U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[30]); - } -} - -void DMA1_715_DriverIRQHandler(void) -{ - if ((EDMA_GetChannelStatusFlags(DMA1, 7U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[23]); - } - if ((EDMA_GetChannelStatusFlags(DMA1, 15U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[31]); - } -} -#endif -#endif /* 16 channels (Shared) */ - -/* 32 channels (Shared): k80 */ -#if defined(FSL_FEATURE_EDMA_MODULE_CHANNEL) && FSL_FEATURE_EDMA_MODULE_CHANNEL == 32U - -void DMA0_DMA16_DriverIRQHandler(void) -{ - if ((EDMA_GetChannelStatusFlags(DMA0, 0U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[0]); - } - if ((EDMA_GetChannelStatusFlags(DMA0, 16U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[16]); - } -} - -void DMA1_DMA17_DriverIRQHandler(void) -{ - if ((EDMA_GetChannelStatusFlags(DMA0, 1U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[1]); - } - if ((EDMA_GetChannelStatusFlags(DMA0, 17U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[17]); - } -} - -void DMA2_DMA18_DriverIRQHandler(void) -{ - if ((EDMA_GetChannelStatusFlags(DMA0, 2U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[2]); - } - if ((EDMA_GetChannelStatusFlags(DMA0, 18U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[18]); - } -} - -void DMA3_DMA19_DriverIRQHandler(void) -{ - if ((EDMA_GetChannelStatusFlags(DMA0, 3U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[3]); - } - if ((EDMA_GetChannelStatusFlags(DMA0, 19U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[19]); - } -} - -void DMA4_DMA20_DriverIRQHandler(void) -{ - if ((EDMA_GetChannelStatusFlags(DMA0, 4U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[4]); - } - if ((EDMA_GetChannelStatusFlags(DMA0, 20U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[20]); - } -} - -void DMA5_DMA21_DriverIRQHandler(void) -{ - if ((EDMA_GetChannelStatusFlags(DMA0, 5U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[5]); - } - if ((EDMA_GetChannelStatusFlags(DMA0, 21U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[21]); - } -} - -void DMA6_DMA22_DriverIRQHandler(void) -{ - if ((EDMA_GetChannelStatusFlags(DMA0, 6U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[6]); - } - if ((EDMA_GetChannelStatusFlags(DMA0, 22U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[22]); - } -} - -void DMA7_DMA23_DriverIRQHandler(void) -{ - if ((EDMA_GetChannelStatusFlags(DMA0, 7U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[7]); - } - if ((EDMA_GetChannelStatusFlags(DMA0, 23U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[23]); - } -} - -void DMA8_DMA24_DriverIRQHandler(void) -{ - if ((EDMA_GetChannelStatusFlags(DMA0, 8U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[8]); - } - if ((EDMA_GetChannelStatusFlags(DMA0, 24U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[24]); - } -} - -void DMA9_DMA25_DriverIRQHandler(void) -{ - if ((EDMA_GetChannelStatusFlags(DMA0, 9U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[9]); - } - if ((EDMA_GetChannelStatusFlags(DMA0, 25U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[25]); - } -} - -void DMA10_DMA26_DriverIRQHandler(void) -{ - if ((EDMA_GetChannelStatusFlags(DMA0, 10U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[10]); - } - if ((EDMA_GetChannelStatusFlags(DMA0, 26U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[26]); - } -} - -void DMA11_DMA27_DriverIRQHandler(void) -{ - if ((EDMA_GetChannelStatusFlags(DMA0, 11U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[11]); - } - if ((EDMA_GetChannelStatusFlags(DMA0, 27U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[27]); - } -} - -void DMA12_DMA28_DriverIRQHandler(void) -{ - if ((EDMA_GetChannelStatusFlags(DMA0, 12U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[12]); - } - if ((EDMA_GetChannelStatusFlags(DMA0, 28U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[28]); - } -} - -void DMA13_DMA29_DriverIRQHandler(void) -{ - if ((EDMA_GetChannelStatusFlags(DMA0, 13U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[13]); - } - if ((EDMA_GetChannelStatusFlags(DMA0, 29U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[29]); - } -} - -void DMA14_DMA30_DriverIRQHandler(void) -{ - if ((EDMA_GetChannelStatusFlags(DMA0, 14U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[14]); - } - if ((EDMA_GetChannelStatusFlags(DMA0, 30U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[30]); - } -} - -void DMA15_DMA31_DriverIRQHandler(void) -{ - if ((EDMA_GetChannelStatusFlags(DMA0, 15U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[15]); - } - if ((EDMA_GetChannelStatusFlags(DMA0, 31U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[31]); - } -} -#endif /* 32 channels (Shared) */ - -/* 32 channels (Shared): MCIMX7U5_M4 */ -#if defined(FSL_FEATURE_EDMA_MODULE_CHANNEL) && FSL_FEATURE_EDMA_MODULE_CHANNEL == 32U - -void DMA0_0_4_DriverIRQHandler(void) -{ - if ((EDMA_GetChannelStatusFlags(DMA0, 0U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[0]); - } - if ((EDMA_GetChannelStatusFlags(DMA0, 4U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[4]); - } -} - -void DMA0_1_5_DriverIRQHandler(void) -{ - if ((EDMA_GetChannelStatusFlags(DMA0, 1U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[1]); - } - if ((EDMA_GetChannelStatusFlags(DMA0, 5U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[5]); - } -} - -void DMA0_2_6_DriverIRQHandler(void) -{ - if ((EDMA_GetChannelStatusFlags(DMA0, 2U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[2]); - } - if ((EDMA_GetChannelStatusFlags(DMA0, 6U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[6]); - } -} - -void DMA0_3_7_DriverIRQHandler(void) -{ - if ((EDMA_GetChannelStatusFlags(DMA0, 3U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[3]); - } - if ((EDMA_GetChannelStatusFlags(DMA0, 7U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[7]); - } -} - -void DMA0_8_12_DriverIRQHandler(void) -{ - if ((EDMA_GetChannelStatusFlags(DMA0, 8U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[8]); - } - if ((EDMA_GetChannelStatusFlags(DMA0, 12U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[12]); - } -} - -void DMA0_9_13_DriverIRQHandler(void) -{ - if ((EDMA_GetChannelStatusFlags(DMA0, 9U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[9]); - } - if ((EDMA_GetChannelStatusFlags(DMA0, 13U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[13]); - } -} - -void DMA0_10_14_DriverIRQHandler(void) -{ - if ((EDMA_GetChannelStatusFlags(DMA0, 10U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[10]); - } - if ((EDMA_GetChannelStatusFlags(DMA0, 14U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[14]); - } -} - -void DMA0_11_15_DriverIRQHandler(void) -{ - if ((EDMA_GetChannelStatusFlags(DMA0, 11U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[11]); - } - if ((EDMA_GetChannelStatusFlags(DMA0, 15U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[15]); - } -} - -void DMA0_16_20_DriverIRQHandler(void) -{ - if ((EDMA_GetChannelStatusFlags(DMA0, 16U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[16]); - } - if ((EDMA_GetChannelStatusFlags(DMA0, 20U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[20]); - } -} - -void DMA0_17_21_DriverIRQHandler(void) -{ - if ((EDMA_GetChannelStatusFlags(DMA0, 17U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[17]); - } - if ((EDMA_GetChannelStatusFlags(DMA0, 21U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[21]); - } -} - -void DMA0_18_22_DriverIRQHandler(void) -{ - if ((EDMA_GetChannelStatusFlags(DMA0, 18U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[18]); - } - if ((EDMA_GetChannelStatusFlags(DMA0, 22U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[22]); - } -} - -void DMA0_19_23_DriverIRQHandler(void) -{ - if ((EDMA_GetChannelStatusFlags(DMA0, 19U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[19]); - } - if ((EDMA_GetChannelStatusFlags(DMA0, 23U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[23]); - } -} - -void DMA0_24_28_DriverIRQHandler(void) -{ - if ((EDMA_GetChannelStatusFlags(DMA0, 24U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[24]); - } - if ((EDMA_GetChannelStatusFlags(DMA0, 28U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[28]); - } -} - -void DMA0_25_29_DriverIRQHandler(void) -{ - if ((EDMA_GetChannelStatusFlags(DMA0, 25U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[25]); - } - if ((EDMA_GetChannelStatusFlags(DMA0, 29U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[29]); - } -} - -void DMA0_26_30_DriverIRQHandler(void) -{ - if ((EDMA_GetChannelStatusFlags(DMA0, 26U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[26]); - } - if ((EDMA_GetChannelStatusFlags(DMA0, 30U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[30]); - } -} - -void DMA0_27_31_DriverIRQHandler(void) -{ - if ((EDMA_GetChannelStatusFlags(DMA0, 27U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[27]); - } - if ((EDMA_GetChannelStatusFlags(DMA0, 31U) & kEDMA_InterruptFlag) != 0U) - { - EDMA_HandleIRQ(s_EDMAHandle[31]); - } -} -#endif /* 32 channels (Shared): MCIMX7U5 */ - -/* 4 channels (No Shared): kv10 */ -#if defined(FSL_FEATURE_EDMA_MODULE_CHANNEL) && FSL_FEATURE_EDMA_MODULE_CHANNEL > 0 - -void DMA0_DriverIRQHandler(void) -{ - EDMA_HandleIRQ(s_EDMAHandle[0]); -} - -void DMA1_DriverIRQHandler(void) -{ - EDMA_HandleIRQ(s_EDMAHandle[1]); -} - -void DMA2_DriverIRQHandler(void) -{ - EDMA_HandleIRQ(s_EDMAHandle[2]); -} - -void DMA3_DriverIRQHandler(void) -{ - EDMA_HandleIRQ(s_EDMAHandle[3]); -} - -/* 8 channels (No Shared) */ -#if defined(FSL_FEATURE_EDMA_MODULE_CHANNEL) && FSL_FEATURE_EDMA_MODULE_CHANNEL > 4U - -void DMA4_DriverIRQHandler(void) -{ - EDMA_HandleIRQ(s_EDMAHandle[4]); -} - -void DMA5_DriverIRQHandler(void) -{ - EDMA_HandleIRQ(s_EDMAHandle[5]); -} - -void DMA6_DriverIRQHandler(void) -{ - EDMA_HandleIRQ(s_EDMAHandle[6]); -} - -void DMA7_DriverIRQHandler(void) -{ - EDMA_HandleIRQ(s_EDMAHandle[7]); -} -#endif /* FSL_FEATURE_EDMA_MODULE_CHANNEL == 8 */ - -/* 16 channels (No Shared) */ -#if defined(FSL_FEATURE_EDMA_MODULE_CHANNEL) && FSL_FEATURE_EDMA_MODULE_CHANNEL > 8U - -void DMA8_DriverIRQHandler(void) -{ - EDMA_HandleIRQ(s_EDMAHandle[8]); -} - -void DMA9_DriverIRQHandler(void) -{ - EDMA_HandleIRQ(s_EDMAHandle[9]); -} - -void DMA10_DriverIRQHandler(void) -{ - EDMA_HandleIRQ(s_EDMAHandle[10]); -} - -void DMA11_DriverIRQHandler(void) -{ - EDMA_HandleIRQ(s_EDMAHandle[11]); -} - -void DMA12_DriverIRQHandler(void) -{ - EDMA_HandleIRQ(s_EDMAHandle[12]); -} - -void DMA13_DriverIRQHandler(void) -{ - EDMA_HandleIRQ(s_EDMAHandle[13]); -} - -void DMA14_DriverIRQHandler(void) -{ - EDMA_HandleIRQ(s_EDMAHandle[14]); -} - -void DMA15_DriverIRQHandler(void) -{ - EDMA_HandleIRQ(s_EDMAHandle[15]); -} -#endif /* FSL_FEATURE_EDMA_MODULE_CHANNEL == 16 */ - -/* 32 channels (No Shared) */ -#if defined(FSL_FEATURE_EDMA_MODULE_CHANNEL) && FSL_FEATURE_EDMA_MODULE_CHANNEL > 16U - -void DMA16_DriverIRQHandler(void) -{ - EDMA_HandleIRQ(s_EDMAHandle[16]); -} - -void DMA17_DriverIRQHandler(void) -{ - EDMA_HandleIRQ(s_EDMAHandle[17]); -} - -void DMA18_DriverIRQHandler(void) -{ - EDMA_HandleIRQ(s_EDMAHandle[18]); -} - -void DMA19_DriverIRQHandler(void) -{ - EDMA_HandleIRQ(s_EDMAHandle[19]); -} - -void DMA20_DriverIRQHandler(void) -{ - EDMA_HandleIRQ(s_EDMAHandle[20]); -} - -void DMA21_DriverIRQHandler(void) -{ - EDMA_HandleIRQ(s_EDMAHandle[21]); -} - -void DMA22_DriverIRQHandler(void) -{ - EDMA_HandleIRQ(s_EDMAHandle[22]); -} - -void DMA23_DriverIRQHandler(void) -{ - EDMA_HandleIRQ(s_EDMAHandle[23]); -} - -void DMA24_DriverIRQHandler(void) -{ - EDMA_HandleIRQ(s_EDMAHandle[24]); -} - -void DMA25_DriverIRQHandler(void) -{ - EDMA_HandleIRQ(s_EDMAHandle[25]); -} - -void DMA26_DriverIRQHandler(void) -{ - EDMA_HandleIRQ(s_EDMAHandle[26]); -} - -void DMA27_DriverIRQHandler(void) -{ - EDMA_HandleIRQ(s_EDMAHandle[27]); -} - -void DMA28_DriverIRQHandler(void) -{ - EDMA_HandleIRQ(s_EDMAHandle[28]); -} - -void DMA29_DriverIRQHandler(void) -{ - EDMA_HandleIRQ(s_EDMAHandle[29]); -} - -void DMA30_DriverIRQHandler(void) -{ - EDMA_HandleIRQ(s_EDMAHandle[30]); -} - -void DMA31_DriverIRQHandler(void) -{ - EDMA_HandleIRQ(s_EDMAHandle[31]); -} -#endif /* FSL_FEATURE_EDMA_MODULE_CHANNEL == 32 */ - -#endif /* 4/8/16/32 channels (No Shared) */ diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_edma.h b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_edma.h deleted file mode 100644 index a97622d7e1e..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_edma.h +++ /dev/null @@ -1,910 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef _FSL_EDMA_H_ -#define _FSL_EDMA_H_ - -#include "fsl_common.h" - -/*! - * @addtogroup edma - * @{ - */ - -/******************************************************************************* - * Definitions - ******************************************************************************/ - -/*! @name Driver version */ -/*@{*/ -/*! @brief eDMA driver version */ -#define FSL_EDMA_DRIVER_VERSION (MAKE_VERSION(2, 1, 1)) /*!< Version 2.1.1. */ -/*@}*/ - -/*! @brief Compute the offset unit from DCHPRI3 */ -#define DMA_DCHPRI_INDEX(channel) (((channel) & ~0x03U) | (3 - ((channel)&0x03U))) - -/*! @brief Get the pointer of DCHPRIn */ -#define DMA_DCHPRIn(base, channel) ((volatile uint8_t *)&(base->DCHPRI3))[DMA_DCHPRI_INDEX(channel)] - -/*! @brief eDMA transfer configuration */ -typedef enum _edma_transfer_size -{ - kEDMA_TransferSize1Bytes = 0x0U, /*!< Source/Destination data transfer size is 1 byte every time */ - kEDMA_TransferSize2Bytes = 0x1U, /*!< Source/Destination data transfer size is 2 bytes every time */ - kEDMA_TransferSize4Bytes = 0x2U, /*!< Source/Destination data transfer size is 4 bytes every time */ - kEDMA_TransferSize16Bytes = 0x4U, /*!< Source/Destination data transfer size is 16 bytes every time */ - kEDMA_TransferSize32Bytes = 0x5U, /*!< Source/Destination data transfer size is 32 bytes every time */ -} edma_transfer_size_t; - -/*! @brief eDMA modulo configuration */ -typedef enum _edma_modulo -{ - kEDMA_ModuloDisable = 0x0U, /*!< Disable modulo */ - kEDMA_Modulo2bytes, /*!< Circular buffer size is 2 bytes. */ - kEDMA_Modulo4bytes, /*!< Circular buffer size is 4 bytes. */ - kEDMA_Modulo8bytes, /*!< Circular buffer size is 8 bytes. */ - kEDMA_Modulo16bytes, /*!< Circular buffer size is 16 bytes. */ - kEDMA_Modulo32bytes, /*!< Circular buffer size is 32 bytes. */ - kEDMA_Modulo64bytes, /*!< Circular buffer size is 64 bytes. */ - kEDMA_Modulo128bytes, /*!< Circular buffer size is 128 bytes. */ - kEDMA_Modulo256bytes, /*!< Circular buffer size is 256 bytes. */ - kEDMA_Modulo512bytes, /*!< Circular buffer size is 512 bytes. */ - kEDMA_Modulo1Kbytes, /*!< Circular buffer size is 1 K bytes. */ - kEDMA_Modulo2Kbytes, /*!< Circular buffer size is 2 K bytes. */ - kEDMA_Modulo4Kbytes, /*!< Circular buffer size is 4 K bytes. */ - kEDMA_Modulo8Kbytes, /*!< Circular buffer size is 8 K bytes. */ - kEDMA_Modulo16Kbytes, /*!< Circular buffer size is 16 K bytes. */ - kEDMA_Modulo32Kbytes, /*!< Circular buffer size is 32 K bytes. */ - kEDMA_Modulo64Kbytes, /*!< Circular buffer size is 64 K bytes. */ - kEDMA_Modulo128Kbytes, /*!< Circular buffer size is 128 K bytes. */ - kEDMA_Modulo256Kbytes, /*!< Circular buffer size is 256 K bytes. */ - kEDMA_Modulo512Kbytes, /*!< Circular buffer size is 512 K bytes. */ - kEDMA_Modulo1Mbytes, /*!< Circular buffer size is 1 M bytes. */ - kEDMA_Modulo2Mbytes, /*!< Circular buffer size is 2 M bytes. */ - kEDMA_Modulo4Mbytes, /*!< Circular buffer size is 4 M bytes. */ - kEDMA_Modulo8Mbytes, /*!< Circular buffer size is 8 M bytes. */ - kEDMA_Modulo16Mbytes, /*!< Circular buffer size is 16 M bytes. */ - kEDMA_Modulo32Mbytes, /*!< Circular buffer size is 32 M bytes. */ - kEDMA_Modulo64Mbytes, /*!< Circular buffer size is 64 M bytes. */ - kEDMA_Modulo128Mbytes, /*!< Circular buffer size is 128 M bytes. */ - kEDMA_Modulo256Mbytes, /*!< Circular buffer size is 256 M bytes. */ - kEDMA_Modulo512Mbytes, /*!< Circular buffer size is 512 M bytes. */ - kEDMA_Modulo1Gbytes, /*!< Circular buffer size is 1 G bytes. */ - kEDMA_Modulo2Gbytes, /*!< Circular buffer size is 2 G bytes. */ -} edma_modulo_t; - -/*! @brief Bandwidth control */ -typedef enum _edma_bandwidth -{ - kEDMA_BandwidthStallNone = 0x0U, /*!< No eDMA engine stalls. */ - kEDMA_BandwidthStall4Cycle = 0x2U, /*!< eDMA engine stalls for 4 cycles after each read/write. */ - kEDMA_BandwidthStall8Cycle = 0x3U, /*!< eDMA engine stalls for 8 cycles after each read/write. */ -} edma_bandwidth_t; - -/*! @brief Channel link type */ -typedef enum _edma_channel_link_type -{ - kEDMA_LinkNone = 0x0U, /*!< No channel link */ - kEDMA_MinorLink, /*!< Channel link after each minor loop */ - kEDMA_MajorLink, /*!< Channel link while major loop count exhausted */ -} edma_channel_link_type_t; - -/*!@brief eDMA channel status flags. */ -enum _edma_channel_status_flags -{ - kEDMA_DoneFlag = 0x1U, /*!< DONE flag, set while transfer finished, CITER value exhausted*/ - kEDMA_ErrorFlag = 0x2U, /*!< eDMA error flag, an error occurred in a transfer */ - kEDMA_InterruptFlag = 0x4U, /*!< eDMA interrupt flag, set while an interrupt occurred of this channel */ -}; - -/*! @brief eDMA channel error status flags. */ -enum _edma_error_status_flags -{ - kEDMA_DestinationBusErrorFlag = DMA_ES_DBE_MASK, /*!< Bus error on destination address */ - kEDMA_SourceBusErrorFlag = DMA_ES_SBE_MASK, /*!< Bus error on the source address */ - kEDMA_ScatterGatherErrorFlag = DMA_ES_SGE_MASK, /*!< Error on the Scatter/Gather address, not 32byte aligned. */ - kEDMA_NbytesErrorFlag = DMA_ES_NCE_MASK, /*!< NBYTES/CITER configuration error */ - kEDMA_DestinationOffsetErrorFlag = DMA_ES_DOE_MASK, /*!< Destination offset not aligned with destination size */ - kEDMA_DestinationAddressErrorFlag = DMA_ES_DAE_MASK, /*!< Destination address not aligned with destination size */ - kEDMA_SourceOffsetErrorFlag = DMA_ES_SOE_MASK, /*!< Source offset not aligned with source size */ - kEDMA_SourceAddressErrorFlag = DMA_ES_SAE_MASK, /*!< Source address not aligned with source size*/ - kEDMA_ErrorChannelFlag = DMA_ES_ERRCHN_MASK, /*!< Error channel number of the cancelled channel number */ - kEDMA_ChannelPriorityErrorFlag = DMA_ES_CPE_MASK, /*!< Channel priority is not unique. */ - kEDMA_TransferCanceledFlag = DMA_ES_ECX_MASK, /*!< Transfer cancelled */ -#if defined(FSL_FEATURE_EDMA_CHANNEL_GROUP_COUNT) && FSL_FEATURE_EDMA_CHANNEL_GROUP_COUNT > 1 - kEDMA_GroupPriorityErrorFlag = DMA_ES_GPE_MASK, /*!< Group priority is not unique. */ -#endif - kEDMA_ValidFlag = DMA_ES_VLD_MASK, /*!< No error occurred, this bit is 0. Otherwise, it is 1. */ -}; - -/*! @brief eDMA interrupt source */ -typedef enum _edma_interrupt_enable -{ - kEDMA_ErrorInterruptEnable = 0x1U, /*!< Enable interrupt while channel error occurs. */ - kEDMA_MajorInterruptEnable = DMA_CSR_INTMAJOR_MASK, /*!< Enable interrupt while major count exhausted. */ - kEDMA_HalfInterruptEnable = DMA_CSR_INTHALF_MASK, /*!< Enable interrupt while major count to half value. */ -} edma_interrupt_enable_t; - -/*! @brief eDMA transfer type */ -typedef enum _edma_transfer_type -{ - kEDMA_MemoryToMemory = 0x0U, /*!< Transfer from memory to memory */ - kEDMA_PeripheralToMemory, /*!< Transfer from peripheral to memory */ - kEDMA_MemoryToPeripheral, /*!< Transfer from memory to peripheral */ -} edma_transfer_type_t; - -/*! @brief eDMA transfer status */ -enum _edma_transfer_status -{ - kStatus_EDMA_QueueFull = MAKE_STATUS(kStatusGroup_EDMA, 0), /*!< TCD queue is full. */ - kStatus_EDMA_Busy = MAKE_STATUS(kStatusGroup_EDMA, 1), /*!< Channel is busy and can't handle the - transfer request. */ -}; - -/*! @brief eDMA global configuration structure.*/ -typedef struct _edma_config -{ - bool enableContinuousLinkMode; /*!< Enable (true) continuous link mode. Upon minor loop completion, the channel - activates again if that channel has a minor loop channel link enabled and - the link channel is itself. */ - bool enableHaltOnError; /*!< Enable (true) transfer halt on error. Any error causes the HALT bit to set. - Subsequently, all service requests are ignored until the HALT bit is cleared.*/ - bool enableRoundRobinArbitration; /*!< Enable (true) round robin channel arbitration method or fixed priority - arbitration is used for channel selection */ - bool enableDebugMode; /*!< Enable(true) eDMA debug mode. When in debug mode, the eDMA stalls the start of - a new channel. Executing channels are allowed to complete. */ -} edma_config_t; - -/*! - * @brief eDMA transfer configuration - * - * This structure configures the source/destination transfer attribute. - * This figure shows the eDMA's transfer model: - * _________________________________________________ - * | Transfer Size | | - * Minor Loop |_______________| Major loop Count 1 | - * Bytes | Transfer Size | | - * ____________|_______________|____________________|--> Minor loop complete - * ____________________________________ - * | | | - * |_______________| Major Loop Count 2 | - * | | | - * |_______________|____________________|--> Minor loop Complete - * - * ---------------------------------------------------------> Transfer complete - */ -typedef struct _edma_transfer_config -{ - uint32_t srcAddr; /*!< Source data address. */ - uint32_t destAddr; /*!< Destination data address. */ - edma_transfer_size_t srcTransferSize; /*!< Source data transfer size. */ - edma_transfer_size_t destTransferSize; /*!< Destination data transfer size. */ - int16_t srcOffset; /*!< Sign-extended offset applied to the current source address to - form the next-state value as each source read is completed. */ - int16_t destOffset; /*!< Sign-extended offset applied to the current destination address to - form the next-state value as each destination write is completed. */ - uint32_t minorLoopBytes; /*!< Bytes to transfer in a minor loop*/ - uint32_t majorLoopCounts; /*!< Major loop iteration count. */ -} edma_transfer_config_t; - -/*! @brief eDMA channel priority configuration */ -typedef struct _edma_channel_Preemption_config -{ - bool enableChannelPreemption; /*!< If true: a channel can be suspended by other channel with higher priority */ - bool enablePreemptAbility; /*!< If true: a channel can suspend other channel with low priority */ - uint8_t channelPriority; /*!< Channel priority */ -} edma_channel_Preemption_config_t; - -/*! @brief eDMA minor offset configuration */ -typedef struct _edma_minor_offset_config -{ - bool enableSrcMinorOffset; /*!< Enable(true) or Disable(false) source minor loop offset. */ - bool enableDestMinorOffset; /*!< Enable(true) or Disable(false) destination minor loop offset. */ - uint32_t minorOffset; /*!< Offset for a minor loop mapping. */ -} edma_minor_offset_config_t; - -/*! - * @brief eDMA TCD. - * - * This structure is same as TCD register which is described in reference manual, - * and is used to configure the scatter/gather feature as a next hardware TCD. - */ -typedef struct _edma_tcd -{ - __IO uint32_t SADDR; /*!< SADDR register, used to save source address */ - __IO uint16_t SOFF; /*!< SOFF register, save offset bytes every transfer */ - __IO uint16_t ATTR; /*!< ATTR register, source/destination transfer size and modulo */ - __IO uint32_t NBYTES; /*!< Nbytes register, minor loop length in bytes */ - __IO uint32_t SLAST; /*!< SLAST register */ - __IO uint32_t DADDR; /*!< DADDR register, used for destination address */ - __IO uint16_t DOFF; /*!< DOFF register, used for destination offset */ - __IO uint16_t CITER; /*!< CITER register, current minor loop numbers, for unfinished minor loop.*/ - __IO uint32_t DLAST_SGA; /*!< DLASTSGA register, next stcd address used in scatter-gather mode */ - __IO uint16_t CSR; /*!< CSR register, for TCD control status */ - __IO uint16_t BITER; /*!< BITER register, begin minor loop count. */ -} edma_tcd_t; - -/*! @brief Callback for eDMA */ -struct _edma_handle; - -/*! @brief Define callback function for eDMA. */ -typedef void (*edma_callback)(struct _edma_handle *handle, void *userData, bool transferDone, uint32_t tcds); - -/*! @brief eDMA transfer handle structure */ -typedef struct _edma_handle -{ - edma_callback callback; /*!< Callback function for major count exhausted. */ - void *userData; /*!< Callback function parameter. */ - DMA_Type *base; /*!< eDMA peripheral base address. */ - edma_tcd_t *tcdPool; /*!< Pointer to memory stored TCDs. */ - uint8_t channel; /*!< eDMA channel number. */ - volatile int8_t header; /*!< The first TCD index. Should point to the next TCD to be loaded into the eDMA engine. */ - volatile int8_t tail; /*!< The last TCD index. Should point to the next TCD to be stored into the memory pool. */ - volatile int8_t tcdUsed; /*!< The number of used TCD slots. Should reflect the number of TCDs can be used/loaded in - the memory. */ - volatile int8_t tcdSize; /*!< The total number of TCD slots in the queue. */ - uint8_t flags; /*!< The status of the current channel. */ -} edma_handle_t; - -/******************************************************************************* - * APIs - ******************************************************************************/ -#if defined(__cplusplus) -extern "C" { -#endif /* __cplusplus */ - -/*! - * @name eDMA initialization and de-initialization - * @{ - */ - -/*! - * @brief Initializes the eDMA peripheral. - * - * This function ungates the eDMA clock and configures the eDMA peripheral according - * to the configuration structure. - * - * @param base eDMA peripheral base address. - * @param config A pointer to the configuration structure, see "edma_config_t". - * @note This function enables the minor loop map feature. - */ -void EDMA_Init(DMA_Type *base, const edma_config_t *config); - -/*! - * @brief Deinitializes the eDMA peripheral. - * - * This function gates the eDMA clock. - * - * @param base eDMA peripheral base address. - */ -void EDMA_Deinit(DMA_Type *base); - -/*! - * @brief Gets the eDMA default configuration structure. - * - * This function sets the configuration structure to default values. - * The default configuration is set to the following values. - * @code - * config.enableContinuousLinkMode = false; - * config.enableHaltOnError = true; - * config.enableRoundRobinArbitration = false; - * config.enableDebugMode = false; - * @endcode - * - * @param config A pointer to the eDMA configuration structure. - */ -void EDMA_GetDefaultConfig(edma_config_t *config); - -/* @} */ -/*! - * @name eDMA Channel Operation - * @{ - */ - -/*! - * @brief Sets all TCD registers to default values. - * - * This function sets TCD registers for this channel to default values. - * - * @param base eDMA peripheral base address. - * @param channel eDMA channel number. - * @note This function must not be called while the channel transfer is ongoing - * or it causes unpredictable results. - * @note This function enables the auto stop request feature. - */ -void EDMA_ResetChannel(DMA_Type *base, uint32_t channel); - -/*! - * @brief Configures the eDMA transfer attribute. - * - * This function configures the transfer attribute, including source address, destination address, - * transfer size, address offset, and so on. It also configures the scatter gather feature if the - * user supplies the TCD address. - * Example: - * @code - * edma_transfer_t config; - * edma_tcd_t tcd; - * config.srcAddr = ..; - * config.destAddr = ..; - * ... - * EDMA_SetTransferConfig(DMA0, channel, &config, &stcd); - * @endcode - * - * @param base eDMA peripheral base address. - * @param channel eDMA channel number. - * @param config Pointer to eDMA transfer configuration structure. - * @param nextTcd Point to TCD structure. It can be NULL if users - * do not want to enable scatter/gather feature. - * @note If nextTcd is not NULL, it means scatter gather feature is enabled - * and DREQ bit is cleared in the previous transfer configuration, which - * is set in the eDMA_ResetChannel. - */ -void EDMA_SetTransferConfig(DMA_Type *base, - uint32_t channel, - const edma_transfer_config_t *config, - edma_tcd_t *nextTcd); - -/*! - * @brief Configures the eDMA minor offset feature. - * - * The minor offset means that the signed-extended value is added to the source address or destination - * address after each minor loop. - * - * @param base eDMA peripheral base address. - * @param channel eDMA channel number. - * @param config A pointer to the minor offset configuration structure. - */ -void EDMA_SetMinorOffsetConfig(DMA_Type *base, uint32_t channel, const edma_minor_offset_config_t *config); - -/*! - * @brief Configures the eDMA channel preemption feature. - * - * This function configures the channel preemption attribute and the priority of the channel. - * - * @param base eDMA peripheral base address. - * @param channel eDMA channel number - * @param config A pointer to the channel preemption configuration structure. - */ -static inline void EDMA_SetChannelPreemptionConfig(DMA_Type *base, - uint32_t channel, - const edma_channel_Preemption_config_t *config) -{ - assert(channel < FSL_FEATURE_EDMA_MODULE_CHANNEL); - assert(config != NULL); - - DMA_DCHPRIn(base, channel) = - (DMA_DCHPRI0_DPA(!config->enablePreemptAbility) | DMA_DCHPRI0_ECP(config->enableChannelPreemption) | - DMA_DCHPRI0_CHPRI(config->channelPriority)); -} - -/*! - * @brief Sets the channel link for the eDMA transfer. - * - * This function configures either the minor link or the major link mode. The minor link means that the channel link is - * triggered every time CITER decreases by 1. The major link means that the channel link is triggered when the CITER is - * exhausted. - * - * @param base eDMA peripheral base address. - * @param channel eDMA channel number. - * @param type A channel link type, which can be one of the following: - * @arg kEDMA_LinkNone - * @arg kEDMA_MinorLink - * @arg kEDMA_MajorLink - * @param linkedChannel The linked channel number. - * @note Users should ensure that DONE flag is cleared before calling this interface, or the configuration is invalid. - */ -void EDMA_SetChannelLink(DMA_Type *base, uint32_t channel, edma_channel_link_type_t type, uint32_t linkedChannel); - -/*! - * @brief Sets the bandwidth for the eDMA transfer. - * - * Because the eDMA processes the minor loop, it continuously generates read/write sequences - * until the minor count is exhausted. The bandwidth forces the eDMA to stall after the completion of - * each read/write access to control the bus request bandwidth seen by the crossbar switch. - * - * @param base eDMA peripheral base address. - * @param channel eDMA channel number. - * @param bandWidth A bandwidth setting, which can be one of the following: - * @arg kEDMABandwidthStallNone - * @arg kEDMABandwidthStall4Cycle - * @arg kEDMABandwidthStall8Cycle - */ -void EDMA_SetBandWidth(DMA_Type *base, uint32_t channel, edma_bandwidth_t bandWidth); - -/*! - * @brief Sets the source modulo and the destination modulo for the eDMA transfer. - * - * This function defines a specific address range specified to be the value after (SADDR + SOFF)/(DADDR + DOFF) - * calculation is performed or the original register value. It provides the ability to implement a circular data - * queue easily. - * - * @param base eDMA peripheral base address. - * @param channel eDMA channel number. - * @param srcModulo A source modulo value. - * @param destModulo A destination modulo value. - */ -void EDMA_SetModulo(DMA_Type *base, uint32_t channel, edma_modulo_t srcModulo, edma_modulo_t destModulo); - -#if defined(FSL_FEATURE_EDMA_ASYNCHRO_REQUEST_CHANNEL_COUNT) && FSL_FEATURE_EDMA_ASYNCHRO_REQUEST_CHANNEL_COUNT -/*! - * @brief Enables an async request for the eDMA transfer. - * - * @param base eDMA peripheral base address. - * @param channel eDMA channel number. - * @param enable The command to enable (true) or disable (false). - */ -static inline void EDMA_EnableAsyncRequest(DMA_Type *base, uint32_t channel, bool enable) -{ - assert(channel < FSL_FEATURE_DMAMUX_MODULE_CHANNEL); - - base->EARS = (base->EARS & (~(1U << channel))) | ((uint32_t)enable << channel); -} -#endif /* FSL_FEATURE_EDMA_ASYNCHRO_REQUEST_CHANNEL_COUNT */ - -/*! - * @brief Enables an auto stop request for the eDMA transfer. - * - * If enabling the auto stop request, the eDMA hardware automatically disables the hardware channel request. - * - * @param base eDMA peripheral base address. - * @param channel eDMA channel number. - * @param enable The command to enable (true) or disable (false). - */ -static inline void EDMA_EnableAutoStopRequest(DMA_Type *base, uint32_t channel, bool enable) -{ - assert(channel < FSL_FEATURE_DMAMUX_MODULE_CHANNEL); - - base->TCD[channel].CSR = (base->TCD[channel].CSR & (~DMA_CSR_DREQ_MASK)) | DMA_CSR_DREQ(enable); -} - -/*! - * @brief Enables the interrupt source for the eDMA transfer. - * - * @param base eDMA peripheral base address. - * @param channel eDMA channel number. - * @param mask The mask of interrupt source to be set. Users need to use - * the defined edma_interrupt_enable_t type. - */ -void EDMA_EnableChannelInterrupts(DMA_Type *base, uint32_t channel, uint32_t mask); - -/*! - * @brief Disables the interrupt source for the eDMA transfer. - * - * @param base eDMA peripheral base address. - * @param channel eDMA channel number. - * @param mask The mask of the interrupt source to be set. Use - * the defined edma_interrupt_enable_t type. - */ -void EDMA_DisableChannelInterrupts(DMA_Type *base, uint32_t channel, uint32_t mask); - -/* @} */ -/*! - * @name eDMA TCD Operation - * @{ - */ - -/*! - * @brief Sets all fields to default values for the TCD structure. - * - * This function sets all fields for this TCD structure to default value. - * - * @param tcd Pointer to the TCD structure. - * @note This function enables the auto stop request feature. - */ -void EDMA_TcdReset(edma_tcd_t *tcd); - -/*! - * @brief Configures the eDMA TCD transfer attribute. - * - * The TCD is a transfer control descriptor. The content of the TCD is the same as the hardware TCD registers. - * The STCD is used in the scatter-gather mode. - * This function configures the TCD transfer attribute, including source address, destination address, - * transfer size, address offset, and so on. It also configures the scatter gather feature if the - * user supplies the next TCD address. - * Example: - * @code - * edma_transfer_t config = { - * ... - * } - * edma_tcd_t tcd __aligned(32); - * edma_tcd_t nextTcd __aligned(32); - * EDMA_TcdSetTransferConfig(&tcd, &config, &nextTcd); - * @endcode - * - * @param tcd Pointer to the TCD structure. - * @param config Pointer to eDMA transfer configuration structure. - * @param nextTcd Pointer to the next TCD structure. It can be NULL if users - * do not want to enable scatter/gather feature. - * @note TCD address should be 32 bytes aligned or it causes an eDMA error. - * @note If the nextTcd is not NULL, the scatter gather feature is enabled - * and DREQ bit is cleared in the previous transfer configuration, which - * is set in the EDMA_TcdReset. - */ -void EDMA_TcdSetTransferConfig(edma_tcd_t *tcd, const edma_transfer_config_t *config, edma_tcd_t *nextTcd); - -/*! - * @brief Configures the eDMA TCD minor offset feature. - * - * A minor offset is a signed-extended value added to the source address or a destination - * address after each minor loop. - * - * @param tcd A point to the TCD structure. - * @param config A pointer to the minor offset configuration structure. - */ -void EDMA_TcdSetMinorOffsetConfig(edma_tcd_t *tcd, const edma_minor_offset_config_t *config); - -/*! - * @brief Sets the channel link for the eDMA TCD. - * - * This function configures either a minor link or a major link. The minor link means the channel link is - * triggered every time CITER decreases by 1. The major link means that the channel link is triggered when the CITER is - * exhausted. - * - * @note Users should ensure that DONE flag is cleared before calling this interface, or the configuration is invalid. - * @param tcd Point to the TCD structure. - * @param type Channel link type, it can be one of: - * @arg kEDMA_LinkNone - * @arg kEDMA_MinorLink - * @arg kEDMA_MajorLink - * @param linkedChannel The linked channel number. - */ -void EDMA_TcdSetChannelLink(edma_tcd_t *tcd, edma_channel_link_type_t type, uint32_t linkedChannel); - -/*! - * @brief Sets the bandwidth for the eDMA TCD. - * - * Because the eDMA processes the minor loop, it continuously generates read/write sequences - * until the minor count is exhausted. The bandwidth forces the eDMA to stall after the completion of - * each read/write access to control the bus request bandwidth seen by the crossbar switch. - * @param tcd A pointer to the TCD structure. - * @param bandWidth A bandwidth setting, which can be one of the following: - * @arg kEDMABandwidthStallNone - * @arg kEDMABandwidthStall4Cycle - * @arg kEDMABandwidthStall8Cycle - */ -static inline void EDMA_TcdSetBandWidth(edma_tcd_t *tcd, edma_bandwidth_t bandWidth) -{ - assert(tcd != NULL); - assert(((uint32_t)tcd & 0x1FU) == 0); - - tcd->CSR = (tcd->CSR & (~DMA_CSR_BWC_MASK)) | DMA_CSR_BWC(bandWidth); -} - -/*! - * @brief Sets the source modulo and the destination modulo for the eDMA TCD. - * - * This function defines a specific address range specified to be the value after (SADDR + SOFF)/(DADDR + DOFF) - * calculation is performed or the original register value. It provides the ability to implement a circular data - * queue easily. - * - * @param tcd A pointer to the TCD structure. - * @param srcModulo A source modulo value. - * @param destModulo A destination modulo value. - */ -void EDMA_TcdSetModulo(edma_tcd_t *tcd, edma_modulo_t srcModulo, edma_modulo_t destModulo); - -/*! - * @brief Sets the auto stop request for the eDMA TCD. - * - * If enabling the auto stop request, the eDMA hardware automatically disables the hardware channel request. - * - * @param tcd A pointer to the TCD structure. - * @param enable The command to enable (true) or disable (false). - */ -static inline void EDMA_TcdEnableAutoStopRequest(edma_tcd_t *tcd, bool enable) -{ - assert(tcd != NULL); - assert(((uint32_t)tcd & 0x1FU) == 0); - - tcd->CSR = (tcd->CSR & (~DMA_CSR_DREQ_MASK)) | DMA_CSR_DREQ(enable); -} - -/*! - * @brief Enables the interrupt source for the eDMA TCD. - * - * @param tcd Point to the TCD structure. - * @param mask The mask of interrupt source to be set. Users need to use - * the defined edma_interrupt_enable_t type. - */ -void EDMA_TcdEnableInterrupts(edma_tcd_t *tcd, uint32_t mask); - -/*! - * @brief Disables the interrupt source for the eDMA TCD. - * - * @param tcd Point to the TCD structure. - * @param mask The mask of interrupt source to be set. Users need to use - * the defined edma_interrupt_enable_t type. - */ -void EDMA_TcdDisableInterrupts(edma_tcd_t *tcd, uint32_t mask); - -/*! @} */ -/*! - * @name eDMA Channel Transfer Operation - * @{ - */ - -/*! - * @brief Enables the eDMA hardware channel request. - * - * This function enables the hardware channel request. - * - * @param base eDMA peripheral base address. - * @param channel eDMA channel number. - */ -static inline void EDMA_EnableChannelRequest(DMA_Type *base, uint32_t channel) -{ - assert(channel < FSL_FEATURE_DMAMUX_MODULE_CHANNEL); - - base->SERQ = DMA_SERQ_SERQ(channel); -} - -/*! - * @brief Disables the eDMA hardware channel request. - * - * This function disables the hardware channel request. - * - * @param base eDMA peripheral base address. - * @param channel eDMA channel number. - */ -static inline void EDMA_DisableChannelRequest(DMA_Type *base, uint32_t channel) -{ - assert(channel < FSL_FEATURE_DMAMUX_MODULE_CHANNEL); - - base->CERQ = DMA_CERQ_CERQ(channel); -} - -/*! - * @brief Starts the eDMA transfer by using the software trigger. - * - * This function starts a minor loop transfer. - * - * @param base eDMA peripheral base address. - * @param channel eDMA channel number. - */ -static inline void EDMA_TriggerChannelStart(DMA_Type *base, uint32_t channel) -{ - assert(channel < FSL_FEATURE_DMAMUX_MODULE_CHANNEL); - - base->SSRT = DMA_SSRT_SSRT(channel); -} - -/*! @} */ -/*! - * @name eDMA Channel Status Operation - * @{ - */ - -/*! - * @brief Gets the remaining major loop count from the eDMA current channel TCD. - * - * This function checks the TCD (Task Control Descriptor) status for a specified - * eDMA channel and returns the the number of major loop count that has not finished. - * - * @param base eDMA peripheral base address. - * @param channel eDMA channel number. - * @return Major loop count which has not been transferred yet for the current TCD. - * @note 1. This function can only be used to get unfinished major loop count of transfer without - * the next TCD, or it might be inaccuracy. - * 2. The unfinished/remaining transfer bytes cannot be obtained directly from registers while - * the channel is running. - * Because to calculate the remaining bytes, the initial NBYTES configured in DMA_TCDn_NBYTES_MLNO - * register is needed while the eDMA IP does not support getting it while a channel is active. - * In another word, the NBYTES value reading is always the actual (decrementing) NBYTES value the dma_engine - * is working with while a channel is running. - * Consequently, to get the remaining transfer bytes, a software-saved initial value of NBYTES (for example - * copied before enabling the channel) is needed. The formula to calculate it is shown below: - * RemainingBytes = RemainingMajorLoopCount * NBYTES(initially configured) - */ -uint32_t EDMA_GetRemainingMajorLoopCount(DMA_Type *base, uint32_t channel); - -/*! - * @brief Gets the eDMA channel error status flags. - * - * @param base eDMA peripheral base address. - * @return The mask of error status flags. Users need to use the -* _edma_error_status_flags type to decode the return variables. - */ -static inline uint32_t EDMA_GetErrorStatusFlags(DMA_Type *base) -{ - return base->ES; -} - -/*! - * @brief Gets the eDMA channel status flags. - * - * @param base eDMA peripheral base address. - * @param channel eDMA channel number. - * @return The mask of channel status flags. Users need to use the - * _edma_channel_status_flags type to decode the return variables. - */ -uint32_t EDMA_GetChannelStatusFlags(DMA_Type *base, uint32_t channel); - -/*! - * @brief Clears the eDMA channel status flags. - * - * @param base eDMA peripheral base address. - * @param channel eDMA channel number. - * @param mask The mask of channel status to be cleared. Users need to use - * the defined _edma_channel_status_flags type. - */ -void EDMA_ClearChannelStatusFlags(DMA_Type *base, uint32_t channel, uint32_t mask); - -/*! @} */ -/*! - * @name eDMA Transactional Operation - */ - -/*! - * @brief Creates the eDMA handle. - * - * This function is called if using the transactional API for eDMA. This function - * initializes the internal state of the eDMA handle. - * - * @param handle eDMA handle pointer. The eDMA handle stores callback function and - * parameters. - * @param base eDMA peripheral base address. - * @param channel eDMA channel number. - */ -void EDMA_CreateHandle(edma_handle_t *handle, DMA_Type *base, uint32_t channel); - -/*! - * @brief Installs the TCDs memory pool into the eDMA handle. - * - * This function is called after the EDMA_CreateHandle to use scatter/gather feature. - * - * @param handle eDMA handle pointer. - * @param tcdPool A memory pool to store TCDs. It must be 32 bytes aligned. - * @param tcdSize The number of TCD slots. - */ -void EDMA_InstallTCDMemory(edma_handle_t *handle, edma_tcd_t *tcdPool, uint32_t tcdSize); - -/*! - * @brief Installs a callback function for the eDMA transfer. - * - * This callback is called in the eDMA IRQ handler. Use the callback to do something after - * the current major loop transfer completes. - * - * @param handle eDMA handle pointer. - * @param callback eDMA callback function pointer. - * @param userData A parameter for the callback function. - */ -void EDMA_SetCallback(edma_handle_t *handle, edma_callback callback, void *userData); - -/*! - * @brief Prepares the eDMA transfer structure. - * - * This function prepares the transfer configuration structure according to the user input. - * - * @param config The user configuration structure of type edma_transfer_t. - * @param srcAddr eDMA transfer source address. - * @param srcWidth eDMA transfer source address width(bytes). - * @param destAddr eDMA transfer destination address. - * @param destWidth eDMA transfer destination address width(bytes). - * @param bytesEachRequest eDMA transfer bytes per channel request. - * @param transferBytes eDMA transfer bytes to be transferred. - * @param type eDMA transfer type. - * @note The data address and the data width must be consistent. For example, if the SRC - * is 4 bytes, the source address must be 4 bytes aligned, or it results in - * source address error (SAE). - */ -void EDMA_PrepareTransfer(edma_transfer_config_t *config, - void *srcAddr, - uint32_t srcWidth, - void *destAddr, - uint32_t destWidth, - uint32_t bytesEachRequest, - uint32_t transferBytes, - edma_transfer_type_t type); - -/*! - * @brief Submits the eDMA transfer request. - * - * This function submits the eDMA transfer request according to the transfer configuration structure. - * If submitting the transfer request repeatedly, this function packs an unprocessed request as - * a TCD and enables scatter/gather feature to process it in the next time. - * - * @param handle eDMA handle pointer. - * @param config Pointer to eDMA transfer configuration structure. - * @retval kStatus_EDMA_Success It means submit transfer request succeed. - * @retval kStatus_EDMA_QueueFull It means TCD queue is full. Submit transfer request is not allowed. - * @retval kStatus_EDMA_Busy It means the given channel is busy, need to submit request later. - */ -status_t EDMA_SubmitTransfer(edma_handle_t *handle, const edma_transfer_config_t *config); - -/*! - * @brief eDMA starts transfer. - * - * This function enables the channel request. Users can call this function after submitting the transfer request - * or before submitting the transfer request. - * - * @param handle eDMA handle pointer. - */ -void EDMA_StartTransfer(edma_handle_t *handle); - -/*! - * @brief eDMA stops transfer. - * - * This function disables the channel request to pause the transfer. Users can call EDMA_StartTransfer() - * again to resume the transfer. - * - * @param handle eDMA handle pointer. - */ -void EDMA_StopTransfer(edma_handle_t *handle); - -/*! - * @brief eDMA aborts transfer. - * - * This function disables the channel request and clear transfer status bits. - * Users can submit another transfer after calling this API. - * - * @param handle DMA handle pointer. - */ -void EDMA_AbortTransfer(edma_handle_t *handle); - -/*! - * @brief eDMA IRQ handler for the current major loop transfer completion. - * - * This function clears the channel major interrupt flag and calls - * the callback function if it is not NULL. - * - * Note: - * For the case using TCD queue, when the major iteration count is exhausted, additional operations are performed. - * These include the final address adjustments and reloading of the BITER field into the CITER. - * Assertion of an optional interrupt request also occurs at this time, as does a possible fetch of a new TCD from - * memory using the scatter/gather address pointer included in the descriptor (if scatter/gather is enabled). - * - * For instance, when the time interrupt of TCD[0] happens, the TCD[1] has already been loaded into the eDMA engine. - * As sga and sga_index are calculated based on the DLAST_SGA bitfield lies in the TCD_CSR register, the sga_index - * in this case should be 2 (DLAST_SGA of TCD[1] stores the address of TCD[2]). Thus, the "tcdUsed" updated should be - * (tcdUsed - 2U) which indicates the number of TCDs can be loaded in the memory pool (because TCD[0] and TCD[1] have - * been loaded into the eDMA engine at this point already.). - * - * For the last two continuous ISRs in a scatter/gather process, they both load the last TCD (The last ISR does not - * load a new TCD) from the memory pool to the eDMA engine when major loop completes. - * Therefore, ensure that the header and tcdUsed updated are identical for them. - * tcdUsed are both 0 in this case as no TCD to be loaded. - * - * See the "eDMA basic data flow" in the eDMA Functional description section of the Reference Manual for - * further details. - * - * @param handle eDMA handle pointer. - */ -void EDMA_HandleIRQ(edma_handle_t *handle); - -/* @} */ - -#if defined(__cplusplus) -} -#endif /* __cplusplus */ - -/* @} */ - -#endif /*_FSL_EDMA_H_*/ diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_ewm.c b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_ewm.c deleted file mode 100644 index f22eff941e9..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_ewm.c +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "fsl_ewm.h" - -/******************************************************************************* - * Code - ******************************************************************************/ - -void EWM_Init(EWM_Type *base, const ewm_config_t *config) -{ - assert(config); - - uint32_t value = 0U; - -#if !((defined(FSL_FEATURE_SOC_PCC_COUNT) && FSL_FEATURE_SOC_PCC_COUNT) && \ - (defined(FSL_FEATURE_PCC_SUPPORT_EWM_CLOCK_REMOVE) && FSL_FEATURE_PCC_SUPPORT_EWM_CLOCK_REMOVE)) -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) - CLOCK_EnableClock(kCLOCK_Ewm0); -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ -#endif - value = EWM_CTRL_EWMEN(config->enableEwm) | EWM_CTRL_ASSIN(config->setInputAssertLogic) | - EWM_CTRL_INEN(config->enableEwmInput) | EWM_CTRL_INTEN(config->enableInterrupt); -#if defined(FSL_FEATURE_EWM_HAS_PRESCALER) && FSL_FEATURE_EWM_HAS_PRESCALER - base->CLKPRESCALER = config->prescaler; -#endif /* FSL_FEATURE_EWM_HAS_PRESCALER */ - -#if defined(FSL_FEATURE_EWM_HAS_CLOCK_SELECT) && FSL_FEATURE_EWM_HAS_CLOCK_SELECT - base->CLKCTRL = config->clockSource; -#endif /* FSL_FEATURE_EWM_HAS_CLOCK_SELECT*/ - - base->CMPL = config->compareLowValue; - base->CMPH = config->compareHighValue; - base->CTRL = value; -} - -void EWM_Deinit(EWM_Type *base) -{ - EWM_DisableInterrupts(base, kEWM_InterruptEnable); -#if !((defined(FSL_FEATURE_SOC_PCC_COUNT) && FSL_FEATURE_SOC_PCC_COUNT) && \ - (defined(FSL_FEATURE_PCC_SUPPORT_EWM_CLOCK_REMOVE) && FSL_FEATURE_PCC_SUPPORT_EWM_CLOCK_REMOVE)) -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) - CLOCK_DisableClock(kCLOCK_Ewm0); -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ -#endif /* FSL_FEATURE_PCC_SUPPORT_EWM_CLOCK_REMOVE */ -} - -void EWM_GetDefaultConfig(ewm_config_t *config) -{ - assert(config); - - config->enableEwm = true; - config->enableEwmInput = false; - config->setInputAssertLogic = false; - config->enableInterrupt = false; -#if defined(FSL_FEATURE_EWM_HAS_CLOCK_SELECT) && FSL_FEATURE_EWM_HAS_CLOCK_SELECT - config->clockSource = kEWM_LpoClockSource0; -#endif /* FSL_FEATURE_EWM_HAS_CLOCK_SELECT*/ -#if defined(FSL_FEATURE_EWM_HAS_PRESCALER) && FSL_FEATURE_EWM_HAS_PRESCALER - config->prescaler = 0U; -#endif /* FSL_FEATURE_EWM_HAS_PRESCALER */ - config->compareLowValue = 0U; - config->compareHighValue = 0xFEU; -} - -void EWM_Refresh(EWM_Type *base) -{ - uint32_t primaskValue = 0U; - - /* Disable the global interrupt to protect refresh sequence */ - primaskValue = DisableGlobalIRQ(); - base->SERV = (uint8_t)0xB4U; - base->SERV = (uint8_t)0x2CU; - EnableGlobalIRQ(primaskValue); -} diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_ewm.h b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_ewm.h deleted file mode 100644 index aa32ed3c713..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_ewm.h +++ /dev/null @@ -1,241 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -#ifndef _FSL_EWM_H_ -#define _FSL_EWM_H_ - -#include "fsl_common.h" - -/*! - * @addtogroup ewm - * @{ - */ - - -/******************************************************************************* - * Definitions - *******************************************************************************/ - -/*! @name Driver version */ -/*@{*/ -/*! @brief EWM driver version 2.0.1. */ -#define FSL_EWM_DRIVER_VERSION (MAKE_VERSION(2, 0, 1)) -/*@}*/ - -/*! @brief Describes EWM clock source. */ -#if defined(FSL_FEATURE_EWM_HAS_CLOCK_SELECT) && FSL_FEATURE_EWM_HAS_CLOCK_SELECT -typedef enum _ewm_lpo_clock_source -{ - kEWM_LpoClockSource0 = 0U, /*!< EWM clock sourced from lpo_clk[0]*/ - kEWM_LpoClockSource1 = 1U, /*!< EWM clock sourced from lpo_clk[1]*/ - kEWM_LpoClockSource2 = 2U, /*!< EWM clock sourced from lpo_clk[2]*/ - kEWM_LpoClockSource3 = 3U, /*!< EWM clock sourced from lpo_clk[3]*/ -} ewm_lpo_clock_source_t; -#endif /* FSL_FEATURE_EWM_HAS_CLOCK_SELECT */ - -/*! -* @brief Data structure for EWM configuration. -* -* This structure is used to configure the EWM. -*/ -typedef struct _ewm_config -{ - bool enableEwm; /*!< Enable EWM module */ - bool enableEwmInput; /*!< Enable EWM_in input */ - bool setInputAssertLogic; /*!< EWM_in signal assertion state */ - bool enableInterrupt; /*!< Enable EWM interrupt */ -#if defined(FSL_FEATURE_EWM_HAS_CLOCK_SELECT) && FSL_FEATURE_EWM_HAS_CLOCK_SELECT - ewm_lpo_clock_source_t clockSource; /*!< Clock source select */ -#endif /* FSL_FEATURE_EWM_HAS_CLOCK_SELECT */ -#if defined(FSL_FEATURE_EWM_HAS_PRESCALER) && FSL_FEATURE_EWM_HAS_PRESCALER - uint8_t prescaler; /*!< Clock prescaler value */ -#endif /* FSL_FEATURE_EWM_HAS_PRESCALER */ - uint8_t compareLowValue; /*!< Compare low-register value */ - uint8_t compareHighValue; /*!< Compare high-register value */ -} ewm_config_t; - -/*! - * @brief EWM interrupt configuration structure with default settings all disabled. - * - * This structure contains the settings for all of EWM interrupt configurations. - */ -enum _ewm_interrupt_enable_t -{ - kEWM_InterruptEnable = EWM_CTRL_INTEN_MASK, /*!< Enable the EWM to generate an interrupt*/ -}; - -/*! - * @brief EWM status flags. - * - * This structure contains the constants for the EWM status flags for use in the EWM functions. - */ -enum _ewm_status_flags_t -{ - kEWM_RunningFlag = EWM_CTRL_EWMEN_MASK, /*!< Running flag, set when EWM is enabled*/ -}; - -/******************************************************************************* - * API - *******************************************************************************/ - -#if defined(__cplusplus) -extern "C" { -#endif /* __cplusplus */ - -/*! - * @name EWM initialization and de-initialization - * @{ - */ - -/*! - * @brief Initializes the EWM peripheral. - * - * This function is used to initialize the EWM. After calling, the EWM - * runs immediately according to the configuration. - * Note that, except for the interrupt enable control bit, other control bits and registers are write once after a - * CPU reset. Modifying them more than once generates a bus transfer error. - * - * This is an example. - * @code - * ewm_config_t config; - * EWM_GetDefaultConfig(&config); - * config.compareHighValue = 0xAAU; - * EWM_Init(ewm_base,&config); - * @endcode - * - * @param base EWM peripheral base address - * @param config The configuration of the EWM -*/ -void EWM_Init(EWM_Type *base, const ewm_config_t *config); - -/*! - * @brief Deinitializes the EWM peripheral. - * - * This function is used to shut down the EWM. - * - * @param base EWM peripheral base address -*/ -void EWM_Deinit(EWM_Type *base); - -/*! - * @brief Initializes the EWM configuration structure. - * - * This function initializes the EWM configuration structure to default values. The default - * values are as follows. - * @code - * ewmConfig->enableEwm = true; - * ewmConfig->enableEwmInput = false; - * ewmConfig->setInputAssertLogic = false; - * ewmConfig->enableInterrupt = false; - * ewmConfig->ewm_lpo_clock_source_t = kEWM_LpoClockSource0; - * ewmConfig->prescaler = 0; - * ewmConfig->compareLowValue = 0; - * ewmConfig->compareHighValue = 0xFEU; - * @endcode - * - * @param config Pointer to the EWM configuration structure. - * @see ewm_config_t - */ -void EWM_GetDefaultConfig(ewm_config_t *config); - -/* @} */ - -/*! - * @name EWM functional Operation - * @{ - */ - -/*! - * @brief Enables the EWM interrupt. - * - * This function enables the EWM interrupt. - * - * @param base EWM peripheral base address - * @param mask The interrupts to enable - * The parameter can be combination of the following source if defined - * @arg kEWM_InterruptEnable - */ -static inline void EWM_EnableInterrupts(EWM_Type *base, uint32_t mask) -{ - base->CTRL |= mask; -} - -/*! - * @brief Disables the EWM interrupt. - * - * This function enables the EWM interrupt. - * - * @param base EWM peripheral base address - * @param mask The interrupts to disable - * The parameter can be combination of the following source if defined - * @arg kEWM_InterruptEnable - */ -static inline void EWM_DisableInterrupts(EWM_Type *base, uint32_t mask) -{ - base->CTRL &= ~mask; -} - -/*! - * @brief Gets all status flags. - * - * This function gets all status flags. - * - * This is an example for getting the running flag. - * @code - * uint32_t status; - * status = EWM_GetStatusFlags(ewm_base) & kEWM_RunningFlag; - * @endcode - * @param base EWM peripheral base address - * @return State of the status flag: asserted (true) or not-asserted (false).@see _ewm_status_flags_t - * - True: a related status flag has been set. - * - False: a related status flag is not set. - */ -static inline uint32_t EWM_GetStatusFlags(EWM_Type *base) -{ - return (base->CTRL & EWM_CTRL_EWMEN_MASK); -} - -/*! - * @brief Services the EWM. - * - * This function resets the EWM counter to zero. - * - * @param base EWM peripheral base address -*/ -void EWM_Refresh(EWM_Type *base); - -/*@}*/ - -#if defined(__cplusplus) -} -#endif /* __cplusplus */ - -/*! @}*/ - -#endif /* _FSL_EWM_H_ */ diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_flash.c b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_flash.c deleted file mode 100644 index f63e6c98145..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_flash.c +++ /dev/null @@ -1,3432 +0,0 @@ -/* - * Copyright (c) 2015-2016, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "fsl_flash.h" - -/******************************************************************************* - * Definitions - ******************************************************************************/ - -/*! - * @name Misc utility defines - * @{ - */ -/*! @brief Alignment utility. */ -#ifndef ALIGN_DOWN -#define ALIGN_DOWN(x, a) ((x) & (uint32_t)(-((int32_t)(a)))) -#endif -#ifndef ALIGN_UP -#define ALIGN_UP(x, a) (-((int32_t)((uint32_t)(-((int32_t)(x))) & (uint32_t)(-((int32_t)(a)))))) -#endif - -/*! @brief Join bytes to word utility. */ -#define B1P4(b) (((uint32_t)(b)&0xFFU) << 24) -#define B1P3(b) (((uint32_t)(b)&0xFFU) << 16) -#define B1P2(b) (((uint32_t)(b)&0xFFU) << 8) -#define B1P1(b) ((uint32_t)(b)&0xFFU) -#define B2P3(b) (((uint32_t)(b)&0xFFFFU) << 16) -#define B2P2(b) (((uint32_t)(b)&0xFFFFU) << 8) -#define B2P1(b) ((uint32_t)(b)&0xFFFFU) -#define B3P2(b) (((uint32_t)(b)&0xFFFFFFU) << 8) -#define B3P1(b) ((uint32_t)(b)&0xFFFFFFU) -#define BYTES_JOIN_TO_WORD_1_3(x, y) (B1P4(x) | B3P1(y)) -#define BYTES_JOIN_TO_WORD_2_2(x, y) (B2P3(x) | B2P1(y)) -#define BYTES_JOIN_TO_WORD_3_1(x, y) (B3P2(x) | B1P1(y)) -#define BYTES_JOIN_TO_WORD_1_1_2(x, y, z) (B1P4(x) | B1P3(y) | B2P1(z)) -#define BYTES_JOIN_TO_WORD_1_2_1(x, y, z) (B1P4(x) | B2P2(y) | B1P1(z)) -#define BYTES_JOIN_TO_WORD_2_1_1(x, y, z) (B2P3(x) | B1P2(y) | B1P1(z)) -#define BYTES_JOIN_TO_WORD_1_1_1_1(x, y, z, w) (B1P4(x) | B1P3(y) | B1P2(z) | B1P1(w)) -/*@}*/ - -/*! - * @name Secondary flash configuration - * @{ - */ -/*! @brief Indicates whether the secondary flash has its own protection register in flash module. */ -#if defined(FSL_FEATURE_FLASH_HAS_MULTIPLE_FLASH) && defined(FTFE_FPROTS_PROTS_MASK) -#define FLASH_SSD_SECONDARY_FLASH_HAS_ITS_OWN_PROTECTION_REGISTER (1) -#else -#define FLASH_SSD_SECONDARY_FLASH_HAS_ITS_OWN_PROTECTION_REGISTER (0) -#endif - -/*! @brief Indicates whether the secondary flash has its own Execute-Only access register in flash module. */ -#if defined(FSL_FEATURE_FLASH_HAS_MULTIPLE_FLASH) && defined(FTFE_FACSSS_SGSIZE_S_MASK) -#define FLASH_SSD_SECONDARY_FLASH_HAS_ITS_OWN_ACCESS_REGISTER (1) -#else -#define FLASH_SSD_SECONDARY_FLASH_HAS_ITS_OWN_ACCESS_REGISTER (0) -#endif -/*@}*/ - -/*! - * @name Flash cache ands speculation control defines - * @{ - */ -#if defined(MCM_PLACR_CFCC_MASK) || defined(MCM_CPCR2_CCBC_MASK) -#define FLASH_CACHE_IS_CONTROLLED_BY_MCM (1) -#else -#define FLASH_CACHE_IS_CONTROLLED_BY_MCM (0) -#endif -#if defined(FMC_PFB0CR_CINV_WAY_MASK) || defined(FMC_PFB01CR_CINV_WAY_MASK) -#define FLASH_CACHE_IS_CONTROLLED_BY_FMC (1) -#else -#define FLASH_CACHE_IS_CONTROLLED_BY_FMC (0) -#endif -#if defined(MCM_PLACR_DFCS_MASK) -#define FLASH_PREFETCH_SPECULATION_IS_CONTROLLED_BY_MCM (1) -#else -#define FLASH_PREFETCH_SPECULATION_IS_CONTROLLED_BY_MCM (0) -#endif -#if defined(MSCM_OCMDR_OCM1_MASK) || defined(MSCM_OCMDR_OCMC1_MASK) -#define FLASH_PREFETCH_SPECULATION_IS_CONTROLLED_BY_MSCM (1) -#else -#define FLASH_PREFETCH_SPECULATION_IS_CONTROLLED_BY_MSCM (0) -#endif -#if defined(FMC_PFB0CR_S_INV_MASK) || defined(FMC_PFB0CR_S_B_INV_MASK) || defined(FMC_PFB01CR_S_INV_MASK) || \ - defined(FMC_PFB01CR_S_B_INV_MASK) -#define FLASH_PREFETCH_SPECULATION_IS_CONTROLLED_BY_FMC (1) -#else -#define FLASH_PREFETCH_SPECULATION_IS_CONTROLLED_BY_FMC (0) -#endif -/*@}*/ - -/*! @brief Data flash IFR map Field*/ -#if defined(FSL_FEATURE_FLASH_IS_FTFE) && FSL_FEATURE_FLASH_IS_FTFE -#define DFLASH_IFR_READRESOURCE_START_ADDRESS 0x8003F8U -#else /* FSL_FEATURE_FLASH_IS_FTFL == 1 or FSL_FEATURE_FLASH_IS_FTFA = =1 */ -#define DFLASH_IFR_READRESOURCE_START_ADDRESS 0x8000F8U -#endif - -/*! - * @name Reserved FlexNVM size (For a variety of purposes) defines - * @{ - */ -#define FLEX_NVM_DFLASH_SIZE_FOR_DEPART_RESERVED 0xFFFFFFFFU -#define FLEX_NVM_EEPROM_SIZE_FOR_EEESIZE_RESERVED 0xFFFFU -/*@}*/ - -/*! - * @name Flash Program Once Field defines - * @{ - */ -#if defined(FSL_FEATURE_FLASH_IS_FTFA) && FSL_FEATURE_FLASH_IS_FTFA -/* FTFA parts(eg. K80, KL80, L5K) support both 4-bytes and 8-bytes unit size */ -#define FLASH_PROGRAM_ONCE_MIN_ID_8BYTES \ - 0x10U /* Minimum Index indcating one of Progam Once Fields which is accessed in 8-byte records */ -#define FLASH_PROGRAM_ONCE_MAX_ID_8BYTES \ - 0x13U /* Maximum Index indcating one of Progam Once Fields which is accessed in 8-byte records */ -#define FLASH_PROGRAM_ONCE_IS_4BYTES_UNIT_SUPPORT 1 -#define FLASH_PROGRAM_ONCE_IS_8BYTES_UNIT_SUPPORT 1 -#elif defined(FSL_FEATURE_FLASH_IS_FTFE) && FSL_FEATURE_FLASH_IS_FTFE -/* FTFE parts(eg. K65, KE18) only support 8-bytes unit size */ -#define FLASH_PROGRAM_ONCE_IS_4BYTES_UNIT_SUPPORT 0 -#define FLASH_PROGRAM_ONCE_IS_8BYTES_UNIT_SUPPORT 1 -#elif defined(FSL_FEATURE_FLASH_IS_FTFL) && FSL_FEATURE_FLASH_IS_FTFL -/* FTFL parts(eg. K20) only support 4-bytes unit size */ -#define FLASH_PROGRAM_ONCE_IS_4BYTES_UNIT_SUPPORT 1 -#define FLASH_PROGRAM_ONCE_IS_8BYTES_UNIT_SUPPORT 0 -#endif -/*@}*/ - -/*! - * @name Flash security status defines - * @{ - */ -#define FLASH_SECURITY_STATE_KEYEN 0x80U -#define FLASH_SECURITY_STATE_UNSECURED 0x02U -#define FLASH_NOT_SECURE 0x01U -#define FLASH_SECURE_BACKDOOR_ENABLED 0x02U -#define FLASH_SECURE_BACKDOOR_DISABLED 0x04U -/*@}*/ - -/*! - * @name Flash controller command numbers - * @{ - */ -#define FTFx_VERIFY_BLOCK 0x00U /*!< RD1BLK*/ -#define FTFx_VERIFY_SECTION 0x01U /*!< RD1SEC*/ -#define FTFx_PROGRAM_CHECK 0x02U /*!< PGMCHK*/ -#define FTFx_READ_RESOURCE 0x03U /*!< RDRSRC*/ -#define FTFx_PROGRAM_LONGWORD 0x06U /*!< PGM4*/ -#define FTFx_PROGRAM_PHRASE 0x07U /*!< PGM8*/ -#define FTFx_ERASE_BLOCK 0x08U /*!< ERSBLK*/ -#define FTFx_ERASE_SECTOR 0x09U /*!< ERSSCR*/ -#define FTFx_PROGRAM_SECTION 0x0BU /*!< PGMSEC*/ -#define FTFx_GENERATE_CRC 0x0CU /*!< CRCGEN*/ -#define FTFx_VERIFY_ALL_BLOCK 0x40U /*!< RD1ALL*/ -#define FTFx_READ_ONCE 0x41U /*!< RDONCE or RDINDEX*/ -#define FTFx_PROGRAM_ONCE 0x43U /*!< PGMONCE or PGMINDEX*/ -#define FTFx_ERASE_ALL_BLOCK 0x44U /*!< ERSALL*/ -#define FTFx_SECURITY_BY_PASS 0x45U /*!< VFYKEY*/ -#define FTFx_SWAP_CONTROL 0x46U /*!< SWAP*/ -#define FTFx_ERASE_ALL_BLOCK_UNSECURE 0x49U /*!< ERSALLU*/ -#define FTFx_VERIFY_ALL_EXECUTE_ONLY_SEGMENT 0x4AU /*!< RD1XA*/ -#define FTFx_ERASE_ALL_EXECUTE_ONLY_SEGMENT 0x4BU /*!< ERSXA*/ -#define FTFx_PROGRAM_PARTITION 0x80U /*!< PGMPART)*/ -#define FTFx_SET_FLEXRAM_FUNCTION 0x81U /*!< SETRAM*/ - /*@}*/ - -/*! - * @name Common flash register info defines - * @{ - */ -#if defined(FTFA) -#define FTFx FTFA -#define FTFx_BASE FTFA_BASE -#define FTFx_FSTAT_CCIF_MASK FTFA_FSTAT_CCIF_MASK -#define FTFx_FSTAT_RDCOLERR_MASK FTFA_FSTAT_RDCOLERR_MASK -#define FTFx_FSTAT_ACCERR_MASK FTFA_FSTAT_ACCERR_MASK -#define FTFx_FSTAT_FPVIOL_MASK FTFA_FSTAT_FPVIOL_MASK -#define FTFx_FSTAT_MGSTAT0_MASK FTFA_FSTAT_MGSTAT0_MASK -#define FTFx_FSEC_SEC_MASK FTFA_FSEC_SEC_MASK -#define FTFx_FSEC_KEYEN_MASK FTFA_FSEC_KEYEN_MASK -#if defined(FSL_FEATURE_FLASH_HAS_FLEX_RAM) && FSL_FEATURE_FLASH_HAS_FLEX_RAM -#define FTFx_FCNFG_RAMRDY_MASK FTFA_FCNFG_RAMRDY_MASK -#endif /* FSL_FEATURE_FLASH_HAS_FLEX_RAM */ -#if defined(FSL_FEATURE_FLASH_HAS_FLEX_NVM) && FSL_FEATURE_FLASH_HAS_FLEX_NVM -#define FTFx_FCNFG_EEERDY_MASK FTFA_FCNFG_EEERDY_MASK -#endif /* FSL_FEATURE_FLASH_HAS_FLEX_NVM */ -#elif defined(FTFE) -#define FTFx FTFE -#define FTFx_BASE FTFE_BASE -#define FTFx_FSTAT_CCIF_MASK FTFE_FSTAT_CCIF_MASK -#define FTFx_FSTAT_RDCOLERR_MASK FTFE_FSTAT_RDCOLERR_MASK -#define FTFx_FSTAT_ACCERR_MASK FTFE_FSTAT_ACCERR_MASK -#define FTFx_FSTAT_FPVIOL_MASK FTFE_FSTAT_FPVIOL_MASK -#define FTFx_FSTAT_MGSTAT0_MASK FTFE_FSTAT_MGSTAT0_MASK -#define FTFx_FSEC_SEC_MASK FTFE_FSEC_SEC_MASK -#define FTFx_FSEC_KEYEN_MASK FTFE_FSEC_KEYEN_MASK -#if defined(FSL_FEATURE_FLASH_HAS_FLEX_RAM) && FSL_FEATURE_FLASH_HAS_FLEX_RAM -#define FTFx_FCNFG_RAMRDY_MASK FTFE_FCNFG_RAMRDY_MASK -#endif /* FSL_FEATURE_FLASH_HAS_FLEX_RAM */ -#if defined(FSL_FEATURE_FLASH_HAS_FLEX_NVM) && FSL_FEATURE_FLASH_HAS_FLEX_NVM -#define FTFx_FCNFG_EEERDY_MASK FTFE_FCNFG_EEERDY_MASK -#endif /* FSL_FEATURE_FLASH_HAS_FLEX_NVM */ -#elif defined(FTFL) -#define FTFx FTFL -#define FTFx_BASE FTFL_BASE -#define FTFx_FSTAT_CCIF_MASK FTFL_FSTAT_CCIF_MASK -#define FTFx_FSTAT_RDCOLERR_MASK FTFL_FSTAT_RDCOLERR_MASK -#define FTFx_FSTAT_ACCERR_MASK FTFL_FSTAT_ACCERR_MASK -#define FTFx_FSTAT_FPVIOL_MASK FTFL_FSTAT_FPVIOL_MASK -#define FTFx_FSTAT_MGSTAT0_MASK FTFL_FSTAT_MGSTAT0_MASK -#define FTFx_FSEC_SEC_MASK FTFL_FSEC_SEC_MASK -#define FTFx_FSEC_KEYEN_MASK FTFL_FSEC_KEYEN_MASK -#if defined(FSL_FEATURE_FLASH_HAS_FLEX_RAM) && FSL_FEATURE_FLASH_HAS_FLEX_RAM -#define FTFx_FCNFG_RAMRDY_MASK FTFL_FCNFG_RAMRDY_MASK -#endif /* FSL_FEATURE_FLASH_HAS_FLEX_RAM */ -#if defined(FSL_FEATURE_FLASH_HAS_FLEX_NVM) && FSL_FEATURE_FLASH_HAS_FLEX_NVM -#define FTFx_FCNFG_EEERDY_MASK FTFL_FCNFG_EEERDY_MASK -#endif /* FSL_FEATURE_FLASH_HAS_FLEX_NVM */ -#else -#error "Unknown flash controller" -#endif -/*@}*/ - -/*! - * @name Common flash register access info defines - * @{ - */ -#define FTFx_FCCOB3_REG (FTFx->FCCOB3) -#define FTFx_FCCOB5_REG (FTFx->FCCOB5) -#define FTFx_FCCOB6_REG (FTFx->FCCOB6) -#define FTFx_FCCOB7_REG (FTFx->FCCOB7) - -#if defined(FTFA_FPROTH0_PROT_MASK) || defined(FTFE_FPROTH0_PROT_MASK) || defined(FTFL_FPROTH0_PROT_MASK) -#define FTFx_FPROT_HIGH_REG (FTFx->FPROTH3) -#define FTFx_FPROTH3_REG (FTFx->FPROTH3) -#define FTFx_FPROTH2_REG (FTFx->FPROTH2) -#define FTFx_FPROTH1_REG (FTFx->FPROTH1) -#define FTFx_FPROTH0_REG (FTFx->FPROTH0) -#endif - -#if defined(FTFA_FPROTL0_PROT_MASK) || defined(FTFE_FPROTL0_PROT_MASK) || defined(FTFL_FPROTL0_PROT_MASK) -#define FTFx_FPROT_LOW_REG (FTFx->FPROTL3) -#define FTFx_FPROTL3_REG (FTFx->FPROTL3) -#define FTFx_FPROTL2_REG (FTFx->FPROTL2) -#define FTFx_FPROTL1_REG (FTFx->FPROTL1) -#define FTFx_FPROTL0_REG (FTFx->FPROTL0) -#elif defined(FTFA_FPROT0_PROT_MASK) || defined(FTFE_FPROT0_PROT_MASK) || defined(FTFL_FPROT0_PROT_MASK) -#define FTFx_FPROT_LOW_REG (FTFx->FPROT3) -#define FTFx_FPROTL3_REG (FTFx->FPROT3) -#define FTFx_FPROTL2_REG (FTFx->FPROT2) -#define FTFx_FPROTL1_REG (FTFx->FPROT1) -#define FTFx_FPROTL0_REG (FTFx->FPROT0) -#endif - -#if FLASH_SSD_IS_SECONDARY_FLASH_ENABLED && FLASH_SSD_SECONDARY_FLASH_HAS_ITS_OWN_PROTECTION_REGISTER -#define FTFx_FPROTSH_REG (FTFx->FPROTSH) -#define FTFx_FPROTSL_REG (FTFx->FPROTSL) -#endif - -#define FTFx_XACCH3_REG (FTFx->XACCH3) -#define FTFx_XACCL3_REG (FTFx->XACCL3) - -#if FLASH_SSD_IS_SECONDARY_FLASH_ENABLED && FLASH_SSD_SECONDARY_FLASH_HAS_ITS_OWN_ACCESS_REGISTER -#define FTFx_XACCSH_REG (FTFx->XACCSH) -#define FTFx_XACCSL_REG (FTFx->XACCSL) -#endif -/*@}*/ - -/*! - * @brief Enumeration for access segment property. - */ -enum _flash_access_segment_property -{ - kFLASH_AccessSegmentBase = 256UL, -}; - -/*! - * @brief Enumeration for flash config area. - */ -enum _flash_config_area_range -{ - kFLASH_ConfigAreaStart = 0x400U, - kFLASH_ConfigAreaEnd = 0x40FU -}; - -/*! - * @name Flash register access type defines - * @{ - */ -#define FTFx_REG8_ACCESS_TYPE volatile uint8_t * -#define FTFx_REG32_ACCESS_TYPE volatile uint32_t * -/*@}*/ - -/*! - * @brief MCM cache register access info defines. - */ -#if defined(MCM_PLACR_CFCC_MASK) -#define MCM_CACHE_CLEAR_MASK MCM_PLACR_CFCC_MASK -#define MCM_CACHE_CLEAR_SHIFT MCM_PLACR_CFCC_SHIFT -#if defined(MCM) -#define MCM0_CACHE_REG MCM->PLACR -#elif defined(MCM0) -#define MCM0_CACHE_REG MCM0->PLACR -#endif -#if defined(MCM1) -#define MCM1_CACHE_REG MCM1->PLACR -#endif -#elif defined(MCM_CPCR2_CCBC_MASK) -#define MCM_CACHE_CLEAR_MASK MCM_CPCR2_CCBC_MASK -#define MCM_CACHE_CLEAR_SHIFT MCM_CPCR2_CCBC_SHIFT -#if defined(MCM) -#define MCM0_CACHE_REG MCM->CPCR2 -#elif defined(MCM0) -#define MCM0_CACHE_REG MCM0->CPCR2 -#endif -#if defined(MCM1) -#define MCM1_CACHE_REG MCM1->CPCR2 -#endif -#endif - -/*! - * @brief MSCM cache register access info defines. - */ -#if defined(MSCM_OCMDR_OCM1_MASK) -#define MSCM_SPECULATION_DISABLE_MASK MSCM_OCMDR_OCM1_MASK -#define MSCM_SPECULATION_DISABLE_SHIFT MSCM_OCMDR_OCM1_SHIFT -#define MSCM_SPECULATION_DISABLE(x) MSCM_OCMDR_OCM1(x) -#elif defined(MSCM_OCMDR_OCMC1_MASK) -#define MSCM_SPECULATION_DISABLE_MASK MSCM_OCMDR_OCMC1_MASK -#define MSCM_SPECULATION_DISABLE_SHIFT MSCM_OCMDR_OCMC1_SHIFT -#define MSCM_SPECULATION_DISABLE(x) MSCM_OCMDR_OCMC1(x) -#endif - -/*! - * @brief MSCM prefetch speculation defines. - */ -#define MSCM_OCMDR_OCMC1_DFDS_MASK (0x10U) -#define MSCM_OCMDR_OCMC1_DFCS_MASK (0x20U) - -#define MSCM_OCMDR_OCMC1_DFDS_SHIFT (4U) -#define MSCM_OCMDR_OCMC1_DFCS_SHIFT (5U) - -/*! - * @brief Flash size encoding rule. - */ -#define FLASH_MEMORY_SIZE_ENCODING_RULE_K1_2 (0x00U) -#define FLASH_MEMORY_SIZE_ENCODING_RULE_K3 (0x01U) - -#if defined(K32W042S1M2_M0P_SERIES) || defined(K32W042S1M2_M4_SERIES) -#define FLASH_MEMORY_SIZE_ENCODING_RULE (FLASH_MEMORY_SIZE_ENCODING_RULE_K3) -#else -#define FLASH_MEMORY_SIZE_ENCODING_RULE (FLASH_MEMORY_SIZE_ENCODING_RULE_K1_2) -#endif - -/******************************************************************************* - * Prototypes - ******************************************************************************/ - -#if FLASH_DRIVER_IS_FLASH_RESIDENT -/*! @brief Copy flash_run_command() to RAM*/ -static void copy_flash_run_command(uint32_t *flashRunCommand); -/*! @brief Copy flash_cache_clear_command() to RAM*/ -static void copy_flash_common_bit_operation(uint32_t *flashCommonBitOperation); -/*! @brief Check whether flash execute-in-ram functions are ready*/ -static status_t flash_check_execute_in_ram_function_info(flash_config_t *config); -#endif /* FLASH_DRIVER_IS_FLASH_RESIDENT */ - -/*! @brief Internal function Flash command sequence. Called by driver APIs only*/ -static status_t flash_command_sequence(flash_config_t *config); - -/*! @brief Perform the cache clear to the flash*/ -void flash_cache_clear(flash_config_t *config); - -/*! @brief Process the cache to the flash*/ -static void flash_cache_clear_process(flash_config_t *config, flash_cache_clear_process_t process); - -/*! @brief Validates the range and alignment of the given address range.*/ -static status_t flash_check_range(flash_config_t *config, - uint32_t startAddress, - uint32_t lengthInBytes, - uint32_t alignmentBaseline); -/*! @brief Gets the right address, sector and block size of current flash type which is indicated by address.*/ -static status_t flash_get_matched_operation_info(flash_config_t *config, - uint32_t address, - flash_operation_config_t *info); -/*! @brief Validates the given user key for flash erase APIs.*/ -static status_t flash_check_user_key(uint32_t key); - -#if FLASH_SSD_IS_FLEXNVM_ENABLED -/*! @brief Updates FlexNVM memory partition status according to data flash 0 IFR.*/ -static status_t flash_update_flexnvm_memory_partition_status(flash_config_t *config); -#endif /* FLASH_SSD_IS_FLEXNVM_ENABLED */ - -#if defined(FSL_FEATURE_FLASH_HAS_READ_RESOURCE_CMD) && FSL_FEATURE_FLASH_HAS_READ_RESOURCE_CMD -/*! @brief Validates the range of the given resource address.*/ -static status_t flash_check_resource_range(uint32_t start, - uint32_t lengthInBytes, - uint32_t alignmentBaseline, - flash_read_resource_option_t option); -#endif /* FSL_FEATURE_FLASH_HAS_READ_RESOURCE_CMD */ - -#if defined(FSL_FEATURE_FLASH_HAS_SWAP_CONTROL_CMD) && FSL_FEATURE_FLASH_HAS_SWAP_CONTROL_CMD -/*! @brief Validates the gived swap control option.*/ -static status_t flash_check_swap_control_option(flash_swap_control_option_t option); -#endif /* FSL_FEATURE_FLASH_HAS_SWAP_CONTROL_CMD */ - -#if defined(FSL_FEATURE_FLASH_HAS_PFLASH_BLOCK_SWAP) && FSL_FEATURE_FLASH_HAS_PFLASH_BLOCK_SWAP -/*! @brief Validates the gived address to see if it is equal to swap indicator address in pflash swap IFR.*/ -static status_t flash_validate_swap_indicator_address(flash_config_t *config, uint32_t address); -#endif /* FSL_FEATURE_FLASH_HAS_PFLASH_BLOCK_SWAP */ - -#if defined(FSL_FEATURE_FLASH_HAS_SET_FLEXRAM_FUNCTION_CMD) && FSL_FEATURE_FLASH_HAS_SET_FLEXRAM_FUNCTION_CMD -/*! @brief Validates the gived flexram function option.*/ -static inline status_t flasn_check_flexram_function_option_range(flash_flexram_function_option_t option); -#endif /* FSL_FEATURE_FLASH_HAS_SET_FLEXRAM_FUNCTION_CMD */ - -/*! @brief Gets the flash protection information (region size, region count).*/ -static status_t flash_get_protection_info(flash_config_t *config, flash_protection_config_t *info); - -#if defined(FSL_FEATURE_FLASH_HAS_ACCESS_CONTROL) && FSL_FEATURE_FLASH_HAS_ACCESS_CONTROL -/*! @brief Gets the flash Execute-Only access information (Segment size, Segment count).*/ -static status_t flash_get_access_info(flash_config_t *config, flash_access_config_t *info); -#endif /* FSL_FEATURE_FLASH_HAS_ACCESS_CONTROL */ - -#if FLASH_CACHE_IS_CONTROLLED_BY_MCM -/*! @brief Performs the cache clear to the flash by MCM.*/ -void mcm_flash_cache_clear(flash_config_t *config); -#endif /* FLASH_CACHE_IS_CONTROLLED_BY_MCM */ - -#if FLASH_CACHE_IS_CONTROLLED_BY_FMC -/*! @brief Performs the cache clear to the flash by FMC.*/ -void fmc_flash_cache_clear(void); -#endif /* FLASH_CACHE_IS_CONTROLLED_BY_FMC */ - -#if FLASH_PREFETCH_SPECULATION_IS_CONTROLLED_BY_MSCM -/*! @brief Sets the prefetch speculation buffer to the flash by MSCM.*/ -void mscm_flash_prefetch_speculation_enable(bool enable); -#endif /* FLASH_PREFETCH_SPECULATION_IS_CONTROLLED_BY_MSCM */ - -#if FLASH_PREFETCH_SPECULATION_IS_CONTROLLED_BY_FMC -/*! @brief Performs the prefetch speculation buffer clear to the flash by FMC.*/ -void fmc_flash_prefetch_speculation_clear(void); -#endif /* FLASH_PREFETCH_SPECULATION_IS_CONTROLLED_BY_FMC */ - -/******************************************************************************* - * Variables - ******************************************************************************/ - -/*! @brief Access to FTFx->FCCOB */ -volatile uint32_t *const kFCCOBx = (volatile uint32_t *)&FTFx_FCCOB3_REG; -/*! @brief Access to FTFx->FPROT */ -volatile uint32_t *const kFPROTL = (volatile uint32_t *)&FTFx_FPROT_LOW_REG; -#if defined(FTFx_FPROT_HIGH_REG) -volatile uint32_t *const kFPROTH = (volatile uint32_t *)&FTFx_FPROT_HIGH_REG; -#endif - -#if FLASH_SSD_IS_SECONDARY_FLASH_ENABLED && FLASH_SSD_SECONDARY_FLASH_HAS_ITS_OWN_PROTECTION_REGISTER -volatile uint8_t *const kFPROTSL = (volatile uint8_t *)&FTFx_FPROTSL_REG; -volatile uint8_t *const kFPROTSH = (volatile uint8_t *)&FTFx_FPROTSH_REG; -#endif - -#if FLASH_DRIVER_IS_FLASH_RESIDENT -/*! @brief A function pointer used to point to relocated flash_run_command() */ -static void (*callFlashRunCommand)(FTFx_REG8_ACCESS_TYPE ftfx_fstat); -/*! @brief A function pointer used to point to relocated flash_common_bit_operation() */ -static void (*callFlashCommonBitOperation)(FTFx_REG32_ACCESS_TYPE base, - uint32_t bitMask, - uint32_t bitShift, - uint32_t bitValue); - -/*! - * @brief Position independent code of flash_run_command() - * - * Note1: The prototype of C function is shown as below: - * @code - * void flash_run_command(FTFx_REG8_ACCESS_TYPE ftfx_fstat) - * { - * // clear CCIF bit - * *ftfx_fstat = FTFx_FSTAT_CCIF_MASK; - * - * // Check CCIF bit of the flash status register, wait till it is set. - * // IP team indicates that this loop will always complete. - * while (!((*ftfx_fstat) & FTFx_FSTAT_CCIF_MASK)) - * { - * } - * } - * @endcode - * Note2: The binary code is generated by IAR 7.70.1 - */ -const static uint16_t s_flashRunCommandFunctionCode[] = { - 0x2180, /* MOVS R1, #128 ; 0x80 */ - 0x7001, /* STRB R1, [R0] */ - /* @4: */ - 0x7802, /* LDRB R2, [R0] */ - 0x420a, /* TST R2, R1 */ - 0xd0fc, /* BEQ.N @4 */ - 0x4770 /* BX LR */ -}; - -/*! - * @brief Position independent code of flash_common_bit_operation() - * - * Note1: The prototype of C function is shown as below: - * @code - * void flash_common_bit_operation(FTFx_REG32_ACCESS_TYPE base, uint32_t bitMask, uint32_t bitShift, uint32_t - * bitValue) - * { - * if (bitMask) - * { - * uint32_t value = (((uint32_t)(((uint32_t)(bitValue)) << bitShift)) & bitMask); - * *base = (*base & (~bitMask)) | value; - * } - * - * __ISB(); - * __DSB(); - * } - * @endcode - * Note2: The binary code is generated by IAR 7.70.1 - */ -const static uint16_t s_flashCommonBitOperationFunctionCode[] = { - 0xb510, /* PUSH {R4, LR} */ - 0x2900, /* CMP R1, #0 */ - 0xd005, /* BEQ.N @12 */ - 0x6804, /* LDR R4, [R0] */ - 0x438c, /* BICS R4, R4, R1 */ - 0x4093, /* LSLS R3, R3, R2 */ - 0x4019, /* ANDS R1, R1, R3 */ - 0x4321, /* ORRS R1, R1, R4 */ - 0x6001, /* STR R1, [R0] */ - /* @12: */ - 0xf3bf, 0x8f6f, /* ISB */ - 0xf3bf, 0x8f4f, /* DSB */ - 0xbd10 /* POP {R4, PC} */ -}; -#endif /* FLASH_DRIVER_IS_FLASH_RESIDENT */ - -#if (FLASH_DRIVER_IS_FLASH_RESIDENT && !FLASH_DRIVER_IS_EXPORTED) -/*! @brief A static buffer used to hold flash_run_command() */ -static uint32_t s_flashRunCommand[kFLASH_ExecuteInRamFunctionMaxSizeInWords]; -/*! @brief A static buffer used to hold flash_common_bit_operation() */ -static uint32_t s_flashCommonBitOperation[kFLASH_ExecuteInRamFunctionMaxSizeInWords]; -/*! @brief Flash execute-in-ram function information */ -static flash_execute_in_ram_function_config_t s_flashExecuteInRamFunctionInfo; -#endif - -/*! - * @brief Table of pflash sizes. - * - * The index into this table is the value of the SIM_FCFG1.PFSIZE bitfield. - * - * The values in this table have been right shifted 10 bits so that they will all fit within - * an 16-bit integer. To get the actual flash density, you must left shift the looked up value - * by 10 bits. - * - * Elements of this table have a value of 0 in cases where the PFSIZE bitfield value is - * reserved. - * - * Code to use the table: - * @code - * uint8_t pfsize = (SIM->FCFG1 & SIM_FCFG1_PFSIZE_MASK) >> SIM_FCFG1_PFSIZE_SHIFT; - * flashDensity = ((uint32_t)kPFlashDensities[pfsize]) << 10; - * @endcode - */ -#if (FLASH_MEMORY_SIZE_ENCODING_RULE == FLASH_MEMORY_SIZE_ENCODING_RULE_K1_2) -const uint16_t kPFlashDensities[] = { - 8, /* 0x0 - 8192, 8KB */ - 16, /* 0x1 - 16384, 16KB */ - 24, /* 0x2 - 24576, 24KB */ - 32, /* 0x3 - 32768, 32KB */ - 48, /* 0x4 - 49152, 48KB */ - 64, /* 0x5 - 65536, 64KB */ - 96, /* 0x6 - 98304, 96KB */ - 128, /* 0x7 - 131072, 128KB */ - 192, /* 0x8 - 196608, 192KB */ - 256, /* 0x9 - 262144, 256KB */ - 384, /* 0xa - 393216, 384KB */ - 512, /* 0xb - 524288, 512KB */ - 768, /* 0xc - 786432, 768KB */ - 1024, /* 0xd - 1048576, 1MB */ - 1536, /* 0xe - 1572864, 1.5MB */ - /* 2048, 0xf - 2097152, 2MB */ -}; -#elif(FLASH_MEMORY_SIZE_ENCODING_RULE == FLASH_MEMORY_SIZE_ENCODING_RULE_K3) -const uint16_t kPFlashDensities[] = { - 0, /* 0x0 - undefined */ - 0, /* 0x1 - undefined */ - 0, /* 0x2 - undefined */ - 0, /* 0x3 - undefined */ - 0, /* 0x4 - undefined */ - 0, /* 0x5 - undefined */ - 0, /* 0x6 - undefined */ - 0, /* 0x7 - undefined */ - 0, /* 0x8 - undefined */ - 0, /* 0x9 - undefined */ - 256, /* 0xa - 262144, 256KB */ - 0, /* 0xb - undefined */ - 1024, /* 0xc - 1048576, 1MB */ - 0, /* 0xd - undefined */ - 0, /* 0xe - undefined */ - 0, /* 0xf - undefined */ -}; -#endif - -/******************************************************************************* - * Code - ******************************************************************************/ - -status_t FLASH_Init(flash_config_t *config) -{ - if (config == NULL) - { - return kStatus_FLASH_InvalidArgument; - } - -#if FLASH_SSD_IS_SECONDARY_FLASH_ENABLED - if (config->FlashMemoryIndex == (uint8_t)kFLASH_MemoryIndexSecondaryFlash) - { -/* calculate the flash density from SIM_FCFG1.PFSIZE */ -#if defined(SIM_FCFG1_CORE1_PFSIZE_MASK) - uint32_t flashDensity; - uint8_t pfsize = (SIM->FCFG1 & SIM_FCFG1_CORE1_PFSIZE_MASK) >> SIM_FCFG1_CORE1_PFSIZE_SHIFT; - if (pfsize == 0xf) - { - flashDensity = FSL_FEATURE_FLASH_PFLASH_1_BLOCK_COUNT * FSL_FEATURE_FLASH_PFLASH_1_BLOCK_SIZE; - } - else - { - flashDensity = ((uint32_t)kPFlashDensities[pfsize]) << 10; - } - config->PFlashTotalSize = flashDensity; -#else - /* Unused code to solve MISRA-C issue*/ - config->PFlashBlockBase = kPFlashDensities[0]; - config->PFlashTotalSize = FSL_FEATURE_FLASH_PFLASH_1_BLOCK_COUNT * FSL_FEATURE_FLASH_PFLASH_1_BLOCK_SIZE; -#endif - config->PFlashBlockBase = FSL_FEATURE_FLASH_PFLASH_1_START_ADDRESS; - config->PFlashBlockCount = FSL_FEATURE_FLASH_PFLASH_1_BLOCK_COUNT; - config->PFlashSectorSize = FSL_FEATURE_FLASH_PFLASH_1_BLOCK_SECTOR_SIZE; - } - else -#endif /* FLASH_SSD_IS_SECONDARY_FLASH_ENABLED */ - { - uint32_t flashDensity; - -/* calculate the flash density from SIM_FCFG1.PFSIZE */ -#if defined(SIM_FCFG1_CORE0_PFSIZE_MASK) - uint8_t pfsize = (SIM->FCFG1 & SIM_FCFG1_CORE0_PFSIZE_MASK) >> SIM_FCFG1_CORE0_PFSIZE_SHIFT; -#elif defined(SIM_FCFG1_PFSIZE_MASK) - uint8_t pfsize = (SIM->FCFG1 & SIM_FCFG1_PFSIZE_MASK) >> SIM_FCFG1_PFSIZE_SHIFT; -#else -#error "Unknown flash size" -#endif - /* PFSIZE=0xf means that on customer parts the IFR was not correctly programmed. - * We just use the pre-defined flash size in feature file here to support pre-production parts */ - if (pfsize == 0xf) - { - flashDensity = FSL_FEATURE_FLASH_PFLASH_BLOCK_COUNT * FSL_FEATURE_FLASH_PFLASH_BLOCK_SIZE; - } - else - { - flashDensity = ((uint32_t)kPFlashDensities[pfsize]) << 10; - } - - /* fill out a few of the structure members */ - config->PFlashBlockBase = FSL_FEATURE_FLASH_PFLASH_START_ADDRESS; - config->PFlashTotalSize = flashDensity; - config->PFlashBlockCount = FSL_FEATURE_FLASH_PFLASH_BLOCK_COUNT; - config->PFlashSectorSize = FSL_FEATURE_FLASH_PFLASH_BLOCK_SECTOR_SIZE; - } - - { -#if defined(FSL_FEATURE_FLASH_HAS_ACCESS_CONTROL) && FSL_FEATURE_FLASH_HAS_ACCESS_CONTROL -#if FLASH_SSD_IS_SECONDARY_FLASH_ENABLED && FLASH_SSD_SECONDARY_FLASH_HAS_ITS_OWN_ACCESS_REGISTER - if (config->FlashMemoryIndex == (uint8_t)kFLASH_MemoryIndexSecondaryFlash) - { - config->PFlashAccessSegmentSize = kFLASH_AccessSegmentBase << FTFx->FACSSS; - config->PFlashAccessSegmentCount = FTFx->FACSNS; - } - else -#endif - { - config->PFlashAccessSegmentSize = kFLASH_AccessSegmentBase << FTFx->FACSS; - config->PFlashAccessSegmentCount = FTFx->FACSN; - } -#else - config->PFlashAccessSegmentSize = 0; - config->PFlashAccessSegmentCount = 0; -#endif /* FSL_FEATURE_FLASH_HAS_ACCESS_CONTROL */ - } - - config->PFlashCallback = NULL; - -/* copy required flash commands to RAM */ -#if (FLASH_DRIVER_IS_FLASH_RESIDENT && !FLASH_DRIVER_IS_EXPORTED) - if (kStatus_FLASH_Success != flash_check_execute_in_ram_function_info(config)) - { - s_flashExecuteInRamFunctionInfo.activeFunctionCount = 0; - s_flashExecuteInRamFunctionInfo.flashRunCommand = s_flashRunCommand; - s_flashExecuteInRamFunctionInfo.flashCommonBitOperation = s_flashCommonBitOperation; - config->flashExecuteInRamFunctionInfo = &s_flashExecuteInRamFunctionInfo.activeFunctionCount; - FLASH_PrepareExecuteInRamFunctions(config); - } -#endif - - config->FlexRAMBlockBase = FSL_FEATURE_FLASH_FLEX_RAM_START_ADDRESS; - config->FlexRAMTotalSize = FSL_FEATURE_FLASH_FLEX_RAM_SIZE; - -#if FLASH_SSD_IS_FLEXNVM_ENABLED - { - status_t returnCode; - config->DFlashBlockBase = FSL_FEATURE_FLASH_FLEX_NVM_START_ADDRESS; - returnCode = flash_update_flexnvm_memory_partition_status(config); - if (returnCode != kStatus_FLASH_Success) - { - return returnCode; - } - } -#endif - - return kStatus_FLASH_Success; -} - -status_t FLASH_SetCallback(flash_config_t *config, flash_callback_t callback) -{ - if (config == NULL) - { - return kStatus_FLASH_InvalidArgument; - } - - config->PFlashCallback = callback; - - return kStatus_FLASH_Success; -} - -#if FLASH_DRIVER_IS_FLASH_RESIDENT -status_t FLASH_PrepareExecuteInRamFunctions(flash_config_t *config) -{ - flash_execute_in_ram_function_config_t *flashExecuteInRamFunctionInfo; - - if (config == NULL) - { - return kStatus_FLASH_InvalidArgument; - } - - flashExecuteInRamFunctionInfo = (flash_execute_in_ram_function_config_t *)config->flashExecuteInRamFunctionInfo; - - copy_flash_run_command(flashExecuteInRamFunctionInfo->flashRunCommand); - copy_flash_common_bit_operation(flashExecuteInRamFunctionInfo->flashCommonBitOperation); - flashExecuteInRamFunctionInfo->activeFunctionCount = kFLASH_ExecuteInRamFunctionTotalNum; - - return kStatus_FLASH_Success; -} -#endif /* FLASH_DRIVER_IS_FLASH_RESIDENT */ - -status_t FLASH_EraseAll(flash_config_t *config, uint32_t key) -{ - status_t returnCode; - - if (config == NULL) - { - return kStatus_FLASH_InvalidArgument; - } - - /* preparing passing parameter to erase all flash blocks */ - kFCCOBx[0] = BYTES_JOIN_TO_WORD_1_3(FTFx_ERASE_ALL_BLOCK, 0xFFFFFFU); - - /* Validate the user key */ - returnCode = flash_check_user_key(key); - if (returnCode) - { - return returnCode; - } - - flash_cache_clear_process(config, kFLASH_CacheClearProcessPre); - - /* calling flash command sequence function to execute the command */ - returnCode = flash_command_sequence(config); - - flash_cache_clear(config); - -#if FLASH_SSD_IS_FLEXNVM_ENABLED - /* Data flash IFR will be erased by erase all command, so we need to - * update FlexNVM memory partition status synchronously */ - if (returnCode == kStatus_FLASH_Success) - { - returnCode = flash_update_flexnvm_memory_partition_status(config); - } -#endif - - return returnCode; -} - -status_t FLASH_Erase(flash_config_t *config, uint32_t start, uint32_t lengthInBytes, uint32_t key) -{ - uint32_t sectorSize; - flash_operation_config_t flashOperationInfo; - uint32_t endAddress; /* storing end address */ - uint32_t numberOfSectors; /* number of sectors calculated by endAddress */ - status_t returnCode; - - flash_get_matched_operation_info(config, start, &flashOperationInfo); - - /* Check the supplied address range. */ - returnCode = flash_check_range(config, start, lengthInBytes, flashOperationInfo.sectorCmdAddressAligment); - if (returnCode) - { - return returnCode; - } - - /* Validate the user key */ - returnCode = flash_check_user_key(key); - if (returnCode) - { - return returnCode; - } - - start = flashOperationInfo.convertedAddress; - sectorSize = flashOperationInfo.activeSectorSize; - - /* calculating Flash end address */ - endAddress = start + lengthInBytes - 1; - - /* re-calculate the endAddress and align it to the start of the next sector - * which will be used in the comparison below */ - if (endAddress % sectorSize) - { - numberOfSectors = endAddress / sectorSize + 1; - endAddress = numberOfSectors * sectorSize - 1; - } - - flash_cache_clear_process(config, kFLASH_CacheClearProcessPre); - - /* the start address will increment to the next sector address - * until it reaches the endAdddress */ - while (start <= endAddress) - { - /* preparing passing parameter to erase a flash block */ - kFCCOBx[0] = BYTES_JOIN_TO_WORD_1_3(FTFx_ERASE_SECTOR, start); - - /* calling flash command sequence function to execute the command */ - returnCode = flash_command_sequence(config); - - /* calling flash callback function if it is available */ - if (config->PFlashCallback) - { - config->PFlashCallback(); - } - - /* checking the success of command execution */ - if (kStatus_FLASH_Success != returnCode) - { - break; - } - else - { - /* Increment to the next sector */ - start += sectorSize; - } - } - - flash_cache_clear(config); - - return (returnCode); -} - -#if defined(FSL_FEATURE_FLASH_HAS_ERASE_ALL_BLOCKS_UNSECURE_CMD) && FSL_FEATURE_FLASH_HAS_ERASE_ALL_BLOCKS_UNSECURE_CMD -status_t FLASH_EraseAllUnsecure(flash_config_t *config, uint32_t key) -{ - status_t returnCode; - - if (config == NULL) - { - return kStatus_FLASH_InvalidArgument; - } - - /* Prepare passing parameter to erase all flash blocks (unsecure). */ - kFCCOBx[0] = BYTES_JOIN_TO_WORD_1_3(FTFx_ERASE_ALL_BLOCK_UNSECURE, 0xFFFFFFU); - - /* Validate the user key */ - returnCode = flash_check_user_key(key); - if (returnCode) - { - return returnCode; - } - - flash_cache_clear_process(config, kFLASH_CacheClearProcessPre); - - /* calling flash command sequence function to execute the command */ - returnCode = flash_command_sequence(config); - - flash_cache_clear(config); - -#if FLASH_SSD_IS_FLEXNVM_ENABLED - /* Data flash IFR will be erased by erase all unsecure command, so we need to - * update FlexNVM memory partition status synchronously */ - if (returnCode == kStatus_FLASH_Success) - { - returnCode = flash_update_flexnvm_memory_partition_status(config); - } -#endif - - return returnCode; -} -#endif /* FSL_FEATURE_FLASH_HAS_ERASE_ALL_BLOCKS_UNSECURE_CMD */ - -status_t FLASH_EraseAllExecuteOnlySegments(flash_config_t *config, uint32_t key) -{ - status_t returnCode; - - if (config == NULL) - { - return kStatus_FLASH_InvalidArgument; - } - - /* preparing passing parameter to erase all execute-only segments - * 1st element for the FCCOB register */ - kFCCOBx[0] = BYTES_JOIN_TO_WORD_1_3(FTFx_ERASE_ALL_EXECUTE_ONLY_SEGMENT, 0xFFFFFFU); - - /* Validate the user key */ - returnCode = flash_check_user_key(key); - if (returnCode) - { - return returnCode; - } - - flash_cache_clear_process(config, kFLASH_CacheClearProcessPre); - - /* calling flash command sequence function to execute the command */ - returnCode = flash_command_sequence(config); - - flash_cache_clear(config); - - return returnCode; -} - -status_t FLASH_Program(flash_config_t *config, uint32_t start, uint32_t *src, uint32_t lengthInBytes) -{ - status_t returnCode; - flash_operation_config_t flashOperationInfo; - - if (src == NULL) - { - return kStatus_FLASH_InvalidArgument; - } - - flash_get_matched_operation_info(config, start, &flashOperationInfo); - - /* Check the supplied address range. */ - returnCode = flash_check_range(config, start, lengthInBytes, flashOperationInfo.blockWriteUnitSize); - if (returnCode) - { - return returnCode; - } - - start = flashOperationInfo.convertedAddress; - - flash_cache_clear_process(config, kFLASH_CacheClearProcessPre); - - while (lengthInBytes > 0) - { - /* preparing passing parameter to program the flash block */ - kFCCOBx[1] = *src++; - if (4 == flashOperationInfo.blockWriteUnitSize) - { - kFCCOBx[0] = BYTES_JOIN_TO_WORD_1_3(FTFx_PROGRAM_LONGWORD, start); - } - else if (8 == flashOperationInfo.blockWriteUnitSize) - { - kFCCOBx[2] = *src++; - kFCCOBx[0] = BYTES_JOIN_TO_WORD_1_3(FTFx_PROGRAM_PHRASE, start); - } - else - { - } - - /* calling flash command sequence function to execute the command */ - returnCode = flash_command_sequence(config); - - /* calling flash callback function if it is available */ - if (config->PFlashCallback) - { - config->PFlashCallback(); - } - - /* checking for the success of command execution */ - if (kStatus_FLASH_Success != returnCode) - { - break; - } - else - { - /* update start address for next iteration */ - start += flashOperationInfo.blockWriteUnitSize; - - /* update lengthInBytes for next iteration */ - lengthInBytes -= flashOperationInfo.blockWriteUnitSize; - } - } - - flash_cache_clear(config); - - return (returnCode); -} - -status_t FLASH_ProgramOnce(flash_config_t *config, uint32_t index, uint32_t *src, uint32_t lengthInBytes) -{ - status_t returnCode; - - if ((config == NULL) || (src == NULL)) - { - return kStatus_FLASH_InvalidArgument; - } - - /* pass paramters to FTFx */ - kFCCOBx[0] = BYTES_JOIN_TO_WORD_1_1_2(FTFx_PROGRAM_ONCE, index, 0xFFFFU); - - kFCCOBx[1] = *src; - -/* Note: Have to seperate the first index from the rest if it equals 0 - * to avoid a pointless comparison of unsigned int to 0 compiler warning */ -#if FLASH_PROGRAM_ONCE_IS_8BYTES_UNIT_SUPPORT -#if FLASH_PROGRAM_ONCE_IS_4BYTES_UNIT_SUPPORT - if (((index == FLASH_PROGRAM_ONCE_MIN_ID_8BYTES) || - /* Range check */ - ((index >= FLASH_PROGRAM_ONCE_MIN_ID_8BYTES + 1) && (index <= FLASH_PROGRAM_ONCE_MAX_ID_8BYTES))) && - (lengthInBytes == 8)) -#endif /* FLASH_PROGRAM_ONCE_IS_4BYTES_UNIT_SUPPORT */ - { - kFCCOBx[2] = *(src + 1); - } -#endif /* FLASH_PROGRAM_ONCE_IS_8BYTES_UNIT_SUPPORT */ - - flash_cache_clear_process(config, kFLASH_CacheClearProcessPre); - - /* calling flash command sequence function to execute the command */ - returnCode = flash_command_sequence(config); - - flash_cache_clear(config); - - return returnCode; -} - -#if defined(FSL_FEATURE_FLASH_HAS_PROGRAM_SECTION_CMD) && FSL_FEATURE_FLASH_HAS_PROGRAM_SECTION_CMD -status_t FLASH_ProgramSection(flash_config_t *config, uint32_t start, uint32_t *src, uint32_t lengthInBytes) -{ - status_t returnCode; - uint32_t sectorSize; - flash_operation_config_t flashOperationInfo; -#if defined(FSL_FEATURE_FLASH_HAS_SET_FLEXRAM_FUNCTION_CMD) && FSL_FEATURE_FLASH_HAS_SET_FLEXRAM_FUNCTION_CMD - bool needSwitchFlexRamMode = false; -#endif /* FSL_FEATURE_FLASH_HAS_SET_FLEXRAM_FUNCTION_CMD */ - - if (src == NULL) - { - return kStatus_FLASH_InvalidArgument; - } - - flash_get_matched_operation_info(config, start, &flashOperationInfo); - - /* Check the supplied address range. */ - returnCode = flash_check_range(config, start, lengthInBytes, flashOperationInfo.sectionCmdAddressAligment); - if (returnCode) - { - return returnCode; - } - - start = flashOperationInfo.convertedAddress; - sectorSize = flashOperationInfo.activeSectorSize; - -#if defined(FSL_FEATURE_FLASH_HAS_SET_FLEXRAM_FUNCTION_CMD) && FSL_FEATURE_FLASH_HAS_SET_FLEXRAM_FUNCTION_CMD - /* Switch function of FlexRAM if needed */ - if (!(FTFx->FCNFG & FTFx_FCNFG_RAMRDY_MASK)) - { - needSwitchFlexRamMode = true; - - returnCode = FLASH_SetFlexramFunction(config, kFLASH_FlexramFunctionOptionAvailableAsRam); - if (returnCode != kStatus_FLASH_Success) - { - return kStatus_FLASH_SetFlexramAsRamError; - } - } -#endif /* FSL_FEATURE_FLASH_HAS_SET_FLEXRAM_FUNCTION_CMD */ - - flash_cache_clear_process(config, kFLASH_CacheClearProcessPre); - - while (lengthInBytes > 0) - { - /* Make sure the write operation doesn't span two sectors */ - uint32_t endAddressOfCurrentSector = ALIGN_UP(start, sectorSize); - uint32_t lengthTobeProgrammedOfCurrentSector; - uint32_t currentOffset = 0; - - if (endAddressOfCurrentSector == start) - { - endAddressOfCurrentSector += sectorSize; - } - - if (lengthInBytes + start > endAddressOfCurrentSector) - { - lengthTobeProgrammedOfCurrentSector = endAddressOfCurrentSector - start; - } - else - { - lengthTobeProgrammedOfCurrentSector = lengthInBytes; - } - - /* Program Current Sector */ - while (lengthTobeProgrammedOfCurrentSector > 0) - { - /* Make sure the program size doesn't exceeds Acceleration RAM size */ - uint32_t programSizeOfCurrentPass; - uint32_t numberOfPhases; - - if (lengthTobeProgrammedOfCurrentSector > kFLASH_AccelerationRamSize) - { - programSizeOfCurrentPass = kFLASH_AccelerationRamSize; - } - else - { - programSizeOfCurrentPass = lengthTobeProgrammedOfCurrentSector; - } - - /* Copy data to FlexRAM */ - memcpy((void *)FSL_FEATURE_FLASH_FLEX_RAM_START_ADDRESS, src + currentOffset / 4, programSizeOfCurrentPass); - /* Set start address of the data to be programmed */ - kFCCOBx[0] = BYTES_JOIN_TO_WORD_1_3(FTFx_PROGRAM_SECTION, start + currentOffset); - /* Set program size in terms of FEATURE_FLASH_SECTION_CMD_ADDRESS_ALIGMENT */ - numberOfPhases = programSizeOfCurrentPass / flashOperationInfo.sectionCmdAddressAligment; - - kFCCOBx[1] = BYTES_JOIN_TO_WORD_2_2(numberOfPhases, 0xFFFFU); - - /* Peform command sequence */ - returnCode = flash_command_sequence(config); - - /* calling flash callback function if it is available */ - if (config->PFlashCallback) - { - config->PFlashCallback(); - } - - if (returnCode != kStatus_FLASH_Success) - { - flash_cache_clear(config); - return returnCode; - } - - lengthTobeProgrammedOfCurrentSector -= programSizeOfCurrentPass; - currentOffset += programSizeOfCurrentPass; - } - - src += currentOffset / 4; - start += currentOffset; - lengthInBytes -= currentOffset; - } - - flash_cache_clear(config); - -#if defined(FSL_FEATURE_FLASH_HAS_SET_FLEXRAM_FUNCTION_CMD) && FSL_FEATURE_FLASH_HAS_SET_FLEXRAM_FUNCTION_CMD - /* Restore function of FlexRAM if needed. */ - if (needSwitchFlexRamMode) - { - returnCode = FLASH_SetFlexramFunction(config, kFLASH_FlexramFunctionOptionAvailableForEeprom); - if (returnCode != kStatus_FLASH_Success) - { - return kStatus_FLASH_RecoverFlexramAsEepromError; - } - } -#endif /* FSL_FEATURE_FLASH_HAS_SET_FLEXRAM_FUNCTION_CMD */ - - return returnCode; -} -#endif /* FSL_FEATURE_FLASH_HAS_PROGRAM_SECTION_CMD */ - -#if FLASH_SSD_IS_FLEXNVM_ENABLED -status_t FLASH_EepromWrite(flash_config_t *config, uint32_t start, uint8_t *src, uint32_t lengthInBytes) -{ - status_t returnCode; - bool needSwitchFlexRamMode = false; - - if (config == NULL) - { - return kStatus_FLASH_InvalidArgument; - } - - /* Validates the range of the given address */ - if ((start < config->FlexRAMBlockBase) || - ((start + lengthInBytes) > (config->FlexRAMBlockBase + config->EEpromTotalSize))) - { - return kStatus_FLASH_AddressError; - } - - returnCode = kStatus_FLASH_Success; - - /* Switch function of FlexRAM if needed */ - if (!(FTFx->FCNFG & FTFx_FCNFG_EEERDY_MASK)) - { - needSwitchFlexRamMode = true; - - returnCode = FLASH_SetFlexramFunction(config, kFLASH_FlexramFunctionOptionAvailableForEeprom); - if (returnCode != kStatus_FLASH_Success) - { - return kStatus_FLASH_SetFlexramAsEepromError; - } - } - - /* Write data to FlexRAM when it is used as EEPROM emulator */ - while (lengthInBytes > 0) - { - if ((!(start & 0x3U)) && (lengthInBytes >= 4)) - { - *(uint32_t *)start = *(uint32_t *)src; - start += 4; - src += 4; - lengthInBytes -= 4; - } - else if ((!(start & 0x1U)) && (lengthInBytes >= 2)) - { - *(uint16_t *)start = *(uint16_t *)src; - start += 2; - src += 2; - lengthInBytes -= 2; - } - else - { - *(uint8_t *)start = *src; - start += 1; - src += 1; - lengthInBytes -= 1; - } - /* Wait till EEERDY bit is set */ - while (!(FTFx->FCNFG & FTFx_FCNFG_EEERDY_MASK)) - { - } - - /* Check for protection violation error */ - if (FTFx->FSTAT & FTFx_FSTAT_FPVIOL_MASK) - { - return kStatus_FLASH_ProtectionViolation; - } - } - - /* Switch function of FlexRAM if needed */ - if (needSwitchFlexRamMode) - { - returnCode = FLASH_SetFlexramFunction(config, kFLASH_FlexramFunctionOptionAvailableAsRam); - if (returnCode != kStatus_FLASH_Success) - { - return kStatus_FLASH_RecoverFlexramAsRamError; - } - } - - return returnCode; -} -#endif /* FLASH_SSD_IS_FLEXNVM_ENABLED */ - -#if defined(FSL_FEATURE_FLASH_HAS_READ_RESOURCE_CMD) && FSL_FEATURE_FLASH_HAS_READ_RESOURCE_CMD -status_t FLASH_ReadResource( - flash_config_t *config, uint32_t start, uint32_t *dst, uint32_t lengthInBytes, flash_read_resource_option_t option) -{ - status_t returnCode; - flash_operation_config_t flashOperationInfo; - - if ((config == NULL) || (dst == NULL)) - { - return kStatus_FLASH_InvalidArgument; - } - - flash_get_matched_operation_info(config, start, &flashOperationInfo); - - /* Check the supplied address range. */ - returnCode = - flash_check_resource_range(start, lengthInBytes, flashOperationInfo.resourceCmdAddressAligment, option); - if (returnCode != kStatus_FLASH_Success) - { - return returnCode; - } - - while (lengthInBytes > 0) - { - /* preparing passing parameter */ - kFCCOBx[0] = BYTES_JOIN_TO_WORD_1_3(FTFx_READ_RESOURCE, start); - if (flashOperationInfo.resourceCmdAddressAligment == 4) - { - kFCCOBx[2] = BYTES_JOIN_TO_WORD_1_3(option, 0xFFFFFFU); - } - else if (flashOperationInfo.resourceCmdAddressAligment == 8) - { - kFCCOBx[1] = BYTES_JOIN_TO_WORD_1_3(option, 0xFFFFFFU); - } - else - { - } - - /* calling flash command sequence function to execute the command */ - returnCode = flash_command_sequence(config); - - if (kStatus_FLASH_Success != returnCode) - { - break; - } - - /* fetch data */ - *dst++ = kFCCOBx[1]; - if (flashOperationInfo.resourceCmdAddressAligment == 8) - { - *dst++ = kFCCOBx[2]; - } - /* update start address for next iteration */ - start += flashOperationInfo.resourceCmdAddressAligment; - /* update lengthInBytes for next iteration */ - lengthInBytes -= flashOperationInfo.resourceCmdAddressAligment; - } - - return (returnCode); -} -#endif /* FSL_FEATURE_FLASH_HAS_READ_RESOURCE_CMD */ - -status_t FLASH_ReadOnce(flash_config_t *config, uint32_t index, uint32_t *dst, uint32_t lengthInBytes) -{ - status_t returnCode; - - if ((config == NULL) || (dst == NULL)) - { - return kStatus_FLASH_InvalidArgument; - } - - /* pass paramters to FTFx */ - kFCCOBx[0] = BYTES_JOIN_TO_WORD_1_1_2(FTFx_READ_ONCE, index, 0xFFFFU); - - /* calling flash command sequence function to execute the command */ - returnCode = flash_command_sequence(config); - - if (kStatus_FLASH_Success == returnCode) - { - *dst = kFCCOBx[1]; -/* Note: Have to seperate the first index from the rest if it equals 0 - * to avoid a pointless comparison of unsigned int to 0 compiler warning */ -#if FLASH_PROGRAM_ONCE_IS_8BYTES_UNIT_SUPPORT -#if FLASH_PROGRAM_ONCE_IS_4BYTES_UNIT_SUPPORT - if (((index == FLASH_PROGRAM_ONCE_MIN_ID_8BYTES) || - /* Range check */ - ((index >= FLASH_PROGRAM_ONCE_MIN_ID_8BYTES + 1) && (index <= FLASH_PROGRAM_ONCE_MAX_ID_8BYTES))) && - (lengthInBytes == 8)) -#endif /* FLASH_PROGRAM_ONCE_IS_4BYTES_UNIT_SUPPORT */ - { - *(dst + 1) = kFCCOBx[2]; - } -#endif /* FLASH_PROGRAM_ONCE_IS_8BYTES_UNIT_SUPPORT */ - } - - return returnCode; -} - -status_t FLASH_GetSecurityState(flash_config_t *config, flash_security_state_t *state) -{ - /* store data read from flash register */ - uint8_t registerValue; - - if ((config == NULL) || (state == NULL)) - { - return kStatus_FLASH_InvalidArgument; - } - - /* Get flash security register value */ - registerValue = FTFx->FSEC; - - /* check the status of the flash security bits in the security register */ - if (FLASH_SECURITY_STATE_UNSECURED == (registerValue & FTFx_FSEC_SEC_MASK)) - { - /* Flash in unsecured state */ - *state = kFLASH_SecurityStateNotSecure; - } - else - { - /* Flash in secured state - * check for backdoor key security enable bit */ - if (FLASH_SECURITY_STATE_KEYEN == (registerValue & FTFx_FSEC_KEYEN_MASK)) - { - /* Backdoor key security enabled */ - *state = kFLASH_SecurityStateBackdoorEnabled; - } - else - { - /* Backdoor key security disabled */ - *state = kFLASH_SecurityStateBackdoorDisabled; - } - } - - return (kStatus_FLASH_Success); -} - -status_t FLASH_SecurityBypass(flash_config_t *config, const uint8_t *backdoorKey) -{ - uint8_t registerValue; /* registerValue */ - status_t returnCode; /* return code variable */ - - if ((config == NULL) || (backdoorKey == NULL)) - { - return kStatus_FLASH_InvalidArgument; - } - - /* set the default return code as kStatus_Success */ - returnCode = kStatus_FLASH_Success; - - /* Get flash security register value */ - registerValue = FTFx->FSEC; - - /* Check to see if flash is in secure state (any state other than 0x2) - * If not, then skip this since flash is not secure */ - if (0x02 != (registerValue & 0x03)) - { - /* preparing passing parameter to erase a flash block */ - kFCCOBx[0] = BYTES_JOIN_TO_WORD_1_3(FTFx_SECURITY_BY_PASS, 0xFFFFFFU); - kFCCOBx[1] = BYTES_JOIN_TO_WORD_1_1_1_1(backdoorKey[0], backdoorKey[1], backdoorKey[2], backdoorKey[3]); - kFCCOBx[2] = BYTES_JOIN_TO_WORD_1_1_1_1(backdoorKey[4], backdoorKey[5], backdoorKey[6], backdoorKey[7]); - - /* calling flash command sequence function to execute the command */ - returnCode = flash_command_sequence(config); - } - - return (returnCode); -} - -status_t FLASH_VerifyEraseAll(flash_config_t *config, flash_margin_value_t margin) -{ - if (config == NULL) - { - return kStatus_FLASH_InvalidArgument; - } - - /* preparing passing parameter to verify all block command */ - kFCCOBx[0] = BYTES_JOIN_TO_WORD_1_1_2(FTFx_VERIFY_ALL_BLOCK, margin, 0xFFFFU); - - /* calling flash command sequence function to execute the command */ - return flash_command_sequence(config); -} - -status_t FLASH_VerifyErase(flash_config_t *config, uint32_t start, uint32_t lengthInBytes, flash_margin_value_t margin) -{ - /* Check arguments. */ - uint32_t blockSize; - flash_operation_config_t flashOperationInfo; - uint32_t nextBlockStartAddress; - uint32_t remainingBytes; - status_t returnCode; - - flash_get_matched_operation_info(config, start, &flashOperationInfo); - - returnCode = flash_check_range(config, start, lengthInBytes, flashOperationInfo.sectionCmdAddressAligment); - if (returnCode) - { - return returnCode; - } - - flash_get_matched_operation_info(config, start, &flashOperationInfo); - start = flashOperationInfo.convertedAddress; - blockSize = flashOperationInfo.activeBlockSize; - - nextBlockStartAddress = ALIGN_UP(start, blockSize); - if (nextBlockStartAddress == start) - { - nextBlockStartAddress += blockSize; - } - - remainingBytes = lengthInBytes; - - while (remainingBytes) - { - uint32_t numberOfPhrases; - uint32_t verifyLength = nextBlockStartAddress - start; - if (verifyLength > remainingBytes) - { - verifyLength = remainingBytes; - } - - numberOfPhrases = verifyLength / flashOperationInfo.sectionCmdAddressAligment; - - /* Fill in verify section command parameters. */ - kFCCOBx[0] = BYTES_JOIN_TO_WORD_1_3(FTFx_VERIFY_SECTION, start); - kFCCOBx[1] = BYTES_JOIN_TO_WORD_2_1_1(numberOfPhrases, margin, 0xFFU); - - /* calling flash command sequence function to execute the command */ - returnCode = flash_command_sequence(config); - if (returnCode) - { - return returnCode; - } - - remainingBytes -= verifyLength; - start += verifyLength; - nextBlockStartAddress += blockSize; - } - - return kStatus_FLASH_Success; -} - -status_t FLASH_VerifyProgram(flash_config_t *config, - uint32_t start, - uint32_t lengthInBytes, - const uint32_t *expectedData, - flash_margin_value_t margin, - uint32_t *failedAddress, - uint32_t *failedData) -{ - status_t returnCode; - flash_operation_config_t flashOperationInfo; - - if (expectedData == NULL) - { - return kStatus_FLASH_InvalidArgument; - } - - flash_get_matched_operation_info(config, start, &flashOperationInfo); - - returnCode = flash_check_range(config, start, lengthInBytes, flashOperationInfo.checkCmdAddressAligment); - if (returnCode) - { - return returnCode; - } - - start = flashOperationInfo.convertedAddress; - - while (lengthInBytes) - { - /* preparing passing parameter to program check the flash block */ - kFCCOBx[0] = BYTES_JOIN_TO_WORD_1_3(FTFx_PROGRAM_CHECK, start); - kFCCOBx[1] = BYTES_JOIN_TO_WORD_1_3(margin, 0xFFFFFFU); - kFCCOBx[2] = *expectedData; - - /* calling flash command sequence function to execute the command */ - returnCode = flash_command_sequence(config); - - /* checking for the success of command execution */ - if (kStatus_FLASH_Success != returnCode) - { - if (failedAddress) - { - *failedAddress = start; - } - if (failedData) - { - *failedData = 0; - } - break; - } - - lengthInBytes -= flashOperationInfo.checkCmdAddressAligment; - expectedData += flashOperationInfo.checkCmdAddressAligment / sizeof(*expectedData); - start += flashOperationInfo.checkCmdAddressAligment; - } - - return (returnCode); -} - -status_t FLASH_VerifyEraseAllExecuteOnlySegments(flash_config_t *config, flash_margin_value_t margin) -{ - if (config == NULL) - { - return kStatus_FLASH_InvalidArgument; - } - - /* preparing passing parameter to verify erase all execute-only segments command */ - kFCCOBx[0] = BYTES_JOIN_TO_WORD_1_1_2(FTFx_VERIFY_ALL_EXECUTE_ONLY_SEGMENT, margin, 0xFFFFU); - - /* calling flash command sequence function to execute the command */ - return flash_command_sequence(config); -} - -status_t FLASH_IsProtected(flash_config_t *config, - uint32_t start, - uint32_t lengthInBytes, - flash_protection_state_t *protection_state) -{ - uint32_t endAddress; /* end address for protection check */ - uint32_t regionCheckedCounter; /* increments each time the flash address was checked for - * protection status */ - uint32_t regionCounter; /* incrementing variable used to increment through the flash - * protection regions */ - uint32_t protectStatusCounter; /* increments each time a flash region was detected as protected */ - - uint8_t flashRegionProtectStatus[FSL_FEATURE_FLASH_PFLASH_PROTECTION_REGION_COUNT]; /* array of the protection - * status for each - * protection region */ - uint32_t flashRegionAddress[FSL_FEATURE_FLASH_PFLASH_PROTECTION_REGION_COUNT + - 1]; /* array of the start addresses for each flash - * protection region. Note this is REGION_COUNT+1 - * due to requiring the next start address after - * the end of flash for loop-check purposes below */ - flash_protection_config_t flashProtectionInfo; /* flash protection information */ - status_t returnCode; - - if (protection_state == NULL) - { - return kStatus_FLASH_InvalidArgument; - } - - /* Check the supplied address range. */ - returnCode = flash_check_range(config, start, lengthInBytes, FSL_FEATURE_FLASH_PFLASH_BLOCK_WRITE_UNIT_SIZE); - if (returnCode) - { - return returnCode; - } - - /* Get necessary flash protection information. */ - returnCode = flash_get_protection_info(config, &flashProtectionInfo); - if (returnCode) - { - return returnCode; - } - - /* calculating Flash end address */ - endAddress = start + lengthInBytes; - - /* populate the flashRegionAddress array with the start address of each flash region */ - regionCounter = 0; /* make sure regionCounter is initialized to 0 first */ - - /* populate up to 33rd element of array, this is the next address after end of flash array */ - while (regionCounter <= flashProtectionInfo.regionCount) - { - flashRegionAddress[regionCounter] = - flashProtectionInfo.regionBase + flashProtectionInfo.regionSize * regionCounter; - regionCounter++; - } - - /* populate flashRegionProtectStatus array with status information - * Protection status for each region is stored in the FPROT[3:0] registers - * Each bit represents one region of flash - * 4 registers * 8-bits-per-register = 32-bits (32-regions) - * The convention is: - * FPROT3[bit 0] is the first protection region (start of flash memory) - * FPROT0[bit 7] is the last protection region (end of flash memory) - * regionCounter is used to determine which FPROT[3:0] register to check for protection status - * Note: FPROT=1 means NOT protected, FPROT=0 means protected */ - regionCounter = 0; /* make sure regionCounter is initialized to 0 first */ - while (regionCounter < flashProtectionInfo.regionCount) - { -#if FLASH_SSD_IS_SECONDARY_FLASH_ENABLED && FLASH_SSD_SECONDARY_FLASH_HAS_ITS_OWN_PROTECTION_REGISTER - if (config->FlashMemoryIndex == (uint8_t)kFLASH_MemoryIndexSecondaryFlash) - { - if (regionCounter < 8) - { - flashRegionProtectStatus[regionCounter] = (FTFx_FPROTSL_REG >> regionCounter) & (0x01u); - } - else if ((regionCounter >= 8) && (regionCounter < 16)) - { - flashRegionProtectStatus[regionCounter] = (FTFx_FPROTSH_REG >> (regionCounter - 8)) & (0x01u); - } - else - { - break; - } - } - else -#endif - { - /* Note: So far protection region count may be 16/20/24/32/64 */ - if (regionCounter < 8) - { - flashRegionProtectStatus[regionCounter] = (FTFx_FPROTL3_REG >> regionCounter) & (0x01u); - } - else if ((regionCounter >= 8) && (regionCounter < 16)) - { - flashRegionProtectStatus[regionCounter] = (FTFx_FPROTL2_REG >> (regionCounter - 8)) & (0x01u); - } -#if defined(FSL_FEATURE_FLASH_PFLASH_PROTECTION_REGION_COUNT) && (FSL_FEATURE_FLASH_PFLASH_PROTECTION_REGION_COUNT > 16) -#if (FSL_FEATURE_FLASH_PFLASH_PROTECTION_REGION_COUNT == 20) - else if ((regionCounter >= 16) && (regionCounter < 20)) - { - flashRegionProtectStatus[regionCounter] = (FTFx_FPROTL1_REG >> (regionCounter - 16)) & (0x01u); - } -#else - else if ((regionCounter >= 16) && (regionCounter < 24)) - { - flashRegionProtectStatus[regionCounter] = (FTFx_FPROTL1_REG >> (regionCounter - 16)) & (0x01u); - } -#endif /* (FSL_FEATURE_FLASH_PFLASH_PROTECTION_REGION_COUNT == 20) */ -#endif -#if defined(FSL_FEATURE_FLASH_PFLASH_PROTECTION_REGION_COUNT) && (FSL_FEATURE_FLASH_PFLASH_PROTECTION_REGION_COUNT > 24) - else if ((regionCounter >= 24) && (regionCounter < 32)) - { - flashRegionProtectStatus[regionCounter] = (FTFx_FPROTL0_REG >> (regionCounter - 24)) & (0x01u); - } -#endif -#if defined(FSL_FEATURE_FLASH_PFLASH_PROTECTION_REGION_COUNT) && \ - (FSL_FEATURE_FLASH_PFLASH_PROTECTION_REGION_COUNT == 64) - else if (regionCounter < 40) - { - flashRegionProtectStatus[regionCounter] = (FTFx_FPROTH3_REG >> (regionCounter - 32)) & (0x01u); - } - else if (regionCounter < 48) - { - flashRegionProtectStatus[regionCounter] = (FTFx_FPROTH2_REG >> (regionCounter - 40)) & (0x01u); - } - else if (regionCounter < 56) - { - flashRegionProtectStatus[regionCounter] = (FTFx_FPROTH1_REG >> (regionCounter - 48)) & (0x01u); - } - else if (regionCounter < 64) - { - flashRegionProtectStatus[regionCounter] = (FTFx_FPROTH0_REG >> (regionCounter - 56)) & (0x01u); - } -#endif - else - { - break; - } - } - - regionCounter++; - } - - /* loop through the flash regions and check - * desired flash address range for protection status - * loop stops when it is detected that start has exceeded the endAddress */ - regionCounter = 0; /* make sure regionCounter is initialized to 0 first */ - regionCheckedCounter = 0; - protectStatusCounter = 0; /* make sure protectStatusCounter is initialized to 0 first */ - while (start < endAddress) - { - /* check to see if the address falls within this protection region - * Note that if the entire flash is to be checked, the last protection - * region checked would consist of the last protection start address and - * the start address following the end of flash */ - if ((start >= flashRegionAddress[regionCounter]) && (start < flashRegionAddress[regionCounter + 1])) - { - /* increment regionCheckedCounter to indicate this region was checked */ - regionCheckedCounter++; - - /* check the protection status of this region - * Note: FPROT=1 means NOT protected, FPROT=0 means protected */ - if (!flashRegionProtectStatus[regionCounter]) - { - /* increment protectStatusCounter to indicate this region is protected */ - protectStatusCounter++; - } - start += flashProtectionInfo.regionSize; /* increment to an address within the next region */ - } - regionCounter++; /* increment regionCounter to check for the next flash protection region */ - } - - /* if protectStatusCounter == 0, then no region of the desired flash region is protected */ - if (protectStatusCounter == 0) - { - *protection_state = kFLASH_ProtectionStateUnprotected; - } - /* if protectStatusCounter == regionCheckedCounter, then each region checked was protected */ - else if (protectStatusCounter == regionCheckedCounter) - { - *protection_state = kFLASH_ProtectionStateProtected; - } - /* if protectStatusCounter != regionCheckedCounter, then protection status is mixed - * In other words, some regions are protected while others are unprotected */ - else - { - *protection_state = kFLASH_ProtectionStateMixed; - } - - return (returnCode); -} - -status_t FLASH_IsExecuteOnly(flash_config_t *config, - uint32_t start, - uint32_t lengthInBytes, - flash_execute_only_access_state_t *access_state) -{ -#if defined(FSL_FEATURE_FLASH_HAS_ACCESS_CONTROL) && FSL_FEATURE_FLASH_HAS_ACCESS_CONTROL - flash_access_config_t flashAccessInfo; /* flash Execute-Only information */ -#endif /* FSL_FEATURE_FLASH_HAS_ACCESS_CONTROL */ - status_t returnCode; - - if (access_state == NULL) - { - return kStatus_FLASH_InvalidArgument; - } - - /* Check the supplied address range. */ - returnCode = flash_check_range(config, start, lengthInBytes, FSL_FEATURE_FLASH_PFLASH_BLOCK_WRITE_UNIT_SIZE); - if (returnCode) - { - return returnCode; - } - -#if defined(FSL_FEATURE_FLASH_HAS_ACCESS_CONTROL) && FSL_FEATURE_FLASH_HAS_ACCESS_CONTROL - /* Get necessary flash Execute-Only information. */ - returnCode = flash_get_access_info(config, &flashAccessInfo); - if (returnCode) - { - return returnCode; - } - - { - uint32_t executeOnlySegmentCounter = 0; - - /* calculating end address */ - uint32_t endAddress = start + lengthInBytes; - - /* Aligning start address and end address */ - uint32_t alignedStartAddress = ALIGN_DOWN(start, flashAccessInfo.SegmentSize); - uint32_t alignedEndAddress = ALIGN_UP(endAddress, flashAccessInfo.SegmentSize); - - uint32_t segmentIndex = 0; - uint32_t maxSupportedExecuteOnlySegmentCount = - (alignedEndAddress - alignedStartAddress) / flashAccessInfo.SegmentSize; - - while (start < endAddress) - { - uint32_t xacc; - - segmentIndex = (start - flashAccessInfo.SegmentBase) / flashAccessInfo.SegmentSize; - -#if FLASH_SSD_IS_SECONDARY_FLASH_ENABLED && FLASH_SSD_SECONDARY_FLASH_HAS_ITS_OWN_ACCESS_REGISTER - if (config->FlashMemoryIndex == (uint8_t)kFLASH_MemoryIndexSecondaryFlash) - { - /* For secondary flash, The two XACCS registers allow up to 16 restricted segments of equal memory size. - */ - if (segmentIndex < 8) - { - xacc = *(const volatile uint8_t *)&FTFx_XACCSL_REG; - } - else if (segmentIndex < flashAccessInfo.SegmentCount) - { - xacc = *(const volatile uint8_t *)&FTFx_XACCSH_REG; - segmentIndex -= 8; - } - else - { - break; - } - } - else -#endif - { - /* For primary flash, The eight XACC registers allow up to 64 restricted segments of equal memory size. - */ - if (segmentIndex < 32) - { - xacc = *(const volatile uint32_t *)&FTFx_XACCL3_REG; - } - else if (segmentIndex < flashAccessInfo.SegmentCount) - { - xacc = *(const volatile uint32_t *)&FTFx_XACCH3_REG; - segmentIndex -= 32; - } - else - { - break; - } - } - - /* Determine if this address range is in a execute-only protection flash segment. */ - if ((~xacc) & (1u << segmentIndex)) - { - executeOnlySegmentCounter++; - } - - start += flashAccessInfo.SegmentSize; - } - - if (executeOnlySegmentCounter < 1u) - { - *access_state = kFLASH_AccessStateUnLimited; - } - else if (executeOnlySegmentCounter < maxSupportedExecuteOnlySegmentCount) - { - *access_state = kFLASH_AccessStateMixed; - } - else - { - *access_state = kFLASH_AccessStateExecuteOnly; - } - } -#else - *access_state = kFLASH_AccessStateUnLimited; -#endif /* FSL_FEATURE_FLASH_HAS_ACCESS_CONTROL */ - - return (returnCode); -} - -status_t FLASH_GetProperty(flash_config_t *config, flash_property_tag_t whichProperty, uint32_t *value) -{ - if ((config == NULL) || (value == NULL)) - { - return kStatus_FLASH_InvalidArgument; - } - - switch (whichProperty) - { - case kFLASH_PropertyPflashSectorSize: - *value = config->PFlashSectorSize; - break; - - case kFLASH_PropertyPflashTotalSize: - *value = config->PFlashTotalSize; - break; - - case kFLASH_PropertyPflashBlockSize: - *value = config->PFlashTotalSize / FSL_FEATURE_FLASH_PFLASH_BLOCK_COUNT; - break; - - case kFLASH_PropertyPflashBlockCount: - *value = (uint32_t)config->PFlashBlockCount; - break; - - case kFLASH_PropertyPflashBlockBaseAddr: - *value = config->PFlashBlockBase; - break; - - case kFLASH_PropertyPflashFacSupport: -#if defined(FSL_FEATURE_FLASH_HAS_ACCESS_CONTROL) - *value = FSL_FEATURE_FLASH_HAS_ACCESS_CONTROL; -#else - *value = 0; -#endif /* FSL_FEATURE_FLASH_HAS_ACCESS_CONTROL */ - break; - - case kFLASH_PropertyPflashAccessSegmentSize: - *value = config->PFlashAccessSegmentSize; - break; - - case kFLASH_PropertyPflashAccessSegmentCount: - *value = config->PFlashAccessSegmentCount; - break; - - case kFLASH_PropertyFlexRamBlockBaseAddr: - *value = config->FlexRAMBlockBase; - break; - - case kFLASH_PropertyFlexRamTotalSize: - *value = config->FlexRAMTotalSize; - break; - -#if FLASH_SSD_IS_FLEXNVM_ENABLED - case kFLASH_PropertyDflashSectorSize: - *value = FSL_FEATURE_FLASH_FLEX_NVM_BLOCK_SECTOR_SIZE; - break; - case kFLASH_PropertyDflashTotalSize: - *value = config->DFlashTotalSize; - break; - case kFLASH_PropertyDflashBlockSize: - *value = FSL_FEATURE_FLASH_FLEX_NVM_BLOCK_SIZE; - break; - case kFLASH_PropertyDflashBlockCount: - *value = FSL_FEATURE_FLASH_FLEX_NVM_BLOCK_COUNT; - break; - case kFLASH_PropertyDflashBlockBaseAddr: - *value = config->DFlashBlockBase; - break; - case kFLASH_PropertyEepromTotalSize: - *value = config->EEpromTotalSize; - break; -#endif /* FLASH_SSD_IS_FLEXNVM_ENABLED */ - - default: /* catch inputs that are not recognized */ - return kStatus_FLASH_UnknownProperty; - } - - return kStatus_FLASH_Success; -} - -status_t FLASH_SetProperty(flash_config_t *config, flash_property_tag_t whichProperty, uint32_t value) -{ - status_t status = kStatus_FLASH_Success; - - if (config == NULL) - { - return kStatus_FLASH_InvalidArgument; - } - - switch (whichProperty) - { -#if FLASH_SSD_IS_SECONDARY_FLASH_ENABLED - case kFLASH_PropertyFlashMemoryIndex: - if ((value != (uint32_t)kFLASH_MemoryIndexPrimaryFlash) && - (value != (uint32_t)kFLASH_MemoryIndexSecondaryFlash)) - { - return kStatus_FLASH_InvalidPropertyValue; - } - config->FlashMemoryIndex = (uint8_t)value; - break; -#endif /* FLASH_SSD_IS_SECONDARY_FLASH_ENABLED */ - - case kFLASH_PropertyFlashCacheControllerIndex: - if ((value != (uint32_t)kFLASH_CacheControllerIndexForCore0) && - (value != (uint32_t)kFLASH_CacheControllerIndexForCore1)) - { - return kStatus_FLASH_InvalidPropertyValue; - } - config->FlashCacheControllerIndex = (uint8_t)value; - break; - - case kFLASH_PropertyPflashSectorSize: - case kFLASH_PropertyPflashTotalSize: - case kFLASH_PropertyPflashBlockSize: - case kFLASH_PropertyPflashBlockCount: - case kFLASH_PropertyPflashBlockBaseAddr: - case kFLASH_PropertyPflashFacSupport: - case kFLASH_PropertyPflashAccessSegmentSize: - case kFLASH_PropertyPflashAccessSegmentCount: - case kFLASH_PropertyFlexRamBlockBaseAddr: - case kFLASH_PropertyFlexRamTotalSize: -#if FLASH_SSD_IS_FLEXNVM_ENABLED - case kFLASH_PropertyDflashSectorSize: - case kFLASH_PropertyDflashTotalSize: - case kFLASH_PropertyDflashBlockSize: - case kFLASH_PropertyDflashBlockCount: - case kFLASH_PropertyDflashBlockBaseAddr: - case kFLASH_PropertyEepromTotalSize: -#endif /* FLASH_SSD_IS_FLEXNVM_ENABLED */ - status = kStatus_FLASH_ReadOnlyProperty; - break; - default: /* catch inputs that are not recognized */ - status = kStatus_FLASH_UnknownProperty; - break; - } - - return status; -} - -#if defined(FSL_FEATURE_FLASH_HAS_SET_FLEXRAM_FUNCTION_CMD) && FSL_FEATURE_FLASH_HAS_SET_FLEXRAM_FUNCTION_CMD -status_t FLASH_SetFlexramFunction(flash_config_t *config, flash_flexram_function_option_t option) -{ - status_t status; - - if (config == NULL) - { - return kStatus_FLASH_InvalidArgument; - } - - status = flasn_check_flexram_function_option_range(option); - if (status != kStatus_FLASH_Success) - { - return status; - } - - /* preparing passing parameter to verify all block command */ - kFCCOBx[0] = BYTES_JOIN_TO_WORD_1_1_2(FTFx_SET_FLEXRAM_FUNCTION, option, 0xFFFFU); - - /* calling flash command sequence function to execute the command */ - return flash_command_sequence(config); -} -#endif /* FSL_FEATURE_FLASH_HAS_SET_FLEXRAM_FUNCTION_CMD */ - -#if defined(FSL_FEATURE_FLASH_HAS_SWAP_CONTROL_CMD) && FSL_FEATURE_FLASH_HAS_SWAP_CONTROL_CMD -status_t FLASH_SwapControl(flash_config_t *config, - uint32_t address, - flash_swap_control_option_t option, - flash_swap_state_config_t *returnInfo) -{ - status_t returnCode; - - if ((config == NULL) || (returnInfo == NULL)) - { - return kStatus_FLASH_InvalidArgument; - } - - if (address & (FSL_FEATURE_FLASH_PFLASH_SWAP_CONTROL_CMD_ADDRESS_ALIGMENT - 1)) - { - return kStatus_FLASH_AlignmentError; - } - - /* Make sure address provided is in the lower half of Program flash but not in the Flash Configuration Field */ - if ((address >= (config->PFlashTotalSize / 2)) || - ((address >= kFLASH_ConfigAreaStart) && (address <= kFLASH_ConfigAreaEnd))) - { - return kStatus_FLASH_SwapIndicatorAddressError; - } - - /* Check the option. */ - returnCode = flash_check_swap_control_option(option); - if (returnCode) - { - return returnCode; - } - - kFCCOBx[0] = BYTES_JOIN_TO_WORD_1_3(FTFx_SWAP_CONTROL, address); - kFCCOBx[1] = BYTES_JOIN_TO_WORD_1_3(option, 0xFFFFFFU); - - returnCode = flash_command_sequence(config); - - returnInfo->flashSwapState = (flash_swap_state_t)FTFx_FCCOB5_REG; - returnInfo->currentSwapBlockStatus = (flash_swap_block_status_t)FTFx_FCCOB6_REG; - returnInfo->nextSwapBlockStatus = (flash_swap_block_status_t)FTFx_FCCOB7_REG; - - return returnCode; -} -#endif /* FSL_FEATURE_FLASH_HAS_SWAP_CONTROL_CMD */ - -#if defined(FSL_FEATURE_FLASH_HAS_PFLASH_BLOCK_SWAP) && FSL_FEATURE_FLASH_HAS_PFLASH_BLOCK_SWAP -status_t FLASH_Swap(flash_config_t *config, uint32_t address, flash_swap_function_option_t option) -{ - flash_swap_state_config_t returnInfo; - status_t returnCode; - - memset(&returnInfo, 0xFFU, sizeof(returnInfo)); - - do - { - returnCode = FLASH_SwapControl(config, address, kFLASH_SwapControlOptionReportStatus, &returnInfo); - if (returnCode != kStatus_FLASH_Success) - { - return returnCode; - } - - if (kFLASH_SwapFunctionOptionDisable == option) - { - if (returnInfo.flashSwapState == kFLASH_SwapStateDisabled) - { - return kStatus_FLASH_Success; - } - else if (returnInfo.flashSwapState == kFLASH_SwapStateUninitialized) - { - /* The swap system changed to the DISABLED state with Program flash block 0 - * located at relative flash address 0x0_0000 */ - returnCode = FLASH_SwapControl(config, address, kFLASH_SwapControlOptionDisableSystem, &returnInfo); - } - else - { - /* Swap disable should be requested only when swap system is in the uninitialized state */ - return kStatus_FLASH_SwapSystemNotInUninitialized; - } - } - else - { - /* When first swap: the initial swap state is Uninitialized, flash swap inidicator address is unset, - * the swap procedure should be Uninitialized -> Update-Erased -> Complete. - * After the first swap has been completed, the flash swap inidicator address cannot be modified - * unless EraseAllBlocks command is issued, the swap procedure is changed to Update -> Update-Erased -> - * Complete. */ - switch (returnInfo.flashSwapState) - { - case kFLASH_SwapStateUninitialized: - /* If current swap mode is Uninitialized, Initialize Swap to Initialized/READY state. */ - returnCode = - FLASH_SwapControl(config, address, kFLASH_SwapControlOptionIntializeSystem, &returnInfo); - break; - case kFLASH_SwapStateReady: - /* Validate whether the address provided to the swap system is matched to - * swap indicator address in the IFR */ - returnCode = flash_validate_swap_indicator_address(config, address); - if (returnCode == kStatus_FLASH_Success) - { - /* If current swap mode is Initialized/Ready, Initialize Swap to UPDATE state. */ - returnCode = - FLASH_SwapControl(config, address, kFLASH_SwapControlOptionSetInUpdateState, &returnInfo); - } - break; - case kFLASH_SwapStateUpdate: - /* If current swap mode is Update, Erase indicator sector in non active block - * to proceed swap system to update-erased state */ - returnCode = FLASH_Erase(config, address + (config->PFlashTotalSize >> 1), - FSL_FEATURE_FLASH_PFLASH_SECTOR_CMD_ADDRESS_ALIGMENT, kFLASH_ApiEraseKey); - break; - case kFLASH_SwapStateUpdateErased: - /* If current swap mode is Update or Update-Erased, progress Swap to COMPLETE State */ - returnCode = - FLASH_SwapControl(config, address, kFLASH_SwapControlOptionSetInCompleteState, &returnInfo); - break; - case kFLASH_SwapStateComplete: - break; - case kFLASH_SwapStateDisabled: - /* When swap system is in disabled state, We need to clear swap system back to uninitialized - * by issuing EraseAllBlocks command */ - returnCode = kStatus_FLASH_SwapSystemNotInUninitialized; - break; - default: - returnCode = kStatus_FLASH_InvalidArgument; - break; - } - } - if (returnCode != kStatus_FLASH_Success) - { - break; - } - } while (!((kFLASH_SwapStateComplete == returnInfo.flashSwapState) && (kFLASH_SwapFunctionOptionEnable == option))); - - return returnCode; -} -#endif /* FSL_FEATURE_FLASH_HAS_PFLASH_BLOCK_SWAP */ - -#if defined(FSL_FEATURE_FLASH_HAS_PROGRAM_PARTITION_CMD) && FSL_FEATURE_FLASH_HAS_PROGRAM_PARTITION_CMD -status_t FLASH_ProgramPartition(flash_config_t *config, - flash_partition_flexram_load_option_t option, - uint32_t eepromDataSizeCode, - uint32_t flexnvmPartitionCode) -{ - status_t returnCode; - - if (config == NULL) - { - return kStatus_FLASH_InvalidArgument; - } - - /* eepromDataSizeCode[7:6], flexnvmPartitionCode[7:4] should be all 1'b0 - * or it will cause access error. */ - /* eepromDataSizeCode &= 0x3FU; */ - /* flexnvmPartitionCode &= 0x0FU; */ - - /* preparing passing parameter to program the flash block */ - kFCCOBx[0] = BYTES_JOIN_TO_WORD_1_2_1(FTFx_PROGRAM_PARTITION, 0xFFFFU, option); - kFCCOBx[1] = BYTES_JOIN_TO_WORD_1_1_2(eepromDataSizeCode, flexnvmPartitionCode, 0xFFFFU); - - flash_cache_clear_process(config, kFLASH_CacheClearProcessPre); - - /* calling flash command sequence function to execute the command */ - returnCode = flash_command_sequence(config); - - flash_cache_clear(config); - -#if FLASH_SSD_IS_FLEXNVM_ENABLED - /* Data flash IFR will be updated by program partition command during reset sequence, - * so we just set reserved values for partitioned FlexNVM size here */ - config->EEpromTotalSize = FLEX_NVM_EEPROM_SIZE_FOR_EEESIZE_RESERVED; - config->DFlashTotalSize = FLEX_NVM_DFLASH_SIZE_FOR_DEPART_RESERVED; -#endif - - return (returnCode); -} -#endif /* FSL_FEATURE_FLASH_HAS_PROGRAM_PARTITION_CMD */ - -status_t FLASH_PflashSetProtection(flash_config_t *config, pflash_protection_status_t *protectStatus) -{ - if (config == NULL) - { - return kStatus_FLASH_InvalidArgument; - } - -#if FLASH_SSD_IS_SECONDARY_FLASH_ENABLED && FLASH_SSD_SECONDARY_FLASH_HAS_ITS_OWN_PROTECTION_REGISTER - if (config->FlashMemoryIndex == (uint8_t)kFLASH_MemoryIndexSecondaryFlash) - { - *kFPROTSL = protectStatus->valueLow32b.prots16b.protsl; - if (protectStatus->valueLow32b.prots16b.protsl != *kFPROTSL) - { - return kStatus_FLASH_CommandFailure; - } - - *kFPROTSH = protectStatus->valueLow32b.prots16b.protsh; - if (protectStatus->valueLow32b.prots16b.protsh != *kFPROTSH) - { - return kStatus_FLASH_CommandFailure; - } - } - else -#endif - { - *kFPROTL = protectStatus->valueLow32b.protl32b; - if (protectStatus->valueLow32b.protl32b != *kFPROTL) - { - return kStatus_FLASH_CommandFailure; - } - -#if defined(FTFx_FPROT_HIGH_REG) - *kFPROTH = protectStatus->valueHigh32b.proth32b; - if (protectStatus->valueHigh32b.proth32b != *kFPROTH) - { - return kStatus_FLASH_CommandFailure; - } -#endif - } - - return kStatus_FLASH_Success; -} - -status_t FLASH_PflashGetProtection(flash_config_t *config, pflash_protection_status_t *protectStatus) -{ - if ((config == NULL) || (protectStatus == NULL)) - { - return kStatus_FLASH_InvalidArgument; - } - -#if FLASH_SSD_IS_SECONDARY_FLASH_ENABLED && FLASH_SSD_SECONDARY_FLASH_HAS_ITS_OWN_PROTECTION_REGISTER - if (config->FlashMemoryIndex == (uint8_t)kFLASH_MemoryIndexSecondaryFlash) - { - protectStatus->valueLow32b.prots16b.protsl = *kFPROTSL; - protectStatus->valueLow32b.prots16b.protsh = *kFPROTSH; - } - else -#endif - { - protectStatus->valueLow32b.protl32b = *kFPROTL; -#if defined(FTFx_FPROT_HIGH_REG) - protectStatus->valueHigh32b.proth32b = *kFPROTH; -#endif - } - - return kStatus_FLASH_Success; -} - -#if FLASH_SSD_IS_FLEXNVM_ENABLED -status_t FLASH_DflashSetProtection(flash_config_t *config, uint8_t protectStatus) -{ - if (config == NULL) - { - return kStatus_FLASH_InvalidArgument; - } - - if ((config->DFlashTotalSize == 0) || (config->DFlashTotalSize == FLEX_NVM_DFLASH_SIZE_FOR_DEPART_RESERVED)) - { - return kStatus_FLASH_CommandNotSupported; - } - - FTFx->FDPROT = protectStatus; - - if (FTFx->FDPROT != protectStatus) - { - return kStatus_FLASH_CommandFailure; - } - - return kStatus_FLASH_Success; -} -#endif /* FLASH_SSD_IS_FLEXNVM_ENABLED */ - -#if FLASH_SSD_IS_FLEXNVM_ENABLED -status_t FLASH_DflashGetProtection(flash_config_t *config, uint8_t *protectStatus) -{ - if ((config == NULL) || (protectStatus == NULL)) - { - return kStatus_FLASH_InvalidArgument; - } - - if ((config->DFlashTotalSize == 0) || (config->DFlashTotalSize == FLEX_NVM_DFLASH_SIZE_FOR_DEPART_RESERVED)) - { - return kStatus_FLASH_CommandNotSupported; - } - - *protectStatus = FTFx->FDPROT; - - return kStatus_FLASH_Success; -} -#endif /* FLASH_SSD_IS_FLEXNVM_ENABLED */ - -#if FLASH_SSD_IS_FLEXNVM_ENABLED -status_t FLASH_EepromSetProtection(flash_config_t *config, uint8_t protectStatus) -{ - if (config == NULL) - { - return kStatus_FLASH_InvalidArgument; - } - - if ((config->EEpromTotalSize == 0) || (config->EEpromTotalSize == FLEX_NVM_EEPROM_SIZE_FOR_EEESIZE_RESERVED)) - { - return kStatus_FLASH_CommandNotSupported; - } - - FTFx->FEPROT = protectStatus; - - if (FTFx->FEPROT != protectStatus) - { - return kStatus_FLASH_CommandFailure; - } - - return kStatus_FLASH_Success; -} -#endif /* FLASH_SSD_IS_FLEXNVM_ENABLED */ - -#if FLASH_SSD_IS_FLEXNVM_ENABLED -status_t FLASH_EepromGetProtection(flash_config_t *config, uint8_t *protectStatus) -{ - if ((config == NULL) || (protectStatus == NULL)) - { - return kStatus_FLASH_InvalidArgument; - } - - if ((config->EEpromTotalSize == 0) || (config->EEpromTotalSize == FLEX_NVM_EEPROM_SIZE_FOR_EEESIZE_RESERVED)) - { - return kStatus_FLASH_CommandNotSupported; - } - - *protectStatus = FTFx->FEPROT; - - return kStatus_FLASH_Success; -} -#endif /* FLASH_SSD_IS_FLEXNVM_ENABLED */ - -status_t FLASH_PflashSetPrefetchSpeculation(flash_prefetch_speculation_status_t *speculationStatus) -{ -#if FLASH_PREFETCH_SPECULATION_IS_CONTROLLED_BY_MCM - { - FTFx_REG32_ACCESS_TYPE regBase; -#if defined(MCM) - regBase = (FTFx_REG32_ACCESS_TYPE)&MCM->PLACR; -#elif defined(MCM0) - regBase = (FTFx_REG32_ACCESS_TYPE)&MCM0->PLACR; -#endif - if (speculationStatus->instructionOption == kFLASH_prefetchSpeculationOptionDisable) - { - if (speculationStatus->dataOption == kFLASH_prefetchSpeculationOptionEnable) - { - return kStatus_FLASH_InvalidSpeculationOption; - } - else - { - *regBase |= MCM_PLACR_DFCS_MASK; - } - } - else - { - *regBase &= ~MCM_PLACR_DFCS_MASK; - if (speculationStatus->dataOption == kFLASH_prefetchSpeculationOptionEnable) - { - *regBase |= MCM_PLACR_EFDS_MASK; - } - else - { - *regBase &= ~MCM_PLACR_EFDS_MASK; - } - } - } -#elif FLASH_PREFETCH_SPECULATION_IS_CONTROLLED_BY_FMC - { - FTFx_REG32_ACCESS_TYPE regBase; - uint32_t b0dpeMask, b0ipeMask; -#if defined(FMC_PFB01CR_B0DPE_MASK) - regBase = (FTFx_REG32_ACCESS_TYPE)&FMC->PFB01CR; - b0dpeMask = FMC_PFB01CR_B0DPE_MASK; - b0ipeMask = FMC_PFB01CR_B0IPE_MASK; -#elif defined(FMC_PFB0CR_B0DPE_MASK) - regBase = (FTFx_REG32_ACCESS_TYPE)&FMC->PFB0CR; - b0dpeMask = FMC_PFB0CR_B0DPE_MASK; - b0ipeMask = FMC_PFB0CR_B0IPE_MASK; -#endif - if (speculationStatus->instructionOption == kFLASH_prefetchSpeculationOptionEnable) - { - *regBase |= b0ipeMask; - } - else - { - *regBase &= ~b0ipeMask; - } - if (speculationStatus->dataOption == kFLASH_prefetchSpeculationOptionEnable) - { - *regBase |= b0dpeMask; - } - else - { - *regBase &= ~b0dpeMask; - } - -/* Invalidate Prefetch Speculation Buffer */ -#if defined(FMC_PFB01CR_S_INV_MASK) - FMC->PFB01CR |= FMC_PFB01CR_S_INV_MASK; -#elif defined(FMC_PFB01CR_S_B_INV_MASK) - FMC->PFB01CR |= FMC_PFB01CR_S_B_INV_MASK; -#elif defined(FMC_PFB0CR_S_INV_MASK) - FMC->PFB0CR |= FMC_PFB0CR_S_INV_MASK; -#elif defined(FMC_PFB0CR_S_B_INV_MASK) - FMC->PFB0CR |= FMC_PFB0CR_S_B_INV_MASK; -#endif - } -#elif FLASH_PREFETCH_SPECULATION_IS_CONTROLLED_BY_MSCM - { - FTFx_REG32_ACCESS_TYPE regBase; - uint32_t flashSpeculationMask, dataPrefetchMask; - regBase = (FTFx_REG32_ACCESS_TYPE)&MSCM->OCMDR[0]; - flashSpeculationMask = MSCM_OCMDR_OCMC1_DFCS_MASK; - dataPrefetchMask = MSCM_OCMDR_OCMC1_DFDS_MASK; - - if (speculationStatus->instructionOption == kFLASH_prefetchSpeculationOptionDisable) - { - if (speculationStatus->dataOption == kFLASH_prefetchSpeculationOptionEnable) - { - return kStatus_FLASH_InvalidSpeculationOption; - } - else - { - *regBase |= flashSpeculationMask; - } - } - else - { - *regBase &= ~flashSpeculationMask; - if (speculationStatus->dataOption == kFLASH_prefetchSpeculationOptionEnable) - { - *regBase &= ~dataPrefetchMask; - } - else - { - *regBase |= dataPrefetchMask; - } - } - } -#endif /* FSL_FEATURE_FTFx_MCM_FLASH_CACHE_CONTROLS */ - - return kStatus_FLASH_Success; -} - -status_t FLASH_PflashGetPrefetchSpeculation(flash_prefetch_speculation_status_t *speculationStatus) -{ - memset(speculationStatus, 0, sizeof(flash_prefetch_speculation_status_t)); - - /* Assuming that all speculation options are enabled. */ - speculationStatus->instructionOption = kFLASH_prefetchSpeculationOptionEnable; - speculationStatus->dataOption = kFLASH_prefetchSpeculationOptionEnable; - -#if FLASH_PREFETCH_SPECULATION_IS_CONTROLLED_BY_MCM - { - uint32_t value; -#if defined(MCM) - value = MCM->PLACR; -#elif defined(MCM0) - value = MCM0->PLACR; -#endif - if (value & MCM_PLACR_DFCS_MASK) - { - /* Speculation buffer is off. */ - speculationStatus->instructionOption = kFLASH_prefetchSpeculationOptionDisable; - speculationStatus->dataOption = kFLASH_prefetchSpeculationOptionDisable; - } - else - { - /* Speculation buffer is on for instruction. */ - if (!(value & MCM_PLACR_EFDS_MASK)) - { - /* Speculation buffer is off for data. */ - speculationStatus->dataOption = kFLASH_prefetchSpeculationOptionDisable; - } - } - } -#elif FLASH_PREFETCH_SPECULATION_IS_CONTROLLED_BY_FMC - { - uint32_t value; - uint32_t b0dpeMask, b0ipeMask; -#if defined(FMC_PFB01CR_B0DPE_MASK) - value = FMC->PFB01CR; - b0dpeMask = FMC_PFB01CR_B0DPE_MASK; - b0ipeMask = FMC_PFB01CR_B0IPE_MASK; -#elif defined(FMC_PFB0CR_B0DPE_MASK) - value = FMC->PFB0CR; - b0dpeMask = FMC_PFB0CR_B0DPE_MASK; - b0ipeMask = FMC_PFB0CR_B0IPE_MASK; -#endif - if (!(value & b0dpeMask)) - { - /* Do not prefetch in response to data references. */ - speculationStatus->dataOption = kFLASH_prefetchSpeculationOptionDisable; - } - if (!(value & b0ipeMask)) - { - /* Do not prefetch in response to instruction fetches. */ - speculationStatus->instructionOption = kFLASH_prefetchSpeculationOptionDisable; - } - } -#elif FLASH_PREFETCH_SPECULATION_IS_CONTROLLED_BY_MSCM - { - uint32_t value; - uint32_t flashSpeculationMask, dataPrefetchMask; - value = MSCM->OCMDR[0]; - flashSpeculationMask = MSCM_OCMDR_OCMC1_DFCS_MASK; - dataPrefetchMask = MSCM_OCMDR_OCMC1_DFDS_MASK; - - if (value & flashSpeculationMask) - { - /* Speculation buffer is off. */ - speculationStatus->instructionOption = kFLASH_prefetchSpeculationOptionDisable; - speculationStatus->dataOption = kFLASH_prefetchSpeculationOptionDisable; - } - else - { - /* Speculation buffer is on for instruction. */ - if (value & dataPrefetchMask) - { - /* Speculation buffer is off for data. */ - speculationStatus->dataOption = kFLASH_prefetchSpeculationOptionDisable; - } - } - } -#endif - - return kStatus_FLASH_Success; -} - -#if FLASH_DRIVER_IS_FLASH_RESIDENT -/*! - * @brief Copy PIC of flash_run_command() to RAM - */ -static void copy_flash_run_command(uint32_t *flashRunCommand) -{ - assert(sizeof(s_flashRunCommandFunctionCode) <= (kFLASH_ExecuteInRamFunctionMaxSizeInWords * 4)); - - /* Since the value of ARM function pointer is always odd, but the real start address - * of function memory should be even, that's why +1 operation exist. */ - memcpy((void *)flashRunCommand, (void *)s_flashRunCommandFunctionCode, sizeof(s_flashRunCommandFunctionCode)); - callFlashRunCommand = (void (*)(FTFx_REG8_ACCESS_TYPE ftfx_fstat))((uint32_t)flashRunCommand + 1); -} -#endif /* FLASH_DRIVER_IS_FLASH_RESIDENT */ - -/*! - * @brief Flash Command Sequence - * - * This function is used to perform the command write sequence to the flash. - * - * @param driver Pointer to storage for the driver runtime state. - * @return An error code or kStatus_FLASH_Success - */ -static status_t flash_command_sequence(flash_config_t *config) -{ - uint8_t registerValue; - -#if FLASH_DRIVER_IS_FLASH_RESIDENT - /* clear RDCOLERR & ACCERR & FPVIOL flag in flash status register */ - FTFx->FSTAT = FTFx_FSTAT_RDCOLERR_MASK | FTFx_FSTAT_ACCERR_MASK | FTFx_FSTAT_FPVIOL_MASK; - - status_t returnCode = flash_check_execute_in_ram_function_info(config); - if (kStatus_FLASH_Success != returnCode) - { - return returnCode; - } - - /* We pass the ftfx_fstat address as a parameter to flash_run_comamnd() instead of using - * pre-processed MICRO sentences or operating global variable in flash_run_comamnd() - * to make sure that flash_run_command() will be compiled into position-independent code (PIC). */ - callFlashRunCommand((FTFx_REG8_ACCESS_TYPE)(&FTFx->FSTAT)); -#else - /* clear RDCOLERR & ACCERR & FPVIOL flag in flash status register */ - FTFx->FSTAT = FTFx_FSTAT_RDCOLERR_MASK | FTFx_FSTAT_ACCERR_MASK | FTFx_FSTAT_FPVIOL_MASK; - - /* clear CCIF bit */ - FTFx->FSTAT = FTFx_FSTAT_CCIF_MASK; - - /* Check CCIF bit of the flash status register, wait till it is set. - * IP team indicates that this loop will always complete. */ - while (!(FTFx->FSTAT & FTFx_FSTAT_CCIF_MASK)) - { - } -#endif /* FLASH_DRIVER_IS_FLASH_RESIDENT */ - - /* Check error bits */ - /* Get flash status register value */ - registerValue = FTFx->FSTAT; - - /* checking access error */ - if (registerValue & FTFx_FSTAT_ACCERR_MASK) - { - return kStatus_FLASH_AccessError; - } - /* checking protection error */ - else if (registerValue & FTFx_FSTAT_FPVIOL_MASK) - { - return kStatus_FLASH_ProtectionViolation; - } - /* checking MGSTAT0 non-correctable error */ - else if (registerValue & FTFx_FSTAT_MGSTAT0_MASK) - { - return kStatus_FLASH_CommandFailure; - } - else - { - return kStatus_FLASH_Success; - } -} - -#if FLASH_DRIVER_IS_FLASH_RESIDENT -/*! - * @brief Copy PIC of flash_common_bit_operation() to RAM - * - */ -static void copy_flash_common_bit_operation(uint32_t *flashCommonBitOperation) -{ - assert(sizeof(s_flashCommonBitOperationFunctionCode) <= (kFLASH_ExecuteInRamFunctionMaxSizeInWords * 4)); - - /* Since the value of ARM function pointer is always odd, but the real start address - * of function memory should be even, that's why +1 operation exist. */ - memcpy((void *)flashCommonBitOperation, (void *)s_flashCommonBitOperationFunctionCode, - sizeof(s_flashCommonBitOperationFunctionCode)); - callFlashCommonBitOperation = (void (*)(FTFx_REG32_ACCESS_TYPE base, uint32_t bitMask, uint32_t bitShift, - uint32_t bitValue))((uint32_t)flashCommonBitOperation + 1); - /* Workround for some devices which doesn't need this function */ - callFlashCommonBitOperation((FTFx_REG32_ACCESS_TYPE)0, 0, 0, 0); -} -#endif /* FLASH_DRIVER_IS_FLASH_RESIDENT */ - -#if FLASH_CACHE_IS_CONTROLLED_BY_MCM -/*! @brief Performs the cache clear to the flash by MCM.*/ -void mcm_flash_cache_clear(flash_config_t *config) -{ - FTFx_REG32_ACCESS_TYPE regBase = (FTFx_REG32_ACCESS_TYPE)&MCM0_CACHE_REG; - -#if defined(MCM0) && defined(MCM1) - if (config->FlashCacheControllerIndex == (uint8_t)kFLASH_CacheControllerIndexForCore1) - { - regBase = (FTFx_REG32_ACCESS_TYPE)&MCM1_CACHE_REG; - } -#endif - -#if FLASH_DRIVER_IS_FLASH_RESIDENT - callFlashCommonBitOperation(regBase, MCM_CACHE_CLEAR_MASK, MCM_CACHE_CLEAR_SHIFT, 1U); -#else /* !FLASH_DRIVER_IS_FLASH_RESIDENT */ - *regBase |= MCM_CACHE_CLEAR_MASK; - - /* Memory barriers for good measure. - * All Cache, Branch predictor and TLB maintenance operations before this instruction complete */ - __ISB(); - __DSB(); -#endif /* FLASH_DRIVER_IS_FLASH_RESIDENT */ -} -#endif /* FLASH_CACHE_IS_CONTROLLED_BY_MCM */ - -#if FLASH_CACHE_IS_CONTROLLED_BY_FMC -/*! @brief Performs the cache clear to the flash by FMC.*/ -void fmc_flash_cache_clear(void) -{ -#if FLASH_DRIVER_IS_FLASH_RESIDENT - FTFx_REG32_ACCESS_TYPE regBase = (FTFx_REG32_ACCESS_TYPE)0; -#if defined(FMC_PFB01CR_CINV_WAY_MASK) - regBase = (FTFx_REG32_ACCESS_TYPE)&FMC->PFB01CR; - callFlashCommonBitOperation(regBase, FMC_PFB01CR_CINV_WAY_MASK, FMC_PFB01CR_CINV_WAY_SHIFT, 0xFU); -#else - regBase = (FTFx_REG32_ACCESS_TYPE)&FMC->PFB0CR; - callFlashCommonBitOperation(regBase, FMC_PFB0CR_CINV_WAY_MASK, FMC_PFB0CR_CINV_WAY_SHIFT, 0xFU); -#endif -#else /* !FLASH_DRIVER_IS_FLASH_RESIDENT */ -#if defined(FMC_PFB01CR_CINV_WAY_MASK) - FMC->PFB01CR = (FMC->PFB01CR & ~FMC_PFB01CR_CINV_WAY_MASK) | FMC_PFB01CR_CINV_WAY(~0); -#else - FMC->PFB0CR = (FMC->PFB0CR & ~FMC_PFB0CR_CINV_WAY_MASK) | FMC_PFB0CR_CINV_WAY(~0); -#endif - /* Memory barriers for good measure. - * All Cache, Branch predictor and TLB maintenance operations before this instruction complete */ - __ISB(); - __DSB(); -#endif /* FLASH_DRIVER_IS_FLASH_RESIDENT */ -} -#endif /* FLASH_CACHE_IS_CONTROLLED_BY_FMC */ - -#if FLASH_PREFETCH_SPECULATION_IS_CONTROLLED_BY_MSCM -/*! @brief Performs the prefetch speculation buffer clear to the flash by MSCM.*/ -void mscm_flash_prefetch_speculation_enable(bool enable) -{ - uint8_t setValue; - if (enable) - { - setValue = 0x0U; - } - else - { - setValue = 0x3U; - } - -/* The OCMDR[0] is always used to prefetch main Pflash*/ -/* For device with FlexNVM support, the OCMDR[1] is used to prefetch Dflash. - * For device with secondary flash support, the OCMDR[1] is used to prefetch secondary Pflash. */ -#if FLASH_DRIVER_IS_FLASH_RESIDENT - callFlashCommonBitOperation((FTFx_REG32_ACCESS_TYPE)&MSCM->OCMDR[0], MSCM_SPECULATION_DISABLE_MASK, - MSCM_SPECULATION_DISABLE_SHIFT, setValue); -#if FLASH_SSD_IS_FLEXNVM_ENABLED || BL_HAS_SECONDARY_INTERNAL_FLASH - callFlashCommonBitOperation((FTFx_REG32_ACCESS_TYPE)&MSCM->OCMDR[1], MSCM_SPECULATION_DISABLE_MASK, - MSCM_SPECULATION_DISABLE_SHIFT, setValue); -#endif -#else /* !FLASH_DRIVER_IS_FLASH_RESIDENT */ - MSCM->OCMDR[0] |= MSCM_SPECULATION_DISABLE(setValue); - - /* Memory barriers for good measure. - * All Cache, Branch predictor and TLB maintenance operations before this instruction complete */ - __ISB(); - __DSB(); -#if FLASH_SSD_IS_FLEXNVM_ENABLED || BL_HAS_SECONDARY_INTERNAL_FLASH - MSCM->OCMDR[1] |= MSCM_SPECULATION_DISABLE(setValue); - - /* Each cahce clear instaruction should be followed by below code*/ - __ISB(); - __DSB(); -#endif - -#endif /* FLASH_DRIVER_IS_FLASH_RESIDENT */ -} -#endif /* FLASH_PREFETCH_SPECULATION_IS_CONTROLLED_BY_MSCM */ - -#if FLASH_PREFETCH_SPECULATION_IS_CONTROLLED_BY_FMC -/*! @brief Performs the prefetch speculation buffer clear to the flash by FMC.*/ -void fmc_flash_prefetch_speculation_clear(void) -{ -#if FLASH_DRIVER_IS_FLASH_RESIDENT - FTFx_REG32_ACCESS_TYPE regBase = (FTFx_REG32_ACCESS_TYPE)0; -#if defined(FMC_PFB01CR_S_INV_MASK) - regBase = (FTFx_REG32_ACCESS_TYPE)&FMC->PFB01CR; - callFlashCommonBitOperation(regBase, FMC_PFB01CR_S_INV_MASK, FMC_PFB01CR_S_INV_SHIFT, 1U); -#elif defined(FMC_PFB01CR_S_B_INV_MASK) - regBase = (FTFx_REG32_ACCESS_TYPE)&FMC->PFB01CR; - callFlashCommonBitOperation(regBase, FMC_PFB01CR_S_B_INV_MASK, FMC_PFB01CR_S_B_INV_SHIFT, 1U); -#elif defined(FMC_PFB0CR_S_INV_MASK) - regBase = (FTFx_REG32_ACCESS_TYPE)&FMC->PFB0CR; - callFlashCommonBitOperation(regBase, FMC_PFB0CR_S_INV_MASK, FMC_PFB0CR_S_INV_SHIFT, 1U); -#elif defined(FMC_PFB0CR_S_B_INV_MASK) - regBase = (FTFx_REG32_ACCESS_TYPE)&FMC->PFB0CR; - callFlashCommonBitOperation(regBase, FMC_PFB0CR_S_B_INV_MASK, FMC_PFB0CR_S_B_INV_SHIFT, 1U); -#endif -#else /* !FLASH_DRIVER_IS_FLASH_RESIDENT */ -#if defined(FMC_PFB01CR_S_INV_MASK) - FMC->PFB01CR |= FMC_PFB01CR_S_INV_MASK; -#elif defined(FMC_PFB01CR_S_B_INV_MASK) - FMC->PFB01CR |= FMC_PFB01CR_S_B_INV_MASK; -#elif defined(FMC_PFB0CR_S_INV_MASK) - FMC->PFB0CR |= FMC_PFB0CR_S_INV_MASK; -#elif defined(FMC_PFB0CR_S_B_INV_MASK) - FMC->PFB0CR |= FMC_PFB0CR_S_B_INV_MASK; -#endif - /* Memory barriers for good measure. - * All Cache, Branch predictor and TLB maintenance operations before this instruction complete */ - __ISB(); - __DSB(); -#endif /* FLASH_DRIVER_IS_FLASH_RESIDENT */ -} -#endif /* FLASH_PREFETCH_SPECULATION_IS_CONTROLLED_BY_FMC */ - -/*! - * @brief Flash Cache Clear - * - * This function is used to perform the cache and prefetch speculation clear to the flash. - */ -void flash_cache_clear(flash_config_t *config) -{ - flash_cache_clear_process(config, kFLASH_CacheClearProcessPost); -} - -/*! - * @brief Flash Cache Clear Process - * - * This function is used to perform the cache and prefetch speculation clear process to the flash. - */ -static void flash_cache_clear_process(flash_config_t *config, flash_cache_clear_process_t process) -{ -#if FLASH_DRIVER_IS_FLASH_RESIDENT - status_t returnCode = flash_check_execute_in_ram_function_info(config); - if (kStatus_FLASH_Success != returnCode) - { - return; - } -#endif /* FLASH_DRIVER_IS_FLASH_RESIDENT */ - - /* We pass the ftfx register address as a parameter to flash_common_bit_operation() instead of using - * pre-processed MACROs or a global variable in flash_common_bit_operation() - * to make sure that flash_common_bit_operation() will be compiled into position-independent code (PIC). */ - if (process == kFLASH_CacheClearProcessPost) - { -#if FLASH_CACHE_IS_CONTROLLED_BY_MCM - mcm_flash_cache_clear(config); -#endif -#if FLASH_CACHE_IS_CONTROLLED_BY_FMC - fmc_flash_cache_clear(); -#endif -#if FLASH_PREFETCH_SPECULATION_IS_CONTROLLED_BY_MSCM - mscm_flash_prefetch_speculation_enable(true); -#endif -#if FLASH_PREFETCH_SPECULATION_IS_CONTROLLED_BY_FMC - fmc_flash_prefetch_speculation_clear(); -#endif - } - if (process == kFLASH_CacheClearProcessPre) - { -#if FLASH_PREFETCH_SPECULATION_IS_CONTROLLED_BY_MSCM - mscm_flash_prefetch_speculation_enable(false); -#endif - } -} - -#if FLASH_DRIVER_IS_FLASH_RESIDENT -/*! @brief Check whether flash execute-in-ram functions are ready */ -static status_t flash_check_execute_in_ram_function_info(flash_config_t *config) -{ - flash_execute_in_ram_function_config_t *flashExecuteInRamFunctionInfo; - - if (config == NULL) - { - return kStatus_FLASH_InvalidArgument; - } - - flashExecuteInRamFunctionInfo = (flash_execute_in_ram_function_config_t *)config->flashExecuteInRamFunctionInfo; - - if ((config->flashExecuteInRamFunctionInfo) && - (kFLASH_ExecuteInRamFunctionTotalNum == flashExecuteInRamFunctionInfo->activeFunctionCount)) - { - return kStatus_FLASH_Success; - } - - return kStatus_FLASH_ExecuteInRamFunctionNotReady; -} -#endif /* FLASH_DRIVER_IS_FLASH_RESIDENT */ - -/*! @brief Validates the range and alignment of the given address range.*/ -static status_t flash_check_range(flash_config_t *config, - uint32_t startAddress, - uint32_t lengthInBytes, - uint32_t alignmentBaseline) -{ - if (config == NULL) - { - return kStatus_FLASH_InvalidArgument; - } - - /* Verify the start and length are alignmentBaseline aligned. */ - if ((startAddress & (alignmentBaseline - 1)) || (lengthInBytes & (alignmentBaseline - 1))) - { - return kStatus_FLASH_AlignmentError; - } - - /* check for valid range of the target addresses */ - if ( -#if FLASH_SSD_IS_FLEXNVM_ENABLED - ((startAddress >= config->DFlashBlockBase) && - ((startAddress + lengthInBytes) <= (config->DFlashBlockBase + config->DFlashTotalSize))) || -#endif - ((startAddress >= config->PFlashBlockBase) && - ((startAddress + lengthInBytes) <= (config->PFlashBlockBase + config->PFlashTotalSize)))) - { - return kStatus_FLASH_Success; - } - - return kStatus_FLASH_AddressError; -} - -/*! @brief Gets the right address, sector and block size of current flash type which is indicated by address.*/ -static status_t flash_get_matched_operation_info(flash_config_t *config, - uint32_t address, - flash_operation_config_t *info) -{ - if (config == NULL) - { - return kStatus_FLASH_InvalidArgument; - } - - /* Clean up info Structure*/ - memset(info, 0, sizeof(flash_operation_config_t)); - -#if FLASH_SSD_IS_FLEXNVM_ENABLED - if ((address >= config->DFlashBlockBase) && (address <= (config->DFlashBlockBase + config->DFlashTotalSize))) - { - /* When required by the command, address bit 23 selects between program flash memory - * (=0) and data flash memory (=1).*/ - info->convertedAddress = address - config->DFlashBlockBase + 0x800000U; - info->activeSectorSize = FSL_FEATURE_FLASH_FLEX_NVM_BLOCK_SECTOR_SIZE; - info->activeBlockSize = config->DFlashTotalSize / FSL_FEATURE_FLASH_FLEX_NVM_BLOCK_COUNT; - - info->blockWriteUnitSize = FSL_FEATURE_FLASH_FLEX_NVM_BLOCK_WRITE_UNIT_SIZE; - info->sectorCmdAddressAligment = FSL_FEATURE_FLASH_FLEX_NVM_SECTOR_CMD_ADDRESS_ALIGMENT; - info->sectionCmdAddressAligment = FSL_FEATURE_FLASH_FLEX_NVM_SECTION_CMD_ADDRESS_ALIGMENT; - info->resourceCmdAddressAligment = FSL_FEATURE_FLASH_FLEX_NVM_RESOURCE_CMD_ADDRESS_ALIGMENT; - info->checkCmdAddressAligment = FSL_FEATURE_FLASH_FLEX_NVM_CHECK_CMD_ADDRESS_ALIGMENT; - } - else -#endif /* FLASH_SSD_IS_FLEXNVM_ENABLED */ - { - info->convertedAddress = address - config->PFlashBlockBase; - info->activeSectorSize = config->PFlashSectorSize; - info->activeBlockSize = config->PFlashTotalSize / config->PFlashBlockCount; -#if FLASH_SSD_IS_SECONDARY_FLASH_ENABLED - if (config->FlashMemoryIndex == (uint8_t)kFLASH_MemoryIndexSecondaryFlash) - { -#if FLASH_SSD_SECONDARY_FLASH_HAS_ITS_OWN_PROTECTION_REGISTER || FLASH_SSD_SECONDARY_FLASH_HAS_ITS_OWN_ACCESS_REGISTER - /* When required by the command, address bit 23 selects between main flash memory - * (=0) and secondary flash memory (=1).*/ - info->convertedAddress += 0x800000U; -#endif - info->blockWriteUnitSize = FSL_FEATURE_FLASH_PFLASH_1_BLOCK_WRITE_UNIT_SIZE; - } - else -#endif /* FLASH_SSD_IS_SECONDARY_FLASH_ENABLED */ - { - info->blockWriteUnitSize = FSL_FEATURE_FLASH_PFLASH_BLOCK_WRITE_UNIT_SIZE; - } - - info->sectorCmdAddressAligment = FSL_FEATURE_FLASH_PFLASH_SECTOR_CMD_ADDRESS_ALIGMENT; - info->sectionCmdAddressAligment = FSL_FEATURE_FLASH_PFLASH_SECTION_CMD_ADDRESS_ALIGMENT; - info->resourceCmdAddressAligment = FSL_FEATURE_FLASH_PFLASH_RESOURCE_CMD_ADDRESS_ALIGMENT; - info->checkCmdAddressAligment = FSL_FEATURE_FLASH_PFLASH_CHECK_CMD_ADDRESS_ALIGMENT; - } - - return kStatus_FLASH_Success; -} - -/*! @brief Validates the given user key for flash erase APIs.*/ -static status_t flash_check_user_key(uint32_t key) -{ - /* Validate the user key */ - if (key != kFLASH_ApiEraseKey) - { - return kStatus_FLASH_EraseKeyError; - } - - return kStatus_FLASH_Success; -} - -#if FLASH_SSD_IS_FLEXNVM_ENABLED -/*! @brief Updates FlexNVM memory partition status according to data flash 0 IFR.*/ -static status_t flash_update_flexnvm_memory_partition_status(flash_config_t *config) -{ - struct - { - uint32_t reserved0; - uint8_t FlexNVMPartitionCode; - uint8_t EEPROMDataSetSize; - uint16_t reserved1; - } dataIFRReadOut; - status_t returnCode; - - if (config == NULL) - { - return kStatus_FLASH_InvalidArgument; - } - -#if defined(FSL_FEATURE_FLASH_HAS_READ_RESOURCE_CMD) && FSL_FEATURE_FLASH_HAS_READ_RESOURCE_CMD - /* Get FlexNVM memory partition info from data flash IFR */ - returnCode = FLASH_ReadResource(config, DFLASH_IFR_READRESOURCE_START_ADDRESS, (uint32_t *)&dataIFRReadOut, - sizeof(dataIFRReadOut), kFLASH_ResourceOptionFlashIfr); - if (returnCode != kStatus_FLASH_Success) - { - return kStatus_FLASH_PartitionStatusUpdateFailure; - } -#else -#error "Cannot get FlexNVM memory partition info" -#endif - - /* Fill out partitioned EEPROM size */ - dataIFRReadOut.EEPROMDataSetSize &= 0x0FU; - switch (dataIFRReadOut.EEPROMDataSetSize) - { - case 0x00U: - config->EEpromTotalSize = FSL_FEATURE_FLASH_FLEX_NVM_EEPROM_SIZE_FOR_EEESIZE_0000; - break; - case 0x01U: - config->EEpromTotalSize = FSL_FEATURE_FLASH_FLEX_NVM_EEPROM_SIZE_FOR_EEESIZE_0001; - break; - case 0x02U: - config->EEpromTotalSize = FSL_FEATURE_FLASH_FLEX_NVM_EEPROM_SIZE_FOR_EEESIZE_0010; - break; - case 0x03U: - config->EEpromTotalSize = FSL_FEATURE_FLASH_FLEX_NVM_EEPROM_SIZE_FOR_EEESIZE_0011; - break; - case 0x04U: - config->EEpromTotalSize = FSL_FEATURE_FLASH_FLEX_NVM_EEPROM_SIZE_FOR_EEESIZE_0100; - break; - case 0x05U: - config->EEpromTotalSize = FSL_FEATURE_FLASH_FLEX_NVM_EEPROM_SIZE_FOR_EEESIZE_0101; - break; - case 0x06U: - config->EEpromTotalSize = FSL_FEATURE_FLASH_FLEX_NVM_EEPROM_SIZE_FOR_EEESIZE_0110; - break; - case 0x07U: - config->EEpromTotalSize = FSL_FEATURE_FLASH_FLEX_NVM_EEPROM_SIZE_FOR_EEESIZE_0111; - break; - case 0x08U: - config->EEpromTotalSize = FSL_FEATURE_FLASH_FLEX_NVM_EEPROM_SIZE_FOR_EEESIZE_1000; - break; - case 0x09U: - config->EEpromTotalSize = FSL_FEATURE_FLASH_FLEX_NVM_EEPROM_SIZE_FOR_EEESIZE_1001; - break; - case 0x0AU: - config->EEpromTotalSize = FSL_FEATURE_FLASH_FLEX_NVM_EEPROM_SIZE_FOR_EEESIZE_1010; - break; - case 0x0BU: - config->EEpromTotalSize = FSL_FEATURE_FLASH_FLEX_NVM_EEPROM_SIZE_FOR_EEESIZE_1011; - break; - case 0x0CU: - config->EEpromTotalSize = FSL_FEATURE_FLASH_FLEX_NVM_EEPROM_SIZE_FOR_EEESIZE_1100; - break; - case 0x0DU: - config->EEpromTotalSize = FSL_FEATURE_FLASH_FLEX_NVM_EEPROM_SIZE_FOR_EEESIZE_1101; - break; - case 0x0EU: - config->EEpromTotalSize = FSL_FEATURE_FLASH_FLEX_NVM_EEPROM_SIZE_FOR_EEESIZE_1110; - break; - case 0x0FU: - config->EEpromTotalSize = FSL_FEATURE_FLASH_FLEX_NVM_EEPROM_SIZE_FOR_EEESIZE_1111; - break; - default: - config->EEpromTotalSize = FLEX_NVM_EEPROM_SIZE_FOR_EEESIZE_RESERVED; - break; - } - - /* Fill out partitioned DFlash size */ - dataIFRReadOut.FlexNVMPartitionCode &= 0x0FU; - switch (dataIFRReadOut.FlexNVMPartitionCode) - { - case 0x00U: -#if (FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_0000 != 0xFFFFFFFF) - config->DFlashTotalSize = FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_0000; -#else - config->DFlashTotalSize = FLEX_NVM_DFLASH_SIZE_FOR_DEPART_RESERVED; -#endif /* FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_0000 */ - break; - case 0x01U: -#if (FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_0001 != 0xFFFFFFFF) - config->DFlashTotalSize = FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_0001; -#else - config->DFlashTotalSize = FLEX_NVM_DFLASH_SIZE_FOR_DEPART_RESERVED; -#endif /* FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_0001 */ - break; - case 0x02U: -#if (FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_0010 != 0xFFFFFFFF) - config->DFlashTotalSize = FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_0010; -#else - config->DFlashTotalSize = FLEX_NVM_DFLASH_SIZE_FOR_DEPART_RESERVED; -#endif /* FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_0010 */ - break; - case 0x03U: -#if (FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_0011 != 0xFFFFFFFF) - config->DFlashTotalSize = FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_0011; -#else - config->DFlashTotalSize = FLEX_NVM_DFLASH_SIZE_FOR_DEPART_RESERVED; -#endif /* FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_0011 */ - break; - case 0x04U: -#if (FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_0100 != 0xFFFFFFFF) - config->DFlashTotalSize = FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_0100; -#else - config->DFlashTotalSize = FLEX_NVM_DFLASH_SIZE_FOR_DEPART_RESERVED; -#endif /* FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_0100 */ - break; - case 0x05U: -#if (FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_0101 != 0xFFFFFFFF) - config->DFlashTotalSize = FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_0101; -#else - config->DFlashTotalSize = FLEX_NVM_DFLASH_SIZE_FOR_DEPART_RESERVED; -#endif /* FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_0101 */ - break; - case 0x06U: -#if (FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_0110 != 0xFFFFFFFF) - config->DFlashTotalSize = FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_0110; -#else - config->DFlashTotalSize = FLEX_NVM_DFLASH_SIZE_FOR_DEPART_RESERVED; -#endif /* FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_0110 */ - break; - case 0x07U: -#if (FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_0111 != 0xFFFFFFFF) - config->DFlashTotalSize = FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_0111; -#else - config->DFlashTotalSize = FLEX_NVM_DFLASH_SIZE_FOR_DEPART_RESERVED; -#endif /* FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_0111 */ - break; - case 0x08U: -#if (FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_1000 != 0xFFFFFFFF) - config->DFlashTotalSize = FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_1000; -#else - config->DFlashTotalSize = FLEX_NVM_DFLASH_SIZE_FOR_DEPART_RESERVED; -#endif /* FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_1000 */ - break; - case 0x09U: -#if (FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_1001 != 0xFFFFFFFF) - config->DFlashTotalSize = FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_1001; -#else - config->DFlashTotalSize = FLEX_NVM_DFLASH_SIZE_FOR_DEPART_RESERVED; -#endif /* FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_1001 */ - break; - case 0x0AU: -#if (FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_1010 != 0xFFFFFFFF) - config->DFlashTotalSize = FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_1010; -#else - config->DFlashTotalSize = FLEX_NVM_DFLASH_SIZE_FOR_DEPART_RESERVED; -#endif /* FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_1010 */ - break; - case 0x0BU: -#if (FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_1011 != 0xFFFFFFFF) - config->DFlashTotalSize = FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_1011; -#else - config->DFlashTotalSize = FLEX_NVM_DFLASH_SIZE_FOR_DEPART_RESERVED; -#endif /* FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_1011 */ - break; - case 0x0CU: -#if (FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_1100 != 0xFFFFFFFF) - config->DFlashTotalSize = FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_1100; -#else - config->DFlashTotalSize = FLEX_NVM_DFLASH_SIZE_FOR_DEPART_RESERVED; -#endif /* FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_1100 */ - break; - case 0x0DU: -#if (FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_1101 != 0xFFFFFFFF) - config->DFlashTotalSize = FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_1101; -#else - config->DFlashTotalSize = FLEX_NVM_DFLASH_SIZE_FOR_DEPART_RESERVED; -#endif /* FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_1101 */ - break; - case 0x0EU: -#if (FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_1110 != 0xFFFFFFFF) - config->DFlashTotalSize = FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_1110; -#else - config->DFlashTotalSize = FLEX_NVM_DFLASH_SIZE_FOR_DEPART_RESERVED; -#endif /* FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_1110 */ - break; - case 0x0FU: -#if (FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_1111 != 0xFFFFFFFF) - config->DFlashTotalSize = FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_1111; -#else - config->DFlashTotalSize = FLEX_NVM_DFLASH_SIZE_FOR_DEPART_RESERVED; -#endif /* FSL_FEATURE_FLASH_FLEX_NVM_DFLASH_SIZE_FOR_DEPART_1111 */ - break; - default: - config->DFlashTotalSize = FLEX_NVM_DFLASH_SIZE_FOR_DEPART_RESERVED; - break; - } - - return kStatus_FLASH_Success; -} -#endif /* FLASH_SSD_IS_FLEXNVM_ENABLED */ - -#if defined(FSL_FEATURE_FLASH_HAS_READ_RESOURCE_CMD) && FSL_FEATURE_FLASH_HAS_READ_RESOURCE_CMD -/*! @brief Validates the range of the given resource address.*/ -static status_t flash_check_resource_range(uint32_t start, - uint32_t lengthInBytes, - uint32_t alignmentBaseline, - flash_read_resource_option_t option) -{ - status_t status; - uint32_t maxReadbleAddress; - - if ((start & (alignmentBaseline - 1)) || (lengthInBytes & (alignmentBaseline - 1))) - { - return kStatus_FLASH_AlignmentError; - } - - status = kStatus_FLASH_Success; - - maxReadbleAddress = start + lengthInBytes - 1; - if (option == kFLASH_ResourceOptionVersionId) - { - if ((start != kFLASH_ResourceRangeVersionIdStart) || - ((start + lengthInBytes - 1) != kFLASH_ResourceRangeVersionIdEnd)) - { - status = kStatus_FLASH_InvalidArgument; - } - } - else if (option == kFLASH_ResourceOptionFlashIfr) - { - if (maxReadbleAddress < kFLASH_ResourceRangePflashIfrSizeInBytes) - { - } -#if defined(FSL_FEATURE_FLASH_HAS_PFLASH_BLOCK_SWAP) && FSL_FEATURE_FLASH_HAS_PFLASH_BLOCK_SWAP - else if ((start >= kFLASH_ResourceRangePflashSwapIfrStart) && - (maxReadbleAddress <= kFLASH_ResourceRangePflashSwapIfrEnd)) - { - } -#endif /* FSL_FEATURE_FLASH_HAS_PFLASH_BLOCK_SWAP */ - else if ((start >= kFLASH_ResourceRangeDflashIfrStart) && - (maxReadbleAddress <= kFLASH_ResourceRangeDflashIfrEnd)) - { - } - else - { - status = kStatus_FLASH_InvalidArgument; - } - } - else - { - status = kStatus_FLASH_InvalidArgument; - } - - return status; -} -#endif /* FSL_FEATURE_FLASH_HAS_READ_RESOURCE_CMD */ - -#if defined(FSL_FEATURE_FLASH_HAS_SWAP_CONTROL_CMD) && FSL_FEATURE_FLASH_HAS_SWAP_CONTROL_CMD -/*! @brief Validates the gived swap control option.*/ -static status_t flash_check_swap_control_option(flash_swap_control_option_t option) -{ - if ((option == kFLASH_SwapControlOptionIntializeSystem) || (option == kFLASH_SwapControlOptionSetInUpdateState) || - (option == kFLASH_SwapControlOptionSetInCompleteState) || (option == kFLASH_SwapControlOptionReportStatus) || - (option == kFLASH_SwapControlOptionDisableSystem)) - { - return kStatus_FLASH_Success; - } - - return kStatus_FLASH_InvalidArgument; -} -#endif /* FSL_FEATURE_FLASH_HAS_SWAP_CONTROL_CMD */ - -#if defined(FSL_FEATURE_FLASH_HAS_PFLASH_BLOCK_SWAP) && FSL_FEATURE_FLASH_HAS_PFLASH_BLOCK_SWAP -/*! @brief Validates the gived address to see if it is equal to swap indicator address in pflash swap IFR.*/ -static status_t flash_validate_swap_indicator_address(flash_config_t *config, uint32_t address) -{ - flash_swap_ifr_field_data_t flashSwapIfrFieldData; - uint32_t swapIndicatorAddress; - - status_t returnCode; -#if defined(FSL_FEATURE_FLASH_HAS_READ_RESOURCE_CMD) && FSL_FEATURE_FLASH_HAS_READ_RESOURCE_CMD - returnCode = - FLASH_ReadResource(config, kFLASH_ResourceRangePflashSwapIfrStart, flashSwapIfrFieldData.flashSwapIfrData, - sizeof(flashSwapIfrFieldData.flashSwapIfrData), kFLASH_ResourceOptionFlashIfr); - - if (returnCode != kStatus_FLASH_Success) - { - return returnCode; - } -#else - { - /* From RM, the actual info are stored in FCCOB6,7 */ - uint32_t returnValue[2]; - returnCode = FLASH_ReadOnce(config, kFLASH_RecordIndexSwapAddr, returnValue, 4); - if (returnCode != kStatus_FLASH_Success) - { - return returnCode; - } - flashSwapIfrFieldData.flashSwapIfrField.swapIndicatorAddress = (uint16_t)returnValue[0]; - returnCode = FLASH_ReadOnce(config, kFLASH_RecordIndexSwapEnable, returnValue, 4); - if (returnCode != kStatus_FLASH_Success) - { - return returnCode; - } - flashSwapIfrFieldData.flashSwapIfrField.swapEnableWord = (uint16_t)returnValue[0]; - returnCode = FLASH_ReadOnce(config, kFLASH_RecordIndexSwapDisable, returnValue, 4); - if (returnCode != kStatus_FLASH_Success) - { - return returnCode; - } - flashSwapIfrFieldData.flashSwapIfrField.swapDisableWord = (uint16_t)returnValue[0]; - } -#endif - - /* The high bits value of Swap Indicator Address is stored in Program Flash Swap IFR Field, - * the low severval bit value of Swap Indicator Address is always 1'b0 */ - swapIndicatorAddress = (uint32_t)flashSwapIfrFieldData.flashSwapIfrField.swapIndicatorAddress * - FSL_FEATURE_FLASH_PFLASH_SWAP_CONTROL_CMD_ADDRESS_ALIGMENT; - if (address != swapIndicatorAddress) - { - return kStatus_FLASH_SwapIndicatorAddressError; - } - - return returnCode; -} -#endif /* FSL_FEATURE_FLASH_HAS_PFLASH_BLOCK_SWAP */ - -#if defined(FSL_FEATURE_FLASH_HAS_SET_FLEXRAM_FUNCTION_CMD) && FSL_FEATURE_FLASH_HAS_SET_FLEXRAM_FUNCTION_CMD -/*! @brief Validates the gived flexram function option.*/ -static inline status_t flasn_check_flexram_function_option_range(flash_flexram_function_option_t option) -{ - if ((option != kFLASH_FlexramFunctionOptionAvailableAsRam) && - (option != kFLASH_FlexramFunctionOptionAvailableForEeprom)) - { - return kStatus_FLASH_InvalidArgument; - } - - return kStatus_FLASH_Success; -} -#endif /* FSL_FEATURE_FLASH_HAS_SET_FLEXRAM_FUNCTION_CMD */ - -/*! @brief Gets the flash protection information (region size, region count).*/ -static status_t flash_get_protection_info(flash_config_t *config, flash_protection_config_t *info) -{ - uint32_t pflashTotalSize; - - if (config == NULL) - { - return kStatus_FLASH_InvalidArgument; - } - - /* Clean up info Structure*/ - memset(info, 0, sizeof(flash_protection_config_t)); - -/* Note: KW40 has a secondary flash, but it doesn't have independent protection register*/ -#if FLASH_SSD_IS_SECONDARY_FLASH_ENABLED && (!FLASH_SSD_SECONDARY_FLASH_HAS_ITS_OWN_PROTECTION_REGISTER) - pflashTotalSize = FSL_FEATURE_FLASH_PFLASH_BLOCK_COUNT * FSL_FEATURE_FLASH_PFLASH_BLOCK_SIZE + - FSL_FEATURE_FLASH_PFLASH_1_BLOCK_COUNT * FSL_FEATURE_FLASH_PFLASH_1_BLOCK_SIZE; - info->regionBase = FSL_FEATURE_FLASH_PFLASH_START_ADDRESS; -#else - pflashTotalSize = config->PFlashTotalSize; - info->regionBase = config->PFlashBlockBase; -#endif - -#if FLASH_SSD_IS_SECONDARY_FLASH_ENABLED && FLASH_SSD_SECONDARY_FLASH_HAS_ITS_OWN_PROTECTION_REGISTER - if (config->FlashMemoryIndex == (uint8_t)kFLASH_MemoryIndexSecondaryFlash) - { - info->regionCount = FSL_FEATURE_FLASH_PFLASH_1_PROTECTION_REGION_COUNT; - } - else -#endif - { - info->regionCount = FSL_FEATURE_FLASH_PFLASH_PROTECTION_REGION_COUNT; - } - - /* Calculate the size of the flash protection region - * If the flash density is > 32KB, then protection region is 1/32 of total flash density - * Else if flash density is < 32KB, then flash protection region is set to 1KB */ - if (pflashTotalSize > info->regionCount * 1024) - { - info->regionSize = (pflashTotalSize) / info->regionCount; - } - else - { - info->regionSize = 1024; - } - - return kStatus_FLASH_Success; -} - -#if defined(FSL_FEATURE_FLASH_HAS_ACCESS_CONTROL) && FSL_FEATURE_FLASH_HAS_ACCESS_CONTROL -/*! @brief Gets the flash Execute-Only access information (Segment size, Segment count).*/ -static status_t flash_get_access_info(flash_config_t *config, flash_access_config_t *info) -{ - if (config == NULL) - { - return kStatus_FLASH_InvalidArgument; - } - - /* Clean up info Structure*/ - memset(info, 0, sizeof(flash_access_config_t)); - -/* Note: KW40 has a secondary flash, but it doesn't have independent access register*/ -#if FLASH_SSD_IS_SECONDARY_FLASH_ENABLED && (!FLASH_SSD_SECONDARY_FLASH_HAS_ITS_OWN_ACCESS_REGISTER) - info->SegmentBase = FSL_FEATURE_FLASH_PFLASH_START_ADDRESS; -#else - info->SegmentBase = config->PFlashBlockBase; -#endif - info->SegmentSize = config->PFlashAccessSegmentSize; - info->SegmentCount = config->PFlashAccessSegmentCount; - - return kStatus_FLASH_Success; -} -#endif /* FSL_FEATURE_FLASH_HAS_ACCESS_CONTROL */ diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_flash.h b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_flash.h deleted file mode 100644 index e143cb3e1f6..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_flash.h +++ /dev/null @@ -1,1386 +0,0 @@ -/* - * Copyright (c) 2013-2016, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef _FSL_FLASH_H_ -#define _FSL_FLASH_H_ - -#if (defined(BL_TARGET_FLASH) || defined(BL_TARGET_ROM) || defined(BL_TARGET_RAM)) -#include -#include -#include "fsl_device_registers.h" -#include "bootloader_common.h" -#else -#include "fsl_common.h" -#endif - -/******************************************************************************* - * Definitions - ******************************************************************************/ - -/*! - * @addtogroup flash_driver - * @{ - */ - -/*! - * @name Flash version - * @{ - */ -/*! @brief Constructs the version number for drivers. */ -#if !defined(MAKE_VERSION) -#define MAKE_VERSION(major, minor, bugfix) (((major) << 16) | ((minor) << 8) | (bugfix)) -#endif - -/*! @brief Flash driver version for SDK*/ -#define FSL_FLASH_DRIVER_VERSION (MAKE_VERSION(2, 3, 1)) /*!< Version 2.3.1. */ - -/*! @brief Flash driver version for ROM*/ -enum _flash_driver_version_constants -{ - kFLASH_DriverVersionName = 'F', /*!< Flash driver version name.*/ - kFLASH_DriverVersionMajor = 2, /*!< Major flash driver version.*/ - kFLASH_DriverVersionMinor = 3, /*!< Minor flash driver version.*/ - kFLASH_DriverVersionBugfix = 1 /*!< Bugfix for flash driver version.*/ -}; -/*@}*/ - -/*! - * @name Flash configuration - * @{ - */ -/*! @brief Indicates whether to support FlexNVM in the Flash driver */ -#if !defined(FLASH_SSD_CONFIG_ENABLE_FLEXNVM_SUPPORT) -#define FLASH_SSD_CONFIG_ENABLE_FLEXNVM_SUPPORT 1 /*!< Enables the FlexNVM support by default. */ -#endif - -/*! @brief Indicates whether the FlexNVM is enabled in the Flash driver */ -#define FLASH_SSD_IS_FLEXNVM_ENABLED (FLASH_SSD_CONFIG_ENABLE_FLEXNVM_SUPPORT && FSL_FEATURE_FLASH_HAS_FLEX_NVM) - -/*! @brief Indicates whether to support Secondary flash in the Flash driver */ -#if !defined(FLASH_SSD_CONFIG_ENABLE_SECONDARY_FLASH_SUPPORT) -#define FLASH_SSD_CONFIG_ENABLE_SECONDARY_FLASH_SUPPORT 1 /*!< Enables the secondary flash support by default. */ -#endif - -/*! @brief Indicates whether the secondary flash is supported in the Flash driver */ -#if defined(FSL_FEATURE_FLASH_HAS_MULTIPLE_FLASH) || defined(FSL_FEATURE_FLASH_PFLASH_1_START_ADDRESS) -#define FLASH_SSD_IS_SECONDARY_FLASH_ENABLED (FLASH_SSD_CONFIG_ENABLE_SECONDARY_FLASH_SUPPORT) -#else -#define FLASH_SSD_IS_SECONDARY_FLASH_ENABLED (0) -#endif - -/*! @brief Flash driver location. */ -#if !defined(FLASH_DRIVER_IS_FLASH_RESIDENT) -#if (!defined(BL_TARGET_ROM) && !defined(BL_TARGET_RAM)) -#define FLASH_DRIVER_IS_FLASH_RESIDENT 1 /*!< Used for the flash resident application. */ -#else -#define FLASH_DRIVER_IS_FLASH_RESIDENT 0 /*!< Used for the non-flash resident application. */ -#endif -#endif - -/*! @brief Flash Driver Export option */ -#if !defined(FLASH_DRIVER_IS_EXPORTED) -#if (defined(BL_TARGET_ROM) || defined(BL_TARGET_FLASH)) -#define FLASH_DRIVER_IS_EXPORTED 1 /*!< Used for the ROM bootloader. */ -#else -#define FLASH_DRIVER_IS_EXPORTED 0 /*!< Used for the MCUXpresso SDK application. */ -#endif -#endif -/*@}*/ - -/*! - * @name Flash status - * @{ - */ -/*! @brief Flash driver status group. */ -#if defined(kStatusGroup_FlashDriver) -#define kStatusGroupGeneric kStatusGroup_Generic -#define kStatusGroupFlashDriver kStatusGroup_FlashDriver -#elif defined(kStatusGroup_FLASH) -#define kStatusGroupGeneric kStatusGroup_Generic -#define kStatusGroupFlashDriver kStatusGroup_FLASH -#else -#define kStatusGroupGeneric 0 -#define kStatusGroupFlashDriver 1 -#endif - -/*! @brief Constructs a status code value from a group and a code number. */ -#if !defined(MAKE_STATUS) -#define MAKE_STATUS(group, code) ((((group)*100) + (code))) -#endif - -/*! - * @brief Flash driver status codes. - */ -enum _flash_status -{ - kStatus_FLASH_Success = MAKE_STATUS(kStatusGroupGeneric, 0), /*!< API is executed successfully*/ - kStatus_FLASH_InvalidArgument = MAKE_STATUS(kStatusGroupGeneric, 4), /*!< Invalid argument*/ - kStatus_FLASH_SizeError = MAKE_STATUS(kStatusGroupFlashDriver, 0), /*!< Error size*/ - kStatus_FLASH_AlignmentError = - MAKE_STATUS(kStatusGroupFlashDriver, 1), /*!< Parameter is not aligned with the specified baseline*/ - kStatus_FLASH_AddressError = MAKE_STATUS(kStatusGroupFlashDriver, 2), /*!< Address is out of range */ - kStatus_FLASH_AccessError = - MAKE_STATUS(kStatusGroupFlashDriver, 3), /*!< Invalid instruction codes and out-of bound addresses */ - kStatus_FLASH_ProtectionViolation = MAKE_STATUS( - kStatusGroupFlashDriver, 4), /*!< The program/erase operation is requested to execute on protected areas */ - kStatus_FLASH_CommandFailure = - MAKE_STATUS(kStatusGroupFlashDriver, 5), /*!< Run-time error during command execution. */ - kStatus_FLASH_UnknownProperty = MAKE_STATUS(kStatusGroupFlashDriver, 6), /*!< Unknown property.*/ - kStatus_FLASH_EraseKeyError = MAKE_STATUS(kStatusGroupFlashDriver, 7), /*!< API erase key is invalid.*/ - kStatus_FLASH_RegionExecuteOnly = - MAKE_STATUS(kStatusGroupFlashDriver, 8), /*!< The current region is execute-only.*/ - kStatus_FLASH_ExecuteInRamFunctionNotReady = - MAKE_STATUS(kStatusGroupFlashDriver, 9), /*!< Execute-in-RAM function is not available.*/ - kStatus_FLASH_PartitionStatusUpdateFailure = - MAKE_STATUS(kStatusGroupFlashDriver, 10), /*!< Failed to update partition status.*/ - kStatus_FLASH_SetFlexramAsEepromError = - MAKE_STATUS(kStatusGroupFlashDriver, 11), /*!< Failed to set FlexRAM as EEPROM.*/ - kStatus_FLASH_RecoverFlexramAsRamError = - MAKE_STATUS(kStatusGroupFlashDriver, 12), /*!< Failed to recover FlexRAM as RAM.*/ - kStatus_FLASH_SetFlexramAsRamError = MAKE_STATUS(kStatusGroupFlashDriver, 13), /*!< Failed to set FlexRAM as RAM.*/ - kStatus_FLASH_RecoverFlexramAsEepromError = - MAKE_STATUS(kStatusGroupFlashDriver, 14), /*!< Failed to recover FlexRAM as EEPROM.*/ - kStatus_FLASH_CommandNotSupported = MAKE_STATUS(kStatusGroupFlashDriver, 15), /*!< Flash API is not supported.*/ - kStatus_FLASH_SwapSystemNotInUninitialized = - MAKE_STATUS(kStatusGroupFlashDriver, 16), /*!< Swap system is not in an uninitialzed state.*/ - kStatus_FLASH_SwapIndicatorAddressError = - MAKE_STATUS(kStatusGroupFlashDriver, 17), /*!< The swap indicator address is invalid.*/ - kStatus_FLASH_ReadOnlyProperty = MAKE_STATUS(kStatusGroupFlashDriver, 18), /*!< The flash property is read-only.*/ - kStatus_FLASH_InvalidPropertyValue = - MAKE_STATUS(kStatusGroupFlashDriver, 19), /*!< The flash property value is out of range.*/ - kStatus_FLASH_InvalidSpeculationOption = - MAKE_STATUS(kStatusGroupFlashDriver, 20), /*!< The option of flash prefetch speculation is invalid.*/ -}; -/*@}*/ - -/*! - * @name Flash API key - * @{ - */ -/*! @brief Constructs the four character code for the Flash driver API key. */ -#if !defined(FOUR_CHAR_CODE) -#define FOUR_CHAR_CODE(a, b, c, d) (((d) << 24) | ((c) << 16) | ((b) << 8) | ((a))) -#endif - -/*! - * @brief Enumeration for Flash driver API keys. - * - * @note The resulting value is built with a byte order such that the string - * being readable in expected order when viewed in a hex editor, if the value - * is treated as a 32-bit little endian value. - */ -enum _flash_driver_api_keys -{ - kFLASH_ApiEraseKey = FOUR_CHAR_CODE('k', 'f', 'e', 'k') /*!< Key value used to validate all flash erase APIs.*/ -}; -/*@}*/ - -/*! - * @brief Enumeration for supported flash margin levels. - */ -typedef enum _flash_margin_value -{ - kFLASH_MarginValueNormal, /*!< Use the 'normal' read level for 1s.*/ - kFLASH_MarginValueUser, /*!< Apply the 'User' margin to the normal read-1 level.*/ - kFLASH_MarginValueFactory, /*!< Apply the 'Factory' margin to the normal read-1 level.*/ - kFLASH_MarginValueInvalid /*!< Not real margin level, Used to determine the range of valid margin level. */ -} flash_margin_value_t; - -/*! - * @brief Enumeration for the three possible flash security states. - */ -typedef enum _flash_security_state -{ - kFLASH_SecurityStateNotSecure, /*!< Flash is not secure.*/ - kFLASH_SecurityStateBackdoorEnabled, /*!< Flash backdoor is enabled.*/ - kFLASH_SecurityStateBackdoorDisabled /*!< Flash backdoor is disabled.*/ -} flash_security_state_t; - -/*! - * @brief Enumeration for the three possible flash protection levels. - */ -typedef enum _flash_protection_state -{ - kFLASH_ProtectionStateUnprotected, /*!< Flash region is not protected.*/ - kFLASH_ProtectionStateProtected, /*!< Flash region is protected.*/ - kFLASH_ProtectionStateMixed /*!< Flash is mixed with protected and unprotected region.*/ -} flash_protection_state_t; - -/*! - * @brief Enumeration for the three possible flash execute access levels. - */ -typedef enum _flash_execute_only_access_state -{ - kFLASH_AccessStateUnLimited, /*!< Flash region is unlimited.*/ - kFLASH_AccessStateExecuteOnly, /*!< Flash region is execute only.*/ - kFLASH_AccessStateMixed /*!< Flash is mixed with unlimited and execute only region.*/ -} flash_execute_only_access_state_t; - -/*! - * @brief Enumeration for various flash properties. - */ -typedef enum _flash_property_tag -{ - kFLASH_PropertyPflashSectorSize = 0x00U, /*!< Pflash sector size property.*/ - kFLASH_PropertyPflashTotalSize = 0x01U, /*!< Pflash total size property.*/ - kFLASH_PropertyPflashBlockSize = 0x02U, /*!< Pflash block size property.*/ - kFLASH_PropertyPflashBlockCount = 0x03U, /*!< Pflash block count property.*/ - kFLASH_PropertyPflashBlockBaseAddr = 0x04U, /*!< Pflash block base address property.*/ - kFLASH_PropertyPflashFacSupport = 0x05U, /*!< Pflash fac support property.*/ - kFLASH_PropertyPflashAccessSegmentSize = 0x06U, /*!< Pflash access segment size property.*/ - kFLASH_PropertyPflashAccessSegmentCount = 0x07U, /*!< Pflash access segment count property.*/ - kFLASH_PropertyFlexRamBlockBaseAddr = 0x08U, /*!< FlexRam block base address property.*/ - kFLASH_PropertyFlexRamTotalSize = 0x09U, /*!< FlexRam total size property.*/ - kFLASH_PropertyDflashSectorSize = 0x10U, /*!< Dflash sector size property.*/ - kFLASH_PropertyDflashTotalSize = 0x11U, /*!< Dflash total size property.*/ - kFLASH_PropertyDflashBlockSize = 0x12U, /*!< Dflash block size property.*/ - kFLASH_PropertyDflashBlockCount = 0x13U, /*!< Dflash block count property.*/ - kFLASH_PropertyDflashBlockBaseAddr = 0x14U, /*!< Dflash block base address property.*/ - kFLASH_PropertyEepromTotalSize = 0x15U, /*!< EEPROM total size property.*/ - kFLASH_PropertyFlashMemoryIndex = 0x20U, /*!< Flash memory index property.*/ - kFLASH_PropertyFlashCacheControllerIndex = 0x21U /*!< Flash cache controller index property.*/ -} flash_property_tag_t; - -/*! - * @brief Constants for execute-in-RAM flash function. - */ -enum _flash_execute_in_ram_function_constants -{ - kFLASH_ExecuteInRamFunctionMaxSizeInWords = 16U, /*!< The maximum size of execute-in-RAM function.*/ - kFLASH_ExecuteInRamFunctionTotalNum = 2U /*!< Total number of execute-in-RAM functions.*/ -}; - -/*! - * @brief Flash execute-in-RAM function information. - */ -typedef struct _flash_execute_in_ram_function_config -{ - uint32_t activeFunctionCount; /*!< Number of available execute-in-RAM functions.*/ - uint32_t *flashRunCommand; /*!< Execute-in-RAM function: flash_run_command.*/ - uint32_t *flashCommonBitOperation; /*!< Execute-in-RAM function: flash_common_bit_operation.*/ -} flash_execute_in_ram_function_config_t; - -/*! - * @brief Enumeration for the two possible options of flash read resource command. - */ -typedef enum _flash_read_resource_option -{ - kFLASH_ResourceOptionFlashIfr = - 0x00U, /*!< Select code for Program flash 0 IFR, Program flash swap 0 IFR, Data flash 0 IFR */ - kFLASH_ResourceOptionVersionId = 0x01U /*!< Select code for the version ID*/ -} flash_read_resource_option_t; - -/*! - * @brief Enumeration for the range of special-purpose flash resource - */ -enum _flash_read_resource_range -{ -#if (FSL_FEATURE_FLASH_IS_FTFE == 1) - kFLASH_ResourceRangePflashIfrSizeInBytes = 1024U, /*!< Pflash IFR size in byte.*/ - kFLASH_ResourceRangeVersionIdSizeInBytes = 8U, /*!< Version ID IFR size in byte.*/ - kFLASH_ResourceRangeVersionIdStart = 0x08U, /*!< Version ID IFR start address.*/ - kFLASH_ResourceRangeVersionIdEnd = 0x0FU, /*!< Version ID IFR end address.*/ - kFLASH_ResourceRangePflashSwapIfrStart = 0x40000U, /*!< Pflash swap IFR start address.*/ - kFLASH_ResourceRangePflashSwapIfrEnd = - (kFLASH_ResourceRangePflashSwapIfrStart + 0x3FFU), /*!< Pflash swap IFR end address.*/ -#else /* FSL_FEATURE_FLASH_IS_FTFL == 1 or FSL_FEATURE_FLASH_IS_FTFA = =1 */ - kFLASH_ResourceRangePflashIfrSizeInBytes = 256U, /*!< Pflash IFR size in byte.*/ - kFLASH_ResourceRangeVersionIdSizeInBytes = 8U, /*!< Version ID IFR size in byte.*/ - kFLASH_ResourceRangeVersionIdStart = 0x00U, /*!< Version ID IFR start address.*/ - kFLASH_ResourceRangeVersionIdEnd = 0x07U, /*!< Version ID IFR end address.*/ -#if 0x20000U == (FSL_FEATURE_FLASH_PFLASH_BLOCK_COUNT * FSL_FEATURE_FLASH_PFLASH_BLOCK_SIZE) - kFLASH_ResourceRangePflashSwapIfrStart = 0x8000U, /*!< Pflash swap IFR start address.*/ -#elif 0x40000U == (FSL_FEATURE_FLASH_PFLASH_BLOCK_COUNT * FSL_FEATURE_FLASH_PFLASH_BLOCK_SIZE) - kFLASH_ResourceRangePflashSwapIfrStart = 0x10000U, /*!< Pflash swap IFR start address.*/ -#elif 0x80000U == (FSL_FEATURE_FLASH_PFLASH_BLOCK_COUNT * FSL_FEATURE_FLASH_PFLASH_BLOCK_SIZE) - kFLASH_ResourceRangePflashSwapIfrStart = 0x20000U, /*!< Pflash swap IFR start address.*/ -#else - kFLASH_ResourceRangePflashSwapIfrStart = 0, -#endif - kFLASH_ResourceRangePflashSwapIfrEnd = - (kFLASH_ResourceRangePflashSwapIfrStart + 0xFFU), /*!< Pflash swap IFR end address.*/ -#endif - kFLASH_ResourceRangeDflashIfrStart = 0x800000U, /*!< Dflash IFR start address.*/ - kFLASH_ResourceRangeDflashIfrEnd = 0x8003FFU, /*!< Dflash IFR end address.*/ -}; - -/*! - * @brief Enumeration for the index of read/program once record - */ -enum _k3_flash_read_once_index -{ - kFLASH_RecordIndexSwapAddr = 0xA1U, /*!< Index of Swap indicator address.*/ - kFLASH_RecordIndexSwapEnable = 0xA2U, /*!< Index of Swap system enable.*/ - kFLASH_RecordIndexSwapDisable = 0xA3U, /*!< Index of Swap system disable.*/ -}; - -/*! - * @brief Enumeration for the two possilbe options of set FlexRAM function command. - */ -typedef enum _flash_flexram_function_option -{ - kFLASH_FlexramFunctionOptionAvailableAsRam = 0xFFU, /*!< An option used to make FlexRAM available as RAM */ - kFLASH_FlexramFunctionOptionAvailableForEeprom = 0x00U /*!< An option used to make FlexRAM available for EEPROM */ -} flash_flexram_function_option_t; - -/*! - * @brief Enumeration for acceleration RAM property. - */ -enum _flash_acceleration_ram_property -{ - kFLASH_AccelerationRamSize = 0x400U -}; - -/*! - * @brief Enumeration for the possible options of Swap function - */ -typedef enum _flash_swap_function_option -{ - kFLASH_SwapFunctionOptionEnable = 0x00U, /*!< An option used to enable the Swap function */ - kFLASH_SwapFunctionOptionDisable = 0x01U /*!< An option used to disable the Swap function */ -} flash_swap_function_option_t; - -/*! - * @brief Enumeration for the possible options of Swap control commands - */ -typedef enum _flash_swap_control_option -{ - kFLASH_SwapControlOptionIntializeSystem = 0x01U, /*!< An option used to initialize the Swap system */ - kFLASH_SwapControlOptionSetInUpdateState = 0x02U, /*!< An option used to set the Swap in an update state */ - kFLASH_SwapControlOptionSetInCompleteState = 0x04U, /*!< An option used to set the Swap in a complete state */ - kFLASH_SwapControlOptionReportStatus = 0x08U, /*!< An option used to report the Swap status */ - kFLASH_SwapControlOptionDisableSystem = 0x10U /*!< An option used to disable the Swap status */ -} flash_swap_control_option_t; - -/*! - * @brief Enumeration for the possible flash Swap status. - */ -typedef enum _flash_swap_state -{ - kFLASH_SwapStateUninitialized = 0x00U, /*!< Flash Swap system is in an uninitialized state.*/ - kFLASH_SwapStateReady = 0x01U, /*!< Flash Swap system is in a ready state.*/ - kFLASH_SwapStateUpdate = 0x02U, /*!< Flash Swap system is in an update state.*/ - kFLASH_SwapStateUpdateErased = 0x03U, /*!< Flash Swap system is in an updateErased state.*/ - kFLASH_SwapStateComplete = 0x04U, /*!< Flash Swap system is in a complete state.*/ - kFLASH_SwapStateDisabled = 0x05U /*!< Flash Swap system is in a disabled state.*/ -} flash_swap_state_t; - -/*! - * @breif Enumeration for the possible flash Swap block status - */ -typedef enum _flash_swap_block_status -{ - kFLASH_SwapBlockStatusLowerHalfProgramBlocksAtZero = - 0x00U, /*!< Swap block status is that lower half program block at zero.*/ - kFLASH_SwapBlockStatusUpperHalfProgramBlocksAtZero = - 0x01U, /*!< Swap block status is that upper half program block at zero.*/ -} flash_swap_block_status_t; - -/*! - * @brief Flash Swap information - */ -typedef struct _flash_swap_state_config -{ - flash_swap_state_t flashSwapState; /*!chip < FB_CSAR_COUNT); - assert(config->waitStates <= 0x3FU); - - uint32_t chip = 0; - uint32_t reg_value = 0; - -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) - /* Ungate clock for FLEXBUS */ - CLOCK_EnableClock(s_flexbusClocks[FLEXBUS_GetInstance(base)]); -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ - - /* Reset all the register to default state */ - for (chip = 0; chip < FB_CSAR_COUNT; chip++) - { - /* Reset CSMR register, all chips not valid (disabled) */ - base->CS[chip].CSMR = 0x0000U; - /* Set default base address */ - base->CS[chip].CSAR &= (~FB_CSAR_BA_MASK); - /* Reset FB_CSCRx register */ - base->CS[chip].CSCR = 0x0000U; - } - /* Set FB_CSPMCR register */ - /* FlexBus signal group 1 multiplex control */ - reg_value |= kFLEXBUS_MultiplexGroup1_FB_ALE << FB_CSPMCR_GROUP1_SHIFT; - /* FlexBus signal group 2 multiplex control */ - reg_value |= kFLEXBUS_MultiplexGroup2_FB_CS4 << FB_CSPMCR_GROUP2_SHIFT; - /* FlexBus signal group 3 multiplex control */ - reg_value |= kFLEXBUS_MultiplexGroup3_FB_CS5 << FB_CSPMCR_GROUP3_SHIFT; - /* FlexBus signal group 4 multiplex control */ - reg_value |= kFLEXBUS_MultiplexGroup4_FB_TBST << FB_CSPMCR_GROUP4_SHIFT; - /* FlexBus signal group 5 multiplex control */ - reg_value |= kFLEXBUS_MultiplexGroup5_FB_TA << FB_CSPMCR_GROUP5_SHIFT; - /* Write to CSPMCR register */ - base->CSPMCR = reg_value; - - /* Update chip value */ - chip = config->chip; - - /* Base address */ - reg_value = config->chipBaseAddress; - /* Write to CSAR register */ - base->CS[chip].CSAR = reg_value; - /* Chip-select validation */ - reg_value = 0x1U << FB_CSMR_V_SHIFT; - /* Write protect */ - reg_value |= (uint32_t)(config->writeProtect) << FB_CSMR_WP_SHIFT; - /* Base address mask */ - reg_value |= config->chipBaseAddressMask << FB_CSMR_BAM_SHIFT; - /* Write to CSMR register */ - base->CS[chip].CSMR = reg_value; - /* Burst write */ - reg_value = (uint32_t)(config->burstWrite) << FB_CSCR_BSTW_SHIFT; - /* Burst read */ - reg_value |= (uint32_t)(config->burstRead) << FB_CSCR_BSTR_SHIFT; - /* Byte-enable mode */ - reg_value |= (uint32_t)(config->byteEnableMode) << FB_CSCR_BEM_SHIFT; - /* Port size */ - reg_value |= (uint32_t)config->portSize << FB_CSCR_PS_SHIFT; - /* The internal transfer acknowledge for accesses */ - reg_value |= (uint32_t)(config->autoAcknowledge) << FB_CSCR_AA_SHIFT; - /* Byte-Lane shift */ - reg_value |= (uint32_t)config->byteLaneShift << FB_CSCR_BLS_SHIFT; - /* The number of wait states */ - reg_value |= (uint32_t)config->waitStates << FB_CSCR_WS_SHIFT; - /* Write address hold or deselect */ - reg_value |= (uint32_t)config->writeAddressHold << FB_CSCR_WRAH_SHIFT; - /* Read address hold or deselect */ - reg_value |= (uint32_t)config->readAddressHold << FB_CSCR_RDAH_SHIFT; - /* Address setup */ - reg_value |= (uint32_t)config->addressSetup << FB_CSCR_ASET_SHIFT; - /* Extended transfer start/extended address latch */ - reg_value |= (uint32_t)(config->extendTransferAddress) << FB_CSCR_EXTS_SHIFT; - /* Secondary wait state */ - reg_value |= (uint32_t)(config->secondaryWaitStates) << FB_CSCR_SWSEN_SHIFT; - /* Write to CSCR register */ - base->CS[chip].CSCR = reg_value; - /* FlexBus signal group 1 multiplex control */ - reg_value = (uint32_t)config->group1MultiplexControl << FB_CSPMCR_GROUP1_SHIFT; - /* FlexBus signal group 2 multiplex control */ - reg_value |= (uint32_t)config->group2MultiplexControl << FB_CSPMCR_GROUP2_SHIFT; - /* FlexBus signal group 3 multiplex control */ - reg_value |= (uint32_t)config->group3MultiplexControl << FB_CSPMCR_GROUP3_SHIFT; - /* FlexBus signal group 4 multiplex control */ - reg_value |= (uint32_t)config->group4MultiplexControl << FB_CSPMCR_GROUP4_SHIFT; - /* FlexBus signal group 5 multiplex control */ - reg_value |= (uint32_t)config->group5MultiplexControl << FB_CSPMCR_GROUP5_SHIFT; - /* Write to CSPMCR register */ - base->CSPMCR = reg_value; -} - -void FLEXBUS_Deinit(FB_Type *base) -{ -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) - /* Gate clock for FLEXBUS */ - CLOCK_DisableClock(s_flexbusClocks[FLEXBUS_GetInstance(base)]); -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ -} - -void FLEXBUS_GetDefaultConfig(flexbus_config_t *config) -{ - config->chip = 0; /* Chip 0 FlexBus for validation */ - config->writeProtect = 0; /* Write accesses are allowed */ - config->burstWrite = 0; /* Burst-Write disable */ - config->burstRead = 0; /* Burst-Read disable */ - config->byteEnableMode = 0; /* Byte-Enable mode is asserted for data write only */ - config->autoAcknowledge = true; /* Auto-Acknowledge enable */ - config->extendTransferAddress = 0; /* Extend transfer start/extend address latch disable */ - config->secondaryWaitStates = 0; /* Secondary wait state disable */ - config->byteLaneShift = kFLEXBUS_NotShifted; /* Byte-Lane shift disable */ - config->writeAddressHold = kFLEXBUS_Hold1Cycle; /* Write address hold 1 cycles */ - config->readAddressHold = kFLEXBUS_Hold1Or0Cycles; /* Read address hold 0 cycles */ - config->addressSetup = - kFLEXBUS_FirstRisingEdge; /* Assert ~FB_CSn on the first rising clock edge after the address is asserted */ - config->portSize = kFLEXBUS_1Byte; /* 1 byte port size of transfer */ - config->group1MultiplexControl = kFLEXBUS_MultiplexGroup1_FB_ALE; /* FB_ALE */ - config->group2MultiplexControl = kFLEXBUS_MultiplexGroup2_FB_CS4; /* FB_CS4 */ - config->group3MultiplexControl = kFLEXBUS_MultiplexGroup3_FB_CS5; /* FB_CS5 */ - config->group4MultiplexControl = kFLEXBUS_MultiplexGroup4_FB_TBST; /* FB_TBST */ - config->group5MultiplexControl = kFLEXBUS_MultiplexGroup5_FB_TA; /* FB_TA */ -} diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_flexbus.h b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_flexbus.h deleted file mode 100644 index f20ed44f055..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_flexbus.h +++ /dev/null @@ -1,265 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef _FSL_FLEXBUS_H_ -#define _FSL_FLEXBUS_H_ - -#include "fsl_common.h" - -/*! - * @addtogroup flexbus - * @{ - */ - - -/******************************************************************************* - * Definitions - ******************************************************************************/ - -/*! @name Driver version */ -/*@{*/ -#define FSL_FLEXBUS_DRIVER_VERSION (MAKE_VERSION(2, 0, 1)) /*!< Version 2.0.1. */ -/*@}*/ - -/*! - * @brief Defines port size for FlexBus peripheral. - */ -typedef enum _flexbus_port_size -{ - kFLEXBUS_4Bytes = 0x00U, /*!< 32-bit port size */ - kFLEXBUS_1Byte = 0x01U, /*!< 8-bit port size */ - kFLEXBUS_2Bytes = 0x02U /*!< 16-bit port size */ -} flexbus_port_size_t; - -/*! - * @brief Defines number of cycles to hold address and attributes for FlexBus peripheral. - */ -typedef enum _flexbus_write_address_hold -{ - kFLEXBUS_Hold1Cycle = 0x00U, /*!< Hold address and attributes one cycles after FB_CSn negates on writes */ - kFLEXBUS_Hold2Cycles = 0x01U, /*!< Hold address and attributes two cycles after FB_CSn negates on writes */ - kFLEXBUS_Hold3Cycles = 0x02U, /*!< Hold address and attributes three cycles after FB_CSn negates on writes */ - kFLEXBUS_Hold4Cycles = 0x03U /*!< Hold address and attributes four cycles after FB_CSn negates on writes */ -} flexbus_write_address_hold_t; - -/*! - * @brief Defines number of cycles to hold address and attributes for FlexBus peripheral. - */ -typedef enum _flexbus_read_address_hold -{ - kFLEXBUS_Hold1Or0Cycles = 0x00U, /*!< Hold address and attributes 1 or 0 cycles on reads */ - kFLEXBUS_Hold2Or1Cycles = 0x01U, /*!< Hold address and attributes 2 or 1 cycles on reads */ - kFLEXBUS_Hold3Or2Cycle = 0x02U, /*!< Hold address and attributes 3 or 2 cycles on reads */ - kFLEXBUS_Hold4Or3Cycle = 0x03U /*!< Hold address and attributes 4 or 3 cycles on reads */ -} flexbus_read_address_hold_t; - -/*! - * @brief Address setup for FlexBus peripheral. - */ -typedef enum _flexbus_address_setup -{ - kFLEXBUS_FirstRisingEdge = 0x00U, /*!< Assert FB_CSn on first rising clock edge after address is asserted */ - kFLEXBUS_SecondRisingEdge = 0x01U, /*!< Assert FB_CSn on second rising clock edge after address is asserted */ - kFLEXBUS_ThirdRisingEdge = 0x02U, /*!< Assert FB_CSn on third rising clock edge after address is asserted */ - kFLEXBUS_FourthRisingEdge = 0x03U, /*!< Assert FB_CSn on fourth rising clock edge after address is asserted */ -} flexbus_address_setup_t; - -/*! - * @brief Defines byte-lane shift for FlexBus peripheral. - */ -typedef enum _flexbus_bytelane_shift -{ - kFLEXBUS_NotShifted = 0x00U, /*!< Not shifted. Data is left-justified on FB_AD */ - kFLEXBUS_Shifted = 0x01U, /*!< Shifted. Data is right justified on FB_AD */ -} flexbus_bytelane_shift_t; - -/*! - * @brief Defines multiplex group1 valid signals. - */ -typedef enum _flexbus_multiplex_group1_signal -{ - kFLEXBUS_MultiplexGroup1_FB_ALE = 0x00U, /*!< FB_ALE */ - kFLEXBUS_MultiplexGroup1_FB_CS1 = 0x01U, /*!< FB_CS1 */ - kFLEXBUS_MultiplexGroup1_FB_TS = 0x02U, /*!< FB_TS */ -} flexbus_multiplex_group1_t; - -/*! - * @brief Defines multiplex group2 valid signals. - */ -typedef enum _flexbus_multiplex_group2_signal -{ - kFLEXBUS_MultiplexGroup2_FB_CS4 = 0x00U, /*!< FB_CS4 */ - kFLEXBUS_MultiplexGroup2_FB_TSIZ0 = 0x01U, /*!< FB_TSIZ0 */ - kFLEXBUS_MultiplexGroup2_FB_BE_31_24 = 0x02U, /*!< FB_BE_31_24 */ -} flexbus_multiplex_group2_t; - -/*! - * @brief Defines multiplex group3 valid signals. - */ -typedef enum _flexbus_multiplex_group3_signal -{ - kFLEXBUS_MultiplexGroup3_FB_CS5 = 0x00U, /*!< FB_CS5 */ - kFLEXBUS_MultiplexGroup3_FB_TSIZ1 = 0x01U, /*!< FB_TSIZ1 */ - kFLEXBUS_MultiplexGroup3_FB_BE_23_16 = 0x02U, /*!< FB_BE_23_16 */ -} flexbus_multiplex_group3_t; - -/*! - * @brief Defines multiplex group4 valid signals. - */ -typedef enum _flexbus_multiplex_group4_signal -{ - kFLEXBUS_MultiplexGroup4_FB_TBST = 0x00U, /*!< FB_TBST */ - kFLEXBUS_MultiplexGroup4_FB_CS2 = 0x01U, /*!< FB_CS2 */ - kFLEXBUS_MultiplexGroup4_FB_BE_15_8 = 0x02U, /*!< FB_BE_15_8 */ -} flexbus_multiplex_group4_t; - -/*! - * @brief Defines multiplex group5 valid signals. - */ -typedef enum _flexbus_multiplex_group5_signal -{ - kFLEXBUS_MultiplexGroup5_FB_TA = 0x00U, /*!< FB_TA */ - kFLEXBUS_MultiplexGroup5_FB_CS3 = 0x01U, /*!< FB_CS3 */ - kFLEXBUS_MultiplexGroup5_FB_BE_7_0 = 0x02U, /*!< FB_BE_7_0 */ -} flexbus_multiplex_group5_t; - -/*! - * @brief Configuration structure that the user needs to set. - */ -typedef struct _flexbus_config -{ - uint8_t chip; /*!< Chip FlexBus for validation */ - uint8_t waitStates; /*!< Value of wait states */ - uint32_t chipBaseAddress; /*!< Chip base address for using FlexBus */ - uint32_t chipBaseAddressMask; /*!< Chip base address mask */ - bool writeProtect; /*!< Write protected */ - bool burstWrite; /*!< Burst-Write enable */ - bool burstRead; /*!< Burst-Read enable */ - bool byteEnableMode; /*!< Byte-enable mode support */ - bool autoAcknowledge; /*!< Auto acknowledge setting */ - bool extendTransferAddress; /*!< Extend transfer start/extend address latch enable */ - bool secondaryWaitStates; /*!< Secondary wait states number */ - flexbus_port_size_t portSize; /*!< Port size of transfer */ - flexbus_bytelane_shift_t byteLaneShift; /*!< Byte-lane shift enable */ - flexbus_write_address_hold_t writeAddressHold; /*!< Write address hold or deselect option */ - flexbus_read_address_hold_t readAddressHold; /*!< Read address hold or deselect option */ - flexbus_address_setup_t addressSetup; /*!< Address setup setting */ - flexbus_multiplex_group1_t group1MultiplexControl; /*!< FlexBus Signal Group 1 Multiplex control */ - flexbus_multiplex_group2_t group2MultiplexControl; /*!< FlexBus Signal Group 2 Multiplex control */ - flexbus_multiplex_group3_t group3MultiplexControl; /*!< FlexBus Signal Group 3 Multiplex control */ - flexbus_multiplex_group4_t group4MultiplexControl; /*!< FlexBus Signal Group 4 Multiplex control */ - flexbus_multiplex_group5_t group5MultiplexControl; /*!< FlexBus Signal Group 5 Multiplex control */ -} flexbus_config_t; - -/******************************************************************************* - * API - ******************************************************************************/ - -#if defined(__cplusplus) -extern "C" { -#endif /* __cplusplus */ - -/*! - * @name FlexBus functional operation - * @{ - */ - -/*! - * @brief Initializes and configures the FlexBus module. - * - * This function enables the clock gate for FlexBus module. - * Only chip 0 is validated and set to known values. Other chips are disabled. - * Note that in this function, certain parameters, depending on external memories, must - * be set before using the FLEXBUS_Init() function. - * This example shows how to set up the uart_state_t and the - * flexbus_config_t parameters and how to call the FLEXBUS_Init function by passing - * in these parameters. - @code - flexbus_config_t flexbusConfig; - FLEXBUS_GetDefaultConfig(&flexbusConfig); - flexbusConfig.waitStates = 2U; - flexbusConfig.chipBaseAddress = 0x60000000U; - flexbusConfig.chipBaseAddressMask = 7U; - FLEXBUS_Init(FB, &flexbusConfig); - @endcode - * - * @param base FlexBus peripheral address. - * @param config Pointer to the configuration structure -*/ -void FLEXBUS_Init(FB_Type *base, const flexbus_config_t *config); - -/*! - * @brief De-initializes a FlexBus instance. - * - * This function disables the clock gate of the FlexBus module clock. - * - * @param base FlexBus peripheral address. - */ -void FLEXBUS_Deinit(FB_Type *base); - -/*! - * @brief Initializes the FlexBus configuration structure. - * - * This function initializes the FlexBus configuration structure to default value. The default - * values are. - @code - fbConfig->chip = 0; - fbConfig->writeProtect = 0; - fbConfig->burstWrite = 0; - fbConfig->burstRead = 0; - fbConfig->byteEnableMode = 0; - fbConfig->autoAcknowledge = true; - fbConfig->extendTransferAddress = 0; - fbConfig->secondaryWaitStates = 0; - fbConfig->byteLaneShift = kFLEXBUS_NotShifted; - fbConfig->writeAddressHold = kFLEXBUS_Hold1Cycle; - fbConfig->readAddressHold = kFLEXBUS_Hold1Or0Cycles; - fbConfig->addressSetup = kFLEXBUS_FirstRisingEdge; - fbConfig->portSize = kFLEXBUS_1Byte; - fbConfig->group1MultiplexControl = kFLEXBUS_MultiplexGroup1_FB_ALE; - fbConfig->group2MultiplexControl = kFLEXBUS_MultiplexGroup2_FB_CS4 ; - fbConfig->group3MultiplexControl = kFLEXBUS_MultiplexGroup3_FB_CS5; - fbConfig->group4MultiplexControl = kFLEXBUS_MultiplexGroup4_FB_TBST; - fbConfig->group5MultiplexControl = kFLEXBUS_MultiplexGroup5_FB_TA; - @endcode - * @param config Pointer to the initialization structure. - * @see FLEXBUS_Init - */ -void FLEXBUS_GetDefaultConfig(flexbus_config_t *config); - -/*! @}*/ - -#if defined(__cplusplus) -} -#endif /* __cplusplus */ - -/*! @}*/ - -#endif /* _FSL_FLEXBUS_H_ */ diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_flexcan.c b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_flexcan.c deleted file mode 100644 index f58f3f55f05..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_flexcan.c +++ /dev/null @@ -1,1407 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "fsl_flexcan.h" - -/******************************************************************************* - * Definitons - ******************************************************************************/ - -#define FLEXCAN_TIME_QUANTA_NUM (10) - -/*! @brief FlexCAN Internal State. */ -enum _flexcan_state -{ - kFLEXCAN_StateIdle = 0x0, /*!< MB/RxFIFO idle.*/ - kFLEXCAN_StateRxData = 0x1, /*!< MB receiving.*/ - kFLEXCAN_StateRxRemote = 0x2, /*!< MB receiving remote reply.*/ - kFLEXCAN_StateTxData = 0x3, /*!< MB transmitting.*/ - kFLEXCAN_StateTxRemote = 0x4, /*!< MB transmitting remote request.*/ - kFLEXCAN_StateRxFifo = 0x5, /*!< RxFIFO receiving.*/ -}; - -/*! @brief FlexCAN message buffer CODE for Rx buffers. */ -enum _flexcan_mb_code_rx -{ - kFLEXCAN_RxMbInactive = 0x0, /*!< MB is not active.*/ - kFLEXCAN_RxMbFull = 0x2, /*!< MB is full.*/ - kFLEXCAN_RxMbEmpty = 0x4, /*!< MB is active and empty.*/ - kFLEXCAN_RxMbOverrun = 0x6, /*!< MB is overwritten into a full buffer.*/ - kFLEXCAN_RxMbBusy = 0x8, /*!< FlexCAN is updating the contents of the MB.*/ - /*! The CPU must not access the MB.*/ - kFLEXCAN_RxMbRanswer = 0xA, /*!< A frame was configured to recognize a Remote Request Frame */ - /*! and transmit a Response Frame in return.*/ - kFLEXCAN_RxMbNotUsed = 0xF, /*!< Not used.*/ -}; - -/*! @brief FlexCAN message buffer CODE FOR Tx buffers. */ -enum _flexcan_mb_code_tx -{ - kFLEXCAN_TxMbInactive = 0x8, /*!< MB is not active.*/ - kFLEXCAN_TxMbAbort = 0x9, /*!< MB is aborted.*/ - kFLEXCAN_TxMbDataOrRemote = 0xC, /*!< MB is a TX Data Frame(when MB RTR = 0) or */ - /*!< MB is a TX Remote Request Frame (when MB RTR = 1).*/ - kFLEXCAN_TxMbTanswer = 0xE, /*!< MB is a TX Response Request Frame from */ - /*! an incoming Remote Request Frame.*/ - kFLEXCAN_TxMbNotUsed = 0xF, /*!< Not used.*/ -}; - -/* Typedef for interrupt handler. */ -typedef void (*flexcan_isr_t)(CAN_Type *base, flexcan_handle_t *handle); - -/******************************************************************************* - * Prototypes - ******************************************************************************/ - -/*! - * @brief Get the FlexCAN instance from peripheral base address. - * - * @param base FlexCAN peripheral base address. - * @return FlexCAN instance. - */ -uint32_t FLEXCAN_GetInstance(CAN_Type *base); - -/*! - * @brief Enter FlexCAN Freeze Mode. - * - * This function makes the FlexCAN work under Freeze Mode. - * - * @param base FlexCAN peripheral base address. - */ -static void FLEXCAN_EnterFreezeMode(CAN_Type *base); - -/*! - * @brief Exit FlexCAN Freeze Mode. - * - * This function makes the FlexCAN leave Freeze Mode. - * - * @param base FlexCAN peripheral base address. - */ -static void FLEXCAN_ExitFreezeMode(CAN_Type *base); - -#if !defined(NDEBUG) -/*! - * @brief Check if Message Buffer is occupied by Rx FIFO. - * - * This function check if Message Buffer is occupied by Rx FIFO. - * - * @param base FlexCAN peripheral base address. - * @param mbIdx The FlexCAN Message Buffer index. - */ -static bool FLEXCAN_IsMbOccupied(CAN_Type *base, uint8_t mbIdx); -#endif - -#if (defined(FSL_FEATURE_FLEXCAN_HAS_ERRATA_5641) && FSL_FEATURE_FLEXCAN_HAS_ERRATA_5641) -/*! - * @brief Get the first valid Message buffer ID of give FlexCAN instance. - * - * This function is a helper function for Errata 5641 workaround. - * - * @param base FlexCAN peripheral base address. - * @return The first valid Message Buffer Number. - */ -static uint32_t FLEXCAN_GetFirstValidMb(CAN_Type *base); -#endif - -/*! - * @brief Check if Message Buffer interrupt is enabled. - * - * This function check if Message Buffer interrupt is enabled. - * - * @param base FlexCAN peripheral base address. - * @param mbIdx The FlexCAN Message Buffer index. - */ -static bool FLEXCAN_IsMbIntEnabled(CAN_Type *base, uint8_t mbIdx); - -/*! - * @brief Reset the FlexCAN Instance. - * - * Restores the FlexCAN module to reset state, notice that this function - * will set all the registers to reset state so the FlexCAN module can not work - * after calling this API. - * - * @param base FlexCAN peripheral base address. -*/ -static void FLEXCAN_Reset(CAN_Type *base); - -/*! - * @brief Set Baud Rate of FlexCAN. - * - * This function set the baud rate of FlexCAN. - * - * @param base FlexCAN peripheral base address. - * @param sourceClock_Hz Source Clock in Hz. - * @param baudRate_Bps Baud Rate in Bps. - */ -static void FLEXCAN_SetBaudRate(CAN_Type *base, uint32_t sourceClock_Hz, uint32_t baudRate_Bps); - -/******************************************************************************* - * Variables - ******************************************************************************/ - -/* Array of FlexCAN peripheral base address. */ -static CAN_Type *const s_flexcanBases[] = CAN_BASE_PTRS; - -/* Array of FlexCAN IRQ number. */ -static const IRQn_Type s_flexcanRxWarningIRQ[] = CAN_Rx_Warning_IRQS; -static const IRQn_Type s_flexcanTxWarningIRQ[] = CAN_Tx_Warning_IRQS; -static const IRQn_Type s_flexcanWakeUpIRQ[] = CAN_Wake_Up_IRQS; -static const IRQn_Type s_flexcanErrorIRQ[] = CAN_Error_IRQS; -static const IRQn_Type s_flexcanBusOffIRQ[] = CAN_Bus_Off_IRQS; -static const IRQn_Type s_flexcanMbIRQ[] = CAN_ORed_Message_buffer_IRQS; - -/* Array of FlexCAN handle. */ -static flexcan_handle_t *s_flexcanHandle[ARRAY_SIZE(s_flexcanBases)]; - -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) -/* Array of FlexCAN clock name. */ -static const clock_ip_name_t s_flexcanClock[] = FLEXCAN_CLOCKS; -#if defined(FLEXCAN_PERIPH_CLOCKS) -/* Array of FlexCAN serial clock name. */ -static const clock_ip_name_t s_flexcanPeriphClock[] = FLEXCAN_PERIPH_CLOCKS; -#endif /* FLEXCAN_PERIPH_CLOCKS */ -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ - -/* FlexCAN ISR for transactional APIs. */ -static flexcan_isr_t s_flexcanIsr; - -/******************************************************************************* - * Code - ******************************************************************************/ - -uint32_t FLEXCAN_GetInstance(CAN_Type *base) -{ - uint32_t instance; - - /* Find the instance index from base address mappings. */ - for (instance = 0; instance < ARRAY_SIZE(s_flexcanBases); instance++) - { - if (s_flexcanBases[instance] == base) - { - break; - } - } - - assert(instance < ARRAY_SIZE(s_flexcanBases)); - - return instance; -} - -static void FLEXCAN_EnterFreezeMode(CAN_Type *base) -{ - /* Set Freeze, Halt bits. */ - base->MCR |= CAN_MCR_HALT_MASK; - - /* Wait until the FlexCAN Module enter freeze mode. */ - while (!(base->MCR & CAN_MCR_FRZACK_MASK)) - { - } -} - -static void FLEXCAN_ExitFreezeMode(CAN_Type *base) -{ - /* Clear Freeze, Halt bits. */ - base->MCR &= ~CAN_MCR_HALT_MASK; - - /* Wait until the FlexCAN Module exit freeze mode. */ - while (base->MCR & CAN_MCR_FRZACK_MASK) - { - } -} - -#if !defined(NDEBUG) -static bool FLEXCAN_IsMbOccupied(CAN_Type *base, uint8_t mbIdx) -{ - uint8_t lastOccupiedMb; - - /* Is Rx FIFO enabled? */ - if (base->MCR & CAN_MCR_RFEN_MASK) - { - /* Get RFFN value. */ - lastOccupiedMb = ((base->CTRL2 & CAN_CTRL2_RFFN_MASK) >> CAN_CTRL2_RFFN_SHIFT); - /* Calculate the number of last Message Buffer occupied by Rx FIFO. */ - lastOccupiedMb = ((lastOccupiedMb + 1) * 2) + 5; - -#if (defined(FSL_FEATURE_FLEXCAN_HAS_ERRATA_5641) && FSL_FEATURE_FLEXCAN_HAS_ERRATA_5641) - if (mbIdx <= (lastOccupiedMb + 1)) -#else - if (mbIdx <= lastOccupiedMb) -#endif - { - return true; - } - else - { - return false; - } - } - else - { -#if (defined(FSL_FEATURE_FLEXCAN_HAS_ERRATA_5641) && FSL_FEATURE_FLEXCAN_HAS_ERRATA_5641) - if (0 == mbIdx) - { - return true; - } - else - { - return false; - } -#else - return false; -#endif - } -} -#endif - -#if (defined(FSL_FEATURE_FLEXCAN_HAS_ERRATA_5641) && FSL_FEATURE_FLEXCAN_HAS_ERRATA_5641) -static uint32_t FLEXCAN_GetFirstValidMb(CAN_Type *base) -{ - uint32_t firstValidMbNum; - - if (base->MCR & CAN_MCR_RFEN_MASK) - { - firstValidMbNum = ((base->CTRL2 & CAN_CTRL2_RFFN_MASK) >> CAN_CTRL2_RFFN_SHIFT); - firstValidMbNum = ((firstValidMbNum + 1) * 2) + 6; - } - else - { - firstValidMbNum = 0; - } - - return firstValidMbNum; -} -#endif - -static bool FLEXCAN_IsMbIntEnabled(CAN_Type *base, uint8_t mbIdx) -{ - /* Assertion. */ - assert(mbIdx < FSL_FEATURE_FLEXCAN_HAS_MESSAGE_BUFFER_MAX_NUMBERn(base)); - -#if (FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER > 0) - if (mbIdx < 32) - { -#endif - if (base->IMASK1 & ((uint32_t)(1 << mbIdx))) - { - return true; - } - else - { - return false; - } -#if (FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER > 0) - } - else - { - if (base->IMASK2 & ((uint32_t)(1 << (mbIdx - 32)))) - { - return true; - } - else - { - return false; - } - } -#endif -} - -static void FLEXCAN_Reset(CAN_Type *base) -{ - /* The module must should be first exit from low power - * mode, and then soft reset can be applied. - */ - assert(!(base->MCR & CAN_MCR_MDIS_MASK)); - - uint8_t i; - -#if (FSL_FEATURE_FLEXCAN_HAS_DOZE_MODE_SUPPORT != 0) - /* De-assert DOZE Enable Bit. */ - base->MCR &= ~CAN_MCR_DOZE_MASK; -#endif - - /* Wait until FlexCAN exit from any Low Power Mode. */ - while (base->MCR & CAN_MCR_LPMACK_MASK) - { - } - - /* Assert Soft Reset Signal. */ - base->MCR |= CAN_MCR_SOFTRST_MASK; - /* Wait until FlexCAN reset completes. */ - while (base->MCR & CAN_MCR_SOFTRST_MASK) - { - } - -/* Reset MCR rigister. */ -#if (defined(FSL_FEATURE_FLEXCAN_HAS_GLITCH_FILTER) && FSL_FEATURE_FLEXCAN_HAS_GLITCH_FILTER) - base->MCR |= CAN_MCR_WRNEN_MASK | CAN_MCR_WAKSRC_MASK | - CAN_MCR_MAXMB(FSL_FEATURE_FLEXCAN_HAS_MESSAGE_BUFFER_MAX_NUMBERn(base) - 1); -#else - base->MCR |= CAN_MCR_WRNEN_MASK | CAN_MCR_MAXMB(FSL_FEATURE_FLEXCAN_HAS_MESSAGE_BUFFER_MAX_NUMBERn(base) - 1); -#endif - - /* Reset CTRL1 and CTRL2 rigister. */ - base->CTRL1 = CAN_CTRL1_SMP_MASK; - base->CTRL2 = CAN_CTRL2_TASD(0x16) | CAN_CTRL2_RRS_MASK | CAN_CTRL2_EACEN_MASK; - - /* Clean all individual Rx Mask of Message Buffers. */ - for (i = 0; i < FSL_FEATURE_FLEXCAN_HAS_MESSAGE_BUFFER_MAX_NUMBERn(base); i++) - { - base->RXIMR[i] = 0x3FFFFFFF; - } - - /* Clean Global Mask of Message Buffers. */ - base->RXMGMASK = 0x3FFFFFFF; - /* Clean Global Mask of Message Buffer 14. */ - base->RX14MASK = 0x3FFFFFFF; - /* Clean Global Mask of Message Buffer 15. */ - base->RX15MASK = 0x3FFFFFFF; - /* Clean Global Mask of Rx FIFO. */ - base->RXFGMASK = 0x3FFFFFFF; - - /* Clean all Message Buffer CS fields. */ - for (i = 0; i < FSL_FEATURE_FLEXCAN_HAS_MESSAGE_BUFFER_MAX_NUMBERn(base); i++) - { - base->MB[i].CS = 0x0; - } -} - -static void FLEXCAN_SetBaudRate(CAN_Type *base, uint32_t sourceClock_Hz, uint32_t baudRate_Bps) -{ - flexcan_timing_config_t timingConfig; - uint32_t priDiv = baudRate_Bps * FLEXCAN_TIME_QUANTA_NUM; - - /* Assertion: Desired baud rate is too high. */ - assert(baudRate_Bps <= 1000000U); - /* Assertion: Source clock should greater than baud rate * FLEXCAN_TIME_QUANTA_NUM. */ - assert(priDiv <= sourceClock_Hz); - - if (0 == priDiv) - { - priDiv = 1; - } - - priDiv = (sourceClock_Hz / priDiv) - 1; - - /* Desired baud rate is too low. */ - if (priDiv > 0xFF) - { - priDiv = 0xFF; - } - - /* FlexCAN timing setting formula: - * FLEXCAN_TIME_QUANTA_NUM = 1 + (PSEG1 + 1) + (PSEG2 + 1) + (PROPSEG + 1); - */ - timingConfig.preDivider = priDiv; - timingConfig.phaseSeg1 = 3; - timingConfig.phaseSeg2 = 2; - timingConfig.propSeg = 1; - timingConfig.rJumpwidth = 1; - - /* Update actual timing characteristic. */ - FLEXCAN_SetTimingConfig(base, &timingConfig); -} - -void FLEXCAN_Init(CAN_Type *base, const flexcan_config_t *config, uint32_t sourceClock_Hz) -{ - uint32_t mcrTemp; -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) - uint32_t instance; -#endif - - /* Assertion. */ - assert(config); - assert((config->maxMbNum > 0) && (config->maxMbNum <= FSL_FEATURE_FLEXCAN_HAS_MESSAGE_BUFFER_MAX_NUMBERn(base))); - -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) - instance = FLEXCAN_GetInstance(base); - /* Enable FlexCAN clock. */ - CLOCK_EnableClock(s_flexcanClock[instance]); -#if defined(FLEXCAN_PERIPH_CLOCKS) - /* Enable FlexCAN serial clock. */ - CLOCK_EnableClock(s_flexcanPeriphClock[instance]); -#endif /* FLEXCAN_PERIPH_CLOCKS */ -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ - -#if (!defined(FSL_FEATURE_FLEXCAN_SUPPORT_ENGINE_CLK_SEL_REMOVE)) || !FSL_FEATURE_FLEXCAN_SUPPORT_ENGINE_CLK_SEL_REMOVE - /* Disable FlexCAN Module. */ - FLEXCAN_Enable(base, false); - - /* Protocol-Engine clock source selection, This bit must be set - * when FlexCAN Module in Disable Mode. - */ - base->CTRL1 = (kFLEXCAN_ClkSrcOsc == config->clkSrc) ? base->CTRL1 & ~CAN_CTRL1_CLKSRC_MASK : - base->CTRL1 | CAN_CTRL1_CLKSRC_MASK; -#endif /* FSL_FEATURE_FLEXCAN_SUPPORT_ENGINE_CLK_SEL_REMOVE */ - - /* Enable FlexCAN Module for configuartion. */ - FLEXCAN_Enable(base, true); - - /* Reset to known status. */ - FLEXCAN_Reset(base); - - /* Save current MCR value and enable to enter Freeze mode(enabled by default). */ - mcrTemp = base->MCR; - - /* Set the maximum number of Message Buffers */ - mcrTemp = (mcrTemp & ~CAN_MCR_MAXMB_MASK) | CAN_MCR_MAXMB(config->maxMbNum - 1); - - /* Enable Loop Back Mode? */ - base->CTRL1 = (config->enableLoopBack) ? base->CTRL1 | CAN_CTRL1_LPB_MASK : base->CTRL1 & ~CAN_CTRL1_LPB_MASK; - - /* Enable Self Wake Up Mode? */ - mcrTemp = (config->enableSelfWakeup) ? mcrTemp | CAN_MCR_SLFWAK_MASK : mcrTemp & ~CAN_MCR_SLFWAK_MASK; - - /* Enable Individual Rx Masking? */ - mcrTemp = (config->enableIndividMask) ? mcrTemp | CAN_MCR_IRMQ_MASK : mcrTemp & ~CAN_MCR_IRMQ_MASK; - -#if (defined(FSL_FEATURE_FLEXCAN_HAS_DOZE_MODE_SUPPORT) && FSL_FEATURE_FLEXCAN_HAS_DOZE_MODE_SUPPORT) - /* Enable Doze Mode? */ - mcrTemp = (config->enableDoze) ? mcrTemp | CAN_MCR_DOZE_MASK : mcrTemp & ~CAN_MCR_DOZE_MASK; -#endif - - /* Save MCR Configuation. */ - base->MCR = mcrTemp; - - /* Baud Rate Configuration.*/ - FLEXCAN_SetBaudRate(base, sourceClock_Hz, config->baudRate); -} - -void FLEXCAN_Deinit(CAN_Type *base) -{ -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) - uint32_t instance; -#endif - /* Reset all Register Contents. */ - FLEXCAN_Reset(base); - - /* Disable FlexCAN module. */ - FLEXCAN_Enable(base, false); - -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) - instance = FLEXCAN_GetInstance(base); -#if defined(FLEXCAN_PERIPH_CLOCKS) - /* Disable FlexCAN serial clock. */ - CLOCK_DisableClock(s_flexcanPeriphClock[instance]); -#endif /* FLEXCAN_PERIPH_CLOCKS */ - /* Disable FlexCAN clock. */ - CLOCK_DisableClock(s_flexcanClock[instance]); -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ -} - -void FLEXCAN_GetDefaultConfig(flexcan_config_t *config) -{ - /* Assertion. */ - assert(config); - - /* Initialize FlexCAN Module config struct with default value. */ -#if (!defined(FSL_FEATURE_FLEXCAN_SUPPORT_ENGINE_CLK_SEL_REMOVE)) || !FSL_FEATURE_FLEXCAN_SUPPORT_ENGINE_CLK_SEL_REMOVE - config->clkSrc = kFLEXCAN_ClkSrcOsc; -#endif /* FSL_FEATURE_FLEXCAN_SUPPORT_ENGINE_CLK_SEL_REMOVE */ - config->baudRate = 125000U; - config->maxMbNum = 16; - config->enableLoopBack = false; - config->enableSelfWakeup = false; - config->enableIndividMask = false; -#if (defined(FSL_FEATURE_FLEXCAN_HAS_DOZE_MODE_SUPPORT) && FSL_FEATURE_FLEXCAN_HAS_DOZE_MODE_SUPPORT) - config->enableDoze = false; -#endif -} - -void FLEXCAN_SetTimingConfig(CAN_Type *base, const flexcan_timing_config_t *config) -{ - /* Assertion. */ - assert(config); - - /* Enter Freeze Mode. */ - FLEXCAN_EnterFreezeMode(base); - - /* Cleaning previous Timing Setting. */ - base->CTRL1 &= ~(CAN_CTRL1_PRESDIV_MASK | CAN_CTRL1_RJW_MASK | CAN_CTRL1_PSEG1_MASK | CAN_CTRL1_PSEG2_MASK | - CAN_CTRL1_PROPSEG_MASK); - - /* Updating Timing Setting according to configuration structure. */ - base->CTRL1 |= - (CAN_CTRL1_PRESDIV(config->preDivider) | CAN_CTRL1_RJW(config->rJumpwidth) | - CAN_CTRL1_PSEG1(config->phaseSeg1) | CAN_CTRL1_PSEG2(config->phaseSeg2) | CAN_CTRL1_PROPSEG(config->propSeg)); - - /* Exit Freeze Mode. */ - FLEXCAN_ExitFreezeMode(base); -} - -void FLEXCAN_SetRxMbGlobalMask(CAN_Type *base, uint32_t mask) -{ - /* Enter Freeze Mode. */ - FLEXCAN_EnterFreezeMode(base); - - /* Setting Rx Message Buffer Global Mask value. */ - base->RXMGMASK = mask; - base->RX14MASK = mask; - base->RX15MASK = mask; - - /* Exit Freeze Mode. */ - FLEXCAN_ExitFreezeMode(base); -} - -void FLEXCAN_SetRxFifoGlobalMask(CAN_Type *base, uint32_t mask) -{ - /* Enter Freeze Mode. */ - FLEXCAN_EnterFreezeMode(base); - - /* Setting Rx FIFO Global Mask value. */ - base->RXFGMASK = mask; - - /* Exit Freeze Mode. */ - FLEXCAN_ExitFreezeMode(base); -} - -void FLEXCAN_SetRxIndividualMask(CAN_Type *base, uint8_t maskIdx, uint32_t mask) -{ - assert(maskIdx <= (base->MCR & CAN_MCR_MAXMB_MASK)); - - /* Enter Freeze Mode. */ - FLEXCAN_EnterFreezeMode(base); - - /* Setting Rx Individual Mask value. */ - base->RXIMR[maskIdx] = mask; - - /* Exit Freeze Mode. */ - FLEXCAN_ExitFreezeMode(base); -} - -void FLEXCAN_SetTxMbConfig(CAN_Type *base, uint8_t mbIdx, bool enable) -{ - /* Assertion. */ - assert(mbIdx <= (base->MCR & CAN_MCR_MAXMB_MASK)); - assert(!FLEXCAN_IsMbOccupied(base, mbIdx)); - - /* Inactivate Message Buffer. */ - if (enable) - { - base->MB[mbIdx].CS = CAN_CS_CODE(kFLEXCAN_TxMbInactive); - } - else - { - base->MB[mbIdx].CS = 0; - } - - /* Clean Message Buffer content. */ - base->MB[mbIdx].ID = 0x0; - base->MB[mbIdx].WORD0 = 0x0; - base->MB[mbIdx].WORD1 = 0x0; -} - -void FLEXCAN_SetRxMbConfig(CAN_Type *base, uint8_t mbIdx, const flexcan_rx_mb_config_t *config, bool enable) -{ - /* Assertion. */ - assert(mbIdx <= (base->MCR & CAN_MCR_MAXMB_MASK)); - assert(((config) || (false == enable))); - assert(!FLEXCAN_IsMbOccupied(base, mbIdx)); - - uint32_t cs_temp = 0; - - /* Inactivate Message Buffer. */ - base->MB[mbIdx].CS = 0; - - /* Clean Message Buffer content. */ - base->MB[mbIdx].ID = 0x0; - base->MB[mbIdx].WORD0 = 0x0; - base->MB[mbIdx].WORD1 = 0x0; - - if (enable) - { - /* Setup Message Buffer ID. */ - base->MB[mbIdx].ID = config->id; - - /* Setup Message Buffer format. */ - if (kFLEXCAN_FrameFormatExtend == config->format) - { - cs_temp |= CAN_CS_IDE_MASK; - } - - /* Setup Message Buffer type. */ - if (kFLEXCAN_FrameTypeRemote == config->type) - { - cs_temp |= CAN_CS_RTR_MASK; - } - - /* Activate Rx Message Buffer. */ - cs_temp |= CAN_CS_CODE(kFLEXCAN_RxMbEmpty); - base->MB[mbIdx].CS = cs_temp; - } -} - -void FLEXCAN_SetRxFifoConfig(CAN_Type *base, const flexcan_rx_fifo_config_t *config, bool enable) -{ - /* Assertion. */ - assert((config) || (false == enable)); - - volatile uint32_t *idFilterRegion = (volatile uint32_t *)(&base->MB[6].CS); - uint8_t setup_mb, i, rffn = 0; - - /* Enter Freeze Mode. */ - FLEXCAN_EnterFreezeMode(base); - - if (enable) - { - assert(config->idFilterNum <= 128); - - /* Get the setup_mb value. */ - setup_mb = (base->MCR & CAN_MCR_MAXMB_MASK) >> CAN_MCR_MAXMB_SHIFT; - setup_mb = (setup_mb < FSL_FEATURE_FLEXCAN_HAS_MESSAGE_BUFFER_MAX_NUMBERn(base)) ? - setup_mb : - FSL_FEATURE_FLEXCAN_HAS_MESSAGE_BUFFER_MAX_NUMBERn(base); - - /* Determine RFFN value. */ - for (i = 0; i <= 0xF; i++) - { - if ((8 * (i + 1)) >= config->idFilterNum) - { - rffn = i; - assert(((setup_mb - 8) - (2 * rffn)) > 0); - - base->CTRL2 = (base->CTRL2 & ~CAN_CTRL2_RFFN_MASK) | CAN_CTRL2_RFFN(rffn); - break; - } - } - } - else - { - rffn = (base->CTRL2 & CAN_CTRL2_RFFN_MASK) >> CAN_CTRL2_RFFN_SHIFT; - } - - /* Clean ID filter table occuyied Message Buffer Region. */ - rffn = (rffn + 1) * 8; - for (i = 0; i < rffn; i++) - { - idFilterRegion[i] = 0x0; - } - - if (enable) - { - /* Disable unused Rx FIFO Filter. */ - for (i = config->idFilterNum; i < rffn; i++) - { - idFilterRegion[i] = 0xFFFFFFFFU; - } - - /* Copy ID filter table to Message Buffer Region. */ - for (i = 0; i < config->idFilterNum; i++) - { - idFilterRegion[i] = config->idFilterTable[i]; - } - - /* Setup ID Fitlter Type. */ - switch (config->idFilterType) - { - case kFLEXCAN_RxFifoFilterTypeA: - base->MCR = (base->MCR & ~CAN_MCR_IDAM_MASK) | CAN_MCR_IDAM(0x0); - break; - case kFLEXCAN_RxFifoFilterTypeB: - base->MCR = (base->MCR & ~CAN_MCR_IDAM_MASK) | CAN_MCR_IDAM(0x1); - break; - case kFLEXCAN_RxFifoFilterTypeC: - base->MCR = (base->MCR & ~CAN_MCR_IDAM_MASK) | CAN_MCR_IDAM(0x2); - break; - case kFLEXCAN_RxFifoFilterTypeD: - /* All frames rejected. */ - base->MCR = (base->MCR & ~CAN_MCR_IDAM_MASK) | CAN_MCR_IDAM(0x3); - break; - default: - break; - } - - /* Setting Message Reception Priority. */ - base->CTRL2 = (config->priority == kFLEXCAN_RxFifoPrioHigh) ? base->CTRL2 & ~CAN_CTRL2_MRP_MASK : - base->CTRL2 | CAN_CTRL2_MRP_MASK; - - /* Enable Rx Message FIFO. */ - base->MCR |= CAN_MCR_RFEN_MASK; - } - else - { - /* Disable Rx Message FIFO. */ - base->MCR &= ~CAN_MCR_RFEN_MASK; - - /* Clean MB0 ~ MB5. */ - FLEXCAN_SetRxMbConfig(base, 0, NULL, false); - FLEXCAN_SetRxMbConfig(base, 1, NULL, false); - FLEXCAN_SetRxMbConfig(base, 2, NULL, false); - FLEXCAN_SetRxMbConfig(base, 3, NULL, false); - FLEXCAN_SetRxMbConfig(base, 4, NULL, false); - FLEXCAN_SetRxMbConfig(base, 5, NULL, false); - } - - /* Exit Freeze Mode. */ - FLEXCAN_ExitFreezeMode(base); -} - -#if (defined(FSL_FEATURE_FLEXCAN_HAS_RX_FIFO_DMA) && FSL_FEATURE_FLEXCAN_HAS_RX_FIFO_DMA) -void FLEXCAN_EnableRxFifoDMA(CAN_Type *base, bool enable) -{ - if (enable) - { - /* Enter Freeze Mode. */ - FLEXCAN_EnterFreezeMode(base); - - /* Enable FlexCAN DMA. */ - base->MCR |= CAN_MCR_DMA_MASK; - - /* Exit Freeze Mode. */ - FLEXCAN_ExitFreezeMode(base); - } - else - { - /* Enter Freeze Mode. */ - FLEXCAN_EnterFreezeMode(base); - - /* Disable FlexCAN DMA. */ - base->MCR &= ~CAN_MCR_DMA_MASK; - - /* Exit Freeze Mode. */ - FLEXCAN_ExitFreezeMode(base); - } -} -#endif /* FSL_FEATURE_FLEXCAN_HAS_RX_FIFO_DMA */ - -status_t FLEXCAN_WriteTxMb(CAN_Type *base, uint8_t mbIdx, const flexcan_frame_t *txFrame) -{ - /* Assertion. */ - assert(mbIdx <= (base->MCR & CAN_MCR_MAXMB_MASK)); - assert(txFrame); - assert(txFrame->length <= 8); - assert(!FLEXCAN_IsMbOccupied(base, mbIdx)); - - uint32_t cs_temp = 0; - - /* Check if Message Buffer is available. */ - if (CAN_CS_CODE(kFLEXCAN_TxMbDataOrRemote) != (base->MB[mbIdx].CS & CAN_CS_CODE_MASK)) - { - /* Inactive Tx Message Buffer. */ - base->MB[mbIdx].CS = (base->MB[mbIdx].CS & ~CAN_CS_CODE_MASK) | CAN_CS_CODE(kFLEXCAN_TxMbInactive); - - /* Fill Message ID field. */ - base->MB[mbIdx].ID = txFrame->id; - - /* Fill Message Format field. */ - if (kFLEXCAN_FrameFormatExtend == txFrame->format) - { - cs_temp |= CAN_CS_SRR_MASK | CAN_CS_IDE_MASK; - } - - /* Fill Message Type field. */ - if (kFLEXCAN_FrameTypeRemote == txFrame->type) - { - cs_temp |= CAN_CS_RTR_MASK; - } - - cs_temp |= CAN_CS_CODE(kFLEXCAN_TxMbDataOrRemote) | CAN_CS_DLC(txFrame->length); - - /* Load Message Payload. */ - base->MB[mbIdx].WORD0 = txFrame->dataWord0; - base->MB[mbIdx].WORD1 = txFrame->dataWord1; - - /* Activate Tx Message Buffer. */ - base->MB[mbIdx].CS = cs_temp; - -#if (defined(FSL_FEATURE_FLEXCAN_HAS_ERRATA_5641) && FSL_FEATURE_FLEXCAN_HAS_ERRATA_5641) - base->MB[FLEXCAN_GetFirstValidMb(base)].CS = CAN_CS_CODE(kFLEXCAN_TxMbInactive); - base->MB[FLEXCAN_GetFirstValidMb(base)].CS = CAN_CS_CODE(kFLEXCAN_TxMbInactive); -#endif - - return kStatus_Success; - } - else - { - /* Tx Message Buffer is activated, return immediately. */ - return kStatus_Fail; - } -} - -status_t FLEXCAN_ReadRxMb(CAN_Type *base, uint8_t mbIdx, flexcan_frame_t *rxFrame) -{ - /* Assertion. */ - assert(mbIdx <= (base->MCR & CAN_MCR_MAXMB_MASK)); - assert(rxFrame); - assert(!FLEXCAN_IsMbOccupied(base, mbIdx)); - - uint32_t cs_temp; - uint8_t rx_code; - - /* Read CS field of Rx Message Buffer to lock Message Buffer. */ - cs_temp = base->MB[mbIdx].CS; - /* Get Rx Message Buffer Code field. */ - rx_code = (cs_temp & CAN_CS_CODE_MASK) >> CAN_CS_CODE_SHIFT; - - /* Check to see if Rx Message Buffer is full. */ - if ((kFLEXCAN_RxMbFull == rx_code) || (kFLEXCAN_RxMbOverrun == rx_code)) - { - /* Store Message ID. */ - rxFrame->id = base->MB[mbIdx].ID & (CAN_ID_EXT_MASK | CAN_ID_STD_MASK); - - /* Get the message ID and format. */ - rxFrame->format = (cs_temp & CAN_CS_IDE_MASK) ? kFLEXCAN_FrameFormatExtend : kFLEXCAN_FrameFormatStandard; - - /* Get the message type. */ - rxFrame->type = (cs_temp & CAN_CS_RTR_MASK) ? kFLEXCAN_FrameTypeRemote : kFLEXCAN_FrameTypeData; - - /* Get the message length. */ - rxFrame->length = (cs_temp & CAN_CS_DLC_MASK) >> CAN_CS_DLC_SHIFT; - - /* Store Message Payload. */ - rxFrame->dataWord0 = base->MB[mbIdx].WORD0; - rxFrame->dataWord1 = base->MB[mbIdx].WORD1; - - /* Read free-running timer to unlock Rx Message Buffer. */ - (void)base->TIMER; - - if (kFLEXCAN_RxMbFull == rx_code) - { - return kStatus_Success; - } - else - { - return kStatus_FLEXCAN_RxOverflow; - } - } - else - { - /* Read free-running timer to unlock Rx Message Buffer. */ - (void)base->TIMER; - - return kStatus_Fail; - } -} - -status_t FLEXCAN_ReadRxFifo(CAN_Type *base, flexcan_frame_t *rxFrame) -{ - /* Assertion. */ - assert(rxFrame); - - uint32_t cs_temp; - - /* Check if Rx FIFO is Enabled. */ - if (base->MCR & CAN_MCR_RFEN_MASK) - { - /* Read CS field of Rx Message Buffer to lock Message Buffer. */ - cs_temp = base->MB[0].CS; - - /* Read data from Rx FIFO output port. */ - /* Store Message ID. */ - rxFrame->id = base->MB[0].ID & (CAN_ID_EXT_MASK | CAN_ID_STD_MASK); - - /* Get the message ID and format. */ - rxFrame->format = (cs_temp & CAN_CS_IDE_MASK) ? kFLEXCAN_FrameFormatExtend : kFLEXCAN_FrameFormatStandard; - - /* Get the message type. */ - rxFrame->type = (cs_temp & CAN_CS_RTR_MASK) ? kFLEXCAN_FrameTypeRemote : kFLEXCAN_FrameTypeData; - - /* Get the message length. */ - rxFrame->length = (cs_temp & CAN_CS_DLC_MASK) >> CAN_CS_DLC_SHIFT; - - /* Store Message Payload. */ - rxFrame->dataWord0 = base->MB[0].WORD0; - rxFrame->dataWord1 = base->MB[0].WORD1; - - /* Store ID Filter Hit Index. */ - rxFrame->idhit = (uint8_t)(base->RXFIR & CAN_RXFIR_IDHIT_MASK); - - /* Read free-running timer to unlock Rx Message Buffer. */ - (void)base->TIMER; - - return kStatus_Success; - } - else - { - return kStatus_Fail; - } -} - -status_t FLEXCAN_TransferSendBlocking(CAN_Type *base, uint8_t mbIdx, flexcan_frame_t *txFrame) -{ - /* Write Tx Message Buffer to initiate a data sending. */ - if (kStatus_Success == FLEXCAN_WriteTxMb(base, mbIdx, txFrame)) - { - /* Wait until CAN Message send out. */ - while (!FLEXCAN_GetMbStatusFlags(base, 1 << mbIdx)) - { - } - - /* Clean Tx Message Buffer Flag. */ - FLEXCAN_ClearMbStatusFlags(base, 1 << mbIdx); - - return kStatus_Success; - } - else - { - return kStatus_Fail; - } -} - -status_t FLEXCAN_TransferReceiveBlocking(CAN_Type *base, uint8_t mbIdx, flexcan_frame_t *rxFrame) -{ - /* Wait until Rx Message Buffer non-empty. */ - while (!FLEXCAN_GetMbStatusFlags(base, 1 << mbIdx)) - { - } - - /* Clean Rx Message Buffer Flag. */ - FLEXCAN_ClearMbStatusFlags(base, 1 << mbIdx); - - /* Read Received CAN Message. */ - return FLEXCAN_ReadRxMb(base, mbIdx, rxFrame); -} - -status_t FLEXCAN_TransferReceiveFifoBlocking(CAN_Type *base, flexcan_frame_t *rxFrame) -{ - status_t rxFifoStatus; - - /* Wait until Rx FIFO non-empty. */ - while (!FLEXCAN_GetMbStatusFlags(base, kFLEXCAN_RxFifoFrameAvlFlag)) - { - } - - /* */ - rxFifoStatus = FLEXCAN_ReadRxFifo(base, rxFrame); - - /* Clean Rx Fifo available flag. */ - FLEXCAN_ClearMbStatusFlags(base, kFLEXCAN_RxFifoFrameAvlFlag); - - return rxFifoStatus; -} - -void FLEXCAN_TransferCreateHandle(CAN_Type *base, - flexcan_handle_t *handle, - flexcan_transfer_callback_t callback, - void *userData) -{ - assert(handle); - - uint8_t instance; - - /* Clean FlexCAN transfer handle. */ - memset(handle, 0, sizeof(*handle)); - - /* Get instance from peripheral base address. */ - instance = FLEXCAN_GetInstance(base); - - /* Save the context in global variables to support the double weak mechanism. */ - s_flexcanHandle[instance] = handle; - - /* Register Callback function. */ - handle->callback = callback; - handle->userData = userData; - - s_flexcanIsr = FLEXCAN_TransferHandleIRQ; - - /* We Enable Error & Status interrupt here, because this interrupt just - * report current status of FlexCAN module through Callback function. - * It is insignificance without a available callback function. - */ - if (handle->callback != NULL) - { - FLEXCAN_EnableInterrupts(base, kFLEXCAN_BusOffInterruptEnable | kFLEXCAN_ErrorInterruptEnable | - kFLEXCAN_RxWarningInterruptEnable | kFLEXCAN_TxWarningInterruptEnable | - kFLEXCAN_WakeUpInterruptEnable); - } - else - { - FLEXCAN_DisableInterrupts(base, kFLEXCAN_BusOffInterruptEnable | kFLEXCAN_ErrorInterruptEnable | - kFLEXCAN_RxWarningInterruptEnable | kFLEXCAN_TxWarningInterruptEnable | - kFLEXCAN_WakeUpInterruptEnable); - } - - /* Enable interrupts in NVIC. */ - EnableIRQ((IRQn_Type)(s_flexcanRxWarningIRQ[instance])); - EnableIRQ((IRQn_Type)(s_flexcanTxWarningIRQ[instance])); - EnableIRQ((IRQn_Type)(s_flexcanWakeUpIRQ[instance])); - EnableIRQ((IRQn_Type)(s_flexcanErrorIRQ[instance])); - EnableIRQ((IRQn_Type)(s_flexcanBusOffIRQ[instance])); - EnableIRQ((IRQn_Type)(s_flexcanMbIRQ[instance])); -} - -status_t FLEXCAN_TransferSendNonBlocking(CAN_Type *base, flexcan_handle_t *handle, flexcan_mb_transfer_t *xfer) -{ - /* Assertion. */ - assert(handle); - assert(xfer); - assert(xfer->mbIdx <= (base->MCR & CAN_MCR_MAXMB_MASK)); - assert(!FLEXCAN_IsMbOccupied(base, xfer->mbIdx)); - - /* Check if Message Buffer is idle. */ - if (kFLEXCAN_StateIdle == handle->mbState[xfer->mbIdx]) - { - /* Distinguish transmit type. */ - if (kFLEXCAN_FrameTypeRemote == xfer->frame->type) - { - handle->mbState[xfer->mbIdx] = kFLEXCAN_StateTxRemote; - - /* Register user Frame buffer to receive remote Frame. */ - handle->mbFrameBuf[xfer->mbIdx] = xfer->frame; - } - else - { - handle->mbState[xfer->mbIdx] = kFLEXCAN_StateTxData; - } - - if (kStatus_Success == FLEXCAN_WriteTxMb(base, xfer->mbIdx, xfer->frame)) - { - /* Enable Message Buffer Interrupt. */ - FLEXCAN_EnableMbInterrupts(base, 1 << xfer->mbIdx); - - return kStatus_Success; - } - else - { - handle->mbState[xfer->mbIdx] = kFLEXCAN_StateIdle; - return kStatus_Fail; - } - } - else - { - return kStatus_FLEXCAN_TxBusy; - } -} - -status_t FLEXCAN_TransferReceiveNonBlocking(CAN_Type *base, flexcan_handle_t *handle, flexcan_mb_transfer_t *xfer) -{ - /* Assertion. */ - assert(handle); - assert(xfer); - assert(xfer->mbIdx <= (base->MCR & CAN_MCR_MAXMB_MASK)); - assert(!FLEXCAN_IsMbOccupied(base, xfer->mbIdx)); - - /* Check if Message Buffer is idle. */ - if (kFLEXCAN_StateIdle == handle->mbState[xfer->mbIdx]) - { - handle->mbState[xfer->mbIdx] = kFLEXCAN_StateRxData; - - /* Register Message Buffer. */ - handle->mbFrameBuf[xfer->mbIdx] = xfer->frame; - - /* Enable Message Buffer Interrupt. */ - FLEXCAN_EnableMbInterrupts(base, 1 << xfer->mbIdx); - - return kStatus_Success; - } - else - { - return kStatus_FLEXCAN_RxBusy; - } -} - -status_t FLEXCAN_TransferReceiveFifoNonBlocking(CAN_Type *base, flexcan_handle_t *handle, flexcan_fifo_transfer_t *xfer) -{ - /* Assertion. */ - assert(handle); - assert(xfer); - - /* Check if Message Buffer is idle. */ - if (kFLEXCAN_StateIdle == handle->rxFifoState) - { - handle->rxFifoState = kFLEXCAN_StateRxFifo; - - /* Register Message Buffer. */ - handle->rxFifoFrameBuf = xfer->frame; - - /* Enable Message Buffer Interrupt. */ - FLEXCAN_EnableMbInterrupts( - base, kFLEXCAN_RxFifoOverflowFlag | kFLEXCAN_RxFifoWarningFlag | kFLEXCAN_RxFifoFrameAvlFlag); - - return kStatus_Success; - } - else - { - return kStatus_FLEXCAN_RxFifoBusy; - } -} - -void FLEXCAN_TransferAbortSend(CAN_Type *base, flexcan_handle_t *handle, uint8_t mbIdx) -{ - /* Assertion. */ - assert(handle); - assert(mbIdx <= (base->MCR & CAN_MCR_MAXMB_MASK)); - assert(!FLEXCAN_IsMbOccupied(base, mbIdx)); - - /* Disable Message Buffer Interrupt. */ - FLEXCAN_DisableMbInterrupts(base, 1 << mbIdx); - - /* Un-register handle. */ - handle->mbFrameBuf[mbIdx] = 0x0; - - /* Clean Message Buffer. */ - FLEXCAN_SetTxMbConfig(base, mbIdx, true); - - handle->mbState[mbIdx] = kFLEXCAN_StateIdle; -} - -void FLEXCAN_TransferAbortReceive(CAN_Type *base, flexcan_handle_t *handle, uint8_t mbIdx) -{ - /* Assertion. */ - assert(handle); - assert(mbIdx <= (base->MCR & CAN_MCR_MAXMB_MASK)); - assert(!FLEXCAN_IsMbOccupied(base, mbIdx)); - - /* Disable Message Buffer Interrupt. */ - FLEXCAN_DisableMbInterrupts(base, 1 << mbIdx); - - /* Un-register handle. */ - handle->mbFrameBuf[mbIdx] = 0x0; - handle->mbState[mbIdx] = kFLEXCAN_StateIdle; -} - -void FLEXCAN_TransferAbortReceiveFifo(CAN_Type *base, flexcan_handle_t *handle) -{ - /* Assertion. */ - assert(handle); - - /* Check if Rx FIFO is enabled. */ - if (base->MCR & CAN_MCR_RFEN_MASK) - { - /* Disable Rx Message FIFO Interrupts. */ - FLEXCAN_DisableMbInterrupts( - base, kFLEXCAN_RxFifoOverflowFlag | kFLEXCAN_RxFifoWarningFlag | kFLEXCAN_RxFifoFrameAvlFlag); - - /* Un-register handle. */ - handle->rxFifoFrameBuf = 0x0; - } - - handle->rxFifoState = kFLEXCAN_StateIdle; -} - -void FLEXCAN_TransferHandleIRQ(CAN_Type *base, flexcan_handle_t *handle) -{ - /* Assertion. */ - assert(handle); - - status_t status = kStatus_FLEXCAN_UnHandled; - uint32_t result; - - /* Store Current FlexCAN Module Error and Status. */ - result = base->ESR1; - - do - { - /* Solve FlexCAN Error and Status Interrupt. */ - if (result & (kFLEXCAN_TxWarningIntFlag | kFLEXCAN_RxWarningIntFlag | kFLEXCAN_BusOffIntFlag | - kFLEXCAN_ErrorIntFlag | kFLEXCAN_WakeUpIntFlag)) - { - status = kStatus_FLEXCAN_ErrorStatus; - - /* Clear FlexCAN Error and Status Interrupt. */ - FLEXCAN_ClearStatusFlags(base, kFLEXCAN_TxWarningIntFlag | kFLEXCAN_RxWarningIntFlag | - kFLEXCAN_BusOffIntFlag | kFLEXCAN_ErrorIntFlag | kFLEXCAN_WakeUpIntFlag); - } - /* Solve FlexCAN Rx FIFO & Message Buffer Interrupt. */ - else - { - /* For this implementation, we solve the Message with lowest MB index first. */ - for (result = 0; result < FSL_FEATURE_FLEXCAN_HAS_MESSAGE_BUFFER_MAX_NUMBERn(base); result++) - { - /* Get the lowest unhandled Message Buffer */ - if ((FLEXCAN_GetMbStatusFlags(base, 1 << result)) && (FLEXCAN_IsMbIntEnabled(base, result))) - { - break; - } - } - - /* Does not find Message to deal with. */ - if (result == FSL_FEATURE_FLEXCAN_HAS_MESSAGE_BUFFER_MAX_NUMBERn(base)) - { - break; - } - - /* Solve Rx FIFO interrupt. */ - if ((kFLEXCAN_StateIdle != handle->rxFifoState) && ((1 << result) <= kFLEXCAN_RxFifoOverflowFlag)) - { - switch (1 << result) - { - case kFLEXCAN_RxFifoOverflowFlag: - status = kStatus_FLEXCAN_RxFifoOverflow; - break; - - case kFLEXCAN_RxFifoWarningFlag: - status = kStatus_FLEXCAN_RxFifoWarning; - break; - - case kFLEXCAN_RxFifoFrameAvlFlag: - status = FLEXCAN_ReadRxFifo(base, handle->rxFifoFrameBuf); - if (kStatus_Success == status) - { - status = kStatus_FLEXCAN_RxFifoIdle; - } - FLEXCAN_TransferAbortReceiveFifo(base, handle); - break; - - default: - status = kStatus_FLEXCAN_UnHandled; - break; - } - } - else - { - /* Get current State of Message Buffer. */ - switch (handle->mbState[result]) - { - /* Solve Rx Data Frame. */ - case kFLEXCAN_StateRxData: - status = FLEXCAN_ReadRxMb(base, result, handle->mbFrameBuf[result]); - if (kStatus_Success == status) - { - status = kStatus_FLEXCAN_RxIdle; - } - FLEXCAN_TransferAbortReceive(base, handle, result); - break; - - /* Solve Rx Remote Frame. */ - case kFLEXCAN_StateRxRemote: - status = FLEXCAN_ReadRxMb(base, result, handle->mbFrameBuf[result]); - if (kStatus_Success == status) - { - status = kStatus_FLEXCAN_RxIdle; - } - FLEXCAN_TransferAbortReceive(base, handle, result); - break; - - /* Solve Tx Data Frame. */ - case kFLEXCAN_StateTxData: - status = kStatus_FLEXCAN_TxIdle; - FLEXCAN_TransferAbortSend(base, handle, result); - break; - - /* Solve Tx Remote Frame. */ - case kFLEXCAN_StateTxRemote: - handle->mbState[result] = kFLEXCAN_StateRxRemote; - status = kStatus_FLEXCAN_TxSwitchToRx; - break; - - default: - status = kStatus_FLEXCAN_UnHandled; - break; - } - } - - /* Clear resolved Message Buffer IRQ. */ - FLEXCAN_ClearMbStatusFlags(base, 1 << result); - } - - /* Calling Callback Function if has one. */ - if (handle->callback != NULL) - { - handle->callback(base, handle, status, result, handle->userData); - } - - /* Reset return status */ - status = kStatus_FLEXCAN_UnHandled; - - /* Store Current FlexCAN Module Error and Status. */ - result = base->ESR1; - } -#if (defined(FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER)) && (FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER > 0) - while ((0 != FLEXCAN_GetMbStatusFlags(base, 0xFFFFFFFFFFFFFFFFU)) || - (0 != (result & (kFLEXCAN_TxWarningIntFlag | kFLEXCAN_RxWarningIntFlag | kFLEXCAN_BusOffIntFlag | - kFLEXCAN_ErrorIntFlag | kFLEXCAN_WakeUpIntFlag)))); -#else - while ((0 != FLEXCAN_GetMbStatusFlags(base, 0xFFFFFFFFU)) || - (0 != (result & (kFLEXCAN_TxWarningIntFlag | kFLEXCAN_RxWarningIntFlag | kFLEXCAN_BusOffIntFlag | - kFLEXCAN_ErrorIntFlag | kFLEXCAN_WakeUpIntFlag)))); -#endif -} - -#if defined(CAN0) -void CAN0_DriverIRQHandler(void) -{ - assert(s_flexcanHandle[0]); - - s_flexcanIsr(CAN0, s_flexcanHandle[0]); -} -#endif - -#if defined(CAN1) -void CAN1_DriverIRQHandler(void) -{ - assert(s_flexcanHandle[1]); - - s_flexcanIsr(CAN1, s_flexcanHandle[1]); -} -#endif - -#if defined(CAN2) -void CAN2_DriverIRQHandler(void) -{ - assert(s_flexcanHandle[2]); - - s_flexcanIsr(CAN2, s_flexcanHandle[2]); -} -#endif - -#if defined(CAN3) -void CAN3_DriverIRQHandler(void) -{ - assert(s_flexcanHandle[3]); - - s_flexcanIsr(CAN3, s_flexcanHandle[3]); -} -#endif - -#if defined(CAN4) -void CAN4_DriverIRQHandler(void) -{ - assert(s_flexcanHandle[4]); - - s_flexcanIsr(CAN4, s_flexcanHandle[4]); -} -#endif - -#if defined(DMA_CAN0) -void DMA_FLEXCAN0_DriverIRQHandler(void) -{ - assert(s_flexcanHandle[FLEXCAN_GetInstance(DMA_CAN0)]); - - s_flexcanIsr(DMA_CAN0, s_flexcanHandle[FLEXCAN_GetInstance(DMA_CAN0)]); -} -#endif - -#if defined(DMA_CAN1) -void DMA_FLEXCAN1_DriverIRQHandler(void) -{ - assert(s_flexcanHandle[FLEXCAN_GetInstance(DMA_CAN1)]); - - s_flexcanIsr(DMA_CAN0, s_flexcanHandle[FLEXCAN_GetInstance(DMA_CAN1)]); -} -#endif - -#if defined(DMA_CAN2) -void DMA_FLEXCAN2_DriverIRQHandler(void) -{ - assert(s_flexcanHandle[FLEXCAN_GetInstance(DMA_CAN2)]); - - s_flexcanIsr(DMA_CAN2, s_flexcanHandle[FLEXCAN_GetInstance(DMA_CAN2)]); -} -#endif diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_flexcan.h b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_flexcan.h deleted file mode 100644 index 118badf58fb..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_flexcan.h +++ /dev/null @@ -1,1052 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -#ifndef _FSL_FLEXCAN_H_ -#define _FSL_FLEXCAN_H_ - -#include "fsl_common.h" - -/*! - * @addtogroup flexcan_driver - * @{ - */ - -/****************************************************************************** - * Definitions - *****************************************************************************/ - -/*! @name Driver version */ -/*@{*/ -/*! @brief FlexCAN driver version 2.2.0. */ -#define FLEXCAN_DRIVER_VERSION (MAKE_VERSION(2, 2, 0)) -/*@}*/ - -/*! @brief FlexCAN Frame ID helper macro. */ -#define FLEXCAN_ID_STD(id) \ - (((uint32_t)(((uint32_t)(id)) << CAN_ID_STD_SHIFT)) & CAN_ID_STD_MASK) /*!< Standard Frame ID helper macro. */ -#define FLEXCAN_ID_EXT(id) \ - (((uint32_t)(((uint32_t)(id)) << CAN_ID_EXT_SHIFT)) & \ - (CAN_ID_EXT_MASK | CAN_ID_STD_MASK)) /*!< Extend Frame ID helper macro. */ - -/*! @brief FlexCAN Rx Message Buffer Mask helper macro. */ -#define FLEXCAN_RX_MB_STD_MASK(id, rtr, ide) \ - (((uint32_t)((uint32_t)(rtr) << 31) | (uint32_t)((uint32_t)(ide) << 30)) | \ - FLEXCAN_ID_STD(id)) /*!< Standard Rx Message Buffer Mask helper macro. */ -#define FLEXCAN_RX_MB_EXT_MASK(id, rtr, ide) \ - (((uint32_t)((uint32_t)(rtr) << 31) | (uint32_t)((uint32_t)(ide) << 30)) | \ - FLEXCAN_ID_EXT(id)) /*!< Extend Rx Message Buffer Mask helper macro. */ - -/*! @brief FlexCAN Rx FIFO Mask helper macro. */ -#define FLEXCAN_RX_FIFO_STD_MASK_TYPE_A(id, rtr, ide) \ - (((uint32_t)((uint32_t)(rtr) << 31) | (uint32_t)((uint32_t)(ide) << 30)) | \ - (FLEXCAN_ID_STD(id) << 1)) /*!< Standard Rx FIFO Mask helper macro Type A helper macro. */ -#define FLEXCAN_RX_FIFO_STD_MASK_TYPE_B_HIGH(id, rtr, ide) \ - (((uint32_t)((uint32_t)(rtr) << 31) | (uint32_t)((uint32_t)(ide) << 30)) | \ - (((uint32_t)(id) & 0x7FF) << 19)) /*!< Standard Rx FIFO Mask helper macro Type B upper part helper macro. */ -#define FLEXCAN_RX_FIFO_STD_MASK_TYPE_B_LOW(id, rtr, ide) \ - (((uint32_t)((uint32_t)(rtr) << 15) | (uint32_t)((uint32_t)(ide) << 14)) | \ - (((uint32_t)(id) & 0x7FF) << 3)) /*!< Standard Rx FIFO Mask helper macro Type B lower part helper macro. */ -#define FLEXCAN_RX_FIFO_STD_MASK_TYPE_C_HIGH(id) \ - (((uint32_t)(id) & 0x7F8) << 21) /*!< Standard Rx FIFO Mask helper macro Type C upper part helper macro. */ -#define FLEXCAN_RX_FIFO_STD_MASK_TYPE_C_MID_HIGH(id) \ - (((uint32_t)(id) & 0x7F8) << 13) /*!< Standard Rx FIFO Mask helper macro Type C mid-upper part helper macro. */ -#define FLEXCAN_RX_FIFO_STD_MASK_TYPE_C_MID_LOW(id) \ - (((uint32_t)(id) & 0x7F8) << 5) /*!< Standard Rx FIFO Mask helper macro Type C mid-lower part helper macro. */ -#define FLEXCAN_RX_FIFO_STD_MASK_TYPE_C_LOW(id) \ - (((uint32_t)(id) & 0x7F8) >> 3) /*!< Standard Rx FIFO Mask helper macro Type C lower part helper macro. */ -#define FLEXCAN_RX_FIFO_EXT_MASK_TYPE_A(id, rtr, ide) \ - (((uint32_t)((uint32_t)(rtr) << 31) | (uint32_t)((uint32_t)(ide) << 30)) | \ - (FLEXCAN_ID_EXT(id) << 1)) /*!< Extend Rx FIFO Mask helper macro Type A helper macro. */ -#define FLEXCAN_RX_FIFO_EXT_MASK_TYPE_B_HIGH(id, rtr, ide) \ - (((uint32_t)((uint32_t)(rtr) << 31) | (uint32_t)((uint32_t)(ide) << 30)) | \ - ((FLEXCAN_ID_EXT(id) & 0x1FFF8000) << 1)) /*!< Extend Rx FIFO Mask helper macro Type B upper part helper macro. */ -#define FLEXCAN_RX_FIFO_EXT_MASK_TYPE_B_LOW(id, rtr, ide) \ - (((uint32_t)((uint32_t)(rtr) << 15) | (uint32_t)((uint32_t)(ide) << 14)) | \ - ((FLEXCAN_ID_EXT(id) & 0x1FFF8000) >> \ - 15)) /*!< Extend Rx FIFO Mask helper macro Type B lower part helper macro. */ -#define FLEXCAN_RX_FIFO_EXT_MASK_TYPE_C_HIGH(id) \ - ((FLEXCAN_ID_EXT(id) & 0x1FE00000) << 3) /*!< Extend Rx FIFO Mask helper macro Type C upper part helper macro. */ -#define FLEXCAN_RX_FIFO_EXT_MASK_TYPE_C_MID_HIGH(id) \ - ((FLEXCAN_ID_EXT(id) & 0x1FE00000) >> \ - 5) /*!< Extend Rx FIFO Mask helper macro Type C mid-upper part helper macro. */ -#define FLEXCAN_RX_FIFO_EXT_MASK_TYPE_C_MID_LOW(id) \ - ((FLEXCAN_ID_EXT(id) & 0x1FE00000) >> \ - 13) /*!< Extend Rx FIFO Mask helper macro Type C mid-lower part helper macro. */ -#define FLEXCAN_RX_FIFO_EXT_MASK_TYPE_C_LOW(id) \ - ((FLEXCAN_ID_EXT(id) & 0x1FE00000) >> 21) /*!< Extend Rx FIFO Mask helper macro Type C lower part helper macro. */ - -/*! @brief FlexCAN Rx FIFO Filter helper macro. */ -#define FLEXCAN_RX_FIFO_STD_FILTER_TYPE_A(id, rtr, ide) \ - FLEXCAN_RX_FIFO_STD_MASK_TYPE_A(id, rtr, ide) /*!< Standard Rx FIFO Filter helper macro Type A helper macro. */ -#define FLEXCAN_RX_FIFO_STD_FILTER_TYPE_B_HIGH(id, rtr, ide) \ - FLEXCAN_RX_FIFO_STD_MASK_TYPE_B_HIGH( \ - id, rtr, ide) /*!< Standard Rx FIFO Filter helper macro Type B upper part helper macro. */ -#define FLEXCAN_RX_FIFO_STD_FILTER_TYPE_B_LOW(id, rtr, ide) \ - FLEXCAN_RX_FIFO_STD_MASK_TYPE_B_LOW( \ - id, rtr, ide) /*!< Standard Rx FIFO Filter helper macro Type B lower part helper macro. */ -#define FLEXCAN_RX_FIFO_STD_FILTER_TYPE_C_HIGH(id) \ - FLEXCAN_RX_FIFO_STD_MASK_TYPE_C_HIGH( \ - id) /*!< Standard Rx FIFO Filter helper macro Type C upper part helper macro. */ -#define FLEXCAN_RX_FIFO_STD_FILTER_TYPE_C_MID_HIGH(id) \ - FLEXCAN_RX_FIFO_STD_MASK_TYPE_C_MID_HIGH( \ - id) /*!< Standard Rx FIFO Filter helper macro Type C mid-upper part helper macro. */ -#define FLEXCAN_RX_FIFO_STD_FILTER_TYPE_C_MID_LOW(id) \ - FLEXCAN_RX_FIFO_STD_MASK_TYPE_C_MID_LOW( \ - id) /*!< Standard Rx FIFO Filter helper macro Type C mid-lower part helper macro. */ -#define FLEXCAN_RX_FIFO_STD_FILTER_TYPE_C_LOW(id) \ - FLEXCAN_RX_FIFO_STD_MASK_TYPE_C_LOW(id) /*!< Standard Rx FIFO Filter helper macro Type C lower part helper macro. \ - */ -#define FLEXCAN_RX_FIFO_EXT_FILTER_TYPE_A(id, rtr, ide) \ - FLEXCAN_RX_FIFO_EXT_MASK_TYPE_A(id, rtr, ide) /*!< Extend Rx FIFO Filter helper macro Type A helper macro. */ -#define FLEXCAN_RX_FIFO_EXT_FILTER_TYPE_B_HIGH(id, rtr, ide) \ - FLEXCAN_RX_FIFO_EXT_MASK_TYPE_B_HIGH( \ - id, rtr, ide) /*!< Extend Rx FIFO Filter helper macro Type B upper part helper macro. */ -#define FLEXCAN_RX_FIFO_EXT_FILTER_TYPE_B_LOW(id, rtr, ide) \ - FLEXCAN_RX_FIFO_EXT_MASK_TYPE_B_LOW( \ - id, rtr, ide) /*!< Extend Rx FIFO Filter helper macro Type B lower part helper macro. */ -#define FLEXCAN_RX_FIFO_EXT_FILTER_TYPE_C_HIGH(id) \ - FLEXCAN_RX_FIFO_EXT_MASK_TYPE_C_HIGH(id) /*!< Extend Rx FIFO Filter helper macro Type C upper part helper macro. \ - */ -#define FLEXCAN_RX_FIFO_EXT_FILTER_TYPE_C_MID_HIGH(id) \ - FLEXCAN_RX_FIFO_EXT_MASK_TYPE_C_MID_HIGH( \ - id) /*!< Extend Rx FIFO Filter helper macro Type C mid-upper part helper macro. */ -#define FLEXCAN_RX_FIFO_EXT_FILTER_TYPE_C_MID_LOW(id) \ - FLEXCAN_RX_FIFO_EXT_MASK_TYPE_C_MID_LOW( \ - id) /*!< Extend Rx FIFO Filter helper macro Type C mid-lower part helper macro. */ -#define FLEXCAN_RX_FIFO_EXT_FILTER_TYPE_C_LOW(id) \ - FLEXCAN_RX_FIFO_EXT_MASK_TYPE_C_LOW(id) /*!< Extend Rx FIFO Filter helper macro Type C lower part helper macro. */ - -/*! @brief FlexCAN transfer status. */ -enum _flexcan_status -{ - kStatus_FLEXCAN_TxBusy = MAKE_STATUS(kStatusGroup_FLEXCAN, 0), /*!< Tx Message Buffer is Busy. */ - kStatus_FLEXCAN_TxIdle = MAKE_STATUS(kStatusGroup_FLEXCAN, 1), /*!< Tx Message Buffer is Idle. */ - kStatus_FLEXCAN_TxSwitchToRx = MAKE_STATUS( - kStatusGroup_FLEXCAN, 2), /*!< Remote Message is send out and Message buffer changed to Receive one. */ - kStatus_FLEXCAN_RxBusy = MAKE_STATUS(kStatusGroup_FLEXCAN, 3), /*!< Rx Message Buffer is Busy. */ - kStatus_FLEXCAN_RxIdle = MAKE_STATUS(kStatusGroup_FLEXCAN, 4), /*!< Rx Message Buffer is Idle. */ - kStatus_FLEXCAN_RxOverflow = MAKE_STATUS(kStatusGroup_FLEXCAN, 5), /*!< Rx Message Buffer is Overflowed. */ - kStatus_FLEXCAN_RxFifoBusy = MAKE_STATUS(kStatusGroup_FLEXCAN, 6), /*!< Rx Message FIFO is Busy. */ - kStatus_FLEXCAN_RxFifoIdle = MAKE_STATUS(kStatusGroup_FLEXCAN, 7), /*!< Rx Message FIFO is Idle. */ - kStatus_FLEXCAN_RxFifoOverflow = MAKE_STATUS(kStatusGroup_FLEXCAN, 8), /*!< Rx Message FIFO is overflowed. */ - kStatus_FLEXCAN_RxFifoWarning = MAKE_STATUS(kStatusGroup_FLEXCAN, 9), /*!< Rx Message FIFO is almost overflowed. */ - kStatus_FLEXCAN_ErrorStatus = MAKE_STATUS(kStatusGroup_FLEXCAN, 10), /*!< FlexCAN Module Error and Status. */ - kStatus_FLEXCAN_UnHandled = MAKE_STATUS(kStatusGroup_FLEXCAN, 11), /*!< UnHadled Interrupt asserted. */ -}; - -/*! @brief FlexCAN frame format. */ -typedef enum _flexcan_frame_format -{ - kFLEXCAN_FrameFormatStandard = 0x0U, /*!< Standard frame format attribute. */ - kFLEXCAN_FrameFormatExtend = 0x1U, /*!< Extend frame format attribute. */ -} flexcan_frame_format_t; - -/*! @brief FlexCAN frame type. */ -typedef enum _flexcan_frame_type -{ - kFLEXCAN_FrameTypeData = 0x0U, /*!< Data frame type attribute. */ - kFLEXCAN_FrameTypeRemote = 0x1U, /*!< Remote frame type attribute. */ -} flexcan_frame_type_t; - -#if (!defined(FSL_FEATURE_FLEXCAN_SUPPORT_ENGINE_CLK_SEL_REMOVE)) || !FSL_FEATURE_FLEXCAN_SUPPORT_ENGINE_CLK_SEL_REMOVE -/*! @brief FlexCAN clock source. */ -typedef enum _flexcan_clock_source -{ - kFLEXCAN_ClkSrcOsc = 0x0U, /*!< FlexCAN Protocol Engine clock from Oscillator. */ - kFLEXCAN_ClkSrcPeri = 0x1U, /*!< FlexCAN Protocol Engine clock from Peripheral Clock. */ -} flexcan_clock_source_t; -#endif /* FSL_FEATURE_FLEXCAN_SUPPORT_ENGINE_CLK_SEL_REMOVE */ - -/*! @brief FlexCAN Rx Fifo Filter type. */ -typedef enum _flexcan_rx_fifo_filter_type -{ - kFLEXCAN_RxFifoFilterTypeA = 0x0U, /*!< One full ID (standard and extended) per ID Filter element. */ - kFLEXCAN_RxFifoFilterTypeB = - 0x1U, /*!< Two full standard IDs or two partial 14-bit ID slices per ID Filter Table element. */ - kFLEXCAN_RxFifoFilterTypeC = - 0x2U, /*!< Four partial 8-bit Standard or extended ID slices per ID Filter Table element. */ - kFLEXCAN_RxFifoFilterTypeD = 0x3U, /*!< All frames rejected. */ -} flexcan_rx_fifo_filter_type_t; - -/*! - * @brief FlexCAN Rx FIFO priority. - * - * The matching process starts from the Rx MB(or Rx FIFO) with higher priority. - * If no MB(or Rx FIFO filter) is satisfied, the matching process goes on with - * the Rx FIFO(or Rx MB) with lower priority. - */ -typedef enum _flexcan_rx_fifo_priority -{ - kFLEXCAN_RxFifoPrioLow = 0x0U, /*!< Matching process start from Rx Message Buffer first*/ - kFLEXCAN_RxFifoPrioHigh = 0x1U, /*!< Matching process start from Rx FIFO first*/ -} flexcan_rx_fifo_priority_t; - -/*! - * @brief FlexCAN interrupt configuration structure, default settings all disabled. - * - * This structure contains the settings for all of the FlexCAN Module interrupt configurations. - * Note: FlexCAN Message Buffers and Rx FIFO have their own interrupts. - */ -enum _flexcan_interrupt_enable -{ - kFLEXCAN_BusOffInterruptEnable = CAN_CTRL1_BOFFMSK_MASK, /*!< Bus Off interrupt. */ - kFLEXCAN_ErrorInterruptEnable = CAN_CTRL1_ERRMSK_MASK, /*!< Error interrupt. */ - kFLEXCAN_RxWarningInterruptEnable = CAN_CTRL1_RWRNMSK_MASK, /*!< Rx Warning interrupt. */ - kFLEXCAN_TxWarningInterruptEnable = CAN_CTRL1_TWRNMSK_MASK, /*!< Tx Warning interrupt. */ - kFLEXCAN_WakeUpInterruptEnable = CAN_MCR_WAKMSK_MASK, /*!< Wake Up interrupt. */ -}; - -/*! - * @brief FlexCAN status flags. - * - * This provides constants for the FlexCAN status flags for use in the FlexCAN functions. - * Note: The CPU read action clears FlEXCAN_ErrorFlag, therefore user need to - * read FlEXCAN_ErrorFlag and distinguish which error is occur using - * @ref _flexcan_error_flags enumerations. - */ -enum _flexcan_flags -{ - kFLEXCAN_SynchFlag = CAN_ESR1_SYNCH_MASK, /*!< CAN Synchronization Status. */ - kFLEXCAN_TxWarningIntFlag = CAN_ESR1_TWRNINT_MASK, /*!< Tx Warning Interrupt Flag. */ - kFLEXCAN_RxWarningIntFlag = CAN_ESR1_RWRNINT_MASK, /*!< Rx Warning Interrupt Flag. */ - kFLEXCAN_TxErrorWarningFlag = CAN_ESR1_TXWRN_MASK, /*!< Tx Error Warning Status. */ - kFLEXCAN_RxErrorWarningFlag = CAN_ESR1_RXWRN_MASK, /*!< Rx Error Warning Status. */ - kFLEXCAN_IdleFlag = CAN_ESR1_IDLE_MASK, /*!< CAN IDLE Status Flag. */ - kFLEXCAN_FaultConfinementFlag = CAN_ESR1_FLTCONF_MASK, /*!< Fault Confinement State Flag. */ - kFLEXCAN_TransmittingFlag = CAN_ESR1_TX_MASK, /*!< FlexCAN In Transmission Status. */ - kFLEXCAN_ReceivingFlag = CAN_ESR1_RX_MASK, /*!< FlexCAN In Reception Status. */ - kFLEXCAN_BusOffIntFlag = CAN_ESR1_BOFFINT_MASK, /*!< Bus Off Interrupt Flag. */ - kFLEXCAN_ErrorIntFlag = CAN_ESR1_ERRINT_MASK, /*!< Error Interrupt Flag. */ - kFLEXCAN_WakeUpIntFlag = CAN_ESR1_WAKINT_MASK, /*!< Wake-Up Interrupt Flag. */ - kFLEXCAN_ErrorFlag = CAN_ESR1_BIT1ERR_MASK | /*!< All FlexCAN Error Status. */ - CAN_ESR1_BIT0ERR_MASK | - CAN_ESR1_ACKERR_MASK | CAN_ESR1_CRCERR_MASK | CAN_ESR1_FRMERR_MASK | CAN_ESR1_STFERR_MASK, -}; - -/*! - * @brief FlexCAN error status flags. - * - * The FlexCAN Error Status enumerations is used to report current error of the FlexCAN bus. - * This enumerations should be used with KFLEXCAN_ErrorFlag in @ref _flexcan_flags enumerations - * to ditermine which error is generated. - */ -enum _flexcan_error_flags -{ - kFLEXCAN_StuffingError = CAN_ESR1_STFERR_MASK, /*!< Stuffing Error. */ - kFLEXCAN_FormError = CAN_ESR1_FRMERR_MASK, /*!< Form Error. */ - kFLEXCAN_CrcError = CAN_ESR1_CRCERR_MASK, /*!< Cyclic Redundancy Check Error. */ - kFLEXCAN_AckError = CAN_ESR1_ACKERR_MASK, /*!< Received no ACK on transmission. */ - kFLEXCAN_Bit0Error = CAN_ESR1_BIT0ERR_MASK, /*!< Unable to send dominant bit. */ - kFLEXCAN_Bit1Error = CAN_ESR1_BIT1ERR_MASK, /*!< Unable to send recessive bit. */ -}; - -/*! - * @brief FlexCAN Rx FIFO status flags. - * - * The FlexCAN Rx FIFO Status enumerations are used to determine the status of the - * Rx FIFO. Because Rx FIFO occupy the MB0 ~ MB7 (Rx Fifo filter also occupies - * more Message Buffer space), Rx FIFO status flags are mapped to the corresponding - * Message Buffer status flags. - */ -enum _flexcan_rx_fifo_flags -{ - kFLEXCAN_RxFifoOverflowFlag = CAN_IFLAG1_BUF7I_MASK, /*!< Rx FIFO overflow flag. */ - kFLEXCAN_RxFifoWarningFlag = CAN_IFLAG1_BUF6I_MASK, /*!< Rx FIFO almost full flag. */ - kFLEXCAN_RxFifoFrameAvlFlag = CAN_IFLAG1_BUF5I_MASK, /*!< Frames available in Rx FIFO flag. */ -}; - -#if defined(__CC_ARM) -#pragma anon_unions -#endif -/*! @brief FlexCAN message frame structure. */ -typedef struct _flexcan_frame -{ - struct - { - uint32_t timestamp : 16; /*!< FlexCAN internal Free-Running Counter Time Stamp. */ - uint32_t length : 4; /*!< CAN frame payload length in bytes(Range: 0~8). */ - uint32_t type : 1; /*!< CAN Frame Type(DATA or REMOTE). */ - uint32_t format : 1; /*!< CAN Frame Identifier(STD or EXT format). */ - uint32_t : 1; /*!< Reserved. */ - uint32_t idhit : 9; /*!< CAN Rx FIFO filter hit id(This value is only used in Rx FIFO receive mode). */ - }; - struct - { - uint32_t id : 29; /*!< CAN Frame Identifier, should be set using FLEXCAN_ID_EXT() or FLEXCAN_ID_STD() macro. */ - uint32_t : 3; /*!< Reserved. */ - }; - union - { - struct - { - uint32_t dataWord0; /*!< CAN Frame payload word0. */ - uint32_t dataWord1; /*!< CAN Frame payload word1. */ - }; - struct - { - uint8_t dataByte3; /*!< CAN Frame payload byte3. */ - uint8_t dataByte2; /*!< CAN Frame payload byte2. */ - uint8_t dataByte1; /*!< CAN Frame payload byte1. */ - uint8_t dataByte0; /*!< CAN Frame payload byte0. */ - uint8_t dataByte7; /*!< CAN Frame payload byte7. */ - uint8_t dataByte6; /*!< CAN Frame payload byte6. */ - uint8_t dataByte5; /*!< CAN Frame payload byte5. */ - uint8_t dataByte4; /*!< CAN Frame payload byte4. */ - }; - }; -} flexcan_frame_t; - -/*! @brief FlexCAN module configuration structure. */ -typedef struct _flexcan_config -{ - uint32_t baudRate; /*!< FlexCAN baud rate in bps. */ -#if (!defined(FSL_FEATURE_FLEXCAN_SUPPORT_ENGINE_CLK_SEL_REMOVE)) || !FSL_FEATURE_FLEXCAN_SUPPORT_ENGINE_CLK_SEL_REMOVE - flexcan_clock_source_t clkSrc; /*!< Clock source for FlexCAN Protocol Engine. */ -#endif /* FSL_FEATURE_FLEXCAN_SUPPORT_ENGINE_CLK_SEL_REMOVE */ - uint8_t maxMbNum; /*!< The maximum number of Message Buffers used by user. */ - bool enableLoopBack; /*!< Enable or Disable Loop Back Self Test Mode. */ - bool enableSelfWakeup; /*!< Enable or Disable Self Wakeup Mode. */ - bool enableIndividMask; /*!< Enable or Disable Rx Individual Mask. */ -#if (defined(FSL_FEATURE_FLEXCAN_HAS_DOZE_MODE_SUPPORT) && FSL_FEATURE_FLEXCAN_HAS_DOZE_MODE_SUPPORT) - bool enableDoze; /*!< Enable or Disable Doze Mode. */ -#endif -} flexcan_config_t; - -/*! @brief FlexCAN protocol timing characteristic configuration structure. */ -typedef struct _flexcan_timing_config -{ - uint8_t preDivider; /*!< Clock Pre-scaler Division Factor. */ - uint8_t rJumpwidth; /*!< Re-sync Jump Width. */ - uint8_t phaseSeg1; /*!< Phase Segment 1. */ - uint8_t phaseSeg2; /*!< Phase Segment 2. */ - uint8_t propSeg; /*!< Propagation Segment. */ -} flexcan_timing_config_t; - -/*! - * @brief FlexCAN Receive Message Buffer configuration structure - * - * This structure is used as the parameter of FLEXCAN_SetRxMbConfig() function. - * The FLEXCAN_SetRxMbConfig() function is used to configure FlexCAN Receive - * Message Buffer. The function abort previous receiving process, clean the - * Message Buffer and activate the Rx Message Buffer using given Message Buffer - * setting. - */ -typedef struct _flexcan_rx_mb_config -{ - uint32_t id; /*!< CAN Message Buffer Frame Identifier, should be set using - FLEXCAN_ID_EXT() or FLEXCAN_ID_STD() macro. */ - flexcan_frame_format_t format; /*!< CAN Frame Identifier format(Standard of Extend). */ - flexcan_frame_type_t type; /*!< CAN Frame Type(Data or Remote). */ -} flexcan_rx_mb_config_t; - -/*! @brief FlexCAN Rx FIFO configuration structure. */ -typedef struct _flexcan_rx_fifo_config -{ - uint32_t *idFilterTable; /*!< Pointer to the FlexCAN Rx FIFO identifier filter table. */ - uint8_t idFilterNum; /*!< The quantity of filter elements. */ - flexcan_rx_fifo_filter_type_t idFilterType; /*!< The FlexCAN Rx FIFO Filter type. */ - flexcan_rx_fifo_priority_t priority; /*!< The FlexCAN Rx FIFO receive priority. */ -} flexcan_rx_fifo_config_t; - -/*! @brief FlexCAN Message Buffer transfer. */ -typedef struct _flexcan_mb_transfer -{ - flexcan_frame_t *frame; /*!< The buffer of CAN Message to be transfer. */ - uint8_t mbIdx; /*!< The index of Message buffer used to transfer Message. */ -} flexcan_mb_transfer_t; - -/*! @brief FlexCAN Rx FIFO transfer. */ -typedef struct _flexcan_fifo_transfer -{ - flexcan_frame_t *frame; /*!< The buffer of CAN Message to be received from Rx FIFO. */ -} flexcan_fifo_transfer_t; - -/*! @brief FlexCAN handle structure definition. */ -typedef struct _flexcan_handle flexcan_handle_t; - -/*! @brief FlexCAN transfer callback function. - * - * The FlexCAN transfer callback returns a value from the underlying layer. - * If the status equals to kStatus_FLEXCAN_ErrorStatus, the result parameter is the Content of - * FlexCAN status register which can be used to get the working status(or error status) of FlexCAN module. - * If the status equals to other FlexCAN Message Buffer transfer status, the result is the index of - * Message Buffer that generate transfer event. - * If the status equals to other FlexCAN Message Buffer transfer status, the result is meaningless and should be - * Ignored. - */ -typedef void (*flexcan_transfer_callback_t)( - CAN_Type *base, flexcan_handle_t *handle, status_t status, uint32_t result, void *userData); - -/*! @brief FlexCAN handle structure. */ -struct _flexcan_handle -{ - flexcan_transfer_callback_t callback; /*!< Callback function. */ - void *userData; /*!< FlexCAN callback function parameter.*/ - flexcan_frame_t *volatile mbFrameBuf[CAN_WORD1_COUNT]; - /*!< The buffer for received data from Message Buffers. */ - flexcan_frame_t *volatile rxFifoFrameBuf; /*!< The buffer for received data from Rx FIFO. */ - volatile uint8_t mbState[CAN_WORD1_COUNT]; /*!< Message Buffer transfer state. */ - volatile uint8_t rxFifoState; /*!< Rx FIFO transfer state. */ -}; - -/****************************************************************************** - * API - *****************************************************************************/ - -#if defined(__cplusplus) -extern "C" { -#endif - -/*! - * @name Initialization and deinitialization - * @{ - */ - -/*! - * @brief Initializes a FlexCAN instance. - * - * This function initializes the FlexCAN module with user-defined settings. - * This example shows how to set up the flexcan_config_t parameters and how - * to call the FLEXCAN_Init function by passing in these parameters. - * @code - * flexcan_config_t flexcanConfig; - * flexcanConfig.clkSrc = kFLEXCAN_ClkSrcOsc; - * flexcanConfig.baudRate = 125000U; - * flexcanConfig.maxMbNum = 16; - * flexcanConfig.enableLoopBack = false; - * flexcanConfig.enableSelfWakeup = false; - * flexcanConfig.enableIndividMask = false; - * flexcanConfig.enableDoze = false; - * FLEXCAN_Init(CAN0, &flexcanConfig, 8000000UL); - * @endcode - * - * @param base FlexCAN peripheral base address. - * @param config Pointer to the user-defined configuration structure. - * @param sourceClock_Hz FlexCAN Protocol Engine clock source frequency in Hz. - */ -void FLEXCAN_Init(CAN_Type *base, const flexcan_config_t *config, uint32_t sourceClock_Hz); - -/*! - * @brief De-initializes a FlexCAN instance. - * - * This function disables the FlexCAN module clock and sets all register values - * to the reset value. - * - * @param base FlexCAN peripheral base address. - */ -void FLEXCAN_Deinit(CAN_Type *base); - -/*! - * @brief Gets the default configuration structure. - * - * This function initializes the FlexCAN configuration structure to default values. The default - * values are as follows. - * flexcanConfig->clkSrc = KFLEXCAN_ClkSrcOsc; - * flexcanConfig->baudRate = 125000U; - * flexcanConfig->maxMbNum = 16; - * flexcanConfig->enableLoopBack = false; - * flexcanConfig->enableSelfWakeup = false; - * flexcanConfig->enableIndividMask = false; - * flexcanConfig->enableDoze = false; - * - * @param config Pointer to the FlexCAN configuration structure. - */ -void FLEXCAN_GetDefaultConfig(flexcan_config_t *config); - -/* @} */ - -/*! - * @name Configuration. - * @{ - */ - -/*! - * @brief Sets the FlexCAN protocol timing characteristic. - * - * This function gives user settings to CAN bus timing characteristic. - * The function is for an experienced user. For less experienced users, call - * the FLEXCAN_Init() and fill the baud rate field with a desired value. - * This provides the default timing characteristics to the module. - * - * Note that calling FLEXCAN_SetTimingConfig() overrides the baud rate set - * in FLEXCAN_Init(). - * - * @param base FlexCAN peripheral base address. - * @param config Pointer to the timing configuration structure. - */ -void FLEXCAN_SetTimingConfig(CAN_Type *base, const flexcan_timing_config_t *config); - -/*! - * @brief Sets the FlexCAN receive message buffer global mask. - * - * This function sets the global mask for the FlexCAN message buffer in a matching process. - * The configuration is only effective when the Rx individual mask is disabled in the FLEXCAN_Init(). - * - * @param base FlexCAN peripheral base address. - * @param mask Rx Message Buffer Global Mask value. - */ -void FLEXCAN_SetRxMbGlobalMask(CAN_Type *base, uint32_t mask); - -/*! - * @brief Sets the FlexCAN receive FIFO global mask. - * - * This function sets the global mask for FlexCAN FIFO in a matching process. - * - * @param base FlexCAN peripheral base address. - * @param mask Rx Fifo Global Mask value. - */ -void FLEXCAN_SetRxFifoGlobalMask(CAN_Type *base, uint32_t mask); - -/*! - * @brief Sets the FlexCAN receive individual mask. - * - * This function sets the individual mask for the FlexCAN matching process. - * The configuration is only effective when the Rx individual mask is enabled in the FLEXCAN_Init(). - * If the Rx FIFO is disabled, the individual mask is applied to the corresponding Message Buffer. - * If the Rx FIFO is enabled, the individual mask for Rx FIFO occupied Message Buffer is applied to - * the Rx Filter with the same index. Note that only the first 32 - * individual masks can be used as the Rx FIFO filter mask. - * - * @param base FlexCAN peripheral base address. - * @param maskIdx The Index of individual Mask. - * @param mask Rx Individual Mask value. - */ -void FLEXCAN_SetRxIndividualMask(CAN_Type *base, uint8_t maskIdx, uint32_t mask); - -/*! - * @brief Configures a FlexCAN transmit message buffer. - * - * This function aborts the previous transmission, cleans the Message Buffer, and - * configures it as a Transmit Message Buffer. - * - * @param base FlexCAN peripheral base address. - * @param mbIdx The Message Buffer index. - * @param enable Enable/disable Tx Message Buffer. - * - true: Enable Tx Message Buffer. - * - false: Disable Tx Message Buffer. - */ -void FLEXCAN_SetTxMbConfig(CAN_Type *base, uint8_t mbIdx, bool enable); - -/*! - * @brief Configures a FlexCAN Receive Message Buffer. - * - * This function cleans a FlexCAN build-in Message Buffer and configures it - * as a Receive Message Buffer. - * - * @param base FlexCAN peripheral base address. - * @param mbIdx The Message Buffer index. - * @param config Pointer to the FlexCAN Message Buffer configuration structure. - * @param enable Enable/disable Rx Message Buffer. - * - true: Enable Rx Message Buffer. - * - false: Disable Rx Message Buffer. - */ -void FLEXCAN_SetRxMbConfig(CAN_Type *base, uint8_t mbIdx, const flexcan_rx_mb_config_t *config, bool enable); - -/*! - * @brief Configures the FlexCAN Rx FIFO. - * - * This function configures the Rx FIFO with given Rx FIFO configuration. - * - * @param base FlexCAN peripheral base address. - * @param config Pointer to the FlexCAN Rx FIFO configuration structure. - * @param enable Enable/disable Rx FIFO. - * - true: Enable Rx FIFO. - * - false: Disable Rx FIFO. - */ -void FLEXCAN_SetRxFifoConfig(CAN_Type *base, const flexcan_rx_fifo_config_t *config, bool enable); - -/* @} */ - -/*! - * @name Status - * @{ - */ - -/*! - * @brief Gets the FlexCAN module interrupt flags. - * - * This function gets all FlexCAN status flags. The flags are returned as the logical - * OR value of the enumerators @ref _flexcan_flags. To check the specific status, - * compare the return value with enumerators in @ref _flexcan_flags. - * - * @param base FlexCAN peripheral base address. - * @return FlexCAN status flags which are ORed by the enumerators in the _flexcan_flags. - */ -static inline uint32_t FLEXCAN_GetStatusFlags(CAN_Type *base) -{ - return base->ESR1; -} - -/*! - * @brief Clears status flags with the provided mask. - * - * This function clears the FlexCAN status flags with a provided mask. An automatically cleared flag - * can't be cleared by this function. - * - * @param base FlexCAN peripheral base address. - * @param mask The status flags to be cleared, it is logical OR value of @ref _flexcan_flags. - */ -static inline void FLEXCAN_ClearStatusFlags(CAN_Type *base, uint32_t mask) -{ - /* Write 1 to clear status flag. */ - base->ESR1 = mask; -} - -/*! - * @brief Gets the FlexCAN Bus Error Counter value. - * - * This function gets the FlexCAN Bus Error Counter value for both Tx and - * Rx direction. These values may be needed in the upper layer error handling. - * - * @param base FlexCAN peripheral base address. - * @param txErrBuf Buffer to store Tx Error Counter value. - * @param rxErrBuf Buffer to store Rx Error Counter value. - */ -static inline void FLEXCAN_GetBusErrCount(CAN_Type *base, uint8_t *txErrBuf, uint8_t *rxErrBuf) -{ - if (txErrBuf) - { - *txErrBuf = (uint8_t)((base->ECR & CAN_ECR_TXERRCNT_MASK) >> CAN_ECR_TXERRCNT_SHIFT); - } - - if (rxErrBuf) - { - *rxErrBuf = (uint8_t)((base->ECR & CAN_ECR_RXERRCNT_MASK) >> CAN_ECR_RXERRCNT_SHIFT); - } -} - -/*! - * @brief Gets the FlexCAN Message Buffer interrupt flags. - * - * This function gets the interrupt flags of a given Message Buffers. - * - * @param base FlexCAN peripheral base address. - * @param mask The ORed FlexCAN Message Buffer mask. - * @return The status of given Message Buffers. - */ -#if (defined(FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER)) && (FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER > 0) -static inline uint64_t FLEXCAN_GetMbStatusFlags(CAN_Type *base, uint64_t mask) -#else -static inline uint32_t FLEXCAN_GetMbStatusFlags(CAN_Type *base, uint32_t mask) -#endif -{ -#if (defined(FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER)) && (FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER > 0) - return ((((uint64_t)base->IFLAG1) & mask) | ((((uint64_t)base->IFLAG2) << 32) & mask)); -#else - return (base->IFLAG1 & mask); -#endif -} - -/*! - * @brief Clears the FlexCAN Message Buffer interrupt flags. - * - * This function clears the interrupt flags of a given Message Buffers. - * - * @param base FlexCAN peripheral base address. - * @param mask The ORed FlexCAN Message Buffer mask. - */ -#if (defined(FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER)) && (FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER > 0) -static inline void FLEXCAN_ClearMbStatusFlags(CAN_Type *base, uint64_t mask) -#else -static inline void FLEXCAN_ClearMbStatusFlags(CAN_Type *base, uint32_t mask) -#endif -{ -#if (defined(FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER)) && (FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER > 0) - base->IFLAG1 = (uint32_t)(mask & 0xFFFFFFFFU); - base->IFLAG2 = (uint32_t)(mask >> 32); -#else - base->IFLAG1 = mask; -#endif -} - -/* @} */ - -/*! - * @name Interrupts - * @{ - */ - -/*! - * @brief Enables FlexCAN interrupts according to the provided mask. - * - * This function enables the FlexCAN interrupts according to the provided mask. The mask - * is a logical OR of enumeration members, see @ref _flexcan_interrupt_enable. - * - * @param base FlexCAN peripheral base address. - * @param mask The interrupts to enable. Logical OR of @ref _flexcan_interrupt_enable. - */ -static inline void FLEXCAN_EnableInterrupts(CAN_Type *base, uint32_t mask) -{ - /* Solve Wake Up Interrupt. */ - if (mask & kFLEXCAN_WakeUpInterruptEnable) - { - base->MCR |= CAN_MCR_WAKMSK_MASK; - } - - /* Solve others. */ - base->CTRL1 |= (mask & (~((uint32_t)kFLEXCAN_WakeUpInterruptEnable))); -} - -/*! - * @brief Disables FlexCAN interrupts according to the provided mask. - * - * This function disables the FlexCAN interrupts according to the provided mask. The mask - * is a logical OR of enumeration members, see @ref _flexcan_interrupt_enable. - * - * @param base FlexCAN peripheral base address. - * @param mask The interrupts to disable. Logical OR of @ref _flexcan_interrupt_enable. - */ -static inline void FLEXCAN_DisableInterrupts(CAN_Type *base, uint32_t mask) -{ - /* Solve Wake Up Interrupt. */ - if (mask & kFLEXCAN_WakeUpInterruptEnable) - { - base->MCR &= ~CAN_MCR_WAKMSK_MASK; - } - - /* Solve others. */ - base->CTRL1 &= ~(mask & (~((uint32_t)kFLEXCAN_WakeUpInterruptEnable))); -} - -/*! - * @brief Enables FlexCAN Message Buffer interrupts. - * - * This function enables the interrupts of given Message Buffers. - * - * @param base FlexCAN peripheral base address. - * @param mask The ORed FlexCAN Message Buffer mask. - */ -#if (defined(FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER)) && (FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER > 0) -static inline void FLEXCAN_EnableMbInterrupts(CAN_Type *base, uint64_t mask) -#else -static inline void FLEXCAN_EnableMbInterrupts(CAN_Type *base, uint32_t mask) -#endif -{ -#if (defined(FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER)) && (FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER > 0) - base->IMASK1 |= (uint32_t)(mask & 0xFFFFFFFFU); - base->IMASK2 |= (uint32_t)(mask >> 32); -#else - base->IMASK1 |= mask; -#endif -} - -/*! - * @brief Disables FlexCAN Message Buffer interrupts. - * - * This function disables the interrupts of given Message Buffers. - * - * @param base FlexCAN peripheral base address. - * @param mask The ORed FlexCAN Message Buffer mask. - */ -#if (defined(FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER)) && (FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER > 0) -static inline void FLEXCAN_DisableMbInterrupts(CAN_Type *base, uint64_t mask) -#else -static inline void FLEXCAN_DisableMbInterrupts(CAN_Type *base, uint32_t mask) -#endif -{ -#if (defined(FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER)) && (FSL_FEATURE_FLEXCAN_HAS_EXTENDED_FLAG_REGISTER > 0) - base->IMASK1 &= ~((uint32_t)(mask & 0xFFFFFFFFU)); - base->IMASK2 &= ~((uint32_t)(mask >> 32)); -#else - base->IMASK1 &= ~mask; -#endif -} - -/* @} */ - -#if (defined(FSL_FEATURE_FLEXCAN_HAS_RX_FIFO_DMA) && FSL_FEATURE_FLEXCAN_HAS_RX_FIFO_DMA) -/*! - * @name DMA Control - * @{ - */ - -/*! - * @brief Enables or disables the FlexCAN Rx FIFO DMA request. - * - * This function enables or disables the DMA feature of FlexCAN build-in Rx FIFO. - * - * @param base FlexCAN peripheral base address. - * @param enable true to enable, false to disable. - */ -void FLEXCAN_EnableRxFifoDMA(CAN_Type *base, bool enable); - -/*! - * @brief Gets the Rx FIFO Head address. - * - * This function returns the FlexCAN Rx FIFO Head address, which is mainly used for the DMA/eDMA use case. - * - * @param base FlexCAN peripheral base address. - * @return FlexCAN Rx FIFO Head address. - */ -static inline uint32_t FLEXCAN_GetRxFifoHeadAddr(CAN_Type *base) -{ - return (uint32_t) & (base->MB[0].CS); -} - -/* @} */ -#endif /* FSL_FEATURE_FLEXCAN_HAS_RX_FIFO_DMA */ - -/*! - * @name Bus Operations - * @{ - */ - -/*! - * @brief Enables or disables the FlexCAN module operation. - * - * This function enables or disables the FlexCAN module. - * - * @param base FlexCAN base pointer. - * @param enable true to enable, false to disable. - */ -static inline void FLEXCAN_Enable(CAN_Type *base, bool enable) -{ - if (enable) - { - base->MCR &= ~CAN_MCR_MDIS_MASK; - - /* Wait FlexCAN exit from low-power mode. */ - while (base->MCR & CAN_MCR_LPMACK_MASK) - { - } - } - else - { - base->MCR |= CAN_MCR_MDIS_MASK; - - /* Wait FlexCAN enter low-power mode. */ - while (!(base->MCR & CAN_MCR_LPMACK_MASK)) - { - } - } -} - -/*! - * @brief Writes a FlexCAN Message to the Transmit Message Buffer. - * - * This function writes a CAN Message to the specified Transmit Message Buffer - * and changes the Message Buffer state to start CAN Message transmit. After - * that the function returns immediately. - * - * @param base FlexCAN peripheral base address. - * @param mbIdx The FlexCAN Message Buffer index. - * @param txFrame Pointer to CAN message frame to be sent. - * @retval kStatus_Success - Write Tx Message Buffer Successfully. - * @retval kStatus_Fail - Tx Message Buffer is currently in use. - */ -status_t FLEXCAN_WriteTxMb(CAN_Type *base, uint8_t mbIdx, const flexcan_frame_t *txFrame); - -/*! - * @brief Reads a FlexCAN Message from Receive Message Buffer. - * - * This function reads a CAN message from a specified Receive Message Buffer. - * The function fills a receive CAN message frame structure with - * just received data and activates the Message Buffer again. - * The function returns immediately. - * - * @param base FlexCAN peripheral base address. - * @param mbIdx The FlexCAN Message Buffer index. - * @param rxFrame Pointer to CAN message frame structure for reception. - * @retval kStatus_Success - Rx Message Buffer is full and has been read successfully. - * @retval kStatus_FLEXCAN_RxOverflow - Rx Message Buffer is already overflowed and has been read successfully. - * @retval kStatus_Fail - Rx Message Buffer is empty. - */ -status_t FLEXCAN_ReadRxMb(CAN_Type *base, uint8_t mbIdx, flexcan_frame_t *rxFrame); - -/*! - * @brief Reads a FlexCAN Message from Rx FIFO. - * - * This function reads a CAN message from the FlexCAN build-in Rx FIFO. - * - * @param base FlexCAN peripheral base address. - * @param rxFrame Pointer to CAN message frame structure for reception. - * @retval kStatus_Success - Read Message from Rx FIFO successfully. - * @retval kStatus_Fail - Rx FIFO is not enabled. - */ -status_t FLEXCAN_ReadRxFifo(CAN_Type *base, flexcan_frame_t *rxFrame); - -/* @} */ - -/*! - * @name Transactional - * @{ - */ - -/*! - * @brief Performs a polling send transaction on the CAN bus. - * - * Note that a transfer handle does not need to be created before calling this API. - * - * @param base FlexCAN peripheral base pointer. - * @param mbIdx The FlexCAN Message Buffer index. - * @param txFrame Pointer to CAN message frame to be sent. - * @retval kStatus_Success - Write Tx Message Buffer Successfully. - * @retval kStatus_Fail - Tx Message Buffer is currently in use. - */ -status_t FLEXCAN_TransferSendBlocking(CAN_Type *base, uint8_t mbIdx, flexcan_frame_t *txFrame); - -/*! - * @brief Performs a polling receive transaction on the CAN bus. - * - * Note that a transfer handle does not need to be created before calling this API. - * - * @param base FlexCAN peripheral base pointer. - * @param mbIdx The FlexCAN Message Buffer index. - * @param rxFrame Pointer to CAN message frame structure for reception. - * @retval kStatus_Success - Rx Message Buffer is full and has been read successfully. - * @retval kStatus_FLEXCAN_RxOverflow - Rx Message Buffer is already overflowed and has been read successfully. - * @retval kStatus_Fail - Rx Message Buffer is empty. - */ -status_t FLEXCAN_TransferReceiveBlocking(CAN_Type *base, uint8_t mbIdx, flexcan_frame_t *rxFrame); - -/*! - * @brief Performs a polling receive transaction from Rx FIFO on the CAN bus. - * - * Note that a transfer handle does not need to be created before calling this API. - * - * @param base FlexCAN peripheral base pointer. - * @param rxFrame Pointer to CAN message frame structure for reception. - * @retval kStatus_Success - Read Message from Rx FIFO successfully. - * @retval kStatus_Fail - Rx FIFO is not enabled. - */ -status_t FLEXCAN_TransferReceiveFifoBlocking(CAN_Type *base, flexcan_frame_t *rxFrame); - -/*! - * @brief Initializes the FlexCAN handle. - * - * This function initializes the FlexCAN handle, which can be used for other FlexCAN - * transactional APIs. Usually, for a specified FlexCAN instance, - * call this API once to get the initialized handle. - * - * @param base FlexCAN peripheral base address. - * @param handle FlexCAN handle pointer. - * @param callback The callback function. - * @param userData The parameter of the callback function. - */ -void FLEXCAN_TransferCreateHandle(CAN_Type *base, - flexcan_handle_t *handle, - flexcan_transfer_callback_t callback, - void *userData); - -/*! - * @brief Sends a message using IRQ. - * - * This function sends a message using IRQ. This is a non-blocking function, which returns - * right away. When messages have been sent out, the send callback function is called. - * - * @param base FlexCAN peripheral base address. - * @param handle FlexCAN handle pointer. - * @param xfer FlexCAN Message Buffer transfer structure. See the #flexcan_mb_transfer_t. - * @retval kStatus_Success Start Tx Message Buffer sending process successfully. - * @retval kStatus_Fail Write Tx Message Buffer failed. - * @retval kStatus_FLEXCAN_TxBusy Tx Message Buffer is in use. - */ -status_t FLEXCAN_TransferSendNonBlocking(CAN_Type *base, flexcan_handle_t *handle, flexcan_mb_transfer_t *xfer); - -/*! - * @brief Receives a message using IRQ. - * - * This function receives a message using IRQ. This is non-blocking function, which returns - * right away. When the message has been received, the receive callback function is called. - * - * @param base FlexCAN peripheral base address. - * @param handle FlexCAN handle pointer. - * @param xfer FlexCAN Message Buffer transfer structure. See the #flexcan_mb_transfer_t. - * @retval kStatus_Success - Start Rx Message Buffer receiving process successfully. - * @retval kStatus_FLEXCAN_RxBusy - Rx Message Buffer is in use. - */ -status_t FLEXCAN_TransferReceiveNonBlocking(CAN_Type *base, flexcan_handle_t *handle, flexcan_mb_transfer_t *xfer); - -/*! - * @brief Receives a message from Rx FIFO using IRQ. - * - * This function receives a message using IRQ. This is a non-blocking function, which returns - * right away. When all messages have been received, the receive callback function is called. - * - * @param base FlexCAN peripheral base address. - * @param handle FlexCAN handle pointer. - * @param xfer FlexCAN Rx FIFO transfer structure. See the @ref flexcan_fifo_transfer_t. - * @retval kStatus_Success - Start Rx FIFO receiving process successfully. - * @retval kStatus_FLEXCAN_RxFifoBusy - Rx FIFO is currently in use. - */ -status_t FLEXCAN_TransferReceiveFifoNonBlocking(CAN_Type *base, - flexcan_handle_t *handle, - flexcan_fifo_transfer_t *xfer); - -/*! - * @brief Aborts the interrupt driven message send process. - * - * This function aborts the interrupt driven message send process. - * - * @param base FlexCAN peripheral base address. - * @param handle FlexCAN handle pointer. - * @param mbIdx The FlexCAN Message Buffer index. - */ -void FLEXCAN_TransferAbortSend(CAN_Type *base, flexcan_handle_t *handle, uint8_t mbIdx); - -/*! - * @brief Aborts the interrupt driven message receive process. - * - * This function aborts the interrupt driven message receive process. - * - * @param base FlexCAN peripheral base address. - * @param handle FlexCAN handle pointer. - * @param mbIdx The FlexCAN Message Buffer index. - */ -void FLEXCAN_TransferAbortReceive(CAN_Type *base, flexcan_handle_t *handle, uint8_t mbIdx); - -/*! - * @brief Aborts the interrupt driven message receive from Rx FIFO process. - * - * This function aborts the interrupt driven message receive from Rx FIFO process. - * - * @param base FlexCAN peripheral base address. - * @param handle FlexCAN handle pointer. - */ -void FLEXCAN_TransferAbortReceiveFifo(CAN_Type *base, flexcan_handle_t *handle); - -/*! - * @brief FlexCAN IRQ handle function. - * - * This function handles the FlexCAN Error, the Message Buffer, and the Rx FIFO IRQ request. - * - * @param base FlexCAN peripheral base address. - * @param handle FlexCAN handle pointer. - */ -void FLEXCAN_TransferHandleIRQ(CAN_Type *base, flexcan_handle_t *handle); - -/* @} */ - -#if defined(__cplusplus) -} -#endif - -/*! @}*/ - -#endif /* _FSL_FLEXCAN_H_ */ diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_ftm.c b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_ftm.c deleted file mode 100644 index 9cca44b0e41..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_ftm.c +++ /dev/null @@ -1,908 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "fsl_ftm.h" - -/******************************************************************************* - * Prototypes - ******************************************************************************/ -/*! - * @brief Gets the instance from the base address - * - * @param base FTM peripheral base address - * - * @return The FTM instance - */ -static uint32_t FTM_GetInstance(FTM_Type *base); - -/*! - * @brief Sets the FTM register PWM synchronization method - * - * This function will set the necessary bits for the PWM synchronization mode that - * user wishes to use. - * - * @param base FTM peripheral base address - * @param syncMethod Syncronization methods to use to update buffered registers. This is a logical - * OR of members of the enumeration ::ftm_pwm_sync_method_t - */ -static void FTM_SetPwmSync(FTM_Type *base, uint32_t syncMethod); - -/*! - * @brief Sets the reload points used as loading points for register update - * - * This function will set the necessary bits based on what the user wishes to use as loading - * points for FTM register update. When using this it is not required to use PWM synchnronization. - * - * @param base FTM peripheral base address - * @param reloadPoints FTM reload points. This is a logical OR of members of the - * enumeration ::ftm_reload_point_t - */ -static void FTM_SetReloadPoints(FTM_Type *base, uint32_t reloadPoints); - -/******************************************************************************* - * Variables - ******************************************************************************/ -/*! @brief Pointers to FTM bases for each instance. */ -static FTM_Type *const s_ftmBases[] = FTM_BASE_PTRS; - -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) -/*! @brief Pointers to FTM clocks for each instance. */ -static const clock_ip_name_t s_ftmClocks[] = FTM_CLOCKS; -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ - -/******************************************************************************* - * Code - ******************************************************************************/ -static uint32_t FTM_GetInstance(FTM_Type *base) -{ - uint32_t instance; - uint32_t ftmArrayCount = (sizeof(s_ftmBases) / sizeof(s_ftmBases[0])); - - /* Find the instance index from base address mappings. */ - for (instance = 0; instance < ftmArrayCount; instance++) - { - if (s_ftmBases[instance] == base) - { - break; - } - } - - assert(instance < ftmArrayCount); - - return instance; -} - -static void FTM_SetPwmSync(FTM_Type *base, uint32_t syncMethod) -{ - uint8_t chnlNumber = 0; - uint32_t reg = 0, syncReg = 0; - - syncReg = base->SYNC; - /* Enable PWM synchronization of output mask register */ - syncReg |= FTM_SYNC_SYNCHOM_MASK; - - reg = base->COMBINE; - for (chnlNumber = 0; chnlNumber < (FSL_FEATURE_FTM_CHANNEL_COUNTn(base) / 2); chnlNumber++) - { - /* Enable PWM synchronization of registers C(n)V and C(n+1)V */ - reg |= (1U << (FTM_COMBINE_SYNCEN0_SHIFT + (FTM_COMBINE_COMBINE1_SHIFT * chnlNumber))); - } - base->COMBINE = reg; - - reg = base->SYNCONF; - - /* Use enhanced PWM synchronization method. Use PWM sync to update register values */ - reg |= (FTM_SYNCONF_SYNCMODE_MASK | FTM_SYNCONF_CNTINC_MASK | FTM_SYNCONF_INVC_MASK | FTM_SYNCONF_SWOC_MASK); - - if (syncMethod & FTM_SYNC_SWSYNC_MASK) - { - /* Enable needed bits for software trigger to update registers with its buffer value */ - reg |= (FTM_SYNCONF_SWRSTCNT_MASK | FTM_SYNCONF_SWWRBUF_MASK | FTM_SYNCONF_SWINVC_MASK | - FTM_SYNCONF_SWSOC_MASK | FTM_SYNCONF_SWOM_MASK); - } - - if (syncMethod & (FTM_SYNC_TRIG0_MASK | FTM_SYNC_TRIG1_MASK | FTM_SYNC_TRIG2_MASK)) - { - /* Enable needed bits for hardware trigger to update registers with its buffer value */ - reg |= (FTM_SYNCONF_HWRSTCNT_MASK | FTM_SYNCONF_HWWRBUF_MASK | FTM_SYNCONF_HWINVC_MASK | - FTM_SYNCONF_HWSOC_MASK | FTM_SYNCONF_HWOM_MASK); - - /* Enable the appropriate hardware trigger that is used for PWM sync */ - if (syncMethod & FTM_SYNC_TRIG0_MASK) - { - syncReg |= FTM_SYNC_TRIG0_MASK; - } - if (syncMethod & FTM_SYNC_TRIG1_MASK) - { - syncReg |= FTM_SYNC_TRIG1_MASK; - } - if (syncMethod & FTM_SYNC_TRIG2_MASK) - { - syncReg |= FTM_SYNC_TRIG2_MASK; - } - } - - /* Write back values to the SYNC register */ - base->SYNC = syncReg; - - /* Write the PWM synch values to the SYNCONF register */ - base->SYNCONF = reg; -} - -static void FTM_SetReloadPoints(FTM_Type *base, uint32_t reloadPoints) -{ - uint32_t chnlNumber = 0; - uint32_t reg = 0; - - /* Need CNTINC bit to be 1 for CNTIN register to update with its buffer value on reload */ - base->SYNCONF |= FTM_SYNCONF_CNTINC_MASK; - - reg = base->COMBINE; - for (chnlNumber = 0; chnlNumber < (FSL_FEATURE_FTM_CHANNEL_COUNTn(base) / 2); chnlNumber++) - { - /* Need SYNCEN bit to be 1 for CnV reg to update with its buffer value on reload */ - reg |= (1U << (FTM_COMBINE_SYNCEN0_SHIFT + (FTM_COMBINE_COMBINE1_SHIFT * chnlNumber))); - } - base->COMBINE = reg; - - /* Set the reload points */ - reg = base->PWMLOAD; - - /* Enable the selected channel match reload points */ - reg &= ~((1U << FSL_FEATURE_FTM_CHANNEL_COUNTn(base)) - 1); - reg |= (reloadPoints & ((1U << FSL_FEATURE_FTM_CHANNEL_COUNTn(base)) - 1)); - -#if defined(FSL_FEATURE_FTM_HAS_HALFCYCLE_RELOAD) && (FSL_FEATURE_FTM_HAS_HALFCYCLE_RELOAD) - /* Enable half cycle match as a reload point */ - if (reloadPoints & kFTM_HalfCycMatch) - { - reg |= FTM_PWMLOAD_HCSEL_MASK; - } - else - { - reg &= ~FTM_PWMLOAD_HCSEL_MASK; - } -#endif /* FSL_FEATURE_FTM_HAS_HALFCYCLE_RELOAD */ - - base->PWMLOAD = reg; - - /* These reload points are used when counter is in up-down counting mode */ - reg = base->SYNC; - if (reloadPoints & kFTM_CntMax) - { - /* Reload when counter turns from up to down */ - reg |= FTM_SYNC_CNTMAX_MASK; - } - else - { - reg &= ~FTM_SYNC_CNTMAX_MASK; - } - - if (reloadPoints & kFTM_CntMin) - { - /* Reload when counter turns from down to up */ - reg |= FTM_SYNC_CNTMIN_MASK; - } - else - { - reg &= ~FTM_SYNC_CNTMIN_MASK; - } - base->SYNC = reg; -} - -status_t FTM_Init(FTM_Type *base, const ftm_config_t *config) -{ - assert(config); - - uint32_t reg; - - if (!(config->pwmSyncMode & - (FTM_SYNC_TRIG0_MASK | FTM_SYNC_TRIG1_MASK | FTM_SYNC_TRIG2_MASK | FTM_SYNC_SWSYNC_MASK))) - { - /* Invalid PWM sync mode */ - return kStatus_Fail; - } - -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) - /* Ungate the FTM clock*/ - CLOCK_EnableClock(s_ftmClocks[FTM_GetInstance(base)]); -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ - - /* Configure the fault mode, enable FTM mode and disable write protection */ - base->MODE = FTM_MODE_FAULTM(config->faultMode) | FTM_MODE_FTMEN_MASK | FTM_MODE_WPDIS_MASK; - - /* Configure the update mechanism for buffered registers */ - FTM_SetPwmSync(base, config->pwmSyncMode); - - /* Setup intermediate register reload points */ - FTM_SetReloadPoints(base, config->reloadPoints); - - /* Set the clock prescale factor */ - base->SC = FTM_SC_PS(config->prescale); - - /* Setup the counter operation */ - base->CONF = (FTM_CONF_BDMMODE(config->bdmMode) | FTM_CONF_GTBEEN(config->useGlobalTimeBase)); - - /* Initial state of channel output */ - base->OUTINIT = config->chnlInitState; - - /* Channel polarity */ - base->POL = config->chnlPolarity; - - /* Set the external trigger sources */ - base->EXTTRIG = config->extTriggers; -#if defined(FSL_FEATURE_FTM_HAS_RELOAD_INITIALIZATION_TRIGGER) && (FSL_FEATURE_FTM_HAS_RELOAD_INITIALIZATION_TRIGGER) - if (config->extTriggers & kFTM_ReloadInitTrigger) - { - base->CONF |= FTM_CONF_ITRIGR_MASK; - } - else - { - base->CONF &= ~FTM_CONF_ITRIGR_MASK; - } -#endif /* FSL_FEATURE_FTM_HAS_RELOAD_INITIALIZATION_TRIGGER */ - - /* FTM deadtime insertion control */ - base->DEADTIME = (0u | -#if defined(FSL_FEATURE_FTM_HAS_EXTENDED_DEADTIME_VALUE) && (FSL_FEATURE_FTM_HAS_EXTENDED_DEADTIME_VALUE) - /* Has extended deadtime value register) */ - FTM_DEADTIME_DTVALEX(config->deadTimeValue >> 6) | -#endif /* FSL_FEATURE_FTM_HAS_EXTENDED_DEADTIME_VALUE */ - FTM_DEADTIME_DTPS(config->deadTimePrescale) | - FTM_DEADTIME_DTVAL(config->deadTimeValue)); - - /* FTM fault filter value */ - reg = base->FLTCTRL; - reg &= ~FTM_FLTCTRL_FFVAL_MASK; - reg |= FTM_FLTCTRL_FFVAL(config->faultFilterValue); - base->FLTCTRL = reg; - - return kStatus_Success; -} - -void FTM_Deinit(FTM_Type *base) -{ - /* Set clock source to none to disable counter */ - base->SC &= ~(FTM_SC_CLKS_MASK); - -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) - /* Gate the FTM clock */ - CLOCK_DisableClock(s_ftmClocks[FTM_GetInstance(base)]); -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ -} - -void FTM_GetDefaultConfig(ftm_config_t *config) -{ - assert(config); - - /* Divide FTM clock by 1 */ - config->prescale = kFTM_Prescale_Divide_1; - /* FTM behavior in BDM mode */ - config->bdmMode = kFTM_BdmMode_0; - /* Software trigger will be used to update registers */ - config->pwmSyncMode = kFTM_SoftwareTrigger; - /* No intermediate register load */ - config->reloadPoints = 0; - /* Fault control disabled for all channels */ - config->faultMode = kFTM_Fault_Disable; - /* Disable the fault filter */ - config->faultFilterValue = 0; - /* Divide the system clock by 1 */ - config->deadTimePrescale = kFTM_Deadtime_Prescale_1; - /* No counts are inserted */ - config->deadTimeValue = 0; - /* No external trigger */ - config->extTriggers = 0; - /* Initialization value is 0 for all channels */ - config->chnlInitState = 0; - /* Active high polarity for all channels */ - config->chnlPolarity = 0; - /* Use internal FTM counter as timebase */ - config->useGlobalTimeBase = false; -} - -status_t FTM_SetupPwm(FTM_Type *base, - const ftm_chnl_pwm_signal_param_t *chnlParams, - uint8_t numOfChnls, - ftm_pwm_mode_t mode, - uint32_t pwmFreq_Hz, - uint32_t srcClock_Hz) -{ - assert(chnlParams); - assert(srcClock_Hz); - assert(pwmFreq_Hz); - assert(numOfChnls); - - uint32_t mod, reg; - uint32_t ftmClock = (srcClock_Hz / (1U << (base->SC & FTM_SC_PS_MASK))); - uint16_t cnv, cnvFirstEdge; - uint8_t i; - - switch (mode) - { - case kFTM_EdgeAlignedPwm: - case kFTM_CombinedPwm: - base->SC &= ~FTM_SC_CPWMS_MASK; - mod = (ftmClock / pwmFreq_Hz) - 1; - break; - case kFTM_CenterAlignedPwm: - base->SC |= FTM_SC_CPWMS_MASK; - mod = ftmClock / (pwmFreq_Hz * 2); - break; - default: - return kStatus_Fail; - } - - /* Return an error in case we overflow the registers, probably would require changing - * clock source to get the desired frequency */ - if (mod > 65535U) - { - return kStatus_Fail; - } - /* Set the PWM period */ - base->MOD = mod; - - /* Setup each FTM channel */ - for (i = 0; i < numOfChnls; i++) - { - /* Return error if requested dutycycle is greater than the max allowed */ - if (chnlParams->dutyCyclePercent > 100) - { - return kStatus_Fail; - } - - if ((mode == kFTM_EdgeAlignedPwm) || (mode == kFTM_CenterAlignedPwm)) - { - /* Clear the current mode and edge level bits */ - reg = base->CONTROLS[chnlParams->chnlNumber].CnSC; - reg &= ~(FTM_CnSC_MSA_MASK | FTM_CnSC_MSB_MASK | FTM_CnSC_ELSA_MASK | FTM_CnSC_ELSB_MASK); - - /* Setup the active level */ - reg |= (uint32_t)(chnlParams->level << FTM_CnSC_ELSA_SHIFT); - - /* Edge-aligned mode needs MSB to be 1, don't care for Center-aligned mode */ - reg |= FTM_CnSC_MSB(1U); - - /* Update the mode and edge level */ - base->CONTROLS[chnlParams->chnlNumber].CnSC = reg; - - if (chnlParams->dutyCyclePercent == 0) - { - /* Signal stays low */ - cnv = 0; - } - else - { - cnv = (mod * chnlParams->dutyCyclePercent) / 100; - /* For 100% duty cycle */ - if (cnv >= mod) - { - cnv = mod + 1; - } - } - - base->CONTROLS[chnlParams->chnlNumber].CnV = cnv; -#if defined(FSL_FEATURE_FTM_HAS_ENABLE_PWM_OUTPUT) && (FSL_FEATURE_FTM_HAS_ENABLE_PWM_OUTPUT) - /* Set to output mode */ - FTM_SetPwmOutputEnable(base, chnlParams->chnlNumber, true); -#endif - } - else - { - /* This check is added for combined mode as the channel number should be the pair number */ - if (chnlParams->chnlNumber >= (FSL_FEATURE_FTM_CHANNEL_COUNTn(base) / 2)) - { - return kStatus_Fail; - } - - /* Return error if requested value is greater than the max allowed */ - if (chnlParams->firstEdgeDelayPercent > 100) - { - return kStatus_Fail; - } - - /* Configure delay of the first edge */ - if (chnlParams->firstEdgeDelayPercent == 0) - { - /* No delay for the first edge */ - cnvFirstEdge = 0; - } - else - { - cnvFirstEdge = (mod * chnlParams->firstEdgeDelayPercent) / 100; - } - - /* Configure dutycycle */ - if (chnlParams->dutyCyclePercent == 0) - { - /* Signal stays low */ - cnv = 0; - cnvFirstEdge = 0; - } - else - { - cnv = (mod * chnlParams->dutyCyclePercent) / 100; - /* For 100% duty cycle */ - if (cnv >= mod) - { - cnv = mod + 1; - } - } - - /* Clear the current mode and edge level bits for channel n */ - reg = base->CONTROLS[chnlParams->chnlNumber * 2].CnSC; - reg &= ~(FTM_CnSC_MSA_MASK | FTM_CnSC_MSB_MASK | FTM_CnSC_ELSA_MASK | FTM_CnSC_ELSB_MASK); - - /* Setup the active level for channel n */ - reg |= (uint32_t)(chnlParams->level << FTM_CnSC_ELSA_SHIFT); - - /* Update the mode and edge level for channel n */ - base->CONTROLS[chnlParams->chnlNumber * 2].CnSC = reg; - - /* Clear the current mode and edge level bits for channel n + 1 */ - reg = base->CONTROLS[(chnlParams->chnlNumber * 2) + 1].CnSC; - reg &= ~(FTM_CnSC_MSA_MASK | FTM_CnSC_MSB_MASK | FTM_CnSC_ELSA_MASK | FTM_CnSC_ELSB_MASK); - - /* Setup the active level for channel n + 1 */ - reg |= (uint32_t)(chnlParams->level << FTM_CnSC_ELSA_SHIFT); - - /* Update the mode and edge level for channel n + 1*/ - base->CONTROLS[(chnlParams->chnlNumber * 2) + 1].CnSC = reg; - - /* Set the combine bit for the channel pair */ - base->COMBINE |= - (1U << (FTM_COMBINE_COMBINE0_SHIFT + (FTM_COMBINE_COMBINE1_SHIFT * chnlParams->chnlNumber))); - - /* Set the channel pair values */ - base->CONTROLS[chnlParams->chnlNumber * 2].CnV = cnvFirstEdge; - base->CONTROLS[(chnlParams->chnlNumber * 2) + 1].CnV = cnvFirstEdge + cnv; - -#if defined(FSL_FEATURE_FTM_HAS_ENABLE_PWM_OUTPUT) && (FSL_FEATURE_FTM_HAS_ENABLE_PWM_OUTPUT) - /* Set to output mode */ - FTM_SetPwmOutputEnable(base, (ftm_chnl_t)((uint8_t)chnlParams->chnlNumber * 2), true); - FTM_SetPwmOutputEnable(base, (ftm_chnl_t)((uint8_t)chnlParams->chnlNumber * 2 + 1), true); -#endif - } - chnlParams++; - } - - return kStatus_Success; -} - -void FTM_UpdatePwmDutycycle(FTM_Type *base, - ftm_chnl_t chnlNumber, - ftm_pwm_mode_t currentPwmMode, - uint8_t dutyCyclePercent) -{ - uint16_t cnv, cnvFirstEdge = 0, mod; - - mod = base->MOD; - if ((currentPwmMode == kFTM_EdgeAlignedPwm) || (currentPwmMode == kFTM_CenterAlignedPwm)) - { - cnv = (mod * dutyCyclePercent) / 100; - /* For 100% duty cycle */ - if (cnv >= mod) - { - cnv = mod + 1; - } - base->CONTROLS[chnlNumber].CnV = cnv; - } - else - { - /* This check is added for combined mode as the channel number should be the pair number */ - if (chnlNumber >= (FSL_FEATURE_FTM_CHANNEL_COUNTn(base) / 2)) - { - return; - } - - cnv = (mod * dutyCyclePercent) / 100; - cnvFirstEdge = base->CONTROLS[chnlNumber * 2].CnV; - /* For 100% duty cycle */ - if (cnv >= mod) - { - cnv = mod + 1; - } - base->CONTROLS[(chnlNumber * 2) + 1].CnV = cnvFirstEdge + cnv; - } -} - -void FTM_UpdateChnlEdgeLevelSelect(FTM_Type *base, ftm_chnl_t chnlNumber, uint8_t level) -{ - uint32_t reg = base->CONTROLS[chnlNumber].CnSC; - - /* Clear the field and write the new level value */ - reg &= ~(FTM_CnSC_ELSA_MASK | FTM_CnSC_ELSB_MASK); - reg |= ((uint32_t)level << FTM_CnSC_ELSA_SHIFT) & (FTM_CnSC_ELSA_MASK | FTM_CnSC_ELSB_MASK); - - base->CONTROLS[chnlNumber].CnSC = reg; -} - -void FTM_SetupInputCapture(FTM_Type *base, - ftm_chnl_t chnlNumber, - ftm_input_capture_edge_t captureMode, - uint32_t filterValue) -{ - uint32_t reg; - - /* Clear the combine bit for the channel pair */ - base->COMBINE &= ~(1U << (FTM_COMBINE_COMBINE0_SHIFT + (FTM_COMBINE_COMBINE1_SHIFT * (chnlNumber >> 1)))); - /* Clear the dual edge capture mode because it's it's higher priority */ - base->COMBINE &= ~(1U << (FTM_COMBINE_DECAPEN0_SHIFT + (FTM_COMBINE_COMBINE1_SHIFT * (chnlNumber >> 1)))); - /* Clear the quadrature decoder mode beacause it's higher priority */ - base->QDCTRL &= ~FTM_QDCTRL_QUADEN_MASK; - - reg = base->CONTROLS[chnlNumber].CnSC; - reg &= ~(FTM_CnSC_MSA_MASK | FTM_CnSC_MSB_MASK | FTM_CnSC_ELSA_MASK | FTM_CnSC_ELSB_MASK); - reg |= captureMode; - - /* Set the requested input capture mode */ - base->CONTROLS[chnlNumber].CnSC = reg; - /* Input filter available only for channels 0, 1, 2, 3 */ - if (chnlNumber < kFTM_Chnl_4) - { - reg = base->FILTER; - reg &= ~(FTM_FILTER_CH0FVAL_MASK << (FTM_FILTER_CH1FVAL_SHIFT * chnlNumber)); - reg |= (filterValue << (FTM_FILTER_CH1FVAL_SHIFT * chnlNumber)); - base->FILTER = reg; - } -#if defined(FSL_FEATURE_FTM_HAS_ENABLE_PWM_OUTPUT) && (FSL_FEATURE_FTM_HAS_ENABLE_PWM_OUTPUT) - /* Set to input mode */ - FTM_SetPwmOutputEnable(base, chnlNumber, false); -#endif -} - -void FTM_SetupOutputCompare(FTM_Type *base, - ftm_chnl_t chnlNumber, - ftm_output_compare_mode_t compareMode, - uint32_t compareValue) -{ - uint32_t reg; - - /* Clear the combine bit for the channel pair */ - base->COMBINE &= ~(1U << (FTM_COMBINE_COMBINE0_SHIFT + (FTM_COMBINE_COMBINE1_SHIFT * (chnlNumber >> 1)))); - /* Clear the dual edge capture mode because it's it's higher priority */ - base->COMBINE &= ~(1U << (FTM_COMBINE_DECAPEN0_SHIFT + (FTM_COMBINE_COMBINE1_SHIFT * (chnlNumber >> 1)))); - /* Clear the quadrature decoder mode beacause it's higher priority */ - base->QDCTRL &= ~FTM_QDCTRL_QUADEN_MASK; - - reg = base->CONTROLS[chnlNumber].CnSC; - reg &= ~(FTM_CnSC_MSA_MASK | FTM_CnSC_MSB_MASK | FTM_CnSC_ELSA_MASK | FTM_CnSC_ELSB_MASK); - reg |= compareMode; - /* Setup the channel output behaviour when a match occurs with the compare value */ - base->CONTROLS[chnlNumber].CnSC = reg; - - /* Set output on match to the requested level */ - base->CONTROLS[chnlNumber].CnV = compareValue; - -#if defined(FSL_FEATURE_FTM_HAS_ENABLE_PWM_OUTPUT) && (FSL_FEATURE_FTM_HAS_ENABLE_PWM_OUTPUT) - /* Set to output mode */ - FTM_SetPwmOutputEnable(base, chnlNumber, true); -#endif -} - -void FTM_SetupDualEdgeCapture(FTM_Type *base, - ftm_chnl_t chnlPairNumber, - const ftm_dual_edge_capture_param_t *edgeParam, - uint32_t filterValue) -{ - assert(edgeParam); - - uint32_t reg; - - reg = base->COMBINE; - /* Clear the combine bit for the channel pair */ - reg &= ~(1U << (FTM_COMBINE_COMBINE0_SHIFT + (FTM_COMBINE_COMBINE1_SHIFT * chnlPairNumber))); - /* Enable the DECAPEN bit */ - reg |= (1U << (FTM_COMBINE_DECAPEN0_SHIFT + (FTM_COMBINE_COMBINE1_SHIFT * chnlPairNumber))); - reg |= (1U << (FTM_COMBINE_DECAP0_SHIFT + (FTM_COMBINE_COMBINE1_SHIFT * chnlPairNumber))); - base->COMBINE = reg; - - /* Setup the edge detection from channel n and n + 1 */ - reg = base->CONTROLS[chnlPairNumber * 2].CnSC; - reg &= ~(FTM_CnSC_MSA_MASK | FTM_CnSC_MSB_MASK | FTM_CnSC_ELSA_MASK | FTM_CnSC_ELSB_MASK); - reg |= ((uint32_t)edgeParam->mode | (uint32_t)edgeParam->currChanEdgeMode); - base->CONTROLS[chnlPairNumber * 2].CnSC = reg; - - reg = base->CONTROLS[(chnlPairNumber * 2) + 1].CnSC; - reg &= ~(FTM_CnSC_MSA_MASK | FTM_CnSC_MSB_MASK | FTM_CnSC_ELSA_MASK | FTM_CnSC_ELSB_MASK); - reg |= ((uint32_t)edgeParam->mode | (uint32_t)edgeParam->nextChanEdgeMode); - base->CONTROLS[(chnlPairNumber * 2) + 1].CnSC = reg; - - /* Input filter available only for channels 0, 1, 2, 3 */ - if (chnlPairNumber < kFTM_Chnl_4) - { - reg = base->FILTER; - reg &= ~(FTM_FILTER_CH0FVAL_MASK << (FTM_FILTER_CH1FVAL_SHIFT * chnlPairNumber)); - reg |= (filterValue << (FTM_FILTER_CH1FVAL_SHIFT * chnlPairNumber)); - base->FILTER = reg; - } - -#if defined(FSL_FEATURE_FTM_HAS_ENABLE_PWM_OUTPUT) && (FSL_FEATURE_FTM_HAS_ENABLE_PWM_OUTPUT) - /* Set to input mode */ - FTM_SetPwmOutputEnable(base, chnlPairNumber, false); -#endif -} - -void FTM_SetupQuadDecode(FTM_Type *base, - const ftm_phase_params_t *phaseAParams, - const ftm_phase_params_t *phaseBParams, - ftm_quad_decode_mode_t quadMode) -{ - assert(phaseAParams); - assert(phaseBParams); - - uint32_t reg; - - /* Set Phase A filter value if phase filter is enabled */ - if (phaseAParams->enablePhaseFilter) - { - reg = base->FILTER; - reg &= ~(FTM_FILTER_CH0FVAL_MASK); - reg |= FTM_FILTER_CH0FVAL(phaseAParams->phaseFilterVal); - base->FILTER = reg; - } - - /* Set Phase B filter value if phase filter is enabled */ - if (phaseBParams->enablePhaseFilter) - { - reg = base->FILTER; - reg &= ~(FTM_FILTER_CH1FVAL_MASK); - reg |= FTM_FILTER_CH1FVAL(phaseBParams->phaseFilterVal); - base->FILTER = reg; - } - - /* Set Quadrature decode properties */ - reg = base->QDCTRL; - reg &= ~(FTM_QDCTRL_QUADMODE_MASK | FTM_QDCTRL_PHAFLTREN_MASK | FTM_QDCTRL_PHBFLTREN_MASK | FTM_QDCTRL_PHAPOL_MASK | - FTM_QDCTRL_PHBPOL_MASK); - reg |= (FTM_QDCTRL_QUADMODE(quadMode) | FTM_QDCTRL_PHAFLTREN(phaseAParams->enablePhaseFilter) | - FTM_QDCTRL_PHBFLTREN(phaseBParams->enablePhaseFilter) | FTM_QDCTRL_PHAPOL(phaseAParams->phasePolarity) | - FTM_QDCTRL_PHBPOL(phaseBParams->phasePolarity)); - base->QDCTRL = reg; - /* Enable Quad decode */ - base->QDCTRL |= FTM_QDCTRL_QUADEN_MASK; -} - -void FTM_SetupFault(FTM_Type *base, ftm_fault_input_t faultNumber, const ftm_fault_param_t *faultParams) -{ - assert(faultParams); - - uint32_t reg; - - reg = base->FLTCTRL; - if (faultParams->enableFaultInput) - { - /* Enable the fault input */ - reg |= (FTM_FLTCTRL_FAULT0EN_MASK << faultNumber); - } - else - { - /* Disable the fault input */ - reg &= ~(FTM_FLTCTRL_FAULT0EN_MASK << faultNumber); - } - - if (faultParams->useFaultFilter) - { - /* Enable the fault filter */ - reg |= (FTM_FLTCTRL_FFLTR0EN_MASK << (FTM_FLTCTRL_FFLTR0EN_SHIFT + faultNumber)); - } - else - { - /* Disable the fault filter */ - reg &= ~(FTM_FLTCTRL_FFLTR0EN_MASK << (FTM_FLTCTRL_FFLTR0EN_SHIFT + faultNumber)); - } - base->FLTCTRL = reg; - - if (faultParams->faultLevel) - { - /* Active low polarity for the fault input pin */ - base->FLTPOL |= (1U << faultNumber); - } - else - { - /* Active high polarity for the fault input pin */ - base->FLTPOL &= ~(1U << faultNumber); - } -} - -void FTM_EnableInterrupts(FTM_Type *base, uint32_t mask) -{ - uint32_t chnlInts = (mask & 0xFFU); - uint8_t chnlNumber = 0; - - /* Enable the timer overflow interrupt */ - if (mask & kFTM_TimeOverflowInterruptEnable) - { - base->SC |= FTM_SC_TOIE_MASK; - } - - /* Enable the fault interrupt */ - if (mask & kFTM_FaultInterruptEnable) - { - base->MODE |= FTM_MODE_FAULTIE_MASK; - } - -#if defined(FSL_FEATURE_FTM_HAS_RELOAD_INTERRUPT) && (FSL_FEATURE_FTM_HAS_RELOAD_INTERRUPT) - /* Enable the reload interrupt available only on certain SoC's */ - if (mask & kFTM_ReloadInterruptEnable) - { - base->SC |= FTM_SC_RIE_MASK; - } -#endif - - /* Enable the channel interrupts */ - while (chnlInts) - { - if (chnlInts & 0x1) - { - base->CONTROLS[chnlNumber].CnSC |= FTM_CnSC_CHIE_MASK; - } - chnlNumber++; - chnlInts = chnlInts >> 1U; - } -} - -void FTM_DisableInterrupts(FTM_Type *base, uint32_t mask) -{ - uint32_t chnlInts = (mask & 0xFF); - uint8_t chnlNumber = 0; - - /* Disable the timer overflow interrupt */ - if (mask & kFTM_TimeOverflowInterruptEnable) - { - base->SC &= ~FTM_SC_TOIE_MASK; - } - /* Disable the fault interrupt */ - if (mask & kFTM_FaultInterruptEnable) - { - base->MODE &= ~FTM_MODE_FAULTIE_MASK; - } - -#if defined(FSL_FEATURE_FTM_HAS_RELOAD_INTERRUPT) && (FSL_FEATURE_FTM_HAS_RELOAD_INTERRUPT) - /* Disable the reload interrupt available only on certain SoC's */ - if (mask & kFTM_ReloadInterruptEnable) - { - base->SC &= ~FTM_SC_RIE_MASK; - } -#endif - - /* Disable the channel interrupts */ - while (chnlInts) - { - if (chnlInts & 0x1) - { - base->CONTROLS[chnlNumber].CnSC &= ~FTM_CnSC_CHIE_MASK; - } - chnlNumber++; - chnlInts = chnlInts >> 1U; - } -} - -uint32_t FTM_GetEnabledInterrupts(FTM_Type *base) -{ - uint32_t enabledInterrupts = 0; - int8_t chnlCount = FSL_FEATURE_FTM_CHANNEL_COUNTn(base); - - /* The CHANNEL_COUNT macro returns -1 if it cannot match the FTM instance */ - assert(chnlCount != -1); - - /* Check if timer overflow interrupt is enabled */ - if (base->SC & FTM_SC_TOIE_MASK) - { - enabledInterrupts |= kFTM_TimeOverflowInterruptEnable; - } - /* Check if fault interrupt is enabled */ - if (base->MODE & FTM_MODE_FAULTIE_MASK) - { - enabledInterrupts |= kFTM_FaultInterruptEnable; - } - -#if defined(FSL_FEATURE_FTM_HAS_RELOAD_INTERRUPT) && (FSL_FEATURE_FTM_HAS_RELOAD_INTERRUPT) - /* Check if the reload interrupt is enabled */ - if (base->SC & FTM_SC_RIE_MASK) - { - enabledInterrupts |= kFTM_ReloadInterruptEnable; - } -#endif - - /* Check if the channel interrupts are enabled */ - while (chnlCount > 0) - { - chnlCount--; - if (base->CONTROLS[chnlCount].CnSC & FTM_CnSC_CHIE_MASK) - { - enabledInterrupts |= (1U << chnlCount); - } - } - - return enabledInterrupts; -} - -uint32_t FTM_GetStatusFlags(FTM_Type *base) -{ - uint32_t statusFlags = 0; - - /* Check the timer flag */ - if (base->SC & FTM_SC_TOF_MASK) - { - statusFlags |= kFTM_TimeOverflowFlag; - } - /* Check fault flag */ - if (base->FMS & FTM_FMS_FAULTF_MASK) - { - statusFlags |= kFTM_FaultFlag; - } - /* Check channel trigger flag */ - if (base->EXTTRIG & FTM_EXTTRIG_TRIGF_MASK) - { - statusFlags |= kFTM_ChnlTriggerFlag; - } -#if defined(FSL_FEATURE_FTM_HAS_RELOAD_INTERRUPT) && (FSL_FEATURE_FTM_HAS_RELOAD_INTERRUPT) - /* Check reload flag */ - if (base->SC & FTM_SC_RF_MASK) - { - statusFlags |= kFTM_ReloadFlag; - } -#endif - - /* Lower 8 bits contain the channel status flags */ - statusFlags |= (base->STATUS & 0xFFU); - - return statusFlags; -} - -void FTM_ClearStatusFlags(FTM_Type *base, uint32_t mask) -{ - /* Clear the timer overflow flag by writing a 0 to the bit while it is set */ - if (mask & kFTM_TimeOverflowFlag) - { - base->SC &= ~FTM_SC_TOF_MASK; - } - /* Clear fault flag by writing a 0 to the bit while it is set */ - if (mask & kFTM_FaultFlag) - { - base->FMS &= ~FTM_FMS_FAULTF_MASK; - } - /* Clear channel trigger flag */ - if (mask & kFTM_ChnlTriggerFlag) - { - base->EXTTRIG &= ~FTM_EXTTRIG_TRIGF_MASK; - } - -#if defined(FSL_FEATURE_FTM_HAS_RELOAD_INTERRUPT) && (FSL_FEATURE_FTM_HAS_RELOAD_INTERRUPT) - /* Check reload flag by writing a 0 to the bit while it is set */ - if (mask & kFTM_ReloadFlag) - { - base->SC &= ~FTM_SC_RF_MASK; - } -#endif - /* Clear the channel status flags by writing a 0 to the bit */ - base->STATUS &= ~(mask & 0xFFU); -} diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_ftm.h b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_ftm.h deleted file mode 100644 index 8db81a633ac..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_ftm.h +++ /dev/null @@ -1,973 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -#ifndef _FSL_FTM_H_ -#define _FSL_FTM_H_ - -#include "fsl_common.h" - -/*! - * @addtogroup ftm - * @{ - */ - - -/******************************************************************************* - * Definitions - ******************************************************************************/ - -/*! @name Driver version */ -/*@{*/ -#define FSL_FTM_DRIVER_VERSION (MAKE_VERSION(2, 0, 2)) /*!< Version 2.0.2 */ - /*@}*/ - -/*! - * @brief List of FTM channels - * @note Actual number of available channels is SoC dependent - */ -typedef enum _ftm_chnl -{ - kFTM_Chnl_0 = 0U, /*!< FTM channel number 0*/ - kFTM_Chnl_1, /*!< FTM channel number 1 */ - kFTM_Chnl_2, /*!< FTM channel number 2 */ - kFTM_Chnl_3, /*!< FTM channel number 3 */ - kFTM_Chnl_4, /*!< FTM channel number 4 */ - kFTM_Chnl_5, /*!< FTM channel number 5 */ - kFTM_Chnl_6, /*!< FTM channel number 6 */ - kFTM_Chnl_7 /*!< FTM channel number 7 */ -} ftm_chnl_t; - -/*! @brief List of FTM faults */ -typedef enum _ftm_fault_input -{ - kFTM_Fault_0 = 0U, /*!< FTM fault 0 input pin */ - kFTM_Fault_1, /*!< FTM fault 1 input pin */ - kFTM_Fault_2, /*!< FTM fault 2 input pin */ - kFTM_Fault_3 /*!< FTM fault 3 input pin */ -} ftm_fault_input_t; - -/*! @brief FTM PWM operation modes */ -typedef enum _ftm_pwm_mode -{ - kFTM_EdgeAlignedPwm = 0U, /*!< Edge-aligned PWM */ - kFTM_CenterAlignedPwm, /*!< Center-aligned PWM */ - kFTM_CombinedPwm /*!< Combined PWM */ -} ftm_pwm_mode_t; - -/*! @brief FTM PWM output pulse mode: high-true, low-true or no output */ -typedef enum _ftm_pwm_level_select -{ - kFTM_NoPwmSignal = 0U, /*!< No PWM output on pin */ - kFTM_LowTrue, /*!< Low true pulses */ - kFTM_HighTrue /*!< High true pulses */ -} ftm_pwm_level_select_t; - -/*! @brief Options to configure a FTM channel's PWM signal */ -typedef struct _ftm_chnl_pwm_signal_param -{ - ftm_chnl_t chnlNumber; /*!< The channel/channel pair number. - In combined mode, this represents the channel pair number. */ - ftm_pwm_level_select_t level; /*!< PWM output active level select. */ - uint8_t dutyCyclePercent; /*!< PWM pulse width, value should be between 0 to 100 - 0 = inactive signal(0% duty cycle)... - 100 = always active signal (100% duty cycle).*/ - uint8_t firstEdgeDelayPercent; /*!< Used only in combined PWM mode to generate an asymmetrical PWM. - Specifies the delay to the first edge in a PWM period. - If unsure leave as 0; Should be specified as a - percentage of the PWM period */ -} ftm_chnl_pwm_signal_param_t; - -/*! @brief FlexTimer output compare mode */ -typedef enum _ftm_output_compare_mode -{ - kFTM_NoOutputSignal = (1U << FTM_CnSC_MSA_SHIFT), /*!< No channel output when counter reaches CnV */ - kFTM_ToggleOnMatch = ((1U << FTM_CnSC_MSA_SHIFT) | (1U << FTM_CnSC_ELSA_SHIFT)), /*!< Toggle output */ - kFTM_ClearOnMatch = ((1U << FTM_CnSC_MSA_SHIFT) | (2U << FTM_CnSC_ELSA_SHIFT)), /*!< Clear output */ - kFTM_SetOnMatch = ((1U << FTM_CnSC_MSA_SHIFT) | (3U << FTM_CnSC_ELSA_SHIFT)) /*!< Set output */ -} ftm_output_compare_mode_t; - -/*! @brief FlexTimer input capture edge */ -typedef enum _ftm_input_capture_edge -{ - kFTM_RisingEdge = (1U << FTM_CnSC_ELSA_SHIFT), /*!< Capture on rising edge only*/ - kFTM_FallingEdge = (2U << FTM_CnSC_ELSA_SHIFT), /*!< Capture on falling edge only*/ - kFTM_RiseAndFallEdge = (3U << FTM_CnSC_ELSA_SHIFT) /*!< Capture on rising or falling edge */ -} ftm_input_capture_edge_t; - -/*! @brief FlexTimer dual edge capture modes */ -typedef enum _ftm_dual_edge_capture_mode -{ - kFTM_OneShot = 0U, /*!< One-shot capture mode */ - kFTM_Continuous = (1U << FTM_CnSC_MSA_SHIFT) /*!< Continuous capture mode */ -} ftm_dual_edge_capture_mode_t; - -/*! @brief FlexTimer dual edge capture parameters */ -typedef struct _ftm_dual_edge_capture_param -{ - ftm_dual_edge_capture_mode_t mode; /*!< Dual Edge Capture mode */ - ftm_input_capture_edge_t currChanEdgeMode; /*!< Input capture edge select for channel n */ - ftm_input_capture_edge_t nextChanEdgeMode; /*!< Input capture edge select for channel n+1 */ -} ftm_dual_edge_capture_param_t; - -/*! @brief FlexTimer quadrature decode modes */ -typedef enum _ftm_quad_decode_mode -{ - kFTM_QuadPhaseEncode = 0U, /*!< Phase A and Phase B encoding mode */ - kFTM_QuadCountAndDir /*!< Count and direction encoding mode */ -} ftm_quad_decode_mode_t; - -/*! @brief FlexTimer quadrature phase polarities */ -typedef enum _ftm_phase_polarity -{ - kFTM_QuadPhaseNormal = 0U, /*!< Phase input signal is not inverted */ - kFTM_QuadPhaseInvert /*!< Phase input signal is inverted */ -} ftm_phase_polarity_t; - -/*! @brief FlexTimer quadrature decode phase parameters */ -typedef struct _ftm_phase_param -{ - bool enablePhaseFilter; /*!< True: enable phase filter; false: disable filter */ - uint32_t phaseFilterVal; /*!< Filter value, used only if phase filter is enabled */ - ftm_phase_polarity_t phasePolarity; /*!< Phase polarity */ -} ftm_phase_params_t; - -/*! @brief Structure is used to hold the parameters to configure a FTM fault */ -typedef struct _ftm_fault_param -{ - bool enableFaultInput; /*!< True: Fault input is enabled; false: Fault input is disabled */ - bool faultLevel; /*!< True: Fault polarity is active low; in other words, '0' indicates a fault; - False: Fault polarity is active high */ - bool useFaultFilter; /*!< True: Use the filtered fault signal; - False: Use the direct path from fault input */ -} ftm_fault_param_t; - -/*! @brief FlexTimer pre-scaler factor for the dead time insertion*/ -typedef enum _ftm_deadtime_prescale -{ - kFTM_Deadtime_Prescale_1 = 1U, /*!< Divide by 1 */ - kFTM_Deadtime_Prescale_4, /*!< Divide by 4 */ - kFTM_Deadtime_Prescale_16 /*!< Divide by 16 */ -} ftm_deadtime_prescale_t; - -/*! @brief FlexTimer clock source selection*/ -typedef enum _ftm_clock_source -{ - kFTM_SystemClock = 1U, /*!< System clock selected */ - kFTM_FixedClock, /*!< Fixed frequency clock */ - kFTM_ExternalClock /*!< External clock */ -} ftm_clock_source_t; - -/*! @brief FlexTimer pre-scaler factor selection for the clock source*/ -typedef enum _ftm_clock_prescale -{ - kFTM_Prescale_Divide_1 = 0U, /*!< Divide by 1 */ - kFTM_Prescale_Divide_2, /*!< Divide by 2 */ - kFTM_Prescale_Divide_4, /*!< Divide by 4 */ - kFTM_Prescale_Divide_8, /*!< Divide by 8 */ - kFTM_Prescale_Divide_16, /*!< Divide by 16 */ - kFTM_Prescale_Divide_32, /*!< Divide by 32 */ - kFTM_Prescale_Divide_64, /*!< Divide by 64 */ - kFTM_Prescale_Divide_128 /*!< Divide by 128 */ -} ftm_clock_prescale_t; - -/*! @brief Options for the FlexTimer behaviour in BDM Mode */ -typedef enum _ftm_bdm_mode -{ - kFTM_BdmMode_0 = 0U, - /*!< FTM counter stopped, CH(n)F bit can be set, FTM channels in functional mode, writes to MOD,CNTIN and C(n)V - registers bypass the register buffers */ - kFTM_BdmMode_1, - /*!< FTM counter stopped, CH(n)F bit is not set, FTM channels outputs are forced to their safe value , writes to - MOD,CNTIN and C(n)V registers bypass the register buffers */ - kFTM_BdmMode_2, - /*!< FTM counter stopped, CH(n)F bit is not set, FTM channels outputs are frozen when chip enters in BDM mode, - writes to MOD,CNTIN and C(n)V registers bypass the register buffers */ - kFTM_BdmMode_3 - /*!< FTM counter in functional mode, CH(n)F bit can be set, FTM channels in functional mode, writes to MOD,CNTIN and - C(n)V registers is in fully functional mode */ -} ftm_bdm_mode_t; - -/*! @brief Options for the FTM fault control mode */ -typedef enum _ftm_fault_mode -{ - kFTM_Fault_Disable = 0U, /*!< Fault control is disabled for all channels */ - kFTM_Fault_EvenChnls, /*!< Enabled for even channels only(0,2,4,6) with manual fault clearing */ - kFTM_Fault_AllChnlsMan, /*!< Enabled for all channels with manual fault clearing */ - kFTM_Fault_AllChnlsAuto /*!< Enabled for all channels with automatic fault clearing */ -} ftm_fault_mode_t; - -/*! - * @brief FTM external trigger options - * @note Actual available external trigger sources are SoC-specific - */ -typedef enum _ftm_external_trigger -{ - kFTM_Chnl0Trigger = (1U << 4), /*!< Generate trigger when counter equals chnl 0 CnV reg */ - kFTM_Chnl1Trigger = (1U << 5), /*!< Generate trigger when counter equals chnl 1 CnV reg */ - kFTM_Chnl2Trigger = (1U << 0), /*!< Generate trigger when counter equals chnl 2 CnV reg */ - kFTM_Chnl3Trigger = (1U << 1), /*!< Generate trigger when counter equals chnl 3 CnV reg */ - kFTM_Chnl4Trigger = (1U << 2), /*!< Generate trigger when counter equals chnl 4 CnV reg */ - kFTM_Chnl5Trigger = (1U << 3), /*!< Generate trigger when counter equals chnl 5 CnV reg */ - kFTM_Chnl6Trigger = - (1U << 8), /*!< Available on certain SoC's, generate trigger when counter equals chnl 6 CnV reg */ - kFTM_Chnl7Trigger = - (1U << 9), /*!< Available on certain SoC's, generate trigger when counter equals chnl 7 CnV reg */ - kFTM_InitTrigger = (1U << 6), /*!< Generate Trigger when counter is updated with CNTIN */ - kFTM_ReloadInitTrigger = (1U << 7) /*!< Available on certain SoC's, trigger on reload point */ -} ftm_external_trigger_t; - -/*! @brief FlexTimer PWM sync options to update registers with buffer */ -typedef enum _ftm_pwm_sync_method -{ - kFTM_SoftwareTrigger = FTM_SYNC_SWSYNC_MASK, /*!< Software triggers PWM sync */ - kFTM_HardwareTrigger_0 = FTM_SYNC_TRIG0_MASK, /*!< Hardware trigger 0 causes PWM sync */ - kFTM_HardwareTrigger_1 = FTM_SYNC_TRIG1_MASK, /*!< Hardware trigger 1 causes PWM sync */ - kFTM_HardwareTrigger_2 = FTM_SYNC_TRIG2_MASK /*!< Hardware trigger 2 causes PWM sync */ -} ftm_pwm_sync_method_t; - -/*! - * @brief FTM options available as loading point for register reload - * @note Actual available reload points are SoC-specific - */ -typedef enum _ftm_reload_point -{ - kFTM_Chnl0Match = (1U << 0), /*!< Channel 0 match included as a reload point */ - kFTM_Chnl1Match = (1U << 1), /*!< Channel 1 match included as a reload point */ - kFTM_Chnl2Match = (1U << 2), /*!< Channel 2 match included as a reload point */ - kFTM_Chnl3Match = (1U << 3), /*!< Channel 3 match included as a reload point */ - kFTM_Chnl4Match = (1U << 4), /*!< Channel 4 match included as a reload point */ - kFTM_Chnl5Match = (1U << 5), /*!< Channel 5 match included as a reload point */ - kFTM_Chnl6Match = (1U << 6), /*!< Channel 6 match included as a reload point */ - kFTM_Chnl7Match = (1U << 7), /*!< Channel 7 match included as a reload point */ - kFTM_CntMax = (1U << 8), /*!< Use in up-down count mode only, reload when counter reaches the maximum value */ - kFTM_CntMin = (1U << 9), /*!< Use in up-down count mode only, reload when counter reaches the minimum value */ - kFTM_HalfCycMatch = (1U << 10) /*!< Available on certain SoC's, half cycle match reload point */ -} ftm_reload_point_t; - -/*! - * @brief List of FTM interrupts - * @note Actual available interrupts are SoC-specific - */ -typedef enum _ftm_interrupt_enable -{ - kFTM_Chnl0InterruptEnable = (1U << 0), /*!< Channel 0 interrupt */ - kFTM_Chnl1InterruptEnable = (1U << 1), /*!< Channel 1 interrupt */ - kFTM_Chnl2InterruptEnable = (1U << 2), /*!< Channel 2 interrupt */ - kFTM_Chnl3InterruptEnable = (1U << 3), /*!< Channel 3 interrupt */ - kFTM_Chnl4InterruptEnable = (1U << 4), /*!< Channel 4 interrupt */ - kFTM_Chnl5InterruptEnable = (1U << 5), /*!< Channel 5 interrupt */ - kFTM_Chnl6InterruptEnable = (1U << 6), /*!< Channel 6 interrupt */ - kFTM_Chnl7InterruptEnable = (1U << 7), /*!< Channel 7 interrupt */ - kFTM_FaultInterruptEnable = (1U << 8), /*!< Fault interrupt */ - kFTM_TimeOverflowInterruptEnable = (1U << 9), /*!< Time overflow interrupt */ - kFTM_ReloadInterruptEnable = (1U << 10) /*!< Reload interrupt; Available only on certain SoC's */ -} ftm_interrupt_enable_t; - -/*! - * @brief List of FTM flags - * @note Actual available flags are SoC-specific - */ -typedef enum _ftm_status_flags -{ - kFTM_Chnl0Flag = (1U << 0), /*!< Channel 0 Flag */ - kFTM_Chnl1Flag = (1U << 1), /*!< Channel 1 Flag */ - kFTM_Chnl2Flag = (1U << 2), /*!< Channel 2 Flag */ - kFTM_Chnl3Flag = (1U << 3), /*!< Channel 3 Flag */ - kFTM_Chnl4Flag = (1U << 4), /*!< Channel 4 Flag */ - kFTM_Chnl5Flag = (1U << 5), /*!< Channel 5 Flag */ - kFTM_Chnl6Flag = (1U << 6), /*!< Channel 6 Flag */ - kFTM_Chnl7Flag = (1U << 7), /*!< Channel 7 Flag */ - kFTM_FaultFlag = (1U << 8), /*!< Fault Flag */ - kFTM_TimeOverflowFlag = (1U << 9), /*!< Time overflow Flag */ - kFTM_ChnlTriggerFlag = (1U << 10), /*!< Channel trigger Flag */ - kFTM_ReloadFlag = (1U << 11) /*!< Reload Flag; Available only on certain SoC's */ -} ftm_status_flags_t; - -/*! - * @brief List of FTM Quad Decoder flags. - */ -enum _ftm_quad_decoder_flags -{ - kFTM_QuadDecoderCountingIncreaseFlag = FTM_QDCTRL_QUADIR_MASK, /*!< Counting direction is increasing (FTM counter - increment), or the direction is decreasing. */ - kFTM_QuadDecoderCountingOverflowOnTopFlag = FTM_QDCTRL_TOFDIR_MASK, /*!< Indicates if the TOF bit was set on the top - or the bottom of counting. */ -}; - -/*! - * @brief FTM configuration structure - * - * This structure holds the configuration settings for the FTM peripheral. To initialize this - * structure to reasonable defaults, call the FTM_GetDefaultConfig() function and pass a - * pointer to the configuration structure instance. - * - * The configuration structure can be made constant so as to reside in flash. - */ -typedef struct _ftm_config -{ - ftm_clock_prescale_t prescale; /*!< FTM clock prescale value */ - ftm_bdm_mode_t bdmMode; /*!< FTM behavior in BDM mode */ - uint32_t pwmSyncMode; /*!< Synchronization methods to use to update buffered registers; Multiple - update modes can be used by providing an OR'ed list of options - available in enumeration ::ftm_pwm_sync_method_t. */ - uint32_t reloadPoints; /*!< FTM reload points; When using this, the PWM - synchronization is not required. Multiple reload points can be used by providing - an OR'ed list of options available in - enumeration ::ftm_reload_point_t. */ - ftm_fault_mode_t faultMode; /*!< FTM fault control mode */ - uint8_t faultFilterValue; /*!< Fault input filter value */ - ftm_deadtime_prescale_t deadTimePrescale; /*!< The dead time prescalar value */ - uint32_t deadTimeValue; /*!< The dead time value - deadTimeValue's available range is 0-1023 when register has DTVALEX, - otherwise its available range is 0-63. */ - uint32_t extTriggers; /*!< External triggers to enable. Multiple trigger sources can be - enabled by providing an OR'ed list of options available in - enumeration ::ftm_external_trigger_t. */ - uint8_t chnlInitState; /*!< Defines the initialization value of the channels in OUTINT register */ - uint8_t chnlPolarity; /*!< Defines the output polarity of the channels in POL register */ - bool useGlobalTimeBase; /*!< True: Use of an external global time base is enabled; - False: disabled */ -} ftm_config_t; - -/******************************************************************************* - * API - ******************************************************************************/ - -#if defined(__cplusplus) -extern "C" { -#endif - -/*! - * @name Initialization and deinitialization - * @{ - */ - -/*! - * @brief Ungates the FTM clock and configures the peripheral for basic operation. - * - * @note This API should be called at the beginning of the application which is using the FTM driver. - * - * @param base FTM peripheral base address - * @param config Pointer to the user configuration structure. - * - * @return kStatus_Success indicates success; Else indicates failure. - */ -status_t FTM_Init(FTM_Type *base, const ftm_config_t *config); - -/*! - * @brief Gates the FTM clock. - * - * @param base FTM peripheral base address - */ -void FTM_Deinit(FTM_Type *base); - -/*! - * @brief Fills in the FTM configuration structure with the default settings. - * - * The default values are: - * @code - * config->prescale = kFTM_Prescale_Divide_1; - * config->bdmMode = kFTM_BdmMode_0; - * config->pwmSyncMode = kFTM_SoftwareTrigger; - * config->reloadPoints = 0; - * config->faultMode = kFTM_Fault_Disable; - * config->faultFilterValue = 0; - * config->deadTimePrescale = kFTM_Deadtime_Prescale_1; - * config->deadTimeValue = 0; - * config->extTriggers = 0; - * config->chnlInitState = 0; - * config->chnlPolarity = 0; - * config->useGlobalTimeBase = false; - * @endcode - * @param config Pointer to the user configuration structure. - */ -void FTM_GetDefaultConfig(ftm_config_t *config); - -/*! @}*/ - -/*! - * @name Channel mode operations - * @{ - */ - -/*! - * @brief Configures the PWM signal parameters. - * - * Call this function to configure the PWM signal period, mode, duty cycle, and edge. Use this - * function to configure all FTM channels that are used to output a PWM signal. - * - * @param base FTM peripheral base address - * @param chnlParams Array of PWM channel parameters to configure the channel(s) - * @param numOfChnls Number of channels to configure; This should be the size of the array passed in - * @param mode PWM operation mode, options available in enumeration ::ftm_pwm_mode_t - * @param pwmFreq_Hz PWM signal frequency in Hz - * @param srcClock_Hz FTM counter clock in Hz - * - * @return kStatus_Success if the PWM setup was successful - * kStatus_Error on failure - */ -status_t FTM_SetupPwm(FTM_Type *base, - const ftm_chnl_pwm_signal_param_t *chnlParams, - uint8_t numOfChnls, - ftm_pwm_mode_t mode, - uint32_t pwmFreq_Hz, - uint32_t srcClock_Hz); - -/*! - * @brief Updates the duty cycle of an active PWM signal. - * - * @param base FTM peripheral base address - * @param chnlNumber The channel/channel pair number. In combined mode, this represents - * the channel pair number - * @param currentPwmMode The current PWM mode set during PWM setup - * @param dutyCyclePercent New PWM pulse width; The value should be between 0 to 100 - * 0=inactive signal(0% duty cycle)... - * 100=active signal (100% duty cycle) - */ -void FTM_UpdatePwmDutycycle(FTM_Type *base, - ftm_chnl_t chnlNumber, - ftm_pwm_mode_t currentPwmMode, - uint8_t dutyCyclePercent); - -/*! - * @brief Updates the edge level selection for a channel. - * - * @param base FTM peripheral base address - * @param chnlNumber The channel number - * @param level The level to be set to the ELSnB:ELSnA field; Valid values are 00, 01, 10, 11. - * See the Kinetis SoC reference manual for details about this field. - */ -void FTM_UpdateChnlEdgeLevelSelect(FTM_Type *base, ftm_chnl_t chnlNumber, uint8_t level); - -/*! - * @brief Enables capturing an input signal on the channel using the function parameters. - * - * When the edge specified in the captureMode argument occurs on the channel, the FTM counter is - * captured into the CnV register. The user has to read the CnV register separately to get this - * value. The filter function is disabled if the filterVal argument passed in is 0. The filter - * function is available only for channels 0, 1, 2, 3. - * - * @param base FTM peripheral base address - * @param chnlNumber The channel number - * @param captureMode Specifies which edge to capture - * @param filterValue Filter value, specify 0 to disable filter. Available only for channels 0-3. - */ -void FTM_SetupInputCapture(FTM_Type *base, - ftm_chnl_t chnlNumber, - ftm_input_capture_edge_t captureMode, - uint32_t filterValue); - -/*! - * @brief Configures the FTM to generate timed pulses. - * - * When the FTM counter matches the value of compareVal argument (this is written into CnV reg), - * the channel output is changed based on what is specified in the compareMode argument. - * - * @param base FTM peripheral base address - * @param chnlNumber The channel number - * @param compareMode Action to take on the channel output when the compare condition is met - * @param compareValue Value to be programmed in the CnV register. - */ -void FTM_SetupOutputCompare(FTM_Type *base, - ftm_chnl_t chnlNumber, - ftm_output_compare_mode_t compareMode, - uint32_t compareValue); - -/*! - * @brief Configures the dual edge capture mode of the FTM. - * - * This function sets up the dual edge capture mode on a channel pair. The capture edge for the - * channel pair and the capture mode (one-shot or continuous) is specified in the parameter - * argument. The filter function is disabled if the filterVal argument passed is zero. The filter - * function is available only on channels 0 and 2. The user has to read the channel CnV registers - * separately to get the capture values. - * - * @param base FTM peripheral base address - * @param chnlPairNumber The FTM channel pair number; options are 0, 1, 2, 3 - * @param edgeParam Sets up the dual edge capture function - * @param filterValue Filter value, specify 0 to disable filter. Available only for channel pair 0 and 1. - */ -void FTM_SetupDualEdgeCapture(FTM_Type *base, - ftm_chnl_t chnlPairNumber, - const ftm_dual_edge_capture_param_t *edgeParam, - uint32_t filterValue); - -/*! @}*/ - -/*! - * @brief Sets up the working of the FTM fault protection. - * - * FTM can have up to 4 fault inputs. This function sets up fault parameters, fault level, and a filter. - * - * @param base FTM peripheral base address - * @param faultNumber FTM fault to configure. - * @param faultParams Parameters passed in to set up the fault - */ -void FTM_SetupFault(FTM_Type *base, ftm_fault_input_t faultNumber, const ftm_fault_param_t *faultParams); - -/*! - * @name Interrupt Interface - * @{ - */ - -/*! - * @brief Enables the selected FTM interrupts. - * - * @param base FTM peripheral base address - * @param mask The interrupts to enable. This is a logical OR of members of the - * enumeration ::ftm_interrupt_enable_t - */ -void FTM_EnableInterrupts(FTM_Type *base, uint32_t mask); - -/*! - * @brief Disables the selected FTM interrupts. - * - * @param base FTM peripheral base address - * @param mask The interrupts to enable. This is a logical OR of members of the - * enumeration ::ftm_interrupt_enable_t - */ -void FTM_DisableInterrupts(FTM_Type *base, uint32_t mask); - -/*! - * @brief Gets the enabled FTM interrupts. - * - * @param base FTM peripheral base address - * - * @return The enabled interrupts. This is the logical OR of members of the - * enumeration ::ftm_interrupt_enable_t - */ -uint32_t FTM_GetEnabledInterrupts(FTM_Type *base); - -/*! @}*/ - -/*! - * @name Status Interface - * @{ - */ - -/*! - * @brief Gets the FTM status flags. - * - * @param base FTM peripheral base address - * - * @return The status flags. This is the logical OR of members of the - * enumeration ::ftm_status_flags_t - */ -uint32_t FTM_GetStatusFlags(FTM_Type *base); - -/*! - * @brief Clears the FTM status flags. - * - * @param base FTM peripheral base address - * @param mask The status flags to clear. This is a logical OR of members of the - * enumeration ::ftm_status_flags_t - */ -void FTM_ClearStatusFlags(FTM_Type *base, uint32_t mask); - -/*! @}*/ - -/*! - * @name Read and write the timer period - * @{ - */ - -/*! - * @brief Sets the timer period in units of ticks. - * - * Timers counts from 0 until it equals the count value set here. The count value is written to - * the MOD register. - * - * @note - * 1. This API allows the user to use the FTM module as a timer. Do not mix usage - * of this API with FTM's PWM setup API's. - * 2. Call the utility macros provided in the fsl_common.h to convert usec or msec to ticks. - * - * @param base FTM peripheral base address - * @param ticks A timer period in units of ticks, which should be equal or greater than 1. - */ -static inline void FTM_SetTimerPeriod(FTM_Type *base, uint32_t ticks) -{ - base->MOD = ticks; -} - -/*! - * @brief Reads the current timer counting value. - * - * This function returns the real-time timer counting value in a range from 0 to a - * timer period. - * - * @note Call the utility macros provided in the fsl_common.h to convert ticks to usec or msec. - * - * @param base FTM peripheral base address - * - * @return The current counter value in ticks - */ -static inline uint32_t FTM_GetCurrentTimerCount(FTM_Type *base) -{ - return (uint32_t)((base->CNT & FTM_CNT_COUNT_MASK) >> FTM_CNT_COUNT_SHIFT); -} - -/*! @}*/ -/*! - * @name Timer Start and Stop - * @{ - */ - -/*! - * @brief Starts the FTM counter. - * - * @param base FTM peripheral base address - * @param clockSource FTM clock source; After the clock source is set, the counter starts running. - */ -static inline void FTM_StartTimer(FTM_Type *base, ftm_clock_source_t clockSource) -{ - uint32_t reg = base->SC; - - reg &= ~(FTM_SC_CLKS_MASK); - reg |= FTM_SC_CLKS(clockSource); - base->SC = reg; -} - -/*! - * @brief Stops the FTM counter. - * - * @param base FTM peripheral base address - */ -static inline void FTM_StopTimer(FTM_Type *base) -{ - /* Set clock source to none to disable counter */ - base->SC &= ~(FTM_SC_CLKS_MASK); -} - -/*! @}*/ - -/*! - * @name Software output control - * @{ - */ - -/*! - * @brief Enables or disables the channel software output control. - * - * @param base FTM peripheral base address - * @param chnlNumber Channel to be enabled or disabled - * @param value true: channel output is affected by software output control - false: channel output is unaffected by software output control - */ -static inline void FTM_SetSoftwareCtrlEnable(FTM_Type *base, ftm_chnl_t chnlNumber, bool value) -{ - if (value) - { - base->SWOCTRL |= (1U << chnlNumber); - } - else - { - base->SWOCTRL &= ~(1U << chnlNumber); - } -} - -/*! - * @brief Sets the channel software output control value. - * - * @param base FTM peripheral base address. - * @param chnlNumber Channel to be configured - * @param value true to set 1, false to set 0 - */ -static inline void FTM_SetSoftwareCtrlVal(FTM_Type *base, ftm_chnl_t chnlNumber, bool value) -{ - if (value) - { - base->SWOCTRL |= (1U << (chnlNumber + FTM_SWOCTRL_CH0OCV_SHIFT)); - } - else - { - base->SWOCTRL &= ~(1U << (chnlNumber + FTM_SWOCTRL_CH0OCV_SHIFT)); - } -} - -/*! @}*/ - -/*! - * @brief Enables or disables the FTM global time base signal generation to other FTMs. - * - * @param base FTM peripheral base address - * @param enable true to enable, false to disable - */ -static inline void FTM_SetGlobalTimeBaseOutputEnable(FTM_Type *base, bool enable) -{ - if (enable) - { - base->CONF |= FTM_CONF_GTBEOUT_MASK; - } - else - { - base->CONF &= ~FTM_CONF_GTBEOUT_MASK; - } -} - -/*! - * @brief Sets the FTM peripheral timer channel output mask. - * - * @param base FTM peripheral base address - * @param chnlNumber Channel to be configured - * @param mask true: masked, channel is forced to its inactive state; false: unmasked - */ -static inline void FTM_SetOutputMask(FTM_Type *base, ftm_chnl_t chnlNumber, bool mask) -{ - if (mask) - { - base->OUTMASK |= (1U << chnlNumber); - } - else - { - base->OUTMASK &= ~(1U << chnlNumber); - } -} - -#if defined(FSL_FEATURE_FTM_HAS_ENABLE_PWM_OUTPUT) && (FSL_FEATURE_FTM_HAS_ENABLE_PWM_OUTPUT) -/*! - * @brief Allows users to enable an output on an FTM channel. - * - * To enable the PWM channel output call this function with val=true. For input mode, - * call this function with val=false. - * - * @param base FTM peripheral base address - * @param chnlNumber Channel to be configured - * @param value true: enable output; false: output is disabled, used in input mode - */ -static inline void FTM_SetPwmOutputEnable(FTM_Type *base, ftm_chnl_t chnlNumber, bool value) -{ - if (value) - { - base->SC |= (1U << (chnlNumber + FTM_SC_PWMEN0_SHIFT)); - } - else - { - base->SC &= ~(1U << (chnlNumber + FTM_SC_PWMEN0_SHIFT)); - } -} -#endif - -/*! - * @name Channel pair operations - * @{ - */ - -/*! - * @brief This function enables/disables the fault control in a channel pair. - * - * @param base FTM peripheral base address - * @param chnlPairNumber The FTM channel pair number; options are 0, 1, 2, 3 - * @param value true: Enable fault control for this channel pair; false: No fault control - */ -static inline void FTM_SetFaultControlEnable(FTM_Type *base, ftm_chnl_t chnlPairNumber, bool value) -{ - if (value) - { - base->COMBINE |= (1U << (FTM_COMBINE_FAULTEN0_SHIFT + (FTM_COMBINE_COMBINE1_SHIFT * chnlPairNumber))); - } - else - { - base->COMBINE &= ~(1U << (FTM_COMBINE_FAULTEN0_SHIFT + (FTM_COMBINE_COMBINE1_SHIFT * chnlPairNumber))); - } -} - -/*! - * @brief This function enables/disables the dead time insertion in a channel pair. - * - * @param base FTM peripheral base address - * @param chnlPairNumber The FTM channel pair number; options are 0, 1, 2, 3 - * @param value true: Insert dead time in this channel pair; false: No dead time inserted - */ -static inline void FTM_SetDeadTimeEnable(FTM_Type *base, ftm_chnl_t chnlPairNumber, bool value) -{ - if (value) - { - base->COMBINE |= (1U << (FTM_COMBINE_DTEN0_SHIFT + (FTM_COMBINE_COMBINE1_SHIFT * chnlPairNumber))); - } - else - { - base->COMBINE &= ~(1U << (FTM_COMBINE_DTEN0_SHIFT + (FTM_COMBINE_COMBINE1_SHIFT * chnlPairNumber))); - } -} - -/*! - * @brief This function enables/disables complementary mode in a channel pair. - * - * @param base FTM peripheral base address - * @param chnlPairNumber The FTM channel pair number; options are 0, 1, 2, 3 - * @param value true: enable complementary mode; false: disable complementary mode - */ -static inline void FTM_SetComplementaryEnable(FTM_Type *base, ftm_chnl_t chnlPairNumber, bool value) -{ - if (value) - { - base->COMBINE |= (1U << (FTM_COMBINE_COMP0_SHIFT + (FTM_COMBINE_COMBINE1_SHIFT * chnlPairNumber))); - } - else - { - base->COMBINE &= ~(1U << (FTM_COMBINE_COMP0_SHIFT + (FTM_COMBINE_COMBINE1_SHIFT * chnlPairNumber))); - } -} - -/*! - * @brief This function enables/disables inverting control in a channel pair. - * - * @param base FTM peripheral base address - * @param chnlPairNumber The FTM channel pair number; options are 0, 1, 2, 3 - * @param value true: enable inverting; false: disable inverting - */ -static inline void FTM_SetInvertEnable(FTM_Type *base, ftm_chnl_t chnlPairNumber, bool value) -{ - if (value) - { - base->INVCTRL |= (1U << chnlPairNumber); - } - else - { - base->INVCTRL &= ~(1U << chnlPairNumber); - } -} - -/*! @}*/ - -/*! - * @name Quad Decoder - * @{ - */ - -/*! - * @brief Configures the parameters and activates the quadrature decoder mode. - * - * @param base FTM peripheral base address - * @param phaseAParams Phase A configuration parameters - * @param phaseBParams Phase B configuration parameters - * @param quadMode Selects encoding mode used in quadrature decoder mode - */ -void FTM_SetupQuadDecode(FTM_Type *base, - const ftm_phase_params_t *phaseAParams, - const ftm_phase_params_t *phaseBParams, - ftm_quad_decode_mode_t quadMode); - -/*! - * @brief Gets the FTM Quad Decoder flags. - * - * @param base FTM peripheral base address. - * @return Flag mask of FTM Quad Decoder, see #_ftm_quad_decoder_flags. - */ -static inline uint32_t FTM_GetQuadDecoderFlags(FTM_Type *base) -{ - return base->QDCTRL & (FTM_QDCTRL_QUADIR_MASK | FTM_QDCTRL_TOFDIR_MASK); -} - -/*! - * @brief Sets the modulo values for Quad Decoder. - * - * The modulo values configure the minimum and maximum values that the Quad decoder counter can reach. After the counter goes - * over, the counter value goes to the other side and decrease/increase again. - * - * @param base FTM peripheral base address. - * @param startValue The low limit value for Quad Decoder counter. - * @param overValue The high limit value for Quad Decoder counter. - */ -static inline void FTM_SetQuadDecoderModuloValue(FTM_Type *base, uint32_t startValue, uint32_t overValue) -{ - base->CNTIN = startValue; - base->MOD = overValue; -} - -/*! - * @brief Gets the current Quad Decoder counter value. - * - * @param base FTM peripheral base address. - * @return Current quad Decoder counter value. - */ -static inline uint32_t FTM_GetQuadDecoderCounterValue(FTM_Type *base) -{ - return base->CNT; -} - -/*! - * @brief Clears the current Quad Decoder counter value. - * - * The counter is set as the initial value. - * - * @param base FTM peripheral base address. - */ -static inline void FTM_ClearQuadDecoderCounterValue(FTM_Type *base) -{ - base->CNT = base->CNTIN; -} - -/*! @}*/ - -/*! - * @brief Enables or disables the FTM software trigger for PWM synchronization. - * - * @param base FTM peripheral base address - * @param enable true: software trigger is selected, false: software trigger is not selected - */ -static inline void FTM_SetSoftwareTrigger(FTM_Type *base, bool enable) -{ - if (enable) - { - base->SYNC |= FTM_SYNC_SWSYNC_MASK; - } - else - { - base->SYNC &= ~FTM_SYNC_SWSYNC_MASK; - } -} - -/*! - * @brief Enables or disables the FTM write protection. - * - * @param base FTM peripheral base address - * @param enable true: Write-protection is enabled, false: Write-protection is disabled - */ -static inline void FTM_SetWriteProtection(FTM_Type *base, bool enable) -{ - /* Configure write protection */ - if (enable) - { - base->FMS |= FTM_FMS_WPEN_MASK; - } - else - { - base->MODE |= FTM_MODE_WPDIS_MASK; - } -} - -#if defined(__cplusplus) -} -#endif - -/*! @}*/ - -#endif /* _FSL_FTM_H_*/ diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_gpio.c b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_gpio.c deleted file mode 100644 index b40ee3ac11c..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_gpio.c +++ /dev/null @@ -1,195 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "fsl_gpio.h" - -/******************************************************************************* - * Variables - ******************************************************************************/ -static PORT_Type *const s_portBases[] = PORT_BASE_PTRS; -static GPIO_Type *const s_gpioBases[] = GPIO_BASE_PTRS; - -/******************************************************************************* -* Prototypes -******************************************************************************/ - -/*! -* @brief Gets the GPIO instance according to the GPIO base -* -* @param base GPIO peripheral base pointer(PTA, PTB, PTC, etc.) -* @retval GPIO instance -*/ -static uint32_t GPIO_GetInstance(GPIO_Type *base); - -/******************************************************************************* - * Code - ******************************************************************************/ - -static uint32_t GPIO_GetInstance(GPIO_Type *base) -{ - uint32_t instance; - - /* Find the instance index from base address mappings. */ - for (instance = 0; instance < ARRAY_SIZE(s_gpioBases); instance++) - { - if (s_gpioBases[instance] == base) - { - break; - } - } - - assert(instance < ARRAY_SIZE(s_gpioBases)); - - return instance; -} - -void GPIO_PinInit(GPIO_Type *base, uint32_t pin, const gpio_pin_config_t *config) -{ - assert(config); - - if (config->pinDirection == kGPIO_DigitalInput) - { - base->PDDR &= ~(1U << pin); - } - else - { - GPIO_WritePinOutput(base, pin, config->outputLogic); - base->PDDR |= (1U << pin); - } -} - -uint32_t GPIO_GetPinsInterruptFlags(GPIO_Type *base) -{ - uint8_t instance; - PORT_Type *portBase; - instance = GPIO_GetInstance(base); - portBase = s_portBases[instance]; - return portBase->ISFR; -} - -void GPIO_ClearPinsInterruptFlags(GPIO_Type *base, uint32_t mask) -{ - uint8_t instance; - PORT_Type *portBase; - instance = GPIO_GetInstance(base); - portBase = s_portBases[instance]; - portBase->ISFR = mask; -} - -#if defined(FSL_FEATURE_GPIO_HAS_ATTRIBUTE_CHECKER) && FSL_FEATURE_GPIO_HAS_ATTRIBUTE_CHECKER -void GPIO_CheckAttributeBytes(GPIO_Type *base, gpio_checker_attribute_t attribute) -{ - base->GACR = ((uint32_t)attribute << GPIO_GACR_ACB0_SHIFT) | ((uint32_t)attribute << GPIO_GACR_ACB1_SHIFT) | - ((uint32_t)attribute << GPIO_GACR_ACB2_SHIFT) | ((uint32_t)attribute << GPIO_GACR_ACB3_SHIFT); -} -#endif - -#if defined(FSL_FEATURE_SOC_FGPIO_COUNT) && FSL_FEATURE_SOC_FGPIO_COUNT - -/******************************************************************************* - * Variables - ******************************************************************************/ -static FGPIO_Type *const s_fgpioBases[] = FGPIO_BASE_PTRS; - -/******************************************************************************* -* Prototypes -******************************************************************************/ -/*! -* @brief Gets the FGPIO instance according to the GPIO base -* -* @param base FGPIO peripheral base pointer(PTA, PTB, PTC, etc.) -* @retval FGPIO instance -*/ -static uint32_t FGPIO_GetInstance(FGPIO_Type *base); - -/******************************************************************************* - * Code - ******************************************************************************/ - -static uint32_t FGPIO_GetInstance(FGPIO_Type *base) -{ - uint32_t instance; - - /* Find the instance index from base address mappings. */ - for (instance = 0; instance < ARRAY_SIZE(s_fgpioBases); instance++) - { - if (s_fgpioBases[instance] == base) - { - break; - } - } - - assert(instance < ARRAY_SIZE(s_fgpioBases)); - - return instance; -} - -void FGPIO_PinInit(FGPIO_Type *base, uint32_t pin, const gpio_pin_config_t *config) -{ - assert(config); - - if (config->pinDirection == kGPIO_DigitalInput) - { - base->PDDR &= ~(1U << pin); - } - else - { - FGPIO_WritePinOutput(base, pin, config->outputLogic); - base->PDDR |= (1U << pin); - } -} - -uint32_t FGPIO_GetPinsInterruptFlags(FGPIO_Type *base) -{ - uint8_t instance; - instance = FGPIO_GetInstance(base); - PORT_Type *portBase; - portBase = s_portBases[instance]; - return portBase->ISFR; -} - -void FGPIO_ClearPinsInterruptFlags(FGPIO_Type *base, uint32_t mask) -{ - uint8_t instance; - instance = FGPIO_GetInstance(base); - PORT_Type *portBase; - portBase = s_portBases[instance]; - portBase->ISFR = mask; -} - -#if defined(FSL_FEATURE_FGPIO_HAS_ATTRIBUTE_CHECKER) && FSL_FEATURE_FGPIO_HAS_ATTRIBUTE_CHECKER -void FGPIO_CheckAttributeBytes(FGPIO_Type *base, gpio_checker_attribute_t attribute) -{ - base->GACR = (attribute << FGPIO_GACR_ACB0_SHIFT) | (attribute << FGPIO_GACR_ACB1_SHIFT) | - (attribute << FGPIO_GACR_ACB2_SHIFT) | (attribute << FGPIO_GACR_ACB3_SHIFT); -} -#endif - -#endif /* FSL_FEATURE_SOC_FGPIO_COUNT */ diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_gpio.h b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_gpio.h deleted file mode 100644 index 410e2b8ee46..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_gpio.h +++ /dev/null @@ -1,440 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef _FSL_GPIO_H_ -#define _FSL_GPIO_H_ - -#include "fsl_common.h" - -/*! - * @addtogroup gpio - * @{ - */ - -/******************************************************************************* - * Definitions - ******************************************************************************/ - -/*! @name Driver version */ -/*@{*/ -/*! @brief GPIO driver version 2.1.1. */ -#define FSL_GPIO_DRIVER_VERSION (MAKE_VERSION(2, 1, 1)) -/*@}*/ - -/*! @brief GPIO direction definition */ -typedef enum _gpio_pin_direction -{ - kGPIO_DigitalInput = 0U, /*!< Set current pin as digital input*/ - kGPIO_DigitalOutput = 1U, /*!< Set current pin as digital output*/ -} gpio_pin_direction_t; - -#if defined(FSL_FEATURE_GPIO_HAS_ATTRIBUTE_CHECKER) && FSL_FEATURE_GPIO_HAS_ATTRIBUTE_CHECKER -/*! @brief GPIO checker attribute */ -typedef enum _gpio_checker_attribute -{ - kGPIO_UsernonsecureRWUsersecureRWPrivilegedsecureRW = - 0x00U, /*!< User nonsecure:Read+Write; User Secure:Read+Write; Privileged Secure:Read+Write */ - kGPIO_UsernonsecureRUsersecureRWPrivilegedsecureRW = - 0x01U, /*!< User nonsecure:Read; User Secure:Read+Write; Privileged Secure:Read+Write */ - kGPIO_UsernonsecureNUsersecureRWPrivilegedsecureRW = - 0x02U, /*!< User nonsecure:None; User Secure:Read+Write; Privileged Secure:Read+Write */ - kGPIO_UsernonsecureRUsersecureRPrivilegedsecureRW = - 0x03U, /*!< User nonsecure:Read; User Secure:Read; Privileged Secure:Read+Write */ - kGPIO_UsernonsecureNUsersecureRPrivilegedsecureRW = - 0x04U, /*!< User nonsecure:None; User Secure:Read; Privileged Secure:Read+Write */ - kGPIO_UsernonsecureNUsersecureNPrivilegedsecureRW = - 0x05U, /*!< User nonsecure:None; User Secure:None; Privileged Secure:Read+Write */ - kGPIO_UsernonsecureNUsersecureNPrivilegedsecureR = - 0x06U, /*!< User nonsecure:None; User Secure:None; Privileged Secure:Read */ - kGPIO_UsernonsecureNUsersecureNPrivilegedsecureN = - 0x07U, /*!< User nonsecure:None; User Secure:None; Privileged Secure:None */ - kGPIO_IgnoreAttributeCheck = 0x10U, /*!< Ignores the attribute check */ -} gpio_checker_attribute_t; -#endif - -/*! - * @brief The GPIO pin configuration structure. - * - * Each pin can only be configured as either an output pin or an input pin at a time. - * If configured as an input pin, leave the outputConfig unused. - * Note that in some use cases, the corresponding port property should be configured in advance - * with the PORT_SetPinConfig(). - */ -typedef struct _gpio_pin_config -{ - gpio_pin_direction_t pinDirection; /*!< GPIO direction, input or output */ - /* Output configurations; ignore if configured as an input pin */ - uint8_t outputLogic; /*!< Set a default output logic, which has no use in input */ -} gpio_pin_config_t; - -/*! @} */ - -/******************************************************************************* - * API - ******************************************************************************/ - -#if defined(__cplusplus) -extern "C" { -#endif - -/*! - * @addtogroup gpio_driver - * @{ - */ - -/*! @name GPIO Configuration */ -/*@{*/ - -/*! - * @brief Initializes a GPIO pin used by the board. - * - * To initialize the GPIO, define a pin configuration, as either input or output, in the user file. - * Then, call the GPIO_PinInit() function. - * - * This is an example to define an input pin or an output pin configuration. - * @code - * // Define a digital input pin configuration, - * gpio_pin_config_t config = - * { - * kGPIO_DigitalInput, - * 0, - * } - * //Define a digital output pin configuration, - * gpio_pin_config_t config = - * { - * kGPIO_DigitalOutput, - * 0, - * } - * @endcode - * - * @param base GPIO peripheral base pointer (GPIOA, GPIOB, GPIOC, and so on.) - * @param pin GPIO port pin number - * @param config GPIO pin configuration pointer - */ -void GPIO_PinInit(GPIO_Type *base, uint32_t pin, const gpio_pin_config_t *config); - -/*@}*/ - -/*! @name GPIO Output Operations */ -/*@{*/ - -/*! - * @brief Sets the output level of the multiple GPIO pins to the logic 1 or 0. - * - * @param base GPIO peripheral base pointer (GPIOA, GPIOB, GPIOC, and so on.) - * @param pin GPIO pin number - * @param output GPIO pin output logic level. - * - 0: corresponding pin output low-logic level. - * - 1: corresponding pin output high-logic level. - */ -static inline void GPIO_WritePinOutput(GPIO_Type *base, uint32_t pin, uint8_t output) -{ - if (output == 0U) - { - base->PCOR = 1U << pin; - } - else - { - base->PSOR = 1U << pin; - } -} - -/*! - * @brief Sets the output level of the multiple GPIO pins to the logic 1. - * - * @param base GPIO peripheral base pointer (GPIOA, GPIOB, GPIOC, and so on.) - * @param mask GPIO pin number macro - */ -static inline void GPIO_SetPinsOutput(GPIO_Type *base, uint32_t mask) -{ - base->PSOR = mask; -} - -/*! - * @brief Sets the output level of the multiple GPIO pins to the logic 0. - * - * @param base GPIO peripheral base pointer (GPIOA, GPIOB, GPIOC, and so on.) - * @param mask GPIO pin number macro - */ -static inline void GPIO_ClearPinsOutput(GPIO_Type *base, uint32_t mask) -{ - base->PCOR = mask; -} - -/*! - * @brief Reverses the current output logic of the multiple GPIO pins. - * - * @param base GPIO peripheral base pointer (GPIOA, GPIOB, GPIOC, and so on.) - * @param mask GPIO pin number macro - */ -static inline void GPIO_TogglePinsOutput(GPIO_Type *base, uint32_t mask) -{ - base->PTOR = mask; -} -/*@}*/ - -/*! @name GPIO Input Operations */ -/*@{*/ - -/*! - * @brief Reads the current input value of the GPIO port. - * - * @param base GPIO peripheral base pointer (GPIOA, GPIOB, GPIOC, and so on.) - * @param pin GPIO pin number - * @retval GPIO port input value - * - 0: corresponding pin input low-logic level. - * - 1: corresponding pin input high-logic level. - */ -static inline uint32_t GPIO_ReadPinInput(GPIO_Type *base, uint32_t pin) -{ - return (((base->PDIR) >> pin) & 0x01U); -} -/*@}*/ - -/*! @name GPIO Interrupt */ -/*@{*/ - -/*! - * @brief Reads the GPIO port interrupt status flag. - * - * If a pin is configured to generate the DMA request, the corresponding flag - * is cleared automatically at the completion of the requested DMA transfer. - * Otherwise, the flag remains set until a logic one is written to that flag. - * If configured for a level sensitive interrupt that remains asserted, the flag - * is set again immediately. - * - * @param base GPIO peripheral base pointer (GPIOA, GPIOB, GPIOC, and so on.) - * @retval The current GPIO port interrupt status flag, for example, 0x00010001 means the - * pin 0 and 17 have the interrupt. - */ -uint32_t GPIO_GetPinsInterruptFlags(GPIO_Type *base); - -/*! - * @brief Clears multiple GPIO pin interrupt status flags. - * - * @param base GPIO peripheral base pointer (GPIOA, GPIOB, GPIOC, and so on.) - * @param mask GPIO pin number macro - */ -void GPIO_ClearPinsInterruptFlags(GPIO_Type *base, uint32_t mask); - -#if defined(FSL_FEATURE_GPIO_HAS_ATTRIBUTE_CHECKER) && FSL_FEATURE_GPIO_HAS_ATTRIBUTE_CHECKER -/*! - * @brief The GPIO module supports a device-specific number of data ports, organized as 32-bit - * words. Each 32-bit data port includes a GACR register, which defines the byte-level - * attributes required for a successful access to the GPIO programming model. The attribute controls for the 4 data - * bytes in the GACR follow a standard little endian - * data convention. - * - * @param base GPIO peripheral base pointer (GPIOA, GPIOB, GPIOC, and so on.) - * @param mask GPIO pin number macro - */ -void GPIO_CheckAttributeBytes(GPIO_Type *base, gpio_checker_attribute_t attribute); -#endif - -/*@}*/ -/*! @} */ - -/*! - * @addtogroup fgpio_driver - * @{ - */ - -/* - * Introduces the FGPIO feature. - * - * The FGPIO features are only support on some Kinetis MCUs. The FGPIO registers are aliased to the IOPORT - * interface. Accesses via the IOPORT interface occur in parallel with any instruction fetches and - * complete in a single cycle. This aliased Fast GPIO memory map is called FGPIO. - */ - -#if defined(FSL_FEATURE_SOC_FGPIO_COUNT) && FSL_FEATURE_SOC_FGPIO_COUNT - -/*! @name FGPIO Configuration */ -/*@{*/ - -/*! - * @brief Initializes a FGPIO pin used by the board. - * - * To initialize the FGPIO driver, define a pin configuration, as either input or output, in the user file. - * Then, call the FGPIO_PinInit() function. - * - * This is an example to define an input pin or an output pin configuration: - * @code - * // Define a digital input pin configuration, - * gpio_pin_config_t config = - * { - * kGPIO_DigitalInput, - * 0, - * } - * //Define a digital output pin configuration, - * gpio_pin_config_t config = - * { - * kGPIO_DigitalOutput, - * 0, - * } - * @endcode - * - * @param base FGPIO peripheral base pointer (FGPIOA, FGPIOB, FGPIOC, and so on.) - * @param pin FGPIO port pin number - * @param config FGPIO pin configuration pointer - */ -void FGPIO_PinInit(FGPIO_Type *base, uint32_t pin, const gpio_pin_config_t *config); - -/*@}*/ - -/*! @name FGPIO Output Operations */ -/*@{*/ - -/*! - * @brief Sets the output level of the multiple FGPIO pins to the logic 1 or 0. - * - * @param base FGPIO peripheral base pointer (FGPIOA, FGPIOB, FGPIOC, and so on.) - * @param pin FGPIO pin number - * @param output FGPIOpin output logic level. - * - 0: corresponding pin output low-logic level. - * - 1: corresponding pin output high-logic level. - */ -static inline void FGPIO_WritePinOutput(FGPIO_Type *base, uint32_t pin, uint8_t output) -{ - if (output == 0U) - { - base->PCOR = 1 << pin; - } - else - { - base->PSOR = 1 << pin; - } -} - -/*! - * @brief Sets the output level of the multiple FGPIO pins to the logic 1. - * - * @param base FGPIO peripheral base pointer (FGPIOA, FGPIOB, FGPIOC, and so on.) - * @param mask FGPIO pin number macro - */ -static inline void FGPIO_SetPinsOutput(FGPIO_Type *base, uint32_t mask) -{ - base->PSOR = mask; -} - -/*! - * @brief Sets the output level of the multiple FGPIO pins to the logic 0. - * - * @param base FGPIO peripheral base pointer (FGPIOA, FGPIOB, FGPIOC, and so on.) - * @param mask FGPIO pin number macro - */ -static inline void FGPIO_ClearPinsOutput(FGPIO_Type *base, uint32_t mask) -{ - base->PCOR = mask; -} - -/*! - * @brief Reverses the current output logic of the multiple FGPIO pins. - * - * @param base FGPIO peripheral base pointer (FGPIOA, FGPIOB, FGPIOC, and so on.) - * @param mask FGPIO pin number macro - */ -static inline void FGPIO_TogglePinsOutput(FGPIO_Type *base, uint32_t mask) -{ - base->PTOR = mask; -} -/*@}*/ - -/*! @name FGPIO Input Operations */ -/*@{*/ - -/*! - * @brief Reads the current input value of the FGPIO port. - * - * @param base FGPIO peripheral base pointer (FGPIOA, FGPIOB, FGPIOC, and so on.) - * @param pin FGPIO pin number - * @retval FGPIO port input value - * - 0: corresponding pin input low-logic level. - * - 1: corresponding pin input high-logic level. - */ -static inline uint32_t FGPIO_ReadPinInput(FGPIO_Type *base, uint32_t pin) -{ - return (((base->PDIR) >> pin) & 0x01U); -} -/*@}*/ - -/*! @name FGPIO Interrupt */ -/*@{*/ - -/*! - * @brief Reads the FGPIO port interrupt status flag. - * - * If a pin is configured to generate the DMA request, the corresponding flag - * is cleared automatically at the completion of the requested DMA transfer. - * Otherwise, the flag remains set until a logic one is written to that flag. - * If configured for a level-sensitive interrupt that remains asserted, the flag - * is set again immediately. - * - * @param base FGPIO peripheral base pointer (FGPIOA, FGPIOB, FGPIOC, and so on.) - * @retval The current FGPIO port interrupt status flags, for example, 0x00010001 means the - * pin 0 and 17 have the interrupt. - */ -uint32_t FGPIO_GetPinsInterruptFlags(FGPIO_Type *base); - -/*! - * @brief Clears the multiple FGPIO pin interrupt status flag. - * - * @param base FGPIO peripheral base pointer (FGPIOA, FGPIOB, FGPIOC, and so on.) - * @param mask FGPIO pin number macro - */ -void FGPIO_ClearPinsInterruptFlags(FGPIO_Type *base, uint32_t mask); - -#if defined(FSL_FEATURE_GPIO_HAS_ATTRIBUTE_CHECKER) && FSL_FEATURE_GPIO_HAS_ATTRIBUTE_CHECKER -/*! - * @brief The FGPIO module supports a device-specific number of data ports, organized as 32-bit - * words. Each 32-bit data port includes a GACR register, which defines the byte-level - * attributes required for a successful access to the GPIO programming model. The attribute controls for the 4 data - * bytes in the GACR follow a standard little endian - * data convention. - * - * @param base FGPIO peripheral base pointer (FGPIOA, FGPIOB, FGPIOC, and so on.) - * @param mask FGPIO pin number macro - */ -void FGPIO_CheckAttributeBytes(FGPIO_Type *base, gpio_checker_attribute_t attribute); -#endif - -/*@}*/ - -#endif /* FSL_FEATURE_SOC_FGPIO_COUNT */ - -#if defined(__cplusplus) -} -#endif - -/*! - * @} - */ - -#endif /* _FSL_GPIO_H_*/ diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_i2c.c b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_i2c.c deleted file mode 100644 index 6c9770af256..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_i2c.c +++ /dev/null @@ -1,1757 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -#include "fsl_i2c.h" - -/******************************************************************************* - * Definitions - ******************************************************************************/ - -/*! @brief i2c transfer state. */ -enum _i2c_transfer_states -{ - kIdleState = 0x0U, /*!< I2C bus idle. */ - kCheckAddressState = 0x1U, /*!< 7-bit address check state. */ - kSendCommandState = 0x2U, /*!< Send command byte phase. */ - kSendDataState = 0x3U, /*!< Send data transfer phase. */ - kReceiveDataBeginState = 0x4U, /*!< Receive data transfer phase begin. */ - kReceiveDataState = 0x5U, /*!< Receive data transfer phase. */ -}; - -/*! @brief Common sets of flags used by the driver. */ -enum _i2c_flag_constants -{ -/*! All flags which are cleared by the driver upon starting a transfer. */ -#if defined(FSL_FEATURE_I2C_HAS_START_STOP_DETECT) && FSL_FEATURE_I2C_HAS_START_STOP_DETECT - kClearFlags = kI2C_ArbitrationLostFlag | kI2C_IntPendingFlag | kI2C_StartDetectFlag | kI2C_StopDetectFlag, - kIrqFlags = kI2C_GlobalInterruptEnable | kI2C_StartStopDetectInterruptEnable, -#elif defined(FSL_FEATURE_I2C_HAS_STOP_DETECT) && FSL_FEATURE_I2C_HAS_STOP_DETECT - kClearFlags = kI2C_ArbitrationLostFlag | kI2C_IntPendingFlag | kI2C_StopDetectFlag, - kIrqFlags = kI2C_GlobalInterruptEnable | kI2C_StopDetectInterruptEnable, -#else - kClearFlags = kI2C_ArbitrationLostFlag | kI2C_IntPendingFlag, - kIrqFlags = kI2C_GlobalInterruptEnable, -#endif - -}; - -/*! @brief Typedef for interrupt handler. */ -typedef void (*i2c_isr_t)(I2C_Type *base, void *i2cHandle); - -/******************************************************************************* - * Prototypes - ******************************************************************************/ - -/*! - * @brief Get instance number for I2C module. - * - * @param base I2C peripheral base address. - */ -uint32_t I2C_GetInstance(I2C_Type *base); - -/*! -* @brief Set SCL/SDA hold time, this API receives SCL stop hold time, calculate the -* closest SCL divider and MULT value for the SDA hold time, SCL start and SCL stop -* hold time. To reduce the ROM size, SDA/SCL hold value mapping table is not provided, -* assume SCL divider = SCL stop hold value *2 to get the closest SCL divider value and MULT -* value, then the related SDA hold time, SCL start and SCL stop hold time is used. -* -* @param base I2C peripheral base address. -* @param sourceClock_Hz I2C functional clock frequency in Hertz. -* @param sclStopHoldTime_ns SCL stop hold time in ns. -*/ -static void I2C_SetHoldTime(I2C_Type *base, uint32_t sclStopHoldTime_ns, uint32_t sourceClock_Hz); - -/*! - * @brief Set up master transfer, send slave address and decide the initial - * transfer state. - * - * @param base I2C peripheral base address. - * @param handle pointer to i2c_master_handle_t structure which stores the transfer state. - * @param xfer pointer to i2c_master_transfer_t structure. - */ -static status_t I2C_InitTransferStateMachine(I2C_Type *base, i2c_master_handle_t *handle, i2c_master_transfer_t *xfer); - -/*! - * @brief Check and clear status operation. - * - * @param base I2C peripheral base address. - * @param status current i2c hardware status. - * @retval kStatus_Success No error found. - * @retval kStatus_I2C_ArbitrationLost Transfer error, arbitration lost. - * @retval kStatus_I2C_Nak Received Nak error. - */ -static status_t I2C_CheckAndClearError(I2C_Type *base, uint32_t status); - -/*! - * @brief Master run transfer state machine to perform a byte of transfer. - * - * @param base I2C peripheral base address. - * @param handle pointer to i2c_master_handle_t structure which stores the transfer state - * @param isDone input param to get whether the thing is done, true is done - * @retval kStatus_Success No error found. - * @retval kStatus_I2C_ArbitrationLost Transfer error, arbitration lost. - * @retval kStatus_I2C_Nak Received Nak error. - * @retval kStatus_I2C_Timeout Transfer error, wait signal timeout. - */ -static status_t I2C_MasterTransferRunStateMachine(I2C_Type *base, i2c_master_handle_t *handle, bool *isDone); - -/*! - * @brief I2C common interrupt handler. - * - * @param base I2C peripheral base address. - * @param handle pointer to i2c_master_handle_t structure which stores the transfer state - */ -static void I2C_TransferCommonIRQHandler(I2C_Type *base, void *handle); - -/******************************************************************************* - * Variables - ******************************************************************************/ - -/*! @brief Pointers to i2c handles for each instance. */ -static void *s_i2cHandle[FSL_FEATURE_SOC_I2C_COUNT] = {NULL}; - -/*! @brief SCL clock divider used to calculate baudrate. */ -static const uint16_t s_i2cDividerTable[] = { - 20, 22, 24, 26, 28, 30, 34, 40, 28, 32, 36, 40, 44, 48, 56, 68, - 48, 56, 64, 72, 80, 88, 104, 128, 80, 96, 112, 128, 144, 160, 192, 240, - 160, 192, 224, 256, 288, 320, 384, 480, 320, 384, 448, 512, 576, 640, 768, 960, - 640, 768, 896, 1024, 1152, 1280, 1536, 1920, 1280, 1536, 1792, 2048, 2304, 2560, 3072, 3840}; - -/*! @brief Pointers to i2c bases for each instance. */ -static I2C_Type *const s_i2cBases[] = I2C_BASE_PTRS; - -/*! @brief Pointers to i2c IRQ number for each instance. */ -static const IRQn_Type s_i2cIrqs[] = I2C_IRQS; - -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) -/*! @brief Pointers to i2c clocks for each instance. */ -static const clock_ip_name_t s_i2cClocks[] = I2C_CLOCKS; -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ - -/*! @brief Pointer to master IRQ handler for each instance. */ -static i2c_isr_t s_i2cMasterIsr; - -/*! @brief Pointer to slave IRQ handler for each instance. */ -static i2c_isr_t s_i2cSlaveIsr; - -/******************************************************************************* - * Codes - ******************************************************************************/ - -uint32_t I2C_GetInstance(I2C_Type *base) -{ - uint32_t instance; - - /* Find the instance index from base address mappings. */ - for (instance = 0; instance < ARRAY_SIZE(s_i2cBases); instance++) - { - if (s_i2cBases[instance] == base) - { - break; - } - } - - assert(instance < ARRAY_SIZE(s_i2cBases)); - - return instance; -} - -static void I2C_SetHoldTime(I2C_Type *base, uint32_t sclStopHoldTime_ns, uint32_t sourceClock_Hz) -{ - uint32_t multiplier; - uint32_t computedSclHoldTime; - uint32_t absError; - uint32_t bestError = UINT32_MAX; - uint32_t bestMult = 0u; - uint32_t bestIcr = 0u; - uint8_t mult; - uint8_t i; - - /* Search for the settings with the lowest error. Mult is the MULT field of the I2C_F register, - * and ranges from 0-2. It selects the multiplier factor for the divider. */ - /* SDA hold time = bus period (s) * mul * SDA hold value. */ - /* SCL start hold time = bus period (s) * mul * SCL start hold value. */ - /* SCL stop hold time = bus period (s) * mul * SCL stop hold value. */ - - for (mult = 0u; (mult <= 2u) && (bestError != 0); ++mult) - { - multiplier = 1u << mult; - - /* Scan table to find best match. */ - for (i = 0u; i < sizeof(s_i2cDividerTable) / sizeof(s_i2cDividerTable[0]); ++i) - { - /* Assume SCL hold(stop) value = s_i2cDividerTable[i]/2. */ - computedSclHoldTime = ((multiplier * s_i2cDividerTable[i]) * 500000000U) / sourceClock_Hz; - absError = sclStopHoldTime_ns > computedSclHoldTime ? (sclStopHoldTime_ns - computedSclHoldTime) : - (computedSclHoldTime - sclStopHoldTime_ns); - - if (absError < bestError) - { - bestMult = mult; - bestIcr = i; - bestError = absError; - - /* If the error is 0, then we can stop searching because we won't find a better match. */ - if (absError == 0) - { - break; - } - } - } - } - - /* Set frequency register based on best settings. */ - base->F = I2C_F_MULT(bestMult) | I2C_F_ICR(bestIcr); -} - -static status_t I2C_InitTransferStateMachine(I2C_Type *base, i2c_master_handle_t *handle, i2c_master_transfer_t *xfer) -{ - status_t result = kStatus_Success; - i2c_direction_t direction = xfer->direction; - - /* Initialize the handle transfer information. */ - handle->transfer = *xfer; - - /* Save total transfer size. */ - handle->transferSize = xfer->dataSize; - - /* Initial transfer state. */ - if (handle->transfer.subaddressSize > 0) - { - if (xfer->direction == kI2C_Read) - { - direction = kI2C_Write; - } - } - - handle->state = kCheckAddressState; - - /* Clear all status before transfer. */ - I2C_MasterClearStatusFlags(base, kClearFlags); - - /* If repeated start is requested, send repeated start. */ - if (handle->transfer.flags & kI2C_TransferRepeatedStartFlag) - { - result = I2C_MasterRepeatedStart(base, handle->transfer.slaveAddress, direction); - } - else /* For normal transfer, send start. */ - { - result = I2C_MasterStart(base, handle->transfer.slaveAddress, direction); - } - - return result; -} - -static status_t I2C_CheckAndClearError(I2C_Type *base, uint32_t status) -{ - status_t result = kStatus_Success; - - /* Check arbitration lost. */ - if (status & kI2C_ArbitrationLostFlag) - { - /* Clear arbitration lost flag. */ - base->S = kI2C_ArbitrationLostFlag; - result = kStatus_I2C_ArbitrationLost; - } - /* Check NAK */ - else if (status & kI2C_ReceiveNakFlag) - { - result = kStatus_I2C_Nak; - } - else - { - } - - return result; -} - -static status_t I2C_MasterTransferRunStateMachine(I2C_Type *base, i2c_master_handle_t *handle, bool *isDone) -{ - status_t result = kStatus_Success; - uint32_t statusFlags = base->S; - *isDone = false; - volatile uint8_t dummy = 0; - bool ignoreNak = ((handle->state == kSendDataState) && (handle->transfer.dataSize == 0U)) || - ((handle->state == kReceiveDataState) && (handle->transfer.dataSize == 1U)); - - /* Add this to avoid build warning. */ - dummy++; - - /* Check & clear error flags. */ - result = I2C_CheckAndClearError(base, statusFlags); - - /* Ignore Nak when it's appeared for last byte. */ - if ((result == kStatus_I2C_Nak) && ignoreNak) - { - result = kStatus_Success; - } - - /* Handle Check address state to check the slave address is Acked in slave - probe application. */ - if (handle->state == kCheckAddressState) - { - if (statusFlags & kI2C_ReceiveNakFlag) - { - result = kStatus_I2C_Addr_Nak; - } - else - { - if (handle->transfer.subaddressSize > 0) - { - handle->state = kSendCommandState; - } - else - { - if (handle->transfer.direction == kI2C_Write) - { - /* Next state, send data. */ - handle->state = kSendDataState; - } - else - { - /* Next state, receive data begin. */ - handle->state = kReceiveDataBeginState; - } - } - } - } - - if (result) - { - return result; - } - - /* Run state machine. */ - switch (handle->state) - { - /* Send I2C command. */ - case kSendCommandState: - if (handle->transfer.subaddressSize) - { - handle->transfer.subaddressSize--; - base->D = ((handle->transfer.subaddress) >> (8 * handle->transfer.subaddressSize)); - } - else - { - if (handle->transfer.direction == kI2C_Write) - { - /* Next state, send data. */ - handle->state = kSendDataState; - - /* Send first byte of data. */ - if (handle->transfer.dataSize > 0) - { - base->D = *handle->transfer.data; - handle->transfer.data++; - handle->transfer.dataSize--; - } - } - else - { - /* Send repeated start and slave address. */ - result = I2C_MasterRepeatedStart(base, handle->transfer.slaveAddress, kI2C_Read); - - /* Next state, receive data begin. */ - handle->state = kReceiveDataBeginState; - } - } - break; - - /* Send I2C data. */ - case kSendDataState: - /* Send one byte of data. */ - if (handle->transfer.dataSize > 0) - { - base->D = *handle->transfer.data; - handle->transfer.data++; - handle->transfer.dataSize--; - } - else - { - *isDone = true; - } - break; - - /* Start I2C data receive. */ - case kReceiveDataBeginState: - base->C1 &= ~(I2C_C1_TX_MASK | I2C_C1_TXAK_MASK); - - /* Send nak at the last receive byte. */ - if (handle->transfer.dataSize == 1) - { - base->C1 |= I2C_C1_TXAK_MASK; - } - - /* Read dummy to release the bus. */ - dummy = base->D; - - /* Next state, receive data. */ - handle->state = kReceiveDataState; - break; - - /* Receive I2C data. */ - case kReceiveDataState: - /* Receive one byte of data. */ - if (handle->transfer.dataSize--) - { - if (handle->transfer.dataSize == 0) - { - *isDone = true; - - /* Send stop if kI2C_TransferNoStop is not asserted. */ - if (!(handle->transfer.flags & kI2C_TransferNoStopFlag)) - { - result = I2C_MasterStop(base); - } - else - { - base->C1 |= I2C_C1_TX_MASK; - } - } - - /* Send NAK at the last receive byte. */ - if (handle->transfer.dataSize == 1) - { - base->C1 |= I2C_C1_TXAK_MASK; - } - - /* Read the data byte into the transfer buffer. */ - *handle->transfer.data = base->D; - handle->transfer.data++; - } - break; - - default: - break; - } - - return result; -} - -static void I2C_TransferCommonIRQHandler(I2C_Type *base, void *handle) -{ - /* Check if master interrupt. */ - if ((base->S & kI2C_ArbitrationLostFlag) || (base->C1 & I2C_C1_MST_MASK)) - { - s_i2cMasterIsr(base, handle); - } - else - { - s_i2cSlaveIsr(base, handle); - } - __DSB(); -} - -void I2C_MasterInit(I2C_Type *base, const i2c_master_config_t *masterConfig, uint32_t srcClock_Hz) -{ - assert(masterConfig && srcClock_Hz); - - /* Temporary register for filter read. */ - uint8_t fltReg; -#if defined(FSL_FEATURE_I2C_HAS_DOUBLE_BUFFER_ENABLE) && FSL_FEATURE_I2C_HAS_DOUBLE_BUFFER_ENABLE - uint8_t s2Reg; -#endif -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) - /* Enable I2C clock. */ - CLOCK_EnableClock(s_i2cClocks[I2C_GetInstance(base)]); -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ - - /* Reset the module. */ - base->A1 = 0; - base->F = 0; - base->C1 = 0; - base->S = 0xFFU; - base->C2 = 0; -#if defined(FSL_FEATURE_I2C_HAS_START_STOP_DETECT) && FSL_FEATURE_I2C_HAS_START_STOP_DETECT - base->FLT = 0x50U; -#elif defined(FSL_FEATURE_I2C_HAS_STOP_DETECT) && FSL_FEATURE_I2C_HAS_STOP_DETECT - base->FLT = 0x40U; -#endif - base->RA = 0; - - /* Disable I2C prior to configuring it. */ - base->C1 &= ~(I2C_C1_IICEN_MASK); - - /* Clear all flags. */ - I2C_MasterClearStatusFlags(base, kClearFlags); - - /* Configure baud rate. */ - I2C_MasterSetBaudRate(base, masterConfig->baudRate_Bps, srcClock_Hz); - - /* Read out the FLT register. */ - fltReg = base->FLT; - -#if defined(FSL_FEATURE_I2C_HAS_STOP_HOLD_OFF) && FSL_FEATURE_I2C_HAS_STOP_HOLD_OFF - /* Configure the stop / hold enable. */ - fltReg &= ~(I2C_FLT_SHEN_MASK); - fltReg |= I2C_FLT_SHEN(masterConfig->enableStopHold); -#endif - - /* Configure the glitch filter value. */ - fltReg &= ~(I2C_FLT_FLT_MASK); - fltReg |= I2C_FLT_FLT(masterConfig->glitchFilterWidth); - - /* Write the register value back to the filter register. */ - base->FLT = fltReg; - -/* Enable/Disable double buffering. */ -#if defined(FSL_FEATURE_I2C_HAS_DOUBLE_BUFFER_ENABLE) && FSL_FEATURE_I2C_HAS_DOUBLE_BUFFER_ENABLE - s2Reg = base->S2 & (~I2C_S2_DFEN_MASK); - base->S2 = s2Reg | I2C_S2_DFEN(masterConfig->enableDoubleBuffering); -#endif - - /* Enable the I2C peripheral based on the configuration. */ - base->C1 = I2C_C1_IICEN(masterConfig->enableMaster); -} - -void I2C_MasterDeinit(I2C_Type *base) -{ - /* Disable I2C module. */ - I2C_Enable(base, false); - -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) - /* Disable I2C clock. */ - CLOCK_DisableClock(s_i2cClocks[I2C_GetInstance(base)]); -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ -} - -void I2C_MasterGetDefaultConfig(i2c_master_config_t *masterConfig) -{ - assert(masterConfig); - - /* Default baud rate at 100kbps. */ - masterConfig->baudRate_Bps = 100000U; - -/* Default stop hold enable is disabled. */ -#if defined(FSL_FEATURE_I2C_HAS_STOP_HOLD_OFF) && FSL_FEATURE_I2C_HAS_STOP_HOLD_OFF - masterConfig->enableStopHold = false; -#endif - - /* Default glitch filter value is no filter. */ - masterConfig->glitchFilterWidth = 0U; - -/* Default enable double buffering. */ -#if defined(FSL_FEATURE_I2C_HAS_DOUBLE_BUFFER_ENABLE) && FSL_FEATURE_I2C_HAS_DOUBLE_BUFFER_ENABLE - masterConfig->enableDoubleBuffering = true; -#endif - - /* Enable the I2C peripheral. */ - masterConfig->enableMaster = true; -} - -void I2C_EnableInterrupts(I2C_Type *base, uint32_t mask) -{ -#ifdef I2C_HAS_STOP_DETECT - uint8_t fltReg; -#endif - - if (mask & kI2C_GlobalInterruptEnable) - { - base->C1 |= I2C_C1_IICIE_MASK; - } - -#if defined(FSL_FEATURE_I2C_HAS_STOP_DETECT) && FSL_FEATURE_I2C_HAS_STOP_DETECT - if (mask & kI2C_StopDetectInterruptEnable) - { - fltReg = base->FLT; - - /* Keep STOPF flag. */ - fltReg &= ~I2C_FLT_STOPF_MASK; - - /* Stop detect enable. */ - fltReg |= I2C_FLT_STOPIE_MASK; - base->FLT = fltReg; - } -#endif /* FSL_FEATURE_I2C_HAS_STOP_DETECT */ - -#if defined(FSL_FEATURE_I2C_HAS_START_STOP_DETECT) && FSL_FEATURE_I2C_HAS_START_STOP_DETECT - if (mask & kI2C_StartStopDetectInterruptEnable) - { - fltReg = base->FLT; - - /* Keep STARTF and STOPF flags. */ - fltReg &= ~(I2C_FLT_STOPF_MASK | I2C_FLT_STARTF_MASK); - - /* Start and stop detect enable. */ - fltReg |= I2C_FLT_SSIE_MASK; - base->FLT = fltReg; - } -#endif /* FSL_FEATURE_I2C_HAS_START_STOP_DETECT */ -} - -void I2C_DisableInterrupts(I2C_Type *base, uint32_t mask) -{ - if (mask & kI2C_GlobalInterruptEnable) - { - base->C1 &= ~I2C_C1_IICIE_MASK; - } - -#if defined(FSL_FEATURE_I2C_HAS_STOP_DETECT) && FSL_FEATURE_I2C_HAS_STOP_DETECT - if (mask & kI2C_StopDetectInterruptEnable) - { - base->FLT &= ~(I2C_FLT_STOPIE_MASK | I2C_FLT_STOPF_MASK); - } -#endif /* FSL_FEATURE_I2C_HAS_STOP_DETECT */ - -#if defined(FSL_FEATURE_I2C_HAS_START_STOP_DETECT) && FSL_FEATURE_I2C_HAS_START_STOP_DETECT - if (mask & kI2C_StartStopDetectInterruptEnable) - { - base->FLT &= ~(I2C_FLT_SSIE_MASK | I2C_FLT_STOPF_MASK | I2C_FLT_STARTF_MASK); - } -#endif /* FSL_FEATURE_I2C_HAS_START_STOP_DETECT */ -} - -void I2C_MasterSetBaudRate(I2C_Type *base, uint32_t baudRate_Bps, uint32_t srcClock_Hz) -{ - uint32_t multiplier; - uint32_t computedRate; - uint32_t absError; - uint32_t bestError = UINT32_MAX; - uint32_t bestMult = 0u; - uint32_t bestIcr = 0u; - uint8_t mult; - uint8_t i; - - /* Search for the settings with the lowest error. Mult is the MULT field of the I2C_F register, - * and ranges from 0-2. It selects the multiplier factor for the divider. */ - for (mult = 0u; (mult <= 2u) && (bestError != 0); ++mult) - { - multiplier = 1u << mult; - - /* Scan table to find best match. */ - for (i = 0u; i < sizeof(s_i2cDividerTable) / sizeof(uint16_t); ++i) - { - computedRate = srcClock_Hz / (multiplier * s_i2cDividerTable[i]); - absError = baudRate_Bps > computedRate ? (baudRate_Bps - computedRate) : (computedRate - baudRate_Bps); - - if (absError < bestError) - { - bestMult = mult; - bestIcr = i; - bestError = absError; - - /* If the error is 0, then we can stop searching because we won't find a better match. */ - if (absError == 0) - { - break; - } - } - } - } - - /* Set frequency register based on best settings. */ - base->F = I2C_F_MULT(bestMult) | I2C_F_ICR(bestIcr); -} - -status_t I2C_MasterStart(I2C_Type *base, uint8_t address, i2c_direction_t direction) -{ - status_t result = kStatus_Success; - uint32_t statusFlags = I2C_MasterGetStatusFlags(base); - - /* Return an error if the bus is already in use. */ - if (statusFlags & kI2C_BusBusyFlag) - { - result = kStatus_I2C_Busy; - } - else - { - /* Send the START signal. */ - base->C1 |= I2C_C1_MST_MASK | I2C_C1_TX_MASK; - -#if defined(FSL_FEATURE_I2C_HAS_DOUBLE_BUFFERING) && FSL_FEATURE_I2C_HAS_DOUBLE_BUFFERING - while (!(base->S2 & I2C_S2_EMPTY_MASK)) - { - } -#endif /* FSL_FEATURE_I2C_HAS_DOUBLE_BUFFERING */ - - base->D = (((uint32_t)address) << 1U | ((direction == kI2C_Read) ? 1U : 0U)); - } - - return result; -} - -status_t I2C_MasterRepeatedStart(I2C_Type *base, uint8_t address, i2c_direction_t direction) -{ - status_t result = kStatus_Success; - uint8_t savedMult; - uint32_t statusFlags = I2C_MasterGetStatusFlags(base); - uint8_t timeDelay = 6; - - /* Return an error if the bus is already in use, but not by us. */ - if ((statusFlags & kI2C_BusBusyFlag) && ((base->C1 & I2C_C1_MST_MASK) == 0)) - { - result = kStatus_I2C_Busy; - } - else - { - savedMult = base->F; - base->F = savedMult & (~I2C_F_MULT_MASK); - - /* We are already in a transfer, so send a repeated start. */ - base->C1 |= I2C_C1_RSTA_MASK | I2C_C1_TX_MASK; - - /* Restore the multiplier factor. */ - base->F = savedMult; - - /* Add some delay to wait the Re-Start signal. */ - while (timeDelay--) - { - __NOP(); - } - -#if defined(FSL_FEATURE_I2C_HAS_DOUBLE_BUFFERING) && FSL_FEATURE_I2C_HAS_DOUBLE_BUFFERING - while (!(base->S2 & I2C_S2_EMPTY_MASK)) - { - } -#endif /* FSL_FEATURE_I2C_HAS_DOUBLE_BUFFERING */ - - base->D = (((uint32_t)address) << 1U | ((direction == kI2C_Read) ? 1U : 0U)); - } - - return result; -} - -status_t I2C_MasterStop(I2C_Type *base) -{ - status_t result = kStatus_Success; - uint16_t timeout = UINT16_MAX; - - /* Issue the STOP command on the bus. */ - base->C1 &= ~(I2C_C1_MST_MASK | I2C_C1_TX_MASK | I2C_C1_TXAK_MASK); - - /* Wait until data transfer complete. */ - while ((base->S & kI2C_BusBusyFlag) && (--timeout)) - { - } - - if (timeout == 0) - { - result = kStatus_I2C_Timeout; - } - - return result; -} - -uint32_t I2C_MasterGetStatusFlags(I2C_Type *base) -{ - uint32_t statusFlags = base->S; - -#ifdef I2C_HAS_STOP_DETECT - /* Look up the STOPF bit from the filter register. */ - if (base->FLT & I2C_FLT_STOPF_MASK) - { - statusFlags |= kI2C_StopDetectFlag; - } -#endif - -#if defined(FSL_FEATURE_I2C_HAS_START_STOP_DETECT) && FSL_FEATURE_I2C_HAS_START_STOP_DETECT - /* Look up the STARTF bit from the filter register. */ - if (base->FLT & I2C_FLT_STARTF_MASK) - { - statusFlags |= kI2C_StartDetectFlag; - } -#endif /* FSL_FEATURE_I2C_HAS_START_STOP_DETECT */ - - return statusFlags; -} - -status_t I2C_MasterWriteBlocking(I2C_Type *base, const uint8_t *txBuff, size_t txSize, uint32_t flags) -{ - status_t result = kStatus_Success; - uint8_t statusFlags = 0; - - /* Wait until the data register is ready for transmit. */ - while (!(base->S & kI2C_TransferCompleteFlag)) - { - } - - /* Clear the IICIF flag. */ - base->S = kI2C_IntPendingFlag; - - /* Setup the I2C peripheral to transmit data. */ - base->C1 |= I2C_C1_TX_MASK; - - while (txSize--) - { - /* Send a byte of data. */ - base->D = *txBuff++; - - /* Wait until data transfer complete. */ - while (!(base->S & kI2C_IntPendingFlag)) - { - } - - statusFlags = base->S; - - /* Clear the IICIF flag. */ - base->S = kI2C_IntPendingFlag; - - /* Check if arbitration lost or no acknowledgement (NAK), return failure status. */ - if (statusFlags & kI2C_ArbitrationLostFlag) - { - base->S = kI2C_ArbitrationLostFlag; - result = kStatus_I2C_ArbitrationLost; - } - - if ((statusFlags & kI2C_ReceiveNakFlag) && txSize) - { - base->S = kI2C_ReceiveNakFlag; - result = kStatus_I2C_Nak; - } - - if (result != kStatus_Success) - { - /* Breaking out of the send loop. */ - break; - } - } - - if (((result == kStatus_Success) && (!(flags & kI2C_TransferNoStopFlag))) || (result == kStatus_I2C_Nak)) - { - /* Clear the IICIF flag. */ - base->S = kI2C_IntPendingFlag; - - /* Send stop. */ - result = I2C_MasterStop(base); - } - - return result; -} - -status_t I2C_MasterReadBlocking(I2C_Type *base, uint8_t *rxBuff, size_t rxSize, uint32_t flags) -{ - status_t result = kStatus_Success; - volatile uint8_t dummy = 0; - - /* Add this to avoid build warning. */ - dummy++; - - /* Wait until the data register is ready for transmit. */ - while (!(base->S & kI2C_TransferCompleteFlag)) - { - } - - /* Clear the IICIF flag. */ - base->S = kI2C_IntPendingFlag; - - /* Setup the I2C peripheral to receive data. */ - base->C1 &= ~(I2C_C1_TX_MASK | I2C_C1_TXAK_MASK); - - /* If rxSize equals 1, configure to send NAK. */ - if (rxSize == 1) - { - /* Issue NACK on read. */ - base->C1 |= I2C_C1_TXAK_MASK; - } - - /* Do dummy read. */ - dummy = base->D; - - while ((rxSize--)) - { - /* Wait until data transfer complete. */ - while (!(base->S & kI2C_IntPendingFlag)) - { - } - - /* Clear the IICIF flag. */ - base->S = kI2C_IntPendingFlag; - - /* Single byte use case. */ - if (rxSize == 0) - { - if (!(flags & kI2C_TransferNoStopFlag)) - { - /* Issue STOP command before reading last byte. */ - result = I2C_MasterStop(base); - } - else - { - /* Change direction to Tx to avoid extra clocks. */ - base->C1 |= I2C_C1_TX_MASK; - } - } - - if (rxSize == 1) - { - /* Issue NACK on read. */ - base->C1 |= I2C_C1_TXAK_MASK; - } - - /* Read from the data register. */ - *rxBuff++ = base->D; - } - - return result; -} - -status_t I2C_MasterTransferBlocking(I2C_Type *base, i2c_master_transfer_t *xfer) -{ - assert(xfer); - - i2c_direction_t direction = xfer->direction; - status_t result = kStatus_Success; - - /* Clear all status before transfer. */ - I2C_MasterClearStatusFlags(base, kClearFlags); - - /* Wait until ready to complete. */ - while (!(base->S & kI2C_TransferCompleteFlag)) - { - } - - /* Change to send write address when it's a read operation with command. */ - if ((xfer->subaddressSize > 0) && (xfer->direction == kI2C_Read)) - { - direction = kI2C_Write; - } - - /* If repeated start is requested, send repeated start. */ - if (xfer->flags & kI2C_TransferRepeatedStartFlag) - { - result = I2C_MasterRepeatedStart(base, xfer->slaveAddress, direction); - } - else /* For normal transfer, send start. */ - { - result = I2C_MasterStart(base, xfer->slaveAddress, direction); - } - - /* Return if error. */ - if (result) - { - return result; - } - - while (!(base->S & kI2C_IntPendingFlag)) - { - } - - /* Check if there's transfer error. */ - result = I2C_CheckAndClearError(base, base->S); - - /* Return if error. */ - if (result) - { - if (result == kStatus_I2C_Nak) - { - result = kStatus_I2C_Addr_Nak; - - I2C_MasterStop(base); - } - - return result; - } - - /* Send subaddress. */ - if (xfer->subaddressSize) - { - do - { - /* Clear interrupt pending flag. */ - base->S = kI2C_IntPendingFlag; - - xfer->subaddressSize--; - base->D = ((xfer->subaddress) >> (8 * xfer->subaddressSize)); - - /* Wait until data transfer complete. */ - while (!(base->S & kI2C_IntPendingFlag)) - { - } - - /* Check if there's transfer error. */ - result = I2C_CheckAndClearError(base, base->S); - - if (result) - { - if (result == kStatus_I2C_Nak) - { - I2C_MasterStop(base); - } - - return result; - } - - } while ((xfer->subaddressSize > 0) && (result == kStatus_Success)); - - if (xfer->direction == kI2C_Read) - { - /* Clear pending flag. */ - base->S = kI2C_IntPendingFlag; - - /* Send repeated start and slave address. */ - result = I2C_MasterRepeatedStart(base, xfer->slaveAddress, kI2C_Read); - - /* Return if error. */ - if (result) - { - return result; - } - - /* Wait until data transfer complete. */ - while (!(base->S & kI2C_IntPendingFlag)) - { - } - - /* Check if there's transfer error. */ - result = I2C_CheckAndClearError(base, base->S); - - if (result) - { - if (result == kStatus_I2C_Nak) - { - result = kStatus_I2C_Addr_Nak; - - I2C_MasterStop(base); - } - - return result; - } - } - } - - /* Transmit data. */ - if ((xfer->direction == kI2C_Write) && (xfer->dataSize > 0)) - { - /* Send Data. */ - result = I2C_MasterWriteBlocking(base, xfer->data, xfer->dataSize, xfer->flags); - } - - /* Receive Data. */ - if ((xfer->direction == kI2C_Read) && (xfer->dataSize > 0)) - { - result = I2C_MasterReadBlocking(base, xfer->data, xfer->dataSize, xfer->flags); - } - - return result; -} - -void I2C_MasterTransferCreateHandle(I2C_Type *base, - i2c_master_handle_t *handle, - i2c_master_transfer_callback_t callback, - void *userData) -{ - assert(handle); - - uint32_t instance = I2C_GetInstance(base); - - /* Zero handle. */ - memset(handle, 0, sizeof(*handle)); - - /* Set callback and userData. */ - handle->completionCallback = callback; - handle->userData = userData; - - /* Save the context in global variables to support the double weak mechanism. */ - s_i2cHandle[instance] = handle; - - /* Save master interrupt handler. */ - s_i2cMasterIsr = I2C_MasterTransferHandleIRQ; - - /* Enable NVIC interrupt. */ - EnableIRQ(s_i2cIrqs[instance]); -} - -status_t I2C_MasterTransferNonBlocking(I2C_Type *base, i2c_master_handle_t *handle, i2c_master_transfer_t *xfer) -{ - assert(handle); - assert(xfer); - - status_t result = kStatus_Success; - - /* Check if the I2C bus is idle - if not return busy status. */ - if (handle->state != kIdleState) - { - result = kStatus_I2C_Busy; - } - else - { - /* Start up the master transfer state machine. */ - result = I2C_InitTransferStateMachine(base, handle, xfer); - - if (result == kStatus_Success) - { - /* Enable the I2C interrupts. */ - I2C_EnableInterrupts(base, kI2C_GlobalInterruptEnable); - } - } - - return result; -} - -void I2C_MasterTransferAbort(I2C_Type *base, i2c_master_handle_t *handle) -{ - assert(handle); - - volatile uint8_t dummy = 0; - - /* Add this to avoid build warning. */ - dummy++; - - /* Disable interrupt. */ - I2C_DisableInterrupts(base, kI2C_GlobalInterruptEnable); - - /* Reset the state to idle. */ - handle->state = kIdleState; - - /* Send STOP signal. */ - if (handle->transfer.direction == kI2C_Read) - { - base->C1 |= I2C_C1_TXAK_MASK; - while (!(base->S & kI2C_IntPendingFlag)) - { - } - base->S = kI2C_IntPendingFlag; - - base->C1 &= ~(I2C_C1_MST_MASK | I2C_C1_TX_MASK | I2C_C1_TXAK_MASK); - dummy = base->D; - } - else - { - while (!(base->S & kI2C_IntPendingFlag)) - { - } - base->S = kI2C_IntPendingFlag; - base->C1 &= ~(I2C_C1_MST_MASK | I2C_C1_TX_MASK | I2C_C1_TXAK_MASK); - } -} - -status_t I2C_MasterTransferGetCount(I2C_Type *base, i2c_master_handle_t *handle, size_t *count) -{ - assert(handle); - - if (!count) - { - return kStatus_InvalidArgument; - } - - *count = handle->transferSize - handle->transfer.dataSize; - - return kStatus_Success; -} - -void I2C_MasterTransferHandleIRQ(I2C_Type *base, void *i2cHandle) -{ - assert(i2cHandle); - - i2c_master_handle_t *handle = (i2c_master_handle_t *)i2cHandle; - status_t result = kStatus_Success; - bool isDone; - - /* Clear the interrupt flag. */ - base->S = kI2C_IntPendingFlag; - - /* Check transfer complete flag. */ - result = I2C_MasterTransferRunStateMachine(base, handle, &isDone); - - if (isDone || result) - { - /* Send stop command if transfer done or received Nak. */ - if ((!(handle->transfer.flags & kI2C_TransferNoStopFlag)) || (result == kStatus_I2C_Nak) || - (result == kStatus_I2C_Addr_Nak)) - { - /* Ensure stop command is a need. */ - if ((base->C1 & I2C_C1_MST_MASK)) - { - if (I2C_MasterStop(base) != kStatus_Success) - { - result = kStatus_I2C_Timeout; - } - } - } - - /* Restore handle to idle state. */ - handle->state = kIdleState; - - /* Disable interrupt. */ - I2C_DisableInterrupts(base, kI2C_GlobalInterruptEnable); - - /* Call the callback function after the function has completed. */ - if (handle->completionCallback) - { - handle->completionCallback(base, handle, result, handle->userData); - } - } -} - -void I2C_SlaveInit(I2C_Type *base, const i2c_slave_config_t *slaveConfig, uint32_t srcClock_Hz) -{ - assert(slaveConfig); - - uint8_t tmpReg; - -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) - CLOCK_EnableClock(s_i2cClocks[I2C_GetInstance(base)]); -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ - - /* Reset the module. */ - base->A1 = 0; - base->F = 0; - base->C1 = 0; - base->S = 0xFFU; - base->C2 = 0; -#if defined(FSL_FEATURE_I2C_HAS_START_STOP_DETECT) && FSL_FEATURE_I2C_HAS_START_STOP_DETECT - base->FLT = 0x50U; -#elif defined(FSL_FEATURE_I2C_HAS_STOP_DETECT) && FSL_FEATURE_I2C_HAS_STOP_DETECT - base->FLT = 0x40U; -#endif - base->RA = 0; - - /* Configure addressing mode. */ - switch (slaveConfig->addressingMode) - { - case kI2C_Address7bit: - base->A1 = ((uint32_t)(slaveConfig->slaveAddress)) << 1U; - break; - - case kI2C_RangeMatch: - assert(slaveConfig->slaveAddress < slaveConfig->upperAddress); - base->A1 = ((uint32_t)(slaveConfig->slaveAddress)) << 1U; - base->RA = ((uint32_t)(slaveConfig->upperAddress)) << 1U; - base->C2 |= I2C_C2_RMEN_MASK; - break; - - default: - break; - } - - /* Configure low power wake up feature. */ - tmpReg = base->C1; - tmpReg &= ~I2C_C1_WUEN_MASK; - base->C1 = tmpReg | I2C_C1_WUEN(slaveConfig->enableWakeUp) | I2C_C1_IICEN(slaveConfig->enableSlave); - - /* Configure general call & baud rate control. */ - tmpReg = base->C2; - tmpReg &= ~(I2C_C2_SBRC_MASK | I2C_C2_GCAEN_MASK); - tmpReg |= I2C_C2_SBRC(slaveConfig->enableBaudRateCtl) | I2C_C2_GCAEN(slaveConfig->enableGeneralCall); - base->C2 = tmpReg; - -/* Enable/Disable double buffering. */ -#if defined(FSL_FEATURE_I2C_HAS_DOUBLE_BUFFER_ENABLE) && FSL_FEATURE_I2C_HAS_DOUBLE_BUFFER_ENABLE - tmpReg = base->S2 & (~I2C_S2_DFEN_MASK); - base->S2 = tmpReg | I2C_S2_DFEN(slaveConfig->enableDoubleBuffering); -#endif - - /* Set hold time. */ - I2C_SetHoldTime(base, slaveConfig->sclStopHoldTime_ns, srcClock_Hz); -} - -void I2C_SlaveDeinit(I2C_Type *base) -{ - /* Disable I2C module. */ - I2C_Enable(base, false); - -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) - /* Disable I2C clock. */ - CLOCK_DisableClock(s_i2cClocks[I2C_GetInstance(base)]); -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ -} - -void I2C_SlaveGetDefaultConfig(i2c_slave_config_t *slaveConfig) -{ - assert(slaveConfig); - - /* By default slave is addressed with 7-bit address. */ - slaveConfig->addressingMode = kI2C_Address7bit; - - /* General call mode is disabled by default. */ - slaveConfig->enableGeneralCall = false; - - /* Slave address match waking up MCU from low power mode is disabled. */ - slaveConfig->enableWakeUp = false; - - /* Independent slave mode baud rate at maximum frequency is disabled. */ - slaveConfig->enableBaudRateCtl = false; - -/* Default enable double buffering. */ -#if defined(FSL_FEATURE_I2C_HAS_DOUBLE_BUFFER_ENABLE) && FSL_FEATURE_I2C_HAS_DOUBLE_BUFFER_ENABLE - slaveConfig->enableDoubleBuffering = true; -#endif - - /* Set default SCL stop hold time to 4us which is minimum requirement in I2C spec. */ - slaveConfig->sclStopHoldTime_ns = 4000; - - /* Enable the I2C peripheral. */ - slaveConfig->enableSlave = true; -} - -status_t I2C_SlaveWriteBlocking(I2C_Type *base, const uint8_t *txBuff, size_t txSize) -{ - status_t result = kStatus_Success; - volatile uint8_t dummy = 0; - - /* Add this to avoid build warning. */ - dummy++; - -#if defined(FSL_FEATURE_I2C_HAS_START_STOP_DETECT) && FSL_FEATURE_I2C_HAS_START_STOP_DETECT - /* Check start flag. */ - while (!(base->FLT & I2C_FLT_STARTF_MASK)) - { - } - /* Clear STARTF flag. */ - base->FLT |= I2C_FLT_STARTF_MASK; - /* Clear the IICIF flag. */ - base->S = kI2C_IntPendingFlag; -#endif /* FSL_FEATURE_I2C_HAS_START_STOP_DETECT */ - - /* Wait for address match flag. */ - while (!(base->S & kI2C_AddressMatchFlag)) - { - } - - /* Read dummy to release bus. */ - dummy = base->D; - - result = I2C_MasterWriteBlocking(base, txBuff, txSize, kI2C_TransferDefaultFlag); - - /* Switch to receive mode. */ - base->C1 &= ~(I2C_C1_TX_MASK | I2C_C1_TXAK_MASK); - - /* Read dummy to release bus. */ - dummy = base->D; - - return result; -} - -void I2C_SlaveReadBlocking(I2C_Type *base, uint8_t *rxBuff, size_t rxSize) -{ - volatile uint8_t dummy = 0; - - /* Add this to avoid build warning. */ - dummy++; - -/* Wait until address match. */ -#if defined(FSL_FEATURE_I2C_HAS_START_STOP_DETECT) && FSL_FEATURE_I2C_HAS_START_STOP_DETECT - /* Check start flag. */ - while (!(base->FLT & I2C_FLT_STARTF_MASK)) - { - } - /* Clear STARTF flag. */ - base->FLT |= I2C_FLT_STARTF_MASK; - /* Clear the IICIF flag. */ - base->S = kI2C_IntPendingFlag; -#endif /* FSL_FEATURE_I2C_HAS_START_STOP_DETECT */ - - /* Wait for address match and int pending flag. */ - while (!(base->S & kI2C_AddressMatchFlag)) - { - } - while (!(base->S & kI2C_IntPendingFlag)) - { - } - - /* Read dummy to release bus. */ - dummy = base->D; - - /* Clear the IICIF flag. */ - base->S = kI2C_IntPendingFlag; - - /* Setup the I2C peripheral to receive data. */ - base->C1 &= ~(I2C_C1_TX_MASK); - - while (rxSize--) - { - /* Wait until data transfer complete. */ - while (!(base->S & kI2C_IntPendingFlag)) - { - } - /* Clear the IICIF flag. */ - base->S = kI2C_IntPendingFlag; - - /* Read from the data register. */ - *rxBuff++ = base->D; - } -} - -void I2C_SlaveTransferCreateHandle(I2C_Type *base, - i2c_slave_handle_t *handle, - i2c_slave_transfer_callback_t callback, - void *userData) -{ - assert(handle); - - uint32_t instance = I2C_GetInstance(base); - - /* Zero handle. */ - memset(handle, 0, sizeof(*handle)); - - /* Set callback and userData. */ - handle->callback = callback; - handle->userData = userData; - - /* Save the context in global variables to support the double weak mechanism. */ - s_i2cHandle[instance] = handle; - - /* Save slave interrupt handler. */ - s_i2cSlaveIsr = I2C_SlaveTransferHandleIRQ; - - /* Enable NVIC interrupt. */ - EnableIRQ(s_i2cIrqs[instance]); -} - -status_t I2C_SlaveTransferNonBlocking(I2C_Type *base, i2c_slave_handle_t *handle, uint32_t eventMask) -{ - assert(handle); - - /* Check if the I2C bus is idle - if not return busy status. */ - if (handle->isBusy) - { - return kStatus_I2C_Busy; - } - else - { - /* Disable LPI2C IRQ sources while we configure stuff. */ - I2C_DisableInterrupts(base, kIrqFlags); - - /* Clear transfer in handle. */ - memset(&handle->transfer, 0, sizeof(handle->transfer)); - - /* Record that we're busy. */ - handle->isBusy = true; - - /* Set up event mask. tx and rx are always enabled. */ - handle->eventMask = eventMask | kI2C_SlaveTransmitEvent | kI2C_SlaveReceiveEvent | kI2C_SlaveGenaralcallEvent; - - /* Clear all flags. */ - I2C_SlaveClearStatusFlags(base, kClearFlags); - - /* Enable I2C internal IRQ sources. NVIC IRQ was enabled in CreateHandle() */ - I2C_EnableInterrupts(base, kIrqFlags); - } - - return kStatus_Success; -} - -void I2C_SlaveTransferAbort(I2C_Type *base, i2c_slave_handle_t *handle) -{ - assert(handle); - - if (handle->isBusy) - { - /* Disable interrupts. */ - I2C_DisableInterrupts(base, kIrqFlags); - - /* Reset transfer info. */ - memset(&handle->transfer, 0, sizeof(handle->transfer)); - - /* Reset the state to idle. */ - handle->isBusy = false; - } -} - -status_t I2C_SlaveTransferGetCount(I2C_Type *base, i2c_slave_handle_t *handle, size_t *count) -{ - assert(handle); - - if (!count) - { - return kStatus_InvalidArgument; - } - - /* Catch when there is not an active transfer. */ - if (!handle->isBusy) - { - *count = 0; - return kStatus_NoTransferInProgress; - } - - /* For an active transfer, just return the count from the handle. */ - *count = handle->transfer.transferredCount; - - return kStatus_Success; -} - -void I2C_SlaveTransferHandleIRQ(I2C_Type *base, void *i2cHandle) -{ - assert(i2cHandle); - - uint16_t status; - bool doTransmit = false; - i2c_slave_handle_t *handle = (i2c_slave_handle_t *)i2cHandle; - i2c_slave_transfer_t *xfer; - volatile uint8_t dummy = 0; - - /* Add this to avoid build warning. */ - dummy++; - - status = I2C_SlaveGetStatusFlags(base); - xfer = &(handle->transfer); - -#ifdef I2C_HAS_STOP_DETECT - /* Check stop flag. */ - if (status & kI2C_StopDetectFlag) - { - I2C_MasterClearStatusFlags(base, kI2C_StopDetectFlag); - - /* Clear the interrupt flag. */ - base->S = kI2C_IntPendingFlag; - - /* Call slave callback if this is the STOP of the transfer. */ - if (handle->isBusy) - { - xfer->event = kI2C_SlaveCompletionEvent; - xfer->completionStatus = kStatus_Success; - handle->isBusy = false; - - if ((handle->eventMask & xfer->event) && (handle->callback)) - { - handle->callback(base, xfer, handle->userData); - } - } - - if (!(status & kI2C_AddressMatchFlag)) - { - return; - } - } -#endif /* I2C_HAS_STOP_DETECT */ - -#if defined(FSL_FEATURE_I2C_HAS_START_STOP_DETECT) && FSL_FEATURE_I2C_HAS_START_STOP_DETECT - /* Check start flag. */ - if (status & kI2C_StartDetectFlag) - { - I2C_MasterClearStatusFlags(base, kI2C_StartDetectFlag); - - /* Clear the interrupt flag. */ - base->S = kI2C_IntPendingFlag; - - xfer->event = kI2C_SlaveStartEvent; - - if ((handle->eventMask & xfer->event) && (handle->callback)) - { - handle->callback(base, xfer, handle->userData); - } - - if (!(status & kI2C_AddressMatchFlag)) - { - return; - } - } -#endif /* FSL_FEATURE_I2C_HAS_START_STOP_DETECT */ - - /* Clear the interrupt flag. */ - base->S = kI2C_IntPendingFlag; - - /* Check NAK */ - if (status & kI2C_ReceiveNakFlag) - { - /* Set receive mode. */ - base->C1 &= ~(I2C_C1_TX_MASK | I2C_C1_TXAK_MASK); - - /* Read dummy. */ - dummy = base->D; - - if (handle->transfer.dataSize != 0) - { - xfer->event = kI2C_SlaveCompletionEvent; - xfer->completionStatus = kStatus_I2C_Nak; - handle->isBusy = false; - - if ((handle->eventMask & xfer->event) && (handle->callback)) - { - handle->callback(base, xfer, handle->userData); - } - } - else - { -#ifndef I2C_HAS_STOP_DETECT - xfer->event = kI2C_SlaveCompletionEvent; - xfer->completionStatus = kStatus_Success; - handle->isBusy = false; - - if ((handle->eventMask & xfer->event) && (handle->callback)) - { - handle->callback(base, xfer, handle->userData); - } -#endif /* !FSL_FEATURE_I2C_HAS_START_STOP_DETECT or !FSL_FEATURE_I2C_HAS_STOP_DETECT */ - } - } - /* Check address match. */ - else if (status & kI2C_AddressMatchFlag) - { - handle->isBusy = true; - xfer->event = kI2C_SlaveAddressMatchEvent; - - /* Slave transmit, master reading from slave. */ - if (status & kI2C_TransferDirectionFlag) - { - /* Change direction to send data. */ - base->C1 |= I2C_C1_TX_MASK; - - doTransmit = true; - } - else - { - /* Slave receive, master writing to slave. */ - base->C1 &= ~(I2C_C1_TX_MASK | I2C_C1_TXAK_MASK); - - /* Read dummy to release the bus. */ - dummy = base->D; - - if (dummy == 0) - { - xfer->event = kI2C_SlaveGenaralcallEvent; - } - } - - if ((handle->eventMask & xfer->event) && (handle->callback)) - { - handle->callback(base, xfer, handle->userData); - } - } - /* Check transfer complete flag. */ - else if (status & kI2C_TransferCompleteFlag) - { - /* Slave transmit, master reading from slave. */ - if (status & kI2C_TransferDirectionFlag) - { - doTransmit = true; - } - else - { - /* If we're out of data, invoke callback to get more. */ - if ((!xfer->data) || (!xfer->dataSize)) - { - xfer->event = kI2C_SlaveReceiveEvent; - - if (handle->callback) - { - handle->callback(base, xfer, handle->userData); - } - - /* Clear the transferred count now that we have a new buffer. */ - xfer->transferredCount = 0; - } - - /* Slave receive, master writing to slave. */ - uint8_t data = base->D; - - if (handle->transfer.dataSize) - { - /* Receive data. */ - *handle->transfer.data++ = data; - handle->transfer.dataSize--; - xfer->transferredCount++; - if (!handle->transfer.dataSize) - { -#ifndef I2C_HAS_STOP_DETECT - xfer->event = kI2C_SlaveCompletionEvent; - xfer->completionStatus = kStatus_Success; - handle->isBusy = false; - - /* Proceed receive complete event. */ - if ((handle->eventMask & xfer->event) && (handle->callback)) - { - handle->callback(base, xfer, handle->userData); - } -#endif /* !FSL_FEATURE_I2C_HAS_START_STOP_DETECT or !FSL_FEATURE_I2C_HAS_STOP_DETECT */ - } - } - } - } - else - { - /* Read dummy to release bus. */ - dummy = base->D; - } - - /* Send data if there is the need. */ - if (doTransmit) - { - /* If we're out of data, invoke callback to get more. */ - if ((!xfer->data) || (!xfer->dataSize)) - { - xfer->event = kI2C_SlaveTransmitEvent; - - if (handle->callback) - { - handle->callback(base, xfer, handle->userData); - } - - /* Clear the transferred count now that we have a new buffer. */ - xfer->transferredCount = 0; - } - - if (handle->transfer.dataSize) - { - /* Send data. */ - base->D = *handle->transfer.data++; - handle->transfer.dataSize--; - xfer->transferredCount++; - } - else - { - /* Switch to receive mode. */ - base->C1 &= ~(I2C_C1_TX_MASK | I2C_C1_TXAK_MASK); - - /* Read dummy to release bus. */ - dummy = base->D; - -#ifndef I2C_HAS_STOP_DETECT - xfer->event = kI2C_SlaveCompletionEvent; - xfer->completionStatus = kStatus_Success; - handle->isBusy = false; - - /* Proceed txdone event. */ - if ((handle->eventMask & xfer->event) && (handle->callback)) - { - handle->callback(base, xfer, handle->userData); - } -#endif /* !FSL_FEATURE_I2C_HAS_START_STOP_DETECT or !FSL_FEATURE_I2C_HAS_STOP_DETECT */ - } - } -} - -#if defined(I2C0) -void I2C0_DriverIRQHandler(void) -{ - I2C_TransferCommonIRQHandler(I2C0, s_i2cHandle[0]); -} -#endif - -#if defined(I2C1) -void I2C1_DriverIRQHandler(void) -{ - I2C_TransferCommonIRQHandler(I2C1, s_i2cHandle[1]); -} -#endif - -#if defined(I2C2) -void I2C2_DriverIRQHandler(void) -{ - I2C_TransferCommonIRQHandler(I2C2, s_i2cHandle[2]); -} -#endif - -#if defined(I2C3) -void I2C3_DriverIRQHandler(void) -{ - I2C_TransferCommonIRQHandler(I2C3, s_i2cHandle[3]); -} -#endif diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_i2c.h b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_i2c.h deleted file mode 100644 index d55fd1d8ea3..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_i2c.h +++ /dev/null @@ -1,794 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -#ifndef _FSL_I2C_H_ -#define _FSL_I2C_H_ - -#include "fsl_common.h" - -/*! - * @addtogroup i2c_driver - * @{ - */ - -/******************************************************************************* - * Definitions - ******************************************************************************/ - -/*! @name Driver version */ -/*@{*/ -/*! @brief I2C driver version 2.0.3. */ -#define FSL_I2C_DRIVER_VERSION (MAKE_VERSION(2, 0, 3)) -/*@}*/ - -#if (defined(FSL_FEATURE_I2C_HAS_START_STOP_DETECT) && FSL_FEATURE_I2C_HAS_START_STOP_DETECT || \ - defined(FSL_FEATURE_I2C_HAS_STOP_DETECT) && FSL_FEATURE_I2C_HAS_STOP_DETECT) -#define I2C_HAS_STOP_DETECT -#endif /* FSL_FEATURE_I2C_HAS_START_STOP_DETECT / FSL_FEATURE_I2C_HAS_STOP_DETECT */ - -/*! @brief I2C status return codes. */ -enum _i2c_status -{ - kStatus_I2C_Busy = MAKE_STATUS(kStatusGroup_I2C, 0), /*!< I2C is busy with current transfer. */ - kStatus_I2C_Idle = MAKE_STATUS(kStatusGroup_I2C, 1), /*!< Bus is Idle. */ - kStatus_I2C_Nak = MAKE_STATUS(kStatusGroup_I2C, 2), /*!< NAK received during transfer. */ - kStatus_I2C_ArbitrationLost = MAKE_STATUS(kStatusGroup_I2C, 3), /*!< Arbitration lost during transfer. */ - kStatus_I2C_Timeout = MAKE_STATUS(kStatusGroup_I2C, 4), /*!< Wait event timeout. */ - kStatus_I2C_Addr_Nak = MAKE_STATUS(kStatusGroup_I2C, 5), /*!< NAK received during the address probe. */ -}; - -/*! - * @brief I2C peripheral flags - * - * The following status register flags can be cleared: - * - #kI2C_ArbitrationLostFlag - * - #kI2C_IntPendingFlag - * - #kI2C_StartDetectFlag - * - #kI2C_StopDetectFlag - * - * @note These enumerations are meant to be OR'd together to form a bit mask. - * - */ -enum _i2c_flags -{ - kI2C_ReceiveNakFlag = I2C_S_RXAK_MASK, /*!< I2C receive NAK flag. */ - kI2C_IntPendingFlag = I2C_S_IICIF_MASK, /*!< I2C interrupt pending flag. */ - kI2C_TransferDirectionFlag = I2C_S_SRW_MASK, /*!< I2C transfer direction flag. */ - kI2C_RangeAddressMatchFlag = I2C_S_RAM_MASK, /*!< I2C range address match flag. */ - kI2C_ArbitrationLostFlag = I2C_S_ARBL_MASK, /*!< I2C arbitration lost flag. */ - kI2C_BusBusyFlag = I2C_S_BUSY_MASK, /*!< I2C bus busy flag. */ - kI2C_AddressMatchFlag = I2C_S_IAAS_MASK, /*!< I2C address match flag. */ - kI2C_TransferCompleteFlag = I2C_S_TCF_MASK, /*!< I2C transfer complete flag. */ -#ifdef I2C_HAS_STOP_DETECT - kI2C_StopDetectFlag = I2C_FLT_STOPF_MASK << 8, /*!< I2C stop detect flag. */ -#endif /* FSL_FEATURE_I2C_HAS_START_STOP_DETECT / FSL_FEATURE_I2C_HAS_STOP_DETECT */ - -#if defined(FSL_FEATURE_I2C_HAS_START_STOP_DETECT) && FSL_FEATURE_I2C_HAS_START_STOP_DETECT - kI2C_StartDetectFlag = I2C_FLT_STARTF_MASK << 8, /*!< I2C start detect flag. */ -#endif /* FSL_FEATURE_I2C_HAS_START_STOP_DETECT */ -}; - -/*! @brief I2C feature interrupt source. */ -enum _i2c_interrupt_enable -{ - kI2C_GlobalInterruptEnable = I2C_C1_IICIE_MASK, /*!< I2C global interrupt. */ - -#if defined(FSL_FEATURE_I2C_HAS_STOP_DETECT) && FSL_FEATURE_I2C_HAS_STOP_DETECT - kI2C_StopDetectInterruptEnable = I2C_FLT_STOPIE_MASK, /*!< I2C stop detect interrupt. */ -#endif /* FSL_FEATURE_I2C_HAS_STOP_DETECT */ - -#if defined(FSL_FEATURE_I2C_HAS_START_STOP_DETECT) && FSL_FEATURE_I2C_HAS_START_STOP_DETECT - kI2C_StartStopDetectInterruptEnable = I2C_FLT_SSIE_MASK, /*!< I2C start&stop detect interrupt. */ -#endif /* FSL_FEATURE_I2C_HAS_START_STOP_DETECT */ -}; - -/*! @brief The direction of master and slave transfers. */ -typedef enum _i2c_direction -{ - kI2C_Write = 0x0U, /*!< Master transmits to the slave. */ - kI2C_Read = 0x1U, /*!< Master receives from the slave. */ -} i2c_direction_t; - -/*! @brief Addressing mode. */ -typedef enum _i2c_slave_address_mode -{ - kI2C_Address7bit = 0x0U, /*!< 7-bit addressing mode. */ - kI2C_RangeMatch = 0X2U, /*!< Range address match addressing mode. */ -} i2c_slave_address_mode_t; - -/*! @brief I2C transfer control flag. */ -enum _i2c_master_transfer_flags -{ - kI2C_TransferDefaultFlag = 0x0U, /*!< A transfer starts with a start signal, stops with a stop signal. */ - kI2C_TransferNoStartFlag = 0x1U, /*!< A transfer starts without a start signal. */ - kI2C_TransferRepeatedStartFlag = 0x2U, /*!< A transfer starts with a repeated start signal. */ - kI2C_TransferNoStopFlag = 0x4U, /*!< A transfer ends without a stop signal. */ -}; - -/*! - * @brief Set of events sent to the callback for nonblocking slave transfers. - * - * These event enumerations are used for two related purposes. First, a bit mask created by OR'ing together - * events is passed to I2C_SlaveTransferNonBlocking() to specify which events to enable. - * Then, when the slave callback is invoked, it is passed the current event through its @a transfer - * parameter. - * - * @note These enumerations are meant to be OR'd together to form a bit mask of events. - */ -typedef enum _i2c_slave_transfer_event -{ - kI2C_SlaveAddressMatchEvent = 0x01U, /*!< Received the slave address after a start or repeated start. */ - kI2C_SlaveTransmitEvent = 0x02U, /*!< A callback is requested to provide data to transmit - (slave-transmitter role). */ - kI2C_SlaveReceiveEvent = 0x04U, /*!< A callback is requested to provide a buffer in which to place received - data (slave-receiver role). */ - kI2C_SlaveTransmitAckEvent = 0x08U, /*!< A callback needs to either transmit an ACK or NACK. */ -#if defined(FSL_FEATURE_I2C_HAS_START_STOP_DETECT) && FSL_FEATURE_I2C_HAS_START_STOP_DETECT - kI2C_SlaveStartEvent = 0x10U, /*!< A start/repeated start was detected. */ -#endif - kI2C_SlaveCompletionEvent = 0x20U, /*!< A stop was detected or finished transfer, completing the transfer. */ - kI2C_SlaveGenaralcallEvent = 0x40U, /*!< Received the general call address after a start or repeated start. */ - - /*! A bit mask of all available events. */ - kI2C_SlaveAllEvents = kI2C_SlaveAddressMatchEvent | kI2C_SlaveTransmitEvent | kI2C_SlaveReceiveEvent | -#if defined(FSL_FEATURE_I2C_HAS_START_STOP_DETECT) && FSL_FEATURE_I2C_HAS_START_STOP_DETECT - kI2C_SlaveStartEvent | -#endif - kI2C_SlaveCompletionEvent | kI2C_SlaveGenaralcallEvent, -} i2c_slave_transfer_event_t; - -/*! @brief I2C master user configuration. */ -typedef struct _i2c_master_config -{ - bool enableMaster; /*!< Enables the I2C peripheral at initialization time. */ -#if defined(FSL_FEATURE_I2C_HAS_STOP_HOLD_OFF) && FSL_FEATURE_I2C_HAS_STOP_HOLD_OFF - bool enableStopHold; /*!< Controls the stop hold enable. */ -#endif -#if defined(FSL_FEATURE_I2C_HAS_DOUBLE_BUFFER_ENABLE) && FSL_FEATURE_I2C_HAS_DOUBLE_BUFFER_ENABLE - bool enableDoubleBuffering; /*!< Controls double buffer enable; notice that - enabling the double buffer disables the clock stretch. */ -#endif - uint32_t baudRate_Bps; /*!< Baud rate configuration of I2C peripheral. */ - uint8_t glitchFilterWidth; /*!< Controls the width of the glitch. */ -} i2c_master_config_t; - -/*! @brief I2C slave user configuration. */ -typedef struct _i2c_slave_config -{ - bool enableSlave; /*!< Enables the I2C peripheral at initialization time. */ - bool enableGeneralCall; /*!< Enables the general call addressing mode. */ - bool enableWakeUp; /*!< Enables/disables waking up MCU from low-power mode. */ -#if defined(FSL_FEATURE_I2C_HAS_DOUBLE_BUFFER_ENABLE) && FSL_FEATURE_I2C_HAS_DOUBLE_BUFFER_ENABLE - bool enableDoubleBuffering; /*!< Controls a double buffer enable; notice that - enabling the double buffer disables the clock stretch. */ -#endif - bool enableBaudRateCtl; /*!< Enables/disables independent slave baud rate on SCL in very fast I2C modes. */ - uint16_t slaveAddress; /*!< A slave address configuration. */ - uint16_t upperAddress; /*!< A maximum boundary slave address used in a range matching mode. */ - i2c_slave_address_mode_t - addressingMode; /*!< An addressing mode configuration of i2c_slave_address_mode_config_t. */ - uint32_t sclStopHoldTime_ns; /*!< the delay from the rising edge of SCL (I2C clock) to the rising edge of SDA (I2C - data) while SCL is high (stop condition), SDA hold time and SCL start hold time - are also configured according to the SCL stop hold time. */ -} i2c_slave_config_t; - -/*! @brief I2C master handle typedef. */ -typedef struct _i2c_master_handle i2c_master_handle_t; - -/*! @brief I2C master transfer callback typedef. */ -typedef void (*i2c_master_transfer_callback_t)(I2C_Type *base, - i2c_master_handle_t *handle, - status_t status, - void *userData); - -/*! @brief I2C slave handle typedef. */ -typedef struct _i2c_slave_handle i2c_slave_handle_t; - -/*! @brief I2C master transfer structure. */ -typedef struct _i2c_master_transfer -{ - uint32_t flags; /*!< A transfer flag which controls the transfer. */ - uint8_t slaveAddress; /*!< 7-bit slave address. */ - i2c_direction_t direction; /*!< A transfer direction, read or write. */ - uint32_t subaddress; /*!< A sub address. Transferred MSB first. */ - uint8_t subaddressSize; /*!< A size of the command buffer. */ - uint8_t *volatile data; /*!< A transfer buffer. */ - volatile size_t dataSize; /*!< A transfer size. */ -} i2c_master_transfer_t; - -/*! @brief I2C master handle structure. */ -struct _i2c_master_handle -{ - i2c_master_transfer_t transfer; /*!< I2C master transfer copy. */ - size_t transferSize; /*!< Total bytes to be transferred. */ - uint8_t state; /*!< A transfer state maintained during transfer. */ - i2c_master_transfer_callback_t completionCallback; /*!< A callback function called when the transfer is finished. */ - void *userData; /*!< A callback parameter passed to the callback function. */ -}; - -/*! @brief I2C slave transfer structure. */ -typedef struct _i2c_slave_transfer -{ - i2c_slave_transfer_event_t event; /*!< A reason that the callback is invoked. */ - uint8_t *volatile data; /*!< A transfer buffer. */ - volatile size_t dataSize; /*!< A transfer size. */ - status_t completionStatus; /*!< Success or error code describing how the transfer completed. Only applies for - #kI2C_SlaveCompletionEvent. */ - size_t transferredCount; /*!< A number of bytes actually transferred since the start or since the last repeated - start. */ -} i2c_slave_transfer_t; - -/*! @brief I2C slave transfer callback typedef. */ -typedef void (*i2c_slave_transfer_callback_t)(I2C_Type *base, i2c_slave_transfer_t *xfer, void *userData); - -/*! @brief I2C slave handle structure. */ -struct _i2c_slave_handle -{ - volatile bool isBusy; /*!< Indicates whether a transfer is busy. */ - i2c_slave_transfer_t transfer; /*!< I2C slave transfer copy. */ - uint32_t eventMask; /*!< A mask of enabled events. */ - i2c_slave_transfer_callback_t callback; /*!< A callback function called at the transfer event. */ - void *userData; /*!< A callback parameter passed to the callback. */ -}; - -/******************************************************************************* - * API - ******************************************************************************/ - -#if defined(__cplusplus) -extern "C" { -#endif /*_cplusplus. */ - -/*! - * @name Initialization and deinitialization - * @{ - */ - -/*! - * @brief Initializes the I2C peripheral. Call this API to ungate the I2C clock - * and configure the I2C with master configuration. - * - * @note This API should be called at the beginning of the application. - * Otherwise, any operation to the I2C module can cause a hard fault - * because the clock is not enabled. The configuration structure can be custom filled - * or it can be set with default values by using the I2C_MasterGetDefaultConfig(). - * After calling this API, the master is ready to transfer. - * This is an example. - * @code - * i2c_master_config_t config = { - * .enableMaster = true, - * .enableStopHold = false, - * .highDrive = false, - * .baudRate_Bps = 100000, - * .glitchFilterWidth = 0 - * }; - * I2C_MasterInit(I2C0, &config, 12000000U); - * @endcode - * - * @param base I2C base pointer - * @param masterConfig A pointer to the master configuration structure - * @param srcClock_Hz I2C peripheral clock frequency in Hz - */ -void I2C_MasterInit(I2C_Type *base, const i2c_master_config_t *masterConfig, uint32_t srcClock_Hz); - -/*! - * @brief Initializes the I2C peripheral. Call this API to ungate the I2C clock - * and initialize the I2C with the slave configuration. - * - * @note This API should be called at the beginning of the application. - * Otherwise, any operation to the I2C module can cause a hard fault - * because the clock is not enabled. The configuration structure can partly be set - * with default values by I2C_SlaveGetDefaultConfig() or it can be custom filled by the user. - * This is an example. - * @code - * i2c_slave_config_t config = { - * .enableSlave = true, - * .enableGeneralCall = false, - * .addressingMode = kI2C_Address7bit, - * .slaveAddress = 0x1DU, - * .enableWakeUp = false, - * .enablehighDrive = false, - * .enableBaudRateCtl = false, - * .sclStopHoldTime_ns = 4000 - * }; - * I2C_SlaveInit(I2C0, &config, 12000000U); - * @endcode - * - * @param base I2C base pointer - * @param slaveConfig A pointer to the slave configuration structure - * @param srcClock_Hz I2C peripheral clock frequency in Hz - */ -void I2C_SlaveInit(I2C_Type *base, const i2c_slave_config_t *slaveConfig, uint32_t srcClock_Hz); - -/*! - * @brief De-initializes the I2C master peripheral. Call this API to gate the I2C clock. - * The I2C master module can't work unless the I2C_MasterInit is called. - * @param base I2C base pointer - */ -void I2C_MasterDeinit(I2C_Type *base); - -/*! - * @brief De-initializes the I2C slave peripheral. Calling this API gates the I2C clock. - * The I2C slave module can't work unless the I2C_SlaveInit is called to enable the clock. - * @param base I2C base pointer - */ -void I2C_SlaveDeinit(I2C_Type *base); - -/*! - * @brief Sets the I2C master configuration structure to default values. - * - * The purpose of this API is to get the configuration structure initialized for use in the I2C_MasterConfigure(). - * Use the initialized structure unchanged in the I2C_MasterConfigure() or modify - * the structure before calling the I2C_MasterConfigure(). - * This is an example. - * @code - * i2c_master_config_t config; - * I2C_MasterGetDefaultConfig(&config); - * @endcode - * @param masterConfig A pointer to the master configuration structure. -*/ -void I2C_MasterGetDefaultConfig(i2c_master_config_t *masterConfig); - -/*! - * @brief Sets the I2C slave configuration structure to default values. - * - * The purpose of this API is to get the configuration structure initialized for use in the I2C_SlaveConfigure(). - * Modify fields of the structure before calling the I2C_SlaveConfigure(). - * This is an example. - * @code - * i2c_slave_config_t config; - * I2C_SlaveGetDefaultConfig(&config); - * @endcode - * @param slaveConfig A pointer to the slave configuration structure. - */ -void I2C_SlaveGetDefaultConfig(i2c_slave_config_t *slaveConfig); - -/*! - * @brief Enables or disabless the I2C peripheral operation. - * - * @param base I2C base pointer - * @param enable Pass true to enable and false to disable the module. - */ -static inline void I2C_Enable(I2C_Type *base, bool enable) -{ - if (enable) - { - base->C1 |= I2C_C1_IICEN_MASK; - } - else - { - base->C1 &= ~I2C_C1_IICEN_MASK; - } -} - -/* @} */ - -/*! - * @name Status - * @{ - */ - -/*! - * @brief Gets the I2C status flags. - * - * @param base I2C base pointer - * @return status flag, use status flag to AND #_i2c_flags to get the related status. - */ -uint32_t I2C_MasterGetStatusFlags(I2C_Type *base); - -/*! - * @brief Gets the I2C status flags. - * - * @param base I2C base pointer - * @return status flag, use status flag to AND #_i2c_flags to get the related status. - */ -static inline uint32_t I2C_SlaveGetStatusFlags(I2C_Type *base) -{ - return I2C_MasterGetStatusFlags(base); -} - -/*! - * @brief Clears the I2C status flag state. - * - * The following status register flags can be cleared kI2C_ArbitrationLostFlag and kI2C_IntPendingFlag. - * - * @param base I2C base pointer - * @param statusMask The status flag mask, defined in type i2c_status_flag_t. - * The parameter can be any combination of the following values: - * @arg kI2C_StartDetectFlag (if available) - * @arg kI2C_StopDetectFlag (if available) - * @arg kI2C_ArbitrationLostFlag - * @arg kI2C_IntPendingFlagFlag - */ -static inline void I2C_MasterClearStatusFlags(I2C_Type *base, uint32_t statusMask) -{ -/* Must clear the STARTF / STOPF bits prior to clearing IICIF */ -#if defined(FSL_FEATURE_I2C_HAS_START_STOP_DETECT) && FSL_FEATURE_I2C_HAS_START_STOP_DETECT - if (statusMask & kI2C_StartDetectFlag) - { - /* Shift the odd-ball flags back into place. */ - base->FLT |= (uint8_t)(statusMask >> 8U); - } -#endif - -#ifdef I2C_HAS_STOP_DETECT - if (statusMask & kI2C_StopDetectFlag) - { - /* Shift the odd-ball flags back into place. */ - base->FLT |= (uint8_t)(statusMask >> 8U); - } -#endif - - base->S = (uint8_t)statusMask; -} - -/*! - * @brief Clears the I2C status flag state. - * - * The following status register flags can be cleared kI2C_ArbitrationLostFlag and kI2C_IntPendingFlag - * - * @param base I2C base pointer - * @param statusMask The status flag mask, defined in type i2c_status_flag_t. - * The parameter can be any combination of the following values: - * @arg kI2C_StartDetectFlag (if available) - * @arg kI2C_StopDetectFlag (if available) - * @arg kI2C_ArbitrationLostFlag - * @arg kI2C_IntPendingFlagFlag - */ -static inline void I2C_SlaveClearStatusFlags(I2C_Type *base, uint32_t statusMask) -{ - I2C_MasterClearStatusFlags(base, statusMask); -} - -/* @} */ - -/*! - * @name Interrupts - * @{ - */ - -/*! - * @brief Enables I2C interrupt requests. - * - * @param base I2C base pointer - * @param mask interrupt source - * The parameter can be combination of the following source if defined: - * @arg kI2C_GlobalInterruptEnable - * @arg kI2C_StopDetectInterruptEnable/kI2C_StartDetectInterruptEnable - * @arg kI2C_SdaTimeoutInterruptEnable - */ -void I2C_EnableInterrupts(I2C_Type *base, uint32_t mask); - -/*! - * @brief Disables I2C interrupt requests. - * - * @param base I2C base pointer - * @param mask interrupt source - * The parameter can be combination of the following source if defined: - * @arg kI2C_GlobalInterruptEnable - * @arg kI2C_StopDetectInterruptEnable/kI2C_StartDetectInterruptEnable - * @arg kI2C_SdaTimeoutInterruptEnable - */ -void I2C_DisableInterrupts(I2C_Type *base, uint32_t mask); - -/*! - * @name DMA Control - * @{ - */ -#if defined(FSL_FEATURE_I2C_HAS_DMA_SUPPORT) && FSL_FEATURE_I2C_HAS_DMA_SUPPORT -/*! - * @brief Enables/disables the I2C DMA interrupt. - * - * @param base I2C base pointer - * @param enable true to enable, false to disable -*/ -static inline void I2C_EnableDMA(I2C_Type *base, bool enable) -{ - if (enable) - { - base->C1 |= I2C_C1_DMAEN_MASK; - } - else - { - base->C1 &= ~I2C_C1_DMAEN_MASK; - } -} - -#endif /* FSL_FEATURE_I2C_HAS_DMA_SUPPORT */ - -/*! - * @brief Gets the I2C tx/rx data register address. This API is used to provide a transfer address - * for I2C DMA transfer configuration. - * - * @param base I2C base pointer - * @return data register address - */ -static inline uint32_t I2C_GetDataRegAddr(I2C_Type *base) -{ - return (uint32_t)(&(base->D)); -} - -/* @} */ -/*! - * @name Bus Operations - * @{ - */ - -/*! - * @brief Sets the I2C master transfer baud rate. - * - * @param base I2C base pointer - * @param baudRate_Bps the baud rate value in bps - * @param srcClock_Hz Source clock - */ -void I2C_MasterSetBaudRate(I2C_Type *base, uint32_t baudRate_Bps, uint32_t srcClock_Hz); - -/*! - * @brief Sends a START on the I2C bus. - * - * This function is used to initiate a new master mode transfer by sending the START signal. - * The slave address is sent following the I2C START signal. - * - * @param base I2C peripheral base pointer - * @param address 7-bit slave device address. - * @param direction Master transfer directions(transmit/receive). - * @retval kStatus_Success Successfully send the start signal. - * @retval kStatus_I2C_Busy Current bus is busy. - */ -status_t I2C_MasterStart(I2C_Type *base, uint8_t address, i2c_direction_t direction); - -/*! - * @brief Sends a STOP signal on the I2C bus. - * - * @retval kStatus_Success Successfully send the stop signal. - * @retval kStatus_I2C_Timeout Send stop signal failed, timeout. - */ -status_t I2C_MasterStop(I2C_Type *base); - -/*! - * @brief Sends a REPEATED START on the I2C bus. - * - * @param base I2C peripheral base pointer - * @param address 7-bit slave device address. - * @param direction Master transfer directions(transmit/receive). - * @retval kStatus_Success Successfully send the start signal. - * @retval kStatus_I2C_Busy Current bus is busy but not occupied by current I2C master. - */ -status_t I2C_MasterRepeatedStart(I2C_Type *base, uint8_t address, i2c_direction_t direction); - -/*! - * @brief Performs a polling send transaction on the I2C bus. - * - * @param base The I2C peripheral base pointer. - * @param txBuff The pointer to the data to be transferred. - * @param txSize The length in bytes of the data to be transferred. - * @param flags Transfer control flag to decide whether need to send a stop, use kI2C_TransferDefaultFlag -* to issue a stop and kI2C_TransferNoStop to not send a stop. - * @retval kStatus_Success Successfully complete the data transmission. - * @retval kStatus_I2C_ArbitrationLost Transfer error, arbitration lost. - * @retval kStataus_I2C_Nak Transfer error, receive NAK during transfer. - */ -status_t I2C_MasterWriteBlocking(I2C_Type *base, const uint8_t *txBuff, size_t txSize, uint32_t flags); - -/*! - * @brief Performs a polling receive transaction on the I2C bus. - * - * @note The I2C_MasterReadBlocking function stops the bus before reading the final byte. - * Without stopping the bus prior for the final read, the bus issues another read, resulting - * in garbage data being read into the data register. - * - * @param base I2C peripheral base pointer. - * @param rxBuff The pointer to the data to store the received data. - * @param rxSize The length in bytes of the data to be received. - * @param flags Transfer control flag to decide whether need to send a stop, use kI2C_TransferDefaultFlag -* to issue a stop and kI2C_TransferNoStop to not send a stop. - * @retval kStatus_Success Successfully complete the data transmission. - * @retval kStatus_I2C_Timeout Send stop signal failed, timeout. - */ -status_t I2C_MasterReadBlocking(I2C_Type *base, uint8_t *rxBuff, size_t rxSize, uint32_t flags); - -/*! - * @brief Performs a polling send transaction on the I2C bus. - * - * @param base The I2C peripheral base pointer. - * @param txBuff The pointer to the data to be transferred. - * @param txSize The length in bytes of the data to be transferred. - * @retval kStatus_Success Successfully complete the data transmission. - * @retval kStatus_I2C_ArbitrationLost Transfer error, arbitration lost. - * @retval kStataus_I2C_Nak Transfer error, receive NAK during transfer. - */ -status_t I2C_SlaveWriteBlocking(I2C_Type *base, const uint8_t *txBuff, size_t txSize); - -/*! - * @brief Performs a polling receive transaction on the I2C bus. - * - * @param base I2C peripheral base pointer. - * @param rxBuff The pointer to the data to store the received data. - * @param rxSize The length in bytes of the data to be received. - */ -void I2C_SlaveReadBlocking(I2C_Type *base, uint8_t *rxBuff, size_t rxSize); - -/*! - * @brief Performs a master polling transfer on the I2C bus. - * - * @note The API does not return until the transfer succeeds or fails due - * to arbitration lost or receiving a NAK. - * - * @param base I2C peripheral base address. - * @param xfer Pointer to the transfer structure. - * @retval kStatus_Success Successfully complete the data transmission. - * @retval kStatus_I2C_Busy Previous transmission still not finished. - * @retval kStatus_I2C_Timeout Transfer error, wait signal timeout. - * @retval kStatus_I2C_ArbitrationLost Transfer error, arbitration lost. - * @retval kStataus_I2C_Nak Transfer error, receive NAK during transfer. - */ -status_t I2C_MasterTransferBlocking(I2C_Type *base, i2c_master_transfer_t *xfer); - -/* @} */ - -/*! - * @name Transactional - * @{ - */ - -/*! - * @brief Initializes the I2C handle which is used in transactional functions. - * - * @param base I2C base pointer. - * @param handle pointer to i2c_master_handle_t structure to store the transfer state. - * @param callback pointer to user callback function. - * @param userData user parameter passed to the callback function. - */ -void I2C_MasterTransferCreateHandle(I2C_Type *base, - i2c_master_handle_t *handle, - i2c_master_transfer_callback_t callback, - void *userData); - -/*! - * @brief Performs a master interrupt non-blocking transfer on the I2C bus. - * - * @note Calling the API returns immediately after transfer initiates. The user needs - * to call I2C_MasterGetTransferCount to poll the transfer status to check whether - * the transfer is finished. If the return status is not kStatus_I2C_Busy, the transfer - * is finished. - * - * @param base I2C base pointer. - * @param handle pointer to i2c_master_handle_t structure which stores the transfer state. - * @param xfer pointer to i2c_master_transfer_t structure. - * @retval kStatus_Success Successfully start the data transmission. - * @retval kStatus_I2C_Busy Previous transmission still not finished. - * @retval kStatus_I2C_Timeout Transfer error, wait signal timeout. - */ -status_t I2C_MasterTransferNonBlocking(I2C_Type *base, i2c_master_handle_t *handle, i2c_master_transfer_t *xfer); - -/*! - * @brief Gets the master transfer status during a interrupt non-blocking transfer. - * - * @param base I2C base pointer. - * @param handle pointer to i2c_master_handle_t structure which stores the transfer state. - * @param count Number of bytes transferred so far by the non-blocking transaction. - * @retval kStatus_InvalidArgument count is Invalid. - * @retval kStatus_Success Successfully return the count. - */ -status_t I2C_MasterTransferGetCount(I2C_Type *base, i2c_master_handle_t *handle, size_t *count); - -/*! - * @brief Aborts an interrupt non-blocking transfer early. - * - * @note This API can be called at any time when an interrupt non-blocking transfer initiates - * to abort the transfer early. - * - * @param base I2C base pointer. - * @param handle pointer to i2c_master_handle_t structure which stores the transfer state - */ -void I2C_MasterTransferAbort(I2C_Type *base, i2c_master_handle_t *handle); - -/*! - * @brief Master interrupt handler. - * - * @param base I2C base pointer. - * @param i2cHandle pointer to i2c_master_handle_t structure. - */ -void I2C_MasterTransferHandleIRQ(I2C_Type *base, void *i2cHandle); - -/*! - * @brief Initializes the I2C handle which is used in transactional functions. - * - * @param base I2C base pointer. - * @param handle pointer to i2c_slave_handle_t structure to store the transfer state. - * @param callback pointer to user callback function. - * @param userData user parameter passed to the callback function. - */ -void I2C_SlaveTransferCreateHandle(I2C_Type *base, - i2c_slave_handle_t *handle, - i2c_slave_transfer_callback_t callback, - void *userData); - -/*! - * @brief Starts accepting slave transfers. - * - * Call this API after calling the I2C_SlaveInit() and I2C_SlaveTransferCreateHandle() to start processing - * transactions driven by an I2C master. The slave monitors the I2C bus and passes events to the - * callback that was passed into the call to I2C_SlaveTransferCreateHandle(). The callback is always invoked - * from the interrupt context. - * - * The set of events received by the callback is customizable. To do so, set the @a eventMask parameter to - * the OR'd combination of #i2c_slave_transfer_event_t enumerators for the events you wish to receive. - * The #kI2C_SlaveTransmitEvent and #kLPI2C_SlaveReceiveEvent events are always enabled and do not need - * to be included in the mask. Alternatively, pass 0 to get a default set of only the transmit and - * receive events that are always enabled. In addition, the #kI2C_SlaveAllEvents constant is provided as - * a convenient way to enable all events. - * - * @param base The I2C peripheral base address. - * @param handle Pointer to #i2c_slave_handle_t structure which stores the transfer state. - * @param eventMask Bit mask formed by OR'ing together #i2c_slave_transfer_event_t enumerators to specify - * which events to send to the callback. Other accepted values are 0 to get a default set of - * only the transmit and receive events, and #kI2C_SlaveAllEvents to enable all events. - * - * @retval #kStatus_Success Slave transfers were successfully started. - * @retval #kStatus_I2C_Busy Slave transfers have already been started on this handle. - */ -status_t I2C_SlaveTransferNonBlocking(I2C_Type *base, i2c_slave_handle_t *handle, uint32_t eventMask); - -/*! - * @brief Aborts the slave transfer. - * - * @note This API can be called at any time to stop slave for handling the bus events. - * - * @param base I2C base pointer. - * @param handle pointer to i2c_slave_handle_t structure which stores the transfer state. - */ -void I2C_SlaveTransferAbort(I2C_Type *base, i2c_slave_handle_t *handle); - -/*! - * @brief Gets the slave transfer remaining bytes during a interrupt non-blocking transfer. - * - * @param base I2C base pointer. - * @param handle pointer to i2c_slave_handle_t structure. - * @param count Number of bytes transferred so far by the non-blocking transaction. - * @retval kStatus_InvalidArgument count is Invalid. - * @retval kStatus_Success Successfully return the count. - */ -status_t I2C_SlaveTransferGetCount(I2C_Type *base, i2c_slave_handle_t *handle, size_t *count); - -/*! - * @brief Slave interrupt handler. - * - * @param base I2C base pointer. - * @param i2cHandle pointer to i2c_slave_handle_t structure which stores the transfer state - */ -void I2C_SlaveTransferHandleIRQ(I2C_Type *base, void *i2cHandle); - -/* @} */ -#if defined(__cplusplus) -} -#endif /*_cplusplus. */ -/*@}*/ - -#endif /* _FSL_I2C_H_*/ diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_i2c_edma.c b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_i2c_edma.c deleted file mode 100644 index 28a415e075a..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_i2c_edma.c +++ /dev/null @@ -1,568 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "fsl_i2c_edma.h" - -/******************************************************************************* - * Definitions - ******************************************************************************/ - -/*base, false); - - /* Send stop if kI2C_TransferNoStop flag is not asserted. */ - if (!(i2cPrivateHandle->handle->transfer.flags & kI2C_TransferNoStopFlag)) - { - if (i2cPrivateHandle->handle->transfer.direction == kI2C_Read) - { - /* Change to send NAK at the last byte. */ - i2cPrivateHandle->base->C1 |= I2C_C1_TXAK_MASK; - - /* Wait the last data to be received. */ - while (!(i2cPrivateHandle->base->S & kI2C_TransferCompleteFlag)) - { - } - - /* Send stop signal. */ - result = I2C_MasterStop(i2cPrivateHandle->base); - - /* Read the last data byte. */ - *(i2cPrivateHandle->handle->transfer.data + i2cPrivateHandle->handle->transfer.dataSize - 1) = - i2cPrivateHandle->base->D; - } - else - { - /* Wait the last data to be sent. */ - while (!(i2cPrivateHandle->base->S & kI2C_TransferCompleteFlag)) - { - } - - /* Send stop signal. */ - result = I2C_MasterStop(i2cPrivateHandle->base); - } - } - else - { - if (i2cPrivateHandle->handle->transfer.direction == kI2C_Read) - { - /* Change to send NAK at the last byte. */ - i2cPrivateHandle->base->C1 |= I2C_C1_TXAK_MASK; - - /* Wait the last data to be received. */ - while (!(i2cPrivateHandle->base->S & kI2C_TransferCompleteFlag)) - { - } - - /* Change direction to send. */ - i2cPrivateHandle->base->C1 |= I2C_C1_TX_MASK; - - /* Read the last data byte. */ - *(i2cPrivateHandle->handle->transfer.data + i2cPrivateHandle->handle->transfer.dataSize - 1) = - i2cPrivateHandle->base->D; - } - } - - i2cPrivateHandle->handle->state = kIdleState; - - if (i2cPrivateHandle->handle->completionCallback) - { - i2cPrivateHandle->handle->completionCallback(i2cPrivateHandle->base, i2cPrivateHandle->handle, result, - i2cPrivateHandle->handle->userData); - } -} - -static status_t I2C_CheckAndClearError(I2C_Type *base, uint32_t status) -{ - status_t result = kStatus_Success; - - /* Check arbitration lost. */ - if (status & kI2C_ArbitrationLostFlag) - { - /* Clear arbitration lost flag. */ - base->S = kI2C_ArbitrationLostFlag; - result = kStatus_I2C_ArbitrationLost; - } - /* Check NAK */ - else if (status & kI2C_ReceiveNakFlag) - { - result = kStatus_I2C_Nak; - } - else - { - } - - return result; -} - -static status_t I2C_InitTransferStateMachineEDMA(I2C_Type *base, - i2c_master_edma_handle_t *handle, - i2c_master_transfer_t *xfer) -{ - assert(handle); - assert(xfer); - - status_t result = kStatus_Success; - - if (handle->state != kIdleState) - { - return kStatus_I2C_Busy; - } - else - { - i2c_direction_t direction = xfer->direction; - - /* Init the handle member. */ - handle->transfer = *xfer; - - /* Save total transfer size. */ - handle->transferSize = xfer->dataSize; - - handle->state = kTransferDataState; - - /* Clear all status before transfer. */ - I2C_MasterClearStatusFlags(base, kClearFlags); - - /* Change to send write address when it's a read operation with command. */ - if ((xfer->subaddressSize > 0) && (xfer->direction == kI2C_Read)) - { - direction = kI2C_Write; - } - - /* If repeated start is requested, send repeated start. */ - if (handle->transfer.flags & kI2C_TransferRepeatedStartFlag) - { - result = I2C_MasterRepeatedStart(base, handle->transfer.slaveAddress, direction); - } - else /* For normal transfer, send start. */ - { - result = I2C_MasterStart(base, handle->transfer.slaveAddress, direction); - } - - if (result) - { - return result; - } - - while (!(base->S & kI2C_IntPendingFlag)) - { - } - - /* Check if there's transfer error. */ - result = I2C_CheckAndClearError(base, base->S); - - /* Return if error. */ - if (result) - { - if (result == kStatus_I2C_Nak) - { - result = kStatus_I2C_Addr_Nak; - - if (I2C_MasterStop(base) != kStatus_Success) - { - result = kStatus_I2C_Timeout; - } - - if (handle->completionCallback) - { - (handle->completionCallback)(base, handle, result, handle->userData); - } - } - - return result; - } - - /* Send subaddress. */ - if (handle->transfer.subaddressSize) - { - do - { - /* Clear interrupt pending flag. */ - base->S = kI2C_IntPendingFlag; - - handle->transfer.subaddressSize--; - base->D = ((handle->transfer.subaddress) >> (8 * handle->transfer.subaddressSize)); - - /* Wait until data transfer complete. */ - while (!(base->S & kI2C_IntPendingFlag)) - { - } - - /* Check if there's transfer error. */ - result = I2C_CheckAndClearError(base, base->S); - - if (result) - { - return result; - } - - } while ((handle->transfer.subaddressSize > 0) && (result == kStatus_Success)); - - if (handle->transfer.direction == kI2C_Read) - { - /* Clear pending flag. */ - base->S = kI2C_IntPendingFlag; - - /* Send repeated start and slave address. */ - result = I2C_MasterRepeatedStart(base, handle->transfer.slaveAddress, kI2C_Read); - - if (result) - { - return result; - } - - /* Wait until data transfer complete. */ - while (!(base->S & kI2C_IntPendingFlag)) - { - } - - /* Check if there's transfer error. */ - result = I2C_CheckAndClearError(base, base->S); - - if (result) - { - return result; - } - } - } - - /* Clear pending flag. */ - base->S = kI2C_IntPendingFlag; - } - - return result; -} - -static void I2C_MasterTransferEDMAConfig(I2C_Type *base, i2c_master_edma_handle_t *handle) -{ - edma_transfer_config_t transfer_config; - - if (handle->transfer.direction == kI2C_Read) - { - transfer_config.srcAddr = (uint32_t)I2C_GetDataRegAddr(base); - transfer_config.destAddr = (uint32_t)(handle->transfer.data); - transfer_config.majorLoopCounts = (handle->transfer.dataSize - 1); - transfer_config.srcTransferSize = kEDMA_TransferSize1Bytes; - transfer_config.srcOffset = 0; - transfer_config.destTransferSize = kEDMA_TransferSize1Bytes; - transfer_config.destOffset = 1; - transfer_config.minorLoopBytes = 1; - } - else - { - transfer_config.srcAddr = (uint32_t)(handle->transfer.data + 1); - transfer_config.destAddr = (uint32_t)I2C_GetDataRegAddr(base); - transfer_config.majorLoopCounts = (handle->transfer.dataSize - 1); - transfer_config.srcTransferSize = kEDMA_TransferSize1Bytes; - transfer_config.srcOffset = 1; - transfer_config.destTransferSize = kEDMA_TransferSize1Bytes; - transfer_config.destOffset = 0; - transfer_config.minorLoopBytes = 1; - } - - /* Store the initially configured eDMA minor byte transfer count into the I2C handle */ - handle->nbytes = transfer_config.minorLoopBytes; - - EDMA_SubmitTransfer(handle->dmaHandle, &transfer_config); - EDMA_StartTransfer(handle->dmaHandle); -} - -void I2C_MasterCreateEDMAHandle(I2C_Type *base, - i2c_master_edma_handle_t *handle, - i2c_master_edma_transfer_callback_t callback, - void *userData, - edma_handle_t *edmaHandle) -{ - assert(handle); - assert(edmaHandle); - - uint32_t instance = I2C_GetInstance(base); - - /* Zero handle. */ - memset(handle, 0, sizeof(*handle)); - - /* Set the user callback and userData. */ - handle->completionCallback = callback; - handle->userData = userData; - - /* Set the base for the handle. */ - base = base; - - /* Set the handle for EDMA. */ - handle->dmaHandle = edmaHandle; - - s_edmaPrivateHandle[instance].base = base; - s_edmaPrivateHandle[instance].handle = handle; - - EDMA_SetCallback(edmaHandle, (edma_callback)I2C_MasterTransferCallbackEDMA, &s_edmaPrivateHandle[instance]); -} - -status_t I2C_MasterTransferEDMA(I2C_Type *base, i2c_master_edma_handle_t *handle, i2c_master_transfer_t *xfer) -{ - assert(handle); - assert(xfer); - - status_t result; - uint8_t tmpReg; - volatile uint8_t dummy = 0; - - /* Add this to avoid build warning. */ - dummy++; - - /* Disable dma xfer. */ - I2C_EnableDMA(base, false); - - /* Send address and command buffer(if there is), until senddata phase or receive data phase. */ - result = I2C_InitTransferStateMachineEDMA(base, handle, xfer); - - if (result) - { - /* Send stop if received Nak. */ - if (result == kStatus_I2C_Nak) - { - if (I2C_MasterStop(base) != kStatus_Success) - { - result = kStatus_I2C_Timeout; - } - } - - /* Reset the state to idle state. */ - handle->state = kIdleState; - - return result; - } - - /* Configure dma transfer. */ - /* For i2c send, need to send 1 byte first to trigger the dma, for i2c read, - need to send stop before reading the last byte, so the dma transfer size should - be (xSize - 1). */ - if (handle->transfer.dataSize > 1) - { - I2C_MasterTransferEDMAConfig(base, handle); - if (handle->transfer.direction == kI2C_Read) - { - /* Change direction for receive. */ - base->C1 &= ~(I2C_C1_TX_MASK | I2C_C1_TXAK_MASK); - - /* Read dummy to release the bus. */ - dummy = base->D; - - /* Enabe dma transfer. */ - I2C_EnableDMA(base, true); - } - else - { - /* Enabe dma transfer. */ - I2C_EnableDMA(base, true); - - /* Send the first data. */ - base->D = *handle->transfer.data; - } - } - else /* If transfer size is 1, use polling method. */ - { - if (handle->transfer.direction == kI2C_Read) - { - tmpReg = base->C1; - - /* Change direction to Rx. */ - tmpReg &= ~I2C_C1_TX_MASK; - - /* Configure send NAK */ - tmpReg |= I2C_C1_TXAK_MASK; - - base->C1 = tmpReg; - - /* Read dummy to release the bus. */ - dummy = base->D; - } - else - { - base->D = *handle->transfer.data; - } - - /* Wait until data transfer complete. */ - while (!(base->S & kI2C_IntPendingFlag)) - { - } - - /* Clear pending flag. */ - base->S = kI2C_IntPendingFlag; - - /* Send stop if kI2C_TransferNoStop flag is not asserted. */ - if (!(handle->transfer.flags & kI2C_TransferNoStopFlag)) - { - result = I2C_MasterStop(base); - } - else - { - /* Change direction to send. */ - base->C1 |= I2C_C1_TX_MASK; - } - - /* Read the last byte of data. */ - if (handle->transfer.direction == kI2C_Read) - { - *handle->transfer.data = base->D; - } - - /* Reset the state to idle. */ - handle->state = kIdleState; - } - - return result; -} - -status_t I2C_MasterTransferGetCountEDMA(I2C_Type *base, i2c_master_edma_handle_t *handle, size_t *count) -{ - assert(handle->dmaHandle); - - if (!count) - { - return kStatus_InvalidArgument; - } - - if (kIdleState != handle->state) - { - *count = (handle->transferSize - - (uint32_t)handle->nbytes * - EDMA_GetRemainingMajorLoopCount(handle->dmaHandle->base, handle->dmaHandle->channel)); - } - else - { - *count = handle->transferSize; - } - - return kStatus_Success; -} - -void I2C_MasterTransferAbortEDMA(I2C_Type *base, i2c_master_edma_handle_t *handle) -{ - EDMA_AbortTransfer(handle->dmaHandle); - - /* Disable dma transfer. */ - I2C_EnableDMA(base, false); - - /* Reset the state to idle. */ - handle->state = kIdleState; -} diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_i2c_edma.h b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_i2c_edma.h deleted file mode 100644 index 40cb648ea99..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_i2c_edma.h +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -#ifndef _FSL_I2C_DMA_H_ -#define _FSL_I2C_DMA_H_ - -#include "fsl_i2c.h" -#include "fsl_dmamux.h" -#include "fsl_edma.h" - -/*! - * @addtogroup i2c_edma_driver - * @{ - */ - -/******************************************************************************* - * Definitions - ******************************************************************************/ - -/*! @brief I2C master eDMA handle typedef. */ -typedef struct _i2c_master_edma_handle i2c_master_edma_handle_t; - -/*! @brief I2C master eDMA transfer callback typedef. */ -typedef void (*i2c_master_edma_transfer_callback_t)(I2C_Type *base, - i2c_master_edma_handle_t *handle, - status_t status, - void *userData); - -/*! @brief I2C master eDMA transfer structure. */ -struct _i2c_master_edma_handle -{ - i2c_master_transfer_t transfer; /*!< I2C master transfer structure. */ - size_t transferSize; /*!< Total bytes to be transferred. */ - uint8_t nbytes; /*!< eDMA minor byte transfer count initially configured. */ - uint8_t state; /*!< I2C master transfer status. */ - edma_handle_t *dmaHandle; /*!< The eDMA handler used. */ - i2c_master_edma_transfer_callback_t - completionCallback; /*!< A callback function called after the eDMA transfer is finished. */ - void *userData; /*!< A callback parameter passed to the callback function. */ -}; - -/******************************************************************************* - * API - ******************************************************************************/ - -#if defined(__cplusplus) -extern "C" { -#endif /*_cplusplus. */ - -/*! - * @name I2C Block eDMA Transfer Operation - * @{ - */ - -/*! - * @brief Initializes the I2C handle which is used in transcational functions. - * - * @param base I2C peripheral base address. - * @param handle A pointer to the i2c_master_edma_handle_t structure. - * @param callback A pointer to the user callback function. - * @param userData A user parameter passed to the callback function. - * @param edmaHandle eDMA handle pointer. - */ -void I2C_MasterCreateEDMAHandle(I2C_Type *base, - i2c_master_edma_handle_t *handle, - i2c_master_edma_transfer_callback_t callback, - void *userData, - edma_handle_t *edmaHandle); - -/*! - * @brief Performs a master eDMA non-blocking transfer on the I2C bus. - * - * @param base I2C peripheral base address. - * @param handle A pointer to the i2c_master_edma_handle_t structure. - * @param xfer A pointer to the transfer structure of i2c_master_transfer_t. - * @retval kStatus_Success Sucessfully completed the data transmission. - * @retval kStatus_I2C_Busy A previous transmission is still not finished. - * @retval kStatus_I2C_Timeout Transfer error, waits for a signal timeout. - * @retval kStatus_I2C_ArbitrationLost Transfer error, arbitration lost. - * @retval kStataus_I2C_Nak Transfer error, receive NAK during transfer. - */ -status_t I2C_MasterTransferEDMA(I2C_Type *base, i2c_master_edma_handle_t *handle, i2c_master_transfer_t *xfer); - -/*! - * @brief Gets a master transfer status during the eDMA non-blocking transfer. - * - * @param base I2C peripheral base address. - * @param handle A pointer to the i2c_master_edma_handle_t structure. - * @param count A number of bytes transferred by the non-blocking transaction. - */ -status_t I2C_MasterTransferGetCountEDMA(I2C_Type *base, i2c_master_edma_handle_t *handle, size_t *count); - -/*! - * @brief Aborts a master eDMA non-blocking transfer early. - * - * @param base I2C peripheral base address. - * @param handle A pointer to the i2c_master_edma_handle_t structure. - */ -void I2C_MasterTransferAbortEDMA(I2C_Type *base, i2c_master_edma_handle_t *handle); - -/* @} */ -#if defined(__cplusplus) -} -#endif /*_cplusplus. */ -/*@}*/ -#endif /*_FSL_I2C_DMA_H_*/ diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_llwu.c b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_llwu.c deleted file mode 100644 index 74b1001a88a..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_llwu.c +++ /dev/null @@ -1,404 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "fsl_llwu.h" - -#if (defined(FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN) && FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN) -void LLWU_SetExternalWakeupPinMode(LLWU_Type *base, uint32_t pinIndex, llwu_external_pin_mode_t pinMode) -{ -#if (defined(FSL_FEATURE_LLWU_REG_BITWIDTH) && (FSL_FEATURE_LLWU_REG_BITWIDTH == 32)) - volatile uint32_t *regBase; - uint32_t regOffset; - uint32_t reg; - - switch (pinIndex >> 4U) - { - case 0U: - regBase = &base->PE1; - break; -#if (defined(FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN) && (FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN > 16)) - case 1U: - regBase = &base->PE2; - break; -#endif - default: - regBase = NULL; - break; - } -#else - volatile uint8_t *regBase; - uint8_t regOffset; - uint8_t reg; - switch (pinIndex >> 2U) - { - case 0U: - regBase = &base->PE1; - break; - case 1U: - regBase = &base->PE2; - break; -#if (defined(FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN) && (FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN > 8)) - case 2U: - regBase = &base->PE3; - break; -#endif -#if (defined(FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN) && (FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN > 12)) - case 3U: - regBase = &base->PE4; - break; -#endif -#if (defined(FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN) && (FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN > 16)) - case 4U: - regBase = &base->PE5; - break; -#endif -#if (defined(FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN) && (FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN > 20)) - case 5U: - regBase = &base->PE6; - break; -#endif -#if (defined(FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN) && (FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN > 24)) - case 6U: - regBase = &base->PE7; - break; -#endif -#if (defined(FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN) && (FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN > 28)) - case 7U: - regBase = &base->PE8; - break; -#endif - default: - regBase = NULL; - break; - } -#endif /* FSL_FEATURE_LLWU_REG_BITWIDTH == 32 */ - - if (regBase) - { - reg = *regBase; -#if (defined(FSL_FEATURE_LLWU_REG_BITWIDTH) && (FSL_FEATURE_LLWU_REG_BITWIDTH == 32)) - regOffset = ((pinIndex & 0x0FU) << 1U); -#else - regOffset = ((pinIndex & 0x03U) << 1U); -#endif - reg &= ~(0x3U << regOffset); - reg |= ((uint32_t)pinMode << regOffset); - *regBase = reg; - } -} - -bool LLWU_GetExternalWakeupPinFlag(LLWU_Type *base, uint32_t pinIndex) -{ -#if (defined(FSL_FEATURE_LLWU_REG_BITWIDTH) && (FSL_FEATURE_LLWU_REG_BITWIDTH == 32)) - return (bool)(base->PF & (1U << pinIndex)); -#else - volatile uint8_t *regBase; - - switch (pinIndex >> 3U) - { -#if (defined(FSL_FEATURE_LLWU_HAS_PF) && FSL_FEATURE_LLWU_HAS_PF) - case 0U: - regBase = &base->PF1; - break; -#if (defined(FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN) && (FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN > 8)) - case 1U: - regBase = &base->PF2; - break; -#endif /* FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN */ -#if (defined(FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN) && (FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN > 16)) - case 2U: - regBase = &base->PF3; - break; -#endif /* FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN */ -#if (defined(FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN) && (FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN > 24)) - case 3U: - regBase = &base->PF4; - break; -#endif /* FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN */ -#else - case 0U: - regBase = &base->F1; - break; -#if (defined(FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN) && (FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN > 8)) - case 1U: - regBase = &base->F2; - break; -#endif /* FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN */ -#if (defined(FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN) && (FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN > 16)) - case 2U: - regBase = &base->F3; - break; -#endif /* FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN */ -#if (defined(FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN) && (FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN > 24)) - case 3U: - regBase = &base->F4; - break; -#endif /* FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN */ -#endif /* FSL_FEATURE_LLWU_HAS_PF */ - default: - regBase = NULL; - break; - } - - if (regBase) - { - return (bool)(*regBase & (1U << pinIndex % 8)); - } - else - { - return false; - } -#endif /* FSL_FEATURE_LLWU_REG_BITWIDTH */ -} - -void LLWU_ClearExternalWakeupPinFlag(LLWU_Type *base, uint32_t pinIndex) -{ -#if (defined(FSL_FEATURE_LLWU_REG_BITWIDTH) && (FSL_FEATURE_LLWU_REG_BITWIDTH == 32)) - base->PF = (1U << pinIndex); -#else - volatile uint8_t *regBase; - switch (pinIndex >> 3U) - { -#if (defined(FSL_FEATURE_LLWU_HAS_PF) && FSL_FEATURE_LLWU_HAS_PF) - case 0U: - regBase = &base->PF1; - break; -#if (defined(FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN) && (FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN > 8)) - case 1U: - regBase = &base->PF2; - break; -#endif /* FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN */ -#if (defined(FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN) && (FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN > 16)) - case 2U: - regBase = &base->PF3; - break; -#endif /* FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN */ -#if (defined(FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN) && (FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN > 24)) - case 3U: - regBase = &base->PF4; - break; -#endif /* FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN */ -#else - case 0U: - regBase = &base->F1; - break; -#if (defined(FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN) && (FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN > 8)) - case 1U: - regBase = &base->F2; - break; -#endif /* FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN */ -#if (defined(FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN) && (FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN > 16)) - case 2U: - regBase = &base->F3; - break; -#endif /* FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN */ -#if (defined(FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN) && (FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN > 24)) - case 3U: - regBase = &base->F4; - break; -#endif /* FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN */ -#endif /* FSL_FEATURE_LLWU_HAS_PF */ - default: - regBase = NULL; - break; - } - if (regBase) - { - *regBase = (1U << pinIndex % 8U); - } -#endif /* FSL_FEATURE_LLWU_REG_BITWIDTH */ -} -#endif /* FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN */ - -#if (defined(FSL_FEATURE_LLWU_HAS_PIN_FILTER) && FSL_FEATURE_LLWU_HAS_PIN_FILTER) -void LLWU_SetPinFilterMode(LLWU_Type *base, uint32_t filterIndex, llwu_external_pin_filter_mode_t filterMode) -{ -#if (defined(FSL_FEATURE_LLWU_REG_BITWIDTH) && (FSL_FEATURE_LLWU_REG_BITWIDTH == 32)) - uint32_t reg; - - reg = base->FILT; - reg &= ~((LLWU_FILT_FILTSEL1_MASK | LLWU_FILT_FILTE1_MASK) << (filterIndex * 8U - 1U)); - reg |= (((filterMode.pinIndex << LLWU_FILT_FILTSEL1_SHIFT) | (filterMode.filterMode << LLWU_FILT_FILTE1_SHIFT) - /* Clear the Filter Detect Flag */ - | LLWU_FILT_FILTF1_MASK) - << (filterIndex * 8U - 1U)); - base->FILT = reg; -#else - volatile uint8_t *regBase; - uint8_t reg; - - switch (filterIndex) - { - case 1: - regBase = &base->FILT1; - break; -#if (defined(FSL_FEATURE_LLWU_HAS_PIN_FILTER) && (FSL_FEATURE_LLWU_HAS_PIN_FILTER > 1)) - case 2: - regBase = &base->FILT2; - break; -#endif /* FSL_FEATURE_LLWU_HAS_PIN_FILTER */ -#if (defined(FSL_FEATURE_LLWU_HAS_PIN_FILTER) && (FSL_FEATURE_LLWU_HAS_PIN_FILTER > 2)) - case 3: - regBase = &base->FILT3; - break; -#endif /* FSL_FEATURE_LLWU_HAS_PIN_FILTER */ -#if (defined(FSL_FEATURE_LLWU_HAS_PIN_FILTER) && (FSL_FEATURE_LLWU_HAS_PIN_FILTER > 3)) - case 4: - regBase = &base->FILT4; - break; -#endif /* FSL_FEATURE_LLWU_HAS_PIN_FILTER */ - default: - regBase = NULL; - break; - } - - if (regBase) - { - reg = *regBase; - reg &= ~(LLWU_FILT1_FILTSEL_MASK | LLWU_FILT1_FILTE_MASK); - reg |= ((uint32_t)filterMode.pinIndex << LLWU_FILT1_FILTSEL_SHIFT); - reg |= ((uint32_t)filterMode.filterMode << LLWU_FILT1_FILTE_SHIFT); - /* Clear the Filter Detect Flag */ - reg |= LLWU_FILT1_FILTF_MASK; - *regBase = reg; - } -#endif /* FSL_FEATURE_LLWU_REG_BITWIDTH */ -} - -bool LLWU_GetPinFilterFlag(LLWU_Type *base, uint32_t filterIndex) -{ -#if (defined(FSL_FEATURE_LLWU_REG_BITWIDTH) && (FSL_FEATURE_LLWU_REG_BITWIDTH == 32)) - return (bool)(base->FILT & (1U << (filterIndex * 8U - 1))); -#else - bool status = false; - - switch (filterIndex) - { - case 1: - status = (base->FILT1 & LLWU_FILT1_FILTF_MASK); - break; -#if (defined(FSL_FEATURE_LLWU_HAS_PIN_FILTER) && (FSL_FEATURE_LLWU_HAS_PIN_FILTER > 1)) - case 2: - status = (base->FILT2 & LLWU_FILT2_FILTF_MASK); - break; -#endif /* FSL_FEATURE_LLWU_HAS_PIN_FILTER */ -#if (defined(FSL_FEATURE_LLWU_HAS_PIN_FILTER) && (FSL_FEATURE_LLWU_HAS_PIN_FILTER > 2)) - case 3: - status = (base->FILT3 & LLWU_FILT3_FILTF_MASK); - break; -#endif /* FSL_FEATURE_LLWU_HAS_PIN_FILTER */ -#if (defined(FSL_FEATURE_LLWU_HAS_PIN_FILTER) && (FSL_FEATURE_LLWU_HAS_PIN_FILTER > 3)) - case 4: - status = (base->FILT4 & LLWU_FILT4_FILTF_MASK); - break; -#endif /* FSL_FEATURE_LLWU_HAS_PIN_FILTER */ - default: - break; - } - - return status; -#endif /* FSL_FEATURE_LLWU_REG_BITWIDTH */ -} - -void LLWU_ClearPinFilterFlag(LLWU_Type *base, uint32_t filterIndex) -{ -#if (defined(FSL_FEATURE_LLWU_REG_BITWIDTH) && (FSL_FEATURE_LLWU_REG_BITWIDTH == 32)) - uint32_t reg; - - reg = base->FILT; - switch (filterIndex) - { - case 1: - reg |= LLWU_FILT_FILTF1_MASK; - break; - case 2: - reg |= LLWU_FILT_FILTF2_MASK; - break; - case 3: - reg |= LLWU_FILT_FILTF3_MASK; - break; - case 4: - reg |= LLWU_FILT_FILTF4_MASK; - break; - default: - break; - } - base->FILT = reg; -#else - volatile uint8_t *regBase; - uint8_t reg; - - switch (filterIndex) - { - case 1: - regBase = &base->FILT1; - break; -#if (defined(FSL_FEATURE_LLWU_HAS_PIN_FILTER) && (FSL_FEATURE_LLWU_HAS_PIN_FILTER > 1)) - case 2: - regBase = &base->FILT2; - break; -#endif /* FSL_FEATURE_LLWU_HAS_PIN_FILTER */ -#if (defined(FSL_FEATURE_LLWU_HAS_PIN_FILTER) && (FSL_FEATURE_LLWU_HAS_PIN_FILTER > 2)) - case 3: - regBase = &base->FILT3; - break; -#endif /* FSL_FEATURE_LLWU_HAS_PIN_FILTER */ -#if (defined(FSL_FEATURE_LLWU_HAS_PIN_FILTER) && (FSL_FEATURE_LLWU_HAS_PIN_FILTER > 3)) - case 4: - regBase = &base->FILT4; - break; -#endif /* FSL_FEATURE_LLWU_HAS_PIN_FILTER */ - default: - regBase = NULL; - break; - } - - if (regBase) - { - reg = *regBase; - reg |= LLWU_FILT1_FILTF_MASK; - *regBase = reg; - } -#endif /* FSL_FEATURE_LLWU_REG_BITWIDTH */ -} -#endif /* FSL_FEATURE_LLWU_HAS_PIN_FILTER */ - -#if (defined(FSL_FEATURE_LLWU_HAS_RESET_ENABLE) && FSL_FEATURE_LLWU_HAS_RESET_ENABLE) -void LLWU_SetResetPinMode(LLWU_Type *base, bool pinEnable, bool enableInLowLeakageMode) -{ - uint8_t reg; - - reg = base->RST; - reg &= ~(LLWU_RST_LLRSTE_MASK | LLWU_RST_RSTFILT_MASK); - reg |= - (((uint32_t)pinEnable << LLWU_RST_LLRSTE_SHIFT) | ((uint32_t)enableInLowLeakageMode << LLWU_RST_RSTFILT_SHIFT)); - base->RST = reg; -} -#endif /* FSL_FEATURE_LLWU_HAS_RESET_ENABLE */ diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_llwu.h b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_llwu.h deleted file mode 100644 index d5a0037bb58..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_llwu.h +++ /dev/null @@ -1,320 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -#ifndef _FSL_LLWU_H_ -#define _FSL_LLWU_H_ - -#include "fsl_common.h" - -/*! @addtogroup llwu */ -/*! @{ */ - - -/******************************************************************************* - * Definitions - ******************************************************************************/ - -/*! @name Driver version */ -/*@{*/ -/*! @brief LLWU driver version 2.0.1. */ -#define FSL_LLWU_DRIVER_VERSION (MAKE_VERSION(2, 0, 1)) -/*@}*/ - -/*! - * @brief External input pin control modes - */ -typedef enum _llwu_external_pin_mode -{ - kLLWU_ExternalPinDisable = 0U, /*!< Pin disabled as a wakeup input. */ - kLLWU_ExternalPinRisingEdge = 1U, /*!< Pin enabled with the rising edge detection. */ - kLLWU_ExternalPinFallingEdge = 2U, /*!< Pin enabled with the falling edge detection.*/ - kLLWU_ExternalPinAnyEdge = 3U /*!< Pin enabled with any change detection. */ -} llwu_external_pin_mode_t; - -/*! - * @brief Digital filter control modes - */ -typedef enum _llwu_pin_filter_mode -{ - kLLWU_PinFilterDisable = 0U, /*!< Filter disabled. */ - kLLWU_PinFilterRisingEdge = 1U, /*!< Filter positive edge detection.*/ - kLLWU_PinFilterFallingEdge = 2U, /*!< Filter negative edge detection.*/ - kLLWU_PinFilterAnyEdge = 3U /*!< Filter any edge detection. */ -} llwu_pin_filter_mode_t; - -#if (defined(FSL_FEATURE_LLWU_HAS_VERID) && FSL_FEATURE_LLWU_HAS_VERID) -/*! - * @brief IP version ID definition. - */ -typedef struct _llwu_version_id -{ - uint16_t feature; /*!< A feature specification number. */ - uint8_t minor; /*!< The minor version number. */ - uint8_t major; /*!< The major version number. */ -} llwu_version_id_t; -#endif /* FSL_FEATURE_LLWU_HAS_VERID */ - -#if (defined(FSL_FEATURE_LLWU_HAS_PARAM) && FSL_FEATURE_LLWU_HAS_PARAM) -/*! - * @brief IP parameter definition. - */ -typedef struct _llwu_param -{ - uint8_t filters; /*!< A number of the pin filter. */ - uint8_t dmas; /*!< A number of the wakeup DMA. */ - uint8_t modules; /*!< A number of the wakeup module. */ - uint8_t pins; /*!< A number of the wake up pin. */ -} llwu_param_t; -#endif /* FSL_FEATURE_LLWU_HAS_PARAM */ - -#if (defined(FSL_FEATURE_LLWU_HAS_PIN_FILTER) && FSL_FEATURE_LLWU_HAS_PIN_FILTER) -/*! - * @brief An external input pin filter control structure - */ -typedef struct _llwu_external_pin_filter_mode -{ - uint32_t pinIndex; /*!< A pin number */ - llwu_pin_filter_mode_t filterMode; /*!< Filter mode */ -} llwu_external_pin_filter_mode_t; -#endif /* FSL_FEATURE_LLWU_HAS_PIN_FILTER */ - -/******************************************************************************* - * API - ******************************************************************************/ - -#if defined(__cplusplus) -extern "C" { -#endif - -/*! - * @name Low-Leakage Wakeup Unit Control APIs - * @{ - */ - -#if (defined(FSL_FEATURE_LLWU_HAS_VERID) && FSL_FEATURE_LLWU_HAS_VERID) -/*! - * @brief Gets the LLWU version ID. - * - * This function gets the LLWU version ID, including the major version number, - * the minor version number, and the feature specification number. - * - * @param base LLWU peripheral base address. - * @param versionId A pointer to the version ID structure. - */ -static inline void LLWU_GetVersionId(LLWU_Type *base, llwu_version_id_t *versionId) -{ - *((uint32_t *)versionId) = base->VERID; -} -#endif /* FSL_FEATURE_LLWU_HAS_VERID */ - -#if (defined(FSL_FEATURE_LLWU_HAS_PARAM) && FSL_FEATURE_LLWU_HAS_PARAM) -/*! - * @brief Gets the LLWU parameter. - * - * This function gets the LLWU parameter, including a wakeup pin number, a module - * number, a DMA number, and a pin filter number. - * - * @param base LLWU peripheral base address. - * @param param A pointer to the LLWU parameter structure. - */ -static inline void LLWU_GetParam(LLWU_Type *base, llwu_param_t *param) -{ - *((uint32_t *)param) = base->PARAM; -} -#endif /* FSL_FEATURE_LLWU_HAS_PARAM */ - -#if (defined(FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN) && FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN) -/*! - * @brief Sets the external input pin source mode. - * - * This function sets the external input pin source mode that is used - * as a wake up source. - * - * @param base LLWU peripheral base address. - * @param pinIndex A pin index to be enabled as an external wakeup source starting from 1. - * @param pinMode A pin configuration mode defined in the llwu_external_pin_modes_t. - */ -void LLWU_SetExternalWakeupPinMode(LLWU_Type *base, uint32_t pinIndex, llwu_external_pin_mode_t pinMode); - -/*! - * @brief Gets the external wakeup source flag. - * - * This function checks the external pin flag to detect whether the MCU is - * woken up by the specific pin. - * - * @param base LLWU peripheral base address. - * @param pinIndex A pin index, which starts from 1. - * @return True if the specific pin is a wakeup source. - */ -bool LLWU_GetExternalWakeupPinFlag(LLWU_Type *base, uint32_t pinIndex); - -/*! - * @brief Clears the external wakeup source flag. - * - * This function clears the external wakeup source flag for a specific pin. - * - * @param base LLWU peripheral base address. - * @param pinIndex A pin index, which starts from 1. - */ -void LLWU_ClearExternalWakeupPinFlag(LLWU_Type *base, uint32_t pinIndex); -#endif /* FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN */ - -#if (defined(FSL_FEATURE_LLWU_HAS_INTERNAL_MODULE) && FSL_FEATURE_LLWU_HAS_INTERNAL_MODULE) -/*! - * @brief Enables/disables the internal module source. - * - * This function enables/disables the internal module source mode that is used - * as a wake up source. - * - * @param base LLWU peripheral base address. - * @param moduleIndex A module index to be enabled as an internal wakeup source starting from 1. - * @param enable An enable or a disable setting - */ -static inline void LLWU_EnableInternalModuleInterruptWakup(LLWU_Type *base, uint32_t moduleIndex, bool enable) -{ - if (enable) - { - base->ME |= 1U << moduleIndex; - } - else - { - base->ME &= ~(1U << moduleIndex); - } -} - -/*! - * @brief Gets the external wakeup source flag. - * - * This function checks the external pin flag to detect whether the system is - * woken up by the specific pin. - * - * @param base LLWU peripheral base address. - * @param moduleIndex A module index, which starts from 1. - * @return True if the specific pin is a wake up source. - */ -static inline bool LLWU_GetInternalWakeupModuleFlag(LLWU_Type *base, uint32_t moduleIndex) -{ -#if (defined(FSL_FEATURE_LLWU_HAS_MF) && FSL_FEATURE_LLWU_HAS_MF) -#if (defined(FSL_FEATURE_LLWU_REG_BITWIDTH) && (FSL_FEATURE_LLWU_REG_BITWIDTH == 32)) - return (bool)(base->MF & (1U << moduleIndex)); -#else - return (bool)(base->MF5 & (1U << moduleIndex)); -#endif /* FSL_FEATURE_LLWU_REG_BITWIDTH */ -#else -#if (defined(FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN) && (FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN > 16)) - return (bool)(base->F5 & (1U << moduleIndex)); -#else -#if (defined(FSL_FEATURE_LLWU_HAS_PF) && FSL_FEATURE_LLWU_HAS_PF) - return (bool)(base->PF3 & (1U << moduleIndex)); -#else - return (bool)(base->F3 & (1U << moduleIndex)); -#endif /* FSL_FEATURE_LLWU_HAS_PF */ -#endif /* FSL_FEATURE_LLWU_HAS_EXTERNAL_PIN */ -#endif /* FSL_FEATURE_LLWU_HAS_MF */ -} -#endif /* FSL_FEATURE_LLWU_HAS_INTERNAL_MODULE */ - -#if (defined(FSL_FEATURE_LLWU_HAS_DMA_ENABLE_REG) && FSL_FEATURE_LLWU_HAS_DMA_ENABLE_REG) -/*! - * @brief Enables/disables the internal module DMA wakeup source. - * - * This function enables/disables the internal DMA that is used as a wake up source. - * - * @param base LLWU peripheral base address. - * @param moduleIndex An internal module index which is used as a DMA request source, starting from 1. - * @param enable Enable or disable the DMA request source - */ -static inline void LLWU_EnableInternalModuleDmaRequestWakup(LLWU_Type *base, uint32_t moduleIndex, bool enable) -{ - if (enable) - { - base->DE |= 1U << moduleIndex; - } - else - { - base->DE &= ~(1U << moduleIndex); - } -} -#endif /* FSL_FEATURE_LLWU_HAS_DMA_ENABLE_REG */ - -#if (defined(FSL_FEATURE_LLWU_HAS_PIN_FILTER) && FSL_FEATURE_LLWU_HAS_PIN_FILTER) -/*! - * @brief Sets the pin filter configuration. - * - * This function sets the pin filter configuration. - * - * @param base LLWU peripheral base address. - * @param filterIndex A pin filter index used to enable/disable the digital filter, starting from 1. - * @param filterMode A filter mode configuration - */ -void LLWU_SetPinFilterMode(LLWU_Type *base, uint32_t filterIndex, llwu_external_pin_filter_mode_t filterMode); - -/*! - * @brief Gets the pin filter configuration. - * - * This function gets the pin filter flag. - * - * @param base LLWU peripheral base address. - * @param filterIndex A pin filter index, which starts from 1. - * @return True if the flag is a source of the existing low-leakage power mode. - */ -bool LLWU_GetPinFilterFlag(LLWU_Type *base, uint32_t filterIndex); - -/*! - * @brief Clears the pin filter configuration. - * - * This function clears the pin filter flag. - * - * @param base LLWU peripheral base address. - * @param filterIndex A pin filter index to clear the flag, starting from 1. - */ -void LLWU_ClearPinFilterFlag(LLWU_Type *base, uint32_t filterIndex); - -#endif /* FSL_FEATURE_LLWU_HAS_PIN_FILTER */ - -#if (defined(FSL_FEATURE_LLWU_HAS_RESET_ENABLE) && FSL_FEATURE_LLWU_HAS_RESET_ENABLE) -/*! - * @brief Sets the reset pin mode. - * - * This function determines how the reset pin is used as a low leakage mode exit source. - * - * @param pinEnable Enable reset the pin filter - * @param pinFilterEnable Specify whether the pin filter is enabled in Low-Leakage power mode. - */ -void LLWU_SetResetPinMode(LLWU_Type *base, bool pinEnable, bool enableInLowLeakageMode); -#endif /* FSL_FEATURE_LLWU_HAS_RESET_ENABLE */ - -/*@}*/ - -#if defined(__cplusplus) -} -#endif - -/*! @}*/ -#endif /* _FSL_LLWU_H_*/ diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_lptmr.c b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_lptmr.c deleted file mode 100644 index 67b3b9785cf..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_lptmr.c +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "fsl_lptmr.h" - -/******************************************************************************* - * Prototypes - ******************************************************************************/ -/*! - * @brief Gets the instance from the base address to be used to gate or ungate the module clock - * - * @param base LPTMR peripheral base address - * - * @return The LPTMR instance - */ -static uint32_t LPTMR_GetInstance(LPTMR_Type *base); - -/******************************************************************************* - * Variables - ******************************************************************************/ -/*! @brief Pointers to LPTMR bases for each instance. */ -static LPTMR_Type *const s_lptmrBases[] = LPTMR_BASE_PTRS; - -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) -/*! @brief Pointers to LPTMR clocks for each instance. */ -static const clock_ip_name_t s_lptmrClocks[] = LPTMR_CLOCKS; - -#if defined(LPTMR_PERIPH_CLOCKS) -/* Array of LPTMR functional clock name. */ -static const clock_ip_name_t s_lptmrPeriphClocks[] = LPTMR_PERIPH_CLOCKS; -#endif - -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ - -/******************************************************************************* - * Code - ******************************************************************************/ -static uint32_t LPTMR_GetInstance(LPTMR_Type *base) -{ - uint32_t instance; - - /* Find the instance index from base address mappings. */ - for (instance = 0; instance < ARRAY_SIZE(s_lptmrBases); instance++) - { - if (s_lptmrBases[instance] == base) - { - break; - } - } - - assert(instance < ARRAY_SIZE(s_lptmrBases)); - - return instance; -} - -void LPTMR_Init(LPTMR_Type *base, const lptmr_config_t *config) -{ - assert(config); - -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) - - uint32_t instance = LPTMR_GetInstance(base); - - /* Ungate the LPTMR clock*/ - CLOCK_EnableClock(s_lptmrClocks[instance]); -#if defined(LPTMR_PERIPH_CLOCKS) - CLOCK_EnableClock(s_lptmrPeriphClocks[instance]); -#endif - -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ - - /* Configure the timers operation mode and input pin setup */ - base->CSR = (LPTMR_CSR_TMS(config->timerMode) | LPTMR_CSR_TFC(config->enableFreeRunning) | - LPTMR_CSR_TPP(config->pinPolarity) | LPTMR_CSR_TPS(config->pinSelect)); - - /* Configure the prescale value and clock source */ - base->PSR = (LPTMR_PSR_PRESCALE(config->value) | LPTMR_PSR_PBYP(config->bypassPrescaler) | - LPTMR_PSR_PCS(config->prescalerClockSource)); -} - -void LPTMR_Deinit(LPTMR_Type *base) -{ - /* Disable the LPTMR and reset the internal logic */ - base->CSR &= ~LPTMR_CSR_TEN_MASK; -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) - - uint32_t instance = LPTMR_GetInstance(base); - - /* Gate the LPTMR clock*/ - CLOCK_DisableClock(s_lptmrClocks[instance]); -#if defined(LPTMR_PERIPH_CLOCKS) - CLOCK_DisableClock(s_lptmrPeriphClocks[instance]); -#endif - -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ -} - -void LPTMR_GetDefaultConfig(lptmr_config_t *config) -{ - assert(config); - - /* Use time counter mode */ - config->timerMode = kLPTMR_TimerModeTimeCounter; - /* Use input 0 as source in pulse counter mode */ - config->pinSelect = kLPTMR_PinSelectInput_0; - /* Pulse input pin polarity is active-high */ - config->pinPolarity = kLPTMR_PinPolarityActiveHigh; - /* Counter resets whenever TCF flag is set */ - config->enableFreeRunning = false; - /* Bypass the prescaler */ - config->bypassPrescaler = true; - /* LPTMR clock source */ - config->prescalerClockSource = kLPTMR_PrescalerClock_1; - /* Divide the prescaler clock by 2 */ - config->value = kLPTMR_Prescale_Glitch_0; -} diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_lptmr.h b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_lptmr.h deleted file mode 100644 index 6cc909b3148..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_lptmr.h +++ /dev/null @@ -1,370 +0,0 @@ -/* - * Copyright (c) 2016, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -#ifndef _FSL_LPTMR_H_ -#define _FSL_LPTMR_H_ - -#include "fsl_common.h" - -/*! - * @addtogroup lptmr - * @{ - */ - -/******************************************************************************* - * Definitions - ******************************************************************************/ - -/*! @name Driver version */ -/*@{*/ -#define FSL_LPTMR_DRIVER_VERSION (MAKE_VERSION(2, 0, 1)) /*!< Version 2.0.1 */ -/*@}*/ - -/*! @brief LPTMR pin selection used in pulse counter mode.*/ -typedef enum _lptmr_pin_select -{ - kLPTMR_PinSelectInput_0 = 0x0U, /*!< Pulse counter input 0 is selected */ - kLPTMR_PinSelectInput_1 = 0x1U, /*!< Pulse counter input 1 is selected */ - kLPTMR_PinSelectInput_2 = 0x2U, /*!< Pulse counter input 2 is selected */ - kLPTMR_PinSelectInput_3 = 0x3U /*!< Pulse counter input 3 is selected */ -} lptmr_pin_select_t; - -/*! @brief LPTMR pin polarity used in pulse counter mode.*/ -typedef enum _lptmr_pin_polarity -{ - kLPTMR_PinPolarityActiveHigh = 0x0U, /*!< Pulse Counter input source is active-high */ - kLPTMR_PinPolarityActiveLow = 0x1U /*!< Pulse Counter input source is active-low */ -} lptmr_pin_polarity_t; - -/*! @brief LPTMR timer mode selection.*/ -typedef enum _lptmr_timer_mode -{ - kLPTMR_TimerModeTimeCounter = 0x0U, /*!< Time Counter mode */ - kLPTMR_TimerModePulseCounter = 0x1U /*!< Pulse Counter mode */ -} lptmr_timer_mode_t; - -/*! @brief LPTMR prescaler/glitch filter values*/ -typedef enum _lptmr_prescaler_glitch_value -{ - kLPTMR_Prescale_Glitch_0 = 0x0U, /*!< Prescaler divide 2, glitch filter does not support this setting */ - kLPTMR_Prescale_Glitch_1 = 0x1U, /*!< Prescaler divide 4, glitch filter 2 */ - kLPTMR_Prescale_Glitch_2 = 0x2U, /*!< Prescaler divide 8, glitch filter 4 */ - kLPTMR_Prescale_Glitch_3 = 0x3U, /*!< Prescaler divide 16, glitch filter 8 */ - kLPTMR_Prescale_Glitch_4 = 0x4U, /*!< Prescaler divide 32, glitch filter 16 */ - kLPTMR_Prescale_Glitch_5 = 0x5U, /*!< Prescaler divide 64, glitch filter 32 */ - kLPTMR_Prescale_Glitch_6 = 0x6U, /*!< Prescaler divide 128, glitch filter 64 */ - kLPTMR_Prescale_Glitch_7 = 0x7U, /*!< Prescaler divide 256, glitch filter 128 */ - kLPTMR_Prescale_Glitch_8 = 0x8U, /*!< Prescaler divide 512, glitch filter 256 */ - kLPTMR_Prescale_Glitch_9 = 0x9U, /*!< Prescaler divide 1024, glitch filter 512*/ - kLPTMR_Prescale_Glitch_10 = 0xAU, /*!< Prescaler divide 2048 glitch filter 1024 */ - kLPTMR_Prescale_Glitch_11 = 0xBU, /*!< Prescaler divide 4096, glitch filter 2048 */ - kLPTMR_Prescale_Glitch_12 = 0xCU, /*!< Prescaler divide 8192, glitch filter 4096 */ - kLPTMR_Prescale_Glitch_13 = 0xDU, /*!< Prescaler divide 16384, glitch filter 8192 */ - kLPTMR_Prescale_Glitch_14 = 0xEU, /*!< Prescaler divide 32768, glitch filter 16384 */ - kLPTMR_Prescale_Glitch_15 = 0xFU /*!< Prescaler divide 65536, glitch filter 32768 */ -} lptmr_prescaler_glitch_value_t; - -/*! - * @brief LPTMR prescaler/glitch filter clock select. - * @note Clock connections are SoC-specific - */ -typedef enum _lptmr_prescaler_clock_select -{ - kLPTMR_PrescalerClock_0 = 0x0U, /*!< Prescaler/glitch filter clock 0 selected. */ - kLPTMR_PrescalerClock_1 = 0x1U, /*!< Prescaler/glitch filter clock 1 selected. */ - kLPTMR_PrescalerClock_2 = 0x2U, /*!< Prescaler/glitch filter clock 2 selected. */ - kLPTMR_PrescalerClock_3 = 0x3U, /*!< Prescaler/glitch filter clock 3 selected. */ -} lptmr_prescaler_clock_select_t; - -/*! @brief List of the LPTMR interrupts */ -typedef enum _lptmr_interrupt_enable -{ - kLPTMR_TimerInterruptEnable = LPTMR_CSR_TIE_MASK, /*!< Timer interrupt enable */ -} lptmr_interrupt_enable_t; - -/*! @brief List of the LPTMR status flags */ -typedef enum _lptmr_status_flags -{ - kLPTMR_TimerCompareFlag = LPTMR_CSR_TCF_MASK, /*!< Timer compare flag */ -} lptmr_status_flags_t; - -/*! - * @brief LPTMR config structure - * - * This structure holds the configuration settings for the LPTMR peripheral. To initialize this - * structure to reasonable defaults, call the LPTMR_GetDefaultConfig() function and pass a - * pointer to your configuration structure instance. - * - * The configuration struct can be made constant so it resides in flash. - */ -typedef struct _lptmr_config -{ - lptmr_timer_mode_t timerMode; /*!< Time counter mode or pulse counter mode */ - lptmr_pin_select_t pinSelect; /*!< LPTMR pulse input pin select; used only in pulse counter mode */ - lptmr_pin_polarity_t pinPolarity; /*!< LPTMR pulse input pin polarity; used only in pulse counter mode */ - bool enableFreeRunning; /*!< True: enable free running, counter is reset on overflow - False: counter is reset when the compare flag is set */ - bool bypassPrescaler; /*!< True: bypass prescaler; false: use clock from prescaler */ - lptmr_prescaler_clock_select_t prescalerClockSource; /*!< LPTMR clock source */ - lptmr_prescaler_glitch_value_t value; /*!< Prescaler or glitch filter value */ -} lptmr_config_t; - -/******************************************************************************* - * API - ******************************************************************************/ - -#if defined(__cplusplus) -extern "C" { -#endif - -/*! - * @name Initialization and deinitialization - * @{ - */ - -/*! - * @brief Ungates the LPTMR clock and configures the peripheral for a basic operation. - * - * @note This API should be called at the beginning of the application using the LPTMR driver. - * - * @param base LPTMR peripheral base address - * @param config A pointer to the LPTMR configuration structure. - */ -void LPTMR_Init(LPTMR_Type *base, const lptmr_config_t *config); - -/*! - * @brief Gates the LPTMR clock. - * - * @param base LPTMR peripheral base address - */ -void LPTMR_Deinit(LPTMR_Type *base); - -/*! - * @brief Fills in the LPTMR configuration structure with default settings. - * - * The default values are as follows. - * @code - * config->timerMode = kLPTMR_TimerModeTimeCounter; - * config->pinSelect = kLPTMR_PinSelectInput_0; - * config->pinPolarity = kLPTMR_PinPolarityActiveHigh; - * config->enableFreeRunning = false; - * config->bypassPrescaler = true; - * config->prescalerClockSource = kLPTMR_PrescalerClock_1; - * config->value = kLPTMR_Prescale_Glitch_0; - * @endcode - * @param config A pointer to the LPTMR configuration structure. - */ -void LPTMR_GetDefaultConfig(lptmr_config_t *config); - -/*! @}*/ - -/*! - * @name Interrupt Interface - * @{ - */ - -/*! - * @brief Enables the selected LPTMR interrupts. - * - * @param base LPTMR peripheral base address - * @param mask The interrupts to enable. This is a logical OR of members of the - * enumeration ::lptmr_interrupt_enable_t - */ -static inline void LPTMR_EnableInterrupts(LPTMR_Type *base, uint32_t mask) -{ - uint32_t reg = base->CSR; - - /* Clear the TCF bit so that we don't clear this w1c bit when writing back */ - reg &= ~(LPTMR_CSR_TCF_MASK); - reg |= mask; - base->CSR = reg; -} - -/*! - * @brief Disables the selected LPTMR interrupts. - * - * @param base LPTMR peripheral base address - * @param mask The interrupts to disable. This is a logical OR of members of the - * enumeration ::lptmr_interrupt_enable_t. - */ -static inline void LPTMR_DisableInterrupts(LPTMR_Type *base, uint32_t mask) -{ - uint32_t reg = base->CSR; - - /* Clear the TCF bit so that we don't clear this w1c bit when writing back */ - reg &= ~(LPTMR_CSR_TCF_MASK); - reg &= ~mask; - base->CSR = reg; -} - -/*! - * @brief Gets the enabled LPTMR interrupts. - * - * @param base LPTMR peripheral base address - * - * @return The enabled interrupts. This is the logical OR of members of the - * enumeration ::lptmr_interrupt_enable_t - */ -static inline uint32_t LPTMR_GetEnabledInterrupts(LPTMR_Type *base) -{ - return (base->CSR & LPTMR_CSR_TIE_MASK); -} - -/*! @}*/ - -/*! - * @name Status Interface - * @{ - */ - -/*! - * @brief Gets the LPTMR status flags. - * - * @param base LPTMR peripheral base address - * - * @return The status flags. This is the logical OR of members of the - * enumeration ::lptmr_status_flags_t - */ -static inline uint32_t LPTMR_GetStatusFlags(LPTMR_Type *base) -{ - return (base->CSR & LPTMR_CSR_TCF_MASK); -} - -/*! - * @brief Clears the LPTMR status flags. - * - * @param base LPTMR peripheral base address - * @param mask The status flags to clear. This is a logical OR of members of the - * enumeration ::lptmr_status_flags_t. - */ -static inline void LPTMR_ClearStatusFlags(LPTMR_Type *base, uint32_t mask) -{ - base->CSR |= mask; -} - -/*! @}*/ - -/*! - * @name Read and write the timer period - * @{ - */ - -/*! - * @brief Sets the timer period in units of count. - * - * Timers counts from 0 until it equals the count value set here. The count value is written to - * the CMR register. - * - * @note - * 1. The TCF flag is set with the CNR equals the count provided here and then increments. - * 2. Call the utility macros provided in the fsl_common.h to convert to ticks. - * - * @param base LPTMR peripheral base address - * @param ticks A timer period in units of ticks, which should be equal or greater than 1. - */ -static inline void LPTMR_SetTimerPeriod(LPTMR_Type *base, uint32_t ticks) -{ - assert(ticks > 0); - base->CMR = ticks - 1; -} - -/*! - * @brief Reads the current timer counting value. - * - * This function returns the real-time timer counting value in a range from 0 to a - * timer period. - * - * @note Call the utility macros provided in the fsl_common.h to convert ticks to usec or msec. - * - * @param base LPTMR peripheral base address - * - * @return The current counter value in ticks - */ -static inline uint32_t LPTMR_GetCurrentTimerCount(LPTMR_Type *base) -{ - /* Must first write any value to the CNR. This synchronizes and registers the current value - * of the CNR into a temporary register which can then be read - */ - base->CNR = 0U; - return (uint32_t)((base->CNR & LPTMR_CNR_COUNTER_MASK) >> LPTMR_CNR_COUNTER_SHIFT); -} - -/*! @}*/ - -/*! - * @name Timer Start and Stop - * @{ - */ - -/*! - * @brief Starts the timer. - * - * After calling this function, the timer counts up to the CMR register value. - * Each time the timer reaches the CMR value and then increments, it generates a - * trigger pulse and sets the timeout interrupt flag. An interrupt is also - * triggered if the timer interrupt is enabled. - * - * @param base LPTMR peripheral base address - */ -static inline void LPTMR_StartTimer(LPTMR_Type *base) -{ - uint32_t reg = base->CSR; - - /* Clear the TCF bit to avoid clearing the w1c bit when writing back. */ - reg &= ~(LPTMR_CSR_TCF_MASK); - reg |= LPTMR_CSR_TEN_MASK; - base->CSR = reg; -} - -/*! - * @brief Stops the timer. - * - * This function stops the timer and resets the timer's counter register. - * - * @param base LPTMR peripheral base address - */ -static inline void LPTMR_StopTimer(LPTMR_Type *base) -{ - uint32_t reg = base->CSR; - - /* Clear the TCF bit to avoid clearing the w1c bit when writing back. */ - reg &= ~(LPTMR_CSR_TCF_MASK); - reg &= ~LPTMR_CSR_TEN_MASK; - base->CSR = reg; -} - -/*! @}*/ - -#if defined(__cplusplus) -} -#endif - -/*! @}*/ - -#endif /* _FSL_LPTMR_H_ */ diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_pdb.c b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_pdb.c deleted file mode 100644 index 1fc4a9a486a..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_pdb.c +++ /dev/null @@ -1,141 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "fsl_pdb.h" - -/******************************************************************************* - * Prototypes - ******************************************************************************/ -/*! - * @brief Get instance number for PDB module. - * - * @param base PDB peripheral base address - */ -static uint32_t PDB_GetInstance(PDB_Type *base); - -/******************************************************************************* - * Variables - ******************************************************************************/ -/*! @brief Pointers to PDB bases for each instance. */ -static PDB_Type *const s_pdbBases[] = PDB_BASE_PTRS; -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) -/*! @brief Pointers to PDB clocks for each instance. */ -static const clock_ip_name_t s_pdbClocks[] = PDB_CLOCKS; -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ - -/******************************************************************************* - * Codes - ******************************************************************************/ -static uint32_t PDB_GetInstance(PDB_Type *base) -{ - uint32_t instance; - - /* Find the instance index from base address mappings. */ - for (instance = 0; instance < ARRAY_SIZE(s_pdbBases); instance++) - { - if (s_pdbBases[instance] == base) - { - break; - } - } - - assert(instance < ARRAY_SIZE(s_pdbBases)); - - return instance; -} - -void PDB_Init(PDB_Type *base, const pdb_config_t *config) -{ - assert(NULL != config); - - uint32_t tmp32; - -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) - /* Enable the clock. */ - CLOCK_EnableClock(s_pdbClocks[PDB_GetInstance(base)]); -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ - - /* Configure. */ - /* PDBx_SC. */ - tmp32 = base->SC & - ~(PDB_SC_LDMOD_MASK | PDB_SC_PRESCALER_MASK | PDB_SC_TRGSEL_MASK | PDB_SC_MULT_MASK | PDB_SC_CONT_MASK); - - tmp32 |= PDB_SC_LDMOD(config->loadValueMode) | PDB_SC_PRESCALER(config->prescalerDivider) | - PDB_SC_TRGSEL(config->triggerInputSource) | PDB_SC_MULT(config->dividerMultiplicationFactor); - if (config->enableContinuousMode) - { - tmp32 |= PDB_SC_CONT_MASK; - } - base->SC = tmp32; - - PDB_Enable(base, true); /* Enable the PDB module. */ -} - -void PDB_Deinit(PDB_Type *base) -{ - PDB_Enable(base, false); /* Disable the PDB module. */ - -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) - /* Disable the clock. */ - CLOCK_DisableClock(s_pdbClocks[PDB_GetInstance(base)]); -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ -} - -void PDB_GetDefaultConfig(pdb_config_t *config) -{ - assert(NULL != config); - - config->loadValueMode = kPDB_LoadValueImmediately; - config->prescalerDivider = kPDB_PrescalerDivider1; - config->dividerMultiplicationFactor = kPDB_DividerMultiplicationFactor1; - config->triggerInputSource = kPDB_TriggerSoftware; - config->enableContinuousMode = false; -} - -#if defined(FSL_FEATURE_PDB_HAS_DAC) && FSL_FEATURE_PDB_HAS_DAC -void PDB_SetDACTriggerConfig(PDB_Type *base, uint32_t channel, pdb_dac_trigger_config_t *config) -{ - assert(channel < PDB_INTC_COUNT); - assert(NULL != config); - - uint32_t tmp32 = 0U; - - /* PDBx_DACINTC. */ - if (config->enableExternalTriggerInput) - { - tmp32 |= PDB_INTC_EXT_MASK; - } - if (config->enableIntervalTrigger) - { - tmp32 |= PDB_INTC_TOE_MASK; - } - base->DAC[channel].INTC = tmp32; -} -#endif /* FSL_FEATURE_PDB_HAS_DAC */ diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_pdb.h b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_pdb.h deleted file mode 100644 index 3dec9463462..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_pdb.h +++ /dev/null @@ -1,576 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef _FSL_PDB_H_ -#define _FSL_PDB_H_ - -#include "fsl_common.h" - -/*! - * @addtogroup pdb - * @{ - */ - - -/******************************************************************************* - * Definitions - ******************************************************************************/ - -/*! @name Driver version */ -/*@{*/ -/*! @brief PDB driver version 2.0.1. */ -#define FSL_PDB_DRIVER_VERSION (MAKE_VERSION(2, 0, 1)) -/*@}*/ - -/*! - * @brief PDB flags. - */ -enum _pdb_status_flags -{ - kPDB_LoadOKFlag = PDB_SC_LDOK_MASK, /*!< This flag is automatically cleared when the values in buffers are - loaded into the internal registers after the LDOK bit is set or the - PDBEN is cleared. */ - kPDB_DelayEventFlag = PDB_SC_PDBIF_MASK, /*!< PDB timer delay event flag. */ -}; - -/*! - * @brief PDB ADC PreTrigger channel flags. - */ -enum _pdb_adc_pretrigger_flags -{ - /* PDB PreTrigger channel match flags. */ - kPDB_ADCPreTriggerChannel0Flag = PDB_S_CF(1U << 0), /*!< Pre-trigger 0 flag. */ - kPDB_ADCPreTriggerChannel1Flag = PDB_S_CF(1U << 1), /*!< Pre-trigger 1 flag. */ -#if (PDB_DLY_COUNT2 > 2) - kPDB_ADCPreTriggerChannel2Flag = PDB_S_CF(1U << 2), /*!< Pre-trigger 2 flag. */ - kPDB_ADCPreTriggerChannel3Flag = PDB_S_CF(1U << 3), /*!< Pre-trigger 3 flag. */ -#endif /* PDB_DLY_COUNT2 > 2 */ -#if (PDB_DLY_COUNT2 > 4) - kPDB_ADCPreTriggerChannel4Flag = PDB_S_CF(1U << 4), /*!< Pre-trigger 4 flag. */ - kPDB_ADCPreTriggerChannel5Flag = PDB_S_CF(1U << 5), /*!< Pre-trigger 5 flag. */ - kPDB_ADCPreTriggerChannel6Flag = PDB_S_CF(1U << 6), /*!< Pre-trigger 6 flag. */ - kPDB_ADCPreTriggerChannel7Flag = PDB_S_CF(1U << 7), /*!< Pre-trigger 7 flag. */ -#endif /* PDB_DLY_COUNT2 > 4 */ - - /* PDB PreTrigger channel error flags. */ - kPDB_ADCPreTriggerChannel0ErrorFlag = PDB_S_ERR(1U << 0), /*!< Pre-trigger 0 Error. */ - kPDB_ADCPreTriggerChannel1ErrorFlag = PDB_S_ERR(1U << 1), /*!< Pre-trigger 1 Error. */ -#if (PDB_DLY_COUNT2 > 2) - kPDB_ADCPreTriggerChannel2ErrorFlag = PDB_S_ERR(1U << 2), /*!< Pre-trigger 2 Error. */ - kPDB_ADCPreTriggerChannel3ErrorFlag = PDB_S_ERR(1U << 3), /*!< Pre-trigger 3 Error. */ -#endif /* PDB_DLY_COUNT2 > 2 */ -#if (PDB_DLY_COUNT2 > 4) - kPDB_ADCPreTriggerChannel4ErrorFlag = PDB_S_ERR(1U << 4), /*!< Pre-trigger 4 Error. */ - kPDB_ADCPreTriggerChannel5ErrorFlag = PDB_S_ERR(1U << 5), /*!< Pre-trigger 5 Error. */ - kPDB_ADCPreTriggerChannel6ErrorFlag = PDB_S_ERR(1U << 6), /*!< Pre-trigger 6 Error. */ - kPDB_ADCPreTriggerChannel7ErrorFlag = PDB_S_ERR(1U << 7), /*!< Pre-trigger 7 Error. */ -#endif /* PDB_DLY_COUNT2 > 4 */ -}; - -/*! - * @brief PDB buffer interrupts. - */ -enum _pdb_interrupt_enable -{ - kPDB_SequenceErrorInterruptEnable = PDB_SC_PDBEIE_MASK, /*!< PDB sequence error interrupt enable. */ - kPDB_DelayInterruptEnable = PDB_SC_PDBIE_MASK, /*!< PDB delay interrupt enable. */ -}; - -/*! - * @brief PDB load value mode. - * - * Selects the mode to load the internal values after doing the load operation (write 1 to PDBx_SC[LDOK]). - * These values are for the following operations. - * - PDB counter (PDBx_MOD, PDBx_IDLY) - * - ADC trigger (PDBx_CHnDLYm) - * - DAC trigger (PDBx_DACINTx) - * - CMP trigger (PDBx_POyDLY) - */ -typedef enum _pdb_load_value_mode -{ - kPDB_LoadValueImmediately = 0U, /*!< Load immediately after 1 is written to LDOK. */ - kPDB_LoadValueOnCounterOverflow = 1U, /*!< Load when the PDB counter overflows (reaches the MOD - register value). */ - kPDB_LoadValueOnTriggerInput = 2U, /*!< Load a trigger input event is detected. */ - kPDB_LoadValueOnCounterOverflowOrTriggerInput = 3U, /*!< Load either when the PDB counter overflows or a trigger - input is detected. */ -} pdb_load_value_mode_t; - -/*! - * @brief Prescaler divider. - * - * Counting uses the peripheral clock divided by multiplication factor selected by times of MULT. - */ -typedef enum _pdb_prescaler_divider -{ - kPDB_PrescalerDivider1 = 0U, /*!< Divider x1. */ - kPDB_PrescalerDivider2 = 1U, /*!< Divider x2. */ - kPDB_PrescalerDivider4 = 2U, /*!< Divider x4. */ - kPDB_PrescalerDivider8 = 3U, /*!< Divider x8. */ - kPDB_PrescalerDivider16 = 4U, /*!< Divider x16. */ - kPDB_PrescalerDivider32 = 5U, /*!< Divider x32. */ - kPDB_PrescalerDivider64 = 6U, /*!< Divider x64. */ - kPDB_PrescalerDivider128 = 7U, /*!< Divider x128. */ -} pdb_prescaler_divider_t; - -/*! - * @brief Multiplication factor select for prescaler. - * - * Selects the multiplication factor of the prescaler divider for the counter clock. - */ -typedef enum _pdb_divider_multiplication_factor -{ - kPDB_DividerMultiplicationFactor1 = 0U, /*!< Multiplication factor is 1. */ - kPDB_DividerMultiplicationFactor10 = 1U, /*!< Multiplication factor is 10. */ - kPDB_DividerMultiplicationFactor20 = 2U, /*!< Multiplication factor is 20. */ - kPDB_DividerMultiplicationFactor40 = 3U, /*!< Multiplication factor is 40. */ -} pdb_divider_multiplication_factor_t; - -/*! - * @brief Trigger input source - * - * Selects the trigger input source for the PDB. The trigger input source can be internal or external (EXTRG pin), or - * the software trigger. See chip configuration details for the actual PDB input trigger connections. - */ -typedef enum _pdb_trigger_input_source -{ - kPDB_TriggerInput0 = 0U, /*!< Trigger-In 0. */ - kPDB_TriggerInput1 = 1U, /*!< Trigger-In 1. */ - kPDB_TriggerInput2 = 2U, /*!< Trigger-In 2. */ - kPDB_TriggerInput3 = 3U, /*!< Trigger-In 3. */ - kPDB_TriggerInput4 = 4U, /*!< Trigger-In 4. */ - kPDB_TriggerInput5 = 5U, /*!< Trigger-In 5. */ - kPDB_TriggerInput6 = 6U, /*!< Trigger-In 6. */ - kPDB_TriggerInput7 = 7U, /*!< Trigger-In 7. */ - kPDB_TriggerInput8 = 8U, /*!< Trigger-In 8. */ - kPDB_TriggerInput9 = 9U, /*!< Trigger-In 9. */ - kPDB_TriggerInput10 = 10U, /*!< Trigger-In 10. */ - kPDB_TriggerInput11 = 11U, /*!< Trigger-In 11. */ - kPDB_TriggerInput12 = 12U, /*!< Trigger-In 12. */ - kPDB_TriggerInput13 = 13U, /*!< Trigger-In 13. */ - kPDB_TriggerInput14 = 14U, /*!< Trigger-In 14. */ - kPDB_TriggerSoftware = 15U, /*!< Trigger-In 15, software trigger. */ -} pdb_trigger_input_source_t; - -/*! - * @brief PDB module configuration. - */ -typedef struct _pdb_config -{ - pdb_load_value_mode_t loadValueMode; /*!< Select the load value mode. */ - pdb_prescaler_divider_t prescalerDivider; /*!< Select the prescaler divider. */ - pdb_divider_multiplication_factor_t dividerMultiplicationFactor; /*!< Multiplication factor select for prescaler. */ - pdb_trigger_input_source_t triggerInputSource; /*!< Select the trigger input source. */ - bool enableContinuousMode; /*!< Enable the PDB operation in Continuous mode.*/ -} pdb_config_t; - -/*! - * @brief PDB ADC Pre-trigger configuration. - */ -typedef struct _pdb_adc_pretrigger_config -{ - uint32_t enablePreTriggerMask; /*!< PDB Channel Pre-trigger Enable. */ - uint32_t enableOutputMask; /*!< PDB Channel Pre-trigger Output Select. - PDB channel's corresponding pre-trigger asserts when the counter - reaches the channel delay register. */ - uint32_t enableBackToBackOperationMask; /*!< PDB Channel pre-trigger Back-to-Back Operation Enable. - Back-to-back operation enables the ADC conversions complete to trigger - the next PDB channel pre-trigger and trigger output, so that the ADC - conversions can be triggered on next set of configuration and results - registers.*/ -} pdb_adc_pretrigger_config_t; - -/*! - * @brief PDB DAC trigger configuration. - */ -typedef struct _pdb_dac_trigger_config -{ - bool enableExternalTriggerInput; /*!< Enables the external trigger for DAC interval counter. */ - bool enableIntervalTrigger; /*!< Enables the DAC interval trigger. */ -} pdb_dac_trigger_config_t; - -/******************************************************************************* - * API - ******************************************************************************/ -#if defined(__cplusplus) -extern "C" { -#endif - -/*! - * @name Initialization - * @{ - */ - -/*! - * @brief Initializes the PDB module. - * - * This function initializes the PDB module. The operations included are as follows. - * - Enable the clock for PDB instance. - * - Configure the PDB module. - * - Enable the PDB module. - * - * @param base PDB peripheral base address. - * @param config Pointer to the configuration structure. See "pdb_config_t". - */ -void PDB_Init(PDB_Type *base, const pdb_config_t *config); - -/*! - * @brief De-initializes the PDB module. - * - * @param base PDB peripheral base address. - */ -void PDB_Deinit(PDB_Type *base); - -/*! - * @brief Initializes the PDB user configuration structure. - * - * This function initializes the user configuration structure to a default value. The default values are as follows. - * @code - * config->loadValueMode = kPDB_LoadValueImmediately; - * config->prescalerDivider = kPDB_PrescalerDivider1; - * config->dividerMultiplicationFactor = kPDB_DividerMultiplicationFactor1; - * config->triggerInputSource = kPDB_TriggerSoftware; - * config->enableContinuousMode = false; - * @endcode - * @param config Pointer to configuration structure. See "pdb_config_t". - */ -void PDB_GetDefaultConfig(pdb_config_t *config); - -/*! - * @brief Enables the PDB module. - * - * @param base PDB peripheral base address. - * @param enable Enable the module or not. - */ -static inline void PDB_Enable(PDB_Type *base, bool enable) -{ - if (enable) - { - base->SC |= PDB_SC_PDBEN_MASK; - } - else - { - base->SC &= ~PDB_SC_PDBEN_MASK; - } -} - -/* @} */ - -/*! - * @name Basic Counter - * @{ - */ - -/*! - * @brief Triggers the PDB counter by software. - * - * @param base PDB peripheral base address. - */ -static inline void PDB_DoSoftwareTrigger(PDB_Type *base) -{ - base->SC |= PDB_SC_SWTRIG_MASK; -} - -/*! - * @brief Loads the counter values. - * - * This function loads the counter values from the internal buffer. - * See "pdb_load_value_mode_t" about PDB's load mode. - * - * @param base PDB peripheral base address. - */ -static inline void PDB_DoLoadValues(PDB_Type *base) -{ - base->SC |= PDB_SC_LDOK_MASK; -} - -/*! - * @brief Enables the DMA for the PDB module. - * - * @param base PDB peripheral base address. - * @param enable Enable the feature or not. - */ -static inline void PDB_EnableDMA(PDB_Type *base, bool enable) -{ - if (enable) - { - base->SC |= PDB_SC_DMAEN_MASK; - } - else - { - base->SC &= ~PDB_SC_DMAEN_MASK; - } -} - -/*! - * @brief Enables the interrupts for the PDB module. - * - * @param base PDB peripheral base address. - * @param mask Mask value for interrupts. See "_pdb_interrupt_enable". - */ -static inline void PDB_EnableInterrupts(PDB_Type *base, uint32_t mask) -{ - assert(0U == (mask & ~(PDB_SC_PDBEIE_MASK | PDB_SC_PDBIE_MASK))); - - base->SC |= mask; -} - -/*! - * @brief Disables the interrupts for the PDB module. - * - * @param base PDB peripheral base address. - * @param mask Mask value for interrupts. See "_pdb_interrupt_enable". - */ -static inline void PDB_DisableInterrupts(PDB_Type *base, uint32_t mask) -{ - assert(0U == (mask & ~(PDB_SC_PDBEIE_MASK | PDB_SC_PDBIE_MASK))); - - base->SC &= ~mask; -} - -/*! - * @brief Gets the status flags of the PDB module. - * - * @param base PDB peripheral base address. - * - * @return Mask value for asserted flags. See "_pdb_status_flags". - */ -static inline uint32_t PDB_GetStatusFlags(PDB_Type *base) -{ - return base->SC & (PDB_SC_PDBIF_MASK | PDB_SC_LDOK_MASK); -} - -/*! - * @brief Clears the status flags of the PDB module. - * - * @param base PDB peripheral base address. - * @param mask Mask value of flags. See "_pdb_status_flags". - */ -static inline void PDB_ClearStatusFlags(PDB_Type *base, uint32_t mask) -{ - assert(0U == (mask & ~PDB_SC_PDBIF_MASK)); - - base->SC &= ~mask; -} - -/*! - * @brief Specifies the counter period. - * - * @param base PDB peripheral base address. - * @param value Setting value for the modulus. 16-bit is available. - */ -static inline void PDB_SetModulusValue(PDB_Type *base, uint32_t value) -{ - base->MOD = PDB_MOD_MOD(value); -} - -/*! - * @brief Gets the PDB counter's current value. - * - * @param base PDB peripheral base address. - * - * @return PDB counter's current value. - */ -static inline uint32_t PDB_GetCounterValue(PDB_Type *base) -{ - return base->CNT; -} - -/*! - * @brief Sets the value for the PDB counter delay event. - * - * @param base PDB peripheral base address. - * @param value Setting value for PDB counter delay event. 16-bit is available. - */ -static inline void PDB_SetCounterDelayValue(PDB_Type *base, uint32_t value) -{ - base->IDLY = PDB_IDLY_IDLY(value); -} -/* @} */ - -/*! - * @name ADC Pre-trigger - * @{ - */ - -/*! - * @brief Configures the ADC pre-trigger in the PDB module. - * - * @param base PDB peripheral base address. - * @param channel Channel index for ADC instance. - * @param config Pointer to the configuration structure. See "pdb_adc_pretrigger_config_t". - */ -static inline void PDB_SetADCPreTriggerConfig(PDB_Type *base, uint32_t channel, pdb_adc_pretrigger_config_t *config) -{ - assert(channel < PDB_C1_COUNT); - assert(NULL != config); - - base->CH[channel].C1 = PDB_C1_BB(config->enableBackToBackOperationMask) | PDB_C1_TOS(config->enableOutputMask) | - PDB_C1_EN(config->enablePreTriggerMask); -} - -/*! - * @brief Sets the value for the ADC pre-trigger delay event. - * - * This function sets the value for ADC pre-trigger delay event. It specifies the delay value for the channel's - * corresponding pre-trigger. The pre-trigger asserts when the PDB counter is equal to the set value. - * - * @param base PDB peripheral base address. - * @param channel Channel index for ADC instance. - * @param preChannel Channel group index for ADC instance. - * @param value Setting value for ADC pre-trigger delay event. 16-bit is available. - */ -static inline void PDB_SetADCPreTriggerDelayValue(PDB_Type *base, uint32_t channel, uint32_t preChannel, uint32_t value) -{ - assert(channel < PDB_C1_COUNT); - assert(preChannel < PDB_DLY_COUNT2); - /* xx_COUNT2 is actually the count for pre-triggers in header file. xx_COUNT is used for the count of channels. */ - - base->CH[channel].DLY[preChannel] = PDB_DLY_DLY(value); -} - -/*! - * @brief Gets the ADC pre-trigger's status flags. - * - * @param base PDB peripheral base address. - * @param channel Channel index for ADC instance. - * - * @return Mask value for asserted flags. See "_pdb_adc_pretrigger_flags". - */ -static inline uint32_t PDB_GetADCPreTriggerStatusFlags(PDB_Type *base, uint32_t channel) -{ - assert(channel < PDB_C1_COUNT); - - return base->CH[channel].S; -} - -/*! - * @brief Clears the ADC pre-trigger status flags. - * - * @param base PDB peripheral base address. - * @param channel Channel index for ADC instance. - * @param mask Mask value for flags. See "_pdb_adc_pretrigger_flags". - */ -static inline void PDB_ClearADCPreTriggerStatusFlags(PDB_Type *base, uint32_t channel, uint32_t mask) -{ - assert(channel < PDB_C1_COUNT); - - base->CH[channel].S &= ~mask; -} - -/* @} */ - -#if defined(FSL_FEATURE_PDB_HAS_DAC) && FSL_FEATURE_PDB_HAS_DAC -/*! - * @name DAC Interval Trigger - * @{ - */ - -/*! - * @brief Configures the DAC trigger in the PDB module. - * - * @param base PDB peripheral base address. - * @param channel Channel index for DAC instance. - * @param config Pointer to the configuration structure. See "pdb_dac_trigger_config_t". - */ -void PDB_SetDACTriggerConfig(PDB_Type *base, uint32_t channel, pdb_dac_trigger_config_t *config); - -/*! - * @brief Sets the value for the DAC interval event. - * - * This fucntion sets the value for DAC interval event. DAC interval trigger triggers the DAC module to update - * the buffer when the DAC interval counter is equal to the set value. - * - * @param base PDB peripheral base address. - * @param channel Channel index for DAC instance. - * @param value Setting value for the DAC interval event. - */ -static inline void PDB_SetDACTriggerIntervalValue(PDB_Type *base, uint32_t channel, uint32_t value) -{ - assert(channel < PDB_INT_COUNT); - - base->DAC[channel].INT = PDB_INT_INT(value); -} - -/* @} */ -#endif /* FSL_FEATURE_PDB_HAS_DAC */ - -/*! - * @name Pulse-Out Trigger - * @{ - */ - -/*! - * @brief Enables the pulse out trigger channels. - * - * @param base PDB peripheral base address. - * @param channelMask Channel mask value for multiple pulse out trigger channel. - * @param enable Whether the feature is enabled or not. - */ -static inline void PDB_EnablePulseOutTrigger(PDB_Type *base, uint32_t channelMask, bool enable) -{ - if (enable) - { - base->POEN |= PDB_POEN_POEN(channelMask); - } - else - { - base->POEN &= ~(PDB_POEN_POEN(channelMask)); - } -} - -/*! - * @brief Sets event values for the pulse out trigger. - * - * This function is used to set event values for the pulse output trigger. - * These pulse output trigger delay values specify the delay for the PDB Pulse-out. Pulse-out goes high when the PDB - * counter is equal to the pulse output high value (value1). Pulse-out goes low when the PDB counter is equal to the - * pulse output low value (value2). - * - * @param base PDB peripheral base address. - * @param channel Channel index for pulse out trigger channel. - * @param value1 Setting value for pulse out high. - * @param value2 Setting value for pulse out low. - */ -static inline void PDB_SetPulseOutTriggerDelayValue(PDB_Type *base, uint32_t channel, uint32_t value1, uint32_t value2) -{ - assert(channel < PDB_PODLY_COUNT); - - base->PODLY[channel] = PDB_PODLY_DLY1(value1) | PDB_PODLY_DLY2(value2); -} - -/* @} */ -#if defined(__cplusplus) -} -#endif -/*! - * @} - */ -#endif /* _FSL_PDB_H_ */ diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_pit.c b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_pit.c deleted file mode 100644 index e5c3c4e013d..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_pit.c +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "fsl_pit.h" - -/******************************************************************************* - * Prototypes - ******************************************************************************/ -/*! - * @brief Gets the instance from the base address to be used to gate or ungate the module clock - * - * @param base PIT peripheral base address - * - * @return The PIT instance - */ -static uint32_t PIT_GetInstance(PIT_Type *base); - -/******************************************************************************* - * Variables - ******************************************************************************/ -/*! @brief Pointers to PIT bases for each instance. */ -static PIT_Type *const s_pitBases[] = PIT_BASE_PTRS; - -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) -/*! @brief Pointers to PIT clocks for each instance. */ -static const clock_ip_name_t s_pitClocks[] = PIT_CLOCKS; -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ - -/******************************************************************************* - * Code - ******************************************************************************/ -static uint32_t PIT_GetInstance(PIT_Type *base) -{ - uint32_t instance; - - /* Find the instance index from base address mappings. */ - for (instance = 0; instance < ARRAY_SIZE(s_pitBases); instance++) - { - if (s_pitBases[instance] == base) - { - break; - } - } - - assert(instance < ARRAY_SIZE(s_pitBases)); - - return instance; -} - -void PIT_Init(PIT_Type *base, const pit_config_t *config) -{ - assert(config); - -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) - /* Ungate the PIT clock*/ - CLOCK_EnableClock(s_pitClocks[PIT_GetInstance(base)]); -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ - - /* Enable PIT timers */ - base->MCR &= ~PIT_MCR_MDIS_MASK; - - /* Config timer operation when in debug mode */ - if (config->enableRunInDebug) - { - base->MCR &= ~PIT_MCR_FRZ_MASK; - } - else - { - base->MCR |= PIT_MCR_FRZ_MASK; - } -} - -void PIT_Deinit(PIT_Type *base) -{ - /* Disable PIT timers */ - base->MCR |= PIT_MCR_MDIS_MASK; - -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) - /* Gate the PIT clock*/ - CLOCK_DisableClock(s_pitClocks[PIT_GetInstance(base)]); -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ -} - -#if defined(FSL_FEATURE_PIT_HAS_LIFETIME_TIMER) && FSL_FEATURE_PIT_HAS_LIFETIME_TIMER - -uint64_t PIT_GetLifetimeTimerCount(PIT_Type *base) -{ - uint32_t valueH = 0U; - uint32_t valueL = 0U; - - /* LTMR64H should be read before LTMR64L */ - valueH = base->LTMR64H; - valueL = base->LTMR64L; - - return (((uint64_t)valueH << 32U) + (uint64_t)(valueL)); -} - -#endif /* FSL_FEATURE_PIT_HAS_LIFETIME_TIMER */ diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_pit.h b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_pit.h deleted file mode 100644 index 99c30e1e4bc..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_pit.h +++ /dev/null @@ -1,354 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -#ifndef _FSL_PIT_H_ -#define _FSL_PIT_H_ - -#include "fsl_common.h" - -/*! - * @addtogroup pit - * @{ - */ - - -/******************************************************************************* - * Definitions - ******************************************************************************/ - -/*! @name Driver version */ -/*@{*/ -#define FSL_PIT_DRIVER_VERSION (MAKE_VERSION(2, 0, 0)) /*!< Version 2.0.0 */ -/*@}*/ - -/*! - * @brief List of PIT channels - * @note Actual number of available channels is SoC dependent - */ -typedef enum _pit_chnl -{ - kPIT_Chnl_0 = 0U, /*!< PIT channel number 0*/ - kPIT_Chnl_1, /*!< PIT channel number 1 */ - kPIT_Chnl_2, /*!< PIT channel number 2 */ - kPIT_Chnl_3, /*!< PIT channel number 3 */ -} pit_chnl_t; - -/*! @brief List of PIT interrupts */ -typedef enum _pit_interrupt_enable -{ - kPIT_TimerInterruptEnable = PIT_TCTRL_TIE_MASK, /*!< Timer interrupt enable*/ -} pit_interrupt_enable_t; - -/*! @brief List of PIT status flags */ -typedef enum _pit_status_flags -{ - kPIT_TimerFlag = PIT_TFLG_TIF_MASK, /*!< Timer flag */ -} pit_status_flags_t; - -/*! - * @brief PIT configuration structure - * - * This structure holds the configuration settings for the PIT peripheral. To initialize this - * structure to reasonable defaults, call the PIT_GetDefaultConfig() function and pass a - * pointer to your config structure instance. - * - * The configuration structure can be made constant so it resides in flash. - */ -typedef struct _pit_config -{ - bool enableRunInDebug; /*!< true: Timers run in debug mode; false: Timers stop in debug mode */ -} pit_config_t; - -/******************************************************************************* - * API - ******************************************************************************/ - -#if defined(__cplusplus) -extern "C" { -#endif - -/*! - * @name Initialization and deinitialization - * @{ - */ - -/*! - * @brief Ungates the PIT clock, enables the PIT module, and configures the peripheral for basic operations. - * - * @note This API should be called at the beginning of the application using the PIT driver. - * - * @param base PIT peripheral base address - * @param config Pointer to the user's PIT config structure - */ -void PIT_Init(PIT_Type *base, const pit_config_t *config); - -/*! - * @brief Gates the PIT clock and disables the PIT module. - * - * @param base PIT peripheral base address - */ -void PIT_Deinit(PIT_Type *base); - -/*! - * @brief Fills in the PIT configuration structure with the default settings. - * - * The default values are as follows. - * @code - * config->enableRunInDebug = false; - * @endcode - * @param config Pointer to the onfiguration structure. - */ -static inline void PIT_GetDefaultConfig(pit_config_t *config) -{ - assert(config); - - /* Timers are stopped in Debug mode */ - config->enableRunInDebug = false; -} - -#if defined(FSL_FEATURE_PIT_HAS_CHAIN_MODE) && FSL_FEATURE_PIT_HAS_CHAIN_MODE - -/*! - * @brief Enables or disables chaining a timer with the previous timer. - * - * When a timer has a chain mode enabled, it only counts after the previous - * timer has expired. If the timer n-1 has counted down to 0, counter n - * decrements the value by one. Each timer is 32-bits, which allows the developers - * to chain timers together and form a longer timer (64-bits and larger). The first timer - * (timer 0) can't be chained to any other timer. - * - * @param base PIT peripheral base address - * @param channel Timer channel number which is chained with the previous timer - * @param enable Enable or disable chain. - * true: Current timer is chained with the previous timer. - * false: Timer doesn't chain with other timers. - */ -static inline void PIT_SetTimerChainMode(PIT_Type *base, pit_chnl_t channel, bool enable) -{ - if (enable) - { - base->CHANNEL[channel].TCTRL |= PIT_TCTRL_CHN_MASK; - } - else - { - base->CHANNEL[channel].TCTRL &= ~PIT_TCTRL_CHN_MASK; - } -} - -#endif /* FSL_FEATURE_PIT_HAS_CHAIN_MODE */ - -/*! @}*/ - -/*! - * @name Interrupt Interface - * @{ - */ - -/*! - * @brief Enables the selected PIT interrupts. - * - * @param base PIT peripheral base address - * @param channel Timer channel number - * @param mask The interrupts to enable. This is a logical OR of members of the - * enumeration ::pit_interrupt_enable_t - */ -static inline void PIT_EnableInterrupts(PIT_Type *base, pit_chnl_t channel, uint32_t mask) -{ - base->CHANNEL[channel].TCTRL |= mask; -} - -/*! - * @brief Disables the selected PIT interrupts. - * - * @param base PIT peripheral base address - * @param channel Timer channel number - * @param mask The interrupts to disable. This is a logical OR of members of the - * enumeration ::pit_interrupt_enable_t - */ -static inline void PIT_DisableInterrupts(PIT_Type *base, pit_chnl_t channel, uint32_t mask) -{ - base->CHANNEL[channel].TCTRL &= ~mask; -} - -/*! - * @brief Gets the enabled PIT interrupts. - * - * @param base PIT peripheral base address - * @param channel Timer channel number - * - * @return The enabled interrupts. This is the logical OR of members of the - * enumeration ::pit_interrupt_enable_t - */ -static inline uint32_t PIT_GetEnabledInterrupts(PIT_Type *base, pit_chnl_t channel) -{ - return (base->CHANNEL[channel].TCTRL & PIT_TCTRL_TIE_MASK); -} - -/*! @}*/ - -/*! - * @name Status Interface - * @{ - */ - -/*! - * @brief Gets the PIT status flags. - * - * @param base PIT peripheral base address - * @param channel Timer channel number - * - * @return The status flags. This is the logical OR of members of the - * enumeration ::pit_status_flags_t - */ -static inline uint32_t PIT_GetStatusFlags(PIT_Type *base, pit_chnl_t channel) -{ - return (base->CHANNEL[channel].TFLG & PIT_TFLG_TIF_MASK); -} - -/*! - * @brief Clears the PIT status flags. - * - * @param base PIT peripheral base address - * @param channel Timer channel number - * @param mask The status flags to clear. This is a logical OR of members of the - * enumeration ::pit_status_flags_t - */ -static inline void PIT_ClearStatusFlags(PIT_Type *base, pit_chnl_t channel, uint32_t mask) -{ - base->CHANNEL[channel].TFLG = mask; -} - -/*! @}*/ - -/*! - * @name Read and Write the timer period - * @{ - */ - -/*! - * @brief Sets the timer period in units of count. - * - * Timers begin counting from the value set by this function until it reaches 0, - * then it generates an interrupt and load this register value again. - * Writing a new value to this register does not restart the timer. Instead, the value - * is loaded after the timer expires. - * - * @note Users can call the utility macros provided in fsl_common.h to convert to ticks. - * - * @param base PIT peripheral base address - * @param channel Timer channel number - * @param count Timer period in units of ticks - */ -static inline void PIT_SetTimerPeriod(PIT_Type *base, pit_chnl_t channel, uint32_t count) -{ - base->CHANNEL[channel].LDVAL = count; -} - -/*! - * @brief Reads the current timer counting value. - * - * This function returns the real-time timer counting value, in a range from 0 to a - * timer period. - * - * @note Users can call the utility macros provided in fsl_common.h to convert ticks to usec or msec. - * - * @param base PIT peripheral base address - * @param channel Timer channel number - * - * @return Current timer counting value in ticks - */ -static inline uint32_t PIT_GetCurrentTimerCount(PIT_Type *base, pit_chnl_t channel) -{ - return base->CHANNEL[channel].CVAL; -} - -/*! @}*/ - -/*! - * @name Timer Start and Stop - * @{ - */ - -/*! - * @brief Starts the timer counting. - * - * After calling this function, timers load period value, count down to 0 and - * then load the respective start value again. Each time a timer reaches 0, - * it generates a trigger pulse and sets the timeout interrupt flag. - * - * @param base PIT peripheral base address - * @param channel Timer channel number. - */ -static inline void PIT_StartTimer(PIT_Type *base, pit_chnl_t channel) -{ - base->CHANNEL[channel].TCTRL |= PIT_TCTRL_TEN_MASK; -} - -/*! - * @brief Stops the timer counting. - * - * This function stops every timer counting. Timers reload their periods - * respectively after the next time they call the PIT_DRV_StartTimer. - * - * @param base PIT peripheral base address - * @param channel Timer channel number. - */ -static inline void PIT_StopTimer(PIT_Type *base, pit_chnl_t channel) -{ - base->CHANNEL[channel].TCTRL &= ~PIT_TCTRL_TEN_MASK; -} - -/*! @}*/ - -#if defined(FSL_FEATURE_PIT_HAS_LIFETIME_TIMER) && FSL_FEATURE_PIT_HAS_LIFETIME_TIMER - -/*! - * @brief Reads the current lifetime counter value. - * - * The lifetime timer is a 64-bit timer which chains timer 0 and timer 1 together. - * Timer 0 and 1 are chained by calling the PIT_SetTimerChainMode before using this timer. - * The period of lifetime timer is equal to the "period of timer 0 * period of timer 1". - * For the 64-bit value, the higher 32-bit has the value of timer 1, and the lower 32-bit - * has the value of timer 0. - * - * @param base PIT peripheral base address - * - * @return Current lifetime timer value - */ -uint64_t PIT_GetLifetimeTimerCount(PIT_Type *base); - -#endif /* FSL_FEATURE_PIT_HAS_LIFETIME_TIMER */ - -#if defined(__cplusplus) -} -#endif - -/*! @}*/ - -#endif /* _FSL_PIT_H_ */ diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_pmc.c b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_pmc.c deleted file mode 100644 index bcdd5cb8231..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_pmc.c +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -#include "fsl_pmc.h" - -#if (defined(FSL_FEATURE_PMC_HAS_PARAM) && FSL_FEATURE_PMC_HAS_PARAM) -void PMC_GetParam(PMC_Type *base, pmc_param_t *param) -{ - uint32_t reg = base->PARAM; - ; - param->vlpoEnable = (bool)(reg & PMC_PARAM_VLPOE_MASK); - param->hvdEnable = (bool)(reg & PMC_PARAM_HVDE_MASK); -} -#endif /* FSL_FEATURE_PMC_HAS_PARAM */ - -void PMC_ConfigureLowVoltDetect(PMC_Type *base, const pmc_low_volt_detect_config_t *config) -{ - base->LVDSC1 = (0U | -#if (defined(FSL_FEATURE_PMC_HAS_LVDV) && FSL_FEATURE_PMC_HAS_LVDV) - ((uint32_t)config->voltSelect << PMC_LVDSC1_LVDV_SHIFT) | -#endif - ((uint32_t)config->enableInt << PMC_LVDSC1_LVDIE_SHIFT) | - ((uint32_t)config->enableReset << PMC_LVDSC1_LVDRE_SHIFT) - /* Clear the Low Voltage Detect Flag with previouse power detect setting */ - | PMC_LVDSC1_LVDACK_MASK); -} - -void PMC_ConfigureLowVoltWarning(PMC_Type *base, const pmc_low_volt_warning_config_t *config) -{ - base->LVDSC2 = (0U | -#if (defined(FSL_FEATURE_PMC_HAS_LVWV) && FSL_FEATURE_PMC_HAS_LVWV) - ((uint32_t)config->voltSelect << PMC_LVDSC2_LVWV_SHIFT) | -#endif - ((uint32_t)config->enableInt << PMC_LVDSC2_LVWIE_SHIFT) - /* Clear the Low Voltage Warning Flag with previouse power detect setting */ - | PMC_LVDSC2_LVWACK_MASK); -} - -#if (defined(FSL_FEATURE_PMC_HAS_HVDSC1) && FSL_FEATURE_PMC_HAS_HVDSC1) -void PMC_ConfigureHighVoltDetect(PMC_Type *base, const pmc_high_volt_detect_config_t *config) -{ - base->HVDSC1 = (((uint32_t)config->voltSelect << PMC_HVDSC1_HVDV_SHIFT) | - ((uint32_t)config->enableInt << PMC_HVDSC1_HVDIE_SHIFT) | - ((uint32_t)config->enableReset << PMC_HVDSC1_HVDRE_SHIFT) - /* Clear the High Voltage Detect Flag with previouse power detect setting */ - | PMC_HVDSC1_HVDACK_MASK); -} -#endif /* FSL_FEATURE_PMC_HAS_HVDSC1 */ - -#if ((defined(FSL_FEATURE_PMC_HAS_BGBE) && FSL_FEATURE_PMC_HAS_BGBE) || \ - (defined(FSL_FEATURE_PMC_HAS_BGEN) && FSL_FEATURE_PMC_HAS_BGEN) || \ - (defined(FSL_FEATURE_PMC_HAS_BGBDS) && FSL_FEATURE_PMC_HAS_BGBDS)) -void PMC_ConfigureBandgapBuffer(PMC_Type *base, const pmc_bandgap_buffer_config_t *config) -{ - base->REGSC = (0U -#if (defined(FSL_FEATURE_PMC_HAS_BGBE) && FSL_FEATURE_PMC_HAS_BGBE) - | ((uint32_t)config->enable << PMC_REGSC_BGBE_SHIFT) -#endif /* FSL_FEATURE_PMC_HAS_BGBE */ -#if (defined(FSL_FEATURE_PMC_HAS_BGEN) && FSL_FEATURE_PMC_HAS_BGEN) - | (((uint32_t)config->enableInLowPowerMode << PMC_REGSC_BGEN_SHIFT)) -#endif /* FSL_FEATURE_PMC_HAS_BGEN */ -#if (defined(FSL_FEATURE_PMC_HAS_BGBDS) && FSL_FEATURE_PMC_HAS_BGBDS) - | ((uint32_t)config->drive << PMC_REGSC_BGBDS_SHIFT) -#endif /* FSL_FEATURE_PMC_HAS_BGBDS */ - ); -} -#endif diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_pmc.h b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_pmc.h deleted file mode 100644 index 99fc149fc22..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_pmc.h +++ /dev/null @@ -1,421 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -#ifndef _FSL_PMC_H_ -#define _FSL_PMC_H_ - -#include "fsl_common.h" - -/*! @addtogroup pmc */ -/*! @{ */ - - -/******************************************************************************* - * Definitions - ******************************************************************************/ - -/*! @name Driver version */ -/*@{*/ -/*! @brief PMC driver version */ -#define FSL_PMC_DRIVER_VERSION (MAKE_VERSION(2, 0, 0)) /*!< Version 2.0.0. */ -/*@}*/ - -#if (defined(FSL_FEATURE_PMC_HAS_LVDV) && FSL_FEATURE_PMC_HAS_LVDV) -/*! - * @brief Low-voltage Detect Voltage Select - */ -typedef enum _pmc_low_volt_detect_volt_select -{ - kPMC_LowVoltDetectLowTrip = 0U, /*!< Low-trip point selected (VLVD = VLVDL )*/ - kPMC_LowVoltDetectHighTrip = 1U /*!< High-trip point selected (VLVD = VLVDH )*/ -} pmc_low_volt_detect_volt_select_t; -#endif - -#if (defined(FSL_FEATURE_PMC_HAS_LVWV) && FSL_FEATURE_PMC_HAS_LVWV) -/*! - * @brief Low-voltage Warning Voltage Select - */ -typedef enum _pmc_low_volt_warning_volt_select -{ - kPMC_LowVoltWarningLowTrip = 0U, /*!< Low-trip point selected (VLVW = VLVW1)*/ - kPMC_LowVoltWarningMid1Trip = 1U, /*!< Mid 1 trip point selected (VLVW = VLVW2)*/ - kPMC_LowVoltWarningMid2Trip = 2U, /*!< Mid 2 trip point selected (VLVW = VLVW3)*/ - kPMC_LowVoltWarningHighTrip = 3U /*!< High-trip point selected (VLVW = VLVW4)*/ -} pmc_low_volt_warning_volt_select_t; -#endif - -#if (defined(FSL_FEATURE_PMC_HAS_HVDSC1) && FSL_FEATURE_PMC_HAS_HVDSC1) -/*! - * @brief High-voltage Detect Voltage Select - */ -typedef enum _pmc_high_volt_detect_volt_select -{ - kPMC_HighVoltDetectLowTrip = 0U, /*!< Low-trip point selected (VHVD = VHVDL )*/ - kPMC_HighVoltDetectHighTrip = 1U /*!< High-trip point selected (VHVD = VHVDH )*/ -} pmc_high_volt_detect_volt_select_t; -#endif /* FSL_FEATURE_PMC_HAS_HVDSC1 */ - -#if (defined(FSL_FEATURE_PMC_HAS_BGBDS) && FSL_FEATURE_PMC_HAS_BGBDS) -/*! - * @brief Bandgap Buffer Drive Select. - */ -typedef enum _pmc_bandgap_buffer_drive_select -{ - kPMC_BandgapBufferDriveLow = 0U, /*!< Low-drive. */ - kPMC_BandgapBufferDriveHigh = 1U /*!< High-drive. */ -} pmc_bandgap_buffer_drive_select_t; -#endif /* FSL_FEATURE_PMC_HAS_BGBDS */ - -#if (defined(FSL_FEATURE_PMC_HAS_VLPO) && FSL_FEATURE_PMC_HAS_VLPO) -/*! - * @brief VLPx Option - */ -typedef enum _pmc_vlp_freq_option -{ - kPMC_FreqRestrict = 0U, /*!< Frequency is restricted in VLPx mode. */ - kPMC_FreqUnrestrict = 1U /*!< Frequency is unrestricted in VLPx mode. */ -} pmc_vlp_freq_mode_t; -#endif /* FSL_FEATURE_PMC_HAS_VLPO */ - -#if (defined(FSL_FEATURE_PMC_HAS_VERID) && FSL_FEATURE_PMC_HAS_VERID) -/*! - @brief IP version ID definition. - */ -typedef struct _pmc_version_id -{ - uint16_t feature; /*!< Feature Specification Number. */ - uint8_t minor; /*!< Minor version number. */ - uint8_t major; /*!< Major version number. */ -} pmc_version_id_t; -#endif /* FSL_FEATURE_PMC_HAS_VERID */ - -#if (defined(FSL_FEATURE_PMC_HAS_PARAM) && FSL_FEATURE_PMC_HAS_PARAM) -/*! @brief IP parameter definition. */ -typedef struct _pmc_param -{ - bool vlpoEnable; /*!< VLPO enable. */ - bool hvdEnable; /*!< HVD enable. */ -} pmc_param_t; -#endif /* FSL_FEATURE_PMC_HAS_PARAM */ - -/*! - * @brief Low-voltage Detect Configuration Structure - */ -typedef struct _pmc_low_volt_detect_config -{ - bool enableInt; /*!< Enable interrupt when Low-voltage detect*/ - bool enableReset; /*!< Enable system reset when Low-voltage detect*/ -#if (defined(FSL_FEATURE_PMC_HAS_LVDV) && FSL_FEATURE_PMC_HAS_LVDV) - pmc_low_volt_detect_volt_select_t voltSelect; /*!< Low-voltage detect trip point voltage selection*/ -#endif -} pmc_low_volt_detect_config_t; - -/*! - * @brief Low-voltage Warning Configuration Structure - */ -typedef struct _pmc_low_volt_warning_config -{ - bool enableInt; /*!< Enable interrupt when low-voltage warning*/ -#if (defined(FSL_FEATURE_PMC_HAS_LVWV) && FSL_FEATURE_PMC_HAS_LVWV) - pmc_low_volt_warning_volt_select_t voltSelect; /*!< Low-voltage warning trip point voltage selection*/ -#endif -} pmc_low_volt_warning_config_t; - -#if (defined(FSL_FEATURE_PMC_HAS_HVDSC1) && FSL_FEATURE_PMC_HAS_HVDSC1) -/*! - * @brief High-voltage Detect Configuration Structure - */ -typedef struct _pmc_high_volt_detect_config -{ - bool enableInt; /*!< Enable interrupt when high-voltage detect*/ - bool enableReset; /*!< Enable system reset when high-voltage detect*/ - pmc_high_volt_detect_volt_select_t voltSelect; /*!< High-voltage detect trip point voltage selection*/ -} pmc_high_volt_detect_config_t; -#endif /* FSL_FEATURE_PMC_HAS_HVDSC1 */ - -#if ((defined(FSL_FEATURE_PMC_HAS_BGBE) && FSL_FEATURE_PMC_HAS_BGBE) || \ - (defined(FSL_FEATURE_PMC_HAS_BGEN) && FSL_FEATURE_PMC_HAS_BGEN) || \ - (defined(FSL_FEATURE_PMC_HAS_BGBDS) && FSL_FEATURE_PMC_HAS_BGBDS)) -/*! - * @brief Bandgap Buffer configuration. - */ -typedef struct _pmc_bandgap_buffer_config -{ -#if (defined(FSL_FEATURE_PMC_HAS_BGBE) && FSL_FEATURE_PMC_HAS_BGBE) - bool enable; /*!< Enable bandgap buffer. */ -#endif -#if (defined(FSL_FEATURE_PMC_HAS_BGEN) && FSL_FEATURE_PMC_HAS_BGEN) - bool enableInLowPowerMode; /*!< Enable bandgap buffer in low-power mode. */ -#endif /* FSL_FEATURE_PMC_HAS_BGEN */ -#if (defined(FSL_FEATURE_PMC_HAS_BGBDS) && FSL_FEATURE_PMC_HAS_BGBDS) - pmc_bandgap_buffer_drive_select_t drive; /*!< Bandgap buffer drive select. */ -#endif /* FSL_FEATURE_PMC_HAS_BGBDS */ -} pmc_bandgap_buffer_config_t; -#endif - -/******************************************************************************* - * API - ******************************************************************************/ - -#if defined(__cplusplus) -extern "C" { -#endif /* __cplusplus*/ - -/*! @name Power Management Controller Control APIs*/ -/*@{*/ - -#if (defined(FSL_FEATURE_PMC_HAS_VERID) && FSL_FEATURE_PMC_HAS_VERID) -/*! - * @brief Gets the PMC version ID. - * - * This function gets the PMC version ID, including major version number, - * minor version number, and a feature specification number. - * - * @param base PMC peripheral base address. - * @param versionId Pointer to version ID structure. - */ -static inline void PMC_GetVersionId(PMC_Type *base, pmc_version_id_t *versionId) -{ - *((uint32_t *)versionId) = base->VERID; -} -#endif /* FSL_FEATURE_PMC_HAS_VERID */ - -#if (defined(FSL_FEATURE_PMC_HAS_PARAM) && FSL_FEATURE_PMC_HAS_PARAM) -/*! - * @brief Gets the PMC parameter. - * - * This function gets the PMC parameter including the VLPO enable and the HVD enable. - * - * @param base PMC peripheral base address. - * @param param Pointer to PMC param structure. - */ -void PMC_GetParam(PMC_Type *base, pmc_param_t *param); -#endif - -/*! - * @brief Configures the low-voltage detect setting. - * - * This function configures the low-voltage detect setting, including the trip - * point voltage setting, enables or disables the interrupt, enables or disables the system reset. - * - * @param base PMC peripheral base address. - * @param config Low-voltage detect configuration structure. - */ -void PMC_ConfigureLowVoltDetect(PMC_Type *base, const pmc_low_volt_detect_config_t *config); - -/*! - * @brief Gets the Low-voltage Detect Flag status. - * - * This function reads the current LVDF status. If it returns 1, a low-voltage event is detected. - * - * @param base PMC peripheral base address. - * @return Current low-voltage detect flag - * - true: Low-voltage detected - * - false: Low-voltage not detected - */ -static inline bool PMC_GetLowVoltDetectFlag(PMC_Type *base) -{ - return (bool)(base->LVDSC1 & PMC_LVDSC1_LVDF_MASK); -} - -/*! - * @brief Acknowledges clearing the Low-voltage Detect flag. - * - * This function acknowledges the low-voltage detection errors (write 1 to - * clear LVDF). - * - * @param base PMC peripheral base address. - */ -static inline void PMC_ClearLowVoltDetectFlag(PMC_Type *base) -{ - base->LVDSC1 |= PMC_LVDSC1_LVDACK_MASK; -} - -/*! - * @brief Configures the low-voltage warning setting. - * - * This function configures the low-voltage warning setting, including the trip - * point voltage setting and enabling or disabling the interrupt. - * - * @param base PMC peripheral base address. - * @param config Low-voltage warning configuration structure. - */ -void PMC_ConfigureLowVoltWarning(PMC_Type *base, const pmc_low_volt_warning_config_t *config); - -/*! - * @brief Gets the Low-voltage Warning Flag status. - * - * This function polls the current LVWF status. When 1 is returned, it - * indicates a low-voltage warning event. LVWF is set when V Supply transitions - * below the trip point or after reset and V Supply is already below the V LVW. - * - * @param base PMC peripheral base address. - * @return Current LVWF status - * - true: Low-voltage Warning Flag is set. - * - false: the Low-voltage Warning does not happen. - */ -static inline bool PMC_GetLowVoltWarningFlag(PMC_Type *base) -{ - return (bool)(base->LVDSC2 & PMC_LVDSC2_LVWF_MASK); -} - -/*! - * @brief Acknowledges the Low-voltage Warning flag. - * - * This function acknowledges the low voltage warning errors (write 1 to - * clear LVWF). - * - * @param base PMC peripheral base address. - */ -static inline void PMC_ClearLowVoltWarningFlag(PMC_Type *base) -{ - base->LVDSC2 |= PMC_LVDSC2_LVWACK_MASK; -} - -#if (defined(FSL_FEATURE_PMC_HAS_HVDSC1) && FSL_FEATURE_PMC_HAS_HVDSC1) -/*! - * @brief Configures the high-voltage detect setting. - * - * This function configures the high-voltage detect setting, including the trip - * point voltage setting, enabling or disabling the interrupt, enabling or disabling the system reset. - * - * @param base PMC peripheral base address. - * @param config High-voltage detect configuration structure. - */ -void PMC_ConfigureHighVoltDetect(PMC_Type *base, const pmc_high_volt_detect_config_t *config); - -/*! - * @brief Gets the High-voltage Detect Flag status. - * - * This function reads the current HVDF status. If it returns 1, a low - * voltage event is detected. - * - * @param base PMC peripheral base address. - * @return Current high-voltage detect flag - * - true: High-voltage detected - * - false: High-voltage not detected - */ -static inline bool PMC_GetHighVoltDetectFlag(PMC_Type *base) -{ - return (bool)(base->HVDSC1 & PMC_HVDSC1_HVDF_MASK); -} - -/*! - * @brief Acknowledges clearing the High-voltage Detect flag. - * - * This function acknowledges the high-voltage detection errors (write 1 to - * clear HVDF). - * - * @param base PMC peripheral base address. - */ -static inline void PMC_ClearHighVoltDetectFlag(PMC_Type *base) -{ - base->HVDSC1 |= PMC_HVDSC1_HVDACK_MASK; -} -#endif /* FSL_FEATURE_PMC_HAS_HVDSC1 */ - -#if ((defined(FSL_FEATURE_PMC_HAS_BGBE) && FSL_FEATURE_PMC_HAS_BGBE) || \ - (defined(FSL_FEATURE_PMC_HAS_BGEN) && FSL_FEATURE_PMC_HAS_BGEN) || \ - (defined(FSL_FEATURE_PMC_HAS_BGBDS) && FSL_FEATURE_PMC_HAS_BGBDS)) -/*! - * @brief Configures the PMC bandgap. - * - * This function configures the PMC bandgap, including the drive select and - * behavior in low-power mode. - * - * @param base PMC peripheral base address. - * @param config Pointer to the configuration structure - */ -void PMC_ConfigureBandgapBuffer(PMC_Type *base, const pmc_bandgap_buffer_config_t *config); -#endif - -#if (defined(FSL_FEATURE_PMC_HAS_ACKISO) && FSL_FEATURE_PMC_HAS_ACKISO) -/*! - * @brief Gets the acknowledge Peripherals and I/O pads isolation flag. - * - * This function reads the Acknowledge Isolation setting that indicates - * whether certain peripherals and the I/O pads are in a latched state as - * a result of having been in the VLLS mode. - * - * @param base PMC peripheral base address. - * @param base Base address for current PMC instance. - * @return ACK isolation - * 0 - Peripherals and I/O pads are in a normal run state. - * 1 - Certain peripherals and I/O pads are in an isolated and - * latched state. - */ -static inline bool PMC_GetPeriphIOIsolationFlag(PMC_Type *base) -{ - return (bool)(base->REGSC & PMC_REGSC_ACKISO_MASK); -} - -/*! - * @brief Acknowledges the isolation flag to Peripherals and I/O pads. - * - * This function clears the ACK Isolation flag. Writing one to this setting - * when it is set releases the I/O pads and certain peripherals to their normal - * run mode state. - * - * @param base PMC peripheral base address. - */ -static inline void PMC_ClearPeriphIOIsolationFlag(PMC_Type *base) -{ - base->REGSC |= PMC_REGSC_ACKISO_MASK; -} -#endif /* FSL_FEATURE_PMC_HAS_ACKISO */ - -#if (defined(FSL_FEATURE_PMC_HAS_REGONS) && FSL_FEATURE_PMC_HAS_REGONS) -/*! - * @brief Gets the regulator regulation status. - * - * This function returns the regulator to run a regulation status. It provides - * the current status of the internal voltage regulator. - * - * @param base PMC peripheral base address. - * @param base Base address for current PMC instance. - * @return Regulation status - * 0 - Regulator is in a stop regulation or in transition to/from the regulation. - * 1 - Regulator is in a run regulation. - * - */ -static inline bool PMC_IsRegulatorInRunRegulation(PMC_Type *base) -{ - return (bool)(base->REGSC & PMC_REGSC_REGONS_MASK); -} -#endif /* FSL_FEATURE_PMC_HAS_REGONS */ - -/*@}*/ - -#if defined(__cplusplus) -} -#endif /* __cplusplus*/ - -/*! @}*/ - -#endif /* _FSL_PMC_H_*/ diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_port.h b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_port.h deleted file mode 100644 index eb8e77e6ddd..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_port.h +++ /dev/null @@ -1,431 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -#ifndef _FSL_PORT_H_ -#define _FSL_PORT_H_ - -#include "fsl_common.h" - -/*! - * @addtogroup port - * @{ - */ - -/******************************************************************************* - * Definitions - ******************************************************************************/ - -/*! @name Driver version */ -/*@{*/ -/*! Version 2.0.2. */ -#define FSL_PORT_DRIVER_VERSION (MAKE_VERSION(2, 0, 2)) -/*@}*/ - -#if defined(FSL_FEATURE_PORT_HAS_PULL_ENABLE) && FSL_FEATURE_PORT_HAS_PULL_ENABLE -/*! @brief Internal resistor pull feature selection */ -enum _port_pull -{ - kPORT_PullDisable = 0U, /*!< Internal pull-up/down resistor is disabled. */ - kPORT_PullDown = 2U, /*!< Internal pull-down resistor is enabled. */ - kPORT_PullUp = 3U, /*!< Internal pull-up resistor is enabled. */ -}; -#endif /* FSL_FEATURE_PORT_HAS_PULL_ENABLE */ - -#if defined(FSL_FEATURE_PORT_HAS_SLEW_RATE) && FSL_FEATURE_PORT_HAS_SLEW_RATE -/*! @brief Slew rate selection */ -enum _port_slew_rate -{ - kPORT_FastSlewRate = 0U, /*!< Fast slew rate is configured. */ - kPORT_SlowSlewRate = 1U, /*!< Slow slew rate is configured. */ -}; -#endif /* FSL_FEATURE_PORT_HAS_SLEW_RATE */ - -#if defined(FSL_FEATURE_PORT_HAS_OPEN_DRAIN) && FSL_FEATURE_PORT_HAS_OPEN_DRAIN -/*! @brief Open Drain feature enable/disable */ -enum _port_open_drain_enable -{ - kPORT_OpenDrainDisable = 0U, /*!< Open drain output is disabled. */ - kPORT_OpenDrainEnable = 1U, /*!< Open drain output is enabled. */ -}; -#endif /* FSL_FEATURE_PORT_HAS_OPEN_DRAIN */ - -#if defined(FSL_FEATURE_PORT_HAS_PASSIVE_FILTER) && FSL_FEATURE_PORT_HAS_PASSIVE_FILTER -/*! @brief Passive filter feature enable/disable */ -enum _port_passive_filter_enable -{ - kPORT_PassiveFilterDisable = 0U, /*!< Passive input filter is disabled. */ - kPORT_PassiveFilterEnable = 1U, /*!< Passive input filter is enabled. */ -}; -#endif - -#if defined(FSL_FEATURE_PORT_HAS_DRIVE_STRENGTH) && FSL_FEATURE_PORT_HAS_DRIVE_STRENGTH -/*! @brief Configures the drive strength. */ -enum _port_drive_strength -{ - kPORT_LowDriveStrength = 0U, /*!< Low-drive strength is configured. */ - kPORT_HighDriveStrength = 1U, /*!< High-drive strength is configured. */ -}; -#endif /* FSL_FEATURE_PORT_HAS_DRIVE_STRENGTH */ - -#if defined(FSL_FEATURE_PORT_HAS_PIN_CONTROL_LOCK) && FSL_FEATURE_PORT_HAS_PIN_CONTROL_LOCK -/*! @brief Unlock/lock the pin control register field[15:0] */ -enum _port_lock_register -{ - kPORT_UnlockRegister = 0U, /*!< Pin Control Register fields [15:0] are not locked. */ - kPORT_LockRegister = 1U, /*!< Pin Control Register fields [15:0] are locked. */ -}; -#endif /* FSL_FEATURE_PORT_HAS_PIN_CONTROL_LOCK */ - -#if defined(FSL_FEATURE_PORT_PCR_MUX_WIDTH) && FSL_FEATURE_PORT_PCR_MUX_WIDTH -/*! @brief Pin mux selection */ -typedef enum _port_mux -{ - kPORT_PinDisabledOrAnalog = 0U, /*!< Corresponding pin is disabled, but is used as an analog pin. */ - kPORT_MuxAsGpio = 1U, /*!< Corresponding pin is configured as GPIO. */ - kPORT_MuxAlt2 = 2U, /*!< Chip-specific */ - kPORT_MuxAlt3 = 3U, /*!< Chip-specific */ - kPORT_MuxAlt4 = 4U, /*!< Chip-specific */ - kPORT_MuxAlt5 = 5U, /*!< Chip-specific */ - kPORT_MuxAlt6 = 6U, /*!< Chip-specific */ - kPORT_MuxAlt7 = 7U, /*!< Chip-specific */ - kPORT_MuxAlt8 = 8U, /*!< Chip-specific */ - kPORT_MuxAlt9 = 9U, /*!< Chip-specific */ - kPORT_MuxAlt10 = 10U, /*!< Chip-specific */ - kPORT_MuxAlt11 = 11U, /*!< Chip-specific */ - kPORT_MuxAlt12 = 12U, /*!< Chip-specific */ - kPORT_MuxAlt13 = 13U, /*!< Chip-specific */ - kPORT_MuxAlt14 = 14U, /*!< Chip-specific */ - kPORT_MuxAlt15 = 15U, /*!< Chip-specific */ -} port_mux_t; -#endif /* FSL_FEATURE_PORT_PCR_MUX_WIDTH */ - -/*! @brief Configures the interrupt generation condition. */ -typedef enum _port_interrupt -{ - kPORT_InterruptOrDMADisabled = 0x0U, /*!< Interrupt/DMA request is disabled. */ -#if defined(FSL_FEATURE_PORT_HAS_DMA_REQUEST) && FSL_FEATURE_PORT_HAS_DMA_REQUEST - kPORT_DMARisingEdge = 0x1U, /*!< DMA request on rising edge. */ - kPORT_DMAFallingEdge = 0x2U, /*!< DMA request on falling edge. */ - kPORT_DMAEitherEdge = 0x3U, /*!< DMA request on either edge. */ -#endif -#if defined(FSL_FEATURE_PORT_HAS_IRQC_FLAG) && FSL_FEATURE_PORT_HAS_IRQC_FLAG - kPORT_FlagRisingEdge = 0x05U, /*!< Flag sets on rising edge. */ - kPORT_FlagFallingEdge = 0x06U, /*!< Flag sets on falling edge. */ - kPORT_FlagEitherEdge = 0x07U, /*!< Flag sets on either edge. */ -#endif - kPORT_InterruptLogicZero = 0x8U, /*!< Interrupt when logic zero. */ - kPORT_InterruptRisingEdge = 0x9U, /*!< Interrupt on rising edge. */ - kPORT_InterruptFallingEdge = 0xAU, /*!< Interrupt on falling edge. */ - kPORT_InterruptEitherEdge = 0xBU, /*!< Interrupt on either edge. */ - kPORT_InterruptLogicOne = 0xCU, /*!< Interrupt when logic one. */ -#if defined(FSL_FEATURE_PORT_HAS_IRQC_TRIGGER) && FSL_FEATURE_PORT_HAS_IRQC_TRIGGER - kPORT_ActiveHighTriggerOutputEnable = 0xDU, /*!< Enable active high-trigger output. */ - kPORT_ActiveLowTriggerOutputEnable = 0xEU, /*!< Enable active low-trigger output. */ -#endif -} port_interrupt_t; - -#if defined(FSL_FEATURE_PORT_HAS_DIGITAL_FILTER) && FSL_FEATURE_PORT_HAS_DIGITAL_FILTER -/*! @brief Digital filter clock source selection */ -typedef enum _port_digital_filter_clock_source -{ - kPORT_BusClock = 0U, /*!< Digital filters are clocked by the bus clock. */ - kPORT_LpoClock = 1U, /*!< Digital filters are clocked by the 1 kHz LPO clock. */ -} port_digital_filter_clock_source_t; - -/*! @brief PORT digital filter feature configuration definition */ -typedef struct _port_digital_filter_config -{ - uint32_t digitalFilterWidth; /*!< Set digital filter width */ - port_digital_filter_clock_source_t clockSource; /*!< Set digital filter clockSource */ -} port_digital_filter_config_t; -#endif /* FSL_FEATURE_PORT_HAS_DIGITAL_FILTER */ - -#if defined(FSL_FEATURE_PORT_PCR_MUX_WIDTH) && FSL_FEATURE_PORT_PCR_MUX_WIDTH -/*! @brief PORT pin configuration structure */ -typedef struct _port_pin_config -{ -#if defined(FSL_FEATURE_PORT_HAS_PULL_ENABLE) && FSL_FEATURE_PORT_HAS_PULL_ENABLE - uint16_t pullSelect : 2; /*!< No-pull/pull-down/pull-up select */ -#else - uint16_t : 2; -#endif /* FSL_FEATURE_PORT_HAS_PULL_ENABLE */ - -#if defined(FSL_FEATURE_PORT_HAS_SLEW_RATE) && FSL_FEATURE_PORT_HAS_SLEW_RATE - uint16_t slewRate : 1; /*!< Fast/slow slew rate Configure */ -#else - uint16_t : 1; -#endif /* FSL_FEATURE_PORT_HAS_SLEW_RATE */ - - uint16_t : 1; - -#if defined(FSL_FEATURE_PORT_HAS_PASSIVE_FILTER) && FSL_FEATURE_PORT_HAS_PASSIVE_FILTER - uint16_t passiveFilterEnable : 1; /*!< Passive filter enable/disable */ -#else - uint16_t : 1; -#endif /* FSL_FEATURE_PORT_HAS_PASSIVE_FILTER */ - -#if defined(FSL_FEATURE_PORT_HAS_OPEN_DRAIN) && FSL_FEATURE_PORT_HAS_OPEN_DRAIN - uint16_t openDrainEnable : 1; /*!< Open drain enable/disable */ -#else - uint16_t : 1; -#endif /* FSL_FEATURE_PORT_HAS_OPEN_DRAIN */ - -#if defined(FSL_FEATURE_PORT_HAS_DRIVE_STRENGTH) && FSL_FEATURE_PORT_HAS_DRIVE_STRENGTH - uint16_t driveStrength : 1; /*!< Fast/slow drive strength configure */ -#else - uint16_t : 1; -#endif - - uint16_t : 1; - -#if defined(FSL_FEATURE_PORT_PCR_MUX_WIDTH) && FSL_FEATURE_PORT_PCR_MUX_WIDTH - uint16_t mux : 3; /*!< Pin mux Configure */ -#else - uint16_t : 3; -#endif - - uint16_t : 4; - -#if defined(FSL_FEATURE_PORT_HAS_PIN_CONTROL_LOCK) && FSL_FEATURE_PORT_HAS_PIN_CONTROL_LOCK - uint16_t lockRegister : 1; /*!< Lock/unlock the PCR field[15:0] */ -#else - uint16_t : 1; -#endif /* FSL_FEATURE_PORT_HAS_PIN_CONTROL_LOCK */ -} port_pin_config_t; -#endif /* FSL_FEATURE_PORT_PCR_MUX_WIDTH */ - -/******************************************************************************* -* API -******************************************************************************/ - -#if defined(__cplusplus) -extern "C" { -#endif - -#if defined(FSL_FEATURE_PORT_PCR_MUX_WIDTH) && FSL_FEATURE_PORT_PCR_MUX_WIDTH -/*! @name Configuration */ -/*@{*/ - -/*! - * @brief Sets the port PCR register. - * - * This is an example to define an input pin or output pin PCR configuration. - * @code - * // Define a digital input pin PCR configuration - * port_pin_config_t config = { - * kPORT_PullUp, - * kPORT_FastSlewRate, - * kPORT_PassiveFilterDisable, - * kPORT_OpenDrainDisable, - * kPORT_LowDriveStrength, - * kPORT_MuxAsGpio, - * kPORT_UnLockRegister, - * }; - * @endcode - * - * @param base PORT peripheral base pointer. - * @param pin PORT pin number. - * @param config PORT PCR register configuration structure. - */ -static inline void PORT_SetPinConfig(PORT_Type *base, uint32_t pin, const port_pin_config_t *config) -{ - assert(config); - uint32_t addr = (uint32_t)&base->PCR[pin]; - *(volatile uint16_t *)(addr) = *((const uint16_t *)config); -} - -/*! - * @brief Sets the port PCR register for multiple pins. - * - * This is an example to define input pins or output pins PCR configuration. - * @code - * // Define a digital input pin PCR configuration - * port_pin_config_t config = { - * kPORT_PullUp , - * kPORT_PullEnable, - * kPORT_FastSlewRate, - * kPORT_PassiveFilterDisable, - * kPORT_OpenDrainDisable, - * kPORT_LowDriveStrength, - * kPORT_MuxAsGpio, - * kPORT_UnlockRegister, - * }; - * @endcode - * - * @param base PORT peripheral base pointer. - * @param mask PORT pin number macro. - * @param config PORT PCR register configuration structure. - */ -static inline void PORT_SetMultiplePinsConfig(PORT_Type *base, uint32_t mask, const port_pin_config_t *config) -{ - assert(config); - - uint16_t pcrl = *((const uint16_t *)config); - - if (mask & 0xffffU) - { - base->GPCLR = ((mask & 0xffffU) << 16) | pcrl; - } - if (mask >> 16) - { - base->GPCHR = (mask & 0xffff0000U) | pcrl; - } -} - -/*! - * @brief Configures the pin muxing. - * - * @param base PORT peripheral base pointer. - * @param pin PORT pin number. - * @param mux pin muxing slot selection. - * - #kPORT_PinDisabledOrAnalog: Pin disabled or work in analog function. - * - #kPORT_MuxAsGpio : Set as GPIO. - * - #kPORT_MuxAlt2 : chip-specific. - * - #kPORT_MuxAlt3 : chip-specific. - * - #kPORT_MuxAlt4 : chip-specific. - * - #kPORT_MuxAlt5 : chip-specific. - * - #kPORT_MuxAlt6 : chip-specific. - * - #kPORT_MuxAlt7 : chip-specific. - * @Note : This function is NOT recommended to use together with the PORT_SetPinsConfig, because - * the PORT_SetPinsConfig need to configure the pin mux anyway (Otherwise the pin mux is - * reset to zero : kPORT_PinDisabledOrAnalog). - * This function is recommended to use to reset the pin mux - * - */ -static inline void PORT_SetPinMux(PORT_Type *base, uint32_t pin, port_mux_t mux) -{ - base->PCR[pin] = (base->PCR[pin] & ~PORT_PCR_MUX_MASK) | PORT_PCR_MUX(mux); -} -#endif /* FSL_FEATURE_PORT_PCR_MUX_WIDTH */ - -#if defined(FSL_FEATURE_PORT_HAS_DIGITAL_FILTER) && FSL_FEATURE_PORT_HAS_DIGITAL_FILTER - -/*! - * @brief Enables the digital filter in one port, each bit of the 32-bit register represents one pin. - * - * @param base PORT peripheral base pointer. - * @param mask PORT pin number macro. - */ -static inline void PORT_EnablePinsDigitalFilter(PORT_Type *base, uint32_t mask, bool enable) -{ - if (enable == true) - { - base->DFER |= mask; - } - else - { - base->DFER &= ~mask; - } -} - -/*! - * @brief Sets the digital filter in one port, each bit of the 32-bit register represents one pin. - * - * @param base PORT peripheral base pointer. - * @param config PORT digital filter configuration structure. - */ -static inline void PORT_SetDigitalFilterConfig(PORT_Type *base, const port_digital_filter_config_t *config) -{ - assert(config); - - base->DFCR = PORT_DFCR_CS(config->clockSource); - base->DFWR = PORT_DFWR_FILT(config->digitalFilterWidth); -} - -#endif /* FSL_FEATURE_PORT_HAS_DIGITAL_FILTER */ - -/*@}*/ - -/*! @name Interrupt */ -/*@{*/ - -/*! - * @brief Configures the port pin interrupt/DMA request. - * - * @param base PORT peripheral base pointer. - * @param pin PORT pin number. - * @param config PORT pin interrupt configuration. - * - #kPORT_InterruptOrDMADisabled: Interrupt/DMA request disabled. - * - #kPORT_DMARisingEdge : DMA request on rising edge(if the DMA requests exit). - * - #kPORT_DMAFallingEdge: DMA request on falling edge(if the DMA requests exit). - * - #kPORT_DMAEitherEdge : DMA request on either edge(if the DMA requests exit). - * - #kPORT_FlagRisingEdge : Flag sets on rising edge(if the Flag states exit). - * - #kPORT_FlagFallingEdge : Flag sets on falling edge(if the Flag states exit). - * - #kPORT_FlagEitherEdge : Flag sets on either edge(if the Flag states exit). - * - #kPORT_InterruptLogicZero : Interrupt when logic zero. - * - #kPORT_InterruptRisingEdge : Interrupt on rising edge. - * - #kPORT_InterruptFallingEdge: Interrupt on falling edge. - * - #kPORT_InterruptEitherEdge : Interrupt on either edge. - * - #kPORT_InterruptLogicOne : Interrupt when logic one. - * - #kPORT_ActiveHighTriggerOutputEnable : Enable active high-trigger output (if the trigger states exit). - * - #kPORT_ActiveLowTriggerOutputEnable : Enable active low-trigger output (if the trigger states exit). - */ -static inline void PORT_SetPinInterruptConfig(PORT_Type *base, uint32_t pin, port_interrupt_t config) -{ - base->PCR[pin] = (base->PCR[pin] & ~PORT_PCR_IRQC_MASK) | PORT_PCR_IRQC(config); -} - -/*! - * @brief Reads the whole port status flag. - * - * If a pin is configured to generate the DMA request, the corresponding flag - * is cleared automatically at the completion of the requested DMA transfer. - * Otherwise, the flag remains set until a logic one is written to that flag. - * If configured for a level sensitive interrupt that remains asserted, the flag - * is set again immediately. - * - * @param base PORT peripheral base pointer. - * @return Current port interrupt status flags, for example, 0x00010001 means the - * pin 0 and 16 have the interrupt. - */ -static inline uint32_t PORT_GetPinsInterruptFlags(PORT_Type *base) -{ - return base->ISFR; -} - -/*! - * @brief Clears the multiple pin interrupt status flag. - * - * @param base PORT peripheral base pointer. - * @param mask PORT pin number macro. - */ -static inline void PORT_ClearPinsInterruptFlags(PORT_Type *base, uint32_t mask) -{ - base->ISFR = mask; -} - -/*@}*/ - -#if defined(__cplusplus) -} -#endif - -/*! @}*/ - -#endif /* _FSL_PORT_H_ */ diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_rcm.c b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_rcm.c deleted file mode 100644 index 0d738643b53..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_rcm.c +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "fsl_rcm.h" - -void RCM_ConfigureResetPinFilter(RCM_Type *base, const rcm_reset_pin_filter_config_t *config) -{ - assert(config); - -#if (defined(FSL_FEATURE_RCM_REG_WIDTH) && (FSL_FEATURE_RCM_REG_WIDTH == 32)) - uint32_t reg; - - reg = (((uint32_t)config->enableFilterInStop << RCM_RPC_RSTFLTSS_SHIFT) | (uint32_t)config->filterInRunWait); - if (config->filterInRunWait == kRCM_FilterBusClock) - { - reg |= ((uint32_t)config->busClockFilterCount << RCM_RPC_RSTFLTSEL_SHIFT); - } - base->RPC = reg; -#else - base->RPFC = ((uint8_t)(config->enableFilterInStop << RCM_RPFC_RSTFLTSS_SHIFT) | (uint8_t)config->filterInRunWait); - if (config->filterInRunWait == kRCM_FilterBusClock) - { - base->RPFW = config->busClockFilterCount; - } -#endif /* FSL_FEATURE_RCM_REG_WIDTH */ -} - -#if (defined(FSL_FEATURE_RCM_HAS_BOOTROM) && FSL_FEATURE_RCM_HAS_BOOTROM) -void RCM_SetForceBootRomSource(RCM_Type *base, rcm_boot_rom_config_t config) -{ - uint32_t reg; - - reg = base->FM; - reg &= ~RCM_FM_FORCEROM_MASK; - reg |= ((uint32_t)config << RCM_FM_FORCEROM_SHIFT); - base->FM = reg; -} -#endif /* #if FSL_FEATURE_RCM_HAS_BOOTROM */ diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_rcm.h b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_rcm.h deleted file mode 100644 index 99b843aaf3a..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_rcm.h +++ /dev/null @@ -1,431 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -#ifndef _FSL_RCM_H_ -#define _FSL_RCM_H_ - -#include "fsl_common.h" - -/*! @addtogroup rcm */ -/*! @{*/ - - -/******************************************************************************* - * Definitions - ******************************************************************************/ - -/*! @name Driver version */ -/*@{*/ -/*! @brief RCM driver version 2.0.1. */ -#define FSL_RCM_DRIVER_VERSION (MAKE_VERSION(2, 0, 1)) -/*@}*/ - -/*! - * @brief System Reset Source Name definitions - */ -typedef enum _rcm_reset_source -{ -#if (defined(FSL_FEATURE_RCM_REG_WIDTH) && (FSL_FEATURE_RCM_REG_WIDTH == 32)) -/* RCM register bit width is 32. */ -#if (defined(FSL_FEATURE_RCM_HAS_WAKEUP) && FSL_FEATURE_RCM_HAS_WAKEUP) - kRCM_SourceWakeup = RCM_SRS_WAKEUP_MASK, /*!< Low-leakage wakeup reset */ -#endif - kRCM_SourceLvd = RCM_SRS_LVD_MASK, /*!< Low-voltage detect reset */ -#if (defined(FSL_FEATURE_RCM_HAS_LOC) && FSL_FEATURE_RCM_HAS_LOC) - kRCM_SourceLoc = RCM_SRS_LOC_MASK, /*!< Loss of clock reset */ -#endif /* FSL_FEATURE_RCM_HAS_LOC */ -#if (defined(FSL_FEATURE_RCM_HAS_LOL) && FSL_FEATURE_RCM_HAS_LOL) - kRCM_SourceLol = RCM_SRS_LOL_MASK, /*!< Loss of lock reset */ -#endif /* FSL_FEATURE_RCM_HAS_LOL */ - kRCM_SourceWdog = RCM_SRS_WDOG_MASK, /*!< Watchdog reset */ - kRCM_SourcePin = RCM_SRS_PIN_MASK, /*!< External pin reset */ - kRCM_SourcePor = RCM_SRS_POR_MASK, /*!< Power on reset */ -#if (defined(FSL_FEATURE_RCM_HAS_JTAG) && FSL_FEATURE_RCM_HAS_JTAG) - kRCM_SourceJtag = RCM_SRS_JTAG_MASK, /*!< JTAG generated reset */ -#endif /* FSL_FEATURE_RCM_HAS_JTAG */ - kRCM_SourceLockup = RCM_SRS_LOCKUP_MASK, /*!< Core lock up reset */ - kRCM_SourceSw = RCM_SRS_SW_MASK, /*!< Software reset */ -#if (defined(FSL_FEATURE_RCM_HAS_MDM_AP) && FSL_FEATURE_RCM_HAS_MDM_AP) - kRCM_SourceMdmap = RCM_SRS_MDM_AP_MASK, /*!< MDM-AP system reset */ -#endif /* FSL_FEATURE_RCM_HAS_MDM_AP */ -#if (defined(FSL_FEATURE_RCM_HAS_EZPORT) && FSL_FEATURE_RCM_HAS_EZPORT) - kRCM_SourceEzpt = RCM_SRS_EZPT_MASK, /*!< EzPort reset */ -#endif /* FSL_FEATURE_RCM_HAS_EZPORT */ - kRCM_SourceSackerr = RCM_SRS_SACKERR_MASK, /*!< Parameter could get all reset flags */ - -#else /* (FSL_FEATURE_RCM_REG_WIDTH == 32) */ -/* RCM register bit width is 8. */ -#if (defined(FSL_FEATURE_RCM_HAS_WAKEUP) && FSL_FEATURE_RCM_HAS_WAKEUP) - kRCM_SourceWakeup = RCM_SRS0_WAKEUP_MASK, /*!< Low-leakage wakeup reset */ -#endif - kRCM_SourceLvd = RCM_SRS0_LVD_MASK, /*!< Low-voltage detect reset */ -#if (defined(FSL_FEATURE_RCM_HAS_LOC) && FSL_FEATURE_RCM_HAS_LOC) - kRCM_SourceLoc = RCM_SRS0_LOC_MASK, /*!< Loss of clock reset */ -#endif /* FSL_FEATURE_RCM_HAS_LOC */ -#if (defined(FSL_FEATURE_RCM_HAS_LOL) && FSL_FEATURE_RCM_HAS_LOL) - kRCM_SourceLol = RCM_SRS0_LOL_MASK, /*!< Loss of lock reset */ -#endif /* FSL_FEATURE_RCM_HAS_LOL */ - kRCM_SourceWdog = RCM_SRS0_WDOG_MASK, /*!< Watchdog reset */ - kRCM_SourcePin = RCM_SRS0_PIN_MASK, /*!< External pin reset */ - kRCM_SourcePor = RCM_SRS0_POR_MASK, /*!< Power on reset */ -#if (defined(FSL_FEATURE_RCM_HAS_JTAG) && FSL_FEATURE_RCM_HAS_JTAG) - kRCM_SourceJtag = RCM_SRS1_JTAG_MASK << 8U, /*!< JTAG generated reset */ -#endif /* FSL_FEATURE_RCM_HAS_JTAG */ - kRCM_SourceLockup = RCM_SRS1_LOCKUP_MASK << 8U, /*!< Core lock up reset */ - kRCM_SourceSw = RCM_SRS1_SW_MASK << 8U, /*!< Software reset */ -#if (defined(FSL_FEATURE_RCM_HAS_MDM_AP) && FSL_FEATURE_RCM_HAS_MDM_AP) - kRCM_SourceMdmap = RCM_SRS1_MDM_AP_MASK << 8U, /*!< MDM-AP system reset */ -#endif /* FSL_FEATURE_RCM_HAS_MDM_AP */ -#if (defined(FSL_FEATURE_RCM_HAS_EZPORT) && FSL_FEATURE_RCM_HAS_EZPORT) - kRCM_SourceEzpt = RCM_SRS1_EZPT_MASK << 8U, /*!< EzPort reset */ -#endif /* FSL_FEATURE_RCM_HAS_EZPORT */ - kRCM_SourceSackerr = RCM_SRS1_SACKERR_MASK << 8U, /*!< Parameter could get all reset flags */ -#endif /* (FSL_FEATURE_RCM_REG_WIDTH == 32) */ - kRCM_SourceAll = 0xffffffffU, -} rcm_reset_source_t; - -/*! - * @brief Reset pin filter select in Run and Wait modes. - */ -typedef enum _rcm_run_wait_filter_mode -{ - kRCM_FilterDisable = 0U, /*!< All filtering disabled */ - kRCM_FilterBusClock = 1U, /*!< Bus clock filter enabled */ - kRCM_FilterLpoClock = 2U /*!< LPO clock filter enabled */ -} rcm_run_wait_filter_mode_t; - -#if (defined(FSL_FEATURE_RCM_HAS_BOOTROM) && FSL_FEATURE_RCM_HAS_BOOTROM) -/*! - * @brief Boot from ROM configuration. - */ -typedef enum _rcm_boot_rom_config -{ - kRCM_BootFlash = 0U, /*!< Boot from flash */ - kRCM_BootRomCfg0 = 1U, /*!< Boot from boot ROM due to BOOTCFG0 */ - kRCM_BootRomFopt = 2U, /*!< Boot from boot ROM due to FOPT[7] */ - kRCM_BootRomBoth = 3U /*!< Boot from boot ROM due to both BOOTCFG0 and FOPT[7] */ -} rcm_boot_rom_config_t; -#endif /* FSL_FEATURE_RCM_HAS_BOOTROM */ - -#if (defined(FSL_FEATURE_RCM_HAS_SRIE) && FSL_FEATURE_RCM_HAS_SRIE) -/*! - * @brief Maximum delay time from interrupt asserts to system reset. - */ -typedef enum _rcm_reset_delay -{ - kRCM_ResetDelay8Lpo = 0U, /*!< Delay 8 LPO cycles. */ - kRCM_ResetDelay32Lpo = 1U, /*!< Delay 32 LPO cycles. */ - kRCM_ResetDelay128Lpo = 2U, /*!< Delay 128 LPO cycles. */ - kRCM_ResetDelay512Lpo = 3U /*!< Delay 512 LPO cycles. */ -} rcm_reset_delay_t; - -/*! - * @brief System reset interrupt enable bit definitions. - */ -typedef enum _rcm_interrupt_enable -{ - kRCM_IntNone = 0U, /*!< No interrupt enabled. */ - kRCM_IntLossOfClk = RCM_SRIE_LOC_MASK, /*!< Loss of clock interrupt. */ - kRCM_IntLossOfLock = RCM_SRIE_LOL_MASK, /*!< Loss of lock interrupt. */ - kRCM_IntWatchDog = RCM_SRIE_WDOG_MASK, /*!< Watch dog interrupt. */ - kRCM_IntExternalPin = RCM_SRIE_PIN_MASK, /*!< External pin interrupt. */ - kRCM_IntGlobal = RCM_SRIE_GIE_MASK, /*!< Global interrupts. */ - kRCM_IntCoreLockup = RCM_SRIE_LOCKUP_MASK, /*!< Core lock up interrupt */ - kRCM_IntSoftware = RCM_SRIE_SW_MASK, /*!< software interrupt */ - kRCM_IntStopModeAckErr = RCM_SRIE_SACKERR_MASK, /*!< Stop mode ACK error interrupt. */ -#if (defined(FSL_FEATURE_RCM_HAS_CORE1) && FSL_FEATURE_RCM_HAS_CORE1) - kRCM_IntCore1 = RCM_SRIE_CORE1_MASK, /*!< Core 1 interrupt. */ -#endif - kRCM_IntAll = RCM_SRIE_LOC_MASK /*!< Enable all interrupts. */ - | - RCM_SRIE_LOL_MASK | RCM_SRIE_WDOG_MASK | RCM_SRIE_PIN_MASK | RCM_SRIE_GIE_MASK | - RCM_SRIE_LOCKUP_MASK | RCM_SRIE_SW_MASK | RCM_SRIE_SACKERR_MASK -#if (defined(FSL_FEATURE_RCM_HAS_CORE1) && FSL_FEATURE_RCM_HAS_CORE1) - | - RCM_SRIE_CORE1_MASK -#endif -} rcm_interrupt_enable_t; -#endif /* FSL_FEATURE_RCM_HAS_SRIE */ - -#if (defined(FSL_FEATURE_RCM_HAS_VERID) && FSL_FEATURE_RCM_HAS_VERID) -/*! - * @brief IP version ID definition. - */ -typedef struct _rcm_version_id -{ - uint16_t feature; /*!< Feature Specification Number. */ - uint8_t minor; /*!< Minor version number. */ - uint8_t major; /*!< Major version number. */ -} rcm_version_id_t; -#endif - -/*! - * @brief Reset pin filter configuration. - */ -typedef struct _rcm_reset_pin_filter_config -{ - bool enableFilterInStop; /*!< Reset pin filter select in stop mode. */ - rcm_run_wait_filter_mode_t filterInRunWait; /*!< Reset pin filter in run/wait mode. */ - uint8_t busClockFilterCount; /*!< Reset pin bus clock filter width. */ -} rcm_reset_pin_filter_config_t; - -/******************************************************************************* - * API - ******************************************************************************/ -#if defined(__cplusplus) -extern "C" { -#endif /* __cplusplus*/ - -/*! @name Reset Control Module APIs*/ -/*@{*/ - -#if (defined(FSL_FEATURE_RCM_HAS_VERID) && FSL_FEATURE_RCM_HAS_VERID) -/*! - * @brief Gets the RCM version ID. - * - * This function gets the RCM version ID including the major version number, - * the minor version number, and the feature specification number. - * - * @param base RCM peripheral base address. - * @param versionId Pointer to the version ID structure. - */ -static inline void RCM_GetVersionId(RCM_Type *base, rcm_version_id_t *versionId) -{ - *((uint32_t *)versionId) = base->VERID; -} -#endif - -#if (defined(FSL_FEATURE_RCM_HAS_PARAM) && FSL_FEATURE_RCM_HAS_PARAM) -/*! - * @brief Gets the reset source implemented status. - * - * This function gets the RCM parameter that indicates whether the corresponding reset source is implemented. - * Use source masks defined in the rcm_reset_source_t to get the desired source status. - * - * This is an example. - @code - uint32_t status; - - // To test whether the MCU is reset using Watchdog. - status = RCM_GetResetSourceImplementedStatus(RCM) & (kRCM_SourceWdog | kRCM_SourcePin); - @endcode - * - * @param base RCM peripheral base address. - * @return All reset source implemented status bit map. - */ -static inline uint32_t RCM_GetResetSourceImplementedStatus(RCM_Type *base) -{ - return base->PARAM; -} -#endif /* FSL_FEATURE_RCM_HAS_PARAM */ - -/*! - * @brief Gets the reset source status which caused a previous reset. - * - * This function gets the current reset source status. Use source masks - * defined in the rcm_reset_source_t to get the desired source status. - * - * This is an example. - @code - uint32_t resetStatus; - - // To get all reset source statuses. - resetStatus = RCM_GetPreviousResetSources(RCM) & kRCM_SourceAll; - - // To test whether the MCU is reset using Watchdog. - resetStatus = RCM_GetPreviousResetSources(RCM) & kRCM_SourceWdog; - - // To test multiple reset sources. - resetStatus = RCM_GetPreviousResetSources(RCM) & (kRCM_SourceWdog | kRCM_SourcePin); - @endcode - * - * @param base RCM peripheral base address. - * @return All reset source status bit map. - */ -static inline uint32_t RCM_GetPreviousResetSources(RCM_Type *base) -{ -#if (defined(FSL_FEATURE_RCM_REG_WIDTH) && (FSL_FEATURE_RCM_REG_WIDTH == 32)) - return base->SRS; -#else - return (uint32_t)((uint32_t)base->SRS0 | ((uint32_t)base->SRS1 << 8U)); -#endif /* (FSL_FEATURE_RCM_REG_WIDTH == 32) */ -} - -#if (defined(FSL_FEATURE_RCM_HAS_SSRS) && FSL_FEATURE_RCM_HAS_SSRS) -/*! - * @brief Gets the sticky reset source status. - * - * This function gets the current reset source status that has not been cleared - * by software for a specific source. - * - * This is an example. - @code - uint32_t resetStatus; - - // To get all reset source statuses. - resetStatus = RCM_GetStickyResetSources(RCM) & kRCM_SourceAll; - - // To test whether the MCU is reset using Watchdog. - resetStatus = RCM_GetStickyResetSources(RCM) & kRCM_SourceWdog; - - // To test multiple reset sources. - resetStatus = RCM_GetStickyResetSources(RCM) & (kRCM_SourceWdog | kRCM_SourcePin); - @endcode - * - * @param base RCM peripheral base address. - * @return All reset source status bit map. - */ -static inline uint32_t RCM_GetStickyResetSources(RCM_Type *base) -{ -#if (defined(FSL_FEATURE_RCM_REG_WIDTH) && (FSL_FEATURE_RCM_REG_WIDTH == 32)) - return base->SSRS; -#else - return (base->SSRS0 | ((uint32_t)base->SSRS1 << 8U)); -#endif /* (FSL_FEATURE_RCM_REG_WIDTH == 32) */ -} - -/*! - * @brief Clears the sticky reset source status. - * - * This function clears the sticky system reset flags indicated by source masks. - * - * This is an example. - @code - // Clears multiple reset sources. - RCM_ClearStickyResetSources(kRCM_SourceWdog | kRCM_SourcePin); - @endcode - * - * @param base RCM peripheral base address. - * @param sourceMasks reset source status bit map - */ -static inline void RCM_ClearStickyResetSources(RCM_Type *base, uint32_t sourceMasks) -{ -#if (defined(FSL_FEATURE_RCM_REG_WIDTH) && (FSL_FEATURE_RCM_REG_WIDTH == 32)) - base->SSRS = sourceMasks; -#else - base->SSRS0 = (sourceMasks & 0xffU); - base->SSRS1 = ((sourceMasks >> 8U) & 0xffU); -#endif /* (FSL_FEATURE_RCM_REG_WIDTH == 32) */ -} -#endif /* FSL_FEATURE_RCM_HAS_SSRS */ - -/*! - * @brief Configures the reset pin filter. - * - * This function sets the reset pin filter including the filter source, filter - * width, and so on. - * - * @param base RCM peripheral base address. - * @param config Pointer to the configuration structure. - */ -void RCM_ConfigureResetPinFilter(RCM_Type *base, const rcm_reset_pin_filter_config_t *config); - -#if (defined(FSL_FEATURE_RCM_HAS_EZPMS) && FSL_FEATURE_RCM_HAS_EZPMS) -/*! - * @brief Gets the EZP_MS_B pin assert status. - * - * This function gets the easy port mode status (EZP_MS_B) pin assert status. - * - * @param base RCM peripheral base address. - * @return status true - asserted, false - reasserted - */ -static inline bool RCM_GetEasyPortModePinStatus(RCM_Type *base) -{ - return (bool)(base->MR & RCM_MR_EZP_MS_MASK); -} -#endif /* FSL_FEATURE_RCM_HAS_EZPMS */ - -#if (defined(FSL_FEATURE_RCM_HAS_BOOTROM) && FSL_FEATURE_RCM_HAS_BOOTROM) -/*! - * @brief Gets the ROM boot source. - * - * This function gets the ROM boot source during the last chip reset. - * - * @param base RCM peripheral base address. - * @return The ROM boot source. - */ -static inline rcm_boot_rom_config_t RCM_GetBootRomSource(RCM_Type *base) -{ - return (rcm_boot_rom_config_t)((base->MR & RCM_MR_BOOTROM_MASK) >> RCM_MR_BOOTROM_SHIFT); -} - -/*! - * @brief Clears the ROM boot source flag. - * - * This function clears the ROM boot source flag. - * - * @param base Register base address of RCM - */ -static inline void RCM_ClearBootRomSource(RCM_Type *base) -{ - base->MR |= RCM_MR_BOOTROM_MASK; -} - -/*! - * @brief Forces the boot from ROM. - * - * This function forces booting from ROM during all subsequent system resets. - * - * @param base RCM peripheral base address. - * @param config Boot configuration. - */ -void RCM_SetForceBootRomSource(RCM_Type *base, rcm_boot_rom_config_t config); -#endif /* FSL_FEATURE_RCM_HAS_BOOTROM */ - -#if (defined(FSL_FEATURE_RCM_HAS_SRIE) && FSL_FEATURE_RCM_HAS_SRIE) -/*! - * @brief Sets the system reset interrupt configuration. - * - * For a graceful shut down, the RCM supports delaying the assertion of the system - * reset for a period of time when the reset interrupt is generated. This function - * can be used to enable the interrupt and the delay period. The interrupts - * are passed in as bit mask. See rcm_int_t for details. For example, to - * delay a reset for 512 LPO cycles after the WDOG timeout or loss-of-clock occurs, - * configure as follows: - * RCM_SetSystemResetInterruptConfig(kRCM_IntWatchDog | kRCM_IntLossOfClk, kRCM_ResetDelay512Lpo); - * - * @param base RCM peripheral base address. - * @param intMask Bit mask of the system reset interrupts to enable. See - * rcm_interrupt_enable_t for details. - * @param Delay Bit mask of the system reset interrupts to enable. - */ -static inline void RCM_SetSystemResetInterruptConfig(RCM_Type *base, uint32_t intMask, rcm_reset_delay_t delay) -{ - base->SRIE = (intMask | delay); -} -#endif /* FSL_FEATURE_RCM_HAS_SRIE */ -/*@}*/ - -#if defined(__cplusplus) -} -#endif /* __cplusplus*/ - -/*! @}*/ - -#endif /* _FSL_RCM_H_ */ diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_rnga.c b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_rnga.c deleted file mode 100644 index 6f0adc66f59..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_rnga.c +++ /dev/null @@ -1,287 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "fsl_rnga.h" - -#if defined(FSL_FEATURE_SOC_RNG_COUNT) && FSL_FEATURE_SOC_RNG_COUNT - -/******************************************************************************* - * Definitions - *******************************************************************************/ - -/******************************************************************************* - * RNG_CR - RNGA Control Register - ******************************************************************************/ -/*! - * @brief RNG_CR - RNGA Control Register (RW) - * - * Reset value: 0x00000000U - * - * Controls the operation of RNGA. - */ -/*! - * @name Constants and macros for entire RNG_CR register - */ -/*@{*/ -#define RNG_CR_REG(base) ((base)->CR) -#define RNG_RD_CR(base) (RNG_CR_REG(base)) -#define RNG_WR_CR(base, value) (RNG_CR_REG(base) = (value)) -#define RNG_RMW_CR(base, mask, value) (RNG_WR_CR(base, (RNG_RD_CR(base) & ~(mask)) | (value))) -/*@}*/ - -/*! - * @name Register RNG_CR, field GO[0] (RW) - * - * Specifies whether random-data generation and loading (into OR[RANDOUT]) is - * enabled.This field is sticky. You must reset RNGA to stop RNGA from loading - * OR[RANDOUT] with data. - * - * Values: - * - 0b0 - Disabled - * - 0b1 - Enabled - */ -/*@{*/ -/*! @brief Read current value of the RNG_CR_GO field. */ -#define RNG_RD_CR_GO(base) ((RNG_CR_REG(base) & RNG_CR_GO_MASK) >> RNG_CR_GO_SHIFT) - -/*! @brief Set the GO field to a new value. */ -#define RNG_WR_CR_GO(base, value) (RNG_RMW_CR(base, RNG_CR_GO_MASK, RNG_CR_GO(value))) -/*@}*/ - -/*! - * @name Register RNG_CR, field SLP[4] (RW) - * - * Specifies whether RNGA is in Sleep or Normal mode. You can also enter Sleep - * mode by asserting the DOZE signal. - * - * Values: - * - 0b0 - Normal mode - * - 0b1 - Sleep (low-power) mode - */ -/*@{*/ -/*! @brief Read current value of the RNG_CR_SLP field. */ -#define RNG_RD_CR_SLP(base) ((RNG_CR_REG(base) & RNG_CR_SLP_MASK) >> RNG_CR_SLP_SHIFT) - -/*! @brief Set the SLP field to a new value. */ -#define RNG_WR_CR_SLP(base, value) (RNG_RMW_CR(base, RNG_CR_SLP_MASK, RNG_CR_SLP(value))) -/*@}*/ - -/******************************************************************************* - * RNG_SR - RNGA Status Register - ******************************************************************************/ -#define RNG_SR_REG(base) ((base)->SR) - -/*! - * @name Register RNG_SR, field OREG_LVL[15:8] (RO) - * - * Indicates the number of random-data words that are in OR[RANDOUT], which - * indicates whether OR[RANDOUT] is valid.If you read OR[RANDOUT] when SR[OREG_LVL] - * is not 0, then the contents of a random number contained in OR[RANDOUT] are - * returned, and RNGA writes 0 to both OR[RANDOUT] and SR[OREG_LVL]. - * - * Values: - * - 0b00000000 - No words (empty) - * - 0b00000001 - One word (valid) - */ -/*@{*/ -/*! @brief Read current value of the RNG_SR_OREG_LVL field. */ -#define RNG_RD_SR_OREG_LVL(base) ((RNG_SR_REG(base) & RNG_SR_OREG_LVL_MASK) >> RNG_SR_OREG_LVL_SHIFT) -/*@}*/ - -/*! - * @name Register RNG_SR, field SLP[4] (RO) - * - * Specifies whether RNGA is in Sleep or Normal mode. You can also enter Sleep - * mode by asserting the DOZE signal. - * - * Values: - * - 0b0 - Normal mode - * - 0b1 - Sleep (low-power) mode - */ -/*@{*/ -/*! @brief Read current value of the RNG_SR_SLP field. */ -#define RNG_RD_SR_SLP(base) ((RNG_SR_REG(base) & RNG_SR_SLP_MASK) >> RNG_SR_SLP_SHIFT) -/*@}*/ - -/******************************************************************************* - * RNG_OR - RNGA Output Register - ******************************************************************************/ -/*! - * @brief RNG_OR - RNGA Output Register (RO) - * - * Reset value: 0x00000000U - * - * Stores a random-data word generated by RNGA. - */ -/*! - * @name Constants and macros for entire RNG_OR register - */ -/*@{*/ -#define RNG_OR_REG(base) ((base)->OR) -#define RNG_RD_OR(base) (RNG_OR_REG(base)) -/*@}*/ - -/******************************************************************************* - * RNG_ER - RNGA Entropy Register - ******************************************************************************/ -/*! - * @brief RNG_ER - RNGA Entropy Register (WORZ) - * - * Reset value: 0x00000000U - * - * Specifies an entropy value that RNGA uses in addition to its ring oscillators - * to seed its pseudorandom algorithm. This is a write-only register; reads - * return all zeros. - */ -/*! - * @name Constants and macros for entire RNG_ER register - */ -/*@{*/ -#define RNG_ER_REG(base) ((base)->ER) -#define RNG_RD_ER(base) (RNG_ER_REG(base)) -#define RNG_WR_ER(base, value) (RNG_ER_REG(base) = (value)) -/*@}*/ - -/******************************************************************************* - * Prototypes - *******************************************************************************/ - -static uint32_t rnga_ReadEntropy(RNG_Type *base); - -/******************************************************************************* - * Code - ******************************************************************************/ - -void RNGA_Init(RNG_Type *base) -{ -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) - /* Enable the clock gate. */ - CLOCK_EnableClock(kCLOCK_Rnga0); -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ - CLOCK_DisableClock(kCLOCK_Rnga0); /* To solve the release version on twrkm43z75m */ -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) - CLOCK_EnableClock(kCLOCK_Rnga0); -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ - - /* Reset the registers for RNGA module to reset state. */ - RNG_WR_CR(base, 0); - /* Enables the RNGA random data generation and loading.*/ - RNG_WR_CR_GO(base, 1); -} - -void RNGA_Deinit(RNG_Type *base) -{ -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) - /* Disable the clock for RNGA module.*/ - CLOCK_DisableClock(kCLOCK_Rnga0); -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ -} - -/*! - * @brief Get a random data from RNGA. - * - * @param base RNGA base address - */ -static uint32_t rnga_ReadEntropy(RNG_Type *base) -{ - uint32_t data = 0; - if (RNGA_GetMode(base) == kRNGA_ModeNormal) /* Is in normal mode.*/ - { - /* Wait for valid random-data.*/ - while (RNG_RD_SR_OREG_LVL(base) == 0) - { - } - data = RNG_RD_OR(base); - } - /* Get random-data word generated by RNGA.*/ - return data; -} - -status_t RNGA_GetRandomData(RNG_Type *base, void *data, size_t data_size) -{ - status_t result = kStatus_Success; - uint32_t random_32; - uint8_t *random_p; - uint32_t random_size; - uint8_t *data_p = (uint8_t *)data; - uint32_t i; - - /* Check input parameters.*/ - if (base && data && data_size) - { - do - { - /* Read Entropy.*/ - random_32 = rnga_ReadEntropy(base); - - random_p = (uint8_t *)&random_32; - - if (data_size < sizeof(random_32)) - { - random_size = data_size; - } - else - { - random_size = sizeof(random_32); - } - - for (i = 0; i < random_size; i++) - { - *data_p++ = *random_p++; - } - - data_size -= random_size; - } while (data_size > 0); - } - else - { - result = kStatus_InvalidArgument; - } - - return result; -} - -void RNGA_SetMode(RNG_Type *base, rnga_mode_t mode) -{ - RNG_WR_CR_SLP(base, (uint32_t)mode); -} - -rnga_mode_t RNGA_GetMode(RNG_Type *base) -{ - return (rnga_mode_t)RNG_RD_SR_SLP(base); -} - -void RNGA_Seed(RNG_Type *base, uint32_t seed) -{ - /* Write to RNGA Entropy Register.*/ - RNG_WR_ER(base, seed); -} - -#endif /* FSL_FEATURE_SOC_RNG_COUNT */ diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_rnga.h b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_rnga.h deleted file mode 100644 index 92f5bff8bec..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_rnga.h +++ /dev/null @@ -1,137 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -#ifndef _FSL_RNGA_DRIVER_H_ -#define _FSL_RNGA_DRIVER_H_ - -#include "fsl_common.h" - -#if defined(FSL_FEATURE_SOC_RNG_COUNT) && FSL_FEATURE_SOC_RNG_COUNT -/*! - * @addtogroup rnga - * @{ - */ - - -/******************************************************************************* - * Definitions - *******************************************************************************/ - -/*! @name Driver version */ -/*@{*/ -/*! @brief RNGA driver version 2.0.1. */ -#define FSL_RNGA_DRIVER_VERSION (MAKE_VERSION(2, 0, 1)) -/*@}*/ - -/*! @brief RNGA working mode */ -typedef enum _rnga_mode -{ - kRNGA_ModeNormal = 0U, /*!< Normal Mode. The ring-oscillator clocks are active; RNGA generates entropy - (randomness) from the clocks and stores it in shift registers.*/ - kRNGA_ModeSleep = 1U, /*!< Sleep Mode. The ring-oscillator clocks are inactive; RNGA does not generate entropy.*/ -} rnga_mode_t; - -/******************************************************************************* - * API - *******************************************************************************/ - -#if defined(__cplusplus) -extern "C" { -#endif - -/*! - * @brief Initializes the RNGA. - * - * This function initializes the RNGA. - * When called, the RNGA entropy generation starts immediately. - * - * @param base RNGA base address - */ -void RNGA_Init(RNG_Type *base); - -/*! - * @brief Shuts down the RNGA. - * - * This function shuts down the RNGA. - * - * @param base RNGA base address - */ -void RNGA_Deinit(RNG_Type *base); - -/*! - * @brief Gets random data. - * - * This function gets random data from the RNGA. - * - * @param base RNGA base address - * @param data pointer to user buffer to be filled by random data - * @param data_size size of data in bytes - * @return RNGA status - */ -status_t RNGA_GetRandomData(RNG_Type *base, void *data, size_t data_size); - -/*! - * @brief Feeds the RNGA module. - * - * This function inputs an entropy value that the RNGA uses to seed its - * pseudo-random algorithm. - * - * @param base RNGA base address - * @param seed input seed value - */ -void RNGA_Seed(RNG_Type *base, uint32_t seed); - -/*! - * @brief Sets the RNGA in normal mode or sleep mode. - * - * This function sets the RNGA in sleep mode or normal mode. - * - * @param base RNGA base address - * @param mode normal mode or sleep mode - */ -void RNGA_SetMode(RNG_Type *base, rnga_mode_t mode); - -/*! - * @brief Gets the RNGA working mode. - * - * This function gets the RNGA working mode. - * - * @param base RNGA base address - * @return normal mode or sleep mode - */ -rnga_mode_t RNGA_GetMode(RNG_Type *base); - -#if defined(__cplusplus) -} -#endif - -/*! @}*/ - -#endif /* FSL_FEATURE_SOC_RNG_COUNT */ -#endif /* _FSL_RNGA_H_*/ diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_rtc.c b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_rtc.c deleted file mode 100644 index d68055a2690..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_rtc.c +++ /dev/null @@ -1,381 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "fsl_rtc.h" - -/******************************************************************************* - * Definitions - ******************************************************************************/ -#define SECONDS_IN_A_DAY (86400U) -#define SECONDS_IN_A_HOUR (3600U) -#define SECONDS_IN_A_MINUTE (60U) -#define DAYS_IN_A_YEAR (365U) -#define YEAR_RANGE_START (1970U) -#define YEAR_RANGE_END (2099U) - -/******************************************************************************* - * Prototypes - ******************************************************************************/ -/*! - * @brief Checks whether the date and time passed in is valid - * - * @param datetime Pointer to structure where the date and time details are stored - * - * @return Returns false if the date & time details are out of range; true if in range - */ -static bool RTC_CheckDatetimeFormat(const rtc_datetime_t *datetime); - -/*! - * @brief Converts time data from datetime to seconds - * - * @param datetime Pointer to datetime structure where the date and time details are stored - * - * @return The result of the conversion in seconds - */ -static uint32_t RTC_ConvertDatetimeToSeconds(const rtc_datetime_t *datetime); - -/*! - * @brief Converts time data from seconds to a datetime structure - * - * @param seconds Seconds value that needs to be converted to datetime format - * @param datetime Pointer to the datetime structure where the result of the conversion is stored - */ -static void RTC_ConvertSecondsToDatetime(uint32_t seconds, rtc_datetime_t *datetime); - -/******************************************************************************* - * Code - ******************************************************************************/ -static bool RTC_CheckDatetimeFormat(const rtc_datetime_t *datetime) -{ - assert(datetime); - - /* Table of days in a month for a non leap year. First entry in the table is not used, - * valid months start from 1 - */ - uint8_t daysPerMonth[] = {0U, 31U, 28U, 31U, 30U, 31U, 30U, 31U, 31U, 30U, 31U, 30U, 31U}; - - /* Check year, month, hour, minute, seconds */ - if ((datetime->year < YEAR_RANGE_START) || (datetime->year > YEAR_RANGE_END) || (datetime->month > 12U) || - (datetime->month < 1U) || (datetime->hour >= 24U) || (datetime->minute >= 60U) || (datetime->second >= 60U)) - { - /* If not correct then error*/ - return false; - } - - /* Adjust the days in February for a leap year */ - if ((((datetime->year & 3U) == 0) && (datetime->year % 100 != 0)) || (datetime->year % 400 == 0)) - { - daysPerMonth[2] = 29U; - } - - /* Check the validity of the day */ - if ((datetime->day > daysPerMonth[datetime->month]) || (datetime->day < 1U)) - { - return false; - } - - return true; -} - -static uint32_t RTC_ConvertDatetimeToSeconds(const rtc_datetime_t *datetime) -{ - assert(datetime); - - /* Number of days from begin of the non Leap-year*/ - /* Number of days from begin of the non Leap-year*/ - uint16_t monthDays[] = {0U, 0U, 31U, 59U, 90U, 120U, 151U, 181U, 212U, 243U, 273U, 304U, 334U}; - uint32_t seconds; - - /* Compute number of days from 1970 till given year*/ - seconds = (datetime->year - 1970U) * DAYS_IN_A_YEAR; - /* Add leap year days */ - seconds += ((datetime->year / 4) - (1970U / 4)); - /* Add number of days till given month*/ - seconds += monthDays[datetime->month]; - /* Add days in given month. We subtract the current day as it is - * represented in the hours, minutes and seconds field*/ - seconds += (datetime->day - 1); - /* For leap year if month less than or equal to Febraury, decrement day counter*/ - if ((!(datetime->year & 3U)) && (datetime->month <= 2U)) - { - seconds--; - } - - seconds = (seconds * SECONDS_IN_A_DAY) + (datetime->hour * SECONDS_IN_A_HOUR) + - (datetime->minute * SECONDS_IN_A_MINUTE) + datetime->second; - - return seconds; -} - -static void RTC_ConvertSecondsToDatetime(uint32_t seconds, rtc_datetime_t *datetime) -{ - assert(datetime); - - uint32_t x; - uint32_t secondsRemaining, days; - uint16_t daysInYear; - /* Table of days in a month for a non leap year. First entry in the table is not used, - * valid months start from 1 - */ - uint8_t daysPerMonth[] = {0U, 31U, 28U, 31U, 30U, 31U, 30U, 31U, 31U, 30U, 31U, 30U, 31U}; - - /* Start with the seconds value that is passed in to be converted to date time format */ - secondsRemaining = seconds; - - /* Calcuate the number of days, we add 1 for the current day which is represented in the - * hours and seconds field - */ - days = secondsRemaining / SECONDS_IN_A_DAY + 1; - - /* Update seconds left*/ - secondsRemaining = secondsRemaining % SECONDS_IN_A_DAY; - - /* Calculate the datetime hour, minute and second fields */ - datetime->hour = secondsRemaining / SECONDS_IN_A_HOUR; - secondsRemaining = secondsRemaining % SECONDS_IN_A_HOUR; - datetime->minute = secondsRemaining / 60U; - datetime->second = secondsRemaining % SECONDS_IN_A_MINUTE; - - /* Calculate year */ - daysInYear = DAYS_IN_A_YEAR; - datetime->year = YEAR_RANGE_START; - while (days > daysInYear) - { - /* Decrease day count by a year and increment year by 1 */ - days -= daysInYear; - datetime->year++; - - /* Adjust the number of days for a leap year */ - if (datetime->year & 3U) - { - daysInYear = DAYS_IN_A_YEAR; - } - else - { - daysInYear = DAYS_IN_A_YEAR + 1; - } - } - - /* Adjust the days in February for a leap year */ - if (!(datetime->year & 3U)) - { - daysPerMonth[2] = 29U; - } - - for (x = 1U; x <= 12U; x++) - { - if (days <= daysPerMonth[x]) - { - datetime->month = x; - break; - } - else - { - days -= daysPerMonth[x]; - } - } - - datetime->day = days; -} - -void RTC_Init(RTC_Type *base, const rtc_config_t *config) -{ - assert(config); - - uint32_t reg; - -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) - CLOCK_EnableClock(kCLOCK_Rtc0); -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ - - /* Issue a software reset if timer is invalid */ - if (RTC_GetStatusFlags(RTC) & kRTC_TimeInvalidFlag) - { - RTC_Reset(RTC); - } - - reg = base->CR; - /* Setup the update mode and supervisor access mode */ - reg &= ~(RTC_CR_UM_MASK | RTC_CR_SUP_MASK); - reg |= RTC_CR_UM(config->updateMode) | RTC_CR_SUP(config->supervisorAccess); -#if defined(FSL_FEATURE_RTC_HAS_WAKEUP_PIN_SELECTION) && FSL_FEATURE_RTC_HAS_WAKEUP_PIN_SELECTION - /* Setup the wakeup pin select */ - reg &= ~(RTC_CR_WPS_MASK); - reg |= RTC_CR_WPS(config->wakeupSelect); -#endif /* FSL_FEATURE_RTC_HAS_WAKEUP_PIN */ - base->CR = reg; - - /* Configure the RTC time compensation register */ - base->TCR = (RTC_TCR_CIR(config->compensationInterval) | RTC_TCR_TCR(config->compensationTime)); -} - -void RTC_GetDefaultConfig(rtc_config_t *config) -{ - assert(config); - - /* Wakeup pin will assert if the RTC interrupt asserts or if the wakeup pin is turned on */ - config->wakeupSelect = false; - /* Registers cannot be written when locked */ - config->updateMode = false; - /* Non-supervisor mode write accesses are not supported and will generate a bus error */ - config->supervisorAccess = false; - /* Compensation interval used by the crystal compensation logic */ - config->compensationInterval = 0; - /* Compensation time used by the crystal compensation logic */ - config->compensationTime = 0; -} - -status_t RTC_SetDatetime(RTC_Type *base, const rtc_datetime_t *datetime) -{ - assert(datetime); - - /* Return error if the time provided is not valid */ - if (!(RTC_CheckDatetimeFormat(datetime))) - { - return kStatus_InvalidArgument; - } - - /* Set time in seconds */ - base->TSR = RTC_ConvertDatetimeToSeconds(datetime); - - return kStatus_Success; -} - -void RTC_GetDatetime(RTC_Type *base, rtc_datetime_t *datetime) -{ - assert(datetime); - - uint32_t seconds = 0; - - seconds = base->TSR; - RTC_ConvertSecondsToDatetime(seconds, datetime); -} - -status_t RTC_SetAlarm(RTC_Type *base, const rtc_datetime_t *alarmTime) -{ - assert(alarmTime); - - uint32_t alarmSeconds = 0; - uint32_t currSeconds = 0; - - /* Return error if the alarm time provided is not valid */ - if (!(RTC_CheckDatetimeFormat(alarmTime))) - { - return kStatus_InvalidArgument; - } - - alarmSeconds = RTC_ConvertDatetimeToSeconds(alarmTime); - - /* Get the current time */ - currSeconds = base->TSR; - - /* Return error if the alarm time has passed */ - if (alarmSeconds < currSeconds) - { - return kStatus_Fail; - } - - /* Set alarm in seconds*/ - base->TAR = alarmSeconds; - - return kStatus_Success; -} - -void RTC_GetAlarm(RTC_Type *base, rtc_datetime_t *datetime) -{ - assert(datetime); - - uint32_t alarmSeconds = 0; - - /* Get alarm in seconds */ - alarmSeconds = base->TAR; - - RTC_ConvertSecondsToDatetime(alarmSeconds, datetime); -} - -void RTC_ClearStatusFlags(RTC_Type *base, uint32_t mask) -{ - /* The alarm flag is cleared by writing to the TAR register */ - if (mask & kRTC_AlarmFlag) - { - base->TAR = 0U; - } - - /* The timer overflow flag is cleared by initializing the TSR register. - * The time counter should be disabled for this write to be successful - */ - if (mask & kRTC_TimeOverflowFlag) - { - base->TSR = 1U; - } - - /* The timer overflow flag is cleared by initializing the TSR register. - * The time counter should be disabled for this write to be successful - */ - if (mask & kRTC_TimeInvalidFlag) - { - base->TSR = 1U; - } -} - -#if defined(FSL_FEATURE_RTC_HAS_MONOTONIC) && (FSL_FEATURE_RTC_HAS_MONOTONIC) - -void RTC_GetMonotonicCounter(RTC_Type *base, uint64_t *counter) -{ - assert(counter); - - *counter = (((uint64_t)base->MCHR << 32) | ((uint64_t)base->MCLR)); -} - -void RTC_SetMonotonicCounter(RTC_Type *base, uint64_t counter) -{ - /* Prepare to initialize the register with the new value written */ - base->MER &= ~RTC_MER_MCE_MASK; - - base->MCHR = (uint32_t)((counter) >> 32); - base->MCLR = (uint32_t)(counter); -} - -status_t RTC_IncrementMonotonicCounter(RTC_Type *base) -{ - if (base->SR & (RTC_SR_MOF_MASK | RTC_SR_TIF_MASK)) - { - return kStatus_Fail; - } - - /* Prepare to switch to increment mode */ - base->MER |= RTC_MER_MCE_MASK; - /* Write anything so the counter increments*/ - base->MCLR = 1U; - - return kStatus_Success; -} - -#endif /* FSL_FEATURE_RTC_HAS_MONOTONIC */ diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_rtc.h b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_rtc.h deleted file mode 100644 index 99effc6dcb9..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_rtc.h +++ /dev/null @@ -1,414 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -#ifndef _FSL_RTC_H_ -#define _FSL_RTC_H_ - -#include "fsl_common.h" - -/*! - * @addtogroup rtc - * @{ - */ - - -/******************************************************************************* - * Definitions - ******************************************************************************/ - -/*! @name Driver version */ -/*@{*/ -#define FSL_RTC_DRIVER_VERSION (MAKE_VERSION(2, 0, 0)) /*!< Version 2.0.0 */ -/*@}*/ - -/*! @brief List of RTC interrupts */ -typedef enum _rtc_interrupt_enable -{ - kRTC_TimeInvalidInterruptEnable = RTC_IER_TIIE_MASK, /*!< Time invalid interrupt.*/ - kRTC_TimeOverflowInterruptEnable = RTC_IER_TOIE_MASK, /*!< Time overflow interrupt.*/ - kRTC_AlarmInterruptEnable = RTC_IER_TAIE_MASK, /*!< Alarm interrupt.*/ - kRTC_SecondsInterruptEnable = RTC_IER_TSIE_MASK /*!< Seconds interrupt.*/ -} rtc_interrupt_enable_t; - -/*! @brief List of RTC flags */ -typedef enum _rtc_status_flags -{ - kRTC_TimeInvalidFlag = RTC_SR_TIF_MASK, /*!< Time invalid flag */ - kRTC_TimeOverflowFlag = RTC_SR_TOF_MASK, /*!< Time overflow flag */ - kRTC_AlarmFlag = RTC_SR_TAF_MASK /*!< Alarm flag*/ -} rtc_status_flags_t; - -#if (defined(FSL_FEATURE_RTC_HAS_OSC_SCXP) && FSL_FEATURE_RTC_HAS_OSC_SCXP) - -/*! @brief List of RTC Oscillator capacitor load settings */ -typedef enum _rtc_osc_cap_load -{ - kRTC_Capacitor_2p = RTC_CR_SC2P_MASK, /*!< 2 pF capacitor load */ - kRTC_Capacitor_4p = RTC_CR_SC4P_MASK, /*!< 4 pF capacitor load */ - kRTC_Capacitor_8p = RTC_CR_SC8P_MASK, /*!< 8 pF capacitor load */ - kRTC_Capacitor_16p = RTC_CR_SC16P_MASK /*!< 16 pF capacitor load */ -} rtc_osc_cap_load_t; - -#endif /* FSL_FEATURE_SCG_HAS_OSC_SCXP */ - -/*! @brief Structure is used to hold the date and time */ -typedef struct _rtc_datetime -{ - uint16_t year; /*!< Range from 1970 to 2099.*/ - uint8_t month; /*!< Range from 1 to 12.*/ - uint8_t day; /*!< Range from 1 to 31 (depending on month).*/ - uint8_t hour; /*!< Range from 0 to 23.*/ - uint8_t minute; /*!< Range from 0 to 59.*/ - uint8_t second; /*!< Range from 0 to 59.*/ -} rtc_datetime_t; - -/*! - * @brief RTC config structure - * - * This structure holds the configuration settings for the RTC peripheral. To initialize this - * structure to reasonable defaults, call the RTC_GetDefaultConfig() function and pass a - * pointer to your config structure instance. - * - * The config struct can be made const so it resides in flash - */ -typedef struct _rtc_config -{ - bool wakeupSelect; /*!< true: Wakeup pin outputs the 32 KHz clock; - false:Wakeup pin used to wakeup the chip */ - bool updateMode; /*!< true: Registers can be written even when locked under certain - conditions, false: No writes allowed when registers are locked */ - bool supervisorAccess; /*!< true: Non-supervisor accesses are allowed; - false: Non-supervisor accesses are not supported */ - uint32_t compensationInterval; /*!< Compensation interval that is written to the CIR field in RTC TCR Register */ - uint32_t compensationTime; /*!< Compensation time that is written to the TCR field in RTC TCR Register */ -} rtc_config_t; - -/******************************************************************************* - * API - ******************************************************************************/ - -#if defined(__cplusplus) -extern "C" { -#endif - -/*! - * @name Initialization and deinitialization - * @{ - */ - -/*! - * @brief Ungates the RTC clock and configures the peripheral for basic operation. - * - * This function issues a software reset if the timer invalid flag is set. - * - * @note This API should be called at the beginning of the application using the RTC driver. - * - * @param base RTC peripheral base address - * @param config Pointer to the user's RTC configuration structure. - */ -void RTC_Init(RTC_Type *base, const rtc_config_t *config); - -/*! - * @brief Stops the timer and gate the RTC clock. - * - * @param base RTC peripheral base address - */ -static inline void RTC_Deinit(RTC_Type *base) -{ - /* Stop the RTC timer */ - base->SR &= ~RTC_SR_TCE_MASK; - -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) - /* Gate the module clock */ - CLOCK_DisableClock(kCLOCK_Rtc0); -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ -} - -/*! - * @brief Fills in the RTC config struct with the default settings. - * - * The default values are as follows. - * @code - * config->wakeupSelect = false; - * config->updateMode = false; - * config->supervisorAccess = false; - * config->compensationInterval = 0; - * config->compensationTime = 0; - * @endcode - * @param config Pointer to the user's RTC configuration structure. - */ -void RTC_GetDefaultConfig(rtc_config_t *config); - -/*! @}*/ - -/*! - * @name Current Time & Alarm - * @{ - */ - -/*! - * @brief Sets the RTC date and time according to the given time structure. - * - * The RTC counter must be stopped prior to calling this function because writes to the RTC - * seconds register fail if the RTC counter is running. - * - * @param base RTC peripheral base address - * @param datetime Pointer to the structure where the date and time details are stored. - * - * @return kStatus_Success: Success in setting the time and starting the RTC - * kStatus_InvalidArgument: Error because the datetime format is incorrect - */ -status_t RTC_SetDatetime(RTC_Type *base, const rtc_datetime_t *datetime); - -/*! - * @brief Gets the RTC time and stores it in the given time structure. - * - * @param base RTC peripheral base address - * @param datetime Pointer to the structure where the date and time details are stored. - */ -void RTC_GetDatetime(RTC_Type *base, rtc_datetime_t *datetime); - -/*! - * @brief Sets the RTC alarm time. - * - * The function checks whether the specified alarm time is greater than the present - * time. If not, the function does not set the alarm and returns an error. - * - * @param base RTC peripheral base address - * @param alarmTime Pointer to the structure where the alarm time is stored. - * - * @return kStatus_Success: success in setting the RTC alarm - * kStatus_InvalidArgument: Error because the alarm datetime format is incorrect - * kStatus_Fail: Error because the alarm time has already passed - */ -status_t RTC_SetAlarm(RTC_Type *base, const rtc_datetime_t *alarmTime); - -/*! - * @brief Returns the RTC alarm time. - * - * @param base RTC peripheral base address - * @param datetime Pointer to the structure where the alarm date and time details are stored. - */ -void RTC_GetAlarm(RTC_Type *base, rtc_datetime_t *datetime); - -/*! @}*/ - -/*! - * @name Interrupt Interface - * @{ - */ - -/*! - * @brief Enables the selected RTC interrupts. - * - * @param base RTC peripheral base address - * @param mask The interrupts to enable. This is a logical OR of members of the - * enumeration ::rtc_interrupt_enable_t - */ -static inline void RTC_EnableInterrupts(RTC_Type *base, uint32_t mask) -{ - base->IER |= mask; -} - -/*! - * @brief Disables the selected RTC interrupts. - * - * @param base RTC peripheral base address - * @param mask The interrupts to enable. This is a logical OR of members of the - * enumeration ::rtc_interrupt_enable_t - */ -static inline void RTC_DisableInterrupts(RTC_Type *base, uint32_t mask) -{ - base->IER &= ~mask; -} - -/*! - * @brief Gets the enabled RTC interrupts. - * - * @param base RTC peripheral base address - * - * @return The enabled interrupts. This is the logical OR of members of the - * enumeration ::rtc_interrupt_enable_t - */ -static inline uint32_t RTC_GetEnabledInterrupts(RTC_Type *base) -{ - return (base->IER & (RTC_IER_TIIE_MASK | RTC_IER_TOIE_MASK | RTC_IER_TAIE_MASK | RTC_IER_TSIE_MASK)); -} - -/*! @}*/ - -/*! - * @name Status Interface - * @{ - */ - -/*! - * @brief Gets the RTC status flags. - * - * @param base RTC peripheral base address - * - * @return The status flags. This is the logical OR of members of the - * enumeration ::rtc_status_flags_t - */ -static inline uint32_t RTC_GetStatusFlags(RTC_Type *base) -{ - return (base->SR & (RTC_SR_TIF_MASK | RTC_SR_TOF_MASK | RTC_SR_TAF_MASK)); -} - -/*! - * @brief Clears the RTC status flags. - * - * @param base RTC peripheral base address - * @param mask The status flags to clear. This is a logical OR of members of the - * enumeration ::rtc_status_flags_t - */ -void RTC_ClearStatusFlags(RTC_Type *base, uint32_t mask); - -/*! @}*/ - -/*! - * @name Timer Start and Stop - * @{ - */ - -/*! - * @brief Starts the RTC time counter. - * - * After calling this function, the timer counter increments once a second provided SR[TOF] or - * SR[TIF] are not set. - * - * @param base RTC peripheral base address - */ -static inline void RTC_StartTimer(RTC_Type *base) -{ - base->SR |= RTC_SR_TCE_MASK; -} - -/*! - * @brief Stops the RTC time counter. - * - * RTC's seconds register can be written to only when the timer is stopped. - * - * @param base RTC peripheral base address - */ -static inline void RTC_StopTimer(RTC_Type *base) -{ - base->SR &= ~RTC_SR_TCE_MASK; -} - -/*! @}*/ - -#if (defined(FSL_FEATURE_RTC_HAS_OSC_SCXP) && FSL_FEATURE_RTC_HAS_OSC_SCXP) - -/*! - * @brief This function sets the specified capacitor configuration for the RTC oscillator. - * - * @param base RTC peripheral base address - * @param capLoad Oscillator loads to enable. This is a logical OR of members of the - * enumeration ::rtc_osc_cap_load_t - */ -static inline void RTC_SetOscCapLoad(RTC_Type *base, uint32_t capLoad) -{ - uint32_t reg = base->CR; - - reg &= ~(RTC_CR_SC2P_MASK | RTC_CR_SC4P_MASK | RTC_CR_SC8P_MASK | RTC_CR_SC16P_MASK); - reg |= capLoad; - - base->CR = reg; -} - -#endif /* FSL_FEATURE_SCG_HAS_OSC_SCXP */ - -/*! - * @brief Performs a software reset on the RTC module. - * - * This resets all RTC registers except for the SWR bit and the RTC_WAR and RTC_RAR - * registers. The SWR bit is cleared by software explicitly clearing it. - * - * @param base RTC peripheral base address - */ -static inline void RTC_Reset(RTC_Type *base) -{ - base->CR |= RTC_CR_SWR_MASK; - base->CR &= ~RTC_CR_SWR_MASK; - - /* Set TSR register to 0x1 to avoid the timer invalid (TIF) bit being set in the SR register */ - base->TSR = 1U; -} - -#if defined(FSL_FEATURE_RTC_HAS_MONOTONIC) && (FSL_FEATURE_RTC_HAS_MONOTONIC) - -/*! - * @name Monotonic counter functions - * @{ - */ - -/*! - * @brief Reads the values of the Monotonic Counter High and Monotonic Counter Low and returns - * them as a single value. - * - * @param base RTC peripheral base address - * @param counter Pointer to variable where the value is stored. - */ -void RTC_GetMonotonicCounter(RTC_Type *base, uint64_t *counter); - -/*! - * @brief Writes values Monotonic Counter High and Monotonic Counter Low by decomposing - * the given single value. - * - * @param base RTC peripheral base address - * @param counter Counter value - */ -void RTC_SetMonotonicCounter(RTC_Type *base, uint64_t counter); - -/*! - * @brief Increments the Monotonic Counter by one. - * - * Increments the Monotonic Counter (registers RTC_MCLR and RTC_MCHR accordingly) by setting - * the monotonic counter enable (MER[MCE]) and then writing to the RTC_MCLR register. A write to the - * monotonic counter low that causes it to overflow also increments the monotonic counter high. - * - * @param base RTC peripheral base address - * - * @return kStatus_Success: success - * kStatus_Fail: error occurred, either time invalid or monotonic overflow flag was found - */ -status_t RTC_IncrementMonotonicCounter(RTC_Type *base); - -/*! @}*/ - -#endif /* FSL_FEATURE_RTC_HAS_MONOTONIC */ - -#if defined(__cplusplus) -} -#endif - -/*! @}*/ - -#endif /* _FSL_RTC_H_ */ diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_sai.c b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_sai.c deleted file mode 100644 index 73ea64fa4ee..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_sai.c +++ /dev/null @@ -1,1192 +0,0 @@ -/* - * Copyright (c) 2016, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "fsl_sai.h" - -/******************************************************************************* - * Definitations - ******************************************************************************/ -enum _sai_transfer_state -{ - kSAI_Busy = 0x0U, /*!< SAI is busy */ - kSAI_Idle, /*!< Transfer is done. */ - kSAI_Error /*!< Transfer error occured. */ -}; - -/*! @brief Typedef for sai tx interrupt handler. */ -typedef void (*sai_tx_isr_t)(I2S_Type *base, sai_handle_t *saiHandle); - -/*! @brief Typedef for sai rx interrupt handler. */ -typedef void (*sai_rx_isr_t)(I2S_Type *base, sai_handle_t *saiHandle); - -/******************************************************************************* - * Prototypes - ******************************************************************************/ -#if defined(FSL_FEATURE_SAI_HAS_MCLKDIV_REGISTER) && (FSL_FEATURE_SAI_HAS_MCLKDIV_REGISTER) - -/*! - * @brief Set the master clock divider. - * - * This API will compute the master clock divider according to master clock frequency and master - * clock source clock source frequency. - * - * @param base SAI base pointer. - * @param mclk_Hz Mater clock frequency in Hz. - * @param mclkSrcClock_Hz Master clock source frequency in Hz. - */ -static void SAI_SetMasterClockDivider(I2S_Type *base, uint32_t mclk_Hz, uint32_t mclkSrcClock_Hz); -#endif /* FSL_FEATURE_SAI_HAS_MCLKDIV_REGISTER */ - -/*! - * @brief Get the instance number for SAI. - * - * @param base SAI base pointer. - */ -uint32_t SAI_GetInstance(I2S_Type *base); - -/*! - * @brief sends a piece of data in non-blocking way. - * - * @param base SAI base pointer - * @param channel Data channel used. - * @param bitWidth How many bits in a audio word, usually 8/16/24/32 bits. - * @param buffer Pointer to the data to be written. - * @param size Bytes to be written. - */ -static void SAI_WriteNonBlocking(I2S_Type *base, uint32_t channel, uint32_t bitWidth, uint8_t *buffer, uint32_t size); - -/*! - * @brief Receive a piece of data in non-blocking way. - * - * @param base SAI base pointer - * @param channel Data channel used. - * @param bitWidth How many bits in a audio word, usually 8/16/24/32 bits. - * @param buffer Pointer to the data to be read. - * @param size Bytes to be read. - */ -static void SAI_ReadNonBlocking(I2S_Type *base, uint32_t channel, uint32_t bitWidth, uint8_t *buffer, uint32_t size); -/******************************************************************************* - * Variables - ******************************************************************************/ -/* Base pointer array */ -static I2S_Type *const s_saiBases[] = I2S_BASE_PTRS; -/*!@brief SAI handle pointer */ -sai_handle_t *s_saiHandle[ARRAY_SIZE(s_saiBases)][2]; -/* IRQ number array */ -static const IRQn_Type s_saiTxIRQ[] = I2S_TX_IRQS; -static const IRQn_Type s_saiRxIRQ[] = I2S_RX_IRQS; -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) -/* Clock name array */ -static const clock_ip_name_t s_saiClock[] = SAI_CLOCKS; -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ -/*! @brief Pointer to tx IRQ handler for each instance. */ -static sai_tx_isr_t s_saiTxIsr; -/*! @brief Pointer to tx IRQ handler for each instance. */ -static sai_rx_isr_t s_saiRxIsr; - -/******************************************************************************* - * Code - ******************************************************************************/ -#if defined(FSL_FEATURE_SAI_HAS_MCLKDIV_REGISTER) && (FSL_FEATURE_SAI_HAS_MCLKDIV_REGISTER) -static void SAI_SetMasterClockDivider(I2S_Type *base, uint32_t mclk_Hz, uint32_t mclkSrcClock_Hz) -{ - uint32_t freq = mclkSrcClock_Hz; - uint16_t fract, divide; - uint32_t remaind = 0; - uint32_t current_remainder = 0xFFFFFFFFU; - uint16_t current_fract = 0; - uint16_t current_divide = 0; - uint32_t mul_freq = 0; - uint32_t max_fract = 256; - - /*In order to prevent overflow */ - freq /= 100; - mclk_Hz /= 100; - - /* Compute the max fract number */ - max_fract = mclk_Hz * 4096 / freq + 1; - if (max_fract > 256) - { - max_fract = 256; - } - - /* Looking for the closet frequency */ - for (fract = 1; fract < max_fract; fract++) - { - mul_freq = freq * fract; - remaind = mul_freq % mclk_Hz; - divide = mul_freq / mclk_Hz; - - /* Find the exactly frequency */ - if (remaind == 0) - { - current_fract = fract; - current_divide = mul_freq / mclk_Hz; - break; - } - - /* Closer to next one, set the closest to next data */ - if (remaind > mclk_Hz / 2) - { - remaind = mclk_Hz - remaind; - divide += 1; - } - - /* Update the closest div and fract */ - if (remaind < current_remainder) - { - current_fract = fract; - current_divide = divide; - current_remainder = remaind; - } - } - - /* Fill the computed fract and divider to registers */ - base->MDR = I2S_MDR_DIVIDE(current_divide - 1) | I2S_MDR_FRACT(current_fract - 1); - - /* Waiting for the divider updated */ - while (base->MCR & I2S_MCR_DUF_MASK) - { - } -} -#endif /* FSL_FEATURE_SAI_HAS_MCLKDIV_REGISTER */ - -uint32_t SAI_GetInstance(I2S_Type *base) -{ - uint32_t instance; - - /* Find the instance index from base address mappings. */ - for (instance = 0; instance < ARRAY_SIZE(s_saiBases); instance++) - { - if (s_saiBases[instance] == base) - { - break; - } - } - - assert(instance < ARRAY_SIZE(s_saiBases)); - - return instance; -} - -static void SAI_WriteNonBlocking(I2S_Type *base, uint32_t channel, uint32_t bitWidth, uint8_t *buffer, uint32_t size) -{ - uint32_t i = 0; - uint8_t j = 0; - uint8_t bytesPerWord = bitWidth / 8U; - uint32_t data = 0; - uint32_t temp = 0; - - for (i = 0; i < size / bytesPerWord; i++) - { - for (j = 0; j < bytesPerWord; j++) - { - temp = (uint32_t)(*buffer); - data |= (temp << (8U * j)); - buffer++; - } - base->TDR[channel] = data; - data = 0; - } -} - -static void SAI_ReadNonBlocking(I2S_Type *base, uint32_t channel, uint32_t bitWidth, uint8_t *buffer, uint32_t size) -{ - uint32_t i = 0; - uint8_t j = 0; - uint8_t bytesPerWord = bitWidth / 8U; - uint32_t data = 0; - - for (i = 0; i < size / bytesPerWord; i++) - { - data = base->RDR[channel]; - for (j = 0; j < bytesPerWord; j++) - { - *buffer = (data >> (8U * j)) & 0xFF; - buffer++; - } - } -} - -void SAI_TxInit(I2S_Type *base, const sai_config_t *config) -{ - uint32_t val = 0; - -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) - /* Enable the SAI clock */ - CLOCK_EnableClock(s_saiClock[SAI_GetInstance(base)]); -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ - -#if defined(FSL_FEATURE_SAI_HAS_MCR) && (FSL_FEATURE_SAI_HAS_MCR) - /* Master clock source setting */ - val = (base->MCR & ~I2S_MCR_MICS_MASK); - base->MCR = (val | I2S_MCR_MICS(config->mclkSource)); - - /* Configure Master clock output enable */ - val = (base->MCR & ~I2S_MCR_MOE_MASK); - base->MCR = (val | I2S_MCR_MOE(config->mclkOutputEnable)); -#endif /* FSL_FEATURE_SAI_HAS_MCR */ - - /* Configure audio protocol */ - switch (config->protocol) - { - case kSAI_BusLeftJustified: - base->TCR2 |= I2S_TCR2_BCP_MASK; - base->TCR3 &= ~I2S_TCR3_WDFL_MASK; - base->TCR4 = I2S_TCR4_MF(1U) | I2S_TCR4_SYWD(31U) | I2S_TCR4_FSE(0U) | I2S_TCR4_FSP(0U) | I2S_TCR4_FRSZ(1U); - break; - - case kSAI_BusRightJustified: - base->TCR2 |= I2S_TCR2_BCP_MASK; - base->TCR3 &= ~I2S_TCR3_WDFL_MASK; - base->TCR4 = I2S_TCR4_MF(1U) | I2S_TCR4_SYWD(31U) | I2S_TCR4_FSE(0U) | I2S_TCR4_FSP(0U) | I2S_TCR4_FRSZ(1U); - break; - - case kSAI_BusI2S: - base->TCR2 |= I2S_TCR2_BCP_MASK; - base->TCR3 &= ~I2S_TCR3_WDFL_MASK; - base->TCR4 = I2S_TCR4_MF(1U) | I2S_TCR4_SYWD(31U) | I2S_TCR4_FSE(1U) | I2S_TCR4_FSP(1U) | I2S_TCR4_FRSZ(1U); - break; - - case kSAI_BusPCMA: - base->TCR2 &= ~I2S_TCR2_BCP_MASK; - base->TCR3 &= ~I2S_TCR3_WDFL_MASK; - base->TCR4 = I2S_TCR4_MF(1U) | I2S_TCR4_SYWD(0U) | I2S_TCR4_FSE(1U) | I2S_TCR4_FSP(0U) | I2S_TCR4_FRSZ(1U); - break; - - case kSAI_BusPCMB: - base->TCR2 &= ~I2S_TCR2_BCP_MASK; - base->TCR3 &= ~I2S_TCR3_WDFL_MASK; - base->TCR4 = I2S_TCR4_MF(1U) | I2S_TCR4_SYWD(0U) | I2S_TCR4_FSE(0U) | I2S_TCR4_FSP(0U) | I2S_TCR4_FRSZ(1U); - break; - - default: - break; - } - - /* Set master or slave */ - if (config->masterSlave == kSAI_Master) - { - base->TCR2 |= I2S_TCR2_BCD_MASK; - base->TCR4 |= I2S_TCR4_FSD_MASK; - - /* Bit clock source setting */ - val = base->TCR2 & (~I2S_TCR2_MSEL_MASK); - base->TCR2 = (val | I2S_TCR2_MSEL(config->bclkSource)); - } - else - { - base->TCR2 &= ~I2S_TCR2_BCD_MASK; - base->TCR4 &= ~I2S_TCR4_FSD_MASK; - } - - /* Set Sync mode */ - switch (config->syncMode) - { - case kSAI_ModeAsync: - val = base->TCR2; - val &= ~I2S_TCR2_SYNC_MASK; - base->TCR2 = (val | I2S_TCR2_SYNC(0U)); - break; - case kSAI_ModeSync: - val = base->TCR2; - val &= ~I2S_TCR2_SYNC_MASK; - base->TCR2 = (val | I2S_TCR2_SYNC(1U)); - /* If sync with Rx, should set Rx to async mode */ - val = base->RCR2; - val &= ~I2S_RCR2_SYNC_MASK; - base->RCR2 = (val | I2S_RCR2_SYNC(0U)); - break; - case kSAI_ModeSyncWithOtherTx: - val = base->TCR2; - val &= ~I2S_TCR2_SYNC_MASK; - base->TCR2 = (val | I2S_TCR2_SYNC(2U)); - break; - case kSAI_ModeSyncWithOtherRx: - val = base->TCR2; - val &= ~I2S_TCR2_SYNC_MASK; - base->TCR2 = (val | I2S_TCR2_SYNC(3U)); - break; - default: - break; - } -} - -void SAI_RxInit(I2S_Type *base, const sai_config_t *config) -{ - uint32_t val = 0; - -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) - /* Enable SAI clock first. */ - CLOCK_EnableClock(s_saiClock[SAI_GetInstance(base)]); -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ - -#if defined(FSL_FEATURE_SAI_HAS_MCR) && (FSL_FEATURE_SAI_HAS_MCR) - /* Master clock source setting */ - val = (base->MCR & ~I2S_MCR_MICS_MASK); - base->MCR = (val | I2S_MCR_MICS(config->mclkSource)); - - /* Configure Master clock output enable */ - val = (base->MCR & ~I2S_MCR_MOE_MASK); - base->MCR = (val | I2S_MCR_MOE(config->mclkOutputEnable)); -#endif /* FSL_FEATURE_SAI_HAS_MCR */ - - /* Configure audio protocol */ - switch (config->protocol) - { - case kSAI_BusLeftJustified: - base->RCR2 |= I2S_RCR2_BCP_MASK; - base->RCR3 &= ~I2S_RCR3_WDFL_MASK; - base->RCR4 = I2S_RCR4_MF(1U) | I2S_RCR4_SYWD(31U) | I2S_RCR4_FSE(0U) | I2S_RCR4_FSP(0U) | I2S_RCR4_FRSZ(1U); - break; - - case kSAI_BusRightJustified: - base->RCR2 |= I2S_RCR2_BCP_MASK; - base->RCR3 &= ~I2S_RCR3_WDFL_MASK; - base->RCR4 = I2S_RCR4_MF(1U) | I2S_RCR4_SYWD(31U) | I2S_RCR4_FSE(0U) | I2S_RCR4_FSP(0U) | I2S_RCR4_FRSZ(1U); - break; - - case kSAI_BusI2S: - base->RCR2 |= I2S_RCR2_BCP_MASK; - base->RCR3 &= ~I2S_RCR3_WDFL_MASK; - base->RCR4 = I2S_RCR4_MF(1U) | I2S_RCR4_SYWD(31U) | I2S_RCR4_FSE(1U) | I2S_RCR4_FSP(1U) | I2S_RCR4_FRSZ(1U); - break; - - case kSAI_BusPCMA: - base->RCR2 &= ~I2S_RCR2_BCP_MASK; - base->RCR3 &= ~I2S_RCR3_WDFL_MASK; - base->RCR4 = I2S_RCR4_MF(1U) | I2S_RCR4_SYWD(0U) | I2S_RCR4_FSE(1U) | I2S_RCR4_FSP(0U) | I2S_RCR4_FRSZ(1U); - break; - - case kSAI_BusPCMB: - base->RCR2 &= ~I2S_RCR2_BCP_MASK; - base->RCR3 &= ~I2S_RCR3_WDFL_MASK; - base->RCR4 = I2S_RCR4_MF(1U) | I2S_RCR4_SYWD(0U) | I2S_RCR4_FSE(0U) | I2S_RCR4_FSP(0U) | I2S_RCR4_FRSZ(1U); - break; - - default: - break; - } - - /* Set master or slave */ - if (config->masterSlave == kSAI_Master) - { - base->RCR2 |= I2S_RCR2_BCD_MASK; - base->RCR4 |= I2S_RCR4_FSD_MASK; - - /* Bit clock source setting */ - val = base->RCR2 & (~I2S_RCR2_MSEL_MASK); - base->RCR2 = (val | I2S_RCR2_MSEL(config->bclkSource)); - } - else - { - base->RCR2 &= ~I2S_RCR2_BCD_MASK; - base->RCR4 &= ~I2S_RCR4_FSD_MASK; - } - - /* Set Sync mode */ - switch (config->syncMode) - { - case kSAI_ModeAsync: - val = base->RCR2; - val &= ~I2S_RCR2_SYNC_MASK; - base->RCR2 = (val | I2S_RCR2_SYNC(0U)); - break; - case kSAI_ModeSync: - val = base->RCR2; - val &= ~I2S_RCR2_SYNC_MASK; - base->RCR2 = (val | I2S_RCR2_SYNC(1U)); - /* If sync with Tx, should set Tx to async mode */ - val = base->TCR2; - val &= ~I2S_TCR2_SYNC_MASK; - base->TCR2 = (val | I2S_TCR2_SYNC(0U)); - break; - case kSAI_ModeSyncWithOtherTx: - val = base->RCR2; - val &= ~I2S_RCR2_SYNC_MASK; - base->RCR2 = (val | I2S_RCR2_SYNC(2U)); - break; - case kSAI_ModeSyncWithOtherRx: - val = base->RCR2; - val &= ~I2S_RCR2_SYNC_MASK; - base->RCR2 = (val | I2S_RCR2_SYNC(3U)); - break; - default: - break; - } -} - -void SAI_Deinit(I2S_Type *base) -{ - SAI_TxEnable(base, false); - SAI_RxEnable(base, false); -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) - CLOCK_DisableClock(s_saiClock[SAI_GetInstance(base)]); -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ -} - -void SAI_TxGetDefaultConfig(sai_config_t *config) -{ - config->bclkSource = kSAI_BclkSourceMclkDiv; - config->masterSlave = kSAI_Master; - config->mclkSource = kSAI_MclkSourceSysclk; - config->protocol = kSAI_BusLeftJustified; - config->syncMode = kSAI_ModeAsync; -#if defined(FSL_FEATURE_SAI_HAS_MCR) && (FSL_FEATURE_SAI_HAS_MCR) - config->mclkOutputEnable = true; -#endif /* FSL_FEATURE_SAI_HAS_MCR */ -} - -void SAI_RxGetDefaultConfig(sai_config_t *config) -{ - config->bclkSource = kSAI_BclkSourceMclkDiv; - config->masterSlave = kSAI_Master; - config->mclkSource = kSAI_MclkSourceSysclk; - config->protocol = kSAI_BusLeftJustified; - config->syncMode = kSAI_ModeSync; -#if defined(FSL_FEATURE_SAI_HAS_MCR) && (FSL_FEATURE_SAI_HAS_MCR) - config->mclkOutputEnable = true; -#endif /* FSL_FEATURE_SAI_HAS_MCR */ -} - -void SAI_TxReset(I2S_Type *base) -{ - /* Set the software reset and FIFO reset to clear internal state */ - base->TCSR = I2S_TCSR_SR_MASK | I2S_TCSR_FR_MASK; - - /* Clear software reset bit, this should be done by software */ - base->TCSR &= ~I2S_TCSR_SR_MASK; - - /* Reset all Tx register values */ - base->TCR2 = 0; - base->TCR3 = 0; - base->TCR4 = 0; - base->TCR5 = 0; - base->TMR = 0; -} - -void SAI_RxReset(I2S_Type *base) -{ - /* Set the software reset and FIFO reset to clear internal state */ - base->RCSR = I2S_RCSR_SR_MASK | I2S_RCSR_FR_MASK; - - /* Clear software reset bit, this should be done by software */ - base->RCSR &= ~I2S_RCSR_SR_MASK; - - /* Reset all Rx register values */ - base->RCR2 = 0; - base->RCR3 = 0; - base->RCR4 = 0; - base->RCR5 = 0; - base->RMR = 0; -} - -void SAI_TxEnable(I2S_Type *base, bool enable) -{ - if (enable) - { - /* If clock is sync with Rx, should enable RE bit. */ - if (((base->TCR2 & I2S_TCR2_SYNC_MASK) >> I2S_TCR2_SYNC_SHIFT) == 0x1U) - { - base->RCSR = ((base->RCSR & 0xFFE3FFFFU) | I2S_RCSR_RE_MASK); - } - base->TCSR = ((base->TCSR & 0xFFE3FFFFU) | I2S_TCSR_TE_MASK); - } - else - { - /* Should not close RE even sync with Rx */ - base->TCSR = ((base->TCSR & 0xFFE3FFFFU) & (~I2S_TCSR_TE_MASK)); - } -} - -void SAI_RxEnable(I2S_Type *base, bool enable) -{ - if (enable) - { - /* If clock is sync with Tx, should enable TE bit. */ - if (((base->RCR2 & I2S_RCR2_SYNC_MASK) >> I2S_RCR2_SYNC_SHIFT) == 0x1U) - { - base->TCSR = ((base->TCSR & 0xFFE3FFFFU) | I2S_TCSR_TE_MASK); - } - base->RCSR = ((base->RCSR & 0xFFE3FFFFU) | I2S_RCSR_RE_MASK); - } - else - { - base->RCSR = ((base->RCSR & 0xFFE3FFFFU) & (~I2S_RCSR_RE_MASK)); - } -} - -void SAI_TxSetFormat(I2S_Type *base, - sai_transfer_format_t *format, - uint32_t mclkSourceClockHz, - uint32_t bclkSourceClockHz) -{ - uint32_t bclk = format->sampleRate_Hz * 32U * 2U; - -/* Compute the mclk */ -#if defined(FSL_FEATURE_SAI_HAS_MCLKDIV_REGISTER) && (FSL_FEATURE_SAI_HAS_MCLKDIV_REGISTER) - /* Check if master clock divider enabled, then set master clock divider */ - if (base->MCR & I2S_MCR_MOE_MASK) - { - SAI_SetMasterClockDivider(base, format->masterClockHz, mclkSourceClockHz); - } -#endif /* FSL_FEATURE_SAI_HAS_MCLKDIV_REGISTER */ - - /* Set bclk if needed */ - if (base->TCR2 & I2S_TCR2_BCD_MASK) - { - base->TCR2 &= ~I2S_TCR2_DIV_MASK; - base->TCR2 |= I2S_TCR2_DIV((bclkSourceClockHz / bclk) / 2U - 1U); - } - - /* Set bitWidth */ - if (format->protocol == kSAI_BusRightJustified) - { - base->TCR5 = I2S_TCR5_WNW(31U) | I2S_TCR5_W0W(31U) | I2S_TCR5_FBT(31U); - } - else - { - base->TCR5 = I2S_TCR5_WNW(31U) | I2S_TCR5_W0W(31U) | I2S_TCR5_FBT(format->bitWidth - 1); - } - - /* Set mono or stereo */ - base->TMR = (uint32_t)format->stereo; - - /* Set data channel */ - base->TCR3 &= ~I2S_TCR3_TCE_MASK; - base->TCR3 |= I2S_TCR3_TCE(1U << format->channel); - -#if defined(FSL_FEATURE_SAI_FIFO_COUNT) && (FSL_FEATURE_SAI_FIFO_COUNT > 1) - /* Set watermark */ - base->TCR1 = format->watermark; -#endif /* FSL_FEATURE_SAI_FIFO_COUNT */ -} - -void SAI_RxSetFormat(I2S_Type *base, - sai_transfer_format_t *format, - uint32_t mclkSourceClockHz, - uint32_t bclkSourceClockHz) -{ - uint32_t bclk = format->sampleRate_Hz * 32U * 2U; - -/* Compute the mclk */ -#if defined(FSL_FEATURE_SAI_HAS_MCLKDIV_REGISTER) && (FSL_FEATURE_SAI_HAS_MCLKDIV_REGISTER) - /* Check if master clock divider enabled */ - if (base->MCR & I2S_MCR_MOE_MASK) - { - SAI_SetMasterClockDivider(base, format->masterClockHz, mclkSourceClockHz); - } -#endif /* FSL_FEATURE_SAI_HAS_MCLKDIV_REGISTER */ - - /* Set bclk if needed */ - if (base->RCR2 & I2S_RCR2_BCD_MASK) - { - base->RCR2 &= ~I2S_RCR2_DIV_MASK; - base->RCR2 |= I2S_RCR2_DIV((bclkSourceClockHz / bclk) / 2U - 1U); - } - - /* Set bitWidth */ - if (format->protocol == kSAI_BusRightJustified) - { - base->RCR5 = I2S_RCR5_WNW(31U) | I2S_RCR5_W0W(31U) | I2S_RCR5_FBT(31U); - } - else - { - base->RCR5 = I2S_RCR5_WNW(31U) | I2S_RCR5_W0W(31U) | I2S_RCR5_FBT(format->bitWidth - 1); - } - - /* Set mono or stereo */ - base->RMR = (uint32_t)format->stereo; - - /* Set data channel */ - base->RCR3 &= ~I2S_RCR3_RCE_MASK; - base->RCR3 |= I2S_RCR3_RCE(1U << format->channel); - -#if defined(FSL_FEATURE_SAI_FIFO_COUNT) && (FSL_FEATURE_SAI_FIFO_COUNT > 1) - /* Set watermark */ - base->RCR1 = format->watermark; -#endif /* FSL_FEATURE_SAI_FIFO_COUNT */ -} - -void SAI_WriteBlocking(I2S_Type *base, uint32_t channel, uint32_t bitWidth, uint8_t *buffer, uint32_t size) -{ - uint32_t i = 0; - uint8_t bytesPerWord = bitWidth / 8U; - - while (i < size) - { - /* Wait until it can write data */ - while (!(base->TCSR & I2S_TCSR_FWF_MASK)) - { - } - - SAI_WriteNonBlocking(base, channel, bitWidth, buffer, bytesPerWord); - buffer += bytesPerWord; - i += bytesPerWord; - } - - /* Wait until the last data is sent */ - while (!(base->TCSR & I2S_TCSR_FWF_MASK)) - { - } -} - -void SAI_ReadBlocking(I2S_Type *base, uint32_t channel, uint32_t bitWidth, uint8_t *buffer, uint32_t size) -{ - uint32_t i = 0; - uint8_t bytesPerWord = bitWidth / 8U; - - while (i < size) - { - /* Wait until data is received */ - while (!(base->RCSR & I2S_RCSR_FWF_MASK)) - { - } - - SAI_ReadNonBlocking(base, channel, bitWidth, buffer, bytesPerWord); - buffer += bytesPerWord; - i += bytesPerWord; - } -} - -void SAI_TransferTxCreateHandle(I2S_Type *base, sai_handle_t *handle, sai_transfer_callback_t callback, void *userData) -{ - assert(handle); - - /* Zero the handle */ - memset(handle, 0, sizeof(*handle)); - - s_saiHandle[SAI_GetInstance(base)][0] = handle; - - handle->callback = callback; - handle->userData = userData; - - /* Set the isr pointer */ - s_saiTxIsr = SAI_TransferTxHandleIRQ; - - /* Enable Tx irq */ - EnableIRQ(s_saiTxIRQ[SAI_GetInstance(base)]); -} - -void SAI_TransferRxCreateHandle(I2S_Type *base, sai_handle_t *handle, sai_transfer_callback_t callback, void *userData) -{ - assert(handle); - - /* Zero the handle */ - memset(handle, 0, sizeof(*handle)); - - s_saiHandle[SAI_GetInstance(base)][1] = handle; - - handle->callback = callback; - handle->userData = userData; - - /* Set the isr pointer */ - s_saiRxIsr = SAI_TransferRxHandleIRQ; - - /* Enable Rx irq */ - EnableIRQ(s_saiRxIRQ[SAI_GetInstance(base)]); -} - -status_t SAI_TransferTxSetFormat(I2S_Type *base, - sai_handle_t *handle, - sai_transfer_format_t *format, - uint32_t mclkSourceClockHz, - uint32_t bclkSourceClockHz) -{ - assert(handle); - - if ((mclkSourceClockHz < format->sampleRate_Hz) || (bclkSourceClockHz < format->sampleRate_Hz)) - { - return kStatus_InvalidArgument; - } - - /* Copy format to handle */ - handle->bitWidth = format->bitWidth; -#if defined(FSL_FEATURE_SAI_FIFO_COUNT) && (FSL_FEATURE_SAI_FIFO_COUNT > 1) - handle->watermark = format->watermark; -#endif - handle->channel = format->channel; - - SAI_TxSetFormat(base, format, mclkSourceClockHz, bclkSourceClockHz); - - return kStatus_Success; -} - -status_t SAI_TransferRxSetFormat(I2S_Type *base, - sai_handle_t *handle, - sai_transfer_format_t *format, - uint32_t mclkSourceClockHz, - uint32_t bclkSourceClockHz) -{ - assert(handle); - - if ((mclkSourceClockHz < format->sampleRate_Hz) || (bclkSourceClockHz < format->sampleRate_Hz)) - { - return kStatus_InvalidArgument; - } - - /* Copy format to handle */ - handle->bitWidth = format->bitWidth; -#if defined(FSL_FEATURE_SAI_FIFO_COUNT) && (FSL_FEATURE_SAI_FIFO_COUNT > 1) - handle->watermark = format->watermark; -#endif - handle->channel = format->channel; - - SAI_RxSetFormat(base, format, mclkSourceClockHz, bclkSourceClockHz); - - return kStatus_Success; -} - -status_t SAI_TransferSendNonBlocking(I2S_Type *base, sai_handle_t *handle, sai_transfer_t *xfer) -{ - assert(handle); - - /* Check if the queue is full */ - if (handle->saiQueue[handle->queueUser].data) - { - return kStatus_SAI_QueueFull; - } - - /* Add into queue */ - handle->transferSize[handle->queueUser] = xfer->dataSize; - handle->saiQueue[handle->queueUser].data = xfer->data; - handle->saiQueue[handle->queueUser].dataSize = xfer->dataSize; - handle->queueUser = (handle->queueUser + 1) % SAI_XFER_QUEUE_SIZE; - - /* Set the state to busy */ - handle->state = kSAI_Busy; - -/* Enable interrupt */ -#if defined(FSL_FEATURE_SAI_FIFO_COUNT) && (FSL_FEATURE_SAI_FIFO_COUNT > 1) - /* Use FIFO request interrupt and fifo error*/ - SAI_TxEnableInterrupts(base, kSAI_FIFOErrorInterruptEnable | kSAI_FIFORequestInterruptEnable); -#else - SAI_TxEnableInterrupts(base, kSAI_FIFOErrorInterruptEnable | kSAI_FIFOWarningInterruptEnable); -#endif /* FSL_FEATURE_SAI_FIFO_COUNT */ - - /* Enable Tx transfer */ - SAI_TxEnable(base, true); - - return kStatus_Success; -} - -status_t SAI_TransferReceiveNonBlocking(I2S_Type *base, sai_handle_t *handle, sai_transfer_t *xfer) -{ - assert(handle); - - /* Check if the queue is full */ - if (handle->saiQueue[handle->queueUser].data) - { - return kStatus_SAI_QueueFull; - } - - /* Add into queue */ - handle->transferSize[handle->queueUser] = xfer->dataSize; - handle->saiQueue[handle->queueUser].data = xfer->data; - handle->saiQueue[handle->queueUser].dataSize = xfer->dataSize; - handle->queueUser = (handle->queueUser + 1) % SAI_XFER_QUEUE_SIZE; - - /* Set state to busy */ - handle->state = kSAI_Busy; - -/* Enable interrupt */ -#if defined(FSL_FEATURE_SAI_FIFO_COUNT) && (FSL_FEATURE_SAI_FIFO_COUNT > 1) - /* Use FIFO request interrupt and fifo error*/ - SAI_RxEnableInterrupts(base, kSAI_FIFOErrorInterruptEnable | kSAI_FIFORequestInterruptEnable); -#else - SAI_RxEnableInterrupts(base, kSAI_FIFOErrorInterruptEnable | kSAI_FIFOWarningInterruptEnable); -#endif /* FSL_FEATURE_SAI_FIFO_COUNT */ - - /* Enable Rx transfer */ - SAI_RxEnable(base, true); - - return kStatus_Success; -} - -status_t SAI_TransferGetSendCount(I2S_Type *base, sai_handle_t *handle, size_t *count) -{ - assert(handle); - - status_t status = kStatus_Success; - - if (handle->state != kSAI_Busy) - { - status = kStatus_NoTransferInProgress; - } - else - { - *count = (handle->transferSize[handle->queueDriver] - handle->saiQueue[handle->queueDriver].dataSize); - } - - return status; -} - -status_t SAI_TransferGetReceiveCount(I2S_Type *base, sai_handle_t *handle, size_t *count) -{ - assert(handle); - - status_t status = kStatus_Success; - - if (handle->state != kSAI_Busy) - { - status = kStatus_NoTransferInProgress; - } - else - { - *count = (handle->transferSize[handle->queueDriver] - handle->saiQueue[handle->queueDriver].dataSize); - } - - return status; -} - -void SAI_TransferAbortSend(I2S_Type *base, sai_handle_t *handle) -{ - assert(handle); - - /* Stop Tx transfer and disable interrupt */ - SAI_TxEnable(base, false); -#if defined(FSL_FEATURE_SAI_FIFO_COUNT) && (FSL_FEATURE_SAI_FIFO_COUNT > 1) - /* Use FIFO request interrupt and fifo error */ - SAI_TxDisableInterrupts(base, kSAI_FIFOErrorInterruptEnable | kSAI_FIFORequestInterruptEnable); -#else - SAI_TxDisableInterrupts(base, kSAI_FIFOErrorInterruptEnable | kSAI_FIFOWarningInterruptEnable); -#endif /* FSL_FEATURE_SAI_FIFO_COUNT */ - - handle->state = kSAI_Idle; - - /* Clear the queue */ - memset(handle->saiQueue, 0, sizeof(sai_transfer_t) * SAI_XFER_QUEUE_SIZE); - handle->queueDriver = 0; - handle->queueUser = 0; -} - -void SAI_TransferAbortReceive(I2S_Type *base, sai_handle_t *handle) -{ - assert(handle); - - /* Stop Tx transfer and disable interrupt */ - SAI_RxEnable(base, false); -#if defined(FSL_FEATURE_SAI_FIFO_COUNT) && (FSL_FEATURE_SAI_FIFO_COUNT > 1) - /* Use FIFO request interrupt and fifo error */ - SAI_RxDisableInterrupts(base, kSAI_FIFOErrorInterruptEnable | kSAI_FIFORequestInterruptEnable); -#else - SAI_RxDisableInterrupts(base, kSAI_FIFOErrorInterruptEnable | kSAI_FIFOWarningInterruptEnable); -#endif /* FSL_FEATURE_SAI_FIFO_COUNT */ - - handle->state = kSAI_Idle; - - /* Clear the queue */ - memset(handle->saiQueue, 0, sizeof(sai_transfer_t) * SAI_XFER_QUEUE_SIZE); - handle->queueDriver = 0; - handle->queueUser = 0; -} - -void SAI_TransferTxHandleIRQ(I2S_Type *base, sai_handle_t *handle) -{ - assert(handle); - - uint8_t *buffer = handle->saiQueue[handle->queueDriver].data; - uint8_t dataSize = handle->bitWidth / 8U; - - /* Handle Error */ - if (base->TCSR & I2S_TCSR_FEF_MASK) - { - /* Clear FIFO error flag to continue transfer */ - SAI_TxClearStatusFlags(base, kSAI_FIFOErrorFlag); - - /* Call the callback */ - if (handle->callback) - { - (handle->callback)(base, handle, kStatus_SAI_TxError, handle->userData); - } - } - -/* Handle transfer */ -#if defined(FSL_FEATURE_SAI_FIFO_COUNT) && (FSL_FEATURE_SAI_FIFO_COUNT > 1) - if (base->TCSR & I2S_TCSR_FRF_MASK) - { - /* Judge if the data need to transmit is less than space */ - uint8_t size = MIN((handle->saiQueue[handle->queueDriver].dataSize), - (size_t)((FSL_FEATURE_SAI_FIFO_COUNT - handle->watermark) * dataSize)); - - /* Copy the data from sai buffer to FIFO */ - SAI_WriteNonBlocking(base, handle->channel, handle->bitWidth, buffer, size); - - /* Update the internal counter */ - handle->saiQueue[handle->queueDriver].dataSize -= size; - handle->saiQueue[handle->queueDriver].data += size; - } -#else - if (base->TCSR & I2S_TCSR_FWF_MASK) - { - uint8_t size = MIN((handle->saiQueue[handle->queueDriver].dataSize), dataSize); - - SAI_WriteNonBlocking(base, handle->channel, handle->bitWidth, buffer, size); - - /* Update internal counter */ - handle->saiQueue[handle->queueDriver].dataSize -= size; - handle->saiQueue[handle->queueDriver].data += size; - } -#endif /* FSL_FEATURE_SAI_FIFO_COUNT */ - - /* If finished a blcok, call the callback function */ - if (handle->saiQueue[handle->queueDriver].dataSize == 0U) - { - memset(&handle->saiQueue[handle->queueDriver], 0, sizeof(sai_transfer_t)); - handle->queueDriver = (handle->queueDriver + 1) % SAI_XFER_QUEUE_SIZE; - if (handle->callback) - { - (handle->callback)(base, handle, kStatus_SAI_TxIdle, handle->userData); - } - } - - /* If all data finished, just stop the transfer */ - if (handle->saiQueue[handle->queueDriver].data == NULL) - { - SAI_TransferAbortSend(base, handle); - } -} - -void SAI_TransferRxHandleIRQ(I2S_Type *base, sai_handle_t *handle) -{ - assert(handle); - - uint8_t *buffer = handle->saiQueue[handle->queueDriver].data; - uint8_t dataSize = handle->bitWidth / 8U; - - /* Handle Error */ - if (base->RCSR & I2S_RCSR_FEF_MASK) - { - /* Clear FIFO error flag to continue transfer */ - SAI_RxClearStatusFlags(base, kSAI_FIFOErrorFlag); - - /* Call the callback */ - if (handle->callback) - { - (handle->callback)(base, handle, kStatus_SAI_RxError, handle->userData); - } - } - -/* Handle transfer */ -#if defined(FSL_FEATURE_SAI_FIFO_COUNT) && (FSL_FEATURE_SAI_FIFO_COUNT > 1) - if (base->RCSR & I2S_RCSR_FRF_MASK) - { - /* Judge if the data need to transmit is less than space */ - uint8_t size = MIN((handle->saiQueue[handle->queueDriver].dataSize), (handle->watermark * dataSize)); - - /* Copy the data from sai buffer to FIFO */ - SAI_ReadNonBlocking(base, handle->channel, handle->bitWidth, buffer, size); - - /* Update the internal counter */ - handle->saiQueue[handle->queueDriver].dataSize -= size; - handle->saiQueue[handle->queueDriver].data += size; - } -#else - if (base->RCSR & I2S_RCSR_FWF_MASK) - { - uint8_t size = MIN((handle->saiQueue[handle->queueDriver].dataSize), dataSize); - - SAI_ReadNonBlocking(base, handle->channel, handle->bitWidth, buffer, size); - - /* Update internal state */ - handle->saiQueue[handle->queueDriver].dataSize -= size; - handle->saiQueue[handle->queueDriver].data += size; - } -#endif /* FSL_FEATURE_SAI_FIFO_COUNT */ - - /* If finished a blcok, call the callback function */ - if (handle->saiQueue[handle->queueDriver].dataSize == 0U) - { - memset(&handle->saiQueue[handle->queueDriver], 0, sizeof(sai_transfer_t)); - handle->queueDriver = (handle->queueDriver + 1) % SAI_XFER_QUEUE_SIZE; - if (handle->callback) - { - (handle->callback)(base, handle, kStatus_SAI_RxIdle, handle->userData); - } - } - - /* If all data finished, just stop the transfer */ - if (handle->saiQueue[handle->queueDriver].data == NULL) - { - SAI_TransferAbortReceive(base, handle); - } -} - -#if defined(I2S0) -void I2S0_DriverIRQHandler(void) -{ -#if defined(FSL_FEATURE_SAI_FIFO_COUNT) && (FSL_FEATURE_SAI_FIFO_COUNT > 1) - if ((s_saiHandle[0][1]) && ((I2S0->RCSR & kSAI_FIFORequestFlag) || (I2S0->RCSR & kSAI_FIFOErrorFlag)) && - ((I2S0->RCSR & kSAI_FIFORequestInterruptEnable) || (I2S0->RCSR & kSAI_FIFOErrorInterruptEnable))) -#else - if ((s_saiHandle[0][1]) && ((I2S0->RCSR & kSAI_FIFOWarningFlag) || (I2S0->RCSR & kSAI_FIFOErrorFlag)) && - ((I2S0->RCSR & kSAI_FIFOWarningInterruptEnable) || (I2S0->RCSR & kSAI_FIFOErrorInterruptEnable))) -#endif - { - s_saiRxIsr(I2S0, s_saiHandle[0][1]); - } -#if defined(FSL_FEATURE_SAI_FIFO_COUNT) && (FSL_FEATURE_SAI_FIFO_COUNT > 1) - if ((s_saiHandle[0][0]) && ((I2S0->TCSR & kSAI_FIFORequestFlag) || (I2S0->TCSR & kSAI_FIFOErrorFlag)) && - ((I2S0->TCSR & kSAI_FIFORequestInterruptEnable) || (I2S0->TCSR & kSAI_FIFOErrorInterruptEnable))) -#else - if ((s_saiHandle[0][0]) && ((I2S0->TCSR & kSAI_FIFOWarningFlag) || (I2S0->TCSR & kSAI_FIFOErrorFlag)) && - ((I2S0->TCSR & kSAI_FIFOWarningInterruptEnable) || (I2S0->TCSR & kSAI_FIFOErrorInterruptEnable))) -#endif - { - s_saiTxIsr(I2S0, s_saiHandle[0][0]); - } -} - -void I2S0_Tx_DriverIRQHandler(void) -{ - assert(s_saiHandle[0][0]); - s_saiTxIsr(I2S0, s_saiHandle[0][0]); -} - -void I2S0_Rx_DriverIRQHandler(void) -{ - assert(s_saiHandle[0][1]); - s_saiRxIsr(I2S0, s_saiHandle[0][1]); -} -#endif /* I2S0*/ - -#if defined(I2S1) -void I2S1_DriverIRQHandler(void) -{ -#if defined(FSL_FEATURE_SAI_FIFO_COUNT) && (FSL_FEATURE_SAI_FIFO_COUNT > 1) - if ((s_saiHandle[1][1]) && ((I2S1->RCSR & kSAI_FIFORequestFlag) || (I2S1->RCSR & kSAI_FIFOErrorFlag)) && - ((I2S1->RCSR & kSAI_FIFORequestInterruptEnable) || (I2S1->RCSR & kSAI_FIFOErrorInterruptEnable))) -#else - if ((s_saiHandle[1][1]) && ((I2S1->RCSR & kSAI_FIFOWarningFlag) || (I2S1->RCSR & kSAI_FIFOErrorFlag)) && - ((I2S1->RCSR & kSAI_FIFOWarningInterruptEnable) || (I2S1->RCSR & kSAI_FIFOErrorInterruptEnable))) -#endif - { - s_saiRxIsr(I2S1, s_saiHandle[1][1]); - } -#if defined(FSL_FEATURE_SAI_FIFO_COUNT) && (FSL_FEATURE_SAI_FIFO_COUNT > 1) - if ((s_saiHandle[1][0]) && ((I2S1->TCSR & kSAI_FIFORequestFlag) || (I2S1->TCSR & kSAI_FIFOErrorFlag)) && - ((I2S1->TCSR & kSAI_FIFORequestInterruptEnable) || (I2S1->TCSR & kSAI_FIFOErrorInterruptEnable))) -#else - if ((s_saiHandle[1][0]) && ((I2S1->TCSR & kSAI_FIFOWarningFlag) || (I2S1->TCSR & kSAI_FIFOErrorFlag)) && - ((I2S1->TCSR & kSAI_FIFOWarningInterruptEnable) || (I2S1->TCSR & kSAI_FIFOErrorInterruptEnable))) -#endif - { - s_saiTxIsr(I2S1, s_saiHandle[1][0]); - } -} - -void I2S1_Tx_DriverIRQHandler(void) -{ - assert(s_saiHandle[1][0]); - s_saiTxIsr(I2S1, s_saiHandle[1][0]); -} - -void I2S1_Rx_DriverIRQHandler(void) -{ - assert(s_saiHandle[1][1]); - s_saiRxIsr(I2S1, s_saiHandle[1][1]); -} -#endif /* I2S1*/ - -#if defined(I2S2) -void I2S2_DriverIRQHandler(void) -{ -#if defined(FSL_FEATURE_SAI_FIFO_COUNT) && (FSL_FEATURE_SAI_FIFO_COUNT > 1) - if ((s_saiHandle[2][1]) && ((I2S2->RCSR & kSAI_FIFORequestFlag) || (I2S2->RCSR & kSAI_FIFOErrorFlag)) && - ((I2S2->RCSR & kSAI_FIFORequestInterruptEnable) || (I2S2->RCSR & kSAI_FIFOErrorInterruptEnable))) -#else - if ((s_saiHandle[2][1]) && ((I2S2->RCSR & kSAI_FIFOWarningFlag) || (I2S2->RCSR & kSAI_FIFOErrorFlag)) && - ((I2S2->RCSR & kSAI_FIFOWarningInterruptEnable) || (I2S2->RCSR & kSAI_FIFOErrorInterruptEnable))) -#endif - { - s_saiRxIsr(I2S2, s_saiHandle[2][1]); - } -#if defined(FSL_FEATURE_SAI_FIFO_COUNT) && (FSL_FEATURE_SAI_FIFO_COUNT > 1) - if ((s_saiHandle[2][0]) && ((I2S2->TCSR & kSAI_FIFORequestFlag) || (I2S2->TCSR & kSAI_FIFOErrorFlag)) && - ((I2S2->TCSR & kSAI_FIFORequestInterruptEnable) || (I2S2->TCSR & kSAI_FIFOErrorInterruptEnable))) -#else - if ((s_saiHandle[2][0]) && ((I2S2->TCSR & kSAI_FIFOWarningFlag) || (I2S2->TCSR & kSAI_FIFOErrorFlag)) && - ((I2S2->TCSR & kSAI_FIFOWarningInterruptEnable) || (I2S2->TCSR & kSAI_FIFOErrorInterruptEnable))) -#endif - { - s_saiTxIsr(I2S2, s_saiHandle[2][0]); - } -} - -void I2S2_Tx_DriverIRQHandler(void) -{ - assert(s_saiHandle[2][0]); - s_saiTxIsr(I2S2, s_saiHandle[2][0]); -} - -void I2S2_Rx_DriverIRQHandler(void) -{ - assert(s_saiHandle[2][1]); - s_saiRxIsr(I2S2, s_saiHandle[2][1]); -} -#endif /* I2S2*/ - -#if defined(I2S3) -void I2S3_DriverIRQHandler(void) -{ -#if defined(FSL_FEATURE_SAI_FIFO_COUNT) && (FSL_FEATURE_SAI_FIFO_COUNT > 1) - if ((s_saiHandle[3][1]) && ((I2S3->RCSR & kSAI_FIFORequestFlag) || (I2S3->RCSR & kSAI_FIFOErrorFlag)) && - ((I2S3->RCSR & kSAI_FIFORequestInterruptEnable) || (I2S3->RCSR & kSAI_FIFOErrorInterruptEnable))) -#else - if ((s_saiHandle[3][1]) && ((I2S3->RCSR & kSAI_FIFOWarningFlag) || (I2S3->RCSR & kSAI_FIFOErrorFlag)) && - ((I2S3->RCSR & kSAI_FIFOWarningInterruptEnable) || (I2S3->RCSR & kSAI_FIFOErrorInterruptEnable))) -#endif - { - s_saiRxIsr(I2S3, s_saiHandle[3][1]); - } -#if defined(FSL_FEATURE_SAI_FIFO_COUNT) && (FSL_FEATURE_SAI_FIFO_COUNT > 1) - if ((s_saiHandle[3][0]) && ((I2S3->TCSR & kSAI_FIFORequestFlag) || (I2S3->TCSR & kSAI_FIFOErrorFlag)) && - ((I2S3->TCSR & kSAI_FIFORequestInterruptEnable) || (I2S3->TCSR & kSAI_FIFOErrorInterruptEnable))) -#else - if ((s_saiHandle[3][0]) && ((I2S3->TCSR & kSAI_FIFOWarningFlag) || (I2S3->TCSR & kSAI_FIFOErrorFlag)) && - ((I2S3->TCSR & kSAI_FIFOWarningInterruptEnable) || (I2S3->TCSR & kSAI_FIFOErrorInterruptEnable))) -#endif - { - s_saiTxIsr(I2S3, s_saiHandle[3][0]); - } -} - -void I2S3_Tx_DriverIRQHandler(void) -{ - assert(s_saiHandle[3][0]); - s_saiTxIsr(I2S3, s_saiHandle[3][0]); -} - -void I2S3_Rx_DriverIRQHandler(void) -{ - assert(s_saiHandle[3][1]); - s_saiRxIsr(I2S3, s_saiHandle[3][1]); -} -#endif /* I2S3*/ diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_sai.h b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_sai.h deleted file mode 100644 index 64a2f667fce..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_sai.h +++ /dev/null @@ -1,848 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef _FSL_SAI_H_ -#define _FSL_SAI_H_ - -#include "fsl_common.h" - -/*! - * @addtogroup sai - * @{ - */ - -/******************************************************************************* - * Definitions - ******************************************************************************/ - -/*! @name Driver version */ -/*@{*/ -#define FSL_SAI_DRIVER_VERSION (MAKE_VERSION(2, 1, 2)) /*!< Version 2.1.2 */ -/*@}*/ - -/*! @brief SAI return status*/ -enum _sai_status_t -{ - kStatus_SAI_TxBusy = MAKE_STATUS(kStatusGroup_SAI, 0), /*!< SAI Tx is busy. */ - kStatus_SAI_RxBusy = MAKE_STATUS(kStatusGroup_SAI, 1), /*!< SAI Rx is busy. */ - kStatus_SAI_TxError = MAKE_STATUS(kStatusGroup_SAI, 2), /*!< SAI Tx FIFO error. */ - kStatus_SAI_RxError = MAKE_STATUS(kStatusGroup_SAI, 3), /*!< SAI Rx FIFO error. */ - kStatus_SAI_QueueFull = MAKE_STATUS(kStatusGroup_SAI, 4), /*!< SAI transfer queue is full. */ - kStatus_SAI_TxIdle = MAKE_STATUS(kStatusGroup_SAI, 5), /*!< SAI Tx is idle */ - kStatus_SAI_RxIdle = MAKE_STATUS(kStatusGroup_SAI, 6) /*!< SAI Rx is idle */ -}; - -/*! @brief Define the SAI bus type */ -typedef enum _sai_protocol -{ - kSAI_BusLeftJustified = 0x0U, /*!< Uses left justified format.*/ - kSAI_BusRightJustified, /*!< Uses right justified format. */ - kSAI_BusI2S, /*!< Uses I2S format. */ - kSAI_BusPCMA, /*!< Uses I2S PCM A format.*/ - kSAI_BusPCMB /*!< Uses I2S PCM B format. */ -} sai_protocol_t; - -/*! @brief Master or slave mode */ -typedef enum _sai_master_slave -{ - kSAI_Master = 0x0U, /*!< Master mode */ - kSAI_Slave = 0x1U /*!< Slave mode */ -} sai_master_slave_t; - -/*! @brief Mono or stereo audio format */ -typedef enum _sai_mono_stereo -{ - kSAI_Stereo = 0x0U, /*!< Stereo sound. */ - kSAI_MonoLeft, /*!< Only left channel have sound. */ - kSAI_MonoRight /*!< Only Right channel have sound. */ -} sai_mono_stereo_t; - -/*! @brief Synchronous or asynchronous mode */ -typedef enum _sai_sync_mode -{ - kSAI_ModeAsync = 0x0U, /*!< Asynchronous mode */ - kSAI_ModeSync, /*!< Synchronous mode (with receiver or transmit) */ - kSAI_ModeSyncWithOtherTx, /*!< Synchronous with another SAI transmit */ - kSAI_ModeSyncWithOtherRx /*!< Synchronous with another SAI receiver */ -} sai_sync_mode_t; - -/*! @brief Mater clock source */ -typedef enum _sai_mclk_source -{ - kSAI_MclkSourceSysclk = 0x0U, /*!< Master clock from the system clock */ - kSAI_MclkSourceSelect1, /*!< Master clock from source 1 */ - kSAI_MclkSourceSelect2, /*!< Master clock from source 2 */ - kSAI_MclkSourceSelect3 /*!< Master clock from source 3 */ -} sai_mclk_source_t; - -/*! @brief Bit clock source */ -typedef enum _sai_bclk_source -{ - kSAI_BclkSourceBusclk = 0x0U, /*!< Bit clock using bus clock */ - kSAI_BclkSourceMclkDiv, /*!< Bit clock using master clock divider */ - kSAI_BclkSourceOtherSai0, /*!< Bit clock from other SAI device */ - kSAI_BclkSourceOtherSai1 /*!< Bit clock from other SAI device */ -} sai_bclk_source_t; - -/*! @brief The SAI interrupt enable flag */ -enum _sai_interrupt_enable_t -{ - kSAI_WordStartInterruptEnable = - I2S_TCSR_WSIE_MASK, /*!< Word start flag, means the first word in a frame detected */ - kSAI_SyncErrorInterruptEnable = I2S_TCSR_SEIE_MASK, /*!< Sync error flag, means the sync error is detected */ - kSAI_FIFOWarningInterruptEnable = I2S_TCSR_FWIE_MASK, /*!< FIFO warning flag, means the FIFO is empty */ - kSAI_FIFOErrorInterruptEnable = I2S_TCSR_FEIE_MASK, /*!< FIFO error flag */ -#if defined(FSL_FEATURE_SAI_FIFO_COUNT) && (FSL_FEATURE_SAI_FIFO_COUNT > 1) - kSAI_FIFORequestInterruptEnable = I2S_TCSR_FRIE_MASK, /*!< FIFO request, means reached watermark */ -#endif /* FSL_FEATURE_SAI_FIFO_COUNT */ -}; - -/*! @brief The DMA request sources */ -enum _sai_dma_enable_t -{ - kSAI_FIFOWarningDMAEnable = I2S_TCSR_FWDE_MASK, /*!< FIFO warning caused by the DMA request */ -#if defined(FSL_FEATURE_SAI_FIFO_COUNT) && (FSL_FEATURE_SAI_FIFO_COUNT > 1) - kSAI_FIFORequestDMAEnable = I2S_TCSR_FRDE_MASK, /*!< FIFO request caused by the DMA request */ -#endif /* FSL_FEATURE_SAI_FIFO_COUNT */ -}; - -/*! @brief The SAI status flag */ -enum _sai_flags -{ - kSAI_WordStartFlag = I2S_TCSR_WSF_MASK, /*!< Word start flag, means the first word in a frame detected */ - kSAI_SyncErrorFlag = I2S_TCSR_SEF_MASK, /*!< Sync error flag, means the sync error is detected */ - kSAI_FIFOErrorFlag = I2S_TCSR_FEF_MASK, /*!< FIFO error flag */ -#if defined(FSL_FEATURE_SAI_FIFO_COUNT) && (FSL_FEATURE_SAI_FIFO_COUNT > 1) - kSAI_FIFORequestFlag = I2S_TCSR_FRF_MASK, /*!< FIFO request flag. */ -#endif /* FSL_FEATURE_SAI_FIFO_COUNT */ - kSAI_FIFOWarningFlag = I2S_TCSR_FWF_MASK, /*!< FIFO warning flag */ -}; - -/*! @brief The reset type */ -typedef enum _sai_reset_type -{ - kSAI_ResetTypeSoftware = I2S_TCSR_SR_MASK, /*!< Software reset, reset the logic state */ - kSAI_ResetTypeFIFO = I2S_TCSR_FR_MASK, /*!< FIFO reset, reset the FIFO read and write pointer */ - kSAI_ResetAll = I2S_TCSR_SR_MASK | I2S_TCSR_FR_MASK /*!< All reset. */ -} sai_reset_type_t; - -#if defined(FSL_FEATURE_SAI_HAS_FIFO_PACKING) && FSL_FEATURE_SAI_HAS_FIFO_PACKING -/*! - * @brief The SAI packing mode - * The mode includes 8 bit and 16 bit packing. - */ -typedef enum _sai_fifo_packing -{ - kSAI_FifoPackingDisabled = 0x0U, /*!< Packing disabled */ - kSAI_FifoPacking8bit = 0x2U, /*!< 8 bit packing enabled */ - kSAI_FifoPacking16bit = 0x3U /*!< 16bit packing enabled */ -} sai_fifo_packing_t; -#endif /* FSL_FEATURE_SAI_HAS_FIFO_PACKING */ - -/*! @brief SAI user configuration structure */ -typedef struct _sai_config -{ - sai_protocol_t protocol; /*!< Audio bus protocol in SAI */ - sai_sync_mode_t syncMode; /*!< SAI sync mode, control Tx/Rx clock sync */ -#if defined(FSL_FEATURE_SAI_HAS_MCR) && (FSL_FEATURE_SAI_HAS_MCR) - bool mclkOutputEnable; /*!< Master clock output enable, true means master clock divider enabled */ -#endif /* FSL_FEATURE_SAI_HAS_MCR */ - sai_mclk_source_t mclkSource; /*!< Master Clock source */ - sai_bclk_source_t bclkSource; /*!< Bit Clock source */ - sai_master_slave_t masterSlave; /*!< Master or slave */ -} sai_config_t; - -/*!@brief SAI transfer queue size, user can refine it according to use case. */ -#define SAI_XFER_QUEUE_SIZE (4) - -/*! @brief Audio sample rate */ -typedef enum _sai_sample_rate -{ - kSAI_SampleRate8KHz = 8000U, /*!< Sample rate 8000 Hz */ - kSAI_SampleRate11025Hz = 11025U, /*!< Sample rate 11025 Hz */ - kSAI_SampleRate12KHz = 12000U, /*!< Sample rate 12000 Hz */ - kSAI_SampleRate16KHz = 16000U, /*!< Sample rate 16000 Hz */ - kSAI_SampleRate22050Hz = 22050U, /*!< Sample rate 22050 Hz */ - kSAI_SampleRate24KHz = 24000U, /*!< Sample rate 24000 Hz */ - kSAI_SampleRate32KHz = 32000U, /*!< Sample rate 32000 Hz */ - kSAI_SampleRate44100Hz = 44100U, /*!< Sample rate 44100 Hz */ - kSAI_SampleRate48KHz = 48000U, /*!< Sample rate 48000 Hz */ - kSAI_SampleRate96KHz = 96000U /*!< Sample rate 96000 Hz */ -} sai_sample_rate_t; - -/*! @brief Audio word width */ -typedef enum _sai_word_width -{ - kSAI_WordWidth8bits = 8U, /*!< Audio data width 8 bits */ - kSAI_WordWidth16bits = 16U, /*!< Audio data width 16 bits */ - kSAI_WordWidth24bits = 24U, /*!< Audio data width 24 bits */ - kSAI_WordWidth32bits = 32U /*!< Audio data width 32 bits */ -} sai_word_width_t; - -/*! @brief sai transfer format */ -typedef struct _sai_transfer_format -{ - uint32_t sampleRate_Hz; /*!< Sample rate of audio data */ - uint32_t bitWidth; /*!< Data length of audio data, usually 8/16/24/32 bits */ - sai_mono_stereo_t stereo; /*!< Mono or stereo */ - uint32_t masterClockHz; /*!< Master clock frequency in Hz */ -#if defined(FSL_FEATURE_SAI_FIFO_COUNT) && (FSL_FEATURE_SAI_FIFO_COUNT > 1) - uint8_t watermark; /*!< Watermark value */ -#endif /* FSL_FEATURE_SAI_FIFO_COUNT */ - uint8_t channel; /*!< Data channel used in transfer.*/ - sai_protocol_t protocol; /*!< Which audio protocol used */ -} sai_transfer_format_t; - -/*! @brief SAI transfer structure */ -typedef struct _sai_transfer -{ - uint8_t *data; /*!< Data start address to transfer. */ - size_t dataSize; /*!< Transfer size. */ -} sai_transfer_t; - -typedef struct _sai_handle sai_handle_t; - -/*! @brief SAI transfer callback prototype */ -typedef void (*sai_transfer_callback_t)(I2S_Type *base, sai_handle_t *handle, status_t status, void *userData); - -/*! @brief SAI handle structure */ -struct _sai_handle -{ - uint32_t state; /*!< Transfer status */ - sai_transfer_callback_t callback; /*!< Callback function called at transfer event*/ - void *userData; /*!< Callback parameter passed to callback function*/ - uint8_t bitWidth; /*!< Bit width for transfer, 8/16/24/32 bits */ - uint8_t channel; /*!< Transfer channel */ - sai_transfer_t saiQueue[SAI_XFER_QUEUE_SIZE]; /*!< Transfer queue storing queued transfer */ - size_t transferSize[SAI_XFER_QUEUE_SIZE]; /*!< Data bytes need to transfer */ - volatile uint8_t queueUser; /*!< Index for user to queue transfer */ - volatile uint8_t queueDriver; /*!< Index for driver to get the transfer data and size */ -#if defined(FSL_FEATURE_SAI_FIFO_COUNT) && (FSL_FEATURE_SAI_FIFO_COUNT > 1) - uint8_t watermark; /*!< Watermark value */ -#endif -}; - -/******************************************************************************* - * API - ******************************************************************************/ - -#if defined(__cplusplus) -extern "C" { -#endif /*_cplusplus*/ - -/*! - * @name Initialization and deinitialization - * @{ - */ - -/*! - * @brief Initializes the SAI Tx peripheral. - * - * Ungates the SAI clock, resets the module, and configures SAI Tx with a configuration structure. - * The configuration structure can be custom filled or set with default values by - * SAI_TxGetDefaultConfig(). - * - * @note This API should be called at the beginning of the application to use - * the SAI driver. Otherwise, accessing the SAIM module can cause a hard fault - * because the clock is not enabled. - * - * @param base SAI base pointer - * @param config SAI configuration structure. -*/ -void SAI_TxInit(I2S_Type *base, const sai_config_t *config); - -/*! - * @brief Initializes the the SAI Rx peripheral. - * - * Ungates the SAI clock, resets the module, and configures the SAI Rx with a configuration structure. - * The configuration structure can be custom filled or set with default values by - * SAI_RxGetDefaultConfig(). - * - * @note This API should be called at the beginning of the application to use - * the SAI driver. Otherwise, accessing the SAI module can cause a hard fault - * because the clock is not enabled. - * - * @param base SAI base pointer - * @param config SAI configuration structure. - */ -void SAI_RxInit(I2S_Type *base, const sai_config_t *config); - -/*! - * @brief Sets the SAI Tx configuration structure to default values. - * - * This API initializes the configuration structure for use in SAI_TxConfig(). - * The initialized structure can remain unchanged in SAI_TxConfig(), or it can be modified - * before calling SAI_TxConfig(). - * This is an example. - @code - sai_config_t config; - SAI_TxGetDefaultConfig(&config); - @endcode - * - * @param config pointer to master configuration structure - */ -void SAI_TxGetDefaultConfig(sai_config_t *config); - -/*! - * @brief Sets the SAI Rx configuration structure to default values. - * - * This API initializes the configuration structure for use in SAI_RxConfig(). - * The initialized structure can remain unchanged in SAI_RxConfig() or it can be modified - * before calling SAI_RxConfig(). - * This is an example. - @code - sai_config_t config; - SAI_RxGetDefaultConfig(&config); - @endcode - * - * @param config pointer to master configuration structure - */ -void SAI_RxGetDefaultConfig(sai_config_t *config); - -/*! - * @brief De-initializes the SAI peripheral. - * - * This API gates the SAI clock. The SAI module can't operate unless SAI_TxInit - * or SAI_RxInit is called to enable the clock. - * - * @param base SAI base pointer -*/ -void SAI_Deinit(I2S_Type *base); - -/*! - * @brief Resets the SAI Tx. - * - * This function enables the software reset and FIFO reset of SAI Tx. After reset, clear the reset bit. - * - * @param base SAI base pointer - */ -void SAI_TxReset(I2S_Type *base); - -/*! - * @brief Resets the SAI Rx. - * - * This function enables the software reset and FIFO reset of SAI Rx. After reset, clear the reset bit. - * - * @param base SAI base pointer - */ -void SAI_RxReset(I2S_Type *base); - -/*! - * @brief Enables/disables the SAI Tx. - * - * @param base SAI base pointer - * @param enable True means enable SAI Tx, false means disable. - */ -void SAI_TxEnable(I2S_Type *base, bool enable); - -/*! - * @brief Enables/disables the SAI Rx. - * - * @param base SAI base pointer - * @param enable True means enable SAI Rx, false means disable. - */ -void SAI_RxEnable(I2S_Type *base, bool enable); - -/*! @} */ - -/*! - * @name Status - * @{ - */ - -/*! - * @brief Gets the SAI Tx status flag state. - * - * @param base SAI base pointer - * @return SAI Tx status flag value. Use the Status Mask to get the status value needed. - */ -static inline uint32_t SAI_TxGetStatusFlag(I2S_Type *base) -{ - return base->TCSR; -} - -/*! - * @brief Clears the SAI Tx status flag state. - * - * @param base SAI base pointer - * @param mask State mask. It can be a combination of the following source if defined: - * @arg kSAI_WordStartFlag - * @arg kSAI_SyncErrorFlag - * @arg kSAI_FIFOErrorFlag - */ -static inline void SAI_TxClearStatusFlags(I2S_Type *base, uint32_t mask) -{ - base->TCSR = ((base->TCSR & 0xFFE3FFFFU) | mask); -} - -/*! - * @brief Gets the SAI Tx status flag state. - * - * @param base SAI base pointer - * @return SAI Rx status flag value. Use the Status Mask to get the status value needed. - */ -static inline uint32_t SAI_RxGetStatusFlag(I2S_Type *base) -{ - return base->RCSR; -} - -/*! - * @brief Clears the SAI Rx status flag state. - * - * @param base SAI base pointer - * @param mask State mask. It can be a combination of the following sources if defined. - * @arg kSAI_WordStartFlag - * @arg kSAI_SyncErrorFlag - * @arg kSAI_FIFOErrorFlag - */ -static inline void SAI_RxClearStatusFlags(I2S_Type *base, uint32_t mask) -{ - base->RCSR = ((base->RCSR & 0xFFE3FFFFU) | mask); -} - -/*! @} */ - -/*! - * @name Interrupts - * @{ - */ - -/*! - * @brief Enables the SAI Tx interrupt requests. - * - * @param base SAI base pointer - * @param mask interrupt source - * The parameter can be a combination of the following sources if defined. - * @arg kSAI_WordStartInterruptEnable - * @arg kSAI_SyncErrorInterruptEnable - * @arg kSAI_FIFOWarningInterruptEnable - * @arg kSAI_FIFORequestInterruptEnable - * @arg kSAI_FIFOErrorInterruptEnable - */ -static inline void SAI_TxEnableInterrupts(I2S_Type *base, uint32_t mask) -{ - base->TCSR = ((base->TCSR & 0xFFE3FFFFU) | mask); -} - -/*! - * @brief Enables the SAI Rx interrupt requests. - * - * @param base SAI base pointer - * @param mask interrupt source - * The parameter can be a combination of the following sources if defined. - * @arg kSAI_WordStartInterruptEnable - * @arg kSAI_SyncErrorInterruptEnable - * @arg kSAI_FIFOWarningInterruptEnable - * @arg kSAI_FIFORequestInterruptEnable - * @arg kSAI_FIFOErrorInterruptEnable - */ -static inline void SAI_RxEnableInterrupts(I2S_Type *base, uint32_t mask) -{ - base->RCSR = ((base->RCSR & 0xFFE3FFFFU) | mask); -} - -/*! - * @brief Disables the SAI Tx interrupt requests. - * - * @param base SAI base pointer - * @param mask interrupt source - * The parameter can be a combination of the following sources if defined. - * @arg kSAI_WordStartInterruptEnable - * @arg kSAI_SyncErrorInterruptEnable - * @arg kSAI_FIFOWarningInterruptEnable - * @arg kSAI_FIFORequestInterruptEnable - * @arg kSAI_FIFOErrorInterruptEnable - */ -static inline void SAI_TxDisableInterrupts(I2S_Type *base, uint32_t mask) -{ - base->TCSR = ((base->TCSR & 0xFFE3FFFFU) & (~mask)); -} - -/*! - * @brief Disables the SAI Rx interrupt requests. - * - * @param base SAI base pointer - * @param mask interrupt source - * The parameter can be a combination of the following sources if defined. - * @arg kSAI_WordStartInterruptEnable - * @arg kSAI_SyncErrorInterruptEnable - * @arg kSAI_FIFOWarningInterruptEnable - * @arg kSAI_FIFORequestInterruptEnable - * @arg kSAI_FIFOErrorInterruptEnable - */ -static inline void SAI_RxDisableInterrupts(I2S_Type *base, uint32_t mask) -{ - base->RCSR = ((base->RCSR & 0xFFE3FFFFU) & (~mask)); -} - -/*! @} */ - -/*! - * @name DMA Control - * @{ - */ - -/*! - * @brief Enables/disables the SAI Tx DMA requests. - * @param base SAI base pointer - * @param mask DMA source - * The parameter can be combination of the following sources if defined. - * @arg kSAI_FIFOWarningDMAEnable - * @arg kSAI_FIFORequestDMAEnable - * @param enable True means enable DMA, false means disable DMA. - */ -static inline void SAI_TxEnableDMA(I2S_Type *base, uint32_t mask, bool enable) -{ - if (enable) - { - base->TCSR = ((base->TCSR & 0xFFE3FFFFU) | mask); - } - else - { - base->TCSR = ((base->TCSR & 0xFFE3FFFFU) & (~mask)); - } -} - -/*! - * @brief Enables/disables the SAI Rx DMA requests. - * @param base SAI base pointer - * @param mask DMA source - * The parameter can be a combination of the following sources if defined. - * @arg kSAI_FIFOWarningDMAEnable - * @arg kSAI_FIFORequestDMAEnable - * @param enable True means enable DMA, false means disable DMA. - */ -static inline void SAI_RxEnableDMA(I2S_Type *base, uint32_t mask, bool enable) -{ - if (enable) - { - base->RCSR = ((base->RCSR & 0xFFE3FFFFU) | mask); - } - else - { - base->RCSR = ((base->RCSR & 0xFFE3FFFFU) & (~mask)); - } -} - -/*! - * @brief Gets the SAI Tx data register address. - * - * This API is used to provide a transfer address for the SAI DMA transfer configuration. - * - * @param base SAI base pointer. - * @param channel Which data channel used. - * @return data register address. - */ -static inline uint32_t SAI_TxGetDataRegisterAddress(I2S_Type *base, uint32_t channel) -{ - return (uint32_t)(&(base->TDR)[channel]); -} - -/*! - * @brief Gets the SAI Rx data register address. - * - * This API is used to provide a transfer address for the SAI DMA transfer configuration. - * - * @param base SAI base pointer. - * @param channel Which data channel used. - * @return data register address. - */ -static inline uint32_t SAI_RxGetDataRegisterAddress(I2S_Type *base, uint32_t channel) -{ - return (uint32_t)(&(base->RDR)[channel]); -} - -/*! @} */ - -/*! - * @name Bus Operations - * @{ - */ - -/*! - * @brief Configures the SAI Tx audio format. - * - * The audio format can be changed at run-time. This function configures the sample rate and audio data - * format to be transferred. - * - * @param base SAI base pointer. - * @param format Pointer to the SAI audio data format structure. - * @param mclkSourceClockHz SAI master clock source frequency in Hz. - * @param bclkSourceClockHz SAI bit clock source frequency in Hz. If the bit clock source is a master - * clock, this value should equal the masterClockHz. -*/ -void SAI_TxSetFormat(I2S_Type *base, - sai_transfer_format_t *format, - uint32_t mclkSourceClockHz, - uint32_t bclkSourceClockHz); - -/*! - * @brief Configures the SAI Rx audio format. - * - * The audio format can be changed at run-time. This function configures the sample rate and audio data - * format to be transferred. - * - * @param base SAI base pointer. - * @param format Pointer to the SAI audio data format structure. - * @param mclkSourceClockHz SAI master clock source frequency in Hz. - * @param bclkSourceClockHz SAI bit clock source frequency in Hz. If the bit clock source is a master - * clock, this value should equal the masterClockHz. -*/ -void SAI_RxSetFormat(I2S_Type *base, - sai_transfer_format_t *format, - uint32_t mclkSourceClockHz, - uint32_t bclkSourceClockHz); - -/*! - * @brief Sends data using a blocking method. - * - * @note This function blocks by polling until data is ready to be sent. - * - * @param base SAI base pointer. - * @param channel Data channel used. - * @param bitWidth How many bits in an audio word; usually 8/16/24/32 bits. - * @param buffer Pointer to the data to be written. - * @param size Bytes to be written. - */ -void SAI_WriteBlocking(I2S_Type *base, uint32_t channel, uint32_t bitWidth, uint8_t *buffer, uint32_t size); - -/*! - * @brief Writes data into SAI FIFO. - * - * @param base SAI base pointer. - * @param channel Data channel used. - * @param data Data needs to be written. - */ -static inline void SAI_WriteData(I2S_Type *base, uint32_t channel, uint32_t data) -{ - base->TDR[channel] = data; -} - -/*! - * @brief Receives data using a blocking method. - * - * @note This function blocks by polling until data is ready to be sent. - * - * @param base SAI base pointer. - * @param channel Data channel used. - * @param bitWidth How many bits in an audio word; usually 8/16/24/32 bits. - * @param buffer Pointer to the data to be read. - * @param size Bytes to be read. - */ -void SAI_ReadBlocking(I2S_Type *base, uint32_t channel, uint32_t bitWidth, uint8_t *buffer, uint32_t size); - -/*! - * @brief Reads data from the SAI FIFO. - * - * @param base SAI base pointer. - * @param channel Data channel used. - * @return Data in SAI FIFO. - */ -static inline uint32_t SAI_ReadData(I2S_Type *base, uint32_t channel) -{ - return base->RDR[channel]; -} - -/*! @} */ - -/*! - * @name Transactional - * @{ - */ - -/*! - * @brief Initializes the SAI Tx handle. - * - * This function initializes the Tx handle for the SAI Tx transactional APIs. Call - * this function once to get the handle initialized. - * - * @param base SAI base pointer - * @param handle SAI handle pointer. - * @param callback Pointer to the user callback function. - * @param userData User parameter passed to the callback function - */ -void SAI_TransferTxCreateHandle(I2S_Type *base, sai_handle_t *handle, sai_transfer_callback_t callback, void *userData); - -/*! - * @brief Initializes the SAI Rx handle. - * - * This function initializes the Rx handle for the SAI Rx transactional APIs. Call - * this function once to get the handle initialized. - * - * @param base SAI base pointer. - * @param handle SAI handle pointer. - * @param callback Pointer to the user callback function. - * @param userData User parameter passed to the callback function. - */ -void SAI_TransferRxCreateHandle(I2S_Type *base, sai_handle_t *handle, sai_transfer_callback_t callback, void *userData); - -/*! - * @brief Configures the SAI Tx audio format. - * - * The audio format can be changed at run-time. This function configures the sample rate and audio data - * format to be transferred. - * - * @param base SAI base pointer. - * @param handle SAI handle pointer. - * @param format Pointer to the SAI audio data format structure. - * @param mclkSourceClockHz SAI master clock source frequency in Hz. - * @param bclkSourceClockHz SAI bit clock source frequency in Hz. If a bit clock source is a master - * clock, this value should equal the masterClockHz in format. - * @return Status of this function. Return value is the status_t. -*/ -status_t SAI_TransferTxSetFormat(I2S_Type *base, - sai_handle_t *handle, - sai_transfer_format_t *format, - uint32_t mclkSourceClockHz, - uint32_t bclkSourceClockHz); - -/*! - * @brief Configures the SAI Rx audio format. - * - * The audio format can be changed at run-time. This function configures the sample rate and audio data - * format to be transferred. - * - * @param base SAI base pointer. - * @param handle SAI handle pointer. - * @param format Pointer to the SAI audio data format structure. - * @param mclkSourceClockHz SAI master clock source frequency in Hz. - * @param bclkSourceClockHz SAI bit clock source frequency in Hz. If a bit clock source is a master - * clock, this value should equal the masterClockHz in format. - * @return Status of this function. Return value is one of status_t. -*/ -status_t SAI_TransferRxSetFormat(I2S_Type *base, - sai_handle_t *handle, - sai_transfer_format_t *format, - uint32_t mclkSourceClockHz, - uint32_t bclkSourceClockHz); - -/*! - * @brief Performs an interrupt non-blocking send transfer on SAI. - * - * @note This API returns immediately after the transfer initiates. - * Call the SAI_TxGetTransferStatusIRQ to poll the transfer status and check whether - * the transfer is finished. If the return status is not kStatus_SAI_Busy, the transfer - * is finished. - * - * @param base SAI base pointer. - * @param handle Pointer to the sai_handle_t structure which stores the transfer state. - * @param xfer Pointer to the sai_transfer_t structure. - * @retval kStatus_Success Successfully started the data receive. - * @retval kStatus_SAI_TxBusy Previous receive still not finished. - * @retval kStatus_InvalidArgument The input parameter is invalid. - */ -status_t SAI_TransferSendNonBlocking(I2S_Type *base, sai_handle_t *handle, sai_transfer_t *xfer); - -/*! - * @brief Performs an interrupt non-blocking receive transfer on SAI. - * - * @note This API returns immediately after the transfer initiates. - * Call the SAI_RxGetTransferStatusIRQ to poll the transfer status and check whether - * the transfer is finished. If the return status is not kStatus_SAI_Busy, the transfer - * is finished. - * - * @param base SAI base pointer - * @param handle Pointer to the sai_handle_t structure which stores the transfer state. - * @param xfer Pointer to the sai_transfer_t structure. - * @retval kStatus_Success Successfully started the data receive. - * @retval kStatus_SAI_RxBusy Previous receive still not finished. - * @retval kStatus_InvalidArgument The input parameter is invalid. - */ -status_t SAI_TransferReceiveNonBlocking(I2S_Type *base, sai_handle_t *handle, sai_transfer_t *xfer); - -/*! - * @brief Gets a set byte count. - * - * @param base SAI base pointer. - * @param handle Pointer to the sai_handle_t structure which stores the transfer state. - * @param count Bytes count sent. - * @retval kStatus_Success Succeed get the transfer count. - * @retval kStatus_NoTransferInProgress There is not a non-blocking transaction currently in progress. - */ -status_t SAI_TransferGetSendCount(I2S_Type *base, sai_handle_t *handle, size_t *count); - -/*! - * @brief Gets a received byte count. - * - * @param base SAI base pointer. - * @param handle Pointer to the sai_handle_t structure which stores the transfer state. - * @param count Bytes count received. - * @retval kStatus_Success Succeed get the transfer count. - * @retval kStatus_NoTransferInProgress There is not a non-blocking transaction currently in progress. - */ -status_t SAI_TransferGetReceiveCount(I2S_Type *base, sai_handle_t *handle, size_t *count); - -/*! - * @brief Aborts the current send. - * - * @note This API can be called any time when an interrupt non-blocking transfer initiates - * to abort the transfer early. - * - * @param base SAI base pointer. - * @param handle Pointer to the sai_handle_t structure which stores the transfer state. - */ -void SAI_TransferAbortSend(I2S_Type *base, sai_handle_t *handle); - -/*! - * @brief Aborts the the current IRQ receive. - * - * @note This API can be called when an interrupt non-blocking transfer initiates - * to abort the transfer early. - * - * @param base SAI base pointer - * @param handle Pointer to the sai_handle_t structure which stores the transfer state. - */ -void SAI_TransferAbortReceive(I2S_Type *base, sai_handle_t *handle); - -/*! - * @brief Tx interrupt handler. - * - * @param base SAI base pointer. - * @param handle Pointer to the sai_handle_t structure. - */ -void SAI_TransferTxHandleIRQ(I2S_Type *base, sai_handle_t *handle); - -/*! - * @brief Tx interrupt handler. - * - * @param base SAI base pointer. - * @param handle Pointer to the sai_handle_t structure. - */ -void SAI_TransferRxHandleIRQ(I2S_Type *base, sai_handle_t *handle); - -/*! @} */ - -#if defined(__cplusplus) -} -#endif /*_cplusplus*/ - -/*! @} */ - -#endif /* _FSL_SAI_H_ */ diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_sai_edma.c b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_sai_edma.c deleted file mode 100644 index dce5a87bfa1..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_sai_edma.c +++ /dev/null @@ -1,413 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "fsl_sai_edma.h" - -/******************************************************************************* - * Definitations - ******************************************************************************/ -/* Used for 32byte aligned */ -#define STCD_ADDR(address) (edma_tcd_t *)(((uint32_t)address + 32) & ~0x1FU) - -/*handle; - - /* If finished a blcok, call the callback function */ - memset(&saiHandle->saiQueue[saiHandle->queueDriver], 0, sizeof(sai_transfer_t)); - saiHandle->queueDriver = (saiHandle->queueDriver + 1) % SAI_XFER_QUEUE_SIZE; - if (saiHandle->callback) - { - (saiHandle->callback)(privHandle->base, saiHandle, kStatus_SAI_TxIdle, saiHandle->userData); - } - - /* If all data finished, just stop the transfer */ - if (saiHandle->saiQueue[saiHandle->queueDriver].data == NULL) - { - SAI_TransferAbortSendEDMA(privHandle->base, saiHandle); - } -} - -static void SAI_RxEDMACallback(edma_handle_t *handle, void *userData, bool done, uint32_t tcds) -{ - sai_edma_private_handle_t *privHandle = (sai_edma_private_handle_t *)userData; - sai_edma_handle_t *saiHandle = privHandle->handle; - - /* If finished a blcok, call the callback function */ - memset(&saiHandle->saiQueue[saiHandle->queueDriver], 0, sizeof(sai_transfer_t)); - saiHandle->queueDriver = (saiHandle->queueDriver + 1) % SAI_XFER_QUEUE_SIZE; - if (saiHandle->callback) - { - (saiHandle->callback)(privHandle->base, saiHandle, kStatus_SAI_RxIdle, saiHandle->userData); - } - - /* If all data finished, just stop the transfer */ - if (saiHandle->saiQueue[saiHandle->queueDriver].data == NULL) - { - SAI_TransferAbortReceiveEDMA(privHandle->base, saiHandle); - } -} - -void SAI_TransferTxCreateHandleEDMA( - I2S_Type *base, sai_edma_handle_t *handle, sai_edma_callback_t callback, void *userData, edma_handle_t *dmaHandle) -{ - assert(handle && dmaHandle); - - uint32_t instance = SAI_GetInstance(base); - - /* Zero the handle */ - memset(handle, 0, sizeof(*handle)); - - /* Set sai base to handle */ - handle->dmaHandle = dmaHandle; - handle->callback = callback; - handle->userData = userData; - - /* Set SAI state to idle */ - handle->state = kSAI_Idle; - - s_edmaPrivateHandle[instance][0].base = base; - s_edmaPrivateHandle[instance][0].handle = handle; - - /* Need to use scatter gather */ - EDMA_InstallTCDMemory(dmaHandle, STCD_ADDR(handle->tcd), SAI_XFER_QUEUE_SIZE); - - /* Install callback for Tx dma channel */ - EDMA_SetCallback(dmaHandle, SAI_TxEDMACallback, &s_edmaPrivateHandle[instance][0]); -} - -void SAI_TransferRxCreateHandleEDMA( - I2S_Type *base, sai_edma_handle_t *handle, sai_edma_callback_t callback, void *userData, edma_handle_t *dmaHandle) -{ - assert(handle && dmaHandle); - - uint32_t instance = SAI_GetInstance(base); - - /* Zero the handle */ - memset(handle, 0, sizeof(*handle)); - - /* Set sai base to handle */ - handle->dmaHandle = dmaHandle; - handle->callback = callback; - handle->userData = userData; - - /* Set SAI state to idle */ - handle->state = kSAI_Idle; - - s_edmaPrivateHandle[instance][1].base = base; - s_edmaPrivateHandle[instance][1].handle = handle; - - /* Need to use scatter gather */ - EDMA_InstallTCDMemory(dmaHandle, STCD_ADDR(handle->tcd), SAI_XFER_QUEUE_SIZE); - - /* Install callback for Tx dma channel */ - EDMA_SetCallback(dmaHandle, SAI_RxEDMACallback, &s_edmaPrivateHandle[instance][1]); -} - -void SAI_TransferTxSetFormatEDMA(I2S_Type *base, - sai_edma_handle_t *handle, - sai_transfer_format_t *format, - uint32_t mclkSourceClockHz, - uint32_t bclkSourceClockHz) -{ - assert(handle && format); - - /* Configure the audio format to SAI registers */ - SAI_TxSetFormat(base, format, mclkSourceClockHz, bclkSourceClockHz); - - /* Get the tranfer size from format, this should be used in EDMA configuration */ - if (format->bitWidth == 24U) - { - handle->bytesPerFrame = 4U; - } - else - { - handle->bytesPerFrame = format->bitWidth / 8U; - } - - /* Update the data channel SAI used */ - handle->channel = format->channel; -#if defined(FSL_FEATURE_SAI_FIFO_COUNT) && (FSL_FEATURE_SAI_FIFO_COUNT > 1) - handle->count = FSL_FEATURE_SAI_FIFO_COUNT - format->watermark; -#else - handle->count = 1U; -#endif /* FSL_FEATURE_SAI_FIFO_COUNT */ -} - -void SAI_TransferRxSetFormatEDMA(I2S_Type *base, - sai_edma_handle_t *handle, - sai_transfer_format_t *format, - uint32_t mclkSourceClockHz, - uint32_t bclkSourceClockHz) -{ - assert(handle && format); - - /* Configure the audio format to SAI registers */ - SAI_RxSetFormat(base, format, mclkSourceClockHz, bclkSourceClockHz); - - /* Get the tranfer size from format, this should be used in EDMA configuration */ - if (format->bitWidth == 24U) - { - handle->bytesPerFrame = 4U; - } - else - { - handle->bytesPerFrame = format->bitWidth / 8U; - } - - /* Update the data channel SAI used */ - handle->channel = format->channel; - -#if defined(FSL_FEATURE_SAI_FIFO_COUNT) && (FSL_FEATURE_SAI_FIFO_COUNT > 1) - handle->count = format->watermark; -#else - handle->count = 1U; -#endif /* FSL_FEATURE_SAI_FIFO_COUNT */ -} - -status_t SAI_TransferSendEDMA(I2S_Type *base, sai_edma_handle_t *handle, sai_transfer_t *xfer) -{ - assert(handle && xfer); - - edma_transfer_config_t config = {0}; - uint32_t destAddr = SAI_TxGetDataRegisterAddress(base, handle->channel); - - /* Check if input parameter invalid */ - if ((xfer->data == NULL) || (xfer->dataSize == 0U)) - { - return kStatus_InvalidArgument; - } - - if (handle->saiQueue[handle->queueUser].data) - { - return kStatus_SAI_QueueFull; - } - - /* Change the state of handle */ - handle->state = kSAI_Busy; - - /* Update the queue state */ - handle->transferSize[handle->queueUser] = xfer->dataSize; - handle->saiQueue[handle->queueUser].data = xfer->data; - handle->saiQueue[handle->queueUser].dataSize = xfer->dataSize; - handle->queueUser = (handle->queueUser + 1) % SAI_XFER_QUEUE_SIZE; - - /* Prepare edma configure */ - EDMA_PrepareTransfer(&config, xfer->data, handle->bytesPerFrame, (void *)destAddr, handle->bytesPerFrame, - handle->count * handle->bytesPerFrame, xfer->dataSize, kEDMA_MemoryToPeripheral); - - /* Store the initially configured eDMA minor byte transfer count into the SAI handle */ - handle->nbytes = handle->count * handle->bytesPerFrame; - - EDMA_SubmitTransfer(handle->dmaHandle, &config); - - /* Start DMA transfer */ - EDMA_StartTransfer(handle->dmaHandle); - - /* Enable DMA enable bit */ - SAI_TxEnableDMA(base, kSAI_FIFORequestDMAEnable, true); - - /* Enable SAI Tx clock */ - SAI_TxEnable(base, true); - - return kStatus_Success; -} - -status_t SAI_TransferReceiveEDMA(I2S_Type *base, sai_edma_handle_t *handle, sai_transfer_t *xfer) -{ - assert(handle && xfer); - - edma_transfer_config_t config = {0}; - uint32_t srcAddr = SAI_RxGetDataRegisterAddress(base, handle->channel); - - /* Check if input parameter invalid */ - if ((xfer->data == NULL) || (xfer->dataSize == 0U)) - { - return kStatus_InvalidArgument; - } - - if (handle->saiQueue[handle->queueUser].data) - { - return kStatus_SAI_QueueFull; - } - - /* Change the state of handle */ - handle->state = kSAI_Busy; - - /* Update queue state */ - handle->transferSize[handle->queueUser] = xfer->dataSize; - handle->saiQueue[handle->queueUser].data = xfer->data; - handle->saiQueue[handle->queueUser].dataSize = xfer->dataSize; - handle->queueUser = (handle->queueUser + 1) % SAI_XFER_QUEUE_SIZE; - - /* Prepare edma configure */ - EDMA_PrepareTransfer(&config, (void *)srcAddr, handle->bytesPerFrame, xfer->data, handle->bytesPerFrame, - handle->count * handle->bytesPerFrame, xfer->dataSize, kEDMA_PeripheralToMemory); - - /* Store the initially configured eDMA minor byte transfer count into the SAI handle */ - handle->nbytes = handle->count * handle->bytesPerFrame; - - EDMA_SubmitTransfer(handle->dmaHandle, &config); - - /* Start DMA transfer */ - EDMA_StartTransfer(handle->dmaHandle); - - /* Enable DMA enable bit */ - SAI_RxEnableDMA(base, kSAI_FIFORequestDMAEnable, true); - - /* Enable SAI Rx clock */ - SAI_RxEnable(base, true); - - return kStatus_Success; -} - -void SAI_TransferAbortSendEDMA(I2S_Type *base, sai_edma_handle_t *handle) -{ - assert(handle); - - /* Disable dma */ - EDMA_AbortTransfer(handle->dmaHandle); - - /* Disable DMA enable bit */ - SAI_TxEnableDMA(base, kSAI_FIFORequestDMAEnable, false); - - /* Disable Tx */ - SAI_TxEnable(base, false); - - /* Set the handle state */ - handle->state = kSAI_Idle; -} - -void SAI_TransferAbortReceiveEDMA(I2S_Type *base, sai_edma_handle_t *handle) -{ - assert(handle); - - /* Disable dma */ - EDMA_AbortTransfer(handle->dmaHandle); - - /* Disable DMA enable bit */ - SAI_RxEnableDMA(base, kSAI_FIFORequestDMAEnable, false); - - /* Disable Rx */ - SAI_RxEnable(base, false); - - /* Set the handle state */ - handle->state = kSAI_Idle; -} - -status_t SAI_TransferGetSendCountEDMA(I2S_Type *base, sai_edma_handle_t *handle, size_t *count) -{ - assert(handle); - - status_t status = kStatus_Success; - - if (handle->state != kSAI_Busy) - { - status = kStatus_NoTransferInProgress; - } - else - { - *count = (handle->transferSize[handle->queueDriver] - - (uint32_t)handle->nbytes * - EDMA_GetRemainingMajorLoopCount(handle->dmaHandle->base, handle->dmaHandle->channel)); - } - - return status; -} - -status_t SAI_TransferGetReceiveCountEDMA(I2S_Type *base, sai_edma_handle_t *handle, size_t *count) -{ - assert(handle); - - status_t status = kStatus_Success; - - if (handle->state != kSAI_Busy) - { - status = kStatus_NoTransferInProgress; - } - else - { - *count = (handle->transferSize[handle->queueDriver] - - (uint32_t)handle->nbytes * - EDMA_GetRemainingMajorLoopCount(handle->dmaHandle->base, handle->dmaHandle->channel)); - } - - return status; -} diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_sai_edma.h b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_sai_edma.h deleted file mode 100644 index 9ae05db0e95..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_sai_edma.h +++ /dev/null @@ -1,231 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -#ifndef _FSL_SAI_EDMA_H_ -#define _FSL_SAI_EDMA_H_ - -#include "fsl_sai.h" -#include "fsl_edma.h" - -/*! - * @addtogroup sai_edma - * @{ - */ - -/******************************************************************************* - * Definitions - ******************************************************************************/ - -typedef struct _sai_edma_handle sai_edma_handle_t; - -/*! @brief SAI eDMA transfer callback function for finish and error */ -typedef void (*sai_edma_callback_t)(I2S_Type *base, sai_edma_handle_t *handle, status_t status, void *userData); - -/*! @brief SAI DMA transfer handle, users should not touch the content of the handle.*/ -struct _sai_edma_handle -{ - edma_handle_t *dmaHandle; /*!< DMA handler for SAI send */ - uint8_t nbytes; /*!< eDMA minor byte transfer count initially configured. */ - uint8_t bytesPerFrame; /*!< Bytes in a frame */ - uint8_t channel; /*!< Which data channel */ - uint8_t count; /*!< The transfer data count in a DMA request */ - uint32_t state; /*!< Internal state for SAI eDMA transfer */ - sai_edma_callback_t callback; /*!< Callback for users while transfer finish or error occurs */ - void *userData; /*!< User callback parameter */ - edma_tcd_t tcd[SAI_XFER_QUEUE_SIZE + 1U]; /*!< TCD pool for eDMA transfer. */ - sai_transfer_t saiQueue[SAI_XFER_QUEUE_SIZE]; /*!< Transfer queue storing queued transfer. */ - size_t transferSize[SAI_XFER_QUEUE_SIZE]; /*!< Data bytes need to transfer */ - volatile uint8_t queueUser; /*!< Index for user to queue transfer. */ - volatile uint8_t queueDriver; /*!< Index for driver to get the transfer data and size */ -}; - -/******************************************************************************* - * APIs - ******************************************************************************/ -#if defined(__cplusplus) -extern "C" { -#endif - -/*! - * @name eDMA Transactional - * @{ - */ - -/*! - * @brief Initializes the SAI eDMA handle. - * - * This function initializes the SAI master DMA handle, which can be used for other SAI master transactional APIs. - * Usually, for a specified SAI instance, call this API once to get the initialized handle. - * - * @param base SAI base pointer. - * @param handle SAI eDMA handle pointer. - * @param base SAI peripheral base address. - * @param callback Pointer to user callback function. - * @param userData User parameter passed to the callback function. - * @param dmaHandle eDMA handle pointer, this handle shall be static allocated by users. - */ -void SAI_TransferTxCreateHandleEDMA( - I2S_Type *base, sai_edma_handle_t *handle, sai_edma_callback_t callback, void *userData, edma_handle_t *dmaHandle); - -/*! - * @brief Initializes the SAI Rx eDMA handle. - * - * This function initializes the SAI slave DMA handle, which can be used for other SAI master transactional APIs. - * Usually, for a specified SAI instance, call this API once to get the initialized handle. - * - * @param base SAI base pointer. - * @param handle SAI eDMA handle pointer. - * @param base SAI peripheral base address. - * @param callback Pointer to user callback function. - * @param userData User parameter passed to the callback function. - * @param dmaHandle eDMA handle pointer, this handle shall be static allocated by users. - */ -void SAI_TransferRxCreateHandleEDMA( - I2S_Type *base, sai_edma_handle_t *handle, sai_edma_callback_t callback, void *userData, edma_handle_t *dmaHandle); - -/*! - * @brief Configures the SAI Tx audio format. - * - * The audio format can be changed at run-time. This function configures the sample rate and audio data - * format to be transferred. This function also sets the eDMA parameter according to formatting requirements. - * - * @param base SAI base pointer. - * @param handle SAI eDMA handle pointer. - * @param format Pointer to SAI audio data format structure. - * @param mclkSourceClockHz SAI master clock source frequency in Hz. - * @param bclkSourceClockHz SAI bit clock source frequency in Hz. If bit clock source is master - * clock, this value should equals to masterClockHz in format. - * @retval kStatus_Success Audio format set successfully. - * @retval kStatus_InvalidArgument The input argument is invalid. -*/ -void SAI_TransferTxSetFormatEDMA(I2S_Type *base, - sai_edma_handle_t *handle, - sai_transfer_format_t *format, - uint32_t mclkSourceClockHz, - uint32_t bclkSourceClockHz); - -/*! - * @brief Configures the SAI Rx audio format. - * - * The audio format can be changed at run-time. This function configures the sample rate and audio data - * format to be transferred. This function also sets the eDMA parameter according to formatting requirements. - * - * @param base SAI base pointer. - * @param handle SAI eDMA handle pointer. - * @param format Pointer to SAI audio data format structure. - * @param mclkSourceClockHz SAI master clock source frequency in Hz. - * @param bclkSourceClockHz SAI bit clock source frequency in Hz. If a bit clock source is the master - * clock, this value should equal to masterClockHz in format. - * @retval kStatus_Success Audio format set successfully. - * @retval kStatus_InvalidArgument The input argument is invalid. -*/ -void SAI_TransferRxSetFormatEDMA(I2S_Type *base, - sai_edma_handle_t *handle, - sai_transfer_format_t *format, - uint32_t mclkSourceClockHz, - uint32_t bclkSourceClockHz); - -/*! - * @brief Performs a non-blocking SAI transfer using DMA. - * - * @note This interface returns immediately after the transfer initiates. Call - * SAI_GetTransferStatus to poll the transfer status and check whether the SAI transfer is finished. - * - * @param base SAI base pointer. - * @param handle SAI eDMA handle pointer. - * @param xfer Pointer to the DMA transfer structure. - * @retval kStatus_Success Start a SAI eDMA send successfully. - * @retval kStatus_InvalidArgument The input argument is invalid. - * @retval kStatus_TxBusy SAI is busy sending data. - */ -status_t SAI_TransferSendEDMA(I2S_Type *base, sai_edma_handle_t *handle, sai_transfer_t *xfer); - -/*! - * @brief Performs a non-blocking SAI receive using eDMA. - * - * @note This interface returns immediately after the transfer initiates. Call - * the SAI_GetReceiveRemainingBytes to poll the transfer status and check whether the SAI transfer is finished. - * - * @param base SAI base pointer - * @param handle SAI eDMA handle pointer. - * @param xfer Pointer to DMA transfer structure. - * @retval kStatus_Success Start a SAI eDMA receive successfully. - * @retval kStatus_InvalidArgument The input argument is invalid. - * @retval kStatus_RxBusy SAI is busy receiving data. - */ -status_t SAI_TransferReceiveEDMA(I2S_Type *base, sai_edma_handle_t *handle, sai_transfer_t *xfer); - -/*! - * @brief Aborts a SAI transfer using eDMA. - * - * @param base SAI base pointer. - * @param handle SAI eDMA handle pointer. - */ -void SAI_TransferAbortSendEDMA(I2S_Type *base, sai_edma_handle_t *handle); - -/*! - * @brief Aborts a SAI receive using eDMA. - * - * @param base SAI base pointer - * @param handle SAI eDMA handle pointer. - */ -void SAI_TransferAbortReceiveEDMA(I2S_Type *base, sai_edma_handle_t *handle); - -/*! - * @brief Gets byte count sent by SAI. - * - * @param base SAI base pointer. - * @param handle SAI eDMA handle pointer. - * @param count Bytes count sent by SAI. - * @retval kStatus_Success Succeed get the transfer count. - * @retval kStatus_NoTransferInProgress There is no non-blocking transaction in progress. - */ -status_t SAI_TransferGetSendCountEDMA(I2S_Type *base, sai_edma_handle_t *handle, size_t *count); - -/*! - * @brief Gets byte count received by SAI. - * - * @param base SAI base pointer - * @param handle SAI eDMA handle pointer. - * @param count Bytes count received by SAI. - * @retval kStatus_Success Succeed get the transfer count. - * @retval kStatus_NoTransferInProgress There is no non-blocking transaction in progress. - */ -status_t SAI_TransferGetReceiveCountEDMA(I2S_Type *base, sai_edma_handle_t *handle, size_t *count); - -/*! @} */ - -#if defined(__cplusplus) -} -#endif - -/*! - * @} - */ -#endif diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_sdhc.c b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_sdhc.c deleted file mode 100644 index 3151cd22ed9..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_sdhc.c +++ /dev/null @@ -1,1416 +0,0 @@ -/* - * Copyright (c) 2016, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "fsl_sdhc.h" - -/******************************************************************************* - * Definitions - ******************************************************************************/ -/*! @brief Clock setting */ -/* Max SD clock divisor from base clock */ -#define SDHC_MAX_DVS ((SDHC_SYSCTL_DVS_MASK >> SDHC_SYSCTL_DVS_SHIFT) + 1U) -#define SDHC_PREV_DVS(x) ((x) -= 1U) -#define SDHC_MAX_CLKFS ((SDHC_SYSCTL_SDCLKFS_MASK >> SDHC_SYSCTL_SDCLKFS_SHIFT) + 1U) -#define SDHC_PREV_CLKFS(x) ((x) >>= 1U) - -/* Typedef for interrupt handler. */ -typedef void (*sdhc_isr_t)(SDHC_Type *base, sdhc_handle_t *handle); - -/*! @brief ADMA table configuration */ -typedef struct _sdhc_adma_table_config -{ - uint32_t *admaTable; /*!< ADMA table address, can't be null if transfer way is ADMA1/ADMA2 */ - uint32_t admaTableWords; /*!< ADMA table length united as words, can't be 0 if transfer way is ADMA1/ADMA2 */ -} sdhc_adma_table_config_t; - -/******************************************************************************* - * Prototypes - ******************************************************************************/ -/*! - * @brief Get the instance. - * - * @param base SDHC peripheral base address. - * @return Instance number. - */ -static uint32_t SDHC_GetInstance(SDHC_Type *base); - -/*! - * @brief Set transfer interrupt. - * - * @param base SDHC peripheral base address. - * @param usingInterruptSignal True to use IRQ signal. - */ -static void SDHC_SetTransferInterrupt(SDHC_Type *base, bool usingInterruptSignal); - -/*! - * @brief Start transfer according to current transfer state - * - * @param base SDHC peripheral base address. - * @param command Command to be sent. - * @param data Data to be transferred. - * @param DMA mode selection - */ -static void SDHC_StartTransfer(SDHC_Type *base, sdhc_command_t *command, sdhc_data_t *data, sdhc_dma_mode_t dmaMode); - -/*! - * @brief Receive command response - * - * @param base SDHC peripheral base address. - * @param command Command to be sent. - */ -static status_t SDHC_ReceiveCommandResponse(SDHC_Type *base, sdhc_command_t *command); - -/*! - * @brief Read DATAPORT when buffer enable bit is set. - * - * @param base SDHC peripheral base address. - * @param data Data to be read. - * @param transferredWords The number of data words have been transferred last time transaction. - * @return The number of total data words have been transferred after this time transaction. - */ -static uint32_t SDHC_ReadDataPort(SDHC_Type *base, sdhc_data_t *data, uint32_t transferredWords); - -/*! - * @brief Read data by using DATAPORT polling way. - * - * @param base SDHC peripheral base address. - * @param data Data to be read. - * @retval kStatus_Fail Read DATAPORT failed. - * @retval kStatus_Success Operate successfully. - */ -static status_t SDHC_ReadByDataPortBlocking(SDHC_Type *base, sdhc_data_t *data); - -/*! - * @brief Write DATAPORT when buffer enable bit is set. - * - * @param base SDHC peripheral base address. - * @param data Data to be read. - * @param transferredWords The number of data words have been transferred last time. - * @return The number of total data words have been transferred after this time transaction. - */ -static uint32_t SDHC_WriteDataPort(SDHC_Type *base, sdhc_data_t *data, uint32_t transferredWords); - -/*! - * @brief Write data by using DATAPORT polling way. - * - * @param base SDHC peripheral base address. - * @param data Data to be transferred. - * @retval kStatus_Fail Write DATAPORT failed. - * @retval kStatus_Success Operate successfully. - */ -static status_t SDHC_WriteByDataPortBlocking(SDHC_Type *base, sdhc_data_t *data); - -/*! - * @brief Send command by using polling way. - * - * @param base SDHC peripheral base address. - * @param command Command to be sent. - * @retval kStatus_Fail Send command failed. - * @retval kStatus_Success Operate successfully. - */ -static status_t SDHC_SendCommandBlocking(SDHC_Type *base, sdhc_command_t *command); - -/*! - * @brief Transfer data by DATAPORT and polling way. - * - * @param base SDHC peripheral base address. - * @param data Data to be transferred. - * @retval kStatus_Fail Transfer data failed. - * @retval kStatus_Success Operate successfully. - */ -static status_t SDHC_TransferByDataPortBlocking(SDHC_Type *base, sdhc_data_t *data); - -/*! - * @brief Transfer data by ADMA2 and polling way. - * - * @param base SDHC peripheral base address. - * @param data Data to be transferred. - * @retval kStatus_Fail Transfer data failed. - * @retval kStatus_Success Operate successfully. - */ -static status_t SDHC_TransferByAdma2Blocking(SDHC_Type *base, sdhc_data_t *data); - -/*! - * @brief Transfer data by polling way. - * - * @param dmaMode DMA mode. - * @param base SDHC peripheral base address. - * @param data Data to be transferred. - * @retval kStatus_Fail Transfer data failed. - * @retval kStatus_InvalidArgument Argument is invalid. - * @retval kStatus_Success Operate successfully. - */ -static status_t SDHC_TransferDataBlocking(sdhc_dma_mode_t dmaMode, SDHC_Type *base, sdhc_data_t *data); - -/*! - * @brief Handle card detect interrupt. - * - * @param handle SDHC handle. - * @param interruptFlags Card detect related interrupt flags. - */ -static void SDHC_TransferHandleCardDetect(sdhc_handle_t *handle, uint32_t interruptFlags); - -/*! - * @brief Handle command interrupt. - * - * @param base SDHC peripheral base address. - * @param handle SDHC handle. - * @param interruptFlags Command related interrupt flags. - */ -static void SDHC_TransferHandleCommand(SDHC_Type *base, sdhc_handle_t *handle, uint32_t interruptFlags); - -/*! - * @brief Handle data interrupt. - * - * @param base SDHC peripheral base address. - * @param handle SDHC handle. - * @param interruptFlags Data related interrupt flags. - */ -static void SDHC_TransferHandleData(SDHC_Type *base, sdhc_handle_t *handle, uint32_t interruptFlags); - -/*! - * @brief Handle SDIO card interrupt signal. - * - * @param handle SDHC handle. - */ -static void SDHC_TransferHandleSdioInterrupt(sdhc_handle_t *handle); - -/*! - * @brief Handle SDIO block gap event. - * - * @param handle SDHC handle. - */ -static void SDHC_TransferHandleSdioBlockGap(sdhc_handle_t *handle); - -/******************************************************************************* - * Variables - ******************************************************************************/ -/*! @brief SDHC internal handle pointer array */ -static sdhc_handle_t *s_sdhcHandle[FSL_FEATURE_SOC_SDHC_COUNT]; - -/*! @brief SDHC base pointer array */ -static SDHC_Type *const s_sdhcBase[] = SDHC_BASE_PTRS; - -/*! @brief SDHC IRQ name array */ -static const IRQn_Type s_sdhcIRQ[] = SDHC_IRQS; - -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) -/*! @brief SDHC clock array name */ -static const clock_ip_name_t s_sdhcClock[] = SDHC_CLOCKS; -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ - -/* SDHC ISR for transactional APIs. */ -static sdhc_isr_t s_sdhcIsr; - -/******************************************************************************* - * Code - ******************************************************************************/ -static uint32_t SDHC_GetInstance(SDHC_Type *base) -{ - uint8_t instance = 0; - - while ((instance < ARRAY_SIZE(s_sdhcBase)) && (s_sdhcBase[instance] != base)) - { - instance++; - } - - assert(instance < ARRAY_SIZE(s_sdhcBase)); - - return instance; -} - -static void SDHC_SetTransferInterrupt(SDHC_Type *base, bool usingInterruptSignal) -{ - uint32_t interruptEnabled; /* The Interrupt status flags to be enabled */ - bool cardDetectDat3 = (bool)(base->PROCTL & SDHC_PROCTL_D3CD_MASK); - - /* Disable all interrupts */ - SDHC_DisableInterruptStatus(base, (uint32_t)kSDHC_AllInterruptFlags); - SDHC_DisableInterruptSignal(base, (uint32_t)kSDHC_AllInterruptFlags); - DisableIRQ(s_sdhcIRQ[SDHC_GetInstance(base)]); - - interruptEnabled = - (kSDHC_CommandIndexErrorFlag | kSDHC_CommandCrcErrorFlag | kSDHC_CommandEndBitErrorFlag | - kSDHC_CommandTimeoutFlag | kSDHC_CommandCompleteFlag | kSDHC_DataTimeoutFlag | kSDHC_DataCrcErrorFlag | - kSDHC_DataEndBitErrorFlag | kSDHC_DataCompleteFlag | kSDHC_AutoCommand12ErrorFlag | kSDHC_BufferReadReadyFlag | - kSDHC_BufferWriteReadyFlag | kSDHC_DmaErrorFlag | kSDHC_DmaCompleteFlag); - if (cardDetectDat3) - { - interruptEnabled |= (kSDHC_CardInsertionFlag | kSDHC_CardRemovalFlag); - } - - SDHC_EnableInterruptStatus(base, interruptEnabled); - if (usingInterruptSignal) - { - SDHC_EnableInterruptSignal(base, interruptEnabled); - } -} - -static void SDHC_StartTransfer(SDHC_Type *base, sdhc_command_t *command, sdhc_data_t *data, sdhc_dma_mode_t dmaMode) -{ - uint32_t flags = 0U; - sdhc_transfer_config_t sdhcTransferConfig = {0}; - - /* Define the flag corresponding to each response type. */ - switch (command->responseType) - { - case kCARD_ResponseTypeNone: - break; - case kCARD_ResponseTypeR1: /* Response 1 */ - flags |= (kSDHC_ResponseLength48Flag | kSDHC_EnableCrcCheckFlag | kSDHC_EnableIndexCheckFlag); - break; - case kCARD_ResponseTypeR1b: /* Response 1 with busy */ - flags |= (kSDHC_ResponseLength48BusyFlag | kSDHC_EnableCrcCheckFlag | kSDHC_EnableIndexCheckFlag); - break; - case kCARD_ResponseTypeR2: /* Response 2 */ - flags |= (kSDHC_ResponseLength136Flag | kSDHC_EnableCrcCheckFlag); - break; - case kCARD_ResponseTypeR3: /* Response 3 */ - flags |= (kSDHC_ResponseLength48Flag); - break; - case kCARD_ResponseTypeR4: /* Response 4 */ - flags |= (kSDHC_ResponseLength48Flag); - break; - case kCARD_ResponseTypeR5: /* Response 5 */ - flags |= (kSDHC_ResponseLength48Flag | kSDHC_EnableCrcCheckFlag | kSDHC_EnableIndexCheckFlag); - break; - case kCARD_ResponseTypeR5b: /* Response 5 with busy */ - flags |= (kSDHC_ResponseLength48BusyFlag | kSDHC_EnableCrcCheckFlag | kSDHC_EnableIndexCheckFlag); - break; - case kCARD_ResponseTypeR6: /* Response 6 */ - flags |= (kSDHC_ResponseLength48Flag | kSDHC_EnableCrcCheckFlag | kSDHC_EnableIndexCheckFlag); - break; - case kCARD_ResponseTypeR7: /* Response 7 */ - flags |= (kSDHC_ResponseLength48Flag | kSDHC_EnableCrcCheckFlag | kSDHC_EnableIndexCheckFlag); - break; - default: - break; - } - if (command->type == kCARD_CommandTypeAbort) - { - flags |= kSDHC_CommandTypeAbortFlag; - } - - if (data) - { - flags |= kSDHC_DataPresentFlag; - - if (dmaMode != kSDHC_DmaModeNo) - { - flags |= kSDHC_EnableDmaFlag; - } - if (data->rxData) - { - flags |= kSDHC_DataReadFlag; - } - if (data->blockCount > 1U) - { - flags |= (kSDHC_MultipleBlockFlag | kSDHC_EnableBlockCountFlag); - if (data->enableAutoCommand12) - { - /* Enable Auto command 12. */ - flags |= kSDHC_EnableAutoCommand12Flag; - } - } - - sdhcTransferConfig.dataBlockSize = data->blockSize; - sdhcTransferConfig.dataBlockCount = data->blockCount; - } - else - { - sdhcTransferConfig.dataBlockSize = 0U; - sdhcTransferConfig.dataBlockCount = 0U; - } - - sdhcTransferConfig.commandArgument = command->argument; - sdhcTransferConfig.commandIndex = command->index; - sdhcTransferConfig.flags = flags; - SDHC_SetTransferConfig(base, &sdhcTransferConfig); -} - -static status_t SDHC_ReceiveCommandResponse(SDHC_Type *base, sdhc_command_t *command) -{ - uint32_t i; - - if (command->responseType != kCARD_ResponseTypeNone) - { - command->response[0U] = SDHC_GetCommandResponse(base, 0U); - if (command->responseType == kCARD_ResponseTypeR2) - { - command->response[1U] = SDHC_GetCommandResponse(base, 1U); - command->response[2U] = SDHC_GetCommandResponse(base, 2U); - command->response[3U] = SDHC_GetCommandResponse(base, 3U); - - i = 4U; - /* R3-R2-R1-R0(lowest 8 bit is invalid bit) has the same format as R2 format in SD specification document - after removed internal CRC7 and end bit. */ - do - { - command->response[i - 1U] <<= 8U; - if (i > 1U) - { - command->response[i - 1U] |= ((command->response[i - 2U] & 0xFF000000U) >> 24U); - } - } while (i--); - } - } - /* check response error flag */ - if ((command->responseErrorFlags != 0U) && - ((command->responseType == kCARD_ResponseTypeR1) || (command->responseType == kCARD_ResponseTypeR1b) || - (command->responseType == kCARD_ResponseTypeR6) || (command->responseType == kCARD_ResponseTypeR5))) - { - if (((command->responseErrorFlags) & (command->response[0U])) != 0U) - { - return kStatus_SDHC_SendCommandFailed; - } - } - - return kStatus_Success; -} - -static uint32_t SDHC_ReadDataPort(SDHC_Type *base, sdhc_data_t *data, uint32_t transferredWords) -{ - uint32_t i; - uint32_t totalWords; - uint32_t wordsCanBeRead; /* The words can be read at this time. */ - uint32_t readWatermark = ((base->WML & SDHC_WML_RDWML_MASK) >> SDHC_WML_RDWML_SHIFT); - - /* - * Add non aligned access support ,user need make sure your buffer size is big - * enough to hold the data,in other words,user need make sure the buffer size - * is 4 byte aligned - */ - if (data->blockSize % sizeof(uint32_t) != 0U) - { - data->blockSize += - sizeof(uint32_t) - (data->blockSize % sizeof(uint32_t)); /* make the block size as word-aligned */ - } - - totalWords = ((data->blockCount * data->blockSize) / sizeof(uint32_t)); - - /* If watermark level is equal or bigger than totalWords, transfers totalWords data. */ - if (readWatermark >= totalWords) - { - wordsCanBeRead = totalWords; - } - /* If watermark level is less than totalWords and left words to be sent is equal or bigger than readWatermark, - transfers watermark level words. */ - else if ((readWatermark < totalWords) && ((totalWords - transferredWords) >= readWatermark)) - { - wordsCanBeRead = readWatermark; - } - /* If watermark level is less than totalWords and left words to be sent is less than readWatermark, transfers left - words. */ - else - { - wordsCanBeRead = (totalWords - transferredWords); - } - - i = 0U; - while (i < wordsCanBeRead) - { - data->rxData[transferredWords++] = SDHC_ReadData(base); - i++; - } - - return transferredWords; -} - -static status_t SDHC_ReadByDataPortBlocking(SDHC_Type *base, sdhc_data_t *data) -{ - uint32_t totalWords; - uint32_t transferredWords = 0U; - status_t error = kStatus_Success; - - /* - * Add non aligned access support ,user need make sure your buffer size is big - * enough to hold the data,in other words,user need make sure the buffer size - * is 4 byte aligned - */ - if (data->blockSize % sizeof(uint32_t) != 0U) - { - data->blockSize += - sizeof(uint32_t) - (data->blockSize % sizeof(uint32_t)); /* make the block size as word-aligned */ - } - - totalWords = ((data->blockCount * data->blockSize) / sizeof(uint32_t)); - - while ((error == kStatus_Success) && (transferredWords < totalWords)) - { - while (!(SDHC_GetInterruptStatusFlags(base) & (kSDHC_BufferReadReadyFlag | kSDHC_DataErrorFlag))) - { - } - - if (SDHC_GetInterruptStatusFlags(base) & kSDHC_DataErrorFlag) - { - if (!(data->enableIgnoreError)) - { - error = kStatus_Fail; - } - } - if (error == kStatus_Success) - { - transferredWords = SDHC_ReadDataPort(base, data, transferredWords); - } - /* clear buffer ready and error */ - SDHC_ClearInterruptStatusFlags(base, kSDHC_BufferReadReadyFlag | kSDHC_DataErrorFlag); - } - - /* Clear data complete flag after the last read operation. */ - SDHC_ClearInterruptStatusFlags(base, kSDHC_DataCompleteFlag | kSDHC_DataErrorFlag); - - return error; -} - -static uint32_t SDHC_WriteDataPort(SDHC_Type *base, sdhc_data_t *data, uint32_t transferredWords) -{ - uint32_t i; - uint32_t totalWords; - uint32_t wordsCanBeWrote; /* Words can be wrote at this time. */ - uint32_t writeWatermark = ((base->WML & SDHC_WML_WRWML_MASK) >> SDHC_WML_WRWML_SHIFT); - - /* - * Add non aligned access support ,user need make sure your buffer size is big - * enough to hold the data,in other words,user need make sure the buffer size - * is 4 byte aligned - */ - if (data->blockSize % sizeof(uint32_t) != 0U) - { - data->blockSize += - sizeof(uint32_t) - (data->blockSize % sizeof(uint32_t)); /* make the block size as word-aligned */ - } - - totalWords = ((data->blockCount * data->blockSize) / sizeof(uint32_t)); - - /* If watermark level is equal or bigger than totalWords, transfers totalWords data.*/ - if (writeWatermark >= totalWords) - { - wordsCanBeWrote = totalWords; - } - /* If watermark level is less than totalWords and left words to be sent is equal or bigger than watermark, - transfers watermark level words. */ - else if ((writeWatermark < totalWords) && ((totalWords - transferredWords) >= writeWatermark)) - { - wordsCanBeWrote = writeWatermark; - } - /* If watermark level is less than totalWords and left words to be sent is less than watermark, transfers left - words. */ - else - { - wordsCanBeWrote = (totalWords - transferredWords); - } - - i = 0U; - while (i < wordsCanBeWrote) - { - SDHC_WriteData(base, data->txData[transferredWords++]); - i++; - } - - return transferredWords; -} - -static status_t SDHC_WriteByDataPortBlocking(SDHC_Type *base, sdhc_data_t *data) -{ - uint32_t totalWords; - uint32_t transferredWords = 0U; - status_t error = kStatus_Success; - - /* - * Add non aligned access support ,user need make sure your buffer size is big - * enough to hold the data,in other words,user need make sure the buffer size - * is 4 byte aligned - */ - if (data->blockSize % sizeof(uint32_t) != 0U) - { - data->blockSize += - sizeof(uint32_t) - (data->blockSize % sizeof(uint32_t)); /* make the block size as word-aligned */ - } - - totalWords = (data->blockCount * data->blockSize) / sizeof(uint32_t); - - while ((error == kStatus_Success) && (transferredWords < totalWords)) - { - while (!(SDHC_GetInterruptStatusFlags(base) & (kSDHC_BufferWriteReadyFlag | kSDHC_DataErrorFlag))) - { - } - - if (SDHC_GetInterruptStatusFlags(base) & kSDHC_DataErrorFlag) - { - if (!(data->enableIgnoreError)) - { - error = kStatus_Fail; - } - } - if (error == kStatus_Success) - { - transferredWords = SDHC_WriteDataPort(base, data, transferredWords); - } - - /* Clear buffer enable flag to trigger transfer. Clear error flag when SDHC encounter error. */ - SDHC_ClearInterruptStatusFlags(base, (kSDHC_BufferWriteReadyFlag | kSDHC_DataErrorFlag)); - } - - /* Wait write data complete or data transfer error after the last writing operation. */ - while (!(SDHC_GetInterruptStatusFlags(base) & (kSDHC_DataCompleteFlag | kSDHC_DataErrorFlag))) - { - } - if (SDHC_GetInterruptStatusFlags(base) & kSDHC_DataErrorFlag) - { - if (!(data->enableIgnoreError)) - { - error = kStatus_Fail; - } - } - - SDHC_ClearInterruptStatusFlags(base, (kSDHC_DataCompleteFlag | kSDHC_DataErrorFlag)); - - return error; -} - -static status_t SDHC_SendCommandBlocking(SDHC_Type *base, sdhc_command_t *command) -{ - status_t error = kStatus_Success; - - /* Wait command complete or SDHC encounters error. */ - while (!(SDHC_GetInterruptStatusFlags(base) & (kSDHC_CommandCompleteFlag | kSDHC_CommandErrorFlag))) - { - } - - if (SDHC_GetInterruptStatusFlags(base) & kSDHC_CommandErrorFlag) - { - error = kStatus_Fail; - } - /* Receive response when command completes successfully. */ - if (error == kStatus_Success) - { - error = SDHC_ReceiveCommandResponse(base, command); - } - - SDHC_ClearInterruptStatusFlags(base, (kSDHC_CommandCompleteFlag | kSDHC_CommandErrorFlag)); - - return error; -} - -static status_t SDHC_TransferByDataPortBlocking(SDHC_Type *base, sdhc_data_t *data) -{ - status_t error = kStatus_Success; - - if (data->rxData) - { - error = SDHC_ReadByDataPortBlocking(base, data); - } - else - { - error = SDHC_WriteByDataPortBlocking(base, data); - } - - return error; -} - -static status_t SDHC_TransferByAdma2Blocking(SDHC_Type *base, sdhc_data_t *data) -{ - status_t error = kStatus_Success; - - /* Wait data complete or SDHC encounters error. */ - while (!(SDHC_GetInterruptStatusFlags(base) & (kSDHC_DataCompleteFlag | kSDHC_DataErrorFlag | kSDHC_DmaErrorFlag))) - { - } - if (SDHC_GetInterruptStatusFlags(base) & (kSDHC_DataErrorFlag | kSDHC_DmaErrorFlag)) - { - if (!(data->enableIgnoreError)) - { - error = kStatus_Fail; - } - } - SDHC_ClearInterruptStatusFlags( - base, (kSDHC_DataCompleteFlag | kSDHC_DmaCompleteFlag | kSDHC_DataErrorFlag | kSDHC_DmaErrorFlag)); - return error; -} - -#if defined FSL_SDHC_ENABLE_ADMA1 -#define SDHC_TransferByAdma1Blocking(base, data) SDHC_TransferByAdma2Blocking(base, data) -#endif /* FSL_SDHC_ENABLE_ADMA1 */ - -static status_t SDHC_TransferDataBlocking(sdhc_dma_mode_t dmaMode, SDHC_Type *base, sdhc_data_t *data) -{ - status_t error = kStatus_Success; - - switch (dmaMode) - { - case kSDHC_DmaModeNo: - error = SDHC_TransferByDataPortBlocking(base, data); - break; -#if defined FSL_SDHC_ENABLE_ADMA1 - case kSDHC_DmaModeAdma1: - error = SDHC_TransferByAdma1Blocking(base, data); - break; -#endif /* FSL_SDHC_ENABLE_ADMA1 */ - case kSDHC_DmaModeAdma2: - error = SDHC_TransferByAdma2Blocking(base, data); - break; - default: - error = kStatus_InvalidArgument; - break; - } - - return error; -} - -static void SDHC_TransferHandleCardDetect(sdhc_handle_t *handle, uint32_t interruptFlags) -{ - if (interruptFlags & kSDHC_CardInsertionFlag) - { - if (handle->callback.CardInserted) - { - handle->callback.CardInserted(); - } - } - else - { - if (handle->callback.CardRemoved) - { - handle->callback.CardRemoved(); - } - } -} - -static void SDHC_TransferHandleCommand(SDHC_Type *base, sdhc_handle_t *handle, uint32_t interruptFlags) -{ - assert(handle->command); - - if ((interruptFlags & kSDHC_CommandErrorFlag) && (!(handle->data)) && (handle->callback.TransferComplete)) - { - handle->callback.TransferComplete(base, handle, kStatus_SDHC_SendCommandFailed, handle->userData); - } - else - { - /* Receive response */ - SDHC_ReceiveCommandResponse(base, handle->command); - if ((!(handle->data)) && (handle->callback.TransferComplete)) - { - handle->callback.TransferComplete(base, handle, kStatus_Success, handle->userData); - } - } -} - -static void SDHC_TransferHandleData(SDHC_Type *base, sdhc_handle_t *handle, uint32_t interruptFlags) -{ - assert(handle->data); - - if ((!(handle->data->enableIgnoreError)) && (interruptFlags & (kSDHC_DataErrorFlag | kSDHC_DmaErrorFlag)) && - (handle->callback.TransferComplete)) - { - handle->callback.TransferComplete(base, handle, kStatus_SDHC_TransferDataFailed, handle->userData); - } - else - { - if (interruptFlags & kSDHC_BufferReadReadyFlag) - { - handle->transferredWords = SDHC_ReadDataPort(base, handle->data, handle->transferredWords); - } - else if (interruptFlags & kSDHC_BufferWriteReadyFlag) - { - handle->transferredWords = SDHC_WriteDataPort(base, handle->data, handle->transferredWords); - } - else - { - } - - if ((interruptFlags & kSDHC_DataCompleteFlag) && (handle->callback.TransferComplete)) - { - handle->callback.TransferComplete(base, handle, kStatus_Success, handle->userData); - } - else - { - /* Do nothing when DMA complete flag is set. Wait until data complete flag is set. */ - } - } -} - -static void SDHC_TransferHandleSdioInterrupt(sdhc_handle_t *handle) -{ - if (handle->callback.SdioInterrupt) - { - handle->callback.SdioInterrupt(); - } -} - -static void SDHC_TransferHandleSdioBlockGap(sdhc_handle_t *handle) -{ - if (handle->callback.SdioBlockGap) - { - handle->callback.SdioBlockGap(); - } -} - -void SDHC_Init(SDHC_Type *base, const sdhc_config_t *config) -{ - assert(config); -#if !defined FSL_SDHC_ENABLE_ADMA1 - assert(config->dmaMode != kSDHC_DmaModeAdma1); -#endif /* FSL_SDHC_ENABLE_ADMA1 */ - assert((config->writeWatermarkLevel >= 1U) && (config->writeWatermarkLevel <= 128U)); - assert((config->readWatermarkLevel >= 1U) && (config->readWatermarkLevel <= 128U)); - - uint32_t proctl; - uint32_t wml; - -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) - /* Enable SDHC clock. */ - CLOCK_EnableClock(s_sdhcClock[SDHC_GetInstance(base)]); -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ - - /* Reset SDHC. */ - SDHC_Reset(base, kSDHC_ResetAll, 100); - - proctl = base->PROCTL; - wml = base->WML; - - proctl &= ~(SDHC_PROCTL_D3CD_MASK | SDHC_PROCTL_EMODE_MASK | SDHC_PROCTL_DMAS_MASK); - /* Set DAT3 as card detection pin */ - if (config->cardDetectDat3) - { - proctl |= SDHC_PROCTL_D3CD_MASK; - } - /* Endian mode and DMA mode */ - proctl |= (SDHC_PROCTL_EMODE(config->endianMode) | SDHC_PROCTL_DMAS(config->dmaMode)); - - /* Watermark level */ - wml &= ~(SDHC_WML_RDWML_MASK | SDHC_WML_WRWML_MASK); - wml |= (SDHC_WML_RDWML(config->readWatermarkLevel) | SDHC_WML_WRWML(config->writeWatermarkLevel)); - - base->WML = wml; - base->PROCTL = proctl; - - /* Disable all clock auto gated off feature because of DAT0 line logic(card buffer full status) can't be updated - correctly when clock auto gated off is enabled. */ - base->SYSCTL |= (SDHC_SYSCTL_PEREN_MASK | SDHC_SYSCTL_HCKEN_MASK | SDHC_SYSCTL_IPGEN_MASK); - - /* Enable interrupt status but doesn't enable interrupt signal. */ - SDHC_SetTransferInterrupt(base, false); -} - -void SDHC_Deinit(SDHC_Type *base) -{ -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) - /* Disable clock. */ - CLOCK_DisableClock(s_sdhcClock[SDHC_GetInstance(base)]); -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ -} - -bool SDHC_Reset(SDHC_Type *base, uint32_t mask, uint32_t timeout) -{ - base->SYSCTL |= (mask & (SDHC_SYSCTL_RSTA_MASK | SDHC_SYSCTL_RSTC_MASK | SDHC_SYSCTL_RSTD_MASK)); - /* Delay some time to wait reset success. */ - while ((base->SYSCTL & mask)) - { - if (!timeout) - { - break; - } - timeout--; - } - - return ((!timeout) ? false : true); -} - -void SDHC_GetCapability(SDHC_Type *base, sdhc_capability_t *capability) -{ - assert(capability); - - uint32_t htCapability; - uint32_t hostVer; - uint32_t maxBlockLength; - - hostVer = base->HOSTVER; - htCapability = base->HTCAPBLT; - - /* Get the capability of SDHC. */ - capability->specVersion = ((hostVer & SDHC_HOSTVER_SVN_MASK) >> SDHC_HOSTVER_SVN_SHIFT); - capability->vendorVersion = ((hostVer & SDHC_HOSTVER_VVN_MASK) >> SDHC_HOSTVER_VVN_SHIFT); - maxBlockLength = ((htCapability & SDHC_HTCAPBLT_MBL_MASK) >> SDHC_HTCAPBLT_MBL_SHIFT); - capability->maxBlockLength = (512U << maxBlockLength); - /* Other attributes not in HTCAPBLT register. */ - capability->maxBlockCount = SDHC_MAX_BLOCK_COUNT; - capability->flags = (htCapability & (kSDHC_SupportAdmaFlag | kSDHC_SupportHighSpeedFlag | kSDHC_SupportDmaFlag | - kSDHC_SupportSuspendResumeFlag | kSDHC_SupportV330Flag)); -#if defined FSL_FEATURE_SDHC_HAS_V300_SUPPORT && FSL_FEATURE_SDHC_HAS_V300_SUPPORT - capability->flags |= (htCapability & kSDHC_SupportV300Flag); -#endif -#if defined FSL_FEATURE_SDHC_HAS_V180_SUPPORT && FSL_FEATURE_SDHC_HAS_V180_SUPPORT - capability->flags |= (htCapability & kSDHC_SupportV180Flag); -#endif - /* eSDHC on all kinetis boards will support 4/8 bit data bus width. */ - capability->flags |= (kSDHC_Support4BitFlag | kSDHC_Support8BitFlag); -} - -uint32_t SDHC_SetSdClock(SDHC_Type *base, uint32_t srcClock_Hz, uint32_t busClock_Hz) -{ - assert(srcClock_Hz != 0U); - assert((busClock_Hz != 0U) && (busClock_Hz <= srcClock_Hz)); - - uint32_t totalDiv = 0U; - uint32_t divisor = 0U; - uint32_t prescaler = 0U; - uint32_t sysctl = 0U; - uint32_t nearestFrequency = 0U; - - /* calucate total divisor first */ - totalDiv = srcClock_Hz / busClock_Hz; - - if (totalDiv != 0U) - { - /* calucate the divisor (srcClock_Hz / divisor) <= busClock_Hz */ - if ((srcClock_Hz / totalDiv) > busClock_Hz) - { - totalDiv++; - } - - /* divide the total divisor to div and prescaler */ - if (totalDiv > SDHC_MAX_DVS) - { - prescaler = totalDiv / SDHC_MAX_DVS; - /* prescaler must be a value which equal 2^n and smaller than SDHC_MAX_CLKFS */ - while (((SDHC_MAX_CLKFS % prescaler) != 0U) || (prescaler == 1U)) - { - prescaler++; - } - /* calucate the divisor */ - divisor = totalDiv / prescaler; - /* fine tuning the divisor until divisor * prescaler >= totalDiv */ - while ((divisor * prescaler) < totalDiv) - { - divisor++; - } - nearestFrequency = srcClock_Hz / divisor / prescaler; - } - else - { - divisor = totalDiv; - prescaler = 0U; - nearestFrequency = srcClock_Hz / divisor; - } - } - /* in this condition , srcClock_Hz = busClock_Hz, */ - else - { - /* total divider = 1U */ - divisor = 0U; - prescaler = 0U; - nearestFrequency = srcClock_Hz; - } - - /* calucate the value write to register */ - if (divisor != 0U) - { - SDHC_PREV_DVS(divisor); - } - /* calucate the value write to register */ - if (prescaler != 0U) - { - SDHC_PREV_CLKFS(prescaler); - } - - /* Disable SD clock. It should be disabled before changing the SD clock frequency.*/ - base->SYSCTL &= ~SDHC_SYSCTL_SDCLKEN_MASK; - - /* Set the SD clock frequency divisor, SD clock frequency select, data timeout counter value. */ - sysctl = base->SYSCTL; - sysctl &= ~(SDHC_SYSCTL_DVS_MASK | SDHC_SYSCTL_SDCLKFS_MASK | SDHC_SYSCTL_DTOCV_MASK); - sysctl |= (SDHC_SYSCTL_DVS(divisor) | SDHC_SYSCTL_SDCLKFS(prescaler) | SDHC_SYSCTL_DTOCV(0xEU)); - base->SYSCTL = sysctl; - - /* Wait until the SD clock is stable. */ - while (!(base->PRSSTAT & SDHC_PRSSTAT_SDSTB_MASK)) - { - } - /* Enable the SD clock. */ - base->SYSCTL |= SDHC_SYSCTL_SDCLKEN_MASK; - - return nearestFrequency; -} - -bool SDHC_SetCardActive(SDHC_Type *base, uint32_t timeout) -{ - base->SYSCTL |= SDHC_SYSCTL_INITA_MASK; - /* Delay some time to wait card become active state. */ - while (base->SYSCTL & SDHC_SYSCTL_INITA_MASK) - { - if (!timeout) - { - break; - } - timeout--; - } - - return ((!timeout) ? false : true); -} - -void SDHC_SetTransferConfig(SDHC_Type *base, const sdhc_transfer_config_t *config) -{ - assert(config); - assert(config->dataBlockSize <= (SDHC_BLKATTR_BLKSIZE_MASK >> SDHC_BLKATTR_BLKSIZE_SHIFT)); - assert(config->dataBlockCount <= (SDHC_BLKATTR_BLKCNT_MASK >> SDHC_BLKATTR_BLKCNT_SHIFT)); - - base->BLKATTR = ((base->BLKATTR & ~(SDHC_BLKATTR_BLKSIZE_MASK | SDHC_BLKATTR_BLKCNT_MASK)) | - (SDHC_BLKATTR_BLKSIZE(config->dataBlockSize) | SDHC_BLKATTR_BLKCNT(config->dataBlockCount))); - base->CMDARG = config->commandArgument; - base->XFERTYP = (((config->commandIndex << SDHC_XFERTYP_CMDINX_SHIFT) & SDHC_XFERTYP_CMDINX_MASK) | - (config->flags & (SDHC_XFERTYP_DMAEN_MASK | SDHC_XFERTYP_MSBSEL_MASK | SDHC_XFERTYP_DPSEL_MASK | - SDHC_XFERTYP_CMDTYP_MASK | SDHC_XFERTYP_BCEN_MASK | SDHC_XFERTYP_CICEN_MASK | - SDHC_XFERTYP_CCCEN_MASK | SDHC_XFERTYP_RSPTYP_MASK | SDHC_XFERTYP_DTDSEL_MASK | - SDHC_XFERTYP_AC12EN_MASK))); -} - -void SDHC_EnableSdioControl(SDHC_Type *base, uint32_t mask, bool enable) -{ - uint32_t proctl = base->PROCTL; - uint32_t vendor = base->VENDOR; - - if (enable) - { - if (mask & kSDHC_StopAtBlockGapFlag) - { - proctl |= SDHC_PROCTL_SABGREQ_MASK; - } - if (mask & kSDHC_ReadWaitControlFlag) - { - proctl |= SDHC_PROCTL_RWCTL_MASK; - } - if (mask & kSDHC_InterruptAtBlockGapFlag) - { - proctl |= SDHC_PROCTL_IABG_MASK; - } - if (mask & kSDHC_ExactBlockNumberReadFlag) - { - vendor |= SDHC_VENDOR_EXBLKNU_MASK; - } - } - else - { - if (mask & kSDHC_StopAtBlockGapFlag) - { - proctl &= ~SDHC_PROCTL_SABGREQ_MASK; - } - if (mask & kSDHC_ReadWaitControlFlag) - { - proctl &= ~SDHC_PROCTL_RWCTL_MASK; - } - if (mask & kSDHC_InterruptAtBlockGapFlag) - { - proctl &= ~SDHC_PROCTL_IABG_MASK; - } - if (mask & kSDHC_ExactBlockNumberReadFlag) - { - vendor &= ~SDHC_VENDOR_EXBLKNU_MASK; - } - } - - base->PROCTL = proctl; - base->VENDOR = vendor; -} - -void SDHC_SetMmcBootConfig(SDHC_Type *base, const sdhc_boot_config_t *config) -{ - assert(config); - assert(config->ackTimeoutCount <= (SDHC_MMCBOOT_DTOCVACK_MASK >> SDHC_MMCBOOT_DTOCVACK_SHIFT)); - assert(config->blockCount <= (SDHC_MMCBOOT_BOOTBLKCNT_MASK >> SDHC_MMCBOOT_BOOTBLKCNT_SHIFT)); - - uint32_t mmcboot = 0U; - - mmcboot = (SDHC_MMCBOOT_DTOCVACK(config->ackTimeoutCount) | SDHC_MMCBOOT_BOOTMODE(config->bootMode) | - SDHC_MMCBOOT_BOOTBLKCNT(config->blockCount)); - if (config->enableBootAck) - { - mmcboot |= SDHC_MMCBOOT_BOOTACK_MASK; - } - if (config->enableBoot) - { - mmcboot |= SDHC_MMCBOOT_BOOTEN_MASK; - } - if (config->enableAutoStopAtBlockGap) - { - mmcboot |= SDHC_MMCBOOT_AUTOSABGEN_MASK; - } - base->MMCBOOT = mmcboot; -} - -status_t SDHC_SetAdmaTableConfig(SDHC_Type *base, - sdhc_dma_mode_t dmaMode, - uint32_t *table, - uint32_t tableWords, - const uint32_t *data, - uint32_t dataBytes) -{ - status_t error = kStatus_Success; - const uint32_t *startAddress = data; - uint32_t entries; - uint32_t i; -#if defined FSL_SDHC_ENABLE_ADMA1 - sdhc_adma1_descriptor_t *adma1EntryAddress; -#endif - sdhc_adma2_descriptor_t *adma2EntryAddress; - - if ((((!table) || (!tableWords)) && ((dmaMode == kSDHC_DmaModeAdma1) || (dmaMode == kSDHC_DmaModeAdma2))) || - (!data) || (!dataBytes) -#if !defined FSL_SDHC_ENABLE_ADMA1 - || (dmaMode == kSDHC_DmaModeAdma1) -#endif - ) - { - error = kStatus_InvalidArgument; - } - else if (((dmaMode == kSDHC_DmaModeAdma2) && (((uint32_t)startAddress % SDHC_ADMA2_LENGTH_ALIGN) != 0U)) -#if defined FSL_SDHC_ENABLE_ADMA1 - || ((dmaMode == kSDHC_DmaModeAdma1) && (((uint32_t)startAddress % SDHC_ADMA1_LENGTH_ALIGN) != 0U)) -#endif - ) - { - error = kStatus_SDHC_DMADataBufferAddrNotAlign; - } - else - { - switch (dmaMode) - { - case kSDHC_DmaModeNo: - break; -#if defined FSL_SDHC_ENABLE_ADMA1 - case kSDHC_DmaModeAdma1: - /* - * Add non aligned access support ,user need make sure your buffer size is big - * enough to hold the data,in other words,user need make sure the buffer size - * is 4 byte aligned - */ - if (dataBytes % sizeof(uint32_t) != 0U) - { - dataBytes += - sizeof(uint32_t) - (dataBytes % sizeof(uint32_t)); /* make the data length as word-aligned */ - } - - /* Check if ADMA descriptor's number is enough. */ - entries = ((dataBytes / SDHC_ADMA1_DESCRIPTOR_MAX_LENGTH_PER_ENTRY) + 1U); - /* ADMA1 needs two descriptors to finish a transfer */ - entries <<= 1U; - if (entries > ((tableWords * sizeof(uint32_t)) / sizeof(sdhc_adma1_descriptor_t))) - { - error = kStatus_OutOfRange; - } - else - { - adma1EntryAddress = (sdhc_adma1_descriptor_t *)(table); - for (i = 0U; i < entries; i += 2U) - { - /* Each descriptor for ADMA1 is 32-bit in length */ - if ((dataBytes - sizeof(uint32_t) * (startAddress - data)) <= - SDHC_ADMA1_DESCRIPTOR_MAX_LENGTH_PER_ENTRY) - { - /* The last piece of data, setting end flag in descriptor */ - adma1EntryAddress[i] = ((uint32_t)(dataBytes - sizeof(uint32_t) * (startAddress - data)) - << SDHC_ADMA1_DESCRIPTOR_LENGTH_SHIFT); - adma1EntryAddress[i] |= kSDHC_Adma1DescriptorTypeSetLength; - adma1EntryAddress[i + 1U] = - ((uint32_t)(startAddress) << SDHC_ADMA1_DESCRIPTOR_ADDRESS_SHIFT); - adma1EntryAddress[i + 1U] |= - (kSDHC_Adma1DescriptorTypeTransfer | kSDHC_Adma1DescriptorEndFlag); - } - else - { - adma1EntryAddress[i] = ((uint32_t)SDHC_ADMA1_DESCRIPTOR_MAX_LENGTH_PER_ENTRY - << SDHC_ADMA1_DESCRIPTOR_LENGTH_SHIFT); - adma1EntryAddress[i] |= kSDHC_Adma1DescriptorTypeSetLength; - adma1EntryAddress[i + 1U] = - ((uint32_t)(startAddress) << SDHC_ADMA1_DESCRIPTOR_ADDRESS_SHIFT); - adma1EntryAddress[i + 1U] |= kSDHC_Adma1DescriptorTypeTransfer; - startAddress += SDHC_ADMA1_DESCRIPTOR_MAX_LENGTH_PER_ENTRY / sizeof(uint32_t); - } - } - - /* When use ADMA, disable simple DMA */ - base->DSADDR = 0U; - base->ADSADDR = (uint32_t)table; - /* disable the buffer ready flag in DMA mode */ - SDHC_DisableInterruptSignal(base, kSDHC_BufferReadReadyFlag | kSDHC_BufferWriteReadyFlag); - SDHC_DisableInterruptStatus(base, kSDHC_BufferReadReadyFlag | kSDHC_BufferWriteReadyFlag); - } - break; -#endif /* FSL_SDHC_ENABLE_ADMA1 */ - case kSDHC_DmaModeAdma2: - /* - * Add non aligned access support ,user need make sure your buffer size is big - * enough to hold the data,in other words,user need make sure the buffer size - * is 4 byte aligned - */ - if (dataBytes % sizeof(uint32_t) != 0U) - { - dataBytes += - sizeof(uint32_t) - (dataBytes % sizeof(uint32_t)); /* make the data length as word-aligned */ - } - - /* Check if ADMA descriptor's number is enough. */ - entries = ((dataBytes / SDHC_ADMA2_DESCRIPTOR_MAX_LENGTH_PER_ENTRY) + 1U); - if (entries > ((tableWords * sizeof(uint32_t)) / sizeof(sdhc_adma2_descriptor_t))) - { - error = kStatus_OutOfRange; - } - else - { - adma2EntryAddress = (sdhc_adma2_descriptor_t *)(table); - for (i = 0U; i < entries; i++) - { - /* Each descriptor for ADMA2 is 64-bit in length */ - if ((dataBytes - sizeof(uint32_t) * (startAddress - data)) <= - SDHC_ADMA2_DESCRIPTOR_MAX_LENGTH_PER_ENTRY) - { - /* The last piece of data, setting end flag in descriptor */ - adma2EntryAddress[i].address = startAddress; - adma2EntryAddress[i].attribute = ((dataBytes - sizeof(uint32_t) * (startAddress - data)) - << SDHC_ADMA2_DESCRIPTOR_LENGTH_SHIFT); - adma2EntryAddress[i].attribute |= - (kSDHC_Adma2DescriptorTypeTransfer | kSDHC_Adma2DescriptorEndFlag); - } - else - { - adma2EntryAddress[i].address = startAddress; - adma2EntryAddress[i].attribute = - (((SDHC_ADMA2_DESCRIPTOR_MAX_LENGTH_PER_ENTRY / sizeof(uint32_t)) * sizeof(uint32_t)) - << SDHC_ADMA2_DESCRIPTOR_LENGTH_SHIFT); - adma2EntryAddress[i].attribute |= kSDHC_Adma2DescriptorTypeTransfer; - startAddress += (SDHC_ADMA2_DESCRIPTOR_MAX_LENGTH_PER_ENTRY / sizeof(uint32_t)); - } - } - - /* When use ADMA, disable simple DMA */ - base->DSADDR = 0U; - base->ADSADDR = (uint32_t)table; - /* disable the buffer read flag in DMA mode */ - SDHC_DisableInterruptSignal(base, kSDHC_BufferReadReadyFlag | kSDHC_BufferWriteReadyFlag); - SDHC_DisableInterruptStatus(base, kSDHC_BufferReadReadyFlag | kSDHC_BufferWriteReadyFlag); - } - break; - default: - break; - } - } - - return error; -} - -status_t SDHC_TransferBlocking(SDHC_Type *base, uint32_t *admaTable, uint32_t admaTableWords, sdhc_transfer_t *transfer) -{ - assert(transfer); - - status_t error = kStatus_Success; - sdhc_dma_mode_t dmaMode = (sdhc_dma_mode_t)((base->PROCTL & SDHC_PROCTL_DMAS_MASK) >> SDHC_PROCTL_DMAS_SHIFT); - sdhc_command_t *command = transfer->command; - sdhc_data_t *data = transfer->data; - - /* make sure the cmd/block count is valid */ - if ((!command) || (data && (data->blockCount > SDHC_MAX_BLOCK_COUNT))) - { - return kStatus_InvalidArgument; - } - - /* Wait until command/data bus out of busy status. */ - while (SDHC_GetPresentStatusFlags(base) & kSDHC_CommandInhibitFlag) - { - } - while (data && (SDHC_GetPresentStatusFlags(base) & kSDHC_DataInhibitFlag)) - { - } - - /* Update ADMA descriptor table according to different DMA mode(no DMA, ADMA1, ADMA2).*/ - if (data && (NULL != admaTable)) - { - error = - SDHC_SetAdmaTableConfig(base, dmaMode, admaTable, admaTableWords, - (data->rxData ? data->rxData : data->txData), (data->blockCount * data->blockSize)); - /* in this situation , we disable the DMA instead of polling transfer mode */ - if (error == kStatus_SDHC_DMADataBufferAddrNotAlign) - { - dmaMode = kSDHC_DmaModeNo; - SDHC_EnableInterruptStatus(base, kSDHC_BufferReadReadyFlag | kSDHC_BufferWriteReadyFlag); - } - else if (error != kStatus_Success) - { - return error; - } - else - { - } - } - - /* Send command and receive data. */ - SDHC_StartTransfer(base, command, data, dmaMode); - if (kStatus_Success != SDHC_SendCommandBlocking(base, command)) - { - return kStatus_SDHC_SendCommandFailed; - } - else if (data && (kStatus_Success != SDHC_TransferDataBlocking(dmaMode, base, data))) - { - return kStatus_SDHC_TransferDataFailed; - } - else - { - } - - return kStatus_Success; -} - -void SDHC_TransferCreateHandle(SDHC_Type *base, - sdhc_handle_t *handle, - const sdhc_transfer_callback_t *callback, - void *userData) -{ - assert(handle); - assert(callback); - - /* Zero the handle. */ - memset(handle, 0, sizeof(*handle)); - - /* Set the callback. */ - handle->callback.CardInserted = callback->CardInserted; - handle->callback.CardRemoved = callback->CardRemoved; - handle->callback.SdioInterrupt = callback->SdioInterrupt; - handle->callback.SdioBlockGap = callback->SdioBlockGap; - handle->callback.TransferComplete = callback->TransferComplete; - handle->userData = userData; - - /* Save the handle in global variables to support the double weak mechanism. */ - s_sdhcHandle[SDHC_GetInstance(base)] = handle; - - /* Enable interrupt in NVIC. */ - SDHC_SetTransferInterrupt(base, true); - - /* save IRQ handler */ - s_sdhcIsr = SDHC_TransferHandleIRQ; - - EnableIRQ(s_sdhcIRQ[SDHC_GetInstance(base)]); -} - -status_t SDHC_TransferNonBlocking( - SDHC_Type *base, sdhc_handle_t *handle, uint32_t *admaTable, uint32_t admaTableWords, sdhc_transfer_t *transfer) -{ - assert(transfer); - - sdhc_dma_mode_t dmaMode = (sdhc_dma_mode_t)((base->PROCTL & SDHC_PROCTL_DMAS_MASK) >> SDHC_PROCTL_DMAS_SHIFT); - status_t error = kStatus_Success; - sdhc_command_t *command = transfer->command; - sdhc_data_t *data = transfer->data; - - /* make sure cmd/block count is valid */ - if ((!command) || (data && (data->blockCount > SDHC_MAX_BLOCK_COUNT))) - { - return kStatus_InvalidArgument; - } - - /* Wait until command/data bus out of busy status. */ - if ((SDHC_GetPresentStatusFlags(base) & kSDHC_CommandInhibitFlag) || - (data && (SDHC_GetPresentStatusFlags(base) & kSDHC_DataInhibitFlag))) - { - return kStatus_SDHC_BusyTransferring; - } - - /* Update ADMA descriptor table according to different DMA mode(no DMA, ADMA1, ADMA2).*/ - if (data && (NULL != admaTable)) - { - error = - SDHC_SetAdmaTableConfig(base, dmaMode, admaTable, admaTableWords, - (data->rxData ? data->rxData : data->txData), (data->blockCount * data->blockSize)); - /* in this situation , we disable the DMA instead of polling transfer mode */ - if (error == kStatus_SDHC_DMADataBufferAddrNotAlign) - { - /* change to polling mode */ - dmaMode = kSDHC_DmaModeNo; - SDHC_EnableInterruptSignal(base, kSDHC_BufferReadReadyFlag | kSDHC_BufferWriteReadyFlag); - SDHC_EnableInterruptStatus(base, kSDHC_BufferReadReadyFlag | kSDHC_BufferWriteReadyFlag); - } - else if (error != kStatus_Success) - { - return error; - } - else - { - } - } - - /* Save command and data into handle before transferring. */ - handle->command = command; - handle->data = data; - handle->interruptFlags = 0U; - /* transferredWords will only be updated in ISR when transfer way is DATAPORT. */ - handle->transferredWords = 0U; - - SDHC_StartTransfer(base, command, data, dmaMode); - - return kStatus_Success; -} - -void SDHC_TransferHandleIRQ(SDHC_Type *base, sdhc_handle_t *handle) -{ - assert(handle); - - uint32_t interruptFlags; - - interruptFlags = SDHC_GetInterruptStatusFlags(base); - handle->interruptFlags = interruptFlags; - - if (interruptFlags & kSDHC_CardDetectFlag) - { - SDHC_TransferHandleCardDetect(handle, (interruptFlags & kSDHC_CardDetectFlag)); - } - if (interruptFlags & kSDHC_CommandFlag) - { - SDHC_TransferHandleCommand(base, handle, (interruptFlags & kSDHC_CommandFlag)); - } - if (interruptFlags & kSDHC_DataFlag) - { - SDHC_TransferHandleData(base, handle, (interruptFlags & kSDHC_DataFlag)); - } - if (interruptFlags & kSDHC_CardInterruptFlag) - { - SDHC_TransferHandleSdioInterrupt(handle); - } - if (interruptFlags & kSDHC_BlockGapEventFlag) - { - SDHC_TransferHandleSdioBlockGap(handle); - } - - SDHC_ClearInterruptStatusFlags(base, interruptFlags); -} - -#if defined(SDHC) -void SDHC_DriverIRQHandler(void) -{ - assert(s_sdhcHandle[0]); - - s_sdhcIsr(SDHC, s_sdhcHandle[0]); -} -#endif diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_sdhc.h b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_sdhc.h deleted file mode 100644 index 336b9618e5b..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_sdhc.h +++ /dev/null @@ -1,1095 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -#ifndef _FSL_SDHC_H_ -#define _FSL_SDHC_H_ - -#include "fsl_common.h" - -/*! - * @addtogroup sdhc - * @{ - */ - -/****************************************************************************** - * Definitions. - *****************************************************************************/ - -/*! @name Driver version */ -/*@{*/ -/*! @brief Driver version 2.1.5. */ -#define FSL_SDHC_DRIVER_VERSION (MAKE_VERSION(2U, 1U, 5U)) -/*@}*/ - -/*! @brief Maximum block count can be set one time */ -#define SDHC_MAX_BLOCK_COUNT (SDHC_BLKATTR_BLKCNT_MASK >> SDHC_BLKATTR_BLKCNT_SHIFT) - -/*! @brief SDHC status */ -enum _sdhc_status -{ - kStatus_SDHC_BusyTransferring = MAKE_STATUS(kStatusGroup_SDHC, 0U), /*!< Transfer is on-going */ - kStatus_SDHC_PrepareAdmaDescriptorFailed = MAKE_STATUS(kStatusGroup_SDHC, 1U), /*!< Set DMA descriptor failed */ - kStatus_SDHC_SendCommandFailed = MAKE_STATUS(kStatusGroup_SDHC, 2U), /*!< Send command failed */ - kStatus_SDHC_TransferDataFailed = MAKE_STATUS(kStatusGroup_SDHC, 3U), /*!< Transfer data failed */ - kStatus_SDHC_DMADataBufferAddrNotAlign = - MAKE_STATUS(kStatusGroup_SDHC, 4U), /*!< data buffer addr not align in DMA mode */ -}; - -/*! @brief Host controller capabilities flag mask */ -enum _sdhc_capability_flag -{ - kSDHC_SupportAdmaFlag = SDHC_HTCAPBLT_ADMAS_MASK, /*!< Support ADMA */ - kSDHC_SupportHighSpeedFlag = SDHC_HTCAPBLT_HSS_MASK, /*!< Support high-speed */ - kSDHC_SupportDmaFlag = SDHC_HTCAPBLT_DMAS_MASK, /*!< Support DMA */ - kSDHC_SupportSuspendResumeFlag = SDHC_HTCAPBLT_SRS_MASK, /*!< Support suspend/resume */ - kSDHC_SupportV330Flag = SDHC_HTCAPBLT_VS33_MASK, /*!< Support voltage 3.3V */ -#if defined FSL_FEATURE_SDHC_HAS_V300_SUPPORT && FSL_FEATURE_SDHC_HAS_V300_SUPPORT - kSDHC_SupportV300Flag = SDHC_HTCAPBLT_VS30_MASK, /*!< Support voltage 3.0V */ -#endif -#if defined FSL_FEATURE_SDHC_HAS_V180_SUPPORT && FSL_FEATURE_SDHC_HAS_V180_SUPPORT - kSDHC_SupportV180Flag = SDHC_HTCAPBLT_VS18_MASK, /*!< Support voltage 1.8V */ -#endif - /* Put additional two flags in HTCAPBLT_MBL's position. */ - kSDHC_Support4BitFlag = (SDHC_HTCAPBLT_MBL_SHIFT << 0U), /*!< Support 4 bit mode */ - kSDHC_Support8BitFlag = (SDHC_HTCAPBLT_MBL_SHIFT << 1U), /*!< Support 8 bit mode */ -}; - -/*! @brief Wakeup event mask */ -enum _sdhc_wakeup_event -{ - kSDHC_WakeupEventOnCardInt = SDHC_PROCTL_WECINT_MASK, /*!< Wakeup on card interrupt */ - kSDHC_WakeupEventOnCardInsert = SDHC_PROCTL_WECINS_MASK, /*!< Wakeup on card insertion */ - kSDHC_WakeupEventOnCardRemove = SDHC_PROCTL_WECRM_MASK, /*!< Wakeup on card removal */ - - kSDHC_WakeupEventsAll = (kSDHC_WakeupEventOnCardInt | kSDHC_WakeupEventOnCardInsert | - kSDHC_WakeupEventOnCardRemove), /*!< All wakeup events */ -}; - -/*! @brief Reset type mask */ -enum _sdhc_reset -{ - kSDHC_ResetAll = SDHC_SYSCTL_RSTA_MASK, /*!< Reset all except card detection */ - kSDHC_ResetCommand = SDHC_SYSCTL_RSTC_MASK, /*!< Reset command line */ - kSDHC_ResetData = SDHC_SYSCTL_RSTD_MASK, /*!< Reset data line */ - - kSDHC_ResetsAll = (kSDHC_ResetAll | kSDHC_ResetCommand | kSDHC_ResetData), /*!< All reset types */ -}; - -/*! @brief Transfer flag mask */ -enum _sdhc_transfer_flag -{ - kSDHC_EnableDmaFlag = SDHC_XFERTYP_DMAEN_MASK, /*!< Enable DMA */ - - kSDHC_CommandTypeSuspendFlag = (SDHC_XFERTYP_CMDTYP(1U)), /*!< Suspend command */ - kSDHC_CommandTypeResumeFlag = (SDHC_XFERTYP_CMDTYP(2U)), /*!< Resume command */ - kSDHC_CommandTypeAbortFlag = (SDHC_XFERTYP_CMDTYP(3U)), /*!< Abort command */ - - kSDHC_EnableBlockCountFlag = SDHC_XFERTYP_BCEN_MASK, /*!< Enable block count */ - kSDHC_EnableAutoCommand12Flag = SDHC_XFERTYP_AC12EN_MASK, /*!< Enable auto CMD12 */ - kSDHC_DataReadFlag = SDHC_XFERTYP_DTDSEL_MASK, /*!< Enable data read */ - kSDHC_MultipleBlockFlag = SDHC_XFERTYP_MSBSEL_MASK, /*!< Multiple block data read/write */ - - kSDHC_ResponseLength136Flag = SDHC_XFERTYP_RSPTYP(1U), /*!< 136 bit response length */ - kSDHC_ResponseLength48Flag = SDHC_XFERTYP_RSPTYP(2U), /*!< 48 bit response length */ - kSDHC_ResponseLength48BusyFlag = SDHC_XFERTYP_RSPTYP(3U), /*!< 48 bit response length with busy status */ - - kSDHC_EnableCrcCheckFlag = SDHC_XFERTYP_CCCEN_MASK, /*!< Enable CRC check */ - kSDHC_EnableIndexCheckFlag = SDHC_XFERTYP_CICEN_MASK, /*!< Enable index check */ - kSDHC_DataPresentFlag = SDHC_XFERTYP_DPSEL_MASK, /*!< Data present flag */ -}; - -/*! @brief Present status flag mask */ -enum _sdhc_present_status_flag -{ - kSDHC_CommandInhibitFlag = SDHC_PRSSTAT_CIHB_MASK, /*!< Command inhibit */ - kSDHC_DataInhibitFlag = SDHC_PRSSTAT_CDIHB_MASK, /*!< Data inhibit */ - kSDHC_DataLineActiveFlag = SDHC_PRSSTAT_DLA_MASK, /*!< Data line active */ - kSDHC_SdClockStableFlag = SDHC_PRSSTAT_SDSTB_MASK, /*!< SD bus clock stable */ - kSDHC_WriteTransferActiveFlag = SDHC_PRSSTAT_WTA_MASK, /*!< Write transfer active */ - kSDHC_ReadTransferActiveFlag = SDHC_PRSSTAT_RTA_MASK, /*!< Read transfer active */ - kSDHC_BufferWriteEnableFlag = SDHC_PRSSTAT_BWEN_MASK, /*!< Buffer write enable */ - kSDHC_BufferReadEnableFlag = SDHC_PRSSTAT_BREN_MASK, /*!< Buffer read enable */ - kSDHC_CardInsertedFlag = SDHC_PRSSTAT_CINS_MASK, /*!< Card inserted */ - kSDHC_CommandLineLevelFlag = SDHC_PRSSTAT_CLSL_MASK, /*!< Command line signal level */ - kSDHC_Data0LineLevelFlag = (1U << 24U), /*!< Data0 line signal level */ - kSDHC_Data1LineLevelFlag = (1U << 25U), /*!< Data1 line signal level */ - kSDHC_Data2LineLevelFlag = (1U << 26U), /*!< Data2 line signal level */ - kSDHC_Data3LineLevelFlag = (1U << 27U), /*!< Data3 line signal level */ - kSDHC_Data4LineLevelFlag = (1U << 28U), /*!< Data4 line signal level */ - kSDHC_Data5LineLevelFlag = (1U << 29U), /*!< Data5 line signal level */ - kSDHC_Data6LineLevelFlag = (1U << 30U), /*!< Data6 line signal level */ - kSDHC_Data7LineLevelFlag = (1U << 31U), /*!< Data7 line signal level */ -}; - -/*! @brief Interrupt status flag mask */ -enum _sdhc_interrupt_status_flag -{ - kSDHC_CommandCompleteFlag = SDHC_IRQSTAT_CC_MASK, /*!< Command complete */ - kSDHC_DataCompleteFlag = SDHC_IRQSTAT_TC_MASK, /*!< Data complete */ - kSDHC_BlockGapEventFlag = SDHC_IRQSTAT_BGE_MASK, /*!< Block gap event */ - kSDHC_DmaCompleteFlag = SDHC_IRQSTAT_DINT_MASK, /*!< DMA interrupt */ - kSDHC_BufferWriteReadyFlag = SDHC_IRQSTAT_BWR_MASK, /*!< Buffer write ready */ - kSDHC_BufferReadReadyFlag = SDHC_IRQSTAT_BRR_MASK, /*!< Buffer read ready */ - kSDHC_CardInsertionFlag = SDHC_IRQSTAT_CINS_MASK, /*!< Card inserted */ - kSDHC_CardRemovalFlag = SDHC_IRQSTAT_CRM_MASK, /*!< Card removed */ - kSDHC_CardInterruptFlag = SDHC_IRQSTAT_CINT_MASK, /*!< Card interrupt */ - kSDHC_CommandTimeoutFlag = SDHC_IRQSTAT_CTOE_MASK, /*!< Command timeout error */ - kSDHC_CommandCrcErrorFlag = SDHC_IRQSTAT_CCE_MASK, /*!< Command CRC error */ - kSDHC_CommandEndBitErrorFlag = SDHC_IRQSTAT_CEBE_MASK, /*!< Command end bit error */ - kSDHC_CommandIndexErrorFlag = SDHC_IRQSTAT_CIE_MASK, /*!< Command index error */ - kSDHC_DataTimeoutFlag = SDHC_IRQSTAT_DTOE_MASK, /*!< Data timeout error */ - kSDHC_DataCrcErrorFlag = SDHC_IRQSTAT_DCE_MASK, /*!< Data CRC error */ - kSDHC_DataEndBitErrorFlag = SDHC_IRQSTAT_DEBE_MASK, /*!< Data end bit error */ - kSDHC_AutoCommand12ErrorFlag = SDHC_IRQSTAT_AC12E_MASK, /*!< Auto CMD12 error */ - kSDHC_DmaErrorFlag = SDHC_IRQSTAT_DMAE_MASK, /*!< DMA error */ - - kSDHC_CommandErrorFlag = (kSDHC_CommandTimeoutFlag | kSDHC_CommandCrcErrorFlag | kSDHC_CommandEndBitErrorFlag | - kSDHC_CommandIndexErrorFlag), /*!< Command error */ - kSDHC_DataErrorFlag = (kSDHC_DataTimeoutFlag | kSDHC_DataCrcErrorFlag | kSDHC_DataEndBitErrorFlag | - kSDHC_AutoCommand12ErrorFlag), /*!< Data error */ - kSDHC_ErrorFlag = (kSDHC_CommandErrorFlag | kSDHC_DataErrorFlag | kSDHC_DmaErrorFlag), /*!< All error */ - kSDHC_DataFlag = (kSDHC_DataCompleteFlag | kSDHC_DmaCompleteFlag | kSDHC_BufferWriteReadyFlag | - kSDHC_BufferReadReadyFlag | kSDHC_DataErrorFlag | kSDHC_DmaErrorFlag), /*!< Data interrupts */ - kSDHC_CommandFlag = (kSDHC_CommandErrorFlag | kSDHC_CommandCompleteFlag), /*!< Command interrupts */ - kSDHC_CardDetectFlag = (kSDHC_CardInsertionFlag | kSDHC_CardRemovalFlag), /*!< Card detection interrupts */ - - kSDHC_AllInterruptFlags = (kSDHC_BlockGapEventFlag | kSDHC_CardInterruptFlag | kSDHC_CommandFlag | kSDHC_DataFlag | - kSDHC_ErrorFlag), /*!< All flags mask */ -}; - -/*! @brief Auto CMD12 error status flag mask */ -enum _sdhc_auto_command12_error_status_flag -{ - kSDHC_AutoCommand12NotExecutedFlag = SDHC_AC12ERR_AC12NE_MASK, /*!< Not executed error */ - kSDHC_AutoCommand12TimeoutFlag = SDHC_AC12ERR_AC12TOE_MASK, /*!< Timeout error */ - kSDHC_AutoCommand12EndBitErrorFlag = SDHC_AC12ERR_AC12EBE_MASK, /*!< End bit error */ - kSDHC_AutoCommand12CrcErrorFlag = SDHC_AC12ERR_AC12CE_MASK, /*!< CRC error */ - kSDHC_AutoCommand12IndexErrorFlag = SDHC_AC12ERR_AC12IE_MASK, /*!< Index error */ - kSDHC_AutoCommand12NotIssuedFlag = SDHC_AC12ERR_CNIBAC12E_MASK, /*!< Not issued error */ -}; - -/*! @brief ADMA error status flag mask */ -enum _sdhc_adma_error_status_flag -{ - kSDHC_AdmaLenghMismatchFlag = SDHC_ADMAES_ADMALME_MASK, /*!< Length mismatch error */ - kSDHC_AdmaDescriptorErrorFlag = SDHC_ADMAES_ADMADCE_MASK, /*!< Descriptor error */ -}; - -/*! - * @brief ADMA error state - * - * This state is the detail state when ADMA error has occurred. - */ -typedef enum _sdhc_adma_error_state -{ - kSDHC_AdmaErrorStateStopDma = 0x00U, /*!< Stop DMA */ - kSDHC_AdmaErrorStateFetchDescriptor = 0x01U, /*!< Fetch descriptor */ - kSDHC_AdmaErrorStateChangeAddress = 0x02U, /*!< Change address */ - kSDHC_AdmaErrorStateTransferData = 0x03U, /*!< Transfer data */ -} sdhc_adma_error_state_t; - -/*! @brief Force event mask */ -enum _sdhc_force_event -{ - kSDHC_ForceEventAutoCommand12NotExecuted = SDHC_FEVT_AC12NE_MASK, /*!< Auto CMD12 not executed error */ - kSDHC_ForceEventAutoCommand12Timeout = SDHC_FEVT_AC12TOE_MASK, /*!< Auto CMD12 timeout error */ - kSDHC_ForceEventAutoCommand12CrcError = SDHC_FEVT_AC12CE_MASK, /*!< Auto CMD12 CRC error */ - kSDHC_ForceEventEndBitError = SDHC_FEVT_AC12EBE_MASK, /*!< Auto CMD12 end bit error */ - kSDHC_ForceEventAutoCommand12IndexError = SDHC_FEVT_AC12IE_MASK, /*!< Auto CMD12 index error */ - kSDHC_ForceEventAutoCommand12NotIssued = SDHC_FEVT_CNIBAC12E_MASK, /*!< Auto CMD12 not issued error */ - kSDHC_ForceEventCommandTimeout = SDHC_FEVT_CTOE_MASK, /*!< Command timeout error */ - kSDHC_ForceEventCommandCrcError = SDHC_FEVT_CCE_MASK, /*!< Command CRC error */ - kSDHC_ForceEventCommandEndBitError = SDHC_FEVT_CEBE_MASK, /*!< Command end bit error */ - kSDHC_ForceEventCommandIndexError = SDHC_FEVT_CIE_MASK, /*!< Command index error */ - kSDHC_ForceEventDataTimeout = SDHC_FEVT_DTOE_MASK, /*!< Data timeout error */ - kSDHC_ForceEventDataCrcError = SDHC_FEVT_DCE_MASK, /*!< Data CRC error */ - kSDHC_ForceEventDataEndBitError = SDHC_FEVT_DEBE_MASK, /*!< Data end bit error */ - kSDHC_ForceEventAutoCommand12Error = SDHC_FEVT_AC12E_MASK, /*!< Auto CMD12 error */ - kSDHC_ForceEventCardInt = SDHC_FEVT_CINT_MASK, /*!< Card interrupt */ - kSDHC_ForceEventDmaError = SDHC_FEVT_DMAE_MASK, /*!< Dma error */ - - kSDHC_ForceEventsAll = - (kSDHC_ForceEventAutoCommand12NotExecuted | kSDHC_ForceEventAutoCommand12Timeout | - kSDHC_ForceEventAutoCommand12CrcError | kSDHC_ForceEventEndBitError | kSDHC_ForceEventAutoCommand12IndexError | - kSDHC_ForceEventAutoCommand12NotIssued | kSDHC_ForceEventCommandTimeout | kSDHC_ForceEventCommandCrcError | - kSDHC_ForceEventCommandEndBitError | kSDHC_ForceEventCommandIndexError | kSDHC_ForceEventDataTimeout | - kSDHC_ForceEventDataCrcError | kSDHC_ForceEventDataEndBitError | kSDHC_ForceEventAutoCommand12Error | - kSDHC_ForceEventCardInt | kSDHC_ForceEventDmaError), /*!< All force event flags mask */ -}; - -/*! @brief Data transfer width */ -typedef enum _sdhc_data_bus_width -{ - kSDHC_DataBusWidth1Bit = 0U, /*!< 1-bit mode */ - kSDHC_DataBusWidth4Bit = 1U, /*!< 4-bit mode */ - kSDHC_DataBusWidth8Bit = 2U, /*!< 8-bit mode */ -} sdhc_data_bus_width_t; - -/*! @brief Endian mode */ -typedef enum _sdhc_endian_mode -{ - kSDHC_EndianModeBig = 0U, /*!< Big endian mode */ - kSDHC_EndianModeHalfWordBig = 1U, /*!< Half word big endian mode */ - kSDHC_EndianModeLittle = 2U, /*!< Little endian mode */ -} sdhc_endian_mode_t; - -/*! @brief DMA mode */ -typedef enum _sdhc_dma_mode -{ - kSDHC_DmaModeNo = 0U, /*!< No DMA */ - kSDHC_DmaModeAdma1 = 1U, /*!< ADMA1 is selected */ - kSDHC_DmaModeAdma2 = 2U, /*!< ADMA2 is selected */ -} sdhc_dma_mode_t; - -/*! @brief SDIO control flag mask */ -enum _sdhc_sdio_control_flag -{ - kSDHC_StopAtBlockGapFlag = 0x01, /*!< Stop at block gap */ - kSDHC_ReadWaitControlFlag = 0x02, /*!< Read wait control */ - kSDHC_InterruptAtBlockGapFlag = 0x04, /*!< Interrupt at block gap */ - kSDHC_ExactBlockNumberReadFlag = 0x08, /*!< Exact block number read */ -}; - -/*! @brief MMC card boot mode */ -typedef enum _sdhc_boot_mode -{ - kSDHC_BootModeNormal = 0U, /*!< Normal boot */ - kSDHC_BootModeAlternative = 1U, /*!< Alternative boot */ -} sdhc_boot_mode_t; - -/*! @brief The command type */ -typedef enum _sdhc_card_command_type -{ - kCARD_CommandTypeNormal = 0U, /*!< Normal command */ - kCARD_CommandTypeSuspend = 1U, /*!< Suspend command */ - kCARD_CommandTypeResume = 2U, /*!< Resume command */ - kCARD_CommandTypeAbort = 3U, /*!< Abort command */ -} sdhc_card_command_type_t; - -/*! - * @brief The command response type. - * - * Define the command response type from card to host controller. - */ -typedef enum _sdhc_card_response_type -{ - kCARD_ResponseTypeNone = 0U, /*!< Response type: none */ - kCARD_ResponseTypeR1 = 1U, /*!< Response type: R1 */ - kCARD_ResponseTypeR1b = 2U, /*!< Response type: R1b */ - kCARD_ResponseTypeR2 = 3U, /*!< Response type: R2 */ - kCARD_ResponseTypeR3 = 4U, /*!< Response type: R3 */ - kCARD_ResponseTypeR4 = 5U, /*!< Response type: R4 */ - kCARD_ResponseTypeR5 = 6U, /*!< Response type: R5 */ - kCARD_ResponseTypeR5b = 7U, /*!< Response type: R5b */ - kCARD_ResponseTypeR6 = 8U, /*!< Response type: R6 */ - kCARD_ResponseTypeR7 = 9U, /*!< Response type: R7 */ -} sdhc_card_response_type_t; - -/*! @brief The alignment size for ADDRESS filed in ADMA1's descriptor */ -#define SDHC_ADMA1_ADDRESS_ALIGN (4096U) -/*! @brief The alignment size for LENGTH field in ADMA1's descriptor */ -#define SDHC_ADMA1_LENGTH_ALIGN (4096U) -/*! @brief The alignment size for ADDRESS field in ADMA2's descriptor */ -#define SDHC_ADMA2_ADDRESS_ALIGN (4U) -/*! @brief The alignment size for LENGTH filed in ADMA2's descriptor */ -#define SDHC_ADMA2_LENGTH_ALIGN (4U) - -/* ADMA1 descriptor table - * |------------------------|---------|--------------------------| - * | Address/page field |Reserved | Attribute | - * |------------------------|---------|--------------------------| - * |31 12|11 6|05 |04 |03|02 |01 |00 | - * |------------------------|---------|----|----|--|---|---|-----| - * | address or data length | 000000 |Act2|Act1| 0|Int|End|Valid| - * |------------------------|---------|----|----|--|---|---|-----| - * - * - * |------|------|-----------------|-------|-------------| - * | Act2 | Act1 | Comment | 31-28 | 27 - 12 | - * |------|------|-----------------|---------------------| - * | 0 | 0 | No op | Don't care | - * |------|------|-----------------|-------|-------------| - * | 0 | 1 | Set data length | 0000 | Data Length | - * |------|------|-----------------|-------|-------------| - * | 1 | 0 | Transfer data | Data address | - * |------|------|-----------------|---------------------| - * | 1 | 1 | Link descriptor | Descriptor address | - * |------|------|-----------------|---------------------| - */ -/*! @brief The bit shift for ADDRESS filed in ADMA1's descriptor */ -#define SDHC_ADMA1_DESCRIPTOR_ADDRESS_SHIFT (12U) -/*! @brief The bit mask for ADDRESS field in ADMA1's descriptor */ -#define SDHC_ADMA1_DESCRIPTOR_ADDRESS_MASK (0xFFFFFU) -/*! @brief The bit shift for LENGTH filed in ADMA1's descriptor */ -#define SDHC_ADMA1_DESCRIPTOR_LENGTH_SHIFT (12U) -/*! @brief The mask for LENGTH field in ADMA1's descriptor */ -#define SDHC_ADMA1_DESCRIPTOR_LENGTH_MASK (0xFFFFU) -/*! @brief The maximum value of LENGTH filed in ADMA1's descriptor */ -#define SDHC_ADMA1_DESCRIPTOR_MAX_LENGTH_PER_ENTRY (SDHC_ADMA1_DESCRIPTOR_LENGTH_MASK + 1U) - -/*! @brief The mask for the control/status field in ADMA1 descriptor */ -enum _sdhc_adma1_descriptor_flag -{ - kSDHC_Adma1DescriptorValidFlag = (1U << 0U), /*!< Valid flag */ - kSDHC_Adma1DescriptorEndFlag = (1U << 1U), /*!< End flag */ - kSDHC_Adma1DescriptorInterrupFlag = (1U << 2U), /*!< Interrupt flag */ - kSDHC_Adma1DescriptorActivity1Flag = (1U << 4U), /*!< Activity 1 flag */ - kSDHC_Adma1DescriptorActivity2Flag = (1U << 5U), /*!< Activity 2 flag */ - kSDHC_Adma1DescriptorTypeNop = (kSDHC_Adma1DescriptorValidFlag), /*!< No operation */ - kSDHC_Adma1DescriptorTypeTransfer = - (kSDHC_Adma1DescriptorActivity2Flag | kSDHC_Adma1DescriptorValidFlag), /*!< Transfer data */ - kSDHC_Adma1DescriptorTypeLink = (kSDHC_Adma1DescriptorActivity1Flag | kSDHC_Adma1DescriptorActivity2Flag | - kSDHC_Adma1DescriptorValidFlag), /*!< Link descriptor */ - kSDHC_Adma1DescriptorTypeSetLength = - (kSDHC_Adma1DescriptorActivity1Flag | kSDHC_Adma1DescriptorValidFlag), /*!< Set data length */ -}; - -/* ADMA2 descriptor table - * |----------------|---------------|-------------|--------------------------| - * | Address field | Length | Reserved | Attribute | - * |----------------|---------------|-------------|--------------------------| - * |63 32|31 16|15 06|05 |04 |03|02 |01 |00 | - * |----------------|---------------|-------------|----|----|--|---|---|-----| - * | 32-bit address | 16-bit length | 0000000000 |Act2|Act1| 0|Int|End|Valid| - * |----------------|---------------|-------------|----|----|--|---|---|-----| - * - * - * | Act2 | Act1 | Comment | Operation | - * |------|------|-----------------|-------------------------------------------------------------------| - * | 0 | 0 | No op | Don't care | - * |------|------|-----------------|-------------------------------------------------------------------| - * | 0 | 1 | Reserved | Read this line and go to next one | - * |------|------|-----------------|-------------------------------------------------------------------| - * | 1 | 0 | Transfer data | Transfer data with address and length set in this descriptor line | - * |------|------|-----------------|-------------------------------------------------------------------| - * | 1 | 1 | Link descriptor | Link to another descriptor | - * |------|------|-----------------|-------------------------------------------------------------------| - */ -/*! @brief The bit shift for LENGTH field in ADMA2's descriptor */ -#define SDHC_ADMA2_DESCRIPTOR_LENGTH_SHIFT (16U) -/*! @brief The bit mask for LENGTH field in ADMA2's descriptor */ -#define SDHC_ADMA2_DESCRIPTOR_LENGTH_MASK (0xFFFFU) -/*! @brief The maximum value of LENGTH field in ADMA2's descriptor */ -#define SDHC_ADMA2_DESCRIPTOR_MAX_LENGTH_PER_ENTRY (SDHC_ADMA2_DESCRIPTOR_LENGTH_MASK) - -/*! @brief ADMA1 descriptor control and status mask */ -enum _sdhc_adma2_descriptor_flag -{ - kSDHC_Adma2DescriptorValidFlag = (1U << 0U), /*!< Valid flag */ - kSDHC_Adma2DescriptorEndFlag = (1U << 1U), /*!< End flag */ - kSDHC_Adma2DescriptorInterruptFlag = (1U << 2U), /*!< Interrupt flag */ - kSDHC_Adma2DescriptorActivity1Flag = (1U << 4U), /*!< Activity 1 mask */ - kSDHC_Adma2DescriptorActivity2Flag = (1U << 5U), /*!< Activity 2 mask */ - - kSDHC_Adma2DescriptorTypeNop = (kSDHC_Adma2DescriptorValidFlag), /*!< No operation */ - kSDHC_Adma2DescriptorTypeReserved = - (kSDHC_Adma2DescriptorActivity1Flag | kSDHC_Adma2DescriptorValidFlag), /*!< Reserved */ - kSDHC_Adma2DescriptorTypeTransfer = - (kSDHC_Adma2DescriptorActivity2Flag | kSDHC_Adma2DescriptorValidFlag), /*!< Transfer type */ - kSDHC_Adma2DescriptorTypeLink = (kSDHC_Adma2DescriptorActivity1Flag | kSDHC_Adma2DescriptorActivity2Flag | - kSDHC_Adma2DescriptorValidFlag), /*!< Link type */ -}; - -/*! @brief Defines the adma1 descriptor structure. */ -typedef uint32_t sdhc_adma1_descriptor_t; - -/*! @brief Defines the ADMA2 descriptor structure. */ -typedef struct _sdhc_adma2_descriptor -{ - uint32_t attribute; /*!< The control and status field */ - const uint32_t *address; /*!< The address field */ -} sdhc_adma2_descriptor_t; - -/*! - * @brief SDHC capability information. - * - * Defines a structure to save the capability information of SDHC. - */ -typedef struct _sdhc_capability -{ - uint32_t specVersion; /*!< Specification version */ - uint32_t vendorVersion; /*!< Vendor version */ - uint32_t maxBlockLength; /*!< Maximum block length united as byte */ - uint32_t maxBlockCount; /*!< Maximum block count can be set one time */ - uint32_t flags; /*!< Capability flags to indicate the support information(_sdhc_capability_flag) */ -} sdhc_capability_t; - -/*! @brief Card transfer configuration. - * - * Define structure to configure the transfer-related command index/argument/flags and data block - * size/data block numbers. This structure needs to be filled each time a command is sent to the card. - */ -typedef struct _sdhc_transfer_config -{ - size_t dataBlockSize; /*!< Data block size */ - uint32_t dataBlockCount; /*!< Data block count */ - uint32_t commandArgument; /*!< Command argument */ - uint32_t commandIndex; /*!< Command index */ - uint32_t flags; /*!< Transfer flags(_sdhc_transfer_flag) */ -} sdhc_transfer_config_t; - -/*! @brief Data structure to configure the MMC boot feature */ -typedef struct _sdhc_boot_config -{ - uint32_t ackTimeoutCount; /*!< Timeout value for the boot ACK. The available range is 0 ~ 15. */ - sdhc_boot_mode_t bootMode; /*!< Boot mode selection. */ - uint32_t blockCount; /*!< Stop at block gap value of automatic mode. Available range is 0 ~ 65535. */ - bool enableBootAck; /*!< Enable or disable boot ACK */ - bool enableBoot; /*!< Enable or disable fast boot */ - bool enableAutoStopAtBlockGap; /*!< Enable or disable auto stop at block gap function in boot period */ -} sdhc_boot_config_t; - -/*! @brief Data structure to initialize the SDHC */ -typedef struct _sdhc_config -{ - bool cardDetectDat3; /*!< Enable DAT3 as card detection pin */ - sdhc_endian_mode_t endianMode; /*!< Endian mode */ - sdhc_dma_mode_t dmaMode; /*!< DMA mode */ - uint32_t readWatermarkLevel; /*!< Watermark level for DMA read operation. Available range is 1 ~ 128. */ - uint32_t writeWatermarkLevel; /*!< Watermark level for DMA write operation. Available range is 1 ~ 128. */ -} sdhc_config_t; - -/*! - * @brief Card data descriptor - * - * Defines a structure to contain data-related attribute. 'enableIgnoreError' is used for the case that upper card - * driver - * want to ignore the error event to read/write all the data not to stop read/write immediately when error event - * happen for example bus testing procedure for MMC card. - */ -typedef struct _sdhc_data -{ - bool enableAutoCommand12; /*!< Enable auto CMD12 */ - bool enableIgnoreError; /*!< Enable to ignore error event to read/write all the data */ - size_t blockSize; /*!< Block size */ - uint32_t blockCount; /*!< Block count */ - uint32_t *rxData; /*!< Buffer to save data read */ - const uint32_t *txData; /*!< Data buffer to write */ -} sdhc_data_t; - -/*! - * @brief Card command descriptor - * - * Define card command-related attribute. - */ -typedef struct _sdhc_command -{ - uint32_t index; /*!< Command index */ - uint32_t argument; /*!< Command argument */ - sdhc_card_command_type_t type; /*!< Command type */ - sdhc_card_response_type_t responseType; /*!< Command response type */ - uint32_t response[4U]; /*!< Response for this command */ - uint32_t responseErrorFlags; /*!< response error flag, the flag which need to check - the command reponse*/ -} sdhc_command_t; - -/*! @brief Transfer state */ -typedef struct _sdhc_transfer -{ - sdhc_data_t *data; /*!< Data to transfer */ - sdhc_command_t *command; /*!< Command to send */ -} sdhc_transfer_t; - -/*! @brief SDHC handle typedef */ -typedef struct _sdhc_handle sdhc_handle_t; - -/*! @brief SDHC callback functions. */ -typedef struct _sdhc_transfer_callback -{ - void (*CardInserted)(void); /*!< Card inserted occurs when DAT3/CD pin is for card detect */ - void (*CardRemoved)(void); /*!< Card removed occurs */ - void (*SdioInterrupt)(void); /*!< SDIO card interrupt occurs */ - void (*SdioBlockGap)(void); /*!< SDIO card stopped at block gap occurs */ - void (*TransferComplete)(SDHC_Type *base, - sdhc_handle_t *handle, - status_t status, - void *userData); /*!< Transfer complete callback */ -} sdhc_transfer_callback_t; - -/*! - * @brief SDHC handle - * - * Defines the structure to save the SDHC state information and callback function. The detailed interrupt status when - * sending a command or transfering data can be obtained from the interruptFlags field by using the mask defined in - * sdhc_interrupt_flag_t. - * - * @note All the fields except interruptFlags and transferredWords must be allocated by the user. - */ -struct _sdhc_handle -{ - /* Transfer parameter */ - sdhc_data_t *volatile data; /*!< Data to transfer */ - sdhc_command_t *volatile command; /*!< Command to send */ - - /* Transfer status */ - volatile uint32_t interruptFlags; /*!< Interrupt flags of last transaction */ - volatile uint32_t transferredWords; /*!< Words transferred by DATAPORT way */ - - /* Callback functions */ - sdhc_transfer_callback_t callback; /*!< Callback function */ - void *userData; /*!< Parameter for transfer complete callback */ -}; - -/*! @brief SDHC transfer function. */ -typedef status_t (*sdhc_transfer_function_t)(SDHC_Type *base, sdhc_transfer_t *content); - -/*! @brief SDHC host descriptor */ -typedef struct _sdhc_host -{ - SDHC_Type *base; /*!< SDHC peripheral base address */ - uint32_t sourceClock_Hz; /*!< SDHC source clock frequency united in Hz */ - sdhc_config_t config; /*!< SDHC configuration */ - sdhc_capability_t capability; /*!< SDHC capability information */ - sdhc_transfer_function_t transfer; /*!< SDHC transfer function */ -} sdhc_host_t; - -/************************************************************************************************* - * API - ************************************************************************************************/ -#if defined(__cplusplus) -extern "C" { -#endif - -/*! - * @name Initialization and deinitialization - * @{ - */ - -/*! - * @brief SDHC module initialization function. - * - * Configures the SDHC according to the user configuration. - * - * Example: - @code - sdhc_config_t config; - config.cardDetectDat3 = false; - config.endianMode = kSDHC_EndianModeLittle; - config.dmaMode = kSDHC_DmaModeAdma2; - config.readWatermarkLevel = 128U; - config.writeWatermarkLevel = 128U; - SDHC_Init(SDHC, &config); - @endcode - * - * @param base SDHC peripheral base address. - * @param config SDHC configuration information. - * @retval kStatus_Success Operate successfully. - */ -void SDHC_Init(SDHC_Type *base, const sdhc_config_t *config); - -/*! - * @brief Deinitializes the SDHC. - * - * @param base SDHC peripheral base address. - */ -void SDHC_Deinit(SDHC_Type *base); - -/*! - * @brief Resets the SDHC. - * - * @param base SDHC peripheral base address. - * @param mask The reset type mask(_sdhc_reset). - * @param timeout Timeout for reset. - * @retval true Reset successfully. - * @retval false Reset failed. - */ -bool SDHC_Reset(SDHC_Type *base, uint32_t mask, uint32_t timeout); - -/* @} */ - -/*! - * @name DMA Control - * @{ - */ - -/*! - * @brief Sets the ADMA descriptor table configuration. - * - * @param base SDHC peripheral base address. - * @param dmaMode DMA mode. - * @param table ADMA table address. - * @param tableWords ADMA table buffer length united as Words. - * @param data Data buffer address. - * @param dataBytes Data length united as bytes. - * @retval kStatus_OutOfRange ADMA descriptor table length isn't enough to describe data. - * @retval kStatus_Success Operate successfully. - */ -status_t SDHC_SetAdmaTableConfig(SDHC_Type *base, - sdhc_dma_mode_t dmaMode, - uint32_t *table, - uint32_t tableWords, - const uint32_t *data, - uint32_t dataBytes); - -/* @} */ - -/*! - * @name Interrupts - * @{ - */ - -/*! - * @brief Enables the interrupt status. - * - * @param base SDHC peripheral base address. - * @param mask Interrupt status flags mask(_sdhc_interrupt_status_flag). - */ -static inline void SDHC_EnableInterruptStatus(SDHC_Type *base, uint32_t mask) -{ - base->IRQSTATEN |= mask; -} - -/*! - * @brief Disables the interrupt status. - * - * @param base SDHC peripheral base address. - * @param mask The interrupt status flags mask(_sdhc_interrupt_status_flag). - */ -static inline void SDHC_DisableInterruptStatus(SDHC_Type *base, uint32_t mask) -{ - base->IRQSTATEN &= ~mask; -} - -/*! - * @brief Enables the interrupt signal corresponding to the interrupt status flag. - * - * @param base SDHC peripheral base address. - * @param mask The interrupt status flags mask(_sdhc_interrupt_status_flag). - */ -static inline void SDHC_EnableInterruptSignal(SDHC_Type *base, uint32_t mask) -{ - base->IRQSIGEN |= mask; -} - -/*! - * @brief Disables the interrupt signal corresponding to the interrupt status flag. - * - * @param base SDHC peripheral base address. - * @param mask The interrupt status flags mask(_sdhc_interrupt_status_flag). - */ -static inline void SDHC_DisableInterruptSignal(SDHC_Type *base, uint32_t mask) -{ - base->IRQSIGEN &= ~mask; -} - -/* @} */ - -/*! - * @name Status - * @{ - */ - -/*! - * @brief Gets the current interrupt status. - * - * @param base SDHC peripheral base address. - * @return Current interrupt status flags mask(_sdhc_interrupt_status_flag). - */ -static inline uint32_t SDHC_GetInterruptStatusFlags(SDHC_Type *base) -{ - return base->IRQSTAT; -} - -/*! - * @brief Clears a specified interrupt status. - * - * @param base SDHC peripheral base address. - * @param mask The interrupt status flags mask(_sdhc_interrupt_status_flag). - */ -static inline void SDHC_ClearInterruptStatusFlags(SDHC_Type *base, uint32_t mask) -{ - base->IRQSTAT = mask; -} - -/*! - * @brief Gets the status of auto command 12 error. - * - * @param base SDHC peripheral base address. - * @return Auto command 12 error status flags mask(_sdhc_auto_command12_error_status_flag). - */ -static inline uint32_t SDHC_GetAutoCommand12ErrorStatusFlags(SDHC_Type *base) -{ - return base->AC12ERR; -} - -/*! - * @brief Gets the status of the ADMA error. - * - * @param base SDHC peripheral base address. - * @return ADMA error status flags mask(_sdhc_adma_error_status_flag). - */ -static inline uint32_t SDHC_GetAdmaErrorStatusFlags(SDHC_Type *base) -{ - return base->ADMAES; -} - -/*! - * @brief Gets a present status. - * - * This function gets the present SDHC's status except for an interrupt status and an error status. - * - * @param base SDHC peripheral base address. - * @return Present SDHC's status flags mask(_sdhc_present_status_flag). - */ -static inline uint32_t SDHC_GetPresentStatusFlags(SDHC_Type *base) -{ - return base->PRSSTAT; -} - -/* @} */ - -/*! - * @name Bus Operations - * @{ - */ - -/*! - * @brief Gets the capability information. - * - * @param base SDHC peripheral base address. - * @param capability Structure to save capability information. - */ -void SDHC_GetCapability(SDHC_Type *base, sdhc_capability_t *capability); - -/*! - * @brief Enables or disables the SD bus clock. - * - * @param base SDHC peripheral base address. - * @param enable True to enable, false to disable. - */ -static inline void SDHC_EnableSdClock(SDHC_Type *base, bool enable) -{ - if (enable) - { - base->SYSCTL |= SDHC_SYSCTL_SDCLKEN_MASK; - } - else - { - base->SYSCTL &= ~SDHC_SYSCTL_SDCLKEN_MASK; - } -} - -/*! - * @brief Sets the SD bus clock frequency. - * - * @param base SDHC peripheral base address. - * @param srcClock_Hz SDHC source clock frequency united in Hz. - * @param busClock_Hz SD bus clock frequency united in Hz. - * - * @return The nearest frequency of busClock_Hz configured to SD bus. - */ -uint32_t SDHC_SetSdClock(SDHC_Type *base, uint32_t srcClock_Hz, uint32_t busClock_Hz); - -/*! - * @brief Sends 80 clocks to the card to set it to the active state. - * - * This function must be called each time the card is inserted to ensure that the card can receive the command - * correctly. - * - * @param base SDHC peripheral base address. - * @param timeout Timeout to initialize card. - * @retval true Set card active successfully. - * @retval false Set card active failed. - */ -bool SDHC_SetCardActive(SDHC_Type *base, uint32_t timeout); - -/*! - * @brief Sets the data transfer width. - * - * @param base SDHC peripheral base address. - * @param width Data transfer width. - */ -static inline void SDHC_SetDataBusWidth(SDHC_Type *base, sdhc_data_bus_width_t width) -{ - base->PROCTL = ((base->PROCTL & ~SDHC_PROCTL_DTW_MASK) | SDHC_PROCTL_DTW(width)); -} - -/*! - * @brief Sets the card transfer-related configuration. - * - * This function fills the card transfer-related command argument/transfer flag/data size. The command and data are sent - by - * SDHC after calling this function. - * - * Example: - @code - sdhc_transfer_config_t transferConfig; - transferConfig.dataBlockSize = 512U; - transferConfig.dataBlockCount = 2U; - transferConfig.commandArgument = 0x01AAU; - transferConfig.commandIndex = 8U; - transferConfig.flags |= (kSDHC_EnableDmaFlag | kSDHC_EnableAutoCommand12Flag | kSDHC_MultipleBlockFlag); - SDHC_SetTransferConfig(SDHC, &transferConfig); - @endcode - * - * @param base SDHC peripheral base address. - * @param config Command configuration structure. - */ -void SDHC_SetTransferConfig(SDHC_Type *base, const sdhc_transfer_config_t *config); - -/*! - * @brief Gets the command response. - * - * @param base SDHC peripheral base address. - * @param index The index of response register, range from 0 to 3. - * @return Response register transfer. - */ -static inline uint32_t SDHC_GetCommandResponse(SDHC_Type *base, uint32_t index) -{ - assert(index < 4U); - - return base->CMDRSP[index]; -} - -/*! - * @brief Fills the the data port. - * - * This function is used to implement the data transfer by Data Port instead of DMA. - * - * @param base SDHC peripheral base address. - * @param data The data about to be sent. - */ -static inline void SDHC_WriteData(SDHC_Type *base, uint32_t data) -{ - base->DATPORT = data; -} - -/*! - * @brief Retrieves the data from the data port. - * - * This function is used to implement the data transfer by Data Port instead of DMA. - * - * @param base SDHC peripheral base address. - * @return The data has been read. - */ -static inline uint32_t SDHC_ReadData(SDHC_Type *base) -{ - return base->DATPORT; -} - -/*! - * @brief Enables or disables a wakeup event in low-power mode. - * - * @param base SDHC peripheral base address. - * @param mask Wakeup events mask(_sdhc_wakeup_event). - * @param enable True to enable, false to disable. - */ -static inline void SDHC_EnableWakeupEvent(SDHC_Type *base, uint32_t mask, bool enable) -{ - if (enable) - { - base->PROCTL |= mask; - } - else - { - base->PROCTL &= ~mask; - } -} - -/*! - * @brief Enables or disables the card detection level for testing. - * - * @param base SDHC peripheral base address. - * @param enable True to enable, false to disable. - */ -static inline void SDHC_EnableCardDetectTest(SDHC_Type *base, bool enable) -{ - if (enable) - { - base->PROCTL |= SDHC_PROCTL_CDSS_MASK; - } - else - { - base->PROCTL &= ~SDHC_PROCTL_CDSS_MASK; - } -} - -/*! - * @brief Sets the card detection test level. - * - * This function sets the card detection test level to indicate whether the card is inserted into the SDHC when DAT[3]/ - * CD pin is selected as a card detection pin. This function can also assert the pin logic when DAT[3]/CD pin is - * selected - * as the card detection pin. - * - * @param base SDHC peripheral base address. - * @param high True to set the card detect level to high. - */ -static inline void SDHC_SetCardDetectTestLevel(SDHC_Type *base, bool high) -{ - if (high) - { - base->PROCTL |= SDHC_PROCTL_CDTL_MASK; - } - else - { - base->PROCTL &= ~SDHC_PROCTL_CDTL_MASK; - } -} - -/*! - * @brief Enables or disables the SDIO card control. - * - * @param base SDHC peripheral base address. - * @param mask SDIO card control flags mask(_sdhc_sdio_control_flag). - * @param enable True to enable, false to disable. - */ -void SDHC_EnableSdioControl(SDHC_Type *base, uint32_t mask, bool enable); - -/*! - * @brief Restarts a transaction which has stopped at the block GAP for the SDIO card. - * - * @param base SDHC peripheral base address. - */ -static inline void SDHC_SetContinueRequest(SDHC_Type *base) -{ - base->PROCTL |= SDHC_PROCTL_CREQ_MASK; -} - -/*! - * @brief Configures the MMC boot feature. - * - * Example: - @code - sdhc_boot_config_t config; - config.ackTimeoutCount = 4; - config.bootMode = kSDHC_BootModeNormal; - config.blockCount = 5; - config.enableBootAck = true; - config.enableBoot = true; - config.enableAutoStopAtBlockGap = true; - SDHC_SetMmcBootConfig(SDHC, &config); - @endcode - * - * @param base SDHC peripheral base address. - * @param config The MMC boot configuration information. - */ -void SDHC_SetMmcBootConfig(SDHC_Type *base, const sdhc_boot_config_t *config); - -/*! - * @brief Forces generating events according to the given mask. - * - * @param base SDHC peripheral base address. - * @param mask The force events mask(_sdhc_force_event). - */ -static inline void SDHC_SetForceEvent(SDHC_Type *base, uint32_t mask) -{ - base->FEVT = mask; -} - -/* @} */ - -/*! - * @name Transactional - * @{ - */ - -/*! - * @brief Transfers the command/data using a blocking method. - * - * This function waits until the command response/data is received or the SDHC encounters an error by polling the status - * flag. - * This function support non word align data addr transfer support, if data buffer addr is not align in DMA mode, - * the API will continue finish the transfer by polling IO directly - * The application must not call this API in multiple threads at the same time. Because of that this API doesn't support - * the re-entry mechanism. - * - * @note There is no need to call the API 'SDHC_TransferCreateHandle' when calling this API. - * - * @param base SDHC peripheral base address. - * @param admaTable ADMA table address, can't be null if transfer way is ADMA1/ADMA2. - * @param admaTableWords ADMA table length united as words, can't be 0 if transfer way is ADMA1/ADMA2. - * @param transfer Transfer content. - * @retval kStatus_InvalidArgument Argument is invalid. - * @retval kStatus_SDHC_PrepareAdmaDescriptorFailed Prepare ADMA descriptor failed. - * @retval kStatus_SDHC_SendCommandFailed Send command failed. - * @retval kStatus_SDHC_TransferDataFailed Transfer data failed. - * @retval kStatus_Success Operate successfully. - */ -status_t SDHC_TransferBlocking(SDHC_Type *base, - uint32_t *admaTable, - uint32_t admaTableWords, - sdhc_transfer_t *transfer); - -/*! - * @brief Creates the SDHC handle. - * - * @param base SDHC peripheral base address. - * @param handle SDHC handle pointer. - * @param callback Structure pointer to contain all callback functions. - * @param userData Callback function parameter. - */ -void SDHC_TransferCreateHandle(SDHC_Type *base, - sdhc_handle_t *handle, - const sdhc_transfer_callback_t *callback, - void *userData); - -/*! - * @brief Transfers the command/data using an interrupt and an asynchronous method. - * - * This function sends a command and data and returns immediately. It doesn't wait the transfer complete or encounter an - * error. - * This function support non word align data addr transfer support, if data buffer addr is not align in DMA mode, - * the API will continue finish the transfer by polling IO directly - * The application must not call this API in multiple threads at the same time. Because of that this API doesn't support - * the re-entry mechanism. - * - * @note Call the API 'SDHC_TransferCreateHandle' when calling this API. - * - * @param base SDHC peripheral base address. - * @param handle SDHC handle. - * @param admaTable ADMA table address, can't be null if transfer way is ADMA1/ADMA2. - * @param admaTableWords ADMA table length united as words, can't be 0 if transfer way is ADMA1/ADMA2. - * @param transfer Transfer content. - * @retval kStatus_InvalidArgument Argument is invalid. - * @retval kStatus_SDHC_BusyTransferring Busy transferring. - * @retval kStatus_SDHC_PrepareAdmaDescriptorFailed Prepare ADMA descriptor failed. - * @retval kStatus_Success Operate successfully. - */ -status_t SDHC_TransferNonBlocking( - SDHC_Type *base, sdhc_handle_t *handle, uint32_t *admaTable, uint32_t admaTableWords, sdhc_transfer_t *transfer); - -/*! - * @brief IRQ handler for the SDHC. - * - * This function deals with the IRQs on the given host controller. - * - * @param base SDHC peripheral base address. - * @param handle SDHC handle. - */ -void SDHC_TransferHandleIRQ(SDHC_Type *base, sdhc_handle_t *handle); - -/* @} */ - -#if defined(__cplusplus) -} -#endif -/*! @} */ - -#endif /* _FSL_SDHC_H_*/ diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_sim.c b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_sim.c deleted file mode 100644 index ade512f0306..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_sim.c +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "fsl_sim.h" - -/******************************************************************************* - * Codes - ******************************************************************************/ -#if (defined(FSL_FEATURE_SIM_OPT_HAS_USB_VOLTAGE_REGULATOR) && FSL_FEATURE_SIM_OPT_HAS_USB_VOLTAGE_REGULATOR) -void SIM_SetUsbVoltRegulatorEnableMode(uint32_t mask) -{ - SIM->SOPT1CFG |= (SIM_SOPT1CFG_URWE_MASK | SIM_SOPT1CFG_UVSWE_MASK | SIM_SOPT1CFG_USSWE_MASK); - - SIM->SOPT1 = (SIM->SOPT1 & ~kSIM_UsbVoltRegEnableInAllModes) | mask; -} -#endif /* FSL_FEATURE_SIM_OPT_HAS_USB_VOLTAGE_REGULATOR */ - -void SIM_GetUniqueId(sim_uid_t *uid) -{ -#if defined(SIM_UIDH) - uid->H = SIM->UIDH; -#endif - uid->MH = SIM->UIDMH; - uid->ML = SIM->UIDML; - uid->L = SIM->UIDL; -} diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_sim.h b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_sim.h deleted file mode 100644 index 0a0e4fb3092..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_sim.h +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef _FSL_SIM_H_ -#define _FSL_SIM_H_ - -#include "fsl_common.h" - -/*! @addtogroup sim */ -/*! @{*/ - - -/******************************************************************************* - * Definitions - *******************************************************************************/ - -/*! @name Driver version */ -/*@{*/ -#define FSL_SIM_DRIVER_VERSION (MAKE_VERSION(2, 0, 0)) /*!< Driver version 2.0.0 */ -/*@}*/ - -#if (defined(FSL_FEATURE_SIM_OPT_HAS_USB_VOLTAGE_REGULATOR) && FSL_FEATURE_SIM_OPT_HAS_USB_VOLTAGE_REGULATOR) -/*!@brief USB voltage regulator enable setting. */ -enum _sim_usb_volt_reg_enable_mode -{ - kSIM_UsbVoltRegEnable = SIM_SOPT1_USBREGEN_MASK, /*!< Enable voltage regulator. */ - kSIM_UsbVoltRegEnableInLowPower = SIM_SOPT1_USBVSTBY_MASK, /*!< Enable voltage regulator in VLPR/VLPW modes. */ - kSIM_UsbVoltRegEnableInStop = SIM_SOPT1_USBSSTBY_MASK, /*!< Enable voltage regulator in STOP/VLPS/LLS/VLLS modes. */ - kSIM_UsbVoltRegEnableInAllModes = SIM_SOPT1_USBREGEN_MASK | SIM_SOPT1_USBSSTBY_MASK | - SIM_SOPT1_USBVSTBY_MASK /*!< Enable voltage regulator in all power modes. */ -}; -#endif /* (defined(FSL_FEATURE_SIM_OPT_HAS_USB_VOLTAGE_REGULATOR) && FSL_FEATURE_SIM_OPT_HAS_USB_VOLTAGE_REGULATOR) */ - -/*!@brief Unique ID. */ -typedef struct _sim_uid -{ -#if defined(SIM_UIDH) - uint32_t H; /*!< UIDH. */ -#endif - uint32_t MH; /*!< UIDMH. */ - uint32_t ML; /*!< UIDML. */ - uint32_t L; /*!< UIDL. */ -} sim_uid_t; - -/*!@brief Flash enable mode. */ -enum _sim_flash_mode -{ - kSIM_FlashDisableInWait = SIM_FCFG1_FLASHDOZE_MASK, /*!< Disable flash in wait mode. */ - kSIM_FlashDisable = SIM_FCFG1_FLASHDIS_MASK /*!< Disable flash in normal mode. */ -}; - -/******************************************************************************* - * API - ******************************************************************************/ - -#if defined(__cplusplus) -extern "C" { -#endif /* __cplusplus*/ - -#if (defined(FSL_FEATURE_SIM_OPT_HAS_USB_VOLTAGE_REGULATOR) && FSL_FEATURE_SIM_OPT_HAS_USB_VOLTAGE_REGULATOR) -/*! - * @brief Sets the USB voltage regulator setting. - * - * This function configures whether the USB voltage regulator is enabled in - * normal RUN mode, STOP/VLPS/LLS/VLLS modes, and VLPR/VLPW modes. The configurations - * are passed in as mask value of \ref _sim_usb_volt_reg_enable_mode. For example, to enable - * USB voltage regulator in RUN/VLPR/VLPW modes and disable in STOP/VLPS/LLS/VLLS mode, - * use: - * - * SIM_SetUsbVoltRegulatorEnableMode(kSIM_UsbVoltRegEnable | kSIM_UsbVoltRegEnableInLowPower); - * - * @param mask USB voltage regulator enable setting. - */ -void SIM_SetUsbVoltRegulatorEnableMode(uint32_t mask); -#endif /* FSL_FEATURE_SIM_OPT_HAS_USB_VOLTAGE_REGULATOR */ - -/*! - * @brief Gets the unique identification register value. - * - * @param uid Pointer to the structure to save the UID value. - */ -void SIM_GetUniqueId(sim_uid_t *uid); - -/*! - * @brief Sets the flash enable mode. - * - * @param mode The mode to set; see \ref _sim_flash_mode for mode details. - */ -static inline void SIM_SetFlashMode(uint8_t mode) -{ - SIM->FCFG1 = mode; -} - -#if defined(__cplusplus) -} -#endif /* __cplusplus*/ - -/*! @}*/ - -#endif /* _FSL_SIM_H_ */ diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_smc.c b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_smc.c deleted file mode 100644 index dacf193476c..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_smc.c +++ /dev/null @@ -1,400 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "fsl_smc.h" -#include "fsl_flash.h" - -#if (defined(FSL_FEATURE_SMC_HAS_PARAM) && FSL_FEATURE_SMC_HAS_PARAM) -void SMC_GetParam(SMC_Type *base, smc_param_t *param) -{ - uint32_t reg = base->PARAM; - param->hsrunEnable = (bool)(reg & SMC_PARAM_EHSRUN_MASK); - param->llsEnable = (bool)(reg & SMC_PARAM_ELLS_MASK); - param->lls2Enable = (bool)(reg & SMC_PARAM_ELLS2_MASK); - param->vlls0Enable = (bool)(reg & SMC_PARAM_EVLLS0_MASK); -} -#endif /* FSL_FEATURE_SMC_HAS_PARAM */ - -void SMC_PreEnterStopModes(void) -{ - flash_prefetch_speculation_status_t speculationStatus = - { - kFLASH_prefetchSpeculationOptionDisable, /* Disable instruction speculation.*/ - kFLASH_prefetchSpeculationOptionDisable, /* Disable data speculation.*/ - }; - - __disable_irq(); - __ISB(); - - /* - * Before enter stop modes, the flash cache prefetch should be disabled. - * Otherwise the prefetch might be interrupted by stop, then the data and - * and instruction from flash are wrong. - */ - FLASH_PflashSetPrefetchSpeculation(&speculationStatus); -} - -void SMC_PostExitStopModes(void) -{ - flash_prefetch_speculation_status_t speculationStatus = - { - kFLASH_prefetchSpeculationOptionEnable, /* Enable instruction speculation.*/ - kFLASH_prefetchSpeculationOptionEnable, /* Enable data speculation.*/ - }; - - FLASH_PflashSetPrefetchSpeculation(&speculationStatus); - - __enable_irq(); - __ISB(); -} - -status_t SMC_SetPowerModeRun(SMC_Type *base) -{ - uint8_t reg; - - reg = base->PMCTRL; - /* configure Normal RUN mode */ - reg &= ~SMC_PMCTRL_RUNM_MASK; - reg |= (kSMC_RunNormal << SMC_PMCTRL_RUNM_SHIFT); - base->PMCTRL = reg; - - return kStatus_Success; -} - -#if (defined(FSL_FEATURE_SMC_HAS_HIGH_SPEED_RUN_MODE) && FSL_FEATURE_SMC_HAS_HIGH_SPEED_RUN_MODE) -status_t SMC_SetPowerModeHsrun(SMC_Type *base) -{ - uint8_t reg; - - reg = base->PMCTRL; - /* configure High Speed RUN mode */ - reg &= ~SMC_PMCTRL_RUNM_MASK; - reg |= (kSMC_Hsrun << SMC_PMCTRL_RUNM_SHIFT); - base->PMCTRL = reg; - - return kStatus_Success; -} -#endif /* FSL_FEATURE_SMC_HAS_HIGH_SPEED_RUN_MODE */ - -status_t SMC_SetPowerModeWait(SMC_Type *base) -{ - /* configure Normal Wait mode */ - SCB->SCR &= ~SCB_SCR_SLEEPDEEP_Msk; - __DSB(); - __WFI(); - __ISB(); - - return kStatus_Success; -} - -status_t SMC_SetPowerModeStop(SMC_Type *base, smc_partial_stop_option_t option) -{ - uint8_t reg; - -#if (defined(FSL_FEATURE_SMC_HAS_PSTOPO) && FSL_FEATURE_SMC_HAS_PSTOPO) - /* configure the Partial Stop mode in Noraml Stop mode */ - reg = base->STOPCTRL; - reg &= ~SMC_STOPCTRL_PSTOPO_MASK; - reg |= ((uint32_t)option << SMC_STOPCTRL_PSTOPO_SHIFT); - base->STOPCTRL = reg; -#endif - - /* configure Normal Stop mode */ - reg = base->PMCTRL; - reg &= ~SMC_PMCTRL_STOPM_MASK; - reg |= (kSMC_StopNormal << SMC_PMCTRL_STOPM_SHIFT); - base->PMCTRL = reg; - - /* Set the SLEEPDEEP bit to enable deep sleep mode (stop mode) */ - SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk; - - /* read back to make sure the configuration valid before enter stop mode */ - (void)base->PMCTRL; - __DSB(); - __WFI(); - __ISB(); - - /* check whether the power mode enter Stop mode succeed */ - if (base->PMCTRL & SMC_PMCTRL_STOPA_MASK) - { - return kStatus_SMC_StopAbort; - } - else - { - return kStatus_Success; - } -} - -status_t SMC_SetPowerModeVlpr(SMC_Type *base -#if (defined(FSL_FEATURE_SMC_HAS_LPWUI) && FSL_FEATURE_SMC_HAS_LPWUI) - , - bool wakeupMode -#endif - ) -{ - uint8_t reg; - - reg = base->PMCTRL; -#if (defined(FSL_FEATURE_SMC_HAS_LPWUI) && FSL_FEATURE_SMC_HAS_LPWUI) - /* configure whether the system remains in VLP mode on an interrupt */ - if (wakeupMode) - { - /* exits to RUN mode on an interrupt */ - reg |= SMC_PMCTRL_LPWUI_MASK; - } - else - { - /* remains in VLP mode on an interrupt */ - reg &= ~SMC_PMCTRL_LPWUI_MASK; - } -#endif /* FSL_FEATURE_SMC_HAS_LPWUI */ - - /* configure VLPR mode */ - reg &= ~SMC_PMCTRL_RUNM_MASK; - reg |= (kSMC_RunVlpr << SMC_PMCTRL_RUNM_SHIFT); - base->PMCTRL = reg; - - return kStatus_Success; -} - -status_t SMC_SetPowerModeVlpw(SMC_Type *base) -{ - /* configure VLPW mode */ - /* Set the SLEEPDEEP bit to enable deep sleep mode */ - SCB->SCR &= ~SCB_SCR_SLEEPDEEP_Msk; - __DSB(); - __WFI(); - __ISB(); - - return kStatus_Success; -} - -status_t SMC_SetPowerModeVlps(SMC_Type *base) -{ - uint8_t reg; - - /* configure VLPS mode */ - reg = base->PMCTRL; - reg &= ~SMC_PMCTRL_STOPM_MASK; - reg |= (kSMC_StopVlps << SMC_PMCTRL_STOPM_SHIFT); - base->PMCTRL = reg; - - /* Set the SLEEPDEEP bit to enable deep sleep mode */ - SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk; - - /* read back to make sure the configuration valid before enter stop mode */ - (void)base->PMCTRL; - __DSB(); - __WFI(); - __ISB(); - - /* check whether the power mode enter VLPS mode succeed */ - if (base->PMCTRL & SMC_PMCTRL_STOPA_MASK) - { - return kStatus_SMC_StopAbort; - } - else - { - return kStatus_Success; - } -} - -#if (defined(FSL_FEATURE_SMC_HAS_LOW_LEAKAGE_STOP_MODE) && FSL_FEATURE_SMC_HAS_LOW_LEAKAGE_STOP_MODE) -status_t SMC_SetPowerModeLls(SMC_Type *base -#if ((defined(FSL_FEATURE_SMC_HAS_LLS_SUBMODE) && FSL_FEATURE_SMC_HAS_LLS_SUBMODE) || \ - (defined(FSL_FEATURE_SMC_HAS_LPOPO) && FSL_FEATURE_SMC_HAS_LPOPO)) - , - const smc_power_mode_lls_config_t *config -#endif - ) -{ - uint8_t reg; - - /* configure to LLS mode */ - reg = base->PMCTRL; - reg &= ~SMC_PMCTRL_STOPM_MASK; - reg |= (kSMC_StopLls << SMC_PMCTRL_STOPM_SHIFT); - base->PMCTRL = reg; - -/* configure LLS sub-mode*/ -#if (defined(FSL_FEATURE_SMC_HAS_LLS_SUBMODE) && FSL_FEATURE_SMC_HAS_LLS_SUBMODE) - reg = base->STOPCTRL; - reg &= ~SMC_STOPCTRL_LLSM_MASK; - reg |= ((uint32_t)config->subMode << SMC_STOPCTRL_LLSM_SHIFT); - base->STOPCTRL = reg; -#endif /* FSL_FEATURE_SMC_HAS_LLS_SUBMODE */ - -#if (defined(FSL_FEATURE_SMC_HAS_LPOPO) && FSL_FEATURE_SMC_HAS_LPOPO) - if (config->enableLpoClock) - { - base->STOPCTRL &= ~SMC_STOPCTRL_LPOPO_MASK; - } - else - { - base->STOPCTRL |= SMC_STOPCTRL_LPOPO_MASK; - } -#endif /* FSL_FEATURE_SMC_HAS_LPOPO */ - - /* Set the SLEEPDEEP bit to enable deep sleep mode */ - SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk; - - /* read back to make sure the configuration valid before enter stop mode */ - (void)base->PMCTRL; - __DSB(); - __WFI(); - __ISB(); - - /* check whether the power mode enter LLS mode succeed */ - if (base->PMCTRL & SMC_PMCTRL_STOPA_MASK) - { - return kStatus_SMC_StopAbort; - } - else - { - return kStatus_Success; - } -} -#endif /* FSL_FEATURE_SMC_HAS_LOW_LEAKAGE_STOP_MODE */ - -#if (defined(FSL_FEATURE_SMC_HAS_VERY_LOW_LEAKAGE_STOP_MODE) && FSL_FEATURE_SMC_HAS_VERY_LOW_LEAKAGE_STOP_MODE) -status_t SMC_SetPowerModeVlls(SMC_Type *base, const smc_power_mode_vlls_config_t *config) -{ - uint8_t reg; - -#if (defined(FSL_FEATURE_SMC_HAS_PORPO) && FSL_FEATURE_SMC_HAS_PORPO) -#if (defined(FSL_FEATURE_SMC_USE_VLLSCTRL_REG) && FSL_FEATURE_SMC_USE_VLLSCTRL_REG) || \ - (defined(FSL_FEATURE_SMC_USE_STOPCTRL_VLLSM) && FSL_FEATURE_SMC_USE_STOPCTRL_VLLSM) || \ - (defined(FSL_FEATURE_SMC_HAS_LLS_SUBMODE) && FSL_FEATURE_SMC_HAS_LLS_SUBMODE) - if (config->subMode == kSMC_StopSub0) -#endif - { - /* configure whether the Por Detect work in Vlls0 mode */ - if (config->enablePorDetectInVlls0) - { -#if (defined(FSL_FEATURE_SMC_USE_VLLSCTRL_REG) && FSL_FEATURE_SMC_USE_VLLSCTRL_REG) - base->VLLSCTRL &= ~SMC_VLLSCTRL_PORPO_MASK; -#else - base->STOPCTRL &= ~SMC_STOPCTRL_PORPO_MASK; -#endif - } - else - { -#if (defined(FSL_FEATURE_SMC_USE_VLLSCTRL_REG) && FSL_FEATURE_SMC_USE_VLLSCTRL_REG) - base->VLLSCTRL |= SMC_VLLSCTRL_PORPO_MASK; -#else - base->STOPCTRL |= SMC_STOPCTRL_PORPO_MASK; -#endif - } - } -#endif /* FSL_FEATURE_SMC_HAS_PORPO */ - -#if (defined(FSL_FEATURE_SMC_HAS_RAM2_POWER_OPTION) && FSL_FEATURE_SMC_HAS_RAM2_POWER_OPTION) - else if (config->subMode == kSMC_StopSub2) - { - /* configure whether the Por Detect work in Vlls0 mode */ - if (config->enableRam2InVlls2) - { -#if (defined(FSL_FEATURE_SMC_USE_VLLSCTRL_REG) && FSL_FEATURE_SMC_USE_VLLSCTRL_REG) - base->VLLSCTRL |= SMC_VLLSCTRL_RAM2PO_MASK; -#else - base->STOPCTRL |= SMC_STOPCTRL_RAM2PO_MASK; -#endif - } - else - { -#if (defined(FSL_FEATURE_SMC_USE_VLLSCTRL_REG) && FSL_FEATURE_SMC_USE_VLLSCTRL_REG) - base->VLLSCTRL &= ~SMC_VLLSCTRL_RAM2PO_MASK; -#else - base->STOPCTRL &= ~SMC_STOPCTRL_RAM2PO_MASK; -#endif - } - } - else - { - } -#endif /* FSL_FEATURE_SMC_HAS_RAM2_POWER_OPTION */ - - /* configure to VLLS mode */ - reg = base->PMCTRL; - reg &= ~SMC_PMCTRL_STOPM_MASK; - reg |= (kSMC_StopVlls << SMC_PMCTRL_STOPM_SHIFT); - base->PMCTRL = reg; - -/* configure the VLLS sub-mode */ -#if (defined(FSL_FEATURE_SMC_USE_VLLSCTRL_REG) && FSL_FEATURE_SMC_USE_VLLSCTRL_REG) - reg = base->VLLSCTRL; - reg &= ~SMC_VLLSCTRL_VLLSM_MASK; - reg |= ((uint32_t)config->subMode << SMC_VLLSCTRL_VLLSM_SHIFT); - base->VLLSCTRL = reg; -#else -#if (defined(FSL_FEATURE_SMC_HAS_LLS_SUBMODE) && FSL_FEATURE_SMC_HAS_LLS_SUBMODE) - reg = base->STOPCTRL; - reg &= ~SMC_STOPCTRL_LLSM_MASK; - reg |= ((uint32_t)config->subMode << SMC_STOPCTRL_LLSM_SHIFT); - base->STOPCTRL = reg; -#else - reg = base->STOPCTRL; - reg &= ~SMC_STOPCTRL_VLLSM_MASK; - reg |= ((uint32_t)config->subMode << SMC_STOPCTRL_VLLSM_SHIFT); - base->STOPCTRL = reg; -#endif /* FSL_FEATURE_SMC_HAS_LLS_SUBMODE */ -#endif - -#if (defined(FSL_FEATURE_SMC_HAS_LPOPO) && FSL_FEATURE_SMC_HAS_LPOPO) - if (config->enableLpoClock) - { - base->STOPCTRL &= ~SMC_STOPCTRL_LPOPO_MASK; - } - else - { - base->STOPCTRL |= SMC_STOPCTRL_LPOPO_MASK; - } -#endif /* FSL_FEATURE_SMC_HAS_LPOPO */ - - /* Set the SLEEPDEEP bit to enable deep sleep mode */ - SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk; - - /* read back to make sure the configuration valid before enter stop mode */ - (void)base->PMCTRL; - __DSB(); - __WFI(); - __ISB(); - - /* check whether the power mode enter LLS mode succeed */ - if (base->PMCTRL & SMC_PMCTRL_STOPA_MASK) - { - return kStatus_SMC_StopAbort; - } - else - { - return kStatus_Success; - } -} -#endif /* FSL_FEATURE_SMC_HAS_VERY_LOW_LEAKAGE_STOP_MODE */ diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_smc.h b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_smc.h deleted file mode 100644 index 168ce835013..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_smc.h +++ /dev/null @@ -1,456 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef _FSL_SMC_H_ -#define _FSL_SMC_H_ - -#include "fsl_common.h" - -/*! @addtogroup smc */ -/*! @{ */ - - -/******************************************************************************* - * Definitions - ******************************************************************************/ - -/*! @name Driver version */ -/*@{*/ -/*! @brief SMC driver version 2.0.3. */ -#define FSL_SMC_DRIVER_VERSION (MAKE_VERSION(2, 0, 3)) -/*@}*/ - -/*! - * @brief Power Modes Protection - */ -typedef enum _smc_power_mode_protection -{ -#if (defined(FSL_FEATURE_SMC_HAS_VERY_LOW_LEAKAGE_STOP_MODE) && FSL_FEATURE_SMC_HAS_VERY_LOW_LEAKAGE_STOP_MODE) - kSMC_AllowPowerModeVlls = SMC_PMPROT_AVLLS_MASK, /*!< Allow Very-low-leakage Stop Mode. */ -#endif -#if (defined(FSL_FEATURE_SMC_HAS_LOW_LEAKAGE_STOP_MODE) && FSL_FEATURE_SMC_HAS_LOW_LEAKAGE_STOP_MODE) - kSMC_AllowPowerModeLls = SMC_PMPROT_ALLS_MASK, /*!< Allow Low-leakage Stop Mode. */ -#endif /* FSL_FEATURE_SMC_HAS_LOW_LEAKAGE_STOP_MODE */ - kSMC_AllowPowerModeVlp = SMC_PMPROT_AVLP_MASK, /*!< Allow Very-Low-power Mode. */ -#if (defined(FSL_FEATURE_SMC_HAS_HIGH_SPEED_RUN_MODE) && FSL_FEATURE_SMC_HAS_HIGH_SPEED_RUN_MODE) - kSMC_AllowPowerModeHsrun = SMC_PMPROT_AHSRUN_MASK, /*!< Allow High-speed Run mode. */ -#endif /* FSL_FEATURE_SMC_HAS_HIGH_SPEED_RUN_MODE */ - kSMC_AllowPowerModeAll = (0U -#if (defined(FSL_FEATURE_SMC_HAS_VERY_LOW_LEAKAGE_STOP_MODE) && FSL_FEATURE_SMC_HAS_VERY_LOW_LEAKAGE_STOP_MODE) - | - SMC_PMPROT_AVLLS_MASK -#endif -#if (defined(FSL_FEATURE_SMC_HAS_LOW_LEAKAGE_STOP_MODE) && FSL_FEATURE_SMC_HAS_LOW_LEAKAGE_STOP_MODE) - | - SMC_PMPROT_ALLS_MASK -#endif /* FSL_FEATURE_SMC_HAS_LOW_LEAKAGE_STOP_MODE */ - | - SMC_PMPROT_AVLP_MASK -#if (defined(FSL_FEATURE_SMC_HAS_HIGH_SPEED_RUN_MODE) && FSL_FEATURE_SMC_HAS_HIGH_SPEED_RUN_MODE) - | - kSMC_AllowPowerModeHsrun -#endif /* FSL_FEATURE_SMC_HAS_HIGH_SPEED_RUN_MODE */ - ) /*!< Allow all power mode. */ -} smc_power_mode_protection_t; - -/*! - * @brief Power Modes in PMSTAT - */ -typedef enum _smc_power_state -{ - kSMC_PowerStateRun = 0x01U << 0U, /*!< 0000_0001 - Current power mode is RUN */ - kSMC_PowerStateStop = 0x01U << 1U, /*!< 0000_0010 - Current power mode is STOP */ - kSMC_PowerStateVlpr = 0x01U << 2U, /*!< 0000_0100 - Current power mode is VLPR */ - kSMC_PowerStateVlpw = 0x01U << 3U, /*!< 0000_1000 - Current power mode is VLPW */ - kSMC_PowerStateVlps = 0x01U << 4U, /*!< 0001_0000 - Current power mode is VLPS */ -#if (defined(FSL_FEATURE_SMC_HAS_LOW_LEAKAGE_STOP_MODE) && FSL_FEATURE_SMC_HAS_LOW_LEAKAGE_STOP_MODE) - kSMC_PowerStateLls = 0x01U << 5U, /*!< 0010_0000 - Current power mode is LLS */ -#endif /* FSL_FEATURE_SMC_HAS_LOW_LEAKAGE_STOP_MODE */ -#if (defined(FSL_FEATURE_SMC_HAS_VERY_LOW_LEAKAGE_STOP_MODE) && FSL_FEATURE_SMC_HAS_VERY_LOW_LEAKAGE_STOP_MODE) - kSMC_PowerStateVlls = 0x01U << 6U, /*!< 0100_0000 - Current power mode is VLLS */ -#endif -#if (defined(FSL_FEATURE_SMC_HAS_HIGH_SPEED_RUN_MODE) && FSL_FEATURE_SMC_HAS_HIGH_SPEED_RUN_MODE) - kSMC_PowerStateHsrun = 0x01U << 7U /*!< 1000_0000 - Current power mode is HSRUN */ -#endif /* FSL_FEATURE_SMC_HAS_HIGH_SPEED_RUN_MODE */ -} smc_power_state_t; - -/*! - * @brief Run mode definition - */ -typedef enum _smc_run_mode -{ - kSMC_RunNormal = 0U, /*!< Normal RUN mode. */ - kSMC_RunVlpr = 2U, /*!< Very-low-power RUN mode. */ -#if (defined(FSL_FEATURE_SMC_HAS_HIGH_SPEED_RUN_MODE) && FSL_FEATURE_SMC_HAS_HIGH_SPEED_RUN_MODE) - kSMC_Hsrun = 3U /*!< High-speed Run mode (HSRUN). */ -#endif /* FSL_FEATURE_SMC_HAS_HIGH_SPEED_RUN_MODE */ -} smc_run_mode_t; - -/*! - * @brief Stop mode definition - */ -typedef enum _smc_stop_mode -{ - kSMC_StopNormal = 0U, /*!< Normal STOP mode. */ - kSMC_StopVlps = 2U, /*!< Very-low-power STOP mode. */ -#if (defined(FSL_FEATURE_SMC_HAS_LOW_LEAKAGE_STOP_MODE) && FSL_FEATURE_SMC_HAS_LOW_LEAKAGE_STOP_MODE) - kSMC_StopLls = 3U, /*!< Low-leakage Stop mode. */ -#endif /* FSL_FEATURE_SMC_HAS_LOW_LEAKAGE_STOP_MODE */ -#if (defined(FSL_FEATURE_SMC_HAS_VERY_LOW_LEAKAGE_STOP_MODE) && FSL_FEATURE_SMC_HAS_VERY_LOW_LEAKAGE_STOP_MODE) - kSMC_StopVlls = 4U /*!< Very-low-leakage Stop mode. */ -#endif -} smc_stop_mode_t; - -#if (defined(FSL_FEATURE_SMC_USE_VLLSCTRL_REG) && FSL_FEATURE_SMC_USE_VLLSCTRL_REG) || \ - (defined(FSL_FEATURE_SMC_USE_STOPCTRL_VLLSM) && FSL_FEATURE_SMC_USE_STOPCTRL_VLLSM) || \ - (defined(FSL_FEATURE_SMC_HAS_LLS_SUBMODE) && FSL_FEATURE_SMC_HAS_LLS_SUBMODE) -/*! - * @brief VLLS/LLS stop sub mode definition - */ -typedef enum _smc_stop_submode -{ - kSMC_StopSub0 = 0U, /*!< Stop submode 0, for VLLS0/LLS0. */ - kSMC_StopSub1 = 1U, /*!< Stop submode 1, for VLLS1/LLS1. */ - kSMC_StopSub2 = 2U, /*!< Stop submode 2, for VLLS2/LLS2. */ - kSMC_StopSub3 = 3U /*!< Stop submode 3, for VLLS3/LLS3. */ -} smc_stop_submode_t; -#endif - -/*! - * @brief Partial STOP option - */ -typedef enum _smc_partial_stop_mode -{ - kSMC_PartialStop = 0U, /*!< STOP - Normal Stop mode*/ - kSMC_PartialStop1 = 1U, /*!< Partial Stop with both system and bus clocks disabled*/ - kSMC_PartialStop2 = 2U, /*!< Partial Stop with system clock disabled and bus clock enabled*/ -} smc_partial_stop_option_t; - -/*! - * @brief SMC configuration status. - */ -enum _smc_status -{ - kStatus_SMC_StopAbort = MAKE_STATUS(kStatusGroup_POWER, 0) /*!< Entering Stop mode is abort*/ -}; - -#if (defined(FSL_FEATURE_SMC_HAS_VERID) && FSL_FEATURE_SMC_HAS_VERID) -/*! - * @brief IP version ID definition. - */ -typedef struct _smc_version_id -{ - uint16_t feature; /*!< Feature Specification Number. */ - uint8_t minor; /*!< Minor version number. */ - uint8_t major; /*!< Major version number. */ -} smc_version_id_t; -#endif /* FSL_FEATURE_SMC_HAS_VERID */ - -#if (defined(FSL_FEATURE_SMC_HAS_PARAM) && FSL_FEATURE_SMC_HAS_PARAM) -/*! - * @brief IP parameter definition. - */ -typedef struct _smc_param -{ - bool hsrunEnable; /*!< HSRUN mode enable. */ - bool llsEnable; /*!< LLS mode enable. */ - bool lls2Enable; /*!< LLS2 mode enable. */ - bool vlls0Enable; /*!< VLLS0 mode enable. */ -} smc_param_t; -#endif /* FSL_FEATURE_SMC_HAS_PARAM */ - -#if (defined(FSL_FEATURE_SMC_HAS_LLS_SUBMODE) && FSL_FEATURE_SMC_HAS_LLS_SUBMODE) || \ - (defined(FSL_FEATURE_SMC_HAS_LPOPO) && FSL_FEATURE_SMC_HAS_LPOPO) -/*! - * @brief SMC Low-Leakage Stop power mode configuration. - */ -typedef struct _smc_power_mode_lls_config -{ -#if (defined(FSL_FEATURE_SMC_HAS_LLS_SUBMODE) && FSL_FEATURE_SMC_HAS_LLS_SUBMODE) - smc_stop_submode_t subMode; /*!< Low-leakage Stop sub-mode */ -#endif -#if (defined(FSL_FEATURE_SMC_HAS_LPOPO) && FSL_FEATURE_SMC_HAS_LPOPO) - bool enableLpoClock; /*!< Enable LPO clock in LLS mode */ -#endif -} smc_power_mode_lls_config_t; -#endif /* (FSL_FEATURE_SMC_HAS_LLS_SUBMODE || FSL_FEATURE_SMC_HAS_LPOPO) */ - -#if (defined(FSL_FEATURE_SMC_HAS_VERY_LOW_LEAKAGE_STOP_MODE) && FSL_FEATURE_SMC_HAS_VERY_LOW_LEAKAGE_STOP_MODE) -/*! - * @brief SMC Very Low-Leakage Stop power mode configuration. - */ -typedef struct _smc_power_mode_vlls_config -{ -#if (defined(FSL_FEATURE_SMC_USE_VLLSCTRL_REG) && FSL_FEATURE_SMC_USE_VLLSCTRL_REG) || \ - (defined(FSL_FEATURE_SMC_USE_STOPCTRL_VLLSM) && FSL_FEATURE_SMC_USE_STOPCTRL_VLLSM) || \ - (defined(FSL_FEATURE_SMC_HAS_LLS_SUBMODE) && FSL_FEATURE_SMC_HAS_LLS_SUBMODE) - smc_stop_submode_t subMode; /*!< Very Low-leakage Stop sub-mode */ -#endif -#if (defined(FSL_FEATURE_SMC_HAS_PORPO) && FSL_FEATURE_SMC_HAS_PORPO) - bool enablePorDetectInVlls0; /*!< Enable Power on reset detect in VLLS mode */ -#endif -#if (defined(FSL_FEATURE_SMC_HAS_RAM2_POWER_OPTION) && FSL_FEATURE_SMC_HAS_RAM2_POWER_OPTION) - bool enableRam2InVlls2; /*!< Enable RAM2 power in VLLS2 */ -#endif -#if (defined(FSL_FEATURE_SMC_HAS_LPOPO) && FSL_FEATURE_SMC_HAS_LPOPO) - bool enableLpoClock; /*!< Enable LPO clock in VLLS mode */ -#endif -} smc_power_mode_vlls_config_t; -#endif - -/******************************************************************************* - * API - ******************************************************************************/ - -#if defined(__cplusplus) -extern "C" { -#endif /* __cplusplus */ - -/*! @name System mode controller APIs*/ -/*@{*/ - -#if (defined(FSL_FEATURE_SMC_HAS_VERID) && FSL_FEATURE_SMC_HAS_VERID) -/*! - * @brief Gets the SMC version ID. - * - * This function gets the SMC version ID, including major version number, - * minor version number, and feature specification number. - * - * @param base SMC peripheral base address. - * @param versionId Pointer to the version ID structure. - */ -static inline void SMC_GetVersionId(SMC_Type *base, smc_version_id_t *versionId) -{ - *((uint32_t *)versionId) = base->VERID; -} -#endif /* FSL_FEATURE_SMC_HAS_VERID */ - -#if (defined(FSL_FEATURE_SMC_HAS_PARAM) && FSL_FEATURE_SMC_HAS_PARAM) -/*! - * @brief Gets the SMC parameter. - * - * This function gets the SMC parameter including the enabled power mdoes. - * - * @param base SMC peripheral base address. - * @param param Pointer to the SMC param structure. - */ -void SMC_GetParam(SMC_Type *base, smc_param_t *param); -#endif - -/*! - * @brief Configures all power mode protection settings. - * - * This function configures the power mode protection settings for - * supported power modes in the specified chip family. The available power modes - * are defined in the smc_power_mode_protection_t. This should be done at an early - * system level initialization stage. See the reference manual for details. - * This register can only write once after the power reset. - * - * The allowed modes are passed as bit map. For example, to allow LLS and VLLS, - * use SMC_SetPowerModeProtection(kSMC_AllowPowerModeVlls | kSMC_AllowPowerModeVlps). - * To allow all modes, use SMC_SetPowerModeProtection(kSMC_AllowPowerModeAll). - * - * @param base SMC peripheral base address. - * @param allowedModes Bitmap of the allowed power modes. - */ -static inline void SMC_SetPowerModeProtection(SMC_Type *base, uint8_t allowedModes) -{ - base->PMPROT = allowedModes; -} - -/*! - * @brief Gets the current power mode status. - * - * This function returns the current power mode status. After the application - * switches the power mode, it should always check the status to check whether it - * runs into the specified mode or not. The application should check - * this mode before switching to a different mode. The system requires that - * only certain modes can switch to other specific modes. See the - * reference manual for details and the smc_power_state_t for information about - * the power status. - * - * @param base SMC peripheral base address. - * @return Current power mode status. - */ -static inline smc_power_state_t SMC_GetPowerModeState(SMC_Type *base) -{ - return (smc_power_state_t)base->PMSTAT; -} - -/*! - * @brief Prepares to enter stop modes. - * - * This function should be called before entering STOP/VLPS/LLS/VLLS modes. - */ -void SMC_PreEnterStopModes(void); - -/*! - * @brief Recovers after wake up from stop modes. - * - * This function should be called after wake up from STOP/VLPS/LLS/VLLS modes. - * It is used with @ref SMC_PreEnterStopModes. - */ -void SMC_PostExitStopModes(void); - -/*! - * @brief Prepares to enter wait modes. - * - * This function should be called before entering WAIT/VLPW modes. - */ -static inline void SMC_PreEnterWaitModes(void) -{ - __disable_irq(); - __ISB(); -} - -/*! - * @brief Recovers after wake up from stop modes. - * - * This function should be called after wake up from WAIT/VLPW modes. - * It is used with @ref SMC_PreEnterWaitModes. - */ -static inline void SMC_PostExitWaitModes(void) -{ - __enable_irq(); - __ISB(); -} - -/*! - * @brief Configures the system to RUN power mode. - * - * @param base SMC peripheral base address. - * @return SMC configuration error code. - */ -status_t SMC_SetPowerModeRun(SMC_Type *base); - -#if (defined(FSL_FEATURE_SMC_HAS_HIGH_SPEED_RUN_MODE) && FSL_FEATURE_SMC_HAS_HIGH_SPEED_RUN_MODE) -/*! - * @brief Configures the system to HSRUN power mode. - * - * @param base SMC peripheral base address. - * @return SMC configuration error code. - */ -status_t SMC_SetPowerModeHsrun(SMC_Type *base); -#endif /* FSL_FEATURE_SMC_HAS_HIGH_SPEED_RUN_MODE */ - -/*! - * @brief Configures the system to WAIT power mode. - * - * @param base SMC peripheral base address. - * @return SMC configuration error code. - */ -status_t SMC_SetPowerModeWait(SMC_Type *base); - -/*! - * @brief Configures the system to Stop power mode. - * - * @param base SMC peripheral base address. - * @param option Partial Stop mode option. - * @return SMC configuration error code. - */ -status_t SMC_SetPowerModeStop(SMC_Type *base, smc_partial_stop_option_t option); - -#if (defined(FSL_FEATURE_SMC_HAS_LPWUI) && FSL_FEATURE_SMC_HAS_LPWUI) -/*! - * @brief Configures the system to VLPR power mode. - * - * @param base SMC peripheral base address. - * @param wakeupMode Enter Normal Run mode if true, else stay in VLPR mode. - * @return SMC configuration error code. - */ -status_t SMC_SetPowerModeVlpr(SMC_Type *base, bool wakeupMode); -#else -/*! - * @brief Configures the system to VLPR power mode. - * - * @param base SMC peripheral base address. - * @return SMC configuration error code. - */ -status_t SMC_SetPowerModeVlpr(SMC_Type *base); -#endif /* FSL_FEATURE_SMC_HAS_LPWUI */ - -/*! - * @brief Configures the system to VLPW power mode. - * - * @param base SMC peripheral base address. - * @return SMC configuration error code. - */ -status_t SMC_SetPowerModeVlpw(SMC_Type *base); - -/*! - * @brief Configures the system to VLPS power mode. - * - * @param base SMC peripheral base address. - * @return SMC configuration error code. - */ -status_t SMC_SetPowerModeVlps(SMC_Type *base); - -#if (defined(FSL_FEATURE_SMC_HAS_LOW_LEAKAGE_STOP_MODE) && FSL_FEATURE_SMC_HAS_LOW_LEAKAGE_STOP_MODE) -#if ((defined(FSL_FEATURE_SMC_HAS_LLS_SUBMODE) && FSL_FEATURE_SMC_HAS_LLS_SUBMODE) || \ - (defined(FSL_FEATURE_SMC_HAS_LPOPO) && FSL_FEATURE_SMC_HAS_LPOPO)) -/*! - * @brief Configures the system to LLS power mode. - * - * @param base SMC peripheral base address. - * @param config The LLS power mode configuration structure - * @return SMC configuration error code. - */ -status_t SMC_SetPowerModeLls(SMC_Type *base, const smc_power_mode_lls_config_t *config); -#else -/*! - * @brief Configures the system to LLS power mode. - * - * @param base SMC peripheral base address. - * @return SMC configuration error code. - */ -status_t SMC_SetPowerModeLls(SMC_Type *base); -#endif -#endif /* FSL_FEATURE_SMC_HAS_LOW_LEAKAGE_STOP_MODE */ - -#if (defined(FSL_FEATURE_SMC_HAS_VERY_LOW_LEAKAGE_STOP_MODE) && FSL_FEATURE_SMC_HAS_VERY_LOW_LEAKAGE_STOP_MODE) -/*! - * @brief Configures the system to VLLS power mode. - * - * @param base SMC peripheral base address. - * @param config The VLLS power mode configuration structure. - * @return SMC configuration error code. - */ -status_t SMC_SetPowerModeVlls(SMC_Type *base, const smc_power_mode_vlls_config_t *config); -#endif /* FSL_FEATURE_SMC_HAS_VERY_LOW_LEAKAGE_STOP_MODE */ - -/*@}*/ - -#if defined(__cplusplus) -} -#endif /* __cplusplus */ - -/*! @}*/ - -#endif /* _FSL_SMC_H_ */ diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_sysmpu.c b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_sysmpu.c deleted file mode 100644 index b89a7b20e4e..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_sysmpu.c +++ /dev/null @@ -1,249 +0,0 @@ -/* - * Copyright (c) 2015 - 2016, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "fsl_sysmpu.h" - -/******************************************************************************* - * Variables - ******************************************************************************/ - -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) -const clock_ip_name_t g_sysmpuClock[FSL_FEATURE_SOC_SYSMPU_COUNT] = SYSMPU_CLOCKS; -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ - -/******************************************************************************* - * Codes - ******************************************************************************/ - -void SYSMPU_Init(SYSMPU_Type *base, const sysmpu_config_t *config) -{ - assert(config); - uint8_t count; - -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) - /* Un-gate SYSMPU clock */ - CLOCK_EnableClock(g_sysmpuClock[0]); -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ - - /* Initializes the regions. */ - for (count = 1; count < FSL_FEATURE_SYSMPU_DESCRIPTOR_COUNT; count++) - { - base->WORD[count][3] = 0; /* VLD/VID+PID. */ - base->WORD[count][0] = 0; /* Start address. */ - base->WORD[count][1] = 0; /* End address. */ - base->WORD[count][2] = 0; /* Access rights. */ - base->RGDAAC[count] = 0; /* Alternate access rights. */ - } - - /* SYSMPU configure. */ - while (config) - { - SYSMPU_SetRegionConfig(base, &(config->regionConfig)); - config = config->next; - } - /* Enable SYSMPU. */ - SYSMPU_Enable(base, true); -} - -void SYSMPU_Deinit(SYSMPU_Type *base) -{ - /* Disable SYSMPU. */ - SYSMPU_Enable(base, false); - -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) - /* Gate the clock. */ - CLOCK_DisableClock(g_sysmpuClock[0]); -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ -} - -void SYSMPU_GetHardwareInfo(SYSMPU_Type *base, sysmpu_hardware_info_t *hardwareInform) -{ - assert(hardwareInform); - - uint32_t cesReg = base->CESR; - - hardwareInform->hardwareRevisionLevel = (cesReg & SYSMPU_CESR_HRL_MASK) >> SYSMPU_CESR_HRL_SHIFT; - hardwareInform->slavePortsNumbers = (cesReg & SYSMPU_CESR_NSP_MASK) >> SYSMPU_CESR_NSP_SHIFT; - hardwareInform->regionsNumbers = (sysmpu_region_total_num_t)((cesReg & SYSMPU_CESR_NRGD_MASK) >> SYSMPU_CESR_NRGD_SHIFT); -} - -void SYSMPU_SetRegionConfig(SYSMPU_Type *base, const sysmpu_region_config_t *regionConfig) -{ - assert(regionConfig); - assert(regionConfig->regionNum < FSL_FEATURE_SYSMPU_DESCRIPTOR_COUNT); - - uint32_t wordReg = 0; - uint8_t msPortNum; - uint8_t regNumber = regionConfig->regionNum; - - /* The start and end address of the region descriptor. */ - base->WORD[regNumber][0] = regionConfig->startAddress; - base->WORD[regNumber][1] = regionConfig->endAddress; - - /* Set the privilege rights for master 0 ~ master 3. */ - for (msPortNum = 0; msPortNum < SYSMPU_MASTER_RWATTRIBUTE_START_PORT; msPortNum++) - { - wordReg |= SYSMPU_REGION_RWXRIGHTS_MASTER( - msPortNum, (((uint32_t)regionConfig->accessRights1[msPortNum].superAccessRights << 3U) | - (uint32_t)regionConfig->accessRights1[msPortNum].userAccessRights)); - -#if FSL_FEATURE_SYSMPU_HAS_PROCESS_IDENTIFIER - wordReg |= - SYSMPU_REGION_RWXRIGHTS_MASTER_PE(msPortNum, regionConfig->accessRights1[msPortNum].processIdentifierEnable); -#endif /* FSL_FEATURE_SYSMPU_HAS_PROCESS_IDENTIFIER */ - } - -#if FSL_FEATURE_SYSMPU_MASTER_COUNT > SYSMPU_MASTER_RWATTRIBUTE_START_PORT - /* Set the normal read write rights for master 4 ~ master 7. */ - for (msPortNum = SYSMPU_MASTER_RWATTRIBUTE_START_PORT; msPortNum < FSL_FEATURE_SYSMPU_MASTER_COUNT; - msPortNum++) - { - wordReg |= SYSMPU_REGION_RWRIGHTS_MASTER(msPortNum, - ((uint32_t)regionConfig->accessRights2[msPortNum - SYSMPU_MASTER_RWATTRIBUTE_START_PORT].readEnable << 1U | - (uint32_t)regionConfig->accessRights2[msPortNum - SYSMPU_MASTER_RWATTRIBUTE_START_PORT].writeEnable)); - } -#endif /* FSL_FEATURE_SYSMPU_MASTER_COUNT > SYSMPU_MASTER_RWATTRIBUTE_START_PORT */ - - /* Set region descriptor access rights. */ - base->WORD[regNumber][2] = wordReg; - - wordReg = SYSMPU_WORD_VLD(1); -#if FSL_FEATURE_SYSMPU_HAS_PROCESS_IDENTIFIER - wordReg |= SYSMPU_WORD_PID(regionConfig->processIdentifier) | SYSMPU_WORD_PIDMASK(regionConfig->processIdMask); -#endif /* FSL_FEATURE_SYSMPU_HAS_PROCESS_IDENTIFIER */ - - base->WORD[regNumber][3] = wordReg; -} - -void SYSMPU_SetRegionAddr(SYSMPU_Type *base, uint32_t regionNum, uint32_t startAddr, uint32_t endAddr) -{ - assert(regionNum < FSL_FEATURE_SYSMPU_DESCRIPTOR_COUNT); - - base->WORD[regionNum][0] = startAddr; - base->WORD[regionNum][1] = endAddr; -} - -void SYSMPU_SetRegionRwxMasterAccessRights(SYSMPU_Type *base, - uint32_t regionNum, - uint32_t masterNum, - const sysmpu_rwxrights_master_access_control_t *accessRights) -{ - assert(accessRights); - assert(regionNum < FSL_FEATURE_SYSMPU_DESCRIPTOR_COUNT); - assert(masterNum < SYSMPU_MASTER_RWATTRIBUTE_START_PORT); - - uint32_t mask = SYSMPU_REGION_RWXRIGHTS_MASTER_MASK(masterNum); - uint32_t right = base->RGDAAC[regionNum]; - -#if FSL_FEATURE_SYSMPU_HAS_PROCESS_IDENTIFIER - mask |= SYSMPU_REGION_RWXRIGHTS_MASTER_PE_MASK(masterNum); -#endif - - /* Build rights control value. */ - right &= ~mask; - right |= SYSMPU_REGION_RWXRIGHTS_MASTER( - masterNum, ((uint32_t)(accessRights->superAccessRights << 3U) | accessRights->userAccessRights)); -#if FSL_FEATURE_SYSMPU_HAS_PROCESS_IDENTIFIER - right |= SYSMPU_REGION_RWXRIGHTS_MASTER_PE(masterNum, accessRights->processIdentifierEnable); -#endif /* FSL_FEATURE_SYSMPU_HAS_PROCESS_IDENTIFIER */ - - /* Set low master region access rights. */ - base->RGDAAC[regionNum] = right; -} - -#if FSL_FEATURE_SYSMPU_MASTER_COUNT > 4 -void SYSMPU_SetRegionRwMasterAccessRights(SYSMPU_Type *base, - uint32_t regionNum, - uint32_t masterNum, - const sysmpu_rwrights_master_access_control_t *accessRights) -{ - assert(accessRights); - assert(regionNum < FSL_FEATURE_SYSMPU_DESCRIPTOR_COUNT); - assert(masterNum >= SYSMPU_MASTER_RWATTRIBUTE_START_PORT); - assert(masterNum <= (FSL_FEATURE_SYSMPU_MASTER_COUNT - 1)); - - uint32_t mask = SYSMPU_REGION_RWRIGHTS_MASTER_MASK(masterNum); - uint32_t right = base->RGDAAC[regionNum]; - - /* Build rights control value. */ - right &= ~mask; - right |= - SYSMPU_REGION_RWRIGHTS_MASTER(masterNum, (((uint32_t)accessRights->readEnable << 1U) | accessRights->writeEnable)); - /* Set low master region access rights. */ - base->RGDAAC[regionNum] = right; -} -#endif /* FSL_FEATURE_SYSMPU_MASTER_COUNT > 4 */ - -bool SYSMPU_GetSlavePortErrorStatus(SYSMPU_Type *base, sysmpu_slave_t slaveNum) -{ - uint8_t sperr; - - sperr = ((base->CESR & SYSMPU_CESR_SPERR_MASK) >> SYSMPU_CESR_SPERR_SHIFT) & (0x1U << (FSL_FEATURE_SYSMPU_SLAVE_COUNT - slaveNum - 1)); - - return (sperr != 0) ? true : false; -} - -void SYSMPU_GetDetailErrorAccessInfo(SYSMPU_Type *base, sysmpu_slave_t slaveNum, sysmpu_access_err_info_t *errInform) -{ - assert(errInform); - - uint16_t value; - uint32_t cesReg; - - /* Error address. */ - errInform->address = base->SP[slaveNum].EAR; - - /* Error detail information. */ - value = (base->SP[slaveNum].EDR & SYSMPU_EDR_EACD_MASK) >> SYSMPU_EDR_EACD_SHIFT; - if (!value) - { - errInform->accessControl = kSYSMPU_NoRegionHit; - } - else if (!(value & (uint16_t)(value - 1))) - { - errInform->accessControl = kSYSMPU_NoneOverlappRegion; - } - else - { - errInform->accessControl = kSYSMPU_OverlappRegion; - } - - value = base->SP[slaveNum].EDR; - errInform->master = (uint32_t)((value & SYSMPU_EDR_EMN_MASK) >> SYSMPU_EDR_EMN_SHIFT); - errInform->attributes = (sysmpu_err_attributes_t)((value & SYSMPU_EDR_EATTR_MASK) >> SYSMPU_EDR_EATTR_SHIFT); - errInform->accessType = (sysmpu_err_access_type_t)((value & SYSMPU_EDR_ERW_MASK) >> SYSMPU_EDR_ERW_SHIFT); -#if FSL_FEATURE_SYSMPU_HAS_PROCESS_IDENTIFIER - errInform->processorIdentification = (uint8_t)((value & SYSMPU_EDR_EPID_MASK) >> SYSMPU_EDR_EPID_SHIFT); -#endif - - /* Clears error slave port bit. */ - cesReg = (base->CESR & ~SYSMPU_CESR_SPERR_MASK) | ((0x1U << (FSL_FEATURE_SYSMPU_SLAVE_COUNT - slaveNum - 1)) << SYSMPU_CESR_SPERR_SHIFT); - base->CESR = cesReg; -} diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_sysmpu.h b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_sysmpu.h deleted file mode 100644 index 6341a31e9d1..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_sysmpu.h +++ /dev/null @@ -1,435 +0,0 @@ -/* - * Copyright (c) 2015 - 2016, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -#ifndef _FSL_SYSMPU_H_ -#define _FSL_SYSMPU_H_ - -#include "fsl_common.h" - -/*! - * @addtogroup sysmpu - * @{ - */ - - -/******************************************************************************* - * Definitions - ******************************************************************************/ - -/*! @name Driver version */ -/*@{*/ -/*! @brief SYSMPU driver version 2.2.0. */ -#define FSL_SYSMPU_DRIVER_VERSION (MAKE_VERSION(2, 2, 0)) -/*@}*/ - -/*! @brief define the start master port with read and write attributes. */ -#define SYSMPU_MASTER_RWATTRIBUTE_START_PORT (4) - -/*! @brief SYSMPU the bit shift for masters with privilege rights: read write and execute. */ -#define SYSMPU_REGION_RWXRIGHTS_MASTER_SHIFT(n) (n * 6) - -/*! @brief SYSMPU masters with read, write and execute rights bit mask. */ -#define SYSMPU_REGION_RWXRIGHTS_MASTER_MASK(n) (0x1Fu << SYSMPU_REGION_RWXRIGHTS_MASTER_SHIFT(n)) - -/*! @brief SYSMPU masters with read, write and execute rights bit width. */ -#define SYSMPU_REGION_RWXRIGHTS_MASTER_WIDTH 5 - -/*! @brief SYSMPU masters with read, write and execute rights priority setting. */ -#define SYSMPU_REGION_RWXRIGHTS_MASTER(n, x) \ - (((uint32_t)(((uint32_t)(x)) << SYSMPU_REGION_RWXRIGHTS_MASTER_SHIFT(n))) & SYSMPU_REGION_RWXRIGHTS_MASTER_MASK(n)) - -/*! @brief SYSMPU masters with read, write and execute rights process enable bit shift. */ -#define SYSMPU_REGION_RWXRIGHTS_MASTER_PE_SHIFT(n) (n * 6 + SYSMPU_REGION_RWXRIGHTS_MASTER_WIDTH) - -/*! @brief SYSMPU masters with read, write and execute rights process enable bit mask. */ -#define SYSMPU_REGION_RWXRIGHTS_MASTER_PE_MASK(n) (0x1u << SYSMPU_REGION_RWXRIGHTS_MASTER_PE_SHIFT(n)) - -/*! @brief SYSMPU masters with read, write and execute rights process enable setting. */ -#define SYSMPU_REGION_RWXRIGHTS_MASTER_PE(n, x) \ - (((uint32_t)(((uint32_t)(x)) << SYSMPU_REGION_RWXRIGHTS_MASTER_PE_SHIFT(n))) & SYSMPU_REGION_RWXRIGHTS_MASTER_PE_MASK(n)) - -/*! @brief SYSMPU masters with normal read write permission bit shift. */ -#define SYSMPU_REGION_RWRIGHTS_MASTER_SHIFT(n) ((n - SYSMPU_MASTER_RWATTRIBUTE_START_PORT) * 2 + 24) - -/*! @brief SYSMPU masters with normal read write rights bit mask. */ -#define SYSMPU_REGION_RWRIGHTS_MASTER_MASK(n) (0x3u << SYSMPU_REGION_RWRIGHTS_MASTER_SHIFT(n)) - -/*! @brief SYSMPU masters with normal read write rights priority setting. */ -#define SYSMPU_REGION_RWRIGHTS_MASTER(n, x) \ - (((uint32_t)(((uint32_t)(x)) << SYSMPU_REGION_RWRIGHTS_MASTER_SHIFT(n))) & SYSMPU_REGION_RWRIGHTS_MASTER_MASK(n)) - - -/*! @brief Describes the number of SYSMPU regions. */ -typedef enum _sysmpu_region_total_num -{ - kSYSMPU_8Regions = 0x0U, /*!< SYSMPU supports 8 regions. */ - kSYSMPU_12Regions = 0x1U, /*!< SYSMPU supports 12 regions. */ - kSYSMPU_16Regions = 0x2U /*!< SYSMPU supports 16 regions. */ -} sysmpu_region_total_num_t; - -/*! @brief SYSMPU slave port number. */ -typedef enum _sysmpu_slave -{ - kSYSMPU_Slave0 = 0U, /*!< SYSMPU slave port 0. */ - kSYSMPU_Slave1 = 1U, /*!< SYSMPU slave port 1. */ - kSYSMPU_Slave2 = 2U, /*!< SYSMPU slave port 2. */ - kSYSMPU_Slave3 = 3U, /*!< SYSMPU slave port 3. */ - kSYSMPU_Slave4 = 4U, /*!< SYSMPU slave port 4. */ -#if FSL_FEATURE_SYSMPU_SLAVE_COUNT > 5 - kSYSMPU_Slave5 = 5U, /*!< SYSMPU slave port 5. */ -#endif -#if FSL_FEATURE_SYSMPU_SLAVE_COUNT > 6 - kSYSMPU_Slave6 = 6U, /*!< SYSMPU slave port 6. */ -#endif -#if FSL_FEATURE_SYSMPU_SLAVE_COUNT > 7 - kSYSMPU_Slave7 = 7U, /*!< SYSMPU slave port 7. */ -#endif -} sysmpu_slave_t; - -/*! @brief SYSMPU error access control detail. */ -typedef enum _sysmpu_err_access_control -{ - kSYSMPU_NoRegionHit = 0U, /*!< No region hit error. */ - kSYSMPU_NoneOverlappRegion = 1U, /*!< Access single region error. */ - kSYSMPU_OverlappRegion = 2U /*!< Access overlapping region error. */ -} sysmpu_err_access_control_t; - -/*! @brief SYSMPU error access type. */ -typedef enum _sysmpu_err_access_type -{ - kSYSMPU_ErrTypeRead = 0U, /*!< SYSMPU error access type --- read. */ - kSYSMPU_ErrTypeWrite = 1U /*!< SYSMPU error access type --- write. */ -} sysmpu_err_access_type_t; - -/*! @brief SYSMPU access error attributes.*/ -typedef enum _sysmpu_err_attributes -{ - kSYSMPU_InstructionAccessInUserMode = 0U, /*!< Access instruction error in user mode. */ - kSYSMPU_DataAccessInUserMode = 1U, /*!< Access data error in user mode. */ - kSYSMPU_InstructionAccessInSupervisorMode = 2U, /*!< Access instruction error in supervisor mode. */ - kSYSMPU_DataAccessInSupervisorMode = 3U /*!< Access data error in supervisor mode. */ -} sysmpu_err_attributes_t; - -/*! @brief SYSMPU access rights in supervisor mode for bus master 0 ~ 3. */ -typedef enum _sysmpu_supervisor_access_rights -{ - kSYSMPU_SupervisorReadWriteExecute = 0U, /*!< Read write and execute operations are allowed in supervisor mode. */ - kSYSMPU_SupervisorReadExecute = 1U, /*!< Read and execute operations are allowed in supervisor mode. */ - kSYSMPU_SupervisorReadWrite = 2U, /*!< Read write operations are allowed in supervisor mode. */ - kSYSMPU_SupervisorEqualToUsermode = 3U /*!< Access permission equal to user mode. */ -} sysmpu_supervisor_access_rights_t; - -/*! @brief SYSMPU access rights in user mode for bus master 0 ~ 3. */ -typedef enum _sysmpu_user_access_rights -{ - kSYSMPU_UserNoAccessRights = 0U, /*!< No access allowed in user mode. */ - kSYSMPU_UserExecute = 1U, /*!< Execute operation is allowed in user mode. */ - kSYSMPU_UserWrite = 2U, /*!< Write operation is allowed in user mode. */ - kSYSMPU_UserWriteExecute = 3U, /*!< Write and execute operations are allowed in user mode. */ - kSYSMPU_UserRead = 4U, /*!< Read is allowed in user mode. */ - kSYSMPU_UserReadExecute = 5U, /*!< Read and execute operations are allowed in user mode. */ - kSYSMPU_UserReadWrite = 6U, /*!< Read and write operations are allowed in user mode. */ - kSYSMPU_UserReadWriteExecute = 7U /*!< Read write and execute operations are allowed in user mode. */ -} sysmpu_user_access_rights_t; - -/*! @brief SYSMPU hardware basic information. */ -typedef struct _sysmpu_hardware_info -{ - uint8_t hardwareRevisionLevel; /*!< Specifies the SYSMPU's hardware and definition reversion level. */ - uint8_t slavePortsNumbers; /*!< Specifies the number of slave ports connected to SYSMPU. */ - sysmpu_region_total_num_t regionsNumbers; /*!< Indicates the number of region descriptors implemented. */ -} sysmpu_hardware_info_t; - -/*! @brief SYSMPU detail error access information. */ -typedef struct _sysmpu_access_err_info -{ - uint32_t master; /*!< Access error master. */ - sysmpu_err_attributes_t attributes; /*!< Access error attributes. */ - sysmpu_err_access_type_t accessType; /*!< Access error type. */ - sysmpu_err_access_control_t accessControl; /*!< Access error control. */ - uint32_t address; /*!< Access error address. */ -#if FSL_FEATURE_SYSMPU_HAS_PROCESS_IDENTIFIER - uint8_t processorIdentification; /*!< Access error processor identification. */ -#endif /* FSL_FEATURE_SYSMPU_HAS_PROCESS_IDENTIFIER */ -} sysmpu_access_err_info_t; - -/*! @brief SYSMPU read/write/execute rights control for bus master 0 ~ 3. */ -typedef struct _sysmpu_rwxrights_master_access_control -{ - sysmpu_supervisor_access_rights_t superAccessRights; /*!< Master access rights in supervisor mode. */ - sysmpu_user_access_rights_t userAccessRights; /*!< Master access rights in user mode. */ -#if FSL_FEATURE_SYSMPU_HAS_PROCESS_IDENTIFIER - bool processIdentifierEnable; /*!< Enables or disables process identifier. */ -#endif /* FSL_FEATURE_SYSMPU_HAS_PROCESS_IDENTIFIER */ -} sysmpu_rwxrights_master_access_control_t; - -/*! @brief SYSMPU read/write access control for bus master 4 ~ 7. */ -typedef struct _sysmpu_rwrights_master_access_control -{ - bool writeEnable; /*!< Enables or disables write permission. */ - bool readEnable; /*!< Enables or disables read permission. */ -} sysmpu_rwrights_master_access_control_t; - -/*! - * @brief SYSMPU region configuration structure. - * - * This structure is used to configure the regionNum region. - * The accessRights1[0] ~ accessRights1[3] are used to configure the bus master - * 0 ~ 3 with the privilege rights setting. The accessRights2[0] ~ accessRights2[3] - * are used to configure the high master 4 ~ 7 with the normal read write permission. - * The master port assignment is the chip configuration. Normally, the core is the - * master 0, debugger is the master 1. - * Note that the SYSMPU assigns a priority scheme where the debugger is treated as the highest - * priority master followed by the core and then all the remaining masters. - * SYSMPU protection does not allow writes from the core to affect the "regionNum 0" start - * and end address nor the permissions associated with the debugger. It can only write - * the permission fields associated with the other masters. This protection guarantees that - * the debugger always has access to the entire address space and those rights can't - * be changed by the core or any other bus master. Prepare - * the region configuration when regionNum is 0. - */ -typedef struct _sysmpu_region_config -{ - uint32_t regionNum; /*!< SYSMPU region number, range form 0 ~ FSL_FEATURE_SYSMPU_DESCRIPTOR_COUNT - 1. */ - uint32_t startAddress; /*!< Memory region start address. Note: bit0 ~ bit4 always be marked as 0 by SYSMPU. The actual - start address is 0-modulo-32 byte address. */ - uint32_t endAddress; /*!< Memory region end address. Note: bit0 ~ bit4 always be marked as 1 by SYSMPU. The actual end - address is 31-modulo-32 byte address. */ - sysmpu_rwxrights_master_access_control_t accessRights1[4]; /*!< Masters with read, write and execute rights setting. */ - sysmpu_rwrights_master_access_control_t accessRights2[4]; /*!< Masters with normal read write rights setting. */ -#if FSL_FEATURE_SYSMPU_HAS_PROCESS_IDENTIFIER - uint8_t processIdentifier; /*!< Process identifier used when "processIdentifierEnable" set with true. */ - uint8_t - processIdMask; /*!< Process identifier mask. The setting bit will ignore the same bit in process identifier. */ -#endif /* FSL_FEATURE_SYSMPU_HAS_PROCESS_IDENTIFIER */ -} sysmpu_region_config_t; - -/*! - * @brief The configuration structure for the SYSMPU initialization. - * - * This structure is used when calling the SYSMPU_Init function. - */ -typedef struct _sysmpu_config -{ - sysmpu_region_config_t regionConfig; /*!< Region access permission. */ - struct _sysmpu_config *next; /*!< Pointer to the next structure. */ -} sysmpu_config_t; - -/******************************************************************************* - * API - ******************************************************************************/ - -#if defined(__cplusplus) -extern "C" { -#endif /* _cplusplus */ - -/*! - * @name Initialization and deinitialization - * @{ - */ - -/*! - * @brief Initializes the SYSMPU with the user configuration structure. - * - * This function configures the SYSMPU module with the user-defined configuration. - * - * @param base SYSMPU peripheral base address. - * @param config The pointer to the configuration structure. - */ -void SYSMPU_Init(SYSMPU_Type *base, const sysmpu_config_t *config); - -/*! - * @brief Deinitializes the SYSMPU regions. - * - * @param base SYSMPU peripheral base address. - */ -void SYSMPU_Deinit(SYSMPU_Type *base); - -/* @}*/ - -/*! - * @name Basic Control Operations - * @{ - */ - -/*! - * @brief Enables/disables the SYSMPU globally. - * - * Call this API to enable or disable the SYSMPU module. - * - * @param base SYSMPU peripheral base address. - * @param enable True enable SYSMPU, false disable SYSMPU. - */ -static inline void SYSMPU_Enable(SYSMPU_Type *base, bool enable) -{ - if (enable) - { - /* Enable the SYSMPU globally. */ - base->CESR |= SYSMPU_CESR_VLD_MASK; - } - else - { /* Disable the SYSMPU globally. */ - base->CESR &= ~SYSMPU_CESR_VLD_MASK; - } -} - -/*! - * @brief Enables/disables the SYSMPU for a special region. - * - * When SYSMPU is enabled, call this API to disable an unused region - * of an enabled SYSMPU. Call this API to minimize the power dissipation. - * - * @param base SYSMPU peripheral base address. - * @param number SYSMPU region number. - * @param enable True enable the special region SYSMPU, false disable the special region SYSMPU. - */ -static inline void SYSMPU_RegionEnable(SYSMPU_Type *base, uint32_t number, bool enable) -{ - if (enable) - { - /* Enable the #number region SYSMPU. */ - base->WORD[number][3] |= SYSMPU_WORD_VLD_MASK; - } - else - { /* Disable the #number region SYSMPU. */ - base->WORD[number][3] &= ~SYSMPU_WORD_VLD_MASK; - } -} - -/*! - * @brief Gets the SYSMPU basic hardware information. - * - * @param base SYSMPU peripheral base address. - * @param hardwareInform The pointer to the SYSMPU hardware information structure. See "sysmpu_hardware_info_t". - */ -void SYSMPU_GetHardwareInfo(SYSMPU_Type *base, sysmpu_hardware_info_t *hardwareInform); - -/*! - * @brief Sets the SYSMPU region. - * - * Note: Due to the SYSMPU protection, the region number 0 does not allow writes from - * core to affect the start and end address nor the permissions associated with - * the debugger. It can only write the permission fields associated - * with the other masters. - * - * @param base SYSMPU peripheral base address. - * @param regionConfig The pointer to the SYSMPU user configuration structure. See "sysmpu_region_config_t". - */ -void SYSMPU_SetRegionConfig(SYSMPU_Type *base, const sysmpu_region_config_t *regionConfig); - -/*! - * @brief Sets the region start and end address. - * - * Memory region start address. Note: bit0 ~ bit4 is always marked as 0 by SYSMPU. - * The actual start address by SYSMPU is 0-modulo-32 byte address. - * Memory region end address. Note: bit0 ~ bit4 always be marked as 1 by SYSMPU. - * The end address used by the SYSMPU is 31-modulo-32 byte address. - * Note: Due to the SYSMPU protection, the startAddr and endAddr can't be - * changed by the core when regionNum is 0. - * - * @param base SYSMPU peripheral base address. - * @param regionNum SYSMPU region number. The range is from 0 to - * FSL_FEATURE_SYSMPU_DESCRIPTOR_COUNT - 1. - * @param startAddr Region start address. - * @param endAddr Region end address. - */ -void SYSMPU_SetRegionAddr(SYSMPU_Type *base, uint32_t regionNum, uint32_t startAddr, uint32_t endAddr); - -/*! - * @brief Sets the SYSMPU region access rights for masters with read, write, and execute rights. - * The SYSMPU access rights depend on two board classifications of bus masters. - * The privilege rights masters and the normal rights masters. - * The privilege rights masters have the read, write, and execute access rights. - * Except the normal read and write rights, the execute rights are also - * allowed for these masters. The privilege rights masters normally range from - * bus masters 0 - 3. However, the maximum master number is device-specific. - * See the "SYSMPU_PRIVILEGED_RIGHTS_MASTER_MAX_INDEX". - * The normal rights masters access rights control see - * "SYSMPU_SetRegionRwMasterAccessRights()". - * - * @param base SYSMPU peripheral base address. - * @param regionNum SYSMPU region number. Should range from 0 to - * FSL_FEATURE_SYSMPU_DESCRIPTOR_COUNT - 1. - * @param masterNum SYSMPU bus master number. Should range from 0 to - * SYSMPU_PRIVILEGED_RIGHTS_MASTER_MAX_INDEX. - * @param accessRights The pointer to the SYSMPU access rights configuration. See "sysmpu_rwxrights_master_access_control_t". - */ -void SYSMPU_SetRegionRwxMasterAccessRights(SYSMPU_Type *base, - uint32_t regionNum, - uint32_t masterNum, - const sysmpu_rwxrights_master_access_control_t *accessRights); -#if FSL_FEATURE_SYSMPU_MASTER_COUNT > 4 -/*! - * @brief Sets the SYSMPU region access rights for masters with read and write rights. - * The SYSMPU access rights depend on two board classifications of bus masters. - * The privilege rights masters and the normal rights masters. - * The normal rights masters only have the read and write access permissions. - * The privilege rights access control see "SYSMPU_SetRegionRwxMasterAccessRights". - * - * @param base SYSMPU peripheral base address. - * @param regionNum SYSMPU region number. The range is from 0 to - * FSL_FEATURE_SYSMPU_DESCRIPTOR_COUNT - 1. - * @param masterNum SYSMPU bus master number. Should range from SYSMPU_MASTER_RWATTRIBUTE_START_PORT - * to ~ FSL_FEATURE_SYSMPU_MASTER_COUNT - 1. - * @param accessRights The pointer to the SYSMPU access rights configuration. See "sysmpu_rwrights_master_access_control_t". - */ -void SYSMPU_SetRegionRwMasterAccessRights(SYSMPU_Type *base, - uint32_t regionNum, - uint32_t masterNum, - const sysmpu_rwrights_master_access_control_t *accessRights); -#endif /* FSL_FEATURE_SYSMPU_MASTER_COUNT > 4 */ -/*! - * @brief Gets the numbers of slave ports where errors occur. - * - * @param base SYSMPU peripheral base address. - * @param slaveNum SYSMPU slave port number. - * @return The slave ports error status. - * true - error happens in this slave port. - * false - error didn't happen in this slave port. - */ -bool SYSMPU_GetSlavePortErrorStatus(SYSMPU_Type *base, sysmpu_slave_t slaveNum); - -/*! - * @brief Gets the SYSMPU detailed error access information. - * - * @param base SYSMPU peripheral base address. - * @param slaveNum SYSMPU slave port number. - * @param errInform The pointer to the SYSMPU access error information. See "sysmpu_access_err_info_t". - */ -void SYSMPU_GetDetailErrorAccessInfo(SYSMPU_Type *base, sysmpu_slave_t slaveNum, sysmpu_access_err_info_t *errInform); - -/* @} */ - -#if defined(__cplusplus) -} -#endif - -/*! @}*/ - -#endif /* _FSL_SYSMPU_H_ */ diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_uart.c b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_uart.c deleted file mode 100644 index 17d9260027b..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_uart.c +++ /dev/null @@ -1,1230 +0,0 @@ -/* - * Copyright (c) 2015-2016, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "fsl_uart.h" - -/******************************************************************************* - * Definitions - ******************************************************************************/ - -/* UART transfer state. */ -enum _uart_tansfer_states -{ - kUART_TxIdle, /* TX idle. */ - kUART_TxBusy, /* TX busy. */ - kUART_RxIdle, /* RX idle. */ - kUART_RxBusy, /* RX busy. */ - kUART_RxFramingError, /* Rx framing error */ - kUART_RxParityError /* Rx parity error */ -}; - -/* Typedef for interrupt handler. */ -typedef void (*uart_isr_t)(UART_Type *base, uart_handle_t *handle); - -/******************************************************************************* - * Prototypes - ******************************************************************************/ - -/*! - * @brief Get the UART instance from peripheral base address. - * - * @param base UART peripheral base address. - * @return UART instance. - */ -uint32_t UART_GetInstance(UART_Type *base); - -/*! - * @brief Get the length of received data in RX ring buffer. - * - * @param handle UART handle pointer. - * @return Length of received data in RX ring buffer. - */ -static size_t UART_TransferGetRxRingBufferLength(uart_handle_t *handle); - -/*! - * @brief Check whether the RX ring buffer is full. - * - * @param handle UART handle pointer. - * @retval true RX ring buffer is full. - * @retval false RX ring buffer is not full. - */ -static bool UART_TransferIsRxRingBufferFull(uart_handle_t *handle); - -/*! - * @brief Read RX register using non-blocking method. - * - * This function reads data from the TX register directly, upper layer must make - * sure the RX register is full or TX FIFO has data before calling this function. - * - * @param base UART peripheral base address. - * @param data Start addresss of the buffer to store the received data. - * @param length Size of the buffer. - */ -static void UART_ReadNonBlocking(UART_Type *base, uint8_t *data, size_t length); - -/*! - * @brief Write to TX register using non-blocking method. - * - * This function writes data to the TX register directly, upper layer must make - * sure the TX register is empty or TX FIFO has empty room before calling this function. - * - * @note This function does not check whether all the data has been sent out to bus, - * so before disable TX, check kUART_TransmissionCompleteFlag to ensure the TX is - * finished. - * - * @param base UART peripheral base address. - * @param data Start addresss of the data to write. - * @param length Size of the buffer to be sent. - */ -static void UART_WriteNonBlocking(UART_Type *base, const uint8_t *data, size_t length); - -/******************************************************************************* - * Variables - ******************************************************************************/ -/* Array of UART handle. */ -#if (defined(UART5)) -#define UART_HANDLE_ARRAY_SIZE 6 -#else /* UART5 */ -#if (defined(UART4)) -#define UART_HANDLE_ARRAY_SIZE 5 -#else /* UART4 */ -#if (defined(UART3)) -#define UART_HANDLE_ARRAY_SIZE 4 -#else /* UART3 */ -#if (defined(UART2)) -#define UART_HANDLE_ARRAY_SIZE 3 -#else /* UART2 */ -#if (defined(UART1)) -#define UART_HANDLE_ARRAY_SIZE 2 -#else /* UART1 */ -#if (defined(UART0)) -#define UART_HANDLE_ARRAY_SIZE 1 -#else /* UART0 */ -#error No UART instance. -#endif /* UART 0 */ -#endif /* UART 1 */ -#endif /* UART 2 */ -#endif /* UART 3 */ -#endif /* UART 4 */ -#endif /* UART 5 */ -static uart_handle_t *s_uartHandle[UART_HANDLE_ARRAY_SIZE]; -/* Array of UART peripheral base address. */ -static UART_Type *const s_uartBases[] = UART_BASE_PTRS; - -/* Array of UART IRQ number. */ -static const IRQn_Type s_uartIRQ[] = UART_RX_TX_IRQS; -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) -/* Array of UART clock name. */ -static const clock_ip_name_t s_uartClock[] = UART_CLOCKS; -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ - -/* UART ISR for transactional APIs. */ -static uart_isr_t s_uartIsr; - -/******************************************************************************* - * Code - ******************************************************************************/ - -uint32_t UART_GetInstance(UART_Type *base) -{ - uint32_t instance; - uint32_t uartArrayCount = (sizeof(s_uartBases) / sizeof(s_uartBases[0])); - - /* Find the instance index from base address mappings. */ - for (instance = 0; instance < uartArrayCount; instance++) - { - if (s_uartBases[instance] == base) - { - break; - } - } - - assert(instance < uartArrayCount); - - return instance; -} - -static size_t UART_TransferGetRxRingBufferLength(uart_handle_t *handle) -{ - assert(handle); - - size_t size; - - if (handle->rxRingBufferTail > handle->rxRingBufferHead) - { - size = (size_t)(handle->rxRingBufferHead + handle->rxRingBufferSize - handle->rxRingBufferTail); - } - else - { - size = (size_t)(handle->rxRingBufferHead - handle->rxRingBufferTail); - } - - return size; -} - -static bool UART_TransferIsRxRingBufferFull(uart_handle_t *handle) -{ - assert(handle); - - bool full; - - if (UART_TransferGetRxRingBufferLength(handle) == (handle->rxRingBufferSize - 1U)) - { - full = true; - } - else - { - full = false; - } - - return full; -} - -status_t UART_Init(UART_Type *base, const uart_config_t *config, uint32_t srcClock_Hz) -{ - assert(config); - assert(config->baudRate_Bps); -#if defined(FSL_FEATURE_UART_HAS_FIFO) && FSL_FEATURE_UART_HAS_FIFO - assert(FSL_FEATURE_UART_FIFO_SIZEn(base) >= config->txFifoWatermark); - assert(FSL_FEATURE_UART_FIFO_SIZEn(base) >= config->rxFifoWatermark); -#endif - - uint16_t sbr = 0; - uint8_t temp = 0; - uint32_t baudDiff = 0; - - /* Calculate the baud rate modulo divisor, sbr*/ - sbr = srcClock_Hz / (config->baudRate_Bps * 16); - /* set sbrTemp to 1 if the sourceClockInHz can not satisfy the desired baud rate */ - if (sbr == 0) - { - sbr = 1; - } -#if defined(FSL_FEATURE_UART_HAS_BAUD_RATE_FINE_ADJUST_SUPPORT) && FSL_FEATURE_UART_HAS_BAUD_RATE_FINE_ADJUST_SUPPORT - /* Determine if a fractional divider is needed to fine tune closer to the - * desired baud, each value of brfa is in 1/32 increments, - * hence the multiply-by-32. */ - uint32_t tempBaud = 0; - - uint16_t brfa = (2 * srcClock_Hz / (config->baudRate_Bps)) - 32 * sbr; - - /* Calculate the baud rate based on the temporary SBR values and BRFA */ - tempBaud = (srcClock_Hz * 2 / ((sbr * 32 + brfa))); - baudDiff = - (tempBaud > config->baudRate_Bps) ? (tempBaud - config->baudRate_Bps) : (config->baudRate_Bps - tempBaud); - -#else - /* Calculate the baud rate based on the temporary SBR values */ - baudDiff = (srcClock_Hz / (sbr * 16)) - config->baudRate_Bps; - - /* Select the better value between sbr and (sbr + 1) */ - if (baudDiff > (config->baudRate_Bps - (srcClock_Hz / (16 * (sbr + 1))))) - { - baudDiff = config->baudRate_Bps - (srcClock_Hz / (16 * (sbr + 1))); - sbr++; - } -#endif - - /* next, check to see if actual baud rate is within 3% of desired baud rate - * based on the calculate SBR value */ - if (baudDiff > ((config->baudRate_Bps / 100) * 3)) - { - /* Unacceptable baud rate difference of more than 3%*/ - return kStatus_UART_BaudrateNotSupport; - } - -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) - /* Enable uart clock */ - CLOCK_EnableClock(s_uartClock[UART_GetInstance(base)]); -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ - - /* Disable UART TX RX before setting. */ - base->C2 &= ~(UART_C2_TE_MASK | UART_C2_RE_MASK); - - /* Write the sbr value to the BDH and BDL registers*/ - base->BDH = (base->BDH & ~UART_BDH_SBR_MASK) | (uint8_t)(sbr >> 8); - base->BDL = (uint8_t)sbr; - -#if defined(FSL_FEATURE_UART_HAS_BAUD_RATE_FINE_ADJUST_SUPPORT) && FSL_FEATURE_UART_HAS_BAUD_RATE_FINE_ADJUST_SUPPORT - /* Write the brfa value to the register*/ - base->C4 = (base->C4 & ~UART_C4_BRFA_MASK) | (brfa & UART_C4_BRFA_MASK); -#endif - - /* Set bit count and parity mode. */ - temp = base->C1 & ~(UART_C1_PE_MASK | UART_C1_PT_MASK | UART_C1_M_MASK); - - if (kUART_ParityDisabled != config->parityMode) - { - temp |= (UART_C1_M_MASK | (uint8_t)config->parityMode); - } - - base->C1 = temp; - -#if defined(FSL_FEATURE_UART_HAS_STOP_BIT_CONFIG_SUPPORT) && FSL_FEATURE_UART_HAS_STOP_BIT_CONFIG_SUPPORT - /* Set stop bit per char */ - base->BDH = (base->BDH & ~UART_BDH_SBNS_MASK) | UART_BDH_SBNS((uint8_t)config->stopBitCount); -#endif - -#if defined(FSL_FEATURE_UART_HAS_FIFO) && FSL_FEATURE_UART_HAS_FIFO - /* Set tx/rx FIFO watermark */ - base->TWFIFO = config->txFifoWatermark; - base->RWFIFO = config->rxFifoWatermark; - - /* Enable tx/rx FIFO */ - base->PFIFO |= (UART_PFIFO_TXFE_MASK | UART_PFIFO_RXFE_MASK); - - /* Flush FIFO */ - base->CFIFO |= (UART_CFIFO_TXFLUSH_MASK | UART_CFIFO_RXFLUSH_MASK); -#endif - - /* Enable TX/RX base on configure structure. */ - temp = base->C2; - - if (config->enableTx) - { - temp |= UART_C2_TE_MASK; - } - - if (config->enableRx) - { - temp |= UART_C2_RE_MASK; - } - - base->C2 = temp; - - return kStatus_Success; -} - -void UART_Deinit(UART_Type *base) -{ -#if defined(FSL_FEATURE_UART_HAS_FIFO) && FSL_FEATURE_UART_HAS_FIFO - /* Wait tx FIFO send out*/ - while (0 != base->TCFIFO) - { - } -#endif - /* Wait last char shoft out */ - while (0 == (base->S1 & UART_S1_TC_MASK)) - { - } - - /* Disable the module. */ - base->C2 = 0; - -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) - /* Disable uart clock */ - CLOCK_DisableClock(s_uartClock[UART_GetInstance(base)]); -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ -} - -void UART_GetDefaultConfig(uart_config_t *config) -{ - assert(config); - - config->baudRate_Bps = 115200U; - config->parityMode = kUART_ParityDisabled; -#if defined(FSL_FEATURE_UART_HAS_STOP_BIT_CONFIG_SUPPORT) && FSL_FEATURE_UART_HAS_STOP_BIT_CONFIG_SUPPORT - config->stopBitCount = kUART_OneStopBit; -#endif -#if defined(FSL_FEATURE_UART_HAS_FIFO) && FSL_FEATURE_UART_HAS_FIFO - config->txFifoWatermark = 0; - config->rxFifoWatermark = 1; -#endif - config->enableTx = false; - config->enableRx = false; -} - -status_t UART_SetBaudRate(UART_Type *base, uint32_t baudRate_Bps, uint32_t srcClock_Hz) -{ - assert(baudRate_Bps); - - uint16_t sbr = 0; - uint32_t baudDiff = 0; - uint8_t oldCtrl; - - /* Calculate the baud rate modulo divisor, sbr*/ - sbr = srcClock_Hz / (baudRate_Bps * 16); - /* set sbrTemp to 1 if the sourceClockInHz can not satisfy the desired baud rate */ - if (sbr == 0) - { - sbr = 1; - } -#if defined(FSL_FEATURE_UART_HAS_BAUD_RATE_FINE_ADJUST_SUPPORT) && FSL_FEATURE_UART_HAS_BAUD_RATE_FINE_ADJUST_SUPPORT - /* Determine if a fractional divider is needed to fine tune closer to the - * desired baud, each value of brfa is in 1/32 increments, - * hence the multiply-by-32. */ - uint32_t tempBaud = 0; - - uint16_t brfa = (2 * srcClock_Hz / (baudRate_Bps)) - 32 * sbr; - - /* Calculate the baud rate based on the temporary SBR values and BRFA */ - tempBaud = (srcClock_Hz * 2 / ((sbr * 32 + brfa))); - baudDiff = (tempBaud > baudRate_Bps) ? (tempBaud - baudRate_Bps) : (baudRate_Bps - tempBaud); -#else - /* Calculate the baud rate based on the temporary SBR values */ - baudDiff = (srcClock_Hz / (sbr * 16)) - baudRate_Bps; - - /* Select the better value between sbr and (sbr + 1) */ - if (baudDiff > (baudRate_Bps - (srcClock_Hz / (16 * (sbr + 1))))) - { - baudDiff = baudRate_Bps - (srcClock_Hz / (16 * (sbr + 1))); - sbr++; - } -#endif - - /* next, check to see if actual baud rate is within 3% of desired baud rate - * based on the calculate SBR value */ - if (baudDiff < ((baudRate_Bps / 100) * 3)) - { - /* Store C2 before disable Tx and Rx */ - oldCtrl = base->C2; - - /* Disable UART TX RX before setting. */ - base->C2 &= ~(UART_C2_TE_MASK | UART_C2_RE_MASK); - - /* Write the sbr value to the BDH and BDL registers*/ - base->BDH = (base->BDH & ~UART_BDH_SBR_MASK) | (uint8_t)(sbr >> 8); - base->BDL = (uint8_t)sbr; - -#if defined(FSL_FEATURE_UART_HAS_BAUD_RATE_FINE_ADJUST_SUPPORT) && FSL_FEATURE_UART_HAS_BAUD_RATE_FINE_ADJUST_SUPPORT - /* Write the brfa value to the register*/ - base->C4 = (base->C4 & ~UART_C4_BRFA_MASK) | (brfa & UART_C4_BRFA_MASK); -#endif - /* Restore C2. */ - base->C2 = oldCtrl; - - return kStatus_Success; - } - else - { - /* Unacceptable baud rate difference of more than 3%*/ - return kStatus_UART_BaudrateNotSupport; - } -} - -void UART_EnableInterrupts(UART_Type *base, uint32_t mask) -{ - mask &= kUART_AllInterruptsEnable; - - /* The interrupt mask is combined by control bits from several register: ((CFIFO<<24) | (C3<<16) | (C2<<8) |(BDH)) - */ - base->BDH |= mask; - base->C2 |= (mask >> 8); - base->C3 |= (mask >> 16); - -#if defined(FSL_FEATURE_UART_HAS_FIFO) && FSL_FEATURE_UART_HAS_FIFO - base->CFIFO |= (mask >> 24); -#endif -} - -void UART_DisableInterrupts(UART_Type *base, uint32_t mask) -{ - mask &= kUART_AllInterruptsEnable; - - /* The interrupt mask is combined by control bits from several register: ((CFIFO<<24) | (C3<<16) | (C2<<8) |(BDH)) - */ - base->BDH &= ~mask; - base->C2 &= ~(mask >> 8); - base->C3 &= ~(mask >> 16); - -#if defined(FSL_FEATURE_UART_HAS_FIFO) && FSL_FEATURE_UART_HAS_FIFO - base->CFIFO &= ~(mask >> 24); -#endif -} - -uint32_t UART_GetEnabledInterrupts(UART_Type *base) -{ - uint32_t temp; - - temp = base->BDH | ((uint32_t)(base->C2) << 8) | ((uint32_t)(base->C3) << 16); - -#if defined(FSL_FEATURE_UART_HAS_FIFO) && FSL_FEATURE_UART_HAS_FIFO - temp |= ((uint32_t)(base->CFIFO) << 24); -#endif - - return temp & kUART_AllInterruptsEnable; -} - -uint32_t UART_GetStatusFlags(UART_Type *base) -{ - uint32_t status_flag; - - status_flag = base->S1 | ((uint32_t)(base->S2) << 8); - -#if defined(FSL_FEATURE_UART_HAS_EXTENDED_DATA_REGISTER_FLAGS) && FSL_FEATURE_UART_HAS_EXTENDED_DATA_REGISTER_FLAGS - status_flag |= ((uint32_t)(base->ED) << 16); -#endif - -#if defined(FSL_FEATURE_UART_HAS_FIFO) && FSL_FEATURE_UART_HAS_FIFO - status_flag |= ((uint32_t)(base->SFIFO) << 24); -#endif - - return status_flag; -} - -status_t UART_ClearStatusFlags(UART_Type *base, uint32_t mask) -{ - uint8_t reg = base->S2; - status_t status; - -#if defined(FSL_FEATURE_UART_HAS_LIN_BREAK_DETECT) && FSL_FEATURE_UART_HAS_LIN_BREAK_DETECT - reg &= ~(UART_S2_RXEDGIF_MASK | UART_S2_LBKDIF_MASK); -#else - reg &= ~UART_S2_RXEDGIF_MASK; -#endif - - base->S2 = reg | (uint8_t)(mask >> 8); - -#if defined(FSL_FEATURE_UART_HAS_FIFO) && FSL_FEATURE_UART_HAS_FIFO - base->SFIFO = (uint8_t)(mask >> 24); -#endif - - if (mask & (kUART_IdleLineFlag | kUART_NoiseErrorFlag | kUART_FramingErrorFlag | kUART_ParityErrorFlag)) - { - /* Read base->D to clear the flags. */ - (void)base->S1; - (void)base->D; - } - - if (mask & kUART_RxOverrunFlag) - { - /* Read base->D to clear the flags and Flush all data in FIFO. */ - (void)base->S1; - (void)base->D; -#if defined(FSL_FEATURE_UART_HAS_FIFO) && FSL_FEATURE_UART_HAS_FIFO - /* Flush FIFO date, otherwise FIFO pointer will be in unknown state. */ - base->CFIFO |= UART_CFIFO_RXFLUSH_MASK; -#endif - } - - /* If some flags still pending. */ - if (mask & UART_GetStatusFlags(base)) - { - /* Some flags can only clear or set by the hardware itself, these flags are: kUART_TxDataRegEmptyFlag, - kUART_TransmissionCompleteFlag, kUART_RxDataRegFullFlag, kUART_RxActiveFlag, kUART_NoiseErrorInRxDataRegFlag, - kUART_ParityErrorInRxDataRegFlag, kUART_TxFifoEmptyFlag, kUART_RxFifoEmptyFlag. */ - status = kStatus_UART_FlagCannotClearManually; - } - else - { - status = kStatus_Success; - } - - return status; -} - -void UART_WriteBlocking(UART_Type *base, const uint8_t *data, size_t length) -{ - /* This API can only ensure that the data is written into the data buffer but can't - ensure all data in the data buffer are sent into the transmit shift buffer. */ - while (length--) - { - while (!(base->S1 & UART_S1_TDRE_MASK)) - { - } - base->D = *(data++); - } -} - -static void UART_WriteNonBlocking(UART_Type *base, const uint8_t *data, size_t length) -{ - assert(data); - - size_t i; - - /* The Non Blocking write data API assume user have ensured there is enough space in - peripheral to write. */ - for (i = 0; i < length; i++) - { - base->D = data[i]; - } -} - -status_t UART_ReadBlocking(UART_Type *base, uint8_t *data, size_t length) -{ - assert(data); - - uint32_t statusFlag; - - while (length--) - { -#if defined(FSL_FEATURE_UART_HAS_FIFO) && FSL_FEATURE_UART_HAS_FIFO - while (!base->RCFIFO) -#else - while (!(base->S1 & UART_S1_RDRF_MASK)) -#endif - { - statusFlag = UART_GetStatusFlags(base); - - if (statusFlag & kUART_RxOverrunFlag) - { - return kStatus_UART_RxHardwareOverrun; - } - - if (statusFlag & kUART_NoiseErrorFlag) - { - return kStatus_UART_NoiseError; - } - - if (statusFlag & kUART_FramingErrorFlag) - { - return kStatus_UART_FramingError; - } - - if (statusFlag & kUART_ParityErrorFlag) - { - return kStatus_UART_ParityError; - } - } - *(data++) = base->D; - } - - return kStatus_Success; -} - -static void UART_ReadNonBlocking(UART_Type *base, uint8_t *data, size_t length) -{ - assert(data); - - size_t i; - - /* The Non Blocking read data API assume user have ensured there is enough space in - peripheral to write. */ - for (i = 0; i < length; i++) - { - data[i] = base->D; - } -} - -void UART_TransferCreateHandle(UART_Type *base, - uart_handle_t *handle, - uart_transfer_callback_t callback, - void *userData) -{ - assert(handle); - - uint32_t instance; - - /* Zero the handle. */ - memset(handle, 0, sizeof(*handle)); - - /* Set the TX/RX state. */ - handle->rxState = kUART_RxIdle; - handle->txState = kUART_TxIdle; - - /* Set the callback and user data. */ - handle->callback = callback; - handle->userData = userData; - -#if defined(FSL_FEATURE_UART_HAS_FIFO) && FSL_FEATURE_UART_HAS_FIFO - /* Note: - Take care of the RX FIFO, RX interrupt request only assert when received bytes - equal or more than RX water mark, there is potential issue if RX water - mark larger than 1. - For example, if RX FIFO water mark is 2, upper layer needs 5 bytes and - 5 bytes are received. the last byte will be saved in FIFO but not trigger - RX interrupt because the water mark is 2. - */ - base->RWFIFO = 1U; -#endif - - /* Get instance from peripheral base address. */ - instance = UART_GetInstance(base); - - /* Save the handle in global variables to support the double weak mechanism. */ - s_uartHandle[instance] = handle; - - s_uartIsr = UART_TransferHandleIRQ; - /* Enable interrupt in NVIC. */ - EnableIRQ(s_uartIRQ[instance]); -} - -void UART_TransferStartRingBuffer(UART_Type *base, uart_handle_t *handle, uint8_t *ringBuffer, size_t ringBufferSize) -{ - assert(handle); - assert(ringBuffer); - - /* Setup the ringbuffer address */ - handle->rxRingBuffer = ringBuffer; - handle->rxRingBufferSize = ringBufferSize; - handle->rxRingBufferHead = 0U; - handle->rxRingBufferTail = 0U; - - /* Enable the interrupt to accept the data when user need the ring buffer. */ - UART_EnableInterrupts( - base, kUART_RxDataRegFullInterruptEnable | kUART_RxOverrunInterruptEnable | kUART_FramingErrorInterruptEnable); - /* Enable parity error interrupt when parity mode is enable*/ - if (UART_C1_PE_MASK & base->C1) - { - UART_EnableInterrupts(base, kUART_ParityErrorInterruptEnable); - } -} - -void UART_TransferStopRingBuffer(UART_Type *base, uart_handle_t *handle) -{ - assert(handle); - - if (handle->rxState == kUART_RxIdle) - { - UART_DisableInterrupts(base, kUART_RxDataRegFullInterruptEnable | kUART_RxOverrunInterruptEnable | - kUART_FramingErrorInterruptEnable); - /* Disable parity error interrupt when parity mode is enable*/ - if (UART_C1_PE_MASK & base->C1) - { - UART_DisableInterrupts(base, kUART_ParityErrorInterruptEnable); - } - } - - handle->rxRingBuffer = NULL; - handle->rxRingBufferSize = 0U; - handle->rxRingBufferHead = 0U; - handle->rxRingBufferTail = 0U; -} - -status_t UART_TransferSendNonBlocking(UART_Type *base, uart_handle_t *handle, uart_transfer_t *xfer) -{ - assert(handle); - assert(xfer); - assert(xfer->dataSize); - assert(xfer->data); - - status_t status; - - /* Return error if current TX busy. */ - if (kUART_TxBusy == handle->txState) - { - status = kStatus_UART_TxBusy; - } - else - { - handle->txData = xfer->data; - handle->txDataSize = xfer->dataSize; - handle->txDataSizeAll = xfer->dataSize; - handle->txState = kUART_TxBusy; - - /* Enable transmiter interrupt. */ - UART_EnableInterrupts(base, kUART_TxDataRegEmptyInterruptEnable); - - status = kStatus_Success; - } - - return status; -} - -void UART_TransferAbortSend(UART_Type *base, uart_handle_t *handle) -{ - assert(handle); - - UART_DisableInterrupts(base, kUART_TxDataRegEmptyInterruptEnable | kUART_TransmissionCompleteInterruptEnable); - - handle->txDataSize = 0; - handle->txState = kUART_TxIdle; -} - -status_t UART_TransferGetSendCount(UART_Type *base, uart_handle_t *handle, uint32_t *count) -{ - assert(handle); - assert(count); - - if (kUART_TxIdle == handle->txState) - { - return kStatus_NoTransferInProgress; - } - - *count = handle->txDataSizeAll - handle->txDataSize; - - return kStatus_Success; -} - -status_t UART_TransferReceiveNonBlocking(UART_Type *base, - uart_handle_t *handle, - uart_transfer_t *xfer, - size_t *receivedBytes) -{ - assert(handle); - assert(xfer); - assert(xfer->data); - assert(xfer->dataSize); - - uint32_t i; - status_t status; - /* How many bytes to copy from ring buffer to user memory. */ - size_t bytesToCopy = 0U; - /* How many bytes to receive. */ - size_t bytesToReceive; - /* How many bytes currently have received. */ - size_t bytesCurrentReceived; - - /* How to get data: - 1. If RX ring buffer is not enabled, then save xfer->data and xfer->dataSize - to uart handle, enable interrupt to store received data to xfer->data. When - all data received, trigger callback. - 2. If RX ring buffer is enabled and not empty, get data from ring buffer first. - If there are enough data in ring buffer, copy them to xfer->data and return. - If there are not enough data in ring buffer, copy all of them to xfer->data, - save the xfer->data remained empty space to uart handle, receive data - to this empty space and trigger callback when finished. */ - - if (kUART_RxBusy == handle->rxState) - { - status = kStatus_UART_RxBusy; - } - else - { - bytesToReceive = xfer->dataSize; - bytesCurrentReceived = 0U; - - /* If RX ring buffer is used. */ - if (handle->rxRingBuffer) - { - /* Disable UART RX IRQ, protect ring buffer. */ - UART_DisableInterrupts(base, kUART_RxDataRegFullInterruptEnable); - - /* How many bytes in RX ring buffer currently. */ - bytesToCopy = UART_TransferGetRxRingBufferLength(handle); - - if (bytesToCopy) - { - bytesToCopy = MIN(bytesToReceive, bytesToCopy); - - bytesToReceive -= bytesToCopy; - - /* Copy data from ring buffer to user memory. */ - for (i = 0U; i < bytesToCopy; i++) - { - xfer->data[bytesCurrentReceived++] = handle->rxRingBuffer[handle->rxRingBufferTail]; - - /* Wrap to 0. Not use modulo (%) because it might be large and slow. */ - if (handle->rxRingBufferTail + 1U == handle->rxRingBufferSize) - { - handle->rxRingBufferTail = 0U; - } - else - { - handle->rxRingBufferTail++; - } - } - } - - /* If ring buffer does not have enough data, still need to read more data. */ - if (bytesToReceive) - { - /* No data in ring buffer, save the request to UART handle. */ - handle->rxData = xfer->data + bytesCurrentReceived; - handle->rxDataSize = bytesToReceive; - handle->rxDataSizeAll = bytesToReceive; - handle->rxState = kUART_RxBusy; - } - - /* Enable UART RX IRQ if previously enabled. */ - UART_EnableInterrupts(base, kUART_RxDataRegFullInterruptEnable); - - /* Call user callback since all data are received. */ - if (0 == bytesToReceive) - { - if (handle->callback) - { - handle->callback(base, handle, kStatus_UART_RxIdle, handle->userData); - } - } - } - /* Ring buffer not used. */ - else - { - handle->rxData = xfer->data + bytesCurrentReceived; - handle->rxDataSize = bytesToReceive; - handle->rxDataSizeAll = bytesToReceive; - handle->rxState = kUART_RxBusy; - - /* Enable RX/Rx overrun/framing error interrupt. */ - UART_EnableInterrupts(base, kUART_RxDataRegFullInterruptEnable | kUART_RxOverrunInterruptEnable | - kUART_FramingErrorInterruptEnable); - /* Enable parity error interrupt when parity mode is enable*/ - if (UART_C1_PE_MASK & base->C1) - { - UART_EnableInterrupts(base, kUART_ParityErrorInterruptEnable); - } - } - - /* Return the how many bytes have read. */ - if (receivedBytes) - { - *receivedBytes = bytesCurrentReceived; - } - - status = kStatus_Success; - } - - return status; -} - -void UART_TransferAbortReceive(UART_Type *base, uart_handle_t *handle) -{ - assert(handle); - - /* Only abort the receive to handle->rxData, the RX ring buffer is still working. */ - if (!handle->rxRingBuffer) - { - /* Disable RX interrupt. */ - UART_DisableInterrupts(base, kUART_RxDataRegFullInterruptEnable | kUART_RxOverrunInterruptEnable | - kUART_FramingErrorInterruptEnable); - /* Disable parity error interrupt when parity mode is enable*/ - if (UART_C1_PE_MASK & base->C1) - { - UART_DisableInterrupts(base, kUART_ParityErrorInterruptEnable); - } - } - - handle->rxDataSize = 0U; - handle->rxState = kUART_RxIdle; -} - -status_t UART_TransferGetReceiveCount(UART_Type *base, uart_handle_t *handle, uint32_t *count) -{ - assert(handle); - assert(count); - - if (kUART_RxIdle == handle->rxState) - { - return kStatus_NoTransferInProgress; - } - - if (!count) - { - return kStatus_InvalidArgument; - } - - *count = handle->rxDataSizeAll - handle->rxDataSize; - - return kStatus_Success; -} - -void UART_TransferHandleIRQ(UART_Type *base, uart_handle_t *handle) -{ - assert(handle); - - uint8_t count; - uint8_t tempCount; - - /* If RX framing error */ - if (UART_S1_FE_MASK & base->S1) - { - /* Read base->D to clear framing error flag, otherwise the RX does not work. */ - while (base->S1 & UART_S1_RDRF_MASK) - { - (void)base->D; - } -#if defined(FSL_FEATURE_UART_HAS_FIFO) && FSL_FEATURE_UART_HAS_FIFO - /* Flush FIFO date, otherwise FIFO pointer will be in unknown state. */ - base->CFIFO |= UART_CFIFO_RXFLUSH_MASK; -#endif - - handle->rxState = kUART_RxFramingError; - handle->rxDataSize = 0U; - /* Trigger callback. */ - if (handle->callback) - { - handle->callback(base, handle, kStatus_UART_FramingError, handle->userData); - } - } - - /* If RX parity error */ - if (UART_S1_PF_MASK & base->S1) - { - /* Read base->D to clear parity error flag, otherwise the RX does not work. */ - while (base->S1 & UART_S1_RDRF_MASK) - { - (void)base->D; - } -#if defined(FSL_FEATURE_UART_HAS_FIFO) && FSL_FEATURE_UART_HAS_FIFO - /* Flush FIFO date, otherwise FIFO pointer will be in unknown state. */ - base->CFIFO |= UART_CFIFO_RXFLUSH_MASK; -#endif - - handle->rxState = kUART_RxParityError; - handle->rxDataSize = 0U; - /* Trigger callback. */ - if (handle->callback) - { - handle->callback(base, handle, kStatus_UART_ParityError, handle->userData); - } - } - - /* If RX overrun. */ - if (UART_S1_OR_MASK & base->S1) - { - /* Read base->D to clear overrun flag, otherwise the RX does not work. */ - while (base->S1 & UART_S1_RDRF_MASK) - { - (void)base->D; - } -#if defined(FSL_FEATURE_UART_HAS_FIFO) && FSL_FEATURE_UART_HAS_FIFO - /* Flush FIFO date, otherwise FIFO pointer will be in unknown state. */ - base->CFIFO |= UART_CFIFO_RXFLUSH_MASK; -#endif - /* Trigger callback. */ - if (handle->callback) - { - handle->callback(base, handle, kStatus_UART_RxHardwareOverrun, handle->userData); - } - } - - /* Receive data register full */ - if ((UART_S1_RDRF_MASK & base->S1) && (UART_C2_RIE_MASK & base->C2)) - { -/* Get the size that can be stored into buffer for this interrupt. */ -#if defined(FSL_FEATURE_UART_HAS_FIFO) && FSL_FEATURE_UART_HAS_FIFO - count = base->RCFIFO; -#else - count = 1; -#endif - - /* If handle->rxDataSize is not 0, first save data to handle->rxData. */ - while ((count) && (handle->rxDataSize)) - { -#if defined(FSL_FEATURE_UART_HAS_FIFO) && FSL_FEATURE_UART_HAS_FIFO - tempCount = MIN(handle->rxDataSize, count); -#else - tempCount = 1; -#endif - - /* Using non block API to read the data from the registers. */ - UART_ReadNonBlocking(base, handle->rxData, tempCount); - handle->rxData += tempCount; - handle->rxDataSize -= tempCount; - count -= tempCount; - - /* If all the data required for upper layer is ready, trigger callback. */ - if (!handle->rxDataSize) - { - handle->rxState = kUART_RxIdle; - - if (handle->callback) - { - handle->callback(base, handle, kStatus_UART_RxIdle, handle->userData); - } - } - } - - /* If use RX ring buffer, receive data to ring buffer. */ - if (handle->rxRingBuffer) - { - while (count--) - { - /* If RX ring buffer is full, trigger callback to notify over run. */ - if (UART_TransferIsRxRingBufferFull(handle)) - { - if (handle->callback) - { - handle->callback(base, handle, kStatus_UART_RxRingBufferOverrun, handle->userData); - } - } - - /* If ring buffer is still full after callback function, the oldest data is overrided. */ - if (UART_TransferIsRxRingBufferFull(handle)) - { - /* Increase handle->rxRingBufferTail to make room for new data. */ - if (handle->rxRingBufferTail + 1U == handle->rxRingBufferSize) - { - handle->rxRingBufferTail = 0U; - } - else - { - handle->rxRingBufferTail++; - } - } - - /* Read data. */ - handle->rxRingBuffer[handle->rxRingBufferHead] = base->D; - - /* Increase handle->rxRingBufferHead. */ - if (handle->rxRingBufferHead + 1U == handle->rxRingBufferSize) - { - handle->rxRingBufferHead = 0U; - } - else - { - handle->rxRingBufferHead++; - } - } - } - - else if (!handle->rxDataSize) - { - /* Disable RX interrupt/overrun interrupt/fram error interrupt */ - UART_DisableInterrupts(base, kUART_RxDataRegFullInterruptEnable | kUART_RxOverrunInterruptEnable | - kUART_FramingErrorInterruptEnable); - - /* Disable parity error interrupt when parity mode is enable*/ - if (UART_C1_PE_MASK & base->C1) - { - UART_DisableInterrupts(base, kUART_ParityErrorInterruptEnable); - } - } - else - { - } - } - - /* If framing error or parity error happened, stop the RX interrupt when ues no ring buffer */ - if (((handle->rxState == kUART_RxFramingError) || (handle->rxState == kUART_RxParityError)) && - (!handle->rxRingBuffer)) - { - UART_DisableInterrupts(base, kUART_RxDataRegFullInterruptEnable | kUART_RxOverrunInterruptEnable | - kUART_FramingErrorInterruptEnable); - - /* Disable parity error interrupt when parity mode is enable*/ - if (UART_C1_PE_MASK & base->C1) - { - UART_DisableInterrupts(base, kUART_ParityErrorInterruptEnable); - } - } - - /* Send data register empty and the interrupt is enabled. */ - if ((base->S1 & UART_S1_TDRE_MASK) && (base->C2 & UART_C2_TIE_MASK)) - { -/* Get the bytes that available at this moment. */ -#if defined(FSL_FEATURE_UART_HAS_FIFO) && FSL_FEATURE_UART_HAS_FIFO - count = FSL_FEATURE_UART_FIFO_SIZEn(base) - base->TCFIFO; -#else - count = 1; -#endif - - while ((count) && (handle->txDataSize)) - { -#if defined(FSL_FEATURE_UART_HAS_FIFO) && FSL_FEATURE_UART_HAS_FIFO - tempCount = MIN(handle->txDataSize, count); -#else - tempCount = 1; -#endif - - /* Using non block API to write the data to the registers. */ - UART_WriteNonBlocking(base, handle->txData, tempCount); - handle->txData += tempCount; - handle->txDataSize -= tempCount; - count -= tempCount; - - /* If all the data are written to data register, TX finished. */ - if (!handle->txDataSize) - { - handle->txState = kUART_TxIdle; - - /* Disable TX register empty interrupt. */ - base->C2 = (base->C2 & ~UART_C2_TIE_MASK); - - /* Trigger callback. */ - if (handle->callback) - { - handle->callback(base, handle, kStatus_UART_TxIdle, handle->userData); - } - } - } - } -} - -void UART_TransferHandleErrorIRQ(UART_Type *base, uart_handle_t *handle) -{ - /* To be implemented by User. */ -} - -#if defined(UART0) -#if ((!(defined(FSL_FEATURE_SOC_LPSCI_COUNT))) || \ - ((defined(FSL_FEATURE_SOC_LPSCI_COUNT)) && (FSL_FEATURE_SOC_LPSCI_COUNT == 0))) -void UART0_DriverIRQHandler(void) -{ - s_uartIsr(UART0, s_uartHandle[0]); -} - -void UART0_RX_TX_DriverIRQHandler(void) -{ - UART0_DriverIRQHandler(); -} -#endif -#endif - -#if defined(UART1) -void UART1_DriverIRQHandler(void) -{ - s_uartIsr(UART1, s_uartHandle[1]); -} - -void UART1_RX_TX_DriverIRQHandler(void) -{ - UART1_DriverIRQHandler(); -} -#endif - -#if defined(UART2) -void UART2_DriverIRQHandler(void) -{ - s_uartIsr(UART2, s_uartHandle[2]); -} - -void UART2_RX_TX_DriverIRQHandler(void) -{ - UART2_DriverIRQHandler(); -} -#endif - -#if defined(UART3) -void UART3_DriverIRQHandler(void) -{ - s_uartIsr(UART3, s_uartHandle[3]); -} - -void UART3_RX_TX_DriverIRQHandler(void) -{ - UART3_DriverIRQHandler(); -} -#endif - -#if defined(UART4) -void UART4_DriverIRQHandler(void) -{ - s_uartIsr(UART4, s_uartHandle[4]); -} - -void UART4_RX_TX_DriverIRQHandler(void) -{ - UART4_DriverIRQHandler(); -} -#endif - -#if defined(UART5) -void UART5_DriverIRQHandler(void) -{ - s_uartIsr(UART5, s_uartHandle[5]); -} - -void UART5_RX_TX_DriverIRQHandler(void) -{ - UART5_DriverIRQHandler(); -} -#endif diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_uart.h b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_uart.h deleted file mode 100644 index 451baa9ffd3..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_uart.h +++ /dev/null @@ -1,777 +0,0 @@ -/* - * Copyright (c) 2015-2016, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -#ifndef _FSL_UART_H_ -#define _FSL_UART_H_ - -#include "fsl_common.h" - -/*! - * @addtogroup uart_driver - * @{ - */ - -/******************************************************************************* - * Definitions - ******************************************************************************/ - -/*! @name Driver version */ -/*@{*/ -/*! @brief UART driver version 2.1.4. */ -#define FSL_UART_DRIVER_VERSION (MAKE_VERSION(2, 1, 4)) -/*@}*/ - -/*! @brief Error codes for the UART driver. */ -enum _uart_status -{ - kStatus_UART_TxBusy = MAKE_STATUS(kStatusGroup_UART, 0), /*!< Transmitter is busy. */ - kStatus_UART_RxBusy = MAKE_STATUS(kStatusGroup_UART, 1), /*!< Receiver is busy. */ - kStatus_UART_TxIdle = MAKE_STATUS(kStatusGroup_UART, 2), /*!< UART transmitter is idle. */ - kStatus_UART_RxIdle = MAKE_STATUS(kStatusGroup_UART, 3), /*!< UART receiver is idle. */ - kStatus_UART_TxWatermarkTooLarge = MAKE_STATUS(kStatusGroup_UART, 4), /*!< TX FIFO watermark too large */ - kStatus_UART_RxWatermarkTooLarge = MAKE_STATUS(kStatusGroup_UART, 5), /*!< RX FIFO watermark too large */ - kStatus_UART_FlagCannotClearManually = - MAKE_STATUS(kStatusGroup_UART, 6), /*!< UART flag can't be manually cleared. */ - kStatus_UART_Error = MAKE_STATUS(kStatusGroup_UART, 7), /*!< Error happens on UART. */ - kStatus_UART_RxRingBufferOverrun = MAKE_STATUS(kStatusGroup_UART, 8), /*!< UART RX software ring buffer overrun. */ - kStatus_UART_RxHardwareOverrun = MAKE_STATUS(kStatusGroup_UART, 9), /*!< UART RX receiver overrun. */ - kStatus_UART_NoiseError = MAKE_STATUS(kStatusGroup_UART, 10), /*!< UART noise error. */ - kStatus_UART_FramingError = MAKE_STATUS(kStatusGroup_UART, 11), /*!< UART framing error. */ - kStatus_UART_ParityError = MAKE_STATUS(kStatusGroup_UART, 12), /*!< UART parity error. */ - kStatus_UART_BaudrateNotSupport = - MAKE_STATUS(kStatusGroup_UART, 13), /*!< Baudrate is not support in current clock source */ -}; - -/*! @brief UART parity mode. */ -typedef enum _uart_parity_mode -{ - kUART_ParityDisabled = 0x0U, /*!< Parity disabled */ - kUART_ParityEven = 0x2U, /*!< Parity enabled, type even, bit setting: PE|PT = 10 */ - kUART_ParityOdd = 0x3U, /*!< Parity enabled, type odd, bit setting: PE|PT = 11 */ -} uart_parity_mode_t; - -/*! @brief UART stop bit count. */ -typedef enum _uart_stop_bit_count -{ - kUART_OneStopBit = 0U, /*!< One stop bit */ - kUART_TwoStopBit = 1U, /*!< Two stop bits */ -} uart_stop_bit_count_t; - -/*! - * @brief UART interrupt configuration structure, default settings all disabled. - * - * This structure contains the settings for all of the UART interrupt configurations. - */ -enum _uart_interrupt_enable -{ -#if defined(FSL_FEATURE_UART_HAS_LIN_BREAK_DETECT) && FSL_FEATURE_UART_HAS_LIN_BREAK_DETECT - kUART_LinBreakInterruptEnable = (UART_BDH_LBKDIE_MASK), /*!< LIN break detect interrupt. */ -#endif - kUART_RxActiveEdgeInterruptEnable = (UART_BDH_RXEDGIE_MASK), /*!< RX active edge interrupt. */ - kUART_TxDataRegEmptyInterruptEnable = (UART_C2_TIE_MASK << 8), /*!< Transmit data register empty interrupt. */ - kUART_TransmissionCompleteInterruptEnable = (UART_C2_TCIE_MASK << 8), /*!< Transmission complete interrupt. */ - kUART_RxDataRegFullInterruptEnable = (UART_C2_RIE_MASK << 8), /*!< Receiver data register full interrupt. */ - kUART_IdleLineInterruptEnable = (UART_C2_ILIE_MASK << 8), /*!< Idle line interrupt. */ - kUART_RxOverrunInterruptEnable = (UART_C3_ORIE_MASK << 16), /*!< Receiver overrun interrupt. */ - kUART_NoiseErrorInterruptEnable = (UART_C3_NEIE_MASK << 16), /*!< Noise error flag interrupt. */ - kUART_FramingErrorInterruptEnable = (UART_C3_FEIE_MASK << 16), /*!< Framing error flag interrupt. */ - kUART_ParityErrorInterruptEnable = (UART_C3_PEIE_MASK << 16), /*!< Parity error flag interrupt. */ -#if defined(FSL_FEATURE_UART_HAS_FIFO) && FSL_FEATURE_UART_HAS_FIFO - kUART_RxFifoOverflowInterruptEnable = (UART_CFIFO_RXOFE_MASK << 24), /*!< RX FIFO overflow interrupt. */ - kUART_TxFifoOverflowInterruptEnable = (UART_CFIFO_TXOFE_MASK << 24), /*!< TX FIFO overflow interrupt. */ - kUART_RxFifoUnderflowInterruptEnable = (UART_CFIFO_RXUFE_MASK << 24), /*!< RX FIFO underflow interrupt. */ -#endif - kUART_AllInterruptsEnable = -#if defined(FSL_FEATURE_UART_HAS_LIN_BREAK_DETECT) && FSL_FEATURE_UART_HAS_LIN_BREAK_DETECT - kUART_LinBreakInterruptEnable | -#endif - kUART_RxActiveEdgeInterruptEnable | kUART_TxDataRegEmptyInterruptEnable | - kUART_TransmissionCompleteInterruptEnable | kUART_RxDataRegFullInterruptEnable | kUART_IdleLineInterruptEnable | - kUART_RxOverrunInterruptEnable | kUART_NoiseErrorInterruptEnable | kUART_FramingErrorInterruptEnable | - kUART_ParityErrorInterruptEnable -#if defined(FSL_FEATURE_UART_HAS_FIFO) && FSL_FEATURE_UART_HAS_FIFO - | - kUART_RxFifoOverflowInterruptEnable | kUART_TxFifoOverflowInterruptEnable | kUART_RxFifoUnderflowInterruptEnable -#endif - , -}; - -/*! - * @brief UART status flags. - * - * This provides constants for the UART status flags for use in the UART functions. - */ -enum _uart_flags -{ - kUART_TxDataRegEmptyFlag = (UART_S1_TDRE_MASK), /*!< TX data register empty flag. */ - kUART_TransmissionCompleteFlag = (UART_S1_TC_MASK), /*!< Transmission complete flag. */ - kUART_RxDataRegFullFlag = (UART_S1_RDRF_MASK), /*!< RX data register full flag. */ - kUART_IdleLineFlag = (UART_S1_IDLE_MASK), /*!< Idle line detect flag. */ - kUART_RxOverrunFlag = (UART_S1_OR_MASK), /*!< RX overrun flag. */ - kUART_NoiseErrorFlag = (UART_S1_NF_MASK), /*!< RX takes 3 samples of each received bit. - If any of these samples differ, noise flag sets */ - kUART_FramingErrorFlag = (UART_S1_FE_MASK), /*!< Frame error flag, sets if logic 0 was detected - where stop bit expected */ - kUART_ParityErrorFlag = (UART_S1_PF_MASK), /*!< If parity enabled, sets upon parity error detection */ -#if defined(FSL_FEATURE_UART_HAS_LIN_BREAK_DETECT) && FSL_FEATURE_UART_HAS_LIN_BREAK_DETECT - kUART_LinBreakFlag = - (UART_S2_LBKDIF_MASK - << 8), /*!< LIN break detect interrupt flag, sets when - LIN break char detected and LIN circuit enabled */ -#endif - kUART_RxActiveEdgeFlag = - (UART_S2_RXEDGIF_MASK << 8), /*!< RX pin active edge interrupt flag, - sets when active edge detected */ - kUART_RxActiveFlag = - (UART_S2_RAF_MASK << 8), /*!< Receiver Active Flag (RAF), - sets at beginning of valid start bit */ -#if defined(FSL_FEATURE_UART_HAS_EXTENDED_DATA_REGISTER_FLAGS) && FSL_FEATURE_UART_HAS_EXTENDED_DATA_REGISTER_FLAGS - kUART_NoiseErrorInRxDataRegFlag = (UART_ED_NOISY_MASK << 16), /*!< Noisy bit, sets if noise detected. */ - kUART_ParityErrorInRxDataRegFlag = (UART_ED_PARITYE_MASK << 16), /*!< Paritye bit, sets if parity error detected. */ -#endif -#if defined(FSL_FEATURE_UART_HAS_FIFO) && FSL_FEATURE_UART_HAS_FIFO - kUART_TxFifoEmptyFlag = (UART_SFIFO_TXEMPT_MASK << 24), /*!< TXEMPT bit, sets if TX buffer is empty */ - kUART_RxFifoEmptyFlag = (UART_SFIFO_RXEMPT_MASK << 24), /*!< RXEMPT bit, sets if RX buffer is empty */ - kUART_TxFifoOverflowFlag = (UART_SFIFO_TXOF_MASK << 24), /*!< TXOF bit, sets if TX buffer overflow occurred */ - kUART_RxFifoOverflowFlag = (UART_SFIFO_RXOF_MASK << 24), /*!< RXOF bit, sets if receive buffer overflow */ - kUART_RxFifoUnderflowFlag = (UART_SFIFO_RXUF_MASK << 24), /*!< RXUF bit, sets if receive buffer underflow */ -#endif -}; - -/*! @brief UART configuration structure. */ -typedef struct _uart_config -{ - uint32_t baudRate_Bps; /*!< UART baud rate */ - uart_parity_mode_t parityMode; /*!< Parity mode, disabled (default), even, odd */ -#if defined(FSL_FEATURE_UART_HAS_STOP_BIT_CONFIG_SUPPORT) && FSL_FEATURE_UART_HAS_STOP_BIT_CONFIG_SUPPORT - uart_stop_bit_count_t stopBitCount; /*!< Number of stop bits, 1 stop bit (default) or 2 stop bits */ -#endif -#if defined(FSL_FEATURE_UART_HAS_FIFO) && FSL_FEATURE_UART_HAS_FIFO - uint8_t txFifoWatermark; /*!< TX FIFO watermark */ - uint8_t rxFifoWatermark; /*!< RX FIFO watermark */ -#endif - bool enableTx; /*!< Enable TX */ - bool enableRx; /*!< Enable RX */ -} uart_config_t; - -/*! @brief UART transfer structure. */ -typedef struct _uart_transfer -{ - uint8_t *data; /*!< The buffer of data to be transfer.*/ - size_t dataSize; /*!< The byte count to be transfer. */ -} uart_transfer_t; - -/* Forward declaration of the handle typedef. */ -typedef struct _uart_handle uart_handle_t; - -/*! @brief UART transfer callback function. */ -typedef void (*uart_transfer_callback_t)(UART_Type *base, uart_handle_t *handle, status_t status, void *userData); - -/*! @brief UART handle structure. */ -struct _uart_handle -{ - uint8_t *volatile txData; /*!< Address of remaining data to send. */ - volatile size_t txDataSize; /*!< Size of the remaining data to send. */ - size_t txDataSizeAll; /*!< Size of the data to send out. */ - uint8_t *volatile rxData; /*!< Address of remaining data to receive. */ - volatile size_t rxDataSize; /*!< Size of the remaining data to receive. */ - size_t rxDataSizeAll; /*!< Size of the data to receive. */ - - uint8_t *rxRingBuffer; /*!< Start address of the receiver ring buffer. */ - size_t rxRingBufferSize; /*!< Size of the ring buffer. */ - volatile uint16_t rxRingBufferHead; /*!< Index for the driver to store received data into ring buffer. */ - volatile uint16_t rxRingBufferTail; /*!< Index for the user to get data from the ring buffer. */ - - uart_transfer_callback_t callback; /*!< Callback function. */ - void *userData; /*!< UART callback function parameter.*/ - - volatile uint8_t txState; /*!< TX transfer state. */ - volatile uint8_t rxState; /*!< RX transfer state */ -}; - -/******************************************************************************* - * API - ******************************************************************************/ - -#if defined(__cplusplus) -extern "C" { -#endif /* _cplusplus */ - -/*! - * @name Initialization and deinitialization - * @{ - */ - -/*! - * @brief Initializes a UART instance with a user configuration structure and peripheral clock. - * - * This function configures the UART module with the user-defined settings. The user can configure the configuration - * structure and also get the default configuration by using the UART_GetDefaultConfig() function. - * The example below shows how to use this API to configure UART. - * @code - * uart_config_t uartConfig; - * uartConfig.baudRate_Bps = 115200U; - * uartConfig.parityMode = kUART_ParityDisabled; - * uartConfig.stopBitCount = kUART_OneStopBit; - * uartConfig.txFifoWatermark = 0; - * uartConfig.rxFifoWatermark = 1; - * UART_Init(UART1, &uartConfig, 20000000U); - * @endcode - * - * @param base UART peripheral base address. - * @param config Pointer to the user-defined configuration structure. - * @param srcClock_Hz UART clock source frequency in HZ. - * @retval kStatus_UART_BaudrateNotSupport Baudrate is not support in current clock source. - * @retval kStatus_Success Status UART initialize succeed - */ -status_t UART_Init(UART_Type *base, const uart_config_t *config, uint32_t srcClock_Hz); - -/*! - * @brief Deinitializes a UART instance. - * - * This function waits for TX complete, disables TX and RX, and disables the UART clock. - * - * @param base UART peripheral base address. - */ -void UART_Deinit(UART_Type *base); - -/*! - * @brief Gets the default configuration structure. - * - * This function initializes the UART configuration structure to a default value. The default - * values are as follows. - * uartConfig->baudRate_Bps = 115200U; - * uartConfig->bitCountPerChar = kUART_8BitsPerChar; - * uartConfig->parityMode = kUART_ParityDisabled; - * uartConfig->stopBitCount = kUART_OneStopBit; - * uartConfig->txFifoWatermark = 0; - * uartConfig->rxFifoWatermark = 1; - * uartConfig->enableTx = false; - * uartConfig->enableRx = false; - * - * @param config Pointer to configuration structure. - */ -void UART_GetDefaultConfig(uart_config_t *config); - -/*! - * @brief Sets the UART instance baud rate. - * - * This function configures the UART module baud rate. This function is used to update - * the UART module baud rate after the UART module is initialized by the UART_Init. - * @code - * UART_SetBaudRate(UART1, 115200U, 20000000U); - * @endcode - * - * @param base UART peripheral base address. - * @param baudRate_Bps UART baudrate to be set. - * @param srcClock_Hz UART clock source freqency in Hz. - * @retval kStatus_UART_BaudrateNotSupport Baudrate is not support in the current clock source. - * @retval kStatus_Success Set baudrate succeeded. - */ -status_t UART_SetBaudRate(UART_Type *base, uint32_t baudRate_Bps, uint32_t srcClock_Hz); - -/* @} */ - -/*! - * @name Status - * @{ - */ - -/*! - * @brief Gets UART status flags. - * - * This function gets all UART status flags. The flags are returned as the logical - * OR value of the enumerators @ref _uart_flags. To check a specific status, - * compare the return value with enumerators in @ref _uart_flags. - * For example, to check whether the TX is empty, do the following. - * @code - * if (kUART_TxDataRegEmptyFlag & UART_GetStatusFlags(UART1)) - * { - * ... - * } - * @endcode - * - * @param base UART peripheral base address. - * @return UART status flags which are ORed by the enumerators in the _uart_flags. - */ -uint32_t UART_GetStatusFlags(UART_Type *base); - -/*! - * @brief Clears status flags with the provided mask. - * - * This function clears UART status flags with a provided mask. An automatically cleared flag - * can't be cleared by this function. - * These flags can only be cleared or set by hardware. - * kUART_TxDataRegEmptyFlag, kUART_TransmissionCompleteFlag, kUART_RxDataRegFullFlag, - * kUART_RxActiveFlag, kUART_NoiseErrorInRxDataRegFlag, kUART_ParityErrorInRxDataRegFlag, - * kUART_TxFifoEmptyFlag,kUART_RxFifoEmptyFlag - * Note that this API should be called when the Tx/Rx is idle. Otherwise it has no effect. - * - * @param base UART peripheral base address. - * @param mask The status flags to be cleared; it is logical OR value of @ref _uart_flags. - * @retval kStatus_UART_FlagCannotClearManually The flag can't be cleared by this function but - * it is cleared automatically by hardware. - * @retval kStatus_Success Status in the mask is cleared. - */ -status_t UART_ClearStatusFlags(UART_Type *base, uint32_t mask); - -/* @} */ - -/*! - * @name Interrupts - * @{ - */ - -/*! - * @brief Enables UART interrupts according to the provided mask. - * - * This function enables the UART interrupts according to the provided mask. The mask - * is a logical OR of enumeration members. See @ref _uart_interrupt_enable. - * For example, to enable TX empty interrupt and RX full interrupt, do the following. - * @code - * UART_EnableInterrupts(UART1,kUART_TxDataRegEmptyInterruptEnable | kUART_RxDataRegFullInterruptEnable); - * @endcode - * - * @param base UART peripheral base address. - * @param mask The interrupts to enable. Logical OR of @ref _uart_interrupt_enable. - */ -void UART_EnableInterrupts(UART_Type *base, uint32_t mask); - -/*! - * @brief Disables the UART interrupts according to the provided mask. - * - * This function disables the UART interrupts according to the provided mask. The mask - * is a logical OR of enumeration members. See @ref _uart_interrupt_enable. - * For example, to disable TX empty interrupt and RX full interrupt do the following. - * @code - * UART_DisableInterrupts(UART1,kUART_TxDataRegEmptyInterruptEnable | kUART_RxDataRegFullInterruptEnable); - * @endcode - * - * @param base UART peripheral base address. - * @param mask The interrupts to disable. Logical OR of @ref _uart_interrupt_enable. - */ -void UART_DisableInterrupts(UART_Type *base, uint32_t mask); - -/*! - * @brief Gets the enabled UART interrupts. - * - * This function gets the enabled UART interrupts. The enabled interrupts are returned - * as the logical OR value of the enumerators @ref _uart_interrupt_enable. To check - * a specific interrupts enable status, compare the return value with enumerators - * in @ref _uart_interrupt_enable. - * For example, to check whether TX empty interrupt is enabled, do the following. - * @code - * uint32_t enabledInterrupts = UART_GetEnabledInterrupts(UART1); - * - * if (kUART_TxDataRegEmptyInterruptEnable & enabledInterrupts) - * { - * ... - * } - * @endcode - * - * @param base UART peripheral base address. - * @return UART interrupt flags which are logical OR of the enumerators in @ref _uart_interrupt_enable. - */ -uint32_t UART_GetEnabledInterrupts(UART_Type *base); - -/* @} */ - -#if defined(FSL_FEATURE_UART_HAS_DMA_SELECT) && FSL_FEATURE_UART_HAS_DMA_SELECT -/*! - * @name DMA Control - * @{ - */ - -/*! - * @brief Gets the UART data register address. - * - * This function returns the UART data register address, which is mainly used by DMA/eDMA. - * - * @param base UART peripheral base address. - * @return UART data register addresses which are used both by the transmitter and the receiver. - */ -static inline uint32_t UART_GetDataRegisterAddress(UART_Type *base) -{ - return (uint32_t) & (base->D); -} - -/*! - * @brief Enables or disables the UART transmitter DMA request. - * - * This function enables or disables the transmit data register empty flag, S1[TDRE], to generate the DMA requests. - * - * @param base UART peripheral base address. - * @param enable True to enable, false to disable. - */ -static inline void UART_EnableTxDMA(UART_Type *base, bool enable) -{ - if (enable) - { -#if (defined(FSL_FEATURE_UART_IS_SCI) && FSL_FEATURE_UART_IS_SCI) - base->C4 |= UART_C4_TDMAS_MASK; -#else - base->C5 |= UART_C5_TDMAS_MASK; -#endif - base->C2 |= UART_C2_TIE_MASK; - } - else - { -#if (defined(FSL_FEATURE_UART_IS_SCI) && FSL_FEATURE_UART_IS_SCI) - base->C4 &= ~UART_C4_TDMAS_MASK; -#else - base->C5 &= ~UART_C5_TDMAS_MASK; -#endif - base->C2 &= ~UART_C2_TIE_MASK; - } -} - -/*! - * @brief Enables or disables the UART receiver DMA. - * - * This function enables or disables the receiver data register full flag, S1[RDRF], to generate DMA requests. - * - * @param base UART peripheral base address. - * @param enable True to enable, false to disable. - */ -static inline void UART_EnableRxDMA(UART_Type *base, bool enable) -{ - if (enable) - { -#if (defined(FSL_FEATURE_UART_IS_SCI) && FSL_FEATURE_UART_IS_SCI) - base->C4 |= UART_C4_RDMAS_MASK; -#else - base->C5 |= UART_C5_RDMAS_MASK; -#endif - base->C2 |= UART_C2_RIE_MASK; - } - else - { -#if (defined(FSL_FEATURE_UART_IS_SCI) && FSL_FEATURE_UART_IS_SCI) - base->C4 &= ~UART_C4_RDMAS_MASK; -#else - base->C5 &= ~UART_C5_RDMAS_MASK; -#endif - base->C2 &= ~UART_C2_RIE_MASK; - } -} - -/* @} */ -#endif /* FSL_FEATURE_UART_HAS_DMA_SELECT */ - -/*! - * @name Bus Operations - * @{ - */ - -/*! - * @brief Enables or disables the UART transmitter. - * - * This function enables or disables the UART transmitter. - * - * @param base UART peripheral base address. - * @param enable True to enable, false to disable. - */ -static inline void UART_EnableTx(UART_Type *base, bool enable) -{ - if (enable) - { - base->C2 |= UART_C2_TE_MASK; - } - else - { - base->C2 &= ~UART_C2_TE_MASK; - } -} - -/*! - * @brief Enables or disables the UART receiver. - * - * This function enables or disables the UART receiver. - * - * @param base UART peripheral base address. - * @param enable True to enable, false to disable. - */ -static inline void UART_EnableRx(UART_Type *base, bool enable) -{ - if (enable) - { - base->C2 |= UART_C2_RE_MASK; - } - else - { - base->C2 &= ~UART_C2_RE_MASK; - } -} - -/*! - * @brief Writes to the TX register. - * - * This function writes data to the TX register directly. The upper layer must ensure - * that the TX register is empty or TX FIFO has empty room before calling this function. - * - * @param base UART peripheral base address. - * @param data The byte to write. - */ -static inline void UART_WriteByte(UART_Type *base, uint8_t data) -{ - base->D = data; -} - -/*! - * @brief Reads the RX register directly. - * - * This function reads data from the RX register directly. The upper layer must - * ensure that the RX register is full or that the TX FIFO has data before calling this function. - * - * @param base UART peripheral base address. - * @return The byte read from UART data register. - */ -static inline uint8_t UART_ReadByte(UART_Type *base) -{ - return base->D; -} - -/*! - * @brief Writes to the TX register using a blocking method. - * - * This function polls the TX register, waits for the TX register to be empty or for the TX FIFO - * to have room and writes data to the TX buffer. - * - * @note This function does not check whether all data is sent out to the bus. - * Before disabling the TX, check kUART_TransmissionCompleteFlag to ensure that the TX is - * finished. - * - * @param base UART peripheral base address. - * @param data Start address of the data to write. - * @param length Size of the data to write. - */ -void UART_WriteBlocking(UART_Type *base, const uint8_t *data, size_t length); - -/*! - * @brief Read RX data register using a blocking method. - * - * This function polls the RX register, waits for the RX register to be full or for RX FIFO to - * have data, and reads data from the TX register. - * - * @param base UART peripheral base address. - * @param data Start address of the buffer to store the received data. - * @param length Size of the buffer. - * @retval kStatus_UART_RxHardwareOverrun Receiver overrun occurred while receiving data. - * @retval kStatus_UART_NoiseError A noise error occurred while receiving data. - * @retval kStatus_UART_FramingError A framing error occurred while receiving data. - * @retval kStatus_UART_ParityError A parity error occurred while receiving data. - * @retval kStatus_Success Successfully received all data. - */ -status_t UART_ReadBlocking(UART_Type *base, uint8_t *data, size_t length); - -/* @} */ - -/*! - * @name Transactional - * @{ - */ - -/*! - * @brief Initializes the UART handle. - * - * This function initializes the UART handle which can be used for other UART - * transactional APIs. Usually, for a specified UART instance, - * call this API once to get the initialized handle. - * - * @param base UART peripheral base address. - * @param handle UART handle pointer. - * @param callback The callback function. - * @param userData The parameter of the callback function. - */ -void UART_TransferCreateHandle(UART_Type *base, - uart_handle_t *handle, - uart_transfer_callback_t callback, - void *userData); - -/*! - * @brief Sets up the RX ring buffer. - * - * This function sets up the RX ring buffer to a specific UART handle. - * - * When the RX ring buffer is used, data received are stored into the ring buffer even when the - * user doesn't call the UART_TransferReceiveNonBlocking() API. If data is already received - * in the ring buffer, the user can get the received data from the ring buffer directly. - * - * @note When using the RX ring buffer, one byte is reserved for internal use. In other - * words, if @p ringBufferSize is 32, only 31 bytes are used for saving data. - * - * @param base UART peripheral base address. - * @param handle UART handle pointer. - * @param ringBuffer Start address of the ring buffer for background receiving. Pass NULL to disable the ring buffer. - * @param ringBufferSize Size of the ring buffer. - */ -void UART_TransferStartRingBuffer(UART_Type *base, uart_handle_t *handle, uint8_t *ringBuffer, size_t ringBufferSize); - -/*! - * @brief Aborts the background transfer and uninstalls the ring buffer. - * - * This function aborts the background transfer and uninstalls the ring buffer. - * - * @param base UART peripheral base address. - * @param handle UART handle pointer. - */ -void UART_TransferStopRingBuffer(UART_Type *base, uart_handle_t *handle); - -/*! - * @brief Transmits a buffer of data using the interrupt method. - * - * This function sends data using an interrupt method. This is a non-blocking function, which - * returns directly without waiting for all data to be written to the TX register. When - * all data is written to the TX register in the ISR, the UART driver calls the callback - * function and passes the @ref kStatus_UART_TxIdle as status parameter. - * - * @note The kStatus_UART_TxIdle is passed to the upper layer when all data is written - * to the TX register. However, it does not ensure that all data is sent out. Before disabling the TX, - * check the kUART_TransmissionCompleteFlag to ensure that the TX is finished. - * - * @param base UART peripheral base address. - * @param handle UART handle pointer. - * @param xfer UART transfer structure. See #uart_transfer_t. - * @retval kStatus_Success Successfully start the data transmission. - * @retval kStatus_UART_TxBusy Previous transmission still not finished; data not all written to TX register yet. - * @retval kStatus_InvalidArgument Invalid argument. - */ -status_t UART_TransferSendNonBlocking(UART_Type *base, uart_handle_t *handle, uart_transfer_t *xfer); - -/*! - * @brief Aborts the interrupt-driven data transmit. - * - * This function aborts the interrupt-driven data sending. The user can get the remainBytes to find out - * how many bytes are not sent out. - * - * @param base UART peripheral base address. - * @param handle UART handle pointer. - */ -void UART_TransferAbortSend(UART_Type *base, uart_handle_t *handle); - -/*! - * @brief Gets the number of bytes written to the UART TX register. - * - * This function gets the number of bytes written to the UART TX - * register by using the interrupt method. - * - * @param base UART peripheral base address. - * @param handle UART handle pointer. - * @param count Send bytes count. - * @retval kStatus_NoTransferInProgress No send in progress. - * @retval kStatus_InvalidArgument The parameter is invalid. - * @retval kStatus_Success Get successfully through the parameter \p count; - */ -status_t UART_TransferGetSendCount(UART_Type *base, uart_handle_t *handle, uint32_t *count); - -/*! - * @brief Receives a buffer of data using an interrupt method. - * - * This function receives data using an interrupt method. This is a non-blocking function, which - * returns without waiting for all data to be received. - * If the RX ring buffer is used and not empty, the data in the ring buffer is copied and - * the parameter @p receivedBytes shows how many bytes are copied from the ring buffer. - * After copying, if the data in the ring buffer is not enough to read, the receive - * request is saved by the UART driver. When the new data arrives, the receive request - * is serviced first. When all data is received, the UART driver notifies the upper layer - * through a callback function and passes the status parameter @ref kStatus_UART_RxIdle. - * For example, the upper layer needs 10 bytes but there are only 5 bytes in the ring buffer. - * The 5 bytes are copied to the xfer->data and this function returns with the - * parameter @p receivedBytes set to 5. For the left 5 bytes, newly arrived data is - * saved from the xfer->data[5]. When 5 bytes are received, the UART driver notifies the upper layer. - * If the RX ring buffer is not enabled, this function enables the RX and RX interrupt - * to receive data to the xfer->data. When all data is received, the upper layer is notified. - * - * @param base UART peripheral base address. - * @param handle UART handle pointer. - * @param xfer UART transfer structure, see #uart_transfer_t. - * @param receivedBytes Bytes received from the ring buffer directly. - * @retval kStatus_Success Successfully queue the transfer into transmit queue. - * @retval kStatus_UART_RxBusy Previous receive request is not finished. - * @retval kStatus_InvalidArgument Invalid argument. - */ -status_t UART_TransferReceiveNonBlocking(UART_Type *base, - uart_handle_t *handle, - uart_transfer_t *xfer, - size_t *receivedBytes); - -/*! - * @brief Aborts the interrupt-driven data receiving. - * - * This function aborts the interrupt-driven data receiving. The user can get the remainBytes to know - * how many bytes are not received yet. - * - * @param base UART peripheral base address. - * @param handle UART handle pointer. - */ -void UART_TransferAbortReceive(UART_Type *base, uart_handle_t *handle); - -/*! - * @brief Gets the number of bytes that have been received. - * - * This function gets the number of bytes that have been received. - * - * @param base UART peripheral base address. - * @param handle UART handle pointer. - * @param count Receive bytes count. - * @retval kStatus_NoTransferInProgress No receive in progress. - * @retval kStatus_InvalidArgument Parameter is invalid. - * @retval kStatus_Success Get successfully through the parameter \p count; - */ -status_t UART_TransferGetReceiveCount(UART_Type *base, uart_handle_t *handle, uint32_t *count); - -/*! - * @brief UART IRQ handle function. - * - * This function handles the UART transmit and receive IRQ request. - * - * @param base UART peripheral base address. - * @param handle UART handle pointer. - */ -void UART_TransferHandleIRQ(UART_Type *base, uart_handle_t *handle); - -/*! - * @brief UART Error IRQ handle function. - * - * This function handles the UART error IRQ request. - * - * @param base UART peripheral base address. - * @param handle UART handle pointer. - */ -void UART_TransferHandleErrorIRQ(UART_Type *base, uart_handle_t *handle); - -/* @} */ - -#if defined(__cplusplus) -} -#endif - -/*! @}*/ - -#endif /* _FSL_UART_H_ */ diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_uart_edma.c b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_uart_edma.c deleted file mode 100644 index c51e4934639..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_uart_edma.c +++ /dev/null @@ -1,368 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "fsl_uart_edma.h" -#include "fsl_dmamux.h" - -/******************************************************************************* - * Definitions - ******************************************************************************/ - -/* Array of UART handle. */ -#if (defined(UART5)) -#define UART_HANDLE_ARRAY_SIZE 6 -#else /* UART5 */ -#if (defined(UART4)) -#define UART_HANDLE_ARRAY_SIZE 5 -#else /* UART4 */ -#if (defined(UART3)) -#define UART_HANDLE_ARRAY_SIZE 4 -#else /* UART3 */ -#if (defined(UART2)) -#define UART_HANDLE_ARRAY_SIZE 3 -#else /* UART2 */ -#if (defined(UART1)) -#define UART_HANDLE_ARRAY_SIZE 2 -#else /* UART1 */ -#if (defined(UART0)) -#define UART_HANDLE_ARRAY_SIZE 1 -#else /* UART0 */ -#error No UART instance. -#endif /* UART 0 */ -#endif /* UART 1 */ -#endif /* UART 2 */ -#endif /* UART 3 */ -#endif /* UART 4 */ -#endif /* UART 5 */ - -/*base, uartPrivateHandle->handle); - - if (uartPrivateHandle->handle->callback) - { - uartPrivateHandle->handle->callback(uartPrivateHandle->base, uartPrivateHandle->handle, kStatus_UART_TxIdle, - uartPrivateHandle->handle->userData); - } - } -} - -static void UART_ReceiveEDMACallback(edma_handle_t *handle, void *param, bool transferDone, uint32_t tcds) -{ - assert(param); - - uart_edma_private_handle_t *uartPrivateHandle = (uart_edma_private_handle_t *)param; - - /* Avoid warning for unused parameters. */ - handle = handle; - tcds = tcds; - - if (transferDone) - { - /* Disable transfer. */ - UART_TransferAbortReceiveEDMA(uartPrivateHandle->base, uartPrivateHandle->handle); - - if (uartPrivateHandle->handle->callback) - { - uartPrivateHandle->handle->callback(uartPrivateHandle->base, uartPrivateHandle->handle, kStatus_UART_RxIdle, - uartPrivateHandle->handle->userData); - } - } -} - -void UART_TransferCreateHandleEDMA(UART_Type *base, - uart_edma_handle_t *handle, - uart_edma_transfer_callback_t callback, - void *userData, - edma_handle_t *txEdmaHandle, - edma_handle_t *rxEdmaHandle) -{ - assert(handle); - - uint32_t instance = UART_GetInstance(base); - - s_edmaPrivateHandle[instance].base = base; - s_edmaPrivateHandle[instance].handle = handle; - - memset(handle, 0, sizeof(*handle)); - - handle->rxState = kUART_RxIdle; - handle->txState = kUART_TxIdle; - - handle->rxEdmaHandle = rxEdmaHandle; - handle->txEdmaHandle = txEdmaHandle; - - handle->callback = callback; - handle->userData = userData; - -#if defined(FSL_FEATURE_UART_HAS_FIFO) && FSL_FEATURE_UART_HAS_FIFO - /* Note: - Take care of the RX FIFO, EDMA request only assert when received bytes - equal or more than RX water mark, there is potential issue if RX water - mark larger than 1. - For example, if RX FIFO water mark is 2, upper layer needs 5 bytes and - 5 bytes are received. the last byte will be saved in FIFO but not trigger - EDMA transfer because the water mark is 2. - */ - if (rxEdmaHandle) - { - base->RWFIFO = 1U; - } -#endif - - /* Configure TX. */ - if (txEdmaHandle) - { - EDMA_SetCallback(handle->txEdmaHandle, UART_SendEDMACallback, &s_edmaPrivateHandle[instance]); - } - - /* Configure RX. */ - if (rxEdmaHandle) - { - EDMA_SetCallback(handle->rxEdmaHandle, UART_ReceiveEDMACallback, &s_edmaPrivateHandle[instance]); - } -} - -status_t UART_SendEDMA(UART_Type *base, uart_edma_handle_t *handle, uart_transfer_t *xfer) -{ - assert(handle); - assert(handle->txEdmaHandle); - assert(xfer); - assert(xfer->data); - assert(xfer->dataSize); - - edma_transfer_config_t xferConfig; - status_t status; - - /* If previous TX not finished. */ - if (kUART_TxBusy == handle->txState) - { - status = kStatus_UART_TxBusy; - } - else - { - handle->txState = kUART_TxBusy; - handle->txDataSizeAll = xfer->dataSize; - - /* Prepare transfer. */ - EDMA_PrepareTransfer(&xferConfig, xfer->data, sizeof(uint8_t), (void *)UART_GetDataRegisterAddress(base), - sizeof(uint8_t), sizeof(uint8_t), xfer->dataSize, kEDMA_MemoryToPeripheral); - - /* Store the initially configured eDMA minor byte transfer count into the UART handle */ - handle->nbytes = sizeof(uint8_t); - - /* Submit transfer. */ - EDMA_SubmitTransfer(handle->txEdmaHandle, &xferConfig); - EDMA_StartTransfer(handle->txEdmaHandle); - - /* Enable UART TX EDMA. */ - UART_EnableTxDMA(base, true); - - status = kStatus_Success; - } - - return status; -} - -status_t UART_ReceiveEDMA(UART_Type *base, uart_edma_handle_t *handle, uart_transfer_t *xfer) -{ - assert(handle); - assert(handle->rxEdmaHandle); - assert(xfer); - assert(xfer->data); - assert(xfer->dataSize); - - edma_transfer_config_t xferConfig; - status_t status; - - /* If previous RX not finished. */ - if (kUART_RxBusy == handle->rxState) - { - status = kStatus_UART_RxBusy; - } - else - { - handle->rxState = kUART_RxBusy; - handle->rxDataSizeAll = xfer->dataSize; - - /* Prepare transfer. */ - EDMA_PrepareTransfer(&xferConfig, (void *)UART_GetDataRegisterAddress(base), sizeof(uint8_t), xfer->data, - sizeof(uint8_t), sizeof(uint8_t), xfer->dataSize, kEDMA_PeripheralToMemory); - - /* Store the initially configured eDMA minor byte transfer count into the UART handle */ - handle->nbytes = sizeof(uint8_t); - - /* Submit transfer. */ - EDMA_SubmitTransfer(handle->rxEdmaHandle, &xferConfig); - EDMA_StartTransfer(handle->rxEdmaHandle); - - /* Enable UART RX EDMA. */ - UART_EnableRxDMA(base, true); - - status = kStatus_Success; - } - - return status; -} - -void UART_TransferAbortSendEDMA(UART_Type *base, uart_edma_handle_t *handle) -{ - assert(handle); - assert(handle->txEdmaHandle); - - /* Disable UART TX EDMA. */ - UART_EnableTxDMA(base, false); - - /* Stop transfer. */ - EDMA_AbortTransfer(handle->txEdmaHandle); - - handle->txState = kUART_TxIdle; -} - -void UART_TransferAbortReceiveEDMA(UART_Type *base, uart_edma_handle_t *handle) -{ - assert(handle); - assert(handle->rxEdmaHandle); - - /* Disable UART RX EDMA. */ - UART_EnableRxDMA(base, false); - - /* Stop transfer. */ - EDMA_AbortTransfer(handle->rxEdmaHandle); - - handle->rxState = kUART_RxIdle; -} - -status_t UART_TransferGetReceiveCountEDMA(UART_Type *base, uart_edma_handle_t *handle, uint32_t *count) -{ - assert(handle); - assert(handle->rxEdmaHandle); - assert(count); - - if (kUART_RxIdle == handle->rxState) - { - return kStatus_NoTransferInProgress; - } - - *count = handle->rxDataSizeAll - - (uint32_t)handle->nbytes * - EDMA_GetRemainingMajorLoopCount(handle->rxEdmaHandle->base, handle->rxEdmaHandle->channel); - - return kStatus_Success; -} - -status_t UART_TransferGetSendCountEDMA(UART_Type *base, uart_edma_handle_t *handle, uint32_t *count) -{ - assert(handle); - assert(handle->txEdmaHandle); - assert(count); - - if (kUART_TxIdle == handle->txState) - { - return kStatus_NoTransferInProgress; - } - - *count = handle->txDataSizeAll - - (uint32_t)handle->nbytes * - EDMA_GetRemainingMajorLoopCount(handle->txEdmaHandle->base, handle->txEdmaHandle->channel); - - return kStatus_Success; -} diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_uart_edma.h b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_uart_edma.h deleted file mode 100644 index e411ffd7a44..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_uart_edma.h +++ /dev/null @@ -1,190 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -#ifndef _FSL_UART_EDMA_H_ -#define _FSL_UART_EDMA_H_ - -#include "fsl_uart.h" -#include "fsl_dmamux.h" -#include "fsl_edma.h" - -/*! - * @addtogroup uart_edma_driver - * @{ - */ - -/******************************************************************************* - * Definitions - ******************************************************************************/ - -/* Forward declaration of the handle typedef. */ -typedef struct _uart_edma_handle uart_edma_handle_t; - -/*! @brief UART transfer callback function. */ -typedef void (*uart_edma_transfer_callback_t)(UART_Type *base, - uart_edma_handle_t *handle, - status_t status, - void *userData); - -/*! -* @brief UART eDMA handle -*/ -struct _uart_edma_handle -{ - uart_edma_transfer_callback_t callback; /*!< Callback function. */ - void *userData; /*!< UART callback function parameter.*/ - size_t rxDataSizeAll; /*!< Size of the data to receive. */ - size_t txDataSizeAll; /*!< Size of the data to send out. */ - - edma_handle_t *txEdmaHandle; /*!< The eDMA TX channel used. */ - edma_handle_t *rxEdmaHandle; /*!< The eDMA RX channel used. */ - - uint8_t nbytes; /*!< eDMA minor byte transfer count initially configured. */ - - volatile uint8_t txState; /*!< TX transfer state. */ - volatile uint8_t rxState; /*!< RX transfer state */ -}; - -/******************************************************************************* - * API - ******************************************************************************/ - -#if defined(__cplusplus) -extern "C" { -#endif - -/*! - * @name eDMA transactional - * @{ - */ - -/*! - * @brief Initializes the UART handle which is used in transactional functions. - * @param base UART peripheral base address. - * @param handle Pointer to the uart_edma_handle_t structure. - * @param callback UART callback, NULL means no callback. - * @param userData User callback function data. - * @param rxEdmaHandle User-requested DMA handle for RX DMA transfer. - * @param txEdmaHandle User-requested DMA handle for TX DMA transfer. - */ -void UART_TransferCreateHandleEDMA(UART_Type *base, - uart_edma_handle_t *handle, - uart_edma_transfer_callback_t callback, - void *userData, - edma_handle_t *txEdmaHandle, - edma_handle_t *rxEdmaHandle); - -/*! - * @brief Sends data using eDMA. - * - * This function sends data using eDMA. This is a non-blocking function, which returns - * right away. When all data is sent, the send callback function is called. - * - * @param base UART peripheral base address. - * @param handle UART handle pointer. - * @param xfer UART eDMA transfer structure. See #uart_transfer_t. - * @retval kStatus_Success if succeeded; otherwise failed. - * @retval kStatus_UART_TxBusy Previous transfer ongoing. - * @retval kStatus_InvalidArgument Invalid argument. - */ -status_t UART_SendEDMA(UART_Type *base, uart_edma_handle_t *handle, uart_transfer_t *xfer); - -/*! - * @brief Receives data using eDMA. - * - * This function receives data using eDMA. This is a non-blocking function, which returns - * right away. When all data is received, the receive callback function is called. - * - * @param base UART peripheral base address. - * @param handle Pointer to the uart_edma_handle_t structure. - * @param xfer UART eDMA transfer structure. See #uart_transfer_t. - * @retval kStatus_Success if succeeded; otherwise failed. - * @retval kStatus_UART_RxBusy Previous transfer ongoing. - * @retval kStatus_InvalidArgument Invalid argument. - */ -status_t UART_ReceiveEDMA(UART_Type *base, uart_edma_handle_t *handle, uart_transfer_t *xfer); - -/*! - * @brief Aborts the sent data using eDMA. - * - * This function aborts sent data using eDMA. - * - * @param base UART peripheral base address. - * @param handle Pointer to the uart_edma_handle_t structure. - */ -void UART_TransferAbortSendEDMA(UART_Type *base, uart_edma_handle_t *handle); - -/*! - * @brief Aborts the receive data using eDMA. - * - * This function aborts receive data using eDMA. - * - * @param base UART peripheral base address. - * @param handle Pointer to the uart_edma_handle_t structure. - */ -void UART_TransferAbortReceiveEDMA(UART_Type *base, uart_edma_handle_t *handle); - -/*! - * @brief Gets the number of bytes that have been written to UART TX register. - * - * This function gets the number of bytes that have been written to UART TX - * register by DMA. - * - * @param base UART peripheral base address. - * @param handle UART handle pointer. - * @param count Send bytes count. - * @retval kStatus_NoTransferInProgress No send in progress. - * @retval kStatus_InvalidArgument Parameter is invalid. - * @retval kStatus_Success Get successfully through the parameter \p count; - */ -status_t UART_TransferGetSendCountEDMA(UART_Type *base, uart_edma_handle_t *handle, uint32_t *count); - -/*! - * @brief Gets the number of received bytes. - * - * This function gets the number of received bytes. - * - * @param base UART peripheral base address. - * @param handle UART handle pointer. - * @param count Receive bytes count. - * @retval kStatus_NoTransferInProgress No receive in progress. - * @retval kStatus_InvalidArgument Parameter is invalid. - * @retval kStatus_Success Get successfully through the parameter \p count; - */ -status_t UART_TransferGetReceiveCountEDMA(UART_Type *base, uart_edma_handle_t *handle, uint32_t *count); - -/*@}*/ - -#if defined(__cplusplus) -} -#endif - -/*! @}*/ - -#endif /* _FSL_UART_EDMA_H_ */ diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_vref.c b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_vref.c deleted file mode 100644 index 24f2d1dc280..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_vref.c +++ /dev/null @@ -1,230 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "fsl_vref.h" - -/******************************************************************************* - * Prototypes - ******************************************************************************/ - -/*! - * @brief Gets the instance from the base address - * - * @param base VREF peripheral base address - * - * @return The VREF instance - */ -static uint32_t VREF_GetInstance(VREF_Type *base); - -/******************************************************************************* - * Variables - ******************************************************************************/ - -/*! @brief Pointers to VREF bases for each instance. */ -static VREF_Type *const s_vrefBases[] = VREF_BASE_PTRS; - -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) -/*! @brief Pointers to VREF clocks for each instance. */ -static const clock_ip_name_t s_vrefClocks[] = VREF_CLOCKS; -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ - -/******************************************************************************* - * Code - ******************************************************************************/ - -static uint32_t VREF_GetInstance(VREF_Type *base) -{ - uint32_t instance; - - /* Find the instance index from base address mappings. */ - for (instance = 0; instance < ARRAY_SIZE(s_vrefBases); instance++) - { - if (s_vrefBases[instance] == base) - { - break; - } - } - - assert(instance < ARRAY_SIZE(s_vrefBases)); - - return instance; -} - -void VREF_Init(VREF_Type *base, const vref_config_t *config) -{ - assert(config != NULL); - - uint8_t reg = 0U; - -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) - /* Ungate clock for VREF */ - CLOCK_EnableClock(s_vrefClocks[VREF_GetInstance(base)]); -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ - -/* Configure VREF to a known state */ -#if defined(FSL_FEATURE_VREF_HAS_CHOP_OSC) && FSL_FEATURE_VREF_HAS_CHOP_OSC - /* Set chop oscillator bit */ - base->TRM |= VREF_TRM_CHOPEN_MASK; -#endif /* FSL_FEATURE_VREF_HAS_CHOP_OSC */ - /* Get current SC register */ -#if defined(FSL_FEATURE_VREF_HAS_LOW_REFERENCE) && FSL_FEATURE_VREF_HAS_LOW_REFERENCE - reg = base->VREFH_SC; -#else - reg = base->SC; -#endif/* FSL_FEATURE_VREF_HAS_LOW_REFERENCE */ - /* Clear old buffer mode selection bits */ - reg &= ~VREF_SC_MODE_LV_MASK; - /* Set buffer Mode selection and Regulator enable bit */ - reg |= VREF_SC_MODE_LV(config->bufferMode) | VREF_SC_REGEN(1U); -#if defined(FSL_FEATURE_VREF_HAS_COMPENSATION) && FSL_FEATURE_VREF_HAS_COMPENSATION - /* Set second order curvature compensation enable bit */ - reg |= VREF_SC_ICOMPEN(1U); -#endif /* FSL_FEATURE_VREF_HAS_COMPENSATION */ - /* Enable VREF module */ - reg |= VREF_SC_VREFEN(1U); - /* Update bit-field from value to Status and Control register */ -#if defined(FSL_FEATURE_VREF_HAS_LOW_REFERENCE) && FSL_FEATURE_VREF_HAS_LOW_REFERENCE - base->VREFH_SC = reg; -#else - base->SC = reg; -#endif/* FSL_FEATURE_VREF_HAS_LOW_REFERENCE */ -#if defined(FSL_FEATURE_VREF_HAS_LOW_REFERENCE) && FSL_FEATURE_VREF_HAS_LOW_REFERENCE - reg = base->VREFL_TRM; - /* Clear old select external voltage reference and VREFL (0.4 V) reference buffer enable bits */ - reg &= ~(VREF_VREFL_TRM_VREFL_EN_MASK | VREF_VREFL_TRM_VREFL_SEL_MASK); - /* Select external voltage reference and set VREFL (0.4 V) reference buffer enable */ - reg |= VREF_VREFL_TRM_VREFL_SEL(config->enableExternalVoltRef) | VREF_VREFL_TRM_VREFL_EN(config->enableLowRef); - base->VREFL_TRM = reg; -#endif /* FSL_FEATURE_VREF_HAS_LOW_REFERENCE */ - -#if defined(FSL_FEATURE_VREF_HAS_TRM4) && FSL_FEATURE_VREF_HAS_TRM4 - reg = base->TRM4; - /* Clear old select internal voltage reference bit (2.1V) */ - reg &= ~VREF_TRM4_VREF2V1_EN_MASK; - /* Select internal voltage reference (2.1V) */ - reg |= VREF_TRM4_VREF2V1_EN(config->enable2V1VoltRef); - base->TRM4 = reg; -#endif /* FSL_FEATURE_VREF_HAS_TRM4 */ - - /* Wait until internal voltage stable */ -#if defined(FSL_FEATURE_VREF_HAS_LOW_REFERENCE) && FSL_FEATURE_VREF_HAS_LOW_REFERENCE - while ((base->VREFH_SC & VREF_SC_VREFST_MASK) == 0) -#else - while ((base->SC & VREF_SC_VREFST_MASK) == 0) -#endif/* FSL_FEATURE_VREF_HAS_LOW_REFERENCE */ - { - } -} - -void VREF_Deinit(VREF_Type *base) -{ -#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) - /* Gate clock for VREF */ - CLOCK_DisableClock(s_vrefClocks[VREF_GetInstance(base)]); -#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ -} - -void VREF_GetDefaultConfig(vref_config_t *config) -{ - assert(config); - -/* Set High power buffer mode in */ -#if defined(FSL_FEATURE_VREF_MODE_LV_TYPE) && FSL_FEATURE_VREF_MODE_LV_TYPE - config->bufferMode = kVREF_ModeHighPowerBuffer; -#else - config->bufferMode = kVREF_ModeTightRegulationBuffer; -#endif /* FSL_FEATURE_VREF_MODE_LV_TYPE */ - -#if defined(FSL_FEATURE_VREF_HAS_LOW_REFERENCE) && FSL_FEATURE_VREF_HAS_LOW_REFERENCE - /* Select internal voltage reference */ - config->enableExternalVoltRef = false; - /* Set VREFL (0.4 V) reference buffer disable */ - config->enableLowRef = false; -#endif /* FSL_FEATURE_VREF_HAS_LOW_REFERENCE */ - -#if defined(FSL_FEATURE_VREF_HAS_TRM4) && FSL_FEATURE_VREF_HAS_TRM4 - /* Disable internal voltage reference (2.1V) */ - config->enable2V1VoltRef = false; -#endif /* FSL_FEATURE_VREF_HAS_TRM4 */ -} - -void VREF_SetTrimVal(VREF_Type *base, uint8_t trimValue) -{ - uint8_t reg = 0U; - - /* Set TRIM bits value in voltage reference */ - reg = base->TRM; - reg = ((reg & ~VREF_TRM_TRIM_MASK) | VREF_TRM_TRIM(trimValue)); - base->TRM = reg; - /* Wait until internal voltage stable */ -#if defined(FSL_FEATURE_VREF_HAS_LOW_REFERENCE) && FSL_FEATURE_VREF_HAS_LOW_REFERENCE - while ((base->VREFH_SC & VREF_SC_VREFST_MASK) == 0) -#else - while ((base->SC & VREF_SC_VREFST_MASK) == 0) -#endif/* FSL_FEATURE_VREF_HAS_LOW_REFERENCE */ - { - } -} - -#if defined(FSL_FEATURE_VREF_HAS_TRM4) && FSL_FEATURE_VREF_HAS_TRM4 -void VREF_SetTrim2V1Val(VREF_Type *base, uint8_t trimValue) -{ - uint8_t reg = 0U; - - /* Set TRIM bits value in voltage reference (2V1) */ - reg = base->TRM4; - reg = ((reg & ~VREF_TRM4_TRIM2V1_MASK) | VREF_TRM4_TRIM2V1(trimValue)); - base->TRM4 = reg; - /* Wait until internal voltage stable */ - while ((base->SC & VREF_SC_VREFST_MASK) == 0) - { - } -} -#endif /* FSL_FEATURE_VREF_HAS_TRM4 */ - -#if defined(FSL_FEATURE_VREF_HAS_LOW_REFERENCE) && FSL_FEATURE_VREF_HAS_LOW_REFERENCE -void VREF_SetLowReferenceTrimVal(VREF_Type *base, uint8_t trimValue) -{ - /* The values 111b and 110b are NOT valid/allowed */ - assert((trimValue != 0x7U) && (trimValue != 0x6U)); - - uint8_t reg = 0U; - - /* Set TRIM bits value in low voltage reference */ - reg = base->VREFL_TRM; - reg = ((reg & ~VREF_VREFL_TRM_VREFL_TRIM_MASK) | VREF_VREFL_TRM_VREFL_TRIM(trimValue)); - base->VREFL_TRM = reg; - /* Wait until internal voltage stable */ - - while ((base->VREFH_SC & VREF_SC_VREFST_MASK) == 0) - { - } -} -#endif /* FSL_FEATURE_VREF_HAS_LOW_REFERENCE */ diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_vref.h b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_vref.h deleted file mode 100644 index 6c6c014b913..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_vref.h +++ /dev/null @@ -1,256 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef _FSL_VREF_H_ -#define _FSL_VREF_H_ - -#include "fsl_common.h" - -/*! - * @addtogroup vref - * @{ - */ - - -/****************************************************************************** - * Definitions - ******************************************************************************/ - -/*! @name Driver version */ -/*@{*/ -#define FSL_VREF_DRIVER_VERSION (MAKE_VERSION(2, 1, 0)) /*!< Version 2.1.0. */ -/*@}*/ - -/* Those macros below defined to support SoC family which have VREFL (0.4V) reference */ -#if defined(FSL_FEATURE_VREF_HAS_LOW_REFERENCE) && FSL_FEATURE_VREF_HAS_LOW_REFERENCE -#define VREF_SC_MODE_LV VREF_VREFH_SC_MODE_LV -#define VREF_SC_REGEN VREF_VREFH_SC_REGEN -#define VREF_SC_VREFEN VREF_VREFH_SC_VREFEN -#define VREF_SC_ICOMPEN VREF_VREFH_SC_ICOMPEN -#define VREF_SC_REGEN_MASK VREF_VREFH_SC_REGEN_MASK -#define VREF_SC_VREFST_MASK VREF_VREFH_SC_VREFST_MASK -#define VREF_SC_VREFEN_MASK VREF_VREFH_SC_VREFEN_MASK -#define VREF_SC_MODE_LV_MASK VREF_VREFH_SC_MODE_LV_MASK -#define VREF_SC_ICOMPEN_MASK VREF_VREFH_SC_ICOMPEN_MASK -#define TRM VREFH_TRM -#define VREF_TRM_TRIM VREF_VREFH_TRM_TRIM -#define VREF_TRM_CHOPEN_MASK VREF_VREFH_TRM_CHOPEN_MASK -#define VREF_TRM_TRIM_MASK VREF_VREFH_TRM_TRIM_MASK -#define VREF_TRM_CHOPEN_SHIFT VREF_VREFH_TRM_CHOPEN_SHIFT -#define VREF_TRM_TRIM_SHIFT VREF_VREFH_TRM_TRIM_SHIFT -#define VREF_SC_MODE_LV_SHIFT VREF_VREFH_SC_MODE_LV_SHIFT -#define VREF_SC_REGEN_SHIFT VREF_VREFH_SC_REGEN_SHIFT -#define VREF_SC_VREFST_SHIFT VREF_VREFH_SC_VREFST_SHIFT -#define VREF_SC_ICOMPEN_SHIFT VREF_VREFH_SC_ICOMPEN_SHIFT -#endif /* FSL_FEATURE_VREF_HAS_LOW_REFERENCE */ - -/*! - * @brief VREF modes. - */ -typedef enum _vref_buffer_mode -{ - kVREF_ModeBandgapOnly = 0U, /*!< Bandgap on only, for stabilization and startup */ -#if defined(FSL_FEATURE_VREF_MODE_LV_TYPE) && FSL_FEATURE_VREF_MODE_LV_TYPE - kVREF_ModeHighPowerBuffer = 1U, /*!< High-power buffer mode enabled */ - kVREF_ModeLowPowerBuffer = 2U /*!< Low-power buffer mode enabled */ -#else - kVREF_ModeTightRegulationBuffer = 2U /*!< Tight regulation buffer enabled */ -#endif /* FSL_FEATURE_VREF_MODE_LV_TYPE */ -} vref_buffer_mode_t; - -/*! - * @brief The description structure for the VREF module. - */ -typedef struct _vref_config -{ - vref_buffer_mode_t bufferMode; /*!< Buffer mode selection */ -#if defined(FSL_FEATURE_VREF_HAS_LOW_REFERENCE) && FSL_FEATURE_VREF_HAS_LOW_REFERENCE - bool enableLowRef; /*!< Set VREFL (0.4 V) reference buffer enable or disable */ - bool enableExternalVoltRef; /*!< Select external voltage reference or not (internal) */ -#endif /* FSL_FEATURE_VREF_HAS_LOW_REFERENCE */ -#if defined(FSL_FEATURE_VREF_HAS_TRM4) && FSL_FEATURE_VREF_HAS_TRM4 - bool enable2V1VoltRef; /*!< Enable Internal Voltage Reference (2.1V) */ -#endif /* FSL_FEATURE_VREF_HAS_TRM4 */ -} vref_config_t; - -/****************************************************************************** - * API - ******************************************************************************/ - -#if defined(__cplusplus) -extern "C" { -#endif /* __cplusplus */ - -/*! - * @name VREF functional operation - * @{ - */ - -/*! - * @brief Enables the clock gate and configures the VREF module according to the configuration structure. - * - * This function must be called before calling all other VREF driver functions, - * read/write registers, and configurations with user-defined settings. - * The example below shows how to set up vref_config_t parameters and - * how to call the VREF_Init function by passing in these parameters. - * This is an example. - * @code - * vref_config_t vrefConfig; - * vrefConfig.bufferMode = kVREF_ModeHighPowerBuffer; - * vrefConfig.enableExternalVoltRef = false; - * vrefConfig.enableLowRef = false; - * VREF_Init(VREF, &vrefConfig); - * @endcode - * - * @param base VREF peripheral address. - * @param config Pointer to the configuration structure. - */ -void VREF_Init(VREF_Type *base, const vref_config_t *config); - -/*! - * @brief Stops and disables the clock for the VREF module. - * - * This function should be called to shut down the module. - * This is an example. - * @code - * vref_config_t vrefUserConfig; - * VREF_Init(VREF); - * VREF_GetDefaultConfig(&vrefUserConfig); - * ... - * VREF_Deinit(VREF); - * @endcode - * - * @param base VREF peripheral address. - */ -void VREF_Deinit(VREF_Type *base); - -/*! - * @brief Initializes the VREF configuration structure. - * - * This function initializes the VREF configuration structure to default values. - * This is an example. - * @code - * vrefConfig->bufferMode = kVREF_ModeHighPowerBuffer; - * vrefConfig->enableExternalVoltRef = false; - * vrefConfig->enableLowRef = false; - * @endcode - * - * @param config Pointer to the initialization structure. - */ -void VREF_GetDefaultConfig(vref_config_t *config); - -/*! - * @brief Sets a TRIM value for the reference voltage. - * - * This function sets a TRIM value for the reference voltage. - * Note that the TRIM value maximum is 0x3F. - * - * @param base VREF peripheral address. - * @param trimValue Value of the trim register to set the output reference voltage (maximum 0x3F (6-bit)). - */ -void VREF_SetTrimVal(VREF_Type *base, uint8_t trimValue); - -/*! - * @brief Reads the value of the TRIM meaning output voltage. - * - * This function gets the TRIM value from the TRM register. - * - * @param base VREF peripheral address. - * @return Six-bit value of trim setting. - */ -static inline uint8_t VREF_GetTrimVal(VREF_Type *base) -{ - return (base->TRM & VREF_TRM_TRIM_MASK); -} - -#if defined(FSL_FEATURE_VREF_HAS_TRM4) && FSL_FEATURE_VREF_HAS_TRM4 -/*! - * @brief Sets a TRIM value for the reference voltage (2V1). - * - * This function sets a TRIM value for the reference voltage (2V1). - * Note that the TRIM value maximum is 0x3F. - * - * @param base VREF peripheral address. - * @param trimValue Value of the trim register to set the output reference voltage (maximum 0x3F (6-bit)). - */ -void VREF_SetTrim2V1Val(VREF_Type *base, uint8_t trimValue); - -/*! - * @brief Reads the value of the TRIM meaning output voltage (2V1). - * - * This function gets the TRIM value from the VREF_TRM4 register. - * - * @param base VREF peripheral address. - * @return Six-bit value of trim setting. - */ -static inline uint8_t VREF_GetTrim2V1Val(VREF_Type *base) -{ - return (base->TRM4 & VREF_TRM4_TRIM2V1_MASK); -} -#endif /* FSL_FEATURE_VREF_HAS_TRM4 */ - -#if defined(FSL_FEATURE_VREF_HAS_LOW_REFERENCE) && FSL_FEATURE_VREF_HAS_LOW_REFERENCE - -/*! - * @brief Sets the TRIM value for the low voltage reference. - * - * This function sets the TRIM value for low reference voltage. - * Note the following. - * - The TRIM value maximum is 0x05U - * - The values 111b and 110b are not valid/allowed. - * - * @param base VREF peripheral address. - * @param trimValue Value of the trim register to set output low reference voltage (maximum 0x05U (3-bit)). - */ -void VREF_SetLowReferenceTrimVal(VREF_Type *base, uint8_t trimValue); - -/*! - * @brief Reads the value of the TRIM meaning output voltage. - * - * This function gets the TRIM value from the VREFL_TRM register. - * - * @param base VREF peripheral address. - * @return Three-bit value of the trim setting. - */ -static inline uint8_t VREF_GetLowReferenceTrimVal(VREF_Type *base) -{ - return (base->VREFL_TRM & VREF_VREFL_TRM_VREFL_TRIM_MASK); -} -#endif /* FSL_FEATURE_VREF_HAS_LOW_REFERENCE */ - -/*@}*/ - -#if defined(__cplusplus) -} -#endif /* __cplusplus */ - -/*! @}*/ - -#endif /* _FSL_VREF_H_ */ diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_wdog.c b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_wdog.c deleted file mode 100644 index 781ac133c1a..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_wdog.c +++ /dev/null @@ -1,153 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "fsl_wdog.h" - -/******************************************************************************* - * Code - ******************************************************************************/ - -void WDOG_GetDefaultConfig(wdog_config_t *config) -{ - assert(config); - - config->enableWdog = true; - config->clockSource = kWDOG_LpoClockSource; - config->prescaler = kWDOG_ClockPrescalerDivide1; -#if defined(FSL_FEATURE_WDOG_HAS_WAITEN) && FSL_FEATURE_WDOG_HAS_WAITEN - config->workMode.enableWait = true; -#endif /* FSL_FEATURE_WDOG_HAS_WAITEN */ - config->workMode.enableStop = false; - config->workMode.enableDebug = false; - config->enableUpdate = true; - config->enableInterrupt = false; - config->enableWindowMode = false; - config->windowValue = 0U; - config->timeoutValue = 0xFFFFU; -} - -void WDOG_Init(WDOG_Type *base, const wdog_config_t *config) -{ - assert(config); - - uint32_t value = 0U; - uint32_t primaskValue = 0U; - - value = WDOG_STCTRLH_WDOGEN(config->enableWdog) | WDOG_STCTRLH_CLKSRC(config->clockSource) | - WDOG_STCTRLH_IRQRSTEN(config->enableInterrupt) | WDOG_STCTRLH_WINEN(config->enableWindowMode) | - WDOG_STCTRLH_ALLOWUPDATE(config->enableUpdate) | WDOG_STCTRLH_DBGEN(config->workMode.enableDebug) | - WDOG_STCTRLH_STOPEN(config->workMode.enableStop) | -#if defined(FSL_FEATURE_WDOG_HAS_WAITEN) && FSL_FEATURE_WDOG_HAS_WAITEN - WDOG_STCTRLH_WAITEN(config->workMode.enableWait) | -#endif /* FSL_FEATURE_WDOG_HAS_WAITEN */ - WDOG_STCTRLH_DISTESTWDOG(1U); - - /* Disable the global interrupts. Otherwise, an interrupt could effectively invalidate the unlock sequence - * and the WCT may expire. After the configuration finishes, re-enable the global interrupts. */ - primaskValue = DisableGlobalIRQ(); - WDOG_Unlock(base); - /* Wait one bus clock cycle */ - base->RSTCNT = 0U; - /* Set configruation */ - base->PRESC = WDOG_PRESC_PRESCVAL(config->prescaler); - base->WINH = (uint16_t)((config->windowValue >> 16U) & 0xFFFFU); - base->WINL = (uint16_t)((config->windowValue) & 0xFFFFU); - base->TOVALH = (uint16_t)((config->timeoutValue >> 16U) & 0xFFFFU); - base->TOVALL = (uint16_t)((config->timeoutValue) & 0xFFFFU); - base->STCTRLH = value; - EnableGlobalIRQ(primaskValue); -} - -void WDOG_Deinit(WDOG_Type *base) -{ - uint32_t primaskValue = 0U; - - /* Disable the global interrupts */ - primaskValue = DisableGlobalIRQ(); - WDOG_Unlock(base); - /* Wait one bus clock cycle */ - base->RSTCNT = 0U; - WDOG_Disable(base); - EnableGlobalIRQ(primaskValue); - WDOG_ClearResetCount(base); -} - -void WDOG_SetTestModeConfig(WDOG_Type *base, wdog_test_config_t *config) -{ - assert(config); - - uint32_t value = 0U; - uint32_t primaskValue = 0U; - - value = WDOG_STCTRLH_DISTESTWDOG(0U) | WDOG_STCTRLH_TESTWDOG(1U) | WDOG_STCTRLH_TESTSEL(config->testMode) | - WDOG_STCTRLH_BYTESEL(config->testedByte) | WDOG_STCTRLH_IRQRSTEN(0U) | WDOG_STCTRLH_WDOGEN(1U) | - WDOG_STCTRLH_ALLOWUPDATE(1U); - - /* Disable the global interrupts. Otherwise, an interrupt could effectively invalidate the unlock sequence - * and the WCT may expire. After the configuration finishes, re-enable the global interrupts. */ - primaskValue = DisableGlobalIRQ(); - WDOG_Unlock(base); - /* Wait one bus clock cycle */ - base->RSTCNT = 0U; - /* Set configruation */ - base->TOVALH = (uint16_t)((config->timeoutValue >> 16U) & 0xFFFFU); - base->TOVALL = (uint16_t)((config->timeoutValue) & 0xFFFFU); - base->STCTRLH = value; - EnableGlobalIRQ(primaskValue); -} - -uint32_t WDOG_GetStatusFlags(WDOG_Type *base) -{ - uint32_t status_flag = 0U; - - status_flag |= (base->STCTRLH & WDOG_STCTRLH_WDOGEN_MASK); - status_flag |= (base->STCTRLL & WDOG_STCTRLL_INTFLG_MASK); - - return status_flag; -} - -void WDOG_ClearStatusFlags(WDOG_Type *base, uint32_t mask) -{ - if (mask & kWDOG_TimeoutFlag) - { - base->STCTRLL |= WDOG_STCTRLL_INTFLG_MASK; - } -} - -void WDOG_Refresh(WDOG_Type *base) -{ - uint32_t primaskValue = 0U; - - /* Disable the global interrupt to protect refresh sequence */ - primaskValue = DisableGlobalIRQ(); - base->REFRESH = WDOG_FIRST_WORD_OF_REFRESH; - base->REFRESH = WDOG_SECOND_WORD_OF_REFRESH; - EnableGlobalIRQ(primaskValue); -} diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_wdog.h b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_wdog.h deleted file mode 100644 index 580adb95a0f..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/drivers/fsl_wdog.h +++ /dev/null @@ -1,433 +0,0 @@ -/* - * Copyright (c) 2015, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -#ifndef _FSL_WDOG_H_ -#define _FSL_WDOG_H_ - -#include "fsl_common.h" - -/*! - * @addtogroup wdog - * @{ - */ - - -/******************************************************************************* - * Definitions - *******************************************************************************/ - -/*! @name Driver version */ -/*@{*/ -/*! @brief Defines WDOG driver version 2.0.0. */ -#define FSL_WDOG_DRIVER_VERSION (MAKE_VERSION(2, 0, 0)) -/*@}*/ - -/*! @name Unlock sequence */ -/*@{*/ -#define WDOG_FIRST_WORD_OF_UNLOCK (0xC520U) /*!< First word of unlock sequence */ -#define WDOG_SECOND_WORD_OF_UNLOCK (0xD928U) /*!< Second word of unlock sequence */ -/*@}*/ - -/*! @name Refresh sequence */ -/*@{*/ -#define WDOG_FIRST_WORD_OF_REFRESH (0xA602U) /*!< First word of refresh sequence */ -#define WDOG_SECOND_WORD_OF_REFRESH (0xB480U) /*!< Second word of refresh sequence */ -/*@}*/ - -/*! @brief Describes WDOG clock source. */ -typedef enum _wdog_clock_source -{ - kWDOG_LpoClockSource = 0U, /*!< WDOG clock sourced from LPO*/ - kWDOG_AlternateClockSource = 1U, /*!< WDOG clock sourced from alternate clock source*/ -} wdog_clock_source_t; - -/*! @brief Defines WDOG work mode. */ -typedef struct _wdog_work_mode -{ -#if defined(FSL_FEATURE_WDOG_HAS_WAITEN) && FSL_FEATURE_WDOG_HAS_WAITEN - bool enableWait; /*!< Enables or disables WDOG in wait mode */ -#endif /* FSL_FEATURE_WDOG_HAS_WAITEN */ - bool enableStop; /*!< Enables or disables WDOG in stop mode */ - bool enableDebug; /*!< Enables or disables WDOG in debug mode */ -} wdog_work_mode_t; - -/*! @brief Describes the selection of the clock prescaler. */ -typedef enum _wdog_clock_prescaler -{ - kWDOG_ClockPrescalerDivide1 = 0x0U, /*!< Divided by 1 */ - kWDOG_ClockPrescalerDivide2 = 0x1U, /*!< Divided by 2 */ - kWDOG_ClockPrescalerDivide3 = 0x2U, /*!< Divided by 3 */ - kWDOG_ClockPrescalerDivide4 = 0x3U, /*!< Divided by 4 */ - kWDOG_ClockPrescalerDivide5 = 0x4U, /*!< Divided by 5 */ - kWDOG_ClockPrescalerDivide6 = 0x5U, /*!< Divided by 6 */ - kWDOG_ClockPrescalerDivide7 = 0x6U, /*!< Divided by 7 */ - kWDOG_ClockPrescalerDivide8 = 0x7U, /*!< Divided by 8 */ -} wdog_clock_prescaler_t; - -/*! @brief Describes WDOG configuration structure. */ -typedef struct _wdog_config -{ - bool enableWdog; /*!< Enables or disables WDOG */ - wdog_clock_source_t clockSource; /*!< Clock source select */ - wdog_clock_prescaler_t prescaler; /*!< Clock prescaler value */ - wdog_work_mode_t workMode; /*!< Configures WDOG work mode in debug stop and wait mode */ - bool enableUpdate; /*!< Update write-once register enable */ - bool enableInterrupt; /*!< Enables or disables WDOG interrupt */ - bool enableWindowMode; /*!< Enables or disables WDOG window mode */ - uint32_t windowValue; /*!< Window value */ - uint32_t timeoutValue; /*!< Timeout value */ -} wdog_config_t; - -/*! @brief Describes WDOG test mode. */ -typedef enum _wdog_test_mode -{ - kWDOG_QuickTest = 0U, /*!< Selects quick test */ - kWDOG_ByteTest = 1U, /*!< Selects byte test */ -} wdog_test_mode_t; - -/*! @brief Describes WDOG tested byte selection in byte test mode. */ -typedef enum _wdog_tested_byte -{ - kWDOG_TestByte0 = 0U, /*!< Byte 0 selected in byte test mode */ - kWDOG_TestByte1 = 1U, /*!< Byte 1 selected in byte test mode */ - kWDOG_TestByte2 = 2U, /*!< Byte 2 selected in byte test mode */ - kWDOG_TestByte3 = 3U, /*!< Byte 3 selected in byte test mode */ -} wdog_tested_byte_t; - -/*! @brief Describes WDOG test mode configuration structure. */ -typedef struct _wdog_test_config -{ - wdog_test_mode_t testMode; /*!< Selects test mode */ - wdog_tested_byte_t testedByte; /*!< Selects tested byte in byte test mode */ - uint32_t timeoutValue; /*!< Timeout value */ -} wdog_test_config_t; - -/*! - * @brief WDOG interrupt configuration structure, default settings all disabled. - * - * This structure contains the settings for all of the WDOG interrupt configurations. - */ -enum _wdog_interrupt_enable_t -{ - kWDOG_InterruptEnable = WDOG_STCTRLH_IRQRSTEN_MASK, /*!< WDOG timeout generates an interrupt before reset*/ -}; - -/*! - * @brief WDOG status flags. - * - * This structure contains the WDOG status flags for use in the WDOG functions. - */ -enum _wdog_status_flags_t -{ - kWDOG_RunningFlag = WDOG_STCTRLH_WDOGEN_MASK, /*!< Running flag, set when WDOG is enabled*/ - kWDOG_TimeoutFlag = WDOG_STCTRLL_INTFLG_MASK, /*!< Interrupt flag, set when an exception occurs*/ -}; - -/******************************************************************************* - * API - *******************************************************************************/ - -#if defined(__cplusplus) -extern "C" { -#endif /* __cplusplus */ - -/*! - * @name WDOG Initialization and De-initialization - * @{ - */ - -/*! - * @brief Initializes the WDOG configuration sturcture. - * - * This function initializes the WDOG configuration structure to default values. The default - * values are as follows. - * @code - * wdogConfig->enableWdog = true; - * wdogConfig->clockSource = kWDOG_LpoClockSource; - * wdogConfig->prescaler = kWDOG_ClockPrescalerDivide1; - * wdogConfig->workMode.enableWait = true; - * wdogConfig->workMode.enableStop = false; - * wdogConfig->workMode.enableDebug = false; - * wdogConfig->enableUpdate = true; - * wdogConfig->enableInterrupt = false; - * wdogConfig->enableWindowMode = false; - * wdogConfig->windowValue = 0; - * wdogConfig->timeoutValue = 0xFFFFU; - * @endcode - * - * @param config Pointer to the WDOG configuration structure. - * @see wdog_config_t - */ -void WDOG_GetDefaultConfig(wdog_config_t *config); - -/*! - * @brief Initializes the WDOG. - * - * This function initializes the WDOG. When called, the WDOG runs according to the configuration. - * To reconfigure WDOG without forcing a reset first, enableUpdate must be set to true - * in the configuration. - * - * This is an example. - * @code - * wdog_config_t config; - * WDOG_GetDefaultConfig(&config); - * config.timeoutValue = 0x7ffU; - * config.enableUpdate = true; - * WDOG_Init(wdog_base,&config); - * @endcode - * - * @param base WDOG peripheral base address - * @param config The configuration of WDOG - */ -void WDOG_Init(WDOG_Type *base, const wdog_config_t *config); - -/*! - * @brief Shuts down the WDOG. - * - * This function shuts down the WDOG. - * Ensure that the WDOG_STCTRLH.ALLOWUPDATE is 1 which indicates that the register update is enabled. - */ -void WDOG_Deinit(WDOG_Type *base); - -/*! - * @brief Configures the WDOG functional test. - * - * This function is used to configure the WDOG functional test. When called, the WDOG goes into test mode - * and runs according to the configuration. - * Ensure that the WDOG_STCTRLH.ALLOWUPDATE is 1 which means that the register update is enabled. - * - * This is an example. - * @code - * wdog_test_config_t test_config; - * test_config.testMode = kWDOG_QuickTest; - * test_config.timeoutValue = 0xfffffu; - * WDOG_SetTestModeConfig(wdog_base, &test_config); - * @endcode - * @param base WDOG peripheral base address - * @param config The functional test configuration of WDOG - */ -void WDOG_SetTestModeConfig(WDOG_Type *base, wdog_test_config_t *config); - -/* @} */ - -/*! - * @name WDOG Functional Operation - * @{ - */ - -/*! - * @brief Enables the WDOG module. - * - * This function write value into WDOG_STCTRLH register to enable the WDOG, it is a write-once register, - * make sure that the WCT window is still open and this register has not been written in this WCT - * while this function is called. - * - * @param base WDOG peripheral base address - */ -static inline void WDOG_Enable(WDOG_Type *base) -{ - base->STCTRLH |= WDOG_STCTRLH_WDOGEN_MASK; -} - -/*! - * @brief Disables the WDOG module. - * - * This function writes a value into the WDOG_STCTRLH register to disable the WDOG. It is a write-once register. - * Ensure that the WCT window is still open and that register has not been written to in this WCT - * while the function is called. - * - * @param base WDOG peripheral base address - */ -static inline void WDOG_Disable(WDOG_Type *base) -{ - base->STCTRLH &= ~WDOG_STCTRLH_WDOGEN_MASK; -} - -/*! - * @brief Enables the WDOG interrupt. - * - * This function writes a value into the WDOG_STCTRLH register to enable the WDOG interrupt. It is a write-once register. - * Ensure that the WCT window is still open and the register has not been written to in this WCT - * while the function is called. - * - * @param base WDOG peripheral base address - * @param mask The interrupts to enable - * The parameter can be combination of the following source if defined. - * @arg kWDOG_InterruptEnable - */ -static inline void WDOG_EnableInterrupts(WDOG_Type *base, uint32_t mask) -{ - base->STCTRLH |= mask; -} - -/*! - * @brief Disables the WDOG interrupt. - * - * This function writes a value into the WDOG_STCTRLH register to disable the WDOG interrupt. It is a write-once register. - * Ensure that the WCT window is still open and the register has not been written to in this WCT - * while the function is called. - * - * @param base WDOG peripheral base address - * @param mask The interrupts to disable - * The parameter can be combination of the following source if defined. - * @arg kWDOG_InterruptEnable - */ -static inline void WDOG_DisableInterrupts(WDOG_Type *base, uint32_t mask) -{ - base->STCTRLH &= ~mask; -} - -/*! - * @brief Gets the WDOG all status flags. - * - * This function gets all status flags. - * - * This is an example for getting the Running Flag. - * @code - * uint32_t status; - * status = WDOG_GetStatusFlags (wdog_base) & kWDOG_RunningFlag; - * @endcode - * @param base WDOG peripheral base address - * @return State of the status flag: asserted (true) or not-asserted (false).@see _wdog_status_flags_t - * - true: a related status flag has been set. - * - false: a related status flag is not set. - */ -uint32_t WDOG_GetStatusFlags(WDOG_Type *base); - -/*! - * @brief Clears the WDOG flag. - * - * This function clears the WDOG status flag. - * - * This is an example for clearing the timeout (interrupt) flag. - * @code - * WDOG_ClearStatusFlags(wdog_base,kWDOG_TimeoutFlag); - * @endcode - * @param base WDOG peripheral base address - * @param mask The status flags to clear. - * The parameter could be any combination of the following values. - * kWDOG_TimeoutFlag - */ -void WDOG_ClearStatusFlags(WDOG_Type *base, uint32_t mask); - -/*! - * @brief Sets the WDOG timeout value. - * - * This function sets the timeout value. - * It should be ensured that the time-out value for the WDOG is always greater than - * 2xWCT time + 20 bus clock cycles. - * This function writes a value into WDOG_TOVALH and WDOG_TOVALL registers which are wirte-once. - * Ensure the WCT window is still open and the two registers have not been written to in this WCT - * while the function is called. - * - * @param base WDOG peripheral base address - * @param timeoutCount WDOG timeout value; count of WDOG clock tick. - */ -static inline void WDOG_SetTimeoutValue(WDOG_Type *base, uint32_t timeoutCount) -{ - base->TOVALH = (uint16_t)((timeoutCount >> 16U) & 0xFFFFU); - base->TOVALL = (uint16_t)((timeoutCount)&0xFFFFU); -} - -/*! - * @brief Sets the WDOG window value. - * - * This function sets the WDOG window value. - * This function writes a value into WDOG_WINH and WDOG_WINL registers which are wirte-once. - * Ensure the WCT window is still open and the two registers have not been written to in this WCT - * while the function is called. - * - * @param base WDOG peripheral base address - * @param windowValue WDOG window value. - */ -static inline void WDOG_SetWindowValue(WDOG_Type *base, uint32_t windowValue) -{ - base->WINH = (uint16_t)((windowValue >> 16U) & 0xFFFFU); - base->WINL = (uint16_t)((windowValue)&0xFFFFU); -} - -/*! - * @brief Unlocks the WDOG register written. - * - * This function unlocks the WDOG register written. - * Before starting the unlock sequence and following congfiguration, disable the global interrupts. - * Otherwise, an interrupt may invalidate the unlocking sequence and the WCT may expire. - * After the configuration finishes, re-enable the global interrupts. - * - * @param base WDOG peripheral base address - */ -static inline void WDOG_Unlock(WDOG_Type *base) -{ - base->UNLOCK = WDOG_FIRST_WORD_OF_UNLOCK; - base->UNLOCK = WDOG_SECOND_WORD_OF_UNLOCK; -} - -/*! - * @brief Refreshes the WDOG timer. - * - * This function feeds the WDOG. - * This function should be called before the WDOG timer is in timeout. Otherwise, a reset is asserted. - * - * @param base WDOG peripheral base address - */ -void WDOG_Refresh(WDOG_Type *base); - -/*! - * @brief Gets the WDOG reset count. - * - * This function gets the WDOG reset count value. - * - * @param base WDOG peripheral base address - * @return WDOG reset count value. - */ -static inline uint16_t WDOG_GetResetCount(WDOG_Type *base) -{ - return base->RSTCNT; -} -/*! - * @brief Clears the WDOG reset count. - * - * This function clears the WDOG reset count value. - * - * @param base WDOG peripheral base address - */ -static inline void WDOG_ClearResetCount(WDOG_Type *base) -{ - base->RSTCNT |= UINT16_MAX; -} - -/*@}*/ - -#if defined(__cplusplus) -} -#endif /* __cplusplus */ - -/*! @}*/ - -#endif /* _FSL_WDOG_H_ */ diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/flash_api.c b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/flash_api.c deleted file mode 100644 index a7c585515ac..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/flash_api.c +++ /dev/null @@ -1,87 +0,0 @@ -/* mbed Microcontroller Library - * Copyright (c) 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. - * You may obtain a copy of the License at - * - * 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, - * 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. - */ - -#include "flash_api.h" -#include "flash_data.h" -#include "mbed_critical.h" - -// This file is automagically generated - -// This is a flash algo binary blob. It is PIC (position independent code) that should be stored in RAM -static uint32_t FLASH_ALGO[] = { - 0xb5104938, 0x60084449, 0xf24c4837, 0x81c15120, 0x1128f64d, 0x880181c1, 0x0101f021, 0x48348001, - 0x44484932, 0x1280f44f, 0x21006001, 0x1201e9c0, 0x52a0f04f, 0xf44f6142, 0x61824280, 0x1020f880, - 0x62411e49, 0xf939f000, 0xd0002800, 0xbd102001, 0x47702000, 0x4a27b508, 0x9200447a, 0x02cff3c1, - 0x48234601, 0x44482300, 0xf92cf000, 0xd0002800, 0xbd082001, 0x491fb508, 0x481d4479, 0x44483920, - 0xf89ff000, 0xd10f2800, 0x4478481a, 0x38324b1a, 0x9000447b, 0x22084816, 0x6181f44f, 0xf0004448, - 0x2800f959, 0x2001d000, 0x4b12bd08, 0x4601447b, 0x3b54480f, 0x5280f44f, 0xf0004448, 0xb508b8b6, - 0x1dc94613, 0x0207f021, 0x4479490a, 0x91003972, 0x48074601, 0xf0004448, 0x2800f93d, 0x2001d000, - 0x0000bd08, 0x00000004, 0x40052000, 0x40020000, 0x00000008, 0x000000a1, 0x0000037c, 0x4604b570, - 0x25006800, 0x061b7803, 0x2370d5fc, 0x20007003, 0x280ce03a, 0xe8dfd236, 0x0a06f000, 0x1a16120e, - 0x2a26221e, 0x6826322e, 0x71f37813, 0x6826e02a, 0x71b37853, 0x6826e026, 0x71737893, 0x6826e022, - 0x713378d3, 0x6826e01e, 0x72f37913, 0x6826e01a, 0x72b37953, 0x6826e016, 0x72737993, 0x6826e012, - 0x723379d3, 0x6826e00e, 0x73f37a13, 0x6826e00a, 0x73b37a53, 0x6826e006, 0x73737a93, 0x6826e002, - 0x73337ad3, 0xb2c01c40, 0xd9c24288, 0x20806821, 0xe0037008, 0x1c416a60, 0x4780d000, 0x78006820, - 0xd5f70600, 0x78006820, 0xd5010681, 0xe0062504, 0xd50106c1, 0xe0022508, 0xd00007c0, 0x46282510, - 0xb508bd70, 0x460b2244, 0x2000f88d, 0x2100466a, 0xbd084798, 0x4614b538, 0xd002070a, 0x7080f44f, - 0x6843bd38, 0xd803428b, 0x441a6882, 0xd80c428a, 0x428b68c3, 0x6902d803, 0x428a441a, 0x2002d801, - 0x1ac9bd38, 0x0100f501, 0x1ac9e000, 0xf88d2208, 0x0c0a2000, 0x2001f88d, 0xf88d0a0a, 0xf88d2002, - 0x466a1003, 0x47a02103, 0xe92dbd38, 0x460745f8, 0x46164698, 0x2000687b, 0x428b198a, 0x68bcd803, - 0x4294441c, 0x68fbd20e, 0xd803428b, 0x441c693c, 0xd2024294, 0xe8bd2002, 0x1acc85f8, 0x0400f504, - 0xe0022500, 0xf44f1acc, 0xfbb45580, 0xfb05f1f5, 0xb1114111, 0x7080f44f, 0xfbb6e7ed, 0xfb05f1f5, - 0xb1a96111, 0xe7e62001, 0xa000f88d, 0xf88d0c20, 0x0a200001, 0x0002f88d, 0x4003f88d, 0x2103466a, - 0x46434638, 0x28004798, 0x1b76d1d5, 0xe001442c, 0x0a09f04f, 0xd1e72e00, 0x4601e7cd, 0x61082000, - 0x477061c8, 0x41fce92d, 0x9d086846, 0x1402eb01, 0xd803428e, 0x44376887, 0xd80a428f, 0x428f68c7, - 0xf8d0d804, 0x4467c010, 0xd802428f, 0xe8bd2002, 0x42a681fc, 0x6887d805, 0x42a74437, 0x1b89d301, - 0x68c6e009, 0xd90342a6, 0x44376907, 0xd3ed42a7, 0xf5011b89, 0x24100100, 0xf6f4fbb1, 0x1416fb04, - 0xf44fb114, 0xe7e27080, 0xf88d2401, 0x0c0c4000, 0x4001f88d, 0xf88d0a0c, 0xf88d4002, 0x0a111003, - 0x1004f88d, 0x2005f88d, 0x3006f88d, 0x2106466a, 0xe7cc47a8, 0x43fee92d, 0x46074616, 0x2000461c, - 0xf8dd198a, 0x074b8028, 0xf44fd003, 0xe8bd7080, 0x077383fe, 0x2001d001, 0x687be7f9, 0xd803428b, - 0x441d68bd, 0xd20c4295, 0x428b68fb, 0x693dd803, 0x4295441d, 0x2002d201, 0x1acde7e9, 0x0500f505, - 0x1acde02e, 0x2007e02c, 0x0000f88d, 0xf88d0c28, 0x0a280001, 0x0002f88d, 0x5003f88d, 0xf88d78e0, - 0x78a00004, 0x0005f88d, 0xf88d7860, 0x78200006, 0x0007f88d, 0xf88d79e0, 0x79a00008, 0x0009f88d, - 0xf88d7960, 0x7920000a, 0x000bf88d, 0x210b466a, 0x46434638, 0x28004798, 0x3508d1b9, 0x34083e08, - 0xd1d02e00, 0x0000e7b3, 0xfffffffe, 0x00000000, 0xffffffff, 0xfffffffe, 0x00000000, 0x00000000, - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, - 0x00000000, 0x00000000 -}; - -static const flash_algo_t flash_algo_config = { - .init = 0x1, - .uninit = 0x51, - .erase_sector = 0xab, - .program_page = 0xbf, - .static_base = 0x418, - .algo_blob = FLASH_ALGO -}; - -static const sector_info_t sectors_info[] = { - {0x0, 0x1000}, -}; - -static const flash_target_config_t flash_target_config = { - .page_size = 0x200, - .flash_start = 0x0, - .flash_size = 0x100000, - .sectors = sectors_info, - .sector_info_count = sizeof(sectors_info) / sizeof(sector_info_t) -}; - -void flash_set_target_config(flash_t *obj) -{ - obj->flash_algo = &flash_algo_config; - obj->target_config = &flash_target_config; -} diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/peripheral_clock_defines.h b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/peripheral_clock_defines.h deleted file mode 100644 index e78b331e346..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/peripheral_clock_defines.h +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) 2016, Freescale Semiconductor, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * o Redistributions of source code must retain the above copyright notice, this list - * of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright notice, this - * list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * o Neither the name of Freescale Semiconductor, Inc. nor the names of its - * contributors may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef _FSL_PERIPHERAL_CLOCK_H_ -#define _FSL_PERIPHERAL_CLOCK_H_ - -#include "fsl_clock.h" - -/* Array for UART module clocks */ -#define UART_CLOCK_FREQS \ - { \ - UART0_CLK_SRC, UART1_CLK_SRC, UART2_CLK_SRC, UART3_CLK_SRC, UART4_CLK_SRC, UART5_CLK_SRC \ - } - -/* Array for I2C module clocks */ -#define I2C_CLOCK_FREQS \ - { \ - I2C0_CLK_SRC, I2C1_CLK_SRC, I2C2_CLK_SRC \ - } - -/* Array for DSPI module clocks */ -#define SPI_CLOCK_FREQS \ - { \ - DSPI0_CLK_SRC, DSPI1_CLK_SRC, DSPI2_CLK_SRC \ - } - -#endif /* _FSL_PERIPHERAL_CLOCK_H_ */ diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/pwmout_api.c b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/pwmout_api.c deleted file mode 100644 index f7a9ba0ba9c..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/pwmout_api.c +++ /dev/null @@ -1,153 +0,0 @@ -/* mbed Microcontroller Library - * Copyright (c) 2006-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. - * You may obtain a copy of the License at - * - * 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, - * 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. - */ -#include "mbed_assert.h" -#include "pwmout_api.h" - -#if DEVICE_PWMOUT - -#include "cmsis.h" -#include "pinmap.h" -#include "fsl_ftm.h" -#include "PeripheralPins.h" - -static float pwm_clock_mhz; -/* Array of FTM peripheral base address. */ -static FTM_Type *const ftm_addrs[] = FTM_BASE_PTRS; - -void pwmout_init(pwmout_t* obj, PinName pin) -{ - PWMName pwm = (PWMName)pinmap_peripheral(pin, PinMap_PWM); - MBED_ASSERT(pwm != (PWMName)NC); - - obj->pwm_name = pwm; - - uint32_t pwm_base_clock; - pwm_base_clock = CLOCK_GetFreq(kCLOCK_BusClk); - float clkval = (float)pwm_base_clock / 1000000.0f; - uint32_t clkdiv = 0; - while (clkval > 1) { - clkdiv++; - clkval /= 2.0f; - if (clkdiv == 7) { - break; - } - } - - pwm_clock_mhz = clkval; - uint32_t channel = pwm & 0xF; - uint32_t instance = pwm >> TPM_SHIFT; - ftm_config_t ftmInfo; - - FTM_GetDefaultConfig(&ftmInfo); - ftmInfo.prescale = (ftm_clock_prescale_t)clkdiv; - /* Initialize FTM module */ - FTM_Init(ftm_addrs[instance], &ftmInfo); - - ftm_addrs[instance]->CONF |= FTM_CONF_NUMTOF(3); - - ftm_chnl_pwm_signal_param_t config = { - .chnlNumber = (ftm_chnl_t)channel, - .level = kFTM_HighTrue, - .dutyCyclePercent = 0, - .firstEdgeDelayPercent = 0 - }; - // default to 20ms: standard for servos, and fine for e.g. brightness control - FTM_SetupPwm(ftm_addrs[instance], &config, 1, kFTM_EdgeAlignedPwm, 50, pwm_base_clock); - - FTM_StartTimer(ftm_addrs[instance], kFTM_SystemClock); - - // Wire pinout - pinmap_pinout(pin, PinMap_PWM); -} - -void pwmout_free(pwmout_t* obj) -{ - FTM_Deinit(ftm_addrs[obj->pwm_name >> TPM_SHIFT]); -} - -void pwmout_write(pwmout_t* obj, float value) -{ - if (value < 0.0f) { - value = 0.0f; - } else if (value > 1.0f) { - value = 1.0f; - } - - FTM_Type *base = ftm_addrs[obj->pwm_name >> TPM_SHIFT]; - uint16_t mod = base->MOD & FTM_MOD_MOD_MASK; - uint32_t new_count = (uint32_t)((float)(mod) * value); - // Update of CnV register - base->CONTROLS[obj->pwm_name & 0xF].CnV = new_count; - base->CNT = 0; - /* Software trigger to update registers */ - FTM_SetSoftwareTrigger(base, true); -} - -float pwmout_read(pwmout_t* obj) -{ - FTM_Type *base = ftm_addrs[obj->pwm_name >> TPM_SHIFT]; - uint16_t count = (base->CONTROLS[obj->pwm_name & 0xF].CnV) & FTM_CnV_VAL_MASK; - uint16_t mod = base->MOD & FTM_MOD_MOD_MASK; - - if (mod == 0) - return 0.0; - float v = (float)(count) / (float)(mod); - return (v > 1.0f) ? (1.0f) : (v); -} - -void pwmout_period(pwmout_t* obj, float seconds) -{ - pwmout_period_us(obj, seconds * 1000000.0f); -} - -void pwmout_period_ms(pwmout_t* obj, int ms) -{ - pwmout_period_us(obj, ms * 1000); -} - -// Set the PWM period, keeping the duty cycle the same. -void pwmout_period_us(pwmout_t* obj, int us) -{ - FTM_Type *base = ftm_addrs[obj->pwm_name >> TPM_SHIFT]; - float dc = pwmout_read(obj); - - // Stop FTM clock to ensure instant update of MOD register - base->MOD = FTM_MOD_MOD((pwm_clock_mhz * (float)us) - 1); - pwmout_write(obj, dc); -} - -void pwmout_pulsewidth(pwmout_t* obj, float seconds) -{ - pwmout_pulsewidth_us(obj, seconds * 1000000.0f); -} - -void pwmout_pulsewidth_ms(pwmout_t* obj, int ms) -{ - pwmout_pulsewidth_us(obj, ms * 1000); -} - -void pwmout_pulsewidth_us(pwmout_t* obj, int us) -{ - FTM_Type *base = ftm_addrs[obj->pwm_name >> TPM_SHIFT]; - uint32_t value = (uint32_t)(pwm_clock_mhz * (float)us); - - // Update of CnV register - base->CONTROLS[obj->pwm_name & 0xF].CnV = value; - /* Software trigger to update registers */ - FTM_SetSoftwareTrigger(base, true); -} - -#endif diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/serial_api.c b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/serial_api.c deleted file mode 100644 index b706932e943..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/serial_api.c +++ /dev/null @@ -1,706 +0,0 @@ -/* mbed Microcontroller Library - * Copyright (c) 2006-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. - * You may obtain a copy of the License at - * - * 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, - * 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. - */ -#include "serial_api.h" - -#if DEVICE_SERIAL - -// math.h required for floating point operations for baud rate calculation -#include -#include "mbed_assert.h" - -#include - -#include "cmsis.h" -#include "pinmap.h" -#include "fsl_uart.h" -#include "peripheral_clock_defines.h" -#include "PeripheralPins.h" -#include "dma_reqs.h" -#include "fsl_clock_config.h" - -static uint32_t serial_irq_ids[FSL_FEATURE_SOC_UART_COUNT] = {0}; -static uart_irq_handler irq_handler; -/* Array of UART peripheral base address. */ -static UART_Type *const uart_addrs[] = UART_BASE_PTRS; -/* Array of UART bus clock frequencies */ -static clock_name_t const uart_clocks[] = UART_CLOCK_FREQS; - -/* UART transfer states */ -#define kUART_TxIdle 0 -#define kUART_TxBusy 1 -#define kUART_RxIdle 2 -#define kUART_RxBusy 3 - -int stdio_uart_inited = 0; -serial_t stdio_uart; - -void serial_init(serial_t *obj, PinName tx, PinName rx) -{ - uint32_t uart_tx = pinmap_peripheral(tx, PinMap_UART_TX); - uint32_t uart_rx = pinmap_peripheral(rx, PinMap_UART_RX); - obj->serial.index = pinmap_merge(uart_tx, uart_rx); - MBED_ASSERT((int)obj->serial.index != NC); - - uart_config_t config; - - UART_GetDefaultConfig(&config); - config.baudRate_Bps = 9600; - config.enableTx = false; - config.enableRx = false; - - UART_Init(uart_addrs[obj->serial.index], &config, CLOCK_GetFreq(uart_clocks[obj->serial.index])); - - pinmap_pinout(tx, PinMap_UART_TX); - pinmap_pinout(rx, PinMap_UART_RX); - - if (tx != NC) { - UART_EnableTx(uart_addrs[obj->serial.index], true); - pin_mode(tx, PullUp); - } - if (rx != NC) { - UART_EnableRx(uart_addrs[obj->serial.index], true); - pin_mode(rx, PullUp); - } - - if (obj->serial.index == STDIO_UART) { - stdio_uart_inited = 1; - memcpy(&stdio_uart, obj, sizeof(serial_t)); - } - - obj->serial.uartDmaRx.dmaUsageState = DMA_USAGE_OPPORTUNISTIC;; - obj->serial.txstate = kUART_TxIdle; - obj->serial.rxstate = kUART_RxIdle; - - /* Zero the handle. */ - memset(&(obj->serial.uart_transfer_handle), 0, sizeof(obj->serial.uart_transfer_handle)); -} - -void serial_free(serial_t *obj) -{ - UART_Deinit(uart_addrs[obj->serial.index]); - serial_irq_ids[obj->serial.index] = 0; -} - -void serial_baud(serial_t *obj, int baudrate) -{ - UART_SetBaudRate(uart_addrs[obj->serial.index], (uint32_t)baudrate, CLOCK_GetFreq(uart_clocks[obj->serial.index])); -} - -void serial_format(serial_t *obj, int data_bits, SerialParity parity, int stop_bits) -{ - UART_Type *base = uart_addrs[obj->serial.index]; - uint8_t temp; - /* Set bit count and parity mode. */ - temp = base->C1 & ~(UART_C1_PE_MASK | UART_C1_PT_MASK | UART_C1_M_MASK); - if (parity != ParityNone) - { - /* Enable Parity */ - temp |= (UART_C1_PE_MASK | UART_C1_M_MASK); - if (parity == ParityOdd) { - temp |= UART_C1_PT_MASK; - } else if (parity == ParityEven) { - // PT=0 so nothing more to do - } else { - // Hardware does not support forced parity - MBED_ASSERT(0); - } - } - base->C1 = temp; -#if defined(FSL_FEATURE_UART_HAS_STOP_BIT_CONFIG_SUPPORT) && FSL_FEATURE_UART_HAS_STOP_BIT_CONFIG_SUPPORT - /* Set stop bit per char */ - base->BDH = (base->BDH & ~UART_BDH_SBNS_MASK) | UART_BDH_SBNS((uint8_t)--stop_bits); -#endif -} - -/****************************************************************************** - * INTERRUPTS HANDLING - ******************************************************************************/ -static inline void uart_irq(uint32_t transmit_empty, uint32_t receive_full, uint32_t index) -{ - UART_Type *base = uart_addrs[index]; - - /* If RX overrun. */ - if (UART_S1_OR_MASK & base->S1) - { - /* Read base->D, otherwise the RX does not work. */ - (void)base->D; - } - - if (serial_irq_ids[index] != 0) { - if (transmit_empty) - irq_handler(serial_irq_ids[index], TxIrq); - - if (receive_full) - irq_handler(serial_irq_ids[index], RxIrq); - } -} - -void uart0_irq() -{ - uint32_t status_flags = UART0->S1; - uart_irq((status_flags & kUART_TxDataRegEmptyFlag), (status_flags & kUART_RxDataRegFullFlag), 0); -} - -void uart1_irq() -{ - uint32_t status_flags = UART1->S1; - uart_irq((status_flags & UART_S1_TDRE_MASK), (status_flags & UART_S1_RDRF_MASK), 1); -} - -void uart2_irq() -{ - uint32_t status_flags = UART2->S1; - uart_irq((status_flags & UART_S1_TDRE_MASK), (status_flags & UART_S1_RDRF_MASK), 2); -} - -void uart3_irq() -{ - uint32_t status_flags = UART3->S1; - uart_irq((status_flags & UART_S1_TDRE_MASK), (status_flags & UART_S1_RDRF_MASK), 3); -} - -void uart4_irq() -{ - uint32_t status_flags = UART4->S1; - uart_irq((status_flags & UART_S1_TDRE_MASK), (status_flags & UART_S1_RDRF_MASK), 4); -} - -void uart5_irq() -{ - uint32_t status_flags = UART5->S1; - uart_irq((status_flags & UART_S1_TDRE_MASK), (status_flags & UART_S1_RDRF_MASK), 5); -} - -void serial_irq_handler(serial_t *obj, uart_irq_handler handler, uint32_t id) -{ - irq_handler = handler; - serial_irq_ids[obj->serial.index] = id; -} - -void serial_irq_set(serial_t *obj, SerialIrq irq, uint32_t enable) -{ - IRQn_Type uart_irqs[] = UART_RX_TX_IRQS; - uint32_t vector = 0; - - switch (obj->serial.index) { - case 0: - vector = (uint32_t)&uart0_irq; - break; - case 1: - vector = (uint32_t)&uart1_irq; - break; - case 2: - vector = (uint32_t)&uart2_irq; - break; - case 3: - vector = (uint32_t)&uart3_irq; - break; - case 4: - vector = (uint32_t)&uart4_irq; - break; - case 5: - vector = (uint32_t)&uart5_irq; - break; - default: - break; - } - - if (enable) { - switch (irq) { - case RxIrq: - UART_EnableInterrupts(uart_addrs[obj->serial.index], kUART_RxDataRegFullInterruptEnable); - break; - case TxIrq: - UART_EnableInterrupts(uart_addrs[obj->serial.index], kUART_TxDataRegEmptyInterruptEnable); - break; - default: - break; - } - NVIC_SetVector(uart_irqs[obj->serial.index], vector); - NVIC_EnableIRQ(uart_irqs[obj->serial.index]); - - } else { // disable - int all_disabled = 0; - SerialIrq other_irq = (irq == RxIrq) ? (TxIrq) : (RxIrq); - switch (irq) { - case RxIrq: - UART_DisableInterrupts(uart_addrs[obj->serial.index], kUART_RxDataRegFullInterruptEnable); - break; - case TxIrq: - UART_DisableInterrupts(uart_addrs[obj->serial.index], kUART_TxDataRegEmptyInterruptEnable); - break; - default: - break; - } - switch (other_irq) { - case RxIrq: - all_disabled = ((UART_GetEnabledInterrupts(uart_addrs[obj->serial.index]) & kUART_RxDataRegFullInterruptEnable) == 0); - break; - case TxIrq: - all_disabled = ((UART_GetEnabledInterrupts(uart_addrs[obj->serial.index]) & kUART_TxDataRegEmptyInterruptEnable) == 0); - break; - default: - break; - } - if (all_disabled) - NVIC_DisableIRQ(uart_irqs[obj->serial.index]); - } -} - -int serial_getc(serial_t *obj) -{ - while (!serial_readable(obj)); - uint8_t data; - data = UART_ReadByte(uart_addrs[obj->serial.index]); - - return data; -} - -void serial_putc(serial_t *obj, int c) -{ - while (!serial_writable(obj)); - UART_WriteByte(uart_addrs[obj->serial.index], (uint8_t)c); -} - -int serial_readable(serial_t *obj) -{ - uint32_t status_flags = UART_GetStatusFlags(uart_addrs[obj->serial.index]); - if (status_flags & kUART_RxOverrunFlag) - UART_ClearStatusFlags(uart_addrs[obj->serial.index], kUART_RxOverrunFlag); - return (status_flags & kUART_RxDataRegFullFlag); -} - -int serial_writable(serial_t *obj) -{ - uint32_t status_flags = UART_GetStatusFlags(uart_addrs[obj->serial.index]); - if (status_flags & kUART_RxOverrunFlag) - UART_ClearStatusFlags(uart_addrs[obj->serial.index], kUART_RxOverrunFlag); - return (status_flags & kUART_TxDataRegEmptyFlag); -} - -void serial_clear(serial_t *obj) -{ -} - -void serial_pinout_tx(PinName tx) -{ - pinmap_pinout(tx, PinMap_UART_TX); -} - -void serial_break_set(serial_t *obj) -{ - uart_addrs[obj->serial.index]->C2 |= UART_C2_SBK_MASK; -} - -void serial_break_clear(serial_t *obj) -{ - uart_addrs[obj->serial.index]->C2 &= ~UART_C2_SBK_MASK; -} - -#if DEVICE_SERIAL_FC - -/* - * Only hardware flow control is implemented in this API. - */ -void serial_set_flow_control(serial_t *obj, FlowControl type, PinName rxflow, PinName txflow) -{ - switch(type) { - case FlowControlRTS: - pinmap_pinout(rxflow, PinMap_UART_RTS); - uart_addrs[obj->serial.index]->MODEM &= ~UART_MODEM_TXCTSE_MASK; - uart_addrs[obj->serial.index]->MODEM |= UART_MODEM_RXRTSE_MASK; - break; - - case FlowControlCTS: - pinmap_pinout(txflow, PinMap_UART_CTS); - uart_addrs[obj->serial.index]->MODEM &= ~UART_MODEM_RXRTSE_MASK; - uart_addrs[obj->serial.index]->MODEM |= UART_MODEM_TXCTSE_MASK; - break; - - case FlowControlRTSCTS: - pinmap_pinout(rxflow, PinMap_UART_RTS); - pinmap_pinout(txflow, PinMap_UART_CTS); - uart_addrs[obj->serial.index]->MODEM |= UART_MODEM_TXCTSE_MASK | UART_MODEM_RXRTSE_MASK; - break; - - case FlowControlNone: - uart_addrs[obj->serial.index]->MODEM &= ~(UART_MODEM_TXCTSE_MASK | UART_MODEM_RXRTSE_MASK); - break; - - default: - break; - } -} - -#endif - -static void serial_send_asynch(serial_t *obj) -{ - uart_transfer_t sendXfer; - - /*Setup send transfer*/ - sendXfer.data = obj->tx_buff.buffer; - sendXfer.dataSize = obj->tx_buff.length; - - if (obj->serial.uartDmaRx.dmaUsageState == DMA_USAGE_ALLOCATED || - obj->serial.uartDmaRx.dmaUsageState == DMA_USAGE_TEMPORARY_ALLOCATED) { - UART_SendEDMA(uart_addrs[obj->serial.index], &obj->serial.uart_dma_handle, &sendXfer); - } else { - UART_TransferSendNonBlocking(uart_addrs[obj->serial.index], &obj->serial.uart_transfer_handle, &sendXfer); - } -} - -static void serial_receive_asynch(serial_t *obj) -{ - uart_transfer_t receiveXfer; - - /*Setup send transfer*/ - receiveXfer.data = obj->rx_buff.buffer; - receiveXfer.dataSize = obj->rx_buff.length; - - if (obj->serial.uartDmaRx.dmaUsageState == DMA_USAGE_ALLOCATED || - obj->serial.uartDmaRx.dmaUsageState == DMA_USAGE_TEMPORARY_ALLOCATED) { - UART_ReceiveEDMA(uart_addrs[obj->serial.index], &obj->serial.uart_dma_handle, &receiveXfer); - } else { - UART_TransferReceiveNonBlocking(uart_addrs[obj->serial.index], &obj->serial.uart_transfer_handle, &receiveXfer, NULL); - } -} - -static bool serial_allocate_dma(serial_t *obj, uint32_t handler) -{ - dma_request_source_t dma_rx_requests[] = UART_DMA_RX_REQUEST_NUMBERS; - dma_request_source_t dma_tx_requests[] = UART_DMA_TX_REQUEST_NUMBERS; - edma_config_t userConfig; - - /* Allocate the UART RX DMA channel */ - obj->serial.uartDmaRx.dmaChannel = dma_channel_allocate(dma_rx_requests[obj->serial.index]); - if (obj->serial.uartDmaRx.dmaChannel == DMA_ERROR_OUT_OF_CHANNELS) { - return false; - } - - /* Allocate the UART TX DMA channel */ - obj->serial.uartDmaTx.dmaChannel = dma_channel_allocate(dma_tx_requests[obj->serial.index]); - if (obj->serial.uartDmaTx.dmaChannel == DMA_ERROR_OUT_OF_CHANNELS) { - dma_channel_free(obj->serial.uartDmaRx.dmaChannel); - return false; - } - - /* EDMA init*/ - /* - * userConfig.enableRoundRobinArbitration = false; - * userConfig.enableHaltOnError = true; - * userConfig.enableContinuousLinkMode = false; - * userConfig.enableDebugMode = false; - */ - EDMA_GetDefaultConfig(&userConfig); - - EDMA_Init(DMA0, &userConfig); - - memset(&(obj->serial.uartDmaTx.handle), 0, sizeof(obj->serial.uartDmaTx.handle)); - memset(&(obj->serial.uartDmaRx.handle), 0, sizeof(obj->serial.uartDmaRx.handle)); - - EDMA_CreateHandle(&(obj->serial.uartDmaRx.handle), DMA0, obj->serial.uartDmaRx.dmaChannel); - EDMA_CreateHandle(&(obj->serial.uartDmaTx.handle), DMA0, obj->serial.uartDmaTx.dmaChannel); - - UART_TransferCreateHandleEDMA(uart_addrs[obj->serial.index], &obj->serial.uart_dma_handle, (uart_edma_transfer_callback_t)handler, - NULL, &obj->serial.uartDmaTx.handle, &obj->serial.uartDmaRx.handle); - - return true; -} - -void serial_enable_dma(serial_t *obj, uint32_t handler, DMAUsage state) -{ - dma_init(); - - if (state == DMA_USAGE_ALWAYS && obj->serial.uartDmaRx.dmaUsageState != DMA_USAGE_ALLOCATED) { - /* Try to allocate channels */ - if (serial_allocate_dma(obj, handler)) { - obj->serial.uartDmaRx.dmaUsageState = DMA_USAGE_ALLOCATED; - } else { - obj->serial.uartDmaRx.dmaUsageState = state; - } - } else if (state == DMA_USAGE_OPPORTUNISTIC) { - if (obj->serial.uartDmaRx.dmaUsageState == DMA_USAGE_ALLOCATED) { - /* Channels have already been allocated previously by an ALWAYS state, so after this transfer, we will release them */ - obj->serial.uartDmaRx.dmaUsageState = DMA_USAGE_TEMPORARY_ALLOCATED; - } else { - /* Try to allocate channels */ - if (serial_allocate_dma(obj, handler)) { - obj->serial.uartDmaRx.dmaUsageState = DMA_USAGE_TEMPORARY_ALLOCATED; - } else { - obj->serial.uartDmaRx.dmaUsageState = state; - } - } - } else if (state == DMA_USAGE_NEVER) { - /* If channels are allocated, get rid of them */ - if (obj->serial.uartDmaRx.dmaUsageState == DMA_USAGE_ALLOCATED) { - dma_channel_free(obj->serial.uartDmaRx.dmaChannel); - dma_channel_free(obj->serial.uartDmaRx.dmaChannel); - } - obj->serial.uartDmaRx.dmaUsageState = DMA_USAGE_NEVER; - } -} - -void serial_enable_event(serial_t *obj, int event, uint8_t enable) -{ - // Keep track of the requested events. - if (enable) { - obj->serial.events |= event; - } else { - obj->serial.events &= ~event; - } -} - -static void serial_tx_buffer_set(serial_t *obj, void *tx, int tx_length, uint8_t width) { - (void)width; - - // Exit if a transmit is already on-going - if (serial_tx_active(obj)) { - return; - } - - obj->tx_buff.buffer = tx; - obj->tx_buff.length = tx_length; - obj->tx_buff.pos = 0; -} - -int serial_tx_asynch(serial_t *obj, const void *tx, size_t tx_length, uint8_t tx_width, uint32_t handler, uint32_t event, DMAUsage hint) -{ - // Check that a buffer has indeed been set up - MBED_ASSERT(tx != (void*)0); - - if (tx_length == 0) return 0; - - if (serial_tx_active(obj)) { - return 0; - } - - // Set up buffer - serial_tx_buffer_set(obj, (void *)tx, tx_length, tx_width); - - // Set up events - serial_enable_event(obj, SERIAL_EVENT_TX_ALL, false); - serial_enable_event(obj, event, true); - - /* If using DMA, allocate channels only if they have not already been allocated */ - if (hint != DMA_USAGE_NEVER) { - /* User requested to transfer using DMA */ - serial_enable_dma(obj, handler, hint); - - /* Check if DMA setup was successful */ - if (obj->serial.uartDmaRx.dmaUsageState != DMA_USAGE_ALLOCATED && obj->serial.uartDmaRx.dmaUsageState != DMA_USAGE_TEMPORARY_ALLOCATED) { - /* Set up an interrupt transfer as DMA is unavailable */ - if (obj->serial.uart_transfer_handle.callback == 0) { - UART_TransferCreateHandle(uart_addrs[obj->serial.index], &obj->serial.uart_transfer_handle, (uart_transfer_callback_t)handler, NULL); - } - } - } else { - /* User requested to transfer using interrupts */ - /* Disable the DMA */ - serial_enable_dma(obj, handler, hint); - - /* Set up the interrupt transfer */ - if (obj->serial.uart_transfer_handle.callback == 0) { - UART_TransferCreateHandle(uart_addrs[obj->serial.index], &obj->serial.uart_transfer_handle, (uart_transfer_callback_t)handler, NULL); - } - } - - obj->serial.txstate = kUART_TxBusy; - - /* Start the transfer */ - serial_send_asynch(obj); - - return 0; -} - -void serial_rx_buffer_set(serial_t *obj, void *rx, int rx_length, uint8_t width) -{ - // We only support byte buffers for now - MBED_ASSERT(width == 8); - - if (serial_rx_active(obj)) return; - - obj->rx_buff.buffer = rx; - obj->rx_buff.length = rx_length; - obj->rx_buff.pos = 0; - - return; -} - -/* Character match is currently not supported */ -void serial_rx_asynch(serial_t *obj, void *rx, size_t rx_length, uint8_t rx_width, uint32_t handler, uint32_t event, uint8_t char_match, DMAUsage hint) -{ - // Check that a buffer has indeed been set up - MBED_ASSERT(rx != (void*)0); - if (rx_length == 0) return; - - if (serial_rx_active(obj)) { - return; - } - - // Set up buffer - serial_rx_buffer_set(obj,(void*) rx, rx_length, rx_width); - - // Set up events - serial_enable_event(obj, SERIAL_EVENT_RX_ALL, false); - serial_enable_event(obj, event, true); - - //obj->char_match = char_match; - - /* If using DMA, allocate channels only if they have not already been allocated */ - if (hint != DMA_USAGE_NEVER) { - /* User requested to transfer using DMA */ - serial_enable_dma(obj, handler, hint); - - /* Check if DMA setup was successful */ - if (obj->serial.uartDmaRx.dmaUsageState != DMA_USAGE_ALLOCATED && obj->serial.uartDmaRx.dmaUsageState != DMA_USAGE_TEMPORARY_ALLOCATED) { - /* Set up an interrupt transfer as DMA is unavailable */ - if (obj->serial.uart_transfer_handle.callback == 0) { - UART_TransferCreateHandle(uart_addrs[obj->serial.index], &obj->serial.uart_transfer_handle, (uart_transfer_callback_t)handler, NULL); - } - } - - } else { - /* User requested to transfer using interrupts */ - /* Disable the DMA */ - serial_enable_dma(obj, handler, hint); - - /* Set up the interrupt transfer */ - if (obj->serial.uart_transfer_handle.callback == 0) { - UART_TransferCreateHandle(uart_addrs[obj->serial.index], &obj->serial.uart_transfer_handle, (uart_transfer_callback_t)handler, NULL); - } - } - - obj->serial.rxstate = kUART_RxBusy; - - /* Start the transfer */ - serial_receive_asynch(obj); -} - -uint8_t serial_tx_active(serial_t *obj) -{ - if (obj->serial.txstate == kUART_TxIdle) { - return 0; - } - - return 1; -} - -uint8_t serial_rx_active(serial_t *obj) -{ - if (obj->serial.rxstate == kUART_RxIdle) { - return 0; - } - - return 1; -} - -int serial_irq_handler_asynch(serial_t *obj) -{ - int status = 0; - //uint8_t *buf = (uint8_t*)obj->rx_buff.buffer; - uint32_t status_flags = UART_GetStatusFlags(uart_addrs[obj->serial.index]); - - /* Determine whether the current scenario is DMA or IRQ, and act accordingly */ - if (obj->serial.uartDmaRx.dmaUsageState == DMA_USAGE_ALLOCATED || obj->serial.uartDmaRx.dmaUsageState == DMA_USAGE_TEMPORARY_ALLOCATED) { - /* DMA implementation */ - if ((obj->serial.txstate != kUART_TxIdle) && (obj->serial.uart_dma_handle.txState == kUART_TxIdle)) { - obj->serial.txstate = kUART_TxIdle; - status |= SERIAL_EVENT_TX_COMPLETE; - } - - if ((obj->serial.rxstate != kUART_RxIdle) && (obj->serial.uart_dma_handle.rxState == kUART_RxIdle)) { - obj->serial.rxstate = kUART_RxIdle; - status |= SERIAL_EVENT_RX_COMPLETE; - } - - /* Release the dma channels if they were opportunistically allocated */ - if (obj->serial.uartDmaRx.dmaUsageState == DMA_USAGE_TEMPORARY_ALLOCATED) { - /* Ensure both TX and RX channels are idle before freeing them */ - if ((obj->serial.uart_dma_handle.txState == kUART_TxIdle) && (obj->serial.uart_dma_handle.rxState == kUART_RxIdle)) { - dma_channel_free(obj->serial.uartDmaRx.dmaChannel); - dma_channel_free(obj->serial.uartDmaTx.dmaChannel); - obj->serial.uartDmaRx.dmaUsageState = DMA_USAGE_OPPORTUNISTIC; - } - } - } else { - /* Interrupt implementation */ - if ((obj->serial.txstate != kUART_TxIdle) && (obj->serial.uart_transfer_handle.txState == kUART_TxIdle)) { - obj->serial.txstate = kUART_TxIdle; - status |= SERIAL_EVENT_TX_COMPLETE; - } - - if ((obj->serial.rxstate != kUART_RxIdle) && (obj->serial.uart_transfer_handle.rxState == kUART_RxIdle)) { - obj->serial.rxstate = kUART_RxIdle; - status |= SERIAL_EVENT_RX_COMPLETE; - } - } - - if (status_flags & kUART_RxOverrunFlag) { - UART_ClearStatusFlags(uart_addrs[obj->serial.index], kUART_RxOverrunFlag); - status |= SERIAL_EVENT_RX_OVERRUN_ERROR; - } - - if (status_flags & kUART_FramingErrorFlag) { - UART_ClearStatusFlags(uart_addrs[obj->serial.index], kUART_FramingErrorFlag); - status |= SERIAL_EVENT_RX_FRAMING_ERROR; - } - - if (status_flags & kUART_ParityErrorFlag) { - UART_ClearStatusFlags(uart_addrs[obj->serial.index], kUART_ParityErrorFlag); - status |= SERIAL_EVENT_RX_PARITY_ERROR; - } - - return status & obj->serial.events; -} - -void serial_tx_abort_asynch(serial_t *obj) -{ - if (obj->serial.uartDmaRx.dmaUsageState == DMA_USAGE_ALLOCATED || obj->serial.uartDmaRx.dmaUsageState == DMA_USAGE_TEMPORARY_ALLOCATED) { - UART_TransferAbortSendEDMA(uart_addrs[obj->serial.index], &obj->serial.uart_dma_handle); - /* Release the dma channels if they were opportunistically allocated */ - if (obj->serial.uartDmaRx.dmaUsageState == DMA_USAGE_TEMPORARY_ALLOCATED) { - /* Ensure both TX and RX channels are idle before freeing them */ - if ((obj->serial.uart_dma_handle.txState == kUART_TxIdle) && (obj->serial.uart_dma_handle.rxState == kUART_RxIdle)) { - dma_channel_free(obj->serial.uartDmaRx.dmaChannel); - dma_channel_free(obj->serial.uartDmaTx.dmaChannel); - obj->serial.uartDmaRx.dmaUsageState = DMA_USAGE_OPPORTUNISTIC; - } - } - } else { - UART_TransferAbortSend(uart_addrs[obj->serial.index], &obj->serial.uart_transfer_handle); - } -} - -void serial_rx_abort_asynch(serial_t *obj) -{ - if (obj->serial.uartDmaRx.dmaUsageState == DMA_USAGE_ALLOCATED || obj->serial.uartDmaRx.dmaUsageState == DMA_USAGE_TEMPORARY_ALLOCATED) { - UART_TransferAbortReceiveEDMA(uart_addrs[obj->serial.index], &obj->serial.uart_dma_handle); - /* Release the dma channels if they were opportunistically allocated */ - if (obj->serial.uartDmaRx.dmaUsageState == DMA_USAGE_TEMPORARY_ALLOCATED) { - /* Ensure both TX and RX channels are idle before freeing them */ - if ((obj->serial.uart_dma_handle.txState == kUART_TxIdle) && (obj->serial.uart_dma_handle.rxState == kUART_RxIdle)) { - dma_channel_free(obj->serial.uartDmaRx.dmaChannel); - dma_channel_free(obj->serial.uartDmaTx.dmaChannel); - obj->serial.uartDmaRx.dmaUsageState = DMA_USAGE_OPPORTUNISTIC; - } - } - } else { - UART_TransferAbortReceive(uart_addrs[obj->serial.index], &obj->serial.uart_transfer_handle); - } -} - -#endif diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/spi_api.c b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/spi_api.c deleted file mode 100644 index bc5bb459bc6..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/spi_api.c +++ /dev/null @@ -1,433 +0,0 @@ -/* mbed Microcontroller Library - * Copyright (c) 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. - * You may obtain a copy of the License at - * - * 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, - * 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. - */ -#include -#include "mbed_assert.h" - -#include "spi_api.h" - -#if DEVICE_SPI - -#include "cmsis.h" -#include "pinmap.h" -#include "mbed_error.h" -#include "fsl_dspi.h" -#include "peripheral_clock_defines.h" -#include "dma_reqs.h" -#include "PeripheralPins.h" - -/* Array of SPI peripheral base address. */ -static SPI_Type *const spi_address[] = SPI_BASE_PTRS; -/* Array of SPI bus clock frequencies */ -static clock_name_t const spi_clocks[] = SPI_CLOCK_FREQS; - -void spi_init(spi_t *obj, PinName mosi, PinName miso, PinName sclk, PinName ssel) -{ - // determine the SPI to use - uint32_t spi_mosi = pinmap_peripheral(mosi, PinMap_SPI_MOSI); - uint32_t spi_miso = pinmap_peripheral(miso, PinMap_SPI_MISO); - uint32_t spi_sclk = pinmap_peripheral(sclk, PinMap_SPI_SCLK); - uint32_t spi_ssel = pinmap_peripheral(ssel, PinMap_SPI_SSEL); - uint32_t spi_data = pinmap_merge(spi_mosi, spi_miso); - uint32_t spi_cntl = pinmap_merge(spi_sclk, spi_ssel); - - obj->spi.instance = pinmap_merge(spi_data, spi_cntl); - MBED_ASSERT((int)obj->spi.instance != NC); - - // pin out the spi pins - pinmap_pinout(mosi, PinMap_SPI_MOSI); - pinmap_pinout(miso, PinMap_SPI_MISO); - pinmap_pinout(sclk, PinMap_SPI_SCLK); - if (ssel != NC) { - pinmap_pinout(ssel, PinMap_SPI_SSEL); - } - - /* Set the transfer status to idle */ - obj->spi.status = kDSPI_Idle; - - obj->spi.spiDmaMasterRx.dmaUsageState = DMA_USAGE_OPPORTUNISTIC; -} - -void spi_free(spi_t *obj) -{ - DSPI_Deinit(spi_address[obj->spi.instance]); -} - -void spi_format(spi_t *obj, int bits, int mode, int slave) -{ - dspi_master_config_t master_config; - dspi_slave_config_t slave_config; - - /* Bits: values between 4 and 16 are valid */ - MBED_ASSERT(bits >= 4 && bits <= 16); - obj->spi.bits = bits; - - if (slave) { - /* Slave config */ - DSPI_SlaveGetDefaultConfig(&slave_config); - slave_config.whichCtar = kDSPI_Ctar0; - slave_config.ctarConfig.bitsPerFrame = (uint32_t)bits;; - slave_config.ctarConfig.cpol = (mode & 0x2) ? kDSPI_ClockPolarityActiveLow : kDSPI_ClockPolarityActiveHigh; - slave_config.ctarConfig.cpha = (mode & 0x1) ? kDSPI_ClockPhaseSecondEdge : kDSPI_ClockPhaseFirstEdge; - - DSPI_SlaveInit(spi_address[obj->spi.instance], &slave_config); - } else { - /* Master config */ - DSPI_MasterGetDefaultConfig(&master_config); - master_config.ctarConfig.bitsPerFrame = (uint32_t)bits;; - master_config.ctarConfig.cpol = (mode & 0x2) ? kDSPI_ClockPolarityActiveLow : kDSPI_ClockPolarityActiveHigh; - master_config.ctarConfig.cpha = (mode & 0x1) ? kDSPI_ClockPhaseSecondEdge : kDSPI_ClockPhaseFirstEdge; - master_config.ctarConfig.direction = kDSPI_MsbFirst; - master_config.ctarConfig.pcsToSckDelayInNanoSec = 0; - - DSPI_MasterInit(spi_address[obj->spi.instance], &master_config, CLOCK_GetFreq(spi_clocks[obj->spi.instance])); - } -} - -void spi_frequency(spi_t *obj, int hz) -{ - uint32_t busClock = CLOCK_GetFreq(spi_clocks[obj->spi.instance]); - DSPI_MasterSetBaudRate(spi_address[obj->spi.instance], kDSPI_Ctar0, (uint32_t)hz, busClock); - //Half clock period delay after SPI transfer - DSPI_MasterSetDelayTimes(spi_address[obj->spi.instance], kDSPI_Ctar0, kDSPI_LastSckToPcs, busClock, 500000000 / hz); -} - -static inline int spi_readable(spi_t * obj) -{ - return (DSPI_GetStatusFlags(spi_address[obj->spi.instance]) & kDSPI_RxFifoDrainRequestFlag); -} - -int spi_master_write(spi_t *obj, int value) -{ - dspi_command_data_config_t command; - uint32_t rx_data; - DSPI_GetDefaultDataCommandConfig(&command); - command.isEndOfQueue = true; - - DSPI_MasterWriteDataBlocking(spi_address[obj->spi.instance], &command, (uint16_t)value); - - DSPI_ClearStatusFlags(spi_address[obj->spi.instance], kDSPI_TxFifoFillRequestFlag); - - // wait rx buffer full - while (!spi_readable(obj)); - rx_data = DSPI_ReadData(spi_address[obj->spi.instance]); - DSPI_ClearStatusFlags(spi_address[obj->spi.instance], kDSPI_RxFifoDrainRequestFlag | kDSPI_EndOfQueueFlag); - return rx_data & 0xffff; -} - -int spi_slave_receive(spi_t *obj) -{ - return spi_readable(obj); -} - -int spi_slave_read(spi_t *obj) -{ - uint32_t rx_data; - - while (!spi_readable(obj)); - rx_data = DSPI_ReadData(spi_address[obj->spi.instance]); - DSPI_ClearStatusFlags(spi_address[obj->spi.instance], kDSPI_RxFifoDrainRequestFlag); - return rx_data & 0xffff; -} - -void spi_slave_write(spi_t *obj, int value) -{ - DSPI_SlaveWriteDataBlocking(spi_address[obj->spi.instance], (uint32_t)value); -} - -static int32_t spi_master_transfer_asynch(spi_t *obj) -{ - dspi_transfer_t masterXfer; - int32_t status; - uint32_t transferSize; - - /*Start master transfer*/ - masterXfer.txData = obj->tx_buff.buffer; - masterXfer.rxData = obj->rx_buff.buffer; - masterXfer.dataSize = obj->tx_buff.length; - masterXfer.configFlags = kDSPI_MasterCtar0 | kDSPI_MasterPcs0 | kDSPI_MasterPcsContinuous; - /* Busy transferring */ - obj->spi.status = kDSPI_Busy; - - if (obj->spi.spiDmaMasterRx.dmaUsageState == DMA_USAGE_ALLOCATED || - obj->spi.spiDmaMasterRx.dmaUsageState == DMA_USAGE_TEMPORARY_ALLOCATED) { - status = DSPI_MasterTransferEDMA(spi_address[obj->spi.instance], &obj->spi.spi_dma_master_handle, &masterXfer); - if (status == kStatus_DSPI_OutOfRange) { - if (obj->spi.bits > 8) { - transferSize = 1022; - } else { - transferSize = 511; - } - masterXfer.dataSize = transferSize; - /* Save amount of TX done by DMA */ - obj->tx_buff.pos += transferSize; - obj->rx_buff.pos += transferSize; - /* Try again */ - status = DSPI_MasterTransferEDMA(spi_address[obj->spi.instance], &obj->spi.spi_dma_master_handle, &masterXfer); - } - } else { - status = DSPI_MasterTransferNonBlocking(spi_address[obj->spi.instance], &obj->spi.spi_master_handle, &masterXfer); - } - - return status; -} - -static bool spi_allocate_dma(spi_t *obj, uint32_t handler) -{ - dma_request_source_t dma_rx_requests[] = SPI_DMA_RX_REQUEST_NUMBERS; - dma_request_source_t dma_tx_requests[] = SPI_DMA_TX_REQUEST_NUMBERS; - edma_config_t userConfig; - - /* Allocate the DMA channels */ - /* Allocate the RX channel */ - obj->spi.spiDmaMasterRx.dmaChannel = dma_channel_allocate(dma_rx_requests[obj->spi.instance]); - if (obj->spi.spiDmaMasterRx.dmaChannel == DMA_ERROR_OUT_OF_CHANNELS) { - return false; - } - - /* Check if we have separate DMA requests for TX & RX */ - if (dma_tx_requests[obj->spi.instance] != dma_rx_requests[obj->spi.instance]) { - /* Allocate the TX channel with the DMA TX request number set as source */ - obj->spi.spiDmaMasterTx.dmaChannel = dma_channel_allocate(dma_tx_requests[obj->spi.instance]); - } else { - /* Allocate the TX channel without setting source */ - obj->spi.spiDmaMasterTx.dmaChannel = dma_channel_allocate(kDmaRequestMux0Disable); - } - if (obj->spi.spiDmaMasterTx.dmaChannel == DMA_ERROR_OUT_OF_CHANNELS) { - dma_channel_free(obj->spi.spiDmaMasterRx.dmaChannel); - return false; - } - - /* Allocate an intermediary DMA channel */ - obj->spi.spiDmaMasterIntermediary.dmaChannel = dma_channel_allocate(kDmaRequestMux0Disable); - if (obj->spi.spiDmaMasterIntermediary.dmaChannel == DMA_ERROR_OUT_OF_CHANNELS) { - dma_channel_free(obj->spi.spiDmaMasterRx.dmaChannel); - dma_channel_free(obj->spi.spiDmaMasterTx.dmaChannel); - return false; - } - - /* EDMA init*/ - /* - * userConfig.enableRoundRobinArbitration = false; - * userConfig.enableHaltOnError = true; - * userConfig.enableContinuousLinkMode = false; - * userConfig.enableDebugMode = false; - */ - EDMA_GetDefaultConfig(&userConfig); - - EDMA_Init(DMA0, &userConfig); - - /* Set up dspi master */ - memset(&(obj->spi.spiDmaMasterRx.handle), 0, sizeof(obj->spi.spiDmaMasterRx.handle)); - memset(&(obj->spi.spiDmaMasterTx.handle), 0, sizeof(obj->spi.spiDmaMasterTx.handle)); - memset(&(obj->spi.spiDmaMasterIntermediary.handle), 0, sizeof(obj->spi.spiDmaMasterIntermediary.handle)); - - EDMA_CreateHandle(&(obj->spi.spiDmaMasterRx.handle), DMA0, obj->spi.spiDmaMasterRx.dmaChannel); - EDMA_CreateHandle(&(obj->spi.spiDmaMasterIntermediary.handle), DMA0, - obj->spi.spiDmaMasterIntermediary.dmaChannel); - EDMA_CreateHandle(&(obj->spi.spiDmaMasterTx.handle), DMA0, obj->spi.spiDmaMasterTx.dmaChannel); - - DSPI_MasterTransferCreateHandleEDMA(spi_address[obj->spi.instance], &obj->spi.spi_dma_master_handle, (dspi_master_edma_transfer_callback_t)handler, - NULL, &obj->spi.spiDmaMasterRx.handle, - &obj->spi.spiDmaMasterIntermediary.handle, - &obj->spi.spiDmaMasterTx.handle); - return true; -} - -static void spi_enable_dma(spi_t *obj, uint32_t handler, DMAUsage state) -{ - dma_init(); - - if (state == DMA_USAGE_ALWAYS && obj->spi.spiDmaMasterRx.dmaUsageState != DMA_USAGE_ALLOCATED) { - /* Try to allocate channels */ - if (spi_allocate_dma(obj, handler)) { - obj->spi.spiDmaMasterRx.dmaUsageState = DMA_USAGE_ALLOCATED; - } else { - obj->spi.spiDmaMasterRx.dmaUsageState = state; - } - } else if (state == DMA_USAGE_OPPORTUNISTIC) { - if (obj->spi.spiDmaMasterRx.dmaUsageState == DMA_USAGE_ALLOCATED) { - /* Channels have already been allocated previously by an ALWAYS state, so after this transfer, we will release them */ - obj->spi.spiDmaMasterRx.dmaUsageState = DMA_USAGE_TEMPORARY_ALLOCATED; - } else { - /* Try to allocate channels */ - if (spi_allocate_dma(obj, handler)) { - obj->spi.spiDmaMasterRx.dmaUsageState = DMA_USAGE_TEMPORARY_ALLOCATED; - } else { - obj->spi.spiDmaMasterRx.dmaUsageState = state; - } - } - } else if (state == DMA_USAGE_NEVER) { - /* If channels are allocated, get rid of them */ - if (obj->spi.spiDmaMasterRx.dmaUsageState == DMA_USAGE_ALLOCATED) { - dma_channel_free(obj->spi.spiDmaMasterRx.dmaChannel); - dma_channel_free(obj->spi.spiDmaMasterTx.dmaChannel); - dma_channel_free(obj->spi.spiDmaMasterIntermediary.dmaChannel); - } - obj->spi.spiDmaMasterRx.dmaUsageState = DMA_USAGE_NEVER; - } -} - -static void spi_buffer_set(spi_t *obj, const void *tx, uint32_t tx_length, void *rx, uint32_t rx_length, uint8_t bit_width) -{ - obj->tx_buff.buffer = (void *)tx; - obj->rx_buff.buffer = rx; - obj->tx_buff.length = tx_length; - obj->rx_buff.length = rx_length; - obj->tx_buff.pos = 0; - obj->rx_buff.pos = 0; - obj->tx_buff.width = bit_width; - obj->rx_buff.width = bit_width; -} - -void spi_master_transfer(spi_t *obj, const void *tx, size_t tx_length, void *rx, size_t rx_length, uint8_t bit_width, uint32_t handler, uint32_t event, DMAUsage hint) -{ - if(spi_active(obj)) { - return; - } - - /* check corner case */ - if(tx_length == 0) { - tx_length = rx_length; - tx = (void*) 0; - } - - /* First, set the buffer */ - spi_buffer_set(obj, tx, tx_length, rx, rx_length, bit_width); - - /* If using DMA, allocate channels only if they have not already been allocated */ - if (hint != DMA_USAGE_NEVER) { - /* User requested to transfer using DMA */ - spi_enable_dma(obj, handler, hint); - - /* Check if DMA setup was successful */ - if (obj->spi.spiDmaMasterRx.dmaUsageState != DMA_USAGE_ALLOCATED && obj->spi.spiDmaMasterRx.dmaUsageState != DMA_USAGE_TEMPORARY_ALLOCATED) { - /* Set up an interrupt transfer as DMA is unavailable */ - DSPI_MasterTransferCreateHandle(spi_address[obj->spi.instance], &obj->spi.spi_master_handle, (dspi_master_transfer_callback_t)handler, NULL); - } - - } else { - /* User requested to transfer using interrupts */ - /* Disable the DMA */ - spi_enable_dma(obj, handler, hint); - - /* Set up the interrupt transfer */ - DSPI_MasterTransferCreateHandle(spi_address[obj->spi.instance], &obj->spi.spi_master_handle, (dspi_master_transfer_callback_t)handler, NULL); - } - - /* Start the transfer */ - if (spi_master_transfer_asynch(obj) != kStatus_Success) { - obj->spi.status = kDSPI_Idle; - } -} - -uint32_t spi_irq_handler_asynch(spi_t *obj) -{ - uint32_t transferSize; - dspi_transfer_t masterXfer; - - /* Determine whether the current scenario is DMA or IRQ, and act accordingly */ - if (obj->spi.spiDmaMasterRx.dmaUsageState == DMA_USAGE_ALLOCATED || obj->spi.spiDmaMasterRx.dmaUsageState == DMA_USAGE_TEMPORARY_ALLOCATED) { - /* DMA implementation */ - /* Check If there is still data in the TX buffer */ - if (obj->tx_buff.pos < obj->tx_buff.length) { - /* Setup a new DMA transfer. */ - if (obj->spi.bits > 8) { - transferSize = 1022; - } else { - transferSize = 511; - } - - /* Update the TX buffer only if it is used */ - if (obj->tx_buff.buffer) { - masterXfer.txData = ((uint8_t *)obj->tx_buff.buffer) + obj->tx_buff.pos; - } else { - masterXfer.txData = 0; - } - - /* Update the RX buffer only if it is used */ - if (obj->rx_buff.buffer) { - masterXfer.rxData = ((uint8_t *)obj->rx_buff.buffer) + obj->rx_buff.pos; - } else { - masterXfer.rxData = 0; - } - - /* Check how much data is remaining in the buffer */ - if ((obj->tx_buff.length - obj->tx_buff.pos) > transferSize) { - masterXfer.dataSize = transferSize; - } else { - masterXfer.dataSize = obj->tx_buff.length - obj->tx_buff.pos; - } - masterXfer.configFlags = kDSPI_MasterCtar0 | kDSPI_MasterPcs0 | kDSPI_MasterPcsContinuous; - - /* Save amount of TX done by DMA */ - obj->tx_buff.pos += masterXfer.dataSize; - obj->rx_buff.pos += masterXfer.dataSize; - - /* Start another transfer */ - DSPI_MasterTransferEDMA(spi_address[obj->spi.instance], &obj->spi.spi_dma_master_handle, &masterXfer); - return 0; - } else { - /* Release the dma channels if they were opportunistically allocated */ - if (obj->spi.spiDmaMasterRx.dmaUsageState == DMA_USAGE_TEMPORARY_ALLOCATED) { - dma_channel_free(obj->spi.spiDmaMasterRx.dmaChannel); - dma_channel_free(obj->spi.spiDmaMasterTx.dmaChannel); - dma_channel_free(obj->spi.spiDmaMasterIntermediary.dmaChannel); - obj->spi.spiDmaMasterRx.dmaUsageState = DMA_USAGE_OPPORTUNISTIC; - } - obj->spi.status = kDSPI_Idle; - - return SPI_EVENT_COMPLETE; - } - } else { - /* Interrupt implementation */ - obj->spi.status = kDSPI_Idle; - - return SPI_EVENT_COMPLETE; - } -} - -void spi_abort_asynch(spi_t *obj) -{ - // If we're not currently transferring, then there's nothing to do here - if(spi_active(obj) == 0) { - return; - } - - // Determine whether we're running DMA or interrupt - if (obj->spi.spiDmaMasterRx.dmaUsageState == DMA_USAGE_ALLOCATED || - obj->spi.spiDmaMasterRx.dmaUsageState == DMA_USAGE_TEMPORARY_ALLOCATED) { - DSPI_MasterTransferAbortEDMA(spi_address[obj->spi.instance], &obj->spi.spi_dma_master_handle); - /* Release the dma channels if they were opportunistically allocated */ - if (obj->spi.spiDmaMasterRx.dmaUsageState == DMA_USAGE_TEMPORARY_ALLOCATED) { - dma_channel_free(obj->spi.spiDmaMasterRx.dmaChannel); - dma_channel_free(obj->spi.spiDmaMasterTx.dmaChannel); - dma_channel_free(obj->spi.spiDmaMasterIntermediary.dmaChannel); - obj->spi.spiDmaMasterRx.dmaUsageState = DMA_USAGE_OPPORTUNISTIC; - } - } else { - /* Interrupt implementation */ - DSPI_MasterTransferAbort(spi_address[obj->spi.instance], &obj->spi.spi_master_handle); - } - - obj->spi.status = kDSPI_Idle; -} - -uint8_t spi_active(spi_t *obj) -{ - return obj->spi.status; -} - -#endif diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/trng_api.c b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/trng_api.c deleted file mode 100644 index 890fc50224f..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/trng_api.c +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Hardware entropy collector for the K64F, using Freescale's RNGA - * - * Copyright (C) 2006-2017, ARM Limited, All Rights Reserved - * SPDX-License-Identifier: Apache-2.0 - * - * Licensed under the Apache License, Version 2.0 (the "License"); 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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, 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. - * - */ - -/* - * Reference: "K64 Sub-Family Reference Manual, Rev. 2", chapter 34 - */ - -#if defined(DEVICE_TRNG) - -#include -#include "cmsis.h" -#include "fsl_common.h" -#include "fsl_clock.h" -#include "trng_api.h" - -void trng_init(trng_t *obj) -{ - (void)obj; - CLOCK_EnableClock(kCLOCK_Rnga0); - CLOCK_DisableClock(kCLOCK_Rnga0); - CLOCK_EnableClock(kCLOCK_Rnga0); -} - -void trng_free(trng_t *obj) -{ - (void)obj; - CLOCK_DisableClock(kCLOCK_Rnga0); -} - -/* - * Get one byte of entropy from the RNG, assuming it is up and running. - * As recommended (34.1.1), get only one bit of each output. - */ -static void trng_get_byte(unsigned char *byte) -{ - size_t bit; - - /* 34.5 Steps 3-4-5: poll SR and read from OR when ready */ - for( bit = 0; bit < 8; bit++ ) - { - while((RNG->SR & RNG_SR_OREG_LVL_MASK) == 0 ); - *byte |= (RNG->OR & 1) << bit; - } -} - -int trng_get_bytes(trng_t *obj, uint8_t *output, size_t length, size_t *output_length) -{ - (void)obj; - size_t i; - - /* Set "Interrupt Mask", "High Assurance" and "Go", - * unset "Clear interrupt" and "Sleep" */ - RNG->CR = RNG_CR_INTM_MASK | RNG_CR_HA_MASK | RNG_CR_GO_MASK; - - for (i = 0; i < length; i++) { - trng_get_byte(output + i); - } - - /* Just be extra sure that we didn't do it wrong */ - if ((RNG->SR & RNG_SR_SECV_MASK) != 0) { - return -1; - } - - *output_length = length; - - return 0; -} - -#endif diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/us_ticker.c b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/us_ticker.c deleted file mode 100644 index 2c7d3945870..00000000000 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/us_ticker.c +++ /dev/null @@ -1,92 +0,0 @@ -/* mbed Microcontroller Library - * Copyright (c) 2006-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. - * You may obtain a copy of the License at - * - * 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, - * 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. - */ -#include -#include "us_ticker_api.h" -#include "PeripheralNames.h" -#include "fsl_pit.h" -#include "fsl_clock_config.h" - -static int us_ticker_inited = 0; - -void us_ticker_init(void) -{ - if (us_ticker_inited) { - return; - } - us_ticker_inited = 1; - //Common for ticker/timer - uint32_t busClock; - // Structure to initialize PIT - pit_config_t pitConfig; - - PIT_GetDefaultConfig(&pitConfig); - PIT_Init(PIT, &pitConfig); - - busClock = CLOCK_GetFreq(kCLOCK_BusClk); - - //Timer - PIT_SetTimerPeriod(PIT, kPIT_Chnl_0, busClock / 1000000 - 1); - PIT_SetTimerPeriod(PIT, kPIT_Chnl_1, 0xFFFFFFFF); - PIT_SetTimerChainMode(PIT, kPIT_Chnl_1, true); - PIT_StartTimer(PIT, kPIT_Chnl_0); - PIT_StartTimer(PIT, kPIT_Chnl_1); - - //Ticker - PIT_SetTimerPeriod(PIT, kPIT_Chnl_2, busClock / 1000000 - 1); - PIT_SetTimerChainMode(PIT, kPIT_Chnl_3, true); - NVIC_SetVector(PIT3_IRQn, (uint32_t)us_ticker_irq_handler); - NVIC_EnableIRQ(PIT3_IRQn); -} - - -uint32_t us_ticker_read() -{ - if (!us_ticker_inited) { - us_ticker_init(); - } - - return ~(PIT_GetCurrentTimerCount(PIT, kPIT_Chnl_1)); -} - -void us_ticker_disable_interrupt(void) -{ - PIT_DisableInterrupts(PIT, kPIT_Chnl_3, kPIT_TimerInterruptEnable); -} - -void us_ticker_clear_interrupt(void) -{ - PIT_ClearStatusFlags(PIT, kPIT_Chnl_3, PIT_TFLG_TIF_MASK); -} - -void us_ticker_set_interrupt(timestamp_t timestamp) -{ - int delta = (int)(timestamp - us_ticker_read()); - if (delta <= 0) { - // This event was in the past. - // Set the interrupt as pending, but don't process it here. - // This prevents a recurive loop under heavy load - // which can lead to a stack overflow. - NVIC_SetPendingIRQ(PIT3_IRQn); - return; - } - - PIT_StopTimer(PIT, kPIT_Chnl_3); - PIT_StopTimer(PIT, kPIT_Chnl_2); - PIT_SetTimerPeriod(PIT, kPIT_Chnl_3, (uint32_t)delta); - PIT_EnableInterrupts(PIT, kPIT_Chnl_3, kPIT_TimerInterruptEnable); - PIT_StartTimer(PIT, kPIT_Chnl_3); - PIT_StartTimer(PIT, kPIT_Chnl_2); -} diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K64F/TARGET_FRDM/PinNames.h b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K64F/TARGET_FRDM/PinNames.h index aa2273f231f..d0624d1d1bc 100644 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K64F/TARGET_FRDM/PinNames.h +++ b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K64F/TARGET_FRDM/PinNames.h @@ -204,9 +204,6 @@ typedef enum { //Push buttons SW2 = PTC6, SW3 = PTA4, - // Standardized button names - BUTTON1 = SW2, - BUTTON2 = SW3, // USB Pins USBTX = PTB17, diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K64F/TARGET_HEXIWEAR/PinNames.h b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K64F/TARGET_HEXIWEAR/PinNames.h index f674c9477cf..32983d0a369 100644 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K64F/TARGET_HEXIWEAR/PinNames.h +++ b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K64F/TARGET_HEXIWEAR/PinNames.h @@ -201,11 +201,6 @@ typedef enum { LED3 = LED_BLUE, LED4 = LED_RED, - // Standardized button names - BUTTON1 = PTA12, - BUTTON2 = PTA13, - BUTTON3 = PTA15, - // USB Pins USBTX = PTB17, USBRX = PTB16, diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K64F/device/TOOLCHAIN_ARM_STD/MK64FN1M0xxx12.sct b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K64F/device/TOOLCHAIN_ARM_STD/MK64FN1M0xxx12.sct index 70796af54e2..66557d071c7 100644 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K64F/device/TOOLCHAIN_ARM_STD/MK64FN1M0xxx12.sct +++ b/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K64F/device/TOOLCHAIN_ARM_STD/MK64FN1M0xxx12.sct @@ -50,6 +50,10 @@ */ #define __ram_vector_table__ 1 +/* Heap 1/4 of ram and stack 1/8 */ +#define __stack_size__ 0x8000 +#define __heap_size__ 0x10000 + #if (defined(__ram_vector_table__)) #define __ram_vector_table_size__ 0x00000400 #else diff --git a/targets/TARGET_Freescale/mbed_rtx.h b/targets/TARGET_Freescale/mbed_rtx.h index 43a913e652f..90060bcd206 100644 --- a/targets/TARGET_Freescale/mbed_rtx.h +++ b/targets/TARGET_Freescale/mbed_rtx.h @@ -247,26 +247,6 @@ #define OS_CLOCK 120000000 #endif -#elif defined(TARGET_RO359B) - -#ifndef INITIAL_SP -#define INITIAL_SP (0x20030000UL) -#endif - -#if defined(__CC_ARM) || defined(__GNUC__) -#define ISR_STACK_SIZE (0x1000) -#endif - -#ifndef OS_TASKCNT -#define OS_TASKCNT 14 -#endif -#ifndef OS_MAINSTKSIZE -#define OS_MAINSTKSIZE 256 -#endif -#ifndef OS_CLOCK -#define OS_CLOCK 96000000 -#endif - #endif #endif // MBED_MBED_RTX_H diff --git a/targets/TARGET_Maxim/TARGET_MAX32600/TARGET_MAX32600MBED/PinNames.h b/targets/TARGET_Maxim/TARGET_MAX32600/TARGET_MAX32600MBED/PinNames.h index 8b81721ee4b..eddfc3f7b4e 100644 --- a/targets/TARGET_Maxim/TARGET_MAX32600/TARGET_MAX32600MBED/PinNames.h +++ b/targets/TARGET_Maxim/TARGET_MAX32600/TARGET_MAX32600MBED/PinNames.h @@ -184,9 +184,6 @@ typedef enum { // Push button SW2 = P6_4, SW3 = P6_5, - // Standardized button names - BUTTON1 = SW2, - BUTTON2 = SW3, // UART pins USBTX = P7_3, diff --git a/targets/TARGET_Maxim/TARGET_MAX32610/TARGET_MAXWSNENV/PinNames.h b/targets/TARGET_Maxim/TARGET_MAX32610/TARGET_MAXWSNENV/PinNames.h index 4e6d39ffa7a..d541185392f 100644 --- a/targets/TARGET_Maxim/TARGET_MAX32610/TARGET_MAXWSNENV/PinNames.h +++ b/targets/TARGET_Maxim/TARGET_MAX32610/TARGET_MAXWSNENV/PinNames.h @@ -128,8 +128,6 @@ typedef enum { // Push button SW1 = P1_5, - // Standardized button names - BUTTON1 = SW1, // UART Pins UART0_RX = P1_0, diff --git a/targets/TARGET_Maxim/TARGET_MAX32620/TARGET_MAX32620HSP/PinNames.h b/targets/TARGET_Maxim/TARGET_MAX32620/TARGET_MAX32620HSP/PinNames.h index c6030ef13d4..559730a359b 100644 --- a/targets/TARGET_Maxim/TARGET_MAX32620/TARGET_MAX32620HSP/PinNames.h +++ b/targets/TARGET_Maxim/TARGET_MAX32620/TARGET_MAX32620HSP/PinNames.h @@ -126,8 +126,6 @@ typedef enum { SW1 = P2_1, SW2 = NOT_CONNECTED, SW3 = NOT_CONNECTED, - // Standardized button names - BUTTON1 = SW1, // USB bridge connected UART pins USBTX = P0_1, diff --git a/targets/TARGET_Maxim/TARGET_MAX32625/TARGET_MAX32625MBED/PinNames.h b/targets/TARGET_Maxim/TARGET_MAX32625/TARGET_MAX32625MBED/PinNames.h index be72f7ca083..9ed4f7d85ec 100644 --- a/targets/TARGET_Maxim/TARGET_MAX32625/TARGET_MAX32625MBED/PinNames.h +++ b/targets/TARGET_Maxim/TARGET_MAX32625/TARGET_MAX32625MBED/PinNames.h @@ -76,9 +76,6 @@ typedef enum { // Push button SW2 = P2_2, SW3 = P2_3, - // Standardized button names - BUTTON1 = SW2, - BUTTON2 = SW3, // USB bridge connected UART pins USBTX = P2_1, diff --git a/targets/TARGET_Maxim/TARGET_MAX32625/TARGET_MAX32625NEXPAQ/PinNames.h b/targets/TARGET_Maxim/TARGET_MAX32625/TARGET_MAX32625NEXPAQ/PinNames.h index a42da3330f4..9574edf1ec6 100644 --- a/targets/TARGET_Maxim/TARGET_MAX32625/TARGET_MAX32625NEXPAQ/PinNames.h +++ b/targets/TARGET_Maxim/TARGET_MAX32625/TARGET_MAX32625NEXPAQ/PinNames.h @@ -75,10 +75,6 @@ typedef enum { SW1 = P4_2, SW2 = P4_3, SW3 = P4_4, - // Standardized button names - BUTTON1 = SW1, - BUTTON2 = SW2, - BUTTON3 = SW3, // USB bridge connected UART pins USBTX = P2_1, diff --git a/targets/TARGET_Maxim/TARGET_MAX32630/TARGET_MAX32630FTHR/PinNames.h b/targets/TARGET_Maxim/TARGET_MAX32630/TARGET_MAX32630FTHR/PinNames.h index 1b5719533a1..d5df59a62c0 100644 --- a/targets/TARGET_Maxim/TARGET_MAX32630/TARGET_MAX32630FTHR/PinNames.h +++ b/targets/TARGET_Maxim/TARGET_MAX32630/TARGET_MAX32630FTHR/PinNames.h @@ -79,8 +79,6 @@ typedef enum { SW1 = P2_3, SW2 = NOT_CONNECTED, SW3 = NOT_CONNECTED, - // Standardized button names - BUTTON1 = SW1, // USB bridge connected UART pins USBTX = P2_1, diff --git a/targets/TARGET_Maxim/TARGET_MAX32630/gpio_irq_api.c b/targets/TARGET_Maxim/TARGET_MAX32630/gpio_irq_api.c index 8a9e7bb4221..143969229a5 100644 --- a/targets/TARGET_Maxim/TARGET_MAX32630/gpio_irq_api.c +++ b/targets/TARGET_Maxim/TARGET_MAX32630/gpio_irq_api.c @@ -100,15 +100,15 @@ int gpio_irq_init(gpio_irq_t *obj, PinName name, gpio_irq_handler handler, uint3 /* register handlers */ irq_handler = handler; - NVIC_SetVector(GPIO_P0_IRQn, (uint32_t)gpio_irq_0); - NVIC_SetVector(GPIO_P1_IRQn, (uint32_t)gpio_irq_1); - NVIC_SetVector(GPIO_P2_IRQn, (uint32_t)gpio_irq_2); - NVIC_SetVector(GPIO_P3_IRQn, (uint32_t)gpio_irq_3); - NVIC_SetVector(GPIO_P4_IRQn, (uint32_t)gpio_irq_4); - NVIC_SetVector(GPIO_P5_IRQn, (uint32_t)gpio_irq_5); - NVIC_SetVector(GPIO_P6_IRQn, (uint32_t)gpio_irq_6); - NVIC_SetVector(GPIO_P7_IRQn, (uint32_t)gpio_irq_7); - NVIC_SetVector(GPIO_P8_IRQn, (uint32_t)gpio_irq_8); + NVIC_SetVector(GPIO_P0_IRQn, gpio_irq_0); + NVIC_SetVector(GPIO_P1_IRQn, gpio_irq_1); + NVIC_SetVector(GPIO_P2_IRQn, gpio_irq_2); + NVIC_SetVector(GPIO_P3_IRQn, gpio_irq_3); + NVIC_SetVector(GPIO_P4_IRQn, gpio_irq_4); + NVIC_SetVector(GPIO_P5_IRQn, gpio_irq_5); + NVIC_SetVector(GPIO_P6_IRQn, gpio_irq_6); + NVIC_SetVector(GPIO_P7_IRQn, gpio_irq_7); + NVIC_SetVector(GPIO_P8_IRQn, gpio_irq_8); /* disable the interrupt locally */ MXC_GPIO->int_mode[port] &= ~(0xF << (pin*4)); diff --git a/targets/TARGET_Maxim/TARGET_MAX32630/mxc/nvic_table.c b/targets/TARGET_Maxim/TARGET_MAX32630/mxc/nvic_table.c index 4bd18960b3b..098e953b54e 100644 --- a/targets/TARGET_Maxim/TARGET_MAX32630/mxc/nvic_table.c +++ b/targets/TARGET_Maxim/TARGET_MAX32630/mxc/nvic_table.c @@ -76,7 +76,7 @@ void NVIC_SetRAM(void) } /* ************************************************************************* */ -int NVIC_SetVector(IRQn_Type irqn, uint32_t irq_handler) +int NVIC_SetVector(IRQn_Type irqn, void(*irq_handler)(void)) { int index = irqn + 16; /* offset for externals */ @@ -85,7 +85,7 @@ int NVIC_SetVector(IRQn_Type irqn, uint32_t irq_handler) NVIC_SetRAM(); } - ramVectorTable[index] = (void(*)(void))irq_handler; + ramVectorTable[index] = irq_handler; NVIC_EnableIRQ(irqn); return 0; diff --git a/targets/TARGET_Maxim/TARGET_MAX32630/mxc/nvic_table.h b/targets/TARGET_Maxim/TARGET_MAX32630/mxc/nvic_table.h index 385253802d8..5e7daa9c207 100644 --- a/targets/TARGET_Maxim/TARGET_MAX32630/mxc/nvic_table.h +++ b/targets/TARGET_Maxim/TARGET_MAX32630/mxc/nvic_table.h @@ -71,7 +71,7 @@ typedef void (*irq_fn)(void); * @param irqn ARM external IRQ number, see #IRQn_Type * @param irq_handler Function to be called at IRQ context */ -int NVIC_SetVector(IRQn_Type irqn, uint32_t irq_handler); +int NVIC_SetVector(IRQn_Type irqn, irq_fn irq_handler); /** * @brief Copy NVIC vector table to RAM and set NVIC to RAM based table. diff --git a/targets/TARGET_Maxim/TARGET_MAX32630/rtc_api.c b/targets/TARGET_Maxim/TARGET_MAX32630/rtc_api.c index 703ea7954c4..2b411c26c31 100644 --- a/targets/TARGET_Maxim/TARGET_MAX32630/rtc_api.c +++ b/targets/TARGET_Maxim/TARGET_MAX32630/rtc_api.c @@ -71,9 +71,9 @@ void rtc_init(void) CLKMAN_SetClkScale(CLKMAN_CLK_SYNC, CLKMAN_SCALE_DIV_1); // Prepare interrupt handlers - NVIC_SetVector(RTC0_IRQn, (uint32_t)lp_ticker_irq_handler); + NVIC_SetVector(RTC0_IRQn, lp_ticker_irq_handler); NVIC_EnableIRQ(RTC0_IRQn); - NVIC_SetVector(RTC3_IRQn, (uint32_t)overflow_handler); + NVIC_SetVector(RTC3_IRQn, overflow_handler); NVIC_EnableIRQ(RTC3_IRQn); // Enable wakeup on RTC rollover diff --git a/targets/TARGET_Maxim/TARGET_MAX32630/serial_api.c b/targets/TARGET_Maxim/TARGET_MAX32630/serial_api.c index 543dfa7cda6..a84df5a297c 100644 --- a/targets/TARGET_Maxim/TARGET_MAX32630/serial_api.c +++ b/targets/TARGET_Maxim/TARGET_MAX32630/serial_api.c @@ -202,19 +202,19 @@ void serial_irq_set(serial_t *obj, SerialIrq irq, uint32_t enable) { switch (obj->index) { case 0: - NVIC_SetVector(UART0_IRQn, (uint32_t)uart0_handler); + NVIC_SetVector(UART0_IRQn, uart0_handler); NVIC_EnableIRQ(UART0_IRQn); break; case 1: - NVIC_SetVector(UART1_IRQn, (uint32_t)uart1_handler); + NVIC_SetVector(UART1_IRQn, uart1_handler); NVIC_EnableIRQ(UART1_IRQn); break; case 2: - NVIC_SetVector(UART2_IRQn, (uint32_t)uart2_handler); + NVIC_SetVector(UART2_IRQn, uart2_handler); NVIC_EnableIRQ(UART2_IRQn); break; case 3: - NVIC_SetVector(UART3_IRQn, (uint32_t)uart3_handler); + NVIC_SetVector(UART3_IRQn, uart3_handler); NVIC_EnableIRQ(UART3_IRQn); break; default: diff --git a/targets/TARGET_Maxim/TARGET_MAX32630/sleep.c b/targets/TARGET_Maxim/TARGET_MAX32630/sleep.c index 3984b4aca33..560a4409293 100644 --- a/targets/TARGET_Maxim/TARGET_MAX32630/sleep.c +++ b/targets/TARGET_Maxim/TARGET_MAX32630/sleep.c @@ -34,13 +34,13 @@ #include "sleep_api.h" #include "lp.h" -void hal_sleep(void) +void sleep(void) { LP_EnterLP2(); } // Low-power stop mode -void hal_deepsleep(void) +void deepsleep(void) { - hal_sleep(); + sleep(); } diff --git a/targets/TARGET_Maxim/TARGET_MAX32630/us_ticker.c b/targets/TARGET_Maxim/TARGET_MAX32630/us_ticker.c index 5da2417d897..dad1ce2339f 100644 --- a/targets/TARGET_Maxim/TARGET_MAX32630/us_ticker.c +++ b/targets/TARGET_Maxim/TARGET_MAX32630/us_ticker.c @@ -140,7 +140,7 @@ void us_ticker_init(void) cfg.compareCount = 0xFFFFFFFF; TMR32_Config(US_TIMER, &cfg); - NVIC_SetVector(US_TIMER_IRQn, (uint32_t)tmr_handler); + NVIC_SetVector(US_TIMER_IRQn, tmr_handler); NVIC_EnableIRQ(US_TIMER_IRQn); TMR32_EnableINT(US_TIMER); diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF51822_UNIFIED/sdk_patch/sdk_config.h b/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF51822_UNIFIED/sdk_patch/sdk_config.h deleted file mode 100644 index 8ee54778fcc..00000000000 --- a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF51822_UNIFIED/sdk_patch/sdk_config.h +++ /dev/null @@ -1,19 +0,0 @@ -#ifndef _SDK_CONFIG_H_ -#define _SDK_CONFIG_H_ - -#include "nrf_drv_config.h" - -#define UART_DEFAULT_CONFIG_BAUDRATE UART0_CONFIG_BAUDRATE -#define UART_DEFAULT_CONFIG_PARITY UART0_CONFIG_PARITY -#define UART_DEFAULT_CONFIG_HWFC UART0_CONFIG_HWFC -#define CTS_PIN_NUMBER UART0_CONFIG_PSEL_CTS -#define RTS_PIN_NUMBER UART0_CONFIG_PSEL_RTS - -#define SPIS_DEFAULT_ORC NRF_DRV_SPIS_DEFAULT_ORC -#define SPIS_DEFAULT_CONFIG_IRQ_PRIORITY SPIS1_CONFIG_IRQ_PRIORITY; -#define SPIS_DEFAULT_ORC NRF_DRV_SPIS_DEFAULT_ORC -#define SPIS_DEFAULT_DEF NRF_DRV_SPIS_DEFAULT_DEF - -#define SPI_DEFAULT_CONFIG_IRQ_PRIORITY SPI1_CONFIG_IRQ_PRIORITY - -#endif \ No newline at end of file diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52832/analogin_api.c b/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52832/analogin_api.c new file mode 100644 index 00000000000..d33effecdf2 --- /dev/null +++ b/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52832/analogin_api.c @@ -0,0 +1,91 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * 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. + */ + +#include "mbed_assert.h" +#include "analogin_api.h" +#include "cmsis.h" +#include "pinmap.h" +#include "app_util_platform.h" +#include "nrf_drv_saadc.h" + +#ifdef DEVICE_ANALOGIN + +#define ADC_12BIT_RANGE 0xFFF +#define ADC_RANGE ADC_12BIT_RANGE + +static void analog_in_event_handler(nrf_drv_saadc_evt_t const *p_event)// type of nrf_drv_saadc_event_handler_t +{ + (void) p_event; +} + +static const nrf_drv_saadc_config_t saadc_config = +{ + .resolution = NRF_SAADC_RESOLUTION_12BIT, + .oversample = NRF_SAADC_OVERSAMPLE_DISABLED, + .interrupt_priority = SAADC_CONFIG_IRQ_PRIORITY +}; + +void SAADC_IRQHandler(void); + +void analogin_init(analogin_t *obj, PinName pin) +{ + ret_code_t ret_code; + + NVIC_SetVector(SAADC_IRQn, (uint32_t)SAADC_IRQHandler); + + ret_code = nrf_drv_saadc_init(&saadc_config, analog_in_event_handler); + MBED_ASSERT(((ret_code == NRF_SUCCESS) || (ret_code == NRF_ERROR_INVALID_STATE))); //NRF_ERROR_INVALID_STATE expected for multiple channels used. + + uint8_t saadcIn = nrf_drv_saadc_gpio_to_ain(pin); + MBED_ASSERT(saadcIn != NRF_SAADC_INPUT_DISABLED); + + obj->adc = ADC0_0; // only one instance of ADC in nRF52 SoC + obj->adc_pin = saadcIn - 1; + + nrf_saadc_channel_config_t channel_config = + NRF_DRV_SAADC_DEFAULT_CHANNEL_CONFIG_SE(saadcIn); //Single ended, negative input to ADC shorted to GND. + + ret_code = nrf_drv_saadc_channel_init(obj->adc_pin, &channel_config); + MBED_ASSERT(ret_code == NRF_SUCCESS); +} + + +uint16_t analogin_read_u16(analogin_t *obj) +{ + int16_t adc_value; + ret_code_t ret_code; + + ret_code = nrf_drv_saadc_sample_convert(obj->adc_pin, &adc_value); + MBED_ASSERT(ret_code == NRF_SUCCESS); + + if (adc_value < 0) + { + // Even in the single ended mode measured value can be {-0}. Saturation for avoid casting to a big integer. + return 0; + } + else + { + return (uint16_t) adc_value; + } +} + +float analogin_read(analogin_t *obj) +{ + uint16_t value = analogin_read_u16(obj); + return (float)value * (1.0f / (float)ADC_RANGE); +} + +#endif // DEVICE_ANALOGIN diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52832/pwmout_api.c b/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52832/pwmout_api.c new file mode 100644 index 00000000000..97e29f256db --- /dev/null +++ b/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52832/pwmout_api.c @@ -0,0 +1,399 @@ +/* + * Copyright (c) 2013 Nordic Semiconductor ASA + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * 2. Redistributions in binary form, except as embedded into a Nordic Semiconductor ASA + * integrated circuit in a product or a software update for such product, must reproduce + * the above copyright notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of Nordic Semiconductor ASA nor the names of its contributors may be + * used to endorse or promote products derived from this software without specific prior + * written permission. + * + * 4. This software, with or without modification, must only be used with a + * Nordic Semiconductor ASA integrated circuit. + * + * 5. Any software provided in binary or object form under this license must not be reverse + * engineered, decompiled, modified and/or disassembled. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#include "mbed_assert.h" +#include "mbed_error.h" +#include "pwmout_api.h" +#include "cmsis.h" +#include "pinmap.h" + +#if DEVICE_PWMOUT + +#include "app_util_platform.h" +#include "nrf_drv_pwm.h" + +#define MAX_PWM_COUNTERTOP (0x7FFF) // 0x7FFF is the max of COUNTERTOP value for the PWM peripherial of the nRF52. +#define MAX_PWM_PERIOD_US (MAX_PWM_COUNTERTOP * 8) // PWM hw is driven by 16 MHz clock, hence the tick is 1_us/16, + // and 128 is the max prescaler value. +#define MAX_PWM_PERIOD_MS ((MAX_PWM_PERIOD_US / 1000) + 1) // approximations advance +#define MAX_PWM_PERIOD_S ((MAX_PWM_PERIOD_US / 1000000) + 1) // approximations advance + + +#define PWM_INSTANCE_COUNT (PWM_COUNT) // import from the nrf_drv_config.h file + +///> instances of nRF52 PWM driver +static const nrf_drv_pwm_t m_pwm_driver[PWM_INSTANCE_COUNT] = +{ +#if PWM0_ENABLED + NRF_DRV_PWM_INSTANCE(0), +#endif +#if PWM1_ENABLED + NRF_DRV_PWM_INSTANCE(1), +#endif +#if PWM2_ENABLED + NRF_DRV_PWM_INSTANCE(2) +#endif +}; + +typedef struct +{ + uint32_t period_us; + uint32_t duty_us; + float duty; +} pwm_signal_t; /// PWM signal description type + +typedef struct +{ + nrf_drv_pwm_t * p_pwm_driver; + pwm_signal_t signal; + volatile nrf_pwm_values_common_t seq_values[1]; +} pwm_t; /// internal PWM instance support type + +static pwm_t m_pwm[PWM_INSTANCE_COUNT] = +{ +#if PWM0_ENABLED + {.p_pwm_driver = NULL}, +#endif +#if PWM1_ENABLED + {.p_pwm_driver = NULL}, +#endif +#if PWM2_ENABLED + {.p_pwm_driver = NULL} +#endif +}; /// Array of internal PWM instances. + +typedef struct +{ + uint16_t period_hwu; // unit related to pwm_clk + uint16_t duty_hwu; // unit related to pwm_clk + nrf_pwm_clk_t pwm_clk; +} pulsewidth_set_t; /// helper type for timing calculations + + +static void internal_pwmout_exe(pwmout_t *obj, bool new_period, bool initialization); + +// extern PWM nIRQ handler implementations +void PWM0_IRQHandler(void); +void PWM1_IRQHandler(void); +void PWM2_IRQHandler(void); + +static const peripheral_handler_desc_t pwm_handlers[PWM_INSTANCE_COUNT] = +{ + { + PWM0_IRQn, + (uint32_t)PWM0_IRQHandler + }, + { + PWM1_IRQn, + (uint32_t)PWM1_IRQHandler + }, + { + PWM2_IRQn, + (uint32_t)PWM2_IRQHandler + } +}; + +void pwmout_init(pwmout_t *obj, PinName pin) +{ + uint32_t i; + + for (i = 0; PWM_INSTANCE_COUNT; i++) + { + if (m_pwm[i].p_pwm_driver == NULL) // a driver instance not assigned to the obj? + { + NVIC_SetVector(pwm_handlers[i].IRQn, pwm_handlers[i].vector); + + obj->pin = pin; + + obj->pwm_channel = i; + + m_pwm[i].p_pwm_driver = (nrf_drv_pwm_t *) &m_pwm_driver[i]; + m_pwm[i].signal.period_us = 200000; // 0.02 s + m_pwm[i].signal.duty_us = 100000; + m_pwm[i].signal.duty = 0.5f; + + obj->pwm_struct = &m_pwm[i]; + + internal_pwmout_exe(obj, true, true); + + break; + } + } + + MBED_ASSERT(i != PWM_INSTANCE_COUNT); // assert if free instance was not found. +} + +void pwmout_free(pwmout_t *obj) +{ + nrf_drv_pwm_uninit( (nrf_drv_pwm_t*) obj->pwm_struct ); + + m_pwm[obj->pwm_channel].p_pwm_driver = NULL; +} + +void pwmout_write(pwmout_t *obj, float percent) +{ + + if (percent < 0) + { + percent = 0; + } + else if (percent > 1) + { + percent = 1; + } + + pwm_signal_t * p_pwm_signal = &(((pwm_t*)obj->pwm_struct)->signal); + + p_pwm_signal->duty = percent; + + int us = (((int)p_pwm_signal->period_us) * percent); + + pwmout_pulsewidth_us(obj, us); +} + +float pwmout_read(pwmout_t *obj) +{ + pwm_signal_t * p_pwm_signal = &(((pwm_t*)obj->pwm_struct)->signal); + + return (float)p_pwm_signal->duty_us / (float)p_pwm_signal->period_us; +} + +void pwmout_period(pwmout_t *obj, float seconds) +{ + // raught saturation < 0, quasi-max> + if (seconds > MAX_PWM_PERIOD_S) + { + seconds = MAX_PWM_PERIOD_S; + } + else if (seconds < 0) + { + seconds = 0; // f. pwmout_period_us will set period to min. value + } + + int us = seconds * 1000000; + + pwmout_period_us(obj, us); +} + +void pwmout_period_ms(pwmout_t *obj, int ms) +{ + // reught saturation < 0, quasi-max> + if (ms > MAX_PWM_PERIOD_MS) + { + ms = MAX_PWM_PERIOD_MS; + } + else if (ms < 0) + { + ms = 0; // f. pwmout_period_us will set period to min. value + } + + int us = ms * 1000; + + pwmout_period_us(obj, us); +} + + +void pwmout_period_us(pwmout_t *obj, int us) +{ + pwm_signal_t * p_pwm_signal = &(((pwm_t*)obj->pwm_struct)->signal); + + // saturation <1, real-max> + if (us > MAX_PWM_PERIOD_US) + { + us = MAX_PWM_PERIOD_US; + } + else if (us < 1) + { + us = 1; + } + + p_pwm_signal->duty_us = (int)((float)us * p_pwm_signal->duty); + + p_pwm_signal->period_us = us; + + internal_pwmout_exe(obj, true, false); +} + +void pwmout_pulsewidth(pwmout_t *obj, float seconds) +{ + // raught saturation < 0, quasi-max> + if (seconds > MAX_PWM_PERIOD_S) + { + seconds = MAX_PWM_PERIOD_S; + } + else if (seconds < 0) + { + seconds = 0; + } + + int us = seconds * 1000000; + + pwmout_pulsewidth_us(obj,us); +} + +void pwmout_pulsewidth_ms(pwmout_t *obj, int ms) +{ + // raught saturation < 0, quasi-max> + if (ms > MAX_PWM_PERIOD_MS) + { + ms = MAX_PWM_PERIOD_MS; + } + else if (ms < 0) + { + ms = 0; + } + + int us = ms * 1000; + + pwmout_pulsewidth_us(obj, us); +} + +void pwmout_pulsewidth_us(pwmout_t *obj, int us) +{ + // saturation <0, real-max> + if (us > MAX_PWM_PERIOD_US) + { + us = MAX_PWM_PERIOD_US; + } + else if (us < 0) + { + us = 0; + } + + pwm_signal_t * p_pwm_signal = &(((pwm_t*)obj->pwm_struct)->signal); + + p_pwm_signal->duty_us = us; + p_pwm_signal->duty = us / p_pwm_signal->period_us; + + internal_pwmout_exe(obj, false, false); +} + + + + + + +static ret_code_t pulsewidth_us_set_get(int period_hwu, int duty_hwu, pulsewidth_set_t * p_settings) +{ + uint16_t div; + nrf_pwm_clk_t pwm_clk = NRF_PWM_CLK_16MHz; + + for(div = 1; div <= 128 ; div <<= 1) // 128 is the maximum of clock prescaler for PWM peripherial + { + if (MAX_PWM_COUNTERTOP >= period_hwu) + { + p_settings->period_hwu = period_hwu; // unit [us/16 * div] + p_settings->duty_hwu = duty_hwu; // unit [us/16 * div] + p_settings->pwm_clk = pwm_clk; + + return NRF_SUCCESS; + } + + period_hwu >>= 1; + duty_hwu >>= 1; + pwm_clk++; + } + + return NRF_ERROR_INVALID_PARAM; +} + + +static void internal_pwmout_exe(pwmout_t *obj, bool new_period, bool initialization) +{ + pulsewidth_set_t pulsewidth_set; + pwm_signal_t * p_pwm_signal; + nrf_drv_pwm_t * p_pwm_driver; + ret_code_t ret_code; + + p_pwm_signal = &(((pwm_t*)obj->pwm_struct)->signal); + + if (NRF_SUCCESS == pulsewidth_us_set_get(p_pwm_signal->period_us * 16, // base clk for PWM is 16 MHz + p_pwm_signal->duty_us * 16, // base clk for PWM is 16 MHz + &pulsewidth_set)) + { + p_pwm_driver = (((pwm_t*)obj->pwm_struct)->p_pwm_driver); + + const nrf_pwm_sequence_t seq = + { + .values.p_common = (nrf_pwm_values_common_t*) (((pwm_t*)obj->pwm_struct)->seq_values), + .length = 1, + .repeats = 0, + .end_delay = 0 + }; + + (((pwm_t*)obj->pwm_struct)->seq_values)[0] = pulsewidth_set.duty_hwu | 0x8000; + + if (new_period) + { + nrf_drv_pwm_config_t config0 = + { + .output_pins = + { + obj->pin | NRF_DRV_PWM_PIN_INVERTED, // channel 0 + NRF_DRV_PWM_PIN_NOT_USED, // channel 1 + NRF_DRV_PWM_PIN_NOT_USED, // channel 2 + NRF_DRV_PWM_PIN_NOT_USED, // channel 3 + }, + .irq_priority = PWM0_CONFIG_IRQ_PRIORITY, + .base_clock = pulsewidth_set.pwm_clk, + .count_mode = NRF_PWM_MODE_UP, + .top_value = pulsewidth_set.period_hwu, + .load_mode = NRF_PWM_LOAD_COMMON, + .step_mode = NRF_PWM_STEP_AUTO + }; + + if (!initialization) + { + nrf_drv_pwm_uninit(p_pwm_driver); + } + + ret_code = nrf_drv_pwm_init( p_pwm_driver, &config0, NULL); + + MBED_ASSERT(ret_code == NRF_SUCCESS); // assert if free instance was not found. + } + + nrf_drv_pwm_simple_playback(p_pwm_driver, &seq, 0, NRF_DRV_PWM_FLAG_LOOP); + } + else + { + MBED_ASSERT(0); // force assertion + } + +} + +#endif // DEVICE_PWMOUT diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52832/sdk_patch/sdk_config.h b/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52832/sdk_patch/sdk_config.h deleted file mode 100644 index e9a63353a9f..00000000000 --- a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52832/sdk_patch/sdk_config.h +++ /dev/null @@ -1,21 +0,0 @@ -#ifndef _SDK_CONFIG_H_ -#define _SDK_CONFIG_H_ - -#include "nrf_drv_config.h" - -#define UART_DEFAULT_CONFIG_BAUDRATE UART0_CONFIG_BAUDRATE -#define UART_DEFAULT_CONFIG_PARITY UART0_CONFIG_PARITY -#define UART_DEFAULT_CONFIG_HWFC UART0_CONFIG_HWFC -#define CTS_PIN_NUMBER UART0_CONFIG_PSEL_CTS -#define RTS_PIN_NUMBER UART0_CONFIG_PSEL_RTS - -#define SPIS_DEFAULT_ORC NRF_DRV_SPIS_DEFAULT_ORC -#define SPIS_DEFAULT_CONFIG_IRQ_PRIORITY SPIS1_CONFIG_IRQ_PRIORITY; -#define SPIS_DEFAULT_ORC NRF_DRV_SPIS_DEFAULT_ORC -#define SPIS_DEFAULT_DEF NRF_DRV_SPIS_DEFAULT_DEF - -#define SPI_DEFAULT_CONFIG_IRQ_PRIORITY SPI1_CONFIG_IRQ_PRIORITY - -#define PWM_DEFAULT_CONFIG_IRQ_PRIORITY PWM0_CONFIG_IRQ_PRIORITY - -#endif \ No newline at end of file diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/gpio_api.c b/targets/TARGET_NORDIC/TARGET_NRF5/gpio_api.c index ec73afa6a3f..a5c6c850c21 100644 --- a/targets/TARGET_NORDIC/TARGET_NRF5/gpio_api.c +++ b/targets/TARGET_NORDIC/TARGET_NRF5/gpio_api.c @@ -22,12 +22,8 @@ #if defined(TARGET_MCU_NRF51822) #define GPIO_PIN_COUNT 31 -#elif defined(TARGET_MCU_NRF52832) - #define GPIO_PIN_COUNT 32 -#elif defined(TARGET_MCU_NRF52840) - #define GPIO_PIN_COUNT 48 #else - #error not recognized gpio count for mcu + #define GPIO_PIN_COUNT 32 #endif typedef struct { @@ -40,14 +36,8 @@ typedef struct { bool irq_rise : 1; } gpio_cfg_t; -#if GPIO_PIN_COUNT > 32 - typedef uint64_t gpio_mask_t; -#else - typedef uint32_t gpio_mask_t; -#endif - -static gpio_mask_t m_gpio_initialized; -static gpio_cfg_t m_gpio_cfg[GPIO_PIN_COUNT]; +uint32_t m_gpio_initialized; +gpio_cfg_t m_gpio_cfg[GPIO_PIN_COUNT]; /*********** @@ -56,7 +46,7 @@ static gpio_cfg_t m_gpio_cfg[GPIO_PIN_COUNT]; static gpio_irq_handler m_irq_handler; static uint32_t m_channel_ids[GPIO_PIN_COUNT] = {0}; -static gpio_mask_t m_gpio_irq_enabled; +uint32_t m_gpio_irq_enabled; static void gpiote_irq_handler(nrf_drv_gpiote_pin_t pin, nrf_gpiote_polarity_t action) @@ -64,7 +54,7 @@ static void gpiote_irq_handler(nrf_drv_gpiote_pin_t pin, nrf_gpiote_polarity_t a nrf_gpio_pin_sense_t sense = nrf_gpio_pin_sense_get(pin); gpio_irq_event event = (sense == NRF_GPIO_PIN_SENSE_LOW) ? IRQ_RISE : IRQ_FALL; - if (m_gpio_irq_enabled & ((gpio_mask_t)1 << pin)) { + if (m_gpio_irq_enabled & (1UL << pin)) { if (((event == IRQ_RISE) && m_gpio_cfg[pin].irq_rise) || ((event == IRQ_FALL) && m_gpio_cfg[pin].irq_fall)) { m_irq_handler(m_channel_ids[pin], event); @@ -89,19 +79,12 @@ void gpio_init(gpio_t *obj, PinName pin) m_gpio_cfg[obj->pin].used_as_gpio = true; } -#ifdef TARGET_SDK11 -// implement polyfill of gpio hal for the nRF5 SDK v11 -__STATIC_INLINE uint32_t nrf_gpio_pin_out_read(uint32_t pin) -{ - return (NRF_GPIO->OUTSET & (1UL << (pin))); -} -#endif int gpio_read(gpio_t *obj) { MBED_ASSERT(obj->pin != (PinName)NC); if (m_gpio_cfg[obj->pin].direction == PIN_OUTPUT) { - return (nrf_gpio_pin_out_read(obj->pin) ? 1 : 0); + return ((NRF_GPIO->OUTSET & (1UL << obj->pin)) ? 1 : 0); } else { return nrf_gpio_pin_read(obj->pin); } @@ -109,7 +92,7 @@ int gpio_read(gpio_t *obj) static void gpiote_pin_uninit(uint8_t pin) { - if (m_gpio_initialized & ((gpio_mask_t)1UL << pin)) { + if (m_gpio_initialized & (1UL << pin)) { if ((m_gpio_cfg[pin].direction == PIN_OUTPUT) && (!m_gpio_cfg[pin].used_as_irq)) { nrf_drv_gpiote_out_uninit(pin); } @@ -133,7 +116,7 @@ static void gpio_apply_config(uint8_t pin) if (m_gpio_cfg[pin].used_as_irq) { cfg.pull = NRF_GPIO_PIN_PULLUP; nrf_drv_gpiote_in_init(pin, &cfg, gpiote_irq_handler); - if ((m_gpio_irq_enabled & ((gpio_mask_t)1 << pin)) + if ((m_gpio_irq_enabled & (1 << pin)) && (m_gpio_cfg[pin].irq_rise || m_gpio_cfg[pin].irq_fall)) { nrf_drv_gpiote_in_event_enable(pin, true); @@ -159,17 +142,17 @@ static void gpio_apply_config(uint8_t pin) nrf_drv_gpiote_out_config_t cfg = GPIOTE_CONFIG_OUT_SIMPLE(m_gpio_cfg[pin].init_high); nrf_drv_gpiote_out_init(pin, &cfg); } - m_gpio_initialized |= ((gpio_mask_t)1UL << pin); + m_gpio_initialized |= (1UL << pin); } else { - m_gpio_initialized &= ~((gpio_mask_t)1UL << pin); + m_gpio_initialized &= ~(1UL << pin); } } void gpio_mode(gpio_t *obj, PinMode mode) { - MBED_ASSERT(obj->pin != (PinName)NC); + MBED_ASSERT(obj->pin <= GPIO_PIN_COUNT); gpiote_pin_uninit(obj->pin); // try to uninitialize gpio before a change. @@ -180,7 +163,7 @@ void gpio_mode(gpio_t *obj, PinMode mode) void gpio_dir(gpio_t *obj, PinDirection direction) { - MBED_ASSERT(obj->pin != (PinName)NC); + MBED_ASSERT(obj->pin <= GPIO_PIN_COUNT); gpiote_pin_uninit(obj->pin); // try to uninitialize gpio before a change. @@ -228,7 +211,7 @@ void gpio_irq_set(gpio_irq_t *obj, gpio_irq_event event, uint32_t enable) { gpio_cfg_t* cfg = &m_gpio_cfg[obj->ch]; bool irq_enabled_before = - (m_gpio_irq_enabled & ((gpio_mask_t)1 << obj->ch)) && + (m_gpio_irq_enabled & (1 << obj->ch)) && (cfg->irq_rise || cfg->irq_fall); if (event == IRQ_RISE) { @@ -252,7 +235,7 @@ void gpio_irq_set(gpio_irq_t *obj, gpio_irq_event event, uint32_t enable) void gpio_irq_enable(gpio_irq_t *obj) { - m_gpio_irq_enabled |= ((gpio_mask_t)1 << obj->ch); + m_gpio_irq_enabled |= (1 << obj->ch); if (m_gpio_cfg[obj->ch].irq_rise || m_gpio_cfg[obj->ch].irq_fall) { nrf_drv_gpiote_in_event_enable(obj->ch, true); } @@ -261,6 +244,6 @@ void gpio_irq_enable(gpio_irq_t *obj) void gpio_irq_disable(gpio_irq_t *obj) { - m_gpio_irq_enabled &= ~((gpio_mask_t)1 << obj->ch); + m_gpio_irq_enabled &= ~(1 << obj->ch); nrf_drv_gpiote_in_event_disable(obj->ch); } diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/i2c_api.c b/targets/TARGET_NORDIC/TARGET_NRF5/i2c_api.c index 723a406dd23..66063b4c499 100644 --- a/targets/TARGET_NORDIC/TARGET_NRF5/i2c_api.c +++ b/targets/TARGET_NORDIC/TARGET_NRF5/i2c_api.c @@ -45,7 +45,7 @@ #include "mbed_error.h" #include "nrf_twi.h" #include "nrf_drv_common.h" -#include "sdk_config.h" +#include "nrf_drv_config.h" #include "app_util_platform.h" #include "nrf_gpio.h" #include "nrf_delay.h" @@ -62,11 +62,6 @@ #endif #define TWI_INFO(obj) (&m_twi_info[TWI_IDX(obj)]) -#ifdef TARGET_SDK13 - #define TWI0_INSTANCE_INDEX 0 - #define TWI1_INSTANCE_INDEX TWI0_INSTANCE_INDEX+TWI0_ENABLED -#endif - typedef struct { bool initialized; uint32_t pselsda; @@ -103,22 +98,22 @@ void SPI1_TWI1_IRQHandler(void); static const peripheral_handler_desc_t twi_handlers[TWI_COUNT] = { -#if TWI0_ENABLED + #if TWI0_ENABLED { SPI0_TWI0_IRQn, (uint32_t) SPI0_TWI0_IRQHandler }, -#endif -#if TWI1_ENABLED + #endif + #if TWI1_ENABLED { SPI1_TWI1_IRQn, (uint32_t) SPI1_TWI1_IRQHandler } -#endif + #endif }; #ifdef NRF51 #define TWI_IRQ_PRIORITY APP_IRQ_PRIORITY_LOW -#elif defined(NRF52) || defined(NRF52840_XXAA) +#elif defined(NRF52) #define TWI_IRQ_PRIORITY APP_IRQ_PRIORITY_LOWEST #endif diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/objects.h b/targets/TARGET_NORDIC/TARGET_NRF5/objects.h index 4ae7530509f..209134b7d15 100644 --- a/targets/TARGET_NORDIC/TARGET_NRF5/objects.h +++ b/targets/TARGET_NORDIC/TARGET_NRF5/objects.h @@ -57,6 +57,9 @@ struct spi_s { }; struct port_s { + __IO uint32_t *reg_cnf; + __IO uint32_t *reg_out; + __I uint32_t *reg_in; PortName port; uint32_t mask; }; diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/pinmap.c b/targets/TARGET_NORDIC/TARGET_NRF5/pinmap.c index f723a5837e1..989fbf209bc 100644 --- a/targets/TARGET_NORDIC/TARGET_NRF5/pinmap.c +++ b/targets/TARGET_NORDIC/TARGET_NRF5/pinmap.c @@ -16,7 +16,6 @@ #include "mbed_assert.h" #include "mbed_error.h" #include "pinmap.h" -#include "nrf_gpio.h" void pin_function(PinName pin, int function) { @@ -30,12 +29,7 @@ void pin_mode(PinName pin, PinMode mode) MBED_ASSERT(pin != (PinName)NC); uint32_t pin_number = (uint32_t)pin; - -#ifdef TARGET_SDK11 - NRF_GPIO_Type * reg = NRF_GPIO; -#else - NRF_GPIO_Type * reg = nrf_gpio_pin_port_decode(&pin_number); -#endif - reg->PIN_CNF[pin_number] &= ~GPIO_PIN_CNF_PULL_Msk; - reg->PIN_CNF[pin_number] |= (mode << GPIO_PIN_CNF_PULL_Pos); + + NRF_GPIO->PIN_CNF[pin_number] &= ~GPIO_PIN_CNF_PULL_Msk; + NRF_GPIO->PIN_CNF[pin_number] |= (mode << GPIO_PIN_CNF_PULL_Pos); } diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/port_api.c b/targets/TARGET_NORDIC/TARGET_NRF5/port_api.c index e8c57184a5a..ad3be048166 100644 --- a/targets/TARGET_NORDIC/TARGET_NRF5/port_api.c +++ b/targets/TARGET_NORDIC/TARGET_NRF5/port_api.c @@ -38,42 +38,23 @@ #include "port_api.h" #include "pinmap.h" - -#if defined(TARGET_MCU_NRF51822) || defined(TARGET_MCU_NRF52832) - #define GPIO_REG_LIST {NRF_GPIO} -#endif - -static NRF_GPIO_Type * const m_ports[] = GPIO_REG_LIST; - -#if defined(TARGET_MCU_NRF51822) - static const uint32_t m_gpio_pin_count[] = {31}; -#elif defined(TARGET_MCU_NRF52832) - static const uint32_t m_gpio_pin_count[] = {32}; -#elif defined(TARGET_MCU_NRF52840) - static const uint32_t m_gpio_pin_count[] = {32, 16}; -#else - #error not recognized gpio count for mcu -#endif - -#define GPIO_PORT_COUNT (sizeof(m_gpio_pin_count)/sizeof(m_gpio_pin_count[0])) - +#include "gpio_api.h" PinName port_pin(PortName port, int pin_n) { -#if defined(TARGET_MCU_NRF51822) || defined(TARGET_MCU_NRF52832) - return (PinName)pin_n; -#else - return (PinName)NRF_GPIO_PIN_MAP(port, pin_n); -#endif + (void) port; + return (PinName)(pin_n); } void port_init(port_t *obj, PortName port, int mask, PinDirection dir) { - MBED_ASSERT((uint32_t)port < GPIO_PORT_COUNT); - obj->port = port; obj->mask = mask; + obj->reg_out = &NRF_GPIO->OUT; + obj->reg_in = &NRF_GPIO->IN; + obj->reg_cnf = NRF_GPIO->PIN_CNF; + port_dir(obj, dir); } @@ -90,45 +71,38 @@ void port_mode(port_t *obj, PinMode mode) void port_dir(port_t *obj, PinDirection dir) { - uint32_t i; - - volatile uint32_t *reg_cnf = (volatile uint32_t*) m_ports[obj->port]->PIN_CNF; - + int i; switch (dir) { - case PIN_INPUT: - - for (i = 0; i < m_gpio_pin_count[obj->port]; i++) { - if (obj->mask & (1 << i)) { - reg_cnf[i] = (GPIO_PIN_CNF_SENSE_Disabled << GPIO_PIN_CNF_SENSE_Pos) - | (GPIO_PIN_CNF_DRIVE_S0S1 << GPIO_PIN_CNF_DRIVE_Pos) - | (GPIO_PIN_CNF_INPUT_Connect << GPIO_PIN_CNF_INPUT_Pos) - | (GPIO_PIN_CNF_DIR_Input << GPIO_PIN_CNF_DIR_Pos); - } + case PIN_INPUT: + for (i = 0; i<31; i++) { + if (obj->mask & (1 << i)) { + obj->reg_cnf[i] = (GPIO_PIN_CNF_SENSE_Disabled << GPIO_PIN_CNF_SENSE_Pos) + | (GPIO_PIN_CNF_DRIVE_S0S1 << GPIO_PIN_CNF_DRIVE_Pos) + | (GPIO_PIN_CNF_INPUT_Connect << GPIO_PIN_CNF_INPUT_Pos) + | (GPIO_PIN_CNF_DIR_Input << GPIO_PIN_CNF_DIR_Pos); } - break; - - case PIN_OUTPUT: - - for (i = 0; i < m_gpio_pin_count[obj->port]; i++) { - if (obj->mask & (1 << i)) { - reg_cnf[i] = (GPIO_PIN_CNF_SENSE_Disabled << GPIO_PIN_CNF_SENSE_Pos) - | (GPIO_PIN_CNF_DRIVE_S0S1 << GPIO_PIN_CNF_DRIVE_Pos) - | (GPIO_PIN_CNF_PULL_Disabled << GPIO_PIN_CNF_PULL_Pos) - | (GPIO_PIN_CNF_INPUT_Connect << GPIO_PIN_CNF_INPUT_Pos) - | (GPIO_PIN_CNF_DIR_Output << GPIO_PIN_CNF_DIR_Pos); - } + } + break; + case PIN_OUTPUT: + for (i = 0; i<31; i++) { + if (obj->mask & (1 << i)) { + obj->reg_cnf[i] = (GPIO_PIN_CNF_SENSE_Disabled << GPIO_PIN_CNF_SENSE_Pos) + | (GPIO_PIN_CNF_DRIVE_S0S1 << GPIO_PIN_CNF_DRIVE_Pos) + | (GPIO_PIN_CNF_PULL_Disabled << GPIO_PIN_CNF_PULL_Pos) + | (GPIO_PIN_CNF_INPUT_Connect << GPIO_PIN_CNF_INPUT_Pos) + | (GPIO_PIN_CNF_DIR_Output << GPIO_PIN_CNF_DIR_Pos); } - break; + } + break; } } void port_write(port_t *obj, int value) { - m_ports[obj->port]->OUTSET = value & obj->mask; - m_ports[obj->port]->OUTCLR = (~value) & obj->mask; + *obj->reg_out = value; } int port_read(port_t *obj) { - return ((m_ports[obj->port]->IN) & obj->mask); + return (*obj->reg_in); } diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/ble_advertising/ble_advertising.c b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/ble_advertising/ble_advertising.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/ble_advertising/ble_advertising.c rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/ble_advertising/ble_advertising.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/ble_advertising/ble_advertising.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/ble_advertising/ble_advertising.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/ble_advertising/ble_advertising.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/ble_advertising/ble_advertising.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/ble_db_discovery/ble_db_discovery.c b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/ble_db_discovery/ble_db_discovery.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/ble_db_discovery/ble_db_discovery.c rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/ble_db_discovery/ble_db_discovery.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/ble_db_discovery/ble_db_discovery.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/ble_db_discovery/ble_db_discovery.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/ble_db_discovery/ble_db_discovery.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/ble_db_discovery/ble_db_discovery.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/ble_debug_assert_handler/ble_debug_assert_handler.c b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/ble_debug_assert_handler/ble_debug_assert_handler.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/ble_debug_assert_handler/ble_debug_assert_handler.c rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/ble_debug_assert_handler/ble_debug_assert_handler.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/ble_debug_assert_handler/ble_debug_assert_handler.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/ble_debug_assert_handler/ble_debug_assert_handler.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/ble_debug_assert_handler/ble_debug_assert_handler.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/ble_debug_assert_handler/ble_debug_assert_handler.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/ble_dtm/ble_dtm.c b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/ble_dtm/ble_dtm.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/ble_dtm/ble_dtm.c rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/ble_dtm/ble_dtm.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/ble_dtm/ble_dtm.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/ble_dtm/ble_dtm.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/ble_dtm/ble_dtm.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/ble_dtm/ble_dtm.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/ble_error_log/ble_error_log.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/ble_error_log/ble_error_log.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/ble_error_log/ble_error_log.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/ble_error_log/ble_error_log.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/ble_racp/ble_racp.c b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/ble_racp/ble_racp.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/ble_racp/ble_racp.c rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/ble_racp/ble_racp.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/ble_racp/ble_racp.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/ble_racp/ble_racp.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/ble_racp/ble_racp.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/ble_racp/ble_racp.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/ble_radio_notification/ble_radio_notification.c b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/ble_radio_notification/ble_radio_notification.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/ble_radio_notification/ble_radio_notification.c rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/ble_radio_notification/ble_radio_notification.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/ble_radio_notification/ble_radio_notification.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/ble_radio_notification/ble_radio_notification.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/ble_radio_notification/ble_radio_notification.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/ble_radio_notification/ble_radio_notification.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/ble_services/ble_dfu/ble_dfu.c b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/ble_services/ble_dfu/ble_dfu.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/ble_services/ble_dfu/ble_dfu.c rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/ble_services/ble_dfu/ble_dfu.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/ble_services/ble_dfu/ble_dfu.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/ble_services/ble_dfu/ble_dfu.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/ble_services/ble_dfu/ble_dfu.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/ble_services/ble_dfu/ble_dfu.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/common/ble_advdata.c b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/common/ble_advdata.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/common/ble_advdata.c rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/common/ble_advdata.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/common/ble_advdata.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/common/ble_advdata.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/common/ble_advdata.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/common/ble_advdata.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/common/ble_conn_params.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/common/ble_conn_params.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/common/ble_conn_params.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/common/ble_conn_params.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/common/ble_conn_state.c b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/common/ble_conn_state.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/common/ble_conn_state.c rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/common/ble_conn_state.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/common/ble_conn_state.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/common/ble_conn_state.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/common/ble_conn_state.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/common/ble_conn_state.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/common/ble_date_time.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/common/ble_date_time.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/common/ble_date_time.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/common/ble_date_time.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/common/ble_gatt_db.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/common/ble_gatt_db.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/common/ble_gatt_db.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/common/ble_gatt_db.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/common/ble_sensor_location.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/common/ble_sensor_location.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/common/ble_sensor_location.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/common/ble_sensor_location.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/common/ble_srv_common.c b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/common/ble_srv_common.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/common/ble_srv_common.c rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/common/ble_srv_common.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/common/ble_srv_common.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/common/ble_srv_common.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/common/ble_srv_common.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/common/ble_srv_common.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/device_manager/config/device_manager_cnfg.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/device_manager/config/device_manager_cnfg.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/device_manager/config/device_manager_cnfg.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/device_manager/config/device_manager_cnfg.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/device_manager/device_manager.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/device_manager/device_manager.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/device_manager/device_manager.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/device_manager/device_manager.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/device_manager/device_manager_peripheral.c b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/device_manager/device_manager_peripheral.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/device_manager/device_manager_peripheral.c rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/device_manager/device_manager_peripheral.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/peer_manager/gatt_cache_manager.c b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/peer_manager/gatt_cache_manager.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/peer_manager/gatt_cache_manager.c rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/peer_manager/gatt_cache_manager.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/peer_manager/gatt_cache_manager.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/peer_manager/gatt_cache_manager.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/peer_manager/gatt_cache_manager.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/peer_manager/gatt_cache_manager.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/peer_manager/gattc_cache_manager.c b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/peer_manager/gattc_cache_manager.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/peer_manager/gattc_cache_manager.c rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/peer_manager/gattc_cache_manager.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/peer_manager/gattc_cache_manager.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/peer_manager/gattc_cache_manager.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/peer_manager/gattc_cache_manager.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/peer_manager/gattc_cache_manager.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/peer_manager/gatts_cache_manager.c b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/peer_manager/gatts_cache_manager.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/peer_manager/gatts_cache_manager.c rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/peer_manager/gatts_cache_manager.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/peer_manager/gatts_cache_manager.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/peer_manager/gatts_cache_manager.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/peer_manager/gatts_cache_manager.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/peer_manager/gatts_cache_manager.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/peer_manager/id_manager.c b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/peer_manager/id_manager.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/peer_manager/id_manager.c rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/peer_manager/id_manager.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/peer_manager/id_manager.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/peer_manager/id_manager.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/peer_manager/id_manager.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/peer_manager/id_manager.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/peer_manager/peer_data.c b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/peer_manager/peer_data.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/peer_manager/peer_data.c rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/peer_manager/peer_data.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/peer_manager/peer_data.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/peer_manager/peer_data.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/peer_manager/peer_data.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/peer_manager/peer_data.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/peer_manager/peer_data_storage.c b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/peer_manager/peer_data_storage.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/peer_manager/peer_data_storage.c rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/peer_manager/peer_data_storage.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/peer_manager/peer_data_storage.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/peer_manager/peer_data_storage.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/peer_manager/peer_data_storage.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/peer_manager/peer_data_storage.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/peer_manager/peer_database.c b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/peer_manager/peer_database.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/peer_manager/peer_database.c rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/peer_manager/peer_database.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/peer_manager/peer_database.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/peer_manager/peer_database.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/peer_manager/peer_database.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/peer_manager/peer_database.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/peer_manager/peer_id.c b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/peer_manager/peer_id.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/peer_manager/peer_id.c rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/peer_manager/peer_id.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/peer_manager/peer_id.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/peer_manager/peer_id.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/peer_manager/peer_id.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/peer_manager/peer_id.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/peer_manager/peer_manager.c b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/peer_manager/peer_manager.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/peer_manager/peer_manager.c rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/peer_manager/peer_manager.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/peer_manager/peer_manager.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/peer_manager/peer_manager.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/peer_manager/peer_manager.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/peer_manager/peer_manager.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/peer_manager/peer_manager_internal.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/peer_manager/peer_manager_internal.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/peer_manager/peer_manager_internal.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/peer_manager/peer_manager_internal.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/peer_manager/peer_manager_types.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/peer_manager/peer_manager_types.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/peer_manager/peer_manager_types.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/peer_manager/peer_manager_types.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/peer_manager/pm_buffer.c b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/peer_manager/pm_buffer.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/peer_manager/pm_buffer.c rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/peer_manager/pm_buffer.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/peer_manager/pm_buffer.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/peer_manager/pm_buffer.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/peer_manager/pm_buffer.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/peer_manager/pm_buffer.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/peer_manager/pm_mutex.c b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/peer_manager/pm_mutex.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/peer_manager/pm_mutex.c rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/peer_manager/pm_mutex.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/peer_manager/pm_mutex.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/peer_manager/pm_mutex.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/peer_manager/pm_mutex.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/peer_manager/pm_mutex.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/peer_manager/security_dispatcher.c b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/peer_manager/security_dispatcher.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/peer_manager/security_dispatcher.c rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/peer_manager/security_dispatcher.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/peer_manager/security_dispatcher.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/peer_manager/security_dispatcher.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/peer_manager/security_dispatcher.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/peer_manager/security_dispatcher.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/peer_manager/security_manager.c b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/peer_manager/security_manager.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/peer_manager/security_manager.c rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/peer_manager/security_manager.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/peer_manager/security_manager.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/peer_manager/security_manager.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/ble/peer_manager/security_manager.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/ble/peer_manager/security_manager.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/device/compiler_abstraction.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/device/compiler_abstraction.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/device/compiler_abstraction.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/device/compiler_abstraction.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/device/nrf.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/device/nrf.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/device/nrf.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/device/nrf.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/device/nrf51.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/device/nrf51.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/device/nrf51.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/device/nrf51.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/device/nrf51_bitfields.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/device/nrf51_bitfields.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/device/nrf51_bitfields.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/device/nrf51_bitfields.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/device/nrf51_deprecated.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/device/nrf51_deprecated.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/device/nrf51_deprecated.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/device/nrf51_deprecated.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/device/nrf51_to_nrf52.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/device/nrf51_to_nrf52.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/device/nrf51_to_nrf52.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/device/nrf51_to_nrf52.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/device/nrf52.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/device/nrf52.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/device/nrf52.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/device/nrf52.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/device/nrf52_bitfields.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/device/nrf52_bitfields.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/device/nrf52_bitfields.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/device/nrf52_bitfields.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/device/nrf52_name_change.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/device/nrf52_name_change.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/device/nrf52_name_change.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/device/nrf52_name_change.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/ble_flash/ble_flash.c b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/ble_flash/ble_flash.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/ble_flash/ble_flash.c rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/ble_flash/ble_flash.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/ble_flash/ble_flash.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/ble_flash/ble_flash.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/ble_flash/ble_flash.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/ble_flash/ble_flash.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/clock/nrf_drv_clock.c b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/clock/nrf_drv_clock.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/clock/nrf_drv_clock.c rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/clock/nrf_drv_clock.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/clock/nrf_drv_clock.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/clock/nrf_drv_clock.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/clock/nrf_drv_clock.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/clock/nrf_drv_clock.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/common/nrf_drv_common.c b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/common/nrf_drv_common.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/common/nrf_drv_common.c rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/common/nrf_drv_common.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/common/nrf_drv_common.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/common/nrf_drv_common.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/common/nrf_drv_common.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/common/nrf_drv_common.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/config/nrf_drv_config_validation.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/config/nrf_drv_config_validation.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/config/nrf_drv_config_validation.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/config/nrf_drv_config_validation.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/delay/nrf_delay.c b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/delay/nrf_delay.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/delay/nrf_delay.c rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/delay/nrf_delay.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/delay/nrf_delay.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/delay/nrf_delay.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/delay/nrf_delay.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/delay/nrf_delay.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/gpiote/nrf_drv_gpiote.c b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/gpiote/nrf_drv_gpiote.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/gpiote/nrf_drv_gpiote.c rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/gpiote/nrf_drv_gpiote.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/gpiote/nrf_drv_gpiote.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/gpiote/nrf_drv_gpiote.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/gpiote/nrf_drv_gpiote.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/gpiote/nrf_drv_gpiote.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/hal/nrf_adc.c b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/hal/nrf_adc.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/hal/nrf_adc.c rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/hal/nrf_adc.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/hal/nrf_adc.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/hal/nrf_adc.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/hal/nrf_adc.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/hal/nrf_adc.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/hal/nrf_clock.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/hal/nrf_clock.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/hal/nrf_clock.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/hal/nrf_clock.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/hal/nrf_ecb.c b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/hal/nrf_ecb.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/hal/nrf_ecb.c rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/hal/nrf_ecb.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/hal/nrf_ecb.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/hal/nrf_ecb.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/hal/nrf_ecb.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/hal/nrf_ecb.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/hal/nrf_gpio.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/hal/nrf_gpio.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/hal/nrf_gpio.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/hal/nrf_gpio.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/hal/nrf_gpiote.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/hal/nrf_gpiote.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/hal/nrf_gpiote.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/hal/nrf_gpiote.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/hal/nrf_nvmc.c b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/hal/nrf_nvmc.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/hal/nrf_nvmc.c rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/hal/nrf_nvmc.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/hal/nrf_nvmc.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/hal/nrf_nvmc.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/hal/nrf_nvmc.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/hal/nrf_nvmc.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/hal/nrf_pdm.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/hal/nrf_pdm.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/hal/nrf_pdm.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/hal/nrf_pdm.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/hal/nrf_ppi.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/hal/nrf_ppi.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/hal/nrf_ppi.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/hal/nrf_ppi.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/hal/nrf_pwm.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/hal/nrf_pwm.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/hal/nrf_pwm.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/hal/nrf_pwm.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/hal/nrf_rtc.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/hal/nrf_rtc.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/hal/nrf_rtc.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/hal/nrf_rtc.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/hal/nrf_saadc.c b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/hal/nrf_saadc.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/hal/nrf_saadc.c rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/hal/nrf_saadc.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/hal/nrf_saadc.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/hal/nrf_saadc.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/hal/nrf_saadc.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/hal/nrf_saadc.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/hal/nrf_spi.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/hal/nrf_spi.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/hal/nrf_spi.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/hal/nrf_spi.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/hal/nrf_spim.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/hal/nrf_spim.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/hal/nrf_spim.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/hal/nrf_spim.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/hal/nrf_spis.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/hal/nrf_spis.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/hal/nrf_spis.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/hal/nrf_spis.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/hal/nrf_temp.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/hal/nrf_temp.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/hal/nrf_temp.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/hal/nrf_temp.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/hal/nrf_timer.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/hal/nrf_timer.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/hal/nrf_timer.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/hal/nrf_timer.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/hal/nrf_twi.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/hal/nrf_twi.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/hal/nrf_twi.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/hal/nrf_twi.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/hal/nrf_uart.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/hal/nrf_uart.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/hal/nrf_uart.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/hal/nrf_uart.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/hal/nrf_wdt.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/hal/nrf_wdt.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/hal/nrf_wdt.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/hal/nrf_wdt.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/ppi/nrf_drv_ppi.c b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/ppi/nrf_drv_ppi.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/ppi/nrf_drv_ppi.c rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/ppi/nrf_drv_ppi.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/ppi/nrf_drv_ppi.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/ppi/nrf_drv_ppi.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/ppi/nrf_drv_ppi.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/ppi/nrf_drv_ppi.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/pstorage/config/pstorage_platform.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/pstorage/config/pstorage_platform.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/pstorage/config/pstorage_platform.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/pstorage/config/pstorage_platform.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/pstorage/pstorage.c b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/pstorage/pstorage.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/pstorage/pstorage.c rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/pstorage/pstorage.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/pstorage/pstorage.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/pstorage/pstorage.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/pstorage/pstorage.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/pstorage/pstorage.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/spi_master/nrf_drv_spi.c b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/spi_master/nrf_drv_spi.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/spi_master/nrf_drv_spi.c rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/spi_master/nrf_drv_spi.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/spi_master/nrf_drv_spi.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/spi_master/nrf_drv_spi.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/spi_master/nrf_drv_spi.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/spi_master/nrf_drv_spi.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/spi_slave/nrf_drv_spis.c b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/spi_slave/nrf_drv_spis.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/spi_slave/nrf_drv_spis.c rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/spi_slave/nrf_drv_spis.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/spi_slave/nrf_drv_spis.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/spi_slave/nrf_drv_spis.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/spi_slave/nrf_drv_spis.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/spi_slave/nrf_drv_spis.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/timer/nrf_drv_timer.c b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/timer/nrf_drv_timer.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/timer/nrf_drv_timer.c rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/timer/nrf_drv_timer.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/timer/nrf_drv_timer.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/timer/nrf_drv_timer.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/drivers_nrf/timer/nrf_drv_timer.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/drivers_nrf/timer/nrf_drv_timer.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/bootloader_dfu/bootloader.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/bootloader_dfu/bootloader.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/bootloader_dfu/bootloader.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/bootloader_dfu/bootloader.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/bootloader_dfu/bootloader_settings.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/bootloader_dfu/bootloader_settings.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/bootloader_dfu/bootloader_settings.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/bootloader_dfu/bootloader_settings.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/bootloader_dfu/bootloader_types.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/bootloader_dfu/bootloader_types.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/bootloader_dfu/bootloader_types.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/bootloader_dfu/bootloader_types.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/bootloader_dfu/bootloader_util.c b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/bootloader_dfu/bootloader_util.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/bootloader_dfu/bootloader_util.c rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/bootloader_dfu/bootloader_util.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/bootloader_dfu/bootloader_util.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/bootloader_dfu/bootloader_util.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/bootloader_dfu/bootloader_util.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/bootloader_dfu/bootloader_util.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/bootloader_dfu/dfu.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/bootloader_dfu/dfu.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/bootloader_dfu/dfu.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/bootloader_dfu/dfu.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/bootloader_dfu/dfu_app_handler.c b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/bootloader_dfu/dfu_app_handler.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/bootloader_dfu/dfu_app_handler.c rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/bootloader_dfu/dfu_app_handler.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/bootloader_dfu/dfu_app_handler.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/bootloader_dfu/dfu_app_handler.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/bootloader_dfu/dfu_app_handler.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/bootloader_dfu/dfu_app_handler.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/bootloader_dfu/dfu_bank_internal.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/bootloader_dfu/dfu_bank_internal.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/bootloader_dfu/dfu_bank_internal.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/bootloader_dfu/dfu_bank_internal.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/bootloader_dfu/dfu_ble_svc.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/bootloader_dfu/dfu_ble_svc.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/bootloader_dfu/dfu_ble_svc.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/bootloader_dfu/dfu_ble_svc.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/bootloader_dfu/dfu_ble_svc_internal.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/bootloader_dfu/dfu_ble_svc_internal.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/bootloader_dfu/dfu_ble_svc_internal.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/bootloader_dfu/dfu_ble_svc_internal.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/bootloader_dfu/dfu_init.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/bootloader_dfu/dfu_init.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/bootloader_dfu/dfu_init.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/bootloader_dfu/dfu_init.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/bootloader_dfu/dfu_init_template.c b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/bootloader_dfu/dfu_init_template.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/bootloader_dfu/dfu_init_template.c rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/bootloader_dfu/dfu_init_template.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/bootloader_dfu/dfu_transport.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/bootloader_dfu/dfu_transport.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/bootloader_dfu/dfu_transport.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/bootloader_dfu/dfu_transport.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/bootloader_dfu/dfu_types.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/bootloader_dfu/dfu_types.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/bootloader_dfu/dfu_types.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/bootloader_dfu/dfu_types.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/bootloader_dfu/hci_transport/hci_mem_pool_internal.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/bootloader_dfu/hci_transport/hci_mem_pool_internal.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/bootloader_dfu/hci_transport/hci_mem_pool_internal.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/bootloader_dfu/hci_transport/hci_mem_pool_internal.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/bootloader_dfu/hci_transport/hci_transport_config.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/bootloader_dfu/hci_transport/hci_transport_config.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/bootloader_dfu/hci_transport/hci_transport_config.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/bootloader_dfu/hci_transport/hci_transport_config.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/crc16/crc16.c b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/crc16/crc16.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/crc16/crc16.c rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/crc16/crc16.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/crc16/crc16.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/crc16/crc16.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/crc16/crc16.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/crc16/crc16.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/experimental_section_vars/section_vars.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/experimental_section_vars/section_vars.h similarity index 99% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/experimental_section_vars/section_vars.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/experimental_section_vars/section_vars.h index 8b0bf6152ba..abd489b06c6 100644 --- a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/experimental_section_vars/section_vars.h +++ b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/experimental_section_vars/section_vars.h @@ -242,7 +242,7 @@ #elif defined(__ICCARM__) #define NRF_SECTION_VARS_ADD(section_name, type_def) \ - static __root type_def @ #section_name + __root type_def @ #section_name #endif diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/fds/config/fds_config.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/fds/config/fds_config.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/fds/config/fds_config.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/fds/config/fds_config.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/fds/fds.c b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/fds/fds.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/fds/fds.c rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/fds/fds.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/fds/fds.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/fds/fds.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/fds/fds.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/fds/fds.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/fds/fds_internal_defs.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/fds/fds_internal_defs.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/fds/fds_internal_defs.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/fds/fds_internal_defs.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/fstorage/config/fstorage_config.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/fstorage/config/fstorage_config.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/fstorage/config/fstorage_config.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/fstorage/config/fstorage_config.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/fstorage/fstorage.c b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/fstorage/fstorage.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/fstorage/fstorage.c rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/fstorage/fstorage.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/fstorage/fstorage.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/fstorage/fstorage.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/fstorage/fstorage.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/fstorage/fstorage.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/fstorage/fstorage_internal_defs.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/fstorage/fstorage_internal_defs.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/fstorage/fstorage_internal_defs.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/fstorage/fstorage_internal_defs.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/fstorage/fstorage_nosd.c b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/fstorage/fstorage_nosd.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/fstorage/fstorage_nosd.c rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/fstorage/fstorage_nosd.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/hci/config/hci_mem_pool_internal.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/hci/config/hci_mem_pool_internal.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/hci/config/hci_mem_pool_internal.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/hci/config/hci_mem_pool_internal.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/hci/config/hci_transport_config.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/hci/config/hci_transport_config.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/hci/config/hci_transport_config.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/hci/config/hci_transport_config.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/hci/hci_mem_pool.c b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/hci/hci_mem_pool.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/hci/hci_mem_pool.c rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/hci/hci_mem_pool.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/hci/hci_mem_pool.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/hci/hci_mem_pool.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/hci/hci_mem_pool.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/hci/hci_mem_pool.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/pwm/app_pwm.c b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/pwm/app_pwm.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/pwm/app_pwm.c rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/pwm/app_pwm.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/pwm/app_pwm.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/pwm/app_pwm.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/pwm/app_pwm.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/pwm/app_pwm.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/scheduler/app_scheduler.c b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/scheduler/app_scheduler.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/scheduler/app_scheduler.c rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/scheduler/app_scheduler.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/scheduler/app_scheduler.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/scheduler/app_scheduler.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/scheduler/app_scheduler.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/scheduler/app_scheduler.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/trace/app_trace.c b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/trace/app_trace.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/trace/app_trace.c rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/trace/app_trace.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/trace/app_trace.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/trace/app_trace.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/trace/app_trace.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/trace/app_trace.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/util/app_error.c b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/util/app_error.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/util/app_error.c rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/util/app_error.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/util/app_error.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/util/app_error.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/util/app_error.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/util/app_error.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/util/app_error_weak.c b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/util/app_error_weak.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/util/app_error_weak.c rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/util/app_error_weak.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/util/app_error_weak.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/util/app_error_weak.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/util/app_error_weak.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/util/app_error_weak.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/util/app_util.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/util/app_util.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/util/app_util.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/util/app_util.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/util/app_util_bds.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/util/app_util_bds.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/util/app_util_bds.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/util/app_util_bds.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/util/app_util_platform.c b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/util/app_util_platform.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/util/app_util_platform.c rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/util/app_util_platform.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/util/app_util_platform.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/util/app_util_platform.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/util/app_util_platform.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/util/app_util_platform.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/util/common.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/util/common.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/util/common.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/util/common.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/util/nordic_common.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/util/nordic_common.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/util/nordic_common.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/util/nordic_common.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/util/nrf_assert.c b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/util/nrf_assert.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/util/nrf_assert.c rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/util/nrf_assert.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/util/nrf_assert.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/util/nrf_assert.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/util/nrf_assert.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/util/nrf_assert.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/util/nrf_log.c b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/util/nrf_log.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/util/nrf_log.c rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/util/nrf_log.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/util/nrf_log.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/util/nrf_log.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/util/nrf_log.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/util/nrf_log.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/util/sdk_common.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/util/sdk_common.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/util/sdk_common.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/util/sdk_common.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/util/sdk_errors.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/util/sdk_errors.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/util/sdk_errors.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/util/sdk_errors.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/util/sdk_macros.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/util/sdk_macros.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/util/sdk_macros.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/util/sdk_macros.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/util/sdk_mapped_flags.c b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/util/sdk_mapped_flags.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/util/sdk_mapped_flags.c rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/util/sdk_mapped_flags.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/util/sdk_mapped_flags.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/util/sdk_mapped_flags.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/util/sdk_mapped_flags.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/util/sdk_mapped_flags.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/util/sdk_os.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/util/sdk_os.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/util/sdk_os.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/util/sdk_os.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/util/sdk_resources.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/util/sdk_resources.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/util/sdk_resources.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/libraries/util/sdk_resources.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/softdevice/common/softdevice_handler/ant_stack_handler_types.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/softdevice/common/softdevice_handler/ant_stack_handler_types.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/softdevice/common/softdevice_handler/ant_stack_handler_types.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/softdevice/common/softdevice_handler/ant_stack_handler_types.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/softdevice/common/softdevice_handler/app_ram_base.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/softdevice/common/softdevice_handler/app_ram_base.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/softdevice/common/softdevice_handler/app_ram_base.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/softdevice/common/softdevice_handler/app_ram_base.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/softdevice/common/softdevice_handler/ble_stack_handler_types.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/softdevice/common/softdevice_handler/ble_stack_handler_types.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/softdevice/common/softdevice_handler/ble_stack_handler_types.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/softdevice/common/softdevice_handler/ble_stack_handler_types.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/softdevice/common/softdevice_handler/softdevice_handler.c b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/softdevice/common/softdevice_handler/softdevice_handler.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/softdevice/common/softdevice_handler/softdevice_handler.c rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/softdevice/common/softdevice_handler/softdevice_handler.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/softdevice/common/softdevice_handler/softdevice_handler.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/softdevice/common/softdevice_handler/softdevice_handler.h similarity index 99% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/softdevice/common/softdevice_handler/softdevice_handler.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/softdevice/common/softdevice_handler/softdevice_handler.h index 439dffa8b32..588ce1626a6 100644 --- a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/softdevice/common/softdevice_handler/softdevice_handler.h +++ b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/softdevice/common/softdevice_handler/softdevice_handler.h @@ -232,7 +232,7 @@ uint32_t softdevice_enable(ble_enable_params_t * p_ble_enable_params); /**@cond NO_DOXYGEN */ void intern_softdevice_events_execute(void); -#define softdevice_handler_is_enabled softdevice_handler_isEnabled + /**@endcond */ #endif // SOFTDEVICE_HANDLER_H__ diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/softdevice/common/softdevice_handler/softdevice_handler_appsh.c b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/softdevice/common/softdevice_handler/softdevice_handler_appsh.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/softdevice/common/softdevice_handler/softdevice_handler_appsh.c rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/softdevice/common/softdevice_handler/softdevice_handler_appsh.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/softdevice/common/softdevice_handler/softdevice_handler_appsh.h b/targets/TARGET_NORDIC/TARGET_NRF5/sdk/softdevice/common/softdevice_handler/softdevice_handler_appsh.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/softdevice/common/softdevice_handler/softdevice_handler_appsh.h rename to targets/TARGET_NORDIC/TARGET_NRF5/sdk/softdevice/common/softdevice_handler/softdevice_handler_appsh.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/serial_api.c b/targets/TARGET_NORDIC/TARGET_NRF5/serial_api.c index 0835c517652..13ab6d3bb51 100644 --- a/targets/TARGET_NORDIC/TARGET_NRF5/serial_api.c +++ b/targets/TARGET_NORDIC/TARGET_NRF5/serial_api.c @@ -45,9 +45,9 @@ #include "mbed_error.h" #include "nrf_uart.h" #include "nrf_drv_common.h" +#include "nrf_drv_config.h" #include "app_util_platform.h" #include "nrf_gpio.h" -#include "sdk_config.h" #define UART_INSTANCE_COUNT 1 #define UART_INSTANCE NRF_UART0 @@ -56,8 +56,8 @@ #define UART_INSTANCE_ID 0 #define UART_CB uart_cb[UART_INSTANCE_ID] -#define UART_DEFAULT_BAUDRATE UART_DEFAULT_CONFIG_BAUDRATE -#define UART_DEFAULT_PARITY UART_DEFAULT_CONFIG_PARITY +#define UART_DEFAULT_BAUDRATE UART0_CONFIG_BAUDRATE +#define UART_DEFAULT_PARITY UART0_CONFIG_PARITY // expected the macro from mbed configuration system #ifndef MBED_CONF_NORDIC_UART_HWFC @@ -66,17 +66,17 @@ #endif #if MBED_CONF_NORDIC_UART_HWFC == 1 - #define UART_DEFAULT_HWFC UART_DEFAULT_CONFIG_HWFC + #define UART_DEFAULT_HWFC UART0_CONFIG_HWFC #else #define UART_DEFAULT_HWFC NRF_UART_HWFC_DISABLED #endif -#define UART_DEFAULT_CTS CTS_PIN_NUMBER -#define UART_DEFAULT_RTS RTS_PIN_NUMBER +#define UART_DEFAULT_CTS UART0_CONFIG_PSEL_CTS +#define UART_DEFAULT_RTS UART0_CONFIG_PSEL_RTS #ifdef NRF51 #define NRFx_MBED_UART_IRQ_PRIORITY APP_IRQ_PRIORITY_LOW -#elif defined(NRF52) || defined(NRF52840_XXAA) +#elif defined(NRF52) #define NRFx_MBED_UART_IRQ_PRIORITY APP_IRQ_PRIORITY_LOWEST #endif @@ -556,7 +556,7 @@ static void internal_set_hwfc(FlowControl type, nrf_gpio_cfg_input(UART_CB.pselcts, NRF_GPIO_PIN_NOPULL); } - UART_CB.hwfc = (nrf_uart_hwfc_t)((type == FlowControlNone)? NRF_UART_HWFC_DISABLED : UART_DEFAULT_CONFIG_HWFC); + UART_CB.hwfc = (type == FlowControlNone)? NRF_UART_HWFC_DISABLED : UART0_CONFIG_HWFC; nrf_uart_configure(UART_INSTANCE, UART_CB.parity, UART_CB.hwfc); nrf_uart_hwfc_pins_set(UART_INSTANCE, UART_CB.pselrts, UART_CB.pselcts); diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/sleep.c b/targets/TARGET_NORDIC/TARGET_NRF5/sleep.c index f806e7a0a65..29020dc934a 100644 --- a/targets/TARGET_NORDIC/TARGET_NRF5/sleep.c +++ b/targets/TARGET_NORDIC/TARGET_NRF5/sleep.c @@ -33,7 +33,7 @@ void hal_sleep(void) // the processor from disabled interrupts. SCB->SCR |= SCB_SCR_SEVONPEND_Msk; -#if defined(NRF52) || defined(NRF52840_XXAA) +#ifdef NRF52 /* Clear exceptions and PendingIRQ from the FPU unit */ __set_FPSCR(__get_FPSCR() & ~(FPU_EXCEPTION_MASK)); (void) __get_FPSCR(); @@ -41,7 +41,7 @@ void hal_sleep(void) #endif // If the SoftDevice is enabled, its API must be used to go to sleep. - if (softdevice_handler_is_enabled()) { + if (softdevice_handler_isEnabled()) { sd_power_mode_set(NRF_POWER_MODE_LOWPWR); sd_app_evt_wait(); } else { diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/spi_api.c b/targets/TARGET_NORDIC/TARGET_NRF5/spi_api.c index 79b73d89fe3..2c07af5e8b5 100644 --- a/targets/TARGET_NORDIC/TARGET_NRF5/spi_api.c +++ b/targets/TARGET_NORDIC/TARGET_NRF5/spi_api.c @@ -48,7 +48,6 @@ #include "nrf_drv_spi.h" #include "nrf_drv_spis.h" #include "app_util_platform.h" -#include "sdk_config.h" #if DEVICE_SPI_ASYNCH #define SPI_IDX(obj) ((obj)->spi.spi_idx) @@ -187,7 +186,7 @@ static void slave_event_handler(uint8_t spi_idx, // And prepare for the next transfer. // Previous data set in 'spi_slave_write' (if any) has been transmitted, // now use the default one, until some new is set by 'spi_slave_write'. - p_spi_info->tx_buf = SPIS_DEFAULT_ORC; + p_spi_info->tx_buf = NRF_DRV_SPIS_DEFAULT_ORC; nrf_drv_spis_buffers_set(&m_instances[spi_idx].slave, (uint8_t const *)&p_spi_info->tx_buf, 1, (uint8_t *)&p_spi_info->rx_buf, 1); @@ -229,7 +228,7 @@ static void prepare_master_config(nrf_drv_spi_config_t *p_config, p_config->frequency = p_spi_info->frequency; p_config->mode = (nrf_drv_spi_mode_t)p_spi_info->spi_mode; - p_config->irq_priority = SPI_DEFAULT_CONFIG_IRQ_PRIORITY; + p_config->irq_priority = SPI1_CONFIG_IRQ_PRIORITY; p_config->orc = 0xFF; p_config->bit_order = NRF_DRV_SPI_BIT_ORDER_MSB_FIRST; } @@ -243,9 +242,9 @@ static void prepare_slave_config(nrf_drv_spis_config_t *p_config, p_config->csn_pin = p_spi_info->ss_pin; p_config->mode = (nrf_drv_spis_mode_t)p_spi_info->spi_mode; - p_config->irq_priority = SPIS_DEFAULT_CONFIG_IRQ_PRIORITY; - p_config->orc = SPIS_DEFAULT_ORC; - p_config->def = SPIS_DEFAULT_DEF; + p_config->irq_priority = SPIS1_CONFIG_IRQ_PRIORITY; + p_config->orc = NRF_DRV_SPIS_DEFAULT_ORC; + p_config->def = NRF_DRV_SPIS_DEFAULT_DEF; p_config->bit_order = NRF_DRV_SPIS_BIT_ORDER_MSB_FIRST; p_config->csn_pullup = NRF_DRV_SPIS_DEFAULT_CSN_PULLUP; p_config->miso_drive = NRF_DRV_SPIS_DEFAULT_MISO_DRIVE; @@ -380,7 +379,7 @@ void spi_format(spi_t *obj, int bits, int mode, int slave) m_slave_event_handlers[SPI_IDX(obj)]); // Prepare the slave for transfer. - p_spi_info->tx_buf = SPIS_DEFAULT_ORC; + p_spi_info->tx_buf = NRF_DRV_SPIS_DEFAULT_ORC; nrf_drv_spis_buffers_set(SLAVE_INST(obj), (uint8_t const *)&p_spi_info->tx_buf, 1, (uint8_t *)&p_spi_info->rx_buf, 1); diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/us_ticker.c b/targets/TARGET_NORDIC/TARGET_NRF5/us_ticker.c index bde1be74734..903979e2a52 100644 --- a/targets/TARGET_NORDIC/TARGET_NRF5/us_ticker.c +++ b/targets/TARGET_NORDIC/TARGET_NRF5/us_ticker.c @@ -40,12 +40,9 @@ #include "common_rtc.h" #include "app_util.h" #include "nrf_drv_common.h" +#include "nrf_drv_config.h" #include "lp_ticker_api.h" -#include "mbed_critical.h" -#if defined(NRF52_ERRATA_20) - #include "softdevice_handler.h" -#endif //------------------------------------------------------------------------------ // Common stuff used also by lp_ticker and rtc_api (see "common_rtc.h"). @@ -55,25 +52,12 @@ bool m_common_rtc_enabled = false; uint32_t volatile m_common_rtc_overflows = 0; -__STATIC_INLINE void rtc_ovf_event_check(void) -{ - if (nrf_rtc_event_pending(COMMON_RTC_INSTANCE, NRF_RTC_EVENT_OVERFLOW)) { - nrf_rtc_event_clear(COMMON_RTC_INSTANCE, NRF_RTC_EVENT_OVERFLOW); - // Don't disable this event. It shall occur periodically. - - ++m_common_rtc_overflows; - } -} - #if defined(TARGET_MCU_NRF51822) void common_rtc_irq_handler(void) #else void COMMON_RTC_IRQ_HANDLER(void) #endif { - - rtc_ovf_event_check(); - if (nrf_rtc_event_pending(COMMON_RTC_INSTANCE, US_TICKER_EVENT)) { us_ticker_irq_handler(); } @@ -84,23 +68,13 @@ void COMMON_RTC_IRQ_HANDLER(void) lp_ticker_irq_handler(); } #endif -} -// Function for fix errata 20: RTC Register values are invalid -__STATIC_INLINE void errata_20(void) -{ -#if defined(NRF52_ERRATA_20) - if (!softdevice_handler_is_enabled()) - { - NRF_CLOCK->EVENTS_LFCLKSTARTED = 0; - NRF_CLOCK->TASKS_LFCLKSTART = 1; - - while (NRF_CLOCK->EVENTS_LFCLKSTARTED == 0) - { - } + if (nrf_rtc_event_pending(COMMON_RTC_INSTANCE, NRF_RTC_EVENT_OVERFLOW)) { + nrf_rtc_event_clear(COMMON_RTC_INSTANCE, NRF_RTC_EVENT_OVERFLOW); + // Don't disable this event. It shall occur periodically. + + ++m_common_rtc_overflows; } - NRF_RTC1->TASKS_STOP = 0; -#endif } #if (defined (__ICCARM__)) && defined(TARGET_MCU_NRF51822)//IAR @@ -114,8 +88,6 @@ void common_rtc_init(void) return; } - errata_20(); - NVIC_SetVector(RTC1_IRQn, (uint32_t)RTC1_IRQHandler); // RTC is driven by the low frequency (32.768 kHz) clock, a proper request @@ -138,9 +110,9 @@ void common_rtc_init(void) // events will be enabled or disabled as needed (such approach is more // energy efficient). nrf_rtc_int_enable(COMMON_RTC_INSTANCE, -#if DEVICE_LOWPOWERTIMER + #if DEVICE_LOWPOWERTIMER LP_TICKER_INT_MASK | -#endif + #endif US_TICKER_INT_MASK | NRF_RTC_INT_OVERFLOW_MASK); @@ -149,18 +121,18 @@ void common_rtc_init(void) nrf_rtc_event_enable(COMMON_RTC_INSTANCE, NRF_RTC_INT_OVERFLOW_MASK); // All other relevant events are initially disabled. nrf_rtc_event_disable(COMMON_RTC_INSTANCE, -#if defined(TARGET_MCU_NRF51822) + #if defined(TARGET_MCU_NRF51822) OS_TICK_INT_MASK | -#endif -#if DEVICE_LOWPOWERTIMER + #endif + #if DEVICE_LOWPOWERTIMER LP_TICKER_INT_MASK | -#endif + #endif US_TICKER_INT_MASK); nrf_drv_common_irq_enable(nrf_drv_get_IRQn(COMMON_RTC_INSTANCE), #ifdef NRF51 APP_IRQ_PRIORITY_LOW -#elif defined(NRF52) || defined(NRF52840_XXAA) +#elif defined(NRF52) APP_IRQ_PRIORITY_LOWEST #endif ); @@ -170,37 +142,13 @@ void common_rtc_init(void) m_common_rtc_enabled = true; } -__STATIC_INLINE void rtc_ovf_event_safe_check(void) -{ - core_util_critical_section_enter(); - - rtc_ovf_event_check(); - - core_util_critical_section_exit(); -} - - uint32_t common_rtc_32bit_ticks_get(void) { - uint32_t ticks; - uint32_t prev_overflows; - - do { - prev_overflows = m_common_rtc_overflows; - - ticks = nrf_rtc_counter_get(COMMON_RTC_INSTANCE); - // The counter used for time measurements is less than 32 bit wide, - // so its value is complemented with the number of registered overflows - // of the counter. - ticks += (m_common_rtc_overflows << RTC_COUNTER_BITS); - - // Check in case that OVF occurred during execution of a RTC handler (apply if call was from RTC handler) - // m_common_rtc_overflows might been updated in this call. - rtc_ovf_event_safe_check(); - - // If call was made from a low priority level m_common_rtc_overflows might have been updated in RTC handler. - } while (m_common_rtc_overflows != prev_overflows); - + uint32_t ticks = nrf_rtc_counter_get(COMMON_RTC_INSTANCE); + // The counter used for time measurements is less than 32 bit wide, + // so its value is complemented with the number of registered overflows + // of the counter. + ticks += (m_common_rtc_overflows << RTC_COUNTER_BITS); return ticks; } @@ -237,8 +185,6 @@ void common_rtc_set_interrupt(uint32_t us_timestamp, uint32_t cc_channel, uint32_t compare_value = (uint32_t)CEIL_DIV((timestamp64) * RTC_INPUT_FREQ, 1000000); - - core_util_critical_section_enter(); // The COMPARE event occurs when the value in compare register is N and // the counter value changes from N-1 to N. Therefore, the minimal safe // difference between the compare value to be set and the current counter @@ -251,8 +197,6 @@ void common_rtc_set_interrupt(uint32_t us_timestamp, uint32_t cc_channel, nrf_rtc_cc_set(COMMON_RTC_INSTANCE, cc_channel, RTC_WRAP(compare_value)); nrf_rtc_event_enable(COMMON_RTC_INSTANCE, int_mask); - - core_util_critical_section_exit(); } //------------------------------------------------------------------------------ @@ -311,9 +255,7 @@ static uint32_t previous_tick_cc_value = 0; */ MBED_WEAK uint32_t const os_trv; MBED_WEAK uint32_t const os_clockrate; -MBED_WEAK void OS_Tick_Handler(void) -{ -} +MBED_WEAK void OS_Tick_Handler() { } #if defined (__CC_ARM) /* ARMCC Compiler */ @@ -454,8 +396,7 @@ __stackless __task void COMMON_RTC_IRQ_HANDLER(void) * Return the next number of clock cycle needed for the next tick. * @note This function has been carrefuly optimized for a systick occuring every 1000us. */ -static uint32_t get_next_tick_cc_delta() -{ +static uint32_t get_next_tick_cc_delta() { uint32_t delta = 0; if (os_clockrate != 1000) { @@ -491,8 +432,7 @@ static uint32_t get_next_tick_cc_delta() return delta; } -static inline void clear_tick_interrupt() -{ +static inline void clear_tick_interrupt() { nrf_rtc_event_clear(COMMON_RTC_INSTANCE, OS_TICK_EVENT); nrf_rtc_event_disable(COMMON_RTC_INSTANCE, OS_TICK_INT_MASK); } @@ -504,8 +444,7 @@ static inline void clear_tick_interrupt() * @param val value to check * @return true if the value is included in the range and false otherwise. */ -static inline bool is_in_wrapped_range(uint32_t begin, uint32_t end, uint32_t val) -{ +static inline bool is_in_wrapped_range(uint32_t begin, uint32_t end, uint32_t val) { // regular case, begin < end // return true if begin <= val < end if (begin < end) { @@ -529,8 +468,7 @@ static inline bool is_in_wrapped_range(uint32_t begin, uint32_t end, uint32_t va /** * Register the next tick. */ -static void register_next_tick() -{ +static void register_next_tick() { previous_tick_cc_value = nrf_rtc_cc_get(COMMON_RTC_INSTANCE, OS_TICK_CC_CHANNEL); uint32_t delta = get_next_tick_cc_delta(); uint32_t new_compare_value = (previous_tick_cc_value + delta) & MAX_RTC_COUNTER_VAL; @@ -589,9 +527,8 @@ void os_tick_irqack(void) * @note This function is exposed by RTX kernel. * @return 1 if the timer has overflowed and 0 otherwise. */ -uint32_t os_tick_ovf(void) -{ - uint32_t current_counter = nrf_rtc_counter_get(COMMON_RTC_INSTANCE); +uint32_t os_tick_ovf(void) { + uint32_t current_counter = nrf_rtc_counter_get(COMMON_RTC_INSTANCE); uint32_t next_tick_cc_value = nrf_rtc_cc_get(COMMON_RTC_INSTANCE, OS_TICK_CC_CHANNEL); return is_in_wrapped_range(previous_tick_cc_value, next_tick_cc_value, current_counter) ? 0 : 1; @@ -606,9 +543,8 @@ uint32_t os_tick_ovf(void) * descending order, even if the internal counter used is an ascending one. * @return the value of the alternative hardware timer. */ -uint32_t os_tick_val(void) -{ - uint32_t current_counter = nrf_rtc_counter_get(COMMON_RTC_INSTANCE); +uint32_t os_tick_val(void) { + uint32_t current_counter = nrf_rtc_counter_get(COMMON_RTC_INSTANCE); uint32_t next_tick_cc_value = nrf_rtc_cc_get(COMMON_RTC_INSTANCE, OS_TICK_CC_CHANNEL); // do not use os_tick_ovf because its counter value can be different diff --git a/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/LF_Clock_config.md b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/LF_Clock_config.md new file mode 100644 index 00000000000..22852ae261a --- /dev/null +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/LF_Clock_config.md @@ -0,0 +1,97 @@ + +# LF Clock configuration using mbed configuration system + +In order to provide the configuration for a low frequency (LF) clock, add a description of the LF clock inside a mbed configuration JSON file. +For example at application level the description might be added in a mbed_app.json file and on target level the description might be added in the hal/target.json file. +LF clock source configuration is used for MCU startup initialization and the BLE SoftDevice LF clock configuration (if BLE libraries is used). Advanced configurations are used only for the BLE SoftDevice LF clock configuration. + + +## Usage: + +1. Clock source + +Default clock source is XTAL oscillator. It is defined at the target level configuration as the target.lf_clock_src key. +There are three options that can be configured as the clock source: + - NRF_LF_SRC_XTAL + - NRF_LF_SRC_RC + - NRF_LF_SRC_SYNTH + +In order to override this configuration use targed_override section in configuration file (e.g mbed_app.json) + +```json +{ + "target_overrides": { + "*": { + "target.lf_clock_src": "NRF_LF_SRC_XTAL" + } + } +} +``` + +2a. Advanced configuration of the LFCLK RC oscillator: + +```json +{ + "config": { + "lf_clock_rc_calib_timer_interval": { + "value": 16, + "macro_name": "MBED_CONF_NORDIC_NRF_LF_CLOCK_CALIB_TIMER_INTERVAL" + }, + "lf_clock_rc_calib_mode_config": { + "value": 1, + "macro_name": "MBED_CONF_NORDIC_NRF_LF_CLOCK_CALIB_MODE_CONFIG" + } + } +} + +``` + +"lf_clock_rc_calib_timer_interval" - Calibration timer interval in 250 ms. It is equivalent to nrf_clock_lf_cfg_t::rc_ctiv. +This item generates macro MBED_CONF_NORDIC_NRF_LF_CLOCK_CALIB_TIMER_INTERVAL. +By default, such configuration is set to 16. + +"lf_clock_rc_calib_mode_config" - This value configures how often the RC oscillator will be calibrated, in number of calibration intervals. +It is equivalent to nrf_clock_lf_cfg_t::rc_temp_ctiv. +For further information, see the documentation for the [API of a SoftDevice 13x version 2.0.0](http://infocenter.nordicsemi.com/topic/com.nordic.infocenter.s132.api.v2.0.0/structnrf__clock__lf__cfg__t.html) +This item generates macro MBED_CONF_NORDIC_NRF_LF_CLOCK_CALIB_MODE_CONFIG. +By default, such configuration is set to 1. + +2b. Advanced configuration of the LFCLK XTAL oscillator: + +Accuracy of the clock source can be set. In order to do so macro MBED_CONF_NORDIC_LF_CLOCK_XTAL_ACCURACY should been provided (e.g. in mbed_app.json). +By default such configuration is set to NRF_CLOCK_LF_XTAL_ACCURACY_20_PPM. +For further information, see the documentation for the [API of a SoftDevice 13x version 2.0.0](https://infocenter.nordicsemi.com/index.jsp?topic=%2Fcom.nordic.infocenter.s132.api.v2.0.0%2Fgroup___n_r_f___s_d_m___d_e_f_i_n_e_s.html) + +```json +{ + "config": { + "lf_clock_xtal_accuracy": { + "value": "NRF_CLOCK_LF_XTAL_ACCURACY_250_PPM", + "macro_name": "MBED_CONF_NORDIC_LF_CLOCK_XTAL_ACCURACY" + } + } +} + +``` + + + +2c. Advance configuration of the LFCLK Synthesized from HFCLK: + +Accuracy of the clock source can be set. In order to do so macro MBED_CONF_NORDIC_LF_CLOCK_SYNTH_ACCURACY should been provided (e.g. in mbed_app.json). +By default, such configuration is set to NRF_CLOCK_LF_XTAL_ACCURACY_20_PPM. +For further information, see the documentation for the [API of a SoftDevice 13x version 2.0.0](https://infocenter.nordicsemi.com/index.jsp?topic=%2Fcom.nordic.infocenter.s132.api.v2.0.0%2Fgroup___n_r_f___s_d_m___d_e_f_i_n_e_s.html) + +```json +{ + "config": { + "lf_clock_synth_accuracy": { + "value": "NRF_CLOCK_LF_SYNTH_ACCURACY_250_PPM", + "macro_name": "MBED_CONF_NORDIC_LF_CLOCK_XTAL_ACCURACY" + } + } +} + +``` + + diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/PeripheralNames.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/PeripheralNames.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/PeripheralNames.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/PeripheralNames.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/PortNames.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/PortNames.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/PortNames.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/PortNames.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/TARGET_NRF52840_DK/PinNames.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/TARGET_NRF52840_DK/PinNames.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/TARGET_NRF52840_DK/PinNames.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/TARGET_NRF52840_DK/PinNames.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/TARGET_NRF52840_DK/device.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/TARGET_NRF52840_DK/device.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/TARGET_NRF52840_DK/device.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/TARGET_NRF52840_DK/device.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/device/TOOLCHAIN_ARM_STD/nRF52832.sct b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/device/TOOLCHAIN_ARM_STD/nRF52832.sct similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/device/TOOLCHAIN_ARM_STD/nRF52832.sct rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/device/TOOLCHAIN_ARM_STD/nRF52832.sct diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/device/TOOLCHAIN_ARM_STD/startup_nrf52832.s b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/device/TOOLCHAIN_ARM_STD/startup_nrf52832.s similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/device/TOOLCHAIN_ARM_STD/startup_nrf52832.s rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/device/TOOLCHAIN_ARM_STD/startup_nrf52832.s diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/device/TOOLCHAIN_ARM_STD/sys.cpp b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/device/TOOLCHAIN_ARM_STD/sys.cpp similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/device/TOOLCHAIN_ARM_STD/sys.cpp rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/device/TOOLCHAIN_ARM_STD/sys.cpp diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/device/TOOLCHAIN_GCC_ARM/NRF52840.ld b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/device/TOOLCHAIN_GCC_ARM/NRF52840.ld similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/device/TOOLCHAIN_GCC_ARM/NRF52840.ld rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/device/TOOLCHAIN_GCC_ARM/NRF52840.ld diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/device/TOOLCHAIN_GCC_ARM/startup_NRF52832.S b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/device/TOOLCHAIN_GCC_ARM/startup_NRF52832.S similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/device/TOOLCHAIN_GCC_ARM/startup_NRF52832.S rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/device/TOOLCHAIN_GCC_ARM/startup_NRF52832.S diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/device/TOOLCHAIN_IAR/nRF52832.icf b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/device/TOOLCHAIN_IAR/nRF52832.icf similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/device/TOOLCHAIN_IAR/nRF52832.icf rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/device/TOOLCHAIN_IAR/nRF52832.icf diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/device/TOOLCHAIN_IAR/startup_NRF52832_IAR.s b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/device/TOOLCHAIN_IAR/startup_NRF52832_IAR.s similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/device/TOOLCHAIN_IAR/startup_NRF52832_IAR.s rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/device/TOOLCHAIN_IAR/startup_NRF52832_IAR.s diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/device/cmsis.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/device/cmsis.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/device/cmsis.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/device/cmsis.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/device/cmsis_nvic.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/device/cmsis_nvic.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/device/cmsis_nvic.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/device/cmsis_nvic.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/device/cmsis_nvic.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/device/cmsis_nvic.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/device/cmsis_nvic.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/device/cmsis_nvic.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/device/system_nrf52840.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/device/system_nrf52840.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/device/system_nrf52840.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/device/system_nrf52840.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/device/system_nrf52840.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/device/system_nrf52840.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/device/system_nrf52840.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/device/system_nrf52840.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/sdk/sdk_config.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/sdk/sdk_config.h similarity index 99% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/sdk/sdk_config.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/sdk/sdk_config.h index e456c12d4c2..25ecf907d92 100644 --- a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/sdk/sdk_config.h +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/sdk/sdk_config.h @@ -2883,7 +2883,7 @@ // APP_TIMER_ENABLED - app_timer - Application timer functionality //========================================================== #ifndef APP_TIMER_ENABLED -#define APP_TIMER_ENABLED 0 +#define APP_TIMER_ENABLED 1 #endif #if APP_TIMER_ENABLED // APP_TIMER_WITH_PROFILER - Enable app_timer profiling diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf_ble.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/ble.h similarity index 99% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf_ble.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/ble.h index 60b18442bc4..86d4d9adffc 100644 --- a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf_ble.h +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/ble.h @@ -49,13 +49,13 @@ #ifndef BLE_H__ #define BLE_H__ -#include "nrf_ble_ranges.h" -#include "nrf_ble_types.h" -#include "nrf_ble_gap.h" -#include "nrf_ble_l2cap.h" -#include "nrf_ble_gatt.h" -#include "nrf_ble_gattc.h" -#include "nrf_ble_gatts.h" +#include "ble_ranges.h" +#include "ble_types.h" +#include "ble_gap.h" +#include "ble_l2cap.h" +#include "ble_gatt.h" +#include "ble_gattc.h" +#include "ble_gatts.h" #ifdef __cplusplus extern "C" { diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf_ble_err.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/ble_err.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf_ble_err.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/ble_err.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf_ble_gap.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/ble_gap.h similarity index 99% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf_ble_gap.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/ble_gap.h index 8f651e21dd8..7748702e822 100644 --- a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf_ble_gap.h +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/ble_gap.h @@ -45,8 +45,8 @@ #ifndef BLE_GAP_H__ #define BLE_GAP_H__ -#include "nrf_ble_types.h" -#include "nrf_ble_ranges.h" +#include "ble_types.h" +#include "ble_ranges.h" #include "nrf_svc.h" #ifdef __cplusplus diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf_ble_gatt.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/ble_gatt.h similarity index 99% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf_ble_gatt.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/ble_gatt.h index ceafee8a460..cfa3860b5fa 100644 --- a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf_ble_gatt.h +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/ble_gatt.h @@ -45,8 +45,8 @@ #ifndef BLE_GATT_H__ #define BLE_GATT_H__ -#include "nrf_ble_types.h" -#include "nrf_ble_ranges.h" +#include "ble_types.h" +#include "ble_ranges.h" #ifdef __cplusplus extern "C" { diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf_ble_gattc.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/ble_gattc.h similarity index 99% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf_ble_gattc.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/ble_gattc.h index eb1f7753d76..c36a4d7e348 100644 --- a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf_ble_gattc.h +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/ble_gattc.h @@ -45,9 +45,9 @@ #ifndef BLE_GATTC_H__ #define BLE_GATTC_H__ -#include "nrf_ble_gatt.h" -#include "nrf_ble_types.h" -#include "nrf_ble_ranges.h" +#include "ble_gatt.h" +#include "ble_types.h" +#include "ble_ranges.h" #include "nrf_svc.h" #include "nrf_error.h" #include "nrf.h" diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf_ble_gatts.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/ble_gatts.h similarity index 99% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf_ble_gatts.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/ble_gatts.h index 588edcc0029..b85735ec31c 100644 --- a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf_ble_gatts.h +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/ble_gatts.h @@ -45,11 +45,11 @@ #ifndef BLE_GATTS_H__ #define BLE_GATTS_H__ -#include "nrf_ble_types.h" -#include "nrf_ble_ranges.h" -#include "nrf_ble_l2cap.h" -#include "nrf_ble_gap.h" -#include "nrf_ble_gatt.h" +#include "ble_types.h" +#include "ble_ranges.h" +#include "ble_l2cap.h" +#include "ble_gap.h" +#include "ble_gatt.h" #include "nrf_svc.h" #ifdef __cplusplus diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf_ble_hci.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/ble_hci.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf_ble_hci.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/ble_hci.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf_ble_l2cap.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/ble_l2cap.h similarity index 98% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf_ble_l2cap.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/ble_l2cap.h index d3cc747b100..eaad7e50fc9 100644 --- a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf_ble_l2cap.h +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/ble_l2cap.h @@ -45,9 +45,9 @@ #ifndef BLE_L2CAP_H__ #define BLE_L2CAP_H__ -#include "nrf_ble_types.h" -#include "nrf_ble_ranges.h" -#include "nrf_ble_err.h" +#include "ble_types.h" +#include "ble_ranges.h" +#include "ble_err.h" #include "nrf_svc.h" #ifdef __cplusplus diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf_ble_ranges.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/ble_ranges.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf_ble_ranges.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/ble_ranges.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf_ble_types.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/ble_types.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf_ble_types.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/ble_types.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf52/nrf_mbr.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf52/nrf_mbr.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf52/nrf_mbr.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf52/nrf_mbr.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf_error.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf_error.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf_error.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf_error.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf_error_sdm.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf_error_sdm.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf_error_sdm.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf_error_sdm.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf_error_soc.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf_error_soc.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf_error_soc.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf_error_soc.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf_nvic.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf_nvic.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf_nvic.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf_nvic.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf_sd_def.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf_sd_def.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf_sd_def.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf_sd_def.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf_sdm.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf_sdm.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf_sdm.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf_sdm.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf_soc.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf_soc.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf_soc.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf_soc.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf_svc.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf_svc.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf_svc.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/sdk/softdevice/s140/headers/nrf_svc.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/sdk/softdevice/s140/hex/s140_nrf52840_5.0.0-1.alpha_softdevice.hex b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/sdk/softdevice/s140/hex/s140_nrf52840_5.0.0-1.alpha_softdevice.hex similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_MCU_NRF52840/sdk/softdevice/s140/hex/s140_nrf52840_5.0.0-1.alpha_softdevice.hex rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/TARGET_MCU_NRF52840/sdk/softdevice/s140/hex/s140_nrf52840_5.0.0-1.alpha_softdevice.hex diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/analogin_api.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/analogin_api.c similarity index 96% rename from targets/TARGET_NORDIC/TARGET_NRF5/analogin_api.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/analogin_api.c index 8dec19a34bf..dcc0f44f0dd 100644 --- a/targets/TARGET_NORDIC/TARGET_NRF5/analogin_api.c +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/analogin_api.c @@ -13,8 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -#ifndef TARGET_MCU_NRF51822 #include "mbed_assert.h" #include "analogin_api.h" @@ -28,9 +26,7 @@ #define ADC_12BIT_RANGE 0xFFF #define ADC_RANGE ADC_12BIT_RANGE -#ifdef TARGET_SDK13 __STATIC_INLINE nrf_saadc_input_t nrf_drv_saadc_gpio_to_ain(uint32_t pin); -#endif static void analog_in_event_handler(nrf_drv_saadc_evt_t const *p_event)// type of nrf_drv_saadc_event_handler_t @@ -95,7 +91,7 @@ float analogin_read(analogin_t *obj) return (float)value * (1.0f / (float)ADC_RANGE); } -#ifdef TARGET_SDK13 + /** * @brief Function for converting a GPIO pin number to an analog input pin number used in the channel * configuration. @@ -123,8 +119,5 @@ __STATIC_INLINE nrf_saadc_input_t nrf_drv_saadc_gpio_to_ain(uint32_t pin) return NRF_SAADC_INPUT_DISABLED; } } -#endif // TARGET_SDK13 #endif // DEVICE_ANALOGIN - -#endif // !TARGET_MCU_NRF51822 diff --git a/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/common_rtc.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/common_rtc.h new file mode 100644 index 00000000000..f15ff83a589 --- /dev/null +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/common_rtc.h @@ -0,0 +1,57 @@ +/* mbed Microcontroller Library + * Copyright (c) 2015 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * 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. + */ + +#ifndef COMMON_RTC_H +#define COMMON_RTC_H + +#include "nrf_rtc.h" + +#define RTC_COUNTER_BITS 24u + +// Instance 0 is reserved for SoftDevice. +// Instance 1 is used as a common one for us_ticker, lp_ticker and (in case +// of NRF51) as an alternative tick source for RTOS. +// ["us_ticker.c" uses hard coded addresses of the 'NRF_RTC1->EVENT_COMPARE[1]' +// register in inline assembly implementations of COMMON_RTC_IRQ_HANDLER, +// please remember to update those in case of doing changes here] +#define COMMON_RTC_INSTANCE NRF_RTC1 +#define COMMON_RTC_IRQ_HANDLER RTC1_IRQHandler +#define US_TICKER_CC_CHANNEL 0 +#define OS_TICK_CC_CHANNEL 1 +#define LP_TICKER_CC_CHANNEL 2 + +#define COMMON_RTC_EVENT_COMPARE(channel) \ + CONCAT_2(NRF_RTC_EVENT_COMPARE_, channel) +#define COMMON_RTC_INT_COMPARE_MASK(channel) \ + CONCAT_3(NRF_RTC_INT_COMPARE, channel, _MASK) + +#define US_TICKER_EVENT COMMON_RTC_EVENT_COMPARE(US_TICKER_CC_CHANNEL) +#define US_TICKER_INT_MASK COMMON_RTC_INT_COMPARE_MASK(US_TICKER_CC_CHANNEL) +#define OS_TICK_EVENT COMMON_RTC_EVENT_COMPARE(OS_TICK_CC_CHANNEL) +#define OS_TICK_INT_MASK COMMON_RTC_INT_COMPARE_MASK(OS_TICK_CC_CHANNEL) +#define LP_TICKER_EVENT COMMON_RTC_EVENT_COMPARE(LP_TICKER_CC_CHANNEL) +#define LP_TICKER_INT_MASK COMMON_RTC_INT_COMPARE_MASK(LP_TICKER_CC_CHANNEL) + +extern bool m_common_rtc_enabled; +extern uint32_t volatile m_common_rtc_overflows; + +void common_rtc_init(void); +uint32_t common_rtc_32bit_ticks_get(void); +uint64_t common_rtc_64bit_us_get(void); +void common_rtc_set_interrupt(uint32_t us_timestamp, uint32_t cc_channel, + uint32_t int_mask); + +#endif // COMMON_RTC_H diff --git a/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/gpio_api.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/gpio_api.c new file mode 100644 index 00000000000..4931b5330e8 --- /dev/null +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/gpio_api.c @@ -0,0 +1,283 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * 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. + */ +#include "mbed_assert.h" +#include "gpio_api.h" +#include "gpio_irq_api.h" +#include "pinmap.h" +#include "nrf_drv_gpiote.h" + +#if defined(TARGET_MCU_NRF51822) + #define GPIO_PIN_COUNT 31 +#elif defined(TARGET_MCU_NRF52832) + #define GPIO_PIN_COUNT 32 +#elif defined(TARGET_MCU_NRF52840) + #define GPIO_PIN_COUNT 48 +#else + #error not recognized gpio count for mcu +#endif + +typedef struct +{ + bool used_as_gpio : 1; + PinDirection direction : 1; + bool init_high : 1; + PinMode pull : 2; + bool used_as_irq : 1; + bool irq_fall : 1; + bool irq_rise : 1; +} gpio_cfg_t; + +#if GPIO_PIN_COUNT > 32 + typedef uint64_t gpio_mask_t; +#else + typedef uint32_t gpio_mask_t; +#endif + +static gpio_mask_t m_gpio_initialized; +static gpio_cfg_t m_gpio_cfg[GPIO_PIN_COUNT]; + + +/*********** + GPIO IRQ +***********/ + +static gpio_irq_handler m_irq_handler; +static uint32_t m_channel_ids[GPIO_PIN_COUNT] = {0}; +static gpio_mask_t m_gpio_irq_enabled; + + +static void gpiote_irq_handler(nrf_drv_gpiote_pin_t pin, nrf_gpiote_polarity_t action) +{ + nrf_gpio_pin_sense_t sense = nrf_gpio_pin_sense_get(pin); + gpio_irq_event event = (sense == NRF_GPIO_PIN_SENSE_LOW) ? IRQ_RISE : IRQ_FALL; + + if (m_gpio_irq_enabled & ((gpio_mask_t)1 << pin)) + { + if (((event == IRQ_RISE) && m_gpio_cfg[pin].irq_rise) + || ((event == IRQ_FALL) && m_gpio_cfg[pin].irq_fall)) + { + m_irq_handler(m_channel_ids[pin], event); + } + } +} + +void GPIOTE_IRQHandler(void);// exported from nrf_drv_gpiote.c + +void gpio_init(gpio_t *obj, PinName pin) +{ + obj->pin = pin; + if (pin == (PinName)NC) + { + return; + } + MBED_ASSERT((uint32_t)pin < GPIO_PIN_COUNT); + + NVIC_SetVector(GPIOTE_IRQn, (uint32_t) GPIOTE_IRQHandler); + + (void) nrf_drv_gpiote_init(); + + m_gpio_cfg[obj->pin].used_as_gpio = true; +} + + +int gpio_read(gpio_t *obj) +{ + MBED_ASSERT(obj->pin != (PinName)NC); + if (m_gpio_cfg[obj->pin].direction == PIN_OUTPUT) + { + return (nrf_gpio_pin_out_read(obj->pin) ? 1 : 0); + } + else + { + return nrf_gpio_pin_read(obj->pin); + } +} + +static void gpiote_pin_uninit(uint8_t pin) +{ + if (m_gpio_initialized & ((gpio_mask_t)1 << pin)) + { + if ((m_gpio_cfg[pin].direction == PIN_OUTPUT) && (!m_gpio_cfg[pin].used_as_irq)) + { + nrf_drv_gpiote_out_uninit(pin); + } + else + { + nrf_drv_gpiote_in_uninit(pin); + } + } +} + +static void gpio_apply_config(uint8_t pin) +{ + if (m_gpio_cfg[pin].used_as_gpio || m_gpio_cfg[pin].used_as_irq) + { + if ((m_gpio_cfg[pin].direction == PIN_INPUT) + || (m_gpio_cfg[pin].used_as_irq)) + { + //Configure as input. + nrf_drv_gpiote_in_config_t cfg; + + cfg.hi_accuracy = false; + cfg.is_watcher = false; + cfg.sense = NRF_GPIOTE_POLARITY_TOGGLE; + if (m_gpio_cfg[pin].used_as_irq) + { + cfg.pull = NRF_GPIO_PIN_PULLUP; + nrf_drv_gpiote_in_init(pin, &cfg, gpiote_irq_handler); + if ((m_gpio_irq_enabled & ((gpio_mask_t)1 << pin)) + && (m_gpio_cfg[pin].irq_rise || m_gpio_cfg[pin].irq_fall)) + { + nrf_drv_gpiote_in_event_enable(pin, true); + } + } + else + { + switch (m_gpio_cfg[pin].pull) + { + case PullUp: + cfg.pull = NRF_GPIO_PIN_PULLUP; + break; + case PullDown: + cfg.pull = NRF_GPIO_PIN_PULLDOWN; + break; + default: + cfg.pull = NRF_GPIO_PIN_NOPULL; + break; + } + nrf_drv_gpiote_in_init(pin, &cfg, NULL); + } + } + else + { + // Configure as output. + nrf_drv_gpiote_out_config_t cfg = GPIOTE_CONFIG_OUT_SIMPLE(m_gpio_cfg[pin].init_high); + nrf_drv_gpiote_out_init(pin, &cfg); + } + m_gpio_initialized |= ((gpio_mask_t)1 << pin); + } + else + { + m_gpio_initialized &= ~((gpio_mask_t)1 << pin); + } +} + + +void gpio_mode(gpio_t *obj, PinMode mode) +{ + MBED_ASSERT(obj->pin != (PinName)NC); + + gpiote_pin_uninit(obj->pin); // try to uninitialize gpio before a change. + + m_gpio_cfg[obj->pin].pull = mode; + gpio_apply_config(obj->pin); +} + + +void gpio_dir(gpio_t *obj, PinDirection direction) +{ + MBED_ASSERT(obj->pin != (PinName)NC); + + gpiote_pin_uninit(obj->pin); // try to uninitialize gpio before a change. + + m_gpio_cfg[obj->pin].direction = direction; + gpio_apply_config(obj->pin); +} + + +/*********** + GPIO IRQ +***********/ + +int gpio_irq_init(gpio_irq_t *obj, PinName pin, gpio_irq_handler handler, uint32_t id) +{ + if (pin == NC) + { + return -1; + } + MBED_ASSERT((uint32_t)pin < GPIO_PIN_COUNT); + (void) nrf_drv_gpiote_init(); + + gpiote_pin_uninit(pin); // try to uninitialize gpio before a change. + + m_gpio_cfg[pin].used_as_irq = true; + m_channel_ids[pin] = id; + obj->ch = pin; + m_irq_handler = handler; + m_channel_ids[pin] = id; + + gpio_apply_config(pin); + return 1; +} + + +void gpio_irq_free(gpio_irq_t *obj) +{ + nrf_drv_gpiote_in_uninit(obj->ch); + m_gpio_cfg[obj->ch].used_as_irq = false; + m_channel_ids[obj->ch] = 0; + + gpio_apply_config(obj->ch); +} + + +void gpio_irq_set(gpio_irq_t *obj, gpio_irq_event event, uint32_t enable) +{ + gpio_cfg_t* cfg = &m_gpio_cfg[obj->ch]; + bool irq_enabled_before = + (m_gpio_irq_enabled & ((gpio_mask_t)1 << obj->ch)) && + (cfg->irq_rise || cfg->irq_fall); + + if (event == IRQ_RISE) + { + cfg->irq_rise = enable ? true : false; + } + else if (event == IRQ_FALL) + { + cfg->irq_fall = enable ? true : false; + } + + bool irq_enabled_after = cfg->irq_rise || cfg->irq_fall; + + if (irq_enabled_before != irq_enabled_after) + { + if (irq_enabled_after) + { + gpio_irq_enable(obj); + } + else + { + gpio_irq_disable(obj); + } + } +} + + +void gpio_irq_enable(gpio_irq_t *obj) +{ + m_gpio_irq_enabled |= ((gpio_mask_t)1 << obj->ch); + if (m_gpio_cfg[obj->ch].irq_rise || m_gpio_cfg[obj->ch].irq_fall) + { + nrf_drv_gpiote_in_event_enable(obj->ch, true); + } +} + + +void gpio_irq_disable(gpio_irq_t *obj) +{ + m_gpio_irq_enabled &= ~((gpio_mask_t)1 << obj->ch); + nrf_drv_gpiote_in_event_disable(obj->ch); +} diff --git a/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/gpio_object.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/gpio_object.h new file mode 100644 index 00000000000..9a6db55284d --- /dev/null +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/gpio_object.h @@ -0,0 +1,54 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * 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. + */ +#ifndef MBED_GPIO_OBJECT_H +#define MBED_GPIO_OBJECT_H + +#include "mbed_assert.h" + +#include "nrf_gpio.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct +{ + PinName pin; +} gpio_t; + +static inline void gpio_write(gpio_t *obj, int value) +{ + MBED_ASSERT(obj->pin != (PinName)NC); + if (value) + { + nrf_gpio_pin_set(obj->pin); + } + else + { + nrf_gpio_pin_clear(obj->pin); + } +} + +static inline int gpio_is_connected(const gpio_t *obj) +{ + return obj->pin != (PinName)NC; +} + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/i2c_api.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/i2c_api.c new file mode 100644 index 00000000000..69a94770baf --- /dev/null +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/i2c_api.c @@ -0,0 +1,784 @@ +/* + * Copyright (c) 2017 Nordic Semiconductor ASA + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * 2. Redistributions in binary form, except as embedded into a Nordic Semiconductor ASA + * integrated circuit in a product or a software update for such product, must reproduce + * the above copyright notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of Nordic Semiconductor ASA nor the names of its contributors may be + * used to endorse or promote products derived from this software without specific prior + * written permission. + * + * 4. This software, with or without modification, must only be used with a + * Nordic Semiconductor ASA integrated circuit. + * + * 5. Any software provided in binary or object form under this license must not be reverse + * engineered, decompiled, modified and/or disassembled. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + + +#include "i2c_api.h" + +#if DEVICE_I2C + +#include "mbed_assert.h" +#include "mbed_error.h" +#include "nrf_twi.h" +#include "nrf_drv_common.h" +#include "sdk_config.h" +#include "app_util_platform.h" +#include "nrf_gpio.h" +#include "nrf_delay.h" + +// An arbitrary value used as the counter in loops waiting for given event +// (e.g. STOPPED), needed to avoid infinite loops (and not involve any timers +// or tickers). +#define TIMEOUT_VALUE 1000 + +#if DEVICE_I2C_ASYNCH + #define TWI_IDX(obj) ((obj)->i2c.twi_idx) +#else + #define TWI_IDX(obj) ((obj)->twi_idx) +#endif +#define TWI_INFO(obj) (&m_twi_info[TWI_IDX(obj)]) + +#define TWI0_INSTANCE_INDEX 0 +#define TWI1_INSTANCE_INDEX TWI0_INSTANCE_INDEX+TWI0_ENABLED + +typedef struct { + bool initialized; + uint32_t pselsda; + uint32_t pselscl; + nrf_twi_frequency_t frequency; + bool start_twi; + +#if DEVICE_I2C_ASYNCH + volatile bool active; + uint8_t const *tx; + size_t tx_length; + uint8_t *rx; + size_t rx_length; + bool stop; + + volatile uint32_t events; + void (*handler)(void); + uint32_t evt_mask; +#endif // DEVICE_I2C_ASYNCH +} twi_info_t; +static twi_info_t m_twi_info[TWI_COUNT]; + +static NRF_TWI_Type * const m_twi_instances[TWI_COUNT] = { +#if TWI0_ENABLED + NRF_TWI0, +#endif +#if TWI1_ENABLED + NRF_TWI1, +#endif +}; + +void SPI0_TWI0_IRQHandler(void); +void SPI1_TWI1_IRQHandler(void); + +static const peripheral_handler_desc_t twi_handlers[TWI_COUNT] = +{ +#if TWI0_ENABLED + { + SPI0_TWI0_IRQn, + (uint32_t) SPI0_TWI0_IRQHandler + }, +#endif +#if TWI1_ENABLED + { + SPI1_TWI1_IRQn, + (uint32_t) SPI1_TWI1_IRQHandler + } +#endif +}; +#ifdef NRF51 + #define TWI_IRQ_PRIORITY APP_IRQ_PRIORITY_LOW +#elif defined(NRF52) || defined(NRF52840_XXAA) + #define TWI_IRQ_PRIORITY APP_IRQ_PRIORITY_LOWEST +#endif + + +#if DEVICE_I2C_ASYNCH +static void start_asynch_rx(twi_info_t *twi_info, NRF_TWI_Type *twi) +{ + if (twi_info->rx_length == 1 && twi_info->stop) + { + nrf_twi_shorts_set(twi, NRF_TWI_SHORT_BB_STOP_MASK); + } + else + { + nrf_twi_shorts_set(twi, NRF_TWI_SHORT_BB_SUSPEND_MASK); + } + nrf_twi_task_trigger(twi, NRF_TWI_TASK_STARTRX); +} + +static void twi_irq_handler(uint8_t instance_idx) +{ + twi_info_t *twi_info = &m_twi_info[instance_idx]; + + NRF_TWI_Type *twi = m_twi_instances[instance_idx]; + if (nrf_twi_event_check(twi, NRF_TWI_EVENT_ERROR)) + { + nrf_twi_event_clear(twi, NRF_TWI_EVENT_ERROR); + + // In case of an error, force STOP. + // The current transfer may be suspended (if it is RX), so it must be + // resumed before the STOP task is triggered. + nrf_twi_task_trigger(twi, NRF_TWI_TASK_RESUME); + nrf_twi_task_trigger(twi, NRF_TWI_TASK_STOP); + + uint32_t errorsrc = nrf_twi_errorsrc_get_and_clear(twi); + twi_info->events |= I2C_EVENT_ERROR; + if (errorsrc & NRF_TWI_ERROR_ADDRESS_NACK) + { + twi_info->events |= I2C_EVENT_ERROR_NO_SLAVE; + } + if (errorsrc & NRF_TWI_ERROR_DATA_NACK) + { + twi_info->events |= I2C_EVENT_TRANSFER_EARLY_NACK; + } + } + + bool finished = false; + + if (nrf_twi_event_check(twi, NRF_TWI_EVENT_TXDSENT)) + { + nrf_twi_event_clear(twi, NRF_TWI_EVENT_TXDSENT); + + MBED_ASSERT(twi_info->tx_length > 0); + --(twi_info->tx_length); + // Send next byte if there is still something to be sent. + if (twi_info->tx_length > 0) + { + nrf_twi_txd_set(twi, *(twi_info->tx)); + ++(twi_info->tx); + // It TX is done, start RX if requested. + } + else if (twi_info->rx_length > 0) + { + start_asynch_rx(twi_info, twi); + // If there is nothing more to do, finalize the transfer. + } + else + { + if (twi_info->stop) + { + nrf_twi_task_trigger(twi, NRF_TWI_TASK_STOP); + } + else + { + nrf_twi_task_trigger(twi, NRF_TWI_TASK_SUSPEND); + finished = true; + } + twi_info->events |= I2C_EVENT_TRANSFER_COMPLETE; + } + } + + if (nrf_twi_event_check(twi, NRF_TWI_EVENT_RXDREADY)) + { + nrf_twi_event_clear(twi, NRF_TWI_EVENT_RXDREADY); + + MBED_ASSERT(twi_info->rx_length > 0); + *(twi_info->rx) = nrf_twi_rxd_get(twi); + ++(twi_info->rx); + --(twi_info->rx_length); + + if (twi_info->rx_length > 0) + { + // If more bytes should be received, resume the transfer + // (in case the stop condition should be generated after the next + // byte, change the shortcuts configuration first). + if (twi_info->rx_length == 1 && twi_info->stop) + { + nrf_twi_shorts_set(twi, NRF_TWI_SHORT_BB_STOP_MASK); + } + nrf_twi_task_trigger(twi, NRF_TWI_TASK_RESUME); + } + else + { + // If all requested bytes were received, finalize the transfer. + finished = true; + twi_info->events |= I2C_EVENT_TRANSFER_COMPLETE; + } + } + + if (finished || + nrf_twi_event_check(twi, NRF_TWI_EVENT_STOPPED) || + (nrf_twi_int_enable_check(twi, NRF_TWI_INT_SUSPENDED_MASK) && + nrf_twi_event_check(twi, NRF_TWI_EVENT_SUSPENDED))) + { + // There is no need to clear the STOPPED and SUSPENDED events here, + // they will no longer generate the interrupt - see below. + + nrf_twi_shorts_set(twi, 0); + // Disable all interrupt sources. + nrf_twi_int_disable(twi, UINT32_MAX); + twi_info->active = false; + + if (twi_info->handler) + { + twi_info->handler(); + } + } +} + +#if TWI0_ENABLED +static void irq_handler_twi0(void) +{ + twi_irq_handler(TWI0_INSTANCE_INDEX); +} +#endif +#if TWI1_ENABLED +static void irq_handler_twi1(void) +{ + twi_irq_handler(TWI1_INSTANCE_INDEX); +} +#endif +static nrf_drv_irq_handler_t const m_twi_irq_handlers[TWI_COUNT] = +{ +#if TWI0_ENABLED + irq_handler_twi0, +#endif +#if TWI1_ENABLED + irq_handler_twi1, +#endif +}; +#endif // DEVICE_I2C_ASYNCH + + +static void configure_twi_pin(uint32_t pin, nrf_gpio_pin_dir_t dir) +{ + nrf_gpio_cfg(pin, + dir, + NRF_GPIO_PIN_INPUT_CONNECT, + NRF_GPIO_PIN_PULLUP, + NRF_GPIO_PIN_S0D1, + NRF_GPIO_PIN_NOSENSE); +} + +static void twi_clear_bus(twi_info_t *twi_info) +{ + // Try to set SDA high, and check if no slave tries to drive it low. + nrf_gpio_pin_set(twi_info->pselsda); + configure_twi_pin(twi_info->pselsda, NRF_GPIO_PIN_DIR_OUTPUT); + // In case SDA is low, make up to 9 cycles on SCL line to help the slave + // that pulls SDA low release it. + if (!nrf_gpio_pin_read(twi_info->pselsda)) + { + nrf_gpio_pin_set(twi_info->pselscl); + configure_twi_pin(twi_info->pselscl, NRF_GPIO_PIN_DIR_OUTPUT); + nrf_delay_us(4); + + for (int i = 0; i < 9; i++) + { + if (nrf_gpio_pin_read(twi_info->pselsda)) + { + break; + } + nrf_gpio_pin_clear(twi_info->pselscl); + nrf_delay_us(4); + nrf_gpio_pin_set(twi_info->pselscl); + nrf_delay_us(4); + } + + // Finally, generate STOP condition to put the bus into initial state. + nrf_gpio_pin_clear(twi_info->pselsda); + nrf_delay_us(4); + nrf_gpio_pin_set(twi_info->pselsda); + } +} + +void i2c_init(i2c_t *obj, PinName sda, PinName scl) +{ + int i; + + for (i = 0; i < TWI_COUNT; ++i) + { + if (m_twi_info[i].initialized && + m_twi_info[i].pselsda == (uint32_t)sda && + m_twi_info[i].pselscl == (uint32_t)scl) + { + TWI_IDX(obj) = i; + TWI_INFO(obj)->frequency = NRF_TWI_FREQ_100K; + i2c_reset(obj); + return; + } + } + + for (i = 0; i < TWI_COUNT; ++i) + { + if (!m_twi_info[i].initialized) + { + TWI_IDX(obj) = i; + + twi_info_t *twi_info = TWI_INFO(obj); + twi_info->initialized = true; + twi_info->pselsda = (uint32_t)sda; + twi_info->pselscl = (uint32_t)scl; + twi_info->frequency = NRF_TWI_FREQ_100K; + twi_info->start_twi = false; +#if DEVICE_I2C_ASYNCH + twi_info->active = false; +#endif + + twi_clear_bus(twi_info); + + configure_twi_pin(twi_info->pselsda, NRF_GPIO_PIN_DIR_INPUT); + configure_twi_pin(twi_info->pselscl, NRF_GPIO_PIN_DIR_INPUT); + + i2c_reset(obj); + +#if DEVICE_I2C_ASYNCH + nrf_drv_common_per_res_acquire(m_twi_instances[i], + m_twi_irq_handlers[i]); + NVIC_SetVector(twi_handlers[i].IRQn, twi_handlers[i].vector); + nrf_drv_common_irq_enable(twi_handlers[i].IRQn, TWI_IRQ_PRIORITY); +#endif + + return; + } + } + + error("No available I2C peripheral\r\n"); +} + +void i2c_reset(i2c_t *obj) +{ + twi_info_t *twi_info = TWI_INFO(obj); + NRF_TWI_Type *twi = m_twi_instances[TWI_IDX(obj)]; + + nrf_twi_disable(twi); + nrf_twi_pins_set(twi, twi_info->pselscl, twi_info->pselsda); + nrf_twi_frequency_set(twi, twi_info->frequency); + nrf_twi_enable(twi); +} + +int i2c_start(i2c_t *obj) +{ + twi_info_t *twi_info = TWI_INFO(obj); +#if DEVICE_I2C_ASYNCH + if (twi_info->active) + { + return I2C_ERROR_BUS_BUSY; + } +#endif + twi_info->start_twi = true; + + return 0; +} + +int i2c_stop(i2c_t *obj) +{ + NRF_TWI_Type *twi = m_twi_instances[TWI_IDX(obj)]; + + // The current transfer may be suspended (if it is RX), so it must be + // resumed before the STOP task is triggered. + nrf_twi_task_trigger(twi, NRF_TWI_TASK_RESUME); + nrf_twi_task_trigger(twi, NRF_TWI_TASK_STOP); + uint32_t remaining_time = TIMEOUT_VALUE; + + do + { + if (nrf_twi_event_check(twi, NRF_TWI_EVENT_STOPPED)) + { + return 0; + } + } + while (--remaining_time); + + return 1; +} + +void i2c_frequency(i2c_t *obj, int hz) +{ + twi_info_t *twi_info = TWI_INFO(obj); + NRF_TWI_Type *twi = m_twi_instances[TWI_IDX(obj)]; + + if (hz < 250000) + { + twi_info->frequency = NRF_TWI_FREQ_100K; + } + else if (hz < 400000) + { + twi_info->frequency = NRF_TWI_FREQ_250K; + } + else + { + twi_info->frequency = NRF_TWI_FREQ_400K; + } + nrf_twi_frequency_set(twi, twi_info->frequency); +} + +static uint8_t twi_address(int i2c_address) +{ + // The TWI peripheral requires 7-bit slave address (without R/W bit). + return (i2c_address >> 1); +} + +static void start_twi_read(NRF_TWI_Type *twi, int address) +{ + nrf_twi_event_clear(twi, NRF_TWI_EVENT_STOPPED); + nrf_twi_event_clear(twi, NRF_TWI_EVENT_RXDREADY); + nrf_twi_event_clear(twi, NRF_TWI_EVENT_ERROR); + (void)nrf_twi_errorsrc_get_and_clear(twi); + + nrf_twi_shorts_set(twi, NRF_TWI_SHORT_BB_SUSPEND_MASK); + + nrf_twi_address_set(twi, twi_address(address)); + nrf_twi_task_trigger(twi, NRF_TWI_TASK_RESUME); + nrf_twi_task_trigger(twi, NRF_TWI_TASK_STARTRX); +} + +int i2c_read(i2c_t *obj, int address, char *data, int length, int stop) +{ + // Zero-length RX transfers are not supported. Such transfers cannot + // be easily achieved with TWI peripheral (some dirty tricks would be + // required for this), and they are actually useless (TX can be used + // to check if the address is acknowledged by a slave). + MBED_ASSERT(length > 0); + + twi_info_t *twi_info = TWI_INFO(obj); +#if DEVICE_I2C_ASYNCH + if (twi_info->active) + { + return I2C_ERROR_BUS_BUSY; + } +#endif + twi_info->start_twi = false; + + NRF_TWI_Type *twi = m_twi_instances[TWI_IDX(obj)]; + start_twi_read(twi, address); + + int result = length; + + while (length > 0) + { + int byte_read_result = i2c_byte_read(obj, (stop && length == 1)); + if (byte_read_result < 0) + { + // When an error occurs, return the number of bytes that have been + // received successfully. + result -= length; + // Force STOP condition. + stop = 1; + break; + } + *data++ = (uint8_t)byte_read_result; + --length; + } + + if (stop) + { + (void)i2c_stop(obj); + } + + return result; +} + +static uint8_t twi_byte_write(NRF_TWI_Type *twi, uint8_t data) +{ + nrf_twi_event_clear(twi, NRF_TWI_EVENT_TXDSENT); + nrf_twi_event_clear(twi, NRF_TWI_EVENT_ERROR); + + nrf_twi_txd_set(twi, data); + uint32_t remaining_time = TIMEOUT_VALUE; + + do + { + if (nrf_twi_event_check(twi, NRF_TWI_EVENT_TXDSENT)) + { + nrf_twi_event_clear(twi, NRF_TWI_EVENT_TXDSENT); + return 1; // ACK received + } + if (nrf_twi_event_check(twi, NRF_TWI_EVENT_ERROR)) + { + nrf_twi_event_clear(twi, NRF_TWI_EVENT_ERROR); + return 0; // some error occurred + } + } + while (--remaining_time); + + return 2; // timeout; +} + +static void start_twi_write(NRF_TWI_Type *twi, int address) +{ + nrf_twi_event_clear(twi, NRF_TWI_EVENT_STOPPED); + nrf_twi_event_clear(twi, NRF_TWI_EVENT_TXDSENT); + nrf_twi_event_clear(twi, NRF_TWI_EVENT_ERROR); + (void)nrf_twi_errorsrc_get_and_clear(twi); + + nrf_twi_shorts_set(twi, 0); + + nrf_twi_address_set(twi, twi_address(address)); + nrf_twi_task_trigger(twi, NRF_TWI_TASK_RESUME); + nrf_twi_task_trigger(twi, NRF_TWI_TASK_STARTTX); +} + +int i2c_write(i2c_t *obj, int address, const char *data, int length, int stop) +{ + twi_info_t *twi_info = TWI_INFO(obj); +#if DEVICE_I2C_ASYNCH + if (twi_info->active) + { + return I2C_ERROR_BUS_BUSY; + } +#endif + twi_info->start_twi = false; + + NRF_TWI_Type *twi = m_twi_instances[TWI_IDX(obj)]; + start_twi_write(twi, address); + + // Special case - transaction with no data. + // It can be used to check if a slave acknowledges the address. + if (length == 0) + { + nrf_twi_event_t event; + if (stop) + { + event = NRF_TWI_EVENT_STOPPED; + nrf_twi_task_trigger(twi, NRF_TWI_TASK_STOP); + } + else + { + event = NRF_TWI_EVENT_SUSPENDED; + nrf_twi_event_clear(twi, event); + nrf_twi_task_trigger(twi, NRF_TWI_TASK_SUSPEND); + } + uint32_t remaining_time = TIMEOUT_VALUE; + + do + { + if (nrf_twi_event_check(twi, event)) + { + break; + } + } + while (--remaining_time); + + uint32_t errorsrc = nrf_twi_errorsrc_get_and_clear(twi); + if (errorsrc & NRF_TWI_ERROR_ADDRESS_NACK) + { + if (!stop) + { + i2c_stop(obj); + } + return I2C_ERROR_NO_SLAVE; + } + + return (remaining_time ? 0 : I2C_ERROR_BUS_BUSY); + } + + int result = length; + + do + { + uint8_t byte_write_result = twi_byte_write(twi, (uint8_t)*data++); + if (byte_write_result != 1) + { + if (byte_write_result == 0) + { + // Check what kind of error has been signaled by TWI. + uint32_t errorsrc = nrf_twi_errorsrc_get_and_clear(twi); + if (errorsrc & NRF_TWI_ERROR_ADDRESS_NACK) + { + result = I2C_ERROR_NO_SLAVE; + } + else + { + // Some other error - return the number of bytes that + // have been sent successfully. + result -= length; + } + } + else + { + result = I2C_ERROR_BUS_BUSY; + } + // Force STOP condition. + stop = 1; + break; + } + --length; + } + while (length > 0); + + if (stop) + { + (void)i2c_stop(obj); + } + + return result; +} + +int i2c_byte_read(i2c_t *obj, int last) +{ + NRF_TWI_Type *twi = m_twi_instances[TWI_IDX(obj)]; + + if (last) + { + nrf_twi_shorts_set(twi, NRF_TWI_SHORT_BB_STOP_MASK); + } + nrf_twi_task_trigger(twi, NRF_TWI_TASK_RESUME); + + uint32_t remaining_time = TIMEOUT_VALUE; + + do + { + if (nrf_twi_event_check(twi, NRF_TWI_EVENT_RXDREADY)) + { + nrf_twi_event_clear(twi, NRF_TWI_EVENT_RXDREADY); + return nrf_twi_rxd_get(twi); + } + if (nrf_twi_event_check(twi, NRF_TWI_EVENT_ERROR)) + { + nrf_twi_event_clear(twi, NRF_TWI_EVENT_ERROR); + return I2C_ERROR_NO_SLAVE; + } + } + while (--remaining_time); + + return I2C_ERROR_BUS_BUSY; +} + +int i2c_byte_write(i2c_t *obj, int data) +{ + NRF_TWI_Type *twi = m_twi_instances[TWI_IDX(obj)]; + twi_info_t *twi_info = TWI_INFO(obj); + if (twi_info->start_twi) + { + twi_info->start_twi = false; + + if (data & 1) + { + start_twi_read(twi, data); + } + else + { + start_twi_write(twi, data); + } + return 1; + } + else + { + nrf_twi_task_trigger(twi, NRF_TWI_TASK_RESUME); + // 0 - TWI signaled error (NAK is the only possibility here) + // 1 - ACK received + // 2 - timeout (clock stretched for too long?) + return twi_byte_write(twi, (uint8_t)data); + } +} + + +#if DEVICE_I2C_ASYNCH +void i2c_transfer_asynch(i2c_t *obj, const void *tx, size_t tx_length, + void *rx, size_t rx_length, uint32_t address, + uint32_t stop, uint32_t handler, + uint32_t event, DMAUsage hint) +{ + (void)hint; + + twi_info_t *twi_info = TWI_INFO(obj); + if (twi_info->active) + { + return; + } + twi_info->active = true; + twi_info->events = 0; + twi_info->handler = (void (*)(void))handler; + twi_info->evt_mask = event; + twi_info->tx_length = tx_length; + twi_info->tx = tx; + twi_info->rx_length = rx_length; + twi_info->rx = rx; + twi_info->stop = stop; + + NRF_TWI_Type *twi = m_twi_instances[TWI_IDX(obj)]; + + nrf_twi_event_clear(twi, NRF_TWI_EVENT_TXDSENT); + nrf_twi_event_clear(twi, NRF_TWI_EVENT_RXDREADY); + nrf_twi_event_clear(twi, NRF_TWI_EVENT_STOPPED); + nrf_twi_event_clear(twi, NRF_TWI_EVENT_SUSPENDED); + nrf_twi_event_clear(twi, NRF_TWI_EVENT_ERROR); + (void)nrf_twi_errorsrc_get_and_clear(twi); + + nrf_twi_address_set(twi, twi_address(address)); + nrf_twi_task_trigger(twi, NRF_TWI_TASK_RESUME); + // TX only, or TX + RX (after a repeated start). + if (tx_length > 0) + { + nrf_twi_task_trigger(twi, NRF_TWI_TASK_STARTTX); + nrf_twi_txd_set(twi, *(twi_info->tx)); + ++(twi_info->tx); + // RX only. + } + else if (rx_length > 0) + { + start_asynch_rx(twi_info, twi); + // Both 'tx_length' and 'rx_length' are 0 - this case may be used + // to test if the slave is presentand ready for transfer (by just + // sending the address and checking if it is acknowledged). + } + else + { + nrf_twi_task_trigger(twi, NRF_TWI_TASK_STARTTX); + if (stop) + { + nrf_twi_task_trigger(twi, NRF_TWI_TASK_STOP); + } + else + { + nrf_twi_task_trigger(twi, NRF_TWI_TASK_SUSPEND); + nrf_twi_int_enable(twi, NRF_TWI_INT_SUSPENDED_MASK); + } + twi_info->events |= I2C_EVENT_TRANSFER_COMPLETE; + } + + nrf_twi_int_enable(twi, NRF_TWI_INT_TXDSENT_MASK | + NRF_TWI_INT_RXDREADY_MASK | + NRF_TWI_INT_STOPPED_MASK | + NRF_TWI_INT_ERROR_MASK); +} + +uint32_t i2c_irq_handler_asynch(i2c_t *obj) +{ + twi_info_t *twi_info = TWI_INFO(obj); + return (twi_info->events & twi_info->evt_mask); +} + +uint8_t i2c_active(i2c_t *obj) +{ + twi_info_t *twi_info = TWI_INFO(obj); + return twi_info->active; +} + +void i2c_abort_asynch(i2c_t *obj) +{ + i2c_reset(obj); +} +#endif // DEVICE_I2C_ASYNCH + +#endif // DEVICE_I2C diff --git a/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/irq_handlers_hw.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/irq_handlers_hw.h new file mode 100644 index 00000000000..7eba37ad998 --- /dev/null +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/irq_handlers_hw.h @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2016 Nordic Semiconductor ASA + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * 2. Redistributions in binary form, except as embedded into a Nordic Semiconductor ASA + * integrated circuit in a product or a software update for such product, must reproduce + * the above copyright notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of Nordic Semiconductor ASA nor the names of its contributors may be + * used to endorse or promote products derived from this software without specific prior + * written permission. + * + * 4. This software, with or without modification, must only be used with a + * Nordic Semiconductor ASA integrated circuit. + * + * 5. Any software provided in binary or object form under this license must not be reverse + * engineered, decompiled, modified and/or disassembled. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +/** + * @file irq_handlers_hw.h + * @brief Heleper file for wiring irq handlers to theirs vectors. + */ + +#ifndef IRQ_HANDLERS_HW_H__ +#define IRQ_HANDLERS_HW_H__ + + +typedef struct +{ + IRQn_Type IRQn; + uint32_t vector; +} peripheral_handler_desc_t; + +#endif // IRQ_HANDLERS_HW_H__ + diff --git a/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/lp_ticker.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/lp_ticker.c new file mode 100644 index 00000000000..ae63c2a1e1a --- /dev/null +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/lp_ticker.c @@ -0,0 +1,48 @@ +/* mbed Microcontroller Library + * Copyright (c) 2015 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * 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. + */ +#include "lp_ticker_api.h" + +#if DEVICE_LOWPOWERTIMER + +#include "common_rtc.h" + +void lp_ticker_init(void) +{ + common_rtc_init(); +} + +uint32_t lp_ticker_read() +{ + return (uint32_t)common_rtc_64bit_us_get(); +} + +void lp_ticker_set_interrupt(timestamp_t timestamp) +{ + common_rtc_set_interrupt(timestamp, + LP_TICKER_CC_CHANNEL, LP_TICKER_INT_MASK); +} + +void lp_ticker_disable_interrupt(void) +{ + nrf_rtc_event_disable(COMMON_RTC_INSTANCE, LP_TICKER_INT_MASK); +} + +void lp_ticker_clear_interrupt(void) +{ + nrf_rtc_event_clear(COMMON_RTC_INSTANCE, LP_TICKER_EVENT); +} + +#endif // DEVICE_LOWPOWERTIMER diff --git a/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/nordic_critical.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/nordic_critical.c new file mode 100644 index 00000000000..3bcd4c9501a --- /dev/null +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/nordic_critical.c @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2015-2016, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); 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 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, 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. + */ + +#include // uint32_t, UINT32_MAX +#include // uint32_t, UINT32_MAX +#include "cmsis.h" +#include "nrf_soc.h" +#include "nrf_sdm.h" +#include "nrf_nvic.h" + +static uint8_t _sd_state = 0; +static volatile uint32_t _entry_count = 0; + +void core_util_critical_section_enter() +{ + // if a critical section has already been entered, just update the counter + if (_entry_count) + { + ++_entry_count; + return; + } + + // in this path, a critical section has never been entered + // routine of SD V11 work even if the softdevice is not active + sd_nvic_critical_region_enter(&_sd_state); + + assert(_entry_count == 0); // entry count should always be equal to 0 at this point + ++_entry_count; +} + +void core_util_critical_section_exit() +{ + assert(_entry_count > 0); + --_entry_count; + + // If their is other segments which have entered the critical section, just leave + if (_entry_count) + { + return; + } + + // This is the last segment of the critical section, state should be restored as before entering + // the critical section + sd_nvic_critical_region_exit(_sd_state); +} diff --git a/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/nrf5x_lf_clk_helper.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/nrf5x_lf_clk_helper.h new file mode 100644 index 00000000000..08744be767f --- /dev/null +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/nrf5x_lf_clk_helper.h @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2016 Nordic Semiconductor ASA + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * 2. Redistributions in binary form, except as embedded into a Nordic Semiconductor ASA + * integrated circuit in a product or a software update for such product, must reproduce + * the above copyright notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of Nordic Semiconductor ASA nor the names of its contributors may be + * used to endorse or promote products derived from this software without specific prior + * written permission. + * + * 4. This software, with or without modification, must only be used with a + * Nordic Semiconductor ASA integrated circuit. + * + * 5. Any software provided in binary or object form under this license must not be reverse + * engineered, decompiled, modified and/or disassembled. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#ifndef __NRF5X_LF_CLK_HELPER_H_ + +#ifndef MBED_CONF_NORDIC_NRF_LF_CLOCK_SRC + #define MBED_CONF_NORDIC_NRF_LF_CLOCK_SRC (NRF_LF_SRC_XTAL) + #warning No configuration for LF clock source. Xtal source will be used as a default configuration. +#endif + + + +#define NRF_LF_SRC_XTAL 2 +#define NRF_LF_SRC_SYNTH 3 +#define NRF_LF_SRC_RC 4 + +#if MBED_CONF_NORDIC_NRF_LF_CLOCK_SRC == NRF_LF_SRC_SYNTH + #define CLOCK_LFCLKSRC_SRC_TO_USE (CLOCK_LFCLKSRC_SRC_Synth) +#elif MBED_CONF_NORDIC_NRF_LF_CLOCK_SRC == NRF_LF_SRC_XTAL + #define CLOCK_LFCLKSRC_SRC_TO_USE (CLOCK_LFCLKSRC_SRC_Xtal) +#elif MBED_CONF_NORDIC_NRF_LF_CLOCK_SRC == NRF_LF_SRC_RC + #define CLOCK_LFCLKSRC_SRC_TO_USE (CLOCK_LFCLKSRC_SRC_RC) +#else + #error Bad LFCLK configuration. Declare proper source through mbed configuration. +#endif + +#undef NRF_LF_SRC_XTAL +#undef NRF_LF_SRC_SYNTH +#undef NRF_LF_SRC_RC + +#endif diff --git a/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/objects.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/objects.h new file mode 100644 index 00000000000..104ff648348 --- /dev/null +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/objects.h @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2013 Nordic Semiconductor ASA + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * 2. Redistributions in binary form, except as embedded into a Nordic Semiconductor ASA + * integrated circuit in a product or a software update for such product, must reproduce + * the above copyright notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of Nordic Semiconductor ASA nor the names of its contributors may be + * used to endorse or promote products derived from this software without specific prior + * written permission. + * + * 4. This software, with or without modification, must only be used with a + * Nordic Semiconductor ASA integrated circuit. + * + * 5. Any software provided in binary or object form under this license must not be reverse + * engineered, decompiled, modified and/or disassembled. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#ifndef MBED_OBJECTS_H +#define MBED_OBJECTS_H + +#include "cmsis.h" +#include "PortNames.h" +#include "PeripheralNames.h" +#include "PinNames.h" + +#ifdef __cplusplus +extern "C" { +#endif + +struct serial_s +{ + uint32_t placeholder; // struct is unused by nRF5x API implementation +}; // but it must be not empty (required by strict compiler - IAR) + +struct spi_s +{ + uint8_t spi_idx; +}; + +struct port_s +{ + PortName port; + uint32_t mask; +}; + +struct pwmout_s +{ + PWMName pwm_name; + PinName pin; + uint8_t pwm_channel; + void * pwm_struct; +}; + +struct i2c_s +{ + uint8_t twi_idx; +}; + +struct analogin_s +{ + ADCName adc; + uint8_t adc_pin; +}; + +struct gpio_irq_s +{ + uint32_t ch; +}; + + +#include "gpio_object.h" + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/pinmap.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/pinmap.c new file mode 100644 index 00000000000..26fa761c1db --- /dev/null +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/pinmap.c @@ -0,0 +1,37 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * 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. + */ +#include "mbed_assert.h" +#include "mbed_error.h" +#include "pinmap.h" + +void pin_function(PinName pin, int function) +{ + /* Avoid compiler warnings */ + (void) pin; + (void) function; +} + +void pin_mode(PinName pin, PinMode mode) +{ + MBED_ASSERT(pin != (PinName)NC); + + uint32_t pin_number = (uint32_t)pin; + + NRF_GPIO_Type * reg = nrf_gpio_pin_port_decode(&pin_number); + + reg->PIN_CNF[pin_number] &= ~GPIO_PIN_CNF_PULL_Msk; + reg->PIN_CNF[pin_number] |= (mode << GPIO_PIN_CNF_PULL_Pos); +} diff --git a/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/port_api.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/port_api.c new file mode 100644 index 00000000000..faecdc9de53 --- /dev/null +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/port_api.c @@ -0,0 +1,133 @@ +/* + * Copyright (c) 2013 Nordic Semiconductor ASA + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * 2. Redistributions in binary form, except as embedded into a Nordic Semiconductor ASA + * integrated circuit in a product or a software update for such product, must reproduce + * the above copyright notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of Nordic Semiconductor ASA nor the names of its contributors may be + * used to endorse or promote products derived from this software without specific prior + * written permission. + * + * 4. This software, with or without modification, must only be used with a + * Nordic Semiconductor ASA integrated circuit. + * + * 5. Any software provided in binary or object form under this license must not be reverse + * engineered, decompiled, modified and/or disassembled. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#include "port_api.h" +#include "pinmap.h" + +static NRF_GPIO_Type * const m_ports[] = GPIO_REG_LIST; + +#if defined(TARGET_MCU_NRF51822) + static const uint32_t m_gpio_pin_count[] = {31}; +#elif defined(TARGET_MCU_NRF52832) + static const uint32_t m_gpio_pin_count[] = {32}; +#elif defined(TARGET_MCU_NRF52840) + static const uint32_t m_gpio_pin_count[] = {32, 16}; +#else + #error not recognized gpio count for mcu +#endif + +#define GPIO_PORT_COUNT (sizeof(m_gpio_pin_count)/sizeof(uint32_t)) + + +PinName port_pin(PortName port, int pin_n) +{ + return (PinName)NRF_GPIO_PIN_MAP(port, pin_n); +} + +void port_init(port_t *obj, PortName port, int mask, PinDirection dir) +{ + MBED_ASSERT((uint32_t)port < GPIO_PORT_COUNT); + + obj->port = port; + obj->mask = mask; + + port_dir(obj, dir); +} + +void port_mode(port_t *obj, PinMode mode) +{ + uint32_t i; + // The mode is set per pin: reuse pinmap logic + for (i = 0; i < m_gpio_pin_count[obj->port]; i++) + { + if (obj->mask & (1 << i)) + { + pin_mode(port_pin(obj->port, i), mode); + } + } +} + +void port_dir(port_t *obj, PinDirection dir) +{ + uint32_t i; + + volatile uint32_t *reg_cnf = (volatile uint32_t*) m_ports[obj->port]->PIN_CNF; + + switch (dir) + { + case PIN_INPUT: + + for (i = 0; i < m_gpio_pin_count[obj->port]; i++) + { + if (obj->mask & (1 << i)) + { + reg_cnf[i] = (GPIO_PIN_CNF_SENSE_Disabled << GPIO_PIN_CNF_SENSE_Pos) + | (GPIO_PIN_CNF_DRIVE_S0S1 << GPIO_PIN_CNF_DRIVE_Pos) + | (GPIO_PIN_CNF_INPUT_Connect << GPIO_PIN_CNF_INPUT_Pos) + | (GPIO_PIN_CNF_DIR_Input << GPIO_PIN_CNF_DIR_Pos); + } + } + break; + + case PIN_OUTPUT: + + for (i = 0; i < m_gpio_pin_count[obj->port]; i++) + { + if (obj->mask & (1 << i)) + { + reg_cnf[i] = (GPIO_PIN_CNF_SENSE_Disabled << GPIO_PIN_CNF_SENSE_Pos) + | (GPIO_PIN_CNF_DRIVE_S0S1 << GPIO_PIN_CNF_DRIVE_Pos) + | (GPIO_PIN_CNF_PULL_Disabled << GPIO_PIN_CNF_PULL_Pos) + | (GPIO_PIN_CNF_INPUT_Connect << GPIO_PIN_CNF_INPUT_Pos) + | (GPIO_PIN_CNF_DIR_Output << GPIO_PIN_CNF_DIR_Pos); + } + } + break; + } +} + +void port_write(port_t *obj, int value) +{ + m_ports[obj->port]->OUTSET = value & obj->mask; + m_ports[obj->port]->OUTCLR = (~value) & obj->mask; +} + +int port_read(port_t *obj) +{ + return ((m_ports[obj->port]->IN) & obj->mask); +} diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/porting_tools/copyright_header.txt b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/porting_tools/copyright_header.txt similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/porting_tools/copyright_header.txt rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/porting_tools/copyright_header.txt diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/porting_tools/replace_headers.py b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/porting_tools/replace_headers.py similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/porting_tools/replace_headers.py rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/porting_tools/replace_headers.py diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/porting_tools/sdk_update.py b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/porting_tools/sdk_update.py similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/porting_tools/sdk_update.py rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/porting_tools/sdk_update.py diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/porting_tools/update_desc.json b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/porting_tools/update_desc.json similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/porting_tools/update_desc.json rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/porting_tools/update_desc.json diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/pwmout_api.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/pwmout_api.c similarity index 99% rename from targets/TARGET_NORDIC/TARGET_NRF5/pwmout_api.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/pwmout_api.c index 08e86a3d1e0..230ca3e9fe6 100644 --- a/targets/TARGET_NORDIC/TARGET_NRF5/pwmout_api.c +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/pwmout_api.c @@ -35,15 +35,12 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ - -#ifndef TARGET_MCU_NRF51822 - + #include "mbed_assert.h" #include "mbed_error.h" #include "pwmout_api.h" #include "cmsis.h" #include "pinmap.h" -#include "sdk_config.h" #if DEVICE_PWMOUT @@ -400,5 +397,3 @@ static void internal_pwmout_exe(pwmout_t *obj, bool new_period, bool initializat } #endif // DEVICE_PWMOUT - -#endif \ No newline at end of file diff --git a/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/reloc_vector_table.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/reloc_vector_table.c new file mode 100644 index 00000000000..bf9577331ab --- /dev/null +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/reloc_vector_table.c @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2016 Nordic Semiconductor ASA + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * 2. Redistributions in binary form, except as embedded into a Nordic Semiconductor ASA + * integrated circuit in a product or a software update for such product, must reproduce + * the above copyright notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of Nordic Semiconductor ASA nor the names of its contributors may be + * used to endorse or promote products derived from this software without specific prior + * written permission. + * + * 4. This software, with or without modification, must only be used with a + * Nordic Semiconductor ASA integrated circuit. + * + * 5. Any software provided in binary or object form under this license must not be reverse + * engineered, decompiled, modified and/or disassembled. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#include "nrf.h" +#include "cmsis_nvic.h" +#include "stdint.h" +#include "nrf_sdm.h" +#include "section_vars.h" + +#if defined(__CC_ARM) + __attribute__ ((section("noinit"),zero_init)) + uint32_t nrf_dispatch_vector[NVIC_NUM_VECTORS]; +#elif defined(__GNUC__) + __attribute__ ((section(".noinit"))) + uint32_t nrf_dispatch_vector[NVIC_NUM_VECTORS]; +#elif defined(__ICCARM__) + uint32_t nrf_dispatch_vector[NVIC_NUM_VECTORS] @ ".noinit"; +#endif + + +typedef void (*generic_irq_handler_t)(void); + + +extern uint32_t __Vectors[]; +#define VECTORS_FLASH_START __Vectors + +/** + * @brief Function for relocation of the vector to RAM on nRF5x devices. + * This function is intended to be called during startup. + */ +void nrf_reloc_vector_table(void) +{ + // Copy and switch to dynamic vectors + uint32_t *old_vectors = (uint32_t*)VECTORS_FLASH_START; + uint32_t i; + + for (i = 0; i< NVIC_NUM_VECTORS; i++) + { + nrf_dispatch_vector[i] = old_vectors[i]; + } + + sd_softdevice_vector_table_base_set((uint32_t) nrf_dispatch_vector); +} diff --git a/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/rtc_api.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/rtc_api.c new file mode 100644 index 00000000000..589b85cd596 --- /dev/null +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/rtc_api.c @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2013 Nordic Semiconductor ASA + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * 2. Redistributions in binary form, except as embedded into a Nordic Semiconductor ASA + * integrated circuit in a product or a software update for such product, must reproduce + * the above copyright notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of Nordic Semiconductor ASA nor the names of its contributors may be + * used to endorse or promote products derived from this software without specific prior + * written permission. + * + * 4. This software, with or without modification, must only be used with a + * Nordic Semiconductor ASA integrated circuit. + * + * 5. Any software provided in binary or object form under this license must not be reverse + * engineered, decompiled, modified and/or disassembled. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#include "rtc_api.h" + +#if DEVICE_RTC + +#include "common_rtc.h" +#include "nrf_drv_clock.h" +#include "app_util_platform.h" + +static time_t m_time_base; + +void rtc_init(void) +{ + common_rtc_init(); +} + +void rtc_free(void) +{ + // A common counter is used for RTC, lp_ticker and us_ticker, so it can't be + // disabled here, but this does not cause any extra cost. Besides, currently + // this function is not used by RTC API in mbed-drivers. +} + +int rtc_isenabled(void) +{ + return m_common_rtc_enabled; +} + +static uint32_t rtc_seconds_get(void) +{ + // Convert current counter value to seconds. + uint32_t seconds = nrf_rtc_counter_get(COMMON_RTC_INSTANCE) / RTC_INPUT_FREQ; + // Add proper amount of seconds for each registered overflow of the counter. + uint32_t seconds_per_overflow = (1uL << RTC_COUNTER_BITS) / RTC_INPUT_FREQ; + return (seconds + (m_common_rtc_overflows * seconds_per_overflow)); +} + +time_t rtc_read(void) +{ + return m_time_base + rtc_seconds_get(); +} + +void rtc_write(time_t t) +{ + uint32_t seconds; + + do + { + seconds = rtc_seconds_get(); + m_time_base = t - seconds; + // If the number of seconds indicated by the counter changed during the + // update of the time base, just repeat the update, now using the new + // number of seconds. + } while (seconds != rtc_seconds_get()); +} + +#endif // DEVICE_RTC diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/ble_advertising/ble_advertising.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/ble_advertising/ble_advertising.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/ble_advertising/ble_advertising.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/ble_advertising/ble_advertising.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/ble_advertising/ble_advertising.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/ble_advertising/ble_advertising.h similarity index 99% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/ble_advertising/ble_advertising.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/ble_advertising/ble_advertising.h index 9b436d7a08f..af409e8f18b 100644 --- a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/ble_advertising/ble_advertising.h +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/ble_advertising/ble_advertising.h @@ -62,8 +62,8 @@ #include #include "nrf_error.h" -#include "headers/nrf_ble.h" -#include "headers/nrf_ble_gattc.h" +#include "headers/ble.h" +#include "ble_gattc.h" #include "ble_advdata.h" #ifdef __cplusplus diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/ble_db_discovery/ble_db_discovery.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/ble_db_discovery/ble_db_discovery.c similarity index 99% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/ble_db_discovery/ble_db_discovery.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/ble_db_discovery/ble_db_discovery.c index 96bbe91a224..eba5b3285de 100644 --- a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/ble_db_discovery/ble_db_discovery.c +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/ble_db_discovery/ble_db_discovery.c @@ -40,7 +40,7 @@ #if NRF_MODULE_ENABLED(BLE_DB_DISCOVERY) #include "ble_db_discovery.h" #include -#include "headers/nrf_ble.h" +#include "headers\ble.h" #include "ble_srv_common.h" #define NRF_LOG_MODULE_NAME "BLE_DB_DISC" #include "nrf_log.h" diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/ble_db_discovery/ble_db_discovery.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/ble_db_discovery/ble_db_discovery.h similarity index 99% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/ble_db_discovery/ble_db_discovery.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/ble_db_discovery/ble_db_discovery.h index dccfe70ad60..0372a68fad4 100644 --- a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/ble_db_discovery/ble_db_discovery.h +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/ble_db_discovery/ble_db_discovery.h @@ -70,8 +70,8 @@ #include #include "nrf_error.h" -#include "headers/nrf_ble.h" -#include "headers/nrf_ble_gattc.h" +#include "headers\ble.h" +#include "ble_gattc.h" #include "ble_srv_common.h" #include "ble_gatt_db.h" diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/ble_debug_assert_handler/ble_debug_assert_handler.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/ble_debug_assert_handler/ble_debug_assert_handler.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/ble_debug_assert_handler/ble_debug_assert_handler.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/ble_debug_assert_handler/ble_debug_assert_handler.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/ble_debug_assert_handler/ble_debug_assert_handler.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/ble_debug_assert_handler/ble_debug_assert_handler.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/ble_debug_assert_handler/ble_debug_assert_handler.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/ble_debug_assert_handler/ble_debug_assert_handler.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/ble_dtm/ble_dtm.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/ble_dtm/ble_dtm.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/ble_dtm/ble_dtm.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/ble_dtm/ble_dtm.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/ble_dtm/ble_dtm.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/ble_dtm/ble_dtm.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/ble_dtm/ble_dtm.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/ble_dtm/ble_dtm.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/ble_dtm/ble_dtm_hw.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/ble_dtm/ble_dtm_hw.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/ble_dtm/ble_dtm_hw.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/ble_dtm/ble_dtm_hw.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/ble_dtm/ble_dtm_hw_nrf52.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/ble_dtm/ble_dtm_hw_nrf52.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/ble_dtm/ble_dtm_hw_nrf52.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/ble_dtm/ble_dtm_hw_nrf52.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/ble_error_log/ble_error_log.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/ble_error_log/ble_error_log.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/ble_error_log/ble_error_log.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/ble_error_log/ble_error_log.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/ble_racp/ble_racp.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/ble_racp/ble_racp.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/ble_racp/ble_racp.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/ble_racp/ble_racp.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/ble_racp/ble_racp.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/ble_racp/ble_racp.h similarity index 99% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/ble_racp/ble_racp.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/ble_racp/ble_racp.h index 97b8f56d4c9..a6a60614ce2 100644 --- a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/ble_racp/ble_racp.h +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/ble_racp/ble_racp.h @@ -49,8 +49,8 @@ #include #include -#include "headers/nrf_ble.h" -#include "headers/nrf_ble_types.h" +#include "headers\ble.h" +#include "ble_types.h" #ifdef __cplusplus extern "C" { diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/ble_radio_notification/ble_radio_notification.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/ble_radio_notification/ble_radio_notification.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/ble_radio_notification/ble_radio_notification.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/ble_radio_notification/ble_radio_notification.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/ble_radio_notification/ble_radio_notification.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/ble_radio_notification/ble_radio_notification.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/ble_radio_notification/ble_radio_notification.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/ble_radio_notification/ble_radio_notification.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/common/ble_advdata.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/common/ble_advdata.c similarity index 99% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/common/ble_advdata.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/common/ble_advdata.c index 9dcc8201cff..f114952fba3 100644 --- a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/common/ble_advdata.c +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/common/ble_advdata.c @@ -37,7 +37,7 @@ */ #include "ble_advdata.h" -#include "headers/nrf_ble_gap.h" +#include "ble_gap.h" #include "ble_srv_common.h" #include "sdk_common.h" diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/common/ble_advdata.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/common/ble_advdata.h similarity index 99% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/common/ble_advdata.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/common/ble_advdata.h index d9bb01a7699..d67ca5fab7a 100644 --- a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/common/ble_advdata.h +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/common/ble_advdata.h @@ -51,7 +51,7 @@ #include #include #include -#include "headers/nrf_ble.h" +#include "headers/ble.h" #include "app_util.h" #ifdef __cplusplus diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/common/ble_conn_params.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/common/ble_conn_params.h similarity index 99% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/common/ble_conn_params.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/common/ble_conn_params.h index f9ff64c12d3..eaf7d84a719 100644 --- a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/common/ble_conn_params.h +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/common/ble_conn_params.h @@ -48,7 +48,7 @@ #define BLE_CONN_PARAMS_H__ #include -#include "headers/nrf_ble.h" +#include "headers/ble.h" #include "ble_srv_common.h" #ifdef __cplusplus diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/common/ble_conn_state.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/common/ble_conn_state.c similarity index 99% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/common/ble_conn_state.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/common/ble_conn_state.c index b4fb337a2ed..6303b50f2cb 100644 --- a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/common/ble_conn_state.c +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/common/ble_conn_state.c @@ -40,7 +40,7 @@ #include #include #include -#include "headers/nrf_ble.h" +#include "headers/ble.h" #include "sdk_mapped_flags.h" #include "app_error.h" diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/common/ble_conn_state.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/common/ble_conn_state.h similarity index 99% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/common/ble_conn_state.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/common/ble_conn_state.h index e310f7b3b5f..8a4417df19a 100644 --- a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/common/ble_conn_state.h +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/common/ble_conn_state.h @@ -68,7 +68,7 @@ #include #include -#include "headers/nrf_ble.h" +#include "headers/ble.h" #include "sdk_mapped_flags.h" #ifdef __cplusplus diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/common/ble_date_time.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/common/ble_date_time.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/common/ble_date_time.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/common/ble_date_time.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/common/ble_gatt_db.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/common/ble_gatt_db.h similarity index 98% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/common/ble_gatt_db.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/common/ble_gatt_db.h index 9d6f0e87f63..712e0520d11 100644 --- a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/common/ble_gatt_db.h +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/common/ble_gatt_db.h @@ -47,8 +47,8 @@ #define BLE_GATT_DB_H__ #include -#include "headers/nrf_ble.h" -#include "headers/nrf_ble_gattc.h" +#include "headers/ble.h" +#include "ble_gattc.h" #ifdef __cplusplus extern "C" { diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/common/ble_sensor_location.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/common/ble_sensor_location.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/common/ble_sensor_location.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/common/ble_sensor_location.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/common/ble_srv_common.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/common/ble_srv_common.c similarity index 99% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/common/ble_srv_common.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/common/ble_srv_common.c index 8b821cdbc66..5f3dd17df3a 100644 --- a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/common/ble_srv_common.c +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/common/ble_srv_common.c @@ -45,7 +45,7 @@ #include #include "nordic_common.h" #include "app_error.h" -#include "headers/nrf_ble.h" +#include "headers/ble.h" bool ble_srv_is_notification_enabled(uint8_t const * p_encoded_data) { diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/common/ble_srv_common.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/common/ble_srv_common.h similarity index 99% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/common/ble_srv_common.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/common/ble_srv_common.h index 85df97e00bc..660e9bf7f5f 100644 --- a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/common/ble_srv_common.h +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/common/ble_srv_common.h @@ -49,11 +49,11 @@ #include #include -#include "headers/nrf_ble_types.h" +#include "ble_types.h" #include "app_util.h" -#include "headers/nrf_ble.h" -#include "headers/nrf_ble_gap.h" -#include "headers/nrf_ble_gatt.h" +#include "headers/ble.h" +#include "ble_gap.h" +#include "ble_gatt.h" #ifdef __cplusplus extern "C" { diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/gatt_cache_manager.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/gatt_cache_manager.c similarity index 99% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/gatt_cache_manager.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/gatt_cache_manager.c index 0e2f2a1835b..ba19efadd35 100644 --- a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/gatt_cache_manager.c +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/gatt_cache_manager.c @@ -40,7 +40,7 @@ #if NRF_MODULE_ENABLED(PEER_MANAGER) #include "gatt_cache_manager.h" -#include "headers/nrf_ble_gap.h" +#include "ble_gap.h" #include "ble_conn_state.h" #include "peer_manager_types.h" #include "peer_manager_internal.h" diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/gatt_cache_manager.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/gatt_cache_manager.h similarity index 99% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/gatt_cache_manager.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/gatt_cache_manager.h index 79d4d718364..fe95dba5452 100644 --- a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/gatt_cache_manager.h +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/gatt_cache_manager.h @@ -42,8 +42,8 @@ #include #include "sdk_errors.h" -#include "headers/nrf_ble.h" -#include "headers/nrf_ble_gap.h" +#include "headers/ble.h" +#include "ble_gap.h" #include "peer_manager_types.h" #ifdef __cplusplus diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/gatts_cache_manager.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/gatts_cache_manager.c similarity index 99% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/gatts_cache_manager.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/gatts_cache_manager.c index 3f4ac470606..3f6b89c8bc1 100644 --- a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/gatts_cache_manager.c +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/gatts_cache_manager.c @@ -41,7 +41,7 @@ #include "gatts_cache_manager.h" #include -#include "headers/nrf_ble_gap.h" +#include "ble_gap.h" #include "peer_manager_types.h" #include "peer_manager_internal.h" #include "peer_database.h" diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/gatts_cache_manager.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/gatts_cache_manager.h similarity index 99% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/gatts_cache_manager.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/gatts_cache_manager.h index 48c314d215f..628276ceab3 100644 --- a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/gatts_cache_manager.h +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/gatts_cache_manager.h @@ -42,8 +42,8 @@ #include #include "sdk_errors.h" -#include "headers/nrf_ble.h" -#include "headers/nrf_ble_gap.h" +#include "headers/ble.h" +#include "ble_gap.h" #include "peer_manager_types.h" #ifdef __cplusplus diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/id_manager.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/id_manager.c similarity index 99% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/id_manager.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/id_manager.c index 03cf432591d..b999a852770 100644 --- a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/id_manager.c +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/id_manager.c @@ -41,8 +41,8 @@ #include "id_manager.h" #include -#include "headers/nrf_ble.h" -#include "headers/nrf_ble_gap.h" +#include "headers/ble.h" +#include "ble_gap.h" #include "ble_conn_state.h" #include "peer_manager_types.h" #include "peer_database.h" diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/id_manager.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/id_manager.h similarity index 99% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/id_manager.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/id_manager.h index 2268884460e..e680f410898 100644 --- a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/id_manager.h +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/id_manager.h @@ -42,8 +42,8 @@ #include #include "sdk_errors.h" -#include "headers/nrf_ble.h" -#include "headers/nrf_ble_gap.h" +#include "headers/ble.h" +#include "ble_gap.h" #include "peer_manager_types.h" #ifdef __cplusplus diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/peer_data.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/peer_data.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/peer_data.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/peer_data.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/peer_data.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/peer_data.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/peer_data.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/peer_data.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/peer_data_storage.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/peer_data_storage.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/peer_data_storage.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/peer_data_storage.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/peer_data_storage.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/peer_data_storage.h similarity index 99% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/peer_data_storage.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/peer_data_storage.h index 0b6343e7a4d..f9b63499245 100644 --- a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/peer_data_storage.h +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/peer_data_storage.h @@ -43,7 +43,7 @@ #include #include "sdk_errors.h" -#include "headers/nrf_ble_gap.h" +#include "ble_gap.h" #include "peer_manager_types.h" #include "peer_manager_internal.h" diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/peer_database.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/peer_database.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/peer_database.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/peer_database.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/peer_database.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/peer_database.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/peer_database.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/peer_database.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/peer_id.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/peer_id.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/peer_id.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/peer_id.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/peer_id.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/peer_id.h similarity index 99% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/peer_id.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/peer_id.h index 1e05ac5a9e3..0c1116c8cb0 100644 --- a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/peer_id.h +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/peer_id.h @@ -43,7 +43,7 @@ #include #include "sdk_errors.h" -#include "headers/nrf_ble_gap.h" +#include "ble_gap.h" #include "peer_manager_types.h" #ifdef __cplusplus diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/peer_manager.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/peer_manager.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/peer_manager.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/peer_manager.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/peer_manager.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/peer_manager.h similarity index 99% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/peer_manager.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/peer_manager.h index ee257546748..b5cc5af7819 100644 --- a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/peer_manager.h +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/peer_manager.h @@ -62,8 +62,8 @@ #include #include #include "sdk_common.h" -#include "headers/nrf_ble.h" -#include "headers/nrf_ble_gap.h" +#include "headers/ble.h" +#include "ble_gap.h" #include "peer_manager_types.h" #include "peer_database.h" diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/peer_manager_internal.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/peer_manager_internal.h similarity index 99% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/peer_manager_internal.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/peer_manager_internal.h index c66bd3dd530..79551404e9c 100644 --- a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/peer_manager_internal.h +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/peer_manager_internal.h @@ -42,8 +42,8 @@ #include #include "sdk_errors.h" -#include "headers/nrf_ble.h" -#include "headers/nrf_ble_gap.h" +#include "headers/ble.h" +#include "ble_gap.h" #include "peer_manager_types.h" #ifdef __cplusplus diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/peer_manager_types.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/peer_manager_types.h similarity index 99% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/peer_manager_types.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/peer_manager_types.h index a934e14c72c..7e085b26c2d 100644 --- a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/peer_manager_types.h +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/peer_manager_types.h @@ -51,8 +51,8 @@ #include #include #include "nrf.h" -#include "headers/nrf_ble_gap.h" -#include "headers/nrf_ble_hci.h" +#include "ble_gap.h" +#include "ble_hci.h" #include "ble_gatt_db.h" #include "app_util.h" #include "app_util_platform.h" diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/pm_buffer.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/pm_buffer.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/pm_buffer.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/pm_buffer.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/pm_buffer.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/pm_buffer.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/pm_buffer.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/pm_buffer.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/pm_mutex.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/pm_mutex.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/pm_mutex.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/pm_mutex.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/pm_mutex.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/pm_mutex.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/pm_mutex.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/pm_mutex.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/security_dispatcher.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/security_dispatcher.c similarity index 99% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/security_dispatcher.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/security_dispatcher.c index 723a6a9777c..a87030bf340 100644 --- a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/security_dispatcher.c +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/security_dispatcher.c @@ -41,8 +41,8 @@ #include "security_dispatcher.h" #include -#include "headers/nrf_ble.h" -#include "headers/nrf_ble_gap.h" +#include "headers/ble.h" +#include "ble_gap.h" #include "ble_conn_state.h" #include "peer_manager_types.h" #include "peer_database.h" diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/security_dispatcher.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/security_dispatcher.h similarity index 99% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/security_dispatcher.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/security_dispatcher.h index 92f8365b64b..7d0b45dc46e 100644 --- a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/security_dispatcher.h +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/security_dispatcher.h @@ -42,8 +42,8 @@ #include #include "sdk_errors.h" -#include "headers/nrf_ble.h" -#include "headers/nrf_ble_gap.h" +#include "headers/ble.h" +#include "ble_gap.h" #include "peer_manager_types.h" #ifdef __cplusplus diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/security_manager.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/security_manager.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/security_manager.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/security_manager.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/security_manager.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/security_manager.h similarity index 99% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/security_manager.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/security_manager.h index 73cb69c1c89..c1043a6a3da 100644 --- a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/ble/peer_manager/security_manager.h +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/ble/peer_manager/security_manager.h @@ -42,8 +42,8 @@ #include #include "sdk_errors.h" -#include "headers/nrf_ble.h" -#include "headers/nrf_ble_gap.h" +#include "headers/ble.h" +#include "ble_gap.h" #include "peer_manager_types.h" #include "security_dispatcher.h" diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/boards/arduino_primo.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/boards/arduino_primo.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/boards/arduino_primo.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/boards/arduino_primo.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/boards/boards.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/boards/boards.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/boards/boards.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/boards/boards.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/boards/boards.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/boards/boards.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/boards/boards.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/boards/boards.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/boards/d52_starterkit.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/boards/d52_starterkit.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/boards/d52_starterkit.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/boards/d52_starterkit.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/boards/n5_starterkit.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/boards/n5_starterkit.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/boards/n5_starterkit.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/boards/n5_starterkit.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/boards/nrf6310.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/boards/nrf6310.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/boards/nrf6310.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/boards/nrf6310.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/boards/pca10000.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/boards/pca10000.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/boards/pca10000.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/boards/pca10000.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/boards/pca10001.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/boards/pca10001.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/boards/pca10001.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/boards/pca10001.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/boards/pca10003.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/boards/pca10003.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/boards/pca10003.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/boards/pca10003.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/boards/pca10028.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/boards/pca10028.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/boards/pca10028.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/boards/pca10028.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/boards/pca10031.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/boards/pca10031.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/boards/pca10031.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/boards/pca10031.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/boards/pca10036.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/boards/pca10036.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/boards/pca10036.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/boards/pca10036.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/boards/pca10040.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/boards/pca10040.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/boards/pca10040.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/boards/pca10040.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/boards/pca10056.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/boards/pca10056.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/boards/pca10056.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/boards/pca10056.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/boards/pca20006.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/boards/pca20006.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/boards/pca20006.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/boards/pca20006.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/boards/wt51822.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/boards/wt51822.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/boards/wt51822.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/boards/wt51822.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/device/compiler_abstraction.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/device/compiler_abstraction.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/device/compiler_abstraction.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/device/compiler_abstraction.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/device/nrf.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/device/nrf.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/device/nrf.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/device/nrf.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/device/nrf51.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/device/nrf51.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/device/nrf51.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/device/nrf51.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/device/nrf51422_peripherals.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/device/nrf51422_peripherals.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/device/nrf51422_peripherals.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/device/nrf51422_peripherals.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/device/nrf51802_peripherals.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/device/nrf51802_peripherals.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/device/nrf51802_peripherals.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/device/nrf51802_peripherals.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/device/nrf51822_peripherals.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/device/nrf51822_peripherals.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/device/nrf51822_peripherals.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/device/nrf51822_peripherals.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/device/nrf51_bitfields.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/device/nrf51_bitfields.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/device/nrf51_bitfields.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/device/nrf51_bitfields.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/device/nrf51_deprecated.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/device/nrf51_deprecated.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/device/nrf51_deprecated.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/device/nrf51_deprecated.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/device/nrf51_to_nrf52.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/device/nrf51_to_nrf52.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/device/nrf51_to_nrf52.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/device/nrf51_to_nrf52.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/device/nrf51_to_nrf52840.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/device/nrf51_to_nrf52840.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/device/nrf51_to_nrf52840.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/device/nrf51_to_nrf52840.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/device/nrf52.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/device/nrf52.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/device/nrf52.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/device/nrf52.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/device/nrf52832_peripherals.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/device/nrf52832_peripherals.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/device/nrf52832_peripherals.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/device/nrf52832_peripherals.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/device/nrf52840.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/device/nrf52840.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/device/nrf52840.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/device/nrf52840.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/device/nrf52840_bitfields.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/device/nrf52840_bitfields.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/device/nrf52840_bitfields.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/device/nrf52840_bitfields.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/device/nrf52840_peripherals.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/device/nrf52840_peripherals.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/device/nrf52840_peripherals.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/device/nrf52840_peripherals.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/device/nrf52_bitfields.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/device/nrf52_bitfields.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/device/nrf52_bitfields.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/device/nrf52_bitfields.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/device/nrf52_name_change.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/device/nrf52_name_change.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/device/nrf52_name_change.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/device/nrf52_name_change.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/device/nrf52_to_nrf52840.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/device/nrf52_to_nrf52840.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/device/nrf52_to_nrf52840.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/device/nrf52_to_nrf52840.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/ble_flash/ble_flash.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/ble_flash/ble_flash.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/ble_flash/ble_flash.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/ble_flash/ble_flash.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/ble_flash/ble_flash.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/ble_flash/ble_flash.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/ble_flash/ble_flash.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/ble_flash/ble_flash.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/clock/nrf_drv_clock.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/clock/nrf_drv_clock.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/clock/nrf_drv_clock.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/clock/nrf_drv_clock.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/clock/nrf_drv_clock.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/clock/nrf_drv_clock.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/clock/nrf_drv_clock.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/clock/nrf_drv_clock.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/common/nrf_drv_common.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/common/nrf_drv_common.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/common/nrf_drv_common.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/common/nrf_drv_common.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/common/nrf_drv_common.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/common/nrf_drv_common.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/common/nrf_drv_common.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/common/nrf_drv_common.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/comp/nrf_drv_comp.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/comp/nrf_drv_comp.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/comp/nrf_drv_comp.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/comp/nrf_drv_comp.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/comp/nrf_drv_comp.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/comp/nrf_drv_comp.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/comp/nrf_drv_comp.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/comp/nrf_drv_comp.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/delay/nrf_delay.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/delay/nrf_delay.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/delay/nrf_delay.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/delay/nrf_delay.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/gpiote/nrf_drv_gpiote.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/gpiote/nrf_drv_gpiote.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/gpiote/nrf_drv_gpiote.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/gpiote/nrf_drv_gpiote.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/gpiote/nrf_drv_gpiote.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/gpiote/nrf_drv_gpiote.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/gpiote/nrf_drv_gpiote.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/gpiote/nrf_drv_gpiote.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_clock.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_clock.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_clock.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_clock.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_comp.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_comp.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_comp.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_comp.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_ecb.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_ecb.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_ecb.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_ecb.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_ecb.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_ecb.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_ecb.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_ecb.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_egu.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_egu.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_egu.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_egu.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_gpio.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_gpio.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_gpio.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_gpio.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_gpiote.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_gpiote.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_gpiote.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_gpiote.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_i2s.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_i2s.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_i2s.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_i2s.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_lpcomp.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_lpcomp.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_lpcomp.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_lpcomp.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_nvmc.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_nvmc.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_nvmc.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_nvmc.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_nvmc.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_nvmc.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_nvmc.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_nvmc.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_pdm.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_pdm.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_pdm.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_pdm.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_peripherals.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_peripherals.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_peripherals.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_peripherals.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_power.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_power.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_power.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_power.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_ppi.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_ppi.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_ppi.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_ppi.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_pwm.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_pwm.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_pwm.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_pwm.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_qdec.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_qdec.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_qdec.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_qdec.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_rng.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_rng.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_rng.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_rng.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_rtc.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_rtc.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_rtc.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_rtc.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_saadc.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_saadc.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_saadc.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_saadc.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_saadc.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_saadc.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_saadc.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_saadc.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_spi.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_spi.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_spi.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_spi.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_spim.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_spim.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_spim.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_spim.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_spis.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_spis.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_spis.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_spis.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_temp.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_temp.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_temp.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_temp.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_timer.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_timer.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_timer.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_timer.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_twi.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_twi.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_twi.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_twi.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_twim.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_twim.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_twim.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_twim.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_twis.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_twis.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_twis.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_twis.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_uart.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_uart.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_uart.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_uart.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_uarte.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_uarte.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_uarte.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_uarte.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_wdt.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_wdt.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/hal/nrf_wdt.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/hal/nrf_wdt.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/i2s/nrf_drv_i2s.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/i2s/nrf_drv_i2s.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/i2s/nrf_drv_i2s.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/i2s/nrf_drv_i2s.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/i2s/nrf_drv_i2s.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/i2s/nrf_drv_i2s.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/i2s/nrf_drv_i2s.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/i2s/nrf_drv_i2s.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/lpcomp/nrf_drv_lpcomp.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/lpcomp/nrf_drv_lpcomp.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/lpcomp/nrf_drv_lpcomp.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/lpcomp/nrf_drv_lpcomp.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/lpcomp/nrf_drv_lpcomp.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/lpcomp/nrf_drv_lpcomp.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/lpcomp/nrf_drv_lpcomp.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/lpcomp/nrf_drv_lpcomp.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/pdm/nrf_drv_pdm.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/pdm/nrf_drv_pdm.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/pdm/nrf_drv_pdm.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/pdm/nrf_drv_pdm.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/pdm/nrf_drv_pdm.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/pdm/nrf_drv_pdm.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/pdm/nrf_drv_pdm.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/pdm/nrf_drv_pdm.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/power/nrf_drv_power.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/power/nrf_drv_power.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/power/nrf_drv_power.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/power/nrf_drv_power.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/power/nrf_drv_power.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/power/nrf_drv_power.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/power/nrf_drv_power.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/power/nrf_drv_power.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/ppi/nrf_drv_ppi.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/ppi/nrf_drv_ppi.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/ppi/nrf_drv_ppi.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/ppi/nrf_drv_ppi.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/ppi/nrf_drv_ppi.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/ppi/nrf_drv_ppi.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/ppi/nrf_drv_ppi.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/ppi/nrf_drv_ppi.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/pwm/nrf_drv_pwm.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/pwm/nrf_drv_pwm.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/pwm/nrf_drv_pwm.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/pwm/nrf_drv_pwm.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/pwm/nrf_drv_pwm.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/pwm/nrf_drv_pwm.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/pwm/nrf_drv_pwm.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/pwm/nrf_drv_pwm.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/qdec/nrf_drv_qdec.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/qdec/nrf_drv_qdec.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/qdec/nrf_drv_qdec.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/qdec/nrf_drv_qdec.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/qdec/nrf_drv_qdec.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/qdec/nrf_drv_qdec.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/qdec/nrf_drv_qdec.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/qdec/nrf_drv_qdec.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/radio_config/radio_config.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/radio_config/radio_config.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/radio_config/radio_config.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/radio_config/radio_config.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/radio_config/radio_config.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/radio_config/radio_config.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/radio_config/radio_config.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/radio_config/radio_config.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/rng/nrf_drv_rng.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/rng/nrf_drv_rng.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/rng/nrf_drv_rng.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/rng/nrf_drv_rng.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/rng/nrf_drv_rng.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/rng/nrf_drv_rng.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/rng/nrf_drv_rng.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/rng/nrf_drv_rng.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/rtc/nrf_drv_rtc.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/rtc/nrf_drv_rtc.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/rtc/nrf_drv_rtc.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/rtc/nrf_drv_rtc.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/rtc/nrf_drv_rtc.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/rtc/nrf_drv_rtc.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/rtc/nrf_drv_rtc.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/rtc/nrf_drv_rtc.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/saadc/nrf_drv_saadc.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/saadc/nrf_drv_saadc.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/saadc/nrf_drv_saadc.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/saadc/nrf_drv_saadc.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/saadc/nrf_drv_saadc.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/saadc/nrf_drv_saadc.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/saadc/nrf_drv_saadc.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/saadc/nrf_drv_saadc.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/sdio/config/sdio_config.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/sdio/config/sdio_config.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/sdio/config/sdio_config.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/sdio/config/sdio_config.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/sdio/sdio.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/sdio/sdio.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/sdio/sdio.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/sdio/sdio.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/sdio/sdio.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/sdio/sdio.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/sdio/sdio.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/sdio/sdio.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/spi_master/nrf_drv_spi.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/spi_master/nrf_drv_spi.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/spi_master/nrf_drv_spi.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/spi_master/nrf_drv_spi.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/spi_master/nrf_drv_spi.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/spi_master/nrf_drv_spi.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/spi_master/nrf_drv_spi.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/spi_master/nrf_drv_spi.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/spi_slave/nrf_drv_spis.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/spi_slave/nrf_drv_spis.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/spi_slave/nrf_drv_spis.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/spi_slave/nrf_drv_spis.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/spi_slave/nrf_drv_spis.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/spi_slave/nrf_drv_spis.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/spi_slave/nrf_drv_spis.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/spi_slave/nrf_drv_spis.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/timer/nrf_drv_timer.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/timer/nrf_drv_timer.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/timer/nrf_drv_timer.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/timer/nrf_drv_timer.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/timer/nrf_drv_timer.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/timer/nrf_drv_timer.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/timer/nrf_drv_timer.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/timer/nrf_drv_timer.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/twi_master/nrf_drv_twi.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/twi_master/nrf_drv_twi.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/twi_master/nrf_drv_twi.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/twi_master/nrf_drv_twi.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/twi_master/nrf_drv_twi.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/twi_master/nrf_drv_twi.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/twi_master/nrf_drv_twi.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/twi_master/nrf_drv_twi.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/twis_slave/nrf_drv_twis.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/twis_slave/nrf_drv_twis.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/twis_slave/nrf_drv_twis.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/twis_slave/nrf_drv_twis.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/twis_slave/nrf_drv_twis.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/twis_slave/nrf_drv_twis.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/twis_slave/nrf_drv_twis.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/twis_slave/nrf_drv_twis.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/twis_slave/nrf_drv_twis_inst.def b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/twis_slave/nrf_drv_twis_inst.def similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/twis_slave/nrf_drv_twis_inst.def rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/twis_slave/nrf_drv_twis_inst.def diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/wdt/nrf_drv_wdt.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/wdt/nrf_drv_wdt.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/wdt/nrf_drv_wdt.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/wdt/nrf_drv_wdt.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/wdt/nrf_drv_wdt.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/wdt/nrf_drv_wdt.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/drivers_nrf/wdt/nrf_drv_wdt.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/drivers_nrf/wdt/nrf_drv_wdt.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/bootloader/dfu/nrf_dfu_flash.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/bootloader/dfu/nrf_dfu_flash.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/bootloader/dfu/nrf_dfu_flash.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/bootloader/dfu/nrf_dfu_flash.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/bootloader/dfu/nrf_dfu_flash.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/bootloader/dfu/nrf_dfu_flash.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/bootloader/dfu/nrf_dfu_flash.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/bootloader/dfu/nrf_dfu_flash.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/bootloader/dfu/nrf_dfu_req_handler.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/bootloader/dfu/nrf_dfu_req_handler.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/bootloader/dfu/nrf_dfu_req_handler.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/bootloader/dfu/nrf_dfu_req_handler.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/bootloader/dfu/nrf_dfu_transport.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/bootloader/dfu/nrf_dfu_transport.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/bootloader/dfu/nrf_dfu_transport.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/bootloader/dfu/nrf_dfu_transport.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/bootloader/dfu/nrf_dfu_transport.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/bootloader/dfu/nrf_dfu_transport.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/bootloader/dfu/nrf_dfu_transport.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/bootloader/dfu/nrf_dfu_transport.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/bootloader/dfu/nrf_dfu_types.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/bootloader/dfu/nrf_dfu_types.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/bootloader/dfu/nrf_dfu_types.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/bootloader/dfu/nrf_dfu_types.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/crc16/crc16.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/crc16/crc16.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/crc16/crc16.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/crc16/crc16.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/crc16/crc16.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/crc16/crc16.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/crc16/crc16.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/crc16/crc16.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/crc32/crc32.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/crc32/crc32.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/crc32/crc32.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/crc32/crc32.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/crc32/crc32.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/crc32/crc32.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/crc32/crc32.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/crc32/crc32.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/experimental_section_vars/section_vars.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/experimental_section_vars/section_vars.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/experimental_section_vars/section_vars.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/experimental_section_vars/section_vars.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/fds/fds.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/fds/fds.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/fds/fds.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/fds/fds.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/fds/fds.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/fds/fds.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/fds/fds.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/fds/fds.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/fds/fds_internal_defs.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/fds/fds_internal_defs.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/fds/fds_internal_defs.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/fds/fds_internal_defs.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/fstorage/fstorage.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/fstorage/fstorage.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/fstorage/fstorage.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/fstorage/fstorage.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/fstorage/fstorage.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/fstorage/fstorage.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/fstorage/fstorage.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/fstorage/fstorage.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/fstorage/fstorage_internal_defs.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/fstorage/fstorage_internal_defs.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/fstorage/fstorage_internal_defs.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/fstorage/fstorage_internal_defs.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/fstorage/fstorage_nosd.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/fstorage/fstorage_nosd.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/fstorage/fstorage_nosd.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/fstorage/fstorage_nosd.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/hci/hci_mem_pool.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/hci/hci_mem_pool.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/hci/hci_mem_pool.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/hci/hci_mem_pool.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/hci/hci_mem_pool.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/hci/hci_mem_pool.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/hci/hci_mem_pool.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/hci/hci_mem_pool.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/log/nrf_log.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/log/nrf_log.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/log/nrf_log.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/log/nrf_log.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/log/nrf_log_backend.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/log/nrf_log_backend.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/log/nrf_log_backend.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/log/nrf_log_backend.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/log/nrf_log_ctrl.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/log/nrf_log_ctrl.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/log/nrf_log_ctrl.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/log/nrf_log_ctrl.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/log/src/nrf_log_backend_serial.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/log/src/nrf_log_backend_serial.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/log/src/nrf_log_backend_serial.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/log/src/nrf_log_backend_serial.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/log/src/nrf_log_ctrl_internal.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/log/src/nrf_log_ctrl_internal.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/log/src/nrf_log_ctrl_internal.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/log/src/nrf_log_ctrl_internal.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/log/src/nrf_log_frontend.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/log/src/nrf_log_frontend.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/log/src/nrf_log_frontend.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/log/src/nrf_log_frontend.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/log/src/nrf_log_internal.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/log/src/nrf_log_internal.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/log/src/nrf_log_internal.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/log/src/nrf_log_internal.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/pwm/app_pwm.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/pwm/app_pwm.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/pwm/app_pwm.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/pwm/app_pwm.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/pwm/app_pwm.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/pwm/app_pwm.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/pwm/app_pwm.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/pwm/app_pwm.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/queue/nrf_queue.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/queue/nrf_queue.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/queue/nrf_queue.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/queue/nrf_queue.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/queue/nrf_queue.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/queue/nrf_queue.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/queue/nrf_queue.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/queue/nrf_queue.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/scheduler/app_scheduler.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/scheduler/app_scheduler.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/scheduler/app_scheduler.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/scheduler/app_scheduler.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/scheduler/app_scheduler.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/scheduler/app_scheduler.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/scheduler/app_scheduler.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/scheduler/app_scheduler.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/timer/app_timer.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/timer/app_timer.c new file mode 100644 index 00000000000..33487310f68 --- /dev/null +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/timer/app_timer.c @@ -0,0 +1,1079 @@ +/* + * Copyright (c) 2012 Nordic Semiconductor ASA + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * 2. Redistributions in binary form, except as embedded into a Nordic Semiconductor ASA + * integrated circuit in a product or a software update for such product, must reproduce + * the above copyright notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of Nordic Semiconductor ASA nor the names of its contributors may be + * used to endorse or promote products derived from this software without specific prior + * written permission. + * + * 4. This software, with or without modification, must only be used with a + * Nordic Semiconductor ASA integrated circuit. + * + * 5. Any software provided in binary or object form under this license must not be reverse + * engineered, decompiled, modified and/or disassembled. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ +#ifndef MBED_CONF_RTOS_PRESENT + +#include "sdk_common.h" +#if NRF_MODULE_ENABLED(APP_TIMER) +#include "app_timer.h" +#include +#include "nrf.h" +#include "nrf_soc.h" +#include "app_error.h" +#include "nrf_delay.h" +#include "app_util_platform.h" + +#define RTC1_IRQ_PRI APP_IRQ_PRIORITY_LOWEST /**< Priority of the RTC1 interrupt (used for checking for timeouts and executing timeout handlers). */ +#define SWI_IRQ_PRI APP_IRQ_PRIORITY_LOWEST /**< Priority of the SWI interrupt (used for updating the timer list). */ + +// The current design assumes that both interrupt handlers run at the same interrupt level. +// If this is to be changed, protection must be added to prevent them from interrupting each other +// (e.g. by using guard/trigger flags). +STATIC_ASSERT(RTC1_IRQ_PRI == SWI_IRQ_PRI); + +#define MAX_RTC_COUNTER_VAL 0x00FFFFFF /**< Maximum value of the RTC counter. */ + +#define RTC_COMPARE_OFFSET_MIN 3 /**< Minimum offset between the current RTC counter value and the Capture Compare register. Although the nRF51 Series User Specification recommends this value to be 2, we use 3 to be safer.*/ + +#define MAX_RTC_TASKS_DELAY 47 /**< Maximum delay until an RTC task is executed. */ + +#define SWI_IRQn SWI0_IRQn +#define SWI_IRQHandler SWI0_IRQHandler + +#define MODULE_INITIALIZED (m_op_queue.p_user_op_queue != NULL) /**< Macro designating whether the module has been initialized properly. */ + +/**@brief Timer node type. The nodes will be used form a linked list of running timers. */ +typedef struct +{ + uint32_t ticks_to_expire; /**< Number of ticks from previous timer interrupt to timer expiry. */ + uint32_t ticks_at_start; /**< Current RTC counter value when the timer was started. */ + uint32_t ticks_first_interval; /**< Number of ticks in the first timer interval. */ + uint32_t ticks_periodic_interval; /**< Timer period (for repeating timers). */ + bool is_running; /**< True if timer is running, False otherwise. */ + app_timer_mode_t mode; /**< Timer mode. */ + app_timer_timeout_handler_t p_timeout_handler; /**< Pointer to function to be executed when the timer expires. */ + void * p_context; /**< General purpose pointer. Will be passed to the timeout handler when the timer expires. */ + void * next; /**< Pointer to the next node. */ +} timer_node_t; + +STATIC_ASSERT(sizeof(timer_node_t) == APP_TIMER_NODE_SIZE); + +/**@brief Set of available timer operation types. */ +typedef enum +{ + TIMER_USER_OP_TYPE_NONE, /**< Invalid timer operation type. */ + TIMER_USER_OP_TYPE_START, /**< Timer operation type Start. */ + TIMER_USER_OP_TYPE_STOP, /**< Timer operation type Stop. */ + TIMER_USER_OP_TYPE_STOP_ALL /**< Timer operation type Stop All. */ +} timer_user_op_type_t; + +/**@brief Structure describing a timer start operation. */ +typedef struct +{ + uint32_t ticks_at_start; /**< Current RTC counter value when the timer was started. */ + uint32_t ticks_first_interval; /**< Number of ticks in the first timer interval. */ + uint32_t ticks_periodic_interval; /**< Timer period (for repeating timers). */ + void * p_context; /**< General purpose pointer. Will be passed to the timeout handler when the timer expires. */ +} timer_user_op_start_t; + +/**@brief Structure describing a timer operation. */ +typedef struct +{ + timer_user_op_type_t op_type; /**< Id of timer on which the operation is to be performed. */ + timer_node_t * p_node; + union + { + timer_user_op_start_t start; /**< Structure describing a timer start operation. */ + } params; +} timer_user_op_t; + +STATIC_ASSERT(sizeof(timer_user_op_t) <= APP_TIMER_USER_OP_SIZE); +STATIC_ASSERT(sizeof(timer_user_op_t) % 4 == 0); + +/**@brief Structure describing a timer operations queue. + * + * @details This queue will hold timer operations issued by the application + * until the timer interrupt handler processes these operations. + */ +typedef struct +{ + uint8_t first; /**< Index of first entry to have been inserted in the queue (i.e. the next entry to be executed). */ + uint8_t last; /**< Index of last entry to have been inserted in the queue. */ + uint8_t size; /**< Queue size. */ + timer_user_op_t * p_user_op_queue; /**< Queue buffer. */ +} timer_op_queue_t; + +STATIC_ASSERT(sizeof(timer_op_queue_t) % 4 == 0); + +#define CONTEXT_QUEUE_SIZE_MAX (2) + +static timer_op_queue_t m_op_queue; /**< Timer operations queue. */ +static timer_node_t * mp_timer_id_head; /**< First timer in list of running timers. */ +static uint32_t m_ticks_latest; /**< Last known RTC counter value. */ +static uint32_t m_ticks_elapsed[CONTEXT_QUEUE_SIZE_MAX]; /**< Timer internal elapsed ticks queue. */ +static uint8_t m_ticks_elapsed_q_read_ind; /**< Timer internal elapsed ticks queue read index. */ +static uint8_t m_ticks_elapsed_q_write_ind; /**< Timer internal elapsed ticks queue write index. */ +static app_timer_evt_schedule_func_t m_evt_schedule_func; /**< Pointer to function for propagating timeout events to the scheduler. */ +static bool m_rtc1_running; /**< Boolean indicating if RTC1 is running. */ +static bool m_rtc1_reset; /**< Boolean indicating if RTC1 counter has been reset due to last timer removed from timer list during the timer list handling. */ + +#if APP_TIMER_WITH_PROFILER +static uint8_t m_max_user_op_queue_utilization; /**< Maximum observed timer user operations queue utilization. */ +#endif + +/**@brief Function for initializing the RTC1 counter. + * + * @param[in] prescaler Value of the RTC1 PRESCALER register. Set to 0 for no prescaling. + */ +static void rtc1_init(uint32_t prescaler) +{ + NRF_RTC1->PRESCALER = prescaler; + NVIC_SetPriority(RTC1_IRQn, RTC1_IRQ_PRI); +} + + +/**@brief Function for starting the RTC1 timer. + */ +static void rtc1_start(void) +{ + NRF_RTC1->EVTENSET = RTC_EVTEN_COMPARE0_Msk; + NRF_RTC1->INTENSET = RTC_INTENSET_COMPARE0_Msk; + + NVIC_ClearPendingIRQ(RTC1_IRQn); + NVIC_EnableIRQ(RTC1_IRQn); + + NRF_RTC1->TASKS_START = 1; + nrf_delay_us(MAX_RTC_TASKS_DELAY); + + m_rtc1_running = true; +} + + +/**@brief Function for stopping the RTC1 timer. + */ +static void rtc1_stop(void) +{ + NVIC_DisableIRQ(RTC1_IRQn); + + NRF_RTC1->EVTENCLR = RTC_EVTEN_COMPARE0_Msk; + NRF_RTC1->INTENCLR = RTC_INTENSET_COMPARE0_Msk; + + NRF_RTC1->TASKS_STOP = 1; + nrf_delay_us(MAX_RTC_TASKS_DELAY); + + NRF_RTC1->TASKS_CLEAR = 1; + m_ticks_latest = 0; + nrf_delay_us(MAX_RTC_TASKS_DELAY); + + m_rtc1_running = false; +} + + +/**@brief Function for returning the current value of the RTC1 counter. + * + * @return Current value of the RTC1 counter. + */ +static __INLINE uint32_t rtc1_counter_get(void) +{ + return NRF_RTC1->COUNTER; +} + + +/**@brief Function for computing the difference between two RTC1 counter values. + * + * @return Number of ticks elapsed from ticks_old to ticks_now. + */ +static __INLINE uint32_t ticks_diff_get(uint32_t ticks_now, uint32_t ticks_old) +{ + return ((ticks_now - ticks_old) & MAX_RTC_COUNTER_VAL); +} + + +/**@brief Function for setting the RTC1 Capture Compare register 0, and enabling the corresponding + * event. + * + * @param[in] value New value of Capture Compare register 0. + */ +static __INLINE void rtc1_compare0_set(uint32_t value) +{ + NRF_RTC1->CC[0] = value; +} + + +/**@brief Function for inserting a timer in the timer list. + * + * @param[in] timer_id Id of timer to insert. + */ +static void timer_list_insert(timer_node_t * p_timer) +{ + if (mp_timer_id_head == NULL) + { + mp_timer_id_head = p_timer; + } + else + { + if (p_timer->ticks_to_expire <= mp_timer_id_head->ticks_to_expire) + { + mp_timer_id_head->ticks_to_expire -= p_timer->ticks_to_expire; + + p_timer->next = mp_timer_id_head; + mp_timer_id_head = p_timer; + } + else + { + timer_node_t * p_previous; + timer_node_t * p_current; + uint32_t ticks_to_expire; + + ticks_to_expire = p_timer->ticks_to_expire; + p_previous = mp_timer_id_head; + p_current = mp_timer_id_head; + + while ((p_current != NULL) && (ticks_to_expire > p_current->ticks_to_expire)) + { + ticks_to_expire -= p_current->ticks_to_expire; + p_previous = p_current; + p_current = p_current->next; + } + + if (p_current != NULL) + { + p_current->ticks_to_expire -= ticks_to_expire; + } + + p_timer->ticks_to_expire = ticks_to_expire; + p_timer->next = p_current; + p_previous->next = p_timer; + } + } +} + + +/**@brief Function for removing a timer from the timer queue. + * + * @param[in] timer_id Id of timer to remove. + */ +static void timer_list_remove(timer_node_t * p_timer) +{ + timer_node_t * p_previous; + timer_node_t * p_current; + uint32_t timeout; + + // Find the timer's position in timer list. + p_previous = mp_timer_id_head; + p_current = p_previous; + + while (p_current != NULL) + { + if (p_current == p_timer) + { + break; + } + p_previous = p_current; + p_current = p_current->next; + } + + // Timer not in active list. + if (p_current == NULL) + { + return; + } + + // Timer is the first in the list + if (p_previous == p_current) + { + mp_timer_id_head = mp_timer_id_head->next; + + // No more timers in the list. Reset RTC1 in case Start timer operations are present in the queue. + if (mp_timer_id_head == NULL) + { + NRF_RTC1->TASKS_CLEAR = 1; + m_ticks_latest = 0; + m_rtc1_reset = true; + } + } + + // Remaining timeout between next timeout. + timeout = p_current->ticks_to_expire; + + // Link previous timer with next of this timer, i.e. removing the timer from list. + p_previous->next = p_current->next; + + // If this is not the last timer, increment the next timer by this timer timeout. + p_current = p_previous->next; + if (p_current != NULL) + { + p_current->ticks_to_expire += timeout; + } +} + + +/**@brief Function for scheduling a check for timeouts by generating a RTC1 interrupt. + */ +static void timer_timeouts_check_sched(void) +{ + NVIC_SetPendingIRQ(RTC1_IRQn); +} + + +/**@brief Function for scheduling a timer list update by generating a SWI interrupt. + */ +static void timer_list_handler_sched(void) +{ + NVIC_SetPendingIRQ(SWI_IRQn); +} + + +/**@brief Function for executing an application timeout handler, either by calling it directly, or + * by passing an event to the @ref app_scheduler. + * + * @param[in] p_timer Pointer to expired timer. + */ +static void timeout_handler_exec(timer_node_t * p_timer) +{ + if (m_evt_schedule_func != NULL) + { + uint32_t err_code = m_evt_schedule_func(p_timer->p_timeout_handler, p_timer->p_context); + APP_ERROR_CHECK(err_code); + } + else + { + p_timer->p_timeout_handler(p_timer->p_context); + } +} + + +/**@brief Function for checking for expired timers. + */ +static void timer_timeouts_check(void) +{ + // Handle expired of timer + if (mp_timer_id_head != NULL) + { + timer_node_t * p_timer; + timer_node_t * p_previous_timer; + uint32_t ticks_elapsed; + uint32_t ticks_expired; + + // Initialize actual elapsed ticks being consumed to 0. + ticks_expired = 0; + + // ticks_elapsed is collected here, job will use it. + ticks_elapsed = ticks_diff_get(rtc1_counter_get(), m_ticks_latest); + + // Auto variable containing the head of timers expiring. + p_timer = mp_timer_id_head; + + // Expire all timers within ticks_elapsed and collect ticks_expired. + while (p_timer != NULL) + { + // Do nothing if timer did not expire. + if (ticks_elapsed < p_timer->ticks_to_expire) + { + break; + } + + // Decrement ticks_elapsed and collect expired ticks. + ticks_elapsed -= p_timer->ticks_to_expire; + ticks_expired += p_timer->ticks_to_expire; + + // Move to next timer. + p_previous_timer = p_timer; + p_timer = p_timer->next; + + // Execute Task. + if (p_previous_timer->is_running) + { + p_previous_timer->is_running = false; + timeout_handler_exec(p_previous_timer); + } + } + + // Prepare to queue the ticks expired in the m_ticks_elapsed queue. + if (m_ticks_elapsed_q_read_ind == m_ticks_elapsed_q_write_ind) + { + // The read index of the queue is equal to the write index. This means the new + // value of ticks_expired should be stored at a new location in the m_ticks_elapsed + // queue (which is implemented as a double buffer). + + // Check if there will be a queue overflow. + if (++m_ticks_elapsed_q_write_ind == CONTEXT_QUEUE_SIZE_MAX) + { + // There will be a queue overflow. Hence the write index should point to the start + // of the queue. + m_ticks_elapsed_q_write_ind = 0; + } + } + + // Queue the ticks expired. + m_ticks_elapsed[m_ticks_elapsed_q_write_ind] = ticks_expired; + + timer_list_handler_sched(); + } +} + + +/**@brief Function for acquiring the number of ticks elapsed. + * + * @param[out] p_ticks_elapsed Number of ticks elapsed. + * + * @return TRUE if elapsed ticks was read from queue, FALSE otherwise. + */ +static bool elapsed_ticks_acquire(uint32_t * p_ticks_elapsed) +{ + // Pick the elapsed value from queue. + if (m_ticks_elapsed_q_read_ind != m_ticks_elapsed_q_write_ind) + { + // Dequeue elapsed value. + m_ticks_elapsed_q_read_ind++; + if (m_ticks_elapsed_q_read_ind == CONTEXT_QUEUE_SIZE_MAX) + { + m_ticks_elapsed_q_read_ind = 0; + } + + *p_ticks_elapsed = m_ticks_elapsed[m_ticks_elapsed_q_read_ind]; + + m_ticks_latest += *p_ticks_elapsed; + m_ticks_latest &= MAX_RTC_COUNTER_VAL; + + return true; + } + else + { + // No elapsed value in queue. + *p_ticks_elapsed = 0; + return false; + } +} + + +/**@brief Function for handling the timer list deletions. + * + * @return TRUE if Capture Compare register must be updated, FALSE otherwise. + */ +static bool list_deletions_handler(void) +{ + timer_node_t * p_timer_old_head; + uint8_t user_ops_first = m_op_queue.first; + + // Remember the old head, so as to decide if new compare needs to be set. + p_timer_old_head = mp_timer_id_head; + + while (user_ops_first != m_op_queue.last) + { + timer_user_op_t * p_user_op = &m_op_queue.p_user_op_queue[user_ops_first]; + + // Traverse to next operation in queue. + user_ops_first++; + if (user_ops_first == m_op_queue.size) + { + user_ops_first = 0; + } + + switch (p_user_op->op_type) + { + case TIMER_USER_OP_TYPE_STOP: + // Delete node if timer is running. + timer_list_remove(p_user_op->p_node); + break; + + case TIMER_USER_OP_TYPE_STOP_ALL: + // Delete list of running timers, and mark all timers as not running. + while (mp_timer_id_head != NULL) + { + timer_node_t * p_head = mp_timer_id_head; + + p_head->is_running = false; + mp_timer_id_head = p_head->next; + } + break; + + default: + // No implementation needed. + break; + } + } + + // Detect change in head of the list. + return (mp_timer_id_head != p_timer_old_head); +} + + +/**@brief Function for updating the timer list for expired timers. + * + * @param[in] ticks_elapsed Number of elapsed ticks. + * @param[in] ticks_previous Previous known value of the RTC counter. + * @param[out] p_restart_list_head List of repeating timers to be restarted. + */ +static void expired_timers_handler(uint32_t ticks_elapsed, + uint32_t ticks_previous, + timer_node_t ** p_restart_list_head) +{ + uint32_t ticks_expired = 0; + + while (mp_timer_id_head != NULL) + { + timer_node_t * p_timer; + timer_node_t * p_timer_expired; + + // Auto variable for current timer node. + p_timer = mp_timer_id_head; + + // Do nothing if timer did not expire + if (ticks_elapsed < p_timer->ticks_to_expire) + { + p_timer->ticks_to_expire -= ticks_elapsed; + break; + } + + // Decrement ticks_elapsed and collect expired ticks. + ticks_elapsed -= p_timer->ticks_to_expire; + ticks_expired += p_timer->ticks_to_expire; + + // Timer expired, set ticks_to_expire zero. + p_timer->ticks_to_expire = 0; + + // Remove the expired timer from head. + p_timer_expired = mp_timer_id_head; + mp_timer_id_head = p_timer->next; + + // Timer will be restarted if periodic. + if (p_timer->ticks_periodic_interval != 0) + { + p_timer->ticks_at_start = (ticks_previous + ticks_expired) & MAX_RTC_COUNTER_VAL; + p_timer->ticks_first_interval = p_timer->ticks_periodic_interval; + p_timer->next = *p_restart_list_head; + *p_restart_list_head = p_timer_expired; + } + } +} + + +/**@brief Function for handling timer list insertions. + * + * @param[in] p_restart_list_head List of repeating timers to be restarted. + * + * @return TRUE if Capture Compare register must be updated, FALSE otherwise. + */ +static bool list_insertions_handler(timer_node_t * p_restart_list_head) +{ + timer_node_t * p_timer_id_old_head; + + // Remember the old head, so as to decide if new compare needs to be set. + p_timer_id_old_head = mp_timer_id_head; + + // Handle insertions of timers. + while ((p_restart_list_head != NULL) || (m_op_queue.first != m_op_queue.last)) + { + timer_node_t * p_timer; + + if (p_restart_list_head != NULL) + { + p_timer = p_restart_list_head; + p_restart_list_head = p_timer->next; + } + else + { + timer_user_op_t * p_user_op = &m_op_queue.p_user_op_queue[m_op_queue.first]; + + m_op_queue.first++; + if (m_op_queue.first == m_op_queue.size) + { + m_op_queue.first = 0; + } + + p_timer = p_user_op->p_node; + + if ((p_user_op->op_type != TIMER_USER_OP_TYPE_START) || p_timer->is_running) + { + continue; + } + + p_timer->ticks_at_start = p_user_op->params.start.ticks_at_start; + p_timer->ticks_first_interval = p_user_op->params.start.ticks_first_interval; + p_timer->ticks_periodic_interval = p_user_op->params.start.ticks_periodic_interval; + p_timer->p_context = p_user_op->params.start.p_context; + + if (m_rtc1_reset) + { + p_timer->ticks_at_start = 0; + } + } + + // Prepare the node to be inserted. + if ( + ((p_timer->ticks_at_start - m_ticks_latest) & MAX_RTC_COUNTER_VAL) + < + (MAX_RTC_COUNTER_VAL / 2) + ) + { + p_timer->ticks_to_expire = ticks_diff_get(p_timer->ticks_at_start, m_ticks_latest) + + p_timer->ticks_first_interval; + } + else + { + uint32_t delta_current_start; + + delta_current_start = ticks_diff_get(m_ticks_latest, p_timer->ticks_at_start); + if (p_timer->ticks_first_interval > delta_current_start) + { + p_timer->ticks_to_expire = p_timer->ticks_first_interval - delta_current_start; + } + else + { + p_timer->ticks_to_expire = 0; + } + } + + p_timer->ticks_at_start = 0; + p_timer->ticks_first_interval = 0; + p_timer->is_running = true; + p_timer->next = NULL; + + // Insert into list + timer_list_insert(p_timer); + } + + return (mp_timer_id_head != p_timer_id_old_head); +} + + +/**@brief Function for updating the Capture Compare register. + */ +static void compare_reg_update(timer_node_t * p_timer_id_head_old) +{ + // Setup the timeout for timers on the head of the list + if (mp_timer_id_head != NULL) + { + uint32_t ticks_to_expire = mp_timer_id_head->ticks_to_expire; + uint32_t pre_counter_val = rtc1_counter_get(); + uint32_t cc = m_ticks_latest; + uint32_t ticks_elapsed = ticks_diff_get(pre_counter_val, cc) + RTC_COMPARE_OFFSET_MIN; + + if (!m_rtc1_running) + { + // No timers were already running, start RTC + rtc1_start(); + } + + cc += (ticks_elapsed < ticks_to_expire) ? ticks_to_expire : ticks_elapsed; + cc &= MAX_RTC_COUNTER_VAL; + + rtc1_compare0_set(cc); + + uint32_t post_counter_val = rtc1_counter_get(); + + if ( + (ticks_diff_get(post_counter_val, pre_counter_val) + RTC_COMPARE_OFFSET_MIN) + > + ticks_diff_get(cc, pre_counter_val) + ) + { + // When this happens the COMPARE event may not be triggered by the RTC. + // The nRF51 Series User Specification states that if the COUNTER value is N + // (i.e post_counter_val = N), writing N or N + 1 to a CC register may not trigger a + // COMPARE event. Hence the RTC interrupt is forcefully pended by calling the following + // function. + rtc1_compare0_set(rtc1_counter_get()); // this should prevent CC to fire again in the background while the code is in RTC-ISR + nrf_delay_us(MAX_RTC_TASKS_DELAY); + timer_timeouts_check_sched(); + } + } + else + { +#if (APP_TIMER_KEEPS_RTC_ACTIVE == 0) + // No timers are running, stop RTC + rtc1_stop(); +#endif //(APP_TIMER_KEEPS_RTC_ACTIVE == 0) + } +} + + +/**@brief Function for handling changes to the timer list. + */ +static void timer_list_handler(void) +{ + timer_node_t * p_restart_list_head = NULL; + + uint32_t ticks_elapsed; + uint32_t ticks_previous; + bool ticks_have_elapsed; + bool compare_update; + timer_node_t * p_timer_id_head_old; + +#if APP_TIMER_WITH_PROFILER + { + uint8_t size = m_op_queue.size; + uint8_t first = m_op_queue.first; + uint8_t last = m_op_queue.last; + uint8_t utilization = (first <= last) ? (last - first) : (size + 1 - first + last); + + if (utilization > m_max_user_op_queue_utilization) + { + m_max_user_op_queue_utilization = utilization; + } + } +#endif + + // Back up the previous known tick and previous list head + ticks_previous = m_ticks_latest; + p_timer_id_head_old = mp_timer_id_head; + + // Get number of elapsed ticks + ticks_have_elapsed = elapsed_ticks_acquire(&ticks_elapsed); + + // Handle list deletions + compare_update = list_deletions_handler(); + + // Handle expired timers + if (ticks_have_elapsed) + { + expired_timers_handler(ticks_elapsed, ticks_previous, &p_restart_list_head); + compare_update = true; + } + + // Handle list insertions + if (list_insertions_handler(p_restart_list_head)) + { + compare_update = true; + } + + // Update compare register if necessary + if (compare_update) + { + compare_reg_update(p_timer_id_head_old); + } + m_rtc1_reset = false; +} + + +/**@brief Function for enqueueing a new operations queue entry. + * + * @param[in] last_index Index of the next last index to be enqueued. + */ +static void user_op_enque(uint8_t last_index) +{ + m_op_queue.last = last_index; +} + + +/**@brief Function for allocating a new operations queue entry. + * + * @param[out] p_last_index Index of the next last index to be enqueued. + * + * @return Pointer to allocated queue entry, or NULL if queue is full. + */ +static timer_user_op_t * user_op_alloc( uint8_t * p_last_index) +{ + uint8_t last; + timer_user_op_t * p_user_op; + + last = m_op_queue.last + 1; + if (last == m_op_queue.size) + { + // Overflow case. + last = 0; + } + if (last == m_op_queue.first) + { + // Queue is full. + return NULL; + } + + *p_last_index = last; + p_user_op = &m_op_queue.p_user_op_queue[m_op_queue.last]; + + return p_user_op; +} + + +/**@brief Function for scheduling a Timer Start operation. + * + * @param[in] timer_id Id of timer to start. + * @param[in] timeout_initial Time (in ticks) to first timer expiry. + * @param[in] timeout_periodic Time (in ticks) between periodic expiries. + * @param[in] p_context General purpose pointer. Will be passed to the timeout handler when + * the timer expires. + * @return NRF_SUCCESS on success, otherwise an error code. + */ + +static uint32_t timer_start_op_schedule(timer_node_t * p_node, + uint32_t timeout_initial, + uint32_t timeout_periodic, + void * p_context) +{ + uint8_t last_index; + uint32_t err_code = NRF_SUCCESS; + + CRITICAL_REGION_ENTER(); + timer_user_op_t * p_user_op = user_op_alloc(&last_index); + if (p_user_op == NULL) + { + err_code = NRF_ERROR_NO_MEM; + } + else + { + + p_user_op->op_type = TIMER_USER_OP_TYPE_START; + p_user_op->p_node = p_node; + p_user_op->params.start.ticks_at_start = rtc1_counter_get(); + p_user_op->params.start.ticks_first_interval = timeout_initial; + p_user_op->params.start.ticks_periodic_interval = timeout_periodic; + p_user_op->params.start.p_context = p_context; + + user_op_enque(last_index); + } + CRITICAL_REGION_EXIT(); + + if (err_code == NRF_SUCCESS) + { + timer_list_handler_sched(); + } + + return err_code; +} + + +/**@brief Function for scheduling a Timer Stop operation. + * + * @param[in] timer_id Id of timer to stop. + * @param[in] op_type Type of stop operation + * + * @return NRF_SUCCESS on successful scheduling a timer stop operation. NRF_ERROR_NO_MEM when there + * is no memory left to schedule the timer stop operation. + */ +static uint32_t timer_stop_op_schedule(timer_node_t * p_node, + timer_user_op_type_t op_type) +{ + uint8_t last_index; + uint32_t err_code = NRF_SUCCESS; + + CRITICAL_REGION_ENTER(); + timer_user_op_t * p_user_op = user_op_alloc(&last_index); + if (p_user_op == NULL) + { + err_code = NRF_ERROR_NO_MEM; + } + else + { + p_user_op->op_type = op_type; + p_user_op->p_node = p_node; + + user_op_enque(last_index); + } + CRITICAL_REGION_EXIT(); + + if (err_code == NRF_SUCCESS) + { + timer_list_handler_sched(); + } + + return err_code; +} + +/**@brief Function for handling the RTC1 interrupt. + * + * @details Checks for timeouts, and executes timeout handlers for expired timers. + */ +void RTC1_IRQHandler(void) +{ + // Clear all events (also unexpected ones) + NRF_RTC1->EVENTS_COMPARE[0] = 0; + NRF_RTC1->EVENTS_COMPARE[1] = 0; + NRF_RTC1->EVENTS_COMPARE[2] = 0; + NRF_RTC1->EVENTS_COMPARE[3] = 0; + NRF_RTC1->EVENTS_TICK = 0; + NRF_RTC1->EVENTS_OVRFLW = 0; + + // Check for expired timers + timer_timeouts_check(); +} + + +/**@brief Function for handling the SWI interrupt. + * + * @details Performs all updates to the timer list. + */ +void SWI_IRQHandler(void) +{ + timer_list_handler(); +} + + +uint32_t app_timer_init(uint32_t prescaler, + uint8_t op_queue_size, + void * p_buffer, + app_timer_evt_schedule_func_t evt_schedule_func) +{ + // Check that buffer is correctly aligned + if (!is_word_aligned(p_buffer)) + { + return NRF_ERROR_INVALID_PARAM; + } + // Check for NULL buffer + if (p_buffer == NULL) + { + return NRF_ERROR_INVALID_PARAM; + } + + // Stop RTC to prevent any running timers from expiring (in case of reinitialization) + rtc1_stop(); + + m_evt_schedule_func = evt_schedule_func; + + // Initialize operation queue + m_op_queue.first = 0; + m_op_queue.last = 0; + m_op_queue.size = op_queue_size; + m_op_queue.p_user_op_queue = p_buffer; + + mp_timer_id_head = NULL; + m_ticks_elapsed_q_read_ind = 0; + m_ticks_elapsed_q_write_ind = 0; + +#if APP_TIMER_WITH_PROFILER + m_max_user_op_queue_utilization = 0; +#endif + + NVIC_ClearPendingIRQ(SWI_IRQn); + NVIC_SetPriority(SWI_IRQn, SWI_IRQ_PRI); + NVIC_EnableIRQ(SWI_IRQn); + + rtc1_init(prescaler); + + m_ticks_latest = rtc1_counter_get(); + + return NRF_SUCCESS; +} + + +uint32_t app_timer_create(app_timer_id_t const * p_timer_id, + app_timer_mode_t mode, + app_timer_timeout_handler_t timeout_handler) +{ + // Check state and parameters + VERIFY_MODULE_INITIALIZED(); + + if (timeout_handler == NULL) + { + return NRF_ERROR_INVALID_PARAM; + } + if (p_timer_id == NULL) + { + return NRF_ERROR_INVALID_PARAM; + } + if (((timer_node_t*)*p_timer_id)->is_running) + { + return NRF_ERROR_INVALID_STATE; + } + + timer_node_t * p_node = (timer_node_t *)*p_timer_id; + p_node->is_running = false; + p_node->mode = mode; + p_node->p_timeout_handler = timeout_handler; + return NRF_SUCCESS; +} + +uint32_t app_timer_start(app_timer_id_t timer_id, uint32_t timeout_ticks, void * p_context) +{ + uint32_t timeout_periodic; + timer_node_t * p_node = (timer_node_t*)timer_id; + + // Check state and parameters + VERIFY_MODULE_INITIALIZED(); + + if (timer_id == 0) + { + return NRF_ERROR_INVALID_STATE; + } + if (timeout_ticks < APP_TIMER_MIN_TIMEOUT_TICKS) + { + return NRF_ERROR_INVALID_PARAM; + } + if (p_node->p_timeout_handler == NULL) + { + return NRF_ERROR_INVALID_STATE; + } + + // Schedule timer start operation + timeout_periodic = (p_node->mode == APP_TIMER_MODE_REPEATED) ? timeout_ticks : 0; + + return timer_start_op_schedule(p_node, + timeout_ticks, + timeout_periodic, + p_context); +} + + +uint32_t app_timer_stop(app_timer_id_t timer_id) +{ + timer_node_t * p_node = (timer_node_t*)timer_id; + // Check state and parameters + VERIFY_MODULE_INITIALIZED(); + + if ((timer_id == NULL) || (p_node->p_timeout_handler == NULL)) + { + return NRF_ERROR_INVALID_STATE; + } + + p_node->is_running = false; + // Schedule timer stop operation + return timer_stop_op_schedule(p_node, TIMER_USER_OP_TYPE_STOP); +} + + +uint32_t app_timer_stop_all(void) +{ + // Check state + VERIFY_MODULE_INITIALIZED(); + + return timer_stop_op_schedule(NULL, TIMER_USER_OP_TYPE_STOP_ALL); +} + + +uint32_t app_timer_cnt_get(void) +{ + return rtc1_counter_get(); +} + + +uint32_t app_timer_cnt_diff_compute(uint32_t ticks_to, + uint32_t ticks_from, + uint32_t * p_ticks_diff) +{ + *p_ticks_diff = ticks_diff_get(ticks_to, ticks_from); + return NRF_SUCCESS; +} + +#if APP_TIMER_WITH_PROFILER +uint8_t app_timer_op_queue_utilization_get(void) +{ + return m_max_user_op_queue_utilization; +} +#endif +#endif //NRF_MODULE_ENABLED(APP_TIMER) +#endif // MBED_CONF_RTOS_PRESENT diff --git a/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/timer/app_timer.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/timer/app_timer.h new file mode 100644 index 00000000000..cc4e104bed8 --- /dev/null +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/timer/app_timer.h @@ -0,0 +1,321 @@ +/* + * Copyright (c) 2012 Nordic Semiconductor ASA + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * 2. Redistributions in binary form, except as embedded into a Nordic Semiconductor ASA + * integrated circuit in a product or a software update for such product, must reproduce + * the above copyright notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of Nordic Semiconductor ASA nor the names of its contributors may be + * used to endorse or promote products derived from this software without specific prior + * written permission. + * + * 4. This software, with or without modification, must only be used with a + * Nordic Semiconductor ASA integrated circuit. + * + * 5. Any software provided in binary or object form under this license must not be reverse + * engineered, decompiled, modified and/or disassembled. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +/** @file + * + * @defgroup app_timer Application Timer + * @{ + * @ingroup app_common + * + * @brief Application timer functionality. + * + * @details This module enables the application to create multiple timer instances based on the RTC1 + * peripheral. Checking for time-outs and invocation of user time-out handlers is performed + * in the RTC1 interrupt handler. List handling is done using a software interrupt (SWI0). + * Both interrupt handlers are running in APP_LOW priority level. + * + * @details When calling app_timer_start() or app_timer_stop(), the timer operation is just queued, + * and the software interrupt is triggered. The actual timer start/stop operation is + * executed by the SWI0 interrupt handler. Since the SWI0 interrupt is running in APP_LOW, + * if the application code calling the timer function is running in APP_LOW or APP_HIGH, + * the timer operation will not be performed until the application handler has returned. + * This will be the case, for example, when stopping a timer from a time-out handler when not using + * the scheduler. + * + * @details Use the USE_SCHEDULER parameter of the APP_TIMER_INIT() macro to select if the + * @ref app_scheduler should be used or not. Even if the scheduler is + * not used, app_timer.h will include app_scheduler.h, so when + * compiling, app_scheduler.h must be available in one of the compiler include paths. + */ + +#ifndef APP_TIMER_H__ +#define APP_TIMER_H__ +#include "sdk_config.h" +#include "app_error.h" +#include "app_util.h" +#include "compiler_abstraction.h" +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define APP_TIMER_CLOCK_FREQ 32768 /**< Clock frequency of the RTC timer used to implement the app timer module. */ +#define APP_TIMER_MIN_TIMEOUT_TICKS 5 /**< Minimum value of the timeout_ticks parameter of app_timer_start(). */ + +#ifdef RTX +#define APP_TIMER_NODE_SIZE 40 /**< Size of app_timer.timer_node_t (used to allocate data). */ +#else +#define APP_TIMER_NODE_SIZE 32 /**< Size of app_timer.timer_node_t (used to allocate data). */ +#endif // RTX +#define APP_TIMER_USER_OP_SIZE 24 /**< Size of app_timer.timer_user_op_t (only for use inside APP_TIMER_BUF_SIZE()). */ + +/**@brief Compute number of bytes required to hold the application timer data structures. + * + * @param[in] OP_QUEUE_SIZE Size of the queue holding timer operations that are pending execution. + * Note that due to the queue implementation, this size must be one more + * than the size that is actually needed. + * + * @return Required application timer buffer size (in bytes). + */ +#define APP_TIMER_BUF_SIZE(OP_QUEUE_SIZE) \ + ( \ + ( \ + (((OP_QUEUE_SIZE) + 1) * APP_TIMER_USER_OP_SIZE) \ + ) \ + ) + +/**@brief Convert milliseconds to timer ticks. + * + * This macro uses 64-bit integer arithmetic, but as long as the macro parameters are + * constants (i.e. defines), the computation will be done by the preprocessor. + * + * When using this macro, ensure that the + * values provided as input result in an output value that is supported by the + * @ref app_timer_start function. For example, when the ticks for 1 ms is needed, the + * maximum possible value of PRESCALER must be 6, when @ref APP_TIMER_CLOCK_FREQ is 32768. + * This will result in a ticks value as 5. Any higher value for PRESCALER will result in a + * ticks value that is not supported by this module. + * + * @param[in] MS Milliseconds. + * @param[in] PRESCALER Value of the RTC1 PRESCALER register (must be the same value that was + * passed to APP_TIMER_INIT()). + * + * @return Number of timer ticks. + */ +#define APP_TIMER_TICKS(MS, PRESCALER)\ + ((uint32_t)ROUNDED_DIV((MS) * (uint64_t)APP_TIMER_CLOCK_FREQ, ((PRESCALER) + 1) * 1000)) + +typedef struct app_timer_t { uint32_t data[CEIL_DIV(APP_TIMER_NODE_SIZE, sizeof(uint32_t))]; } app_timer_t; + +/**@brief Timer ID type. + * Never declare a variable of this type, but use the macro @ref APP_TIMER_DEF instead.*/ +typedef app_timer_t * app_timer_id_t; + +/** + * @brief Create a timer identifier and statically allocate memory for the timer. + * + * @param timer_id Name of the timer identifier variable that will be used to control the timer. + */ +#define APP_TIMER_DEF(timer_id) \ + static app_timer_t timer_id##_data = { {0} }; \ + static const app_timer_id_t timer_id = &timer_id##_data + + +/**@brief Application time-out handler type. */ +typedef void (*app_timer_timeout_handler_t)(void * p_context); + +/**@brief Type of function for passing events from the timer module to the scheduler. */ +typedef uint32_t (*app_timer_evt_schedule_func_t) (app_timer_timeout_handler_t timeout_handler, + void * p_context); + +/**@brief Timer modes. */ +typedef enum +{ + APP_TIMER_MODE_SINGLE_SHOT, /**< The timer will expire only once. */ + APP_TIMER_MODE_REPEATED /**< The timer will restart each time it expires. */ +} app_timer_mode_t; + +/**@brief Initialize the application timer module. + * + * @details This macro handles dimensioning and allocation of the memory buffer required by the timer, + * making sure that the buffer is correctly aligned. It will also connect the timer module + * to the scheduler (if specified). + * + * @note This module assumes that the LFCLK is already running. If it is not, the module will + * be non-functional, since the RTC will not run. If you do not use a SoftDevice, you + * must start the LFCLK manually. See the rtc_example's lfclk_config() function + * for an example of how to do this. If you use a SoftDevice, the LFCLK is started on + * SoftDevice init. + * + * + * @param[in] PRESCALER Value of the RTC1 PRESCALER register. This will decide the + * timer tick rate. Set to 0 for no prescaling. + * @param[in] OP_QUEUE_SIZE Size of the queue holding timer operations that are pending execution. + * @param[in] SCHEDULER_FUNC Pointer to scheduler event handler + * + * @note Since this macro allocates a buffer, it must only be called once (it is OK to call it + * several times as long as it is from the same location, for example, to do a re-initialization). + */ +/*lint -emacro(506, APP_TIMER_INIT) */ /* Suppress "Constant value Boolean */ +#define APP_TIMER_INIT(PRESCALER, OP_QUEUE_SIZE, SCHEDULER_FUNC) \ + do \ + { \ + static uint32_t APP_TIMER_BUF[CEIL_DIV(APP_TIMER_BUF_SIZE(OP_QUEUE_SIZE), \ + sizeof(uint32_t))]; \ + uint32_t ERR_CODE = app_timer_init((PRESCALER), \ + (OP_QUEUE_SIZE) + 1, \ + APP_TIMER_BUF, \ + SCHEDULER_FUNC); \ + APP_ERROR_CHECK(ERR_CODE); \ + } while (0) + + + +/**@brief Function for initializing the timer module. + * + * Normally, initialization should be done using the APP_TIMER_INIT() macro, because that macro will both + * allocate the buffers needed by the timer module (including aligning the buffers correctly) + * and take care of connecting the timer module to the scheduler (if specified). + * + * @param[in] prescaler Value of the RTC1 PRESCALER register. Set to 0 for no prescaling. + * @param[in] op_queue_size Size of the queue holding timer operations that are pending + * execution. Note that due to the queue implementation, this size must + * be one more than the size that is actually needed. + * @param[in] p_buffer Pointer to memory buffer for internal use in the app_timer + * module. The size of the buffer can be computed using the + * APP_TIMER_BUF_SIZE() macro. The buffer must be aligned to a + * 4 byte boundary. + * @param[in] evt_schedule_func Function for passing time-out events to the scheduler. Point to + * app_timer_evt_schedule() to connect to the scheduler. Set to NULL + * to make the timer module call the time-out handler directly from + * the timer interrupt handler. + * + * @retval NRF_SUCCESS If the module was initialized successfully. + * @retval NRF_ERROR_INVALID_PARAM If a parameter was invalid (buffer not aligned to a 4 byte + * boundary or NULL). + */ +uint32_t app_timer_init(uint32_t prescaler, + uint8_t op_queue_size, + void * p_buffer, + app_timer_evt_schedule_func_t evt_schedule_func); + +/**@brief Function for creating a timer instance. + * + * @param[in] p_timer_id Pointer to timer identifier. + * @param[in] mode Timer mode. + * @param[in] timeout_handler Function to be executed when the timer expires. + * + * @retval NRF_SUCCESS If the timer was successfully created. + * @retval NRF_ERROR_INVALID_PARAM If a parameter was invalid. + * @retval NRF_ERROR_INVALID_STATE If the application timer module has not been initialized or + * the timer is running. + * + * @note This function does the timer allocation in the caller's context. It is also not protected + * by a critical region. Therefore care must be taken not to call it from several interrupt + * levels simultaneously. + * @note The function can be called again on the timer instance and will re-initialize the instance if + * the timer is not running. + * @attention The FreeRTOS and RTX app_timer implementation does not allow app_timer_create to + * be called on the previously initialized instance. + */ +uint32_t app_timer_create(app_timer_id_t const * p_timer_id, + app_timer_mode_t mode, + app_timer_timeout_handler_t timeout_handler); + +/**@brief Function for starting a timer. + * + * @param[in] timer_id Timer identifier. + * @param[in] timeout_ticks Number of ticks (of RTC1, including prescaling) to time-out event + * (minimum 5 ticks). + * @param[in] p_context General purpose pointer. Will be passed to the time-out handler when + * the timer expires. + * + * @retval NRF_SUCCESS If the timer was successfully started. + * @retval NRF_ERROR_INVALID_PARAM If a parameter was invalid. + * @retval NRF_ERROR_INVALID_STATE If the application timer module has not been initialized or the timer + * has not been created. + * @retval NRF_ERROR_NO_MEM If the timer operations queue was full. + * + * @note The minimum timeout_ticks value is 5. + * @note For multiple active timers, time-outs occurring in close proximity to each other (in the + * range of 1 to 3 ticks) will have a positive jitter of maximum 3 ticks. + * @note When calling this method on a timer that is already running, the second start operation + * is ignored. + */ +uint32_t app_timer_start(app_timer_id_t timer_id, uint32_t timeout_ticks, void * p_context); + +/**@brief Function for stopping the specified timer. + * + * @param[in] timer_id Timer identifier. + * + * @retval NRF_SUCCESS If the timer was successfully stopped. + * @retval NRF_ERROR_INVALID_PARAM If a parameter was invalid. + * @retval NRF_ERROR_INVALID_STATE If the application timer module has not been initialized or the timer + * has not been created. + * @retval NRF_ERROR_NO_MEM If the timer operations queue was full. + */ +uint32_t app_timer_stop(app_timer_id_t timer_id); + +/**@brief Function for stopping all running timers. + * + * @retval NRF_SUCCESS If all timers were successfully stopped. + * @retval NRF_ERROR_INVALID_STATE If the application timer module has not been initialized. + * @retval NRF_ERROR_NO_MEM If the timer operations queue was full. + */ +uint32_t app_timer_stop_all(void); + +/**@brief Function for returning the current value of the RTC1 counter. + * + * @return Current value of the RTC1 counter. + */ +uint32_t app_timer_cnt_get(void); + +/**@brief Function for computing the difference between two RTC1 counter values. + * + * @param[in] ticks_to Value returned by app_timer_cnt_get(). + * @param[in] ticks_from Value returned by app_timer_cnt_get(). + * @param[out] p_ticks_diff Number of ticks from ticks_from to ticks_to. + * + * @retval NRF_SUCCESS If the counter difference was successfully computed. + */ +uint32_t app_timer_cnt_diff_compute(uint32_t ticks_to, + uint32_t ticks_from, + uint32_t * p_ticks_diff); + + +/**@brief Function for getting the maximum observed operation queue utilization. + * + * Function for tuning the module and determining OP_QUEUE_SIZE value and thus module RAM usage. + * + * @note APP_TIMER_WITH_PROFILER must be enabled to use this functionality. + * + * @return Maximum number of events in queue observed so far. + */ +uint8_t app_timer_op_queue_utilization_get(void); + + +#ifdef __cplusplus +} +#endif + +#endif // APP_TIMER_H__ + +/** @} */ diff --git a/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/timer/app_timer_appsh.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/timer/app_timer_appsh.c new file mode 100644 index 00000000000..b3df7095b92 --- /dev/null +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/timer/app_timer_appsh.c @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2014 Nordic Semiconductor ASA + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * 2. Redistributions in binary form, except as embedded into a Nordic Semiconductor ASA + * integrated circuit in a product or a software update for such product, must reproduce + * the above copyright notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of Nordic Semiconductor ASA nor the names of its contributors may be + * used to endorse or promote products derived from this software without specific prior + * written permission. + * + * 4. This software, with or without modification, must only be used with a + * Nordic Semiconductor ASA integrated circuit. + * + * 5. Any software provided in binary or object form under this license must not be reverse + * engineered, decompiled, modified and/or disassembled. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#include "app_timer_appsh.h" +#include "app_scheduler.h" + +static void app_timer_evt_get(void * p_event_data, uint16_t event_size) +{ + app_timer_event_t * p_timer_event = (app_timer_event_t *)p_event_data; + + APP_ERROR_CHECK_BOOL(event_size == sizeof(app_timer_event_t)); + p_timer_event->timeout_handler(p_timer_event->p_context); +} + +uint32_t app_timer_evt_schedule(app_timer_timeout_handler_t timeout_handler, + void * p_context) +{ + app_timer_event_t timer_event; + + timer_event.timeout_handler = timeout_handler; + timer_event.p_context = p_context; + + return app_sched_event_put(&timer_event, sizeof(timer_event), app_timer_evt_get); +} + diff --git a/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/timer/app_timer_appsh.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/timer/app_timer_appsh.h new file mode 100644 index 00000000000..bcefc13580b --- /dev/null +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/timer/app_timer_appsh.h @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2014 Nordic Semiconductor ASA + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * 2. Redistributions in binary form, except as embedded into a Nordic Semiconductor ASA + * integrated circuit in a product or a software update for such product, must reproduce + * the above copyright notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of Nordic Semiconductor ASA nor the names of its contributors may be + * used to endorse or promote products derived from this software without specific prior + * written permission. + * + * 4. This software, with or without modification, must only be used with a + * Nordic Semiconductor ASA integrated circuit. + * + * 5. Any software provided in binary or object form under this license must not be reverse + * engineered, decompiled, modified and/or disassembled. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + + #ifndef APP_TIMER_APPSH_H + #define APP_TIMER_APPSH_H + +#include "app_timer.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define APP_TIMER_SCHED_EVT_SIZE sizeof(app_timer_event_t) /**< Size of button events being passed through the scheduler (is to be used for computing the maximum size of scheduler events). */ + +/**@brief Macro for initializing the application timer module to use with app_scheduler. + * + * @param[in] PRESCALER Value of the RTC1 PRESCALER register. This will decide the + * timer tick rate. Set to 0 for no prescaling. + * @param[in] OP_QUEUES_SIZE Size of queues holding timer operations that are pending execution. + * @param[in] USE_SCHEDULER TRUE if the application is using the app_scheduler, + * FALSE otherwise. + * + * @note Since this macro allocates a buffer, it must only be called once (it is OK to call it + * several times as long as it is from the same location, e.g. to do a reinitialization). + */ +#define APP_TIMER_APPSH_INIT(PRESCALER, OP_QUEUES_SIZE, USE_SCHEDULER) \ + APP_TIMER_INIT(PRESCALER, OP_QUEUES_SIZE, \ + (USE_SCHEDULER) ? app_timer_evt_schedule : NULL) + +typedef struct +{ + app_timer_timeout_handler_t timeout_handler; + void * p_context; +} app_timer_event_t; + +uint32_t app_timer_evt_schedule(app_timer_timeout_handler_t timeout_handler, + void * p_context); + +#ifdef __cplusplus +} +#endif + +#endif // APP_TIMER_APPSH_H + diff --git a/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/timer/app_timer_dox_config.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/timer/app_timer_dox_config.h new file mode 100644 index 00000000000..c142cfca406 --- /dev/null +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/timer/app_timer_dox_config.h @@ -0,0 +1,37 @@ +/** + * + * @defgroup app_timer_config Application timer functionality configuration + * @{ + * @ingroup app_timer + */ +/** @brief Enabling app_timer module + * + * Set to 1 to activate. + * + * @note This is an NRF_CONFIG macro. + */ +#define APP_TIMER_ENABLED + +/** @brief Enable app_timer profiling + * + * Set to 1 to activate. + * + * @note This is an NRF_CONFIG macro. + */ +#define APP_TIMER_WITH_PROFILER + + +/** @brief Enable RTC always on + * + * If option is enabled RTC is kept running even if there is no active timers. + * This option can be used when app_timer is used for timestamping. + * + * Set to 1 to activate. + * + * @note This is an NRF_CONFIG macro. + */ +#define APP_TIMER_KEEPS_RTC_ACTIVE + + + +/** @} */ diff --git a/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/timer/app_timer_rtx.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/timer/app_timer_rtx.c new file mode 100644 index 00000000000..acf9e566c56 --- /dev/null +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/timer/app_timer_rtx.c @@ -0,0 +1,285 @@ +/* + * Copyright (c) 2016 Nordic Semiconductor ASA + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * 2. Redistributions in binary form, except as embedded into a Nordic Semiconductor ASA + * integrated circuit in a product or a software update for such product, must reproduce + * the above copyright notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of Nordic Semiconductor ASA nor the names of its contributors may be + * used to endorse or promote products derived from this software without specific prior + * written permission. + * + * 4. This software, with or without modification, must only be used with a + * Nordic Semiconductor ASA integrated circuit. + * + * 5. Any software provided in binary or object form under this license must not be reverse + * engineered, decompiled, modified and/or disassembled. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ +#ifdef MBED_CONF_RTOS_PRESENT + +#include "sdk_common.h" +#if NRF_MODULE_ENABLED(APP_TIMER) +#include "app_timer.h" +#include +#include "nrf.h" +#include "nrf_soc.h" +#include "app_error.h" +#include "cmsis_os.h" +#include "app_util_platform.h" + +#define RTC1_IRQ_PRI APP_IRQ_PRIORITY_LOWEST /**< Priority of the RTC1 interrupt. */ + +#define MAX_RTC_COUNTER_VAL 0x00FFFFFF /**< Maximum value of the RTC counter. */ + +/**@brief This structure keeps information about osTimer.*/ +typedef struct +{ + osTimerDef_t timerDef; + uint32_t buffer[6]; + osTimerId id; +}app_timer_info_t; + +/**@brief Store an array of timers with configuration. */ +typedef struct +{ + uint8_t max_timers; /**< The maximum number of timers*/ + uint32_t prescaler; + app_timer_info_t * app_timers; /**< Pointer to table of timers*/ +}app_timer_control_t; +app_timer_control_t app_timer_control; + +/**@brief This structure is defined by RTX. It keeps information about created osTimers. It is used in app_timer_start(). */ +typedef struct os_timer_cb_ +{ + struct os_timer_cb_ * next; /**< Pointer to next active Timer */ + uint8_t state; /**< Timer State */ + uint8_t type; /**< Timer Type (Periodic/One-shot). */ + uint16_t reserved; /**< Reserved. */ + uint32_t tcnt; /**< Timer Delay Count. */ + uint32_t icnt; /**< Timer Initial Count. */ + void * arg; /**< Timer Function Argument. */ + const osTimerDef_t * timer; /**< Pointer to Timer definition. */ +} os_timer_cb; + +/**@brief This functions are defined by RTX.*/ +//lint --save -e10 -e19 -e526 +extern osStatus svcTimerStop(osTimerId timer_id); /**< Used in app_timer_stop(). */ +extern osStatus svcTimerStart(osTimerId timer_id, uint32_t millisec); /**< Used in app_timer_start(). */ +// lint --restore +static void * rt_id2obj (void *id) /**< Used in app_timer_start(). This function gives information if osTimerID is valid */ +{ + if ((uint32_t)id & 3U) + { + return NULL; + } + +#ifdef OS_SECTIONS_LINK_INFO + + if ((os_section_id$$Base != 0U) && (os_section_id$$Limit != 0U)) + { + if (id < (void *)os_section_id$$Base) + { + return NULL; + } + + if (id >= (void *)os_section_id$$Limit) + { + return NULL; + } + } +#endif + + return id; +} + + + +uint32_t app_timer_init(uint32_t prescaler, + uint8_t op_queues_size, + void * p_buffer, + app_timer_evt_schedule_func_t evt_schedule_func) +{ + if (p_buffer == NULL) + { + return NRF_ERROR_INVALID_PARAM; + } + + app_timer_control.prescaler = prescaler; + app_timer_control.app_timers = p_buffer; + NVIC_SetPriority(RTC1_IRQn, RTC1_IRQ_PRI); + + return NRF_SUCCESS; +} + + +uint32_t app_timer_create(app_timer_id_t const * p_timer_id, + app_timer_mode_t mode, + app_timer_timeout_handler_t timeout_handler) +{ + + if ((timeout_handler == NULL) || (p_timer_id == NULL)) + { + return NRF_ERROR_INVALID_PARAM; + } + + app_timer_info_t * p_timer_info = (app_timer_info_t *)*p_timer_id; + p_timer_info->timerDef.timer = p_timer_info->buffer; + p_timer_info->timerDef.ptimer = (os_ptimer)timeout_handler; + + p_timer_info->id = osTimerCreate(&(p_timer_info->timerDef), (os_timer_type)mode, NULL); + + if (p_timer_info->id) + return NRF_SUCCESS; + else + { + return NRF_ERROR_INVALID_PARAM; // This error is unspecified by rtx + } +} + +#define osTimerRunning 2 +uint32_t app_timer_start(app_timer_id_t timer_id, uint32_t timeout_ticks, void * p_context) +{ + if ((timeout_ticks < APP_TIMER_MIN_TIMEOUT_TICKS)) + { + return NRF_ERROR_INVALID_PARAM; + } + uint32_t timeout_ms = + ((uint32_t)ROUNDED_DIV(timeout_ticks * 1000 * (app_timer_control.prescaler + 1), + (uint32_t)APP_TIMER_CLOCK_FREQ)); + + app_timer_info_t * p_timer_info = (app_timer_info_t *)timer_id; + if (rt_id2obj((void *)p_timer_info->id) == NULL) + return NRF_ERROR_INVALID_PARAM; + + // Pass p_context to timer_timeout_handler + ((os_timer_cb *)(p_timer_info->id))->arg = p_context; + + if (((os_timer_cb *)(p_timer_info->id))->state == osTimerRunning) + { + return NRF_SUCCESS; + } + // osTimerStart() returns osErrorISR if it is called in interrupt routine. + switch (osTimerStart((osTimerId)p_timer_info->id, timeout_ms) ) + { + case osOK: + return NRF_SUCCESS; + + case osErrorISR: + break; + + case osErrorParameter: + return NRF_ERROR_INVALID_PARAM; + + default: + return NRF_ERROR_INVALID_PARAM; + } + + // Start timer without svcCall + switch (svcTimerStart((osTimerId)p_timer_info->id, timeout_ms)) + { + case osOK: + return NRF_SUCCESS; + + case osErrorISR: + return NRF_ERROR_INVALID_STATE; + + case osErrorParameter: + return NRF_ERROR_INVALID_PARAM; + + default: + return NRF_ERROR_INVALID_PARAM; + } +} + +uint32_t app_timer_stop(app_timer_id_t timer_id) +{ + app_timer_info_t * p_timer_info = (app_timer_info_t *)timer_id; + switch (osTimerStop((osTimerId)p_timer_info->id) ) + { + case osOK: + return NRF_SUCCESS; + + case osErrorISR: + break; + + case osErrorParameter: + return NRF_ERROR_INVALID_PARAM; + + case osErrorResource: + return NRF_SUCCESS; + + default: + return NRF_ERROR_INVALID_PARAM; + } + + // Stop timer without svcCall + switch (svcTimerStop((osTimerId)p_timer_info->id)) + { + case osOK: + return NRF_SUCCESS; + + case osErrorISR: + return NRF_ERROR_INVALID_STATE; + + case osErrorParameter: + return NRF_ERROR_INVALID_PARAM; + + case osErrorResource: + return NRF_SUCCESS; + + default: + return NRF_ERROR_INVALID_PARAM; + } +} + + +uint32_t app_timer_stop_all(void) +{ + for (int i = 0; i < app_timer_control.max_timers; i++) + { + if (app_timer_control.app_timers[i].id) + { + (void)app_timer_stop((app_timer_id_t)app_timer_control.app_timers[i].id); + } + } + return 0; +} + + +extern uint32_t os_tick_val(void); +uint32_t app_timer_cnt_get(void) +{ + return os_tick_val(); +} + + +uint32_t app_timer_cnt_diff_compute(uint32_t ticks_to, + uint32_t ticks_from, + uint32_t * p_ticks_diff) +{ + *p_ticks_diff = ((ticks_to - ticks_from) & MAX_RTC_COUNTER_VAL); + return NRF_SUCCESS; +} +#endif //NRF_MODULE_ENABLED(APP_TIMER) + +#endif // MBED_CONF_RTOS_PRESENT diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/util/app_error.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/util/app_error.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/util/app_error.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/util/app_error.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/util/app_error.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/util/app_error.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/util/app_error.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/util/app_error.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/util/app_error_weak.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/util/app_error_weak.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/util/app_error_weak.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/util/app_error_weak.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/util/app_error_weak.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/util/app_error_weak.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/util/app_error_weak.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/util/app_error_weak.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/util/app_util.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/util/app_util.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/util/app_util.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/util/app_util.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/util/app_util_bds.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/util/app_util_bds.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/util/app_util_bds.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/util/app_util_bds.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/util/app_util_platform.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/util/app_util_platform.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/util/app_util_platform.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/util/app_util_platform.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/util/app_util_platform.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/util/app_util_platform.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/util/app_util_platform.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/util/app_util_platform.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/util/nordic_common.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/util/nordic_common.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/util/nordic_common.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/util/nordic_common.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/util/nrf_assert.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/util/nrf_assert.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/util/nrf_assert.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/util/nrf_assert.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/util/nrf_assert.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/util/nrf_assert.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/util/nrf_assert.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/util/nrf_assert.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/util/nrf_bitmask.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/util/nrf_bitmask.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/util/nrf_bitmask.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/util/nrf_bitmask.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/util/sdk_common.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/util/sdk_common.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/util/sdk_common.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/util/sdk_common.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/util/sdk_errors.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/util/sdk_errors.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/util/sdk_errors.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/util/sdk_errors.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/util/sdk_macros.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/util/sdk_macros.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/util/sdk_macros.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/util/sdk_macros.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/util/sdk_mapped_flags.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/util/sdk_mapped_flags.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/util/sdk_mapped_flags.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/util/sdk_mapped_flags.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/util/sdk_mapped_flags.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/util/sdk_mapped_flags.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/util/sdk_mapped_flags.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/util/sdk_mapped_flags.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/util/sdk_os.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/util/sdk_os.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/util/sdk_os.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/util/sdk_os.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/util/sdk_resources.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/util/sdk_resources.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/libraries/util/sdk_resources.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/libraries/util/sdk_resources.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/sdk_validation.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/sdk_validation.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/sdk_validation.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/sdk_validation.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/softdevice/common/softdevice_handler/ant_stack_handler_types.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/softdevice/common/softdevice_handler/ant_stack_handler_types.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/softdevice/common/softdevice_handler/ant_stack_handler_types.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/softdevice/common/softdevice_handler/ant_stack_handler_types.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/softdevice/common/softdevice_handler/app_ram_base.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/softdevice/common/softdevice_handler/app_ram_base.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/softdevice/common/softdevice_handler/app_ram_base.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/softdevice/common/softdevice_handler/app_ram_base.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/softdevice/common/softdevice_handler/ble_stack_handler_types.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/softdevice/common/softdevice_handler/ble_stack_handler_types.h similarity index 99% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/softdevice/common/softdevice_handler/ble_stack_handler_types.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/softdevice/common/softdevice_handler/ble_stack_handler_types.h index 30da33c7569..7be7850f581 100644 --- a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/softdevice/common/softdevice_handler/ble_stack_handler_types.h +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/softdevice/common/softdevice_handler/ble_stack_handler_types.h @@ -55,7 +55,7 @@ extern "C" { #ifdef BLE_STACK_SUPPORT_REQD #include -#include "headers/nrf_ble.h" +#include "headers/ble.h" #include "nrf_sdm.h" #include "app_error.h" #include "app_util.h" diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/softdevice/common/softdevice_handler/softdevice_handler.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/softdevice/common/softdevice_handler/softdevice_handler.c similarity index 99% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/softdevice/common/softdevice_handler/softdevice_handler.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/softdevice/common/softdevice_handler/softdevice_handler.c index 868532b4851..34e534e9f65 100644 --- a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/softdevice/common/softdevice_handler/softdevice_handler.c +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/softdevice/common/softdevice_handler/softdevice_handler.c @@ -62,7 +62,7 @@ #elif defined(ANT_STACK_SUPPORT_REQD) #include "ant_interface.h" #elif defined(BLE_STACK_SUPPORT_REQD) - #include "headers/nrf_ble.h" + #include "headers/ble.h" #endif #define RAM_START_ADDRESS 0x20000000 diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/softdevice/common/softdevice_handler/softdevice_handler.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/softdevice/common/softdevice_handler/softdevice_handler.h similarity index 99% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/softdevice/common/softdevice_handler/softdevice_handler.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/softdevice/common/softdevice_handler/softdevice_handler.h index 64d4465be03..59bc60f3d5a 100644 --- a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/softdevice/common/softdevice_handler/softdevice_handler.h +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/softdevice/common/softdevice_handler/softdevice_handler.h @@ -66,7 +66,7 @@ #include "ble_stack_handler_types.h" #include "ant_stack_handler_types.h" #if defined(BLE_STACK_SUPPORT_REQD) - #include "headers/nrf_ble.h" + #include "headers/ble.h" #endif #include "app_ram_base.h" diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/softdevice/common/softdevice_handler/softdevice_handler_appsh.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/softdevice/common/softdevice_handler/softdevice_handler_appsh.c similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/softdevice/common/softdevice_handler/softdevice_handler_appsh.c rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/softdevice/common/softdevice_handler/softdevice_handler_appsh.c diff --git a/targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/softdevice/common/softdevice_handler/softdevice_handler_appsh.h b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/softdevice/common/softdevice_handler/softdevice_handler_appsh.h similarity index 100% rename from targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK13/softdevice/common/softdevice_handler/softdevice_handler_appsh.h rename to targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sdk/softdevice/common/softdevice_handler/softdevice_handler_appsh.h diff --git a/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/serial_api.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/serial_api.c new file mode 100644 index 00000000000..e0b91656c8e --- /dev/null +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/serial_api.c @@ -0,0 +1,723 @@ +/* + * Copyright (c) 2013 Nordic Semiconductor ASA + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * 2. Redistributions in binary form, except as embedded into a Nordic Semiconductor ASA + * integrated circuit in a product or a software update for such product, must reproduce + * the above copyright notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of Nordic Semiconductor ASA nor the names of its contributors may be + * used to endorse or promote products derived from this software without specific prior + * written permission. + * + * 4. This software, with or without modification, must only be used with a + * Nordic Semiconductor ASA integrated circuit. + * + * 5. Any software provided in binary or object form under this license must not be reverse + * engineered, decompiled, modified and/or disassembled. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#include "serial_api.h" + +#if DEVICE_SERIAL + +#include +#include "mbed_assert.h" +#include "mbed_error.h" +#include "nrf_uart.h" +#include "nrf_drv_common.h" +#include "app_util_platform.h" +#include "nrf_gpio.h" + +#define UART_INSTANCE_COUNT 1 +#define UART_INSTANCE NRF_UART0 +#define UART_IRQn UART0_IRQn +#define UART_IRQ_HANDLER UART0_IRQHandler +#define UART_INSTANCE_ID 0 +#define UART_CB uart_cb[UART_INSTANCE_ID] + +#define UART_DEFAULT_BAUDRATE UART_DEFAULT_CONFIG_BAUDRATE +#define UART_DEFAULT_PARITY UART_DEFAULT_CONFIG_PARITY + +// expected the macro from mbed configuration system +#ifndef MBED_CONF_NORDIC_UART_HWFC + #define MBED_CONF_NORDIC_UART_HWFC 1 + #warning None of UART flow control configuration (expected macro MBED_CONF_NORDIC_UART_HWFC). The RTSCTS flow control is used by default . +#endif + +#if MBED_CONF_NORDIC_UART_HWFC == 1 + #define UART_DEFAULT_HWFC UART_DEFAULT_CONFIG_HWFC +#else + #define UART_DEFAULT_HWFC NRF_UART_HWFC_DISABLED +#endif + +#define UART_DEFAULT_CTS CTS_PIN_NUMBER +#define UART_DEFAULT_RTS RTS_PIN_NUMBER + +#ifdef NRF51 + #define NRFx_MBED_UART_IRQ_PRIORITY APP_IRQ_PRIORITY_LOW +#elif defined(NRF52) || defined(NRF52840_XXAA) + #define NRFx_MBED_UART_IRQ_PRIORITY APP_IRQ_PRIORITY_LOWEST +#endif + +// Required by "retarget.cpp". +int stdio_uart_inited = 0; +serial_t stdio_uart; + +typedef struct +{ + bool initialized; + uint32_t irq_context; + uart_irq_handler irq_handler; + + uint32_t pselrxd; + uint32_t pseltxd; + uint32_t pselcts; + uint32_t pselrts; + nrf_uart_hwfc_t hwfc; + nrf_uart_parity_t parity; + nrf_uart_baudrate_t baudrate; + +#if DEVICE_SERIAL_ASYNCH + bool volatile rx_active; + uint8_t *rx_buffer; + size_t rx_length; + size_t rx_pos; + void (*rx_asynch_handler)(); + uint8_t char_match; + + bool volatile tx_active; + const uint8_t *tx_buffer; + size_t tx_length; + size_t tx_pos; + void (*tx_asynch_handler)(); + + uint32_t events_wanted; + uint32_t events_occured; + +#define UART_IRQ_TX 1 +#define UART_IRQ_RX 2 + uint8_t irq_enabled; +#endif // DEVICE_SERIAL_ASYNCH +} uart_ctlblock_t; + +static uart_ctlblock_t uart_cb[UART_INSTANCE_COUNT]; + +static void internal_set_hwfc(FlowControl type, + PinName rxflow, PinName txflow); + + +#if DEVICE_SERIAL_ASYNCH +static void end_asynch_rx(void) +{ + // If RX interrupt is activated for synchronous operations, + // don't disable it, just stop handling it here. + if (!(UART_CB.irq_enabled & UART_IRQ_RX)) + { + nrf_uart_int_disable(UART_INSTANCE, NRF_UART_INT_MASK_RXDRDY); + } + UART_CB.rx_active = false; +} +static void end_asynch_tx(void) +{ + // If TX interrupt is activated for synchronous operations, + // don't disable it, just stop handling it here. + if (!(UART_CB.irq_enabled & UART_IRQ_TX)) + { + nrf_uart_int_disable(UART_INSTANCE, NRF_UART_INT_MASK_TXDRDY); + } + UART_CB.tx_active = false; +} +#endif // DEVICE_SERIAL_ASYNCH + +void UART_IRQ_HANDLER(void) +{ + if (nrf_uart_int_enable_check(UART_INSTANCE, NRF_UART_INT_MASK_RXDRDY) && + nrf_uart_event_check(UART_INSTANCE, NRF_UART_EVENT_RXDRDY)) + { + +#if DEVICE_SERIAL_ASYNCH + if (UART_CB.rx_active) + { + nrf_uart_event_clear(UART_INSTANCE, NRF_UART_EVENT_RXDRDY); + + uint8_t rx_data = nrf_uart_rxd_get(UART_INSTANCE); + UART_CB.rx_buffer[UART_CB.rx_pos] = rx_data; + + bool end_rx = false; + // If character matching should be performed, check if the current + // data matches the given one. + if (UART_CB.char_match != SERIAL_RESERVED_CHAR_MATCH && + rx_data == UART_CB.char_match) + { + // If it does, report the match and abort further receiving. + UART_CB.events_occured |= SERIAL_EVENT_RX_CHARACTER_MATCH; + if (UART_CB.events_wanted & SERIAL_EVENT_RX_CHARACTER_MATCH) + { + end_rx = true; + } + } + if (++UART_CB.rx_pos >= UART_CB.rx_length) + { + UART_CB.events_occured |= SERIAL_EVENT_RX_COMPLETE; + end_rx = true; + } + if (end_rx) + { + end_asynch_rx(); + + if (UART_CB.rx_asynch_handler) + { + // Use local variable to make it possible to start a next + // transfer from callback routine. + void (*handler)() = UART_CB.rx_asynch_handler; + UART_CB.rx_asynch_handler = NULL; + handler(); + } + } + } + else +#endif + + if (UART_CB.irq_handler) + { + UART_CB.irq_handler(UART_CB.irq_context, RxIrq); + } + } + + if (nrf_uart_int_enable_check(UART_INSTANCE, NRF_UART_INT_MASK_TXDRDY) && + nrf_uart_event_check(UART_INSTANCE, NRF_UART_EVENT_TXDRDY)) + { + +#if DEVICE_SERIAL_ASYNCH + if (UART_CB.tx_active) + { + if (++UART_CB.tx_pos <= UART_CB.tx_length) + { + // When there is still something to send, clear the TXDRDY event + // and put next byte to transmitter. + nrf_uart_event_clear(UART_INSTANCE, NRF_UART_EVENT_TXDRDY); + nrf_uart_txd_set(UART_INSTANCE, + UART_CB.tx_buffer[UART_CB.tx_pos]); + } + else + { + // When the TXDRDY event is set after the last byte to be sent + // has been passed to the transmitter, the job is done and TX + // complete can be indicated. + // Don't clear the TXDRDY event, it needs to remain set for the + // 'serial_writable' function to work properly. + end_asynch_tx(); + + UART_CB.events_occured |= SERIAL_EVENT_TX_COMPLETE; + if (UART_CB.tx_asynch_handler) + { + // Use local variable to make it possible to start a next + // transfer from callback routine. + void (*handler)() = UART_CB.tx_asynch_handler; + UART_CB.tx_asynch_handler = NULL; + handler(); + } + } + } + else +#endif + + if (UART_CB.irq_handler) + { + UART_CB.irq_handler(UART_CB.irq_context, TxIrq); + } + } + +#if DEVICE_SERIAL_ASYNCH + if (nrf_uart_event_check(UART_INSTANCE, NRF_UART_EVENT_ERROR)) + { + nrf_uart_event_clear(UART_INSTANCE, NRF_UART_EVENT_ERROR); + + uint8_t errorsrc = nrf_uart_errorsrc_get_and_clear(UART_INSTANCE); + if (UART_CB.rx_asynch_handler) + { + UART_CB.events_occured |= SERIAL_EVENT_ERROR; + if (errorsrc & NRF_UART_ERROR_PARITY_MASK) + { + UART_CB.events_occured |= SERIAL_EVENT_RX_PARITY_ERROR; + } + if (errorsrc & NRF_UART_ERROR_FRAMING_MASK) + { + UART_CB.events_occured |= SERIAL_EVENT_RX_FRAMING_ERROR; + } + if (errorsrc & NRF_UART_ERROR_OVERRUN_MASK) + { + UART_CB.events_occured |= SERIAL_EVENT_RX_OVERRUN_ERROR; + } + UART_CB.rx_asynch_handler(); + } + } +#endif // DEVICE_SERIAL_ASYNCH +} + + +void serial_init(serial_t *obj, PinName tx, PinName rx) +{ + + NVIC_SetVector(UART0_IRQn, (uint32_t) UART0_IRQHandler); + + + UART_CB.pseltxd = + (tx == NC) ? NRF_UART_PSEL_DISCONNECTED : (uint32_t)tx; + UART_CB.pselrxd = + (rx == NC) ? NRF_UART_PSEL_DISCONNECTED : (uint32_t)rx; + if (UART_CB.pseltxd != NRF_UART_PSEL_DISCONNECTED) + { + nrf_gpio_pin_set(UART_CB.pseltxd); + nrf_gpio_cfg_output(UART_CB.pseltxd); + } + if (UART_CB.pselrxd != NRF_UART_PSEL_DISCONNECTED) + { + nrf_gpio_cfg_input(UART_CB.pselrxd, NRF_GPIO_PIN_NOPULL); + } + + if (UART_CB.initialized) + { + // For already initialized peripheral it is sufficient to reconfigure + // RX/TX pins only. + + // Ensure that there is no unfinished TX transfer. + while (!serial_writable(obj)) + { + } + // UART pins can be configured only when the peripheral is disabled. + nrf_uart_disable(UART_INSTANCE); + nrf_uart_txrx_pins_set(UART_INSTANCE, UART_CB.pseltxd, UART_CB.pselrxd); + nrf_uart_enable(UART_INSTANCE); + } + else + { + UART_CB.baudrate = (nrf_uart_baudrate_t)UART_DEFAULT_BAUDRATE; + UART_CB.parity = (nrf_uart_parity_t)UART_DEFAULT_PARITY; + UART_CB.hwfc = (nrf_uart_hwfc_t)UART_DEFAULT_HWFC; + UART_CB.pselcts = UART_DEFAULT_CTS; + UART_CB.pselrts = UART_DEFAULT_RTS; + + nrf_uart_event_clear(UART_INSTANCE, NRF_UART_EVENT_RXDRDY); + nrf_uart_event_clear(UART_INSTANCE, NRF_UART_EVENT_TXDRDY); + nrf_uart_task_trigger(UART_INSTANCE, NRF_UART_TASK_STARTRX); + nrf_uart_task_trigger(UART_INSTANCE, NRF_UART_TASK_STARTTX); + + nrf_uart_int_disable(UART_INSTANCE, NRF_UART_INT_MASK_RXDRDY | + NRF_UART_INT_MASK_TXDRDY); +#if DEVICE_SERIAL_ASYNCH + nrf_uart_int_enable(UART_INSTANCE, NRF_UART_INT_MASK_ERROR); +#endif + nrf_drv_common_irq_enable(UART_IRQn, NRFx_MBED_UART_IRQ_PRIORITY); + + // TX interrupt needs to be signaled when transmitter buffer is empty, + // so a dummy transmission is needed to get the TXDRDY event initially + // set. + nrf_uart_configure(UART_INSTANCE, + NRF_UART_PARITY_EXCLUDED, NRF_UART_HWFC_DISABLED); + // Use maximum baud rate, so this dummy transmission takes as little + // time as possible. + nrf_uart_baudrate_set(UART_INSTANCE, NRF_UART_BAUDRATE_1000000); + // Perform it with disconnected TX pin, so nothing actually comes out + // of the device. + nrf_uart_txrx_pins_disconnect(UART_INSTANCE); + nrf_uart_hwfc_pins_disconnect(UART_INSTANCE); + nrf_uart_enable(UART_INSTANCE); + nrf_uart_txd_set(UART_INSTANCE, 0); + + while (!nrf_uart_event_check(UART_INSTANCE, NRF_UART_EVENT_TXDRDY)) + { + } + nrf_uart_disable(UART_INSTANCE); + + // Now everything is prepared to set the default configuration and + // connect the peripheral to actual pins. + nrf_uart_txrx_pins_set(UART_INSTANCE, UART_CB.pseltxd, UART_CB.pselrxd); + nrf_uart_baudrate_set(UART_INSTANCE, UART_CB.baudrate); + nrf_uart_configure(UART_INSTANCE, UART_CB.parity, UART_CB.hwfc); + if (UART_CB.hwfc == NRF_UART_HWFC_ENABLED) + { + internal_set_hwfc(FlowControlRTSCTS, + (PinName) UART_CB.pselrts, (PinName) UART_CB.pselcts); + } + + nrf_uart_enable(UART_INSTANCE); + + UART_CB.initialized = true; + } + + if (tx == STDIO_UART_TX && rx == STDIO_UART_RX) + { + stdio_uart_inited = 1; + memcpy(&stdio_uart, obj, sizeof(serial_t)); + } + else + { + stdio_uart_inited = 0; + } +} + +void serial_free(serial_t *obj) +{ + (void)obj; + + if (UART_CB.initialized) + { + nrf_uart_disable(UART_INSTANCE); + nrf_uart_int_disable(UART_INSTANCE, NRF_UART_INT_MASK_RXDRDY | + NRF_UART_INT_MASK_TXDRDY | + NRF_UART_INT_MASK_ERROR); + nrf_drv_common_irq_disable(UART_IRQn); + UART_CB.initialized = false; + + // There is only one UART instance, thus at this point the stdio UART + // can no longer be initialized. + stdio_uart_inited = 0; + } +} + +void serial_baud(serial_t *obj, int baudrate) +{ + // nrf_uart_baudrate_set() is not used here (registers are accessed + // directly) to make it possible to set special baud rates like 56000 + // or 31250. + + static uint32_t const acceptedSpeeds[][2] = { + { 1200, UART_BAUDRATE_BAUDRATE_Baud1200 }, + { 2400, UART_BAUDRATE_BAUDRATE_Baud2400 }, + { 4800, UART_BAUDRATE_BAUDRATE_Baud4800 }, + { 9600, UART_BAUDRATE_BAUDRATE_Baud9600 }, + { 14400, UART_BAUDRATE_BAUDRATE_Baud14400 }, + { 19200, UART_BAUDRATE_BAUDRATE_Baud19200 }, + { 28800, UART_BAUDRATE_BAUDRATE_Baud28800 }, + { 31250, (0x00800000UL) /* 31250 baud */ }, + { 38400, UART_BAUDRATE_BAUDRATE_Baud38400 }, + { 56000, (0x00E51000UL) /* 56000 baud */ }, + { 57600, UART_BAUDRATE_BAUDRATE_Baud57600 }, + { 76800, UART_BAUDRATE_BAUDRATE_Baud76800 }, + { 115200, UART_BAUDRATE_BAUDRATE_Baud115200 }, + { 230400, UART_BAUDRATE_BAUDRATE_Baud230400 }, + { 250000, UART_BAUDRATE_BAUDRATE_Baud250000 }, + { 460800, UART_BAUDRATE_BAUDRATE_Baud460800 }, + { 921600, UART_BAUDRATE_BAUDRATE_Baud921600 }, + { 1000000, UART_BAUDRATE_BAUDRATE_Baud1M } + }; + + if (baudrate <= 1200) + { + UART_INSTANCE->BAUDRATE = UART_BAUDRATE_BAUDRATE_Baud1200; + return; + } + + int const item_cnt = sizeof(acceptedSpeeds)/sizeof(acceptedSpeeds[0]); + + for (int i = 1; i < item_cnt; i++) + { + if ((uint32_t)baudrate < acceptedSpeeds[i][0]) + { + UART_INSTANCE->BAUDRATE = acceptedSpeeds[i - 1][1]; + return; + } + } + + UART_INSTANCE->BAUDRATE = UART_BAUDRATE_BAUDRATE_Baud1M; +} + +void serial_format(serial_t *obj, + int data_bits, SerialParity parity, int stop_bits) +{ + (void)obj; + + if (data_bits != 8) + { + error("UART supports only 8 data bits.\r\n"); + } + if (stop_bits != 1) + { + error("UART supports only 1 stop bits.\r\n"); + } + if (parity == ParityNone) + { + UART_CB.parity = NRF_UART_PARITY_EXCLUDED; + } + else if (parity == ParityEven) + { + UART_CB.parity = NRF_UART_PARITY_INCLUDED; + } + else + { + error("UART supports only even parity.\r\n"); + } + + // Reconfigure UART peripheral. + nrf_uart_configure(UART_INSTANCE, UART_CB.parity, UART_CB.hwfc); +} + +void serial_irq_handler(serial_t *obj, uart_irq_handler handler, uint32_t id) +{ + (void)obj; + UART_CB.irq_handler = handler; + UART_CB.irq_context = id; +} + +void serial_irq_set(serial_t *obj, SerialIrq irq, uint32_t enable) +{ + (void)obj; + if (enable) + { + switch (irq) + { + case RxIrq: +#if DEVICE_SERIAL_ASYNCH + UART_CB.irq_enabled |= UART_IRQ_RX; +#endif + nrf_uart_int_enable(UART_INSTANCE, NRF_UART_INT_MASK_RXDRDY); + break; + + case TxIrq: +#if DEVICE_SERIAL_ASYNCH + UART_CB.irq_enabled |= UART_IRQ_TX; +#endif + nrf_uart_int_enable(UART_INSTANCE, NRF_UART_INT_MASK_TXDRDY); + break; + } + } + else + { + switch (irq) + { + case RxIrq: +#if DEVICE_SERIAL_ASYNCH + UART_CB.irq_enabled &= ~UART_IRQ_RX; + if (!UART_CB.rx_active) +#endif + { + nrf_uart_int_disable(UART_INSTANCE, + NRF_UART_INT_MASK_RXDRDY); + } + break; + + case TxIrq: +#if DEVICE_SERIAL_ASYNCH + UART_CB.irq_enabled &= ~UART_IRQ_TX; + if (!UART_CB.tx_active) +#endif + { + nrf_uart_int_disable(UART_INSTANCE, + NRF_UART_INT_MASK_TXDRDY); + } + break; + } + } +} + +int serial_getc(serial_t *obj) +{ + while (!serial_readable(obj)) + { + } + + nrf_uart_event_clear(UART_INSTANCE, NRF_UART_EVENT_RXDRDY); + return nrf_uart_rxd_get(UART_INSTANCE); +} + +void serial_putc(serial_t *obj, int c) +{ + while (!serial_writable(obj)) + { + } + + nrf_uart_event_clear(UART_INSTANCE, NRF_UART_EVENT_TXDRDY); + nrf_uart_txd_set(UART_INSTANCE, (uint8_t)c); +} + +int serial_readable(serial_t *obj) +{ + (void)obj; +#if DEVICE_SERIAL_ASYNCH + if (UART_CB.rx_active) + { + return 0; + } +#endif + return (nrf_uart_event_check(UART_INSTANCE, NRF_UART_EVENT_RXDRDY)); +} + +int serial_writable(serial_t *obj) +{ + (void)obj; +#if DEVICE_SERIAL_ASYNCH + if (UART_CB.tx_active) + { + return 0; + } +#endif + return (nrf_uart_event_check(UART_INSTANCE, NRF_UART_EVENT_TXDRDY)); +} + +void serial_break_set(serial_t *obj) +{ + (void)obj; + nrf_uart_task_trigger(UART_INSTANCE, NRF_UART_TASK_SUSPEND); + nrf_uart_txrx_pins_disconnect(UART_INSTANCE); + nrf_gpio_pin_clear(UART_CB.pseltxd); +} + +void serial_break_clear(serial_t *obj) +{ + (void)obj; + nrf_gpio_pin_set(UART_CB.pseltxd); + nrf_uart_txrx_pins_set(UART_INSTANCE, UART_CB.pseltxd, UART_CB.pselrxd); + nrf_uart_task_trigger(UART_INSTANCE, NRF_UART_TASK_STARTRX); + nrf_uart_task_trigger(UART_INSTANCE, NRF_UART_TASK_STARTTX); +} + + +static void internal_set_hwfc(FlowControl type, + PinName rxflow, PinName txflow) +{ + UART_CB.pselrts = + ((rxflow == NC) || (type == FlowControlCTS)) ? NRF_UART_PSEL_DISCONNECTED : (uint32_t)rxflow; + UART_CB.pselcts = + ((txflow == NC) || (type == FlowControlRTS)) ? NRF_UART_PSEL_DISCONNECTED : (uint32_t)txflow; + + if (UART_CB.pselrts != NRF_UART_PSEL_DISCONNECTED) + { + nrf_gpio_pin_set(UART_CB.pselrts); + nrf_gpio_cfg_output(UART_CB.pselrts); + } + if (UART_CB.pselcts != NRF_UART_PSEL_DISCONNECTED) + { + nrf_gpio_cfg_input(UART_CB.pselcts, NRF_GPIO_PIN_NOPULL); + } + + UART_CB.hwfc = (nrf_uart_hwfc_t)((type == FlowControlNone)? NRF_UART_HWFC_DISABLED : UART_DEFAULT_CONFIG_HWFC); + + nrf_uart_configure(UART_INSTANCE, UART_CB.parity, UART_CB.hwfc); + nrf_uart_hwfc_pins_set(UART_INSTANCE, UART_CB.pselrts, UART_CB.pselcts); +} + +void serial_set_flow_control(serial_t *obj, FlowControl type, + PinName rxflow, PinName txflow) +{ + (void)obj; + + nrf_uart_disable(UART_INSTANCE); + internal_set_hwfc(type, rxflow, txflow); + nrf_uart_enable(UART_INSTANCE); +} + + +void serial_clear(serial_t *obj) +{ + (void)obj; +} + +#if DEVICE_SERIAL_ASYNCH + +int serial_tx_asynch(serial_t *obj, const void *tx, size_t tx_length, + uint8_t tx_width, uint32_t handler, uint32_t event, + DMAUsage hint) +{ + (void)obj; + (void)tx_width; + (void)hint; + if (UART_CB.tx_active || !tx_length) + { + return 0; + } + + UART_CB.tx_buffer = tx; + UART_CB.tx_length = tx_length; + UART_CB.tx_pos = 0; + UART_CB.tx_asynch_handler = (void(*)())handler; + UART_CB.events_wanted &= ~SERIAL_EVENT_TX_ALL; + UART_CB.events_wanted |= event; + + UART_CB.tx_active = true; + nrf_uart_int_enable(UART_INSTANCE, NRF_UART_INT_MASK_TXDRDY); + + return 0; +} + +void serial_rx_asynch(serial_t *obj, void *rx, size_t rx_length, + uint8_t rx_width, uint32_t handler, uint32_t event, + uint8_t char_match, DMAUsage hint) +{ + (void)obj; + (void)rx_width; + (void)hint; + if (UART_CB.rx_active || !rx_length) + { + return; + } + + UART_CB.rx_buffer = rx; + UART_CB.rx_length = rx_length; + UART_CB.rx_pos = 0; + UART_CB.rx_asynch_handler = (void(*)())handler; + UART_CB.events_wanted &= ~SERIAL_EVENT_RX_ALL; + UART_CB.events_wanted |= event; + UART_CB.char_match = char_match; + + UART_CB.rx_active = true; + nrf_uart_int_enable(UART_INSTANCE, NRF_UART_INT_MASK_RXDRDY); +} + +uint8_t serial_tx_active(serial_t *obj) +{ + (void)obj; + return UART_CB.tx_active; +} + +uint8_t serial_rx_active(serial_t *obj) +{ + (void)obj; + return UART_CB.rx_active; +} + +int serial_irq_handler_asynch(serial_t *obj) +{ + (void)obj; + uint32_t events_to_report = UART_CB.events_wanted & UART_CB.events_occured; + UART_CB.events_occured &= (~events_to_report); + return events_to_report; +} + +void serial_tx_abort_asynch(serial_t *obj) +{ + (void)obj; + end_asynch_tx(); + UART_CB.tx_asynch_handler = NULL; +} + +void serial_rx_abort_asynch(serial_t *obj) +{ + (void)obj; + end_asynch_rx(); + UART_CB.rx_asynch_handler = NULL; +} + +#endif // DEVICE_SERIAL_ASYNCH + +#endif // DEVICE_SERIAL diff --git a/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sleep.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sleep.c new file mode 100644 index 00000000000..cc73962fccb --- /dev/null +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/sleep.c @@ -0,0 +1,85 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * 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. + */ +#include "sleep_api.h" +#include "cmsis.h" +#include "mbed_interface.h" +#include "softdevice_handler.h" +#include "nrf_soc.h" + +// Mask of reserved bits of the register ICSR in the System Control Block peripheral +// In this case, bits which are equal to 0 are the bits reserved in this register +#define SCB_ICSR_RESERVED_BITS_MASK 0x9E43F03F + +#define FPU_EXCEPTION_MASK 0x0000009F + +void hal_sleep(void) +{ + // ensure debug is disconnected if semihost is enabled.... + + // Trigger an event when an interrupt is pending. This allows to wake up + // the processor from disabled interrupts. + SCB->SCR |= SCB_SCR_SEVONPEND_Msk; + +#if defined(NRF52) || defined(NRF52840_XXAA) + /* Clear exceptions and PendingIRQ from the FPU unit */ + __set_FPSCR(__get_FPSCR() & ~(FPU_EXCEPTION_MASK)); + (void) __get_FPSCR(); + NVIC_ClearPendingIRQ(FPU_IRQn); +#endif + + // If the SoftDevice is enabled, its API must be used to go to sleep. + if (softdevice_handler_is_enabled()) + { + sd_power_mode_set(NRF_POWER_MODE_LOWPWR); + sd_app_evt_wait(); + } + else + { + NRF_POWER->TASKS_LOWPWR = 1; + + // Note: it is not sufficient to just use WFE here, since the internal + // event register may be already set from an event that occurred in the + // past (like an SVC call to the SoftDevice) and in such case WFE will + // just clear the register and continue execution. + // Therefore, the strategy here is to first clear the event register + // by using SEV/WFE pair, and then execute WFE again, unless there is + // a pending interrupt. + + // Set an event and wake up whatsoever, this will clear the event + // register from all previous events set (SVC call included) + __SEV(); + __WFE(); + + // Test if there is an interrupt pending (mask reserved regions) + if (SCB->ICSR & (SCB_ICSR_RESERVED_BITS_MASK)) + { + // Ok, there is an interrut pending, no need to go to sleep + return; + } + else + { + // next event will wakeup the CPU + // If an interrupt occured between the test of SCB->ICSR and this + // instruction, WFE will just not put the CPU to sleep + __WFE(); + } + } +} + +void hal_deepsleep(void) +{ + hal_sleep(); +} diff --git a/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/spi_api.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/spi_api.c new file mode 100644 index 00000000000..da757720990 --- /dev/null +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/spi_api.c @@ -0,0 +1,600 @@ +/* + * Copyright (c) 2013 Nordic Semiconductor ASA + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * 2. Redistributions in binary form, except as embedded into a Nordic Semiconductor ASA + * integrated circuit in a product or a software update for such product, must reproduce + * the above copyright notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of Nordic Semiconductor ASA nor the names of its contributors may be + * used to endorse or promote products derived from this software without specific prior + * written permission. + * + * 4. This software, with or without modification, must only be used with a + * Nordic Semiconductor ASA integrated circuit. + * + * 5. Any software provided in binary or object form under this license must not be reverse + * engineered, decompiled, modified and/or disassembled. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + + +#include "spi_api.h" + +#if DEVICE_SPI + +#include "cmsis.h" +#include "pinmap.h" +#include "mbed_assert.h" +#include "mbed_error.h" +#include "nrf_drv_spi.h" +#include "nrf_drv_spis.h" +#include "app_util_platform.h" + +#if DEVICE_SPI_ASYNCH + #define SPI_IDX(obj) ((obj)->spi.spi_idx) +#else + #define SPI_IDX(obj) ((obj)->spi_idx) +#endif +#define SPI_INFO(obj) (&m_spi_info[SPI_IDX(obj)]) +#define MASTER_INST(obj) (&m_instances[SPI_IDX(obj)].master) +#define SLAVE_INST(obj) (&m_instances[SPI_IDX(obj)].slave) + +typedef struct +{ + bool initialized; + bool master; + uint8_t sck_pin; + uint8_t mosi_pin; + uint8_t miso_pin; + uint8_t ss_pin; + uint8_t spi_mode; + nrf_drv_spi_frequency_t frequency; + volatile union + { + bool busy; // master + bool readable; // slave + } flag; + volatile uint8_t tx_buf; + volatile uint8_t rx_buf; + +#if DEVICE_SPI_ASYNCH + uint32_t handler; + uint32_t event; +#endif +} spi_info_t; +static spi_info_t m_spi_info[SPI_COUNT]; + +typedef struct +{ + nrf_drv_spi_t master; + nrf_drv_spis_t slave; +} sdk_driver_instances_t; + +void SPI0_TWI0_IRQHandler(void); +void SPI1_TWI1_IRQHandler(void); +void SPIM2_SPIS2_SPI2_IRQHandler(void); + +static const peripheral_handler_desc_t spi_handler_desc[SPI_COUNT] = { +#if SPI0_ENABLED + { + SPI0_IRQ, + (uint32_t) SPI0_TWI0_IRQHandler + }, +#endif +#if SPI1_ENABLED + { + SPI1_IRQ, + (uint32_t) SPI1_TWI1_IRQHandler + }, +#endif +#if SPI2_ENABLED + { + SPI2_IRQ, + (uint32_t) SPIM2_SPIS2_SPI2_IRQHandler + }, +#endif +}; + + +static sdk_driver_instances_t m_instances[SPI_COUNT] = { +#if SPI0_ENABLED + { + NRF_DRV_SPI_INSTANCE(0), + NRF_DRV_SPIS_INSTANCE(0) + }, +#endif +#if SPI1_ENABLED + { + NRF_DRV_SPI_INSTANCE(1), + NRF_DRV_SPIS_INSTANCE(1) + }, +#endif +#if SPI2_ENABLED + { + NRF_DRV_SPI_INSTANCE(2), + NRF_DRV_SPIS_INSTANCE(2) + }, +#endif +}; + +static void master_event_handler(uint8_t spi_idx, + nrf_drv_spi_evt_t const *p_event) +{ + spi_info_t *p_spi_info = &m_spi_info[spi_idx]; + + if (p_event->type == NRF_DRV_SPI_EVENT_DONE) + { + p_spi_info->flag.busy = false; + if (p_spi_info->handler) + { + void (*handler)(void) = (void (*)(void))p_spi_info->handler; + p_spi_info->handler = 0; + handler(); + } + } +} +#define MASTER_EVENT_HANDLER(idx) \ + static void master_event_handler_##idx(nrf_drv_spi_evt_t const *p_event) { \ + master_event_handler(SPI##idx##_INSTANCE_INDEX, p_event); \ + } +#if SPI0_ENABLED + MASTER_EVENT_HANDLER(0) +#endif +#if SPI1_ENABLED + MASTER_EVENT_HANDLER(1) +#endif +#if SPI2_ENABLED + MASTER_EVENT_HANDLER(2) +#endif + +static nrf_drv_spi_handler_t const m_master_event_handlers[SPI_COUNT] = { +#if SPI0_ENABLED + master_event_handler_0, +#endif +#if SPI1_ENABLED + master_event_handler_1, +#endif +#if SPI2_ENABLED + master_event_handler_2, +#endif +}; + + +static void slave_event_handler(uint8_t spi_idx, + nrf_drv_spis_event_t event) +{ + spi_info_t *p_spi_info = &m_spi_info[spi_idx]; + + if (event.evt_type == NRF_DRV_SPIS_XFER_DONE) + { + // Signal that there is some data received that could be read. + p_spi_info->flag.readable = true; + + // And prepare for the next transfer. + // Previous data set in 'spi_slave_write' (if any) has been transmitted, + // now use the default one, until some new is set by 'spi_slave_write'. + p_spi_info->tx_buf = SPIS_DEFAULT_ORC; + nrf_drv_spis_buffers_set(&m_instances[spi_idx].slave, + (uint8_t const *)&p_spi_info->tx_buf, 1, + (uint8_t *)&p_spi_info->rx_buf, 1); + } +} +#define SLAVE_EVENT_HANDLER(idx) \ + static void slave_event_handler_##idx(nrf_drv_spis_event_t event) { \ + slave_event_handler(SPIS##idx##_INSTANCE_INDEX, event); \ + } +#if SPIS0_ENABLED + SLAVE_EVENT_HANDLER(0) +#endif +#if SPIS1_ENABLED + SLAVE_EVENT_HANDLER(1) +#endif +#if SPIS2_ENABLED + SLAVE_EVENT_HANDLER(2) +#endif + +static nrf_drv_spis_event_handler_t const m_slave_event_handlers[SPIS_COUNT] = { +#if SPIS0_ENABLED + slave_event_handler_0, +#endif +#if SPIS1_ENABLED + slave_event_handler_1, +#endif +#if SPIS2_ENABLED + slave_event_handler_2, +#endif +}; + +static void prepare_master_config(nrf_drv_spi_config_t *p_config, + spi_info_t const *p_spi_info) +{ + p_config->sck_pin = p_spi_info->sck_pin; + p_config->mosi_pin = p_spi_info->mosi_pin; + p_config->miso_pin = p_spi_info->miso_pin; + p_config->ss_pin = p_spi_info->ss_pin; + p_config->frequency = p_spi_info->frequency; + p_config->mode = (nrf_drv_spi_mode_t)p_spi_info->spi_mode; + + p_config->irq_priority = SPI_DEFAULT_CONFIG_IRQ_PRIORITY; + p_config->orc = 0xFF; + p_config->bit_order = NRF_DRV_SPI_BIT_ORDER_MSB_FIRST; +} + +static void prepare_slave_config(nrf_drv_spis_config_t *p_config, + spi_info_t const *p_spi_info) +{ + p_config->sck_pin = p_spi_info->sck_pin; + p_config->mosi_pin = p_spi_info->mosi_pin; + p_config->miso_pin = p_spi_info->miso_pin; + p_config->csn_pin = p_spi_info->ss_pin; + p_config->mode = (nrf_drv_spis_mode_t)p_spi_info->spi_mode; + + p_config->irq_priority = SPIS_DEFAULT_CONFIG_IRQ_PRIORITY; + p_config->orc = SPIS_DEFAULT_ORC; + p_config->def = SPIS_DEFAULT_DEF; + p_config->bit_order = NRF_DRV_SPIS_BIT_ORDER_MSB_FIRST; + p_config->csn_pullup = NRF_DRV_SPIS_DEFAULT_CSN_PULLUP; + p_config->miso_drive = NRF_DRV_SPIS_DEFAULT_MISO_DRIVE; +} + +void spi_init(spi_t *obj, + PinName mosi, PinName miso, PinName sclk, PinName ssel) +{ + int i; + + // This block is only a workaround that allows to create SPI object several + // times, what would be otherwise impossible in the current implementation + // of mbed driver that does not call spi_free() from SPI destructor. + // Once this mbed's imperfection is corrected, this block should be removed. + for (i = 0; i < SPI_COUNT; ++i) + { + spi_info_t *p_spi_info = &m_spi_info[i]; + + if (p_spi_info->initialized && + p_spi_info->mosi_pin == (uint8_t)mosi && + p_spi_info->miso_pin == (uint8_t)miso && + p_spi_info->sck_pin == (uint8_t)sclk && + p_spi_info->ss_pin == (uint8_t)ssel) + { + // Reuse the already allocated SPI instance (instead of allocating + // a new one), if it appears to be initialized with exactly the same + // pin assignments. + SPI_IDX(obj) = i; + return; + } + } + + for (i = 0; i < SPI_COUNT; ++i) + { + spi_info_t *p_spi_info = &m_spi_info[i]; + + if (!p_spi_info->initialized) + { + p_spi_info->sck_pin = (uint8_t)sclk; + p_spi_info->mosi_pin = (mosi != NC) ? + (uint8_t)mosi : NRF_DRV_SPI_PIN_NOT_USED; + p_spi_info->miso_pin = (miso != NC) ? + (uint8_t)miso : NRF_DRV_SPI_PIN_NOT_USED; + p_spi_info->ss_pin = (ssel != NC) ? + (uint8_t)ssel : NRF_DRV_SPI_PIN_NOT_USED; + p_spi_info->spi_mode = (uint8_t)NRF_DRV_SPI_MODE_0; + p_spi_info->frequency = NRF_DRV_SPI_FREQ_1M; + + NVIC_SetVector(spi_handler_desc[i].IRQn, spi_handler_desc[i].vector); + + // By default each SPI instance is initialized to work as a master. + // Should the slave mode be used, the instance will be reconfigured + // appropriately in 'spi_format'. + nrf_drv_spi_config_t config; + prepare_master_config(&config, p_spi_info); + + nrf_drv_spi_t const *p_spi = &m_instances[i].master; + ret_code_t ret_code = nrf_drv_spi_init(p_spi, + &config, m_master_event_handlers[i]); + if (ret_code == NRF_SUCCESS) + { + p_spi_info->initialized = true; + p_spi_info->master = true; + p_spi_info->flag.busy = false; +#if DEVICE_SPI_ASYNCH + p_spi_info->handler = 0; +#endif + SPI_IDX(obj) = i; + + return; + } + } + } + + // No available peripheral + error("No available SPI peripheral\r\n"); +} + +void spi_free(spi_t *obj) +{ + spi_info_t *p_spi_info = SPI_INFO(obj); + + if (p_spi_info->master) + { + nrf_drv_spi_uninit(MASTER_INST(obj)); + } + else + { + nrf_drv_spis_uninit(SLAVE_INST(obj)); + } + p_spi_info->initialized = false; +} + +int spi_busy(spi_t *obj) +{ + return (int)(SPI_INFO(obj)->flag.busy); +} + +void spi_format(spi_t *obj, int bits, int mode, int slave) +{ + if (bits != 8) + { + error("Only 8-bits SPI is supported\r\n"); + } + if (mode > 3) + { + error("SPI format error\r\n"); + } + + spi_info_t *p_spi_info = SPI_INFO(obj); + + if (slave) + { + nrf_drv_spis_mode_t spi_modes[4] = { + NRF_DRV_SPIS_MODE_0, + NRF_DRV_SPIS_MODE_1, + NRF_DRV_SPIS_MODE_2, + NRF_DRV_SPIS_MODE_3, + }; + nrf_drv_spis_mode_t new_mode = spi_modes[mode]; + + // If the peripheral is currently working as a master, the SDK driver + // it uses needs to be switched from SPI to SPIS. + if (p_spi_info->master) + { + nrf_drv_spi_uninit(MASTER_INST(obj)); + } + // I the SPI mode has to be changed, the SDK's SPIS driver needs to be + // re-initialized (there is no other way to change its configuration). + else if (p_spi_info->spi_mode != (uint8_t)new_mode) + { + nrf_drv_spis_uninit(SLAVE_INST(obj)); + } + else + { + return; + } + + p_spi_info->spi_mode = (uint8_t)new_mode; + p_spi_info->master = false; + p_spi_info->flag.readable = false; + + // Initialize SDK's SPIS driver with the new configuration. + nrf_drv_spis_config_t config; + prepare_slave_config(&config, p_spi_info); + (void)nrf_drv_spis_init(SLAVE_INST(obj), &config, + m_slave_event_handlers[SPI_IDX(obj)]); + + // Prepare the slave for transfer. + p_spi_info->tx_buf = SPIS_DEFAULT_ORC; + nrf_drv_spis_buffers_set(SLAVE_INST(obj), + (uint8_t const *)&p_spi_info->tx_buf, 1, + (uint8_t *)&p_spi_info->rx_buf, 1); + } + else // master + { + nrf_drv_spi_mode_t spi_modes[4] = { + NRF_DRV_SPI_MODE_0, + NRF_DRV_SPI_MODE_1, + NRF_DRV_SPI_MODE_2, + NRF_DRV_SPI_MODE_3, + }; + nrf_drv_spi_mode_t new_mode = spi_modes[mode]; + + // If the peripheral is currently working as a slave, the SDK driver + // it uses needs to be switched from SPIS to SPI. + if (!p_spi_info->master) + { + nrf_drv_spis_uninit(SLAVE_INST(obj)); + } + // I the SPI mode has to be changed, the SDK's SPI driver needs to be + // re-initialized (there is no other way to change its configuration). + else if (p_spi_info->spi_mode != (uint8_t)new_mode) + { + nrf_drv_spi_uninit(MASTER_INST(obj)); + } + else + { + return; + } + + p_spi_info->spi_mode = (uint8_t)new_mode; + p_spi_info->master = true; + p_spi_info->flag.busy = false; + + // Initialize SDK's SPI driver with the new configuration. + nrf_drv_spi_config_t config; + prepare_master_config(&config, p_spi_info); + (void)nrf_drv_spi_init(MASTER_INST(obj), &config, + m_master_event_handlers[SPI_IDX(obj)]); + } +} + +static nrf_drv_spi_frequency_t freq_translate(int hz) +{ + nrf_drv_spi_frequency_t frequency; + + if (hz<250000) //125Kbps + { + frequency = NRF_DRV_SPI_FREQ_125K; + } + else if (hz<500000) //250Kbps + { + frequency = NRF_DRV_SPI_FREQ_250K; + } + else if (hz<1000000) //500Kbps + { + frequency = NRF_DRV_SPI_FREQ_500K; + } + else if (hz<2000000) //1Mbps + { + frequency = NRF_DRV_SPI_FREQ_1M; + } + else if (hz<4000000) //2Mbps + { + frequency = NRF_DRV_SPI_FREQ_2M; + } + else if (hz<8000000) //4Mbps + { + frequency = NRF_DRV_SPI_FREQ_4M; + } + else //8Mbps + { + frequency = NRF_DRV_SPI_FREQ_8M; + } + return frequency; +} + +void spi_frequency(spi_t *obj, int hz) +{ + spi_info_t *p_spi_info = SPI_INFO(obj); + nrf_drv_spi_frequency_t new_frequency = freq_translate(hz); + + if (p_spi_info->master) + { + if (p_spi_info->frequency != new_frequency) + { + p_spi_info->frequency = new_frequency; + + nrf_drv_spi_config_t config; + prepare_master_config(&config, p_spi_info); + + nrf_drv_spi_t const *p_spi = MASTER_INST(obj); + nrf_drv_spi_uninit(p_spi); + (void)nrf_drv_spi_init(p_spi, &config, + m_master_event_handlers[SPI_IDX(obj)]); + } + } + // There is no need to set anything in slaves when it comes to frequency, + // since slaves just synchronize with the clock provided by a master. +} + +int spi_master_write(spi_t *obj, int value) +{ + spi_info_t *p_spi_info = SPI_INFO(obj); + +#if DEVICE_SPI_ASYNCH + + while (p_spi_info->flag.busy) + { + } +#endif + + p_spi_info->tx_buf = value; + p_spi_info->flag.busy = true; + (void)nrf_drv_spi_transfer(MASTER_INST(obj), + (uint8_t const *)&p_spi_info->tx_buf, 1, + (uint8_t *)&p_spi_info->rx_buf, 1); + + while (p_spi_info->flag.busy) + { + } + + return p_spi_info->rx_buf; +} + +int spi_slave_receive(spi_t *obj) +{ + spi_info_t *p_spi_info = SPI_INFO(obj); + MBED_ASSERT(!p_spi_info->master); + return p_spi_info->flag.readable; +} + +int spi_slave_read(spi_t *obj) +{ + spi_info_t *p_spi_info = SPI_INFO(obj); + MBED_ASSERT(!p_spi_info->master); + + while (!p_spi_info->flag.readable) + { + } + p_spi_info->flag.readable = false; + return p_spi_info->rx_buf; +} + +void spi_slave_write(spi_t *obj, int value) +{ + spi_info_t *p_spi_info = SPI_INFO(obj); + MBED_ASSERT(!p_spi_info->master); + + p_spi_info->tx_buf = (uint8_t)value; +} + +#if DEVICE_SPI_ASYNCH + +void spi_master_transfer(spi_t *obj, + const void *tx, size_t tx_length, + void *rx, size_t rx_length, uint8_t bit_width, + uint32_t handler, uint32_t event, DMAUsage hint) +{ + spi_info_t *p_spi_info = SPI_INFO(obj); + MBED_ASSERT(p_spi_info->master); + (void)hint; + (void)bit_width; + + p_spi_info->handler = handler; + p_spi_info->event = event; + + p_spi_info->flag.busy = true; + (void)nrf_drv_spi_transfer(MASTER_INST(obj), + (uint8_t const *)tx, tx_length, + (uint8_t *)rx, rx_length); +} + +uint32_t spi_irq_handler_asynch(spi_t *obj) +{ + spi_info_t *p_spi_info = SPI_INFO(obj); + MBED_ASSERT(p_spi_info->master); + return p_spi_info->event & SPI_EVENT_COMPLETE; +} + +uint8_t spi_active(spi_t *obj) +{ + spi_info_t *p_spi_info = SPI_INFO(obj); + MBED_ASSERT(p_spi_info->master); + return p_spi_info->flag.busy; +} + +void spi_abort_asynch(spi_t *obj) +{ + MBED_ASSERT(SPI_INFO(obj)->master); + nrf_drv_spi_abort(MASTER_INST(obj)); +} + +#endif // DEVICE_SPI_ASYNCH + +#endif // DEVICE_SPI diff --git a/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/us_ticker.c b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/us_ticker.c new file mode 100644 index 00000000000..1ef96f5438f --- /dev/null +++ b/targets/TARGET_NORDIC/TARGET_NRF5_SDK13/us_ticker.c @@ -0,0 +1,637 @@ +/* + * Copyright (c) 2013 Nordic Semiconductor ASA + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * 2. Redistributions in binary form, except as embedded into a Nordic Semiconductor ASA + * integrated circuit in a product or a software update for such product, must reproduce + * the above copyright notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of Nordic Semiconductor ASA nor the names of its contributors may be + * used to endorse or promote products derived from this software without specific prior + * written permission. + * + * 4. This software, with or without modification, must only be used with a + * Nordic Semiconductor ASA integrated circuit. + * + * 5. Any software provided in binary or object form under this license must not be reverse + * engineered, decompiled, modified and/or disassembled. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#include "us_ticker_api.h" +#include "common_rtc.h" +#include "app_util.h" +#include "nrf_drv_common.h" +#include "lp_ticker_api.h" +#include "mbed_critical.h" + +#if defined(NRF52_ERRATA_20) + #include "softdevice_handler.h" +#endif + +//------------------------------------------------------------------------------ +// Common stuff used also by lp_ticker and rtc_api (see "common_rtc.h"). +// +#include "app_util_platform.h" + +bool m_common_rtc_enabled = false; +uint32_t volatile m_common_rtc_overflows = 0; + +#if defined(TARGET_MCU_NRF51822) +void common_rtc_irq_handler(void) +#else +void COMMON_RTC_IRQ_HANDLER(void) +#endif +{ + if (nrf_rtc_event_pending(COMMON_RTC_INSTANCE, US_TICKER_EVENT)) + { + us_ticker_irq_handler(); + } + +#if DEVICE_LOWPOWERTIMER + if (nrf_rtc_event_pending(COMMON_RTC_INSTANCE, LP_TICKER_EVENT)) + { + + lp_ticker_irq_handler(); + } +#endif + + if (nrf_rtc_event_pending(COMMON_RTC_INSTANCE, NRF_RTC_EVENT_OVERFLOW)) + { + nrf_rtc_event_clear(COMMON_RTC_INSTANCE, NRF_RTC_EVENT_OVERFLOW); + // Don't disable this event. It shall occur periodically. + + ++m_common_rtc_overflows; + } +} + +// Function for fix errata 20: RTC Register values are invalid +__STATIC_INLINE void errata_20(void) +{ +#if defined(NRF52_ERRATA_20) + if (!softdevice_handler_is_enabled()) + { + NRF_CLOCK->EVENTS_LFCLKSTARTED = 0; + NRF_CLOCK->TASKS_LFCLKSTART = 1; + + while (NRF_CLOCK->EVENTS_LFCLKSTARTED == 0) + { + } + } + NRF_RTC1->TASKS_STOP = 0; +#endif +} + +#if (defined (__ICCARM__)) && defined(TARGET_MCU_NRF51822)//IAR +__stackless __task +#endif +void RTC1_IRQHandler(void); + +void common_rtc_init(void) +{ + if (m_common_rtc_enabled) + { + return; + } + + errata_20(); + + NVIC_SetVector(RTC1_IRQn, (uint32_t)RTC1_IRQHandler); + + // RTC is driven by the low frequency (32.768 kHz) clock, a proper request + // must be made to have it running. + // Currently this clock is started in 'SystemInit' (see "system_nrf51.c" + // or "system_nrf52.c", respectively). + + nrf_rtc_prescaler_set(COMMON_RTC_INSTANCE, 0); + + nrf_rtc_event_clear(COMMON_RTC_INSTANCE, US_TICKER_EVENT); +#if defined(TARGET_MCU_NRF51822) + nrf_rtc_event_clear(COMMON_RTC_INSTANCE, OS_TICK_EVENT); +#endif +#if DEVICE_LOWPOWERTIMER + nrf_rtc_event_clear(COMMON_RTC_INSTANCE, LP_TICKER_EVENT); +#endif + nrf_rtc_event_clear(COMMON_RTC_INSTANCE, NRF_RTC_EVENT_OVERFLOW); + + // Interrupts on all related events are enabled permanently. Particular + // events will be enabled or disabled as needed (such approach is more + // energy efficient). + nrf_rtc_int_enable(COMMON_RTC_INSTANCE, +#if DEVICE_LOWPOWERTIMER + LP_TICKER_INT_MASK | +#endif + US_TICKER_INT_MASK | + NRF_RTC_INT_OVERFLOW_MASK); + + // This event is enabled permanently, since overflow indications are needed + // continuously. + nrf_rtc_event_enable(COMMON_RTC_INSTANCE, NRF_RTC_INT_OVERFLOW_MASK); + // All other relevant events are initially disabled. + nrf_rtc_event_disable(COMMON_RTC_INSTANCE, +#if defined(TARGET_MCU_NRF51822) + OS_TICK_INT_MASK | +#endif +#if DEVICE_LOWPOWERTIMER + LP_TICKER_INT_MASK | +#endif + US_TICKER_INT_MASK); + + nrf_drv_common_irq_enable(nrf_drv_get_IRQn(COMMON_RTC_INSTANCE), +#ifdef NRF51 + APP_IRQ_PRIORITY_LOW +#elif defined(NRF52) || defined(NRF52840_XXAA) + APP_IRQ_PRIORITY_LOWEST +#endif + ); + + nrf_rtc_task_trigger(COMMON_RTC_INSTANCE, NRF_RTC_TASK_START); + + m_common_rtc_enabled = true; +} + +uint32_t common_rtc_32bit_ticks_get(void) +{ + uint32_t ticks = nrf_rtc_counter_get(COMMON_RTC_INSTANCE); + // The counter used for time measurements is less than 32 bit wide, + // so its value is complemented with the number of registered overflows + // of the counter. + ticks += (m_common_rtc_overflows << RTC_COUNTER_BITS); + return ticks; +} + +uint64_t common_rtc_64bit_us_get(void) +{ + uint32_t ticks = common_rtc_32bit_ticks_get(); + // [ticks -> microseconds] + return ROUNDED_DIV(((uint64_t)ticks) * 1000000, RTC_INPUT_FREQ); +} + +void common_rtc_set_interrupt(uint32_t us_timestamp, uint32_t cc_channel, + uint32_t int_mask) +{ + // The internal counter is clocked with a frequency that cannot be easily + // multiplied to 1 MHz, therefore besides the translation of values + // (microsecond <-> ticks) a special care of overflows handling must be + // taken. Here the 32-bit timestamp value is complemented with information + // about current the system up time of (ticks + number of overflows of tick + // counter on upper bits, converted to microseconds), and such 64-bit value + // is then translated to counter ticks. Finally, the lower 24 bits of thus + // calculated value is written to the counter compare register to prepare + // the interrupt generation. + uint64_t current_time64 = common_rtc_64bit_us_get(); + // [add upper 32 bits from the current time to the timestamp value] + uint64_t timestamp64 = us_timestamp + + (current_time64 & ~(uint64_t)0xFFFFFFFF); + + // [if the original timestamp value happens to be after the 32 bit counter + // of microsends overflows, correct the upper 32 bits accordingly] + if (us_timestamp < (uint32_t)(current_time64 & 0xFFFFFFFF)) + { + timestamp64 += ((uint64_t)1 << 32); + } + // [microseconds -> ticks, always round the result up to avoid too early + // interrupt generation] + uint32_t compare_value = + (uint32_t)CEIL_DIV((timestamp64) * RTC_INPUT_FREQ, 1000000); + + // The COMPARE event occurs when the value in compare register is N and + // the counter value changes from N-1 to N. Therefore, the minimal safe + // difference between the compare value to be set and the current counter + // value is 2 ticks. This guarantees that the compare trigger is properly + // setup before the compare condition occurs. + uint32_t closest_safe_compare = common_rtc_32bit_ticks_get() + 2; + if ((int)(compare_value - closest_safe_compare) <= 0) + { + compare_value = closest_safe_compare; + } + + nrf_rtc_cc_set(COMMON_RTC_INSTANCE, cc_channel, RTC_WRAP(compare_value)); + nrf_rtc_event_enable(COMMON_RTC_INSTANCE, int_mask); +} +//------------------------------------------------------------------------------ + + +void us_ticker_init(void) +{ + common_rtc_init(); +} + +uint32_t us_ticker_read() +{ + us_ticker_init(); + return (uint32_t)common_rtc_64bit_us_get(); +} + +void us_ticker_set_interrupt(timestamp_t timestamp) +{ + common_rtc_set_interrupt(timestamp, + US_TICKER_CC_CHANNEL, US_TICKER_INT_MASK); +} + +void us_ticker_disable_interrupt(void) +{ + nrf_rtc_event_disable(COMMON_RTC_INSTANCE, US_TICKER_INT_MASK); +} + +void us_ticker_clear_interrupt(void) +{ + nrf_rtc_event_clear(COMMON_RTC_INSTANCE, US_TICKER_EVENT); +} + + +// Since there is no SysTick on NRF51, the RTC1 channel 1 is used as an +// alternative source of RTOS ticks. +#if defined(TARGET_MCU_NRF51822) + +#include "mbed_toolchain.h" + + +#define MAX_RTC_COUNTER_VAL ((1uL << RTC_COUNTER_BITS) - 1) + +/** + * The value previously set in the capture compare register of channel 1 + */ +static uint32_t previous_tick_cc_value = 0; + +/* + RTX provide the following definitions which are used by the tick code: + * os_trv: The number (minus 1) of clock cycle between two tick. + * os_clockrate: Time duration between two ticks (in us). + * OS_Tick_Handler: The function which handle a tick event. + This function is special because it never returns. + Those definitions are used by the code which handle the os tick. + To allow compilation of us_ticker programs without RTOS, those symbols are + exported from this module as weak ones. + */ +MBED_WEAK uint32_t const os_trv; +MBED_WEAK uint32_t const os_clockrate; +MBED_WEAK void OS_Tick_Handler() +{ +} + + +#if defined (__CC_ARM) /* ARMCC Compiler */ + +__asm void COMMON_RTC_IRQ_HANDLER(void) +{ + IMPORT OS_Tick_Handler + IMPORT common_rtc_irq_handler + + /** + * Chanel 1 of RTC1 is used by RTX as a systick. + * If the compare event on channel 1 is set, then branch to OS_Tick_Handler. + * Otherwise, just execute common_rtc_irq_handler. + * This function has to be written in assembly and tagged as naked because OS_Tick_Handler + * will never return. + * A c function would put lr on the stack before calling OS_Tick_Handler and this value + * would never been dequeued. + * + * \code + * void COMMON_RTC_IRQ_HANDLER(void) { + if(NRF_RTC1->EVENTS_COMPARE[1]) { + // never return... + OS_Tick_Handler(); + } else { + common_rtc_irq_handler(); + } + } + * \endcode + */ + ldr r0,=0x40011144 + ldr r1, [r0, #0] + cmp r1, #0 + beq US_TICKER_HANDLER + bl OS_Tick_Handler +US_TICKER_HANDLER + push {r3, lr} + bl common_rtc_irq_handler + pop {r3, pc} + ; ALIGN ; +} + +#elif defined (__GNUC__) /* GNU Compiler */ + +__attribute__((naked)) void COMMON_RTC_IRQ_HANDLER(void) +{ + /** + * Chanel 1 of RTC1 is used by RTX as a systick. + * If the compare event on channel 1 is set, then branch to OS_Tick_Handler. + * Otherwise, just execute common_rtc_irq_handler. + * This function has to be written in assembly and tagged as naked because OS_Tick_Handler + * will never return. + * A c function would put lr on the stack before calling OS_Tick_Handler and this value + * would never been dequeued. + * + * \code + * void COMMON_RTC_IRQ_HANDLER(void) { + if(NRF_RTC1->EVENTS_COMPARE[1]) { + // never return... + OS_Tick_Handler(); + } else { + common_rtc_irq_handler(); + } + } + * \endcode + */ + __asm__ ( + "ldr r0,=0x40011144\n" + "ldr r1, [r0, #0]\n" + "cmp r1, #0\n" + "beq US_TICKER_HANDLER\n" + "bl OS_Tick_Handler\n" + "US_TICKER_HANDLER:\n" + "push {r3, lr}\n" + "bl common_rtc_irq_handler\n" + "pop {r3, pc}\n" + "nop" + ); +} + +#elif defined (__ICCARM__)//IAR +void common_rtc_irq_handler(void); + +__stackless __task void COMMON_RTC_IRQ_HANDLER(void) +{ + uint32_t temp; + + __asm volatile( + " ldr %[temp], [%[reg2check]] \n" + " cmp %[temp], #0 \n" + " beq 1f \n" + " bl.w OS_Tick_Handler \n" + "1: \n" + " push {r3, lr}\n" + " blx %[rtc_irq] \n" + " pop {r3, pc}\n" + + : /* Outputs */ + [temp] "=&r"(temp) + : /* Inputs */ + [reg2check] "r"(0x40011144), + [rtc_irq] "r"(common_rtc_irq_handler) + : /* Clobbers */ + "cc" + ); + (void)temp; +} + + +#else + +#error Compiler not supported. +#error Provide a definition of COMMON_RTC_IRQ_HANDLER. + +/* + * Chanel 1 of RTC1 is used by RTX as a systick. + * If the compare event on channel 1 is set, then branch to OS_Tick_Handler. + * Otherwise, just execute common_rtc_irq_handler. + * This function has to be written in assembly and tagged as naked because OS_Tick_Handler + * will never return. + * A c function would put lr on the stack before calling OS_Tick_Handler and this value + * will never been dequeued. After a certain time a stack overflow will happen. + * + * \code + * void COMMON_RTC_IRQ_HANDLER(void) { + if(NRF_RTC1->EVENTS_COMPARE[1]) { + // never return... + OS_Tick_Handler(); + } else { + common_rtc_irq_handler(); + } + } + * \endcode + */ + +#endif + +/** + * Return the next number of clock cycle needed for the next tick. + * @note This function has been carrefuly optimized for a systick occuring every 1000us. + */ +static uint32_t get_next_tick_cc_delta() +{ + uint32_t delta = 0; + + if (os_clockrate != 1000) + { + // In RTX, by default SYSTICK is is used. + // A tick event is generated every os_trv + 1 clock cycles of the system timer. + delta = os_trv + 1; + } + else + { + // If the clockrate is set to 1000us then 1000 tick should happen every second. + // Unfortunatelly, when clockrate is set to 1000, os_trv is equal to 31. + // If (os_trv + 1) is used as the delta value between two ticks, 1000 ticks will be + // generated in 32000 clock cycle instead of 32768 clock cycles. + // As a result, if a user schedule an OS timer to start in 100s, the timer will start + // instead after 97.656s + // The code below fix this issue, a clock rate of 1000s will generate 1000 ticks in 32768 + // clock cycles. + // The strategy is simple, for 1000 ticks: + // * 768 ticks will occur 33 clock cycles after the previous tick + // * 232 ticks will occur 32 clock cycles after the previous tick + // By default every delta is equal to 33. + // Every five ticks (20%, 200 delta in one second), the delta is equal to 32 + // The remaining (32) deltas equal to 32 are distributed using primes numbers. + static uint32_t counter = 0; + if ((counter % 5) == 0 || (counter % 31) == 0 || (counter % 139) == 0 || (counter == 503)) + { + delta = 32; + } + else + { + delta = 33; + } + ++counter; + if (counter == 1000) + { + counter = 0; + } + } + return delta; +} + + +static inline void clear_tick_interrupt() +{ + nrf_rtc_event_clear(COMMON_RTC_INSTANCE, OS_TICK_EVENT); + nrf_rtc_event_disable(COMMON_RTC_INSTANCE, OS_TICK_INT_MASK); +} + +/** + * Indicate if a value is included in a range which can be wrapped. + * @param begin start of the range + * @param end end of the range + * @param val value to check + * @return true if the value is included in the range and false otherwise. + */ +static inline bool is_in_wrapped_range(uint32_t begin, uint32_t end, uint32_t val) +{ + // regular case, begin < end + // return true if begin <= val < end + if (begin < end) + { + if (begin <= val && val < end) + { + return true; + } + else + { + return false; + } + } + else + { + // In this case end < begin because it has wrap around the limits + // return false if end < val < begin + if (end < val && val < begin) + { + return false; + } + else + { + return true; + } + } + +} + +/** + * Register the next tick. + */ +static void register_next_tick() +{ + previous_tick_cc_value = nrf_rtc_cc_get(COMMON_RTC_INSTANCE, OS_TICK_CC_CHANNEL); + uint32_t delta = get_next_tick_cc_delta(); + uint32_t new_compare_value = (previous_tick_cc_value + delta) & MAX_RTC_COUNTER_VAL; + + // Disable irq directly for few cycles, + // Validation of the new CC value against the COUNTER, + // Setting the new CC value and enabling CC IRQ should be an atomic operation + // Otherwise, there is a possibility to set an invalid CC value because + // the RTC1 keeps running. + // This code is very short 20-38 cycles in the worst case, it shouldn't + // disturb softdevice. + core_util_critical_section_enter(); + uint32_t current_counter = nrf_rtc_counter_get(COMMON_RTC_INSTANCE); + + // If an overflow occur, set the next tick in COUNTER + delta clock cycles + if (is_in_wrapped_range(previous_tick_cc_value, new_compare_value, current_counter + 1) == false) + { + new_compare_value = current_counter + delta; + } + nrf_rtc_cc_set(COMMON_RTC_INSTANCE, OS_TICK_CC_CHANNEL, new_compare_value); + // Enable generation of the compare event for the value set above (this + // event will trigger the interrupt). + nrf_rtc_event_enable(COMMON_RTC_INSTANCE, OS_TICK_INT_MASK); + core_util_critical_section_exit(); +} + +/** + * Initialize alternative hardware timer as RTX kernel timer + * This function is directly called by RTX. + * @note this function shouldn't be called directly. + * @return IRQ number of the alternative hardware timer + */ +int os_tick_init (void) +{ + common_rtc_init(); + nrf_rtc_int_enable(COMMON_RTC_INSTANCE, OS_TICK_INT_MASK); + + nrf_rtc_cc_set(COMMON_RTC_INSTANCE, OS_TICK_CC_CHANNEL, 0); + register_next_tick(); + + return nrf_drv_get_IRQn(COMMON_RTC_INSTANCE); +} + +/** + * Acknowledge the tick interrupt. + * This function is called by the function OS_Tick_Handler of RTX. + * @note this function shouldn't be called directly. + */ +void os_tick_irqack(void) +{ + clear_tick_interrupt(); + register_next_tick(); +} + +/** + * Returns the overflow flag of the alternative hardware timer. + * @note This function is exposed by RTX kernel. + * @return 1 if the timer has overflowed and 0 otherwise. + */ +uint32_t os_tick_ovf(void) +{ + uint32_t current_counter = nrf_rtc_counter_get(COMMON_RTC_INSTANCE); + uint32_t next_tick_cc_value = nrf_rtc_cc_get(COMMON_RTC_INSTANCE, OS_TICK_CC_CHANNEL); + + return is_in_wrapped_range(previous_tick_cc_value, next_tick_cc_value, current_counter) ? 0 : 1; +} + +/** + * Return the value of the alternative hardware timer. + * @note The documentation is not very clear about what is expected as a result, + * is it an ascending counter, a descending one ? + * None of this is specified. + * The default systick is a descending counter and this function return values in + * descending order, even if the internal counter used is an ascending one. + * @return the value of the alternative hardware timer. + */ +uint32_t os_tick_val(void) +{ + uint32_t current_counter = nrf_rtc_counter_get(COMMON_RTC_INSTANCE); + uint32_t next_tick_cc_value = nrf_rtc_cc_get(COMMON_RTC_INSTANCE, OS_TICK_CC_CHANNEL); + + // do not use os_tick_ovf because its counter value can be different + if (is_in_wrapped_range(previous_tick_cc_value, next_tick_cc_value, current_counter)) + { + if (next_tick_cc_value > previous_tick_cc_value) + { + return next_tick_cc_value - current_counter; + } + else if (current_counter <= next_tick_cc_value) + { + return next_tick_cc_value - current_counter; + } + else + { + return next_tick_cc_value + (MAX_RTC_COUNTER_VAL - current_counter); + } + } + else + { + // use (os_trv + 1) has the base step, can be totally inacurate ... + uint32_t clock_cycles_by_tick = os_trv + 1; + + // if current counter has wrap arround, add the limit to it. + if (current_counter < next_tick_cc_value) + { + current_counter = current_counter + MAX_RTC_COUNTER_VAL; + } + + return clock_cycles_by_tick - ((current_counter - next_tick_cc_value) % clock_cycles_by_tick); + } + +} + +#endif // defined(TARGET_MCU_NRF51822) diff --git a/targets/TARGET_NORDIC/mbed_rtx.h b/targets/TARGET_NORDIC/mbed_rtx.h index 4318915f37e..15c1ef684f3 100644 --- a/targets/TARGET_NORDIC/mbed_rtx.h +++ b/targets/TARGET_NORDIC/mbed_rtx.h @@ -28,7 +28,7 @@ #endif #ifndef OS_TASKCNT -#define OS_TASKCNT 7 +#define OS_TASKCNT 6 #endif #ifndef OS_MAINSTKSIZE #define OS_MAINSTKSIZE 512 @@ -46,7 +46,7 @@ #define INITIAL_SP (0x20010000UL) #endif #ifndef OS_TASKCNT -#define OS_TASKCNT 7 +#define OS_TASKCNT 6 #endif #ifndef OS_MAINSTKSIZE #define OS_MAINSTKSIZE 512 diff --git a/targets/TARGET_NUVOTON/TARGET_M451/TARGET_NUMAKER_PFM_M453/objects.h b/targets/TARGET_NUVOTON/TARGET_M451/TARGET_NUMAKER_PFM_M453/objects.h index 6744a32ce9a..7191422fa09 100644 --- a/targets/TARGET_NUVOTON/TARGET_M451/TARGET_NUMAKER_PFM_M453/objects.h +++ b/targets/TARGET_NUVOTON/TARGET_M451/TARGET_NUMAKER_PFM_M453/objects.h @@ -61,7 +61,6 @@ struct serial_s { void (*vec)(void); uint32_t irq_handler; uint32_t irq_id; - uint32_t irq_en; uint32_t inten_msk; // Async transfer related fields diff --git a/targets/TARGET_NUVOTON/TARGET_M451/device/TOOLCHAIN_ARM_MICRO/M453.sct b/targets/TARGET_NUVOTON/TARGET_M451/device/TOOLCHAIN_ARM_MICRO/M453.sct index f33be95109f..f9346f10c32 100644 --- a/targets/TARGET_NUVOTON/TARGET_M451/device/TOOLCHAIN_ARM_MICRO/M453.sct +++ b/targets/TARGET_NUVOTON/TARGET_M451/device/TOOLCHAIN_ARM_MICRO/M453.sct @@ -1,15 +1,6 @@ -#! armcc -E -#if !defined(MBED_APP_START) - #define MBED_APP_START 0x00000000 -#endif - -#if !defined(MBED_APP_SIZE) - #define MBED_APP_SIZE 0x00040000 -#endif - -LR_IROM1 MBED_APP_START { - ER_IROM1 MBED_APP_START { ; load address = execution address +LR_IROM1 0x00000000 { + ER_IROM1 0x00000000 { ; load address = execution address *(RESET, +First) *(InRoot$$Sections) .ANY (+RO) @@ -32,6 +23,6 @@ LR_IROM1 MBED_APP_START { ARM_LIB_HEAP AlignExpr(+0, 16) EMPTY (0x20000000 + 0x8000 - AlignExpr(ImageLimit(RW_IRAM1), 16)) { } } -ScatterAssert(LoadLimit(LR_IROM1) <= (MBED_APP_START + MBED_APP_SIZE)) ; 256 KB APROM +ScatterAssert(LoadLimit(LR_IROM1) <= 0x00040000) ; 256 KB APROM ScatterAssert(ImageLimit(ARM_LIB_HEAP) <= 0x20008000) ; 32 KB SRAM diff --git a/targets/TARGET_NUVOTON/TARGET_M451/device/TOOLCHAIN_ARM_STD/M453.sct b/targets/TARGET_NUVOTON/TARGET_M451/device/TOOLCHAIN_ARM_STD/M453.sct index f33be95109f..f9346f10c32 100644 --- a/targets/TARGET_NUVOTON/TARGET_M451/device/TOOLCHAIN_ARM_STD/M453.sct +++ b/targets/TARGET_NUVOTON/TARGET_M451/device/TOOLCHAIN_ARM_STD/M453.sct @@ -1,15 +1,6 @@ -#! armcc -E -#if !defined(MBED_APP_START) - #define MBED_APP_START 0x00000000 -#endif - -#if !defined(MBED_APP_SIZE) - #define MBED_APP_SIZE 0x00040000 -#endif - -LR_IROM1 MBED_APP_START { - ER_IROM1 MBED_APP_START { ; load address = execution address +LR_IROM1 0x00000000 { + ER_IROM1 0x00000000 { ; load address = execution address *(RESET, +First) *(InRoot$$Sections) .ANY (+RO) @@ -32,6 +23,6 @@ LR_IROM1 MBED_APP_START { ARM_LIB_HEAP AlignExpr(+0, 16) EMPTY (0x20000000 + 0x8000 - AlignExpr(ImageLimit(RW_IRAM1), 16)) { } } -ScatterAssert(LoadLimit(LR_IROM1) <= (MBED_APP_START + MBED_APP_SIZE)) ; 256 KB APROM +ScatterAssert(LoadLimit(LR_IROM1) <= 0x00040000) ; 256 KB APROM ScatterAssert(ImageLimit(ARM_LIB_HEAP) <= 0x20008000) ; 32 KB SRAM diff --git a/targets/TARGET_NUVOTON/TARGET_M451/device/TOOLCHAIN_GCC_ARM/M453.ld b/targets/TARGET_NUVOTON/TARGET_M451/device/TOOLCHAIN_GCC_ARM/M453.ld index 20b4ac9bcb0..05812d7a4cf 100644 --- a/targets/TARGET_NUVOTON/TARGET_M451/device/TOOLCHAIN_GCC_ARM/M453.ld +++ b/targets/TARGET_NUVOTON/TARGET_M451/device/TOOLCHAIN_GCC_ARM/M453.ld @@ -2,20 +2,12 @@ * Nuvoton M453 GCC linker script file */ -#if !defined(MBED_APP_START) - #define MBED_APP_START 0x00000000 -#endif - -#if !defined(MBED_APP_SIZE) - #define MBED_APP_SIZE 0x00040000 -#endif - StackSize = 0x800; MEMORY { - VECTORS (rx) : ORIGIN = MBED_APP_START, LENGTH = 0x00000400 - FLASH (rx) : ORIGIN = MBED_APP_START + 0x400, LENGTH = MBED_APP_SIZE - 0x00000400 + VECTORS (rx) : ORIGIN = 0x00000000, LENGTH = 0x00000400 + FLASH (rx) : ORIGIN = 0x00000400, LENGTH = 0x00040000 - 0x00000400 RAM_INTERN (rwx) : ORIGIN = 0x20000000, LENGTH = 0x00008000 - 0x00000000 } diff --git a/targets/TARGET_NUVOTON/TARGET_M451/device/TOOLCHAIN_IAR/M453.icf b/targets/TARGET_NUVOTON/TARGET_M451/device/TOOLCHAIN_IAR/M453.icf index 04fab3eee8f..b9f722055f8 100644 --- a/targets/TARGET_NUVOTON/TARGET_M451/device/TOOLCHAIN_IAR/M453.icf +++ b/targets/TARGET_NUVOTON/TARGET_M451/device/TOOLCHAIN_IAR/M453.icf @@ -1,13 +1,11 @@ /*###ICF### Section handled by ICF editor, don't touch! ****/ /*-Editor annotation file-*/ /* IcfEditorFile="$TOOLKIT_DIR$\config\ide\IcfEditor\cortex_v1_0.xml" */ -if (!isdefinedsymbol(MBED_APP_START)) { define symbol MBED_APP_START = 0x00000000; } -if (!isdefinedsymbol(MBED_APP_SIZE)) { define symbol MBED_APP_SIZE = 0x00040000; } /*-Specials-*/ -define symbol __ICFEDIT_intvec_start__ = MBED_APP_START; +define symbol __ICFEDIT_intvec_start__ = 0x00000000; /*-Memory Regions-*/ -define symbol __ICFEDIT_region_ROM_start__ = MBED_APP_START; -define symbol __ICFEDIT_region_ROM_end__ = MBED_APP_START + MBED_APP_SIZE - 1; +define symbol __ICFEDIT_region_ROM_start__ = 0x00000000; +define symbol __ICFEDIT_region_ROM_end__ = 0x00040000; define symbol __ICFEDIT_region_IRAM_start__ = 0x20000000; define symbol __ICFEDIT_region_IRAM_end__ = 0x20008000; /*-Sizes-*/ diff --git a/targets/TARGET_NUVOTON/TARGET_M451/device/cmsis_nvic.h b/targets/TARGET_NUVOTON/TARGET_M451/device/cmsis_nvic.h index 26049c886f3..77cc94d9864 100644 --- a/targets/TARGET_NUVOTON/TARGET_M451/device/cmsis_nvic.h +++ b/targets/TARGET_NUVOTON/TARGET_M451/device/cmsis_nvic.h @@ -32,18 +32,8 @@ # define NVIC_RAM_VECTOR_ADDRESS ((uint32_t) &__start_vector_table__) #endif -#if defined(__CC_ARM) - extern uint32_t Load$$LR$$LR_IROM1$$Base[]; - #define NVIC_FLASH_VECTOR_ADDRESS ((uint32_t)Load$$LR$$LR_IROM1$$Base) -#elif defined(__ICCARM__) - #pragma section=".intvec" - #define NVIC_FLASH_VECTOR_ADDRESS ((uint32_t)__section_begin(".intvec")) -#elif defined(__GNUC__) - extern uint32_t __vector_table; - #define NVIC_FLASH_VECTOR_ADDRESS ((uint32_t)&__vector_table) -#else - #error "Flash vector address not set for this toolchain" -#endif + +#define NVIC_FLASH_VECTOR_ADDRESS 0 #ifdef __cplusplus extern "C" { diff --git a/targets/TARGET_NUVOTON/TARGET_M451/dma_api.c b/targets/TARGET_NUVOTON/TARGET_M451/dma_api.c index ab7fdff47d2..0bfc53f4855 100644 --- a/targets/TARGET_NUVOTON/TARGET_M451/dma_api.c +++ b/targets/TARGET_NUVOTON/TARGET_M451/dma_api.c @@ -23,10 +23,6 @@ #include "nu_bitutil.h" #include "dma.h" -#define NU_PDMA_CH_MAX PDMA_CH_MAX /* Specify maximum channels of PDMA */ -#define NU_PDMA_CH_Pos 0 /* Specify first channel number of PDMA */ -#define NU_PDMA_CH_Msk (((1 << NU_PDMA_CH_MAX) - 1) << NU_PDMA_CH_Pos) - struct nu_dma_chn_s { void (*handler)(uint32_t, uint32_t); uint32_t id; @@ -35,7 +31,7 @@ struct nu_dma_chn_s { static int dma_inited = 0; static uint32_t dma_chn_mask = 0; -static struct nu_dma_chn_s dma_chn_arr[NU_PDMA_CH_MAX]; +static struct nu_dma_chn_s dma_chn_arr[PDMA_CH_MAX]; static void pdma_vec(void); static const struct nu_modinit_s dma_modinit = {DMA_0, PDMA_MODULE, 0, 0, PDMA_RST, PDMA_IRQn, (void *) pdma_vec}; @@ -48,7 +44,7 @@ void dma_init(void) } dma_inited = 1; - dma_chn_mask = ~NU_PDMA_CH_Msk; + dma_chn_mask = 0; memset(dma_chn_arr, 0x00, sizeof (dma_chn_arr)); // Reset this module @@ -69,12 +65,25 @@ int dma_channel_allocate(uint32_t capabilities) dma_init(); } +#if 1 int i = nu_cto(dma_chn_mask); if (i != 32) { dma_chn_mask |= 1 << i; - memset(dma_chn_arr + i - NU_PDMA_CH_Pos, 0x00, sizeof (struct nu_dma_chn_s)); + memset(dma_chn_arr + i, 0x00, sizeof (struct nu_dma_chn_s)); return i; } +#else + int i; + + for (i = 0; i < PDMA_CH_MAX; i ++) { + if ((dma_chn_mask & (1 << i)) == 0) { + // Channel available + dma_chn_mask |= 1 << i; + memset(dma_chn_arr + i, 0x00, sizeof (struct nu_dma_chn_s)); + return i; + } + } +#endif // No channel available return DMA_ERROR_OUT_OF_CHANNELS; @@ -93,9 +102,9 @@ void dma_set_handler(int channelid, uint32_t handler, uint32_t id, uint32_t even { MBED_ASSERT(dma_chn_mask & (1 << channelid)); - dma_chn_arr[channelid - NU_PDMA_CH_Pos].handler = (void (*)(uint32_t, uint32_t)) handler; - dma_chn_arr[channelid - NU_PDMA_CH_Pos].id = id; - dma_chn_arr[channelid - NU_PDMA_CH_Pos].event = event; + dma_chn_arr[channelid].handler = (void (*)(uint32_t, uint32_t)) handler; + dma_chn_arr[channelid].id = id; + dma_chn_arr[channelid].event = event; // Set interrupt vector if someone has removed it. NVIC_SetVector(dma_modinit.irq_n, (uint32_t) dma_modinit.var); @@ -118,14 +127,14 @@ static void pdma_vec(void) PDMA_CLR_ABORT_FLAG(abtsts); while (abtsts) { - int chn_id = nu_ctz(abtsts) - PDMA_ABTSTS_ABTIFn_Pos + NU_PDMA_CH_Pos; + int chn_id = nu_ctz(abtsts); if (dma_chn_mask & (1 << chn_id)) { - struct nu_dma_chn_s *dma_chn = dma_chn_arr + chn_id - NU_PDMA_CH_Pos; + struct nu_dma_chn_s *dma_chn = dma_chn_arr + chn_id; if (dma_chn->handler && (dma_chn->event & DMA_EVENT_ABORT)) { dma_chn->handler(dma_chn->id, DMA_EVENT_ABORT); } } - abtsts &= ~(1 << (chn_id - NU_PDMA_CH_Pos + PDMA_ABTSTS_ABTIFn_Pos)); + abtsts &= ~(1 << chn_id); } } @@ -136,14 +145,14 @@ static void pdma_vec(void) PDMA_CLR_TD_FLAG(tdsts); while (tdsts) { - int chn_id = nu_ctz(tdsts) - PDMA_TDSTS_TDIFn_Pos + NU_PDMA_CH_Pos; + int chn_id = nu_ctz(tdsts); if (dma_chn_mask & (1 << chn_id)) { - struct nu_dma_chn_s *dma_chn = dma_chn_arr + chn_id - NU_PDMA_CH_Pos; + struct nu_dma_chn_s *dma_chn = dma_chn_arr + chn_id; if (dma_chn->handler && (dma_chn->event & DMA_EVENT_TRANSFER_DONE)) { dma_chn->handler(dma_chn->id, DMA_EVENT_TRANSFER_DONE); } } - tdsts &= ~(1 << (chn_id - NU_PDMA_CH_Pos + PDMA_TDSTS_TDIFn_Pos)); + tdsts &= ~(1 << chn_id); } } @@ -161,14 +170,14 @@ static void pdma_vec(void) PDMA->INTSTS = reqto; while (reqto) { - int chn_id = nu_ctz(reqto) - PDMA_INTSTS_REQTOFn_Pos + NU_PDMA_CH_Pos; + int chn_id = nu_ctz(reqto) - PDMA_INTSTS_REQTOFn_Pos; if (dma_chn_mask & (1 << chn_id)) { - struct nu_dma_chn_s *dma_chn = dma_chn_arr + chn_id - NU_PDMA_CH_Pos; + struct nu_dma_chn_s *dma_chn = dma_chn_arr + chn_id; if (dma_chn->handler && (dma_chn->event & DMA_EVENT_TIMEOUT)) { dma_chn->handler(dma_chn->id, DMA_EVENT_TIMEOUT); } } - reqto &= ~(1 << (chn_id - NU_PDMA_CH_Pos + PDMA_INTSTS_REQTOFn_Pos)); + reqto &= ~(1 << (chn_id + PDMA_INTSTS_REQTOFn_Pos)); } } } diff --git a/targets/TARGET_NUVOTON/TARGET_M451/flash_api.c b/targets/TARGET_NUVOTON/TARGET_M451/flash_api.c deleted file mode 100644 index 01e19a20fd2..00000000000 --- a/targets/TARGET_NUVOTON/TARGET_M451/flash_api.c +++ /dev/null @@ -1,79 +0,0 @@ -/* mbed Microcontroller Library - * Copyright (c) 2015-2016 Nuvoton - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * 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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * 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. - */ - -#include "flash_api.h" -#include "flash_data.h" -#include "mbed_critical.h" - -// This is a flash algo binary blob. It is PIC (position independent code) that should be stored in RAM -// NOTE: On ARMv7-M/ARMv8-M, instruction fetches are always little-endian. -static uint32_t FLASH_ALGO[] = { - 0x4603b530, 0x2164460c, 0x4dd72059, 0x20166028, 0xf8c5070d, 0x20880100, 0x0100f8c5, 0xf8d006c0, - 0xf0000100, 0xb9080001, 0xbd302001, 0x680048cf, 0x0004f040, 0x4580f04f, 0x0200f8c5, 0xf8d04628, - 0xf0400204, 0xf8c50004, 0xbf000204, 0xf1a11e08, 0xd1fb0101, 0x680048c6, 0x002df040, 0x60284dc4, - 0x68004628, 0x0001f000, 0x2001b908, 0x48c0e7dd, 0xf0406800, 0x4dbe0040, 0x20006028, 0x4601e7d5, - 0x48bbbf00, 0xf0006900, 0x28000001, 0x48b8d1f9, 0xf0206800, 0x4ab6002d, 0x20006010, 0x60104ab2, - 0x46014770, 0x48b2bf00, 0xf0006900, 0x28000001, 0x48afd1f9, 0xf0406800, 0x4aad0040, 0x20226010, - 0xf02160d0, 0x60500003, 0x61102001, 0x8f60f3bf, 0x48a7bf00, 0xf0006900, 0x28000001, 0x48a4d1f9, - 0xf0006800, 0xb1380040, 0x680048a1, 0x0040f040, 0x60104a9f, 0x47702001, 0xe7fc2000, 0x4604b570, - 0x4615460b, 0x46292200, 0x000ff103, 0x030ff020, 0x4897bf00, 0xf0006900, 0x28000001, 0x4894d1f9, - 0xf0406800, 0x4e920040, 0xf0246030, 0x6070000f, 0x60f02027, 0x1c524610, 0x0020f851, 0x36804e8c, - 0x46106030, 0xf8511c52, 0x4e890020, 0x0084f8c6, 0x1c524610, 0x0020f851, 0x36884e85, 0x46106030, - 0xf8511c52, 0x1d360020, 0x20016030, 0x61304e80, 0xe02c3b10, 0x487ebf00, 0x680030c0, 0x0030f000, - 0xd1f82800, 0x1c524610, 0x0020f851, 0x36804e78, 0x46106030, 0xf8511c52, 0x4e750020, 0x0084f8c6, - 0x4873bf00, 0x680030c0, 0x00c0f000, 0xd1f82800, 0x1c524610, 0x0020f851, 0x36884e6d, 0x46106030, - 0xf8511c52, 0x4e6a0020, 0x008cf8c6, 0x2b003b10, 0xbf00d1d0, 0x69004866, 0x0001f000, 0xd1f92800, - 0xb510bd70, 0x1cc84603, 0x0103f020, 0x4860bf00, 0xf0006900, 0x28000001, 0x485dd1f9, 0xf0406800, - 0x4c5b0040, 0x20216020, 0xe02060e0, 0x0003f023, 0x60604c57, 0x60a06810, 0x61202001, 0x8f60f3bf, - 0x4853bf00, 0xf0006900, 0x28000001, 0x4850d1f9, 0xf0006800, 0xb1380040, 0x6800484d, 0x0040f040, - 0x60204c4b, 0xbd102001, 0x1d121d1b, 0x29001f09, 0x2000d1dc, 0xe92de7f7, 0x460547f0, 0x4616460c, - 0x0800f04f, 0xbf0046c2, 0x69004841, 0x0001f000, 0xd1f92800, 0x6800483e, 0x0040f040, 0x6008493c, - 0xf0201ce0, 0xe02d0403, 0xb958b2e8, 0xd9092cff, 0x7780f44f, 0x0208eb06, 0x46284639, 0xff2ef7ff, - 0xe0164682, 0x0008f3c5, 0x2c10b958, 0xf024d309, 0xeb06070f, 0x46390208, 0xf7ff4628, 0x4682ff1f, - 0x4627e007, 0x0208eb06, 0x46284639, 0xff89f7ff, 0x443d4682, 0x1be444b8, 0x0f00f1ba, 0x2001d002, - 0x87f0e8bd, 0xd1cf2c00, 0xe7f92000, 0x1ccbb510, 0x0103f023, 0x4b1ebf00, 0xf003691b, 0x2b000301, - 0x4b1bd1f9, 0xf043681b, 0x4c190340, 0x23006023, 0xe02560e3, 0x0303f020, 0x60634c15, 0x60a32300, - 0x61232301, 0x8f60f3bf, 0x4b11bf00, 0xf003691b, 0x2b000301, 0x4b0ed1f9, 0xf003681b, 0xb1330340, - 0x681b4b0b, 0x0340f043, 0x60234c09, 0x4b08bd10, 0x6814689b, 0xd00042a3, 0x1d00e7f8, 0x1f091d12, - 0xd1d72900, 0xe7f1bf00, 0x40000100, 0x40000200, 0x4000c000, 0x00000000, -}; - -static const flash_algo_t flash_algo_config = { - .init = 0x00000001, - .uninit = 0x0000007f, - .erase_sector = 0x000000a3, - .program_page = 0x00000257, - .static_base = 0x00000374, - .algo_blob = FLASH_ALGO -}; - -static const sector_info_t sectors_info[] = { - {0x0, 0x800}, // (start, sector size) -}; - -static const flash_target_config_t flash_target_config = { - .page_size = 0x800, // 2 KB - .flash_start = 0x0, - .flash_size = 0x40000, // 256 KB - .sectors = sectors_info, - .sector_info_count = sizeof(sectors_info) / sizeof(sector_info_t) -}; - -void flash_set_target_config(flash_t *obj) -{ - obj->flash_algo = &flash_algo_config; - obj->target_config = &flash_target_config; -} diff --git a/targets/TARGET_NUVOTON/TARGET_M451/pwmout_api.c b/targets/TARGET_NUVOTON/TARGET_M451/pwmout_api.c index f89dc4f6a00..f04d1b8b057 100644 --- a/targets/TARGET_NUVOTON/TARGET_M451/pwmout_api.c +++ b/targets/TARGET_NUVOTON/TARGET_M451/pwmout_api.c @@ -99,9 +99,11 @@ void pwmout_init(pwmout_t* obj, PinName pin) ((struct nu_pwm_var *) modinit->var)->en_msk |= 1 << chn; - // Mark this module to be inited. - int i = modinit - pwm_modinit_tab; - pwm_modinit_mask |= 1 << i; + if (((struct nu_pwm_var *) modinit->var)->en_msk) { + // Mark this module to be inited. + int i = modinit - pwm_modinit_tab; + pwm_modinit_mask |= 1 << i; + } } void pwmout_free(pwmout_t* obj) @@ -120,9 +122,11 @@ void pwmout_free(pwmout_t* obj) CLK_DisableModuleClock(modinit->clkidx); } - // Mark this module to be deinited. - int i = modinit - pwm_modinit_tab; - pwm_modinit_mask &= ~(1 << i); + if (((struct nu_pwm_var *) modinit->var)->en_msk == 0) { + // Mark this module to be deinited. + int i = modinit - pwm_modinit_tab; + pwm_modinit_mask &= ~(1 << i); + } } void pwmout_write(pwmout_t* obj, float value) diff --git a/targets/TARGET_NUVOTON/TARGET_M451/serial_api.c b/targets/TARGET_NUVOTON/TARGET_M451/serial_api.c index 4fa7e7a47ac..30eb950285f 100644 --- a/targets/TARGET_NUVOTON/TARGET_M451/serial_api.c +++ b/targets/TARGET_NUVOTON/TARGET_M451/serial_api.c @@ -24,7 +24,6 @@ #include "PeripheralPins.h" #include "nu_modutil.h" #include "nu_bitutil.h" -#include #if DEVICE_SERIAL_ASYNCH #include "dma_api.h" @@ -62,8 +61,6 @@ static void uart_dma_handler_rx(uint32_t id, uint32_t event); static void serial_tx_enable_interrupt(serial_t *obj, uint32_t address, uint8_t enable); static void serial_rx_enable_interrupt(serial_t *obj, uint32_t address, uint8_t enable); -static void serial_enable_interrupt(serial_t *obj, SerialIrq irq, uint32_t enable); -static void serial_rollback_interrupt(serial_t *obj, SerialIrq irq); static int serial_write_async(serial_t *obj); static int serial_read_async(serial_t *obj); @@ -162,7 +159,7 @@ void serial_init(serial_t *obj, PinName tx, PinName rx) const struct nu_modinit_s *modinit = get_modinit(obj->serial.uart, uart_modinit_tab); MBED_ASSERT(modinit != NULL); - MBED_ASSERT(modinit->modname == (int) obj->serial.uart); + MBED_ASSERT(modinit->modname == obj->serial.uart); struct nu_uart_var *var = (struct nu_uart_var *) modinit->var; @@ -189,7 +186,6 @@ void serial_init(serial_t *obj, PinName tx, PinName rx) serial_format(obj, 8, ParityNone, 1); obj->serial.vec = var->vec; - obj->serial.irq_en = 0; #if DEVICE_SERIAL_ASYNCH obj->serial.dma_usage_tx = DMA_USAGE_NEVER; @@ -216,7 +212,7 @@ void serial_free(serial_t *obj) { const struct nu_modinit_s *modinit = get_modinit(obj->serial.uart, uart_modinit_tab); MBED_ASSERT(modinit != NULL); - MBED_ASSERT(modinit->modname == (int) obj->serial.uart); + MBED_ASSERT(modinit->modname == obj->serial.uart); struct nu_uart_var *var = (struct nu_uart_var *) modinit->var; @@ -333,7 +329,7 @@ void serial_irq_handler(serial_t *obj, uart_irq_handler handler, uint32_t id) const struct nu_modinit_s *modinit = get_modinit(obj->serial.uart, uart_modinit_tab); MBED_ASSERT(modinit != NULL); - MBED_ASSERT(modinit->modname == (int) obj->serial.uart); + MBED_ASSERT(modinit->modname == obj->serial.uart); obj->serial.irq_handler = (uint32_t) handler; obj->serial.irq_id = id; @@ -344,18 +340,51 @@ void serial_irq_handler(serial_t *obj, uart_irq_handler handler, uint32_t id) void serial_irq_set(serial_t *obj, SerialIrq irq, uint32_t enable) { - obj->serial.irq_en = enable; - serial_enable_interrupt(obj, irq, enable); + if (enable) { + const struct nu_modinit_s *modinit = get_modinit(obj->serial.uart, uart_modinit_tab); + MBED_ASSERT(modinit != NULL); + MBED_ASSERT(modinit->modname == obj->serial.uart); + + NVIC_SetVector(modinit->irq_n, (uint32_t) obj->serial.vec); + NVIC_EnableIRQ(modinit->irq_n); + + struct nu_uart_var *var = (struct nu_uart_var *) modinit->var; + // Multiple serial S/W objects for single UART H/W module possibly. + // Bind serial S/W object to UART H/W module as interrupt is enabled. + var->obj = obj; + + switch (irq) { + // NOTE: Setting inten_msk first to avoid race condition + case RxIrq: + obj->serial.inten_msk = obj->serial.inten_msk | (UART_INTEN_RDAIEN_Msk | UART_INTEN_RXTOIEN_Msk); + UART_ENABLE_INT(((UART_T *) NU_MODBASE(obj->serial.uart)), (UART_INTEN_RDAIEN_Msk | UART_INTEN_RXTOIEN_Msk)); + break; + case TxIrq: + obj->serial.inten_msk = obj->serial.inten_msk | UART_INTEN_THREIEN_Msk; + UART_ENABLE_INT(((UART_T *) NU_MODBASE(obj->serial.uart)), UART_INTEN_THREIEN_Msk); + break; + } + } else { // disable + switch (irq) { + case RxIrq: + UART_DISABLE_INT(((UART_T *) NU_MODBASE(obj->serial.uart)), (UART_INTEN_RDAIEN_Msk | UART_INTEN_RXTOIEN_Msk)); + obj->serial.inten_msk = obj->serial.inten_msk & ~(UART_INTEN_RDAIEN_Msk | UART_INTEN_RXTOIEN_Msk); + break; + case TxIrq: + UART_DISABLE_INT(((UART_T *) NU_MODBASE(obj->serial.uart)), UART_INTEN_THREIEN_Msk); + obj->serial.inten_msk = obj->serial.inten_msk & ~UART_INTEN_THREIEN_Msk; + break; + } + } } int serial_getc(serial_t *obj) { - // NOTE: Every byte access requires accompaniment of one interrupt. This has side effect of performance degradation. + // TODO: Fix every byte access requires accompaniness of one interrupt. This degrades performance much. while (! serial_readable(obj)); int c = UART_READ(((UART_T *) NU_MODBASE(obj->serial.uart))); - // NOTE: On Nuvoton targets, no H/W IRQ to match TxIrq/RxIrq. - // Simulation of TxIrq/RxIrq requires the call to Serial::putc()/Serial::getc() respectively. + // Simulate clear of the interrupt flag if (obj->serial.inten_msk & (UART_INTEN_RDAIEN_Msk | UART_INTEN_RXTOIEN_Msk)) { UART_ENABLE_INT(((UART_T *) NU_MODBASE(obj->serial.uart)), (UART_INTEN_RDAIEN_Msk | UART_INTEN_RXTOIEN_Msk)); } @@ -365,12 +394,11 @@ int serial_getc(serial_t *obj) void serial_putc(serial_t *obj, int c) { - // NOTE: Every byte access requires accompaniment of one interrupt. This has side effect of performance degradation. + // TODO: Fix every byte access requires accompaniness of one interrupt. This degrades performance much. while (! serial_writable(obj)); UART_WRITE(((UART_T *) NU_MODBASE(obj->serial.uart)), c); - // NOTE: On Nuvoton targets, no H/W IRQ to match TxIrq/RxIrq. - // Simulation of TxIrq/RxIrq requires the call to Serial::putc()/Serial::getc() respectively. + // Simulate clear of the interrupt flag if (obj->serial.inten_msk & UART_INTEN_THREIEN_Msk) { UART_ENABLE_INT(((UART_T *) NU_MODBASE(obj->serial.uart)), UART_INTEN_THREIEN_Msk); } @@ -472,7 +500,7 @@ int serial_tx_asynch(serial_t *obj, const void *tx, size_t tx_length, uint8_t tx // DMA way const struct nu_modinit_s *modinit = get_modinit(obj->serial.uart, uart_modinit_tab); MBED_ASSERT(modinit != NULL); - MBED_ASSERT(modinit->modname == (int) obj->serial.uart); + MBED_ASSERT(modinit->modname == obj->serial.uart); PDMA_T *pdma_base = dma_modbase(); @@ -535,7 +563,7 @@ void serial_rx_asynch(serial_t *obj, void *rx, size_t rx_length, uint8_t rx_widt // DMA way const struct nu_modinit_s *modinit = get_modinit(obj->serial.uart, uart_modinit_tab); MBED_ASSERT(modinit != NULL); - MBED_ASSERT(modinit->modname == (int) obj->serial.uart); + MBED_ASSERT(modinit->modname == obj->serial.uart); PDMA_T *pdma_base = dma_modbase(); @@ -584,8 +612,10 @@ void serial_tx_abort_asynch(serial_t *obj) } // Necessary for both interrupt way and DMA way - serial_enable_interrupt(obj, TxIrq, 0); - serial_rollback_interrupt(obj, TxIrq); + serial_irq_set(obj, TxIrq, 0); + // FIXME: more complete abort operation + //UART_HAL_DisableTransmitter(obj->serial.serial.address); + //UART_HAL_FlushTxFifo(obj->serial.serial.address); } void serial_rx_abort_asynch(serial_t *obj) @@ -603,30 +633,20 @@ void serial_rx_abort_asynch(serial_t *obj) } // Necessary for both interrupt way and DMA way - serial_enable_interrupt(obj, RxIrq, 0); - serial_rollback_interrupt(obj, RxIrq); + serial_irq_set(obj, RxIrq, 0); + // FIXME: more complete abort operation + //UART_HAL_DisableReceiver(obj->serial.serial.address); + //UART_HAL_FlushRxFifo(obj->serial.serial.address); } uint8_t serial_tx_active(serial_t *obj) { - // NOTE: Judge by serial_is_irq_en(obj, TxIrq) doesn't work with sync/async modes interleaved. Change with TX FIFO empty flag. - const struct nu_modinit_s *modinit = get_modinit(obj->serial.uart, uart_modinit_tab); - MBED_ASSERT(modinit != NULL); - MBED_ASSERT(modinit->modname == (int) obj->serial.uart); - - struct nu_uart_var *var = (struct nu_uart_var *) modinit->var; - return (obj->serial.vec == var->vec_async); + return serial_is_irq_en(obj, TxIrq); } uint8_t serial_rx_active(serial_t *obj) { - // NOTE: Judge by serial_is_irq_en(obj, RxIrq) doesn't work with sync/async modes interleaved. Change with RX FIFO empty flag. - const struct nu_modinit_s *modinit = get_modinit(obj->serial.uart, uart_modinit_tab); - MBED_ASSERT(modinit != NULL); - MBED_ASSERT(modinit->modname == (int) obj->serial.uart); - - struct nu_uart_var *var = (struct nu_uart_var *) modinit->var; - return (obj->serial.vec == var->vec_async); + return serial_is_irq_en(obj, RxIrq); } int serial_irq_handler_asynch(serial_t *obj) @@ -866,7 +886,7 @@ static int serial_write_async(serial_t *obj) { const struct nu_modinit_s *modinit = get_modinit(obj->serial.uart, uart_modinit_tab); MBED_ASSERT(modinit != NULL); - MBED_ASSERT(modinit->modname == (int) obj->serial.uart); + MBED_ASSERT(modinit->modname == obj->serial.uart); UART_T *uart_base = (UART_T *) NU_MODBASE(obj->serial.uart); @@ -918,7 +938,7 @@ static int serial_read_async(serial_t *obj) { const struct nu_modinit_s *modinit = get_modinit(obj->serial.uart, uart_modinit_tab); MBED_ASSERT(modinit != NULL); - MBED_ASSERT(modinit->modname == (int) obj->serial.uart); + MBED_ASSERT(modinit->modname == obj->serial.uart); uint32_t rx_fifo_busy = (((UART_T *) NU_MODBASE(obj->serial.uart))->FIFOSTS & UART_FIFOSTS_RXPTR_Msk) >> UART_FIFOSTS_RXPTR_Pos; //uint32_t rx_fifo_free = ((struct nu_uart_var *) modinit->var)->fifo_size_rx - rx_fifo_busy; @@ -993,81 +1013,28 @@ static void serial_tx_enable_interrupt(serial_t *obj, uint32_t handler, uint8_t { const struct nu_modinit_s *modinit = get_modinit(obj->serial.uart, uart_modinit_tab); MBED_ASSERT(modinit != NULL); - MBED_ASSERT(modinit->modname == (int) obj->serial.uart); + MBED_ASSERT(modinit->modname == obj->serial.uart); // Necessary for both interrupt way and DMA way struct nu_uart_var *var = (struct nu_uart_var *) modinit->var; // With our own async vector, tx/rx handlers can be different. obj->serial.vec = var->vec_async; obj->serial.irq_handler_tx_async = (void (*)(void)) handler; - serial_enable_interrupt(obj, TxIrq, enable); + serial_irq_set(obj, TxIrq, enable); } static void serial_rx_enable_interrupt(serial_t *obj, uint32_t handler, uint8_t enable) { const struct nu_modinit_s *modinit = get_modinit(obj->serial.uart, uart_modinit_tab); MBED_ASSERT(modinit != NULL); - MBED_ASSERT(modinit->modname == (int) obj->serial.uart); + MBED_ASSERT(modinit->modname == obj->serial.uart); // Necessary for both interrupt way and DMA way struct nu_uart_var *var = (struct nu_uart_var *) modinit->var; // With our own async vector, tx/rx handlers can be different. obj->serial.vec = var->vec_async; obj->serial.irq_handler_rx_async = (void (*) (void)) handler; - serial_enable_interrupt(obj, RxIrq, enable); -} - -static void serial_enable_interrupt(serial_t *obj, SerialIrq irq, uint32_t enable) -{ - if (enable) { - const struct nu_modinit_s *modinit = get_modinit(obj->serial.uart, uart_modinit_tab); - MBED_ASSERT(modinit != NULL); - MBED_ASSERT(modinit->modname == (int) obj->serial.uart); - - NVIC_SetVector(modinit->irq_n, (uint32_t) obj->serial.vec); - NVIC_EnableIRQ(modinit->irq_n); - - struct nu_uart_var *var = (struct nu_uart_var *) modinit->var; - // Multiple serial S/W objects for single UART H/W module possibly. - // Bind serial S/W object to UART H/W module as interrupt is enabled. - var->obj = obj; - - switch (irq) { - // NOTE: Setting inten_msk first to avoid race condition - case RxIrq: - obj->serial.inten_msk = obj->serial.inten_msk | (UART_INTEN_RDAIEN_Msk | UART_INTEN_RXTOIEN_Msk); - UART_ENABLE_INT(((UART_T *) NU_MODBASE(obj->serial.uart)), (UART_INTEN_RDAIEN_Msk | UART_INTEN_RXTOIEN_Msk)); - break; - case TxIrq: - obj->serial.inten_msk = obj->serial.inten_msk | UART_INTEN_THREIEN_Msk; - UART_ENABLE_INT(((UART_T *) NU_MODBASE(obj->serial.uart)), UART_INTEN_THREIEN_Msk); - break; - } - } - else { // disable - switch (irq) { - case RxIrq: - UART_DISABLE_INT(((UART_T *) NU_MODBASE(obj->serial.uart)), (UART_INTEN_RDAIEN_Msk | UART_INTEN_RXTOIEN_Msk)); - obj->serial.inten_msk = obj->serial.inten_msk & ~(UART_INTEN_RDAIEN_Msk | UART_INTEN_RXTOIEN_Msk); - break; - case TxIrq: - UART_DISABLE_INT(((UART_T *) NU_MODBASE(obj->serial.uart)), UART_INTEN_THREIEN_Msk); - obj->serial.inten_msk = obj->serial.inten_msk & ~UART_INTEN_THREIEN_Msk; - break; - } - } -} - -static void serial_rollback_interrupt(serial_t *obj, SerialIrq irq) -{ - const struct nu_modinit_s *modinit = get_modinit(obj->serial.uart, uart_modinit_tab); - MBED_ASSERT(modinit != NULL); - MBED_ASSERT(modinit->modname == (int) obj->serial.uart); - - struct nu_uart_var *var = (struct nu_uart_var *) modinit->var; - - obj->serial.vec = var->vec; - serial_enable_interrupt(obj, irq, obj->serial.irq_en); + serial_irq_set(obj, RxIrq, enable); } static void serial_check_dma_usage(DMAUsage *dma_usage, int *dma_ch) diff --git a/targets/TARGET_NUVOTON/TARGET_NUC472/TARGET_NUMAKER_PFM_NUC472/objects.h b/targets/TARGET_NUVOTON/TARGET_NUC472/TARGET_NUMAKER_PFM_NUC472/objects.h index 2e62f15efc7..2f0596770b3 100644 --- a/targets/TARGET_NUVOTON/TARGET_NUC472/TARGET_NUMAKER_PFM_NUC472/objects.h +++ b/targets/TARGET_NUVOTON/TARGET_NUC472/TARGET_NUMAKER_PFM_NUC472/objects.h @@ -61,7 +61,6 @@ struct serial_s { void (*vec)(void); uint32_t irq_handler; uint32_t irq_id; - uint32_t irq_en; uint32_t inten_msk; // Async transfer related fields diff --git a/targets/TARGET_NUVOTON/TARGET_NUC472/device/TOOLCHAIN_ARM_MICRO/TARGET_NU_XRAM_SUPPORTED/NUC472.sct b/targets/TARGET_NUVOTON/TARGET_NUC472/device/TOOLCHAIN_ARM_MICRO/TARGET_NU_XRAM_SUPPORTED/NUC472.sct index 5247706a714..be17f4b49fb 100644 --- a/targets/TARGET_NUVOTON/TARGET_NUC472/device/TOOLCHAIN_ARM_MICRO/TARGET_NU_XRAM_SUPPORTED/NUC472.sct +++ b/targets/TARGET_NUVOTON/TARGET_NUC472/device/TOOLCHAIN_ARM_MICRO/TARGET_NU_XRAM_SUPPORTED/NUC472.sct @@ -1,15 +1,6 @@ -#! armcc -E -#if !defined(MBED_APP_START) - #define MBED_APP_START 0x00000000 -#endif - -#if !defined(MBED_APP_SIZE) - #define MBED_APP_SIZE 0x00080000 -#endif - -LR_IROM1 MBED_APP_START { - ER_IROM1 MBED_APP_START { ; load address = execution address +LR_IROM1 0x00000000 { + ER_IROM1 0x00000000 { ; load address = execution address *(RESET, +First) *(InRoot$$Sections) .ANY (+RO) @@ -38,7 +29,7 @@ LR_IROM1 MBED_APP_START { ARM_LIB_HEAP AlignExpr(+0, 16) EMPTY (0x60000000 + 0x100000 - AlignExpr(ImageLimit(ER_XRAM1), 16)) { } } -ScatterAssert(LoadLimit(LR_IROM1) <= (MBED_APP_START + MBED_APP_SIZE)) ; 512 KB APROM +ScatterAssert(LoadLimit(LR_IROM1) <= 0x00080000) ; 512 KB APROM ScatterAssert(ImageLimit(RW_IRAM1) <= 0x20010000) ; 64 KB SRAM (internal) ScatterAssert(ImageLimit(ARM_LIB_HEAP) <= 0x60100000) ; 1 MB SRAM (external) diff --git a/targets/TARGET_NUVOTON/TARGET_NUC472/device/TOOLCHAIN_ARM_MICRO/TARGET_NU_XRAM_UNSUPPORTED/NUC472.sct b/targets/TARGET_NUVOTON/TARGET_NUC472/device/TOOLCHAIN_ARM_MICRO/TARGET_NU_XRAM_UNSUPPORTED/NUC472.sct index 5a392251b49..5b3d1bc55d7 100644 --- a/targets/TARGET_NUVOTON/TARGET_NUC472/device/TOOLCHAIN_ARM_MICRO/TARGET_NU_XRAM_UNSUPPORTED/NUC472.sct +++ b/targets/TARGET_NUVOTON/TARGET_NUC472/device/TOOLCHAIN_ARM_MICRO/TARGET_NU_XRAM_UNSUPPORTED/NUC472.sct @@ -1,15 +1,6 @@ -#! armcc -E -#if !defined(MBED_APP_START) - #define MBED_APP_START 0x00000000 -#endif - -#if !defined(MBED_APP_SIZE) - #define MBED_APP_SIZE 0x00080000 -#endif - -LR_IROM1 MBED_APP_START { - ER_IROM1 MBED_APP_START { ; load address = execution address +LR_IROM1 0x00000000 { + ER_IROM1 0x00000000 { ; load address = execution address *(RESET, +First) *(InRoot$$Sections) .ANY (+RO) @@ -33,6 +24,6 @@ LR_IROM1 MBED_APP_START { ARM_LIB_HEAP AlignExpr(+0, 16) EMPTY (0x20000000 + 0x10000 - AlignExpr(ImageLimit(RW_IRAM1), 16)) { } } -ScatterAssert(LoadLimit(LR_IROM1) <= (MBED_APP_START + MBED_APP_SIZE)) ; 512 KB APROM +ScatterAssert(LoadLimit(LR_IROM1) <= 0x00080000) ; 512 KB APROM ScatterAssert(ImageLimit(RW_IRAM1) <= 0x20010000) ; 64 KB SRAM (internal) diff --git a/targets/TARGET_NUVOTON/TARGET_NUC472/device/TOOLCHAIN_ARM_STD/TARGET_NU_XRAM_SUPPORTED/NUC472.sct b/targets/TARGET_NUVOTON/TARGET_NUC472/device/TOOLCHAIN_ARM_STD/TARGET_NU_XRAM_SUPPORTED/NUC472.sct index 7c9673d3b9f..459f97c3d38 100644 --- a/targets/TARGET_NUVOTON/TARGET_NUC472/device/TOOLCHAIN_ARM_STD/TARGET_NU_XRAM_SUPPORTED/NUC472.sct +++ b/targets/TARGET_NUVOTON/TARGET_NUC472/device/TOOLCHAIN_ARM_STD/TARGET_NU_XRAM_SUPPORTED/NUC472.sct @@ -1,15 +1,6 @@ -#! armcc -E -#if !defined(MBED_APP_START) - #define MBED_APP_START 0x00000000 -#endif - -#if !defined(MBED_APP_SIZE) - #define MBED_APP_SIZE 0x00080000 -#endif - -LR_IROM1 MBED_APP_START { - ER_IROM1 MBED_APP_START { ; load address = execution address +LR_IROM1 0x00000000 { + ER_IROM1 0x00000000 { ; load address = execution address *(RESET, +First) *(InRoot$$Sections) .ANY (+RO) @@ -40,7 +31,7 @@ LR_IROM1 MBED_APP_START { ARM_LIB_HEAP AlignExpr(+0, 16) EMPTY (0x60000000 + 0x100000 - AlignExpr(ImageLimit(ER_XRAM1), 16)) { } } -ScatterAssert(LoadLimit(LR_IROM1) <= (MBED_APP_START + MBED_APP_SIZE)) ; 512 KB APROM +ScatterAssert(LoadLimit(LR_IROM1) <= 0x00080000) ; 512 KB APROM ScatterAssert(ImageLimit(RW_IRAM1) <= 0x20010000) ; 64 KB SRAM (internal) ScatterAssert(ImageLimit(ARM_LIB_HEAP) <= 0x60100000) ; 1 MB SRAM (external) diff --git a/targets/TARGET_NUVOTON/TARGET_NUC472/device/TOOLCHAIN_ARM_STD/TARGET_NU_XRAM_UNSUPPORTED/NUC472.sct b/targets/TARGET_NUVOTON/TARGET_NUC472/device/TOOLCHAIN_ARM_STD/TARGET_NU_XRAM_UNSUPPORTED/NUC472.sct index 5a392251b49..5b3d1bc55d7 100644 --- a/targets/TARGET_NUVOTON/TARGET_NUC472/device/TOOLCHAIN_ARM_STD/TARGET_NU_XRAM_UNSUPPORTED/NUC472.sct +++ b/targets/TARGET_NUVOTON/TARGET_NUC472/device/TOOLCHAIN_ARM_STD/TARGET_NU_XRAM_UNSUPPORTED/NUC472.sct @@ -1,15 +1,6 @@ -#! armcc -E -#if !defined(MBED_APP_START) - #define MBED_APP_START 0x00000000 -#endif - -#if !defined(MBED_APP_SIZE) - #define MBED_APP_SIZE 0x00080000 -#endif - -LR_IROM1 MBED_APP_START { - ER_IROM1 MBED_APP_START { ; load address = execution address +LR_IROM1 0x00000000 { + ER_IROM1 0x00000000 { ; load address = execution address *(RESET, +First) *(InRoot$$Sections) .ANY (+RO) @@ -33,6 +24,6 @@ LR_IROM1 MBED_APP_START { ARM_LIB_HEAP AlignExpr(+0, 16) EMPTY (0x20000000 + 0x10000 - AlignExpr(ImageLimit(RW_IRAM1), 16)) { } } -ScatterAssert(LoadLimit(LR_IROM1) <= (MBED_APP_START + MBED_APP_SIZE)) ; 512 KB APROM +ScatterAssert(LoadLimit(LR_IROM1) <= 0x00080000) ; 512 KB APROM ScatterAssert(ImageLimit(RW_IRAM1) <= 0x20010000) ; 64 KB SRAM (internal) diff --git a/targets/TARGET_NUVOTON/TARGET_NUC472/device/TOOLCHAIN_GCC_ARM/TARGET_NU_XRAM_SUPPORTED/NUC472.ld b/targets/TARGET_NUVOTON/TARGET_NUC472/device/TOOLCHAIN_GCC_ARM/TARGET_NU_XRAM_SUPPORTED/NUC472.ld index 3f16540c971..c0ba5faf55b 100644 --- a/targets/TARGET_NUVOTON/TARGET_NUC472/device/TOOLCHAIN_GCC_ARM/TARGET_NU_XRAM_SUPPORTED/NUC472.ld +++ b/targets/TARGET_NUVOTON/TARGET_NUC472/device/TOOLCHAIN_GCC_ARM/TARGET_NU_XRAM_SUPPORTED/NUC472.ld @@ -2,21 +2,13 @@ * Nuvoton NUC472 GCC linker script file */ -#if !defined(MBED_APP_START) - #define MBED_APP_START 0x00000000 -#endif - -#if !defined(MBED_APP_SIZE) - #define MBED_APP_SIZE 0x00080000 -#endif - StackSize = 0x800; MEMORY { - VECTORS (rx) : ORIGIN = MBED_APP_START, LENGTH = 0x00000400 - FLASH (rx) : ORIGIN = MBED_APP_START + 0x400, LENGTH = MBED_APP_SIZE - 0x00000400 + VECTORS (rx) : ORIGIN = 0x00000000, LENGTH = 0x00000400 + FLASH (rx) : ORIGIN = 0x00000400, LENGTH = 0x00080000 - 0x00000400 RAM_INTERN (rwx) : ORIGIN = 0x20000000, LENGTH = 0x00010000 - 0x00000000 RAM_EXTERN (rwx) : ORIGIN = 0x60000000, LENGTH = 0x00100000 } diff --git a/targets/TARGET_NUVOTON/TARGET_NUC472/device/TOOLCHAIN_GCC_ARM/TARGET_NU_XRAM_UNSUPPORTED/NUC472.ld b/targets/TARGET_NUVOTON/TARGET_NUC472/device/TOOLCHAIN_GCC_ARM/TARGET_NU_XRAM_UNSUPPORTED/NUC472.ld index 6a85b9339cf..3440229f87c 100644 --- a/targets/TARGET_NUVOTON/TARGET_NUC472/device/TOOLCHAIN_GCC_ARM/TARGET_NU_XRAM_UNSUPPORTED/NUC472.ld +++ b/targets/TARGET_NUVOTON/TARGET_NUC472/device/TOOLCHAIN_GCC_ARM/TARGET_NU_XRAM_UNSUPPORTED/NUC472.ld @@ -2,21 +2,13 @@ * Nuvoton NUC472 GCC linker script file */ -#if !defined(MBED_APP_START) - #define MBED_APP_START 0x00000000 -#endif - -#if !defined(MBED_APP_SIZE) - #define MBED_APP_SIZE 0x00080000 -#endif - StackSize = 0x800; MEMORY { - VECTORS (rx) : ORIGIN = MBED_APP_START, LENGTH = 0x00000400 - FLASH (rx) : ORIGIN = MBED_APP_START + 0x400, LENGTH = MBED_APP_SIZE - 0x00000400 + VECTORS (rx) : ORIGIN = 0x00000000, LENGTH = 0x00000400 + FLASH (rx) : ORIGIN = 0x00000400, LENGTH = 0x00080000 - 0x00000400 RAM_INTERN (rwx) : ORIGIN = 0x20000000, LENGTH = 0x00010000 - 0x00000000 } diff --git a/targets/TARGET_NUVOTON/TARGET_NUC472/device/TOOLCHAIN_IAR/TARGET_NU_XRAM_SUPPORTED/NUC472_442.icf b/targets/TARGET_NUVOTON/TARGET_NUC472/device/TOOLCHAIN_IAR/TARGET_NU_XRAM_SUPPORTED/NUC472_442.icf index 70faed67f71..e625d5cc796 100644 --- a/targets/TARGET_NUVOTON/TARGET_NUC472/device/TOOLCHAIN_IAR/TARGET_NU_XRAM_SUPPORTED/NUC472_442.icf +++ b/targets/TARGET_NUVOTON/TARGET_NUC472/device/TOOLCHAIN_IAR/TARGET_NU_XRAM_SUPPORTED/NUC472_442.icf @@ -1,13 +1,11 @@ /*###ICF### Section handled by ICF editor, don't touch! ****/ /*-Editor annotation file-*/ /* IcfEditorFile="$TOOLKIT_DIR$\config\ide\IcfEditor\cortex_v1_0.xml" */ -if (!isdefinedsymbol(MBED_APP_START)) { define symbol MBED_APP_START = 0x00000000; } -if (!isdefinedsymbol(MBED_APP_SIZE)) { define symbol MBED_APP_SIZE = 0x00080000; } /*-Specials-*/ -define symbol __ICFEDIT_intvec_start__ = MBED_APP_START; +define symbol __ICFEDIT_intvec_start__ = 0x00000000; /*-Memory Regions-*/ -define symbol __ICFEDIT_region_ROM_start__ = MBED_APP_START; -define symbol __ICFEDIT_region_ROM_end__ = MBED_APP_START + MBED_APP_SIZE - 1; +define symbol __ICFEDIT_region_ROM_start__ = 0x00000000; +define symbol __ICFEDIT_region_ROM_end__ = 0x00080000; define symbol __ICFEDIT_region_IRAM_start__ = 0x20000000; define symbol __ICFEDIT_region_IRAM_end__ = 0x20010000; define symbol __ICFEDIT_region_XRAM_start__ = 0x60000000; diff --git a/targets/TARGET_NUVOTON/TARGET_NUC472/device/TOOLCHAIN_IAR/TARGET_NU_XRAM_UNSUPPORTED/NUC472_442.icf b/targets/TARGET_NUVOTON/TARGET_NUC472/device/TOOLCHAIN_IAR/TARGET_NU_XRAM_UNSUPPORTED/NUC472_442.icf index 9d271180158..e62e9579082 100644 --- a/targets/TARGET_NUVOTON/TARGET_NUC472/device/TOOLCHAIN_IAR/TARGET_NU_XRAM_UNSUPPORTED/NUC472_442.icf +++ b/targets/TARGET_NUVOTON/TARGET_NUC472/device/TOOLCHAIN_IAR/TARGET_NU_XRAM_UNSUPPORTED/NUC472_442.icf @@ -1,13 +1,11 @@ /*###ICF### Section handled by ICF editor, don't touch! ****/ /*-Editor annotation file-*/ /* IcfEditorFile="$TOOLKIT_DIR$\config\ide\IcfEditor\cortex_v1_0.xml" */ -if (!isdefinedsymbol(MBED_APP_START)) { define symbol MBED_APP_START = 0x00000000; } -if (!isdefinedsymbol(MBED_APP_SIZE)) { define symbol MBED_APP_SIZE = 0x00080000; } /*-Specials-*/ -define symbol __ICFEDIT_intvec_start__ = MBED_APP_START; +define symbol __ICFEDIT_intvec_start__ = 0x00000000; /*-Memory Regions-*/ -define symbol __ICFEDIT_region_ROM_start__ = MBED_APP_START; -define symbol __ICFEDIT_region_ROM_end__ = MBED_APP_START + MBED_APP_SIZE - 1; +define symbol __ICFEDIT_region_ROM_start__ = 0x00000000; +define symbol __ICFEDIT_region_ROM_end__ = 0x00080000; define symbol __ICFEDIT_region_IRAM_start__ = 0x20000000; define symbol __ICFEDIT_region_IRAM_end__ = 0x20010000; /*-Sizes-*/ diff --git a/targets/TARGET_NUVOTON/TARGET_NUC472/device/cmsis_nvic.h b/targets/TARGET_NUVOTON/TARGET_NUC472/device/cmsis_nvic.h index e5e797a87a3..cc87b4a4acf 100644 --- a/targets/TARGET_NUVOTON/TARGET_NUC472/device/cmsis_nvic.h +++ b/targets/TARGET_NUVOTON/TARGET_NUC472/device/cmsis_nvic.h @@ -32,18 +32,8 @@ # define NVIC_RAM_VECTOR_ADDRESS ((uint32_t) &__start_vector_table__) #endif -#if defined(__CC_ARM) - extern uint32_t Load$$LR$$LR_IROM1$$Base[]; - #define NVIC_FLASH_VECTOR_ADDRESS ((uint32_t)Load$$LR$$LR_IROM1$$Base) -#elif defined(__ICCARM__) - #pragma section=".intvec" - #define NVIC_FLASH_VECTOR_ADDRESS ((uint32_t)__section_begin(".intvec")) -#elif defined(__GNUC__) - extern uint32_t __vector_table; - #define NVIC_FLASH_VECTOR_ADDRESS ((uint32_t)&__vector_table) -#else - #error "Flash vector address not set for this toolchain" -#endif + +#define NVIC_FLASH_VECTOR_ADDRESS 0 #ifdef __cplusplus extern "C" { diff --git a/targets/TARGET_NUVOTON/TARGET_NUC472/dma_api.c b/targets/TARGET_NUVOTON/TARGET_NUC472/dma_api.c index 257fe019ae5..1b789090f3c 100644 --- a/targets/TARGET_NUVOTON/TARGET_NUC472/dma_api.c +++ b/targets/TARGET_NUVOTON/TARGET_NUC472/dma_api.c @@ -23,10 +23,6 @@ #include "nu_bitutil.h" #include "dma.h" -#define NU_PDMA_CH_MAX PDMA_CH_MAX /* Specify maximum channels of PDMA */ -#define NU_PDMA_CH_Pos 0 /* Specify first channel number of PDMA */ -#define NU_PDMA_CH_Msk (((1 << NU_PDMA_CH_MAX) - 1) << NU_PDMA_CH_Pos) - struct nu_dma_chn_s { void (*handler)(uint32_t, uint32_t); uint32_t id; @@ -35,7 +31,7 @@ struct nu_dma_chn_s { static int dma_inited = 0; static uint32_t dma_chn_mask = 0; -static struct nu_dma_chn_s dma_chn_arr[NU_PDMA_CH_MAX]; +static struct nu_dma_chn_s dma_chn_arr[PDMA_CH_MAX]; static void pdma_vec(void); static const struct nu_modinit_s dma_modinit = {DMA_0, PDMA_MODULE, 0, 0, PDMA_RST, PDMA_IRQn, (void *) pdma_vec}; @@ -48,7 +44,7 @@ void dma_init(void) } dma_inited = 1; - dma_chn_mask = ~NU_PDMA_CH_Msk; + dma_chn_mask = 0; memset(dma_chn_arr, 0x00, sizeof (dma_chn_arr)); // Reset this module @@ -69,12 +65,25 @@ int dma_channel_allocate(uint32_t capabilities) dma_init(); } +#if 1 int i = nu_cto(dma_chn_mask); if (i != 32) { dma_chn_mask |= 1 << i; - memset(dma_chn_arr + i - NU_PDMA_CH_Pos, 0x00, sizeof (struct nu_dma_chn_s)); + memset(dma_chn_arr + i, 0x00, sizeof (struct nu_dma_chn_s)); return i; } +#else + int i; + + for (i = 0; i < PDMA_CH_MAX; i ++) { + if ((dma_chn_mask & (1 << i)) == 0) { + // Channel available + dma_chn_mask |= 1 << i; + memset(dma_chn_arr + i, 0x00, sizeof (struct nu_dma_chn_s)); + return i; + } + } +#endif // No channel available return DMA_ERROR_OUT_OF_CHANNELS; @@ -93,9 +102,9 @@ void dma_set_handler(int channelid, uint32_t handler, uint32_t id, uint32_t even { MBED_ASSERT(dma_chn_mask & (1 << channelid)); - dma_chn_arr[channelid - NU_PDMA_CH_Pos].handler = (void (*)(uint32_t, uint32_t)) handler; - dma_chn_arr[channelid - NU_PDMA_CH_Pos].id = id; - dma_chn_arr[channelid - NU_PDMA_CH_Pos].event = event; + dma_chn_arr[channelid].handler = (void (*)(uint32_t, uint32_t)) handler; + dma_chn_arr[channelid].id = id; + dma_chn_arr[channelid].event = event; // Set interrupt vector if someone has removed it. NVIC_SetVector(dma_modinit.irq_n, (uint32_t) dma_modinit.var); @@ -118,14 +127,14 @@ static void pdma_vec(void) PDMA_CLR_ABORT_FLAG(abtsts); while (abtsts) { - int chn_id = nu_ctz(abtsts) - PDMA_ABTSTS_ABTIF_Pos + NU_PDMA_CH_Pos; + int chn_id = nu_ctz(abtsts); if (dma_chn_mask & (1 << chn_id)) { - struct nu_dma_chn_s *dma_chn = dma_chn_arr + chn_id - NU_PDMA_CH_Pos; + struct nu_dma_chn_s *dma_chn = dma_chn_arr + chn_id; if (dma_chn->handler && (dma_chn->event & DMA_EVENT_ABORT)) { dma_chn->handler(dma_chn->id, DMA_EVENT_ABORT); } } - abtsts &= ~(1 << (chn_id - NU_PDMA_CH_Pos + PDMA_ABTSTS_ABTIF_Pos)); + abtsts &= ~(1 << chn_id); } } @@ -136,14 +145,14 @@ static void pdma_vec(void) PDMA_CLR_TD_FLAG(tdsts); while (tdsts) { - int chn_id = nu_ctz(tdsts) - PDMA_TDSTS_TDIF_Pos + NU_PDMA_CH_Pos; + int chn_id = nu_ctz(tdsts); if (dma_chn_mask & (1 << chn_id)) { - struct nu_dma_chn_s *dma_chn = dma_chn_arr + chn_id - NU_PDMA_CH_Pos; + struct nu_dma_chn_s *dma_chn = dma_chn_arr + chn_id; if (dma_chn->handler && (dma_chn->event & DMA_EVENT_TRANSFER_DONE)) { dma_chn->handler(dma_chn->id, DMA_EVENT_TRANSFER_DONE); } } - tdsts &= ~(1 << (chn_id - NU_PDMA_CH_Pos + PDMA_TDSTS_TDIF_Pos)); + tdsts &= ~(1 << chn_id); } } @@ -161,14 +170,14 @@ static void pdma_vec(void) PDMA->INTSTS = reqto; while (reqto) { - int chn_id = nu_ctz(reqto) - PDMA_INTSTS_REQTOFX_Pos + NU_PDMA_CH_Pos; + int chn_id = nu_ctz(reqto) - PDMA_INTSTS_REQTOFX_Pos; if (dma_chn_mask & (1 << chn_id)) { - struct nu_dma_chn_s *dma_chn = dma_chn_arr + chn_id - NU_PDMA_CH_Pos; + struct nu_dma_chn_s *dma_chn = dma_chn_arr + chn_id; if (dma_chn->handler && (dma_chn->event & DMA_EVENT_TIMEOUT)) { dma_chn->handler(dma_chn->id, DMA_EVENT_TIMEOUT); } } - reqto &= ~(1 << (chn_id - NU_PDMA_CH_Pos + PDMA_INTSTS_REQTOFX_Pos)); + reqto &= ~(1 << (chn_id + PDMA_INTSTS_REQTOFX_Pos)); } } } diff --git a/targets/TARGET_NUVOTON/TARGET_NUC472/flash_api.c b/targets/TARGET_NUVOTON/TARGET_NUC472/flash_api.c deleted file mode 100644 index 0d3a74ffbb2..00000000000 --- a/targets/TARGET_NUVOTON/TARGET_NUC472/flash_api.c +++ /dev/null @@ -1,81 +0,0 @@ -/* mbed Microcontroller Library - * Copyright (c) 2015-2016 Nuvoton - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * 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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * 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. - */ - -#include "flash_api.h" -#include "flash_data.h" -#include "mbed_critical.h" - -// This is a flash algo binary blob. It is PIC (position independent code) that should be stored in RAM -// NOTE: On ARMv7-M/ARMv8-M, instruction fetches are always little-endian. -static uint32_t FLASH_ALGO[] = { - 0x4603b530, 0x2164460c, 0x4de72059, 0x20166028, 0xf8c5070d, 0x20880100, 0x0100f8c5, 0xf8d006c0, - 0xf0000100, 0xb9080001, 0xbd302001, 0x680048df, 0x0004f040, 0x4580f04f, 0x0200f8c5, 0xf8d04628, - 0xf0400204, 0xf8c50004, 0xbf000204, 0xf1a11e08, 0xd1fb0101, 0x680048d6, 0x0029f040, 0x60284dd4, - 0x68004628, 0x0001f000, 0x2001b908, 0xf04fe7dd, 0x4dcf30ff, 0x46286468, 0x1c406c40, 0x2001b108, - 0x48cbe7d3, 0xf0406800, 0x4dc90040, 0x20006028, 0x4601e7cb, 0x48c6bf00, 0xf0006900, 0x28000001, - 0x48c3d1f9, 0xf0206800, 0x4ac10029, 0x20006010, 0x60104abd, 0x46014770, 0x48bdbf00, 0xf0006900, - 0x28000001, 0x48bad1f9, 0xf0406800, 0x4ab80040, 0x20226010, 0xf02160d0, 0x60500003, 0x61102001, - 0x8f60f3bf, 0x48b2bf00, 0xf0006900, 0x28000001, 0x48afd1f9, 0xf0006800, 0xb1380040, 0x680048ac, - 0x0040f040, 0x60104aaa, 0x47702001, 0xe7fc2000, 0x4603b570, 0x2500460c, 0x4629e009, 0xf8531c6d, - 0xf7ff0021, 0x1e06ffc8, 0x4630d001, 0x42a5bd70, 0x2000d3f3, 0xb570e7fa, 0x460b4604, 0x22004615, - 0xf1034629, 0xf020000f, 0xbf00030f, 0x69004898, 0x0001f000, 0xd1f92800, 0x68004895, 0x0040f040, - 0x60304e93, 0x000ff024, 0x20276070, 0x461060f0, 0xf8511c52, 0x4e8e0020, 0x60303680, 0x1c524610, - 0x0020f851, 0xf8c64e8a, 0x46100084, 0xf8511c52, 0x4e870020, 0x60303688, 0x1c524610, 0x0020f851, - 0x60301d36, 0x4e822001, 0x3b106130, 0xbf00e02c, 0x30c0487f, 0xf0006800, 0x28000030, 0x4610d1f8, - 0xf8511c52, 0x4e7a0020, 0x60303680, 0x1c524610, 0x0020f851, 0xf8c64e76, 0xbf000084, 0x30c04874, - 0xf0006800, 0x280000c0, 0x4610d1f8, 0xf8511c52, 0x4e6f0020, 0x60303688, 0x1c524610, 0x0020f851, - 0xf8c64e6b, 0x3b10008c, 0xd1d02b00, 0x4868bf00, 0xf0006900, 0x28000001, 0xbd70d1f9, 0x4603b510, - 0xf0201cc8, 0xbf000103, 0x69004861, 0x0001f000, 0xd1f92800, 0x6800485e, 0x0040f040, 0x60204c5c, - 0x60e02021, 0xf023e020, 0x4c590003, 0x68106060, 0x200160a0, 0xf3bf6120, 0xbf008f60, 0x69004854, - 0x0001f000, 0xd1f92800, 0x68004851, 0x0040f000, 0x484fb138, 0xf0406800, 0x4c4d0040, 0x20016020, - 0x1d1bbd10, 0x1f091d12, 0xd1dc2900, 0xe7f72000, 0x47f0e92d, 0x460c4605, 0xf04f4616, 0x46c20800, - 0x4843bf00, 0xf0006900, 0x28000001, 0x4840d1f9, 0xf0406800, 0x493e0040, 0x1ce06008, 0x0403f020, - 0xf3c5e02f, 0xb9600008, 0x7f00f5b4, 0xf44fd309, 0xeb067700, 0x46390208, 0xf7ff4628, 0x4682ff2c, - 0xf3c5e016, 0xb9580008, 0xd3092c10, 0x070ff024, 0x0208eb06, 0x46284639, 0xff1df7ff, 0xe0074682, - 0xeb064627, 0x46390208, 0xf7ff4628, 0x4682ff87, 0x44b8443d, 0xf1ba1be4, 0xd0020f00, 0xe8bd2001, - 0x2c0087f0, 0x2000d1cd, 0xb510e7f9, 0xf0231ccb, 0xbf000103, 0x691b4b1e, 0x0301f003, 0xd1f92b00, - 0x681b4b1b, 0x0340f043, 0x60234c19, 0x60e32300, 0xf020e025, 0x4c160303, 0x23006063, 0x230160a3, - 0xf3bf6123, 0xbf008f60, 0x691b4b11, 0x0301f003, 0xd1f92b00, 0x681b4b0e, 0x0340f003, 0x4b0cb133, - 0xf043681b, 0x4c0a0340, 0xbd106023, 0x689b4b08, 0x42a36814, 0xe7f8d000, 0x1d121d00, 0x29001f09, - 0xbf00d1d7, 0x0000e7f1, 0x40000100, 0x40000200, 0x4000c000, 0x00000000, -}; - -static const flash_algo_t flash_algo_config = { - .init = 0x00000001, - .uninit = 0x00000093, - .erase_sector = 0x000000b7, - .program_page = 0x00000291, - .static_base = 0x000003b4, - .algo_blob = FLASH_ALGO -}; - -static const sector_info_t sectors_info[] = { - {0x0, 0x800}, // (start, sector size) -}; - -static const flash_target_config_t flash_target_config = { - .page_size = 0x800, // 2 KB - .flash_start = 0x0, - .flash_size = 0x80000, // 512 KB - .sectors = sectors_info, - .sector_info_count = sizeof(sectors_info) / sizeof(sector_info_t) -}; - -void flash_set_target_config(flash_t *obj) -{ - obj->flash_algo = &flash_algo_config; - obj->target_config = &flash_target_config; -} diff --git a/targets/TARGET_NUVOTON/TARGET_NUC472/pwmout_api.c b/targets/TARGET_NUVOTON/TARGET_NUC472/pwmout_api.c index 90165697c63..2ca1cd49cd3 100644 --- a/targets/TARGET_NUVOTON/TARGET_NUC472/pwmout_api.c +++ b/targets/TARGET_NUVOTON/TARGET_NUC472/pwmout_api.c @@ -105,9 +105,11 @@ void pwmout_init(pwmout_t* obj, PinName pin) ((struct nu_pwm_var *) modinit->var)->en_msk |= 1 << chn; - // Mark this module to be inited. - int i = modinit - pwm_modinit_tab; - pwm_modinit_mask |= 1 << i; + if (((struct nu_pwm_var *) modinit->var)->en_msk) { + // Mark this module to be inited. + int i = modinit - pwm_modinit_tab; + pwm_modinit_mask |= 1 << i; + } } void pwmout_free(pwmout_t* obj) @@ -143,9 +145,11 @@ void pwmout_free(pwmout_t* obj) } } - // Mark this module to be deinited. - int i = modinit - pwm_modinit_tab; - pwm_modinit_mask &= ~(1 << i); + if (((struct nu_pwm_var *) modinit->var)->en_msk == 0) { + // Mark this module to be deinited. + int i = modinit - pwm_modinit_tab; + pwm_modinit_mask &= ~(1 << i); + } } void pwmout_write(pwmout_t* obj, float value) diff --git a/targets/TARGET_NUVOTON/TARGET_NUC472/serial_api.c b/targets/TARGET_NUVOTON/TARGET_NUC472/serial_api.c index a67684d8d4e..13bae2a9665 100644 --- a/targets/TARGET_NUVOTON/TARGET_NUC472/serial_api.c +++ b/targets/TARGET_NUVOTON/TARGET_NUC472/serial_api.c @@ -24,7 +24,6 @@ #include "PeripheralPins.h" #include "nu_modutil.h" #include "nu_bitutil.h" -#include #if DEVICE_SERIAL_ASYNCH #include "dma_api.h" @@ -66,8 +65,6 @@ static void uart_dma_handler_rx(uint32_t id, uint32_t event); static void serial_tx_enable_interrupt(serial_t *obj, uint32_t address, uint8_t enable); static void serial_rx_enable_interrupt(serial_t *obj, uint32_t address, uint8_t enable); -static void serial_enable_interrupt(serial_t *obj, SerialIrq irq, uint32_t enable); -static void serial_rollback_interrupt(serial_t *obj, SerialIrq irq); static int serial_write_async(serial_t *obj); static int serial_read_async(serial_t *obj); @@ -192,7 +189,7 @@ void serial_init(serial_t *obj, PinName tx, PinName rx) const struct nu_modinit_s *modinit = get_modinit(obj->serial.uart, uart_modinit_tab); MBED_ASSERT(modinit != NULL); - MBED_ASSERT(modinit->modname == (int) obj->serial.uart); + MBED_ASSERT(modinit->modname == obj->serial.uart); struct nu_uart_var *var = (struct nu_uart_var *) modinit->var; @@ -219,7 +216,6 @@ void serial_init(serial_t *obj, PinName tx, PinName rx) serial_format(obj, 8, ParityNone, 1); obj->serial.vec = var->vec; - obj->serial.irq_en = 0; #if DEVICE_SERIAL_ASYNCH obj->serial.dma_usage_tx = DMA_USAGE_NEVER; @@ -246,7 +242,7 @@ void serial_free(serial_t *obj) { const struct nu_modinit_s *modinit = get_modinit(obj->serial.uart, uart_modinit_tab); MBED_ASSERT(modinit != NULL); - MBED_ASSERT(modinit->modname == (int) obj->serial.uart); + MBED_ASSERT(modinit->modname == obj->serial.uart); struct nu_uart_var *var = (struct nu_uart_var *) modinit->var; @@ -365,7 +361,7 @@ void serial_irq_handler(serial_t *obj, uart_irq_handler handler, uint32_t id) const struct nu_modinit_s *modinit = get_modinit(obj->serial.uart, uart_modinit_tab); MBED_ASSERT(modinit != NULL); - MBED_ASSERT(modinit->modname == (int) obj->serial.uart); + MBED_ASSERT(modinit->modname == obj->serial.uart); obj->serial.irq_handler = (uint32_t) handler; obj->serial.irq_id = id; @@ -376,18 +372,51 @@ void serial_irq_handler(serial_t *obj, uart_irq_handler handler, uint32_t id) void serial_irq_set(serial_t *obj, SerialIrq irq, uint32_t enable) { - obj->serial.irq_en = enable; - serial_enable_interrupt(obj, irq, enable); + if (enable) { + const struct nu_modinit_s *modinit = get_modinit(obj->serial.uart, uart_modinit_tab); + MBED_ASSERT(modinit != NULL); + MBED_ASSERT(modinit->modname == obj->serial.uart); + + NVIC_SetVector(modinit->irq_n, (uint32_t) obj->serial.vec); + NVIC_EnableIRQ(modinit->irq_n); + + struct nu_uart_var *var = (struct nu_uart_var *) modinit->var; + // Multiple serial S/W objects for single UART H/W module possibly. + // Bind serial S/W object to UART H/W module as interrupt is enabled. + var->obj = obj; + + switch (irq) { + // NOTE: Setting inten_msk first to avoid race condition + case RxIrq: + obj->serial.inten_msk = obj->serial.inten_msk | (UART_INTEN_RDAIEN_Msk | UART_INTEN_RXTOIEN_Msk); + UART_ENABLE_INT(((UART_T *) NU_MODBASE(obj->serial.uart)), (UART_INTEN_RDAIEN_Msk | UART_INTEN_RXTOIEN_Msk)); + break; + case TxIrq: + obj->serial.inten_msk = obj->serial.inten_msk | UART_INTEN_THREIEN_Msk; + UART_ENABLE_INT(((UART_T *) NU_MODBASE(obj->serial.uart)), UART_INTEN_THREIEN_Msk); + break; + } + } else { // disable + switch (irq) { + case RxIrq: + UART_DISABLE_INT(((UART_T *) NU_MODBASE(obj->serial.uart)), (UART_INTEN_RDAIEN_Msk | UART_INTEN_RXTOIEN_Msk)); + obj->serial.inten_msk = obj->serial.inten_msk & ~(UART_INTEN_RDAIEN_Msk | UART_INTEN_RXTOIEN_Msk); + break; + case TxIrq: + UART_DISABLE_INT(((UART_T *) NU_MODBASE(obj->serial.uart)), UART_INTEN_THREIEN_Msk); + obj->serial.inten_msk = obj->serial.inten_msk & ~UART_INTEN_THREIEN_Msk; + break; + } + } } int serial_getc(serial_t *obj) { - // NOTE: Every byte access requires accompaniment of one interrupt. This has side effect of performance degradation. + // TODO: Fix every byte access requires accompaniness of one interrupt. This degrades performance much. while (! serial_readable(obj)); int c = UART_READ(((UART_T *) NU_MODBASE(obj->serial.uart))); - // NOTE: On Nuvoton targets, no H/W IRQ to match TxIrq/RxIrq. - // Simulation of TxIrq/RxIrq requires the call to Serial::putc()/Serial::getc() respectively. + // Simulate clear of the interrupt flag if (obj->serial.inten_msk & (UART_INTEN_RDAIEN_Msk | UART_INTEN_RXTOIEN_Msk)) { UART_ENABLE_INT(((UART_T *) NU_MODBASE(obj->serial.uart)), (UART_INTEN_RDAIEN_Msk | UART_INTEN_RXTOIEN_Msk)); } @@ -397,12 +426,11 @@ int serial_getc(serial_t *obj) void serial_putc(serial_t *obj, int c) { - // NOTE: Every byte access requires accompaniment of one interrupt. This has side effect of performance degradation. + // TODO: Fix every byte access requires accompaniness of one interrupt. This degrades performance much. while (! serial_writable(obj)); UART_WRITE(((UART_T *) NU_MODBASE(obj->serial.uart)), c); - // NOTE: On Nuvoton targets, no H/W IRQ to match TxIrq/RxIrq. - // Simulation of TxIrq/RxIrq requires the call to Serial::putc()/Serial::getc() respectively. + // Simulate clear of the interrupt flag if (obj->serial.inten_msk & UART_INTEN_THREIEN_Msk) { UART_ENABLE_INT(((UART_T *) NU_MODBASE(obj->serial.uart)), UART_INTEN_THREIEN_Msk); } @@ -514,7 +542,7 @@ int serial_tx_asynch(serial_t *obj, const void *tx, size_t tx_length, uint8_t tx // DMA way const struct nu_modinit_s *modinit = get_modinit(obj->serial.uart, uart_modinit_tab); MBED_ASSERT(modinit != NULL); - MBED_ASSERT(modinit->modname == (int) obj->serial.uart); + MBED_ASSERT(modinit->modname == obj->serial.uart); PDMA_T *pdma_base = dma_modbase(); @@ -575,7 +603,7 @@ void serial_rx_asynch(serial_t *obj, void *rx, size_t rx_length, uint8_t rx_widt // DMA way const struct nu_modinit_s *modinit = get_modinit(obj->serial.uart, uart_modinit_tab); MBED_ASSERT(modinit != NULL); - MBED_ASSERT(modinit->modname == (int) obj->serial.uart); + MBED_ASSERT(modinit->modname == obj->serial.uart); PDMA_T *pdma_base = dma_modbase(); @@ -622,8 +650,10 @@ void serial_tx_abort_asynch(serial_t *obj) } // Necessary for both interrupt way and DMA way - serial_enable_interrupt(obj, TxIrq, 0); - serial_rollback_interrupt(obj, TxIrq); + serial_irq_set(obj, TxIrq, 0); + // FIXME: more complete abort operation + //UART_HAL_DisableTransmitter(obj->serial.serial.address); + //UART_HAL_FlushTxFifo(obj->serial.serial.address); } void serial_rx_abort_asynch(serial_t *obj) @@ -641,30 +671,20 @@ void serial_rx_abort_asynch(serial_t *obj) } // Necessary for both interrupt way and DMA way - serial_enable_interrupt(obj, RxIrq, 0); - serial_rollback_interrupt(obj, RxIrq); + serial_irq_set(obj, RxIrq, 0); + // FIXME: more complete abort operation + //UART_HAL_DisableReceiver(obj->serial.serial.address); + //UART_HAL_FlushRxFifo(obj->serial.serial.address); } uint8_t serial_tx_active(serial_t *obj) { - // NOTE: Judge by serial_is_irq_en(obj, TxIrq) doesn't work with sync/async modes interleaved. Change with TX FIFO empty flag. - const struct nu_modinit_s *modinit = get_modinit(obj->serial.uart, uart_modinit_tab); - MBED_ASSERT(modinit != NULL); - MBED_ASSERT(modinit->modname == (int) obj->serial.uart); - - struct nu_uart_var *var = (struct nu_uart_var *) modinit->var; - return (obj->serial.vec == var->vec_async); + return serial_is_irq_en(obj, TxIrq); } uint8_t serial_rx_active(serial_t *obj) { - // NOTE: Judge by serial_is_irq_en(obj, RxIrq) doesn't work with sync/async modes interleaved. Change with RX FIFO empty flag. - const struct nu_modinit_s *modinit = get_modinit(obj->serial.uart, uart_modinit_tab); - MBED_ASSERT(modinit != NULL); - MBED_ASSERT(modinit->modname == (int) obj->serial.uart); - - struct nu_uart_var *var = (struct nu_uart_var *) modinit->var; - return (obj->serial.vec == var->vec_async); + return serial_is_irq_en(obj, RxIrq); } int serial_irq_handler_asynch(serial_t *obj) @@ -914,7 +934,7 @@ static int serial_write_async(serial_t *obj) { const struct nu_modinit_s *modinit = get_modinit(obj->serial.uart, uart_modinit_tab); MBED_ASSERT(modinit != NULL); - MBED_ASSERT(modinit->modname == (int) obj->serial.uart); + MBED_ASSERT(modinit->modname == obj->serial.uart); UART_T *uart_base = (UART_T *) NU_MODBASE(obj->serial.uart); @@ -966,7 +986,7 @@ static int serial_read_async(serial_t *obj) { const struct nu_modinit_s *modinit = get_modinit(obj->serial.uart, uart_modinit_tab); MBED_ASSERT(modinit != NULL); - MBED_ASSERT(modinit->modname == (int) obj->serial.uart); + MBED_ASSERT(modinit->modname == obj->serial.uart); uint32_t rx_fifo_busy = (((UART_T *) NU_MODBASE(obj->serial.uart))->FIFOSTS & UART_FIFOSTS_RXPTR_Msk) >> UART_FIFOSTS_RXPTR_Pos; //uint32_t rx_fifo_free = ((struct nu_uart_var *) modinit->var)->fifo_size_rx - rx_fifo_busy; @@ -1041,81 +1061,28 @@ static void serial_tx_enable_interrupt(serial_t *obj, uint32_t handler, uint8_t { const struct nu_modinit_s *modinit = get_modinit(obj->serial.uart, uart_modinit_tab); MBED_ASSERT(modinit != NULL); - MBED_ASSERT(modinit->modname == (int) obj->serial.uart); + MBED_ASSERT(modinit->modname == obj->serial.uart); // Necessary for both interrupt way and DMA way struct nu_uart_var *var = (struct nu_uart_var *) modinit->var; // With our own async vector, tx/rx handlers can be different. obj->serial.vec = var->vec_async; obj->serial.irq_handler_tx_async = (void (*)(void)) handler; - serial_enable_interrupt(obj, TxIrq, enable); + serial_irq_set(obj, TxIrq, enable); } static void serial_rx_enable_interrupt(serial_t *obj, uint32_t handler, uint8_t enable) { const struct nu_modinit_s *modinit = get_modinit(obj->serial.uart, uart_modinit_tab); MBED_ASSERT(modinit != NULL); - MBED_ASSERT(modinit->modname == (int) obj->serial.uart); + MBED_ASSERT(modinit->modname == obj->serial.uart); // Necessary for both interrupt way and DMA way struct nu_uart_var *var = (struct nu_uart_var *) modinit->var; // With our own async vector, tx/rx handlers can be different. obj->serial.vec = var->vec_async; obj->serial.irq_handler_rx_async = (void (*) (void)) handler; - serial_enable_interrupt(obj, RxIrq, enable); -} - -static void serial_enable_interrupt(serial_t *obj, SerialIrq irq, uint32_t enable) -{ - if (enable) { - const struct nu_modinit_s *modinit = get_modinit(obj->serial.uart, uart_modinit_tab); - MBED_ASSERT(modinit != NULL); - MBED_ASSERT(modinit->modname == (int) obj->serial.uart); - - NVIC_SetVector(modinit->irq_n, (uint32_t) obj->serial.vec); - NVIC_EnableIRQ(modinit->irq_n); - - struct nu_uart_var *var = (struct nu_uart_var *) modinit->var; - // Multiple serial S/W objects for single UART H/W module possibly. - // Bind serial S/W object to UART H/W module as interrupt is enabled. - var->obj = obj; - - switch (irq) { - // NOTE: Setting inten_msk first to avoid race condition - case RxIrq: - obj->serial.inten_msk = obj->serial.inten_msk | (UART_INTEN_RDAIEN_Msk | UART_INTEN_RXTOIEN_Msk); - UART_ENABLE_INT(((UART_T *) NU_MODBASE(obj->serial.uart)), (UART_INTEN_RDAIEN_Msk | UART_INTEN_RXTOIEN_Msk)); - break; - case TxIrq: - obj->serial.inten_msk = obj->serial.inten_msk | UART_INTEN_THREIEN_Msk; - UART_ENABLE_INT(((UART_T *) NU_MODBASE(obj->serial.uart)), UART_INTEN_THREIEN_Msk); - break; - } - } - else { // disable - switch (irq) { - case RxIrq: - UART_DISABLE_INT(((UART_T *) NU_MODBASE(obj->serial.uart)), (UART_INTEN_RDAIEN_Msk | UART_INTEN_RXTOIEN_Msk)); - obj->serial.inten_msk = obj->serial.inten_msk & ~(UART_INTEN_RDAIEN_Msk | UART_INTEN_RXTOIEN_Msk); - break; - case TxIrq: - UART_DISABLE_INT(((UART_T *) NU_MODBASE(obj->serial.uart)), UART_INTEN_THREIEN_Msk); - obj->serial.inten_msk = obj->serial.inten_msk & ~UART_INTEN_THREIEN_Msk; - break; - } - } -} - -static void serial_rollback_interrupt(serial_t *obj, SerialIrq irq) -{ - const struct nu_modinit_s *modinit = get_modinit(obj->serial.uart, uart_modinit_tab); - MBED_ASSERT(modinit != NULL); - MBED_ASSERT(modinit->modname == (int) obj->serial.uart); - - struct nu_uart_var *var = (struct nu_uart_var *) modinit->var; - - obj->serial.vec = var->vec; - serial_enable_interrupt(obj, irq, obj->serial.irq_en); + serial_irq_set(obj, RxIrq, enable); } static void serial_check_dma_usage(DMAUsage *dma_usage, int *dma_ch) diff --git a/targets/TARGET_NUVOTON/TARGET_NUC472/trng_api.c b/targets/TARGET_NUVOTON/TARGET_NUC472/trng_api.c index 6fab1b43063..29566c3ab3f 100644 --- a/targets/TARGET_NUVOTON/TARGET_NUC472/trng_api.c +++ b/targets/TARGET_NUVOTON/TARGET_NUC472/trng_api.c @@ -31,16 +31,12 @@ * Get Random number generator. */ static volatile int g_PRNG_done; -volatile int g_AES_done; void CRYPTO_IRQHandler() { if (PRNG_GET_INT_FLAG()) { g_PRNG_done = 1; PRNG_CLR_INT_FLAG(); - } else if (AES_GET_INT_FLAG()) { - g_AES_done = 1; - AES_CLR_INT_FLAG(); } } @@ -90,7 +86,7 @@ int trng_get_bytes(trng_t *obj, uint8_t *output, size_t length, size_t *output_l memcpy(output, &tmpBuff, length); *output_length = length; } else { - for (int i = 0; i < (length/32); i++) { + for (size_t i = 0; i < (length/32); i++) { trng_get(output); *output_length += 32; output += 32; diff --git a/targets/TARGET_NXP/TARGET_LPC11UXX/TARGET_LPC11U37H_401/PinNames.h b/targets/TARGET_NXP/TARGET_LPC11UXX/TARGET_LPC11U37H_401/PinNames.h index 56e1f557f4a..9a0e81a15b0 100644 --- a/targets/TARGET_NXP/TARGET_LPC11UXX/TARGET_LPC11U37H_401/PinNames.h +++ b/targets/TARGET_NXP/TARGET_LPC11UXX/TARGET_LPC11U37H_401/PinNames.h @@ -106,9 +106,6 @@ typedef enum { // BTN Names BTN1 = P0_16, BTN2 = P0_1, - // Standardized button names - BUTTON1 = BTN1, - BUTTON2 = BTN2, // UART UART_TX = P0_19, diff --git a/targets/TARGET_NXP/TARGET_LPC176X/TARGET_MBED_LPC1768/PinNames.h b/targets/TARGET_NXP/TARGET_LPC176X/TARGET_MBED_LPC1768/PinNames.h index 8ed4113f1f4..f0b060d8d9b 100644 --- a/targets/TARGET_NXP/TARGET_LPC176X/TARGET_MBED_LPC1768/PinNames.h +++ b/targets/TARGET_NXP/TARGET_LPC176X/TARGET_MBED_LPC1768/PinNames.h @@ -106,17 +106,11 @@ typedef enum { A4 = P1_30, A5 = P1_31, + I2C_SCL = D15, + I2C_SDA = D14, + // Not connected - NC = (int)0xFFFFFFFF, - - I2C_SCL0 = NC, - I2C_SDA0 = NC, - I2C_SCL1 = p10, - I2C_SDA1 = p9, - I2C_SCL2 = p27, // pin used by application board - I2C_SDA2 = p28, // pin used by application board - I2C_SCL = I2C_SCL2, - I2C_SDA = I2C_SDA2, + NC = (int)0xFFFFFFFF } PinName; typedef enum { diff --git a/targets/TARGET_NXP/TARGET_LPC176X/TARGET_XBED_LPC1768/PinNames.h b/targets/TARGET_NXP/TARGET_LPC176X/TARGET_XBED_LPC1768/PinNames.h index 50bdb1bb57e..00950a9b36e 100644 --- a/targets/TARGET_NXP/TARGET_LPC176X/TARGET_XBED_LPC1768/PinNames.h +++ b/targets/TARGET_NXP/TARGET_LPC176X/TARGET_XBED_LPC1768/PinNames.h @@ -79,8 +79,6 @@ typedef enum { //xbed lpc1768 Pin Names LED5 = P2_6, BTN1 = P2_8, - // Standardized button names - BUTTON1 = BTN1, SDA = P0_27, SCL = P0_28, ISP = P2_10, diff --git a/targets/TARGET_NXP/TARGET_LPC176X/device/TOOLCHAIN_ARM_MICRO/LPC1768.sct b/targets/TARGET_NXP/TARGET_LPC176X/device/TOOLCHAIN_ARM_MICRO/LPC1768.sct index 6af8037232f..56b9495f957 100644 --- a/targets/TARGET_NXP/TARGET_LPC176X/device/TOOLCHAIN_ARM_MICRO/LPC1768.sct +++ b/targets/TARGET_NXP/TARGET_LPC176X/device/TOOLCHAIN_ARM_MICRO/LPC1768.sct @@ -6,8 +6,8 @@ LR_IROM1 0x00000000 0x80000 { ; load region size_region .ANY (+RO) } ; 8_byte_aligned(49 vect * 4 bytes) = 8_byte_aligned(0xC4) = 0xC8 - ; 32KB (RAM size) - 0xC8 (NIVT) - 32 (topmost 32 bytes used by IAP functions) = 0x7F18 - RW_IRAM1 0x100000C8 0x7F18 { + ; 32KB - 0xC8 = 0x7F38 + RW_IRAM1 0x100000C8 0x7F38 { .ANY (+RW +ZI) } RW_IRAM2 0x2007C000 0x4000 { ; RW data, USB RAM diff --git a/targets/TARGET_NXP/TARGET_LPC176X/device/TOOLCHAIN_ARM_STD/LPC1768.sct b/targets/TARGET_NXP/TARGET_LPC176X/device/TOOLCHAIN_ARM_STD/LPC1768.sct index 2e5afcd5e1e..6fb28c5d301 100644 --- a/targets/TARGET_NXP/TARGET_LPC176X/device/TOOLCHAIN_ARM_STD/LPC1768.sct +++ b/targets/TARGET_NXP/TARGET_LPC176X/device/TOOLCHAIN_ARM_STD/LPC1768.sct @@ -6,8 +6,8 @@ LR_IROM1 0x00000000 0x80000 { ; load region size_region .ANY (+RO) } ; 8_byte_aligned(49 vect * 4 bytes) = 8_byte_aligned(0xC4) = 0xC8 - ; 32KB (RAM size) - 0xC8 (NIVT) - 32 (topmost 32 bytes used by IAP functions) = 0x7F18 - RW_IRAM1 0x100000C8 0x7F18 { + ; 32KB - 0xC8 = 0x7F38 + RW_IRAM1 0x100000C8 0x7F38 { .ANY (+RW +ZI) } RW_IRAM2 0x2007C000 0x4000 { ; RW data, ETH RAM diff --git a/targets/TARGET_NXP/TARGET_LPC176X/device/TOOLCHAIN_GCC_ARM/LPC1768.ld b/targets/TARGET_NXP/TARGET_LPC176X/device/TOOLCHAIN_GCC_ARM/LPC1768.ld index 8ab5bcaf22e..ae8c58fda86 100644 --- a/targets/TARGET_NXP/TARGET_LPC176X/device/TOOLCHAIN_GCC_ARM/LPC1768.ld +++ b/targets/TARGET_NXP/TARGET_LPC176X/device/TOOLCHAIN_GCC_ARM/LPC1768.ld @@ -4,7 +4,7 @@ MEMORY { FLASH (rx) : ORIGIN = 0x00000000, LENGTH = 512K - RAM (rwx) : ORIGIN = 0x100000C8, LENGTH = (32K - 0xC8 - 32) /* topmost 32 bytes used by IAP functions */ + RAM (rwx) : ORIGIN = 0x100000C8, LENGTH = (32K - 0xC8) USB_RAM(rwx) : ORIGIN = 0x2007C000, LENGTH = 16K ETH_RAM(rwx) : ORIGIN = 0x20080000, LENGTH = 16K diff --git a/targets/TARGET_NXP/TARGET_LPC176X/device/TOOLCHAIN_GCC_ARM/TARGET_XBED_LPC1768/XBED_LPC1768.ld b/targets/TARGET_NXP/TARGET_LPC176X/device/TOOLCHAIN_GCC_ARM/TARGET_XBED_LPC1768/XBED_LPC1768.ld index 247bc920252..115edf1369a 100644 --- a/targets/TARGET_NXP/TARGET_LPC176X/device/TOOLCHAIN_GCC_ARM/TARGET_XBED_LPC1768/XBED_LPC1768.ld +++ b/targets/TARGET_NXP/TARGET_LPC176X/device/TOOLCHAIN_GCC_ARM/TARGET_XBED_LPC1768/XBED_LPC1768.ld @@ -4,7 +4,7 @@ MEMORY { FLASH (rx) : ORIGIN = 0x00002000, LENGTH = 504K - RAM (rwx) : ORIGIN = 0x100000C8, LENGTH = (32K - 0xC8 - 32) /* topmost 32 bytes used by IAP functions */ + RAM (rwx) : ORIGIN = 0x100000C8, LENGTH = (32K - 0xC8) USB_RAM(rwx) : ORIGIN = 0x2007C000, LENGTH = 16K ETH_RAM(rwx) : ORIGIN = 0x20080000, LENGTH = 16K diff --git a/targets/TARGET_NXP/TARGET_LPC176X/device/TOOLCHAIN_GCC_CR/LPC1768.ld b/targets/TARGET_NXP/TARGET_LPC176X/device/TOOLCHAIN_GCC_CR/LPC1768.ld index f5f0d93ef1a..abbb2cdc9fa 100644 --- a/targets/TARGET_NXP/TARGET_LPC176X/device/TOOLCHAIN_GCC_CR/LPC1768.ld +++ b/targets/TARGET_NXP/TARGET_LPC176X/device/TOOLCHAIN_GCC_CR/LPC1768.ld @@ -7,7 +7,7 @@ MEMORY { /* Define each memory region */ MFlash512 (rx) : ORIGIN = 0x0, LENGTH = 0x80000 /* 512k */ - RamLoc32 (rwx) : ORIGIN = 0x100000C8, LENGTH = 0x7F18 /* 32k (topmost 32 bytes used by IAP functions) */ + RamLoc32 (rwx) : ORIGIN = 0x100000C8, LENGTH = 0x7F38 /* 32k */ RamAHB_USB (rwx) : ORIGIN = 0x2007c000, LENGTH = 0x4000 /* 16k */ RamAHB_Eth (rwx) : ORIGIN = 0x20080000, LENGTH = 0x4000 /* 16k */ diff --git a/targets/TARGET_NXP/TARGET_LPC176X/device/TOOLCHAIN_GCC_CS/LPC1768.ld b/targets/TARGET_NXP/TARGET_LPC176X/device/TOOLCHAIN_GCC_CS/LPC1768.ld index e16eb3caf99..e88d34de6c6 100644 --- a/targets/TARGET_NXP/TARGET_LPC176X/device/TOOLCHAIN_GCC_CS/LPC1768.ld +++ b/targets/TARGET_NXP/TARGET_LPC176X/device/TOOLCHAIN_GCC_CS/LPC1768.ld @@ -20,13 +20,13 @@ SEARCH_DIR(.) /* ram ORIGIN: 8_byte_aligned(49 vect * 4 bytes) = 8_byte_aligned(0xC4) = 0xC8 -ram LENGTH: 32KB (RAM size) - 0xC8 (NIVT) - 32 (topmost 32 bytes used by IAP functions) = 0x7F18 +ram LENGTH: 32KB - 0xC8 = 0x7F38 */ MEMORY { rom (rx) : ORIGIN = 0x00000000, LENGTH = 512K - ram (rwx) : ORIGIN = 0x100000C8, LENGTH = 0x7F18 + ram (rwx) : ORIGIN = 0x100000C8, LENGTH = 0x7F38 ram1(rwx) : ORIGIN = 0x2007C000, LENGTH = 16K ram2(rwx) : ORIGIN = 0x20080000, LENGTH = 16K diff --git a/targets/TARGET_NXP/TARGET_LPC176X/device/flash_api.c b/targets/TARGET_NXP/TARGET_LPC176X/device/flash_api.c deleted file mode 100644 index 0b140350bf5..00000000000 --- a/targets/TARGET_NXP/TARGET_LPC176X/device/flash_api.c +++ /dev/null @@ -1,67 +0,0 @@ -/* mbed Microcontroller Library - * Copyright (c) 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. - * You may obtain a copy of the License at - * - * 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, - * 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. - */ - -#include "flash_api.h" -#include "platform/mbed_critical.h" - -// This file is automatically generated - -#if DEVICE_FLASH - -#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 -}; - -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 -}; - -static const sector_info_t sectors_info[] = { - {0x0, 0x1000}, - {0x10000, 0x8000}, -}; - -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) -}; - -void flash_set_target_config(flash_t *obj) -{ - obj->flash_algo = &flash_algo_config; - obj->target_config = &flash_target_config; -} - -#endif diff --git a/targets/TARGET_NXP/TARGET_LPC23XX/PeripheralNames.h b/targets/TARGET_NXP/TARGET_LPC23XX/PeripheralNames.h new file mode 100644 index 00000000000..285837eedf2 --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC23XX/PeripheralNames.h @@ -0,0 +1,110 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * 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. + */ +#ifndef MBED_PERIPHERALNAMES_H +#define MBED_PERIPHERALNAMES_H + +#include "cmsis.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + UART_0 = (int)LPC_UART0_BASE, + UART_1 = (int)LPC_UART1_BASE, + UART_2 = (int)LPC_UART2_BASE, + UART_3 = (int)LPC_UART3_BASE +} UARTName; + +typedef enum { + ADC0_0 = 0, + ADC0_1, + ADC0_2, + ADC0_3, + ADC0_4, + ADC0_5, + ADC0_6, + ADC0_7 +} ADCName; + +typedef enum { + DAC_0 = 0 +} DACName; + +typedef enum { + SPI_0 = (int)LPC_SSP0_BASE, + SPI_1 = (int)LPC_SSP1_BASE +} SPIName; + +typedef enum { + I2C_0 = (int)LPC_I2C0_BASE, + I2C_1 = (int)LPC_I2C1_BASE, + I2C_2 = (int)LPC_I2C2_BASE +} I2CName; + +typedef enum { + PWM_1 = 1, + PWM_2, + PWM_3, + PWM_4, + PWM_5, + PWM_6 +} PWMName; + +typedef enum { + CAN_1 = (int)LPC_CAN1_BASE, + CAN_2 = (int)LPC_CAN2_BASE +} CANName; + +#define STDIO_UART_TX USBTX +#define STDIO_UART_RX USBRX +#define STDIO_UART UART_0 + +// Default peripherals +#define MBED_SPI0 p5, p6, p7, p8 +#define MBED_SPI1 p11, p12, p13, p14 + +#define MBED_UART0 p9, p10 +#define MBED_UART1 p13, p14 +#define MBED_UART2 p28, p27 +#define MBED_UARTUSB USBTX, USBRX + +#define MBED_I2C0 p28, p27 +#define MBED_I2C1 p9, p10 + +#define MBED_CAN0 p30, p29 + +#define MBED_ANALOGOUT0 p18 + +#define MBED_ANALOGIN0 p15 +#define MBED_ANALOGIN1 p16 +#define MBED_ANALOGIN2 p17 +#define MBED_ANALOGIN3 p18 +#define MBED_ANALOGIN4 p19 +#define MBED_ANALOGIN5 p20 + +#define MBED_PWMOUT0 p26 +#define MBED_PWMOUT1 p25 +#define MBED_PWMOUT2 p24 +#define MBED_PWMOUT3 p23 +#define MBED_PWMOUT4 p22 +#define MBED_PWMOUT5 p21 + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/targets/TARGET_NXP/TARGET_LPC23XX/PinNames.h b/targets/TARGET_NXP/TARGET_LPC23XX/PinNames.h new file mode 100644 index 00000000000..2b85b9ca27f --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC23XX/PinNames.h @@ -0,0 +1,104 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * 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. + */ + +#ifndef MBED_PINNAMES_H +#define MBED_PINNAMES_H + +#include "cmsis.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + PIN_INPUT, + PIN_OUTPUT +} PinDirection; + +#define PORT_SHIFT 5 + +typedef enum { + // LPC Pin Names + P0_0 = LPC_GPIO0_BASE, + P0_1, P0_2, P0_3, P0_4, P0_5, P0_6, P0_7, P0_8, P0_9, P0_10, P0_11, P0_12, P0_13, P0_14, P0_15, P0_16, P0_17, P0_18, P0_19, P0_20, P0_21, P0_22, P0_23, P0_24, P0_25, P0_26, P0_27, P0_28, P0_29, P0_30, P0_31, + P1_0, P1_1, P1_2, P1_3, P1_4, P1_5, P1_6, P1_7, P1_8, P1_9, P1_10, P1_11, P1_12, P1_13, P1_14, P1_15, P1_16, P1_17, P1_18, P1_19, P1_20, P1_21, P1_22, P1_23, P1_24, P1_25, P1_26, P1_27, P1_28, P1_29, P1_30, P1_31, + P2_0, P2_1, P2_2, P2_3, P2_4, P2_5, P2_6, P2_7, P2_8, P2_9, P2_10, P2_11, P2_12, P2_13, P2_14, P2_15, P2_16, P2_17, P2_18, P2_19, P2_20, P2_21, P2_22, P2_23, P2_24, P2_25, P2_26, P2_27, P2_28, P2_29, P2_30, P2_31, + P3_0, P3_1, P3_2, P3_3, P3_4, P3_5, P3_6, P3_7, P3_8, P3_9, P3_10, P3_11, P3_12, P3_13, P3_14, P3_15, P3_16, P3_17, P3_18, P3_19, P3_20, P3_21, P3_22, P3_23, P3_24, P3_25, P3_26, P3_27, P3_28, P3_29, P3_30, P3_31, + P4_0, P4_1, P4_2, P4_3, P4_4, P4_5, P4_6, P4_7, P4_8, P4_9, P4_10, P4_11, P4_12, P4_13, P4_14, P4_15, P4_16, P4_17, P4_18, P4_19, P4_20, P4_21, P4_22, P4_23, P4_24, P4_25, P4_26, P4_27, P4_28, P4_29, P4_30, P4_31, + + // mbed DIP Pin Names + p5 = P0_9, + p6 = P0_8, + p7 = P0_7, + p8 = P0_6, + p9 = P0_0, + p10 = P0_1, + p11 = P0_18, + p12 = P0_17, + p13 = P0_15, + p14 = P0_16, + p15 = P0_23, + p16 = P0_24, + p17 = P0_25, + p18 = P0_26, + p19 = P1_30, + p20 = P1_31, + p21 = P2_5, + p22 = P2_4, + p23 = P2_3, + p24 = P2_2, + p25 = P2_1, + p26 = P2_0, + p27 = P0_11, + p28 = P0_10, + p29 = P0_5, + p30 = P0_4, + + // Other mbed Pin Names + LED1 = P1_18, + LED2 = P1_20, + LED3 = P1_21, + LED4 = P1_23, + + USBTX = P0_2, + USBRX = P0_3, + + // Not connected + NC = (int)0xFFFFFFFF +} PinName; + +typedef enum { + PullUp = 0, + PullDown = 3, + PullNone = 2, + OpenDrain = 4, + PullDefault = PullDown +} PinMode; + +// version of PINCON_TypeDef using register arrays +typedef struct { + __IO uint32_t PINSEL[11]; + uint32_t RESERVED0[5]; + __IO uint32_t PINMODE[10]; +} PINCONARRAY_TypeDef; + +#define PINCONARRAY ((PINCONARRAY_TypeDef *)LPC_PINCON_BASE) + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/targets/TARGET_NXP/TARGET_LPC23XX/PortNames.h b/targets/TARGET_NXP/TARGET_LPC23XX/PortNames.h new file mode 100644 index 00000000000..270cdeecb0c --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC23XX/PortNames.h @@ -0,0 +1,34 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * 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. + */ +#ifndef MBED_PORTNAMES_H +#define MBED_PORTNAMES_H + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + Port0 = 0, + Port1 = 1, + Port2 = 2, + Port3 = 3, + Port4 = 4 +} PortName; + +#ifdef __cplusplus +} +#endif +#endif diff --git a/targets/TARGET_NXP/TARGET_LPC23XX/analogin_api.c b/targets/TARGET_NXP/TARGET_LPC23XX/analogin_api.c new file mode 100644 index 00000000000..4c3770e836b --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC23XX/analogin_api.c @@ -0,0 +1,123 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * 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. + */ +#include "mbed_assert.h" +#include "analogin_api.h" +#include "cmsis.h" +#include "pinmap.h" + +#define ANALOGIN_MEDIAN_FILTER 1 + +#define ADC_10BIT_RANGE 0x3FF +#define ADC_12BIT_RANGE 0xFFF + +static inline int div_round_up(int x, int y) { + return (x + (y - 1)) / y; +} + +static const PinMap PinMap_ADC[] = { + {P0_23, ADC0_0, 1}, + {P0_24, ADC0_1, 1}, + {P0_25, ADC0_2, 1}, + {P0_26, ADC0_3, 1}, + {P1_30, ADC0_4, 3}, + {P1_31, ADC0_5, 3}, + {NC, NC, 0} +}; + +#define ADC_RANGE ADC_10BIT_RANGE + + +void analogin_init(analogin_t *obj, PinName pin) { + obj->adc = (ADCName)pinmap_peripheral(pin, PinMap_ADC); + MBED_ASSERT(obj->adc != (ADCName)NC); + + // ensure power is turned on + LPC_SC->PCONP |= (1 << 12); + + // set PCLK of ADC to /1 + LPC_SC->PCLKSEL0 &= ~(0x3 << 24); + LPC_SC->PCLKSEL0 |= (0x1 << 24); + uint32_t PCLK = SystemCoreClock; + + // calculate minimum clock divider + // clkdiv = divider - 1 + uint32_t MAX_ADC_CLK = 13000000; + uint32_t clkdiv = div_round_up(PCLK, MAX_ADC_CLK) - 1; + + // Set the generic software-controlled ADC settings + LPC_ADC->ADCR = (0 << 0) // SEL: 0 = no channels selected + | (clkdiv << 8) // CLKDIV: PCLK max ~= 25MHz, /25 to give safe 1MHz at fastest + | (0 << 16) // BURST: 0 = software control + | (0 << 17) // CLKS: not applicable + | (1 << 21) // PDN: 1 = operational + | (0 << 24) // START: 0 = no start + | (0 << 27); // EDGE: not applicable + + pinmap_pinout(pin, PinMap_ADC); +} + +static inline uint32_t adc_read(analogin_t *obj) { + // Select the appropriate channel and start conversion + LPC_ADC->ADCR &= ~0xFF; + LPC_ADC->ADCR |= 1 << (int)obj->adc; + LPC_ADC->ADCR |= 1 << 24; + + // Repeatedly get the sample data until DONE bit + unsigned int data; + do { + data = LPC_ADC->ADGDR; + } while ((data & ((unsigned int)1 << 31)) == 0); + + // Stop conversion + LPC_ADC->ADCR &= ~(1 << 24); + + return (data >> 6) & ADC_RANGE; // 10 bit +} + +static inline void order(uint32_t *a, uint32_t *b) { + if (*a > *b) { + uint32_t t = *a; + *a = *b; + *b = t; + } +} + +static inline uint32_t adc_read_u32(analogin_t *obj) { + uint32_t value; +#if ANALOGIN_MEDIAN_FILTER + uint32_t v1 = adc_read(obj); + uint32_t v2 = adc_read(obj); + uint32_t v3 = adc_read(obj); + order(&v1, &v2); + order(&v2, &v3); + order(&v1, &v2); + value = v2; +#else + value = adc_read(obj); +#endif + return value; +} + +uint16_t analogin_read_u16(analogin_t *obj) { + uint32_t value = adc_read_u32(obj); + + return (value << 6) | ((value >> 4) & 0x003F); // 10 bit +} + +float analogin_read(analogin_t *obj) { + uint32_t value = adc_read_u32(obj); + return (float)value * (1.0f / (float)ADC_RANGE); +} diff --git a/targets/TARGET_NXP/TARGET_LPC23XX/analogout_api.c b/targets/TARGET_NXP/TARGET_LPC23XX/analogout_api.c new file mode 100644 index 00000000000..66c77ceaceb --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC23XX/analogout_api.c @@ -0,0 +1,75 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * 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. + */ +#include "mbed_assert.h" +#include "analogout_api.h" +#include "cmsis.h" +#include "pinmap.h" + +static const PinMap PinMap_DAC[] = { + {P0_26, DAC_0, 2}, + {NC , NC , 0} +}; + +void analogout_init(dac_t *obj, PinName pin) { + obj->dac = (DACName)pinmap_peripheral(pin, PinMap_DAC); + MBED_ASSERT(obj->dac != (DACName)NC); + + // power is on by default, set DAC clk divider is /4 + LPC_SC->PCLKSEL0 &= ~(0x3 << 22); + + // map out (must be done before accessing registers) + pinmap_pinout(pin, PinMap_DAC); + + analogout_write_u16(obj, 0); +} + +void analogout_free(dac_t *obj) {} + +static inline void dac_write(int value) { + value &= 0x3FF; // 10-bit + + // Set the DAC output + LPC_DAC->DACR = (0 << 16) // bias = 0 + | (value << 6); +} + +static inline int dac_read() { + return (LPC_DAC->DACR >> 6) & 0x3FF; +} + +void analogout_write(dac_t *obj, float value) { + if (value < 0.0f) { + dac_write(0); + } else if (value > 1.0f) { + dac_write(0x3FF); + } else { + dac_write(value * (float)0x3FF); + } +} + +void analogout_write_u16(dac_t *obj, uint16_t value) { + dac_write(value >> 6); // 10-bit +} + +float analogout_read(dac_t *obj) { + uint32_t value = dac_read(); + return (float)value * (1.0f / (float)0x3FF); +} + +uint16_t analogout_read_u16(dac_t *obj) { + uint32_t value = dac_read(); // 10-bit + return (value << 6) | ((value >> 4) & 0x003F); +} diff --git a/targets/TARGET_NXP/TARGET_LPC23XX/can_api.c b/targets/TARGET_NXP/TARGET_LPC23XX/can_api.c new file mode 100644 index 00000000000..a3170acc1d5 --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC23XX/can_api.c @@ -0,0 +1,303 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * 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. + */ +#include "mbed_assert.h" +#include "can_api.h" +#include "cmsis.h" +#include "pinmap.h" + +#include +#include + +/* Acceptance filter mode in AFMR register */ +#define ACCF_OFF 0x01 +#define ACCF_BYPASS 0x02 +#define ACCF_ON 0x00 +#define ACCF_FULLCAN 0x04 + +/* There are several bit timing calculators on the internet. +http://www.port.de/engl/canprod/sv_req_form.html +http://www.kvaser.com/can/index.htm +*/ + +static const PinMap PinMap_CAN_RD[] = { + {P0_0 , CAN_1, 1}, + {P0_4 , CAN_2, 2}, + {P0_21, CAN_1, 3}, + {P2_7 , CAN_2, 1}, + {NC , NC , 0} +}; + +static const PinMap PinMap_CAN_TD[] = { + {P0_1 , CAN_1, 1}, + {P0_5 , CAN_2, 2}, + {P0_22, CAN_1, 3}, + {P2_8 , CAN_2, 1}, + {NC , NC , 0} +}; + +// Type definition to hold a CAN message +struct CANMsg { + unsigned int reserved1 : 16; + unsigned int dlc : 4; // Bits 16..19: DLC - Data Length Counter + unsigned int reserved0 : 10; + unsigned int rtr : 1; // Bit 30: Set if this is a RTR message + unsigned int type : 1; // Bit 31: Set if this is a 29-bit ID message + unsigned int id; // CAN Message ID (11-bit or 29-bit) + unsigned char data[8]; // CAN Message Data Bytes 0-7 +}; +typedef struct CANMsg CANMsg; + +static uint32_t can_disable(can_t *obj) { + uint32_t sm = obj->dev->MOD; + obj->dev->MOD |= 1; + return sm; +} + +static inline void can_enable(can_t *obj) { + if (obj->dev->MOD & 1) { + obj->dev->MOD &= ~(1); + } +} + +int can_mode(can_t *obj, CanMode mode) { + return 0; // not implemented +} + +int can_filter(can_t *obj, uint32_t id, uint32_t mask, CANFormat format, int32_t handle) { + return 0; // not implemented +} + +static int can_pclk(can_t *obj) { + int value = 0; + switch ((int)obj->dev) { + case CAN_1: value = (LPC_SC->PCLKSEL0 & (0x3 << 26)) >> 26; break; + case CAN_2: value = (LPC_SC->PCLKSEL0 & (0x3 << 28)) >> 28; break; + } + + switch (value) { + case 1: return 1; + case 2: return 2; + case 3: return 6; + default: return 4; + } +} + +// This table has the sampling points as close to 75% as possible. The first +// value is TSEG1, the second TSEG2. +static const int timing_pts[23][2] = { + {0x0, 0x0}, // 2, 50% + {0x1, 0x0}, // 3, 67% + {0x2, 0x0}, // 4, 75% + {0x3, 0x0}, // 5, 80% + {0x3, 0x1}, // 6, 67% + {0x4, 0x1}, // 7, 71% + {0x5, 0x1}, // 8, 75% + {0x6, 0x1}, // 9, 78% + {0x6, 0x2}, // 10, 70% + {0x7, 0x2}, // 11, 73% + {0x8, 0x2}, // 12, 75% + {0x9, 0x2}, // 13, 77% + {0x9, 0x3}, // 14, 71% + {0xA, 0x3}, // 15, 73% + {0xB, 0x3}, // 16, 75% + {0xC, 0x3}, // 17, 76% + {0xD, 0x3}, // 18, 78% + {0xD, 0x4}, // 19, 74% + {0xE, 0x4}, // 20, 75% + {0xF, 0x4}, // 21, 76% + {0xF, 0x5}, // 22, 73% + {0xF, 0x6}, // 23, 70% + {0xF, 0x7}, // 24, 67% +}; + +static unsigned int can_speed(unsigned int sclk, unsigned int pclk, unsigned int cclk, unsigned char psjw) { + uint32_t btr; + uint16_t brp = 0; + uint32_t calcbit; + uint32_t bitwidth; + int hit = 0; + int bits; + + bitwidth = sclk / (pclk * cclk); + + brp = bitwidth / 0x18; + while ((!hit) && (brp < bitwidth / 4)) { + brp++; + for (bits = 22; bits > 0; bits--) { + calcbit = (bits + 3) * (brp + 1); + if (calcbit == bitwidth) { + hit = 1; + break; + } + } + } + + if (hit) { + btr = ((timing_pts[bits][1] << 20) & 0x00700000) + | ((timing_pts[bits][0] << 16) & 0x000F0000) + | ((psjw << 14) & 0x0000C000) + | ((brp << 0) & 0x000003FF); + } else { + btr = 0xFFFFFFFF; + } + + return btr; +} + +void can_init(can_t *obj, PinName rd, PinName td) { + CANName can_rd = (CANName)pinmap_peripheral(rd, PinMap_CAN_RD); + CANName can_td = (CANName)pinmap_peripheral(td, PinMap_CAN_TD); + obj->dev = (LPC_CAN_TypeDef *)pinmap_merge(can_rd, can_td); + MBED_ASSERT((int)obj->dev != NC); + + switch ((int)obj->dev) { + case CAN_1: LPC_SC->PCONP |= 1 << 13; break; + case CAN_2: LPC_SC->PCONP |= 1 << 14; break; + } + + pinmap_pinout(rd, PinMap_CAN_RD); + pinmap_pinout(td, PinMap_CAN_TD); + + can_reset(obj); + obj->dev->IER = 0; // Disable Interrupts + can_frequency(obj, 100000); + + LPC_CANAF->AFMR = ACCF_BYPASS; // Bypass Filter +} + +void can_free(can_t *obj) { + switch ((int)obj->dev) { + case CAN_1: LPC_SC->PCONP &= ~(1 << 13); break; + case CAN_2: LPC_SC->PCONP &= ~(1 << 14); break; + } +} + +int can_frequency(can_t *obj, int f) { + int pclk = can_pclk(obj); + int btr = can_speed(SystemCoreClock, pclk, (unsigned int)f, 1); + + if (btr > 0) { + uint32_t modmask = can_disable(obj); + obj->dev->BTR = btr; + obj->dev->MOD = modmask; + return 1; + } else { + return 0; + } +} + +int can_write(can_t *obj, CAN_Message msg, int cc) { + unsigned int CANStatus; + CANMsg m; + + can_enable(obj); + + m.id = msg.id ; + m.dlc = msg.len & 0xF; + m.rtr = msg.type; + m.type = msg.format; + memcpy(m.data, msg.data, msg.len); + const unsigned int *buf = (const unsigned int *)&m; + + CANStatus = obj->dev->SR; + if (CANStatus & 0x00000004) { + obj->dev->TFI1 = buf[0] & 0xC00F0000; + obj->dev->TID1 = buf[1]; + obj->dev->TDA1 = buf[2]; + obj->dev->TDB1 = buf[3]; + if (cc) { + obj->dev->CMR = 0x30; + } else { + obj->dev->CMR = 0x21; + } + return 1; + + } else if (CANStatus & 0x00000400) { + obj->dev->TFI2 = buf[0] & 0xC00F0000; + obj->dev->TID2 = buf[1]; + obj->dev->TDA2 = buf[2]; + obj->dev->TDB2 = buf[3]; + if (cc) { + obj->dev->CMR = 0x50; + } else { + obj->dev->CMR = 0x41; + } + return 1; + + } else if (CANStatus & 0x00040000) { + obj->dev->TFI3 = buf[0] & 0xC00F0000; + obj->dev->TID3 = buf[1]; + obj->dev->TDA3 = buf[2]; + obj->dev->TDB3 = buf[3]; + if (cc) { + obj->dev->CMR = 0x90; + } else { + obj->dev->CMR = 0x81; + } + return 1; + } + + return 0; +} + +int can_read(can_t *obj, CAN_Message *msg, int handle) { + CANMsg x; + unsigned int *i = (unsigned int *)&x; + + can_enable(obj); + + if (obj->dev->GSR & 0x1) { + *i++ = obj->dev->RFS; // Frame + *i++ = obj->dev->RID; // ID + *i++ = obj->dev->RDA; // Data A + *i++ = obj->dev->RDB; // Data B + obj->dev->CMR = 0x04; // release receive buffer + + msg->id = x.id; + msg->len = x.dlc; + msg->format = (x.type)? CANExtended : CANStandard; + msg->type = (x.rtr)? CANRemote: CANData; + memcpy(msg->data,x.data,x.dlc); + return 1; + } + + return 0; +} + +void can_reset(can_t *obj) { + can_disable(obj); + obj->dev->GSR = 0; // Reset error counter when CAN1MOD is in reset +} + +unsigned char can_rderror(can_t *obj) { + return (obj->dev->GSR >> 16) & 0xFF; +} + +unsigned char can_tderror(can_t *obj) { + return (obj->dev->GSR >> 24) & 0xFF; +} + +void can_monitor(can_t *obj, int silent) { + uint32_t mod_mask = can_disable(obj); + if (silent) { + obj->dev->MOD |= (1 << 1); + } else { + obj->dev->MOD &= ~(1 << 1); + } + if (!(mod_mask & 1)) { + can_enable(obj); + } +} diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/TARGET_RO359B/device.h b/targets/TARGET_NXP/TARGET_LPC23XX/device.h similarity index 89% rename from targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/TARGET_RO359B/device.h rename to targets/TARGET_NXP/TARGET_LPC23XX/device.h index 976726a94a8..5d57c9de571 100644 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/TARGET_RO359B/device.h +++ b/targets/TARGET_NXP/TARGET_LPC23XX/device.h @@ -1,7 +1,7 @@ // The 'features' section in 'target.json' is now used to create the device's hardware preprocessor switches. // Check the 'features' section of the target description in 'targets.json' for more details. /* mbed Microcontroller Library - * Copyright (c) 2006-2017 ARM Limited + * Copyright (c) 2006-2013 ARM Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,7 +28,8 @@ -#define DEVICE_ID_LENGTH 24 +#define DEVICE_ID_LENGTH 32 +#define DEVICE_MAC_OFFSET 20 diff --git a/targets/TARGET_NXP/TARGET_LPC23XX/device/LPC23xx.h b/targets/TARGET_NXP/TARGET_LPC23XX/device/LPC23xx.h new file mode 100644 index 00000000000..9adaac48868 --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC23XX/device/LPC23xx.h @@ -0,0 +1,864 @@ +/* mbed Microcontroller Library - LPC23xx CMSIS-like structs + * Copyright (C) 2009 ARM Limited. All rights reserved. + * + * An LPC23xx header file, based on the CMSIS LPC17xx.h and old LPC23xx.h + */ + +#ifndef __LPC23xx_H +#define __LPC23xx_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* + * ========================================================================== + * ---------- Interrupt Number Definition ----------------------------------- + * ========================================================================== + */ + +typedef enum IRQn +{ +/****** LPC23xx Specific Interrupt Numbers *******************************************************/ + WDT_IRQn = 0, /*!< Watchdog Timer Interrupt */ + + TIMER0_IRQn = 4, /*!< Timer0 Interrupt */ + TIMER1_IRQn = 5, /*!< Timer1 Interrupt */ + UART0_IRQn = 6, /*!< UART0 Interrupt */ + UART1_IRQn = 7, /*!< UART1 Interrupt */ + PWM1_IRQn = 8, /*!< PWM1 Interrupt */ + I2C0_IRQn = 9, /*!< I2C0 Interrupt */ + SPI_IRQn = 10, /*!< SPI Interrupt */ + SSP0_IRQn = 10, /*!< SSP0 Interrupt */ + SSP1_IRQn = 11, /*!< SSP1 Interrupt */ + PLL0_IRQn = 12, /*!< PLL0 Lock (Main PLL) Interrupt */ + RTC_IRQn = 13, /*!< Real Time Clock Interrupt */ + EINT0_IRQn = 14, /*!< External Interrupt 0 Interrupt */ + EINT1_IRQn = 15, /*!< External Interrupt 1 Interrupt */ + EINT2_IRQn = 16, /*!< External Interrupt 2 Interrupt */ + EINT3_IRQn = 17, /*!< External Interrupt 3 Interrupt */ + ADC_IRQn = 18, /*!< A/D Converter Interrupt */ + I2C1_IRQn = 19, /*!< I2C1 Interrupt */ + BOD_IRQn = 20, /*!< Brown-Out Detect Interrupt */ + ENET_IRQn = 21, /*!< Ethernet Interrupt */ + USB_IRQn = 22, /*!< USB Interrupt */ + CAN_IRQn = 23, /*!< CAN Interrupt */ + MIC_IRQn = 24, /*!< Multimedia Interface Controler */ + DMA_IRQn = 25, /*!< General Purpose DMA Interrupt */ + TIMER2_IRQn = 26, /*!< Timer2 Interrupt */ + TIMER3_IRQn = 27, /*!< Timer3 Interrupt */ + UART2_IRQn = 28, /*!< UART2 Interrupt */ + UART3_IRQn = 29, /*!< UART3 Interrupt */ + I2C2_IRQn = 30, /*!< I2C2 Interrupt */ + I2S_IRQn = 31, /*!< I2S Interrupt */ +} IRQn_Type; + +/* + * ========================================================================== + * ----------- Processor and Core Peripheral Section ------------------------ + * ========================================================================== + */ + +/* Configuration of the ARM7 Processor and Core Peripherals */ +#define __MPU_PRESENT 0 /*!< MPU present or not */ +#define __NVIC_PRIO_BITS 4 /*!< Number of Bits used for Priority Levels */ +#define __Vendor_SysTickConfig 0 /*!< Set to 1 if different SysTick Config is used */ + + +#include +#include "system_LPC23xx.h" /* System Header */ + + +/******************************************************************************/ +/* Device Specific Peripheral registers structures */ +/******************************************************************************/ +#if defined ( __CC_ARM ) + #pragma anon_unions +#endif + +/*------------- Vector Interupt Controler (VIC) ------------------------------*/ +typedef struct +{ + __I uint32_t IRQStatus; + __I uint32_t FIQStatus; + __I uint32_t RawIntr; + __IO uint32_t IntSelect; + __IO uint32_t IntEnable; + __O uint32_t IntEnClr; + __IO uint32_t SoftInt; + __O uint32_t SoftIntClr; + __IO uint32_t Protection; + __IO uint32_t SWPriorityMask; + __IO uint32_t RESERVED0[54]; + __IO uint32_t VectAddr[32]; + __IO uint32_t RESERVED1[32]; + __IO uint32_t VectPriority[32]; + __IO uint32_t RESERVED2[800]; + __IO uint32_t Address; +} LPC_VIC_TypeDef; + +/*------------- System Control (SC) ------------------------------------------*/ +typedef struct +{ + __IO uint32_t MAMCR; + __IO uint32_t MAMTIM; + uint32_t RESERVED0[14]; + __IO uint32_t MEMMAP; + uint32_t RESERVED1[15]; + __IO uint32_t PLL0CON; /* Clocking and Power Control */ + __IO uint32_t PLL0CFG; + __I uint32_t PLL0STAT; + __O uint32_t PLL0FEED; + uint32_t RESERVED2[12]; + __IO uint32_t PCON; + __IO uint32_t PCONP; + uint32_t RESERVED3[15]; + __IO uint32_t CCLKCFG; + __IO uint32_t USBCLKCFG; + __IO uint32_t CLKSRCSEL; + uint32_t RESERVED4[12]; + __IO uint32_t EXTINT; /* External Interrupts */ + __IO uint32_t INTWAKE; + __IO uint32_t EXTMODE; + __IO uint32_t EXTPOLAR; + uint32_t RESERVED6[12]; + __IO uint32_t RSID; /* Reset */ + __IO uint32_t CSPR; + __IO uint32_t AHBCFG1; + __IO uint32_t AHBCFG2; + uint32_t RESERVED7[4]; + __IO uint32_t SCS; /* Syscon Miscellaneous Registers */ + __IO uint32_t IRCTRIM; /* Clock Dividers */ + __IO uint32_t PCLKSEL0; + __IO uint32_t PCLKSEL1; + uint32_t RESERVED8[4]; + __IO uint32_t USBIntSt; /* USB Device/OTG Interrupt Register */ + uint32_t RESERVED9; +// __IO uint32_t CLKOUTCFG; /* Clock Output Configuration */ + } LPC_SC_TypeDef; + +/*------------- Pin Connect Block (PINCON) -----------------------------------*/ +typedef struct +{ + __IO uint32_t PINSEL0; + __IO uint32_t PINSEL1; + __IO uint32_t PINSEL2; + __IO uint32_t PINSEL3; + __IO uint32_t PINSEL4; + __IO uint32_t PINSEL5; + __IO uint32_t PINSEL6; + __IO uint32_t PINSEL7; + __IO uint32_t PINSEL8; + __IO uint32_t PINSEL9; + __IO uint32_t PINSEL10; + uint32_t RESERVED0[5]; + __IO uint32_t PINMODE0; + __IO uint32_t PINMODE1; + __IO uint32_t PINMODE2; + __IO uint32_t PINMODE3; + __IO uint32_t PINMODE4; + __IO uint32_t PINMODE5; + __IO uint32_t PINMODE6; + __IO uint32_t PINMODE7; + __IO uint32_t PINMODE8; + __IO uint32_t PINMODE9; + __IO uint32_t PINMODE_OD0; + __IO uint32_t PINMODE_OD1; + __IO uint32_t PINMODE_OD2; + __IO uint32_t PINMODE_OD3; + __IO uint32_t PINMODE_OD4; +} LPC_PINCON_TypeDef; + +/*------------- General Purpose Input/Output (GPIO) --------------------------*/ +typedef struct +{ + __IO uint32_t FIODIR; + uint32_t RESERVED0[3]; + __IO uint32_t FIOMASK; + __IO uint32_t FIOPIN; + __IO uint32_t FIOSET; + __O uint32_t FIOCLR; +} LPC_GPIO_TypeDef; + +typedef struct +{ + __I uint32_t IntStatus; + __I uint32_t IO0IntStatR; + __I uint32_t IO0IntStatF; + __O uint32_t IO0IntClr; + __IO uint32_t IO0IntEnR; + __IO uint32_t IO0IntEnF; + uint32_t RESERVED0[3]; + __I uint32_t IO2IntStatR; + __I uint32_t IO2IntStatF; + __O uint32_t IO2IntClr; + __IO uint32_t IO2IntEnR; + __IO uint32_t IO2IntEnF; +} LPC_GPIOINT_TypeDef; + +/*------------- Timer (TIM) --------------------------------------------------*/ +typedef struct +{ + __IO uint32_t IR; + __IO uint32_t TCR; + __IO uint32_t TC; + __IO uint32_t PR; + __IO uint32_t PC; + __IO uint32_t MCR; + __IO uint32_t MR0; + __IO uint32_t MR1; + __IO uint32_t MR2; + __IO uint32_t MR3; + __IO uint32_t CCR; + __I uint32_t CR0; + __I uint32_t CR1; + uint32_t RESERVED0[2]; + __IO uint32_t EMR; + uint32_t RESERVED1[12]; + __IO uint32_t CTCR; +} LPC_TIM_TypeDef; + +/*------------- Pulse-Width Modulation (PWM) ---------------------------------*/ +typedef struct +{ + __IO uint32_t IR; + __IO uint32_t TCR; + __IO uint32_t TC; + __IO uint32_t PR; + __IO uint32_t PC; + __IO uint32_t MCR; + __IO uint32_t MR0; + __IO uint32_t MR1; + __IO uint32_t MR2; + __IO uint32_t MR3; + __IO uint32_t CCR; + __I uint32_t CR0; + __I uint32_t CR1; + __I uint32_t CR2; + __I uint32_t CR3; + uint32_t RESERVED0; + __IO uint32_t MR4; + __IO uint32_t MR5; + __IO uint32_t MR6; + __IO uint32_t PCR; + __IO uint32_t LER; + uint32_t RESERVED1[7]; + __IO uint32_t CTCR; +} LPC_PWM_TypeDef; + +/*------------- Universal Asynchronous Receiver Transmitter (UART) -----------*/ +typedef struct +{ + union { + __I uint8_t RBR; + __O uint8_t THR; + __IO uint8_t DLL; + uint32_t RESERVED0; + }; + union { + __IO uint8_t DLM; + __IO uint32_t IER; + }; + union { + __I uint32_t IIR; + __O uint8_t FCR; + }; + __IO uint8_t LCR; + uint8_t RESERVED1[7]; + __IO uint8_t LSR; + uint8_t RESERVED2[7]; + __IO uint8_t SCR; + uint8_t RESERVED3[3]; + __IO uint32_t ACR; + __IO uint8_t ICR; + uint8_t RESERVED4[3]; + __IO uint8_t FDR; + uint8_t RESERVED5[7]; + __IO uint8_t TER; + uint8_t RESERVED6[27]; + __IO uint8_t RS485CTRL; + uint8_t RESERVED7[3]; + __IO uint8_t ADRMATCH; +} LPC_UART_TypeDef; + +typedef struct +{ + union { + __I uint8_t RBR; + __O uint8_t THR; + __IO uint8_t DLL; + uint32_t RESERVED0; + }; + union { + __IO uint8_t DLM; + __IO uint32_t IER; + }; + union { + __I uint32_t IIR; + __O uint8_t FCR; + }; + __IO uint8_t LCR; + uint8_t RESERVED1[3]; + __IO uint8_t MCR; + uint8_t RESERVED2[3]; + __IO uint8_t LSR; + uint8_t RESERVED3[3]; + __IO uint8_t MSR; + uint8_t RESERVED4[3]; + __IO uint8_t SCR; + uint8_t RESERVED5[3]; + __IO uint32_t ACR; + uint32_t RESERVED6; + __IO uint32_t FDR; + uint32_t RESERVED7; + __IO uint8_t TER; + uint8_t RESERVED8[27]; + __IO uint8_t RS485CTRL; + uint8_t RESERVED9[3]; + __IO uint8_t ADRMATCH; + uint8_t RESERVED10[3]; + __IO uint8_t RS485DLY; +} LPC_UART1_TypeDef; + +/*------------- Serial Peripheral Interface (SPI) ----------------------------*/ +typedef struct +{ + __IO uint32_t SPCR; + __I uint32_t SPSR; + __IO uint32_t SPDR; + __IO uint32_t SPCCR; + uint32_t RESERVED0[3]; + __IO uint32_t SPINT; +} LPC_SPI_TypeDef; + +/*------------- Synchronous Serial Communication (SSP) -----------------------*/ +typedef struct +{ + __IO uint32_t CR0; + __IO uint32_t CR1; + __IO uint32_t DR; + __I uint32_t SR; + __IO uint32_t CPSR; + __IO uint32_t IMSC; + __IO uint32_t RIS; + __IO uint32_t MIS; + __IO uint32_t ICR; + __IO uint32_t DMACR; +} LPC_SSP_TypeDef; + +/*------------- Inter-Integrated Circuit (I2C) -------------------------------*/ +typedef struct +{ + __IO uint32_t I2CONSET; + __I uint32_t I2STAT; + __IO uint32_t I2DAT; + __IO uint32_t I2ADR0; + __IO uint32_t I2SCLH; + __IO uint32_t I2SCLL; + __O uint32_t I2CONCLR; + __IO uint32_t MMCTRL; + __IO uint32_t I2ADR1; + __IO uint32_t I2ADR2; + __IO uint32_t I2ADR3; + __I uint32_t I2DATA_BUFFER; + __IO uint32_t I2MASK0; + __IO uint32_t I2MASK1; + __IO uint32_t I2MASK2; + __IO uint32_t I2MASK3; +} LPC_I2C_TypeDef; + +/*------------- Inter IC Sound (I2S) -----------------------------------------*/ +typedef struct +{ + __IO uint32_t I2SDAO; + __I uint32_t I2SDAI; + __O uint32_t I2STXFIFO; + __I uint32_t I2SRXFIFO; + __I uint32_t I2SSTATE; + __IO uint32_t I2SDMA1; + __IO uint32_t I2SDMA2; + __IO uint32_t I2SIRQ; + __IO uint32_t I2STXRATE; + __IO uint32_t I2SRXRATE; + __IO uint32_t I2STXBITRATE; + __IO uint32_t I2SRXBITRATE; + __IO uint32_t I2STXMODE; + __IO uint32_t I2SRXMODE; +} LPC_I2S_TypeDef; + +/*------------- Real-Time Clock (RTC) ----------------------------------------*/ +typedef struct +{ + __IO uint8_t ILR; + uint8_t RESERVED0[3]; + __IO uint8_t CTC; + uint8_t RESERVED1[3]; + __IO uint8_t CCR; + uint8_t RESERVED2[3]; + __IO uint8_t CIIR; + uint8_t RESERVED3[3]; + __IO uint8_t AMR; + uint8_t RESERVED4[3]; + __I uint32_t CTIME0; + __I uint32_t CTIME1; + __I uint32_t CTIME2; + __IO uint8_t SEC; + uint8_t RESERVED5[3]; + __IO uint8_t MIN; + uint8_t RESERVED6[3]; + __IO uint8_t HOUR; + uint8_t RESERVED7[3]; + __IO uint8_t DOM; + uint8_t RESERVED8[3]; + __IO uint8_t DOW; + uint8_t RESERVED9[3]; + __IO uint16_t DOY; + uint16_t RESERVED10; + __IO uint8_t MONTH; + uint8_t RESERVED11[3]; + __IO uint16_t YEAR; + uint16_t RESERVED12; + __IO uint32_t CALIBRATION; + __IO uint32_t GPREG0; + __IO uint32_t GPREG1; + __IO uint32_t GPREG2; + __IO uint32_t GPREG3; + __IO uint32_t GPREG4; + __IO uint8_t WAKEUPDIS; + uint8_t RESERVED13[3]; + __IO uint8_t PWRCTRL; + uint8_t RESERVED14[3]; + __IO uint8_t ALSEC; + uint8_t RESERVED15[3]; + __IO uint8_t ALMIN; + uint8_t RESERVED16[3]; + __IO uint8_t ALHOUR; + uint8_t RESERVED17[3]; + __IO uint8_t ALDOM; + uint8_t RESERVED18[3]; + __IO uint8_t ALDOW; + uint8_t RESERVED19[3]; + __IO uint16_t ALDOY; + uint16_t RESERVED20; + __IO uint8_t ALMON; + uint8_t RESERVED21[3]; + __IO uint16_t ALYEAR; + uint16_t RESERVED22; +} LPC_RTC_TypeDef; + +/*------------- Watchdog Timer (WDT) -----------------------------------------*/ +typedef struct +{ + __IO uint8_t WDMOD; + uint8_t RESERVED0[3]; + __IO uint32_t WDTC; + __O uint8_t WDFEED; + uint8_t RESERVED1[3]; + __I uint32_t WDTV; + __IO uint32_t WDCLKSEL; +} LPC_WDT_TypeDef; + +/*------------- Analog-to-Digital Converter (ADC) ----------------------------*/ +typedef struct +{ + __IO uint32_t ADCR; + __IO uint32_t ADGDR; + uint32_t RESERVED0; + __IO uint32_t ADINTEN; + __I uint32_t ADDR0; + __I uint32_t ADDR1; + __I uint32_t ADDR2; + __I uint32_t ADDR3; + __I uint32_t ADDR4; + __I uint32_t ADDR5; + __I uint32_t ADDR6; + __I uint32_t ADDR7; + __I uint32_t ADSTAT; + __IO uint32_t ADTRM; +} LPC_ADC_TypeDef; + +/*------------- Digital-to-Analog Converter (DAC) ----------------------------*/ +typedef struct +{ + __IO uint32_t DACR; + __IO uint32_t DACCTRL; + __IO uint16_t DACCNTVAL; +} LPC_DAC_TypeDef; + +/*------------- Multimedia Card Interface (MCI) ------------------------------*/ +typedef struct +{ + __IO uint32_t MCIPower; /* Power control */ + __IO uint32_t MCIClock; /* Clock control */ + __IO uint32_t MCIArgument; + __IO uint32_t MMCCommand; + __I uint32_t MCIRespCmd; + __I uint32_t MCIResponse0; + __I uint32_t MCIResponse1; + __I uint32_t MCIResponse2; + __I uint32_t MCIResponse3; + __IO uint32_t MCIDataTimer; + __IO uint32_t MCIDataLength; + __IO uint32_t MCIDataCtrl; + __I uint32_t MCIDataCnt; +} LPC_MCI_TypeDef; + +/*------------- Controller Area Network (CAN) --------------------------------*/ +typedef struct +{ + __IO uint32_t mask[512]; /* ID Masks */ +} LPC_CANAF_RAM_TypeDef; + +typedef struct /* Acceptance Filter Registers */ +{ + __IO uint32_t AFMR; + __IO uint32_t SFF_sa; + __IO uint32_t SFF_GRP_sa; + __IO uint32_t EFF_sa; + __IO uint32_t EFF_GRP_sa; + __IO uint32_t ENDofTable; + __I uint32_t LUTerrAd; + __I uint32_t LUTerr; +} LPC_CANAF_TypeDef; + +typedef struct /* Central Registers */ +{ + __I uint32_t CANTxSR; + __I uint32_t CANRxSR; + __I uint32_t CANMSR; +} LPC_CANCR_TypeDef; + +typedef struct /* Controller Registers */ +{ + __IO uint32_t MOD; + __O uint32_t CMR; + __IO uint32_t GSR; + __I uint32_t ICR; + __IO uint32_t IER; + __IO uint32_t BTR; + __IO uint32_t EWL; + __I uint32_t SR; + __IO uint32_t RFS; + __IO uint32_t RID; + __IO uint32_t RDA; + __IO uint32_t RDB; + __IO uint32_t TFI1; + __IO uint32_t TID1; + __IO uint32_t TDA1; + __IO uint32_t TDB1; + __IO uint32_t TFI2; + __IO uint32_t TID2; + __IO uint32_t TDA2; + __IO uint32_t TDB2; + __IO uint32_t TFI3; + __IO uint32_t TID3; + __IO uint32_t TDA3; + __IO uint32_t TDB3; +} LPC_CAN_TypeDef; + +/*------------- General Purpose Direct Memory Access (GPDMA) -----------------*/ +typedef struct /* Common Registers */ +{ + __I uint32_t DMACIntStat; + __I uint32_t DMACIntTCStat; + __O uint32_t DMACIntTCClear; + __I uint32_t DMACIntErrStat; + __O uint32_t DMACIntErrClr; + __I uint32_t DMACRawIntTCStat; + __I uint32_t DMACRawIntErrStat; + __I uint32_t DMACEnbldChns; + __IO uint32_t DMACSoftBReq; + __IO uint32_t DMACSoftSReq; + __IO uint32_t DMACSoftLBReq; + __IO uint32_t DMACSoftLSReq; + __IO uint32_t DMACConfig; + __IO uint32_t DMACSync; +} LPC_GPDMA_TypeDef; + +typedef struct /* Channel Registers */ +{ + __IO uint32_t DMACCSrcAddr; + __IO uint32_t DMACCDestAddr; + __IO uint32_t DMACCLLI; + __IO uint32_t DMACCControl; + __IO uint32_t DMACCConfig; +} LPC_GPDMACH_TypeDef; + +/*------------- Universal Serial Bus (USB) -----------------------------------*/ +typedef struct +{ + __I uint32_t HcRevision; /* USB Host Registers */ + __IO uint32_t HcControl; + __IO uint32_t HcCommandStatus; + __IO uint32_t HcInterruptStatus; + __IO uint32_t HcInterruptEnable; + __IO uint32_t HcInterruptDisable; + __IO uint32_t HcHCCA; + __I uint32_t HcPeriodCurrentED; + __IO uint32_t HcControlHeadED; + __IO uint32_t HcControlCurrentED; + __IO uint32_t HcBulkHeadED; + __IO uint32_t HcBulkCurrentED; + __I uint32_t HcDoneHead; + __IO uint32_t HcFmInterval; + __I uint32_t HcFmRemaining; + __I uint32_t HcFmNumber; + __IO uint32_t HcPeriodicStart; + __IO uint32_t HcLSTreshold; + __IO uint32_t HcRhDescriptorA; + __IO uint32_t HcRhDescriptorB; + __IO uint32_t HcRhStatus; + __IO uint32_t HcRhPortStatus1; + __IO uint32_t HcRhPortStatus2; + uint32_t RESERVED0[40]; + __I uint32_t Module_ID; + + __I uint32_t OTGIntSt; /* USB On-The-Go Registers */ + __IO uint32_t OTGIntEn; + __O uint32_t OTGIntSet; + __O uint32_t OTGIntClr; + __IO uint32_t OTGStCtrl; + __IO uint32_t OTGTmr; + uint32_t RESERVED1[58]; + + __I uint32_t USBDevIntSt; /* USB Device Interrupt Registers */ + __IO uint32_t USBDevIntEn; + __O uint32_t USBDevIntClr; + __O uint32_t USBDevIntSet; + + __O uint32_t USBCmdCode; /* USB Device SIE Command Registers */ + __I uint32_t USBCmdData; + + __I uint32_t USBRxData; /* USB Device Transfer Registers */ + __O uint32_t USBTxData; + __I uint32_t USBRxPLen; + __O uint32_t USBTxPLen; + __IO uint32_t USBCtrl; + __O uint32_t USBDevIntPri; + + __I uint32_t USBEpIntSt; /* USB Device Endpoint Interrupt Regs */ + __IO uint32_t USBEpIntEn; + __O uint32_t USBEpIntClr; + __O uint32_t USBEpIntSet; + __O uint32_t USBEpIntPri; + + __IO uint32_t USBReEp; /* USB Device Endpoint Realization Reg*/ + __O uint32_t USBEpInd; + __IO uint32_t USBMaxPSize; + + __I uint32_t USBDMARSt; /* USB Device DMA Registers */ + __O uint32_t USBDMARClr; + __O uint32_t USBDMARSet; + uint32_t RESERVED2[9]; + __IO uint32_t USBUDCAH; + __I uint32_t USBEpDMASt; + __O uint32_t USBEpDMAEn; + __O uint32_t USBEpDMADis; + __I uint32_t USBDMAIntSt; + __IO uint32_t USBDMAIntEn; + uint32_t RESERVED3[2]; + __I uint32_t USBEoTIntSt; + __O uint32_t USBEoTIntClr; + __O uint32_t USBEoTIntSet; + __I uint32_t USBNDDRIntSt; + __O uint32_t USBNDDRIntClr; + __O uint32_t USBNDDRIntSet; + __I uint32_t USBSysErrIntSt; + __O uint32_t USBSysErrIntClr; + __O uint32_t USBSysErrIntSet; + uint32_t RESERVED4[15]; + + __I uint32_t I2C_RX; /* USB OTG I2C Registers */ + __O uint32_t I2C_WO; + __I uint32_t I2C_STS; + __IO uint32_t I2C_CTL; + __IO uint32_t I2C_CLKHI; + __O uint32_t I2C_CLKLO; + uint32_t RESERVED5[823]; + + union { + __IO uint32_t USBClkCtrl; /* USB Clock Control Registers */ + __IO uint32_t OTGClkCtrl; + }; + union { + __I uint32_t USBClkSt; + __I uint32_t OTGClkSt; + }; +} LPC_USB_TypeDef; + +/*------------- Ethernet Media Access Controller (EMAC) ----------------------*/ +typedef struct +{ + __IO uint32_t MAC1; /* MAC Registers */ + __IO uint32_t MAC2; + __IO uint32_t IPGT; + __IO uint32_t IPGR; + __IO uint32_t CLRT; + __IO uint32_t MAXF; + __IO uint32_t SUPP; + __IO uint32_t TEST; + __IO uint32_t MCFG; + __IO uint32_t MCMD; + __IO uint32_t MADR; + __O uint32_t MWTD; + __I uint32_t MRDD; + __I uint32_t MIND; + uint32_t RESERVED0[2]; + __IO uint32_t SA0; + __IO uint32_t SA1; + __IO uint32_t SA2; + uint32_t RESERVED1[45]; + __IO uint32_t Command; /* Control Registers */ + __I uint32_t Status; + __IO uint32_t RxDescriptor; + __IO uint32_t RxStatus; + __IO uint32_t RxDescriptorNumber; + __I uint32_t RxProduceIndex; + __IO uint32_t RxConsumeIndex; + __IO uint32_t TxDescriptor; + __IO uint32_t TxStatus; + __IO uint32_t TxDescriptorNumber; + __IO uint32_t TxProduceIndex; + __I uint32_t TxConsumeIndex; + uint32_t RESERVED2[10]; + __I uint32_t TSV0; + __I uint32_t TSV1; + __I uint32_t RSV; + uint32_t RESERVED3[3]; + __IO uint32_t FlowControlCounter; + __I uint32_t FlowControlStatus; + uint32_t RESERVED4[34]; + __IO uint32_t RxFilterCtrl; /* Rx Filter Registers */ + __IO uint32_t RxFilterWoLStatus; + __IO uint32_t RxFilterWoLClear; + uint32_t RESERVED5; + __IO uint32_t HashFilterL; + __IO uint32_t HashFilterH; + uint32_t RESERVED6[882]; + __I uint32_t IntStatus; /* Module Control Registers */ + __IO uint32_t IntEnable; + __O uint32_t IntClear; + __O uint32_t IntSet; + uint32_t RESERVED7; + __IO uint32_t PowerDown; + uint32_t RESERVED8; + __IO uint32_t Module_ID; +} LPC_EMAC_TypeDef; + +#if defined ( __CC_ARM ) + #pragma no_anon_unions +#endif + +/******************************************************************************/ +/* Peripheral memory map */ +/******************************************************************************/ +/* Base addresses */ + +/* AHB Peripheral # 0 */ + +/* +#define FLASH_BASE (0x00000000UL) +#define RAM_BASE (0x10000000UL) +#define GPIO_BASE (0x2009C000UL) +#define APB0_BASE (0x40000000UL) +#define APB1_BASE (0x40080000UL) +#define AHB_BASE (0x50000000UL) +#define CM3_BASE (0xE0000000UL) +*/ + +// TODO - #define VIC_BASE_ADDR 0xFFFFF000 + +#define LPC_WDT_BASE (0xE0000000) +#define LPC_TIM0_BASE (0xE0004000) +#define LPC_TIM1_BASE (0xE0008000) +#define LPC_UART0_BASE (0xE000C000) +#define LPC_UART1_BASE (0xE0010000) +#define LPC_PWM1_BASE (0xE0018000) +#define LPC_I2C0_BASE (0xE001C000) +#define LPC_SPI_BASE (0xE0020000) +#define LPC_RTC_BASE (0xE0024000) +#define LPC_GPIOINT_BASE (0xE0028080) +#define LPC_PINCON_BASE (0xE002C000) +#define LPC_SSP1_BASE (0xE0030000) +#define LPC_ADC_BASE (0xE0034000) +#define LPC_CANAF_RAM_BASE (0xE0038000) +#define LPC_CANAF_BASE (0xE003C000) +#define LPC_CANCR_BASE (0xE0040000) +#define LPC_CAN1_BASE (0xE0044000) +#define LPC_CAN2_BASE (0xE0048000) +#define LPC_I2C1_BASE (0xE005C000) +#define LPC_SSP0_BASE (0xE0068000) +#define LPC_DAC_BASE (0xE006C000) +#define LPC_TIM2_BASE (0xE0070000) +#define LPC_TIM3_BASE (0xE0074000) +#define LPC_UART2_BASE (0xE0078000) +#define LPC_UART3_BASE (0xE007C000) +#define LPC_I2C2_BASE (0xE0080000) +#define LPC_I2S_BASE (0xE0088000) +#define LPC_MCI_BASE (0xE008C000) +#define LPC_SC_BASE (0xE01FC000) +#define LPC_EMAC_BASE (0xFFE00000) +#define LPC_GPDMA_BASE (0xFFE04000) +#define LPC_GPDMACH0_BASE (0xFFE04100) +#define LPC_GPDMACH1_BASE (0xFFE04120) +#define LPC_USB_BASE (0xFFE0C000) +#define LPC_VIC_BASE (0xFFFFF000) + +/* GPIOs */ +#define LPC_GPIO0_BASE (0x3FFFC000) +#define LPC_GPIO1_BASE (0x3FFFC020) +#define LPC_GPIO2_BASE (0x3FFFC040) +#define LPC_GPIO3_BASE (0x3FFFC060) +#define LPC_GPIO4_BASE (0x3FFFC080) + + +/******************************************************************************/ +/* Peripheral declaration */ +/******************************************************************************/ +#define LPC_SC (( LPC_SC_TypeDef *) LPC_SC_BASE) +#define LPC_GPIO0 (( LPC_GPIO_TypeDef *) LPC_GPIO0_BASE) +#define LPC_GPIO1 (( LPC_GPIO_TypeDef *) LPC_GPIO1_BASE) +#define LPC_GPIO2 (( LPC_GPIO_TypeDef *) LPC_GPIO2_BASE) +#define LPC_GPIO3 (( LPC_GPIO_TypeDef *) LPC_GPIO3_BASE) +#define LPC_GPIO4 (( LPC_GPIO_TypeDef *) LPC_GPIO4_BASE) +#define LPC_WDT (( LPC_WDT_TypeDef *) LPC_WDT_BASE) +#define LPC_TIM0 (( LPC_TIM_TypeDef *) LPC_TIM0_BASE) +#define LPC_TIM1 (( LPC_TIM_TypeDef *) LPC_TIM1_BASE) +#define LPC_TIM2 (( LPC_TIM_TypeDef *) LPC_TIM2_BASE) +#define LPC_TIM3 (( LPC_TIM_TypeDef *) LPC_TIM3_BASE) +#define LPC_UART0 (( LPC_UART_TypeDef *) LPC_UART0_BASE) +#define LPC_UART1 (( LPC_UART1_TypeDef *) LPC_UART1_BASE) +#define LPC_UART2 (( LPC_UART_TypeDef *) LPC_UART2_BASE) +#define LPC_UART3 (( LPC_UART_TypeDef *) LPC_UART3_BASE) +#define LPC_PWM1 (( LPC_PWM_TypeDef *) LPC_PWM1_BASE) +#define LPC_I2C0 (( LPC_I2C_TypeDef *) LPC_I2C0_BASE) +#define LPC_I2C1 (( LPC_I2C_TypeDef *) LPC_I2C1_BASE) +#define LPC_I2C2 (( LPC_I2C_TypeDef *) LPC_I2C2_BASE) +#define LPC_I2S (( LPC_I2S_TypeDef *) LPC_I2S_BASE) +#define LPC_SPI (( LPC_SPI_TypeDef *) LPC_SPI_BASE) +#define LPC_RTC (( LPC_RTC_TypeDef *) LPC_RTC_BASE) +#define LPC_GPIOINT (( LPC_GPIOINT_TypeDef *) LPC_GPIOINT_BASE) +#define LPC_PINCON (( LPC_PINCON_TypeDef *) LPC_PINCON_BASE) +#define LPC_SSP0 (( LPC_SSP_TypeDef *) LPC_SSP0_BASE) +#define LPC_SSP1 (( LPC_SSP_TypeDef *) LPC_SSP1_BASE) +#define LPC_ADC (( LPC_ADC_TypeDef *) LPC_ADC_BASE) +#define LPC_DAC (( LPC_DAC_TypeDef *) LPC_DAC_BASE) +#define LPC_CANAF_RAM ((LPC_CANAF_RAM_TypeDef *) LPC_CANAF_RAM_BASE) +#define LPC_CANAF (( LPC_CANAF_TypeDef *) LPC_CANAF_BASE) +#define LPC_CANCR (( LPC_CANCR_TypeDef *) LPC_CANCR_BASE) +#define LPC_CAN1 (( LPC_CAN_TypeDef *) LPC_CAN1_BASE) +#define LPC_CAN2 (( LPC_CAN_TypeDef *) LPC_CAN2_BASE) +#define LPC_MCI (( LPC_MCI_TypeDef *) LPC_MCI_BASE) +#define LPC_EMAC (( LPC_EMAC_TypeDef *) LPC_EMAC_BASE) +#define LPC_GPDMA (( LPC_GPDMA_TypeDef *) LPC_GPDMA_BASE) +#define LPC_GPDMACH0 (( LPC_GPDMACH_TypeDef *) LPC_GPDMACH0_BASE) +#define LPC_GPDMACH1 (( LPC_GPDMACH_TypeDef *) LPC_GPDMACH1_BASE) +#define LPC_USB (( LPC_USB_TypeDef *) LPC_USB_BASE) +#define LPC_VIC (( LPC_VIC_TypeDef *) LPC_VIC_BASE) + +#ifdef __cplusplus + } +#endif + +#endif // __LPC23xx_H + diff --git a/targets/TARGET_NXP/TARGET_LPC23XX/device/TOOLCHAIN_ARM_MICRO/LPC2368.sct b/targets/TARGET_NXP/TARGET_LPC23XX/device/TOOLCHAIN_ARM_MICRO/LPC2368.sct new file mode 100644 index 00000000000..e2fdfdc09fd --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC23XX/device/TOOLCHAIN_ARM_MICRO/LPC2368.sct @@ -0,0 +1,24 @@ + +LR_IROM1 0x00000000 0x80000 { ; load region size_region + ER_IROM1 0x00000000 0x80000 { ; load address = execution address + *.o (RESET, +First) + *(InRoot$$Sections) + .ANY (+RO) + } + RW_IRAM1 0x40000120 0x7EE0 { ; RW data, inc space for realmonitor + .ANY (+RW +ZI) + } + RW_IRAM2 0x7FD00000 0x2000 { ; RW data, USB RAM + .ANY (AHBSRAM0) + } + RW_IRAM3 0x7FE00000 0x4000 { ; RW data, ETH RAM + .ANY (AHBSRAM1) + } + RW_IRAM4 0xE0038000 0x0800 { ; RW data, CAN RAM + .ANY (CANRAM) + } + RW_IRAM5 0xE0084000 0x0800 { ; RW data, RTC RAM + .ANY (RTCRAM) + } +} + diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/device/TOOLCHAIN_ARM_STD/sys.cpp b/targets/TARGET_NXP/TARGET_LPC23XX/device/TOOLCHAIN_ARM_MICRO/sys.cpp similarity index 83% rename from targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/device/TOOLCHAIN_ARM_STD/sys.cpp rename to targets/TARGET_NXP/TARGET_LPC23XX/device/TOOLCHAIN_ARM_MICRO/sys.cpp index 2438e9db8cb..2f1024ace8b 100644 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/device/TOOLCHAIN_ARM_STD/sys.cpp +++ b/targets/TARGET_NXP/TARGET_LPC23XX/device/TOOLCHAIN_ARM_MICRO/sys.cpp @@ -1,13 +1,13 @@ /* mbed Microcontroller Library - stackheap - * Copyright (C) 2009-2017 ARM Limited. All rights reserved. - * - * Setup a fixed single stack/heap memory model, + * Copyright (C) 2009-2011 ARM Limited. All rights reserved. + * + * Setup a fixed single stack/heap memory model, * between the top of the RW/ZI region and the stackpointer */ #ifdef __cplusplus extern "C" { -#endif +#endif #include #include @@ -28,4 +28,4 @@ extern __value_in_regs struct __initial_stackheap __user_setup_stackheap(uint32_ #ifdef __cplusplus } -#endif +#endif diff --git a/targets/TARGET_NXP/TARGET_LPC23XX/device/TOOLCHAIN_ARM_MICRO/vector_functions.S b/targets/TARGET_NXP/TARGET_LPC23XX/device/TOOLCHAIN_ARM_MICRO/vector_functions.S new file mode 100644 index 00000000000..462eb73c100 --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC23XX/device/TOOLCHAIN_ARM_MICRO/vector_functions.S @@ -0,0 +1,248 @@ +;/* mbed Microcontroller Library - InterruptIn +; * Copyright (c) 2006-2009 ARM Limited. All rights reserved. +; */ + +#line 1 "vector_functions.s" +; +; +; + +#line 1 "vector_defns.h" + + + + + + + + + +#line 21 "vector_defns.h" + + + + + + + + + + + + + + + + + + +#line 47 "vector_defns.h" + + +#line 58 "vector_defns.h" + + + + + + + + + + + + + + + + + + +#line 6 "vector_functions.s" + + + AREA VECFUNCS, CODE, READONLY + ARM + PRESERVE8 + + + + + + EXPORT __mbed_fiq [WEAK] + EXPORT __mbed_undef [WEAK] + EXPORT __mbed_prefetch_abort [WEAK] + EXPORT __mbed_data_abort [WEAK] + EXPORT __mbed_irq [WEAK] + EXPORT __mbed_swi [WEAK] + EXPORT __mbed_dcc_irq [WEAK] + EXPORT __mbed_reset [WEAK] + IMPORT __mbed_init_realmonitor + +; +; +__mbed_fiq + B __mbed_fiq + +; +; +__mbed_undef + LDR PC, =0x7fffffa0 + +; +; +__mbed_prefetch_abort + LDR PC, =0x7fffffb0 + +; +; +__mbed_data_abort + LDR PC, =0x7fffffc0 + +; +; +; +; +; +; +; +; +; +__mbed_irq + ; + MSR CPSR_c, #0x1F:OR:0x80:OR:0x40 + + ; + STMDB sp!, {r0-r3,r12,lr} + + ; + MOV r0, #0xFFFFFF00 + LDR r0, [r0] + + ; + MOV lr, pc + BX r0 + + ; + MOV r0, #0xFFFFFF00 + STR r0, [r0] ; + + ; + LDMFD sp!,{r0-r3,r12,lr} + + ; + MSR CPSR_c, #0x12:OR:0x80:OR:0x40 + + ; + SUBS pc, lr, #4 + +; +; +; +; +__mbed_swi + ; + ; + STMFD sp!, {a4, r4, ip, lr} + + ; + LDR r4, =0x40000040 + + ; + ; + LDR a4, =0x00940000 + LDR PC, =0x7ffff820 + +; +; +; +; +__mbed_dcc_irq + + ; + + ; + LDMFD sp!,{r0-r3,r12,lr} + + ; + MSR CPSR_c, #0x12:OR:0x80:OR:0x40 + + ; + + ; + SUB lr, lr, #4 ; + STMFD sp!, {ip,lr} ; + + ; + LDR LR, =0xfffff000 + STR LR, [LR, #0xf00] + + ; + ; + ; + ; + LDR PC, =0x7fffffe0 + +; +; __mbed_reset is called after reset +; we setup the stacks and realmonitor, then call Reset_Handler like on M3 + +; Reset Handler + +Reset_Handler PROC + EXPORT Reset_Handler [WEAK] + IMPORT SystemInit + IMPORT __main + LDR R0, =SystemInit + MOV LR, PC + BX R0 + LDR R0, =__main + BX R0 + ENDP + +__mbed_reset + + ; + + LDR R0, =(0x40000000 + 0x8000) + + ; + MSR CPSR_c, #0x1B:OR:0x80:OR:0x40 + MOV SP, R0 + SUB R0, R0, #0x00000040 + + ; + MSR CPSR_c, #0x17:OR:0x80:OR:0x40 + MOV SP, R0 + SUB R0, R0, #0x00000040 + + ; + MSR CPSR_c, #0x11:OR:0x80:OR:0x40 + MOV SP, R0 + SUB R0, R0, #0x00000000 + + ; + MSR CPSR_c, #0x12:OR:0x80:OR:0x40 + MOV SP, R0 + SUB R0, R0, #0x00000040 + + ; + MSR CPSR_c, #0x13:OR:0x80:OR:0x40 + MOV SP, R0 + SUB R0, R0, #0x00000040 + + ; + MSR CPSR_c, #0x10 + MOV SP, R0 + + ; + LDR R0, =__mbed_init_realmonitor + MOV LR, PC + BX R0 + + ; + LDR R0, =Reset_Handler + BX R0 + + + END diff --git a/targets/TARGET_NXP/TARGET_LPC23XX/device/TOOLCHAIN_ARM_MICRO/vector_table.S b/targets/TARGET_NXP/TARGET_LPC23XX/device/TOOLCHAIN_ARM_MICRO/vector_table.S new file mode 100644 index 00000000000..2fca3247281 --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC23XX/device/TOOLCHAIN_ARM_MICRO/vector_table.S @@ -0,0 +1,99 @@ +;/* mbed Microcontroller Library - InterruptIn +; * Copyright (c) 2006-2009 ARM Limited. All rights reserved. +; */ + +#line 1 "vector_table.s" +; + + + + +#line 1 "vector_defns.h" + + + + + + + + + +#line 21 "vector_defns.h" + + + + + + + + + + + + + + + + + + +#line 47 "vector_defns.h" + + +#line 58 "vector_defns.h" + + + + + + + + + + + + + + + + + + +#line 7 "vector_table.s" + +; + + + AREA RESET, CODE, READONLY + ARM +; ENTRY + PRESERVE8 + + + + + +; EXPORT __main + IMPORT __mbed_reset + IMPORT __mbed_undef + IMPORT __mbed_swi + IMPORT __mbed_prefetch_abort + IMPORT __mbed_data_abort + IMPORT __mbed_irq + IMPORT __mbed_fiq + +; + + +;__main + LDR PC, =__mbed_reset + LDR PC, =__mbed_undef + LDR PC, =__mbed_swi + LDR PC, =__mbed_prefetch_abort + LDR PC, =__mbed_data_abort + NOP ; + LDR PC, =__mbed_irq + LDR PC, =__mbed_fiq + + + END diff --git a/targets/TARGET_NXP/TARGET_LPC23XX/device/TOOLCHAIN_ARM_STD/LPC2368.sct b/targets/TARGET_NXP/TARGET_LPC23XX/device/TOOLCHAIN_ARM_STD/LPC2368.sct new file mode 100644 index 00000000000..e2fdfdc09fd --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC23XX/device/TOOLCHAIN_ARM_STD/LPC2368.sct @@ -0,0 +1,24 @@ + +LR_IROM1 0x00000000 0x80000 { ; load region size_region + ER_IROM1 0x00000000 0x80000 { ; load address = execution address + *.o (RESET, +First) + *(InRoot$$Sections) + .ANY (+RO) + } + RW_IRAM1 0x40000120 0x7EE0 { ; RW data, inc space for realmonitor + .ANY (+RW +ZI) + } + RW_IRAM2 0x7FD00000 0x2000 { ; RW data, USB RAM + .ANY (AHBSRAM0) + } + RW_IRAM3 0x7FE00000 0x4000 { ; RW data, ETH RAM + .ANY (AHBSRAM1) + } + RW_IRAM4 0xE0038000 0x0800 { ; RW data, CAN RAM + .ANY (CANRAM) + } + RW_IRAM5 0xE0084000 0x0800 { ; RW data, RTC RAM + .ANY (RTCRAM) + } +} + diff --git a/targets/TARGET_NXP/TARGET_LPC23XX/device/TOOLCHAIN_ARM_STD/sys.cpp b/targets/TARGET_NXP/TARGET_LPC23XX/device/TOOLCHAIN_ARM_STD/sys.cpp new file mode 100644 index 00000000000..2f1024ace8b --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC23XX/device/TOOLCHAIN_ARM_STD/sys.cpp @@ -0,0 +1,31 @@ +/* mbed Microcontroller Library - stackheap + * Copyright (C) 2009-2011 ARM Limited. All rights reserved. + * + * Setup a fixed single stack/heap memory model, + * between the top of the RW/ZI region and the stackpointer + */ + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include + +extern char Image$$RW_IRAM1$$ZI$$Limit[]; + +extern __value_in_regs struct __initial_stackheap __user_setup_stackheap(uint32_t R0, uint32_t R1, uint32_t R2, uint32_t R3) { + uint32_t zi_limit = (uint32_t)Image$$RW_IRAM1$$ZI$$Limit; + uint32_t sp_limit = __current_sp(); + + zi_limit = (zi_limit + 7) & ~0x7; // ensure zi_limit is 8-byte aligned + + struct __initial_stackheap r; + r.heap_base = zi_limit; + r.heap_limit = sp_limit; + return r; +} + +#ifdef __cplusplus +} +#endif diff --git a/targets/TARGET_NXP/TARGET_LPC23XX/device/TOOLCHAIN_ARM_STD/vector_functions.S b/targets/TARGET_NXP/TARGET_LPC23XX/device/TOOLCHAIN_ARM_STD/vector_functions.S new file mode 100644 index 00000000000..462eb73c100 --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC23XX/device/TOOLCHAIN_ARM_STD/vector_functions.S @@ -0,0 +1,248 @@ +;/* mbed Microcontroller Library - InterruptIn +; * Copyright (c) 2006-2009 ARM Limited. All rights reserved. +; */ + +#line 1 "vector_functions.s" +; +; +; + +#line 1 "vector_defns.h" + + + + + + + + + +#line 21 "vector_defns.h" + + + + + + + + + + + + + + + + + + +#line 47 "vector_defns.h" + + +#line 58 "vector_defns.h" + + + + + + + + + + + + + + + + + + +#line 6 "vector_functions.s" + + + AREA VECFUNCS, CODE, READONLY + ARM + PRESERVE8 + + + + + + EXPORT __mbed_fiq [WEAK] + EXPORT __mbed_undef [WEAK] + EXPORT __mbed_prefetch_abort [WEAK] + EXPORT __mbed_data_abort [WEAK] + EXPORT __mbed_irq [WEAK] + EXPORT __mbed_swi [WEAK] + EXPORT __mbed_dcc_irq [WEAK] + EXPORT __mbed_reset [WEAK] + IMPORT __mbed_init_realmonitor + +; +; +__mbed_fiq + B __mbed_fiq + +; +; +__mbed_undef + LDR PC, =0x7fffffa0 + +; +; +__mbed_prefetch_abort + LDR PC, =0x7fffffb0 + +; +; +__mbed_data_abort + LDR PC, =0x7fffffc0 + +; +; +; +; +; +; +; +; +; +__mbed_irq + ; + MSR CPSR_c, #0x1F:OR:0x80:OR:0x40 + + ; + STMDB sp!, {r0-r3,r12,lr} + + ; + MOV r0, #0xFFFFFF00 + LDR r0, [r0] + + ; + MOV lr, pc + BX r0 + + ; + MOV r0, #0xFFFFFF00 + STR r0, [r0] ; + + ; + LDMFD sp!,{r0-r3,r12,lr} + + ; + MSR CPSR_c, #0x12:OR:0x80:OR:0x40 + + ; + SUBS pc, lr, #4 + +; +; +; +; +__mbed_swi + ; + ; + STMFD sp!, {a4, r4, ip, lr} + + ; + LDR r4, =0x40000040 + + ; + ; + LDR a4, =0x00940000 + LDR PC, =0x7ffff820 + +; +; +; +; +__mbed_dcc_irq + + ; + + ; + LDMFD sp!,{r0-r3,r12,lr} + + ; + MSR CPSR_c, #0x12:OR:0x80:OR:0x40 + + ; + + ; + SUB lr, lr, #4 ; + STMFD sp!, {ip,lr} ; + + ; + LDR LR, =0xfffff000 + STR LR, [LR, #0xf00] + + ; + ; + ; + ; + LDR PC, =0x7fffffe0 + +; +; __mbed_reset is called after reset +; we setup the stacks and realmonitor, then call Reset_Handler like on M3 + +; Reset Handler + +Reset_Handler PROC + EXPORT Reset_Handler [WEAK] + IMPORT SystemInit + IMPORT __main + LDR R0, =SystemInit + MOV LR, PC + BX R0 + LDR R0, =__main + BX R0 + ENDP + +__mbed_reset + + ; + + LDR R0, =(0x40000000 + 0x8000) + + ; + MSR CPSR_c, #0x1B:OR:0x80:OR:0x40 + MOV SP, R0 + SUB R0, R0, #0x00000040 + + ; + MSR CPSR_c, #0x17:OR:0x80:OR:0x40 + MOV SP, R0 + SUB R0, R0, #0x00000040 + + ; + MSR CPSR_c, #0x11:OR:0x80:OR:0x40 + MOV SP, R0 + SUB R0, R0, #0x00000000 + + ; + MSR CPSR_c, #0x12:OR:0x80:OR:0x40 + MOV SP, R0 + SUB R0, R0, #0x00000040 + + ; + MSR CPSR_c, #0x13:OR:0x80:OR:0x40 + MOV SP, R0 + SUB R0, R0, #0x00000040 + + ; + MSR CPSR_c, #0x10 + MOV SP, R0 + + ; + LDR R0, =__mbed_init_realmonitor + MOV LR, PC + BX R0 + + ; + LDR R0, =Reset_Handler + BX R0 + + + END diff --git a/targets/TARGET_NXP/TARGET_LPC23XX/device/TOOLCHAIN_ARM_STD/vector_table.S b/targets/TARGET_NXP/TARGET_LPC23XX/device/TOOLCHAIN_ARM_STD/vector_table.S new file mode 100644 index 00000000000..2fca3247281 --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC23XX/device/TOOLCHAIN_ARM_STD/vector_table.S @@ -0,0 +1,99 @@ +;/* mbed Microcontroller Library - InterruptIn +; * Copyright (c) 2006-2009 ARM Limited. All rights reserved. +; */ + +#line 1 "vector_table.s" +; + + + + +#line 1 "vector_defns.h" + + + + + + + + + +#line 21 "vector_defns.h" + + + + + + + + + + + + + + + + + + +#line 47 "vector_defns.h" + + +#line 58 "vector_defns.h" + + + + + + + + + + + + + + + + + + +#line 7 "vector_table.s" + +; + + + AREA RESET, CODE, READONLY + ARM +; ENTRY + PRESERVE8 + + + + + +; EXPORT __main + IMPORT __mbed_reset + IMPORT __mbed_undef + IMPORT __mbed_swi + IMPORT __mbed_prefetch_abort + IMPORT __mbed_data_abort + IMPORT __mbed_irq + IMPORT __mbed_fiq + +; + + +;__main + LDR PC, =__mbed_reset + LDR PC, =__mbed_undef + LDR PC, =__mbed_swi + LDR PC, =__mbed_prefetch_abort + LDR PC, =__mbed_data_abort + NOP ; + LDR PC, =__mbed_irq + LDR PC, =__mbed_fiq + + + END diff --git a/targets/TARGET_NXP/TARGET_LPC23XX/device/TOOLCHAIN_GCC_ARM/LPC2368.ld b/targets/TARGET_NXP/TARGET_LPC23XX/device/TOOLCHAIN_GCC_ARM/LPC2368.ld new file mode 100644 index 00000000000..503141fd5fc --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC23XX/device/TOOLCHAIN_GCC_ARM/LPC2368.ld @@ -0,0 +1,208 @@ +OUTPUT_FORMAT("elf32-littlearm", "elf32-bigarm", "elf32-littlearm") +OUTPUT_ARCH(arm) +ENTRY(vectors) + +/* Memory Definitions: */ +MEMORY +{ + Flash (rx) : ORIGIN = 0x00000000, LENGTH = 512k + Ram (rwx) : ORIGIN = 0x40000000, LENGTH = 32k + UsbRam (rw) : ORIGIN = 0x7FD00000, LENGTH = 8k + EthRam (rw) : ORIGIN = 0x7FE00000, LENGTH = 16k + CanRam (rw) : ORIGIN = 0xE0038000, LENGTH = 2k + BatRam (rw) : ORIGIN = 0xE0084000, LENGTH = 2k +} + +/* Stack sizes: */ +UND_Stack_Size = 16; +SVC_Stack_Size = 512; +ABT_Stack_Size = 16; +FIQ_Stack_Size = 16; +IRQ_Stack_Size = 256; +Stack_Size_Total = UND_Stack_Size + SVC_Stack_Size + ABT_Stack_Size + FIQ_Stack_Size + IRQ_Stack_Size; + +/* Stack tops for each mode: */ +__und_stack_top__ = __stacks_top__; +__abt_stack_top__ = __und_stack_top__ - UND_Stack_Size ; +__fiq_stack_top__ = __abt_stack_top__ - ABT_Stack_Size ; +__irq_stack_top__ = __fiq_stack_top__ - FIQ_Stack_Size ; +__svc_stack_top__ = __irq_stack_top__ - IRQ_Stack_Size ; + +/* C-accessible symbols for memory address ranges: */ +__FLASH_segment_start__ = ORIGIN( Flash ); +__FLASH_segment_end__ = ORIGIN( Flash ) + LENGTH( Flash ); +__SRAM_segment_start__ = ORIGIN( Ram ); +__SRAM_segment_end__ = ORIGIN( Ram ) + LENGTH( Ram ); + +/* Stacks (full descending) at top of RAM, grows downward: + * + * __stack_min__ is used by the malloc implementation to ensure heap never collides + * with stack (assuming stack never grows beyond Stack_Size_Total in length) */ +__stacks_top__ = __SRAM_segment_end__; +__stacks_min__ = __SRAM_segment_end__ - Stack_Size_Total; + +SECTIONS +{ + /* first section is .text which is used for code */ + __text_start__ = . ; + .text : { + __privileged_code_start__ = . ; + KEEP( *( .vectors ) ) + *( .privileged_code ) + + __privileged_code_end__ = .; + + *( .text .text.* .gnu.linkonce.t.* ) + *( .plt ) + *( .gnu.warning ) + *( .glue_7t ) *( .glue_7 ) *( .vfp11_veneer ) + + *( .rodata .rodata.* .gnu.linkonce.r.* ) + + *(.ARM.extab* .gnu.linkonce.armextab.*) + *(.gcc_except_table) + *(.eh_frame_hdr) + *(.eh_frame) + + . = ALIGN( 4 ) ; + KEEP( *( .init ) ) + . = ALIGN( 4 ) ; + __preinit_array_start = . ; + KEEP( *( .preinit_array ) ) + __preinit_array_end = . ; + . = ALIGN( 4 ) ; + __init_array_start = . ; + KEEP( *( SORT( .init_array.* ) ) ) + KEEP( *( .init_array ) ) + __init_array_end = . ; + + . = ALIGN( 4 ) ; + KEEP( *crtbegin.o( .ctors ) ) + KEEP( *( EXCLUDE_FILE( *crtend.o ) .ctors ) ) + KEEP( *( SORT( .ctors.* ) ) ) + KEEP( *crtend.o( .ctors ) ) + + . = ALIGN( 4 ) ; + KEEP( *( .fini ) ) + . = ALIGN( 4 ) ; + __fini_array_start = . ; + KEEP( *( .fini_array ) ) + KEEP( *( SORT( .fini_array.* ) ) ) + __fini_array_end = . ; + + KEEP( *crtbegin.o( .dtors ) ) + KEEP( *( EXCLUDE_FILE( *crtend.o ) .dtors ) ) + KEEP( *( SORT( .dtors.* ) ) ) + KEEP( *crtend.o( .dtors ) ) + + } >Flash + + __exidx_start = . ; + .ARM.exidx : { + *( .ARM.exidx* .gnu.linkonce.armexidx.* ) + } >Flash + __exidx_end = . ; + + .text.align : { . = ALIGN( 8 ) ; } >Flash /* Alignment schenanigans */ + __text_end__ = . ; + + /* .bss section -- used for uninitialized data */ + /* Located at the start of RAM */ + .bss (NOLOAD) : { + __bss_start__ = . ; + *crt0.o( .ram_vectors ) + + __user_bss_start__ = . ; + *( .user_bss ) + __user_bss_end__ = . ; + + *( .shbss ) + *( .bss .bss.* .gnu.linkonce.b.* ) + *( COMMON ) + *( .ram.b ) + . = ALIGN( 8 ) ; + + __bss_end__ = . ; + } >Ram AT>Flash + + /* .data section -- used for initialized data */ + .data : { + __data_start__ = . ; + KEEP( *( .jcr ) ) + *( .got.plt ) *( .got ) + *( .shdata ) + *( .data .data.* .gnu.linkonce.d.* ) + *( .ram ) + . = ALIGN( 8 ) ; + __data_end__ = . ; + } >Ram AT>Flash + + __data_init_start__ = LOADADDR( .data ) ; + + /* Heap starts here and grows up in memory */ + . = ALIGN( 8 ) ; + __heap_start__ = . ; + end = . ; + __end__ = . ; + + .stab 0 (NOLOAD) : { *(.stab) } + .stabstr 0 (NOLOAD) : { *(.stabstr) } + /* DWARF debug sections. */ + /* Symbols in the DWARF debugging sections are relative to the */ + /* beginning of the section so we begin them at 0. */ + /* DWARF 1 */ + .debug 0 : { *(.debug) } + .line 0 : { *(.line) } + /* GNU DWARF 1 extensions */ + .debug_srcinfo 0 : { *(.debug_srcinfo) } + .debug_sfnames 0 : { *(.debug_sfnames) } + /* DWARF 1.1 and DWARF 2 */ + .debug_aranges 0 : { *(.debug_aranges) } + .debug_pubnames 0 : { *(.debug_pubnames) } + /* DWARF 2 */ + .debug_info 0 : { *(.debug_info .gnu.linkonce.wi.*) } + .debug_abbrev 0 : { *(.debug_abbrev) } + .debug_line 0 : { *(.debug_line) } + .debug_frame 0 : { *(.debug_frame) } + .debug_str 0 : { *(.debug_str) } + .debug_loc 0 : { *(.debug_loc) } + .debug_macinfo 0 : { *(.debug_macinfo) } + /* SGI/MIPS DWARF 2 extensions */ + .debug_weaknames 0 : { *(.debug_weaknames) } + .debug_funcnames 0 : { *(.debug_funcnames) } + .debug_typenames 0 : { *(.debug_typenames) } + .debug_varnames 0 : { *(.debug_varnames) } + /* DWARF 3 */ + .debug_pubtypes 0 : { *(.debug_pubtypes) } + .debug_ranges 0 : { *(.debug_ranges) } + + .note.gnu.arm.ident 0 : { KEEP( *( .note.gnu.arm.ident ) ) } + .ARM.attributes 0 : { + KEEP( *( .ARM.attributes ) ) + KEEP( *( .gnu.attributes ) ) + } + /DISCARD/ : { *( .note.GNU-stack ) } + + /* C data can be defined as being in special purpose RAMs using + * __attribute__ ((section ("ethram"))) for example. */ + .usbram (NOLOAD): + { + *( .usbram ) + *( .usbram.* ) + } > UsbRam + .ethram (NOLOAD): + { + *( .ethram ) + *( .ethram.* ) + } > EthRam + .canram (NOLOAD): + { + *( .canram ) + *( .canram.* ) + } > CanRam + .batram (NOLOAD): + { + *( .batram ) + *( .batram.* ) + } > BatRam +} diff --git a/targets/TARGET_NXP/TARGET_LPC23XX/device/TOOLCHAIN_GCC_ARM/vector_functions.S b/targets/TARGET_NXP/TARGET_LPC23XX/device/TOOLCHAIN_GCC_ARM/vector_functions.S new file mode 100644 index 00000000000..a3803a0f2be --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC23XX/device/TOOLCHAIN_GCC_ARM/vector_functions.S @@ -0,0 +1,148 @@ +/* .include "vector_defns.h" */ + + + +.section .privileged_code, "ax" +.arm + + +.weak __mbed_fiq +.weak __mbed_undef +.weak __mbed_prefetch_abort +.weak __mbed_data_abort +.weak __mbed_irq +.weak __mbed_swi +.weak __mbed_dcc_irq +.weak __mbed_reset +.global __mbed_init_realmonitor +/* .global __mbed_init */ + + + + +__mbed_fiq: + B __mbed_fiq +__mbed_undef: + LDR PC, =0x7fffffa0 +__mbed_prefetch_abort: + LDR PC, =0x7fffffb0 +__mbed_data_abort: + LDR PC, =0x7fffffc0 +__mbed_irq: + MSR CPSR_c, #0x1F|0x80|0x40 + + STMDB sp!, {r0-r3,r12,lr} + + MOV r0, #0xFFFFFF00 + LDR r0, [r0] + + MOV lr, pc + BX r0 + + MOV r0, #0xFFFFFF00 + STR r0, [r0] + + LDMFD sp!,{r0-r3,r12,lr} + + MSR CPSR_c, #0x12|0x80|0x40 + + SUBS pc, lr, #4 +__mbed_swi: + STMFD sp!, {a4, r4, ip, lr} + + LDR r4, =0x40000040 + + LDR a4, =0x00940000 + LDR PC, =0x7ffff820 +__mbed_dcc_irq: + LDMFD sp!,{r0-r3,r12,lr} + + MSR CPSR_c, #0x12|0x80|0x40 + + SUB lr, lr, #4 + STMFD sp!, {ip,lr} + + LDR LR, =0xfffff000 + STR LR, [LR, #0xf00] + + LDR PC, =0x7fffffe0 +/* + __mbed_reset is called after reset + we setup the stacks and realmonitor, then call Reset_Handler like on M3 +*/ + +.section .text, "ax" +.arm +.global Reset_handler +Reset_Handler: + .extern __libc_init_array + .extern SystemInit + LDR R0, =SystemInit + MOV LR, PC + BX R0 + + LDR R0, =__libc_init_array + MOV LR, PC + BX R0 + + LDR R0, =main + BX R0 + +__mbed_reset: + LDR R0, =( __SRAM_segment_end__ ) + + MSR CPSR_c, #0x1B|0x80|0x40 + MOV SP, R0 + SUB R0, R0, #0x00000040 + + MSR CPSR_c, #0x17|0x80|0x40 + MOV SP, R0 + SUB R0, R0, #0x00000040 + + MSR CPSR_c, #0x11|0x80|0x40 + MOV SP, R0 + SUB R0, R0, #0x00000000 + + MSR CPSR_c, #0x12|0x80|0x40 + MOV SP, R0 + SUB R0, R0, #0x00000040 + + MSR CPSR_c, #0x13|0x80|0x40 + MOV SP, R0 + SUB R0, R0, #0x00000040 + + MSR CPSR_c, #0x10 + MOV SP, R0 + +/* Relocate .data section (Copy from ROM to RAM) */ + LDR R1, =__text_end__ /* _etext */ + LDR R2, =__data_start__ /* _data */ + LDR R3, =__data_end__ /* _edata */ + CMP R2, R3 + BEQ DataIsEmpty +LoopRel: CMP R2, R3 + LDRLO R0, [R1], #4 + STRLO R0, [R2], #4 + BLO LoopRel +DataIsEmpty: + +/* Clear .bss section (Zero init) */ + MOV R0, #0 + LDR R1, =__bss_start__ + LDR R2, =__bss_end__ + CMP R1,R2 + BEQ BSSIsEmpty +LoopZI: CMP R1, R2 + STRLO R0, [R1], #4 + BLO LoopZI +BSSIsEmpty: + + +/* Init realmonitor */ + LDR R0, =__mbed_init_realmonitor + MOV LR, PC + BX R0 + +/* Go to Reset_Handler */ + LDR R0, =Reset_Handler + BX R0 diff --git a/targets/TARGET_NXP/TARGET_LPC23XX/device/TOOLCHAIN_GCC_ARM/vector_table.S b/targets/TARGET_NXP/TARGET_LPC23XX/device/TOOLCHAIN_GCC_ARM/vector_table.S new file mode 100644 index 00000000000..d797c3794d1 --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC23XX/device/TOOLCHAIN_GCC_ARM/vector_table.S @@ -0,0 +1,45 @@ +# 1 "vector_table.s" +# 1 "" +# 1 "" +# 1 "vector_table.s" +; + + + + +# 1 "vector_defns.h" 1 +# 7 "vector_table.s" 2 + +; + + + + + + + + .section .vectors, "ax" + .arm + + + .global __main + .global __mbed_reset + .global __mbed_undef + .global __mbed_swi + .global __mbed_prefetch_abort + .global __mbed_data_abort + .global __mbed_irq + .global __mbed_fiq + +; + + +_start: + LDR PC, =__mbed_reset + LDR PC, =__mbed_undef + LDR PC, =__mbed_swi + LDR PC, =__mbed_prefetch_abort + LDR PC, =__mbed_data_abort + NOP ; + LDR PC, =__mbed_irq + LDR PC, =__mbed_fiq diff --git a/targets/TARGET_NXP/TARGET_LPC23XX/device/TOOLCHAIN_GCC_CR/LPC2368.ld b/targets/TARGET_NXP/TARGET_LPC23XX/device/TOOLCHAIN_GCC_CR/LPC2368.ld new file mode 100644 index 00000000000..29c738fbf5f --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC23XX/device/TOOLCHAIN_GCC_CR/LPC2368.ld @@ -0,0 +1,210 @@ +OUTPUT_FORMAT("elf32-littlearm", "elf32-bigarm", "elf32-littlearm") +OUTPUT_ARCH(arm) +ENTRY(vectors) + +GROUP( libgcc.a libc.a libm.a libcr_newlib_nohost.a crti.o crtn.o crtbegin.o crtend.o ) + +/* Memory Definitions: */ +MEMORY +{ + Flash (rx) : ORIGIN = 0x00000000, LENGTH = 512k + Ram (rwx) : ORIGIN = 0x40000000, LENGTH = 32k + UsbRam (rw) : ORIGIN = 0x7FD00000, LENGTH = 8k + EthRam (rw) : ORIGIN = 0x7FE00000, LENGTH = 16k + CanRam (rw) : ORIGIN = 0xE0038000, LENGTH = 2k + BatRam (rw) : ORIGIN = 0xE0084000, LENGTH = 2k +} + +/* Stack sizes: */ +UND_Stack_Size = 16; +SVC_Stack_Size = 512; +ABT_Stack_Size = 16; +FIQ_Stack_Size = 16; +IRQ_Stack_Size = 256; +Stack_Size_Total = UND_Stack_Size + SVC_Stack_Size + ABT_Stack_Size + FIQ_Stack_Size + IRQ_Stack_Size; + +/* Stack tops for each mode: */ +__und_stack_top__ = __stacks_top__; +__abt_stack_top__ = __und_stack_top__ - UND_Stack_Size ; +__fiq_stack_top__ = __abt_stack_top__ - ABT_Stack_Size ; +__irq_stack_top__ = __fiq_stack_top__ - FIQ_Stack_Size ; +__svc_stack_top__ = __irq_stack_top__ - IRQ_Stack_Size ; + +/* C-accessible symbols for memory address ranges: */ +__FLASH_segment_start__ = ORIGIN( Flash ); +__FLASH_segment_end__ = ORIGIN( Flash ) + LENGTH( Flash ); +__SRAM_segment_start__ = ORIGIN( Ram ); +__SRAM_segment_end__ = ORIGIN( Ram ) + LENGTH( Ram ); + +/* Stacks (full descending) at top of RAM, grows downward: + * + * __stack_min__ is used by the malloc implementation to ensure heap never collides + * with stack (assuming stack never grows beyond Stack_Size_Total in length) */ +__stacks_top__ = __SRAM_segment_end__; +__stacks_min__ = __SRAM_segment_end__ - Stack_Size_Total; + +SECTIONS +{ + /* first section is .text which is used for code */ + __text_start__ = . ; + .text : { + __privileged_code_start__ = . ; + KEEP( *( .vectors ) ) + *( .privileged_code ) + + __privileged_code_end__ = .; + + *( .text .text.* .gnu.linkonce.t.* ) + *( .plt ) + *( .gnu.warning ) + *( .glue_7t ) *( .glue_7 ) *( .vfp11_veneer ) + + *( .rodata .rodata.* .gnu.linkonce.r.* ) + + *(.ARM.extab* .gnu.linkonce.armextab.*) + *(.gcc_except_table) + *(.eh_frame_hdr) + *(.eh_frame) + + . = ALIGN( 4 ) ; + KEEP( *( .init ) ) + . = ALIGN( 4 ) ; + __preinit_array_start = . ; + KEEP( *( .preinit_array ) ) + __preinit_array_end = . ; + . = ALIGN( 4 ) ; + __init_array_start = . ; + KEEP( *( SORT( .init_array.* ) ) ) + KEEP( *( .init_array ) ) + __init_array_end = . ; + + . = ALIGN( 4 ) ; + KEEP( *crtbegin.o( .ctors ) ) + KEEP( *( EXCLUDE_FILE( *crtend.o ) .ctors ) ) + KEEP( *( SORT( .ctors.* ) ) ) + KEEP( *crtend.o( .ctors ) ) + + . = ALIGN( 4 ) ; + KEEP( *( .fini ) ) + . = ALIGN( 4 ) ; + __fini_array_start = . ; + KEEP( *( .fini_array ) ) + KEEP( *( SORT( .fini_array.* ) ) ) + __fini_array_end = . ; + + KEEP( *crtbegin.o( .dtors ) ) + KEEP( *( EXCLUDE_FILE( *crtend.o ) .dtors ) ) + KEEP( *( SORT( .dtors.* ) ) ) + KEEP( *crtend.o( .dtors ) ) + + } >Flash + + __exidx_start = . ; + .ARM.exidx : { + *( .ARM.exidx* .gnu.linkonce.armexidx.* ) + } >Flash + __exidx_end = . ; + + .text.align : { . = ALIGN( 8 ) ; } >Flash /* Alignment schenanigans */ + __text_end__ = . ; + + /* .bss section -- used for uninitialized data */ + /* Located at the start of RAM */ + .bss (NOLOAD) : { + __bss_start__ = . ; + *crt0.o( .ram_vectors ) + + __user_bss_start__ = . ; + *( .user_bss ) + __user_bss_end__ = . ; + + *( .shbss ) + *( .bss .bss.* .gnu.linkonce.b.* ) + *( COMMON ) + *( .ram.b ) + . = ALIGN( 8 ) ; + + __bss_end__ = . ; + } >Ram AT>Flash + + /* .data section -- used for initialized data */ + .data : { + __data_start__ = . ; + KEEP( *( .jcr ) ) + *( .got.plt ) *( .got ) + *( .shdata ) + *( .data .data.* .gnu.linkonce.d.* ) + *( .ram ) + . = ALIGN( 8 ) ; + __data_end__ = . ; + } >Ram AT>Flash + + __data_init_start__ = LOADADDR( .data ) ; + + /* Heap starts here and grows up in memory */ + . = ALIGN( 8 ) ; + __heap_start__ = . ; + _pvHeapStart = . ; + end = . ; + + .stab 0 (NOLOAD) : { *(.stab) } + .stabstr 0 (NOLOAD) : { *(.stabstr) } + /* DWARF debug sections. */ + /* Symbols in the DWARF debugging sections are relative to the */ + /* beginning of the section so we begin them at 0. */ + /* DWARF 1 */ + .debug 0 : { *(.debug) } + .line 0 : { *(.line) } + /* GNU DWARF 1 extensions */ + .debug_srcinfo 0 : { *(.debug_srcinfo) } + .debug_sfnames 0 : { *(.debug_sfnames) } + /* DWARF 1.1 and DWARF 2 */ + .debug_aranges 0 : { *(.debug_aranges) } + .debug_pubnames 0 : { *(.debug_pubnames) } + /* DWARF 2 */ + .debug_info 0 : { *(.debug_info .gnu.linkonce.wi.*) } + .debug_abbrev 0 : { *(.debug_abbrev) } + .debug_line 0 : { *(.debug_line) } + .debug_frame 0 : { *(.debug_frame) } + .debug_str 0 : { *(.debug_str) } + .debug_loc 0 : { *(.debug_loc) } + .debug_macinfo 0 : { *(.debug_macinfo) } + /* SGI/MIPS DWARF 2 extensions */ + .debug_weaknames 0 : { *(.debug_weaknames) } + .debug_funcnames 0 : { *(.debug_funcnames) } + .debug_typenames 0 : { *(.debug_typenames) } + .debug_varnames 0 : { *(.debug_varnames) } + /* DWARF 3 */ + .debug_pubtypes 0 : { *(.debug_pubtypes) } + .debug_ranges 0 : { *(.debug_ranges) } + + .note.gnu.arm.ident 0 : { KEEP( *( .note.gnu.arm.ident ) ) } + .ARM.attributes 0 : { + KEEP( *( .ARM.attributes ) ) + KEEP( *( .gnu.attributes ) ) + } + /DISCARD/ : { *( .note.GNU-stack ) } + + /* C data can be defined as being in special purpose RAMs using + * __attribute__ ((section ("ethram"))) for example. */ + .usbram (NOLOAD): + { + *( .usbram ) + *( .usbram.* ) + } > UsbRam + .ethram (NOLOAD): + { + *( .ethram ) + *( .ethram.* ) + } > EthRam + .canram (NOLOAD): + { + *( .canram ) + *( .canram.* ) + } > CanRam + .batram (NOLOAD): + { + *( .batram ) + *( .batram.* ) + } > BatRam +} diff --git a/targets/TARGET_NXP/TARGET_LPC23XX/device/TOOLCHAIN_GCC_CR/vector_functions.S b/targets/TARGET_NXP/TARGET_LPC23XX/device/TOOLCHAIN_GCC_CR/vector_functions.S new file mode 100644 index 00000000000..6e99ec8e08e --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC23XX/device/TOOLCHAIN_GCC_CR/vector_functions.S @@ -0,0 +1,149 @@ +/* .include "vector_defns.h" */ + + + +.section .privileged_code, "ax" +.arm + + +.weak __mbed_fiq +.weak __mbed_undef +.weak __mbed_prefetch_abort +.weak __mbed_data_abort +.weak __mbed_irq +.weak __mbed_swi +.weak __mbed_dcc_irq +.weak __mbed_reset +.global __mbed_init_realmonitor +/* .global __mbed_init */ + + + + +__mbed_fiq: + B __mbed_fiq +__mbed_undef: + LDR PC, =0x7fffffa0 +__mbed_prefetch_abort: + LDR PC, =0x7fffffb0 +__mbed_data_abort: + LDR PC, =0x7fffffc0 +__mbed_irq: + MSR CPSR_c, #0x1F|0x80|0x40 + + STMDB sp!, {r0-r3,r12,lr} + + MOV r0, #0xFFFFFF00 + LDR r0, [r0] + + MOV lr, pc + BX r0 + + MOV r0, #0xFFFFFF00 + STR r0, [r0] + + LDMFD sp!,{r0-r3,r12,lr} + + MSR CPSR_c, #0x12|0x80|0x40 + + SUBS pc, lr, #4 +__mbed_swi: + STMFD sp!, {a4, r4, ip, lr} + + LDR r4, =0x40000040 + + LDR a4, =0x00940000 + LDR PC, =0x7ffff820 +__mbed_dcc_irq: + LDMFD sp!,{r0-r3,r12,lr} + + MSR CPSR_c, #0x12|0x80|0x40 + + SUB lr, lr, #4 + STMFD sp!, {ip,lr} + + LDR LR, =0xfffff000 + STR LR, [LR, #0xf00] + + LDR PC, =0x7fffffe0 +/* + __mbed_reset is called after reset + we setup the stacks and realmonitor, then call Reset_Handler like on M3 +*/ + +.section .text, "ax" +.arm +.global Reset_handler +Reset_Handler: + .extern __libc_init_array + .extern SystemInit + .extern __wrap_main + LDR R0, =SystemInit + MOV LR, PC + BX R0 + + LDR R0, =__libc_init_array + MOV LR, PC + BX R0 + + LDR R0, =__wrap_main + BX R0 + +__mbed_reset: + LDR R0, =( __SRAM_segment_end__ ) + + MSR CPSR_c, #0x1B|0x80|0x40 + MOV SP, R0 + SUB R0, R0, #0x00000040 + + MSR CPSR_c, #0x17|0x80|0x40 + MOV SP, R0 + SUB R0, R0, #0x00000040 + + MSR CPSR_c, #0x11|0x80|0x40 + MOV SP, R0 + SUB R0, R0, #0x00000000 + + MSR CPSR_c, #0x12|0x80|0x40 + MOV SP, R0 + SUB R0, R0, #0x00000040 + + MSR CPSR_c, #0x13|0x80|0x40 + MOV SP, R0 + SUB R0, R0, #0x00000040 + + MSR CPSR_c, #0x10 + MOV SP, R0 + +/* Relocate .data section (Copy from ROM to RAM) */ + LDR R1, =__text_end__ /* _etext */ + LDR R2, =__data_start__ /* _data */ + LDR R3, =__data_end__ /* _edata */ + CMP R2, R3 + BEQ DataIsEmpty +LoopRel: CMP R2, R3 + LDRLO R0, [R1], #4 + STRLO R0, [R2], #4 + BLO LoopRel +DataIsEmpty: + +/* Clear .bss section (Zero init) */ + MOV R0, #0 + LDR R1, =__bss_start__ + LDR R2, =__bss_end__ + CMP R1,R2 + BEQ BSSIsEmpty +LoopZI: CMP R1, R2 + STRLO R0, [R1], #4 + BLO LoopZI +BSSIsEmpty: + + +/* Init realmonitor */ + LDR R0, =__mbed_init_realmonitor + MOV LR, PC + BX R0 + +/* Go to Reset_Handler */ + LDR R0, =Reset_Handler + BX R0 diff --git a/targets/TARGET_NXP/TARGET_LPC23XX/device/TOOLCHAIN_GCC_CR/vector_table.S b/targets/TARGET_NXP/TARGET_LPC23XX/device/TOOLCHAIN_GCC_CR/vector_table.S new file mode 100644 index 00000000000..d797c3794d1 --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC23XX/device/TOOLCHAIN_GCC_CR/vector_table.S @@ -0,0 +1,45 @@ +# 1 "vector_table.s" +# 1 "" +# 1 "" +# 1 "vector_table.s" +; + + + + +# 1 "vector_defns.h" 1 +# 7 "vector_table.s" 2 + +; + + + + + + + + .section .vectors, "ax" + .arm + + + .global __main + .global __mbed_reset + .global __mbed_undef + .global __mbed_swi + .global __mbed_prefetch_abort + .global __mbed_data_abort + .global __mbed_irq + .global __mbed_fiq + +; + + +_start: + LDR PC, =__mbed_reset + LDR PC, =__mbed_undef + LDR PC, =__mbed_swi + LDR PC, =__mbed_prefetch_abort + LDR PC, =__mbed_data_abort + NOP ; + LDR PC, =__mbed_irq + LDR PC, =__mbed_fiq diff --git a/targets/TARGET_NXP/TARGET_LPC23XX/device/TOOLCHAIN_GCC_CS/LPC2368.ld b/targets/TARGET_NXP/TARGET_LPC23XX/device/TOOLCHAIN_GCC_CS/LPC2368.ld new file mode 100644 index 00000000000..fcac8264855 --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC23XX/device/TOOLCHAIN_GCC_CS/LPC2368.ld @@ -0,0 +1,207 @@ +OUTPUT_FORMAT("elf32-littlearm", "elf32-bigarm", "elf32-littlearm") +OUTPUT_ARCH(arm) +ENTRY(vectors) +GROUP(-lsupc++ -lm -lc -lcs3unhosted -lcs3 -lgcc) + +/* Memory Definitions: */ +MEMORY +{ + Flash (rx) : ORIGIN = 0x00000000, LENGTH = 512k + Ram (rwx) : ORIGIN = 0x40000000, LENGTH = 32k + UsbRam (rw) : ORIGIN = 0x7FD00000, LENGTH = 8k + EthRam (rw) : ORIGIN = 0x7FE00000, LENGTH = 16k + CanRam (rw) : ORIGIN = 0xE0038000, LENGTH = 2k + BatRam (rw) : ORIGIN = 0xE0084000, LENGTH = 2k +} + +/* Stack sizes: */ +UND_Stack_Size = 16; +SVC_Stack_Size = 512; +ABT_Stack_Size = 16; +FIQ_Stack_Size = 16; +IRQ_Stack_Size = 256; +Stack_Size_Total = UND_Stack_Size + SVC_Stack_Size + ABT_Stack_Size + FIQ_Stack_Size + IRQ_Stack_Size; + +/* Stack tops for each mode: */ +__und_stack_top__ = __stacks_top__; +__abt_stack_top__ = __und_stack_top__ - UND_Stack_Size ; +__fiq_stack_top__ = __abt_stack_top__ - ABT_Stack_Size ; +__irq_stack_top__ = __fiq_stack_top__ - FIQ_Stack_Size ; +__svc_stack_top__ = __irq_stack_top__ - IRQ_Stack_Size ; + +/* C-accessible symbols for memory address ranges: */ +__FLASH_segment_start__ = ORIGIN( Flash ); +__FLASH_segment_end__ = ORIGIN( Flash ) + LENGTH( Flash ); +__SRAM_segment_start__ = ORIGIN( Ram ); +__SRAM_segment_end__ = ORIGIN( Ram ) + LENGTH( Ram ); + +/* Stacks (full descending) at top of RAM, grows downward: + * + * __stack_min__ is used by the malloc implementation to ensure heap never collides + * with stack (assuming stack never grows beyond Stack_Size_Total in length) */ +__stacks_top__ = __SRAM_segment_end__; +__stacks_min__ = __SRAM_segment_end__ - Stack_Size_Total; + +SECTIONS +{ + /* first section is .text which is used for code */ + __text_start__ = . ; + .text : { + __privileged_code_start__ = . ; + KEEP( *( .vectors ) ) + *( .privileged_code ) + + __privileged_code_end__ = .; + + *( .text .text.* .gnu.linkonce.t.* ) + *( .plt ) + *( .gnu.warning ) + *( .glue_7t ) *( .glue_7 ) *( .vfp11_veneer ) + + *( .rodata .rodata.* .gnu.linkonce.r.* ) + + *(.ARM.extab* .gnu.linkonce.armextab.*) + *(.gcc_except_table) + *(.eh_frame_hdr) + *(.eh_frame) + + . = ALIGN( 4 ) ; + KEEP( *( .init ) ) + . = ALIGN( 4 ) ; + __preinit_array_start = . ; + KEEP( *( .preinit_array ) ) + __preinit_array_end = . ; + . = ALIGN( 4 ) ; + __init_array_start = . ; + KEEP( *( SORT( .init_array.* ) ) ) + KEEP( *( .init_array ) ) + __init_array_end = . ; + + . = ALIGN( 4 ) ; + KEEP( *crtbegin.o( .ctors ) ) + KEEP( *( EXCLUDE_FILE( *crtend.o ) .ctors ) ) + KEEP( *( SORT( .ctors.* ) ) ) + KEEP( *crtend.o( .ctors ) ) + + . = ALIGN( 4 ) ; + KEEP( *( .fini ) ) + . = ALIGN( 4 ) ; + __fini_array_start = . ; + KEEP( *( .fini_array ) ) + KEEP( *( SORT( .fini_array.* ) ) ) + __fini_array_end = . ; + + KEEP( *crtbegin.o( .dtors ) ) + KEEP( *( EXCLUDE_FILE( *crtend.o ) .dtors ) ) + KEEP( *( SORT( .dtors.* ) ) ) + KEEP( *crtend.o( .dtors ) ) + + } >Flash + + __exidx_start = . ; + .ARM.exidx : { + *( .ARM.exidx* .gnu.linkonce.armexidx.* ) + } >Flash + __exidx_end = . ; + + .text.align : { . = ALIGN( 8 ) ; } >Flash /* Alignment schenanigans */ + __text_end__ = . ; + + /* .bss section -- used for uninitialized data */ + /* Located at the start of RAM */ + .bss (NOLOAD) : { + __bss_start__ = . ; + *crt0.o( .ram_vectors ) + + __user_bss_start__ = . ; + *( .user_bss ) + __user_bss_end__ = . ; + + *( .shbss ) + *( .bss .bss.* .gnu.linkonce.b.* ) + *( COMMON ) + *( .ram.b ) + . = ALIGN( 8 ) ; + + __bss_end__ = . ; + } >Ram AT>Flash + + /* .data section -- used for initialized data */ + .data : { + __data_start__ = . ; + KEEP( *( .jcr ) ) + *( .got.plt ) *( .got ) + *( .shdata ) + *( .data .data.* .gnu.linkonce.d.* ) + *( .ram ) + . = ALIGN( 8 ) ; + __data_end__ = . ; + } >Ram AT>Flash + + __data_init_start__ = LOADADDR( .data ) ; + + /* Heap starts here and grows up in memory */ + . = ALIGN( 8 ) ; + __heap_start__ = . ; + + .stab 0 (NOLOAD) : { *(.stab) } + .stabstr 0 (NOLOAD) : { *(.stabstr) } + /* DWARF debug sections. */ + /* Symbols in the DWARF debugging sections are relative to the */ + /* beginning of the section so we begin them at 0. */ + /* DWARF 1 */ + .debug 0 : { *(.debug) } + .line 0 : { *(.line) } + /* GNU DWARF 1 extensions */ + .debug_srcinfo 0 : { *(.debug_srcinfo) } + .debug_sfnames 0 : { *(.debug_sfnames) } + /* DWARF 1.1 and DWARF 2 */ + .debug_aranges 0 : { *(.debug_aranges) } + .debug_pubnames 0 : { *(.debug_pubnames) } + /* DWARF 2 */ + .debug_info 0 : { *(.debug_info .gnu.linkonce.wi.*) } + .debug_abbrev 0 : { *(.debug_abbrev) } + .debug_line 0 : { *(.debug_line) } + .debug_frame 0 : { *(.debug_frame) } + .debug_str 0 : { *(.debug_str) } + .debug_loc 0 : { *(.debug_loc) } + .debug_macinfo 0 : { *(.debug_macinfo) } + /* SGI/MIPS DWARF 2 extensions */ + .debug_weaknames 0 : { *(.debug_weaknames) } + .debug_funcnames 0 : { *(.debug_funcnames) } + .debug_typenames 0 : { *(.debug_typenames) } + .debug_varnames 0 : { *(.debug_varnames) } + /* DWARF 3 */ + .debug_pubtypes 0 : { *(.debug_pubtypes) } + .debug_ranges 0 : { *(.debug_ranges) } + + .note.gnu.arm.ident 0 : { KEEP( *( .note.gnu.arm.ident ) ) } + .ARM.attributes 0 : { + KEEP( *( .ARM.attributes ) ) + KEEP( *( .gnu.attributes ) ) + } + /DISCARD/ : { *( .note.GNU-stack ) } + + /* C data can be defined as being in special purpose RAMs using + * __attribute__ ((section ("ethram"))) for example. */ + .usbram (NOLOAD): + { + *( .usbram ) + *( .usbram.* ) + } > UsbRam + .ethram (NOLOAD): + { + *( .ethram ) + *( .ethram.* ) + } > EthRam + .canram (NOLOAD): + { + *( .canram ) + *( .canram.* ) + } > CanRam + .batram (NOLOAD): + { + *( .batram ) + *( .batram.* ) + } > BatRam +} diff --git a/targets/TARGET_NXP/TARGET_LPC23XX/device/TOOLCHAIN_GCC_CS/vector_functions.S b/targets/TARGET_NXP/TARGET_LPC23XX/device/TOOLCHAIN_GCC_CS/vector_functions.S new file mode 100644 index 00000000000..0751c50591d --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC23XX/device/TOOLCHAIN_GCC_CS/vector_functions.S @@ -0,0 +1,180 @@ +# 1 "vector_functions.s" +# 1 "" +# 1 "" +# 1 "vector_functions.s" +; +; +; + +# 1 "vector_defns.h" 1 +# 6 "vector_functions.s" 2 + + + + + + + .section VECFUNCS, "ax" + .arm + + + .weak __mbed_fiq + .weak __mbed_undef + .weak __mbed_prefetch_abort + .weak __mbed_data_abort + .weak __mbed_irq + .weak __mbed_swi + .weak __mbed_dcc_irq + .weak __mbed_reset + .global __mbed_init_realmonitor + .global __mbed_init + +; +; +__mbed_fiq: + B __mbed_fiq + +; +; +__mbed_undef: + LDR PC, =0x7fffffa0 + +; +; +__mbed_prefetch_abort: + LDR PC, =0x7fffffb0 + +; +; +__mbed_data_abort: + LDR PC, =0x7fffffc0 + +; +; +; +; +; +; +; +; +; +__mbed_irq: + ; + MSR CPSR_c, #0x1F|0x80|0x40 + + ; + STMDB sp!, {r0-r3,r12,lr} + + ; + MOV r0, #0xFFFFFF00 + LDR r0, [r0] + + ; + MOV lr, pc + BX r0 + + ; + MOV r0, #0xFFFFFF00 + STR r0, [r0] ; + + ; + LDMFD sp!,{r0-r3,r12,lr} + + ; + MSR CPSR_c, #0x12|0x80|0x40 + + ; + SUBS pc, lr, #4 + +; +; +; +; +__mbed_swi: + ; + ; + STMFD sp!, {a4, r4, ip, lr} + + ; + LDR r4, =0x40000040 + + ; + ; + LDR a4, =0x00940000 + LDR PC, =0x7ffff820 + +; +; +; +; +__mbed_dcc_irq: + + ; + + ; + LDMFD sp!,{r0-r3,r12,lr} + + ; + MSR CPSR_c, #0x12|0x80|0x40 + + ; + + ; + SUB lr, lr, #4 ; + STMFD sp!, {ip,lr} ; + + ; + LDR LR, =0xfffff000 + STR LR, [LR, #0xf00] + + ; + ; + ; + ; + LDR PC, =0x7fffffe0 + +; +; +__mbed_reset: + + ; + + LDR R0, =(0x40000000 + 0x8000) + + ; + MSR CPSR_c, #0x1B|0x80|0x40 + MOV SP, R0 + SUB R0, R0, #0x00000040 + + ; + MSR CPSR_c, #0x17|0x80|0x40 + MOV SP, R0 + SUB R0, R0, #0x00000040 + + ; + MSR CPSR_c, #0x11|0x80|0x40 + MOV SP, R0 + SUB R0, R0, #0x00000000 + + ; + MSR CPSR_c, #0x12|0x80|0x40 + MOV SP, R0 + SUB R0, R0, #0x00000040 + + ; + MSR CPSR_c, #0x13|0x80|0x40 + MOV SP, R0 + SUB R0, R0, #0x00000040 + + ; + MSR CPSR_c, #0x10 + MOV SP, R0 + + ; + LDR R0, =__mbed_init_realmonitor + MOV LR, PC + BX R0 + + ; + LDR R0, =__mbed_init + BX R0 diff --git a/targets/TARGET_NXP/TARGET_LPC23XX/device/TOOLCHAIN_GCC_CS/vector_table.S b/targets/TARGET_NXP/TARGET_LPC23XX/device/TOOLCHAIN_GCC_CS/vector_table.S new file mode 100644 index 00000000000..281e7a9bd4c --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC23XX/device/TOOLCHAIN_GCC_CS/vector_table.S @@ -0,0 +1,45 @@ +# 1 "vector_table.s" +# 1 "" +# 1 "" +# 1 "vector_table.s" +; + + + + +# 1 "vector_defns.h" 1 +# 7 "vector_table.s" 2 + +; + + + + + + + + .section VECTOR_TABLE, "ax" + .arm + + + .global __main + .global __mbed_reset + .global __mbed_undef + .global __mbed_swi + .global __mbed_prefetch_abort + .global __mbed_data_abort + .global __mbed_irq + .global __mbed_fiq + +; + + +__main: + LDR PC, =__mbed_reset + LDR PC, =__mbed_undef + LDR PC, =__mbed_swi + LDR PC, =__mbed_prefetch_abort + LDR PC, =__mbed_data_abort + NOP ; + LDR PC, =__mbed_irq + LDR PC, =__mbed_fiq diff --git a/targets/TARGET_NXP/TARGET_LPC23XX/device/cmsis.h b/targets/TARGET_NXP/TARGET_LPC23XX/device/cmsis.h new file mode 100644 index 00000000000..3926baf40ad --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC23XX/device/cmsis.h @@ -0,0 +1,13 @@ +/* mbed Microcontroller Library - CMSIS + * Copyright (C) 2009-2011 ARM Limited. All rights reserved. + * + * A generic CMSIS include header, pulling in LPC2368 specifics + */ + +#ifndef MBED_CMSIS_H +#define MBED_CMSIS_H + +#include "LPC23xx.h" +#include "cmsis_nvic.h" + +#endif diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/device/cmsis_nvic.c b/targets/TARGET_NXP/TARGET_LPC23XX/device/cmsis_nvic.c similarity index 84% rename from targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/device/cmsis_nvic.c rename to targets/TARGET_NXP/TARGET_LPC23XX/device/cmsis_nvic.c index 0de56f35da8..6df47d1b3ef 100644 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/device/cmsis_nvic.c +++ b/targets/TARGET_NXP/TARGET_LPC23XX/device/cmsis_nvic.c @@ -1,7 +1,7 @@ /* mbed Microcontroller Library * CMSIS-style functionality to support dynamic vectors ******************************************************************************* - * Copyright (c) 2017 ARM Limited. All rights reserved. + * Copyright (c) 2011 ARM Limited. All rights reserved. * All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -30,13 +30,11 @@ */ #include "cmsis_nvic.h" -extern void InstallIRQHandler(IRQn_Type irq, uint32_t irqHandler); - -void __NVIC_SetVector(IRQn_Type IRQn, uint32_t vector) { - InstallIRQHandler(IRQn, vector); +void NVIC_SetVector(IRQn_Type IRQn, uint32_t vector) { + LPC_VIC->VectAddr[(int)IRQn] = vector; } -uint32_t __NVIC_GetVector(IRQn_Type IRQn) { - uint32_t *vectors = (uint32_t*)SCB->VTOR; - return vectors[IRQn + 16]; +uint32_t NVIC_GetVector(IRQn_Type IRQn) { + return LPC_VIC->VectAddr[(int)IRQn]; } + diff --git a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/device/cmsis_nvic.h b/targets/TARGET_NXP/TARGET_LPC23XX/device/cmsis_nvic.h similarity index 88% rename from targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/device/cmsis_nvic.h rename to targets/TARGET_NXP/TARGET_LPC23XX/device/cmsis_nvic.h index 68f955d408b..a4ab2564986 100644 --- a/targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_MCU_K24F/TARGET_MCU_K24F1M/device/cmsis_nvic.h +++ b/targets/TARGET_NXP/TARGET_LPC23XX/device/cmsis_nvic.h @@ -1,7 +1,7 @@ /* mbed Microcontroller Library * CMSIS-style functionality to support dynamic vectors ******************************************************************************* - * Copyright (c) 2017 ARM Limited. All rights reserved. + * Copyright (c) 2011 ARM Limited. All rights reserved. * All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -32,8 +32,8 @@ #ifndef MBED_CMSIS_NVIC_H #define MBED_CMSIS_NVIC_H -#define NVIC_NUM_VECTORS (16 + 86) // CORE + MCU Peripherals -#define NVIC_USER_IRQ_OFFSET 16 +#define NVIC_NUM_VECTORS 32 +#define NVIC_USER_IRQ_OFFSET 0 #include "cmsis.h" @@ -41,8 +41,8 @@ extern "C" { #endif -void __NVIC_SetVector(IRQn_Type IRQn, uint32_t vector); -uint32_t __NVIC_GetVector(IRQn_Type IRQn); +void NVIC_SetVector(IRQn_Type IRQn, uint32_t vector); +uint32_t NVIC_GetVector(IRQn_Type IRQn); #ifdef __cplusplus } diff --git a/targets/TARGET_NXP/TARGET_LPC23XX/device/core_arm7.c b/targets/TARGET_NXP/TARGET_LPC23XX/device/core_arm7.c new file mode 100644 index 00000000000..3ed1daeeb46 --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC23XX/device/core_arm7.c @@ -0,0 +1,44 @@ +/* mbed Microcontroller Library + * Copyright (C) 2008-2009 ARM Limited. All rights reserved. + * + * ARM7 version of CMSIS-like functionality - not advised for use outside mbed! + * based on core_cm3.h, V1.20 + */ + +#include + + +/* define compiler specific symbols */ +#if defined ( __CC_ARM ) + #define __ASM __asm /*!< asm keyword for armcc */ + #define __INLINE __inline /*!< inline keyword for armcc */ + +#elif defined ( __ICCARM__ ) + #define __ASM __asm /*!< asm keyword for iarcc */ + #define __INLINE inline /*!< inline keyword for iarcc. Only avaiable in High optimization mode! */ + +#elif defined ( __GNUC__ ) + #define __ASM __asm /*!< asm keyword for gcc */ + #define __INLINE inline /*!< inline keyword for gcc */ + +#elif defined ( __TASKING__ ) + #define __ASM __asm /*!< asm keyword for TASKING Compiler */ + #define __INLINE inline /*!< inline keyword for TASKING Compiler */ + +#endif + +#if defined ( __CC_ARM ) +/** + * @brief Return the Main Stack Pointer (return current ARM7 stack) + * + * @param none + * @return uint32_t Main Stack Pointer + * + * Return the current value of the MSP (main stack pointer) + * Cortex processor register + */ +uint32_t __get_MSP(void) +{ + return __current_sp(); +} +#endif diff --git a/targets/TARGET_NXP/TARGET_LPC23XX/device/core_arm7.h b/targets/TARGET_NXP/TARGET_LPC23XX/device/core_arm7.h new file mode 100644 index 00000000000..96558130586 --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC23XX/device/core_arm7.h @@ -0,0 +1,276 @@ +/* mbed Microcontroller Library + * Copyright (C) 2008-2009 ARM Limited. All rights reserved. + * + * ARM7 version of CMSIS-like functionality - not advised for use outside mbed! + * based on core_cm3.h, V1.20 + */ + +#ifndef __ARM7_CORE_H__ +#define __ARM7_CORE_H__ + +#include "vector_defns.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define __CM3_CMSIS_VERSION_MAIN (0x01) /*!< [31:16] CMSIS HAL main version */ +#define __CM3_CMSIS_VERSION_SUB (0x20) /*!< [15:0] CMSIS HAL sub version */ +#define __CM3_CMSIS_VERSION ((__CM3_CMSIS_VERSION_MAIN << 16) | __CM3_CMSIS_VERSION_SUB) /*!< CMSIS HAL version number */ + +#define __CORTEX_M (0x03) /*!< Cortex core */ + +/** + * Lint configuration \n + * ----------------------- \n + * + * The following Lint messages will be suppressed and not shown: \n + * \n + * --- Error 10: --- \n + * register uint32_t __regBasePri __asm("basepri"); \n + * Error 10: Expecting ';' \n + * \n + * --- Error 530: --- \n + * return(__regBasePri); \n + * Warning 530: Symbol '__regBasePri' (line 264) not initialized \n + * \n + * --- Error 550: --- \n + * __regBasePri = (basePri & 0x1ff); \n + * } \n + * Warning 550: Symbol '__regBasePri' (line 271) not accessed \n + * \n + * --- Error 754: --- \n + * uint32_t RESERVED0[24]; \n + * Info 754: local structure member '' (line 109, file ./cm3_core.h) not referenced \n + * \n + * --- Error 750: --- \n + * #define __CM3_CORE_H__ \n + * Info 750: local macro '__CM3_CORE_H__' (line 43, file./cm3_core.h) not referenced \n + * \n + * --- Error 528: --- \n + * static __INLINE void NVIC_DisableIRQ(uint32_t IRQn) \n + * Warning 528: Symbol 'NVIC_DisableIRQ(unsigned int)' (line 419, file ./cm3_core.h) not referenced \n + * \n + * --- Error 751: --- \n + * } InterruptType_Type; \n + * Info 751: local typedef 'InterruptType_Type' (line 170, file ./cm3_core.h) not referenced \n + * \n + * \n + * Note: To re-enable a Message, insert a space before 'lint' * \n + * + */ + +/*lint -save */ +/*lint -e10 */ +/*lint -e530 */ +/*lint -e550 */ +/*lint -e754 */ +/*lint -e750 */ +/*lint -e528 */ +/*lint -e751 */ + +#include /* Include standard types */ + +#if defined ( __CC_ARM ) +/** + * @brief Return the Main Stack Pointer (current ARM7 stack) + * + * @param none + * @return uint32_t Main Stack Pointer + * + * Return the current value of the MSP (main stack pointer) + * Cortex processor register + */ +extern uint32_t __get_MSP(void); +#endif + + +#if defined (__ICCARM__) + #include /* IAR Intrinsics */ +#endif + + +#ifndef __NVIC_PRIO_BITS + #define __NVIC_PRIO_BITS 4 /*!< standard definition for NVIC Priority Bits */ +#endif + +typedef struct +{ + uint32_t IRQStatus; + uint32_t FIQStatus; + uint32_t RawIntr; + uint32_t IntSelect; + uint32_t IntEnable; + uint32_t IntEnClr; + uint32_t SoftInt; + uint32_t SoftIntClr; + uint32_t Protection; + uint32_t SWPriorityMask; + uint32_t RESERVED0[54]; + uint32_t VectAddr[32]; + uint32_t RESERVED1[32]; + uint32_t VectPriority[32]; + uint32_t RESERVED2[800]; + uint32_t Address; +} NVIC_TypeDef; + +#define NVIC_BASE (0xFFFFF000) +#define NVIC (( NVIC_TypeDef *) NVIC_BASE) + + + +/** + * IO definitions + * + * define access restrictions to peripheral registers + */ + +#ifdef __cplusplus +#define __I volatile /*!< defines 'read only' permissions */ +#else +#define __I volatile const /*!< defines 'read only' permissions */ +#endif +#define __O volatile /*!< defines 'write only' permissions */ +#define __IO volatile /*!< defines 'read / write' permissions */ + + + + + +#if defined ( __CC_ARM ) + #define __ASM __asm /*!< asm keyword for ARM Compiler */ + #define __INLINE __inline /*!< inline keyword for ARM Compiler */ + +#elif defined ( __ICCARM__ ) + #define __ASM __asm /*!< asm keyword for IAR Compiler */ + #define __INLINE inline /*!< inline keyword for IAR Compiler. Only avaiable in High optimization mode! */ + +#elif defined ( __GNUC__ ) + #define __ASM __asm /*!< asm keyword for GNU Compiler */ + #define __INLINE inline /*!< inline keyword for GNU Compiler */ + +#elif defined ( __TASKING__ ) + #define __ASM __asm /*!< asm keyword for TASKING Compiler */ + #define __INLINE inline /*!< inline keyword for TASKING Compiler */ + +#endif + + +/* ################### Compiler specific Intrinsics ########################### */ + +#if defined ( __CC_ARM ) /*------------------RealView Compiler -----------------*/ +/* ARM armcc specific functions */ + +#define __enable_fault_irq __enable_fiq +#define __disable_fault_irq __disable_fiq + +#define __NOP __nop +//#define __WFI __wfi +//#define __WFE __wfe +//#define __SEV __sev +//#define __ISB() __isb(0) +//#define __DSB() __dsb(0) +//#define __DMB() __dmb(0) +//#define __REV __rev +//#define __RBIT __rbit +#define __LDREXB(ptr) ((unsigned char ) __ldrex(ptr)) +#define __LDREXH(ptr) ((unsigned short) __ldrex(ptr)) +#define __LDREXW(ptr) ((unsigned int ) __ldrex(ptr)) +#define __STREXB(value, ptr) __strex(value, ptr) +#define __STREXH(value, ptr) __strex(value, ptr) +#define __STREXW(value, ptr) __strex(value, ptr) + +#define __disable_irq() unsigned tmp_IntEnable = LPC_VIC->IntEnable; \ + LPC_VIC->IntEnClr = 0xffffffff + +#define __enable_irq() LPC_VIC->IntEnable = tmp_IntEnable + +#elif (defined (__ICCARM__)) /*------------------ ICC Compiler -------------------*/ + +#define __enable_irq __enable_interrupt /*!< global Interrupt enable */ +#define __disable_irq __disable_interrupt /*!< global Interrupt disable */ +#define __NOP __no_operation() /*!< no operation intrinsic in IAR Compiler */ + +#elif (defined (__GNUC__)) /*------------------ GNU Compiler ---------------------*/ + +static __INLINE void __enable_irq() { + unsigned long temp; + __asm__ __volatile__("mrs %0, cpsr\n" + "bic %0, %0, #0x80\n" + "msr cpsr_c, %0" + : "=r" (temp) + : + : "memory"); +} + +static __INLINE void __disable_irq() { + unsigned long old,temp; + __asm__ __volatile__("mrs %0, cpsr\n" + "orr %1, %0, #0xc0\n" + "msr cpsr_c, %1" + : "=r" (old), "=r" (temp) + : + : "memory"); + // return (old & 0x80) == 0; +} + +static __INLINE void __NOP() { __ASM volatile ("nop"); } + +#elif (defined (__TASKING__)) /*------------------ TASKING Compiler ---------------------*/ +/* TASKING carm specific functions */ + +/* + * The CMSIS functions have been implemented as intrinsics in the compiler. + * Please use "carm -?i" to get an up to date list of all instrinsics, + * Including the CMSIS ones. + */ + +#endif + + +/** + * @brief Enable Interrupt in NVIC Interrupt Controller + * + * @param IRQn_Type IRQn specifies the interrupt number + * @return none + * + * Enable a device specific interupt in the NVIC interrupt controller. + * The interrupt number cannot be a negative value. + */ +static __INLINE void NVIC_EnableIRQ(IRQn_Type IRQn) +{ + NVIC->IntEnable = 1 << (uint32_t)IRQn; +} + + +/** + * @brief Disable the interrupt line for external interrupt specified + * + * @param IRQn_Type IRQn is the positive number of the external interrupt + * @return none + * + * Disable a device specific interupt in the NVIC interrupt controller. + * The interrupt number cannot be a negative value. + */ +static __INLINE void NVIC_DisableIRQ(IRQn_Type IRQn) +{ + NVIC->IntEnClr = 1 << (uint32_t)IRQn; +} + +static __INLINE uint32_t __get_IPSR(void) +{ + unsigned i; + + for(i = 0; i < 32; i ++) + if(NVIC->Address == NVIC->VectAddr[i]) + return i; + return 1; // 1 is an invalid entry in the interrupt table on LPC2368 +} + +#ifdef __cplusplus +} +#endif + +#endif /* __ARM7_CORE_H__ */ + +/*lint -restore */ diff --git a/targets/TARGET_NXP/TARGET_LPC23XX/device/system_LPC23xx.c b/targets/TARGET_NXP/TARGET_LPC23XX/device/system_LPC23xx.c new file mode 100644 index 00000000000..fc5d804ab2d --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC23XX/device/system_LPC23xx.c @@ -0,0 +1,144 @@ +/* mbed Microcontroller Library + * Copyright (C) 2008-2009 ARM Limited. All rights reserved. + * + * ARM7 version of CMSIS-like functionality - not advised for use outside mbed! + */ + +#include +#include "LPC23xx.h" + +#define CLOCK_SETUP 1 +#define SCS_Val 0x00000020 +#define CLKSRCSEL_Val 0x00000001 + +#define PLL0_SETUP 1 +#define PLL0CFG_Val 0x00000013 +#define CCLKCFG_Val 0x00000007 +#define USBCLKCFG_Val 0x00000009 +#define PCLKSEL0_Val 0x00000000 +#define PCLKSEL1_Val 0x00000000 +#define PCONP_Val 0x042887DE +#define CLKOUTCFG_Val 0x00000000 +#define MAMCR_Val 0x00000001 // there is a bug in the MAM so it should never be fully enabled (only disabled or partially enabled) +#define MAMTIM_Val 0x00000004 + +/*---------------------------------------------------------------------------- + DEFINES + *----------------------------------------------------------------------------*/ + +#define XTAL (12000000UL) /* Oscillator frequency */ +#define OSC_CLK ( XTAL) /* Main oscillator frequency */ +#define RTC_CLK ( 32000UL) /* RTC oscillator frequency */ +#define IRC_OSC ( 4000000UL) /* Internal RC oscillator frequency */ + +/* F_cco0 = (2 * M * F_in) / N */ +#define __M (((PLL0CFG_Val ) & 0x7FFF) + 1) +#define __N (((PLL0CFG_Val >> 16) & 0x00FF) + 1) +#define __FCCO(__F_IN) ((2 * __M * __F_IN) / __N) +#define __CCLK_DIV (((CCLKCFG_Val ) & 0x00FF) + 1) + +/* Determine core clock frequency according to settings */ + #if (PLL0_SETUP) + #if ((CLKSRCSEL_Val & 0x03) == 1) + #define __CORE_CLK (__FCCO(OSC_CLK) / __CCLK_DIV) + #elif ((CLKSRCSEL_Val & 0x03) == 2) + #define __CORE_CLK (__FCCO(RTC_CLK) / __CCLK_DIV) + #else + #define __CORE_CLK (__FCCO(IRC_OSC) / __CCLK_DIV) + #endif + #endif + + +/*---------------------------------------------------------------------------- + Clock Variable definitions + *----------------------------------------------------------------------------*/ +uint32_t SystemCoreClock = __CORE_CLK;/*!< System Clock Frequency (Core Clock)*/ + +/*---------------------------------------------------------------------------- + Clock functions + *----------------------------------------------------------------------------*/ +void SystemCoreClockUpdate (void) /* Get Core Clock Frequency */ +{ + /* Determine clock frequency according to clock register values */ + if (((LPC_SC->PLL0STAT >> 24) & 3) == 3) { /* If PLL0 enabled and connected */ + switch (LPC_SC->CLKSRCSEL & 0x03) { + case 0: /* Int. RC oscillator => PLL0 */ + case 3: /* Reserved, default to Int. RC */ + SystemCoreClock = (IRC_OSC * + (((2 * ((LPC_SC->PLL0STAT & 0x7FFF) + 1))) / + (((LPC_SC->PLL0STAT >> 16) & 0xFF) + 1)) / + ((LPC_SC->CCLKCFG & 0xFF)+ 1)); + break; + case 1: /* Main oscillator => PLL0 */ + SystemCoreClock = (OSC_CLK * + (((2 * ((LPC_SC->PLL0STAT & 0x7FFF) + 1))) / + (((LPC_SC->PLL0STAT >> 16) & 0xFF) + 1)) / + ((LPC_SC->CCLKCFG & 0xFF)+ 1)); + break; + case 2: /* RTC oscillator => PLL0 */ + SystemCoreClock = (RTC_CLK * + (((2 * ((LPC_SC->PLL0STAT & 0x7FFF) + 1))) / + (((LPC_SC->PLL0STAT >> 16) & 0xFF) + 1)) / + ((LPC_SC->CCLKCFG & 0xFF)+ 1)); + break; + } + } else { + switch (LPC_SC->CLKSRCSEL & 0x03) { + case 0: /* Int. RC oscillator => PLL0 */ + case 3: /* Reserved, default to Int. RC */ + SystemCoreClock = IRC_OSC / ((LPC_SC->CCLKCFG & 0xFF)+ 1); + break; + case 1: /* Main oscillator => PLL0 */ + SystemCoreClock = OSC_CLK / ((LPC_SC->CCLKCFG & 0xFF)+ 1); + break; + case 2: /* RTC oscillator => PLL0 */ + SystemCoreClock = RTC_CLK / ((LPC_SC->CCLKCFG & 0xFF)+ 1); + break; + } + } +} + +/** + * Initialize the system + * + * @param none + * @return none + * + * @brief Setup the microcontroller system. + * Initialize the System and update the SystemFrequency variable. + */ +void SystemInit (void) +{ +#if (CLOCK_SETUP) /* Clock Setup */ + LPC_SC->SCS = SCS_Val; + if (SCS_Val & (1 << 5)) { /* If Main Oscillator is enabled */ + while ((LPC_SC->SCS & (1 << 6)) == 0); /* Wait for Oscillator to be ready */ + } + + LPC_SC->CCLKCFG = CCLKCFG_Val; /* Setup Clock Divider */ + +#if (PLL0_SETUP) + LPC_SC->CLKSRCSEL = CLKSRCSEL_Val; /* Select Clock Source for PLL0 */ + LPC_SC->PLL0CFG = PLL0CFG_Val; + LPC_SC->PLL0CON = 0x01; /* PLL0 Enable */ + LPC_SC->PLL0FEED = 0xAA; + LPC_SC->PLL0FEED = 0x55; + while (!(LPC_SC->PLL0STAT & (1 << 26))); /* Wait for PLOCK0 */ + + LPC_SC->PLL0CON = 0x03; /* PLL0 Enable & Connect */ + LPC_SC->PLL0FEED = 0xAA; + LPC_SC->PLL0FEED = 0x55; +#endif + + LPC_SC->USBCLKCFG = USBCLKCFG_Val; /* Setup USB Clock Divider */ +#endif + + LPC_SC->PCLKSEL0 = PCLKSEL0_Val; /* Peripheral Clock Selection */ + LPC_SC->PCLKSEL1 = PCLKSEL1_Val; + + LPC_SC->PCONP = PCONP_Val; /* Power Control for Peripherals */ + + // Setup MAM + LPC_SC->MAMTIM = MAMTIM_Val; + LPC_SC->MAMCR = MAMCR_Val; +} diff --git a/targets/TARGET_NXP/TARGET_LPC23XX/device/system_LPC23xx.h b/targets/TARGET_NXP/TARGET_LPC23XX/device/system_LPC23xx.h new file mode 100644 index 00000000000..f14b72a83ba --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC23XX/device/system_LPC23xx.h @@ -0,0 +1,44 @@ +/* mbed Microcontroller Library + * Copyright (C) 2008-2009 ARM Limited. All rights reserved. + * + * ARM7 version of CMSIS-like functionality - not advised for use outside mbed! + * based on cmsis system_LPC17xx.h + */ + +#ifndef __SYSTEM_LPC23xx_H +#define __SYSTEM_LPC23xx_H + +#ifdef __cplusplus + extern "C" { +#endif + +extern uint32_t SystemCoreClock; /*!< System Clock Frequency (Core Clock) */ + +/** + * Initialize the system + * + * @param none + * @return none + * + * @brief Setup the microcontroller system. + * Initialize the System and update the SystemCoreClock variable. + */ +extern void SystemInit (void); + +/** + * Update SystemCoreClock variable + * + * @param none + * @return none + * + * @brief Updates the SystemCoreClock with current core Clock + * retrieved from cpu registers. + */ +extern void SystemCoreClockUpdate (void); + + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/targets/TARGET_NXP/TARGET_LPC23XX/device/vector_defns.h b/targets/TARGET_NXP/TARGET_LPC23XX/device/vector_defns.h new file mode 100644 index 00000000000..10b0b6a056d --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC23XX/device/vector_defns.h @@ -0,0 +1,77 @@ +/* mbed Microcontroller Library - Vectors + * Copyright (c) 2006-2009 ARM Limited. All rights reserved. + */ + +#ifndef MBED_VECTOR_DEFNS_H +#define MBED_VECTOR_DEFNS_H + +// Assember Macros +#ifdef __ARMCC_VERSION +#define EXPORT(x) EXPORT x +#define WEAK_EXPORT(x) EXPORT x [WEAK] +#define IMPORT(x) IMPORT x +#define LABEL(x) x +#else +#define EXPORT(x) .global x +#define WEAK_EXPORT(x) .weak x +#define IMPORT(x) .global x +#define LABEL(x) x: +#endif + +// RealMonitor +// Requires RAM (0x40000040-0x4000011F) to be allocated by the linker + +// RealMonitor entry points +#define rm_init_entry 0x7fffff91 +#define rm_undef_handler 0x7fffffa0 +#define rm_prefetchabort_handler 0x7fffffb0 +#define rm_dataabort_handler 0x7fffffc0 +#define rm_irqhandler2 0x7fffffe0 +//#define rm_RunningToStopped 0x7ffff808 // ARM - MBED64 +#define rm_RunningToStopped 0x7ffff820 // ARM - PHAT40 + +// Unofficial RealMonitor entry points and variables +#define RM_MSG_SWI 0x00940000 +#define StateP 0x40000040 + +// VIC register addresses +#define VIC_Base 0xfffff000 +#define VICAddress_Offset 0xf00 +#define VICVectAddr0_Offset 0x100 +#define VICVectAddr2_Offset 0x108 +#define VICVectAddr3_Offset 0x10c +#define VICVectAddr31_Offset 0x17c +#define VICIntEnClr_Offset 0x014 +#define VICIntEnClr (*(volatile unsigned long *)(VIC_Base + 0x014)) +#define VICVectAddr2 (*(volatile unsigned long *)(VIC_Base + 0x108)) +#define VICVectAddr3 (*(volatile unsigned long *)(VIC_Base + 0x10C)) + +// ARM Mode bits and Interrupt flags in PSRs +#define Mode_USR 0x10 +#define Mode_FIQ 0x11 +#define Mode_IRQ 0x12 +#define Mode_SVC 0x13 +#define Mode_ABT 0x17 +#define Mode_UND 0x1B +#define Mode_SYS 0x1F +#define I_Bit 0x80 // when I bit is set, IRQ is disabled +#define F_Bit 0x40 // when F bit is set, FIQ is disabled + +// MCU RAM +#define LPC2368_RAM_ADDRESS 0x40000000 // RAM Base +#define LPC2368_RAM_SIZE 0x8000 // 32KB + +// ISR Stack Allocation +#define UND_stack_size 0x00000040 +#define SVC_stack_size 0x00000040 +#define ABT_stack_size 0x00000040 +#define FIQ_stack_size 0x00000000 +#define IRQ_stack_size 0x00000040 + +#define ISR_stack_size (UND_stack_size + SVC_stack_size + ABT_stack_size + FIQ_stack_size + IRQ_stack_size) + +// Full Descending Stack, so top-most stack points to just above the top of RAM +#define LPC2368_STACK_TOP (LPC2368_RAM_ADDRESS + LPC2368_RAM_SIZE) +#define USR_STACK_TOP (LPC2368_STACK_TOP - ISR_stack_size) + +#endif diff --git a/targets/TARGET_NXP/TARGET_LPC23XX/device/vector_realmonitor.c b/targets/TARGET_NXP/TARGET_LPC23XX/device/vector_realmonitor.c new file mode 100644 index 00000000000..921fe432998 --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC23XX/device/vector_realmonitor.c @@ -0,0 +1,22 @@ +/* mbed Microcontroller Library - RealMonitor + * Copyright (c) 2006-2009 ARM Limited. All rights reserved. + */ +#include "vector_defns.h" + +extern void __mbed_dcc_irq(void); + +/* Function: __mbed_init_realmonitor + * Setup the RealMonitor DCC Interrupt Handlers + */ +void __mbed_init_realmonitor(void) __attribute__((weak)); +void __mbed_init_realmonitor() { + // Disable all interrupts + VICIntEnClr = 0xffffffff; + + // Set DCC interrupt vector addresses + VICVectAddr2 = (unsigned)&__mbed_dcc_irq; + VICVectAddr3 = (unsigned)&__mbed_dcc_irq; + + // Initialise RealMonitor + ((void (*)(void))rm_init_entry)(); +} diff --git a/targets/TARGET_NXP/TARGET_LPC23XX/ethernet_api.c b/targets/TARGET_NXP/TARGET_LPC23XX/ethernet_api.c new file mode 100644 index 00000000000..ef882702337 --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC23XX/ethernet_api.c @@ -0,0 +1,935 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * 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. + */ +#include + +#include "ethernet_api.h" +#include "cmsis.h" +#include "mbed_interface.h" +#include "mbed_toolchain.h" +#include "mbed_error.h" + +#define NEW_LOGIC 0 +#define NEW_ETH_BUFFER 0 + +#if NEW_ETH_BUFFER + +#define NUM_RX_FRAG 4 // Number of Rx Fragments (== packets) +#define NUM_TX_FRAG 3 // Number of Tx Fragments (== packets) + +#define ETH_MAX_FLEN 1536 // Maximum Ethernet Frame Size +#define ETH_FRAG_SIZE ETH_MAX_FLEN // Packet Fragment size (same as packet length) + +#else + +// Memfree calculation: +// (16 * 1024) - ((2 * 4 * NUM_RX) + (2 * 4 * NUM_RX) + (0x300 * NUM_RX) + +// (2 * 4 * NUM_TX) + (1 * 4 * NUM_TX) + (0x300 * NUM_TX)) = 8556 +/* EMAC Memory Buffer configuration for 16K Ethernet RAM. */ +#define NUM_RX_FRAG 4 /* Num.of RX Fragments 4*1536= 6.0kB */ +#define NUM_TX_FRAG 3 /* Num.of TX Fragments 3*1536= 4.6kB */ +//#define ETH_FRAG_SIZE 1536 /* Packet Fragment size 1536 Bytes */ + +//#define ETH_MAX_FLEN 1536 /* Max. Ethernet Frame Size */ +#define ETH_FRAG_SIZE 0x300 /* Packet Fragment size 1536/2 Bytes */ +#define ETH_MAX_FLEN 0x300 /* Max. Ethernet Frame Size */ + +const int ethernet_MTU_SIZE = 0x300; + +#endif + +#define ETHERNET_ADDR_SIZE 6 + +PACKED struct RX_DESC_TypeDef { /* RX Descriptor struct */ + unsigned int Packet; + unsigned int Ctrl; +}; +typedef struct RX_DESC_TypeDef RX_DESC_TypeDef; + +PACKED struct RX_STAT_TypeDef { /* RX Status struct */ + unsigned int Info; + unsigned int HashCRC; +}; +typedef struct RX_STAT_TypeDef RX_STAT_TypeDef; + +PACKED struct TX_DESC_TypeDef { /* TX Descriptor struct */ + unsigned int Packet; + unsigned int Ctrl; +}; +typedef struct TX_DESC_TypeDef TX_DESC_TypeDef; + +PACKED struct TX_STAT_TypeDef { /* TX Status struct */ + unsigned int Info; +}; +typedef struct TX_STAT_TypeDef TX_STAT_TypeDef; + +/* MAC Configuration Register 1 */ +#define MAC1_REC_EN 0x00000001 /* Receive Enable */ +#define MAC1_PASS_ALL 0x00000002 /* Pass All Receive Frames */ +#define MAC1_RX_FLOWC 0x00000004 /* RX Flow Control */ +#define MAC1_TX_FLOWC 0x00000008 /* TX Flow Control */ +#define MAC1_LOOPB 0x00000010 /* Loop Back Mode */ +#define MAC1_RES_TX 0x00000100 /* Reset TX Logic */ +#define MAC1_RES_MCS_TX 0x00000200 /* Reset MAC TX Control Sublayer */ +#define MAC1_RES_RX 0x00000400 /* Reset RX Logic */ +#define MAC1_RES_MCS_RX 0x00000800 /* Reset MAC RX Control Sublayer */ +#define MAC1_SIM_RES 0x00004000 /* Simulation Reset */ +#define MAC1_SOFT_RES 0x00008000 /* Soft Reset MAC */ + +/* MAC Configuration Register 2 */ +#define MAC2_FULL_DUP 0x00000001 /* Full Duplex Mode */ +#define MAC2_FRM_LEN_CHK 0x00000002 /* Frame Length Checking */ +#define MAC2_HUGE_FRM_EN 0x00000004 /* Huge Frame Enable */ +#define MAC2_DLY_CRC 0x00000008 /* Delayed CRC Mode */ +#define MAC2_CRC_EN 0x00000010 /* Append CRC to every Frame */ +#define MAC2_PAD_EN 0x00000020 /* Pad all Short Frames */ +#define MAC2_VLAN_PAD_EN 0x00000040 /* VLAN Pad Enable */ +#define MAC2_ADET_PAD_EN 0x00000080 /* Auto Detect Pad Enable */ +#define MAC2_PPREAM_ENF 0x00000100 /* Pure Preamble Enforcement */ +#define MAC2_LPREAM_ENF 0x00000200 /* Long Preamble Enforcement */ +#define MAC2_NO_BACKOFF 0x00001000 /* No Backoff Algorithm */ +#define MAC2_BACK_PRESSURE 0x00002000 /* Backoff Presurre / No Backoff */ +#define MAC2_EXCESS_DEF 0x00004000 /* Excess Defer */ + +/* Back-to-Back Inter-Packet-Gap Register */ +#define IPGT_FULL_DUP 0x00000015 /* Recommended value for Full Duplex */ +#define IPGT_HALF_DUP 0x00000012 /* Recommended value for Half Duplex */ + +/* Non Back-to-Back Inter-Packet-Gap Register */ +#define IPGR_DEF 0x00000012 /* Recommended value */ + +/* Collision Window/Retry Register */ +#define CLRT_DEF 0x0000370F /* Default value */ + +/* PHY Support Register */ +#define SUPP_SPEED 0x00000100 /* Reduced MII Logic Current Speed */ +//#define SUPP_RES_RMII 0x00000800 /* Reset Reduced MII Logic */ +#define SUPP_RES_RMII 0x00000000 /* Reset Reduced MII Logic */ + +/* Test Register */ +#define TEST_SHCUT_PQUANTA 0x00000001 /* Shortcut Pause Quanta */ +#define TEST_TST_PAUSE 0x00000002 /* Test Pause */ +#define TEST_TST_BACKP 0x00000004 /* Test Back Pressure */ + +/* MII Management Configuration Register */ +#define MCFG_SCAN_INC 0x00000001 /* Scan Increment PHY Address */ +#define MCFG_SUPP_PREAM 0x00000002 /* Suppress Preamble */ +#define MCFG_CLK_SEL 0x0000003C /* Clock Select Mask */ +#define MCFG_RES_MII 0x00008000 /* Reset MII Management Hardware */ + +/* MII Management Command Register */ +#define MCMD_READ 0x00000001 /* MII Read */ +#define MCMD_SCAN 0x00000002 /* MII Scan continuously */ + +#define MII_WR_TOUT 0x00050000 /* MII Write timeout count */ +#define MII_RD_TOUT 0x00050000 /* MII Read timeout count */ + +/* MII Management Address Register */ +#define MADR_REG_ADR 0x0000001F /* MII Register Address Mask */ +#define MADR_PHY_ADR 0x00001F00 /* PHY Address Mask */ + +/* MII Management Indicators Register */ +#define MIND_BUSY 0x00000001 /* MII is Busy */ +#define MIND_SCAN 0x00000002 /* MII Scanning in Progress */ +#define MIND_NOT_VAL 0x00000004 /* MII Read Data not valid */ +#define MIND_MII_LINK_FAIL 0x00000008 /* MII Link Failed */ + +/* Command Register */ +#define CR_RX_EN 0x00000001 /* Enable Receive */ +#define CR_TX_EN 0x00000002 /* Enable Transmit */ +#define CR_REG_RES 0x00000008 /* Reset Host Registers */ +#define CR_TX_RES 0x00000010 /* Reset Transmit Datapath */ +#define CR_RX_RES 0x00000020 /* Reset Receive Datapath */ +#define CR_PASS_RUNT_FRM 0x00000040 /* Pass Runt Frames */ +#define CR_PASS_RX_FILT 0x00000080 /* Pass RX Filter */ +#define CR_TX_FLOW_CTRL 0x00000100 /* TX Flow Control */ +#define CR_RMII 0x00000200 /* Reduced MII Interface */ +#define CR_FULL_DUP 0x00000400 /* Full Duplex */ + +/* Status Register */ +#define SR_RX_EN 0x00000001 /* Enable Receive */ +#define SR_TX_EN 0x00000002 /* Enable Transmit */ + +/* Transmit Status Vector 0 Register */ +#define TSV0_CRC_ERR 0x00000001 /* CRC error */ +#define TSV0_LEN_CHKERR 0x00000002 /* Length Check Error */ +#define TSV0_LEN_OUTRNG 0x00000004 /* Length Out of Range */ +#define TSV0_DONE 0x00000008 /* Tramsmission Completed */ +#define TSV0_MCAST 0x00000010 /* Multicast Destination */ +#define TSV0_BCAST 0x00000020 /* Broadcast Destination */ +#define TSV0_PKT_DEFER 0x00000040 /* Packet Deferred */ +#define TSV0_EXC_DEFER 0x00000080 /* Excessive Packet Deferral */ +#define TSV0_EXC_COLL 0x00000100 /* Excessive Collision */ +#define TSV0_LATE_COLL 0x00000200 /* Late Collision Occured */ +#define TSV0_GIANT 0x00000400 /* Giant Frame */ +#define TSV0_UNDERRUN 0x00000800 /* Buffer Underrun */ +#define TSV0_BYTES 0x0FFFF000 /* Total Bytes Transferred */ +#define TSV0_CTRL_FRAME 0x10000000 /* Control Frame */ +#define TSV0_PAUSE 0x20000000 /* Pause Frame */ +#define TSV0_BACK_PRESS 0x40000000 /* Backpressure Method Applied */ +#define TSV0_VLAN 0x80000000 /* VLAN Frame */ + +/* Transmit Status Vector 1 Register */ +#define TSV1_BYTE_CNT 0x0000FFFF /* Transmit Byte Count */ +#define TSV1_COLL_CNT 0x000F0000 /* Transmit Collision Count */ + +/* Receive Status Vector Register */ +#define RSV_BYTE_CNT 0x0000FFFF /* Receive Byte Count */ +#define RSV_PKT_IGNORED 0x00010000 /* Packet Previously Ignored */ +#define RSV_RXDV_SEEN 0x00020000 /* RXDV Event Previously Seen */ +#define RSV_CARR_SEEN 0x00040000 /* Carrier Event Previously Seen */ +#define RSV_REC_CODEV 0x00080000 /* Receive Code Violation */ +#define RSV_CRC_ERR 0x00100000 /* CRC Error */ +#define RSV_LEN_CHKERR 0x00200000 /* Length Check Error */ +#define RSV_LEN_OUTRNG 0x00400000 /* Length Out of Range */ +#define RSV_REC_OK 0x00800000 /* Frame Received OK */ +#define RSV_MCAST 0x01000000 /* Multicast Frame */ +#define RSV_BCAST 0x02000000 /* Broadcast Frame */ +#define RSV_DRIB_NIBB 0x04000000 /* Dribble Nibble */ +#define RSV_CTRL_FRAME 0x08000000 /* Control Frame */ +#define RSV_PAUSE 0x10000000 /* Pause Frame */ +#define RSV_UNSUPP_OPC 0x20000000 /* Unsupported Opcode */ +#define RSV_VLAN 0x40000000 /* VLAN Frame */ + +/* Flow Control Counter Register */ +#define FCC_MIRR_CNT 0x0000FFFF /* Mirror Counter */ +#define FCC_PAUSE_TIM 0xFFFF0000 /* Pause Timer */ + +/* Flow Control Status Register */ +#define FCS_MIRR_CNT 0x0000FFFF /* Mirror Counter Current */ + +/* Receive Filter Control Register */ +#define RFC_UCAST_EN 0x00000001 /* Accept Unicast Frames Enable */ +#define RFC_BCAST_EN 0x00000002 /* Accept Broadcast Frames Enable */ +#define RFC_MCAST_EN 0x00000004 /* Accept Multicast Frames Enable */ +#define RFC_UCAST_HASH_EN 0x00000008 /* Accept Unicast Hash Filter Frames */ +#define RFC_MCAST_HASH_EN 0x00000010 /* Accept Multicast Hash Filter Fram.*/ +#define RFC_PERFECT_EN 0x00000020 /* Accept Perfect Match Enable */ +#define RFC_MAGP_WOL_EN 0x00001000 /* Magic Packet Filter WoL Enable */ +#define RFC_PFILT_WOL_EN 0x00002000 /* Perfect Filter WoL Enable */ + +/* Receive Filter WoL Status/Clear Registers */ +#define WOL_UCAST 0x00000001 /* Unicast Frame caused WoL */ +#define WOL_BCAST 0x00000002 /* Broadcast Frame caused WoL */ +#define WOL_MCAST 0x00000004 /* Multicast Frame caused WoL */ +#define WOL_UCAST_HASH 0x00000008 /* Unicast Hash Filter Frame WoL */ +#define WOL_MCAST_HASH 0x00000010 /* Multicast Hash Filter Frame WoL */ +#define WOL_PERFECT 0x00000020 /* Perfect Filter WoL */ +#define WOL_RX_FILTER 0x00000080 /* RX Filter caused WoL */ +#define WOL_MAG_PACKET 0x00000100 /* Magic Packet Filter caused WoL */ + +/* Interrupt Status/Enable/Clear/Set Registers */ +#define INT_RX_OVERRUN 0x00000001 /* Overrun Error in RX Queue */ +#define INT_RX_ERR 0x00000002 /* Receive Error */ +#define INT_RX_FIN 0x00000004 /* RX Finished Process Descriptors */ +#define INT_RX_DONE 0x00000008 /* Receive Done */ +#define INT_TX_UNDERRUN 0x00000010 /* Transmit Underrun */ +#define INT_TX_ERR 0x00000020 /* Transmit Error */ +#define INT_TX_FIN 0x00000040 /* TX Finished Process Descriptors */ +#define INT_TX_DONE 0x00000080 /* Transmit Done */ +#define INT_SOFT_INT 0x00001000 /* Software Triggered Interrupt */ +#define INT_WAKEUP 0x00002000 /* Wakeup Event Interrupt */ + +/* Power Down Register */ +#define PD_POWER_DOWN 0x80000000 /* Power Down MAC */ + +/* RX Descriptor Control Word */ +#define RCTRL_SIZE 0x000007FF /* Buffer size mask */ +#define RCTRL_INT 0x80000000 /* Generate RxDone Interrupt */ + +/* RX Status Hash CRC Word */ +#define RHASH_SA 0x000001FF /* Hash CRC for Source Address */ +#define RHASH_DA 0x001FF000 /* Hash CRC for Destination Address */ + +/* RX Status Information Word */ +#define RINFO_SIZE 0x000007FF /* Data size in bytes */ +#define RINFO_CTRL_FRAME 0x00040000 /* Control Frame */ +#define RINFO_VLAN 0x00080000 /* VLAN Frame */ +#define RINFO_FAIL_FILT 0x00100000 /* RX Filter Failed */ +#define RINFO_MCAST 0x00200000 /* Multicast Frame */ +#define RINFO_BCAST 0x00400000 /* Broadcast Frame */ +#define RINFO_CRC_ERR 0x00800000 /* CRC Error in Frame */ +#define RINFO_SYM_ERR 0x01000000 /* Symbol Error from PHY */ +#define RINFO_LEN_ERR 0x02000000 /* Length Error */ +#define RINFO_RANGE_ERR 0x04000000 /* Range Error (exceeded max. size) */ +#define RINFO_ALIGN_ERR 0x08000000 /* Alignment Error */ +#define RINFO_OVERRUN 0x10000000 /* Receive overrun */ +#define RINFO_NO_DESCR 0x20000000 /* No new Descriptor available */ +#define RINFO_LAST_FLAG 0x40000000 /* Last Fragment in Frame */ +#define RINFO_ERR 0x80000000 /* Error Occured (OR of all errors) */ + +//#define RINFO_ERR_MASK (RINFO_FAIL_FILT | RINFO_CRC_ERR | RINFO_SYM_ERR | RINFO_LEN_ERR | RINFO_ALIGN_ERR | RINFO_OVERRUN) +#define RINFO_ERR_MASK (RINFO_FAIL_FILT | RINFO_SYM_ERR | \ + RINFO_LEN_ERR | RINFO_ALIGN_ERR | RINFO_OVERRUN) + + +/* TX Descriptor Control Word */ +#define TCTRL_SIZE 0x000007FF /* Size of data buffer in bytes */ +#define TCTRL_OVERRIDE 0x04000000 /* Override Default MAC Registers */ +#define TCTRL_HUGE 0x08000000 /* Enable Huge Frame */ +#define TCTRL_PAD 0x10000000 /* Pad short Frames to 64 bytes */ +#define TCTRL_CRC 0x20000000 /* Append a hardware CRC to Frame */ +#define TCTRL_LAST 0x40000000 /* Last Descriptor for TX Frame */ +#define TCTRL_INT 0x80000000 /* Generate TxDone Interrupt */ + +/* TX Status Information Word */ +#define TINFO_COL_CNT 0x01E00000 /* Collision Count */ +#define TINFO_DEFER 0x02000000 /* Packet Deferred (not an error) */ +#define TINFO_EXCESS_DEF 0x04000000 /* Excessive Deferral */ +#define TINFO_EXCESS_COL 0x08000000 /* Excessive Collision */ +#define TINFO_LATE_COL 0x10000000 /* Late Collision Occured */ +#define TINFO_UNDERRUN 0x20000000 /* Transmit Underrun */ +#define TINFO_NO_DESCR 0x40000000 /* No new Descriptor available */ +#define TINFO_ERR 0x80000000 /* Error Occured (OR of all errors) */ + +/* ENET Device Revision ID */ +#define OLD_EMAC_MODULE_ID 0x39022000 /* Rev. ID for first rev '-' */ + +/* DP83848C PHY Registers */ +#define PHY_REG_BMCR 0x00 /* Basic Mode Control Register */ +#define PHY_REG_BMSR 0x01 /* Basic Mode Status Register */ +#define PHY_REG_IDR1 0x02 /* PHY Identifier 1 */ +#define PHY_REG_IDR2 0x03 /* PHY Identifier 2 */ +#define PHY_REG_ANAR 0x04 /* Auto-Negotiation Advertisement */ +#define PHY_REG_ANLPAR 0x05 /* Auto-Neg. Link Partner Abitily */ +#define PHY_REG_ANER 0x06 /* Auto-Neg. Expansion Register */ +#define PHY_REG_ANNPTR 0x07 /* Auto-Neg. Next Page TX */ + +/* PHY Extended Registers */ +#define PHY_REG_STS 0x10 /* Status Register */ +#define PHY_REG_MICR 0x11 /* MII Interrupt Control Register */ +#define PHY_REG_MISR 0x12 /* MII Interrupt Status Register */ +#define PHY_REG_FCSCR 0x14 /* False Carrier Sense Counter */ +#define PHY_REG_RECR 0x15 /* Receive Error Counter */ +#define PHY_REG_PCSR 0x16 /* PCS Sublayer Config. and Status */ +#define PHY_REG_RBR 0x17 /* RMII and Bypass Register */ +#define PHY_REG_LEDCR 0x18 /* LED Direct Control Register */ +#define PHY_REG_PHYCR 0x19 /* PHY Control Register */ +#define PHY_REG_10BTSCR 0x1A /* 10Base-T Status/Control Register */ +#define PHY_REG_CDCTRL1 0x1B /* CD Test Control and BIST Extens. */ +#define PHY_REG_EDCR 0x1D /* Energy Detect Control Register */ + +#define PHY_REG_SCSR 0x1F /* PHY Special Control/Status Register */ + +#define PHY_FULLD_100M 0x2100 /* Full Duplex 100Mbit */ +#define PHY_HALFD_100M 0x2000 /* Half Duplex 100Mbit */ +#define PHY_FULLD_10M 0x0100 /* Full Duplex 10Mbit */ +#define PHY_HALFD_10M 0x0000 /* Half Duplex 10MBit */ +#define PHY_AUTO_NEG 0x3000 /* Select Auto Negotiation */ + +#define DP83848C_DEF_ADR 0x0100 /* Default PHY device address */ +#define DP83848C_ID 0x20005C90 /* PHY Identifier - DP83848C */ + +#define LAN8720_ID 0x0007C0F0 /* PHY Identifier - LAN8720 */ + +#define PHY_STS_LINK 0x0001 /* PHY Status Link Mask */ +#define PHY_STS_SPEED 0x0002 /* PHY Status Speed Mask */ +#define PHY_STS_DUPLEX 0x0004 /* PHY Status Duplex Mask */ + +#define PHY_BMCR_RESET 0x8000 /* PHY Reset */ + +#define PHY_BMSR_LINK 0x0004 /* PHY BMSR Link valid */ + +#define PHY_SCSR_100MBIT 0x0008 /* Speed: 1=100 MBit, 0=10Mbit */ +#define PHY_SCSR_DUPLEX 0x0010 /* PHY Duplex Mask */ + + +static int phy_read(unsigned int PhyReg); +static int phy_write(unsigned int PhyReg, unsigned short Data); + +static void txdscr_init(void); +static void rxdscr_init(void); + +#if defined (__ICCARM__) +# define AHBSRAM1 +#elif defined(TOOLCHAIN_GCC_CR) +# define AHBSRAM1 __attribute__((section(".data.$RamPeriph32"))) +#else +# define AHBSRAM1 __attribute__((section("AHBSRAM1"),aligned)) +#endif + +AHBSRAM1 volatile uint8_t rxbuf[NUM_RX_FRAG][ETH_FRAG_SIZE]; +AHBSRAM1 volatile uint8_t txbuf[NUM_TX_FRAG][ETH_FRAG_SIZE]; +AHBSRAM1 volatile RX_DESC_TypeDef rxdesc[NUM_RX_FRAG]; +AHBSRAM1 volatile RX_STAT_TypeDef rxstat[NUM_RX_FRAG]; +AHBSRAM1 volatile TX_DESC_TypeDef txdesc[NUM_TX_FRAG]; +AHBSRAM1 volatile TX_STAT_TypeDef txstat[NUM_TX_FRAG]; + + +#if NEW_LOGIC +static int rx_consume_offset = -1; +static int tx_produce_offset = -1; +#else +static int send_doff = 0; +static int send_idx = -1; +static int send_size = 0; + +static int receive_soff = 0; +static int receive_idx = -1; +#endif + +static uint32_t phy_id = 0; + +static inline int rinc(int idx, int mod) { + ++idx; + idx %= mod; + return idx; +} + +//extern unsigned int SystemFrequency; +static inline unsigned int clockselect() { + if(SystemCoreClock < 10000000) { + return 1; + } else if(SystemCoreClock < 15000000) { + return 2; + } else if(SystemCoreClock < 20000000) { + return 3; + } else if(SystemCoreClock < 25000000) { + return 4; + } else if(SystemCoreClock < 35000000) { + return 5; + } else if(SystemCoreClock < 50000000) { + return 6; + } else if(SystemCoreClock < 70000000) { + return 7; + } else if(SystemCoreClock < 80000000) { + return 8; + } else if(SystemCoreClock < 90000000) { + return 9; + } else if(SystemCoreClock < 100000000) { + return 10; + } else if(SystemCoreClock < 120000000) { + return 11; + } else if(SystemCoreClock < 130000000) { + return 12; + } else if(SystemCoreClock < 140000000) { + return 13; + } else if(SystemCoreClock < 150000000) { + return 15; + } else if(SystemCoreClock < 160000000) { + return 16; + } else { + return 0; + } +} + +#ifndef min +#define min(x, y) (((x)<(y))?(x):(y)) +#endif + +/*---------------------------------------------------------------------------- + Ethernet Device initialize + *----------------------------------------------------------------------------*/ +int ethernet_init() { + int regv, tout; + char mac[ETHERNET_ADDR_SIZE]; + unsigned int clock = clockselect(); + + LPC_SC->PCONP |= 0x40000000; /* Power Up the EMAC controller. */ + + LPC_PINCON->PINSEL2 = 0x50150105; /* Enable P1 Ethernet Pins. */ + LPC_PINCON->PINSEL3 = (LPC_PINCON->PINSEL3 & ~0x0000000F) | 0x00000005; + + /* Reset all EMAC internal modules. */ + LPC_EMAC->MAC1 = MAC1_RES_TX | MAC1_RES_MCS_TX | MAC1_RES_RX | + MAC1_RES_MCS_RX | MAC1_SIM_RES | MAC1_SOFT_RES; + LPC_EMAC->Command = CR_REG_RES | CR_TX_RES | CR_RX_RES | CR_PASS_RUNT_FRM; + + for(tout = 100; tout; tout--) __NOP(); /* A short delay after reset. */ + + LPC_EMAC->MAC1 = MAC1_PASS_ALL; /* Initialize MAC control registers. */ + LPC_EMAC->MAC2 = MAC2_CRC_EN | MAC2_PAD_EN; + LPC_EMAC->MAXF = ETH_MAX_FLEN; + LPC_EMAC->CLRT = CLRT_DEF; + LPC_EMAC->IPGR = IPGR_DEF; + + LPC_EMAC->Command = CR_RMII | CR_PASS_RUNT_FRM; /* Enable Reduced MII interface. */ + + LPC_EMAC->MCFG = (clock << 0x2) & MCFG_CLK_SEL; /* Set clock */ + LPC_EMAC->MCFG |= MCFG_RES_MII; /* and reset */ + + for(tout = 100; tout; tout--) __NOP(); /* A short delay */ + + LPC_EMAC->MCFG = (clock << 0x2) & MCFG_CLK_SEL; + LPC_EMAC->MCMD = 0; + + LPC_EMAC->SUPP = SUPP_RES_RMII; /* Reset Reduced MII Logic. */ + + for (tout = 100; tout; tout--) __NOP(); /* A short delay */ + + LPC_EMAC->SUPP = 0; + + phy_write(PHY_REG_BMCR, PHY_BMCR_RESET); /* perform PHY reset */ + for(tout = 0x20000; ; tout--) { /* Wait for hardware reset to end. */ + regv = phy_read(PHY_REG_BMCR); + if(regv < 0 || tout == 0) { + return -1; /* Error */ + } + if(!(regv & PHY_BMCR_RESET)) { + break; /* Reset complete. */ + } + } + + phy_id = (phy_read(PHY_REG_IDR1) << 16); + phy_id |= (phy_read(PHY_REG_IDR2) & 0XFFF0); + + if (phy_id != DP83848C_ID && phy_id != LAN8720_ID) { + error("Unknown Ethernet PHY (%x)", (unsigned int)phy_id); + } + + ethernet_set_link(-1, 0); + + /* Set the Ethernet MAC Address registers */ + ethernet_address(mac); + LPC_EMAC->SA0 = ((uint32_t)mac[5] << 8) | (uint32_t)mac[4]; + LPC_EMAC->SA1 = ((uint32_t)mac[3] << 8) | (uint32_t)mac[2]; + LPC_EMAC->SA2 = ((uint32_t)mac[1] << 8) | (uint32_t)mac[0]; + + txdscr_init(); /* initialize DMA TX Descriptor */ + rxdscr_init(); /* initialize DMA RX Descriptor */ + + LPC_EMAC->RxFilterCtrl = RFC_UCAST_EN | RFC_MCAST_EN | RFC_BCAST_EN | RFC_PERFECT_EN; + /* Receive Broadcast, Perfect Match Packets */ + + LPC_EMAC->IntEnable = INT_RX_DONE | INT_TX_DONE; /* Enable EMAC interrupts. */ + LPC_EMAC->IntClear = 0xFFFF; /* Reset all interrupts */ + + + LPC_EMAC->Command |= (CR_RX_EN | CR_TX_EN); /* Enable receive and transmit mode of MAC Ethernet core */ + LPC_EMAC->MAC1 |= MAC1_REC_EN; + +#if NEW_LOGIC + rx_consume_offset = -1; + tx_produce_offset = -1; +#else + send_doff = 0; + send_idx = -1; + send_size = 0; + + receive_soff = 0; + receive_idx = -1; +#endif + + return 0; +} + +/*---------------------------------------------------------------------------- + Ethernet Device Uninitialize + *----------------------------------------------------------------------------*/ +void ethernet_free() { + LPC_EMAC->IntEnable &= ~(INT_RX_DONE | INT_TX_DONE); + LPC_EMAC->IntClear = 0xFFFF; + + LPC_SC->PCONP &= ~0x40000000; /* Power down the EMAC controller. */ + + LPC_PINCON->PINSEL2 &= ~0x50150105; /* Disable P1 ethernet pins. */ + LPC_PINCON->PINSEL3 = (LPC_PINCON->PINSEL3 & ~0x0000000F) | 0x00000000; +} + +// if(TxProduceIndex == TxConsumeIndex) buffer array is empty +// if(TxProduceIndex == TxConsumeIndex - 1) buffer is full, should not fill +// TxProduceIndex - The buffer that will/is being fileld by driver, s/w increment +// TxConsumeIndex - The buffer that will/is beign sent by hardware + +int ethernet_write(const char *data, int slen) { + +#if NEW_LOGIC + + if(tx_produce_offset < 0) { // mark as active if not already + tx_produce_offset = 0; + } + + int index = LPC_EMAC->TxProduceIndex; + + int remaining = ETH_MAX_FLEN - tx_produce_offset - 4; // bytes written plus checksum + int requested = slen; + int ncopy = min(remaining, requested); + + void *pdst = (void *)(txdesc[index].Packet + tx_produce_offset); + void *psrc = (void *)(data); + + if(ncopy > 0 ){ + if(data != NULL) { + memcpy(pdst, psrc, ncopy); + } else { + memset(pdst, 0, ncopy); + } + } + + tx_produce_offset += ncopy; + + return ncopy; + +#else + void *pdst, *psrc; + const int dlen = ETH_FRAG_SIZE; + int copy = 0; + int soff = 0; + + if(send_idx == -1) { + send_idx = LPC_EMAC->TxProduceIndex; + } + + if(slen + send_doff > ethernet_MTU_SIZE) { + return -1; + } + + do { + copy = min(slen - soff, dlen - send_doff); + pdst = (void *)(txdesc[send_idx].Packet + send_doff); + psrc = (void *)(data + soff); + if(send_doff + copy > ETH_FRAG_SIZE) { + txdesc[send_idx].Ctrl = (send_doff-1) | (TCTRL_INT); + send_idx = rinc(send_idx, NUM_TX_FRAG); + send_doff = 0; + } + + if(data != NULL) { + memcpy(pdst, psrc, copy); + } else { + memset(pdst, 0, copy); + } + + soff += copy; + send_doff += copy; + send_size += copy; + } while(soff != slen); + + return soff; +#endif +} + +int ethernet_send() { + +#if NEW_LOGIC + if(tx_produce_offset < 0) { // no buffer active + return -1; + } + + // ensure there is a link + if(!ethernet_link()) { + return -2; + } + + // we have been writing in to a buffer, so finalise it + int size = tx_produce_offset; + int index = LPC_EMAC->TxProduceIndex; + txdesc[index].Ctrl = (tx_produce_offset-1) | (TCTRL_INT | TCTRL_LAST); + + // Increment ProduceIndex to allow it to be sent + // We can only do this if the next slot is free + int next = rinc(index, NUM_TX_FRAG); + while(next == LPC_EMAC->TxConsumeIndex) { + for(int i=0; i<1000; i++) { __NOP(); } + } + + LPC_EMAC->TxProduceIndex = next; + tx_produce_offset = -1; + return size; + +#else + int s = send_size; + txdesc[send_idx].Ctrl = (send_doff-1) | (TCTRL_INT | TCTRL_LAST); + send_idx = rinc(send_idx, NUM_TX_FRAG); + LPC_EMAC->TxProduceIndex = send_idx; + send_doff = 0; + send_idx = -1; + send_size = 0; + return s; +#endif +} + +// RxConsmeIndex - The index of buffer the driver will/is reading from. Driver should inc once read +// RxProduceIndex - The index of buffer that will/is being filled by MAC. H/w will inc once rxd +// +// if(RxConsumeIndex == RxProduceIndex) buffer array is empty +// if(RxConsumeIndex == RxProduceIndex + 1) buffer array is full + +// Recevies an arrived ethernet packet. +// Receiving an ethernet packet will drop the last received ethernet packet +// and make a new ethernet packet ready to read. +// Returns size of packet, else 0 if nothing to receive + +// We read from RxConsumeIndex from position rx_consume_offset +// if rx_consume_offset < 0, then we have not recieved the RxConsumeIndex packet for reading +// rx_consume_offset = -1 // no frame +// rx_consume_offset = 0 // start of frame +// Assumption: A fragment should alway be a whole frame + +int ethernet_receive() { +#if NEW_LOGIC + + // if we are currently reading a valid RxConsume buffer, increment to the next one + if(rx_consume_offset >= 0) { + LPC_EMAC->RxConsumeIndex = rinc(LPC_EMAC->RxConsumeIndex, NUM_RX_FRAG); + } + + // if the buffer is empty, mark it as no valid buffer + if(LPC_EMAC->RxConsumeIndex == LPC_EMAC->RxProduceIndex) { + rx_consume_offset = -1; + return 0; + } + + uint32_t info = rxstat[LPC_EMAC->RxConsumeIndex].Info; + rx_consume_offset = 0; + + // check if it is not marked as last or for errors + if(!(info & RINFO_LAST_FLAG) || (info & RINFO_ERR_MASK)) { + return -1; + } + + int size = (info & RINFO_SIZE) + 1; + return size - 4; // don't include checksum bytes + +#else + if(receive_idx == -1) { + receive_idx = LPC_EMAC->RxConsumeIndex; + } else { + while(!(rxstat[receive_idx].Info & RINFO_LAST_FLAG) && ((uint32_t)receive_idx != LPC_EMAC->RxProduceIndex)) { + receive_idx = rinc(receive_idx, NUM_RX_FRAG); + } + unsigned int info = rxstat[receive_idx].Info; + int slen = (info & RINFO_SIZE) + 1; + + if(slen > ethernet_MTU_SIZE || (info & RINFO_ERR_MASK)) { + /* Invalid frame, ignore it and free buffer. */ + receive_idx = rinc(receive_idx, NUM_RX_FRAG); + } + receive_idx = rinc(receive_idx, NUM_RX_FRAG); + receive_soff = 0; + + LPC_EMAC->RxConsumeIndex = receive_idx; + } + + if((uint32_t)receive_idx == LPC_EMAC->RxProduceIndex) { + receive_idx = -1; + return 0; + } + + return (rxstat[receive_idx].Info & RINFO_SIZE) - 3; +#endif +} + +// Read from an recevied ethernet packet. +// After receive returnd a number bigger than 0 it is +// possible to read bytes from this packet. +// Read will write up to size bytes into data. +// It is possible to use read multible times. +// Each time read will start reading after the last read byte before. + +int ethernet_read(char *data, int dlen) { +#if NEW_LOGIC + // Check we have a valid buffer to read + if(rx_consume_offset < 0) { + return 0; + } + + // Assume 1 fragment block + uint32_t info = rxstat[LPC_EMAC->RxConsumeIndex].Info; + int size = (info & RINFO_SIZE) + 1 - 4; // exclude checksum + + int remaining = size - rx_consume_offset; + int requested = dlen; + int ncopy = min(remaining, requested); + + void *psrc = (void *)(rxdesc[LPC_EMAC->RxConsumeIndex].Packet + rx_consume_offset); + void *pdst = (void *)(data); + + if(data != NULL && ncopy > 0) { + memcpy(pdst, psrc, ncopy); + } + + rx_consume_offset += ncopy; + + return ncopy; +#else + int slen; + int copy = 0; + unsigned int more; + unsigned int info; + void *pdst, *psrc; + int doff = 0; + + if((uint32_t)receive_idx == LPC_EMAC->RxProduceIndex || receive_idx == -1) { + return 0; + } + + do { + info = rxstat[receive_idx].Info; + more = !(info & RINFO_LAST_FLAG); + slen = (info & RINFO_SIZE) + 1; + + if(slen > ethernet_MTU_SIZE || (info & RINFO_ERR_MASK)) { + /* Invalid frame, ignore it and free buffer. */ + receive_idx = rinc(receive_idx, NUM_RX_FRAG); + } else { + + copy = min(slen - receive_soff, dlen - doff); + psrc = (void *)(rxdesc[receive_idx].Packet + receive_soff); + pdst = (void *)(data + doff); + + if(data != NULL) { + /* check if Buffer available */ + memcpy(pdst, psrc, copy); + } + + receive_soff += copy; + doff += copy; + + if((more && (receive_soff == slen))) { + receive_idx = rinc(receive_idx, NUM_RX_FRAG); + receive_soff = 0; + } + } + } while(more && !(doff == dlen) && !receive_soff); + + return doff; +#endif +} + +int ethernet_link(void) { + if (phy_id == DP83848C_ID) { + return (phy_read(PHY_REG_STS) & PHY_STS_LINK); + } + else { // LAN8720_ID + return (phy_read(PHY_REG_BMSR) & PHY_BMSR_LINK); + } +} + +static int phy_write(unsigned int PhyReg, unsigned short Data) { + unsigned int timeOut; + + LPC_EMAC->MADR = DP83848C_DEF_ADR | PhyReg; + LPC_EMAC->MWTD = Data; + + for(timeOut = 0; timeOut < MII_WR_TOUT; timeOut++) { /* Wait until operation completed */ + if((LPC_EMAC->MIND & MIND_BUSY) == 0) { + return 0; + } + } + + return -1; +} + +static int phy_read(unsigned int PhyReg) { + unsigned int timeOut; + + LPC_EMAC->MADR = DP83848C_DEF_ADR | PhyReg; + LPC_EMAC->MCMD = MCMD_READ; + + for(timeOut = 0; timeOut < MII_RD_TOUT; timeOut++) { /* Wait until operation completed */ + if((LPC_EMAC->MIND & MIND_BUSY) == 0) { + LPC_EMAC->MCMD = 0; + return LPC_EMAC->MRDD; /* Return a 16-bit value. */ + } + } + + return -1; +} + + +static void txdscr_init() { + int i; + + for(i = 0; i < NUM_TX_FRAG; i++) { + txdesc[i].Packet = (uint32_t)&txbuf[i]; + txdesc[i].Ctrl = 0; + txstat[i].Info = 0; + } + + LPC_EMAC->TxDescriptor = (uint32_t)txdesc; /* Set EMAC Transmit Descriptor Registers. */ + LPC_EMAC->TxStatus = (uint32_t)txstat; + LPC_EMAC->TxDescriptorNumber = NUM_TX_FRAG-1; + + LPC_EMAC->TxProduceIndex = 0; /* Tx Descriptors Point to 0 */ +} + +static void rxdscr_init() { + int i; + + for(i = 0; i < NUM_RX_FRAG; i++) { + rxdesc[i].Packet = (uint32_t)&rxbuf[i]; + rxdesc[i].Ctrl = RCTRL_INT | (ETH_FRAG_SIZE-1); + rxstat[i].Info = 0; + rxstat[i].HashCRC = 0; + } + + LPC_EMAC->RxDescriptor = (uint32_t)rxdesc; /* Set EMAC Receive Descriptor Registers. */ + LPC_EMAC->RxStatus = (uint32_t)rxstat; + LPC_EMAC->RxDescriptorNumber = NUM_RX_FRAG-1; + + LPC_EMAC->RxConsumeIndex = 0; /* Rx Descriptors Point to 0 */ +} + +void ethernet_address(char *mac) { + mbed_mac_address(mac); +} + +void ethernet_set_link(int speed, int duplex) { + unsigned short phy_data; + int tout; + + if((speed < 0) || (speed > 1)) { + phy_data = PHY_AUTO_NEG; + } else { + phy_data = (((unsigned short) speed << 13) | + ((unsigned short) duplex << 8)); + } + + phy_write(PHY_REG_BMCR, phy_data); + + for(tout = 100; tout; tout--) { __NOP(); } /* A short delay */ + + switch(phy_id) { + case DP83848C_ID: + phy_data = phy_read(PHY_REG_STS); + + if(phy_data & PHY_STS_DUPLEX) { + LPC_EMAC->MAC2 |= MAC2_FULL_DUP; + LPC_EMAC->Command |= CR_FULL_DUP; + LPC_EMAC->IPGT = IPGT_FULL_DUP; + } else { + LPC_EMAC->MAC2 &= ~MAC2_FULL_DUP; + LPC_EMAC->Command &= ~CR_FULL_DUP; + LPC_EMAC->IPGT = IPGT_HALF_DUP; + } + + if(phy_data & PHY_STS_SPEED) { + LPC_EMAC->SUPP &= ~SUPP_SPEED; + } else { + LPC_EMAC->SUPP |= SUPP_SPEED; + } + break; + + case LAN8720_ID: + phy_data = phy_read(PHY_REG_SCSR); + + if (phy_data & PHY_SCSR_DUPLEX) { + LPC_EMAC->MAC2 |= MAC2_FULL_DUP; + LPC_EMAC->Command |= CR_FULL_DUP; + LPC_EMAC->IPGT = IPGT_FULL_DUP; + } else { + LPC_EMAC->Command &= ~CR_FULL_DUP; + LPC_EMAC->IPGT = IPGT_HALF_DUP; + } + + if(phy_data & PHY_SCSR_100MBIT) { + LPC_EMAC->SUPP |= SUPP_SPEED; + } else { + LPC_EMAC->SUPP &= ~SUPP_SPEED; + } + break; + } +} diff --git a/targets/TARGET_NXP/TARGET_LPC23XX/gpio_api.c b/targets/TARGET_NXP/TARGET_LPC23XX/gpio_api.c new file mode 100644 index 00000000000..10ac3664fca --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC23XX/gpio_api.c @@ -0,0 +1,53 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * 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. + */ +#include "mbed_assert.h" +#include "gpio_api.h" +#include "pinmap.h" + +uint32_t gpio_set(PinName pin) { + LPC_SC->SCS |= 1; // High speed GPIO is enabled on ports 0 and 1 + + pin_function(pin, 0); + + return (1 << ((int)pin & 0x1F)); +} + +void gpio_init(gpio_t *obj, PinName pin) { + if (pin == (PinName)NC) + return; + obj->pin = pin; + obj->mask = gpio_set(pin); + + LPC_GPIO_TypeDef *port_reg = (LPC_GPIO_TypeDef *) ((int)pin & ~0x1F); + + obj->reg_set = &port_reg->FIOSET; + obj->reg_clr = &port_reg->FIOCLR; + obj->reg_in = &port_reg->FIOPIN; + obj->reg_dir = &port_reg->FIODIR; +} + +void gpio_mode(gpio_t *obj, PinMode mode) { + pin_mode(obj->pin, mode); +} + +void gpio_dir(gpio_t *obj, PinDirection direction) { + if (obj->pin == (PinName)NC) + return; + switch (direction) { + case PIN_INPUT : *obj->reg_dir &= ~obj->mask; break; + case PIN_OUTPUT: *obj->reg_dir |= obj->mask; break; + } +} diff --git a/targets/TARGET_NXP/TARGET_LPC23XX/gpio_irq_api.c b/targets/TARGET_NXP/TARGET_LPC23XX/gpio_irq_api.c new file mode 100644 index 00000000000..40fcaa6dbe0 --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC23XX/gpio_irq_api.c @@ -0,0 +1,154 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * 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. + */ +#include "gpio_irq_api.h" +#include "mbed_error.h" +#include +#include "cmsis.h" + +#define CHANNEL_NUM 48 + +static uint32_t channel_ids[CHANNEL_NUM] = {0}; +static gpio_irq_handler irq_handler; + +static void handle_interrupt_in(void) { + // Read in all current interrupt registers. We do this once as the + // GPIO interrupt registers are on the APB bus, and this is slow. + uint32_t rise0 = LPC_GPIOINT->IO0IntStatR; + uint32_t fall0 = LPC_GPIOINT->IO0IntStatF; + uint32_t rise2 = LPC_GPIOINT->IO2IntStatR; + uint32_t fall2 = LPC_GPIOINT->IO2IntStatF; + uint32_t mask0 = 0; + uint32_t mask2 = 0; + int i; + + // P0.0-0.31 + for (i = 0; i < 32; i++) { + uint32_t pmask = (1 << i); + if (rise0 & pmask) { + mask0 |= pmask; + if (channel_ids[i] != 0) + irq_handler(channel_ids[i], IRQ_RISE); + } + if (fall0 & pmask) { + mask0 |= pmask; + if (channel_ids[i] != 0) + irq_handler(channel_ids[i], IRQ_FALL); + } + } + + // P2.0-2.15 + for (i = 0; i < 16; i++) { + uint32_t pmask = (1 << i); + int channel_index = i + 32; + if (rise2 & pmask) { + mask2 |= pmask; + if (channel_ids[channel_index] != 0) + irq_handler(channel_ids[channel_index], IRQ_RISE); + } + if (fall2 & pmask) { + mask2 |= pmask; + if (channel_ids[channel_index] != 0) + irq_handler(channel_ids[channel_index], IRQ_FALL); + } + } + + // Clear the interrupts we just handled + LPC_GPIOINT->IO0IntClr = mask0; + LPC_GPIOINT->IO2IntClr = mask2; +} + +int gpio_irq_init(gpio_irq_t *obj, PinName pin, gpio_irq_handler handler, uint32_t id) { + if (pin == NC) return -1; + + irq_handler = handler; + + obj->port = (int)pin & ~0x1F; + obj->pin = (int)pin & 0x1F; + + // Interrupts available only on GPIO0 and GPIO2 + if (obj->port != LPC_GPIO0_BASE && obj->port != LPC_GPIO2_BASE) { + error("pins on this port cannot generate interrupts"); + } + + // put us in the interrupt table + int index = (obj->port == LPC_GPIO0_BASE) ? obj->pin : obj->pin + 32; + channel_ids[index] = id; + obj->ch = index; + + NVIC_SetVector(EINT3_IRQn, (uint32_t)handle_interrupt_in); + NVIC_EnableIRQ(EINT3_IRQn); + + return 0; +} + +void gpio_irq_free(gpio_irq_t *obj) { + channel_ids[obj->ch] = 0; +} + +void gpio_irq_set(gpio_irq_t *obj, gpio_irq_event event, uint32_t enable) { + // ensure nothing is pending + switch (obj->port) { + case LPC_GPIO0_BASE: LPC_GPIOINT->IO0IntClr = 1 << obj->pin; break; + case LPC_GPIO2_BASE: LPC_GPIOINT->IO2IntClr = 1 << obj->pin; break; + } + + // enable the pin interrupt + if (event == IRQ_RISE) { + switch (obj->port) { + case LPC_GPIO0_BASE: + if (enable) { + LPC_GPIOINT->IO0IntEnR |= 1 << obj->pin; + } else { + LPC_GPIOINT->IO0IntEnR &= ~(1 << obj->pin); + } + break; + case LPC_GPIO2_BASE: + if (enable) { + LPC_GPIOINT->IO2IntEnR |= 1 << obj->pin; + } else { + LPC_GPIOINT->IO2IntEnR &= ~(1 << obj->pin); + } + break; + } + } else { + switch (obj->port) { + case LPC_GPIO0_BASE: + if (enable) { + LPC_GPIOINT->IO0IntEnF |= 1 << obj->pin; + } else { + LPC_GPIOINT->IO0IntEnF &= ~(1 << obj->pin); + } + break; + + case LPC_GPIO2_BASE: + if (enable) { + LPC_GPIOINT->IO2IntEnF |= 1 << obj->pin; + } else { + LPC_GPIOINT->IO2IntEnF &= ~(1 << obj->pin); + } + break; + } + } +} + +void gpio_irq_enable(gpio_irq_t *obj) { + NVIC_EnableIRQ(EINT3_IRQn); +} + +void gpio_irq_disable(gpio_irq_t *obj) { + NVIC_DisableIRQ(EINT3_IRQn); +} + diff --git a/targets/TARGET_NXP/TARGET_LPC23XX/gpio_object.h b/targets/TARGET_NXP/TARGET_LPC23XX/gpio_object.h new file mode 100644 index 00000000000..fe6d6c1e05c --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC23XX/gpio_object.h @@ -0,0 +1,56 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * 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. + */ +#ifndef MBED_GPIO_OBJECT_H +#define MBED_GPIO_OBJECT_H + +#include "mbed_assert.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct { + PinName pin; + uint32_t mask; + + __IO uint32_t *reg_dir; + __IO uint32_t *reg_set; + __IO uint32_t *reg_clr; + __I uint32_t *reg_in; +} gpio_t; + +static inline void gpio_write(gpio_t *obj, int value) { + MBED_ASSERT(obj->pin != (PinName)NC); + if (value) + *obj->reg_set = obj->mask; + else + *obj->reg_clr = obj->mask; +} + +static inline int gpio_read(gpio_t *obj) { + MBED_ASSERT(obj->pin != (PinName)NC); + return ((*obj->reg_in & obj->mask) ? 1 : 0); +} + +static inline int gpio_is_connected(const gpio_t *obj) { + return obj->pin != (PinName)NC; +} + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/targets/TARGET_NXP/TARGET_LPC23XX/i2c_api.c b/targets/TARGET_NXP/TARGET_LPC23XX/i2c_api.c new file mode 100644 index 00000000000..e24978dcb22 --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC23XX/i2c_api.c @@ -0,0 +1,399 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * 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. + */ +#include "i2c_api.h" +#include "cmsis.h" +#include "pinmap.h" + +static const PinMap PinMap_I2C_SDA[] = { + {P0_0 , I2C_1, 3}, + {P0_10, I2C_2, 2}, + {P0_19, I2C_1, 3}, + {P0_27, I2C_0, 1}, + {NC , NC , 0} +}; + +static const PinMap PinMap_I2C_SCL[] = { + {P0_1 , I2C_1, 3}, + {P0_11, I2C_2, 2}, + {P0_20, I2C_1, 3}, + {P0_28, I2C_0, 1}, + {NC , NC, 0} +}; + +#define I2C_CONSET(x) (x->i2c->I2CONSET) +#define I2C_CONCLR(x) (x->i2c->I2CONCLR) +#define I2C_STAT(x) (x->i2c->I2STAT) +#define I2C_DAT(x) (x->i2c->I2DAT) +#define I2C_SCLL(x, val) (x->i2c->I2SCLL = val) +#define I2C_SCLH(x, val) (x->i2c->I2SCLH = val) + +static const uint32_t I2C_addr_offset[2][4] = { + {0x0C, 0x20, 0x24, 0x28}, + {0x30, 0x34, 0x38, 0x3C} +}; + +static inline void i2c_conclr(i2c_t *obj, int start, int stop, int interrupt, int acknowledge) { + I2C_CONCLR(obj) = (start << 5) + | (stop << 4) + | (interrupt << 3) + | (acknowledge << 2); +} + +static inline void i2c_conset(i2c_t *obj, int start, int stop, int interrupt, int acknowledge) { + I2C_CONSET(obj) = (start << 5) + | (stop << 4) + | (interrupt << 3) + | (acknowledge << 2); +} + +// Clear the Serial Interrupt (SI) +static inline void i2c_clear_SI(i2c_t *obj) { + i2c_conclr(obj, 0, 0, 1, 0); +} + +static inline int i2c_status(i2c_t *obj) { + return I2C_STAT(obj); +} + +// Wait until the Serial Interrupt (SI) is set +static int i2c_wait_SI(i2c_t *obj) { + int timeout = 0; + while (!(I2C_CONSET(obj) & (1 << 3))) { + timeout++; + if (timeout > 100000) return -1; + } + return 0; +} + +static inline void i2c_interface_enable(i2c_t *obj) { + I2C_CONSET(obj) = 0x40; +} + +static inline void i2c_power_enable(i2c_t *obj) { + switch ((int)obj->i2c) { + case I2C_0: LPC_SC->PCONP |= 1 << 7; break; + case I2C_1: LPC_SC->PCONP |= 1 << 19; break; + case I2C_2: LPC_SC->PCONP |= 1 << 26; break; + } +} + +void i2c_init(i2c_t *obj, PinName sda, PinName scl) { + // determine the SPI to use + I2CName i2c_sda = (I2CName)pinmap_peripheral(sda, PinMap_I2C_SDA); + I2CName i2c_scl = (I2CName)pinmap_peripheral(scl, PinMap_I2C_SCL); + obj->i2c = (LPC_I2C_TypeDef *)pinmap_merge(i2c_sda, i2c_scl); + MBED_ASSERT((int)obj->i2c != NC); + + // enable power + i2c_power_enable(obj); + + // set default frequency at 100k + i2c_frequency(obj, 100000); + i2c_conclr(obj, 1, 1, 1, 1); + i2c_interface_enable(obj); + + pinmap_pinout(sda, PinMap_I2C_SDA); + pinmap_pinout(scl, PinMap_I2C_SCL); +} + +inline int i2c_start(i2c_t *obj) { + int status = 0; + int isInterrupted = I2C_CONSET(obj) & (1 << 3); + + // 8.1 Before master mode can be entered, I2CON must be initialised to: + // - I2EN STA STO SI AA - - + // - 1 0 0 x x - - + // if AA = 0, it can't enter slave mode + i2c_conclr(obj, 1, 1, 0, 1); + + // The master mode may now be entered by setting the STA bit + // this will generate a start condition when the bus becomes free + i2c_conset(obj, 1, 0, 0, 1); + // Clearing SI bit when it wasn't set on entry can jump past state + // 0x10 or 0x08 and erroneously send uninitialized slave address. + if (isInterrupted) + i2c_clear_SI(obj); + + i2c_wait_SI(obj); + status = i2c_status(obj); + + // Clear start bit now that it's transmitted + i2c_conclr(obj, 1, 0, 0, 0); + return status; +} + +inline int i2c_stop(i2c_t *obj) { + int timeout = 0; + + // write the stop bit + i2c_conset(obj, 0, 1, 0, 0); + i2c_clear_SI(obj); + + // wait for STO bit to reset + while (I2C_CONSET(obj) & (1 << 4)) { + timeout ++; + if (timeout > 100000) return 1; + } + + return 0; +} + +static inline int i2c_do_write(i2c_t *obj, int value, uint8_t addr) { + // write the data + I2C_DAT(obj) = value; + + // clear SI to init a send + i2c_clear_SI(obj); + + // wait and return status + i2c_wait_SI(obj); + return i2c_status(obj); +} + +static inline int i2c_do_read(i2c_t *obj, int last) { + // we are in state 0x40 (SLA+R tx'd) or 0x50 (data rx'd and ack) + if (last) { + i2c_conclr(obj, 0, 0, 0, 1); // send a NOT ACK + } else { + i2c_conset(obj, 0, 0, 0, 1); // send a ACK + } + + // accept byte + i2c_clear_SI(obj); + + // wait for it to arrive + i2c_wait_SI(obj); + + // return the data + return (I2C_DAT(obj) & 0xFF); +} + +void i2c_frequency(i2c_t *obj, int hz) { + // [TODO] set pclk to /4 + uint32_t PCLK = SystemCoreClock / 4; + + uint32_t pulse = PCLK / (hz * 2); + + // I2C Rate + I2C_SCLL(obj, pulse); + I2C_SCLH(obj, pulse); +} + +// The I2C does a read or a write as a whole operation +// There are two types of error conditions it can encounter +// 1) it can not obtain the bus +// 2) it gets error responses at part of the transmission +// +// We tackle them as follows: +// 1) we retry until we get the bus. we could have a "timeout" if we can not get it +// which basically turns it in to a 2) +// 2) on error, we use the standard error mechanisms to report/debug +// +// Therefore an I2C transaction should always complete. If it doesn't it is usually +// because something is setup wrong (e.g. wiring), and we don't need to programatically +// check for that +int i2c_read(i2c_t *obj, int address, char *data, int length, int stop) { + int count, status; + + status = i2c_start(obj); + + if ((status != 0x10) && (status != 0x08)) { + i2c_stop(obj); + return I2C_ERROR_BUS_BUSY; + } + + status = i2c_do_write(obj, (address | 0x01), 1); + if (status != 0x40) { + i2c_stop(obj); + return I2C_ERROR_NO_SLAVE; + } + + // Read in all except last byte + for (count = 0; count < (length - 1); count++) { + int value = i2c_do_read(obj, 0); + status = i2c_status(obj); + if (status != 0x50) { + i2c_stop(obj); + return count; + } + data[count] = (char) value; + } + + // read in last byte + int value = i2c_do_read(obj, 1); + status = i2c_status(obj); + if (status != 0x58) { + i2c_stop(obj); + return length - 1; + } + + data[count] = (char) value; + + // If not repeated start, send stop. + if (stop) { + i2c_stop(obj); + } + + return length; +} + +int i2c_write(i2c_t *obj, int address, const char *data, int length, int stop) { + int i, status; + + status = i2c_start(obj); + + if ((status != 0x10) && (status != 0x08)) { + i2c_stop(obj); + return I2C_ERROR_BUS_BUSY; + } + + status = i2c_do_write(obj, (address & 0xFE), 1); + if (status != 0x18) { + i2c_stop(obj); + return I2C_ERROR_NO_SLAVE; + } + + for (i=0; i= 0) && (idx <= 3)) { + addr = ((uint32_t)obj->i2c) + I2C_addr_offset[0][idx]; + *((uint32_t *) addr) = address & 0xFF; + } +} diff --git a/targets/TARGET_NXP/TARGET_LPC23XX/objects.h b/targets/TARGET_NXP/TARGET_LPC23XX/objects.h new file mode 100644 index 00000000000..41d717adc60 --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC23XX/objects.h @@ -0,0 +1,78 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * 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. + */ +#ifndef MBED_OBJECTS_H +#define MBED_OBJECTS_H + +#include "cmsis.h" +#include "PortNames.h" +#include "PeripheralNames.h" +#include "PinNames.h" + +#ifdef __cplusplus +extern "C" { +#endif + +struct gpio_irq_s { + uint32_t port; + uint32_t pin; + uint32_t ch; +}; + +struct port_s { + __IO uint32_t *reg_dir; + __IO uint32_t *reg_out; + __I uint32_t *reg_in; + PortName port; + uint32_t mask; +}; + +struct pwmout_s { + __IO uint32_t *MR; + PWMName pwm; +}; + +struct serial_s { + LPC_UART_TypeDef *uart; + int index; +}; + +struct analogin_s { + ADCName adc; +}; + +struct dac_s { + DACName dac; +}; + +struct can_s { + LPC_CAN_TypeDef *dev; +}; + +struct i2c_s { + LPC_I2C_TypeDef *i2c; +}; + +struct spi_s { + LPC_SSP_TypeDef *spi; +}; + +#include "gpio_object.h" + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/targets/TARGET_NXP/TARGET_LPC23XX/pinmap.c b/targets/TARGET_NXP/TARGET_LPC23XX/pinmap.c new file mode 100644 index 00000000000..12636f5d699 --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC23XX/pinmap.c @@ -0,0 +1,46 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * 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. + */ +#include "mbed_assert.h" +#include "pinmap.h" +#include "mbed_error.h" + +void pin_function(PinName pin, int function) { + MBED_ASSERT(pin != (PinName)NC); + + uint32_t pin_number = (uint32_t)pin - (uint32_t)P0_0; + int index = pin_number >> 4; + int offset = (pin_number & 0xF) << 1; + + PINCONARRAY->PINSEL[index] &= ~(0x3 << offset); + PINCONARRAY->PINSEL[index] |= function << offset; +} + +void pin_mode(PinName pin, PinMode mode) { + MBED_ASSERT((pin != (PinName)NC) && (mode != OpenDrain)); + + uint32_t pin_number = (uint32_t)pin - (uint32_t)P0_0; + int index = pin_number >> 5; + int offset = pin_number & 0x1F; + uint32_t drain = ((uint32_t) mode & (uint32_t) OpenDrain) >> 2; + + if (!drain) { + index = pin_number >> 4; + offset = (pin_number & 0xF) << 1; + + PINCONARRAY->PINMODE[index] &= ~(0x3 << offset); + PINCONARRAY->PINMODE[index] |= (uint32_t)mode << offset; + } +} diff --git a/targets/TARGET_NXP/TARGET_LPC23XX/port_api.c b/targets/TARGET_NXP/TARGET_LPC23XX/port_api.c new file mode 100644 index 00000000000..2a84a3ffc47 --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC23XX/port_api.c @@ -0,0 +1,71 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * 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. + */ +#include "port_api.h" +#include "pinmap.h" +#include "gpio_api.h" + +PinName port_pin(PortName port, int pin_n) { + return (PinName)(LPC_GPIO0_BASE + ((port << PORT_SHIFT) | pin_n)); +} + +void port_init(port_t *obj, PortName port, int mask, PinDirection dir) { + obj->port = port; + obj->mask = mask; + + LPC_GPIO_TypeDef *port_reg = (LPC_GPIO_TypeDef *)(LPC_GPIO0_BASE + ((int)port * 0x20)); + + // Do not use masking, because it prevents the use of the unmasked pins + // port_reg->FIOMASK = ~mask; + + obj->reg_out = &port_reg->FIOPIN; + obj->reg_in = &port_reg->FIOPIN; + obj->reg_dir = &port_reg->FIODIR; + + uint32_t i; + // The function is set per pin: reuse gpio logic + for (i=0; i<32; i++) { + if (obj->mask & (1<port, i)); + } + } + + port_dir(obj, dir); +} + +void port_mode(port_t *obj, PinMode mode) { + uint32_t i; + // The mode is set per pin: reuse pinmap logic + for (i=0; i<32; i++) { + if (obj->mask & (1<port, i), mode); + } + } +} + +void port_dir(port_t *obj, PinDirection dir) { + switch (dir) { + case PIN_INPUT : *obj->reg_dir &= ~obj->mask; break; + case PIN_OUTPUT: *obj->reg_dir |= obj->mask; break; + } +} + +void port_write(port_t *obj, int value) { + *obj->reg_out = (*obj->reg_in & ~obj->mask) | (value & obj->mask); +} + +int port_read(port_t *obj) { + return (*obj->reg_in & obj->mask); +} diff --git a/targets/TARGET_NXP/TARGET_LPC23XX/pwmout_api.c b/targets/TARGET_NXP/TARGET_LPC23XX/pwmout_api.c new file mode 100644 index 00000000000..3773d7e6b7a --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC23XX/pwmout_api.c @@ -0,0 +1,171 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * 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. + */ +#include "mbed_assert.h" +#include "pwmout_api.h" +#include "cmsis.h" +#include "pinmap.h" + +#define TCR_CNT_EN 0x00000001 +#define TCR_RESET 0x00000002 + +// PORT ID, PWM ID, Pin function +static const PinMap PinMap_PWM[] = { + {P1_18, PWM_1, 2}, + {P1_20, PWM_2, 2}, + {P1_21, PWM_3, 2}, + {P1_23, PWM_4, 2}, + {P1_24, PWM_5, 2}, + {P1_26, PWM_6, 2}, + {P2_0 , PWM_1, 1}, + {P2_1 , PWM_2, 1}, + {P2_2 , PWM_3, 1}, + {P2_3 , PWM_4, 1}, + {P2_4 , PWM_5, 1}, + {P2_5 , PWM_6, 1}, + {P3_25, PWM_2, 3}, + {P3_26, PWM_3, 3}, + {NC, NC, 0} +}; + +__IO uint32_t *PWM_MATCH[] = { + &(LPC_PWM1->MR0), + &(LPC_PWM1->MR1), + &(LPC_PWM1->MR2), + &(LPC_PWM1->MR3), + &(LPC_PWM1->MR4), + &(LPC_PWM1->MR5), + &(LPC_PWM1->MR6) +}; + +#define TCR_PWM_EN 0x00000008 + +static unsigned int pwm_clock_mhz; + +void pwmout_init(pwmout_t* obj, PinName pin) { + // determine the channel + PWMName pwm = (PWMName)pinmap_peripheral(pin, PinMap_PWM); + MBED_ASSERT(pwm != (PWMName)NC); + + obj->pwm = pwm; + obj->MR = PWM_MATCH[pwm]; + + // ensure the power is on + LPC_SC->PCONP |= 1 << 6; + + // ensure clock to /4 + LPC_SC->PCLKSEL0 &= ~(0x3 << 12); // pclk = /4 + LPC_PWM1->PR = 0; // no pre-scale + + // ensure single PWM mode + LPC_PWM1->MCR = 1 << 1; // reset TC on match 0 + + // enable the specific PWM output + LPC_PWM1->PCR |= 1 << (8 + pwm); + + pwm_clock_mhz = SystemCoreClock / 4000000; + + // default to 20ms: standard for servos, and fine for e.g. brightness control + pwmout_period_ms(obj, 20); + pwmout_write (obj, 0); + + // Wire pinout + pinmap_pinout(pin, PinMap_PWM); +} + +void pwmout_free(pwmout_t* obj) { + // [TODO] +} + +void pwmout_write(pwmout_t* obj, float value) { + if (value < 0.0f) { + value = 0.0; + } else if (value > 1.0f) { + value = 1.0; + } + + // set channel match to percentage + uint32_t v = (uint32_t)((float)(LPC_PWM1->MR0) * value); + + // workaround for PWM1[1] - Never make it equal MR0, else we get 1 cycle dropout + if (v == LPC_PWM1->MR0) { + v++; + } + + *obj->MR = v; + + // accept on next period start + LPC_PWM1->LER |= 1 << obj->pwm; +} + +float pwmout_read(pwmout_t* obj) { + float v = (float)(*obj->MR) / (float)(LPC_PWM1->MR0); + return (v > 1.0f) ? (1.0f) : (v); +} + +void pwmout_period(pwmout_t* obj, float seconds) { + pwmout_period_us(obj, seconds * 1000000.0f); +} + +void pwmout_period_ms(pwmout_t* obj, int ms) { + pwmout_period_us(obj, ms * 1000); +} + +// Set the PWM period, keeping the duty cycle the same. +void pwmout_period_us(pwmout_t* obj, int us) { + // calculate number of ticks + uint32_t ticks = pwm_clock_mhz * us; + + // set reset + LPC_PWM1->TCR = TCR_RESET; + + // set the global match register + LPC_PWM1->MR0 = ticks; + + // Scale the pulse width to preserve the duty ratio + if (LPC_PWM1->MR0 > 0) { + *obj->MR = (*obj->MR * ticks) / LPC_PWM1->MR0; + } + + // set the channel latch to update value at next period start + LPC_PWM1->LER |= 1 << 0; + + // enable counter and pwm, clear reset + LPC_PWM1->TCR = TCR_CNT_EN | TCR_PWM_EN; +} + +void pwmout_pulsewidth(pwmout_t* obj, float seconds) { + pwmout_pulsewidth_us(obj, seconds * 1000000.0f); +} + +void pwmout_pulsewidth_ms(pwmout_t* obj, int ms) { + pwmout_pulsewidth_us(obj, ms * 1000); +} + +void pwmout_pulsewidth_us(pwmout_t* obj, int us) { + // calculate number of ticks + uint32_t v = pwm_clock_mhz * us; + + // workaround for PWM1[1] - Never make it equal MR0, else we get 1 cycle dropout + if (v == LPC_PWM1->MR0) { + v++; + } + + // set the match register value + *obj->MR = v; + + // set the channel latch to update value at next period start + LPC_PWM1->LER |= 1 << obj->pwm; +} diff --git a/targets/TARGET_NXP/TARGET_LPC23XX/rtc_api.c b/targets/TARGET_NXP/TARGET_LPC23XX/rtc_api.c new file mode 100644 index 00000000000..a4e7b96a618 --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC23XX/rtc_api.c @@ -0,0 +1,117 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * 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. + */ +#include "rtc_api.h" + +// ensure rtc is running (unchanged if already running) + +/* Setup the RTC based on a time structure, ensuring RTC is enabled + * + * Can be clocked by a 32.768KHz oscillator or prescale divider based on the APB clock + * - We want to use the 32khz clock, allowing for sleep mode + * + * Most registers are not changed by a Reset + * - We must initialize these registers between power-on and setting the RTC into operation + + * Clock Control Register + * RTC_CCR[0] : Enable - 0 = Disabled, 1 = Enabled + * RTC_CCR[1] : Reset - 0 = Normal, 1 = Reset + * RTC_CCR[4] : Clock Source - 0 = Prescaler, 1 = 32k Xtal + * + * The RTC may already be running, so we should set it up + * without impacting if it is the case + */ +void rtc_init(void) { + LPC_SC->PCONP |= 0x200; // Ensure power is on + LPC_RTC->CCR = 0x00; + + // clock source on 2368 is special test mode on 1768! + LPC_RTC->CCR |= 1 << 4; // Ensure clock source is 32KHz Xtal + + LPC_RTC->CCR |= 1 << 0; // Ensure the RTC is enabled +} + +void rtc_free(void) { + // [TODO] +} + +/* + * Little check routine to see if the RTC has been enabled + * + * Clock Control Register + * RTC_CCR[0] : 0 = Disabled, 1 = Enabled + * + */ + +int rtc_isenabled(void) { + return(((LPC_RTC->CCR) & 0x01) != 0); +} + +/* + * RTC Registers + * RTC_SEC Seconds 0-59 + * RTC_MIN Minutes 0-59 + * RTC_HOUR Hour 0-23 + * RTC_DOM Day of Month 1-28..31 + * RTC_DOW Day of Week 0-6 + * RTC_DOY Day of Year 1-365 + * RTC_MONTH Month 1-12 + * RTC_YEAR Year 0-4095 + * + * struct tm + * tm_sec seconds after the minute 0-61 + * tm_min minutes after the hour 0-59 + * tm_hour hours since midnight 0-23 + * tm_mday day of the month 1-31 + * tm_mon months since January 0-11 + * tm_year years since 1900 + * tm_wday days since Sunday 0-6 + * tm_yday days since January 1 0-365 + * tm_isdst Daylight Saving Time flag + */ +time_t rtc_read(void) { + // Setup a tm structure based on the RTC + struct tm timeinfo; + timeinfo.tm_sec = LPC_RTC->SEC; + timeinfo.tm_min = LPC_RTC->MIN; + timeinfo.tm_hour = LPC_RTC->HOUR; + timeinfo.tm_mday = LPC_RTC->DOM; + timeinfo.tm_mon = LPC_RTC->MONTH - 1; + timeinfo.tm_year = LPC_RTC->YEAR - 1900; + + // Convert to timestamp + time_t t = mktime(&timeinfo); + + return t; +} + +void rtc_write(time_t t) { + // Convert the time in to a tm + struct tm *timeinfo = localtime(&t); + + // Pause clock, and clear counter register (clears us count) + LPC_RTC->CCR |= 2; + + // Set the RTC + LPC_RTC->SEC = timeinfo->tm_sec; + LPC_RTC->MIN = timeinfo->tm_min; + LPC_RTC->HOUR = timeinfo->tm_hour; + LPC_RTC->DOM = timeinfo->tm_mday; + LPC_RTC->MONTH = timeinfo->tm_mon + 1; + LPC_RTC->YEAR = timeinfo->tm_year + 1900; + + // Restart clock + LPC_RTC->CCR &= ~((uint32_t)2); +} diff --git a/targets/TARGET_NXP/TARGET_LPC23XX/serial_api.c b/targets/TARGET_NXP/TARGET_LPC23XX/serial_api.c new file mode 100644 index 00000000000..12142ab59f2 --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC23XX/serial_api.c @@ -0,0 +1,337 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * 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. + */ +// math.h required for floating point operations for baud rate calculation +#include "mbed_assert.h" +#include +#include +#include + +#include "serial_api.h" +#include "cmsis.h" +#include "pinmap.h" + +/****************************************************************************** + * INITIALIZATION + ******************************************************************************/ +#define UART_NUM 4 + +static const PinMap PinMap_UART_TX[] = { + {P0_0, UART_3, 2}, + {P0_2, UART_0, 1}, + {P0_10, UART_2, 1}, + {P0_15, UART_1, 1}, + {P0_25, UART_3, 3}, + {P2_0 , UART_1, 2}, + {P2_8 , UART_2, 2}, + {P4_28, UART_3, 3}, + {NC , NC , 0} +}; + +static const PinMap PinMap_UART_RX[] = { + {P0_1 , UART_3, 2}, + {P0_3 , UART_0, 1}, + {P0_11, UART_2, 1}, + {P0_16, UART_1, 1}, + {P0_26, UART_3, 3}, + {P2_1 , UART_1, 2}, + {P2_9 , UART_2, 2}, + {P4_29, UART_3, 3}, + {NC , NC , 0} +}; + +static uint32_t serial_irq_ids[UART_NUM] = {0}; +static uart_irq_handler irq_handler; + +int stdio_uart_inited = 0; +serial_t stdio_uart; + +void serial_init(serial_t *obj, PinName tx, PinName rx) { + int is_stdio_uart = 0; + + // determine the UART to use + UARTName uart_tx = (UARTName)pinmap_peripheral(tx, PinMap_UART_TX); + UARTName uart_rx = (UARTName)pinmap_peripheral(rx, PinMap_UART_RX); + UARTName uart = (UARTName)pinmap_merge(uart_tx, uart_rx); + MBED_ASSERT((int)uart != NC); + + obj->uart = (LPC_UART_TypeDef *)uart; + // enable power + switch (uart) { + case UART_0: LPC_SC->PCONP |= 1 << 3; break; + case UART_1: LPC_SC->PCONP |= 1 << 4; break; + case UART_2: LPC_SC->PCONP |= 1 << 24; break; + case UART_3: LPC_SC->PCONP |= 1 << 25; break; + } + + // enable fifos and default rx trigger level + obj->uart->FCR = 1 << 0 // FIFO Enable - 0 = Disables, 1 = Enabled + | 0 << 1 // Rx Fifo Reset + | 0 << 2 // Tx Fifo Reset + | 0 << 6; // Rx irq trigger level - 0 = 1 char, 1 = 4 chars, 2 = 8 chars, 3 = 14 chars + + // disable irqs + obj->uart->IER = 0 << 0 // Rx Data available irq enable + | 0 << 1 // Tx Fifo empty irq enable + | 0 << 2; // Rx Line Status irq enable + + // set default baud rate and format + serial_baud (obj, 9600); + serial_format(obj, 8, ParityNone, 1); + + // pinout the chosen uart + pinmap_pinout(tx, PinMap_UART_TX); + pinmap_pinout(rx, PinMap_UART_RX); + + // set rx/tx pins in PullUp mode + if (tx != NC) { + pin_mode(tx, PullUp); + } + if (rx != NC) { + pin_mode(rx, PullUp); + } + + switch (uart) { + case UART_0: obj->index = 0; break; + case UART_1: obj->index = 1; break; + case UART_2: obj->index = 2; break; + case UART_3: obj->index = 3; break; + } + + is_stdio_uart = (uart == STDIO_UART) ? (1) : (0); + + if (is_stdio_uart) { + stdio_uart_inited = 1; + memcpy(&stdio_uart, obj, sizeof(serial_t)); + } +} + +void serial_free(serial_t *obj) { + serial_irq_ids[obj->index] = 0; +} + +// serial_baud +// set the baud rate, taking in to account the current SystemFrequency +void serial_baud(serial_t *obj, int baudrate) { + MBED_ASSERT((int)obj->uart <= UART_3); + // The LPC2300 and LPC1700 have a divider and a fractional divider to control the + // baud rate. The formula is: + // + // Baudrate = (1 / PCLK) * 16 * DL * (1 + DivAddVal / MulVal) + // where: + // 1 < MulVal <= 15 + // 0 <= DivAddVal < 14 + // DivAddVal < MulVal + // + // set pclk to /1 + switch ((int)obj->uart) { + case UART_0: LPC_SC->PCLKSEL0 &= ~(0x3 << 6); LPC_SC->PCLKSEL0 |= (0x1 << 6); break; + case UART_1: LPC_SC->PCLKSEL0 &= ~(0x3 << 8); LPC_SC->PCLKSEL0 |= (0x1 << 8); break; + case UART_2: LPC_SC->PCLKSEL1 &= ~(0x3 << 16); LPC_SC->PCLKSEL1 |= (0x1 << 16); break; + case UART_3: LPC_SC->PCLKSEL1 &= ~(0x3 << 18); LPC_SC->PCLKSEL1 |= (0x1 << 18); break; + default: break; + } + + uint32_t PCLK = SystemCoreClock; + + // First we check to see if the basic divide with no DivAddVal/MulVal + // ratio gives us an integer result. If it does, we set DivAddVal = 0, + // MulVal = 1. Otherwise, we search the valid ratio value range to find + // the closest match. This could be more elegant, using search methods + // and/or lookup tables, but the brute force method is not that much + // slower, and is more maintainable. + uint16_t DL = PCLK / (16 * baudrate); + + uint8_t DivAddVal = 0; + uint8_t MulVal = 1; + int hit = 0; + uint16_t dlv; + uint8_t mv, dav; + if ((PCLK % (16 * baudrate)) != 0) { // Checking for zero remainder + int err_best = baudrate, b; + for (mv = 1; mv < 16 && !hit; mv++) + { + for (dav = 0; dav < mv; dav++) + { + // baudrate = PCLK / (16 * dlv * (1 + (DivAdd / Mul)) + // solving for dlv, we get dlv = mul * PCLK / (16 * baudrate * (divadd + mul)) + // mul has 4 bits, PCLK has 27 so we have 1 bit headroom which can be used for rounding + // for many values of mul and PCLK we have 2 or more bits of headroom which can be used to improve precision + // note: X / 32 doesn't round correctly. Instead, we use ((X / 16) + 1) / 2 for correct rounding + + if ((mv * PCLK * 2) & 0x80000000) // 1 bit headroom + dlv = ((((2 * mv * PCLK) / (baudrate * (dav + mv))) / 16) + 1) / 2; + else // 2 bits headroom, use more precision + dlv = ((((4 * mv * PCLK) / (baudrate * (dav + mv))) / 32) + 1) / 2; + + // datasheet says if DLL==DLM==0, then 1 is used instead since divide by zero is ungood + if (dlv == 0) + dlv = 1; + + // datasheet says if dav > 0 then DL must be >= 2 + if ((dav > 0) && (dlv < 2)) + dlv = 2; + + // integer rearrangement of the baudrate equation (with rounding) + b = ((PCLK * mv / (dlv * (dav + mv) * 8)) + 1) / 2; + + // check to see how we went + b = abs(b - baudrate); + if (b < err_best) + { + err_best = b; + + DL = dlv; + MulVal = mv; + DivAddVal = dav; + + if (b == baudrate) + { + hit = 1; + break; + } + } + } + } + } + + // set LCR[DLAB] to enable writing to divider registers + obj->uart->LCR |= (1 << 7); + + // set divider values + obj->uart->DLM = (DL >> 8) & 0xFF; + obj->uart->DLL = (DL >> 0) & 0xFF; + obj->uart->FDR = (uint32_t) DivAddVal << 0 + | (uint32_t) MulVal << 4; + + // clear LCR[DLAB] + obj->uart->LCR &= ~(1 << 7); +} + +void serial_format(serial_t *obj, int data_bits, SerialParity parity, int stop_bits) { + MBED_ASSERT((stop_bits == 1) || (stop_bits == 2)); // 0: 1 stop bits, 1: 2 stop bits + MBED_ASSERT((data_bits > 4) && (data_bits < 9)); // 0: 5 data bits ... 3: 8 data bits + MBED_ASSERT((parity == ParityNone) || (parity == ParityOdd) || (parity == ParityEven) || + (parity == ParityForced1) || (parity == ParityForced0)); + + stop_bits -= 1; + data_bits -= 5; + + int parity_enable = 0, parity_select = 0; + switch (parity) { + case ParityNone: parity_enable = 0; parity_select = 0; break; + case ParityOdd : parity_enable = 1; parity_select = 0; break; + case ParityEven: parity_enable = 1; parity_select = 1; break; + case ParityForced1: parity_enable = 1; parity_select = 2; break; + case ParityForced0: parity_enable = 1; parity_select = 3; break; + default: + break; + } + + obj->uart->LCR = data_bits << 0 + | stop_bits << 2 + | parity_enable << 3 + | parity_select << 4; +} + +/****************************************************************************** + * INTERRUPTS HANDLING + ******************************************************************************/ +static inline void uart_irq(uint32_t iir, uint32_t index) { + // [Chapter 14] LPC17xx UART0/2/3: UARTn Interrupt Handling + SerialIrq irq_type; + switch (iir) { + case 1: irq_type = TxIrq; break; + case 2: irq_type = RxIrq; break; + default: return; + } + + if (serial_irq_ids[index] != 0) + irq_handler(serial_irq_ids[index], irq_type); +} + +void uart0_irq() {uart_irq((LPC_UART0->IIR >> 1) & 0x7, 0);} +void uart1_irq() {uart_irq((LPC_UART1->IIR >> 1) & 0x7, 1);} +void uart2_irq() {uart_irq((LPC_UART2->IIR >> 1) & 0x7, 2);} +void uart3_irq() {uart_irq((LPC_UART3->IIR >> 1) & 0x7, 3);} + +void serial_irq_handler(serial_t *obj, uart_irq_handler handler, uint32_t id) { + irq_handler = handler; + serial_irq_ids[obj->index] = id; +} + +void serial_irq_set(serial_t *obj, SerialIrq irq, uint32_t enable) { + IRQn_Type irq_n = (IRQn_Type)0; + uint32_t vector = 0; + switch ((int)obj->uart) { + case UART_0: irq_n=UART0_IRQn; vector = (uint32_t)&uart0_irq; break; + case UART_1: irq_n=UART1_IRQn; vector = (uint32_t)&uart1_irq; break; + case UART_2: irq_n=UART2_IRQn; vector = (uint32_t)&uart2_irq; break; + case UART_3: irq_n=UART3_IRQn; vector = (uint32_t)&uart3_irq; break; + } + + if (enable) { + obj->uart->IER |= 1 << irq; + NVIC_SetVector(irq_n, vector); + NVIC_EnableIRQ(irq_n); + } else { // disable + int all_disabled = 0; + SerialIrq other_irq = (irq == RxIrq) ? (TxIrq) : (RxIrq); + obj->uart->IER &= ~(1 << irq); + all_disabled = (obj->uart->IER & (1 << other_irq)) == 0; + if (all_disabled) + NVIC_DisableIRQ(irq_n); + } +} + +/****************************************************************************** + * READ/WRITE + ******************************************************************************/ +int serial_getc(serial_t *obj) { + while (!serial_readable(obj)); + return obj->uart->RBR; +} + +void serial_putc(serial_t *obj, int c) { + while (!serial_writable(obj)); + obj->uart->THR = c; +} + +int serial_readable(serial_t *obj) { + return obj->uart->LSR & 0x01; +} + +int serial_writable(serial_t *obj) { + return obj->uart->LSR & 0x20; +} + +void serial_clear(serial_t *obj) { + obj->uart->FCR = 1 << 1 // rx FIFO reset + | 1 << 2 // tx FIFO reset + | 0 << 6; // interrupt depth +} + +void serial_pinout_tx(PinName tx) { + pinmap_pinout(tx, PinMap_UART_TX); +} + +void serial_break_set(serial_t *obj) { + obj->uart->LCR |= (1 << 6); +} + +void serial_break_clear(serial_t *obj) { + obj->uart->LCR &= ~(1 << 6); +} + diff --git a/targets/TARGET_NXP/TARGET_LPC23XX/spi_api.c b/targets/TARGET_NXP/TARGET_LPC23XX/spi_api.c new file mode 100644 index 00000000000..7768e11046d --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC23XX/spi_api.c @@ -0,0 +1,208 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * 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. + */ +#include "mbed_assert.h" +#include + +#include "spi_api.h" +#include "cmsis.h" +#include "pinmap.h" +#include "mbed_error.h" + +static const PinMap PinMap_SPI_SCLK[] = { + {P0_7 , SPI_1, 2}, + {P0_15, SPI_0, 2}, + {P1_20, SPI_0, 3}, + {P1_31, SPI_1, 2}, + {NC , NC , 0} +}; + +static const PinMap PinMap_SPI_MOSI[] = { + {P0_9 , SPI_1, 2}, + {P0_13, SPI_1, 2}, + {P0_18, SPI_0, 2}, + {P1_24, SPI_0, 3}, + {NC , NC , 0} +}; + +static const PinMap PinMap_SPI_MISO[] = { + {P0_8 , SPI_1, 2}, + {P0_12, SPI_1, 2}, + {P0_17, SPI_0, 2}, + {P1_23, SPI_0, 3}, + {NC , NC , 0} +}; + +static const PinMap PinMap_SPI_SSEL[] = { + {P0_6 , SPI_1, 2}, + {P0_11, SPI_1, 2}, + {P0_16, SPI_0, 2}, + {P1_21, SPI_0, 3}, + {NC , NC , 0} +}; + +static inline int ssp_disable(spi_t *obj); +static inline int ssp_enable(spi_t *obj); + +void spi_init(spi_t *obj, PinName mosi, PinName miso, PinName sclk, PinName ssel) { + // determine the SPI to use + SPIName spi_mosi = (SPIName)pinmap_peripheral(mosi, PinMap_SPI_MOSI); + SPIName spi_miso = (SPIName)pinmap_peripheral(miso, PinMap_SPI_MISO); + SPIName spi_sclk = (SPIName)pinmap_peripheral(sclk, PinMap_SPI_SCLK); + SPIName spi_ssel = (SPIName)pinmap_peripheral(ssel, PinMap_SPI_SSEL); + SPIName spi_data = (SPIName)pinmap_merge(spi_mosi, spi_miso); + SPIName spi_cntl = (SPIName)pinmap_merge(spi_sclk, spi_ssel); + obj->spi = (LPC_SSP_TypeDef*)pinmap_merge(spi_data, spi_cntl); + MBED_ASSERT((int)obj->spi != NC); + + // enable power and clocking + switch ((int)obj->spi) { + case SPI_0: LPC_SC->PCONP |= 1 << 21; break; + case SPI_1: LPC_SC->PCONP |= 1 << 10; break; + } + + // pin out the spi pins + pinmap_pinout(mosi, PinMap_SPI_MOSI); + pinmap_pinout(miso, PinMap_SPI_MISO); + pinmap_pinout(sclk, PinMap_SPI_SCLK); + if (ssel != NC) { + pinmap_pinout(ssel, PinMap_SPI_SSEL); + } +} + +void spi_free(spi_t *obj) {} + +void spi_format(spi_t *obj, int bits, int mode, int slave) { + MBED_ASSERT(((bits >= 4) && (bits <= 16)) && ((mode >= 0) && (mode <= 3))); + ssp_disable(obj); + + int polarity = (mode & 0x2) ? 1 : 0; + int phase = (mode & 0x1) ? 1 : 0; + + // set it up + int DSS = bits - 1; // DSS (data select size) + int SPO = (polarity) ? 1 : 0; // SPO - clock out polarity + int SPH = (phase) ? 1 : 0; // SPH - clock out phase + + int FRF = 0; // FRF (frame format) = SPI + uint32_t tmp = obj->spi->CR0; + tmp &= ~(0xFFFF); + tmp |= DSS << 0 + | FRF << 4 + | SPO << 6 + | SPH << 7; + obj->spi->CR0 = tmp; + + tmp = obj->spi->CR1; + tmp &= ~(0xD); + tmp |= 0 << 0 // LBM - loop back mode - off + | ((slave) ? 1 : 0) << 2 // MS - master slave mode, 1 = slave + | 0 << 3; // SOD - slave output disable - na + obj->spi->CR1 = tmp; + + ssp_enable(obj); +} + +void spi_frequency(spi_t *obj, int hz) { + ssp_disable(obj); + + // setup the spi clock diveder to /1 + switch ((int)obj->spi) { + case SPI_0: + LPC_SC->PCLKSEL1 &= ~(3 << 10); + LPC_SC->PCLKSEL1 |= (1 << 10); + break; + case SPI_1: + LPC_SC->PCLKSEL0 &= ~(3 << 20); + LPC_SC->PCLKSEL0 |= (1 << 20); + break; + } + + uint32_t PCLK = SystemCoreClock; + + int prescaler; + + for (prescaler = 2; prescaler <= 254; prescaler += 2) { + int prescale_hz = PCLK / prescaler; + + // calculate the divider + int divider = floor(((float)prescale_hz / (float)hz) + 0.5f); + + // check we can support the divider + if (divider < 256) { + // prescaler + obj->spi->CPSR = prescaler; + + // divider + obj->spi->CR0 &= ~(0xFFFF << 8); + obj->spi->CR0 |= (divider - 1) << 8; + ssp_enable(obj); + return; + } + } + error("Couldn't setup requested SPI frequency"); +} + +static inline int ssp_disable(spi_t *obj) { + return obj->spi->CR1 &= ~(1 << 1); +} + +static inline int ssp_enable(spi_t *obj) { + return obj->spi->CR1 |= (1 << 1); +} + +static inline int ssp_readable(spi_t *obj) { + return obj->spi->SR & (1 << 2); +} + +static inline int ssp_writeable(spi_t *obj) { + return obj->spi->SR & (1 << 1); +} + +static inline void ssp_write(spi_t *obj, int value) { + while (!ssp_writeable(obj)); + obj->spi->DR = value; +} + +static inline int ssp_read(spi_t *obj) { + while (!ssp_readable(obj)); + return obj->spi->DR; +} + +static inline int ssp_busy(spi_t *obj) { + return (obj->spi->SR & (1 << 4)) ? (1) : (0); +} + +int spi_master_write(spi_t *obj, int value) { + ssp_write(obj, value); + return ssp_read(obj); +} + +int spi_slave_receive(spi_t *obj) { + return (ssp_readable(obj) && !ssp_busy(obj)) ? (1) : (0); +} + +int spi_slave_read(spi_t *obj) { + return obj->spi->DR; +} + +void spi_slave_write(spi_t *obj, int value) { + while (ssp_writeable(obj) == 0) ; + obj->spi->DR = value; +} + +int spi_busy(spi_t *obj) { + return ssp_busy(obj); +} diff --git a/targets/TARGET_NXP/TARGET_LPC23XX/us_ticker.c b/targets/TARGET_NXP/TARGET_LPC23XX/us_ticker.c new file mode 100644 index 00000000000..b46d75e6bcc --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC23XX/us_ticker.c @@ -0,0 +1,64 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * 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. + */ +#include +#include "us_ticker_api.h" +#include "PeripheralNames.h" + +#define US_TICKER_TIMER ((LPC_TIM_TypeDef *)LPC_TIM3_BASE) +#define US_TICKER_TIMER_IRQn TIMER3_IRQn + +int us_ticker_inited = 0; + +void us_ticker_init(void) { + if (us_ticker_inited) return; + us_ticker_inited = 1; + + LPC_SC->PCONP |= 1 << 23; // Clock TIMER_3 + + US_TICKER_TIMER->CTCR = 0x0; // timer mode + uint32_t PCLK = SystemCoreClock / 4; + + US_TICKER_TIMER->TCR = 0x2; // reset + + uint32_t prescale = PCLK / 1000000; // default to 1MHz (1 us ticks) + US_TICKER_TIMER->PR = prescale - 1; + US_TICKER_TIMER->TCR = 1; // enable = 1, reset = 0 + + NVIC_SetVector(US_TICKER_TIMER_IRQn, (uint32_t)us_ticker_irq_handler); + NVIC_EnableIRQ(US_TICKER_TIMER_IRQn); +} + +uint32_t us_ticker_read() { + if (!us_ticker_inited) + us_ticker_init(); + + return US_TICKER_TIMER->TC; +} + +void us_ticker_set_interrupt(timestamp_t timestamp) { + // set match value + US_TICKER_TIMER->MR0 = (uint32_t)timestamp; + // enable match interrupt + US_TICKER_TIMER->MCR |= 1; +} + +void us_ticker_disable_interrupt(void) { + US_TICKER_TIMER->MCR &= ~1; +} + +void us_ticker_clear_interrupt(void) { + US_TICKER_TIMER->IR = 1; +} diff --git a/targets/TARGET_NXP/TARGET_LPC2460/PeripheralNames.h b/targets/TARGET_NXP/TARGET_LPC2460/PeripheralNames.h new file mode 100644 index 00000000000..653aa9ea7c1 --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC2460/PeripheralNames.h @@ -0,0 +1,120 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2015 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * 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. + */ +#ifndef MBED_PERIPHERALNAMES_H +#define MBED_PERIPHERALNAMES_H + +#include "cmsis.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + UART_0 = (int)LPC_UART0_BASE, + UART_1 = (int)LPC_UART1_BASE, + UART_2 = (int)LPC_UART2_BASE, + UART_3 = (int)LPC_UART3_BASE +} UARTName; + +typedef enum { + ADC0_0 = 0, + ADC0_1, + ADC0_2, + ADC0_3, + ADC0_4, + ADC0_5, + ADC0_6, + ADC0_7 +} ADCName; + +typedef enum { + DAC_0 = 0 +} DACName; + +typedef enum { + SPI_0 = (int)LPC_SSP0_BASE, + SPI_1 = (int)LPC_SSP1_BASE +} SPIName; + +typedef enum { + I2C_0 = (int)LPC_I2C0_BASE, + I2C_1 = (int)LPC_I2C1_BASE, + I2C_2 = (int)LPC_I2C2_BASE +} I2CName; + +typedef enum { + PWM_1 = 1, + PWM_2, + PWM_3, + PWM_4, + PWM_5, + PWM_6 +} PWMName; + +typedef enum { + CAN_1 = (int)LPC_CAN1_BASE, + CAN_2 = (int)LPC_CAN2_BASE +} CANName; + +#define STDIO_UART_TX USBTX +#define STDIO_UART_RX USBRX +#define STDIO_UART UART_2 + +// Default peripherals +#define MBED_SPI0 p5, p6, p7, p8 +//#define MBED_SPI1 p11, p12, p13, p14 + +#define MBED_UART0 p9, p10 +#define MBED_UART1 p13, p14 +#define MBED_UART2 p15, p16 +#define MBED_UARTUSB USBTX, USBRX + +#define MBED_I2C0 p17, p18 +//#define MBED_I2C1 p9, p10 + +#define MBED_CAN0 p19, p20 + +#define MBED_ANALOGOUT0 p21 + +#define MBED_ANALOGIN0 p22 +#define MBED_ANALOGIN1 p23 +//#define MBED_ANALOGIN2 p17 +//#define MBED_ANALOGIN3 p18 +//#define MBED_ANALOGIN4 p19 +//#define MBED_ANALOGIN5 p20 + +#define MBED_PWMOUT0 p24 +#define MBED_PWMOUT1 p25 +#define MBED_PWMOUT2 p26 +#define MBED_PWMOUT3 p27 +//#define MBED_PWMOUT4 p22 +//#define MBED_PWMOUT5 p21 + +#define MBED_USB_D_PLUS p28 +#define MBED_USB_D_MINUS p29 + +#define MBED_MCICLK p30 +#define MBED_MCICMD p31 +#define MBED_MCIDAT0 p32 +#define MBED_MCIDAT1 p33 +#define MBED_MCIDAT2 p34 +#define MBED_MCIDAT3 p35 + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/targets/TARGET_NXP/TARGET_LPC2460/PinNames.h b/targets/TARGET_NXP/TARGET_LPC2460/PinNames.h new file mode 100644 index 00000000000..95279121971 --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC2460/PinNames.h @@ -0,0 +1,112 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2015 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * 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. + */ + +#ifndef MBED_PINNAMES_H +#define MBED_PINNAMES_H + +#include "cmsis.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + PIN_INPUT, + PIN_OUTPUT +} PinDirection; + +#define PORT_SHIFT 5 + +typedef enum { + // LPC Pin Names + P0_0 = LPC_GPIO0_BASE, + P0_1, P0_2, P0_3, P0_4, P0_5, P0_6, P0_7, P0_8, P0_9, P0_10, P0_11, P0_12, P0_13, P0_14, P0_15, P0_16, P0_17, P0_18, P0_19, P0_20, P0_21, P0_22, P0_23, P0_24, P0_25, P0_26, P0_27, P0_28, P0_29, P0_30, P0_31, + P1_0, P1_1, P1_2, P1_3, P1_4, P1_5, P1_6, P1_7, P1_8, P1_9, P1_10, P1_11, P1_12, P1_13, P1_14, P1_15, P1_16, P1_17, P1_18, P1_19, P1_20, P1_21, P1_22, P1_23, P1_24, P1_25, P1_26, P1_27, P1_28, P1_29, P1_30, P1_31, + P2_0, P2_1, P2_2, P2_3, P2_4, P2_5, P2_6, P2_7, P2_8, P2_9, P2_10, P2_11, P2_12, P2_13, P2_14, P2_15, P2_16, P2_17, P2_18, P2_19, P2_20, P2_21, P2_22, P2_23, P2_24, P2_25, P2_26, P2_27, P2_28, P2_29, P2_30, P2_31, + P3_0, P3_1, P3_2, P3_3, P3_4, P3_5, P3_6, P3_7, P3_8, P3_9, P3_10, P3_11, P3_12, P3_13, P3_14, P3_15, P3_16, P3_17, P3_18, P3_19, P3_20, P3_21, P3_22, P3_23, P3_24, P3_25, P3_26, P3_27, P3_28, P3_29, P3_30, P3_31, + P4_0, P4_1, P4_2, P4_3, P4_4, P4_5, P4_6, P4_7, P4_8, P4_9, P4_10, P4_11, P4_12, P4_13, P4_14, P4_15, P4_16, P4_17, P4_18, P4_19, P4_20, P4_21, P4_22, P4_23, P4_24, P4_25, P4_26, P4_27, P4_28, P4_29, P4_30, P4_31, + + // mbed DIP Pin Names + p5 = P0_18, + p6 = P0_17, + p7 = P0_15, + p8 = P0_16, + + p9 = P0_2, + p10 = P0_3, + p11 = P0_18, + p12 = P0_17, + p13 = P2_0, + p14 = P2_1, + p15 = P4_28, + p16 = P4_29, + p17 = P2_30, + p18 = P2_31, + p19 = P0_0, + p20 = P0_1, + p21 = P0_26, + p22 = P0_12, + p23 = P0_13, + p24 = P1_20, + p25 = P1_21, + p26 = P1_23, + p27 = P1_24, + p28 = P0_29, + p29 = P0_30, + p30 = P1_2, + p31 = P1_3, + p32 = P1_6, + p33 = P1_7, + p34 = P1_11, + p35 = P1_12, + + // Other mbed Pin Names + LED1 = P1_19, + LED2 = P2_26, + LED3 = P2_27, + LED4 = P2_27, + + USBTX = P2_8, + USBRX = P2_9, + + EXT_WDT = P0_10, + + // Not connected + NC = (int)0xFFFFFFFF +} PinName; + +typedef enum { + PullUp = 0, + PullDown = 3, + PullNone = 2, + OpenDrain = 4, + PullDefault = PullDown +} PinMode; + +// version of PINCON_TypeDef using register arrays +typedef struct { + __IO uint32_t PINSEL[11]; + uint32_t RESERVED0[5]; + __IO uint32_t PINMODE[10]; +} PINCONARRAY_TypeDef; + +#define PINCONARRAY ((PINCONARRAY_TypeDef *)LPC_PINCON_BASE) + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/targets/TARGET_NXP/TARGET_LPC2460/PortNames.h b/targets/TARGET_NXP/TARGET_LPC2460/PortNames.h new file mode 100644 index 00000000000..c17e9de12ed --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC2460/PortNames.h @@ -0,0 +1,38 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2015 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * 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. + */ +#ifndef MBED_PORTNAMES_H +#define MBED_PORTNAMES_H + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + Port0 = 0, + Port1 = 1, + Port2 = 2, + Port3 = 3, + Port4 = 4 +} PortName; + +#define PORT_0 Port0 +#define PORT_1 Port1 +#define PORT_2 Port2 +#define PORT_3 Port3 +#ifdef __cplusplus +} +#endif +#endif diff --git a/targets/TARGET_NXP/TARGET_LPC2460/analogin_api.c b/targets/TARGET_NXP/TARGET_LPC2460/analogin_api.c new file mode 100644 index 00000000000..6293c3f5a49 --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC2460/analogin_api.c @@ -0,0 +1,125 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2015 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * 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. + */ +#include "mbed_assert.h" +#include "analogin_api.h" +#include "cmsis.h" +#include "pinmap.h" + +#define ANALOGIN_MEDIAN_FILTER 1 + +#define ADC_10BIT_RANGE 0x3FF +#define ADC_12BIT_RANGE 0xFFF + +static inline int div_round_up(int x, int y) { + return (x + (y - 1)) / y; +} + +static const PinMap PinMap_ADC[] = { + {P0_23, ADC0_0, 1}, + {P0_24, ADC0_1, 1}, + {P0_25, ADC0_2, 1}, + {P0_26, ADC0_3, 1}, + {P1_30, ADC0_4, 3}, + {P1_31, ADC0_5, 3}, + {P0_12, ADC0_6, 3}, + {P0_13, ADC0_7, 3}, + {NC, NC, 0} +}; + +#define ADC_RANGE ADC_10BIT_RANGE + + +void analogin_init(analogin_t *obj, PinName pin) { + obj->adc = (ADCName)pinmap_peripheral(pin, PinMap_ADC); + MBED_ASSERT(obj->adc != (ADCName)NC); + + // ensure power is turned on + LPC_SC->PCONP |= (1 << PCADC); + + // set PCLK of ADC to /1 + LPC_SC->PCLKSEL0 &= ~(0x3 << 24); + LPC_SC->PCLKSEL0 |= (0x1 << 24); + uint32_t PCLK = SystemCoreClock; + + // calculate minimum clock divider + // clkdiv = divider - 1 + uint32_t MAX_ADC_CLK = 4500000; + uint32_t clkdiv = div_round_up(PCLK, MAX_ADC_CLK) - 1; + + // Set the generic software-controlled ADC settings + LPC_ADC->ADCR = (0 << 0) // SEL: 0 = no channels selected + | (clkdiv << 8) // CLKDIV: PCLK max ~= 25MHz, /25 to give safe 1MHz at fastest + | (0 << 16) // BURST: 0 = software control + | (0 << 17) // CLKS: not applicable + | (1 << 21) // PDN: 1 = operational + | (0 << 24) // START: 0 = no start + | (0 << 27); // EDGE: not applicable + + pinmap_pinout(pin, PinMap_ADC); +} + +static inline uint32_t adc_read(analogin_t *obj) { + // Select the appropriate channel and start conversion + LPC_ADC->ADCR &= ~0xFF; + LPC_ADC->ADCR |= 1 << (int)obj->adc; + LPC_ADC->ADCR |= 1 << 24; + + // Repeatedly get the sample data until DONE bit + unsigned int data; + do { + data = LPC_ADC->ADGDR; + } while ((data & ((unsigned int)1 << 31)) == 0); + + // Stop conversion + LPC_ADC->ADCR &= ~(1 << 24); + + return (data >> 6) & ADC_RANGE; // 10 bit +} + +static inline void order(uint32_t *a, uint32_t *b) { + if (*a > *b) { + uint32_t t = *a; + *a = *b; + *b = t; + } +} + +static inline uint32_t adc_read_u32(analogin_t *obj) { + uint32_t value; +#if ANALOGIN_MEDIAN_FILTER + uint32_t v1 = adc_read(obj); + uint32_t v2 = adc_read(obj); + uint32_t v3 = adc_read(obj); + order(&v1, &v2); + order(&v2, &v3); + order(&v1, &v2); + value = v2; +#else + value = adc_read(obj); +#endif + return value; +} + +uint16_t analogin_read_u16(analogin_t *obj) { + uint32_t value = adc_read_u32(obj); + + return (value << 6) | ((value >> 4) & 0x003F); // 10 bit +} + +float analogin_read(analogin_t *obj) { + uint32_t value = adc_read_u32(obj); + return (float)value * (1.0f / (float)ADC_RANGE); +} diff --git a/targets/TARGET_NXP/TARGET_LPC2460/analogout_api.c b/targets/TARGET_NXP/TARGET_LPC2460/analogout_api.c new file mode 100644 index 00000000000..2a6194d059a --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC2460/analogout_api.c @@ -0,0 +1,75 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2015 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * 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. + */ +#include "mbed_assert.h" +#include "analogout_api.h" +#include "cmsis.h" +#include "pinmap.h" + +static const PinMap PinMap_DAC[] = { + {P0_26, DAC_0, 2}, + {NC , NC , 0} +}; + +void analogout_init(dac_t *obj, PinName pin) { + obj->dac = (DACName)pinmap_peripheral(pin, PinMap_DAC); + MBED_ASSERT(obj->dac != (DACName)NC); + + // power is on by default, set DAC clk divider is /4 + LPC_SC->PCLKSEL0 &= ~(0x3 << 22); + + // map out (must be done before accessing registers) + pinmap_pinout(pin, PinMap_DAC); + + analogout_write_u16(obj, 0); +} + +void analogout_free(dac_t *obj) {} + +static inline void dac_write(int value) { + value &= 0x3FF; // 10-bit + + // Set the DAC output + LPC_DAC->DACR = (0 << 16) // bias = 0 + | (value << 6); +} + +static inline int dac_read() { + return (LPC_DAC->DACR >> 6) & 0x3FF; +} + +void analogout_write(dac_t *obj, float value) { + if (value < 0.0f) { + dac_write(0); + } else if (value > 1.0f) { + dac_write(0x3FF); + } else { + dac_write(value * (float)0x3FF); + } +} + +void analogout_write_u16(dac_t *obj, uint16_t value) { + dac_write(value >> 6); // 10-bit +} + +float analogout_read(dac_t *obj) { + uint32_t value = dac_read(); + return (float)value * (1.0f / (float)0x3FF); +} + +uint16_t analogout_read_u16(dac_t *obj) { + uint32_t value = dac_read(); // 10-bit + return (value << 6) | ((value >> 4) & 0x003F); +} diff --git a/targets/TARGET_NXP/TARGET_LPC2460/can_api.c b/targets/TARGET_NXP/TARGET_LPC2460/can_api.c new file mode 100644 index 00000000000..5107615f784 --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC2460/can_api.c @@ -0,0 +1,303 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2015 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * 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. + */ +#include "mbed_assert.h" +#include "can_api.h" +#include "cmsis.h" +#include "pinmap.h" + +#include +#include + +/* Acceptance filter mode in AFMR register */ +#define ACCF_OFF 0x01 +#define ACCF_BYPASS 0x02 +#define ACCF_ON 0x00 +#define ACCF_FULLCAN 0x04 + +/* There are several bit timing calculators on the internet. +http://www.port.de/engl/canprod/sv_req_form.html +http://www.kvaser.com/can/index.htm +*/ + +static const PinMap PinMap_CAN_RD[] = { + {P0_0 , CAN_1, 1}, + {P0_4 , CAN_2, 2}, + {P0_21, CAN_1, 3}, + {P2_7 , CAN_2, 1}, + {NC , NC , 0} +}; + +static const PinMap PinMap_CAN_TD[] = { + {P0_1 , CAN_1, 1}, + {P0_5 , CAN_2, 2}, + {P0_22, CAN_1, 3}, + {P2_8 , CAN_2, 1}, + {NC , NC , 0} +}; + +// Type definition to hold a CAN message +struct CANMsg { + unsigned int reserved1 : 16; + unsigned int dlc : 4; // Bits 16..19: DLC - Data Length Counter + unsigned int reserved0 : 10; + unsigned int rtr : 1; // Bit 30: Set if this is a RTR message + unsigned int type : 1; // Bit 31: Set if this is a 29-bit ID message + unsigned int id; // CAN Message ID (11-bit or 29-bit) + unsigned char data[8]; // CAN Message Data Bytes 0-7 +}; +typedef struct CANMsg CANMsg; + +static uint32_t can_disable(can_t *obj) { + uint32_t sm = obj->dev->MOD; + obj->dev->MOD |= 1; + return sm; +} + +static inline void can_enable(can_t *obj) { + if (obj->dev->MOD & 1) { + obj->dev->MOD &= ~(1); + } +} + +int can_mode(can_t *obj, CanMode mode) { + return 0; // not implemented +} + +int can_filter(can_t *obj, uint32_t id, uint32_t mask, CANFormat format, int32_t handle) { + return 0; // not implemented +} + +static int can_pclk(can_t *obj) { + int value = 0; + switch ((int)obj->dev) { + case CAN_1: value = (LPC_SC->PCLKSEL0 & (0x3 << 26)) >> 26; break; + case CAN_2: value = (LPC_SC->PCLKSEL0 & (0x3 << 28)) >> 28; break; + } + + switch (value) { + case 1: return 1; + case 2: return 2; + case 3: return 6; + default: return 4; + } +} + +// This table has the sampling points as close to 75% as possible. The first +// value is TSEG1, the second TSEG2. +static const int timing_pts[23][2] = { + {0x0, 0x0}, // 2, 50% + {0x1, 0x0}, // 3, 67% + {0x2, 0x0}, // 4, 75% + {0x3, 0x0}, // 5, 80% + {0x3, 0x1}, // 6, 67% + {0x4, 0x1}, // 7, 71% + {0x5, 0x1}, // 8, 75% + {0x6, 0x1}, // 9, 78% + {0x6, 0x2}, // 10, 70% + {0x7, 0x2}, // 11, 73% + {0x8, 0x2}, // 12, 75% + {0x9, 0x2}, // 13, 77% + {0x9, 0x3}, // 14, 71% + {0xA, 0x3}, // 15, 73% + {0xB, 0x3}, // 16, 75% + {0xC, 0x3}, // 17, 76% + {0xD, 0x3}, // 18, 78% + {0xD, 0x4}, // 19, 74% + {0xE, 0x4}, // 20, 75% + {0xF, 0x4}, // 21, 76% + {0xF, 0x5}, // 22, 73% + {0xF, 0x6}, // 23, 70% + {0xF, 0x7}, // 24, 67% +}; + +static unsigned int can_speed(unsigned int sclk, unsigned int pclk, unsigned int cclk, unsigned char psjw) { + uint32_t btr; + uint16_t brp = 0; + uint32_t calcbit; + uint32_t bitwidth; + int hit = 0; + int bits; + + bitwidth = sclk / (pclk * cclk); + + brp = bitwidth / 0x18; + while ((!hit) && (brp < bitwidth / 4)) { + brp++; + for (bits = 22; bits > 0; bits--) { + calcbit = (bits + 3) * (brp + 1); + if (calcbit == bitwidth) { + hit = 1; + break; + } + } + } + + if (hit) { + btr = ((timing_pts[bits][1] << 20) & 0x00700000) + | ((timing_pts[bits][0] << 16) & 0x000F0000) + | ((psjw << 14) & 0x0000C000) + | ((brp << 0) & 0x000003FF); + } else { + btr = 0xFFFFFFFF; + } + + return btr; +} + +void can_init(can_t *obj, PinName rd, PinName td) { + CANName can_rd = (CANName)pinmap_peripheral(rd, PinMap_CAN_RD); + CANName can_td = (CANName)pinmap_peripheral(td, PinMap_CAN_TD); + obj->dev = (LPC_CAN_TypeDef *)pinmap_merge(can_rd, can_td); + MBED_ASSERT((int)obj->dev != NC); + + switch ((int)obj->dev) { + case CAN_1: LPC_SC->PCONP |= 1 << PCAN1; break; + case CAN_2: LPC_SC->PCONP |= 1 << PCAN2; break; + } + + pinmap_pinout(rd, PinMap_CAN_RD); + pinmap_pinout(td, PinMap_CAN_TD); + + can_reset(obj); + obj->dev->IER = 0; // Disable Interrupts + can_frequency(obj, 100000); + + LPC_CANAF->AFMR = ACCF_BYPASS; // Bypass Filter +} + +void can_free(can_t *obj) { + switch ((int)obj->dev) { + case CAN_1: LPC_SC->PCONP &= ~(1 << PCAN1); break; + case CAN_2: LPC_SC->PCONP &= ~(1 << PCAN2); break; + } +} + +int can_frequency(can_t *obj, int f) { + int pclk = can_pclk(obj); + int btr = can_speed(SystemCoreClock, pclk, (unsigned int)f, 1); + + if (btr > 0) { + uint32_t modmask = can_disable(obj); + obj->dev->BTR = btr; + obj->dev->MOD = modmask; + return 1; + } else { + return 0; + } +} + +int can_write(can_t *obj, CAN_Message msg, int cc) { + unsigned int CANStatus; + CANMsg m; + + can_enable(obj); + + m.id = msg.id ; + m.dlc = msg.len & 0xF; + m.rtr = msg.type; + m.type = msg.format; + memcpy(m.data, msg.data, msg.len); + const unsigned int *buf = (const unsigned int *)&m; + + CANStatus = obj->dev->SR; + if (CANStatus & 0x00000004) { + obj->dev->TFI1 = buf[0] & 0xC00F0000; + obj->dev->TID1 = buf[1]; + obj->dev->TDA1 = buf[2]; + obj->dev->TDB1 = buf[3]; + if (cc) { + obj->dev->CMR = 0x30; + } else { + obj->dev->CMR = 0x21; + } + return 1; + + } else if (CANStatus & 0x00000400) { + obj->dev->TFI2 = buf[0] & 0xC00F0000; + obj->dev->TID2 = buf[1]; + obj->dev->TDA2 = buf[2]; + obj->dev->TDB2 = buf[3]; + if (cc) { + obj->dev->CMR = 0x50; + } else { + obj->dev->CMR = 0x41; + } + return 1; + + } else if (CANStatus & 0x00040000) { + obj->dev->TFI3 = buf[0] & 0xC00F0000; + obj->dev->TID3 = buf[1]; + obj->dev->TDA3 = buf[2]; + obj->dev->TDB3 = buf[3]; + if (cc) { + obj->dev->CMR = 0x90; + } else { + obj->dev->CMR = 0x81; + } + return 1; + } + + return 0; +} + +int can_read(can_t *obj, CAN_Message *msg, int handle) { + CANMsg x; + unsigned int *i = (unsigned int *)&x; + + can_enable(obj); + + if (obj->dev->GSR & 0x1) { + *i++ = obj->dev->RFS; // Frame + *i++ = obj->dev->RID; // ID + *i++ = obj->dev->RDA; // Data A + *i++ = obj->dev->RDB; // Data B + obj->dev->CMR = 0x04; // release receive buffer + + msg->id = x.id; + msg->len = x.dlc; + msg->format = (x.type)? CANExtended : CANStandard; + msg->type = (x.rtr)? CANRemote: CANData; + memcpy(msg->data,x.data,x.dlc); + return 1; + } + + return 0; +} + +void can_reset(can_t *obj) { + can_disable(obj); + obj->dev->GSR = 0; // Reset error counter when CAN1MOD is in reset +} + +unsigned char can_rderror(can_t *obj) { + return (obj->dev->GSR >> 16) & 0xFF; +} + +unsigned char can_tderror(can_t *obj) { + return (obj->dev->GSR >> 24) & 0xFF; +} + +void can_monitor(can_t *obj, int silent) { + uint32_t mod_mask = can_disable(obj); + if (silent) { + obj->dev->MOD |= (1 << 1); + } else { + obj->dev->MOD &= ~(1 << 1); + } + if (!(mod_mask & 1)) { + can_enable(obj); + } +} diff --git a/features/FEATURE_LWIP/lwip-interface/lwip-sys/lwip_random.c b/targets/TARGET_NXP/TARGET_LPC2460/device.h similarity index 57% rename from features/FEATURE_LWIP/lwip-interface/lwip-sys/lwip_random.c rename to targets/TARGET_NXP/TARGET_LPC2460/device.h index 7c1cf8de0e1..71deacc1116 100644 --- a/features/FEATURE_LWIP/lwip-interface/lwip-sys/lwip_random.c +++ b/targets/TARGET_NXP/TARGET_LPC2460/device.h @@ -1,5 +1,7 @@ +// The 'features' section in 'target.json' is now used to create the device's hardware preprocessor switches. +// Check the 'features' section of the target description in 'targets.json' for more details. /* mbed Microcontroller Library - * Copyright (c) 2017 ARM Limited + * Copyright (c) 2006-2015 ARM Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,41 +15,26 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#ifndef MBED_DEVICE_H +#define MBED_DEVICE_H -#include "lwip_random.h" -#if FEATURE_COMMON_PAL -#include "randLIB.h" -void lwip_seed_random(void) -{ - randLIB_seed_random(); -} -void lwip_add_random_seed(uint64_t seed) -{ - randLIB_add_seed(seed); -} -inline uint32_t lwip_get_random(void) -{ - return randLIB_get_32bit(); -} -#else -void lwip_seed_random(void) -{ -} -void lwip_add_random_seed(uint64_t seed) -{ -} -uint32_t lwip_get_random(void) -{ - return rand(); -} + +#define DEVICE_ID_LENGTH 32 +#define DEVICE_MAC_OFFSET 20 + + + + + +#include "objects.h" #endif diff --git a/targets/TARGET_NXP/TARGET_LPC2460/device/LPC24xx.h b/targets/TARGET_NXP/TARGET_LPC2460/device/LPC24xx.h new file mode 100644 index 00000000000..e73f0b17ffb --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC2460/device/LPC24xx.h @@ -0,0 +1,972 @@ +/* mbed Microcontroller Library - LPC24xx CMSIS-like structs + * Copyright (C) 2009-2015 ARM Limited. All rights reserved. + * + * An LPC24xx header file, based on LPC23xx.h + */ + +#ifndef __LPC24xx_H +#define __LPC24xx_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* + * ========================================================================== + * ---------- Interrupt Number Definition ----------------------------------- + * ========================================================================== + */ + +typedef enum IRQn +{ +/****** LPC23xx Specific Interrupt Numbers *******************************************************/ + WDT_IRQn = 0, /*!< Watchdog Timer Interrupt */ + + TIMER0_IRQn = 4, /*!< Timer0 Interrupt */ + TIMER1_IRQn = 5, /*!< Timer1 Interrupt */ + UART0_IRQn = 6, /*!< UART0 Interrupt */ + UART1_IRQn = 7, /*!< UART1 Interrupt */ + PWM0_IRQn = 8, /*!< PWM0 Interrupt */ + PWM1_IRQn = 8, /*!< PWM1 Interrupt */ + I2C0_IRQn = 9, /*!< I2C0 Interrupt */ + SPI_IRQn = 10, /*!< SPI Interrupt */ + SSP0_IRQn = 10, /*!< SSP0 Interrupt */ + SSP1_IRQn = 11, /*!< SSP1 Interrupt */ + PLL0_IRQn = 12, /*!< PLL0 Lock (Main PLL) Interrupt */ + RTC_IRQn = 13, /*!< Real Time Clock Interrupt */ + EINT0_IRQn = 14, /*!< External Interrupt 0 Interrupt */ + EINT1_IRQn = 15, /*!< External Interrupt 1 Interrupt */ + EINT2_IRQn = 16, /*!< External Interrupt 2 Interrupt */ + EINT3_IRQn = 17, /*!< External Interrupt 3 Interrupt */ + ADC_IRQn = 18, /*!< A/D Converter Interrupt */ + I2C1_IRQn = 19, /*!< I2C1 Interrupt */ + BOD_IRQn = 20, /*!< Brown-Out Detect Interrupt */ + ENET_IRQn = 21, /*!< Ethernet Interrupt */ + USB_IRQn = 22, /*!< USB Interrupt */ + CAN_IRQn = 23, /*!< CAN Interrupt */ + SDMMC_IRQn = 24, /*!< SD/MMC Interrupt */ + DMA_IRQn = 25, /*!< General Purpose DMA Interrupt */ + TIMER2_IRQn = 26, /*!< Timer2 Interrupt */ + TIMER3_IRQn = 27, /*!< Timer3 Interrupt */ + UART2_IRQn = 28, /*!< UART2 Interrupt */ + UART3_IRQn = 29, /*!< UART3 Interrupt */ + I2C2_IRQn = 30, /*!< I2C2 Interrupt */ + I2S_IRQn = 31, /*!< I2S Interrupt */ +} IRQn_Type; + +/* + * ========================================================================== + * ----------- Processor and Core Peripheral Section ------------------------ + * ========================================================================== + */ + +/* Configuration of the ARM7 Processor and Core Peripherals */ +#define __MPU_PRESENT 0 /*!< MPU present or not */ +#define __NVIC_PRIO_BITS 4 /*!< Number of Bits used for Priority Levels */ +#define __Vendor_SysTickConfig 0 /*!< Set to 1 if different SysTick Config is used */ + + +#include +#include "system_LPC24xx.h" /* System Header */ + + +/******************************************************************************/ +/* Device Specific Peripheral registers structures */ +/******************************************************************************/ +#if defined ( __CC_ARM ) + #pragma anon_unions +#endif + +/*------------- Vector Interupt Controler (VIC) ------------------------------*/ +typedef struct +{ + __I uint32_t IRQStatus; + __I uint32_t FIQStatus; + __I uint32_t RawIntr; + __IO uint32_t IntSelect; + __IO uint32_t IntEnable; + __O uint32_t IntEnClr; + __IO uint32_t SoftInt; + __O uint32_t SoftIntClr; + __IO uint32_t Protection; + __IO uint32_t SWPriorityMask; + __IO uint32_t RESERVED0[54]; + __IO uint32_t VectAddr[32]; + __IO uint32_t RESERVED1[32]; + __IO uint32_t VectPriority[32]; + __IO uint32_t RESERVED2[800]; + __IO uint32_t Address; +} LPC_VIC_TypeDef; + +/*------------- System Control (SC) ------------------------------------------*/ +typedef struct +{ + __IO uint32_t MAMCR; + __IO uint32_t MAMTIM; + uint32_t RESERVED0[14]; + __IO uint32_t MEMMAP; + uint32_t RESERVED1[15]; + __IO uint32_t PLL0CON; /* Clocking and Power Control */ + __IO uint32_t PLL0CFG; + __I uint32_t PLL0STAT; + __O uint32_t PLL0FEED; + uint32_t RESERVED2[12]; + __IO uint32_t PCON; + __IO uint32_t PCONP; + uint32_t RESERVED3[15]; + __IO uint32_t CCLKCFG; + __IO uint32_t USBCLKCFG; + __IO uint32_t CLKSRCSEL; + uint32_t RESERVED4[12]; + __IO uint32_t EXTINT; /* External Interrupts */ + __IO uint32_t INTWAKE; + __IO uint32_t EXTMODE; + __IO uint32_t EXTPOLAR; + uint32_t RESERVED6[12]; + __IO uint32_t RSID; /* Reset */ + __IO uint32_t CSPR; + __IO uint32_t AHBCFG1; + __IO uint32_t AHBCFG2; + uint32_t RESERVED7[4]; + __IO uint32_t SCS; /* Syscon Miscellaneous Registers */ + __IO uint32_t IRCTRIM; /* Clock Dividers */ + __IO uint32_t PCLKSEL0; + __IO uint32_t PCLKSEL1; + uint32_t RESERVED8[4]; + __IO uint32_t USBIntSt; /* USB Device/OTG Interrupt Register */ + uint32_t RESERVED9; +// __IO uint32_t CLKOUTCFG; /* Clock Output Configuration */ + } LPC_SC_TypeDef; + +/*------------- Pin Connect Block (PINCON) -----------------------------------*/ +typedef struct +{ + __IO uint32_t PINSEL0; + __IO uint32_t PINSEL1; + __IO uint32_t PINSEL2; + __IO uint32_t PINSEL3; + __IO uint32_t PINSEL4; + __IO uint32_t PINSEL5; + __IO uint32_t PINSEL6; + __IO uint32_t PINSEL7; + __IO uint32_t PINSEL8; + __IO uint32_t PINSEL9; + __IO uint32_t PINSEL10; + uint32_t RESERVED0[5]; + __IO uint32_t PINMODE0; + __IO uint32_t PINMODE1; + __IO uint32_t PINMODE2; + __IO uint32_t PINMODE3; + __IO uint32_t PINMODE4; + __IO uint32_t PINMODE5; + __IO uint32_t PINMODE6; + __IO uint32_t PINMODE7; + __IO uint32_t PINMODE8; + __IO uint32_t PINMODE9; + __IO uint32_t PINMODE_OD0; + __IO uint32_t PINMODE_OD1; + __IO uint32_t PINMODE_OD2; + __IO uint32_t PINMODE_OD3; + __IO uint32_t PINMODE_OD4; +} LPC_PINCON_TypeDef; + +#define PCTIM0 1 +#define PCTIM1 2 +#define PCUART0 3 +#define PCUART1 4 +#define PCPWM1 6 +#define PCI2C0 7 +#define PCSPI 8 +#define PCRTC 9 +#define PCSSP1 10 +#define PCEMC 11 +#define PCADC 12 +#define PCAN1 13 +#define PCAN2 14 +#define PCI2C1 19 +#define PCSSP0 21 +#define PCTIM2 22 +#define PCTIM3 23 +#define PCUART2 24 +#define PCUART3 25 +#define PCI2C2 26 +#define PCI2S 27 +#define PCSDC 28 +#define PCGPDMA 29 +#define PCENET 30 +#define PCUSB 31 + +/*------------- General Purpose Input/Output (GPIO) --------------------------*/ +typedef struct +{ + __IO uint32_t FIODIR; + uint32_t RESERVED0[3]; + __IO uint32_t FIOMASK; + __IO uint32_t FIOPIN; + __IO uint32_t FIOSET; + __O uint32_t FIOCLR; +} LPC_GPIO_TypeDef; + +typedef struct +{ + __I uint32_t IntStatus; + __I uint32_t IO0IntStatR; + __I uint32_t IO0IntStatF; + __O uint32_t IO0IntClr; + __IO uint32_t IO0IntEnR; + __IO uint32_t IO0IntEnF; + uint32_t RESERVED0[3]; + __I uint32_t IO2IntStatR; + __I uint32_t IO2IntStatF; + __O uint32_t IO2IntClr; + __IO uint32_t IO2IntEnR; + __IO uint32_t IO2IntEnF; +} LPC_GPIOINT_TypeDef; + +/*------------- Timer (TIM) --------------------------------------------------*/ +typedef struct +{ + __IO uint32_t IR; + __IO uint32_t TCR; + __IO uint32_t TC; + __IO uint32_t PR; + __IO uint32_t PC; + __IO uint32_t MCR; + __IO uint32_t MR0; + __IO uint32_t MR1; + __IO uint32_t MR2; + __IO uint32_t MR3; + __IO uint32_t CCR; + __I uint32_t CR0; + __I uint32_t CR1; + uint32_t RESERVED0[2]; + __IO uint32_t EMR; + uint32_t RESERVED1[12]; + __IO uint32_t CTCR; +} LPC_TIM_TypeDef; + +/*------------- Pulse-Width Modulation (PWM) ---------------------------------*/ +typedef struct +{ + __IO uint32_t IR; + __IO uint32_t TCR; + __IO uint32_t TC; + __IO uint32_t PR; + __IO uint32_t PC; + __IO uint32_t MCR; + __IO uint32_t MR0; + __IO uint32_t MR1; + __IO uint32_t MR2; + __IO uint32_t MR3; + __IO uint32_t CCR; + __I uint32_t CR0; + __I uint32_t CR1; + __I uint32_t CR2; + __I uint32_t CR3; + uint32_t RESERVED0; + __IO uint32_t MR4; + __IO uint32_t MR5; + __IO uint32_t MR6; + __IO uint32_t PCR; + __IO uint32_t LER; + uint32_t RESERVED1[7]; + __IO uint32_t CTCR; +} LPC_PWM_TypeDef; + +/*------------- Universal Asynchronous Receiver Transmitter (UART) -----------*/ +typedef struct +{ + union { + __I uint8_t RBR; + __O uint8_t THR; + __IO uint8_t DLL; + uint32_t RESERVED0; + }; + union { + __IO uint8_t DLM; + __IO uint32_t IER; + }; + union { + __I uint32_t IIR; + __O uint8_t FCR; + }; + __IO uint8_t LCR; + uint8_t RESERVED1[7]; + __IO uint8_t LSR; + uint8_t RESERVED2[7]; + __IO uint8_t SCR; + uint8_t RESERVED3[3]; + __IO uint32_t ACR; + __IO uint8_t ICR; + uint8_t RESERVED4[3]; + __IO uint8_t FDR; + uint8_t RESERVED5[7]; + __IO uint8_t TER; + uint8_t RESERVED6[27]; + __IO uint8_t RS485CTRL; + uint8_t RESERVED7[3]; + __IO uint8_t ADRMATCH; +} LPC_UART_TypeDef; + +typedef struct +{ + union { + __I uint8_t RBR; + __O uint8_t THR; + __IO uint8_t DLL; + uint32_t RESERVED0; + }; + union { + __IO uint8_t DLM; + __IO uint32_t IER; + }; + union { + __I uint32_t IIR; + __O uint8_t FCR; + }; + __IO uint8_t LCR; + uint8_t RESERVED1[3]; + __IO uint8_t MCR; + uint8_t RESERVED2[3]; + __IO uint8_t LSR; + uint8_t RESERVED3[3]; + __IO uint8_t MSR; + uint8_t RESERVED4[3]; + __IO uint8_t SCR; + uint8_t RESERVED5[3]; + __IO uint32_t ACR; + uint32_t RESERVED6; + __IO uint32_t FDR; + uint32_t RESERVED7; + __IO uint8_t TER; + uint8_t RESERVED8[27]; + __IO uint8_t RS485CTRL; + uint8_t RESERVED9[3]; + __IO uint8_t ADRMATCH; + uint8_t RESERVED10[3]; + __IO uint8_t RS485DLY; +} LPC_UART1_TypeDef; + +/*------------- Serial Peripheral Interface (SPI) ----------------------------*/ +typedef struct +{ + __IO uint32_t SPCR; + __I uint32_t SPSR; + __IO uint32_t SPDR; + __IO uint32_t SPCCR; + uint32_t RESERVED0[3]; + __IO uint32_t SPINT; +} LPC_SPI_TypeDef; + +/*------------- Synchronous Serial Communication (SSP) -----------------------*/ +typedef struct +{ + __IO uint32_t CR0; + __IO uint32_t CR1; + __IO uint32_t DR; + __I uint32_t SR; + __IO uint32_t CPSR; + __IO uint32_t IMSC; + __IO uint32_t RIS; + __IO uint32_t MIS; + __IO uint32_t ICR; + __IO uint32_t DMACR; +} LPC_SSP_TypeDef; + +/*------------- Inter-Integrated Circuit (I2C) -------------------------------*/ +typedef struct +{ + __IO uint32_t I2CONSET; + __I uint32_t I2STAT; + __IO uint32_t I2DAT; + __IO uint32_t I2ADR0; + __IO uint32_t I2SCLH; + __IO uint32_t I2SCLL; + __O uint32_t I2CONCLR; + __IO uint32_t MMCTRL; + __IO uint32_t I2ADR1; + __IO uint32_t I2ADR2; + __IO uint32_t I2ADR3; + __I uint32_t I2DATA_BUFFER; + __IO uint32_t I2MASK0; + __IO uint32_t I2MASK1; + __IO uint32_t I2MASK2; + __IO uint32_t I2MASK3; +} LPC_I2C_TypeDef; + +/*------------- Inter IC Sound (I2S) -----------------------------------------*/ +typedef struct +{ + __IO uint32_t I2SDAO; + __I uint32_t I2SDAI; + __O uint32_t I2STXFIFO; + __I uint32_t I2SRXFIFO; + __I uint32_t I2SSTATE; + __IO uint32_t I2SDMA1; + __IO uint32_t I2SDMA2; + __IO uint32_t I2SIRQ; + __IO uint32_t I2STXRATE; + __IO uint32_t I2SRXRATE; + __IO uint32_t I2STXBITRATE; + __IO uint32_t I2SRXBITRATE; + __IO uint32_t I2STXMODE; + __IO uint32_t I2SRXMODE; +} LPC_I2S_TypeDef; + +/*------------- Real-Time Clock (RTC) ----------------------------------------*/ +typedef struct +{ + __IO uint8_t ILR; + uint8_t RESERVED0[3]; + __IO uint8_t CTC; + uint8_t RESERVED1[3]; + __IO uint8_t CCR; + uint8_t RESERVED2[3]; + __IO uint8_t CIIR; + uint8_t RESERVED3[3]; + __IO uint8_t AMR; + uint8_t RESERVED4[3]; + __I uint32_t CTIME0; + __I uint32_t CTIME1; + __I uint32_t CTIME2; + __IO uint8_t SEC; + uint8_t RESERVED5[3]; + __IO uint8_t MIN; + uint8_t RESERVED6[3]; + __IO uint8_t HOUR; + uint8_t RESERVED7[3]; + __IO uint8_t DOM; + uint8_t RESERVED8[3]; + __IO uint8_t DOW; + uint8_t RESERVED9[3]; + __IO uint16_t DOY; + uint16_t RESERVED10; + __IO uint8_t MONTH; + uint8_t RESERVED11[3]; + __IO uint16_t YEAR; + uint16_t RESERVED12; + __IO uint32_t CALIBRATION; + __IO uint32_t GPREG0; + __IO uint32_t GPREG1; + __IO uint32_t GPREG2; + __IO uint32_t GPREG3; + __IO uint32_t GPREG4; + __IO uint8_t WAKEUPDIS; + uint8_t RESERVED13[3]; + __IO uint8_t PWRCTRL; + uint8_t RESERVED14[3]; + __IO uint8_t ALSEC; + uint8_t RESERVED15[3]; + __IO uint8_t ALMIN; + uint8_t RESERVED16[3]; + __IO uint8_t ALHOUR; + uint8_t RESERVED17[3]; + __IO uint8_t ALDOM; + uint8_t RESERVED18[3]; + __IO uint8_t ALDOW; + uint8_t RESERVED19[3]; + __IO uint16_t ALDOY; + uint16_t RESERVED20; + __IO uint8_t ALMON; + uint8_t RESERVED21[3]; + __IO uint16_t ALYEAR; + uint16_t RESERVED22; +} LPC_RTC_TypeDef; + +/*------------- Watchdog Timer (WDT) -----------------------------------------*/ +typedef struct +{ + __IO uint8_t WDMOD; + uint8_t RESERVED0[3]; + __IO uint32_t WDTC; + __O uint8_t WDFEED; + uint8_t RESERVED1[3]; + __I uint32_t WDTV; + __IO uint32_t WDCLKSEL; +} LPC_WDT_TypeDef; + +/*------------- Analog-to-Digital Converter (ADC) ----------------------------*/ +typedef struct +{ + __IO uint32_t ADCR; + __IO uint32_t ADGDR; + uint32_t RESERVED0; + __IO uint32_t ADINTEN; + __I uint32_t ADDR0; + __I uint32_t ADDR1; + __I uint32_t ADDR2; + __I uint32_t ADDR3; + __I uint32_t ADDR4; + __I uint32_t ADDR5; + __I uint32_t ADDR6; + __I uint32_t ADDR7; + __I uint32_t ADSTAT; + __IO uint32_t ADTRM; +} LPC_ADC_TypeDef; + +/*------------- Digital-to-Analog Converter (DAC) ----------------------------*/ +typedef struct +{ + __IO uint32_t DACR; + __IO uint32_t DACCTRL; + __IO uint16_t DACCNTVAL; +} LPC_DAC_TypeDef; + +/*------------- Multimedia Card Interface (MCI) ------------------------------*/ +typedef struct +{ + __IO uint32_t MCIPower; /* Power control */ + __IO uint32_t MCIClock; /* Clock control */ + __IO uint32_t MCIArgument; + __IO uint32_t MMCCommand; + __I uint32_t MCIRespCmd; + __I uint32_t MCIResponse0; + __I uint32_t MCIResponse1; + __I uint32_t MCIResponse2; + __I uint32_t MCIResponse3; + __IO uint32_t MCIDataTimer; + __IO uint32_t MCIDataLength; + __IO uint32_t MCIDataCtrl; + __I uint32_t MCIDataCnt; + __I uint32_t MCIStatus; + __O uint32_t MCIClear; + __IO uint32_t MCIMask0; + uint32_t RESERVED1[2]; + __I uint32_t MCIFifoCnt; + uint32_t RESERVED2[13]; + __IO uint32_t MCIFIFO[16]; +} LPC_MCI_TypeDef; + +/*------------- Controller Area Network (CAN) --------------------------------*/ +typedef struct +{ + __IO uint32_t mask[512]; /* ID Masks */ +} LPC_CANAF_RAM_TypeDef; + +typedef struct /* Acceptance Filter Registers */ +{ + __IO uint32_t AFMR; + __IO uint32_t SFF_sa; + __IO uint32_t SFF_GRP_sa; + __IO uint32_t EFF_sa; + __IO uint32_t EFF_GRP_sa; + __IO uint32_t ENDofTable; + __I uint32_t LUTerrAd; + __I uint32_t LUTerr; + __IO uint32_t FCANIE; + __IO uint32_t FCANIC0; + __IO uint32_t FCANIC1; +} LPC_CANAF_TypeDef; + +typedef struct /* Central Registers */ +{ + __I uint32_t CANTxSR; + __I uint32_t CANRxSR; + __I uint32_t CANMSR; +} LPC_CANCR_TypeDef; + +typedef struct /* Controller Registers */ +{ + __IO uint32_t MOD; + __O uint32_t CMR; + __IO uint32_t GSR; + __I uint32_t ICR; + __IO uint32_t IER; + __IO uint32_t BTR; + __IO uint32_t EWL; + __I uint32_t SR; + __IO uint32_t RFS; + __IO uint32_t RID; + __IO uint32_t RDA; + __IO uint32_t RDB; + __IO uint32_t TFI1; + __IO uint32_t TID1; + __IO uint32_t TDA1; + __IO uint32_t TDB1; + __IO uint32_t TFI2; + __IO uint32_t TID2; + __IO uint32_t TDA2; + __IO uint32_t TDB2; + __IO uint32_t TFI3; + __IO uint32_t TID3; + __IO uint32_t TDA3; + __IO uint32_t TDB3; +} LPC_CAN_TypeDef; + +/*------------- General Purpose Direct Memory Access (GPDMA) -----------------*/ +typedef struct /* Common Registers */ +{ + __I uint32_t DMACIntStat; + __I uint32_t DMACIntTCStat; + __O uint32_t DMACIntTCClear; + __I uint32_t DMACIntErrStat; + __O uint32_t DMACIntErrClr; + __I uint32_t DMACRawIntTCStat; + __I uint32_t DMACRawIntErrStat; + __I uint32_t DMACEnbldChns; + __IO uint32_t DMACSoftBReq; + __IO uint32_t DMACSoftSReq; + __IO uint32_t DMACSoftLBReq; + __IO uint32_t DMACSoftLSReq; + __IO uint32_t DMACConfig; + __IO uint32_t DMACSync; +} LPC_GPDMA_TypeDef; + +typedef struct /* Channel Registers */ +{ + __IO uint32_t DMACCSrcAddr; + __IO uint32_t DMACCDestAddr; + __IO uint32_t DMACCLLI; + __IO uint32_t DMACCControl; + __IO uint32_t DMACCConfig; +} LPC_GPDMACH_TypeDef; + +/*------------- Universal Serial Bus (USB) -----------------------------------*/ +typedef struct +{ + __I uint32_t HcRevision; /* USB Host Registers */ + __IO uint32_t HcControl; + __IO uint32_t HcCommandStatus; + __IO uint32_t HcInterruptStatus; + __IO uint32_t HcInterruptEnable; + __IO uint32_t HcInterruptDisable; + __IO uint32_t HcHCCA; + __I uint32_t HcPeriodCurrentED; + __IO uint32_t HcControlHeadED; + __IO uint32_t HcControlCurrentED; + __IO uint32_t HcBulkHeadED; + __IO uint32_t HcBulkCurrentED; + __I uint32_t HcDoneHead; + __IO uint32_t HcFmInterval; + __I uint32_t HcFmRemaining; + __I uint32_t HcFmNumber; + __IO uint32_t HcPeriodicStart; + __IO uint32_t HcLSTreshold; + __IO uint32_t HcRhDescriptorA; + __IO uint32_t HcRhDescriptorB; + __IO uint32_t HcRhStatus; + __IO uint32_t HcRhPortStatus1; + __IO uint32_t HcRhPortStatus2; + uint32_t RESERVED0[40]; + __I uint32_t Module_ID; + + __I uint32_t OTGIntSt; /* USB On-The-Go Registers */ + __IO uint32_t OTGIntEn; + __O uint32_t OTGIntSet; + __O uint32_t OTGIntClr; + __IO uint32_t OTGStCtrl; + __IO uint32_t OTGTmr; + uint32_t RESERVED1[58]; + + __I uint32_t USBDevIntSt; /* USB Device Interrupt Registers */ + __IO uint32_t USBDevIntEn; + __O uint32_t USBDevIntClr; + __O uint32_t USBDevIntSet; + + __O uint32_t USBCmdCode; /* USB Device SIE Command Registers */ + __I uint32_t USBCmdData; + + __I uint32_t USBRxData; /* USB Device Transfer Registers */ + __O uint32_t USBTxData; + __I uint32_t USBRxPLen; + __O uint32_t USBTxPLen; + __IO uint32_t USBCtrl; + __O uint32_t USBDevIntPri; + + __I uint32_t USBEpIntSt; /* USB Device Endpoint Interrupt Regs */ + __IO uint32_t USBEpIntEn; + __O uint32_t USBEpIntClr; + __O uint32_t USBEpIntSet; + __O uint32_t USBEpIntPri; + + __IO uint32_t USBReEp; /* USB Device Endpoint Realization Reg*/ + __O uint32_t USBEpInd; + __IO uint32_t USBMaxPSize; + + __I uint32_t USBDMARSt; /* USB Device DMA Registers */ + __O uint32_t USBDMARClr; + __O uint32_t USBDMARSet; + uint32_t RESERVED2[9]; + __IO uint32_t USBUDCAH; + __I uint32_t USBEpDMASt; + __O uint32_t USBEpDMAEn; + __O uint32_t USBEpDMADis; + __I uint32_t USBDMAIntSt; + __IO uint32_t USBDMAIntEn; + uint32_t RESERVED3[2]; + __I uint32_t USBEoTIntSt; + __O uint32_t USBEoTIntClr; + __O uint32_t USBEoTIntSet; + __I uint32_t USBNDDRIntSt; + __O uint32_t USBNDDRIntClr; + __O uint32_t USBNDDRIntSet; + __I uint32_t USBSysErrIntSt; + __O uint32_t USBSysErrIntClr; + __O uint32_t USBSysErrIntSet; + uint32_t RESERVED4[15]; + + __I uint32_t I2C_RX; /* USB OTG I2C Registers */ + __O uint32_t I2C_WO; + __I uint32_t I2C_STS; + __IO uint32_t I2C_CTL; + __IO uint32_t I2C_CLKHI; + __O uint32_t I2C_CLKLO; + uint32_t RESERVED5[823]; + + union { + __IO uint32_t USBClkCtrl; /* USB Clock Control Registers */ + __IO uint32_t OTGClkCtrl; + }; + union { + __I uint32_t USBClkSt; + __I uint32_t OTGClkSt; + }; +} LPC_USB_TypeDef; + +/*------------- Ethernet Media Access Controller (EMAC) ----------------------*/ +typedef struct +{ + __IO uint32_t MAC1; /* MAC Registers */ + __IO uint32_t MAC2; + __IO uint32_t IPGT; + __IO uint32_t IPGR; + __IO uint32_t CLRT; + __IO uint32_t MAXF; + __IO uint32_t SUPP; + __IO uint32_t TEST; + __IO uint32_t MCFG; + __IO uint32_t MCMD; + __IO uint32_t MADR; + __O uint32_t MWTD; + __I uint32_t MRDD; + __I uint32_t MIND; + uint32_t RESERVED0[2]; + __IO uint32_t SA0; + __IO uint32_t SA1; + __IO uint32_t SA2; + uint32_t RESERVED1[45]; + __IO uint32_t Command; /* Control Registers */ + __I uint32_t Status; + __IO uint32_t RxDescriptor; + __IO uint32_t RxStatus; + __IO uint32_t RxDescriptorNumber; + __I uint32_t RxProduceIndex; + __IO uint32_t RxConsumeIndex; + __IO uint32_t TxDescriptor; + __IO uint32_t TxStatus; + __IO uint32_t TxDescriptorNumber; + __IO uint32_t TxProduceIndex; + __I uint32_t TxConsumeIndex; + uint32_t RESERVED2[10]; + __I uint32_t TSV0; + __I uint32_t TSV1; + __I uint32_t RSV; + uint32_t RESERVED3[3]; + __IO uint32_t FlowControlCounter; + __I uint32_t FlowControlStatus; + uint32_t RESERVED4[34]; + __IO uint32_t RxFilterCtrl; /* Rx Filter Registers */ + __IO uint32_t RxFilterWoLStatus; + __IO uint32_t RxFilterWoLClear; + uint32_t RESERVED5; + __IO uint32_t HashFilterL; + __IO uint32_t HashFilterH; + uint32_t RESERVED6[882]; + __I uint32_t IntStatus; /* Module Control Registers */ + __IO uint32_t IntEnable; + __O uint32_t IntClear; + __O uint32_t IntSet; + uint32_t RESERVED7; + __IO uint32_t PowerDown; + uint32_t RESERVED8; + __IO uint32_t Module_ID; +} LPC_EMAC_TypeDef; + +/*-------------------- External Memory Controller (EMC) ----------------------*/ +typedef struct +{ + __IO uint32_t EMCControl; + __I uint32_t EMCStatus; + __IO uint32_t EMCConfig; + uint32_t RESERVED1[5]; + __IO uint32_t EMCDynamicControl; + __IO uint32_t EMCDynamicRefresh; + __IO uint32_t EMCDynamicReadConfig; + uint32_t RESERVED2; + __IO uint32_t EMCDynamicRP; + __IO uint32_t EMCDynamicRAS; + __IO uint32_t EMCDynamicSREX; + __IO uint32_t EMCDynamicAPR; + __IO uint32_t EMCDynamicDAL; + __IO uint32_t EMCDynamicWR; + __IO uint32_t EMCDynamicRC; + __IO uint32_t EMCDynamicRFC; + __IO uint32_t EMCDynamicXSR; + __IO uint32_t EMCDynamicRRD; + __IO uint32_t EMCDynamicMRD; + uint32_t RESERVED3[9]; + __IO uint32_t EMCStaticExtendedWait; + uint32_t RESERVED4[31]; + __IO uint32_t EMCDynamicConfig0; + __IO uint32_t EMCDynamicRasCas0; + uint32_t RESERVED5[6]; + __IO uint32_t EMCDynamicConfig1; + __IO uint32_t EMCDynamicRasCas1; + uint32_t RESERVED6[6]; + __IO uint32_t EMCDynamicConfic2; + __IO uint32_t EMCDynamicRasCas2; + uint32_t RESERVED7[6]; + __IO uint32_t EMCDynamicConfig3; + __IO uint32_t EMCDynamicRasCas3; + uint32_t RESERVED8[38]; + __IO uint32_t EMCStaticConfig0; + __IO uint32_t EMCStaticWaitWen0; + __IO uint32_t EMCStaticWaitOen0; + __IO uint32_t EMCStaticWaitRd0; + __IO uint32_t EMCStaticWaitPage0; + __IO uint32_t EMCStaticWaitWr0; + __IO uint32_t EMCStaticWaitTurn0; + uint32_t RESERVED9; + __IO uint32_t EMCStaticConfig1; + __IO uint32_t EMCStaticWaitWen1; + __IO uint32_t EMCStaticWaitOen1; + __IO uint32_t EMCStaticWaitRd1; + __IO uint32_t EMCStaticWaitPage1; + __IO uint32_t EMCStaticWaitWr1; + __IO uint32_t EMCStaticWaitTurn1; + uint32_t RESERVED10; + __IO uint32_t EMCStaticConfig2; + __IO uint32_t EMCStaticWaitWen2; + __IO uint32_t EMCStaticWaitOen2; + __IO uint32_t EMCStaticWaitRd2; + __IO uint32_t EMCStaticWaitPage2; + __IO uint32_t EMCStaticWaitWr2; + __IO uint32_t EMCStaticWaitTurn2; + uint32_t RESERVED11; + __IO uint32_t EMCStaticConfig3; + __IO uint32_t EMCStaticWaitWen3; + __IO uint32_t EMCStaticWaitOen3; + __IO uint32_t EMCStaticWaitRd3; + __IO uint32_t EMCStaticWaitPage3; + __IO uint32_t EMCStaticWaitWr3; + __IO uint32_t EMCStaticWaitTurn3; +} LPC_EMC_TypeDef; +#if defined ( __CC_ARM ) + #pragma no_anon_unions +#endif + +/******************************************************************************/ +/* Peripheral memory map */ +/******************************************************************************/ +/* Base addresses */ + +/* AHB Peripheral # 0 */ + +/* +#define FLASH_BASE (0x00000000UL) +#define RAM_BASE (0x10000000UL) +#define GPIO_BASE (0x2009C000UL) +#define APB0_BASE (0x40000000UL) +#define APB1_BASE (0x40080000UL) +#define AHB_BASE (0x50000000UL) +#define CM3_BASE (0xE0000000UL) +*/ + +// TODO - #define VIC_BASE_ADDR 0xFFFFF000 + +#define LPC_WDT_BASE (0xE0000000) +#define LPC_TIM0_BASE (0xE0004000) +#define LPC_TIM1_BASE (0xE0008000) +#define LPC_UART0_BASE (0xE000C000) +#define LPC_UART1_BASE (0xE0010000) +#define LPC_PWM1_BASE (0xE0018000) +#define LPC_I2C0_BASE (0xE001C000) +#define LPC_SPI_BASE (0xE0020000) +#define LPC_RTC_BASE (0xE0024000) +#define LPC_GPIOINT_BASE (0xE0028080) +#define LPC_PINCON_BASE (0xE002C000) +#define LPC_SSP1_BASE (0xE0030000) +#define LPC_ADC_BASE (0xE0034000) +#define LPC_CANAF_RAM_BASE (0xE0038000) +#define LPC_CANAF_BASE (0xE003C000) +#define LPC_CANCR_BASE (0xE0040000) +#define LPC_CAN1_BASE (0xE0044000) +#define LPC_CAN2_BASE (0xE0048000) +#define LPC_I2C1_BASE (0xE005C000) +#define LPC_SSP0_BASE (0xE0068000) +#define LPC_DAC_BASE (0xE006C000) +#define LPC_TIM2_BASE (0xE0070000) +#define LPC_TIM3_BASE (0xE0074000) +#define LPC_UART2_BASE (0xE0078000) +#define LPC_UART3_BASE (0xE007C000) +#define LPC_I2C2_BASE (0xE0080000) +#define LPC_I2S_BASE (0xE0088000) +#define LPC_MCI_BASE (0xE008C000) +#define LPC_SC_BASE (0xE01FC000) +#define LPC_EMAC_BASE (0xFFE00000) +#define LPC_GPDMA_BASE (0xFFE04000) +#define LPC_GPDMACH0_BASE (0xFFE04100) +#define LPC_GPDMACH1_BASE (0xFFE04120) +#define LPC_EMC_BASE (0xFFE08000) +#define LPC_USB_BASE (0xFFE0C000) +#define LPC_VIC_BASE (0xFFFFF000) + +/* GPIOs */ +#define LPC_GPIO0_BASE (0x3FFFC000) +#define LPC_GPIO1_BASE (0x3FFFC020) +#define LPC_GPIO2_BASE (0x3FFFC040) +#define LPC_GPIO3_BASE (0x3FFFC060) +#define LPC_GPIO4_BASE (0x3FFFC080) + + +/******************************************************************************/ +/* Peripheral declaration */ +/******************************************************************************/ +#define LPC_SC (( LPC_SC_TypeDef *) LPC_SC_BASE) +#define LPC_GPIO0 (( LPC_GPIO_TypeDef *) LPC_GPIO0_BASE) +#define LPC_GPIO1 (( LPC_GPIO_TypeDef *) LPC_GPIO1_BASE) +#define LPC_GPIO2 (( LPC_GPIO_TypeDef *) LPC_GPIO2_BASE) +#define LPC_GPIO3 (( LPC_GPIO_TypeDef *) LPC_GPIO3_BASE) +#define LPC_GPIO4 (( LPC_GPIO_TypeDef *) LPC_GPIO4_BASE) +#define LPC_WDT (( LPC_WDT_TypeDef *) LPC_WDT_BASE) +#define LPC_TIM0 (( LPC_TIM_TypeDef *) LPC_TIM0_BASE) +#define LPC_TIM1 (( LPC_TIM_TypeDef *) LPC_TIM1_BASE) +#define LPC_TIM2 (( LPC_TIM_TypeDef *) LPC_TIM2_BASE) +#define LPC_TIM3 (( LPC_TIM_TypeDef *) LPC_TIM3_BASE) +#define LPC_UART0 (( LPC_UART_TypeDef *) LPC_UART0_BASE) +#define LPC_UART1 (( LPC_UART1_TypeDef *) LPC_UART1_BASE) +#define LPC_UART2 (( LPC_UART_TypeDef *) LPC_UART2_BASE) +#define LPC_UART3 (( LPC_UART_TypeDef *) LPC_UART3_BASE) +#define LPC_PWM1 (( LPC_PWM_TypeDef *) LPC_PWM1_BASE) +#define LPC_I2C0 (( LPC_I2C_TypeDef *) LPC_I2C0_BASE) +#define LPC_I2C1 (( LPC_I2C_TypeDef *) LPC_I2C1_BASE) +#define LPC_I2C2 (( LPC_I2C_TypeDef *) LPC_I2C2_BASE) +#define LPC_I2S (( LPC_I2S_TypeDef *) LPC_I2S_BASE) +#define LPC_SPI (( LPC_SPI_TypeDef *) LPC_SPI_BASE) +#define LPC_RTC (( LPC_RTC_TypeDef *) LPC_RTC_BASE) +#define LPC_GPIOINT (( LPC_GPIOINT_TypeDef *) LPC_GPIOINT_BASE) +#define LPC_PINCON (( LPC_PINCON_TypeDef *) LPC_PINCON_BASE) +#define LPC_SSP0 (( LPC_SSP_TypeDef *) LPC_SSP0_BASE) +#define LPC_SSP1 (( LPC_SSP_TypeDef *) LPC_SSP1_BASE) +#define LPC_ADC (( LPC_ADC_TypeDef *) LPC_ADC_BASE) +#define LPC_DAC (( LPC_DAC_TypeDef *) LPC_DAC_BASE) +#define LPC_CANAF_RAM ((LPC_CANAF_RAM_TypeDef *) LPC_CANAF_RAM_BASE) +#define LPC_CANAF (( LPC_CANAF_TypeDef *) LPC_CANAF_BASE) +#define LPC_CANCR (( LPC_CANCR_TypeDef *) LPC_CANCR_BASE) +#define LPC_CAN1 (( LPC_CAN_TypeDef *) LPC_CAN1_BASE) +#define LPC_CAN2 (( LPC_CAN_TypeDef *) LPC_CAN2_BASE) +#define LPC_MCI (( LPC_MCI_TypeDef *) LPC_MCI_BASE) +#define LPC_EMAC (( LPC_EMAC_TypeDef *) LPC_EMAC_BASE) +#define LPC_GPDMA (( LPC_GPDMA_TypeDef *) LPC_GPDMA_BASE) +#define LPC_GPDMACH0 (( LPC_GPDMACH_TypeDef *) LPC_GPDMACH0_BASE) +#define LPC_GPDMACH1 (( LPC_GPDMACH_TypeDef *) LPC_GPDMACH1_BASE) +#define LPC_USB (( LPC_USB_TypeDef *) LPC_USB_BASE) +#define LPC_VIC (( LPC_VIC_TypeDef *) LPC_VIC_BASE) +#define LPC_EMC (( LPC_EMC_TypeDef *) LPC_EMC_BASE) + +#ifdef __cplusplus + } +#endif + +#endif // __LPC24xx_H + diff --git a/targets/TARGET_NXP/TARGET_LPC2460/device/TOOLCHAIN_GCC_ARM/LPC2460.ld b/targets/TARGET_NXP/TARGET_LPC2460/device/TOOLCHAIN_GCC_ARM/LPC2460.ld new file mode 100644 index 00000000000..db36b39dcce --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC2460/device/TOOLCHAIN_GCC_ARM/LPC2460.ld @@ -0,0 +1,210 @@ +OUTPUT_FORMAT("elf32-littlearm", "elf32-bigarm", "elf32-littlearm") +OUTPUT_ARCH(arm) +ENTRY(vectors) + +/* Memory Definitions: */ +MEMORY +{ + Flash (rx) : ORIGIN = 0xA0001000, LENGTH = 512k + Ram (rwx) : ORIGIN = 0x40000040, LENGTH = 64k - 0x40 + UsbRam (rw) : ORIGIN = 0x7FD00000, LENGTH = 8k + EthRam (rw) : ORIGIN = 0x7FE00000, LENGTH = 16k + CanRam (rw) : ORIGIN = 0xE0038000, LENGTH = 2k + BatRam (rw) : ORIGIN = 0xE0084000, LENGTH = 2k +} + +/* Stack sizes: */ +UND_Stack_Size = 64; +SVC_Stack_Size = 64; +ABT_Stack_Size = 64; +FIQ_Stack_Size = 64; +IRQ_Stack_Size = 64; +User_Stack_Size = 4096; +Stack_Size_Total = UND_Stack_Size + SVC_Stack_Size + ABT_Stack_Size + FIQ_Stack_Size + IRQ_Stack_Size + User_Stack_Size; + +/* Stack tops for each mode: */ +__und_stack_top__ = __stacks_top__; +__abt_stack_top__ = __und_stack_top__ - UND_Stack_Size ; +__fiq_stack_top__ = __abt_stack_top__ - ABT_Stack_Size ; +__irq_stack_top__ = __fiq_stack_top__ - FIQ_Stack_Size ; +__svc_stack_top__ = __irq_stack_top__ - IRQ_Stack_Size ; +__usr_stack_top__ = __svc_stack_top__ - User_Stack_Size ; + +/* C-accessible symbols for memory address ranges: */ +__FLASH_segment_start__ = ORIGIN( Flash ); +__FLASH_segment_end__ = ORIGIN( Flash ) + LENGTH( Flash ); +__SRAM_segment_start__ = ORIGIN( Ram ); +__SRAM_segment_end__ = ORIGIN( Ram ) + LENGTH( Ram ); + +/* Stacks (full descending) at top of RAM, grows downward: + * + * __stack_min__ is used by the malloc implementation to ensure heap never collides + * with stack (assuming stack never grows beyond Stack_Size_Total in length) */ +__stacks_top__ = __SRAM_segment_end__; +__stacks_min__ = __SRAM_segment_end__ - Stack_Size_Total; + +SECTIONS +{ + /* first section is .text which is used for code */ + __text_start__ = . ; + .text : { + __privileged_code_start__ = . ; + KEEP( *( .vectors ) ) + *( .privileged_code ) + + __privileged_code_end__ = .; + + *( .text .text.* .gnu.linkonce.t.* ) + *( .plt ) + *( .gnu.warning ) + *( .glue_7t ) *( .glue_7 ) *( .vfp11_veneer ) + + *( .rodata .rodata.* .gnu.linkonce.r.* ) + + *(.ARM.extab* .gnu.linkonce.armextab.*) + *(.gcc_except_table) + *(.eh_frame_hdr) + *(.eh_frame) + + . = ALIGN( 4 ) ; + KEEP( *( .init ) ) + . = ALIGN( 4 ) ; + __preinit_array_start = . ; + KEEP( *( .preinit_array ) ) + __preinit_array_end = . ; + . = ALIGN( 4 ) ; + __init_array_start = . ; + KEEP( *( SORT( .init_array.* ) ) ) + KEEP( *( .init_array ) ) + __init_array_end = . ; + + . = ALIGN( 4 ) ; + KEEP( *crtbegin.o( .ctors ) ) + KEEP( *( EXCLUDE_FILE( *crtend.o ) .ctors ) ) + KEEP( *( SORT( .ctors.* ) ) ) + KEEP( *crtend.o( .ctors ) ) + + . = ALIGN( 4 ) ; + KEEP( *( .fini ) ) + . = ALIGN( 4 ) ; + __fini_array_start = . ; + KEEP( *( .fini_array ) ) + KEEP( *( SORT( .fini_array.* ) ) ) + __fini_array_end = . ; + + KEEP( *crtbegin.o( .dtors ) ) + KEEP( *( EXCLUDE_FILE( *crtend.o ) .dtors ) ) + KEEP( *( SORT( .dtors.* ) ) ) + KEEP( *crtend.o( .dtors ) ) + + } >Flash + + __exidx_start = . ; + .ARM.exidx : { + *( .ARM.exidx* .gnu.linkonce.armexidx.* ) + } >Flash + __exidx_end = . ; + + .text.align : { . = ALIGN( 8 ) ; } >Flash /* Alignment schenanigans */ + __text_end__ = . ; + + /* .bss section -- used for uninitialized data */ + /* Located at the start of RAM */ + .bss (NOLOAD) : { + __bss_start__ = . ; + *crt0.o( .ram_vectors ) + + __user_bss_start__ = . ; + *( .user_bss ) + __user_bss_end__ = . ; + + *( .shbss ) + *( .bss .bss.* .gnu.linkonce.b.* ) + *( COMMON ) + *( .ram.b ) + . = ALIGN( 8 ) ; + + __bss_end__ = . ; + } >Ram AT>Flash + + /* .data section -- used for initialized data */ + .data : { + __data_start__ = . ; + KEEP( *( .jcr ) ) + *( .got.plt ) *( .got ) + *( .shdata ) + *( .data .data.* .gnu.linkonce.d.* ) + *( .ram ) + . = ALIGN( 8 ) ; + __data_end__ = . ; + } >Ram AT>Flash + + __data_init_start__ = LOADADDR( .data ) ; + + /* Heap starts here and grows up in memory */ + . = ALIGN( 8 ) ; + __heap_start__ = . ; + end = . ; + __end__ = . ; + + .stab 0 (NOLOAD) : { *(.stab) } + .stabstr 0 (NOLOAD) : { *(.stabstr) } + /* DWARF debug sections. */ + /* Symbols in the DWARF debugging sections are relative to the */ + /* beginning of the section so we begin them at 0. */ + /* DWARF 1 */ + .debug 0 : { *(.debug) } + .line 0 : { *(.line) } + /* GNU DWARF 1 extensions */ + .debug_srcinfo 0 : { *(.debug_srcinfo) } + .debug_sfnames 0 : { *(.debug_sfnames) } + /* DWARF 1.1 and DWARF 2 */ + .debug_aranges 0 : { *(.debug_aranges) } + .debug_pubnames 0 : { *(.debug_pubnames) } + /* DWARF 2 */ + .debug_info 0 : { *(.debug_info .gnu.linkonce.wi.*) } + .debug_abbrev 0 : { *(.debug_abbrev) } + .debug_line 0 : { *(.debug_line) } + .debug_frame 0 : { *(.debug_frame) } + .debug_str 0 : { *(.debug_str) } + .debug_loc 0 : { *(.debug_loc) } + .debug_macinfo 0 : { *(.debug_macinfo) } + /* SGI/MIPS DWARF 2 extensions */ + .debug_weaknames 0 : { *(.debug_weaknames) } + .debug_funcnames 0 : { *(.debug_funcnames) } + .debug_typenames 0 : { *(.debug_typenames) } + .debug_varnames 0 : { *(.debug_varnames) } + /* DWARF 3 */ + .debug_pubtypes 0 : { *(.debug_pubtypes) } + .debug_ranges 0 : { *(.debug_ranges) } + + .note.gnu.arm.ident 0 : { KEEP( *( .note.gnu.arm.ident ) ) } + .ARM.attributes 0 : { + KEEP( *( .ARM.attributes ) ) + KEEP( *( .gnu.attributes ) ) + } + /DISCARD/ : { *( .note.GNU-stack ) } + + /* C data can be defined as being in special purpose RAMs using + * __attribute__ ((section ("ethram"))) for example. */ + .usbram (NOLOAD): + { + *( .usbram ) + *( .usbram.* ) + } > UsbRam + .ethram (NOLOAD): + { + *( .ethram ) + *( .ethram.* ) + } > EthRam + .canram (NOLOAD): + { + *( .canram ) + *( .canram.* ) + } > CanRam + .batram (NOLOAD): + { + *( .batram ) + *( .batram.* ) + } > BatRam +} diff --git a/targets/TARGET_NXP/TARGET_LPC2460/device/TOOLCHAIN_GCC_ARM/vector_functions.S b/targets/TARGET_NXP/TARGET_LPC2460/device/TOOLCHAIN_GCC_ARM/vector_functions.S new file mode 100644 index 00000000000..8afac4c300f --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC2460/device/TOOLCHAIN_GCC_ARM/vector_functions.S @@ -0,0 +1,195 @@ +/* .include "vector_defns.h" */ + + + +.section .privileged_code, "ax" +.arm + + +.weak __mbed_fiq +.weak __mbed_undef +.weak __mbed_prefetch_abort +.weak __mbed_data_abort +.weak __mbed_irq +.weak __mbed_swi +.weak __mbed_dcc_irq +.weak __mbed_reset +.global __mbed_init_realmonitor +.weak SVC_Handler +.weak IRQ_Handler +/* .global __mbed_init */ + + + + +__mbed_fiq: + B __mbed_fiq +__mbed_undef: + LDR PC, =0x7fffffa0 +__mbed_prefetch_abort: + LDR PC, =0x7fffffb0 +__mbed_data_abort: + LDR PC, =0x7fffffc0 +__mbed_irq: +/* + If RTOS is enabled then goto RTOS IRQ handler +*/ + PUSH {R0} + LDR R0, =IRQ_Handler + CMP R0, #0 + POP {R0} + BNE IRQ_Handler +/* + else use CMSIS IRQ handler +*/ + MSR CPSR_c, #0x1F|0x80|0x40 + + STMDB sp!, {r0-r3,r12,lr} + + MOV r0, #0xFFFFFF00 + LDR r0, [r0] + + MOV lr, pc + BX r0 + + MOV r0, #0xFFFFFF00 + STR r0, [r0] + + LDMFD sp!,{r0-r3,r12,lr} + + MSR CPSR_c, #0x12|0x80|0x40 + + SUBS pc, lr, #4 + +__mbed_swi: +/* + If RTOS is enabled then goto RTOS SVC handler +*/ + PUSH {R0} + LDR R0, =SVC_Handler + CMP R0, #0 + POP {R0} + BNE SVC_Handler +/* + else use CMSIS SVC handler +*/ + STMFD sp!, {a4, r4, ip, lr} + + LDR r4, =0x40000040 + + LDR a4, =0x00940000 + LDR PC, =0x7ffff820 + +__mbed_dcc_irq: + LDMFD sp!,{r0-r3,r12,lr} + + MSR CPSR_c, #0x12|0x80|0x40 + + SUB lr, lr, #4 + STMFD sp!, {ip,lr} + + LDR LR, =0xfffff000 + STR LR, [LR, #0xf00] + + LDR PC, =0x7fffffe0 +/* + __mbed_reset is called after reset + we setup the stacks and realmonitor, then call Reset_Handler like on M3 +*/ + +.section .text, "ax" +.arm +.global Reset_handler +Reset_Handler: + .extern __libc_init_array + .extern SystemInit + .weak software_init_hook + LDR R0, =SystemInit + MOV LR, PC + BX R0 + +/* if (software_init_hook) // give control to the RTOS + software_init_hook(); // this will also call __libc_init_array +*/ + LDR R0, =software_init_hook + CMP R0, #0 + BEQ nortos + ORR R0,R0,#1 /* set thumb address */ + BX R0 +/* else */ +nortos: + LDR R0, =__libc_init_array + MOV LR, PC + BX R0 + + MSR CPSR_c, #0x1F /* enable irq */ + + LDR R0, =main + BX R0 + +__mbed_reset: + LDR R0, =( __SRAM_segment_end__ ) + + MSR CPSR_c, #0x1B|0x80|0x40 + MOV SP, R0 + SUB R0, R0, #0x00000040 + + MSR CPSR_c, #0x17|0x80|0x40 + MOV SP, R0 + SUB R0, R0, #0x00000040 + + MSR CPSR_c, #0x11|0x80|0x40 + MOV SP, R0 + SUB R0, R0, #0x00000040 + + MSR CPSR_c, #0x12|0x80|0x40 + MOV SP, R0 + SUB R0, R0, #0x00000040 + + MSR CPSR_c, #0x13|0x80|0x40 + MOV SP, R0 + SUB R0, R0, #0x00000040 + +/* + MSR CPSR_c, #0x10|0x80|0x40 + MOV SP, R0 +*/ + MSR CPSR_c, #0x1F|0x80|0x40 + MOV SP, R0 + + MSR CPSR_c, #0x13|0x80|0x40 /* execute in Supervisor mode */ + +/* Relocate .data section (Copy from ROM to RAM) */ + LDR R1, =__text_end__ /* _etext */ + LDR R2, =__data_start__ /* _data */ + LDR R3, =__data_end__ /* _edata */ + CMP R2, R3 + BEQ DataIsEmpty +LoopRel: CMP R2, R3 + LDRLO R0, [R1], #4 + STRLO R0, [R2], #4 + BLO LoopRel +DataIsEmpty: + +/* Clear .bss section (Zero init) */ + MOV R0, #0 + LDR R1, =__bss_start__ + LDR R2, =__bss_end__ + CMP R1,R2 + BEQ BSSIsEmpty +LoopZI: CMP R1, R2 + STRLO R0, [R1], #4 + BLO LoopZI +BSSIsEmpty: + + +/* Init realmonitor */ +/* + LDR R0, =__mbed_init_realmonitor + MOV LR, PC + BX R0 +*/ + +/* Go to Reset_Handler */ + LDR R0, =Reset_Handler + BX R0 diff --git a/targets/TARGET_NXP/TARGET_LPC2460/device/TOOLCHAIN_GCC_ARM/vector_table.S b/targets/TARGET_NXP/TARGET_LPC2460/device/TOOLCHAIN_GCC_ARM/vector_table.S new file mode 100644 index 00000000000..d797c3794d1 --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC2460/device/TOOLCHAIN_GCC_ARM/vector_table.S @@ -0,0 +1,45 @@ +# 1 "vector_table.s" +# 1 "" +# 1 "" +# 1 "vector_table.s" +; + + + + +# 1 "vector_defns.h" 1 +# 7 "vector_table.s" 2 + +; + + + + + + + + .section .vectors, "ax" + .arm + + + .global __main + .global __mbed_reset + .global __mbed_undef + .global __mbed_swi + .global __mbed_prefetch_abort + .global __mbed_data_abort + .global __mbed_irq + .global __mbed_fiq + +; + + +_start: + LDR PC, =__mbed_reset + LDR PC, =__mbed_undef + LDR PC, =__mbed_swi + LDR PC, =__mbed_prefetch_abort + LDR PC, =__mbed_data_abort + NOP ; + LDR PC, =__mbed_irq + LDR PC, =__mbed_fiq diff --git a/targets/TARGET_NXP/TARGET_LPC2460/device/cmsis.h b/targets/TARGET_NXP/TARGET_LPC2460/device/cmsis.h new file mode 100644 index 00000000000..ae57701416f --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC2460/device/cmsis.h @@ -0,0 +1,13 @@ +/* mbed Microcontroller Library - CMSIS + * Copyright (C) 2009-2015 ARM Limited. All rights reserved. + * + * A generic CMSIS include header, pulling in LPC2368 specifics + */ + +#ifndef MBED_CMSIS_H +#define MBED_CMSIS_H + +#include "LPC24xx.h" +#include "cmsis_nvic.h" + +#endif diff --git a/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L072CZ_LRWAN1/device/cmsis.h b/targets/TARGET_NXP/TARGET_LPC2460/device/cmsis_nvic.c similarity index 81% rename from targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L072CZ_LRWAN1/device/cmsis.h rename to targets/TARGET_NXP/TARGET_LPC2460/device/cmsis_nvic.c index 734947a235d..b7f02e2fa74 100644 --- a/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L072CZ_LRWAN1/device/cmsis.h +++ b/targets/TARGET_NXP/TARGET_LPC2460/device/cmsis_nvic.c @@ -1,7 +1,7 @@ /* mbed Microcontroller Library - * A generic CMSIS include header + * CMSIS-style functionality to support dynamic vectors ******************************************************************************* - * Copyright (c) 2017, STMicroelectronics + * Copyright (c) 2011-2015 ARM Limited. All rights reserved. * All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -12,7 +12,7 @@ * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of its contributors + * 3. Neither the name of ARM Limited nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * @@ -28,11 +28,13 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ******************************************************************************* */ +#include "cmsis_nvic.h" -#ifndef MBED_CMSIS_H -#define MBED_CMSIS_H +void NVIC_SetVector(IRQn_Type IRQn, uint32_t vector) { + LPC_VIC->VectAddr[(int)IRQn] = vector; +} -#include "stm32l0xx.h" -#include "cmsis_nvic.h" +uint32_t NVIC_GetVector(IRQn_Type IRQn) { + return LPC_VIC->VectAddr[(int)IRQn]; +} -#endif diff --git a/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L072CZ_LRWAN1/device/cmsis_nvic.h b/targets/TARGET_NXP/TARGET_LPC2460/device/cmsis_nvic.h similarity index 84% rename from targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L072CZ_LRWAN1/device/cmsis_nvic.h rename to targets/TARGET_NXP/TARGET_LPC2460/device/cmsis_nvic.h index baba2251b18..d22cf0e4c70 100644 --- a/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L072CZ_LRWAN1/device/cmsis_nvic.h +++ b/targets/TARGET_NXP/TARGET_LPC2460/device/cmsis_nvic.h @@ -1,7 +1,7 @@ /* mbed Microcontroller Library * CMSIS-style functionality to support dynamic vectors ******************************************************************************* - * Copyright (c) 2017, STMicroelectronics + * Copyright (c) 2011-2015 ARM Limited. All rights reserved. * All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -12,7 +12,7 @@ * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of its contributors + * 3. Neither the name of ARM Limited nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * @@ -27,16 +27,13 @@ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ******************************************************************************* - */ + */ #ifndef MBED_CMSIS_NVIC_H #define MBED_CMSIS_NVIC_H -// CORE: 16 vectors = 64 bytes from 0x00 to 0x3F -// MCU Peripherals: 32 vectors = 128 bytes from 0x40 to 0xBF -// Total: 48 vectors = 192 bytes (0xC0) to be reserved in RAM -#define NVIC_NUM_VECTORS 48 -#define NVIC_USER_IRQ_OFFSET 16 +#define NVIC_NUM_VECTORS 32 +#define NVIC_USER_IRQ_OFFSET 0 #include "cmsis.h" diff --git a/targets/TARGET_NXP/TARGET_LPC2460/device/core_arm7.c b/targets/TARGET_NXP/TARGET_LPC2460/device/core_arm7.c new file mode 100644 index 00000000000..6eba5565d34 --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC2460/device/core_arm7.c @@ -0,0 +1,44 @@ +/* mbed Microcontroller Library + * Copyright (C) 2008-2015 ARM Limited. All rights reserved. + * + * ARM7 version of CMSIS-like functionality - not advised for use outside mbed! + * based on core_cm3.h, V1.20 + */ + +#include + + +/* define compiler specific symbols */ +#if defined ( __CC_ARM ) + #define __ASM __asm /*!< asm keyword for armcc */ + #define __INLINE __inline /*!< inline keyword for armcc */ + +#elif defined ( __ICCARM__ ) + #define __ASM __asm /*!< asm keyword for iarcc */ + #define __INLINE inline /*!< inline keyword for iarcc. Only avaiable in High optimization mode! */ + +#elif defined ( __GNUC__ ) + #define __ASM __asm /*!< asm keyword for gcc */ + #define __INLINE inline /*!< inline keyword for gcc */ + +#elif defined ( __TASKING__ ) + #define __ASM __asm /*!< asm keyword for TASKING Compiler */ + #define __INLINE inline /*!< inline keyword for TASKING Compiler */ + +#endif + +#if defined ( __CC_ARM ) +/** + * @brief Return the Main Stack Pointer (return current ARM7 stack) + * + * @param none + * @return uint32_t Main Stack Pointer + * + * Return the current value of the MSP (main stack pointer) + * Cortex processor register + */ +uint32_t __get_MSP(void) +{ + return __current_sp(); +} +#endif diff --git a/targets/TARGET_NXP/TARGET_LPC2460/device/core_arm7.h b/targets/TARGET_NXP/TARGET_LPC2460/device/core_arm7.h new file mode 100644 index 00000000000..5879cc19ada --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC2460/device/core_arm7.h @@ -0,0 +1,343 @@ +/* mbed Microcontroller Library + * Copyright (C) 2008-2015 ARM Limited. All rights reserved. + * + * ARM7 version of CMSIS-like functionality - not advised for use outside mbed! + * based on core_cm3.h, V1.20 + */ + +#ifndef __ARM7_CORE_H__ +#define __ARM7_CORE_H__ + +#include "vector_defns.h" +#ifdef __cplusplus +extern "C" { +#endif +//#include "cmsis_nvic.h" + +#define __CM3_CMSIS_VERSION_MAIN (0x01) /*!< [31:16] CMSIS HAL main version */ +#define __CM3_CMSIS_VERSION_SUB (0x20) /*!< [15:0] CMSIS HAL sub version */ +#define __CM3_CMSIS_VERSION ((__CM3_CMSIS_VERSION_MAIN << 16) | __CM3_CMSIS_VERSION_SUB) /*!< CMSIS HAL version number */ + +#define __CORTEX_M (0x00) /*!< Cortex core */ + +/** + * Lint configuration \n + * ----------------------- \n + * + * The following Lint messages will be suppressed and not shown: \n + * \n + * --- Error 10: --- \n + * register uint32_t __regBasePri __asm("basepri"); \n + * Error 10: Expecting ';' \n + * \n + * --- Error 530: --- \n + * return(__regBasePri); \n + * Warning 530: Symbol '__regBasePri' (line 264) not initialized \n + * \n + * --- Error 550: --- \n + * __regBasePri = (basePri & 0x1ff); \n + * } \n + * Warning 550: Symbol '__regBasePri' (line 271) not accessed \n + * \n + * --- Error 754: --- \n + * uint32_t RESERVED0[24]; \n + * Info 754: local structure member '' (line 109, file ./cm3_core.h) not referenced \n + * \n + * --- Error 750: --- \n + * #define __CM3_CORE_H__ \n + * Info 750: local macro '__CM3_CORE_H__' (line 43, file./cm3_core.h) not referenced \n + * \n + * --- Error 528: --- \n + * static __INLINE void NVIC_DisableIRQ(uint32_t IRQn) \n + * Warning 528: Symbol 'NVIC_DisableIRQ(unsigned int)' (line 419, file ./cm3_core.h) not referenced \n + * \n + * --- Error 751: --- \n + * } InterruptType_Type; \n + * Info 751: local typedef 'InterruptType_Type' (line 170, file ./cm3_core.h) not referenced \n + * \n + * \n + * Note: To re-enable a Message, insert a space before 'lint' * \n + * + */ + +/*lint -save */ +/*lint -e10 */ +/*lint -e530 */ +/*lint -e550 */ +/*lint -e754 */ +/*lint -e750 */ +/*lint -e528 */ +/*lint -e751 */ + +#include /* Include standard types */ + +#if defined ( __CC_ARM ) +/** + * @brief Return the Main Stack Pointer (current ARM7 stack) + * + * @param none + * @return uint32_t Main Stack Pointer + * + * Return the current value of the MSP (main stack pointer) + * Cortex processor register + */ +extern uint32_t __get_MSP(void); +#endif + + +#if defined (__ICCARM__) + #include /* IAR Intrinsics */ +#endif + + +#ifndef __NVIC_PRIO_BITS + #define __NVIC_PRIO_BITS 4 /*!< standard definition for NVIC Priority Bits */ +#endif + +typedef struct +{ + uint32_t IRQStatus; + uint32_t FIQStatus; + uint32_t RawIntr; + uint32_t IntSelect; + uint32_t IntEnable; + uint32_t IntEnClr; + uint32_t SoftInt; + uint32_t SoftIntClr; + uint32_t Protection; + uint32_t SWPriorityMask; + uint32_t RESERVED0[54]; + uint32_t VectAddr[32]; + uint32_t RESERVED1[32]; + uint32_t VectPriority[32]; + uint32_t RESERVED2[800]; + uint32_t Address; +} NVIC_TypeDef; + +#define NVIC_BASE (0xFFFFF000) +#define NVIC (( NVIC_TypeDef *) NVIC_BASE) + + + +/** + * IO definitions + * + * define access restrictions to peripheral registers + */ + +#ifdef __cplusplus +#define __I volatile /*!< defines 'read only' permissions */ +#else +#define __I volatile const /*!< defines 'read only' permissions */ +#endif +#define __O volatile /*!< defines 'write only' permissions */ +#define __IO volatile /*!< defines 'read / write' permissions */ + + + + + +#if defined ( __CC_ARM ) + #define __ASM __asm /*!< asm keyword for ARM Compiler */ + #define __INLINE __inline /*!< inline keyword for ARM Compiler */ + +#elif defined ( __ICCARM__ ) + #define __ASM __asm /*!< asm keyword for IAR Compiler */ + #define __INLINE inline /*!< inline keyword for IAR Compiler. Only avaiable in High optimization mode! */ + +#elif defined ( __GNUC__ ) + #define __ASM __asm /*!< asm keyword for GNU Compiler */ + #define __INLINE inline /*!< inline keyword for GNU Compiler */ + +#elif defined ( __TASKING__ ) + #define __ASM __asm /*!< asm keyword for TASKING Compiler */ + #define __INLINE inline /*!< inline keyword for TASKING Compiler */ + +#endif + + +/* ################### Compiler specific Intrinsics ########################### */ + +#if defined ( __CC_ARM ) /*------------------RealView Compiler -----------------*/ +/* ARM armcc specific functions */ + +#define __enable_fault_irq __enable_fiq +#define __disable_fault_irq __disable_fiq + +#define __NOP __nop +//#define __WFI __wfi +//#define __WFE __wfe +//#define __SEV __sev +//#define __ISB() __isb(0) +//#define __DSB() __dsb(0) +//#define __DMB() __dmb(0) +//#define __REV __rev +//#define __RBIT __rbit +#define __LDREXB(ptr) ((unsigned char ) __ldrex(ptr)) +#define __LDREXH(ptr) ((unsigned short) __ldrex(ptr)) +#define __LDREXW(ptr) ((unsigned int ) __ldrex(ptr)) +#define __STREXB(value, ptr) __strex(value, ptr) +#define __STREXH(value, ptr) __strex(value, ptr) +#define __STREXW(value, ptr) __strex(value, ptr) + +#define __disable_irq() unsigned tmp_IntEnable = LPC_VIC->IntEnable; \ + LPC_VIC->IntEnClr = 0xffffffff + +#define __enable_irq() LPC_VIC->IntEnable = tmp_IntEnable + +#elif (defined (__ICCARM__)) /*------------------ ICC Compiler -------------------*/ + +#define __enable_irq __enable_interrupt /*!< global Interrupt enable */ +#define __disable_irq __disable_interrupt /*!< global Interrupt disable */ +#define __NOP __no_operation() /*!< no operation intrinsic in IAR Compiler */ + +#elif (defined (__GNUC__)) /*------------------ GNU Compiler ---------------------*/ + +static __INLINE void __enable_irq() { + unsigned long temp; + __asm__ __volatile__("mrs %0, cpsr\n" + "bic %0, %0, #0x80\n" + "msr cpsr_c, %0" + : "=r" (temp) + : + : "memory"); +} + +static __INLINE uint32_t __disable_irq() { + unsigned long old,temp; + __asm__ __volatile__("mrs %0, cpsr\n" + "orr %1, %0, #0xc0\n" + "msr cpsr_c, %1" + : "=r" (old), "=r" (temp) + : + : "memory"); + return (old & 0x80) == 0; +} + +static __INLINE void __NOP() { __ASM volatile ("nop"); } + +/** \brief Get Control Bits of Status Register + + This function returns the content of the Control Bits from the Program Status Register. + + \return Control Bits value + */ +__attribute__( ( always_inline ) ) static inline uint32_t __get_CONTROL(void) +{ + uint32_t result; + + __asm__ __volatile__ ("MRS %0, CPSR \n" + "AND %0,%0,#31" : "=r" (result) ); + return(result); +} +#define MODE_USER 0x10 +#define MODE_FIQ 0x11 +#define MODE_IRQ 0x12 +#define MODE_SUPERVISOR 0x13 +#define MODE_ABORT 0x17 +#define MODE_UNDEFINED 0x1B +#define MODE_SYSTEM 0x1F + + +#elif (defined (__TASKING__)) /*------------------ TASKING Compiler ---------------------*/ +/* TASKING carm specific functions */ + +/* + * The CMSIS functions have been implemented as intrinsics in the compiler. + * Please use "carm -?i" to get an up to date list of all instrinsics, + * Including the CMSIS ones. + */ + +#endif + + +/** + * @brief Enable Interrupt in NVIC Interrupt Controller + * + * @param IRQn_Type IRQn specifies the interrupt number + * @return none + * + * Enable a device specific interupt in the NVIC interrupt controller. + * The interrupt number cannot be a negative value. + */ +static __INLINE void NVIC_EnableIRQ(uint32_t IRQn) +{ + NVIC->IntEnable = 1 << (uint32_t)IRQn; +} + + +/** + * @brief Disable the interrupt line for external interrupt specified + * + * @param IRQn_Type IRQn is the positive number of the external interrupt + * @return none + * + * Disable a device specific interupt in the NVIC interrupt controller. + * The interrupt number cannot be a negative value. + */ +static __INLINE void NVIC_DisableIRQ(uint32_t IRQn) +{ + NVIC->IntEnClr = 1 << (uint32_t)IRQn; +} + +/** + * @brief Pend Interrupt in NVIC Interrupt Controller + * + * @param IRQn_Type IRQn specifies the interrupt number + * @return none + * + * Force software a device specific interupt in the NVIC interrupt controller. + * The interrupt number cannot be a negative value. + */ +static __INLINE void NVIC_PendIRQ(uint32_t IRQn) +{ + NVIC->SoftInt = 1 << (uint32_t)IRQn; +} + + +/** + * @brief Unpend the interrupt in NVIC Interrupt Controller + * + * @param IRQn_Type IRQn is the positive number of the external interrupt + * @return none + * + * Clear software device specific interupt in the NVIC interrupt controller. + * The interrupt number cannot be a negative value. + */ +static __INLINE void NVIC_UnpendIRQ(uint32_t IRQn) +{ + NVIC->SoftIntClr = 1 << (uint32_t)IRQn; +} + +/** + * @brief Is IRQ pending + * + * @param IRQn_Type IRQn is the positive number of the external interrupt + * @return 0 if IRQ is not pending + * 1 if IRQ is pending + * + * Returns software device specific interupt in the NVIC interrupt controller. + * The interrupt number cannot be a negative value. + */ +static __INLINE uint32_t NVIC_Pending(uint32_t IRQn) +{ + return (NVIC->SoftInt & (1 << (uint32_t)IRQn)) != 0; +} + +static __INLINE uint32_t __get_IPSR(void) +{ + unsigned i; + + for(i = 0; i < 32; i ++) + if(NVIC->Address == NVIC->VectAddr[i]) + return i; + return 1; // 1 is an invalid entry in the interrupt table on LPC2460 +} + +#ifdef __cplusplus +} +#endif + +#endif /* __ARM7_CORE_H__ */ + +/*lint -restore */ diff --git a/targets/TARGET_NXP/TARGET_LPC2460/device/system_LPC24xx.c b/targets/TARGET_NXP/TARGET_LPC2460/device/system_LPC24xx.c new file mode 100644 index 00000000000..f1698c2658b --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC2460/device/system_LPC24xx.c @@ -0,0 +1,164 @@ +/* mbed Microcontroller Library + * Copyright (C) 2008-2015 ARM Limited. All rights reserved. + * + * ARM7 version of CMSIS-like functionality - not advised for use outside mbed! + */ + +#include +#include "LPC24xx.h" + +#define CLOCK_SETUP 1 +#define SCS_Val ((1<<4) | (1 << 5)) +#define CLKSRCSEL_Val 0x00000001 + +#define PLL0_SETUP 1 +#define PLL0CFG_Val 0x0000000B +#define CCLKCFG_Val 0x00000003 +#define USBCLKCFG_Val 0x00000005 +#define PCLKSEL0_Val 0x00000000 +#define PCLKSEL1_Val 0x00000000 +#define PCONP_Val (1 << PCEMC) +#define CLKOUTCFG_Val 0x00000000 +#define MAMCR_Val 0x00000002 +#define MAMTIM_Val 0x00000004 + +/*---------------------------------------------------------------------------- + DEFINES + *----------------------------------------------------------------------------*/ + +#define XTAL (12000000UL) /* Oscillator frequency */ +#define OSC_CLK ( XTAL) /* Main oscillator frequency */ +#define RTC_CLK ( 32000UL) /* RTC oscillator frequency */ +#define IRC_OSC ( 4000000UL) /* Internal RC oscillator frequency */ + +/* F_cco0 = (2 * M * F_in) / N */ +#define __M (((PLL0CFG_Val ) & 0x7FFF) + 1) +#define __N (((PLL0CFG_Val >> 16) & 0x00FF) + 1) +#define __FCCO(__F_IN) ((2 * __M * __F_IN) / __N) +#define __CCLK_DIV (((CCLKCFG_Val ) & 0x00FF) + 1) + +/* Determine core clock frequency according to settings */ + #if (PLL0_SETUP) + #if ((CLKSRCSEL_Val & 0x03) == 1) + #define __CORE_CLK (__FCCO(OSC_CLK) / __CCLK_DIV) + #elif ((CLKSRCSEL_Val & 0x03) == 2) + #define __CORE_CLK (__FCCO(RTC_CLK) / __CCLK_DIV) + #else + #define __CORE_CLK (__FCCO(IRC_OSC) / __CCLK_DIV) + #endif + #endif + + +/*---------------------------------------------------------------------------- + Clock Variable definitions + *----------------------------------------------------------------------------*/ +uint32_t SystemCoreClock = __CORE_CLK;/*!< System Clock Frequency (Core Clock)*/ + +/*---------------------------------------------------------------------------- + Clock functions + *----------------------------------------------------------------------------*/ +void SystemCoreClockUpdate (void) /* Get Core Clock Frequency */ +{ + /* Determine clock frequency according to clock register values */ + if (((LPC_SC->PLL0STAT >> 24) & 3) == 3) { /* If PLL0 enabled and connected */ + switch (LPC_SC->CLKSRCSEL & 0x03) { + case 0: /* Int. RC oscillator => PLL0 */ + case 3: /* Reserved, default to Int. RC */ + SystemCoreClock = (IRC_OSC * + (((2 * ((LPC_SC->PLL0STAT & 0x7FFF) + 1))) / + (((LPC_SC->PLL0STAT >> 16) & 0xFF) + 1)) / + ((LPC_SC->CCLKCFG & 0xFF)+ 1)); + break; + case 1: /* Main oscillator => PLL0 */ + SystemCoreClock = (OSC_CLK * + (((2 * ((LPC_SC->PLL0STAT & 0x7FFF) + 1))) / + (((LPC_SC->PLL0STAT >> 16) & 0xFF) + 1)) / + ((LPC_SC->CCLKCFG & 0xFF)+ 1)); + break; + case 2: /* RTC oscillator => PLL0 */ + SystemCoreClock = (RTC_CLK * + (((2 * ((LPC_SC->PLL0STAT & 0x7FFF) + 1))) / + (((LPC_SC->PLL0STAT >> 16) & 0xFF) + 1)) / + ((LPC_SC->CCLKCFG & 0xFF)+ 1)); + break; + } + } else { + switch (LPC_SC->CLKSRCSEL & 0x03) { + case 0: /* Int. RC oscillator => PLL0 */ + case 3: /* Reserved, default to Int. RC */ + SystemCoreClock = IRC_OSC / ((LPC_SC->CCLKCFG & 0xFF)+ 1); + break; + case 1: /* Main oscillator => PLL0 */ + SystemCoreClock = OSC_CLK / ((LPC_SC->CCLKCFG & 0xFF)+ 1); + break; + case 2: /* RTC oscillator => PLL0 */ + SystemCoreClock = RTC_CLK / ((LPC_SC->CCLKCFG & 0xFF)+ 1); + break; + } + } +} + +void vectorRemap() +{ + #define ARM_VECTOR_REBASE (0x40000000) + extern unsigned long __privileged_code_start__; /* Startup code address from linker */ + int i; + + /* Copy ARM vector table into internal RAM */ + for (i = 0; i <= 56; i+=2) + { + *(unsigned short *)(ARM_VECTOR_REBASE + i) = *(unsigned short *)((unsigned long)(&__privileged_code_start__) + i); + } + +// *(unsigned long *)(ARM_VECTOR_REBASE) = (unsigned long)armUnexpReset; + /* Remap the interrupt vectors to RAM */ + LPC_SC->MEMMAP = 2; +} + +/** + * Initialize the system + * + * @param none + * @return none + * + * @brief Setup the microcontroller system. + * Initialize the System and update the SystemFrequency variable. + */ +void SystemInit (void) +{ + LPC_WDT->WDMOD = 0; /* Disable internal watchdog */ +#if (CLOCK_SETUP) /* Clock Setup */ + LPC_SC->SCS = SCS_Val; + if (SCS_Val & (1 << 5)) { /* If Main Oscillator is enabled */ + while ((LPC_SC->SCS & (1 << 6)) == 0); /* Wait for Oscillator to be ready */ + } + + LPC_SC->CCLKCFG = CCLKCFG_Val; /* Setup Clock Divider */ + +#if (PLL0_SETUP) + LPC_SC->CLKSRCSEL = CLKSRCSEL_Val; /* Select Clock Source for PLL0 */ + LPC_SC->PLL0CFG = PLL0CFG_Val; + LPC_SC->PLL0CON = 0x01; /* PLL0 Enable */ + LPC_SC->PLL0FEED = 0xAA; + LPC_SC->PLL0FEED = 0x55; + while (!(LPC_SC->PLL0STAT & (1 << 26))); /* Wait for PLOCK0 */ + + LPC_SC->PLL0CON = 0x03; /* PLL0 Enable & Connect */ + LPC_SC->PLL0FEED = 0xAA; + LPC_SC->PLL0FEED = 0x55; +#endif + + LPC_SC->USBCLKCFG = USBCLKCFG_Val; /* Setup USB Clock Divider */ +#endif + + LPC_SC->PCLKSEL0 = PCLKSEL0_Val; /* Peripheral Clock Selection */ + LPC_SC->PCLKSEL1 = PCLKSEL1_Val; + + LPC_SC->PCONP = PCONP_Val; /* Power Control for Peripherals */ + + // Setup MAM + LPC_SC->MAMTIM = MAMTIM_Val; + LPC_SC->MAMCR = MAMCR_Val; + vectorRemap(); +} + diff --git a/targets/TARGET_NXP/TARGET_LPC2460/device/system_LPC24xx.h b/targets/TARGET_NXP/TARGET_LPC2460/device/system_LPC24xx.h new file mode 100644 index 00000000000..4e566818fa9 --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC2460/device/system_LPC24xx.h @@ -0,0 +1,44 @@ +/* mbed Microcontroller Library + * Copyright (C) 2008-2015 ARM Limited. All rights reserved. + * + * ARM7 version of CMSIS-like functionality - not advised for use outside mbed! + * based on cmsis system_LPC17xx.h + */ + +#ifndef __SYSTEM_LPC24xx_H +#define __SYSTEM_LPC24xx_H + +#ifdef __cplusplus + extern "C" { +#endif + +extern uint32_t SystemCoreClock; /*!< System Clock Frequency (Core Clock) */ + +/** + * Initialize the system + * + * @param none + * @return none + * + * @brief Setup the microcontroller system. + * Initialize the System and update the SystemCoreClock variable. + */ +extern void SystemInit (void); + +/** + * Update SystemCoreClock variable + * + * @param none + * @return none + * + * @brief Updates the SystemCoreClock with current core Clock + * retrieved from cpu registers. + */ +extern void SystemCoreClockUpdate (void); + + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/targets/TARGET_NXP/TARGET_LPC2460/device/vector_defns.h b/targets/TARGET_NXP/TARGET_LPC2460/device/vector_defns.h new file mode 100644 index 00000000000..00b6f869b30 --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC2460/device/vector_defns.h @@ -0,0 +1,77 @@ +/* mbed Microcontroller Library - Vectors + * Copyright (c) 2006-2015 ARM Limited. All rights reserved. + */ + +#ifndef MBED_VECTOR_DEFNS_H +#define MBED_VECTOR_DEFNS_H + +// Assember Macros +#ifdef __ARMCC_VERSION +#define EXPORT(x) EXPORT x +#define WEAK_EXPORT(x) EXPORT x [WEAK] +#define IMPORT(x) IMPORT x +#define LABEL(x) x +#else +#define EXPORT(x) .global x +#define WEAK_EXPORT(x) .weak x +#define IMPORT(x) .global x +#define LABEL(x) x: +#endif + +// RealMonitor +// Requires RAM (0x40000040-0x4000011F) to be allocated by the linker + +// RealMonitor entry points +#define rm_init_entry 0x7fffff91 +#define rm_undef_handler 0x7fffffa0 +#define rm_prefetchabort_handler 0x7fffffb0 +#define rm_dataabort_handler 0x7fffffc0 +#define rm_irqhandler2 0x7fffffe0 +//#define rm_RunningToStopped 0x7ffff808 // ARM - MBED64 +#define rm_RunningToStopped 0x7ffff820 // ARM - PHAT40 + +// Unofficial RealMonitor entry points and variables +#define RM_MSG_SWI 0x00940000 +#define StateP 0x40000040 + +// VIC register addresses +#define VIC_Base 0xfffff000 +#define VICAddress_Offset 0xf00 +#define VICVectAddr0_Offset 0x100 +#define VICVectAddr2_Offset 0x108 +#define VICVectAddr3_Offset 0x10c +#define VICVectAddr31_Offset 0x17c +#define VICIntEnClr_Offset 0x014 +#define VICIntEnClr (*(volatile unsigned long *)(VIC_Base + 0x014)) +#define VICVectAddr2 (*(volatile unsigned long *)(VIC_Base + 0x108)) +#define VICVectAddr3 (*(volatile unsigned long *)(VIC_Base + 0x10C)) + +// ARM Mode bits and Interrupt flags in PSRs +#define Mode_USR 0x10 +#define Mode_FIQ 0x11 +#define Mode_IRQ 0x12 +#define Mode_SVC 0x13 +#define Mode_ABT 0x17 +#define Mode_UND 0x1B +#define Mode_SYS 0x1F +#define I_Bit 0x80 // when I bit is set, IRQ is disabled +#define F_Bit 0x40 // when F bit is set, FIQ is disabled + +// MCU RAM +#define LPC2460_RAM_ADDRESS 0x40000000 // RAM Base +#define LPC2460_RAM_SIZE 0x10000 // 64KB + +// ISR Stack Allocation +#define UND_stack_size 0x00000040 +#define SVC_stack_size 0x00000040 +#define ABT_stack_size 0x00000040 +#define FIQ_stack_size 0x00000000 +#define IRQ_stack_size 0x00000040 + +#define ISR_stack_size (UND_stack_size + SVC_stack_size + ABT_stack_size + FIQ_stack_size + IRQ_stack_size) + +// Full Descending Stack, so top-most stack points to just above the top of RAM +#define LPC2460_STACK_TOP (LPC2460_RAM_ADDRESS + LPC2460_RAM_SIZE) +#define USR_STACK_TOP (LPC2460_STACK_TOP - ISR_stack_size) + +#endif diff --git a/targets/TARGET_NXP/TARGET_LPC2460/device/vector_realmonitor.c b/targets/TARGET_NXP/TARGET_LPC2460/device/vector_realmonitor.c new file mode 100644 index 00000000000..cb84e74c084 --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC2460/device/vector_realmonitor.c @@ -0,0 +1,22 @@ +/* mbed Microcontroller Library - RealMonitor + * Copyright (c) 2006-2015 ARM Limited. All rights reserved. + */ +#include "vector_defns.h" + +extern void __mbed_dcc_irq(void); + +/* Function: __mbed_init_realmonitor + * Setup the RealMonitor DCC Interrupt Handlers + */ +void __mbed_init_realmonitor(void) __attribute__((weak)); +void __mbed_init_realmonitor() { + // Disable all interrupts + VICIntEnClr = 0xffffffff; + + // Set DCC interrupt vector addresses + VICVectAddr2 = (unsigned)&__mbed_dcc_irq; + VICVectAddr3 = (unsigned)&__mbed_dcc_irq; + + // Initialise RealMonitor + ((void (*)(void))rm_init_entry)(); +} diff --git a/targets/TARGET_NXP/TARGET_LPC2460/ethernet_api.c b/targets/TARGET_NXP/TARGET_LPC2460/ethernet_api.c new file mode 100644 index 00000000000..793874c11be --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC2460/ethernet_api.c @@ -0,0 +1,935 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2015 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * 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. + */ +#include + +#include "ethernet_api.h" +#include "cmsis.h" +#include "mbed_interface.h" +#include "mbed_toolchain.h" +#include "mbed_error.h" + +#define NEW_LOGIC 0 +#define NEW_ETH_BUFFER 0 + +#if NEW_ETH_BUFFER + +#define NUM_RX_FRAG 4 // Number of Rx Fragments (== packets) +#define NUM_TX_FRAG 3 // Number of Tx Fragments (== packets) + +#define ETH_MAX_FLEN 1536 // Maximum Ethernet Frame Size +#define ETH_FRAG_SIZE ETH_MAX_FLEN // Packet Fragment size (same as packet length) + +#else + +// Memfree calculation: +// (16 * 1024) - ((2 * 4 * NUM_RX) + (2 * 4 * NUM_RX) + (0x300 * NUM_RX) + +// (2 * 4 * NUM_TX) + (1 * 4 * NUM_TX) + (0x300 * NUM_TX)) = 8556 +/* EMAC Memory Buffer configuration for 16K Ethernet RAM. */ +#define NUM_RX_FRAG 4 /* Num.of RX Fragments 4*1536= 6.0kB */ +#define NUM_TX_FRAG 3 /* Num.of TX Fragments 3*1536= 4.6kB */ +//#define ETH_FRAG_SIZE 1536 /* Packet Fragment size 1536 Bytes */ + +//#define ETH_MAX_FLEN 1536 /* Max. Ethernet Frame Size */ +#define ETH_FRAG_SIZE 0x300 /* Packet Fragment size 1536/2 Bytes */ +#define ETH_MAX_FLEN 0x300 /* Max. Ethernet Frame Size */ + +const int ethernet_MTU_SIZE = 0x300; + +#endif + +#define ETHERNET_ADDR_SIZE 6 + +PACKED struct RX_DESC_TypeDef { /* RX Descriptor struct */ + unsigned int Packet; + unsigned int Ctrl; +}; +typedef struct RX_DESC_TypeDef RX_DESC_TypeDef; + +PACKED struct RX_STAT_TypeDef { /* RX Status struct */ + unsigned int Info; + unsigned int HashCRC; +}; +typedef struct RX_STAT_TypeDef RX_STAT_TypeDef; + +PACKED struct TX_DESC_TypeDef { /* TX Descriptor struct */ + unsigned int Packet; + unsigned int Ctrl; +}; +typedef struct TX_DESC_TypeDef TX_DESC_TypeDef; + +PACKED struct TX_STAT_TypeDef { /* TX Status struct */ + unsigned int Info; +}; +typedef struct TX_STAT_TypeDef TX_STAT_TypeDef; + +/* MAC Configuration Register 1 */ +#define MAC1_REC_EN 0x00000001 /* Receive Enable */ +#define MAC1_PASS_ALL 0x00000002 /* Pass All Receive Frames */ +#define MAC1_RX_FLOWC 0x00000004 /* RX Flow Control */ +#define MAC1_TX_FLOWC 0x00000008 /* TX Flow Control */ +#define MAC1_LOOPB 0x00000010 /* Loop Back Mode */ +#define MAC1_RES_TX 0x00000100 /* Reset TX Logic */ +#define MAC1_RES_MCS_TX 0x00000200 /* Reset MAC TX Control Sublayer */ +#define MAC1_RES_RX 0x00000400 /* Reset RX Logic */ +#define MAC1_RES_MCS_RX 0x00000800 /* Reset MAC RX Control Sublayer */ +#define MAC1_SIM_RES 0x00004000 /* Simulation Reset */ +#define MAC1_SOFT_RES 0x00008000 /* Soft Reset MAC */ + +/* MAC Configuration Register 2 */ +#define MAC2_FULL_DUP 0x00000001 /* Full Duplex Mode */ +#define MAC2_FRM_LEN_CHK 0x00000002 /* Frame Length Checking */ +#define MAC2_HUGE_FRM_EN 0x00000004 /* Huge Frame Enable */ +#define MAC2_DLY_CRC 0x00000008 /* Delayed CRC Mode */ +#define MAC2_CRC_EN 0x00000010 /* Append CRC to every Frame */ +#define MAC2_PAD_EN 0x00000020 /* Pad all Short Frames */ +#define MAC2_VLAN_PAD_EN 0x00000040 /* VLAN Pad Enable */ +#define MAC2_ADET_PAD_EN 0x00000080 /* Auto Detect Pad Enable */ +#define MAC2_PPREAM_ENF 0x00000100 /* Pure Preamble Enforcement */ +#define MAC2_LPREAM_ENF 0x00000200 /* Long Preamble Enforcement */ +#define MAC2_NO_BACKOFF 0x00001000 /* No Backoff Algorithm */ +#define MAC2_BACK_PRESSURE 0x00002000 /* Backoff Presurre / No Backoff */ +#define MAC2_EXCESS_DEF 0x00004000 /* Excess Defer */ + +/* Back-to-Back Inter-Packet-Gap Register */ +#define IPGT_FULL_DUP 0x00000015 /* Recommended value for Full Duplex */ +#define IPGT_HALF_DUP 0x00000012 /* Recommended value for Half Duplex */ + +/* Non Back-to-Back Inter-Packet-Gap Register */ +#define IPGR_DEF 0x00000012 /* Recommended value */ + +/* Collision Window/Retry Register */ +#define CLRT_DEF 0x0000370F /* Default value */ + +/* PHY Support Register */ +#define SUPP_SPEED 0x00000100 /* Reduced MII Logic Current Speed */ +//#define SUPP_RES_RMII 0x00000800 /* Reset Reduced MII Logic */ +#define SUPP_RES_RMII 0x00000000 /* Reset Reduced MII Logic */ + +/* Test Register */ +#define TEST_SHCUT_PQUANTA 0x00000001 /* Shortcut Pause Quanta */ +#define TEST_TST_PAUSE 0x00000002 /* Test Pause */ +#define TEST_TST_BACKP 0x00000004 /* Test Back Pressure */ + +/* MII Management Configuration Register */ +#define MCFG_SCAN_INC 0x00000001 /* Scan Increment PHY Address */ +#define MCFG_SUPP_PREAM 0x00000002 /* Suppress Preamble */ +#define MCFG_CLK_SEL 0x0000003C /* Clock Select Mask */ +#define MCFG_RES_MII 0x00008000 /* Reset MII Management Hardware */ + +/* MII Management Command Register */ +#define MCMD_READ 0x00000001 /* MII Read */ +#define MCMD_SCAN 0x00000002 /* MII Scan continuously */ + +#define MII_WR_TOUT 0x00050000 /* MII Write timeout count */ +#define MII_RD_TOUT 0x00050000 /* MII Read timeout count */ + +/* MII Management Address Register */ +#define MADR_REG_ADR 0x0000001F /* MII Register Address Mask */ +#define MADR_PHY_ADR 0x00001F00 /* PHY Address Mask */ + +/* MII Management Indicators Register */ +#define MIND_BUSY 0x00000001 /* MII is Busy */ +#define MIND_SCAN 0x00000002 /* MII Scanning in Progress */ +#define MIND_NOT_VAL 0x00000004 /* MII Read Data not valid */ +#define MIND_MII_LINK_FAIL 0x00000008 /* MII Link Failed */ + +/* Command Register */ +#define CR_RX_EN 0x00000001 /* Enable Receive */ +#define CR_TX_EN 0x00000002 /* Enable Transmit */ +#define CR_REG_RES 0x00000008 /* Reset Host Registers */ +#define CR_TX_RES 0x00000010 /* Reset Transmit Datapath */ +#define CR_RX_RES 0x00000020 /* Reset Receive Datapath */ +#define CR_PASS_RUNT_FRM 0x00000040 /* Pass Runt Frames */ +#define CR_PASS_RX_FILT 0x00000080 /* Pass RX Filter */ +#define CR_TX_FLOW_CTRL 0x00000100 /* TX Flow Control */ +#define CR_RMII 0x00000200 /* Reduced MII Interface */ +#define CR_FULL_DUP 0x00000400 /* Full Duplex */ + +/* Status Register */ +#define SR_RX_EN 0x00000001 /* Enable Receive */ +#define SR_TX_EN 0x00000002 /* Enable Transmit */ + +/* Transmit Status Vector 0 Register */ +#define TSV0_CRC_ERR 0x00000001 /* CRC error */ +#define TSV0_LEN_CHKERR 0x00000002 /* Length Check Error */ +#define TSV0_LEN_OUTRNG 0x00000004 /* Length Out of Range */ +#define TSV0_DONE 0x00000008 /* Tramsmission Completed */ +#define TSV0_MCAST 0x00000010 /* Multicast Destination */ +#define TSV0_BCAST 0x00000020 /* Broadcast Destination */ +#define TSV0_PKT_DEFER 0x00000040 /* Packet Deferred */ +#define TSV0_EXC_DEFER 0x00000080 /* Excessive Packet Deferral */ +#define TSV0_EXC_COLL 0x00000100 /* Excessive Collision */ +#define TSV0_LATE_COLL 0x00000200 /* Late Collision Occured */ +#define TSV0_GIANT 0x00000400 /* Giant Frame */ +#define TSV0_UNDERRUN 0x00000800 /* Buffer Underrun */ +#define TSV0_BYTES 0x0FFFF000 /* Total Bytes Transferred */ +#define TSV0_CTRL_FRAME 0x10000000 /* Control Frame */ +#define TSV0_PAUSE 0x20000000 /* Pause Frame */ +#define TSV0_BACK_PRESS 0x40000000 /* Backpressure Method Applied */ +#define TSV0_VLAN 0x80000000 /* VLAN Frame */ + +/* Transmit Status Vector 1 Register */ +#define TSV1_BYTE_CNT 0x0000FFFF /* Transmit Byte Count */ +#define TSV1_COLL_CNT 0x000F0000 /* Transmit Collision Count */ + +/* Receive Status Vector Register */ +#define RSV_BYTE_CNT 0x0000FFFF /* Receive Byte Count */ +#define RSV_PKT_IGNORED 0x00010000 /* Packet Previously Ignored */ +#define RSV_RXDV_SEEN 0x00020000 /* RXDV Event Previously Seen */ +#define RSV_CARR_SEEN 0x00040000 /* Carrier Event Previously Seen */ +#define RSV_REC_CODEV 0x00080000 /* Receive Code Violation */ +#define RSV_CRC_ERR 0x00100000 /* CRC Error */ +#define RSV_LEN_CHKERR 0x00200000 /* Length Check Error */ +#define RSV_LEN_OUTRNG 0x00400000 /* Length Out of Range */ +#define RSV_REC_OK 0x00800000 /* Frame Received OK */ +#define RSV_MCAST 0x01000000 /* Multicast Frame */ +#define RSV_BCAST 0x02000000 /* Broadcast Frame */ +#define RSV_DRIB_NIBB 0x04000000 /* Dribble Nibble */ +#define RSV_CTRL_FRAME 0x08000000 /* Control Frame */ +#define RSV_PAUSE 0x10000000 /* Pause Frame */ +#define RSV_UNSUPP_OPC 0x20000000 /* Unsupported Opcode */ +#define RSV_VLAN 0x40000000 /* VLAN Frame */ + +/* Flow Control Counter Register */ +#define FCC_MIRR_CNT 0x0000FFFF /* Mirror Counter */ +#define FCC_PAUSE_TIM 0xFFFF0000 /* Pause Timer */ + +/* Flow Control Status Register */ +#define FCS_MIRR_CNT 0x0000FFFF /* Mirror Counter Current */ + +/* Receive Filter Control Register */ +#define RFC_UCAST_EN 0x00000001 /* Accept Unicast Frames Enable */ +#define RFC_BCAST_EN 0x00000002 /* Accept Broadcast Frames Enable */ +#define RFC_MCAST_EN 0x00000004 /* Accept Multicast Frames Enable */ +#define RFC_UCAST_HASH_EN 0x00000008 /* Accept Unicast Hash Filter Frames */ +#define RFC_MCAST_HASH_EN 0x00000010 /* Accept Multicast Hash Filter Fram.*/ +#define RFC_PERFECT_EN 0x00000020 /* Accept Perfect Match Enable */ +#define RFC_MAGP_WOL_EN 0x00001000 /* Magic Packet Filter WoL Enable */ +#define RFC_PFILT_WOL_EN 0x00002000 /* Perfect Filter WoL Enable */ + +/* Receive Filter WoL Status/Clear Registers */ +#define WOL_UCAST 0x00000001 /* Unicast Frame caused WoL */ +#define WOL_BCAST 0x00000002 /* Broadcast Frame caused WoL */ +#define WOL_MCAST 0x00000004 /* Multicast Frame caused WoL */ +#define WOL_UCAST_HASH 0x00000008 /* Unicast Hash Filter Frame WoL */ +#define WOL_MCAST_HASH 0x00000010 /* Multicast Hash Filter Frame WoL */ +#define WOL_PERFECT 0x00000020 /* Perfect Filter WoL */ +#define WOL_RX_FILTER 0x00000080 /* RX Filter caused WoL */ +#define WOL_MAG_PACKET 0x00000100 /* Magic Packet Filter caused WoL */ + +/* Interrupt Status/Enable/Clear/Set Registers */ +#define INT_RX_OVERRUN 0x00000001 /* Overrun Error in RX Queue */ +#define INT_RX_ERR 0x00000002 /* Receive Error */ +#define INT_RX_FIN 0x00000004 /* RX Finished Process Descriptors */ +#define INT_RX_DONE 0x00000008 /* Receive Done */ +#define INT_TX_UNDERRUN 0x00000010 /* Transmit Underrun */ +#define INT_TX_ERR 0x00000020 /* Transmit Error */ +#define INT_TX_FIN 0x00000040 /* TX Finished Process Descriptors */ +#define INT_TX_DONE 0x00000080 /* Transmit Done */ +#define INT_SOFT_INT 0x00001000 /* Software Triggered Interrupt */ +#define INT_WAKEUP 0x00002000 /* Wakeup Event Interrupt */ + +/* Power Down Register */ +#define PD_POWER_DOWN 0x80000000 /* Power Down MAC */ + +/* RX Descriptor Control Word */ +#define RCTRL_SIZE 0x000007FF /* Buffer size mask */ +#define RCTRL_INT 0x80000000 /* Generate RxDone Interrupt */ + +/* RX Status Hash CRC Word */ +#define RHASH_SA 0x000001FF /* Hash CRC for Source Address */ +#define RHASH_DA 0x001FF000 /* Hash CRC for Destination Address */ + +/* RX Status Information Word */ +#define RINFO_SIZE 0x000007FF /* Data size in bytes */ +#define RINFO_CTRL_FRAME 0x00040000 /* Control Frame */ +#define RINFO_VLAN 0x00080000 /* VLAN Frame */ +#define RINFO_FAIL_FILT 0x00100000 /* RX Filter Failed */ +#define RINFO_MCAST 0x00200000 /* Multicast Frame */ +#define RINFO_BCAST 0x00400000 /* Broadcast Frame */ +#define RINFO_CRC_ERR 0x00800000 /* CRC Error in Frame */ +#define RINFO_SYM_ERR 0x01000000 /* Symbol Error from PHY */ +#define RINFO_LEN_ERR 0x02000000 /* Length Error */ +#define RINFO_RANGE_ERR 0x04000000 /* Range Error (exceeded max. size) */ +#define RINFO_ALIGN_ERR 0x08000000 /* Alignment Error */ +#define RINFO_OVERRUN 0x10000000 /* Receive overrun */ +#define RINFO_NO_DESCR 0x20000000 /* No new Descriptor available */ +#define RINFO_LAST_FLAG 0x40000000 /* Last Fragment in Frame */ +#define RINFO_ERR 0x80000000 /* Error Occured (OR of all errors) */ + +//#define RINFO_ERR_MASK (RINFO_FAIL_FILT | RINFO_CRC_ERR | RINFO_SYM_ERR | RINFO_LEN_ERR | RINFO_ALIGN_ERR | RINFO_OVERRUN) +#define RINFO_ERR_MASK (RINFO_FAIL_FILT | RINFO_SYM_ERR | \ + RINFO_LEN_ERR | RINFO_ALIGN_ERR | RINFO_OVERRUN) + + +/* TX Descriptor Control Word */ +#define TCTRL_SIZE 0x000007FF /* Size of data buffer in bytes */ +#define TCTRL_OVERRIDE 0x04000000 /* Override Default MAC Registers */ +#define TCTRL_HUGE 0x08000000 /* Enable Huge Frame */ +#define TCTRL_PAD 0x10000000 /* Pad short Frames to 64 bytes */ +#define TCTRL_CRC 0x20000000 /* Append a hardware CRC to Frame */ +#define TCTRL_LAST 0x40000000 /* Last Descriptor for TX Frame */ +#define TCTRL_INT 0x80000000 /* Generate TxDone Interrupt */ + +/* TX Status Information Word */ +#define TINFO_COL_CNT 0x01E00000 /* Collision Count */ +#define TINFO_DEFER 0x02000000 /* Packet Deferred (not an error) */ +#define TINFO_EXCESS_DEF 0x04000000 /* Excessive Deferral */ +#define TINFO_EXCESS_COL 0x08000000 /* Excessive Collision */ +#define TINFO_LATE_COL 0x10000000 /* Late Collision Occured */ +#define TINFO_UNDERRUN 0x20000000 /* Transmit Underrun */ +#define TINFO_NO_DESCR 0x40000000 /* No new Descriptor available */ +#define TINFO_ERR 0x80000000 /* Error Occured (OR of all errors) */ + +/* ENET Device Revision ID */ +#define OLD_EMAC_MODULE_ID 0x39022000 /* Rev. ID for first rev '-' */ + +/* DP83848C PHY Registers */ +#define PHY_REG_BMCR 0x00 /* Basic Mode Control Register */ +#define PHY_REG_BMSR 0x01 /* Basic Mode Status Register */ +#define PHY_REG_IDR1 0x02 /* PHY Identifier 1 */ +#define PHY_REG_IDR2 0x03 /* PHY Identifier 2 */ +#define PHY_REG_ANAR 0x04 /* Auto-Negotiation Advertisement */ +#define PHY_REG_ANLPAR 0x05 /* Auto-Neg. Link Partner Abitily */ +#define PHY_REG_ANER 0x06 /* Auto-Neg. Expansion Register */ +#define PHY_REG_ANNPTR 0x07 /* Auto-Neg. Next Page TX */ + +/* PHY Extended Registers */ +#define PHY_REG_STS 0x10 /* Status Register */ +#define PHY_REG_MICR 0x11 /* MII Interrupt Control Register */ +#define PHY_REG_MISR 0x12 /* MII Interrupt Status Register */ +#define PHY_REG_FCSCR 0x14 /* False Carrier Sense Counter */ +#define PHY_REG_RECR 0x15 /* Receive Error Counter */ +#define PHY_REG_PCSR 0x16 /* PCS Sublayer Config. and Status */ +#define PHY_REG_RBR 0x17 /* RMII and Bypass Register */ +#define PHY_REG_LEDCR 0x18 /* LED Direct Control Register */ +#define PHY_REG_PHYCR 0x19 /* PHY Control Register */ +#define PHY_REG_10BTSCR 0x1A /* 10Base-T Status/Control Register */ +#define PHY_REG_CDCTRL1 0x1B /* CD Test Control and BIST Extens. */ +#define PHY_REG_EDCR 0x1D /* Energy Detect Control Register */ + +#define PHY_REG_SCSR 0x1F /* PHY Special Control/Status Register */ + +#define PHY_FULLD_100M 0x2100 /* Full Duplex 100Mbit */ +#define PHY_HALFD_100M 0x2000 /* Half Duplex 100Mbit */ +#define PHY_FULLD_10M 0x0100 /* Full Duplex 10Mbit */ +#define PHY_HALFD_10M 0x0000 /* Half Duplex 10MBit */ +#define PHY_AUTO_NEG 0x3000 /* Select Auto Negotiation */ + +#define DP83848C_DEF_ADR 0x0100 /* Default PHY device address */ +#define DP83848C_ID 0x20005C90 /* PHY Identifier - DP83848C */ + +#define LAN8720_ID 0x0007C0F0 /* PHY Identifier - LAN8720 */ + +#define PHY_STS_LINK 0x0001 /* PHY Status Link Mask */ +#define PHY_STS_SPEED 0x0002 /* PHY Status Speed Mask */ +#define PHY_STS_DUPLEX 0x0004 /* PHY Status Duplex Mask */ + +#define PHY_BMCR_RESET 0x8000 /* PHY Reset */ + +#define PHY_BMSR_LINK 0x0004 /* PHY BMSR Link valid */ + +#define PHY_SCSR_100MBIT 0x0008 /* Speed: 1=100 MBit, 0=10Mbit */ +#define PHY_SCSR_DUPLEX 0x0010 /* PHY Duplex Mask */ + + +static int phy_read(unsigned int PhyReg); +static int phy_write(unsigned int PhyReg, unsigned short Data); + +static void txdscr_init(void); +static void rxdscr_init(void); + +#if defined (__ICCARM__) +# define AHBSRAM1 +#elif defined(TOOLCHAIN_GCC_CR) +# define AHBSRAM1 __attribute__((section(".data.$RamPeriph32"))) +#else +# define AHBSRAM1 __attribute__((section("AHBSRAM1"),aligned)) +#endif + +AHBSRAM1 volatile uint8_t rxbuf[NUM_RX_FRAG][ETH_FRAG_SIZE]; +AHBSRAM1 volatile uint8_t txbuf[NUM_TX_FRAG][ETH_FRAG_SIZE]; +AHBSRAM1 volatile RX_DESC_TypeDef rxdesc[NUM_RX_FRAG]; +AHBSRAM1 volatile RX_STAT_TypeDef rxstat[NUM_RX_FRAG]; +AHBSRAM1 volatile TX_DESC_TypeDef txdesc[NUM_TX_FRAG]; +AHBSRAM1 volatile TX_STAT_TypeDef txstat[NUM_TX_FRAG]; + + +#if NEW_LOGIC +static int rx_consume_offset = -1; +static int tx_produce_offset = -1; +#else +static int send_doff = 0; +static int send_idx = -1; +static int send_size = 0; + +static int receive_soff = 0; +static int receive_idx = -1; +#endif + +static uint32_t phy_id = 0; + +static inline int rinc(int idx, int mod) { + ++idx; + idx %= mod; + return idx; +} + +//extern unsigned int SystemFrequency; +static inline unsigned int clockselect() { + if(SystemCoreClock < 10000000) { + return 1; + } else if(SystemCoreClock < 15000000) { + return 2; + } else if(SystemCoreClock < 20000000) { + return 3; + } else if(SystemCoreClock < 25000000) { + return 4; + } else if(SystemCoreClock < 35000000) { + return 5; + } else if(SystemCoreClock < 50000000) { + return 6; + } else if(SystemCoreClock < 70000000) { + return 7; + } else if(SystemCoreClock < 80000000) { + return 8; + } else if(SystemCoreClock < 90000000) { + return 9; + } else if(SystemCoreClock < 100000000) { + return 10; + } else if(SystemCoreClock < 120000000) { + return 11; + } else if(SystemCoreClock < 130000000) { + return 12; + } else if(SystemCoreClock < 140000000) { + return 13; + } else if(SystemCoreClock < 150000000) { + return 15; + } else if(SystemCoreClock < 160000000) { + return 16; + } else { + return 0; + } +} + +#ifndef min +#define min(x, y) (((x)<(y))?(x):(y)) +#endif + +/*---------------------------------------------------------------------------- + Ethernet Device initialize + *----------------------------------------------------------------------------*/ +int ethernet_init() { + int regv, tout; + char mac[ETHERNET_ADDR_SIZE]; + unsigned int clock = clockselect(); + + LPC_SC->PCONP |= 0x40000000; /* Power Up the EMAC controller. */ + + LPC_PINCON->PINSEL2 = 0x50150105; /* Enable P1 Ethernet Pins. */ + LPC_PINCON->PINSEL3 = (LPC_PINCON->PINSEL3 & ~0x0000000F) | 0x00000005; + + /* Reset all EMAC internal modules. */ + LPC_EMAC->MAC1 = MAC1_RES_TX | MAC1_RES_MCS_TX | MAC1_RES_RX | + MAC1_RES_MCS_RX | MAC1_SIM_RES | MAC1_SOFT_RES; + LPC_EMAC->Command = CR_REG_RES | CR_TX_RES | CR_RX_RES | CR_PASS_RUNT_FRM; + + for(tout = 100; tout; tout--) __NOP(); /* A short delay after reset. */ + + LPC_EMAC->MAC1 = MAC1_PASS_ALL; /* Initialize MAC control registers. */ + LPC_EMAC->MAC2 = MAC2_CRC_EN | MAC2_PAD_EN; + LPC_EMAC->MAXF = ETH_MAX_FLEN; + LPC_EMAC->CLRT = CLRT_DEF; + LPC_EMAC->IPGR = IPGR_DEF; + + LPC_EMAC->Command = CR_RMII | CR_PASS_RUNT_FRM; /* Enable Reduced MII interface. */ + + LPC_EMAC->MCFG = (clock << 0x2) & MCFG_CLK_SEL; /* Set clock */ + LPC_EMAC->MCFG |= MCFG_RES_MII; /* and reset */ + + for(tout = 100; tout; tout--) __NOP(); /* A short delay */ + + LPC_EMAC->MCFG = (clock << 0x2) & MCFG_CLK_SEL; + LPC_EMAC->MCMD = 0; + + LPC_EMAC->SUPP = SUPP_RES_RMII; /* Reset Reduced MII Logic. */ + + for (tout = 100; tout; tout--) __NOP(); /* A short delay */ + + LPC_EMAC->SUPP = 0; + + phy_write(PHY_REG_BMCR, PHY_BMCR_RESET); /* perform PHY reset */ + for(tout = 0x20000; ; tout--) { /* Wait for hardware reset to end. */ + regv = phy_read(PHY_REG_BMCR); + if(regv < 0 || tout == 0) { + return -1; /* Error */ + } + if(!(regv & PHY_BMCR_RESET)) { + break; /* Reset complete. */ + } + } + + phy_id = (phy_read(PHY_REG_IDR1) << 16); + phy_id |= (phy_read(PHY_REG_IDR2) & 0XFFF0); + + if (phy_id != DP83848C_ID && phy_id != LAN8720_ID) { + error("Unknown Ethernet PHY (%x)", (unsigned int)phy_id); + } + + ethernet_set_link(-1, 0); + + /* Set the Ethernet MAC Address registers */ + ethernet_address(mac); + LPC_EMAC->SA0 = ((uint32_t)mac[5] << 8) | (uint32_t)mac[4]; + LPC_EMAC->SA1 = ((uint32_t)mac[3] << 8) | (uint32_t)mac[2]; + LPC_EMAC->SA2 = ((uint32_t)mac[1] << 8) | (uint32_t)mac[0]; + + txdscr_init(); /* initialize DMA TX Descriptor */ + rxdscr_init(); /* initialize DMA RX Descriptor */ + + LPC_EMAC->RxFilterCtrl = RFC_UCAST_EN | RFC_MCAST_EN | RFC_BCAST_EN | RFC_PERFECT_EN; + /* Receive Broadcast, Perfect Match Packets */ + + LPC_EMAC->IntEnable = INT_RX_DONE | INT_TX_DONE; /* Enable EMAC interrupts. */ + LPC_EMAC->IntClear = 0xFFFF; /* Reset all interrupts */ + + + LPC_EMAC->Command |= (CR_RX_EN | CR_TX_EN); /* Enable receive and transmit mode of MAC Ethernet core */ + LPC_EMAC->MAC1 |= MAC1_REC_EN; + +#if NEW_LOGIC + rx_consume_offset = -1; + tx_produce_offset = -1; +#else + send_doff = 0; + send_idx = -1; + send_size = 0; + + receive_soff = 0; + receive_idx = -1; +#endif + + return 0; +} + +/*---------------------------------------------------------------------------- + Ethernet Device Uninitialize + *----------------------------------------------------------------------------*/ +void ethernet_free() { + LPC_EMAC->IntEnable &= ~(INT_RX_DONE | INT_TX_DONE); + LPC_EMAC->IntClear = 0xFFFF; + + LPC_SC->PCONP &= ~0x40000000; /* Power down the EMAC controller. */ + + LPC_PINCON->PINSEL2 &= ~0x50150105; /* Disable P1 ethernet pins. */ + LPC_PINCON->PINSEL3 = (LPC_PINCON->PINSEL3 & ~0x0000000F) | 0x00000000; +} + +// if(TxProduceIndex == TxConsumeIndex) buffer array is empty +// if(TxProduceIndex == TxConsumeIndex - 1) buffer is full, should not fill +// TxProduceIndex - The buffer that will/is being fileld by driver, s/w increment +// TxConsumeIndex - The buffer that will/is beign sent by hardware + +int ethernet_write(const char *data, int slen) { + +#if NEW_LOGIC + + if(tx_produce_offset < 0) { // mark as active if not already + tx_produce_offset = 0; + } + + int index = LPC_EMAC->TxProduceIndex; + + int remaining = ETH_MAX_FLEN - tx_produce_offset - 4; // bytes written plus checksum + int requested = slen; + int ncopy = min(remaining, requested); + + void *pdst = (void *)(txdesc[index].Packet + tx_produce_offset); + void *psrc = (void *)(data); + + if(ncopy > 0 ){ + if(data != NULL) { + memcpy(pdst, psrc, ncopy); + } else { + memset(pdst, 0, ncopy); + } + } + + tx_produce_offset += ncopy; + + return ncopy; + +#else + void *pdst, *psrc; + const int dlen = ETH_FRAG_SIZE; + int copy = 0; + int soff = 0; + + if(send_idx == -1) { + send_idx = LPC_EMAC->TxProduceIndex; + } + + if(slen + send_doff > ethernet_MTU_SIZE) { + return -1; + } + + do { + copy = min(slen - soff, dlen - send_doff); + pdst = (void *)(txdesc[send_idx].Packet + send_doff); + psrc = (void *)(data + soff); + if(send_doff + copy > ETH_FRAG_SIZE) { + txdesc[send_idx].Ctrl = (send_doff-1) | (TCTRL_INT); + send_idx = rinc(send_idx, NUM_TX_FRAG); + send_doff = 0; + } + + if(data != NULL) { + memcpy(pdst, psrc, copy); + } else { + memset(pdst, 0, copy); + } + + soff += copy; + send_doff += copy; + send_size += copy; + } while(soff != slen); + + return soff; +#endif +} + +int ethernet_send() { + +#if NEW_LOGIC + if(tx_produce_offset < 0) { // no buffer active + return -1; + } + + // ensure there is a link + if(!ethernet_link()) { + return -2; + } + + // we have been writing in to a buffer, so finalise it + int size = tx_produce_offset; + int index = LPC_EMAC->TxProduceIndex; + txdesc[index].Ctrl = (tx_produce_offset-1) | (TCTRL_INT | TCTRL_LAST); + + // Increment ProduceIndex to allow it to be sent + // We can only do this if the next slot is free + int next = rinc(index, NUM_TX_FRAG); + while(next == LPC_EMAC->TxConsumeIndex) { + for(int i=0; i<1000; i++) { __NOP(); } + } + + LPC_EMAC->TxProduceIndex = next; + tx_produce_offset = -1; + return size; + +#else + int s = send_size; + txdesc[send_idx].Ctrl = (send_doff-1) | (TCTRL_INT | TCTRL_LAST); + send_idx = rinc(send_idx, NUM_TX_FRAG); + LPC_EMAC->TxProduceIndex = send_idx; + send_doff = 0; + send_idx = -1; + send_size = 0; + return s; +#endif +} + +// RxConsmeIndex - The index of buffer the driver will/is reading from. Driver should inc once read +// RxProduceIndex - The index of buffer that will/is being filled by MAC. H/w will inc once rxd +// +// if(RxConsumeIndex == RxProduceIndex) buffer array is empty +// if(RxConsumeIndex == RxProduceIndex + 1) buffer array is full + +// Recevies an arrived ethernet packet. +// Receiving an ethernet packet will drop the last received ethernet packet +// and make a new ethernet packet ready to read. +// Returns size of packet, else 0 if nothing to receive + +// We read from RxConsumeIndex from position rx_consume_offset +// if rx_consume_offset < 0, then we have not recieved the RxConsumeIndex packet for reading +// rx_consume_offset = -1 // no frame +// rx_consume_offset = 0 // start of frame +// Assumption: A fragment should alway be a whole frame + +int ethernet_receive() { +#if NEW_LOGIC + + // if we are currently reading a valid RxConsume buffer, increment to the next one + if(rx_consume_offset >= 0) { + LPC_EMAC->RxConsumeIndex = rinc(LPC_EMAC->RxConsumeIndex, NUM_RX_FRAG); + } + + // if the buffer is empty, mark it as no valid buffer + if(LPC_EMAC->RxConsumeIndex == LPC_EMAC->RxProduceIndex) { + rx_consume_offset = -1; + return 0; + } + + uint32_t info = rxstat[LPC_EMAC->RxConsumeIndex].Info; + rx_consume_offset = 0; + + // check if it is not marked as last or for errors + if(!(info & RINFO_LAST_FLAG) || (info & RINFO_ERR_MASK)) { + return -1; + } + + int size = (info & RINFO_SIZE) + 1; + return size - 4; // don't include checksum bytes + +#else + if(receive_idx == -1) { + receive_idx = LPC_EMAC->RxConsumeIndex; + } else { + while(!(rxstat[receive_idx].Info & RINFO_LAST_FLAG) && ((uint32_t)receive_idx != LPC_EMAC->RxProduceIndex)) { + receive_idx = rinc(receive_idx, NUM_RX_FRAG); + } + unsigned int info = rxstat[receive_idx].Info; + int slen = (info & RINFO_SIZE) + 1; + + if(slen > ethernet_MTU_SIZE || (info & RINFO_ERR_MASK)) { + /* Invalid frame, ignore it and free buffer. */ + receive_idx = rinc(receive_idx, NUM_RX_FRAG); + } + receive_idx = rinc(receive_idx, NUM_RX_FRAG); + receive_soff = 0; + + LPC_EMAC->RxConsumeIndex = receive_idx; + } + + if((uint32_t)receive_idx == LPC_EMAC->RxProduceIndex) { + receive_idx = -1; + return 0; + } + + return (rxstat[receive_idx].Info & RINFO_SIZE) - 3; +#endif +} + +// Read from an recevied ethernet packet. +// After receive returnd a number bigger than 0 it is +// possible to read bytes from this packet. +// Read will write up to size bytes into data. +// It is possible to use read multible times. +// Each time read will start reading after the last read byte before. + +int ethernet_read(char *data, int dlen) { +#if NEW_LOGIC + // Check we have a valid buffer to read + if(rx_consume_offset < 0) { + return 0; + } + + // Assume 1 fragment block + uint32_t info = rxstat[LPC_EMAC->RxConsumeIndex].Info; + int size = (info & RINFO_SIZE) + 1 - 4; // exclude checksum + + int remaining = size - rx_consume_offset; + int requested = dlen; + int ncopy = min(remaining, requested); + + void *psrc = (void *)(rxdesc[LPC_EMAC->RxConsumeIndex].Packet + rx_consume_offset); + void *pdst = (void *)(data); + + if(data != NULL && ncopy > 0) { + memcpy(pdst, psrc, ncopy); + } + + rx_consume_offset += ncopy; + + return ncopy; +#else + int slen; + int copy = 0; + unsigned int more; + unsigned int info; + void *pdst, *psrc; + int doff = 0; + + if((uint32_t)receive_idx == LPC_EMAC->RxProduceIndex || receive_idx == -1) { + return 0; + } + + do { + info = rxstat[receive_idx].Info; + more = !(info & RINFO_LAST_FLAG); + slen = (info & RINFO_SIZE) + 1; + + if(slen > ethernet_MTU_SIZE || (info & RINFO_ERR_MASK)) { + /* Invalid frame, ignore it and free buffer. */ + receive_idx = rinc(receive_idx, NUM_RX_FRAG); + } else { + + copy = min(slen - receive_soff, dlen - doff); + psrc = (void *)(rxdesc[receive_idx].Packet + receive_soff); + pdst = (void *)(data + doff); + + if(data != NULL) { + /* check if Buffer available */ + memcpy(pdst, psrc, copy); + } + + receive_soff += copy; + doff += copy; + + if((more && (receive_soff == slen))) { + receive_idx = rinc(receive_idx, NUM_RX_FRAG); + receive_soff = 0; + } + } + } while(more && !(doff == dlen) && !receive_soff); + + return doff; +#endif +} + +int ethernet_link(void) { + if (phy_id == DP83848C_ID) { + return (phy_read(PHY_REG_STS) & PHY_STS_LINK); + } + else { // LAN8720_ID + return (phy_read(PHY_REG_BMSR) & PHY_BMSR_LINK); + } +} + +static int phy_write(unsigned int PhyReg, unsigned short Data) { + unsigned int timeOut; + + LPC_EMAC->MADR = DP83848C_DEF_ADR | PhyReg; + LPC_EMAC->MWTD = Data; + + for(timeOut = 0; timeOut < MII_WR_TOUT; timeOut++) { /* Wait until operation completed */ + if((LPC_EMAC->MIND & MIND_BUSY) == 0) { + return 0; + } + } + + return -1; +} + +static int phy_read(unsigned int PhyReg) { + unsigned int timeOut; + + LPC_EMAC->MADR = DP83848C_DEF_ADR | PhyReg; + LPC_EMAC->MCMD = MCMD_READ; + + for(timeOut = 0; timeOut < MII_RD_TOUT; timeOut++) { /* Wait until operation completed */ + if((LPC_EMAC->MIND & MIND_BUSY) == 0) { + LPC_EMAC->MCMD = 0; + return LPC_EMAC->MRDD; /* Return a 16-bit value. */ + } + } + + return -1; +} + + +static void txdscr_init() { + int i; + + for(i = 0; i < NUM_TX_FRAG; i++) { + txdesc[i].Packet = (uint32_t)&txbuf[i]; + txdesc[i].Ctrl = 0; + txstat[i].Info = 0; + } + + LPC_EMAC->TxDescriptor = (uint32_t)txdesc; /* Set EMAC Transmit Descriptor Registers. */ + LPC_EMAC->TxStatus = (uint32_t)txstat; + LPC_EMAC->TxDescriptorNumber = NUM_TX_FRAG-1; + + LPC_EMAC->TxProduceIndex = 0; /* Tx Descriptors Point to 0 */ +} + +static void rxdscr_init() { + int i; + + for(i = 0; i < NUM_RX_FRAG; i++) { + rxdesc[i].Packet = (uint32_t)&rxbuf[i]; + rxdesc[i].Ctrl = RCTRL_INT | (ETH_FRAG_SIZE-1); + rxstat[i].Info = 0; + rxstat[i].HashCRC = 0; + } + + LPC_EMAC->RxDescriptor = (uint32_t)rxdesc; /* Set EMAC Receive Descriptor Registers. */ + LPC_EMAC->RxStatus = (uint32_t)rxstat; + LPC_EMAC->RxDescriptorNumber = NUM_RX_FRAG-1; + + LPC_EMAC->RxConsumeIndex = 0; /* Rx Descriptors Point to 0 */ +} + +void ethernet_address(char *mac) { + mbed_mac_address(mac); +} + +void ethernet_set_link(int speed, int duplex) { + unsigned short phy_data; + int tout; + + if((speed < 0) || (speed > 1)) { + phy_data = PHY_AUTO_NEG; + } else { + phy_data = (((unsigned short) speed << 13) | + ((unsigned short) duplex << 8)); + } + + phy_write(PHY_REG_BMCR, phy_data); + + for(tout = 100; tout; tout--) { __NOP(); } /* A short delay */ + + switch(phy_id) { + case DP83848C_ID: + phy_data = phy_read(PHY_REG_STS); + + if(phy_data & PHY_STS_DUPLEX) { + LPC_EMAC->MAC2 |= MAC2_FULL_DUP; + LPC_EMAC->Command |= CR_FULL_DUP; + LPC_EMAC->IPGT = IPGT_FULL_DUP; + } else { + LPC_EMAC->MAC2 &= ~MAC2_FULL_DUP; + LPC_EMAC->Command &= ~CR_FULL_DUP; + LPC_EMAC->IPGT = IPGT_HALF_DUP; + } + + if(phy_data & PHY_STS_SPEED) { + LPC_EMAC->SUPP &= ~SUPP_SPEED; + } else { + LPC_EMAC->SUPP |= SUPP_SPEED; + } + break; + + case LAN8720_ID: + phy_data = phy_read(PHY_REG_SCSR); + + if (phy_data & PHY_SCSR_DUPLEX) { + LPC_EMAC->MAC2 |= MAC2_FULL_DUP; + LPC_EMAC->Command |= CR_FULL_DUP; + LPC_EMAC->IPGT = IPGT_FULL_DUP; + } else { + LPC_EMAC->Command &= ~CR_FULL_DUP; + LPC_EMAC->IPGT = IPGT_HALF_DUP; + } + + if(phy_data & PHY_SCSR_100MBIT) { + LPC_EMAC->SUPP |= SUPP_SPEED; + } else { + LPC_EMAC->SUPP &= ~SUPP_SPEED; + } + break; + } +} diff --git a/targets/TARGET_NXP/TARGET_LPC2460/gpio_api.c b/targets/TARGET_NXP/TARGET_LPC2460/gpio_api.c new file mode 100644 index 00000000000..425274fbba7 --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC2460/gpio_api.c @@ -0,0 +1,57 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2015 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * 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. + */ +#include "mbed_assert.h" +#include "gpio_api.h" +#include "pinmap.h" + +uint32_t gpio_set(PinName pin) { + LPC_SC->SCS |= 1; // High speed GPIO is enabled on ports 0 and 1 + + pin_function(pin, 0); + + return (1 << ((int)pin & 0x1F)); +} + +void gpio_init(gpio_t *obj, PinName pin) { + if (pin == (PinName)NC) + return; + obj->pin = pin; + if (pin == (PinName)NC) + return; + + obj->mask = gpio_set(pin); + + LPC_GPIO_TypeDef *port_reg = (LPC_GPIO_TypeDef *) ((int)pin & ~0x1F); + + obj->reg_set = &port_reg->FIOSET; + obj->reg_mask = &port_reg->FIOMASK; + obj->reg_clr = &port_reg->FIOCLR; + obj->reg_in = &port_reg->FIOPIN; + obj->reg_dir = &port_reg->FIODIR; +} + +void gpio_mode(gpio_t *obj, PinMode mode) { + pin_mode(obj->pin, mode); +} + +void gpio_dir(gpio_t *obj, PinDirection direction) { + if (obj->pin == (PinName)NC) + return; + switch (direction) { + case PIN_INPUT : *obj->reg_dir &= ~obj->mask; break; + case PIN_OUTPUT: *obj->reg_dir |= obj->mask; break; + } +} diff --git a/targets/TARGET_NXP/TARGET_LPC2460/gpio_irq_api.c b/targets/TARGET_NXP/TARGET_LPC2460/gpio_irq_api.c new file mode 100644 index 00000000000..9b4f3ae62ed --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC2460/gpio_irq_api.c @@ -0,0 +1,154 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2015 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * 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. + */ +#include "gpio_irq_api.h" +#include "mbed_error.h" +#include +#include "cmsis.h" + +#define CHANNEL_NUM 48 + +static uint32_t channel_ids[CHANNEL_NUM] = {0}; +static gpio_irq_handler irq_handler; + +static void handle_interrupt_in(void) { + // Read in all current interrupt registers. We do this once as the + // GPIO interrupt registers are on the APB bus, and this is slow. + uint32_t rise0 = LPC_GPIOINT->IO0IntStatR; + uint32_t fall0 = LPC_GPIOINT->IO0IntStatF; + uint32_t rise2 = LPC_GPIOINT->IO2IntStatR; + uint32_t fall2 = LPC_GPIOINT->IO2IntStatF; + uint32_t mask0 = 0; + uint32_t mask2 = 0; + int i; + + // P0.0-0.31 + for (i = 0; i < 32; i++) { + uint32_t pmask = (1 << i); + if (rise0 & pmask) { + mask0 |= pmask; + if (channel_ids[i] != 0) + irq_handler(channel_ids[i], IRQ_RISE); + } + if (fall0 & pmask) { + mask0 |= pmask; + if (channel_ids[i] != 0) + irq_handler(channel_ids[i], IRQ_FALL); + } + } + + // P2.0-2.15 + for (i = 0; i < 16; i++) { + uint32_t pmask = (1 << i); + int channel_index = i + 32; + if (rise2 & pmask) { + mask2 |= pmask; + if (channel_ids[channel_index] != 0) + irq_handler(channel_ids[channel_index], IRQ_RISE); + } + if (fall2 & pmask) { + mask2 |= pmask; + if (channel_ids[channel_index] != 0) + irq_handler(channel_ids[channel_index], IRQ_FALL); + } + } + + // Clear the interrupts we just handled + LPC_GPIOINT->IO0IntClr = mask0; + LPC_GPIOINT->IO2IntClr = mask2; +} + +int gpio_irq_init(gpio_irq_t *obj, PinName pin, gpio_irq_handler handler, uint32_t id) { + if (pin == NC) return -1; + + irq_handler = handler; + + obj->port = (int)pin & ~0x1F; + obj->pin = (int)pin & 0x1F; + + // Interrupts available only on GPIO0 and GPIO2 + if (obj->port != LPC_GPIO0_BASE && obj->port != LPC_GPIO2_BASE) { + error("pins on this port cannot generate interrupts"); + } + + // put us in the interrupt table + int index = (obj->port == LPC_GPIO0_BASE) ? obj->pin : obj->pin + 32; + channel_ids[index] = id; + obj->ch = index; + + NVIC_SetVector(EINT3_IRQn, (uint32_t)handle_interrupt_in); + NVIC_EnableIRQ(EINT3_IRQn); + + return 0; +} + +void gpio_irq_free(gpio_irq_t *obj) { + channel_ids[obj->ch] = 0; +} + +void gpio_irq_set(gpio_irq_t *obj, gpio_irq_event event, uint32_t enable) { + // ensure nothing is pending + switch (obj->port) { + case LPC_GPIO0_BASE: LPC_GPIOINT->IO0IntClr = 1 << obj->pin; break; + case LPC_GPIO2_BASE: LPC_GPIOINT->IO2IntClr = 1 << obj->pin; break; + } + + // enable the pin interrupt + if (event == IRQ_RISE) { + switch (obj->port) { + case LPC_GPIO0_BASE: + if (enable) { + LPC_GPIOINT->IO0IntEnR |= 1 << obj->pin; + } else { + LPC_GPIOINT->IO0IntEnR &= ~(1 << obj->pin); + } + break; + case LPC_GPIO2_BASE: + if (enable) { + LPC_GPIOINT->IO2IntEnR |= 1 << obj->pin; + } else { + LPC_GPIOINT->IO2IntEnR &= ~(1 << obj->pin); + } + break; + } + } else { + switch (obj->port) { + case LPC_GPIO0_BASE: + if (enable) { + LPC_GPIOINT->IO0IntEnF |= 1 << obj->pin; + } else { + LPC_GPIOINT->IO0IntEnF &= ~(1 << obj->pin); + } + break; + + case LPC_GPIO2_BASE: + if (enable) { + LPC_GPIOINT->IO2IntEnF |= 1 << obj->pin; + } else { + LPC_GPIOINT->IO2IntEnF &= ~(1 << obj->pin); + } + break; + } + } +} + +void gpio_irq_enable(gpio_irq_t *obj) { + NVIC_EnableIRQ(EINT3_IRQn); +} + +void gpio_irq_disable(gpio_irq_t *obj) { + NVIC_DisableIRQ(EINT3_IRQn); +} + diff --git a/targets/TARGET_NXP/TARGET_LPC2460/gpio_object.h b/targets/TARGET_NXP/TARGET_LPC2460/gpio_object.h new file mode 100644 index 00000000000..21b99e5e317 --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC2460/gpio_object.h @@ -0,0 +1,59 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2015 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * 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. + */ +#ifndef MBED_GPIO_OBJECT_H +#define MBED_GPIO_OBJECT_H + +#include "mbed_assert.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct { + PinName pin; + uint32_t mask; + + __IO uint32_t *reg_dir; + __IO uint32_t *reg_mask; + __IO uint32_t *reg_set; + __IO uint32_t *reg_clr; + __I uint32_t *reg_in; +} gpio_t; + +static inline void gpio_write(gpio_t *obj, int value) { + MBED_ASSERT(obj->pin != (PinName)NC); + *obj->reg_mask &= ~obj->mask; + if (value) + *obj->reg_set = obj->mask; + else + *obj->reg_clr = obj->mask; +} + +static inline int gpio_read(gpio_t *obj) { + MBED_ASSERT(obj->pin != (PinName)NC); + *obj->reg_mask &= ~obj->mask; + return ((*obj->reg_in & obj->mask) ? 1 : 0); +} + +static inline int gpio_is_connected(const gpio_t *obj) { + return obj->pin != (PinName)NC; +} + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/targets/TARGET_NXP/TARGET_LPC2460/i2c_api.c b/targets/TARGET_NXP/TARGET_LPC2460/i2c_api.c new file mode 100644 index 00000000000..e497eea83a4 --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC2460/i2c_api.c @@ -0,0 +1,405 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2015 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * 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. + */ +#include "i2c_api.h" +#include "cmsis.h" +#include "pinmap.h" + +static const PinMap PinMap_I2C_SDA[] = { + {P0_0 , I2C_1, 3}, + {P0_10, I2C_2, 2}, + {P0_19, I2C_1, 3}, + {P0_27, I2C_0, 1}, + {P2_14, I2C_1, 3}, + {P2_30, I2C_2, 3}, + {P4_20, I2C_2, 2}, + {NC , NC , 0} +}; + +static const PinMap PinMap_I2C_SCL[] = { + {P0_1 , I2C_1, 3}, + {P0_11, I2C_2, 2}, + {P0_20, I2C_1, 3}, + {P0_28, I2C_0, 1}, + {P2_15, I2C_1, 3}, + {P2_31, I2C_2, 3}, + {P4_21, I2C_2, 2}, + {NC , NC, 0} +}; + +#define I2C_CONSET(x) (x->i2c->I2CONSET) +#define I2C_CONCLR(x) (x->i2c->I2CONCLR) +#define I2C_STAT(x) (x->i2c->I2STAT) +#define I2C_DAT(x) (x->i2c->I2DAT) +#define I2C_SCLL(x, val) (x->i2c->I2SCLL = val) +#define I2C_SCLH(x, val) (x->i2c->I2SCLH = val) + +static const uint32_t I2C_addr_offset[2][4] = { + {0x0C, 0x20, 0x24, 0x28}, + {0x30, 0x34, 0x38, 0x3C} +}; + +static inline void i2c_conclr(i2c_t *obj, int start, int stop, int interrupt, int acknowledge) { + I2C_CONCLR(obj) = (start << 5) + | (stop << 4) + | (interrupt << 3) + | (acknowledge << 2); +} + +static inline void i2c_conset(i2c_t *obj, int start, int stop, int interrupt, int acknowledge) { + I2C_CONSET(obj) = (start << 5) + | (stop << 4) + | (interrupt << 3) + | (acknowledge << 2); +} + +// Clear the Serial Interrupt (SI) +static inline void i2c_clear_SI(i2c_t *obj) { + i2c_conclr(obj, 0, 0, 1, 0); +} + +static inline int i2c_status(i2c_t *obj) { + return I2C_STAT(obj); +} + +// Wait until the Serial Interrupt (SI) is set +static int i2c_wait_SI(i2c_t *obj) { + int timeout = 0; + while (!(I2C_CONSET(obj) & (1 << 3))) { + timeout++; + if (timeout > 100000) return -1; + } + return 0; +} + +static inline void i2c_interface_enable(i2c_t *obj) { + I2C_CONSET(obj) = 0x40; +} + +static inline void i2c_power_enable(i2c_t *obj) { + switch ((int)obj->i2c) { + case I2C_0: LPC_SC->PCONP |= 1 << PCI2C0; break; + case I2C_1: LPC_SC->PCONP |= 1 << PCI2C1; break; + case I2C_2: LPC_SC->PCONP |= 1 << PCI2C2; break; + } +} + +void i2c_init(i2c_t *obj, PinName sda, PinName scl) { + // determine the SPI to use + I2CName i2c_sda = (I2CName)pinmap_peripheral(sda, PinMap_I2C_SDA); + I2CName i2c_scl = (I2CName)pinmap_peripheral(scl, PinMap_I2C_SCL); + obj->i2c = (LPC_I2C_TypeDef *)pinmap_merge(i2c_sda, i2c_scl); + MBED_ASSERT((int)obj->i2c != NC); + + // enable power + i2c_power_enable(obj); + + // set default frequency at 100k + i2c_frequency(obj, 100000); + i2c_conclr(obj, 1, 1, 1, 1); + i2c_interface_enable(obj); + + pinmap_pinout(sda, PinMap_I2C_SDA); + pinmap_pinout(scl, PinMap_I2C_SCL); +} + +inline int i2c_start(i2c_t *obj) { + int status = 0; + int isInterrupted = I2C_CONSET(obj) & (1 << 3); + + // 8.1 Before master mode can be entered, I2CON must be initialised to: + // - I2EN STA STO SI AA - - + // - 1 0 0 x x - - + // if AA = 0, it can't enter slave mode + i2c_conclr(obj, 1, 1, 0, 1); + + // The master mode may now be entered by setting the STA bit + // this will generate a start condition when the bus becomes free + i2c_conset(obj, 1, 0, 0, 1); + // Clearing SI bit when it wasn't set on entry can jump past state + // 0x10 or 0x08 and erroneously send uninitialized slave address. + if (isInterrupted) + i2c_clear_SI(obj); + + i2c_wait_SI(obj); + status = i2c_status(obj); + + // Clear start bit now that it's transmitted + i2c_conclr(obj, 1, 0, 0, 0); + return status; +} + +inline int i2c_stop(i2c_t *obj) { + int timeout = 0; + + // write the stop bit + i2c_conset(obj, 0, 1, 0, 0); + i2c_clear_SI(obj); + + // wait for STO bit to reset + while (I2C_CONSET(obj) & (1 << 4)) { + timeout ++; + if (timeout > 100000) return 1; + } + + return 0; +} + +static inline int i2c_do_write(i2c_t *obj, int value, uint8_t addr) { + // write the data + I2C_DAT(obj) = value; + + // clear SI to init a send + i2c_clear_SI(obj); + + // wait and return status + i2c_wait_SI(obj); + return i2c_status(obj); +} + +static inline int i2c_do_read(i2c_t *obj, int last) { + // we are in state 0x40 (SLA+R tx'd) or 0x50 (data rx'd and ack) + if (last) { + i2c_conclr(obj, 0, 0, 0, 1); // send a NOT ACK + } else { + i2c_conset(obj, 0, 0, 0, 1); // send a ACK + } + + // accept byte + i2c_clear_SI(obj); + + // wait for it to arrive + i2c_wait_SI(obj); + + // return the data + return (I2C_DAT(obj) & 0xFF); +} + +void i2c_frequency(i2c_t *obj, int hz) { + // [TODO] set pclk to /4 + uint32_t PCLK = SystemCoreClock / 4; + + uint32_t pulse = PCLK / (hz * 2); + + // I2C Rate + I2C_SCLL(obj, pulse); + I2C_SCLH(obj, pulse); +} + +// The I2C does a read or a write as a whole operation +// There are two types of error conditions it can encounter +// 1) it can not obtain the bus +// 2) it gets error responses at part of the transmission +// +// We tackle them as follows: +// 1) we retry until we get the bus. we could have a "timeout" if we can not get it +// which basically turns it in to a 2) +// 2) on error, we use the standard error mechanisms to report/debug +// +// Therefore an I2C transaction should always complete. If it doesn't it is usually +// because something is setup wrong (e.g. wiring), and we don't need to programatically +// check for that +int i2c_read(i2c_t *obj, int address, char *data, int length, int stop) { + int count, status; + + status = i2c_start(obj); + + if ((status != 0x10) && (status != 0x08)) { + i2c_stop(obj); + return I2C_ERROR_BUS_BUSY; + } + + status = i2c_do_write(obj, (address | 0x01), 1); + if (status != 0x40) { + i2c_stop(obj); + return I2C_ERROR_NO_SLAVE; + } + + // Read in all except last byte + for (count = 0; count < (length - 1); count++) { + int value = i2c_do_read(obj, 0); + status = i2c_status(obj); + if (status != 0x50) { + i2c_stop(obj); + return count; + } + data[count] = (char) value; + } + + // read in last byte + int value = i2c_do_read(obj, 1); + status = i2c_status(obj); + if (status != 0x58) { + i2c_stop(obj); + return length - 1; + } + + data[count] = (char) value; + + // If not repeated start, send stop. + if (stop) { + i2c_stop(obj); + } + + return length; +} + +int i2c_write(i2c_t *obj, int address, const char *data, int length, int stop) { + int i, status; + + status = i2c_start(obj); + + if ((status != 0x10) && (status != 0x08)) { + i2c_stop(obj); + return I2C_ERROR_BUS_BUSY; + } + + status = i2c_do_write(obj, (address & 0xFE), 1); + if (status != 0x18) { + i2c_stop(obj); + return I2C_ERROR_NO_SLAVE; + } + + for (i=0; i= 0) && (idx <= 3)) { + addr = ((uint32_t)obj->i2c) + I2C_addr_offset[0][idx]; + *((uint32_t *) addr) = address & 0xFF; + } +} diff --git a/targets/TARGET_NXP/TARGET_LPC2460/objects.h b/targets/TARGET_NXP/TARGET_LPC2460/objects.h new file mode 100644 index 00000000000..157e44a357a --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC2460/objects.h @@ -0,0 +1,78 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2015 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * 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. + */ +#ifndef MBED_OBJECTS_H +#define MBED_OBJECTS_H + +#include "cmsis.h" +#include "PortNames.h" +#include "PeripheralNames.h" +#include "PinNames.h" + +#ifdef __cplusplus +extern "C" { +#endif + +struct gpio_irq_s { + uint32_t port; + uint32_t pin; + uint32_t ch; +}; + +struct port_s { + __IO uint32_t *reg_dir; + __IO uint32_t *reg_out; + __I uint32_t *reg_in; + PortName port; + uint32_t mask; +}; + +struct pwmout_s { + __IO uint32_t *MR; + PWMName pwm; +}; + +struct serial_s { + LPC_UART_TypeDef *uart; + int index; +}; + +struct analogin_s { + ADCName adc; +}; + +struct dac_s { + DACName dac; +}; + +struct can_s { + LPC_CAN_TypeDef *dev; +}; + +struct i2c_s { + LPC_I2C_TypeDef *i2c; +}; + +struct spi_s { + LPC_SSP_TypeDef *spi; +}; + +#include "gpio_object.h" + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/targets/TARGET_NXP/TARGET_LPC2460/pinmap.c b/targets/TARGET_NXP/TARGET_LPC2460/pinmap.c new file mode 100644 index 00000000000..2327928978f --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC2460/pinmap.c @@ -0,0 +1,46 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2015 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * 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. + */ +#include "mbed_assert.h" +#include "pinmap.h" +#include "mbed_error.h" + +void pin_function(PinName pin, int function) { + MBED_ASSERT(pin != (PinName)NC); + + uint32_t pin_number = (uint32_t)pin - (uint32_t)P0_0; + int index = pin_number >> 4; + int offset = (pin_number & 0xF) << 1; + + PINCONARRAY->PINSEL[index] &= ~(0x3 << offset); + PINCONARRAY->PINSEL[index] |= function << offset; +} + +void pin_mode(PinName pin, PinMode mode) { + MBED_ASSERT((pin != (PinName)NC) && (mode != OpenDrain)); + + uint32_t pin_number = (uint32_t)pin - (uint32_t)P0_0; + int index = pin_number >> 5; + int offset = pin_number & 0x1F; + uint32_t drain = ((uint32_t) mode & (uint32_t) OpenDrain) >> 2; + + if (!drain) { + index = pin_number >> 4; + offset = (pin_number & 0xF) << 1; + + PINCONARRAY->PINMODE[index] &= ~(0x3 << offset); + PINCONARRAY->PINMODE[index] |= (uint32_t)mode << offset; + } +} diff --git a/targets/TARGET_NXP/TARGET_LPC2460/port_api.c b/targets/TARGET_NXP/TARGET_LPC2460/port_api.c new file mode 100644 index 00000000000..da9aa4f5ca7 --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC2460/port_api.c @@ -0,0 +1,71 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2015 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * 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. + */ +#include "port_api.h" +#include "pinmap.h" +#include "gpio_api.h" + +PinName port_pin(PortName port, int pin_n) { + return (PinName)(LPC_GPIO0_BASE + ((port << PORT_SHIFT) | pin_n)); +} + +void port_init(port_t *obj, PortName port, int mask, PinDirection dir) { + obj->port = port; + obj->mask = mask; + + LPC_GPIO_TypeDef *port_reg = (LPC_GPIO_TypeDef *)(LPC_GPIO0_BASE + ((int)port * 0x20)); + + // Do not use masking, because it prevents the use of the unmasked pins + // port_reg->FIOMASK = ~mask; + + obj->reg_out = &port_reg->FIOPIN; + obj->reg_in = &port_reg->FIOPIN; + obj->reg_dir = &port_reg->FIODIR; + + uint32_t i; + // The function is set per pin: reuse gpio logic + for (i=0; i<32; i++) { + if (obj->mask & (1<port, i)); + } + } + + port_dir(obj, dir); +} + +void port_mode(port_t *obj, PinMode mode) { + uint32_t i; + // The mode is set per pin: reuse pinmap logic + for (i=0; i<32; i++) { + if (obj->mask & (1<port, i), mode); + } + } +} + +void port_dir(port_t *obj, PinDirection dir) { + switch (dir) { + case PIN_INPUT : *obj->reg_dir &= ~obj->mask; break; + case PIN_OUTPUT: *obj->reg_dir |= obj->mask; break; + } +} + +void port_write(port_t *obj, int value) { + *obj->reg_out = (*obj->reg_in & ~obj->mask) | (value & obj->mask); +} + +int port_read(port_t *obj) { + return (*obj->reg_in & obj->mask); +} diff --git a/targets/TARGET_NXP/TARGET_LPC2460/pwmout_api.c b/targets/TARGET_NXP/TARGET_LPC2460/pwmout_api.c new file mode 100644 index 00000000000..0ce7138f58a --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC2460/pwmout_api.c @@ -0,0 +1,175 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2015 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * 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. + */ +#include "mbed_assert.h" +#include "pwmout_api.h" +#include "cmsis.h" +#include "pinmap.h" + +#define TCR_CNT_EN 0x00000001 +#define TCR_RESET 0x00000002 + +// PORT ID, PWM ID, Pin function +static const PinMap PinMap_PWM[] = { + {P1_18, PWM_1, 2}, + {P1_20, PWM_2, 2}, + {P1_21, PWM_3, 2}, + {P1_23, PWM_4, 2}, + {P1_24, PWM_5, 2}, + {P1_26, PWM_6, 2}, + {P2_0 , PWM_1, 1}, + {P2_1 , PWM_2, 1}, + {P2_2 , PWM_3, 1}, + {P2_3 , PWM_4, 1}, + {P2_4 , PWM_5, 1}, + {P2_5 , PWM_6, 1}, + {P3_24, PWM_1, 3}, + {P3_25, PWM_2, 3}, + {P3_26, PWM_3, 3}, + {P3_27, PWM_4, 3}, + {P3_28, PWM_5, 3}, + {P3_29, PWM_6, 3}, + {NC, NC, 0} +}; + +__IO uint32_t *PWM_MATCH[] = { + &(LPC_PWM1->MR0), + &(LPC_PWM1->MR1), + &(LPC_PWM1->MR2), + &(LPC_PWM1->MR3), + &(LPC_PWM1->MR4), + &(LPC_PWM1->MR5), + &(LPC_PWM1->MR6) +}; + +#define TCR_PWM_EN 0x00000008 + +static unsigned int pwm_clock_mhz; + +void pwmout_init(pwmout_t* obj, PinName pin) { + // determine the channel + PWMName pwm = (PWMName)pinmap_peripheral(pin, PinMap_PWM); + MBED_ASSERT(pwm != (PWMName)NC); + + obj->pwm = pwm; + obj->MR = PWM_MATCH[pwm]; + + // ensure the power is on + LPC_SC->PCONP |= 1 << 6; + + // ensure clock to /4 + LPC_SC->PCLKSEL0 &= ~(0x3 << 12); // pclk = /4 + LPC_PWM1->PR = 0; // no pre-scale + + // ensure single PWM mode + LPC_PWM1->MCR = 1 << 1; // reset TC on match 0 + + // enable the specific PWM output + LPC_PWM1->PCR |= 1 << (8 + pwm); + + pwm_clock_mhz = SystemCoreClock / 4000000; + + // default to 20ms: standard for servos, and fine for e.g. brightness control + pwmout_period_ms(obj, 20); + pwmout_write (obj, 0); + + // Wire pinout + pinmap_pinout(pin, PinMap_PWM); +} + +void pwmout_free(pwmout_t* obj) { + // [TODO] +} + +void pwmout_write(pwmout_t* obj, float value) { + if (value < 0.0f) { + value = 0.0; + } else if (value > 1.0f) { + value = 1.0; + } + + // set channel match to percentage + uint32_t v = (uint32_t)((float)(LPC_PWM1->MR0) * value); + + // workaround for PWM1[1] - Never make it equal MR0, else we get 1 cycle dropout + if (v == LPC_PWM1->MR0) { + v++; + } + + *obj->MR = v; + + // accept on next period start + LPC_PWM1->LER |= 1 << obj->pwm; +} + +float pwmout_read(pwmout_t* obj) { + float v = (float)(*obj->MR) / (float)(LPC_PWM1->MR0); + return (v > 1.0f) ? (1.0f) : (v); +} + +void pwmout_period(pwmout_t* obj, float seconds) { + pwmout_period_us(obj, seconds * 1000000.0f); +} + +void pwmout_period_ms(pwmout_t* obj, int ms) { + pwmout_period_us(obj, ms * 1000); +} + +// Set the PWM period, keeping the duty cycle the same. +void pwmout_period_us(pwmout_t* obj, int us) { + // calculate number of ticks + uint32_t ticks = pwm_clock_mhz * us; + + // set reset + LPC_PWM1->TCR = TCR_RESET; + + // set the global match register + LPC_PWM1->MR0 = ticks; + + // Scale the pulse width to preserve the duty ratio + if (LPC_PWM1->MR0 > 0) { + *obj->MR = (*obj->MR * ticks) / LPC_PWM1->MR0; + } + + // set the channel latch to update value at next period start + LPC_PWM1->LER |= 1 << 0; + + // enable counter and pwm, clear reset + LPC_PWM1->TCR = TCR_CNT_EN | TCR_PWM_EN; +} + +void pwmout_pulsewidth(pwmout_t* obj, float seconds) { + pwmout_pulsewidth_us(obj, seconds * 1000000.0f); +} + +void pwmout_pulsewidth_ms(pwmout_t* obj, int ms) { + pwmout_pulsewidth_us(obj, ms * 1000); +} + +void pwmout_pulsewidth_us(pwmout_t* obj, int us) { + // calculate number of ticks + uint32_t v = pwm_clock_mhz * us; + + // workaround for PWM1[1] - Never make it equal MR0, else we get 1 cycle dropout + if (v == LPC_PWM1->MR0) { + v++; + } + + // set the match register value + *obj->MR = v; + + // set the channel latch to update value at next period start + LPC_PWM1->LER |= 1 << obj->pwm; +} diff --git a/targets/TARGET_NXP/TARGET_LPC2460/rtc_api.c b/targets/TARGET_NXP/TARGET_LPC2460/rtc_api.c new file mode 100644 index 00000000000..526c6f3ad4d --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC2460/rtc_api.c @@ -0,0 +1,117 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2015 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * 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. + */ +#include "rtc_api.h" + +// ensure rtc is running (unchanged if already running) + +/* Setup the RTC based on a time structure, ensuring RTC is enabled + * + * Can be clocked by a 32.768KHz oscillator or prescale divider based on the APB clock + * - We want to use the 32khz clock, allowing for sleep mode + * + * Most registers are not changed by a Reset + * - We must initialize these registers between power-on and setting the RTC into operation + + * Clock Control Register + * RTC_CCR[0] : Enable - 0 = Disabled, 1 = Enabled + * RTC_CCR[1] : Reset - 0 = Normal, 1 = Reset + * RTC_CCR[4] : Clock Source - 0 = Prescaler, 1 = 32k Xtal + * + * The RTC may already be running, so we should set it up + * without impacting if it is the case + */ +void rtc_init(void) { + LPC_SC->PCONP |= (1 << PCRTC); // Ensure power is on + LPC_RTC->CCR = 0x00; + + // clock source on 2368 is special test mode on 1768! + LPC_RTC->CCR |= 1 << 4; // Ensure clock source is 32KHz Xtal + + LPC_RTC->CCR |= 1 << 0; // Ensure the RTC is enabled +} + +void rtc_free(void) { + // [TODO] +} + +/* + * Little check routine to see if the RTC has been enabled + * + * Clock Control Register + * RTC_CCR[0] : 0 = Disabled, 1 = Enabled + * + */ + +int rtc_isenabled(void) { + return(((LPC_RTC->CCR) & 0x01) != 0); +} + +/* + * RTC Registers + * RTC_SEC Seconds 0-59 + * RTC_MIN Minutes 0-59 + * RTC_HOUR Hour 0-23 + * RTC_DOM Day of Month 1-28..31 + * RTC_DOW Day of Week 0-6 + * RTC_DOY Day of Year 1-365 + * RTC_MONTH Month 1-12 + * RTC_YEAR Year 0-4095 + * + * struct tm + * tm_sec seconds after the minute 0-61 + * tm_min minutes after the hour 0-59 + * tm_hour hours since midnight 0-23 + * tm_mday day of the month 1-31 + * tm_mon months since January 0-11 + * tm_year years since 1900 + * tm_wday days since Sunday 0-6 + * tm_yday days since January 1 0-365 + * tm_isdst Daylight Saving Time flag + */ +time_t rtc_read(void) { + // Setup a tm structure based on the RTC + struct tm timeinfo; + timeinfo.tm_sec = LPC_RTC->SEC; + timeinfo.tm_min = LPC_RTC->MIN; + timeinfo.tm_hour = LPC_RTC->HOUR; + timeinfo.tm_mday = LPC_RTC->DOM; + timeinfo.tm_mon = LPC_RTC->MONTH - 1; + timeinfo.tm_year = LPC_RTC->YEAR - 1900; + + // Convert to timestamp + time_t t = mktime(&timeinfo); + + return t; +} + +void rtc_write(time_t t) { + // Convert the time in to a tm + struct tm *timeinfo = localtime(&t); + + // Pause clock, and clear counter register (clears us count) + LPC_RTC->CCR |= 2; + + // Set the RTC + LPC_RTC->SEC = timeinfo->tm_sec; + LPC_RTC->MIN = timeinfo->tm_min; + LPC_RTC->HOUR = timeinfo->tm_hour; + LPC_RTC->DOM = timeinfo->tm_mday; + LPC_RTC->MONTH = timeinfo->tm_mon + 1; + LPC_RTC->YEAR = timeinfo->tm_year + 1900; + + // Restart clock + LPC_RTC->CCR &= ~((uint32_t)2); +} diff --git a/targets/TARGET_NXP/TARGET_LPC2460/serial_api.c b/targets/TARGET_NXP/TARGET_LPC2460/serial_api.c new file mode 100644 index 00000000000..9a92bb04ba9 --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC2460/serial_api.c @@ -0,0 +1,338 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2015 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * 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. + */ +// math.h required for floating point operations for baud rate calculation +#include "mbed_assert.h" +#include +#include +#include + +#include "serial_api.h" +#include "cmsis.h" +#include "pinmap.h" + +/****************************************************************************** + * INITIALIZATION + ******************************************************************************/ +#define UART_NUM 4 + +static const PinMap PinMap_UART_TX[] = { + {P0_0, UART_3, 2}, + {P0_2, UART_0, 1}, + {P0_10, UART_2, 1}, + {P0_15, UART_1, 1}, + {P0_25, UART_3, 3}, + {P2_0 , UART_1, 2}, + {P2_8 , UART_2, 2}, + {P4_28, UART_3, 3}, + {NC , NC , 0} +}; + +static const PinMap PinMap_UART_RX[] = { + {P0_1 , UART_3, 2}, + {P0_3 , UART_0, 1}, + {P0_11, UART_2, 1}, + {P0_16, UART_1, 1}, + {P0_26, UART_3, 3}, + {P2_1 , UART_1, 2}, + {P2_9 , UART_2, 2}, + {P4_29, UART_3, 3}, + {NC , NC , 0} +}; + +static uint32_t serial_irq_ids[UART_NUM] = {0}; +static uart_irq_handler irq_handler; + +int stdio_uart_inited = 0; +serial_t stdio_uart; + +void serial_init(serial_t *obj, PinName tx, PinName rx) { + int is_stdio_uart = 0; + + // determine the UART to use + UARTName uart_tx = (UARTName)pinmap_peripheral(tx, PinMap_UART_TX); + UARTName uart_rx = (UARTName)pinmap_peripheral(rx, PinMap_UART_RX); + UARTName uart = (UARTName)pinmap_merge(uart_tx, uart_rx); + MBED_ASSERT((int)uart != NC); + + obj->uart = (LPC_UART_TypeDef *)uart; + // enable power + switch (uart) { + case UART_0: LPC_SC->PCONP |= 1 << 3; break; + case UART_1: LPC_SC->PCONP |= 1 << 4; break; + case UART_2: LPC_SC->PCONP |= 1 << 24; break; + case UART_3: LPC_SC->PCONP |= 1 << 25; break; + } + + // enable fifos and default rx trigger level + obj->uart->FCR = 1 << 0 // FIFO Enable - 0 = Disables, 1 = Enabled + | 0 << 1 // Rx Fifo Reset + | 0 << 2 // Tx Fifo Reset + | 0 << 6; // Rx irq trigger level - 0 = 1 char, 1 = 4 chars, 2 = 8 chars, 3 = 14 chars + + // disable irqs + obj->uart->IER = 0 << 0 // Rx Data available irq enable + | 0 << 1 // Tx Fifo empty irq enable + | 0 << 2; // Rx Line Status irq enable + + // set default baud rate and format + serial_baud (obj, 9600); + serial_format(obj, 8, ParityNone, 1); + + // pinout the chosen uart + pinmap_pinout(tx, PinMap_UART_TX); + pinmap_pinout(rx, PinMap_UART_RX); + + // set rx/tx pins in PullUp mode + if (tx != NC) { + pin_mode(tx, PullUp); + } + if (rx != NC) { + pin_mode(rx, PullUp); + } + + switch (uart) { + case UART_0: obj->index = 0; break; + case UART_1: obj->index = 1; break; + case UART_2: obj->index = 2; break; + case UART_3: obj->index = 3; break; + } + + is_stdio_uart = (uart == STDIO_UART) ? (1) : (0); + + if (is_stdio_uart) { + stdio_uart_inited = 1; + memcpy(&stdio_uart, obj, sizeof(serial_t)); + } +} + +void serial_free(serial_t *obj) { + serial_irq_ids[obj->index] = 0; +} + +// serial_baud +// set the baud rate, taking in to account the current SystemFrequency +void serial_baud(serial_t *obj, int baudrate) { + MBED_ASSERT((int)obj->uart <= UART_3); + // The LPC2300 and LPC1700 have a divider and a fractional divider to control the + // baud rate. The formula is: + // + // Baudrate = (1 / PCLK) * 16 * DL * (1 + DivAddVal / MulVal) + // where: + // 1 < MulVal <= 15 + // 0 <= DivAddVal < 14 + // DivAddVal < MulVal + // + // set pclk to /1 + switch ((int)obj->uart) { + case UART_0: LPC_SC->PCLKSEL0 &= ~(0x3 << 6); LPC_SC->PCLKSEL0 |= (0x1 << 6); break; + case UART_1: LPC_SC->PCLKSEL0 &= ~(0x3 << 8); LPC_SC->PCLKSEL0 |= (0x1 << 8); break; + case UART_2: LPC_SC->PCLKSEL1 &= ~(0x3 << 16); LPC_SC->PCLKSEL1 |= (0x1 << 16); break; + case UART_3: LPC_SC->PCLKSEL1 &= ~(0x3 << 18); LPC_SC->PCLKSEL1 |= (0x1 << 18); break; + default: break; + } + + uint32_t PCLK = SystemCoreClock; + + // First we check to see if the basic divide with no DivAddVal/MulVal + // ratio gives us an integer result. If it does, we set DivAddVal = 0, + // MulVal = 1. Otherwise, we search the valid ratio value range to find + // the closest match. This could be more elegant, using search methods + // and/or lookup tables, but the brute force method is not that much + // slower, and is more maintainable. + uint16_t DL = PCLK / (16 * baudrate); + + uint8_t DivAddVal = 0; + uint8_t MulVal = 1; + int hit = 0; + uint16_t dlv; + uint8_t mv, dav; + if ((PCLK % (16 * baudrate)) != 0) { // Checking for zero remainder + int err_best = baudrate, b; + for (mv = 1; mv < 16 && !hit; mv++) + { + for (dav = 0; dav < mv; dav++) + { + // baudrate = PCLK / (16 * dlv * (1 + (DivAdd / Mul)) + // solving for dlv, we get dlv = mul * PCLK / (16 * baudrate * (divadd + mul)) + // mul has 4 bits, PCLK has 27 so we have 1 bit headroom which can be used for rounding + // for many values of mul and PCLK we have 2 or more bits of headroom which can be used to improve precision + // note: X / 32 doesn't round correctly. Instead, we use ((X / 16) + 1) / 2 for correct rounding + + if ((mv * PCLK * 2) & 0x80000000) // 1 bit headroom + dlv = ((((2 * mv * PCLK) / (baudrate * (dav + mv))) / 16) + 1) / 2; + else // 2 bits headroom, use more precision + dlv = ((((4 * mv * PCLK) / (baudrate * (dav + mv))) / 32) + 1) / 2; + + // datasheet says if DLL==DLM==0, then 1 is used instead since divide by zero is ungood + if (dlv == 0) + dlv = 1; + + // datasheet says if dav > 0 then DL must be >= 2 + if ((dav > 0) && (dlv < 2)) + dlv = 2; + + // integer rearrangement of the baudrate equation (with rounding) + b = ((PCLK * mv / (dlv * (dav + mv) * 8)) + 1) / 2; + + // check to see how we went + b = abs(b - baudrate); + if (b < err_best) + { + err_best = b; + + DL = dlv; + MulVal = mv; + DivAddVal = dav; + + if (b == baudrate) + { + hit = 1; + break; + } + } + } + } + } + + // set LCR[DLAB] to enable writing to divider registers + obj->uart->LCR |= (1 << 7); + + // set divider values + obj->uart->DLM = (DL >> 8) & 0xFF; + obj->uart->DLL = (DL >> 0) & 0xFF; + obj->uart->FDR = (uint32_t) DivAddVal << 0 + | (uint32_t) MulVal << 4; + + // clear LCR[DLAB] + obj->uart->LCR &= ~(1 << 7); +} + +void serial_format(serial_t *obj, int data_bits, SerialParity parity, int stop_bits) { + MBED_ASSERT((stop_bits == 1) || (stop_bits == 2)); // 0: 1 stop bits, 1: 2 stop bits + MBED_ASSERT((data_bits > 4) && (data_bits < 9)); // 0: 5 data bits ... 3: 8 data bits + MBED_ASSERT((parity == ParityNone) || (parity == ParityOdd) || (parity == ParityEven) || + (parity == ParityForced1) || (parity == ParityForced0)); + + stop_bits -= 1; + data_bits -= 5; + + int parity_enable = 0, parity_select = 0; + switch (parity) { + case ParityNone: parity_enable = 0; parity_select = 0; break; + case ParityOdd : parity_enable = 1; parity_select = 0; break; + case ParityEven: parity_enable = 1; parity_select = 1; break; + case ParityForced1: parity_enable = 1; parity_select = 2; break; + case ParityForced0: parity_enable = 1; parity_select = 3; break; + default: + break; + } + + obj->uart->LCR = data_bits << 0 + | stop_bits << 2 + | parity_enable << 3 + | parity_select << 4; +} + +/****************************************************************************** + * INTERRUPTS HANDLING + ******************************************************************************/ +static inline void uart_irq(uint32_t iir, uint32_t index) { + // [Chapter 14] LPC17xx UART0/2/3: UARTn Interrupt Handling + SerialIrq irq_type; + switch (iir) { + case 1: irq_type = TxIrq; break; + case 2: irq_type = RxIrq; break; + default: return; + } + + if (serial_irq_ids[index] != 0){ + irq_handler(serial_irq_ids[index], irq_type); + } +} + +void uart0_irq() {uart_irq((LPC_UART0->IIR >> 1) & 0x7, 0);} +void uart1_irq() {uart_irq((LPC_UART1->IIR >> 1) & 0x7, 1);} +void uart2_irq() {uart_irq((LPC_UART2->IIR >> 1) & 0x7, 2);} +void uart3_irq() {uart_irq((LPC_UART3->IIR >> 1) & 0x7, 3);} + +void serial_irq_handler(serial_t *obj, uart_irq_handler handler, uint32_t id) { + irq_handler = handler; + serial_irq_ids[obj->index] = id; +} + +void serial_irq_set(serial_t *obj, SerialIrq irq, uint32_t enable) { + IRQn_Type irq_n = (IRQn_Type)0; + uint32_t vector = 0; + switch ((int)obj->uart) { + case UART_0: irq_n=UART0_IRQn; vector = (uint32_t)&uart0_irq; break; + case UART_1: irq_n=UART1_IRQn; vector = (uint32_t)&uart1_irq; break; + case UART_2: irq_n=UART2_IRQn; vector = (uint32_t)&uart2_irq; break; + case UART_3: irq_n=UART3_IRQn; vector = (uint32_t)&uart3_irq; break; + } + + if (enable) { + obj->uart->IER |= 1 << irq; + NVIC_SetVector(irq_n, vector); + NVIC_EnableIRQ(irq_n); + } else { // disable + int all_disabled = 0; + SerialIrq other_irq = (irq == RxIrq) ? (TxIrq) : (RxIrq); + obj->uart->IER &= ~(1 << irq); + all_disabled = (obj->uart->IER & (1 << other_irq)) == 0; + if (all_disabled) + NVIC_DisableIRQ(irq_n); + } +} + +/****************************************************************************** + * READ/WRITE + ******************************************************************************/ +int serial_getc(serial_t *obj) { + while (!serial_readable(obj)); + return obj->uart->RBR; +} + +void serial_putc(serial_t *obj, int c) { + while (!serial_writable(obj)); + obj->uart->THR = c; +} + +int serial_readable(serial_t *obj) { + return obj->uart->LSR & 0x01; +} + +int serial_writable(serial_t *obj) { + return obj->uart->LSR & 0x20; +} + +void serial_clear(serial_t *obj) { + obj->uart->FCR = 1 << 1 // rx FIFO reset + | 1 << 2 // tx FIFO reset + | 0 << 6; // interrupt depth +} + +void serial_pinout_tx(PinName tx) { + pinmap_pinout(tx, PinMap_UART_TX); +} + +void serial_break_set(serial_t *obj) { + obj->uart->LCR |= (1 << 6); +} + +void serial_break_clear(serial_t *obj) { + obj->uart->LCR &= ~(1 << 6); +} + diff --git a/targets/TARGET_NXP/TARGET_LPC2460/spi_api.c b/targets/TARGET_NXP/TARGET_LPC2460/spi_api.c new file mode 100644 index 00000000000..a7de67dfcb1 --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC2460/spi_api.c @@ -0,0 +1,219 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2015 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * 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. + */ +#include "mbed_assert.h" +#include + +#include "spi_api.h" +#include "cmsis.h" +#include "pinmap.h" +#include "mbed_error.h" + +static const PinMap PinMap_SPI_SCLK[] = { + {P0_7 , SPI_1, 2}, + {P0_15, SPI_0, 2}, + {P1_20, SPI_0, 3}, + {P1_31, SPI_1, 2}, + {NC , NC , 0} +}; + +static const PinMap PinMap_SPI_MOSI[] = { + {P0_9 , SPI_1, 2}, + {P0_13, SPI_1, 2}, + {P0_18, SPI_0, 2}, + {P1_24, SPI_0, 3}, + {NC , NC , 0} +}; + +static const PinMap PinMap_SPI_MISO[] = { + {P0_8 , SPI_1, 2}, + {P0_12, SPI_1, 2}, + {P0_17, SPI_0, 2}, + {P1_23, SPI_0, 3}, + {NC , NC , 0} +}; + +static const PinMap PinMap_SPI_SSEL[] = { + {P0_6 , SPI_1, 2}, + {P0_14, SPI_1, 3}, + {P0_16, SPI_0, 2}, + {P1_21, SPI_0, 3}, + {NC , NC , 0} +}; + +static inline int ssp_disable(spi_t *obj); +static inline int ssp_enable(spi_t *obj); + +void spi_init(spi_t *obj, PinName mosi, PinName miso, PinName sclk, PinName ssel) { + // determine the SPI to use + SPIName spi_mosi = (SPIName)pinmap_peripheral(mosi, PinMap_SPI_MOSI); + SPIName spi_miso = (SPIName)pinmap_peripheral(miso, PinMap_SPI_MISO); + SPIName spi_sclk = (SPIName)pinmap_peripheral(sclk, PinMap_SPI_SCLK); + SPIName spi_ssel = (SPIName)pinmap_peripheral(ssel, PinMap_SPI_SSEL); + SPIName spi_data = (SPIName)pinmap_merge(spi_mosi, spi_miso); + SPIName spi_cntl = (SPIName)pinmap_merge(spi_sclk, spi_ssel); + obj->spi = (LPC_SSP_TypeDef*)pinmap_merge(spi_data, spi_cntl); + MBED_ASSERT((int)obj->spi != NC); + + // enable power and clocking + switch ((int)obj->spi) { + case SPI_0: LPC_SC->PCONP |= 1 << PCSSP0; break; + case SPI_1: LPC_SC->PCONP |= 1 << PCSSP1; break; + } + + // set default format and frequency + if (ssel == NC) { + spi_format(obj, 8, 0, 0); // 8 bits, mode 0, master + } else { + spi_format(obj, 8, 0, 1); // 8 bits, mode 0, slave + } + spi_frequency(obj, 1000000); + + // enable the ssp channel + ssp_enable(obj); + + // pin out the spi pins + pinmap_pinout(mosi, PinMap_SPI_MOSI); + pinmap_pinout(miso, PinMap_SPI_MISO); + pinmap_pinout(sclk, PinMap_SPI_SCLK); + if (ssel != NC) { + pinmap_pinout(ssel, PinMap_SPI_SSEL); + } +} + +void spi_free(spi_t *obj) {} + +void spi_format(spi_t *obj, int bits, int mode, int slave) { + MBED_ASSERT(((bits >= 4) && (bits <= 16)) && ((mode >= 0) && (mode <= 3))); + ssp_disable(obj); + + int polarity = (mode & 0x2) ? 1 : 0; + int phase = (mode & 0x1) ? 1 : 0; + + // set it up + int DSS = bits - 1; // DSS (data select size) + int SPO = (polarity) ? 1 : 0; // SPO - clock out polarity + int SPH = (phase) ? 1 : 0; // SPH - clock out phase + + int FRF = 0; // FRF (frame format) = SPI + uint32_t tmp = obj->spi->CR0; + tmp &= ~(0xFFFF); + tmp |= DSS << 0 + | FRF << 4 + | SPO << 6 + | SPH << 7; + obj->spi->CR0 = tmp; + + tmp = obj->spi->CR1; + tmp &= ~(0xD); + tmp |= 0 << 0 // LBM - loop back mode - off + | ((slave) ? 1 : 0) << 2 // MS - master slave mode, 1 = slave + | 0 << 3; // SOD - slave output disable - na + obj->spi->CR1 = tmp; + + ssp_enable(obj); +} + +void spi_frequency(spi_t *obj, int hz) { + ssp_disable(obj); + + // setup the spi clock diveder to /1 + switch ((int)obj->spi) { + case SPI_0: + LPC_SC->PCLKSEL1 &= ~(3 << 10); + LPC_SC->PCLKSEL1 |= (1 << 10); + break; + case SPI_1: + LPC_SC->PCLKSEL0 &= ~(3 << 20); + LPC_SC->PCLKSEL0 |= (1 << 20); + break; + } + + uint32_t PCLK = SystemCoreClock; + + int prescaler; + + for (prescaler = 2; prescaler <= 254; prescaler += 2) { + int prescale_hz = PCLK / prescaler; + + // calculate the divider + int divider = floor(((float)prescale_hz / (float)hz) + 0.5f); + + // check we can support the divider + if (divider < 256) { + // prescaler + obj->spi->CPSR = prescaler; + + // divider + obj->spi->CR0 &= ~(0xFFFF << 8); + obj->spi->CR0 |= (divider - 1) << 8; + ssp_enable(obj); + return; + } + } + error("Couldn't setup requested SPI frequency"); +} + +static inline int ssp_disable(spi_t *obj) { + return obj->spi->CR1 &= ~(1 << 1); +} + +static inline int ssp_enable(spi_t *obj) { + return obj->spi->CR1 |= (1 << 1); +} + +static inline int ssp_readable(spi_t *obj) { + return obj->spi->SR & (1 << 2); +} + +static inline int ssp_writeable(spi_t *obj) { + return obj->spi->SR & (1 << 1); +} + +static inline void ssp_write(spi_t *obj, int value) { + while (!ssp_writeable(obj)); + obj->spi->DR = value; +} + +static inline int ssp_read(spi_t *obj) { + while (!ssp_readable(obj)); + return obj->spi->DR; +} + +static inline int ssp_busy(spi_t *obj) { + return (obj->spi->SR & (1 << 4)) ? (1) : (0); +} + +int spi_master_write(spi_t *obj, int value) { + ssp_write(obj, value); + return ssp_read(obj); +} + +int spi_slave_receive(spi_t *obj) { + return (ssp_readable(obj) && !ssp_busy(obj)) ? (1) : (0); +} + +int spi_slave_read(spi_t *obj) { + return obj->spi->DR; +} + +void spi_slave_write(spi_t *obj, int value) { + while (ssp_writeable(obj) == 0) ; + obj->spi->DR = value; +} + +int spi_busy(spi_t *obj) { + return ssp_busy(obj); +} diff --git a/targets/TARGET_NXP/TARGET_LPC2460/us_ticker.c b/targets/TARGET_NXP/TARGET_LPC2460/us_ticker.c new file mode 100644 index 00000000000..7fdccf35a42 --- /dev/null +++ b/targets/TARGET_NXP/TARGET_LPC2460/us_ticker.c @@ -0,0 +1,64 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2015 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * 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. + */ +#include +#include "us_ticker_api.h" +#include "PeripheralNames.h" + +#define US_TICKER_TIMER ((LPC_TIM_TypeDef *)LPC_TIM3_BASE) +#define US_TICKER_TIMER_IRQn TIMER3_IRQn + +int us_ticker_inited = 0; + +void us_ticker_init(void) { + if (us_ticker_inited) return; + us_ticker_inited = 1; + + LPC_SC->PCONP |= 1 << PCTIM3; // Clock TIMER_3 + + US_TICKER_TIMER->CTCR = 0x0; // timer mode + uint32_t PCLK = SystemCoreClock / 4; + + US_TICKER_TIMER->TCR = 0x2; // reset + + uint32_t prescale = PCLK / 1000000; // default to 1MHz (1 us ticks) + US_TICKER_TIMER->PR = prescale - 1; + US_TICKER_TIMER->TCR = 1; // enable = 1, reset = 0 + + NVIC_SetVector(US_TICKER_TIMER_IRQn, (uint32_t)us_ticker_irq_handler); + NVIC_EnableIRQ(US_TICKER_TIMER_IRQn); +} + +uint32_t us_ticker_read() { + if (!us_ticker_inited) + us_ticker_init(); + + return US_TICKER_TIMER->TC; +} + +void us_ticker_set_interrupt(timestamp_t timestamp) { + // set match value + US_TICKER_TIMER->MR0 = (uint32_t)timestamp; + // enable match interrupt + US_TICKER_TIMER->MCR |= 1; +} + +void us_ticker_disable_interrupt(void) { + US_TICKER_TIMER->MCR &= ~1; +} + +void us_ticker_clear_interrupt(void) { + US_TICKER_TIMER->IR = 1; +} diff --git a/targets/TARGET_NXP/TARGET_LPC43XX/TARGET_LPC4330/PinNames.h b/targets/TARGET_NXP/TARGET_LPC43XX/TARGET_LPC4330/PinNames.h index d2b411dbf27..9a3c5f8382c 100644 --- a/targets/TARGET_NXP/TARGET_LPC43XX/TARGET_LPC4330/PinNames.h +++ b/targets/TARGET_NXP/TARGET_LPC43XX/TARGET_LPC4330/PinNames.h @@ -615,8 +615,6 @@ typedef enum { LED_BLUE = LED4, BTN1 = P2_7, - // Standardized button names - BUTTON1 = BTN1, // Serial pins - UART, SPI, I2C // 210E 210 200E 200 diff --git a/targets/TARGET_NXP/mbed_rtx.h b/targets/TARGET_NXP/mbed_rtx.h index f7f2d97539c..bb28e4684ac 100644 --- a/targets/TARGET_NXP/mbed_rtx.h +++ b/targets/TARGET_NXP/mbed_rtx.h @@ -110,6 +110,41 @@ #define OS_CLOCK 96000000 #endif +#elif defined(TARGET_LPC2368) + +/* FIXME: INITIAL_SP is undefined for this target */ +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 256 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 96000000 +#endif +#ifndef OS_SCHEDULERSTKSIZE +#define OS_SCHEDULERSTKSIZE (136*2) +#endif + +#elif defined(TARGET_LPC2460) + +extern unsigned char __usr_stack_top__[]; +#ifndef INITIAL_SP +#define INITIAL_SP (__usr_stack_top__) +#endif +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 256 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 72000000 +#endif +#ifndef OS_SCHEDULERSTKSIZE +#define OS_SCHEDULERSTKSIZE (136*2) +#endif + #elif defined(TARGET_LPC4088) || defined(TARGET_LPC4088_DM) #ifndef INITIAL_SP diff --git a/targets/TARGET_ONSEMI/TARGET_NCS36510/PinNames.h b/targets/TARGET_ONSEMI/TARGET_NCS36510/PinNames.h index f49368c096d..61305788c75 100644 --- a/targets/TARGET_ONSEMI/TARGET_NCS36510/PinNames.h +++ b/targets/TARGET_ONSEMI/TARGET_NCS36510/PinNames.h @@ -128,14 +128,8 @@ typedef enum { LED_YELLOW = GPIO6, LED_BLUE = GPIO5, USER_BUTTON = GPIO7, /*NEW connection on NCS36510-RF Rev 1.1 - Alias of SW1 */ - SW1 = GPIO7, /*NEW connection on NCS36510-RF Rev 1.1 */ SW2 = GPIO10, /*NEW connection on NCS36510-RF Rev 1.1 */ - - // Standardized button names - BUTTON1 = SW1, - BUTTON2 = SW2, - SERIAL_TX = GPIO0, SERIAL_RX = GPIO1, USBTX = GPIO0, diff --git a/targets/TARGET_ONSEMI/TARGET_NCS36510/device/TOOLCHAIN_ARM/NCS36510.sct b/targets/TARGET_ONSEMI/TARGET_NCS36510/device/TOOLCHAIN_ARM/NCS36510.sct index 56b1e6bf94a..04b039fe115 100644 --- a/targets/TARGET_ONSEMI/TARGET_NCS36510/device/TOOLCHAIN_ARM/NCS36510.sct +++ b/targets/TARGET_ONSEMI/TARGET_NCS36510/device/TOOLCHAIN_ARM/NCS36510.sct @@ -9,7 +9,7 @@ LR_IROM1 0x00003000 0x0004F000 { ; load region size_region ; no uvisor support at this time - RW_IRAM1 0x3FFF4000 + 0x90 { ; 8_byte_aligned(35 vectors * 4 bytes each) = 0x90 + RW_IRAM1 0x3FFF4000 { .ANY(+RW +ZI) } ARM_LIB_HEAP AlignExpr(+0, 8) ALIGN 8 EMPTY (0x3FFF4000 + 0xC000 - AlignExpr(ImageLimit(RW_IRAM1),8) ) {} diff --git a/targets/TARGET_ONSEMI/TARGET_NCS36510/device/TOOLCHAIN_GCC_ARM/NCS36510.ld b/targets/TARGET_ONSEMI/TARGET_NCS36510/device/TOOLCHAIN_GCC_ARM/NCS36510.ld index 1d87e639626..6076d11859d 100644 --- a/targets/TARGET_ONSEMI/TARGET_NCS36510/device/TOOLCHAIN_GCC_ARM/NCS36510.ld +++ b/targets/TARGET_ONSEMI/TARGET_NCS36510/device/TOOLCHAIN_GCC_ARM/NCS36510.ld @@ -5,7 +5,7 @@ MEMORY { VECTORS (rx) : ORIGIN = 0x00003000, LENGTH = 0x00000090 FLASH (rx) : ORIGIN = 0x00003090, LENGTH = 320K - 4K - 0x90 - RAM (rwx) : ORIGIN = 0x3FFF4090, LENGTH = 48K - 0x90 /* 8_byte_aligned(35 vectors * 4 bytes each) = 0x90 */ + RAM (rwx) : ORIGIN = 0x3FFF4000, LENGTH = 48K } /* Linker script to place sections and symbol values. Should be used together diff --git a/targets/TARGET_ONSEMI/TARGET_NCS36510/device/TOOLCHAIN_IAR/NCS36510.icf b/targets/TARGET_ONSEMI/TARGET_NCS36510/device/TOOLCHAIN_IAR/NCS36510.icf index 572cdcd2bec..0c090199972 100644 --- a/targets/TARGET_ONSEMI/TARGET_NCS36510/device/TOOLCHAIN_IAR/NCS36510.icf +++ b/targets/TARGET_ONSEMI/TARGET_NCS36510/device/TOOLCHAIN_IAR/NCS36510.icf @@ -8,14 +8,14 @@ define region FLASHB = Mem:[from 0x00100000 size 0x50000]; define region RAMA = Mem:[from 0x3FFFC000 size 0x4000]; define region RAMB = Mem:[from 0x3FFF8000 size 0x4000]; /* G2H ZPRO requires RAMC to be enabled */ -define region RAMC = Mem:[from 0x3FFF4000 + 0x90 size 0x4000 - 0x90]; /* 8_byte_aligned(35 vectors * 4 bytes each) = 0x90 */ -define region RAM_ALL = Mem:[from 0x3FFF4000 + 0x90 size 0xC000 - 0x90]; /* 8_byte_aligned(35 vectors * 4 bytes each) = 0x90 */ +define region RAMC = Mem:[from 0x3FFF4000 size 0x4000]; +define region RAM_ALL = Mem:[from 0x3FFF4000 size 0xC000]; /* Create a stack */ define block CSTACK with size = 0x200, alignment = 8 { }; /* No Heap is created for C library, all memory management should be handled by the application */ - define block HEAP with alignment = 8, size = 0x3000 { }; + define block HEAP with alignment = 8, size = 0x4000 { }; /* Handle initialization */ do not initialize { section .noinit }; diff --git a/targets/TARGET_ONSEMI/TARGET_NCS36510/device/cmsis_nvic.c b/targets/TARGET_ONSEMI/TARGET_NCS36510/device/cmsis_nvic.c index 76ed0fd68d8..06bbcd6759c 100644 --- a/targets/TARGET_ONSEMI/TARGET_NCS36510/device/cmsis_nvic.c +++ b/targets/TARGET_ONSEMI/TARGET_NCS36510/device/cmsis_nvic.c @@ -31,7 +31,7 @@ #include -#define NVIC_RAM_VECTOR_ADDRESS (0x3FFF4000) // Vectors positioned at start of RAM +#define NVIC_RAM_VECTOR_ADDRESS (0x20000000) // Vectors positioned at start of RAM #define NVIC_FLASH_VECTOR_ADDRESS (0x00000000) // Initial vector position in flash diff --git a/targets/TARGET_RENESAS/TARGET_RZ_A1H/PinNames.h b/targets/TARGET_RENESAS/TARGET_RZ_A1H/PinNames.h index b5e935da081..c002401af44 100644 --- a/targets/TARGET_RENESAS/TARGET_RZ_A1H/PinNames.h +++ b/targets/TARGET_RENESAS/TARGET_RZ_A1H/PinNames.h @@ -87,8 +87,6 @@ typedef enum { I2C_SDA = D14, USER_BUTTON0 = P6_0, - // Standardized button names - BUTTON1 = USER_BUTTON0, // Not connected NC = (int)0xFFFFFFFF diff --git a/targets/TARGET_STM/PeripheralPins.h b/targets/TARGET_STM/PeripheralPins.h index f96b84890ba..3a2c7ecd48a 100644 --- a/targets/TARGET_STM/PeripheralPins.h +++ b/targets/TARGET_STM/PeripheralPins.h @@ -37,7 +37,6 @@ //*** ADC *** #ifdef DEVICE_ANALOGIN extern const PinMap PinMap_ADC[]; -extern const PinMap PinMap_ADC_Internal[]; #endif //*** DAC *** diff --git a/targets/TARGET_STM/TARGET_STM32F0/TARGET_DISCO_F051R8/PinNames.h b/targets/TARGET_STM/TARGET_STM32F0/TARGET_DISCO_F051R8/PinNames.h index c7b5fd67543..1a9ae9dea4c 100644 --- a/targets/TARGET_STM/TARGET_STM32F0/TARGET_DISCO_F051R8/PinNames.h +++ b/targets/TARGET_STM/TARGET_STM32F0/TARGET_DISCO_F051R8/PinNames.h @@ -186,8 +186,6 @@ typedef enum { LED3 = PC_9, LED4 = PC_8, USER_BUTTON = PA_0, - // Standardized button names - BUTTON1 = USER_BUTTON, SERIAL_TX = PA_2, SERIAL_RX = PA_3, USBTX = PA_2, diff --git a/targets/TARGET_STM/TARGET_STM32F0/TARGET_NUCLEO_F030R8/PinNames.h b/targets/TARGET_STM/TARGET_STM32F0/TARGET_NUCLEO_F030R8/PinNames.h index 68256c2a4dd..da752d856f1 100644 --- a/targets/TARGET_STM/TARGET_STM32F0/TARGET_NUCLEO_F030R8/PinNames.h +++ b/targets/TARGET_STM/TARGET_STM32F0/TARGET_NUCLEO_F030R8/PinNames.h @@ -133,8 +133,6 @@ typedef enum { LED3 = PA_5, LED4 = PA_5, USER_BUTTON = PC_13, - // Standardized button names - BUTTON1 = USER_BUTTON, SERIAL_TX = PA_2, SERIAL_RX = PA_3, USBTX = PA_2, diff --git a/targets/TARGET_STM/TARGET_STM32F0/TARGET_NUCLEO_F070RB/PinNames.h b/targets/TARGET_STM/TARGET_STM32F0/TARGET_NUCLEO_F070RB/PinNames.h index 8aec3bd620b..5ae174aca26 100644 --- a/targets/TARGET_STM/TARGET_STM32F0/TARGET_NUCLEO_F070RB/PinNames.h +++ b/targets/TARGET_STM/TARGET_STM32F0/TARGET_NUCLEO_F070RB/PinNames.h @@ -129,8 +129,6 @@ typedef enum { LED3 = PA_5, LED4 = PA_5, USER_BUTTON = PC_13, - // Standardized button names - BUTTON1 = USER_BUTTON, SERIAL_TX = PA_2, SERIAL_RX = PA_3, USBTX = PA_2, diff --git a/targets/TARGET_STM/TARGET_STM32F0/TARGET_NUCLEO_F072RB/PinNames.h b/targets/TARGET_STM/TARGET_STM32F0/TARGET_NUCLEO_F072RB/PinNames.h index 8aec3bd620b..5ae174aca26 100644 --- a/targets/TARGET_STM/TARGET_STM32F0/TARGET_NUCLEO_F072RB/PinNames.h +++ b/targets/TARGET_STM/TARGET_STM32F0/TARGET_NUCLEO_F072RB/PinNames.h @@ -129,8 +129,6 @@ typedef enum { LED3 = PA_5, LED4 = PA_5, USER_BUTTON = PC_13, - // Standardized button names - BUTTON1 = USER_BUTTON, SERIAL_TX = PA_2, SERIAL_RX = PA_3, USBTX = PA_2, diff --git a/targets/TARGET_STM/TARGET_STM32F0/TARGET_NUCLEO_F091RC/PinNames.h b/targets/TARGET_STM/TARGET_STM32F0/TARGET_NUCLEO_F091RC/PinNames.h index 3c33d81d857..c33e9d2a147 100644 --- a/targets/TARGET_STM/TARGET_STM32F0/TARGET_NUCLEO_F091RC/PinNames.h +++ b/targets/TARGET_STM/TARGET_STM32F0/TARGET_NUCLEO_F091RC/PinNames.h @@ -130,8 +130,6 @@ typedef enum { LED3 = PA_5, LED4 = PA_5, USER_BUTTON = PC_13, - // Standardized button names - BUTTON1 = USER_BUTTON, SERIAL_TX = PA_2, SERIAL_RX = PA_3, USBTX = PA_2, diff --git a/targets/TARGET_STM/TARGET_STM32F0/analogout_api.c b/targets/TARGET_STM/TARGET_STM32F0/analogout_api.c index f9f907b9f2f..25319b3fef8 100644 --- a/targets/TARGET_STM/TARGET_STM32F0/analogout_api.c +++ b/targets/TARGET_STM/TARGET_STM32F0/analogout_api.c @@ -59,7 +59,7 @@ void analogout_init(dac_t *obj, PinName pin) { obj->pin = pin; // Enable DAC clock - __HAL_RCC_DAC1_CLK_ENABLE(); + __DAC1_CLK_ENABLE(); // Configure DAC DacHandle.Instance = (DAC_TypeDef *)(obj->dac); @@ -78,9 +78,9 @@ void analogout_init(dac_t *obj, PinName pin) { void analogout_free(dac_t *obj) { // Reset DAC and disable clock - __HAL_RCC_DAC1_FORCE_RESET(); - __HAL_RCC_DAC1_RELEASE_RESET(); - __HAL_RCC_DAC1_CLK_DISABLE(); + __DAC1_FORCE_RESET(); + __DAC1_RELEASE_RESET(); + __DAC1_CLK_DISABLE(); // Configure GPIO pin_function(obj->pin, STM_PIN_DATA(STM_MODE_INPUT, GPIO_NOPULL, 0)); diff --git a/targets/TARGET_STM/TARGET_STM32F0/device/stm32f0xx_hal_def.h b/targets/TARGET_STM/TARGET_STM32F0/device/stm32f0xx_hal_def.h index be1eabc4878..a81826b9614 100644 --- a/targets/TARGET_STM/TARGET_STM32F0/device/stm32f0xx_hal_def.h +++ b/targets/TARGET_STM/TARGET_STM32F0/device/stm32f0xx_hal_def.h @@ -124,7 +124,7 @@ typedef enum }while (0) #endif /* USE_RTOS */ -#if defined ( __GNUC__ ) && !defined ( __CC_ARM ) +#if defined ( __GNUC__ ) #ifndef __weak #define __weak __attribute__((weak)) #endif /* __weak */ diff --git a/targets/TARGET_STM/TARGET_STM32F1/TARGET_BLUEPILL_F103C8/device/hal_tick.h b/targets/TARGET_STM/TARGET_STM32F1/TARGET_BLUEPILL_F103C8/device/hal_tick.h index 5872d57f7ae..608a14ff991 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/TARGET_BLUEPILL_F103C8/device/hal_tick.h +++ b/targets/TARGET_STM/TARGET_STM32F1/TARGET_BLUEPILL_F103C8/device/hal_tick.h @@ -44,10 +44,10 @@ #define TIM_MST TIM4 #define TIM_MST_IRQ TIM4_IRQn -#define TIM_MST_RCC __HAL_RCC_TIM4_CLK_ENABLE() +#define TIM_MST_RCC __TIM4_CLK_ENABLE() -#define TIM_MST_RESET_ON __HAL_RCC_TIM4_FORCE_RESET() -#define TIM_MST_RESET_OFF __HAL_RCC_TIM4_RELEASE_RESET() +#define TIM_MST_RESET_ON __TIM4_FORCE_RESET() +#define TIM_MST_RESET_OFF __TIM4_RELEASE_RESET() #define TIM_MST_16BIT 1 // 1=16-bit timer, 0=32-bit timer diff --git a/targets/TARGET_STM/TARGET_STM32F1/TARGET_BLUEPILL_F103C8/device/stm32f103xb.h b/targets/TARGET_STM/TARGET_STM32F1/TARGET_BLUEPILL_F103C8/device/stm32f103xb.h index 9ff8ad63859..140567a9a2a 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/TARGET_BLUEPILL_F103C8/device/stm32f103xb.h +++ b/targets/TARGET_STM/TARGET_STM32F1/TARGET_BLUEPILL_F103C8/device/stm32f103xb.h @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f103xb.h * @author MCD Application Team - * @version V4.2.0 - * @date 31-March-2017 + * @version V4.1.0 + * @date 29-April-2016 * @brief CMSIS Cortex-M3 Device Peripheral Access Layer Header File. * This file contains all the peripheral register's definitions, bits * definitions and memory mapping for STM32F1xx devices. @@ -16,7 +16,7 @@ ****************************************************************************** * @attention * - *

© COPYRIGHT(c) 2017 STMicroelectronics

+ *

© COPYRIGHT(c) 2016 STMicroelectronics

* * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: @@ -65,10 +65,10 @@ /** * @brief Configuration of the Cortex-M3 Processor and Core Peripherals */ -#define __CM3_REV 0x0200U /*!< Core Revision r2p0 */ - #define __MPU_PRESENT 0U /*!< Other STM32 devices does not provide an MPU */ -#define __NVIC_PRIO_BITS 4U /*!< STM32 uses 4 Bits for the Priority Levels */ -#define __Vendor_SysTickConfig 0U /*!< Set to 1 if different SysTick Config is used */ + #define __MPU_PRESENT 0 /*!< Other STM32 devices does not provide an MPU */ +#define __CM3_REV 0x0200 /*!< Core Revision r2p0 */ +#define __NVIC_PRIO_BITS 4 /*!< STM32 uses 4 Bits for the Priority Levels */ +#define __Vendor_SysTickConfig 0 /*!< Set to 1 if different SysTick Config is used */ /** * @} @@ -143,6 +143,7 @@ typedef enum USBWakeUp_IRQn = 42, /*!< USB Device WakeUp from suspend through EXTI Line Interrupt */ } IRQn_Type; + /** * @} */ @@ -616,72 +617,72 @@ typedef struct */ -#define FLASH_BASE 0x08000000U /*!< FLASH base address in the alias region */ -#define FLASH_BANK1_END 0x0801FFFFU /*!< FLASH END address of bank1 */ -#define SRAM_BASE 0x20000000U /*!< SRAM base address in the alias region */ -#define PERIPH_BASE 0x40000000U /*!< Peripheral base address in the alias region */ +#define FLASH_BASE ((uint32_t)0x08000000) /*!< FLASH base address in the alias region */ +#define FLASH_BANK1_END ((uint32_t)0x0801FFFF) /*!< FLASH END address of bank1 */ +#define SRAM_BASE ((uint32_t)0x20000000) /*!< SRAM base address in the alias region */ +#define PERIPH_BASE ((uint32_t)0x40000000) /*!< Peripheral base address in the alias region */ -#define SRAM_BB_BASE 0x22000000U /*!< SRAM base address in the bit-band region */ -#define PERIPH_BB_BASE 0x42000000U /*!< Peripheral base address in the bit-band region */ +#define SRAM_BB_BASE ((uint32_t)0x22000000) /*!< SRAM base address in the bit-band region */ +#define PERIPH_BB_BASE ((uint32_t)0x42000000) /*!< Peripheral base address in the bit-band region */ /*!< Peripheral memory map */ #define APB1PERIPH_BASE PERIPH_BASE -#define APB2PERIPH_BASE (PERIPH_BASE + 0x00010000U) -#define AHBPERIPH_BASE (PERIPH_BASE + 0x00020000U) - -#define TIM2_BASE (APB1PERIPH_BASE + 0x00000000U) -#define TIM3_BASE (APB1PERIPH_BASE + 0x00000400U) -#define TIM4_BASE (APB1PERIPH_BASE + 0x00000800U) -#define RTC_BASE (APB1PERIPH_BASE + 0x00002800U) -#define WWDG_BASE (APB1PERIPH_BASE + 0x00002C00U) -#define IWDG_BASE (APB1PERIPH_BASE + 0x00003000U) -#define SPI2_BASE (APB1PERIPH_BASE + 0x00003800U) -#define USART2_BASE (APB1PERIPH_BASE + 0x00004400U) -#define USART3_BASE (APB1PERIPH_BASE + 0x00004800U) -#define I2C1_BASE (APB1PERIPH_BASE + 0x00005400U) +#define APB2PERIPH_BASE (PERIPH_BASE + 0x10000) +#define AHBPERIPH_BASE (PERIPH_BASE + 0x20000) + +#define TIM2_BASE (APB1PERIPH_BASE + 0x0000) +#define TIM3_BASE (APB1PERIPH_BASE + 0x0400) +#define TIM4_BASE (APB1PERIPH_BASE + 0x0800) +#define RTC_BASE (APB1PERIPH_BASE + 0x2800) +#define WWDG_BASE (APB1PERIPH_BASE + 0x2C00) +#define IWDG_BASE (APB1PERIPH_BASE + 0x3000) +#define SPI2_BASE (APB1PERIPH_BASE + 0x3800) +#define USART2_BASE (APB1PERIPH_BASE + 0x4400) +#define USART3_BASE (APB1PERIPH_BASE + 0x4800) +#define I2C1_BASE (APB1PERIPH_BASE + 0x5400) #define I2C2_BASE (APB1PERIPH_BASE + 0x5800) -#define CAN1_BASE (APB1PERIPH_BASE + 0x00006400U) -#define BKP_BASE (APB1PERIPH_BASE + 0x00006C00U) -#define PWR_BASE (APB1PERIPH_BASE + 0x00007000U) -#define AFIO_BASE (APB2PERIPH_BASE + 0x00000000U) -#define EXTI_BASE (APB2PERIPH_BASE + 0x00000400U) -#define GPIOA_BASE (APB2PERIPH_BASE + 0x00000800U) -#define GPIOB_BASE (APB2PERIPH_BASE + 0x00000C00U) -#define GPIOC_BASE (APB2PERIPH_BASE + 0x00001000U) -#define GPIOD_BASE (APB2PERIPH_BASE + 0x00001400U) -#define GPIOE_BASE (APB2PERIPH_BASE + 0x00001800U) -#define ADC1_BASE (APB2PERIPH_BASE + 0x00002400U) -#define ADC2_BASE (APB2PERIPH_BASE + 0x00002800U) -#define TIM1_BASE (APB2PERIPH_BASE + 0x00002C00U) -#define SPI1_BASE (APB2PERIPH_BASE + 0x00003000U) -#define USART1_BASE (APB2PERIPH_BASE + 0x00003800U) - -#define SDIO_BASE (PERIPH_BASE + 0x00018000U) - -#define DMA1_BASE (AHBPERIPH_BASE + 0x00000000U) -#define DMA1_Channel1_BASE (AHBPERIPH_BASE + 0x00000008U) -#define DMA1_Channel2_BASE (AHBPERIPH_BASE + 0x0000001CU) -#define DMA1_Channel3_BASE (AHBPERIPH_BASE + 0x00000030U) -#define DMA1_Channel4_BASE (AHBPERIPH_BASE + 0x00000044U) -#define DMA1_Channel5_BASE (AHBPERIPH_BASE + 0x00000058U) -#define DMA1_Channel6_BASE (AHBPERIPH_BASE + 0x0000006CU) -#define DMA1_Channel7_BASE (AHBPERIPH_BASE + 0x00000080U) -#define RCC_BASE (AHBPERIPH_BASE + 0x00001000U) -#define CRC_BASE (AHBPERIPH_BASE + 0x00003000U) - -#define FLASH_R_BASE (AHBPERIPH_BASE + 0x00002000U) /*!< Flash registers base address */ -#define FLASHSIZE_BASE 0x1FFFF7E0U /*!< FLASH Size register base address */ -#define UID_BASE 0x1FFFF7E8U /*!< Unique device ID register base address */ -#define OB_BASE 0x1FFFF800U /*!< Flash Option Bytes base address */ - - - -#define DBGMCU_BASE 0xE0042000U /*!< Debug MCU registers base address */ +#define CAN1_BASE (APB1PERIPH_BASE + 0x6400) +#define BKP_BASE (APB1PERIPH_BASE + 0x6C00) +#define PWR_BASE (APB1PERIPH_BASE + 0x7000) +#define AFIO_BASE (APB2PERIPH_BASE + 0x0000) +#define EXTI_BASE (APB2PERIPH_BASE + 0x0400) +#define GPIOA_BASE (APB2PERIPH_BASE + 0x0800) +#define GPIOB_BASE (APB2PERIPH_BASE + 0x0C00) +#define GPIOC_BASE (APB2PERIPH_BASE + 0x1000) +#define GPIOD_BASE (APB2PERIPH_BASE + 0x1400) +#define GPIOE_BASE (APB2PERIPH_BASE + 0x1800) +#define ADC1_BASE (APB2PERIPH_BASE + 0x2400) +#define ADC2_BASE (APB2PERIPH_BASE + 0x2800) +#define TIM1_BASE (APB2PERIPH_BASE + 0x2C00) +#define SPI1_BASE (APB2PERIPH_BASE + 0x3000) +#define USART1_BASE (APB2PERIPH_BASE + 0x3800) + +#define SDIO_BASE (PERIPH_BASE + 0x18000) + +#define DMA1_BASE (AHBPERIPH_BASE + 0x0000) +#define DMA1_Channel1_BASE (AHBPERIPH_BASE + 0x0008) +#define DMA1_Channel2_BASE (AHBPERIPH_BASE + 0x001C) +#define DMA1_Channel3_BASE (AHBPERIPH_BASE + 0x0030) +#define DMA1_Channel4_BASE (AHBPERIPH_BASE + 0x0044) +#define DMA1_Channel5_BASE (AHBPERIPH_BASE + 0x0058) +#define DMA1_Channel6_BASE (AHBPERIPH_BASE + 0x006C) +#define DMA1_Channel7_BASE (AHBPERIPH_BASE + 0x0080) +#define RCC_BASE (AHBPERIPH_BASE + 0x1000) +#define CRC_BASE (AHBPERIPH_BASE + 0x3000) + +#define FLASH_R_BASE (AHBPERIPH_BASE + 0x2000) /*!< Flash registers base address */ +#define FLASHSIZE_BASE ((uint32_t)0x1FFFF7E0) /*!< FLASH Size register base address */ +#define UID_BASE ((uint32_t)0x1FFFF7E8) /*!< Unique device ID register base address */ +#define OB_BASE ((uint32_t)0x1FFFF800) /*!< Flash Option Bytes base address */ + + + +#define DBGMCU_BASE ((uint32_t)0xE0042000) /*!< Debug MCU registers base address */ /* USB device FS */ -#define USB_BASE (APB1PERIPH_BASE + 0x00005C00U) /*!< USB_IP Peripheral Registers base address */ -#define USB_PMAADDR (APB1PERIPH_BASE + 0x00006000U) /*!< USB_IP Packet Memory Area base address */ +#define USB_BASE (APB1PERIPH_BASE + 0x00005C00) /*!< USB_IP Peripheral Registers base address */ +#define USB_PMAADDR (APB1PERIPH_BASE + 0x00006000) /*!< USB_IP Packet Memory Area base address */ /** @@ -692,48 +693,48 @@ typedef struct * @{ */ -#define TIM2 ((TIM_TypeDef *)TIM2_BASE) -#define TIM3 ((TIM_TypeDef *)TIM3_BASE) -#define TIM4 ((TIM_TypeDef *)TIM4_BASE) -#define RTC ((RTC_TypeDef *)RTC_BASE) -#define WWDG ((WWDG_TypeDef *)WWDG_BASE) -#define IWDG ((IWDG_TypeDef *)IWDG_BASE) -#define SPI2 ((SPI_TypeDef *)SPI2_BASE) -#define USART2 ((USART_TypeDef *)USART2_BASE) -#define USART3 ((USART_TypeDef *)USART3_BASE) -#define I2C1 ((I2C_TypeDef *)I2C1_BASE) -#define I2C2 ((I2C_TypeDef *)I2C2_BASE) -#define USB ((USB_TypeDef *)USB_BASE) -#define CAN1 ((CAN_TypeDef *)CAN1_BASE) -#define BKP ((BKP_TypeDef *)BKP_BASE) -#define PWR ((PWR_TypeDef *)PWR_BASE) -#define AFIO ((AFIO_TypeDef *)AFIO_BASE) -#define EXTI ((EXTI_TypeDef *)EXTI_BASE) -#define GPIOA ((GPIO_TypeDef *)GPIOA_BASE) -#define GPIOB ((GPIO_TypeDef *)GPIOB_BASE) -#define GPIOC ((GPIO_TypeDef *)GPIOC_BASE) -#define GPIOD ((GPIO_TypeDef *)GPIOD_BASE) -#define GPIOE ((GPIO_TypeDef *)GPIOE_BASE) -#define ADC1 ((ADC_TypeDef *)ADC1_BASE) -#define ADC2 ((ADC_TypeDef *)ADC2_BASE) -#define ADC12_COMMON ((ADC_Common_TypeDef *)ADC1_BASE) -#define TIM1 ((TIM_TypeDef *)TIM1_BASE) -#define SPI1 ((SPI_TypeDef *)SPI1_BASE) -#define USART1 ((USART_TypeDef *)USART1_BASE) -#define SDIO ((SDIO_TypeDef *)SDIO_BASE) -#define DMA1 ((DMA_TypeDef *)DMA1_BASE) -#define DMA1_Channel1 ((DMA_Channel_TypeDef *)DMA1_Channel1_BASE) -#define DMA1_Channel2 ((DMA_Channel_TypeDef *)DMA1_Channel2_BASE) -#define DMA1_Channel3 ((DMA_Channel_TypeDef *)DMA1_Channel3_BASE) -#define DMA1_Channel4 ((DMA_Channel_TypeDef *)DMA1_Channel4_BASE) -#define DMA1_Channel5 ((DMA_Channel_TypeDef *)DMA1_Channel5_BASE) -#define DMA1_Channel6 ((DMA_Channel_TypeDef *)DMA1_Channel6_BASE) -#define DMA1_Channel7 ((DMA_Channel_TypeDef *)DMA1_Channel7_BASE) -#define RCC ((RCC_TypeDef *)RCC_BASE) -#define CRC ((CRC_TypeDef *)CRC_BASE) -#define FLASH ((FLASH_TypeDef *)FLASH_R_BASE) -#define OB ((OB_TypeDef *)OB_BASE) -#define DBGMCU ((DBGMCU_TypeDef *)DBGMCU_BASE) +#define TIM2 ((TIM_TypeDef *) TIM2_BASE) +#define TIM3 ((TIM_TypeDef *) TIM3_BASE) +#define TIM4 ((TIM_TypeDef *) TIM4_BASE) +#define RTC ((RTC_TypeDef *) RTC_BASE) +#define WWDG ((WWDG_TypeDef *) WWDG_BASE) +#define IWDG ((IWDG_TypeDef *) IWDG_BASE) +#define SPI2 ((SPI_TypeDef *) SPI2_BASE) +#define USART2 ((USART_TypeDef *) USART2_BASE) +#define USART3 ((USART_TypeDef *) USART3_BASE) +#define I2C1 ((I2C_TypeDef *) I2C1_BASE) +#define I2C2 ((I2C_TypeDef *) I2C2_BASE) +#define USB ((USB_TypeDef *) USB_BASE) +#define CAN1 ((CAN_TypeDef *) CAN1_BASE) +#define BKP ((BKP_TypeDef *) BKP_BASE) +#define PWR ((PWR_TypeDef *) PWR_BASE) +#define AFIO ((AFIO_TypeDef *) AFIO_BASE) +#define EXTI ((EXTI_TypeDef *) EXTI_BASE) +#define GPIOA ((GPIO_TypeDef *) GPIOA_BASE) +#define GPIOB ((GPIO_TypeDef *) GPIOB_BASE) +#define GPIOC ((GPIO_TypeDef *) GPIOC_BASE) +#define GPIOD ((GPIO_TypeDef *) GPIOD_BASE) +#define GPIOE ((GPIO_TypeDef *) GPIOE_BASE) +#define ADC1 ((ADC_TypeDef *) ADC1_BASE) +#define ADC2 ((ADC_TypeDef *) ADC2_BASE) +#define ADC12_COMMON ((ADC_Common_TypeDef *) ADC1_BASE) +#define TIM1 ((TIM_TypeDef *) TIM1_BASE) +#define SPI1 ((SPI_TypeDef *) SPI1_BASE) +#define USART1 ((USART_TypeDef *) USART1_BASE) +#define SDIO ((SDIO_TypeDef *) SDIO_BASE) +#define DMA1 ((DMA_TypeDef *) DMA1_BASE) +#define DMA1_Channel1 ((DMA_Channel_TypeDef *) DMA1_Channel1_BASE) +#define DMA1_Channel2 ((DMA_Channel_TypeDef *) DMA1_Channel2_BASE) +#define DMA1_Channel3 ((DMA_Channel_TypeDef *) DMA1_Channel3_BASE) +#define DMA1_Channel4 ((DMA_Channel_TypeDef *) DMA1_Channel4_BASE) +#define DMA1_Channel5 ((DMA_Channel_TypeDef *) DMA1_Channel5_BASE) +#define DMA1_Channel6 ((DMA_Channel_TypeDef *) DMA1_Channel6_BASE) +#define DMA1_Channel7 ((DMA_Channel_TypeDef *) DMA1_Channel7_BASE) +#define RCC ((RCC_TypeDef *) RCC_BASE) +#define CRC ((CRC_TypeDef *) CRC_BASE) +#define FLASH ((FLASH_TypeDef *) FLASH_R_BASE) +#define OB ((OB_TypeDef *) OB_BASE) +#define DBGMCU ((DBGMCU_TypeDef *) DBGMCU_BASE) /** @@ -804,24 +805,14 @@ typedef struct #define PWR_CR_PLS_2 (0x4U << PWR_CR_PLS_Pos) /*!< 0x00000080 */ /*!< PVD level configuration */ -#define PWR_CR_PLS_LEV0 0x00000000U /*!< PVD level 2.2V */ -#define PWR_CR_PLS_LEV1 0x00000020U /*!< PVD level 2.3V */ -#define PWR_CR_PLS_LEV2 0x00000040U /*!< PVD level 2.4V */ -#define PWR_CR_PLS_LEV3 0x00000060U /*!< PVD level 2.5V */ -#define PWR_CR_PLS_LEV4 0x00000080U /*!< PVD level 2.6V */ -#define PWR_CR_PLS_LEV5 0x000000A0U /*!< PVD level 2.7V */ -#define PWR_CR_PLS_LEV6 0x000000C0U /*!< PVD level 2.8V */ -#define PWR_CR_PLS_LEV7 0x000000E0U /*!< PVD level 2.9V */ - -/* Legacy defines */ -#define PWR_CR_PLS_2V2 PWR_CR_PLS_LEV0 -#define PWR_CR_PLS_2V3 PWR_CR_PLS_LEV1 -#define PWR_CR_PLS_2V4 PWR_CR_PLS_LEV2 -#define PWR_CR_PLS_2V5 PWR_CR_PLS_LEV3 -#define PWR_CR_PLS_2V6 PWR_CR_PLS_LEV4 -#define PWR_CR_PLS_2V7 PWR_CR_PLS_LEV5 -#define PWR_CR_PLS_2V8 PWR_CR_PLS_LEV6 -#define PWR_CR_PLS_2V9 PWR_CR_PLS_LEV7 +#define PWR_CR_PLS_2V2 ((uint32_t)0x00000000) /*!< PVD level 2.2V */ +#define PWR_CR_PLS_2V3 ((uint32_t)0x00000020) /*!< PVD level 2.3V */ +#define PWR_CR_PLS_2V4 ((uint32_t)0x00000040) /*!< PVD level 2.4V */ +#define PWR_CR_PLS_2V5 ((uint32_t)0x00000060) /*!< PVD level 2.5V */ +#define PWR_CR_PLS_2V6 ((uint32_t)0x00000080) /*!< PVD level 2.6V */ +#define PWR_CR_PLS_2V7 ((uint32_t)0x000000A0) /*!< PVD level 2.7V */ +#define PWR_CR_PLS_2V8 ((uint32_t)0x000000C0) /*!< PVD level 2.8V */ +#define PWR_CR_PLS_2V9 ((uint32_t)0x000000E0) /*!< PVD level 2.9V */ #define PWR_CR_DBP_Pos (8U) #define PWR_CR_DBP_Msk (0x1U << PWR_CR_DBP_Pos) /*!< 0x00000100 */ @@ -986,9 +977,9 @@ typedef struct #define RCC_CFGR_SW_0 (0x1U << RCC_CFGR_SW_Pos) /*!< 0x00000001 */ #define RCC_CFGR_SW_1 (0x2U << RCC_CFGR_SW_Pos) /*!< 0x00000002 */ -#define RCC_CFGR_SW_HSI 0x00000000U /*!< HSI selected as system clock */ -#define RCC_CFGR_SW_HSE 0x00000001U /*!< HSE selected as system clock */ -#define RCC_CFGR_SW_PLL 0x00000002U /*!< PLL selected as system clock */ +#define RCC_CFGR_SW_HSI ((uint32_t)0x00000000) /*!< HSI selected as system clock */ +#define RCC_CFGR_SW_HSE ((uint32_t)0x00000001) /*!< HSE selected as system clock */ +#define RCC_CFGR_SW_PLL ((uint32_t)0x00000002) /*!< PLL selected as system clock */ /*!< SWS configuration */ #define RCC_CFGR_SWS_Pos (2U) @@ -997,9 +988,9 @@ typedef struct #define RCC_CFGR_SWS_0 (0x1U << RCC_CFGR_SWS_Pos) /*!< 0x00000004 */ #define RCC_CFGR_SWS_1 (0x2U << RCC_CFGR_SWS_Pos) /*!< 0x00000008 */ -#define RCC_CFGR_SWS_HSI 0x00000000U /*!< HSI oscillator used as system clock */ -#define RCC_CFGR_SWS_HSE 0x00000004U /*!< HSE oscillator used as system clock */ -#define RCC_CFGR_SWS_PLL 0x00000008U /*!< PLL used as system clock */ +#define RCC_CFGR_SWS_HSI ((uint32_t)0x00000000) /*!< HSI oscillator used as system clock */ +#define RCC_CFGR_SWS_HSE ((uint32_t)0x00000004) /*!< HSE oscillator used as system clock */ +#define RCC_CFGR_SWS_PLL ((uint32_t)0x00000008) /*!< PLL used as system clock */ /*!< HPRE configuration */ #define RCC_CFGR_HPRE_Pos (4U) @@ -1010,15 +1001,15 @@ typedef struct #define RCC_CFGR_HPRE_2 (0x4U << RCC_CFGR_HPRE_Pos) /*!< 0x00000040 */ #define RCC_CFGR_HPRE_3 (0x8U << RCC_CFGR_HPRE_Pos) /*!< 0x00000080 */ -#define RCC_CFGR_HPRE_DIV1 0x00000000U /*!< SYSCLK not divided */ -#define RCC_CFGR_HPRE_DIV2 0x00000080U /*!< SYSCLK divided by 2 */ -#define RCC_CFGR_HPRE_DIV4 0x00000090U /*!< SYSCLK divided by 4 */ -#define RCC_CFGR_HPRE_DIV8 0x000000A0U /*!< SYSCLK divided by 8 */ -#define RCC_CFGR_HPRE_DIV16 0x000000B0U /*!< SYSCLK divided by 16 */ -#define RCC_CFGR_HPRE_DIV64 0x000000C0U /*!< SYSCLK divided by 64 */ -#define RCC_CFGR_HPRE_DIV128 0x000000D0U /*!< SYSCLK divided by 128 */ -#define RCC_CFGR_HPRE_DIV256 0x000000E0U /*!< SYSCLK divided by 256 */ -#define RCC_CFGR_HPRE_DIV512 0x000000F0U /*!< SYSCLK divided by 512 */ +#define RCC_CFGR_HPRE_DIV1 ((uint32_t)0x00000000) /*!< SYSCLK not divided */ +#define RCC_CFGR_HPRE_DIV2 ((uint32_t)0x00000080) /*!< SYSCLK divided by 2 */ +#define RCC_CFGR_HPRE_DIV4 ((uint32_t)0x00000090) /*!< SYSCLK divided by 4 */ +#define RCC_CFGR_HPRE_DIV8 ((uint32_t)0x000000A0) /*!< SYSCLK divided by 8 */ +#define RCC_CFGR_HPRE_DIV16 ((uint32_t)0x000000B0) /*!< SYSCLK divided by 16 */ +#define RCC_CFGR_HPRE_DIV64 ((uint32_t)0x000000C0) /*!< SYSCLK divided by 64 */ +#define RCC_CFGR_HPRE_DIV128 ((uint32_t)0x000000D0) /*!< SYSCLK divided by 128 */ +#define RCC_CFGR_HPRE_DIV256 ((uint32_t)0x000000E0) /*!< SYSCLK divided by 256 */ +#define RCC_CFGR_HPRE_DIV512 ((uint32_t)0x000000F0) /*!< SYSCLK divided by 512 */ /*!< PPRE1 configuration */ #define RCC_CFGR_PPRE1_Pos (8U) @@ -1028,11 +1019,11 @@ typedef struct #define RCC_CFGR_PPRE1_1 (0x2U << RCC_CFGR_PPRE1_Pos) /*!< 0x00000200 */ #define RCC_CFGR_PPRE1_2 (0x4U << RCC_CFGR_PPRE1_Pos) /*!< 0x00000400 */ -#define RCC_CFGR_PPRE1_DIV1 0x00000000U /*!< HCLK not divided */ -#define RCC_CFGR_PPRE1_DIV2 0x00000400U /*!< HCLK divided by 2 */ -#define RCC_CFGR_PPRE1_DIV4 0x00000500U /*!< HCLK divided by 4 */ -#define RCC_CFGR_PPRE1_DIV8 0x00000600U /*!< HCLK divided by 8 */ -#define RCC_CFGR_PPRE1_DIV16 0x00000700U /*!< HCLK divided by 16 */ +#define RCC_CFGR_PPRE1_DIV1 ((uint32_t)0x00000000) /*!< HCLK not divided */ +#define RCC_CFGR_PPRE1_DIV2 ((uint32_t)0x00000400) /*!< HCLK divided by 2 */ +#define RCC_CFGR_PPRE1_DIV4 ((uint32_t)0x00000500) /*!< HCLK divided by 4 */ +#define RCC_CFGR_PPRE1_DIV8 ((uint32_t)0x00000600) /*!< HCLK divided by 8 */ +#define RCC_CFGR_PPRE1_DIV16 ((uint32_t)0x00000700) /*!< HCLK divided by 16 */ /*!< PPRE2 configuration */ #define RCC_CFGR_PPRE2_Pos (11U) @@ -1042,11 +1033,11 @@ typedef struct #define RCC_CFGR_PPRE2_1 (0x2U << RCC_CFGR_PPRE2_Pos) /*!< 0x00001000 */ #define RCC_CFGR_PPRE2_2 (0x4U << RCC_CFGR_PPRE2_Pos) /*!< 0x00002000 */ -#define RCC_CFGR_PPRE2_DIV1 0x00000000U /*!< HCLK not divided */ -#define RCC_CFGR_PPRE2_DIV2 0x00002000U /*!< HCLK divided by 2 */ -#define RCC_CFGR_PPRE2_DIV4 0x00002800U /*!< HCLK divided by 4 */ -#define RCC_CFGR_PPRE2_DIV8 0x00003000U /*!< HCLK divided by 8 */ -#define RCC_CFGR_PPRE2_DIV16 0x00003800U /*!< HCLK divided by 16 */ +#define RCC_CFGR_PPRE2_DIV1 ((uint32_t)0x00000000) /*!< HCLK not divided */ +#define RCC_CFGR_PPRE2_DIV2 ((uint32_t)0x00002000) /*!< HCLK divided by 2 */ +#define RCC_CFGR_PPRE2_DIV4 ((uint32_t)0x00002800) /*!< HCLK divided by 4 */ +#define RCC_CFGR_PPRE2_DIV8 ((uint32_t)0x00003000) /*!< HCLK divided by 8 */ +#define RCC_CFGR_PPRE2_DIV16 ((uint32_t)0x00003800) /*!< HCLK divided by 16 */ /*!< ADCPPRE configuration */ #define RCC_CFGR_ADCPRE_Pos (14U) @@ -1055,10 +1046,10 @@ typedef struct #define RCC_CFGR_ADCPRE_0 (0x1U << RCC_CFGR_ADCPRE_Pos) /*!< 0x00004000 */ #define RCC_CFGR_ADCPRE_1 (0x2U << RCC_CFGR_ADCPRE_Pos) /*!< 0x00008000 */ -#define RCC_CFGR_ADCPRE_DIV2 0x00000000U /*!< PCLK2 divided by 2 */ -#define RCC_CFGR_ADCPRE_DIV4 0x00004000U /*!< PCLK2 divided by 4 */ -#define RCC_CFGR_ADCPRE_DIV6 0x00008000U /*!< PCLK2 divided by 6 */ -#define RCC_CFGR_ADCPRE_DIV8 0x0000C000U /*!< PCLK2 divided by 8 */ +#define RCC_CFGR_ADCPRE_DIV2 ((uint32_t)0x00000000) /*!< PCLK2 divided by 2 */ +#define RCC_CFGR_ADCPRE_DIV4 ((uint32_t)0x00004000) /*!< PCLK2 divided by 4 */ +#define RCC_CFGR_ADCPRE_DIV6 ((uint32_t)0x00008000) /*!< PCLK2 divided by 6 */ +#define RCC_CFGR_ADCPRE_DIV8 ((uint32_t)0x0000C000) /*!< PCLK2 divided by 8 */ #define RCC_CFGR_PLLSRC_Pos (16U) #define RCC_CFGR_PLLSRC_Msk (0x1U << RCC_CFGR_PLLSRC_Pos) /*!< 0x00010000 */ @@ -1077,10 +1068,10 @@ typedef struct #define RCC_CFGR_PLLMULL_2 (0x4U << RCC_CFGR_PLLMULL_Pos) /*!< 0x00100000 */ #define RCC_CFGR_PLLMULL_3 (0x8U << RCC_CFGR_PLLMULL_Pos) /*!< 0x00200000 */ -#define RCC_CFGR_PLLXTPRE_HSE 0x00000000U /*!< HSE clock not divided for PLL entry */ -#define RCC_CFGR_PLLXTPRE_HSE_DIV2 0x00020000U /*!< HSE clock divided by 2 for PLL entry */ +#define RCC_CFGR_PLLXTPRE_HSE ((uint32_t)0x00000000) /*!< HSE clock not divided for PLL entry */ +#define RCC_CFGR_PLLXTPRE_HSE_DIV2 ((uint32_t)0x00020000) /*!< HSE clock divided by 2 for PLL entry */ -#define RCC_CFGR_PLLMULL2 0x00000000U /*!< PLL input clock*2 */ +#define RCC_CFGR_PLLMULL2 ((uint32_t)0x00000000) /*!< PLL input clock*2 */ #define RCC_CFGR_PLLMULL3_Pos (18U) #define RCC_CFGR_PLLMULL3_Msk (0x1U << RCC_CFGR_PLLMULL3_Pos) /*!< 0x00040000 */ #define RCC_CFGR_PLLMULL3 RCC_CFGR_PLLMULL3_Msk /*!< PLL input clock*3 */ @@ -1135,11 +1126,11 @@ typedef struct #define RCC_CFGR_MCO_1 (0x2U << RCC_CFGR_MCO_Pos) /*!< 0x02000000 */ #define RCC_CFGR_MCO_2 (0x4U << RCC_CFGR_MCO_Pos) /*!< 0x04000000 */ -#define RCC_CFGR_MCO_NOCLOCK 0x00000000U /*!< No clock */ -#define RCC_CFGR_MCO_SYSCLK 0x04000000U /*!< System clock selected as MCO source */ -#define RCC_CFGR_MCO_HSI 0x05000000U /*!< HSI clock selected as MCO source */ -#define RCC_CFGR_MCO_HSE 0x06000000U /*!< HSE clock selected as MCO source */ -#define RCC_CFGR_MCO_PLLCLK_DIV2 0x07000000U /*!< PLL clock divided by 2 selected as MCO source */ +#define RCC_CFGR_MCO_NOCLOCK ((uint32_t)0x00000000) /*!< No clock */ +#define RCC_CFGR_MCO_SYSCLK ((uint32_t)0x04000000) /*!< System clock selected as MCO source */ +#define RCC_CFGR_MCO_HSI ((uint32_t)0x05000000) /*!< HSI clock selected as MCO source */ +#define RCC_CFGR_MCO_HSE ((uint32_t)0x06000000) /*!< HSE clock selected as MCO source */ +#define RCC_CFGR_MCO_PLLCLK_DIV2 ((uint32_t)0x07000000) /*!< PLL clock divided by 2 selected as MCO source */ /* Reference defines */ #define RCC_CFGR_MCOSEL RCC_CFGR_MCO @@ -1425,10 +1416,10 @@ typedef struct #define RCC_BDCR_RTCSEL_1 (0x2U << RCC_BDCR_RTCSEL_Pos) /*!< 0x00000200 */ /*!< RTC congiguration */ -#define RCC_BDCR_RTCSEL_NOCLOCK 0x00000000U /*!< No clock */ -#define RCC_BDCR_RTCSEL_LSE 0x00000100U /*!< LSE oscillator clock used as RTC clock */ -#define RCC_BDCR_RTCSEL_LSI 0x00000200U /*!< LSI oscillator clock used as RTC clock */ -#define RCC_BDCR_RTCSEL_HSE 0x00000300U /*!< HSE oscillator clock divided by 128 used as RTC clock */ +#define RCC_BDCR_RTCSEL_NOCLOCK ((uint32_t)0x00000000) /*!< No clock */ +#define RCC_BDCR_RTCSEL_LSE ((uint32_t)0x00000100) /*!< LSE oscillator clock used as RTC clock */ +#define RCC_BDCR_RTCSEL_LSI ((uint32_t)0x00000200) /*!< LSI oscillator clock used as RTC clock */ +#define RCC_BDCR_RTCSEL_HSE ((uint32_t)0x00000300) /*!< HSE oscillator clock divided by 128 used as RTC clock */ #define RCC_BDCR_RTCEN_Pos (15U) #define RCC_BDCR_RTCEN_Msk (0x1U << RCC_BDCR_RTCEN_Pos) /*!< 0x00008000 */ @@ -1998,7 +1989,7 @@ typedef struct #define AFIO_EVCR_PIN_3 (0x8U << AFIO_EVCR_PIN_Pos) /*!< 0x00000008 */ /*!< PIN configuration */ -#define AFIO_EVCR_PIN_PX0 0x00000000U /*!< Pin 0 selected */ +#define AFIO_EVCR_PIN_PX0 ((uint32_t)0x00000000) /*!< Pin 0 selected */ #define AFIO_EVCR_PIN_PX1_Pos (0U) #define AFIO_EVCR_PIN_PX1_Msk (0x1U << AFIO_EVCR_PIN_PX1_Pos) /*!< 0x00000001 */ #define AFIO_EVCR_PIN_PX1 AFIO_EVCR_PIN_PX1_Msk /*!< Pin 1 selected */ @@ -2053,7 +2044,7 @@ typedef struct #define AFIO_EVCR_PORT_2 (0x4U << AFIO_EVCR_PORT_Pos) /*!< 0x00000040 */ /*!< PORT configuration */ -#define AFIO_EVCR_PORT_PA 0x00000000 /*!< Port A selected */ +#define AFIO_EVCR_PORT_PA ((uint32_t)0x00000000) /*!< Port A selected */ #define AFIO_EVCR_PORT_PB_Pos (4U) #define AFIO_EVCR_PORT_PB_Msk (0x1U << AFIO_EVCR_PORT_PB_Pos) /*!< 0x00000010 */ #define AFIO_EVCR_PORT_PB AFIO_EVCR_PORT_PB_Msk /*!< Port B selected */ @@ -2092,7 +2083,7 @@ typedef struct #define AFIO_MAPR_USART3_REMAP_1 (0x2U << AFIO_MAPR_USART3_REMAP_Pos) /*!< 0x00000020 */ /* USART3_REMAP configuration */ -#define AFIO_MAPR_USART3_REMAP_NOREMAP 0x00000000U /*!< No remap (TX/PB10, RX/PB11, CK/PB12, CTS/PB13, RTS/PB14) */ +#define AFIO_MAPR_USART3_REMAP_NOREMAP ((uint32_t)0x00000000) /*!< No remap (TX/PB10, RX/PB11, CK/PB12, CTS/PB13, RTS/PB14) */ #define AFIO_MAPR_USART3_REMAP_PARTIALREMAP_Pos (4U) #define AFIO_MAPR_USART3_REMAP_PARTIALREMAP_Msk (0x1U << AFIO_MAPR_USART3_REMAP_PARTIALREMAP_Pos) /*!< 0x00000010 */ #define AFIO_MAPR_USART3_REMAP_PARTIALREMAP AFIO_MAPR_USART3_REMAP_PARTIALREMAP_Msk /*!< Partial remap (TX/PC10, RX/PC11, CK/PC12, CTS/PB13, RTS/PB14) */ @@ -2107,7 +2098,7 @@ typedef struct #define AFIO_MAPR_TIM1_REMAP_1 (0x2U << AFIO_MAPR_TIM1_REMAP_Pos) /*!< 0x00000080 */ /*!< TIM1_REMAP configuration */ -#define AFIO_MAPR_TIM1_REMAP_NOREMAP 0x00000000U /*!< No remap (ETR/PA12, CH1/PA8, CH2/PA9, CH3/PA10, CH4/PA11, BKIN/PB12, CH1N/PB13, CH2N/PB14, CH3N/PB15) */ +#define AFIO_MAPR_TIM1_REMAP_NOREMAP ((uint32_t)0x00000000) /*!< No remap (ETR/PA12, CH1/PA8, CH2/PA9, CH3/PA10, CH4/PA11, BKIN/PB12, CH1N/PB13, CH2N/PB14, CH3N/PB15) */ #define AFIO_MAPR_TIM1_REMAP_PARTIALREMAP_Pos (6U) #define AFIO_MAPR_TIM1_REMAP_PARTIALREMAP_Msk (0x1U << AFIO_MAPR_TIM1_REMAP_PARTIALREMAP_Pos) /*!< 0x00000040 */ #define AFIO_MAPR_TIM1_REMAP_PARTIALREMAP AFIO_MAPR_TIM1_REMAP_PARTIALREMAP_Msk /*!< Partial remap (ETR/PA12, CH1/PA8, CH2/PA9, CH3/PA10, CH4/PA11, BKIN/PA6, CH1N/PA7, CH2N/PB0, CH3N/PB1) */ @@ -2122,7 +2113,7 @@ typedef struct #define AFIO_MAPR_TIM2_REMAP_1 (0x2U << AFIO_MAPR_TIM2_REMAP_Pos) /*!< 0x00000200 */ /*!< TIM2_REMAP configuration */ -#define AFIO_MAPR_TIM2_REMAP_NOREMAP 0x00000000U /*!< No remap (CH1/ETR/PA0, CH2/PA1, CH3/PA2, CH4/PA3) */ +#define AFIO_MAPR_TIM2_REMAP_NOREMAP ((uint32_t)0x00000000) /*!< No remap (CH1/ETR/PA0, CH2/PA1, CH3/PA2, CH4/PA3) */ #define AFIO_MAPR_TIM2_REMAP_PARTIALREMAP1_Pos (8U) #define AFIO_MAPR_TIM2_REMAP_PARTIALREMAP1_Msk (0x1U << AFIO_MAPR_TIM2_REMAP_PARTIALREMAP1_Pos) /*!< 0x00000100 */ #define AFIO_MAPR_TIM2_REMAP_PARTIALREMAP1 AFIO_MAPR_TIM2_REMAP_PARTIALREMAP1_Msk /*!< Partial remap (CH1/ETR/PA15, CH2/PB3, CH3/PA2, CH4/PA3) */ @@ -2140,7 +2131,7 @@ typedef struct #define AFIO_MAPR_TIM3_REMAP_1 (0x2U << AFIO_MAPR_TIM3_REMAP_Pos) /*!< 0x00000800 */ /*!< TIM3_REMAP configuration */ -#define AFIO_MAPR_TIM3_REMAP_NOREMAP 0x00000000U /*!< No remap (CH1/PA6, CH2/PA7, CH3/PB0, CH4/PB1) */ +#define AFIO_MAPR_TIM3_REMAP_NOREMAP ((uint32_t)0x00000000) /*!< No remap (CH1/PA6, CH2/PA7, CH3/PB0, CH4/PB1) */ #define AFIO_MAPR_TIM3_REMAP_PARTIALREMAP_Pos (11U) #define AFIO_MAPR_TIM3_REMAP_PARTIALREMAP_Msk (0x1U << AFIO_MAPR_TIM3_REMAP_PARTIALREMAP_Pos) /*!< 0x00000800 */ #define AFIO_MAPR_TIM3_REMAP_PARTIALREMAP AFIO_MAPR_TIM3_REMAP_PARTIALREMAP_Msk /*!< Partial remap (CH1/PB4, CH2/PB5, CH3/PB0, CH4/PB1) */ @@ -2159,7 +2150,7 @@ typedef struct #define AFIO_MAPR_CAN_REMAP_1 (0x2U << AFIO_MAPR_CAN_REMAP_Pos) /*!< 0x00004000 */ /*!< CAN_REMAP configuration */ -#define AFIO_MAPR_CAN_REMAP_REMAP1 0x00000000U /*!< CANRX mapped to PA11, CANTX mapped to PA12 */ +#define AFIO_MAPR_CAN_REMAP_REMAP1 ((uint32_t)0x00000000) /*!< CANRX mapped to PA11, CANTX mapped to PA12 */ #define AFIO_MAPR_CAN_REMAP_REMAP2_Pos (14U) #define AFIO_MAPR_CAN_REMAP_REMAP2_Msk (0x1U << AFIO_MAPR_CAN_REMAP_REMAP2_Pos) /*!< 0x00004000 */ #define AFIO_MAPR_CAN_REMAP_REMAP2 AFIO_MAPR_CAN_REMAP_REMAP2_Msk /*!< CANRX mapped to PB8, CANTX mapped to PB9 */ @@ -2179,7 +2170,7 @@ typedef struct #define AFIO_MAPR_SWJ_CFG_1 (0x2U << AFIO_MAPR_SWJ_CFG_Pos) /*!< 0x02000000 */ #define AFIO_MAPR_SWJ_CFG_2 (0x4U << AFIO_MAPR_SWJ_CFG_Pos) /*!< 0x04000000 */ -#define AFIO_MAPR_SWJ_CFG_RESET 0x00000000U /*!< Full SWJ (JTAG-DP + SW-DP) : Reset State */ +#define AFIO_MAPR_SWJ_CFG_RESET ((uint32_t)0x00000000) /*!< Full SWJ (JTAG-DP + SW-DP) : Reset State */ #define AFIO_MAPR_SWJ_CFG_NOJNTRST_Pos (24U) #define AFIO_MAPR_SWJ_CFG_NOJNTRST_Msk (0x1U << AFIO_MAPR_SWJ_CFG_NOJNTRST_Pos) /*!< 0x01000000 */ #define AFIO_MAPR_SWJ_CFG_NOJNTRST AFIO_MAPR_SWJ_CFG_NOJNTRST_Msk /*!< Full SWJ (JTAG-DP + SW-DP) but without JNTRST */ @@ -2206,7 +2197,7 @@ typedef struct #define AFIO_EXTICR1_EXTI3 AFIO_EXTICR1_EXTI3_Msk /*!< EXTI 3 configuration */ /*!< EXTI0 configuration */ -#define AFIO_EXTICR1_EXTI0_PA 0x00000000U /*!< PA[0] pin */ +#define AFIO_EXTICR1_EXTI0_PA ((uint32_t)0x00000000) /*!< PA[0] pin */ #define AFIO_EXTICR1_EXTI0_PB_Pos (0U) #define AFIO_EXTICR1_EXTI0_PB_Msk (0x1U << AFIO_EXTICR1_EXTI0_PB_Pos) /*!< 0x00000001 */ #define AFIO_EXTICR1_EXTI0_PB AFIO_EXTICR1_EXTI0_PB_Msk /*!< PB[0] pin */ @@ -2227,7 +2218,7 @@ typedef struct #define AFIO_EXTICR1_EXTI0_PG AFIO_EXTICR1_EXTI0_PG_Msk /*!< PG[0] pin */ /*!< EXTI1 configuration */ -#define AFIO_EXTICR1_EXTI1_PA 0x00000000U /*!< PA[1] pin */ +#define AFIO_EXTICR1_EXTI1_PA ((uint32_t)0x00000000) /*!< PA[1] pin */ #define AFIO_EXTICR1_EXTI1_PB_Pos (4U) #define AFIO_EXTICR1_EXTI1_PB_Msk (0x1U << AFIO_EXTICR1_EXTI1_PB_Pos) /*!< 0x00000010 */ #define AFIO_EXTICR1_EXTI1_PB AFIO_EXTICR1_EXTI1_PB_Msk /*!< PB[1] pin */ @@ -2248,7 +2239,7 @@ typedef struct #define AFIO_EXTICR1_EXTI1_PG AFIO_EXTICR1_EXTI1_PG_Msk /*!< PG[1] pin */ /*!< EXTI2 configuration */ -#define AFIO_EXTICR1_EXTI2_PA 0x00000000U /*!< PA[2] pin */ +#define AFIO_EXTICR1_EXTI2_PA ((uint32_t)0x00000000) /*!< PA[2] pin */ #define AFIO_EXTICR1_EXTI2_PB_Pos (8U) #define AFIO_EXTICR1_EXTI2_PB_Msk (0x1U << AFIO_EXTICR1_EXTI2_PB_Pos) /*!< 0x00000100 */ #define AFIO_EXTICR1_EXTI2_PB AFIO_EXTICR1_EXTI2_PB_Msk /*!< PB[2] pin */ @@ -2269,7 +2260,7 @@ typedef struct #define AFIO_EXTICR1_EXTI2_PG AFIO_EXTICR1_EXTI2_PG_Msk /*!< PG[2] pin */ /*!< EXTI3 configuration */ -#define AFIO_EXTICR1_EXTI3_PA 0x00000000U /*!< PA[3] pin */ +#define AFIO_EXTICR1_EXTI3_PA ((uint32_t)0x00000000) /*!< PA[3] pin */ #define AFIO_EXTICR1_EXTI3_PB_Pos (12U) #define AFIO_EXTICR1_EXTI3_PB_Msk (0x1U << AFIO_EXTICR1_EXTI3_PB_Pos) /*!< 0x00001000 */ #define AFIO_EXTICR1_EXTI3_PB AFIO_EXTICR1_EXTI3_PB_Msk /*!< PB[3] pin */ @@ -2304,7 +2295,7 @@ typedef struct #define AFIO_EXTICR2_EXTI7 AFIO_EXTICR2_EXTI7_Msk /*!< EXTI 7 configuration */ /*!< EXTI4 configuration */ -#define AFIO_EXTICR2_EXTI4_PA 0x00000000U /*!< PA[4] pin */ +#define AFIO_EXTICR2_EXTI4_PA ((uint32_t)0x00000000) /*!< PA[4] pin */ #define AFIO_EXTICR2_EXTI4_PB_Pos (0U) #define AFIO_EXTICR2_EXTI4_PB_Msk (0x1U << AFIO_EXTICR2_EXTI4_PB_Pos) /*!< 0x00000001 */ #define AFIO_EXTICR2_EXTI4_PB AFIO_EXTICR2_EXTI4_PB_Msk /*!< PB[4] pin */ @@ -2325,7 +2316,7 @@ typedef struct #define AFIO_EXTICR2_EXTI4_PG AFIO_EXTICR2_EXTI4_PG_Msk /*!< PG[4] pin */ /* EXTI5 configuration */ -#define AFIO_EXTICR2_EXTI5_PA 0x00000000U /*!< PA[5] pin */ +#define AFIO_EXTICR2_EXTI5_PA ((uint32_t)0x00000000) /*!< PA[5] pin */ #define AFIO_EXTICR2_EXTI5_PB_Pos (4U) #define AFIO_EXTICR2_EXTI5_PB_Msk (0x1U << AFIO_EXTICR2_EXTI5_PB_Pos) /*!< 0x00000010 */ #define AFIO_EXTICR2_EXTI5_PB AFIO_EXTICR2_EXTI5_PB_Msk /*!< PB[5] pin */ @@ -2346,7 +2337,7 @@ typedef struct #define AFIO_EXTICR2_EXTI5_PG AFIO_EXTICR2_EXTI5_PG_Msk /*!< PG[5] pin */ /*!< EXTI6 configuration */ -#define AFIO_EXTICR2_EXTI6_PA 0x00000000U /*!< PA[6] pin */ +#define AFIO_EXTICR2_EXTI6_PA ((uint32_t)0x00000000) /*!< PA[6] pin */ #define AFIO_EXTICR2_EXTI6_PB_Pos (8U) #define AFIO_EXTICR2_EXTI6_PB_Msk (0x1U << AFIO_EXTICR2_EXTI6_PB_Pos) /*!< 0x00000100 */ #define AFIO_EXTICR2_EXTI6_PB AFIO_EXTICR2_EXTI6_PB_Msk /*!< PB[6] pin */ @@ -2367,7 +2358,7 @@ typedef struct #define AFIO_EXTICR2_EXTI6_PG AFIO_EXTICR2_EXTI6_PG_Msk /*!< PG[6] pin */ /*!< EXTI7 configuration */ -#define AFIO_EXTICR2_EXTI7_PA 0x00000000U /*!< PA[7] pin */ +#define AFIO_EXTICR2_EXTI7_PA ((uint32_t)0x00000000) /*!< PA[7] pin */ #define AFIO_EXTICR2_EXTI7_PB_Pos (12U) #define AFIO_EXTICR2_EXTI7_PB_Msk (0x1U << AFIO_EXTICR2_EXTI7_PB_Pos) /*!< 0x00001000 */ #define AFIO_EXTICR2_EXTI7_PB AFIO_EXTICR2_EXTI7_PB_Msk /*!< PB[7] pin */ @@ -2402,7 +2393,7 @@ typedef struct #define AFIO_EXTICR3_EXTI11 AFIO_EXTICR3_EXTI11_Msk /*!< EXTI 11 configuration */ /*!< EXTI8 configuration */ -#define AFIO_EXTICR3_EXTI8_PA 0x00000000U /*!< PA[8] pin */ +#define AFIO_EXTICR3_EXTI8_PA ((uint32_t)0x00000000) /*!< PA[8] pin */ #define AFIO_EXTICR3_EXTI8_PB_Pos (0U) #define AFIO_EXTICR3_EXTI8_PB_Msk (0x1U << AFIO_EXTICR3_EXTI8_PB_Pos) /*!< 0x00000001 */ #define AFIO_EXTICR3_EXTI8_PB AFIO_EXTICR3_EXTI8_PB_Msk /*!< PB[8] pin */ @@ -2423,7 +2414,7 @@ typedef struct #define AFIO_EXTICR3_EXTI8_PG AFIO_EXTICR3_EXTI8_PG_Msk /*!< PG[8] pin */ /*!< EXTI9 configuration */ -#define AFIO_EXTICR3_EXTI9_PA 0x00000000U /*!< PA[9] pin */ +#define AFIO_EXTICR3_EXTI9_PA ((uint32_t)0x00000000) /*!< PA[9] pin */ #define AFIO_EXTICR3_EXTI9_PB_Pos (4U) #define AFIO_EXTICR3_EXTI9_PB_Msk (0x1U << AFIO_EXTICR3_EXTI9_PB_Pos) /*!< 0x00000010 */ #define AFIO_EXTICR3_EXTI9_PB AFIO_EXTICR3_EXTI9_PB_Msk /*!< PB[9] pin */ @@ -2444,7 +2435,7 @@ typedef struct #define AFIO_EXTICR3_EXTI9_PG AFIO_EXTICR3_EXTI9_PG_Msk /*!< PG[9] pin */ /*!< EXTI10 configuration */ -#define AFIO_EXTICR3_EXTI10_PA 0x00000000U /*!< PA[10] pin */ +#define AFIO_EXTICR3_EXTI10_PA ((uint32_t)0x00000000) /*!< PA[10] pin */ #define AFIO_EXTICR3_EXTI10_PB_Pos (8U) #define AFIO_EXTICR3_EXTI10_PB_Msk (0x1U << AFIO_EXTICR3_EXTI10_PB_Pos) /*!< 0x00000100 */ #define AFIO_EXTICR3_EXTI10_PB AFIO_EXTICR3_EXTI10_PB_Msk /*!< PB[10] pin */ @@ -2465,7 +2456,7 @@ typedef struct #define AFIO_EXTICR3_EXTI10_PG AFIO_EXTICR3_EXTI10_PG_Msk /*!< PG[10] pin */ /*!< EXTI11 configuration */ -#define AFIO_EXTICR3_EXTI11_PA 0x00000000U /*!< PA[11] pin */ +#define AFIO_EXTICR3_EXTI11_PA ((uint32_t)0x00000000) /*!< PA[11] pin */ #define AFIO_EXTICR3_EXTI11_PB_Pos (12U) #define AFIO_EXTICR3_EXTI11_PB_Msk (0x1U << AFIO_EXTICR3_EXTI11_PB_Pos) /*!< 0x00001000 */ #define AFIO_EXTICR3_EXTI11_PB AFIO_EXTICR3_EXTI11_PB_Msk /*!< PB[11] pin */ @@ -2500,7 +2491,7 @@ typedef struct #define AFIO_EXTICR4_EXTI15 AFIO_EXTICR4_EXTI15_Msk /*!< EXTI 15 configuration */ /* EXTI12 configuration */ -#define AFIO_EXTICR4_EXTI12_PA 0x00000000U /*!< PA[12] pin */ +#define AFIO_EXTICR4_EXTI12_PA ((uint32_t)0x00000000) /*!< PA[12] pin */ #define AFIO_EXTICR4_EXTI12_PB_Pos (0U) #define AFIO_EXTICR4_EXTI12_PB_Msk (0x1U << AFIO_EXTICR4_EXTI12_PB_Pos) /*!< 0x00000001 */ #define AFIO_EXTICR4_EXTI12_PB AFIO_EXTICR4_EXTI12_PB_Msk /*!< PB[12] pin */ @@ -2521,7 +2512,7 @@ typedef struct #define AFIO_EXTICR4_EXTI12_PG AFIO_EXTICR4_EXTI12_PG_Msk /*!< PG[12] pin */ /* EXTI13 configuration */ -#define AFIO_EXTICR4_EXTI13_PA 0x00000000U /*!< PA[13] pin */ +#define AFIO_EXTICR4_EXTI13_PA ((uint32_t)0x00000000) /*!< PA[13] pin */ #define AFIO_EXTICR4_EXTI13_PB_Pos (4U) #define AFIO_EXTICR4_EXTI13_PB_Msk (0x1U << AFIO_EXTICR4_EXTI13_PB_Pos) /*!< 0x00000010 */ #define AFIO_EXTICR4_EXTI13_PB AFIO_EXTICR4_EXTI13_PB_Msk /*!< PB[13] pin */ @@ -2542,7 +2533,7 @@ typedef struct #define AFIO_EXTICR4_EXTI13_PG AFIO_EXTICR4_EXTI13_PG_Msk /*!< PG[13] pin */ /*!< EXTI14 configuration */ -#define AFIO_EXTICR4_EXTI14_PA 0x00000000U /*!< PA[14] pin */ +#define AFIO_EXTICR4_EXTI14_PA ((uint32_t)0x00000000) /*!< PA[14] pin */ #define AFIO_EXTICR4_EXTI14_PB_Pos (8U) #define AFIO_EXTICR4_EXTI14_PB_Msk (0x1U << AFIO_EXTICR4_EXTI14_PB_Pos) /*!< 0x00000100 */ #define AFIO_EXTICR4_EXTI14_PB AFIO_EXTICR4_EXTI14_PB_Msk /*!< PB[14] pin */ @@ -2563,7 +2554,7 @@ typedef struct #define AFIO_EXTICR4_EXTI14_PG AFIO_EXTICR4_EXTI14_PG_Msk /*!< PG[14] pin */ /*!< EXTI15 configuration */ -#define AFIO_EXTICR4_EXTI15_PA 0x00000000U /*!< PA[15] pin */ +#define AFIO_EXTICR4_EXTI15_PA ((uint32_t)0x00000000) /*!< PA[15] pin */ #define AFIO_EXTICR4_EXTI15_PB_Pos (12U) #define AFIO_EXTICR4_EXTI15_PB_Msk (0x1U << AFIO_EXTICR4_EXTI15_PB_Pos) /*!< 0x00001000 */ #define AFIO_EXTICR4_EXTI15_PB AFIO_EXTICR4_EXTI15_PB_Msk /*!< PB[15] pin */ @@ -2587,6 +2578,440 @@ typedef struct +/******************************************************************************/ +/* */ +/* SystemTick */ +/* */ +/******************************************************************************/ + +/***************** Bit definition for SysTick_CTRL register *****************/ +#define SysTick_CTRL_ENABLE ((uint32_t)0x00000001) /*!< Counter enable */ +#define SysTick_CTRL_TICKINT ((uint32_t)0x00000002) /*!< Counting down to 0 pends the SysTick handler */ +#define SysTick_CTRL_CLKSOURCE ((uint32_t)0x00000004) /*!< Clock source */ +#define SysTick_CTRL_COUNTFLAG ((uint32_t)0x00010000) /*!< Count Flag */ + +/***************** Bit definition for SysTick_LOAD register *****************/ +#define SysTick_LOAD_RELOAD ((uint32_t)0x00FFFFFF) /*!< Value to load into the SysTick Current Value Register when the counter reaches 0 */ + +/***************** Bit definition for SysTick_VAL register ******************/ +#define SysTick_VAL_CURRENT ((uint32_t)0x00FFFFFF) /*!< Current value at the time the register is accessed */ + +/***************** Bit definition for SysTick_CALIB register ****************/ +#define SysTick_CALIB_TENMS ((uint32_t)0x00FFFFFF) /*!< Reload value to use for 10ms timing */ +#define SysTick_CALIB_SKEW ((uint32_t)0x40000000) /*!< Calibration value is not exactly 10 ms */ +#define SysTick_CALIB_NOREF ((uint32_t)0x80000000) /*!< The reference clock is not provided */ + +/******************************************************************************/ +/* */ +/* Nested Vectored Interrupt Controller */ +/* */ +/******************************************************************************/ + +/****************** Bit definition for NVIC_ISER register *******************/ +#define NVIC_ISER_SETENA_Pos (0U) +#define NVIC_ISER_SETENA_Msk (0xFFFFFFFFU << NVIC_ISER_SETENA_Pos) /*!< 0xFFFFFFFF */ +#define NVIC_ISER_SETENA NVIC_ISER_SETENA_Msk /*!< Interrupt set enable bits */ +#define NVIC_ISER_SETENA_0 (0x00000001U << NVIC_ISER_SETENA_Pos) /*!< 0x00000001 */ +#define NVIC_ISER_SETENA_1 (0x00000002U << NVIC_ISER_SETENA_Pos) /*!< 0x00000002 */ +#define NVIC_ISER_SETENA_2 (0x00000004U << NVIC_ISER_SETENA_Pos) /*!< 0x00000004 */ +#define NVIC_ISER_SETENA_3 (0x00000008U << NVIC_ISER_SETENA_Pos) /*!< 0x00000008 */ +#define NVIC_ISER_SETENA_4 (0x00000010U << NVIC_ISER_SETENA_Pos) /*!< 0x00000010 */ +#define NVIC_ISER_SETENA_5 (0x00000020U << NVIC_ISER_SETENA_Pos) /*!< 0x00000020 */ +#define NVIC_ISER_SETENA_6 (0x00000040U << NVIC_ISER_SETENA_Pos) /*!< 0x00000040 */ +#define NVIC_ISER_SETENA_7 (0x00000080U << NVIC_ISER_SETENA_Pos) /*!< 0x00000080 */ +#define NVIC_ISER_SETENA_8 (0x00000100U << NVIC_ISER_SETENA_Pos) /*!< 0x00000100 */ +#define NVIC_ISER_SETENA_9 (0x00000200U << NVIC_ISER_SETENA_Pos) /*!< 0x00000200 */ +#define NVIC_ISER_SETENA_10 (0x00000400U << NVIC_ISER_SETENA_Pos) /*!< 0x00000400 */ +#define NVIC_ISER_SETENA_11 (0x00000800U << NVIC_ISER_SETENA_Pos) /*!< 0x00000800 */ +#define NVIC_ISER_SETENA_12 (0x00001000U << NVIC_ISER_SETENA_Pos) /*!< 0x00001000 */ +#define NVIC_ISER_SETENA_13 (0x00002000U << NVIC_ISER_SETENA_Pos) /*!< 0x00002000 */ +#define NVIC_ISER_SETENA_14 (0x00004000U << NVIC_ISER_SETENA_Pos) /*!< 0x00004000 */ +#define NVIC_ISER_SETENA_15 (0x00008000U << NVIC_ISER_SETENA_Pos) /*!< 0x00008000 */ +#define NVIC_ISER_SETENA_16 (0x00010000U << NVIC_ISER_SETENA_Pos) /*!< 0x00010000 */ +#define NVIC_ISER_SETENA_17 (0x00020000U << NVIC_ISER_SETENA_Pos) /*!< 0x00020000 */ +#define NVIC_ISER_SETENA_18 (0x00040000U << NVIC_ISER_SETENA_Pos) /*!< 0x00040000 */ +#define NVIC_ISER_SETENA_19 (0x00080000U << NVIC_ISER_SETENA_Pos) /*!< 0x00080000 */ +#define NVIC_ISER_SETENA_20 (0x00100000U << NVIC_ISER_SETENA_Pos) /*!< 0x00100000 */ +#define NVIC_ISER_SETENA_21 (0x00200000U << NVIC_ISER_SETENA_Pos) /*!< 0x00200000 */ +#define NVIC_ISER_SETENA_22 (0x00400000U << NVIC_ISER_SETENA_Pos) /*!< 0x00400000 */ +#define NVIC_ISER_SETENA_23 (0x00800000U << NVIC_ISER_SETENA_Pos) /*!< 0x00800000 */ +#define NVIC_ISER_SETENA_24 (0x01000000U << NVIC_ISER_SETENA_Pos) /*!< 0x01000000 */ +#define NVIC_ISER_SETENA_25 (0x02000000U << NVIC_ISER_SETENA_Pos) /*!< 0x02000000 */ +#define NVIC_ISER_SETENA_26 (0x04000000U << NVIC_ISER_SETENA_Pos) /*!< 0x04000000 */ +#define NVIC_ISER_SETENA_27 (0x08000000U << NVIC_ISER_SETENA_Pos) /*!< 0x08000000 */ +#define NVIC_ISER_SETENA_28 (0x10000000U << NVIC_ISER_SETENA_Pos) /*!< 0x10000000 */ +#define NVIC_ISER_SETENA_29 (0x20000000U << NVIC_ISER_SETENA_Pos) /*!< 0x20000000 */ +#define NVIC_ISER_SETENA_30 (0x40000000U << NVIC_ISER_SETENA_Pos) /*!< 0x40000000 */ +#define NVIC_ISER_SETENA_31 (0x80000000U << NVIC_ISER_SETENA_Pos) /*!< 0x80000000 */ + +/****************** Bit definition for NVIC_ICER register *******************/ +#define NVIC_ICER_CLRENA_Pos (0U) +#define NVIC_ICER_CLRENA_Msk (0xFFFFFFFFU << NVIC_ICER_CLRENA_Pos) /*!< 0xFFFFFFFF */ +#define NVIC_ICER_CLRENA NVIC_ICER_CLRENA_Msk /*!< Interrupt clear-enable bits */ +#define NVIC_ICER_CLRENA_0 (0x00000001U << NVIC_ICER_CLRENA_Pos) /*!< 0x00000001 */ +#define NVIC_ICER_CLRENA_1 (0x00000002U << NVIC_ICER_CLRENA_Pos) /*!< 0x00000002 */ +#define NVIC_ICER_CLRENA_2 (0x00000004U << NVIC_ICER_CLRENA_Pos) /*!< 0x00000004 */ +#define NVIC_ICER_CLRENA_3 (0x00000008U << NVIC_ICER_CLRENA_Pos) /*!< 0x00000008 */ +#define NVIC_ICER_CLRENA_4 (0x00000010U << NVIC_ICER_CLRENA_Pos) /*!< 0x00000010 */ +#define NVIC_ICER_CLRENA_5 (0x00000020U << NVIC_ICER_CLRENA_Pos) /*!< 0x00000020 */ +#define NVIC_ICER_CLRENA_6 (0x00000040U << NVIC_ICER_CLRENA_Pos) /*!< 0x00000040 */ +#define NVIC_ICER_CLRENA_7 (0x00000080U << NVIC_ICER_CLRENA_Pos) /*!< 0x00000080 */ +#define NVIC_ICER_CLRENA_8 (0x00000100U << NVIC_ICER_CLRENA_Pos) /*!< 0x00000100 */ +#define NVIC_ICER_CLRENA_9 (0x00000200U << NVIC_ICER_CLRENA_Pos) /*!< 0x00000200 */ +#define NVIC_ICER_CLRENA_10 (0x00000400U << NVIC_ICER_CLRENA_Pos) /*!< 0x00000400 */ +#define NVIC_ICER_CLRENA_11 (0x00000800U << NVIC_ICER_CLRENA_Pos) /*!< 0x00000800 */ +#define NVIC_ICER_CLRENA_12 (0x00001000U << NVIC_ICER_CLRENA_Pos) /*!< 0x00001000 */ +#define NVIC_ICER_CLRENA_13 (0x00002000U << NVIC_ICER_CLRENA_Pos) /*!< 0x00002000 */ +#define NVIC_ICER_CLRENA_14 (0x00004000U << NVIC_ICER_CLRENA_Pos) /*!< 0x00004000 */ +#define NVIC_ICER_CLRENA_15 (0x00008000U << NVIC_ICER_CLRENA_Pos) /*!< 0x00008000 */ +#define NVIC_ICER_CLRENA_16 (0x00010000U << NVIC_ICER_CLRENA_Pos) /*!< 0x00010000 */ +#define NVIC_ICER_CLRENA_17 (0x00020000U << NVIC_ICER_CLRENA_Pos) /*!< 0x00020000 */ +#define NVIC_ICER_CLRENA_18 (0x00040000U << NVIC_ICER_CLRENA_Pos) /*!< 0x00040000 */ +#define NVIC_ICER_CLRENA_19 (0x00080000U << NVIC_ICER_CLRENA_Pos) /*!< 0x00080000 */ +#define NVIC_ICER_CLRENA_20 (0x00100000U << NVIC_ICER_CLRENA_Pos) /*!< 0x00100000 */ +#define NVIC_ICER_CLRENA_21 (0x00200000U << NVIC_ICER_CLRENA_Pos) /*!< 0x00200000 */ +#define NVIC_ICER_CLRENA_22 (0x00400000U << NVIC_ICER_CLRENA_Pos) /*!< 0x00400000 */ +#define NVIC_ICER_CLRENA_23 (0x00800000U << NVIC_ICER_CLRENA_Pos) /*!< 0x00800000 */ +#define NVIC_ICER_CLRENA_24 (0x01000000U << NVIC_ICER_CLRENA_Pos) /*!< 0x01000000 */ +#define NVIC_ICER_CLRENA_25 (0x02000000U << NVIC_ICER_CLRENA_Pos) /*!< 0x02000000 */ +#define NVIC_ICER_CLRENA_26 (0x04000000U << NVIC_ICER_CLRENA_Pos) /*!< 0x04000000 */ +#define NVIC_ICER_CLRENA_27 (0x08000000U << NVIC_ICER_CLRENA_Pos) /*!< 0x08000000 */ +#define NVIC_ICER_CLRENA_28 (0x10000000U << NVIC_ICER_CLRENA_Pos) /*!< 0x10000000 */ +#define NVIC_ICER_CLRENA_29 (0x20000000U << NVIC_ICER_CLRENA_Pos) /*!< 0x20000000 */ +#define NVIC_ICER_CLRENA_30 (0x40000000U << NVIC_ICER_CLRENA_Pos) /*!< 0x40000000 */ +#define NVIC_ICER_CLRENA_31 (0x80000000U << NVIC_ICER_CLRENA_Pos) /*!< 0x80000000 */ + +/****************** Bit definition for NVIC_ISPR register *******************/ +#define NVIC_ISPR_SETPEND_Pos (0U) +#define NVIC_ISPR_SETPEND_Msk (0xFFFFFFFFU << NVIC_ISPR_SETPEND_Pos) /*!< 0xFFFFFFFF */ +#define NVIC_ISPR_SETPEND NVIC_ISPR_SETPEND_Msk /*!< Interrupt set-pending bits */ +#define NVIC_ISPR_SETPEND_0 (0x00000001U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00000001 */ +#define NVIC_ISPR_SETPEND_1 (0x00000002U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00000002 */ +#define NVIC_ISPR_SETPEND_2 (0x00000004U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00000004 */ +#define NVIC_ISPR_SETPEND_3 (0x00000008U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00000008 */ +#define NVIC_ISPR_SETPEND_4 (0x00000010U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00000010 */ +#define NVIC_ISPR_SETPEND_5 (0x00000020U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00000020 */ +#define NVIC_ISPR_SETPEND_6 (0x00000040U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00000040 */ +#define NVIC_ISPR_SETPEND_7 (0x00000080U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00000080 */ +#define NVIC_ISPR_SETPEND_8 (0x00000100U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00000100 */ +#define NVIC_ISPR_SETPEND_9 (0x00000200U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00000200 */ +#define NVIC_ISPR_SETPEND_10 (0x00000400U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00000400 */ +#define NVIC_ISPR_SETPEND_11 (0x00000800U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00000800 */ +#define NVIC_ISPR_SETPEND_12 (0x00001000U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00001000 */ +#define NVIC_ISPR_SETPEND_13 (0x00002000U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00002000 */ +#define NVIC_ISPR_SETPEND_14 (0x00004000U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00004000 */ +#define NVIC_ISPR_SETPEND_15 (0x00008000U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00008000 */ +#define NVIC_ISPR_SETPEND_16 (0x00010000U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00010000 */ +#define NVIC_ISPR_SETPEND_17 (0x00020000U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00020000 */ +#define NVIC_ISPR_SETPEND_18 (0x00040000U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00040000 */ +#define NVIC_ISPR_SETPEND_19 (0x00080000U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00080000 */ +#define NVIC_ISPR_SETPEND_20 (0x00100000U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00100000 */ +#define NVIC_ISPR_SETPEND_21 (0x00200000U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00200000 */ +#define NVIC_ISPR_SETPEND_22 (0x00400000U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00400000 */ +#define NVIC_ISPR_SETPEND_23 (0x00800000U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00800000 */ +#define NVIC_ISPR_SETPEND_24 (0x01000000U << NVIC_ISPR_SETPEND_Pos) /*!< 0x01000000 */ +#define NVIC_ISPR_SETPEND_25 (0x02000000U << NVIC_ISPR_SETPEND_Pos) /*!< 0x02000000 */ +#define NVIC_ISPR_SETPEND_26 (0x04000000U << NVIC_ISPR_SETPEND_Pos) /*!< 0x04000000 */ +#define NVIC_ISPR_SETPEND_27 (0x08000000U << NVIC_ISPR_SETPEND_Pos) /*!< 0x08000000 */ +#define NVIC_ISPR_SETPEND_28 (0x10000000U << NVIC_ISPR_SETPEND_Pos) /*!< 0x10000000 */ +#define NVIC_ISPR_SETPEND_29 (0x20000000U << NVIC_ISPR_SETPEND_Pos) /*!< 0x20000000 */ +#define NVIC_ISPR_SETPEND_30 (0x40000000U << NVIC_ISPR_SETPEND_Pos) /*!< 0x40000000 */ +#define NVIC_ISPR_SETPEND_31 (0x80000000U << NVIC_ISPR_SETPEND_Pos) /*!< 0x80000000 */ + +/****************** Bit definition for NVIC_ICPR register *******************/ +#define NVIC_ICPR_CLRPEND_Pos (0U) +#define NVIC_ICPR_CLRPEND_Msk (0xFFFFFFFFU << NVIC_ICPR_CLRPEND_Pos) /*!< 0xFFFFFFFF */ +#define NVIC_ICPR_CLRPEND NVIC_ICPR_CLRPEND_Msk /*!< Interrupt clear-pending bits */ +#define NVIC_ICPR_CLRPEND_0 (0x00000001U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00000001 */ +#define NVIC_ICPR_CLRPEND_1 (0x00000002U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00000002 */ +#define NVIC_ICPR_CLRPEND_2 (0x00000004U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00000004 */ +#define NVIC_ICPR_CLRPEND_3 (0x00000008U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00000008 */ +#define NVIC_ICPR_CLRPEND_4 (0x00000010U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00000010 */ +#define NVIC_ICPR_CLRPEND_5 (0x00000020U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00000020 */ +#define NVIC_ICPR_CLRPEND_6 (0x00000040U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00000040 */ +#define NVIC_ICPR_CLRPEND_7 (0x00000080U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00000080 */ +#define NVIC_ICPR_CLRPEND_8 (0x00000100U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00000100 */ +#define NVIC_ICPR_CLRPEND_9 (0x00000200U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00000200 */ +#define NVIC_ICPR_CLRPEND_10 (0x00000400U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00000400 */ +#define NVIC_ICPR_CLRPEND_11 (0x00000800U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00000800 */ +#define NVIC_ICPR_CLRPEND_12 (0x00001000U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00001000 */ +#define NVIC_ICPR_CLRPEND_13 (0x00002000U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00002000 */ +#define NVIC_ICPR_CLRPEND_14 (0x00004000U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00004000 */ +#define NVIC_ICPR_CLRPEND_15 (0x00008000U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00008000 */ +#define NVIC_ICPR_CLRPEND_16 (0x00010000U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00010000 */ +#define NVIC_ICPR_CLRPEND_17 (0x00020000U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00020000 */ +#define NVIC_ICPR_CLRPEND_18 (0x00040000U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00040000 */ +#define NVIC_ICPR_CLRPEND_19 (0x00080000U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00080000 */ +#define NVIC_ICPR_CLRPEND_20 (0x00100000U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00100000 */ +#define NVIC_ICPR_CLRPEND_21 (0x00200000U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00200000 */ +#define NVIC_ICPR_CLRPEND_22 (0x00400000U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00400000 */ +#define NVIC_ICPR_CLRPEND_23 (0x00800000U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00800000 */ +#define NVIC_ICPR_CLRPEND_24 (0x01000000U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x01000000 */ +#define NVIC_ICPR_CLRPEND_25 (0x02000000U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x02000000 */ +#define NVIC_ICPR_CLRPEND_26 (0x04000000U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x04000000 */ +#define NVIC_ICPR_CLRPEND_27 (0x08000000U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x08000000 */ +#define NVIC_ICPR_CLRPEND_28 (0x10000000U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x10000000 */ +#define NVIC_ICPR_CLRPEND_29 (0x20000000U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x20000000 */ +#define NVIC_ICPR_CLRPEND_30 (0x40000000U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x40000000 */ +#define NVIC_ICPR_CLRPEND_31 (0x80000000U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x80000000 */ + +/****************** Bit definition for NVIC_IABR register *******************/ +#define NVIC_IABR_ACTIVE_Pos (0U) +#define NVIC_IABR_ACTIVE_Msk (0xFFFFFFFFU << NVIC_IABR_ACTIVE_Pos) /*!< 0xFFFFFFFF */ +#define NVIC_IABR_ACTIVE NVIC_IABR_ACTIVE_Msk /*!< Interrupt active flags */ +#define NVIC_IABR_ACTIVE_0 (0x00000001U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00000001 */ +#define NVIC_IABR_ACTIVE_1 (0x00000002U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00000002 */ +#define NVIC_IABR_ACTIVE_2 (0x00000004U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00000004 */ +#define NVIC_IABR_ACTIVE_3 (0x00000008U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00000008 */ +#define NVIC_IABR_ACTIVE_4 (0x00000010U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00000010 */ +#define NVIC_IABR_ACTIVE_5 (0x00000020U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00000020 */ +#define NVIC_IABR_ACTIVE_6 (0x00000040U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00000040 */ +#define NVIC_IABR_ACTIVE_7 (0x00000080U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00000080 */ +#define NVIC_IABR_ACTIVE_8 (0x00000100U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00000100 */ +#define NVIC_IABR_ACTIVE_9 (0x00000200U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00000200 */ +#define NVIC_IABR_ACTIVE_10 (0x00000400U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00000400 */ +#define NVIC_IABR_ACTIVE_11 (0x00000800U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00000800 */ +#define NVIC_IABR_ACTIVE_12 (0x00001000U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00001000 */ +#define NVIC_IABR_ACTIVE_13 (0x00002000U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00002000 */ +#define NVIC_IABR_ACTIVE_14 (0x00004000U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00004000 */ +#define NVIC_IABR_ACTIVE_15 (0x00008000U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00008000 */ +#define NVIC_IABR_ACTIVE_16 (0x00010000U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00010000 */ +#define NVIC_IABR_ACTIVE_17 (0x00020000U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00020000 */ +#define NVIC_IABR_ACTIVE_18 (0x00040000U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00040000 */ +#define NVIC_IABR_ACTIVE_19 (0x00080000U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00080000 */ +#define NVIC_IABR_ACTIVE_20 (0x00100000U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00100000 */ +#define NVIC_IABR_ACTIVE_21 (0x00200000U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00200000 */ +#define NVIC_IABR_ACTIVE_22 (0x00400000U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00400000 */ +#define NVIC_IABR_ACTIVE_23 (0x00800000U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00800000 */ +#define NVIC_IABR_ACTIVE_24 (0x01000000U << NVIC_IABR_ACTIVE_Pos) /*!< 0x01000000 */ +#define NVIC_IABR_ACTIVE_25 (0x02000000U << NVIC_IABR_ACTIVE_Pos) /*!< 0x02000000 */ +#define NVIC_IABR_ACTIVE_26 (0x04000000U << NVIC_IABR_ACTIVE_Pos) /*!< 0x04000000 */ +#define NVIC_IABR_ACTIVE_27 (0x08000000U << NVIC_IABR_ACTIVE_Pos) /*!< 0x08000000 */ +#define NVIC_IABR_ACTIVE_28 (0x10000000U << NVIC_IABR_ACTIVE_Pos) /*!< 0x10000000 */ +#define NVIC_IABR_ACTIVE_29 (0x20000000U << NVIC_IABR_ACTIVE_Pos) /*!< 0x20000000 */ +#define NVIC_IABR_ACTIVE_30 (0x40000000U << NVIC_IABR_ACTIVE_Pos) /*!< 0x40000000 */ +#define NVIC_IABR_ACTIVE_31 (0x80000000U << NVIC_IABR_ACTIVE_Pos) /*!< 0x80000000 */ + +/****************** Bit definition for NVIC_PRI0 register *******************/ +#define NVIC_IPR0_PRI_0 ((uint32_t)0x000000FF) /*!< Priority of interrupt 0 */ +#define NVIC_IPR0_PRI_1 ((uint32_t)0x0000FF00) /*!< Priority of interrupt 1 */ +#define NVIC_IPR0_PRI_2 ((uint32_t)0x00FF0000) /*!< Priority of interrupt 2 */ +#define NVIC_IPR0_PRI_3 ((uint32_t)0xFF000000) /*!< Priority of interrupt 3 */ + +/****************** Bit definition for NVIC_PRI1 register *******************/ +#define NVIC_IPR1_PRI_4 ((uint32_t)0x000000FF) /*!< Priority of interrupt 4 */ +#define NVIC_IPR1_PRI_5 ((uint32_t)0x0000FF00) /*!< Priority of interrupt 5 */ +#define NVIC_IPR1_PRI_6 ((uint32_t)0x00FF0000) /*!< Priority of interrupt 6 */ +#define NVIC_IPR1_PRI_7 ((uint32_t)0xFF000000) /*!< Priority of interrupt 7 */ + +/****************** Bit definition for NVIC_PRI2 register *******************/ +#define NVIC_IPR2_PRI_8 ((uint32_t)0x000000FF) /*!< Priority of interrupt 8 */ +#define NVIC_IPR2_PRI_9 ((uint32_t)0x0000FF00) /*!< Priority of interrupt 9 */ +#define NVIC_IPR2_PRI_10 ((uint32_t)0x00FF0000) /*!< Priority of interrupt 10 */ +#define NVIC_IPR2_PRI_11 ((uint32_t)0xFF000000) /*!< Priority of interrupt 11 */ + +/****************** Bit definition for NVIC_PRI3 register *******************/ +#define NVIC_IPR3_PRI_12 ((uint32_t)0x000000FF) /*!< Priority of interrupt 12 */ +#define NVIC_IPR3_PRI_13 ((uint32_t)0x0000FF00) /*!< Priority of interrupt 13 */ +#define NVIC_IPR3_PRI_14 ((uint32_t)0x00FF0000) /*!< Priority of interrupt 14 */ +#define NVIC_IPR3_PRI_15 ((uint32_t)0xFF000000) /*!< Priority of interrupt 15 */ + +/****************** Bit definition for NVIC_PRI4 register *******************/ +#define NVIC_IPR4_PRI_16 ((uint32_t)0x000000FF) /*!< Priority of interrupt 16 */ +#define NVIC_IPR4_PRI_17 ((uint32_t)0x0000FF00) /*!< Priority of interrupt 17 */ +#define NVIC_IPR4_PRI_18 ((uint32_t)0x00FF0000) /*!< Priority of interrupt 18 */ +#define NVIC_IPR4_PRI_19 ((uint32_t)0xFF000000) /*!< Priority of interrupt 19 */ + +/****************** Bit definition for NVIC_PRI5 register *******************/ +#define NVIC_IPR5_PRI_20 ((uint32_t)0x000000FF) /*!< Priority of interrupt 20 */ +#define NVIC_IPR5_PRI_21 ((uint32_t)0x0000FF00) /*!< Priority of interrupt 21 */ +#define NVIC_IPR5_PRI_22 ((uint32_t)0x00FF0000) /*!< Priority of interrupt 22 */ +#define NVIC_IPR5_PRI_23 ((uint32_t)0xFF000000) /*!< Priority of interrupt 23 */ + +/****************** Bit definition for NVIC_PRI6 register *******************/ +#define NVIC_IPR6_PRI_24 ((uint32_t)0x000000FF) /*!< Priority of interrupt 24 */ +#define NVIC_IPR6_PRI_25 ((uint32_t)0x0000FF00) /*!< Priority of interrupt 25 */ +#define NVIC_IPR6_PRI_26 ((uint32_t)0x00FF0000) /*!< Priority of interrupt 26 */ +#define NVIC_IPR6_PRI_27 ((uint32_t)0xFF000000) /*!< Priority of interrupt 27 */ + +/****************** Bit definition for NVIC_PRI7 register *******************/ +#define NVIC_IPR7_PRI_28 ((uint32_t)0x000000FF) /*!< Priority of interrupt 28 */ +#define NVIC_IPR7_PRI_29 ((uint32_t)0x0000FF00) /*!< Priority of interrupt 29 */ +#define NVIC_IPR7_PRI_30 ((uint32_t)0x00FF0000) /*!< Priority of interrupt 30 */ +#define NVIC_IPR7_PRI_31 ((uint32_t)0xFF000000) /*!< Priority of interrupt 31 */ + +/****************** Bit definition for SCB_CPUID register *******************/ +#define SCB_CPUID_REVISION ((uint32_t)0x0000000F) /*!< Implementation defined revision number */ +#define SCB_CPUID_PARTNO ((uint32_t)0x0000FFF0) /*!< Number of processor within family */ +#define SCB_CPUID_Constant ((uint32_t)0x000F0000) /*!< Reads as 0x0F */ +#define SCB_CPUID_VARIANT ((uint32_t)0x00F00000) /*!< Implementation defined variant number */ +#define SCB_CPUID_IMPLEMENTER ((uint32_t)0xFF000000) /*!< Implementer code. ARM is 0x41 */ + +/******************* Bit definition for SCB_ICSR register *******************/ +#define SCB_ICSR_VECTACTIVE ((uint32_t)0x000001FF) /*!< Active ISR number field */ +#define SCB_ICSR_RETTOBASE ((uint32_t)0x00000800) /*!< All active exceptions minus the IPSR_current_exception yields the empty set */ +#define SCB_ICSR_VECTPENDING ((uint32_t)0x003FF000) /*!< Pending ISR number field */ +#define SCB_ICSR_ISRPENDING ((uint32_t)0x00400000) /*!< Interrupt pending flag */ +#define SCB_ICSR_ISRPREEMPT ((uint32_t)0x00800000) /*!< It indicates that a pending interrupt becomes active in the next running cycle */ +#define SCB_ICSR_PENDSTCLR ((uint32_t)0x02000000) /*!< Clear pending SysTick bit */ +#define SCB_ICSR_PENDSTSET ((uint32_t)0x04000000) /*!< Set pending SysTick bit */ +#define SCB_ICSR_PENDSVCLR ((uint32_t)0x08000000) /*!< Clear pending pendSV bit */ +#define SCB_ICSR_PENDSVSET ((uint32_t)0x10000000) /*!< Set pending pendSV bit */ +#define SCB_ICSR_NMIPENDSET ((uint32_t)0x80000000) /*!< Set pending NMI bit */ + +/******************* Bit definition for SCB_VTOR register *******************/ +#define SCB_VTOR_TBLOFF ((uint32_t)0x1FFFFF80) /*!< Vector table base offset field */ +#define SCB_VTOR_TBLBASE ((uint32_t)0x20000000) /*!< Table base in code(0) or RAM(1) */ + +/*!<***************** Bit definition for SCB_AIRCR register *******************/ +#define SCB_AIRCR_VECTRESET ((uint32_t)0x00000001) /*!< System Reset bit */ +#define SCB_AIRCR_VECTCLRACTIVE ((uint32_t)0x00000002) /*!< Clear active vector bit */ +#define SCB_AIRCR_SYSRESETREQ ((uint32_t)0x00000004) /*!< Requests chip control logic to generate a reset */ + +#define SCB_AIRCR_PRIGROUP ((uint32_t)0x00000700) /*!< PRIGROUP[2:0] bits (Priority group) */ +#define SCB_AIRCR_PRIGROUP_0 ((uint32_t)0x00000100) /*!< Bit 0 */ +#define SCB_AIRCR_PRIGROUP_1 ((uint32_t)0x00000200) /*!< Bit 1 */ +#define SCB_AIRCR_PRIGROUP_2 ((uint32_t)0x00000400) /*!< Bit 2 */ + +/* prority group configuration */ +#define SCB_AIRCR_PRIGROUP0 ((uint32_t)0x00000000) /*!< Priority group=0 (7 bits of pre-emption priority, 1 bit of subpriority) */ +#define SCB_AIRCR_PRIGROUP1 ((uint32_t)0x00000100) /*!< Priority group=1 (6 bits of pre-emption priority, 2 bits of subpriority) */ +#define SCB_AIRCR_PRIGROUP2 ((uint32_t)0x00000200) /*!< Priority group=2 (5 bits of pre-emption priority, 3 bits of subpriority) */ +#define SCB_AIRCR_PRIGROUP3 ((uint32_t)0x00000300) /*!< Priority group=3 (4 bits of pre-emption priority, 4 bits of subpriority) */ +#define SCB_AIRCR_PRIGROUP4 ((uint32_t)0x00000400) /*!< Priority group=4 (3 bits of pre-emption priority, 5 bits of subpriority) */ +#define SCB_AIRCR_PRIGROUP5 ((uint32_t)0x00000500) /*!< Priority group=5 (2 bits of pre-emption priority, 6 bits of subpriority) */ +#define SCB_AIRCR_PRIGROUP6 ((uint32_t)0x00000600) /*!< Priority group=6 (1 bit of pre-emption priority, 7 bits of subpriority) */ +#define SCB_AIRCR_PRIGROUP7 ((uint32_t)0x00000700) /*!< Priority group=7 (no pre-emption priority, 8 bits of subpriority) */ + +#define SCB_AIRCR_ENDIANESS ((uint32_t)0x00008000) /*!< Data endianness bit */ +#define SCB_AIRCR_VECTKEY ((uint32_t)0xFFFF0000) /*!< Register key (VECTKEY) - Reads as 0xFA05 (VECTKEYSTAT) */ + +/******************* Bit definition for SCB_SCR register ********************/ +#define SCB_SCR_SLEEPONEXIT ((uint32_t)0x00000002) /*!< Sleep on exit bit */ +#define SCB_SCR_SLEEPDEEP ((uint32_t)0x00000004) /*!< Sleep deep bit */ +#define SCB_SCR_SEVONPEND ((uint32_t)0x00000010) /*!< Wake up from WFE */ + +/******************** Bit definition for SCB_CCR register *******************/ +#define SCB_CCR_NONBASETHRDENA ((uint32_t)0x00000001) /*!< Thread mode can be entered from any level in Handler mode by controlled return value */ +#define SCB_CCR_USERSETMPEND ((uint32_t)0x00000002) /*!< Enables user code to write the Software Trigger Interrupt register to trigger (pend) a Main exception */ +#define SCB_CCR_UNALIGN_TRP ((uint32_t)0x00000008) /*!< Trap for unaligned access */ +#define SCB_CCR_DIV_0_TRP ((uint32_t)0x00000010) /*!< Trap on Divide by 0 */ +#define SCB_CCR_BFHFNMIGN ((uint32_t)0x00000100) /*!< Handlers running at priority -1 and -2 */ +#define SCB_CCR_STKALIGN ((uint32_t)0x00000200) /*!< On exception entry, the SP used prior to the exception is adjusted to be 8-byte aligned */ + +/******************* Bit definition for SCB_SHPR register ********************/ +#define SCB_SHPR_PRI_N_Pos (0U) +#define SCB_SHPR_PRI_N_Msk (0xFFU << SCB_SHPR_PRI_N_Pos) /*!< 0x000000FF */ +#define SCB_SHPR_PRI_N SCB_SHPR_PRI_N_Msk /*!< Priority of system handler 4,8, and 12. Mem Manage, reserved and Debug Monitor */ +#define SCB_SHPR_PRI_N1_Pos (8U) +#define SCB_SHPR_PRI_N1_Msk (0xFFU << SCB_SHPR_PRI_N1_Pos) /*!< 0x0000FF00 */ +#define SCB_SHPR_PRI_N1 SCB_SHPR_PRI_N1_Msk /*!< Priority of system handler 5,9, and 13. Bus Fault, reserved and reserved */ +#define SCB_SHPR_PRI_N2_Pos (16U) +#define SCB_SHPR_PRI_N2_Msk (0xFFU << SCB_SHPR_PRI_N2_Pos) /*!< 0x00FF0000 */ +#define SCB_SHPR_PRI_N2 SCB_SHPR_PRI_N2_Msk /*!< Priority of system handler 6,10, and 14. Usage Fault, reserved and PendSV */ +#define SCB_SHPR_PRI_N3_Pos (24U) +#define SCB_SHPR_PRI_N3_Msk (0xFFU << SCB_SHPR_PRI_N3_Pos) /*!< 0xFF000000 */ +#define SCB_SHPR_PRI_N3 SCB_SHPR_PRI_N3_Msk /*!< Priority of system handler 7,11, and 15. Reserved, SVCall and SysTick */ + +/****************** Bit definition for SCB_SHCSR register *******************/ +#define SCB_SHCSR_MEMFAULTACT ((uint32_t)0x00000001) /*!< MemManage is active */ +#define SCB_SHCSR_BUSFAULTACT ((uint32_t)0x00000002) /*!< BusFault is active */ +#define SCB_SHCSR_USGFAULTACT ((uint32_t)0x00000008) /*!< UsageFault is active */ +#define SCB_SHCSR_SVCALLACT ((uint32_t)0x00000080) /*!< SVCall is active */ +#define SCB_SHCSR_MONITORACT ((uint32_t)0x00000100) /*!< Monitor is active */ +#define SCB_SHCSR_PENDSVACT ((uint32_t)0x00000400) /*!< PendSV is active */ +#define SCB_SHCSR_SYSTICKACT ((uint32_t)0x00000800) /*!< SysTick is active */ +#define SCB_SHCSR_USGFAULTPENDED ((uint32_t)0x00001000) /*!< Usage Fault is pended */ +#define SCB_SHCSR_MEMFAULTPENDED ((uint32_t)0x00002000) /*!< MemManage is pended */ +#define SCB_SHCSR_BUSFAULTPENDED ((uint32_t)0x00004000) /*!< Bus Fault is pended */ +#define SCB_SHCSR_SVCALLPENDED ((uint32_t)0x00008000) /*!< SVCall is pended */ +#define SCB_SHCSR_MEMFAULTENA ((uint32_t)0x00010000) /*!< MemManage enable */ +#define SCB_SHCSR_BUSFAULTENA ((uint32_t)0x00020000) /*!< Bus Fault enable */ +#define SCB_SHCSR_USGFAULTENA ((uint32_t)0x00040000) /*!< UsageFault enable */ + +/******************* Bit definition for SCB_CFSR register *******************/ +/*!< MFSR */ +#define SCB_CFSR_IACCVIOL_Pos (0U) +#define SCB_CFSR_IACCVIOL_Msk (0x1U << SCB_CFSR_IACCVIOL_Pos) /*!< 0x00000001 */ +#define SCB_CFSR_IACCVIOL SCB_CFSR_IACCVIOL_Msk /*!< Instruction access violation */ +#define SCB_CFSR_DACCVIOL_Pos (1U) +#define SCB_CFSR_DACCVIOL_Msk (0x1U << SCB_CFSR_DACCVIOL_Pos) /*!< 0x00000002 */ +#define SCB_CFSR_DACCVIOL SCB_CFSR_DACCVIOL_Msk /*!< Data access violation */ +#define SCB_CFSR_MUNSTKERR_Pos (3U) +#define SCB_CFSR_MUNSTKERR_Msk (0x1U << SCB_CFSR_MUNSTKERR_Pos) /*!< 0x00000008 */ +#define SCB_CFSR_MUNSTKERR SCB_CFSR_MUNSTKERR_Msk /*!< Unstacking error */ +#define SCB_CFSR_MSTKERR_Pos (4U) +#define SCB_CFSR_MSTKERR_Msk (0x1U << SCB_CFSR_MSTKERR_Pos) /*!< 0x00000010 */ +#define SCB_CFSR_MSTKERR SCB_CFSR_MSTKERR_Msk /*!< Stacking error */ +#define SCB_CFSR_MMARVALID_Pos (7U) +#define SCB_CFSR_MMARVALID_Msk (0x1U << SCB_CFSR_MMARVALID_Pos) /*!< 0x00000080 */ +#define SCB_CFSR_MMARVALID SCB_CFSR_MMARVALID_Msk /*!< Memory Manage Address Register address valid flag */ +/*!< BFSR */ +#define SCB_CFSR_IBUSERR_Pos (8U) +#define SCB_CFSR_IBUSERR_Msk (0x1U << SCB_CFSR_IBUSERR_Pos) /*!< 0x00000100 */ +#define SCB_CFSR_IBUSERR SCB_CFSR_IBUSERR_Msk /*!< Instruction bus error flag */ +#define SCB_CFSR_PRECISERR_Pos (9U) +#define SCB_CFSR_PRECISERR_Msk (0x1U << SCB_CFSR_PRECISERR_Pos) /*!< 0x00000200 */ +#define SCB_CFSR_PRECISERR SCB_CFSR_PRECISERR_Msk /*!< Precise data bus error */ +#define SCB_CFSR_IMPRECISERR_Pos (10U) +#define SCB_CFSR_IMPRECISERR_Msk (0x1U << SCB_CFSR_IMPRECISERR_Pos) /*!< 0x00000400 */ +#define SCB_CFSR_IMPRECISERR SCB_CFSR_IMPRECISERR_Msk /*!< Imprecise data bus error */ +#define SCB_CFSR_UNSTKERR_Pos (11U) +#define SCB_CFSR_UNSTKERR_Msk (0x1U << SCB_CFSR_UNSTKERR_Pos) /*!< 0x00000800 */ +#define SCB_CFSR_UNSTKERR SCB_CFSR_UNSTKERR_Msk /*!< Unstacking error */ +#define SCB_CFSR_STKERR_Pos (12U) +#define SCB_CFSR_STKERR_Msk (0x1U << SCB_CFSR_STKERR_Pos) /*!< 0x00001000 */ +#define SCB_CFSR_STKERR SCB_CFSR_STKERR_Msk /*!< Stacking error */ +#define SCB_CFSR_BFARVALID_Pos (15U) +#define SCB_CFSR_BFARVALID_Msk (0x1U << SCB_CFSR_BFARVALID_Pos) /*!< 0x00008000 */ +#define SCB_CFSR_BFARVALID SCB_CFSR_BFARVALID_Msk /*!< Bus Fault Address Register address valid flag */ +/*!< UFSR */ +#define SCB_CFSR_UNDEFINSTR_Pos (16U) +#define SCB_CFSR_UNDEFINSTR_Msk (0x1U << SCB_CFSR_UNDEFINSTR_Pos) /*!< 0x00010000 */ +#define SCB_CFSR_UNDEFINSTR SCB_CFSR_UNDEFINSTR_Msk /*!< The processor attempt to execute an undefined instruction */ +#define SCB_CFSR_INVSTATE_Pos (17U) +#define SCB_CFSR_INVSTATE_Msk (0x1U << SCB_CFSR_INVSTATE_Pos) /*!< 0x00020000 */ +#define SCB_CFSR_INVSTATE SCB_CFSR_INVSTATE_Msk /*!< Invalid combination of EPSR and instruction */ +#define SCB_CFSR_INVPC_Pos (18U) +#define SCB_CFSR_INVPC_Msk (0x1U << SCB_CFSR_INVPC_Pos) /*!< 0x00040000 */ +#define SCB_CFSR_INVPC SCB_CFSR_INVPC_Msk /*!< Attempt to load EXC_RETURN into pc illegally */ +#define SCB_CFSR_NOCP_Pos (19U) +#define SCB_CFSR_NOCP_Msk (0x1U << SCB_CFSR_NOCP_Pos) /*!< 0x00080000 */ +#define SCB_CFSR_NOCP SCB_CFSR_NOCP_Msk /*!< Attempt to use a coprocessor instruction */ +#define SCB_CFSR_UNALIGNED_Pos (24U) +#define SCB_CFSR_UNALIGNED_Msk (0x1U << SCB_CFSR_UNALIGNED_Pos) /*!< 0x01000000 */ +#define SCB_CFSR_UNALIGNED SCB_CFSR_UNALIGNED_Msk /*!< Fault occurs when there is an attempt to make an unaligned memory access */ +#define SCB_CFSR_DIVBYZERO_Pos (25U) +#define SCB_CFSR_DIVBYZERO_Msk (0x1U << SCB_CFSR_DIVBYZERO_Pos) /*!< 0x02000000 */ +#define SCB_CFSR_DIVBYZERO SCB_CFSR_DIVBYZERO_Msk /*!< Fault occurs when SDIV or DIV instruction is used with a divisor of 0 */ + +/******************* Bit definition for SCB_HFSR register *******************/ +#define SCB_HFSR_VECTTBL ((uint32_t)0x00000002) /*!< Fault occurs because of vector table read on exception processing */ +#define SCB_HFSR_FORCED ((uint32_t)0x40000000) /*!< Hard Fault activated when a configurable Fault was received and cannot activate */ +#define SCB_HFSR_DEBUGEVT ((uint32_t)0x80000000) /*!< Fault related to debug */ + +/******************* Bit definition for SCB_DFSR register *******************/ +#define SCB_DFSR_HALTED ((uint32_t)0x00000001) /*!< Halt request flag */ +#define SCB_DFSR_BKPT ((uint32_t)0x00000002) /*!< BKPT flag */ +#define SCB_DFSR_DWTTRAP ((uint32_t)0x00000004) /*!< Data Watchpoint and Trace (DWT) flag */ +#define SCB_DFSR_VCATCH ((uint32_t)0x00000008) /*!< Vector catch flag */ +#define SCB_DFSR_EXTERNAL ((uint32_t)0x00000010) /*!< External debug request flag */ + +/******************* Bit definition for SCB_MMFAR register ******************/ +#define SCB_MMFAR_ADDRESS_Pos (0U) +#define SCB_MMFAR_ADDRESS_Msk (0xFFFFFFFFU << SCB_MMFAR_ADDRESS_Pos) /*!< 0xFFFFFFFF */ +#define SCB_MMFAR_ADDRESS SCB_MMFAR_ADDRESS_Msk /*!< Mem Manage fault address field */ + +/******************* Bit definition for SCB_BFAR register *******************/ +#define SCB_BFAR_ADDRESS_Pos (0U) +#define SCB_BFAR_ADDRESS_Msk (0xFFFFFFFFU << SCB_BFAR_ADDRESS_Pos) /*!< 0xFFFFFFFF */ +#define SCB_BFAR_ADDRESS SCB_BFAR_ADDRESS_Msk /*!< Bus fault address field */ + +/******************* Bit definition for SCB_afsr register *******************/ +#define SCB_AFSR_IMPDEF_Pos (0U) +#define SCB_AFSR_IMPDEF_Msk (0xFFFFFFFFU << SCB_AFSR_IMPDEF_Pos) /*!< 0xFFFFFFFF */ +#define SCB_AFSR_IMPDEF SCB_AFSR_IMPDEF_Msk /*!< Implementation defined */ + /******************************************************************************/ /* */ /* External Interrupt/Event Controller */ @@ -2651,6 +3076,9 @@ typedef struct #define EXTI_IMR_MR18_Pos (18U) #define EXTI_IMR_MR18_Msk (0x1U << EXTI_IMR_MR18_Pos) /*!< 0x00040000 */ #define EXTI_IMR_MR18 EXTI_IMR_MR18_Msk /*!< Interrupt Mask on line 18 */ +#define EXTI_IMR_MR19_Pos (19U) +#define EXTI_IMR_MR19_Msk (0x1U << EXTI_IMR_MR19_Pos) /*!< 0x00080000 */ +#define EXTI_IMR_MR19 EXTI_IMR_MR19_Msk /*!< Interrupt Mask on line 19 */ /* References Defines */ #define EXTI_IMR_IM0 EXTI_IMR_MR0 @@ -2672,8 +3100,8 @@ typedef struct #define EXTI_IMR_IM16 EXTI_IMR_MR16 #define EXTI_IMR_IM17 EXTI_IMR_MR17 #define EXTI_IMR_IM18 EXTI_IMR_MR18 -#define EXTI_IMR_IM 0x0007FFFFU /*!< Interrupt Mask All */ - +#define EXTI_IMR_IM19 EXTI_IMR_MR19 + /******************* Bit definition for EXTI_EMR register *******************/ #define EXTI_EMR_MR0_Pos (0U) #define EXTI_EMR_MR0_Msk (0x1U << EXTI_EMR_MR0_Pos) /*!< 0x00000001 */ @@ -2732,6 +3160,9 @@ typedef struct #define EXTI_EMR_MR18_Pos (18U) #define EXTI_EMR_MR18_Msk (0x1U << EXTI_EMR_MR18_Pos) /*!< 0x00040000 */ #define EXTI_EMR_MR18 EXTI_EMR_MR18_Msk /*!< Event Mask on line 18 */ +#define EXTI_EMR_MR19_Pos (19U) +#define EXTI_EMR_MR19_Msk (0x1U << EXTI_EMR_MR19_Pos) /*!< 0x00080000 */ +#define EXTI_EMR_MR19 EXTI_EMR_MR19_Msk /*!< Event Mask on line 19 */ /* References Defines */ #define EXTI_EMR_EM0 EXTI_EMR_MR0 @@ -2753,6 +3184,7 @@ typedef struct #define EXTI_EMR_EM16 EXTI_EMR_MR16 #define EXTI_EMR_EM17 EXTI_EMR_MR17 #define EXTI_EMR_EM18 EXTI_EMR_MR18 +#define EXTI_EMR_EM19 EXTI_EMR_MR19 /****************** Bit definition for EXTI_RTSR register *******************/ #define EXTI_RTSR_TR0_Pos (0U) @@ -2812,6 +3244,9 @@ typedef struct #define EXTI_RTSR_TR18_Pos (18U) #define EXTI_RTSR_TR18_Msk (0x1U << EXTI_RTSR_TR18_Pos) /*!< 0x00040000 */ #define EXTI_RTSR_TR18 EXTI_RTSR_TR18_Msk /*!< Rising trigger event configuration bit of line 18 */ +#define EXTI_RTSR_TR19_Pos (19U) +#define EXTI_RTSR_TR19_Msk (0x1U << EXTI_RTSR_TR19_Pos) /*!< 0x00080000 */ +#define EXTI_RTSR_TR19 EXTI_RTSR_TR19_Msk /*!< Rising trigger event configuration bit of line 19 */ /* References Defines */ #define EXTI_RTSR_RT0 EXTI_RTSR_TR0 @@ -2833,6 +3268,7 @@ typedef struct #define EXTI_RTSR_RT16 EXTI_RTSR_TR16 #define EXTI_RTSR_RT17 EXTI_RTSR_TR17 #define EXTI_RTSR_RT18 EXTI_RTSR_TR18 +#define EXTI_RTSR_RT19 EXTI_RTSR_TR19 /****************** Bit definition for EXTI_FTSR register *******************/ #define EXTI_FTSR_TR0_Pos (0U) @@ -2892,6 +3328,9 @@ typedef struct #define EXTI_FTSR_TR18_Pos (18U) #define EXTI_FTSR_TR18_Msk (0x1U << EXTI_FTSR_TR18_Pos) /*!< 0x00040000 */ #define EXTI_FTSR_TR18 EXTI_FTSR_TR18_Msk /*!< Falling trigger event configuration bit of line 18 */ +#define EXTI_FTSR_TR19_Pos (19U) +#define EXTI_FTSR_TR19_Msk (0x1U << EXTI_FTSR_TR19_Pos) /*!< 0x00080000 */ +#define EXTI_FTSR_TR19 EXTI_FTSR_TR19_Msk /*!< Falling trigger event configuration bit of line 19 */ /* References Defines */ #define EXTI_FTSR_FT0 EXTI_FTSR_TR0 @@ -2913,6 +3352,7 @@ typedef struct #define EXTI_FTSR_FT16 EXTI_FTSR_TR16 #define EXTI_FTSR_FT17 EXTI_FTSR_TR17 #define EXTI_FTSR_FT18 EXTI_FTSR_TR18 +#define EXTI_FTSR_FT19 EXTI_FTSR_TR19 /****************** Bit definition for EXTI_SWIER register ******************/ #define EXTI_SWIER_SWIER0_Pos (0U) @@ -2972,6 +3412,9 @@ typedef struct #define EXTI_SWIER_SWIER18_Pos (18U) #define EXTI_SWIER_SWIER18_Msk (0x1U << EXTI_SWIER_SWIER18_Pos) /*!< 0x00040000 */ #define EXTI_SWIER_SWIER18 EXTI_SWIER_SWIER18_Msk /*!< Software Interrupt on line 18 */ +#define EXTI_SWIER_SWIER19_Pos (19U) +#define EXTI_SWIER_SWIER19_Msk (0x1U << EXTI_SWIER_SWIER19_Pos) /*!< 0x00080000 */ +#define EXTI_SWIER_SWIER19 EXTI_SWIER_SWIER19_Msk /*!< Software Interrupt on line 19 */ /* References Defines */ #define EXTI_SWIER_SWI0 EXTI_SWIER_SWIER0 @@ -2993,6 +3436,7 @@ typedef struct #define EXTI_SWIER_SWI16 EXTI_SWIER_SWIER16 #define EXTI_SWIER_SWI17 EXTI_SWIER_SWIER17 #define EXTI_SWIER_SWI18 EXTI_SWIER_SWIER18 +#define EXTI_SWIER_SWI19 EXTI_SWIER_SWIER19 /******************* Bit definition for EXTI_PR register ********************/ #define EXTI_PR_PR0_Pos (0U) @@ -3052,6 +3496,9 @@ typedef struct #define EXTI_PR_PR18_Pos (18U) #define EXTI_PR_PR18_Msk (0x1U << EXTI_PR_PR18_Pos) /*!< 0x00040000 */ #define EXTI_PR_PR18 EXTI_PR_PR18_Msk /*!< Pending bit for line 18 */ +#define EXTI_PR_PR19_Pos (19U) +#define EXTI_PR_PR19_Msk (0x1U << EXTI_PR_PR19_Pos) /*!< 0x00080000 */ +#define EXTI_PR_PR19 EXTI_PR_PR19_Msk /*!< Pending bit for line 19 */ /* References Defines */ #define EXTI_PR_PIF0 EXTI_PR_PR0 @@ -3073,6 +3520,7 @@ typedef struct #define EXTI_PR_PIF16 EXTI_PR_PR16 #define EXTI_PR_PIF17 EXTI_PR_PR17 #define EXTI_PR_PIF18 EXTI_PR_PR18 +#define EXTI_PR_PIF19 EXTI_PR_PR19 /******************************************************************************/ /* */ @@ -3933,6 +4381,10 @@ typedef struct #define TIM_SMCR_SMS_1 (0x2U << TIM_SMCR_SMS_Pos) /*!< 0x00000002 */ #define TIM_SMCR_SMS_2 (0x4U << TIM_SMCR_SMS_Pos) /*!< 0x00000004 */ +#define TIM_SMCR_OCCS_Pos (3U) +#define TIM_SMCR_OCCS_Msk (0x1U << TIM_SMCR_OCCS_Pos) /*!< 0x00000008 */ +#define TIM_SMCR_OCCS TIM_SMCR_OCCS_Msk /*!< OCREF clear selection */ + #define TIM_SMCR_TS_Pos (4U) #define TIM_SMCR_TS_Msk (0x7U << TIM_SMCR_TS_Pos) /*!< 0x00000070 */ #define TIM_SMCR_TS TIM_SMCR_TS_Msk /*!
© COPYRIGHT(c) 2017 STMicroelectronics
+ *

© COPYRIGHT(c) 2016 STMicroelectronics

* * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: @@ -108,10 +108,10 @@ #endif /* USE_HAL_DRIVER */ /** - * @brief CMSIS Device version number V4.2.0 + * @brief CMSIS Device version number V4.0.0 */ -#define __STM32F1_CMSIS_VERSION_MAIN (0x04) /*!< [31:24] main version */ -#define __STM32F1_CMSIS_VERSION_SUB1 (0x02) /*!< [23:16] sub1 version */ +#define __STM32F1_CMSIS_VERSION_MAIN (0x04) /*!< [31:24] main version */ +#define __STM32F1_CMSIS_VERSION_SUB1 (0x01) /*!< [23:16] sub1 version */ #define __STM32F1_CMSIS_VERSION_SUB2 (0x00) /*!< [15:8] sub2 version */ #define __STM32F1_CMSIS_VERSION_RC (0x00) /*!< [7:0] release candidate */ #define __STM32F1_CMSIS_VERSION ((__STM32F1_CMSIS_VERSION_MAIN << 24)\ diff --git a/targets/TARGET_STM/TARGET_STM32F1/TARGET_BLUEPILL_F103C8/device/system_stm32f1xx.c b/targets/TARGET_STM/TARGET_STM32F1/TARGET_BLUEPILL_F103C8/device/system_stm32f1xx.c index 717c3cddfbd..4e27fcd17cd 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/TARGET_BLUEPILL_F103C8/device/system_stm32f1xx.c +++ b/targets/TARGET_STM/TARGET_STM32F1/TARGET_BLUEPILL_F103C8/device/system_stm32f1xx.c @@ -2,8 +2,8 @@ ****************************************************************************** * @file system_stm32f1xx.c * @author MCD Application Team - * @version V4.2.0 - * @date 31-March-2017 + * @version V4.1.0 + * @date 29-April-2016 * @brief CMSIS Cortex-M3 Device Peripheral Access Layer System Source File. * * 1. This file provides two functions and one global variable to be called from @@ -52,7 +52,7 @@ ****************************************************************************** * @attention * - *

© COPYRIGHT(c) 2017 STMicroelectronics

+ *

© COPYRIGHT(c) 2016 STMicroelectronics

* * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: @@ -111,12 +111,12 @@ */ #if !defined (HSE_VALUE) - #define HSE_VALUE 8000000U /*!< Default value of the External oscillator in Hz. + #define HSE_VALUE ((uint32_t)8000000) /*!< Default value of the External oscillator in Hz. This value can be provided and adapted by the user application. */ #endif /* HSE_VALUE */ #if !defined (HSI_VALUE) - #define HSI_VALUE 8000000U /*!< Default value of the Internal oscillator in Hz. + #define HSI_VALUE ((uint32_t)8000000) /*!< Default value of the Internal oscillator in Hz. This value can be provided and adapted by the user application. */ #endif /* HSI_VALUE */ @@ -128,7 +128,7 @@ /*!< Uncomment the following line if you need to relocate your vector Table in Internal SRAM. */ /* #define VECT_TAB_SRAM */ -#define VECT_TAB_OFFSET 0x00000000U /*!< Vector Table base offset field. +#define VECT_TAB_OFFSET 0x0 /*!< Vector Table base offset field. This value must be a multiple of 0x200. */ @@ -156,13 +156,13 @@ * Clock Definitions *******************************************************************************/ #if defined(STM32F100xB) ||defined(STM32F100xE) - uint32_t SystemCoreClock = 24000000U; /*!< System Clock Frequency (Core Clock) */ + uint32_t SystemCoreClock = 24000000; /*!< System Clock Frequency (Core Clock) */ #else /*!< HSI Selected as System Clock source */ - uint32_t SystemCoreClock = 72000000U; /*!< System Clock Frequency (Core Clock) */ + uint32_t SystemCoreClock = 72000000; /*!< System Clock Frequency (Core Clock) */ #endif -const uint8_t AHBPrescTable[16U] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 7, 8, 9}; -const uint8_t APBPrescTable[8U] = {0, 0, 0, 0, 1, 2, 3, 4}; +const uint8_t AHBPrescTable[16] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 7, 8, 9}; +const uint8_t APBPrescTable[8] = {0, 0, 0, 0, 1, 2, 3, 4}; /** * @} @@ -204,42 +204,42 @@ void SystemInit (void) { /* Reset the RCC clock configuration to the default reset state(for debug purpose) */ /* Set HSION bit */ - RCC->CR |= 0x00000001U; + RCC->CR |= (uint32_t)0x00000001; /* Reset SW, HPRE, PPRE1, PPRE2, ADCPRE and MCO bits */ #if !defined(STM32F105xC) && !defined(STM32F107xC) - RCC->CFGR &= 0xF8FF0000U; + RCC->CFGR &= (uint32_t)0xF8FF0000; #else - RCC->CFGR &= 0xF0FF0000U; + RCC->CFGR &= (uint32_t)0xF0FF0000; #endif /* STM32F105xC */ /* Reset HSEON, CSSON and PLLON bits */ - RCC->CR &= 0xFEF6FFFFU; + RCC->CR &= (uint32_t)0xFEF6FFFF; /* Reset HSEBYP bit */ - RCC->CR &= 0xFFFBFFFFU; + RCC->CR &= (uint32_t)0xFFFBFFFF; /* Reset PLLSRC, PLLXTPRE, PLLMUL and USBPRE/OTGFSPRE bits */ - RCC->CFGR &= 0xFF80FFFFU; + RCC->CFGR &= (uint32_t)0xFF80FFFF; #if defined(STM32F105xC) || defined(STM32F107xC) /* Reset PLL2ON and PLL3ON bits */ - RCC->CR &= 0xEBFFFFFFU; + RCC->CR &= (uint32_t)0xEBFFFFFF; /* Disable all interrupts and clear pending bits */ - RCC->CIR = 0x00FF0000U; + RCC->CIR = 0x00FF0000; /* Reset CFGR2 register */ - RCC->CFGR2 = 0x00000000U; + RCC->CFGR2 = 0x00000000; #elif defined(STM32F100xB) || defined(STM32F100xE) /* Disable all interrupts and clear pending bits */ - RCC->CIR = 0x009F0000U; + RCC->CIR = 0x009F0000; /* Reset CFGR2 register */ - RCC->CFGR2 = 0x00000000U; + RCC->CFGR2 = 0x00000000; #else /* Disable all interrupts and clear pending bits */ - RCC->CIR = 0x009F0000U; + RCC->CIR = 0x009F0000; #endif /* STM32F105xC */ #if defined(STM32F100xE) || defined(STM32F101xE) || defined(STM32F101xG) || defined(STM32F103xE) || defined(STM32F103xG) @@ -304,14 +304,14 @@ void SystemInit (void) */ void SystemCoreClockUpdate (void) { - uint32_t tmp = 0U, pllmull = 0U, pllsource = 0U; + uint32_t tmp = 0, pllmull = 0, pllsource = 0; #if defined(STM32F105xC) || defined(STM32F107xC) - uint32_t prediv1source = 0U, prediv1factor = 0U, prediv2factor = 0U, pll2mull = 0U; + uint32_t prediv1source = 0, prediv1factor = 0, prediv2factor = 0, pll2mull = 0; #endif /* STM32F105xC */ #if defined(STM32F100xB) || defined(STM32F100xE) - uint32_t prediv1factor = 0U; + uint32_t prediv1factor = 0; #endif /* STM32F100xB or STM32F100xE */ /* Get SYSCLK source -------------------------------------------------------*/ @@ -319,37 +319,37 @@ void SystemCoreClockUpdate (void) switch (tmp) { - case 0x00U: /* HSI used as system clock */ + case 0x00: /* HSI used as system clock */ SystemCoreClock = HSI_VALUE; break; - case 0x04U: /* HSE used as system clock */ + case 0x04: /* HSE used as system clock */ SystemCoreClock = HSE_VALUE; break; - case 0x08U: /* PLL used as system clock */ + case 0x08: /* PLL used as system clock */ /* Get PLL clock source and multiplication factor ----------------------*/ pllmull = RCC->CFGR & RCC_CFGR_PLLMULL; pllsource = RCC->CFGR & RCC_CFGR_PLLSRC; #if !defined(STM32F105xC) && !defined(STM32F107xC) - pllmull = ( pllmull >> 18U) + 2U; + pllmull = ( pllmull >> 18) + 2; - if (pllsource == 0x00U) + if (pllsource == 0x00) { /* HSI oscillator clock divided by 2 selected as PLL clock entry */ - SystemCoreClock = (HSI_VALUE >> 1U) * pllmull; + SystemCoreClock = (HSI_VALUE >> 1) * pllmull; } else { #if defined(STM32F100xB) || defined(STM32F100xE) - prediv1factor = (RCC->CFGR2 & RCC_CFGR2_PREDIV1) + 1U; + prediv1factor = (RCC->CFGR2 & RCC_CFGR2_PREDIV1) + 1; /* HSE oscillator clock selected as PREDIV1 clock entry */ SystemCoreClock = (HSE_VALUE / prediv1factor) * pllmull; #else /* HSE selected as PLL clock entry */ if ((RCC->CFGR & RCC_CFGR_PLLXTPRE) != (uint32_t)RESET) {/* HSE oscillator clock divided by 2 */ - SystemCoreClock = (HSE_VALUE >> 1U) * pllmull; + SystemCoreClock = (HSE_VALUE >> 1) * pllmull; } else { @@ -358,30 +358,30 @@ void SystemCoreClockUpdate (void) #endif } #else - pllmull = pllmull >> 18U; + pllmull = pllmull >> 18; - if (pllmull != 0x0DU) + if (pllmull != 0x0D) { - pllmull += 2U; + pllmull += 2; } else { /* PLL multiplication factor = PLL input clock * 6.5 */ - pllmull = 13U / 2U; + pllmull = 13 / 2; } - if (pllsource == 0x00U) + if (pllsource == 0x00) { /* HSI oscillator clock divided by 2 selected as PLL clock entry */ - SystemCoreClock = (HSI_VALUE >> 1U) * pllmull; + SystemCoreClock = (HSI_VALUE >> 1) * pllmull; } else {/* PREDIV1 selected as PLL clock entry */ /* Get PREDIV1 clock source and division factor */ prediv1source = RCC->CFGR2 & RCC_CFGR2_PREDIV1SRC; - prediv1factor = (RCC->CFGR2 & RCC_CFGR2_PREDIV1) + 1U; + prediv1factor = (RCC->CFGR2 & RCC_CFGR2_PREDIV1) + 1; - if (prediv1source == 0U) + if (prediv1source == 0) { /* HSE oscillator clock selected as PREDIV1 clock entry */ SystemCoreClock = (HSE_VALUE / prediv1factor) * pllmull; @@ -390,8 +390,8 @@ void SystemCoreClockUpdate (void) {/* PLL2 clock selected as PREDIV1 clock entry */ /* Get PREDIV2 division factor and PLL2 multiplication factor */ - prediv2factor = ((RCC->CFGR2 & RCC_CFGR2_PREDIV2) >> 4U) + 1U; - pll2mull = ((RCC->CFGR2 & RCC_CFGR2_PLL2MUL) >> 8U) + 2U; + prediv2factor = ((RCC->CFGR2 & RCC_CFGR2_PREDIV2) >> 4) + 1; + pll2mull = ((RCC->CFGR2 & RCC_CFGR2_PLL2MUL) >> 8 ) + 2; SystemCoreClock = (((HSE_VALUE / prediv2factor) * pll2mull) / prediv1factor) * pllmull; } } @@ -405,7 +405,7 @@ void SystemCoreClockUpdate (void) /* Compute HCLK clock frequency ----------------*/ /* Get HCLK prescaler */ - tmp = AHBPrescTable[((RCC->CFGR & RCC_CFGR_HPRE) >> 4U)]; + tmp = AHBPrescTable[((RCC->CFGR & RCC_CFGR_HPRE) >> 4)]; /* HCLK clock frequency */ SystemCoreClock >>= tmp; } @@ -434,13 +434,13 @@ void SystemInit_ExtMemCtl(void) required, then adjust the Register Addresses */ /* Enable FSMC clock */ - RCC->AHBENR = 0x00000114U; + RCC->AHBENR = 0x00000114; /* Delay after an RCC peripheral clock enabling */ tmpreg = READ_BIT(RCC->AHBENR, RCC_AHBENR_FSMCEN); /* Enable GPIOD, GPIOE, GPIOF and GPIOG clocks */ - RCC->APB2ENR = 0x000001E0U; + RCC->APB2ENR = 0x000001E0; /* Delay after an RCC peripheral clock enabling */ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_IOPDEN); @@ -453,23 +453,23 @@ void SystemInit_ExtMemCtl(void) /*---------------- NE3 configuration ----------------------------------------*/ /*---------------- NBL0, NBL1 configuration ---------------------------------*/ - GPIOD->CRL = 0x44BB44BBU; - GPIOD->CRH = 0xBBBBBBBBU; + GPIOD->CRL = 0x44BB44BB; + GPIOD->CRH = 0xBBBBBBBB; - GPIOE->CRL = 0xB44444BBU; - GPIOE->CRH = 0xBBBBBBBBU; + GPIOE->CRL = 0xB44444BB; + GPIOE->CRH = 0xBBBBBBBB; - GPIOF->CRL = 0x44BBBBBBU; - GPIOF->CRH = 0xBBBB4444U; + GPIOF->CRL = 0x44BBBBBB; + GPIOF->CRH = 0xBBBB4444; - GPIOG->CRL = 0x44BBBBBBU; - GPIOG->CRH = 0x444B4B44U; + GPIOG->CRL = 0x44BBBBBB; + GPIOG->CRH = 0x444B4B44; /*---------------- FSMC Configuration ---------------------------------------*/ /*---------------- Enable FSMC Bank1_SRAM Bank ------------------------------*/ - FSMC_Bank1->BTCR[4U] = 0x00001091U; - FSMC_Bank1->BTCR[5U] = 0x00110212U; + FSMC_Bank1->BTCR[4] = 0x00001091; + FSMC_Bank1->BTCR[5] = 0x00110212; } #endif /* DATA_IN_ExtSRAM */ #endif /* STM32F100xE || STM32F101xE || STM32F101xG || STM32F103xE || STM32F103xG */ diff --git a/targets/TARGET_STM/TARGET_STM32F1/TARGET_BLUEPILL_F103C8/device/system_stm32f1xx.h b/targets/TARGET_STM/TARGET_STM32F1/TARGET_BLUEPILL_F103C8/device/system_stm32f1xx.h index f2557fa9579..8efeb9aadbc 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/TARGET_BLUEPILL_F103C8/device/system_stm32f1xx.h +++ b/targets/TARGET_STM/TARGET_STM32F1/TARGET_BLUEPILL_F103C8/device/system_stm32f1xx.h @@ -2,13 +2,13 @@ ****************************************************************************** * @file system_stm32f10x.h * @author MCD Application Team - * @version V4.2.0 - * @date 31-March-2017 + * @version V4.1.0 + * @date 29-April-2016 * @brief CMSIS Cortex-M3 Device Peripheral Access Layer System Header File. ****************************************************************************** * @attention * - *

© COPYRIGHT(c) 2017 STMicroelectronics

+ *

© COPYRIGHT(c) 2016 STMicroelectronics

* * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: @@ -67,8 +67,8 @@ */ extern uint32_t SystemCoreClock; /*!< System Clock Frequency (Core Clock) */ -extern const uint8_t AHBPrescTable[16U]; /*!< AHB prescalers table values */ -extern const uint8_t APBPrescTable[8U]; /*!< APB prescalers table values */ +extern const uint8_t AHBPrescTable[16]; /*!< AHB prescalers table values */ +extern const uint8_t APBPrescTable[8]; /*!< APB prescalers table values */ /** * @} diff --git a/targets/TARGET_STM/TARGET_STM32F1/TARGET_DISCO_F100RB/PinNames.h b/targets/TARGET_STM/TARGET_STM32F1/TARGET_DISCO_F100RB/PinNames.h index a8a684f69c6..c8624a880c1 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/TARGET_DISCO_F100RB/PinNames.h +++ b/targets/TARGET_STM/TARGET_STM32F1/TARGET_DISCO_F100RB/PinNames.h @@ -150,8 +150,6 @@ typedef enum { LED3 = PC_9, LED4 = PC_8, USER_BUTTON = PA_0, - // Standardized button names - BUTTON1 = USER_BUTTON, USBTX = PA_2, USBRX = PA_3, I2C_SCL = PB_6, diff --git a/targets/TARGET_STM/TARGET_STM32F1/TARGET_DISCO_F100RB/device/hal_tick.h b/targets/TARGET_STM/TARGET_STM32F1/TARGET_DISCO_F100RB/device/hal_tick.h index 5872d57f7ae..608a14ff991 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/TARGET_DISCO_F100RB/device/hal_tick.h +++ b/targets/TARGET_STM/TARGET_STM32F1/TARGET_DISCO_F100RB/device/hal_tick.h @@ -44,10 +44,10 @@ #define TIM_MST TIM4 #define TIM_MST_IRQ TIM4_IRQn -#define TIM_MST_RCC __HAL_RCC_TIM4_CLK_ENABLE() +#define TIM_MST_RCC __TIM4_CLK_ENABLE() -#define TIM_MST_RESET_ON __HAL_RCC_TIM4_FORCE_RESET() -#define TIM_MST_RESET_OFF __HAL_RCC_TIM4_RELEASE_RESET() +#define TIM_MST_RESET_ON __TIM4_FORCE_RESET() +#define TIM_MST_RESET_OFF __TIM4_RELEASE_RESET() #define TIM_MST_16BIT 1 // 1=16-bit timer, 0=32-bit timer diff --git a/targets/TARGET_STM/TARGET_STM32F1/TARGET_DISCO_F100RB/device/stm32f100xb.h b/targets/TARGET_STM/TARGET_STM32F1/TARGET_DISCO_F100RB/device/stm32f100xb.h index fecc192071d..bebed071dd4 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/TARGET_DISCO_F100RB/device/stm32f100xb.h +++ b/targets/TARGET_STM/TARGET_STM32F1/TARGET_DISCO_F100RB/device/stm32f100xb.h @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f100xb.h * @author MCD Application Team - * @version V4.2.0 - * @date 31-March-2017 + * @version V4.1.0 + * @date 29-April-2016 * @brief CMSIS Cortex-M3 Device Peripheral Access Layer Header File. * This file contains all the peripheral register's definitions, bits * definitions and memory mapping for STM32F1xx devices. @@ -16,7 +16,7 @@ ****************************************************************************** * @attention * - *

© COPYRIGHT(c) 2017 STMicroelectronics

+ *

© COPYRIGHT(c) 2016 STMicroelectronics

* * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: @@ -65,10 +65,10 @@ /** * @brief Configuration of the Cortex-M3 Processor and Core Peripherals */ -#define __CM3_REV 0x0200U /*!< Core Revision r2p0 */ - #define __MPU_PRESENT 0U /*!< Other STM32 devices does not provide an MPU */ -#define __NVIC_PRIO_BITS 4U /*!< STM32 uses 4 Bits for the Priority Levels */ -#define __Vendor_SysTickConfig 0U /*!< Set to 1 if different SysTick Config is used */ + #define __MPU_PRESENT 0 /*!< Other STM32 devices does not provide an MPU */ +#define __CM3_REV 0x0200 /*!< Core Revision r2p0 */ +#define __NVIC_PRIO_BITS 4 /*!< STM32 uses 4 Bits for the Priority Levels */ +#define __Vendor_SysTickConfig 0 /*!< Set to 1 if different SysTick Config is used */ /** * @} @@ -141,6 +141,7 @@ typedef enum TIM7_IRQn = 55, /*!< TIM7 global Interrupt */ } IRQn_Type; + /** * @} */ @@ -554,73 +555,73 @@ typedef struct */ -#define FLASH_BASE 0x08000000U /*!< FLASH base address in the alias region */ -#define FLASH_BANK1_END 0x0801FFFFU /*!< FLASH END address of bank1 */ -#define SRAM_BASE 0x20000000U /*!< SRAM base address in the alias region */ -#define PERIPH_BASE 0x40000000U /*!< Peripheral base address in the alias region */ +#define FLASH_BASE ((uint32_t)0x08000000) /*!< FLASH base address in the alias region */ +#define FLASH_BANK1_END ((uint32_t)0x0801FFFF) /*!< FLASH END address of bank1 */ +#define SRAM_BASE ((uint32_t)0x20000000) /*!< SRAM base address in the alias region */ +#define PERIPH_BASE ((uint32_t)0x40000000) /*!< Peripheral base address in the alias region */ -#define SRAM_BB_BASE 0x22000000U /*!< SRAM base address in the bit-band region */ -#define PERIPH_BB_BASE 0x42000000U /*!< Peripheral base address in the bit-band region */ +#define SRAM_BB_BASE ((uint32_t)0x22000000) /*!< SRAM base address in the bit-band region */ +#define PERIPH_BB_BASE ((uint32_t)0x42000000) /*!< Peripheral base address in the bit-band region */ /*!< Peripheral memory map */ #define APB1PERIPH_BASE PERIPH_BASE -#define APB2PERIPH_BASE (PERIPH_BASE + 0x00010000U) -#define AHBPERIPH_BASE (PERIPH_BASE + 0x00020000U) - -#define TIM2_BASE (APB1PERIPH_BASE + 0x00000000U) -#define TIM3_BASE (APB1PERIPH_BASE + 0x00000400U) -#define TIM4_BASE (APB1PERIPH_BASE + 0x00000800U) -#define TIM6_BASE (APB1PERIPH_BASE + 0x00001000U) -#define TIM7_BASE (APB1PERIPH_BASE + 0x00001400U) -#define RTC_BASE (APB1PERIPH_BASE + 0x00002800U) -#define WWDG_BASE (APB1PERIPH_BASE + 0x00002C00U) -#define IWDG_BASE (APB1PERIPH_BASE + 0x00003000U) -#define SPI2_BASE (APB1PERIPH_BASE + 0x00003800U) -#define USART2_BASE (APB1PERIPH_BASE + 0x00004400U) -#define USART3_BASE (APB1PERIPH_BASE + 0x00004800U) -#define I2C1_BASE (APB1PERIPH_BASE + 0x00005400U) +#define APB2PERIPH_BASE (PERIPH_BASE + 0x10000) +#define AHBPERIPH_BASE (PERIPH_BASE + 0x20000) + +#define TIM2_BASE (APB1PERIPH_BASE + 0x0000) +#define TIM3_BASE (APB1PERIPH_BASE + 0x0400) +#define TIM4_BASE (APB1PERIPH_BASE + 0x0800) +#define TIM6_BASE (APB1PERIPH_BASE + 0x1000) +#define TIM7_BASE (APB1PERIPH_BASE + 0x1400) +#define RTC_BASE (APB1PERIPH_BASE + 0x2800) +#define WWDG_BASE (APB1PERIPH_BASE + 0x2C00) +#define IWDG_BASE (APB1PERIPH_BASE + 0x3000) +#define SPI2_BASE (APB1PERIPH_BASE + 0x3800) +#define USART2_BASE (APB1PERIPH_BASE + 0x4400) +#define USART3_BASE (APB1PERIPH_BASE + 0x4800) +#define I2C1_BASE (APB1PERIPH_BASE + 0x5400) #define I2C2_BASE (APB1PERIPH_BASE + 0x5800) -#define BKP_BASE (APB1PERIPH_BASE + 0x00006C00U) -#define PWR_BASE (APB1PERIPH_BASE + 0x00007000U) -#define DAC_BASE (APB1PERIPH_BASE + 0x00007400U) -#define CEC_BASE (APB1PERIPH_BASE + 0x00007800U) -#define AFIO_BASE (APB2PERIPH_BASE + 0x00000000U) -#define EXTI_BASE (APB2PERIPH_BASE + 0x00000400U) -#define GPIOA_BASE (APB2PERIPH_BASE + 0x00000800U) -#define GPIOB_BASE (APB2PERIPH_BASE + 0x00000C00U) -#define GPIOC_BASE (APB2PERIPH_BASE + 0x00001000U) -#define GPIOD_BASE (APB2PERIPH_BASE + 0x00001400U) -#define GPIOE_BASE (APB2PERIPH_BASE + 0x00001800U) -#define ADC1_BASE (APB2PERIPH_BASE + 0x00002400U) -#define TIM1_BASE (APB2PERIPH_BASE + 0x00002C00U) -#define SPI1_BASE (APB2PERIPH_BASE + 0x00003000U) -#define USART1_BASE (APB2PERIPH_BASE + 0x00003800U) -#define TIM15_BASE (APB2PERIPH_BASE + 0x00004000U) -#define TIM16_BASE (APB2PERIPH_BASE + 0x00004400U) -#define TIM17_BASE (APB2PERIPH_BASE + 0x00004800U) - -#define SDIO_BASE (PERIPH_BASE + 0x00018000U) - -#define DMA1_BASE (AHBPERIPH_BASE + 0x00000000U) -#define DMA1_Channel1_BASE (AHBPERIPH_BASE + 0x00000008U) -#define DMA1_Channel2_BASE (AHBPERIPH_BASE + 0x0000001CU) -#define DMA1_Channel3_BASE (AHBPERIPH_BASE + 0x00000030U) -#define DMA1_Channel4_BASE (AHBPERIPH_BASE + 0x00000044U) -#define DMA1_Channel5_BASE (AHBPERIPH_BASE + 0x00000058U) -#define DMA1_Channel6_BASE (AHBPERIPH_BASE + 0x0000006CU) -#define DMA1_Channel7_BASE (AHBPERIPH_BASE + 0x00000080U) -#define RCC_BASE (AHBPERIPH_BASE + 0x00001000U) -#define CRC_BASE (AHBPERIPH_BASE + 0x00003000U) - -#define FLASH_R_BASE (AHBPERIPH_BASE + 0x00002000U) /*!< Flash registers base address */ -#define FLASHSIZE_BASE 0x1FFFF7E0U /*!< FLASH Size register base address */ -#define UID_BASE 0x1FFFF7E8U /*!< Unique device ID register base address */ -#define OB_BASE 0x1FFFF800U /*!< Flash Option Bytes base address */ - - - -#define DBGMCU_BASE 0xE0042000U /*!< Debug MCU registers base address */ +#define BKP_BASE (APB1PERIPH_BASE + 0x6C00) +#define PWR_BASE (APB1PERIPH_BASE + 0x7000) +#define DAC_BASE (APB1PERIPH_BASE + 0x7400) +#define CEC_BASE (APB1PERIPH_BASE + 0x7800) +#define AFIO_BASE (APB2PERIPH_BASE + 0x0000) +#define EXTI_BASE (APB2PERIPH_BASE + 0x0400) +#define GPIOA_BASE (APB2PERIPH_BASE + 0x0800) +#define GPIOB_BASE (APB2PERIPH_BASE + 0x0C00) +#define GPIOC_BASE (APB2PERIPH_BASE + 0x1000) +#define GPIOD_BASE (APB2PERIPH_BASE + 0x1400) +#define GPIOE_BASE (APB2PERIPH_BASE + 0x1800) +#define ADC1_BASE (APB2PERIPH_BASE + 0x2400) +#define TIM1_BASE (APB2PERIPH_BASE + 0x2C00) +#define SPI1_BASE (APB2PERIPH_BASE + 0x3000) +#define USART1_BASE (APB2PERIPH_BASE + 0x3800) +#define TIM15_BASE (APB2PERIPH_BASE + 0x4000) +#define TIM16_BASE (APB2PERIPH_BASE + 0x4400) +#define TIM17_BASE (APB2PERIPH_BASE + 0x4800) + +#define SDIO_BASE (PERIPH_BASE + 0x18000) + +#define DMA1_BASE (AHBPERIPH_BASE + 0x0000) +#define DMA1_Channel1_BASE (AHBPERIPH_BASE + 0x0008) +#define DMA1_Channel2_BASE (AHBPERIPH_BASE + 0x001C) +#define DMA1_Channel3_BASE (AHBPERIPH_BASE + 0x0030) +#define DMA1_Channel4_BASE (AHBPERIPH_BASE + 0x0044) +#define DMA1_Channel5_BASE (AHBPERIPH_BASE + 0x0058) +#define DMA1_Channel6_BASE (AHBPERIPH_BASE + 0x006C) +#define DMA1_Channel7_BASE (AHBPERIPH_BASE + 0x0080) +#define RCC_BASE (AHBPERIPH_BASE + 0x1000) +#define CRC_BASE (AHBPERIPH_BASE + 0x3000) + +#define FLASH_R_BASE (AHBPERIPH_BASE + 0x2000) /*!< Flash registers base address */ +#define FLASHSIZE_BASE ((uint32_t)0x1FFFF7E0) /*!< FLASH Size register base address */ +#define UID_BASE ((uint32_t)0x1FFFF7E8) /*!< Unique device ID register base address */ +#define OB_BASE ((uint32_t)0x1FFFF800) /*!< Flash Option Bytes base address */ + + + +#define DBGMCU_BASE ((uint32_t)0xE0042000) /*!< Debug MCU registers base address */ @@ -632,53 +633,52 @@ typedef struct * @{ */ -#define TIM2 ((TIM_TypeDef *)TIM2_BASE) -#define TIM3 ((TIM_TypeDef *)TIM3_BASE) -#define TIM4 ((TIM_TypeDef *)TIM4_BASE) -#define TIM6 ((TIM_TypeDef *)TIM6_BASE) -#define TIM7 ((TIM_TypeDef *)TIM7_BASE) -#define RTC ((RTC_TypeDef *)RTC_BASE) -#define WWDG ((WWDG_TypeDef *)WWDG_BASE) -#define IWDG ((IWDG_TypeDef *)IWDG_BASE) -#define SPI2 ((SPI_TypeDef *)SPI2_BASE) -#define USART2 ((USART_TypeDef *)USART2_BASE) -#define USART3 ((USART_TypeDef *)USART3_BASE) -#define I2C1 ((I2C_TypeDef *)I2C1_BASE) -#define I2C2 ((I2C_TypeDef *)I2C2_BASE) -#define BKP ((BKP_TypeDef *)BKP_BASE) -#define PWR ((PWR_TypeDef *)PWR_BASE) -#define DAC1 ((DAC_TypeDef *)DAC_BASE) -#define DAC ((DAC_TypeDef *)DAC_BASE) /* Kept for legacy purpose */ -#define CEC ((CEC_TypeDef *)CEC_BASE) -#define AFIO ((AFIO_TypeDef *)AFIO_BASE) -#define EXTI ((EXTI_TypeDef *)EXTI_BASE) -#define GPIOA ((GPIO_TypeDef *)GPIOA_BASE) -#define GPIOB ((GPIO_TypeDef *)GPIOB_BASE) -#define GPIOC ((GPIO_TypeDef *)GPIOC_BASE) -#define GPIOD ((GPIO_TypeDef *)GPIOD_BASE) -#define GPIOE ((GPIO_TypeDef *)GPIOE_BASE) -#define ADC1 ((ADC_TypeDef *)ADC1_BASE) -#define ADC1_COMMON ((ADC_Common_TypeDef *)ADC1_BASE) -#define TIM1 ((TIM_TypeDef *)TIM1_BASE) -#define SPI1 ((SPI_TypeDef *)SPI1_BASE) -#define USART1 ((USART_TypeDef *)USART1_BASE) -#define TIM15 ((TIM_TypeDef *)TIM15_BASE) -#define TIM16 ((TIM_TypeDef *)TIM16_BASE) -#define TIM17 ((TIM_TypeDef *)TIM17_BASE) -#define SDIO ((SDIO_TypeDef *)SDIO_BASE) -#define DMA1 ((DMA_TypeDef *)DMA1_BASE) -#define DMA1_Channel1 ((DMA_Channel_TypeDef *)DMA1_Channel1_BASE) -#define DMA1_Channel2 ((DMA_Channel_TypeDef *)DMA1_Channel2_BASE) -#define DMA1_Channel3 ((DMA_Channel_TypeDef *)DMA1_Channel3_BASE) -#define DMA1_Channel4 ((DMA_Channel_TypeDef *)DMA1_Channel4_BASE) -#define DMA1_Channel5 ((DMA_Channel_TypeDef *)DMA1_Channel5_BASE) -#define DMA1_Channel6 ((DMA_Channel_TypeDef *)DMA1_Channel6_BASE) -#define DMA1_Channel7 ((DMA_Channel_TypeDef *)DMA1_Channel7_BASE) -#define RCC ((RCC_TypeDef *)RCC_BASE) -#define CRC ((CRC_TypeDef *)CRC_BASE) -#define FLASH ((FLASH_TypeDef *)FLASH_R_BASE) -#define OB ((OB_TypeDef *)OB_BASE) -#define DBGMCU ((DBGMCU_TypeDef *)DBGMCU_BASE) +#define TIM2 ((TIM_TypeDef *) TIM2_BASE) +#define TIM3 ((TIM_TypeDef *) TIM3_BASE) +#define TIM4 ((TIM_TypeDef *) TIM4_BASE) +#define TIM6 ((TIM_TypeDef *) TIM6_BASE) +#define TIM7 ((TIM_TypeDef *) TIM7_BASE) +#define RTC ((RTC_TypeDef *) RTC_BASE) +#define WWDG ((WWDG_TypeDef *) WWDG_BASE) +#define IWDG ((IWDG_TypeDef *) IWDG_BASE) +#define SPI2 ((SPI_TypeDef *) SPI2_BASE) +#define USART2 ((USART_TypeDef *) USART2_BASE) +#define USART3 ((USART_TypeDef *) USART3_BASE) +#define I2C1 ((I2C_TypeDef *) I2C1_BASE) +#define I2C2 ((I2C_TypeDef *) I2C2_BASE) +#define BKP ((BKP_TypeDef *) BKP_BASE) +#define PWR ((PWR_TypeDef *) PWR_BASE) +#define DAC ((DAC_TypeDef *) DAC_BASE) +#define CEC ((CEC_TypeDef *) CEC_BASE) +#define AFIO ((AFIO_TypeDef *) AFIO_BASE) +#define EXTI ((EXTI_TypeDef *) EXTI_BASE) +#define GPIOA ((GPIO_TypeDef *) GPIOA_BASE) +#define GPIOB ((GPIO_TypeDef *) GPIOB_BASE) +#define GPIOC ((GPIO_TypeDef *) GPIOC_BASE) +#define GPIOD ((GPIO_TypeDef *) GPIOD_BASE) +#define GPIOE ((GPIO_TypeDef *) GPIOE_BASE) +#define ADC1 ((ADC_TypeDef *) ADC1_BASE) +#define ADC1_COMMON ((ADC_Common_TypeDef *) ADC1_BASE) +#define TIM1 ((TIM_TypeDef *) TIM1_BASE) +#define SPI1 ((SPI_TypeDef *) SPI1_BASE) +#define USART1 ((USART_TypeDef *) USART1_BASE) +#define TIM15 ((TIM_TypeDef *) TIM15_BASE) +#define TIM16 ((TIM_TypeDef *) TIM16_BASE) +#define TIM17 ((TIM_TypeDef *) TIM17_BASE) +#define SDIO ((SDIO_TypeDef *) SDIO_BASE) +#define DMA1 ((DMA_TypeDef *) DMA1_BASE) +#define DMA1_Channel1 ((DMA_Channel_TypeDef *) DMA1_Channel1_BASE) +#define DMA1_Channel2 ((DMA_Channel_TypeDef *) DMA1_Channel2_BASE) +#define DMA1_Channel3 ((DMA_Channel_TypeDef *) DMA1_Channel3_BASE) +#define DMA1_Channel4 ((DMA_Channel_TypeDef *) DMA1_Channel4_BASE) +#define DMA1_Channel5 ((DMA_Channel_TypeDef *) DMA1_Channel5_BASE) +#define DMA1_Channel6 ((DMA_Channel_TypeDef *) DMA1_Channel6_BASE) +#define DMA1_Channel7 ((DMA_Channel_TypeDef *) DMA1_Channel7_BASE) +#define RCC ((RCC_TypeDef *) RCC_BASE) +#define CRC ((CRC_TypeDef *) CRC_BASE) +#define FLASH ((FLASH_TypeDef *) FLASH_R_BASE) +#define OB ((OB_TypeDef *) OB_BASE) +#define DBGMCU ((DBGMCU_TypeDef *) DBGMCU_BASE) /** @@ -749,24 +749,14 @@ typedef struct #define PWR_CR_PLS_2 (0x4U << PWR_CR_PLS_Pos) /*!< 0x00000080 */ /*!< PVD level configuration */ -#define PWR_CR_PLS_LEV0 0x00000000U /*!< PVD level 2.2V */ -#define PWR_CR_PLS_LEV1 0x00000020U /*!< PVD level 2.3V */ -#define PWR_CR_PLS_LEV2 0x00000040U /*!< PVD level 2.4V */ -#define PWR_CR_PLS_LEV3 0x00000060U /*!< PVD level 2.5V */ -#define PWR_CR_PLS_LEV4 0x00000080U /*!< PVD level 2.6V */ -#define PWR_CR_PLS_LEV5 0x000000A0U /*!< PVD level 2.7V */ -#define PWR_CR_PLS_LEV6 0x000000C0U /*!< PVD level 2.8V */ -#define PWR_CR_PLS_LEV7 0x000000E0U /*!< PVD level 2.9V */ - -/* Legacy defines */ -#define PWR_CR_PLS_2V2 PWR_CR_PLS_LEV0 -#define PWR_CR_PLS_2V3 PWR_CR_PLS_LEV1 -#define PWR_CR_PLS_2V4 PWR_CR_PLS_LEV2 -#define PWR_CR_PLS_2V5 PWR_CR_PLS_LEV3 -#define PWR_CR_PLS_2V6 PWR_CR_PLS_LEV4 -#define PWR_CR_PLS_2V7 PWR_CR_PLS_LEV5 -#define PWR_CR_PLS_2V8 PWR_CR_PLS_LEV6 -#define PWR_CR_PLS_2V9 PWR_CR_PLS_LEV7 +#define PWR_CR_PLS_2V2 ((uint32_t)0x00000000) /*!< PVD level 2.2V */ +#define PWR_CR_PLS_2V3 ((uint32_t)0x00000020) /*!< PVD level 2.3V */ +#define PWR_CR_PLS_2V4 ((uint32_t)0x00000040) /*!< PVD level 2.4V */ +#define PWR_CR_PLS_2V5 ((uint32_t)0x00000060) /*!< PVD level 2.5V */ +#define PWR_CR_PLS_2V6 ((uint32_t)0x00000080) /*!< PVD level 2.6V */ +#define PWR_CR_PLS_2V7 ((uint32_t)0x000000A0) /*!< PVD level 2.7V */ +#define PWR_CR_PLS_2V8 ((uint32_t)0x000000C0) /*!< PVD level 2.8V */ +#define PWR_CR_PLS_2V9 ((uint32_t)0x000000E0) /*!< PVD level 2.9V */ #define PWR_CR_DBP_Pos (8U) #define PWR_CR_DBP_Msk (0x1U << PWR_CR_DBP_Pos) /*!< 0x00000100 */ @@ -931,9 +921,9 @@ typedef struct #define RCC_CFGR_SW_0 (0x1U << RCC_CFGR_SW_Pos) /*!< 0x00000001 */ #define RCC_CFGR_SW_1 (0x2U << RCC_CFGR_SW_Pos) /*!< 0x00000002 */ -#define RCC_CFGR_SW_HSI 0x00000000U /*!< HSI selected as system clock */ -#define RCC_CFGR_SW_HSE 0x00000001U /*!< HSE selected as system clock */ -#define RCC_CFGR_SW_PLL 0x00000002U /*!< PLL selected as system clock */ +#define RCC_CFGR_SW_HSI ((uint32_t)0x00000000) /*!< HSI selected as system clock */ +#define RCC_CFGR_SW_HSE ((uint32_t)0x00000001) /*!< HSE selected as system clock */ +#define RCC_CFGR_SW_PLL ((uint32_t)0x00000002) /*!< PLL selected as system clock */ /*!< SWS configuration */ #define RCC_CFGR_SWS_Pos (2U) @@ -942,9 +932,9 @@ typedef struct #define RCC_CFGR_SWS_0 (0x1U << RCC_CFGR_SWS_Pos) /*!< 0x00000004 */ #define RCC_CFGR_SWS_1 (0x2U << RCC_CFGR_SWS_Pos) /*!< 0x00000008 */ -#define RCC_CFGR_SWS_HSI 0x00000000U /*!< HSI oscillator used as system clock */ -#define RCC_CFGR_SWS_HSE 0x00000004U /*!< HSE oscillator used as system clock */ -#define RCC_CFGR_SWS_PLL 0x00000008U /*!< PLL used as system clock */ +#define RCC_CFGR_SWS_HSI ((uint32_t)0x00000000) /*!< HSI oscillator used as system clock */ +#define RCC_CFGR_SWS_HSE ((uint32_t)0x00000004) /*!< HSE oscillator used as system clock */ +#define RCC_CFGR_SWS_PLL ((uint32_t)0x00000008) /*!< PLL used as system clock */ /*!< HPRE configuration */ #define RCC_CFGR_HPRE_Pos (4U) @@ -955,15 +945,15 @@ typedef struct #define RCC_CFGR_HPRE_2 (0x4U << RCC_CFGR_HPRE_Pos) /*!< 0x00000040 */ #define RCC_CFGR_HPRE_3 (0x8U << RCC_CFGR_HPRE_Pos) /*!< 0x00000080 */ -#define RCC_CFGR_HPRE_DIV1 0x00000000U /*!< SYSCLK not divided */ -#define RCC_CFGR_HPRE_DIV2 0x00000080U /*!< SYSCLK divided by 2 */ -#define RCC_CFGR_HPRE_DIV4 0x00000090U /*!< SYSCLK divided by 4 */ -#define RCC_CFGR_HPRE_DIV8 0x000000A0U /*!< SYSCLK divided by 8 */ -#define RCC_CFGR_HPRE_DIV16 0x000000B0U /*!< SYSCLK divided by 16 */ -#define RCC_CFGR_HPRE_DIV64 0x000000C0U /*!< SYSCLK divided by 64 */ -#define RCC_CFGR_HPRE_DIV128 0x000000D0U /*!< SYSCLK divided by 128 */ -#define RCC_CFGR_HPRE_DIV256 0x000000E0U /*!< SYSCLK divided by 256 */ -#define RCC_CFGR_HPRE_DIV512 0x000000F0U /*!< SYSCLK divided by 512 */ +#define RCC_CFGR_HPRE_DIV1 ((uint32_t)0x00000000) /*!< SYSCLK not divided */ +#define RCC_CFGR_HPRE_DIV2 ((uint32_t)0x00000080) /*!< SYSCLK divided by 2 */ +#define RCC_CFGR_HPRE_DIV4 ((uint32_t)0x00000090) /*!< SYSCLK divided by 4 */ +#define RCC_CFGR_HPRE_DIV8 ((uint32_t)0x000000A0) /*!< SYSCLK divided by 8 */ +#define RCC_CFGR_HPRE_DIV16 ((uint32_t)0x000000B0) /*!< SYSCLK divided by 16 */ +#define RCC_CFGR_HPRE_DIV64 ((uint32_t)0x000000C0) /*!< SYSCLK divided by 64 */ +#define RCC_CFGR_HPRE_DIV128 ((uint32_t)0x000000D0) /*!< SYSCLK divided by 128 */ +#define RCC_CFGR_HPRE_DIV256 ((uint32_t)0x000000E0) /*!< SYSCLK divided by 256 */ +#define RCC_CFGR_HPRE_DIV512 ((uint32_t)0x000000F0) /*!< SYSCLK divided by 512 */ /*!< PPRE1 configuration */ #define RCC_CFGR_PPRE1_Pos (8U) @@ -973,11 +963,11 @@ typedef struct #define RCC_CFGR_PPRE1_1 (0x2U << RCC_CFGR_PPRE1_Pos) /*!< 0x00000200 */ #define RCC_CFGR_PPRE1_2 (0x4U << RCC_CFGR_PPRE1_Pos) /*!< 0x00000400 */ -#define RCC_CFGR_PPRE1_DIV1 0x00000000U /*!< HCLK not divided */ -#define RCC_CFGR_PPRE1_DIV2 0x00000400U /*!< HCLK divided by 2 */ -#define RCC_CFGR_PPRE1_DIV4 0x00000500U /*!< HCLK divided by 4 */ -#define RCC_CFGR_PPRE1_DIV8 0x00000600U /*!< HCLK divided by 8 */ -#define RCC_CFGR_PPRE1_DIV16 0x00000700U /*!< HCLK divided by 16 */ +#define RCC_CFGR_PPRE1_DIV1 ((uint32_t)0x00000000) /*!< HCLK not divided */ +#define RCC_CFGR_PPRE1_DIV2 ((uint32_t)0x00000400) /*!< HCLK divided by 2 */ +#define RCC_CFGR_PPRE1_DIV4 ((uint32_t)0x00000500) /*!< HCLK divided by 4 */ +#define RCC_CFGR_PPRE1_DIV8 ((uint32_t)0x00000600) /*!< HCLK divided by 8 */ +#define RCC_CFGR_PPRE1_DIV16 ((uint32_t)0x00000700) /*!< HCLK divided by 16 */ /*!< PPRE2 configuration */ #define RCC_CFGR_PPRE2_Pos (11U) @@ -987,11 +977,11 @@ typedef struct #define RCC_CFGR_PPRE2_1 (0x2U << RCC_CFGR_PPRE2_Pos) /*!< 0x00001000 */ #define RCC_CFGR_PPRE2_2 (0x4U << RCC_CFGR_PPRE2_Pos) /*!< 0x00002000 */ -#define RCC_CFGR_PPRE2_DIV1 0x00000000U /*!< HCLK not divided */ -#define RCC_CFGR_PPRE2_DIV2 0x00002000U /*!< HCLK divided by 2 */ -#define RCC_CFGR_PPRE2_DIV4 0x00002800U /*!< HCLK divided by 4 */ -#define RCC_CFGR_PPRE2_DIV8 0x00003000U /*!< HCLK divided by 8 */ -#define RCC_CFGR_PPRE2_DIV16 0x00003800U /*!< HCLK divided by 16 */ +#define RCC_CFGR_PPRE2_DIV1 ((uint32_t)0x00000000) /*!< HCLK not divided */ +#define RCC_CFGR_PPRE2_DIV2 ((uint32_t)0x00002000) /*!< HCLK divided by 2 */ +#define RCC_CFGR_PPRE2_DIV4 ((uint32_t)0x00002800) /*!< HCLK divided by 4 */ +#define RCC_CFGR_PPRE2_DIV8 ((uint32_t)0x00003000) /*!< HCLK divided by 8 */ +#define RCC_CFGR_PPRE2_DIV16 ((uint32_t)0x00003800) /*!< HCLK divided by 16 */ /*!< ADCPPRE configuration */ #define RCC_CFGR_ADCPRE_Pos (14U) @@ -1000,10 +990,10 @@ typedef struct #define RCC_CFGR_ADCPRE_0 (0x1U << RCC_CFGR_ADCPRE_Pos) /*!< 0x00004000 */ #define RCC_CFGR_ADCPRE_1 (0x2U << RCC_CFGR_ADCPRE_Pos) /*!< 0x00008000 */ -#define RCC_CFGR_ADCPRE_DIV2 0x00000000U /*!< PCLK2 divided by 2 */ -#define RCC_CFGR_ADCPRE_DIV4 0x00004000U /*!< PCLK2 divided by 4 */ -#define RCC_CFGR_ADCPRE_DIV6 0x00008000U /*!< PCLK2 divided by 6 */ -#define RCC_CFGR_ADCPRE_DIV8 0x0000C000U /*!< PCLK2 divided by 8 */ +#define RCC_CFGR_ADCPRE_DIV2 ((uint32_t)0x00000000) /*!< PCLK2 divided by 2 */ +#define RCC_CFGR_ADCPRE_DIV4 ((uint32_t)0x00004000) /*!< PCLK2 divided by 4 */ +#define RCC_CFGR_ADCPRE_DIV6 ((uint32_t)0x00008000) /*!< PCLK2 divided by 6 */ +#define RCC_CFGR_ADCPRE_DIV8 ((uint32_t)0x0000C000) /*!< PCLK2 divided by 8 */ #define RCC_CFGR_PLLSRC_Pos (16U) #define RCC_CFGR_PLLSRC_Msk (0x1U << RCC_CFGR_PLLSRC_Pos) /*!< 0x00010000 */ @@ -1022,10 +1012,10 @@ typedef struct #define RCC_CFGR_PLLMULL_2 (0x4U << RCC_CFGR_PLLMULL_Pos) /*!< 0x00100000 */ #define RCC_CFGR_PLLMULL_3 (0x8U << RCC_CFGR_PLLMULL_Pos) /*!< 0x00200000 */ -#define RCC_CFGR_PLLXTPRE_PREDIV1 0x00000000U /*!< PREDIV1 clock not divided for PLL entry */ -#define RCC_CFGR_PLLXTPRE_PREDIV1_DIV2 0x00020000U /*!< PREDIV1 clock divided by 2 for PLL entry */ +#define RCC_CFGR_PLLXTPRE_PREDIV1 ((uint32_t)0x00000000) /*!< PREDIV1 clock not divided for PLL entry */ +#define RCC_CFGR_PLLXTPRE_PREDIV1_DIV2 ((uint32_t)0x00020000) /*!< PREDIV1 clock divided by 2 for PLL entry */ -#define RCC_CFGR_PLLMULL2 0x00000000U /*!< PLL input clock*2 */ +#define RCC_CFGR_PLLMULL2 ((uint32_t)0x00000000) /*!< PLL input clock*2 */ #define RCC_CFGR_PLLMULL3_Pos (18U) #define RCC_CFGR_PLLMULL3_Msk (0x1U << RCC_CFGR_PLLMULL3_Pos) /*!< 0x00040000 */ #define RCC_CFGR_PLLMULL3 RCC_CFGR_PLLMULL3_Msk /*!< PLL input clock*3 */ @@ -1077,22 +1067,22 @@ typedef struct #define RCC_CFGR_MCO_1 (0x2U << RCC_CFGR_MCO_Pos) /*!< 0x02000000 */ #define RCC_CFGR_MCO_2 (0x4U << RCC_CFGR_MCO_Pos) /*!< 0x04000000 */ -#define RCC_CFGR_MCO_NOCLOCK 0x00000000U /*!< No clock */ -#define RCC_CFGR_MCO_SYSCLK 0x04000000U /*!< System clock selected as MCO source */ -#define RCC_CFGR_MCO_HSI 0x05000000U /*!< HSI clock selected as MCO source */ -#define RCC_CFGR_MCO_HSE 0x06000000U /*!< HSE clock selected as MCO source */ -#define RCC_CFGR_MCO_PLLCLK_DIV2 0x07000000U /*!< PLL clock divided by 2 selected as MCO source */ +#define RCC_CFGR_MCO_NOCLOCK ((uint32_t)0x00000000) /*!< No clock */ +#define RCC_CFGR_MCO_SYSCLK ((uint32_t)0x04000000) /*!< System clock selected as MCO source */ +#define RCC_CFGR_MCO_HSI ((uint32_t)0x05000000) /*!< HSI clock selected as MCO source */ +#define RCC_CFGR_MCO_HSE ((uint32_t)0x06000000) /*!< HSE clock selected as MCO source */ +#define RCC_CFGR_MCO_PLLCLK_DIV2 ((uint32_t)0x07000000) /*!< PLL clock divided by 2 selected as MCO source */ /* Reference defines */ - #define RCC_CFGR_MCOSEL RCC_CFGR_MCO - #define RCC_CFGR_MCOSEL_0 RCC_CFGR_MCO_0 - #define RCC_CFGR_MCOSEL_1 RCC_CFGR_MCO_1 - #define RCC_CFGR_MCOSEL_2 RCC_CFGR_MCO_2 - #define RCC_CFGR_MCOSEL_NOCLOCK RCC_CFGR_MCO_NOCLOCK - #define RCC_CFGR_MCOSEL_SYSCLK RCC_CFGR_MCO_SYSCLK - #define RCC_CFGR_MCOSEL_HSI RCC_CFGR_MCO_HSI - #define RCC_CFGR_MCOSEL_HSE RCC_CFGR_MCO_HSE - #define RCC_CFGR_MCOSEL_PLL_DIV2 RCC_CFGR_MCO_PLLCLK_DIV2 + #define RCC_CFGR_MCOSEL RCC_CFGR_MCO + #define RCC_CFGR_MCOSEL_0 RCC_CFGR_MCO_0 + #define RCC_CFGR_MCOSEL_1 RCC_CFGR_MCO_1 + #define RCC_CFGR_MCOSEL_2 RCC_CFGR_MCO_2 + #define RCC_CFGR_MCOSEL_NOCLOCK RCC_CFGR_MCO_NOCLOCK + #define RCC_CFGR_MCOSEL_SYSCLK RCC_CFGR_MCO_SYSCLK + #define RCC_CFGR_MCOSEL_HSI RCC_CFGR_MCO_HSI + #define RCC_CFGR_MCOSEL_HSE RCC_CFGR_MCO_HSE + #define RCC_CFGR_MCOSEL_PLL_DIV2 RCC_CFGR_MCO_PLLCLK_DIV2 /*!<****************** Bit definition for RCC_CIR register ********************/ #define RCC_CIR_LSIRDYF_Pos (0U) @@ -1391,10 +1381,10 @@ typedef struct #define RCC_BDCR_RTCSEL_1 (0x2U << RCC_BDCR_RTCSEL_Pos) /*!< 0x00000200 */ /*!< RTC congiguration */ -#define RCC_BDCR_RTCSEL_NOCLOCK 0x00000000U /*!< No clock */ -#define RCC_BDCR_RTCSEL_LSE 0x00000100U /*!< LSE oscillator clock used as RTC clock */ -#define RCC_BDCR_RTCSEL_LSI 0x00000200U /*!< LSI oscillator clock used as RTC clock */ -#define RCC_BDCR_RTCSEL_HSE 0x00000300U /*!< HSE oscillator clock divided by 128 used as RTC clock */ +#define RCC_BDCR_RTCSEL_NOCLOCK ((uint32_t)0x00000000) /*!< No clock */ +#define RCC_BDCR_RTCSEL_LSE ((uint32_t)0x00000100) /*!< LSE oscillator clock used as RTC clock */ +#define RCC_BDCR_RTCSEL_LSI ((uint32_t)0x00000200) /*!< LSI oscillator clock used as RTC clock */ +#define RCC_BDCR_RTCSEL_HSE ((uint32_t)0x00000300) /*!< HSE oscillator clock divided by 128 used as RTC clock */ #define RCC_BDCR_RTCEN_Pos (15U) #define RCC_BDCR_RTCEN_Msk (0x1U << RCC_BDCR_RTCEN_Pos) /*!< 0x00008000 */ @@ -1443,7 +1433,7 @@ typedef struct #define RCC_CFGR2_PREDIV1_2 (0x4U << RCC_CFGR2_PREDIV1_Pos) /*!< 0x00000004 */ #define RCC_CFGR2_PREDIV1_3 (0x8U << RCC_CFGR2_PREDIV1_Pos) /*!< 0x00000008 */ -#define RCC_CFGR2_PREDIV1_DIV1 0x00000000U /*!< PREDIV1 input clock not divided */ +#define RCC_CFGR2_PREDIV1_DIV1 ((uint32_t)0x00000000) /*!< PREDIV1 input clock not divided */ #define RCC_CFGR2_PREDIV1_DIV2_Pos (0U) #define RCC_CFGR2_PREDIV1_DIV2_Msk (0x1U << RCC_CFGR2_PREDIV1_DIV2_Pos) /*!< 0x00000001 */ #define RCC_CFGR2_PREDIV1_DIV2 RCC_CFGR2_PREDIV1_DIV2_Msk /*!< PREDIV1 input clock divided by 2 */ @@ -2020,7 +2010,7 @@ typedef struct #define AFIO_EVCR_PIN_3 (0x8U << AFIO_EVCR_PIN_Pos) /*!< 0x00000008 */ /*!< PIN configuration */ -#define AFIO_EVCR_PIN_PX0 0x00000000U /*!< Pin 0 selected */ +#define AFIO_EVCR_PIN_PX0 ((uint32_t)0x00000000) /*!< Pin 0 selected */ #define AFIO_EVCR_PIN_PX1_Pos (0U) #define AFIO_EVCR_PIN_PX1_Msk (0x1U << AFIO_EVCR_PIN_PX1_Pos) /*!< 0x00000001 */ #define AFIO_EVCR_PIN_PX1 AFIO_EVCR_PIN_PX1_Msk /*!< Pin 1 selected */ @@ -2075,7 +2065,7 @@ typedef struct #define AFIO_EVCR_PORT_2 (0x4U << AFIO_EVCR_PORT_Pos) /*!< 0x00000040 */ /*!< PORT configuration */ -#define AFIO_EVCR_PORT_PA 0x00000000 /*!< Port A selected */ +#define AFIO_EVCR_PORT_PA ((uint32_t)0x00000000) /*!< Port A selected */ #define AFIO_EVCR_PORT_PB_Pos (4U) #define AFIO_EVCR_PORT_PB_Msk (0x1U << AFIO_EVCR_PORT_PB_Pos) /*!< 0x00000010 */ #define AFIO_EVCR_PORT_PB AFIO_EVCR_PORT_PB_Msk /*!< Port B selected */ @@ -2114,7 +2104,7 @@ typedef struct #define AFIO_MAPR_USART3_REMAP_1 (0x2U << AFIO_MAPR_USART3_REMAP_Pos) /*!< 0x00000020 */ /* USART3_REMAP configuration */ -#define AFIO_MAPR_USART3_REMAP_NOREMAP 0x00000000U /*!< No remap (TX/PB10, RX/PB11, CK/PB12, CTS/PB13, RTS/PB14) */ +#define AFIO_MAPR_USART3_REMAP_NOREMAP ((uint32_t)0x00000000) /*!< No remap (TX/PB10, RX/PB11, CK/PB12, CTS/PB13, RTS/PB14) */ #define AFIO_MAPR_USART3_REMAP_PARTIALREMAP_Pos (4U) #define AFIO_MAPR_USART3_REMAP_PARTIALREMAP_Msk (0x1U << AFIO_MAPR_USART3_REMAP_PARTIALREMAP_Pos) /*!< 0x00000010 */ #define AFIO_MAPR_USART3_REMAP_PARTIALREMAP AFIO_MAPR_USART3_REMAP_PARTIALREMAP_Msk /*!< Partial remap (TX/PC10, RX/PC11, CK/PC12, CTS/PB13, RTS/PB14) */ @@ -2129,7 +2119,7 @@ typedef struct #define AFIO_MAPR_TIM1_REMAP_1 (0x2U << AFIO_MAPR_TIM1_REMAP_Pos) /*!< 0x00000080 */ /*!< TIM1_REMAP configuration */ -#define AFIO_MAPR_TIM1_REMAP_NOREMAP 0x00000000U /*!< No remap (ETR/PA12, CH1/PA8, CH2/PA9, CH3/PA10, CH4/PA11, BKIN/PB12, CH1N/PB13, CH2N/PB14, CH3N/PB15) */ +#define AFIO_MAPR_TIM1_REMAP_NOREMAP ((uint32_t)0x00000000) /*!< No remap (ETR/PA12, CH1/PA8, CH2/PA9, CH3/PA10, CH4/PA11, BKIN/PB12, CH1N/PB13, CH2N/PB14, CH3N/PB15) */ #define AFIO_MAPR_TIM1_REMAP_PARTIALREMAP_Pos (6U) #define AFIO_MAPR_TIM1_REMAP_PARTIALREMAP_Msk (0x1U << AFIO_MAPR_TIM1_REMAP_PARTIALREMAP_Pos) /*!< 0x00000040 */ #define AFIO_MAPR_TIM1_REMAP_PARTIALREMAP AFIO_MAPR_TIM1_REMAP_PARTIALREMAP_Msk /*!< Partial remap (ETR/PA12, CH1/PA8, CH2/PA9, CH3/PA10, CH4/PA11, BKIN/PA6, CH1N/PA7, CH2N/PB0, CH3N/PB1) */ @@ -2144,7 +2134,7 @@ typedef struct #define AFIO_MAPR_TIM2_REMAP_1 (0x2U << AFIO_MAPR_TIM2_REMAP_Pos) /*!< 0x00000200 */ /*!< TIM2_REMAP configuration */ -#define AFIO_MAPR_TIM2_REMAP_NOREMAP 0x00000000U /*!< No remap (CH1/ETR/PA0, CH2/PA1, CH3/PA2, CH4/PA3) */ +#define AFIO_MAPR_TIM2_REMAP_NOREMAP ((uint32_t)0x00000000) /*!< No remap (CH1/ETR/PA0, CH2/PA1, CH3/PA2, CH4/PA3) */ #define AFIO_MAPR_TIM2_REMAP_PARTIALREMAP1_Pos (8U) #define AFIO_MAPR_TIM2_REMAP_PARTIALREMAP1_Msk (0x1U << AFIO_MAPR_TIM2_REMAP_PARTIALREMAP1_Pos) /*!< 0x00000100 */ #define AFIO_MAPR_TIM2_REMAP_PARTIALREMAP1 AFIO_MAPR_TIM2_REMAP_PARTIALREMAP1_Msk /*!< Partial remap (CH1/ETR/PA15, CH2/PB3, CH3/PA2, CH4/PA3) */ @@ -2162,7 +2152,7 @@ typedef struct #define AFIO_MAPR_TIM3_REMAP_1 (0x2U << AFIO_MAPR_TIM3_REMAP_Pos) /*!< 0x00000800 */ /*!< TIM3_REMAP configuration */ -#define AFIO_MAPR_TIM3_REMAP_NOREMAP 0x00000000U /*!< No remap (CH1/PA6, CH2/PA7, CH3/PB0, CH4/PB1) */ +#define AFIO_MAPR_TIM3_REMAP_NOREMAP ((uint32_t)0x00000000) /*!< No remap (CH1/PA6, CH2/PA7, CH3/PB0, CH4/PB1) */ #define AFIO_MAPR_TIM3_REMAP_PARTIALREMAP_Pos (11U) #define AFIO_MAPR_TIM3_REMAP_PARTIALREMAP_Msk (0x1U << AFIO_MAPR_TIM3_REMAP_PARTIALREMAP_Pos) /*!< 0x00000800 */ #define AFIO_MAPR_TIM3_REMAP_PARTIALREMAP AFIO_MAPR_TIM3_REMAP_PARTIALREMAP_Msk /*!< Partial remap (CH1/PB4, CH2/PB5, CH3/PB0, CH4/PB1) */ @@ -2187,7 +2177,7 @@ typedef struct #define AFIO_MAPR_SWJ_CFG_1 (0x2U << AFIO_MAPR_SWJ_CFG_Pos) /*!< 0x02000000 */ #define AFIO_MAPR_SWJ_CFG_2 (0x4U << AFIO_MAPR_SWJ_CFG_Pos) /*!< 0x04000000 */ -#define AFIO_MAPR_SWJ_CFG_RESET 0x00000000U /*!< Full SWJ (JTAG-DP + SW-DP) : Reset State */ +#define AFIO_MAPR_SWJ_CFG_RESET ((uint32_t)0x00000000) /*!< Full SWJ (JTAG-DP + SW-DP) : Reset State */ #define AFIO_MAPR_SWJ_CFG_NOJNTRST_Pos (24U) #define AFIO_MAPR_SWJ_CFG_NOJNTRST_Msk (0x1U << AFIO_MAPR_SWJ_CFG_NOJNTRST_Pos) /*!< 0x01000000 */ #define AFIO_MAPR_SWJ_CFG_NOJNTRST AFIO_MAPR_SWJ_CFG_NOJNTRST_Msk /*!< Full SWJ (JTAG-DP + SW-DP) but without JNTRST */ @@ -2214,7 +2204,7 @@ typedef struct #define AFIO_EXTICR1_EXTI3 AFIO_EXTICR1_EXTI3_Msk /*!< EXTI 3 configuration */ /*!< EXTI0 configuration */ -#define AFIO_EXTICR1_EXTI0_PA 0x00000000U /*!< PA[0] pin */ +#define AFIO_EXTICR1_EXTI0_PA ((uint32_t)0x00000000) /*!< PA[0] pin */ #define AFIO_EXTICR1_EXTI0_PB_Pos (0U) #define AFIO_EXTICR1_EXTI0_PB_Msk (0x1U << AFIO_EXTICR1_EXTI0_PB_Pos) /*!< 0x00000001 */ #define AFIO_EXTICR1_EXTI0_PB AFIO_EXTICR1_EXTI0_PB_Msk /*!< PB[0] pin */ @@ -2235,7 +2225,7 @@ typedef struct #define AFIO_EXTICR1_EXTI0_PG AFIO_EXTICR1_EXTI0_PG_Msk /*!< PG[0] pin */ /*!< EXTI1 configuration */ -#define AFIO_EXTICR1_EXTI1_PA 0x00000000U /*!< PA[1] pin */ +#define AFIO_EXTICR1_EXTI1_PA ((uint32_t)0x00000000) /*!< PA[1] pin */ #define AFIO_EXTICR1_EXTI1_PB_Pos (4U) #define AFIO_EXTICR1_EXTI1_PB_Msk (0x1U << AFIO_EXTICR1_EXTI1_PB_Pos) /*!< 0x00000010 */ #define AFIO_EXTICR1_EXTI1_PB AFIO_EXTICR1_EXTI1_PB_Msk /*!< PB[1] pin */ @@ -2256,7 +2246,7 @@ typedef struct #define AFIO_EXTICR1_EXTI1_PG AFIO_EXTICR1_EXTI1_PG_Msk /*!< PG[1] pin */ /*!< EXTI2 configuration */ -#define AFIO_EXTICR1_EXTI2_PA 0x00000000U /*!< PA[2] pin */ +#define AFIO_EXTICR1_EXTI2_PA ((uint32_t)0x00000000) /*!< PA[2] pin */ #define AFIO_EXTICR1_EXTI2_PB_Pos (8U) #define AFIO_EXTICR1_EXTI2_PB_Msk (0x1U << AFIO_EXTICR1_EXTI2_PB_Pos) /*!< 0x00000100 */ #define AFIO_EXTICR1_EXTI2_PB AFIO_EXTICR1_EXTI2_PB_Msk /*!< PB[2] pin */ @@ -2277,7 +2267,7 @@ typedef struct #define AFIO_EXTICR1_EXTI2_PG AFIO_EXTICR1_EXTI2_PG_Msk /*!< PG[2] pin */ /*!< EXTI3 configuration */ -#define AFIO_EXTICR1_EXTI3_PA 0x00000000U /*!< PA[3] pin */ +#define AFIO_EXTICR1_EXTI3_PA ((uint32_t)0x00000000) /*!< PA[3] pin */ #define AFIO_EXTICR1_EXTI3_PB_Pos (12U) #define AFIO_EXTICR1_EXTI3_PB_Msk (0x1U << AFIO_EXTICR1_EXTI3_PB_Pos) /*!< 0x00001000 */ #define AFIO_EXTICR1_EXTI3_PB AFIO_EXTICR1_EXTI3_PB_Msk /*!< PB[3] pin */ @@ -2312,7 +2302,7 @@ typedef struct #define AFIO_EXTICR2_EXTI7 AFIO_EXTICR2_EXTI7_Msk /*!< EXTI 7 configuration */ /*!< EXTI4 configuration */ -#define AFIO_EXTICR2_EXTI4_PA 0x00000000U /*!< PA[4] pin */ +#define AFIO_EXTICR2_EXTI4_PA ((uint32_t)0x00000000) /*!< PA[4] pin */ #define AFIO_EXTICR2_EXTI4_PB_Pos (0U) #define AFIO_EXTICR2_EXTI4_PB_Msk (0x1U << AFIO_EXTICR2_EXTI4_PB_Pos) /*!< 0x00000001 */ #define AFIO_EXTICR2_EXTI4_PB AFIO_EXTICR2_EXTI4_PB_Msk /*!< PB[4] pin */ @@ -2333,7 +2323,7 @@ typedef struct #define AFIO_EXTICR2_EXTI4_PG AFIO_EXTICR2_EXTI4_PG_Msk /*!< PG[4] pin */ /* EXTI5 configuration */ -#define AFIO_EXTICR2_EXTI5_PA 0x00000000U /*!< PA[5] pin */ +#define AFIO_EXTICR2_EXTI5_PA ((uint32_t)0x00000000) /*!< PA[5] pin */ #define AFIO_EXTICR2_EXTI5_PB_Pos (4U) #define AFIO_EXTICR2_EXTI5_PB_Msk (0x1U << AFIO_EXTICR2_EXTI5_PB_Pos) /*!< 0x00000010 */ #define AFIO_EXTICR2_EXTI5_PB AFIO_EXTICR2_EXTI5_PB_Msk /*!< PB[5] pin */ @@ -2354,7 +2344,7 @@ typedef struct #define AFIO_EXTICR2_EXTI5_PG AFIO_EXTICR2_EXTI5_PG_Msk /*!< PG[5] pin */ /*!< EXTI6 configuration */ -#define AFIO_EXTICR2_EXTI6_PA 0x00000000U /*!< PA[6] pin */ +#define AFIO_EXTICR2_EXTI6_PA ((uint32_t)0x00000000) /*!< PA[6] pin */ #define AFIO_EXTICR2_EXTI6_PB_Pos (8U) #define AFIO_EXTICR2_EXTI6_PB_Msk (0x1U << AFIO_EXTICR2_EXTI6_PB_Pos) /*!< 0x00000100 */ #define AFIO_EXTICR2_EXTI6_PB AFIO_EXTICR2_EXTI6_PB_Msk /*!< PB[6] pin */ @@ -2375,7 +2365,7 @@ typedef struct #define AFIO_EXTICR2_EXTI6_PG AFIO_EXTICR2_EXTI6_PG_Msk /*!< PG[6] pin */ /*!< EXTI7 configuration */ -#define AFIO_EXTICR2_EXTI7_PA 0x00000000U /*!< PA[7] pin */ +#define AFIO_EXTICR2_EXTI7_PA ((uint32_t)0x00000000) /*!< PA[7] pin */ #define AFIO_EXTICR2_EXTI7_PB_Pos (12U) #define AFIO_EXTICR2_EXTI7_PB_Msk (0x1U << AFIO_EXTICR2_EXTI7_PB_Pos) /*!< 0x00001000 */ #define AFIO_EXTICR2_EXTI7_PB AFIO_EXTICR2_EXTI7_PB_Msk /*!< PB[7] pin */ @@ -2410,7 +2400,7 @@ typedef struct #define AFIO_EXTICR3_EXTI11 AFIO_EXTICR3_EXTI11_Msk /*!< EXTI 11 configuration */ /*!< EXTI8 configuration */ -#define AFIO_EXTICR3_EXTI8_PA 0x00000000U /*!< PA[8] pin */ +#define AFIO_EXTICR3_EXTI8_PA ((uint32_t)0x00000000) /*!< PA[8] pin */ #define AFIO_EXTICR3_EXTI8_PB_Pos (0U) #define AFIO_EXTICR3_EXTI8_PB_Msk (0x1U << AFIO_EXTICR3_EXTI8_PB_Pos) /*!< 0x00000001 */ #define AFIO_EXTICR3_EXTI8_PB AFIO_EXTICR3_EXTI8_PB_Msk /*!< PB[8] pin */ @@ -2431,7 +2421,7 @@ typedef struct #define AFIO_EXTICR3_EXTI8_PG AFIO_EXTICR3_EXTI8_PG_Msk /*!< PG[8] pin */ /*!< EXTI9 configuration */ -#define AFIO_EXTICR3_EXTI9_PA 0x00000000U /*!< PA[9] pin */ +#define AFIO_EXTICR3_EXTI9_PA ((uint32_t)0x00000000) /*!< PA[9] pin */ #define AFIO_EXTICR3_EXTI9_PB_Pos (4U) #define AFIO_EXTICR3_EXTI9_PB_Msk (0x1U << AFIO_EXTICR3_EXTI9_PB_Pos) /*!< 0x00000010 */ #define AFIO_EXTICR3_EXTI9_PB AFIO_EXTICR3_EXTI9_PB_Msk /*!< PB[9] pin */ @@ -2452,7 +2442,7 @@ typedef struct #define AFIO_EXTICR3_EXTI9_PG AFIO_EXTICR3_EXTI9_PG_Msk /*!< PG[9] pin */ /*!< EXTI10 configuration */ -#define AFIO_EXTICR3_EXTI10_PA 0x00000000U /*!< PA[10] pin */ +#define AFIO_EXTICR3_EXTI10_PA ((uint32_t)0x00000000) /*!< PA[10] pin */ #define AFIO_EXTICR3_EXTI10_PB_Pos (8U) #define AFIO_EXTICR3_EXTI10_PB_Msk (0x1U << AFIO_EXTICR3_EXTI10_PB_Pos) /*!< 0x00000100 */ #define AFIO_EXTICR3_EXTI10_PB AFIO_EXTICR3_EXTI10_PB_Msk /*!< PB[10] pin */ @@ -2473,7 +2463,7 @@ typedef struct #define AFIO_EXTICR3_EXTI10_PG AFIO_EXTICR3_EXTI10_PG_Msk /*!< PG[10] pin */ /*!< EXTI11 configuration */ -#define AFIO_EXTICR3_EXTI11_PA 0x00000000U /*!< PA[11] pin */ +#define AFIO_EXTICR3_EXTI11_PA ((uint32_t)0x00000000) /*!< PA[11] pin */ #define AFIO_EXTICR3_EXTI11_PB_Pos (12U) #define AFIO_EXTICR3_EXTI11_PB_Msk (0x1U << AFIO_EXTICR3_EXTI11_PB_Pos) /*!< 0x00001000 */ #define AFIO_EXTICR3_EXTI11_PB AFIO_EXTICR3_EXTI11_PB_Msk /*!< PB[11] pin */ @@ -2508,7 +2498,7 @@ typedef struct #define AFIO_EXTICR4_EXTI15 AFIO_EXTICR4_EXTI15_Msk /*!< EXTI 15 configuration */ /* EXTI12 configuration */ -#define AFIO_EXTICR4_EXTI12_PA 0x00000000U /*!< PA[12] pin */ +#define AFIO_EXTICR4_EXTI12_PA ((uint32_t)0x00000000) /*!< PA[12] pin */ #define AFIO_EXTICR4_EXTI12_PB_Pos (0U) #define AFIO_EXTICR4_EXTI12_PB_Msk (0x1U << AFIO_EXTICR4_EXTI12_PB_Pos) /*!< 0x00000001 */ #define AFIO_EXTICR4_EXTI12_PB AFIO_EXTICR4_EXTI12_PB_Msk /*!< PB[12] pin */ @@ -2529,7 +2519,7 @@ typedef struct #define AFIO_EXTICR4_EXTI12_PG AFIO_EXTICR4_EXTI12_PG_Msk /*!< PG[12] pin */ /* EXTI13 configuration */ -#define AFIO_EXTICR4_EXTI13_PA 0x00000000U /*!< PA[13] pin */ +#define AFIO_EXTICR4_EXTI13_PA ((uint32_t)0x00000000) /*!< PA[13] pin */ #define AFIO_EXTICR4_EXTI13_PB_Pos (4U) #define AFIO_EXTICR4_EXTI13_PB_Msk (0x1U << AFIO_EXTICR4_EXTI13_PB_Pos) /*!< 0x00000010 */ #define AFIO_EXTICR4_EXTI13_PB AFIO_EXTICR4_EXTI13_PB_Msk /*!< PB[13] pin */ @@ -2550,7 +2540,7 @@ typedef struct #define AFIO_EXTICR4_EXTI13_PG AFIO_EXTICR4_EXTI13_PG_Msk /*!< PG[13] pin */ /*!< EXTI14 configuration */ -#define AFIO_EXTICR4_EXTI14_PA 0x00000000U /*!< PA[14] pin */ +#define AFIO_EXTICR4_EXTI14_PA ((uint32_t)0x00000000) /*!< PA[14] pin */ #define AFIO_EXTICR4_EXTI14_PB_Pos (8U) #define AFIO_EXTICR4_EXTI14_PB_Msk (0x1U << AFIO_EXTICR4_EXTI14_PB_Pos) /*!< 0x00000100 */ #define AFIO_EXTICR4_EXTI14_PB AFIO_EXTICR4_EXTI14_PB_Msk /*!< PB[14] pin */ @@ -2571,7 +2561,7 @@ typedef struct #define AFIO_EXTICR4_EXTI14_PG AFIO_EXTICR4_EXTI14_PG_Msk /*!< PG[14] pin */ /*!< EXTI15 configuration */ -#define AFIO_EXTICR4_EXTI15_PA 0x00000000U /*!< PA[15] pin */ +#define AFIO_EXTICR4_EXTI15_PA ((uint32_t)0x00000000) /*!< PA[15] pin */ #define AFIO_EXTICR4_EXTI15_PB_Pos (12U) #define AFIO_EXTICR4_EXTI15_PB_Msk (0x1U << AFIO_EXTICR4_EXTI15_PB_Pos) /*!< 0x00001000 */ #define AFIO_EXTICR4_EXTI15_PB AFIO_EXTICR4_EXTI15_PB_Msk /*!< PB[15] pin */ @@ -2613,6 +2603,440 @@ typedef struct #define AFIO_MAPR2_TIM67_DAC_DMA_REMAP AFIO_MAPR2_TIM67_DAC_DMA_REMAP_Msk /*!< TIM6/TIM7 and DAC DMA remapping */ +/******************************************************************************/ +/* */ +/* SystemTick */ +/* */ +/******************************************************************************/ + +/***************** Bit definition for SysTick_CTRL register *****************/ +#define SysTick_CTRL_ENABLE ((uint32_t)0x00000001) /*!< Counter enable */ +#define SysTick_CTRL_TICKINT ((uint32_t)0x00000002) /*!< Counting down to 0 pends the SysTick handler */ +#define SysTick_CTRL_CLKSOURCE ((uint32_t)0x00000004) /*!< Clock source */ +#define SysTick_CTRL_COUNTFLAG ((uint32_t)0x00010000) /*!< Count Flag */ + +/***************** Bit definition for SysTick_LOAD register *****************/ +#define SysTick_LOAD_RELOAD ((uint32_t)0x00FFFFFF) /*!< Value to load into the SysTick Current Value Register when the counter reaches 0 */ + +/***************** Bit definition for SysTick_VAL register ******************/ +#define SysTick_VAL_CURRENT ((uint32_t)0x00FFFFFF) /*!< Current value at the time the register is accessed */ + +/***************** Bit definition for SysTick_CALIB register ****************/ +#define SysTick_CALIB_TENMS ((uint32_t)0x00FFFFFF) /*!< Reload value to use for 10ms timing */ +#define SysTick_CALIB_SKEW ((uint32_t)0x40000000) /*!< Calibration value is not exactly 10 ms */ +#define SysTick_CALIB_NOREF ((uint32_t)0x80000000) /*!< The reference clock is not provided */ + +/******************************************************************************/ +/* */ +/* Nested Vectored Interrupt Controller */ +/* */ +/******************************************************************************/ + +/****************** Bit definition for NVIC_ISER register *******************/ +#define NVIC_ISER_SETENA_Pos (0U) +#define NVIC_ISER_SETENA_Msk (0xFFFFFFFFU << NVIC_ISER_SETENA_Pos) /*!< 0xFFFFFFFF */ +#define NVIC_ISER_SETENA NVIC_ISER_SETENA_Msk /*!< Interrupt set enable bits */ +#define NVIC_ISER_SETENA_0 (0x00000001U << NVIC_ISER_SETENA_Pos) /*!< 0x00000001 */ +#define NVIC_ISER_SETENA_1 (0x00000002U << NVIC_ISER_SETENA_Pos) /*!< 0x00000002 */ +#define NVIC_ISER_SETENA_2 (0x00000004U << NVIC_ISER_SETENA_Pos) /*!< 0x00000004 */ +#define NVIC_ISER_SETENA_3 (0x00000008U << NVIC_ISER_SETENA_Pos) /*!< 0x00000008 */ +#define NVIC_ISER_SETENA_4 (0x00000010U << NVIC_ISER_SETENA_Pos) /*!< 0x00000010 */ +#define NVIC_ISER_SETENA_5 (0x00000020U << NVIC_ISER_SETENA_Pos) /*!< 0x00000020 */ +#define NVIC_ISER_SETENA_6 (0x00000040U << NVIC_ISER_SETENA_Pos) /*!< 0x00000040 */ +#define NVIC_ISER_SETENA_7 (0x00000080U << NVIC_ISER_SETENA_Pos) /*!< 0x00000080 */ +#define NVIC_ISER_SETENA_8 (0x00000100U << NVIC_ISER_SETENA_Pos) /*!< 0x00000100 */ +#define NVIC_ISER_SETENA_9 (0x00000200U << NVIC_ISER_SETENA_Pos) /*!< 0x00000200 */ +#define NVIC_ISER_SETENA_10 (0x00000400U << NVIC_ISER_SETENA_Pos) /*!< 0x00000400 */ +#define NVIC_ISER_SETENA_11 (0x00000800U << NVIC_ISER_SETENA_Pos) /*!< 0x00000800 */ +#define NVIC_ISER_SETENA_12 (0x00001000U << NVIC_ISER_SETENA_Pos) /*!< 0x00001000 */ +#define NVIC_ISER_SETENA_13 (0x00002000U << NVIC_ISER_SETENA_Pos) /*!< 0x00002000 */ +#define NVIC_ISER_SETENA_14 (0x00004000U << NVIC_ISER_SETENA_Pos) /*!< 0x00004000 */ +#define NVIC_ISER_SETENA_15 (0x00008000U << NVIC_ISER_SETENA_Pos) /*!< 0x00008000 */ +#define NVIC_ISER_SETENA_16 (0x00010000U << NVIC_ISER_SETENA_Pos) /*!< 0x00010000 */ +#define NVIC_ISER_SETENA_17 (0x00020000U << NVIC_ISER_SETENA_Pos) /*!< 0x00020000 */ +#define NVIC_ISER_SETENA_18 (0x00040000U << NVIC_ISER_SETENA_Pos) /*!< 0x00040000 */ +#define NVIC_ISER_SETENA_19 (0x00080000U << NVIC_ISER_SETENA_Pos) /*!< 0x00080000 */ +#define NVIC_ISER_SETENA_20 (0x00100000U << NVIC_ISER_SETENA_Pos) /*!< 0x00100000 */ +#define NVIC_ISER_SETENA_21 (0x00200000U << NVIC_ISER_SETENA_Pos) /*!< 0x00200000 */ +#define NVIC_ISER_SETENA_22 (0x00400000U << NVIC_ISER_SETENA_Pos) /*!< 0x00400000 */ +#define NVIC_ISER_SETENA_23 (0x00800000U << NVIC_ISER_SETENA_Pos) /*!< 0x00800000 */ +#define NVIC_ISER_SETENA_24 (0x01000000U << NVIC_ISER_SETENA_Pos) /*!< 0x01000000 */ +#define NVIC_ISER_SETENA_25 (0x02000000U << NVIC_ISER_SETENA_Pos) /*!< 0x02000000 */ +#define NVIC_ISER_SETENA_26 (0x04000000U << NVIC_ISER_SETENA_Pos) /*!< 0x04000000 */ +#define NVIC_ISER_SETENA_27 (0x08000000U << NVIC_ISER_SETENA_Pos) /*!< 0x08000000 */ +#define NVIC_ISER_SETENA_28 (0x10000000U << NVIC_ISER_SETENA_Pos) /*!< 0x10000000 */ +#define NVIC_ISER_SETENA_29 (0x20000000U << NVIC_ISER_SETENA_Pos) /*!< 0x20000000 */ +#define NVIC_ISER_SETENA_30 (0x40000000U << NVIC_ISER_SETENA_Pos) /*!< 0x40000000 */ +#define NVIC_ISER_SETENA_31 (0x80000000U << NVIC_ISER_SETENA_Pos) /*!< 0x80000000 */ + +/****************** Bit definition for NVIC_ICER register *******************/ +#define NVIC_ICER_CLRENA_Pos (0U) +#define NVIC_ICER_CLRENA_Msk (0xFFFFFFFFU << NVIC_ICER_CLRENA_Pos) /*!< 0xFFFFFFFF */ +#define NVIC_ICER_CLRENA NVIC_ICER_CLRENA_Msk /*!< Interrupt clear-enable bits */ +#define NVIC_ICER_CLRENA_0 (0x00000001U << NVIC_ICER_CLRENA_Pos) /*!< 0x00000001 */ +#define NVIC_ICER_CLRENA_1 (0x00000002U << NVIC_ICER_CLRENA_Pos) /*!< 0x00000002 */ +#define NVIC_ICER_CLRENA_2 (0x00000004U << NVIC_ICER_CLRENA_Pos) /*!< 0x00000004 */ +#define NVIC_ICER_CLRENA_3 (0x00000008U << NVIC_ICER_CLRENA_Pos) /*!< 0x00000008 */ +#define NVIC_ICER_CLRENA_4 (0x00000010U << NVIC_ICER_CLRENA_Pos) /*!< 0x00000010 */ +#define NVIC_ICER_CLRENA_5 (0x00000020U << NVIC_ICER_CLRENA_Pos) /*!< 0x00000020 */ +#define NVIC_ICER_CLRENA_6 (0x00000040U << NVIC_ICER_CLRENA_Pos) /*!< 0x00000040 */ +#define NVIC_ICER_CLRENA_7 (0x00000080U << NVIC_ICER_CLRENA_Pos) /*!< 0x00000080 */ +#define NVIC_ICER_CLRENA_8 (0x00000100U << NVIC_ICER_CLRENA_Pos) /*!< 0x00000100 */ +#define NVIC_ICER_CLRENA_9 (0x00000200U << NVIC_ICER_CLRENA_Pos) /*!< 0x00000200 */ +#define NVIC_ICER_CLRENA_10 (0x00000400U << NVIC_ICER_CLRENA_Pos) /*!< 0x00000400 */ +#define NVIC_ICER_CLRENA_11 (0x00000800U << NVIC_ICER_CLRENA_Pos) /*!< 0x00000800 */ +#define NVIC_ICER_CLRENA_12 (0x00001000U << NVIC_ICER_CLRENA_Pos) /*!< 0x00001000 */ +#define NVIC_ICER_CLRENA_13 (0x00002000U << NVIC_ICER_CLRENA_Pos) /*!< 0x00002000 */ +#define NVIC_ICER_CLRENA_14 (0x00004000U << NVIC_ICER_CLRENA_Pos) /*!< 0x00004000 */ +#define NVIC_ICER_CLRENA_15 (0x00008000U << NVIC_ICER_CLRENA_Pos) /*!< 0x00008000 */ +#define NVIC_ICER_CLRENA_16 (0x00010000U << NVIC_ICER_CLRENA_Pos) /*!< 0x00010000 */ +#define NVIC_ICER_CLRENA_17 (0x00020000U << NVIC_ICER_CLRENA_Pos) /*!< 0x00020000 */ +#define NVIC_ICER_CLRENA_18 (0x00040000U << NVIC_ICER_CLRENA_Pos) /*!< 0x00040000 */ +#define NVIC_ICER_CLRENA_19 (0x00080000U << NVIC_ICER_CLRENA_Pos) /*!< 0x00080000 */ +#define NVIC_ICER_CLRENA_20 (0x00100000U << NVIC_ICER_CLRENA_Pos) /*!< 0x00100000 */ +#define NVIC_ICER_CLRENA_21 (0x00200000U << NVIC_ICER_CLRENA_Pos) /*!< 0x00200000 */ +#define NVIC_ICER_CLRENA_22 (0x00400000U << NVIC_ICER_CLRENA_Pos) /*!< 0x00400000 */ +#define NVIC_ICER_CLRENA_23 (0x00800000U << NVIC_ICER_CLRENA_Pos) /*!< 0x00800000 */ +#define NVIC_ICER_CLRENA_24 (0x01000000U << NVIC_ICER_CLRENA_Pos) /*!< 0x01000000 */ +#define NVIC_ICER_CLRENA_25 (0x02000000U << NVIC_ICER_CLRENA_Pos) /*!< 0x02000000 */ +#define NVIC_ICER_CLRENA_26 (0x04000000U << NVIC_ICER_CLRENA_Pos) /*!< 0x04000000 */ +#define NVIC_ICER_CLRENA_27 (0x08000000U << NVIC_ICER_CLRENA_Pos) /*!< 0x08000000 */ +#define NVIC_ICER_CLRENA_28 (0x10000000U << NVIC_ICER_CLRENA_Pos) /*!< 0x10000000 */ +#define NVIC_ICER_CLRENA_29 (0x20000000U << NVIC_ICER_CLRENA_Pos) /*!< 0x20000000 */ +#define NVIC_ICER_CLRENA_30 (0x40000000U << NVIC_ICER_CLRENA_Pos) /*!< 0x40000000 */ +#define NVIC_ICER_CLRENA_31 (0x80000000U << NVIC_ICER_CLRENA_Pos) /*!< 0x80000000 */ + +/****************** Bit definition for NVIC_ISPR register *******************/ +#define NVIC_ISPR_SETPEND_Pos (0U) +#define NVIC_ISPR_SETPEND_Msk (0xFFFFFFFFU << NVIC_ISPR_SETPEND_Pos) /*!< 0xFFFFFFFF */ +#define NVIC_ISPR_SETPEND NVIC_ISPR_SETPEND_Msk /*!< Interrupt set-pending bits */ +#define NVIC_ISPR_SETPEND_0 (0x00000001U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00000001 */ +#define NVIC_ISPR_SETPEND_1 (0x00000002U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00000002 */ +#define NVIC_ISPR_SETPEND_2 (0x00000004U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00000004 */ +#define NVIC_ISPR_SETPEND_3 (0x00000008U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00000008 */ +#define NVIC_ISPR_SETPEND_4 (0x00000010U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00000010 */ +#define NVIC_ISPR_SETPEND_5 (0x00000020U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00000020 */ +#define NVIC_ISPR_SETPEND_6 (0x00000040U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00000040 */ +#define NVIC_ISPR_SETPEND_7 (0x00000080U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00000080 */ +#define NVIC_ISPR_SETPEND_8 (0x00000100U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00000100 */ +#define NVIC_ISPR_SETPEND_9 (0x00000200U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00000200 */ +#define NVIC_ISPR_SETPEND_10 (0x00000400U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00000400 */ +#define NVIC_ISPR_SETPEND_11 (0x00000800U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00000800 */ +#define NVIC_ISPR_SETPEND_12 (0x00001000U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00001000 */ +#define NVIC_ISPR_SETPEND_13 (0x00002000U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00002000 */ +#define NVIC_ISPR_SETPEND_14 (0x00004000U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00004000 */ +#define NVIC_ISPR_SETPEND_15 (0x00008000U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00008000 */ +#define NVIC_ISPR_SETPEND_16 (0x00010000U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00010000 */ +#define NVIC_ISPR_SETPEND_17 (0x00020000U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00020000 */ +#define NVIC_ISPR_SETPEND_18 (0x00040000U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00040000 */ +#define NVIC_ISPR_SETPEND_19 (0x00080000U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00080000 */ +#define NVIC_ISPR_SETPEND_20 (0x00100000U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00100000 */ +#define NVIC_ISPR_SETPEND_21 (0x00200000U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00200000 */ +#define NVIC_ISPR_SETPEND_22 (0x00400000U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00400000 */ +#define NVIC_ISPR_SETPEND_23 (0x00800000U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00800000 */ +#define NVIC_ISPR_SETPEND_24 (0x01000000U << NVIC_ISPR_SETPEND_Pos) /*!< 0x01000000 */ +#define NVIC_ISPR_SETPEND_25 (0x02000000U << NVIC_ISPR_SETPEND_Pos) /*!< 0x02000000 */ +#define NVIC_ISPR_SETPEND_26 (0x04000000U << NVIC_ISPR_SETPEND_Pos) /*!< 0x04000000 */ +#define NVIC_ISPR_SETPEND_27 (0x08000000U << NVIC_ISPR_SETPEND_Pos) /*!< 0x08000000 */ +#define NVIC_ISPR_SETPEND_28 (0x10000000U << NVIC_ISPR_SETPEND_Pos) /*!< 0x10000000 */ +#define NVIC_ISPR_SETPEND_29 (0x20000000U << NVIC_ISPR_SETPEND_Pos) /*!< 0x20000000 */ +#define NVIC_ISPR_SETPEND_30 (0x40000000U << NVIC_ISPR_SETPEND_Pos) /*!< 0x40000000 */ +#define NVIC_ISPR_SETPEND_31 (0x80000000U << NVIC_ISPR_SETPEND_Pos) /*!< 0x80000000 */ + +/****************** Bit definition for NVIC_ICPR register *******************/ +#define NVIC_ICPR_CLRPEND_Pos (0U) +#define NVIC_ICPR_CLRPEND_Msk (0xFFFFFFFFU << NVIC_ICPR_CLRPEND_Pos) /*!< 0xFFFFFFFF */ +#define NVIC_ICPR_CLRPEND NVIC_ICPR_CLRPEND_Msk /*!< Interrupt clear-pending bits */ +#define NVIC_ICPR_CLRPEND_0 (0x00000001U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00000001 */ +#define NVIC_ICPR_CLRPEND_1 (0x00000002U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00000002 */ +#define NVIC_ICPR_CLRPEND_2 (0x00000004U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00000004 */ +#define NVIC_ICPR_CLRPEND_3 (0x00000008U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00000008 */ +#define NVIC_ICPR_CLRPEND_4 (0x00000010U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00000010 */ +#define NVIC_ICPR_CLRPEND_5 (0x00000020U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00000020 */ +#define NVIC_ICPR_CLRPEND_6 (0x00000040U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00000040 */ +#define NVIC_ICPR_CLRPEND_7 (0x00000080U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00000080 */ +#define NVIC_ICPR_CLRPEND_8 (0x00000100U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00000100 */ +#define NVIC_ICPR_CLRPEND_9 (0x00000200U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00000200 */ +#define NVIC_ICPR_CLRPEND_10 (0x00000400U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00000400 */ +#define NVIC_ICPR_CLRPEND_11 (0x00000800U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00000800 */ +#define NVIC_ICPR_CLRPEND_12 (0x00001000U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00001000 */ +#define NVIC_ICPR_CLRPEND_13 (0x00002000U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00002000 */ +#define NVIC_ICPR_CLRPEND_14 (0x00004000U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00004000 */ +#define NVIC_ICPR_CLRPEND_15 (0x00008000U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00008000 */ +#define NVIC_ICPR_CLRPEND_16 (0x00010000U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00010000 */ +#define NVIC_ICPR_CLRPEND_17 (0x00020000U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00020000 */ +#define NVIC_ICPR_CLRPEND_18 (0x00040000U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00040000 */ +#define NVIC_ICPR_CLRPEND_19 (0x00080000U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00080000 */ +#define NVIC_ICPR_CLRPEND_20 (0x00100000U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00100000 */ +#define NVIC_ICPR_CLRPEND_21 (0x00200000U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00200000 */ +#define NVIC_ICPR_CLRPEND_22 (0x00400000U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00400000 */ +#define NVIC_ICPR_CLRPEND_23 (0x00800000U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00800000 */ +#define NVIC_ICPR_CLRPEND_24 (0x01000000U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x01000000 */ +#define NVIC_ICPR_CLRPEND_25 (0x02000000U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x02000000 */ +#define NVIC_ICPR_CLRPEND_26 (0x04000000U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x04000000 */ +#define NVIC_ICPR_CLRPEND_27 (0x08000000U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x08000000 */ +#define NVIC_ICPR_CLRPEND_28 (0x10000000U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x10000000 */ +#define NVIC_ICPR_CLRPEND_29 (0x20000000U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x20000000 */ +#define NVIC_ICPR_CLRPEND_30 (0x40000000U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x40000000 */ +#define NVIC_ICPR_CLRPEND_31 (0x80000000U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x80000000 */ + +/****************** Bit definition for NVIC_IABR register *******************/ +#define NVIC_IABR_ACTIVE_Pos (0U) +#define NVIC_IABR_ACTIVE_Msk (0xFFFFFFFFU << NVIC_IABR_ACTIVE_Pos) /*!< 0xFFFFFFFF */ +#define NVIC_IABR_ACTIVE NVIC_IABR_ACTIVE_Msk /*!< Interrupt active flags */ +#define NVIC_IABR_ACTIVE_0 (0x00000001U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00000001 */ +#define NVIC_IABR_ACTIVE_1 (0x00000002U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00000002 */ +#define NVIC_IABR_ACTIVE_2 (0x00000004U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00000004 */ +#define NVIC_IABR_ACTIVE_3 (0x00000008U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00000008 */ +#define NVIC_IABR_ACTIVE_4 (0x00000010U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00000010 */ +#define NVIC_IABR_ACTIVE_5 (0x00000020U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00000020 */ +#define NVIC_IABR_ACTIVE_6 (0x00000040U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00000040 */ +#define NVIC_IABR_ACTIVE_7 (0x00000080U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00000080 */ +#define NVIC_IABR_ACTIVE_8 (0x00000100U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00000100 */ +#define NVIC_IABR_ACTIVE_9 (0x00000200U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00000200 */ +#define NVIC_IABR_ACTIVE_10 (0x00000400U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00000400 */ +#define NVIC_IABR_ACTIVE_11 (0x00000800U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00000800 */ +#define NVIC_IABR_ACTIVE_12 (0x00001000U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00001000 */ +#define NVIC_IABR_ACTIVE_13 (0x00002000U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00002000 */ +#define NVIC_IABR_ACTIVE_14 (0x00004000U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00004000 */ +#define NVIC_IABR_ACTIVE_15 (0x00008000U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00008000 */ +#define NVIC_IABR_ACTIVE_16 (0x00010000U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00010000 */ +#define NVIC_IABR_ACTIVE_17 (0x00020000U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00020000 */ +#define NVIC_IABR_ACTIVE_18 (0x00040000U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00040000 */ +#define NVIC_IABR_ACTIVE_19 (0x00080000U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00080000 */ +#define NVIC_IABR_ACTIVE_20 (0x00100000U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00100000 */ +#define NVIC_IABR_ACTIVE_21 (0x00200000U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00200000 */ +#define NVIC_IABR_ACTIVE_22 (0x00400000U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00400000 */ +#define NVIC_IABR_ACTIVE_23 (0x00800000U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00800000 */ +#define NVIC_IABR_ACTIVE_24 (0x01000000U << NVIC_IABR_ACTIVE_Pos) /*!< 0x01000000 */ +#define NVIC_IABR_ACTIVE_25 (0x02000000U << NVIC_IABR_ACTIVE_Pos) /*!< 0x02000000 */ +#define NVIC_IABR_ACTIVE_26 (0x04000000U << NVIC_IABR_ACTIVE_Pos) /*!< 0x04000000 */ +#define NVIC_IABR_ACTIVE_27 (0x08000000U << NVIC_IABR_ACTIVE_Pos) /*!< 0x08000000 */ +#define NVIC_IABR_ACTIVE_28 (0x10000000U << NVIC_IABR_ACTIVE_Pos) /*!< 0x10000000 */ +#define NVIC_IABR_ACTIVE_29 (0x20000000U << NVIC_IABR_ACTIVE_Pos) /*!< 0x20000000 */ +#define NVIC_IABR_ACTIVE_30 (0x40000000U << NVIC_IABR_ACTIVE_Pos) /*!< 0x40000000 */ +#define NVIC_IABR_ACTIVE_31 (0x80000000U << NVIC_IABR_ACTIVE_Pos) /*!< 0x80000000 */ + +/****************** Bit definition for NVIC_PRI0 register *******************/ +#define NVIC_IPR0_PRI_0 ((uint32_t)0x000000FF) /*!< Priority of interrupt 0 */ +#define NVIC_IPR0_PRI_1 ((uint32_t)0x0000FF00) /*!< Priority of interrupt 1 */ +#define NVIC_IPR0_PRI_2 ((uint32_t)0x00FF0000) /*!< Priority of interrupt 2 */ +#define NVIC_IPR0_PRI_3 ((uint32_t)0xFF000000) /*!< Priority of interrupt 3 */ + +/****************** Bit definition for NVIC_PRI1 register *******************/ +#define NVIC_IPR1_PRI_4 ((uint32_t)0x000000FF) /*!< Priority of interrupt 4 */ +#define NVIC_IPR1_PRI_5 ((uint32_t)0x0000FF00) /*!< Priority of interrupt 5 */ +#define NVIC_IPR1_PRI_6 ((uint32_t)0x00FF0000) /*!< Priority of interrupt 6 */ +#define NVIC_IPR1_PRI_7 ((uint32_t)0xFF000000) /*!< Priority of interrupt 7 */ + +/****************** Bit definition for NVIC_PRI2 register *******************/ +#define NVIC_IPR2_PRI_8 ((uint32_t)0x000000FF) /*!< Priority of interrupt 8 */ +#define NVIC_IPR2_PRI_9 ((uint32_t)0x0000FF00) /*!< Priority of interrupt 9 */ +#define NVIC_IPR2_PRI_10 ((uint32_t)0x00FF0000) /*!< Priority of interrupt 10 */ +#define NVIC_IPR2_PRI_11 ((uint32_t)0xFF000000) /*!< Priority of interrupt 11 */ + +/****************** Bit definition for NVIC_PRI3 register *******************/ +#define NVIC_IPR3_PRI_12 ((uint32_t)0x000000FF) /*!< Priority of interrupt 12 */ +#define NVIC_IPR3_PRI_13 ((uint32_t)0x0000FF00) /*!< Priority of interrupt 13 */ +#define NVIC_IPR3_PRI_14 ((uint32_t)0x00FF0000) /*!< Priority of interrupt 14 */ +#define NVIC_IPR3_PRI_15 ((uint32_t)0xFF000000) /*!< Priority of interrupt 15 */ + +/****************** Bit definition for NVIC_PRI4 register *******************/ +#define NVIC_IPR4_PRI_16 ((uint32_t)0x000000FF) /*!< Priority of interrupt 16 */ +#define NVIC_IPR4_PRI_17 ((uint32_t)0x0000FF00) /*!< Priority of interrupt 17 */ +#define NVIC_IPR4_PRI_18 ((uint32_t)0x00FF0000) /*!< Priority of interrupt 18 */ +#define NVIC_IPR4_PRI_19 ((uint32_t)0xFF000000) /*!< Priority of interrupt 19 */ + +/****************** Bit definition for NVIC_PRI5 register *******************/ +#define NVIC_IPR5_PRI_20 ((uint32_t)0x000000FF) /*!< Priority of interrupt 20 */ +#define NVIC_IPR5_PRI_21 ((uint32_t)0x0000FF00) /*!< Priority of interrupt 21 */ +#define NVIC_IPR5_PRI_22 ((uint32_t)0x00FF0000) /*!< Priority of interrupt 22 */ +#define NVIC_IPR5_PRI_23 ((uint32_t)0xFF000000) /*!< Priority of interrupt 23 */ + +/****************** Bit definition for NVIC_PRI6 register *******************/ +#define NVIC_IPR6_PRI_24 ((uint32_t)0x000000FF) /*!< Priority of interrupt 24 */ +#define NVIC_IPR6_PRI_25 ((uint32_t)0x0000FF00) /*!< Priority of interrupt 25 */ +#define NVIC_IPR6_PRI_26 ((uint32_t)0x00FF0000) /*!< Priority of interrupt 26 */ +#define NVIC_IPR6_PRI_27 ((uint32_t)0xFF000000) /*!< Priority of interrupt 27 */ + +/****************** Bit definition for NVIC_PRI7 register *******************/ +#define NVIC_IPR7_PRI_28 ((uint32_t)0x000000FF) /*!< Priority of interrupt 28 */ +#define NVIC_IPR7_PRI_29 ((uint32_t)0x0000FF00) /*!< Priority of interrupt 29 */ +#define NVIC_IPR7_PRI_30 ((uint32_t)0x00FF0000) /*!< Priority of interrupt 30 */ +#define NVIC_IPR7_PRI_31 ((uint32_t)0xFF000000) /*!< Priority of interrupt 31 */ + +/****************** Bit definition for SCB_CPUID register *******************/ +#define SCB_CPUID_REVISION ((uint32_t)0x0000000F) /*!< Implementation defined revision number */ +#define SCB_CPUID_PARTNO ((uint32_t)0x0000FFF0) /*!< Number of processor within family */ +#define SCB_CPUID_Constant ((uint32_t)0x000F0000) /*!< Reads as 0x0F */ +#define SCB_CPUID_VARIANT ((uint32_t)0x00F00000) /*!< Implementation defined variant number */ +#define SCB_CPUID_IMPLEMENTER ((uint32_t)0xFF000000) /*!< Implementer code. ARM is 0x41 */ + +/******************* Bit definition for SCB_ICSR register *******************/ +#define SCB_ICSR_VECTACTIVE ((uint32_t)0x000001FF) /*!< Active ISR number field */ +#define SCB_ICSR_RETTOBASE ((uint32_t)0x00000800) /*!< All active exceptions minus the IPSR_current_exception yields the empty set */ +#define SCB_ICSR_VECTPENDING ((uint32_t)0x003FF000) /*!< Pending ISR number field */ +#define SCB_ICSR_ISRPENDING ((uint32_t)0x00400000) /*!< Interrupt pending flag */ +#define SCB_ICSR_ISRPREEMPT ((uint32_t)0x00800000) /*!< It indicates that a pending interrupt becomes active in the next running cycle */ +#define SCB_ICSR_PENDSTCLR ((uint32_t)0x02000000) /*!< Clear pending SysTick bit */ +#define SCB_ICSR_PENDSTSET ((uint32_t)0x04000000) /*!< Set pending SysTick bit */ +#define SCB_ICSR_PENDSVCLR ((uint32_t)0x08000000) /*!< Clear pending pendSV bit */ +#define SCB_ICSR_PENDSVSET ((uint32_t)0x10000000) /*!< Set pending pendSV bit */ +#define SCB_ICSR_NMIPENDSET ((uint32_t)0x80000000) /*!< Set pending NMI bit */ + +/******************* Bit definition for SCB_VTOR register *******************/ +#define SCB_VTOR_TBLOFF ((uint32_t)0x1FFFFF80) /*!< Vector table base offset field */ +#define SCB_VTOR_TBLBASE ((uint32_t)0x20000000) /*!< Table base in code(0) or RAM(1) */ + +/*!<***************** Bit definition for SCB_AIRCR register *******************/ +#define SCB_AIRCR_VECTRESET ((uint32_t)0x00000001) /*!< System Reset bit */ +#define SCB_AIRCR_VECTCLRACTIVE ((uint32_t)0x00000002) /*!< Clear active vector bit */ +#define SCB_AIRCR_SYSRESETREQ ((uint32_t)0x00000004) /*!< Requests chip control logic to generate a reset */ + +#define SCB_AIRCR_PRIGROUP ((uint32_t)0x00000700) /*!< PRIGROUP[2:0] bits (Priority group) */ +#define SCB_AIRCR_PRIGROUP_0 ((uint32_t)0x00000100) /*!< Bit 0 */ +#define SCB_AIRCR_PRIGROUP_1 ((uint32_t)0x00000200) /*!< Bit 1 */ +#define SCB_AIRCR_PRIGROUP_2 ((uint32_t)0x00000400) /*!< Bit 2 */ + +/* prority group configuration */ +#define SCB_AIRCR_PRIGROUP0 ((uint32_t)0x00000000) /*!< Priority group=0 (7 bits of pre-emption priority, 1 bit of subpriority) */ +#define SCB_AIRCR_PRIGROUP1 ((uint32_t)0x00000100) /*!< Priority group=1 (6 bits of pre-emption priority, 2 bits of subpriority) */ +#define SCB_AIRCR_PRIGROUP2 ((uint32_t)0x00000200) /*!< Priority group=2 (5 bits of pre-emption priority, 3 bits of subpriority) */ +#define SCB_AIRCR_PRIGROUP3 ((uint32_t)0x00000300) /*!< Priority group=3 (4 bits of pre-emption priority, 4 bits of subpriority) */ +#define SCB_AIRCR_PRIGROUP4 ((uint32_t)0x00000400) /*!< Priority group=4 (3 bits of pre-emption priority, 5 bits of subpriority) */ +#define SCB_AIRCR_PRIGROUP5 ((uint32_t)0x00000500) /*!< Priority group=5 (2 bits of pre-emption priority, 6 bits of subpriority) */ +#define SCB_AIRCR_PRIGROUP6 ((uint32_t)0x00000600) /*!< Priority group=6 (1 bit of pre-emption priority, 7 bits of subpriority) */ +#define SCB_AIRCR_PRIGROUP7 ((uint32_t)0x00000700) /*!< Priority group=7 (no pre-emption priority, 8 bits of subpriority) */ + +#define SCB_AIRCR_ENDIANESS ((uint32_t)0x00008000) /*!< Data endianness bit */ +#define SCB_AIRCR_VECTKEY ((uint32_t)0xFFFF0000) /*!< Register key (VECTKEY) - Reads as 0xFA05 (VECTKEYSTAT) */ + +/******************* Bit definition for SCB_SCR register ********************/ +#define SCB_SCR_SLEEPONEXIT ((uint32_t)0x00000002) /*!< Sleep on exit bit */ +#define SCB_SCR_SLEEPDEEP ((uint32_t)0x00000004) /*!< Sleep deep bit */ +#define SCB_SCR_SEVONPEND ((uint32_t)0x00000010) /*!< Wake up from WFE */ + +/******************** Bit definition for SCB_CCR register *******************/ +#define SCB_CCR_NONBASETHRDENA ((uint32_t)0x00000001) /*!< Thread mode can be entered from any level in Handler mode by controlled return value */ +#define SCB_CCR_USERSETMPEND ((uint32_t)0x00000002) /*!< Enables user code to write the Software Trigger Interrupt register to trigger (pend) a Main exception */ +#define SCB_CCR_UNALIGN_TRP ((uint32_t)0x00000008) /*!< Trap for unaligned access */ +#define SCB_CCR_DIV_0_TRP ((uint32_t)0x00000010) /*!< Trap on Divide by 0 */ +#define SCB_CCR_BFHFNMIGN ((uint32_t)0x00000100) /*!< Handlers running at priority -1 and -2 */ +#define SCB_CCR_STKALIGN ((uint32_t)0x00000200) /*!< On exception entry, the SP used prior to the exception is adjusted to be 8-byte aligned */ + +/******************* Bit definition for SCB_SHPR register ********************/ +#define SCB_SHPR_PRI_N_Pos (0U) +#define SCB_SHPR_PRI_N_Msk (0xFFU << SCB_SHPR_PRI_N_Pos) /*!< 0x000000FF */ +#define SCB_SHPR_PRI_N SCB_SHPR_PRI_N_Msk /*!< Priority of system handler 4,8, and 12. Mem Manage, reserved and Debug Monitor */ +#define SCB_SHPR_PRI_N1_Pos (8U) +#define SCB_SHPR_PRI_N1_Msk (0xFFU << SCB_SHPR_PRI_N1_Pos) /*!< 0x0000FF00 */ +#define SCB_SHPR_PRI_N1 SCB_SHPR_PRI_N1_Msk /*!< Priority of system handler 5,9, and 13. Bus Fault, reserved and reserved */ +#define SCB_SHPR_PRI_N2_Pos (16U) +#define SCB_SHPR_PRI_N2_Msk (0xFFU << SCB_SHPR_PRI_N2_Pos) /*!< 0x00FF0000 */ +#define SCB_SHPR_PRI_N2 SCB_SHPR_PRI_N2_Msk /*!< Priority of system handler 6,10, and 14. Usage Fault, reserved and PendSV */ +#define SCB_SHPR_PRI_N3_Pos (24U) +#define SCB_SHPR_PRI_N3_Msk (0xFFU << SCB_SHPR_PRI_N3_Pos) /*!< 0xFF000000 */ +#define SCB_SHPR_PRI_N3 SCB_SHPR_PRI_N3_Msk /*!< Priority of system handler 7,11, and 15. Reserved, SVCall and SysTick */ + +/****************** Bit definition for SCB_SHCSR register *******************/ +#define SCB_SHCSR_MEMFAULTACT ((uint32_t)0x00000001) /*!< MemManage is active */ +#define SCB_SHCSR_BUSFAULTACT ((uint32_t)0x00000002) /*!< BusFault is active */ +#define SCB_SHCSR_USGFAULTACT ((uint32_t)0x00000008) /*!< UsageFault is active */ +#define SCB_SHCSR_SVCALLACT ((uint32_t)0x00000080) /*!< SVCall is active */ +#define SCB_SHCSR_MONITORACT ((uint32_t)0x00000100) /*!< Monitor is active */ +#define SCB_SHCSR_PENDSVACT ((uint32_t)0x00000400) /*!< PendSV is active */ +#define SCB_SHCSR_SYSTICKACT ((uint32_t)0x00000800) /*!< SysTick is active */ +#define SCB_SHCSR_USGFAULTPENDED ((uint32_t)0x00001000) /*!< Usage Fault is pended */ +#define SCB_SHCSR_MEMFAULTPENDED ((uint32_t)0x00002000) /*!< MemManage is pended */ +#define SCB_SHCSR_BUSFAULTPENDED ((uint32_t)0x00004000) /*!< Bus Fault is pended */ +#define SCB_SHCSR_SVCALLPENDED ((uint32_t)0x00008000) /*!< SVCall is pended */ +#define SCB_SHCSR_MEMFAULTENA ((uint32_t)0x00010000) /*!< MemManage enable */ +#define SCB_SHCSR_BUSFAULTENA ((uint32_t)0x00020000) /*!< Bus Fault enable */ +#define SCB_SHCSR_USGFAULTENA ((uint32_t)0x00040000) /*!< UsageFault enable */ + +/******************* Bit definition for SCB_CFSR register *******************/ +/*!< MFSR */ +#define SCB_CFSR_IACCVIOL_Pos (0U) +#define SCB_CFSR_IACCVIOL_Msk (0x1U << SCB_CFSR_IACCVIOL_Pos) /*!< 0x00000001 */ +#define SCB_CFSR_IACCVIOL SCB_CFSR_IACCVIOL_Msk /*!< Instruction access violation */ +#define SCB_CFSR_DACCVIOL_Pos (1U) +#define SCB_CFSR_DACCVIOL_Msk (0x1U << SCB_CFSR_DACCVIOL_Pos) /*!< 0x00000002 */ +#define SCB_CFSR_DACCVIOL SCB_CFSR_DACCVIOL_Msk /*!< Data access violation */ +#define SCB_CFSR_MUNSTKERR_Pos (3U) +#define SCB_CFSR_MUNSTKERR_Msk (0x1U << SCB_CFSR_MUNSTKERR_Pos) /*!< 0x00000008 */ +#define SCB_CFSR_MUNSTKERR SCB_CFSR_MUNSTKERR_Msk /*!< Unstacking error */ +#define SCB_CFSR_MSTKERR_Pos (4U) +#define SCB_CFSR_MSTKERR_Msk (0x1U << SCB_CFSR_MSTKERR_Pos) /*!< 0x00000010 */ +#define SCB_CFSR_MSTKERR SCB_CFSR_MSTKERR_Msk /*!< Stacking error */ +#define SCB_CFSR_MMARVALID_Pos (7U) +#define SCB_CFSR_MMARVALID_Msk (0x1U << SCB_CFSR_MMARVALID_Pos) /*!< 0x00000080 */ +#define SCB_CFSR_MMARVALID SCB_CFSR_MMARVALID_Msk /*!< Memory Manage Address Register address valid flag */ +/*!< BFSR */ +#define SCB_CFSR_IBUSERR_Pos (8U) +#define SCB_CFSR_IBUSERR_Msk (0x1U << SCB_CFSR_IBUSERR_Pos) /*!< 0x00000100 */ +#define SCB_CFSR_IBUSERR SCB_CFSR_IBUSERR_Msk /*!< Instruction bus error flag */ +#define SCB_CFSR_PRECISERR_Pos (9U) +#define SCB_CFSR_PRECISERR_Msk (0x1U << SCB_CFSR_PRECISERR_Pos) /*!< 0x00000200 */ +#define SCB_CFSR_PRECISERR SCB_CFSR_PRECISERR_Msk /*!< Precise data bus error */ +#define SCB_CFSR_IMPRECISERR_Pos (10U) +#define SCB_CFSR_IMPRECISERR_Msk (0x1U << SCB_CFSR_IMPRECISERR_Pos) /*!< 0x00000400 */ +#define SCB_CFSR_IMPRECISERR SCB_CFSR_IMPRECISERR_Msk /*!< Imprecise data bus error */ +#define SCB_CFSR_UNSTKERR_Pos (11U) +#define SCB_CFSR_UNSTKERR_Msk (0x1U << SCB_CFSR_UNSTKERR_Pos) /*!< 0x00000800 */ +#define SCB_CFSR_UNSTKERR SCB_CFSR_UNSTKERR_Msk /*!< Unstacking error */ +#define SCB_CFSR_STKERR_Pos (12U) +#define SCB_CFSR_STKERR_Msk (0x1U << SCB_CFSR_STKERR_Pos) /*!< 0x00001000 */ +#define SCB_CFSR_STKERR SCB_CFSR_STKERR_Msk /*!< Stacking error */ +#define SCB_CFSR_BFARVALID_Pos (15U) +#define SCB_CFSR_BFARVALID_Msk (0x1U << SCB_CFSR_BFARVALID_Pos) /*!< 0x00008000 */ +#define SCB_CFSR_BFARVALID SCB_CFSR_BFARVALID_Msk /*!< Bus Fault Address Register address valid flag */ +/*!< UFSR */ +#define SCB_CFSR_UNDEFINSTR_Pos (16U) +#define SCB_CFSR_UNDEFINSTR_Msk (0x1U << SCB_CFSR_UNDEFINSTR_Pos) /*!< 0x00010000 */ +#define SCB_CFSR_UNDEFINSTR SCB_CFSR_UNDEFINSTR_Msk /*!< The processor attempt to execute an undefined instruction */ +#define SCB_CFSR_INVSTATE_Pos (17U) +#define SCB_CFSR_INVSTATE_Msk (0x1U << SCB_CFSR_INVSTATE_Pos) /*!< 0x00020000 */ +#define SCB_CFSR_INVSTATE SCB_CFSR_INVSTATE_Msk /*!< Invalid combination of EPSR and instruction */ +#define SCB_CFSR_INVPC_Pos (18U) +#define SCB_CFSR_INVPC_Msk (0x1U << SCB_CFSR_INVPC_Pos) /*!< 0x00040000 */ +#define SCB_CFSR_INVPC SCB_CFSR_INVPC_Msk /*!< Attempt to load EXC_RETURN into pc illegally */ +#define SCB_CFSR_NOCP_Pos (19U) +#define SCB_CFSR_NOCP_Msk (0x1U << SCB_CFSR_NOCP_Pos) /*!< 0x00080000 */ +#define SCB_CFSR_NOCP SCB_CFSR_NOCP_Msk /*!< Attempt to use a coprocessor instruction */ +#define SCB_CFSR_UNALIGNED_Pos (24U) +#define SCB_CFSR_UNALIGNED_Msk (0x1U << SCB_CFSR_UNALIGNED_Pos) /*!< 0x01000000 */ +#define SCB_CFSR_UNALIGNED SCB_CFSR_UNALIGNED_Msk /*!< Fault occurs when there is an attempt to make an unaligned memory access */ +#define SCB_CFSR_DIVBYZERO_Pos (25U) +#define SCB_CFSR_DIVBYZERO_Msk (0x1U << SCB_CFSR_DIVBYZERO_Pos) /*!< 0x02000000 */ +#define SCB_CFSR_DIVBYZERO SCB_CFSR_DIVBYZERO_Msk /*!< Fault occurs when SDIV or DIV instruction is used with a divisor of 0 */ + +/******************* Bit definition for SCB_HFSR register *******************/ +#define SCB_HFSR_VECTTBL ((uint32_t)0x00000002) /*!< Fault occurs because of vector table read on exception processing */ +#define SCB_HFSR_FORCED ((uint32_t)0x40000000) /*!< Hard Fault activated when a configurable Fault was received and cannot activate */ +#define SCB_HFSR_DEBUGEVT ((uint32_t)0x80000000) /*!< Fault related to debug */ + +/******************* Bit definition for SCB_DFSR register *******************/ +#define SCB_DFSR_HALTED ((uint32_t)0x00000001) /*!< Halt request flag */ +#define SCB_DFSR_BKPT ((uint32_t)0x00000002) /*!< BKPT flag */ +#define SCB_DFSR_DWTTRAP ((uint32_t)0x00000004) /*!< Data Watchpoint and Trace (DWT) flag */ +#define SCB_DFSR_VCATCH ((uint32_t)0x00000008) /*!< Vector catch flag */ +#define SCB_DFSR_EXTERNAL ((uint32_t)0x00000010) /*!< External debug request flag */ + +/******************* Bit definition for SCB_MMFAR register ******************/ +#define SCB_MMFAR_ADDRESS_Pos (0U) +#define SCB_MMFAR_ADDRESS_Msk (0xFFFFFFFFU << SCB_MMFAR_ADDRESS_Pos) /*!< 0xFFFFFFFF */ +#define SCB_MMFAR_ADDRESS SCB_MMFAR_ADDRESS_Msk /*!< Mem Manage fault address field */ + +/******************* Bit definition for SCB_BFAR register *******************/ +#define SCB_BFAR_ADDRESS_Pos (0U) +#define SCB_BFAR_ADDRESS_Msk (0xFFFFFFFFU << SCB_BFAR_ADDRESS_Pos) /*!< 0xFFFFFFFF */ +#define SCB_BFAR_ADDRESS SCB_BFAR_ADDRESS_Msk /*!< Bus fault address field */ + +/******************* Bit definition for SCB_afsr register *******************/ +#define SCB_AFSR_IMPDEF_Pos (0U) +#define SCB_AFSR_IMPDEF_Msk (0xFFFFFFFFU << SCB_AFSR_IMPDEF_Pos) /*!< 0xFFFFFFFF */ +#define SCB_AFSR_IMPDEF SCB_AFSR_IMPDEF_Msk /*!< Implementation defined */ + /******************************************************************************/ /* */ /* External Interrupt/Event Controller */ @@ -2674,6 +3098,12 @@ typedef struct #define EXTI_IMR_MR17_Pos (17U) #define EXTI_IMR_MR17_Msk (0x1U << EXTI_IMR_MR17_Pos) /*!< 0x00020000 */ #define EXTI_IMR_MR17 EXTI_IMR_MR17_Msk /*!< Interrupt Mask on line 17 */ +#define EXTI_IMR_MR18_Pos (18U) +#define EXTI_IMR_MR18_Msk (0x1U << EXTI_IMR_MR18_Pos) /*!< 0x00040000 */ +#define EXTI_IMR_MR18 EXTI_IMR_MR18_Msk /*!< Interrupt Mask on line 18 */ +#define EXTI_IMR_MR19_Pos (19U) +#define EXTI_IMR_MR19_Msk (0x1U << EXTI_IMR_MR19_Pos) /*!< 0x00080000 */ +#define EXTI_IMR_MR19 EXTI_IMR_MR19_Msk /*!< Interrupt Mask on line 19 */ /* References Defines */ #define EXTI_IMR_IM0 EXTI_IMR_MR0 @@ -2694,8 +3124,9 @@ typedef struct #define EXTI_IMR_IM15 EXTI_IMR_MR15 #define EXTI_IMR_IM16 EXTI_IMR_MR16 #define EXTI_IMR_IM17 EXTI_IMR_MR17 -#define EXTI_IMR_IM 0x0003FFFFU /*!< Interrupt Mask All */ - +#define EXTI_IMR_IM18 EXTI_IMR_MR18 +#define EXTI_IMR_IM19 EXTI_IMR_MR19 + /******************* Bit definition for EXTI_EMR register *******************/ #define EXTI_EMR_MR0_Pos (0U) #define EXTI_EMR_MR0_Msk (0x1U << EXTI_EMR_MR0_Pos) /*!< 0x00000001 */ @@ -2751,6 +3182,12 @@ typedef struct #define EXTI_EMR_MR17_Pos (17U) #define EXTI_EMR_MR17_Msk (0x1U << EXTI_EMR_MR17_Pos) /*!< 0x00020000 */ #define EXTI_EMR_MR17 EXTI_EMR_MR17_Msk /*!< Event Mask on line 17 */ +#define EXTI_EMR_MR18_Pos (18U) +#define EXTI_EMR_MR18_Msk (0x1U << EXTI_EMR_MR18_Pos) /*!< 0x00040000 */ +#define EXTI_EMR_MR18 EXTI_EMR_MR18_Msk /*!< Event Mask on line 18 */ +#define EXTI_EMR_MR19_Pos (19U) +#define EXTI_EMR_MR19_Msk (0x1U << EXTI_EMR_MR19_Pos) /*!< 0x00080000 */ +#define EXTI_EMR_MR19 EXTI_EMR_MR19_Msk /*!< Event Mask on line 19 */ /* References Defines */ #define EXTI_EMR_EM0 EXTI_EMR_MR0 @@ -2771,6 +3208,8 @@ typedef struct #define EXTI_EMR_EM15 EXTI_EMR_MR15 #define EXTI_EMR_EM16 EXTI_EMR_MR16 #define EXTI_EMR_EM17 EXTI_EMR_MR17 +#define EXTI_EMR_EM18 EXTI_EMR_MR18 +#define EXTI_EMR_EM19 EXTI_EMR_MR19 /****************** Bit definition for EXTI_RTSR register *******************/ #define EXTI_RTSR_TR0_Pos (0U) @@ -2827,6 +3266,12 @@ typedef struct #define EXTI_RTSR_TR17_Pos (17U) #define EXTI_RTSR_TR17_Msk (0x1U << EXTI_RTSR_TR17_Pos) /*!< 0x00020000 */ #define EXTI_RTSR_TR17 EXTI_RTSR_TR17_Msk /*!< Rising trigger event configuration bit of line 17 */ +#define EXTI_RTSR_TR18_Pos (18U) +#define EXTI_RTSR_TR18_Msk (0x1U << EXTI_RTSR_TR18_Pos) /*!< 0x00040000 */ +#define EXTI_RTSR_TR18 EXTI_RTSR_TR18_Msk /*!< Rising trigger event configuration bit of line 18 */ +#define EXTI_RTSR_TR19_Pos (19U) +#define EXTI_RTSR_TR19_Msk (0x1U << EXTI_RTSR_TR19_Pos) /*!< 0x00080000 */ +#define EXTI_RTSR_TR19 EXTI_RTSR_TR19_Msk /*!< Rising trigger event configuration bit of line 19 */ /* References Defines */ #define EXTI_RTSR_RT0 EXTI_RTSR_TR0 @@ -2847,6 +3292,8 @@ typedef struct #define EXTI_RTSR_RT15 EXTI_RTSR_TR15 #define EXTI_RTSR_RT16 EXTI_RTSR_TR16 #define EXTI_RTSR_RT17 EXTI_RTSR_TR17 +#define EXTI_RTSR_RT18 EXTI_RTSR_TR18 +#define EXTI_RTSR_RT19 EXTI_RTSR_TR19 /****************** Bit definition for EXTI_FTSR register *******************/ #define EXTI_FTSR_TR0_Pos (0U) @@ -2903,6 +3350,12 @@ typedef struct #define EXTI_FTSR_TR17_Pos (17U) #define EXTI_FTSR_TR17_Msk (0x1U << EXTI_FTSR_TR17_Pos) /*!< 0x00020000 */ #define EXTI_FTSR_TR17 EXTI_FTSR_TR17_Msk /*!< Falling trigger event configuration bit of line 17 */ +#define EXTI_FTSR_TR18_Pos (18U) +#define EXTI_FTSR_TR18_Msk (0x1U << EXTI_FTSR_TR18_Pos) /*!< 0x00040000 */ +#define EXTI_FTSR_TR18 EXTI_FTSR_TR18_Msk /*!< Falling trigger event configuration bit of line 18 */ +#define EXTI_FTSR_TR19_Pos (19U) +#define EXTI_FTSR_TR19_Msk (0x1U << EXTI_FTSR_TR19_Pos) /*!< 0x00080000 */ +#define EXTI_FTSR_TR19 EXTI_FTSR_TR19_Msk /*!< Falling trigger event configuration bit of line 19 */ /* References Defines */ #define EXTI_FTSR_FT0 EXTI_FTSR_TR0 @@ -2923,6 +3376,8 @@ typedef struct #define EXTI_FTSR_FT15 EXTI_FTSR_TR15 #define EXTI_FTSR_FT16 EXTI_FTSR_TR16 #define EXTI_FTSR_FT17 EXTI_FTSR_TR17 +#define EXTI_FTSR_FT18 EXTI_FTSR_TR18 +#define EXTI_FTSR_FT19 EXTI_FTSR_TR19 /****************** Bit definition for EXTI_SWIER register ******************/ #define EXTI_SWIER_SWIER0_Pos (0U) @@ -2979,6 +3434,12 @@ typedef struct #define EXTI_SWIER_SWIER17_Pos (17U) #define EXTI_SWIER_SWIER17_Msk (0x1U << EXTI_SWIER_SWIER17_Pos) /*!< 0x00020000 */ #define EXTI_SWIER_SWIER17 EXTI_SWIER_SWIER17_Msk /*!< Software Interrupt on line 17 */ +#define EXTI_SWIER_SWIER18_Pos (18U) +#define EXTI_SWIER_SWIER18_Msk (0x1U << EXTI_SWIER_SWIER18_Pos) /*!< 0x00040000 */ +#define EXTI_SWIER_SWIER18 EXTI_SWIER_SWIER18_Msk /*!< Software Interrupt on line 18 */ +#define EXTI_SWIER_SWIER19_Pos (19U) +#define EXTI_SWIER_SWIER19_Msk (0x1U << EXTI_SWIER_SWIER19_Pos) /*!< 0x00080000 */ +#define EXTI_SWIER_SWIER19 EXTI_SWIER_SWIER19_Msk /*!< Software Interrupt on line 19 */ /* References Defines */ #define EXTI_SWIER_SWI0 EXTI_SWIER_SWIER0 @@ -2999,6 +3460,8 @@ typedef struct #define EXTI_SWIER_SWI15 EXTI_SWIER_SWIER15 #define EXTI_SWIER_SWI16 EXTI_SWIER_SWIER16 #define EXTI_SWIER_SWI17 EXTI_SWIER_SWIER17 +#define EXTI_SWIER_SWI18 EXTI_SWIER_SWIER18 +#define EXTI_SWIER_SWI19 EXTI_SWIER_SWIER19 /******************* Bit definition for EXTI_PR register ********************/ #define EXTI_PR_PR0_Pos (0U) @@ -3055,6 +3518,12 @@ typedef struct #define EXTI_PR_PR17_Pos (17U) #define EXTI_PR_PR17_Msk (0x1U << EXTI_PR_PR17_Pos) /*!< 0x00020000 */ #define EXTI_PR_PR17 EXTI_PR_PR17_Msk /*!< Pending bit for line 17 */ +#define EXTI_PR_PR18_Pos (18U) +#define EXTI_PR_PR18_Msk (0x1U << EXTI_PR_PR18_Pos) /*!< 0x00040000 */ +#define EXTI_PR_PR18 EXTI_PR_PR18_Msk /*!< Pending bit for line 18 */ +#define EXTI_PR_PR19_Pos (19U) +#define EXTI_PR_PR19_Msk (0x1U << EXTI_PR_PR19_Pos) /*!< 0x00080000 */ +#define EXTI_PR_PR19 EXTI_PR_PR19_Msk /*!< Pending bit for line 19 */ /* References Defines */ #define EXTI_PR_PIF0 EXTI_PR_PR0 @@ -3075,6 +3544,8 @@ typedef struct #define EXTI_PR_PIF15 EXTI_PR_PR15 #define EXTI_PR_PIF16 EXTI_PR_PR16 #define EXTI_PR_PIF17 EXTI_PR_PR17 +#define EXTI_PR_PIF18 EXTI_PR_PR18 +#define EXTI_PR_PIF19 EXTI_PR_PR19 /******************************************************************************/ /* */ @@ -4177,6 +4648,10 @@ typedef struct #define TIM_SMCR_SMS_1 (0x2U << TIM_SMCR_SMS_Pos) /*!< 0x00000002 */ #define TIM_SMCR_SMS_2 (0x4U << TIM_SMCR_SMS_Pos) /*!< 0x00000004 */ +#define TIM_SMCR_OCCS_Pos (3U) +#define TIM_SMCR_OCCS_Msk (0x1U << TIM_SMCR_OCCS_Pos) /*!< 0x00000008 */ +#define TIM_SMCR_OCCS TIM_SMCR_OCCS_Msk /*!< OCREF clear selection */ + #define TIM_SMCR_TS_Pos (4U) #define TIM_SMCR_TS_Msk (0x7U << TIM_SMCR_TS_Pos) /*!< 0x00000070 */ #define TIM_SMCR_TS TIM_SMCR_TS_Msk /*!
© COPYRIGHT(c) 2017 STMicroelectronics
+ *

© COPYRIGHT(c) 2016 STMicroelectronics

* * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: @@ -108,10 +108,10 @@ #endif /* USE_HAL_DRIVER */ /** - * @brief CMSIS Device version number V4.2.0 + * @brief CMSIS Device version number V4.0.0 */ -#define __STM32F1_CMSIS_VERSION_MAIN (0x04) /*!< [31:24] main version */ -#define __STM32F1_CMSIS_VERSION_SUB1 (0x02) /*!< [23:16] sub1 version */ +#define __STM32F1_CMSIS_VERSION_MAIN (0x04) /*!< [31:24] main version */ +#define __STM32F1_CMSIS_VERSION_SUB1 (0x01) /*!< [23:16] sub1 version */ #define __STM32F1_CMSIS_VERSION_SUB2 (0x00) /*!< [15:8] sub2 version */ #define __STM32F1_CMSIS_VERSION_RC (0x00) /*!< [7:0] release candidate */ #define __STM32F1_CMSIS_VERSION ((__STM32F1_CMSIS_VERSION_MAIN << 24)\ diff --git a/targets/TARGET_STM/TARGET_STM32F1/TARGET_DISCO_F100RB/device/system_stm32f1xx.c b/targets/TARGET_STM/TARGET_STM32F1/TARGET_DISCO_F100RB/device/system_stm32f1xx.c index a2efc1a6e18..0c2e24fd702 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/TARGET_DISCO_F100RB/device/system_stm32f1xx.c +++ b/targets/TARGET_STM/TARGET_STM32F1/TARGET_DISCO_F100RB/device/system_stm32f1xx.c @@ -2,8 +2,8 @@ ****************************************************************************** * @file system_stm32f1xx.c * @author MCD Application Team - * @version V4.2.0 - * @date 31-March-2017 + * @version V4.1.0 + * @date 29-April-2016 * @brief CMSIS Cortex-M3 Device Peripheral Access Layer System Source File. * * 1. This file provides two functions and one global variable to be called from @@ -50,7 +50,7 @@ ****************************************************************************** * @attention * - *

© COPYRIGHT(c) 2017 STMicroelectronics

+ *

© COPYRIGHT(c) 2016 STMicroelectronics

* * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: @@ -109,12 +109,12 @@ */ #if !defined (HSE_VALUE) - #define HSE_VALUE 8000000U /*!< Default value of the External oscillator in Hz. + #define HSE_VALUE ((uint32_t)8000000) /*!< Default value of the External oscillator in Hz. This value can be provided and adapted by the user application. */ #endif /* HSE_VALUE */ #if !defined (HSI_VALUE) - #define HSI_VALUE 8000000U /*!< Default value of the Internal oscillator in Hz. + #define HSI_VALUE ((uint32_t)8000000) /*!< Default value of the Internal oscillator in Hz. This value can be provided and adapted by the user application. */ #endif /* HSI_VALUE */ @@ -126,7 +126,7 @@ /*!< Uncomment the following line if you need to relocate your vector Table in Internal SRAM. */ /* #define VECT_TAB_SRAM */ -#define VECT_TAB_OFFSET 0x00000000U /*!< Vector Table base offset field. +#define VECT_TAB_OFFSET 0x0 /*!< Vector Table base offset field. This value must be a multiple of 0x200. */ @@ -154,13 +154,13 @@ * Clock Definitions *******************************************************************************/ #if defined(STM32F100xB) ||defined(STM32F100xE) - uint32_t SystemCoreClock = 24000000U; /*!< System Clock Frequency (Core Clock) */ + uint32_t SystemCoreClock = 24000000; /*!< System Clock Frequency (Core Clock) */ #else /*!< HSI Selected as System Clock source */ - uint32_t SystemCoreClock = 72000000U; /*!< System Clock Frequency (Core Clock) */ + uint32_t SystemCoreClock = 72000000; /*!< System Clock Frequency (Core Clock) */ #endif -const uint8_t AHBPrescTable[16U] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 7, 8, 9}; -const uint8_t APBPrescTable[8U] = {0, 0, 0, 0, 1, 2, 3, 4}; +const uint8_t AHBPrescTable[16] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 7, 8, 9}; +const uint8_t APBPrescTable[8] = {0, 0, 0, 0, 1, 2, 3, 4}; /** * @} @@ -202,42 +202,42 @@ void SystemInit (void) { /* Reset the RCC clock configuration to the default reset state(for debug purpose) */ /* Set HSION bit */ - RCC->CR |= 0x00000001U; + RCC->CR |= (uint32_t)0x00000001; /* Reset SW, HPRE, PPRE1, PPRE2, ADCPRE and MCO bits */ #if !defined(STM32F105xC) && !defined(STM32F107xC) - RCC->CFGR &= 0xF8FF0000U; + RCC->CFGR &= (uint32_t)0xF8FF0000; #else - RCC->CFGR &= 0xF0FF0000U; + RCC->CFGR &= (uint32_t)0xF0FF0000; #endif /* STM32F105xC */ /* Reset HSEON, CSSON and PLLON bits */ - RCC->CR &= 0xFEF6FFFFU; + RCC->CR &= (uint32_t)0xFEF6FFFF; /* Reset HSEBYP bit */ - RCC->CR &= 0xFFFBFFFFU; + RCC->CR &= (uint32_t)0xFFFBFFFF; /* Reset PLLSRC, PLLXTPRE, PLLMUL and USBPRE/OTGFSPRE bits */ - RCC->CFGR &= 0xFF80FFFFU; + RCC->CFGR &= (uint32_t)0xFF80FFFF; #if defined(STM32F105xC) || defined(STM32F107xC) /* Reset PLL2ON and PLL3ON bits */ - RCC->CR &= 0xEBFFFFFFU; + RCC->CR &= (uint32_t)0xEBFFFFFF; /* Disable all interrupts and clear pending bits */ - RCC->CIR = 0x00FF0000U; + RCC->CIR = 0x00FF0000; /* Reset CFGR2 register */ - RCC->CFGR2 = 0x00000000U; + RCC->CFGR2 = 0x00000000; #elif defined(STM32F100xB) || defined(STM32F100xE) /* Disable all interrupts and clear pending bits */ - RCC->CIR = 0x009F0000U; + RCC->CIR = 0x009F0000; /* Reset CFGR2 register */ - RCC->CFGR2 = 0x00000000U; + RCC->CFGR2 = 0x00000000; #else /* Disable all interrupts and clear pending bits */ - RCC->CIR = 0x009F0000U; + RCC->CIR = 0x009F0000; #endif /* STM32F105xC */ #if defined(STM32F100xE) || defined(STM32F101xE) || defined(STM32F101xG) || defined(STM32F103xE) || defined(STM32F103xG) @@ -302,14 +302,14 @@ void SystemInit (void) */ void SystemCoreClockUpdate (void) { - uint32_t tmp = 0U, pllmull = 0U, pllsource = 0U; + uint32_t tmp = 0, pllmull = 0, pllsource = 0; #if defined(STM32F105xC) || defined(STM32F107xC) - uint32_t prediv1source = 0U, prediv1factor = 0U, prediv2factor = 0U, pll2mull = 0U; + uint32_t prediv1source = 0, prediv1factor = 0, prediv2factor = 0, pll2mull = 0; #endif /* STM32F105xC */ #if defined(STM32F100xB) || defined(STM32F100xE) - uint32_t prediv1factor = 0U; + uint32_t prediv1factor = 0; #endif /* STM32F100xB or STM32F100xE */ /* Get SYSCLK source -------------------------------------------------------*/ @@ -317,37 +317,37 @@ void SystemCoreClockUpdate (void) switch (tmp) { - case 0x00U: /* HSI used as system clock */ + case 0x00: /* HSI used as system clock */ SystemCoreClock = HSI_VALUE; break; - case 0x04U: /* HSE used as system clock */ + case 0x04: /* HSE used as system clock */ SystemCoreClock = HSE_VALUE; break; - case 0x08U: /* PLL used as system clock */ + case 0x08: /* PLL used as system clock */ /* Get PLL clock source and multiplication factor ----------------------*/ pllmull = RCC->CFGR & RCC_CFGR_PLLMULL; pllsource = RCC->CFGR & RCC_CFGR_PLLSRC; #if !defined(STM32F105xC) && !defined(STM32F107xC) - pllmull = ( pllmull >> 18U) + 2U; + pllmull = ( pllmull >> 18) + 2; - if (pllsource == 0x00U) + if (pllsource == 0x00) { /* HSI oscillator clock divided by 2 selected as PLL clock entry */ - SystemCoreClock = (HSI_VALUE >> 1U) * pllmull; + SystemCoreClock = (HSI_VALUE >> 1) * pllmull; } else { #if defined(STM32F100xB) || defined(STM32F100xE) - prediv1factor = (RCC->CFGR2 & RCC_CFGR2_PREDIV1) + 1U; + prediv1factor = (RCC->CFGR2 & RCC_CFGR2_PREDIV1) + 1; /* HSE oscillator clock selected as PREDIV1 clock entry */ SystemCoreClock = (HSE_VALUE / prediv1factor) * pllmull; #else /* HSE selected as PLL clock entry */ if ((RCC->CFGR & RCC_CFGR_PLLXTPRE) != (uint32_t)RESET) {/* HSE oscillator clock divided by 2 */ - SystemCoreClock = (HSE_VALUE >> 1U) * pllmull; + SystemCoreClock = (HSE_VALUE >> 1) * pllmull; } else { @@ -356,30 +356,30 @@ void SystemCoreClockUpdate (void) #endif } #else - pllmull = pllmull >> 18U; + pllmull = pllmull >> 18; - if (pllmull != 0x0DU) + if (pllmull != 0x0D) { - pllmull += 2U; + pllmull += 2; } else { /* PLL multiplication factor = PLL input clock * 6.5 */ - pllmull = 13U / 2U; + pllmull = 13 / 2; } - if (pllsource == 0x00U) + if (pllsource == 0x00) { /* HSI oscillator clock divided by 2 selected as PLL clock entry */ - SystemCoreClock = (HSI_VALUE >> 1U) * pllmull; + SystemCoreClock = (HSI_VALUE >> 1) * pllmull; } else {/* PREDIV1 selected as PLL clock entry */ /* Get PREDIV1 clock source and division factor */ prediv1source = RCC->CFGR2 & RCC_CFGR2_PREDIV1SRC; - prediv1factor = (RCC->CFGR2 & RCC_CFGR2_PREDIV1) + 1U; + prediv1factor = (RCC->CFGR2 & RCC_CFGR2_PREDIV1) + 1; - if (prediv1source == 0U) + if (prediv1source == 0) { /* HSE oscillator clock selected as PREDIV1 clock entry */ SystemCoreClock = (HSE_VALUE / prediv1factor) * pllmull; @@ -388,8 +388,8 @@ void SystemCoreClockUpdate (void) {/* PLL2 clock selected as PREDIV1 clock entry */ /* Get PREDIV2 division factor and PLL2 multiplication factor */ - prediv2factor = ((RCC->CFGR2 & RCC_CFGR2_PREDIV2) >> 4U) + 1U; - pll2mull = ((RCC->CFGR2 & RCC_CFGR2_PLL2MUL) >> 8U) + 2U; + prediv2factor = ((RCC->CFGR2 & RCC_CFGR2_PREDIV2) >> 4) + 1; + pll2mull = ((RCC->CFGR2 & RCC_CFGR2_PLL2MUL) >> 8 ) + 2; SystemCoreClock = (((HSE_VALUE / prediv2factor) * pll2mull) / prediv1factor) * pllmull; } } @@ -403,7 +403,7 @@ void SystemCoreClockUpdate (void) /* Compute HCLK clock frequency ----------------*/ /* Get HCLK prescaler */ - tmp = AHBPrescTable[((RCC->CFGR & RCC_CFGR_HPRE) >> 4U)]; + tmp = AHBPrescTable[((RCC->CFGR & RCC_CFGR_HPRE) >> 4)]; /* HCLK clock frequency */ SystemCoreClock >>= tmp; } @@ -432,13 +432,13 @@ void SystemInit_ExtMemCtl(void) required, then adjust the Register Addresses */ /* Enable FSMC clock */ - RCC->AHBENR = 0x00000114U; + RCC->AHBENR = 0x00000114; /* Delay after an RCC peripheral clock enabling */ tmpreg = READ_BIT(RCC->AHBENR, RCC_AHBENR_FSMCEN); /* Enable GPIOD, GPIOE, GPIOF and GPIOG clocks */ - RCC->APB2ENR = 0x000001E0U; + RCC->APB2ENR = 0x000001E0; /* Delay after an RCC peripheral clock enabling */ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_IOPDEN); @@ -451,23 +451,23 @@ void SystemInit_ExtMemCtl(void) /*---------------- NE3 configuration ----------------------------------------*/ /*---------------- NBL0, NBL1 configuration ---------------------------------*/ - GPIOD->CRL = 0x44BB44BBU; - GPIOD->CRH = 0xBBBBBBBBU; + GPIOD->CRL = 0x44BB44BB; + GPIOD->CRH = 0xBBBBBBBB; - GPIOE->CRL = 0xB44444BBU; - GPIOE->CRH = 0xBBBBBBBBU; + GPIOE->CRL = 0xB44444BB; + GPIOE->CRH = 0xBBBBBBBB; - GPIOF->CRL = 0x44BBBBBBU; - GPIOF->CRH = 0xBBBB4444U; + GPIOF->CRL = 0x44BBBBBB; + GPIOF->CRH = 0xBBBB4444; - GPIOG->CRL = 0x44BBBBBBU; - GPIOG->CRH = 0x444B4B44U; + GPIOG->CRL = 0x44BBBBBB; + GPIOG->CRH = 0x444B4B44; /*---------------- FSMC Configuration ---------------------------------------*/ /*---------------- Enable FSMC Bank1_SRAM Bank ------------------------------*/ - FSMC_Bank1->BTCR[4U] = 0x00001091U; - FSMC_Bank1->BTCR[5U] = 0x00110212U; + FSMC_Bank1->BTCR[4] = 0x00001091; + FSMC_Bank1->BTCR[5] = 0x00110212; } #endif /* DATA_IN_ExtSRAM */ #endif /* STM32F100xE || STM32F101xE || STM32F101xG || STM32F103xE || STM32F103xG */ diff --git a/targets/TARGET_STM/TARGET_STM32F1/TARGET_DISCO_F100RB/device/system_stm32f1xx.h b/targets/TARGET_STM/TARGET_STM32F1/TARGET_DISCO_F100RB/device/system_stm32f1xx.h index f2557fa9579..8efeb9aadbc 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/TARGET_DISCO_F100RB/device/system_stm32f1xx.h +++ b/targets/TARGET_STM/TARGET_STM32F1/TARGET_DISCO_F100RB/device/system_stm32f1xx.h @@ -2,13 +2,13 @@ ****************************************************************************** * @file system_stm32f10x.h * @author MCD Application Team - * @version V4.2.0 - * @date 31-March-2017 + * @version V4.1.0 + * @date 29-April-2016 * @brief CMSIS Cortex-M3 Device Peripheral Access Layer System Header File. ****************************************************************************** * @attention * - *

© COPYRIGHT(c) 2017 STMicroelectronics

+ *

© COPYRIGHT(c) 2016 STMicroelectronics

* * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: @@ -67,8 +67,8 @@ */ extern uint32_t SystemCoreClock; /*!< System Clock Frequency (Core Clock) */ -extern const uint8_t AHBPrescTable[16U]; /*!< AHB prescalers table values */ -extern const uint8_t APBPrescTable[8U]; /*!< APB prescalers table values */ +extern const uint8_t AHBPrescTable[16]; /*!< AHB prescalers table values */ +extern const uint8_t APBPrescTable[8]; /*!< APB prescalers table values */ /** * @} diff --git a/targets/TARGET_STM/TARGET_STM32F1/TARGET_NUCLEO_F103RB/PinNames.h b/targets/TARGET_STM/TARGET_STM32F1/TARGET_NUCLEO_F103RB/PinNames.h index ba7e6b30fee..2576abd66de 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/TARGET_NUCLEO_F103RB/PinNames.h +++ b/targets/TARGET_STM/TARGET_STM32F1/TARGET_NUCLEO_F103RB/PinNames.h @@ -125,8 +125,6 @@ typedef enum { LED3 = PA_5, LED4 = PA_5, USER_BUTTON = PC_13, - // Standardized button names - BUTTON1 = USER_BUTTON, SERIAL_TX = PA_2, SERIAL_RX = PA_3, USBTX = PA_2, diff --git a/features/unsupported/USBDevice/USBDevice/TARGET_STM/TARGET_STM32F1/TARGET_NUCLEO_F103RB/USBHAL_STM32F103RB.h b/targets/TARGET_STM/TARGET_STM32F1/TARGET_NUCLEO_F103RB/USBHAL_STM32F103RB.h similarity index 100% rename from features/unsupported/USBDevice/USBDevice/TARGET_STM/TARGET_STM32F1/TARGET_NUCLEO_F103RB/USBHAL_STM32F103RB.h rename to targets/TARGET_STM/TARGET_STM32F1/TARGET_NUCLEO_F103RB/USBHAL_STM32F103RB.h diff --git a/features/unsupported/USBDevice/USBDevice/TARGET_STM/TARGET_STM32F1/TARGET_NUCLEO_F103RB/USBHAL_STM_TARGET.h b/targets/TARGET_STM/TARGET_STM32F1/TARGET_NUCLEO_F103RB/USBHAL_STM_TARGET.h similarity index 100% rename from features/unsupported/USBDevice/USBDevice/TARGET_STM/TARGET_STM32F1/TARGET_NUCLEO_F103RB/USBHAL_STM_TARGET.h rename to targets/TARGET_STM/TARGET_STM32F1/TARGET_NUCLEO_F103RB/USBHAL_STM_TARGET.h diff --git a/targets/TARGET_STM/TARGET_STM32F1/TARGET_NUCLEO_F103RB/device/hal_tick.h b/targets/TARGET_STM/TARGET_STM32F1/TARGET_NUCLEO_F103RB/device/hal_tick.h index 5872d57f7ae..608a14ff991 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/TARGET_NUCLEO_F103RB/device/hal_tick.h +++ b/targets/TARGET_STM/TARGET_STM32F1/TARGET_NUCLEO_F103RB/device/hal_tick.h @@ -44,10 +44,10 @@ #define TIM_MST TIM4 #define TIM_MST_IRQ TIM4_IRQn -#define TIM_MST_RCC __HAL_RCC_TIM4_CLK_ENABLE() +#define TIM_MST_RCC __TIM4_CLK_ENABLE() -#define TIM_MST_RESET_ON __HAL_RCC_TIM4_FORCE_RESET() -#define TIM_MST_RESET_OFF __HAL_RCC_TIM4_RELEASE_RESET() +#define TIM_MST_RESET_ON __TIM4_FORCE_RESET() +#define TIM_MST_RESET_OFF __TIM4_RELEASE_RESET() #define TIM_MST_16BIT 1 // 1=16-bit timer, 0=32-bit timer diff --git a/targets/TARGET_STM/TARGET_STM32F1/TARGET_NUCLEO_F103RB/device/stm32f103xb.h b/targets/TARGET_STM/TARGET_STM32F1/TARGET_NUCLEO_F103RB/device/stm32f103xb.h index 9ff8ad63859..140567a9a2a 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/TARGET_NUCLEO_F103RB/device/stm32f103xb.h +++ b/targets/TARGET_STM/TARGET_STM32F1/TARGET_NUCLEO_F103RB/device/stm32f103xb.h @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f103xb.h * @author MCD Application Team - * @version V4.2.0 - * @date 31-March-2017 + * @version V4.1.0 + * @date 29-April-2016 * @brief CMSIS Cortex-M3 Device Peripheral Access Layer Header File. * This file contains all the peripheral register's definitions, bits * definitions and memory mapping for STM32F1xx devices. @@ -16,7 +16,7 @@ ****************************************************************************** * @attention * - *

© COPYRIGHT(c) 2017 STMicroelectronics

+ *

© COPYRIGHT(c) 2016 STMicroelectronics

* * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: @@ -65,10 +65,10 @@ /** * @brief Configuration of the Cortex-M3 Processor and Core Peripherals */ -#define __CM3_REV 0x0200U /*!< Core Revision r2p0 */ - #define __MPU_PRESENT 0U /*!< Other STM32 devices does not provide an MPU */ -#define __NVIC_PRIO_BITS 4U /*!< STM32 uses 4 Bits for the Priority Levels */ -#define __Vendor_SysTickConfig 0U /*!< Set to 1 if different SysTick Config is used */ + #define __MPU_PRESENT 0 /*!< Other STM32 devices does not provide an MPU */ +#define __CM3_REV 0x0200 /*!< Core Revision r2p0 */ +#define __NVIC_PRIO_BITS 4 /*!< STM32 uses 4 Bits for the Priority Levels */ +#define __Vendor_SysTickConfig 0 /*!< Set to 1 if different SysTick Config is used */ /** * @} @@ -143,6 +143,7 @@ typedef enum USBWakeUp_IRQn = 42, /*!< USB Device WakeUp from suspend through EXTI Line Interrupt */ } IRQn_Type; + /** * @} */ @@ -616,72 +617,72 @@ typedef struct */ -#define FLASH_BASE 0x08000000U /*!< FLASH base address in the alias region */ -#define FLASH_BANK1_END 0x0801FFFFU /*!< FLASH END address of bank1 */ -#define SRAM_BASE 0x20000000U /*!< SRAM base address in the alias region */ -#define PERIPH_BASE 0x40000000U /*!< Peripheral base address in the alias region */ +#define FLASH_BASE ((uint32_t)0x08000000) /*!< FLASH base address in the alias region */ +#define FLASH_BANK1_END ((uint32_t)0x0801FFFF) /*!< FLASH END address of bank1 */ +#define SRAM_BASE ((uint32_t)0x20000000) /*!< SRAM base address in the alias region */ +#define PERIPH_BASE ((uint32_t)0x40000000) /*!< Peripheral base address in the alias region */ -#define SRAM_BB_BASE 0x22000000U /*!< SRAM base address in the bit-band region */ -#define PERIPH_BB_BASE 0x42000000U /*!< Peripheral base address in the bit-band region */ +#define SRAM_BB_BASE ((uint32_t)0x22000000) /*!< SRAM base address in the bit-band region */ +#define PERIPH_BB_BASE ((uint32_t)0x42000000) /*!< Peripheral base address in the bit-band region */ /*!< Peripheral memory map */ #define APB1PERIPH_BASE PERIPH_BASE -#define APB2PERIPH_BASE (PERIPH_BASE + 0x00010000U) -#define AHBPERIPH_BASE (PERIPH_BASE + 0x00020000U) - -#define TIM2_BASE (APB1PERIPH_BASE + 0x00000000U) -#define TIM3_BASE (APB1PERIPH_BASE + 0x00000400U) -#define TIM4_BASE (APB1PERIPH_BASE + 0x00000800U) -#define RTC_BASE (APB1PERIPH_BASE + 0x00002800U) -#define WWDG_BASE (APB1PERIPH_BASE + 0x00002C00U) -#define IWDG_BASE (APB1PERIPH_BASE + 0x00003000U) -#define SPI2_BASE (APB1PERIPH_BASE + 0x00003800U) -#define USART2_BASE (APB1PERIPH_BASE + 0x00004400U) -#define USART3_BASE (APB1PERIPH_BASE + 0x00004800U) -#define I2C1_BASE (APB1PERIPH_BASE + 0x00005400U) +#define APB2PERIPH_BASE (PERIPH_BASE + 0x10000) +#define AHBPERIPH_BASE (PERIPH_BASE + 0x20000) + +#define TIM2_BASE (APB1PERIPH_BASE + 0x0000) +#define TIM3_BASE (APB1PERIPH_BASE + 0x0400) +#define TIM4_BASE (APB1PERIPH_BASE + 0x0800) +#define RTC_BASE (APB1PERIPH_BASE + 0x2800) +#define WWDG_BASE (APB1PERIPH_BASE + 0x2C00) +#define IWDG_BASE (APB1PERIPH_BASE + 0x3000) +#define SPI2_BASE (APB1PERIPH_BASE + 0x3800) +#define USART2_BASE (APB1PERIPH_BASE + 0x4400) +#define USART3_BASE (APB1PERIPH_BASE + 0x4800) +#define I2C1_BASE (APB1PERIPH_BASE + 0x5400) #define I2C2_BASE (APB1PERIPH_BASE + 0x5800) -#define CAN1_BASE (APB1PERIPH_BASE + 0x00006400U) -#define BKP_BASE (APB1PERIPH_BASE + 0x00006C00U) -#define PWR_BASE (APB1PERIPH_BASE + 0x00007000U) -#define AFIO_BASE (APB2PERIPH_BASE + 0x00000000U) -#define EXTI_BASE (APB2PERIPH_BASE + 0x00000400U) -#define GPIOA_BASE (APB2PERIPH_BASE + 0x00000800U) -#define GPIOB_BASE (APB2PERIPH_BASE + 0x00000C00U) -#define GPIOC_BASE (APB2PERIPH_BASE + 0x00001000U) -#define GPIOD_BASE (APB2PERIPH_BASE + 0x00001400U) -#define GPIOE_BASE (APB2PERIPH_BASE + 0x00001800U) -#define ADC1_BASE (APB2PERIPH_BASE + 0x00002400U) -#define ADC2_BASE (APB2PERIPH_BASE + 0x00002800U) -#define TIM1_BASE (APB2PERIPH_BASE + 0x00002C00U) -#define SPI1_BASE (APB2PERIPH_BASE + 0x00003000U) -#define USART1_BASE (APB2PERIPH_BASE + 0x00003800U) - -#define SDIO_BASE (PERIPH_BASE + 0x00018000U) - -#define DMA1_BASE (AHBPERIPH_BASE + 0x00000000U) -#define DMA1_Channel1_BASE (AHBPERIPH_BASE + 0x00000008U) -#define DMA1_Channel2_BASE (AHBPERIPH_BASE + 0x0000001CU) -#define DMA1_Channel3_BASE (AHBPERIPH_BASE + 0x00000030U) -#define DMA1_Channel4_BASE (AHBPERIPH_BASE + 0x00000044U) -#define DMA1_Channel5_BASE (AHBPERIPH_BASE + 0x00000058U) -#define DMA1_Channel6_BASE (AHBPERIPH_BASE + 0x0000006CU) -#define DMA1_Channel7_BASE (AHBPERIPH_BASE + 0x00000080U) -#define RCC_BASE (AHBPERIPH_BASE + 0x00001000U) -#define CRC_BASE (AHBPERIPH_BASE + 0x00003000U) - -#define FLASH_R_BASE (AHBPERIPH_BASE + 0x00002000U) /*!< Flash registers base address */ -#define FLASHSIZE_BASE 0x1FFFF7E0U /*!< FLASH Size register base address */ -#define UID_BASE 0x1FFFF7E8U /*!< Unique device ID register base address */ -#define OB_BASE 0x1FFFF800U /*!< Flash Option Bytes base address */ - - - -#define DBGMCU_BASE 0xE0042000U /*!< Debug MCU registers base address */ +#define CAN1_BASE (APB1PERIPH_BASE + 0x6400) +#define BKP_BASE (APB1PERIPH_BASE + 0x6C00) +#define PWR_BASE (APB1PERIPH_BASE + 0x7000) +#define AFIO_BASE (APB2PERIPH_BASE + 0x0000) +#define EXTI_BASE (APB2PERIPH_BASE + 0x0400) +#define GPIOA_BASE (APB2PERIPH_BASE + 0x0800) +#define GPIOB_BASE (APB2PERIPH_BASE + 0x0C00) +#define GPIOC_BASE (APB2PERIPH_BASE + 0x1000) +#define GPIOD_BASE (APB2PERIPH_BASE + 0x1400) +#define GPIOE_BASE (APB2PERIPH_BASE + 0x1800) +#define ADC1_BASE (APB2PERIPH_BASE + 0x2400) +#define ADC2_BASE (APB2PERIPH_BASE + 0x2800) +#define TIM1_BASE (APB2PERIPH_BASE + 0x2C00) +#define SPI1_BASE (APB2PERIPH_BASE + 0x3000) +#define USART1_BASE (APB2PERIPH_BASE + 0x3800) + +#define SDIO_BASE (PERIPH_BASE + 0x18000) + +#define DMA1_BASE (AHBPERIPH_BASE + 0x0000) +#define DMA1_Channel1_BASE (AHBPERIPH_BASE + 0x0008) +#define DMA1_Channel2_BASE (AHBPERIPH_BASE + 0x001C) +#define DMA1_Channel3_BASE (AHBPERIPH_BASE + 0x0030) +#define DMA1_Channel4_BASE (AHBPERIPH_BASE + 0x0044) +#define DMA1_Channel5_BASE (AHBPERIPH_BASE + 0x0058) +#define DMA1_Channel6_BASE (AHBPERIPH_BASE + 0x006C) +#define DMA1_Channel7_BASE (AHBPERIPH_BASE + 0x0080) +#define RCC_BASE (AHBPERIPH_BASE + 0x1000) +#define CRC_BASE (AHBPERIPH_BASE + 0x3000) + +#define FLASH_R_BASE (AHBPERIPH_BASE + 0x2000) /*!< Flash registers base address */ +#define FLASHSIZE_BASE ((uint32_t)0x1FFFF7E0) /*!< FLASH Size register base address */ +#define UID_BASE ((uint32_t)0x1FFFF7E8) /*!< Unique device ID register base address */ +#define OB_BASE ((uint32_t)0x1FFFF800) /*!< Flash Option Bytes base address */ + + + +#define DBGMCU_BASE ((uint32_t)0xE0042000) /*!< Debug MCU registers base address */ /* USB device FS */ -#define USB_BASE (APB1PERIPH_BASE + 0x00005C00U) /*!< USB_IP Peripheral Registers base address */ -#define USB_PMAADDR (APB1PERIPH_BASE + 0x00006000U) /*!< USB_IP Packet Memory Area base address */ +#define USB_BASE (APB1PERIPH_BASE + 0x00005C00) /*!< USB_IP Peripheral Registers base address */ +#define USB_PMAADDR (APB1PERIPH_BASE + 0x00006000) /*!< USB_IP Packet Memory Area base address */ /** @@ -692,48 +693,48 @@ typedef struct * @{ */ -#define TIM2 ((TIM_TypeDef *)TIM2_BASE) -#define TIM3 ((TIM_TypeDef *)TIM3_BASE) -#define TIM4 ((TIM_TypeDef *)TIM4_BASE) -#define RTC ((RTC_TypeDef *)RTC_BASE) -#define WWDG ((WWDG_TypeDef *)WWDG_BASE) -#define IWDG ((IWDG_TypeDef *)IWDG_BASE) -#define SPI2 ((SPI_TypeDef *)SPI2_BASE) -#define USART2 ((USART_TypeDef *)USART2_BASE) -#define USART3 ((USART_TypeDef *)USART3_BASE) -#define I2C1 ((I2C_TypeDef *)I2C1_BASE) -#define I2C2 ((I2C_TypeDef *)I2C2_BASE) -#define USB ((USB_TypeDef *)USB_BASE) -#define CAN1 ((CAN_TypeDef *)CAN1_BASE) -#define BKP ((BKP_TypeDef *)BKP_BASE) -#define PWR ((PWR_TypeDef *)PWR_BASE) -#define AFIO ((AFIO_TypeDef *)AFIO_BASE) -#define EXTI ((EXTI_TypeDef *)EXTI_BASE) -#define GPIOA ((GPIO_TypeDef *)GPIOA_BASE) -#define GPIOB ((GPIO_TypeDef *)GPIOB_BASE) -#define GPIOC ((GPIO_TypeDef *)GPIOC_BASE) -#define GPIOD ((GPIO_TypeDef *)GPIOD_BASE) -#define GPIOE ((GPIO_TypeDef *)GPIOE_BASE) -#define ADC1 ((ADC_TypeDef *)ADC1_BASE) -#define ADC2 ((ADC_TypeDef *)ADC2_BASE) -#define ADC12_COMMON ((ADC_Common_TypeDef *)ADC1_BASE) -#define TIM1 ((TIM_TypeDef *)TIM1_BASE) -#define SPI1 ((SPI_TypeDef *)SPI1_BASE) -#define USART1 ((USART_TypeDef *)USART1_BASE) -#define SDIO ((SDIO_TypeDef *)SDIO_BASE) -#define DMA1 ((DMA_TypeDef *)DMA1_BASE) -#define DMA1_Channel1 ((DMA_Channel_TypeDef *)DMA1_Channel1_BASE) -#define DMA1_Channel2 ((DMA_Channel_TypeDef *)DMA1_Channel2_BASE) -#define DMA1_Channel3 ((DMA_Channel_TypeDef *)DMA1_Channel3_BASE) -#define DMA1_Channel4 ((DMA_Channel_TypeDef *)DMA1_Channel4_BASE) -#define DMA1_Channel5 ((DMA_Channel_TypeDef *)DMA1_Channel5_BASE) -#define DMA1_Channel6 ((DMA_Channel_TypeDef *)DMA1_Channel6_BASE) -#define DMA1_Channel7 ((DMA_Channel_TypeDef *)DMA1_Channel7_BASE) -#define RCC ((RCC_TypeDef *)RCC_BASE) -#define CRC ((CRC_TypeDef *)CRC_BASE) -#define FLASH ((FLASH_TypeDef *)FLASH_R_BASE) -#define OB ((OB_TypeDef *)OB_BASE) -#define DBGMCU ((DBGMCU_TypeDef *)DBGMCU_BASE) +#define TIM2 ((TIM_TypeDef *) TIM2_BASE) +#define TIM3 ((TIM_TypeDef *) TIM3_BASE) +#define TIM4 ((TIM_TypeDef *) TIM4_BASE) +#define RTC ((RTC_TypeDef *) RTC_BASE) +#define WWDG ((WWDG_TypeDef *) WWDG_BASE) +#define IWDG ((IWDG_TypeDef *) IWDG_BASE) +#define SPI2 ((SPI_TypeDef *) SPI2_BASE) +#define USART2 ((USART_TypeDef *) USART2_BASE) +#define USART3 ((USART_TypeDef *) USART3_BASE) +#define I2C1 ((I2C_TypeDef *) I2C1_BASE) +#define I2C2 ((I2C_TypeDef *) I2C2_BASE) +#define USB ((USB_TypeDef *) USB_BASE) +#define CAN1 ((CAN_TypeDef *) CAN1_BASE) +#define BKP ((BKP_TypeDef *) BKP_BASE) +#define PWR ((PWR_TypeDef *) PWR_BASE) +#define AFIO ((AFIO_TypeDef *) AFIO_BASE) +#define EXTI ((EXTI_TypeDef *) EXTI_BASE) +#define GPIOA ((GPIO_TypeDef *) GPIOA_BASE) +#define GPIOB ((GPIO_TypeDef *) GPIOB_BASE) +#define GPIOC ((GPIO_TypeDef *) GPIOC_BASE) +#define GPIOD ((GPIO_TypeDef *) GPIOD_BASE) +#define GPIOE ((GPIO_TypeDef *) GPIOE_BASE) +#define ADC1 ((ADC_TypeDef *) ADC1_BASE) +#define ADC2 ((ADC_TypeDef *) ADC2_BASE) +#define ADC12_COMMON ((ADC_Common_TypeDef *) ADC1_BASE) +#define TIM1 ((TIM_TypeDef *) TIM1_BASE) +#define SPI1 ((SPI_TypeDef *) SPI1_BASE) +#define USART1 ((USART_TypeDef *) USART1_BASE) +#define SDIO ((SDIO_TypeDef *) SDIO_BASE) +#define DMA1 ((DMA_TypeDef *) DMA1_BASE) +#define DMA1_Channel1 ((DMA_Channel_TypeDef *) DMA1_Channel1_BASE) +#define DMA1_Channel2 ((DMA_Channel_TypeDef *) DMA1_Channel2_BASE) +#define DMA1_Channel3 ((DMA_Channel_TypeDef *) DMA1_Channel3_BASE) +#define DMA1_Channel4 ((DMA_Channel_TypeDef *) DMA1_Channel4_BASE) +#define DMA1_Channel5 ((DMA_Channel_TypeDef *) DMA1_Channel5_BASE) +#define DMA1_Channel6 ((DMA_Channel_TypeDef *) DMA1_Channel6_BASE) +#define DMA1_Channel7 ((DMA_Channel_TypeDef *) DMA1_Channel7_BASE) +#define RCC ((RCC_TypeDef *) RCC_BASE) +#define CRC ((CRC_TypeDef *) CRC_BASE) +#define FLASH ((FLASH_TypeDef *) FLASH_R_BASE) +#define OB ((OB_TypeDef *) OB_BASE) +#define DBGMCU ((DBGMCU_TypeDef *) DBGMCU_BASE) /** @@ -804,24 +805,14 @@ typedef struct #define PWR_CR_PLS_2 (0x4U << PWR_CR_PLS_Pos) /*!< 0x00000080 */ /*!< PVD level configuration */ -#define PWR_CR_PLS_LEV0 0x00000000U /*!< PVD level 2.2V */ -#define PWR_CR_PLS_LEV1 0x00000020U /*!< PVD level 2.3V */ -#define PWR_CR_PLS_LEV2 0x00000040U /*!< PVD level 2.4V */ -#define PWR_CR_PLS_LEV3 0x00000060U /*!< PVD level 2.5V */ -#define PWR_CR_PLS_LEV4 0x00000080U /*!< PVD level 2.6V */ -#define PWR_CR_PLS_LEV5 0x000000A0U /*!< PVD level 2.7V */ -#define PWR_CR_PLS_LEV6 0x000000C0U /*!< PVD level 2.8V */ -#define PWR_CR_PLS_LEV7 0x000000E0U /*!< PVD level 2.9V */ - -/* Legacy defines */ -#define PWR_CR_PLS_2V2 PWR_CR_PLS_LEV0 -#define PWR_CR_PLS_2V3 PWR_CR_PLS_LEV1 -#define PWR_CR_PLS_2V4 PWR_CR_PLS_LEV2 -#define PWR_CR_PLS_2V5 PWR_CR_PLS_LEV3 -#define PWR_CR_PLS_2V6 PWR_CR_PLS_LEV4 -#define PWR_CR_PLS_2V7 PWR_CR_PLS_LEV5 -#define PWR_CR_PLS_2V8 PWR_CR_PLS_LEV6 -#define PWR_CR_PLS_2V9 PWR_CR_PLS_LEV7 +#define PWR_CR_PLS_2V2 ((uint32_t)0x00000000) /*!< PVD level 2.2V */ +#define PWR_CR_PLS_2V3 ((uint32_t)0x00000020) /*!< PVD level 2.3V */ +#define PWR_CR_PLS_2V4 ((uint32_t)0x00000040) /*!< PVD level 2.4V */ +#define PWR_CR_PLS_2V5 ((uint32_t)0x00000060) /*!< PVD level 2.5V */ +#define PWR_CR_PLS_2V6 ((uint32_t)0x00000080) /*!< PVD level 2.6V */ +#define PWR_CR_PLS_2V7 ((uint32_t)0x000000A0) /*!< PVD level 2.7V */ +#define PWR_CR_PLS_2V8 ((uint32_t)0x000000C0) /*!< PVD level 2.8V */ +#define PWR_CR_PLS_2V9 ((uint32_t)0x000000E0) /*!< PVD level 2.9V */ #define PWR_CR_DBP_Pos (8U) #define PWR_CR_DBP_Msk (0x1U << PWR_CR_DBP_Pos) /*!< 0x00000100 */ @@ -986,9 +977,9 @@ typedef struct #define RCC_CFGR_SW_0 (0x1U << RCC_CFGR_SW_Pos) /*!< 0x00000001 */ #define RCC_CFGR_SW_1 (0x2U << RCC_CFGR_SW_Pos) /*!< 0x00000002 */ -#define RCC_CFGR_SW_HSI 0x00000000U /*!< HSI selected as system clock */ -#define RCC_CFGR_SW_HSE 0x00000001U /*!< HSE selected as system clock */ -#define RCC_CFGR_SW_PLL 0x00000002U /*!< PLL selected as system clock */ +#define RCC_CFGR_SW_HSI ((uint32_t)0x00000000) /*!< HSI selected as system clock */ +#define RCC_CFGR_SW_HSE ((uint32_t)0x00000001) /*!< HSE selected as system clock */ +#define RCC_CFGR_SW_PLL ((uint32_t)0x00000002) /*!< PLL selected as system clock */ /*!< SWS configuration */ #define RCC_CFGR_SWS_Pos (2U) @@ -997,9 +988,9 @@ typedef struct #define RCC_CFGR_SWS_0 (0x1U << RCC_CFGR_SWS_Pos) /*!< 0x00000004 */ #define RCC_CFGR_SWS_1 (0x2U << RCC_CFGR_SWS_Pos) /*!< 0x00000008 */ -#define RCC_CFGR_SWS_HSI 0x00000000U /*!< HSI oscillator used as system clock */ -#define RCC_CFGR_SWS_HSE 0x00000004U /*!< HSE oscillator used as system clock */ -#define RCC_CFGR_SWS_PLL 0x00000008U /*!< PLL used as system clock */ +#define RCC_CFGR_SWS_HSI ((uint32_t)0x00000000) /*!< HSI oscillator used as system clock */ +#define RCC_CFGR_SWS_HSE ((uint32_t)0x00000004) /*!< HSE oscillator used as system clock */ +#define RCC_CFGR_SWS_PLL ((uint32_t)0x00000008) /*!< PLL used as system clock */ /*!< HPRE configuration */ #define RCC_CFGR_HPRE_Pos (4U) @@ -1010,15 +1001,15 @@ typedef struct #define RCC_CFGR_HPRE_2 (0x4U << RCC_CFGR_HPRE_Pos) /*!< 0x00000040 */ #define RCC_CFGR_HPRE_3 (0x8U << RCC_CFGR_HPRE_Pos) /*!< 0x00000080 */ -#define RCC_CFGR_HPRE_DIV1 0x00000000U /*!< SYSCLK not divided */ -#define RCC_CFGR_HPRE_DIV2 0x00000080U /*!< SYSCLK divided by 2 */ -#define RCC_CFGR_HPRE_DIV4 0x00000090U /*!< SYSCLK divided by 4 */ -#define RCC_CFGR_HPRE_DIV8 0x000000A0U /*!< SYSCLK divided by 8 */ -#define RCC_CFGR_HPRE_DIV16 0x000000B0U /*!< SYSCLK divided by 16 */ -#define RCC_CFGR_HPRE_DIV64 0x000000C0U /*!< SYSCLK divided by 64 */ -#define RCC_CFGR_HPRE_DIV128 0x000000D0U /*!< SYSCLK divided by 128 */ -#define RCC_CFGR_HPRE_DIV256 0x000000E0U /*!< SYSCLK divided by 256 */ -#define RCC_CFGR_HPRE_DIV512 0x000000F0U /*!< SYSCLK divided by 512 */ +#define RCC_CFGR_HPRE_DIV1 ((uint32_t)0x00000000) /*!< SYSCLK not divided */ +#define RCC_CFGR_HPRE_DIV2 ((uint32_t)0x00000080) /*!< SYSCLK divided by 2 */ +#define RCC_CFGR_HPRE_DIV4 ((uint32_t)0x00000090) /*!< SYSCLK divided by 4 */ +#define RCC_CFGR_HPRE_DIV8 ((uint32_t)0x000000A0) /*!< SYSCLK divided by 8 */ +#define RCC_CFGR_HPRE_DIV16 ((uint32_t)0x000000B0) /*!< SYSCLK divided by 16 */ +#define RCC_CFGR_HPRE_DIV64 ((uint32_t)0x000000C0) /*!< SYSCLK divided by 64 */ +#define RCC_CFGR_HPRE_DIV128 ((uint32_t)0x000000D0) /*!< SYSCLK divided by 128 */ +#define RCC_CFGR_HPRE_DIV256 ((uint32_t)0x000000E0) /*!< SYSCLK divided by 256 */ +#define RCC_CFGR_HPRE_DIV512 ((uint32_t)0x000000F0) /*!< SYSCLK divided by 512 */ /*!< PPRE1 configuration */ #define RCC_CFGR_PPRE1_Pos (8U) @@ -1028,11 +1019,11 @@ typedef struct #define RCC_CFGR_PPRE1_1 (0x2U << RCC_CFGR_PPRE1_Pos) /*!< 0x00000200 */ #define RCC_CFGR_PPRE1_2 (0x4U << RCC_CFGR_PPRE1_Pos) /*!< 0x00000400 */ -#define RCC_CFGR_PPRE1_DIV1 0x00000000U /*!< HCLK not divided */ -#define RCC_CFGR_PPRE1_DIV2 0x00000400U /*!< HCLK divided by 2 */ -#define RCC_CFGR_PPRE1_DIV4 0x00000500U /*!< HCLK divided by 4 */ -#define RCC_CFGR_PPRE1_DIV8 0x00000600U /*!< HCLK divided by 8 */ -#define RCC_CFGR_PPRE1_DIV16 0x00000700U /*!< HCLK divided by 16 */ +#define RCC_CFGR_PPRE1_DIV1 ((uint32_t)0x00000000) /*!< HCLK not divided */ +#define RCC_CFGR_PPRE1_DIV2 ((uint32_t)0x00000400) /*!< HCLK divided by 2 */ +#define RCC_CFGR_PPRE1_DIV4 ((uint32_t)0x00000500) /*!< HCLK divided by 4 */ +#define RCC_CFGR_PPRE1_DIV8 ((uint32_t)0x00000600) /*!< HCLK divided by 8 */ +#define RCC_CFGR_PPRE1_DIV16 ((uint32_t)0x00000700) /*!< HCLK divided by 16 */ /*!< PPRE2 configuration */ #define RCC_CFGR_PPRE2_Pos (11U) @@ -1042,11 +1033,11 @@ typedef struct #define RCC_CFGR_PPRE2_1 (0x2U << RCC_CFGR_PPRE2_Pos) /*!< 0x00001000 */ #define RCC_CFGR_PPRE2_2 (0x4U << RCC_CFGR_PPRE2_Pos) /*!< 0x00002000 */ -#define RCC_CFGR_PPRE2_DIV1 0x00000000U /*!< HCLK not divided */ -#define RCC_CFGR_PPRE2_DIV2 0x00002000U /*!< HCLK divided by 2 */ -#define RCC_CFGR_PPRE2_DIV4 0x00002800U /*!< HCLK divided by 4 */ -#define RCC_CFGR_PPRE2_DIV8 0x00003000U /*!< HCLK divided by 8 */ -#define RCC_CFGR_PPRE2_DIV16 0x00003800U /*!< HCLK divided by 16 */ +#define RCC_CFGR_PPRE2_DIV1 ((uint32_t)0x00000000) /*!< HCLK not divided */ +#define RCC_CFGR_PPRE2_DIV2 ((uint32_t)0x00002000) /*!< HCLK divided by 2 */ +#define RCC_CFGR_PPRE2_DIV4 ((uint32_t)0x00002800) /*!< HCLK divided by 4 */ +#define RCC_CFGR_PPRE2_DIV8 ((uint32_t)0x00003000) /*!< HCLK divided by 8 */ +#define RCC_CFGR_PPRE2_DIV16 ((uint32_t)0x00003800) /*!< HCLK divided by 16 */ /*!< ADCPPRE configuration */ #define RCC_CFGR_ADCPRE_Pos (14U) @@ -1055,10 +1046,10 @@ typedef struct #define RCC_CFGR_ADCPRE_0 (0x1U << RCC_CFGR_ADCPRE_Pos) /*!< 0x00004000 */ #define RCC_CFGR_ADCPRE_1 (0x2U << RCC_CFGR_ADCPRE_Pos) /*!< 0x00008000 */ -#define RCC_CFGR_ADCPRE_DIV2 0x00000000U /*!< PCLK2 divided by 2 */ -#define RCC_CFGR_ADCPRE_DIV4 0x00004000U /*!< PCLK2 divided by 4 */ -#define RCC_CFGR_ADCPRE_DIV6 0x00008000U /*!< PCLK2 divided by 6 */ -#define RCC_CFGR_ADCPRE_DIV8 0x0000C000U /*!< PCLK2 divided by 8 */ +#define RCC_CFGR_ADCPRE_DIV2 ((uint32_t)0x00000000) /*!< PCLK2 divided by 2 */ +#define RCC_CFGR_ADCPRE_DIV4 ((uint32_t)0x00004000) /*!< PCLK2 divided by 4 */ +#define RCC_CFGR_ADCPRE_DIV6 ((uint32_t)0x00008000) /*!< PCLK2 divided by 6 */ +#define RCC_CFGR_ADCPRE_DIV8 ((uint32_t)0x0000C000) /*!< PCLK2 divided by 8 */ #define RCC_CFGR_PLLSRC_Pos (16U) #define RCC_CFGR_PLLSRC_Msk (0x1U << RCC_CFGR_PLLSRC_Pos) /*!< 0x00010000 */ @@ -1077,10 +1068,10 @@ typedef struct #define RCC_CFGR_PLLMULL_2 (0x4U << RCC_CFGR_PLLMULL_Pos) /*!< 0x00100000 */ #define RCC_CFGR_PLLMULL_3 (0x8U << RCC_CFGR_PLLMULL_Pos) /*!< 0x00200000 */ -#define RCC_CFGR_PLLXTPRE_HSE 0x00000000U /*!< HSE clock not divided for PLL entry */ -#define RCC_CFGR_PLLXTPRE_HSE_DIV2 0x00020000U /*!< HSE clock divided by 2 for PLL entry */ +#define RCC_CFGR_PLLXTPRE_HSE ((uint32_t)0x00000000) /*!< HSE clock not divided for PLL entry */ +#define RCC_CFGR_PLLXTPRE_HSE_DIV2 ((uint32_t)0x00020000) /*!< HSE clock divided by 2 for PLL entry */ -#define RCC_CFGR_PLLMULL2 0x00000000U /*!< PLL input clock*2 */ +#define RCC_CFGR_PLLMULL2 ((uint32_t)0x00000000) /*!< PLL input clock*2 */ #define RCC_CFGR_PLLMULL3_Pos (18U) #define RCC_CFGR_PLLMULL3_Msk (0x1U << RCC_CFGR_PLLMULL3_Pos) /*!< 0x00040000 */ #define RCC_CFGR_PLLMULL3 RCC_CFGR_PLLMULL3_Msk /*!< PLL input clock*3 */ @@ -1135,11 +1126,11 @@ typedef struct #define RCC_CFGR_MCO_1 (0x2U << RCC_CFGR_MCO_Pos) /*!< 0x02000000 */ #define RCC_CFGR_MCO_2 (0x4U << RCC_CFGR_MCO_Pos) /*!< 0x04000000 */ -#define RCC_CFGR_MCO_NOCLOCK 0x00000000U /*!< No clock */ -#define RCC_CFGR_MCO_SYSCLK 0x04000000U /*!< System clock selected as MCO source */ -#define RCC_CFGR_MCO_HSI 0x05000000U /*!< HSI clock selected as MCO source */ -#define RCC_CFGR_MCO_HSE 0x06000000U /*!< HSE clock selected as MCO source */ -#define RCC_CFGR_MCO_PLLCLK_DIV2 0x07000000U /*!< PLL clock divided by 2 selected as MCO source */ +#define RCC_CFGR_MCO_NOCLOCK ((uint32_t)0x00000000) /*!< No clock */ +#define RCC_CFGR_MCO_SYSCLK ((uint32_t)0x04000000) /*!< System clock selected as MCO source */ +#define RCC_CFGR_MCO_HSI ((uint32_t)0x05000000) /*!< HSI clock selected as MCO source */ +#define RCC_CFGR_MCO_HSE ((uint32_t)0x06000000) /*!< HSE clock selected as MCO source */ +#define RCC_CFGR_MCO_PLLCLK_DIV2 ((uint32_t)0x07000000) /*!< PLL clock divided by 2 selected as MCO source */ /* Reference defines */ #define RCC_CFGR_MCOSEL RCC_CFGR_MCO @@ -1425,10 +1416,10 @@ typedef struct #define RCC_BDCR_RTCSEL_1 (0x2U << RCC_BDCR_RTCSEL_Pos) /*!< 0x00000200 */ /*!< RTC congiguration */ -#define RCC_BDCR_RTCSEL_NOCLOCK 0x00000000U /*!< No clock */ -#define RCC_BDCR_RTCSEL_LSE 0x00000100U /*!< LSE oscillator clock used as RTC clock */ -#define RCC_BDCR_RTCSEL_LSI 0x00000200U /*!< LSI oscillator clock used as RTC clock */ -#define RCC_BDCR_RTCSEL_HSE 0x00000300U /*!< HSE oscillator clock divided by 128 used as RTC clock */ +#define RCC_BDCR_RTCSEL_NOCLOCK ((uint32_t)0x00000000) /*!< No clock */ +#define RCC_BDCR_RTCSEL_LSE ((uint32_t)0x00000100) /*!< LSE oscillator clock used as RTC clock */ +#define RCC_BDCR_RTCSEL_LSI ((uint32_t)0x00000200) /*!< LSI oscillator clock used as RTC clock */ +#define RCC_BDCR_RTCSEL_HSE ((uint32_t)0x00000300) /*!< HSE oscillator clock divided by 128 used as RTC clock */ #define RCC_BDCR_RTCEN_Pos (15U) #define RCC_BDCR_RTCEN_Msk (0x1U << RCC_BDCR_RTCEN_Pos) /*!< 0x00008000 */ @@ -1998,7 +1989,7 @@ typedef struct #define AFIO_EVCR_PIN_3 (0x8U << AFIO_EVCR_PIN_Pos) /*!< 0x00000008 */ /*!< PIN configuration */ -#define AFIO_EVCR_PIN_PX0 0x00000000U /*!< Pin 0 selected */ +#define AFIO_EVCR_PIN_PX0 ((uint32_t)0x00000000) /*!< Pin 0 selected */ #define AFIO_EVCR_PIN_PX1_Pos (0U) #define AFIO_EVCR_PIN_PX1_Msk (0x1U << AFIO_EVCR_PIN_PX1_Pos) /*!< 0x00000001 */ #define AFIO_EVCR_PIN_PX1 AFIO_EVCR_PIN_PX1_Msk /*!< Pin 1 selected */ @@ -2053,7 +2044,7 @@ typedef struct #define AFIO_EVCR_PORT_2 (0x4U << AFIO_EVCR_PORT_Pos) /*!< 0x00000040 */ /*!< PORT configuration */ -#define AFIO_EVCR_PORT_PA 0x00000000 /*!< Port A selected */ +#define AFIO_EVCR_PORT_PA ((uint32_t)0x00000000) /*!< Port A selected */ #define AFIO_EVCR_PORT_PB_Pos (4U) #define AFIO_EVCR_PORT_PB_Msk (0x1U << AFIO_EVCR_PORT_PB_Pos) /*!< 0x00000010 */ #define AFIO_EVCR_PORT_PB AFIO_EVCR_PORT_PB_Msk /*!< Port B selected */ @@ -2092,7 +2083,7 @@ typedef struct #define AFIO_MAPR_USART3_REMAP_1 (0x2U << AFIO_MAPR_USART3_REMAP_Pos) /*!< 0x00000020 */ /* USART3_REMAP configuration */ -#define AFIO_MAPR_USART3_REMAP_NOREMAP 0x00000000U /*!< No remap (TX/PB10, RX/PB11, CK/PB12, CTS/PB13, RTS/PB14) */ +#define AFIO_MAPR_USART3_REMAP_NOREMAP ((uint32_t)0x00000000) /*!< No remap (TX/PB10, RX/PB11, CK/PB12, CTS/PB13, RTS/PB14) */ #define AFIO_MAPR_USART3_REMAP_PARTIALREMAP_Pos (4U) #define AFIO_MAPR_USART3_REMAP_PARTIALREMAP_Msk (0x1U << AFIO_MAPR_USART3_REMAP_PARTIALREMAP_Pos) /*!< 0x00000010 */ #define AFIO_MAPR_USART3_REMAP_PARTIALREMAP AFIO_MAPR_USART3_REMAP_PARTIALREMAP_Msk /*!< Partial remap (TX/PC10, RX/PC11, CK/PC12, CTS/PB13, RTS/PB14) */ @@ -2107,7 +2098,7 @@ typedef struct #define AFIO_MAPR_TIM1_REMAP_1 (0x2U << AFIO_MAPR_TIM1_REMAP_Pos) /*!< 0x00000080 */ /*!< TIM1_REMAP configuration */ -#define AFIO_MAPR_TIM1_REMAP_NOREMAP 0x00000000U /*!< No remap (ETR/PA12, CH1/PA8, CH2/PA9, CH3/PA10, CH4/PA11, BKIN/PB12, CH1N/PB13, CH2N/PB14, CH3N/PB15) */ +#define AFIO_MAPR_TIM1_REMAP_NOREMAP ((uint32_t)0x00000000) /*!< No remap (ETR/PA12, CH1/PA8, CH2/PA9, CH3/PA10, CH4/PA11, BKIN/PB12, CH1N/PB13, CH2N/PB14, CH3N/PB15) */ #define AFIO_MAPR_TIM1_REMAP_PARTIALREMAP_Pos (6U) #define AFIO_MAPR_TIM1_REMAP_PARTIALREMAP_Msk (0x1U << AFIO_MAPR_TIM1_REMAP_PARTIALREMAP_Pos) /*!< 0x00000040 */ #define AFIO_MAPR_TIM1_REMAP_PARTIALREMAP AFIO_MAPR_TIM1_REMAP_PARTIALREMAP_Msk /*!< Partial remap (ETR/PA12, CH1/PA8, CH2/PA9, CH3/PA10, CH4/PA11, BKIN/PA6, CH1N/PA7, CH2N/PB0, CH3N/PB1) */ @@ -2122,7 +2113,7 @@ typedef struct #define AFIO_MAPR_TIM2_REMAP_1 (0x2U << AFIO_MAPR_TIM2_REMAP_Pos) /*!< 0x00000200 */ /*!< TIM2_REMAP configuration */ -#define AFIO_MAPR_TIM2_REMAP_NOREMAP 0x00000000U /*!< No remap (CH1/ETR/PA0, CH2/PA1, CH3/PA2, CH4/PA3) */ +#define AFIO_MAPR_TIM2_REMAP_NOREMAP ((uint32_t)0x00000000) /*!< No remap (CH1/ETR/PA0, CH2/PA1, CH3/PA2, CH4/PA3) */ #define AFIO_MAPR_TIM2_REMAP_PARTIALREMAP1_Pos (8U) #define AFIO_MAPR_TIM2_REMAP_PARTIALREMAP1_Msk (0x1U << AFIO_MAPR_TIM2_REMAP_PARTIALREMAP1_Pos) /*!< 0x00000100 */ #define AFIO_MAPR_TIM2_REMAP_PARTIALREMAP1 AFIO_MAPR_TIM2_REMAP_PARTIALREMAP1_Msk /*!< Partial remap (CH1/ETR/PA15, CH2/PB3, CH3/PA2, CH4/PA3) */ @@ -2140,7 +2131,7 @@ typedef struct #define AFIO_MAPR_TIM3_REMAP_1 (0x2U << AFIO_MAPR_TIM3_REMAP_Pos) /*!< 0x00000800 */ /*!< TIM3_REMAP configuration */ -#define AFIO_MAPR_TIM3_REMAP_NOREMAP 0x00000000U /*!< No remap (CH1/PA6, CH2/PA7, CH3/PB0, CH4/PB1) */ +#define AFIO_MAPR_TIM3_REMAP_NOREMAP ((uint32_t)0x00000000) /*!< No remap (CH1/PA6, CH2/PA7, CH3/PB0, CH4/PB1) */ #define AFIO_MAPR_TIM3_REMAP_PARTIALREMAP_Pos (11U) #define AFIO_MAPR_TIM3_REMAP_PARTIALREMAP_Msk (0x1U << AFIO_MAPR_TIM3_REMAP_PARTIALREMAP_Pos) /*!< 0x00000800 */ #define AFIO_MAPR_TIM3_REMAP_PARTIALREMAP AFIO_MAPR_TIM3_REMAP_PARTIALREMAP_Msk /*!< Partial remap (CH1/PB4, CH2/PB5, CH3/PB0, CH4/PB1) */ @@ -2159,7 +2150,7 @@ typedef struct #define AFIO_MAPR_CAN_REMAP_1 (0x2U << AFIO_MAPR_CAN_REMAP_Pos) /*!< 0x00004000 */ /*!< CAN_REMAP configuration */ -#define AFIO_MAPR_CAN_REMAP_REMAP1 0x00000000U /*!< CANRX mapped to PA11, CANTX mapped to PA12 */ +#define AFIO_MAPR_CAN_REMAP_REMAP1 ((uint32_t)0x00000000) /*!< CANRX mapped to PA11, CANTX mapped to PA12 */ #define AFIO_MAPR_CAN_REMAP_REMAP2_Pos (14U) #define AFIO_MAPR_CAN_REMAP_REMAP2_Msk (0x1U << AFIO_MAPR_CAN_REMAP_REMAP2_Pos) /*!< 0x00004000 */ #define AFIO_MAPR_CAN_REMAP_REMAP2 AFIO_MAPR_CAN_REMAP_REMAP2_Msk /*!< CANRX mapped to PB8, CANTX mapped to PB9 */ @@ -2179,7 +2170,7 @@ typedef struct #define AFIO_MAPR_SWJ_CFG_1 (0x2U << AFIO_MAPR_SWJ_CFG_Pos) /*!< 0x02000000 */ #define AFIO_MAPR_SWJ_CFG_2 (0x4U << AFIO_MAPR_SWJ_CFG_Pos) /*!< 0x04000000 */ -#define AFIO_MAPR_SWJ_CFG_RESET 0x00000000U /*!< Full SWJ (JTAG-DP + SW-DP) : Reset State */ +#define AFIO_MAPR_SWJ_CFG_RESET ((uint32_t)0x00000000) /*!< Full SWJ (JTAG-DP + SW-DP) : Reset State */ #define AFIO_MAPR_SWJ_CFG_NOJNTRST_Pos (24U) #define AFIO_MAPR_SWJ_CFG_NOJNTRST_Msk (0x1U << AFIO_MAPR_SWJ_CFG_NOJNTRST_Pos) /*!< 0x01000000 */ #define AFIO_MAPR_SWJ_CFG_NOJNTRST AFIO_MAPR_SWJ_CFG_NOJNTRST_Msk /*!< Full SWJ (JTAG-DP + SW-DP) but without JNTRST */ @@ -2206,7 +2197,7 @@ typedef struct #define AFIO_EXTICR1_EXTI3 AFIO_EXTICR1_EXTI3_Msk /*!< EXTI 3 configuration */ /*!< EXTI0 configuration */ -#define AFIO_EXTICR1_EXTI0_PA 0x00000000U /*!< PA[0] pin */ +#define AFIO_EXTICR1_EXTI0_PA ((uint32_t)0x00000000) /*!< PA[0] pin */ #define AFIO_EXTICR1_EXTI0_PB_Pos (0U) #define AFIO_EXTICR1_EXTI0_PB_Msk (0x1U << AFIO_EXTICR1_EXTI0_PB_Pos) /*!< 0x00000001 */ #define AFIO_EXTICR1_EXTI0_PB AFIO_EXTICR1_EXTI0_PB_Msk /*!< PB[0] pin */ @@ -2227,7 +2218,7 @@ typedef struct #define AFIO_EXTICR1_EXTI0_PG AFIO_EXTICR1_EXTI0_PG_Msk /*!< PG[0] pin */ /*!< EXTI1 configuration */ -#define AFIO_EXTICR1_EXTI1_PA 0x00000000U /*!< PA[1] pin */ +#define AFIO_EXTICR1_EXTI1_PA ((uint32_t)0x00000000) /*!< PA[1] pin */ #define AFIO_EXTICR1_EXTI1_PB_Pos (4U) #define AFIO_EXTICR1_EXTI1_PB_Msk (0x1U << AFIO_EXTICR1_EXTI1_PB_Pos) /*!< 0x00000010 */ #define AFIO_EXTICR1_EXTI1_PB AFIO_EXTICR1_EXTI1_PB_Msk /*!< PB[1] pin */ @@ -2248,7 +2239,7 @@ typedef struct #define AFIO_EXTICR1_EXTI1_PG AFIO_EXTICR1_EXTI1_PG_Msk /*!< PG[1] pin */ /*!< EXTI2 configuration */ -#define AFIO_EXTICR1_EXTI2_PA 0x00000000U /*!< PA[2] pin */ +#define AFIO_EXTICR1_EXTI2_PA ((uint32_t)0x00000000) /*!< PA[2] pin */ #define AFIO_EXTICR1_EXTI2_PB_Pos (8U) #define AFIO_EXTICR1_EXTI2_PB_Msk (0x1U << AFIO_EXTICR1_EXTI2_PB_Pos) /*!< 0x00000100 */ #define AFIO_EXTICR1_EXTI2_PB AFIO_EXTICR1_EXTI2_PB_Msk /*!< PB[2] pin */ @@ -2269,7 +2260,7 @@ typedef struct #define AFIO_EXTICR1_EXTI2_PG AFIO_EXTICR1_EXTI2_PG_Msk /*!< PG[2] pin */ /*!< EXTI3 configuration */ -#define AFIO_EXTICR1_EXTI3_PA 0x00000000U /*!< PA[3] pin */ +#define AFIO_EXTICR1_EXTI3_PA ((uint32_t)0x00000000) /*!< PA[3] pin */ #define AFIO_EXTICR1_EXTI3_PB_Pos (12U) #define AFIO_EXTICR1_EXTI3_PB_Msk (0x1U << AFIO_EXTICR1_EXTI3_PB_Pos) /*!< 0x00001000 */ #define AFIO_EXTICR1_EXTI3_PB AFIO_EXTICR1_EXTI3_PB_Msk /*!< PB[3] pin */ @@ -2304,7 +2295,7 @@ typedef struct #define AFIO_EXTICR2_EXTI7 AFIO_EXTICR2_EXTI7_Msk /*!< EXTI 7 configuration */ /*!< EXTI4 configuration */ -#define AFIO_EXTICR2_EXTI4_PA 0x00000000U /*!< PA[4] pin */ +#define AFIO_EXTICR2_EXTI4_PA ((uint32_t)0x00000000) /*!< PA[4] pin */ #define AFIO_EXTICR2_EXTI4_PB_Pos (0U) #define AFIO_EXTICR2_EXTI4_PB_Msk (0x1U << AFIO_EXTICR2_EXTI4_PB_Pos) /*!< 0x00000001 */ #define AFIO_EXTICR2_EXTI4_PB AFIO_EXTICR2_EXTI4_PB_Msk /*!< PB[4] pin */ @@ -2325,7 +2316,7 @@ typedef struct #define AFIO_EXTICR2_EXTI4_PG AFIO_EXTICR2_EXTI4_PG_Msk /*!< PG[4] pin */ /* EXTI5 configuration */ -#define AFIO_EXTICR2_EXTI5_PA 0x00000000U /*!< PA[5] pin */ +#define AFIO_EXTICR2_EXTI5_PA ((uint32_t)0x00000000) /*!< PA[5] pin */ #define AFIO_EXTICR2_EXTI5_PB_Pos (4U) #define AFIO_EXTICR2_EXTI5_PB_Msk (0x1U << AFIO_EXTICR2_EXTI5_PB_Pos) /*!< 0x00000010 */ #define AFIO_EXTICR2_EXTI5_PB AFIO_EXTICR2_EXTI5_PB_Msk /*!< PB[5] pin */ @@ -2346,7 +2337,7 @@ typedef struct #define AFIO_EXTICR2_EXTI5_PG AFIO_EXTICR2_EXTI5_PG_Msk /*!< PG[5] pin */ /*!< EXTI6 configuration */ -#define AFIO_EXTICR2_EXTI6_PA 0x00000000U /*!< PA[6] pin */ +#define AFIO_EXTICR2_EXTI6_PA ((uint32_t)0x00000000) /*!< PA[6] pin */ #define AFIO_EXTICR2_EXTI6_PB_Pos (8U) #define AFIO_EXTICR2_EXTI6_PB_Msk (0x1U << AFIO_EXTICR2_EXTI6_PB_Pos) /*!< 0x00000100 */ #define AFIO_EXTICR2_EXTI6_PB AFIO_EXTICR2_EXTI6_PB_Msk /*!< PB[6] pin */ @@ -2367,7 +2358,7 @@ typedef struct #define AFIO_EXTICR2_EXTI6_PG AFIO_EXTICR2_EXTI6_PG_Msk /*!< PG[6] pin */ /*!< EXTI7 configuration */ -#define AFIO_EXTICR2_EXTI7_PA 0x00000000U /*!< PA[7] pin */ +#define AFIO_EXTICR2_EXTI7_PA ((uint32_t)0x00000000) /*!< PA[7] pin */ #define AFIO_EXTICR2_EXTI7_PB_Pos (12U) #define AFIO_EXTICR2_EXTI7_PB_Msk (0x1U << AFIO_EXTICR2_EXTI7_PB_Pos) /*!< 0x00001000 */ #define AFIO_EXTICR2_EXTI7_PB AFIO_EXTICR2_EXTI7_PB_Msk /*!< PB[7] pin */ @@ -2402,7 +2393,7 @@ typedef struct #define AFIO_EXTICR3_EXTI11 AFIO_EXTICR3_EXTI11_Msk /*!< EXTI 11 configuration */ /*!< EXTI8 configuration */ -#define AFIO_EXTICR3_EXTI8_PA 0x00000000U /*!< PA[8] pin */ +#define AFIO_EXTICR3_EXTI8_PA ((uint32_t)0x00000000) /*!< PA[8] pin */ #define AFIO_EXTICR3_EXTI8_PB_Pos (0U) #define AFIO_EXTICR3_EXTI8_PB_Msk (0x1U << AFIO_EXTICR3_EXTI8_PB_Pos) /*!< 0x00000001 */ #define AFIO_EXTICR3_EXTI8_PB AFIO_EXTICR3_EXTI8_PB_Msk /*!< PB[8] pin */ @@ -2423,7 +2414,7 @@ typedef struct #define AFIO_EXTICR3_EXTI8_PG AFIO_EXTICR3_EXTI8_PG_Msk /*!< PG[8] pin */ /*!< EXTI9 configuration */ -#define AFIO_EXTICR3_EXTI9_PA 0x00000000U /*!< PA[9] pin */ +#define AFIO_EXTICR3_EXTI9_PA ((uint32_t)0x00000000) /*!< PA[9] pin */ #define AFIO_EXTICR3_EXTI9_PB_Pos (4U) #define AFIO_EXTICR3_EXTI9_PB_Msk (0x1U << AFIO_EXTICR3_EXTI9_PB_Pos) /*!< 0x00000010 */ #define AFIO_EXTICR3_EXTI9_PB AFIO_EXTICR3_EXTI9_PB_Msk /*!< PB[9] pin */ @@ -2444,7 +2435,7 @@ typedef struct #define AFIO_EXTICR3_EXTI9_PG AFIO_EXTICR3_EXTI9_PG_Msk /*!< PG[9] pin */ /*!< EXTI10 configuration */ -#define AFIO_EXTICR3_EXTI10_PA 0x00000000U /*!< PA[10] pin */ +#define AFIO_EXTICR3_EXTI10_PA ((uint32_t)0x00000000) /*!< PA[10] pin */ #define AFIO_EXTICR3_EXTI10_PB_Pos (8U) #define AFIO_EXTICR3_EXTI10_PB_Msk (0x1U << AFIO_EXTICR3_EXTI10_PB_Pos) /*!< 0x00000100 */ #define AFIO_EXTICR3_EXTI10_PB AFIO_EXTICR3_EXTI10_PB_Msk /*!< PB[10] pin */ @@ -2465,7 +2456,7 @@ typedef struct #define AFIO_EXTICR3_EXTI10_PG AFIO_EXTICR3_EXTI10_PG_Msk /*!< PG[10] pin */ /*!< EXTI11 configuration */ -#define AFIO_EXTICR3_EXTI11_PA 0x00000000U /*!< PA[11] pin */ +#define AFIO_EXTICR3_EXTI11_PA ((uint32_t)0x00000000) /*!< PA[11] pin */ #define AFIO_EXTICR3_EXTI11_PB_Pos (12U) #define AFIO_EXTICR3_EXTI11_PB_Msk (0x1U << AFIO_EXTICR3_EXTI11_PB_Pos) /*!< 0x00001000 */ #define AFIO_EXTICR3_EXTI11_PB AFIO_EXTICR3_EXTI11_PB_Msk /*!< PB[11] pin */ @@ -2500,7 +2491,7 @@ typedef struct #define AFIO_EXTICR4_EXTI15 AFIO_EXTICR4_EXTI15_Msk /*!< EXTI 15 configuration */ /* EXTI12 configuration */ -#define AFIO_EXTICR4_EXTI12_PA 0x00000000U /*!< PA[12] pin */ +#define AFIO_EXTICR4_EXTI12_PA ((uint32_t)0x00000000) /*!< PA[12] pin */ #define AFIO_EXTICR4_EXTI12_PB_Pos (0U) #define AFIO_EXTICR4_EXTI12_PB_Msk (0x1U << AFIO_EXTICR4_EXTI12_PB_Pos) /*!< 0x00000001 */ #define AFIO_EXTICR4_EXTI12_PB AFIO_EXTICR4_EXTI12_PB_Msk /*!< PB[12] pin */ @@ -2521,7 +2512,7 @@ typedef struct #define AFIO_EXTICR4_EXTI12_PG AFIO_EXTICR4_EXTI12_PG_Msk /*!< PG[12] pin */ /* EXTI13 configuration */ -#define AFIO_EXTICR4_EXTI13_PA 0x00000000U /*!< PA[13] pin */ +#define AFIO_EXTICR4_EXTI13_PA ((uint32_t)0x00000000) /*!< PA[13] pin */ #define AFIO_EXTICR4_EXTI13_PB_Pos (4U) #define AFIO_EXTICR4_EXTI13_PB_Msk (0x1U << AFIO_EXTICR4_EXTI13_PB_Pos) /*!< 0x00000010 */ #define AFIO_EXTICR4_EXTI13_PB AFIO_EXTICR4_EXTI13_PB_Msk /*!< PB[13] pin */ @@ -2542,7 +2533,7 @@ typedef struct #define AFIO_EXTICR4_EXTI13_PG AFIO_EXTICR4_EXTI13_PG_Msk /*!< PG[13] pin */ /*!< EXTI14 configuration */ -#define AFIO_EXTICR4_EXTI14_PA 0x00000000U /*!< PA[14] pin */ +#define AFIO_EXTICR4_EXTI14_PA ((uint32_t)0x00000000) /*!< PA[14] pin */ #define AFIO_EXTICR4_EXTI14_PB_Pos (8U) #define AFIO_EXTICR4_EXTI14_PB_Msk (0x1U << AFIO_EXTICR4_EXTI14_PB_Pos) /*!< 0x00000100 */ #define AFIO_EXTICR4_EXTI14_PB AFIO_EXTICR4_EXTI14_PB_Msk /*!< PB[14] pin */ @@ -2563,7 +2554,7 @@ typedef struct #define AFIO_EXTICR4_EXTI14_PG AFIO_EXTICR4_EXTI14_PG_Msk /*!< PG[14] pin */ /*!< EXTI15 configuration */ -#define AFIO_EXTICR4_EXTI15_PA 0x00000000U /*!< PA[15] pin */ +#define AFIO_EXTICR4_EXTI15_PA ((uint32_t)0x00000000) /*!< PA[15] pin */ #define AFIO_EXTICR4_EXTI15_PB_Pos (12U) #define AFIO_EXTICR4_EXTI15_PB_Msk (0x1U << AFIO_EXTICR4_EXTI15_PB_Pos) /*!< 0x00001000 */ #define AFIO_EXTICR4_EXTI15_PB AFIO_EXTICR4_EXTI15_PB_Msk /*!< PB[15] pin */ @@ -2587,6 +2578,440 @@ typedef struct +/******************************************************************************/ +/* */ +/* SystemTick */ +/* */ +/******************************************************************************/ + +/***************** Bit definition for SysTick_CTRL register *****************/ +#define SysTick_CTRL_ENABLE ((uint32_t)0x00000001) /*!< Counter enable */ +#define SysTick_CTRL_TICKINT ((uint32_t)0x00000002) /*!< Counting down to 0 pends the SysTick handler */ +#define SysTick_CTRL_CLKSOURCE ((uint32_t)0x00000004) /*!< Clock source */ +#define SysTick_CTRL_COUNTFLAG ((uint32_t)0x00010000) /*!< Count Flag */ + +/***************** Bit definition for SysTick_LOAD register *****************/ +#define SysTick_LOAD_RELOAD ((uint32_t)0x00FFFFFF) /*!< Value to load into the SysTick Current Value Register when the counter reaches 0 */ + +/***************** Bit definition for SysTick_VAL register ******************/ +#define SysTick_VAL_CURRENT ((uint32_t)0x00FFFFFF) /*!< Current value at the time the register is accessed */ + +/***************** Bit definition for SysTick_CALIB register ****************/ +#define SysTick_CALIB_TENMS ((uint32_t)0x00FFFFFF) /*!< Reload value to use for 10ms timing */ +#define SysTick_CALIB_SKEW ((uint32_t)0x40000000) /*!< Calibration value is not exactly 10 ms */ +#define SysTick_CALIB_NOREF ((uint32_t)0x80000000) /*!< The reference clock is not provided */ + +/******************************************************************************/ +/* */ +/* Nested Vectored Interrupt Controller */ +/* */ +/******************************************************************************/ + +/****************** Bit definition for NVIC_ISER register *******************/ +#define NVIC_ISER_SETENA_Pos (0U) +#define NVIC_ISER_SETENA_Msk (0xFFFFFFFFU << NVIC_ISER_SETENA_Pos) /*!< 0xFFFFFFFF */ +#define NVIC_ISER_SETENA NVIC_ISER_SETENA_Msk /*!< Interrupt set enable bits */ +#define NVIC_ISER_SETENA_0 (0x00000001U << NVIC_ISER_SETENA_Pos) /*!< 0x00000001 */ +#define NVIC_ISER_SETENA_1 (0x00000002U << NVIC_ISER_SETENA_Pos) /*!< 0x00000002 */ +#define NVIC_ISER_SETENA_2 (0x00000004U << NVIC_ISER_SETENA_Pos) /*!< 0x00000004 */ +#define NVIC_ISER_SETENA_3 (0x00000008U << NVIC_ISER_SETENA_Pos) /*!< 0x00000008 */ +#define NVIC_ISER_SETENA_4 (0x00000010U << NVIC_ISER_SETENA_Pos) /*!< 0x00000010 */ +#define NVIC_ISER_SETENA_5 (0x00000020U << NVIC_ISER_SETENA_Pos) /*!< 0x00000020 */ +#define NVIC_ISER_SETENA_6 (0x00000040U << NVIC_ISER_SETENA_Pos) /*!< 0x00000040 */ +#define NVIC_ISER_SETENA_7 (0x00000080U << NVIC_ISER_SETENA_Pos) /*!< 0x00000080 */ +#define NVIC_ISER_SETENA_8 (0x00000100U << NVIC_ISER_SETENA_Pos) /*!< 0x00000100 */ +#define NVIC_ISER_SETENA_9 (0x00000200U << NVIC_ISER_SETENA_Pos) /*!< 0x00000200 */ +#define NVIC_ISER_SETENA_10 (0x00000400U << NVIC_ISER_SETENA_Pos) /*!< 0x00000400 */ +#define NVIC_ISER_SETENA_11 (0x00000800U << NVIC_ISER_SETENA_Pos) /*!< 0x00000800 */ +#define NVIC_ISER_SETENA_12 (0x00001000U << NVIC_ISER_SETENA_Pos) /*!< 0x00001000 */ +#define NVIC_ISER_SETENA_13 (0x00002000U << NVIC_ISER_SETENA_Pos) /*!< 0x00002000 */ +#define NVIC_ISER_SETENA_14 (0x00004000U << NVIC_ISER_SETENA_Pos) /*!< 0x00004000 */ +#define NVIC_ISER_SETENA_15 (0x00008000U << NVIC_ISER_SETENA_Pos) /*!< 0x00008000 */ +#define NVIC_ISER_SETENA_16 (0x00010000U << NVIC_ISER_SETENA_Pos) /*!< 0x00010000 */ +#define NVIC_ISER_SETENA_17 (0x00020000U << NVIC_ISER_SETENA_Pos) /*!< 0x00020000 */ +#define NVIC_ISER_SETENA_18 (0x00040000U << NVIC_ISER_SETENA_Pos) /*!< 0x00040000 */ +#define NVIC_ISER_SETENA_19 (0x00080000U << NVIC_ISER_SETENA_Pos) /*!< 0x00080000 */ +#define NVIC_ISER_SETENA_20 (0x00100000U << NVIC_ISER_SETENA_Pos) /*!< 0x00100000 */ +#define NVIC_ISER_SETENA_21 (0x00200000U << NVIC_ISER_SETENA_Pos) /*!< 0x00200000 */ +#define NVIC_ISER_SETENA_22 (0x00400000U << NVIC_ISER_SETENA_Pos) /*!< 0x00400000 */ +#define NVIC_ISER_SETENA_23 (0x00800000U << NVIC_ISER_SETENA_Pos) /*!< 0x00800000 */ +#define NVIC_ISER_SETENA_24 (0x01000000U << NVIC_ISER_SETENA_Pos) /*!< 0x01000000 */ +#define NVIC_ISER_SETENA_25 (0x02000000U << NVIC_ISER_SETENA_Pos) /*!< 0x02000000 */ +#define NVIC_ISER_SETENA_26 (0x04000000U << NVIC_ISER_SETENA_Pos) /*!< 0x04000000 */ +#define NVIC_ISER_SETENA_27 (0x08000000U << NVIC_ISER_SETENA_Pos) /*!< 0x08000000 */ +#define NVIC_ISER_SETENA_28 (0x10000000U << NVIC_ISER_SETENA_Pos) /*!< 0x10000000 */ +#define NVIC_ISER_SETENA_29 (0x20000000U << NVIC_ISER_SETENA_Pos) /*!< 0x20000000 */ +#define NVIC_ISER_SETENA_30 (0x40000000U << NVIC_ISER_SETENA_Pos) /*!< 0x40000000 */ +#define NVIC_ISER_SETENA_31 (0x80000000U << NVIC_ISER_SETENA_Pos) /*!< 0x80000000 */ + +/****************** Bit definition for NVIC_ICER register *******************/ +#define NVIC_ICER_CLRENA_Pos (0U) +#define NVIC_ICER_CLRENA_Msk (0xFFFFFFFFU << NVIC_ICER_CLRENA_Pos) /*!< 0xFFFFFFFF */ +#define NVIC_ICER_CLRENA NVIC_ICER_CLRENA_Msk /*!< Interrupt clear-enable bits */ +#define NVIC_ICER_CLRENA_0 (0x00000001U << NVIC_ICER_CLRENA_Pos) /*!< 0x00000001 */ +#define NVIC_ICER_CLRENA_1 (0x00000002U << NVIC_ICER_CLRENA_Pos) /*!< 0x00000002 */ +#define NVIC_ICER_CLRENA_2 (0x00000004U << NVIC_ICER_CLRENA_Pos) /*!< 0x00000004 */ +#define NVIC_ICER_CLRENA_3 (0x00000008U << NVIC_ICER_CLRENA_Pos) /*!< 0x00000008 */ +#define NVIC_ICER_CLRENA_4 (0x00000010U << NVIC_ICER_CLRENA_Pos) /*!< 0x00000010 */ +#define NVIC_ICER_CLRENA_5 (0x00000020U << NVIC_ICER_CLRENA_Pos) /*!< 0x00000020 */ +#define NVIC_ICER_CLRENA_6 (0x00000040U << NVIC_ICER_CLRENA_Pos) /*!< 0x00000040 */ +#define NVIC_ICER_CLRENA_7 (0x00000080U << NVIC_ICER_CLRENA_Pos) /*!< 0x00000080 */ +#define NVIC_ICER_CLRENA_8 (0x00000100U << NVIC_ICER_CLRENA_Pos) /*!< 0x00000100 */ +#define NVIC_ICER_CLRENA_9 (0x00000200U << NVIC_ICER_CLRENA_Pos) /*!< 0x00000200 */ +#define NVIC_ICER_CLRENA_10 (0x00000400U << NVIC_ICER_CLRENA_Pos) /*!< 0x00000400 */ +#define NVIC_ICER_CLRENA_11 (0x00000800U << NVIC_ICER_CLRENA_Pos) /*!< 0x00000800 */ +#define NVIC_ICER_CLRENA_12 (0x00001000U << NVIC_ICER_CLRENA_Pos) /*!< 0x00001000 */ +#define NVIC_ICER_CLRENA_13 (0x00002000U << NVIC_ICER_CLRENA_Pos) /*!< 0x00002000 */ +#define NVIC_ICER_CLRENA_14 (0x00004000U << NVIC_ICER_CLRENA_Pos) /*!< 0x00004000 */ +#define NVIC_ICER_CLRENA_15 (0x00008000U << NVIC_ICER_CLRENA_Pos) /*!< 0x00008000 */ +#define NVIC_ICER_CLRENA_16 (0x00010000U << NVIC_ICER_CLRENA_Pos) /*!< 0x00010000 */ +#define NVIC_ICER_CLRENA_17 (0x00020000U << NVIC_ICER_CLRENA_Pos) /*!< 0x00020000 */ +#define NVIC_ICER_CLRENA_18 (0x00040000U << NVIC_ICER_CLRENA_Pos) /*!< 0x00040000 */ +#define NVIC_ICER_CLRENA_19 (0x00080000U << NVIC_ICER_CLRENA_Pos) /*!< 0x00080000 */ +#define NVIC_ICER_CLRENA_20 (0x00100000U << NVIC_ICER_CLRENA_Pos) /*!< 0x00100000 */ +#define NVIC_ICER_CLRENA_21 (0x00200000U << NVIC_ICER_CLRENA_Pos) /*!< 0x00200000 */ +#define NVIC_ICER_CLRENA_22 (0x00400000U << NVIC_ICER_CLRENA_Pos) /*!< 0x00400000 */ +#define NVIC_ICER_CLRENA_23 (0x00800000U << NVIC_ICER_CLRENA_Pos) /*!< 0x00800000 */ +#define NVIC_ICER_CLRENA_24 (0x01000000U << NVIC_ICER_CLRENA_Pos) /*!< 0x01000000 */ +#define NVIC_ICER_CLRENA_25 (0x02000000U << NVIC_ICER_CLRENA_Pos) /*!< 0x02000000 */ +#define NVIC_ICER_CLRENA_26 (0x04000000U << NVIC_ICER_CLRENA_Pos) /*!< 0x04000000 */ +#define NVIC_ICER_CLRENA_27 (0x08000000U << NVIC_ICER_CLRENA_Pos) /*!< 0x08000000 */ +#define NVIC_ICER_CLRENA_28 (0x10000000U << NVIC_ICER_CLRENA_Pos) /*!< 0x10000000 */ +#define NVIC_ICER_CLRENA_29 (0x20000000U << NVIC_ICER_CLRENA_Pos) /*!< 0x20000000 */ +#define NVIC_ICER_CLRENA_30 (0x40000000U << NVIC_ICER_CLRENA_Pos) /*!< 0x40000000 */ +#define NVIC_ICER_CLRENA_31 (0x80000000U << NVIC_ICER_CLRENA_Pos) /*!< 0x80000000 */ + +/****************** Bit definition for NVIC_ISPR register *******************/ +#define NVIC_ISPR_SETPEND_Pos (0U) +#define NVIC_ISPR_SETPEND_Msk (0xFFFFFFFFU << NVIC_ISPR_SETPEND_Pos) /*!< 0xFFFFFFFF */ +#define NVIC_ISPR_SETPEND NVIC_ISPR_SETPEND_Msk /*!< Interrupt set-pending bits */ +#define NVIC_ISPR_SETPEND_0 (0x00000001U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00000001 */ +#define NVIC_ISPR_SETPEND_1 (0x00000002U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00000002 */ +#define NVIC_ISPR_SETPEND_2 (0x00000004U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00000004 */ +#define NVIC_ISPR_SETPEND_3 (0x00000008U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00000008 */ +#define NVIC_ISPR_SETPEND_4 (0x00000010U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00000010 */ +#define NVIC_ISPR_SETPEND_5 (0x00000020U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00000020 */ +#define NVIC_ISPR_SETPEND_6 (0x00000040U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00000040 */ +#define NVIC_ISPR_SETPEND_7 (0x00000080U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00000080 */ +#define NVIC_ISPR_SETPEND_8 (0x00000100U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00000100 */ +#define NVIC_ISPR_SETPEND_9 (0x00000200U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00000200 */ +#define NVIC_ISPR_SETPEND_10 (0x00000400U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00000400 */ +#define NVIC_ISPR_SETPEND_11 (0x00000800U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00000800 */ +#define NVIC_ISPR_SETPEND_12 (0x00001000U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00001000 */ +#define NVIC_ISPR_SETPEND_13 (0x00002000U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00002000 */ +#define NVIC_ISPR_SETPEND_14 (0x00004000U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00004000 */ +#define NVIC_ISPR_SETPEND_15 (0x00008000U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00008000 */ +#define NVIC_ISPR_SETPEND_16 (0x00010000U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00010000 */ +#define NVIC_ISPR_SETPEND_17 (0x00020000U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00020000 */ +#define NVIC_ISPR_SETPEND_18 (0x00040000U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00040000 */ +#define NVIC_ISPR_SETPEND_19 (0x00080000U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00080000 */ +#define NVIC_ISPR_SETPEND_20 (0x00100000U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00100000 */ +#define NVIC_ISPR_SETPEND_21 (0x00200000U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00200000 */ +#define NVIC_ISPR_SETPEND_22 (0x00400000U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00400000 */ +#define NVIC_ISPR_SETPEND_23 (0x00800000U << NVIC_ISPR_SETPEND_Pos) /*!< 0x00800000 */ +#define NVIC_ISPR_SETPEND_24 (0x01000000U << NVIC_ISPR_SETPEND_Pos) /*!< 0x01000000 */ +#define NVIC_ISPR_SETPEND_25 (0x02000000U << NVIC_ISPR_SETPEND_Pos) /*!< 0x02000000 */ +#define NVIC_ISPR_SETPEND_26 (0x04000000U << NVIC_ISPR_SETPEND_Pos) /*!< 0x04000000 */ +#define NVIC_ISPR_SETPEND_27 (0x08000000U << NVIC_ISPR_SETPEND_Pos) /*!< 0x08000000 */ +#define NVIC_ISPR_SETPEND_28 (0x10000000U << NVIC_ISPR_SETPEND_Pos) /*!< 0x10000000 */ +#define NVIC_ISPR_SETPEND_29 (0x20000000U << NVIC_ISPR_SETPEND_Pos) /*!< 0x20000000 */ +#define NVIC_ISPR_SETPEND_30 (0x40000000U << NVIC_ISPR_SETPEND_Pos) /*!< 0x40000000 */ +#define NVIC_ISPR_SETPEND_31 (0x80000000U << NVIC_ISPR_SETPEND_Pos) /*!< 0x80000000 */ + +/****************** Bit definition for NVIC_ICPR register *******************/ +#define NVIC_ICPR_CLRPEND_Pos (0U) +#define NVIC_ICPR_CLRPEND_Msk (0xFFFFFFFFU << NVIC_ICPR_CLRPEND_Pos) /*!< 0xFFFFFFFF */ +#define NVIC_ICPR_CLRPEND NVIC_ICPR_CLRPEND_Msk /*!< Interrupt clear-pending bits */ +#define NVIC_ICPR_CLRPEND_0 (0x00000001U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00000001 */ +#define NVIC_ICPR_CLRPEND_1 (0x00000002U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00000002 */ +#define NVIC_ICPR_CLRPEND_2 (0x00000004U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00000004 */ +#define NVIC_ICPR_CLRPEND_3 (0x00000008U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00000008 */ +#define NVIC_ICPR_CLRPEND_4 (0x00000010U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00000010 */ +#define NVIC_ICPR_CLRPEND_5 (0x00000020U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00000020 */ +#define NVIC_ICPR_CLRPEND_6 (0x00000040U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00000040 */ +#define NVIC_ICPR_CLRPEND_7 (0x00000080U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00000080 */ +#define NVIC_ICPR_CLRPEND_8 (0x00000100U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00000100 */ +#define NVIC_ICPR_CLRPEND_9 (0x00000200U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00000200 */ +#define NVIC_ICPR_CLRPEND_10 (0x00000400U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00000400 */ +#define NVIC_ICPR_CLRPEND_11 (0x00000800U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00000800 */ +#define NVIC_ICPR_CLRPEND_12 (0x00001000U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00001000 */ +#define NVIC_ICPR_CLRPEND_13 (0x00002000U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00002000 */ +#define NVIC_ICPR_CLRPEND_14 (0x00004000U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00004000 */ +#define NVIC_ICPR_CLRPEND_15 (0x00008000U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00008000 */ +#define NVIC_ICPR_CLRPEND_16 (0x00010000U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00010000 */ +#define NVIC_ICPR_CLRPEND_17 (0x00020000U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00020000 */ +#define NVIC_ICPR_CLRPEND_18 (0x00040000U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00040000 */ +#define NVIC_ICPR_CLRPEND_19 (0x00080000U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00080000 */ +#define NVIC_ICPR_CLRPEND_20 (0x00100000U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00100000 */ +#define NVIC_ICPR_CLRPEND_21 (0x00200000U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00200000 */ +#define NVIC_ICPR_CLRPEND_22 (0x00400000U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00400000 */ +#define NVIC_ICPR_CLRPEND_23 (0x00800000U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x00800000 */ +#define NVIC_ICPR_CLRPEND_24 (0x01000000U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x01000000 */ +#define NVIC_ICPR_CLRPEND_25 (0x02000000U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x02000000 */ +#define NVIC_ICPR_CLRPEND_26 (0x04000000U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x04000000 */ +#define NVIC_ICPR_CLRPEND_27 (0x08000000U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x08000000 */ +#define NVIC_ICPR_CLRPEND_28 (0x10000000U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x10000000 */ +#define NVIC_ICPR_CLRPEND_29 (0x20000000U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x20000000 */ +#define NVIC_ICPR_CLRPEND_30 (0x40000000U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x40000000 */ +#define NVIC_ICPR_CLRPEND_31 (0x80000000U << NVIC_ICPR_CLRPEND_Pos) /*!< 0x80000000 */ + +/****************** Bit definition for NVIC_IABR register *******************/ +#define NVIC_IABR_ACTIVE_Pos (0U) +#define NVIC_IABR_ACTIVE_Msk (0xFFFFFFFFU << NVIC_IABR_ACTIVE_Pos) /*!< 0xFFFFFFFF */ +#define NVIC_IABR_ACTIVE NVIC_IABR_ACTIVE_Msk /*!< Interrupt active flags */ +#define NVIC_IABR_ACTIVE_0 (0x00000001U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00000001 */ +#define NVIC_IABR_ACTIVE_1 (0x00000002U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00000002 */ +#define NVIC_IABR_ACTIVE_2 (0x00000004U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00000004 */ +#define NVIC_IABR_ACTIVE_3 (0x00000008U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00000008 */ +#define NVIC_IABR_ACTIVE_4 (0x00000010U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00000010 */ +#define NVIC_IABR_ACTIVE_5 (0x00000020U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00000020 */ +#define NVIC_IABR_ACTIVE_6 (0x00000040U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00000040 */ +#define NVIC_IABR_ACTIVE_7 (0x00000080U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00000080 */ +#define NVIC_IABR_ACTIVE_8 (0x00000100U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00000100 */ +#define NVIC_IABR_ACTIVE_9 (0x00000200U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00000200 */ +#define NVIC_IABR_ACTIVE_10 (0x00000400U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00000400 */ +#define NVIC_IABR_ACTIVE_11 (0x00000800U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00000800 */ +#define NVIC_IABR_ACTIVE_12 (0x00001000U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00001000 */ +#define NVIC_IABR_ACTIVE_13 (0x00002000U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00002000 */ +#define NVIC_IABR_ACTIVE_14 (0x00004000U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00004000 */ +#define NVIC_IABR_ACTIVE_15 (0x00008000U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00008000 */ +#define NVIC_IABR_ACTIVE_16 (0x00010000U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00010000 */ +#define NVIC_IABR_ACTIVE_17 (0x00020000U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00020000 */ +#define NVIC_IABR_ACTIVE_18 (0x00040000U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00040000 */ +#define NVIC_IABR_ACTIVE_19 (0x00080000U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00080000 */ +#define NVIC_IABR_ACTIVE_20 (0x00100000U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00100000 */ +#define NVIC_IABR_ACTIVE_21 (0x00200000U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00200000 */ +#define NVIC_IABR_ACTIVE_22 (0x00400000U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00400000 */ +#define NVIC_IABR_ACTIVE_23 (0x00800000U << NVIC_IABR_ACTIVE_Pos) /*!< 0x00800000 */ +#define NVIC_IABR_ACTIVE_24 (0x01000000U << NVIC_IABR_ACTIVE_Pos) /*!< 0x01000000 */ +#define NVIC_IABR_ACTIVE_25 (0x02000000U << NVIC_IABR_ACTIVE_Pos) /*!< 0x02000000 */ +#define NVIC_IABR_ACTIVE_26 (0x04000000U << NVIC_IABR_ACTIVE_Pos) /*!< 0x04000000 */ +#define NVIC_IABR_ACTIVE_27 (0x08000000U << NVIC_IABR_ACTIVE_Pos) /*!< 0x08000000 */ +#define NVIC_IABR_ACTIVE_28 (0x10000000U << NVIC_IABR_ACTIVE_Pos) /*!< 0x10000000 */ +#define NVIC_IABR_ACTIVE_29 (0x20000000U << NVIC_IABR_ACTIVE_Pos) /*!< 0x20000000 */ +#define NVIC_IABR_ACTIVE_30 (0x40000000U << NVIC_IABR_ACTIVE_Pos) /*!< 0x40000000 */ +#define NVIC_IABR_ACTIVE_31 (0x80000000U << NVIC_IABR_ACTIVE_Pos) /*!< 0x80000000 */ + +/****************** Bit definition for NVIC_PRI0 register *******************/ +#define NVIC_IPR0_PRI_0 ((uint32_t)0x000000FF) /*!< Priority of interrupt 0 */ +#define NVIC_IPR0_PRI_1 ((uint32_t)0x0000FF00) /*!< Priority of interrupt 1 */ +#define NVIC_IPR0_PRI_2 ((uint32_t)0x00FF0000) /*!< Priority of interrupt 2 */ +#define NVIC_IPR0_PRI_3 ((uint32_t)0xFF000000) /*!< Priority of interrupt 3 */ + +/****************** Bit definition for NVIC_PRI1 register *******************/ +#define NVIC_IPR1_PRI_4 ((uint32_t)0x000000FF) /*!< Priority of interrupt 4 */ +#define NVIC_IPR1_PRI_5 ((uint32_t)0x0000FF00) /*!< Priority of interrupt 5 */ +#define NVIC_IPR1_PRI_6 ((uint32_t)0x00FF0000) /*!< Priority of interrupt 6 */ +#define NVIC_IPR1_PRI_7 ((uint32_t)0xFF000000) /*!< Priority of interrupt 7 */ + +/****************** Bit definition for NVIC_PRI2 register *******************/ +#define NVIC_IPR2_PRI_8 ((uint32_t)0x000000FF) /*!< Priority of interrupt 8 */ +#define NVIC_IPR2_PRI_9 ((uint32_t)0x0000FF00) /*!< Priority of interrupt 9 */ +#define NVIC_IPR2_PRI_10 ((uint32_t)0x00FF0000) /*!< Priority of interrupt 10 */ +#define NVIC_IPR2_PRI_11 ((uint32_t)0xFF000000) /*!< Priority of interrupt 11 */ + +/****************** Bit definition for NVIC_PRI3 register *******************/ +#define NVIC_IPR3_PRI_12 ((uint32_t)0x000000FF) /*!< Priority of interrupt 12 */ +#define NVIC_IPR3_PRI_13 ((uint32_t)0x0000FF00) /*!< Priority of interrupt 13 */ +#define NVIC_IPR3_PRI_14 ((uint32_t)0x00FF0000) /*!< Priority of interrupt 14 */ +#define NVIC_IPR3_PRI_15 ((uint32_t)0xFF000000) /*!< Priority of interrupt 15 */ + +/****************** Bit definition for NVIC_PRI4 register *******************/ +#define NVIC_IPR4_PRI_16 ((uint32_t)0x000000FF) /*!< Priority of interrupt 16 */ +#define NVIC_IPR4_PRI_17 ((uint32_t)0x0000FF00) /*!< Priority of interrupt 17 */ +#define NVIC_IPR4_PRI_18 ((uint32_t)0x00FF0000) /*!< Priority of interrupt 18 */ +#define NVIC_IPR4_PRI_19 ((uint32_t)0xFF000000) /*!< Priority of interrupt 19 */ + +/****************** Bit definition for NVIC_PRI5 register *******************/ +#define NVIC_IPR5_PRI_20 ((uint32_t)0x000000FF) /*!< Priority of interrupt 20 */ +#define NVIC_IPR5_PRI_21 ((uint32_t)0x0000FF00) /*!< Priority of interrupt 21 */ +#define NVIC_IPR5_PRI_22 ((uint32_t)0x00FF0000) /*!< Priority of interrupt 22 */ +#define NVIC_IPR5_PRI_23 ((uint32_t)0xFF000000) /*!< Priority of interrupt 23 */ + +/****************** Bit definition for NVIC_PRI6 register *******************/ +#define NVIC_IPR6_PRI_24 ((uint32_t)0x000000FF) /*!< Priority of interrupt 24 */ +#define NVIC_IPR6_PRI_25 ((uint32_t)0x0000FF00) /*!< Priority of interrupt 25 */ +#define NVIC_IPR6_PRI_26 ((uint32_t)0x00FF0000) /*!< Priority of interrupt 26 */ +#define NVIC_IPR6_PRI_27 ((uint32_t)0xFF000000) /*!< Priority of interrupt 27 */ + +/****************** Bit definition for NVIC_PRI7 register *******************/ +#define NVIC_IPR7_PRI_28 ((uint32_t)0x000000FF) /*!< Priority of interrupt 28 */ +#define NVIC_IPR7_PRI_29 ((uint32_t)0x0000FF00) /*!< Priority of interrupt 29 */ +#define NVIC_IPR7_PRI_30 ((uint32_t)0x00FF0000) /*!< Priority of interrupt 30 */ +#define NVIC_IPR7_PRI_31 ((uint32_t)0xFF000000) /*!< Priority of interrupt 31 */ + +/****************** Bit definition for SCB_CPUID register *******************/ +#define SCB_CPUID_REVISION ((uint32_t)0x0000000F) /*!< Implementation defined revision number */ +#define SCB_CPUID_PARTNO ((uint32_t)0x0000FFF0) /*!< Number of processor within family */ +#define SCB_CPUID_Constant ((uint32_t)0x000F0000) /*!< Reads as 0x0F */ +#define SCB_CPUID_VARIANT ((uint32_t)0x00F00000) /*!< Implementation defined variant number */ +#define SCB_CPUID_IMPLEMENTER ((uint32_t)0xFF000000) /*!< Implementer code. ARM is 0x41 */ + +/******************* Bit definition for SCB_ICSR register *******************/ +#define SCB_ICSR_VECTACTIVE ((uint32_t)0x000001FF) /*!< Active ISR number field */ +#define SCB_ICSR_RETTOBASE ((uint32_t)0x00000800) /*!< All active exceptions minus the IPSR_current_exception yields the empty set */ +#define SCB_ICSR_VECTPENDING ((uint32_t)0x003FF000) /*!< Pending ISR number field */ +#define SCB_ICSR_ISRPENDING ((uint32_t)0x00400000) /*!< Interrupt pending flag */ +#define SCB_ICSR_ISRPREEMPT ((uint32_t)0x00800000) /*!< It indicates that a pending interrupt becomes active in the next running cycle */ +#define SCB_ICSR_PENDSTCLR ((uint32_t)0x02000000) /*!< Clear pending SysTick bit */ +#define SCB_ICSR_PENDSTSET ((uint32_t)0x04000000) /*!< Set pending SysTick bit */ +#define SCB_ICSR_PENDSVCLR ((uint32_t)0x08000000) /*!< Clear pending pendSV bit */ +#define SCB_ICSR_PENDSVSET ((uint32_t)0x10000000) /*!< Set pending pendSV bit */ +#define SCB_ICSR_NMIPENDSET ((uint32_t)0x80000000) /*!< Set pending NMI bit */ + +/******************* Bit definition for SCB_VTOR register *******************/ +#define SCB_VTOR_TBLOFF ((uint32_t)0x1FFFFF80) /*!< Vector table base offset field */ +#define SCB_VTOR_TBLBASE ((uint32_t)0x20000000) /*!< Table base in code(0) or RAM(1) */ + +/*!<***************** Bit definition for SCB_AIRCR register *******************/ +#define SCB_AIRCR_VECTRESET ((uint32_t)0x00000001) /*!< System Reset bit */ +#define SCB_AIRCR_VECTCLRACTIVE ((uint32_t)0x00000002) /*!< Clear active vector bit */ +#define SCB_AIRCR_SYSRESETREQ ((uint32_t)0x00000004) /*!< Requests chip control logic to generate a reset */ + +#define SCB_AIRCR_PRIGROUP ((uint32_t)0x00000700) /*!< PRIGROUP[2:0] bits (Priority group) */ +#define SCB_AIRCR_PRIGROUP_0 ((uint32_t)0x00000100) /*!< Bit 0 */ +#define SCB_AIRCR_PRIGROUP_1 ((uint32_t)0x00000200) /*!< Bit 1 */ +#define SCB_AIRCR_PRIGROUP_2 ((uint32_t)0x00000400) /*!< Bit 2 */ + +/* prority group configuration */ +#define SCB_AIRCR_PRIGROUP0 ((uint32_t)0x00000000) /*!< Priority group=0 (7 bits of pre-emption priority, 1 bit of subpriority) */ +#define SCB_AIRCR_PRIGROUP1 ((uint32_t)0x00000100) /*!< Priority group=1 (6 bits of pre-emption priority, 2 bits of subpriority) */ +#define SCB_AIRCR_PRIGROUP2 ((uint32_t)0x00000200) /*!< Priority group=2 (5 bits of pre-emption priority, 3 bits of subpriority) */ +#define SCB_AIRCR_PRIGROUP3 ((uint32_t)0x00000300) /*!< Priority group=3 (4 bits of pre-emption priority, 4 bits of subpriority) */ +#define SCB_AIRCR_PRIGROUP4 ((uint32_t)0x00000400) /*!< Priority group=4 (3 bits of pre-emption priority, 5 bits of subpriority) */ +#define SCB_AIRCR_PRIGROUP5 ((uint32_t)0x00000500) /*!< Priority group=5 (2 bits of pre-emption priority, 6 bits of subpriority) */ +#define SCB_AIRCR_PRIGROUP6 ((uint32_t)0x00000600) /*!< Priority group=6 (1 bit of pre-emption priority, 7 bits of subpriority) */ +#define SCB_AIRCR_PRIGROUP7 ((uint32_t)0x00000700) /*!< Priority group=7 (no pre-emption priority, 8 bits of subpriority) */ + +#define SCB_AIRCR_ENDIANESS ((uint32_t)0x00008000) /*!< Data endianness bit */ +#define SCB_AIRCR_VECTKEY ((uint32_t)0xFFFF0000) /*!< Register key (VECTKEY) - Reads as 0xFA05 (VECTKEYSTAT) */ + +/******************* Bit definition for SCB_SCR register ********************/ +#define SCB_SCR_SLEEPONEXIT ((uint32_t)0x00000002) /*!< Sleep on exit bit */ +#define SCB_SCR_SLEEPDEEP ((uint32_t)0x00000004) /*!< Sleep deep bit */ +#define SCB_SCR_SEVONPEND ((uint32_t)0x00000010) /*!< Wake up from WFE */ + +/******************** Bit definition for SCB_CCR register *******************/ +#define SCB_CCR_NONBASETHRDENA ((uint32_t)0x00000001) /*!< Thread mode can be entered from any level in Handler mode by controlled return value */ +#define SCB_CCR_USERSETMPEND ((uint32_t)0x00000002) /*!< Enables user code to write the Software Trigger Interrupt register to trigger (pend) a Main exception */ +#define SCB_CCR_UNALIGN_TRP ((uint32_t)0x00000008) /*!< Trap for unaligned access */ +#define SCB_CCR_DIV_0_TRP ((uint32_t)0x00000010) /*!< Trap on Divide by 0 */ +#define SCB_CCR_BFHFNMIGN ((uint32_t)0x00000100) /*!< Handlers running at priority -1 and -2 */ +#define SCB_CCR_STKALIGN ((uint32_t)0x00000200) /*!< On exception entry, the SP used prior to the exception is adjusted to be 8-byte aligned */ + +/******************* Bit definition for SCB_SHPR register ********************/ +#define SCB_SHPR_PRI_N_Pos (0U) +#define SCB_SHPR_PRI_N_Msk (0xFFU << SCB_SHPR_PRI_N_Pos) /*!< 0x000000FF */ +#define SCB_SHPR_PRI_N SCB_SHPR_PRI_N_Msk /*!< Priority of system handler 4,8, and 12. Mem Manage, reserved and Debug Monitor */ +#define SCB_SHPR_PRI_N1_Pos (8U) +#define SCB_SHPR_PRI_N1_Msk (0xFFU << SCB_SHPR_PRI_N1_Pos) /*!< 0x0000FF00 */ +#define SCB_SHPR_PRI_N1 SCB_SHPR_PRI_N1_Msk /*!< Priority of system handler 5,9, and 13. Bus Fault, reserved and reserved */ +#define SCB_SHPR_PRI_N2_Pos (16U) +#define SCB_SHPR_PRI_N2_Msk (0xFFU << SCB_SHPR_PRI_N2_Pos) /*!< 0x00FF0000 */ +#define SCB_SHPR_PRI_N2 SCB_SHPR_PRI_N2_Msk /*!< Priority of system handler 6,10, and 14. Usage Fault, reserved and PendSV */ +#define SCB_SHPR_PRI_N3_Pos (24U) +#define SCB_SHPR_PRI_N3_Msk (0xFFU << SCB_SHPR_PRI_N3_Pos) /*!< 0xFF000000 */ +#define SCB_SHPR_PRI_N3 SCB_SHPR_PRI_N3_Msk /*!< Priority of system handler 7,11, and 15. Reserved, SVCall and SysTick */ + +/****************** Bit definition for SCB_SHCSR register *******************/ +#define SCB_SHCSR_MEMFAULTACT ((uint32_t)0x00000001) /*!< MemManage is active */ +#define SCB_SHCSR_BUSFAULTACT ((uint32_t)0x00000002) /*!< BusFault is active */ +#define SCB_SHCSR_USGFAULTACT ((uint32_t)0x00000008) /*!< UsageFault is active */ +#define SCB_SHCSR_SVCALLACT ((uint32_t)0x00000080) /*!< SVCall is active */ +#define SCB_SHCSR_MONITORACT ((uint32_t)0x00000100) /*!< Monitor is active */ +#define SCB_SHCSR_PENDSVACT ((uint32_t)0x00000400) /*!< PendSV is active */ +#define SCB_SHCSR_SYSTICKACT ((uint32_t)0x00000800) /*!< SysTick is active */ +#define SCB_SHCSR_USGFAULTPENDED ((uint32_t)0x00001000) /*!< Usage Fault is pended */ +#define SCB_SHCSR_MEMFAULTPENDED ((uint32_t)0x00002000) /*!< MemManage is pended */ +#define SCB_SHCSR_BUSFAULTPENDED ((uint32_t)0x00004000) /*!< Bus Fault is pended */ +#define SCB_SHCSR_SVCALLPENDED ((uint32_t)0x00008000) /*!< SVCall is pended */ +#define SCB_SHCSR_MEMFAULTENA ((uint32_t)0x00010000) /*!< MemManage enable */ +#define SCB_SHCSR_BUSFAULTENA ((uint32_t)0x00020000) /*!< Bus Fault enable */ +#define SCB_SHCSR_USGFAULTENA ((uint32_t)0x00040000) /*!< UsageFault enable */ + +/******************* Bit definition for SCB_CFSR register *******************/ +/*!< MFSR */ +#define SCB_CFSR_IACCVIOL_Pos (0U) +#define SCB_CFSR_IACCVIOL_Msk (0x1U << SCB_CFSR_IACCVIOL_Pos) /*!< 0x00000001 */ +#define SCB_CFSR_IACCVIOL SCB_CFSR_IACCVIOL_Msk /*!< Instruction access violation */ +#define SCB_CFSR_DACCVIOL_Pos (1U) +#define SCB_CFSR_DACCVIOL_Msk (0x1U << SCB_CFSR_DACCVIOL_Pos) /*!< 0x00000002 */ +#define SCB_CFSR_DACCVIOL SCB_CFSR_DACCVIOL_Msk /*!< Data access violation */ +#define SCB_CFSR_MUNSTKERR_Pos (3U) +#define SCB_CFSR_MUNSTKERR_Msk (0x1U << SCB_CFSR_MUNSTKERR_Pos) /*!< 0x00000008 */ +#define SCB_CFSR_MUNSTKERR SCB_CFSR_MUNSTKERR_Msk /*!< Unstacking error */ +#define SCB_CFSR_MSTKERR_Pos (4U) +#define SCB_CFSR_MSTKERR_Msk (0x1U << SCB_CFSR_MSTKERR_Pos) /*!< 0x00000010 */ +#define SCB_CFSR_MSTKERR SCB_CFSR_MSTKERR_Msk /*!< Stacking error */ +#define SCB_CFSR_MMARVALID_Pos (7U) +#define SCB_CFSR_MMARVALID_Msk (0x1U << SCB_CFSR_MMARVALID_Pos) /*!< 0x00000080 */ +#define SCB_CFSR_MMARVALID SCB_CFSR_MMARVALID_Msk /*!< Memory Manage Address Register address valid flag */ +/*!< BFSR */ +#define SCB_CFSR_IBUSERR_Pos (8U) +#define SCB_CFSR_IBUSERR_Msk (0x1U << SCB_CFSR_IBUSERR_Pos) /*!< 0x00000100 */ +#define SCB_CFSR_IBUSERR SCB_CFSR_IBUSERR_Msk /*!< Instruction bus error flag */ +#define SCB_CFSR_PRECISERR_Pos (9U) +#define SCB_CFSR_PRECISERR_Msk (0x1U << SCB_CFSR_PRECISERR_Pos) /*!< 0x00000200 */ +#define SCB_CFSR_PRECISERR SCB_CFSR_PRECISERR_Msk /*!< Precise data bus error */ +#define SCB_CFSR_IMPRECISERR_Pos (10U) +#define SCB_CFSR_IMPRECISERR_Msk (0x1U << SCB_CFSR_IMPRECISERR_Pos) /*!< 0x00000400 */ +#define SCB_CFSR_IMPRECISERR SCB_CFSR_IMPRECISERR_Msk /*!< Imprecise data bus error */ +#define SCB_CFSR_UNSTKERR_Pos (11U) +#define SCB_CFSR_UNSTKERR_Msk (0x1U << SCB_CFSR_UNSTKERR_Pos) /*!< 0x00000800 */ +#define SCB_CFSR_UNSTKERR SCB_CFSR_UNSTKERR_Msk /*!< Unstacking error */ +#define SCB_CFSR_STKERR_Pos (12U) +#define SCB_CFSR_STKERR_Msk (0x1U << SCB_CFSR_STKERR_Pos) /*!< 0x00001000 */ +#define SCB_CFSR_STKERR SCB_CFSR_STKERR_Msk /*!< Stacking error */ +#define SCB_CFSR_BFARVALID_Pos (15U) +#define SCB_CFSR_BFARVALID_Msk (0x1U << SCB_CFSR_BFARVALID_Pos) /*!< 0x00008000 */ +#define SCB_CFSR_BFARVALID SCB_CFSR_BFARVALID_Msk /*!< Bus Fault Address Register address valid flag */ +/*!< UFSR */ +#define SCB_CFSR_UNDEFINSTR_Pos (16U) +#define SCB_CFSR_UNDEFINSTR_Msk (0x1U << SCB_CFSR_UNDEFINSTR_Pos) /*!< 0x00010000 */ +#define SCB_CFSR_UNDEFINSTR SCB_CFSR_UNDEFINSTR_Msk /*!< The processor attempt to execute an undefined instruction */ +#define SCB_CFSR_INVSTATE_Pos (17U) +#define SCB_CFSR_INVSTATE_Msk (0x1U << SCB_CFSR_INVSTATE_Pos) /*!< 0x00020000 */ +#define SCB_CFSR_INVSTATE SCB_CFSR_INVSTATE_Msk /*!< Invalid combination of EPSR and instruction */ +#define SCB_CFSR_INVPC_Pos (18U) +#define SCB_CFSR_INVPC_Msk (0x1U << SCB_CFSR_INVPC_Pos) /*!< 0x00040000 */ +#define SCB_CFSR_INVPC SCB_CFSR_INVPC_Msk /*!< Attempt to load EXC_RETURN into pc illegally */ +#define SCB_CFSR_NOCP_Pos (19U) +#define SCB_CFSR_NOCP_Msk (0x1U << SCB_CFSR_NOCP_Pos) /*!< 0x00080000 */ +#define SCB_CFSR_NOCP SCB_CFSR_NOCP_Msk /*!< Attempt to use a coprocessor instruction */ +#define SCB_CFSR_UNALIGNED_Pos (24U) +#define SCB_CFSR_UNALIGNED_Msk (0x1U << SCB_CFSR_UNALIGNED_Pos) /*!< 0x01000000 */ +#define SCB_CFSR_UNALIGNED SCB_CFSR_UNALIGNED_Msk /*!< Fault occurs when there is an attempt to make an unaligned memory access */ +#define SCB_CFSR_DIVBYZERO_Pos (25U) +#define SCB_CFSR_DIVBYZERO_Msk (0x1U << SCB_CFSR_DIVBYZERO_Pos) /*!< 0x02000000 */ +#define SCB_CFSR_DIVBYZERO SCB_CFSR_DIVBYZERO_Msk /*!< Fault occurs when SDIV or DIV instruction is used with a divisor of 0 */ + +/******************* Bit definition for SCB_HFSR register *******************/ +#define SCB_HFSR_VECTTBL ((uint32_t)0x00000002) /*!< Fault occurs because of vector table read on exception processing */ +#define SCB_HFSR_FORCED ((uint32_t)0x40000000) /*!< Hard Fault activated when a configurable Fault was received and cannot activate */ +#define SCB_HFSR_DEBUGEVT ((uint32_t)0x80000000) /*!< Fault related to debug */ + +/******************* Bit definition for SCB_DFSR register *******************/ +#define SCB_DFSR_HALTED ((uint32_t)0x00000001) /*!< Halt request flag */ +#define SCB_DFSR_BKPT ((uint32_t)0x00000002) /*!< BKPT flag */ +#define SCB_DFSR_DWTTRAP ((uint32_t)0x00000004) /*!< Data Watchpoint and Trace (DWT) flag */ +#define SCB_DFSR_VCATCH ((uint32_t)0x00000008) /*!< Vector catch flag */ +#define SCB_DFSR_EXTERNAL ((uint32_t)0x00000010) /*!< External debug request flag */ + +/******************* Bit definition for SCB_MMFAR register ******************/ +#define SCB_MMFAR_ADDRESS_Pos (0U) +#define SCB_MMFAR_ADDRESS_Msk (0xFFFFFFFFU << SCB_MMFAR_ADDRESS_Pos) /*!< 0xFFFFFFFF */ +#define SCB_MMFAR_ADDRESS SCB_MMFAR_ADDRESS_Msk /*!< Mem Manage fault address field */ + +/******************* Bit definition for SCB_BFAR register *******************/ +#define SCB_BFAR_ADDRESS_Pos (0U) +#define SCB_BFAR_ADDRESS_Msk (0xFFFFFFFFU << SCB_BFAR_ADDRESS_Pos) /*!< 0xFFFFFFFF */ +#define SCB_BFAR_ADDRESS SCB_BFAR_ADDRESS_Msk /*!< Bus fault address field */ + +/******************* Bit definition for SCB_afsr register *******************/ +#define SCB_AFSR_IMPDEF_Pos (0U) +#define SCB_AFSR_IMPDEF_Msk (0xFFFFFFFFU << SCB_AFSR_IMPDEF_Pos) /*!< 0xFFFFFFFF */ +#define SCB_AFSR_IMPDEF SCB_AFSR_IMPDEF_Msk /*!< Implementation defined */ + /******************************************************************************/ /* */ /* External Interrupt/Event Controller */ @@ -2651,6 +3076,9 @@ typedef struct #define EXTI_IMR_MR18_Pos (18U) #define EXTI_IMR_MR18_Msk (0x1U << EXTI_IMR_MR18_Pos) /*!< 0x00040000 */ #define EXTI_IMR_MR18 EXTI_IMR_MR18_Msk /*!< Interrupt Mask on line 18 */ +#define EXTI_IMR_MR19_Pos (19U) +#define EXTI_IMR_MR19_Msk (0x1U << EXTI_IMR_MR19_Pos) /*!< 0x00080000 */ +#define EXTI_IMR_MR19 EXTI_IMR_MR19_Msk /*!< Interrupt Mask on line 19 */ /* References Defines */ #define EXTI_IMR_IM0 EXTI_IMR_MR0 @@ -2672,8 +3100,8 @@ typedef struct #define EXTI_IMR_IM16 EXTI_IMR_MR16 #define EXTI_IMR_IM17 EXTI_IMR_MR17 #define EXTI_IMR_IM18 EXTI_IMR_MR18 -#define EXTI_IMR_IM 0x0007FFFFU /*!< Interrupt Mask All */ - +#define EXTI_IMR_IM19 EXTI_IMR_MR19 + /******************* Bit definition for EXTI_EMR register *******************/ #define EXTI_EMR_MR0_Pos (0U) #define EXTI_EMR_MR0_Msk (0x1U << EXTI_EMR_MR0_Pos) /*!< 0x00000001 */ @@ -2732,6 +3160,9 @@ typedef struct #define EXTI_EMR_MR18_Pos (18U) #define EXTI_EMR_MR18_Msk (0x1U << EXTI_EMR_MR18_Pos) /*!< 0x00040000 */ #define EXTI_EMR_MR18 EXTI_EMR_MR18_Msk /*!< Event Mask on line 18 */ +#define EXTI_EMR_MR19_Pos (19U) +#define EXTI_EMR_MR19_Msk (0x1U << EXTI_EMR_MR19_Pos) /*!< 0x00080000 */ +#define EXTI_EMR_MR19 EXTI_EMR_MR19_Msk /*!< Event Mask on line 19 */ /* References Defines */ #define EXTI_EMR_EM0 EXTI_EMR_MR0 @@ -2753,6 +3184,7 @@ typedef struct #define EXTI_EMR_EM16 EXTI_EMR_MR16 #define EXTI_EMR_EM17 EXTI_EMR_MR17 #define EXTI_EMR_EM18 EXTI_EMR_MR18 +#define EXTI_EMR_EM19 EXTI_EMR_MR19 /****************** Bit definition for EXTI_RTSR register *******************/ #define EXTI_RTSR_TR0_Pos (0U) @@ -2812,6 +3244,9 @@ typedef struct #define EXTI_RTSR_TR18_Pos (18U) #define EXTI_RTSR_TR18_Msk (0x1U << EXTI_RTSR_TR18_Pos) /*!< 0x00040000 */ #define EXTI_RTSR_TR18 EXTI_RTSR_TR18_Msk /*!< Rising trigger event configuration bit of line 18 */ +#define EXTI_RTSR_TR19_Pos (19U) +#define EXTI_RTSR_TR19_Msk (0x1U << EXTI_RTSR_TR19_Pos) /*!< 0x00080000 */ +#define EXTI_RTSR_TR19 EXTI_RTSR_TR19_Msk /*!< Rising trigger event configuration bit of line 19 */ /* References Defines */ #define EXTI_RTSR_RT0 EXTI_RTSR_TR0 @@ -2833,6 +3268,7 @@ typedef struct #define EXTI_RTSR_RT16 EXTI_RTSR_TR16 #define EXTI_RTSR_RT17 EXTI_RTSR_TR17 #define EXTI_RTSR_RT18 EXTI_RTSR_TR18 +#define EXTI_RTSR_RT19 EXTI_RTSR_TR19 /****************** Bit definition for EXTI_FTSR register *******************/ #define EXTI_FTSR_TR0_Pos (0U) @@ -2892,6 +3328,9 @@ typedef struct #define EXTI_FTSR_TR18_Pos (18U) #define EXTI_FTSR_TR18_Msk (0x1U << EXTI_FTSR_TR18_Pos) /*!< 0x00040000 */ #define EXTI_FTSR_TR18 EXTI_FTSR_TR18_Msk /*!< Falling trigger event configuration bit of line 18 */ +#define EXTI_FTSR_TR19_Pos (19U) +#define EXTI_FTSR_TR19_Msk (0x1U << EXTI_FTSR_TR19_Pos) /*!< 0x00080000 */ +#define EXTI_FTSR_TR19 EXTI_FTSR_TR19_Msk /*!< Falling trigger event configuration bit of line 19 */ /* References Defines */ #define EXTI_FTSR_FT0 EXTI_FTSR_TR0 @@ -2913,6 +3352,7 @@ typedef struct #define EXTI_FTSR_FT16 EXTI_FTSR_TR16 #define EXTI_FTSR_FT17 EXTI_FTSR_TR17 #define EXTI_FTSR_FT18 EXTI_FTSR_TR18 +#define EXTI_FTSR_FT19 EXTI_FTSR_TR19 /****************** Bit definition for EXTI_SWIER register ******************/ #define EXTI_SWIER_SWIER0_Pos (0U) @@ -2972,6 +3412,9 @@ typedef struct #define EXTI_SWIER_SWIER18_Pos (18U) #define EXTI_SWIER_SWIER18_Msk (0x1U << EXTI_SWIER_SWIER18_Pos) /*!< 0x00040000 */ #define EXTI_SWIER_SWIER18 EXTI_SWIER_SWIER18_Msk /*!< Software Interrupt on line 18 */ +#define EXTI_SWIER_SWIER19_Pos (19U) +#define EXTI_SWIER_SWIER19_Msk (0x1U << EXTI_SWIER_SWIER19_Pos) /*!< 0x00080000 */ +#define EXTI_SWIER_SWIER19 EXTI_SWIER_SWIER19_Msk /*!< Software Interrupt on line 19 */ /* References Defines */ #define EXTI_SWIER_SWI0 EXTI_SWIER_SWIER0 @@ -2993,6 +3436,7 @@ typedef struct #define EXTI_SWIER_SWI16 EXTI_SWIER_SWIER16 #define EXTI_SWIER_SWI17 EXTI_SWIER_SWIER17 #define EXTI_SWIER_SWI18 EXTI_SWIER_SWIER18 +#define EXTI_SWIER_SWI19 EXTI_SWIER_SWIER19 /******************* Bit definition for EXTI_PR register ********************/ #define EXTI_PR_PR0_Pos (0U) @@ -3052,6 +3496,9 @@ typedef struct #define EXTI_PR_PR18_Pos (18U) #define EXTI_PR_PR18_Msk (0x1U << EXTI_PR_PR18_Pos) /*!< 0x00040000 */ #define EXTI_PR_PR18 EXTI_PR_PR18_Msk /*!< Pending bit for line 18 */ +#define EXTI_PR_PR19_Pos (19U) +#define EXTI_PR_PR19_Msk (0x1U << EXTI_PR_PR19_Pos) /*!< 0x00080000 */ +#define EXTI_PR_PR19 EXTI_PR_PR19_Msk /*!< Pending bit for line 19 */ /* References Defines */ #define EXTI_PR_PIF0 EXTI_PR_PR0 @@ -3073,6 +3520,7 @@ typedef struct #define EXTI_PR_PIF16 EXTI_PR_PR16 #define EXTI_PR_PIF17 EXTI_PR_PR17 #define EXTI_PR_PIF18 EXTI_PR_PR18 +#define EXTI_PR_PIF19 EXTI_PR_PR19 /******************************************************************************/ /* */ @@ -3933,6 +4381,10 @@ typedef struct #define TIM_SMCR_SMS_1 (0x2U << TIM_SMCR_SMS_Pos) /*!< 0x00000002 */ #define TIM_SMCR_SMS_2 (0x4U << TIM_SMCR_SMS_Pos) /*!< 0x00000004 */ +#define TIM_SMCR_OCCS_Pos (3U) +#define TIM_SMCR_OCCS_Msk (0x1U << TIM_SMCR_OCCS_Pos) /*!< 0x00000008 */ +#define TIM_SMCR_OCCS TIM_SMCR_OCCS_Msk /*!< OCREF clear selection */ + #define TIM_SMCR_TS_Pos (4U) #define TIM_SMCR_TS_Msk (0x7U << TIM_SMCR_TS_Pos) /*!< 0x00000070 */ #define TIM_SMCR_TS TIM_SMCR_TS_Msk /*!
© COPYRIGHT(c) 2017 STMicroelectronics
+ *

© COPYRIGHT(c) 2016 STMicroelectronics

* * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: @@ -108,10 +108,10 @@ #endif /* USE_HAL_DRIVER */ /** - * @brief CMSIS Device version number V4.2.0 + * @brief CMSIS Device version number V4.0.0 */ -#define __STM32F1_CMSIS_VERSION_MAIN (0x04) /*!< [31:24] main version */ -#define __STM32F1_CMSIS_VERSION_SUB1 (0x02) /*!< [23:16] sub1 version */ +#define __STM32F1_CMSIS_VERSION_MAIN (0x04) /*!< [31:24] main version */ +#define __STM32F1_CMSIS_VERSION_SUB1 (0x01) /*!< [23:16] sub1 version */ #define __STM32F1_CMSIS_VERSION_SUB2 (0x00) /*!< [15:8] sub2 version */ #define __STM32F1_CMSIS_VERSION_RC (0x00) /*!< [7:0] release candidate */ #define __STM32F1_CMSIS_VERSION ((__STM32F1_CMSIS_VERSION_MAIN << 24)\ diff --git a/targets/TARGET_STM/TARGET_STM32F1/TARGET_NUCLEO_F103RB/device/system_stm32f1xx.c b/targets/TARGET_STM/TARGET_STM32F1/TARGET_NUCLEO_F103RB/device/system_stm32f1xx.c index 717c3cddfbd..4e27fcd17cd 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/TARGET_NUCLEO_F103RB/device/system_stm32f1xx.c +++ b/targets/TARGET_STM/TARGET_STM32F1/TARGET_NUCLEO_F103RB/device/system_stm32f1xx.c @@ -2,8 +2,8 @@ ****************************************************************************** * @file system_stm32f1xx.c * @author MCD Application Team - * @version V4.2.0 - * @date 31-March-2017 + * @version V4.1.0 + * @date 29-April-2016 * @brief CMSIS Cortex-M3 Device Peripheral Access Layer System Source File. * * 1. This file provides two functions and one global variable to be called from @@ -52,7 +52,7 @@ ****************************************************************************** * @attention * - *

© COPYRIGHT(c) 2017 STMicroelectronics

+ *

© COPYRIGHT(c) 2016 STMicroelectronics

* * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: @@ -111,12 +111,12 @@ */ #if !defined (HSE_VALUE) - #define HSE_VALUE 8000000U /*!< Default value of the External oscillator in Hz. + #define HSE_VALUE ((uint32_t)8000000) /*!< Default value of the External oscillator in Hz. This value can be provided and adapted by the user application. */ #endif /* HSE_VALUE */ #if !defined (HSI_VALUE) - #define HSI_VALUE 8000000U /*!< Default value of the Internal oscillator in Hz. + #define HSI_VALUE ((uint32_t)8000000) /*!< Default value of the Internal oscillator in Hz. This value can be provided and adapted by the user application. */ #endif /* HSI_VALUE */ @@ -128,7 +128,7 @@ /*!< Uncomment the following line if you need to relocate your vector Table in Internal SRAM. */ /* #define VECT_TAB_SRAM */ -#define VECT_TAB_OFFSET 0x00000000U /*!< Vector Table base offset field. +#define VECT_TAB_OFFSET 0x0 /*!< Vector Table base offset field. This value must be a multiple of 0x200. */ @@ -156,13 +156,13 @@ * Clock Definitions *******************************************************************************/ #if defined(STM32F100xB) ||defined(STM32F100xE) - uint32_t SystemCoreClock = 24000000U; /*!< System Clock Frequency (Core Clock) */ + uint32_t SystemCoreClock = 24000000; /*!< System Clock Frequency (Core Clock) */ #else /*!< HSI Selected as System Clock source */ - uint32_t SystemCoreClock = 72000000U; /*!< System Clock Frequency (Core Clock) */ + uint32_t SystemCoreClock = 72000000; /*!< System Clock Frequency (Core Clock) */ #endif -const uint8_t AHBPrescTable[16U] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 7, 8, 9}; -const uint8_t APBPrescTable[8U] = {0, 0, 0, 0, 1, 2, 3, 4}; +const uint8_t AHBPrescTable[16] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 7, 8, 9}; +const uint8_t APBPrescTable[8] = {0, 0, 0, 0, 1, 2, 3, 4}; /** * @} @@ -204,42 +204,42 @@ void SystemInit (void) { /* Reset the RCC clock configuration to the default reset state(for debug purpose) */ /* Set HSION bit */ - RCC->CR |= 0x00000001U; + RCC->CR |= (uint32_t)0x00000001; /* Reset SW, HPRE, PPRE1, PPRE2, ADCPRE and MCO bits */ #if !defined(STM32F105xC) && !defined(STM32F107xC) - RCC->CFGR &= 0xF8FF0000U; + RCC->CFGR &= (uint32_t)0xF8FF0000; #else - RCC->CFGR &= 0xF0FF0000U; + RCC->CFGR &= (uint32_t)0xF0FF0000; #endif /* STM32F105xC */ /* Reset HSEON, CSSON and PLLON bits */ - RCC->CR &= 0xFEF6FFFFU; + RCC->CR &= (uint32_t)0xFEF6FFFF; /* Reset HSEBYP bit */ - RCC->CR &= 0xFFFBFFFFU; + RCC->CR &= (uint32_t)0xFFFBFFFF; /* Reset PLLSRC, PLLXTPRE, PLLMUL and USBPRE/OTGFSPRE bits */ - RCC->CFGR &= 0xFF80FFFFU; + RCC->CFGR &= (uint32_t)0xFF80FFFF; #if defined(STM32F105xC) || defined(STM32F107xC) /* Reset PLL2ON and PLL3ON bits */ - RCC->CR &= 0xEBFFFFFFU; + RCC->CR &= (uint32_t)0xEBFFFFFF; /* Disable all interrupts and clear pending bits */ - RCC->CIR = 0x00FF0000U; + RCC->CIR = 0x00FF0000; /* Reset CFGR2 register */ - RCC->CFGR2 = 0x00000000U; + RCC->CFGR2 = 0x00000000; #elif defined(STM32F100xB) || defined(STM32F100xE) /* Disable all interrupts and clear pending bits */ - RCC->CIR = 0x009F0000U; + RCC->CIR = 0x009F0000; /* Reset CFGR2 register */ - RCC->CFGR2 = 0x00000000U; + RCC->CFGR2 = 0x00000000; #else /* Disable all interrupts and clear pending bits */ - RCC->CIR = 0x009F0000U; + RCC->CIR = 0x009F0000; #endif /* STM32F105xC */ #if defined(STM32F100xE) || defined(STM32F101xE) || defined(STM32F101xG) || defined(STM32F103xE) || defined(STM32F103xG) @@ -304,14 +304,14 @@ void SystemInit (void) */ void SystemCoreClockUpdate (void) { - uint32_t tmp = 0U, pllmull = 0U, pllsource = 0U; + uint32_t tmp = 0, pllmull = 0, pllsource = 0; #if defined(STM32F105xC) || defined(STM32F107xC) - uint32_t prediv1source = 0U, prediv1factor = 0U, prediv2factor = 0U, pll2mull = 0U; + uint32_t prediv1source = 0, prediv1factor = 0, prediv2factor = 0, pll2mull = 0; #endif /* STM32F105xC */ #if defined(STM32F100xB) || defined(STM32F100xE) - uint32_t prediv1factor = 0U; + uint32_t prediv1factor = 0; #endif /* STM32F100xB or STM32F100xE */ /* Get SYSCLK source -------------------------------------------------------*/ @@ -319,37 +319,37 @@ void SystemCoreClockUpdate (void) switch (tmp) { - case 0x00U: /* HSI used as system clock */ + case 0x00: /* HSI used as system clock */ SystemCoreClock = HSI_VALUE; break; - case 0x04U: /* HSE used as system clock */ + case 0x04: /* HSE used as system clock */ SystemCoreClock = HSE_VALUE; break; - case 0x08U: /* PLL used as system clock */ + case 0x08: /* PLL used as system clock */ /* Get PLL clock source and multiplication factor ----------------------*/ pllmull = RCC->CFGR & RCC_CFGR_PLLMULL; pllsource = RCC->CFGR & RCC_CFGR_PLLSRC; #if !defined(STM32F105xC) && !defined(STM32F107xC) - pllmull = ( pllmull >> 18U) + 2U; + pllmull = ( pllmull >> 18) + 2; - if (pllsource == 0x00U) + if (pllsource == 0x00) { /* HSI oscillator clock divided by 2 selected as PLL clock entry */ - SystemCoreClock = (HSI_VALUE >> 1U) * pllmull; + SystemCoreClock = (HSI_VALUE >> 1) * pllmull; } else { #if defined(STM32F100xB) || defined(STM32F100xE) - prediv1factor = (RCC->CFGR2 & RCC_CFGR2_PREDIV1) + 1U; + prediv1factor = (RCC->CFGR2 & RCC_CFGR2_PREDIV1) + 1; /* HSE oscillator clock selected as PREDIV1 clock entry */ SystemCoreClock = (HSE_VALUE / prediv1factor) * pllmull; #else /* HSE selected as PLL clock entry */ if ((RCC->CFGR & RCC_CFGR_PLLXTPRE) != (uint32_t)RESET) {/* HSE oscillator clock divided by 2 */ - SystemCoreClock = (HSE_VALUE >> 1U) * pllmull; + SystemCoreClock = (HSE_VALUE >> 1) * pllmull; } else { @@ -358,30 +358,30 @@ void SystemCoreClockUpdate (void) #endif } #else - pllmull = pllmull >> 18U; + pllmull = pllmull >> 18; - if (pllmull != 0x0DU) + if (pllmull != 0x0D) { - pllmull += 2U; + pllmull += 2; } else { /* PLL multiplication factor = PLL input clock * 6.5 */ - pllmull = 13U / 2U; + pllmull = 13 / 2; } - if (pllsource == 0x00U) + if (pllsource == 0x00) { /* HSI oscillator clock divided by 2 selected as PLL clock entry */ - SystemCoreClock = (HSI_VALUE >> 1U) * pllmull; + SystemCoreClock = (HSI_VALUE >> 1) * pllmull; } else {/* PREDIV1 selected as PLL clock entry */ /* Get PREDIV1 clock source and division factor */ prediv1source = RCC->CFGR2 & RCC_CFGR2_PREDIV1SRC; - prediv1factor = (RCC->CFGR2 & RCC_CFGR2_PREDIV1) + 1U; + prediv1factor = (RCC->CFGR2 & RCC_CFGR2_PREDIV1) + 1; - if (prediv1source == 0U) + if (prediv1source == 0) { /* HSE oscillator clock selected as PREDIV1 clock entry */ SystemCoreClock = (HSE_VALUE / prediv1factor) * pllmull; @@ -390,8 +390,8 @@ void SystemCoreClockUpdate (void) {/* PLL2 clock selected as PREDIV1 clock entry */ /* Get PREDIV2 division factor and PLL2 multiplication factor */ - prediv2factor = ((RCC->CFGR2 & RCC_CFGR2_PREDIV2) >> 4U) + 1U; - pll2mull = ((RCC->CFGR2 & RCC_CFGR2_PLL2MUL) >> 8U) + 2U; + prediv2factor = ((RCC->CFGR2 & RCC_CFGR2_PREDIV2) >> 4) + 1; + pll2mull = ((RCC->CFGR2 & RCC_CFGR2_PLL2MUL) >> 8 ) + 2; SystemCoreClock = (((HSE_VALUE / prediv2factor) * pll2mull) / prediv1factor) * pllmull; } } @@ -405,7 +405,7 @@ void SystemCoreClockUpdate (void) /* Compute HCLK clock frequency ----------------*/ /* Get HCLK prescaler */ - tmp = AHBPrescTable[((RCC->CFGR & RCC_CFGR_HPRE) >> 4U)]; + tmp = AHBPrescTable[((RCC->CFGR & RCC_CFGR_HPRE) >> 4)]; /* HCLK clock frequency */ SystemCoreClock >>= tmp; } @@ -434,13 +434,13 @@ void SystemInit_ExtMemCtl(void) required, then adjust the Register Addresses */ /* Enable FSMC clock */ - RCC->AHBENR = 0x00000114U; + RCC->AHBENR = 0x00000114; /* Delay after an RCC peripheral clock enabling */ tmpreg = READ_BIT(RCC->AHBENR, RCC_AHBENR_FSMCEN); /* Enable GPIOD, GPIOE, GPIOF and GPIOG clocks */ - RCC->APB2ENR = 0x000001E0U; + RCC->APB2ENR = 0x000001E0; /* Delay after an RCC peripheral clock enabling */ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_IOPDEN); @@ -453,23 +453,23 @@ void SystemInit_ExtMemCtl(void) /*---------------- NE3 configuration ----------------------------------------*/ /*---------------- NBL0, NBL1 configuration ---------------------------------*/ - GPIOD->CRL = 0x44BB44BBU; - GPIOD->CRH = 0xBBBBBBBBU; + GPIOD->CRL = 0x44BB44BB; + GPIOD->CRH = 0xBBBBBBBB; - GPIOE->CRL = 0xB44444BBU; - GPIOE->CRH = 0xBBBBBBBBU; + GPIOE->CRL = 0xB44444BB; + GPIOE->CRH = 0xBBBBBBBB; - GPIOF->CRL = 0x44BBBBBBU; - GPIOF->CRH = 0xBBBB4444U; + GPIOF->CRL = 0x44BBBBBB; + GPIOF->CRH = 0xBBBB4444; - GPIOG->CRL = 0x44BBBBBBU; - GPIOG->CRH = 0x444B4B44U; + GPIOG->CRL = 0x44BBBBBB; + GPIOG->CRH = 0x444B4B44; /*---------------- FSMC Configuration ---------------------------------------*/ /*---------------- Enable FSMC Bank1_SRAM Bank ------------------------------*/ - FSMC_Bank1->BTCR[4U] = 0x00001091U; - FSMC_Bank1->BTCR[5U] = 0x00110212U; + FSMC_Bank1->BTCR[4] = 0x00001091; + FSMC_Bank1->BTCR[5] = 0x00110212; } #endif /* DATA_IN_ExtSRAM */ #endif /* STM32F100xE || STM32F101xE || STM32F101xG || STM32F103xE || STM32F103xG */ diff --git a/targets/TARGET_STM/TARGET_STM32F1/TARGET_NUCLEO_F103RB/device/system_stm32f1xx.h b/targets/TARGET_STM/TARGET_STM32F1/TARGET_NUCLEO_F103RB/device/system_stm32f1xx.h index f2557fa9579..8efeb9aadbc 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/TARGET_NUCLEO_F103RB/device/system_stm32f1xx.h +++ b/targets/TARGET_STM/TARGET_STM32F1/TARGET_NUCLEO_F103RB/device/system_stm32f1xx.h @@ -2,13 +2,13 @@ ****************************************************************************** * @file system_stm32f10x.h * @author MCD Application Team - * @version V4.2.0 - * @date 31-March-2017 + * @version V4.1.0 + * @date 29-April-2016 * @brief CMSIS Cortex-M3 Device Peripheral Access Layer System Header File. ****************************************************************************** * @attention * - *

© COPYRIGHT(c) 2017 STMicroelectronics

+ *

© COPYRIGHT(c) 2016 STMicroelectronics

* * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: @@ -67,8 +67,8 @@ */ extern uint32_t SystemCoreClock; /*!< System Clock Frequency (Core Clock) */ -extern const uint8_t AHBPrescTable[16U]; /*!< AHB prescalers table values */ -extern const uint8_t APBPrescTable[8U]; /*!< APB prescalers table values */ +extern const uint8_t AHBPrescTable[16]; /*!< AHB prescalers table values */ +extern const uint8_t APBPrescTable[8]; /*!< APB prescalers table values */ /** * @} diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/Release_Notes_stm32f1xx_hal.html b/targets/TARGET_STM/TARGET_STM32F1/device/Release_Notes_stm32f1xx_hal.html index c026d296fc5..9339962394e 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/Release_Notes_stm32f1xx_hal.html +++ b/targets/TARGET_STM/TARGET_STM32F1/device/Release_Notes_stm32f1xx_hal.html @@ -920,91 +920,7 @@

Update History

-

V1.1.0 / 14-April-2017

  • Add Low Layer drivers allowing performance and footprint optimization
    • Low -Layer drivers APIs provide register level programming: require deep -knowledge of peripherals described in STM32F1xx Reference Manuals
    • Low -Layer drivers are available for: ADC, Cortex, CRC, DAC, DMA, EXTI, GPIO, I2C, IWDG, PWR, RCC, RTC, SPI, TIM, -USART, WWDG peripherals and additionnal Low Level Bus, System and -Utilities APIs.
    • Low Layer drivers APIs are implemented as static inline function in new Inc/stm32f1xx_ll_ppp.h files for PPP peripherals, there is no configuration file and each stm32f1xx_ll_ppp.h file must be included in user code.
  • Add new HAL MMC driver
  • General updates to fix known defects and enhancements implementation
  • - -Enhance HAL delay and time base implementation:
    • Add -new drivers stm32f1xx_hal_timebase_rtc_alarm_template.c and -stm32f1xx_hal_timebase_tim_template.c which override the native -HAL time base functions (defined as weak) to either use the RTC/TIM as time -base tick source. For more details about the usage of these drivers, -please refer to HAL\HAL_TimeBase_RTC  and HAL\HAL_TimeBase_TIM examples and FreeRTOS-based applications
  • Fix extra warnings with GCC compiler
  • HAL drivers clean up: update 'uint32_t' cast with 'U'
  • Update to used the new defined Bit_Pos CMSIS defines insetad of POSITION_VAL() macro
  • Update HAL -weak empty callbacks to prevent unused argument compilation warnings with some -compilers by calling the following line: -
    • UNUSED(hppp);
  • STM32Fxxx_User_Manual.chm files regenerated for HAL V1.1.0
  • The following changes done on the HAL drivers require an update on the application code based on older HAL versions
    • HAL UART, USART, IRDA, SMARTCARD, SPI, I2C (referenced as PPP here below) drivers
      • Add PPP error management during DMA process. This requires the following updates on user application:
        • Configure and enable the PPP IRQ in HAL_PPP_MspInit() function
        • In stm32f1xx_it.c file, PPP_IRQHandler() function: add a call to HAL_PPP_IRQHandler() function
        • Add customize the Error Callback API: HAL_PPP_ErrorCallback()
    • HAL SD driver:
      • Overall rework of the driver for a more efficient implementation
        • Modify initialization API and structures
        • Modify Read / Write sequences: separate transfer process and SD Cards state management 
        • Adding interrupt mode for Read / Write operations
        • Update the HAL_SD_IRQHandler function by optimizing the management of interrupt errors
      • Refer to the following example to identify the changes: BSP example and USB_Device/MSC_Standalone application
    • HAL NAND driver:
      • Modify NAND_AddressTypeDef, NAND_DeviceConfigTypeDef and NAND_HandleTypeDef structures fields
      • Add new HAL_NAND_ConfigDevice API
    • HAL CEC driver:  Overall driver rework with compatibility break versus previous HAL version
      • Remove HAL CEC polling Process functions: HAL_CEC_Transmit() and HAL_CEC_Receive()
      • Remove -HAL CEC receive interrupt process function HAL_CEC_Receive_IT() -and enable the "receive"  mode during the Init phase
      • Rename HAL_CEC_GetReceivedFrameSize() funtion to HAL_CEC_GetLastReceivedFrameSize()
      • Add new HAL APIs: HAL_CEC_SetDeviceAddress() and HAL_CEC_ChangeRxBuffer()
      • Remove the 'InitiatorAddress' -field from the CEC_InitTypeDef structure and manage -it as a parameter in the HAL_CEC_Transmit_IT() function
      • Add new parameter 'RxFrameSize' in HAL_CEC_RxCpltCallback() function
      • Move CEC Rx buffer pointer from CEC_HandleTypeDef structure to CEC_InitTypeDef structure
    • HAL IWDG driver: rework overall driver for better implementation
      • Remove HAL_IWDG_Start(), HAL_IWDG_MspInit() and HAL_IWDG_GetState() APIs
    • HAL WWDG driver: rework overall driver for better implementation
      • Remove HAL_WWDG_Start(), HAL_WWDG_Start_IT(), HAL_WWDG_MspDeInit() and HAL_WWDG_GetState() APIs 
      • Update the HAL_WWDG_Refresh(WWDG_HandleTypeDef *hwwdg, uint32_t counter)  function and API  by removing the  "counter" parameter
  • HAL GENERIC update
    • Modifiy default HAL_Delay implementation to guarantee minimum delay 
    • stm32f1xx_hal_conf_template.h
      • Add new define LSI_VALUE
      • Add new define USE_SPI_CRC for code cleanup when the CRC calculation is disabled.
  • HAL CORTEX update
    • Move HAL_MPU_Disable() and HAL_MPU_Enable() from stm32f4xx_hal_cortex.h to stm32f4xx_hal_cortex.c
    • Clear the whole MPU control register in HAL_MPU_Disable() API
  • HAL FLASH update
    • HAL_FLASH_OB_Launch(): fix static code analyzer warning: The removed code will not execute under any circumstances
  • HAL GPIO update
    • Update IS_GPIO_PIN() macro implementation to be more safe
    • Update remap macros implementation to use CLEAR_BIT()/SET_BIT() macros instead of  MODIFY_REG() macro.
  • HAL RCC update
    • Update LSI workaround delay to use CPU cycles instead of systick
    • Move LSI_VALUE define from RCC HAL driver to stm32f1xx_hal_conf.h file
    • Adjust defined PLL MUL values in aPLLMULFactorTable[]
  • HAL ADC update
    • HAL_ADCEx_MultiModeStart_DMA()  and HAL_ADCEx_MultiModeStop_DMA() API's update to fix code static analyzer warning: Redundant Condition / Unreachable Computation
  • HAL DMA update
    • HAL_DMA_Init(): update to check compatibility between FIFO threshold level and size of the memory burst 
    • Global driver code optimization to reduce memory footprint 
    • New APIs HAL_DMA_RegisterCallback() and HAL_DMA_UnRegisterCallback() to register/unregister the different possible callbacks identified by enum typedef HAL_DMA_CallbackIDTypeDef
    • Add new Error Codes: HAL_DMA_ERROR_NO_XFER and HAL_DMA_ERROR_NOT_SUPPORTED
  • HAL USART update
    • Add Transfer abort functions and callbacks
    • DMA Receive process; the code -has been updated to clear the USART OVR flag before enabling DMA receive request.

    • Update HAL_USART_IRQHandler() to add a check on interrupt source before managing the error 
  • - -HAL UART update -
    • Several update on HAL UART driver to implement the new UART state machine: 
      • Add new field in UART_HandleTypeDef structure: "rxState", UART state information related to Rx Operations
      • Rename "state" field in UART_HandleTypeDef structure by "gstate": UART state information related to global Handle management and Tx Operations
      • Update UART process to manage the new UART states.
      • Update __HAL_UART_RESET_HANDLE_STATE() macro -to handle the new UART state parameters (gState, rxState)
    • Add Transfer abort functions and callbacks
    • Update HAL_UART_IRQHandler() to add a check on interrupt source before managing the error 
    • DMA Receive process; the code -has been updated to clear the USART OVR flag before enabling DMA receive request.

- - - - -
  • - -HAL IRDA update -
    • Several update on HAL IRDA driver to implement the new UART state machine: 
      • Add new field in IRDA_HandleTypeDef structure: "rxState", IRDA state information related to Rx Operations
      • Rename "state" field in UART_HandleTypeDef structure by "gstate": IRDA state information related to global Handle management and Tx Operations
      • Update IRDA process to manage the new UART states.
      • Update __HAL_IRDA_RESET_HANDLE_STATE() macro -to handle the new IRDA state parameters (gState, rxState)
    • Removal of IRDA_TIMEOUT_VALUE define
    • Add Transfer abort functions and callbacks
    • Update HAL_IRDA_IRQHandler() to add a check on interrupt source before managing the error 
    • DMA Receive process; the code -has been updated to clear the USART OVR flag before enabling DMA receive request.

  • - -HAL SMARTCARD update -
    • Several update on HAL SMARTCARD driver to implement the new UART state machine: 
      • Add new field in SMARTCARD_HandleTypeDef structure: "rxState", SMARTCARDstate information related to Rx Operations
      • Rename "state" field in UART_HandleTypeDef structure by "gstate": SMARTCARDstate information related to global Handle management and Tx Operations
      • Update SMARTCARD process to manage the new UART states.
      • Update __HAL_SMARTCARD_RESET_HANDLE_STATE() macro -to handle the new SMARTCARD state parameters (gState, rxState)
    • Add Transfer abort functions and callbacks
    • Update HAL_SMARTCARD_IRQHandler() to add a check on interrupt source before managing the error 
    • DMA Receive process; the code -has been updated to clear the USART OVR flag before enabling DMA receive request.

  • HAL CAN update
    • Add - management of overrun error. 
    • Allow - possibility to receive messages from the 2 RX FIFOs in parallel via - interrupt.
    • Fix message - lost issue with specific sequence of transmit requests.
    • Handle - transmission failure with error callback, when NART is enabled.
    • Add __HAL_CAN_CANCEL_TRANSMIT() call to abort transmission when - timeout is reached
  • HAL TIM update
    • Add __HAL_TIM_MOE_DISABLE_UNCONDITIONALLY() macro to disable Master output without check on TIM channel state. 
    • Update HAL_TIMEx_ConfigBreakDeadTime() to fix TIM BDTR register corruption.
    • Update Input Capture polarity by removing non-supported "TIM_INPUTCHANNELPOLARITY_BOTHEDGE" define.
    • Update HAL_TIM_ConfigOCrefClear() API by removing the usage of non-existant SMCR OCCS bit.
    • Add -"AutoReloadPreload" field to TIM_Base_InitTypeDef structure and -corresponding macros __HAL_TIM_ENABLE_OCxPRELOAD() and -__HAL_TIM_DISABLE_OCxPRELOAD() .
    • Update TIM_Base_SetConfig() API to set the auto-reload preload.
  • HAL I2C update
    • Update -HAL_I2C_Master_Transmit() and HAL_I2C_Slave_Transmit() to avoid sending -extra bytes at the end of the transmit processes
    • Update - HAL_I2C_Mem_Read() API to fix wrong check on misused parameter �Size�
    • Update - I2C_MasterReceive_RXNE() and I2C_MasterReceive_BTF() static APIs to - enhance Master sequential reception process.
  • HAL SPI update
    • Major Update to improve performance in - polling/interrupt mode to reach max frequency:
      • Polling mode :
        • Replace use of - SPI_WaitOnFlagUnitTimeout() funnction by "if" statement to - check on RXNE/TXE flage while transferring data.
        • Use API data pointer instead of SPI - handle data pointer.
      • Use a Goto implementation instead of - "if..else" statements
      • Interrupt mode
        • Minimize access on SPI registers.
        • Split the SPI modes into dedicated - static functions to minimize checking statements under - HAL_IRQHandler():
          • 1lines/2lines modes
          • 8 bit/ 16 bits data formats
          • CRC calculation enabled/disabled.
      • Remove waiting loop under ISR when - closing  the communication.
      • All modes:  
        • Adding switch USE_SPI_CRC to minimize - number of statements when CRC calculation is disabled.
        • Update Timeout management to check on - global process.
        • Update Error code management in all - processes.
    • Add note to the max frequencies reached in - all modes.
    • Add note about Master Receive mode - restrictions :
    • Master Receive mode restriction:
      -       (#) In Master unidirectional receive-only - mode (MSTR =1, BIDIMODE=0, RXONLY=0) or
      -           bidirectional - receive mode (MSTR=1, BIDIMODE=1, BIDIOE=0), to ensure that the SPI
      -           does not initiate - a new transfer the following procedure has to be respected:
      -           (##) - HAL_SPI_DeInit()
      -           (##) - HAL_SPI_Init()
    • Add transfer abort APIs and - associated callbacks in interrupt mode
      • HAL_SPI_Abort()
      • HAL_SPI_Abort_IT()
      • HAL_SPI_AbortCpltCallback()
  • - -HAL CEC update
    • Overall driver rework with break of compatibility with HAL V1.0.5
      • Remove the HAL CEC polling Process: HAL_CEC_Transmit() and HAL_CEC_Receive()
      • Remove the HAL CEC receive interrupt process (HAL_CEC_Receive_IT()) and manage the "Receive" mode enable within the Init phase
      • Rename HAL_CEC_GetReceivedFrameSize() function to HAL_CEC_GetLastReceivedFrameSize() function
      • Add new HAL APIs: HAL_CEC_SetDeviceAddress() and HAL_CEC_ChangeRxBuffer()
      • Remove the 'InitiatorAddress' -field from the CEC_InitTypeDef structure and manage -it as a parameter in the HAL_CEC_Transmit_IT() function
      • Add new parameter 'RxFrameSize' in HAL_CEC_RxCpltCallback() function
      • Move CEC Rx buffer pointer from CEC_HandleTypeDef structure to CEC_InitTypeDef structure
    • Update driver to implement the new CEC state machine:
      • Add new "rxState" field in CEC_HandleTypeDef structure to provide the CEC state information related to Rx Operations
      • Rename "state" field in CEC_HandleTypeDef structure to "gstate": CEC state information related to global Handle management and Tx Operations
      • Update CEC process to manage the new CEC states.
      • Update __HAL_CEC_RESET_HANDLE_STATE() macro to handle the new CEC state parameters (gState, rxState)
-
  • HAL I2S update
    • Update I2S Transmit/Receive polling process to manage Overrun and Underrun errors
    • HAL I2S driver ovall clean-up and optimization
    • HAL_I2S_Init() API updated to
      • Fix wrong I2S clock calculation when PCM mode is used.
      • Return state HAL_I2S_ERROR_PRESCALER when the I2S clock is wrongly configured
  • HAL NAND update
    • Modify NAND_AddressTypeDef, NAND_DeviceConfigTypeDef and NAND_HandleTypeDef structures fields
    • Add new HAL_NAND_ConfigDevice API
-
  • HAL USB PCD update
    • Flush all TX FIFOs on USB Reset
    • Remove Lock mechanism from HAL_PCD_EP_Transmit() and HAL_PCD_EP_Receive() API's
  • LL USB update
    • Enable DMA Burst mode for USB OTG HS
    • Fix SD card detection issue
  • LL SDMMC update
    • Add new SDMMC_CmdSDEraseStartAdd, SDMMC_CmdSDEraseEndAdd, SDMMC_CmdOpCondition and SDMMC_CmdSwitch functions

V1.0.5 / 06-December-2016

+

V1.0.5 / 06-December-2016

diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32_hal_legacy.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32_hal_legacy.h index 6cc1ce6c2b8..932527387a6 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32_hal_legacy.h +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32_hal_legacy.h @@ -2,14 +2,14 @@ ****************************************************************************** * @file stm32_hal_legacy.h * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.4 + * @date 29-April-2016 * @brief This file contains aliases definition for the STM32Cube HAL constants * macros and functions maintained for legacy purpose. ****************************************************************************** * @attention * - *

© COPYRIGHT(c) 2017 STMicroelectronics

+ *

© COPYRIGHT(c) 2016 STMicroelectronics

* * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: @@ -138,7 +138,6 @@ #define COMP_EXTI_LINE_COMP5_EVENT COMP_EXTI_LINE_COMP5 #define COMP_EXTI_LINE_COMP6_EVENT COMP_EXTI_LINE_COMP6 #define COMP_EXTI_LINE_COMP7_EVENT COMP_EXTI_LINE_COMP7 -#define COMP_LPTIMCONNECTION_ENABLED COMP_LPTIMCONNECTION_IN1_ENABLED /*!< COMPX output is connected to LPTIM input 1 */ #define COMP_OUTPUT_COMP6TIM2OCREFCLR COMP_OUTPUT_COMP6_TIM2OCREFCLR #if defined(STM32F373xC) || defined(STM32F378xx) #define COMP_OUTPUT_TIM3IC1 COMP_OUTPUT_COMP1_TIM3IC1 @@ -151,9 +150,6 @@ #define COMP_NONINVERTINGINPUT_IO1 COMP_INPUT_PLUS_IO1 #define COMP_NONINVERTINGINPUT_IO2 COMP_INPUT_PLUS_IO2 #define COMP_NONINVERTINGINPUT_IO3 COMP_INPUT_PLUS_IO3 -#define COMP_NONINVERTINGINPUT_IO4 COMP_INPUT_PLUS_IO4 -#define COMP_NONINVERTINGINPUT_IO5 COMP_INPUT_PLUS_IO5 -#define COMP_NONINVERTINGINPUT_IO6 COMP_INPUT_PLUS_IO6 #define COMP_INVERTINGINPUT_1_4VREFINT COMP_INPUT_MINUS_1_4VREFINT #define COMP_INVERTINGINPUT_1_2VREFINT COMP_INPUT_MINUS_1_2VREFINT @@ -164,16 +160,8 @@ #define COMP_INVERTINGINPUT_DAC1 COMP_INPUT_MINUS_DAC1_CH1 #define COMP_INVERTINGINPUT_DAC2 COMP_INPUT_MINUS_DAC1_CH2 #define COMP_INVERTINGINPUT_IO1 COMP_INPUT_MINUS_IO1 -#if defined(STM32L0) -/* Issue fixed on STM32L0 COMP driver: only 2 dedicated IO (IO1 and IO2), */ -/* IO2 was wrongly assigned to IO shared with DAC and IO3 was corresponding */ -/* to the second dedicated IO (only for COMP2). */ -#define COMP_INVERTINGINPUT_IO2 COMP_INPUT_MINUS_DAC1_CH2 -#define COMP_INVERTINGINPUT_IO3 COMP_INPUT_MINUS_IO2 -#else #define COMP_INVERTINGINPUT_IO2 COMP_INPUT_MINUS_IO2 #define COMP_INVERTINGINPUT_IO3 COMP_INPUT_MINUS_IO3 -#endif #define COMP_INVERTINGINPUT_IO4 COMP_INPUT_MINUS_IO4 #define COMP_INVERTINGINPUT_IO5 COMP_INPUT_MINUS_IO5 @@ -241,9 +229,9 @@ #define DAC1_CHANNEL_1 DAC_CHANNEL_1 #define DAC1_CHANNEL_2 DAC_CHANNEL_2 #define DAC2_CHANNEL_1 DAC_CHANNEL_1 -#define DAC_WAVE_NONE 0x00000000U -#define DAC_WAVE_NOISE DAC_CR_WAVE1_0 -#define DAC_WAVE_TRIANGLE DAC_CR_WAVE1_1 +#define DAC_WAVE_NONE ((uint32_t)0x00000000U) +#define DAC_WAVE_NOISE ((uint32_t)DAC_CR_WAVE1_0) +#define DAC_WAVE_TRIANGLE ((uint32_t)DAC_CR_WAVE1_1) #define DAC_WAVEGENERATION_NONE DAC_WAVE_NONE #define DAC_WAVEGENERATION_NOISE DAC_WAVE_NOISE #define DAC_WAVEGENERATION_TRIANGLE DAC_WAVE_TRIANGLE @@ -356,7 +344,6 @@ #define OB_RDP_LEVEL0 OB_RDP_LEVEL_0 #define OB_RDP_LEVEL1 OB_RDP_LEVEL_1 #define OB_RDP_LEVEL2 OB_RDP_LEVEL_2 - /** * @} */ @@ -382,7 +369,7 @@ /** @defgroup LL_FMC_Aliased_Defines LL FMC Aliased Defines maintained for compatibility purpose * @{ */ -#if defined(STM32L4) || defined(STM32F7) || defined(STM32H7) +#if defined(STM32L4) || defined(STM32F7) #define FMC_NAND_PCC_WAIT_FEATURE_DISABLE FMC_NAND_WAIT_FEATURE_DISABLE #define FMC_NAND_PCC_WAIT_FEATURE_ENABLE FMC_NAND_WAIT_FEATURE_ENABLE #define FMC_NAND_PCC_MEM_BUS_WIDTH_8 FMC_NAND_MEM_BUS_WIDTH_8 @@ -457,25 +444,6 @@ * @} */ -/** @defgroup HAL_JPEG_Aliased_Macros HAL JPEG Aliased Macros maintained for legacy purpose - * @{ - */ - -#if defined(STM32H7) - #define __HAL_RCC_JPEG_CLK_ENABLE __HAL_RCC_JPGDECEN_CLK_ENABLE - #define __HAL_RCC_JPEG_CLK_DISABLE __HAL_RCC_JPGDECEN_CLK_DISABLE - #define __HAL_RCC_JPEG_FORCE_RESET __HAL_RCC_JPGDECRST_FORCE_RESET - #define __HAL_RCC_JPEG_RELEASE_RESET __HAL_RCC_JPGDECRST_RELEASE_RESET - #define __HAL_RCC_JPEG_CLK_SLEEP_ENABLE __HAL_RCC_JPGDEC_CLK_SLEEP_ENABLE - #define __HAL_RCC_JPEG_CLK_SLEEP_DISABLE __HAL_RCC_JPGDEC_CLK_SLEEP_DISABLE -#endif /* STM32H7 */ - - -/** - * @} - */ - - /** @defgroup HAL_HRTIM_Aliased_Macros HAL HRTIM Aliased Macros maintained for legacy purpose * @{ */ @@ -873,8 +841,6 @@ #define __DIVFRAQ_SAMPLING8 UART_DIVFRAQ_SAMPLING8 #define __UART_BRR_SAMPLING8 UART_BRR_SAMPLING8 -#define __DIV_LPUART UART_DIV_LPUART - #define UART_WAKEUPMETHODE_IDLELINE UART_WAKEUPMETHOD_IDLELINE #define UART_WAKEUPMETHODE_ADDRESSMARK UART_WAKEUPMETHOD_ADDRESSMARK @@ -915,9 +881,9 @@ #define CAN_IT_RQCP2 CAN_IT_TME #define INAK_TIMEOUT CAN_TIMEOUT_VALUE #define SLAK_TIMEOUT CAN_TIMEOUT_VALUE -#define CAN_TXSTATUS_FAILED ((uint8_t)0x00) -#define CAN_TXSTATUS_OK ((uint8_t)0x01) -#define CAN_TXSTATUS_PENDING ((uint8_t)0x02) +#define CAN_TXSTATUS_FAILED ((uint8_t)0x00U) +#define CAN_TXSTATUS_OK ((uint8_t)0x01U) +#define CAN_TXSTATUS_PENDING ((uint8_t)0x02U) /** * @} @@ -936,45 +902,48 @@ #define MACFCR_CLEAR_MASK ETH_MACFCR_CLEAR_MASK #define DMAOMR_CLEAR_MASK ETH_DMAOMR_CLEAR_MASK -#define ETH_MMCCR 0x00000100U -#define ETH_MMCRIR 0x00000104U -#define ETH_MMCTIR 0x00000108U -#define ETH_MMCRIMR 0x0000010CU -#define ETH_MMCTIMR 0x00000110U -#define ETH_MMCTGFSCCR 0x0000014CU -#define ETH_MMCTGFMSCCR 0x00000150U -#define ETH_MMCTGFCR 0x00000168U -#define ETH_MMCRFCECR 0x00000194U -#define ETH_MMCRFAECR 0x00000198U -#define ETH_MMCRGUFCR 0x000001C4U +#define ETH_MMCCR ((uint32_t)0x00000100U) +#define ETH_MMCRIR ((uint32_t)0x00000104U) +#define ETH_MMCTIR ((uint32_t)0x00000108U) +#define ETH_MMCRIMR ((uint32_t)0x0000010CU) +#define ETH_MMCTIMR ((uint32_t)0x00000110U) +#define ETH_MMCTGFSCCR ((uint32_t)0x0000014CU) +#define ETH_MMCTGFMSCCR ((uint32_t)0x00000150U) +#define ETH_MMCTGFCR ((uint32_t)0x00000168U) +#define ETH_MMCRFCECR ((uint32_t)0x00000194U) +#define ETH_MMCRFAECR ((uint32_t)0x00000198U) +#define ETH_MMCRGUFCR ((uint32_t)0x000001C4U) -#define ETH_MAC_TXFIFO_FULL 0x02000000U /* Tx FIFO full */ -#define ETH_MAC_TXFIFONOT_EMPTY 0x01000000U /* Tx FIFO not empty */ -#define ETH_MAC_TXFIFO_WRITE_ACTIVE 0x00400000U /* Tx FIFO write active */ -#define ETH_MAC_TXFIFO_IDLE 0x00000000U /* Tx FIFO read status: Idle */ -#define ETH_MAC_TXFIFO_READ 0x00100000U /* Tx FIFO read status: Read (transferring data to the MAC transmitter) */ -#define ETH_MAC_TXFIFO_WAITING 0x00200000U /* Tx FIFO read status: Waiting for TxStatus from MAC transmitter */ -#define ETH_MAC_TXFIFO_WRITING 0x00300000U /* Tx FIFO read status: Writing the received TxStatus or flushing the TxFIFO */ -#define ETH_MAC_TRANSMISSION_PAUSE 0x00080000U /* MAC transmitter in pause */ -#define ETH_MAC_TRANSMITFRAMECONTROLLER_IDLE 0x00000000U /* MAC transmit frame controller: Idle */ -#define ETH_MAC_TRANSMITFRAMECONTROLLER_WAITING 0x00020000U /* MAC transmit frame controller: Waiting for Status of previous frame or IFG/backoff period to be over */ -#define ETH_MAC_TRANSMITFRAMECONTROLLER_GENRATING_PCF 0x00040000U /* MAC transmit frame controller: Generating and transmitting a Pause control frame (in full duplex mode) */ -#define ETH_MAC_TRANSMITFRAMECONTROLLER_TRANSFERRING 0x00060000U /* MAC transmit frame controller: Transferring input frame for transmission */ -#define ETH_MAC_MII_TRANSMIT_ACTIVE 0x00010000U /* MAC MII transmit engine active */ -#define ETH_MAC_RXFIFO_EMPTY 0x00000000U /* Rx FIFO fill level: empty */ -#define ETH_MAC_RXFIFO_BELOW_THRESHOLD 0x00000100U /* Rx FIFO fill level: fill-level below flow-control de-activate threshold */ -#define ETH_MAC_RXFIFO_ABOVE_THRESHOLD 0x00000200U /* Rx FIFO fill level: fill-level above flow-control activate threshold */ -#define ETH_MAC_RXFIFO_FULL 0x00000300U /* Rx FIFO fill level: full */ -#define ETH_MAC_READCONTROLLER_IDLE 0x00000000U /* Rx FIFO read controller IDLE state */ -#define ETH_MAC_READCONTROLLER_READING_DATA 0x00000020U /* Rx FIFO read controller Reading frame data */ -#define ETH_MAC_READCONTROLLER_READING_STATUS 0x00000040U /* Rx FIFO read controller Reading frame status (or time-stamp) */ -#define ETH_MAC_READCONTROLLER_FLUSHING 0x00000060U /* Rx FIFO read controller Flushing the frame data and status */ -#define ETH_MAC_RXFIFO_WRITE_ACTIVE 0x00000010U /* Rx FIFO write controller active */ -#define ETH_MAC_SMALL_FIFO_NOTACTIVE 0x00000000U /* MAC small FIFO read / write controllers not active */ -#define ETH_MAC_SMALL_FIFO_READ_ACTIVE 0x00000002U /* MAC small FIFO read controller active */ -#define ETH_MAC_SMALL_FIFO_WRITE_ACTIVE 0x00000004U /* MAC small FIFO write controller active */ -#define ETH_MAC_SMALL_FIFO_RW_ACTIVE 0x00000006U /* MAC small FIFO read / write controllers active */ -#define ETH_MAC_MII_RECEIVE_PROTOCOL_ACTIVE 0x00000001U /* MAC MII receive protocol engine active */ +#define ETH_MAC_TXFIFO_FULL ((uint32_t)0x02000000) /* Tx FIFO full */ +#define ETH_MAC_TXFIFONOT_EMPTY ((uint32_t)0x01000000) /* Tx FIFO not empty */ +#define ETH_MAC_TXFIFO_WRITE_ACTIVE ((uint32_t)0x00400000) /* Tx FIFO write active */ +#define ETH_MAC_TXFIFO_IDLE ((uint32_t)0x00000000) /* Tx FIFO read status: Idle */ +#define ETH_MAC_TXFIFO_READ ((uint32_t)0x00100000) /* Tx FIFO read status: Read (transferring data to the MAC transmitter) */ +#define ETH_MAC_TXFIFO_WAITING ((uint32_t)0x00200000) /* Tx FIFO read status: Waiting for TxStatus from MAC transmitter */ +#define ETH_MAC_TXFIFO_WRITING ((uint32_t)0x00300000) /* Tx FIFO read status: Writing the received TxStatus or flushing the TxFIFO */ +#define ETH_MAC_TRANSMISSION_PAUSE ((uint32_t)0x00080000) /* MAC transmitter in pause */ +#define ETH_MAC_TRANSMITFRAMECONTROLLER_IDLE ((uint32_t)0x00000000) /* MAC transmit frame controller: Idle */ +#define ETH_MAC_TRANSMITFRAMECONTROLLER_WAITING ((uint32_t)0x00020000) /* MAC transmit frame controller: Waiting for Status of previous frame or IFG/backoff period to be over */ +#define ETH_MAC_TRANSMITFRAMECONTROLLER_GENRATING_PCF ((uint32_t)0x00040000) /* MAC transmit frame controller: Generating and transmitting a Pause control frame (in full duplex mode) */ +#define ETH_MAC_TRANSMITFRAMECONTROLLER_TRANSFERRING ((uint32_t)0x00060000) /* MAC transmit frame controller: Transferring input frame for transmission */ +#define ETH_MAC_MII_TRANSMIT_ACTIVE ((uint32_t)0x00010000) /* MAC MII transmit engine active */ +#define ETH_MAC_RXFIFO_EMPTY ((uint32_t)0x00000000) /* Rx FIFO fill level: empty */ +#define ETH_MAC_RXFIFO_BELOW_THRESHOLD ((uint32_t)0x00000100) /* Rx FIFO fill level: fill-level below flow-control de-activate threshold */ +#define ETH_MAC_RXFIFO_ABOVE_THRESHOLD ((uint32_t)0x00000200) /* Rx FIFO fill level: fill-level above flow-control activate threshold */ +#define ETH_MAC_RXFIFO_FULL ((uint32_t)0x00000300) /* Rx FIFO fill level: full */ +#if defined(STM32F1) +#else +#define ETH_MAC_READCONTROLLER_IDLE ((uint32_t)0x00000000) /* Rx FIFO read controller IDLE state */ +#define ETH_MAC_READCONTROLLER_READING_DATA ((uint32_t)0x00000020) /* Rx FIFO read controller Reading frame data */ +#define ETH_MAC_READCONTROLLER_READING_STATUS ((uint32_t)0x00000040) /* Rx FIFO read controller Reading frame status (or time-stamp) */ +#endif +#define ETH_MAC_READCONTROLLER_FLUSHING ((uint32_t)0x00000060) /* Rx FIFO read controller Flushing the frame data and status */ +#define ETH_MAC_RXFIFO_WRITE_ACTIVE ((uint32_t)0x00000010) /* Rx FIFO write controller active */ +#define ETH_MAC_SMALL_FIFO_NOTACTIVE ((uint32_t)0x00000000) /* MAC small FIFO read / write controllers not active */ +#define ETH_MAC_SMALL_FIFO_READ_ACTIVE ((uint32_t)0x00000002) /* MAC small FIFO read controller active */ +#define ETH_MAC_SMALL_FIFO_WRITE_ACTIVE ((uint32_t)0x00000004) /* MAC small FIFO write controller active */ +#define ETH_MAC_SMALL_FIFO_RW_ACTIVE ((uint32_t)0x00000006) /* MAC small FIFO read / write controllers active */ +#define ETH_MAC_MII_RECEIVE_PROTOCOL_ACTIVE ((uint32_t)0x00000001) /* MAC MII receive protocol engine active */ /** * @} @@ -996,7 +965,7 @@ * @} */ -#if defined(STM32L4) || defined(STM32F7) || defined(STM32F427xx) || defined(STM32F437xx) ||\ +#if defined(STM32L4xx) || defined(STM32F7) || defined(STM32F427xx) || defined(STM32F437xx) ||\ defined(STM32F429xx) || defined(STM32F439xx) || defined(STM32F469xx) || defined(STM32F479xx) /** @defgroup HAL_DMA2D_Aliased_Defines HAL DMA2D Aliased Defines maintained for legacy purpose * @{ @@ -1021,7 +990,7 @@ /** * @} */ -#endif /* STM32L4 || STM32F7*/ +#endif /* STM32L4xx || STM32F7*/ /** @defgroup HAL_PPP_Aliased_Defines HAL PPP Aliased Defines maintained for legacy purpose * @{ @@ -1206,9 +1175,6 @@ * @{ */ #define HAL_LTDC_LineEvenCallback HAL_LTDC_LineEventCallback -#define HAL_LTDC_Relaod HAL_LTDC_Reload -#define HAL_LTDC_StructInitFromVideoConfig HAL_LTDCEx_StructInitFromVideoConfig -#define HAL_LTDC_StructInitFromAdaptedCommandConfig HAL_LTDCEx_StructInitFromAdaptedCommandConfig /** * @} */ @@ -1250,7 +1216,6 @@ #define __HAL_CLEAR_FLAG __HAL_SYSCFG_CLEAR_FLAG #define __HAL_VREFINT_OUT_ENABLE __HAL_SYSCFG_VREFINT_OUT_ENABLE #define __HAL_VREFINT_OUT_DISABLE __HAL_SYSCFG_VREFINT_OUT_DISABLE -#define __HAL_SYSCFG_SRAM2_WRP_ENABLE __HAL_SYSCFG_SRAM2_WRP_0_31_ENABLE #define SYSCFG_FLAG_VREF_READY SYSCFG_FLAG_VREFINT_READY #define SYSCFG_FLAG_RC48 RCC_FLAG_HSI48 @@ -1645,11 +1610,7 @@ #define __HAL_I2C_RESET_CR2 I2C_RESET_CR2 #define __HAL_I2C_GENERATE_START I2C_GENERATE_START -#if defined(STM32F1) -#define __HAL_I2C_FREQ_RANGE I2C_FREQRANGE -#else #define __HAL_I2C_FREQ_RANGE I2C_FREQ_RANGE -#endif /* STM32F1 */ #define __HAL_I2C_RISE_TIME I2C_RISE_TIME #define __HAL_I2C_SPEED_STANDARD I2C_SPEED_STANDARD #define __HAL_I2C_SPEED_FAST I2C_SPEED_FAST @@ -2255,26 +2216,26 @@ #define __USART3_CLK_SLEEP_ENABLE __HAL_RCC_USART3_CLK_SLEEP_ENABLE #define __USART3_FORCE_RESET __HAL_RCC_USART3_FORCE_RESET #define __USART3_RELEASE_RESET __HAL_RCC_USART3_RELEASE_RESET -#define __USART4_CLK_DISABLE __HAL_RCC_UART4_CLK_DISABLE -#define __USART4_CLK_ENABLE __HAL_RCC_UART4_CLK_ENABLE -#define __USART4_CLK_SLEEP_ENABLE __HAL_RCC_UART4_CLK_SLEEP_ENABLE -#define __USART4_CLK_SLEEP_DISABLE __HAL_RCC_UART4_CLK_SLEEP_DISABLE -#define __USART4_FORCE_RESET __HAL_RCC_UART4_FORCE_RESET -#define __USART4_RELEASE_RESET __HAL_RCC_UART4_RELEASE_RESET -#define __USART5_CLK_DISABLE __HAL_RCC_UART5_CLK_DISABLE -#define __USART5_CLK_ENABLE __HAL_RCC_UART5_CLK_ENABLE -#define __USART5_CLK_SLEEP_ENABLE __HAL_RCC_UART5_CLK_SLEEP_ENABLE -#define __USART5_CLK_SLEEP_DISABLE __HAL_RCC_UART5_CLK_SLEEP_DISABLE -#define __USART5_FORCE_RESET __HAL_RCC_UART5_FORCE_RESET -#define __USART5_RELEASE_RESET __HAL_RCC_UART5_RELEASE_RESET -#define __USART7_CLK_DISABLE __HAL_RCC_UART7_CLK_DISABLE -#define __USART7_CLK_ENABLE __HAL_RCC_UART7_CLK_ENABLE -#define __USART7_FORCE_RESET __HAL_RCC_UART7_FORCE_RESET -#define __USART7_RELEASE_RESET __HAL_RCC_UART7_RELEASE_RESET -#define __USART8_CLK_DISABLE __HAL_RCC_UART8_CLK_DISABLE -#define __USART8_CLK_ENABLE __HAL_RCC_UART8_CLK_ENABLE -#define __USART8_FORCE_RESET __HAL_RCC_UART8_FORCE_RESET -#define __USART8_RELEASE_RESET __HAL_RCC_UART8_RELEASE_RESET +#define __USART4_CLK_DISABLE __HAL_RCC_USART4_CLK_DISABLE +#define __USART4_CLK_ENABLE __HAL_RCC_USART4_CLK_ENABLE +#define __USART4_CLK_SLEEP_ENABLE __HAL_RCC_USART4_CLK_SLEEP_ENABLE +#define __USART4_CLK_SLEEP_DISABLE __HAL_RCC_USART4_CLK_SLEEP_DISABLE +#define __USART4_FORCE_RESET __HAL_RCC_USART4_FORCE_RESET +#define __USART4_RELEASE_RESET __HAL_RCC_USART4_RELEASE_RESET +#define __USART5_CLK_DISABLE __HAL_RCC_USART5_CLK_DISABLE +#define __USART5_CLK_ENABLE __HAL_RCC_USART5_CLK_ENABLE +#define __USART5_CLK_SLEEP_ENABLE __HAL_RCC_USART5_CLK_SLEEP_ENABLE +#define __USART5_CLK_SLEEP_DISABLE __HAL_RCC_USART5_CLK_SLEEP_DISABLE +#define __USART5_FORCE_RESET __HAL_RCC_USART5_FORCE_RESET +#define __USART5_RELEASE_RESET __HAL_RCC_USART5_RELEASE_RESET +#define __USART7_CLK_DISABLE __HAL_RCC_USART7_CLK_DISABLE +#define __USART7_CLK_ENABLE __HAL_RCC_USART7_CLK_ENABLE +#define __USART7_FORCE_RESET __HAL_RCC_USART7_FORCE_RESET +#define __USART7_RELEASE_RESET __HAL_RCC_USART7_RELEASE_RESET +#define __USART8_CLK_DISABLE __HAL_RCC_USART8_CLK_DISABLE +#define __USART8_CLK_ENABLE __HAL_RCC_USART8_CLK_ENABLE +#define __USART8_FORCE_RESET __HAL_RCC_USART8_FORCE_RESET +#define __USART8_RELEASE_RESET __HAL_RCC_USART8_RELEASE_RESET #define __USB_CLK_DISABLE __HAL_RCC_USB_CLK_DISABLE #define __USB_CLK_ENABLE __HAL_RCC_USB_CLK_ENABLE #define __USB_FORCE_RESET __HAL_RCC_USB_FORCE_RESET @@ -2658,30 +2619,6 @@ #define __HAL_RCC_GET_SDIO_SOURCE __HAL_RCC_GET_SDMMC1_SOURCE #endif -#if defined(STM32H7) -#define __HAL_RCC_USB_OTG_HS_CLK_ENABLE() __HAL_RCC_USB1_OTG_HS_CLK_ENABLE() -#define __HAL_RCC_USB_OTG_HS_ULPI_CLK_ENABLE() __HAL_RCC_USB1_OTG_HS_ULPI_CLK_ENABLE() -#define __HAL_RCC_USB_OTG_HS_CLK_DISABLE() __HAL_RCC_USB1_OTG_HS_CLK_DISABLE() -#define __HAL_RCC_USB_OTG_HS_ULPI_CLK_DISABLE() __HAL_RCC_USB1_OTG_HS_ULPI_CLK_DISABLE() -#define __HAL_RCC_USB_OTG_HS_FORCE_RESET() __HAL_RCC_USB1_OTG_HS_FORCE_RESET() -#define __HAL_RCC_USB_OTG_HS_RELEASE_RESET() __HAL_RCC_USB1_OTG_HS_RELEASE_RESET() -#define __HAL_RCC_USB_OTG_HS_CLK_SLEEP_ENABLE() __HAL_RCC_USB1_OTG_HS_CLK_SLEEP_ENABLE() -#define __HAL_RCC_USB_OTG_HS_ULPI_CLK_SLEEP_ENABLE() __HAL_RCC_USB1_OTG_HS_ULPI_CLK_SLEEP_ENABLE() -#define __HAL_RCC_USB_OTG_HS_CLK_SLEEP_DISABLE() __HAL_RCC_USB1_OTG_HS_CLK_SLEEP_DISABLE() -#define __HAL_RCC_USB_OTG_HS_ULPI_CLK_SLEEP_DISABLE() __HAL_RCC_USB1_OTG_HS_ULPI_CLK_SLEEP_DISABLE() - -#define __HAL_RCC_USB_OTG_FS_CLK_ENABLE() __HAL_RCC_USB2_OTG_FS_CLK_ENABLE() -#define __HAL_RCC_USB_OTG_FS_ULPI_CLK_ENABLE() __HAL_RCC_USB2_OTG_FS_ULPI_CLK_ENABLE() -#define __HAL_RCC_USB_OTG_FS_CLK_DISABLE() __HAL_RCC_USB2_OTG_FS_CLK_DISABLE() -#define __HAL_RCC_USB_OTG_FS_ULPI_CLK_DISABLE() __HAL_RCC_USB2_OTG_FS_ULPI_CLK_DISABLE() -#define __HAL_RCC_USB_OTG_FS_FORCE_RESET() __HAL_RCC_USB2_OTG_FS_FORCE_RESET() -#define __HAL_RCC_USB_OTG_FS_RELEASE_RESET() __HAL_RCC_USB2_OTG_FS_RELEASE_RESET() -#define __HAL_RCC_USB_OTG_FS_CLK_SLEEP_ENABLE() __HAL_RCC_USB2_OTG_FS_CLK_SLEEP_ENABLE() -#define __HAL_RCC_USB_OTG_FS_ULPI_CLK_SLEEP_ENABLE() __HAL_RCC_USB2_OTG_FS_ULPI_CLK_SLEEP_ENABLE() -#define __HAL_RCC_USB_OTG_FS_CLK_SLEEP_DISABLE() __HAL_RCC_USB2_OTG_FS_CLK_SLEEP_DISABLE() -#define __HAL_RCC_USB_OTG_FS_ULPI_CLK_SLEEP_DISABLE() __HAL_RCC_USB2_OTG_FS_ULPI_CLK_SLEEP_DISABLE() -#endif - #if defined(STM32F7) #define RCC_SDIOCLKSOURCE_CLK48 RCC_SDMMC1CLKSOURCE_CLK48 #define RCC_SDIOCLKSOURCE_SYSCLK RCC_SDMMC1CLKSOURCE_SYSCLK @@ -2700,22 +2637,10 @@ #define RCC_IT_HSI14 RCC_IT_HSI14RDY -#define RCC_IT_CSSLSE RCC_IT_LSECSS -#define RCC_IT_CSSHSE RCC_IT_CSS - -#define RCC_PLLMUL_3 RCC_PLL_MUL3 -#define RCC_PLLMUL_4 RCC_PLL_MUL4 -#define RCC_PLLMUL_6 RCC_PLL_MUL6 -#define RCC_PLLMUL_8 RCC_PLL_MUL8 -#define RCC_PLLMUL_12 RCC_PLL_MUL12 -#define RCC_PLLMUL_16 RCC_PLL_MUL16 -#define RCC_PLLMUL_24 RCC_PLL_MUL24 -#define RCC_PLLMUL_32 RCC_PLL_MUL32 -#define RCC_PLLMUL_48 RCC_PLL_MUL48 - -#define RCC_PLLDIV_2 RCC_PLL_DIV2 -#define RCC_PLLDIV_3 RCC_PLL_DIV3 -#define RCC_PLLDIV_4 RCC_PLL_DIV4 +#if defined(STM32L0) +#define RCC_IT_LSECSS RCC_IT_CSSLSE +#define RCC_IT_CSS RCC_IT_CSSHSE +#endif #define IS_RCC_MCOSOURCE IS_RCC_MCO1SOURCE #define __HAL_RCC_MCO_CONFIG __HAL_RCC_MCO1_CONFIG @@ -2832,22 +2757,10 @@ #define __HAL_RCC_DFSDM_IS_CLK_SLEEP_DISABLED __HAL_RCC_DFSDM1_IS_CLK_SLEEP_DISABLED #define DfsdmClockSelection Dfsdm1ClockSelection #define RCC_PERIPHCLK_DFSDM RCC_PERIPHCLK_DFSDM1 -#define RCC_DFSDMCLKSOURCE_PCLK RCC_DFSDM1CLKSOURCE_PCLK2 +#define RCC_DFSDMCLKSOURCE_PCLK RCC_DFSDM1CLKSOURCE_PCLK #define RCC_DFSDMCLKSOURCE_SYSCLK RCC_DFSDM1CLKSOURCE_SYSCLK #define __HAL_RCC_DFSDM_CONFIG __HAL_RCC_DFSDM1_CONFIG #define __HAL_RCC_GET_DFSDM_SOURCE __HAL_RCC_GET_DFSDM1_SOURCE -#define RCC_DFSDM1CLKSOURCE_PCLK RCC_DFSDM1CLKSOURCE_PCLK2 -#define RCC_SWPMI1CLKSOURCE_PCLK RCC_SWPMI1CLKSOURCE_PCLK1 -#define RCC_LPTIM1CLKSOURCE_PCLK RCC_LPTIM1CLKSOURCE_PCLK1 -#define RCC_LPTIM2CLKSOURCE_PCLK RCC_LPTIM2CLKSOURCE_PCLK1 - -#define RCC_DFSDM1AUDIOCLKSOURCE_I2SAPB1 RCC_DFSDM1AUDIOCLKSOURCE_I2S1 -#define RCC_DFSDM1AUDIOCLKSOURCE_I2SAPB2 RCC_DFSDM1AUDIOCLKSOURCE_I2S2 -#define RCC_DFSDM2AUDIOCLKSOURCE_I2SAPB1 RCC_DFSDM2AUDIOCLKSOURCE_I2S1 -#define RCC_DFSDM2AUDIOCLKSOURCE_I2SAPB2 RCC_DFSDM2AUDIOCLKSOURCE_I2S2 -#define RCC_DFSDM1CLKSOURCE_APB2 RCC_DFSDM1CLKSOURCE_PCLK2 -#define RCC_DFSDM2CLKSOURCE_APB2 RCC_DFSDM2CLKSOURCE_PCLK2 -#define RCC_FMPI2C1CLKSOURCE_APB RCC_FMPI2C1CLKSOURCE_PCLK1 /** * @} @@ -2927,7 +2840,7 @@ #define SD_OCR_CID_CSD_OVERWRIETE SD_OCR_CID_CSD_OVERWRITE #define SD_CMD_SD_APP_STAUS SD_CMD_SD_APP_STATUS -#if defined(STM32F4) || defined(STM32F2) +#if defined(STM32F4) #define SD_SDMMC_DISABLED SD_SDIO_DISABLED #define SD_SDMMC_FUNCTION_BUSY SD_SDIO_FUNCTION_BUSY #define SD_SDMMC_FUNCTION_FAILED SD_SDIO_FUNCTION_FAILED @@ -2978,14 +2891,6 @@ #define SDIO_IRQn SDMMC1_IRQn #define SDIO_IRQHandler SDMMC1_IRQHandler #endif - -#if defined(STM32F7) || defined(STM32F4) || defined(STM32F2) -#define HAL_SD_CardCIDTypedef HAL_SD_CardCIDTypeDef -#define HAL_SD_CardCSDTypedef HAL_SD_CardCSDTypeDef -#define HAL_SD_CardStatusTypedef HAL_SD_CardStatusTypeDef -#define HAL_SD_CardStateTypedef HAL_SD_CardStateTypeDef -#endif - /** * @} */ @@ -3174,7 +3079,6 @@ * @{ */ #define __HAL_LTDC_LAYER LTDC_LAYER -#define __HAL_LTDC_RELOAD_CONFIG __HAL_LTDC_RELOAD_IMMEDIATE_CONFIG /** * @} */ diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal.c b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal.c index 59a58207708..7cbec5a20b1 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal.c +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal.c @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_hal.c * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief HAL module driver. * This is the common part of the HAL initialization * @@ -70,19 +70,20 @@ /** @defgroup HAL_Private_Constants HAL Private Constants * @{ */ + /** - * @brief STM32F1xx HAL Driver version number V1.1.0 + * @brief STM32F1xx HAL Driver version number */ -#define __STM32F1xx_HAL_VERSION_MAIN (0x01U) /*!< [31:24] main version */ -#define __STM32F1xx_HAL_VERSION_SUB1 (0x01U) /*!< [23:16] sub1 version */ -#define __STM32F1xx_HAL_VERSION_SUB2 (0x00U) /*!< [15:8] sub2 version */ -#define __STM32F1xx_HAL_VERSION_RC (0x00U) /*!< [7:0] release candidate */ +#define __STM32F1xx_HAL_VERSION_MAIN (0x01) /*!< [31:24] main version */ +#define __STM32F1xx_HAL_VERSION_SUB1 (0x00) /*!< [23:16] sub1 version */ +#define __STM32F1xx_HAL_VERSION_SUB2 (0x05) /*!< [15:8] sub2 version */ +#define __STM32F1xx_HAL_VERSION_RC (0x00) /*!< [7:0] release candidate */ #define __STM32F1xx_HAL_VERSION ((__STM32F1xx_HAL_VERSION_MAIN << 24)\ |(__STM32F1xx_HAL_VERSION_SUB1 << 16)\ |(__STM32F1xx_HAL_VERSION_SUB2 << 8 )\ |(__STM32F1xx_HAL_VERSION_RC)) -#define IDCODE_DEVID_MASK 0x00000FFFU +#define IDCODE_DEVID_MASK ((uint32_t)0x00000FFF) /** * @} @@ -94,10 +95,13 @@ /** @defgroup HAL_Private_Variables HAL Private Variables * @{ */ -__IO uint32_t uwTick; + +static __IO uint32_t uwTick; + /** * @} */ + /* Private function prototypes -----------------------------------------------*/ /* Exported functions ---------------------------------------------------------*/ @@ -132,27 +136,22 @@ __IO uint32_t uwTick; peripheral ISR process, the Tick interrupt line must have higher priority (numerically lower) than the peripheral interrupt. Otherwise the caller ISR process will be blocked. - (++) functions affecting time base configurations are declared as __weak + (++) functions affecting time base configurations are declared as __Weak to make override possible in case of other implementations in user file. + @endverbatim * @{ */ /** - * @brief This function is used to initialize the HAL Library; it must be the first - * instruction to be executed in the main program (before to call any other - * HAL function), it performs the following: - * Configure the Flash prefetch. - * Configures the SysTick to generate an interrupt each 1 millisecond, - * which is clocked by the HSI (at this stage, the clock is not yet - * configured and thus the system is running from the internal HSI at 16 MHz). - * Set NVIC Group Priority to 4. - * Calls the HAL_MspInit() callback function defined in user file - * "stm32f1xx_hal_msp.c" to do the global low level hardware initialization - * - * @note SysTick is used as time base for the HAL_Delay() function, the application - * need to ensure that the SysTick time base is always set to 1 millisecond - * to have correct HAL operation. + * @brief This function configures the Flash prefetch, + * Configures time base source, NVIC and Low level hardware + * @note This function is called at the beginning of program after reset and before + * the clock configuration + * @note The time base configuration is based on MSI clock when exiting from Reset. + * Once done, time base tick start incrementing. + * In the default implementation,Systick is used as source of time base. + * The tick variable is incremented each 1ms in its ISR. * @retval HAL status */ HAL_StatusTypeDef HAL_Init(void) @@ -242,7 +241,7 @@ __weak void HAL_MspDeInit(void) * Care must be taken if HAL_Delay() is called from a peripheral ISR process, * The the SysTick interrupt must have higher priority (numerically lower) * than the peripheral interrupt. Otherwise the caller ISR process will be blocked. - * The function is declared as __weak to be overwritten in case of other + * The function is declared as __Weak to be overwritten in case of other * implementation in user file. * @param TickPriority: Tick interrupt priority. * @retval HAL status @@ -250,12 +249,12 @@ __weak void HAL_MspDeInit(void) __weak HAL_StatusTypeDef HAL_InitTick(uint32_t TickPriority) { /*Configure the SysTick to have interrupt in 1ms time basis*/ - HAL_SYSTICK_Config(SystemCoreClock/1000U); + HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq()/1000); /*Configure the SysTick IRQ priority */ - HAL_NVIC_SetPriority(SysTick_IRQn, TickPriority ,0U); + HAL_NVIC_SetPriority(SysTick_IRQn, TickPriority ,0); - /* Return function status */ + /* Return function status */ return HAL_OK; } @@ -264,8 +263,8 @@ __weak HAL_StatusTypeDef HAL_InitTick(uint32_t TickPriority) */ /** @defgroup HAL_Exported_Functions_Group2 HAL Control functions - * @brief HAL Control functions - * + * @brief HAL Control functions + * @verbatim =============================================================================== ##### HAL Control functions ##### @@ -278,10 +277,10 @@ __weak HAL_StatusTypeDef HAL_InitTick(uint32_t TickPriority) (+) Get the HAL API driver version (+) Get the device identifier (+) Get the device revision identifier - (+) Enable/Disable Debug module during SLEEP mode + (+) Enable/Disable Debug module during Sleep mode (+) Enable/Disable Debug module during STOP mode (+) Enable/Disable Debug module during STANDBY mode - + @endverbatim * @{ */ @@ -302,7 +301,7 @@ __weak void HAL_IncTick(void) /** * @brief Provides a tick value in millisecond. - * @note This function is declared as __weak to be overwritten in case of other + * @note This function is declared as __weak to be overwritten in case of other * implementations in user file. * @retval tick value */ @@ -312,28 +311,21 @@ __weak uint32_t HAL_GetTick(void) } /** - * @brief This function provides minimum delay (in milliseconds) based + * @brief This function provides accurate delay (in milliseconds) based * on variable incremented. * @note In the default implementation , SysTick timer is the source of time base. * It is used to generate interrupts at regular time intervals where uwTick * is incremented. - * @note This function is declared as __weak to be overwritten in case of other + * @note ThiS function is declared as __weak to be overwritten in case of other * implementations in user file. * @param Delay: specifies the delay time length, in milliseconds. * @retval None */ __weak void HAL_Delay(__IO uint32_t Delay) { - uint32_t tickstart = HAL_GetTick(); - uint32_t wait = Delay; - - /* Add a period to guarantee minimum wait */ - if (wait < HAL_MAX_DELAY) - { - wait++; - } - - while((HAL_GetTick() - tickstart) < wait) + uint32_t tickstart = 0; + tickstart = HAL_GetTick(); + while((HAL_GetTick() - tickstart) < Delay) { } } @@ -342,7 +334,7 @@ __weak void HAL_Delay(__IO uint32_t Delay) * @brief Suspend Tick increment. * @note In the default implementation , SysTick timer is the source of time base. It is * used to generate interrupts at regular time intervals. Once HAL_SuspendTick() - * is called, the SysTick interrupt will be disabled and so Tick increment + * is called, the the SysTick interrupt will be disabled and so Tick increment * is suspended. * @note This function is declared as __weak to be overwritten in case of other * implementations in user file. @@ -358,9 +350,9 @@ __weak void HAL_SuspendTick(void) * @brief Resume Tick increment. * @note In the default implementation , SysTick timer is the source of time base. It is * used to generate interrupts at regular time intervals. Once HAL_ResumeTick() - * is called, the SysTick interrupt will be enabled and so Tick increment + * is called, the the SysTick interrupt will be enabled and so Tick increment * is resumed. - * @note This function is declared as __weak to be overwritten in case of other + * @note This function is declared as __weak to be overwritten in case of other * implementations in user file. * @retval None */ @@ -371,8 +363,8 @@ __weak void HAL_ResumeTick(void) } /** - * @brief Returns the HAL revision - * @retval version : 0xXYZR (8bits for each decimal, R for RC) + * @brief This method returns the HAL revision + * @retval version: 0xXYZR (8bits for each decimal, R for RC) */ uint32_t HAL_GetHalVersion(void) { @@ -392,7 +384,7 @@ uint32_t HAL_GetHalVersion(void) */ uint32_t HAL_GetREVID(void) { - return((DBGMCU->IDCODE) >> DBGMCU_IDCODE_REV_ID_Pos); + return((DBGMCU->IDCODE) >> POSITION_VAL(DBGMCU_IDCODE_REV_ID)); } /** @@ -514,18 +506,6 @@ void HAL_DBGMCU_DisableDBGStandbyMode(void) CLEAR_BIT(DBGMCU->CR, DBGMCU_CR_DBG_STANDBY); } -/** - * @brief Return the unique device identifier (UID based on 96 bits) - * @param UID: pointer to 3 words array. - * @retval Device identifier - */ -void HAL_GetUID(uint32_t *UID) -{ - UID[0] = (uint32_t)(READ_REG(*((uint32_t *)UID_BASE))); - UID[1] = (uint32_t)(READ_REG(*((uint32_t *)(UID_BASE + 4U)))); - UID[2] = (uint32_t)(READ_REG(*((uint32_t *)(UID_BASE + 8U)))); -} - /** * @} */ diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal.h index d48fb278a03..31b4e16395d 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal.h +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal.h @@ -2,14 +2,14 @@ ****************************************************************************** * @file stm32f1xx_hal.h * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief This file contains all the functions prototypes for the HAL * module driver. ****************************************************************************** * @attention * - *

© COPYRIGHT(c) 2017 STMicroelectronics

+ *

© COPYRIGHT(c) 2016 STMicroelectronics

* * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: @@ -59,6 +59,7 @@ /* Exported constants --------------------------------------------------------*/ /* Exported macro ------------------------------------------------------------*/ + /** @defgroup HAL_Exported_Macros HAL Exported Macros * @{ */ @@ -261,18 +262,22 @@ */ /* Exported functions --------------------------------------------------------*/ + /** @addtogroup HAL_Exported_Functions * @{ */ + /** @addtogroup HAL_Exported_Functions_Group1 * @{ */ + /* Initialization and de-initialization functions ******************************/ HAL_StatusTypeDef HAL_Init(void); HAL_StatusTypeDef HAL_DeInit(void); -void HAL_MspInit(void); -void HAL_MspDeInit(void); +void HAL_MspInit(void); +void HAL_MspDeInit(void); HAL_StatusTypeDef HAL_InitTick (uint32_t TickPriority); + /** * @} */ @@ -280,49 +285,35 @@ HAL_StatusTypeDef HAL_InitTick (uint32_t TickPriority); /** @addtogroup HAL_Exported_Functions_Group2 * @{ */ + /* Peripheral Control functions ************************************************/ -void HAL_IncTick(void); -void HAL_Delay(__IO uint32_t Delay); -uint32_t HAL_GetTick(void); -void HAL_SuspendTick(void); -void HAL_ResumeTick(void); -uint32_t HAL_GetHalVersion(void); -uint32_t HAL_GetREVID(void); -uint32_t HAL_GetDEVID(void); -void HAL_DBGMCU_EnableDBGSleepMode(void); -void HAL_DBGMCU_DisableDBGSleepMode(void); -void HAL_DBGMCU_EnableDBGStopMode(void); -void HAL_DBGMCU_DisableDBGStopMode(void); -void HAL_DBGMCU_EnableDBGStandbyMode(void); -void HAL_DBGMCU_DisableDBGStandbyMode(void); -void HAL_GetUID(uint32_t *UID); -/** - * @} - */ +void HAL_IncTick(void); +void HAL_Delay(__IO uint32_t Delay); +uint32_t HAL_GetTick(void); +void HAL_SuspendTick(void); +void HAL_ResumeTick(void); +uint32_t HAL_GetHalVersion(void); +uint32_t HAL_GetREVID(void); +uint32_t HAL_GetDEVID(void); +void HAL_DBGMCU_EnableDBGSleepMode(void); +void HAL_DBGMCU_DisableDBGSleepMode(void); +void HAL_DBGMCU_EnableDBGStopMode(void); +void HAL_DBGMCU_DisableDBGStopMode(void); +void HAL_DBGMCU_EnableDBGStandbyMode(void); +void HAL_DBGMCU_DisableDBGStandbyMode(void); /** * @} */ -/* Private types -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/** @defgroup HAL_Private_Variables HAL Private Variables - * @{ - */ -/** - * @} - */ -/* Private constants ---------------------------------------------------------*/ -/** @defgroup HAL_Private_Constants HAL Private Constants - * @{ - */ + /** * @} */ -/* Private macros ------------------------------------------------------------*/ -/* Private functions ---------------------------------------------------------*/ + + /** * @} - */ + */ /** * @} diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_adc.c b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_adc.c index ddc0776f94b..452186190eb 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_adc.c +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_adc.c @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_hal_adc.c * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief This file provides firmware functions to manage the following * functionalities of the Analog to Digital Convertor (ADC) * peripheral: @@ -300,18 +300,18 @@ /* Ex of profile low frequency : Clock source at 0.1 MHz, ADC clock */ /* prescaler 4, sampling time 12.5 ADC clock cycles, resolution 12 bits. */ /* Unit: ms */ - #define ADC_ENABLE_TIMEOUT 2U - #define ADC_DISABLE_TIMEOUT 2U + #define ADC_ENABLE_TIMEOUT ((uint32_t) 2) + #define ADC_DISABLE_TIMEOUT ((uint32_t) 2) /* Delay for ADC stabilization time. */ /* Maximum delay is 1us (refer to device datasheet, parameter tSTAB). */ /* Unit: us */ - #define ADC_STAB_DELAY_US 1U + #define ADC_STAB_DELAY_US ((uint32_t) 1) /* Delay for temperature sensor stabilization time. */ /* Maximum delay is 10us (refer to device datasheet, parameter tSTART). */ /* Unit: us */ - #define ADC_TEMPSENSOR_DELAY_US 10U + #define ADC_TEMPSENSOR_DELAY_US ((uint32_t) 10) /** * @} @@ -374,9 +374,9 @@ HAL_StatusTypeDef HAL_ADC_Init(ADC_HandleTypeDef* hadc) { HAL_StatusTypeDef tmp_hal_status = HAL_OK; - uint32_t tmp_cr1 = 0U; - uint32_t tmp_cr2 = 0U; - uint32_t tmp_sqr1 = 0U; + uint32_t tmp_cr1 = 0; + uint32_t tmp_cr2 = 0; + uint32_t tmp_sqr1 = 0; /* Check ADC handle */ if(hadc == NULL) @@ -924,12 +924,12 @@ HAL_StatusTypeDef HAL_ADC_Stop(ADC_HandleTypeDef* hadc) */ HAL_StatusTypeDef HAL_ADC_PollForConversion(ADC_HandleTypeDef* hadc, uint32_t Timeout) { - uint32_t tickstart = 0U; + uint32_t tickstart = 0; /* Variables for polling in case of scan mode enabled and polling for each */ /* conversion. */ - __IO uint32_t Conversion_Timeout_CPU_cycles = 0U; - uint32_t Conversion_Timeout_CPU_cycles_max = 0U; + __IO uint32_t Conversion_Timeout_CPU_cycles = 0; + uint32_t Conversion_Timeout_CPU_cycles_max = 0; /* Check the parameters */ assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); @@ -974,7 +974,7 @@ HAL_StatusTypeDef HAL_ADC_PollForConversion(ADC_HandleTypeDef* hadc, uint32_t Ti /* Check if timeout is disabled (set to infinite wait) */ if(Timeout != HAL_MAX_DELAY) { - if((Timeout == 0U) || ((HAL_GetTick() - tickstart ) > Timeout)) + if((Timeout == 0) || ((HAL_GetTick() - tickstart ) > Timeout)) { /* Update ADC state machine to timeout */ SET_BIT(hadc->State, HAL_ADC_STATE_TIMEOUT); @@ -1002,7 +1002,7 @@ HAL_StatusTypeDef HAL_ADC_PollForConversion(ADC_HandleTypeDef* hadc, uint32_t Ti /* Check if timeout is disabled (set to infinite wait) */ if(Timeout != HAL_MAX_DELAY) { - if((Timeout == 0U) || ((HAL_GetTick() - tickstart) > Timeout)) + if((Timeout == 0) || ((HAL_GetTick() - tickstart) > Timeout)) { /* Update ADC state machine to timeout */ SET_BIT(hadc->State, HAL_ADC_STATE_TIMEOUT); @@ -1055,7 +1055,7 @@ HAL_StatusTypeDef HAL_ADC_PollForConversion(ADC_HandleTypeDef* hadc, uint32_t Ti */ HAL_StatusTypeDef HAL_ADC_PollForEvent(ADC_HandleTypeDef* hadc, uint32_t EventType, uint32_t Timeout) { - uint32_t tickstart = 0U; + uint32_t tickstart = 0; /* Check the parameters */ assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); @@ -1070,7 +1070,7 @@ HAL_StatusTypeDef HAL_ADC_PollForEvent(ADC_HandleTypeDef* hadc, uint32_t EventTy /* Check if timeout is disabled (set to infinite wait) */ if(Timeout != HAL_MAX_DELAY) { - if((Timeout == 0U) || ((HAL_GetTick() - tickstart ) > Timeout)) + if((Timeout == 0) || ((HAL_GetTick() - tickstart ) > Timeout)) { /* Update ADC state machine to timeout */ SET_BIT(hadc->State, HAL_ADC_STATE_TIMEOUT); @@ -1702,7 +1702,7 @@ __weak void HAL_ADC_ErrorCallback(ADC_HandleTypeDef *hadc) HAL_StatusTypeDef HAL_ADC_ConfigChannel(ADC_HandleTypeDef* hadc, ADC_ChannelConfTypeDef* sConfig) { HAL_StatusTypeDef tmp_hal_status = HAL_OK; - __IO uint32_t wait_loop_index = 0U; + __IO uint32_t wait_loop_index = 0; /* Check the parameters */ assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); @@ -1716,14 +1716,14 @@ HAL_StatusTypeDef HAL_ADC_ConfigChannel(ADC_HandleTypeDef* hadc, ADC_ChannelConf /* Regular sequence configuration */ /* For Rank 1 to 6 */ - if (sConfig->Rank < 7U) + if (sConfig->Rank < 7) { MODIFY_REG(hadc->Instance->SQR3 , ADC_SQR3_RK(ADC_SQR3_SQ1, sConfig->Rank) , ADC_SQR3_RK(sConfig->Channel, sConfig->Rank) ); } /* For Rank 7 to 12 */ - else if (sConfig->Rank < 13U) + else if (sConfig->Rank < 13) { MODIFY_REG(hadc->Instance->SQR2 , ADC_SQR2_RK(ADC_SQR2_SQ7, sConfig->Rank) , @@ -1771,8 +1771,8 @@ HAL_StatusTypeDef HAL_ADC_ConfigChannel(ADC_HandleTypeDef* hadc, ADC_ChannelConf { /* Delay for temperature sensor stabilization time */ /* Compute number of CPU cycles to wait for */ - wait_loop_index = (ADC_TEMPSENSOR_DELAY_US * (SystemCoreClock / 1000000U)); - while(wait_loop_index != 0U) + wait_loop_index = (ADC_TEMPSENSOR_DELAY_US * (SystemCoreClock / 1000000)); + while(wait_loop_index != 0) { wait_loop_index--; } @@ -1933,8 +1933,8 @@ uint32_t HAL_ADC_GetError(ADC_HandleTypeDef *hadc) */ HAL_StatusTypeDef ADC_Enable(ADC_HandleTypeDef* hadc) { - uint32_t tickstart = 0U; - __IO uint32_t wait_loop_index = 0U; + uint32_t tickstart = 0; + __IO uint32_t wait_loop_index = 0; /* ADC enable and wait for ADC ready (in case of ADC is disabled or */ /* enabling phase not yet completed: flag ADC ready not yet set). */ @@ -1947,8 +1947,8 @@ HAL_StatusTypeDef ADC_Enable(ADC_HandleTypeDef* hadc) /* Delay for ADC stabilization time */ /* Compute number of CPU cycles to wait for */ - wait_loop_index = (ADC_STAB_DELAY_US * (SystemCoreClock / 1000000U)); - while(wait_loop_index != 0U) + wait_loop_index = (ADC_STAB_DELAY_US * (SystemCoreClock / 1000000)); + while(wait_loop_index != 0) { wait_loop_index--; } @@ -1988,7 +1988,7 @@ HAL_StatusTypeDef ADC_Enable(ADC_HandleTypeDef* hadc) */ HAL_StatusTypeDef ADC_ConversionStop_Disable(ADC_HandleTypeDef* hadc) { - uint32_t tickstart = 0U; + uint32_t tickstart = 0; /* Verification if ADC is not already disabled */ if (ADC_IS_ENABLE(hadc) != RESET) diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_adc.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_adc.h index 4d2ed413587..0b88d548357 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_adc.h +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_adc.h @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_hal_adc.h * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief Header file containing functions prototypes of ADC HAL library. ****************************************************************************** * @attention @@ -154,36 +154,36 @@ typedef struct * @brief HAL ADC state machine: ADC states definition (bitfields) */ /* States of ADC global scope */ -#define HAL_ADC_STATE_RESET 0x00000000U /*!< ADC not yet initialized or disabled */ -#define HAL_ADC_STATE_READY 0x00000001U /*!< ADC peripheral ready for use */ -#define HAL_ADC_STATE_BUSY_INTERNAL 0x00000002U /*!< ADC is busy to internal process (initialization, calibration) */ -#define HAL_ADC_STATE_TIMEOUT 0x00000004U /*!< TimeOut occurrence */ +#define HAL_ADC_STATE_RESET ((uint32_t)0x00000000) /*!< ADC not yet initialized or disabled */ +#define HAL_ADC_STATE_READY ((uint32_t)0x00000001) /*!< ADC peripheral ready for use */ +#define HAL_ADC_STATE_BUSY_INTERNAL ((uint32_t)0x00000002) /*!< ADC is busy to internal process (initialization, calibration) */ +#define HAL_ADC_STATE_TIMEOUT ((uint32_t)0x00000004) /*!< TimeOut occurrence */ /* States of ADC errors */ -#define HAL_ADC_STATE_ERROR_INTERNAL 0x00000010U /*!< Internal error occurrence */ -#define HAL_ADC_STATE_ERROR_CONFIG 0x00000020U /*!< Configuration error occurrence */ -#define HAL_ADC_STATE_ERROR_DMA 0x00000040U /*!< DMA error occurrence */ +#define HAL_ADC_STATE_ERROR_INTERNAL ((uint32_t)0x00000010) /*!< Internal error occurrence */ +#define HAL_ADC_STATE_ERROR_CONFIG ((uint32_t)0x00000020) /*!< Configuration error occurrence */ +#define HAL_ADC_STATE_ERROR_DMA ((uint32_t)0x00000040) /*!< DMA error occurrence */ /* States of ADC group regular */ -#define HAL_ADC_STATE_REG_BUSY 0x00000100U /*!< A conversion on group regular is ongoing or can occur (either by continuous mode, - external trigger, low power auto power-on, multimode ADC master control) */ -#define HAL_ADC_STATE_REG_EOC 0x00000200U /*!< Conversion data available on group regular */ -#define HAL_ADC_STATE_REG_OVR 0x00000400U /*!< Not available on STM32F1 device: Overrun occurrence */ -#define HAL_ADC_STATE_REG_EOSMP 0x00000800U /*!< Not available on STM32F1 device: End Of Sampling flag raised */ +#define HAL_ADC_STATE_REG_BUSY ((uint32_t)0x00000100) /*!< A conversion on group regular is ongoing or can occur (either by continuous mode, + external trigger, low power auto power-on, multimode ADC master control) */ +#define HAL_ADC_STATE_REG_EOC ((uint32_t)0x00000200) /*!< Conversion data available on group regular */ +#define HAL_ADC_STATE_REG_OVR ((uint32_t)0x00000400) /*!< Not available on STM32F1 device: Overrun occurrence */ +#define HAL_ADC_STATE_REG_EOSMP ((uint32_t)0x00000800) /*!< Not available on STM32F1 device: End Of Sampling flag raised */ /* States of ADC group injected */ -#define HAL_ADC_STATE_INJ_BUSY 0x00001000U /*!< A conversion on group injected is ongoing or can occur (either by auto-injection mode, - external trigger, low power auto power-on, multimode ADC master control) */ -#define HAL_ADC_STATE_INJ_EOC 0x00002000U /*!< Conversion data available on group injected */ -#define HAL_ADC_STATE_INJ_JQOVF 0x00004000U /*!< Not available on STM32F1 device: Injected queue overflow occurrence */ +#define HAL_ADC_STATE_INJ_BUSY ((uint32_t)0x00001000) /*!< A conversion on group injected is ongoing or can occur (either by auto-injection mode, + external trigger, low power auto power-on, multimode ADC master control) */ +#define HAL_ADC_STATE_INJ_EOC ((uint32_t)0x00002000) /*!< Conversion data available on group injected */ +#define HAL_ADC_STATE_INJ_JQOVF ((uint32_t)0x00004000) /*!< Not available on STM32F1 device: Injected queue overflow occurrence */ /* States of ADC analog watchdogs */ -#define HAL_ADC_STATE_AWD1 0x00010000U /*!< Out-of-window occurrence of analog watchdog 1 */ -#define HAL_ADC_STATE_AWD2 0x00020000U /*!< Not available on STM32F1 device: Out-of-window occurrence of analog watchdog 2 */ -#define HAL_ADC_STATE_AWD3 0x00040000U /*!< Not available on STM32F1 device: Out-of-window occurrence of analog watchdog 3 */ +#define HAL_ADC_STATE_AWD1 ((uint32_t)0x00010000) /*!< Out-of-window occurrence of analog watchdog 1 */ +#define HAL_ADC_STATE_AWD2 ((uint32_t)0x00020000) /*!< Not available on STM32F1 device: Out-of-window occurrence of analog watchdog 2 */ +#define HAL_ADC_STATE_AWD3 ((uint32_t)0x00040000) /*!< Not available on STM32F1 device: Out-of-window occurrence of analog watchdog 3 */ /* States of ADC multi-mode */ -#define HAL_ADC_STATE_MULTIMODE_SLAVE 0x00100000U /*!< ADC in multimode slave state, controlled by another ADC master ( */ +#define HAL_ADC_STATE_MULTIMODE_SLAVE ((uint32_t)0x00100000) /*!< ADC in multimode slave state, controlled by another ADC master ( */ /** @@ -218,11 +218,11 @@ typedef struct /** @defgroup ADC_Error_Code ADC Error Code * @{ */ -#define HAL_ADC_ERROR_NONE 0x00U /*!< No error */ -#define HAL_ADC_ERROR_INTERNAL 0x01U /*!< ADC IP internal error: if problem of clocking, - enable/disable, erroneous state */ -#define HAL_ADC_ERROR_OVR 0x02U /*!< Overrun error */ -#define HAL_ADC_ERROR_DMA 0x04U /*!< DMA transfer error */ +#define HAL_ADC_ERROR_NONE ((uint32_t)0x00) /*!< No error */ +#define HAL_ADC_ERROR_INTERNAL ((uint32_t)0x01) /*!< ADC IP internal error: if problem of clocking, + enable/disable, erroneous state */ +#define HAL_ADC_ERROR_OVR ((uint32_t)0x02) /*!< Overrun error */ +#define HAL_ADC_ERROR_DMA ((uint32_t)0x04) /*!< DMA transfer error */ /** * @} @@ -232,7 +232,7 @@ typedef struct /** @defgroup ADC_Data_align ADC data alignment * @{ */ -#define ADC_DATAALIGN_RIGHT 0x00000000U +#define ADC_DATAALIGN_RIGHT ((uint32_t)0x00000000) #define ADC_DATAALIGN_LEFT ((uint32_t)ADC_CR2_ALIGN) /** * @} @@ -244,7 +244,7 @@ typedef struct /* Note: Scan mode values are not among binary choices ENABLE/DISABLE for */ /* compatibility with other STM32 devices having a sequencer with */ /* additional options. */ -#define ADC_SCAN_DISABLE 0x00000000U +#define ADC_SCAN_DISABLE ((uint32_t)0x00000000) #define ADC_SCAN_ENABLE ((uint32_t)ADC_CR1_SCAN) /** * @} @@ -253,7 +253,7 @@ typedef struct /** @defgroup ADC_External_trigger_edge_Regular ADC external trigger enable for regular group * @{ */ -#define ADC_EXTERNALTRIGCONVEDGE_NONE 0x00000000U +#define ADC_EXTERNALTRIGCONVEDGE_NONE ((uint32_t)0x00000000) #define ADC_EXTERNALTRIGCONVEDGE_RISING ((uint32_t)ADC_CR2_EXTTRIG) /** * @} @@ -264,7 +264,7 @@ typedef struct */ /* Note: Depending on devices, some channels may not be available on package */ /* pins. Refer to device datasheet for channels availability. */ -#define ADC_CHANNEL_0 0x00000000U +#define ADC_CHANNEL_0 ((uint32_t)0x00000000) #define ADC_CHANNEL_1 ((uint32_t)( ADC_SQR3_SQ1_0)) #define ADC_CHANNEL_2 ((uint32_t)( ADC_SQR3_SQ1_1 )) #define ADC_CHANNEL_3 ((uint32_t)( ADC_SQR3_SQ1_1 | ADC_SQR3_SQ1_0)) @@ -292,7 +292,7 @@ typedef struct /** @defgroup ADC_sampling_times ADC sampling times * @{ */ -#define ADC_SAMPLETIME_1CYCLE_5 0x00000000U /*!< Sampling time 1.5 ADC clock cycle */ +#define ADC_SAMPLETIME_1CYCLE_5 ((uint32_t)0x00000000) /*!< Sampling time 1.5 ADC clock cycle */ #define ADC_SAMPLETIME_7CYCLES_5 ((uint32_t)( ADC_SMPR2_SMP0_0)) /*!< Sampling time 7.5 ADC clock cycles */ #define ADC_SAMPLETIME_13CYCLES_5 ((uint32_t)( ADC_SMPR2_SMP0_1 )) /*!< Sampling time 13.5 ADC clock cycles */ #define ADC_SAMPLETIME_28CYCLES_5 ((uint32_t)( ADC_SMPR2_SMP0_1 | ADC_SMPR2_SMP0_0)) /*!< Sampling time 28.5 ADC clock cycles */ @@ -307,22 +307,22 @@ typedef struct /** @defgroup ADC_regular_rank ADC rank into regular group * @{ */ -#define ADC_REGULAR_RANK_1 0x00000001U -#define ADC_REGULAR_RANK_2 0x00000002U -#define ADC_REGULAR_RANK_3 0x00000003U -#define ADC_REGULAR_RANK_4 0x00000004U -#define ADC_REGULAR_RANK_5 0x00000005U -#define ADC_REGULAR_RANK_6 0x00000006U -#define ADC_REGULAR_RANK_7 0x00000007U -#define ADC_REGULAR_RANK_8 0x00000008U -#define ADC_REGULAR_RANK_9 0x00000009U -#define ADC_REGULAR_RANK_10 0x0000000AU -#define ADC_REGULAR_RANK_11 0x0000000BU -#define ADC_REGULAR_RANK_12 0x0000000CU -#define ADC_REGULAR_RANK_13 0x0000000DU -#define ADC_REGULAR_RANK_14 0x0000000EU -#define ADC_REGULAR_RANK_15 0x0000000FU -#define ADC_REGULAR_RANK_16 0x00000010U +#define ADC_REGULAR_RANK_1 ((uint32_t)0x00000001) +#define ADC_REGULAR_RANK_2 ((uint32_t)0x00000002) +#define ADC_REGULAR_RANK_3 ((uint32_t)0x00000003) +#define ADC_REGULAR_RANK_4 ((uint32_t)0x00000004) +#define ADC_REGULAR_RANK_5 ((uint32_t)0x00000005) +#define ADC_REGULAR_RANK_6 ((uint32_t)0x00000006) +#define ADC_REGULAR_RANK_7 ((uint32_t)0x00000007) +#define ADC_REGULAR_RANK_8 ((uint32_t)0x00000008) +#define ADC_REGULAR_RANK_9 ((uint32_t)0x00000009) +#define ADC_REGULAR_RANK_10 ((uint32_t)0x0000000A) +#define ADC_REGULAR_RANK_11 ((uint32_t)0x0000000B) +#define ADC_REGULAR_RANK_12 ((uint32_t)0x0000000C) +#define ADC_REGULAR_RANK_13 ((uint32_t)0x0000000D) +#define ADC_REGULAR_RANK_14 ((uint32_t)0x0000000E) +#define ADC_REGULAR_RANK_15 ((uint32_t)0x0000000F) +#define ADC_REGULAR_RANK_16 ((uint32_t)0x00000010) /** * @} */ @@ -330,12 +330,12 @@ typedef struct /** @defgroup ADC_analog_watchdog_mode ADC analog watchdog mode * @{ */ -#define ADC_ANALOGWATCHDOG_NONE 0x00000000U +#define ADC_ANALOGWATCHDOG_NONE ((uint32_t)0x00000000) #define ADC_ANALOGWATCHDOG_SINGLE_REG ((uint32_t)(ADC_CR1_AWDSGL | ADC_CR1_AWDEN)) #define ADC_ANALOGWATCHDOG_SINGLE_INJEC ((uint32_t)(ADC_CR1_AWDSGL | ADC_CR1_JAWDEN)) #define ADC_ANALOGWATCHDOG_SINGLE_REGINJEC ((uint32_t)(ADC_CR1_AWDSGL | ADC_CR1_AWDEN | ADC_CR1_JAWDEN)) -#define ADC_ANALOGWATCHDOG_ALL_REG ((uint32_t)ADC_CR1_AWDEN) -#define ADC_ANALOGWATCHDOG_ALL_INJEC ((uint32_t)ADC_CR1_JAWDEN) +#define ADC_ANALOGWATCHDOG_ALL_REG ((uint32_t) ADC_CR1_AWDEN) +#define ADC_ANALOGWATCHDOG_ALL_INJEC ((uint32_t) ADC_CR1_JAWDEN) #define ADC_ANALOGWATCHDOG_ALL_REGINJEC ((uint32_t)(ADC_CR1_AWDEN | ADC_CR1_JAWDEN)) /** * @} @@ -400,14 +400,14 @@ typedef struct /* ADC conversion cycles (unit: ADC clock cycles) */ /* (selected sampling time + conversion time of 12.5 ADC clock cycles, with */ /* resolution 12 bits) */ -#define ADC_CONVERSIONCLOCKCYCLES_SAMPLETIME_1CYCLE5 14U -#define ADC_CONVERSIONCLOCKCYCLES_SAMPLETIME_7CYCLES5 20U -#define ADC_CONVERSIONCLOCKCYCLES_SAMPLETIME_13CYCLES5 26U -#define ADC_CONVERSIONCLOCKCYCLES_SAMPLETIME_28CYCLES5 41U -#define ADC_CONVERSIONCLOCKCYCLES_SAMPLETIME_41CYCLES5 54U -#define ADC_CONVERSIONCLOCKCYCLES_SAMPLETIME_55CYCLES5 68U -#define ADC_CONVERSIONCLOCKCYCLES_SAMPLETIME_71CYCLES5 84U -#define ADC_CONVERSIONCLOCKCYCLES_SAMPLETIME_239CYCLES5 252U +#define ADC_CONVERSIONCLOCKCYCLES_SAMPLETIME_1CYCLE5 ((uint32_t) 14) +#define ADC_CONVERSIONCLOCKCYCLES_SAMPLETIME_7CYCLES5 ((uint32_t) 20) +#define ADC_CONVERSIONCLOCKCYCLES_SAMPLETIME_13CYCLES5 ((uint32_t) 26) +#define ADC_CONVERSIONCLOCKCYCLES_SAMPLETIME_28CYCLES5 ((uint32_t) 41) +#define ADC_CONVERSIONCLOCKCYCLES_SAMPLETIME_41CYCLES5 ((uint32_t) 54) +#define ADC_CONVERSIONCLOCKCYCLES_SAMPLETIME_55CYCLES5 ((uint32_t) 68) +#define ADC_CONVERSIONCLOCKCYCLES_SAMPLETIME_71CYCLES5 ((uint32_t) 84) +#define ADC_CONVERSIONCLOCKCYCLES_SAMPLETIME_239CYCLES5 ((uint32_t)252) /** * @} */ @@ -439,7 +439,7 @@ typedef struct (ADC_SMPR1_SMP17_0 | ADC_SMPR1_SMP16_0 | ADC_SMPR1_SMP15_0 | ADC_SMPR1_SMP14_0 | \ ADC_SMPR1_SMP13_0 | ADC_SMPR1_SMP12_0 | ADC_SMPR1_SMP11_0 | ADC_SMPR1_SMP10_0 ) -#define ADC_SAMPLETIME_1CYCLE5_SMPR2ALLCHANNELS 0x00000000U +#define ADC_SAMPLETIME_1CYCLE5_SMPR2ALLCHANNELS ((uint32_t)0x00000000) #define ADC_SAMPLETIME_7CYCLES5_SMPR2ALLCHANNELS (ADC_SAMPLETIME_ALLCHANNELS_SMPR2BIT0) #define ADC_SAMPLETIME_13CYCLES5_SMPR2ALLCHANNELS (ADC_SAMPLETIME_ALLCHANNELS_SMPR2BIT1) #define ADC_SAMPLETIME_28CYCLES5_SMPR2ALLCHANNELS (ADC_SAMPLETIME_ALLCHANNELS_SMPR2BIT1 | ADC_SAMPLETIME_ALLCHANNELS_SMPR2BIT0) @@ -448,7 +448,7 @@ typedef struct #define ADC_SAMPLETIME_71CYCLES5_SMPR2ALLCHANNELS (ADC_SAMPLETIME_ALLCHANNELS_SMPR2BIT2 | ADC_SAMPLETIME_ALLCHANNELS_SMPR2BIT1) #define ADC_SAMPLETIME_239CYCLES5_SMPR2ALLCHANNELS (ADC_SAMPLETIME_ALLCHANNELS_SMPR2BIT2 | ADC_SAMPLETIME_ALLCHANNELS_SMPR2BIT1 | ADC_SAMPLETIME_ALLCHANNELS_SMPR2BIT0) -#define ADC_SAMPLETIME_1CYCLE5_SMPR1ALLCHANNELS 0x00000000U +#define ADC_SAMPLETIME_1CYCLE5_SMPR1ALLCHANNELS ((uint32_t)0x00000000) #define ADC_SAMPLETIME_7CYCLES5_SMPR1ALLCHANNELS (ADC_SAMPLETIME_ALLCHANNELS_SMPR1BIT0) #define ADC_SAMPLETIME_13CYCLES5_SMPR1ALLCHANNELS (ADC_SAMPLETIME_ALLCHANNELS_SMPR1BIT1) #define ADC_SAMPLETIME_28CYCLES5_SMPR1ALLCHANNELS (ADC_SAMPLETIME_ALLCHANNELS_SMPR1BIT1 | ADC_SAMPLETIME_ALLCHANNELS_SMPR1BIT0) @@ -629,7 +629,7 @@ typedef struct * @retval None */ #define ADC_SQR1_L_SHIFT(_NbrOfConversion_) \ - (((_NbrOfConversion_) - (uint8_t)1) << ADC_SQR1_L_Pos) + (((_NbrOfConversion_) - (uint8_t)1) << POSITION_VAL(ADC_SQR1_L)) /** * @brief Set the ADC's sample time for channel numbers between 10 and 18. @@ -638,7 +638,7 @@ typedef struct * @retval None */ #define ADC_SMPR1(_SAMPLETIME_, _CHANNELNB_) \ - ((_SAMPLETIME_) << (ADC_SMPR1_SMP11_Pos * ((_CHANNELNB_) - 10))) + ((_SAMPLETIME_) << (POSITION_VAL(ADC_SMPR1_SMP11) * ((_CHANNELNB_) - 10))) /** * @brief Set the ADC's sample time for channel numbers between 0 and 9. @@ -647,7 +647,7 @@ typedef struct * @retval None */ #define ADC_SMPR2(_SAMPLETIME_, _CHANNELNB_) \ - ((_SAMPLETIME_) << (ADC_SMPR2_SMP1_Pos * (_CHANNELNB_))) + ((_SAMPLETIME_) << (POSITION_VAL(ADC_SMPR2_SMP1) * (_CHANNELNB_))) /** * @brief Set the selected regular channel rank for rank between 1 and 6. @@ -656,7 +656,7 @@ typedef struct * @retval None */ #define ADC_SQR3_RK(_CHANNELNB_, _RANKNB_) \ - ((_CHANNELNB_) << (ADC_SQR3_SQ2_Pos * ((_RANKNB_) - 1))) + ((_CHANNELNB_) << (POSITION_VAL(ADC_SQR3_SQ2) * ((_RANKNB_) - 1))) /** * @brief Set the selected regular channel rank for rank between 7 and 12. @@ -665,7 +665,7 @@ typedef struct * @retval None */ #define ADC_SQR2_RK(_CHANNELNB_, _RANKNB_) \ - ((_CHANNELNB_) << (ADC_SQR2_SQ8_Pos * ((_RANKNB_) - 7))) + ((_CHANNELNB_) << (POSITION_VAL(ADC_SQR2_SQ8) * ((_RANKNB_) - 7))) /** * @brief Set the selected regular channel rank for rank between 13 and 16. @@ -674,7 +674,7 @@ typedef struct * @retval None */ #define ADC_SQR1_RK(_CHANNELNB_, _RANKNB_) \ - ((_CHANNELNB_) << (ADC_SQR1_SQ14_Pos * ((_RANKNB_) - 13))) + ((_CHANNELNB_) << (POSITION_VAL(ADC_SQR1_SQ14) * ((_RANKNB_) - 13))) /** * @brief Set the injected sequence length. @@ -682,7 +682,7 @@ typedef struct * @retval None */ #define ADC_JSQR_JL_SHIFT(_JSQR_JL_) \ - (((_JSQR_JL_) -1) << ADC_JSQR_JL_Pos) + (((_JSQR_JL_) -1) << POSITION_VAL(ADC_JSQR_JL)) /** * @brief Set the selected injected channel rank @@ -695,7 +695,7 @@ typedef struct * @retval None */ #define ADC_JSQR_RK_JL(_CHANNELNB_, _RANKNB_, _JSQR_JL_) \ - ((_CHANNELNB_) << (ADC_JSQR_JSQ2_Pos * ((4 - ((_JSQR_JL_) - (_RANKNB_))) - 1))) + ((_CHANNELNB_) << (POSITION_VAL(ADC_JSQR_JSQ2) * ((4 - ((_JSQR_JL_) - (_RANKNB_))) - 1))) /** * @brief Enable ADC continuous conversion mode. @@ -703,7 +703,7 @@ typedef struct * @retval None */ #define ADC_CR2_CONTINUOUS(_CONTINUOUS_MODE_) \ - ((_CONTINUOUS_MODE_) << ADC_CR2_CONT_Pos) + ((_CONTINUOUS_MODE_) << POSITION_VAL(ADC_CR2_CONT)) /** * @brief Configures the number of discontinuous conversions for the regular group channels. @@ -711,7 +711,7 @@ typedef struct * @retval None */ #define ADC_CR1_DISCONTINUOUS_NUM(_NBR_DISCONTINUOUS_CONV_) \ - (((_NBR_DISCONTINUOUS_CONV_) - 1) << ADC_CR1_DISCNUM_Pos) + (((_NBR_DISCONTINUOUS_CONV_) - 1) << POSITION_VAL(ADC_CR1_DISCNUM)) /** * @brief Enable ADC scan mode to convert multiple ranks with sequencer. @@ -825,7 +825,7 @@ typedef struct * For a unique ADC resolution: 12 bits * @{ */ -#define IS_ADC_RANGE(ADC_VALUE) ((ADC_VALUE) <= 0x0FFFU) +#define IS_ADC_RANGE(ADC_VALUE) ((ADC_VALUE) <= ((uint32_t)0x0FFF)) /** * @} */ @@ -833,7 +833,7 @@ typedef struct /** @defgroup ADC_regular_nb_conv_verification ADC regular nb conv verification * @{ */ -#define IS_ADC_REGULAR_NB_CONV(LENGTH) (((LENGTH) >= 1U) && ((LENGTH) <= 16U)) +#define IS_ADC_REGULAR_NB_CONV(LENGTH) (((LENGTH) >= ((uint32_t)1)) && ((LENGTH) <= ((uint32_t)16))) /** * @} */ @@ -841,7 +841,7 @@ typedef struct /** @defgroup ADC_regular_discontinuous_mode_number_verification ADC regular discontinuous mode number verification * @{ */ -#define IS_ADC_REGULAR_DISCONT_NUMBER(NUMBER) (((NUMBER) >= 1U) && ((NUMBER) <= 8U)) +#define IS_ADC_REGULAR_DISCONT_NUMBER(NUMBER) (((NUMBER) >= ((uint32_t)1)) && ((NUMBER) <= ((uint32_t)8))) /** * @} */ diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_adc_ex.c b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_adc_ex.c index df0cacf3fa8..b1c050f157e 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_adc_ex.c +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_adc_ex.c @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_hal_adc_ex.c * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief This file provides firmware functions to manage the following * functionalities of the Analog to Digital Convertor (ADC) * peripheral: @@ -77,7 +77,7 @@ /* Hardware prerequisite before starting a calibration: the ADC must have */ /* been in power-on state for at least two ADC clock cycles. */ /* Unit: ADC clock cycles */ - #define ADC_PRECALIBRATION_DELAY_ADCCLOCKCYCLES 2U + #define ADC_PRECALIBRATION_DELAY_ADCCLOCKCYCLES ((uint32_t) 2) /* Timeout value for ADC calibration */ /* Value defined to be higher than worst cases: low clocks freq, */ @@ -85,12 +85,12 @@ /* Ex of profile low frequency : Clock source at 0.1 MHz, ADC clock */ /* prescaler 4, sampling time 12.5 ADC clock cycles, resolution 12 bits. */ /* Unit: ms */ - #define ADC_CALIBRATION_TIMEOUT 10U + #define ADC_CALIBRATION_TIMEOUT ((uint32_t) 10) /* Delay for temperature sensor stabilization time. */ /* Maximum delay is 10us (refer to device datasheet, parameter tSTART). */ /* Unit: us */ - #define ADC_TEMPSENSOR_DELAY_US 10U + #define ADC_TEMPSENSOR_DELAY_US ((uint32_t) 10) /** * @} @@ -145,7 +145,7 @@ HAL_StatusTypeDef HAL_ADCEx_Calibration_Start(ADC_HandleTypeDef* hadc) { HAL_StatusTypeDef tmp_hal_status = HAL_OK; uint32_t tickstart; - __IO uint32_t wait_loop_index = 0U; + __IO uint32_t wait_loop_index = 0; /* Check the parameters */ assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); @@ -175,7 +175,7 @@ HAL_StatusTypeDef HAL_ADCEx_Calibration_Start(ADC_HandleTypeDef* hadc) / HAL_RCCEx_GetPeriphCLKFreq(RCC_PERIPHCLK_ADC)) * ADC_PRECALIBRATION_DELAY_ADCCLOCKCYCLES ); - while(wait_loop_index != 0U) + while(wait_loop_index != 0) { wait_loop_index--; } @@ -405,8 +405,8 @@ HAL_StatusTypeDef HAL_ADCEx_InjectedPollForConversion(ADC_HandleTypeDef* hadc, u /* Variables for polling in case of scan mode enabled and polling for each */ /* conversion. */ - __IO uint32_t Conversion_Timeout_CPU_cycles = 0U; - uint32_t Conversion_Timeout_CPU_cycles_max = 0U; + __IO uint32_t Conversion_Timeout_CPU_cycles = 0; + uint32_t Conversion_Timeout_CPU_cycles_max = 0; /* Check the parameters */ assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); @@ -438,7 +438,7 @@ HAL_StatusTypeDef HAL_ADCEx_InjectedPollForConversion(ADC_HandleTypeDef* hadc, u /* Check if timeout is disabled (set to infinite wait) */ if(Timeout != HAL_MAX_DELAY) { - if((Timeout == 0U) || ((HAL_GetTick() - tickstart ) > Timeout)) + if((Timeout == 0) || ((HAL_GetTick() - tickstart ) > Timeout)) { /* Update ADC state machine to timeout */ SET_BIT(hadc->State, HAL_ADC_STATE_TIMEOUT); @@ -666,7 +666,7 @@ HAL_StatusTypeDef HAL_ADCEx_InjectedStop_IT(ADC_HandleTypeDef* hadc) return tmp_hal_status; } -#if defined (STM32F103x6) || defined (STM32F103xB) || defined (STM32F105xC) || defined (STM32F107xC) || defined (STM32F103xE) || defined (STM32F103xG) +#if defined (STM32F101xG) || defined (STM32F103x6) || defined (STM32F103xB) || defined (STM32F105xC) || defined (STM32F107xC) || defined (STM32F103xE) || defined (STM32F103xG) /** * @brief Enables ADC, starts conversion of regular group and transfers result * through DMA. @@ -704,7 +704,8 @@ HAL_StatusTypeDef HAL_ADCEx_MultiModeStart_DMA(ADC_HandleTypeDef* hadc, uint32_t /* conversion trigger ADC_SOFTWARE_START. */ /* Note: External trigger of ADC slave must be enabled, it is already done */ /* into function "HAL_ADC_Init()". */ - if(!ADC_IS_SOFTWARE_START_REGULAR(&tmphadcSlave)) + if ((tmphadcSlave.Instance == NULL) || + (! ADC_IS_SOFTWARE_START_REGULAR(&tmphadcSlave)) ) { /* Update ADC state machine to error */ SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG); @@ -828,26 +829,39 @@ HAL_StatusTypeDef HAL_ADCEx_MultiModeStop_DMA(ADC_HandleTypeDef* hadc) tmp_hal_status = ADC_ConversionStop_Disable(hadc); /* Check if ADC is effectively disabled */ - if(tmp_hal_status == HAL_OK) + if (tmp_hal_status == HAL_OK) { /* Set a temporary handle of the ADC slave associated to the ADC master */ ADC_MULTI_SLAVE(hadc, &tmphadcSlave); - /* Disable ADC slave peripheral */ - tmp_hal_status = ADC_ConversionStop_Disable(&tmphadcSlave); - - /* Check if ADC is effectively disabled */ - if(tmp_hal_status != HAL_OK) + if (tmphadcSlave.Instance == NULL) { /* Update ADC state machine to error */ - SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL); - + SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_DMA); + /* Process unlocked */ __HAL_UNLOCK(hadc); - + return HAL_ERROR; } - + else + { + /* Disable ADC slave peripheral */ + tmp_hal_status = ADC_ConversionStop_Disable(&tmphadcSlave); + + /* Check if ADC is effectively disabled */ + if (tmp_hal_status != HAL_OK) + { + /* Update ADC state machine to error */ + SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL); + + /* Process unlocked */ + __HAL_UNLOCK(hadc); + + return HAL_ERROR; + } + } + /* Disable ADC DMA mode */ CLEAR_BIT(hadc->Instance->CR2, ADC_CR2_DMA); @@ -857,11 +871,21 @@ HAL_StatusTypeDef HAL_ADCEx_MultiModeStop_DMA(ADC_HandleTypeDef* hadc) /* Disable the DMA channel (in case of DMA in circular mode or stop while */ /* while DMA transfer is on going) */ tmp_hal_status = HAL_DMA_Abort(hadc->DMA_Handle); - - /* Change ADC state (ADC master) */ - ADC_STATE_CLR_SET(hadc->State, - HAL_ADC_STATE_REG_BUSY | HAL_ADC_STATE_INJ_BUSY, - HAL_ADC_STATE_READY); + + + /* Check if DMA channel effectively disabled */ + if (tmp_hal_status == HAL_OK) + { + /* Change ADC state (ADC master) */ + ADC_STATE_CLR_SET(hadc->State, + HAL_ADC_STATE_REG_BUSY | HAL_ADC_STATE_INJ_BUSY, + HAL_ADC_STATE_READY); + } + else + { + /* Update ADC state machine to error */ + SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_DMA); + } } /* Process unlocked */ @@ -870,7 +894,7 @@ HAL_StatusTypeDef HAL_ADCEx_MultiModeStop_DMA(ADC_HandleTypeDef* hadc) /* Return function status */ return tmp_hal_status; } -#endif /* defined STM32F103x6 || defined STM32F103xB || defined STM32F105xC || defined STM32F107xC || defined STM32F103xE || defined STM32F103xG */ +#endif /* STM32F101xG || defined STM32F103x6 || defined STM32F103xB || defined STM32F105xC || defined STM32F107xC || defined STM32F103xE || defined STM32F103xG */ /** * @brief Get ADC injected group conversion result. @@ -902,7 +926,7 @@ HAL_StatusTypeDef HAL_ADCEx_MultiModeStop_DMA(ADC_HandleTypeDef* hadc) */ uint32_t HAL_ADCEx_InjectedGetValue(ADC_HandleTypeDef* hadc, uint32_t InjectedRank) { - uint32_t tmp_jdr = 0U; + uint32_t tmp_jdr = 0; /* Check the parameters */ assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); @@ -930,7 +954,7 @@ uint32_t HAL_ADCEx_InjectedGetValue(ADC_HandleTypeDef* hadc, uint32_t InjectedRa return tmp_jdr; } -#if defined (STM32F103x6) || defined (STM32F103xB) || defined (STM32F105xC) || defined (STM32F107xC) || defined (STM32F103xE) || defined (STM32F103xG) +#if defined (STM32F101xG) || defined (STM32F103x6) || defined (STM32F103xB) || defined (STM32F105xC) || defined (STM32F107xC) || defined (STM32F103xE) || defined (STM32F103xG) /** * @brief Returns the last ADC Master&Slave regular conversions results data * in the selected multi mode. @@ -939,7 +963,7 @@ uint32_t HAL_ADCEx_InjectedGetValue(ADC_HandleTypeDef* hadc, uint32_t InjectedRa */ uint32_t HAL_ADCEx_MultiModeGetValue(ADC_HandleTypeDef* hadc) { - uint32_t tmpDR = 0U; + uint32_t tmpDR = 0; /* Check the parameters */ assert_param(IS_ADC_MULTIMODE_MASTER_INSTANCE(hadc->Instance)); @@ -956,13 +980,13 @@ uint32_t HAL_ADCEx_MultiModeGetValue(ADC_HandleTypeDef* hadc) if (HAL_IS_BIT_CLR(ADC1->CR2, ADC_CR2_DMA)) { - tmpDR |= (ADC2->DR << 16U); + tmpDR |= (ADC2->DR << 16); } /* Return ADC converted value */ return tmpDR; } -#endif /* defined STM32F103x6 || defined STM32F103xB || defined STM32F105xC || defined STM32F107xC || defined STM32F103xE || defined STM32F103xG */ +#endif /* STM32F101xG || defined STM32F103x6 || defined STM32F103xB || defined STM32F105xC || defined STM32F107xC || defined STM32F103xE || defined STM32F103xG */ /** * @brief Injected conversion complete callback in non blocking mode @@ -1014,7 +1038,7 @@ __weak void HAL_ADCEx_InjectedConvCpltCallback(ADC_HandleTypeDef* hadc) HAL_StatusTypeDef HAL_ADCEx_InjectedConfigChannel(ADC_HandleTypeDef* hadc, ADC_InjectionConfTypeDef* sConfigInjected) { HAL_StatusTypeDef tmp_hal_status = HAL_OK; - __IO uint32_t wait_loop_index = 0U; + __IO uint32_t wait_loop_index = 0; /* Check the parameters */ assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); @@ -1056,7 +1080,7 @@ HAL_StatusTypeDef HAL_ADCEx_InjectedConfigChannel(ADC_HandleTypeDef* hadc, ADC_I ADC_JSQR_JSQ1 , ADC_JSQR_RK_JL(sConfigInjected->InjectedChannel, ADC_INJECTED_RANK_1, - 0x01U)); + 0x01) ); } /* If another injected rank than rank1 was intended to be set, and could */ /* not due to ScanConvMode disabled, error is reported. */ @@ -1099,7 +1123,7 @@ HAL_StatusTypeDef HAL_ADCEx_InjectedConfigChannel(ADC_HandleTypeDef* hadc, ADC_I sConfigInjected->InjectedRank, sConfigInjected->InjectedNbrOfConversion) , - 0x00000000U); + 0x00000000 ); } } @@ -1231,8 +1255,8 @@ HAL_StatusTypeDef HAL_ADCEx_InjectedConfigChannel(ADC_HandleTypeDef* hadc, ADC_I { /* Delay for temperature sensor stabilization time */ /* Compute number of CPU cycles to wait for */ - wait_loop_index = (ADC_TEMPSENSOR_DELAY_US * (SystemCoreClock / 1000000U)); - while(wait_loop_index != 0U) + wait_loop_index = (ADC_TEMPSENSOR_DELAY_US * (SystemCoreClock / 1000000)); + while(wait_loop_index != 0) { wait_loop_index--; } @@ -1255,7 +1279,7 @@ HAL_StatusTypeDef HAL_ADCEx_InjectedConfigChannel(ADC_HandleTypeDef* hadc, ADC_I return tmp_hal_status; } -#if defined (STM32F103x6) || defined (STM32F103xB) || defined (STM32F105xC) || defined (STM32F107xC) || defined (STM32F103xE) || defined (STM32F103xG) +#if defined (STM32F101xG) || defined (STM32F103x6) || defined (STM32F103xB) || defined (STM32F105xC) || defined (STM32F107xC) || defined (STM32F103xE) || defined (STM32F103xG) /** * @brief Enable ADC multimode and configure multimode parameters * @note Possibility to update parameters on the fly: @@ -1320,7 +1344,7 @@ HAL_StatusTypeDef HAL_ADCEx_MultiModeConfigChannel(ADC_HandleTypeDef* hadc, ADC_ /* Return function status */ return tmp_hal_status; } -#endif /* defined STM32F103x6 || defined STM32F103xB || defined STM32F105xC || defined STM32F107xC || defined STM32F103xE || defined STM32F103xG */ +#endif /* STM32F101xG || defined STM32F103x6 || defined STM32F103xB || defined STM32F105xC || defined STM32F107xC || defined STM32F103xE || defined STM32F103xG */ /** * @} */ diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_adc_ex.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_adc_ex.h index eba417077a0..2337bf61f5b 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_adc_ex.h +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_adc_ex.h @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_hal_adc_ex.h * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief Header file of ADC HAL extension module. ****************************************************************************** * @attention @@ -125,7 +125,7 @@ typedef struct configure a channel on injected group can impact the configuration of other channels previously set. */ }ADC_InjectionConfTypeDef; -#if defined (STM32F103x6) || defined (STM32F103xB) || defined (STM32F105xC) || defined (STM32F107xC) || defined (STM32F103xE) || defined (STM32F103xG) +#if defined (STM32F101xG) || defined (STM32F103x6) || defined (STM32F103xB) || defined (STM32F105xC) || defined (STM32F107xC) || defined (STM32F103xE) || defined (STM32F103xG) /** * @brief Structure definition of ADC multimode * @note The setting of these parameters with function HAL_ADCEx_MultiModeConfigChannel() is conditioned to ADCs state (both ADCs of the common group). @@ -145,7 +145,7 @@ typedef struct }ADC_MultiModeTypeDef; -#endif /* defined STM32F103x6 || defined STM32F103xB || defined STM32F105xC || defined STM32F107xC || defined STM32F103xE || defined STM32F103xG */ +#endif /* STM32F101xG || defined STM32F103x6 || defined STM32F103xB || defined STM32F105xC || defined STM32F107xC || defined STM32F103xE || defined STM32F103xG */ /** * @} @@ -161,10 +161,10 @@ typedef struct /** @defgroup ADCEx_injected_rank ADCEx rank into injected group * @{ */ -#define ADC_INJECTED_RANK_1 0x00000001U -#define ADC_INJECTED_RANK_2 0x00000002U -#define ADC_INJECTED_RANK_3 0x00000003U -#define ADC_INJECTED_RANK_4 0x00000004U +#define ADC_INJECTED_RANK_1 ((uint32_t)0x00000001) +#define ADC_INJECTED_RANK_2 ((uint32_t)0x00000002) +#define ADC_INJECTED_RANK_3 ((uint32_t)0x00000003) +#define ADC_INJECTED_RANK_4 ((uint32_t)0x00000004) /** * @} */ @@ -172,7 +172,7 @@ typedef struct /** @defgroup ADCEx_External_trigger_edge_Injected ADCEx external trigger enable for injected group * @{ */ -#define ADC_EXTERNALTRIGINJECCONV_EDGE_NONE 0x00000000U +#define ADC_EXTERNALTRIGINJECCONV_EDGE_NONE ((uint32_t)0x00000000) #define ADC_EXTERNALTRIGINJECCONV_EDGE_RISING ((uint32_t)ADC_CR2_JEXTTRIG) /** * @} @@ -204,7 +204,7 @@ typedef struct /*!< External triggers of regular group for all ADC instances */ #define ADC_EXTERNALTRIGCONV_T1_CC3 ADC1_2_3_EXTERNALTRIG_T1_CC3 -#if defined (STM32F101xE) || defined (STM32F103xE) || defined (STM32F103xG) || defined (STM32F105xC) || defined (STM32F107xC) +#if defined (STM32F101xE) || defined (STM32F101xG) || defined (STM32F103xE) || defined (STM32F103xG) || defined (STM32F105xC) || defined (STM32F107xC) /*!< Note: TIM8_TRGO is available on ADC1 and ADC2 only in high-density and */ /* XL-density devices. */ /* To use it on ADC or ADC2, a remap of trigger must be done from */ @@ -216,7 +216,7 @@ typedef struct /* its definition is set to value for ADC1&ADC2 by default and changed to */ /* value for ADC3 by HAL ADC driver if ADC3 is selected. */ #define ADC_EXTERNALTRIGCONV_T8_TRGO ADC1_2_EXTERNALTRIG_T8_TRGO -#endif /* STM32F101xE || STM32F103xE || STM32F103xG || STM32F105xC || STM32F107xC */ +#endif /* STM32F101xE || STM32F101xG || STM32F103xE || STM32F103xG || STM32F105xC || STM32F107xC */ #define ADC_SOFTWARE_START ADC1_2_3_SWSTART /** @@ -248,7 +248,7 @@ typedef struct #define ADC_EXTERNALTRIGINJECCONV_T1_CC4 ADC1_2_3_EXTERNALTRIGINJEC_T1_CC4 #define ADC_EXTERNALTRIGINJECCONV_T1_TRGO ADC1_2_3_EXTERNALTRIGINJEC_T1_TRGO -#if defined (STM32F101xE) || defined (STM32F103xE) || defined (STM32F103xG) || defined (STM32F105xC) || defined (STM32F107xC) +#if defined (STM32F101xE) || defined (STM32F101xG) || defined (STM32F103xE) || defined (STM32F103xG) || defined (STM32F105xC) || defined (STM32F107xC) /*!< Note: TIM8_CC4 is available on ADC1 and ADC2 only in high-density and */ /* XL-density devices. */ /* To use it on ADC1 or ADC2, a remap of trigger must be done from */ @@ -260,18 +260,18 @@ typedef struct /* its definition is set to value for ADC1&ADC2 by default and changed to */ /* value for ADC3 by HAL ADC driver if ADC3 is selected. */ #define ADC_EXTERNALTRIGINJECCONV_T8_CC4 ADC1_2_EXTERNALTRIGINJEC_T8_CC4 -#endif /* STM32F101xE || STM32F103xE || STM32F103xG || STM32F105xC || STM32F107xC */ +#endif /* STM32F101xE || STM32F101xG || STM32F103xE || STM32F103xG || STM32F105xC || STM32F107xC */ #define ADC_INJECTED_SOFTWARE_START ADC1_2_3_JSWSTART /** * @} */ -#if defined (STM32F103x6) || defined (STM32F103xB) || defined (STM32F105xC) || defined (STM32F107xC) || defined (STM32F103xE) || defined (STM32F103xG) +#if defined (STM32F101xG) || defined (STM32F103x6) || defined (STM32F103xB) || defined (STM32F105xC) || defined (STM32F107xC) || defined (STM32F103xE) || defined (STM32F103xG) /** @defgroup ADCEx_Common_mode ADC Extended Dual ADC Mode * @{ */ -#define ADC_MODE_INDEPENDENT 0x00000000U /*!< ADC dual mode disabled (ADC independent mode) */ +#define ADC_MODE_INDEPENDENT ((uint32_t)(0x00000000)) /*!< ADC dual mode disabled (ADC independent mode) */ #define ADC_DUALMODE_REGSIMULT_INJECSIMULT ((uint32_t)( ADC_CR1_DUALMOD_0)) /*!< ADC dual mode enabled: Combined regular simultaneous + injected simultaneous mode, on groups regular and injected */ #define ADC_DUALMODE_REGSIMULT_ALTERTRIG ((uint32_t)( ADC_CR1_DUALMOD_1 )) /*!< ADC dual mode enabled: Combined regular simultaneous + alternate trigger mode, on groups regular and injected */ #define ADC_DUALMODE_INJECSIMULT_INTERLFAST ((uint32_t)( ADC_CR1_DUALMOD_1 | ADC_CR1_DUALMOD_0)) /*!< ADC dual mode enabled: Combined injected simultaneous + fast interleaved mode, on groups regular and injected (delay between ADC sampling phases: 7 ADC clock cycles (equivalent to parameter "TwoSamplingDelay" set to "ADC_TWOSAMPLINGDELAY_7CYCLES" on other STM32 devices)) */ @@ -284,7 +284,7 @@ typedef struct /** * @} */ -#endif /* defined STM32F103x6 || defined STM32F103xB || defined STM32F105xC || defined STM32F107xC || defined STM32F103xE || defined STM32F103xG */ +#endif /* STM32F101xG || defined STM32F103x6 || defined STM32F103xB || defined STM32F105xC || defined STM32F107xC || defined STM32F103xE || defined STM32F103xG */ /** * @} @@ -305,13 +305,13 @@ typedef struct /* (used internally by HAL driver. To not use into HAL structure parameters) */ /* External triggers of regular group for ADC1&ADC2 (if ADCx available) */ -#define ADC1_2_EXTERNALTRIG_T1_CC1 0x00000000U +#define ADC1_2_EXTERNALTRIG_T1_CC1 ((uint32_t) 0x00000000) #define ADC1_2_EXTERNALTRIG_T1_CC2 ((uint32_t)( ADC_CR2_EXTSEL_0)) #define ADC1_2_EXTERNALTRIG_T2_CC2 ((uint32_t)( ADC_CR2_EXTSEL_1 | ADC_CR2_EXTSEL_0)) #define ADC1_2_EXTERNALTRIG_T3_TRGO ((uint32_t)(ADC_CR2_EXTSEL_2 )) #define ADC1_2_EXTERNALTRIG_T4_CC4 ((uint32_t)(ADC_CR2_EXTSEL_2 | ADC_CR2_EXTSEL_0)) #define ADC1_2_EXTERNALTRIG_EXT_IT11 ((uint32_t)(ADC_CR2_EXTSEL_2 | ADC_CR2_EXTSEL_1 )) -#if defined (STM32F101xE) || defined (STM32F103xE) || defined (STM32F103xG) +#if defined (STM32F101xE) || defined (STM32F101xG) || defined (STM32F103xE) || defined (STM32F103xG) /* Note: TIM8_TRGO is available on ADC1 and ADC2 only in high-density and */ /* XL-density devices. */ #define ADC1_2_EXTERNALTRIG_T8_TRGO ADC1_2_EXTERNALTRIG_EXT_IT11 @@ -347,7 +347,7 @@ typedef struct #define ADC1_2_EXTERNALTRIGINJEC_T3_CC4 ((uint32_t)(ADC_CR2_JEXTSEL_2 )) #define ADC1_2_EXTERNALTRIGINJEC_T4_TRGO ((uint32_t)(ADC_CR2_JEXTSEL_2 | ADC_CR2_JEXTSEL_0)) #define ADC1_2_EXTERNALTRIGINJEC_EXT_IT15 ((uint32_t)(ADC_CR2_JEXTSEL_2 | ADC_CR2_JEXTSEL_1 )) -#if defined (STM32F101xE) || defined (STM32F103xE) || defined (STM32F103xG) +#if defined (STM32F101xE) || defined (STM32F101xG) || defined (STM32F103xE) || defined (STM32F103xG) /* Note: TIM8_CC4 is available on ADC1 and ADC2 only in high-density and */ /* XL-density devices. */ #define ADC1_2_EXTERNALTRIGINJEC_T8_CC4 ADC1_2_EXTERNALTRIGINJEC_EXT_IT15 @@ -363,7 +363,7 @@ typedef struct #endif /* STM32F103xE || defined STM32F103xG */ /* External triggers of injected group for ADC1&ADC2&ADC3 (if ADCx available) */ -#define ADC1_2_3_EXTERNALTRIGINJEC_T1_TRGO 0x00000000U +#define ADC1_2_3_EXTERNALTRIGINJEC_T1_TRGO ((uint32_t) 0x00000000) #define ADC1_2_3_EXTERNALTRIGINJEC_T1_CC4 ((uint32_t)( ADC_CR2_JEXTSEL_0)) #define ADC1_2_3_JSWSTART ((uint32_t)(ADC_CR2_JEXTSEL_2 | ADC_CR2_JEXTSEL_1 | ADC_CR2_JEXTSEL_0)) /** @@ -448,7 +448,7 @@ typedef struct * @param __HANDLE__: ADC handle * @retval Multimode state: RESET if multimode is disabled, other value if multimode is enabled */ -#if defined (STM32F103x6) || defined (STM32F103xB) || defined (STM32F105xC) || defined (STM32F107xC) || defined (STM32F103xE) || defined (STM32F103xG) +#if defined (STM32F101xG) || defined (STM32F103x6) || defined (STM32F103xB) || defined (STM32F105xC) || defined (STM32F107xC) || defined (STM32F103xE) || defined (STM32F103xG) #define ADC_MULTIMODE_IS_ENABLE(__HANDLE__) \ (( (((__HANDLE__)->Instance) == ADC1) || (((__HANDLE__)->Instance) == ADC2) \ )? \ @@ -459,14 +459,14 @@ typedef struct #else #define ADC_MULTIMODE_IS_ENABLE(__HANDLE__) \ (RESET) -#endif /* defined STM32F103x6 || defined STM32F103xB || defined STM32F105xC || defined STM32F107xC || defined STM32F103xE || defined STM32F103xG */ +#endif /* STM32F101xG || defined STM32F103x6 || defined STM32F103xB || defined STM32F105xC || defined STM32F107xC || defined STM32F103xE || defined STM32F103xG */ /** * @brief Verification of condition for ADC start conversion: ADC must be in non-multimode, or multimode with handle of ADC master (applicable for devices with several ADCs) * @param __HANDLE__: ADC handle * @retval None */ -#if defined (STM32F103x6) || defined (STM32F103xB) || defined (STM32F105xC) || defined (STM32F107xC) || defined (STM32F103xE) || defined (STM32F103xG) +#if defined (STM32F101xG) || defined (STM32F103x6) || defined (STM32F103xB) || defined (STM32F105xC) || defined (STM32F107xC) || defined (STM32F103xE) || defined (STM32F103xG) #define ADC_NONMULTIMODE_OR_MULTIMODEMASTER(__HANDLE__) \ (( (((__HANDLE__)->Instance) == ADC2) \ )? \ @@ -477,14 +477,14 @@ typedef struct #else #define ADC_NONMULTIMODE_OR_MULTIMODEMASTER(__HANDLE__) \ (!RESET) -#endif /* defined STM32F103x6 || defined STM32F103xB || defined STM32F105xC || defined STM32F107xC || defined STM32F103xE || defined STM32F103xG */ +#endif /* STM32F101xG || defined STM32F103x6 || defined STM32F103xB || defined STM32F105xC || defined STM32F107xC || defined STM32F103xE || defined STM32F103xG */ /** * @brief Check ADC multimode setting: In case of multimode, check whether ADC master of the selected ADC has feature auto-injection enabled (applicable for devices with several ADCs) * @param __HANDLE__: ADC handle * @retval None */ -#if defined (STM32F103x6) || defined (STM32F103xB) || defined (STM32F105xC) || defined (STM32F107xC) || defined (STM32F103xE) || defined (STM32F103xG) +#if defined (STM32F101xG) || defined (STM32F103x6) || defined (STM32F103xB) || defined (STM32F105xC) || defined (STM32F107xC) || defined (STM32F103xE) || defined (STM32F103xG) #define ADC_MULTIMODE_AUTO_INJECTED(__HANDLE__) \ (( (((__HANDLE__)->Instance) == ADC1) || (((__HANDLE__)->Instance) == ADC2) \ )? \ @@ -495,9 +495,9 @@ typedef struct #else #define ADC_MULTIMODE_AUTO_INJECTED(__HANDLE__) \ (RESET) -#endif /* defined STM32F103x6 || defined STM32F103xB || defined STM32F105xC || defined STM32F107xC || defined STM32F103xE || defined STM32F103xG */ +#endif /* STM32F101xG || defined STM32F103x6 || defined STM32F103xB || defined STM32F105xC || defined STM32F107xC || defined STM32F103xE || defined STM32F103xG */ -#if defined (STM32F103x6) || defined (STM32F103xB) || defined (STM32F105xC) || defined (STM32F107xC) || defined (STM32F103xE) || defined (STM32F103xG) +#if defined (STM32F101xG) || defined (STM32F103x6) || defined (STM32F103xB) || defined (STM32F105xC) || defined (STM32F107xC) || defined (STM32F103xE) || defined (STM32F103xG) /** * @brief Set handle of the other ADC sharing the common multimode settings * @param __HANDLE__: ADC handle @@ -518,20 +518,21 @@ typedef struct #define ADC_MULTI_SLAVE(__HANDLE_MASTER__, __HANDLE_SLAVE__) \ ((__HANDLE_SLAVE__)->Instance = ADC2) -#endif /* defined STM32F103x6 || defined STM32F103xB || defined STM32F105xC || defined STM32F107xC || defined STM32F103xE || defined STM32F103xG */ +#endif /* STM32F101xG || defined STM32F103x6 || defined STM32F103xB || defined STM32F105xC || defined STM32F107xC || defined STM32F103xE || defined STM32F103xG */ #define IS_ADC_INJECTED_RANK(CHANNEL) (((CHANNEL) == ADC_INJECTED_RANK_1) || \ ((CHANNEL) == ADC_INJECTED_RANK_2) || \ ((CHANNEL) == ADC_INJECTED_RANK_3) || \ - ((CHANNEL) == ADC_INJECTED_RANK_4)) + ((CHANNEL) == ADC_INJECTED_RANK_4) ) #define IS_ADC_EXTTRIGINJEC_EDGE(EDGE) (((EDGE) == ADC_EXTERNALTRIGINJECCONV_EDGE_NONE) || \ - ((EDGE) == ADC_EXTERNALTRIGINJECCONV_EDGE_RISING)) + ((EDGE) == ADC_EXTERNALTRIGINJECCONV_EDGE_RISING) ) /** @defgroup ADCEx_injected_nb_conv_verification ADCEx injected nb conv verification * @{ */ -#define IS_ADC_INJECTED_NB_CONV(LENGTH) (((LENGTH) >= 1U) && ((LENGTH) <= 4U)) +#define IS_ADC_INJECTED_NB_CONV(LENGTH) \ + (((LENGTH) >= ((uint32_t)1)) && ((LENGTH) <= ((uint32_t)4))) /** * @} */ @@ -543,9 +544,10 @@ typedef struct ((REGTRIG) == ADC_EXTERNALTRIGCONV_T3_TRGO) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T4_CC4) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_EXT_IT11) || \ - ((REGTRIG) == ADC_SOFTWARE_START)) + \ + ((REGTRIG) == ADC_SOFTWARE_START) ) #endif -#if defined (STM32F101xE) +#if defined (STM32F101xE) || defined (STM32F101xG) #define IS_ADC_EXTTRIG(REGTRIG) (((REGTRIG) == ADC_EXTERNALTRIGCONV_T1_CC1) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T1_CC2) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T2_CC2) || \ @@ -553,16 +555,8 @@ typedef struct ((REGTRIG) == ADC_EXTERNALTRIGCONV_T4_CC4) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_EXT_IT11) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T8_TRGO) || \ - ((REGTRIG) == ADC_SOFTWARE_START)) -#endif -#if defined (STM32F101xG) -#define IS_ADC_EXTTRIG(REGTRIG) (((REGTRIG) == ADC_EXTERNALTRIGCONV_T1_CC1) || \ - ((REGTRIG) == ADC_EXTERNALTRIGCONV_T1_CC2) || \ - ((REGTRIG) == ADC_EXTERNALTRIGCONV_T2_CC2) || \ - ((REGTRIG) == ADC_EXTERNALTRIGCONV_T3_TRGO) || \ - ((REGTRIG) == ADC_EXTERNALTRIGCONV_T4_CC4) || \ - ((REGTRIG) == ADC_EXTERNALTRIGCONV_EXT_IT11) || \ - ((REGTRIG) == ADC_SOFTWARE_START)) + \ + ((REGTRIG) == ADC_SOFTWARE_START) ) #endif #if defined (STM32F103xE) || defined (STM32F103xG) #define IS_ADC_EXTTRIG(REGTRIG) (((REGTRIG) == ADC_EXTERNALTRIGCONV_T1_CC1) || \ @@ -571,14 +565,16 @@ typedef struct ((REGTRIG) == ADC_EXTERNALTRIGCONV_T3_TRGO) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T4_CC4) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_EXT_IT11) || \ + \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T3_CC1) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T2_CC3) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T8_CC1) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T5_CC1) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T5_CC3) || \ + \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T1_CC3) || \ ((REGTRIG) == ADC_EXTERNALTRIGCONV_T8_TRGO) || \ - ((REGTRIG) == ADC_SOFTWARE_START)) + ((REGTRIG) == ADC_SOFTWARE_START) ) #endif #if defined (STM32F100xB) || defined (STM32F100xE) || defined (STM32F101x6) || defined (STM32F101xB) || defined (STM32F102x6) || defined (STM32F102xB) || defined (STM32F103x6) || defined (STM32F103xB) || defined (STM32F105xC) || defined (STM32F107xC) @@ -587,30 +583,24 @@ typedef struct ((REGTRIG) == ADC_EXTERNALTRIGINJECCONV_T3_CC4) || \ ((REGTRIG) == ADC_EXTERNALTRIGINJECCONV_T4_TRGO) || \ ((REGTRIG) == ADC_EXTERNALTRIGINJECCONV_EXT_IT15) || \ + \ ((REGTRIG) == ADC_EXTERNALTRIGINJECCONV_T1_CC4) || \ ((REGTRIG) == ADC_EXTERNALTRIGINJECCONV_T1_TRGO) || \ - ((REGTRIG) == ADC_INJECTED_SOFTWARE_START)) + \ + ((REGTRIG) == ADC_INJECTED_SOFTWARE_START) ) #endif -#if defined (STM32F101xE) +#if defined (STM32F101xE) || defined (STM32F101xG) #define IS_ADC_EXTTRIGINJEC(REGTRIG) (((REGTRIG) == ADC_EXTERNALTRIGINJECCONV_T2_TRGO) || \ ((REGTRIG) == ADC_EXTERNALTRIGINJECCONV_T2_CC1) || \ ((REGTRIG) == ADC_EXTERNALTRIGINJECCONV_T3_CC4) || \ ((REGTRIG) == ADC_EXTERNALTRIGINJECCONV_T4_TRGO) || \ ((REGTRIG) == ADC_EXTERNALTRIGINJECCONV_EXT_IT15) || \ + \ ((REGTRIG) == ADC_EXTERNALTRIGINJECCONV_T1_CC4) || \ ((REGTRIG) == ADC_EXTERNALTRIGINJECCONV_T1_TRGO) || \ ((REGTRIG) == ADC_EXTERNALTRIGINJECCONV_T8_CC4) || \ - ((REGTRIG) == ADC_INJECTED_SOFTWARE_START)) -#endif -#if defined (STM32F101xG) -#define IS_ADC_EXTTRIGINJEC(REGTRIG) (((REGTRIG) == ADC_EXTERNALTRIGINJECCONV_T2_TRGO) || \ - ((REGTRIG) == ADC_EXTERNALTRIGINJECCONV_T2_CC1) || \ - ((REGTRIG) == ADC_EXTERNALTRIGINJECCONV_T3_CC4) || \ - ((REGTRIG) == ADC_EXTERNALTRIGINJECCONV_T4_TRGO) || \ - ((REGTRIG) == ADC_EXTERNALTRIGINJECCONV_EXT_IT15) || \ - ((REGTRIG) == ADC_EXTERNALTRIGINJECCONV_T1_CC4) || \ - ((REGTRIG) == ADC_EXTERNALTRIGINJECCONV_T1_TRGO) || \ - ((REGTRIG) == ADC_INJECTED_SOFTWARE_START)) + \ + ((REGTRIG) == ADC_INJECTED_SOFTWARE_START) ) #endif #if defined (STM32F103xE) || defined (STM32F103xG) #define IS_ADC_EXTTRIGINJEC(REGTRIG) (((REGTRIG) == ADC_EXTERNALTRIGINJECCONV_T2_TRGO) || \ @@ -619,17 +609,20 @@ typedef struct ((REGTRIG) == ADC_EXTERNALTRIGINJECCONV_T4_TRGO) || \ ((REGTRIG) == ADC_EXTERNALTRIGINJECCONV_T5_CC4) || \ ((REGTRIG) == ADC_EXTERNALTRIGINJECCONV_EXT_IT15) || \ + \ ((REGTRIG) == ADC_EXTERNALTRIGINJECCONV_T4_CC3) || \ ((REGTRIG) == ADC_EXTERNALTRIGINJECCONV_T8_CC2) || \ ((REGTRIG) == ADC_EXTERNALTRIGINJECCONV_T5_TRGO) || \ ((REGTRIG) == ADC_EXTERNALTRIGINJECCONV_T5_CC4) || \ + \ ((REGTRIG) == ADC_EXTERNALTRIGINJECCONV_T1_CC4) || \ ((REGTRIG) == ADC_EXTERNALTRIGINJECCONV_T1_TRGO) || \ ((REGTRIG) == ADC_EXTERNALTRIGINJECCONV_T8_CC4) || \ - ((REGTRIG) == ADC_INJECTED_SOFTWARE_START)) + \ + ((REGTRIG) == ADC_INJECTED_SOFTWARE_START) ) #endif -#if defined (STM32F103x6) || defined (STM32F103xB) || defined (STM32F105xC) || defined (STM32F107xC) || defined (STM32F103xE) || defined (STM32F103xG) +#if defined (STM32F101xG) || defined (STM32F103x6) || defined (STM32F103xB) || defined (STM32F105xC) || defined (STM32F107xC) || defined (STM32F103xE) || defined (STM32F103xG) #define IS_ADC_MODE(MODE) (((MODE) == ADC_MODE_INDEPENDENT) || \ ((MODE) == ADC_DUALMODE_REGSIMULT_INJECSIMULT) || \ ((MODE) == ADC_DUALMODE_REGSIMULT_ALTERTRIG) || \ @@ -639,8 +632,8 @@ typedef struct ((MODE) == ADC_DUALMODE_REGSIMULT) || \ ((MODE) == ADC_DUALMODE_INTERLFAST) || \ ((MODE) == ADC_DUALMODE_INTERLSLOW) || \ - ((MODE) == ADC_DUALMODE_ALTERTRIG) ) -#endif /* defined STM32F103x6 || defined STM32F103xB || defined STM32F105xC || defined STM32F107xC || defined STM32F103xE || defined STM32F103xG */ + ((MODE) == ADC_DUALMODE_ALTERTRIG) ) +#endif /* STM32F101xG || defined STM32F103x6 || defined STM32F103xB || defined STM32F105xC || defined STM32F107xC || defined STM32F103xE || defined STM32F103xG */ /** * @} @@ -673,17 +666,17 @@ HAL_StatusTypeDef HAL_ADCEx_InjectedPollForConversion(ADC_HandleTypeDef* h HAL_StatusTypeDef HAL_ADCEx_InjectedStart_IT(ADC_HandleTypeDef* hadc); HAL_StatusTypeDef HAL_ADCEx_InjectedStop_IT(ADC_HandleTypeDef* hadc); -#if defined (STM32F103x6) || defined (STM32F103xB) || defined (STM32F105xC) || defined (STM32F107xC) || defined (STM32F103xE) || defined (STM32F103xG) +#if defined (STM32F101xG) || defined (STM32F103x6) || defined (STM32F103xB) || defined (STM32F105xC) || defined (STM32F107xC) || defined (STM32F103xE) || defined (STM32F103xG) /* ADC multimode */ HAL_StatusTypeDef HAL_ADCEx_MultiModeStart_DMA(ADC_HandleTypeDef *hadc, uint32_t *pData, uint32_t Length); HAL_StatusTypeDef HAL_ADCEx_MultiModeStop_DMA(ADC_HandleTypeDef *hadc); -#endif /* defined STM32F103x6 || defined STM32F103xB || defined STM32F105xC || defined STM32F107xC || defined STM32F103xE || defined STM32F103xG */ +#endif /* STM32F101xG || defined STM32F103x6 || defined STM32F103xB || defined STM32F105xC || defined STM32F107xC || defined STM32F103xE || defined STM32F103xG */ /* ADC retrieve conversion value intended to be used with polling or interruption */ uint32_t HAL_ADCEx_InjectedGetValue(ADC_HandleTypeDef* hadc, uint32_t InjectedRank); -#if defined (STM32F103x6) || defined (STM32F103xB) || defined (STM32F105xC) || defined (STM32F107xC) || defined (STM32F103xE) || defined (STM32F103xG) +#if defined (STM32F101xG) || defined (STM32F103x6) || defined (STM32F103xB) || defined (STM32F105xC) || defined (STM32F107xC) || defined (STM32F103xE) || defined (STM32F103xG) uint32_t HAL_ADCEx_MultiModeGetValue(ADC_HandleTypeDef *hadc); -#endif /* defined STM32F103x6 || defined STM32F103xB || defined STM32F105xC || defined STM32F107xC || defined STM32F103xE || defined STM32F103xG */ +#endif /* STM32F101xG || defined STM32F103x6 || defined STM32F103xB || defined STM32F105xC || defined STM32F107xC || defined STM32F103xE || defined STM32F103xG */ /* ADC IRQHandler and Callbacks used in non-blocking modes (Interruption) */ void HAL_ADCEx_InjectedConvCpltCallback(ADC_HandleTypeDef* hadc); @@ -697,9 +690,9 @@ void HAL_ADCEx_InjectedConvCpltCallback(ADC_HandleTypeDef* ha * @{ */ HAL_StatusTypeDef HAL_ADCEx_InjectedConfigChannel(ADC_HandleTypeDef* hadc,ADC_InjectionConfTypeDef* sConfigInjected); -#if defined (STM32F103x6) || defined (STM32F103xB) || defined (STM32F105xC) || defined (STM32F107xC) || defined (STM32F103xE) || defined (STM32F103xG) +#if defined (STM32F101xG) || defined (STM32F103x6) || defined (STM32F103xB) || defined (STM32F105xC) || defined (STM32F107xC) || defined (STM32F103xE) || defined (STM32F103xG) HAL_StatusTypeDef HAL_ADCEx_MultiModeConfigChannel(ADC_HandleTypeDef *hadc, ADC_MultiModeTypeDef *multimode); -#endif /* defined STM32F103x6 || defined STM32F103xB || defined STM32F105xC || defined STM32F107xC || defined STM32F103xE || defined STM32F103xG */ +#endif /* STM32F101xG || defined STM32F103x6 || defined STM32F103xB || defined STM32F105xC || defined STM32F107xC || defined STM32F103xE || defined STM32F103xG */ /** * @} */ diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_can.c b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_can.c index 9eccce65384..df438113ad5 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_can.c +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_can.c @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_hal_can.c * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief CAN HAL module driver. * This file provides firmware functions to manage the following * functionalities of the Controller Area Network (CAN) peripheral: @@ -27,16 +27,12 @@ (++) Connect and configure the involved CAN pins using the following function HAL_GPIO_Init(); - (#) Initialize and configure the CAN using HAL_CAN_Init() function. + (#) Initialise and configure the CAN using HAL_CAN_Init() function. (#) Transmit the desired CAN frame using HAL_CAN_Transmit() function. - - (#) Or transmit the desired CAN frame using HAL_CAN_Transmit_IT() function. (#) Receive a CAN frame using HAL_CAN_Receive() function. - (#) Or receive a CAN frame using HAL_CAN_Receive_IT() function. - *** Polling mode IO operation *** ================================= [..] @@ -77,7 +73,7 @@ ****************************************************************************** * @attention * - *

© COPYRIGHT(c) 2017 STMicroelectronics

+ *

© COPYRIGHT(c) 2016 STMicroelectronics

* * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: @@ -106,7 +102,12 @@ /* Includes ------------------------------------------------------------------*/ #include "stm32f1xx_hal.h" - + +#ifdef HAL_CAN_MODULE_ENABLED + +#if defined(STM32F103x6) || defined(STM32F103xB) || defined(STM32F103xE) || \ + defined(STM32F103xG) || defined(STM32F105xC) || defined(STM32F107xC) + /** @addtogroup STM32F1xx_HAL_Driver * @{ */ @@ -116,34 +117,31 @@ * @{ */ -#ifdef HAL_CAN_MODULE_ENABLED - -#if defined(STM32F103x6) || defined(STM32F103xB) || defined(STM32F103xE) || \ - defined(STM32F103xG) || defined(STM32F105xC) || defined(STM32F107xC) - - /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /** @defgroup CAN_Private_Constants CAN Private Constants * @{ */ -#define CAN_TIMEOUT_VALUE 10U +#define CAN_TIMEOUT_VALUE 10 + +#define CAN_TI0R_STID_BIT_POSITION ((uint32_t)21) /* Position of LSB bits STID in register CAN_TI0R */ +#define CAN_TI0R_EXID_BIT_POSITION ((uint32_t) 3) /* Position of LSB bits EXID in register CAN_TI0R */ +#define CAN_TDL0R_DATA0_BIT_POSITION ((uint32_t) 0) /* Position of LSB bits DATA0 in register CAN_TDL0R */ +#define CAN_TDL0R_DATA1_BIT_POSITION ((uint32_t) 8) /* Position of LSB bits DATA1 in register CAN_TDL0R */ +#define CAN_TDL0R_DATA2_BIT_POSITION ((uint32_t)16) /* Position of LSB bits DATA2 in register CAN_TDL0R */ +#define CAN_TDL0R_DATA3_BIT_POSITION ((uint32_t)24) /* Position of LSB bits DATA3 in register CAN_TDL0R */ + /** * @} */ + /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ -/** @defgroup CAN_Private_Functions CAN Private Functions - * @{ - */ static HAL_StatusTypeDef CAN_Receive_IT(CAN_HandleTypeDef* hcan, uint8_t FIFONumber); static HAL_StatusTypeDef CAN_Transmit_IT(CAN_HandleTypeDef* hcan); -/** - * @} - */ +/* Exported functions ---------------------------------------------------------*/ -/* Exported functions --------------------------------------------------------*/ /** @defgroup CAN_Exported_Functions CAN Exported Functions * @{ */ @@ -173,8 +171,8 @@ static HAL_StatusTypeDef CAN_Transmit_IT(CAN_HandleTypeDef* hcan); HAL_StatusTypeDef HAL_CAN_Init(CAN_HandleTypeDef* hcan) { uint32_t status = CAN_INITSTATUS_FAILED; /* Default init status */ - uint32_t tickstart = 0U; - uint32_t tmp_mcr = 0U; + uint32_t tickstart = 0; + uint32_t tmp_mcr = 0; /* Check CAN handle */ if(hcan == NULL) @@ -222,8 +220,10 @@ HAL_StatusTypeDef HAL_CAN_Init(CAN_HandleTypeDef* hcan) if((HAL_GetTick()-tickstart) > CAN_TIMEOUT_VALUE) { hcan->State= HAL_CAN_STATE_TIMEOUT; + /* Process unlocked */ __HAL_UNLOCK(hcan); + return HAL_TIMEOUT; } } @@ -236,58 +236,36 @@ HAL_StatusTypeDef HAL_CAN_Init(CAN_HandleTypeDef* hcan) { SET_BIT(tmp_mcr, CAN_MCR_TTCM); } - else - { - CLEAR_BIT(tmp_mcr, CAN_MCR_TTCM); - } /* Set the automatic bus-off management */ if (hcan->Init.ABOM == ENABLE) { SET_BIT(tmp_mcr, CAN_MCR_ABOM); } - else - { - CLEAR_BIT(tmp_mcr, CAN_MCR_ABOM); - } /* Set the automatic wake-up mode */ if (hcan->Init.AWUM == ENABLE) { SET_BIT(tmp_mcr, CAN_MCR_AWUM); } - else - { - CLEAR_BIT(tmp_mcr, CAN_MCR_AWUM); - } + /* Set the no automatic retransmission */ if (hcan->Init.NART == ENABLE) { SET_BIT(tmp_mcr, CAN_MCR_NART); } - else - { - CLEAR_BIT(tmp_mcr, CAN_MCR_NART); - } /* Set the receive FIFO locked mode */ if (hcan->Init.RFLM == ENABLE) { SET_BIT(tmp_mcr, CAN_MCR_RFLM); } - else - { - CLEAR_BIT(tmp_mcr, CAN_MCR_RFLM); - } + /* Set the transmit FIFO priority */ if (hcan->Init.TXFP == ENABLE) { SET_BIT(tmp_mcr, CAN_MCR_TXFP); } - else - { - CLEAR_BIT(tmp_mcr, CAN_MCR_TXFP); - } /* Update register MCR */ MODIFY_REG(hcan->Instance->MCR, @@ -304,7 +282,7 @@ HAL_StatusTypeDef HAL_CAN_Init(CAN_HandleTypeDef* hcan) hcan->Init.SJW | hcan->Init.BS1 | hcan->Init.BS2 | - (hcan->Init.Prescaler - 1U))); + (hcan->Init.Prescaler - 1) )); /* Request leave initialisation */ CLEAR_BIT(hcan->Instance->MCR, CAN_MCR_INRQ); @@ -313,7 +291,7 @@ HAL_StatusTypeDef HAL_CAN_Init(CAN_HandleTypeDef* hcan) tickstart = HAL_GetTick(); /* Wait the acknowledge */ - while(HAL_IS_BIT_SET(hcan->Instance->MSR, CAN_MSR_INAK)) + while(HAL_IS_BIT_CLR(hcan->Instance->MSR, CAN_MSR_INAK)) { if((HAL_GetTick()-tickstart) > CAN_TIMEOUT_VALUE) { @@ -327,7 +305,7 @@ HAL_StatusTypeDef HAL_CAN_Init(CAN_HandleTypeDef* hcan) } /* Check acknowledged */ - if(HAL_IS_BIT_CLR(hcan->Instance->MSR, CAN_MSR_INAK)) + if (HAL_IS_BIT_SET(hcan->Instance->MSR, CAN_MSR_INAK)) { status = CAN_INITSTATUS_SUCCESS; } @@ -348,7 +326,7 @@ HAL_StatusTypeDef HAL_CAN_Init(CAN_HandleTypeDef* hcan) { /* Initialize the CAN state */ hcan->State = HAL_CAN_STATE_ERROR; - + /* Return function status */ return HAL_ERROR; } @@ -365,11 +343,8 @@ HAL_StatusTypeDef HAL_CAN_Init(CAN_HandleTypeDef* hcan) */ HAL_StatusTypeDef HAL_CAN_ConfigFilter(CAN_HandleTypeDef* hcan, CAN_FilterConfTypeDef* sFilterConfig) { - uint32_t filternbrbitpos = 0U; + uint32_t filternbrbitpos = 0; - /* Prevent unused argument(s) compilation warning */ - UNUSED(hcan); - /* Check the parameters */ assert_param(IS_CAN_FILTER_NUMBER(sFilterConfig->FilterNumber)); assert_param(IS_CAN_FILTER_MODE(sFilterConfig->FilterMode)); @@ -378,18 +353,18 @@ HAL_StatusTypeDef HAL_CAN_ConfigFilter(CAN_HandleTypeDef* hcan, CAN_FilterConfTy assert_param(IS_FUNCTIONAL_STATE(sFilterConfig->FilterActivation)); assert_param(IS_CAN_BANKNUMBER(sFilterConfig->BankNumber)); - filternbrbitpos = (1U) << sFilterConfig->FilterNumber; + filternbrbitpos = ((uint32_t)1) << sFilterConfig->FilterNumber; /* Initialisation mode for the filter */ /* Select the start slave bank */ MODIFY_REG(hcan->Instance->FMR , CAN_FMR_CAN2SB , CAN_FMR_FINIT | - (uint32_t)(sFilterConfig->BankNumber << 8U) ); - + (uint32_t)(sFilterConfig->BankNumber << 8) ); + /* Filter Deactivation */ CLEAR_BIT(hcan->Instance->FA1R, filternbrbitpos); - + /* Filter Scale */ if (sFilterConfig->FilterScale == CAN_FILTERSCALE_16BIT) { @@ -399,14 +374,14 @@ HAL_StatusTypeDef HAL_CAN_ConfigFilter(CAN_HandleTypeDef* hcan, CAN_FilterConfTy /* First 16-bit identifier and First 16-bit mask */ /* Or First 16-bit identifier and Second 16-bit identifier */ hcan->Instance->sFilterRegister[sFilterConfig->FilterNumber].FR1 = - ((0x0000FFFFU & (uint32_t)sFilterConfig->FilterMaskIdLow) << 16U) | - (0x0000FFFFU & (uint32_t)sFilterConfig->FilterIdLow); + ((0x0000FFFF & (uint32_t)sFilterConfig->FilterMaskIdLow) << 16) | + (0x0000FFFF & (uint32_t)sFilterConfig->FilterIdLow); /* Second 16-bit identifier and Second 16-bit mask */ /* Or Third 16-bit identifier and Fourth 16-bit identifier */ hcan->Instance->sFilterRegister[sFilterConfig->FilterNumber].FR2 = - ((0x0000FFFFU & (uint32_t)sFilterConfig->FilterMaskIdHigh) << 16U) | - (0x0000FFFFU & (uint32_t)sFilterConfig->FilterIdHigh); + ((0x0000FFFF & (uint32_t)sFilterConfig->FilterMaskIdHigh) << 16) | + (0x0000FFFF & (uint32_t)sFilterConfig->FilterIdHigh); } if (sFilterConfig->FilterScale == CAN_FILTERSCALE_32BIT) @@ -415,12 +390,12 @@ HAL_StatusTypeDef HAL_CAN_ConfigFilter(CAN_HandleTypeDef* hcan, CAN_FilterConfTy SET_BIT(hcan->Instance->FS1R, filternbrbitpos); /* 32-bit identifier or First 32-bit identifier */ hcan->Instance->sFilterRegister[sFilterConfig->FilterNumber].FR1 = - ((0x0000FFFFU & (uint32_t)sFilterConfig->FilterIdHigh) << 16U) | - (0x0000FFFFU & (uint32_t)sFilterConfig->FilterIdLow); + ((0x0000FFFF & (uint32_t)sFilterConfig->FilterIdHigh) << 16) | + (0x0000FFFF & (uint32_t)sFilterConfig->FilterIdLow); /* 32-bit mask or Second 32-bit identifier */ hcan->Instance->sFilterRegister[sFilterConfig->FilterNumber].FR2 = - ((0x0000FFFFU & (uint32_t)sFilterConfig->FilterMaskIdHigh) << 16U) | - (0x0000FFFFU & (uint32_t)sFilterConfig->FilterMaskIdLow); + ((0x0000FFFF & (uint32_t)sFilterConfig->FilterMaskIdHigh) << 16) | + (0x0000FFFF & (uint32_t)sFilterConfig->FilterMaskIdLow); } /* Filter Mode */ @@ -528,8 +503,8 @@ __weak void HAL_CAN_MspDeInit(CAN_HandleTypeDef* hcan) */ /** @defgroup CAN_Exported_Functions_Group2 Input and Output operation functions - * @brief I/O operation functions - * + * @brief I/O operation functions + * @verbatim ============================================================================== ##### IO operation functions ##### @@ -554,7 +529,7 @@ __weak void HAL_CAN_MspDeInit(CAN_HandleTypeDef* hcan) HAL_StatusTypeDef HAL_CAN_Transmit(CAN_HandleTypeDef* hcan, uint32_t Timeout) { uint32_t transmitmailbox = CAN_TXSTATUS_NOMAILBOX; - uint32_t tickstart = 0U; + uint32_t tickstart = 0; /* Check the parameters */ assert_param(IS_CAN_IDTYPE(hcan->pTxMsg->IDE)); @@ -564,39 +539,33 @@ HAL_StatusTypeDef HAL_CAN_Transmit(CAN_HandleTypeDef* hcan, uint32_t Timeout) if(((hcan->Instance->TSR&CAN_TSR_TME0) == CAN_TSR_TME0) || \ ((hcan->Instance->TSR&CAN_TSR_TME1) == CAN_TSR_TME1) || \ ((hcan->Instance->TSR&CAN_TSR_TME2) == CAN_TSR_TME2)) - { + { /* Process locked */ __HAL_LOCK(hcan); - /* Change CAN state */ - switch(hcan->State) + if(hcan->State == HAL_CAN_STATE_BUSY_RX) { - case(HAL_CAN_STATE_BUSY_RX0): - hcan->State = HAL_CAN_STATE_BUSY_TX_RX0; - break; - case(HAL_CAN_STATE_BUSY_RX1): - hcan->State = HAL_CAN_STATE_BUSY_TX_RX1; - break; - case(HAL_CAN_STATE_BUSY_RX0_RX1): - hcan->State = HAL_CAN_STATE_BUSY_TX_RX0_RX1; - break; - default: /* HAL_CAN_STATE_READY */ - hcan->State = HAL_CAN_STATE_BUSY_TX; - break; + /* Change CAN state */ + hcan->State = HAL_CAN_STATE_BUSY_TX_RX; + } + else + { + /* Change CAN state */ + hcan->State = HAL_CAN_STATE_BUSY_TX; } /* Select one empty transmit mailbox */ if (HAL_IS_BIT_SET(hcan->Instance->TSR, CAN_TSR_TME0)) { - transmitmailbox = CAN_TXMAILBOX_0; + transmitmailbox = 0; } else if (HAL_IS_BIT_SET(hcan->Instance->TSR, CAN_TSR_TME1)) { - transmitmailbox = CAN_TXMAILBOX_1; + transmitmailbox = 1; } else { - transmitmailbox = CAN_TXMAILBOX_2; + transmitmailbox = 2; } /* Set up the Id */ @@ -604,35 +573,35 @@ HAL_StatusTypeDef HAL_CAN_Transmit(CAN_HandleTypeDef* hcan, uint32_t Timeout) if (hcan->pTxMsg->IDE == CAN_ID_STD) { assert_param(IS_CAN_STDID(hcan->pTxMsg->StdId)); - hcan->Instance->sTxMailBox[transmitmailbox].TIR |= ((hcan->pTxMsg->StdId << CAN_TI0R_STID_Pos) | + hcan->Instance->sTxMailBox[transmitmailbox].TIR |= ((hcan->pTxMsg->StdId << CAN_TI0R_STID_BIT_POSITION) | hcan->pTxMsg->RTR); } else { assert_param(IS_CAN_EXTID(hcan->pTxMsg->ExtId)); - hcan->Instance->sTxMailBox[transmitmailbox].TIR |= ((hcan->pTxMsg->ExtId << CAN_TI0R_EXID_Pos) | + hcan->Instance->sTxMailBox[transmitmailbox].TIR |= ((hcan->pTxMsg->ExtId << CAN_TI0R_EXID_BIT_POSITION) | hcan->pTxMsg->IDE | hcan->pTxMsg->RTR); } /* Set up the DLC */ hcan->pTxMsg->DLC &= (uint8_t)0x0000000F; - hcan->Instance->sTxMailBox[transmitmailbox].TDTR &= 0xFFFFFFF0U; + hcan->Instance->sTxMailBox[transmitmailbox].TDTR &= (uint32_t)0xFFFFFFF0; hcan->Instance->sTxMailBox[transmitmailbox].TDTR |= hcan->pTxMsg->DLC; /* Set up the data field */ - WRITE_REG(hcan->Instance->sTxMailBox[transmitmailbox].TDLR, ((uint32_t)hcan->pTxMsg->Data[3] << CAN_TDL0R_DATA3_Pos) | - ((uint32_t)hcan->pTxMsg->Data[2] << CAN_TDL0R_DATA2_Pos) | - ((uint32_t)hcan->pTxMsg->Data[1] << CAN_TDL0R_DATA1_Pos) | - ((uint32_t)hcan->pTxMsg->Data[0] << CAN_TDL0R_DATA0_Pos)); - WRITE_REG(hcan->Instance->sTxMailBox[transmitmailbox].TDHR, ((uint32_t)hcan->pTxMsg->Data[7] << CAN_TDL0R_DATA3_Pos) | - ((uint32_t)hcan->pTxMsg->Data[6] << CAN_TDL0R_DATA2_Pos) | - ((uint32_t)hcan->pTxMsg->Data[5] << CAN_TDL0R_DATA1_Pos) | - ((uint32_t)hcan->pTxMsg->Data[4] << CAN_TDL0R_DATA0_Pos)); + WRITE_REG(hcan->Instance->sTxMailBox[transmitmailbox].TDLR, ((uint32_t)hcan->pTxMsg->Data[3] << CAN_TDL0R_DATA3_BIT_POSITION) | + ((uint32_t)hcan->pTxMsg->Data[2] << CAN_TDL0R_DATA2_BIT_POSITION) | + ((uint32_t)hcan->pTxMsg->Data[1] << CAN_TDL0R_DATA1_BIT_POSITION) | + ((uint32_t)hcan->pTxMsg->Data[0] << CAN_TDL0R_DATA0_BIT_POSITION) ); + WRITE_REG(hcan->Instance->sTxMailBox[transmitmailbox].TDHR, ((uint32_t)hcan->pTxMsg->Data[7] << CAN_TDL0R_DATA3_BIT_POSITION) | + ((uint32_t)hcan->pTxMsg->Data[6] << CAN_TDL0R_DATA2_BIT_POSITION) | + ((uint32_t)hcan->pTxMsg->Data[5] << CAN_TDL0R_DATA1_BIT_POSITION) | + ((uint32_t)hcan->pTxMsg->Data[4] << CAN_TDL0R_DATA0_BIT_POSITION) ); /* Request transmission */ SET_BIT(hcan->Instance->sTxMailBox[transmitmailbox].TIR, CAN_TI0R_TXRQ); - /* Get tick */ + /* Get tick */ tickstart = HAL_GetTick(); /* Check End of transmission flag */ @@ -641,34 +610,24 @@ HAL_StatusTypeDef HAL_CAN_Transmit(CAN_HandleTypeDef* hcan, uint32_t Timeout) /* Check for the Timeout */ if(Timeout != HAL_MAX_DELAY) { - if((Timeout == 0U) || ((HAL_GetTick()-tickstart) > Timeout)) + if((Timeout == 0) || ((HAL_GetTick()-tickstart) > Timeout)) { hcan->State = HAL_CAN_STATE_TIMEOUT; - - /* Cancel transmission */ - __HAL_CAN_CANCEL_TRANSMIT(hcan, transmitmailbox); - /* Process unlocked */ __HAL_UNLOCK(hcan); return HAL_TIMEOUT; } } } - /* Change CAN state */ - switch(hcan->State) + if(hcan->State == HAL_CAN_STATE_BUSY_TX_RX) { - case(HAL_CAN_STATE_BUSY_TX_RX0): - hcan->State = HAL_CAN_STATE_BUSY_RX0; - break; - case(HAL_CAN_STATE_BUSY_TX_RX1): - hcan->State = HAL_CAN_STATE_BUSY_RX1; - break; - case(HAL_CAN_STATE_BUSY_TX_RX0_RX1): - hcan->State = HAL_CAN_STATE_BUSY_RX0_RX1; - break; - default: /* HAL_CAN_STATE_BUSY_TX */ - hcan->State = HAL_CAN_STATE_READY; - break; + /* Change CAN state */ + hcan->State = HAL_CAN_STATE_BUSY_RX; + } + else + { + /* Change CAN state */ + hcan->State = HAL_CAN_STATE_READY; } /* Process unlocked */ @@ -712,63 +671,57 @@ HAL_StatusTypeDef HAL_CAN_Transmit_IT(CAN_HandleTypeDef* hcan) /* Select one empty transmit mailbox */ if(HAL_IS_BIT_SET(hcan->Instance->TSR, CAN_TSR_TME0)) { - transmitmailbox = CAN_TXMAILBOX_0; + transmitmailbox = 0; } else if(HAL_IS_BIT_SET(hcan->Instance->TSR, CAN_TSR_TME1)) { - transmitmailbox = CAN_TXMAILBOX_1; + transmitmailbox = 1; } else { - transmitmailbox = CAN_TXMAILBOX_2; + transmitmailbox = 2; } /* Set up the Id */ hcan->Instance->sTxMailBox[transmitmailbox].TIR &= CAN_TI0R_TXRQ; - if(hcan->pTxMsg->IDE == CAN_ID_STD) + if (hcan->pTxMsg->IDE == CAN_ID_STD) { assert_param(IS_CAN_STDID(hcan->pTxMsg->StdId)); - hcan->Instance->sTxMailBox[transmitmailbox].TIR |= ((hcan->pTxMsg->StdId << CAN_TI0R_STID_Pos) | \ + hcan->Instance->sTxMailBox[transmitmailbox].TIR |= ((hcan->pTxMsg->StdId << CAN_TI0R_STID_BIT_POSITION) | hcan->pTxMsg->RTR); } else { assert_param(IS_CAN_EXTID(hcan->pTxMsg->ExtId)); - hcan->Instance->sTxMailBox[transmitmailbox].TIR |= ((hcan->pTxMsg->ExtId << CAN_TI0R_EXID_Pos) | \ + hcan->Instance->sTxMailBox[transmitmailbox].TIR |= ((hcan->pTxMsg->ExtId << CAN_TI0R_EXID_BIT_POSITION) | hcan->pTxMsg->IDE | hcan->pTxMsg->RTR); } /* Set up the DLC */ - hcan->pTxMsg->DLC &= (uint8_t)0x0000000FU; - hcan->Instance->sTxMailBox[transmitmailbox].TDTR &= 0xFFFFFFF0U; + hcan->pTxMsg->DLC &= (uint8_t)0x0000000F; + hcan->Instance->sTxMailBox[transmitmailbox].TDTR &= (uint32_t)0xFFFFFFF0; hcan->Instance->sTxMailBox[transmitmailbox].TDTR |= hcan->pTxMsg->DLC; /* Set up the data field */ - WRITE_REG(hcan->Instance->sTxMailBox[transmitmailbox].TDLR, ((uint32_t)hcan->pTxMsg->Data[3U] << CAN_TDL0R_DATA3_Pos) | - ((uint32_t)hcan->pTxMsg->Data[2U] << CAN_TDL0R_DATA2_Pos) | - ((uint32_t)hcan->pTxMsg->Data[1U] << CAN_TDL0R_DATA1_Pos) | - ((uint32_t)hcan->pTxMsg->Data[0U] << CAN_TDL0R_DATA0_Pos)); - WRITE_REG(hcan->Instance->sTxMailBox[transmitmailbox].TDHR, ((uint32_t)hcan->pTxMsg->Data[7U] << CAN_TDL0R_DATA3_Pos) | - ((uint32_t)hcan->pTxMsg->Data[6U] << CAN_TDL0R_DATA2_Pos) | - ((uint32_t)hcan->pTxMsg->Data[5U] << CAN_TDL0R_DATA1_Pos) | - ((uint32_t)hcan->pTxMsg->Data[4U] << CAN_TDL0R_DATA0_Pos)); - - /* Change CAN state */ - switch(hcan->State) + WRITE_REG(hcan->Instance->sTxMailBox[transmitmailbox].TDLR, ((uint32_t)hcan->pTxMsg->Data[3] << CAN_TDL0R_DATA3_BIT_POSITION) | + ((uint32_t)hcan->pTxMsg->Data[2] << CAN_TDL0R_DATA2_BIT_POSITION) | + ((uint32_t)hcan->pTxMsg->Data[1] << CAN_TDL0R_DATA1_BIT_POSITION) | + ((uint32_t)hcan->pTxMsg->Data[0] << CAN_TDL0R_DATA0_BIT_POSITION) ); + WRITE_REG(hcan->Instance->sTxMailBox[transmitmailbox].TDHR, ((uint32_t)hcan->pTxMsg->Data[7] << CAN_TDL0R_DATA3_BIT_POSITION) | + ((uint32_t)hcan->pTxMsg->Data[6] << CAN_TDL0R_DATA2_BIT_POSITION) | + ((uint32_t)hcan->pTxMsg->Data[5] << CAN_TDL0R_DATA1_BIT_POSITION) | + ((uint32_t)hcan->pTxMsg->Data[4] << CAN_TDL0R_DATA0_BIT_POSITION) ); + + if(hcan->State == HAL_CAN_STATE_BUSY_RX) { - case(HAL_CAN_STATE_BUSY_RX0): - hcan->State = HAL_CAN_STATE_BUSY_TX_RX0; - break; - case(HAL_CAN_STATE_BUSY_RX1): - hcan->State = HAL_CAN_STATE_BUSY_TX_RX1; - break; - case(HAL_CAN_STATE_BUSY_RX0_RX1): - hcan->State = HAL_CAN_STATE_BUSY_TX_RX0_RX1; - break; - default: /* HAL_CAN_STATE_READY */ - hcan->State = HAL_CAN_STATE_BUSY_TX; - break; + /* Change CAN state */ + hcan->State = HAL_CAN_STATE_BUSY_TX_RX; + } + else + { + /* Change CAN state */ + hcan->State = HAL_CAN_STATE_BUSY_TX; } /* Set CAN error code to none */ @@ -777,9 +730,6 @@ HAL_StatusTypeDef HAL_CAN_Transmit_IT(CAN_HandleTypeDef* hcan) /* Process Unlocked */ __HAL_UNLOCK(hcan); - /* Request transmission */ - hcan->Instance->sTxMailBox[transmitmailbox].TIR |= CAN_TI0R_TXRQ; - /* Enable interrupts: */ /* - Enable Error warning Interrupt */ /* - Enable Error passive Interrupt */ @@ -793,6 +743,9 @@ HAL_StatusTypeDef HAL_CAN_Transmit_IT(CAN_HandleTypeDef* hcan) CAN_IT_LEC | CAN_IT_ERR | CAN_IT_TME ); + + /* Request transmission */ + hcan->Instance->sTxMailBox[transmitmailbox].TIR |= CAN_TI0R_TXRQ; } else { @@ -813,129 +766,75 @@ HAL_StatusTypeDef HAL_CAN_Transmit_IT(CAN_HandleTypeDef* hcan) * @param FIFONumber: FIFO Number value * @param Timeout: Specify Timeout value * @retval HAL status + * @retval None */ HAL_StatusTypeDef HAL_CAN_Receive(CAN_HandleTypeDef* hcan, uint8_t FIFONumber, uint32_t Timeout) { - uint32_t tickstart = 0U; - CanRxMsgTypeDef* pRxMsg = NULL; - + uint32_t tickstart = 0; + /* Check the parameters */ assert_param(IS_CAN_FIFO(FIFONumber)); - - /* Check if CAN state is not busy for RX FIFO0 */ - if ((FIFONumber == CAN_FIFO0) && ((hcan->State == HAL_CAN_STATE_BUSY_RX0) || \ - (hcan->State == HAL_CAN_STATE_BUSY_TX_RX0) || \ - (hcan->State == HAL_CAN_STATE_BUSY_RX0_RX1) || \ - (hcan->State == HAL_CAN_STATE_BUSY_TX_RX0_RX1))) - { - return HAL_BUSY; - } - - /* Check if CAN state is not busy for RX FIFO1 */ - if ((FIFONumber == CAN_FIFO1) && ((hcan->State == HAL_CAN_STATE_BUSY_RX1) || \ - (hcan->State == HAL_CAN_STATE_BUSY_TX_RX1) || \ - (hcan->State == HAL_CAN_STATE_BUSY_RX0_RX1) || \ - (hcan->State == HAL_CAN_STATE_BUSY_TX_RX0_RX1))) - { - return HAL_BUSY; - } - + /* Process locked */ __HAL_LOCK(hcan); - - /* Change CAN state */ - if (FIFONumber == CAN_FIFO0) + + if(hcan->State == HAL_CAN_STATE_BUSY_TX) { - switch(hcan->State) - { - case(HAL_CAN_STATE_BUSY_TX): - hcan->State = HAL_CAN_STATE_BUSY_TX_RX0; - break; - case(HAL_CAN_STATE_BUSY_RX1): - hcan->State = HAL_CAN_STATE_BUSY_RX0_RX1; - break; - case(HAL_CAN_STATE_BUSY_TX_RX1): - hcan->State = HAL_CAN_STATE_BUSY_TX_RX0_RX1; - break; - default: /* HAL_CAN_STATE_READY */ - hcan->State = HAL_CAN_STATE_BUSY_RX0; - break; - } + /* Change CAN state */ + hcan->State = HAL_CAN_STATE_BUSY_TX_RX; } - else /* FIFONumber == CAN_FIFO1 */ + else { - switch(hcan->State) - { - case(HAL_CAN_STATE_BUSY_TX): - hcan->State = HAL_CAN_STATE_BUSY_TX_RX1; - break; - case(HAL_CAN_STATE_BUSY_RX0): - hcan->State = HAL_CAN_STATE_BUSY_RX0_RX1; - break; - case(HAL_CAN_STATE_BUSY_TX_RX0): - hcan->State = HAL_CAN_STATE_BUSY_TX_RX0_RX1; - break; - default: /* HAL_CAN_STATE_READY */ - hcan->State = HAL_CAN_STATE_BUSY_RX1; - break; - } + /* Change CAN state */ + hcan->State = HAL_CAN_STATE_BUSY_RX; } + /* Get tick */ tickstart = HAL_GetTick(); /* Check pending message */ - while(__HAL_CAN_MSG_PENDING(hcan, FIFONumber) == 0U) + while(__HAL_CAN_MSG_PENDING(hcan, FIFONumber) == 0) { /* Check for the Timeout */ if(Timeout != HAL_MAX_DELAY) { - if((Timeout == 0U) || ((HAL_GetTick()-tickstart) > Timeout)) + if((Timeout == 0) || ((HAL_GetTick()-tickstart) > Timeout)) { hcan->State = HAL_CAN_STATE_TIMEOUT; + /* Process unlocked */ __HAL_UNLOCK(hcan); + return HAL_TIMEOUT; } } } - - /* Set RxMsg pointer */ - if(FIFONumber == CAN_FIFO0) - { - pRxMsg = hcan->pRxMsg; - } - else /* FIFONumber == CAN_FIFO1 */ - { - pRxMsg = hcan->pRx1Msg; - } - + /* Get the Id */ - pRxMsg->IDE = (uint8_t)CAN_ID_EXT & hcan->Instance->sFIFOMailBox[FIFONumber].RIR; - if (pRxMsg->IDE == CAN_ID_STD) + hcan->pRxMsg->IDE = (uint8_t)CAN_ID_EXT & hcan->Instance->sFIFOMailBox[FIFONumber].RIR; + if (hcan->pRxMsg->IDE == CAN_ID_STD) { - pRxMsg->StdId = 0x000007FFU & (hcan->Instance->sFIFOMailBox[FIFONumber].RIR >> 21U); + hcan->pRxMsg->StdId = (uint32_t)0x000007FF & (hcan->Instance->sFIFOMailBox[FIFONumber].RIR >> 21); } else { - pRxMsg->ExtId = 0x1FFFFFFFU & (hcan->Instance->sFIFOMailBox[FIFONumber].RIR >> 3U); + hcan->pRxMsg->ExtId = (uint32_t)0x1FFFFFFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RIR >> 3); } - pRxMsg->RTR = (uint8_t)CAN_RTR_REMOTE & hcan->Instance->sFIFOMailBox[FIFONumber].RIR; + hcan->pRxMsg->RTR = (uint8_t)CAN_RTR_REMOTE & hcan->Instance->sFIFOMailBox[FIFONumber].RIR; /* Get the DLC */ - pRxMsg->DLC = (uint8_t)0x0FU & hcan->Instance->sFIFOMailBox[FIFONumber].RDTR; + hcan->pRxMsg->DLC = (uint8_t)0x0F & hcan->Instance->sFIFOMailBox[FIFONumber].RDTR; /* Get the FMI */ - pRxMsg->FMI = (uint8_t)0xFFU & (hcan->Instance->sFIFOMailBox[FIFONumber].RDTR >> 8U); - /* Get the FIFONumber */ - pRxMsg->FIFONumber = FIFONumber; + hcan->pRxMsg->FMI = (uint8_t)0xFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RDTR >> 8); /* Get the data field */ - pRxMsg->Data[0] = (uint8_t)0xFFU & hcan->Instance->sFIFOMailBox[FIFONumber].RDLR; - pRxMsg->Data[1] = (uint8_t)0xFFU & (hcan->Instance->sFIFOMailBox[FIFONumber].RDLR >> 8U); - pRxMsg->Data[2] = (uint8_t)0xFFU & (hcan->Instance->sFIFOMailBox[FIFONumber].RDLR >> 16U); - pRxMsg->Data[3] = (uint8_t)0xFFU & (hcan->Instance->sFIFOMailBox[FIFONumber].RDLR >> 24U); - pRxMsg->Data[4] = (uint8_t)0xFFU & hcan->Instance->sFIFOMailBox[FIFONumber].RDHR; - pRxMsg->Data[5] = (uint8_t)0xFFU & (hcan->Instance->sFIFOMailBox[FIFONumber].RDHR >> 8U); - pRxMsg->Data[6] = (uint8_t)0xFFU & (hcan->Instance->sFIFOMailBox[FIFONumber].RDHR >> 16U); - pRxMsg->Data[7] = (uint8_t)0xFFU & (hcan->Instance->sFIFOMailBox[FIFONumber].RDHR >> 24U); + hcan->pRxMsg->Data[0] = (uint8_t)0xFF & hcan->Instance->sFIFOMailBox[FIFONumber].RDLR; + hcan->pRxMsg->Data[1] = (uint8_t)0xFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RDLR >> 8); + hcan->pRxMsg->Data[2] = (uint8_t)0xFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RDLR >> 16); + hcan->pRxMsg->Data[3] = (uint8_t)0xFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RDLR >> 24); + hcan->pRxMsg->Data[4] = (uint8_t)0xFF & hcan->Instance->sFIFOMailBox[FIFONumber].RDHR; + hcan->pRxMsg->Data[5] = (uint8_t)0xFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RDHR >> 8); + hcan->pRxMsg->Data[6] = (uint8_t)0xFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RDHR >> 16); + hcan->pRxMsg->Data[7] = (uint8_t)0xFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RDHR >> 24); /* Release the FIFO */ if(FIFONumber == CAN_FIFO0) @@ -949,44 +848,17 @@ HAL_StatusTypeDef HAL_CAN_Receive(CAN_HandleTypeDef* hcan, uint8_t FIFONumber, u __HAL_CAN_FIFO_RELEASE(hcan, CAN_FIFO1); } - /* Change CAN state */ - if (FIFONumber == CAN_FIFO0) + if(hcan->State == HAL_CAN_STATE_BUSY_TX_RX) { - switch(hcan->State) - { - case(HAL_CAN_STATE_BUSY_TX_RX0): - hcan->State = HAL_CAN_STATE_BUSY_TX; - break; - case(HAL_CAN_STATE_BUSY_RX0_RX1): - hcan->State = HAL_CAN_STATE_BUSY_RX1; - break; - case(HAL_CAN_STATE_BUSY_TX_RX0_RX1): - hcan->State = HAL_CAN_STATE_BUSY_TX_RX1; - break; - default: /* HAL_CAN_STATE_BUSY_RX0 */ - hcan->State = HAL_CAN_STATE_READY; - break; - } + /* Change CAN state */ + hcan->State = HAL_CAN_STATE_BUSY_TX; } - else /* FIFONumber == CAN_FIFO1 */ + else { - switch(hcan->State) - { - case(HAL_CAN_STATE_BUSY_TX_RX1): - hcan->State = HAL_CAN_STATE_BUSY_TX; - break; - case(HAL_CAN_STATE_BUSY_RX0_RX1): - hcan->State = HAL_CAN_STATE_BUSY_RX0; - break; - case(HAL_CAN_STATE_BUSY_TX_RX0_RX1): - hcan->State = HAL_CAN_STATE_BUSY_TX_RX0; - break; - default: /* HAL_CAN_STATE_BUSY_RX1 */ - hcan->State = HAL_CAN_STATE_READY; - break; - } + /* Change CAN state */ + hcan->State = HAL_CAN_STATE_READY; } - + /* Process unlocked */ __HAL_UNLOCK(hcan); @@ -1000,102 +872,66 @@ HAL_StatusTypeDef HAL_CAN_Receive(CAN_HandleTypeDef* hcan, uint8_t FIFONumber, u * the configuration information for the specified CAN. * @param FIFONumber: Specify the FIFO number * @retval HAL status + * @retval None */ HAL_StatusTypeDef HAL_CAN_Receive_IT(CAN_HandleTypeDef* hcan, uint8_t FIFONumber) { /* Check the parameters */ assert_param(IS_CAN_FIFO(FIFONumber)); - /* Check if CAN state is not busy for RX FIFO0 */ - if((FIFONumber == CAN_FIFO0) && ((hcan->State == HAL_CAN_STATE_BUSY_RX0) || \ - (hcan->State == HAL_CAN_STATE_BUSY_TX_RX0) || \ - (hcan->State == HAL_CAN_STATE_BUSY_RX0_RX1) || \ - (hcan->State == HAL_CAN_STATE_BUSY_TX_RX0_RX1))) + if((hcan->State == HAL_CAN_STATE_READY) || (hcan->State == HAL_CAN_STATE_BUSY_TX)) { - return HAL_BUSY; - } - - /* Check if CAN state is not busy for RX FIFO1 */ - if((FIFONumber == CAN_FIFO1) && ((hcan->State == HAL_CAN_STATE_BUSY_RX1) || \ - (hcan->State == HAL_CAN_STATE_BUSY_TX_RX1) || \ - (hcan->State == HAL_CAN_STATE_BUSY_RX0_RX1) || \ - (hcan->State == HAL_CAN_STATE_BUSY_TX_RX0_RX1))) - { - return HAL_BUSY; - } + /* Process locked */ + __HAL_LOCK(hcan); + + if(hcan->State == HAL_CAN_STATE_BUSY_TX) + { + /* Change CAN state */ + hcan->State = HAL_CAN_STATE_BUSY_TX_RX; + } + else + { + /* Change CAN state */ + hcan->State = HAL_CAN_STATE_BUSY_RX; + } + + /* Set CAN error code to none */ + hcan->ErrorCode = HAL_CAN_ERROR_NONE; + + /* Enable interrupts: */ + /* - Enable Error warning Interrupt */ + /* - Enable Error passive Interrupt */ + /* - Enable Bus-off Interrupt */ + /* - Enable Last error code Interrupt */ + /* - Enable Error Interrupt */ + /* - Enable Transmit mailbox empty Interrupt */ + __HAL_CAN_ENABLE_IT(hcan, CAN_IT_EWG | + CAN_IT_EPV | + CAN_IT_BOF | + CAN_IT_LEC | + CAN_IT_ERR | + CAN_IT_TME ); - /* Process locked */ - __HAL_LOCK(hcan); + /* Process unlocked */ + __HAL_UNLOCK(hcan); - /* Change CAN state */ - if(FIFONumber == CAN_FIFO0) - { - switch(hcan->State) + if(FIFONumber == CAN_FIFO0) { - case(HAL_CAN_STATE_BUSY_TX): - hcan->State = HAL_CAN_STATE_BUSY_TX_RX0; - break; - case(HAL_CAN_STATE_BUSY_RX1): - hcan->State = HAL_CAN_STATE_BUSY_RX0_RX1; - break; - case(HAL_CAN_STATE_BUSY_TX_RX1): - hcan->State = HAL_CAN_STATE_BUSY_TX_RX0_RX1; - break; - default: /* HAL_CAN_STATE_READY */ - hcan->State = HAL_CAN_STATE_BUSY_RX0; - break; + /* Enable FIFO 0 message pending Interrupt */ + __HAL_CAN_ENABLE_IT(hcan, CAN_IT_FMP0); } - } - else /* FIFONumber == CAN_FIFO1 */ - { - switch(hcan->State) + else { - case(HAL_CAN_STATE_BUSY_TX): - hcan->State = HAL_CAN_STATE_BUSY_TX_RX1; - break; - case(HAL_CAN_STATE_BUSY_RX0): - hcan->State = HAL_CAN_STATE_BUSY_RX0_RX1; - break; - case(HAL_CAN_STATE_BUSY_TX_RX0): - hcan->State = HAL_CAN_STATE_BUSY_TX_RX0_RX1; - break; - default: /* HAL_CAN_STATE_READY */ - hcan->State = HAL_CAN_STATE_BUSY_RX1; - break; + /* Enable FIFO 1 message pending Interrupt */ + __HAL_CAN_ENABLE_IT(hcan, CAN_IT_FMP1); } - } - /* Set CAN error code to none */ - hcan->ErrorCode = HAL_CAN_ERROR_NONE; - - - /* Enable interrupts: */ - /* - Enable Error warning Interrupt */ - /* - Enable Error passive Interrupt */ - /* - Enable Bus-off Interrupt */ - /* - Enable Last error code Interrupt */ - /* - Enable Error Interrupt */ - /* - Enable Transmit mailbox empty Interrupt */ - __HAL_CAN_ENABLE_IT(hcan, CAN_IT_EWG | - CAN_IT_EPV | - CAN_IT_BOF | - CAN_IT_LEC | - CAN_IT_ERR | - CAN_IT_TME ); - - /* Process unlocked */ - __HAL_UNLOCK(hcan); - - if(FIFONumber == CAN_FIFO0) - { - /* Enable FIFO 0 overrun and message pending Interrupt */ - __HAL_CAN_ENABLE_IT(hcan, CAN_IT_FOV0 | CAN_IT_FMP0); + } else { - /* Enable FIFO 1 overrun and message pending Interrupt */ - __HAL_CAN_ENABLE_IT(hcan, CAN_IT_FOV1 | CAN_IT_FMP1); + return HAL_BUSY; } - + /* Return function status */ return HAL_OK; } @@ -1108,7 +944,7 @@ HAL_StatusTypeDef HAL_CAN_Receive_IT(CAN_HandleTypeDef* hcan, uint8_t FIFONumber */ HAL_StatusTypeDef HAL_CAN_Sleep(CAN_HandleTypeDef* hcan) { - uint32_t tickstart = 0U; + uint32_t tickstart = 0; /* Process locked */ __HAL_LOCK(hcan); @@ -1120,7 +956,7 @@ HAL_StatusTypeDef HAL_CAN_Sleep(CAN_HandleTypeDef* hcan) MODIFY_REG(hcan->Instance->MCR, CAN_MCR_INRQ , CAN_MCR_SLEEP ); - + /* Sleep mode status */ if (HAL_IS_BIT_CLR(hcan->Instance->MSR, CAN_MSR_SLAK) || HAL_IS_BIT_SET(hcan->Instance->MSR, CAN_MSR_INAK) ) @@ -1132,20 +968,20 @@ HAL_StatusTypeDef HAL_CAN_Sleep(CAN_HandleTypeDef* hcan) return HAL_ERROR; } - /* Get tick */ + /* Get tick */ tickstart = HAL_GetTick(); /* Wait the acknowledge */ while (HAL_IS_BIT_CLR(hcan->Instance->MSR, CAN_MSR_SLAK) || - HAL_IS_BIT_SET(hcan->Instance->MSR, CAN_MSR_INAK)) + HAL_IS_BIT_SET(hcan->Instance->MSR, CAN_MSR_INAK) ) { if((HAL_GetTick()-tickstart) > CAN_TIMEOUT_VALUE) { hcan->State = HAL_CAN_STATE_TIMEOUT; - + /* Process unlocked */ __HAL_UNLOCK(hcan); - + return HAL_TIMEOUT; } } @@ -1169,7 +1005,7 @@ HAL_StatusTypeDef HAL_CAN_Sleep(CAN_HandleTypeDef* hcan) */ HAL_StatusTypeDef HAL_CAN_WakeUp(CAN_HandleTypeDef* hcan) { - uint32_t tickstart = 0U; + uint32_t tickstart = 0; /* Process locked */ __HAL_LOCK(hcan); @@ -1189,8 +1025,10 @@ HAL_StatusTypeDef HAL_CAN_WakeUp(CAN_HandleTypeDef* hcan) if((HAL_GetTick()-tickstart) > CAN_TIMEOUT_VALUE) { hcan->State= HAL_CAN_STATE_TIMEOUT; + /* Process unlocked */ __HAL_UNLOCK(hcan); + return HAL_TIMEOUT; } } @@ -1221,125 +1059,70 @@ HAL_StatusTypeDef HAL_CAN_WakeUp(CAN_HandleTypeDef* hcan) */ void HAL_CAN_IRQHandler(CAN_HandleTypeDef* hcan) { - uint32_t tmp1 = 0U, tmp2 = 0U, tmp3 = 0U; - uint32_t errorcode = HAL_CAN_ERROR_NONE; - - /* Check Overrun flag for FIFO0 */ - tmp1 = __HAL_CAN_GET_FLAG(hcan, CAN_FLAG_FOV0); - tmp2 = __HAL_CAN_GET_IT_SOURCE(hcan, CAN_IT_FOV0); - if((tmp1 != 0U) && tmp2) - { - /* Set CAN error code to FOV0 error */ - errorcode |= HAL_CAN_ERROR_FOV0; - - /* Clear FIFO0 Overrun Flag */ - __HAL_CAN_CLEAR_FLAG(hcan, CAN_FLAG_FOV0); - } - - /* Check Overrun flag for FIFO1 */ - tmp1 = __HAL_CAN_GET_FLAG(hcan, CAN_FLAG_FOV1); - tmp2 = __HAL_CAN_GET_IT_SOURCE(hcan, CAN_IT_FOV1); - if((tmp1 != 0U) && tmp2) - { - /* Set CAN error code to FOV1 error */ - errorcode |= HAL_CAN_ERROR_FOV1; - - /* Clear FIFO1 Overrun Flag */ - __HAL_CAN_CLEAR_FLAG(hcan, CAN_FLAG_FOV1); - } - /* Check End of transmission flag */ if(__HAL_CAN_GET_IT_SOURCE(hcan, CAN_IT_TME)) { - /* Check Transmit request completion status */ - tmp1 = __HAL_CAN_TRANSMIT_STATUS(hcan, CAN_TXMAILBOX_0); - tmp2 = __HAL_CAN_TRANSMIT_STATUS(hcan, CAN_TXMAILBOX_1); - tmp3 = __HAL_CAN_TRANSMIT_STATUS(hcan, CAN_TXMAILBOX_2); - if(tmp1 || tmp2 || tmp3) + if((__HAL_CAN_TRANSMIT_STATUS(hcan, CAN_TXMAILBOX_0)) || + (__HAL_CAN_TRANSMIT_STATUS(hcan, CAN_TXMAILBOX_1)) || + (__HAL_CAN_TRANSMIT_STATUS(hcan, CAN_TXMAILBOX_2))) { - tmp1 = __HAL_CAN_GET_FLAG(hcan, CAN_FLAG_TXOK0); - tmp2 = __HAL_CAN_GET_FLAG(hcan, CAN_FLAG_TXOK1); - tmp3 = __HAL_CAN_GET_FLAG(hcan, CAN_FLAG_TXOK2); - /* Check Transmit success */ - if((tmp1) || (tmp2) || (tmp3)) - { - /* Call transmit function */ - CAN_Transmit_IT(hcan); - } - else /* Transmit failure */ - { - /* Set CAN error code to TXFAIL error */ - errorcode |= HAL_CAN_ERROR_TXFAIL; - } - - /* Clear transmission status flags (RQCPx and TXOKx) */ - SET_BIT(hcan->Instance->TSR, CAN_TSR_RQCP0 | CAN_TSR_RQCP1 | CAN_TSR_RQCP2 | \ - CAN_FLAG_TXOK0 | CAN_FLAG_TXOK1 | CAN_FLAG_TXOK2); + /* Call transmit function */ + CAN_Transmit_IT(hcan); } } - tmp1 = __HAL_CAN_MSG_PENDING(hcan, CAN_FIFO0); - tmp2 = __HAL_CAN_GET_IT_SOURCE(hcan, CAN_IT_FMP0); /* Check End of reception flag for FIFO0 */ - if((tmp1 != 0U) && tmp2) + if((__HAL_CAN_GET_IT_SOURCE(hcan, CAN_IT_FMP0)) && + (__HAL_CAN_MSG_PENDING(hcan, CAN_FIFO0) != 0)) { /* Call receive function */ CAN_Receive_IT(hcan, CAN_FIFO0); } - tmp1 = __HAL_CAN_MSG_PENDING(hcan, CAN_FIFO1); - tmp2 = __HAL_CAN_GET_IT_SOURCE(hcan, CAN_IT_FMP1); /* Check End of reception flag for FIFO1 */ - if((tmp1 != 0U) && tmp2) + if((__HAL_CAN_GET_IT_SOURCE(hcan, CAN_IT_FMP1)) && + (__HAL_CAN_MSG_PENDING(hcan, CAN_FIFO1) != 0)) { /* Call receive function */ CAN_Receive_IT(hcan, CAN_FIFO1); } - - /* Set error code in handle */ - hcan->ErrorCode |= errorcode; - - tmp1 = __HAL_CAN_GET_FLAG(hcan, CAN_FLAG_EWG); - tmp2 = __HAL_CAN_GET_IT_SOURCE(hcan, CAN_IT_EWG); - tmp3 = __HAL_CAN_GET_IT_SOURCE(hcan, CAN_IT_ERR); + /* Check Error Warning Flag */ - if(tmp1 && tmp2 && tmp3) + if((__HAL_CAN_GET_FLAG(hcan, CAN_FLAG_EWG)) && + (__HAL_CAN_GET_IT_SOURCE(hcan, CAN_IT_EWG)) && + (__HAL_CAN_GET_IT_SOURCE(hcan, CAN_IT_ERR))) { /* Set CAN error code to EWG error */ hcan->ErrorCode |= HAL_CAN_ERROR_EWG; /* No need for clear of Error Warning Flag as read-only */ } - tmp1 = __HAL_CAN_GET_FLAG(hcan, CAN_FLAG_EPV); - tmp2 = __HAL_CAN_GET_IT_SOURCE(hcan, CAN_IT_EPV); - tmp3 = __HAL_CAN_GET_IT_SOURCE(hcan, CAN_IT_ERR); /* Check Error Passive Flag */ - if(tmp1 && tmp2 && tmp3) + if((__HAL_CAN_GET_FLAG(hcan, CAN_FLAG_EPV)) && + (__HAL_CAN_GET_IT_SOURCE(hcan, CAN_IT_EPV)) && + (__HAL_CAN_GET_IT_SOURCE(hcan, CAN_IT_ERR))) { /* Set CAN error code to EPV error */ hcan->ErrorCode |= HAL_CAN_ERROR_EPV; /* No need for clear of Error Passive Flag as read-only */ } - tmp1 = __HAL_CAN_GET_FLAG(hcan, CAN_FLAG_BOF); - tmp2 = __HAL_CAN_GET_IT_SOURCE(hcan, CAN_IT_BOF); - tmp3 = __HAL_CAN_GET_IT_SOURCE(hcan, CAN_IT_ERR); /* Check Bus-Off Flag */ - if(tmp1 && tmp2 && tmp3) + if((__HAL_CAN_GET_FLAG(hcan, CAN_FLAG_BOF)) && + (__HAL_CAN_GET_IT_SOURCE(hcan, CAN_IT_BOF)) && + (__HAL_CAN_GET_IT_SOURCE(hcan, CAN_IT_ERR))) { /* Set CAN error code to BOF error */ hcan->ErrorCode |= HAL_CAN_ERROR_BOF; /* No need for clear of Bus-Off Flag as read-only */ } - tmp1 = HAL_IS_BIT_CLR(hcan->Instance->ESR, CAN_ESR_LEC); - tmp2 = __HAL_CAN_GET_IT_SOURCE(hcan, CAN_IT_LEC); - tmp3 = __HAL_CAN_GET_IT_SOURCE(hcan, CAN_IT_ERR); /* Check Last error code Flag */ - if((!tmp1) && tmp2 && tmp3) + if((!HAL_IS_BIT_CLR(hcan->Instance->ESR, CAN_ESR_LEC)) && + (__HAL_CAN_GET_IT_SOURCE(hcan, CAN_IT_LEC)) && + (__HAL_CAN_GET_IT_SOURCE(hcan, CAN_IT_ERR))) { - tmp1 = (hcan->Instance->ESR & CAN_ESR_LEC); - switch(tmp1) + switch(hcan->Instance->ESR & CAN_ESR_LEC) { case(CAN_ESR_LEC_0): /* Set CAN error code to STF error */ @@ -1372,37 +1155,15 @@ void HAL_CAN_IRQHandler(CAN_HandleTypeDef* hcan) /* Clear Last error code Flag */ CLEAR_BIT(hcan->Instance->ESR, CAN_ESR_LEC); } - + /* Call the Error call Back in case of Errors */ if(hcan->ErrorCode != HAL_CAN_ERROR_NONE) { /* Clear ERRI Flag */ - hcan->Instance->MSR = CAN_MSR_ERRI; + hcan->Instance->MSR |= CAN_MSR_ERRI; /* Set the CAN state ready to be able to start again the process */ hcan->State = HAL_CAN_STATE_READY; - - /* Disable interrupts: */ - /* - Disable Error warning Interrupt */ - /* - Disable Error passive Interrupt */ - /* - Disable Bus-off Interrupt */ - /* - Disable Last error code Interrupt */ - /* - Disable Error Interrupt */ - /* - Disable FIFO 0 message pending Interrupt */ - /* - Disable FIFO 0 Overrun Interrupt */ - /* - Disable FIFO 1 message pending Interrupt */ - /* - Disable FIFO 1 Overrun Interrupt */ - /* - Disable Transmit mailbox empty Interrupt */ - __HAL_CAN_DISABLE_IT(hcan, CAN_IT_EWG | - CAN_IT_EPV | - CAN_IT_BOF | - CAN_IT_LEC | - CAN_IT_ERR | - CAN_IT_FMP0| - CAN_IT_FOV0| - CAN_IT_FMP1| - CAN_IT_FOV1| - CAN_IT_TME ); - + /* Call Error callback function */ HAL_CAN_ErrorCallback(hcan); } @@ -1458,8 +1219,8 @@ __weak void HAL_CAN_ErrorCallback(CAN_HandleTypeDef *hcan) */ /** @defgroup CAN_Exported_Functions_Group3 Peripheral State and Error functions - * @brief CAN Peripheral State functions - * + * @brief CAN Peripheral State functions + * @verbatim ============================================================================== ##### Peripheral State and Error functions ##### @@ -1504,9 +1265,9 @@ uint32_t HAL_CAN_GetError(CAN_HandleTypeDef *hcan) * @} */ -/** @addtogroup CAN_Private_Functions - * @{ - */ +/** @defgroup CAN_Private_Functions CAN Private Functions + * @{ + */ /** * @brief Initiates and transmits a CAN frame message. * @param hcan: pointer to a CAN_HandleTypeDef structure that contains @@ -1530,26 +1291,20 @@ static HAL_StatusTypeDef CAN_Transmit_IT(CAN_HandleTypeDef* hcan) CAN_IT_EPV | CAN_IT_BOF | CAN_IT_LEC | - CAN_IT_ERR); + CAN_IT_ERR ); } - - /* Change CAN state */ - switch(hcan->State) + + if(hcan->State == HAL_CAN_STATE_BUSY_TX_RX) { - case(HAL_CAN_STATE_BUSY_TX_RX0): - hcan->State = HAL_CAN_STATE_BUSY_RX0; - break; - case(HAL_CAN_STATE_BUSY_TX_RX1): - hcan->State = HAL_CAN_STATE_BUSY_RX1; - break; - case(HAL_CAN_STATE_BUSY_TX_RX0_RX1): - hcan->State = HAL_CAN_STATE_BUSY_RX0_RX1; - break; - default: /* HAL_CAN_STATE_BUSY_TX */ - hcan->State = HAL_CAN_STATE_READY; - break; + /* Change CAN state */ + hcan->State = HAL_CAN_STATE_BUSY_RX; } - + else + { + /* Change CAN state */ + hcan->State = HAL_CAN_STATE_READY; + } + /* Transmission complete callback */ HAL_CAN_TxCpltCallback(hcan); @@ -1566,66 +1321,50 @@ static HAL_StatusTypeDef CAN_Transmit_IT(CAN_HandleTypeDef* hcan) */ static HAL_StatusTypeDef CAN_Receive_IT(CAN_HandleTypeDef* hcan, uint8_t FIFONumber) { - uint32_t tmp1 = 0U; - CanRxMsgTypeDef* pRxMsg = NULL; - - /* Set RxMsg pointer */ - if(FIFONumber == CAN_FIFO0) - { - pRxMsg = hcan->pRxMsg; - } - else /* FIFONumber == CAN_FIFO1 */ - { - pRxMsg = hcan->pRx1Msg; - } - /* Get the Id */ - pRxMsg->IDE = (uint8_t)0x04U & hcan->Instance->sFIFOMailBox[FIFONumber].RIR; - if (pRxMsg->IDE == CAN_ID_STD) + hcan->pRxMsg->IDE = (uint8_t)0x04 & hcan->Instance->sFIFOMailBox[FIFONumber].RIR; + if (hcan->pRxMsg->IDE == CAN_ID_STD) { - pRxMsg->StdId = 0x000007FFU & (hcan->Instance->sFIFOMailBox[FIFONumber].RIR >> 21U); + hcan->pRxMsg->StdId = (uint32_t)0x000007FF & (hcan->Instance->sFIFOMailBox[FIFONumber].RIR >> 21); } else { - pRxMsg->ExtId = 0x1FFFFFFFU & (hcan->Instance->sFIFOMailBox[FIFONumber].RIR >> 3U); + hcan->pRxMsg->ExtId = (uint32_t)0x1FFFFFFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RIR >> 3); } - pRxMsg->RTR = (uint8_t)0x02U & hcan->Instance->sFIFOMailBox[FIFONumber].RIR; + hcan->pRxMsg->RTR = (uint8_t)0x02 & hcan->Instance->sFIFOMailBox[FIFONumber].RIR; /* Get the DLC */ - pRxMsg->DLC = (uint8_t)0x0FU & hcan->Instance->sFIFOMailBox[FIFONumber].RDTR; - /* Get the FIFONumber */ - pRxMsg->FIFONumber = FIFONumber; + hcan->pRxMsg->DLC = (uint8_t)0x0F & hcan->Instance->sFIFOMailBox[FIFONumber].RDTR; /* Get the FMI */ - pRxMsg->FMI = (uint8_t)0xFFU & (hcan->Instance->sFIFOMailBox[FIFONumber].RDTR >> 8U); + hcan->pRxMsg->FMI = (uint8_t)0xFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RDTR >> 8); /* Get the data field */ - pRxMsg->Data[0] = (uint8_t)0xFFU & hcan->Instance->sFIFOMailBox[FIFONumber].RDLR; - pRxMsg->Data[1] = (uint8_t)0xFFU & (hcan->Instance->sFIFOMailBox[FIFONumber].RDLR >> 8U); - pRxMsg->Data[2] = (uint8_t)0xFFU & (hcan->Instance->sFIFOMailBox[FIFONumber].RDLR >> 16U); - pRxMsg->Data[3] = (uint8_t)0xFFU & (hcan->Instance->sFIFOMailBox[FIFONumber].RDLR >> 24U); - pRxMsg->Data[4] = (uint8_t)0xFFU & hcan->Instance->sFIFOMailBox[FIFONumber].RDHR; - pRxMsg->Data[5] = (uint8_t)0xFFU & (hcan->Instance->sFIFOMailBox[FIFONumber].RDHR >> 8U); - pRxMsg->Data[6] = (uint8_t)0xFFU & (hcan->Instance->sFIFOMailBox[FIFONumber].RDHR >> 16U); - pRxMsg->Data[7] = (uint8_t)0xFFU & (hcan->Instance->sFIFOMailBox[FIFONumber].RDHR >> 24U); + hcan->pRxMsg->Data[0] = (uint8_t)0xFF & hcan->Instance->sFIFOMailBox[FIFONumber].RDLR; + hcan->pRxMsg->Data[1] = (uint8_t)0xFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RDLR >> 8); + hcan->pRxMsg->Data[2] = (uint8_t)0xFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RDLR >> 16); + hcan->pRxMsg->Data[3] = (uint8_t)0xFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RDLR >> 24); + hcan->pRxMsg->Data[4] = (uint8_t)0xFF & hcan->Instance->sFIFOMailBox[FIFONumber].RDHR; + hcan->pRxMsg->Data[5] = (uint8_t)0xFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RDHR >> 8); + hcan->pRxMsg->Data[6] = (uint8_t)0xFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RDHR >> 16); + hcan->pRxMsg->Data[7] = (uint8_t)0xFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RDHR >> 24); /* Release the FIFO */ /* Release FIFO0 */ if (FIFONumber == CAN_FIFO0) { __HAL_CAN_FIFO_RELEASE(hcan, CAN_FIFO0); - /* Disable FIFO 0 overrun and message pending Interrupt */ - __HAL_CAN_DISABLE_IT(hcan, CAN_IT_FOV0 | CAN_IT_FMP0); + /* Disable FIFO 0 message pending Interrupt */ + __HAL_CAN_DISABLE_IT(hcan, CAN_IT_FMP0); } /* Release FIFO1 */ else /* FIFONumber == CAN_FIFO1 */ { __HAL_CAN_FIFO_RELEASE(hcan, CAN_FIFO1); - /* Disable FIFO 1 overrun and message pending Interrupt */ - __HAL_CAN_DISABLE_IT(hcan, CAN_IT_FOV1 | CAN_IT_FMP1); + /* Disable FIFO 1 message pending Interrupt */ + __HAL_CAN_DISABLE_IT(hcan, CAN_IT_FMP1); } - - tmp1 = hcan->State; - if((tmp1 == HAL_CAN_STATE_BUSY_RX0) || (tmp1 == HAL_CAN_STATE_BUSY_RX1)) + + if(hcan->State == HAL_CAN_STATE_BUSY_RX) { /* Disable interrupts: */ /* - Disable Error warning Interrupt */ @@ -1637,45 +1376,18 @@ static HAL_StatusTypeDef CAN_Receive_IT(CAN_HandleTypeDef* hcan, uint8_t FIFONum CAN_IT_EPV | CAN_IT_BOF | CAN_IT_LEC | - CAN_IT_ERR); + CAN_IT_ERR ); } - - /* Change CAN state */ - if (FIFONumber == CAN_FIFO0) + + if(hcan->State == HAL_CAN_STATE_BUSY_TX_RX) { - switch(hcan->State) - { - case(HAL_CAN_STATE_BUSY_TX_RX0): - hcan->State = HAL_CAN_STATE_BUSY_TX; - break; - case(HAL_CAN_STATE_BUSY_RX0_RX1): - hcan->State = HAL_CAN_STATE_BUSY_RX1; - break; - case(HAL_CAN_STATE_BUSY_TX_RX0_RX1): - hcan->State = HAL_CAN_STATE_BUSY_TX_RX1; - break; - default: /* HAL_CAN_STATE_BUSY_RX0 */ - hcan->State = HAL_CAN_STATE_READY; - break; - } + /* Disable CAN state */ + hcan->State = HAL_CAN_STATE_BUSY_TX; } - else /* FIFONumber == CAN_FIFO1 */ + else { - switch(hcan->State) - { - case(HAL_CAN_STATE_BUSY_TX_RX1): - hcan->State = HAL_CAN_STATE_BUSY_TX; - break; - case(HAL_CAN_STATE_BUSY_RX0_RX1): - hcan->State = HAL_CAN_STATE_BUSY_RX0; - break; - case(HAL_CAN_STATE_BUSY_TX_RX0_RX1): - hcan->State = HAL_CAN_STATE_BUSY_TX_RX0; - break; - default: /* HAL_CAN_STATE_BUSY_RX1 */ - hcan->State = HAL_CAN_STATE_READY; - break; - } + /* Change CAN state */ + hcan->State = HAL_CAN_STATE_READY; } /* Receive complete callback */ @@ -1686,15 +1398,18 @@ static HAL_StatusTypeDef CAN_Receive_IT(CAN_HandleTypeDef* hcan, uint8_t FIFONum } /** - * @} - */ -#endif /* STM32F103x6) || STM32F103xB || STM32F103xE || STM32F103xG) || STM32F105xC || STM32F107xC */ + * @} + */ -#endif /* HAL_CAN_MODULE_ENABLED */ /** * @} */ +#endif /* STM32F103x6) || STM32F103xB || STM32F103xE || */ + /* STM32F103xG) || STM32F105xC || STM32F107xC */ + +#endif /* HAL_CAN_MODULE_ENABLED */ + /** * @} */ diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_can.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_can.h index 9be1de209ad..79d3b330a2f 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_can.h +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_can.h @@ -2,13 +2,13 @@ ****************************************************************************** * @file stm32f1xx_hal_can.h * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief Header file of CAN HAL module. ****************************************************************************** * @attention * - *

© COPYRIGHT(c) 2017 STMicroelectronics

+ *

© COPYRIGHT(c) 2016 STMicroelectronics

* * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: @@ -36,13 +36,13 @@ */ /* Define to prevent recursive inclusion -------------------------------------*/ -#ifndef __STM32F1xx_HAL_CAN_H -#define __STM32F1xx_HAL_CAN_H +#ifndef __stm32f1xx_CAN_H +#define __stm32f1xx_CAN_H #ifdef __cplusplus extern "C" { #endif - + #if defined(STM32F103x6) || defined(STM32F103xB) || defined(STM32F103xE) || \ defined(STM32F103xG) || defined(STM32F105xC) || defined(STM32F107xC) @@ -60,41 +60,37 @@ /* Exported types ------------------------------------------------------------*/ /** @defgroup CAN_Exported_Types CAN Exported Types * @{ - */ - -/** - * @brief HAL State structures definition - */ + */ +/** + * @brief HAL State structures definition + */ typedef enum { - HAL_CAN_STATE_RESET = 0x00U, /*!< CAN not yet initialized or disabled */ - HAL_CAN_STATE_READY = 0x01U, /*!< CAN initialized and ready for use */ - HAL_CAN_STATE_BUSY = 0x02U, /*!< CAN process is ongoing */ - HAL_CAN_STATE_BUSY_TX = 0x12U, /*!< CAN process is ongoing */ - HAL_CAN_STATE_BUSY_RX0 = 0x22U, /*!< CAN process is ongoing */ - HAL_CAN_STATE_BUSY_RX1 = 0x32U, /*!< CAN process is ongoing */ - HAL_CAN_STATE_BUSY_TX_RX0 = 0x42U, /*!< CAN process is ongoing */ - HAL_CAN_STATE_BUSY_TX_RX1 = 0x52U, /*!< CAN process is ongoing */ - HAL_CAN_STATE_BUSY_RX0_RX1 = 0x62U, /*!< CAN process is ongoing */ - HAL_CAN_STATE_BUSY_TX_RX0_RX1 = 0x72U, /*!< CAN process is ongoing */ - HAL_CAN_STATE_TIMEOUT = 0x03U, /*!< CAN in Timeout state */ - HAL_CAN_STATE_ERROR = 0x04U /*!< CAN error state */ + HAL_CAN_STATE_RESET = 0x00, /*!< CAN not yet initialized or disabled */ + HAL_CAN_STATE_READY = 0x01, /*!< CAN initialized and ready for use */ + HAL_CAN_STATE_BUSY = 0x02, /*!< CAN process is ongoing */ + HAL_CAN_STATE_BUSY_TX = 0x12, /*!< CAN process is ongoing */ + HAL_CAN_STATE_BUSY_RX = 0x22, /*!< CAN process is ongoing */ + HAL_CAN_STATE_BUSY_TX_RX = 0x32, /*!< CAN process is ongoing */ + HAL_CAN_STATE_TIMEOUT = 0x03, /*!< CAN in Timeout state */ + HAL_CAN_STATE_ERROR = 0x04 /*!< CAN error state */ }HAL_CAN_StateTypeDef; -/** + +/** * @brief CAN init structure definition */ typedef struct { - uint32_t Prescaler; /*!< Specifies the length of a time quantum. - This parameter must be a number between Min_Data = 1 and Max_Data = 1024 */ - + uint32_t Prescaler; /*!< Specifies the length of a time quantum. + This parameter must be a number between Min_Data = 1 and Max_Data = 1024. */ + uint32_t Mode; /*!< Specifies the CAN operating mode. This parameter can be a value of @ref CAN_operating_mode */ - uint32_t SJW; /*!< Specifies the maximum number of time quanta - the CAN hardware is allowed to lengthen or + uint32_t SJW; /*!< Specifies the maximum number of time quanta + the CAN hardware is allowed to lengthen or shorten a bit to perform resynchronization. This parameter can be a value of @ref CAN_synchronisation_jump_width */ @@ -103,24 +99,24 @@ typedef struct uint32_t BS2; /*!< Specifies the number of time quanta in Bit Segment 2. This parameter can be a value of @ref CAN_time_quantum_in_bit_segment_2 */ - + uint32_t TTCM; /*!< Enable or disable the time triggered communication mode. This parameter can be set to ENABLE or DISABLE. */ - + uint32_t ABOM; /*!< Enable or disable the automatic bus-off management. - This parameter can be set to ENABLE or DISABLE */ + This parameter can be set to ENABLE or DISABLE. */ - uint32_t AWUM; /*!< Enable or disable the automatic wake-up mode. - This parameter can be set to ENABLE or DISABLE */ + uint32_t AWUM; /*!< Enable or disable the automatic wake-up mode. + This parameter can be set to ENABLE or DISABLE. */ uint32_t NART; /*!< Enable or disable the non-automatic retransmission mode. - This parameter can be set to ENABLE or DISABLE */ + This parameter can be set to ENABLE or DISABLE. */ - uint32_t RFLM; /*!< Enable or disable the receive FIFO Locked mode. - This parameter can be set to ENABLE or DISABLE */ + uint32_t RFLM; /*!< Enable or disable the Receive FIFO Locked mode. + This parameter can be set to ENABLE or DISABLE. */ uint32_t TXFP; /*!< Enable or disable the transmit FIFO priority. - This parameter can be set to ENABLE or DISABLE */ + This parameter can be set to ENABLE or DISABLE. */ }CAN_InitTypeDef; /** @@ -129,84 +125,81 @@ typedef struct typedef struct { uint32_t StdId; /*!< Specifies the standard identifier. - This parameter must be a number between Min_Data = 0 and Max_Data = 0x7FF */ - + This parameter must be a number between Min_Data = 0 and Max_Data = 0x7FF. */ + uint32_t ExtId; /*!< Specifies the extended identifier. - This parameter must be a number between Min_Data = 0 and Max_Data = 0x1FFFFFFF */ - + This parameter must be a number between Min_Data = 0 and Max_Data = 0x1FFFFFFF. */ + uint32_t IDE; /*!< Specifies the type of identifier for the message that will be transmitted. - This parameter can be a value of @ref CAN_Identifier_Type */ + This parameter can be a value of @ref CAN_identifier_type */ uint32_t RTR; /*!< Specifies the type of frame for the message that will be transmitted. This parameter can be a value of @ref CAN_remote_transmission_request */ uint32_t DLC; /*!< Specifies the length of the frame that will be transmitted. - This parameter must be a number between Min_Data = 0 and Max_Data = 8 */ - - uint8_t Data[8]; /*!< Contains the data to be transmitted. - This parameter must be a number between Min_Data = 0 and Max_Data = 0xFF */ + This parameter must be a number between Min_Data = 0 and Max_Data = 8. */ + uint8_t Data[8]; /*!< Contains the data to be transmitted. + This parameter must be a number between Min_Data = 0 and Max_Data = 0xFF. */ + }CanTxMsgTypeDef; -/** - * @brief CAN Rx message structure definition +/** + * @brief CAN Rx message structure definition */ typedef struct { uint32_t StdId; /*!< Specifies the standard identifier. - This parameter must be a number between Min_Data = 0 and Max_Data = 0x7FF */ + This parameter must be a number between Min_Data = 0 and Max_Data = 0x7FF. */ uint32_t ExtId; /*!< Specifies the extended identifier. - This parameter must be a number between Min_Data = 0 and Max_Data = 0x1FFFFFFF */ + This parameter must be a number between Min_Data = 0 and Max_Data = 0x1FFFFFFF. */ uint32_t IDE; /*!< Specifies the type of identifier for the message that will be received. - This parameter can be a value of @ref CAN_Identifier_Type */ + This parameter can be a value of @ref CAN_identifier_type */ uint32_t RTR; /*!< Specifies the type of frame for the received message. This parameter can be a value of @ref CAN_remote_transmission_request */ uint32_t DLC; /*!< Specifies the length of the frame that will be received. - This parameter must be a number between Min_Data = 0 and Max_Data = 8 */ + This parameter must be a number between Min_Data = 0 and Max_Data = 8. */ - uint8_t Data[8]; /*!< Contains the data to be received. - This parameter must be a number between Min_Data = 0 and Max_Data = 0xFF */ + uint8_t Data[8]; /*!< Contains the data to be received. + This parameter must be a number between Min_Data = 0 and Max_Data = 0xFF. */ uint32_t FMI; /*!< Specifies the index of the filter the message stored in the mailbox passes through. - This parameter must be a number between Min_Data = 0 and Max_Data = 0xFF */ + This parameter must be a number between Min_Data = 0 and Max_Data = 0xFF. */ - uint32_t FIFONumber; /*!< Specifies the receive FIFO number. - This parameter can be CAN_FIFO0 or CAN_FIFO1 */ + uint32_t FIFONumber; /*!< Specifies the receive FIFO number. + This parameter can be a value of @ref CAN_receive_FIFO_number_constants */ }CanRxMsgTypeDef; -/** - * @brief CAN handle Structure definition - */ +/** + * @brief CAN handle Structure definition + */ typedef struct { CAN_TypeDef *Instance; /*!< Register base address */ - + CAN_InitTypeDef Init; /*!< CAN required parameters */ - + CanTxMsgTypeDef* pTxMsg; /*!< Pointer to transmit structure */ - CanRxMsgTypeDef* pRxMsg; /*!< Pointer to reception structure for RX FIFO0 msg */ - - CanRxMsgTypeDef* pRx1Msg; /*!< Pointer to reception structure for RX FIFO1 msg */ - - __IO HAL_CAN_StateTypeDef State; /*!< CAN communication state */ - + CanRxMsgTypeDef* pRxMsg; /*!< Pointer to reception structure */ + HAL_LockTypeDef Lock; /*!< CAN locking object */ - + + __IO HAL_CAN_StateTypeDef State; /*!< CAN communication state */ + __IO uint32_t ErrorCode; /*!< CAN Error code */ - + }CAN_HandleTypeDef; - /** * @} */ - /* Exported constants --------------------------------------------------------*/ + /** @defgroup CAN_Exported_Constants CAN Exported Constants * @{ */ @@ -214,28 +207,30 @@ typedef struct /** @defgroup CAN_Error_Code CAN Error Code * @{ */ -#define HAL_CAN_ERROR_NONE 0x00000000U /*!< No error */ -#define HAL_CAN_ERROR_EWG 0x00000001U /*!< EWG error */ -#define HAL_CAN_ERROR_EPV 0x00000002U /*!< EPV error */ -#define HAL_CAN_ERROR_BOF 0x00000004U /*!< BOF error */ -#define HAL_CAN_ERROR_STF 0x00000008U /*!< Stuff error */ -#define HAL_CAN_ERROR_FOR 0x00000010U /*!< Form error */ -#define HAL_CAN_ERROR_ACK 0x00000020U /*!< Acknowledgment error */ -#define HAL_CAN_ERROR_BR 0x00000040U /*!< Bit recessive */ -#define HAL_CAN_ERROR_BD 0x00000080U /*!< LEC dominant */ -#define HAL_CAN_ERROR_CRC 0x00000100U /*!< LEC transfer error */ -#define HAL_CAN_ERROR_FOV0 0x00000200U /*!< FIFO0 overrun error */ -#define HAL_CAN_ERROR_FOV1 0x00000400U /*!< FIFO1 overrun error */ -#define HAL_CAN_ERROR_TXFAIL 0x00000800U /*!< Transmit failure */ + + +#define HAL_CAN_ERROR_NONE ((uint32_t)0x00) /*!< No error */ +#define HAL_CAN_ERROR_EWG ((uint32_t)0x01) /*!< EWG error */ +#define HAL_CAN_ERROR_EPV ((uint32_t)0x02) /*!< EPV error */ +#define HAL_CAN_ERROR_BOF ((uint32_t)0x04) /*!< BOF error */ +#define HAL_CAN_ERROR_STF ((uint32_t)0x08) /*!< Stuff error */ +#define HAL_CAN_ERROR_FOR ((uint32_t)0x10) /*!< Form error */ +#define HAL_CAN_ERROR_ACK ((uint32_t)0x20) /*!< Acknowledgment error */ +#define HAL_CAN_ERROR_BR ((uint32_t)0x40) /*!< Bit recessive */ +#define HAL_CAN_ERROR_BD ((uint32_t)0x80) /*!< LEC dominant */ +#define HAL_CAN_ERROR_CRC ((uint32_t)0x100) /*!< LEC transfer error */ + + /** * @} */ + /** @defgroup CAN_InitStatus CAN initialization Status * @{ */ -#define CAN_INITSTATUS_FAILED 0x00000000U /*!< CAN initialization failed */ -#define CAN_INITSTATUS_SUCCESS 0x00000001U /*!< CAN initialization OK */ +#define CAN_INITSTATUS_FAILED ((uint32_t)0x00000000) /*!< CAN initialization failed */ +#define CAN_INITSTATUS_SUCCESS ((uint32_t)0x00000001) /*!< CAN initialization OK */ /** * @} */ @@ -243,21 +238,24 @@ typedef struct /** @defgroup CAN_operating_mode CAN Operating Mode * @{ */ -#define CAN_MODE_NORMAL 0x00000000U /*!< Normal mode */ +#define CAN_MODE_NORMAL ((uint32_t)0x00000000) /*!< Normal mode */ #define CAN_MODE_LOOPBACK ((uint32_t)CAN_BTR_LBKM) /*!< Loopback mode */ #define CAN_MODE_SILENT ((uint32_t)CAN_BTR_SILM) /*!< Silent mode */ #define CAN_MODE_SILENT_LOOPBACK ((uint32_t)(CAN_BTR_LBKM | CAN_BTR_SILM)) /*!< Loopback combined with silent mode */ + /** * @} */ + /** @defgroup CAN_synchronisation_jump_width CAN Synchronization Jump Width * @{ */ -#define CAN_SJW_1TQ 0x00000000U /*!< 1 time quantum */ +#define CAN_SJW_1TQ ((uint32_t)0x00000000) /*!< 1 time quantum */ #define CAN_SJW_2TQ ((uint32_t)CAN_BTR_SJW_0) /*!< 2 time quantum */ #define CAN_SJW_3TQ ((uint32_t)CAN_BTR_SJW_1) /*!< 3 time quantum */ #define CAN_SJW_4TQ ((uint32_t)CAN_BTR_SJW) /*!< 4 time quantum */ + /** * @} */ @@ -265,7 +263,7 @@ typedef struct /** @defgroup CAN_time_quantum_in_bit_segment_1 CAN Time Quantum in Bit Segment 1 * @{ */ -#define CAN_BS1_1TQ 0x00000000U /*!< 1 time quantum */ +#define CAN_BS1_1TQ ((uint32_t)0x00000000) /*!< 1 time quantum */ #define CAN_BS1_2TQ ((uint32_t)CAN_BTR_TS1_0) /*!< 2 time quantum */ #define CAN_BS1_3TQ ((uint32_t)CAN_BTR_TS1_1) /*!< 3 time quantum */ #define CAN_BS1_4TQ ((uint32_t)(CAN_BTR_TS1_1 | CAN_BTR_TS1_0)) /*!< 4 time quantum */ @@ -281,14 +279,15 @@ typedef struct #define CAN_BS1_14TQ ((uint32_t)(CAN_BTR_TS1_3 | CAN_BTR_TS1_2 | CAN_BTR_TS1_0)) /*!< 14 time quantum */ #define CAN_BS1_15TQ ((uint32_t)(CAN_BTR_TS1_3 | CAN_BTR_TS1_2 | CAN_BTR_TS1_1)) /*!< 15 time quantum */ #define CAN_BS1_16TQ ((uint32_t)CAN_BTR_TS1) /*!< 16 time quantum */ + /** * @} */ -/** @defgroup CAN_time_quantum_in_bit_segment_2 CAN Time Quantum in bit segment 2 +/** @defgroup CAN_time_quantum_in_bit_segment_2 CAN Time Quantum in Bit Segment 2 * @{ */ -#define CAN_BS2_1TQ 0x00000000U /*!< 1 time quantum */ +#define CAN_BS2_1TQ ((uint32_t)0x00000000) /*!< 1 time quantum */ #define CAN_BS2_2TQ ((uint32_t)CAN_BTR_TS2_0) /*!< 2 time quantum */ #define CAN_BS2_3TQ ((uint32_t)CAN_BTR_TS2_1) /*!< 3 time quantum */ #define CAN_BS2_4TQ ((uint32_t)(CAN_BTR_TS2_1 | CAN_BTR_TS2_0)) /*!< 4 time quantum */ @@ -296,15 +295,17 @@ typedef struct #define CAN_BS2_6TQ ((uint32_t)(CAN_BTR_TS2_2 | CAN_BTR_TS2_0)) /*!< 6 time quantum */ #define CAN_BS2_7TQ ((uint32_t)(CAN_BTR_TS2_2 | CAN_BTR_TS2_1)) /*!< 7 time quantum */ #define CAN_BS2_8TQ ((uint32_t)CAN_BTR_TS2) /*!< 8 time quantum */ + /** * @} */ -/** @defgroup CAN_filter_mode CAN Filter Mode +/** @defgroup CAN_filter_mode CAN Filter Mode * @{ */ #define CAN_FILTERMODE_IDMASK ((uint8_t)0x00) /*!< Identifier mask mode */ #define CAN_FILTERMODE_IDLIST ((uint8_t)0x01) /*!< Identifier list mode */ + /** * @} */ @@ -314,6 +315,7 @@ typedef struct */ #define CAN_FILTERSCALE_16BIT ((uint8_t)0x00) /*!< Two 16-bit filters */ #define CAN_FILTERSCALE_32BIT ((uint8_t)0x01) /*!< One 32-bit filter */ + /** * @} */ @@ -323,15 +325,18 @@ typedef struct */ #define CAN_FILTER_FIFO0 ((uint8_t)0x00) /*!< Filter FIFO 0 assignment for filter x */ #define CAN_FILTER_FIFO1 ((uint8_t)0x01) /*!< Filter FIFO 1 assignment for filter x */ + + /** * @} */ -/** @defgroup CAN_Identifier_Type CAN Identifier Type +/** @defgroup CAN_identifier_type CAN Identifier Type * @{ */ -#define CAN_ID_STD 0x00000000U /*!< Standard Id */ -#define CAN_ID_EXT 0x00000004U /*!< Extended Id */ +#define CAN_ID_STD ((uint32_t)0x00000000) /*!< Standard Id */ +#define CAN_ID_EXT ((uint32_t)0x00000004) /*!< Extended Id */ + /** * @} */ @@ -339,8 +344,9 @@ typedef struct /** @defgroup CAN_remote_transmission_request CAN Remote Transmission Request * @{ */ -#define CAN_RTR_DATA 0x00000000U /*!< Data frame */ -#define CAN_RTR_REMOTE 0x00000002U /*!< Remote frame */ +#define CAN_RTR_DATA ((uint32_t)0x00000000) /*!< Data frame */ +#define CAN_RTR_REMOTE ((uint32_t)0x00000002) /*!< Remote frame */ + /** * @} */ @@ -349,6 +355,7 @@ typedef struct * @{ */ #define CAN_TXSTATUS_NOMAILBOX ((uint8_t)0x04) /*!< CAN cell did not provide CAN_TxStatus_NoMailBox */ + /** * @} */ @@ -358,6 +365,7 @@ typedef struct */ #define CAN_FIFO0 ((uint8_t)0x00) /*!< CAN FIFO 0 used to receive */ #define CAN_FIFO1 ((uint8_t)0x01) /*!< CAN FIFO 1 used to receive */ + /** * @} */ @@ -367,7 +375,7 @@ typedef struct */ /* If the flag is 0x3XXXXXXX, it means that it can be used with CAN_GetFlagStatus() and CAN_ClearFlag() functions. */ -/* If the flag is 0x1XXXXXXX, it means that it can only be used with +/* If the flag is 0x1XXXXXXX, it means that it can only be used with CAN_GetFlagStatus() function. */ /* Transmit Flags */ @@ -392,7 +400,6 @@ typedef struct #define CAN_FLAG_WKU ((uint32_t)((MSR_REGISTER_INDEX << 8U) | CAN_MSR_WKU_BIT_POSITION)) /*!< Wake up flag */ #define CAN_FLAG_SLAK ((uint32_t)((MSR_REGISTER_INDEX << 8U) | CAN_MSR_SLAK_BIT_POSITION)) /*!< Sleep acknowledge flag */ #define CAN_FLAG_SLAKI ((uint32_t)((MSR_REGISTER_INDEX << 8U) | CAN_MSR_SLAKI_BIT_POSITION)) /*!< Sleep acknowledge flag */ - /* @note When SLAK interrupt is disabled (SLKIE=0), no polling on SLAKI is possible. In this case the SLAK bit can be polled.*/ @@ -405,9 +412,10 @@ typedef struct * @} */ -/** @defgroup CAN_Interrupts CAN Interrupts + +/** @defgroup CAN_interrupts CAN Interrupts * @{ - */ + */ #define CAN_IT_TME ((uint32_t)CAN_IER_TMEIE) /*!< Transmit mailbox empty interrupt */ /* Receive Interrupts */ @@ -428,10 +436,14 @@ typedef struct #define CAN_IT_BOF ((uint32_t)CAN_IER_BOFIE) /*!< Bus-off interrupt */ #define CAN_IT_LEC ((uint32_t)CAN_IER_LECIE) /*!< Last error code interrupt */ #define CAN_IT_ERR ((uint32_t)CAN_IER_ERRIE) /*!< Error Interrupt */ + + /** * @} */ + + /** * @} */ @@ -441,54 +453,57 @@ typedef struct */ /* CAN intermediate shift values used for CAN flags */ -#define TSR_REGISTER_INDEX 0x5U -#define RF0R_REGISTER_INDEX 0x2U -#define RF1R_REGISTER_INDEX 0x4U -#define MSR_REGISTER_INDEX 0x1U -#define ESR_REGISTER_INDEX 0x3U +#define TSR_REGISTER_INDEX ((uint32_t)0x5) +#define RF0R_REGISTER_INDEX ((uint32_t)0x2) +#define RF1R_REGISTER_INDEX ((uint32_t)0x4) +#define MSR_REGISTER_INDEX ((uint32_t)0x1) +#define ESR_REGISTER_INDEX ((uint32_t)0x3) /* CAN flags bits position into their respective register (TSR, RF0R, RF1R or MSR regsiters) */ /* Transmit Flags */ -#define CAN_TSR_RQCP0_BIT_POSITION 0x00000000U -#define CAN_TSR_RQCP1_BIT_POSITION 0x00000008U -#define CAN_TSR_RQCP2_BIT_POSITION 0x00000010U -#define CAN_TSR_TXOK0_BIT_POSITION 0x00000001U -#define CAN_TSR_TXOK1_BIT_POSITION 0x00000009U -#define CAN_TSR_TXOK2_BIT_POSITION 0x00000011U -#define CAN_TSR_TME0_BIT_POSITION 0x0000001AU -#define CAN_TSR_TME1_BIT_POSITION 0x0000001BU -#define CAN_TSR_TME2_BIT_POSITION 0x0000001CU +#define CAN_TSR_RQCP0_BIT_POSITION ((uint32_t)0x00000000) +#define CAN_TSR_RQCP1_BIT_POSITION ((uint32_t)0x00000008) +#define CAN_TSR_RQCP2_BIT_POSITION ((uint32_t)0x00000010) +#define CAN_TSR_TXOK0_BIT_POSITION ((uint32_t)0x00000001) +#define CAN_TSR_TXOK1_BIT_POSITION ((uint32_t)0x00000009) +#define CAN_TSR_TXOK2_BIT_POSITION ((uint32_t)0x00000011) +#define CAN_TSR_TME0_BIT_POSITION ((uint32_t)0x0000001A) +#define CAN_TSR_TME1_BIT_POSITION ((uint32_t)0x0000001B) +#define CAN_TSR_TME2_BIT_POSITION ((uint32_t)0x0000001C) /* Receive Flags */ -#define CAN_RF0R_FF0_BIT_POSITION 0x00000003U -#define CAN_RF0R_FOV0_BIT_POSITION 0x00000004U +#define CAN_RF0R_FF0_BIT_POSITION ((uint32_t)0x00000003) +#define CAN_RF0R_FOV0_BIT_POSITION ((uint32_t)0x00000004) -#define CAN_RF1R_FF1_BIT_POSITION 0x00000003U -#define CAN_RF1R_FOV1_BIT_POSITION 0x00000004U +#define CAN_RF1R_FF1_BIT_POSITION ((uint32_t)0x00000003) +#define CAN_RF1R_FOV1_BIT_POSITION ((uint32_t)0x00000004) /* Operating Mode Flags */ -#define CAN_MSR_WKU_BIT_POSITION 0x00000003U -#define CAN_MSR_SLAK_BIT_POSITION 0x00000001U -#define CAN_MSR_SLAKI_BIT_POSITION 0x00000004U +#define CAN_MSR_WKU_BIT_POSITION ((uint32_t)0x00000003) +#define CAN_MSR_SLAK_BIT_POSITION ((uint32_t)0x00000001) +#define CAN_MSR_SLAKI_BIT_POSITION ((uint32_t)0x00000004) /* Error Flags */ -#define CAN_ESR_EWG_BIT_POSITION 0x00000000U -#define CAN_ESR_EPV_BIT_POSITION 0x00000001U -#define CAN_ESR_BOF_BIT_POSITION 0x00000002U +#define CAN_ESR_EWG_BIT_POSITION ((uint32_t)0x00000000) +#define CAN_ESR_EPV_BIT_POSITION ((uint32_t)0x00000001) +#define CAN_ESR_BOF_BIT_POSITION ((uint32_t)0x00000002) /* Mask used by macro to get/clear CAN flags*/ -#define CAN_FLAG_MASK 0x000000FFU +#define CAN_FLAG_MASK ((uint32_t)0x000000FF) /* Mailboxes definition */ #define CAN_TXMAILBOX_0 ((uint8_t)0x00) #define CAN_TXMAILBOX_1 ((uint8_t)0x01) #define CAN_TXMAILBOX_2 ((uint8_t)0x02) + + /** * @} */ + /* Exported macros -----------------------------------------------------------*/ -/** @defgroup CAN_Exported_Macros CAN Exported Macros +/** @defgroup CAN_Exported_Macro CAN Exported Macros * @{ */ @@ -551,7 +566,7 @@ typedef struct * @retval The number of pending message. */ #define __HAL_CAN_MSG_PENDING(__HANDLE__, __FIFONUMBER__) (((__FIFONUMBER__) == CAN_FIFO0)? \ -((uint8_t)((__HANDLE__)->Instance->RF0R & 0x03U)) : ((uint8_t)((__HANDLE__)->Instance->RF1R & 0x03U))) +((uint8_t)((__HANDLE__)->Instance->RF0R&(uint32_t)0x03)) : ((uint8_t)((__HANDLE__)->Instance->RF1R&(uint32_t)0x03))) /** @brief Check whether the specified CAN flag is set or not. * @param __HANDLE__: specifies the CAN Handle. @@ -581,10 +596,10 @@ typedef struct * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_CAN_GET_FLAG(__HANDLE__, __FLAG__) \ -((((__FLAG__) >> 8U) == 5U)? ((((__HANDLE__)->Instance->TSR) & (1U << ((__FLAG__) & CAN_FLAG_MASK))) == (1U << ((__FLAG__) & CAN_FLAG_MASK))): \ - (((__FLAG__) >> 8U) == 2U)? ((((__HANDLE__)->Instance->RF0R) & (1U << ((__FLAG__) & CAN_FLAG_MASK))) == (1U << ((__FLAG__) & CAN_FLAG_MASK))): \ - (((__FLAG__) >> 8U) == 4U)? ((((__HANDLE__)->Instance->RF1R) & (1U << ((__FLAG__) & CAN_FLAG_MASK))) == (1U << ((__FLAG__) & CAN_FLAG_MASK))): \ - (((__FLAG__) >> 8U) == 1U)? ((((__HANDLE__)->Instance->MSR) & (1U << ((__FLAG__) & CAN_FLAG_MASK))) == (1U << ((__FLAG__) & CAN_FLAG_MASK))): \ +((((__FLAG__) >> 8) == 5)? ((((__HANDLE__)->Instance->TSR) & (1U << ((__FLAG__) & CAN_FLAG_MASK))) == (1U << ((__FLAG__) & CAN_FLAG_MASK))): \ + (((__FLAG__) >> 8) == 2)? ((((__HANDLE__)->Instance->RF0R) & (1U << ((__FLAG__) & CAN_FLAG_MASK))) == (1U << ((__FLAG__) & CAN_FLAG_MASK))): \ + (((__FLAG__) >> 8) == 4)? ((((__HANDLE__)->Instance->RF1R) & (1U << ((__FLAG__) & CAN_FLAG_MASK))) == (1U << ((__FLAG__) & CAN_FLAG_MASK))): \ + (((__FLAG__) >> 8) == 1)? ((((__HANDLE__)->Instance->MSR) & (1U << ((__FLAG__) & CAN_FLAG_MASK))) == (1U << ((__FLAG__) & CAN_FLAG_MASK))): \ ((((__HANDLE__)->Instance->ESR) & (1U << ((__FLAG__) & CAN_FLAG_MASK))) == (1U << ((__FLAG__) & CAN_FLAG_MASK)))) /** @brief Clear the specified CAN pending flag. @@ -614,7 +629,8 @@ typedef struct ((((__FLAG__) >> 8U) == TSR_REGISTER_INDEX) ? (((__HANDLE__)->Instance->TSR) = (1U << ((__FLAG__) & CAN_FLAG_MASK))): \ (((__FLAG__) >> 8U) == RF0R_REGISTER_INDEX)? (((__HANDLE__)->Instance->RF0R) = (1U << ((__FLAG__) & CAN_FLAG_MASK))): \ (((__FLAG__) >> 8U) == RF1R_REGISTER_INDEX)? (((__HANDLE__)->Instance->RF1R) = (1U << ((__FLAG__) & CAN_FLAG_MASK))): \ - (((__FLAG__) >> 8U) == MSR_REGISTER_INDEX) ? (((__HANDLE__)->Instance->MSR) = (1U << ((__FLAG__) & CAN_FLAG_MASK))): 0U) + (((__FLAG__) >> 8U) == MSR_REGISTER_INDEX) ? (((__HANDLE__)->Instance->MSR) = (1U << ((__FLAG__) & CAN_FLAG_MASK))): 0) + /** @brief Check if the specified CAN interrupt source is enabled or disabled. * @param __HANDLE__: specifies the CAN Handle. @@ -645,9 +661,9 @@ typedef struct * @retval The new status of transmission (TRUE or FALSE). */ #define __HAL_CAN_TRANSMIT_STATUS(__HANDLE__, __TRANSMITMAILBOX__)\ -(((__TRANSMITMAILBOX__) == CAN_TXMAILBOX_0)? ((((__HANDLE__)->Instance->TSR) & (CAN_TSR_RQCP0 | CAN_TSR_TME0)) == (CAN_TSR_RQCP0 | CAN_TSR_TME0)) :\ - ((__TRANSMITMAILBOX__) == CAN_TXMAILBOX_1)? ((((__HANDLE__)->Instance->TSR) & (CAN_TSR_RQCP1 | CAN_TSR_TME1)) == (CAN_TSR_RQCP1 | CAN_TSR_TME1)) :\ - ((((__HANDLE__)->Instance->TSR) & (CAN_TSR_RQCP2 | CAN_TSR_TME2)) == (CAN_TSR_RQCP2 | CAN_TSR_TME2))) +(((__TRANSMITMAILBOX__) == CAN_TXMAILBOX_0)? ((((__HANDLE__)->Instance->TSR) & (CAN_TSR_RQCP0 | CAN_TSR_TXOK0 | CAN_TSR_TME0)) == (CAN_TSR_RQCP0 | CAN_TSR_TXOK0 | CAN_TSR_TME0)) :\ + ((__TRANSMITMAILBOX__) == CAN_TXMAILBOX_1)? ((((__HANDLE__)->Instance->TSR) & (CAN_TSR_RQCP1 | CAN_TSR_TXOK1 | CAN_TSR_TME1)) == (CAN_TSR_RQCP1 | CAN_TSR_TXOK1 | CAN_TSR_TME1)) :\ + ((((__HANDLE__)->Instance->TSR) & (CAN_TSR_RQCP2 | CAN_TSR_TXOK2 | CAN_TSR_TME2)) == (CAN_TSR_RQCP2 | CAN_TSR_TXOK2 | CAN_TSR_TME2))) /** * @brief Release the specified receive FIFO. @@ -656,7 +672,7 @@ typedef struct * @retval None. */ #define __HAL_CAN_FIFO_RELEASE(__HANDLE__, __FIFONUMBER__) (((__FIFONUMBER__) == CAN_FIFO0)? \ -((__HANDLE__)->Instance->RF0R = CAN_RF0R_RFOM0) : ((__HANDLE__)->Instance->RF1R = CAN_RF1R_RFOM1)) +((__HANDLE__)->Instance->RF0R |= CAN_RF0R_RFOM0) : ((__HANDLE__)->Instance->RF1R |= CAN_RF1R_RFOM1)) /** * @brief Cancel a transmit request. @@ -665,21 +681,68 @@ typedef struct * @retval None. */ #define __HAL_CAN_CANCEL_TRANSMIT(__HANDLE__, __TRANSMITMAILBOX__)\ -(((__TRANSMITMAILBOX__) == CAN_TXMAILBOX_0)? ((__HANDLE__)->Instance->TSR = CAN_TSR_ABRQ0) :\ - ((__TRANSMITMAILBOX__) == CAN_TXMAILBOX_1)? ((__HANDLE__)->Instance->TSR = CAN_TSR_ABRQ1) :\ - ((__HANDLE__)->Instance->TSR = CAN_TSR_ABRQ2)) +(((__TRANSMITMAILBOX__) == CAN_TXMAILBOX_0)? ((__HANDLE__)->Instance->TSR |= CAN_TSR_ABRQ0) :\ + ((__TRANSMITMAILBOX__) == CAN_TXMAILBOX_1)? ((__HANDLE__)->Instance->TSR |= CAN_TSR_ABRQ1) :\ + ((__HANDLE__)->Instance->TSR |= CAN_TSR_ABRQ2)) /** * @brief Enable or disables the DBG Freeze for CAN. * @param __HANDLE__: specifies the CAN Handle. - * @param __NEWSTATE__: new state of the CAN peripheral. + * @param __NEWSTATE__: new state of the CAN peripheral. * This parameter can be: ENABLE (CAN reception/transmission is frozen - * during debug. Reception FIFOs can still be accessed/controlled normally) + * during debug. Reception FIFOs can still be accessed/controlled normally) * or DISABLE (CAN is working during debug). * @retval None */ #define __HAL_CAN_DBG_FREEZE(__HANDLE__, __NEWSTATE__) (((__NEWSTATE__) == ENABLE)? \ -((__HANDLE__)->Instance->MCR |= CAN_MCR_DBF) : ((__HANDLE__)->Instance->MCR &= ~CAN_MCR_DBF)) +((__HANDLE__)->Instance->MCR |= CAN_MCR_DBF) : ((__HANDLE__)->Instance->MCR &= ~CAN_MCR_DBF)) + +/** + * @} + */ + +/* Private macros --------------------------------------------------------*/ +/** @defgroup CAN_Private_Macros CAN Private Macros + * @{ + */ + +#define IS_CAN_MODE(MODE) (((MODE) == CAN_MODE_NORMAL) || \ + ((MODE) == CAN_MODE_LOOPBACK)|| \ + ((MODE) == CAN_MODE_SILENT) || \ + ((MODE) == CAN_MODE_SILENT_LOOPBACK)) + +#define IS_CAN_SJW(SJW) (((SJW) == CAN_SJW_1TQ) || ((SJW) == CAN_SJW_2TQ)|| \ + ((SJW) == CAN_SJW_3TQ) || ((SJW) == CAN_SJW_4TQ)) + +#define IS_CAN_BS1(BS1) ((BS1) <= CAN_BS1_16TQ) + +#define IS_CAN_BS2(BS2) ((BS2) <= CAN_BS2_8TQ) + +#define IS_CAN_FILTER_MODE(MODE) (((MODE) == CAN_FILTERMODE_IDMASK) || \ + ((MODE) == CAN_FILTERMODE_IDLIST)) + +#define IS_CAN_FILTER_SCALE(SCALE) (((SCALE) == CAN_FILTERSCALE_16BIT) || \ + ((SCALE) == CAN_FILTERSCALE_32BIT)) + + +#define IS_CAN_FILTER_FIFO(FIFO) (((FIFO) == CAN_FILTER_FIFO0) || \ + ((FIFO) == CAN_FILTER_FIFO1)) + +#define IS_CAN_IDTYPE(IDTYPE) (((IDTYPE) == CAN_ID_STD) || \ + ((IDTYPE) == CAN_ID_EXT)) + +#define IS_CAN_RTR(RTR) (((RTR) == CAN_RTR_DATA) || ((RTR) == CAN_RTR_REMOTE)) + +#define IS_CAN_FIFO(FIFO) (((FIFO) == CAN_FIFO0) || ((FIFO) == CAN_FIFO1)) + +#define IS_CAN_BANKNUMBER(BANKNUMBER) ((BANKNUMBER) <= 28) + +#define IS_CAN_TRANSMITMAILBOX(TRANSMITMAILBOX) ((TRANSMITMAILBOX) <= ((uint8_t)0x02)) +#define IS_CAN_STDID(STDID) ((STDID) <= ((uint32_t)0x7FF)) +#define IS_CAN_EXTID(EXTID) ((EXTID) <= ((uint32_t)0x1FFFFFFF)) +#define IS_CAN_DLC(DLC) ((DLC) <= ((uint8_t)0x08)) + +#define IS_CAN_PRESCALER(PRESCALER) (((PRESCALER) >= 1) && ((PRESCALER) <= 1024)) /** * @} @@ -688,30 +751,30 @@ typedef struct /* Include CAN HAL Extension module */ #include "stm32f1xx_hal_can_ex.h" -/* Exported functions --------------------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ /** @addtogroup CAN_Exported_Functions * @{ */ - + /** @addtogroup CAN_Exported_Functions_Group1 - * @brief Initialization and Configuration functions - * @{ - */ -/* Initialization and de-initialization functions *****************************/ + * @brief Initialization and Configuration functions + * @{ + */ +/* Initialization and de-initialization functions *****************************/ HAL_StatusTypeDef HAL_CAN_Init(CAN_HandleTypeDef* hcan); HAL_StatusTypeDef HAL_CAN_ConfigFilter(CAN_HandleTypeDef* hcan, CAN_FilterConfTypeDef* sFilterConfig); HAL_StatusTypeDef HAL_CAN_DeInit(CAN_HandleTypeDef* hcan); void HAL_CAN_MspInit(CAN_HandleTypeDef* hcan); void HAL_CAN_MspDeInit(CAN_HandleTypeDef* hcan); /** - * @} - */ - + * @} + */ + /** @addtogroup CAN_Exported_Functions_Group2 - * @brief I/O operation functions - * @{ - */ -/* I/O operation functions *****************************************************/ + * @brief I/O operation functions + * @{ + */ +/* IO operation functions *****************************************************/ HAL_StatusTypeDef HAL_CAN_Transmit(CAN_HandleTypeDef *hcan, uint32_t Timeout); HAL_StatusTypeDef HAL_CAN_Transmit_IT(CAN_HandleTypeDef *hcan); HAL_StatusTypeDef HAL_CAN_Receive(CAN_HandleTypeDef *hcan, uint8_t FIFONumber, uint32_t Timeout); @@ -723,61 +786,24 @@ void HAL_CAN_TxCpltCallback(CAN_HandleTypeDef* hcan); void HAL_CAN_RxCpltCallback(CAN_HandleTypeDef* hcan); void HAL_CAN_ErrorCallback(CAN_HandleTypeDef *hcan); /** - * @} - */ - + * @} + */ + /** @addtogroup CAN_Exported_Functions_Group3 - * @brief CAN Peripheral State functions - * @{ - */ + * @brief CAN Peripheral State functions + * @{ + */ /* Peripheral State and Error functions ***************************************/ uint32_t HAL_CAN_GetError(CAN_HandleTypeDef *hcan); HAL_CAN_StateTypeDef HAL_CAN_GetState(CAN_HandleTypeDef* hcan); /** - * @} - */ - + * @} + */ + /** - * @} - */ - -/* Private macros --------------------------------------------------------*/ -/** @defgroup CAN_Private_Macros CAN Private Macros - * @{ - */ - -#define IS_CAN_MODE(MODE) (((MODE) == CAN_MODE_NORMAL) || \ - ((MODE) == CAN_MODE_LOOPBACK)|| \ - ((MODE) == CAN_MODE_SILENT) || \ - ((MODE) == CAN_MODE_SILENT_LOOPBACK)) -#define IS_CAN_SJW(SJW) (((SJW) == CAN_SJW_1TQ) || ((SJW) == CAN_SJW_2TQ)|| \ - ((SJW) == CAN_SJW_3TQ) || ((SJW) == CAN_SJW_4TQ)) -#define IS_CAN_BS1(BS1) ((BS1) <= CAN_BS1_16TQ) -#define IS_CAN_BS2(BS2) ((BS2) <= CAN_BS2_8TQ) -#define IS_CAN_PRESCALER(PRESCALER) (((PRESCALER) >= 1U) && ((PRESCALER) <= 1024U)) - -#define IS_CAN_FILTER_MODE(MODE) (((MODE) == CAN_FILTERMODE_IDMASK) || \ - ((MODE) == CAN_FILTERMODE_IDLIST)) -#define IS_CAN_FILTER_SCALE(SCALE) (((SCALE) == CAN_FILTERSCALE_16BIT) || \ - ((SCALE) == CAN_FILTERSCALE_32BIT)) -#define IS_CAN_FILTER_FIFO(FIFO) (((FIFO) == CAN_FILTER_FIFO0) || \ - ((FIFO) == CAN_FILTER_FIFO1)) -#define IS_CAN_BANKNUMBER(BANKNUMBER) ((BANKNUMBER) <= 28U) - -#define IS_CAN_TRANSMITMAILBOX(TRANSMITMAILBOX) ((TRANSMITMAILBOX) <= ((uint8_t)0x02)) -#define IS_CAN_STDID(STDID) ((STDID) <= 0x00007FFU) -#define IS_CAN_EXTID(EXTID) ((EXTID) <= 0x1FFFFFFFU) -#define IS_CAN_DLC(DLC) ((DLC) <= ((uint8_t)0x08)) - -#define IS_CAN_IDTYPE(IDTYPE) (((IDTYPE) == CAN_ID_STD) || \ - ((IDTYPE) == CAN_ID_EXT)) -#define IS_CAN_RTR(RTR) (((RTR) == CAN_RTR_DATA) || ((RTR) == CAN_RTR_REMOTE)) -#define IS_CAN_FIFO(FIFO) (((FIFO) == CAN_FIFO0) || ((FIFO) == CAN_FIFO1)) - -/** - * @} - */ - + * @} + */ + /** * @} */ @@ -786,13 +812,14 @@ HAL_CAN_StateTypeDef HAL_CAN_GetState(CAN_HandleTypeDef* hcan); * @} */ -#endif /* STM32F103x6) || STM32F103xB || STM32F103xE || STM32F103xG) || STM32F105xC || STM32F107xC */ +#endif /* STM32F103x6) || STM32F103xB || STM32F103xE || */ + /* STM32F103xG) || STM32F105xC || STM32F107xC */ #ifdef __cplusplus } #endif -#endif /* __STM32F1xx_HAL_CAN_H */ +#endif /* __stm32f1xx_CAN_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_can_ex.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_can_ex.h index 69995b52d0d..d7ea278000e 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_can_ex.h +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_can_ex.h @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_hal_can_ex.h * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief Header file of CAN HAL Extension module. ****************************************************************************** * @attention @@ -58,7 +58,7 @@ */ /* Exported types ------------------------------------------------------------*/ - + /** * @brief CAN filter configuration structure definition */ @@ -117,9 +117,9 @@ typedef struct * @{ */ #if defined(STM32F105xC) || defined(STM32F107xC) -#define IS_CAN_FILTER_NUMBER(NUMBER) ((NUMBER) <= 27U) +#define IS_CAN_FILTER_NUMBER(NUMBER) ((NUMBER) <= 27) #else -#define IS_CAN_FILTER_NUMBER(NUMBER) ((NUMBER) <= 13U) +#define IS_CAN_FILTER_NUMBER(NUMBER) ((NUMBER) <= 13) #endif /* STM32F105xC || STM32F107xC */ /** @@ -135,7 +135,8 @@ typedef struct * @} */ -#endif /* STM32F103x6) || STM32F103xB || STM32F103xE || STM32F103xG) || STM32F105xC || STM32F107xC */ +#endif /* STM32F103x6) || STM32F103xB || STM32F103xE || */ + /* STM32F103xG) || STM32F105xC || STM32F107xC */ #ifdef __cplusplus } diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_cec.c b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_cec.c index 96c61ac39ad..dc3ce1fd2c3 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_cec.c +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_cec.c @@ -2,46 +2,39 @@ ****************************************************************************** * @file stm32f1xx_hal_cec.c * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief CEC HAL module driver. * This file provides firmware functions to manage the following * functionalities of the High Definition Multimedia Interface * Consumer Electronics Control Peripheral (CEC). - * + Initialization and de-initialization function - * + IO operation function - * + Peripheral Control function - * - * - @verbatim - =============================================================================== + * + Initialization and de-initialization functions + * + IO operation functions + * + Peripheral Control functions + * + * @verbatim + ============================================================================== ##### How to use this driver ##### - =============================================================================== - [..] - The CEC HAL driver can be used as follow: - + ============================================================================== + [..] + The CEC HAL driver can be used as follows: (#) Declare a CEC_HandleTypeDef handle structure. (#) Initialize the CEC low level resources by implementing the HAL_CEC_MspInit ()API: (##) Enable the CEC interface clock. - (##) CEC pins configuration: - (+++) Enable the clock for the CEC GPIOs. - (+++) Configure these CEC pins as alternate function pull-up. + (##) Enable the clock for the CEC GPIOs. + (##) Configure these CEC pins as alternate function pull-up. (##) NVIC configuration if you need to use interrupt process (HAL_CEC_Transmit_IT() and HAL_CEC_Receive_IT() APIs): - (+++) Configure the CEC interrupt priority. - (+++) Enable the NVIC CEC IRQ handle. - (+++) The specific CEC interrupts (Transmission complete interrupt, - RXNE interrupt and Error Interrupts) will be managed using the macros - __HAL_CEC_ENABLE_IT() and __HAL_CEC_DISABLE_IT() inside the transmit - and receive process. + (##) Configure the CEC interrupt priority. + (##) Enable the NVIC CEC IRQ handle. + (##) The CEC interrupt is activated/deactivated by the HAL driver (#) Program the Bit Timing Error Mode and the Bit Period Error Mode in the hcec Init structure. (#) Initialize the CEC registers by calling the HAL_CEC_Init() API. - - [..] - (@) This API (HAL_CEC_Init()) configures also the low level Hardware (GPIO, CLOCK, CORTEX...etc) - by calling the customed HAL_CEC_MspInit() API. + + (#) This API (HAL_CEC_Init()) configures also the low level Hardware GPIO, CLOCK, CORTEX...etc) + by calling the customized HAL_CEC_MspInit() API. @endverbatim ****************************************************************************** @@ -89,7 +82,7 @@ * @brief HAL CEC module driver * @{ */ - + /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /** @defgroup CEC_Private_Constants CEC Private Constants @@ -101,8 +94,8 @@ #define CEC_ESR_ALL_ERROR (CEC_ESR_BTE|CEC_ESR_BPE|CEC_ESR_RBTFE|CEC_ESR_SBE|CEC_ESR_ACKE|CEC_ESR_LINE|CEC_ESR_TBTFE) #define CEC_RXXFERSIZE_INITIALIZE 0xFFFF /*!< Value used to initialise the RxXferSize of the handle */ /** - * @} - */ + * @} + */ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ @@ -113,9 +106,9 @@ static HAL_StatusTypeDef CEC_Transmit_IT(CEC_HandleTypeDef *hcec); static HAL_StatusTypeDef CEC_Receive_IT(CEC_HandleTypeDef *hcec); /** - * @} - */ - + * @} + */ + /* Exported functions ---------------------------------------------------------*/ /** @defgroup CEC_Exported_Functions CEC Exported Functions @@ -125,7 +118,7 @@ static HAL_StatusTypeDef CEC_Receive_IT(CEC_HandleTypeDef *hcec); /** @defgroup CEC_Exported_Functions_Group1 Initialization and de-initialization functions * @brief Initialization and Configuration functions * -@verbatim +@verbatim =============================================================================== ##### Initialization and Configuration functions ##### =============================================================================== @@ -149,7 +142,7 @@ static HAL_StatusTypeDef CEC_Receive_IT(CEC_HandleTypeDef *hcec); HAL_StatusTypeDef HAL_CEC_Init(CEC_HandleTypeDef *hcec) { /* Check the CEC handle allocation */ - if((hcec == NULL) ||(hcec->Init.RxBuffer == NULL)) + if(hcec == NULL) { return HAL_ERROR; } @@ -158,42 +151,40 @@ HAL_StatusTypeDef HAL_CEC_Init(CEC_HandleTypeDef *hcec) assert_param(IS_CEC_ALL_INSTANCE(hcec->Instance)); assert_param(IS_CEC_BIT_TIMING_ERROR_MODE(hcec->Init.TimingErrorFree)); assert_param(IS_CEC_BIT_PERIOD_ERROR_MODE(hcec->Init.PeriodErrorFree)); - assert_param(IS_CEC_ADDRESS(hcec->Init.OwnAddress)); + assert_param(IS_CEC_ADDRESS(hcec->Init.InitiatorAddress)); - if(hcec->gState == HAL_CEC_STATE_RESET) + if(hcec->State == HAL_CEC_STATE_RESET) { /* Allocate lock resource and initialize it */ hcec->Lock = HAL_UNLOCKED; /* Init the low level hardware : GPIO, CLOCK */ HAL_CEC_MspInit(hcec); } - hcec->gState = HAL_CEC_STATE_BUSY; + + hcec->State = HAL_CEC_STATE_BUSY; /* Disable the Peripheral */ __HAL_CEC_DISABLE(hcec); /* Write to CEC Control Register */ - MODIFY_REG(hcec->Instance->CFGR, CEC_CFGR_FIELDS, hcec->Init.TimingErrorFree | hcec->Init.PeriodErrorFree); + MODIFY_REG(hcec->Instance->CFGR, CEC_CFGR_FIELDS, hcec->Init.TimingErrorFree|hcec->Init.PeriodErrorFree); /* Write to CEC Own Address Register */ - MODIFY_REG(hcec->Instance->OAR, CEC_OAR_OA, hcec->Init.OwnAddress); + MODIFY_REG(hcec->Instance->OAR, CEC_OAR_OA, hcec->Init.InitiatorAddress); /* Configure the prescaler to generate the required 50 microseconds time base.*/ - MODIFY_REG(hcec->Instance->PRES, CEC_PRES_PRES, 50U * (HAL_RCC_GetPCLK1Freq()/1000000U) - 1U); + MODIFY_REG(hcec->Instance->PRES, CEC_PRES_PRES, 50*(HAL_RCC_GetPCLK1Freq()/1000000)-1); - /* Enable the following CEC Interrupt */ - __HAL_CEC_ENABLE_IT(hcec, CEC_IT_IE); - - /* Enable the CEC Peripheral */ + /* Enable the Peripheral */ __HAL_CEC_ENABLE(hcec); - - hcec->ErrorCode = HAL_CEC_ERROR_NONE; - hcec->gState = HAL_CEC_STATE_READY; - hcec->RxState = HAL_CEC_STATE_READY; + + hcec->State = HAL_CEC_STATE_READY; return HAL_OK; } + + /** * @brief DeInitializes the CEC peripheral * @param hcec: CEC handle @@ -210,17 +201,26 @@ HAL_StatusTypeDef HAL_CEC_DeInit(CEC_HandleTypeDef *hcec) /* Check the parameters */ assert_param(IS_CEC_ALL_INSTANCE(hcec->Instance)); - hcec->gState = HAL_CEC_STATE_BUSY; - + hcec->State = HAL_CEC_STATE_BUSY; + + /* Set peripheral to reset state */ + hcec->Instance->CFGR = 0x0; + hcec->Instance->OAR = 0x0; + hcec->Instance->PRES = 0x0; + hcec->Instance->CFGR = 0x0; + hcec->Instance->ESR = 0x0; + hcec->Instance->CSR = 0x0; + hcec->Instance->TXD = 0x0; + hcec->Instance->RXD = 0x0; + + /* Disable the Peripheral */ + __HAL_CEC_DISABLE(hcec); + /* DeInit the low level hardware */ HAL_CEC_MspDeInit(hcec); - __HAL_RCC_CEC_FORCE_RESET(); - __HAL_RCC_CEC_RELEASE_RESET(); - hcec->ErrorCode = HAL_CEC_ERROR_NONE; - hcec->gState = HAL_CEC_STATE_RESET; - hcec->RxState = HAL_CEC_STATE_RESET; + hcec->State = HAL_CEC_STATE_RESET; /* Process Unlock */ __HAL_UNLOCK(hcec); @@ -228,53 +228,6 @@ HAL_StatusTypeDef HAL_CEC_DeInit(CEC_HandleTypeDef *hcec) return HAL_OK; } -/** - * @brief Initializes the Own Address of the CEC device - * @param hcec: CEC handle - * @param CEC_OwnAddress: The CEC own address. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_CEC_SetDeviceAddress(CEC_HandleTypeDef *hcec, uint16_t CEC_OwnAddress) -{ - /* Check the parameters */ - assert_param(IS_CEC_OWN_ADDRESS(CEC_OwnAddress)); - - if ((hcec->gState == HAL_CEC_STATE_READY) && (hcec->RxState == HAL_CEC_STATE_READY)) - { - /* Process Locked */ - __HAL_LOCK(hcec); - - hcec->gState = HAL_CEC_STATE_BUSY; - - /* Disable the Peripheral */ - __HAL_CEC_DISABLE(hcec); - - if(CEC_OwnAddress != CEC_OWN_ADDRESS_NONE) - { - MODIFY_REG(hcec->Instance->OAR, CEC_OAR_OA, hcec->Init.OwnAddress); - } - else - { - CLEAR_BIT(hcec->Instance->OAR, CEC_OAR_OA); - } - - hcec->gState = HAL_CEC_STATE_READY; - hcec->ErrorCode = HAL_CEC_ERROR_NONE; - - /* Process Unlocked */ - __HAL_UNLOCK(hcec); - - /* Enable the Peripheral */ - __HAL_CEC_ENABLE(hcec); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - /** * @brief CEC MSP Init * @param hcec: CEC handle @@ -316,36 +269,318 @@ HAL_StatusTypeDef HAL_CEC_SetDeviceAddress(CEC_HandleTypeDef *hcec, uint16_t CEC =============================================================================== [..] This subsection provides a set of functions allowing to manage the CEC data transfers. - - (#) The CEC handle must contain the initiator (TX side) and the destination (RX side) - logical addresses (4-bit long addresses, 0xF for broadcast messages destination) - - (#) The communication is performed using Interrupts. + + (#) There are two modes of transfer: + (##) Blocking mode: The communication is performed in polling mode. + The HAL status of all data processing is returned by the same function + after finishing transfer. + (##) No-Blocking mode: The communication is performed using Interrupts. These API's return the HAL status. The end of the data processing will be indicated through the dedicated CEC IRQ when using Interrupt mode. The HAL_CEC_TxCpltCallback(), HAL_CEC_RxCpltCallback() user callbacks - will be executed respectively at the end of the transmit or Receive process - The HAL_CEC_ErrorCallback() user callback will be executed when a communication + will be executed respectivelly at the end of the Transmit or Receive process. + The HAL_CEC_ErrorCallback()user callback will be executed when a communication error is detected - - (#) API's with Interrupt are : - (+) HAL_CEC_Transmit_IT() - (+) HAL_CEC_IRQHandler() - - (#) A set of User Callbacks are provided: - (+) HAL_CEC_TxCpltCallback() - (+) HAL_CEC_RxCpltCallback() - (+) HAL_CEC_ErrorCallback() + (#) Blocking mode API's are : + (##) HAL_CEC_Transmit() + (##) HAL_CEC_Receive() + (#) Non-Blocking mode API's with Interrupt are : + (##) HAL_CEC_Transmit_IT() + (##) HAL_CEC_Receive_IT() + (##) HAL_CEC_IRQHandler() + (#) A set of Transfer Complete Callbacks are provided in No_Blocking mode: + (##) HAL_CEC_TxCpltCallback() + (##) HAL_CEC_RxCpltCallback() + (##) HAL_CEC_ErrorCallback() @endverbatim * @{ */ +/** + * @brief Send data in blocking mode + * @param hcec: CEC handle + * @param DestinationAddress: destination logical address + * @param pData: pointer to input byte data buffer + * @param Size: amount of data to be sent in bytes (without counting the header). + * 0 means only the header is sent (ping operation). + * Maximum TX size is 15 bytes (1 opcode and up to 14 operands). + * @param Timeout: Timeout duration. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_CEC_Transmit(CEC_HandleTypeDef *hcec, uint8_t DestinationAddress, uint8_t *pData, uint32_t Size, uint32_t Timeout) +{ + uint8_t temp = 0; + uint32_t tickstart = 0; + + /* If the IP is ready */ + if((hcec->State == HAL_CEC_STATE_READY) + && (__HAL_CEC_GET_TRANSMISSION_START_FLAG(hcec) == RESET)) + { + /* Basic check on pData pointer */ + if(((pData == NULL) && (Size > 0)) || (! IS_CEC_MSGSIZE(Size))) + { + return HAL_ERROR; + } + + assert_param(IS_CEC_ADDRESS(DestinationAddress)); + + /* Process Locked */ + __HAL_LOCK(hcec); + + /* Enter the transmit mode */ + hcec->State = HAL_CEC_STATE_BUSY_TX; + hcec->ErrorCode = HAL_CEC_ERROR_NONE; + + /* Initialize the number of bytes to send, + * 0 means only one header is sent (ping operation) */ + hcec->TxXferCount = Size; + + /* Send header block */ + temp = (uint8_t)((uint32_t)(hcec->Init.InitiatorAddress) << CEC_INITIATOR_LSB_POS) | DestinationAddress; + hcec->Instance->TXD = temp; + + /* In case no data to be sent, sender is only pinging the system */ + if (Size != 0) + { + /* Set TX Start of Message (TXSOM) bit */ + hcec->Instance->CSR = CEC_FLAG_TSOM; + } + else + { + /* Send a ping command */ + hcec->Instance->CSR = CEC_FLAG_TEOM|CEC_FLAG_TSOM; + } + + /* Polling TBTRF bit with timeout handling*/ + while (hcec->TxXferCount > 0) + { + /* Decreasing of the number of remaining data to receive */ + hcec->TxXferCount--; + + /* Timeout handling */ + tickstart = HAL_GetTick(); + + /* Waiting for the next data transmission */ + while(HAL_IS_BIT_CLR(hcec->Instance->CSR, CEC_FLAG_TBTRF)) + { + /* Timeout handling */ + if(Timeout != HAL_MAX_DELAY) + { + if((Timeout == 0) || ((HAL_GetTick()-tickstart) > Timeout)) + { + hcec->State = HAL_CEC_STATE_READY; + /* Process Unlocked */ + __HAL_UNLOCK(hcec); + return HAL_TIMEOUT; + } + } + + /* Check if an error occured */ + if(HAL_IS_BIT_SET(hcec->Instance->CSR, CEC_FLAG_TERR) || HAL_IS_BIT_SET(hcec->Instance->CSR, CEC_FLAG_RERR)) + { + /* Copy ESR for error handling purposes */ + hcec->ErrorCode = READ_BIT(hcec->Instance->ESR, CEC_ESR_ALL_ERROR); + + /* Acknowledgement of the error */ + __HAL_CEC_CLEAR_FLAG(hcec, CEC_FLAG_TERR); + __HAL_CEC_CLEAR_FLAG(hcec, CEC_FLAG_RERR); + + hcec->State = HAL_CEC_STATE_READY; + __HAL_UNLOCK(hcec); + return HAL_ERROR; + } + } + + /* Write the next data to TX buffer */ + hcec->Instance->TXD = *pData++; + + /* If this is the last byte of the ongoing transmission */ + if (hcec->TxXferCount == 0) + { + /* Acknowledge byte request and signal end of message */ + MODIFY_REG(hcec->Instance->CSR, CEC_FLAG_TRANSMIT_MASK, CEC_FLAG_TEOM); + } + else + { + /* Acknowledge byte request by writing 0x00 */ + MODIFY_REG(hcec->Instance->CSR, CEC_FLAG_TRANSMIT_MASK, 0x00); + } + } + + /* Timeout handling */ + tickstart = HAL_GetTick(); + + /* Wait for message transmission completion (TBTRF is set) */ + while (HAL_IS_BIT_CLR(hcec->Instance->CSR, CEC_FLAG_TBTRF)) + { + /* Timeout handling */ + if(Timeout != HAL_MAX_DELAY) + { + if((Timeout == 0) || ((HAL_GetTick()-tickstart) > Timeout)) + { + hcec->State = HAL_CEC_STATE_READY; + __HAL_UNLOCK(hcec); + return HAL_TIMEOUT; + } + } + + /* Check of error during transmission of the last byte */ + if(HAL_IS_BIT_SET(hcec->Instance->CSR, CEC_FLAG_TERR) || HAL_IS_BIT_SET(hcec->Instance->CSR, CEC_FLAG_RERR)) + { + /* Copy ESR for error handling purposes */ + hcec->ErrorCode = READ_BIT(hcec->Instance->ESR, CEC_ESR_ALL_ERROR); + + /* Acknowledgement of the error */ + __HAL_CEC_CLEAR_FLAG(hcec, CEC_FLAG_TERR); + __HAL_CEC_CLEAR_FLAG(hcec, CEC_FLAG_RERR); + + hcec->State = HAL_CEC_STATE_READY; + __HAL_UNLOCK(hcec); + return HAL_ERROR; + } + } + + /* Check of error after the last byte transmission */ + if(HAL_IS_BIT_SET(hcec->Instance->CSR, CEC_FLAG_TERR) || HAL_IS_BIT_SET(hcec->Instance->CSR, CEC_FLAG_RERR)) + { + /* Copy ESR for error handling purposes */ + hcec->ErrorCode = READ_BIT(hcec->Instance->ESR, CEC_ESR_ALL_ERROR); + + /* Acknowledgement of the error */ + __HAL_CEC_CLEAR_FLAG(hcec, CEC_FLAG_TERR); + __HAL_CEC_CLEAR_FLAG(hcec, CEC_FLAG_RERR); + + hcec->State = HAL_CEC_STATE_READY; + __HAL_UNLOCK(hcec); + return HAL_ERROR; + } + + /* Acknowledge successful completion by writing 0x00 */ + MODIFY_REG(hcec->Instance->CSR, CEC_FLAG_TRANSMIT_MASK, 0x00); + + hcec->State = HAL_CEC_STATE_READY; + __HAL_UNLOCK(hcec); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive data in blocking mode. + * @param hcec: CEC handle + * @param pData: pointer to received data buffer. + * @param Timeout: Timeout duration. + * @note The received data size is not known beforehand, the latter is known + * when the reception is complete and is stored in hcec->RxXferSize. + * hcec->RxXferSize is the sum of opcodes + operands (0 to 14 operands max). + * If only a header is received, hcec->RxXferSize = 0 + * @retval HAL status + */ +HAL_StatusTypeDef HAL_CEC_Receive(CEC_HandleTypeDef *hcec, uint8_t *pData, uint32_t Timeout) +{ + uint32_t temp = 0; + uint32_t tickstart = 0; + + if(hcec->State == HAL_CEC_STATE_READY) + { + if(pData == NULL) + { + return HAL_ERROR; + } + + /* When a ping is received, RxXferSize is 0*/ + /* When a message is received, RxXferSize contains the number of received bytes */ + hcec->RxXferSize = CEC_RXXFERSIZE_INITIALIZE; + + /* Process Locked */ + __HAL_LOCK(hcec); + + hcec->ErrorCode = HAL_CEC_ERROR_NONE; + + /* Continue the reception until the End Of Message is received (CEC_FLAG_REOM) */ + do + { + /* Timeout handling */ + tickstart = HAL_GetTick(); + + /* Wait for next byte to be received */ + while (HAL_IS_BIT_CLR(hcec->Instance->CSR, CEC_FLAG_RBTF)) + { + /* Timeout handling */ + if(Timeout != HAL_MAX_DELAY) + { + if((Timeout == 0) || ((HAL_GetTick()-tickstart) > Timeout)) + { + hcec->State = HAL_CEC_STATE_READY; + __HAL_UNLOCK(hcec); + return HAL_TIMEOUT; + } + } + + /* Check if an error occured during the reception */ + if(HAL_IS_BIT_SET(hcec->Instance->CSR, CEC_FLAG_RERR)) + { + /* Copy ESR for error handling purposes */ + hcec->ErrorCode = READ_BIT(hcec->Instance->ESR, CEC_ESR_ALL_ERROR); + + /* Acknowledgement of the error */ + __HAL_CEC_CLEAR_FLAG(hcec, CEC_FLAG_RERR); + + hcec->State = HAL_CEC_STATE_READY; + __HAL_UNLOCK(hcec); + return HAL_ERROR; + } + } + + /* Keep the value of CSR register as the register is cleared during reception process */ + temp = hcec->Instance->CSR; + + /* Read received data */ + *pData++ = hcec->Instance->RXD; + + /* Acknowledge received byte by writing 0x00 */ + CLEAR_BIT(hcec->Instance->CSR, CEC_FLAG_RECEIVE_MASK); + + /* Increment the number of received data */ + if(hcec->RxXferSize == CEC_RXXFERSIZE_INITIALIZE) + { + hcec->RxXferSize = 0; + } + else + { + hcec->RxXferSize++; + } + + }while (HAL_IS_BIT_CLR(temp, CEC_FLAG_REOM)); + + hcec->State = HAL_CEC_STATE_READY; + __HAL_UNLOCK(hcec); + + if(IS_CEC_MSGSIZE(hcec->RxXferSize)) + { + return HAL_OK; + } + else + { + return HAL_ERROR; + } + } + else + { + return HAL_BUSY; + } +} + + /** * @brief Send data in interrupt mode * @param hcec: CEC handle - * @param InitiatorAddress: Initiator address * @param DestinationAddress: destination logical address * @param pData: pointer to input byte data buffer * @param Size: amount of data to be sent in bytes (without counting the header). @@ -353,33 +588,52 @@ HAL_StatusTypeDef HAL_CEC_SetDeviceAddress(CEC_HandleTypeDef *hcec, uint16_t CEC * Maximum TX size is 15 bytes (1 opcode and up to 14 operands). * @retval HAL status */ -HAL_StatusTypeDef HAL_CEC_Transmit_IT(CEC_HandleTypeDef *hcec, uint8_t InitiatorAddress,uint8_t DestinationAddress, uint8_t *pData, uint32_t Size) +HAL_StatusTypeDef HAL_CEC_Transmit_IT(CEC_HandleTypeDef *hcec, uint8_t DestinationAddress, uint8_t *pData, uint32_t Size) { - /* if the IP isn't already busy and if there is no previous transmission - already pending due to arbitration lost */ - if(hcec->gState == HAL_CEC_STATE_READY) - { - if((pData == NULL ) && (Size > 0U)) + uint8_t temp = 0; + uint32_t tmp_state = 0; + + tmp_state = hcec->State; + if(((tmp_state == HAL_CEC_STATE_READY) || (tmp_state == HAL_CEC_STATE_BUSY_RX)) + && (__HAL_CEC_GET_TRANSMISSION_START_FLAG(hcec) == RESET)) + { + + /* Basic check on pData pointer */ + if(((pData == NULL) && (Size > 0)) || (! IS_CEC_MSGSIZE(Size))) { return HAL_ERROR; } assert_param(IS_CEC_ADDRESS(DestinationAddress)); - assert_param(IS_CEC_ADDRESS(InitiatorAddress)); - assert_param(IS_CEC_MSGSIZE(Size)); /* Process Locked */ __HAL_LOCK(hcec); hcec->pTxBuffPtr = pData; - hcec->gState = HAL_CEC_STATE_BUSY_TX; + + /* Check if a receive process is ongoing or not */ + if(hcec->State == HAL_CEC_STATE_BUSY_RX) + { + hcec->State = HAL_CEC_STATE_BUSY_TX_RX; + + /* Interrupt are not enabled here because they are already enabled in the Reception process */ + } + else + { + hcec->State = HAL_CEC_STATE_BUSY_TX; + + /* Enable the CEC interrupt */ + __HAL_CEC_ENABLE_IT(hcec, CEC_IT_IE); + } + hcec->ErrorCode = HAL_CEC_ERROR_NONE; - + /* initialize the number of bytes to send, * 0 means only one header is sent (ping operation) */ hcec->TxXferCount = Size; /* send header block */ - hcec->Instance->TXD = (uint8_t)((uint32_t)InitiatorAddress << CEC_INITIATOR_LSB_POS) | DestinationAddress; + temp = (uint8_t)((uint32_t)(hcec->Init.InitiatorAddress) << CEC_INITIATOR_LSB_POS) | DestinationAddress; + hcec->Instance->TXD = temp; /* Process Unlocked */ __HAL_UNLOCK(hcec); @@ -396,7 +650,6 @@ HAL_StatusTypeDef HAL_CEC_Transmit_IT(CEC_HandleTypeDef *hcec, uint8_t Initiator MODIFY_REG(hcec->Instance->CSR, CEC_FLAG_TRANSMIT_MASK, CEC_FLAG_TEOM|CEC_FLAG_TSOM); } return HAL_OK; - } else { @@ -404,26 +657,70 @@ HAL_StatusTypeDef HAL_CEC_Transmit_IT(CEC_HandleTypeDef *hcec, uint8_t Initiator } } + /** - * @brief Get size of the received frame. + * @brief Receive data in interrupt mode. * @param hcec: CEC handle - * @retval Frame size + * @param pData: pointer to received data buffer. + * @note The received data size is not known beforehand, the latter is known + * when the reception is complete and is stored in hcec->RxXferSize. + * hcec->RxXferSize is the sum of opcodes + operands (0 to 14 operands max). + * If only a header is received, hcec->RxXferSize = 0 + * @retval HAL status */ -uint32_t HAL_CEC_GetLastReceivedFrameSize(CEC_HandleTypeDef *hcec) +HAL_StatusTypeDef HAL_CEC_Receive_IT(CEC_HandleTypeDef *hcec, uint8_t *pData) { - return hcec->RxXferSize; + uint32_t tmp_state = 0; + tmp_state = hcec->State; + if((tmp_state == HAL_CEC_STATE_READY) || (tmp_state == HAL_CEC_STATE_BUSY_TX)) + { + if(pData == NULL) + { + return HAL_ERROR; + } + + /* When a ping is received, RxXferSize is 0 */ + /* When a message is received, RxXferSize contains the number of received bytes */ + hcec->RxXferSize = CEC_RXXFERSIZE_INITIALIZE; + + /* Process Locked */ + __HAL_LOCK(hcec); + + hcec->pRxBuffPtr = pData; + hcec->ErrorCode = HAL_CEC_ERROR_NONE; + + /* Process Unlocked */ + __HAL_UNLOCK(hcec); + + /* Check if a transmit process is ongoing or not */ + if(hcec->State == HAL_CEC_STATE_BUSY_TX) + { + hcec->State = HAL_CEC_STATE_BUSY_TX_RX; + } + else + { + hcec->State = HAL_CEC_STATE_BUSY_RX; + + /* Enable CEC interrupt */ + __HAL_CEC_ENABLE_IT(hcec, CEC_IT_IE); + } + + return HAL_OK; + } + else + { + return HAL_BUSY; + } } /** - * @brief Change Rx Buffer. + * @brief Get size of the received frame. * @param hcec: CEC handle - * @param Rxbuffer: Rx Buffer - * @note This function can be called only inside the HAL_CEC_RxCpltCallback() * @retval Frame size */ -void HAL_CEC_ChangeRxBuffer(CEC_HandleTypeDef *hcec, uint8_t* Rxbuffer) +uint32_t HAL_CEC_GetReceivedFrameSize(CEC_HandleTypeDef *hcec) { - hcec->Init.RxBuffer = Rxbuffer; + return hcec->RxXferSize; } /** @@ -437,44 +734,63 @@ void HAL_CEC_IRQHandler(CEC_HandleTypeDef *hcec) hcec->ErrorCode = READ_BIT(hcec->Instance->ESR, CEC_ESR_ALL_ERROR); /* Transmit error */ - if(__HAL_CEC_GET_FLAG(hcec, CEC_FLAG_TERR) != RESET) + if((__HAL_CEC_GET_FLAG(hcec, CEC_FLAG_TERR) != RESET)) { /* Acknowledgement of the error */ __HAL_CEC_CLEAR_FLAG(hcec, CEC_FLAG_TERR); - hcec->gState = HAL_CEC_STATE_READY; + /* Check if a receive process is ongoing or not */ + if(hcec->State == HAL_CEC_STATE_BUSY_TX_RX) + { + /* Interrupts are not disabled due to reception still ongoing */ + + hcec->State = HAL_CEC_STATE_BUSY_RX; + } + else + { + /* Disable the CEC Transmission Interrupts */ + __HAL_CEC_DISABLE_IT(hcec, CEC_IT_IE); + + hcec->State = HAL_CEC_STATE_READY; + } } /* Receive error */ - if(__HAL_CEC_GET_FLAG(hcec, CEC_FLAG_RERR) != RESET) + if((__HAL_CEC_GET_FLAG(hcec, CEC_FLAG_RERR) != RESET)) { /* Acknowledgement of the error */ __HAL_CEC_CLEAR_FLAG(hcec, CEC_FLAG_RERR); - hcec->Init.RxBuffer-=hcec->RxXferSize; - hcec->RxXferSize = 0U; - hcec->RxState = HAL_CEC_STATE_READY; - } + + /* Check if a transmit process is ongoing or not */ + if(hcec->State == HAL_CEC_STATE_BUSY_TX_RX) + { + /* Interrupts are not disabled due to reception still ongoing */ + + hcec->State = HAL_CEC_STATE_BUSY_TX; + } + else + { + /* Disable the CEC Transmission Interrupts */ + __HAL_CEC_DISABLE_IT(hcec, CEC_IT_IE); + + hcec->State = HAL_CEC_STATE_READY; + } + } - if((hcec->ErrorCode & CEC_ESR_ALL_ERROR) != 0U) + if ((hcec->ErrorCode & CEC_ESR_ALL_ERROR) != 0) { - /* Error Call Back */ HAL_CEC_ErrorCallback(hcec); } /* Transmit byte request or block transfer finished */ - if(__HAL_CEC_GET_FLAG(hcec, CEC_FLAG_TBTRF) != RESET) + if((__HAL_CEC_GET_FLAG(hcec, CEC_FLAG_TBTRF) != RESET)) { CEC_Transmit_IT(hcec); - } + } /* Receive byte or block transfer finished */ - if(__HAL_CEC_GET_FLAG(hcec, CEC_FLAG_RBTF) != RESET) + if((__HAL_CEC_GET_FLAG(hcec, CEC_FLAG_RBTF) != RESET)) { - if(hcec->RxXferSize == 0U) - { - /* reception is starting */ - hcec->RxState = HAL_CEC_STATE_BUSY_RX; - } CEC_Receive_IT(hcec); } } @@ -497,14 +813,12 @@ void HAL_CEC_IRQHandler(CEC_HandleTypeDef *hcec) /** * @brief Rx Transfer completed callback * @param hcec: CEC handle - * @param RxFrameSize: Size of frame * @retval None */ -__weak void HAL_CEC_RxCpltCallback(CEC_HandleTypeDef *hcec, uint32_t RxFrameSize) +__weak void HAL_CEC_RxCpltCallback(CEC_HandleTypeDef *hcec) { /* Prevent unused argument(s) compilation warning */ UNUSED(hcec); - UNUSED(RxFrameSize); /* NOTE : This function should not be modified, when the callback is needed, the HAL_CEC_RxCpltCallback can be implemented in the user file */ @@ -523,6 +837,7 @@ __weak void HAL_CEC_RxCpltCallback(CEC_HandleTypeDef *hcec, uint32_t RxFrameSize the HAL_CEC_ErrorCallback can be implemented in the user file */ } + /** * @} */ @@ -532,28 +847,24 @@ __weak void HAL_CEC_RxCpltCallback(CEC_HandleTypeDef *hcec, uint32_t RxFrameSize * @verbatim =============================================================================== - ##### Peripheral Control function ##### + ##### Peripheral Control functions ##### =============================================================================== [..] This subsection provides a set of functions allowing to control the CEC. (+) HAL_CEC_GetState() API can be helpful to check in run-time the state of the CEC peripheral. - (+) HAL_CEC_GetError() API can be helpful to check in run-time the error of the CEC peripheral. + (+) HAL_CEC_GetError() API can be helpful to get the error code of a failed transmission or reception. @endverbatim * @{ */ + /** * @brief return the CEC state - * @param hcec: pointer to a CEC_HandleTypeDef structure that contains - * the configuration information for the specified CEC module. + * @param hcec: CEC handle * @retval HAL state */ HAL_CEC_StateTypeDef HAL_CEC_GetState(CEC_HandleTypeDef *hcec) { - uint32_t temp1= 0x00U, temp2 = 0x00U; - temp1 = hcec->gState; - temp2 = hcec->RxState; - - return (HAL_CEC_StateTypeDef)(temp1 | temp2); + return hcec->State; } /** @@ -588,17 +899,34 @@ uint32_t HAL_CEC_GetError(CEC_HandleTypeDef *hcec) */ static HAL_StatusTypeDef CEC_Transmit_IT(CEC_HandleTypeDef *hcec) { + uint32_t tmp_state = 0; + + tmp_state = hcec->State; /* if the IP is already busy or if there is a previous transmission already pending due to arbitration loss */ - if((hcec->gState == HAL_CEC_STATE_BUSY_TX) || (__HAL_CEC_GET_TRANSMISSION_START_FLAG(hcec) != RESET)) + if(((tmp_state == HAL_CEC_STATE_BUSY_TX) || (tmp_state == HAL_CEC_STATE_BUSY_TX_RX)) + || (__HAL_CEC_GET_TRANSMISSION_START_FLAG(hcec) != RESET)) { /* if all data have been sent */ - if(hcec->TxXferCount == 0U) + if(hcec->TxXferCount == 0) { /* Acknowledge successful completion by writing 0x00 */ - MODIFY_REG(hcec->Instance->CSR, CEC_FLAG_TRANSMIT_MASK, 0x00U); + MODIFY_REG(hcec->Instance->CSR, CEC_FLAG_TRANSMIT_MASK, 0x00); - hcec->gState = HAL_CEC_STATE_READY; + /* Check if a receive process is ongoing or not */ + if(hcec->State == HAL_CEC_STATE_BUSY_TX_RX) + { + /* Interrupts are not disabled due to reception still ongoing */ + + hcec->State = HAL_CEC_STATE_BUSY_RX; + } + else + { + /* Disable the CEC Transmission Interrupts */ + __HAL_CEC_DISABLE_IT(hcec, CEC_IT_IE); + + hcec->State = HAL_CEC_STATE_READY; + } HAL_CEC_TxCpltCallback(hcec); @@ -613,7 +941,7 @@ static HAL_StatusTypeDef CEC_Transmit_IT(CEC_HandleTypeDef *hcec) hcec->Instance->TXD = *hcec->pTxBuffPtr++; /* If this is the last byte of the ongoing transmission */ - if(hcec->TxXferCount == 0U) + if (hcec->TxXferCount == 0) { /* Acknowledge byte request and signal end of message */ MODIFY_REG(hcec->Instance->CSR, CEC_FLAG_TRANSMIT_MASK, CEC_FLAG_TEOM); @@ -621,7 +949,7 @@ static HAL_StatusTypeDef CEC_Transmit_IT(CEC_HandleTypeDef *hcec) else { /* Acknowledge byte request by writing 0x00 */ - MODIFY_REG(hcec->Instance->CSR, CEC_FLAG_TRANSMIT_MASK, 0x00U); + MODIFY_REG(hcec->Instance->CSR, CEC_FLAG_TRANSMIT_MASK, 0x00); } return HAL_OK; @@ -643,28 +971,50 @@ static HAL_StatusTypeDef CEC_Transmit_IT(CEC_HandleTypeDef *hcec) static HAL_StatusTypeDef CEC_Receive_IT(CEC_HandleTypeDef *hcec) { static uint32_t temp; - - if(hcec->RxState == HAL_CEC_STATE_BUSY_RX) + uint32_t tmp_state = 0; + + tmp_state = hcec->State; + if((tmp_state == HAL_CEC_STATE_BUSY_RX) || (tmp_state == HAL_CEC_STATE_BUSY_TX_RX)) { temp = hcec->Instance->CSR; /* Store received data */ - hcec->RxXferSize++; - *hcec->Init.RxBuffer++ = hcec->Instance->RXD; + *hcec->pRxBuffPtr++ = hcec->Instance->RXD; /* Acknowledge received byte by writing 0x00 */ - MODIFY_REG(hcec->Instance->CSR, CEC_FLAG_RECEIVE_MASK, 0x00U); + MODIFY_REG(hcec->Instance->CSR, CEC_FLAG_RECEIVE_MASK, 0x00); + + /* Increment the number of received data */ + if(hcec->RxXferSize == CEC_RXXFERSIZE_INITIALIZE) + { + hcec->RxXferSize = 0; + } + else + { + hcec->RxXferSize++; + } /* If the End Of Message is reached */ if(HAL_IS_BIT_SET(temp, CEC_FLAG_REOM)) { - /* Interrupts are not disabled due to transmission still ongoing */ - hcec->RxState = HAL_CEC_STATE_READY; - - HAL_CEC_RxCpltCallback(hcec, hcec->RxXferSize); - + if(hcec->State == HAL_CEC_STATE_BUSY_TX_RX) + { + /* Interrupts are not disabled due to transmission still ongoing */ + + hcec->State = HAL_CEC_STATE_BUSY_TX; + } + else + { + /* Disable the CEC Transmission Interrupts */ + __HAL_CEC_DISABLE_IT(hcec, CEC_IT_IE); + + hcec->State = HAL_CEC_STATE_READY; + } + + HAL_CEC_RxCpltCallback(hcec); + return HAL_OK; - } + } else { return HAL_BUSY; diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_cec.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_cec.h index eb1fd35d359..f0af5fcb0c0 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_cec.h +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_cec.h @@ -2,13 +2,13 @@ ****************************************************************************** * @file stm32f1xx_hal_cec.h * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief Header file of CEC HAL module. ****************************************************************************** * @attention * - *

© COPYRIGHT(c) 2017 STMicroelectronics

+ *

© COPYRIGHT(c) 2016 STMicroelectronics

* * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: @@ -53,82 +53,89 @@ /** @addtogroup CEC * @{ + */ + +/** @addtogroup CEC_Private_Constants + * @{ + */ +#define IS_CEC_BIT_TIMING_ERROR_MODE(MODE) (((MODE) == CEC_BIT_TIMING_ERROR_MODE_STANDARD) || \ + ((MODE) == CEC_BIT_TIMING_ERROR_MODE_ERRORFREE)) +#define IS_CEC_BIT_PERIOD_ERROR_MODE(MODE) (((MODE) == CEC_BIT_PERIOD_ERROR_MODE_STANDARD) || \ + ((MODE) == CEC_BIT_PERIOD_ERROR_MODE_FLEXIBLE)) + +/** @brief Check CEC device Own Address Register (OAR) setting. + * @param __ADDRESS__: CEC own address. + * @retval Test result (TRUE or FALSE). + */ +#define IS_CEC_OAR_ADDRESS(__ADDRESS__) ((__ADDRESS__) <= 0xF) + +/** @brief Check CEC initiator or destination logical address setting. + * Initiator and destination addresses are coded over 4 bits. + * @param __ADDRESS__: CEC initiator or logical address. + * @retval Test result (TRUE or FALSE). */ +#define IS_CEC_ADDRESS(__ADDRESS__) ((__ADDRESS__) <= 0xF) + +/** @brief Check CEC message size. + * The message size is the payload size: without counting the header, + * it varies from 0 byte (ping operation, one header only, no payload) to + * 15 bytes (1 opcode and up to 14 operands following the header). + * @param __SIZE__: CEC message size. + * @retval Test result (TRUE or FALSE). + */ +#define IS_CEC_MSGSIZE(__SIZE__) ((__SIZE__) <= 0xF) + +/** + * @} + */ /* Exported types ------------------------------------------------------------*/ /** @defgroup CEC_Exported_Types CEC Exported Types * @{ - */ + */ /** * @brief CEC Init Structure definition */ typedef struct -{ +{ uint32_t TimingErrorFree; /*!< Configures the CEC Bit Timing Error Mode. This parameter can be a value of @ref CEC_BitTimingErrorMode */ uint32_t PeriodErrorFree; /*!< Configures the CEC Bit Period Error Mode. This parameter can be a value of @ref CEC_BitPeriodErrorMode */ - uint16_t OwnAddress; /*!< Own addresses configuration - This parameter can be a value of @ref CEC_OWN_ADDRESS */ - uint8_t *RxBuffer; /*!< CEC Rx buffer pointeur */ + uint8_t InitiatorAddress; /*!< Initiator address (source logical address, sent in each header) + This parameter can be a value <= 0xF */ }CEC_InitTypeDef; /** - * @brief HAL CEC State structures definition - * @note HAL CEC State value is a combination of 2 different substates: gState and RxState. - * - gState contains CEC state information related to global Handle management - * and also information related to Tx operations. - * gState value coding follow below described bitmap : - * b7 (not used) - * x : Should be set to 0 - * b6 Error information - * 0 : No Error - * 1 : Error - * b5 IP initilisation status - * 0 : Reset (IP not initialized) - * 1 : Init done (IP initialized. HAL CEC Init function already called) - * b4-b3 (not used) - * xx : Should be set to 00 - * b2 Intrinsic process state - * 0 : Ready - * 1 : Busy (IP busy with some configuration or internal operations) - * b1 (not used) - * x : Should be set to 0 - * b0 Tx state - * 0 : Ready (no Tx operation ongoing) - * 1 : Busy (Tx operation ongoing) - * - RxState contains information related to Rx operations. - * RxState value coding follow below described bitmap : - * b7-b6 (not used) - * xx : Should be set to 00 - * b5 IP initilisation status - * 0 : Reset (IP not initialized) - * 1 : Init done (IP initialized) - * b4-b2 (not used) - * xxx : Should be set to 000 - * b1 Rx state - * 0 : Ready (no Rx operation ongoing) - * 1 : Busy (Rx operation ongoing) - * b0 (not used) - * x : Should be set to 0. + * @brief HAL CEC State structures definition */ typedef enum { - HAL_CEC_STATE_RESET = 0x00U, /*!< Peripheral is not yet Initialized - Value is allowed for gState and RxState */ - HAL_CEC_STATE_READY = 0x20U, /*!< Peripheral Initialized and ready for use - Value is allowed for gState and RxState */ - HAL_CEC_STATE_BUSY = 0x24U, /*!< an internal process is ongoing - Value is allowed for gState only */ - HAL_CEC_STATE_BUSY_RX = 0x22U, /*!< Data Reception process is ongoing - Value is allowed for RxState only */ - HAL_CEC_STATE_BUSY_TX = 0x21U, /*!< Data Transmission process is ongoing - Value is allowed for gState only */ - HAL_CEC_STATE_BUSY_RX_TX = 0x23U, /*!< an internal process is ongoing - Value is allowed for gState only */ - HAL_CEC_STATE_ERROR = 0x60U /*!< Error Value is allowed for gState only */ + HAL_CEC_STATE_RESET = 0x00, /*!< Peripheral Reset state */ + HAL_CEC_STATE_READY = 0x01, /*!< Peripheral Initialized and ready for use */ + HAL_CEC_STATE_BUSY = 0x02, /*!< An internal process is ongoing */ + HAL_CEC_STATE_BUSY_TX = 0x03, /*!< Data Transmission process is ongoing */ + HAL_CEC_STATE_BUSY_RX = 0x04, /*!< Data Reception process is ongoing */ + HAL_CEC_STATE_BUSY_TX_RX = 0x05, /*!< Data Transmission and Reception process is ongoing */ + HAL_CEC_STATE_TIMEOUT = 0x06, /*!< Timeout state */ + HAL_CEC_STATE_ERROR = 0x07 /*!< State Error */ }HAL_CEC_StateTypeDef; +/** + * @brief HAL Error structures definition + */ +typedef enum +{ + HAL_CEC_ERROR_NONE = (uint32_t) 0x0, /*!< no error */ + HAL_CEC_ERROR_BTE = CEC_ESR_BTE, /*!< Bit Timing Error */ + HAL_CEC_ERROR_BPE = CEC_ESR_BPE, /*!< Bit Period Error */ + HAL_CEC_ERROR_RBTFE = CEC_ESR_RBTFE, /*!< Rx Block Transfer Finished Error */ + HAL_CEC_ERROR_SBE = CEC_ESR_SBE, /*!< Start Bit Error */ + HAL_CEC_ERROR_ACKE = CEC_ESR_ACKE, /*!< Block Acknowledge Error */ + HAL_CEC_ERROR_LINE = CEC_ESR_LINE, /*!< Line Error */ + HAL_CEC_ERROR_TBTFE = CEC_ESR_TBTFE, /*!< Tx Block Transfer Finished Error */ +}HAL_CEC_ErrorTypeDef; + /** * @brief CEC handle Structure definition */ @@ -142,48 +149,31 @@ typedef struct uint16_t TxXferCount; /*!< CEC Tx Transfer Counter */ + uint8_t *pRxBuffPtr; /*!< Pointer to CEC Rx transfer Buffer */ + uint16_t RxXferSize; /*!< CEC Rx Transfer size, 0: header received only */ - HAL_LockTypeDef Lock; /*!< Locking object */ - - HAL_CEC_StateTypeDef gState; /*!< CEC state information related to global Handle management - and also related to Tx operations. - This parameter can be a value of @ref HAL_CEC_StateTypeDef */ + uint32_t ErrorCode; /*!< For errors handling purposes, copy of ESR register in case error is reported */ - HAL_CEC_StateTypeDef RxState; /*!< CEC state information related to Rx operations. - This parameter can be a value of @ref HAL_CEC_StateTypeDef */ + HAL_LockTypeDef Lock; /*!< Locking object */ - uint32_t ErrorCode; /*!< For errors handling purposes, copy of ISR register - in case error is reported */ + HAL_CEC_StateTypeDef State; /*!< CEC communication state */ + }CEC_HandleTypeDef; + /** - * @} - */ + * @} + */ /* Exported constants --------------------------------------------------------*/ /** @defgroup CEC_Exported_Constants CEC Exported Constants * @{ */ - -/** @defgroup CEC_Error_Code CEC Error Code - * @{ - */ -#define HAL_CEC_ERROR_NONE 0x00000000U /*!< no error */ -#define HAL_CEC_ERROR_BTE CEC_ESR_BTE /*!< Bit Timing Error */ -#define HAL_CEC_ERROR_BPE CEC_ESR_BPE /*!< Bit Period Error */ -#define HAL_CEC_ERROR_RBTFE CEC_ESR_RBTFE /*!< Rx Block Transfer Finished Error */ -#define HAL_CEC_ERROR_SBE CEC_ESR_SBE /*!< Start Bit Error */ -#define HAL_CEC_ERROR_ACKE CEC_ESR_ACKE /*!< Block Acknowledge Error */ -#define HAL_CEC_ERROR_LINE CEC_ESR_LINE /*!< Line Error */ -#define HAL_CEC_ERROR_TBTFE CEC_ESR_TBTFE /*!< Tx Block Transfer Finished Error */ -/** - * @} - */ - + /** @defgroup CEC_BitTimingErrorMode Bit Timing Error Mode * @{ */ -#define CEC_BIT_TIMING_ERROR_MODE_STANDARD 0x00000000U /*!< Bit timing error Standard Mode */ +#define CEC_BIT_TIMING_ERROR_MODE_STANDARD ((uint32_t)0x00) /*!< Bit timing error Standard Mode */ #define CEC_BIT_TIMING_ERROR_MODE_ERRORFREE CEC_CFGR_BTEM /*!< Bit timing error Free Mode */ /** * @} @@ -192,44 +182,19 @@ typedef struct /** @defgroup CEC_BitPeriodErrorMode Bit Period Error Mode * @{ */ -#define CEC_BIT_PERIOD_ERROR_MODE_STANDARD 0x00000000U /*!< Bit period error Standard Mode */ +#define CEC_BIT_PERIOD_ERROR_MODE_STANDARD ((uint32_t)0x00) /*!< Bit period error Standard Mode */ #define CEC_BIT_PERIOD_ERROR_MODE_FLEXIBLE CEC_CFGR_BPEM /*!< Bit period error Flexible Mode */ /** * @} */ -/** @defgroup CEC_Initiator_Position CEC Initiator logical address position in message header - * @{ - */ -#define CEC_INITIATOR_LSB_POS 4U -/** - * @} - */ - -/** @defgroup CEC_OWN_ADDRESS CEC Own Address +/** @defgroup CEC_Initiator_Position Initiator logical address position in message header * @{ */ -#define CEC_OWN_ADDRESS_NONE CEC_OWN_ADDRESS_0 /* Reset value */ -#define CEC_OWN_ADDRESS_0 ((uint16_t)0x0000U) /* Logical Address 0 */ -#define CEC_OWN_ADDRESS_1 ((uint16_t)0x0001U) /* Logical Address 1 */ -#define CEC_OWN_ADDRESS_2 ((uint16_t)0x0002U) /* Logical Address 2 */ -#define CEC_OWN_ADDRESS_3 ((uint16_t)0x0003U) /* Logical Address 3 */ -#define CEC_OWN_ADDRESS_4 ((uint16_t)0x0004U) /* Logical Address 4 */ -#define CEC_OWN_ADDRESS_5 ((uint16_t)0x0005U) /* Logical Address 5 */ -#define CEC_OWN_ADDRESS_6 ((uint16_t)0x0006U) /* Logical Address 6 */ -#define CEC_OWN_ADDRESS_7 ((uint16_t)0x0007U) /* Logical Address 7 */ -#define CEC_OWN_ADDRESS_8 ((uint16_t)0x0008U) /* Logical Address 8 */ -#define CEC_OWN_ADDRESS_9 ((uint16_t)0x0009U) /* Logical Address 9 */ -#define CEC_OWN_ADDRESS_10 ((uint16_t)0x000AU) /* Logical Address 10 */ -#define CEC_OWN_ADDRESS_11 ((uint16_t)0x000BU) /* Logical Address 11 */ -#define CEC_OWN_ADDRESS_12 ((uint16_t)0x000CU) /* Logical Address 12 */ -#define CEC_OWN_ADDRESS_13 ((uint16_t)0x000DU) /* Logical Address 13 */ -#define CEC_OWN_ADDRESS_14 ((uint16_t)0x000EU) /* Logical Address 14 */ -#define CEC_OWN_ADDRESS_15 ((uint16_t)0x000FU) /* Logical Address 15 */ +#define CEC_INITIATOR_LSB_POS ((uint32_t) 4) /** * @} */ - /** @defgroup CEC_Interrupts_Definitions Interrupts definition * @{ */ @@ -262,66 +227,63 @@ typedef struct * @{ */ -/** @brief Reset CEC handle gstate & RxState +/** @brief Reset CEC handle state * @param __HANDLE__: CEC handle. * @retval None */ -#define __HAL_CEC_RESET_HANDLE_STATE(__HANDLE__) do{ \ - (__HANDLE__)->gState = HAL_CEC_STATE_RESET; \ - (__HANDLE__)->RxState = HAL_CEC_STATE_RESET; \ - } while(0U) +#define __HAL_CEC_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_CEC_STATE_RESET) /** @brief Checks whether or not the specified CEC interrupt flag is set. * @param __HANDLE__: specifies the CEC Handle. - * @param __FLAG__: specifies the flag to check. + * @param __INTERRUPT__: specifies the interrupt to check. * @arg CEC_FLAG_TERR: Tx Error - * @arg CEC_FLAG_TBTRF:Tx Block Transfer Finished + * @arg CEC_FLAG_TBTF: Tx Block Transfer Finished * @arg CEC_FLAG_RERR: Rx Error * @arg CEC_FLAG_RBTF: Rx Block Transfer Finished * @retval ITStatus */ -#define __HAL_CEC_GET_FLAG(__HANDLE__, __FLAG__) READ_BIT((__HANDLE__)->Instance->CSR,(__FLAG__)) +#define __HAL_CEC_GET_FLAG(__HANDLE__, __INTERRUPT__) READ_BIT((__HANDLE__)->Instance->CSR,(__INTERRUPT__)) /** @brief Clears the CEC's pending flags. * @param __HANDLE__: specifies the CEC Handle. - * @param __FLAG__: specifies the flag to clear. + * @param __FLAG__: specifies the flag to clear. * This parameter can be any combination of the following values: * @arg CEC_CSR_TERR: Tx Error - * @arg CEC_FLAG_TBTRF: Tx Block Transfer Finished + * @arg CEC_CSR_TBTF: Tx Block Transfer Finished * @arg CEC_CSR_RERR: Rx Error * @arg CEC_CSR_RBTF: Rx Block Transfer Finished * @retval none */ -#define __HAL_CEC_CLEAR_FLAG(__HANDLE__, __FLAG__) \ - do { \ - uint32_t tmp = 0x0U; \ - tmp = (__HANDLE__)->Instance->CSR & 0x00000002U; \ - (__HANDLE__)->Instance->CSR &= (uint32_t)(((~(uint32_t)(__FLAG__)) & 0xFFFFFFFCU) | tmp);\ - } while(0U) - +#define __HAL_CEC_CLEAR_FLAG(__HANDLE__, __FLAG__) \ + do { \ + uint32_t tmp = 0x0; \ + tmp = (__HANDLE__)->Instance->CSR & 0x2; \ + (__HANDLE__)->Instance->CSR &= (uint32_t)(((~(uint32_t)(__FLAG__)) & 0xFFFFFFFC) | tmp);\ + } while(0) + /** @brief Enables the specified CEC interrupt. * @param __HANDLE__: specifies the CEC Handle. - * @param __INTERRUPT__: specifies the CEC interrupt to enable. + * @param __INTERRUPT__: The CEC interrupt to enable. * This parameter can be: - * @arg CEC_IT_IE : Interrupt Enable. + * @arg CEC_IT_IE : Interrupt Enable * @retval none */ #define __HAL_CEC_ENABLE_IT(__HANDLE__, __INTERRUPT__) SET_BIT((__HANDLE__)->Instance->CFGR, (__INTERRUPT__)) /** @brief Disables the specified CEC interrupt. * @param __HANDLE__: specifies the CEC Handle. - * @param __INTERRUPT__: specifies the CEC interrupt to disable. + * @param __INTERRUPT__: The CEC interrupt to enable. * This parameter can be: - * @arg CEC_IT_IE : Interrupt Enable + * @arg CEC_IT_IE : Interrupt Enable * @retval none */ #define __HAL_CEC_DISABLE_IT(__HANDLE__, __INTERRUPT__) CLEAR_BIT((__HANDLE__)->Instance->CFGR, (__INTERRUPT__)) /** @brief Checks whether or not the specified CEC interrupt is enabled. * @param __HANDLE__: specifies the CEC Handle. - * @param __INTERRUPT__: specifies the CEC interrupt to check. + * @param __INTERRUPT__: The CEC interrupt to enable. * This parameter can be: - * @arg CEC_IT_IE : Interrupt Enable + * @arg CEC_IT_IE : Interrupt Enable * @retval FlagStatus */ #define __HAL_CEC_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) READ_BIT((__HANDLE__)->Instance->CFGR, (__INTERRUPT__)) @@ -346,7 +308,7 @@ typedef struct /** @brief Set Transmission End flag * @param __HANDLE__: specifies the CEC Handle. - * @retval none + * @retval none */ #define __HAL_CEC_LAST_BYTE_TX_SET(__HANDLE__) SET_BIT((__HANDLE__)->Instance->CSR, CEC_CSR_TEOM) @@ -383,7 +345,7 @@ typedef struct /** @addtogroup CEC_Exported_Functions CEC Exported Functions * @{ */ - + /** @addtogroup CEC_Exported_Functions_Group1 Initialization and de-initialization functions * @brief Initialization and Configuration functions * @{ @@ -391,7 +353,6 @@ typedef struct /* Initialization and de-initialization functions ****************************/ HAL_StatusTypeDef HAL_CEC_Init(CEC_HandleTypeDef *hcec); HAL_StatusTypeDef HAL_CEC_DeInit(CEC_HandleTypeDef *hcec); -HAL_StatusTypeDef HAL_CEC_SetDeviceAddress(CEC_HandleTypeDef *hcec, uint16_t CEC_OwnAddress); void HAL_CEC_MspInit(CEC_HandleTypeDef *hcec); void HAL_CEC_MspDeInit(CEC_HandleTypeDef *hcec); /** @@ -402,13 +363,15 @@ void HAL_CEC_MspDeInit(CEC_HandleTypeDef *hcec); * @brief CEC Transmit/Receive functions * @{ */ -/* I/O operation functions ***************************************************/ -HAL_StatusTypeDef HAL_CEC_Transmit_IT(CEC_HandleTypeDef *hcec, uint8_t InitiatorAddress,uint8_t DestinationAddress, uint8_t *pData, uint32_t Size); -uint32_t HAL_CEC_GetLastReceivedFrameSize(CEC_HandleTypeDef *hcec); -void HAL_CEC_ChangeRxBuffer(CEC_HandleTypeDef *hcec, uint8_t* Rxbuffer); +/* IO operation functions *****************************************************/ +HAL_StatusTypeDef HAL_CEC_Transmit(CEC_HandleTypeDef *hcec, uint8_t DestinationAddress, uint8_t *pData, uint32_t Size, uint32_t Timeout); +HAL_StatusTypeDef HAL_CEC_Receive(CEC_HandleTypeDef *hcec, uint8_t *pData, uint32_t Timeout); +HAL_StatusTypeDef HAL_CEC_Transmit_IT(CEC_HandleTypeDef *hcec, uint8_t DestinationAddress, uint8_t *pData, uint32_t Size); +HAL_StatusTypeDef HAL_CEC_Receive_IT(CEC_HandleTypeDef *hcec, uint8_t *pData); +uint32_t HAL_CEC_GetReceivedFrameSize(CEC_HandleTypeDef *hcec); void HAL_CEC_IRQHandler(CEC_HandleTypeDef *hcec); void HAL_CEC_TxCpltCallback(CEC_HandleTypeDef *hcec); -void HAL_CEC_RxCpltCallback(CEC_HandleTypeDef *hcec, uint32_t RxFrameSize); +void HAL_CEC_RxCpltCallback(CEC_HandleTypeDef *hcec); void HAL_CEC_ErrorCallback(CEC_HandleTypeDef *hcec); /** * @} @@ -429,86 +392,16 @@ uint32_t HAL_CEC_GetError(CEC_HandleTypeDef *hcec); * @} */ -/* Private types -------------------------------------------------------------*/ -/** @defgroup CEC_Private_Types CEC Private Types - * @{ - */ - /** * @} */ -/* Private variables ---------------------------------------------------------*/ -/** @defgroup CEC_Private_Variables CEC Private Variables - * @{ - */ - -/** - * @} - */ - -/* Private constants ---------------------------------------------------------*/ -/** @defgroup CEC_Private_Constants CEC Private Constants - * @{ - */ - /** * @} */ - -/* Private macros ------------------------------------------------------------*/ -/** @defgroup CEC_Private_Macros CEC Private Macros - * @{ - */ -#define IS_CEC_BIT_TIMING_ERROR_MODE(MODE) (((MODE) == CEC_BIT_TIMING_ERROR_MODE_STANDARD) || \ - ((MODE) == CEC_BIT_TIMING_ERROR_MODE_ERRORFREE)) - -#define IS_CEC_BIT_PERIOD_ERROR_MODE(MODE) (((MODE) == CEC_BIT_PERIOD_ERROR_MODE_STANDARD) || \ - ((MODE) == CEC_BIT_PERIOD_ERROR_MODE_FLEXIBLE)) - -/** @brief Check CEC message size. - * The message size is the payload size: without counting the header, - * it varies from 0 byte (ping operation, one header only, no payload) to - * 15 bytes (1 opcode and up to 14 operands following the header). - * @param __SIZE__: CEC message size. - * @retval Test result (TRUE or FALSE). - */ -#define IS_CEC_MSGSIZE(__SIZE__) ((__SIZE__) <= 0x10U) -/** @brief Check CEC device Own Address Register (OAR) setting. - * @param __ADDRESS__: CEC own address. - * @retval Test result (TRUE or FALSE). - */ -#define IS_CEC_OWN_ADDRESS(__ADDRESS__) ((__ADDRESS__) <= 0x0000000FU) - -/** @brief Check CEC initiator or destination logical address setting. - * Initiator and destination addresses are coded over 4 bits. - * @param __ADDRESS__: CEC initiator or logical address. - * @retval Test result (TRUE or FALSE). - */ -#define IS_CEC_ADDRESS(__ADDRESS__) ((__ADDRESS__) <= 0x0000000FU) - - - -/** - * @} - */ -/* Private functions ---------------------------------------------------------*/ -/** @defgroup CEC_Private_Functions CEC Private Functions - * @{ - */ -/** - * @} - */ - -/** - * @} - */ - -/** - * @} - */ #endif /* defined(STM32F100xB) || defined(STM32F100xE) */ + #ifdef __cplusplus } #endif diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_conf.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_conf.h index 31178c3fc11..89cd6356a8f 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_conf.h +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_conf.h @@ -2,15 +2,15 @@ ****************************************************************************** * @file stm32f1xx_hal_conf.h * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.4 + * @date 29-April-2016 * @brief HAL configuration template file. * This file should be copied to the application folder and renamed * to stm32f1xx_hal_conf.h. ****************************************************************************** * @attention * - *

© COPYRIGHT(c) 2017 STMicroelectronics

+ *

© COPYRIGHT(c) 2016 STMicroelectronics

* * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: @@ -83,7 +83,6 @@ #define HAL_UART_MODULE_ENABLED #define HAL_USART_MODULE_ENABLED #define HAL_WWDG_MODULE_ENABLED -#define HAL_MMC_MODULE_ENABLED /* ########################## Oscillator Values adaptation ####################*/ /** @@ -93,14 +92,14 @@ */ #if !defined (HSE_VALUE) #if defined(USE_STM3210C_EVAL) - #define HSE_VALUE 25000000U /*!< Value of the External oscillator in Hz */ + #define HSE_VALUE ((uint32_t)25000000) /*!< Value of the External oscillator in Hz */ #else - #define HSE_VALUE 8000000U /*!< Value of the External oscillator in Hz */ + #define HSE_VALUE ((uint32_t)8000000) /*!< Value of the External oscillator in Hz */ #endif #endif /* HSE_VALUE */ #if !defined (HSE_STARTUP_TIMEOUT) - #define HSE_STARTUP_TIMEOUT 100U /*!< Time out for HSE start up, in ms */ + #define HSE_STARTUP_TIMEOUT ((uint32_t)100) /*!< Time out for HSE start up, in ms */ #endif /* HSE_STARTUP_TIMEOUT */ /** @@ -109,29 +108,23 @@ * (when HSI is used as system clock source, directly or through the PLL). */ #if !defined (HSI_VALUE) - #define HSI_VALUE 8000000U /*!< Value of the Internal oscillator in Hz */ + #define HSI_VALUE ((uint32_t)8000000) /*!< Value of the Internal oscillator in Hz*/ #endif /* HSI_VALUE */ -/** - * @brief Internal Low Speed oscillator (LSI) value. - */ -#if !defined (LSI_VALUE) - #define LSI_VALUE 40000U /*!< LSI Typical Value in Hz */ -#endif /* LSI_VALUE */ /*!< Value of the Internal Low Speed oscillator in Hz - The real value may vary depending on the variations - in voltage and temperature. */ /** * @brief External Low Speed oscillator (LSE) value. * This value is used by the UART, RTC HAL module to compute the system frequency */ #if !defined (LSE_VALUE) - #define LSE_VALUE 32768U /*!< Value of the External Low Speed oscillator in Hz */ + #define LSE_VALUE ((uint32_t)32768) /*!< Value of the External oscillator in Hz*/ #endif /* LSE_VALUE */ + #if !defined (LSE_STARTUP_TIMEOUT) - #define LSE_STARTUP_TIMEOUT 5000U /*!< Time out for LSE start up, in ms */ -#endif /* LSE_STARTUP_TIMEOUT */ + #define LSE_STARTUP_TIMEOUT ((uint32_t)5000) /*!< Time out for LSE start up, in ms */ +#endif /* HSE_STARTUP_TIMEOUT */ + /* Tip: To avoid modifying this file each time you need to use different HSE, === you can define the HSE value in your toolchain compiler preprocessor. */ @@ -139,52 +132,53 @@ /** * @brief This is the HAL system configuration section */ -#define VDD_VALUE 3300U /*!< Value of VDD in mv */ -#define TICK_INT_PRIORITY 0x0FU /*!< tick interrupt priority */ -#define USE_RTOS 0U -#define PREFETCH_ENABLE 1U +#define VDD_VALUE ((uint32_t)3300) /*!< Value of VDD in mv */ +#define TICK_INT_PRIORITY ((uint32_t)0x000F) /*!< tick interrupt priority */ +#define USE_RTOS 0 +#define PREFETCH_ENABLE 1 /* ########################## Assert Selection ############################## */ /** * @brief Uncomment the line below to expanse the "assert_param" macro in the * HAL drivers code */ -/* #define USE_FULL_ASSERT 1U */ +/*#define USE_FULL_ASSERT 1*/ + /* ################## Ethernet peripheral configuration ##################### */ /* Section 1 : Ethernet peripheral configuration */ /* MAC ADDRESS: MAC_ADDR0:MAC_ADDR1:MAC_ADDR2:MAC_ADDR3:MAC_ADDR4:MAC_ADDR5 */ -#define MAC_ADDR0 2U -#define MAC_ADDR1 0U -#define MAC_ADDR2 0U -#define MAC_ADDR3 0U -#define MAC_ADDR4 0U -#define MAC_ADDR5 0U +#define MAC_ADDR0 2 +#define MAC_ADDR1 0 +#define MAC_ADDR2 0 +#define MAC_ADDR3 0 +#define MAC_ADDR4 0 +#define MAC_ADDR5 0 /* Definition of the Ethernet driver buffers size and count */ #define ETH_RX_BUF_SIZE ETH_MAX_PACKET_SIZE /* buffer size for receive */ #define ETH_TX_BUF_SIZE ETH_MAX_PACKET_SIZE /* buffer size for transmit */ -#define ETH_RXBUFNB 8U /* 8 Rx buffers of size ETH_RX_BUF_SIZE */ -#define ETH_TXBUFNB 4U /* 4 Tx buffers of size ETH_TX_BUF_SIZE */ +#define ETH_RXBUFNB ((uint32_t)8) /* 4 Rx buffers of size ETH_RX_BUF_SIZE */ +#define ETH_TXBUFNB ((uint32_t)4) /* 4 Tx buffers of size ETH_TX_BUF_SIZE */ /* Section 2: PHY configuration section */ /* DP83848 PHY Address*/ -#define DP83848_PHY_ADDRESS 0x01U +#define DP83848_PHY_ADDRESS 0x01 /* PHY Reset delay these values are based on a 1 ms Systick interrupt*/ -#define PHY_RESET_DELAY 0x000000FFU +#define PHY_RESET_DELAY ((uint32_t)0x000000FF) /* PHY Configuration delay */ -#define PHY_CONFIG_DELAY 0x00000FFFU +#define PHY_CONFIG_DELAY ((uint32_t)0x00000FFF) -#define PHY_READ_TO 0x0000FFFFU -#define PHY_WRITE_TO 0x0000FFFFU +#define PHY_READ_TO ((uint32_t)0x0000FFFF) +#define PHY_WRITE_TO ((uint32_t)0x0000FFFF) /* Section 3: Common PHY Registers */ -#define PHY_BCR ((uint16_t)0x0000) /*!< Transceiver Basic Control Register */ -#define PHY_BSR ((uint16_t)0x0001) /*!< Transceiver Basic Status Register */ +#define PHY_BCR ((uint16_t)0x00) /*!< Transceiver Basic Control Register */ +#define PHY_BSR ((uint16_t)0x01) /*!< Transceiver Basic Status Register */ #define PHY_RESET ((uint16_t)0x8000) /*!< PHY Reset */ #define PHY_LOOPBACK ((uint16_t)0x4000) /*!< Select loop-back mode */ @@ -203,9 +197,9 @@ /* Section 4: Extended PHY Registers */ -#define PHY_SR ((uint16_t)0x0010) /*!< PHY status register Offset */ -#define PHY_MICR ((uint16_t)0x0011) /*!< MII Interrupt Control Register */ -#define PHY_MISR ((uint16_t)0x0012) /*!< MII Interrupt Status and Misc. Control Register */ +#define PHY_SR ((uint16_t)0x10) /*!< PHY status register Offset */ +#define PHY_MICR ((uint16_t)0x11) /*!< MII Interrupt Control Register */ +#define PHY_MISR ((uint16_t)0x12) /*!< MII Interrupt Status and Misc. Control Register */ #define PHY_LINK_STATUS ((uint16_t)0x0001) /*!< PHY Link mask */ #define PHY_SPEED_STATUS ((uint16_t)0x0002) /*!< PHY Speed mask */ @@ -217,14 +211,7 @@ #define PHY_MISR_LINK_INT_EN ((uint16_t)0x0020) /*!< Enable Interrupt on change of link status */ #define PHY_LINK_INTERRUPT ((uint16_t)0x2000) /*!< PHY link status interrupt mask */ -/* ################## SPI peripheral configuration ########################## */ -/* CRC FEATURE: Use to activate CRC feature inside HAL SPI Driver -* Activated: CRC code is present inside driver -* Deactivated: CRC code cleaned from driver -*/ - -#define USE_SPI_CRC 1U /* Includes ------------------------------------------------------------------*/ /** @@ -347,13 +334,11 @@ #include "stm32f1xx_hal_pcd.h" #endif /* HAL_PCD_MODULE_ENABLED */ + #ifdef HAL_HCD_MODULE_ENABLED #include "stm32f1xx_hal_hcd.h" -#endif /* HAL_HCD_MODULE_ENABLED */ - -#ifdef HAL_MMC_MODULE_ENABLED - #include "stm32f1xx_hal_mmc.h" -#endif /* HAL_MMC_MODULE_ENABLED */ +#endif /* HAL_HCD_MODULE_ENABLED */ + /* Exported macro ------------------------------------------------------------*/ #ifdef USE_FULL_ASSERT @@ -368,10 +353,9 @@ #include "mbed_assert.h" #define assert_param(expr) MBED_ASSERT(expr) #else - #define assert_param(expr) ((void)0U) + #define assert_param(expr) ((void)0) #endif /* USE_FULL_ASSERT */ - #ifdef __cplusplus } #endif diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_cortex.c b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_cortex.c index eaa8c73cf2a..29dd4f36016 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_cortex.c +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_cortex.c @@ -2,59 +2,81 @@ ****************************************************************************** * @file stm32f1xx_hal_cortex.c * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief CORTEX HAL module driver. - * This file provides firmware functions to manage the following + * + * This file provides firmware functions to manage the following * functionalities of the CORTEX: * + Initialization and de-initialization functions - * + Peripheral Control functions - * - @verbatim + * + Peripheral Control functions + * + * @verbatim ============================================================================== ##### How to use this driver ##### ============================================================================== [..] - *** How to configure Interrupts using CORTEX HAL driver *** + *** How to configure Interrupts using Cortex HAL driver *** =========================================================== [..] - This section provides functions allowing to configure the NVIC interrupts (IRQ). + This section provide functions allowing to configure the NVIC interrupts (IRQ). The Cortex-M3 exceptions are managed by CMSIS functions. (#) Configure the NVIC Priority Grouping using HAL_NVIC_SetPriorityGrouping() function according to the following table. - (#) Configure the priority of the selected IRQ Channels using HAL_NVIC_SetPriority(). - (#) Enable the selected IRQ Channels using HAL_NVIC_EnableIRQ(). - (#) please refer to programming manual for details in how to configure priority. + + The table below gives the allowed values of the pre-emption priority and subpriority according + to the Priority Grouping configuration performed by HAL_NVIC_SetPriorityGrouping() function. + ========================================================================================================================== + NVIC_PriorityGroup | NVIC_IRQChannelPreemptionPriority | NVIC_IRQChannelSubPriority | Description + ========================================================================================================================== + NVIC_PRIORITYGROUP_0 | 0 | 0-15 | 0 bits for pre-emption priority + | | | 4 bits for subpriority + -------------------------------------------------------------------------------------------------------------------------- + NVIC_PRIORITYGROUP_1 | 0-1 | 0-7 | 1 bits for pre-emption priority + | | | 3 bits for subpriority + -------------------------------------------------------------------------------------------------------------------------- + NVIC_PRIORITYGROUP_2 | 0-3 | 0-3 | 2 bits for pre-emption priority + | | | 2 bits for subpriority + -------------------------------------------------------------------------------------------------------------------------- + NVIC_PRIORITYGROUP_3 | 0-7 | 0-1 | 3 bits for pre-emption priority + | | | 1 bits for subpriority + -------------------------------------------------------------------------------------------------------------------------- + NVIC_PRIORITYGROUP_4 | 0-15 | 0 | 4 bits for pre-emption priority + | | | 0 bits for subpriority + ========================================================================================================================== + (#) Configure the priority of the selected IRQ Channels using HAL_NVIC_SetPriority() + + (#) Enable the selected IRQ Channels using HAL_NVIC_EnableIRQ() - -@- When the NVIC_PRIORITYGROUP_0 is selected, IRQ preemption is no more possible. + + -@- When the NVIC_PRIORITYGROUP_0 is selected, IRQ pre-emption is no more possible. The pending IRQ priority will be managed only by the sub priority. -@- IRQ priority order (sorted by highest to lowest priority): - (+@) Lowest preemption priority + (+@) Lowest pre-emption priority (+@) Lowest sub priority (+@) Lowest hardware priority (IRQ number) [..] - *** How to configure Systick using CORTEX HAL driver *** + *** How to configure Systick using Cortex HAL driver *** ======================================================== [..] - Setup SysTick Timer for time base. + Setup SysTick Timer for 1 msec interrupts. (+) The HAL_SYSTICK_Config()function calls the SysTick_Config() function which is a CMSIS function that: (++) Configures the SysTick Reload register with value passed as function parameter. - (++) Configures the SysTick IRQ priority to the lowest value 0x0F. + (++) Configures the SysTick IRQ priority to the lowest value (0x0F). (++) Resets the SysTick Counter register. (++) Configures the SysTick Counter clock source to be Core Clock Source (HCLK). (++) Enables the SysTick Interrupt. (++) Starts the SysTick Counter. - (+) You can change the SysTick Clock source to be HCLK_Div8 by calling the macro - __HAL_CORTEX_SYSTICKCLK_CONFIG(SYSTICK_CLKSOURCE_HCLK_DIV8) just after the - HAL_SYSTICK_Config() function call. The __HAL_CORTEX_SYSTICKCLK_CONFIG() macro is defined - inside the stm32f1xx_hal_cortex.h file. + (+) You can change the SysTick Clock source to be HCLK_Div8 by calling the function + HAL_SYSTICK_CLKSourceConfig(SYSTICK_CLKSOURCE_HCLK_DIV8) just after the + HAL_SYSTICK_Config() function call. (+) You can change the SysTick IRQ priority by calling the HAL_NVIC_SetPriority(SysTick_IRQn,...) function just after the HAL_SYSTICK_Config() function @@ -70,7 +92,7 @@ ****************************************************************************** * @attention * - *

© COPYRIGHT(c) 2017 STMicroelectronics

+ *

© COPYRIGHT(c) 2016 STMicroelectronics

* * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: @@ -111,12 +133,12 @@ #ifdef HAL_CORTEX_MODULE_ENABLED -/* Private types -------------------------------------------------------------*/ +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ -/* Private constants ---------------------------------------------------------*/ -/* Private macros ------------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ -/* Exported functions --------------------------------------------------------*/ /** @defgroup CORTEX_Exported_Functions CORTEX Exported Functions * @{ @@ -124,14 +146,14 @@ /** @defgroup CORTEX_Exported_Functions_Group1 Initialization and de-initialization functions - * @brief Initialization and Configuration functions - * + * @brief Initialization and Configuration functions + * @verbatim ============================================================================== ##### Initialization and de-initialization functions ##### ============================================================================== [..] - This section provides the CORTEX HAL driver functions allowing to configure Interrupts + This section provide the Cortex HAL driver functions allowing to configure Interrupts Systick functionalities @endverbatim @@ -140,21 +162,21 @@ /** - * @brief Sets the priority grouping field (preemption priority and subpriority) + * @brief Sets the priority grouping field (pre-emption priority and subpriority) * using the required unlock sequence. * @param PriorityGroup: The priority grouping bits length. * This parameter can be one of the following values: - * @arg NVIC_PRIORITYGROUP_0: 0 bits for preemption priority + * @arg NVIC_PRIORITYGROUP_0: 0 bits for pre-emption priority * 4 bits for subpriority - * @arg NVIC_PRIORITYGROUP_1: 1 bits for preemption priority + * @arg NVIC_PRIORITYGROUP_1: 1 bits for pre-emption priority * 3 bits for subpriority - * @arg NVIC_PRIORITYGROUP_2: 2 bits for preemption priority + * @arg NVIC_PRIORITYGROUP_2: 2 bits for pre-emption priority * 2 bits for subpriority - * @arg NVIC_PRIORITYGROUP_3: 3 bits for preemption priority + * @arg NVIC_PRIORITYGROUP_3: 3 bits for pre-emption priority * 1 bits for subpriority - * @arg NVIC_PRIORITYGROUP_4: 4 bits for preemption priority + * @arg NVIC_PRIORITYGROUP_4: 4 bits for pre-emption priority * 0 bits for subpriority - * @note When the NVIC_PriorityGroup_0 is selected, IRQ preemption is no more possible. + * @note When the NVIC_PriorityGroup_0 is selected, IRQ pre-emption is no more possible. * The pending IRQ priority will be managed only by the subpriority. * @retval None */ @@ -169,10 +191,10 @@ void HAL_NVIC_SetPriorityGrouping(uint32_t PriorityGroup) /** * @brief Sets the priority of an interrupt. - * @param IRQn: External interrupt number. + * @param IRQn: External interrupt number * This parameter can be an enumerator of IRQn_Type enumeration - * (For the complete STM32 Devices IRQ Channels list, please refer to the appropriate CMSIS device file (stm32f10xx.h)) - * @param PreemptPriority: The preemption priority for the IRQn channel. + * (For the complete STM32 Devices IRQ Channels list, please refer to the appropriate CMSIS device file (stm32f10xxx.h)) + * @param PreemptPriority: The pre-emption priority for the IRQn channel. * This parameter can be a value between 0 and 15 * A lower priority value indicates a higher priority * @param SubPriority: the subpriority level for the IRQ channel. @@ -181,8 +203,8 @@ void HAL_NVIC_SetPriorityGrouping(uint32_t PriorityGroup) * @retval None */ void HAL_NVIC_SetPriority(IRQn_Type IRQn, uint32_t PreemptPriority, uint32_t SubPriority) -{ - uint32_t prioritygroup = 0x00U; +{ + uint32_t prioritygroup = 0x00; /* Check the parameters */ assert_param(IS_NVIC_SUB_PRIORITY(SubPriority)); @@ -197,7 +219,7 @@ void HAL_NVIC_SetPriority(IRQn_Type IRQn, uint32_t PreemptPriority, uint32_t Sub * @brief Enables a device specific interrupt in the NVIC interrupt controller. * @note To configure interrupts priority correctly, the NVIC_PriorityGroupConfig() * function should be called before. - * @param IRQn External interrupt number. + * @param IRQn External interrupt number * This parameter can be an enumerator of IRQn_Type enumeration * (For the complete STM32 Devices IRQ Channels list, please refer to the appropriate CMSIS device file (stm32f10xxx.h)) * @retval None @@ -213,7 +235,7 @@ void HAL_NVIC_EnableIRQ(IRQn_Type IRQn) /** * @brief Disables a device specific interrupt in the NVIC interrupt controller. - * @param IRQn External interrupt number. + * @param IRQn External interrupt number * This parameter can be an enumerator of IRQn_Type enumeration * (For the complete STM32 Devices IRQ Channels list, please refer to the appropriate CMSIS device file (stm32f10xxx.h)) * @retval None @@ -223,6 +245,7 @@ void HAL_NVIC_DisableIRQ(IRQn_Type IRQn) /* Check the parameters */ assert_param(IS_NVIC_DEVICE_IRQ(IRQn)); + /* Disable interrupt */ NVIC_DisableIRQ(IRQn); } @@ -253,8 +276,8 @@ uint32_t HAL_SYSTICK_Config(uint32_t TicksNumb) */ /** @defgroup CORTEX_Exported_Functions_Group2 Peripheral Control functions - * @brief Cortex control functions - * + * @brief Cortex control functions + * @verbatim ============================================================================== ##### Peripheral Control functions ##### @@ -268,47 +291,7 @@ uint32_t HAL_SYSTICK_Config(uint32_t TicksNumb) * @{ */ -#if (__MPU_PRESENT == 1U) -/** - * @brief Disables the MPU - * @retval None - */ -void HAL_MPU_Disable(void) -{ - /* Make sure outstanding transfers are done */ - __DMB(); - - /* Disable fault exceptions */ - SCB->SHCSR &= ~SCB_SHCSR_MEMFAULTENA_Msk; - - /* Disable the MPU and clear the control register*/ - MPU->CTRL = 0U; -} - -/** - * @brief Enable the MPU. - * @param MPU_Control: Specifies the control mode of the MPU during hard fault, - * NMI, FAULTMASK and privileged access to the default memory - * This parameter can be one of the following values: - * @arg MPU_HFNMI_PRIVDEF_NONE - * @arg MPU_HARDFAULT_NMI - * @arg MPU_PRIVILEGED_DEFAULT - * @arg MPU_HFNMI_PRIVDEF - * @retval None - */ -void HAL_MPU_Enable(uint32_t MPU_Control) -{ - /* Enable the MPU */ - MPU->CTRL = MPU_Control | MPU_CTRL_ENABLE_Msk; - - /* Enable fault exceptions */ - SCB->SHCSR |= SCB_SHCSR_MEMFAULTENA_Msk; - - /* Ensure MPU setting take effects */ - __DSB(); - __ISB(); -} - +#if (__MPU_PRESENT == 1) /** * @brief Initializes and configures the Region and the memory to be protected. * @param MPU_Init: Pointer to a MPU_Region_InitTypeDef structure that contains @@ -349,8 +332,8 @@ void HAL_MPU_ConfigRegion(MPU_Region_InitTypeDef *MPU_Init) } else { - MPU->RBAR = 0x00U; - MPU->RASR = 0x00U; + MPU->RBAR = 0x00; + MPU->RASR = 0x00; } } #endif /* __MPU_PRESENT */ @@ -367,26 +350,26 @@ uint32_t HAL_NVIC_GetPriorityGrouping(void) /** * @brief Gets the priority of an interrupt. - * @param IRQn: External interrupt number. + * @param IRQn: External interrupt number * This parameter can be an enumerator of IRQn_Type enumeration * (For the complete STM32 Devices IRQ Channels list, please refer to the appropriate CMSIS device file (stm32f10xxx.h)) * @param PriorityGroup: the priority grouping bits length. * This parameter can be one of the following values: - * @arg NVIC_PRIORITYGROUP_0: 0 bits for preemption priority + * @arg NVIC_PRIORITYGROUP_0: 0 bits for pre-emption priority * 4 bits for subpriority - * @arg NVIC_PRIORITYGROUP_1: 1 bits for preemption priority + * @arg NVIC_PRIORITYGROUP_1: 1 bits for pre-emption priority * 3 bits for subpriority - * @arg NVIC_PRIORITYGROUP_2: 2 bits for preemption priority + * @arg NVIC_PRIORITYGROUP_2: 2 bits for pre-emption priority * 2 bits for subpriority - * @arg NVIC_PRIORITYGROUP_3: 3 bits for preemption priority + * @arg NVIC_PRIORITYGROUP_3: 3 bits for pre-emption priority * 1 bits for subpriority - * @arg NVIC_PRIORITYGROUP_4: 4 bits for preemption priority + * @arg NVIC_PRIORITYGROUP_4: 4 bits for pre-emption priority * 0 bits for subpriority * @param pPreemptPriority: Pointer on the Preemptive priority value (starting from 0). * @param pSubPriority: Pointer on the Subpriority value (starting from 0). * @retval None */ -void HAL_NVIC_GetPriority(IRQn_Type IRQn, uint32_t PriorityGroup, uint32_t *pPreemptPriority, uint32_t *pSubPriority) +void HAL_NVIC_GetPriority(IRQn_Type IRQn, uint32_t PriorityGroup, uint32_t* pPreemptPriority, uint32_t* pSubPriority) { /* Check the parameters */ assert_param(IS_NVIC_PRIORITY_GROUP(PriorityGroup)); @@ -402,44 +385,35 @@ void HAL_NVIC_GetPriority(IRQn_Type IRQn, uint32_t PriorityGroup, uint32_t *pPre * @retval None */ void HAL_NVIC_SetPendingIRQ(IRQn_Type IRQn) -{ - /* Check the parameters */ - assert_param(IS_NVIC_DEVICE_IRQ(IRQn)); - +{ /* Set interrupt pending */ NVIC_SetPendingIRQ(IRQn); } /** - * @brief Gets Pending Interrupt (reads the pending register in the NVIC + * @brief Gets Pending Interrupt (reads the pending register in the NVIC * and returns the pending bit for the specified interrupt). - * @param IRQn External interrupt number. + * @param IRQn External interrupt number * This parameter can be an enumerator of IRQn_Type enumeration * (For the complete STM32 Devices IRQ Channels list, please refer to the appropriate CMSIS device file (stm32f10xxx.h)) * @retval status: - 0 Interrupt status is not pending. * - 1 Interrupt status is pending. */ uint32_t HAL_NVIC_GetPendingIRQ(IRQn_Type IRQn) -{ - /* Check the parameters */ - assert_param(IS_NVIC_DEVICE_IRQ(IRQn)); - +{ /* Return 1 if pending else 0 */ return NVIC_GetPendingIRQ(IRQn); } /** - * @brief Clears the pending bit of an external interrupt. - * @param IRQn External interrupt number. + * @brief Clears the pending bit of an external interrupt. + * @param IRQn External interrupt number * This parameter can be an enumerator of IRQn_Type enumeration * (For the complete STM32 Devices IRQ Channels list, please refer to the appropriate CMSIS device file (stm32f10xxx.h)) * @retval None */ void HAL_NVIC_ClearPendingIRQ(IRQn_Type IRQn) -{ - /* Check the parameters */ - assert_param(IS_NVIC_DEVICE_IRQ(IRQn)); - +{ /* Clear pending interrupt */ NVIC_ClearPendingIRQ(IRQn); } @@ -453,10 +427,7 @@ void HAL_NVIC_ClearPendingIRQ(IRQn_Type IRQn) * - 1 Interrupt status is pending. */ uint32_t HAL_NVIC_GetActive(IRQn_Type IRQn) -{ - /* Check the parameters */ - assert_param(IS_NVIC_DEVICE_IRQ(IRQn)); - +{ /* Return 1 if active else 0 */ return NVIC_GetActive(IRQn); } diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_cortex.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_cortex.h index f7fedadf0b5..a74f74d82a1 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_cortex.h +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_cortex.h @@ -2,13 +2,13 @@ ****************************************************************************** * @file stm32f1xx_hal_cortex.h * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief Header file of CORTEX HAL module. ****************************************************************************** * @attention * - *

© COPYRIGHT(c) 2017 STMicroelectronics

+ *

© COPYRIGHT(c) 2016 STMicroelectronics

* * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: @@ -58,7 +58,7 @@ * @{ */ -#if (__MPU_PRESENT == 1U) +#if (__MPU_PRESENT == 1) /** @defgroup CORTEX_MPU_Region_Initialization_Structure_definition MPU Region Initialization Structure Definition * @brief MPU Region initialization structure * @{ @@ -97,33 +97,34 @@ typedef struct */ /* Exported constants --------------------------------------------------------*/ - /** @defgroup CORTEX_Exported_Constants CORTEX Exported Constants * @{ */ -/** @defgroup CORTEX_Preemption_Priority_Group CORTEX Preemption Priority Group + +/** @defgroup CORTEX_Preemption_Priority_Group CORTEX Preemption Priority Group * @{ */ -#define NVIC_PRIORITYGROUP_0 0x00000007U /*!< 0 bits for pre-emption priority - 4 bits for subpriority */ -#define NVIC_PRIORITYGROUP_1 0x00000006U /*!< 1 bits for pre-emption priority - 3 bits for subpriority */ -#define NVIC_PRIORITYGROUP_2 0x00000005U /*!< 2 bits for pre-emption priority - 2 bits for subpriority */ -#define NVIC_PRIORITYGROUP_3 0x00000004U /*!< 3 bits for pre-emption priority - 1 bits for subpriority */ -#define NVIC_PRIORITYGROUP_4 0x00000003U /*!< 4 bits for pre-emption priority - 0 bits for subpriority */ + +#define NVIC_PRIORITYGROUP_0 ((uint32_t)0x00000007) /*!< 0 bits for pre-emption priority + 4 bits for subpriority */ +#define NVIC_PRIORITYGROUP_1 ((uint32_t)0x00000006) /*!< 1 bits for pre-emption priority + 3 bits for subpriority */ +#define NVIC_PRIORITYGROUP_2 ((uint32_t)0x00000005) /*!< 2 bits for pre-emption priority + 2 bits for subpriority */ +#define NVIC_PRIORITYGROUP_3 ((uint32_t)0x00000004) /*!< 3 bits for pre-emption priority + 1 bits for subpriority */ +#define NVIC_PRIORITYGROUP_4 ((uint32_t)0x00000003) /*!< 4 bits for pre-emption priority + 0 bits for subpriority */ /** * @} */ -/** @defgroup CORTEX_SysTick_clock_source CORTEX _SysTick clock source +/** @defgroup CORTEX_SysTick_clock_source CORTEX SysTick clock source * @{ */ -#define SYSTICK_CLKSOURCE_HCLK_DIV8 0x00000000U -#define SYSTICK_CLKSOURCE_HCLK 0x00000004U +#define SYSTICK_CLKSOURCE_HCLK_DIV8 ((uint32_t)0x00000000) +#define SYSTICK_CLKSOURCE_HCLK ((uint32_t)0x00000004) /** * @} @@ -133,11 +134,10 @@ typedef struct /** @defgroup CORTEX_MPU_HFNMI_PRIVDEF_Control MPU HFNMI and PRIVILEGED Access control * @{ */ -#define MPU_HFNMI_PRIVDEF_NONE 0x00000000U -#define MPU_HARDFAULT_NMI MPU_CTRL_HFNMIENA_Msk -#define MPU_PRIVILEGED_DEFAULT MPU_CTRL_PRIVDEFENA_Msk -#define MPU_HFNMI_PRIVDEF (MPU_CTRL_HFNMIENA_Msk | MPU_CTRL_PRIVDEFENA_Msk) - +#define MPU_HFNMI_PRIVDEF_NONE ((uint32_t)0x00000000) +#define MPU_HARDFAULT_NMI ((uint32_t)0x00000002) +#define MPU_PRIVILEGED_DEFAULT ((uint32_t)0x00000004) +#define MPU_HFNMI_PRIVDEF ((uint32_t)0x00000006) /** * @} */ @@ -202,44 +202,44 @@ typedef struct */ #define MPU_REGION_SIZE_32B ((uint8_t)0x04) #define MPU_REGION_SIZE_64B ((uint8_t)0x05) -#define MPU_REGION_SIZE_128B ((uint8_t)0x06) -#define MPU_REGION_SIZE_256B ((uint8_t)0x07) -#define MPU_REGION_SIZE_512B ((uint8_t)0x08) -#define MPU_REGION_SIZE_1KB ((uint8_t)0x09) +#define MPU_REGION_SIZE_128B ((uint8_t)0x06) +#define MPU_REGION_SIZE_256B ((uint8_t)0x07) +#define MPU_REGION_SIZE_512B ((uint8_t)0x08) +#define MPU_REGION_SIZE_1KB ((uint8_t)0x09) #define MPU_REGION_SIZE_2KB ((uint8_t)0x0A) -#define MPU_REGION_SIZE_4KB ((uint8_t)0x0B) -#define MPU_REGION_SIZE_8KB ((uint8_t)0x0C) -#define MPU_REGION_SIZE_16KB ((uint8_t)0x0D) -#define MPU_REGION_SIZE_32KB ((uint8_t)0x0E) -#define MPU_REGION_SIZE_64KB ((uint8_t)0x0F) +#define MPU_REGION_SIZE_4KB ((uint8_t)0x0B) +#define MPU_REGION_SIZE_8KB ((uint8_t)0x0C) +#define MPU_REGION_SIZE_16KB ((uint8_t)0x0D) +#define MPU_REGION_SIZE_32KB ((uint8_t)0x0E) +#define MPU_REGION_SIZE_64KB ((uint8_t)0x0F) #define MPU_REGION_SIZE_128KB ((uint8_t)0x10) #define MPU_REGION_SIZE_256KB ((uint8_t)0x11) #define MPU_REGION_SIZE_512KB ((uint8_t)0x12) -#define MPU_REGION_SIZE_1MB ((uint8_t)0x13) -#define MPU_REGION_SIZE_2MB ((uint8_t)0x14) -#define MPU_REGION_SIZE_4MB ((uint8_t)0x15) -#define MPU_REGION_SIZE_8MB ((uint8_t)0x16) +#define MPU_REGION_SIZE_1MB ((uint8_t)0x13) +#define MPU_REGION_SIZE_2MB ((uint8_t)0x14) +#define MPU_REGION_SIZE_4MB ((uint8_t)0x15) +#define MPU_REGION_SIZE_8MB ((uint8_t)0x16) #define MPU_REGION_SIZE_16MB ((uint8_t)0x17) #define MPU_REGION_SIZE_32MB ((uint8_t)0x18) #define MPU_REGION_SIZE_64MB ((uint8_t)0x19) #define MPU_REGION_SIZE_128MB ((uint8_t)0x1A) #define MPU_REGION_SIZE_256MB ((uint8_t)0x1B) #define MPU_REGION_SIZE_512MB ((uint8_t)0x1C) -#define MPU_REGION_SIZE_1GB ((uint8_t)0x1D) -#define MPU_REGION_SIZE_2GB ((uint8_t)0x1E) +#define MPU_REGION_SIZE_1GB ((uint8_t)0x1D) +#define MPU_REGION_SIZE_2GB ((uint8_t)0x1E) #define MPU_REGION_SIZE_4GB ((uint8_t)0x1F) -/** +/** * @} */ /** @defgroup CORTEX_MPU_Region_Permission_Attributes CORTEX MPU Region Permission Attributes * @{ */ -#define MPU_REGION_NO_ACCESS ((uint8_t)0x00) -#define MPU_REGION_PRIV_RW ((uint8_t)0x01) -#define MPU_REGION_PRIV_RW_URO ((uint8_t)0x02) -#define MPU_REGION_FULL_ACCESS ((uint8_t)0x03) -#define MPU_REGION_PRIV_RO ((uint8_t)0x05) +#define MPU_REGION_NO_ACCESS ((uint8_t)0x00) +#define MPU_REGION_PRIV_RW ((uint8_t)0x01) +#define MPU_REGION_PRIV_RW_URO ((uint8_t)0x02) +#define MPU_REGION_FULL_ACCESS ((uint8_t)0x03) +#define MPU_REGION_PRIV_RO ((uint8_t)0x05) #define MPU_REGION_PRIV_RO_URO ((uint8_t)0x06) /** * @} @@ -248,11 +248,11 @@ typedef struct /** @defgroup CORTEX_MPU_Region_Number CORTEX MPU Region Number * @{ */ -#define MPU_REGION_NUMBER0 ((uint8_t)0x00) -#define MPU_REGION_NUMBER1 ((uint8_t)0x01) -#define MPU_REGION_NUMBER2 ((uint8_t)0x02) -#define MPU_REGION_NUMBER3 ((uint8_t)0x03) -#define MPU_REGION_NUMBER4 ((uint8_t)0x04) +#define MPU_REGION_NUMBER0 ((uint8_t)0x00) +#define MPU_REGION_NUMBER1 ((uint8_t)0x01) +#define MPU_REGION_NUMBER2 ((uint8_t)0x02) +#define MPU_REGION_NUMBER3 ((uint8_t)0x03) +#define MPU_REGION_NUMBER4 ((uint8_t)0x04) #define MPU_REGION_NUMBER5 ((uint8_t)0x05) #define MPU_REGION_NUMBER6 ((uint8_t)0x06) #define MPU_REGION_NUMBER7 ((uint8_t)0x07) @@ -264,61 +264,14 @@ typedef struct /** * @} */ - - -/* Exported Macros -----------------------------------------------------------*/ - -/* Exported functions --------------------------------------------------------*/ -/** @addtogroup CORTEX_Exported_Functions - * @{ - */ -/** @addtogroup CORTEX_Exported_Functions_Group1 - * @{ - */ -/* Initialization and de-initialization functions *****************************/ -void HAL_NVIC_SetPriorityGrouping(uint32_t PriorityGroup); -void HAL_NVIC_SetPriority(IRQn_Type IRQn, uint32_t PreemptPriority, uint32_t SubPriority); -void HAL_NVIC_EnableIRQ(IRQn_Type IRQn); -void HAL_NVIC_DisableIRQ(IRQn_Type IRQn); -void HAL_NVIC_SystemReset(void); -uint32_t HAL_SYSTICK_Config(uint32_t TicksNumb); -/** - * @} - */ -/** @addtogroup CORTEX_Exported_Functions_Group2 +/* Private macro -------------------------------------------------------------*/ +/** @defgroup CORTEX_Private_Macros CORTEX Private Macros * @{ - */ -/* Peripheral Control functions ***********************************************/ -uint32_t HAL_NVIC_GetPriorityGrouping(void); -void HAL_NVIC_GetPriority(IRQn_Type IRQn, uint32_t PriorityGroup, uint32_t* pPreemptPriority, uint32_t* pSubPriority); -uint32_t HAL_NVIC_GetPendingIRQ(IRQn_Type IRQn); -void HAL_NVIC_SetPendingIRQ(IRQn_Type IRQn); -void HAL_NVIC_ClearPendingIRQ(IRQn_Type IRQn); -uint32_t HAL_NVIC_GetActive(IRQn_Type IRQn); -void HAL_SYSTICK_CLKSourceConfig(uint32_t CLKSource); -void HAL_SYSTICK_IRQHandler(void); -void HAL_SYSTICK_Callback(void); - -#if (__MPU_PRESENT == 1U) -void HAL_MPU_Enable(uint32_t MPU_Control); -void HAL_MPU_Disable(void); -void HAL_MPU_ConfigRegion(MPU_Region_InitTypeDef *MPU_Init); -#endif /* __MPU_PRESENT */ -/** - * @} - */ - -/** - * @} - */ + */ -/* Private types -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private constants ---------------------------------------------------------*/ -/* Private macros ------------------------------------------------------------*/ -/** @defgroup CORTEX_Private_Macros CORTEX Private Macros +/** @defgroup CORTEX_Preemption_Priority_Group_Macro CORTEX Preemption Priority Group * @{ */ #define IS_NVIC_PRIORITY_GROUP(GROUP) (((GROUP) == NVIC_PRIORITYGROUP_0) || \ @@ -327,16 +280,25 @@ void HAL_MPU_ConfigRegion(MPU_Region_InitTypeDef *MPU_Init); ((GROUP) == NVIC_PRIORITYGROUP_3) || \ ((GROUP) == NVIC_PRIORITYGROUP_4)) -#define IS_NVIC_PREEMPTION_PRIORITY(PRIORITY) ((PRIORITY) < 0x10U) +#define IS_NVIC_PREEMPTION_PRIORITY(PRIORITY) ((PRIORITY) < 0x10) + +#define IS_NVIC_SUB_PRIORITY(PRIORITY) ((PRIORITY) < 0x10) -#define IS_NVIC_SUB_PRIORITY(PRIORITY) ((PRIORITY) < 0x10U) +#define IS_NVIC_DEVICE_IRQ(IRQ) ((IRQ) >= 0x00) -#define IS_NVIC_DEVICE_IRQ(IRQ) ((IRQ) >= (IRQn_Type)0x00U) +/** + * @} + */ +/** @defgroup CORTEX_SysTick_clock_source_Macro_Private CORTEX SysTick clock source + * @{ + */ #define IS_SYSTICK_CLK_SOURCE(SOURCE) (((SOURCE) == SYSTICK_CLKSOURCE_HCLK) || \ ((SOURCE) == SYSTICK_CLKSOURCE_HCLK_DIV8)) - -#if (__MPU_PRESENT == 1U) +/** + * @} + */ +#if (__MPU_PRESENT == 1) #define IS_MPU_REGION_ENABLE(STATE) (((STATE) == MPU_REGION_ENABLE) || \ ((STATE) == MPU_REGION_DISABLE)) @@ -404,11 +366,97 @@ void HAL_MPU_ConfigRegion(MPU_Region_InitTypeDef *MPU_Init); #define IS_MPU_SUB_REGION_DISABLE(SUBREGION) ((SUBREGION) < (uint16_t)0x00FF) #endif /* __MPU_PRESENT */ -/** - * @} +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/** @addtogroup CORTEX_Exported_Functions + * @{ + */ + +/** @addtogroup CORTEX_Exported_Functions_Group1 + * @{ + */ +/* Initialization and de-initialization functions *****************************/ +void HAL_NVIC_SetPriorityGrouping(uint32_t PriorityGroup); +void HAL_NVIC_SetPriority(IRQn_Type IRQn, uint32_t PreemptPriority, uint32_t SubPriority); +void HAL_NVIC_EnableIRQ(IRQn_Type IRQn); +void HAL_NVIC_DisableIRQ(IRQn_Type IRQn); +void HAL_NVIC_SystemReset(void); +uint32_t HAL_SYSTICK_Config(uint32_t TicksNumb); +/** + * @} + */ + +/** @addtogroup CORTEX_Exported_Functions_Group2 + * @{ + */ +/* Peripheral Control functions ***********************************************/ +#if (__MPU_PRESENT == 1) +void HAL_MPU_ConfigRegion(MPU_Region_InitTypeDef *MPU_Init); +#endif /* __MPU_PRESENT */ +uint32_t HAL_NVIC_GetPriorityGrouping(void); +void HAL_NVIC_GetPriority(IRQn_Type IRQn, uint32_t PriorityGroup, uint32_t* pPreemptPriority, uint32_t* pSubPriority); +uint32_t HAL_NVIC_GetPendingIRQ(IRQn_Type IRQn); +void HAL_NVIC_SetPendingIRQ(IRQn_Type IRQn); +void HAL_NVIC_ClearPendingIRQ(IRQn_Type IRQn); +uint32_t HAL_NVIC_GetActive(IRQn_Type IRQn); +void HAL_SYSTICK_CLKSourceConfig(uint32_t CLKSource); +void HAL_SYSTICK_IRQHandler(void); +void HAL_SYSTICK_Callback(void); +/** + * @} + */ + +/** + * @} + */ + +/* Private functions ---------------------------------------------------------*/ +/** @defgroup CORTEX_Private_Functions CORTEX Private Functions + * @brief CORTEX private functions + * @{ */ -/* Private functions ---------------------------------------------------------*/ +#if (__MPU_PRESENT == 1) +/** + * @brief Disables the MPU + * @retval None + */ +__STATIC_INLINE void HAL_MPU_Disable(void) +{ + /* Disable fault exceptions */ + SCB->SHCSR &= ~SCB_SHCSR_MEMFAULTENA_Msk; + + /* Disable the MPU */ + MPU->CTRL &= ~MPU_CTRL_ENABLE_Msk; +} + +/** + * @brief Enables the MPU + * @param MPU_Control: Specifies the control mode of the MPU during hard fault, + * NMI, FAULTMASK and privileged accessto the default memory + * This parameter can be one of the following values: + * @arg MPU_HFNMI_PRIVDEF_NONE + * @arg MPU_HARDFAULT_NMI + * @arg MPU_PRIVILEGED_DEFAULT + * @arg MPU_HFNMI_PRIVDEF + * @retval None + */ +__STATIC_INLINE void HAL_MPU_Enable(uint32_t MPU_Control) +{ + /* Enable the MPU */ + MPU->CTRL = MPU_Control | MPU_CTRL_ENABLE_Msk; + + /* Enable fault exceptions */ + SCB->SHCSR |= SCB_SHCSR_MEMFAULTENA_Msk; +} +#endif /* __MPU_PRESENT */ + +/** + * @} + */ /** * @} diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_crc.c b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_crc.c index ab491e39b2e..fe8195b06ee 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_crc.c +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_crc.c @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_hal_crc.c * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief CRC HAL module driver. * This file provides firmware functions to manage the following * functionalities of the Cyclic Redundancy Check (CRC) peripheral: @@ -162,9 +162,6 @@ HAL_StatusTypeDef HAL_CRC_DeInit(CRC_HandleTypeDef *hcrc) /* Resets the CRC calculation unit and sets the data register to 0xFFFF FFFF */ __HAL_CRC_DR_RESET(hcrc); - /* Reset IDR register content */ - CLEAR_BIT(hcrc->Instance->IDR, CRC_IDR_IDR); - /* Change CRC peripheral state */ hcrc->State = HAL_CRC_STATE_RESET; @@ -237,7 +234,7 @@ __weak void HAL_CRC_MspDeInit(CRC_HandleTypeDef *hcrc) */ uint32_t HAL_CRC_Accumulate(CRC_HandleTypeDef *hcrc, uint32_t pBuffer[], uint32_t BufferLength) { - uint32_t index = 0U; + uint32_t index = 0; /* Process Locked */ __HAL_LOCK(hcrc); @@ -246,7 +243,7 @@ uint32_t HAL_CRC_Accumulate(CRC_HandleTypeDef *hcrc, uint32_t pBuffer[], uint32_ hcrc->State = HAL_CRC_STATE_BUSY; /* Enter Data to the CRC calculator */ - for(index = 0U; index < BufferLength; index++) + for(index = 0; index < BufferLength; index++) { hcrc->Instance->DR = pBuffer[index]; } @@ -272,7 +269,7 @@ uint32_t HAL_CRC_Accumulate(CRC_HandleTypeDef *hcrc, uint32_t pBuffer[], uint32_ */ uint32_t HAL_CRC_Calculate(CRC_HandleTypeDef *hcrc, uint32_t pBuffer[], uint32_t BufferLength) { - uint32_t index = 0U; + uint32_t index = 0; /* Process Locked */ __HAL_LOCK(hcrc); @@ -284,7 +281,7 @@ uint32_t HAL_CRC_Calculate(CRC_HandleTypeDef *hcrc, uint32_t pBuffer[], uint32_t __HAL_CRC_DR_RESET(hcrc); /* Enter Data to the CRC calculator */ - for(index = 0U; index < BufferLength; index++) + for(index = 0; index < BufferLength; index++) { hcrc->Instance->DR = pBuffer[index]; } diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_crc.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_crc.h index 155f387eeae..83d0e078a14 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_crc.h +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_crc.h @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_hal_crc.h * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief Header file of CRC HAL module. ****************************************************************************** * @attention @@ -65,11 +65,11 @@ */ typedef enum { - HAL_CRC_STATE_RESET = 0x00U, /*!< CRC not yet initialized or disabled */ - HAL_CRC_STATE_READY = 0x01U, /*!< CRC initialized and ready for use */ - HAL_CRC_STATE_BUSY = 0x02U, /*!< CRC internal process is ongoing */ - HAL_CRC_STATE_TIMEOUT = 0x03U, /*!< CRC timeout state */ - HAL_CRC_STATE_ERROR = 0x04U /*!< CRC error state */ + HAL_CRC_STATE_RESET = 0x00, /*!< CRC not yet initialized or disabled */ + HAL_CRC_STATE_READY = 0x01, /*!< CRC initialized and ready for use */ + HAL_CRC_STATE_BUSY = 0x02, /*!< CRC internal process is ongoing */ + HAL_CRC_STATE_TIMEOUT = 0x03, /*!< CRC timeout state */ + HAL_CRC_STATE_ERROR = 0x04 /*!< CRC error state */ }HAL_CRC_StateTypeDef; diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_dac.c b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_dac.c index 1c84042343d..f380eae018b 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_dac.c +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_dac.c @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_hal_dac.c * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief DAC HAL module driver. * This file provides firmware functions to manage the following * functionalities of the Digital to Analog Converter (DAC) peripheral: @@ -471,7 +471,7 @@ HAL_StatusTypeDef HAL_DAC_Stop(DAC_HandleTypeDef* hdac, uint32_t Channel) * This parameter can be one of the following values: * @arg DAC_CHANNEL_1: DAC Channel1 selected * @arg DAC_CHANNEL_2: DAC Channel2 selected - * @param pData: The Source memory Buffer address. + * @param pData: The destination peripheral Buffer address. * @param Length: The length of data to be transferred from memory to DAC peripheral * @param Alignment: Specifies the data alignment for DAC channel. * This parameter can be one of the following values: @@ -482,7 +482,7 @@ HAL_StatusTypeDef HAL_DAC_Stop(DAC_HandleTypeDef* hdac, uint32_t Channel) */ __weak HAL_StatusTypeDef HAL_DAC_Start_DMA(DAC_HandleTypeDef* hdac, uint32_t Channel, uint32_t* pData, uint32_t Length, uint32_t Alignment) { - uint32_t tmpreg = 0U; + uint32_t tmpreg = 0; /* Check the parameters */ assert_param(IS_DAC_CHANNEL(Channel)); @@ -740,7 +740,7 @@ __weak void HAL_DAC_ErrorCallbackCh1(DAC_HandleTypeDef *hdac) */ HAL_StatusTypeDef HAL_DAC_ConfigChannel(DAC_HandleTypeDef* hdac, DAC_ChannelConfTypeDef* sConfig, uint32_t Channel) { - uint32_t tmpreg1 = 0U; + uint32_t tmpreg1 = 0; /* Check the DAC parameters */ assert_param(IS_DAC_TRIGGER(sConfig->DAC_Trigger)); @@ -795,7 +795,7 @@ HAL_StatusTypeDef HAL_DAC_ConfigChannel(DAC_HandleTypeDef* hdac, DAC_ChannelConf */ HAL_StatusTypeDef HAL_DAC_SetValue(DAC_HandleTypeDef* hdac, uint32_t Channel, uint32_t Alignment, uint32_t Data) { - __IO uint32_t tmp = 0U; + __IO uint32_t tmp = 0; /* Check the parameters */ assert_param(IS_DAC_CHANNEL(Channel)); diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_dac.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_dac.h index 9487a1ef7e6..6e095cfce5f 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_dac.h +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_dac.h @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_hal_dac.h * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief Header file of DAC HAL module. ****************************************************************************** * @attention @@ -67,11 +67,11 @@ */ typedef enum { - HAL_DAC_STATE_RESET = 0x00U, /*!< DAC not yet initialized or disabled */ - HAL_DAC_STATE_READY = 0x01U, /*!< DAC initialized and ready for use */ - HAL_DAC_STATE_BUSY = 0x02U, /*!< DAC internal processing is ongoing */ - HAL_DAC_STATE_TIMEOUT = 0x03U, /*!< DAC timeout state */ - HAL_DAC_STATE_ERROR = 0x04U /*!< DAC error state */ + HAL_DAC_STATE_RESET = 0x00, /*!< DAC not yet initialized or disabled */ + HAL_DAC_STATE_READY = 0x01, /*!< DAC initialized and ready for use */ + HAL_DAC_STATE_BUSY = 0x02, /*!< DAC internal processing is ongoing */ + HAL_DAC_STATE_TIMEOUT = 0x03, /*!< DAC timeout state */ + HAL_DAC_STATE_ERROR = 0x04 /*!< DAC error state */ }HAL_DAC_StateTypeDef; @@ -121,10 +121,10 @@ typedef struct /** @defgroup DAC_Error_Code DAC Error Code * @{ */ -#define HAL_DAC_ERROR_NONE 0x00000000U /*!< No error */ -#define HAL_DAC_ERROR_DMAUNDERRUNCH1 0x00000001U /*!< DAC channel1 DMA underrun error */ -#define HAL_DAC_ERROR_DMAUNDERRUNCH2 0x00000002U /*!< DAC channel2 DMA underrun error */ -#define HAL_DAC_ERROR_DMA 0x00000004U /*!< DMA error */ +#define HAL_DAC_ERROR_NONE 0x00 /*!< No error */ +#define HAL_DAC_ERROR_DMAUNDERRUNCH1 0x01 /*!< DAC channel1 DMA underrun error */ +#define HAL_DAC_ERROR_DMAUNDERRUNCH2 0x02 /*!< DAC channel2 DMA underrun error */ +#define HAL_DAC_ERROR_DMA 0x04 /*!< DMA error */ /** * @} */ @@ -132,7 +132,7 @@ typedef struct /** @defgroup DAC_output_buffer DAC output buffer * @{ */ -#define DAC_OUTPUTBUFFER_ENABLE 0x00000000U +#define DAC_OUTPUTBUFFER_ENABLE ((uint32_t)0x00000000) #define DAC_OUTPUTBUFFER_DISABLE ((uint32_t)DAC_CR_BOFF1) /** @@ -142,8 +142,8 @@ typedef struct /** @defgroup DAC_Channel_selection DAC Channel selection * @{ */ -#define DAC_CHANNEL_1 0x00000000U -#define DAC_CHANNEL_2 0x00000010U +#define DAC_CHANNEL_1 ((uint32_t)0x00000000) +#define DAC_CHANNEL_2 ((uint32_t)0x00000010) /** * @} @@ -152,9 +152,9 @@ typedef struct /** @defgroup DAC_data_alignement DAC data alignement * @{ */ -#define DAC_ALIGN_12B_R 0x00000000U -#define DAC_ALIGN_12B_L 0x00000004U -#define DAC_ALIGN_8B_R 0x00000008U +#define DAC_ALIGN_12B_R ((uint32_t)0x00000000) +#define DAC_ALIGN_12B_L ((uint32_t)0x00000004) +#define DAC_ALIGN_8B_R ((uint32_t)0x00000008) /** * @} @@ -212,13 +212,13 @@ typedef struct ((ALIGN) == DAC_ALIGN_12B_L) || \ ((ALIGN) == DAC_ALIGN_8B_R)) -#define IS_DAC_DATA(DATA) ((DATA) <= 0xFFF0U) +#define IS_DAC_DATA(DATA) ((DATA) <= 0xFFF0) -#define DAC_DHR12R1_ALIGNMENT(__ALIGNMENT__) (0x00000008U + (__ALIGNMENT__)) +#define DAC_DHR12R1_ALIGNMENT(__ALIGNMENT__) (((uint32_t)0x00000008) + (__ALIGNMENT__)) -#define DAC_DHR12R2_ALIGNMENT(__ALIGNMENT__) (0x00000014U + (__ALIGNMENT__)) +#define DAC_DHR12R2_ALIGNMENT(__ALIGNMENT__) (((uint32_t)0x00000014) + (__ALIGNMENT__)) -#define DAC_DHR12RD_ALIGNMENT(__ALIGNMENT__) (0x00000020U + (__ALIGNMENT__)) +#define DAC_DHR12RD_ALIGNMENT(__ALIGNMENT__) (((uint32_t)0x00000020) + (__ALIGNMENT__)) /** * @} diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_dac_ex.c b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_dac_ex.c index 188cefb7d78..38ebcecbd47 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_dac_ex.c +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_dac_ex.c @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_hal_dac_ex.c * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief DAC HAL module driver. * This file provides firmware functions to manage the following * functionalities of DAC extension peripheral: @@ -106,11 +106,11 @@ */ uint32_t HAL_DACEx_DualGetValue(DAC_HandleTypeDef* hdac) { - uint32_t tmp = 0U; + uint32_t tmp = 0; tmp |= hdac->Instance->DOR1; - tmp |= hdac->Instance->DOR2 << 16U; + tmp |= hdac->Instance->DOR2 << 16; /* Returns the DAC channel data output register value */ return tmp; @@ -229,7 +229,7 @@ HAL_StatusTypeDef HAL_DACEx_NoiseWaveGenerate(DAC_HandleTypeDef* hdac, uint32_t */ HAL_StatusTypeDef HAL_DACEx_DualSetValue(DAC_HandleTypeDef* hdac, uint32_t Alignment, uint32_t Data1, uint32_t Data2) { - uint32_t data = 0U, tmp = 0U; + uint32_t data = 0, tmp = 0; /* Check the parameters */ assert_param(IS_DAC_ALIGN(Alignment)); @@ -239,11 +239,11 @@ HAL_StatusTypeDef HAL_DACEx_DualSetValue(DAC_HandleTypeDef* hdac, uint32_t Align /* Calculate and set dual DAC data holding register value */ if (Alignment == DAC_ALIGN_8B_R) { - data = ((uint32_t)Data2 << 8U) | Data1; + data = ((uint32_t)Data2 << 8) | Data1; } else { - data = ((uint32_t)Data2 << 16U) | Data1; + data = ((uint32_t)Data2 << 16) | Data1; } tmp = (uint32_t)hdac->Instance; @@ -366,7 +366,7 @@ __weak void HAL_DACEx_DMAUnderrunCallbackCh2(DAC_HandleTypeDef *hdac) */ HAL_StatusTypeDef HAL_DAC_Start_DMA(DAC_HandleTypeDef* hdac, uint32_t Channel, uint32_t* pData, uint32_t Length, uint32_t Alignment) { - uint32_t tmpreg = 0U; + uint32_t tmpreg = 0; /* Check the parameters */ assert_param(IS_DAC_CHANNEL(Channel)); diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_dac_ex.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_dac_ex.h index 1fc977ee4d1..5f5c9c856a5 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_dac_ex.h +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_dac_ex.h @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_hal_dac_ex.h * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief Header file of DAC HAL Extension module. ****************************************************************************** * @attention @@ -67,7 +67,7 @@ /** @defgroup DACEx_lfsrunmask_triangleamplitude DACEx lfsrunmask triangleamplitude * @{ */ -#define DAC_LFSRUNMASK_BIT0 0x00000000U /*!< Unmask DAC channel LFSR bit0 for noise wave generation */ +#define DAC_LFSRUNMASK_BIT0 ((uint32_t)0x00000000) /*!< Unmask DAC channel LFSR bit0 for noise wave generation */ #define DAC_LFSRUNMASK_BITS1_0 ((uint32_t)DAC_CR_MAMP1_0) /*!< Unmask DAC channel LFSR bit[1:0] for noise wave generation */ #define DAC_LFSRUNMASK_BITS2_0 ((uint32_t)DAC_CR_MAMP1_1) /*!< Unmask DAC channel LFSR bit[2:0] for noise wave generation */ #define DAC_LFSRUNMASK_BITS3_0 ((uint32_t)DAC_CR_MAMP1_1 | DAC_CR_MAMP1_0)/*!< Unmask DAC channel LFSR bit[3:0] for noise wave generation */ @@ -79,7 +79,7 @@ #define DAC_LFSRUNMASK_BITS9_0 ((uint32_t)DAC_CR_MAMP1_3 | DAC_CR_MAMP1_0) /*!< Unmask DAC channel LFSR bit[9:0] for noise wave generation */ #define DAC_LFSRUNMASK_BITS10_0 ((uint32_t)DAC_CR_MAMP1_3 | DAC_CR_MAMP1_1) /*!< Unmask DAC channel LFSR bit[10:0] for noise wave generation */ #define DAC_LFSRUNMASK_BITS11_0 ((uint32_t)DAC_CR_MAMP1_3 | DAC_CR_MAMP1_1 | DAC_CR_MAMP1_0) /*!< Unmask DAC channel LFSR bit[11:0] for noise wave generation */ -#define DAC_TRIANGLEAMPLITUDE_1 0x00000000U /*!< Select max triangle amplitude of 1 */ +#define DAC_TRIANGLEAMPLITUDE_1 ((uint32_t)0x00000000) /*!< Select max triangle amplitude of 1 */ #define DAC_TRIANGLEAMPLITUDE_3 ((uint32_t)DAC_CR_MAMP1_0) /*!< Select max triangle amplitude of 3 */ #define DAC_TRIANGLEAMPLITUDE_7 ((uint32_t)DAC_CR_MAMP1_1) /*!< Select max triangle amplitude of 7 */ #define DAC_TRIANGLEAMPLITUDE_15 ((uint32_t)DAC_CR_MAMP1_1 | DAC_CR_MAMP1_0) /*!< Select max triangle amplitude of 15 */ @@ -99,7 +99,7 @@ /** @defgroup DACEx_trigger_selection DAC trigger selection * @{ */ -#define DAC_TRIGGER_NONE 0x00000000U /*!< Conversion is automatic once the DAC1_DHRxxxx register +#define DAC_TRIGGER_NONE ((uint32_t)0x00000000) /*!< Conversion is automatic once the DAC1_DHRxxxx register has been loaded, and not by external trigger */ #define DAC_TRIGGER_T6_TRGO ((uint32_t) DAC_CR_TEN1) /*!< TIM6 TRGO selected as external conversion trigger for DAC channel */ #define DAC_TRIGGER_T7_TRGO ((uint32_t)( DAC_CR_TSEL1_1 | DAC_CR_TEN1)) /*!< TIM7 TRGO selected as external conversion trigger for DAC channel */ diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_def.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_def.h index be4adf42f4f..9f1eeeace33 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_def.h +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_def.h @@ -2,14 +2,14 @@ ****************************************************************************** * @file stm32f1xx_hal_def.h * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief This file contains HAL common defines, enumeration, macros and * structures definitions. ****************************************************************************** * @attention * - *

© COPYRIGHT(c) 2017 STMicroelectronics

+ *

© COPYRIGHT(c) 2016 STMicroelectronics

* * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: @@ -46,9 +46,7 @@ /* Includes ------------------------------------------------------------------*/ #include "stm32f1xx.h" -#if defined(USE_HAL_LEGACY) #include "stm32_hal_legacy.h" -#endif #include /* Exported types ------------------------------------------------------------*/ @@ -58,10 +56,10 @@ */ typedef enum { - HAL_OK = 0x00U, - HAL_ERROR = 0x01U, - HAL_BUSY = 0x02U, - HAL_TIMEOUT = 0x03U + HAL_OK = 0x00, + HAL_ERROR = 0x01, + HAL_BUSY = 0x02, + HAL_TIMEOUT = 0x03 } HAL_StatusTypeDef; /** @@ -69,21 +67,22 @@ typedef enum */ typedef enum { - HAL_UNLOCKED = 0x00U, - HAL_LOCKED = 0x01U + HAL_UNLOCKED = 0x00, + HAL_LOCKED = 0x01 } HAL_LockTypeDef; /* Exported macro ------------------------------------------------------------*/ -#define HAL_MAX_DELAY 0xFFFFFFFFU + +#define HAL_MAX_DELAY 0xFFFFFFFF #define HAL_IS_BIT_SET(REG, BIT) (((REG) & (BIT)) != RESET) #define HAL_IS_BIT_CLR(REG, BIT) (((REG) & (BIT)) == RESET) -#define __HAL_LINKDMA(__HANDLE__, __PPP_DMA_FIELD__, __DMA_HANDLE__) \ - do{ \ - (__HANDLE__)->__PPP_DMA_FIELD__ = &(__DMA_HANDLE__); \ - (__DMA_HANDLE__).Parent = (__HANDLE__); \ - } while(0U) +#define __HAL_LINKDMA(__HANDLE__, __PPP_DMA_FIELD_, __DMA_HANDLE_) \ + do{ \ + (__HANDLE__)->__PPP_DMA_FIELD_ = &(__DMA_HANDLE_); \ + (__DMA_HANDLE_).Parent = (__HANDLE__); \ + } while(0) #define UNUSED(x) ((void)(x)) @@ -102,15 +101,14 @@ typedef enum * HAL_PPP_MspInit() which will reconfigure the low level hardware. * @retval None */ -#define __HAL_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = 0U) +#define __HAL_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = 0) -#if (USE_RTOS == 1U) - /* Reserved for future use */ - #error "USE_RTOS should be 0 in the current HAL release" +#if (USE_RTOS == 1) + #error " USE_RTOS should be 0 in the current HAL release " #else #define __HAL_LOCK(__HANDLE__) \ do{ \ - if((__HANDLE__)->Lock == HAL_LOCKED) \ + if((__HANDLE__)->Lock == HAL_LOCKED) \ { \ return HAL_BUSY; \ } \ @@ -118,15 +116,15 @@ typedef enum { \ (__HANDLE__)->Lock = HAL_LOCKED; \ } \ - }while (0U) + }while (0) #define __HAL_UNLOCK(__HANDLE__) \ do{ \ - (__HANDLE__)->Lock = HAL_UNLOCKED; \ - }while (0U) + (__HANDLE__)->Lock = HAL_UNLOCKED; \ + }while (0) #endif /* USE_RTOS */ -#if defined ( __GNUC__ ) && !defined ( __CC_ARM ) +#if defined ( __GNUC__ ) #ifndef __weak #define __weak __attribute__((weak)) #endif /* __weak */ @@ -150,14 +148,13 @@ typedef enum #endif /* __ALIGN_END */ #ifndef __ALIGN_BEGIN #if defined (__CC_ARM) /* ARM Compiler */ - #define __ALIGN_BEGIN __align(4) + #define __ALIGN_BEGIN __align(4) #elif defined (__ICCARM__) /* IAR Compiler */ #define __ALIGN_BEGIN #endif /* __CC_ARM */ #endif /* __ALIGN_BEGIN */ #endif /* __GNUC__ */ - /** * @brief __RAM_FUNC definition */ @@ -197,7 +194,7 @@ typedef enum /* ARM & GNUCompiler ---------------- */ -#define __NOINLINE __attribute__ ( (noinline) ) +#define __NOINLINE __attribute__ ( (noinline) ) #elif defined ( __ICCARM__ ) /* ICCARM Compiler @@ -207,6 +204,7 @@ typedef enum #endif + #ifdef __cplusplus } #endif diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_dma.c b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_dma.c index 2b271fccf2b..76167bb4d8a 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_dma.c +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_dma.c @@ -2,27 +2,28 @@ ****************************************************************************** * @file stm32f1xx_hal_dma.c * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief DMA HAL module driver. - * This file provides firmware functions to manage the following - * functionalities of the Direct Memory Access (DMA) peripheral: + * + * This file provides firmware functions to manage the following + * functionalities of the Direct Memory Access (DMA) peripheral: * + Initialization and de-initialization functions * + IO operation functions * + Peripheral State and errors functions - @verbatim - ============================================================================== + @verbatim + ============================================================================== ##### How to use this driver ##### - ============================================================================== + ============================================================================== [..] (#) Enable and configure the peripheral to be connected to the DMA Channel (except for internal SRAM / FLASH memories: no initialization is - necessary). Please refer to the Reference manual for connection between peripherals + necessary) please refer to Reference manual for connection between peripherals and DMA requests. - (#) For a given Channel, program the required configuration through the following parameters: - Channel request, Transfer Direction, Source and Destination data formats, - Circular or Normal mode, Channel Priority level, Source and Destination Increment mode + (#) For a given Channel, program the required configuration through the following parameters: + Transfer Direction, Source and Destination data formats, + Circular or Normal mode, Channel Priority level, Source and Destination Increment mode, using HAL_DMA_Init() function. (#) Use HAL_DMA_GetState() function to return the DMA state and HAL_DMA_GetError() in case of error @@ -32,29 +33,29 @@ -@- In Memory-to-Memory transfer mode, Circular mode is not allowed. *** Polling mode IO operation *** - ================================= + ================================= + [..] + (+) Use HAL_DMA_Start() to start DMA transfer after the configuration of Source + address and destination address and the Length of data to be transferred + (+) Use HAL_DMA_PollForTransfer() to poll for the end of current transfer, in this + case a fixed Timeout can be configured by User depending from his application. + + *** Interrupt mode IO operation *** + =================================== [..] - (+) Use HAL_DMA_Start() to start DMA transfer after the configuration of Source - address and destination address and the Length of data to be transferred - (+) Use HAL_DMA_PollForTransfer() to poll for the end of current transfer, in this - case a fixed Timeout can be configured by User depending from his application. - - *** Interrupt mode IO operation *** - =================================== - [..] - (+) Configure the DMA interrupt priority using HAL_NVIC_SetPriority() - (+) Enable the DMA IRQ handler using HAL_NVIC_EnableIRQ() - (+) Use HAL_DMA_Start_IT() to start DMA transfer after the configuration of - Source address and destination address and the Length of data to be transferred. - In this case the DMA interrupt is configured - (+) Use HAL_DMA_IRQHandler() called under DMA_IRQHandler() Interrupt subroutine - (+) At the end of data transfer HAL_DMA_IRQHandler() function is executed and user can - add his own function by customization of function pointer XferCpltCallback and - XferErrorCallback (i.e. a member of DMA handle structure). + (+) Configure the DMA interrupt priority using HAL_NVIC_SetPriority() + (+) Enable the DMA IRQ handler using HAL_NVIC_EnableIRQ() + (+) Use HAL_DMA_Start_IT() to start DMA transfer after the configuration of + Source address and destination address and the Length of data to be transferred. + In this case the DMA interrupt is configured + (+) Use HAL_DMAy_Channelx_IRQHandler() called under DMA_IRQHandler() Interrupt subroutine + (+) At the end of data transfer HAL_DMA_IRQHandler() function is executed and user can + add his own function by customization of function pointer XferCpltCallback and + XferErrorCallback (i.e a member of DMA handle structure). *** DMA HAL driver macros list *** ============================================= - [..] + [..] Below the list of most used macros in DMA HAL driver. (+) __HAL_DMA_ENABLE: Enable the specified DMA Channel. @@ -72,7 +73,7 @@ ****************************************************************************** * @attention * - *

© COPYRIGHT(c) 2017 STMicroelectronics

+ *

© COPYRIGHT(c) 2016 STMicroelectronics

* * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: @@ -97,7 +98,7 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** - */ + */ /* Includes ------------------------------------------------------------------*/ #include "stm32f1xx_hal.h" @@ -115,6 +116,14 @@ /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ +/** @defgroup DMA_Private_Constants DMA Private Constants + * @{ + */ +#define HAL_TIMEOUT_DMA_ABORT ((uint32_t)1000) /* 1s */ +/** + * @} + */ + /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ @@ -133,12 +142,12 @@ static void DMA_SetConfig(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t */ /** @defgroup DMA_Exported_Functions_Group1 Initialization and de-initialization functions - * @brief Initialization and de-initialization functions - * -@verbatim + * @brief Initialization and de-initialization functions + * +@verbatim =============================================================================== ##### Initialization and de-initialization functions ##### - =============================================================================== + =============================================================================== [..] This section provides functions allowing to initialize the DMA Channel source and destination addresses, incrementation and data sizes, transfer direction, @@ -150,24 +159,24 @@ static void DMA_SetConfig(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t @endverbatim * @{ */ - + /** - * @brief Initialize the DMA according to the specified - * parameters in the DMA_InitTypeDef and initialize the associated handle. + * @brief Initializes the DMA according to the specified + * parameters in the DMA_InitTypeDef and create the associated handle. * @param hdma: Pointer to a DMA_HandleTypeDef structure that contains - * the configuration information for the specified DMA Channel. + * the configuration information for the specified DMA Channel. * @retval HAL status */ HAL_StatusTypeDef HAL_DMA_Init(DMA_HandleTypeDef *hdma) -{ - uint32_t tmp = 0U; - +{ + uint32_t tmp = 0; + /* Check the DMA handle allocation */ if(hdma == NULL) { return HAL_ERROR; } - + /* Check the parameters */ assert_param(IS_DMA_ALL_INSTANCE(hdma->Instance)); assert_param(IS_DMA_DIRECTION(hdma->Init.Direction)); @@ -177,38 +186,24 @@ HAL_StatusTypeDef HAL_DMA_Init(DMA_HandleTypeDef *hdma) assert_param(IS_DMA_MEMORY_DATA_SIZE(hdma->Init.MemDataAlignment)); assert_param(IS_DMA_MODE(hdma->Init.Mode)); assert_param(IS_DMA_PRIORITY(hdma->Init.Priority)); - -#if defined (STM32F101xE) || defined (STM32F101xG) || defined (STM32F103xE) || defined (STM32F103xG) || defined (STM32F100xE) || defined (STM32F105xC) || defined (STM32F107xC) - /* calculation of the channel index */ - if ((uint32_t)(hdma->Instance) < (uint32_t)(DMA2_Channel1)) - { - /* DMA1 */ - hdma->ChannelIndex = (((uint32_t)hdma->Instance - (uint32_t)DMA1_Channel1) / ((uint32_t)DMA1_Channel2 - (uint32_t)DMA1_Channel1)) << 2; - hdma->DmaBaseAddress = DMA1; - } - else - { - /* DMA2 */ - hdma->ChannelIndex = (((uint32_t)hdma->Instance - (uint32_t)DMA2_Channel1) / ((uint32_t)DMA2_Channel2 - (uint32_t)DMA2_Channel1)) << 2; - hdma->DmaBaseAddress = DMA2; + + if(hdma->State == HAL_DMA_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + hdma->Lock = HAL_UNLOCKED; } -#else - /* DMA1 */ - hdma->ChannelIndex = (((uint32_t)hdma->Instance - (uint32_t)DMA1_Channel1) / ((uint32_t)DMA1_Channel2 - (uint32_t)DMA1_Channel1)) << 2; - hdma->DmaBaseAddress = DMA1; -#endif /* STM32F101xE || STM32F101xG || STM32F103xE || STM32F103xG || STM32F100xE || STM32F105xC || STM32F107xC */ - + /* Change DMA peripheral state */ hdma->State = HAL_DMA_STATE_BUSY; /* Get the CR register value */ tmp = hdma->Instance->CCR; - - /* Clear PL, MSIZE, PSIZE, MINC, PINC, CIRC and DIR bits */ + + /* Clear PL, MSIZE, PSIZE, MINC, PINC, CIRC, DIR bits */ tmp &= ((uint32_t)~(DMA_CCR_PL | DMA_CCR_MSIZE | DMA_CCR_PSIZE | \ DMA_CCR_MINC | DMA_CCR_PINC | DMA_CCR_CIRC | \ DMA_CCR_DIR)); - + /* Prepare the DMA Channel configuration */ tmp |= hdma->Init.Direction | hdma->Init.PeriphInc | hdma->Init.MemInc | @@ -216,30 +211,21 @@ HAL_StatusTypeDef HAL_DMA_Init(DMA_HandleTypeDef *hdma) hdma->Init.Mode | hdma->Init.Priority; /* Write to DMA Channel CR register */ - hdma->Instance->CCR = tmp; - - - /* Clean callbacks */ - hdma->XferCpltCallback = NULL; - hdma->XferHalfCpltCallback = NULL; - hdma->XferErrorCallback = NULL; - hdma->XferAbortCallback = NULL; - + hdma->Instance->CCR = tmp; + /* Initialise the error code */ hdma->ErrorCode = HAL_DMA_ERROR_NONE; /* Initialize the DMA state*/ hdma->State = HAL_DMA_STATE_READY; - /* Allocate lock resource and initialize it */ - hdma->Lock = HAL_UNLOCKED; return HAL_OK; } /** - * @brief DeInitialize the DMA peripheral. + * @brief DeInitializes the DMA peripheral * @param hdma: pointer to a DMA_HandleTypeDef structure that contains - * the configuration information for the specified DMA Channel. + * the configuration information for the specified DMA Channel. * @retval HAL status */ HAL_StatusTypeDef HAL_DMA_DeInit(DMA_HandleTypeDef *hdma) @@ -249,48 +235,36 @@ HAL_StatusTypeDef HAL_DMA_DeInit(DMA_HandleTypeDef *hdma) { return HAL_ERROR; } - + /* Check the parameters */ assert_param(IS_DMA_ALL_INSTANCE(hdma->Instance)); + /* Check the DMA peripheral state */ + if(hdma->State == HAL_DMA_STATE_BUSY) + { + return HAL_ERROR; + } + /* Disable the selected DMA Channelx */ __HAL_DMA_DISABLE(hdma); - + /* Reset DMA Channel control register */ - hdma->Instance->CCR = 0U; - + hdma->Instance->CCR = 0; + /* Reset DMA Channel Number of Data to Transfer register */ - hdma->Instance->CNDTR = 0U; - + hdma->Instance->CNDTR = 0; + /* Reset DMA Channel peripheral address register */ - hdma->Instance->CPAR = 0U; - + hdma->Instance->CPAR = 0; + /* Reset DMA Channel memory address register */ - hdma->Instance->CMAR = 0U; - -#if defined (STM32F101xE) || defined (STM32F101xG) || defined (STM32F103xE) || defined (STM32F103xG) || defined (STM32F100xE) || defined (STM32F105xC) || defined (STM32F107xC) - /* calculation of the channel index */ - if ((uint32_t)(hdma->Instance) < (uint32_t)(DMA2_Channel1)) - { - /* DMA1 */ - hdma->ChannelIndex = (((uint32_t)hdma->Instance - (uint32_t)DMA1_Channel1) / ((uint32_t)DMA1_Channel2 - (uint32_t)DMA1_Channel1)) << 2; - hdma->DmaBaseAddress = DMA1; - } - else - { - /* DMA2 */ - hdma->ChannelIndex = (((uint32_t)hdma->Instance - (uint32_t)DMA2_Channel1) / ((uint32_t)DMA2_Channel2 - (uint32_t)DMA2_Channel1)) << 2; - hdma->DmaBaseAddress = DMA2; - } -#else - /* DMA1 */ - hdma->ChannelIndex = (((uint32_t)hdma->Instance - (uint32_t)DMA1_Channel1) / ((uint32_t)DMA1_Channel2 - (uint32_t)DMA1_Channel1)) << 2; - hdma->DmaBaseAddress = DMA1; -#endif /* STM32F101xE || STM32F101xG || STM32F103xE || STM32F103xG || STM32F100xE || STM32F105xC || STM32F107xC */ + hdma->Instance->CMAR = 0; /* Clear all flags */ - hdma->DmaBaseAddress->IFCR = (DMA_ISR_GIF1 << (hdma->ChannelIndex)); - + __HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_TC_FLAG_INDEX(hdma)); + __HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_TE_FLAG_INDEX(hdma)); + __HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_HT_FLAG_INDEX(hdma)); + /* Initialize the error code */ hdma->ErrorCode = HAL_DMA_ERROR_NONE; @@ -307,29 +281,29 @@ HAL_StatusTypeDef HAL_DMA_DeInit(DMA_HandleTypeDef *hdma) * @} */ -/** @defgroup DMA_Exported_Functions_Group2 Input and Output operation functions - * @brief Input and Output operation functions - * -@verbatim +/** @defgroup DMA_Exported_Functions_Group2 Input and Output operation functions + * @brief I/O operation functions + * +@verbatim =============================================================================== ##### IO operation functions ##### - =============================================================================== + =============================================================================== [..] This section provides functions allowing to: (+) Configure the source, destination address and data length and Start DMA transfer - (+) Configure the source, destination address and data length and + (+) Configure the source, destination address and data length and Start DMA transfer with interrupt (+) Abort DMA transfer (+) Poll for transfer complete - (+) Handle DMA interrupt request + (+) Handle DMA interrupt request @endverbatim * @{ */ /** - * @brief Start the DMA Transfer. - * @param hdma: pointer to a DMA_HandleTypeDef structure that contains - * the configuration information for the specified DMA Channel. + * @brief Starts the DMA Transfer. + * @param hdma : pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA Channel. * @param SrcAddress: The source memory Buffer address * @param DstAddress: The destination memory Buffer address * @param DataLength: The length of data to be transferred from source to destination @@ -337,42 +311,31 @@ HAL_StatusTypeDef HAL_DMA_DeInit(DMA_HandleTypeDef *hdma) */ HAL_StatusTypeDef HAL_DMA_Start(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t DataLength) { - HAL_StatusTypeDef status = HAL_OK; + /* Process locked */ + __HAL_LOCK(hdma); - /* Check the parameters */ + /* Change DMA peripheral state */ + hdma->State = HAL_DMA_STATE_BUSY; + + /* Check the parameters */ assert_param(IS_DMA_BUFFER_SIZE(DataLength)); + + /* Disable the peripheral */ + __HAL_DMA_DISABLE(hdma); + + /* Configure the source, destination address and the data length */ + DMA_SetConfig(hdma, SrcAddress, DstAddress, DataLength); - /* Process locked */ - __HAL_LOCK(hdma); + /* Enable the Peripheral */ + __HAL_DMA_ENABLE(hdma); - if(HAL_DMA_STATE_READY == hdma->State) - { - /* Change DMA peripheral state */ - hdma->State = HAL_DMA_STATE_BUSY; - hdma->ErrorCode = HAL_DMA_ERROR_NONE; - - /* Disable the peripheral */ - __HAL_DMA_DISABLE(hdma); - - /* Configure the source, destination address and the data length & clear flags*/ - DMA_SetConfig(hdma, SrcAddress, DstAddress, DataLength); - - /* Enable the Peripheral */ - __HAL_DMA_ENABLE(hdma); - } - else - { - /* Process Unlocked */ - __HAL_UNLOCK(hdma); - status = HAL_BUSY; - } - return status; + return HAL_OK; } /** * @brief Start the DMA Transfer with interrupt enabled. - * @param hdma: pointer to a DMA_HandleTypeDef structure that contains - * the configuration information for the specified DMA Channel. + * @param hdma: pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA Channel. * @param SrcAddress: The source memory Buffer address * @param DstAddress: The destination memory Buffer address * @param DataLength: The length of data to be transferred from source to destination @@ -380,84 +343,89 @@ HAL_StatusTypeDef HAL_DMA_Start(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, ui */ HAL_StatusTypeDef HAL_DMA_Start_IT(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t DataLength) { - HAL_StatusTypeDef status = HAL_OK; - - /* Check the parameters */ - assert_param(IS_DMA_BUFFER_SIZE(DataLength)); - /* Process locked */ __HAL_LOCK(hdma); + + /* Change DMA peripheral state */ + hdma->State = HAL_DMA_STATE_BUSY; + + /* Check the parameters */ + assert_param(IS_DMA_BUFFER_SIZE(DataLength)); - if(HAL_DMA_STATE_READY == hdma->State) - { - /* Change DMA peripheral state */ - hdma->State = HAL_DMA_STATE_BUSY; - hdma->ErrorCode = HAL_DMA_ERROR_NONE; - - /* Disable the peripheral */ - __HAL_DMA_DISABLE(hdma); - - /* Configure the source, destination address and the data length & clear flags*/ - DMA_SetConfig(hdma, SrcAddress, DstAddress, DataLength); - - /* Enable the transfer complete interrupt */ - /* Enable the transfer Error interrupt */ - if(NULL != hdma->XferHalfCpltCallback) - { - /* Enable the Half transfer complete interrupt as well */ - __HAL_DMA_ENABLE_IT(hdma, (DMA_IT_TC | DMA_IT_HT | DMA_IT_TE)); - } - else - { - __HAL_DMA_DISABLE_IT(hdma, DMA_IT_HT); - __HAL_DMA_ENABLE_IT(hdma, (DMA_IT_TC | DMA_IT_TE)); - } - /* Enable the Peripheral */ - __HAL_DMA_ENABLE(hdma); - } - else - { - /* Process Unlocked */ - __HAL_UNLOCK(hdma); + /* Disable the peripheral */ + __HAL_DMA_DISABLE(hdma); + + /* Configure the source, destination address and the data length */ + DMA_SetConfig(hdma, SrcAddress, DstAddress, DataLength); + + /* Enable the transfer complete interrupt */ + __HAL_DMA_ENABLE_IT(hdma, DMA_IT_TC); - /* Remain BUSY */ - status = HAL_BUSY; - } - return status; -} + /* Enable the Half transfer complete interrupt */ + __HAL_DMA_ENABLE_IT(hdma, DMA_IT_HT); + + /* Enable the transfer Error interrupt */ + __HAL_DMA_ENABLE_IT(hdma, DMA_IT_TE); + + /* Enable the Peripheral */ + __HAL_DMA_ENABLE(hdma); + + return HAL_OK; +} /** - * @brief Abort the DMA Transfer. - * @param hdma: pointer to a DMA_HandleTypeDef structure that contains - * the configuration information for the specified DMA Channel. + * @brief Aborts the DMA Transfer. + * @param hdma : pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA Channel. + * + * @note After disabling a DMA Channel, a check for wait until the DMA Channel is + * effectively disabled is added. If a Channel is disabled + * while a data transfer is ongoing, the current data will be transferred + * and the Channel will be effectively disabled only after the transfer of + * this single data is finished. * @retval HAL status */ HAL_StatusTypeDef HAL_DMA_Abort(DMA_HandleTypeDef *hdma) { - HAL_StatusTypeDef status = HAL_OK; - - /* Disable DMA IT */ - __HAL_DMA_DISABLE_IT(hdma, (DMA_IT_TC | DMA_IT_HT | DMA_IT_TE)); - + uint32_t tickstart = 0x00; + /* Disable the channel */ __HAL_DMA_DISABLE(hdma); - - /* Clear all flags */ - hdma->DmaBaseAddress->IFCR = (DMA_ISR_GIF1 << hdma->ChannelIndex); + /* Get tick */ + tickstart = HAL_GetTick(); + + /* Check if the DMA Channel is effectively disabled */ + while((hdma->Instance->CCR & DMA_CCR_EN) != 0) + { + /* Check for the Timeout */ + if((HAL_GetTick() - tickstart) > HAL_TIMEOUT_DMA_ABORT) + { + /* Update error code */ + SET_BIT(hdma->ErrorCode, HAL_DMA_ERROR_TIMEOUT); + + /* Change the DMA state */ + hdma->State = HAL_DMA_STATE_TIMEOUT; + + /* Process Unlocked */ + __HAL_UNLOCK(hdma); + + return HAL_TIMEOUT; + } + } /* Change the DMA state */ hdma->State = HAL_DMA_STATE_READY; - + /* Process Unlocked */ - __HAL_UNLOCK(hdma); + __HAL_UNLOCK(hdma); - return status; + return HAL_OK; } /** * @brief Aborts the DMA Transfer in Interrupt mode. * @param hdma : pointer to a DMA_HandleTypeDef structure that contains - * the configuration information for the specified DMA Channel. + * the configuration information for the specified DMA Stream. * @retval HAL status */ HAL_StatusTypeDef HAL_DMA_Abort_IT(DMA_HandleTypeDef *hdma) @@ -468,11 +436,11 @@ HAL_StatusTypeDef HAL_DMA_Abort_IT(DMA_HandleTypeDef *hdma) { /* no transfer ongoing */ hdma->ErrorCode = HAL_DMA_ERROR_NO_XFER; - + status = HAL_ERROR; } else - { + { /* Disable DMA IT */ __HAL_DMA_DISABLE_IT(hdma, (DMA_IT_TC | DMA_IT_HT | DMA_IT_TE)); @@ -501,29 +469,14 @@ HAL_StatusTypeDef HAL_DMA_Abort_IT(DMA_HandleTypeDef *hdma) * @brief Polling for transfer complete. * @param hdma: pointer to a DMA_HandleTypeDef structure that contains * the configuration information for the specified DMA Channel. - * @param CompleteLevel: Specifies the DMA level complete. + * @param CompleteLevel: Specifies the DMA level complete. * @param Timeout: Timeout duration. * @retval HAL status */ HAL_StatusTypeDef HAL_DMA_PollForTransfer(DMA_HandleTypeDef *hdma, uint32_t CompleteLevel, uint32_t Timeout) { uint32_t temp; - uint32_t tickstart = 0U; - - if(HAL_DMA_STATE_BUSY != hdma->State) - { - /* no transfer ongoing */ - hdma->ErrorCode = HAL_DMA_ERROR_NO_XFER; - __HAL_UNLOCK(hdma); - return HAL_ERROR; - } - - /* Polling mode not supported in circular mode */ - if (RESET != (hdma->Instance->CCR & DMA_CCR_CIRC)) - { - hdma->ErrorCode = HAL_DMA_ERROR_NOT_SUPPORTED; - return HAL_ERROR; - } + uint32_t tickstart = 0x00; /* Get the level transfer complete flag */ if(CompleteLevel == HAL_DMA_FULL_TRANSFER) @@ -543,38 +496,36 @@ HAL_StatusTypeDef HAL_DMA_PollForTransfer(DMA_HandleTypeDef *hdma, uint32_t Comp while(__HAL_DMA_GET_FLAG(hdma, temp) == RESET) { if((__HAL_DMA_GET_FLAG(hdma, __HAL_DMA_GET_TE_FLAG_INDEX(hdma)) != RESET)) - { - /* When a DMA transfer error occurs */ - /* A hardware clear of its EN bits is performed */ - /* Clear all flags */ - hdma->DmaBaseAddress->IFCR = (DMA_ISR_GIF1 << hdma->ChannelIndex); - + { + /* Clear the transfer error flags */ + __HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_TE_FLAG_INDEX(hdma)); + /* Update error code */ SET_BIT(hdma->ErrorCode, HAL_DMA_ERROR_TE); /* Change the DMA state */ - hdma->State= HAL_DMA_STATE_READY; - + hdma->State= HAL_DMA_STATE_ERROR; + /* Process Unlocked */ __HAL_UNLOCK(hdma); - + return HAL_ERROR; } /* Check for the Timeout */ if(Timeout != HAL_MAX_DELAY) { - if((Timeout == 0U) || ((HAL_GetTick() - tickstart) > Timeout)) + if((Timeout == 0) || ((HAL_GetTick() - tickstart) > Timeout)) { /* Update error code */ SET_BIT(hdma->ErrorCode, HAL_DMA_ERROR_TIMEOUT); - + /* Change the DMA state */ - hdma->State = HAL_DMA_STATE_READY; + hdma->State = HAL_DMA_STATE_TIMEOUT; /* Process Unlocked */ __HAL_UNLOCK(hdma); - - return HAL_ERROR; + + return HAL_TIMEOUT; } } } @@ -584,14 +535,19 @@ HAL_StatusTypeDef HAL_DMA_PollForTransfer(DMA_HandleTypeDef *hdma, uint32_t Comp /* Clear the transfer complete flag */ __HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_TC_FLAG_INDEX(hdma)); - /* The selected Channelx EN bit is cleared (DMA is disabled and + /* The selected Channelx EN bit is cleared (DMA is disabled and all transfers are complete) */ hdma->State = HAL_DMA_STATE_READY; + } else - { + { /* Clear the half transfer complete flag */ __HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_HT_FLAG_INDEX(hdma)); + + /* The selected Channelx EN bit is cleared (DMA is disabled and + all transfers of half buffer are complete) */ + hdma->State = HAL_DMA_STATE_READY_HALF; } /* Process unlocked */ @@ -608,206 +564,101 @@ HAL_StatusTypeDef HAL_DMA_PollForTransfer(DMA_HandleTypeDef *hdma, uint32_t Comp */ void HAL_DMA_IRQHandler(DMA_HandleTypeDef *hdma) { - uint32_t flag_it = hdma->DmaBaseAddress->ISR; - uint32_t source_it = hdma->Instance->CCR; - - /* Half Transfer Complete Interrupt management ******************************/ - if (((flag_it & (DMA_FLAG_HT1 << hdma->ChannelIndex)) != RESET) && ((source_it & DMA_IT_HT) != RESET)) + /* Transfer Error Interrupt management ***************************************/ + if(__HAL_DMA_GET_FLAG(hdma, __HAL_DMA_GET_TE_FLAG_INDEX(hdma)) != RESET) { - /* Disable the half transfer interrupt if the DMA mode is not CIRCULAR */ - if((hdma->Instance->CCR & DMA_CCR_CIRC) == 0U) + if(__HAL_DMA_GET_IT_SOURCE(hdma, DMA_IT_TE) != RESET) { - /* Disable the half transfer interrupt */ - __HAL_DMA_DISABLE_IT(hdma, DMA_IT_HT); - } - /* Clear the half transfer complete flag */ - __HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_HT_FLAG_INDEX(hdma)); - - /* DMA peripheral state is not updated in Half Transfer */ - /* but in Transfer Complete case */ - - if(hdma->XferHalfCpltCallback != NULL) - { - /* Half transfer callback */ - hdma->XferHalfCpltCallback(hdma); - } - } - - /* Transfer Complete Interrupt management ***********************************/ - else if (((flag_it & (DMA_FLAG_TC1 << hdma->ChannelIndex)) != RESET) && ((source_it & DMA_IT_TC) != RESET)) - { - if((hdma->Instance->CCR & DMA_CCR_CIRC) == 0U) - { - /* Disable the transfer complete and error interrupt */ - __HAL_DMA_DISABLE_IT(hdma, DMA_IT_TE | DMA_IT_TC); - + /* Disable the transfer error interrupt */ + __HAL_DMA_DISABLE_IT(hdma, DMA_IT_TE); + + /* Clear the transfer error flag */ + __HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_TE_FLAG_INDEX(hdma)); + + /* Update error code */ + SET_BIT(hdma->ErrorCode, HAL_DMA_ERROR_TE); + /* Change the DMA state */ - hdma->State = HAL_DMA_STATE_READY; - } - /* Clear the transfer complete flag */ - __HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_TC_FLAG_INDEX(hdma)); - - /* Process Unlocked */ - __HAL_UNLOCK(hdma); - - if(hdma->XferCpltCallback != NULL) - { - /* Transfer complete callback */ - hdma->XferCpltCallback(hdma); + hdma->State = HAL_DMA_STATE_ERROR; + + /* Process Unlocked */ + __HAL_UNLOCK(hdma); + + if (hdma->XferErrorCallback != NULL) + { + /* Transfer error callback */ + hdma->XferErrorCallback(hdma); + } } } - /* Transfer Error Interrupt management **************************************/ - else if (( RESET != (flag_it & (DMA_FLAG_TE1 << hdma->ChannelIndex))) && (RESET != (source_it & DMA_IT_TE))) + /* Half Transfer Complete Interrupt management ******************************/ + if(__HAL_DMA_GET_FLAG(hdma, __HAL_DMA_GET_HT_FLAG_INDEX(hdma)) != RESET) { - /* When a DMA transfer error occurs */ - /* A hardware clear of its EN bits is performed */ - /* Disable ALL DMA IT */ - __HAL_DMA_DISABLE_IT(hdma, (DMA_IT_TC | DMA_IT_HT | DMA_IT_TE)); - - /* Clear all flags */ - hdma->DmaBaseAddress->IFCR = (DMA_ISR_GIF1 << hdma->ChannelIndex); - - /* Update error code */ - hdma->ErrorCode = HAL_DMA_ERROR_TE; - - /* Change the DMA state */ - hdma->State = HAL_DMA_STATE_READY; + if(__HAL_DMA_GET_IT_SOURCE(hdma, DMA_IT_HT) != RESET) + { + /* Disable the half transfer interrupt if the DMA mode is not CIRCULAR */ + if((hdma->Instance->CCR & DMA_CCR_CIRC) == 0) + { + /* Disable the half transfer interrupt */ + __HAL_DMA_DISABLE_IT(hdma, DMA_IT_HT); + } + /* Clear the half transfer complete flag */ + __HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_HT_FLAG_INDEX(hdma)); - /* Process Unlocked */ - __HAL_UNLOCK(hdma); + /* Change DMA peripheral state */ + hdma->State = HAL_DMA_STATE_READY_HALF; - if (hdma->XferErrorCallback != NULL) - { - /* Transfer error callback */ - hdma->XferErrorCallback(hdma); + if(hdma->XferHalfCpltCallback != NULL) + { + /* Half transfer callback */ + hdma->XferHalfCpltCallback(hdma); + } } } - return; -} - -/** - * @brief Register callbacks - * @param hdma: pointer to a DMA_HandleTypeDef structure that contains - * the configuration information for the specified DMA Channel. - * @param CallbackID: User Callback identifer - * a HAL_DMA_CallbackIDTypeDef ENUM as parameter. - * @param pCallback: pointer to private callbacsk function which has pointer to - * a DMA_HandleTypeDef structure as parameter. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_DMA_RegisterCallback(DMA_HandleTypeDef *hdma, HAL_DMA_CallbackIDTypeDef CallbackID, void (* pCallback)( DMA_HandleTypeDef * _hdma)) -{ - HAL_StatusTypeDef status = HAL_OK; - /* Process locked */ - __HAL_LOCK(hdma); - - if(HAL_DMA_STATE_READY == hdma->State) + /* Transfer Complete Interrupt management ***********************************/ + if(__HAL_DMA_GET_FLAG(hdma, __HAL_DMA_GET_TC_FLAG_INDEX(hdma)) != RESET) { - switch (CallbackID) + if(__HAL_DMA_GET_IT_SOURCE(hdma, DMA_IT_TC) != RESET) { - case HAL_DMA_XFER_CPLT_CB_ID: - hdma->XferCpltCallback = pCallback; - break; - - case HAL_DMA_XFER_HALFCPLT_CB_ID: - hdma->XferHalfCpltCallback = pCallback; - break; + if((hdma->Instance->CCR & DMA_CCR_CIRC) == 0) + { + /* Disable the transfer complete interrupt */ + __HAL_DMA_DISABLE_IT(hdma, DMA_IT_TC); + } + /* Clear the transfer complete flag */ + __HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_TC_FLAG_INDEX(hdma)); + + /* Update error code */ + SET_BIT(hdma->ErrorCode, HAL_DMA_ERROR_NONE); - case HAL_DMA_XFER_ERROR_CB_ID: - hdma->XferErrorCallback = pCallback; - break; - - case HAL_DMA_XFER_ABORT_CB_ID: - hdma->XferAbortCallback = pCallback; - break; - - default: - status = HAL_ERROR; - break; + /* Change the DMA state */ + hdma->State = HAL_DMA_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hdma); + + if(hdma->XferCpltCallback != NULL) + { + /* Transfer complete callback */ + hdma->XferCpltCallback(hdma); + } } } - else - { - status = HAL_ERROR; - } - - /* Release Lock */ - __HAL_UNLOCK(hdma); - - return status; } -/** - * @brief UnRegister callbacks - * @param hdma: pointer to a DMA_HandleTypeDef structure that contains - * the configuration information for the specified DMA Channel. - * @param CallbackID: User Callback identifer - * a HAL_DMA_CallbackIDTypeDef ENUM as parameter. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_DMA_UnRegisterCallback(DMA_HandleTypeDef *hdma, HAL_DMA_CallbackIDTypeDef CallbackID) -{ - HAL_StatusTypeDef status = HAL_OK; - - /* Process locked */ - __HAL_LOCK(hdma); - - if(HAL_DMA_STATE_READY == hdma->State) - { - switch (CallbackID) - { - case HAL_DMA_XFER_CPLT_CB_ID: - hdma->XferCpltCallback = NULL; - break; - - case HAL_DMA_XFER_HALFCPLT_CB_ID: - hdma->XferHalfCpltCallback = NULL; - break; - - case HAL_DMA_XFER_ERROR_CB_ID: - hdma->XferErrorCallback = NULL; - break; - - case HAL_DMA_XFER_ABORT_CB_ID: - hdma->XferAbortCallback = NULL; - break; - - case HAL_DMA_XFER_ALL_CB_ID: - hdma->XferCpltCallback = NULL; - hdma->XferHalfCpltCallback = NULL; - hdma->XferErrorCallback = NULL; - hdma->XferAbortCallback = NULL; - break; - - default: - status = HAL_ERROR; - break; - } - } - else - { - status = HAL_ERROR; - } - - /* Release Lock */ - __HAL_UNLOCK(hdma); - - return status; -} - /** * @} */ -/** @defgroup DMA_Exported_Functions_Group3 Peripheral State and Errors functions - * @brief Peripheral State and Errors functions - * -@verbatim +/** @defgroup DMA_Exported_Functions_Group3 Peripheral State functions + * @brief Peripheral State functions + * +@verbatim + =============================================================================== + ##### State and Errors functions ##### =============================================================================== - ##### Peripheral State and Errors functions ##### - =============================================================================== [..] This subsection provides functions allowing to (+) Check the DMA state @@ -818,19 +669,18 @@ HAL_StatusTypeDef HAL_DMA_UnRegisterCallback(DMA_HandleTypeDef *hdma, HAL_DMA_Ca */ /** - * @brief Return the DMA hande state. + * @brief Returns the DMA state. * @param hdma: pointer to a DMA_HandleTypeDef structure that contains - * the configuration information for the specified DMA Channel. + * the configuration information for the specified DMA Channel. * @retval HAL state */ HAL_DMA_StateTypeDef HAL_DMA_GetState(DMA_HandleTypeDef *hdma) { - /* Return DMA handle state */ return hdma->State; } /** - * @brief Return the DMA error code. + * @brief Return the DMA error code * @param hdma : pointer to a DMA_HandleTypeDef structure that contains * the configuration information for the specified DMA Channel. * @retval DMA Error Code @@ -848,14 +698,14 @@ uint32_t HAL_DMA_GetError(DMA_HandleTypeDef *hdma) * @} */ -/** @addtogroup DMA_Private_Functions +/** @addtogroup DMA_Private_Functions DMA Private Functions * @{ */ /** * @brief Sets the DMA Transfer parameter. * @param hdma: pointer to a DMA_HandleTypeDef structure that contains - * the configuration information for the specified DMA Channel. + * the configuration information for the specified DMA Channel. * @param SrcAddress: The source memory Buffer address * @param DstAddress: The destination memory Buffer address * @param DataLength: The length of data to be transferred from source to destination @@ -863,18 +713,15 @@ uint32_t HAL_DMA_GetError(DMA_HandleTypeDef *hdma) */ static void DMA_SetConfig(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t DataLength) { - /* Clear all flags */ - hdma->DmaBaseAddress->IFCR = (DMA_ISR_GIF1 << hdma->ChannelIndex); - /* Configure DMA Channel data length */ hdma->Instance->CNDTR = DataLength; - + /* Peripheral to Memory */ if((hdma->Init.Direction) == DMA_MEMORY_TO_PERIPH) { /* Configure DMA Channel destination address */ hdma->Instance->CPAR = DstAddress; - + /* Configure DMA Channel source address */ hdma->Instance->CMAR = SrcAddress; } @@ -883,7 +730,7 @@ static void DMA_SetConfig(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t { /* Configure DMA Channel source address */ hdma->Instance->CPAR = SrcAddress; - + /* Configure DMA Channel destination address */ hdma->Instance->CMAR = DstAddress; } diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_dma.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_dma.h index 03521b9b3f8..607a70b92ec 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_dma.h +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_dma.h @@ -2,13 +2,13 @@ ****************************************************************************** * @file stm32f1xx_hal_dma.h * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief Header file of DMA HAL module. ****************************************************************************** * @attention * - *

© COPYRIGHT(c) 2017 STMicroelectronics

+ *

© COPYRIGHT(c) 2016 STMicroelectronics

* * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: @@ -33,7 +33,7 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** - */ + */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F1xx_HAL_DMA_H @@ -52,15 +52,15 @@ /** @addtogroup DMA * @{ - */ + */ /* Exported types ------------------------------------------------------------*/ /** @defgroup DMA_Exported_Types DMA Exported Types * @{ */ - -/** + +/** * @brief DMA Configuration Structure definition */ typedef struct @@ -71,57 +71,56 @@ typedef struct uint32_t PeriphInc; /*!< Specifies whether the Peripheral address register should be incremented or not. This parameter can be a value of @ref DMA_Peripheral_incremented_mode */ - + uint32_t MemInc; /*!< Specifies whether the memory address register should be incremented or not. This parameter can be a value of @ref DMA_Memory_incremented_mode */ - + uint32_t PeriphDataAlignment; /*!< Specifies the Peripheral data width. This parameter can be a value of @ref DMA_Peripheral_data_size */ uint32_t MemDataAlignment; /*!< Specifies the Memory data width. This parameter can be a value of @ref DMA_Memory_data_size */ - + uint32_t Mode; /*!< Specifies the operation mode of the DMAy Channelx. This parameter can be a value of @ref DMA_mode @note The circular buffer mode cannot be used if the memory-to-memory - data transfer is configured on the selected Channel */ + data transfer is configured on the selected Channel */ - uint32_t Priority; /*!< Specifies the software priority for the DMAy Channelx. - This parameter can be a value of @ref DMA_Priority_level */ + uint32_t Priority; /*!< Specifies the software priority for the DMAy Channelx. + This parameter can be a value of @ref DMA_Priority_level */ } DMA_InitTypeDef; -/** - * @brief HAL DMA State structures definition - */ -typedef enum +/** + * @brief DMA Configuration enumeration values definition + */ +typedef enum { - HAL_DMA_STATE_RESET = 0x00U, /*!< DMA not yet initialized or disabled */ - HAL_DMA_STATE_READY = 0x01U, /*!< DMA initialized and ready for use */ - HAL_DMA_STATE_BUSY = 0x02U, /*!< DMA process is ongoing */ - HAL_DMA_STATE_TIMEOUT = 0x03U /*!< DMA timeout state */ -}HAL_DMA_StateTypeDef; + DMA_MODE = 0, /*!< Control related DMA mode Parameter in DMA_InitTypeDef */ + DMA_PRIORITY = 1, /*!< Control related priority level Parameter in DMA_InitTypeDef */ + +} DMA_ControlTypeDef; /** - * @brief HAL DMA Error Code structure definition + * @brief HAL DMA State structures definition */ typedef enum { - HAL_DMA_FULL_TRANSFER = 0x00U, /*!< Full transfer */ - HAL_DMA_HALF_TRANSFER = 0x01U /*!< Half Transfer */ -}HAL_DMA_LevelCompleteTypeDef; + HAL_DMA_STATE_RESET = 0x00, /*!< DMA not yet initialized or disabled */ + HAL_DMA_STATE_READY = 0x01, /*!< DMA initialized and ready for use */ + HAL_DMA_STATE_READY_HALF = 0x11, /*!< DMA Half process success */ + HAL_DMA_STATE_BUSY = 0x02, /*!< DMA process is ongoing */ + HAL_DMA_STATE_TIMEOUT = 0x03, /*!< DMA timeout state */ + HAL_DMA_STATE_ERROR = 0x04, /*!< DMA error state */ +}HAL_DMA_StateTypeDef; /** - * @brief HAL DMA Callback ID structure definition + * @brief HAL DMA Error Code structure definition */ typedef enum { - HAL_DMA_XFER_CPLT_CB_ID = 0x00U, /*!< Full transfer */ - HAL_DMA_XFER_HALFCPLT_CB_ID = 0x01U, /*!< Half transfer */ - HAL_DMA_XFER_ERROR_CB_ID = 0x02U, /*!< Error */ - HAL_DMA_XFER_ABORT_CB_ID = 0x03U, /*!< Abort */ - HAL_DMA_XFER_ALL_CB_ID = 0x04U /*!< All */ - -}HAL_DMA_CallbackIDTypeDef; + HAL_DMA_FULL_TRANSFER = 0x00, /*!< Full transfer */ + HAL_DMA_HALF_TRANSFER = 0x01, /*!< Half Transfer */ +}HAL_DMA_LevelCompleteTypeDef; /** * @brief DMA handle Structure definition @@ -147,11 +146,6 @@ typedef struct __DMA_HandleTypeDef void (* XferAbortCallback)( struct __DMA_HandleTypeDef * hdma); /*!< DMA transfer abort callback */ __IO uint32_t ErrorCode; /*!< DMA Error code */ - - DMA_TypeDef *DmaBaseAddress; /*!< DMA Channel Base Address */ - - uint32_t ChannelIndex; /*!< DMA Channel Index */ - } DMA_HandleTypeDef; /** * @} @@ -166,19 +160,19 @@ typedef struct __DMA_HandleTypeDef /** @defgroup DMA_Error_Code DMA Error Code * @{ */ -#define HAL_DMA_ERROR_NONE 0x00000000U /*!< No error */ -#define HAL_DMA_ERROR_TE 0x00000001U /*!< Transfer error */ -#define HAL_DMA_ERROR_NO_XFER 0x00000004U /*!< no ongoing transfer */ -#define HAL_DMA_ERROR_TIMEOUT 0x00000020U /*!< Timeout error */ -#define HAL_DMA_ERROR_NOT_SUPPORTED 0x00000100U /*!< Not supported mode */ +#define HAL_DMA_ERROR_NONE ((uint32_t)0x00000000) /*!< No error */ +#define HAL_DMA_ERROR_TE ((uint32_t)0x00000001) /*!< Transfer error */ +#define HAL_DMA_ERROR_NO_XFER ((uint32_t)0x00000004) /*!< no ongoing transfer */ +#define HAL_DMA_ERROR_TIMEOUT ((uint32_t)0x00000020) /*!< Timeout error */ + /** * @} */ /** @defgroup DMA_Data_transfer_direction DMA Data transfer direction * @{ - */ -#define DMA_PERIPH_TO_MEMORY 0x00000000U /*!< Peripheral to memory direction */ + */ +#define DMA_PERIPH_TO_MEMORY ((uint32_t)0x00000000) /*!< Peripheral to memory direction */ #define DMA_MEMORY_TO_PERIPH ((uint32_t)DMA_CCR_DIR) /*!< Memory to peripheral direction */ #define DMA_MEMORY_TO_MEMORY ((uint32_t)DMA_CCR_MEM2MEM) /*!< Memory to memory direction */ @@ -188,46 +182,46 @@ typedef struct __DMA_HandleTypeDef /** @defgroup DMA_Peripheral_incremented_mode DMA Peripheral incremented mode * @{ - */ -#define DMA_PINC_ENABLE ((uint32_t)DMA_CCR_PINC) /*!< Peripheral increment mode Enable */ -#define DMA_PINC_DISABLE 0x00000000U /*!< Peripheral increment mode Disable */ + */ +#define DMA_PINC_ENABLE ((uint32_t)DMA_CCR_PINC) /*!< Peripheral increment mode Enable */ +#define DMA_PINC_DISABLE ((uint32_t)0x00000000) /*!< Peripheral increment mode Disable */ /** * @} - */ + */ /** @defgroup DMA_Memory_incremented_mode DMA Memory incremented mode * @{ - */ -#define DMA_MINC_ENABLE ((uint32_t)DMA_CCR_MINC) /*!< Memory increment mode Enable */ -#define DMA_MINC_DISABLE 0x00000000U /*!< Memory increment mode Disable */ + */ +#define DMA_MINC_ENABLE ((uint32_t)DMA_CCR_MINC) /*!< Memory increment mode Enable */ +#define DMA_MINC_DISABLE ((uint32_t)0x00000000) /*!< Memory increment mode Disable */ /** * @} */ /** @defgroup DMA_Peripheral_data_size DMA Peripheral data size * @{ - */ -#define DMA_PDATAALIGN_BYTE 0x00000000U /*!< Peripheral data alignment: Byte */ -#define DMA_PDATAALIGN_HALFWORD ((uint32_t)DMA_CCR_PSIZE_0) /*!< Peripheral data alignment: HalfWord */ -#define DMA_PDATAALIGN_WORD ((uint32_t)DMA_CCR_PSIZE_1) /*!< Peripheral data alignment: Word */ + */ +#define DMA_PDATAALIGN_BYTE ((uint32_t)0x00000000) /*!< Peripheral data alignment: Byte */ +#define DMA_PDATAALIGN_HALFWORD ((uint32_t)DMA_CCR_PSIZE_0) /*!< Peripheral data alignment: HalfWord */ +#define DMA_PDATAALIGN_WORD ((uint32_t)DMA_CCR_PSIZE_1) /*!< Peripheral data alignment: Word */ /** * @} - */ + */ /** @defgroup DMA_Memory_data_size DMA Memory data size - * @{ + * @{ */ -#define DMA_MDATAALIGN_BYTE 0x00000000U /*!< Memory data alignment: Byte */ -#define DMA_MDATAALIGN_HALFWORD ((uint32_t)DMA_CCR_MSIZE_0) /*!< Memory data alignment: HalfWord */ -#define DMA_MDATAALIGN_WORD ((uint32_t)DMA_CCR_MSIZE_1) /*!< Memory data alignment: Word */ +#define DMA_MDATAALIGN_BYTE ((uint32_t)0x00000000) /*!< Memory data alignment: Byte */ +#define DMA_MDATAALIGN_HALFWORD ((uint32_t)DMA_CCR_MSIZE_0) /*!< Memory data alignment: HalfWord */ +#define DMA_MDATAALIGN_WORD ((uint32_t)DMA_CCR_MSIZE_1) /*!< Memory data alignment: Word */ /** * @} */ /** @defgroup DMA_mode DMA mode * @{ - */ -#define DMA_NORMAL 0x00000000U /*!< Normal mode */ + */ +#define DMA_NORMAL ((uint32_t)0x00000000) /*!< Normal mode */ #define DMA_CIRCULAR ((uint32_t)DMA_CCR_CIRC) /*!< Circular mode */ /** * @} @@ -236,13 +230,13 @@ typedef struct __DMA_HandleTypeDef /** @defgroup DMA_Priority_level DMA Priority level * @{ */ -#define DMA_PRIORITY_LOW 0x00000000U /*!< Priority level : Low */ -#define DMA_PRIORITY_MEDIUM ((uint32_t)DMA_CCR_PL_0) /*!< Priority level : Medium */ -#define DMA_PRIORITY_HIGH ((uint32_t)DMA_CCR_PL_1) /*!< Priority level : High */ -#define DMA_PRIORITY_VERY_HIGH ((uint32_t)DMA_CCR_PL) /*!< Priority level : Very_High */ +#define DMA_PRIORITY_LOW ((uint32_t)0x00000000) /*!< Priority level : Low */ +#define DMA_PRIORITY_MEDIUM ((uint32_t)DMA_CCR_PL_0) /*!< Priority level : Medium */ +#define DMA_PRIORITY_HIGH ((uint32_t)DMA_CCR_PL_1) /*!< Priority level : High */ +#define DMA_PRIORITY_VERY_HIGH ((uint32_t)DMA_CCR_PL) /*!< Priority level : Very_High */ /** * @} - */ + */ /** @defgroup DMA_interrupt_enable_definitions DMA interrupt enable definitions @@ -257,35 +251,35 @@ typedef struct __DMA_HandleTypeDef /** @defgroup DMA_flag_definitions DMA flag definitions * @{ - */ -#define DMA_FLAG_GL1 0x00000001U -#define DMA_FLAG_TC1 0x00000002U -#define DMA_FLAG_HT1 0x00000004U -#define DMA_FLAG_TE1 0x00000008U -#define DMA_FLAG_GL2 0x00000010U -#define DMA_FLAG_TC2 0x00000020U -#define DMA_FLAG_HT2 0x00000040U -#define DMA_FLAG_TE2 0x00000080U -#define DMA_FLAG_GL3 0x00000100U -#define DMA_FLAG_TC3 0x00000200U -#define DMA_FLAG_HT3 0x00000400U -#define DMA_FLAG_TE3 0x00000800U -#define DMA_FLAG_GL4 0x00001000U -#define DMA_FLAG_TC4 0x00002000U -#define DMA_FLAG_HT4 0x00004000U -#define DMA_FLAG_TE4 0x00008000U -#define DMA_FLAG_GL5 0x00010000U -#define DMA_FLAG_TC5 0x00020000U -#define DMA_FLAG_HT5 0x00040000U -#define DMA_FLAG_TE5 0x00080000U -#define DMA_FLAG_GL6 0x00100000U -#define DMA_FLAG_TC6 0x00200000U -#define DMA_FLAG_HT6 0x00400000U -#define DMA_FLAG_TE6 0x00800000U -#define DMA_FLAG_GL7 0x01000000U -#define DMA_FLAG_TC7 0x02000000U -#define DMA_FLAG_HT7 0x04000000U -#define DMA_FLAG_TE7 0x08000000U + */ +#define DMA_FLAG_GL1 ((uint32_t)0x00000001) +#define DMA_FLAG_TC1 ((uint32_t)0x00000002) +#define DMA_FLAG_HT1 ((uint32_t)0x00000004) +#define DMA_FLAG_TE1 ((uint32_t)0x00000008) +#define DMA_FLAG_GL2 ((uint32_t)0x00000010) +#define DMA_FLAG_TC2 ((uint32_t)0x00000020) +#define DMA_FLAG_HT2 ((uint32_t)0x00000040) +#define DMA_FLAG_TE2 ((uint32_t)0x00000080) +#define DMA_FLAG_GL3 ((uint32_t)0x00000100) +#define DMA_FLAG_TC3 ((uint32_t)0x00000200) +#define DMA_FLAG_HT3 ((uint32_t)0x00000400) +#define DMA_FLAG_TE3 ((uint32_t)0x00000800) +#define DMA_FLAG_GL4 ((uint32_t)0x00001000) +#define DMA_FLAG_TC4 ((uint32_t)0x00002000) +#define DMA_FLAG_HT4 ((uint32_t)0x00004000) +#define DMA_FLAG_TE4 ((uint32_t)0x00008000) +#define DMA_FLAG_GL5 ((uint32_t)0x00010000) +#define DMA_FLAG_TC5 ((uint32_t)0x00020000) +#define DMA_FLAG_HT5 ((uint32_t)0x00040000) +#define DMA_FLAG_TE5 ((uint32_t)0x00080000) +#define DMA_FLAG_GL6 ((uint32_t)0x00100000) +#define DMA_FLAG_TC6 ((uint32_t)0x00200000) +#define DMA_FLAG_HT6 ((uint32_t)0x00400000) +#define DMA_FLAG_TE6 ((uint32_t)0x00800000) +#define DMA_FLAG_GL7 ((uint32_t)0x01000000) +#define DMA_FLAG_TC7 ((uint32_t)0x02000000) +#define DMA_FLAG_HT7 ((uint32_t)0x04000000) +#define DMA_FLAG_TE7 ((uint32_t)0x08000000) /** * @} */ @@ -293,15 +287,15 @@ typedef struct __DMA_HandleTypeDef /** * @} */ + - -/* Exported macros -----------------------------------------------------------*/ +/* Exported macro ------------------------------------------------------------*/ /** @defgroup DMA_Exported_Macros DMA Exported Macros * @{ */ -/** @brief Reset DMA handle state. - * @param __HANDLE__: DMA handle +/** @brief Reset DMA handle state + * @param __HANDLE__: DMA handle. * @retval None */ #define __HAL_DMA_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_DMA_STATE_RESET) @@ -309,14 +303,14 @@ typedef struct __DMA_HandleTypeDef /** * @brief Enable the specified DMA Channel. * @param __HANDLE__: DMA handle - * @retval None + * @retval None. */ #define __HAL_DMA_ENABLE(__HANDLE__) (SET_BIT((__HANDLE__)->Instance->CCR, DMA_CCR_EN)) /** * @brief Disable the specified DMA Channel. * @param __HANDLE__: DMA handle - * @retval None + * @retval None. */ #define __HAL_DMA_DISABLE(__HANDLE__) (CLEAR_BIT((__HANDLE__)->Instance->CCR, DMA_CCR_EN)) @@ -326,7 +320,7 @@ typedef struct __DMA_HandleTypeDef /** * @brief Enables the specified DMA Channel interrupts. * @param __HANDLE__: DMA handle - * @param __INTERRUPT__: specifies the DMA interrupt sources to be enabled or disabled. + * @param __INTERRUPT__: specifies the DMA interrupt sources to be enabled or disabled. * This parameter can be any combination of the following values: * @arg DMA_IT_TC: Transfer complete interrupt mask * @arg DMA_IT_HT: Half transfer complete interrupt mask @@ -336,9 +330,9 @@ typedef struct __DMA_HandleTypeDef #define __HAL_DMA_ENABLE_IT(__HANDLE__, __INTERRUPT__) (SET_BIT((__HANDLE__)->Instance->CCR, (__INTERRUPT__))) /** - * @brief Disable the specified DMA Channel interrupts. + * @brief Disables the specified DMA Channel interrupts. * @param __HANDLE__: DMA handle - * @param __INTERRUPT__: specifies the DMA interrupt sources to be enabled or disabled. + * @param __INTERRUPT__: specifies the DMA interrupt sources to be enabled or disabled. * This parameter can be any combination of the following values: * @arg DMA_IT_TC: Transfer complete interrupt mask * @arg DMA_IT_HT: Half transfer complete interrupt mask @@ -348,7 +342,7 @@ typedef struct __DMA_HandleTypeDef #define __HAL_DMA_DISABLE_IT(__HANDLE__, __INTERRUPT__) (CLEAR_BIT((__HANDLE__)->Instance->CCR , (__INTERRUPT__))) /** - * @brief Check whether the specified DMA Channel interrupt is enabled or not. + * @brief Checks whether the specified DMA Channel interrupt is enabled or disabled. * @param __HANDLE__: DMA handle * @param __INTERRUPT__: specifies the DMA interrupt source to check. * This parameter can be one of the following values: @@ -360,8 +354,9 @@ typedef struct __DMA_HandleTypeDef #define __HAL_DMA_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->CCR & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET) /** - * @brief Return the number of remaining data units in the current DMA Channel transfer. + * @brief Returns the number of remaining data units in the current DMAy Channelx transfer. * @param __HANDLE__: DMA handle + * * @retval The number of remaining data units in the current DMA Channel transfer. */ #define __HAL_DMA_GET_COUNTER(__HANDLE__) ((__HANDLE__)->Instance->CNDTR) @@ -374,11 +369,11 @@ typedef struct __DMA_HandleTypeDef #include "stm32f1xx_hal_dma_ex.h" /* Exported functions --------------------------------------------------------*/ -/** @addtogroup DMA_Exported_Functions +/** @addtogroup DMA_Exported_Functions DMA Exported Functions * @{ */ -/** @addtogroup DMA_Exported_Functions_Group1 +/** @addtogroup DMA_Exported_Functions_Group1 Initialization and de-initialization functions * @{ */ /* Initialization and de-initialization functions *****************************/ @@ -388,7 +383,7 @@ HAL_StatusTypeDef HAL_DMA_DeInit (DMA_HandleTypeDef *hdma); * @} */ -/** @addtogroup DMA_Exported_Functions_Group2 +/** @addtogroup DMA_Exported_Functions_Group2 Input and Output operation functions * @{ */ /* IO operation functions *****************************************************/ @@ -397,20 +392,17 @@ HAL_StatusTypeDef HAL_DMA_Start_IT(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, HAL_StatusTypeDef HAL_DMA_Abort(DMA_HandleTypeDef *hdma); HAL_StatusTypeDef HAL_DMA_Abort_IT(DMA_HandleTypeDef *hdma); HAL_StatusTypeDef HAL_DMA_PollForTransfer(DMA_HandleTypeDef *hdma, uint32_t CompleteLevel, uint32_t Timeout); -void HAL_DMA_IRQHandler(DMA_HandleTypeDef *hdma); -HAL_StatusTypeDef HAL_DMA_RegisterCallback(DMA_HandleTypeDef *hdma, HAL_DMA_CallbackIDTypeDef CallbackID, void (* pCallback)( DMA_HandleTypeDef * _hdma)); -HAL_StatusTypeDef HAL_DMA_UnRegisterCallback(DMA_HandleTypeDef *hdma, HAL_DMA_CallbackIDTypeDef CallbackID); - +void HAL_DMA_IRQHandler(DMA_HandleTypeDef *hdma); /** * @} */ -/** @addtogroup DMA_Exported_Functions_Group3 +/** @addtogroup DMA_Exported_Functions_Group3 Peripheral State functions * @{ */ /* Peripheral State and Error functions ***************************************/ HAL_DMA_StateTypeDef HAL_DMA_GetState(DMA_HandleTypeDef *hdma); -uint32_t HAL_DMA_GetError(DMA_HandleTypeDef *hdma); +uint32_t HAL_DMA_GetError(DMA_HandleTypeDef *hdma); /** * @} */ @@ -419,16 +411,26 @@ uint32_t HAL_DMA_GetError(DMA_HandleTypeDef *hdma); * @} */ +/* Private Constants -------------------------------------------------------------*/ +/** @defgroup DMA_Private_Constants DMA Private Constants + * @brief DMA private defines and constants + * @{ + */ +/** + * @} + */ + /* Private macros ------------------------------------------------------------*/ /** @defgroup DMA_Private_Macros DMA Private Macros + * @brief DMA private macros * @{ */ +#define IS_DMA_BUFFER_SIZE(SIZE) (((SIZE) >= 0x1) && ((SIZE) < 0x10000)) + #define IS_DMA_DIRECTION(DIRECTION) (((DIRECTION) == DMA_PERIPH_TO_MEMORY ) || \ ((DIRECTION) == DMA_MEMORY_TO_PERIPH) || \ - ((DIRECTION) == DMA_MEMORY_TO_MEMORY)) - -#define IS_DMA_BUFFER_SIZE(SIZE) (((SIZE) >= 0x1U) && ((SIZE) < 0x10000U)) + ((DIRECTION) == DMA_MEMORY_TO_MEMORY)) #define IS_DMA_PERIPHERAL_INC_STATE(STATE) (((STATE) == DMA_PINC_ENABLE) || \ ((STATE) == DMA_PINC_DISABLE)) @@ -445,23 +447,30 @@ uint32_t HAL_DMA_GetError(DMA_HandleTypeDef *hdma); ((SIZE) == DMA_MDATAALIGN_WORD )) #define IS_DMA_MODE(MODE) (((MODE) == DMA_NORMAL ) || \ - ((MODE) == DMA_CIRCULAR)) + ((MODE) == DMA_CIRCULAR)) #define IS_DMA_PRIORITY(PRIORITY) (((PRIORITY) == DMA_PRIORITY_LOW ) || \ ((PRIORITY) == DMA_PRIORITY_MEDIUM) || \ ((PRIORITY) == DMA_PRIORITY_HIGH) || \ - ((PRIORITY) == DMA_PRIORITY_VERY_HIGH)) + ((PRIORITY) == DMA_PRIORITY_VERY_HIGH)) /** * @} */ /* Private functions ---------------------------------------------------------*/ - +/** @defgroup DMA_Private_Functions DMA Private Functions + * @brief DMA private functions + * @{ + */ /** * @} */ +/** + * @} + */ + /** * @} */ diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_dma_ex.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_dma_ex.h index 6f03958bd63..b28cdeada70 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_dma_ex.h +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_dma_ex.h @@ -2,13 +2,13 @@ ****************************************************************************** * @file stm32f1xx_hal_dma_ex.h * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief Header file of DMA HAL extension module. ****************************************************************************** * @attention * - *

© COPYRIGHT(c) 2017 STMicroelectronics

+ *

© COPYRIGHT(c) 2016 STMicroelectronics

* * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: @@ -52,7 +52,7 @@ /** @defgroup DMAEx DMAEx * @{ - */ + */ /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ @@ -197,10 +197,10 @@ DMA_FLAG_TC7) /** - * @brief Return the current DMA Channel half transfer complete flag. + * @brief Returns the current DMA Channel half transfer complete flag. * @param __HANDLE__: DMA handle * @retval The specified half transfer complete flag index. - */ + */ #define __HAL_DMA_GET_HT_FLAG_INDEX(__HANDLE__)\ (((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel1))? DMA_FLAG_HT1 :\ ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel2))? DMA_FLAG_HT2 :\ @@ -211,7 +211,7 @@ DMA_FLAG_HT7) /** - * @brief Return the current DMA Channel transfer error flag. + * @brief Returns the current DMA Channel transfer error flag. * @param __HANDLE__: DMA handle * @retval The specified transfer error flag index. */ @@ -246,7 +246,6 @@ * @arg DMA_FLAG_TCx: Transfer complete flag * @arg DMA_FLAG_HTx: Half transfer complete flag * @arg DMA_FLAG_TEx: Transfer error flag - * @arg DMA_FLAG_GLx: Global interrupt flag * Where x can be 1_7 to select the DMA Channel flag. * @retval The state of FLAG (SET or RESET). */ @@ -254,14 +253,13 @@ #define __HAL_DMA_GET_FLAG(__HANDLE__, __FLAG__) (DMA1->ISR & (__FLAG__)) /** - * @brief Clear the DMA Channel pending flags. + * @brief Clears the DMA Channel pending flags. * @param __HANDLE__: DMA handle * @param __FLAG__: specifies the flag to clear. * This parameter can be any combination of the following values: * @arg DMA_FLAG_TCx: Transfer complete flag * @arg DMA_FLAG_HTx: Half transfer complete flag * @arg DMA_FLAG_TEx: Transfer error flag - * @arg DMA_FLAG_GLx: Global interrupt flag * Where x can be 1_7 to select the DMA Channel flag. * @retval None */ diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_eth.c b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_eth.c index 0905aeb4286..439cb7012c7 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_eth.c +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_eth.c @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_hal_eth.c * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief ETH HAL module driver. * This file provides firmware functions to manage the following * functionalities of the Ethernet (ETH) peripheral: @@ -118,13 +118,13 @@ /** @defgroup ETH_Private_Constants ETH Private Constants * @{ */ -#define ETH_TIMEOUT_SWRESET 500U -#define ETH_TIMEOUT_LINKED_STATE 5000U -#define ETH_TIMEOUT_AUTONEGO_COMPLETED 5000U +#define LINKED_STATE_TIMEOUT_VALUE ((uint32_t)2000) /* 2000 ms */ +#define AUTONEGO_COMPLETED_TIMEOUT_VALUE ((uint32_t)1000) /* 1000 ms */ /** * @} */ + /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ @@ -142,7 +142,6 @@ static void ETH_DMATransmissionDisable(ETH_HandleTypeDef *heth); static void ETH_DMAReceptionEnable(ETH_HandleTypeDef *heth); static void ETH_DMAReceptionDisable(ETH_HandleTypeDef *heth); static void ETH_FlushTransmitFIFO(ETH_HandleTypeDef *heth); -static void ETH_Delay(uint32_t mdelay); /** * @} @@ -177,9 +176,9 @@ static void ETH_Delay(uint32_t mdelay); */ HAL_StatusTypeDef HAL_ETH_Init(ETH_HandleTypeDef *heth) { - uint32_t tmpreg1 = 0U, phyreg = 0U; - uint32_t hclk = 60000000U; - uint32_t tickstart = 0U; + uint32_t tmpreg = 0, phyreg = 0; + uint32_t hclk = 60000000; + uint32_t tickstart = 0; uint32_t err = ETH_SUCCESS; /* Check the ETH peripheral state */ @@ -198,6 +197,7 @@ HAL_StatusTypeDef HAL_ETH_Init(ETH_HandleTypeDef *heth) { /* Allocate lock resource and initialize it */ heth->Lock = HAL_UNLOCKED; + /* Init the low level hardware : GPIO, CLOCK, NVIC. */ HAL_ETH_MspInit(heth); } @@ -211,54 +211,39 @@ HAL_StatusTypeDef HAL_ETH_Init(ETH_HandleTypeDef *heth) /* After reset all the registers holds their respective reset values */ (heth->Instance)->DMABMR |= ETH_DMABMR_SR; - /* Get tick */ - tickstart = HAL_GetTick(); - /* Wait for software reset */ while (((heth->Instance)->DMABMR & ETH_DMABMR_SR) != (uint32_t)RESET) { - /* Check for the Timeout */ - if((HAL_GetTick() - tickstart ) > ETH_TIMEOUT_SWRESET) - { - heth->State= HAL_ETH_STATE_TIMEOUT; - - /* Process Unlocked */ - __HAL_UNLOCK(heth); - - /* Note: The SWR is not performed if the ETH_RX_CLK or the ETH_TX_CLK are - not available, please check your external PHY or the IO configuration */ - return HAL_TIMEOUT; - } } /*-------------------------------- MAC Initialization ----------------------*/ /* Get the ETHERNET MACMIIAR value */ - tmpreg1 = (heth->Instance)->MACMIIAR; + tmpreg = (heth->Instance)->MACMIIAR; /* Clear CSR Clock Range CR[2:0] bits */ - tmpreg1 &= ETH_MACMIIAR_CR_MASK; + tmpreg &= ETH_MACMIIAR_CR_MASK; /* Get hclk frequency value */ hclk = HAL_RCC_GetHCLKFreq(); /* Set CR bits depending on hclk value */ - if((hclk >= 20000000U)&&(hclk < 35000000U)) + if((hclk >= 20000000)&&(hclk < 35000000)) { /* CSR Clock Range between 20-35 MHz */ - tmpreg1 |= (uint32_t)ETH_MACMIIAR_CR_DIV16; + tmpreg |= (uint32_t)ETH_MACMIIAR_CR_DIV16; } - else if((hclk >= 35000000U)&&(hclk < 60000000U)) + else if((hclk >= 35000000)&&(hclk < 60000000)) { /* CSR Clock Range between 35-60 MHz */ - tmpreg1 |= (uint32_t)ETH_MACMIIAR_CR_DIV26; + tmpreg |= (uint32_t)ETH_MACMIIAR_CR_DIV26; } else { /* CSR Clock Range between 60-72 MHz */ - tmpreg1 |= (uint32_t)ETH_MACMIIAR_CR_DIV42; + tmpreg |= (uint32_t)ETH_MACMIIAR_CR_DIV42; } /* Write to ETHERNET MAC MIIAR: Configure the ETHERNET CSR Clock Range */ - (heth->Instance)->MACMIIAR = (uint32_t)tmpreg1; + (heth->Instance)->MACMIIAR = (uint32_t)tmpreg; /*-------------------- PHY initialization and configuration ----------------*/ /* Put the PHY in reset mode */ @@ -291,7 +276,7 @@ HAL_StatusTypeDef HAL_ETH_Init(ETH_HandleTypeDef *heth) HAL_ETH_ReadPHYRegister(heth, PHY_BSR, &phyreg); /* Check for the Timeout */ - if((HAL_GetTick() - tickstart ) > ETH_TIMEOUT_LINKED_STATE) + if((HAL_GetTick() - tickstart ) > LINKED_STATE_TIMEOUT_VALUE) { /* In case of write timeout */ err = ETH_ERROR; @@ -334,7 +319,7 @@ HAL_StatusTypeDef HAL_ETH_Init(ETH_HandleTypeDef *heth) HAL_ETH_ReadPHYRegister(heth, PHY_BSR, &phyreg); /* Check for the Timeout */ - if((HAL_GetTick() - tickstart ) > ETH_TIMEOUT_AUTONEGO_COMPLETED) + if((HAL_GetTick() - tickstart ) > AUTONEGO_COMPLETED_TIMEOUT_VALUE) { /* In case of write timeout */ err = ETH_ERROR; @@ -398,8 +383,8 @@ HAL_StatusTypeDef HAL_ETH_Init(ETH_HandleTypeDef *heth) assert_param(IS_ETH_DUPLEX_MODE(heth->Init.DuplexMode)); /* Set MAC Speed and Duplex Mode */ - if(HAL_ETH_WritePHYRegister(heth, PHY_BCR, ((uint16_t)((heth->Init).DuplexMode >> 3U) | - (uint16_t)((heth->Init).Speed >> 1U))) != HAL_OK) + if(HAL_ETH_WritePHYRegister(heth, PHY_BCR, ((uint16_t)((heth->Init).DuplexMode >> 3) | + (uint16_t)((heth->Init).Speed >> 1))) != HAL_OK) { /* In case of write timeout */ err = ETH_ERROR; @@ -463,7 +448,7 @@ HAL_StatusTypeDef HAL_ETH_DeInit(ETH_HandleTypeDef *heth) */ HAL_StatusTypeDef HAL_ETH_DMATxDescListInit(ETH_HandleTypeDef *heth, ETH_DMADescTypeDef *DMATxDescTab, uint8_t *TxBuff, uint32_t TxBuffCount) { - uint32_t i = 0U; + uint32_t i = 0; ETH_DMADescTypeDef *dmatxdesc; /* Process Locked */ @@ -476,7 +461,7 @@ HAL_StatusTypeDef HAL_ETH_DMATxDescListInit(ETH_HandleTypeDef *heth, ETH_DMADesc heth->TxDesc = DMATxDescTab; /* Fill each DMATxDesc descriptor with the right values */ - for(i=0U; i < TxBuffCount; i++) + for(i=0; i < TxBuffCount; i++) { /* Get the pointer on the ith member of the Tx Desc list */ dmatxdesc = DMATxDescTab + i; @@ -494,10 +479,10 @@ HAL_StatusTypeDef HAL_ETH_DMATxDescListInit(ETH_HandleTypeDef *heth, ETH_DMADesc } /* Initialize the next descriptor with the Next Descriptor Polling Enable */ - if(i < (TxBuffCount-1U)) + if(i < (TxBuffCount-1)) { /* Set next descriptor address register with next descriptor base address */ - dmatxdesc->Buffer2NextDescAddr = (uint32_t)(DMATxDescTab+i+1U); + dmatxdesc->Buffer2NextDescAddr = (uint32_t)(DMATxDescTab+i+1); } else { @@ -530,7 +515,7 @@ HAL_StatusTypeDef HAL_ETH_DMATxDescListInit(ETH_HandleTypeDef *heth, ETH_DMADesc */ HAL_StatusTypeDef HAL_ETH_DMARxDescListInit(ETH_HandleTypeDef *heth, ETH_DMADescTypeDef *DMARxDescTab, uint8_t *RxBuff, uint32_t RxBuffCount) { - uint32_t i = 0U; + uint32_t i = 0; ETH_DMADescTypeDef *DMARxDesc; /* Process Locked */ @@ -543,7 +528,7 @@ HAL_StatusTypeDef HAL_ETH_DMARxDescListInit(ETH_HandleTypeDef *heth, ETH_DMADesc heth->RxDesc = DMARxDescTab; /* Fill each DMARxDesc descriptor with the right values */ - for(i=0U; i < RxBuffCount; i++) + for(i=0; i < RxBuffCount; i++) { /* Get the pointer on the ith member of the Rx Desc list */ DMARxDesc = DMARxDescTab+i; @@ -564,10 +549,10 @@ HAL_StatusTypeDef HAL_ETH_DMARxDescListInit(ETH_HandleTypeDef *heth, ETH_DMADesc } /* Initialize the next descriptor with the Next Descriptor Polling Enable */ - if(i < (RxBuffCount-1U)) + if(i < (RxBuffCount-1)) { /* Set next descriptor address register with next descriptor base address */ - DMARxDesc->Buffer2NextDescAddr = (uint32_t)(DMARxDescTab+i+1U); + DMARxDesc->Buffer2NextDescAddr = (uint32_t)(DMARxDescTab+i+1); } else { @@ -655,7 +640,7 @@ __weak void HAL_ETH_MspDeInit(ETH_HandleTypeDef *heth) */ HAL_StatusTypeDef HAL_ETH_TransmitFrame(ETH_HandleTypeDef *heth, uint32_t FrameLength) { - uint32_t bufcount = 0U, size = 0U, i = 0U; + uint32_t bufcount = 0, size = 0, i = 0; /* Process Locked */ __HAL_LOCK(heth); @@ -663,7 +648,7 @@ HAL_StatusTypeDef HAL_ETH_TransmitFrame(ETH_HandleTypeDef *heth, uint32_t FrameL /* Set the ETH peripheral state to BUSY */ heth->State = HAL_ETH_STATE_BUSY; - if (FrameLength == 0U) + if (FrameLength == 0) { /* Set ETH HAL state to READY */ heth->State = HAL_ETH_STATE_READY; @@ -697,9 +682,9 @@ HAL_StatusTypeDef HAL_ETH_TransmitFrame(ETH_HandleTypeDef *heth, uint32_t FrameL } else { - bufcount = 1U; + bufcount = 1; } - if (bufcount == 1U) + if (bufcount == 1) { /* Set LAST and FIRST segment */ heth->TxDesc->Status |=ETH_DMATXDESC_FS|ETH_DMATXDESC_LS; @@ -712,12 +697,12 @@ HAL_StatusTypeDef HAL_ETH_TransmitFrame(ETH_HandleTypeDef *heth, uint32_t FrameL } else { - for (i=0U; i< bufcount; i++) + for (i=0; i< bufcount; i++) { /* Clear FIRST and LAST segment bits */ heth->TxDesc->Status &= ~(ETH_DMATXDESC_FS | ETH_DMATXDESC_LS); - if (i == 0U) + if (i == 0) { /* Setting the first segment bit */ heth->TxDesc->Status |= ETH_DMATXDESC_FS; @@ -726,11 +711,11 @@ HAL_StatusTypeDef HAL_ETH_TransmitFrame(ETH_HandleTypeDef *heth, uint32_t FrameL /* Program size */ heth->TxDesc->ControlBufferSize = (ETH_TX_BUF_SIZE & ETH_DMATXDESC_TBS1); - if (i == (bufcount-1U)) + if (i == (bufcount-1)) { /* Setting the last segment bit */ heth->TxDesc->Status |= ETH_DMATXDESC_LS; - size = FrameLength - (bufcount-1U)*ETH_TX_BUF_SIZE; + size = FrameLength - (bufcount-1)*ETH_TX_BUF_SIZE; heth->TxDesc->ControlBufferSize = (size & ETH_DMATXDESC_TBS1); } @@ -747,7 +732,7 @@ HAL_StatusTypeDef HAL_ETH_TransmitFrame(ETH_HandleTypeDef *heth, uint32_t FrameL /* Clear TBUS ETHERNET DMA flag */ (heth->Instance)->DMASR = ETH_DMASR_TBUS; /* Resume DMA transmission*/ - (heth->Instance)->DMATPDR = 0U; + (heth->Instance)->DMATPDR = 0; } /* Set ETH HAL State to Ready */ @@ -768,7 +753,7 @@ HAL_StatusTypeDef HAL_ETH_TransmitFrame(ETH_HandleTypeDef *heth, uint32_t FrameL */ HAL_StatusTypeDef HAL_ETH_GetReceivedFrame(ETH_HandleTypeDef *heth) { - uint32_t framelength = 0U; + uint32_t framelength = 0; /* Process Locked */ __HAL_LOCK(heth); @@ -787,7 +772,7 @@ HAL_StatusTypeDef HAL_ETH_GetReceivedFrame(ETH_HandleTypeDef *heth) (heth->RxFrameInfos).SegCount++; /* Check if last segment is first segment: one segment contains the frame */ - if ((heth->RxFrameInfos).SegCount == 1U) + if ((heth->RxFrameInfos).SegCount == 1) { (heth->RxFrameInfos).FSRxDesc =heth->RxDesc; } @@ -795,7 +780,7 @@ HAL_StatusTypeDef HAL_ETH_GetReceivedFrame(ETH_HandleTypeDef *heth) heth->RxFrameInfos.LSRxDesc = heth->RxDesc; /* Get the Frame Length of the received packet: substruct 4 bytes of the CRC */ - framelength = (((heth->RxDesc)->Status & ETH_DMARXDESC_FL) >> ETH_DMARXDESC_FRAMELENGTHSHIFT) - 4U; + framelength = (((heth->RxDesc)->Status & ETH_DMARXDESC_FL) >> ETH_DMARXDESC_FRAMELENGTHSHIFT) - 4; heth->RxFrameInfos.length = framelength; /* Get the address of the buffer start address */ @@ -817,7 +802,7 @@ HAL_StatusTypeDef HAL_ETH_GetReceivedFrame(ETH_HandleTypeDef *heth) { (heth->RxFrameInfos).FSRxDesc = heth->RxDesc; (heth->RxFrameInfos).LSRxDesc = NULL; - (heth->RxFrameInfos).SegCount = 1U; + (heth->RxFrameInfos).SegCount = 1; /* Point to next descriptor */ heth->RxDesc = (ETH_DMADescTypeDef*) (heth->RxDesc->Buffer2NextDescAddr); } @@ -848,7 +833,7 @@ HAL_StatusTypeDef HAL_ETH_GetReceivedFrame(ETH_HandleTypeDef *heth) */ HAL_StatusTypeDef HAL_ETH_GetReceivedFrame_IT(ETH_HandleTypeDef *heth) { - uint32_t descriptorscancounter = 0U; + uint32_t descriptorscancounter = 0; /* Process Locked */ __HAL_LOCK(heth); @@ -867,7 +852,7 @@ HAL_StatusTypeDef HAL_ETH_GetReceivedFrame_IT(ETH_HandleTypeDef *heth) if((heth->RxDesc->Status & (ETH_DMARXDESC_FS | ETH_DMARXDESC_LS)) == (uint32_t)ETH_DMARXDESC_FS) { heth->RxFrameInfos.FSRxDesc = heth->RxDesc; - heth->RxFrameInfos.SegCount = 1U; + heth->RxFrameInfos.SegCount = 1; /* Point to next descriptor */ heth->RxDesc = (ETH_DMADescTypeDef*) (heth->RxDesc->Buffer2NextDescAddr); } @@ -890,13 +875,13 @@ HAL_StatusTypeDef HAL_ETH_GetReceivedFrame_IT(ETH_HandleTypeDef *heth) (heth->RxFrameInfos.SegCount)++; /* Check if last segment is first segment: one segment contains the frame */ - if ((heth->RxFrameInfos.SegCount) == 1U) + if ((heth->RxFrameInfos.SegCount) == 1) { heth->RxFrameInfos.FSRxDesc = heth->RxDesc; } /* Get the Frame Length of the received packet: substruct 4 bytes of the CRC */ - heth->RxFrameInfos.length = (((heth->RxDesc)->Status & ETH_DMARXDESC_FL) >> ETH_DMARXDESC_FRAMELENGTHSHIFT) - 4U; + heth->RxFrameInfos.length = (((heth->RxDesc)->Status & ETH_DMARXDESC_FL) >> ETH_DMARXDESC_FRAMELENGTHSHIFT) - 4; /* Get the address of the buffer start address */ heth->RxFrameInfos.buffer =((heth->RxFrameInfos).FSRxDesc)->Buffer1Addr; @@ -1044,8 +1029,8 @@ __weak void HAL_ETH_ErrorCallback(ETH_HandleTypeDef *heth) */ HAL_StatusTypeDef HAL_ETH_ReadPHYRegister(ETH_HandleTypeDef *heth, uint16_t PHYReg, uint32_t *RegValue) { - uint32_t tmpreg1 = 0U; - uint32_t tickstart = 0U; + uint32_t tmpreg = 0; + uint32_t tickstart = 0; /* Check parameters */ assert_param(IS_ETH_PHY_ADDRESS(heth->Init.PhyAddress)); @@ -1059,25 +1044,25 @@ HAL_StatusTypeDef HAL_ETH_ReadPHYRegister(ETH_HandleTypeDef *heth, uint16_t PHYR heth->State = HAL_ETH_STATE_BUSY_RD; /* Get the ETHERNET MACMIIAR value */ - tmpreg1 = heth->Instance->MACMIIAR; + tmpreg = heth->Instance->MACMIIAR; /* Keep only the CSR Clock Range CR[2:0] bits value */ - tmpreg1 &= ~ETH_MACMIIAR_CR_MASK; + tmpreg &= ~ETH_MACMIIAR_CR_MASK; /* Prepare the MII address register value */ - tmpreg1 |=(((uint32_t)heth->Init.PhyAddress << 11U) & ETH_MACMIIAR_PA); /* Set the PHY device address */ - tmpreg1 |=(((uint32_t)PHYReg<<6U) & ETH_MACMIIAR_MR); /* Set the PHY register address */ - tmpreg1 &= ~ETH_MACMIIAR_MW; /* Set the read mode */ - tmpreg1 |= ETH_MACMIIAR_MB; /* Set the MII Busy bit */ + tmpreg |=(((uint32_t)heth->Init.PhyAddress << 11) & ETH_MACMIIAR_PA); /* Set the PHY device address */ + tmpreg |=(((uint32_t)PHYReg<<6) & ETH_MACMIIAR_MR); /* Set the PHY register address */ + tmpreg &= ~ETH_MACMIIAR_MW; /* Set the read mode */ + tmpreg |= ETH_MACMIIAR_MB; /* Set the MII Busy bit */ /* Write the result value into the MII Address register */ - heth->Instance->MACMIIAR = tmpreg1; + heth->Instance->MACMIIAR = tmpreg; /* Get tick */ tickstart = HAL_GetTick(); /* Check for the Busy flag */ - while((tmpreg1 & ETH_MACMIIAR_MB) == ETH_MACMIIAR_MB) + while((tmpreg & ETH_MACMIIAR_MB) == ETH_MACMIIAR_MB) { /* Check for the Timeout */ if((HAL_GetTick() - tickstart ) > PHY_READ_TO) @@ -1090,7 +1075,7 @@ HAL_StatusTypeDef HAL_ETH_ReadPHYRegister(ETH_HandleTypeDef *heth, uint16_t PHYR return HAL_TIMEOUT; } - tmpreg1 = heth->Instance->MACMIIAR; + tmpreg = heth->Instance->MACMIIAR; } /* Get MACMIIDR value */ @@ -1116,8 +1101,8 @@ HAL_StatusTypeDef HAL_ETH_ReadPHYRegister(ETH_HandleTypeDef *heth, uint16_t PHYR */ HAL_StatusTypeDef HAL_ETH_WritePHYRegister(ETH_HandleTypeDef *heth, uint16_t PHYReg, uint32_t RegValue) { - uint32_t tmpreg1 = 0U; - uint32_t tickstart = 0U; + uint32_t tmpreg = 0; + uint32_t tickstart = 0; /* Check parameters */ assert_param(IS_ETH_PHY_ADDRESS(heth->Init.PhyAddress)); @@ -1131,28 +1116,28 @@ HAL_StatusTypeDef HAL_ETH_WritePHYRegister(ETH_HandleTypeDef *heth, uint16_t PHY heth->State = HAL_ETH_STATE_BUSY_WR; /* Get the ETHERNET MACMIIAR value */ - tmpreg1 = heth->Instance->MACMIIAR; + tmpreg = heth->Instance->MACMIIAR; /* Keep only the CSR Clock Range CR[2:0] bits value */ - tmpreg1 &= ~ETH_MACMIIAR_CR_MASK; + tmpreg &= ~ETH_MACMIIAR_CR_MASK; /* Prepare the MII register address value */ - tmpreg1 |=(((uint32_t)heth->Init.PhyAddress<<11U) & ETH_MACMIIAR_PA); /* Set the PHY device address */ - tmpreg1 |=(((uint32_t)PHYReg<<6U) & ETH_MACMIIAR_MR); /* Set the PHY register address */ - tmpreg1 |= ETH_MACMIIAR_MW; /* Set the write mode */ - tmpreg1 |= ETH_MACMIIAR_MB; /* Set the MII Busy bit */ + tmpreg |=(((uint32_t)heth->Init.PhyAddress<<11) & ETH_MACMIIAR_PA); /* Set the PHY device address */ + tmpreg |=(((uint32_t)PHYReg<<6) & ETH_MACMIIAR_MR); /* Set the PHY register address */ + tmpreg |= ETH_MACMIIAR_MW; /* Set the write mode */ + tmpreg |= ETH_MACMIIAR_MB; /* Set the MII Busy bit */ /* Give the value to the MII data register */ heth->Instance->MACMIIDR = (uint16_t)RegValue; /* Write the result value into the MII Address register */ - heth->Instance->MACMIIAR = tmpreg1; + heth->Instance->MACMIIAR = tmpreg; /* Get tick */ tickstart = HAL_GetTick(); /* Check for the Busy flag */ - while((tmpreg1 & ETH_MACMIIAR_MB) == ETH_MACMIIAR_MB) + while((tmpreg & ETH_MACMIIAR_MB) == ETH_MACMIIAR_MB) { /* Check for the Timeout */ if((HAL_GetTick() - tickstart ) > PHY_WRITE_TO) @@ -1165,7 +1150,7 @@ HAL_StatusTypeDef HAL_ETH_WritePHYRegister(ETH_HandleTypeDef *heth, uint16_t PHY return HAL_TIMEOUT; } - tmpreg1 = heth->Instance->MACMIIAR; + tmpreg = heth->Instance->MACMIIAR; } /* Set ETH HAL State to READY */ @@ -1287,7 +1272,7 @@ HAL_StatusTypeDef HAL_ETH_Stop(ETH_HandleTypeDef *heth) */ HAL_StatusTypeDef HAL_ETH_ConfigMAC(ETH_HandleTypeDef *heth, ETH_MACInitTypeDef *macconf) { - uint32_t tmpreg1 = 0U; + uint32_t tmpreg = 0; /* Process Locked */ __HAL_LOCK(heth); @@ -1331,11 +1316,11 @@ HAL_StatusTypeDef HAL_ETH_ConfigMAC(ETH_HandleTypeDef *heth, ETH_MACInitTypeDef /*------------------------ ETHERNET MACCR Configuration --------------------*/ /* Get the ETHERNET MACCR value */ - tmpreg1 = (heth->Instance)->MACCR; + tmpreg = (heth->Instance)->MACCR; /* Clear WD, PCE, PS, TE and RE bits */ - tmpreg1 &= ETH_MACCR_CLEAR_MASK; + tmpreg &= ETH_MACCR_CLEAR_MASK; - tmpreg1 |= (uint32_t)(macconf->Watchdog | + tmpreg |= (uint32_t)(macconf->Watchdog | macconf->Jabber | macconf->InterFrameGap | macconf->CarrierSense | @@ -1350,13 +1335,13 @@ HAL_StatusTypeDef HAL_ETH_ConfigMAC(ETH_HandleTypeDef *heth, ETH_MACInitTypeDef macconf->DeferralCheck); /* Write to ETHERNET MACCR */ - (heth->Instance)->MACCR = (uint32_t)tmpreg1; + (heth->Instance)->MACCR = (uint32_t)tmpreg; /* Wait until the write operation will be taken into account : at least four TX_CLK/RX_CLK clock cycles */ - tmpreg1 = (heth->Instance)->MACCR; + tmpreg = (heth->Instance)->MACCR; HAL_Delay(ETH_REG_WRITE_DELAY); - (heth->Instance)->MACCR = tmpreg1; + (heth->Instance)->MACCR = tmpreg; /*----------------------- ETHERNET MACFFR Configuration --------------------*/ /* Write to ETHERNET MACFFR */ @@ -1371,9 +1356,9 @@ HAL_StatusTypeDef HAL_ETH_ConfigMAC(ETH_HandleTypeDef *heth, ETH_MACInitTypeDef /* Wait until the write operation will be taken into account : at least four TX_CLK/RX_CLK clock cycles */ - tmpreg1 = (heth->Instance)->MACFFR; + tmpreg = (heth->Instance)->MACFFR; HAL_Delay(ETH_REG_WRITE_DELAY); - (heth->Instance)->MACFFR = tmpreg1; + (heth->Instance)->MACFFR = tmpreg; /*--------------- ETHERNET MACHTHR and MACHTLR Configuration ---------------*/ /* Write to ETHERNET MACHTHR */ @@ -1384,11 +1369,11 @@ HAL_StatusTypeDef HAL_ETH_ConfigMAC(ETH_HandleTypeDef *heth, ETH_MACInitTypeDef /*----------------------- ETHERNET MACFCR Configuration --------------------*/ /* Get the ETHERNET MACFCR value */ - tmpreg1 = (heth->Instance)->MACFCR; + tmpreg = (heth->Instance)->MACFCR; /* Clear xx bits */ - tmpreg1 &= ETH_MACFCR_CLEAR_MASK; + tmpreg &= ETH_MACFCR_CLEAR_MASK; - tmpreg1 |= (uint32_t)((macconf->PauseTime << 16U) | + tmpreg |= (uint32_t)((macconf->PauseTime << 16) | macconf->ZeroQuantaPause | macconf->PauseLowThreshold | macconf->UnicastPauseFrameDetect | @@ -1396,13 +1381,13 @@ HAL_StatusTypeDef HAL_ETH_ConfigMAC(ETH_HandleTypeDef *heth, ETH_MACInitTypeDef macconf->TransmitFlowControl); /* Write to ETHERNET MACFCR */ - (heth->Instance)->MACFCR = (uint32_t)tmpreg1; + (heth->Instance)->MACFCR = (uint32_t)tmpreg; /* Wait until the write operation will be taken into account : at least four TX_CLK/RX_CLK clock cycles */ - tmpreg1 = (heth->Instance)->MACFCR; + tmpreg = (heth->Instance)->MACFCR; HAL_Delay(ETH_REG_WRITE_DELAY); - (heth->Instance)->MACFCR = tmpreg1; + (heth->Instance)->MACFCR = tmpreg; /*----------------------- ETHERNET MACVLANTR Configuration -----------------*/ (heth->Instance)->MACVLANTR = (uint32_t)(macconf->VLANTagComparison | @@ -1410,29 +1395,29 @@ HAL_StatusTypeDef HAL_ETH_ConfigMAC(ETH_HandleTypeDef *heth, ETH_MACInitTypeDef /* Wait until the write operation will be taken into account : at least four TX_CLK/RX_CLK clock cycles */ - tmpreg1 = (heth->Instance)->MACVLANTR; + tmpreg = (heth->Instance)->MACVLANTR; HAL_Delay(ETH_REG_WRITE_DELAY); - (heth->Instance)->MACVLANTR = tmpreg1; + (heth->Instance)->MACVLANTR = tmpreg; } else /* macconf == NULL : here we just configure Speed and Duplex mode */ { /*------------------------ ETHERNET MACCR Configuration --------------------*/ /* Get the ETHERNET MACCR value */ - tmpreg1 = (heth->Instance)->MACCR; + tmpreg = (heth->Instance)->MACCR; /* Clear FES and DM bits */ - tmpreg1 &= ~(0x00004800U); + tmpreg &= ~((uint32_t)0x00004800); - tmpreg1 |= (uint32_t)(heth->Init.Speed | heth->Init.DuplexMode); + tmpreg |= (uint32_t)(heth->Init.Speed | heth->Init.DuplexMode); /* Write to ETHERNET MACCR */ - (heth->Instance)->MACCR = (uint32_t)tmpreg1; + (heth->Instance)->MACCR = (uint32_t)tmpreg; /* Wait until the write operation will be taken into account: at least four TX_CLK/RX_CLK clock cycles */ - tmpreg1 = (heth->Instance)->MACCR; + tmpreg = (heth->Instance)->MACCR; HAL_Delay(ETH_REG_WRITE_DELAY); - (heth->Instance)->MACCR = tmpreg1; + (heth->Instance)->MACCR = tmpreg; } /* Set the ETH state to Ready */ @@ -1454,7 +1439,7 @@ HAL_StatusTypeDef HAL_ETH_ConfigMAC(ETH_HandleTypeDef *heth, ETH_MACInitTypeDef */ HAL_StatusTypeDef HAL_ETH_ConfigDMA(ETH_HandleTypeDef *heth, ETH_DMAInitTypeDef *dmaconf) { - uint32_t tmpreg1 = 0U; + uint32_t tmpreg = 0; /* Process Locked */ __HAL_LOCK(heth); @@ -1481,11 +1466,11 @@ HAL_StatusTypeDef HAL_ETH_ConfigDMA(ETH_HandleTypeDef *heth, ETH_DMAInitTypeDef /*----------------------- ETHERNET DMAOMR Configuration --------------------*/ /* Get the ETHERNET DMAOMR value */ - tmpreg1 = (heth->Instance)->DMAOMR; + tmpreg = (heth->Instance)->DMAOMR; /* Clear xx bits */ - tmpreg1 &= ETH_DMAOMR_CLEAR_MASK; + tmpreg &= ETH_DMAOMR_CLEAR_MASK; - tmpreg1 |= (uint32_t)(dmaconf->DropTCPIPChecksumErrorFrame | + tmpreg |= (uint32_t)(dmaconf->DropTCPIPChecksumErrorFrame | dmaconf->ReceiveStoreForward | dmaconf->FlushReceivedFrame | dmaconf->TransmitStoreForward | @@ -1496,28 +1481,28 @@ HAL_StatusTypeDef HAL_ETH_ConfigDMA(ETH_HandleTypeDef *heth, ETH_DMAInitTypeDef dmaconf->SecondFrameOperate); /* Write to ETHERNET DMAOMR */ - (heth->Instance)->DMAOMR = (uint32_t)tmpreg1; + (heth->Instance)->DMAOMR = (uint32_t)tmpreg; /* Wait until the write operation will be taken into account: at least four TX_CLK/RX_CLK clock cycles */ - tmpreg1 = (heth->Instance)->DMAOMR; + tmpreg = (heth->Instance)->DMAOMR; HAL_Delay(ETH_REG_WRITE_DELAY); - (heth->Instance)->DMAOMR = tmpreg1; + (heth->Instance)->DMAOMR = tmpreg; /*----------------------- ETHERNET DMABMR Configuration --------------------*/ (heth->Instance)->DMABMR = (uint32_t)(dmaconf->AddressAlignedBeats | dmaconf->FixedBurst | dmaconf->RxDMABurstLength | /* !! if 4xPBL is selected for Tx or Rx it is applied for the other */ dmaconf->TxDMABurstLength | - (dmaconf->DescriptorSkipLength << 2U) | + (dmaconf->DescriptorSkipLength << 2) | dmaconf->DMAArbitration | ETH_DMABMR_USP); /* Enable use of separate PBL for Rx and Tx */ /* Wait until the write operation will be taken into account: at least four TX_CLK/RX_CLK clock cycles */ - tmpreg1 = (heth->Instance)->DMABMR; + tmpreg = (heth->Instance)->DMABMR; HAL_Delay(ETH_REG_WRITE_DELAY); - (heth->Instance)->DMABMR = tmpreg1; + (heth->Instance)->DMABMR = tmpreg; /* Set the ETH state to Ready */ heth->State= HAL_ETH_STATE_READY; @@ -1586,7 +1571,7 @@ static void ETH_MACDMAConfig(ETH_HandleTypeDef *heth, uint32_t err) { ETH_MACInitTypeDef macinit; ETH_DMAInitTypeDef dmainit; - uint32_t tmpreg1 = 0U; + uint32_t tmpreg = 0; if (err != ETH_SUCCESS) /* Auto-negotiation failed */ { @@ -1624,22 +1609,22 @@ static void ETH_MACDMAConfig(ETH_HandleTypeDef *heth, uint32_t err) macinit.PromiscuousMode = ETH_PROMISCUOUS_MODE_DISABLE; macinit.MulticastFramesFilter = ETH_MULTICASTFRAMESFILTER_PERFECT; macinit.UnicastFramesFilter = ETH_UNICASTFRAMESFILTER_PERFECT; - macinit.HashTableHigh = 0x0U; - macinit.HashTableLow = 0x0U; - macinit.PauseTime = 0x0U; + macinit.HashTableHigh = 0x0; + macinit.HashTableLow = 0x0; + macinit.PauseTime = 0x0; macinit.ZeroQuantaPause = ETH_ZEROQUANTAPAUSE_DISABLE; macinit.PauseLowThreshold = ETH_PAUSELOWTHRESHOLD_MINUS4; macinit.UnicastPauseFrameDetect = ETH_UNICASTPAUSEFRAMEDETECT_DISABLE; macinit.ReceiveFlowControl = ETH_RECEIVEFLOWCONTROL_DISABLE; macinit.TransmitFlowControl = ETH_TRANSMITFLOWCONTROL_DISABLE; macinit.VLANTagComparison = ETH_VLANTAGCOMPARISON_16BIT; - macinit.VLANTagIdentifier = 0x0U; + macinit.VLANTagIdentifier = 0x0; /*------------------------ ETHERNET MACCR Configuration --------------------*/ /* Get the ETHERNET MACCR value */ - tmpreg1 = (heth->Instance)->MACCR; + tmpreg = (heth->Instance)->MACCR; /* Clear WD, PCE, PS, TE and RE bits */ - tmpreg1 &= ETH_MACCR_CLEAR_MASK; + tmpreg &= ETH_MACCR_CLEAR_MASK; /* Set the WD bit according to ETH Watchdog value */ /* Set the JD: bit according to ETH Jabber value */ /* Set the IFG bit according to ETH InterFrameGap value */ @@ -1653,7 +1638,7 @@ static void ETH_MACDMAConfig(ETH_HandleTypeDef *heth, uint32_t err) /* Set the ACS bit according to ETH AutomaticPadCRCStrip value */ /* Set the BL bit according to ETH BackOffLimit value */ /* Set the DC bit according to ETH DeferralCheck value */ - tmpreg1 |= (uint32_t)(macinit.Watchdog | + tmpreg |= (uint32_t)(macinit.Watchdog | macinit.Jabber | macinit.InterFrameGap | macinit.CarrierSense | @@ -1668,13 +1653,13 @@ static void ETH_MACDMAConfig(ETH_HandleTypeDef *heth, uint32_t err) macinit.DeferralCheck); /* Write to ETHERNET MACCR */ - (heth->Instance)->MACCR = (uint32_t)tmpreg1; + (heth->Instance)->MACCR = (uint32_t)tmpreg; /* Wait until the write operation will be taken into account: at least four TX_CLK/RX_CLK clock cycles */ - tmpreg1 = (heth->Instance)->MACCR; + tmpreg = (heth->Instance)->MACCR; HAL_Delay(ETH_REG_WRITE_DELAY); - (heth->Instance)->MACCR = tmpreg1; + (heth->Instance)->MACCR = tmpreg; /*----------------------- ETHERNET MACFFR Configuration --------------------*/ /* Set the RA bit according to ETH ReceiveAll value */ @@ -1697,9 +1682,9 @@ static void ETH_MACDMAConfig(ETH_HandleTypeDef *heth, uint32_t err) /* Wait until the write operation will be taken into account: at least four TX_CLK/RX_CLK clock cycles */ - tmpreg1 = (heth->Instance)->MACFFR; + tmpreg = (heth->Instance)->MACFFR; HAL_Delay(ETH_REG_WRITE_DELAY); - (heth->Instance)->MACFFR = tmpreg1; + (heth->Instance)->MACFFR = tmpreg; /*--------------- ETHERNET MACHTHR and MACHTLR Configuration --------------*/ /* Write to ETHERNET MACHTHR */ @@ -1710,9 +1695,9 @@ static void ETH_MACDMAConfig(ETH_HandleTypeDef *heth, uint32_t err) /*----------------------- ETHERNET MACFCR Configuration -------------------*/ /* Get the ETHERNET MACFCR value */ - tmpreg1 = (heth->Instance)->MACFCR; + tmpreg = (heth->Instance)->MACFCR; /* Clear xx bits */ - tmpreg1 &= ETH_MACFCR_CLEAR_MASK; + tmpreg &= ETH_MACFCR_CLEAR_MASK; /* Set the PT bit according to ETH PauseTime value */ /* Set the DZPQ bit according to ETH ZeroQuantaPause value */ @@ -1720,7 +1705,7 @@ static void ETH_MACDMAConfig(ETH_HandleTypeDef *heth, uint32_t err) /* Set the UP bit according to ETH UnicastPauseFrameDetect value */ /* Set the RFE bit according to ETH ReceiveFlowControl value */ /* Set the TFE bit according to ETH TransmitFlowControl value */ - tmpreg1 |= (uint32_t)((macinit.PauseTime << 16U) | + tmpreg |= (uint32_t)((macinit.PauseTime << 16) | macinit.ZeroQuantaPause | macinit.PauseLowThreshold | macinit.UnicastPauseFrameDetect | @@ -1728,13 +1713,13 @@ static void ETH_MACDMAConfig(ETH_HandleTypeDef *heth, uint32_t err) macinit.TransmitFlowControl); /* Write to ETHERNET MACFCR */ - (heth->Instance)->MACFCR = (uint32_t)tmpreg1; + (heth->Instance)->MACFCR = (uint32_t)tmpreg; /* Wait until the write operation will be taken into account: at least four TX_CLK/RX_CLK clock cycles */ - tmpreg1 = (heth->Instance)->MACFCR; + tmpreg = (heth->Instance)->MACFCR; HAL_Delay(ETH_REG_WRITE_DELAY); - (heth->Instance)->MACFCR = tmpreg1; + (heth->Instance)->MACFCR = tmpreg; /*----------------------- ETHERNET MACVLANTR Configuration ----------------*/ /* Set the ETV bit according to ETH VLANTagComparison value */ @@ -1744,9 +1729,9 @@ static void ETH_MACDMAConfig(ETH_HandleTypeDef *heth, uint32_t err) /* Wait until the write operation will be taken into account: at least four TX_CLK/RX_CLK clock cycles */ - tmpreg1 = (heth->Instance)->MACVLANTR; + tmpreg = (heth->Instance)->MACVLANTR; HAL_Delay(ETH_REG_WRITE_DELAY); - (heth->Instance)->MACVLANTR = tmpreg1; + (heth->Instance)->MACVLANTR = tmpreg; /* Ethernet DMA default initialization ************************************/ dmainit.DropTCPIPChecksumErrorFrame = ETH_DROPTCPIPCHECKSUMERRORFRAME_ENABLE; @@ -1762,13 +1747,13 @@ static void ETH_MACDMAConfig(ETH_HandleTypeDef *heth, uint32_t err) dmainit.FixedBurst = ETH_FIXEDBURST_ENABLE; dmainit.RxDMABurstLength = ETH_RXDMABURSTLENGTH_32BEAT; dmainit.TxDMABurstLength = ETH_TXDMABURSTLENGTH_32BEAT; - dmainit.DescriptorSkipLength = 0x0U; + dmainit.DescriptorSkipLength = 0x0; dmainit.DMAArbitration = ETH_DMAARBITRATION_ROUNDROBIN_RXTX_1_1; /* Get the ETHERNET DMAOMR value */ - tmpreg1 = (heth->Instance)->DMAOMR; + tmpreg = (heth->Instance)->DMAOMR; /* Clear xx bits */ - tmpreg1 &= ETH_DMAOMR_CLEAR_MASK; + tmpreg &= ETH_DMAOMR_CLEAR_MASK; /* Set the DT bit according to ETH DropTCPIPChecksumErrorFrame value */ /* Set the RSF bit according to ETH ReceiveStoreForward value */ @@ -1779,7 +1764,7 @@ static void ETH_MACDMAConfig(ETH_HandleTypeDef *heth, uint32_t err) /* Set the FUF bit according to ETH ForwardUndersizedGoodFrames value */ /* Set the RTC bit according to ETH ReceiveThresholdControl value */ /* Set the OSF bit according to ETH SecondFrameOperate value */ - tmpreg1 |= (uint32_t)(dmainit.DropTCPIPChecksumErrorFrame | + tmpreg |= (uint32_t)(dmainit.DropTCPIPChecksumErrorFrame | dmainit.ReceiveStoreForward | dmainit.FlushReceivedFrame | dmainit.TransmitStoreForward | @@ -1790,13 +1775,13 @@ static void ETH_MACDMAConfig(ETH_HandleTypeDef *heth, uint32_t err) dmainit.SecondFrameOperate); /* Write to ETHERNET DMAOMR */ - (heth->Instance)->DMAOMR = (uint32_t)tmpreg1; + (heth->Instance)->DMAOMR = (uint32_t)tmpreg; /* Wait until the write operation will be taken into account: at least four TX_CLK/RX_CLK clock cycles */ - tmpreg1 = (heth->Instance)->DMAOMR; + tmpreg = (heth->Instance)->DMAOMR; HAL_Delay(ETH_REG_WRITE_DELAY); - (heth->Instance)->DMAOMR = tmpreg1; + (heth->Instance)->DMAOMR = tmpreg; /*----------------------- ETHERNET DMABMR Configuration ------------------*/ /* Set the AAL bit according to ETH AddressAlignedBeats value */ @@ -1809,15 +1794,15 @@ static void ETH_MACDMAConfig(ETH_HandleTypeDef *heth, uint32_t err) dmainit.FixedBurst | dmainit.RxDMABurstLength | /* !! if 4xPBL is selected for Tx or Rx it is applied for the other */ dmainit.TxDMABurstLength | - (dmainit.DescriptorSkipLength << 2U) | + (dmainit.DescriptorSkipLength << 2) | dmainit.DMAArbitration | ETH_DMABMR_USP); /* Enable use of separate PBL for Rx and Tx */ /* Wait until the write operation will be taken into account: at least four TX_CLK/RX_CLK clock cycles */ - tmpreg1 = (heth->Instance)->DMABMR; + tmpreg = (heth->Instance)->DMABMR; HAL_Delay(ETH_REG_WRITE_DELAY); - (heth->Instance)->DMABMR = tmpreg1; + (heth->Instance)->DMABMR = tmpreg; if((heth->Init).RxMode == ETH_RXINTERRUPT_MODE) { @@ -1844,23 +1829,20 @@ static void ETH_MACDMAConfig(ETH_HandleTypeDef *heth, uint32_t err) */ static void ETH_MACAddressConfig(ETH_HandleTypeDef *heth, uint32_t MacAddr, uint8_t *Addr) { - uint32_t tmpreg1; + uint32_t tmpreg; - /* Prevent unused argument(s) compilation warning */ - UNUSED(heth); - /* Check the parameters */ assert_param(IS_ETH_MAC_ADDRESS0123(MacAddr)); /* Calculate the selected MAC address high register */ - tmpreg1 = ((uint32_t)Addr[5U] << 8U) | (uint32_t)Addr[4U]; + tmpreg = ((uint32_t)Addr[5] << 8) | (uint32_t)Addr[4]; /* Load the selected MAC address high register */ - (*(__IO uint32_t *)((uint32_t)(ETH_MAC_ADDR_HBASE + MacAddr))) = tmpreg1; + (*(__IO uint32_t *)((uint32_t)(ETH_MAC_ADDR_HBASE + MacAddr))) = tmpreg; /* Calculate the selected MAC address low register */ - tmpreg1 = ((uint32_t)Addr[3U] << 24U) | ((uint32_t)Addr[2U] << 16U) | ((uint32_t)Addr[1U] << 8U) | Addr[0U]; + tmpreg = ((uint32_t)Addr[3] << 24) | ((uint32_t)Addr[2] << 16) | ((uint32_t)Addr[1] << 8) | Addr[0]; /* Load the selected MAC address low register */ - (*(__IO uint32_t *)((uint32_t)(ETH_MAC_ADDR_LBASE + MacAddr))) = tmpreg1; + (*(__IO uint32_t *)((uint32_t)(ETH_MAC_ADDR_LBASE + MacAddr))) = tmpreg; } /** @@ -1871,16 +1853,16 @@ static void ETH_MACAddressConfig(ETH_HandleTypeDef *heth, uint32_t MacAddr, uint */ static void ETH_MACTransmissionEnable(ETH_HandleTypeDef *heth) { - __IO uint32_t tmpreg1 = 0U; + __IO uint32_t tmpreg = 0; /* Enable the MAC transmission */ (heth->Instance)->MACCR |= ETH_MACCR_TE; /* Wait until the write operation will be taken into account: at least four TX_CLK/RX_CLK clock cycles */ - tmpreg1 = (heth->Instance)->MACCR; - ETH_Delay(ETH_REG_WRITE_DELAY); - (heth->Instance)->MACCR = tmpreg1; + tmpreg = (heth->Instance)->MACCR; + HAL_Delay(ETH_REG_WRITE_DELAY); + (heth->Instance)->MACCR = tmpreg; } /** @@ -1891,16 +1873,16 @@ static void ETH_MACTransmissionEnable(ETH_HandleTypeDef *heth) */ static void ETH_MACTransmissionDisable(ETH_HandleTypeDef *heth) { - __IO uint32_t tmpreg1 = 0U; + __IO uint32_t tmpreg = 0; /* Disable the MAC transmission */ (heth->Instance)->MACCR &= ~ETH_MACCR_TE; /* Wait until the write operation will be taken into account: at least four TX_CLK/RX_CLK clock cycles */ - tmpreg1 = (heth->Instance)->MACCR; - ETH_Delay(ETH_REG_WRITE_DELAY); - (heth->Instance)->MACCR = tmpreg1; + tmpreg = (heth->Instance)->MACCR; + HAL_Delay(ETH_REG_WRITE_DELAY); + (heth->Instance)->MACCR = tmpreg; } /** @@ -1911,16 +1893,16 @@ static void ETH_MACTransmissionDisable(ETH_HandleTypeDef *heth) */ static void ETH_MACReceptionEnable(ETH_HandleTypeDef *heth) { - __IO uint32_t tmpreg1 = 0U; + __IO uint32_t tmpreg = 0; /* Enable the MAC reception */ (heth->Instance)->MACCR |= ETH_MACCR_RE; /* Wait until the write operation will be taken into account: at least four TX_CLK/RX_CLK clock cycles */ - tmpreg1 = (heth->Instance)->MACCR; - ETH_Delay(ETH_REG_WRITE_DELAY); - (heth->Instance)->MACCR = tmpreg1; + tmpreg = (heth->Instance)->MACCR; + HAL_Delay(ETH_REG_WRITE_DELAY); + (heth->Instance)->MACCR = tmpreg; } /** @@ -1931,16 +1913,16 @@ static void ETH_MACReceptionEnable(ETH_HandleTypeDef *heth) */ static void ETH_MACReceptionDisable(ETH_HandleTypeDef *heth) { - __IO uint32_t tmpreg1 = 0U; + __IO uint32_t tmpreg = 0; /* Disable the MAC reception */ (heth->Instance)->MACCR &= ~ETH_MACCR_RE; /* Wait until the write operation will be taken into account: at least four TX_CLK/RX_CLK clock cycles */ - tmpreg1 = (heth->Instance)->MACCR; - ETH_Delay(ETH_REG_WRITE_DELAY); - (heth->Instance)->MACCR = tmpreg1; + tmpreg = (heth->Instance)->MACCR; + HAL_Delay(ETH_REG_WRITE_DELAY); + (heth->Instance)->MACCR = tmpreg; } /** @@ -1999,31 +1981,16 @@ static void ETH_DMAReceptionDisable(ETH_HandleTypeDef *heth) */ static void ETH_FlushTransmitFIFO(ETH_HandleTypeDef *heth) { - __IO uint32_t tmpreg1 = 0U; + __IO uint32_t tmpreg = 0; /* Set the Flush Transmit FIFO bit */ (heth->Instance)->DMAOMR |= ETH_DMAOMR_FTF; /* Wait until the write operation will be taken into account: at least four TX_CLK/RX_CLK clock cycles */ - tmpreg1 = (heth->Instance)->DMAOMR; - ETH_Delay(ETH_REG_WRITE_DELAY); - (heth->Instance)->DMAOMR = tmpreg1; -} - -/** - * @brief This function provides delay (in milliseconds) based on CPU cycles method. - * @param mdelay: specifies the delay time length, in milliseconds. - * @retval None - */ -static void ETH_Delay(uint32_t mdelay) -{ - __IO uint32_t Delay = mdelay * (SystemCoreClock / 8U / 1000U); - do - { - __NOP(); - } - while (Delay --); + tmpreg = (heth->Instance)->DMAOMR; + HAL_Delay(ETH_REG_WRITE_DELAY); + (heth->Instance)->DMAOMR = tmpreg; } /** diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_eth.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_eth.h index cb2f3c85ba4..8ec39a39ab4 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_eth.h +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_eth.h @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_hal_eth.h * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief Header file of ETH HAL module. ****************************************************************************** * @attention @@ -58,7 +58,7 @@ /** @addtogroup ETH_Private_Macros * @{ */ -#define IS_ETH_PHY_ADDRESS(ADDRESS) ((ADDRESS) <= 0x20U) +#define IS_ETH_PHY_ADDRESS(ADDRESS) ((ADDRESS) <= 0x20) #define IS_ETH_AUTONEGOTIATION(CMD) (((CMD) == ETH_AUTONEGOTIATION_ENABLE) || \ ((CMD) == ETH_AUTONEGOTIATION_DISABLE)) #define IS_ETH_SPEED(SPEED) (((SPEED) == ETH_SPEED_10M) || \ @@ -122,7 +122,7 @@ #define IS_ETH_UNICAST_FRAMES_FILTER(FILTER) (((FILTER) == ETH_UNICASTFRAMESFILTER_PERFECTHASHTABLE) || \ ((FILTER) == ETH_UNICASTFRAMESFILTER_HASHTABLE) || \ ((FILTER) == ETH_UNICASTFRAMESFILTER_PERFECT)) -#define IS_ETH_PAUSE_TIME(TIME) ((TIME) <= 0xFFFFU) +#define IS_ETH_PAUSE_TIME(TIME) ((TIME) <= 0xFFFF) #define IS_ETH_ZEROQUANTA_PAUSE(CMD) (((CMD) == ETH_ZEROQUANTAPAUSE_ENABLE) || \ ((CMD) == ETH_ZEROQUANTAPAUSE_DISABLE)) #define IS_ETH_PAUSE_LOW_THRESHOLD(THRESHOLD) (((THRESHOLD) == ETH_PAUSELOWTHRESHOLD_MINUS4) || \ @@ -137,7 +137,7 @@ ((CMD) == ETH_TRANSMITFLOWCONTROL_DISABLE)) #define IS_ETH_VLAN_TAG_COMPARISON(COMPARISON) (((COMPARISON) == ETH_VLANTAGCOMPARISON_12BIT) || \ ((COMPARISON) == ETH_VLANTAGCOMPARISON_16BIT)) -#define IS_ETH_VLAN_TAG_IDENTIFIER(IDENTIFIER) ((IDENTIFIER) <= 0xFFFFU) +#define IS_ETH_VLAN_TAG_IDENTIFIER(IDENTIFIER) ((IDENTIFIER) <= 0xFFFF) #define IS_ETH_MAC_ADDRESS0123(ADDRESS) (((ADDRESS) == ETH_MAC_ADDRESS0) || \ ((ADDRESS) == ETH_MAC_ADDRESS1) || \ ((ADDRESS) == ETH_MAC_ADDRESS2) || \ @@ -207,157 +207,80 @@ ((LENGTH) == ETH_TXDMABURSTLENGTH_4XPBL_32BEAT) || \ ((LENGTH) == ETH_TXDMABURSTLENGTH_4XPBL_64BEAT) || \ ((LENGTH) == ETH_TXDMABURSTLENGTH_4XPBL_128BEAT)) -#define IS_ETH_DMA_DESC_SKIP_LENGTH(LENGTH) ((LENGTH) <= 0x1FU) +#define IS_ETH_DMA_DESC_SKIP_LENGTH(LENGTH) ((LENGTH) <= 0x1F) #define IS_ETH_DMA_ARBITRATION_ROUNDROBIN_RXTX(RATIO) (((RATIO) == ETH_DMAARBITRATION_ROUNDROBIN_RXTX_1_1) || \ ((RATIO) == ETH_DMAARBITRATION_ROUNDROBIN_RXTX_2_1) || \ ((RATIO) == ETH_DMAARBITRATION_ROUNDROBIN_RXTX_3_1) || \ ((RATIO) == ETH_DMAARBITRATION_ROUNDROBIN_RXTX_4_1) || \ ((RATIO) == ETH_DMAARBITRATION_RXPRIORTX)) -#define IS_ETH_DMATXDESC_GET_FLAG(FLAG) (((FLAG) == ETH_DMATXDESC_OWN) || \ - ((FLAG) == ETH_DMATXDESC_IC) || \ - ((FLAG) == ETH_DMATXDESC_LS) || \ - ((FLAG) == ETH_DMATXDESC_FS) || \ - ((FLAG) == ETH_DMATXDESC_DC) || \ - ((FLAG) == ETH_DMATXDESC_DP) || \ - ((FLAG) == ETH_DMATXDESC_TTSE) || \ - ((FLAG) == ETH_DMATXDESC_TER) || \ - ((FLAG) == ETH_DMATXDESC_TCH) || \ - ((FLAG) == ETH_DMATXDESC_TTSS) || \ - ((FLAG) == ETH_DMATXDESC_IHE) || \ - ((FLAG) == ETH_DMATXDESC_ES) || \ - ((FLAG) == ETH_DMATXDESC_JT) || \ - ((FLAG) == ETH_DMATXDESC_FF) || \ - ((FLAG) == ETH_DMATXDESC_PCE) || \ - ((FLAG) == ETH_DMATXDESC_LCA) || \ - ((FLAG) == ETH_DMATXDESC_NC) || \ - ((FLAG) == ETH_DMATXDESC_LCO) || \ - ((FLAG) == ETH_DMATXDESC_EC) || \ - ((FLAG) == ETH_DMATXDESC_VF) || \ - ((FLAG) == ETH_DMATXDESC_CC) || \ - ((FLAG) == ETH_DMATXDESC_ED) || \ - ((FLAG) == ETH_DMATXDESC_UF) || \ - ((FLAG) == ETH_DMATXDESC_DB)) + #define IS_ETH_DMA_TXDESC_SEGMENT(SEGMENT) (((SEGMENT) == ETH_DMATXDESC_LASTSEGMENTS) || \ ((SEGMENT) == ETH_DMATXDESC_FIRSTSEGMENT)) #define IS_ETH_DMA_TXDESC_CHECKSUM(CHECKSUM) (((CHECKSUM) == ETH_DMATXDESC_CHECKSUMBYPASS) || \ ((CHECKSUM) == ETH_DMATXDESC_CHECKSUMIPV4HEADER) || \ ((CHECKSUM) == ETH_DMATXDESC_CHECKSUMTCPUDPICMPSEGMENT) || \ ((CHECKSUM) == ETH_DMATXDESC_CHECKSUMTCPUDPICMPFULL)) -#define IS_ETH_DMATXDESC_BUFFER_SIZE(SIZE) ((SIZE) <= 0x1FFFU) -#define IS_ETH_DMARXDESC_GET_FLAG(FLAG) (((FLAG) == ETH_DMARXDESC_OWN) || \ - ((FLAG) == ETH_DMARXDESC_AFM) || \ - ((FLAG) == ETH_DMARXDESC_ES) || \ - ((FLAG) == ETH_DMARXDESC_DE) || \ - ((FLAG) == ETH_DMARXDESC_SAF) || \ - ((FLAG) == ETH_DMARXDESC_LE) || \ - ((FLAG) == ETH_DMARXDESC_OE) || \ - ((FLAG) == ETH_DMARXDESC_VLAN) || \ - ((FLAG) == ETH_DMARXDESC_FS) || \ - ((FLAG) == ETH_DMARXDESC_LS) || \ - ((FLAG) == ETH_DMARXDESC_IPV4HCE) || \ - ((FLAG) == ETH_DMARXDESC_LC) || \ - ((FLAG) == ETH_DMARXDESC_FT) || \ - ((FLAG) == ETH_DMARXDESC_RWT) || \ - ((FLAG) == ETH_DMARXDESC_RE) || \ - ((FLAG) == ETH_DMARXDESC_DBE) || \ - ((FLAG) == ETH_DMARXDESC_CE) || \ - ((FLAG) == ETH_DMARXDESC_MAMPCE)) +#define IS_ETH_DMATXDESC_BUFFER_SIZE(SIZE) ((SIZE) <= 0x1FFF) + #define IS_ETH_DMA_RXDESC_BUFFER(BUFFER) (((BUFFER) == ETH_DMARXDESC_BUFFER1) || \ ((BUFFER) == ETH_DMARXDESC_BUFFER2)) -#define IS_ETH_PMT_GET_FLAG(FLAG) (((FLAG) == ETH_PMT_FLAG_WUFR) || \ - ((FLAG) == ETH_PMT_FLAG_MPR)) -#define IS_ETH_DMA_FLAG(FLAG) ((((FLAG) & 0xC7FE1800U) == 0x00U) && ((FLAG) != 0x00U)) -#define IS_ETH_DMA_GET_FLAG(FLAG) (((FLAG) == ETH_DMA_FLAG_TST) || ((FLAG) == ETH_DMA_FLAG_PMT) || \ - ((FLAG) == ETH_DMA_FLAG_MMC) || ((FLAG) == ETH_DMA_FLAG_DATATRANSFERERROR) || \ - ((FLAG) == ETH_DMA_FLAG_READWRITEERROR) || ((FLAG) == ETH_DMA_FLAG_ACCESSERROR) || \ - ((FLAG) == ETH_DMA_FLAG_NIS) || ((FLAG) == ETH_DMA_FLAG_AIS) || \ - ((FLAG) == ETH_DMA_FLAG_ER) || ((FLAG) == ETH_DMA_FLAG_FBE) || \ - ((FLAG) == ETH_DMA_FLAG_ET) || ((FLAG) == ETH_DMA_FLAG_RWT) || \ - ((FLAG) == ETH_DMA_FLAG_RPS) || ((FLAG) == ETH_DMA_FLAG_RBU) || \ - ((FLAG) == ETH_DMA_FLAG_R) || ((FLAG) == ETH_DMA_FLAG_TU) || \ - ((FLAG) == ETH_DMA_FLAG_RO) || ((FLAG) == ETH_DMA_FLAG_TJT) || \ - ((FLAG) == ETH_DMA_FLAG_TBU) || ((FLAG) == ETH_DMA_FLAG_TPS) || \ - ((FLAG) == ETH_DMA_FLAG_T)) -#define IS_ETH_MAC_IT(IT) ((((IT) & 0xFFFFFDF1U) == 0x00U) && ((IT) != 0x00U)) -#define IS_ETH_MAC_GET_IT(IT) (((IT) == ETH_MAC_IT_TST) || ((IT) == ETH_MAC_IT_MMCT) || \ - ((IT) == ETH_MAC_IT_MMCR) || ((IT) == ETH_MAC_IT_MMC) || \ - ((IT) == ETH_MAC_IT_PMT)) -#define IS_ETH_MAC_GET_FLAG(FLAG) (((FLAG) == ETH_MAC_FLAG_TST) || ((FLAG) == ETH_MAC_FLAG_MMCT) || \ - ((FLAG) == ETH_MAC_FLAG_MMCR) || ((FLAG) == ETH_MAC_FLAG_MMC) || \ - ((FLAG) == ETH_MAC_FLAG_PMT)) -#define IS_ETH_DMA_IT(IT) ((((IT) & 0xC7FE1800U) == 0x00U) && ((IT) != 0x00U)) -#define IS_ETH_DMA_GET_IT(IT) (((IT) == ETH_DMA_IT_TST) || ((IT) == ETH_DMA_IT_PMT) || \ - ((IT) == ETH_DMA_IT_MMC) || ((IT) == ETH_DMA_IT_NIS) || \ - ((IT) == ETH_DMA_IT_AIS) || ((IT) == ETH_DMA_IT_ER) || \ - ((IT) == ETH_DMA_IT_FBE) || ((IT) == ETH_DMA_IT_ET) || \ - ((IT) == ETH_DMA_IT_RWT) || ((IT) == ETH_DMA_IT_RPS) || \ - ((IT) == ETH_DMA_IT_RBU) || ((IT) == ETH_DMA_IT_R) || \ - ((IT) == ETH_DMA_IT_TU) || ((IT) == ETH_DMA_IT_RO) || \ - ((IT) == ETH_DMA_IT_TJT) || ((IT) == ETH_DMA_IT_TBU) || \ - ((IT) == ETH_DMA_IT_TPS) || ((IT) == ETH_DMA_IT_T)) + #define IS_ETH_DMA_GET_OVERFLOW(OVERFLOW) (((OVERFLOW) == ETH_DMA_OVERFLOW_RXFIFOCOUNTER) || \ ((OVERFLOW) == ETH_DMA_OVERFLOW_MISSEDFRAMECOUNTER)) -#define IS_ETH_MMC_IT(IT) (((((IT) & 0xFFDF3FFFU) == 0x00U) || (((IT) & 0xEFFDFF9FU) == 0x00U)) && \ - ((IT) != 0x00U)) -#define IS_ETH_MMC_GET_IT(IT) (((IT) == ETH_MMC_IT_TGF) || ((IT) == ETH_MMC_IT_TGFMSC) || \ - ((IT) == ETH_MMC_IT_TGFSC) || ((IT) == ETH_MMC_IT_RGUF) || \ - ((IT) == ETH_MMC_IT_RFAE) || ((IT) == ETH_MMC_IT_RFCE)) -#define IS_ETH_ENHANCED_DESCRIPTOR_FORMAT(CMD) (((CMD) == ETH_DMAENHANCEDDESCRIPTOR_ENABLE) || \ - ((CMD) == ETH_DMAENHANCEDDESCRIPTOR_DISABLE)) /** * @} */ -/** @addtogroup ETH_Private_Defines +/** @addtogroup ETH_Private_Constants * @{ */ /* Delay to wait when writing to some Ethernet registers */ -#define ETH_REG_WRITE_DELAY 0x00000001U +#define ETH_REG_WRITE_DELAY ((uint32_t)0x00000001) /* ETHERNET Errors */ -#define ETH_SUCCESS 0U -#define ETH_ERROR 1U +#define ETH_SUCCESS ((uint32_t)0) +#define ETH_ERROR ((uint32_t)1) /* ETHERNET DMA Tx descriptors Collision Count Shift */ -#define ETH_DMATXDESC_COLLISION_COUNTSHIFT 3U +#define ETH_DMATXDESC_COLLISION_COUNTSHIFT ((uint32_t)3) /* ETHERNET DMA Tx descriptors Buffer2 Size Shift */ -#define ETH_DMATXDESC_BUFFER2_SIZESHIFT 16U +#define ETH_DMATXDESC_BUFFER2_SIZESHIFT ((uint32_t)16) /* ETHERNET DMA Rx descriptors Frame Length Shift */ -#define ETH_DMARXDESC_FRAME_LENGTHSHIFT 16U +#define ETH_DMARXDESC_FRAME_LENGTHSHIFT ((uint32_t)16) /* ETHERNET DMA Rx descriptors Buffer2 Size Shift */ -#define ETH_DMARXDESC_BUFFER2_SIZESHIFT 16U +#define ETH_DMARXDESC_BUFFER2_SIZESHIFT ((uint32_t)16) /* ETHERNET DMA Rx descriptors Frame length Shift */ -#define ETH_DMARXDESC_FRAMELENGTHSHIFT 16U +#define ETH_DMARXDESC_FRAMELENGTHSHIFT ((uint32_t)16) /* ETHERNET MAC address offsets */ -#define ETH_MAC_ADDR_HBASE (uint32_t)(ETH_MAC_BASE + 0x40U) /* ETHERNET MAC address high offset */ -#define ETH_MAC_ADDR_LBASE (uint32_t)(ETH_MAC_BASE + 0x44U) /* ETHERNET MAC address low offset */ +#define ETH_MAC_ADDR_HBASE (uint32_t)(ETH_MAC_BASE + (uint32_t)0x40) /* ETHERNET MAC address high offset */ +#define ETH_MAC_ADDR_LBASE (uint32_t)(ETH_MAC_BASE + (uint32_t)0x44) /* ETHERNET MAC address low offset */ /* ETHERNET MACMIIAR register Mask */ -#define ETH_MACMIIAR_CR_MASK 0xFFFFFFE3U +#define ETH_MACMIIAR_CR_MASK ((uint32_t)0xFFFFFFE3) /* ETHERNET MACCR register Mask */ -#define ETH_MACCR_CLEAR_MASK 0xFF20810FU +#define ETH_MACCR_CLEAR_MASK ((uint32_t)0xFF20810F) /* ETHERNET MACFCR register Mask */ -#define ETH_MACFCR_CLEAR_MASK 0x0000FF41U +#define ETH_MACFCR_CLEAR_MASK ((uint32_t)0x0000FF41) /* ETHERNET DMAOMR register Mask */ -#define ETH_DMAOMR_CLEAR_MASK 0xF8DE3F23U +#define ETH_DMAOMR_CLEAR_MASK ((uint32_t)0xF8DE3F23) /* ETHERNET Remote Wake-up frame register length */ -#define ETH_WAKEUP_REGISTER_LENGTH 8U +#define ETH_WAKEUP_REGISTER_LENGTH 8 /* ETHERNET Missed frames counter Shift */ -#define ETH_DMA_RX_OVERFLOW_MISSEDFRAMES_COUNTERSHIFT 17U +#define ETH_DMA_RX_OVERFLOW_MISSEDFRAMES_COUNTERSHIFT 17 /** * @} - */ + */ /* Exported types ------------------------------------------------------------*/ /** @defgroup ETH_Exported_Types ETH Exported Types @@ -369,16 +292,16 @@ */ typedef enum { - HAL_ETH_STATE_RESET = 0x00U, /*!< Peripheral not yet Initialized or disabled */ - HAL_ETH_STATE_READY = 0x01U, /*!< Peripheral Initialized and ready for use */ - HAL_ETH_STATE_BUSY = 0x02U, /*!< an internal process is ongoing */ - HAL_ETH_STATE_BUSY_TX = 0x12U, /*!< Data Transmission process is ongoing */ - HAL_ETH_STATE_BUSY_RX = 0x22U, /*!< Data Reception process is ongoing */ - HAL_ETH_STATE_BUSY_TX_RX = 0x32U, /*!< Data Transmission and Reception process is ongoing */ - HAL_ETH_STATE_BUSY_WR = 0x42U, /*!< Write process is ongoing */ - HAL_ETH_STATE_BUSY_RD = 0x82U, /*!< Read process is ongoing */ - HAL_ETH_STATE_TIMEOUT = 0x03U, /*!< Timeout state */ - HAL_ETH_STATE_ERROR = 0x04U /*!< Reception process is ongoing */ + HAL_ETH_STATE_RESET = 0x00, /*!< Peripheral not yet Initialized or disabled */ + HAL_ETH_STATE_READY = 0x01, /*!< Peripheral Initialized and ready for use */ + HAL_ETH_STATE_BUSY = 0x02, /*!< an internal process is ongoing */ + HAL_ETH_STATE_BUSY_TX = 0x12, /*!< Data Transmission process is ongoing */ + HAL_ETH_STATE_BUSY_RX = 0x22, /*!< Data Reception process is ongoing */ + HAL_ETH_STATE_BUSY_TX_RX = 0x32, /*!< Data Transmission and Reception process is ongoing */ + HAL_ETH_STATE_BUSY_WR = 0x42, /*!< Write process is ongoing */ + HAL_ETH_STATE_BUSY_RD = 0x82, /*!< Read process is ongoing */ + HAL_ETH_STATE_TIMEOUT = 0x03, /*!< Timeout state */ + HAL_ETH_STATE_ERROR = 0x04 /*!< Reception process is ongoing */ }HAL_ETH_StateTypeDef; /** @@ -409,7 +332,7 @@ typedef struct uint32_t ChecksumMode; /*!< Selects if the checksum is check by hardware or by software. This parameter can be a value of @ref ETH_Checksum_Mode */ - uint32_t MediaInterface; /*!< Selects the media-independent interface or the reduced media-independent interface. + uint32_t MediaInterface ; /*!< Selects the media-independent interface or the reduced media-independent interface. This parameter can be a value of @ref ETH_Media_Interface */ } ETH_InitTypeDef; @@ -464,10 +387,10 @@ typedef struct uint32_t ReceiveAll; /*!< Selects or not all frames reception by the MAC (No filtering). This parameter can be a value of @ref ETH_Receive_All */ - uint32_t SourceAddrFilter; /*!< Selects the Source Address Filter mode. - This parameter can be a value of @ref ETH_Source_Addr_Filter */ + uint32_t SourceAddrFilter; /*!< Selects the Source Address Filter mode. + This parameter can be a value of @ref ETH_Source_Addr_Filter */ - uint32_t PassControlFrames; /*!< Sets the forwarding mode of the control frames (including unicast and multicast PAUSE frames) + uint32_t PassControlFrames; /*!< Sets the forwarding mode of the control frames (including unicast and multicast PAUSE frames) This parameter can be a value of @ref ETH_Pass_Control_Frames */ uint32_t BroadcastFramesReception; /*!< Selects or not the reception of Broadcast Frames. @@ -486,13 +409,13 @@ typedef struct This parameter can be a value of @ref ETH_Unicast_Frames_Filter */ uint32_t HashTableHigh; /*!< This field holds the higher 32 bits of Hash table. - This parameter must be a number between Min_Data = 0x0 and Max_Data = 0xFFFFFFFFU */ + This parameter must be a number between Min_Data = 0x0 and Max_Data = 0xFFFFFFFF */ uint32_t HashTableLow; /*!< This field holds the lower 32 bits of Hash table. - This parameter must be a number between Min_Data = 0x0 and Max_Data = 0xFFFFFFFFU */ + This parameter must be a number between Min_Data = 0x0 and Max_Data = 0xFFFFFFFF */ uint32_t PauseTime; /*!< This field holds the value to be used in the Pause Time field in the transmit control frame. - This parameter must be a number between Min_Data = 0x0 and Max_Data = 0xFFFFU */ + This parameter must be a number between Min_Data = 0x0 and Max_Data = 0xFFFF */ uint32_t ZeroQuantaPause; /*!< Selects or not the automatic generation of Zero-Quanta Pause Control frames. This parameter can be a value of @ref ETH_Zero_Quanta_Pause */ @@ -500,7 +423,7 @@ typedef struct uint32_t PauseLowThreshold; /*!< This field configures the threshold of the PAUSE to be checked for automatic retransmission of PAUSE Frame. This parameter can be a value of @ref ETH_Pause_Low_Threshold */ - + uint32_t UnicastPauseFrameDetect; /*!< Selects or not the MAC detection of the Pause frames (with MAC Address0 unicast address and unique multicast address). This parameter can be a value of @ref ETH_Unicast_Pause_Frame_Detect */ @@ -521,6 +444,7 @@ typedef struct } ETH_MACInitTypeDef; + /** * @brief ETH DMA Configuration Structure definition */ @@ -561,7 +485,7 @@ typedef struct uint32_t FixedBurst; /*!< Enables or disables the AHB Master interface fixed burst transfers. This parameter can be a value of @ref ETH_Fixed_Burst */ - + uint32_t RxDMABurstLength; /*!< Indicates the maximum number of beats to be transferred in one Rx DMA transaction. This parameter can be a value of @ref ETH_Rx_DMA_Burst_Length */ @@ -569,7 +493,7 @@ typedef struct This parameter can be a value of @ref ETH_Tx_DMA_Burst_Length */ uint32_t DescriptorSkipLength; /*!< Specifies the number of word to skip between two unchained descriptors (Ring mode) - This parameter must be a number between Min_Data = 0 and Max_Data = 32 */ + This parameter must be a number between Min_Data = 0 and Max_Data = 32 */ uint32_t DMAArbitration; /*!< Selects the DMA Tx/Rx arbitration. This parameter can be a value of @ref ETH_DMA_Arbitration */ @@ -592,6 +516,7 @@ typedef struct } ETH_DMADescTypeDef; + /** * @brief Received Frame Informations structure definition */ @@ -609,6 +534,7 @@ typedef struct } ETH_DMARxFrameInfos; + /** * @brief ETH Handle Structure definition */ @@ -645,14 +571,14 @@ typedef struct /** @defgroup ETH_Buffers_setting ETH Buffers setting * @{ */ -#define ETH_MAX_PACKET_SIZE 1524U /*!< ETH_HEADER + ETH_EXTRA + ETH_VLAN_TAG + ETH_MAX_ETH_PAYLOAD + ETH_CRC */ -#define ETH_HEADER 14U /*!< 6 byte Dest addr, 6 byte Src addr, 2 byte length/type */ -#define ETH_CRC 4U /*!< Ethernet CRC */ -#define ETH_EXTRA 2U /*!< Extra bytes in some cases */ -#define ETH_VLAN_TAG 4U /*!< optional 802.1q VLAN Tag */ -#define ETH_MIN_ETH_PAYLOAD 46U /*!< Minimum Ethernet payload size */ -#define ETH_MAX_ETH_PAYLOAD 1500U /*!< Maximum Ethernet payload size */ -#define ETH_JUMBO_FRAME_PAYLOAD 9000U /*!< Jumbo frame payload size */ +#define ETH_MAX_PACKET_SIZE ((uint32_t)1524) /*!< ETH_HEADER + ETH_EXTRA + ETH_VLAN_TAG + ETH_MAX_ETH_PAYLOAD + ETH_CRC */ +#define ETH_HEADER ((uint32_t)14) /*!< 6 byte Dest addr, 6 byte Src addr, 2 byte length/type */ +#define ETH_CRC ((uint32_t)4) /*!< Ethernet CRC */ +#define ETH_EXTRA ((uint32_t)2) /*!< Extra bytes in some cases */ +#define ETH_VLAN_TAG ((uint32_t)4) /*!< optional 802.1q VLAN Tag */ +#define ETH_MIN_ETH_PAYLOAD ((uint32_t)46) /*!< Minimum Ethernet payload size */ +#define ETH_MAX_ETH_PAYLOAD ((uint32_t)1500) /*!< Maximum Ethernet payload size */ +#define ETH_JUMBO_FRAME_PAYLOAD ((uint32_t)9000) /*!< Jumbo frame payload size */ /* Ethernet driver receive buffers are organized in a chained linked-list, when an ethernet packet is received, the Rx-DMA will transfer the packet from RxFIFO @@ -677,7 +603,7 @@ typedef struct /* 5 Ethernet driver receive buffers are used (in a chained linked list)*/ #ifndef ETH_RXBUFNB - #define ETH_RXBUFNB 5U /* 5 Rx buffers of size ETH_RX_BUF_SIZE */ + #define ETH_RXBUFNB ((uint32_t)5 /* 5 Rx buffers of size ETH_RX_BUF_SIZE */ #endif @@ -704,7 +630,7 @@ typedef struct /* 5 ethernet driver transmit buffers are used (in a chained linked list)*/ #ifndef ETH_TXBUFNB - #define ETH_TXBUFNB 5U /* 5 Tx buffers of size ETH_TX_BUF_SIZE */ + #define ETH_TXBUFNB ((uint32_t)5 /* 5 Tx buffers of size ETH_TX_BUF_SIZE */ #endif /** @@ -716,7 +642,7 @@ typedef struct */ /* - DMA Tx Descriptor + DMA Tx Desciptor ----------------------------------------------------------------------------------------------- TDES0 | OWN(31) | CTRL[30:26] | Reserved[25:24] | CTRL[23:20] | Reserved[19:17] | Status[16:0] | ----------------------------------------------------------------------------------------------- @@ -731,56 +657,56 @@ typedef struct /** * @brief Bit definition of TDES0 register: DMA Tx descriptor status register */ -#define ETH_DMATXDESC_OWN 0x80000000U /*!< OWN bit: descriptor is owned by DMA engine */ -#define ETH_DMATXDESC_IC 0x40000000U /*!< Interrupt on Completion */ -#define ETH_DMATXDESC_LS 0x20000000U /*!< Last Segment */ -#define ETH_DMATXDESC_FS 0x10000000U /*!< First Segment */ -#define ETH_DMATXDESC_DC 0x08000000U /*!< Disable CRC */ -#define ETH_DMATXDESC_DP 0x04000000U /*!< Disable Padding */ -#define ETH_DMATXDESC_TTSE 0x02000000U /*!< Transmit Time Stamp Enable */ -#define ETH_DMATXDESC_CIC 0x00C00000U /*!< Checksum Insertion Control: 4 cases */ -#define ETH_DMATXDESC_CIC_BYPASS 0x00000000U /*!< Do Nothing: Checksum Engine is bypassed */ -#define ETH_DMATXDESC_CIC_IPV4HEADER 0x00400000U /*!< IPV4 header Checksum Insertion */ -#define ETH_DMATXDESC_CIC_TCPUDPICMP_SEGMENT 0x00800000U /*!< TCP/UDP/ICMP Checksum Insertion calculated over segment only */ -#define ETH_DMATXDESC_CIC_TCPUDPICMP_FULL 0x00C00000U /*!< TCP/UDP/ICMP Checksum Insertion fully calculated */ -#define ETH_DMATXDESC_TER 0x00200000U /*!< Transmit End of Ring */ -#define ETH_DMATXDESC_TCH 0x00100000U /*!< Second Address Chained */ -#define ETH_DMATXDESC_TTSS 0x00020000U /*!< Tx Time Stamp Status */ -#define ETH_DMATXDESC_IHE 0x00010000U /*!< IP Header Error */ -#define ETH_DMATXDESC_ES 0x00008000U /*!< Error summary: OR of the following bits: UE || ED || EC || LCO || NC || LCA || FF || JT */ -#define ETH_DMATXDESC_JT 0x00004000U /*!< Jabber Timeout */ -#define ETH_DMATXDESC_FF 0x00002000U /*!< Frame Flushed: DMA/MTL flushed the frame due to SW flush */ -#define ETH_DMATXDESC_PCE 0x00001000U /*!< Payload Checksum Error */ -#define ETH_DMATXDESC_LCA 0x00000800U /*!< Loss of Carrier: carrier lost during transmission */ -#define ETH_DMATXDESC_NC 0x00000400U /*!< No Carrier: no carrier signal from the transceiver */ -#define ETH_DMATXDESC_LCO 0x00000200U /*!< Late Collision: transmission aborted due to collision */ -#define ETH_DMATXDESC_EC 0x00000100U /*!< Excessive Collision: transmission aborted after 16 collisions */ -#define ETH_DMATXDESC_VF 0x00000080U /*!< VLAN Frame */ -#define ETH_DMATXDESC_CC 0x00000078U /*!< Collision Count */ -#define ETH_DMATXDESC_ED 0x00000004U /*!< Excessive Deferral */ -#define ETH_DMATXDESC_UF 0x00000002U /*!< Underflow Error: late data arrival from the memory */ -#define ETH_DMATXDESC_DB 0x00000001U /*!< Deferred Bit */ +#define ETH_DMATXDESC_OWN ((uint32_t)0x80000000) /*!< OWN bit: descriptor is owned by DMA engine */ +#define ETH_DMATXDESC_IC ((uint32_t)0x40000000) /*!< Interrupt on Completion */ +#define ETH_DMATXDESC_LS ((uint32_t)0x20000000) /*!< Last Segment */ +#define ETH_DMATXDESC_FS ((uint32_t)0x10000000) /*!< First Segment */ +#define ETH_DMATXDESC_DC ((uint32_t)0x08000000) /*!< Disable CRC */ +#define ETH_DMATXDESC_DP ((uint32_t)0x04000000) /*!< Disable Padding */ +#define ETH_DMATXDESC_TTSE ((uint32_t)0x02000000) /*!< Transmit Time Stamp Enable */ +#define ETH_DMATXDESC_CIC ((uint32_t)0x00C00000) /*!< Checksum Insertion Control: 4 cases */ +#define ETH_DMATXDESC_CIC_BYPASS ((uint32_t)0x00000000) /*!< Do Nothing: Checksum Engine is bypassed */ +#define ETH_DMATXDESC_CIC_IPV4HEADER ((uint32_t)0x00400000) /*!< IPV4 header Checksum Insertion */ +#define ETH_DMATXDESC_CIC_TCPUDPICMP_SEGMENT ((uint32_t)0x00800000) /*!< TCP/UDP/ICMP Checksum Insertion calculated over segment only */ +#define ETH_DMATXDESC_CIC_TCPUDPICMP_FULL ((uint32_t)0x00C00000) /*!< TCP/UDP/ICMP Checksum Insertion fully calculated */ +#define ETH_DMATXDESC_TER ((uint32_t)0x00200000) /*!< Transmit End of Ring */ +#define ETH_DMATXDESC_TCH ((uint32_t)0x00100000) /*!< Second Address Chained */ +#define ETH_DMATXDESC_TTSS ((uint32_t)0x00020000) /*!< Tx Time Stamp Status */ +#define ETH_DMATXDESC_IHE ((uint32_t)0x00010000) /*!< IP Header Error */ +#define ETH_DMATXDESC_ES ((uint32_t)0x00008000) /*!< Error summary: OR of the following bits: UE || ED || EC || LCO || NC || LCA || FF || JT */ +#define ETH_DMATXDESC_JT ((uint32_t)0x00004000) /*!< Jabber Timeout */ +#define ETH_DMATXDESC_FF ((uint32_t)0x00002000) /*!< Frame Flushed: DMA/MTL flushed the frame due to SW flush */ +#define ETH_DMATXDESC_PCE ((uint32_t)0x00001000) /*!< Payload Checksum Error */ +#define ETH_DMATXDESC_LCA ((uint32_t)0x00000800) /*!< Loss of Carrier: carrier lost during transmission */ +#define ETH_DMATXDESC_NC ((uint32_t)0x00000400) /*!< No Carrier: no carrier signal from the transceiver */ +#define ETH_DMATXDESC_LCO ((uint32_t)0x00000200) /*!< Late Collision: transmission aborted due to collision */ +#define ETH_DMATXDESC_EC ((uint32_t)0x00000100) /*!< Excessive Collision: transmission aborted after 16 collisions */ +#define ETH_DMATXDESC_VF ((uint32_t)0x00000080) /*!< VLAN Frame */ +#define ETH_DMATXDESC_CC ((uint32_t)0x00000078) /*!< Collision Count */ +#define ETH_DMATXDESC_ED ((uint32_t)0x00000004) /*!< Excessive Deferral */ +#define ETH_DMATXDESC_UF ((uint32_t)0x00000002) /*!< Underflow Error: late data arrival from the memory */ +#define ETH_DMATXDESC_DB ((uint32_t)0x00000001) /*!< Deferred Bit */ /** * @brief Bit definition of TDES1 register */ -#define ETH_DMATXDESC_TBS2 0x1FFF0000U /*!< Transmit Buffer2 Size */ -#define ETH_DMATXDESC_TBS1 0x00001FFFU /*!< Transmit Buffer1 Size */ +#define ETH_DMATXDESC_TBS2 ((uint32_t)0x1FFF0000) /*!< Transmit Buffer2 Size */ +#define ETH_DMATXDESC_TBS1 ((uint32_t)0x00001FFF) /*!< Transmit Buffer1 Size */ /** * @brief Bit definition of TDES2 register */ -#define ETH_DMATXDESC_B1AP 0xFFFFFFFFU /*!< Buffer1 Address Pointer */ +#define ETH_DMATXDESC_B1AP ((uint32_t)0xFFFFFFFF) /*!< Buffer1 Address Pointer */ /** * @brief Bit definition of TDES3 register */ -#define ETH_DMATXDESC_B2AP 0xFFFFFFFFU /*!< Buffer2 Address Pointer */ +#define ETH_DMATXDESC_B2AP ((uint32_t)0xFFFFFFFF) /*!< Buffer2 Address Pointer */ /** * @} */ -/** @defgroup ETH_DMA_RX_Descriptor ETH DMA RX Descriptor +/** @defgroup ETH_DMA_RX_Descriptor ETH DMA RX Descriptor * @{ */ @@ -800,44 +726,44 @@ typedef struct /** * @brief Bit definition of RDES0 register: DMA Rx descriptor status register */ -#define ETH_DMARXDESC_OWN 0x80000000U /*!< OWN bit: descriptor is owned by DMA engine */ -#define ETH_DMARXDESC_AFM 0x40000000U /*!< DA Filter Fail for the rx frame */ -#define ETH_DMARXDESC_FL 0x3FFF0000U /*!< Receive descriptor frame length */ -#define ETH_DMARXDESC_ES 0x00008000U /*!< Error summary: OR of the following bits: DE || OE || IPC || LC || RWT || RE || CE */ -#define ETH_DMARXDESC_DE 0x00004000U /*!< Descriptor error: no more descriptors for receive frame */ -#define ETH_DMARXDESC_SAF 0x00002000U /*!< SA Filter Fail for the received frame */ -#define ETH_DMARXDESC_LE 0x00001000U /*!< Frame size not matching with length field */ -#define ETH_DMARXDESC_OE 0x00000800U /*!< Overflow Error: Frame was damaged due to buffer overflow */ -#define ETH_DMARXDESC_VLAN 0x00000400U /*!< VLAN Tag: received frame is a VLAN frame */ -#define ETH_DMARXDESC_FS 0x00000200U /*!< First descriptor of the frame */ -#define ETH_DMARXDESC_LS 0x00000100U /*!< Last descriptor of the frame */ -#define ETH_DMARXDESC_IPV4HCE 0x00000080U /*!< IPC Checksum Error: Rx Ipv4 header checksum error */ -#define ETH_DMARXDESC_LC 0x00000040U /*!< Late collision occurred during reception */ -#define ETH_DMARXDESC_FT 0x00000020U /*!< Frame type - Ethernet, otherwise 802.3 */ -#define ETH_DMARXDESC_RWT 0x00000010U /*!< Receive Watchdog Timeout: watchdog timer expired during reception */ -#define ETH_DMARXDESC_RE 0x00000008U /*!< Receive error: error reported by MII interface */ -#define ETH_DMARXDESC_DBE 0x00000004U /*!< Dribble bit error: frame contains non int multiple of 8 bits */ -#define ETH_DMARXDESC_CE 0x00000002U /*!< CRC error */ -#define ETH_DMARXDESC_MAMPCE 0x00000001U /*!< Rx MAC Address/Payload Checksum Error: Rx MAC address matched/ Rx Payload Checksum Error */ +#define ETH_DMARXDESC_OWN ((uint32_t)0x80000000) /*!< OWN bit: descriptor is owned by DMA engine */ +#define ETH_DMARXDESC_AFM ((uint32_t)0x40000000) /*!< DA Filter Fail for the rx frame */ +#define ETH_DMARXDESC_FL ((uint32_t)0x3FFF0000) /*!< Receive descriptor frame length */ +#define ETH_DMARXDESC_ES ((uint32_t)0x00008000) /*!< Error summary: OR of the following bits: DE || OE || IPC || LC || RWT || RE || CE */ +#define ETH_DMARXDESC_DE ((uint32_t)0x00004000) /*!< Descriptor error: no more descriptors for receive frame */ +#define ETH_DMARXDESC_SAF ((uint32_t)0x00002000) /*!< SA Filter Fail for the received frame */ +#define ETH_DMARXDESC_LE ((uint32_t)0x00001000) /*!< Frame size not matching with length field */ +#define ETH_DMARXDESC_OE ((uint32_t)0x00000800) /*!< Overflow Error: Frame was damaged due to buffer overflow */ +#define ETH_DMARXDESC_VLAN ((uint32_t)0x00000400) /*!< VLAN Tag: received frame is a VLAN frame */ +#define ETH_DMARXDESC_FS ((uint32_t)0x00000200) /*!< First descriptor of the frame */ +#define ETH_DMARXDESC_LS ((uint32_t)0x00000100) /*!< Last descriptor of the frame */ +#define ETH_DMARXDESC_IPV4HCE ((uint32_t)0x00000080) /*!< IPC Checksum Error: Rx Ipv4 header checksum error */ +#define ETH_DMARXDESC_LC ((uint32_t)0x00000040) /*!< Late collision occurred during reception */ +#define ETH_DMARXDESC_FT ((uint32_t)0x00000020) /*!< Frame type - Ethernet, otherwise 802.3 */ +#define ETH_DMARXDESC_RWT ((uint32_t)0x00000010) /*!< Receive Watchdog Timeout: watchdog timer expired during reception */ +#define ETH_DMARXDESC_RE ((uint32_t)0x00000008) /*!< Receive error: error reported by MII interface */ +#define ETH_DMARXDESC_DBE ((uint32_t)0x00000004) /*!< Dribble bit error: frame contains non int multiple of 8 bits */ +#define ETH_DMARXDESC_CE ((uint32_t)0x00000002) /*!< CRC error */ +#define ETH_DMARXDESC_MAMPCE ((uint32_t)0x00000001) /*!< Rx MAC Address/Payload Checksum Error: Rx MAC address matched/ Rx Payload Checksum Error */ /** * @brief Bit definition of RDES1 register */ -#define ETH_DMARXDESC_DIC 0x80000000U /*!< Disable Interrupt on Completion */ -#define ETH_DMARXDESC_RBS2 0x1FFF0000U /*!< Receive Buffer2 Size */ -#define ETH_DMARXDESC_RER 0x00008000U /*!< Receive End of Ring */ -#define ETH_DMARXDESC_RCH 0x00004000U /*!< Second Address Chained */ -#define ETH_DMARXDESC_RBS1 0x00001FFFU /*!< Receive Buffer1 Size */ +#define ETH_DMARXDESC_DIC ((uint32_t)0x80000000) /*!< Disable Interrupt on Completion */ +#define ETH_DMARXDESC_RBS2 ((uint32_t)0x1FFF0000) /*!< Receive Buffer2 Size */ +#define ETH_DMARXDESC_RER ((uint32_t)0x00008000) /*!< Receive End of Ring */ +#define ETH_DMARXDESC_RCH ((uint32_t)0x00004000) /*!< Second Address Chained */ +#define ETH_DMARXDESC_RBS1 ((uint32_t)0x00001FFF) /*!< Receive Buffer1 Size */ /** * @brief Bit definition of RDES2 register */ -#define ETH_DMARXDESC_B1AP 0xFFFFFFFFU /*!< Buffer1 Address Pointer */ +#define ETH_DMARXDESC_B1AP ((uint32_t)0xFFFFFFFF) /*!< Buffer1 Address Pointer */ /** * @brief Bit definition of RDES3 register */ -#define ETH_DMARXDESC_B2AP 0xFFFFFFFFU /*!< Buffer2 Address Pointer */ +#define ETH_DMARXDESC_B2AP ((uint32_t)0xFFFFFFFF) /*!< Buffer2 Address Pointer */ /** * @} @@ -845,8 +771,8 @@ typedef struct /** @defgroup ETH_AutoNegotiation ETH AutoNegotiation * @{ */ -#define ETH_AUTONEGOTIATION_ENABLE 0x00000001U -#define ETH_AUTONEGOTIATION_DISABLE 0x00000000U +#define ETH_AUTONEGOTIATION_ENABLE ((uint32_t)0x00000001) +#define ETH_AUTONEGOTIATION_DISABLE ((uint32_t)0x00000000) /** * @} @@ -854,25 +780,25 @@ typedef struct /** @defgroup ETH_Speed ETH Speed * @{ */ -#define ETH_SPEED_10M 0x00000000U -#define ETH_SPEED_100M 0x00004000U +#define ETH_SPEED_10M ((uint32_t)0x00000000) +#define ETH_SPEED_100M ((uint32_t)0x00004000) /** * @} */ -/** @defgroup ETH_Duplex_Mode ETH Duplex Mode +/** @defgroup ETH_Duplex_Mode ETH Duplex Mode * @{ */ -#define ETH_MODE_FULLDUPLEX 0x00000800U -#define ETH_MODE_HALFDUPLEX 0x00000000U +#define ETH_MODE_FULLDUPLEX ((uint32_t)0x00000800) +#define ETH_MODE_HALFDUPLEX ((uint32_t)0x00000000) /** * @} */ -/** @defgroup ETH_Rx_Mode ETH Rx Mode +/** @defgroup ETH_Rx_Mode ETH Rx Mode * @{ */ -#define ETH_RXPOLLING_MODE 0x00000000U -#define ETH_RXINTERRUPT_MODE 0x00000001U +#define ETH_RXPOLLING_MODE ((uint32_t)0x00000000) +#define ETH_RXINTERRUPT_MODE ((uint32_t)0x00000001) /** * @} */ @@ -880,8 +806,8 @@ typedef struct /** @defgroup ETH_Checksum_Mode ETH Checksum Mode * @{ */ -#define ETH_CHECKSUM_BY_HARDWARE 0x00000000U -#define ETH_CHECKSUM_BY_SOFTWARE 0x00000001U +#define ETH_CHECKSUM_BY_HARDWARE ((uint32_t)0x00000000) +#define ETH_CHECKSUM_BY_SOFTWARE ((uint32_t)0x00000001) /** * @} */ @@ -889,7 +815,7 @@ typedef struct /** @defgroup ETH_Media_Interface ETH Media Interface * @{ */ -#define ETH_MEDIA_INTERFACE_MII 0x00000000U +#define ETH_MEDIA_INTERFACE_MII ((uint32_t)0x00000000) #define ETH_MEDIA_INTERFACE_RMII ((uint32_t)AFIO_MAPR_MII_RMII_SEL) /** @@ -899,17 +825,19 @@ typedef struct /** @defgroup ETH_Watchdog ETH Watchdog * @{ */ -#define ETH_WATCHDOG_ENABLE 0x00000000U -#define ETH_WATCHDOG_DISABLE 0x00800000U +#define ETH_WATCHDOG_ENABLE ((uint32_t)0x00000000) +#define ETH_WATCHDOG_DISABLE ((uint32_t)0x00800000) + /** * @} */ -/** @defgroup ETH_Jabber ETH Jabber +/** @defgroup ETH_Jabber ETH Jabber * @{ */ -#define ETH_JABBER_ENABLE 0x00000000U -#define ETH_JABBER_DISABLE 0x00400000U +#define ETH_JABBER_ENABLE ((uint32_t)0x00000000) +#define ETH_JABBER_DISABLE ((uint32_t)0x00400000) + /** * @} */ @@ -917,14 +845,15 @@ typedef struct /** @defgroup ETH_Inter_Frame_Gap ETH Inter Frame Gap * @{ */ -#define ETH_INTERFRAMEGAP_96BIT 0x00000000U /*!< minimum IFG between frames during transmission is 96Bit */ -#define ETH_INTERFRAMEGAP_88BIT 0x00020000U /*!< minimum IFG between frames during transmission is 88Bit */ -#define ETH_INTERFRAMEGAP_80BIT 0x00040000U /*!< minimum IFG between frames during transmission is 80Bit */ -#define ETH_INTERFRAMEGAP_72BIT 0x00060000U /*!< minimum IFG between frames during transmission is 72Bit */ -#define ETH_INTERFRAMEGAP_64BIT 0x00080000U /*!< minimum IFG between frames during transmission is 64Bit */ -#define ETH_INTERFRAMEGAP_56BIT 0x000A0000U /*!< minimum IFG between frames during transmission is 56Bit */ -#define ETH_INTERFRAMEGAP_48BIT 0x000C0000U /*!< minimum IFG between frames during transmission is 48Bit */ -#define ETH_INTERFRAMEGAP_40BIT 0x000E0000U /*!< minimum IFG between frames during transmission is 40Bit */ +#define ETH_INTERFRAMEGAP_96BIT ((uint32_t)0x00000000) /*!< minimum IFG between frames during transmission is 96Bit */ +#define ETH_INTERFRAMEGAP_88BIT ((uint32_t)0x00020000) /*!< minimum IFG between frames during transmission is 88Bit */ +#define ETH_INTERFRAMEGAP_80BIT ((uint32_t)0x00040000) /*!< minimum IFG between frames during transmission is 80Bit */ +#define ETH_INTERFRAMEGAP_72BIT ((uint32_t)0x00060000) /*!< minimum IFG between frames during transmission is 72Bit */ +#define ETH_INTERFRAMEGAP_64BIT ((uint32_t)0x00080000) /*!< minimum IFG between frames during transmission is 64Bit */ +#define ETH_INTERFRAMEGAP_56BIT ((uint32_t)0x000A0000) /*!< minimum IFG between frames during transmission is 56Bit */ +#define ETH_INTERFRAMEGAP_48BIT ((uint32_t)0x000C0000) /*!< minimum IFG between frames during transmission is 48Bit */ +#define ETH_INTERFRAMEGAP_40BIT ((uint32_t)0x000E0000) /*!< minimum IFG between frames during transmission is 40Bit */ + /** * @} */ @@ -932,8 +861,9 @@ typedef struct /** @defgroup ETH_Carrier_Sense ETH Carrier Sense * @{ */ -#define ETH_CARRIERSENCE_ENABLE 0x00000000U -#define ETH_CARRIERSENCE_DISABLE 0x00010000U +#define ETH_CARRIERSENCE_ENABLE ((uint32_t)0x00000000) +#define ETH_CARRIERSENCE_DISABLE ((uint32_t)0x00010000) + /** * @} */ @@ -941,17 +871,19 @@ typedef struct /** @defgroup ETH_Receive_Own ETH Receive Own * @{ */ -#define ETH_RECEIVEOWN_ENABLE 0x00000000U -#define ETH_RECEIVEOWN_DISABLE 0x00002000U +#define ETH_RECEIVEOWN_ENABLE ((uint32_t)0x00000000) +#define ETH_RECEIVEOWN_DISABLE ((uint32_t)0x00002000) + /** * @} */ -/** @defgroup ETH_Loop_Back_Mode ETH Loop Back Mode +/** @defgroup ETH_Loop_Back_Mode ETH Loop Back Mode * @{ */ -#define ETH_LOOPBACKMODE_ENABLE 0x00001000U -#define ETH_LOOPBACKMODE_DISABLE 0x00000000U +#define ETH_LOOPBACKMODE_ENABLE ((uint32_t)0x00001000) +#define ETH_LOOPBACKMODE_DISABLE ((uint32_t)0x00000000) + /** * @} */ @@ -959,8 +891,9 @@ typedef struct /** @defgroup ETH_Checksum_Offload ETH Checksum Offload * @{ */ -#define ETH_CHECKSUMOFFLAOD_ENABLE 0x00000400U -#define ETH_CHECKSUMOFFLAOD_DISABLE 0x00000000U +#define ETH_CHECKSUMOFFLAOD_ENABLE ((uint32_t)0x00000400) +#define ETH_CHECKSUMOFFLAOD_DISABLE ((uint32_t)0x00000000) + /** * @} */ @@ -968,8 +901,9 @@ typedef struct /** @defgroup ETH_Retry_Transmission ETH Retry Transmission * @{ */ -#define ETH_RETRYTRANSMISSION_ENABLE 0x00000000U -#define ETH_RETRYTRANSMISSION_DISABLE 0x00000200U +#define ETH_RETRYTRANSMISSION_ENABLE ((uint32_t)0x00000000) +#define ETH_RETRYTRANSMISSION_DISABLE ((uint32_t)0x00000200) + /** * @} */ @@ -977,8 +911,9 @@ typedef struct /** @defgroup ETH_Automatic_Pad_CRC_Strip ETH Automatic Pad CRC Strip * @{ */ -#define ETH_AUTOMATICPADCRCSTRIP_ENABLE 0x00000080U -#define ETH_AUTOMATICPADCRCSTRIP_DISABLE 0x00000000U +#define ETH_AUTOMATICPADCRCSTRIP_ENABLE ((uint32_t)0x00000080) +#define ETH_AUTOMATICPADCRCSTRIP_DISABLE ((uint32_t)0x00000000) + /** * @} */ @@ -986,10 +921,11 @@ typedef struct /** @defgroup ETH_Back_Off_Limit ETH Back Off Limit * @{ */ -#define ETH_BACKOFFLIMIT_10 0x00000000U -#define ETH_BACKOFFLIMIT_8 0x00000020U -#define ETH_BACKOFFLIMIT_4 0x00000040U -#define ETH_BACKOFFLIMIT_1 0x00000060U +#define ETH_BACKOFFLIMIT_10 ((uint32_t)0x00000000) +#define ETH_BACKOFFLIMIT_8 ((uint32_t)0x00000020) +#define ETH_BACKOFFLIMIT_4 ((uint32_t)0x00000040) +#define ETH_BACKOFFLIMIT_1 ((uint32_t)0x00000060) + /** * @} */ @@ -997,8 +933,9 @@ typedef struct /** @defgroup ETH_Deferral_Check ETH Deferral Check * @{ */ -#define ETH_DEFFERRALCHECK_ENABLE 0x00000010U -#define ETH_DEFFERRALCHECK_DISABLE 0x00000000U +#define ETH_DEFFERRALCHECK_ENABLE ((uint32_t)0x00000010) +#define ETH_DEFFERRALCHECK_DISABLE ((uint32_t)0x00000000) + /** * @} */ @@ -1006,8 +943,9 @@ typedef struct /** @defgroup ETH_Receive_All ETH Receive All * @{ */ -#define ETH_RECEIVEALL_ENABLE 0x80000000U -#define ETH_RECEIVEAll_DISABLE 0x00000000U +#define ETH_RECEIVEALL_ENABLE ((uint32_t)0x80000000) +#define ETH_RECEIVEAll_DISABLE ((uint32_t)0x00000000) + /** * @} */ @@ -1015,9 +953,10 @@ typedef struct /** @defgroup ETH_Source_Addr_Filter ETH Source Addr Filter * @{ */ -#define ETH_SOURCEADDRFILTER_NORMAL_ENABLE 0x00000200U -#define ETH_SOURCEADDRFILTER_INVERSE_ENABLE 0x00000300U -#define ETH_SOURCEADDRFILTER_DISABLE 0x00000000U +#define ETH_SOURCEADDRFILTER_NORMAL_ENABLE ((uint32_t)0x00000200) +#define ETH_SOURCEADDRFILTER_INVERSE_ENABLE ((uint32_t)0x00000300) +#define ETH_SOURCEADDRFILTER_DISABLE ((uint32_t)0x00000000) + /** * @} */ @@ -1025,9 +964,10 @@ typedef struct /** @defgroup ETH_Pass_Control_Frames ETH Pass Control Frames * @{ */ -#define ETH_PASSCONTROLFRAMES_BLOCKALL 0x00000040U /*!< MAC filters all control frames from reaching the application */ -#define ETH_PASSCONTROLFRAMES_FORWARDALL 0x00000080U /*!< MAC forwards all control frames to application even if they fail the Address Filter */ -#define ETH_PASSCONTROLFRAMES_FORWARDPASSEDADDRFILTER 0x000000C0U /*!< MAC forwards control frames that pass the Address Filter. */ +#define ETH_PASSCONTROLFRAMES_BLOCKALL ((uint32_t)0x00000040) /*!< MAC filters all control frames from reaching the application */ +#define ETH_PASSCONTROLFRAMES_FORWARDALL ((uint32_t)0x00000080) /*!< MAC forwards all control frames to application even if they fail the Address Filter */ +#define ETH_PASSCONTROLFRAMES_FORWARDPASSEDADDRFILTER ((uint32_t)0x000000C0) /*!< MAC forwards control frames that pass the Address Filter. */ + /** * @} */ @@ -1035,8 +975,9 @@ typedef struct /** @defgroup ETH_Broadcast_Frames_Reception ETH Broadcast Frames Reception * @{ */ -#define ETH_BROADCASTFRAMESRECEPTION_ENABLE 0x00000000U -#define ETH_BROADCASTFRAMESRECEPTION_DISABLE 0x00000020U +#define ETH_BROADCASTFRAMESRECEPTION_ENABLE ((uint32_t)0x00000000) +#define ETH_BROADCASTFRAMESRECEPTION_DISABLE ((uint32_t)0x00000020) + /** * @} */ @@ -1044,8 +985,9 @@ typedef struct /** @defgroup ETH_Destination_Addr_Filter ETH Destination Addr Filter * @{ */ -#define ETH_DESTINATIONADDRFILTER_NORMAL 0x00000000U -#define ETH_DESTINATIONADDRFILTER_INVERSE 0x00000008U +#define ETH_DESTINATIONADDRFILTER_NORMAL ((uint32_t)0x00000000) +#define ETH_DESTINATIONADDRFILTER_INVERSE ((uint32_t)0x00000008) + /** * @} */ @@ -1053,8 +995,9 @@ typedef struct /** @defgroup ETH_Promiscuous_Mode ETH Promiscuous Mode * @{ */ -#define ETH_PROMISCUOUS_MODE_ENABLE 0x00000001U -#define ETH_PROMISCUOUS_MODE_DISABLE 0x00000000U +#define ETH_PROMISCUOUS_MODE_ENABLE ((uint32_t)0x00000001) +#define ETH_PROMISCUOUS_MODE_DISABLE ((uint32_t)0x00000000) + /** * @} */ @@ -1062,10 +1005,11 @@ typedef struct /** @defgroup ETH_Multicast_Frames_Filter ETH Multicast Frames Filter * @{ */ -#define ETH_MULTICASTFRAMESFILTER_PERFECTHASHTABLE 0x00000404U -#define ETH_MULTICASTFRAMESFILTER_HASHTABLE 0x00000004U -#define ETH_MULTICASTFRAMESFILTER_PERFECT 0x00000000U -#define ETH_MULTICASTFRAMESFILTER_NONE 0x00000010U +#define ETH_MULTICASTFRAMESFILTER_PERFECTHASHTABLE ((uint32_t)0x00000404) +#define ETH_MULTICASTFRAMESFILTER_HASHTABLE ((uint32_t)0x00000004) +#define ETH_MULTICASTFRAMESFILTER_PERFECT ((uint32_t)0x00000000) +#define ETH_MULTICASTFRAMESFILTER_NONE ((uint32_t)0x00000010) + /** * @} */ @@ -1073,18 +1017,20 @@ typedef struct /** @defgroup ETH_Unicast_Frames_Filter ETH Unicast Frames Filter * @{ */ -#define ETH_UNICASTFRAMESFILTER_PERFECTHASHTABLE 0x00000402U -#define ETH_UNICASTFRAMESFILTER_HASHTABLE 0x00000002U -#define ETH_UNICASTFRAMESFILTER_PERFECT 0x00000000U +#define ETH_UNICASTFRAMESFILTER_PERFECTHASHTABLE ((uint32_t)0x00000402) +#define ETH_UNICASTFRAMESFILTER_HASHTABLE ((uint32_t)0x00000002) +#define ETH_UNICASTFRAMESFILTER_PERFECT ((uint32_t)0x00000000) + /** * @} */ -/** @defgroup ETH_Zero_Quanta_Pause ETH Zero Quanta Pause +/** @defgroup ETH_Zero_Quanta_Pause ETH Zero Quanta Pause * @{ */ -#define ETH_ZEROQUANTAPAUSE_ENABLE 0x00000000U -#define ETH_ZEROQUANTAPAUSE_DISABLE 0x00000080U +#define ETH_ZEROQUANTAPAUSE_ENABLE ((uint32_t)0x00000000) +#define ETH_ZEROQUANTAPAUSE_DISABLE ((uint32_t)0x00000080) + /** * @} */ @@ -1092,10 +1038,11 @@ typedef struct /** @defgroup ETH_Pause_Low_Threshold ETH Pause Low Threshold * @{ */ -#define ETH_PAUSELOWTHRESHOLD_MINUS4 0x00000000U /*!< Pause time minus 4 slot times */ -#define ETH_PAUSELOWTHRESHOLD_MINUS28 0x00000010U /*!< Pause time minus 28 slot times */ -#define ETH_PAUSELOWTHRESHOLD_MINUS144 0x00000020U /*!< Pause time minus 144 slot times */ -#define ETH_PAUSELOWTHRESHOLD_MINUS256 0x00000030U /*!< Pause time minus 256 slot times */ +#define ETH_PAUSELOWTHRESHOLD_MINUS4 ((uint32_t)0x00000000) /*!< Pause time minus 4 slot times */ +#define ETH_PAUSELOWTHRESHOLD_MINUS28 ((uint32_t)0x00000010) /*!< Pause time minus 28 slot times */ +#define ETH_PAUSELOWTHRESHOLD_MINUS144 ((uint32_t)0x00000020) /*!< Pause time minus 144 slot times */ +#define ETH_PAUSELOWTHRESHOLD_MINUS256 ((uint32_t)0x00000030) /*!< Pause time minus 256 slot times */ + /** * @} */ @@ -1103,8 +1050,9 @@ typedef struct /** @defgroup ETH_Unicast_Pause_Frame_Detect ETH Unicast Pause Frame Detect * @{ */ -#define ETH_UNICASTPAUSEFRAMEDETECT_ENABLE 0x00000008U -#define ETH_UNICASTPAUSEFRAMEDETECT_DISABLE 0x00000000U +#define ETH_UNICASTPAUSEFRAMEDETECT_ENABLE ((uint32_t)0x00000008) +#define ETH_UNICASTPAUSEFRAMEDETECT_DISABLE ((uint32_t)0x00000000) + /** * @} */ @@ -1112,8 +1060,9 @@ typedef struct /** @defgroup ETH_Receive_Flow_Control ETH Receive Flow Control * @{ */ -#define ETH_RECEIVEFLOWCONTROL_ENABLE 0x00000004U -#define ETH_RECEIVEFLOWCONTROL_DISABLE 0x00000000U +#define ETH_RECEIVEFLOWCONTROL_ENABLE ((uint32_t)0x00000004) +#define ETH_RECEIVEFLOWCONTROL_DISABLE ((uint32_t)0x00000000) + /** * @} */ @@ -1121,8 +1070,9 @@ typedef struct /** @defgroup ETH_Transmit_Flow_Control ETH Transmit Flow Control * @{ */ -#define ETH_TRANSMITFLOWCONTROL_ENABLE 0x00000002U -#define ETH_TRANSMITFLOWCONTROL_DISABLE 0x00000000U +#define ETH_TRANSMITFLOWCONTROL_ENABLE ((uint32_t)0x00000002) +#define ETH_TRANSMITFLOWCONTROL_DISABLE ((uint32_t)0x00000000) + /** * @} */ @@ -1130,8 +1080,9 @@ typedef struct /** @defgroup ETH_VLAN_Tag_Comparison ETH VLAN Tag Comparison * @{ */ -#define ETH_VLANTAGCOMPARISON_12BIT 0x00010000U -#define ETH_VLANTAGCOMPARISON_16BIT 0x00000000U +#define ETH_VLANTAGCOMPARISON_12BIT ((uint32_t)0x00010000) +#define ETH_VLANTAGCOMPARISON_16BIT ((uint32_t)0x00000000) + /** * @} */ @@ -1139,32 +1090,34 @@ typedef struct /** @defgroup ETH_MAC_addresses ETH MAC addresses * @{ */ -#define ETH_MAC_ADDRESS0 0x00000000U -#define ETH_MAC_ADDRESS1 0x00000008U -#define ETH_MAC_ADDRESS2 0x00000010U -#define ETH_MAC_ADDRESS3 0x00000018U +#define ETH_MAC_ADDRESS0 ((uint32_t)0x00000000) +#define ETH_MAC_ADDRESS1 ((uint32_t)0x00000008) +#define ETH_MAC_ADDRESS2 ((uint32_t)0x00000010) +#define ETH_MAC_ADDRESS3 ((uint32_t)0x00000018) + /** * @} */ -/** @defgroup ETH_MAC_addresses_filter_SA_DA ETH MAC addresses filter SA DA +/** @defgroup ETH_MAC_Addresses_Filter_SA_DA ETH MAC Addresses Filter SA DA * @{ */ -#define ETH_MAC_ADDRESSFILTER_SA 0x00000000U -#define ETH_MAC_ADDRESSFILTER_DA 0x00000008U +#define ETH_MAC_ADDRESSFILTER_SA ((uint32_t)0x00000000) +#define ETH_MAC_ADDRESSFILTER_DA ((uint32_t)0x00000008) /** * @} */ -/** @defgroup ETH_MAC_addresses_filter_Mask_bytes ETH MAC addresses filter Mask bytes +/** @defgroup ETH_MAC_Addresses_Filter_Mask_Bytes ETH_MAC Addresses Filter Mask Bytes * @{ */ -#define ETH_MAC_ADDRESSMASK_BYTE6 0x20000000U /*!< Mask MAC Address high reg bits [15:8] */ -#define ETH_MAC_ADDRESSMASK_BYTE5 0x10000000U /*!< Mask MAC Address high reg bits [7:0] */ -#define ETH_MAC_ADDRESSMASK_BYTE4 0x08000000U /*!< Mask MAC Address low reg bits [31:24] */ -#define ETH_MAC_ADDRESSMASK_BYTE3 0x04000000U /*!< Mask MAC Address low reg bits [23:16] */ -#define ETH_MAC_ADDRESSMASK_BYTE2 0x02000000U /*!< Mask MAC Address low reg bits [15:8] */ -#define ETH_MAC_ADDRESSMASK_BYTE1 0x01000000U /*!< Mask MAC Address low reg bits [70] */ +#define ETH_MAC_ADDRESSMASK_BYTE6 ((uint32_t)0x20000000) /*!< Mask MAC Address high reg bits [15:8] */ +#define ETH_MAC_ADDRESSMASK_BYTE5 ((uint32_t)0x10000000) /*!< Mask MAC Address high reg bits [7:0] */ +#define ETH_MAC_ADDRESSMASK_BYTE4 ((uint32_t)0x08000000) /*!< Mask MAC Address low reg bits [31:24] */ +#define ETH_MAC_ADDRESSMASK_BYTE3 ((uint32_t)0x04000000) /*!< Mask MAC Address low reg bits [23:16] */ +#define ETH_MAC_ADDRESSMASK_BYTE2 ((uint32_t)0x02000000) /*!< Mask MAC Address low reg bits [15:8] */ +#define ETH_MAC_ADDRESSMASK_BYTE1 ((uint32_t)0x01000000) /*!< Mask MAC Address low reg bits [70] */ + /** * @} */ @@ -1172,17 +1125,19 @@ typedef struct /** @defgroup ETH_Drop_TCP_IP_Checksum_Error_Frame ETH Drop TCP IP Checksum Error Frame * @{ */ -#define ETH_DROPTCPIPCHECKSUMERRORFRAME_ENABLE 0x00000000U -#define ETH_DROPTCPIPCHECKSUMERRORFRAME_DISABLE 0x04000000U +#define ETH_DROPTCPIPCHECKSUMERRORFRAME_ENABLE ((uint32_t)0x00000000) +#define ETH_DROPTCPIPCHECKSUMERRORFRAME_DISABLE ((uint32_t)0x04000000) + /** * @} */ -/** @defgroup ETH_Receive_Store_Forward ETH Receive Store Forward +/** @defgroup ETH_Receive_Store_Forward ETH Receive Store Forward * @{ */ -#define ETH_RECEIVESTOREFORWARD_ENABLE 0x02000000U -#define ETH_RECEIVESTOREFORWARD_DISABLE 0x00000000U +#define ETH_RECEIVESTOREFORWARD_ENABLE ((uint32_t)0x02000000) +#define ETH_RECEIVESTOREFORWARD_DISABLE ((uint32_t)0x00000000) + /** * @} */ @@ -1190,8 +1145,9 @@ typedef struct /** @defgroup ETH_Flush_Received_Frame ETH Flush Received Frame * @{ */ -#define ETH_FLUSHRECEIVEDFRAME_ENABLE 0x00000000U -#define ETH_FLUSHRECEIVEDFRAME_DISABLE 0x01000000U +#define ETH_FLUSHRECEIVEDFRAME_ENABLE ((uint32_t)0x00000000) +#define ETH_FLUSHRECEIVEDFRAME_DISABLE ((uint32_t)0x01000000) + /** * @} */ @@ -1199,8 +1155,9 @@ typedef struct /** @defgroup ETH_Transmit_Store_Forward ETH Transmit Store Forward * @{ */ -#define ETH_TRANSMITSTOREFORWARD_ENABLE 0x00200000U -#define ETH_TRANSMITSTOREFORWARD_DISABLE 0x00000000U +#define ETH_TRANSMITSTOREFORWARD_ENABLE ((uint32_t)0x00200000) +#define ETH_TRANSMITSTOREFORWARD_DISABLE ((uint32_t)0x00000000) + /** * @} */ @@ -1208,14 +1165,15 @@ typedef struct /** @defgroup ETH_Transmit_Threshold_Control ETH Transmit Threshold Control * @{ */ -#define ETH_TRANSMITTHRESHOLDCONTROL_64BYTES 0x00000000U /*!< threshold level of the MTL Transmit FIFO is 64 Bytes */ -#define ETH_TRANSMITTHRESHOLDCONTROL_128BYTES 0x00004000U /*!< threshold level of the MTL Transmit FIFO is 128 Bytes */ -#define ETH_TRANSMITTHRESHOLDCONTROL_192BYTES 0x00008000U /*!< threshold level of the MTL Transmit FIFO is 192 Bytes */ -#define ETH_TRANSMITTHRESHOLDCONTROL_256BYTES 0x0000C000U /*!< threshold level of the MTL Transmit FIFO is 256 Bytes */ -#define ETH_TRANSMITTHRESHOLDCONTROL_40BYTES 0x00010000U /*!< threshold level of the MTL Transmit FIFO is 40 Bytes */ -#define ETH_TRANSMITTHRESHOLDCONTROL_32BYTES 0x00014000U /*!< threshold level of the MTL Transmit FIFO is 32 Bytes */ -#define ETH_TRANSMITTHRESHOLDCONTROL_24BYTES 0x00018000U /*!< threshold level of the MTL Transmit FIFO is 24 Bytes */ -#define ETH_TRANSMITTHRESHOLDCONTROL_16BYTES 0x0001C000U /*!< threshold level of the MTL Transmit FIFO is 16 Bytes */ +#define ETH_TRANSMITTHRESHOLDCONTROL_64BYTES ((uint32_t)0x00000000) /*!< threshold level of the MTL Transmit FIFO is 64 Bytes */ +#define ETH_TRANSMITTHRESHOLDCONTROL_128BYTES ((uint32_t)0x00004000) /*!< threshold level of the MTL Transmit FIFO is 128 Bytes */ +#define ETH_TRANSMITTHRESHOLDCONTROL_192BYTES ((uint32_t)0x00008000) /*!< threshold level of the MTL Transmit FIFO is 192 Bytes */ +#define ETH_TRANSMITTHRESHOLDCONTROL_256BYTES ((uint32_t)0x0000C000) /*!< threshold level of the MTL Transmit FIFO is 256 Bytes */ +#define ETH_TRANSMITTHRESHOLDCONTROL_40BYTES ((uint32_t)0x00010000) /*!< threshold level of the MTL Transmit FIFO is 40 Bytes */ +#define ETH_TRANSMITTHRESHOLDCONTROL_32BYTES ((uint32_t)0x00014000) /*!< threshold level of the MTL Transmit FIFO is 32 Bytes */ +#define ETH_TRANSMITTHRESHOLDCONTROL_24BYTES ((uint32_t)0x00018000) /*!< threshold level of the MTL Transmit FIFO is 24 Bytes */ +#define ETH_TRANSMITTHRESHOLDCONTROL_16BYTES ((uint32_t)0x0001C000) /*!< threshold level of the MTL Transmit FIFO is 16 Bytes */ + /** * @} */ @@ -1223,8 +1181,9 @@ typedef struct /** @defgroup ETH_Forward_Error_Frames ETH Forward Error Frames * @{ */ -#define ETH_FORWARDERRORFRAMES_ENABLE 0x00000080U -#define ETH_FORWARDERRORFRAMES_DISABLE 0x00000000U +#define ETH_FORWARDERRORFRAMES_ENABLE ((uint32_t)0x00000080) +#define ETH_FORWARDERRORFRAMES_DISABLE ((uint32_t)0x00000000) + /** * @} */ @@ -1232,8 +1191,9 @@ typedef struct /** @defgroup ETH_Forward_Undersized_Good_Frames ETH Forward Undersized Good Frames * @{ */ -#define ETH_FORWARDUNDERSIZEDGOODFRAMES_ENABLE 0x00000040U -#define ETH_FORWARDUNDERSIZEDGOODFRAMES_DISABLE 0x00000000U +#define ETH_FORWARDUNDERSIZEDGOODFRAMES_ENABLE ((uint32_t)0x00000040) +#define ETH_FORWARDUNDERSIZEDGOODFRAMES_DISABLE ((uint32_t)0x00000000) + /** * @} */ @@ -1241,10 +1201,11 @@ typedef struct /** @defgroup ETH_Receive_Threshold_Control ETH Receive Threshold Control * @{ */ -#define ETH_RECEIVEDTHRESHOLDCONTROL_64BYTES 0x00000000U /*!< threshold level of the MTL Receive FIFO is 64 Bytes */ -#define ETH_RECEIVEDTHRESHOLDCONTROL_32BYTES 0x00000008U /*!< threshold level of the MTL Receive FIFO is 32 Bytes */ -#define ETH_RECEIVEDTHRESHOLDCONTROL_96BYTES 0x00000010U /*!< threshold level of the MTL Receive FIFO is 96 Bytes */ -#define ETH_RECEIVEDTHRESHOLDCONTROL_128BYTES 0x00000018U /*!< threshold level of the MTL Receive FIFO is 128 Bytes */ +#define ETH_RECEIVEDTHRESHOLDCONTROL_64BYTES ((uint32_t)0x00000000) /*!< threshold level of the MTL Receive FIFO is 64 Bytes */ +#define ETH_RECEIVEDTHRESHOLDCONTROL_32BYTES ((uint32_t)0x00000008) /*!< threshold level of the MTL Receive FIFO is 32 Bytes */ +#define ETH_RECEIVEDTHRESHOLDCONTROL_96BYTES ((uint32_t)0x00000010) /*!< threshold level of the MTL Receive FIFO is 96 Bytes */ +#define ETH_RECEIVEDTHRESHOLDCONTROL_128BYTES ((uint32_t)0x00000018) /*!< threshold level of the MTL Receive FIFO is 128 Bytes */ + /** * @} */ @@ -1252,17 +1213,19 @@ typedef struct /** @defgroup ETH_Second_Frame_Operate ETH Second Frame Operate * @{ */ -#define ETH_SECONDFRAMEOPERARTE_ENABLE 0x00000004U -#define ETH_SECONDFRAMEOPERARTE_DISABLE 0x00000000U +#define ETH_SECONDFRAMEOPERARTE_ENABLE ((uint32_t)0x00000004) +#define ETH_SECONDFRAMEOPERARTE_DISABLE ((uint32_t)0x00000000) + /** * @} */ -/** @defgroup ETH_Address_Aligned_Beats ETH Address Aligned Beats +/** @defgroup ETH_Address_Aligned_Beats ETH Address Aligned Beats * @{ */ -#define ETH_ADDRESSALIGNEDBEATS_ENABLE 0x02000000U -#define ETH_ADDRESSALIGNEDBEATS_DISABLE 0x00000000U +#define ETH_ADDRESSALIGNEDBEATS_ENABLE ((uint32_t)0x02000000) +#define ETH_ADDRESSALIGNEDBEATS_DISABLE ((uint32_t)0x00000000) + /** * @} */ @@ -1270,27 +1233,29 @@ typedef struct /** @defgroup ETH_Fixed_Burst ETH Fixed Burst * @{ */ -#define ETH_FIXEDBURST_ENABLE 0x00010000U -#define ETH_FIXEDBURST_DISABLE 0x00000000U +#define ETH_FIXEDBURST_ENABLE ((uint32_t)0x00010000) +#define ETH_FIXEDBURST_DISABLE ((uint32_t)0x00000000) + /** * @} */ -/** @defgroup ETH_Rx_DMA_Burst_Length ETH Rx DMA Burst Length +/** @defgroup ETH_Rx_DMA_Burst_Length ETH Rx DMA_Burst Length * @{ */ -#define ETH_RXDMABURSTLENGTH_1BEAT 0x00020000U /*!< maximum number of beats to be transferred in one RxDMA transaction is 1 */ -#define ETH_RXDMABURSTLENGTH_2BEAT 0x00040000U /*!< maximum number of beats to be transferred in one RxDMA transaction is 2 */ -#define ETH_RXDMABURSTLENGTH_4BEAT 0x00080000U /*!< maximum number of beats to be transferred in one RxDMA transaction is 4 */ -#define ETH_RXDMABURSTLENGTH_8BEAT 0x00100000U /*!< maximum number of beats to be transferred in one RxDMA transaction is 8 */ -#define ETH_RXDMABURSTLENGTH_16BEAT 0x00200000U /*!< maximum number of beats to be transferred in one RxDMA transaction is 16 */ -#define ETH_RXDMABURSTLENGTH_32BEAT 0x00400000U /*!< maximum number of beats to be transferred in one RxDMA transaction is 32 */ -#define ETH_RXDMABURSTLENGTH_4XPBL_4BEAT 0x01020000U /*!< maximum number of beats to be transferred in one RxDMA transaction is 4 */ -#define ETH_RXDMABURSTLENGTH_4XPBL_8BEAT 0x01040000U /*!< maximum number of beats to be transferred in one RxDMA transaction is 8 */ -#define ETH_RXDMABURSTLENGTH_4XPBL_16BEAT 0x01080000U /*!< maximum number of beats to be transferred in one RxDMA transaction is 16 */ -#define ETH_RXDMABURSTLENGTH_4XPBL_32BEAT 0x01100000U /*!< maximum number of beats to be transferred in one RxDMA transaction is 32 */ -#define ETH_RXDMABURSTLENGTH_4XPBL_64BEAT 0x01200000U /*!< maximum number of beats to be transferred in one RxDMA transaction is 64 */ -#define ETH_RXDMABURSTLENGTH_4XPBL_128BEAT 0x01400000U /*!< maximum number of beats to be transferred in one RxDMA transaction is 128 */ +#define ETH_RXDMABURSTLENGTH_1BEAT ((uint32_t)0x00020000) /*!< maximum number of beats to be transferred in one RxDMA transaction is 1 */ +#define ETH_RXDMABURSTLENGTH_2BEAT ((uint32_t)0x00040000) /*!< maximum number of beats to be transferred in one RxDMA transaction is 2 */ +#define ETH_RXDMABURSTLENGTH_4BEAT ((uint32_t)0x00080000) /*!< maximum number of beats to be transferred in one RxDMA transaction is 4 */ +#define ETH_RXDMABURSTLENGTH_8BEAT ((uint32_t)0x00100000) /*!< maximum number of beats to be transferred in one RxDMA transaction is 8 */ +#define ETH_RXDMABURSTLENGTH_16BEAT ((uint32_t)0x00200000) /*!< maximum number of beats to be transferred in one RxDMA transaction is 16 */ +#define ETH_RXDMABURSTLENGTH_32BEAT ((uint32_t)0x00400000) /*!< maximum number of beats to be transferred in one RxDMA transaction is 32 */ +#define ETH_RXDMABURSTLENGTH_4XPBL_4BEAT ((uint32_t)0x01020000) /*!< maximum number of beats to be transferred in one RxDMA transaction is 4 */ +#define ETH_RXDMABURSTLENGTH_4XPBL_8BEAT ((uint32_t)0x01040000) /*!< maximum number of beats to be transferred in one RxDMA transaction is 8 */ +#define ETH_RXDMABURSTLENGTH_4XPBL_16BEAT ((uint32_t)0x01080000) /*!< maximum number of beats to be transferred in one RxDMA transaction is 16 */ +#define ETH_RXDMABURSTLENGTH_4XPBL_32BEAT ((uint32_t)0x01100000) /*!< maximum number of beats to be transferred in one RxDMA transaction is 32 */ +#define ETH_RXDMABURSTLENGTH_4XPBL_64BEAT ((uint32_t)0x01200000) /*!< maximum number of beats to be transferred in one RxDMA transaction is 64 */ +#define ETH_RXDMABURSTLENGTH_4XPBL_128BEAT ((uint32_t)0x01400000) /*!< maximum number of beats to be transferred in one RxDMA transaction is 128 */ + /** * @} */ @@ -1298,18 +1263,18 @@ typedef struct /** @defgroup ETH_Tx_DMA_Burst_Length ETH Tx DMA Burst Length * @{ */ -#define ETH_TXDMABURSTLENGTH_1BEAT 0x00000100U /*!< maximum number of beats to be transferred in one TxDMA (or both) transaction is 1 */ -#define ETH_TXDMABURSTLENGTH_2BEAT 0x00000200U /*!< maximum number of beats to be transferred in one TxDMA (or both) transaction is 2 */ -#define ETH_TXDMABURSTLENGTH_4BEAT 0x00000400U /*!< maximum number of beats to be transferred in one TxDMA (or both) transaction is 4 */ -#define ETH_TXDMABURSTLENGTH_8BEAT 0x00000800U /*!< maximum number of beats to be transferred in one TxDMA (or both) transaction is 8 */ -#define ETH_TXDMABURSTLENGTH_16BEAT 0x00001000U /*!< maximum number of beats to be transferred in one TxDMA (or both) transaction is 16 */ -#define ETH_TXDMABURSTLENGTH_32BEAT 0x00002000U /*!< maximum number of beats to be transferred in one TxDMA (or both) transaction is 32 */ -#define ETH_TXDMABURSTLENGTH_4XPBL_4BEAT 0x01000100U /*!< maximum number of beats to be transferred in one TxDMA (or both) transaction is 4 */ -#define ETH_TXDMABURSTLENGTH_4XPBL_8BEAT 0x01000200U /*!< maximum number of beats to be transferred in one TxDMA (or both) transaction is 8 */ -#define ETH_TXDMABURSTLENGTH_4XPBL_16BEAT 0x01000400U /*!< maximum number of beats to be transferred in one TxDMA (or both) transaction is 16 */ -#define ETH_TXDMABURSTLENGTH_4XPBL_32BEAT 0x01000800U /*!< maximum number of beats to be transferred in one TxDMA (or both) transaction is 32 */ -#define ETH_TXDMABURSTLENGTH_4XPBL_64BEAT 0x01001000U /*!< maximum number of beats to be transferred in one TxDMA (or both) transaction is 64 */ -#define ETH_TXDMABURSTLENGTH_4XPBL_128BEAT 0x01002000U /*!< maximum number of beats to be transferred in one TxDMA (or both) transaction is 128 */ +#define ETH_TXDMABURSTLENGTH_1BEAT ((uint32_t)0x00000100) /*!< maximum number of beats to be transferred in one TxDMA (or both) transaction is 1 */ +#define ETH_TXDMABURSTLENGTH_2BEAT ((uint32_t)0x00000200) /*!< maximum number of beats to be transferred in one TxDMA (or both) transaction is 2 */ +#define ETH_TXDMABURSTLENGTH_4BEAT ((uint32_t)0x00000400) /*!< maximum number of beats to be transferred in one TxDMA (or both) transaction is 4 */ +#define ETH_TXDMABURSTLENGTH_8BEAT ((uint32_t)0x00000800) /*!< maximum number of beats to be transferred in one TxDMA (or both) transaction is 8 */ +#define ETH_TXDMABURSTLENGTH_16BEAT ((uint32_t)0x00001000) /*!< maximum number of beats to be transferred in one TxDMA (or both) transaction is 16 */ +#define ETH_TXDMABURSTLENGTH_32BEAT ((uint32_t)0x00002000) /*!< maximum number of beats to be transferred in one TxDMA (or both) transaction is 32 */ +#define ETH_TXDMABURSTLENGTH_4XPBL_4BEAT ((uint32_t)0x01000100) /*!< maximum number of beats to be transferred in one TxDMA (or both) transaction is 4 */ +#define ETH_TXDMABURSTLENGTH_4XPBL_8BEAT ((uint32_t)0x01000200) /*!< maximum number of beats to be transferred in one TxDMA (or both) transaction is 8 */ +#define ETH_TXDMABURSTLENGTH_4XPBL_16BEAT ((uint32_t)0x01000400) /*!< maximum number of beats to be transferred in one TxDMA (or both) transaction is 16 */ +#define ETH_TXDMABURSTLENGTH_4XPBL_32BEAT ((uint32_t)0x01000800) /*!< maximum number of beats to be transferred in one TxDMA (or both) transaction is 32 */ +#define ETH_TXDMABURSTLENGTH_4XPBL_64BEAT ((uint32_t)0x01001000) /*!< maximum number of beats to be transferred in one TxDMA (or both) transaction is 64 */ +#define ETH_TXDMABURSTLENGTH_4XPBL_128BEAT ((uint32_t)0x01002000) /*!< maximum number of beats to be transferred in one TxDMA (or both) transaction is 128 */ /** * @} @@ -1318,40 +1283,44 @@ typedef struct /** @defgroup ETH_DMA_Arbitration ETH DMA Arbitration * @{ */ -#define ETH_DMAARBITRATION_ROUNDROBIN_RXTX_1_1 0x00000000U -#define ETH_DMAARBITRATION_ROUNDROBIN_RXTX_2_1 0x00004000U -#define ETH_DMAARBITRATION_ROUNDROBIN_RXTX_3_1 0x00008000U -#define ETH_DMAARBITRATION_ROUNDROBIN_RXTX_4_1 0x0000C000U -#define ETH_DMAARBITRATION_RXPRIORTX 0x00000002U +#define ETH_DMAARBITRATION_ROUNDROBIN_RXTX_1_1 ((uint32_t)0x00000000) +#define ETH_DMAARBITRATION_ROUNDROBIN_RXTX_2_1 ((uint32_t)0x00004000) +#define ETH_DMAARBITRATION_ROUNDROBIN_RXTX_3_1 ((uint32_t)0x00008000) +#define ETH_DMAARBITRATION_ROUNDROBIN_RXTX_4_1 ((uint32_t)0x0000C000) +#define ETH_DMAARBITRATION_RXPRIORTX ((uint32_t)0x00000002) + /** * @} */ -/** @defgroup ETH_DMA_Tx_descriptor_segment ETH DMA Tx descriptor segment +/** @defgroup ETH_DMA_Tx_Descriptor_Segment ETH DMA Tx Descriptor Segment * @{ */ -#define ETH_DMATXDESC_LASTSEGMENTS 0x40000000U /*!< Last Segment */ -#define ETH_DMATXDESC_FIRSTSEGMENT 0x20000000U /*!< First Segment */ +#define ETH_DMATXDESC_LASTSEGMENTS ((uint32_t)0x40000000) /*!< Last Segment */ +#define ETH_DMATXDESC_FIRSTSEGMENT ((uint32_t)0x20000000) /*!< First Segment */ + /** * @} */ -/** @defgroup ETH_DMA_Tx_descriptor_Checksum_Insertion_Control ETH DMA Tx descriptor Checksum Insertion Control +/** @defgroup ETH_DMA_Tx_Descriptor_Checksum_Insertion_Control ETH DMA Tx Descriptor Checksum Insertion Control * @{ */ -#define ETH_DMATXDESC_CHECKSUMBYPASS 0x00000000U /*!< Checksum engine bypass */ -#define ETH_DMATXDESC_CHECKSUMIPV4HEADER 0x00400000U /*!< IPv4 header checksum insertion */ -#define ETH_DMATXDESC_CHECKSUMTCPUDPICMPSEGMENT 0x00800000U /*!< TCP/UDP/ICMP checksum insertion. Pseudo header checksum is assumed to be present */ -#define ETH_DMATXDESC_CHECKSUMTCPUDPICMPFULL 0x00C00000U /*!< TCP/UDP/ICMP checksum fully in hardware including pseudo header */ +#define ETH_DMATXDESC_CHECKSUMBYPASS ((uint32_t)0x00000000) /*!< Checksum engine bypass */ +#define ETH_DMATXDESC_CHECKSUMIPV4HEADER ((uint32_t)0x00400000) /*!< IPv4 header checksum insertion */ +#define ETH_DMATXDESC_CHECKSUMTCPUDPICMPSEGMENT ((uint32_t)0x00800000) /*!< TCP/UDP/ICMP checksum insertion. Pseudo header checksum is assumed to be present */ +#define ETH_DMATXDESC_CHECKSUMTCPUDPICMPFULL ((uint32_t)0x00C00000) /*!< TCP/UDP/ICMP checksum fully in hardware including pseudo header */ + /** * @} */ -/** @defgroup ETH_DMA_Rx_descriptor_buffers ETH DMA Rx descriptor buffers +/** @defgroup ETH_DMA_Rx_Descriptor_Buffers ETH DMA Rx Descriptor Buffers * @{ */ -#define ETH_DMARXDESC_BUFFER1 0x00000000U /*!< DMA Rx Desc Buffer1 */ -#define ETH_DMARXDESC_BUFFER2 0x00000001U /*!< DMA Rx Desc Buffer2 */ +#define ETH_DMARXDESC_BUFFER1 ((uint32_t)0x00000000) /*!< DMA Rx Desc Buffer1 */ +#define ETH_DMARXDESC_BUFFER2 ((uint32_t)0x00000001) /*!< DMA Rx Desc Buffer2 */ + /** * @} */ @@ -1359,9 +1328,10 @@ typedef struct /** @defgroup ETH_PMT_Flags ETH PMT Flags * @{ */ -#define ETH_PMT_FLAG_WUFFRPR 0x80000000U /*!< Wake-Up Frame Filter Register Pointer Reset */ -#define ETH_PMT_FLAG_WUFR 0x00000040U /*!< Wake-Up Frame Received */ -#define ETH_PMT_FLAG_MPR 0x00000020U /*!< Magic Packet Received */ +#define ETH_PMT_FLAG_WUFFRPR ((uint32_t)0x80000000) /*!< Wake-Up Frame Filter Register Pointer Reset */ +#define ETH_PMT_FLAG_WUFR ((uint32_t)0x00000040) /*!< Wake-Up Frame Received */ +#define ETH_PMT_FLAG_MPR ((uint32_t)0x00000020) /*!< Magic Packet Received */ + /** * @} */ @@ -1369,9 +1339,10 @@ typedef struct /** @defgroup ETH_MMC_Tx_Interrupts ETH MMC Tx Interrupts * @{ */ -#define ETH_MMC_IT_TGF 0x00200000U /*!< When Tx good frame counter reaches half the maximum value */ -#define ETH_MMC_IT_TGFMSC 0x00008000U /*!< When Tx good multi col counter reaches half the maximum value */ -#define ETH_MMC_IT_TGFSC 0x00004000U /*!< When Tx good single col counter reaches half the maximum value */ +#define ETH_MMC_IT_TGF ((uint32_t)0x00200000) /*!< When Tx good frame counter reaches half the maximum value */ +#define ETH_MMC_IT_TGFMSC ((uint32_t)0x00008000) /*!< When Tx good multi col counter reaches half the maximum value */ +#define ETH_MMC_IT_TGFSC ((uint32_t)0x00004000) /*!< When Tx good single col counter reaches half the maximum value */ + /** * @} */ @@ -1379,9 +1350,10 @@ typedef struct /** @defgroup ETH_MMC_Rx_Interrupts ETH MMC Rx Interrupts * @{ */ -#define ETH_MMC_IT_RGUF 0x10020000U /*!< When Rx good unicast frames counter reaches half the maximum value */ -#define ETH_MMC_IT_RFAE 0x10000040U /*!< When Rx alignment error counter reaches half the maximum value */ -#define ETH_MMC_IT_RFCE 0x10000020U /*!< When Rx crc error counter reaches half the maximum value */ +#define ETH_MMC_IT_RGUF ((uint32_t)0x10020000) /*!< When Rx good unicast frames counter reaches half the maximum value */ +#define ETH_MMC_IT_RFAE ((uint32_t)0x10000040) /*!< When Rx alignment error counter reaches half the maximum value */ +#define ETH_MMC_IT_RFCE ((uint32_t)0x10000020) /*!< When Rx crc error counter reaches half the maximum value */ + /** * @} */ @@ -1389,11 +1361,12 @@ typedef struct /** @defgroup ETH_MAC_Flags ETH MAC Flags * @{ */ -#define ETH_MAC_FLAG_TST 0x00000200U /*!< Time stamp trigger flag (on MAC) */ -#define ETH_MAC_FLAG_MMCT 0x00000040U /*!< MMC transmit flag */ -#define ETH_MAC_FLAG_MMCR 0x00000020U /*!< MMC receive flag */ -#define ETH_MAC_FLAG_MMC 0x00000010U /*!< MMC flag (on MAC) */ -#define ETH_MAC_FLAG_PMT 0x00000008U /*!< PMT flag (on MAC) */ +#define ETH_MAC_FLAG_TST ((uint32_t)0x00000200) /*!< Time stamp trigger flag (on MAC) */ +#define ETH_MAC_FLAG_MMCT ((uint32_t)0x00000040) /*!< MMC transmit flag */ +#define ETH_MAC_FLAG_MMCR ((uint32_t)0x00000020) /*!< MMC receive flag */ +#define ETH_MAC_FLAG_MMC ((uint32_t)0x00000010) /*!< MMC flag (on MAC) */ +#define ETH_MAC_FLAG_PMT ((uint32_t)0x00000008) /*!< PMT flag (on MAC) */ + /** * @} */ @@ -1401,64 +1374,67 @@ typedef struct /** @defgroup ETH_DMA_Flags ETH DMA Flags * @{ */ -#define ETH_DMA_FLAG_TST 0x20000000U /*!< Time-stamp trigger interrupt (on DMA) */ -#define ETH_DMA_FLAG_PMT 0x10000000U /*!< PMT interrupt (on DMA) */ -#define ETH_DMA_FLAG_MMC 0x08000000U /*!< MMC interrupt (on DMA) */ -#define ETH_DMA_FLAG_DATATRANSFERERROR 0x00800000U /*!< Error bits 0-Rx DMA, 1-Tx DMA */ -#define ETH_DMA_FLAG_READWRITEERROR 0x01000000U /*!< Error bits 0-write transfer, 1-read transfer */ -#define ETH_DMA_FLAG_ACCESSERROR 0x02000000U /*!< Error bits 0-data buffer, 1-desc. access */ -#define ETH_DMA_FLAG_NIS 0x00010000U /*!< Normal interrupt summary flag */ -#define ETH_DMA_FLAG_AIS 0x00008000U /*!< Abnormal interrupt summary flag */ -#define ETH_DMA_FLAG_ER 0x00004000U /*!< Early receive flag */ -#define ETH_DMA_FLAG_FBE 0x00002000U /*!< Fatal bus error flag */ -#define ETH_DMA_FLAG_ET 0x00000400U /*!< Early transmit flag */ -#define ETH_DMA_FLAG_RWT 0x00000200U /*!< Receive watchdog timeout flag */ -#define ETH_DMA_FLAG_RPS 0x00000100U /*!< Receive process stopped flag */ -#define ETH_DMA_FLAG_RBU 0x00000080U /*!< Receive buffer unavailable flag */ -#define ETH_DMA_FLAG_R 0x00000040U /*!< Receive flag */ -#define ETH_DMA_FLAG_TU 0x00000020U /*!< Underflow flag */ -#define ETH_DMA_FLAG_RO 0x00000010U /*!< Overflow flag */ -#define ETH_DMA_FLAG_TJT 0x00000008U /*!< Transmit jabber timeout flag */ -#define ETH_DMA_FLAG_TBU 0x00000004U /*!< Transmit buffer unavailable flag */ -#define ETH_DMA_FLAG_TPS 0x00000002U /*!< Transmit process stopped flag */ -#define ETH_DMA_FLAG_T 0x00000001U /*!< Transmit flag */ +#define ETH_DMA_FLAG_TST ((uint32_t)0x20000000) /*!< Time-stamp trigger interrupt (on DMA) */ +#define ETH_DMA_FLAG_PMT ((uint32_t)0x10000000) /*!< PMT interrupt (on DMA) */ +#define ETH_DMA_FLAG_MMC ((uint32_t)0x08000000) /*!< MMC interrupt (on DMA) */ +#define ETH_DMA_FLAG_DATATRANSFERERROR ((uint32_t)0x00800000) /*!< Error bits 0-Rx DMA, 1-Tx DMA */ +#define ETH_DMA_FLAG_READWRITEERROR ((uint32_t)0x01000000) /*!< Error bits 0-write trnsf, 1-read transfr */ +#define ETH_DMA_FLAG_ACCESSERROR ((uint32_t)0x02000000) /*!< Error bits 0-data buffer, 1-desc. access */ +#define ETH_DMA_FLAG_NIS ((uint32_t)0x00010000) /*!< Normal interrupt summary flag */ +#define ETH_DMA_FLAG_AIS ((uint32_t)0x00008000) /*!< Abnormal interrupt summary flag */ +#define ETH_DMA_FLAG_ER ((uint32_t)0x00004000) /*!< Early receive flag */ +#define ETH_DMA_FLAG_FBE ((uint32_t)0x00002000) /*!< Fatal bus error flag */ +#define ETH_DMA_FLAG_ET ((uint32_t)0x00000400) /*!< Early transmit flag */ +#define ETH_DMA_FLAG_RWT ((uint32_t)0x00000200) /*!< Receive watchdog timeout flag */ +#define ETH_DMA_FLAG_RPS ((uint32_t)0x00000100) /*!< Receive process stopped flag */ +#define ETH_DMA_FLAG_RBU ((uint32_t)0x00000080) /*!< Receive buffer unavailable flag */ +#define ETH_DMA_FLAG_R ((uint32_t)0x00000040) /*!< Receive flag */ +#define ETH_DMA_FLAG_TU ((uint32_t)0x00000020) /*!< Underflow flag */ +#define ETH_DMA_FLAG_RO ((uint32_t)0x00000010) /*!< Overflow flag */ +#define ETH_DMA_FLAG_TJT ((uint32_t)0x00000008) /*!< Transmit jabber timeout flag */ +#define ETH_DMA_FLAG_TBU ((uint32_t)0x00000004) /*!< Transmit buffer unavailable flag */ +#define ETH_DMA_FLAG_TPS ((uint32_t)0x00000002) /*!< Transmit process stopped flag */ +#define ETH_DMA_FLAG_T ((uint32_t)0x00000001) /*!< Transmit flag */ + /** * @} */ -/** @defgroup ETH_MAC_Interrupts ETH MAC Interrupts +/** @defgroup ETH_MAC_Interrupts ETH MAC Interrupts * @{ */ -#define ETH_MAC_IT_TST 0x00000200U /*!< Time stamp trigger interrupt (on MAC) */ -#define ETH_MAC_IT_MMCT 0x00000040U /*!< MMC transmit interrupt */ -#define ETH_MAC_IT_MMCR 0x00000020U /*!< MMC receive interrupt */ -#define ETH_MAC_IT_MMC 0x00000010U /*!< MMC interrupt (on MAC) */ -#define ETH_MAC_IT_PMT 0x00000008U /*!< PMT interrupt (on MAC) */ +#define ETH_MAC_IT_TST ((uint32_t)0x00000200) /*!< Time stamp trigger interrupt (on MAC) */ +#define ETH_MAC_IT_MMCT ((uint32_t)0x00000040) /*!< MMC transmit interrupt */ +#define ETH_MAC_IT_MMCR ((uint32_t)0x00000020) /*!< MMC receive interrupt */ +#define ETH_MAC_IT_MMC ((uint32_t)0x00000010) /*!< MMC interrupt (on MAC) */ +#define ETH_MAC_IT_PMT ((uint32_t)0x00000008) /*!< PMT interrupt (on MAC) */ + /** * @} */ -/** @defgroup ETH_DMA_Interrupts ETH DMA Interrupts +/** @defgroup ETH_DMA_Interrupts ETH DMA Interrupts * @{ */ -#define ETH_DMA_IT_TST 0x20000000U /*!< Time-stamp trigger interrupt (on DMA) */ -#define ETH_DMA_IT_PMT 0x10000000U /*!< PMT interrupt (on DMA) */ -#define ETH_DMA_IT_MMC 0x08000000U /*!< MMC interrupt (on DMA) */ -#define ETH_DMA_IT_NIS 0x00010000U /*!< Normal interrupt summary */ -#define ETH_DMA_IT_AIS 0x00008000U /*!< Abnormal interrupt summary */ -#define ETH_DMA_IT_ER 0x00004000U /*!< Early receive interrupt */ -#define ETH_DMA_IT_FBE 0x00002000U /*!< Fatal bus error interrupt */ -#define ETH_DMA_IT_ET 0x00000400U /*!< Early transmit interrupt */ -#define ETH_DMA_IT_RWT 0x00000200U /*!< Receive watchdog timeout interrupt */ -#define ETH_DMA_IT_RPS 0x00000100U /*!< Receive process stopped interrupt */ -#define ETH_DMA_IT_RBU 0x00000080U /*!< Receive buffer unavailable interrupt */ -#define ETH_DMA_IT_R 0x00000040U /*!< Receive interrupt */ -#define ETH_DMA_IT_TU 0x00000020U /*!< Underflow interrupt */ -#define ETH_DMA_IT_RO 0x00000010U /*!< Overflow interrupt */ -#define ETH_DMA_IT_TJT 0x00000008U /*!< Transmit jabber timeout interrupt */ -#define ETH_DMA_IT_TBU 0x00000004U /*!< Transmit buffer unavailable interrupt */ -#define ETH_DMA_IT_TPS 0x00000002U /*!< Transmit process stopped interrupt */ -#define ETH_DMA_IT_T 0x00000001U /*!< Transmit interrupt */ +#define ETH_DMA_IT_TST ((uint32_t)0x20000000) /*!< Time-stamp trigger interrupt (on DMA) */ +#define ETH_DMA_IT_PMT ((uint32_t)0x10000000) /*!< PMT interrupt (on DMA) */ +#define ETH_DMA_IT_MMC ((uint32_t)0x08000000) /*!< MMC interrupt (on DMA) */ +#define ETH_DMA_IT_NIS ((uint32_t)0x00010000) /*!< Normal interrupt summary */ +#define ETH_DMA_IT_AIS ((uint32_t)0x00008000) /*!< Abnormal interrupt summary */ +#define ETH_DMA_IT_ER ((uint32_t)0x00004000) /*!< Early receive interrupt */ +#define ETH_DMA_IT_FBE ((uint32_t)0x00002000) /*!< Fatal bus error interrupt */ +#define ETH_DMA_IT_ET ((uint32_t)0x00000400) /*!< Early transmit interrupt */ +#define ETH_DMA_IT_RWT ((uint32_t)0x00000200) /*!< Receive watchdog timeout interrupt */ +#define ETH_DMA_IT_RPS ((uint32_t)0x00000100) /*!< Receive process stopped interrupt */ +#define ETH_DMA_IT_RBU ((uint32_t)0x00000080) /*!< Receive buffer unavailable interrupt */ +#define ETH_DMA_IT_R ((uint32_t)0x00000040) /*!< Receive interrupt */ +#define ETH_DMA_IT_TU ((uint32_t)0x00000020) /*!< Underflow interrupt */ +#define ETH_DMA_IT_RO ((uint32_t)0x00000010) /*!< Overflow interrupt */ +#define ETH_DMA_IT_TJT ((uint32_t)0x00000008) /*!< Transmit jabber timeout interrupt */ +#define ETH_DMA_IT_TBU ((uint32_t)0x00000004) /*!< Transmit buffer unavailable interrupt */ +#define ETH_DMA_IT_TPS ((uint32_t)0x00000002) /*!< Transmit process stopped interrupt */ +#define ETH_DMA_IT_T ((uint32_t)0x00000001) /*!< Transmit interrupt */ + /** * @} */ @@ -1466,12 +1442,12 @@ typedef struct /** @defgroup ETH_DMA_transmit_process_state ETH DMA transmit process state * @{ */ -#define ETH_DMA_TRANSMITPROCESS_STOPPED 0x00000000U /*!< Stopped - Reset or Stop Tx Command issued */ -#define ETH_DMA_TRANSMITPROCESS_FETCHING 0x00100000U /*!< Running - fetching the Tx descriptor */ -#define ETH_DMA_TRANSMITPROCESS_WAITING 0x00200000U /*!< Running - waiting for status */ -#define ETH_DMA_TRANSMITPROCESS_READING 0x00300000U /*!< Running - reading the data from host memory */ -#define ETH_DMA_TRANSMITPROCESS_SUSPENDED 0x00600000U /*!< Suspended - Tx Descriptor unavailable */ -#define ETH_DMA_TRANSMITPROCESS_CLOSING 0x00700000U /*!< Running - closing Rx descriptor */ +#define ETH_DMA_TRANSMITPROCESS_STOPPED ((uint32_t)0x00000000) /*!< Stopped - Reset or Stop Tx Command issued */ +#define ETH_DMA_TRANSMITPROCESS_FETCHING ((uint32_t)0x00100000) /*!< Running - fetching the Tx descriptor */ +#define ETH_DMA_TRANSMITPROCESS_WAITING ((uint32_t)0x00200000) /*!< Running - waiting for status */ +#define ETH_DMA_TRANSMITPROCESS_READING ((uint32_t)0x00300000) /*!< Running - reading the data from host memory */ +#define ETH_DMA_TRANSMITPROCESS_SUSPENDED ((uint32_t)0x00600000) /*!< Suspended - Tx Descriptor unavailable */ +#define ETH_DMA_TRANSMITPROCESS_CLOSING ((uint32_t)0x00700000) /*!< Running - closing Rx descriptor */ /** * @} @@ -1481,12 +1457,12 @@ typedef struct /** @defgroup ETH_DMA_receive_process_state ETH DMA receive process state * @{ */ -#define ETH_DMA_RECEIVEPROCESS_STOPPED 0x00000000U /*!< Stopped - Reset or Stop Rx Command issued */ -#define ETH_DMA_RECEIVEPROCESS_FETCHING 0x00020000U /*!< Running - fetching the Rx descriptor */ -#define ETH_DMA_RECEIVEPROCESS_WAITING 0x00060000U /*!< Running - waiting for packet */ -#define ETH_DMA_RECEIVEPROCESS_SUSPENDED 0x00080000U /*!< Suspended - Rx Descriptor unavailable */ -#define ETH_DMA_RECEIVEPROCESS_CLOSING 0x000A0000U /*!< Running - closing descriptor */ -#define ETH_DMA_RECEIVEPROCESS_QUEUING 0x000E0000U /*!< Running - queuing the receive frame into host memory */ +#define ETH_DMA_RECEIVEPROCESS_STOPPED ((uint32_t)0x00000000) /*!< Stopped - Reset or Stop Rx Command issued */ +#define ETH_DMA_RECEIVEPROCESS_FETCHING ((uint32_t)0x00020000) /*!< Running - fetching the Rx descriptor */ +#define ETH_DMA_RECEIVEPROCESS_WAITING ((uint32_t)0x00060000) /*!< Running - waiting for packet */ +#define ETH_DMA_RECEIVEPROCESS_SUSPENDED ((uint32_t)0x00080000) /*!< Suspended - Rx Descriptor unavailable */ +#define ETH_DMA_RECEIVEPROCESS_CLOSING ((uint32_t)0x000A0000) /*!< Running - closing descriptor */ +#define ETH_DMA_RECEIVEPROCESS_QUEUING ((uint32_t)0x000E0000) /*!< Running - queuing the receive frame into host memory */ /** * @} @@ -1495,16 +1471,17 @@ typedef struct /** @defgroup ETH_DMA_overflow ETH DMA overflow * @{ */ -#define ETH_DMA_OVERFLOW_RXFIFOCOUNTER 0x10000000U /*!< Overflow bit for FIFO overflow counter */ -#define ETH_DMA_OVERFLOW_MISSEDFRAMECOUNTER 0x00010000U /*!< Overflow bit for missed frame counter */ +#define ETH_DMA_OVERFLOW_RXFIFOCOUNTER ((uint32_t)0x10000000) /*!< Overflow bit for FIFO overflow counter */ +#define ETH_DMA_OVERFLOW_MISSEDFRAMECOUNTER ((uint32_t)0x00010000) /*!< Overflow bit for missed frame counter */ + /** * @} */ -/** @defgroup ETH_EXTI_LINE_WAKEUP ETH EXTI LINE WAKEUP + /** @defgroup ETH_EXTI_LINE_WAKEUP ETH EXTI LINE WAKEUP * @{ */ -#define ETH_EXTI_LINE_WAKEUP 0x00080000U /*!< External interrupt line 19 Connected to the ETH EXTI Line */ +#define ETH_EXTI_LINE_WAKEUP ((uint32_t)0x00080000) /*!< External interrupt line 19 Connected to the ETH EXTI Line */ /** * @} @@ -1529,7 +1506,7 @@ typedef struct /** * @brief Checks whether the specified ETHERNET DMA Tx Desc flag is set or not. * @param __HANDLE__: ETH Handle - * @param __FLAG__: specifies the flag of TDES0 to check. + * @param __FLAG__: specifies the flag of TDES0 to check . * @retval the ETH_DMATxDescFlag (SET or RESET). */ #define __HAL_ETH_DMATXDESC_GET_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->TxDesc->Status & (__FLAG__) == (__FLAG__)) @@ -1599,7 +1576,7 @@ typedef struct * @arg ETH_DMATXDESC_CHECKSUMBYPASS : Checksum bypass * @arg ETH_DMATXDESC_CHECKSUMIPV4HEADER : IPv4 header checksum * @arg ETH_DMATXDESC_CHECKSUMTCPUDPICMPSEGMENT : TCP/UDP/ICMP checksum. Pseudo header checksum is assumed to be present - * @arg ETH_DMATXDESC_CHECKSUMTCPUDPICMPFULL : TCP/UDP/ICMP checksum fully in hardware including pseudo header + * @arg ETH_DMATXDESC_CHECKSUMTCPUDPICMPFULL : TCP/UDP/ICMP checksum fully in hardware including pseudo header * @retval None */ #define __HAL_ETH_DMATXDESC_CHECKSUM_INSERTION(__HANDLE__, __CHECKSUM__) ((__HANDLE__)->TxDesc->Status |= (__CHECKSUM__)) @@ -1842,7 +1819,7 @@ typedef struct * @retval None */ #define __HAL_ETH_MMC_COUNTER_HALF_PRESET(__HANDLE__) do{(__HANDLE__)->Instance->MMCCR &= ~ETH_MMCCR_MCFHP;\ - (__HANDLE__)->Instance->MMCCR |= ETH_MMCCR_MCP;} while(0U) + (__HANDLE__)->Instance->MMCCR |= ETH_MMCCR_MCP;} while (0) /** * @brief Enables the MMC Counter Freeze. @@ -1903,7 +1880,7 @@ typedef struct * @arg ETH_MMC_IT_RFCE : When Rx crc error counter reaches half the maximum value * @retval None */ -#define __HAL_ETH_MMC_RX_IT_ENABLE(__HANDLE__, __INTERRUPT__) (__HANDLE__)->Instance->MMCRIMR &= ~((__INTERRUPT__) & 0xEFFFFFFFU) +#define __HAL_ETH_MMC_RX_IT_ENABLE(__HANDLE__, __INTERRUPT__) (__HANDLE__)->Instance->MMCRIMR &= ~((__INTERRUPT__) & 0xEFFFFFFF) /** * @brief Disables the specified ETHERNET MMC Rx interrupts. * @param __HANDLE__: ETH Handle. @@ -1914,7 +1891,7 @@ typedef struct * @arg ETH_MMC_IT_RFCE : When Rx crc error counter reaches half the maximum value * @retval None */ -#define __HAL_ETH_MMC_RX_IT_DISABLE(__HANDLE__, __INTERRUPT__) (__HANDLE__)->Instance->MMCRIMR |= ((__INTERRUPT__) & 0xEFFFFFFFU) +#define __HAL_ETH_MMC_RX_IT_DISABLE(__HANDLE__, __INTERRUPT__) (__HANDLE__)->Instance->MMCRIMR |= ((__INTERRUPT__) & 0xEFFFFFFF) /** * @brief Enables the specified ETHERNET MMC Tx interrupts. * @param __HANDLE__: ETH Handle. @@ -1980,17 +1957,17 @@ typedef struct * @retval None */ #define __HAL_ETH_WAKEUP_EXTI_ENABLE_RISING_EDGE_TRIGGER() EXTI->RTSR |= ETH_EXTI_LINE_WAKEUP - + /** * @brief Disables the rising edge trigger to the ETH External interrupt line. * @retval None */ -#define __HAL_ETH_WAKEUP_EXTI_DISABLE_RISING_EDGE_TRIGGER() EXTI->RTSR &= ~(ETH_EXTI_LINE_WAKEUP) +#define __HAL_ETH_WAKEUP_EXTI_DISABLE_RISING_EDGE_TRIGGER() EXTI->RTSR &= ~(ETH_EXTI_LINE_WAKEUP) /** * @brief Enables falling edge trigger to the ETH External interrupt line. * @retval None - */ + */ #define __HAL_ETH_WAKEUP_EXTI_ENABLE_FALLING_EDGE_TRIGGER() EXTI->FTSR |= (ETH_EXTI_LINE_WAKEUP) /** @@ -1998,22 +1975,27 @@ typedef struct * @retval None */ #define __HAL_ETH_WAKEUP_EXTI_DISABLE_FALLING_EDGE_TRIGGER() EXTI->FTSR &= ~(ETH_EXTI_LINE_WAKEUP) + /** * @brief Enables rising/falling edge trigger to the ETH External interrupt line. * @retval None */ -#define __HAL_ETH_WAKEUP_EXTI_ENABLE_FALLINGRISING_TRIGGER() do{EXTI->RTSR |= ETH_EXTI_LINE_WAKEUP;\ - EXTI->FTSR |= ETH_EXTI_LINE_WAKEUP;\ - }while(0U) +#define __HAL_ETH_WAKEUP_EXTI_ENABLE_FALLINGRISING_TRIGGER() \ + do{ \ + EXTI->RTSR |= ETH_EXTI_LINE_WAKEUP;\ + EXTI->FTSR |= ETH_EXTI_LINE_WAKEUP;\ + } while(0) /** * @brief Disables rising/falling edge trigger to the ETH External interrupt line. * @retval None */ -#define __HAL_ETH_WAKEUP_EXTI_DISABLE_FALLINGRISING_TRIGGER() do{EXTI->RTSR &= ~(ETH_EXTI_LINE_WAKEUP);\ - EXTI->FTSR &= ~(ETH_EXTI_LINE_WAKEUP);\ - }while(0U) +#define __HAL_ETH_WAKEUP_EXTI_DISABLE_FALLINGRISING_TRIGGER() \ + do{ \ + EXTI->RTSR &= ~(ETH_EXTI_LINE_WAKEUP);\ + EXTI->FTSR &= ~(ETH_EXTI_LINE_WAKEUP);\ + } while(0) /** * @brief Generate a Software interrupt on selected EXTI line. @@ -2024,6 +2006,7 @@ typedef struct /** * @} */ + /* Exported functions --------------------------------------------------------*/ /** @addtogroup ETH_Exported_Functions @@ -2035,6 +2018,7 @@ typedef struct /** @addtogroup ETH_Exported_Functions_Group1 * @{ */ + HAL_StatusTypeDef HAL_ETH_Init(ETH_HandleTypeDef *heth); HAL_StatusTypeDef HAL_ETH_DeInit(ETH_HandleTypeDef *heth); void HAL_ETH_MspInit(ETH_HandleTypeDef *heth); @@ -2045,6 +2029,7 @@ HAL_StatusTypeDef HAL_ETH_DMARxDescListInit(ETH_HandleTypeDef *heth, ETH_DMADesc /** * @} */ + /* IO operation functions ****************************************************/ /** @addtogroup ETH_Exported_Functions_Group2 @@ -2055,13 +2040,14 @@ HAL_StatusTypeDef HAL_ETH_GetReceivedFrame(ETH_HandleTypeDef *heth); /* Communication with PHY functions*/ HAL_StatusTypeDef HAL_ETH_ReadPHYRegister(ETH_HandleTypeDef *heth, uint16_t PHYReg, uint32_t *RegValue); HAL_StatusTypeDef HAL_ETH_WritePHYRegister(ETH_HandleTypeDef *heth, uint16_t PHYReg, uint32_t RegValue); -/* Non-Blocking mode: Interrupt */ + /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_ETH_GetReceivedFrame_IT(ETH_HandleTypeDef *heth); void HAL_ETH_IRQHandler(ETH_HandleTypeDef *heth); -/* Callback in non blocking modes (Interrupt) */ + /* Callback in non blocking modes (Interrupt) */ void HAL_ETH_TxCpltCallback(ETH_HandleTypeDef *heth); void HAL_ETH_RxCpltCallback(ETH_HandleTypeDef *heth); void HAL_ETH_ErrorCallback(ETH_HandleTypeDef *heth); + /** * @} */ @@ -2071,7 +2057,6 @@ void HAL_ETH_ErrorCallback(ETH_HandleTypeDef *heth); /** @addtogroup ETH_Exported_Functions_Group3 * @{ */ - HAL_StatusTypeDef HAL_ETH_Start(ETH_HandleTypeDef *heth); HAL_StatusTypeDef HAL_ETH_Stop(ETH_HandleTypeDef *heth); HAL_StatusTypeDef HAL_ETH_ConfigMAC(ETH_HandleTypeDef *heth, ETH_MACInitTypeDef *macconf); @@ -2079,21 +2064,22 @@ HAL_StatusTypeDef HAL_ETH_ConfigDMA(ETH_HandleTypeDef *heth, ETH_DMAInitTypeDef /** * @} */ - + /* Peripheral State functions ************************************************/ /** @addtogroup ETH_Exported_Functions_Group4 * @{ */ HAL_ETH_StateTypeDef HAL_ETH_GetState(ETH_HandleTypeDef *heth); + /** * @} */ - + /** * @} - */ - + */ + /** * @} */ @@ -2101,7 +2087,7 @@ HAL_ETH_StateTypeDef HAL_ETH_GetState(ETH_HandleTypeDef *heth); #endif /* STM32F107xC */ /** * @} - */ + */ #ifdef __cplusplus } @@ -2110,4 +2096,5 @@ HAL_ETH_StateTypeDef HAL_ETH_GetState(ETH_HandleTypeDef *heth); #endif /* __STM32F1xx_HAL_ETH_H */ + /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_flash.c b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_flash.c index 2bbb626f145..5a3330d2585 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_flash.c +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_flash.c @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_hal_flash.c * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief FLASH HAL module driver. * This file provides firmware functions to manage the following * functionalities of the internal FLASH memory: @@ -41,6 +41,7 @@ (++) Lock and Unlock the FLASH interface (++) Erase function: Erase page, erase all pages (++) Program functions: half word, word and doubleword + (#) FLASH Option Bytes Programming functions: this group includes all needed functions to manage the Option Bytes: (++) Lock and Unlock the Option Bytes @@ -57,7 +58,7 @@ includes all needed functions to: (++) Handle FLASH interrupts (++) Wait for last FLASH operation according to its status - (++) Get error flag status + (++) Get error flag status [..] In addition to these function, this driver includes a set of macros allowing to handle the following operations: @@ -147,7 +148,6 @@ FLASH_ProcessTypeDef pFlash; */ static void FLASH_Program_HalfWord(uint32_t Address, uint16_t Data); static void FLASH_SetErrorCode(void); -extern void FLASH_PageErase(uint32_t PageAddress); /** * @} */ @@ -201,13 +201,13 @@ HAL_StatusTypeDef HAL_FLASH_Program(uint32_t TypeProgram, uint32_t Address, uint { #endif /* FLASH_BANK2_END */ /* Wait for last operation to be completed */ - status = FLASH_WaitForLastOperation(FLASH_TIMEOUT_VALUE); + status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE); #if defined(FLASH_BANK2_END) } else { /* Wait for last operation to be completed */ - status = FLASH_WaitForLastOperationBank2(FLASH_TIMEOUT_VALUE); + status = FLASH_WaitForLastOperationBank2((uint32_t)FLASH_TIMEOUT_VALUE); } #endif /* FLASH_BANK2_END */ @@ -216,29 +216,29 @@ HAL_StatusTypeDef HAL_FLASH_Program(uint32_t TypeProgram, uint32_t Address, uint if(TypeProgram == FLASH_TYPEPROGRAM_HALFWORD) { /* Program halfword (16-bit) at a specified address. */ - nbiterations = 1U; + nbiterations = 1; } else if(TypeProgram == FLASH_TYPEPROGRAM_WORD) { /* Program word (32-bit = 2*16-bit) at a specified address. */ - nbiterations = 2U; + nbiterations = 2; } else { /* Program double word (64-bit = 4*16-bit) at a specified address. */ - nbiterations = 4U; + nbiterations = 4; } - for (index = 0U; index < nbiterations; index++) + for (index = 0; index < nbiterations; index++) { - FLASH_Program_HalfWord((Address + (2U*index)), (uint16_t)(Data >> (16U*index))); + FLASH_Program_HalfWord((Address + (2*index)), (uint16_t)(Data >> (16*index))); #if defined(FLASH_BANK2_END) if(Address <= FLASH_BANK1_END) { #endif /* FLASH_BANK2_END */ /* Wait for last operation to be completed */ - status = FLASH_WaitForLastOperation(FLASH_TIMEOUT_VALUE); + status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE); /* If the program operation is completed, disable the PG Bit */ CLEAR_BIT(FLASH->CR, FLASH_CR_PG); @@ -247,7 +247,7 @@ HAL_StatusTypeDef HAL_FLASH_Program(uint32_t TypeProgram, uint32_t Address, uint else { /* Wait for last operation to be completed */ - status = FLASH_WaitForLastOperationBank2(FLASH_TIMEOUT_VALUE); + status = FLASH_WaitForLastOperationBank2((uint32_t)FLASH_TIMEOUT_VALUE); /* If the program operation is completed, disable the PG Bit */ CLEAR_BIT(FLASH->CR2, FLASH_CR2_PG); @@ -321,23 +321,23 @@ HAL_StatusTypeDef HAL_FLASH_Program_IT(uint32_t TypeProgram, uint32_t Address, u if(TypeProgram == FLASH_TYPEPROGRAM_HALFWORD) { pFlash.ProcedureOnGoing = FLASH_PROC_PROGRAMHALFWORD; - /* Program halfword (16-bit) at a specified address. */ - pFlash.DataRemaining = 1U; + /*Program halfword (16-bit) at a specified address.*/ + pFlash.DataRemaining = 1; } else if(TypeProgram == FLASH_TYPEPROGRAM_WORD) { pFlash.ProcedureOnGoing = FLASH_PROC_PROGRAMWORD; - /* Program word (32-bit : 2*16-bit) at a specified address. */ - pFlash.DataRemaining = 2U; + /*Program word (32-bit : 2*16-bit) at a specified address.*/ + pFlash.DataRemaining = 2; } else { pFlash.ProcedureOnGoing = FLASH_PROC_PROGRAMDOUBLEWORD; - /* Program double word (64-bit : 4*16-bit) at a specified address. */ - pFlash.DataRemaining = 4U; + /*Program double word (64-bit : 4*16-bit) at a specified address.*/ + pFlash.DataRemaining = 4; } - /* Program halfword (16-bit) at a specified address. */ + /*Program halfword (16-bit) at a specified address.*/ FLASH_Program_HalfWord(Address, (uint16_t)Data); return status; @@ -349,7 +349,7 @@ HAL_StatusTypeDef HAL_FLASH_Program_IT(uint32_t TypeProgram, uint32_t Address, u */ void HAL_FLASH_IRQHandler(void) { - uint32_t addresstmp = 0U; + uint32_t addresstmp = 0; /* Check FLASH operation error flags */ #if defined(FLASH_BANK2_END) @@ -359,18 +359,18 @@ void HAL_FLASH_IRQHandler(void) if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_WRPERR) ||__HAL_FLASH_GET_FLAG(FLASH_FLAG_PGERR)) #endif /* FLASH_BANK2_END */ { - /* Return the faulty address */ + /*return the faulty address*/ addresstmp = pFlash.Address; /* Reset address */ - pFlash.Address = 0xFFFFFFFFU; + pFlash.Address = 0xFFFFFFFF; - /* Save the Error code */ + /*Save the Error code*/ FLASH_SetErrorCode(); /* FLASH error interrupt user callback */ HAL_FLASH_OperationErrorCallback(addresstmp); - /* Stop the procedure ongoing */ + /* Stop the procedure ongoing*/ pFlash.ProcedureOnGoing = FLASH_PROC_NONE; } @@ -395,11 +395,11 @@ void HAL_FLASH_IRQHandler(void) /* Nb of pages to erased can be decreased */ pFlash.DataRemaining--; - /* Check if there are still pages to erase */ - if(pFlash.DataRemaining != 0U) + /* Check if there are still pages to erase*/ + if(pFlash.DataRemaining != 0) { addresstmp = pFlash.Address; - /*Indicate user which sector has been erased */ + /*Indicate user which sector has been erased*/ HAL_FLASH_EndOfOperationCallback(addresstmp); /*Increment sector number*/ @@ -413,9 +413,9 @@ void HAL_FLASH_IRQHandler(void) } else { - /* No more pages to Erase, user callback can be called. */ - /* Reset Sector and stop Erase pages procedure */ - pFlash.Address = addresstmp = 0xFFFFFFFFU; + /*No more pages to Erase, user callback can be called.*/ + /*Reset Sector and stop Erase pages procedure*/ + pFlash.Address = addresstmp = 0xFFFFFFFF; pFlash.ProcedureOnGoing = FLASH_PROC_NONE; /* FLASH EOP interrupt user callback */ HAL_FLASH_EndOfOperationCallback(addresstmp); @@ -431,9 +431,9 @@ void HAL_FLASH_IRQHandler(void) if (HAL_IS_BIT_CLR(FLASH->CR2, FLASH_CR2_MER)) { #endif /* FLASH_BANK2_END */ - /* MassErase ended. Return the selected bank */ + /* MassErase ended. Return the selected bank*/ /* FLASH EOP interrupt user callback */ - HAL_FLASH_EndOfOperationCallback(0U); + HAL_FLASH_EndOfOperationCallback(0); /* Stop Mass Erase procedure*/ pFlash.ProcedureOnGoing = FLASH_PROC_NONE; @@ -447,14 +447,14 @@ void HAL_FLASH_IRQHandler(void) pFlash.DataRemaining--; /* Check if there are still 16-bit data to program */ - if(pFlash.DataRemaining != 0U) + if(pFlash.DataRemaining != 0) { /* Increment address to 16-bit */ - pFlash.Address += 2U; + pFlash.Address += 2; addresstmp = pFlash.Address; /* Shift to have next 16-bit data */ - pFlash.Data = (pFlash.Data >> 16U); + pFlash.Data = (pFlash.Data >> 16); /* Operation is completed, disable the PG Bit */ CLEAR_BIT(FLASH->CR, FLASH_CR_PG); @@ -464,7 +464,7 @@ void HAL_FLASH_IRQHandler(void) } else { - /* Program ended. Return the selected address */ + /*Program ended. Return the selected address*/ /* FLASH EOP interrupt user callback */ if (pFlash.ProcedureOnGoing == FLASH_PROC_PROGRAMHALFWORD) { @@ -472,15 +472,15 @@ void HAL_FLASH_IRQHandler(void) } else if (pFlash.ProcedureOnGoing == FLASH_PROC_PROGRAMWORD) { - HAL_FLASH_EndOfOperationCallback(pFlash.Address - 2U); + HAL_FLASH_EndOfOperationCallback(pFlash.Address - 2); } else { - HAL_FLASH_EndOfOperationCallback(pFlash.Address - 6U); + HAL_FLASH_EndOfOperationCallback(pFlash.Address - 6); } - /* Reset Address and stop Program procedure */ - pFlash.Address = 0xFFFFFFFFU; + /* Reset Address and stop Program procedure*/ + pFlash.Address = 0xFFFFFFFF; pFlash.ProcedureOnGoing = FLASH_PROC_NONE; } } @@ -503,7 +503,7 @@ void HAL_FLASH_IRQHandler(void) pFlash.DataRemaining--; /* Check if there are still pages to erase*/ - if(pFlash.DataRemaining != 0U) + if(pFlash.DataRemaining != 0) { /* Indicate user which page address has been erased*/ HAL_FLASH_EndOfOperationCallback(pFlash.Address); @@ -522,7 +522,7 @@ void HAL_FLASH_IRQHandler(void) /*No more pages to Erase*/ /*Reset Address and stop Erase pages procedure*/ - pFlash.Address = 0xFFFFFFFFU; + pFlash.Address = 0xFFFFFFFF; pFlash.ProcedureOnGoing = FLASH_PROC_NONE; /* FLASH EOP interrupt user callback */ @@ -538,7 +538,7 @@ void HAL_FLASH_IRQHandler(void) { /* MassErase ended. Return the selected bank*/ /* FLASH EOP interrupt user callback */ - HAL_FLASH_EndOfOperationCallback(0U); + HAL_FLASH_EndOfOperationCallback(0); pFlash.ProcedureOnGoing = FLASH_PROC_NONE; } @@ -549,14 +549,14 @@ void HAL_FLASH_IRQHandler(void) pFlash.DataRemaining--; /* Check if there are still 16-bit data to program */ - if(pFlash.DataRemaining != 0U) + if(pFlash.DataRemaining != 0) { /* Increment address to 16-bit */ - pFlash.Address += 2U; + pFlash.Address += 2; addresstmp = pFlash.Address; /* Shift to have next 16-bit data */ - pFlash.Data = (pFlash.Data >> 16U); + pFlash.Data = (pFlash.Data >> 16); /* Operation is completed, disable the PG Bit */ CLEAR_BIT(FLASH->CR2, FLASH_CR2_PG); @@ -574,15 +574,15 @@ void HAL_FLASH_IRQHandler(void) } else if (pFlash.ProcedureOnGoing == FLASH_PROC_PROGRAMWORD) { - HAL_FLASH_EndOfOperationCallback(pFlash.Address-2U); + HAL_FLASH_EndOfOperationCallback(pFlash.Address-2); } else { - HAL_FLASH_EndOfOperationCallback(pFlash.Address-6U); + HAL_FLASH_EndOfOperationCallback(pFlash.Address-6); } /* Reset Address and stop Program procedure*/ - pFlash.Address = 0xFFFFFFFFU; + pFlash.Address = 0xFFFFFFFF; pFlash.ProcedureOnGoing = FLASH_PROC_NONE; } } @@ -612,6 +612,7 @@ void HAL_FLASH_IRQHandler(void) } } + /** * @brief FLASH end of operation interrupt callback * @param ReturnValue: The value saved in this parameter depends on the ongoing procedure @@ -625,7 +626,6 @@ __weak void HAL_FLASH_EndOfOperationCallback(uint32_t ReturnValue) { /* Prevent unused argument(s) compilation warning */ UNUSED(ReturnValue); - /* NOTE : This function Should not be modified, when the callback is needed, the HAL_FLASH_EndOfOperationCallback could be implemented in the user file */ @@ -643,7 +643,6 @@ __weak void HAL_FLASH_OperationErrorCallback(uint32_t ReturnValue) { /* Prevent unused argument(s) compilation warning */ UNUSED(ReturnValue); - /* NOTE : This function Should not be modified, when the callback is needed, the HAL_FLASH_OperationErrorCallback could be implemented in the user file */ @@ -713,11 +712,12 @@ HAL_StatusTypeDef HAL_FLASH_Lock(void) #if defined(FLASH_BANK2_END) /* Set the LOCK Bit to lock the FLASH BANK2 Registers access */ SET_BIT(FLASH->CR2, FLASH_CR2_LOCK); - #endif /* FLASH_BANK2_END */ + return HAL_OK; } + /** * @brief Unlock the FLASH Option Control Registers access. * @retval HAL Status @@ -753,27 +753,29 @@ HAL_StatusTypeDef HAL_FLASH_OB_Lock(void) /** * @brief Launch the option byte loading. * @note This function will reset automatically the MCU. - * @retval None + * @retval HAL_StatusTypeDef HAL Status */ -void HAL_FLASH_OB_Launch(void) +HAL_StatusTypeDef HAL_FLASH_OB_Launch(void) { /* Initiates a system reset request to launch the option byte loading */ HAL_NVIC_SystemReset(); + + return HAL_OK; } /** * @} */ -/** @defgroup FLASH_Exported_Functions_Group3 Peripheral errors functions - * @brief Peripheral errors functions +/** @defgroup FLASH_Exported_Functions_Group3 Peripheral State functions + * @brief Peripheral State functions * @verbatim =============================================================================== - ##### Peripheral Errors functions ##### + ##### Peripheral State functions ##### =============================================================================== [..] - This subsection permit to get in run-time errors of the FLASH peripheral. + This subsection permit to get in run-time the status of the FLASH peripheral. @endverbatim * @{ @@ -781,14 +783,13 @@ void HAL_FLASH_OB_Launch(void) /** * @brief Get the specific FLASH error flag. - * @retval FLASH_ErrorCode The returned value can be: + * @retval FLASH_ErrorCode: The returned value can be: * @ref FLASH_Error_Codes */ uint32_t HAL_FLASH_GetError(void) -{ +{ return pFlash.ErrorCode; -} - +} /** * @} */ @@ -803,8 +804,8 @@ uint32_t HAL_FLASH_GetError(void) /** * @brief Program a half-word (16-bit) at a specified address. - * @param Address specify the address to be programmed. - * @param Data specify the data to be programmed. + * @param Address: specifies the address to be programmed. + * @param Data: specifies the data to be programmed. * @retval None */ static void FLASH_Program_HalfWord(uint32_t Address, uint16_t Data) @@ -833,8 +834,8 @@ static void FLASH_Program_HalfWord(uint32_t Address, uint16_t Data) /** * @brief Wait for a FLASH operation to complete. - * @param Timeout maximum flash operation timeout - * @retval HAL Status + * @param Timeout: maximum flash operation timeout + * @retval HAL_StatusTypeDef HAL Status */ HAL_StatusTypeDef FLASH_WaitForLastOperation(uint32_t Timeout) { @@ -848,7 +849,7 @@ HAL_StatusTypeDef FLASH_WaitForLastOperation(uint32_t Timeout) { if (Timeout != HAL_MAX_DELAY) { - if((Timeout == 0U) || ((HAL_GetTick()-tickstart) > Timeout)) + if((Timeout == 0) || ((HAL_GetTick()-tickstart) > Timeout)) { return HAL_TIMEOUT; } @@ -871,14 +872,14 @@ HAL_StatusTypeDef FLASH_WaitForLastOperation(uint32_t Timeout) return HAL_ERROR; } - /* There is no error flag set */ + /* If there is no error flag set */ return HAL_OK; } #if defined(FLASH_BANK2_END) /** * @brief Wait for a FLASH BANK2 operation to complete. - * @param Timeout maximum flash operation timeout + * @param Timeout: maximum flash operation timeout * @retval HAL_StatusTypeDef HAL Status */ HAL_StatusTypeDef FLASH_WaitForLastOperationBank2(uint32_t Timeout) @@ -893,7 +894,7 @@ HAL_StatusTypeDef FLASH_WaitForLastOperationBank2(uint32_t Timeout) { if (Timeout != HAL_MAX_DELAY) { - if((Timeout == 0U) || ((HAL_GetTick()-tickstart) > Timeout)) + if((Timeout == 0) || ((HAL_GetTick()-tickstart) > Timeout)) { return HAL_TIMEOUT; } @@ -925,9 +926,7 @@ HAL_StatusTypeDef FLASH_WaitForLastOperationBank2(uint32_t Timeout) * @retval None */ static void FLASH_SetErrorCode(void) -{ - uint32_t flags = 0U; - +{ #if defined(FLASH_BANK2_END) if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_WRPERR) || __HAL_FLASH_GET_FLAG(FLASH_FLAG_WRPERR_BANK2)) #else @@ -935,11 +934,6 @@ static void FLASH_SetErrorCode(void) #endif /* FLASH_BANK2_END */ { pFlash.ErrorCode |= HAL_FLASH_ERROR_WRP; -#if defined(FLASH_BANK2_END) - flags |= FLASH_FLAG_WRPERR | FLASH_FLAG_WRPERR_BANK2; -#else - flags |= FLASH_FLAG_WRPERR; -#endif /* FLASH_BANK2_END */ } #if defined(FLASH_BANK2_END) if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_PGERR) || __HAL_FLASH_GET_FLAG(FLASH_FLAG_PGERR_BANK2)) @@ -947,21 +941,21 @@ static void FLASH_SetErrorCode(void) if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_PGERR)) #endif /* FLASH_BANK2_END */ { - pFlash.ErrorCode |= HAL_FLASH_ERROR_PROG; -#if defined(FLASH_BANK2_END) - flags |= FLASH_FLAG_PGERR | FLASH_FLAG_PGERR_BANK2; -#else - flags |= FLASH_FLAG_PGERR; -#endif /* FLASH_BANK2_END */ + pFlash.ErrorCode |= HAL_FLASH_ERROR_PROG; } + if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_OPTVERR)) { - pFlash.ErrorCode |= HAL_FLASH_ERROR_OPTV; - __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_OPTVERR); + pFlash.ErrorCode |= HAL_FLASH_ERROR_OPTV; + __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_OPTVERR); } /* Clear FLASH error pending bits */ - __HAL_FLASH_CLEAR_FLAG(flags); +#if defined(FLASH_BANK2_END) + __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_WRPERR | FLASH_FLAG_WRPERR_BANK2 | FLASH_FLAG_PGERR | FLASH_FLAG_PGERR_BANK2); +#else + __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_WRPERR | FLASH_FLAG_PGERR); +#endif /* FLASH_BANK2_END */ } /** * @} diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_flash.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_flash.h index 3016b549591..abb0fa4564c 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_flash.h +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_flash.h @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_hal_flash.h * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief Header file of Flash HAL module. ****************************************************************************** * @attention @@ -57,7 +57,7 @@ /** @addtogroup FLASH_Private_Constants * @{ */ -#define FLASH_TIMEOUT_VALUE 50000U /* 50 s */ +#define FLASH_TIMEOUT_VALUE ((uint32_t)50000)/* 50 s */ /** * @} */ @@ -87,17 +87,18 @@ * @{ */ + /** * @brief FLASH Procedure structure definition */ typedef enum { - FLASH_PROC_NONE = 0U, - FLASH_PROC_PAGEERASE = 1U, - FLASH_PROC_MASSERASE = 2U, - FLASH_PROC_PROGRAMHALFWORD = 3U, - FLASH_PROC_PROGRAMWORD = 4U, - FLASH_PROC_PROGRAMDOUBLEWORD = 5U + FLASH_PROC_NONE = 0, + FLASH_PROC_PAGEERASE = 1, + FLASH_PROC_MASSERASE = 2, + FLASH_PROC_PROGRAMHALFWORD = 3, + FLASH_PROC_PROGRAMWORD = 4, + FLASH_PROC_PROGRAMDOUBLEWORD = 5 } FLASH_ProcedureTypeDef; /** @@ -132,10 +133,10 @@ typedef struct * @{ */ -#define HAL_FLASH_ERROR_NONE 0x00U /*!< No error */ -#define HAL_FLASH_ERROR_PROG 0x01U /*!< Programming error */ -#define HAL_FLASH_ERROR_WRP 0x02U /*!< Write protection error */ -#define HAL_FLASH_ERROR_OPTV 0x04U /*!< Option validity error */ +#define HAL_FLASH_ERROR_NONE ((uint32_t)0x00) /*!< No error */ +#define HAL_FLASH_ERROR_PROG ((uint32_t)0x01) /*!< Programming error */ +#define HAL_FLASH_ERROR_WRP ((uint32_t)0x02) /*!< Write protection error */ +#define HAL_FLASH_ERROR_OPTV ((uint32_t)0x04) /*!< Option validity error */ /** * @} @@ -144,9 +145,9 @@ typedef struct /** @defgroup FLASH_Type_Program FLASH Type Program * @{ */ -#define FLASH_TYPEPROGRAM_HALFWORD 0x01U /*!PageAddress; @@ -291,7 +290,7 @@ HAL_StatusTypeDef HAL_FLASHEx_Erase(FLASH_EraseInitTypeDef *pEraseInit, uint32_t if (FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE) == HAL_OK) { /*Initialization of PageError variable*/ - *PageError = 0xFFFFFFFFU; + *PageError = 0xFFFFFFFF; /* Erase page by page to be done*/ for(address = pEraseInit->PageAddress; @@ -636,10 +635,6 @@ static void FLASH_MassErase(uint32_t Banks) else { #endif /* FLASH_BANK2_END */ -#if !defined(FLASH_BANK2_END) - /* Prevent unused argument(s) compilation warning */ - UNUSED(Banks); -#endif /* FLASH_BANK2_END */ /* Only bank1 will be erased*/ SET_BIT(FLASH->CR, FLASH_CR_MER); SET_BIT(FLASH->CR, FLASH_CR_STRT); @@ -686,26 +681,26 @@ static HAL_StatusTypeDef FLASH_OB_EnableWRP(uint32_t WriteProtectPage) #endif /* OB_WRP_PAGES0TO31MASK */ #if defined(OB_WRP_PAGES16TO31MASK) - WRP1_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES16TO31MASK) >> 8U); + WRP1_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES16TO31MASK) >> 8); #elif defined(OB_WRP_PAGES32TO63MASK) - WRP1_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES32TO63MASK) >> 8U); + WRP1_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES32TO63MASK) >> 8); #endif /* OB_WRP_PAGES32TO63MASK */ #if defined(OB_WRP_PAGES64TO95MASK) - WRP2_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES64TO95MASK) >> 16U); + WRP2_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES64TO95MASK) >> 16); #endif /* OB_WRP_PAGES64TO95MASK */ #if defined(OB_WRP_PAGES32TO47MASK) - WRP2_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES32TO47MASK) >> 16U); + WRP2_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES32TO47MASK) >> 16); #endif /* OB_WRP_PAGES32TO47MASK */ #if defined(OB_WRP_PAGES96TO127MASK) - WRP3_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES96TO127MASK) >> 24U); + WRP3_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES96TO127MASK) >> 24); #elif defined(OB_WRP_PAGES48TO255MASK) - WRP3_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES48TO255MASK) >> 24U); + WRP3_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES48TO255MASK) >> 24); #elif defined(OB_WRP_PAGES48TO511MASK) - WRP3_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES48TO511MASK) >> 24U); + WRP3_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES48TO511MASK) >> 24); #elif defined(OB_WRP_PAGES48TO127MASK) - WRP3_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES48TO127MASK) >> 24U); + WRP3_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES48TO127MASK) >> 24); #endif /* OB_WRP_PAGES96TO127MASK */ /* Wait for last operation to be completed */ @@ -724,7 +719,7 @@ static HAL_StatusTypeDef FLASH_OB_EnableWRP(uint32_t WriteProtectPage) SET_BIT(FLASH->CR, FLASH_CR_OPTPG); #if defined(FLASH_WRP0_WRP0) - if(WRP0_Data != 0xFFU) + if(WRP0_Data != 0xFF) { OB->WRP0 &= WRP0_Data; @@ -734,7 +729,7 @@ static HAL_StatusTypeDef FLASH_OB_EnableWRP(uint32_t WriteProtectPage) #endif /* FLASH_WRP0_WRP0 */ #if defined(FLASH_WRP1_WRP1) - if((status == HAL_OK) && (WRP1_Data != 0xFFU)) + if((status == HAL_OK) && (WRP1_Data != 0xFF)) { OB->WRP1 &= WRP1_Data; @@ -744,7 +739,7 @@ static HAL_StatusTypeDef FLASH_OB_EnableWRP(uint32_t WriteProtectPage) #endif /* FLASH_WRP1_WRP1 */ #if defined(FLASH_WRP2_WRP2) - if((status == HAL_OK) && (WRP2_Data != 0xFFU)) + if((status == HAL_OK) && (WRP2_Data != 0xFF)) { OB->WRP2 &= WRP2_Data; @@ -754,7 +749,7 @@ static HAL_StatusTypeDef FLASH_OB_EnableWRP(uint32_t WriteProtectPage) #endif /* FLASH_WRP2_WRP2 */ #if defined(FLASH_WRP3_WRP3) - if((status == HAL_OK) && (WRP3_Data != 0xFFU)) + if((status == HAL_OK) && (WRP3_Data != 0xFF)) { OB->WRP3 &= WRP3_Data; @@ -809,26 +804,26 @@ static HAL_StatusTypeDef FLASH_OB_DisableWRP(uint32_t WriteProtectPage) #endif /* OB_WRP_PAGES0TO31MASK */ #if defined(OB_WRP_PAGES16TO31MASK) - WRP1_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES16TO31MASK) >> 8U); + WRP1_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES16TO31MASK) >> 8); #elif defined(OB_WRP_PAGES32TO63MASK) - WRP1_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES32TO63MASK) >> 8U); + WRP1_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES32TO63MASK) >> 8); #endif /* OB_WRP_PAGES32TO63MASK */ #if defined(OB_WRP_PAGES64TO95MASK) - WRP2_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES64TO95MASK) >> 16U); + WRP2_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES64TO95MASK) >> 16); #endif /* OB_WRP_PAGES64TO95MASK */ #if defined(OB_WRP_PAGES32TO47MASK) - WRP2_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES32TO47MASK) >> 16U); + WRP2_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES32TO47MASK) >> 16); #endif /* OB_WRP_PAGES32TO47MASK */ #if defined(OB_WRP_PAGES96TO127MASK) - WRP3_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES96TO127MASK) >> 24U); + WRP3_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES96TO127MASK) >> 24); #elif defined(OB_WRP_PAGES48TO255MASK) - WRP3_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES48TO255MASK) >> 24U); + WRP3_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES48TO255MASK) >> 24); #elif defined(OB_WRP_PAGES48TO511MASK) - WRP3_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES48TO511MASK) >> 24U); + WRP3_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES48TO511MASK) >> 24); #elif defined(OB_WRP_PAGES48TO127MASK) - WRP3_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES48TO127MASK) >> 24U); + WRP3_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES48TO127MASK) >> 24); #endif /* OB_WRP_PAGES96TO127MASK */ @@ -847,7 +842,7 @@ static HAL_StatusTypeDef FLASH_OB_DisableWRP(uint32_t WriteProtectPage) SET_BIT(FLASH->CR, FLASH_CR_OPTPG); #if defined(FLASH_WRP0_WRP0) - if(WRP0_Data != 0xFFU) + if(WRP0_Data != 0xFF) { OB->WRP0 |= WRP0_Data; @@ -857,7 +852,7 @@ static HAL_StatusTypeDef FLASH_OB_DisableWRP(uint32_t WriteProtectPage) #endif /* FLASH_WRP0_WRP0 */ #if defined(FLASH_WRP1_WRP1) - if((status == HAL_OK) && (WRP1_Data != 0xFFU)) + if((status == HAL_OK) && (WRP1_Data != 0xFF)) { OB->WRP1 |= WRP1_Data; @@ -867,7 +862,7 @@ static HAL_StatusTypeDef FLASH_OB_DisableWRP(uint32_t WriteProtectPage) #endif /* FLASH_WRP1_WRP1 */ #if defined(FLASH_WRP2_WRP2) - if((status == HAL_OK) && (WRP2_Data != 0xFFU)) + if((status == HAL_OK) && (WRP2_Data != 0xFF)) { OB->WRP2 |= WRP2_Data; @@ -877,7 +872,7 @@ static HAL_StatusTypeDef FLASH_OB_DisableWRP(uint32_t WriteProtectPage) #endif /* FLASH_WRP2_WRP2 */ #if defined(FLASH_WRP3_WRP3) - if((status == HAL_OK) && (WRP3_Data != 0xFFU)) + if((status == HAL_OK) && (WRP3_Data != 0xFF)) { OB->WRP3 |= WRP3_Data; @@ -976,9 +971,9 @@ static HAL_StatusTypeDef FLASH_OB_UserConfig(uint8_t UserConfig) SET_BIT(FLASH->CR, FLASH_CR_OPTPG); #if defined(FLASH_BANK2_END) - OB->USER = (UserConfig | 0xF0U); + OB->USER = (UserConfig | 0xF0); #else - OB->USER = (UserConfig | 0x88U); + OB->USER = (UserConfig | 0x88); #endif /* FLASH_BANK2_END */ /* Wait for last operation to be completed */ @@ -1044,7 +1039,7 @@ static uint32_t FLASH_OB_GetWRP(void) /** * @brief Returns the FLASH Read Protection level. - * @retval FLASH RDP level + * @retval FLASH ReadOut Protection Status: * This parameter can be one of the following values: * @arg @ref OB_RDP_LEVEL_0 No protection * @arg @ref OB_RDP_LEVEL_1 Read protection of the memory @@ -1052,7 +1047,7 @@ static uint32_t FLASH_OB_GetWRP(void) static uint32_t FLASH_OB_GetRDP(void) { uint32_t readstatus = OB_RDP_LEVEL_0; - uint32_t tmp_reg = 0U; + uint32_t tmp_reg = 0; /* Read RDP level bits */ tmp_reg = READ_BIT(FLASH->OBR, FLASH_OBR_RDPRT); diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_flash_ex.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_flash_ex.h index 9dd06f54b23..a77c2a82ffc 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_flash_ex.h +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_flash_ex.h @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_hal_flash_ex.h * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief Header file of Flash HAL Extended module. ****************************************************************************** * @attention @@ -58,9 +58,9 @@ * @{ */ -#define FLASH_SIZE_DATA_REGISTER 0x1FFFF7E0U -#define OBR_REG_INDEX 1U -#define SR_FLAG_MASK ((uint32_t)(FLASH_SR_BSY | FLASH_SR_PGERR | FLASH_SR_WRPRTERR | FLASH_SR_EOP)) +#define FLASH_SIZE_DATA_REGISTER ((uint32_t)0x1FFFF7E0) +#define OBR_REG_INDEX ((uint32_t)1) +#define SR_FLAG_MASK ((uint32_t)(FLASH_SR_BSY | FLASH_SR_PGERR | FLASH_SR_WRPRTERR | FLASH_SR_EOP)) /** * @} @@ -74,7 +74,7 @@ #define IS_OPTIONBYTE(VALUE) (((VALUE) <= (OPTIONBYTE_WRP | OPTIONBYTE_RDP | OPTIONBYTE_USER | OPTIONBYTE_DATA))) -#define IS_WRPSTATE(VALUE) (((VALUE) == OB_WRPSTATE_DISABLE) || ((VALUE) == OB_WRPSTATE_ENABLE)) +#define IS_WRPSTATE(VALUE) (((VALUE) == OB_WRPSTATE_DISABLE) || ((VALUE) == OB_WRPSTATE_ENABLE)) #define IS_OB_RDP_LEVEL(LEVEL) (((LEVEL) == OB_RDP_LEVEL_0) || ((LEVEL) == OB_RDP_LEVEL_1)) @@ -92,39 +92,39 @@ /* Low Density */ #if (defined(STM32F101x6) || defined(STM32F102x6) || defined(STM32F103x6)) -#define IS_FLASH_NB_PAGES(ADDRESS,NBPAGES) (((*((uint16_t *)FLASH_SIZE_DATA_REGISTER)) == 0x20U) ? ((ADDRESS)+((NBPAGES)*FLASH_PAGE_SIZE)- 1 <= 0x08007FFFU) : \ - ((ADDRESS)+((NBPAGES)*FLASH_PAGE_SIZE)- 1 <= 0x08003FFFU)) +#define IS_FLASH_NB_PAGES(ADDRESS,NBPAGES) (((*((uint16_t *)FLASH_SIZE_DATA_REGISTER)) == 0x20) ? ((ADDRESS)+((NBPAGES)*FLASH_PAGE_SIZE)-1 <= 0x08007FFF) : \ + ((ADDRESS)+((NBPAGES)*FLASH_PAGE_SIZE)-1 <= 0x08003FFF)) #endif /* STM32F101x6 || STM32F102x6 || STM32F103x6 */ /* Medium Density */ #if (defined(STM32F100xB) || defined(STM32F101xB) || defined(STM32F102xB) || defined(STM32F103xB)) -#define IS_FLASH_NB_PAGES(ADDRESS,NBPAGES) (((*((uint16_t *)FLASH_SIZE_DATA_REGISTER)) == 0x80U) ? ((ADDRESS)+((NBPAGES)*FLASH_PAGE_SIZE)-1 <= 0x0801FFFFU) : \ - (((*((uint16_t *)FLASH_SIZE_DATA_REGISTER)) == 0x40U) ? ((ADDRESS)+((NBPAGES)*FLASH_PAGE_SIZE)-1 <= 0x0800FFFFU) : \ - (((*((uint16_t *)FLASH_SIZE_DATA_REGISTER)) == 0x20U) ? ((ADDRESS)+((NBPAGES)*FLASH_PAGE_SIZE)-1 <= 0x08007FFFU) : \ - ((ADDRESS)+((NBPAGES)*FLASH_PAGE_SIZE)-1 <= 0x08003FFFU)))) +#define IS_FLASH_NB_PAGES(ADDRESS,NBPAGES) (((*((uint16_t *)FLASH_SIZE_DATA_REGISTER)) == 0x80) ? ((ADDRESS)+((NBPAGES)*FLASH_PAGE_SIZE)-1 <= 0x0801FFFF) : \ + (((*((uint16_t *)FLASH_SIZE_DATA_REGISTER)) == 0x40) ? ((ADDRESS)+((NBPAGES)*FLASH_PAGE_SIZE)-1 <= 0x0800FFFF) : \ + (((*((uint16_t *)FLASH_SIZE_DATA_REGISTER)) == 0x20) ? ((ADDRESS)+((NBPAGES)*FLASH_PAGE_SIZE)-1 <= 0x08007FFF) : \ + ((ADDRESS)+((NBPAGES)*FLASH_PAGE_SIZE)-1 <= 0x08003FFF)))) #endif /* STM32F100xB || STM32F101xB || STM32F102xB || STM32F103xB*/ /* High Density */ #if (defined(STM32F100xE) || defined(STM32F101xE) || defined(STM32F103xE)) -#define IS_FLASH_NB_PAGES(ADDRESS,NBPAGES) (((*((uint16_t *)FLASH_SIZE_DATA_REGISTER)) == 0x200U) ? ((ADDRESS)+((NBPAGES)*FLASH_PAGE_SIZE)-1 <= 0x0807FFFFU) : \ - (((*((uint16_t *)FLASH_SIZE_DATA_REGISTER)) == 0x180U) ? ((ADDRESS)+((NBPAGES)*FLASH_PAGE_SIZE)-1 <= 0x0805FFFFU) : \ - ((ADDRESS)+((NBPAGES)*FLASH_PAGE_SIZE)-1 <= 0x0803FFFFU))) +#define IS_FLASH_NB_PAGES(ADDRESS,NBPAGES) (((*((uint16_t *)FLASH_SIZE_DATA_REGISTER)) == 0x200) ? ((ADDRESS)+((NBPAGES)*FLASH_PAGE_SIZE)-1 <= 0x0807FFFF) : \ + (((*((uint16_t *)FLASH_SIZE_DATA_REGISTER)) == 0x180) ? ((ADDRESS)+((NBPAGES)*FLASH_PAGE_SIZE)-1 <= 0x0805FFFF) : \ + ((ADDRESS)+((NBPAGES)*FLASH_PAGE_SIZE)-1 <= 0x0803FFFF))) #endif /* STM32F100xE || STM32F101xE || STM32F103xE */ /* XL Density */ #if defined(FLASH_BANK2_END) -#define IS_FLASH_NB_PAGES(ADDRESS,NBPAGES) (((*((uint16_t *)FLASH_SIZE_DATA_REGISTER)) == 0x400U) ? ((ADDRESS)+((NBPAGES)*FLASH_PAGE_SIZE)-1 <= 0x080FFFFFU) : \ - ((ADDRESS)+((NBPAGES)*FLASH_PAGE_SIZE)-1 <= 0x080BFFFFU)) +#define IS_FLASH_NB_PAGES(ADDRESS,NBPAGES) (((*((uint16_t *)FLASH_SIZE_DATA_REGISTER)) == 0x400) ? ((ADDRESS)+((NBPAGES)*FLASH_PAGE_SIZE)-1 <= 0x080FFFFF) : \ + ((ADDRESS)+((NBPAGES)*FLASH_PAGE_SIZE)-1 <= 0x080BFFFF)) #endif /* FLASH_BANK2_END */ /* Connectivity Line */ #if (defined(STM32F105xC) || defined(STM32F107xC)) -#define IS_FLASH_NB_PAGES(ADDRESS,NBPAGES) (((*((uint16_t *)FLASH_SIZE_DATA_REGISTER)) == 0x100U) ? ((ADDRESS)+((NBPAGES)*FLASH_PAGE_SIZE)-1 <= 0x0803FFFFU) : \ - (((*((uint16_t *)FLASH_SIZE_DATA_REGISTER)) == 0x80U) ? ((ADDRESS)+((NBPAGES)*FLASH_PAGE_SIZE)-1 <= 0x0801FFFFU) : \ - ((ADDRESS)+((NBPAGES)*FLASH_PAGE_SIZE)-1 <= 0x0800FFFFU))) +#define IS_FLASH_NB_PAGES(ADDRESS,NBPAGES) (((*((uint16_t *)FLASH_SIZE_DATA_REGISTER)) == 0x100) ? ((ADDRESS)+((NBPAGES)*FLASH_PAGE_SIZE)-1 <= 0x0803FFFF) : \ + (((*((uint16_t *)FLASH_SIZE_DATA_REGISTER)) == 0x80) ? ((ADDRESS)+((NBPAGES)*FLASH_PAGE_SIZE)-1 <= 0x0801FFFF) : \ + ((ADDRESS)+((NBPAGES)*FLASH_PAGE_SIZE)-1 <= 0x0800FFFF))) #endif /* STM32F105xC || STM32F107xC */ -#define IS_OB_WRP(PAGE) (((PAGE) != 0x0000000U)) +#define IS_OB_WRP(PAGE) (((PAGE) != 0x0000000)) #if defined(FLASH_BANK2_END) #define IS_FLASH_BANK(BANK) (((BANK) == FLASH_BANK_1) || \ @@ -136,40 +136,40 @@ /* Low Density */ #if (defined(STM32F101x6) || defined(STM32F102x6) || defined(STM32F103x6)) -#define IS_FLASH_PROGRAM_ADDRESS(ADDRESS) (((ADDRESS) >= FLASH_BASE) && (((*((uint16_t *)FLASH_SIZE_DATA_REGISTER)) == 0x20U) ? \ - ((ADDRESS) <= FLASH_BANK1_END) : ((ADDRESS) <= 0x08003FFFU))) +#define IS_FLASH_PROGRAM_ADDRESS(ADDRESS) (((ADDRESS) >= FLASH_BASE) && (((*((uint16_t *)FLASH_SIZE_DATA_REGISTER)) == 0x20) ? \ + ((ADDRESS) <= FLASH_BANK1_END) : ((ADDRESS) <= 0x08003FFF))) #endif /* STM32F101x6 || STM32F102x6 || STM32F103x6 */ /* Medium Density */ #if (defined(STM32F100xB) || defined(STM32F101xB) || defined(STM32F102xB) || defined(STM32F103xB)) -#define IS_FLASH_PROGRAM_ADDRESS(ADDRESS) (((ADDRESS) >= FLASH_BASE) && (((*((uint16_t *)FLASH_SIZE_DATA_REGISTER)) == 0x80U) ? \ - ((ADDRESS) <= FLASH_BANK1_END) : (((*((uint16_t *)FLASH_SIZE_DATA_REGISTER)) == 0x40U) ? \ - ((ADDRESS) <= 0x0800FFFF) : (((*((uint16_t *)FLASH_SIZE_DATA_REGISTER)) == 0x20U) ? \ - ((ADDRESS) <= 0x08007FFF) : ((ADDRESS) <= 0x08003FFFU))))) +#define IS_FLASH_PROGRAM_ADDRESS(ADDRESS) (((ADDRESS) >= FLASH_BASE) && (((*((uint16_t *)FLASH_SIZE_DATA_REGISTER)) == 0x80) ? \ + ((ADDRESS) <= FLASH_BANK1_END) : (((*((uint16_t *)FLASH_SIZE_DATA_REGISTER)) == 0x40) ? \ + ((ADDRESS) <= 0x0800FFFF) : (((*((uint16_t *)FLASH_SIZE_DATA_REGISTER)) == 0x20) ? \ + ((ADDRESS) <= 0x08007FFF) : ((ADDRESS) <= 0x08003FFF))))) #endif /* STM32F100xB || STM32F101xB || STM32F102xB || STM32F103xB*/ /* High Density */ #if (defined(STM32F100xE) || defined(STM32F101xE) || defined(STM32F103xE)) -#define IS_FLASH_PROGRAM_ADDRESS(ADDRESS) (((ADDRESS) >= FLASH_BASE) && (((*((uint16_t *)FLASH_SIZE_DATA_REGISTER)) == 0x200U) ? \ - ((ADDRESS) <= FLASH_BANK1_END) : (((*((uint16_t *)FLASH_SIZE_DATA_REGISTER)) == 0x180U) ? \ - ((ADDRESS) <= 0x0805FFFFU) : ((ADDRESS) <= 0x0803FFFFU)))) +#define IS_FLASH_PROGRAM_ADDRESS(ADDRESS) (((ADDRESS) >= FLASH_BASE) && (((*((uint16_t *)FLASH_SIZE_DATA_REGISTER)) == 0x200) ? \ + ((ADDRESS) <= FLASH_BANK1_END) : (((*((uint16_t *)FLASH_SIZE_DATA_REGISTER)) == 0x180) ? \ + ((ADDRESS) <= 0x0805FFFF) : ((ADDRESS) <= 0x0803FFFF)))) #endif /* STM32F100xE || STM32F101xE || STM32F103xE */ /* XL Density */ #if defined(FLASH_BANK2_END) -#define IS_FLASH_PROGRAM_ADDRESS(ADDRESS) (((ADDRESS) >= FLASH_BASE) && (((*((uint16_t *)FLASH_SIZE_DATA_REGISTER)) == 0x400U) ? \ - ((ADDRESS) <= FLASH_BANK2_END) : ((ADDRESS) <= 0x080BFFFFU))) +#define IS_FLASH_PROGRAM_ADDRESS(ADDRESS) (((ADDRESS) >= FLASH_BASE) && (((*((uint16_t *)FLASH_SIZE_DATA_REGISTER)) == 0x400) ? \ + ((ADDRESS) <= FLASH_BANK2_END) : ((ADDRESS) <= 0x080BFFFF))) #endif /* FLASH_BANK2_END */ /* Connectivity Line */ #if (defined(STM32F105xC) || defined(STM32F107xC)) -#define IS_FLASH_PROGRAM_ADDRESS(ADDRESS) (((ADDRESS) >= FLASH_BASE) && (((*((uint16_t *)FLASH_SIZE_DATA_REGISTER)) == 0x100U) ? \ - ((ADDRESS) <= FLASH_BANK1_END) : (((*((uint16_t *)FLASH_SIZE_DATA_REGISTER)) == 0x80U) ? \ - ((ADDRESS) <= 0x0801FFFFU) : ((ADDRESS) <= 0x0800FFFFU)))) +#define IS_FLASH_PROGRAM_ADDRESS(ADDRESS) (((ADDRESS) >= FLASH_BASE) && (((*((uint16_t *)FLASH_SIZE_DATA_REGISTER)) == 0x100) ? \ + ((ADDRESS) <= FLASH_BANK1_END) : (((*((uint16_t *)FLASH_SIZE_DATA_REGISTER)) == 0x80) ? \ + ((ADDRESS) <= 0x0801FFFF) : ((ADDRESS) <= 0x0800FFFF)))) #endif /* STM32F105xC || STM32F107xC */ @@ -258,12 +258,12 @@ typedef struct * @{ */ #if (defined(STM32F101x6) || defined(STM32F102x6) || defined(STM32F103x6) || defined(STM32F100xB) || defined(STM32F101xB) || defined(STM32F102xB) || defined(STM32F103xB)) -#define FLASH_PAGE_SIZE 0x400U +#define FLASH_PAGE_SIZE ((uint32_t)0x400) #endif /* STM32F101x6 || STM32F102x6 || STM32F103x6 */ /* STM32F100xB || STM32F101xB || STM32F102xB || STM32F103xB */ #if (defined(STM32F100xE) || defined(STM32F101xE) || defined(STM32F103xE) || defined(STM32F101xG) || defined(STM32F103xG) || defined(STM32F105xC) || defined(STM32F107xC)) -#define FLASH_PAGE_SIZE 0x800U +#define FLASH_PAGE_SIZE ((uint32_t)0x800) #endif /* STM32F100xB || STM32F101xB || STM32F102xB || STM32F103xB */ /* STM32F101xG || STM32F103xG */ /* STM32F105xC || STM32F107xC */ @@ -275,8 +275,8 @@ typedef struct /** @defgroup FLASHEx_Type_Erase Type Erase * @{ */ -#define FLASH_TYPEERASE_PAGES 0x00U /*!CR, ((__INTERRUPT__) & 0x0000FFFFU)); \ + SET_BIT(FLASH->CR, ((__INTERRUPT__) & 0x0000FFFF)); \ /* Enable Bank2 IT */ \ - SET_BIT(FLASH->CR2, ((__INTERRUPT__) >> 16U)); \ - } while(0U) + SET_BIT(FLASH->CR2, ((__INTERRUPT__) >> 16)); \ + } while(0) /** * @brief Disable the specified FLASH interrupt. @@ -629,10 +629,10 @@ typedef struct */ #define __HAL_FLASH_DISABLE_IT(__INTERRUPT__) do { \ /* Disable Bank1 IT */ \ - CLEAR_BIT(FLASH->CR, ((__INTERRUPT__) & 0x0000FFFFU)); \ + CLEAR_BIT(FLASH->CR, ((__INTERRUPT__) & 0x0000FFFF)); \ /* Disable Bank2 IT */ \ - CLEAR_BIT(FLASH->CR2, ((__INTERRUPT__) >> 16U)); \ - } while(0U) + CLEAR_BIT(FLASH->CR2, ((__INTERRUPT__) >> 16)); \ + } while(0) /** * @brief Get the specified FLASH flag status. @@ -653,7 +653,7 @@ typedef struct (FLASH->OBR & FLASH_OBR_OPTERR) : \ ((((__FLAG__) & SR_FLAG_MASK) != RESET)? \ (FLASH->SR & ((__FLAG__) & SR_FLAG_MASK)) : \ - (FLASH->SR2 & ((__FLAG__) >> 16U)))) + (FLASH->SR2 & ((__FLAG__) >> 16)))) /** * @brief Clear the specified FLASH flag. @@ -683,12 +683,12 @@ typedef struct FLASH->SR = ((__FLAG__) & SR_FLAG_MASK); \ } \ /* Clear Flag in Bank2 */ \ - if (((__FLAG__) >> 16U) != RESET) \ + if (((__FLAG__) >> 16) != RESET) \ { \ - FLASH->SR2 = ((__FLAG__) >> 16U); \ + FLASH->SR2 = ((__FLAG__) >> 16); \ } \ } \ - } while(0U) + } while(0) #else /** * @brief Enable the specified FLASH interrupt. @@ -744,7 +744,7 @@ typedef struct /* Clear Flag in Bank1 */ \ FLASH->SR = (__FLAG__); \ } \ - } while(0U) + } while(0) #endif diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_gpio.c b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_gpio.c index 1d09efbfb30..0a920f194b1 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_gpio.c +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_gpio.c @@ -2,18 +2,18 @@ ****************************************************************************** * @file stm32f1xx_hal_gpio.c * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief GPIO HAL module driver. - * This file provides firmware functions to manage the following + * This file provides firmware functions to manage the following * functionalities of the General Purpose Input/Output (GPIO) peripheral: * + Initialization and de-initialization functions * + IO operation functions - * + * @verbatim ============================================================================== ##### GPIO Peripheral features ##### - ============================================================================== + ============================================================================== [..] Subject to the specific hardware characteristics of each I/O port listed in the datasheet, each port bit of the General Purpose IO (GPIO) Ports, can be individually configured by software @@ -50,7 +50,7 @@ ##### How to use this driver ##### ============================================================================== - [..] + [..] (#) Enable the GPIO APB2 clock using the following function : __HAL_RCC_GPIOx_CLK_ENABLE(). (#) Configure the GPIO pin(s) using HAL_GPIO_Init(). @@ -135,47 +135,48 @@ /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ -/** @addtogroup GPIO_Private_Constants GPIO Private Constants +/** @defgroup GPIO_Private_Constants GPIO Private Constants * @{ */ -#define GPIO_MODE 0x00000003U -#define EXTI_MODE 0x10000000U -#define GPIO_MODE_IT 0x00010000U -#define GPIO_MODE_EVT 0x00020000U -#define RISING_EDGE 0x00100000U -#define FALLING_EDGE 0x00200000U -#define GPIO_OUTPUT_TYPE 0x00000010U - -#define GPIO_NUMBER 16U + +#define GPIO_MODE ((uint32_t)0x00000003) +#define EXTI_MODE ((uint32_t)0x10000000) +#define GPIO_MODE_IT ((uint32_t)0x00010000) +#define GPIO_MODE_EVT ((uint32_t)0x00020000) +#define RISING_EDGE ((uint32_t)0x00100000) +#define FALLING_EDGE ((uint32_t)0x00200000) +#define GPIO_OUTPUT_TYPE ((uint32_t)0x00000010) +#define GPIO_NUMBER ((uint32_t)16) /* Definitions for bit manipulation of CRL and CRH register */ -#define GPIO_CR_MODE_INPUT 0x00000000U /*!< 00: Input mode (reset state) */ -#define GPIO_CR_CNF_ANALOG 0x00000000U /*!< 00: Analog mode */ -#define GPIO_CR_CNF_INPUT_FLOATING 0x00000004U /*!< 01: Floating input (reset state) */ -#define GPIO_CR_CNF_INPUT_PU_PD 0x00000008U /*!< 10: Input with pull-up / pull-down */ -#define GPIO_CR_CNF_GP_OUTPUT_PP 0x00000000U /*!< 00: General purpose output push-pull */ -#define GPIO_CR_CNF_GP_OUTPUT_OD 0x00000004U /*!< 01: General purpose output Open-drain */ -#define GPIO_CR_CNF_AF_OUTPUT_PP 0x00000008U /*!< 10: Alternate function output Push-pull */ -#define GPIO_CR_CNF_AF_OUTPUT_OD 0x0000000CU /*!< 11: Alternate function output Open-drain */ +#define GPIO_CR_MODE_INPUT ((uint32_t)0x00000000) /*!< 00: Input mode (reset state) */ +#define GPIO_CR_CNF_ANALOG ((uint32_t)0x00000000) /*!< 00: Analog mode */ +#define GPIO_CR_CNF_INPUT_FLOATING ((uint32_t)0x00000004) /*!< 01: Floating input (reset state) */ +#define GPIO_CR_CNF_INPUT_PU_PD ((uint32_t)0x00000008) /*!< 10: Input with pull-up / pull-down */ +#define GPIO_CR_CNF_GP_OUTPUT_PP ((uint32_t)0x00000000) /*!< 00: General purpose output push-pull */ +#define GPIO_CR_CNF_GP_OUTPUT_OD ((uint32_t)0x00000004) /*!< 01: General purpose output Open-drain */ +#define GPIO_CR_CNF_AF_OUTPUT_PP ((uint32_t)0x00000008) /*!< 10: Alternate function output Push-pull */ +#define GPIO_CR_CNF_AF_OUTPUT_OD ((uint32_t)0x0000000C) /*!< 11: Alternate function output Open-drain */ /** * @} */ + /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ -/* Exported functions --------------------------------------------------------*/ + /** @defgroup GPIO_Exported_Functions GPIO Exported Functions * @{ */ -/** @defgroup GPIO_Exported_Functions_Group1 Initialization and de-initialization functions +/** @defgroup GPIO_Exported_Functions_Group1 Initialization and deinitialization functions * @brief Initialization and Configuration functions * @verbatim =============================================================================== - ##### Initialization and de-initialization functions ##### + ##### Initialization and deinitialization functions ##### =============================================================================== [..] This section provides functions allowing to initialize and de-initialize the GPIOs @@ -185,7 +186,6 @@ * @{ */ - /** * @brief Initializes the GPIOx peripheral according to the specified parameters in the GPIO_Init. * @param GPIOx: where x can be (A..G depending on device used) to select the GPIO peripheral @@ -196,12 +196,12 @@ void HAL_GPIO_Init(GPIO_TypeDef *GPIOx, GPIO_InitTypeDef *GPIO_Init) { uint32_t position; - uint32_t ioposition = 0x00U; - uint32_t iocurrent = 0x00U; - uint32_t temp = 0x00U; - uint32_t config = 0x00U; + uint32_t ioposition = 0x00; + uint32_t iocurrent = 0x00; + uint32_t temp = 0x00; + uint32_t config = 0x00; __IO uint32_t *configregister; /* Store the address of CRL or CRH register based on pin number */ - uint32_t registeroffset = 0U; /* offset used during computation of CNF and MODE bits placement inside CRL or CRH register */ + uint32_t registeroffset = 0; /* offset used during computation of CNF and MODE bits placement inside CRL or CRH register */ /* Check the parameters */ assert_param(IS_GPIO_ALL_INSTANCE(GPIOx)); @@ -209,10 +209,10 @@ void HAL_GPIO_Init(GPIO_TypeDef *GPIOx, GPIO_InitTypeDef *GPIO_Init) assert_param(IS_GPIO_MODE(GPIO_Init->Mode)); /* Configure the port pins */ - for (position = 0U; position < GPIO_NUMBER; position++) + for (position = 0; position < GPIO_NUMBER; position++) { /* Get the IO position */ - ioposition = (0x01U << position); + ioposition = ((uint32_t)0x01) << position; /* Get the current IO position */ iocurrent = (uint32_t)(GPIO_Init->Pin) & ioposition; @@ -296,7 +296,7 @@ void HAL_GPIO_Init(GPIO_TypeDef *GPIOx, GPIO_InitTypeDef *GPIO_Init) /* Check if the current bit belongs to first half or last half of the pin count number in order to address CRH or CRL register*/ configregister = (iocurrent < GPIO_PIN_8) ? &GPIOx->CRL : &GPIOx->CRH; - registeroffset = (iocurrent < GPIO_PIN_8) ? (position << 2U) : ((position - 8U) << 2U); + registeroffset = (iocurrent < GPIO_PIN_8) ? (position << 2) : ((position - 8) << 2); /* Apply the new configuration of the pin to the register */ MODIFY_REG((*configregister), ((GPIO_CRL_MODE0 | GPIO_CRL_CNF0) << registeroffset ), (config << registeroffset)); @@ -307,10 +307,10 @@ void HAL_GPIO_Init(GPIO_TypeDef *GPIOx, GPIO_InitTypeDef *GPIO_Init) { /* Enable AFIO Clock */ __HAL_RCC_AFIO_CLK_ENABLE(); - temp = AFIO->EXTICR[position >> 2U]; - CLEAR_BIT(temp, (0x0FU) << (4U * (position & 0x03U))); - SET_BIT(temp, (GPIO_GET_INDEX(GPIOx)) << (4U * (position & 0x03U))); - AFIO->EXTICR[position >> 2U] = temp; + temp = AFIO->EXTICR[position >> 2]; + CLEAR_BIT(temp, ((uint32_t)0x0F) << (4 * (position & 0x03))); + SET_BIT(temp, (GPIO_GET_INDEX(GPIOx)) << (4 * (position & 0x03))); + AFIO->EXTICR[position >> 2] = temp; /* Configure the interrupt mask */ @@ -366,21 +366,21 @@ void HAL_GPIO_Init(GPIO_TypeDef *GPIOx, GPIO_InitTypeDef *GPIO_Init) */ void HAL_GPIO_DeInit(GPIO_TypeDef *GPIOx, uint32_t GPIO_Pin) { - uint32_t position = 0x00U; - uint32_t iocurrent = 0x00U; - uint32_t tmp = 0x00U; + uint32_t position = 0x00; + uint32_t iocurrent = 0x00; + uint32_t tmp = 0x00; __IO uint32_t *configregister; /* Store the address of CRL or CRH register based on pin number */ - uint32_t registeroffset = 0U; + uint32_t registeroffset = 0; /* Check the parameters */ assert_param(IS_GPIO_ALL_INSTANCE(GPIOx)); assert_param(IS_GPIO_PIN(GPIO_Pin)); /* Configure the port pins */ - while ((GPIO_Pin >> position) != 0U) + while ((GPIO_Pin >> position) != 0) { /* Get current io position */ - iocurrent = (GPIO_Pin) & (1U << position); + iocurrent = (GPIO_Pin) & ((uint32_t)1 << position); if (iocurrent) { @@ -388,7 +388,7 @@ void HAL_GPIO_DeInit(GPIO_TypeDef *GPIOx, uint32_t GPIO_Pin) /* Check if the current bit belongs to first half or last half of the pin count number in order to address CRH or CRL register */ configregister = (iocurrent < GPIO_PIN_8) ? &GPIOx->CRL : &GPIOx->CRH; - registeroffset = (iocurrent < GPIO_PIN_8) ? (position << 2U) : ((position - 8U) << 2U); + registeroffset = (iocurrent < GPIO_PIN_8) ? (position << 2) : ((position - 8) << 2); /* CRL/CRH default value is floating input(0x04) shifted to correct position */ MODIFY_REG(*configregister, ((GPIO_CRL_MODE0 | GPIO_CRL_CNF0) << registeroffset ), GPIO_CRL_CNF0_0 << registeroffset); @@ -399,12 +399,12 @@ void HAL_GPIO_DeInit(GPIO_TypeDef *GPIOx, uint32_t GPIO_Pin) /*------------------------- EXTI Mode Configuration --------------------*/ /* Clear the External Interrupt or Event for the current IO */ - tmp = AFIO->EXTICR[position >> 2U]; - tmp &= 0x0FU << (4U * (position & 0x03U)); - if(tmp == (GPIO_GET_INDEX(GPIOx) << (4U * (position & 0x03U)))) + tmp = AFIO->EXTICR[position >> 2]; + tmp &= (((uint32_t)0x0F) << (4 * (position & 0x03))); + if(tmp == (GPIO_GET_INDEX(GPIOx) << (4 * (position & 0x03)))) { - tmp = 0x0FU << (4U * (position & 0x03U)); - CLEAR_BIT(AFIO->EXTICR[position >> 2U], tmp); + tmp = ((uint32_t)0x0F) << (4 * (position & 0x03)); + CLEAR_BIT(AFIO->EXTICR[position >> 2], tmp); /* Clear EXTI line configuration */ CLEAR_BIT(EXTI->IMR, (uint32_t)iocurrent); @@ -425,9 +425,9 @@ void HAL_GPIO_DeInit(GPIO_TypeDef *GPIOx, uint32_t GPIO_Pin) */ /** @defgroup GPIO_Exported_Functions_Group2 IO operation functions - * @brief GPIO Read and Write + * @brief GPIO Read and Write * -@verbatim +@verbatim =============================================================================== ##### IO operation functions ##### =============================================================================== @@ -437,7 +437,6 @@ void HAL_GPIO_DeInit(GPIO_TypeDef *GPIOx, uint32_t GPIO_Pin) @endverbatim * @{ */ - /** * @brief Reads the specified input port pin. * @param GPIOx: where x can be (A..G depending on device used) to select the GPIO peripheral @@ -491,7 +490,7 @@ void HAL_GPIO_WritePin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin, GPIO_PinState Pin } else { - GPIOx->BSRR = (uint32_t)GPIO_Pin << 16U; + GPIOx->BSRR = (uint32_t)GPIO_Pin << 16; } } @@ -549,38 +548,39 @@ HAL_StatusTypeDef HAL_GPIO_LockPin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin) } /** - * @brief This function handles EXTI interrupt request. - * @param GPIO_Pin: Specifies the pins connected EXTI line + * @brief This function handles EXTI interrupt request. + * @param GPIO_Pin: Specifies the pins connected EXTI line * @retval None */ void HAL_GPIO_EXTI_IRQHandler(uint16_t GPIO_Pin) { /* EXTI line interrupt detected */ - if(__HAL_GPIO_EXTI_GET_IT(GPIO_Pin) != RESET) - { + if(__HAL_GPIO_EXTI_GET_IT(GPIO_Pin) != RESET) + { __HAL_GPIO_EXTI_CLEAR_IT(GPIO_Pin); HAL_GPIO_EXTI_Callback(GPIO_Pin); } } /** - * @brief EXTI line detection callbacks. - * @param GPIO_Pin: Specifies the pins connected EXTI line + * @brief EXTI line detection callback + * @param GPIO_Pin: Specifies the pins connected EXTI line * @retval None */ __weak void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin) { /* Prevent unused argument(s) compilation warning */ UNUSED(GPIO_Pin); - /* NOTE: This function Should not be modified, when the callback is needed, - the HAL_GPIO_EXTI_Callback could be implemented in the user file - */ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_GPIO_EXTI_Callback could be implemented in the user file + */ } /** * @} */ + /** * @} */ diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_gpio.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_gpio.h index ca9251d0864..1178290a5eb 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_gpio.h +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_gpio.h @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_hal_gpio.h * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief Header file of GPIO HAL module. ****************************************************************************** * @attention @@ -57,10 +57,10 @@ /* Exported types ------------------------------------------------------------*/ /** @defgroup GPIO_Exported_Types GPIO Exported Types * @{ - */ + */ /** - * @brief GPIO Init structure definition + * @brief GPIO Init structure definition */ typedef struct { @@ -69,26 +69,28 @@ typedef struct uint32_t Mode; /*!< Specifies the operating mode for the selected pins. This parameter can be a value of @ref GPIO_mode_define */ - + uint32_t Pull; /*!< Specifies the Pull-up or Pull-Down activation for the selected pins. This parameter can be a value of @ref GPIO_pull_define */ - + uint32_t Speed; /*!< Specifies the speed for the selected pins. This parameter can be a value of @ref GPIO_speed_define */ }GPIO_InitTypeDef; - + /** * @brief GPIO Bit SET and Bit RESET enumeration */ typedef enum -{ - GPIO_PIN_RESET = 0U, +{ + GPIO_PIN_RESET = 0, GPIO_PIN_SET }GPIO_PinState; + /** * @} */ + /* Exported constants --------------------------------------------------------*/ /** @defgroup GPIO_Exported_Constants GPIO Exported Constants @@ -97,7 +99,7 @@ typedef enum /** @defgroup GPIO_pins_define GPIO pins define * @{ - */ + */ #define GPIO_PIN_0 ((uint16_t)0x0001) /* Pin 0 selected */ #define GPIO_PIN_1 ((uint16_t)0x0002) /* Pin 1 selected */ #define GPIO_PIN_2 ((uint16_t)0x0004) /* Pin 2 selected */ @@ -116,11 +118,12 @@ typedef enum #define GPIO_PIN_15 ((uint16_t)0x8000) /* Pin 15 selected */ #define GPIO_PIN_All ((uint16_t)0xFFFF) /* All pins selected */ -#define GPIO_PIN_MASK 0x0000FFFFU /* PIN mask for assert test */ +#define GPIO_PIN_MASK ((uint32_t)0x0000FFFF) /* PIN mask for assert test */ /** * @} - */ + */ + /** @defgroup GPIO_mode_define GPIO mode define * @brief GPIO Configuration Mode * Elements values convention: 0xX0yz00YZ @@ -131,31 +134,32 @@ typedef enum * - Z : IO Direction mode (Input, Output, Alternate or Analog) * @{ */ -#define GPIO_MODE_INPUT 0x00000000U /*!< Input Floating Mode */ -#define GPIO_MODE_OUTPUT_PP 0x00000001U /*!< Output Push Pull Mode */ -#define GPIO_MODE_OUTPUT_OD 0x00000011U /*!< Output Open Drain Mode */ -#define GPIO_MODE_AF_PP 0x00000002U /*!< Alternate Function Push Pull Mode */ -#define GPIO_MODE_AF_OD 0x00000012U /*!< Alternate Function Open Drain Mode */ +#define GPIO_MODE_INPUT ((uint32_t)0x00000000) /*!< Input Floating Mode */ +#define GPIO_MODE_OUTPUT_PP ((uint32_t)0x00000001) /*!< Output Push Pull Mode */ +#define GPIO_MODE_OUTPUT_OD ((uint32_t)0x00000011) /*!< Output Open Drain Mode */ +#define GPIO_MODE_AF_PP ((uint32_t)0x00000002) /*!< Alternate Function Push Pull Mode */ +#define GPIO_MODE_AF_OD ((uint32_t)0x00000012) /*!< Alternate Function Open Drain Mode */ #define GPIO_MODE_AF_INPUT GPIO_MODE_INPUT /*!< Alternate Function Input Mode */ -#define GPIO_MODE_ANALOG 0x00000003U /*!< Analog Mode */ +#define GPIO_MODE_ANALOG ((uint32_t)0x00000003) /*!< Analog Mode */ -#define GPIO_MODE_IT_RISING 0x10110000U /*!< External Interrupt Mode with Rising edge trigger detection */ -#define GPIO_MODE_IT_FALLING 0x10210000U /*!< External Interrupt Mode with Falling edge trigger detection */ -#define GPIO_MODE_IT_RISING_FALLING 0x10310000U /*!< External Interrupt Mode with Rising/Falling edge trigger detection */ +#define GPIO_MODE_IT_RISING ((uint32_t)0x10110000) /*!< External Interrupt Mode with Rising edge trigger detection */ +#define GPIO_MODE_IT_FALLING ((uint32_t)0x10210000) /*!< External Interrupt Mode with Falling edge trigger detection */ +#define GPIO_MODE_IT_RISING_FALLING ((uint32_t)0x10310000) /*!< External Interrupt Mode with Rising/Falling edge trigger detection */ -#define GPIO_MODE_EVT_RISING 0x10120000U /*!< External Event Mode with Rising edge trigger detection */ -#define GPIO_MODE_EVT_FALLING 0x10220000U /*!< External Event Mode with Falling edge trigger detection */ -#define GPIO_MODE_EVT_RISING_FALLING 0x10320000U /*!< External Event Mode with Rising/Falling edge trigger detection */ +#define GPIO_MODE_EVT_RISING ((uint32_t)0x10120000) /*!< External Event Mode with Rising edge trigger detection */ +#define GPIO_MODE_EVT_FALLING ((uint32_t)0x10220000) /*!< External Event Mode with Falling edge trigger detection */ +#define GPIO_MODE_EVT_RISING_FALLING ((uint32_t)0x10320000) /*!< External Event Mode with Rising/Falling edge trigger detection */ /** * @} */ - -/** @defgroup GPIO_speed_define GPIO speed define + + +/** @defgroup GPIO_speed_define GPIO speed define * @brief GPIO Output Maximum frequency * @{ - */ + */ #define GPIO_SPEED_FREQ_LOW (GPIO_CRL_MODE0_1) /*!< Low speed */ #define GPIO_SPEED_FREQ_MEDIUM (GPIO_CRL_MODE0_0) /*!< Medium speed */ #define GPIO_SPEED_FREQ_HIGH (GPIO_CRL_MODE0) /*!< High speed */ @@ -164,13 +168,15 @@ typedef enum * @} */ + /** @defgroup GPIO_pull_define GPIO pull define * @brief GPIO Pull-Up or Pull-Down Activation * @{ */ -#define GPIO_NOPULL 0x00000000U /*!< No Pull-up or Pull-down activation */ -#define GPIO_PULLUP 0x00000001U /*!< Pull-up activation */ -#define GPIO_PULLDOWN 0x00000002U /*!< Pull-down activation */ +#define GPIO_NOPULL ((uint32_t)0x00000000) /*!< No Pull-up or Pull-down activation */ +#define GPIO_PULLUP ((uint32_t)0x00000001) /*!< Pull-up activation */ +#define GPIO_PULLDOWN ((uint32_t)0x00000002) /*!< Pull-down activation */ + /** * @} */ @@ -179,6 +185,40 @@ typedef enum * @} */ + +/* Private macros --------------------------------------------------------*/ +/** @addtogroup GPIO_Private_Macros + * @{ + */ + +#define IS_GPIO_PIN_ACTION(ACTION) (((ACTION) == GPIO_PIN_RESET) || ((ACTION) == GPIO_PIN_SET)) + +#define IS_GPIO_PIN(PIN) (((PIN) & GPIO_PIN_MASK ) != (uint32_t)0x00) + +#define IS_GPIO_PULL(PULL) (((PULL) == GPIO_NOPULL) || ((PULL) == GPIO_PULLUP) || \ + ((PULL) == GPIO_PULLDOWN)) + +#define IS_GPIO_SPEED(SPEED) (((SPEED) == GPIO_SPEED_FREQ_LOW) || \ + ((SPEED) == GPIO_SPEED_FREQ_MEDIUM) || ((SPEED) == GPIO_SPEED_FREQ_HIGH)) + +#define IS_GPIO_MODE(MODE) (((MODE) == GPIO_MODE_INPUT) ||\ + ((MODE) == GPIO_MODE_OUTPUT_PP) ||\ + ((MODE) == GPIO_MODE_OUTPUT_OD) ||\ + ((MODE) == GPIO_MODE_AF_PP) ||\ + ((MODE) == GPIO_MODE_AF_OD) ||\ + ((MODE) == GPIO_MODE_IT_RISING) ||\ + ((MODE) == GPIO_MODE_IT_FALLING) ||\ + ((MODE) == GPIO_MODE_IT_RISING_FALLING) ||\ + ((MODE) == GPIO_MODE_EVT_RISING) ||\ + ((MODE) == GPIO_MODE_EVT_FALLING) ||\ + ((MODE) == GPIO_MODE_EVT_RISING_FALLING) ||\ + ((MODE) == GPIO_MODE_ANALOG)) + +/** + * @} + */ + + /* Exported macro ------------------------------------------------------------*/ /** @defgroup GPIO_Exported_Macros GPIO Exported Macros * @{ @@ -190,8 +230,8 @@ typedef enum * This parameter can be GPIO_PIN_x where x can be(0..15) * @retval The new state of __EXTI_LINE__ (SET or RESET). */ -#define __HAL_GPIO_EXTI_GET_FLAG(__EXTI_LINE__) (EXTI->PR & (__EXTI_LINE__)) - +#define __HAL_GPIO_EXTI_GET_FLAG(__EXTI_LINE__) (EXTI->PR & (__EXTI_LINE__)) + /** * @brief Clears the EXTI's line pending flags. * @param __EXTI_LINE__: specifies the EXTI lines flags to clear. @@ -206,8 +246,8 @@ typedef enum * This parameter can be GPIO_PIN_x where x can be(0..15) * @retval The new state of __EXTI_LINE__ (SET or RESET). */ -#define __HAL_GPIO_EXTI_GET_IT(__EXTI_LINE__) (EXTI->PR & (__EXTI_LINE__)) - +#define __HAL_GPIO_EXTI_GET_IT(__EXTI_LINE__) (EXTI->PR & (__EXTI_LINE__)) + /** * @brief Clears the EXTI's line pending bits. * @param __EXTI_LINE__: specifies the EXTI lines to clear. @@ -223,14 +263,18 @@ typedef enum * @retval None */ #define __HAL_GPIO_EXTI_GENERATE_SWIT(__EXTI_LINE__) (EXTI->SWIER |= (__EXTI_LINE__)) + +/* Include GPIO HAL Extension module */ +#include "stm32f1xx_hal_gpio_ex.h" + /** * @} */ -/* Include GPIO HAL Extension module */ -#include "stm32f1xx_hal_gpio_ex.h" -/* Exported functions --------------------------------------------------------*/ + +/* Exported functions --------------------------------------------------------*/ +/* Initialization and de-initialization functions *******************************/ /** @addtogroup GPIO_Exported_Functions * @{ */ @@ -238,84 +282,38 @@ typedef enum /** @addtogroup GPIO_Exported_Functions_Group1 * @{ */ -/* Initialization and de-initialization functions *****************************/ void HAL_GPIO_Init(GPIO_TypeDef *GPIOx, GPIO_InitTypeDef *GPIO_Init); void HAL_GPIO_DeInit(GPIO_TypeDef *GPIOx, uint32_t GPIO_Pin); /** * @} */ +/* IO operation functions *******************************************************/ /** @addtogroup GPIO_Exported_Functions_Group2 * @{ */ -/* IO operation functions *****************************************************/ GPIO_PinState HAL_GPIO_ReadPin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin); -void HAL_GPIO_WritePin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin, GPIO_PinState PinState); -void HAL_GPIO_TogglePin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin); +void HAL_GPIO_WritePin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin, GPIO_PinState PinState); +void HAL_GPIO_TogglePin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin); HAL_StatusTypeDef HAL_GPIO_LockPin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin); -void HAL_GPIO_EXTI_IRQHandler(uint16_t GPIO_Pin); -void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin); - -/** - * @} - */ - -/** - * @} - */ -/* Private types -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private constants ---------------------------------------------------------*/ -/** @defgroup GPIO_Private_Constants GPIO Private Constants - * @{ - */ - +void HAL_GPIO_EXTI_IRQHandler(uint16_t GPIO_Pin); +void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin); /** * @} */ -/* Private macros ------------------------------------------------------------*/ -/** @defgroup GPIO_Private_Macros GPIO Private Macros - * @{ - */ -#define IS_GPIO_PIN_ACTION(ACTION) (((ACTION) == GPIO_PIN_RESET) || ((ACTION) == GPIO_PIN_SET)) -#define IS_GPIO_PIN(PIN) ((((PIN) & GPIO_PIN_MASK ) != 0x00U) && (((PIN) & ~GPIO_PIN_MASK) == 0x00U)) -#define IS_GPIO_MODE(MODE) (((MODE) == GPIO_MODE_INPUT) ||\ - ((MODE) == GPIO_MODE_OUTPUT_PP) ||\ - ((MODE) == GPIO_MODE_OUTPUT_OD) ||\ - ((MODE) == GPIO_MODE_AF_PP) ||\ - ((MODE) == GPIO_MODE_AF_OD) ||\ - ((MODE) == GPIO_MODE_IT_RISING) ||\ - ((MODE) == GPIO_MODE_IT_FALLING) ||\ - ((MODE) == GPIO_MODE_IT_RISING_FALLING) ||\ - ((MODE) == GPIO_MODE_EVT_RISING) ||\ - ((MODE) == GPIO_MODE_EVT_FALLING) ||\ - ((MODE) == GPIO_MODE_EVT_RISING_FALLING) ||\ - ((MODE) == GPIO_MODE_ANALOG)) -#define IS_GPIO_SPEED(SPEED) (((SPEED) == GPIO_SPEED_FREQ_LOW) || \ - ((SPEED) == GPIO_SPEED_FREQ_MEDIUM) || ((SPEED) == GPIO_SPEED_FREQ_HIGH)) -#define IS_GPIO_PULL(PULL) (((PULL) == GPIO_NOPULL) || ((PULL) == GPIO_PULLUP) || \ - ((PULL) == GPIO_PULLDOWN)) /** * @} - */ - -/* Private functions ---------------------------------------------------------*/ -/** @defgroup GPIO_Private_Functions GPIO Private Functions - * @{ - */ + */ /** * @} - */ + */ /** * @} */ -/** - * @} - */ #ifdef __cplusplus } diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_gpio_ex.c b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_gpio_ex.c index cc269d2d658..ea3fc90b4a2 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_gpio_ex.c +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_gpio_ex.c @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_hal_gpio_ex.c * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief GPIO Extension HAL module driver. * This file provides firmware functions to manage the following * functionalities of the General Purpose Input/Output (GPIO) extension peripheral. diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_gpio_ex.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_gpio_ex.h index 67b3a8cef83..e2f3479d864 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_gpio_ex.h +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_gpio_ex.h @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_hal_gpio_ex.h * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief Header file of GPIO HAL Extension module. ****************************************************************************** * @attention @@ -197,89 +197,70 @@ * @note ENABLE: Full remap (TX/PD8, RX/PD9, CK/PD10, CTS/PD11, RTS/PD12) * @retval None */ -#define __HAL_AFIO_REMAP_USART3_ENABLE() do{ CLEAR_BIT(AFIO->MAPR, AFIO_MAPR_USART3_REMAP); \ - SET_BIT(AFIO->MAPR, AFIO_MAPR_USART3_REMAP_FULLREMAP); \ - }while(0U) +#define __HAL_AFIO_REMAP_USART3_ENABLE() MODIFY_REG(AFIO->MAPR, AFIO_MAPR_USART3_REMAP, AFIO_MAPR_USART3_REMAP_FULLREMAP) + /** * @brief Enable the remapping of USART3 alternate function CTS, RTS, CK, TX and RX. * @note PARTIAL: Partial remap (TX/PC10, RX/PC11, CK/PC12, CTS/PB13, RTS/PB14) * @retval None */ -#define __HAL_AFIO_REMAP_USART3_PARTIAL() do{ CLEAR_BIT(AFIO->MAPR, AFIO_MAPR_USART3_REMAP); \ - SET_BIT(AFIO->MAPR, AFIO_MAPR_USART3_REMAP_PARTIALREMAP); \ - }while(0U) +#define __HAL_AFIO_REMAP_USART3_PARTIAL() MODIFY_REG(AFIO->MAPR, AFIO_MAPR_USART3_REMAP, AFIO_MAPR_USART3_REMAP_PARTIALREMAP) /** * @brief Disable the remapping of USART3 alternate function CTS, RTS, CK, TX and RX. * @note DISABLE: No remap (TX/PB10, RX/PB11, CK/PB12, CTS/PB13, RTS/PB14) * @retval None */ -#define __HAL_AFIO_REMAP_USART3_DISABLE() do{ CLEAR_BIT(AFIO->MAPR, AFIO_MAPR_USART3_REMAP); \ - SET_BIT(AFIO->MAPR, AFIO_MAPR_USART3_REMAP_NOREMAP); \ - }while(0U) +#define __HAL_AFIO_REMAP_USART3_DISABLE() MODIFY_REG(AFIO->MAPR, AFIO_MAPR_USART3_REMAP, AFIO_MAPR_USART3_REMAP_NOREMAP) /** * @brief Enable the remapping of TIM1 alternate function channels 1 to 4, 1N to 3N, external trigger (ETR) and Break input (BKIN) * @note ENABLE: Full remap (ETR/PE7, CH1/PE9, CH2/PE11, CH3/PE13, CH4/PE14, BKIN/PE15, CH1N/PE8, CH2N/PE10, CH3N/PE12) * @retval None */ -#define __HAL_AFIO_REMAP_TIM1_ENABLE() do{ CLEAR_BIT(AFIO->MAPR, AFIO_MAPR_TIM1_REMAP); \ - SET_BIT(AFIO->MAPR, AFIO_MAPR_TIM1_REMAP_FULLREMAP); \ - }while(0U) +#define __HAL_AFIO_REMAP_TIM1_ENABLE() MODIFY_REG(AFIO->MAPR, AFIO_MAPR_TIM1_REMAP, AFIO_MAPR_TIM1_REMAP_FULLREMAP) /** * @brief Enable the remapping of TIM1 alternate function channels 1 to 4, 1N to 3N, external trigger (ETR) and Break input (BKIN) * @note PARTIAL: Partial remap (ETR/PA12, CH1/PA8, CH2/PA9, CH3/PA10, CH4/PA11, BKIN/PA6, CH1N/PA7, CH2N/PB0, CH3N/PB1) * @retval None */ -#define __HAL_AFIO_REMAP_TIM1_PARTIAL() do{ CLEAR_BIT(AFIO->MAPR, AFIO_MAPR_TIM1_REMAP); \ - SET_BIT(AFIO->MAPR, AFIO_MAPR_TIM1_REMAP_PARTIALREMAP); \ - }while(0U) +#define __HAL_AFIO_REMAP_TIM1_PARTIAL() MODIFY_REG(AFIO->MAPR, AFIO_MAPR_TIM1_REMAP, AFIO_MAPR_TIM1_REMAP_PARTIALREMAP) /** * @brief Disable the remapping of TIM1 alternate function channels 1 to 4, 1N to 3N, external trigger (ETR) and Break input (BKIN) * @note DISABLE: No remap (ETR/PA12, CH1/PA8, CH2/PA9, CH3/PA10, CH4/PA11, BKIN/PB12, CH1N/PB13, CH2N/PB14, CH3N/PB15) * @retval None */ -#define __HAL_AFIO_REMAP_TIM1_DISABLE() do{ CLEAR_BIT(AFIO->MAPR, AFIO_MAPR_TIM1_REMAP); \ - SET_BIT(AFIO->MAPR, AFIO_MAPR_TIM1_REMAP_NOREMAP); \ - }while(0U) +#define __HAL_AFIO_REMAP_TIM1_DISABLE() MODIFY_REG(AFIO->MAPR, AFIO_MAPR_TIM1_REMAP, AFIO_MAPR_TIM1_REMAP_NOREMAP) /** * @brief Enable the remapping of TIM2 alternate function channels 1 to 4 and external trigger (ETR) * @note ENABLE: Full remap (CH1/ETR/PA15, CH2/PB3, CH3/PB10, CH4/PB11) * @retval None */ -#define __HAL_AFIO_REMAP_TIM2_ENABLE() do{ CLEAR_BIT(AFIO->MAPR, AFIO_MAPR_TIM2_REMAP); \ - SET_BIT(AFIO->MAPR, AFIO_MAPR_TIM2_REMAP_FULLREMAP); \ - }while(0U) +#define __HAL_AFIO_REMAP_TIM2_ENABLE() MODIFY_REG(AFIO->MAPR, AFIO_MAPR_TIM2_REMAP, AFIO_MAPR_TIM2_REMAP_FULLREMAP) /** * @brief Enable the remapping of TIM2 alternate function channels 1 to 4 and external trigger (ETR) * @note PARTIAL_2: Partial remap (CH1/ETR/PA0, CH2/PA1, CH3/PB10, CH4/PB11) * @retval None */ -#define __HAL_AFIO_REMAP_TIM2_PARTIAL_2() do{ CLEAR_BIT(AFIO->MAPR, AFIO_MAPR_TIM2_REMAP); \ - SET_BIT(AFIO->MAPR, AFIO_MAPR_TIM2_REMAP_PARTIALREMAP2); \ - }while(0U) +#define __HAL_AFIO_REMAP_TIM2_PARTIAL_2() MODIFY_REG(AFIO->MAPR, AFIO_MAPR_TIM2_REMAP, AFIO_MAPR_TIM2_REMAP_PARTIALREMAP2) /** * @brief Enable the remapping of TIM2 alternate function channels 1 to 4 and external trigger (ETR) * @note PARTIAL_1: Partial remap (CH1/ETR/PA15, CH2/PB3, CH3/PA2, CH4/PA3) * @retval None */ -#define __HAL_AFIO_REMAP_TIM2_PARTIAL_1() do{ CLEAR_BIT(AFIO->MAPR, AFIO_MAPR_TIM2_REMAP); \ - SET_BIT(AFIO->MAPR, AFIO_MAPR_TIM2_REMAP_PARTIALREMAP1); \ - }while(0U) +#define __HAL_AFIO_REMAP_TIM2_PARTIAL_1() MODIFY_REG(AFIO->MAPR, AFIO_MAPR_TIM2_REMAP, AFIO_MAPR_TIM2_REMAP_PARTIALREMAP1) /** * @brief Disable the remapping of TIM2 alternate function channels 1 to 4 and external trigger (ETR) * @note DISABLE: No remap (CH1/ETR/PA0, CH2/PA1, CH3/PA2, CH4/PA3) * @retval None */ -#define __HAL_AFIO_REMAP_TIM2_DISABLE() do{ CLEAR_BIT(AFIO->MAPR, AFIO_MAPR_TIM2_REMAP); \ - SET_BIT(AFIO->MAPR, AFIO_MAPR_TIM2_REMAP_NOREMAP); \ - }while(0U) +#define __HAL_AFIO_REMAP_TIM2_DISABLE() MODIFY_REG(AFIO->MAPR, AFIO_MAPR_TIM2_REMAP, AFIO_MAPR_TIM2_REMAP_NOREMAP) /** * @brief Enable the remapping of TIM3 alternate function channels 1 to 4 @@ -287,9 +268,7 @@ * @note TIM3_ETR on PE0 is not re-mapped. * @retval None */ -#define __HAL_AFIO_REMAP_TIM3_ENABLE() do{ CLEAR_BIT(AFIO->MAPR, AFIO_MAPR_TIM3_REMAP); \ - SET_BIT(AFIO->MAPR, AFIO_MAPR_TIM3_REMAP_FULLREMAP); \ - }while(0U) +#define __HAL_AFIO_REMAP_TIM3_ENABLE() MODIFY_REG(AFIO->MAPR, AFIO_MAPR_TIM3_REMAP, AFIO_MAPR_TIM3_REMAP_FULLREMAP) /** * @brief Enable the remapping of TIM3 alternate function channels 1 to 4 @@ -297,9 +276,7 @@ * @note TIM3_ETR on PE0 is not re-mapped. * @retval None */ -#define __HAL_AFIO_REMAP_TIM3_PARTIAL() do{ CLEAR_BIT(AFIO->MAPR, AFIO_MAPR_TIM3_REMAP); \ - SET_BIT(AFIO->MAPR, AFIO_MAPR_TIM3_REMAP_PARTIALREMAP); \ - }while(0U) +#define __HAL_AFIO_REMAP_TIM3_PARTIAL() MODIFY_REG(AFIO->MAPR, AFIO_MAPR_TIM3_REMAP, AFIO_MAPR_TIM3_REMAP_PARTIALREMAP) /** * @brief Disable the remapping of TIM3 alternate function channels 1 to 4 @@ -307,9 +284,7 @@ * @note TIM3_ETR on PE0 is not re-mapped. * @retval None */ -#define __HAL_AFIO_REMAP_TIM3_DISABLE() do{ CLEAR_BIT(AFIO->MAPR, AFIO_MAPR_TIM3_REMAP); \ - SET_BIT(AFIO->MAPR, AFIO_MAPR_TIM3_REMAP_NOREMAP); \ - }while(0U) +#define __HAL_AFIO_REMAP_TIM3_DISABLE() MODIFY_REG(AFIO->MAPR, AFIO_MAPR_TIM3_REMAP, AFIO_MAPR_TIM3_REMAP_NOREMAP) /** * @brief Enable the remapping of TIM4 alternate function channels 1 to 4. @@ -334,27 +309,21 @@ * @note CASE 1: CAN_RX mapped to PA11, CAN_TX mapped to PA12 * @retval None */ -#define __HAL_AFIO_REMAP_CAN1_1() do{ CLEAR_BIT(AFIO->MAPR, AFIO_MAPR_CAN_REMAP); \ - SET_BIT(AFIO->MAPR, AFIO_MAPR_CAN_REMAP_REMAP1); \ - }while(0U) +#define __HAL_AFIO_REMAP_CAN1_1() MODIFY_REG(AFIO->MAPR, AFIO_MAPR_CAN_REMAP, AFIO_MAPR_CAN_REMAP_REMAP1) /** * @brief Enable or disable the remapping of CAN alternate function CAN_RX and CAN_TX in devices with a single CAN interface. * @note CASE 2: CAN_RX mapped to PB8, CAN_TX mapped to PB9 (not available on 36-pin package) * @retval None */ -#define __HAL_AFIO_REMAP_CAN1_2() do{ CLEAR_BIT(AFIO->MAPR, AFIO_MAPR_CAN_REMAP); \ - SET_BIT(AFIO->MAPR, AFIO_MAPR_CAN_REMAP_REMAP2); \ - }while(0U) +#define __HAL_AFIO_REMAP_CAN1_2() MODIFY_REG(AFIO->MAPR, AFIO_MAPR_CAN_REMAP, AFIO_MAPR_CAN_REMAP_REMAP2) /** * @brief Enable or disable the remapping of CAN alternate function CAN_RX and CAN_TX in devices with a single CAN interface. * @note CASE 3: CAN_RX mapped to PD0, CAN_TX mapped to PD1 * @retval None */ -#define __HAL_AFIO_REMAP_CAN1_3() do{ CLEAR_BIT(AFIO->MAPR, AFIO_MAPR_CAN_REMAP); \ - SET_BIT(AFIO->MAPR, AFIO_MAPR_CAN_REMAP_REMAP3); \ - }while(0U) +#define __HAL_AFIO_REMAP_CAN1_3() MODIFY_REG(AFIO->MAPR, AFIO_MAPR_CAN_REMAP, AFIO_MAPR_CAN_REMAP_REMAP3) #endif /** @@ -517,36 +486,28 @@ * @note ENABLE: Full SWJ (JTAG-DP + SW-DP): Reset State * @retval None */ -#define __HAL_AFIO_REMAP_SWJ_ENABLE() do{ CLEAR_BIT(AFIO->MAPR, AFIO_MAPR_SWJ_CFG); \ - SET_BIT(AFIO->MAPR, AFIO_MAPR_SWJ_CFG_RESET); \ - }while(0U) +#define __HAL_AFIO_REMAP_SWJ_ENABLE() MODIFY_REG(AFIO->MAPR, AFIO_MAPR_SWJ_CFG, AFIO_MAPR_SWJ_CFG_RESET) /** * @brief Enable the Serial wire JTAG configuration * @note NONJTRST: Full SWJ (JTAG-DP + SW-DP) but without NJTRST * @retval None */ -#define __HAL_AFIO_REMAP_SWJ_NONJTRST() do{ CLEAR_BIT(AFIO->MAPR, AFIO_MAPR_SWJ_CFG); \ - SET_BIT(AFIO->MAPR, AFIO_MAPR_SWJ_CFG_NOJNTRST); \ - }while(0U) +#define __HAL_AFIO_REMAP_SWJ_NONJTRST() MODIFY_REG(AFIO->MAPR, AFIO_MAPR_SWJ_CFG, AFIO_MAPR_SWJ_CFG_NOJNTRST) /** * @brief Enable the Serial wire JTAG configuration * @note NOJTAG: JTAG-DP Disabled and SW-DP Enabled * @retval None */ -#define __HAL_AFIO_REMAP_SWJ_NOJTAG() do{ CLEAR_BIT(AFIO->MAPR, AFIO_MAPR_SWJ_CFG); \ - SET_BIT(AFIO->MAPR, AFIO_MAPR_SWJ_CFG_JTAGDISABLE); \ - }while(0U) +#define __HAL_AFIO_REMAP_SWJ_NOJTAG() MODIFY_REG(AFIO->MAPR, AFIO_MAPR_SWJ_CFG, AFIO_MAPR_SWJ_CFG_JTAGDISABLE) /** * @brief Disable the Serial wire JTAG configuration * @note DISABLE: JTAG-DP Disabled and SW-DP Disabled * @retval None */ -#define __HAL_AFIO_REMAP_SWJ_DISABLE() do{ CLEAR_BIT(AFIO->MAPR, AFIO_MAPR_SWJ_CFG); \ - SET_BIT(AFIO->MAPR, AFIO_MAPR_SWJ_CFG_DISABLE); \ - }while(0U) +#define __HAL_AFIO_REMAP_SWJ_DISABLE() MODIFY_REG(AFIO->MAPR, AFIO_MAPR_SWJ_CFG, AFIO_MAPR_SWJ_CFG_DISABLE) #if defined(AFIO_MAPR_SPI3_REMAP) diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_hcd.c b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_hcd.c index 7328bd214ab..cd05ea59ee2 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_hcd.c +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_hcd.c @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_hal_hcd.c * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief HCD HAL module driver. * This file provides firmware functions to manage the following * functionalities of the USB Peripheral Controller: @@ -149,7 +149,7 @@ HAL_StatusTypeDef HAL_HCD_Init(HCD_HandleTypeDef *hhcd) /* Disable the Interrupts */ __HAL_HCD_DISABLE(hhcd); - /* Init the Core (common init.) */ + /*Init the Core (common init.) */ USB_CoreInit(hhcd->Instance, hhcd->Init); /* Force Host Mode*/ @@ -202,8 +202,8 @@ HAL_StatusTypeDef HAL_HCD_HC_Init(HCD_HandleTypeDef *hhcd, hhcd->hc[ch_num].max_packet = mps; hhcd->hc[ch_num].ch_num = ch_num; hhcd->hc[ch_num].ep_type = ep_type; - hhcd->hc[ch_num].ep_num = epnum & 0x7FU; - hhcd->hc[ch_num].ep_is_in = ((epnum & 0x80U) == 0x80U); + hhcd->hc[ch_num].ep_num = epnum & 0x7F; + hhcd->hc[ch_num].ep_is_in = ((epnum & 0x80) == 0x80); hhcd->hc[ch_num].speed = speed; status = USB_HC_Init(hhcd->Instance, @@ -253,7 +253,7 @@ HAL_StatusTypeDef HAL_HCD_DeInit(HCD_HandleTypeDef *hhcd) /* DeInit the low level hardware */ HAL_HCD_MspDeInit(hhcd); - __HAL_HCD_DISABLE(hhcd); + __HAL_HCD_DISABLE(hhcd); hhcd->State = HAL_HCD_STATE_RESET; @@ -292,7 +292,7 @@ __weak void HAL_HCD_MspDeInit(HCD_HandleTypeDef *hhcd) * @} */ -/** @defgroup HCD_Exported_Functions_Group2 IO operation functions +/** @defgroup HCD_Exported_Functions_Group2 IO operation functions * @brief HCD IO operation functions * @verbatim @@ -332,7 +332,7 @@ __weak void HAL_HCD_MspDeInit(HCD_HandleTypeDef *hhcd) */ HAL_StatusTypeDef HAL_HCD_HC_SubmitRequest(HCD_HandleTypeDef *hhcd, uint8_t ch_num, - uint8_t direction, + uint8_t direction , uint8_t ep_type, uint8_t token, uint8_t* pbuff, @@ -342,7 +342,7 @@ HAL_StatusTypeDef HAL_HCD_HC_SubmitRequest(HCD_HandleTypeDef *hhcd, hhcd->hc[ch_num].ep_is_in = direction; hhcd->hc[ch_num].ep_type = ep_type; - if(token == 0U) + if(token == 0) { hhcd->hc[ch_num].data_pid = HC_PID_SETUP; } @@ -355,21 +355,21 @@ HAL_StatusTypeDef HAL_HCD_HC_SubmitRequest(HCD_HandleTypeDef *hhcd, switch(ep_type) { case EP_TYPE_CTRL: - if((token == 1U) && (direction == 0U)) /*send data */ + if((token == 1) && (direction == 0)) /*send data */ { - if (length == 0U) + if ( length == 0 ) { /* For Status OUT stage, Length==0, Status Out PID = 1 */ - hhcd->hc[ch_num].toggle_out = 1U; + hhcd->hc[ch_num].toggle_out = 1; } /* Set the Data Toggle bit as per the Flag */ - if ( hhcd->hc[ch_num].toggle_out == 0U) + if ( hhcd->hc[ch_num].toggle_out == 0) { /* Put the PID 0 */ hhcd->hc[ch_num].data_pid = HC_PID_DATA0; } else { /* Put the PID 1 */ - hhcd->hc[ch_num].data_pid = HC_PID_DATA1; + hhcd->hc[ch_num].data_pid = HC_PID_DATA1 ; } if(hhcd->hc[ch_num].urb_state != URB_NOTREADY) { @@ -379,16 +379,16 @@ HAL_StatusTypeDef HAL_HCD_HC_SubmitRequest(HCD_HandleTypeDef *hhcd, break; case EP_TYPE_BULK: - if(direction == 0U) + if(direction == 0) { /* Set the Data Toggle bit as per the Flag */ - if ( hhcd->hc[ch_num].toggle_out == 0U) + if ( hhcd->hc[ch_num].toggle_out == 0) { /* Put the PID 0 */ hhcd->hc[ch_num].data_pid = HC_PID_DATA0; } else { /* Put the PID 1 */ - hhcd->hc[ch_num].data_pid = HC_PID_DATA1; + hhcd->hc[ch_num].data_pid = HC_PID_DATA1 ; } if(hhcd->hc[ch_num].urb_state != URB_NOTREADY) { @@ -397,7 +397,7 @@ HAL_StatusTypeDef HAL_HCD_HC_SubmitRequest(HCD_HandleTypeDef *hhcd, } else { - if( hhcd->hc[ch_num].toggle_in == 0U) + if( hhcd->hc[ch_num].toggle_in == 0) { hhcd->hc[ch_num].data_pid = HC_PID_DATA0; } @@ -409,21 +409,21 @@ HAL_StatusTypeDef HAL_HCD_HC_SubmitRequest(HCD_HandleTypeDef *hhcd, break; case EP_TYPE_INTR: - if(direction == 0U) + if(direction == 0) { /* Set the Data Toggle bit as per the Flag */ - if ( hhcd->hc[ch_num].toggle_out == 0U) + if ( hhcd->hc[ch_num].toggle_out == 0) { /* Put the PID 0 */ hhcd->hc[ch_num].data_pid = HC_PID_DATA0; } else { /* Put the PID 1 */ - hhcd->hc[ch_num].data_pid = HC_PID_DATA1; + hhcd->hc[ch_num].data_pid = HC_PID_DATA1 ; } } else { - if( hhcd->hc[ch_num].toggle_in == 0U) + if( hhcd->hc[ch_num].toggle_in == 0) { hhcd->hc[ch_num].data_pid = HC_PID_DATA0; } @@ -441,8 +441,8 @@ HAL_StatusTypeDef HAL_HCD_HC_SubmitRequest(HCD_HandleTypeDef *hhcd, hhcd->hc[ch_num].xfer_buff = pbuff; hhcd->hc[ch_num].xfer_len = length; - hhcd->hc[ch_num].urb_state = URB_IDLE; - hhcd->hc[ch_num].xfer_count = 0U; + hhcd->hc[ch_num].urb_state = URB_IDLE; + hhcd->hc[ch_num].xfer_count = 0 ; hhcd->hc[ch_num].ch_num = ch_num; hhcd->hc[ch_num].state = HC_IDLE; @@ -450,7 +450,7 @@ HAL_StatusTypeDef HAL_HCD_HC_SubmitRequest(HCD_HandleTypeDef *hhcd, } /** - * @brief handle HCD interrupt request. + * @brief This function handles HCD interrupt request. * @param hhcd: HCD handle * @retval None */ @@ -458,12 +458,12 @@ void HAL_HCD_IRQHandler(HCD_HandleTypeDef *hhcd) { USB_OTG_GlobalTypeDef *USBx = hhcd->Instance; - uint32_t index = 0U, interrupt = 0U; - + uint32_t index = 0 , interrupt = 0; + /* ensure that we are in device mode */ if (USB_GetMode(hhcd->Instance) == USB_OTG_MODE_HOST) { - /* Avoid spurious interrupt */ + /* avoid spurious interrupt */ if(__HAL_HCD_IS_INVALID_INTERRUPT(hhcd)) { return; @@ -471,25 +471,25 @@ void HAL_HCD_IRQHandler(HCD_HandleTypeDef *hhcd) if(__HAL_HCD_GET_FLAG(hhcd, USB_OTG_GINTSTS_PXFR_INCOMPISOOUT)) { - /* Incorrect mode, acknowledge the interrupt */ + /* incorrect mode, acknowledge the interrupt */ __HAL_HCD_CLEAR_FLAG(hhcd, USB_OTG_GINTSTS_PXFR_INCOMPISOOUT); } if(__HAL_HCD_GET_FLAG(hhcd, USB_OTG_GINTSTS_IISOIXFR)) { - /* Incorrect mode, acknowledge the interrupt */ + /* incorrect mode, acknowledge the interrupt */ __HAL_HCD_CLEAR_FLAG(hhcd, USB_OTG_GINTSTS_IISOIXFR); } if(__HAL_HCD_GET_FLAG(hhcd, USB_OTG_GINTSTS_PTXFE)) { - /* Incorrect mode, acknowledge the interrupt */ + /* incorrect mode, acknowledge the interrupt */ __HAL_HCD_CLEAR_FLAG(hhcd, USB_OTG_GINTSTS_PTXFE); } if(__HAL_HCD_GET_FLAG(hhcd, USB_OTG_GINTSTS_MMIS)) { - /* Incorrect mode, acknowledge the interrupt */ + /* incorrect mode, acknowledge the interrupt */ __HAL_HCD_CLEAR_FLAG(hhcd, USB_OTG_GINTSTS_MMIS); } @@ -503,7 +503,7 @@ void HAL_HCD_IRQHandler(HCD_HandleTypeDef *hhcd) /* Handle Host Port Interrupts */ HAL_HCD_Disconnect_Callback(hhcd); - USB_InitFSLSPClkSel(hhcd->Instance ,HCFG_48_MHZ); + USB_InitFSLSPClkSel(hhcd->Instance ,HCFG_48_MHZ ); __HAL_HCD_CLEAR_FLAG(hhcd, USB_OTG_GINTSTS_DISCINT); } @@ -524,7 +524,7 @@ void HAL_HCD_IRQHandler(HCD_HandleTypeDef *hhcd) if(__HAL_HCD_GET_FLAG(hhcd, USB_OTG_GINTSTS_HCINT)) { interrupt = USB_HC_ReadInterrupt(hhcd->Instance); - for (index = 0U; index < hhcd->Init.Host_channels ; index++) + for (index = 0; index < hhcd->Init.Host_channels ; index++) { if (interrupt & (1 << index)) { @@ -550,6 +550,7 @@ void HAL_HCD_IRQHandler(HCD_HandleTypeDef *hhcd) USB_UNMASK_INTERRUPT(hhcd->Instance, USB_OTG_GINTSTS_RXFLVL); } + } } @@ -582,7 +583,7 @@ __weak void HAL_HCD_Connect_Callback(HCD_HandleTypeDef *hhcd) } /** - * @brief Disonnection Event callback. + * @brief Disonnexion Event callback. * @param hhcd: HCD handle * @retval None */ @@ -607,7 +608,7 @@ __weak void HAL_HCD_Disconnect_Callback(HCD_HandleTypeDef *hhcd) * URB_NOTREADY/ * URB_NYET/ * URB_ERROR/ - * URB_STALL/ + * URB_STALL/ * @retval None */ __weak void HAL_HCD_HC_NotifyURBChange_Callback(HCD_HandleTypeDef *hhcd, uint8_t chnum, HCD_URBStateTypeDef urb_state) @@ -649,7 +650,7 @@ HAL_StatusTypeDef HAL_HCD_Start(HCD_HandleTypeDef *hhcd) { __HAL_LOCK(hhcd); __HAL_HCD_ENABLE(hhcd); - USB_DriveVbus(hhcd->Instance, 1U); + USB_DriveVbus(hhcd->Instance, 1); __HAL_UNLOCK(hhcd); return HAL_OK; } @@ -698,7 +699,7 @@ HAL_StatusTypeDef HAL_HCD_ResetPort(HCD_HandleTypeDef *hhcd) */ /** - * @brief Return the HCD handle state + * @brief Return the HCD state * @param hhcd: HCD handle * @retval HAL state */ @@ -801,7 +802,7 @@ uint32_t HAL_HCD_GetCurrentSpeed(HCD_HandleTypeDef *hhcd) static void HCD_HC_IN_IRQHandler (HCD_HandleTypeDef *hhcd, uint8_t chnum) { USB_OTG_GlobalTypeDef *USBx = hhcd->Instance; - uint32_t tmpreg = 0U; + uint32_t tmpreg = 0; if ((USBx_HC(chnum)->HCINT) & USB_OTG_HCINT_AHBERR) { @@ -840,7 +841,7 @@ static void HCD_HC_IN_IRQHandler (HCD_HandleTypeDef *hhcd, uint8_t chnum) else if ((USBx_HC(chnum)->HCINT) & USB_OTG_HCINT_XFRC) { hhcd->hc[chnum].state = HC_XFRC; - hhcd->hc[chnum].ErrCnt = 0U; + hhcd->hc[chnum].ErrCnt = 0; __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_XFRC); if ((hhcd->hc[chnum].ep_type == EP_TYPE_CTRL)|| @@ -857,7 +858,7 @@ static void HCD_HC_IN_IRQHandler (HCD_HandleTypeDef *hhcd, uint8_t chnum) hhcd->hc[chnum].urb_state = URB_DONE; HAL_HCD_HC_NotifyURBChange_Callback(hhcd, chnum, hhcd->hc[chnum].urb_state); } - hhcd->hc[chnum].toggle_in ^= 1U; + hhcd->hc[chnum].toggle_in ^= 1; } else if ((USBx_HC(chnum)->HCINT) & USB_OTG_HCINT_CHH) @@ -875,9 +876,9 @@ static void HCD_HC_IN_IRQHandler (HCD_HandleTypeDef *hhcd, uint8_t chnum) else if((hhcd->hc[chnum].state == HC_XACTERR) || (hhcd->hc[chnum].state == HC_DATATGLERR)) { - if(hhcd->hc[chnum].ErrCnt++ > 3U) + if(hhcd->hc[chnum].ErrCnt++ > 3) { - hhcd->hc[chnum].ErrCnt = 0U; + hhcd->hc[chnum].ErrCnt = 0; hhcd->hc[chnum].urb_state = URB_ERROR; } else @@ -934,7 +935,7 @@ static void HCD_HC_IN_IRQHandler (HCD_HandleTypeDef *hhcd, uint8_t chnum) static void HCD_HC_OUT_IRQHandler (HCD_HandleTypeDef *hhcd, uint8_t chnum) { USB_OTG_GlobalTypeDef *USBx = hhcd->Instance; - uint32_t tmpreg = 0U; + uint32_t tmpreg = 0; if ((USBx_HC(chnum)->HCINT) & USB_OTG_HCINT_AHBERR) { @@ -945,7 +946,7 @@ static void HCD_HC_OUT_IRQHandler (HCD_HandleTypeDef *hhcd, uint8_t chnum) { __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_ACK); - if( hhcd->hc[chnum].do_ping == 1U) + if( hhcd->hc[chnum].do_ping == 1) { hhcd->hc[chnum].state = HC_NYET; __HAL_HCD_UNMASK_HALT_HC_INT(chnum); @@ -957,7 +958,7 @@ static void HCD_HC_OUT_IRQHandler (HCD_HandleTypeDef *hhcd, uint8_t chnum) else if ((USBx_HC(chnum)->HCINT) & USB_OTG_HCINT_NYET) { hhcd->hc[chnum].state = HC_NYET; - hhcd->hc[chnum].ErrCnt= 0U; + hhcd->hc[chnum].ErrCnt= 0; __HAL_HCD_UNMASK_HALT_HC_INT(chnum); USB_HC_Halt(hhcd->Instance, chnum); __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_NYET); @@ -973,7 +974,7 @@ static void HCD_HC_OUT_IRQHandler (HCD_HandleTypeDef *hhcd, uint8_t chnum) else if ((USBx_HC(chnum)->HCINT) & USB_OTG_HCINT_XFRC) { - hhcd->hc[chnum].ErrCnt = 0U; + hhcd->hc[chnum].ErrCnt = 0; __HAL_HCD_UNMASK_HALT_HC_INT(chnum); USB_HC_Halt(hhcd->Instance, chnum); __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_XFRC); @@ -988,7 +989,7 @@ static void HCD_HC_OUT_IRQHandler (HCD_HandleTypeDef *hhcd, uint8_t chnum) } else if ((USBx_HC(chnum)->HCINT) & USB_OTG_HCINT_NAK) { - hhcd->hc[chnum].ErrCnt = 0U; + hhcd->hc[chnum].ErrCnt = 0; __HAL_HCD_UNMASK_HALT_HC_INT(chnum); USB_HC_Halt(hhcd->Instance, chnum); hhcd->hc[chnum].state = HC_NAK; @@ -1018,7 +1019,7 @@ static void HCD_HC_OUT_IRQHandler (HCD_HandleTypeDef *hhcd, uint8_t chnum) hhcd->hc[chnum].urb_state = URB_DONE; if (hhcd->hc[chnum].ep_type == EP_TYPE_BULK) { - hhcd->hc[chnum].toggle_out ^= 1U; + hhcd->hc[chnum].toggle_out ^= 1; } } else if (hhcd->hc[chnum].state == HC_NAK) @@ -1028,7 +1029,7 @@ static void HCD_HC_OUT_IRQHandler (HCD_HandleTypeDef *hhcd, uint8_t chnum) else if (hhcd->hc[chnum].state == HC_NYET) { hhcd->hc[chnum].urb_state = URB_NOTREADY; - hhcd->hc[chnum].do_ping = 0U; + hhcd->hc[chnum].do_ping = 0; } else if (hhcd->hc[chnum].state == HC_STALL) { @@ -1037,9 +1038,9 @@ static void HCD_HC_OUT_IRQHandler (HCD_HandleTypeDef *hhcd, uint8_t chnum) else if((hhcd->hc[chnum].state == HC_XACTERR) || (hhcd->hc[chnum].state == HC_DATATGLERR)) { - if(hhcd->hc[chnum].ErrCnt++ > 3U) + if(hhcd->hc[chnum].ErrCnt++ > 3) { - hhcd->hc[chnum].ErrCnt = 0U; + hhcd->hc[chnum].ErrCnt = 0; hhcd->hc[chnum].urb_state = URB_ERROR; } else @@ -1067,22 +1068,22 @@ static void HCD_HC_OUT_IRQHandler (HCD_HandleTypeDef *hhcd, uint8_t chnum) static void HCD_RXQLVL_IRQHandler (HCD_HandleTypeDef *hhcd) { USB_OTG_GlobalTypeDef *USBx = hhcd->Instance; - uint8_t channelnum =0U; + uint8_t channelnum =0; uint32_t pktsts; uint32_t pktcnt; - uint32_t temp = 0U; - uint32_t tmpreg = 0U; + uint32_t temp = 0; + uint32_t tmpreg = 0; temp = hhcd->Instance->GRXSTSP; channelnum = temp & USB_OTG_GRXSTSP_EPNUM; - pktsts = (temp & USB_OTG_GRXSTSP_PKTSTS) >> 17U; - pktcnt = (temp & USB_OTG_GRXSTSP_BCNT) >> 4U; + pktsts = (temp & USB_OTG_GRXSTSP_PKTSTS) >> 17; + pktcnt = (temp & USB_OTG_GRXSTSP_BCNT) >> 4; switch (pktsts) { case GRXSTS_PKTSTS_IN: /* Read the data into the host buffer. */ - if ((pktcnt > 0U) && (hhcd->hc[channelnum].xfer_buff != (void *)0U)) + if ((pktcnt > 0) && (hhcd->hc[channelnum].xfer_buff != (void *)0)) { USB_ReadPacket(hhcd->Instance, hhcd->hc[channelnum].xfer_buff, pktcnt); @@ -1090,14 +1091,14 @@ static void HCD_RXQLVL_IRQHandler (HCD_HandleTypeDef *hhcd) hhcd->hc[channelnum].xfer_buff += pktcnt; hhcd->hc[channelnum].xfer_count += pktcnt; - if((USBx_HC(channelnum)->HCTSIZ & USB_OTG_HCTSIZ_PKTCNT) > 0U) + if((USBx_HC(channelnum)->HCTSIZ & USB_OTG_HCTSIZ_PKTCNT) > 0) { /* re-activate the channel when more packets are expected */ tmpreg = USBx_HC(channelnum)->HCCHAR; tmpreg &= ~USB_OTG_HCCHAR_CHDIS; tmpreg |= USB_OTG_HCCHAR_CHENA; USBx_HC(channelnum)->HCCHAR = tmpreg; - hhcd->hc[channelnum].toggle_in ^= 1U; + hhcd->hc[channelnum].toggle_in ^= 1; } } break; @@ -1120,7 +1121,7 @@ static void HCD_RXQLVL_IRQHandler (HCD_HandleTypeDef *hhcd) static void HCD_Port_IRQHandler (HCD_HandleTypeDef *hhcd) { USB_OTG_GlobalTypeDef *USBx = hhcd->Instance; - __IO uint32_t hprt0 = 0, hprt0_dup = 0U; + __IO uint32_t hprt0 = 0, hprt0_dup = 0; /* Handle Host Port Interrupts */ hprt0 = USBx_HPRT0; @@ -1147,7 +1148,7 @@ static void HCD_Port_IRQHandler (HCD_HandleTypeDef *hhcd) if((hprt0 & USB_OTG_HPRT_PENA) == USB_OTG_HPRT_PENA) { - if ((hprt0 & USB_OTG_HPRT_PSPD) == (HPRT0_PRTSPD_LOW_SPEED << 17U)) + if ((hprt0 & USB_OTG_HPRT_PSPD) == (HPRT0_PRTSPD_LOW_SPEED << 17)) { USB_InitFSLSPClkSel(hhcd->Instance ,HCFG_6_MHZ ); } diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_hcd.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_hcd.h index abc302f0694..2d0437508fd 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_hcd.h +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_hcd.h @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_hal_hcd.h * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief Header file of HCD HAL module. ****************************************************************************** * @attention @@ -67,11 +67,11 @@ */ typedef enum { - HAL_HCD_STATE_RESET = 0x00U, - HAL_HCD_STATE_READY = 0x01U, - HAL_HCD_STATE_ERROR = 0x02U, - HAL_HCD_STATE_BUSY = 0x03U, - HAL_HCD_STATE_TIMEOUT = 0x04U + HAL_HCD_STATE_RESET = 0x00, + HAL_HCD_STATE_READY = 0x01, + HAL_HCD_STATE_ERROR = 0x02, + HAL_HCD_STATE_BUSY = 0x03, + HAL_HCD_STATE_TIMEOUT = 0x04 } HCD_StateTypeDef; typedef USB_OTG_GlobalTypeDef HCD_TypeDef; @@ -87,7 +87,7 @@ typedef struct { HCD_TypeDef *Instance; /*!< Register base address */ HCD_InitTypeDef Init; /*!< HCD required parameters */ - HCD_HCTypeDef hc[15U]; /*!< Host channels parameters */ + HCD_HCTypeDef hc[15]; /*!< Host channels parameters */ HAL_LockTypeDef Lock; /*!< HCD peripheral status */ __IO HCD_StateTypeDef State; /*!< HCD communication state */ void *pData; /*!< Pointer Stack Handler */ @@ -104,8 +104,8 @@ typedef struct /** @defgroup HCD_Speed HCD Speed * @{ */ -#define HCD_SPEED_LOW 2U -#define HCD_SPEED_FULL 3U +#define HCD_SPEED_LOW 2 +#define HCD_SPEED_FULL 3 /** * @} @@ -126,7 +126,7 @@ typedef struct #define __HAL_HCD_GET_FLAG(__HANDLE__, __INTERRUPT__) ((USB_ReadInterrupts((__HANDLE__)->Instance) & (__INTERRUPT__)) == (__INTERRUPT__)) #define __HAL_HCD_CLEAR_FLAG(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->GINTSTS) = (__INTERRUPT__)) -#define __HAL_HCD_IS_INVALID_INTERRUPT(__HANDLE__) (USB_ReadInterrupts((__HANDLE__)->Instance) == 0U) +#define __HAL_HCD_IS_INVALID_INTERRUPT(__HANDLE__) (USB_ReadInterrupts((__HANDLE__)->Instance) == 0) #define __HAL_HCD_CLEAR_HC_INT(chnum, __INTERRUPT__) (USBx_HC(chnum)->HCINT = (__INTERRUPT__)) diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_i2c.c b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_i2c.c index 3a950bad416..7c72e1f840d 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_i2c.c +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_i2c.c @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_hal_i2c.c * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief I2C HAL module driver. * This file provides firmware functions to manage the following * functionalities of the Inter Integrated Circuit (I2C) peripheral: @@ -669,7 +669,7 @@ HAL_StatusTypeDef HAL_I2C_Master_Transmit(I2C_HandleTypeDef *hi2c, uint16_t DevA hi2c->XferCount--; hi2c->XferSize--; - if((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF) == SET) && (hi2c->XferSize != 0U)) + if((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF) == SET) && (Size != 0U)) { /* Write data to DR */ hi2c->Instance->DR = (*hi2c->pBuffPtr++); @@ -1065,7 +1065,7 @@ HAL_StatusTypeDef HAL_I2C_Slave_Transmit(I2C_HandleTypeDef *hi2c, uint8_t *pData hi2c->XferCount--; hi2c->XferSize--; - if((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF) == SET) && (hi2c->XferSize != 0U)) + if((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF) == SET) && (Size != 0U)) { /* Write data to DR */ hi2c->Instance->DR = (*hi2c->pBuffPtr++); @@ -2197,9 +2197,6 @@ HAL_StatusTypeDef HAL_I2C_Master_Receive_DMA(I2C_HandleTypeDef *hi2c, uint16_t D */ HAL_StatusTypeDef HAL_I2C_Master_Abort_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(DevAddress); - /* Abort Master transfer during Receive or Transmit process */ if(hi2c->Mode == HAL_I2C_MODE_MASTER) { @@ -2707,7 +2704,7 @@ HAL_StatusTypeDef HAL_I2C_Mem_Read(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, hi2c->XferCount--; } /* Two bytes */ - else if(hi2c->XferSize == 2U) + else if(Size == 2U) { /* Wait until BTF flag is set */ if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BTF, RESET, Timeout, tickstart) != HAL_OK) diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_i2c.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_i2c.h index 36842f5acb6..5af2067ef78 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_i2c.h +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_i2c.h @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_hal_i2c.h * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief Header file of I2C HAL module. ****************************************************************************** * @attention @@ -438,7 +438,7 @@ typedef struct tmpreg = (__HANDLE__)->Instance->SR1; \ tmpreg = (__HANDLE__)->Instance->SR2; \ UNUSED(tmpreg); \ - } while(0U) + } while(0) /** @brief Clears the I2C STOPF pending flag. * @param __HANDLE__: specifies the I2C Handle. @@ -451,7 +451,7 @@ typedef struct tmpreg = (__HANDLE__)->Instance->SR1; \ (__HANDLE__)->Instance->CR1 |= I2C_CR1_PE; \ UNUSED(tmpreg); \ - } while(0U) + } while(0) /** @brief Enable the I2C peripheral. * @param __HANDLE__: specifies the I2C Handle. diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_i2s.c b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_i2s.c index 332717572f6..2246e5e70bc 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_i2s.c +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_i2s.c @@ -2,10 +2,10 @@ ****************************************************************************** * @file stm32f1xx_hal_i2s.c * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief I2S HAL module driver. - * This file provides firmware functions to manage the following + * This file provides firmware functions to manage the following * functionalities of the Integrated Interchip Sound (I2S) peripheral: * + Initialization and de-initialization functions * + IO operation functions @@ -16,10 +16,10 @@ =============================================================================== [..] The I2S HAL driver can be used as follow: - + (#) Declare a I2S_HandleTypeDef handle structure. (#) Initialize the I2S low level resources by implement the HAL_I2S_MspInit() API: - (##) Enable the SPIx interface clock. + (##) Enable the SPIx interface clock. (##) I2S pins configuration: (+++) Enable the clock for the I2S GPIOs. (+++) Configure these I2S pins as alternate function. @@ -33,14 +33,14 @@ (+++) Enable the DMAx interface clock. (+++) Configure the declared DMA handle structure with the required Tx/Rx parameters. (+++) Configure the DMA Tx/Rx Channel. - (+++) Associate the initialized DMA handle to the I2S DMA Tx/Rx handle. + (+++) Associate the initilalized DMA handle to the I2S DMA Tx/Rx handle. (+++) Configure the priority and enable the NVIC for the transfer complete interrupt on the DMA Tx/Rx Channel. (#) Program the Mode, Standard, Data Format, MCLK Output, Audio frequency and Polarity using HAL_I2S_Init() function. - -@- The specific I2S interrupts (Transmission complete interrupt, + -@- The specific I2S interrupts (Transmission complete interrupt, RXNE interrupt and Error Interrupts) will be managed using the macros __HAL_I2S_ENABLE_IT() and __HAL_I2S_DISABLE_IT() inside the transmit and receive process. -@- The I2SxCLK source is the system clock (provided by the HSI, the HSE or the PLL, and sourcing the AHB clock). @@ -50,44 +50,44 @@ (+@) External clock source is configured after setting correctly the define constant HSE_VALUE in the stm32f1xx_hal_conf.h file. - (#) Three operation modes are available within this driver : + (#) Three mode of operations are available within this driver : *** Polling mode IO operation *** ================================= - [..] - (+) Send an amount of data in blocking mode using HAL_I2S_Transmit() + [..] + (+) Send an amount of data in blocking mode using HAL_I2S_Transmit() (+) Receive an amount of data in blocking mode using HAL_I2S_Receive() - + *** Interrupt mode IO operation *** =================================== - [..] - (+) Send an amount of data in non blocking mode using HAL_I2S_Transmit_IT() - (+) At transmission end of half transfer HAL_I2S_TxHalfCpltCallback is executed and user can - add his own code by customization of function pointer HAL_I2S_TxHalfCpltCallback - (+) At transmission end of transfer HAL_I2S_TxCpltCallback is executed and user can + [..] + (+) Send an amount of data in non blocking mode using HAL_I2S_Transmit_IT() + (+) At transmission end of half transfer HAL_I2S_TxHalfCpltCallback is executed and user can + add his own code by customization of function pointer HAL_I2S_TxHalfCpltCallback + (+) At transmission end of transfer HAL_I2S_TxCpltCallback is executed and user can add his own code by customization of function pointer HAL_I2S_TxCpltCallback - (+) Receive an amount of data in non blocking mode using HAL_I2S_Receive_IT() - (+) At reception end of half transfer HAL_I2S_RxHalfCpltCallback is executed and user can - add his own code by customization of function pointer HAL_I2S_RxHalfCpltCallback - (+) At reception end of transfer HAL_I2S_RxCpltCallback is executed and user can + (+) Receive an amount of data in non blocking mode using HAL_I2S_Receive_IT() + (+) At reception end of half transfer HAL_I2S_RxHalfCpltCallback is executed and user can + add his own code by customization of function pointer HAL_I2S_RxHalfCpltCallback + (+) At reception end of transfer HAL_I2S_RxCpltCallback is executed and user can add his own code by customization of function pointer HAL_I2S_RxCpltCallback - (+) In case of transfer Error, HAL_I2S_ErrorCallback() function is executed and user can + (+) In case of transfer Error, HAL_I2S_ErrorCallback() function is executed and user can add his own code by customization of function pointer HAL_I2S_ErrorCallback *** DMA mode IO operation *** ============================== - [..] - (+) Send an amount of data in non blocking mode (DMA) using HAL_I2S_Transmit_DMA() - (+) At transmission end of half transfer HAL_I2S_TxHalfCpltCallback is executed and user can - add his own code by customization of function pointer HAL_I2S_TxHalfCpltCallback - (+) At transmission end of transfer HAL_I2S_TxCpltCallback is executed and user can + [..] + (+) Send an amount of data in non blocking mode (DMA) using HAL_I2S_Transmit_DMA() + (+) At transmission end of half transfer HAL_I2S_TxHalfCpltCallback is executed and user can + add his own code by customization of function pointer HAL_I2S_TxHalfCpltCallback + (+) At transmission end of transfer HAL_I2S_TxCpltCallback is executed and user can add his own code by customization of function pointer HAL_I2S_TxCpltCallback - (+) Receive an amount of data in non blocking mode (DMA) using HAL_I2S_Receive_DMA() - (+) At reception end of half transfer HAL_I2S_RxHalfCpltCallback is executed and user can - add his own code by customization of function pointer HAL_I2S_RxHalfCpltCallback - (+) At reception end of transfer HAL_I2S_RxCpltCallback is executed and user can + (+) Receive an amount of data in non blocking mode (DMA) using HAL_I2S_Receive_DMA() + (+) At reception end of half transfer HAL_I2S_RxHalfCpltCallback is executed and user can + add his own code by customization of function pointer HAL_I2S_RxHalfCpltCallback + (+) At reception end of transfer HAL_I2S_RxCpltCallback is executed and user can add his own code by customization of function pointer HAL_I2S_RxCpltCallback - (+) In case of transfer Error, HAL_I2S_ErrorCallback() function is executed and user can + (+) In case of transfer Error, HAL_I2S_ErrorCallback() function is executed and user can add his own code by customization of function pointer HAL_I2S_ErrorCallback (+) Pause the DMA Transfer using HAL_I2S_DMAPause() (+) Resume the DMA Transfer using HAL_I2S_DMAResume() @@ -96,9 +96,9 @@ *** I2S HAL driver macros list *** ============================================= [..] - Below the list of most used macros in I2S HAL driver. - - (+) __HAL_I2S_ENABLE: Enable the specified SPI peripheral (in I2S mode) + Below the list of most used macros in USART HAL driver. + + (+) __HAL_I2S_ENABLE: Enable the specified SPI peripheral (in I2S mode) (+) __HAL_I2S_DISABLE: Disable the specified SPI peripheral (in I2S mode) (+) __HAL_I2S_ENABLE_IT : Enable the specified I2S interrupts (+) __HAL_I2S_DISABLE_IT : Disable the specified I2S interrupts @@ -119,7 +119,7 @@ ****************************************************************************** * @attention * - *

© COPYRIGHT(c) 2017 STMicroelectronics

+ *

© COPYRIGHT(c) 2016 STMicroelectronics

* * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: @@ -144,7 +144,7 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** - */ + */ /* Includes ------------------------------------------------------------------*/ #include "stm32f1xx_hal.h" @@ -152,7 +152,7 @@ /** @addtogroup STM32F1xx_HAL_Driver * @{ */ - + #ifdef HAL_I2S_MODULE_ENABLED #if defined(STM32F103xE) || defined(STM32F103xG) || defined(STM32F105xC) || defined(STM32F107xC) @@ -170,54 +170,52 @@ * @{ */ static void I2S_DMATxCplt(DMA_HandleTypeDef *hdma); -static void I2S_DMATxHalfCplt(DMA_HandleTypeDef *hdma); +static void I2S_DMATxHalfCplt(DMA_HandleTypeDef *hdma); static void I2S_DMARxCplt(DMA_HandleTypeDef *hdma); static void I2S_DMARxHalfCplt(DMA_HandleTypeDef *hdma); static void I2S_DMAError(DMA_HandleTypeDef *hdma); static void I2S_Transmit_IT(I2S_HandleTypeDef *hi2s); static void I2S_Receive_IT(I2S_HandleTypeDef *hi2s); -static void I2S_IRQHandler(I2S_HandleTypeDef *hi2s); -static HAL_StatusTypeDef I2S_WaitFlagStateUntilTimeout(I2S_HandleTypeDef *hi2s, uint32_t Flag, uint32_t State, - uint32_t Timeout); +static HAL_StatusTypeDef I2S_WaitFlagStateUntilTimeout(I2S_HandleTypeDef *hi2s, uint32_t Flag, uint32_t Status, uint32_t Timeout); /** * @} */ - + /* Exported functions ---------------------------------------------------------*/ /** @defgroup I2S_Exported_Functions I2S Exported Functions * @{ */ /** @defgroup I2S_Exported_Functions_Group1 Initialization and de-initialization functions - * @brief Initialization and Configuration functions + * @brief Initialization and Configuration functions * -@verbatim +@verbatim =============================================================================== ##### Initialization and de-initialization functions ##### =============================================================================== - [..] This subsection provides a set of functions allowing to initialize and - de-initialize the I2Sx peripheral in simplex mode: + [..] This subsection provides a set of functions allowing to initialize and + de-initialiaze the I2Sx peripheral in simplex mode: - (+) User must Implement HAL_I2S_MspInit() function in which he configures + (+) User must Implement HAL_I2S_MspInit() function in which he configures all related peripherals resources (CLOCK, GPIO, DMA, IT and NVIC ). - (+) Call the function HAL_I2S_Init() to configure the selected device with + (+) Call the function HAL_I2S_Init() to configure the selected device with the selected configuration: (++) Mode - (++) Standard + (++) Standard (++) Data Format (++) MCLK Output (++) Audio frequency (++) Polarity - (+) Call the function HAL_I2S_DeInit() to restore the default configuration - of the selected I2Sx peripheral. -@endverbatim + (+) Call the function HAL_I2S_DeInit() to restore the default configuration + of the selected I2Sx periperal. + @endverbatim * @{ */ /** - * @brief Initializes the I2S according to the specified parameters + * @brief Initializes the I2S according to the specified parameters * in the I2S_InitTypeDef and create the associated handle. * @param hi2s: pointer to a I2S_HandleTypeDef structure that contains * the configuration information for I2S module @@ -225,15 +223,15 @@ static HAL_StatusTypeDef I2S_WaitFlagStateUntilTimeout(I2S_HandleTypeDef *hi2s, */ HAL_StatusTypeDef HAL_I2S_Init(I2S_HandleTypeDef *hi2s) { - uint32_t tmpreg = 0U, i2sdiv = 2U, i2sodd = 0U, packetlength = 16U; - uint32_t tmp = 0U, i2sclk = 0U; - + uint32_t i2sdiv = 2, i2sodd = 0, packetlength = 1; + uint32_t tmp = 0, i2sclk = 0; + /* Check the I2S handle allocation */ if(hi2s == NULL) { return HAL_ERROR; } - + /* Check the I2S parameters */ assert_param(IS_I2S_ALL_INSTANCE(hi2s->Instance)); assert_param(IS_I2S_MODE(hi2s->Init.Mode)); @@ -241,50 +239,40 @@ HAL_StatusTypeDef HAL_I2S_Init(I2S_HandleTypeDef *hi2s) assert_param(IS_I2S_DATA_FORMAT(hi2s->Init.DataFormat)); assert_param(IS_I2S_MCLK_OUTPUT(hi2s->Init.MCLKOutput)); assert_param(IS_I2S_AUDIO_FREQ(hi2s->Init.AudioFreq)); - assert_param(IS_I2S_CPOL(hi2s->Init.CPOL)); - + assert_param(IS_I2S_CPOL(hi2s->Init.CPOL)); + + if(hi2s->State == HAL_I2S_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + hi2s->Lock = HAL_UNLOCKED; + + /* Init the low level hardware : GPIO, CLOCK, CORTEX...etc */ + HAL_I2S_MspInit(hi2s); + } + hi2s->State = HAL_I2S_STATE_BUSY; - /* Initialize Default I2S IrqHandler ISR */ - hi2s->IrqHandlerISR = I2S_IRQHandler; - - /* Init the low level hardware : GPIO, CLOCK, CORTEX...etc */ - HAL_I2S_MspInit(hi2s); - - /*----------------------- SPIx I2SCFGR & I2SPR Configuration ---------------*/ - /* Clear I2SMOD, I2SE, I2SCFG, PCMSYNC, I2SSTD, CKPOL, DATLEN and CHLEN bits */ - CLEAR_BIT(hi2s->Instance->I2SCFGR,(SPI_I2SCFGR_CHLEN | SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CKPOL | \ - SPI_I2SCFGR_I2SSTD | SPI_I2SCFGR_PCMSYNC | SPI_I2SCFGR_I2SCFG | \ - SPI_I2SCFGR_I2SE | SPI_I2SCFGR_I2SMOD)); - hi2s->Instance->I2SPR = 0x0002U; - - /* Get the I2SCFGR register value */ - tmpreg = hi2s->Instance->I2SCFGR; - - /* If the default frequency value has to be written, reinitialize i2sdiv and i2sodd */ + /* If the default value has to be written, reinitialize i2sdiv and i2sodd*/ + if(hi2s->Init.AudioFreq == I2S_AUDIOFREQ_DEFAULT) + { + i2sodd = (uint32_t)0; + i2sdiv = (uint32_t)2; + } /* If the requested audio frequency is not the default, compute the prescaler */ - if(hi2s->Init.AudioFreq != I2S_AUDIOFREQ_DEFAULT) + else { /* Check the frame length (For the Prescaler computing) *******************/ - /* Set I2S Packet Length value*/ - if(hi2s->Init.DataFormat != I2S_DATAFORMAT_16B) - { - /* Packet length is 32 bits */ - packetlength = 32U; - } - else + if(hi2s->Init.DataFormat == I2S_DATAFORMAT_16B) { /* Packet length is 16 bits */ - packetlength = 16U; + packetlength = 1; } - - /* I2S standard */ - if(hi2s->Init.Standard <= I2S_STANDARD_LSB) + else { - /* In I2S standard packet lenght is multiplied by 2 */ - packetlength = packetlength * 2U; + /* Packet length is 32 bits */ + packetlength = 2; } - + if(hi2s->Instance == SPI2) { /* Get the source clock value: based on SPI2 Instance */ @@ -298,71 +286,68 @@ HAL_StatusTypeDef HAL_I2S_Init(I2S_HandleTypeDef *hi2s) else { /* Get the source clock value: based on System Clock value */ - i2sclk = HAL_RCC_GetSysClockFreq(); + i2sclk = HAL_RCC_GetSysClockFreq(); } - + if(i2sclk == 0) + { + return HAL_ERROR; + } + /* Compute the Real divider depending on the MCLK output state, with a floating point */ if(hi2s->Init.MCLKOutput == I2S_MCLKOUTPUT_ENABLE) { /* MCLK output is enabled */ - if (hi2s->Init.DataFormat != I2S_DATAFORMAT_16B) - { - tmp = (uint32_t)(((((i2sclk / (packetlength*4)) * 10) / hi2s->Init.AudioFreq)) + 5); - } - else - { - tmp = (uint32_t)(((((i2sclk / (packetlength*8)) * 10) / hi2s->Init.AudioFreq)) + 5); - } + tmp = (uint32_t)(((((i2sclk / 256) * 10) / hi2s->Init.AudioFreq)) + 5); } else { /* MCLK output is disabled */ - tmp = (uint32_t)(((((i2sclk / packetlength) *10 ) / hi2s->Init.AudioFreq)) + 5); + tmp = (uint32_t)(((((i2sclk / (32 * packetlength)) *10 ) / hi2s->Init.AudioFreq)) + 5); } /* Remove the flatting point */ - tmp = tmp / 10U; + tmp = tmp / 10; /* Check the parity of the divider */ - i2sodd = (uint16_t)(tmp & (uint16_t)1U); + i2sodd = (uint32_t)(tmp & (uint32_t)1); /* Compute the i2sdiv prescaler */ - i2sdiv = (uint16_t)((tmp - i2sodd) / 2U); + i2sdiv = (uint32_t)((tmp - i2sodd) / 2); /* Get the Mask for the Odd bit (SPI_I2SPR[8]) register */ - i2sodd = (uint32_t) (i2sodd << 8U); + i2sodd = (uint32_t) (i2sodd << 8); } /* Test if the divider is 1 or 0 or greater than 0xFF */ - if((i2sdiv < 2U) || (i2sdiv > 0xFFU)) + if((i2sdiv < 2) || (i2sdiv > 0xFF)) { /* Set the default values */ - i2sdiv = 2U; - i2sodd = 0U; - - /* Set the error code and execute error callback*/ - SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_PRESCALER); - HAL_I2S_ErrorCallback(hi2s); - return HAL_ERROR; + i2sdiv = 2; + i2sodd = 0; } + /*----------------------- SPIx I2SCFGR & I2SPR Configuration ----------------*/ + /* Clear I2SMOD, I2SE, I2SCFG, PCMSYNC, I2SSTD, CKPOL, DATLEN and CHLEN bits */ + /* And configure the I2S with the I2S_InitStruct values */ + MODIFY_REG( hi2s->Instance->I2SCFGR, (SPI_I2SCFGR_CHLEN | SPI_I2SCFGR_DATLEN |\ + SPI_I2SCFGR_CKPOL | SPI_I2SCFGR_I2SSTD |\ + SPI_I2SCFGR_PCMSYNC | SPI_I2SCFGR_I2SCFG |\ + SPI_I2SCFGR_I2SE | SPI_I2SCFGR_I2SMOD),\ + (SPI_I2SCFGR_I2SMOD | hi2s->Init.Mode |\ + hi2s->Init.Standard | hi2s->Init.DataFormat |\ + hi2s->Init.CPOL)); + /* Write to SPIx I2SPR register the computed value */ hi2s->Instance->I2SPR = (uint32_t)((uint32_t)i2sdiv | (uint32_t)(i2sodd | (uint32_t)hi2s->Init.MCLKOutput)); - /* Configure the I2S with the I2S_InitStruct values */ - tmpreg |= (uint16_t)((uint16_t)SPI_I2SCFGR_I2SMOD | (uint16_t)(hi2s->Init.Mode | \ - (uint16_t)(hi2s->Init.Standard | (uint16_t)(hi2s->Init.DataFormat | \ - (uint16_t)hi2s->Init.CPOL)))); - /* Write to SPIx I2SCFGR */ - WRITE_REG(hi2s->Instance->I2SCFGR,tmpreg); hi2s->ErrorCode = HAL_I2S_ERROR_NONE; - hi2s->State = HAL_I2S_STATE_READY; + hi2s->State= HAL_I2S_STATE_READY; return HAL_OK; } /** - * @brief DeInitializes the I2S peripheral + * @brief DeInitializes the I2S peripheral * @param hi2s: pointer to a I2S_HandleTypeDef structure that contains * the configuration information for I2S module * @retval HAL status @@ -374,14 +359,17 @@ HAL_StatusTypeDef HAL_I2S_DeInit(I2S_HandleTypeDef *hi2s) { return HAL_ERROR; } - + hi2s->State = HAL_I2S_STATE_BUSY; + + /* Disable the I2S Peripheral Clock */ + __HAL_I2S_DISABLE(hi2s); /* DeInit the low level hardware: GPIO, CLOCK, NVIC... */ HAL_I2S_MspDeInit(hi2s); hi2s->ErrorCode = HAL_I2S_ERROR_NONE; - hi2s->State = HAL_I2S_STATE_RESET; + hi2s->State = HAL_I2S_STATE_RESET; /* Release Lock */ __HAL_UNLOCK(hi2s); @@ -401,7 +389,7 @@ HAL_StatusTypeDef HAL_I2S_DeInit(I2S_HandleTypeDef *hi2s) UNUSED(hi2s); /* NOTE : This function Should not be modified, when the callback is needed, the HAL_I2S_MspInit could be implemented in the user file - */ + */ } /** @@ -416,8 +404,9 @@ HAL_StatusTypeDef HAL_I2S_DeInit(I2S_HandleTypeDef *hi2s) UNUSED(hi2s); /* NOTE : This function Should not be modified, when the callback is needed, the HAL_I2S_MspDeInit could be implemented in the user file - */ + */ } + /** * @} */ @@ -425,28 +414,28 @@ HAL_StatusTypeDef HAL_I2S_DeInit(I2S_HandleTypeDef *hi2s) /** @defgroup I2S_Exported_Functions_Group2 IO operation functions * @brief Data transfers functions * -@verbatim +@verbatim =============================================================================== ##### IO operation functions ##### =============================================================================== [..] - This subsection provides a set of functions allowing to manage the I2S data + This subsection provides a set of functions allowing to manage the I2S data transfers. (#) There are two modes of transfer: - (++) Blocking mode : The communication is performed in the polling mode. - The status of all data processing is returned by the same function - after finishing transfer. - (++) No-Blocking mode : The communication is performed using Interrupts + (++) Blocking mode : The communication is performed in the polling mode. + The status of all data processing is returned by the same function + after finishing transfer. + (++) No-Blocking mode : The communication is performed using Interrupts or DMA. These functions return the status of the transfer startup. - The end of the data processing will be indicated through the - dedicated I2S IRQ when using Interrupt mode or the DMA IRQ when + The end of the data processing will be indicated through the + dedicated I2S IRQ when using Interrupt mode or the DMA IRQ when using DMA mode. (#) Blocking mode functions are : (++) HAL_I2S_Transmit() (++) HAL_I2S_Receive() - + (#) No-Blocking mode functions with Interrupt are : (++) HAL_I2S_Transmit_IT() (++) HAL_I2S_Receive_IT() @@ -471,200 +460,195 @@ HAL_StatusTypeDef HAL_I2S_DeInit(I2S_HandleTypeDef *hi2s) * @param pData: a 16-bit pointer to data buffer. * @param Size: number of data sample to be sent: * @note When a 16-bit data frame or a 16-bit data frame extended is selected during the I2S - * configuration phase, the Size parameter means the number of 16-bit data length - * in the transaction and when a 24-bit data frame or a 32-bit data frame is selected - * the Size parameter means the number of 16-bit data length. + * configuration phase, the Size parameter means the number of 16-bit data length + * in the transaction and when a 24-bit data frame or a 32-bit data frame is selected + * the Size parameter means the number of 16-bit data length. * @param Timeout: Timeout duration - * @note The I2S is kept enabled at the end of transaction to avoid the clock de-synchronization + * @note The I2S is kept enabled at the end of transaction to avoid the clock de-synchronization * between Master and Slave(example: audio streaming). * @retval HAL status */ HAL_StatusTypeDef HAL_I2S_Transmit(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size, uint32_t Timeout) { - uint32_t tmp1 = 0U; - - if((pData == NULL ) || (Size == 0U)) + if((pData == NULL ) || (Size == 0)) { - return HAL_ERROR; + return HAL_ERROR; } + + /* Process Locked */ + __HAL_LOCK(hi2s); if(hi2s->State == HAL_I2S_STATE_READY) - { - tmp1 = hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN); - - if((tmp1 == I2S_DATAFORMAT_24B) || (tmp1 == I2S_DATAFORMAT_32B)) + { + if(((hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN)) == I2S_DATAFORMAT_24B)||\ + ((hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN)) == I2S_DATAFORMAT_32B)) { - hi2s->TxXferSize = (Size << 1U); - hi2s->TxXferCount = (Size << 1U); + hi2s->TxXferSize = (Size << 1); + hi2s->TxXferCount = (Size << 1); } else { - hi2s->TxXferSize = Size; + hi2s->TxXferSize = Size; hi2s->TxXferCount = Size; } - - /* Process Locked */ - __HAL_LOCK(hi2s); - + + /* Set state and reset error code */ hi2s->ErrorCode = HAL_I2S_ERROR_NONE; - hi2s->State = HAL_I2S_STATE_BUSY_TX; - - /* Check if the I2S is already enabled */ - if((hi2s->Instance->I2SCFGR &SPI_I2SCFGR_I2SE) != SPI_I2SCFGR_I2SE) + hi2s->State = HAL_I2S_STATE_BUSY_TX; + hi2s->pTxBuffPtr = pData; + + /* Check if the I2S is already enabled */ + if((hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SE) != SPI_I2SCFGR_I2SE) { /* Enable I2S peripheral */ __HAL_I2S_ENABLE(hi2s); } - - while(hi2s->TxXferCount > 0U) + + while(hi2s->TxXferCount > 0) { - hi2s->Instance->DR = (*pData++); - hi2s->TxXferCount--; - /* Wait until TXE flag is set */ - if (I2S_WaitFlagStateUntilTimeout(hi2s, I2S_FLAG_TXE, SET, Timeout) != HAL_OK) + if (I2S_WaitFlagStateUntilTimeout(hi2s, I2S_FLAG_TXE, RESET, Timeout) != HAL_OK) { - /* Set the error code and execute error callback*/ - SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_TIMEOUT); - HAL_I2S_ErrorCallback(hi2s); return HAL_TIMEOUT; } + hi2s->Instance->DR = (*hi2s->pTxBuffPtr++); + hi2s->TxXferCount--; /* Check if an underrun occurs */ - if(__HAL_I2S_GET_FLAG(hi2s, I2S_FLAG_UDR) == SET) + if(__HAL_I2S_GET_FLAG(hi2s, I2S_FLAG_UDR) == SET) { - /* Clear underrun flag */ - __HAL_I2S_CLEAR_UDRFLAG(hi2s); /* Set the I2S State ready */ - hi2s->State = HAL_I2S_STATE_READY; + hi2s->State = HAL_I2S_STATE_READY; /* Process Unlocked */ __HAL_UNLOCK(hi2s); /* Set the error code and execute error callback*/ - SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_UDR); - HAL_I2S_ErrorCallback(hi2s); - + hi2s->ErrorCode |= HAL_I2S_ERROR_UDR; return HAL_ERROR; } - } - hi2s->State = HAL_I2S_STATE_READY; + } + /* Wait until TXE flag is set, to confirm the end of the transcation */ + if (I2S_WaitFlagStateUntilTimeout(hi2s, I2S_FLAG_TXE, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + /* Check if Slave mode is selected */ + if(((hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SCFG) == I2S_MODE_SLAVE_TX) || ((hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SCFG) == I2S_MODE_SLAVE_RX)) + { + /* Wait until Busy flag is reset */ + if (I2S_WaitFlagStateUntilTimeout(hi2s, I2S_FLAG_BSY, SET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + } + hi2s->State = HAL_I2S_STATE_READY; + /* Process Unlocked */ __HAL_UNLOCK(hi2s); - + return HAL_OK; } else { + /* Process Unlocked */ + __HAL_UNLOCK(hi2s); return HAL_BUSY; } } /** - * @brief Receive an amount of data in blocking mode + * @brief Receive an amount of data in blocking mode * @param hi2s: pointer to a I2S_HandleTypeDef structure that contains * the configuration information for I2S module - * @param pData: a 16-bit pointer to data buffer + * @param pData: a 16-bit pointer to data buffer. * @param Size: number of data sample to be sent: * @note When a 16-bit data frame or a 16-bit data frame extended is selected during the I2S - * configuration phase, the Size parameter means the number of 16-bit data length - * in the transaction and when a 24-bit data frame or a 32-bit data frame is selected - * the Size parameter means the number of 16-bit data length. + * configuration phase, the Size parameter means the number of 16-bit data length + * in the transaction and when a 24-bit data frame or a 32-bit data frame is selected + * the Size parameter means the number of 16-bit data length. * @param Timeout: Timeout duration - * @note The I2S is kept enabled at the end of transaction to avoid the clock de-synchronization - * between Master and Slave(example: audio streaming) + * @note The I2S is kept enabled at the end of transaction to avoid the clock de-synchronization + * between Master and Slave(example: audio streaming). * @note In I2S Master Receiver mode, just after enabling the peripheral the clock will be generate - * in continuous way and as the I2S is not disabled at the end of the I2S transaction + * in continouse way and as the I2S is not disabled at the end of the I2S transaction. * @retval HAL status */ HAL_StatusTypeDef HAL_I2S_Receive(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size, uint32_t Timeout) { - uint32_t tmp1 = 0U; - - if((pData == NULL ) || (Size == 0U)) + if((pData == NULL ) || (Size == 0)) { return HAL_ERROR; } - + + /* Process Locked */ + __HAL_LOCK(hi2s); + if(hi2s->State == HAL_I2S_STATE_READY) - { - tmp1 = hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN); - if((tmp1 == I2S_DATAFORMAT_24B) || (tmp1 == I2S_DATAFORMAT_32B)) + { + if(((hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN)) == I2S_DATAFORMAT_24B)||\ + ((hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN)) == I2S_DATAFORMAT_32B)) { - hi2s->RxXferSize = (Size << 1U); - hi2s->RxXferCount = (Size << 1U); + hi2s->RxXferSize = (Size << 1); + hi2s->RxXferCount = (Size << 1); } else { - hi2s->RxXferSize = Size; + hi2s->RxXferSize = Size; hi2s->RxXferCount = Size; } - /* Process Locked */ - __HAL_LOCK(hi2s); - + + /* Set state and reset error code */ hi2s->ErrorCode = HAL_I2S_ERROR_NONE; - hi2s->State = HAL_I2S_STATE_BUSY_RX; - - /* Check if the I2S is already enabled */ + hi2s->State = HAL_I2S_STATE_BUSY_RX; + hi2s->pRxBuffPtr = pData; + + /* Check if the I2S is already enabled */ if((hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SE) != SPI_I2SCFGR_I2SE) { /* Enable I2S peripheral */ __HAL_I2S_ENABLE(hi2s); } - - /* Check if Master Receiver mode is selected */ - if((hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SCFG) == I2S_MODE_MASTER_RX) - { - /* Clear the Overrun Flag by a read operation on the SPI_DR register followed by a read - access to the SPI_SR register. */ - __HAL_I2S_CLEAR_OVRFLAG(hi2s); - } - + /* Receive data */ - while(hi2s->RxXferCount > 0U) + while(hi2s->RxXferCount > 0) { - /* Wait until RXNE flag is set */ - if (I2S_WaitFlagStateUntilTimeout(hi2s, I2S_FLAG_RXNE, SET, Timeout) != HAL_OK) + /* Wait until RXNE flag is reset */ + if (I2S_WaitFlagStateUntilTimeout(hi2s, I2S_FLAG_RXNE, RESET, Timeout) != HAL_OK) { - /* Set the error code and execute error callback*/ - SET_BIT(hi2s->ErrorCode,HAL_I2S_ERROR_TIMEOUT); - HAL_I2S_ErrorCallback(hi2s); return HAL_TIMEOUT; } + + (*hi2s->pRxBuffPtr++) = hi2s->Instance->DR; + hi2s->RxXferCount--; /* Check if an overrun occurs */ - if(__HAL_I2S_GET_FLAG(hi2s, I2S_FLAG_OVR) == SET) + if(__HAL_I2S_GET_FLAG(hi2s, I2S_FLAG_OVR) == SET) { - /* Clear overrun flag */ - __HAL_I2S_CLEAR_OVRFLAG(hi2s); - /* Set the I2S State ready */ - hi2s->State = HAL_I2S_STATE_READY; + hi2s->State = HAL_I2S_STATE_READY; /* Process Unlocked */ __HAL_UNLOCK(hi2s); /* Set the error code and execute error callback*/ - SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_OVR); - HAL_I2S_ErrorCallback(hi2s); - + hi2s->ErrorCode |= HAL_I2S_ERROR_OVR; return HAL_ERROR; } - - (*pData++) = hi2s->Instance->DR; - hi2s->RxXferCount--; } - - hi2s->State = HAL_I2S_STATE_READY; - + + hi2s->State = HAL_I2S_STATE_READY; + /* Process Unlocked */ __HAL_UNLOCK(hi2s); - + return HAL_OK; } else { + /* Process Unlocked */ + __HAL_UNLOCK(hi2s); return HAL_BUSY; } } @@ -676,47 +660,45 @@ HAL_StatusTypeDef HAL_I2S_Receive(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint * @param pData: a 16-bit pointer to data buffer. * @param Size: number of data sample to be sent: * @note When a 16-bit data frame or a 16-bit data frame extended is selected during the I2S - * configuration phase, the Size parameter means the number of 16-bit data length - * in the transaction and when a 24-bit data frame or a 32-bit data frame is selected - * the Size parameter means the number of 16-bit data length. - * @note The I2S is kept enabled at the end of transaction to avoid the clock de-synchronization + * configuration phase, the Size parameter means the number of 16-bit data length + * in the transaction and when a 24-bit data frame or a 32-bit data frame is selected + * the Size parameter means the number of 16-bit data length. + * @note The I2S is kept enabled at the end of transaction to avoid the clock de-synchronization * between Master and Slave(example: audio streaming). * @retval HAL status */ HAL_StatusTypeDef HAL_I2S_Transmit_IT(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size) { - uint32_t tmp1 = 0U; - + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hi2s); + if(hi2s->State == HAL_I2S_STATE_READY) { - if((pData == NULL) || (Size == 0U)) - { - return HAL_ERROR; - } - hi2s->pTxBuffPtr = pData; - tmp1 = hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN); - if((tmp1 == I2S_DATAFORMAT_24B) || (tmp1 == I2S_DATAFORMAT_32B)) + hi2s->State = HAL_I2S_STATE_BUSY_TX; + hi2s->ErrorCode = HAL_I2S_ERROR_NONE; + + if(((hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN)) == I2S_DATAFORMAT_24B)||\ + ((hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN)) == I2S_DATAFORMAT_32B)) { - hi2s->TxXferSize = (Size << 1U); - hi2s->TxXferCount = (Size << 1U); + hi2s->TxXferSize = (Size << 1); + hi2s->TxXferCount = (Size << 1); } else { - hi2s->TxXferSize = Size; + hi2s->TxXferSize = Size; hi2s->TxXferCount = Size; } - /* Process Locked */ - __HAL_LOCK(hi2s); - - hi2s->State = HAL_I2S_STATE_BUSY_TX; - hi2s->ErrorCode = HAL_I2S_ERROR_NONE; - /* Enable TXE and ERR interrupt */ __HAL_I2S_ENABLE_IT(hi2s, (I2S_IT_TXE | I2S_IT_ERR)); - /* Check if the I2S is already enabled */ + /* Check if the I2S is already enabled */ if((hi2s->Instance->I2SCFGR &SPI_I2SCFGR_I2SE) != SPI_I2SCFGR_I2SE) { /* Enable I2S peripheral */ @@ -725,11 +707,13 @@ HAL_StatusTypeDef HAL_I2S_Transmit_IT(I2S_HandleTypeDef *hi2s, uint16_t *pData, /* Process Unlocked */ __HAL_UNLOCK(hi2s); - + return HAL_OK; } else { + /* Process Unlocked */ + __HAL_UNLOCK(hi2s); return HAL_BUSY; } } @@ -741,48 +725,47 @@ HAL_StatusTypeDef HAL_I2S_Transmit_IT(I2S_HandleTypeDef *hi2s, uint16_t *pData, * @param pData: a 16-bit pointer to the Receive data buffer. * @param Size: number of data sample to be sent: * @note When a 16-bit data frame or a 16-bit data frame extended is selected during the I2S - * configuration phase, the Size parameter means the number of 16-bit data length - * in the transaction and when a 24-bit data frame or a 32-bit data frame is selected - * the Size parameter means the number of 16-bit data length. - * @note The I2S is kept enabled at the end of transaction to avoid the clock de-synchronization + * configuration phase, the Size parameter means the number of 16-bit data length + * in the transaction and when a 24-bit data frame or a 32-bit data frame is selected + * the Size parameter means the number of 16-bit data length. + * @note The I2S is kept enabled at the end of transaction to avoid the clock de-synchronization * between Master and Slave(example: audio streaming). - * @note It is recommended to use DMA for the I2S receiver to avoid de-synchronisation - * between Master and Slave otherwise the I2S interrupt should be optimized. + * @note It is recommended to use DMA for the I2S receiver to avoid de-synchronisation + * between Master and Slave otherwise the I2S interrupt should be optimized. * @retval HAL status */ HAL_StatusTypeDef HAL_I2S_Receive_IT(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size) { - uint32_t tmp1 = 0U; - - if(hi2s->State == HAL_I2S_STATE_READY) - { - if((pData == NULL) || (Size == 0U)) + if((pData == NULL) || (Size == 0)) { return HAL_ERROR; } + /* Process Locked */ + __HAL_LOCK(hi2s); + + if(hi2s->State == HAL_I2S_STATE_READY) + { hi2s->pRxBuffPtr = pData; - tmp1 = hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN); - if((tmp1 == I2S_DATAFORMAT_24B) || (tmp1 == I2S_DATAFORMAT_32B)) + hi2s->State = HAL_I2S_STATE_BUSY_RX; + hi2s->ErrorCode = HAL_I2S_ERROR_NONE; + + if(((hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN)) == I2S_DATAFORMAT_24B)||\ + ((hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN)) == I2S_DATAFORMAT_32B)) { - hi2s->RxXferSize = (Size << 1U); - hi2s->RxXferCount = (Size << 1U); - } + hi2s->RxXferSize = (Size << 1); + hi2s->RxXferCount = (Size << 1); + } else { - hi2s->RxXferSize = Size; + hi2s->RxXferSize = Size; hi2s->RxXferCount = Size; } - /* Process Locked */ - __HAL_LOCK(hi2s); - - hi2s->State = HAL_I2S_STATE_BUSY_RX; - hi2s->ErrorCode = HAL_I2S_ERROR_NONE; - - /* Enable TXE and ERR interrupt */ + + /* Enable RXNE and ERR interrupt */ __HAL_I2S_ENABLE_IT(hi2s, (I2S_IT_RXNE | I2S_IT_ERR)); - - /* Check if the I2S is already enabled */ + + /* Check if the I2S is already enabled */ if((hi2s->Instance->I2SCFGR &SPI_I2SCFGR_I2SE) != SPI_I2SCFGR_I2SE) { /* Enable I2S peripheral */ @@ -794,11 +777,12 @@ HAL_StatusTypeDef HAL_I2S_Receive_IT(I2S_HandleTypeDef *hi2s, uint16_t *pData, u return HAL_OK; } - else { - return HAL_BUSY; - } + /* Process Unlocked */ + __HAL_UNLOCK(hi2s); + return HAL_BUSY; + } } /** @@ -808,159 +792,155 @@ HAL_StatusTypeDef HAL_I2S_Receive_IT(I2S_HandleTypeDef *hi2s, uint16_t *pData, u * @param pData: a 16-bit pointer to the Transmit data buffer. * @param Size: number of data sample to be sent: * @note When a 16-bit data frame or a 16-bit data frame extended is selected during the I2S - * configuration phase, the Size parameter means the number of 16-bit data length - * in the transaction and when a 24-bit data frame or a 32-bit data frame is selected - * the Size parameter means the number of 16-bit data length. - * @note The I2S is kept enabled at the end of transaction to avoid the clock de-synchronization + * configuration phase, the Size parameter means the number of 16-bit data length + * in the transaction and when a 24-bit data frame or a 32-bit data frame is selected + * the Size parameter means the number of 16-bit data length. + * @note The I2S is kept enabled at the end of transaction to avoid the clock de-synchronization * between Master and Slave(example: audio streaming). * @retval HAL status */ HAL_StatusTypeDef HAL_I2S_Transmit_DMA(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size) { - uint32_t *tmp = NULL; - uint32_t tmp1 = 0U; - - if((pData == NULL) || (Size == 0U)) + if((pData == NULL) || (Size == 0)) { return HAL_ERROR; } + /* Process Locked */ + __HAL_LOCK(hi2s); + if(hi2s->State == HAL_I2S_STATE_READY) - { + { hi2s->pTxBuffPtr = pData; - tmp1 = hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN); - if((tmp1 == I2S_DATAFORMAT_24B) || (tmp1 == I2S_DATAFORMAT_32B)) + hi2s->State = HAL_I2S_STATE_BUSY_TX; + hi2s->ErrorCode = HAL_I2S_ERROR_NONE; + + if(((hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN)) == I2S_DATAFORMAT_24B)||\ + ((hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN)) == I2S_DATAFORMAT_32B)) { - hi2s->TxXferSize = (Size << 1U); - hi2s->TxXferCount = (Size << 1U); + hi2s->TxXferSize = (Size << 1); + hi2s->TxXferCount = (Size << 1); } else { - hi2s->TxXferSize = Size; + hi2s->TxXferSize = Size; hi2s->TxXferCount = Size; } - /* Process Locked */ - __HAL_LOCK(hi2s); - - hi2s->ErrorCode = HAL_I2S_ERROR_NONE; - hi2s->State = HAL_I2S_STATE_BUSY_TX; - - /* Set the I2S Tx DMA Half transfer complete callback */ + /* Set the I2S Tx DMA Half transfert complete callback */ hi2s->hdmatx->XferHalfCpltCallback = I2S_DMATxHalfCplt; - /* Set the I2S Tx DMA transfer complete callback */ + /* Set the I2S Tx DMA transfert complete callback */ hi2s->hdmatx->XferCpltCallback = I2S_DMATxCplt; /* Set the DMA error callback */ hi2s->hdmatx->XferErrorCallback = I2S_DMAError; - /* Enable the Tx DMA Stream */ - tmp = (uint32_t*)&pData; - HAL_DMA_Start_IT(hi2s->hdmatx, *(uint32_t*)tmp, (uint32_t)&hi2s->Instance->DR, hi2s->TxXferSize); + /* Enable the Tx DMA Channel */ + HAL_DMA_Start_IT(hi2s->hdmatx, (uint32_t)hi2s->pTxBuffPtr, (uint32_t)&hi2s->Instance->DR, hi2s->TxXferSize); - /* Check if the I2S is already enabled */ - if((hi2s->Instance->I2SCFGR &SPI_I2SCFGR_I2SE) != SPI_I2SCFGR_I2SE) + /* Check if the I2S is already enabled */ + if(HAL_IS_BIT_CLR(hi2s->Instance->I2SCFGR, SPI_I2SCFGR_I2SE)) { /* Enable I2S peripheral */ __HAL_I2S_ENABLE(hi2s); } - /* Check if the I2S Tx request is already enabled */ - if((hi2s->Instance->CR2 & SPI_CR2_TXDMAEN) != SPI_CR2_TXDMAEN) + /* Check if the I2S Tx request is already enabled */ + if(HAL_IS_BIT_CLR(hi2s->Instance->CR2, SPI_CR2_TXDMAEN)) { - /* Enable Tx DMA Request */ + /* Enable Tx DMA Request */ SET_BIT(hi2s->Instance->CR2, SPI_CR2_TXDMAEN); } /* Process Unlocked */ __HAL_UNLOCK(hi2s); - + return HAL_OK; } else { + /* Process Unlocked */ + __HAL_UNLOCK(hi2s); return HAL_BUSY; } } /** - * @brief Receive an amount of data in non-blocking mode with DMA + * @brief Receive an amount of data in non-blocking mode with DMA * @param hi2s: pointer to a I2S_HandleTypeDef structure that contains * the configuration information for I2S module * @param pData: a 16-bit pointer to the Receive data buffer. * @param Size: number of data sample to be sent: * @note When a 16-bit data frame or a 16-bit data frame extended is selected during the I2S - * configuration phase, the Size parameter means the number of 16-bit data length - * in the transaction and when a 24-bit data frame or a 32-bit data frame is selected - * the Size parameter means the number of 16-bit data length. - * @note The I2S is kept enabled at the end of transaction to avoid the clock de-synchronization + * configuration phase, the Size parameter means the number of 16-bit data length + * in the transaction and when a 24-bit data frame or a 32-bit data frame is selected + * the Size parameter means the number of 16-bit data length. + * @note The I2S is kept enabled at the end of transaction to avoid the clock de-synchronization * between Master and Slave(example: audio streaming). * @retval HAL status */ HAL_StatusTypeDef HAL_I2S_Receive_DMA(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size) { - uint32_t *tmp = NULL; - uint32_t tmp1 = 0U; - - if((pData == NULL) || (Size == 0U)) + if((pData == NULL) || (Size == 0)) { return HAL_ERROR; } + /* Process Locked */ + __HAL_LOCK(hi2s); + if(hi2s->State == HAL_I2S_STATE_READY) { hi2s->pRxBuffPtr = pData; - tmp1 = hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN); - if((tmp1 == I2S_DATAFORMAT_24B) || (tmp1 == I2S_DATAFORMAT_32B)) + hi2s->State = HAL_I2S_STATE_BUSY_RX; + hi2s->ErrorCode = HAL_I2S_ERROR_NONE; + + if(((hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN)) == I2S_DATAFORMAT_24B)||\ + ((hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN)) == I2S_DATAFORMAT_32B)) { - hi2s->RxXferSize = (Size << 1U); - hi2s->RxXferCount = (Size << 1U); + hi2s->RxXferSize = (Size << 1); + hi2s->RxXferCount = (Size << 1); } else { - hi2s->RxXferSize = Size; + hi2s->RxXferSize = Size; hi2s->RxXferCount = Size; } - /* Process Locked */ - __HAL_LOCK(hi2s); - - hi2s->State = HAL_I2S_STATE_BUSY_RX; - hi2s->ErrorCode = HAL_I2S_ERROR_NONE; - - /* Set the I2S Rx DMA Half transfer complete callback */ + + + /* Set the I2S Rx DMA Half transfert complete callback */ hi2s->hdmarx->XferHalfCpltCallback = I2S_DMARxHalfCplt; - - /* Set the I2S Rx DMA transfer complete callback */ + + /* Set the I2S Rx DMA transfert complete callback */ hi2s->hdmarx->XferCpltCallback = I2S_DMARxCplt; - + /* Set the DMA error callback */ hi2s->hdmarx->XferErrorCallback = I2S_DMAError; - + /* Check if Master Receiver mode is selected */ if((hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SCFG) == I2S_MODE_MASTER_RX) { /* Clear the Overrun Flag by a read operation to the SPI_DR register followed by a read - access to the SPI_SR register. */ + access to the SPI_SR register. */ __HAL_I2S_CLEAR_OVRFLAG(hi2s); } - - /* Enable the Rx DMA Stream */ - tmp = (uint32_t*)&pData; - HAL_DMA_Start_IT(hi2s->hdmarx, (uint32_t)&hi2s->Instance->DR, *(uint32_t*)tmp, hi2s->RxXferSize); - - /* Check if the I2S is already enabled */ - if((hi2s->Instance->I2SCFGR &SPI_I2SCFGR_I2SE) != SPI_I2SCFGR_I2SE) + + /* Enable the Rx DMA Channel */ + HAL_DMA_Start_IT(hi2s->hdmarx, (uint32_t)&hi2s->Instance->DR, (uint32_t)hi2s->pRxBuffPtr, hi2s->RxXferSize); + + /* Check if the I2S is already enabled */ + if(HAL_IS_BIT_CLR(hi2s->Instance->I2SCFGR, SPI_I2SCFGR_I2SE)) { /* Enable I2S peripheral */ __HAL_I2S_ENABLE(hi2s); } - /* Check if the I2S Rx request is already enabled */ - if((hi2s->Instance->CR2 &SPI_CR2_RXDMAEN) != SPI_CR2_RXDMAEN) + /* Check if the I2S Rx request is already enabled */ + if(HAL_IS_BIT_CLR(hi2s->Instance->CR2, SPI_CR2_RXDMAEN)) { - /* Enable Rx DMA Request */ - SET_BIT(hi2s->Instance->CR2,SPI_CR2_RXDMAEN); + /* Enable Rx DMA Request */ + SET_BIT(hi2s->Instance->CR2, SPI_CR2_RXDMAEN); } /* Process Unlocked */ @@ -970,12 +950,14 @@ HAL_StatusTypeDef HAL_I2S_Receive_DMA(I2S_HandleTypeDef *hi2s, uint16_t *pData, } else { + /* Process Unlocked */ + __HAL_UNLOCK(hi2s); return HAL_BUSY; } } /** - * @brief Pauses the audio channel playing from the Media. + * @brief Pauses the audio stream playing from the Media. * @param hi2s: pointer to a I2S_HandleTypeDef structure that contains * the configuration information for I2S module * @retval HAL status @@ -984,26 +966,26 @@ HAL_StatusTypeDef HAL_I2S_DMAPause(I2S_HandleTypeDef *hi2s) { /* Process Locked */ __HAL_LOCK(hi2s); - + if(hi2s->State == HAL_I2S_STATE_BUSY_TX) { /* Disable the I2S DMA Tx request */ - CLEAR_BIT(hi2s->Instance->CR2,SPI_CR2_TXDMAEN); + CLEAR_BIT(hi2s->Instance->CR2, SPI_CR2_TXDMAEN); } else if(hi2s->State == HAL_I2S_STATE_BUSY_RX) { /* Disable the I2S DMA Rx request */ - CLEAR_BIT(hi2s->Instance->CR2,SPI_CR2_RXDMAEN); + CLEAR_BIT(hi2s->Instance->CR2, SPI_CR2_RXDMAEN); } - + /* Process Unlocked */ __HAL_UNLOCK(hi2s); - - return HAL_OK; + + return HAL_OK; } /** - * @brief Resumes the audio channel playing from the Media. + * @brief Resumes the audio stream playing from the Media. * @param hi2s: pointer to a I2S_HandleTypeDef structure that contains * the configuration information for I2S module * @retval HAL status @@ -1012,33 +994,33 @@ HAL_StatusTypeDef HAL_I2S_DMAResume(I2S_HandleTypeDef *hi2s) { /* Process Locked */ __HAL_LOCK(hi2s); - + if(hi2s->State == HAL_I2S_STATE_BUSY_TX) { /* Enable the I2S DMA Tx request */ - SET_BIT(hi2s->Instance->CR2,SPI_CR2_TXDMAEN); + SET_BIT(hi2s->Instance->CR2, SPI_CR2_TXDMAEN); } else if(hi2s->State == HAL_I2S_STATE_BUSY_RX) { /* Enable the I2S DMA Rx request */ - SET_BIT(hi2s->Instance->CR2,SPI_CR2_RXDMAEN); + SET_BIT(hi2s->Instance->CR2, SPI_CR2_RXDMAEN); } /* If the I2S peripheral is still not enabled, enable it */ - if ((hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SE) == 0U) + if(HAL_IS_BIT_CLR(hi2s->Instance->I2SCFGR, SPI_I2SCFGR_I2SE)) { - /* Enable I2S peripheral */ + /* Enable I2S peripheral */ __HAL_I2S_ENABLE(hi2s); } - + /* Process Unlocked */ __HAL_UNLOCK(hi2s); - + return HAL_OK; } /** - * @brief Resumes the audio channel playing from the Media. + * @brief Resumes the audio stream playing from the Media. * @param hi2s: pointer to a I2S_HandleTypeDef structure that contains * the configuration information for I2S module * @retval HAL status @@ -1047,31 +1029,34 @@ HAL_StatusTypeDef HAL_I2S_DMAStop(I2S_HandleTypeDef *hi2s) { /* Process Locked */ __HAL_LOCK(hi2s); - - if(hi2s->State == HAL_I2S_STATE_BUSY_TX) + + /* Disable the I2S Tx/Rx DMA requests */ + CLEAR_BIT(hi2s->Instance->CR2, SPI_CR2_TXDMAEN); + CLEAR_BIT(hi2s->Instance->CR2, SPI_CR2_RXDMAEN); + + /* Abort the I2S DMA Channel tx */ + if(hi2s->hdmatx != NULL) { - /* Disable the I2S DMA requests */ - CLEAR_BIT(hi2s->Instance->CR2,SPI_CR2_TXDMAEN); - - /* Disable the I2S DMA Channel */ + /* Disable the I2S DMA channel */ + __HAL_DMA_DISABLE(hi2s->hdmatx); HAL_DMA_Abort(hi2s->hdmatx); } - else if(hi2s->State == HAL_I2S_STATE_BUSY_RX) + /* Abort the I2S DMA Channel rx */ + if(hi2s->hdmarx != NULL) { - /* Disable the I2S DMA requests */ - CLEAR_BIT(hi2s->Instance->CR2,SPI_CR2_RXDMAEN); - - /* Disable the I2S DMA Channel */ + /* Disable the I2S DMA channel */ + __HAL_DMA_DISABLE(hi2s->hdmarx); HAL_DMA_Abort(hi2s->hdmarx); } + /* Disable I2S peripheral */ __HAL_I2S_DISABLE(hi2s); - + hi2s->State = HAL_I2S_STATE_READY; - + /* Process Unlocked */ __HAL_UNLOCK(hi2s); - + return HAL_OK; } @@ -1082,9 +1067,52 @@ HAL_StatusTypeDef HAL_I2S_DMAStop(I2S_HandleTypeDef *hi2s) * @retval None */ void HAL_I2S_IRQHandler(I2S_HandleTypeDef *hi2s) -{ - /* Call the IrqHandler ISR set during HAL_I2S_INIT */ - hi2s->IrqHandlerISR(hi2s); +{ + uint32_t i2ssr = hi2s->Instance->SR; + + /* I2S in mode Receiver ------------------------------------------------*/ + if(((i2ssr & I2S_FLAG_OVR) != I2S_FLAG_OVR) && + ((i2ssr & I2S_FLAG_RXNE) == I2S_FLAG_RXNE) && (__HAL_I2S_GET_IT_SOURCE(hi2s, I2S_IT_RXNE) != RESET)) + { + I2S_Receive_IT(hi2s); + return; + } + + /* I2S in mode Tramitter -----------------------------------------------*/ + if(((i2ssr & I2S_FLAG_TXE) == I2S_FLAG_TXE) && (__HAL_I2S_GET_IT_SOURCE(hi2s, I2S_IT_TXE) != RESET)) + { + I2S_Transmit_IT(hi2s); + return; + } + + /* I2S interrupt error -------------------------------------------------*/ + if(__HAL_I2S_GET_IT_SOURCE(hi2s, I2S_IT_ERR) != RESET) + { + /* I2S Overrun error interrupt occured ---------------------------------*/ + if((i2ssr & I2S_FLAG_OVR) == I2S_FLAG_OVR) + { + /* Disable RXNE and ERR interrupt */ + __HAL_I2S_DISABLE_IT(hi2s, (I2S_IT_RXNE | I2S_IT_ERR)); + + /* Set the error code and execute error callback*/ + SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_OVR); + } + + /* I2S Underrun error interrupt occured --------------------------------*/ + if((i2ssr & I2S_FLAG_UDR) == I2S_FLAG_UDR) + { + /* Disable TXE and ERR interrupt */ + __HAL_I2S_DISABLE_IT(hi2s, (I2S_IT_TXE | I2S_IT_ERR)); + + /* Set the error code and execute error callback*/ + SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_UDR); + } + + /* Set the I2S State ready */ + hi2s->State = HAL_I2S_STATE_READY; + /* Call the Error Callback */ + HAL_I2S_ErrorCallback(hi2s); + } } /** @@ -1099,7 +1127,7 @@ void HAL_I2S_IRQHandler(I2S_HandleTypeDef *hi2s) UNUSED(hi2s); /* NOTE : This function Should not be modified, when the callback is needed, the HAL_I2S_TxHalfCpltCallback could be implemented in the user file - */ + */ } /** @@ -1114,7 +1142,7 @@ void HAL_I2S_IRQHandler(I2S_HandleTypeDef *hi2s) UNUSED(hi2s); /* NOTE : This function Should not be modified, when the callback is needed, the HAL_I2S_TxCpltCallback could be implemented in the user file - */ + */ } /** @@ -1159,7 +1187,7 @@ __weak void HAL_I2S_RxCpltCallback(I2S_HandleTypeDef *hi2s) UNUSED(hi2s); /* NOTE : This function Should not be modified, when the callback is needed, the HAL_I2S_ErrorCallback could be implemented in the user file - */ + */ } /** @@ -1169,12 +1197,12 @@ __weak void HAL_I2S_RxCpltCallback(I2S_HandleTypeDef *hi2s) /** @defgroup I2S_Exported_Functions_Group3 Peripheral State and Errors functions * @brief Peripheral State functions * -@verbatim +@verbatim =============================================================================== ##### Peripheral State and Errors functions ##### - =============================================================================== + =============================================================================== [..] - This subsection permits to get in run-time the status of the peripheral + This subsection permits to get in run-time the status of the peripheral and the data flow. @endverbatim @@ -1215,27 +1243,28 @@ uint32_t HAL_I2S_GetError(I2S_HandleTypeDef *hi2s) * @{ */ /** - * @brief DMA I2S transmit process complete callback + * @brief DMA I2S transmit process complete callback * @param hdma: pointer to a DMA_HandleTypeDef structure that contains * the configuration information for the specified DMA module. * @retval None */ static void I2S_DMATxCplt(DMA_HandleTypeDef *hdma) { - I2S_HandleTypeDef* hi2s = ( I2S_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; - + I2S_HandleTypeDef* hi2s = (I2S_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent; + if(HAL_IS_BIT_CLR(hdma->Instance->CCR, DMA_CCR_CIRC)) { /* Disable Tx DMA Request */ - CLEAR_BIT(hi2s->Instance->CR2,SPI_CR2_TXDMAEN); + CLEAR_BIT(hi2s->Instance->CR2, SPI_CR2_TXDMAEN); - hi2s->TxXferCount = 0U; - hi2s->State = HAL_I2S_STATE_READY; + hi2s->TxXferCount = 0; + hi2s->State = HAL_I2S_STATE_READY; } HAL_I2S_TxCpltCallback(hi2s); } + /** - * @brief DMA I2S transmit process half complete callback + * @brief DMA I2S transmit process half complete callback * @param hdma: pointer to a DMA_HandleTypeDef structure that contains * the configuration information for the specified DMA module. * @retval None @@ -1248,27 +1277,27 @@ static void I2S_DMATxHalfCplt(DMA_HandleTypeDef *hdma) } /** - * @brief DMA I2S receive process complete callback + * @brief DMA I2S receive process complete callback * @param hdma: pointer to a DMA_HandleTypeDef structure that contains * the configuration information for the specified DMA module. * @retval None */ static void I2S_DMARxCplt(DMA_HandleTypeDef *hdma) { - I2S_HandleTypeDef* hi2s = ( I2S_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + I2S_HandleTypeDef* hi2s = (I2S_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent; if(HAL_IS_BIT_CLR(hdma->Instance->CCR, DMA_CCR_CIRC)) { /* Disable Rx DMA Request */ - CLEAR_BIT(hi2s->Instance->CR2,SPI_CR2_RXDMAEN); - hi2s->RxXferCount = 0U; - hi2s->State = HAL_I2S_STATE_READY; + CLEAR_BIT(hi2s->Instance->CR2, SPI_CR2_RXDMAEN); + hi2s->RxXferCount = 0; + hi2s->State = HAL_I2S_STATE_READY; } - HAL_I2S_RxCpltCallback(hi2s); + HAL_I2S_RxCpltCallback(hi2s); } /** - * @brief DMA I2S receive process half complete callback + * @brief DMA I2S receive process half complete callback * @param hdma: pointer to a DMA_HandleTypeDef structure that contains * the configuration information for the specified DMA module. * @retval None @@ -1277,11 +1306,11 @@ static void I2S_DMARxHalfCplt(DMA_HandleTypeDef *hdma) { I2S_HandleTypeDef* hi2s = (I2S_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent; - HAL_I2S_RxHalfCpltCallback(hi2s); + HAL_I2S_RxHalfCpltCallback(hi2s); } /** - * @brief DMA I2S communication error callback + * @brief DMA I2S communication error callback * @param hdma: pointer to a DMA_HandleTypeDef structure that contains * the configuration information for the specified DMA module. * @retval None @@ -1291,13 +1320,14 @@ static void I2S_DMAError(DMA_HandleTypeDef *hdma) I2S_HandleTypeDef* hi2s = (I2S_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent; /* Disable Rx and Tx DMA Request */ - CLEAR_BIT(hi2s->Instance->CR2,(SPI_CR2_RXDMAEN | SPI_CR2_TXDMAEN)); - hi2s->TxXferCount = 0U; - hi2s->RxXferCount = 0U; + CLEAR_BIT(hi2s->Instance->CR2, (SPI_CR2_RXDMAEN | SPI_CR2_TXDMAEN)); + hi2s->TxXferCount = 0; + hi2s->RxXferCount = 0; hi2s->State= HAL_I2S_STATE_READY; - SET_BIT(hi2s->ErrorCode,HAL_I2S_ERROR_DMA); + /* Set the error code and execute error callback*/ + SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_DMA); HAL_I2S_ErrorCallback(hi2s); } @@ -1305,15 +1335,15 @@ static void I2S_DMAError(DMA_HandleTypeDef *hdma) * @brief Transmit an amount of data in non-blocking mode with Interrupt * @param hi2s: pointer to a I2S_HandleTypeDef structure that contains * the configuration information for I2S module - * @retval HAL status + * @retval None */ static void I2S_Transmit_IT(I2S_HandleTypeDef *hi2s) { /* Transmit data */ hi2s->Instance->DR = (*hi2s->pTxBuffPtr++); hi2s->TxXferCount--; - - if(hi2s->TxXferCount == 0U) + + if(hi2s->TxXferCount == 0) { /* Disable TXE and ERR interrupt */ __HAL_I2S_DISABLE_IT(hi2s, (I2S_IT_TXE | I2S_IT_ERR)); @@ -1325,118 +1355,78 @@ static void I2S_Transmit_IT(I2S_HandleTypeDef *hi2s) /** * @brief Receive an amount of data in non-blocking mode with Interrupt - * @param hi2s: pointer to a I2S_HandleTypeDef structure that contains - * the configuration information for I2S module - * @retval HAL status + * @param hi2s: I2S handle + * @retval None */ static void I2S_Receive_IT(I2S_HandleTypeDef *hi2s) { - /* Receive data */ + /* Receive data */ (*hi2s->pRxBuffPtr++) = hi2s->Instance->DR; hi2s->RxXferCount--; - - if(hi2s->RxXferCount == 0U) + + if(hi2s->RxXferCount == 0) { /* Disable RXNE and ERR interrupt */ __HAL_I2S_DISABLE_IT(hi2s, (I2S_IT_RXNE | I2S_IT_ERR)); - hi2s->State = HAL_I2S_STATE_READY; - HAL_I2S_RxCpltCallback(hi2s); + hi2s->State = HAL_I2S_STATE_READY; + HAL_I2S_RxCpltCallback(hi2s); } } + /** - * @brief This function handles I2S interrupt request. + * @brief This function handles I2S Communication Timeout. * @param hi2s: pointer to a I2S_HandleTypeDef structure that contains * the configuration information for I2S module - * @retval None + * @param Flag: Flag checked + * @param Status: Value of the flag expected + * @param Timeout: Duration of the timeout + * @retval HAL status */ -static void I2S_IRQHandler(I2S_HandleTypeDef *hi2s) +static HAL_StatusTypeDef I2S_WaitFlagStateUntilTimeout(I2S_HandleTypeDef *hi2s, uint32_t Flag, uint32_t Status, uint32_t Timeout) { - __IO uint32_t i2ssr = hi2s->Instance->SR; - - if(hi2s->State == HAL_I2S_STATE_BUSY_RX) + uint32_t tickstart = 0; + + /* Get tick */ + tickstart = HAL_GetTick(); + + /* Wait until flag is set */ + if(Status == RESET) { - /* I2S in mode Receiver ------------------------------------------------*/ - if(((i2ssr & I2S_FLAG_RXNE) == I2S_FLAG_RXNE) && (__HAL_I2S_GET_IT_SOURCE(hi2s, I2S_IT_RXNE) != RESET)) + while(__HAL_I2S_GET_FLAG(hi2s, Flag) == RESET) { - I2S_Receive_IT(hi2s); - } - - /* I2S Overrun error interrupt occured -------------------------------------*/ - if(((i2ssr & I2S_FLAG_OVR) == I2S_FLAG_OVR) && (__HAL_I2S_GET_IT_SOURCE(hi2s, I2S_IT_ERR) != RESET)) - { - /* Disable RXNE and ERR interrupt */ - __HAL_I2S_DISABLE_IT(hi2s, (I2S_IT_RXNE | I2S_IT_ERR)); - - /* Clear Overrun flag */ - __HAL_I2S_CLEAR_OVRFLAG(hi2s); - - /* Set the I2S State ready */ - hi2s->State = HAL_I2S_STATE_READY; - - - /* Set the error code and execute error callback*/ - SET_BIT(hi2s->ErrorCode,HAL_I2S_ERROR_OVR); - HAL_I2S_ErrorCallback(hi2s); - } - } - - if(hi2s->State == HAL_I2S_STATE_BUSY_TX) - { - /* I2S in mode Transmitter -----------------------------------------------*/ - if(((i2ssr & I2S_FLAG_TXE) == I2S_FLAG_TXE) && (__HAL_I2S_GET_IT_SOURCE(hi2s, I2S_IT_TXE) != RESET)) + if(Timeout != HAL_MAX_DELAY) { - I2S_Transmit_IT(hi2s); - } - - /* I2S Underrun error interrupt occurred --------------------------------*/ - if(((i2ssr & I2S_FLAG_UDR) == I2S_FLAG_UDR) && (__HAL_I2S_GET_IT_SOURCE(hi2s, I2S_IT_ERR) != RESET)) - { - /* Disable TXE and ERR interrupt */ - __HAL_I2S_DISABLE_IT(hi2s, (I2S_IT_TXE | I2S_IT_ERR)); + if((Timeout == 0)||((HAL_GetTick() - tickstart ) > Timeout)) + { + /* Set the I2S State ready */ + hi2s->State= HAL_I2S_STATE_READY; - /* Clear Underrun flag */ - __HAL_I2S_CLEAR_UDRFLAG(hi2s); + /* Process Unlocked */ + __HAL_UNLOCK(hi2s); - /* Set the I2S State ready */ - hi2s->State = HAL_I2S_STATE_READY; - - /* Set the error code and execute error callback*/ - SET_BIT(hi2s->ErrorCode, HAL_I2S_ERROR_UDR); - HAL_I2S_ErrorCallback(hi2s); + return HAL_TIMEOUT; + } + } } } -} - -/** - * @brief This function handles I2S Communication Timeout. - * @param hi2s: pointer to a I2S_HandleTypeDef structure that contains - * the configuration information for I2S module - * @param Flag: Flag checked - * @param State: Value of the flag expected - * @param Timeout: Duration of the timeout - * @retval HAL status - */ -static HAL_StatusTypeDef I2S_WaitFlagStateUntilTimeout(I2S_HandleTypeDef *hi2s, uint32_t Flag, uint32_t State, - uint32_t Timeout) -{ - uint32_t tickstart = HAL_GetTick(); - - /* Wait until flag is set to status*/ - while(((__HAL_I2S_GET_FLAG(hi2s, Flag)) ? SET : RESET) != State) + else { - if(Timeout != HAL_MAX_DELAY) + while(__HAL_I2S_GET_FLAG(hi2s, Flag) != RESET) { - if((Timeout == 0U)||((HAL_GetTick() - tickstart ) > Timeout)) + if(Timeout != HAL_MAX_DELAY) { - /* Set the I2S State ready */ - hi2s->State = HAL_I2S_STATE_READY; + if((Timeout == 0)||((HAL_GetTick() - tickstart ) > Timeout)) + { + /* Set the I2S State ready */ + hi2s->State= HAL_I2S_STATE_READY; - /* Process Unlocked */ - __HAL_UNLOCK(hi2s); + /* Process Unlocked */ + __HAL_UNLOCK(hi2s); - return HAL_TIMEOUT; + return HAL_TIMEOUT; + } } } } @@ -1453,6 +1443,8 @@ static HAL_StatusTypeDef I2S_WaitFlagStateUntilTimeout(I2S_HandleTypeDef *hi2s, #endif /* STM32F103xE || STM32F103xG || STM32F105xC || STM32F107xC */ #endif /* HAL_I2S_MODULE_ENABLED */ + + /** * @} */ diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_i2s.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_i2s.h index 2bf8d58b50c..8b65569c1b5 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_i2s.h +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_i2s.h @@ -2,13 +2,13 @@ ****************************************************************************** * @file stm32f1xx_hal_i2s.h * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief Header file of I2S HAL module. ****************************************************************************** * @attention * - *

© COPYRIGHT(c) 2017 STMicroelectronics

+ *

© COPYRIGHT(c) 2016 STMicroelectronics

* * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: @@ -33,7 +33,7 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** - */ + */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F1xx_HAL_I2S_H @@ -54,91 +54,87 @@ /** @addtogroup I2S * @{ - */ + */ /* Exported types ------------------------------------------------------------*/ /** @defgroup I2S_Exported_Types I2S Exported Types * @{ */ -/** - * @brief I2S Init structure definition +/** + * @brief I2S Init structure definition */ typedef struct { - uint32_t Mode; /*!< Specifies the I2S operating mode. - This parameter can be a value of @ref I2S_Mode */ + uint32_t Mode; /*!< Specifies the I2S operating mode. + This parameter can be a value of @ref I2S_Mode */ + + uint32_t Standard; /*!< Specifies the standard used for the I2S communication. + This parameter can be a value of @ref I2S_Standard */ - uint32_t Standard; /*!< Specifies the standard used for the I2S communication. - This parameter can be a value of @ref I2S_Standard */ + uint32_t DataFormat; /*!< Specifies the data format for the I2S communication. + This parameter can be a value of @ref I2S_Data_Format */ - uint32_t DataFormat; /*!< Specifies the data format for the I2S communication. - This parameter can be a value of @ref I2S_Data_Format */ + uint32_t MCLKOutput; /*!< Specifies whether the I2S MCLK output is enabled or not. + This parameter can be a value of @ref I2S_MCLK_Output */ - uint32_t MCLKOutput; /*!< Specifies whether the I2S MCLK output is enabled or not. - This parameter can be a value of @ref I2S_MCLK_Output */ + uint32_t AudioFreq; /*!< Specifies the frequency selected for the I2S communication. + This parameter can be a value of @ref I2S_Audio_Frequency */ - uint32_t AudioFreq; /*!< Specifies the frequency selected for the I2S communication. - This parameter can be a value of @ref I2S_Audio_Frequency */ + uint32_t CPOL; /*!< Specifies the idle state of the I2S clock. + This parameter can be a value of @ref I2S_Clock_Polarity */ - uint32_t CPOL; /*!< Specifies the idle state of the I2S clock. - This parameter can be a value of @ref I2S_Clock_Polarity */ }I2S_InitTypeDef; -/** +/** * @brief HAL State structures definition - */ + */ typedef enum { - HAL_I2S_STATE_RESET = 0x00U, /*!< I2S not yet initialized or disabled */ - HAL_I2S_STATE_READY = 0x01U, /*!< I2S initialized and ready for use */ - HAL_I2S_STATE_BUSY = 0x02U, /*!< I2S internal process is ongoing */ - HAL_I2S_STATE_BUSY_TX = 0x03U, /*!< Data Transmission process is ongoing */ - HAL_I2S_STATE_BUSY_RX = 0x04U, /*!< Data Reception process is ongoing */ - HAL_I2S_STATE_BUSY_TX_RX = 0x05U, /*!< Data Transmission and Reception process is ongoing */ - HAL_I2S_STATE_TIMEOUT = 0x06U, /*!< I2S timeout state */ - HAL_I2S_STATE_ERROR = 0x07U /*!< I2S error state */ - + HAL_I2S_STATE_RESET = 0x00, /*!< I2S not yet initialized or disabled */ + HAL_I2S_STATE_READY = 0x01, /*!< I2S initialized and ready for use */ + HAL_I2S_STATE_BUSY = 0x02, /*!< I2S internal process is ongoing */ + HAL_I2S_STATE_BUSY_TX = 0x12, /*!< Data Transmission process is ongoing */ + HAL_I2S_STATE_BUSY_RX = 0x22, /*!< Data Reception process is ongoing */ + HAL_I2S_STATE_TIMEOUT = 0x03, /*!< I2S timeout state */ + HAL_I2S_STATE_ERROR = 0x04 /*!< I2S error state */ }HAL_I2S_StateTypeDef; -/** - * @brief I2S handle Structure definition +/** + * @brief I2S handle Structure definition */ -typedef struct __I2S_HandleTypeDef +typedef struct { - SPI_TypeDef *Instance; /*!< I2S registers base address */ - - I2S_InitTypeDef Init; /*!< I2S communication parameters */ - - uint16_t *pTxBuffPtr; /*!< Pointer to I2S Tx transfer buffer */ - - __IO uint16_t TxXferSize; /*!< I2S Tx transfer size */ - - __IO uint16_t TxXferCount; /*!< I2S Tx transfer Counter */ - - uint16_t *pRxBuffPtr; /*!< Pointer to I2S Rx transfer buffer */ - - __IO uint16_t RxXferSize; /*!< I2S Rx transfer size */ - - __IO uint16_t RxXferCount; /*!< I2S Rx transfer counter - (This field is initialized at the - same value as transfer size at the - beginning of the transfer and - decremented when a sample is received + SPI_TypeDef *Instance; /* I2S registers base address */ + + I2S_InitTypeDef Init; /* I2S communication parameters */ + + uint16_t *pTxBuffPtr; /* Pointer to I2S Tx transfer buffer */ + + __IO uint16_t TxXferSize; /* I2S Tx transfer size */ + + __IO uint16_t TxXferCount; /* I2S Tx transfer Counter */ + + uint16_t *pRxBuffPtr; /* Pointer to I2S Rx transfer buffer */ + + __IO uint16_t RxXferSize; /* I2S Rx transfer size */ + + __IO uint16_t RxXferCount; /* I2S Rx transfer counter + (This field is initialized at the + same value as transfer size at the + beginning of the transfer and + decremented when a sample is received. NbSamplesReceived = RxBufferSize-RxBufferCount) */ - void (*IrqHandlerISR) (struct __I2S_HandleTypeDef *hi2s); /*!< I2S function pointer on IrqHandler */ + DMA_HandleTypeDef *hdmatx; /* I2S Tx DMA handle parameters */ - DMA_HandleTypeDef *hdmatx; /*!< I2S Tx DMA handle parameters */ + DMA_HandleTypeDef *hdmarx; /* I2S Rx DMA handle parameters */ + + __IO HAL_LockTypeDef Lock; /* I2S locking object */ + + __IO HAL_I2S_StateTypeDef State; /* I2S communication state */ - DMA_HandleTypeDef *hdmarx; /*!< I2S Rx DMA handle parameters */ - - __IO HAL_LockTypeDef Lock; /*!< I2S locking object */ - - __IO HAL_I2S_StateTypeDef State; /*!< I2S communication state */ - - __IO uint32_t ErrorCode; /*!< I2S Error code - This parameter can be a value of @ref I2S_ErrorCode */ + __IO uint32_t ErrorCode; /* I2S Error code */ }I2S_HandleTypeDef; /** @@ -149,59 +145,66 @@ typedef struct __I2S_HandleTypeDef /** @defgroup I2S_Exported_Constants I2S Exported Constants * @{ */ -/** - * @defgroup I2S_ErrorCode I2S Error Code + +/** @defgroup I2S_Error_Codes I2S Error Codes * @{ */ -#define HAL_I2S_ERROR_NONE 0x00000000U /*!< No error */ -#define HAL_I2S_ERROR_TIMEOUT 0x00000001U /*!< Timeout error */ -#define HAL_I2S_ERROR_OVR 0x00000002U /*!< OVR error */ -#define HAL_I2S_ERROR_UDR 0x00000004U /*!< UDR error */ -#define HAL_I2S_ERROR_DMA 0x00000008U /*!< DMA transfer error */ -#define HAL_I2S_ERROR_PRESCALER 0x00000010U /*!< Prescaler Calculation error */ +#define HAL_I2S_ERROR_NONE ((uint32_t)0x00) /*!< No error */ +#define HAL_I2S_ERROR_UDR ((uint32_t)0x01) /*!< I2S Underrun error */ +#define HAL_I2S_ERROR_OVR ((uint32_t)0x02) /*!< I2S Overrun error */ +#define HAL_I2S_ERROR_FRE ((uint32_t)0x04) /*!< I2S Frame format error */ +#define HAL_I2S_ERROR_DMA ((uint32_t)0x08) /*!< DMA transfer error */ + /** * @} */ + /** @defgroup I2S_Mode I2S Mode * @{ */ -#define I2S_MODE_SLAVE_TX 0x00000000U -#define I2S_MODE_SLAVE_RX ((uint32_t)SPI_I2SCFGR_I2SCFG_0) -#define I2S_MODE_MASTER_TX ((uint32_t)SPI_I2SCFGR_I2SCFG_1) -#define I2S_MODE_MASTER_RX ((uint32_t)(SPI_I2SCFGR_I2SCFG_0 | SPI_I2SCFGR_I2SCFG_1)) +#define I2S_MODE_SLAVE_TX ((uint32_t) 0x00000000) +#define I2S_MODE_SLAVE_RX ((uint32_t) SPI_I2SCFGR_I2SCFG_0) +#define I2S_MODE_MASTER_TX ((uint32_t) SPI_I2SCFGR_I2SCFG_1) +#define I2S_MODE_MASTER_RX ((uint32_t)(SPI_I2SCFGR_I2SCFG_0 |\ + SPI_I2SCFGR_I2SCFG_1)) + /** * @} */ - + /** @defgroup I2S_Standard I2S Standard * @{ */ -#define I2S_STANDARD_PHILIPS 0x00000000U -#define I2S_STANDARD_MSB ((uint32_t)SPI_I2SCFGR_I2SSTD_0) -#define I2S_STANDARD_LSB ((uint32_t)SPI_I2SCFGR_I2SSTD_1) -#define I2S_STANDARD_PCM_SHORT ((uint32_t)(SPI_I2SCFGR_I2SSTD_0 | SPI_I2SCFGR_I2SSTD_1)) -#define I2S_STANDARD_PCM_LONG ((uint32_t)(SPI_I2SCFGR_I2SSTD_0 | SPI_I2SCFGR_I2SSTD_1 | SPI_I2SCFGR_PCMSYNC)) +#define I2S_STANDARD_PHILIPS ((uint32_t) 0x00000000) +#define I2S_STANDARD_MSB ((uint32_t) SPI_I2SCFGR_I2SSTD_0) +#define I2S_STANDARD_LSB ((uint32_t) SPI_I2SCFGR_I2SSTD_1) +#define I2S_STANDARD_PCM_SHORT ((uint32_t)(SPI_I2SCFGR_I2SSTD_0 |\ + SPI_I2SCFGR_I2SSTD_1)) +#define I2S_STANDARD_PCM_LONG ((uint32_t)(SPI_I2SCFGR_I2SSTD_0 |\ + SPI_I2SCFGR_I2SSTD_1 |\ + SPI_I2SCFGR_PCMSYNC)) + /** * @} */ - + /** @defgroup I2S_Data_Format I2S Data Format * @{ */ -#define I2S_DATAFORMAT_16B 0x00000000U -#define I2S_DATAFORMAT_16B_EXTENDED ((uint32_t)SPI_I2SCFGR_CHLEN) +#define I2S_DATAFORMAT_16B ((uint32_t) 0x00000000) +#define I2S_DATAFORMAT_16B_EXTENDED ((uint32_t) SPI_I2SCFGR_CHLEN) #define I2S_DATAFORMAT_24B ((uint32_t)(SPI_I2SCFGR_CHLEN | SPI_I2SCFGR_DATLEN_0)) #define I2S_DATAFORMAT_32B ((uint32_t)(SPI_I2SCFGR_CHLEN | SPI_I2SCFGR_DATLEN_1)) /** * @} */ -/** @defgroup I2S_MCLK_Output I2S Mclk Output +/** @defgroup I2S_MCLK_Output I2S MCLK Output * @{ */ #define I2S_MCLKOUTPUT_ENABLE ((uint32_t)SPI_I2SPR_MCKOE) -#define I2S_MCLKOUTPUT_DISABLE 0x00000000U +#define I2S_MCLKOUTPUT_DISABLE ((uint32_t)0x00000000) /** * @} */ @@ -209,30 +212,30 @@ typedef struct __I2S_HandleTypeDef /** @defgroup I2S_Audio_Frequency I2S Audio Frequency * @{ */ -#define I2S_AUDIOFREQ_192K 192000U -#define I2S_AUDIOFREQ_96K 96000U -#define I2S_AUDIOFREQ_48K 48000U -#define I2S_AUDIOFREQ_44K 44100U -#define I2S_AUDIOFREQ_32K 32000U -#define I2S_AUDIOFREQ_22K 22050U -#define I2S_AUDIOFREQ_16K 16000U -#define I2S_AUDIOFREQ_11K 11025U -#define I2S_AUDIOFREQ_8K 8000U -#define I2S_AUDIOFREQ_DEFAULT 2U +#define I2S_AUDIOFREQ_192K ((uint32_t)192000) +#define I2S_AUDIOFREQ_96K ((uint32_t)96000) +#define I2S_AUDIOFREQ_48K ((uint32_t)48000) +#define I2S_AUDIOFREQ_44K ((uint32_t)44100) +#define I2S_AUDIOFREQ_32K ((uint32_t)32000) +#define I2S_AUDIOFREQ_22K ((uint32_t)22050) +#define I2S_AUDIOFREQ_16K ((uint32_t)16000) +#define I2S_AUDIOFREQ_11K ((uint32_t)11025) +#define I2S_AUDIOFREQ_8K ((uint32_t)8000) +#define I2S_AUDIOFREQ_DEFAULT ((uint32_t)2) /** * @} */ -/** @defgroup I2S_Clock_Polarity I2S Clock Polarity +/** @defgroup I2S_Clock_Polarity I2S Clock Polarity * @{ */ -#define I2S_CPOL_LOW 0x00000000U +#define I2S_CPOL_LOW ((uint32_t)0x00000000) #define I2S_CPOL_HIGH ((uint32_t)SPI_I2SCFGR_CKPOL) /** * @} */ -/** @defgroup I2S_Interrupts_Definition I2S Interrupts Definition +/** @defgroup I2S_Interrupt_configuration_definition I2S Interrupt configuration definition * @{ */ #define I2S_IT_TXE SPI_CR2_TXEIE @@ -242,7 +245,7 @@ typedef struct __I2S_HandleTypeDef * @} */ -/** @defgroup I2S_Flags_Definition I2S Flags Definition +/** @defgroup I2S_Flag_definition I2S Flag definition * @{ */ #define I2S_FLAG_TXE SPI_SR_TXE @@ -260,21 +263,21 @@ typedef struct __I2S_HandleTypeDef /** * @} - */ - + */ + /* Exported macro ------------------------------------------------------------*/ -/** @defgroup I2S_Exported_Macros I2S Exported Macros +/** @defgroup I2S_Exported_macros I2S Exported Macros * @{ */ -/** @brief Reset I2S handle state +/** @brief Reset I2S handle state * @param __HANDLE__: specifies the I2S Handle. * @retval None */ #define __HAL_I2S_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_I2S_STATE_RESET) /** @brief Enable the specified SPI peripheral (in I2S mode). - * @param __HANDLE__: specifies the I2S Handle. + * @param __HANDLE__: specifies the I2S Handle. * @retval None */ #define __HAL_I2S_ENABLE(__HANDLE__) (SET_BIT((__HANDLE__)->Instance->I2SCFGR, SPI_I2SCFGR_I2SE)) @@ -293,7 +296,7 @@ typedef struct __I2S_HandleTypeDef * @arg I2S_IT_RXNE: RX buffer not empty interrupt enable * @arg I2S_IT_ERR: Error interrupt enable * @retval None - */ + */ #define __HAL_I2S_ENABLE_IT(__HANDLE__, __INTERRUPT__) (SET_BIT((__HANDLE__)->Instance->CR2,(__INTERRUPT__))) /** @brief Disable the specified I2S interrupts. @@ -327,7 +330,6 @@ typedef struct __I2S_HandleTypeDef * @arg I2S_FLAG_TXE: Transmit buffer empty flag * @arg I2S_FLAG_UDR: Underrun flag * @arg I2S_FLAG_OVR: Overrun flag - * @arg I2S_FLAG_FRE: Frame error flag * @arg I2S_FLAG_CHSIDE: Channel Side flag * @arg I2S_FLAG_BSY: Busy flag * @retval The new state of __FLAG__ (TRUE or FALSE). @@ -337,34 +339,25 @@ typedef struct __I2S_HandleTypeDef /** @brief Clears the I2S OVR pending flag. * @param __HANDLE__: specifies the I2S Handle. * @retval None - */ -#define __HAL_I2S_CLEAR_OVRFLAG(__HANDLE__) \ - do{ \ - __IO uint32_t tmpreg = 0x00U; \ - tmpreg = (__HANDLE__)->Instance->DR; \ - tmpreg = (__HANDLE__)->Instance->SR; \ - UNUSED(tmpreg); \ - } while(0U) - + */ +#define __HAL_I2S_CLEAR_OVRFLAG(__HANDLE__) do{__IO uint32_t tmpreg = (__HANDLE__)->Instance->DR;\ + tmpreg = (__HANDLE__)->Instance->SR;\ + UNUSED(tmpreg); \ + }while(0) /** @brief Clears the I2S UDR pending flag. * @param __HANDLE__: specifies the I2S Handle. * @retval None */ -#define __HAL_I2S_CLEAR_UDRFLAG(__HANDLE__) \ - do{ \ - __IO uint32_t tmpreg = 0x00U; \ - tmpreg = (__HANDLE__)->Instance->SR; \ - UNUSED(tmpreg); \ - } while(0U) +#define __HAL_I2S_CLEAR_UDRFLAG(__HANDLE__)((__HANDLE__)->Instance->SR) /** * @} - */ - + */ + /* Exported functions --------------------------------------------------------*/ /** @addtogroup I2S_Exported_Functions * @{ */ - + /** @addtogroup I2S_Exported_Functions_Group1 * @{ */ @@ -381,7 +374,7 @@ void HAL_I2S_MspDeInit(I2S_HandleTypeDef *hi2s); * @{ */ /* I/O operation functions ***************************************************/ -/* Blocking mode: Polling */ + /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_I2S_Transmit(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_I2S_Receive(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size, uint32_t Timeout); @@ -422,17 +415,6 @@ uint32_t HAL_I2S_GetError(I2S_HandleTypeDef *hi2s); * @} */ -/* Private types -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private constants ---------------------------------------------------------*/ -/** @defgroup I2S_Private_Constants I2S Private Constants - * @{ - */ - -/** - * @} - */ - /* Private macros ------------------------------------------------------------*/ /** @defgroup I2S_Private_Macros I2S Private Macros * @{ diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_irda.c b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_irda.c index 14511eb4a24..4773f0d51cd 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_irda.c +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_irda.c @@ -2,15 +2,16 @@ ****************************************************************************** * @file stm32f1xx_hal_irda.c * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief IRDA HAL module driver. * This file provides firmware functions to manage the following * functionalities of the IrDA SIR ENDEC block (IrDA): * + Initialization and de-initialization functions * + IO operation functions - * + Peripheral Control functions - * + Peripheral State and Errors functions + * + Peripheral State and Errors functions + * + Peripheral Control functions + * @verbatim ============================================================================== ##### How to use this driver ##### @@ -23,7 +24,7 @@ (##) Enable the USARTx interface clock. (##) IRDA pins configuration: (+++) Enable the clock for the IRDA GPIOs. - (+++) Configure the IRDA pins as alternate function pull-up. + (+++) Configure the USART pins (TX as alternate function pull-up, RX as alternate function Input). (##) NVIC configuration if you need to use interrupt process (HAL_IRDA_Transmit_IT() and HAL_IRDA_Receive_IT() APIs): (+++) Configure the USARTx interrupt priority. @@ -34,23 +35,23 @@ (+++) Enable the DMAx interface clock. (+++) Configure the declared DMA handle structure with the required Tx/Rx parameters. (+++) Configure the DMA Tx/Rx channel. - (+++) Associate the initialized DMA handle to the IRDA DMA Tx/Rx handle. + (+++) Associate the initilalized DMA handle to the IRDA DMA Tx/Rx handle. (+++) Configure the priority and enable the NVIC for the transfer complete interrupt on the DMA Tx/Rx channel. - (+++) Configure the IRDAx interrupt priority and enable the NVIC USART IRQ handle - (used for last byte sending completion detection in DMA non circular mode) + (+++) Configure the USARTx interrupt priority and enable the NVIC USART IRQ handle + (used for last byte sending completion detection in DMA non circular mode) (#) Program the Baud Rate, Word Length, Parity, IrDA Mode, Prescaler and Mode(Receiver/Transmitter) in the hirda Init structure. (#) Initialize the IRDA registers by calling the HAL_IRDA_Init() API: (++) This API configures also the low level Hardware GPIO, CLOCK, CORTEX...etc) - by calling the customized HAL_IRDA_MspInit() API. - [..] - (@) The specific IRDA interrupts (Transmission complete interrupt, + by calling the customed HAL_IRDA_MspInit() API. + + -@@- The specific IRDA interrupts (Transmission complete interrupt, RXNE interrupt and Error Interrupts) will be managed using the macros __HAL_IRDA_ENABLE_IT() and __HAL_IRDA_DISABLE_IT() inside the transmit and receive process. - [..] - Three operation modes are available within this driver : + + (#) Three operation modes are available within this driver : *** Polling mode IO operation *** ================================= @@ -58,7 +59,7 @@ (+) Send an amount of data in blocking mode using HAL_IRDA_Transmit() (+) Receive an amount of data in blocking mode using HAL_IRDA_Receive() - *** Interrupt mode IO operation *** + *** Interrupt mode IO operation *** =================================== [..] (+) Send an amount of data in non blocking mode using HAL_IRDA_Transmit_IT() @@ -70,61 +71,39 @@ (+) In case of transfer Error, HAL_IRDA_ErrorCallback() function is executed and user can add his own code by customization of function pointer HAL_IRDA_ErrorCallback - *** DMA mode IO operation *** + *** DMA mode IO operation *** ============================== [..] (+) Send an amount of data in non blocking mode (DMA) using HAL_IRDA_Transmit_DMA() - (+) At transmission end of half transfer HAL_IRDA_TxHalfCpltCallback is executed and user can - add his own code by customization of function pointer HAL_IRDA_TxHalfCpltCallback (+) At transmission end of transfer HAL_IRDA_TxCpltCallback is executed and user can add his own code by customization of function pointer HAL_IRDA_TxCpltCallback (+) Receive an amount of data in non blocking mode (DMA) using HAL_IRDA_Receive_DMA() - (+) At reception end of half transfer HAL_IRDA_RxHalfCpltCallback is executed and user can - add his own code by customization of function pointer HAL_IRDA_RxHalfCpltCallback (+) At reception end of transfer HAL_IRDA_RxCpltCallback is executed and user can - add his own code by customization of function pointer HAL_IRDA_RxCpltCallback + add his own code by customization of function pointer HAL_IRDA_RxCpltCallback (+) In case of transfer Error, HAL_IRDA_ErrorCallback() function is executed and user can add his own code by customization of function pointer HAL_IRDA_ErrorCallback - (+) Pause the DMA Transfer using HAL_IRDA_DMAPause() - (+) Resume the DMA Transfer using HAL_IRDA_DMAResume() - (+) Stop the DMA Transfer using HAL_IRDA_DMAStop() *** IRDA HAL driver macros list *** ==================================== [..] Below the list of most used macros in IRDA HAL driver. - + (+) __HAL_IRDA_ENABLE: Enable the IRDA peripheral - (+) __HAL_IRDA_DISABLE: Disable the IRDA peripheral + (+) __HAL_IRDA_DISABLE: Disable the IRDA peripheral (+) __HAL_IRDA_GET_FLAG : Check whether the specified IRDA flag is set or not (+) __HAL_IRDA_CLEAR_FLAG : Clear the specified IRDA pending flag (+) __HAL_IRDA_ENABLE_IT: Enable the specified IRDA interrupt (+) __HAL_IRDA_DISABLE_IT: Disable the specified IRDA interrupt (+) __HAL_IRDA_GET_IT_SOURCE: Check whether the specified IRDA interrupt has occurred or not - - [..] + + [..] (@) You can refer to the IRDA HAL driver header file for more useful macros + @endverbatim - [..] - (@) Additionnal remark: If the parity is enabled, then the MSB bit of the data written - in the data register is transmitted but is changed by the parity bit. - Depending on the frame length defined by the M bit (8-bits or 9-bits), - the possible IRDA frame formats are as listed in the following table: - +-------------------------------------------------------------+ - | M bit | PCE bit | IRDA frame | - |---------------------|---------------------------------------| - | 0 | 0 | | SB | 8 bit data | 1 STB | | - |---------|-----------|---------------------------------------| - | 0 | 1 | | SB | 7 bit data | PB | 1 STB | | - |---------|-----------|---------------------------------------| - | 1 | 0 | | SB | 9 bit data | 1 STB | | - |---------|-----------|---------------------------------------| - | 1 | 1 | | SB | 8 bit data | PB | 1 STB | | - +-------------------------------------------------------------+ ****************************************************************************** * @attention * - *

© COPYRIGHT(c) 2017 STMicroelectronics

+ *

© COPYRIGHT(c) 2016 STMicroelectronics

* * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: @@ -162,78 +141,99 @@ * @brief HAL IRDA module driver * @{ */ + #ifdef HAL_IRDA_MODULE_ENABLED /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ -/** @addtogroup IRDA_Private_Constants +/** @defgroup IRDA_Private_Constants IRDA Private Constants * @{ */ +#define IRDA_DR_MASK_U16_8DATABITS (uint16_t)0x00FF +#define IRDA_DR_MASK_U16_9DATABITS (uint16_t)0x01FF + +#define IRDA_DR_MASK_U8_7DATABITS (uint8_t)0x7F +#define IRDA_DR_MASK_U8_8DATABITS (uint8_t)0xFF + + /** * @} */ -/* Private macro -------------------------------------------------------------*/ + +/* Private macros --------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ -/** @addtogroup IRDA_Private_Functions +/** @addtogroup IRDA_Private_Functions IRDA Private Functions * @{ */ -static void IRDA_SetConfig (IRDA_HandleTypeDef *hirda); static HAL_StatusTypeDef IRDA_Transmit_IT(IRDA_HandleTypeDef *hirda); static HAL_StatusTypeDef IRDA_EndTransmit_IT(IRDA_HandleTypeDef *hirda); static HAL_StatusTypeDef IRDA_Receive_IT(IRDA_HandleTypeDef *hirda); +static void IRDA_SetConfig (IRDA_HandleTypeDef *hirda); static void IRDA_DMATransmitCplt(DMA_HandleTypeDef *hdma); static void IRDA_DMATransmitHalfCplt(DMA_HandleTypeDef *hdma); static void IRDA_DMAReceiveCplt(DMA_HandleTypeDef *hdma); static void IRDA_DMAReceiveHalfCplt(DMA_HandleTypeDef *hdma); static void IRDA_DMAError(DMA_HandleTypeDef *hdma); -static void IRDA_DMAAbortOnError(DMA_HandleTypeDef *hdma); -static void IRDA_DMATxAbortCallback(DMA_HandleTypeDef *hdma); -static void IRDA_DMARxAbortCallback(DMA_HandleTypeDef *hdma); -static void IRDA_DMATxOnlyAbortCallback(DMA_HandleTypeDef *hdma); -static void IRDA_DMARxOnlyAbortCallback(DMA_HandleTypeDef *hdma); -static HAL_StatusTypeDef IRDA_WaitOnFlagUntilTimeout(IRDA_HandleTypeDef *hirda, uint32_t Flag, FlagStatus Status, uint32_t Tickstart,uint32_t Timeout); -static void IRDA_EndTxTransfer(IRDA_HandleTypeDef *hirda); -static void IRDA_EndRxTransfer(IRDA_HandleTypeDef *hirda); +static HAL_StatusTypeDef IRDA_WaitOnFlagUntilTimeout(IRDA_HandleTypeDef *hirda, uint32_t Flag, FlagStatus Status, uint32_t Timeout); /** * @} */ + /* Exported functions ---------------------------------------------------------*/ -/** @defgroup IRDA_Exported_Functions IrDA Exported Functions + +/** @defgroup IRDA_Exported_Functions IRDA Exported Functions * @{ */ -/** @defgroup IRDA_Exported_Functions_Group1 IrDA Initialization and de-initialization functions +/** @defgroup IRDA_Exported_Functions_Group1 Initialization and de-initialization functions * @brief Initialization and Configuration functions * @verbatim ============================================================================== - ##### Initialization and Configuration functions ##### + ##### Initialization and Configuration functions ##### ============================================================================== - [..] - This subsection provides a set of functions allowing to initialize the USARTx or the UARTy - in IrDA mode. - (+) For the asynchronous mode only these parameters can be configured: - (++) BaudRate - (++) WordLength - (++) Parity: If the parity is enabled, then the MSB bit of the data written - in the data register is transmitted but is changed by the parity bit. - Depending on the frame length defined by the M bit (8-bits or 9-bits), - please refer to Reference manual for possible IRDA frame formats. - (++) Prescaler: A pulse of width less than two and greater than one PSC period(s) may or may - not be rejected. The receiver set up time should be managed by software. The IrDA physical layer - specification specifies a minimum of 10 ms delay between transmission and - reception (IrDA is a half duplex protocol). - (++) Mode: Receiver/transmitter modes - (++) IrDAMode: the IrDA can operate in the Normal mode or in the Low power mode. - [..] - The HAL_IRDA_Init() API follows IRDA configuration procedures (details for the procedures - are available in reference manual). + [..] + This subsection provides a set of functions allowing to initialize the USARTx or the UARTy + in IrDA mode. + (+) For the asynchronous mode only these parameters can be configured: + (++) Baud Rate + (++) Word Length + (++) Parity + (++) Prescaler: A pulse of width less than two and greater than one PSC period(s) may or may + not be rejected. The receiver set up time should be managed by software. The IrDA physical layer + specification specifies a minimum of 10 ms delay between transmission and + reception (IrDA is a half duplex protocol). + (++) Mode: Receiver/transmitter modes + (++) IrDAMode: the IrDA can operate in the Normal mode or in the Low power mode. + + [..] + The HAL_IRDA_Init() function follows IRDA configuration procedures (details for the procedures + are available in reference manuals (RM0008 for STM32F10Xxx MCUs and RM0041 for STM32F100xx MCUs)). @endverbatim * @{ */ + +/* + Additionnal remark: If the parity is enabled, then the MSB bit of the data written + in the data register is transmitted but is changed by the parity bit. + Depending on the frame length defined by the M bit (8-bits or 9-bits), + the possible IRDA frame formats are as listed in the following table: + +-------------------------------------------------------------+ + | M bit | PCE bit | IRDA frame | + |---------------------|---------------------------------------| + | 0 | 0 | | SB | 8 bit data | STB | | + |---------|-----------|---------------------------------------| + | 0 | 1 | | SB | 7 bit data | PB | STB | | + |---------|-----------|---------------------------------------| + | 1 | 0 | | SB | 9 bit data | STB | | + |---------|-----------|---------------------------------------| + | 1 | 1 | | SB | 8 bit data | PB | STB | | + +-------------------------------------------------------------+ +*/ + /** * @brief Initializes the IRDA mode according to the specified * parameters in the IRDA_InitTypeDef and create the associated handle. @@ -248,19 +248,22 @@ HAL_StatusTypeDef HAL_IRDA_Init(IRDA_HandleTypeDef *hirda) { return HAL_ERROR; } - - /* Check the parameters */ + + /* Check the IRDA instance parameters */ assert_param(IS_IRDA_INSTANCE(hirda->Instance)); - - if(hirda->gState == HAL_IRDA_STATE_RESET) + /* Check the IRDA mode parameter in the IRDA handle */ + assert_param(IS_IRDA_POWERMODE(hirda->Init.IrDAMode)); + + if(hirda->State == HAL_IRDA_STATE_RESET) { /* Allocate lock resource and initialize it */ hirda->Lock = HAL_UNLOCKED; - /* Init the low level hardware : GPIO, CLOCK, CORTEX...etc */ + + /* Init the low level hardware */ HAL_IRDA_MspInit(hirda); } - hirda->gState = HAL_IRDA_STATE_BUSY; + hirda->State = HAL_IRDA_STATE_BUSY; /* Disable the IRDA peripheral */ __HAL_IRDA_DISABLE(hirda); @@ -269,8 +272,8 @@ HAL_StatusTypeDef HAL_IRDA_Init(IRDA_HandleTypeDef *hirda) IRDA_SetConfig(hirda); /* In IrDA mode, the following bits must be kept cleared: - - LINEN, STOP and CLKEN bits in the USART_CR2 register, - - SCEN and HDSEL bits in the USART_CR3 register.*/ + - LINEN, STOP and CLKEN bits in the USART_CR2 register, + - SCEN and HDSEL bits in the USART_CR3 register.*/ CLEAR_BIT(hirda->Instance->CR2, (USART_CR2_LINEN | USART_CR2_STOP | USART_CR2_CLKEN)); CLEAR_BIT(hirda->Instance->CR3, (USART_CR3_SCEN | USART_CR3_HDSEL)); @@ -288,8 +291,7 @@ HAL_StatusTypeDef HAL_IRDA_Init(IRDA_HandleTypeDef *hirda) /* Initialize the IRDA state*/ hirda->ErrorCode = HAL_IRDA_ERROR_NONE; - hirda->gState= HAL_IRDA_STATE_READY; - hirda->RxState= HAL_IRDA_STATE_READY; + hirda->State= HAL_IRDA_STATE_READY; return HAL_OK; } @@ -310,9 +312,9 @@ HAL_StatusTypeDef HAL_IRDA_DeInit(IRDA_HandleTypeDef *hirda) /* Check the parameters */ assert_param(IS_IRDA_INSTANCE(hirda->Instance)); - - hirda->gState = HAL_IRDA_STATE_BUSY; - + + hirda->State = HAL_IRDA_STATE_BUSY; + /* Disable the Peripheral */ __HAL_IRDA_DISABLE(hirda); @@ -320,9 +322,8 @@ HAL_StatusTypeDef HAL_IRDA_DeInit(IRDA_HandleTypeDef *hirda) HAL_IRDA_MspDeInit(hirda); hirda->ErrorCode = HAL_IRDA_ERROR_NONE; - hirda->gState = HAL_IRDA_STATE_RESET; - hirda->RxState = HAL_IRDA_STATE_RESET; - + hirda->State = HAL_IRDA_STATE_RESET; + /* Release Lock */ __HAL_UNLOCK(hirda); @@ -335,13 +336,13 @@ HAL_StatusTypeDef HAL_IRDA_DeInit(IRDA_HandleTypeDef *hirda) * the configuration information for the specified IRDA module. * @retval None */ -__weak void HAL_IRDA_MspInit(IRDA_HandleTypeDef *hirda) + __weak void HAL_IRDA_MspInit(IRDA_HandleTypeDef *hirda) { /* Prevent unused argument(s) compilation warning */ UNUSED(hirda); /* NOTE: This function should not be modified, when the callback is needed, the HAL_IRDA_MspInit can be implemented in the user file - */ + */ } /** @@ -350,13 +351,13 @@ __weak void HAL_IRDA_MspInit(IRDA_HandleTypeDef *hirda) * the configuration information for the specified IRDA module. * @retval None */ -__weak void HAL_IRDA_MspDeInit(IRDA_HandleTypeDef *hirda) + __weak void HAL_IRDA_MspDeInit(IRDA_HandleTypeDef *hirda) { /* Prevent unused argument(s) compilation warning */ UNUSED(hirda); /* NOTE: This function should not be modified, when the callback is needed, the HAL_IRDA_MspDeInit can be implemented in the user file - */ + */ } /** @@ -372,6 +373,8 @@ __weak void HAL_IRDA_MspDeInit(IRDA_HandleTypeDef *hirda) ============================================================================== [..] This subsection provides a set of functions allowing to manage the IRDA data transfers. + + [..] IrDA is a half duplex communication protocol. If the Transmitter is busy, any data on the IrDA receive line will be ignored by the IrDA decoder and if the Receiver is busy, data on the TX from the USART to IrDA will not be encoded by IrDA. @@ -383,7 +386,7 @@ __weak void HAL_IRDA_MspDeInit(IRDA_HandleTypeDef *hirda) The HAL status of all data processing is returned by the same function after finishing transfer. (++) No-Blocking mode: The communication is performed using Interrupts - or DMA, these APIs return the HAL status. + or DMA, These API's return the HAL status. The end of the data processing will be indicated through the dedicated IRDA IRQ when using Interrupt mode or the DMA IRQ when using DMA mode. @@ -392,16 +395,16 @@ __weak void HAL_IRDA_MspDeInit(IRDA_HandleTypeDef *hirda) The HAL_IRDA_ErrorCallback() user callback will be executed when a communication error is detected - (#) Blocking mode APIs are: + (#) Blocking mode APIs are : (++) HAL_IRDA_Transmit() (++) HAL_IRDA_Receive() - (#) Non Blocking mode APIs with Interrupt are: + (#) Non Blocking mode APIs with Interrupt are : (++) HAL_IRDA_Transmit_IT() (++) HAL_IRDA_Receive_IT() (++) HAL_IRDA_IRQHandler() - (#) Non Blocking mode functions with DMA are: + (#) Non Blocking mode functions with DMA are : (++) HAL_IRDA_Transmit_DMA() (++) HAL_IRDA_Receive_DMA() (++) HAL_IRDA_DMAPause() @@ -430,13 +433,13 @@ __weak void HAL_IRDA_MspDeInit(IRDA_HandleTypeDef *hirda) */ HAL_StatusTypeDef HAL_IRDA_Transmit(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size, uint32_t Timeout) { - uint16_t* tmp; - uint32_t tickstart = 0U; - - /* Check that a Tx process is not already ongoing */ - if(hirda->gState == HAL_IRDA_STATE_READY) + uint16_t* tmp = 0; + uint32_t tmp_state = 0; + + tmp_state = hirda->State; + if((tmp_state == HAL_IRDA_STATE_READY) || (tmp_state == HAL_IRDA_STATE_BUSY_RX)) { - if((pData == NULL) || (Size == 0U)) + if((pData == NULL) || (Size == 0)) { return HAL_ERROR; } @@ -445,54 +448,64 @@ HAL_StatusTypeDef HAL_IRDA_Transmit(IRDA_HandleTypeDef *hirda, uint8_t *pData, u __HAL_LOCK(hirda); hirda->ErrorCode = HAL_IRDA_ERROR_NONE; - hirda->gState = HAL_IRDA_STATE_BUSY_TX; - - /* Init tickstart for timeout managment */ - tickstart = HAL_GetTick(); + if(hirda->State == HAL_IRDA_STATE_BUSY_RX) + { + hirda->State = HAL_IRDA_STATE_BUSY_TX_RX; + } + else + { + hirda->State = HAL_IRDA_STATE_BUSY_TX; + } hirda->TxXferSize = Size; hirda->TxXferCount = Size; - while(hirda->TxXferCount > 0U) + while(hirda->TxXferCount > 0) { - hirda->TxXferCount--; if(hirda->Init.WordLength == IRDA_WORDLENGTH_9B) { - if(IRDA_WaitOnFlagUntilTimeout(hirda, IRDA_FLAG_TXE, RESET, tickstart, Timeout) != HAL_OK) + if(IRDA_WaitOnFlagUntilTimeout(hirda, IRDA_FLAG_TXE, RESET, Timeout) != HAL_OK) { return HAL_TIMEOUT; } tmp = (uint16_t*) pData; - hirda->Instance->DR = (*tmp & (uint16_t)0x01FF); + WRITE_REG(hirda->Instance->DR,(*tmp & IRDA_DR_MASK_U16_9DATABITS)); if(hirda->Init.Parity == IRDA_PARITY_NONE) { - pData +=2U; + pData +=2; } else { - pData +=1U; + pData +=1; } } else { - if(IRDA_WaitOnFlagUntilTimeout(hirda, IRDA_FLAG_TXE, RESET, tickstart, Timeout) != HAL_OK) + if(IRDA_WaitOnFlagUntilTimeout(hirda, IRDA_FLAG_TXE, RESET, Timeout) != HAL_OK) { return HAL_TIMEOUT; } - hirda->Instance->DR = (*pData++ & (uint8_t)0xFF); + WRITE_REG(hirda->Instance->DR, (*pData++ & IRDA_DR_MASK_U8_8DATABITS)); } + hirda->TxXferCount--; } - - if(IRDA_WaitOnFlagUntilTimeout(hirda, IRDA_FLAG_TC, RESET, tickstart, Timeout) != HAL_OK) - { + + if(IRDA_WaitOnFlagUntilTimeout(hirda, IRDA_FLAG_TC, RESET, Timeout) != HAL_OK) + { return HAL_TIMEOUT; } - - /* At end of Tx process, restore hirda->gState to Ready */ - hirda->gState = HAL_IRDA_STATE_READY; - + + if(hirda->State == HAL_IRDA_STATE_BUSY_TX_RX) + { + hirda->State = HAL_IRDA_STATE_BUSY_RX; + } + else + { + hirda->State = HAL_IRDA_STATE_READY; + } + /* Process Unlocked */ __HAL_UNLOCK(hirda); - + return HAL_OK; } else @@ -512,13 +525,13 @@ HAL_StatusTypeDef HAL_IRDA_Transmit(IRDA_HandleTypeDef *hirda, uint8_t *pData, u */ HAL_StatusTypeDef HAL_IRDA_Receive(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size, uint32_t Timeout) { - uint16_t* tmp; - uint32_t tickstart = 0U; + uint16_t* tmp = 0; + uint32_t tmp_state = 0; - /* Check that a Rx process is not already ongoing */ - if(hirda->RxState == HAL_IRDA_STATE_READY) + tmp_state = hirda->State; + if((tmp_state == HAL_IRDA_STATE_READY) || (tmp_state == HAL_IRDA_STATE_BUSY_TX)) { - if((pData == NULL) || (Size == 0U)) + if((pData == NULL) || (Size == 0)) { return HAL_ERROR; } @@ -527,55 +540,62 @@ HAL_StatusTypeDef HAL_IRDA_Receive(IRDA_HandleTypeDef *hirda, uint8_t *pData, ui __HAL_LOCK(hirda); hirda->ErrorCode = HAL_IRDA_ERROR_NONE; - hirda->RxState = HAL_IRDA_STATE_BUSY_RX; - - /* Init tickstart for timeout managment */ - tickstart = HAL_GetTick(); - + if(hirda->State == HAL_IRDA_STATE_BUSY_TX) + { + hirda->State = HAL_IRDA_STATE_BUSY_TX_RX; + } + else + { + hirda->State = HAL_IRDA_STATE_BUSY_RX; + } hirda->RxXferSize = Size; hirda->RxXferCount = Size; - /* Check the remain data to be received */ - while(hirda->RxXferCount > 0U) + while(hirda->RxXferCount > 0) { - hirda->RxXferCount--; if(hirda->Init.WordLength == IRDA_WORDLENGTH_9B) { - if(IRDA_WaitOnFlagUntilTimeout(hirda, IRDA_FLAG_RXNE, RESET, tickstart, Timeout) != HAL_OK) - { + if(IRDA_WaitOnFlagUntilTimeout(hirda, IRDA_FLAG_RXNE, RESET, Timeout) != HAL_OK) + { return HAL_TIMEOUT; } - tmp = (uint16_t*)pData; + tmp = (uint16_t*) pData ; if(hirda->Init.Parity == IRDA_PARITY_NONE) { - *tmp = (uint16_t)(hirda->Instance->DR & (uint16_t)0x01FF); - pData +=2U; + *tmp = (uint16_t)(hirda->Instance->DR & IRDA_DR_MASK_U16_9DATABITS); + pData +=2; } else { - *tmp = (uint16_t)(hirda->Instance->DR & (uint16_t)0x00FF); - pData +=1U; + *tmp = (uint16_t)(hirda->Instance->DR & IRDA_DR_MASK_U16_8DATABITS); + pData +=1; } } else { - if(IRDA_WaitOnFlagUntilTimeout(hirda, IRDA_FLAG_RXNE, RESET, tickstart, Timeout) != HAL_OK) - { + if(IRDA_WaitOnFlagUntilTimeout(hirda, IRDA_FLAG_RXNE, RESET, Timeout) != HAL_OK) + { return HAL_TIMEOUT; } if(hirda->Init.Parity == IRDA_PARITY_NONE) { - *pData++ = (uint8_t)(hirda->Instance->DR & (uint8_t)0x00FF); + *pData++ = (uint8_t)(hirda->Instance->DR & IRDA_DR_MASK_U8_8DATABITS); } else { - *pData++ = (uint8_t)(hirda->Instance->DR & (uint8_t)0x007F); + *pData++ = (uint8_t)(hirda->Instance->DR & IRDA_DR_MASK_U8_7DATABITS); } } + hirda->RxXferCount--; + } + if(hirda->State == HAL_IRDA_STATE_BUSY_TX_RX) + { + hirda->State = HAL_IRDA_STATE_BUSY_TX; + } + else + { + hirda->State = HAL_IRDA_STATE_READY; } - - /* At end of Rx process, restore hirda->RxState to Ready */ - hirda->RxState = HAL_IRDA_STATE_READY; /* Process Unlocked */ __HAL_UNLOCK(hirda); @@ -584,12 +604,12 @@ HAL_StatusTypeDef HAL_IRDA_Receive(IRDA_HandleTypeDef *hirda, uint8_t *pData, ui } else { - return HAL_BUSY; + return HAL_BUSY; } } /** - * @brief Sends an amount of data in non blocking mode. + * @brief Sends an amount of data in non-blocking mode. * @param hirda: Pointer to a IRDA_HandleTypeDef structure that contains * the configuration information for the specified IRDA module. * @param pData: Pointer to data buffer @@ -598,10 +618,12 @@ HAL_StatusTypeDef HAL_IRDA_Receive(IRDA_HandleTypeDef *hirda, uint8_t *pData, ui */ HAL_StatusTypeDef HAL_IRDA_Transmit_IT(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size) { - /* Check that a Tx process is not already ongoing */ - if(hirda->gState == HAL_IRDA_STATE_READY) + uint32_t tmp_state = 0; + + tmp_state = hirda->State; + if((tmp_state == HAL_IRDA_STATE_READY) || (tmp_state == HAL_IRDA_STATE_BUSY_RX)) { - if((pData == NULL) || (Size == 0U)) + if((pData == NULL) || (Size == 0)) { return HAL_ERROR; } @@ -613,12 +635,19 @@ HAL_StatusTypeDef HAL_IRDA_Transmit_IT(IRDA_HandleTypeDef *hirda, uint8_t *pData hirda->TxXferCount = Size; hirda->ErrorCode = HAL_IRDA_ERROR_NONE; - hirda->gState = HAL_IRDA_STATE_BUSY_TX; + if(hirda->State == HAL_IRDA_STATE_BUSY_RX) + { + hirda->State = HAL_IRDA_STATE_BUSY_TX_RX; + } + else + { + hirda->State = HAL_IRDA_STATE_BUSY_TX; + } /* Process Unlocked */ __HAL_UNLOCK(hirda); - /* Enable the IRDA Transmit data register empty Interrupt */ + /* Enable the IRDA Transmit Data Register Empty Interrupt */ __HAL_IRDA_ENABLE_IT(hirda, IRDA_IT_TXE); return HAL_OK; @@ -630,7 +659,7 @@ HAL_StatusTypeDef HAL_IRDA_Transmit_IT(IRDA_HandleTypeDef *hirda, uint8_t *pData } /** - * @brief Receives an amount of data in non blocking mode. + * @brief Receives an amount of data in non-blocking mode. * @param hirda: Pointer to a IRDA_HandleTypeDef structure that contains * the configuration information for the specified IRDA module. * @param pData: Pointer to data buffer @@ -639,36 +668,45 @@ HAL_StatusTypeDef HAL_IRDA_Transmit_IT(IRDA_HandleTypeDef *hirda, uint8_t *pData */ HAL_StatusTypeDef HAL_IRDA_Receive_IT(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size) { - /* Check that a Rx process is not already ongoing */ - if(hirda->RxState == HAL_IRDA_STATE_READY) + uint32_t tmp_state = 0; + + tmp_state = hirda->State; + if((tmp_state == HAL_IRDA_STATE_READY) || (tmp_state == HAL_IRDA_STATE_BUSY_TX)) { - if((pData == NULL) || (Size == 0U)) + if((pData == NULL) || (Size == 0)) { return HAL_ERROR; } - + /* Process Locked */ __HAL_LOCK(hirda); - + hirda->pRxBuffPtr = pData; hirda->RxXferSize = Size; hirda->RxXferCount = Size; hirda->ErrorCode = HAL_IRDA_ERROR_NONE; - hirda->RxState = HAL_IRDA_STATE_BUSY_RX; - + if(hirda->State == HAL_IRDA_STATE_BUSY_TX) + { + hirda->State = HAL_IRDA_STATE_BUSY_TX_RX; + } + else + { + hirda->State = HAL_IRDA_STATE_BUSY_RX; + } + /* Process Unlocked */ __HAL_UNLOCK(hirda); + /* Enable the IRDA Data Register not empty Interrupt */ + __HAL_IRDA_ENABLE_IT(hirda, IRDA_IT_RXNE); + /* Enable the IRDA Parity Error Interrupt */ __HAL_IRDA_ENABLE_IT(hirda, IRDA_IT_PE); /* Enable the IRDA Error Interrupt: (Frame error, noise error, overrun error) */ __HAL_IRDA_ENABLE_IT(hirda, IRDA_IT_ERR); - /* Enable the IRDA Data Register not empty Interrupt */ - __HAL_IRDA_ENABLE_IT(hirda, IRDA_IT_RXNE); - return HAL_OK; } else @@ -678,7 +716,7 @@ HAL_StatusTypeDef HAL_IRDA_Receive_IT(IRDA_HandleTypeDef *hirda, uint8_t *pData, } /** - * @brief Sends an amount of data in non blocking mode. + * @brief Sends an amount of data in non-blocking mode. * @param hirda: Pointer to a IRDA_HandleTypeDef structure that contains * the configuration information for the specified IRDA module. * @param pData: Pointer to data buffer @@ -687,12 +725,13 @@ HAL_StatusTypeDef HAL_IRDA_Receive_IT(IRDA_HandleTypeDef *hirda, uint8_t *pData, */ HAL_StatusTypeDef HAL_IRDA_Transmit_DMA(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size) { - uint32_t *tmp; - - /* Check that a Tx process is not already ongoing */ - if(hirda->gState == HAL_IRDA_STATE_READY) + uint32_t *tmp = 0; + uint32_t tmp_state = 0; + + tmp_state = hirda->State; + if((tmp_state == HAL_IRDA_STATE_READY) || (tmp_state == HAL_IRDA_STATE_BUSY_RX)) { - if((pData == NULL) || (Size == 0U)) + if((pData == NULL) || (Size == 0)) { return HAL_ERROR; } @@ -703,36 +742,40 @@ HAL_StatusTypeDef HAL_IRDA_Transmit_DMA(IRDA_HandleTypeDef *hirda, uint8_t *pDat hirda->pTxBuffPtr = pData; hirda->TxXferSize = Size; hirda->TxXferCount = Size; - hirda->ErrorCode = HAL_IRDA_ERROR_NONE; - hirda->gState = HAL_IRDA_STATE_BUSY_TX; + + if(hirda->State == HAL_IRDA_STATE_BUSY_RX) + { + hirda->State = HAL_IRDA_STATE_BUSY_TX_RX; + } + else + { + hirda->State = HAL_IRDA_STATE_BUSY_TX; + } /* Set the IRDA DMA transfer complete callback */ hirda->hdmatx->XferCpltCallback = IRDA_DMATransmitCplt; - /* Set the IRDA DMA half transfer complete callback */ + /* Set the IRDA DMA half transfert complete callback */ hirda->hdmatx->XferHalfCpltCallback = IRDA_DMATransmitHalfCplt; /* Set the DMA error callback */ hirda->hdmatx->XferErrorCallback = IRDA_DMAError; - /* Set the DMA abort callback */ - hirda->hdmatx->XferAbortCallback = NULL; - - /* Enable the IRDA transmit DMA Channel */ + /* Enable the IRDA transmit DMA channel */ tmp = (uint32_t*)&pData; HAL_DMA_Start_IT(hirda->hdmatx, *(uint32_t*)tmp, (uint32_t)&hirda->Instance->DR, Size); /* Clear the TC flag in the SR register by writing 0 to it */ __HAL_IRDA_CLEAR_FLAG(hirda, IRDA_FLAG_TC); - - /* Process Unlocked */ - __HAL_UNLOCK(hirda); /* Enable the DMA transfer for transmit request by setting the DMAT bit in the USART CR3 register */ SET_BIT(hirda->Instance->CR3, USART_CR3_DMAT); + /* Process Unlocked */ + __HAL_UNLOCK(hirda); + return HAL_OK; } else @@ -742,7 +785,7 @@ HAL_StatusTypeDef HAL_IRDA_Transmit_DMA(IRDA_HandleTypeDef *hirda, uint8_t *pDat } /** - * @brief Receives an amount of data in non blocking mode. + * @brief Receive an amount of data in non-blocking mode. * @param hirda: Pointer to a IRDA_HandleTypeDef structure that contains * the configuration information for the specified IRDA module. * @param pData: Pointer to data buffer @@ -752,12 +795,13 @@ HAL_StatusTypeDef HAL_IRDA_Transmit_DMA(IRDA_HandleTypeDef *hirda, uint8_t *pDat */ HAL_StatusTypeDef HAL_IRDA_Receive_DMA(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size) { - uint32_t *tmp; - - /* Check that a Rx process is not already ongoing */ - if(hirda->RxState == HAL_IRDA_STATE_READY) + uint32_t *tmp = 0; + uint32_t tmp_state = 0; + + tmp_state = hirda->State; + if((tmp_state == HAL_IRDA_STATE_READY) || (tmp_state == HAL_IRDA_STATE_BUSY_TX)) { - if((pData == NULL) || (Size == 0U)) + if((pData == NULL) || (Size == 0)) { return HAL_ERROR; } @@ -767,42 +811,36 @@ HAL_StatusTypeDef HAL_IRDA_Receive_DMA(IRDA_HandleTypeDef *hirda, uint8_t *pData hirda->pRxBuffPtr = pData; hirda->RxXferSize = Size; - - hirda->ErrorCode = HAL_IRDA_ERROR_NONE; - hirda->RxState = HAL_IRDA_STATE_BUSY_RX; + hirda->ErrorCode = HAL_IRDA_ERROR_NONE; + if(hirda->State == HAL_IRDA_STATE_BUSY_TX) + { + hirda->State = HAL_IRDA_STATE_BUSY_TX_RX; + } + else + { + hirda->State = HAL_IRDA_STATE_BUSY_RX; + } /* Set the IRDA DMA transfer complete callback */ hirda->hdmarx->XferCpltCallback = IRDA_DMAReceiveCplt; - /* Set the IRDA DMA half transfer complete callback */ + /* Set the IRDA DMA half transfert complete callback */ hirda->hdmarx->XferHalfCpltCallback = IRDA_DMAReceiveHalfCplt; /* Set the DMA error callback */ hirda->hdmarx->XferErrorCallback = IRDA_DMAError; - /* Set the DMA abort callback */ - hirda->hdmarx->XferAbortCallback = NULL; - /* Enable the DMA channel */ tmp = (uint32_t*)&pData; HAL_DMA_Start_IT(hirda->hdmarx, (uint32_t)&hirda->Instance->DR, *(uint32_t*)tmp, Size); - /* Clear the Overrun flag just before enabling the DMA Rx request: can be mandatory for the second transfer */ - __HAL_IRDA_CLEAR_OREFLAG(hirda); + /* Enable the DMA transfer for the receiver request by setting the DMAR bit + in the USART CR3 register */ + SET_BIT(hirda->Instance->CR3, USART_CR3_DMAR); /* Process Unlocked */ __HAL_UNLOCK(hirda); - /* Enable the IRDA Parity Error Interrupt */ - SET_BIT(hirda->Instance->CR1, USART_CR1_PEIE); - - /* Enable the IRDA Error Interrupt: (Frame error, noise error, overrun error) */ - SET_BIT(hirda->Instance->CR3, USART_CR3_EIE); - - /* Enable the DMA transfer for the receiver request by setting the DMAR bit - in the USART CR3 register */ - SET_BIT(hirda->Instance->CR3, USART_CR3_DMAR); - return HAL_OK; } else @@ -819,39 +857,42 @@ HAL_StatusTypeDef HAL_IRDA_Receive_DMA(IRDA_HandleTypeDef *hirda, uint8_t *pData */ HAL_StatusTypeDef HAL_IRDA_DMAPause(IRDA_HandleTypeDef *hirda) { - uint32_t dmarequest = 0x00U; - /* Process Locked */ __HAL_LOCK(hirda); - - dmarequest = HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAT); - if((hirda->gState == HAL_IRDA_STATE_BUSY_TX) && dmarequest) + + if(hirda->State == HAL_IRDA_STATE_BUSY_TX) { /* Disable the IRDA DMA Tx request */ CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAT); } - - dmarequest = HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAR); - if((hirda->RxState == HAL_IRDA_STATE_BUSY_RX) && dmarequest) + else if(hirda->State == HAL_IRDA_STATE_BUSY_RX) { - /* Disable PE and ERR (Frame error, noise error, overrun error) interrupts */ - CLEAR_BIT(hirda->Instance->CR1, USART_CR1_PEIE); - CLEAR_BIT(hirda->Instance->CR3, USART_CR3_EIE); - /* Disable the IRDA DMA Rx request */ CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAR); } + else if (hirda->State == HAL_IRDA_STATE_BUSY_TX_RX) + { + /* Disable the IRDA DMA Tx & Rx requests */ + CLEAR_BIT(hirda->Instance->CR3, (USART_CR3_DMAT | USART_CR3_DMAR)); + } + else + { + /* Process Unlocked */ + __HAL_UNLOCK(hirda); + + return HAL_ERROR; + } /* Process Unlocked */ __HAL_UNLOCK(hirda); - return HAL_OK; + return HAL_OK; } /** * @brief Resumes the DMA Transfer. * @param hirda: Pointer to a IRDA_HandleTypeDef structure that contains - * the configuration information for the specified IRDA module. + * the configuration information for the specified UART module. * @retval HAL status */ HAL_StatusTypeDef HAL_IRDA_DMAResume(IRDA_HandleTypeDef *hirda) @@ -859,25 +900,33 @@ HAL_StatusTypeDef HAL_IRDA_DMAResume(IRDA_HandleTypeDef *hirda) /* Process Locked */ __HAL_LOCK(hirda); - if(hirda->gState == HAL_IRDA_STATE_BUSY_TX) + if(hirda->State == HAL_IRDA_STATE_BUSY_TX) { /* Enable the IRDA DMA Tx request */ SET_BIT(hirda->Instance->CR3, USART_CR3_DMAT); } - - if(hirda->RxState == HAL_IRDA_STATE_BUSY_RX) + else if(hirda->State == HAL_IRDA_STATE_BUSY_RX) { - /* Clear the Overrun flag before resuming the Rx transfer */ + /* Clear the Overrun flag before resumming the Rx transfer*/ __HAL_IRDA_CLEAR_OREFLAG(hirda); - - /* Reenable PE and ERR (Frame error, noise error, overrun error) interrupts */ - SET_BIT(hirda->Instance->CR1, USART_CR1_PEIE); - SET_BIT(hirda->Instance->CR3, USART_CR3_EIE); - /* Enable the IRDA DMA Rx request */ SET_BIT(hirda->Instance->CR3, USART_CR3_DMAR); } - + else if(hirda->State == HAL_IRDA_STATE_BUSY_TX_RX) + { + /* Clear the Overrun flag before resumming the Rx transfer*/ + __HAL_IRDA_CLEAR_OREFLAG(hirda); + /* Enable the IRDA DMA Tx & Rx request */ + SET_BIT(hirda->Instance->CR3, (USART_CR3_DMAT | USART_CR3_DMAR)); + } + else + { + /* Process Unlocked */ + __HAL_UNLOCK(hirda); + + return HAL_ERROR; + } + /* Process Unlocked */ __HAL_UNLOCK(hirda); @@ -887,591 +936,132 @@ HAL_StatusTypeDef HAL_IRDA_DMAResume(IRDA_HandleTypeDef *hirda) /** * @brief Stops the DMA Transfer. * @param hirda: Pointer to a IRDA_HandleTypeDef structure that contains - * the configuration information for the specified IRDA module. + * the configuration information for the specified UART module. * @retval HAL status */ HAL_StatusTypeDef HAL_IRDA_DMAStop(IRDA_HandleTypeDef *hirda) { - uint32_t dmarequest = 0x00U; /* The Lock is not implemented on this API to allow the user application - to call the HAL IRDA API under callbacks HAL_IRDA_TxCpltCallback() / HAL_IRDA_RxCpltCallback(): - when calling HAL_DMA_Abort() API the DMA TX/RX Transfer complete interrupt is generated - and the correspond call back is executed HAL_IRDA_TxCpltCallback() / HAL_IRDA_RxCpltCallback() - */ - - /* Stop IRDA DMA Tx request if ongoing */ - dmarequest = HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAT); - if((hirda->gState == HAL_IRDA_STATE_BUSY_TX) && dmarequest) + to call the HAL IRDA API under callbacks HAL_IRDA_TxCpltCallback() / HAL_IRDA_RxCpltCallback(): + when calling HAL_DMA_Abort() API the DMA TX/RX Transfer complete interrupt is generated + and the correspond call back is executed HAL_IRDA_TxCpltCallback() / HAL_IRDA_RxCpltCallback() + */ + + /* Disable the IRDA Tx/Rx DMA requests */ + CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAT); + CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAR); + + /* Abort the IRDA DMA tx channel */ + if(hirda->hdmatx != NULL) { - CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAT); - - /* Abort the IRDA DMA Tx channel */ - if(hirda->hdmatx != NULL) - { - HAL_DMA_Abort(hirda->hdmatx); - } - IRDA_EndTxTransfer(hirda); + HAL_DMA_Abort(hirda->hdmatx); } - - /* Stop IRDA DMA Rx request if ongoing */ - dmarequest = HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAR); - if((hirda->RxState == HAL_IRDA_STATE_BUSY_RX) && dmarequest) + /* Abort the IRDA DMA rx channel */ + if(hirda->hdmarx != NULL) { - CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAR); - - /* Abort the IRDA DMA Rx channel */ - if(hirda->hdmarx != NULL) - { - HAL_DMA_Abort(hirda->hdmarx); - } - IRDA_EndRxTransfer(hirda); + HAL_DMA_Abort(hirda->hdmarx); } + + hirda->State = HAL_IRDA_STATE_READY; return HAL_OK; } /** - * @brief Abort ongoing transfers (blocking mode). - * @param hirda IRDA handle. - * @note This procedure could be used for aborting any ongoing transfer started in Interrupt or DMA mode. - * This procedure performs following operations : - * - Disable PPP Interrupts - * - Disable the DMA transfer in the peripheral register (if enabled) - * - Abort DMA transfer by calling HAL_DMA_Abort (in case of transfer in DMA mode) - * - Set handle State to READY - * @note This procedure is executed in blocking mode : when exiting function, Abort is considered as completed. - * @retval HAL status -*/ -HAL_StatusTypeDef HAL_IRDA_Abort(IRDA_HandleTypeDef *hirda) + * @brief This function handles IRDA interrupt request. + * @param hirda: Pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified IRDA module. + * @retval None + */ +void HAL_IRDA_IRQHandler(IRDA_HandleTypeDef *hirda) { - /* Disable TXEIE, TCIE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */ - CLEAR_BIT(hirda->Instance->CR1, (USART_CR1_RXNEIE | USART_CR1_PEIE | USART_CR1_TXEIE | USART_CR1_TCIE)); - CLEAR_BIT(hirda->Instance->CR3, USART_CR3_EIE); + uint32_t tmp_flag = 0, tmp_it_source = 0; - /* Disable the IRDA DMA Tx request if enabled */ - if(HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAT)) + tmp_flag = __HAL_IRDA_GET_FLAG(hirda, IRDA_FLAG_PE); + tmp_it_source = __HAL_IRDA_GET_IT_SOURCE(hirda, IRDA_IT_PE); + /* IRDA parity error interrupt occurred -----------------------------------*/ + if((tmp_flag != RESET) && (tmp_it_source != RESET)) { - CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAT); - - /* Abort the IRDA DMA Tx channel: use blocking DMA Abort API (no callback) */ - if(hirda->hdmatx != NULL) - { - /* Set the IRDA DMA Abort callback to Null. - No call back execution at end of DMA abort procedure */ - hirda->hdmatx->XferAbortCallback = NULL; - - HAL_DMA_Abort(hirda->hdmatx); - } + hirda->ErrorCode |= HAL_IRDA_ERROR_PE; } - /* Disable the IRDA DMA Rx request if enabled */ - if(HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAR)) + tmp_flag = __HAL_IRDA_GET_FLAG(hirda, IRDA_FLAG_FE); + tmp_it_source = __HAL_IRDA_GET_IT_SOURCE(hirda, IRDA_IT_ERR); + /* IRDA frame error interrupt occurred ------------------------------------*/ + if((tmp_flag != RESET) && (tmp_it_source != RESET)) { - CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAR); - - /* Abort the IRDA DMA Rx channel: use blocking DMA Abort API (no callback) */ - if(hirda->hdmarx != NULL) - { - /* Set the IRDA DMA Abort callback to Null. - No call back execution at end of DMA abort procedure */ - hirda->hdmarx->XferAbortCallback = NULL; - - HAL_DMA_Abort(hirda->hdmarx); - } + hirda->ErrorCode |= HAL_IRDA_ERROR_FE; } - /* Reset Tx and Rx transfer counters */ - hirda->TxXferCount = 0x00U; - hirda->RxXferCount = 0x00U; - - /* Reset ErrorCode */ - hirda->ErrorCode = HAL_IRDA_ERROR_NONE; - - /* Restore hirda->RxState and hirda->gState to Ready */ - hirda->RxState = HAL_IRDA_STATE_READY; - hirda->gState = HAL_IRDA_STATE_READY; - - return HAL_OK; -} - -/** - * @brief Abort ongoing Transmit transfer (blocking mode). - * @param hirda IRDA handle. - * @note This procedure could be used for aborting any ongoing transfer started in Interrupt or DMA mode. - * This procedure performs following operations : - * - Disable PPP Interrupts - * - Disable the DMA transfer in the peripheral register (if enabled) - * - Abort DMA transfer by calling HAL_DMA_Abort (in case of transfer in DMA mode) - * - Set handle State to READY - * @note This procedure is executed in blocking mode : when exiting function, Abort is considered as completed. - * @retval HAL status -*/ -HAL_StatusTypeDef HAL_IRDA_AbortTransmit(IRDA_HandleTypeDef *hirda) -{ - /* Disable TXEIE and TCIE interrupts */ - CLEAR_BIT(hirda->Instance->CR1, (USART_CR1_TXEIE | USART_CR1_TCIE)); + tmp_flag = __HAL_IRDA_GET_FLAG(hirda, IRDA_FLAG_NE); + /* IRDA noise error interrupt occurred ------------------------------------*/ + if((tmp_flag != RESET) && (tmp_it_source != RESET)) + { + hirda->ErrorCode |= HAL_IRDA_ERROR_NE; + } - /* Disable the IRDA DMA Tx request if enabled */ - if(HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAT)) + tmp_flag = __HAL_IRDA_GET_FLAG(hirda, IRDA_FLAG_ORE); + /* IRDA Over-Run interrupt occurred ---------------------------------------*/ + if((tmp_flag != RESET) && (tmp_it_source != RESET)) { - CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAT); + hirda->ErrorCode |= HAL_IRDA_ERROR_ORE; + } - /* Abort the IRDA DMA Tx channel : use blocking DMA Abort API (no callback) */ - if(hirda->hdmatx != NULL) - { - /* Set the IRDA DMA Abort callback to Null. - No call back execution at end of DMA abort procedure */ - hirda->hdmatx->XferAbortCallback = NULL; + /* Call the Error call Back in case of Errors */ + if(hirda->ErrorCode != HAL_IRDA_ERROR_NONE) + { + /* Disable PE and ERR interrupt */ + __HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_ERR); + __HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_PE); + __HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_TXE); + + /* Clear all the error flag at once */ + __HAL_IRDA_CLEAR_PEFLAG(hirda); - HAL_DMA_Abort(hirda->hdmatx); - } + /* Set the IRDA state ready to be able to start again the process */ + hirda->State = HAL_IRDA_STATE_READY; + HAL_IRDA_ErrorCallback(hirda); } - /* Reset Tx transfer counter */ - hirda->TxXferCount = 0x00U; + tmp_flag = __HAL_IRDA_GET_FLAG(hirda, IRDA_FLAG_RXNE); + tmp_it_source = __HAL_IRDA_GET_IT_SOURCE(hirda, IRDA_IT_RXNE); + /* IRDA in mode Receiver --------------------------------------------------*/ + if((tmp_flag != RESET) && (tmp_it_source != RESET)) + { + IRDA_Receive_IT(hirda); + } - /* Restore hirda->gState to Ready */ - hirda->gState = HAL_IRDA_STATE_READY; + tmp_flag = __HAL_IRDA_GET_FLAG(hirda, IRDA_FLAG_TXE); + tmp_it_source = __HAL_IRDA_GET_IT_SOURCE(hirda, IRDA_IT_TXE); + /* IRDA in mode Transmitter -----------------------------------------------*/ + if((tmp_flag != RESET) && (tmp_it_source != RESET)) + { + IRDA_Transmit_IT(hirda); + } - return HAL_OK; + tmp_flag = __HAL_IRDA_GET_FLAG(hirda, IRDA_FLAG_TC); + tmp_it_source = __HAL_IRDA_GET_IT_SOURCE(hirda, IRDA_IT_TC); + /* IRDA in mode Transmitter (transmission end) -----------------------------*/ + if((tmp_flag != RESET) && (tmp_it_source != RESET)) + { + IRDA_EndTransmit_IT(hirda); + } + } /** - * @brief Abort ongoing Receive transfer (blocking mode). - * @param hirda IRDA handle. - * @note This procedure could be used for aborting any ongoing transfer started in Interrupt or DMA mode. - * This procedure performs following operations : - * - Disable PPP Interrupts - * - Disable the DMA transfer in the peripheral register (if enabled) - * - Abort DMA transfer by calling HAL_DMA_Abort (in case of transfer in DMA mode) - * - Set handle State to READY - * @note This procedure is executed in blocking mode : when exiting function, Abort is considered as completed. - * @retval HAL status -*/ -HAL_StatusTypeDef HAL_IRDA_AbortReceive(IRDA_HandleTypeDef *hirda) -{ - /* Disable RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */ - CLEAR_BIT(hirda->Instance->CR1, (USART_CR1_RXNEIE | USART_CR1_PEIE)); - CLEAR_BIT(hirda->Instance->CR3, USART_CR3_EIE); - - /* Disable the IRDA DMA Rx request if enabled */ - if(HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAR)) - { - CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAR); - - /* Abort the IRDA DMA Rx channel : use blocking DMA Abort API (no callback) */ - if(hirda->hdmarx != NULL) - { - /* Set the IRDA DMA Abort callback to Null. - No call back execution at end of DMA abort procedure */ - hirda->hdmarx->XferAbortCallback = NULL; - - HAL_DMA_Abort(hirda->hdmarx); - } - } - - /* Reset Rx transfer counter */ - hirda->RxXferCount = 0x00U; - - /* Restore hirda->RxState to Ready */ - hirda->RxState = HAL_IRDA_STATE_READY; - - return HAL_OK; -} - -/** - * @brief Abort ongoing transfers (Interrupt mode). - * @param hirda IRDA handle. - * @note This procedure could be used for aborting any ongoing transfer started in Interrupt or DMA mode. - * This procedure performs following operations : - * - Disable PPP Interrupts - * - Disable the DMA transfer in the peripheral register (if enabled) - * - Abort DMA transfer by calling HAL_DMA_Abort_IT (in case of transfer in DMA mode) - * - Set handle State to READY - * - At abort completion, call user abort complete callback - * @note This procedure is executed in Interrupt mode, meaning that abort procedure could be - * considered as completed only when user abort complete callback is executed (not when exiting function). - * @retval HAL status -*/ -HAL_StatusTypeDef HAL_IRDA_Abort_IT(IRDA_HandleTypeDef *hirda) -{ - uint32_t AbortCplt = 0x01U; - - /* Disable TXEIE, TCIE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */ - CLEAR_BIT(hirda->Instance->CR1, (USART_CR1_RXNEIE | USART_CR1_PEIE | USART_CR1_TXEIE | USART_CR1_TCIE)); - CLEAR_BIT(hirda->Instance->CR3, USART_CR3_EIE); - - /* If DMA Tx and/or DMA Rx Handles are associated to IRDA Handle, DMA Abort complete callbacks should be initialised - before any call to DMA Abort functions */ - /* DMA Tx Handle is valid */ - if(hirda->hdmatx != NULL) - { - /* Set DMA Abort Complete callback if IRDA DMA Tx request if enabled. - Otherwise, set it to NULL */ - if(HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAT)) - { - hirda->hdmatx->XferAbortCallback = IRDA_DMATxAbortCallback; - } - else - { - hirda->hdmatx->XferAbortCallback = NULL; - } - } - /* DMA Rx Handle is valid */ - if(hirda->hdmarx != NULL) - { - /* Set DMA Abort Complete callback if IRDA DMA Rx request if enabled. - Otherwise, set it to NULL */ - if(HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAR)) - { - hirda->hdmarx->XferAbortCallback = IRDA_DMARxAbortCallback; - } - else - { - hirda->hdmarx->XferAbortCallback = NULL; - } - } - - /* Disable the IRDA DMA Tx request if enabled */ - if(HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAT)) - { - /* Disable DMA Tx at IRDA level */ - CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAT); - - /* Abort the IRDA DMA Tx channel : use non blocking DMA Abort API (callback) */ - if(hirda->hdmatx != NULL) - { - /* IRDA Tx DMA Abort callback has already been initialised : - will lead to call HAL_IRDA_AbortCpltCallback() at end of DMA abort procedure */ - - /* Abort DMA TX */ - if(HAL_DMA_Abort_IT(hirda->hdmatx) != HAL_OK) - { - hirda->hdmatx->XferAbortCallback = NULL; - } - else - { - AbortCplt = 0x00U; - } - } - } - - /* Disable the IRDA DMA Rx request if enabled */ - if(HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAR)) - { - CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAR); - - /* Abort the IRDA DMA Rx channel : use non blocking DMA Abort API (callback) */ - if(hirda->hdmarx != NULL) - { - /* IRDA Rx DMA Abort callback has already been initialised : - will lead to call HAL_IRDA_AbortCpltCallback() at end of DMA abort procedure */ - - /* Abort DMA RX */ - if(HAL_DMA_Abort_IT(hirda->hdmarx) != HAL_OK) - { - hirda->hdmarx->XferAbortCallback = NULL; - AbortCplt = 0x01U; - } - else - { - AbortCplt = 0x00U; - } - } - } - - /* if no DMA abort complete callback execution is required => call user Abort Complete callback */ - if(AbortCplt == 0x01U) - { - /* Reset Tx and Rx transfer counters */ - hirda->TxXferCount = 0x00U; - hirda->RxXferCount = 0x00U; - - /* Reset ErrorCode */ - hirda->ErrorCode = HAL_IRDA_ERROR_NONE; - - /* Restore hirda->gState and hirda->RxState to Ready */ - hirda->gState = HAL_IRDA_STATE_READY; - hirda->RxState = HAL_IRDA_STATE_READY; - - /* As no DMA to be aborted, call directly user Abort complete callback */ - HAL_IRDA_AbortCpltCallback(hirda); - } - - return HAL_OK; -} - -/** - * @brief Abort ongoing Transmit transfer (Interrupt mode). - * @param hirda IRDA handle. - * @note This procedure could be used for aborting any ongoing transfer started in Interrupt or DMA mode. - * This procedure performs following operations : - * - Disable PPP Interrupts - * - Disable the DMA transfer in the peripheral register (if enabled) - * - Abort DMA transfer by calling HAL_DMA_Abort_IT (in case of transfer in DMA mode) - * - Set handle State to READY - * - At abort completion, call user abort complete callback - * @note This procedure is executed in Interrupt mode, meaning that abort procedure could be - * considered as completed only when user abort complete callback is executed (not when exiting function). - * @retval HAL status -*/ -HAL_StatusTypeDef HAL_IRDA_AbortTransmit_IT(IRDA_HandleTypeDef *hirda) -{ - /* Disable TXEIE and TCIE interrupts */ - CLEAR_BIT(hirda->Instance->CR1, (USART_CR1_TXEIE | USART_CR1_TCIE)); - - /* Disable the IRDA DMA Tx request if enabled */ - if(HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAT)) - { - CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAT); - - /* Abort the IRDA DMA Tx channel : use blocking DMA Abort API (no callback) */ - if(hirda->hdmatx != NULL) - { - /* Set the IRDA DMA Abort callback : - will lead to call HAL_IRDA_AbortCpltCallback() at end of DMA abort procedure */ - hirda->hdmatx->XferAbortCallback = IRDA_DMATxOnlyAbortCallback; - - /* Abort DMA TX */ - if(HAL_DMA_Abort_IT(hirda->hdmatx) != HAL_OK) - { - /* Call Directly hirda->hdmatx->XferAbortCallback function in case of error */ - hirda->hdmatx->XferAbortCallback(hirda->hdmatx); - } - } - else - { - /* Reset Tx transfer counter */ - hirda->TxXferCount = 0x00U; - - /* Restore hirda->gState to Ready */ - hirda->gState = HAL_IRDA_STATE_READY; - - /* As no DMA to be aborted, call directly user Abort complete callback */ - HAL_IRDA_AbortTransmitCpltCallback(hirda); - } - } - else - { - /* Reset Tx transfer counter */ - hirda->TxXferCount = 0x00U; - - /* Restore hirda->gState to Ready */ - hirda->gState = HAL_IRDA_STATE_READY; - - /* As no DMA to be aborted, call directly user Abort complete callback */ - HAL_IRDA_AbortTransmitCpltCallback(hirda); - } - - return HAL_OK; -} - -/** - * @brief Abort ongoing Receive transfer (Interrupt mode). - * @param hirda IRDA handle. - * @note This procedure could be used for aborting any ongoing transfer started in Interrupt or DMA mode. - * This procedure performs following operations : - * - Disable PPP Interrupts - * - Disable the DMA transfer in the peripheral register (if enabled) - * - Abort DMA transfer by calling HAL_DMA_Abort_IT (in case of transfer in DMA mode) - * - Set handle State to READY - * - At abort completion, call user abort complete callback - * @note This procedure is executed in Interrupt mode, meaning that abort procedure could be - * considered as completed only when user abort complete callback is executed (not when exiting function). - * @retval HAL status -*/ -HAL_StatusTypeDef HAL_IRDA_AbortReceive_IT(IRDA_HandleTypeDef *hirda) -{ - /* Disable RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */ - CLEAR_BIT(hirda->Instance->CR1, (USART_CR1_RXNEIE | USART_CR1_PEIE)); - CLEAR_BIT(hirda->Instance->CR3, USART_CR3_EIE); - - /* Disable the IRDA DMA Rx request if enabled */ - if(HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAR)) - { - CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAR); - - /* Abort the IRDA DMA Rx channel : use blocking DMA Abort API (no callback) */ - if(hirda->hdmarx != NULL) - { - /* Set the IRDA DMA Abort callback : - will lead to call HAL_IRDA_AbortCpltCallback() at end of DMA abort procedure */ - hirda->hdmarx->XferAbortCallback = IRDA_DMARxOnlyAbortCallback; - - /* Abort DMA RX */ - if(HAL_DMA_Abort_IT(hirda->hdmarx) != HAL_OK) - { - /* Call Directly hirda->hdmarx->XferAbortCallback function in case of error */ - hirda->hdmarx->XferAbortCallback(hirda->hdmarx); - } - } - else - { - /* Reset Rx transfer counter */ - hirda->RxXferCount = 0x00U; - - /* Restore hirda->RxState to Ready */ - hirda->RxState = HAL_IRDA_STATE_READY; - - /* As no DMA to be aborted, call directly user Abort complete callback */ - HAL_IRDA_AbortReceiveCpltCallback(hirda); - } - } - else - { - /* Reset Rx transfer counter */ - hirda->RxXferCount = 0x00U; - - /* Restore hirda->RxState to Ready */ - hirda->RxState = HAL_IRDA_STATE_READY; - - /* As no DMA to be aborted, call directly user Abort complete callback */ - HAL_IRDA_AbortReceiveCpltCallback(hirda); - } - - return HAL_OK; -} - -/** - * @brief This function handles IRDA interrupt request. + * @brief Tx Transfer completed callbacks. * @param hirda: Pointer to a IRDA_HandleTypeDef structure that contains * the configuration information for the specified IRDA module. * @retval None */ -void HAL_IRDA_IRQHandler(IRDA_HandleTypeDef *hirda) -{ - uint32_t isrflags = READ_REG(hirda->Instance->SR); - uint32_t cr1its = READ_REG(hirda->Instance->CR1); - uint32_t cr3its = READ_REG(hirda->Instance->CR3); - uint32_t errorflags = 0x00U; - uint32_t dmarequest = 0x00U; - - /* If no error occurs */ - errorflags = (isrflags & (uint32_t)(USART_SR_PE | USART_SR_FE | USART_SR_ORE | USART_SR_NE)); - if(errorflags == RESET) - { - /* IRDA in mode Receiver -----------------------------------------------*/ - if(((isrflags & USART_SR_RXNE) != RESET) && ((cr1its & USART_CR1_RXNEIE) != RESET)) - { - IRDA_Receive_IT(hirda); - return; - } - } - - /* If some errors occur */ - if((errorflags != RESET) && (((cr3its & USART_CR3_EIE) != RESET) || ((cr1its & (USART_CR1_RXNEIE | USART_CR1_PEIE)) != RESET))) - { - /* IRDA parity error interrupt occurred -------------------------------*/ - if(((isrflags & USART_SR_PE) != RESET) && ((cr1its & USART_CR1_PEIE) != RESET)) - { - hirda->ErrorCode |= HAL_IRDA_ERROR_PE; - } - - /* IRDA noise error interrupt occurred --------------------------------*/ - if(((isrflags & USART_SR_NE) != RESET) && ((cr3its & USART_CR3_EIE) != RESET)) - { - hirda->ErrorCode |= HAL_IRDA_ERROR_NE; - } - - /* IRDA frame error interrupt occurred --------------------------------*/ - if(((isrflags & USART_SR_FE) != RESET) && ((cr3its & USART_CR3_EIE) != RESET)) - { - hirda->ErrorCode |= HAL_IRDA_ERROR_FE; - } - - /* IRDA Over-Run interrupt occurred -----------------------------------*/ - if(((isrflags & USART_SR_ORE) != RESET) && ((cr3its & USART_CR3_EIE) != RESET)) - { - hirda->ErrorCode |= HAL_IRDA_ERROR_ORE; - } - /* Call IRDA Error Call back function if need be -----------------------*/ - if(hirda->ErrorCode != HAL_IRDA_ERROR_NONE) - { - /* IRDA in mode Receiver ---------------------------------------------*/ - if(((isrflags & USART_SR_RXNE) != RESET) && ((cr1its & USART_CR1_RXNEIE) != RESET)) - { - IRDA_Receive_IT(hirda); - } - - /* If Overrun error occurs, or if any error occurs in DMA mode reception, - consider error as blocking */ - dmarequest = HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAR); - if(((hirda->ErrorCode & HAL_IRDA_ERROR_ORE) != RESET) || dmarequest) - { - /* Blocking error : transfer is aborted - Set the IRDA state ready to be able to start again the process, - Disable Rx Interrupts, and disable Rx DMA request, if ongoing */ - IRDA_EndRxTransfer(hirda); - - /* Disable the IRDA DMA Rx request if enabled */ - if(HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAR)) - { - CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAR); - - /* Abort the IRDA DMA Rx channel */ - if(hirda->hdmarx != NULL) - { - /* Set the IRDA DMA Abort callback : - will lead to call HAL_IRDA_ErrorCallback() at end of DMA abort procedure */ - hirda->hdmarx->XferAbortCallback = IRDA_DMAAbortOnError; - - if(HAL_DMA_Abort_IT(hirda->hdmarx) != HAL_OK) - { - /* Call Directly XferAbortCallback function in case of error */ - hirda->hdmarx->XferAbortCallback(hirda->hdmarx); - } - } - else - { - /* Call user error callback */ - HAL_IRDA_ErrorCallback(hirda); - } - } - else - { - /* Call user error callback */ - HAL_IRDA_ErrorCallback(hirda); - } - } - else - { - /* Non Blocking error : transfer could go on. - Error is notified to user through user error callback */ - HAL_IRDA_ErrorCallback(hirda); - hirda->ErrorCode = HAL_IRDA_ERROR_NONE; - } - } - return; - } /* End if some error occurs */ - - /* IRDA in mode Transmitter ------------------------------------------------*/ - if(((isrflags & USART_SR_TXE) != RESET) && ((cr1its & USART_CR1_TXEIE) != RESET)) - { - IRDA_Transmit_IT(hirda); - return; - } - - /* IRDA in mode Transmitter end --------------------------------------------*/ - if(((isrflags & USART_SR_TC) != RESET) && ((cr1its & USART_CR1_TCIE) != RESET)) - { - IRDA_EndTransmit_IT(hirda); - return; - } -} - -/** - * @brief Tx Transfer complete callbacks. - * @param hirda: pointer to a IRDA_HandleTypeDef structure that contains - * the configuration information for the specified IRDA module. - * @retval None - */ -__weak void HAL_IRDA_TxCpltCallback(IRDA_HandleTypeDef *hirda) + __weak void HAL_IRDA_TxCpltCallback(IRDA_HandleTypeDef *hirda) { /* Prevent unused argument(s) compilation warning */ UNUSED(hirda); /* NOTE: This function should not be modified, when the callback is needed, the HAL_IRDA_TxCpltCallback can be implemented in the user file - */ + */ } /** @@ -1480,17 +1070,17 @@ __weak void HAL_IRDA_TxCpltCallback(IRDA_HandleTypeDef *hirda) * the configuration information for the specified USART module. * @retval None */ -__weak void HAL_IRDA_TxHalfCpltCallback(IRDA_HandleTypeDef *hirda) + __weak void HAL_IRDA_TxHalfCpltCallback(IRDA_HandleTypeDef *hirda) { /* Prevent unused argument(s) compilation warning */ UNUSED(hirda); /* NOTE: This function should not be modified, when the callback is needed, the HAL_IRDA_TxHalfCpltCallback can be implemented in the user file - */ + */ } /** - * @brief Rx Transfer complete callbacks. + * @brief Rx Transfer completed callbacks. * @param hirda: Pointer to a IRDA_HandleTypeDef structure that contains * the configuration information for the specified IRDA module. * @retval None @@ -1501,7 +1091,7 @@ __weak void HAL_IRDA_RxCpltCallback(IRDA_HandleTypeDef *hirda) UNUSED(hirda); /* NOTE: This function should not be modified, when the callback is needed, the HAL_IRDA_RxCpltCallback can be implemented in the user file - */ + */ } /** @@ -1516,67 +1106,22 @@ __weak void HAL_IRDA_RxHalfCpltCallback(IRDA_HandleTypeDef *hirda) UNUSED(hirda); /* NOTE : This function should not be modified, when the callback is needed, the HAL_IRDA_RxHalfCpltCallback can be implemented in the user file - */ + */ } /** - * @brief IRDA error callbacks. + * @brief IRDA error callbacks. * @param hirda: Pointer to a IRDA_HandleTypeDef structure that contains * the configuration information for the specified IRDA module. * @retval None */ -__weak void HAL_IRDA_ErrorCallback(IRDA_HandleTypeDef *hirda) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hirda); - /* NOTE : This function Should not be modified, when the callback is needed, - the HAL_IRDA_ErrorCallback could be implemented in the user file - */ -} - -/** - * @brief IRDA Abort Complete callback. - * @param hirda IRDA handle. - * @retval None - */ -__weak void HAL_IRDA_AbortCpltCallback(IRDA_HandleTypeDef *hirda) + __weak void HAL_IRDA_ErrorCallback(IRDA_HandleTypeDef *hirda) { /* Prevent unused argument(s) compilation warning */ UNUSED(hirda); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_IRDA_AbortCpltCallback can be implemented in the user file. - */ -} - -/** - * @brief IRDA Abort Transmit Complete callback. - * @param hirda IRDA handle. - * @retval None - */ -__weak void HAL_IRDA_AbortTransmitCpltCallback(IRDA_HandleTypeDef *hirda) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hirda); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_IRDA_AbortTransmitCpltCallback can be implemented in the user file. - */ -} - -/** - * @brief IRDA Abort ReceiveComplete callback. - * @param hirda IRDA handle. - * @retval None - */ -__weak void HAL_IRDA_AbortReceiveCpltCallback(IRDA_HandleTypeDef *hirda) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hirda); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_IRDA_AbortReceiveCpltCallback can be implemented in the user file. - */ + /* NOTE: This function should not be modified, when the callback is needed, + the HAL_IRDA_ErrorCallback can be implemented in the user file + */ } /** @@ -1593,9 +1138,11 @@ __weak void HAL_IRDA_AbortReceiveCpltCallback(IRDA_HandleTypeDef *hirda) [..] This subsection provides a set of functions allowing to return the State of IrDA communication process and also return Peripheral Errors occurred during communication process - (+) HAL_IRDA_GetState() API can be helpful to check in run-time the state of the IrDA peripheral. - (+) HAL_IRDA_GetError() check in run-time errors that could be occurred during communication. - + (+) HAL_IRDA_GetState() API can be helpful to check in run-time the state + of the IRDA peripheral. + (+) HAL_IRDA_GetError() check in run-time errors that could be occurred during + communication. + @endverbatim * @{ */ @@ -1608,11 +1155,7 @@ __weak void HAL_IRDA_AbortReceiveCpltCallback(IRDA_HandleTypeDef *hirda) */ HAL_IRDA_StateTypeDef HAL_IRDA_GetState(IRDA_HandleTypeDef *hirda) { - uint32_t temp1 = 0x00U, temp2 = 0x00U; - temp1 = hirda->gState; - temp2 = hirda->RxState; - - return (HAL_IRDA_StateTypeDef)(temp1 | temp2); + return hirda->State; } /** @@ -1630,6 +1173,14 @@ uint32_t HAL_IRDA_GetError(IRDA_HandleTypeDef *hirda) * @} */ +/** + * @} + */ + +/** @defgroup IRDA_Private_Functions IRDA Private Functions + * @brief IRDA Private functions + * @{ + */ /** * @brief DMA IRDA transmit process complete callback. * @param hdma: Pointer to a DMA_HandleTypeDef structure that contains @@ -1640,15 +1191,15 @@ static void IRDA_DMATransmitCplt(DMA_HandleTypeDef *hdma) { IRDA_HandleTypeDef* hirda = ( IRDA_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; /* DMA Normal mode */ - if((hdma->Instance->CCR & DMA_CCR_CIRC) == 0U) + if ( HAL_IS_BIT_CLR(hdma->Instance->CCR, DMA_CCR_CIRC) ) { - hirda->TxXferCount = 0U; - + hirda->TxXferCount = 0; + /* Disable the DMA transfer for transmit request by setting the DMAT bit - in the IRDA CR3 register */ + in the IRDA CR3 register */ CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAT); - - /* Enable the IRDA Transmit Complete Interrupt */ + + /* Enable the IRDA Transmit Complete Interrupt */ __HAL_IRDA_ENABLE_IT(hirda, IRDA_IT_TC); } /* DMA Circular mode */ @@ -1661,82 +1212,74 @@ static void IRDA_DMATransmitCplt(DMA_HandleTypeDef *hdma) /** * @brief DMA IRDA receive process half complete callback * @param hdma: Pointer to a DMA_HandleTypeDef structure that contains - * the configuration information for the specified DMA module. + * the configuration information for the specified DMA module. * @retval None */ static void IRDA_DMATransmitHalfCplt(DMA_HandleTypeDef *hdma) { IRDA_HandleTypeDef* hirda = ( IRDA_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; - + HAL_IRDA_TxHalfCpltCallback(hirda); } /** * @brief DMA IRDA receive process complete callback. - * @param hdma: DMA handle + * @param hdma: Pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. * @retval None */ static void IRDA_DMAReceiveCplt(DMA_HandleTypeDef *hdma) { IRDA_HandleTypeDef* hirda = ( IRDA_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; /* DMA Normal mode */ - if((hdma->Instance->CCR & DMA_CCR_CIRC) == 0U) + if ( HAL_IS_BIT_CLR(hdma->Instance->CCR, DMA_CCR_CIRC) ) { - hirda->RxXferCount = 0U; + hirda->RxXferCount = 0; - /* Disable PE and ERR (Frame error, noise error, overrun error) interrupts */ - CLEAR_BIT(hirda->Instance->CR1, USART_CR1_PEIE); - CLEAR_BIT(hirda->Instance->CR3, USART_CR3_EIE); - /* Disable the DMA transfer for the receiver request by setting the DMAR bit - in the IRDA CR3 register */ + in the IRDA CR3 register */ CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAR); - /* At end of Rx process, restore hirda->RxState to Ready */ - hirda->RxState = HAL_IRDA_STATE_READY; + if(hirda->State == HAL_IRDA_STATE_BUSY_TX_RX) + { + hirda->State = HAL_IRDA_STATE_BUSY_TX; + } + else + { + hirda->State = HAL_IRDA_STATE_READY; + } } + HAL_IRDA_RxCpltCallback(hirda); } /** * @brief DMA IRDA receive process half complete callback * @param hdma: Pointer to a DMA_HandleTypeDef structure that contains - * the configuration information for the specified DMA module. + * the configuration information for the specified DMA module. * @retval None */ static void IRDA_DMAReceiveHalfCplt(DMA_HandleTypeDef *hdma) { IRDA_HandleTypeDef* hirda = ( IRDA_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + HAL_IRDA_RxHalfCpltCallback(hirda); } /** - * @brief DMA IRDA communication error callback. - * @param hdma: DMA handle + * @brief DMA IRDA communication error callback. + * @param hdma: Pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. * @retval None */ -static void IRDA_DMAError(DMA_HandleTypeDef *hdma) +static void IRDA_DMAError(DMA_HandleTypeDef *hdma) { - uint32_t dmarequest = 0x00U; IRDA_HandleTypeDef* hirda = ( IRDA_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; - /* Stop IRDA DMA Tx request if ongoing */ - dmarequest = HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAT); - if((hirda->gState == HAL_IRDA_STATE_BUSY_TX) && dmarequest) - { - hirda->TxXferCount = 0U; - IRDA_EndTxTransfer(hirda); - } - - /* Stop IRDA DMA Rx request if ongoing */ - dmarequest = HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAR); - if((hirda->RxState == HAL_IRDA_STATE_BUSY_RX) && dmarequest) - { - hirda->RxXferCount = 0U; - IRDA_EndRxTransfer(hirda); - } - + hirda->RxXferCount = 0; + hirda->TxXferCount = 0; hirda->ErrorCode |= HAL_IRDA_ERROR_DMA; + hirda->State= HAL_IRDA_STATE_READY; HAL_IRDA_ErrorCallback(hirda); } @@ -1747,238 +1290,113 @@ static void IRDA_DMAError(DMA_HandleTypeDef *hdma) * the configuration information for the specified IRDA module. * @param Flag: specifies the IRDA flag to check. * @param Status: The new Flag status (SET or RESET). - * @param Tickstart: Tick start value * @param Timeout: Timeout duration * @retval HAL status */ -static HAL_StatusTypeDef IRDA_WaitOnFlagUntilTimeout(IRDA_HandleTypeDef *hirda, uint32_t Flag, FlagStatus Status, uint32_t Tickstart, uint32_t Timeout) +static HAL_StatusTypeDef IRDA_WaitOnFlagUntilTimeout(IRDA_HandleTypeDef *hirda, uint32_t Flag, FlagStatus Status, uint32_t Timeout) { + uint32_t tickstart = 0; + + /* Get tick */ + tickstart = HAL_GetTick(); + /* Wait until flag is set */ - while((__HAL_IRDA_GET_FLAG(hirda, Flag) ? SET : RESET) == Status) + if(Status == RESET) { - /* Check for the Timeout */ - if(Timeout != HAL_MAX_DELAY) + while(__HAL_IRDA_GET_FLAG(hirda, Flag) == RESET) { - if((Timeout == 0U)||((HAL_GetTick() - Tickstart ) > Timeout)) + /* Check for the Timeout */ + if(Timeout != HAL_MAX_DELAY) { - /* Disable TXE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts for the interrupt process */ - CLEAR_BIT(hirda->Instance->CR1, (USART_CR1_RXNEIE | USART_CR1_PEIE | USART_CR1_TXEIE)); - CLEAR_BIT(hirda->Instance->CR3, USART_CR3_EIE); - - hirda->gState = HAL_IRDA_STATE_READY; - hirda->RxState = HAL_IRDA_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hirda); - - return HAL_TIMEOUT; - } - } - } - return HAL_OK; -} - -/** - * @brief End ongoing Tx transfer on IRDA peripheral (following error detection or Transmit completion). - * @param hirda: IRDA handle. - * @retval None - */ -static void IRDA_EndTxTransfer(IRDA_HandleTypeDef *hirda) -{ - /* Disable TXEIE and TCIE interrupts */ - CLEAR_BIT(hirda->Instance->CR1, (USART_CR1_TXEIE | USART_CR1_TCIE)); - - /* At end of Tx process, restore hirda->gState to Ready */ - hirda->gState = HAL_IRDA_STATE_READY; -} - -/** - * @brief End ongoing Rx transfer on IRDA peripheral (following error detection or Reception completion). - * @param hirda: IRDA handle. - * @retval None - */ -static void IRDA_EndRxTransfer(IRDA_HandleTypeDef *hirda) -{ - /* Disable RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */ - CLEAR_BIT(hirda->Instance->CR1, (USART_CR1_RXNEIE | USART_CR1_PEIE)); - CLEAR_BIT(hirda->Instance->CR3, USART_CR3_EIE); - - /* At end of Rx process, restore hirda->RxState to Ready */ - hirda->RxState = HAL_IRDA_STATE_READY; -} + if((Timeout == 0)||((HAL_GetTick() - tickstart ) > Timeout)) + { + /* Disable TXE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts for the interrupt process */ + __HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_TXE); + __HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_RXNE); + __HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_PE); + __HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_ERR); -/** - * @brief DMA IRDA communication abort callback, when initiated by HAL services on Error - * (To be called at end of DMA Abort procedure following error occurrence). - * @param hdma DMA handle. - * @retval None - */ -static void IRDA_DMAAbortOnError(DMA_HandleTypeDef *hdma) -{ - IRDA_HandleTypeDef* hirda = ( IRDA_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; - hirda->RxXferCount = 0x00U; - hirda->TxXferCount = 0x00U; + hirda->State= HAL_IRDA_STATE_READY; - HAL_IRDA_ErrorCallback(hirda); -} + /* Process Unlocked */ + __HAL_UNLOCK(hirda); -/** - * @brief DMA IRDA Tx communication abort callback, when initiated by user - * (To be called at end of DMA Tx Abort procedure following user abort request). - * @note When this callback is executed, User Abort complete call back is called only if no - * Abort still ongoing for Rx DMA Handle. - * @param hdma DMA handle. - * @retval None - */ -static void IRDA_DMATxAbortCallback(DMA_HandleTypeDef *hdma) -{ - IRDA_HandleTypeDef* hirda = ( IRDA_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; - - hirda->hdmatx->XferAbortCallback = NULL; - - /* Check if an Abort process is still ongoing */ - if(hirda->hdmarx != NULL) - { - if(hirda->hdmarx->XferAbortCallback != NULL) - { - return; + return HAL_TIMEOUT; + } + } } } - - /* No Abort process still ongoing : All DMA channels are aborted, call user Abort Complete callback */ - hirda->TxXferCount = 0x00U; - hirda->RxXferCount = 0x00U; - - /* Reset ErrorCode */ - hirda->ErrorCode = HAL_IRDA_ERROR_NONE; - - /* Restore hirda->gState and hirda->RxState to Ready */ - hirda->gState = HAL_IRDA_STATE_READY; - hirda->RxState = HAL_IRDA_STATE_READY; - - /* Call user Abort complete callback */ - HAL_IRDA_AbortCpltCallback(hirda); -} - -/** - * @brief DMA IRDA Rx communication abort callback, when initiated by user - * (To be called at end of DMA Rx Abort procedure following user abort request). - * @note When this callback is executed, User Abort complete call back is called only if no - * Abort still ongoing for Tx DMA Handle. - * @param hdma DMA handle. - * @retval None - */ -static void IRDA_DMARxAbortCallback(DMA_HandleTypeDef *hdma) -{ - IRDA_HandleTypeDef* hirda = ( IRDA_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; - - hirda->hdmarx->XferAbortCallback = NULL; - - /* Check if an Abort process is still ongoing */ - if(hirda->hdmatx != NULL) + else { - if(hirda->hdmatx->XferAbortCallback != NULL) + while(__HAL_IRDA_GET_FLAG(hirda, Flag) != RESET) { - return; - } - } - - /* No Abort process still ongoing : All DMA channels are aborted, call user Abort Complete callback */ - hirda->TxXferCount = 0x00U; - hirda->RxXferCount = 0x00U; - - /* Reset ErrorCode */ - hirda->ErrorCode = HAL_IRDA_ERROR_NONE; - - /* Restore hirda->gState and hirda->RxState to Ready */ - hirda->gState = HAL_IRDA_STATE_READY; - hirda->RxState = HAL_IRDA_STATE_READY; - - /* Call user Abort complete callback */ - HAL_IRDA_AbortCpltCallback(hirda); -} - -/** - * @brief DMA IRDA Tx communication abort callback, when initiated by user by a call to - * HAL_IRDA_AbortTransmit_IT API (Abort only Tx transfer) - * (This callback is executed at end of DMA Tx Abort procedure following user abort request, - * and leads to user Tx Abort Complete callback execution). - * @param hdma DMA handle. - * @retval None - */ -static void IRDA_DMATxOnlyAbortCallback(DMA_HandleTypeDef *hdma) -{ - IRDA_HandleTypeDef* hirda = ( IRDA_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; - - hirda->TxXferCount = 0x00U; - - /* Restore hirda->gState to Ready */ - hirda->gState = HAL_IRDA_STATE_READY; - - /* Call user Abort complete callback */ - HAL_IRDA_AbortTransmitCpltCallback(hirda); -} - -/** - * @brief DMA IRDA Rx communication abort callback, when initiated by user by a call to - * HAL_IRDA_AbortReceive_IT API (Abort only Rx transfer) - * (This callback is executed at end of DMA Rx Abort procedure following user abort request, - * and leads to user Rx Abort Complete callback execution). - * @param hdma DMA handle. - * @retval None - */ -static void IRDA_DMARxOnlyAbortCallback(DMA_HandleTypeDef *hdma) -{ - IRDA_HandleTypeDef* hirda = ( IRDA_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; - - hirda->RxXferCount = 0x00U; + /* Check for the Timeout */ + if(Timeout != HAL_MAX_DELAY) + { + if((Timeout == 0)||((HAL_GetTick() - tickstart ) > Timeout)) + { + /* Disable TXE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts for the interrupt process */ + __HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_TXE); + __HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_RXNE); + __HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_PE); + __HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_ERR); - /* Restore hirda->RxState to Ready */ - hirda->RxState = HAL_IRDA_STATE_READY; + hirda->State= HAL_IRDA_STATE_READY; - /* Call user Abort complete callback */ - HAL_IRDA_AbortReceiveCpltCallback(hirda); + /* Process Unlocked */ + __HAL_UNLOCK(hirda); + + return HAL_TIMEOUT; + } + } + } + } + return HAL_OK; } /** - * @brief Send an amount of data in non blocking mode. - * @param hirda: pointer to a IRDA_HandleTypeDef structure that contains + * @brief Send an amount of data in non-blocking mode. + * Function called under interruption only, once + * interruptions have been enabled by HAL_IRDA_Transmit_IT() + * @param hirda: Pointer to a IRDA_HandleTypeDef structure that contains * the configuration information for the specified IRDA module. * @retval HAL status */ static HAL_StatusTypeDef IRDA_Transmit_IT(IRDA_HandleTypeDef *hirda) { - uint16_t* tmp; - - /* Check that a Tx process is ongoing */ - if(hirda->gState == HAL_IRDA_STATE_BUSY_TX) + uint16_t* tmp = 0; + uint32_t tmp_state = 0; + + tmp_state = hirda->State; + if((tmp_state == HAL_IRDA_STATE_BUSY_TX) || (tmp_state == HAL_IRDA_STATE_BUSY_TX_RX)) { if(hirda->Init.WordLength == IRDA_WORDLENGTH_9B) { tmp = (uint16_t*) hirda->pTxBuffPtr; - hirda->Instance->DR = (uint16_t)(*tmp & (uint16_t)0x01FF); + WRITE_REG(hirda->Instance->DR, (uint16_t)(*tmp & IRDA_DR_MASK_U16_9DATABITS)); if(hirda->Init.Parity == IRDA_PARITY_NONE) { - hirda->pTxBuffPtr += 2U; + hirda->pTxBuffPtr += 2; } else { - hirda->pTxBuffPtr += 1U; + hirda->pTxBuffPtr += 1; } } else { - hirda->Instance->DR = (uint8_t)(*hirda->pTxBuffPtr++ & (uint8_t)0x00FF); + WRITE_REG(hirda->Instance->DR, (uint8_t)(*hirda->pTxBuffPtr++ & IRDA_DR_MASK_U8_8DATABITS)); } - - if(--hirda->TxXferCount == 0U) + + if(--hirda->TxXferCount == 0) { /* Disable the IRDA Transmit Data Register Empty Interrupt */ - CLEAR_BIT(hirda->Instance->CR1, USART_CR1_TXEIE); - - /* Enable the IRDA Transmit Complete Interrupt */ - SET_BIT(hirda->Instance->CR1, USART_CR1_TCIE); + __HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_TXE); + + /* Enable the IRDA Transmit Complete Interrupt */ + __HAL_IRDA_ENABLE_IT(hirda, IRDA_IT_TC); } + return HAL_OK; } else @@ -1996,69 +1414,86 @@ static HAL_StatusTypeDef IRDA_Transmit_IT(IRDA_HandleTypeDef *hirda) static HAL_StatusTypeDef IRDA_EndTransmit_IT(IRDA_HandleTypeDef *hirda) { /* Disable the IRDA Transmit Complete Interrupt */ - CLEAR_BIT(hirda->Instance->CR1, USART_CR1_TCIE); + __HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_TC); + + /* Check if a receive process is ongoing or not */ + if(hirda->State == HAL_IRDA_STATE_BUSY_TX_RX) + { + hirda->State = HAL_IRDA_STATE_BUSY_RX; + } + else + { + /* Disable the IRDA Error Interrupt: (Frame error, noise error, overrun error) */ + __HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_ERR); + + hirda->State = HAL_IRDA_STATE_READY; + } - /* Tx process is ended, restore hirda->gState to Ready */ - hirda->gState = HAL_IRDA_STATE_READY; HAL_IRDA_TxCpltCallback(hirda); return HAL_OK; } + /** - * @brief Receives an amount of data in non blocking mode. + * @brief Receive an amount of data in non-blocking mode. * @param hirda: Pointer to a IRDA_HandleTypeDef structure that contains * the configuration information for the specified IRDA module. * @retval HAL status */ static HAL_StatusTypeDef IRDA_Receive_IT(IRDA_HandleTypeDef *hirda) { - uint16_t* tmp; - uint16_t uhdata; - - /* Check that a Rx process is ongoing */ - if(hirda->RxState == HAL_IRDA_STATE_BUSY_RX) + uint16_t* tmp = 0; + uint32_t tmp_state = 0; + + tmp_state = hirda->State; + if((tmp_state == HAL_IRDA_STATE_BUSY_RX) || (tmp_state == HAL_IRDA_STATE_BUSY_TX_RX)) { - uhdata = (uint16_t) READ_REG(hirda->Instance->DR); if(hirda->Init.WordLength == IRDA_WORDLENGTH_9B) { tmp = (uint16_t*) hirda->pRxBuffPtr; if(hirda->Init.Parity == IRDA_PARITY_NONE) { - *tmp = (uint16_t)(uhdata & (uint16_t)0x01FF); - hirda->pRxBuffPtr += 2U; + *tmp = (uint16_t)(hirda->Instance->DR & IRDA_DR_MASK_U16_9DATABITS); + hirda->pRxBuffPtr += 2; } else { - *tmp = (uint16_t)(uhdata & (uint16_t)0x00FF); - hirda->pRxBuffPtr += 1U; + *tmp = (uint16_t)(hirda->Instance->DR & IRDA_DR_MASK_U16_8DATABITS); + hirda->pRxBuffPtr += 1; } - } + } else { if(hirda->Init.Parity == IRDA_PARITY_NONE) { - *hirda->pRxBuffPtr++ = (uint8_t)(uhdata & (uint8_t)0x00FF); + *hirda->pRxBuffPtr++ = (uint8_t)(hirda->Instance->DR & IRDA_DR_MASK_U8_8DATABITS); } else { - *hirda->pRxBuffPtr++ = (uint8_t)(uhdata & (uint8_t)0x007F); + *hirda->pRxBuffPtr++ = (uint8_t)(hirda->Instance->DR & IRDA_DR_MASK_U8_7DATABITS); } } - if(--hirda->RxXferCount == 0U) + if(--hirda->RxXferCount == 0) { - /* Disable the IRDA Data Register not empty Interrupt */ __HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_RXNE); - - /* Disable the IRDA Parity Error Interrupt */ - __HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_PE); - /* Disable the IRDA Error Interrupt: (Frame error, noise error, overrun error) */ - __HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_ERR); - - /* Rx process is completed, restore hirda->RxState to Ready */ - hirda->RxState = HAL_IRDA_STATE_READY; + if(hirda->State == HAL_IRDA_STATE_BUSY_TX_RX) + { + hirda->State = HAL_IRDA_STATE_BUSY_TX; + } + else + { + /* Disable the IRDA Error Interrupt: (Frame error, noise error, overrun error) */ + __HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_ERR); + + /* Disable the IRDA Parity Error Interrupt */ + __HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_PE); + + + hirda->State = HAL_IRDA_STATE_READY; + } HAL_IRDA_RxCpltCallback(hirda); return HAL_OK; @@ -2067,7 +1502,7 @@ static HAL_StatusTypeDef IRDA_Receive_IT(IRDA_HandleTypeDef *hirda) } else { - return HAL_BUSY; + return HAL_BUSY; } } @@ -2080,43 +1515,38 @@ static HAL_StatusTypeDef IRDA_Receive_IT(IRDA_HandleTypeDef *hirda) static void IRDA_SetConfig(IRDA_HandleTypeDef *hirda) { /* Check the parameters */ - assert_param(IS_IRDA_INSTANCE(hirda->Instance)); assert_param(IS_IRDA_BAUDRATE(hirda->Init.BaudRate)); assert_param(IS_IRDA_WORD_LENGTH(hirda->Init.WordLength)); assert_param(IS_IRDA_PARITY(hirda->Init.Parity)); assert_param(IS_IRDA_MODE(hirda->Init.Mode)); - assert_param(IS_IRDA_POWERMODE(hirda->Init.IrDAMode)); - - /*-------------------------- USART CR2 Configuration ------------------------*/ + + /*------- IRDA-associated USART registers setting : CR2 Configuration ------*/ /* Clear STOP[13:12] bits */ CLEAR_BIT(hirda->Instance->CR2, USART_CR2_STOP); - /*-------------------------- USART CR1 Configuration -----------------------*/ - /* Clear M, PCE, PS, TE and RE bits */ - CLEAR_BIT(hirda->Instance->CR1, USART_CR1_M | USART_CR1_PCE | USART_CR1_PS | USART_CR1_TE | USART_CR1_RE); - + /*------- IRDA-associated USART registers setting : CR1 Configuration ------*/ /* Configure the USART Word Length, Parity and mode: - Set the M bits according to hirda->Init.WordLength value - Set PCE and PS bits according to hirda->Init.Parity value - Set TE and RE bits according to hirda->Init.Mode value */ - /* Write to USART CR1 */ - SET_BIT(hirda->Instance->CR1, (uint32_t)hirda->Init.WordLength | hirda->Init.Parity | hirda->Init.Mode); + Set the M bits according to hirda->Init.WordLength value + Set PCE and PS bits according to hirda->Init.Parity value + Set TE and RE bits according to hirda->Init.Mode value */ + MODIFY_REG(hirda->Instance->CR1, + ((uint32_t)(USART_CR1_M | USART_CR1_PCE | USART_CR1_PS | USART_CR1_TE | USART_CR1_RE)), + (uint32_t)hirda->Init.WordLength | hirda->Init.Parity | hirda->Init.Mode); - /*-------------------------- USART CR3 Configuration -----------------------*/ + /*------- IRDA-associated USART registers setting : CR3 Configuration ------*/ /* Clear CTSE and RTSE bits */ - CLEAR_BIT(hirda->Instance->CR3, USART_CR3_RTSE | USART_CR3_CTSE); + CLEAR_BIT(hirda->Instance->CR3, (USART_CR3_RTSE | USART_CR3_CTSE)); - /*-------------------------- USART BRR Configuration -----------------------*/ + /*------- IRDA-associated USART registers setting : BRR Configuration ------*/ if(hirda->Instance == USART1) { - SET_BIT(hirda->Instance->BRR, IRDA_BRR(HAL_RCC_GetPCLK2Freq(), hirda->Init.BaudRate)); + hirda->Instance->BRR = IRDA_BRR(HAL_RCC_GetPCLK2Freq(), hirda->Init.BaudRate); } else { - SET_BIT(hirda->Instance->BRR, IRDA_BRR(HAL_RCC_GetPCLK1Freq(), hirda->Init.BaudRate)); + hirda->Instance->BRR = IRDA_BRR(HAL_RCC_GetPCLK1Freq(), hirda->Init.BaudRate); } } - /** * @} */ diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_irda.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_irda.h index 983bc22e820..a339d2f97a7 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_irda.h +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_irda.h @@ -2,13 +2,13 @@ ****************************************************************************** * @file stm32f1xx_hal_irda.h * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief Header file of IRDA HAL module. ****************************************************************************** * @attention * - *

© COPYRIGHT(c) 2017 STMicroelectronics

+ *

© COPYRIGHT(c) 2016 STMicroelectronics

* * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: @@ -57,7 +57,7 @@ /* Exported types ------------------------------------------------------------*/ /** @defgroup IRDA_Exported_Types IRDA Exported Types * @{ - */ + */ /** * @brief IRDA Init Structure definition @@ -79,8 +79,8 @@ typedef struct at the MSB position of the transmitted data (9th bit when the word length is set to 9 data bits; 8th bit when the word length is set to 8 data bits). */ - - uint32_t Mode; /*!< Specifies whether the Receive or Transmit mode is enabled or disabled. + + uint32_t Mode; /*!< Specifies wether the Receive or Transmit mode is enabled or disabled. This parameter can be a value of @ref IRDA_Transfer_Mode */ uint8_t Prescaler; /*!< Specifies the Prescaler value prescaler value to be programmed @@ -93,100 +93,52 @@ typedef struct }IRDA_InitTypeDef; /** - * @brief HAL IRDA State structures definition - * @note HAL IRDA State value is a combination of 2 different substates: gState and RxState. - * - gState contains IRDA state information related to global Handle management - * and also information related to Tx operations. - * gState value coding follow below described bitmap : - * b7-b6 Error information - * 00 : No Error - * 01 : (Not Used) - * 10 : Timeout - * 11 : Error - * b5 IP initilisation status - * 0 : Reset (IP not initialized) - * 1 : Init done (IP not initialized. HAL IRDA Init function already called) - * b4-b3 (not used) - * xx : Should be set to 00 - * b2 Intrinsic process state - * 0 : Ready - * 1 : Busy (IP busy with some configuration or internal operations) - * b1 (not used) - * x : Should be set to 0 - * b0 Tx state - * 0 : Ready (no Tx operation ongoing) - * 1 : Busy (Tx operation ongoing) - * - RxState contains information related to Rx operations. - * RxState value coding follow below described bitmap : - * b7-b6 (not used) - * xx : Should be set to 00 - * b5 IP initilisation status - * 0 : Reset (IP not initialized) - * 1 : Init done (IP not initialized) - * b4-b2 (not used) - * xxx : Should be set to 000 - * b1 Rx state - * 0 : Ready (no Rx operation ongoing) - * 1 : Busy (Rx operation ongoing) - * b0 (not used) - * x : Should be set to 0. + * @brief HAL IRDA State structures definition */ typedef enum { - HAL_IRDA_STATE_RESET = 0x00U, /*!< Peripheral is not yet Initialized - Value is allowed for gState and RxState */ - HAL_IRDA_STATE_READY = 0x20U, /*!< Peripheral Initialized and ready for use - Value is allowed for gState and RxState */ - HAL_IRDA_STATE_BUSY = 0x24U, /*!< An internal process is ongoing - Value is allowed for gState only */ - HAL_IRDA_STATE_BUSY_TX = 0x21U, /*!< Data Transmission process is ongoing - Value is allowed for gState only */ - HAL_IRDA_STATE_BUSY_RX = 0x22U, /*!< Data Reception process is ongoing - Value is allowed for RxState only */ - HAL_IRDA_STATE_BUSY_TX_RX = 0x23U, /*!< Data Transmission and Reception process is ongoing - Not to be used for neither gState nor RxState. - Value is result of combination (Or) between gState and RxState values */ - HAL_IRDA_STATE_TIMEOUT = 0xA0U, /*!< Timeout state - Value is allowed for gState only */ - HAL_IRDA_STATE_ERROR = 0xE0U /*!< Error - Value is allowed for gState only */ + HAL_IRDA_STATE_RESET = 0x00, /*!< Peripheral is not initialized */ + HAL_IRDA_STATE_READY = 0x01, /*!< Peripheral Initialized and ready for use */ + HAL_IRDA_STATE_BUSY = 0x02, /*!< an internal process is ongoing */ + HAL_IRDA_STATE_BUSY_TX = 0x12, /*!< Data Transmission process is ongoing */ + HAL_IRDA_STATE_BUSY_RX = 0x22, /*!< Data Reception process is ongoing */ + HAL_IRDA_STATE_BUSY_TX_RX = 0x32, /*!< Data Transmission and Reception process is ongoing */ + HAL_IRDA_STATE_TIMEOUT = 0x03, /*!< Timeout state */ + HAL_IRDA_STATE_ERROR = 0x04 /*!< Error */ }HAL_IRDA_StateTypeDef; + /** - * @brief IRDA handle Structure definition + * @brief IRDA handle Structure definition */ typedef struct { USART_TypeDef *Instance; /*!< USART registers base address */ - + IRDA_InitTypeDef Init; /*!< IRDA communication parameters */ - + uint8_t *pTxBuffPtr; /*!< Pointer to IRDA Tx transfer Buffer */ - + uint16_t TxXferSize; /*!< IRDA Tx Transfer size */ - - __IO uint16_t TxXferCount; /*!< IRDA Tx Transfer Counter */ - + + uint16_t TxXferCount; /*!< IRDA Tx Transfer Counter */ + uint8_t *pRxBuffPtr; /*!< Pointer to IRDA Rx transfer Buffer */ - + uint16_t RxXferSize; /*!< IRDA Rx Transfer size */ - - __IO uint16_t RxXferCount; /*!< IRDA Rx Transfer Counter */ - + + uint16_t RxXferCount; /*!< IRDA Rx Transfer Counter */ + DMA_HandleTypeDef *hdmatx; /*!< IRDA Tx DMA Handle parameters */ - + DMA_HandleTypeDef *hdmarx; /*!< IRDA Rx DMA Handle parameters */ - + HAL_LockTypeDef Lock; /*!< Locking object */ - - __IO HAL_IRDA_StateTypeDef gState; /*!< IRDA state information related to global Handle management - and also related to Tx operations. - This parameter can be a value of @ref HAL_IRDA_StateTypeDef */ - - __IO HAL_IRDA_StateTypeDef RxState; /*!< IRDA state information related to Rx operations. - This parameter can be a value of @ref HAL_IRDA_StateTypeDef */ - - __IO uint32_t ErrorCode; /*!< IRDA Error code */ + + __IO HAL_IRDA_StateTypeDef State; /*!< IRDA communication state */ + + __IO uint32_t ErrorCode; /*!< IRDA Error code */ + }IRDA_HandleTypeDef; /** @@ -197,39 +149,44 @@ typedef struct /** @defgroup IRDA_Exported_Constants IRDA Exported constants * @{ */ -/** @defgroup IRDA_Error_Code IRDA Error Code + +/** @defgroup IRDA_Error_Codes IRDA Error Codes * @{ - */ -#define HAL_IRDA_ERROR_NONE 0x00000000U /*!< No error */ -#define HAL_IRDA_ERROR_PE 0x00000001U /*!< Parity error */ -#define HAL_IRDA_ERROR_NE 0x00000002U /*!< Noise error */ -#define HAL_IRDA_ERROR_FE 0x00000004U /*!< Frame error */ -#define HAL_IRDA_ERROR_ORE 0x00000008U /*!< Overrun error */ -#define HAL_IRDA_ERROR_DMA 0x00000010U /*!< DMA transfer error */ + */ +#define HAL_IRDA_ERROR_NONE ((uint32_t)0x00) /*!< No error */ +#define HAL_IRDA_ERROR_PE ((uint32_t)0x01) /*!< Parity error */ +#define HAL_IRDA_ERROR_NE ((uint32_t)0x02) /*!< Noise error */ +#define HAL_IRDA_ERROR_FE ((uint32_t)0x04) /*!< frame error */ +#define HAL_IRDA_ERROR_ORE ((uint32_t)0x08) /*!< Overrun error */ +#define HAL_IRDA_ERROR_DMA ((uint32_t)0x10) /*!< DMA transfer error */ + /** * @} */ + /** @defgroup IRDA_Word_Length IRDA Word Length * @{ */ -#define IRDA_WORDLENGTH_8B 0x00000000U +#define IRDA_WORDLENGTH_8B ((uint32_t)0x00000000) #define IRDA_WORDLENGTH_9B ((uint32_t)USART_CR1_M) /** * @} */ -/** @defgroup IRDA_Parity IRDA Parity + +/** @defgroup IRDA_Parity IRDA Parity * @{ */ -#define IRDA_PARITY_NONE 0x00000000U +#define IRDA_PARITY_NONE ((uint32_t)0x00000000) #define IRDA_PARITY_EVEN ((uint32_t)USART_CR1_PCE) #define IRDA_PARITY_ODD ((uint32_t)(USART_CR1_PCE | USART_CR1_PS)) /** * @} */ -/** @defgroup IRDA_Transfer_Mode IRDA Transfer Mode + +/** @defgroup IRDA_Transfer_Mode IRDA Transfer Mode * @{ */ #define IRDA_MODE_RX ((uint32_t)USART_CR1_RE) @@ -239,11 +196,11 @@ typedef struct * @} */ -/** @defgroup IRDA_Low_Power IRDA Low Power +/** @defgroup IRDA_Low_Power IRDA Low Power * @{ */ -#define IRDA_POWERMODE_LOWPOWER ((uint32_t)USART_CR3_IRLP) -#define IRDA_POWERMODE_NORMAL 0x00000000U +#define IRDA_POWERMODE_LOWPOWER ((uint32_t)USART_CR3_IRLP) +#define IRDA_POWERMODE_NORMAL ((uint32_t)0x00000000) /** * @} */ @@ -267,23 +224,26 @@ typedef struct /** @defgroup IRDA_Interrupt_definition IRDA Interrupt Definitions * Elements values convention: 0xY000XXXX - * - XXXX : Interrupt mask in the XX register - * - Y : Interrupt source register (2bits) - * - 01: CR1 register - * - 10: CR2 register - * - 11: CR3 register + * - XXXX : Interrupt mask (16 bits) in the Y register + * - Y : Interrupt source register (4 bits) + * - 0001: CR1 register + * - 0010: CR2 register + * - 0011: CR3 register + * * @{ */ -#define IRDA_IT_PE ((uint32_t)(IRDA_CR1_REG_INDEX << 28U | USART_CR1_PEIE)) -#define IRDA_IT_TXE ((uint32_t)(IRDA_CR1_REG_INDEX << 28U | USART_CR1_TXEIE)) -#define IRDA_IT_TC ((uint32_t)(IRDA_CR1_REG_INDEX << 28U | USART_CR1_TCIE)) -#define IRDA_IT_RXNE ((uint32_t)(IRDA_CR1_REG_INDEX << 28U | USART_CR1_RXNEIE)) -#define IRDA_IT_IDLE ((uint32_t)(IRDA_CR1_REG_INDEX << 28U | USART_CR1_IDLEIE)) -#define IRDA_IT_LBD ((uint32_t)(IRDA_CR2_REG_INDEX << 28U | USART_CR2_LBDIE)) +#define IRDA_IT_PE ((uint32_t)(IRDA_CR1_REG_INDEX << 28 | USART_CR1_PEIE)) +#define IRDA_IT_TXE ((uint32_t)(IRDA_CR1_REG_INDEX << 28 | USART_CR1_TXEIE)) +#define IRDA_IT_TC ((uint32_t)(IRDA_CR1_REG_INDEX << 28 | USART_CR1_TCIE)) +#define IRDA_IT_RXNE ((uint32_t)(IRDA_CR1_REG_INDEX << 28 | USART_CR1_RXNEIE)) +#define IRDA_IT_IDLE ((uint32_t)(IRDA_CR1_REG_INDEX << 28 | USART_CR1_IDLEIE)) + +#define IRDA_IT_LBD ((uint32_t)(IRDA_CR2_REG_INDEX << 28 | USART_CR2_LBDIE)) + +#define IRDA_IT_CTS ((uint32_t)(IRDA_CR3_REG_INDEX << 28 | USART_CR3_CTSIE)) +#define IRDA_IT_ERR ((uint32_t)(IRDA_CR3_REG_INDEX << 28 | USART_CR3_EIE)) -#define IRDA_IT_CTS ((uint32_t)(IRDA_CR3_REG_INDEX << 28U | USART_CR3_CTSIE)) -#define IRDA_IT_ERR ((uint32_t)(IRDA_CR3_REG_INDEX << 28U | USART_CR3_EIE)) /** * @} */ @@ -292,20 +252,19 @@ typedef struct * @} */ + /* Exported macro ------------------------------------------------------------*/ /** @defgroup IRDA_Exported_Macros IRDA Exported Macros * @{ */ -/** @brief Reset IRDA handle gstate & RxState +/** @brief Reset IRDA handle state * @param __HANDLE__: specifies the IRDA Handle. * IRDA Handle selects the USARTx or UARTy peripheral * (USART,UART availability and x,y values depending on device). + * @retval None */ -#define __HAL_IRDA_RESET_HANDLE_STATE(__HANDLE__) do{ \ - (__HANDLE__)->gState = HAL_IRDA_STATE_RESET; \ - (__HANDLE__)->RxState = HAL_IRDA_STATE_RESET; \ - } while(0U) +#define __HAL_IRDA_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_IRDA_STATE_RESET) /** @brief Flush the IRDA DR register * @param __HANDLE__: specifies the USART Handle. @@ -350,6 +309,7 @@ typedef struct * USART_SR register followed by a write operation to USART_DR register. * @note TXE flag is cleared only by a write to the USART_DR register. * + * @retval None */ #define __HAL_IRDA_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->SR = ~(__FLAG__)) @@ -357,19 +317,21 @@ typedef struct * @param __HANDLE__: specifies the IRDA Handle. * IRDA Handle selects the USARTx or UARTy peripheral * (USART,UART availability and x,y values depending on device). - */ -#define __HAL_IRDA_CLEAR_PEFLAG(__HANDLE__) \ -do{ \ - __IO uint32_t tmpreg = 0x00U; \ - tmpreg = (__HANDLE__)->Instance->SR; \ - tmpreg = (__HANDLE__)->Instance->DR; \ - UNUSED(tmpreg); \ - } while(0U) - + * @retval None + */ +#define __HAL_IRDA_CLEAR_PEFLAG(__HANDLE__) \ +do{ \ + __IO uint32_t tmpreg; \ + tmpreg = (__HANDLE__)->Instance->SR; \ + tmpreg = (__HANDLE__)->Instance->DR; \ + UNUSED(tmpreg); \ + }while(0) \ + /** @brief Clear the IRDA FE pending flag. * @param __HANDLE__: specifies the IRDA Handle. * IRDA Handle selects the USARTx or UARTy peripheral * (USART,UART availability and x,y values depending on device). + * @retval None */ #define __HAL_IRDA_CLEAR_FEFLAG(__HANDLE__) __HAL_IRDA_CLEAR_PEFLAG(__HANDLE__) @@ -377,6 +339,7 @@ do{ \ * @param __HANDLE__: specifies the IRDA Handle. * IRDA Handle selects the USARTx or UARTy peripheral * (USART,UART availability and x,y values depending on device). + * @retval None */ #define __HAL_IRDA_CLEAR_NEFLAG(__HANDLE__) __HAL_IRDA_CLEAR_PEFLAG(__HANDLE__) @@ -384,6 +347,7 @@ do{ \ * @param __HANDLE__: specifies the IRDA Handle. * IRDA Handle selects the USARTx or UARTy peripheral * (USART,UART availability and x,y values depending on device). + * @retval None */ #define __HAL_IRDA_CLEAR_OREFLAG(__HANDLE__) __HAL_IRDA_CLEAR_PEFLAG(__HANDLE__) @@ -391,6 +355,7 @@ do{ \ * @param __HANDLE__: specifies the IRDA Handle. * IRDA Handle selects the USARTx or UARTy peripheral * (USART,UART availability and x,y values depending on device). + * @retval None */ #define __HAL_IRDA_CLEAR_IDLEFLAG(__HANDLE__) __HAL_IRDA_CLEAR_PEFLAG(__HANDLE__) @@ -406,10 +371,12 @@ do{ \ * @arg IRDA_IT_IDLE: Idle line detection interrupt * @arg IRDA_IT_PE: Parity Error interrupt * @arg IRDA_IT_ERR: Error interrupt(Frame error, noise error, overrun error) + * @retval None */ -#define __HAL_IRDA_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((((__INTERRUPT__) >> 28U) == IRDA_CR1_REG_INDEX)? ((__HANDLE__)->Instance->CR1 |= ((__INTERRUPT__) & IRDA_IT_MASK)): \ - (((__INTERRUPT__) >> 28U) == IRDA_CR2_REG_INDEX)? ((__HANDLE__)->Instance->CR2 |= ((__INTERRUPT__) & IRDA_IT_MASK)): \ +#define __HAL_IRDA_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((((__INTERRUPT__) >> 28) == IRDA_CR1_REG_INDEX)? ((__HANDLE__)->Instance->CR1 |= ((__INTERRUPT__) & IRDA_IT_MASK)): \ + (((__INTERRUPT__) >> 28) == IRDA_CR2_REG_INDEX)? ((__HANDLE__)->Instance->CR2 |= ((__INTERRUPT__) & IRDA_IT_MASK)): \ ((__HANDLE__)->Instance->CR3 |= ((__INTERRUPT__) & IRDA_IT_MASK))) + /** @brief Disable the specified IRDA interrupt. * @param __HANDLE__: specifies the IRDA Handle. * IRDA Handle selects the USARTx or UARTy peripheral @@ -422,9 +389,10 @@ do{ \ * @arg IRDA_IT_IDLE: Idle line detection interrupt * @arg IRDA_IT_PE: Parity Error interrupt * @arg IRDA_IT_ERR: Error interrupt(Frame error, noise error, overrun error) + * @retval None */ -#define __HAL_IRDA_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((((__INTERRUPT__) >> 28U) == IRDA_CR1_REG_INDEX)? ((__HANDLE__)->Instance->CR1 &= ~((__INTERRUPT__) & IRDA_IT_MASK)): \ - (((__INTERRUPT__) >> 28U) == IRDA_CR2_REG_INDEX)? ((__HANDLE__)->Instance->CR2 &= ~((__INTERRUPT__) & IRDA_IT_MASK)): \ +#define __HAL_IRDA_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((((__INTERRUPT__) >> 28) == IRDA_CR1_REG_INDEX)? ((__HANDLE__)->Instance->CR1 &= ~((__INTERRUPT__) & IRDA_IT_MASK)): \ + (((__INTERRUPT__) >> 28) == IRDA_CR2_REG_INDEX)? ((__HANDLE__)->Instance->CR2 &= ~((__INTERRUPT__) & IRDA_IT_MASK)): \ ((__HANDLE__)->Instance->CR3 &= ~ ((__INTERRUPT__) & IRDA_IT_MASK))) /** @brief Check whether the specified IRDA interrupt has occurred or not. @@ -441,20 +409,22 @@ do{ \ * @arg IRDA_IT_PE: Parity Error interrupt * @retval The new state of __IT__ (TRUE or FALSE). */ -#define __HAL_IRDA_GET_IT_SOURCE(__HANDLE__, __IT__) (((((__IT__) >> 28U) == IRDA_CR1_REG_INDEX)? (__HANDLE__)->Instance->CR1:(((((uint32_t)(__IT__)) >> 28U) == IRDA_CR2_REG_INDEX)? \ +#define __HAL_IRDA_GET_IT_SOURCE(__HANDLE__, __IT__) (((((__IT__) >> 28) == IRDA_CR1_REG_INDEX)? (__HANDLE__)->Instance->CR1:((((__IT__) >> 28) == IRDA_CR2_REG_INDEX)? \ (__HANDLE__)->Instance->CR2 : (__HANDLE__)->Instance->CR3)) & (((uint32_t)(__IT__)) & IRDA_IT_MASK)) /** @brief Enable UART/USART associated to IRDA Handle * @param __HANDLE__: specifies the IRDA Handle. * IRDA Handle selects the USARTx or UARTy peripheral * (USART,UART availability and x,y values depending on device). - */ + * @retval None + */ #define __HAL_IRDA_ENABLE(__HANDLE__) (SET_BIT((__HANDLE__)->Instance->CR1, USART_CR1_UE)) /** @brief Disable UART/USART associated to IRDA Handle * @param __HANDLE__: specifies the IRDA Handle. * IRDA Handle selects the USARTx or UARTy peripheral * (USART,UART availability and x,y values depending on device). + * @retval None */ #define __HAL_IRDA_DISABLE(__HANDLE__) (CLEAR_BIT((__HANDLE__)->Instance->CR1, USART_CR1_UE)) @@ -462,27 +432,80 @@ do{ \ * @} */ +/* Private macros --------------------------------------------------------*/ +/** @defgroup IRDA_Private_Macros IRDA Private Macros + * @{ + */ + +#define IRDA_CR1_REG_INDEX 1 +#define IRDA_CR2_REG_INDEX 2 +#define IRDA_CR3_REG_INDEX 3 + +#define IRDA_DIV(__PCLK__, __BAUD__) (((__PCLK__)*25)/(4*(__BAUD__))) +#define IRDA_DIVMANT(__PCLK__, __BAUD__) (IRDA_DIV((__PCLK__), (__BAUD__))/100) +#define IRDA_DIVFRAQ(__PCLK__, __BAUD__) (((IRDA_DIV((__PCLK__), (__BAUD__)) - (IRDA_DIVMANT((__PCLK__), (__BAUD__)) * 100)) * 16 + 50) / 100) +/* UART BRR = mantissa + overflow + fraction + = (UART DIVMANT << 4) + (UART DIVFRAQ & 0xF0) + (UART DIVFRAQ & 0x0F) */ +#define IRDA_BRR(_PCLK_, _BAUD_) (((IRDA_DIVMANT((_PCLK_), (_BAUD_)) << 4) + \ + (IRDA_DIVFRAQ((_PCLK_), (_BAUD_)) & 0xF0)) + \ + (IRDA_DIVFRAQ((_PCLK_), (_BAUD_)) & 0x0F)) + +/** Ensure that IRDA Baud rate is less or equal to maximum value + * __BAUDRATE__: specifies the IRDA Baudrate set by the user. + * The maximum Baud Rate is 115200bps + * Returns : True or False + */ +#define IS_IRDA_BAUDRATE(__BAUDRATE__) ((__BAUDRATE__) < 115201) + +#define IS_IRDA_WORD_LENGTH(LENGTH) (((LENGTH) == IRDA_WORDLENGTH_8B) || \ + ((LENGTH) == IRDA_WORDLENGTH_9B)) + +#define IS_IRDA_PARITY(PARITY) (((PARITY) == IRDA_PARITY_NONE) || \ + ((PARITY) == IRDA_PARITY_EVEN) || \ + ((PARITY) == IRDA_PARITY_ODD)) + +#define IS_IRDA_MODE(MODE) ((((MODE) & (~((uint32_t)IRDA_MODE_TX_RX))) == 0x00) && \ + ((MODE) != (uint32_t)0x00000000)) + +#define IS_IRDA_POWERMODE(MODE) (((MODE) == IRDA_POWERMODE_LOWPOWER) || \ + ((MODE) == IRDA_POWERMODE_NORMAL)) + +/** IRDA interruptions flag mask + * + */ +#define IRDA_IT_MASK ((uint32_t) USART_CR1_PEIE | USART_CR1_TXEIE | USART_CR1_TCIE | USART_CR1_RXNEIE | \ + USART_CR1_IDLEIE | USART_CR2_LBDIE | USART_CR3_CTSIE | USART_CR3_EIE ) + +/** + * @} + */ + + /* Exported functions --------------------------------------------------------*/ -/** @addtogroup IRDA_Exported_Functions + +/** @addtogroup IRDA_Exported_Functions IRDA Exported Functions * @{ */ -/** @addtogroup IRDA_Exported_Functions_Group1 +/** @addtogroup IRDA_Exported_Functions_Group1 Initialization and de-initialization functions * @{ */ -/* Initialization/de-initialization functions **********************************/ + +/* Initialization and de-initialization functions ****************************/ HAL_StatusTypeDef HAL_IRDA_Init(IRDA_HandleTypeDef *hirda); HAL_StatusTypeDef HAL_IRDA_DeInit(IRDA_HandleTypeDef *hirda); void HAL_IRDA_MspInit(IRDA_HandleTypeDef *hirda); void HAL_IRDA_MspDeInit(IRDA_HandleTypeDef *hirda); + /** * @} */ -/** @addtogroup IRDA_Exported_Functions_Group2 +/** @addtogroup IRDA_Exported_Functions_Group2 IO operation functions * @{ */ -/* IO operation functions *******************************************************/ + +/* IO operation functions *****************************************************/ HAL_StatusTypeDef HAL_IRDA_Transmit(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_IRDA_Receive(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_IRDA_Transmit_IT(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size); @@ -492,92 +515,29 @@ HAL_StatusTypeDef HAL_IRDA_Receive_DMA(IRDA_HandleTypeDef *hirda, uint8_t *pData HAL_StatusTypeDef HAL_IRDA_DMAPause(IRDA_HandleTypeDef *hirda); HAL_StatusTypeDef HAL_IRDA_DMAResume(IRDA_HandleTypeDef *hirda); HAL_StatusTypeDef HAL_IRDA_DMAStop(IRDA_HandleTypeDef *hirda); -/* Transfer Abort functions */ -HAL_StatusTypeDef HAL_IRDA_Abort(IRDA_HandleTypeDef *hirda); -HAL_StatusTypeDef HAL_IRDA_AbortTransmit(IRDA_HandleTypeDef *hirda); -HAL_StatusTypeDef HAL_IRDA_AbortReceive(IRDA_HandleTypeDef *hirda); -HAL_StatusTypeDef HAL_IRDA_Abort_IT(IRDA_HandleTypeDef *hirda); -HAL_StatusTypeDef HAL_IRDA_AbortTransmit_IT(IRDA_HandleTypeDef *hirda); -HAL_StatusTypeDef HAL_IRDA_AbortReceive_IT(IRDA_HandleTypeDef *hirda); - void HAL_IRDA_IRQHandler(IRDA_HandleTypeDef *hirda); void HAL_IRDA_TxCpltCallback(IRDA_HandleTypeDef *hirda); void HAL_IRDA_RxCpltCallback(IRDA_HandleTypeDef *hirda); void HAL_IRDA_TxHalfCpltCallback(IRDA_HandleTypeDef *hirda); void HAL_IRDA_RxHalfCpltCallback(IRDA_HandleTypeDef *hirda); void HAL_IRDA_ErrorCallback(IRDA_HandleTypeDef *hirda); -void HAL_IRDA_AbortCpltCallback(IRDA_HandleTypeDef *hirda); -void HAL_IRDA_AbortTransmitCpltCallback(IRDA_HandleTypeDef *hirda); -void HAL_IRDA_AbortReceiveCpltCallback(IRDA_HandleTypeDef *hirda); -/** - * @} - */ - -/** @addtogroup IRDA_Exported_Functions_Group3 - * @{ - */ -/* Peripheral State functions **************************************************/ -HAL_IRDA_StateTypeDef HAL_IRDA_GetState(IRDA_HandleTypeDef *hirda); -uint32_t HAL_IRDA_GetError(IRDA_HandleTypeDef *hirda); -/** - * @} - */ /** * @} */ -/* Private types -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private constants ---------------------------------------------------------*/ -/** @defgroup IRDA_Private_Constants IRDA Private Constants +/** @addtogroup IRDA_Exported_Functions_Group3 Peripheral State and Errors functions * @{ */ -/** @brief IRDA interruptions flag mask - * - */ -#define IRDA_IT_MASK 0x0000FFFFU - -#define IRDA_CR1_REG_INDEX 1U -#define IRDA_CR2_REG_INDEX 2U -#define IRDA_CR3_REG_INDEX 3U -/** - * @} - */ - -/* Private macros --------------------------------------------------------*/ -/** @defgroup IRDA_Private_Macros IRDA Private Macros - * @{ - */ -#define IS_IRDA_WORD_LENGTH(LENGTH) (((LENGTH) == IRDA_WORDLENGTH_8B) || \ - ((LENGTH) == IRDA_WORDLENGTH_9B)) -#define IS_IRDA_PARITY(PARITY) (((PARITY) == IRDA_PARITY_NONE) || \ - ((PARITY) == IRDA_PARITY_EVEN) || \ - ((PARITY) == IRDA_PARITY_ODD)) -#define IS_IRDA_MODE(MODE) ((((MODE) & 0x0000FFF3U) == 0x00U) && ((MODE) != 0x00000000U)) -#define IS_IRDA_POWERMODE(MODE) (((MODE) == IRDA_POWERMODE_LOWPOWER) || \ - ((MODE) == IRDA_POWERMODE_NORMAL)) -#define IS_IRDA_BAUDRATE(BAUDRATE) ((BAUDRATE) < 115201U) - -#define IRDA_DIV(_PCLK_, _BAUD_) (((_PCLK_)*25U)/(4U*(_BAUD_))) -#define IRDA_DIVMANT(_PCLK_, _BAUD_) (IRDA_DIV((_PCLK_), (_BAUD_))/100U) -#define IRDA_DIVFRAQ(_PCLK_, _BAUD_) (((IRDA_DIV((_PCLK_), (_BAUD_)) - (IRDA_DIVMANT((_PCLK_), (_BAUD_)) * 100U)) * 16U + 50U) / 100U) -/* UART BRR = mantissa + overflow + fraction - = (UART DIVMANT << 4) + (UART DIVFRAQ & 0xF0) + (UART DIVFRAQ & 0x0FU) */ -#define IRDA_BRR(_PCLK_, _BAUD_) (((IRDA_DIVMANT((_PCLK_), (_BAUD_)) << 4U) + \ - (IRDA_DIVFRAQ((_PCLK_), (_BAUD_)) & 0xF0U)) + \ - (IRDA_DIVFRAQ((_PCLK_), (_BAUD_)) & 0x0FU)) +/* Peripheral State and Error functions ***************************************/ +HAL_IRDA_StateTypeDef HAL_IRDA_GetState(IRDA_HandleTypeDef *hirda); +uint32_t HAL_IRDA_GetError(IRDA_HandleTypeDef *hirda); /** * @} */ -/* Private functions ---------------------------------------------------------*/ -/** @defgroup IRDA_Private_Functions IRDA Private Functions - * @{ - */ - /** * @} */ @@ -589,7 +549,7 @@ uint32_t HAL_IRDA_GetError(IRDA_HandleTypeDef *hirda); /** * @} */ - + #ifdef __cplusplus } #endif diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_iwdg.c b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_iwdg.c index debd2aed9b8..1919221a66e 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_iwdg.c +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_iwdg.c @@ -2,73 +2,66 @@ ****************************************************************************** * @file stm32f1xx_hal_iwdg.c * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief IWDG HAL module driver. - * This file provides firmware functions to manage the following + * This file provides firmware functions to manage the following * functionalities of the Independent Watchdog (IWDG) peripheral: - * + Initialization and Start functions + * + Initialization and Configuration functions * + IO operation functions - * - @verbatim - ============================================================================== - ##### IWDG Generic features ##### - ============================================================================== - [..] + * + Peripheral State functions + @verbatim +================================================================================ + ##### IWDG specific features ##### +================================================================================ + [..] (+) The IWDG can be started by either software or hardware (configurable through option byte). - - (+) The IWDG is clocked by Low-Speed clock (LSI) and thus stays active even - if the main clock fails. - - (+) Once the IWDG is started, the LSI is forced ON and both can not be - disabled. The counter starts counting down from the reset value (0xFFF). - When it reaches the end of count value (0x000) a reset signal is - generated (IWDG reset). - - (+) Whenever the key value 0x0000 AAAA is written in the IWDG_KR register, - the IWDG_RLR value is reloaded in the counter and the watchdog reset is - prevented. - + (+) The IWDG is clocked by its own dedicated Low-Speed clock (LSI) and + thus stays active even if the main clock fails. + (+) Once the IWDG is started, the LSI is forced ON and cannot be disabled + (LSI cannot be disabled too), and the counter starts counting down from + the reset value of 0xFFF. When it reaches the end of count value (0x000) + a system reset is generated. + (+) The IWDG counter should be refreshed at regular intervals, otherwise the + watchdog generates an MCU reset when the counter reaches 0. (+) The IWDG is implemented in the VDD voltage domain that is still functional in STOP and STANDBY mode (IWDG reset can wake-up from STANDBY). - IWDGRST flag in RCC_CSR register can be used to inform when an IWDG + (+) IWDGRST flag in RCC_CSR register can be used to inform when an IWDG reset occurs. - (+) Debug mode : When the microcontroller enters debug mode (core halted), - the IWDG counter either continues to work normally or stops, depending - on DBG_IWDG_STOP configuration bit in DBG module, accessible through - __HAL_DBGMCU_FREEZE_IWDG() and __HAL_DBGMCU_UNFREEZE_IWDG() macros - - [..] Min-max timeout value @32KHz (LSI): ~125us / ~32.7s - The IWDG timeout may vary due to LSI frequency dispersion. STM32F1xx - devices provide the capability to measure the LSI frequency (LSI clock - connected internally to TIM5 CH4 input capture). The measured value - can be used to have an IWDG timeout with an acceptable accuracy. + (+) Min-max timeout value at 40KHz (LSI): 0.1us / 26.2s . + The IWDG timeout may vary due to LSI frequency dispersion. STM32F1xx + devices provide the capability to measure the LSI frequency (LSI clock + connected internally to TIM5 CH4 input capture). The measured value + can be used to have an IWDG timeout with an acceptable accuracy. + For more information, please refer to the STM32F1xx Reference manual. + Note: LSI Calibration is only available on: High density, XL-density and Connectivity line devices. ##### How to use this driver ##### ============================================================================== - [..] - (#) Use IWDG using HAL_IWDG_Init() function to : - (++) Enable instance by writing Start keyword in IWDG_KEY register. LSI - clock is forced ON and IWDG counter starts downcounting. - (++) Enable write access to configuration register: IWDG_PR & IWDG_RLR. - (++) Configure the IWDG prescaler and counter reload value. This reload - value will be loaded in the IWDG counter each time the watchdog is - reloaded, then the IWDG will start counting down from this value. - (++) wait for status flags to be reset" - - (#) Then the application program must refresh the IWDG counter at regular + [..] + (+) Use IWDG using HAL_IWDG_Init() function to : + (++) Enable write access to IWDG_PR, IWDG_RLR. + (++) Configure the IWDG prescaler, counter reload value. + This reload value will be loaded in the IWDG counter each time the counter + is reloaded, then the IWDG will start counting down from this value. + (+) Use IWDG using HAL_IWDG_Start() function to : + (++) Reload IWDG counter with value defined in the IWDG_RLR register. + (++) Start the IWDG, when the IWDG is used in software mode (no need + to enable the LSI, it will be enabled by hardware). + (+) Then the application program must refresh the IWDG counter at regular intervals during normal operation to prevent an MCU reset, using - HAL_IWDG_Refresh() function. - + HAL_IWDG_Refresh() function. + *** IWDG HAL driver macros list *** ==================================== [..] - Below the list of most used macros in IWDG HAL driver: + Below the list of most used macros in IWDG HAL driver. + (+) __HAL_IWDG_START: Enable the IWDG peripheral - (+) __HAL_IWDG_RELOAD_COUNTER: Reloads IWDG counter with value defined in - the reload register + (+) __HAL_IWDG_RELOAD_COUNTER: Reloads IWDG counter with value defined in the reload register + (+) __HAL_IWDG_GET_FLAG: Get the selected IWDG's flag status @endverbatim ****************************************************************************** @@ -82,7 +75,7 @@ * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution + * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. @@ -99,7 +92,7 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** - */ + */ /* Includes ------------------------------------------------------------------*/ #include "stm32f1xx_hal.h" @@ -108,21 +101,22 @@ * @{ */ -#ifdef HAL_IWDG_MODULE_ENABLED /** @defgroup IWDG IWDG * @brief IWDG HAL module driver. * @{ */ +#ifdef HAL_IWDG_MODULE_ENABLED + /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ -/** @defgroup IWDG_Private_Defines IWDG Private Defines + +/** @defgroup IWDG_Private_Constants IWDG Private Constants * @{ */ -/* Status register need 5 RC LSI divided by prescaler clock to be updated. With - higher prescaler (256), and according to HSI variation, we need to wait at - least 6 cycles so 48 ms. */ -#define HAL_IWDG_DEFAULT_TIMEOUT 48U + +#define IWDG_DEFAULT_TIMEOUT (uint32_t)1000 + /** * @} */ @@ -130,41 +124,38 @@ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ -/* Exported functions --------------------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ -/** @addtogroup IWDG_Exported_Functions +/** @defgroup IWDG_Exported_Functions IWDG Exported Functions * @{ */ -/** @addtogroup IWDG_Exported_Functions_Group1 - * @brief Initialization and Start functions. - * -@verbatim +/** @defgroup IWDG_Exported_Functions_Group1 Initialization and de-initialization functions + * @brief Initialization and Configuration functions. + * +@verbatim =============================================================================== - ##### Initialization and Start functions ##### + ##### Initialization and de-initialization functions ##### =============================================================================== - [..] This section provides functions allowing to: - (+) Initialize the IWDG according to the specified parameters in the - IWDG_InitTypeDef of associated handle. - (+) Once initialization is performed in HAL_IWDG_Init function, Watchdog - is reloaded in order to exit function with correct time base. - + [..] This section provides functions allowing to: + (+) Initialize the IWDG according to the specified parameters + in the IWDG_InitTypeDef and create the associated handle + (+) Initialize the IWDG MSP + (+) DeInitialize IWDG MSP + @endverbatim * @{ */ /** - * @brief Initialize the IWDG according to the specified parameters in the - * IWDG_InitTypeDef and start watchdog. Before exiting function, - * watchdog is refreshed in order to have correct time base. - * @param hiwdg pointer to a IWDG_HandleTypeDef structure that contains + * @brief Initializes the IWDG according to the specified + * parameters in the IWDG_InitTypeDef and creates the associated handle. + * @param hiwdg: pointer to a IWDG_HandleTypeDef structure that contains * the configuration information for the specified IWDG module. * @retval HAL status */ HAL_StatusTypeDef HAL_IWDG_Init(IWDG_HandleTypeDef *hiwdg) { - uint32_t tickstart; - /* Check the IWDG handle allocation */ if(hiwdg == NULL) { @@ -174,33 +165,147 @@ HAL_StatusTypeDef HAL_IWDG_Init(IWDG_HandleTypeDef *hiwdg) /* Check the parameters */ assert_param(IS_IWDG_ALL_INSTANCE(hiwdg->Instance)); assert_param(IS_IWDG_PRESCALER(hiwdg->Init.Prescaler)); - assert_param(IS_IWDG_RELOAD(hiwdg->Init.Reload)); + assert_param(IS_IWDG_RELOAD(hiwdg->Init.Reload)); + + /* Check pending flag, if previous update not done, return error */ + if((__HAL_IWDG_GET_FLAG(hiwdg, IWDG_FLAG_PVU) != RESET) + &&(__HAL_IWDG_GET_FLAG(hiwdg, IWDG_FLAG_RVU) != RESET)) + { + return HAL_ERROR; + } + + if(hiwdg->State == HAL_IWDG_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + hiwdg->Lock = HAL_UNLOCKED; + + /* Init the low level hardware */ + HAL_IWDG_MspInit(hiwdg); + } + + /* Change IWDG peripheral state */ + hiwdg->State = HAL_IWDG_STATE_BUSY; + + /* Enable write access to IWDG_PR and IWDG_RLR registers */ + IWDG_ENABLE_WRITE_ACCESS(hiwdg); + + /* Write to IWDG registers the IWDG_Prescaler & IWDG_Reload values to work with */ + MODIFY_REG(hiwdg->Instance->PR, IWDG_PR_PR, hiwdg->Init.Prescaler); + MODIFY_REG(hiwdg->Instance->RLR, IWDG_RLR_RL, hiwdg->Init.Reload); + + /* Change IWDG peripheral state */ + hiwdg->State = HAL_IWDG_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Initializes the IWDG MSP. + * @param hiwdg: pointer to a IWDG_HandleTypeDef structure that contains + * the configuration information for the specified IWDG module. + * @retval None + */ +__weak void HAL_IWDG_MspInit(IWDG_HandleTypeDef *hiwdg) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hiwdg); + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_IWDG_MspInit could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup IWDG_Exported_Functions_Group2 IO operation functions + * @brief IO operation functions + * +@verbatim + =============================================================================== + ##### IO operation functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Start the IWDG. + (+) Refresh the IWDG. + +@endverbatim + * @{ + */ + +/** + * @brief Starts the IWDG. + * @param hiwdg: pointer to a IWDG_HandleTypeDef structure that contains + * the configuration information for the specified IWDG module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_IWDG_Start(IWDG_HandleTypeDef *hiwdg) +{ + /* Process Locked */ + __HAL_LOCK(hiwdg); + + /* Change IWDG peripheral state */ + hiwdg->State = HAL_IWDG_STATE_BUSY; - /* Enable IWDG. LSI is turned on automaticaly */ + /* Start the IWDG peripheral */ __HAL_IWDG_START(hiwdg); + + /* Reload IWDG counter with value defined in the RLR register */ + __HAL_IWDG_RELOAD_COUNTER(hiwdg); + + /* Change IWDG peripheral state */ + hiwdg->State = HAL_IWDG_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hiwdg); + + /* Return function status */ + return HAL_OK; +} - /* Enable write access to IWDG_PR and IWDG_RLR registers by writing 0x5555 in KR */ - IWDG_ENABLE_WRITE_ACCESS(hiwdg); +/** + * @brief Refreshes the IWDG. + * @param hiwdg: pointer to a IWDG_HandleTypeDef structure that contains + * the configuration information for the specified IWDG module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_IWDG_Refresh(IWDG_HandleTypeDef *hiwdg) +{ + uint32_t tickstart = 0; - /* Write to IWDG registers the Prescaler & Reload values to work with */ - hiwdg->Instance->PR = hiwdg->Init.Prescaler; - hiwdg->Instance->RLR = hiwdg->Init.Reload; + /* Process Locked */ + __HAL_LOCK(hiwdg); + + /* Change IWDG peripheral state */ + hiwdg->State = HAL_IWDG_STATE_BUSY; - /* Check pending flag, if previous update not done, return timeout */ tickstart = HAL_GetTick(); - /* Wait for register to be updated */ - while(hiwdg->Instance->SR != RESET) + /* Wait until RVU flag is RESET */ + while(__HAL_IWDG_GET_FLAG(hiwdg, IWDG_FLAG_RVU) != RESET) { - if((HAL_GetTick() - tickstart ) > HAL_IWDG_DEFAULT_TIMEOUT) + if((HAL_GetTick() - tickstart ) > IWDG_DEFAULT_TIMEOUT) { + /* Set IWDG state */ + hiwdg->State = HAL_IWDG_STATE_TIMEOUT; + + /* Process unlocked */ + __HAL_UNLOCK(hiwdg); + return HAL_TIMEOUT; } } - + /* Reload IWDG counter with value defined in the reload register */ __HAL_IWDG_RELOAD_COUNTER(hiwdg); - + + /* Change IWDG peripheral state */ + hiwdg->State = HAL_IWDG_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hiwdg); + /* Return function status */ return HAL_OK; } @@ -209,33 +314,30 @@ HAL_StatusTypeDef HAL_IWDG_Init(IWDG_HandleTypeDef *hiwdg) * @} */ -/** @addtogroup IWDG_Exported_Functions_Group2 - * @brief IO operation functions - * -@verbatim +/** @defgroup IWDG_Exported_Functions_Group3 Peripheral State functions + * @brief Peripheral State functions. + * +@verbatim =============================================================================== - ##### IO operation functions ##### - =============================================================================== - [..] This section provides functions allowing to: - (+) Refresh the IWDG. + ##### Peripheral State functions ##### + =============================================================================== + [..] + This subsection permits to get in run-time the status of the peripheral + and the data flow. @endverbatim * @{ */ /** - * @brief Refresh the IWDG. - * @param hiwdg pointer to a IWDG_HandleTypeDef structure that contains + * @brief Returns the IWDG state. + * @param hiwdg: pointer to a IWDG_HandleTypeDef structure that contains * the configuration information for the specified IWDG module. - * @retval HAL status + * @retval HAL state */ -HAL_StatusTypeDef HAL_IWDG_Refresh(IWDG_HandleTypeDef *hiwdg) +HAL_IWDG_StateTypeDef HAL_IWDG_GetState(IWDG_HandleTypeDef *hiwdg) { - /* Reload IWDG counter with value defined in the reload register */ - __HAL_IWDG_RELOAD_COUNTER(hiwdg); - - /* Return function status */ - return HAL_OK; + return hiwdg->State; } /** diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_iwdg.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_iwdg.h index af20632cc2d..4a8c682609b 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_iwdg.h +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_iwdg.h @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_hal_iwdg.h * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief Header file of IWDG HAL module. ****************************************************************************** * @attention @@ -33,7 +33,7 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** - */ + */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F1xx_HAL_IWDG_H @@ -52,35 +52,53 @@ /** @addtogroup IWDG * @{ - */ + */ /* Exported types ------------------------------------------------------------*/ + /** @defgroup IWDG_Exported_Types IWDG Exported Types * @{ */ /** - * @brief IWDG Init structure definition - */ + * @brief IWDG HAL State Structure definition + */ +typedef enum +{ + HAL_IWDG_STATE_RESET = 0x00, /*!< IWDG not yet initialized or disabled */ + HAL_IWDG_STATE_READY = 0x01, /*!< IWDG initialized and ready for use */ + HAL_IWDG_STATE_BUSY = 0x02, /*!< IWDG internal process is ongoing */ + HAL_IWDG_STATE_TIMEOUT = 0x03, /*!< IWDG timeout state */ + HAL_IWDG_STATE_ERROR = 0x04 /*!< IWDG error state */ + +}HAL_IWDG_StateTypeDef; + +/** + * @brief IWDG Init structure definition + */ typedef struct { - uint32_t Prescaler; /*!< Select the prescaler of the IWDG. + uint32_t Prescaler; /*!< Select the prescaler of the IWDG. This parameter can be a value of @ref IWDG_Prescaler */ - - uint32_t Reload; /*!< Specifies the IWDG down-counter reload value. + + uint32_t Reload; /*!< Specifies the IWDG down-counter reload value. This parameter must be a number between Min_Data = 0 and Max_Data = 0x0FFF */ -} IWDG_InitTypeDef; +}IWDG_InitTypeDef; -/** - * @brief IWDG Handle Structure definition - */ +/** + * @brief IWDG Handle Structure definition + */ typedef struct { - IWDG_TypeDef *Instance; /*!< Register base address */ - + IWDG_TypeDef *Instance; /*!< Register base address */ + IWDG_InitTypeDef Init; /*!< IWDG required parameters */ - + + HAL_LockTypeDef Lock; /*!< IWDG Locking object */ + + __IO HAL_IWDG_StateTypeDef State; /*!< IWDG communication state */ + }IWDG_HandleTypeDef; /** @@ -88,149 +106,190 @@ typedef struct */ /* Exported constants --------------------------------------------------------*/ + /** @defgroup IWDG_Exported_Constants IWDG Exported Constants * @{ */ -/** @defgroup IWDG_Prescaler IWDG Prescaler +/** @defgroup IWDG_Registers_BitMask IWDG Registers BitMask + * @brief IWDG registers bit mask * @{ */ -#define IWDG_PRESCALER_4 0x00000000U /*!< IWDG prescaler set to 4 */ -#define IWDG_PRESCALER_8 IWDG_PR_PR_0 /*!< IWDG prescaler set to 8 */ -#define IWDG_PRESCALER_16 IWDG_PR_PR_1 /*!< IWDG prescaler set to 16 */ -#define IWDG_PRESCALER_32 (IWDG_PR_PR_1 | IWDG_PR_PR_0) /*!< IWDG prescaler set to 32 */ -#define IWDG_PRESCALER_64 IWDG_PR_PR_2 /*!< IWDG prescaler set to 64 */ -#define IWDG_PRESCALER_128 (IWDG_PR_PR_2 | IWDG_PR_PR_0) /*!< IWDG prescaler set to 128 */ -#define IWDG_PRESCALER_256 (IWDG_PR_PR_2 | IWDG_PR_PR_1) /*!< IWDG prescaler set to 256 */ +/* --- KR Register ---*/ +/* KR register bit mask */ +#define IWDG_KEY_RELOAD ((uint32_t)0xAAAA) /*!< IWDG Reload Counter Enable */ +#define IWDG_KEY_ENABLE ((uint32_t)0xCCCC) /*!< IWDG Peripheral Enable */ +#define IWDG_KEY_WRITE_ACCESS_ENABLE ((uint32_t)0x5555) /*!< IWDG KR Write Access Enable */ +#define IWDG_KEY_WRITE_ACCESS_DISABLE ((uint32_t)0x0000) /*!< IWDG KR Write Access Disable */ + /** * @} */ +/** @defgroup IWDG_Flag_definition IWDG Flag definition + * @{ + */ +#define IWDG_FLAG_PVU ((uint32_t)IWDG_SR_PVU) /*!< Watchdog counter prescaler value update Flag */ +#define IWDG_FLAG_RVU ((uint32_t)IWDG_SR_RVU) /*!< Watchdog counter reload value update Flag */ + /** * @} */ - -/* Exported macros -----------------------------------------------------------*/ -/** @defgroup IWDG_Exported_Macros IWDG Exported Macros +/** @defgroup IWDG_Prescaler IWDG Prescaler * @{ - */ + */ +#define IWDG_PRESCALER_4 ((uint8_t)0x00) /*!< IWDG prescaler set to 4 */ +#define IWDG_PRESCALER_8 ((uint8_t)(IWDG_PR_PR_0)) /*!< IWDG prescaler set to 8 */ +#define IWDG_PRESCALER_16 ((uint8_t)(IWDG_PR_PR_1)) /*!< IWDG prescaler set to 16 */ +#define IWDG_PRESCALER_32 ((uint8_t)(IWDG_PR_PR_1 | IWDG_PR_PR_0)) /*!< IWDG prescaler set to 32 */ +#define IWDG_PRESCALER_64 ((uint8_t)(IWDG_PR_PR_2)) /*!< IWDG prescaler set to 64 */ +#define IWDG_PRESCALER_128 ((uint8_t)(IWDG_PR_PR_2 | IWDG_PR_PR_0)) /*!< IWDG prescaler set to 128 */ +#define IWDG_PRESCALER_256 ((uint8_t)(IWDG_PR_PR_2 | IWDG_PR_PR_1)) /*!< IWDG prescaler set to 256 */ /** - * @brief Enable the IWDG peripheral. - * @param __HANDLE__ IWDG handle - * @retval None - */ -#define __HAL_IWDG_START(__HANDLE__) WRITE_REG((__HANDLE__)->Instance->KR, IWDG_KEY_ENABLE) + * @} + */ -/** - * @brief Reload IWDG counter with value defined in the reload register - * (write access to IWDG_PR & IWDG_RLR registers disabled). - * @param __HANDLE__ IWDG handle - * @retval None - */ -#define __HAL_IWDG_RELOAD_COUNTER(__HANDLE__) WRITE_REG((__HANDLE__)->Instance->KR, IWDG_KEY_RELOAD) /** * @} */ -/* Exported functions --------------------------------------------------------*/ -/** @defgroup IWDG_Exported_Functions IWDG Exported Functions - * @{ - */ +/* Exported macros -----------------------------------------------------------*/ -/** @defgroup IWDG_Exported_Functions_Group1 Initialization and Start functions +/** @defgroup IWDG_Exported_Macros IWDG Exported Macros * @{ */ -/* Initialization/Start functions ********************************************/ -HAL_StatusTypeDef HAL_IWDG_Init(IWDG_HandleTypeDef *hiwdg); -/** - * @} - */ -/** @defgroup IWDG_Exported_Functions_Group2 IO operation functions - * @{ +/** @brief Reset IWDG handle state + * @param __HANDLE__: IWDG handle. + * @retval None */ -/* I/O operation functions ****************************************************/ -HAL_StatusTypeDef HAL_IWDG_Refresh(IWDG_HandleTypeDef *hiwdg); +#define __HAL_IWDG_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_IWDG_STATE_RESET) + /** - * @} + * @brief Enables the IWDG peripheral. + * @param __HANDLE__: IWDG handle + * @retval None */ +#define __HAL_IWDG_START(__HANDLE__) WRITE_REG((__HANDLE__)->Instance->KR, IWDG_KEY_ENABLE) /** - * @} + * @brief Reloads IWDG counter with value defined in the reload register + * (write access to IWDG_PR and IWDG_RLR registers disabled). + * @param __HANDLE__: IWDG handle + * @retval None */ +#define __HAL_IWDG_RELOAD_COUNTER(__HANDLE__) WRITE_REG((__HANDLE__)->Instance->KR, IWDG_KEY_RELOAD) + -/* Private constants ---------------------------------------------------------*/ -/** @defgroup IWDG_Private_Constants IWDG Private Constants - * @{ - */ /** - * @brief IWDG Key Register BitMask + * @brief Gets the selected IWDG's flag status. + * @param __HANDLE__: IWDG handle + * @param __FLAG__: specifies the flag to check. + * This parameter can be one of the following values: + * @arg IWDG_FLAG_PVU: Watchdog counter reload value update flag + * @arg IWDG_FLAG_RVU: Watchdog counter prescaler value flag + * @retval The new state of __FLAG__ (TRUE or FALSE). */ -#define IWDG_KEY_RELOAD 0x0000AAAAU /*!< IWDG Reload Counter Enable */ -#define IWDG_KEY_ENABLE 0x0000CCCCU /*!< IWDG Peripheral Enable */ -#define IWDG_KEY_WRITE_ACCESS_ENABLE 0x00005555U /*!< IWDG KR Write Access Enable */ -#define IWDG_KEY_WRITE_ACCESS_DISABLE 0x00000000U /*!< IWDG KR Write Access Disable */ +#define __HAL_IWDG_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->SR & (__FLAG__)) == (__FLAG__)) /** * @} - */ + */ + +/* Private macro -------------------------------------------------------------*/ -/* Private macros ------------------------------------------------------------*/ /** @defgroup IWDG_Private_Macros IWDG Private Macros * @{ */ + /** - * @brief Enable write access to IWDG_PR and IWDG_RLR registers. - * @param __HANDLE__ IWDG handle + * @brief Enables write access to IWDG_PR and IWDG_RLR registers. + * @param __HANDLE__: IWDG handle * @retval None */ -#define IWDG_ENABLE_WRITE_ACCESS(__HANDLE__) WRITE_REG((__HANDLE__)->Instance->KR, IWDG_KEY_WRITE_ACCESS_ENABLE) +#define IWDG_ENABLE_WRITE_ACCESS(__HANDLE__) WRITE_REG((__HANDLE__)->Instance->KR, IWDG_KEY_WRITE_ACCESS_ENABLE) /** - * @brief Disable write access to IWDG_PR and IWDG_RLR registers. - * @param __HANDLE__ IWDG handle + * @brief Disables write access to IWDG_PR and IWDG_RLR registers. + * @param __HANDLE__: IWDG handle * @retval None */ #define IWDG_DISABLE_WRITE_ACCESS(__HANDLE__) WRITE_REG((__HANDLE__)->Instance->KR, IWDG_KEY_WRITE_ACCESS_DISABLE) + +#define IS_IWDG_PRESCALER(__PRESCALER__) (((__PRESCALER__) == IWDG_PRESCALER_4) || \ + ((__PRESCALER__) == IWDG_PRESCALER_8) || \ + ((__PRESCALER__) == IWDG_PRESCALER_16) || \ + ((__PRESCALER__) == IWDG_PRESCALER_32) || \ + ((__PRESCALER__) == IWDG_PRESCALER_64) || \ + ((__PRESCALER__) == IWDG_PRESCALER_128)|| \ + ((__PRESCALER__) == IWDG_PRESCALER_256)) + + +#define IS_IWDG_RELOAD(__RELOAD__) ((__RELOAD__) <= 0xFFF) + + /** - * @brief Check IWDG prescaler value. - * @param __PRESCALER__ IWDG prescaler value - * @retval None + * @} */ -#define IS_IWDG_PRESCALER(__PRESCALER__) (((__PRESCALER__) == IWDG_PRESCALER_4) || \ - ((__PRESCALER__) == IWDG_PRESCALER_8) || \ - ((__PRESCALER__) == IWDG_PRESCALER_16) || \ - ((__PRESCALER__) == IWDG_PRESCALER_32) || \ - ((__PRESCALER__) == IWDG_PRESCALER_64) || \ - ((__PRESCALER__) == IWDG_PRESCALER_128)|| \ - ((__PRESCALER__) == IWDG_PRESCALER_256)) -/** - * @brief Check IWDG reload value. - * @param __RELOAD__ IWDG reload value - * @retval None + + +/* Exported functions --------------------------------------------------------*/ + +/** @addtogroup IWDG_Exported_Functions + * @{ */ -#define IS_IWDG_RELOAD(__RELOAD__) ((__RELOAD__) <= IWDG_RLR_RL) + +/** @addtogroup IWDG_Exported_Functions_Group1 + * @{ + */ +/* Initialization/de-initialization functions ********************************/ +HAL_StatusTypeDef HAL_IWDG_Init(IWDG_HandleTypeDef *hiwdg); +void HAL_IWDG_MspInit(IWDG_HandleTypeDef *hiwdg); /** * @} */ + +/** @addtogroup IWDG_Exported_Functions_Group2 + * @{ + */ +/* I/O operation functions ****************************************************/ +HAL_StatusTypeDef HAL_IWDG_Start(IWDG_HandleTypeDef *hiwdg); +HAL_StatusTypeDef HAL_IWDG_Refresh(IWDG_HandleTypeDef *hiwdg); /** * @} */ + +/** @addtogroup IWDG_Exported_Functions_Group3 + * @{ + */ +/* Peripheral State functions ************************************************/ +HAL_IWDG_StateTypeDef HAL_IWDG_GetState(IWDG_HandleTypeDef *hiwdg); /** * @} - */ + */ +/** + * @} + */ + +/** + * @} + */ +/** + * @} + */ + #ifdef __cplusplus } #endif diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_mmc.c b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_mmc.c deleted file mode 100644 index 61001b49195..00000000000 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_mmc.c +++ /dev/null @@ -1,2598 +0,0 @@ -/** - ****************************************************************************** - * @file stm32f1xx_hal_mmc.c - * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 - * @brief MMC card HAL module driver. - * This file provides firmware functions to manage the following - * functionalities of the Secure Digital (MMC) peripheral: - * + Initialization and de-initialization functions - * + IO operation functions - * + Peripheral Control functions - * + MMC card Control functions - * - @verbatim - ============================================================================== - ##### How to use this driver ##### - ============================================================================== - [..] - This driver implements a high level communication layer for read and write from/to - this memory. The needed STM32 hardware resources (SDMMC and GPIO) are performed by - the user in HAL_MMC_MspInit() function (MSP layer). - Basically, the MSP layer configuration should be the same as we provide in the - examples. - You can easily tailor this configuration according to hardware resources. - - [..] - This driver is a generic layered driver for SDMMC memories which uses the HAL - SDMMC driver functions to interface with MMC and eMMC cards devices. - It is used as follows: - - (#)Initialize the SDMMC low level resources by implement the HAL_MMC_MspInit() API: - (##) Enable the SDMMC interface clock using __HAL_RCC_SDMMC_CLK_ENABLE(); - (##) SDMMC pins configuration for MMC card - (+++) Enable the clock for the SDMMC GPIOs using the functions __HAL_RCC_GPIOx_CLK_ENABLE(); - (+++) Configure these SDMMC pins as alternate function pull-up using HAL_GPIO_Init() - and according to your pin assignment; - (##) DMA Configuration if you need to use DMA process (HAL_MMC_ReadBlocks_DMA() - and HAL_MMC_WriteBlocks_DMA() APIs). - (+++) Enable the DMAx interface clock using __HAL_RCC_DMAx_CLK_ENABLE(); - (+++) Configure the DMA using the function HAL_DMA_Init() with predeclared and filled. - (##) NVIC configuration if you need to use interrupt process when using DMA transfer. - (+++) Configure the SDMMC and DMA interrupt priorities using functions - HAL_NVIC_SetPriority(); DMA priority is superior to SDMMC's priority - (+++) Enable the NVIC DMA and SDMMC IRQs using function HAL_NVIC_EnableIRQ() - (+++) SDMMC interrupts are managed using the macros __HAL_MMC_ENABLE_IT() - and __HAL_MMC_DISABLE_IT() inside the communication process. - (+++) SDMMC interrupts pending bits are managed using the macros __HAL_MMC_GET_IT() - and __HAL_MMC_CLEAR_IT() - (##) NVIC configuration if you need to use interrupt process (HAL_MMC_ReadBlocks_IT() - and HAL_MMC_WriteBlocks_IT() APIs). - (+++) Configure the SDMMC interrupt priorities using function - HAL_NVIC_SetPriority(); - (+++) Enable the NVIC SDMMC IRQs using function HAL_NVIC_EnableIRQ() - (+++) SDMMC interrupts are managed using the macros __HAL_MMC_ENABLE_IT() - and __HAL_MMC_DISABLE_IT() inside the communication process. - (+++) SDMMC interrupts pending bits are managed using the macros __HAL_MMC_GET_IT() - and __HAL_MMC_CLEAR_IT() - (#) At this stage, you can perform MMC read/write/erase operations after MMC card initialization - - - *** MMC Card Initialization and configuration *** - ================================================ - [..] - To initialize the MMC Card, use the HAL_MMC_Init() function. It Initializes - SDMMC IP (STM32 side) and the MMC Card, and put it into StandBy State (Ready for data transfer). - This function provide the following operations: - - (#) Initialize the SDMMC peripheral interface with defaullt configuration. - The initialization process is done at 400KHz. You can change or adapt - this frequency by adjusting the "ClockDiv" field. - The MMC Card frequency (SDMMC_CK) is computed as follows: - - SDMMC_CK = SDMMCCLK / (ClockDiv + 2) - - In initialization mode and according to the MMC Card standard, - make sure that the SDMMC_CK frequency doesn't exceed 400KHz. - - This phase of initialization is done through SDMMC_Init() and - SDMMC_PowerState_ON() SDMMC low level APIs. - - (#) Initialize the MMC card. The API used is HAL_MMC_InitCard(). - This phase allows the card initialization and identification - and check the MMC Card type (Standard Capacity or High Capacity) - The initialization flow is compatible with MMC standard. - - This API (HAL_MMC_InitCard()) could be used also to reinitialize the card in case - of plug-off plug-in. - - (#) Configure the MMC Card Data transfer frequency. By Default, the card transfer - frequency is set to 24MHz. You can change or adapt this frequency by adjusting - the "ClockDiv" field. - In transfer mode and according to the MMC Card standard, make sure that the - SDMMC_CK frequency doesn't exceed 25MHz and 50MHz in High-speed mode switch. - To be able to use a frequency higher than 24MHz, you should use the SDMMC - peripheral in bypass mode. Refer to the corresponding reference manual - for more details. - - (#) Select the corresponding MMC Card according to the address read with the step 2. - - (#) Configure the MMC Card in wide bus mode: 4-bits data. - - *** MMC Card Read operation *** - ============================== - [..] - (+) You can read from MMC card in polling mode by using function HAL_MMC_ReadBlocks(). - This function allows the read of 512 bytes blocks. - You can choose either one block read operation or multiple block read operation - by adjusting the "NumberOfBlocks" parameter. - After this, you have to ensure that the transfer is done correctly. The check is done - through HAL_MMC_GetCardState() function for MMC card state. - - (+) You can read from MMC card in DMA mode by using function HAL_MMC_ReadBlocks_DMA(). - This function allows the read of 512 bytes blocks. - You can choose either one block read operation or multiple block read operation - by adjusting the "NumberOfBlocks" parameter. - After this, you have to ensure that the transfer is done correctly. The check is done - through HAL_MMC_GetCardState() function for MMC card state. - You could also check the DMA transfer process through the MMC Rx interrupt event. - - (+) You can read from MMC card in Interrupt mode by using function HAL_MMC_ReadBlocks_IT(). - This function allows the read of 512 bytes blocks. - You can choose either one block read operation or multiple block read operation - by adjusting the "NumberOfBlocks" parameter. - After this, you have to ensure that the transfer is done correctly. The check is done - through HAL_MMC_GetCardState() function for MMC card state. - You could also check the IT transfer process through the MMC Rx interrupt event. - - *** MMC Card Write operation *** - =============================== - [..] - (+) You can write to MMC card in polling mode by using function HAL_MMC_WriteBlocks(). - This function allows the read of 512 bytes blocks. - You can choose either one block read operation or multiple block read operation - by adjusting the "NumberOfBlocks" parameter. - After this, you have to ensure that the transfer is done correctly. The check is done - through HAL_MMC_GetCardState() function for MMC card state. - - (+) You can write to MMC card in DMA mode by using function HAL_MMC_WriteBlocks_DMA(). - This function allows the read of 512 bytes blocks. - You can choose either one block read operation or multiple block read operation - by adjusting the "NumberOfBlocks" parameter. - After this, you have to ensure that the transfer is done correctly. The check is done - through HAL_MMC_GetCardState() function for MMC card state. - You could also check the DMA transfer process through the MMC Tx interrupt event. - - (+) You can write to MMC card in Interrupt mode by using function HAL_MMC_WriteBlocks_IT(). - This function allows the read of 512 bytes blocks. - You can choose either one block read operation or multiple block read operation - by adjusting the "NumberOfBlocks" parameter. - After this, you have to ensure that the transfer is done correctly. The check is done - through HAL_MMC_GetCardState() function for MMC card state. - You could also check the IT transfer process through the MMC Tx interrupt event. - - *** MMC card status *** - ====================== - [..] - (+) The MMC Status contains status bits that are related to the MMC Memory - Card proprietary features. To get MMC card status use the HAL_MMC_GetCardStatus(). - - *** MMC card information *** - =========================== - [..] - (+) To get MMC card information, you can use the function HAL_MMC_GetCardInfo(). - It returns useful information about the MMC card such as block size, card type, - block number ... - - *** MMC card CSD register *** - ============================ - [..] - (+) The HAL_MMC_GetCardCSD() API allows to get the parameters of the CSD register. - Some of the CSD parameters are useful for card initialization and identification. - - *** MMC card CID register *** - ============================ - [..] - (+) The HAL_MMC_GetCardCID() API allows to get the parameters of the CID register. - Some of the CID parameters are useful for card initialization and identification. - - *** MMC HAL driver macros list *** - ================================== - [..] - Below the list of most used macros in MMC HAL driver. - - (+) __HAL_MMC_ENABLE : Enable the MMC device - (+) __HAL_MMC_DISABLE : Disable the MMC device - (+) __HAL_MMC_DMA_ENABLE: Enable the SDMMC DMA transfer - (+) __HAL_MMC_DMA_DISABLE: Disable the SDMMC DMA transfer - (+) __HAL_MMC_ENABLE_IT: Enable the MMC device interrupt - (+) __HAL_MMC_DISABLE_IT: Disable the MMC device interrupt - (+) __HAL_MMC_GET_FLAG:Check whether the specified MMC flag is set or not - (+) __HAL_MMC_CLEAR_FLAG: Clear the MMC's pending flags - - [..] - (@) You can refer to the MMC HAL driver header file for more useful macros - - @endverbatim - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2017 STMicroelectronics

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ - -/* Includes ------------------------------------------------------------------*/ -#include "stm32f1xx_hal.h" - -/** @addtogroup STM32F1xx_HAL_Driver - * @{ - */ - -/** @addtogroup MMC - * @{ - */ - -#ifdef HAL_MMC_MODULE_ENABLED - -#if defined(STM32F103xE) || defined(STM32F103xG) - -/* Private typedef -----------------------------------------------------------*/ -/* Private define ------------------------------------------------------------*/ -/** @addtogroup MMC_Private_Defines - * @{ - */ - -/** - * @} - */ - -/* Private macro -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private function prototypes -----------------------------------------------*/ -/* Private functions ---------------------------------------------------------*/ -/** @defgroup MMC_Private_Functions MMC Private Functions - * @{ - */ -static uint32_t MMC_InitCard(MMC_HandleTypeDef *hmmc); -static uint32_t MMC_PowerON(MMC_HandleTypeDef *hmmc); -static uint32_t MMC_SendStatus(MMC_HandleTypeDef *hmmc, uint32_t *pCardStatus); -static HAL_StatusTypeDef MMC_PowerOFF(MMC_HandleTypeDef *hmmc); -static HAL_StatusTypeDef MMC_Write_IT(MMC_HandleTypeDef *hmmc); -static HAL_StatusTypeDef MMC_Read_IT(MMC_HandleTypeDef *hmmc); -static void MMC_DMATransmitCplt(DMA_HandleTypeDef *hdma); -static void MMC_DMAReceiveCplt(DMA_HandleTypeDef *hdma); -static void MMC_DMAError(DMA_HandleTypeDef *hdma); -static void MMC_DMATxAbort(DMA_HandleTypeDef *hdma); -static void MMC_DMARxAbort(DMA_HandleTypeDef *hdma); -/** - * @} - */ - -/* Exported functions --------------------------------------------------------*/ -/** @addtogroup MMC_Exported_Functions - * @{ - */ - -/** @addtogroup MMC_Exported_Functions_Group1 - * @brief Initialization and de-initialization functions - * -@verbatim - ============================================================================== - ##### Initialization and de-initialization functions ##### - ============================================================================== - [..] - This section provides functions allowing to initialize/de-initialize the MMC - card device to be ready for use. - -@endverbatim - * @{ - */ - -/** - * @brief Initializes the MMC according to the specified parameters in the - MMC_HandleTypeDef and create the associated handle. - * @param hmmc: Pointer to the MMC handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MMC_Init(MMC_HandleTypeDef *hmmc) -{ - /* Check the MMC handle allocation */ - if(hmmc == NULL) - { - return HAL_ERROR; - } - - /* Check the parameters */ - assert_param(IS_SDIO_ALL_INSTANCE(hmmc->Instance)); - assert_param(IS_SDIO_CLOCK_EDGE(hmmc->Init.ClockEdge)); - assert_param(IS_SDIO_CLOCK_BYPASS(hmmc->Init.ClockBypass)); - assert_param(IS_SDIO_CLOCK_POWER_SAVE(hmmc->Init.ClockPowerSave)); - assert_param(IS_SDIO_BUS_WIDE(hmmc->Init.BusWide)); - assert_param(IS_SDIO_HARDWARE_FLOW_CONTROL(hmmc->Init.HardwareFlowControl)); - assert_param(IS_SDIO_CLKDIV(hmmc->Init.ClockDiv)); - - if(hmmc->State == HAL_MMC_STATE_RESET) - { - /* Allocate lock resource and initialize it */ - hmmc->Lock = HAL_UNLOCKED; - /* Init the low level hardware : GPIO, CLOCK, CORTEX...etc */ - HAL_MMC_MspInit(hmmc); - } - - hmmc->State = HAL_MMC_STATE_BUSY; - - /* Initialize the Card parameters */ - HAL_MMC_InitCard(hmmc); - - /* Initialize the error code */ - hmmc->ErrorCode = HAL_DMA_ERROR_NONE; - - /* Initialize the MMC operation */ - hmmc->Context = MMC_CONTEXT_NONE; - - /* Initialize the MMC state */ - hmmc->State = HAL_MMC_STATE_READY; - - return HAL_OK; -} - -/** - * @brief Initializes the MMC Card. - * @param hmmc: Pointer to MMC handle - * @note This function initializes the MMC card. It could be used when a card - re-initialization is needed. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MMC_InitCard(MMC_HandleTypeDef *hmmc) -{ - uint32_t errorstate = HAL_MMC_ERROR_NONE; - MMC_InitTypeDef Init; - - /* Default SDMMC peripheral configuration for MMC card initialization */ - Init.ClockEdge = SDIO_CLOCK_EDGE_RISING; - Init.ClockBypass = SDIO_CLOCK_BYPASS_DISABLE; - Init.ClockPowerSave = SDIO_CLOCK_POWER_SAVE_DISABLE; - Init.BusWide = SDIO_BUS_WIDE_1B; - Init.HardwareFlowControl = SDIO_HARDWARE_FLOW_CONTROL_DISABLE; - Init.ClockDiv = SDIO_INIT_CLK_DIV; - - /* Initialize SDMMC peripheral interface with default configuration */ - SDIO_Init(hmmc->Instance, Init); - - /* Disable SDMMC Clock */ - __HAL_MMC_DISABLE(hmmc); - - /* Set Power State to ON */ - SDIO_PowerState_ON(hmmc->Instance); - - /* Enable SDMMC Clock */ - __HAL_MMC_ENABLE(hmmc); - - /* Required power up waiting time before starting the SD initialization - sequence */ - HAL_Delay(2U); - - /* Identify card operating voltage */ - errorstate = MMC_PowerON(hmmc); - if(errorstate != HAL_MMC_ERROR_NONE) - { - hmmc->State = HAL_MMC_STATE_READY; - hmmc->ErrorCode |= errorstate; - return HAL_ERROR; - } - - /* Card initialization */ - errorstate = MMC_InitCard(hmmc); - if(errorstate != HAL_MMC_ERROR_NONE) - { - hmmc->State = HAL_MMC_STATE_READY; - hmmc->ErrorCode |= errorstate; - return HAL_ERROR; - } - - return HAL_OK; -} - -/** - * @brief De-Initializes the MMC card. - * @param hmmc: Pointer to MMC handle - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MMC_DeInit(MMC_HandleTypeDef *hmmc) -{ - /* Check the MMC handle allocation */ - if(hmmc == NULL) - { - return HAL_ERROR; - } - - /* Check the parameters */ - assert_param(IS_SDIO_ALL_INSTANCE(hmmc->Instance)); - - hmmc->State = HAL_MMC_STATE_BUSY; - - /* Set SD power state to off */ - MMC_PowerOFF(hmmc); - - /* De-Initialize the MSP layer */ - HAL_MMC_MspDeInit(hmmc); - - hmmc->ErrorCode = HAL_MMC_ERROR_NONE; - hmmc->State = HAL_MMC_STATE_RESET; - - return HAL_OK; -} - - -/** - * @brief Initializes the MMC MSP. - * @param hmmc: Pointer to MMC handle - * @retval None - */ -__weak void HAL_MMC_MspInit(MMC_HandleTypeDef *hmmc) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hmmc); - - /* NOTE : This function Should not be modified, when the callback is needed, - the HAL_MMC_MspInit could be implemented in the user file - */ -} - -/** - * @brief De-Initialize MMC MSP. - * @param hmmc: Pointer to MMC handle - * @retval None - */ -__weak void HAL_MMC_MspDeInit(MMC_HandleTypeDef *hmmc) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hmmc); - - /* NOTE : This function Should not be modified, when the callback is needed, - the HAL_MMC_MspDeInit could be implemented in the user file - */ -} - -/** - * @} - */ - -/** @addtogroup MMC_Exported_Functions_Group2 - * @brief Data transfer functions - * -@verbatim - ============================================================================== - ##### IO operation functions ##### - ============================================================================== - [..] - This subsection provides a set of functions allowing to manage the data - transfer from/to MMC card. - -@endverbatim - * @{ - */ - -/** - * @brief Reads block(s) from a specified address in a card. The Data transfer - * is managed by polling mode. - * @note This API should be followed by a check on the card state through - * HAL_MMC_GetCardState(). - * @param hmmc: Pointer to MMC handle - * @param pData: pointer to the buffer that will contain the received data - * @param BlockAdd: Block Address from where data is to be read - * @param NumberOfBlocks: Number of MMC blocks to read - * @param Timeout: Specify timeout value - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MMC_ReadBlocks(MMC_HandleTypeDef *hmmc, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks, uint32_t Timeout) -{ - SDIO_DataInitTypeDef config; - uint32_t errorstate = HAL_MMC_ERROR_NONE; - uint32_t tickstart = HAL_GetTick(); - uint32_t count = 0U, *tempbuff = (uint32_t *)pData; - - if(NULL == pData) - { - hmmc->ErrorCode |= HAL_MMC_ERROR_PARAM; - return HAL_ERROR; - } - - if(hmmc->State == HAL_MMC_STATE_READY) - { - hmmc->ErrorCode = HAL_DMA_ERROR_NONE; - - if((BlockAdd + NumberOfBlocks) > (hmmc->MmcCard.LogBlockNbr)) - { - hmmc->ErrorCode |= HAL_MMC_ERROR_ADDR_OUT_OF_RANGE; - return HAL_ERROR; - } - - hmmc->State = HAL_MMC_STATE_BUSY; - - /* Initialize data control register */ - hmmc->Instance->DCTRL = 0U; - - /* Check the Card capacity in term of Logical number of blocks */ - if ((hmmc->MmcCard.LogBlockNbr) < CAPACITY) - { - BlockAdd *= 512U; - } - - /* Set Block Size for Card */ - errorstate = SDMMC_CmdBlockLength(hmmc->Instance, BLOCKSIZE); - if(errorstate != HAL_MMC_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - - /* Configure the MMC DPSM (Data Path State Machine) */ - config.DataTimeOut = SDMMC_DATATIMEOUT; - config.DataLength = NumberOfBlocks * BLOCKSIZE; - config.DataBlockSize = SDIO_DATABLOCK_SIZE_512B; - config.TransferDir = SDIO_TRANSFER_DIR_TO_SDIO; - config.TransferMode = SDIO_TRANSFER_MODE_BLOCK; - config.DPSM = SDIO_DPSM_ENABLE; - SDIO_ConfigData(hmmc->Instance, &config); - - /* Read block(s) in polling mode */ - if(NumberOfBlocks > 1U) - { - hmmc->Context = MMC_CONTEXT_READ_MULTIPLE_BLOCK; - - /* Read Multi Block command */ - errorstate = SDMMC_CmdReadMultiBlock(hmmc->Instance, BlockAdd); - } - else - { - hmmc->Context = MMC_CONTEXT_READ_SINGLE_BLOCK; - - /* Read Single Block command */ - errorstate = SDMMC_CmdReadSingleBlock(hmmc->Instance, BlockAdd); - } - if(errorstate != HAL_MMC_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - - /* Poll on SDMMC flags */ -#ifdef SDIO_STA_STBITERR - while(!__HAL_MMC_GET_FLAG(hmmc, SDIO_FLAG_RXOVERR | SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DTIMEOUT | SDIO_FLAG_DATAEND | SDIO_STA_STBITERR)) -#else /* SDIO_STA_STBITERR not defined */ - while(!__HAL_MMC_GET_FLAG(hmmc, SDIO_FLAG_RXOVERR | SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DTIMEOUT | SDIO_FLAG_DATAEND)) -#endif /* SDIO_STA_STBITERR */ - { - if(__HAL_MMC_GET_FLAG(hmmc, SDIO_FLAG_RXFIFOHF)) - { - /* Read data from SDMMC Rx FIFO */ - for(count = 0U; count < 8U; count++) - { - *(tempbuff + count) = SDIO_ReadFIFO(hmmc->Instance); - } - tempbuff += 8U; - } - - if((Timeout == 0U)||((HAL_GetTick()-tickstart) >= Timeout)) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); - hmmc->ErrorCode |= HAL_MMC_ERROR_TIMEOUT; - hmmc->State= HAL_MMC_STATE_READY; - return HAL_TIMEOUT; - } - } - - /* Send stop transmission command in case of multiblock read */ - if(__HAL_MMC_GET_FLAG(hmmc, SDIO_FLAG_DATAEND) && (NumberOfBlocks > 1U)) - { - /* Send stop transmission command */ - errorstate = SDMMC_CmdStopTransfer(hmmc->Instance); - if(errorstate != HAL_MMC_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - } - - /* Get error state */ - if(__HAL_MMC_GET_FLAG(hmmc, SDIO_FLAG_DTIMEOUT)) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); - hmmc->ErrorCode |= HAL_MMC_ERROR_DATA_TIMEOUT; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - else if(__HAL_MMC_GET_FLAG(hmmc, SDIO_FLAG_DCRCFAIL)) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); - hmmc->ErrorCode |= HAL_MMC_ERROR_DATA_CRC_FAIL; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - else if(__HAL_MMC_GET_FLAG(hmmc, SDIO_FLAG_RXOVERR)) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); - hmmc->ErrorCode |= HAL_MMC_ERROR_RX_OVERRUN; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - - /* Empty FIFO if there is still any data */ - while ((__HAL_MMC_GET_FLAG(hmmc, SDIO_FLAG_RXDAVL))) - { - *tempbuff = SDIO_ReadFIFO(hmmc->Instance); - tempbuff++; - - if((Timeout == 0U)||((HAL_GetTick()-tickstart) >= Timeout)) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); - hmmc->ErrorCode |= HAL_MMC_ERROR_TIMEOUT; - hmmc->State= HAL_MMC_STATE_READY; - return HAL_ERROR; - } - } - - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); - - hmmc->State = HAL_MMC_STATE_READY; - - return HAL_OK; - } - else - { - hmmc->ErrorCode |= HAL_MMC_ERROR_BUSY; - return HAL_ERROR; - } -} - -/** - * @brief Allows to write block(s) to a specified address in a card. The Data - * transfer is managed by polling mode. - * @note This API should be followed by a check on the card state through - * HAL_MMC_GetCardState(). - * @param hmmc: Pointer to MMC handle - * @param pData: pointer to the buffer that will contain the data to transmit - * @param BlockAdd: Block Address where data will be written - * @param NumberOfBlocks: Number of MMC blocks to write - * @param Timeout: Specify timeout value - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MMC_WriteBlocks(MMC_HandleTypeDef *hmmc, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks, uint32_t Timeout) -{ - SDIO_DataInitTypeDef config; - uint32_t errorstate = HAL_MMC_ERROR_NONE; - uint32_t tickstart = HAL_GetTick(); - uint32_t count = 0U; - uint32_t *tempbuff = (uint32_t *)pData; - - if(NULL == pData) - { - hmmc->ErrorCode |= HAL_MMC_ERROR_PARAM; - return HAL_ERROR; - } - - if(hmmc->State == HAL_MMC_STATE_READY) - { - hmmc->ErrorCode = HAL_DMA_ERROR_NONE; - - if((BlockAdd + NumberOfBlocks) > (hmmc->MmcCard.LogBlockNbr)) - { - hmmc->ErrorCode |= HAL_MMC_ERROR_ADDR_OUT_OF_RANGE; - return HAL_ERROR; - } - - hmmc->State = HAL_MMC_STATE_BUSY; - - /* Initialize data control register */ - hmmc->Instance->DCTRL = 0U; - - /* Check the Card capacity in term of Logical number of blocks */ - if ((hmmc->MmcCard.LogBlockNbr) < CAPACITY) - { - BlockAdd *= 512U; - } - - /* Set Block Size for Card */ - errorstate = SDMMC_CmdBlockLength(hmmc->Instance, BLOCKSIZE); - if(errorstate != HAL_MMC_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - - /* Write Blocks in Polling mode */ - if(NumberOfBlocks > 1U) - { - hmmc->Context = MMC_CONTEXT_WRITE_MULTIPLE_BLOCK; - - /* Write Multi Block command */ - errorstate = SDMMC_CmdWriteMultiBlock(hmmc->Instance, BlockAdd); - } - else - { - hmmc->Context = MMC_CONTEXT_WRITE_SINGLE_BLOCK; - - /* Write Single Block command */ - errorstate = SDMMC_CmdWriteSingleBlock(hmmc->Instance, BlockAdd); - } - if(errorstate != HAL_MMC_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - - /* Configure the MMC DPSM (Data Path State Machine) */ - config.DataTimeOut = SDMMC_DATATIMEOUT; - config.DataLength = NumberOfBlocks * BLOCKSIZE; - config.DataBlockSize = SDIO_DATABLOCK_SIZE_512B; - config.TransferDir = SDIO_TRANSFER_DIR_TO_CARD; - config.TransferMode = SDIO_TRANSFER_MODE_BLOCK; - config.DPSM = SDIO_DPSM_ENABLE; - SDIO_ConfigData(hmmc->Instance, &config); - - /* Write block(s) in polling mode */ -#ifdef SDIO_STA_STBITERR - while(!__HAL_MMC_GET_FLAG(hmmc, SDIO_FLAG_TXUNDERR | SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DTIMEOUT | SDIO_FLAG_DATAEND | SDIO_FLAG_STBITERR)) -#else /* SDIO_STA_STBITERR not defined */ - while(!__HAL_MMC_GET_FLAG(hmmc, SDIO_FLAG_TXUNDERR | SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DTIMEOUT | SDIO_FLAG_DATAEND)) -#endif /* SDIO_STA_STBITERR */ - { - if(__HAL_MMC_GET_FLAG(hmmc, SDIO_FLAG_TXFIFOHE)) - { - /* Write data to SDIO Tx FIFO */ - for(count = 0U; count < 8U; count++) - { - SDIO_WriteFIFO(hmmc->Instance, (tempbuff + count)); - } - tempbuff += 8U; - } - - if((Timeout == 0U)||((HAL_GetTick()-tickstart) >= Timeout)) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_TIMEOUT; - } - } - - /* Send stop transmission command in case of multiblock write */ - if(__HAL_MMC_GET_FLAG(hmmc, SDIO_FLAG_DATAEND) && (NumberOfBlocks > 1U)) - { - /* Send stop transmission command */ - errorstate = SDMMC_CmdStopTransfer(hmmc->Instance); - if(errorstate != HAL_MMC_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - } - - /* Get error state */ - if(__HAL_MMC_GET_FLAG(hmmc, SDIO_FLAG_DTIMEOUT)) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); - hmmc->ErrorCode |= HAL_MMC_ERROR_DATA_TIMEOUT; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - else if(__HAL_MMC_GET_FLAG(hmmc, SDIO_FLAG_DCRCFAIL)) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); - hmmc->ErrorCode |= HAL_MMC_ERROR_DATA_CRC_FAIL; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - else if(__HAL_MMC_GET_FLAG(hmmc, SDIO_FLAG_TXUNDERR)) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); - hmmc->ErrorCode |= HAL_MMC_ERROR_TX_UNDERRUN; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); - - hmmc->State = HAL_MMC_STATE_READY; - - return HAL_OK; - } - else - { - hmmc->ErrorCode |= HAL_MMC_ERROR_BUSY; - return HAL_ERROR; - } -} - -/** - * @brief Reads block(s) from a specified address in a card. The Data transfer - * is managed in interrupt mode. - * @note This API should be followed by a check on the card state through - * HAL_MMC_GetCardState(). - * @note You could also check the IT transfer process through the MMC Rx - * interrupt event. - * @param hmmc: Pointer to MMC handle - * @param pData: Pointer to the buffer that will contain the received data - * @param BlockAdd: Block Address from where data is to be read - * @param NumberOfBlocks: Number of blocks to read. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MMC_ReadBlocks_IT(MMC_HandleTypeDef *hmmc, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks) -{ - SDIO_DataInitTypeDef config; - uint32_t errorstate = HAL_MMC_ERROR_NONE; - - if(NULL == pData) - { - hmmc->ErrorCode |= HAL_MMC_ERROR_PARAM; - return HAL_ERROR; - } - - if(hmmc->State == HAL_MMC_STATE_READY) - { - hmmc->ErrorCode = HAL_DMA_ERROR_NONE; - - if((BlockAdd + NumberOfBlocks) > (hmmc->MmcCard.LogBlockNbr)) - { - hmmc->ErrorCode |= HAL_MMC_ERROR_ADDR_OUT_OF_RANGE; - return HAL_ERROR; - } - - hmmc->State = HAL_MMC_STATE_BUSY; - - /* Initialize data control register */ - hmmc->Instance->DCTRL = 0U; - - hmmc->pRxBuffPtr = (uint32_t *)pData; - hmmc->RxXferSize = BLOCKSIZE * NumberOfBlocks; - - __HAL_MMC_ENABLE_IT(hmmc, (SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_RXOVERR | SDIO_IT_DATAEND | SDIO_FLAG_RXFIFOHF)); - - /* Check the Card capacity in term of Logical number of blocks */ - if ((hmmc->MmcCard.LogBlockNbr) < CAPACITY) - { - BlockAdd *= 512U; - } - - /* Configure the MMC DPSM (Data Path State Machine) */ - config.DataTimeOut = SDMMC_DATATIMEOUT; - config.DataLength = BLOCKSIZE * NumberOfBlocks; - config.DataBlockSize = SDIO_DATABLOCK_SIZE_512B; - config.TransferDir = SDIO_TRANSFER_DIR_TO_SDIO; - config.TransferMode = SDIO_TRANSFER_MODE_BLOCK; - config.DPSM = SDIO_DPSM_ENABLE; - SDIO_ConfigData(hmmc->Instance, &config); - - /* Set Block Size for Card */ - errorstate = SDMMC_CmdBlockLength(hmmc->Instance, BLOCKSIZE); - if(errorstate != HAL_MMC_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - - /* Read Blocks in IT mode */ - if(NumberOfBlocks > 1U) - { - hmmc->Context = (MMC_CONTEXT_READ_MULTIPLE_BLOCK | MMC_CONTEXT_IT); - - /* Read Multi Block command */ - errorstate = SDMMC_CmdReadMultiBlock(hmmc->Instance, BlockAdd); - } - else - { - hmmc->Context = (MMC_CONTEXT_READ_SINGLE_BLOCK | MMC_CONTEXT_IT); - - /* Read Single Block command */ - errorstate = SDMMC_CmdReadSingleBlock(hmmc->Instance, BlockAdd); - } - if(errorstate != HAL_MMC_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Writes block(s) to a specified address in a card. The Data transfer - * is managed in interrupt mode. - * @note This API should be followed by a check on the card state through - * HAL_MMC_GetCardState(). - * @note You could also check the IT transfer process through the MMC Tx - * interrupt event. - * @param hmmc: Pointer to MMC handle - * @param pData: Pointer to the buffer that will contain the data to transmit - * @param BlockAdd: Block Address where data will be written - * @param NumberOfBlocks: Number of blocks to write - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MMC_WriteBlocks_IT(MMC_HandleTypeDef *hmmc, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks) -{ - SDIO_DataInitTypeDef config; - uint32_t errorstate = HAL_MMC_ERROR_NONE; - - if(NULL == pData) - { - hmmc->ErrorCode |= HAL_MMC_ERROR_PARAM; - return HAL_ERROR; - } - - if(hmmc->State == HAL_MMC_STATE_READY) - { - hmmc->ErrorCode = HAL_DMA_ERROR_NONE; - - if((BlockAdd + NumberOfBlocks) > (hmmc->MmcCard.LogBlockNbr)) - { - hmmc->ErrorCode |= HAL_MMC_ERROR_ADDR_OUT_OF_RANGE; - return HAL_ERROR; - } - - hmmc->State = HAL_MMC_STATE_BUSY; - - /* Initialize data control register */ - hmmc->Instance->DCTRL = 0U; - - hmmc->pTxBuffPtr = (uint32_t *)pData; - hmmc->TxXferSize = BLOCKSIZE * NumberOfBlocks; - - /* Enable transfer interrupts */ - __HAL_MMC_ENABLE_IT(hmmc, (SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_TXUNDERR | SDIO_IT_DATAEND | SDIO_FLAG_TXFIFOHE)); - - /* Check the Card capacity in term of Logical number of blocks */ - if ((hmmc->MmcCard.LogBlockNbr) < CAPACITY) - { - BlockAdd *= 512U; - } - - /* Set Block Size for Card */ - errorstate = SDMMC_CmdBlockLength(hmmc->Instance, BLOCKSIZE); - if(errorstate != HAL_MMC_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - - /* Write Blocks in Polling mode */ - if(NumberOfBlocks > 1U) - { - hmmc->Context = (MMC_CONTEXT_WRITE_MULTIPLE_BLOCK| MMC_CONTEXT_IT); - - /* Write Multi Block command */ - errorstate = SDMMC_CmdWriteMultiBlock(hmmc->Instance, BlockAdd); - } - else - { - hmmc->Context = (MMC_CONTEXT_WRITE_SINGLE_BLOCK | MMC_CONTEXT_IT); - - /* Write Single Block command */ - errorstate = SDMMC_CmdWriteSingleBlock(hmmc->Instance, BlockAdd); - } - if(errorstate != HAL_MMC_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - - /* Configure the MMC DPSM (Data Path State Machine) */ - config.DataTimeOut = SDMMC_DATATIMEOUT; - config.DataLength = BLOCKSIZE * NumberOfBlocks; - config.DataBlockSize = SDIO_DATABLOCK_SIZE_512B; - config.TransferDir = SDIO_TRANSFER_DIR_TO_CARD; - config.TransferMode = SDIO_TRANSFER_MODE_BLOCK; - config.DPSM = SDIO_DPSM_ENABLE; - SDIO_ConfigData(hmmc->Instance, &config); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Reads block(s) from a specified address in a card. The Data transfer - * is managed by DMA mode. - * @note This API should be followed by a check on the card state through - * HAL_MMC_GetCardState(). - * @note You could also check the DMA transfer process through the MMC Rx - * interrupt event. - * @param hmmc: Pointer MMC handle - * @param pData: Pointer to the buffer that will contain the received data - * @param BlockAdd: Block Address from where data is to be read - * @param NumberOfBlocks: Number of blocks to read. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MMC_ReadBlocks_DMA(MMC_HandleTypeDef *hmmc, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks) -{ - SDIO_DataInitTypeDef config; - uint32_t errorstate = HAL_MMC_ERROR_NONE; - - if(NULL == pData) - { - hmmc->ErrorCode |= HAL_MMC_ERROR_PARAM; - return HAL_ERROR; - } - - if(hmmc->State == HAL_MMC_STATE_READY) - { - hmmc->ErrorCode = HAL_DMA_ERROR_NONE; - - if((BlockAdd + NumberOfBlocks) > (hmmc->MmcCard.LogBlockNbr)) - { - hmmc->ErrorCode |= HAL_MMC_ERROR_ADDR_OUT_OF_RANGE; - return HAL_ERROR; - } - - hmmc->State = HAL_MMC_STATE_BUSY; - - /* Initialize data control register */ - hmmc->Instance->DCTRL = 0U; - -#ifdef SDIO_STA_STBITER - __HAL_MMC_ENABLE_IT(hmmc, (SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_RXOVERR | SDIO_IT_DATAEND | SDIO_IT_STBITERR)); -#else /* SDIO_STA_STBITERR not defined */ - __HAL_MMC_ENABLE_IT(hmmc, (SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_RXOVERR | SDIO_IT_DATAEND)); -#endif /* SDIO_STA_STBITERR */ - - /* Set the DMA transfer complete callback */ - hmmc->hdmarx->XferCpltCallback = MMC_DMAReceiveCplt; - - /* Set the DMA error callback */ - hmmc->hdmarx->XferErrorCallback = MMC_DMAError; - - /* Set the DMA Abort callback */ - hmmc->hdmarx->XferAbortCallback = NULL; - - /* Enable the DMA Channel */ - HAL_DMA_Start_IT(hmmc->hdmarx, (uint32_t)&hmmc->Instance->FIFO, (uint32_t)pData, (uint32_t)(BLOCKSIZE * NumberOfBlocks)/4); - - /* Enable MMC DMA transfer */ - __HAL_MMC_DMA_ENABLE(hmmc); - - /* Check the Card capacity in term of Logical number of blocks */ - if ((hmmc->MmcCard.LogBlockNbr) < CAPACITY) - { - BlockAdd *= 512U; - } - - /* Configure the MMC DPSM (Data Path State Machine) */ - config.DataTimeOut = SDMMC_DATATIMEOUT; - config.DataLength = BLOCKSIZE * NumberOfBlocks; - config.DataBlockSize = SDIO_DATABLOCK_SIZE_512B; - config.TransferDir = SDIO_TRANSFER_DIR_TO_SDIO; - config.TransferMode = SDIO_TRANSFER_MODE_BLOCK; - config.DPSM = SDIO_DPSM_ENABLE; - SDIO_ConfigData(hmmc->Instance, &config); - - /* Set Block Size for Card */ - errorstate = SDMMC_CmdBlockLength(hmmc->Instance, BLOCKSIZE); - if(errorstate != HAL_MMC_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - - /* Read Blocks in DMA mode */ - if(NumberOfBlocks > 1U) - { - hmmc->Context = (MMC_CONTEXT_READ_MULTIPLE_BLOCK | MMC_CONTEXT_DMA); - - /* Read Multi Block command */ - errorstate = SDMMC_CmdReadMultiBlock(hmmc->Instance, BlockAdd); - } - else - { - hmmc->Context = (MMC_CONTEXT_READ_SINGLE_BLOCK | MMC_CONTEXT_DMA); - - /* Read Single Block command */ - errorstate = SDMMC_CmdReadSingleBlock(hmmc->Instance, BlockAdd); - } - if(errorstate != HAL_MMC_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Writes block(s) to a specified address in a card. The Data transfer - * is managed by DMA mode. - * @note This API should be followed by a check on the card state through - * HAL_MMC_GetCardState(). - * @note You could also check the DMA transfer process through the MMC Tx - * interrupt event. - * @param hmmc: Pointer to MMC handle - * @param pData: Pointer to the buffer that will contain the data to transmit - * @param BlockAdd: Block Address where data will be written - * @param NumberOfBlocks: Number of blocks to write - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MMC_WriteBlocks_DMA(MMC_HandleTypeDef *hmmc, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks) -{ - SDIO_DataInitTypeDef config; - uint32_t errorstate = HAL_MMC_ERROR_NONE; - - if(NULL == pData) - { - hmmc->ErrorCode |= HAL_MMC_ERROR_PARAM; - return HAL_ERROR; - } - - if(hmmc->State == HAL_MMC_STATE_READY) - { - hmmc->ErrorCode = HAL_DMA_ERROR_NONE; - - if((BlockAdd + NumberOfBlocks) > (hmmc->MmcCard.LogBlockNbr)) - { - hmmc->ErrorCode |= HAL_MMC_ERROR_ADDR_OUT_OF_RANGE; - return HAL_ERROR; - } - - hmmc->State = HAL_MMC_STATE_BUSY; - - /* Initialize data control register */ - hmmc->Instance->DCTRL = 0U; - - /* Enable MMC Error interrupts */ -#ifdef SDIO_STA_STBITER - __HAL_MMC_ENABLE_IT(hmmc, (SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_TXUNDERR | SDIO_IT_STBITERR)); -#else /* SDIO_STA_STBITERR not defined */ - __HAL_MMC_ENABLE_IT(hmmc, (SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_TXUNDERR)); -#endif /* SDIO_STA_STBITERR */ - - /* Set the DMA transfer complete callback */ - hmmc->hdmatx->XferCpltCallback = MMC_DMATransmitCplt; - - /* Set the DMA error callback */ - hmmc->hdmatx->XferErrorCallback = MMC_DMAError; - - /* Set the DMA Abort callback */ - hmmc->hdmatx->XferAbortCallback = NULL; - - /* Check the Card capacity in term of Logical number of blocks */ - if ((hmmc->MmcCard.LogBlockNbr) < CAPACITY) - { - BlockAdd *= 512U; - } - - /* Set Block Size for Card */ - errorstate = SDMMC_CmdBlockLength(hmmc->Instance, BLOCKSIZE); - if(errorstate != HAL_MMC_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - - /* Write Blocks in Polling mode */ - if(NumberOfBlocks > 1U) - { - hmmc->Context = (MMC_CONTEXT_WRITE_MULTIPLE_BLOCK | MMC_CONTEXT_DMA); - - /* Write Multi Block command */ - errorstate = SDMMC_CmdWriteMultiBlock(hmmc->Instance, BlockAdd); - } - else - { - hmmc->Context = (MMC_CONTEXT_WRITE_SINGLE_BLOCK | MMC_CONTEXT_DMA); - - /* Write Single Block command */ - errorstate = SDMMC_CmdWriteSingleBlock(hmmc->Instance, BlockAdd); - } - if(errorstate != HAL_MMC_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - - /* Enable SDIO DMA transfer */ - __HAL_MMC_DMA_ENABLE(hmmc); - - /* Enable the DMA Channel */ - HAL_DMA_Start_IT(hmmc->hdmatx, (uint32_t)pData, (uint32_t)&hmmc->Instance->FIFO, (uint32_t)(BLOCKSIZE * NumberOfBlocks)/4); - - /* Configure the MMC DPSM (Data Path State Machine) */ - config.DataTimeOut = SDMMC_DATATIMEOUT; - config.DataLength = BLOCKSIZE * NumberOfBlocks; - config.DataBlockSize = SDIO_DATABLOCK_SIZE_512B; - config.TransferDir = SDIO_TRANSFER_DIR_TO_CARD; - config.TransferMode = SDIO_TRANSFER_MODE_BLOCK; - config.DPSM = SDIO_DPSM_ENABLE; - SDIO_ConfigData(hmmc->Instance, &config); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Erases the specified memory area of the given MMC card. - * @note This API should be followed by a check on the card state through - * HAL_MMC_GetCardState(). - * @param hmmc: Pointer to MMC handle - * @param BlockStartAdd: Start Block address - * @param BlockEndAdd: End Block address - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MMC_Erase(MMC_HandleTypeDef *hmmc, uint32_t BlockStartAdd, uint32_t BlockEndAdd) -{ - uint32_t errorstate = HAL_MMC_ERROR_NONE; - - if(hmmc->State == HAL_MMC_STATE_READY) - { - hmmc->ErrorCode = HAL_DMA_ERROR_NONE; - - if(BlockEndAdd < BlockStartAdd) - { - hmmc->ErrorCode |= HAL_MMC_ERROR_PARAM; - return HAL_ERROR; - } - - if(BlockEndAdd > (hmmc->MmcCard.LogBlockNbr)) - { - hmmc->ErrorCode |= HAL_MMC_ERROR_ADDR_OUT_OF_RANGE; - return HAL_ERROR; - } - - hmmc->State = HAL_MMC_STATE_BUSY; - - /* Check if the card command class supports erase command */ - if((hmmc->MmcCard.Class) & SDIO_CCCC_ERASE == 0U) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); - hmmc->ErrorCode |= HAL_MMC_ERROR_REQUEST_NOT_APPLICABLE; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - - if((SDIO_GetResponse(hmmc->Instance, SDIO_RESP1) & SDMMC_CARD_LOCKED) == SDMMC_CARD_LOCKED) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); - hmmc->ErrorCode |= HAL_MMC_ERROR_LOCK_UNLOCK_FAILED; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - - /* Check the Card capacity in term of Logical number of blocks */ - if ((hmmc->MmcCard.LogBlockNbr) < CAPACITY) - { - BlockStartAdd *= 512U; - BlockEndAdd *= 512U; - } - - /* Send CMD35 MMC_ERASE_GRP_START with argument as addr */ - errorstate = SDMMC_CmdEraseStartAdd(hmmc->Instance, BlockStartAdd); - if(errorstate != HAL_MMC_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - - /* Send CMD36 MMC_ERASE_GRP_END with argument as addr */ - errorstate = SDMMC_CmdEraseEndAdd(hmmc->Instance, BlockEndAdd); - if(errorstate != HAL_MMC_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - - /* Send CMD38 ERASE */ - errorstate = SDMMC_CmdErase(hmmc->Instance); - if(errorstate != HAL_MMC_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); - hmmc->ErrorCode |= errorstate; - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - - hmmc->State = HAL_MMC_STATE_READY; - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief This function handles MMC card interrupt request. - * @param hmmc: Pointer to MMC handle - * @retval None - */ -void HAL_MMC_IRQHandler(MMC_HandleTypeDef *hmmc) -{ - uint32_t errorstate = HAL_MMC_ERROR_NONE; - - /* Check for SDIO interrupt flags */ - if(__HAL_MMC_GET_FLAG(hmmc, SDIO_IT_DATAEND) != RESET) - { - __HAL_MMC_CLEAR_FLAG(hmmc, SDIO_FLAG_DATAEND); - -#ifdef SDIO_STA_STBITERR - __HAL_MMC_DISABLE_IT(hmmc, SDIO_IT_DATAEND | SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT|\ - SDIO_IT_TXUNDERR | SDIO_IT_RXOVERR | SDIO_IT_STBITERR); -#else /* SDIO_STA_STBITERR not defined */ - __HAL_MMC_DISABLE_IT(hmmc, SDIO_IT_DATAEND | SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT|\ - SDIO_IT_TXUNDERR | SDIO_IT_RXOVERR); -#endif - - if((hmmc->Context & MMC_CONTEXT_IT) != RESET) - { - if(((hmmc->Context & MMC_CONTEXT_READ_MULTIPLE_BLOCK) != RESET) || ((hmmc->Context & MMC_CONTEXT_WRITE_MULTIPLE_BLOCK) != RESET)) - { - errorstate = SDMMC_CmdStopTransfer(hmmc->Instance); - if(errorstate != HAL_MMC_ERROR_NONE) - { - hmmc->ErrorCode |= errorstate; - HAL_MMC_ErrorCallback(hmmc); - } - } - - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); - - hmmc->State = HAL_MMC_STATE_READY; - if(((hmmc->Context & MMC_CONTEXT_READ_SINGLE_BLOCK) != RESET) || ((hmmc->Context & MMC_CONTEXT_READ_MULTIPLE_BLOCK) != RESET)) - { - HAL_MMC_RxCpltCallback(hmmc); - } - else - { - HAL_MMC_TxCpltCallback(hmmc); - } - } - else if((hmmc->Context & MMC_CONTEXT_DMA) != RESET) - { - if((hmmc->Context & MMC_CONTEXT_WRITE_MULTIPLE_BLOCK) != RESET) - { - errorstate = SDMMC_CmdStopTransfer(hmmc->Instance); - if(errorstate != HAL_MMC_ERROR_NONE) - { - hmmc->ErrorCode |= errorstate; - HAL_MMC_ErrorCallback(hmmc); - } - } - if(((hmmc->Context & MMC_CONTEXT_READ_SINGLE_BLOCK) == RESET) && ((hmmc->Context & MMC_CONTEXT_READ_MULTIPLE_BLOCK) == RESET)) - { - /* Disable the DMA transfer for transmit request by setting the DMAEN bit - in the MMC DCTRL register */ - hmmc->Instance->DCTRL &= (uint32_t)~((uint32_t)SDIO_DCTRL_DMAEN); - - hmmc->State = HAL_MMC_STATE_READY; - - HAL_MMC_TxCpltCallback(hmmc); - } - } - } - - else if(__HAL_MMC_GET_FLAG(hmmc, SDIO_IT_TXFIFOHE) != RESET) - { - __HAL_MMC_CLEAR_FLAG(hmmc, SDIO_FLAG_TXFIFOHE); - - MMC_Write_IT(hmmc); - } - - else if(__HAL_MMC_GET_FLAG(hmmc, SDIO_IT_RXFIFOHF) != RESET) - { - __HAL_MMC_CLEAR_FLAG(hmmc, SDIO_FLAG_RXFIFOHF); - - MMC_Read_IT(hmmc); - } - -#ifdef SDIO_STA_STBITERR - else if(__HAL_MMC_GET_FLAG(hmmc, SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_RXOVERR | SDIO_IT_TXUNDERR | SDIO_IT_STBITERR) != RESET) - { - /* Set Error code */ - if(__HAL_MMC_GET_FLAG(hmmc, SDIO_IT_DCRCFAIL) != RESET) - { - hmmc->ErrorCode |= HAL_MMC_ERROR_DATA_CRC_FAIL; - } - if(__HAL_MMC_GET_FLAG(hmmc, SDIO_IT_DTIMEOUT) != RESET) - { - hmmc->ErrorCode |= HAL_MMC_ERROR_DATA_TIMEOUT; - } - if(__HAL_MMC_GET_FLAG(hmmc, SDIO_IT_RXOVERR) != RESET) - { - hmmc->ErrorCode |= HAL_MMC_ERROR_RX_OVERRUN; - } - if(__HAL_MMC_GET_FLAG(hmmc, SDIO_IT_TXUNDERR) != RESET) - { - hmmc->ErrorCode |= HAL_MMC_ERROR_TX_UNDERRUN; - } - if(__HAL_MMC_GET_FLAG(hmmc, SDIO_IT_STBITERR) != RESET) - { - hmmc->ErrorCode |= HAL_MMC_ERROR_DATA_TIMEOUT; - } - - /* Clear All flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS | SDIO_FLAG_STBITERR); - - /* Disable all interrupts */ - __HAL_MMC_DISABLE_IT(hmmc, SDIO_IT_DATAEND | SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT|\ - SDIO_IT_TXUNDERR| SDIO_IT_RXOVERR |SDIO_IT_STBITERR); - - if((hmmc->Context & MMC_CONTEXT_DMA) != RESET) - { - /* Abort the MMC DMA Streams */ - if(hmmc->hdmatx != NULL) - { - /* Set the DMA Tx abort callback */ - hmmc->hdmatx->XferAbortCallback = MMC_DMATxAbort; - /* Abort DMA in IT mode */ - if(HAL_DMA_Abort_IT(hmmc->hdmatx) != HAL_OK) - { - MMC_DMATxAbort(hmmc->hdmatx); - } - } - else if(hmmc->hdmarx != NULL) - { - /* Set the DMA Rx abort callback */ - hmmc->hdmarx->XferAbortCallback = MMC_DMARxAbort; - /* Abort DMA in IT mode */ - if(HAL_DMA_Abort_IT(hmmc->hdmarx) != HAL_OK) - { - MMC_DMARxAbort(hmmc->hdmarx); - } - } - else - { - hmmc->ErrorCode = HAL_MMC_ERROR_NONE; - hmmc->State = HAL_MMC_STATE_READY; - HAL_MMC_AbortCallback(hmmc); - } - } - else if((hmmc->Context & MMC_CONTEXT_IT) != RESET) - { - /* Set the MMC state to ready to be able to start again the process */ - hmmc->State = HAL_MMC_STATE_READY; - HAL_MMC_ErrorCallback(hmmc); - } - } -#else /* SDIO_STA_STBITERR not defined */ - else if(__HAL_MMC_GET_FLAG(hmmc, SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_RXOVERR | SDIO_IT_TXUNDERR) != RESET) - { - /* Set Error code */ - if(__HAL_MMC_GET_FLAG(hmmc, SDIO_IT_DCRCFAIL) != RESET) - { - hmmc->ErrorCode |= HAL_MMC_ERROR_DATA_CRC_FAIL; - } - if(__HAL_MMC_GET_FLAG(hmmc, SDIO_IT_DTIMEOUT) != RESET) - { - hmmc->ErrorCode |= HAL_MMC_ERROR_DATA_TIMEOUT; - } - if(__HAL_MMC_GET_FLAG(hmmc, SDIO_IT_RXOVERR) != RESET) - { - hmmc->ErrorCode |= HAL_MMC_ERROR_RX_OVERRUN; - } - if(__HAL_MMC_GET_FLAG(hmmc, SDIO_IT_TXUNDERR) != RESET) - { - hmmc->ErrorCode |= HAL_MMC_ERROR_TX_UNDERRUN; - } - - /* Clear All flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); - - /* Disable all interrupts */ - __HAL_MMC_DISABLE_IT(hmmc, SDIO_IT_DATAEND | SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT|\ - SDIO_IT_TXUNDERR| SDIO_IT_RXOVERR); - - if((hmmc->Context & MMC_CONTEXT_DMA) != RESET) - { - /* Abort the MMC DMA Streams */ - if(hmmc->hdmatx != NULL) - { - /* Set the DMA Tx abort callback */ - hmmc->hdmatx->XferAbortCallback = MMC_DMATxAbort; - /* Abort DMA in IT mode */ - if(HAL_DMA_Abort_IT(hmmc->hdmatx) != HAL_OK) - { - MMC_DMATxAbort(hmmc->hdmatx); - } - } - else if(hmmc->hdmarx != NULL) - { - /* Set the DMA Rx abort callback */ - hmmc->hdmarx->XferAbortCallback = MMC_DMARxAbort; - /* Abort DMA in IT mode */ - if(HAL_DMA_Abort_IT(hmmc->hdmarx) != HAL_OK) - { - MMC_DMARxAbort(hmmc->hdmarx); - } - } - else - { - hmmc->ErrorCode = HAL_MMC_ERROR_NONE; - hmmc->State = HAL_MMC_STATE_READY; - HAL_MMC_AbortCallback(hmmc); - } - } - else if((hmmc->Context & MMC_CONTEXT_IT) != RESET) - { - /* Set the MMC state to ready to be able to start again the process */ - hmmc->State = HAL_MMC_STATE_READY; - HAL_MMC_ErrorCallback(hmmc); - } - } -#endif /* SDIO_STA_STBITERR */ -} - -/** - * @brief return the MMC state - * @param hmmc: Pointer to mmc handle - * @retval HAL state - */ -HAL_MMC_StateTypeDef HAL_MMC_GetState(MMC_HandleTypeDef *hmmc) -{ - return hmmc->State; -} - -/** -* @brief Return the MMC error code -* @param hmmc : Pointer to a MMC_HandleTypeDef structure that contains - * the configuration information. -* @retval MMC Error Code -*/ -uint32_t HAL_MMC_GetError(MMC_HandleTypeDef *hmmc) -{ - return hmmc->ErrorCode; -} - -/** - * @brief Tx Transfer completed callbacks - * @param hmmc: Pointer to MMC handle - * @retval None - */ - __weak void HAL_MMC_TxCpltCallback(MMC_HandleTypeDef *hmmc) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hmmc); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_MMC_TxCpltCallback can be implemented in the user file - */ -} - -/** - * @brief Rx Transfer completed callbacks - * @param hmmc: Pointer MMC handle - * @retval None - */ -__weak void HAL_MMC_RxCpltCallback(MMC_HandleTypeDef *hmmc) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hmmc); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_MMC_RxCpltCallback can be implemented in the user file - */ -} - -/** - * @brief MMC error callbacks - * @param hmmc: Pointer MMC handle - * @retval None - */ -__weak void HAL_MMC_ErrorCallback(MMC_HandleTypeDef *hmmc) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hmmc); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_MMC_ErrorCallback can be implemented in the user file - */ -} - -/** - * @brief MMC Abort callbacks - * @param hmmc: Pointer MMC handle - * @retval None - */ -__weak void HAL_MMC_AbortCallback(MMC_HandleTypeDef *hmmc) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hmmc); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_MMC_ErrorCallback can be implemented in the user file - */ -} - - -/** - * @} - */ - -/** @addtogroup MMC_Exported_Functions_Group3 - * @brief management functions - * -@verbatim - ============================================================================== - ##### Peripheral Control functions ##### - ============================================================================== - [..] - This subsection provides a set of functions allowing to control the MMC card - operations and get the related information - -@endverbatim - * @{ - */ - -/** - * @brief Returns information the information of the card which are stored on - * the CID register. - * @param hmmc: Pointer to MMC handle - * @param pCID: Pointer to a HAL_MMC_CIDTypedef structure that - * contains all CID register parameters - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MMC_GetCardCID(MMC_HandleTypeDef *hmmc, HAL_MMC_CardCIDTypeDef *pCID) -{ - uint32_t tmp = 0U; - - /* Byte 0 */ - tmp = (uint8_t)((hmmc->CID[0U] & 0xFF000000U) >> 24U); - pCID->ManufacturerID = tmp; - - /* Byte 1 */ - tmp = (uint8_t)((hmmc->CID[0U] & 0x00FF0000U) >> 16U); - pCID->OEM_AppliID = tmp << 8U; - - /* Byte 2 */ - tmp = (uint8_t)((hmmc->CID[0U] & 0x000000FF00U) >> 8U); - pCID->OEM_AppliID |= tmp; - - /* Byte 3 */ - tmp = (uint8_t)(hmmc->CID[0U] & 0x000000FFU); - pCID->ProdName1 = tmp << 24U; - - /* Byte 4 */ - tmp = (uint8_t)((hmmc->CID[1U] & 0xFF000000U) >> 24U); - pCID->ProdName1 |= tmp << 16U; - - /* Byte 5 */ - tmp = (uint8_t)((hmmc->CID[1U] & 0x00FF0000U) >> 16U); - pCID->ProdName1 |= tmp << 8U; - - /* Byte 6 */ - tmp = (uint8_t)((hmmc->CID[1U] & 0x0000FF00U) >> 8U); - pCID->ProdName1 |= tmp; - - /* Byte 7 */ - tmp = (uint8_t)(hmmc->CID[1U] & 0x000000FFU); - pCID->ProdName2 = tmp; - - /* Byte 8 */ - tmp = (uint8_t)((hmmc->CID[2U] & 0xFF000000U) >> 24U); - pCID->ProdRev = tmp; - - /* Byte 9 */ - tmp = (uint8_t)((hmmc->CID[2U] & 0x00FF0000U) >> 16U); - pCID->ProdSN = tmp << 24U; - - /* Byte 10 */ - tmp = (uint8_t)((hmmc->CID[2U] & 0x0000FF00U) >> 8U); - pCID->ProdSN |= tmp << 16U; - - /* Byte 11 */ - tmp = (uint8_t)(hmmc->CID[2U] & 0x000000FFU); - pCID->ProdSN |= tmp << 8U; - - /* Byte 12 */ - tmp = (uint8_t)((hmmc->CID[3U] & 0xFF000000U) >> 24U); - pCID->ProdSN |= tmp; - - /* Byte 13 */ - tmp = (uint8_t)((hmmc->CID[3U] & 0x00FF0000U) >> 16U); - pCID->Reserved1 |= (tmp & 0xF0U) >> 4U; - pCID->ManufactDate = (tmp & 0x0FU) << 8U; - - /* Byte 14 */ - tmp = (uint8_t)((hmmc->CID[3U] & 0x0000FF00U) >> 8U); - pCID->ManufactDate |= tmp; - - /* Byte 15 */ - tmp = (uint8_t)(hmmc->CID[3U] & 0x000000FFU); - pCID->CID_CRC = (tmp & 0xFEU) >> 1U; - pCID->Reserved2 = 1U; - - return HAL_OK; -} - -/** - * @brief Returns information the information of the card which are stored on - * the CSD register. - * @param hmmc: Pointer to MMC handle - * @param pCSD: Pointer to a HAL_MMC_CardInfoTypeDef structure that - * contains all CSD register parameters - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MMC_GetCardCSD(MMC_HandleTypeDef *hmmc, HAL_MMC_CardCSDTypeDef *pCSD) -{ - uint32_t tmp = 0U; - - /* Byte 0 */ - tmp = (hmmc->CSD[0U] & 0xFF000000U) >> 24U; - pCSD->CSDStruct = (uint8_t)((tmp & 0xC0U) >> 6U); - pCSD->SysSpecVersion = (uint8_t)((tmp & 0x3CU) >> 2U); - pCSD->Reserved1 = tmp & 0x03U; - - /* Byte 1 */ - tmp = (hmmc->CSD[0U] & 0x00FF0000U) >> 16U; - pCSD->TAAC = (uint8_t)tmp; - - /* Byte 2 */ - tmp = (hmmc->CSD[0U] & 0x0000FF00U) >> 8U; - pCSD->NSAC = (uint8_t)tmp; - - /* Byte 3 */ - tmp = hmmc->CSD[0U] & 0x000000FFU; - pCSD->MaxBusClkFrec = (uint8_t)tmp; - - /* Byte 4 */ - tmp = (hmmc->CSD[1U] & 0xFF000000U) >> 24U; - pCSD->CardComdClasses = (uint16_t)(tmp << 4U); - - /* Byte 5 */ - tmp = (hmmc->CSD[1U] & 0x00FF0000U) >> 16U; - pCSD->CardComdClasses |= (uint16_t)((tmp & 0xF0U) >> 4U); - pCSD->RdBlockLen = (uint8_t)(tmp & 0x0FU); - - /* Byte 6 */ - tmp = (hmmc->CSD[1U] & 0x0000FF00U) >> 8U; - pCSD->PartBlockRead = (uint8_t)((tmp & 0x80U) >> 7U); - pCSD->WrBlockMisalign = (uint8_t)((tmp & 0x40U) >> 6U); - pCSD->RdBlockMisalign = (uint8_t)((tmp & 0x20U) >> 5U); - pCSD->DSRImpl = (uint8_t)((tmp & 0x10U) >> 4U); - pCSD->Reserved2 = 0; /*!< Reserved */ - - pCSD->DeviceSize = (tmp & 0x03U) << 10U; - - /* Byte 7 */ - tmp = (uint8_t)(hmmc->CSD[1U] & 0x000000FFU); - pCSD->DeviceSize |= (tmp) << 2U; - - /* Byte 8 */ - tmp = (uint8_t)((hmmc->CSD[2U] & 0xFF000000U) >> 24U); - pCSD->DeviceSize |= (tmp & 0xC0U) >> 6U; - - pCSD->MaxRdCurrentVDDMin = (tmp & 0x38U) >> 3U; - pCSD->MaxRdCurrentVDDMax = (tmp & 0x07U); - - /* Byte 9 */ - tmp = (uint8_t)((hmmc->CSD[2U] & 0x00FF0000U) >> 16U); - pCSD->MaxWrCurrentVDDMin = (tmp & 0xE0U) >> 5U; - pCSD->MaxWrCurrentVDDMax = (tmp & 0x1CU) >> 2U; - pCSD->DeviceSizeMul = (tmp & 0x03U) << 1U; - /* Byte 10 */ - tmp = (uint8_t)((hmmc->CSD[2] & 0x0000FF00U) >> 8U); - pCSD->DeviceSizeMul |= (tmp & 0x80U) >> 7U; - - hmmc->MmcCard.BlockNbr = (pCSD->DeviceSize + 1U) ; - hmmc->MmcCard.BlockNbr *= (1U << (pCSD->DeviceSizeMul + 2U)); - hmmc->MmcCard.BlockSize = 1U << (pCSD->RdBlockLen); - - hmmc->MmcCard.LogBlockNbr = (hmmc->MmcCard.BlockNbr) * ((hmmc->MmcCard.BlockSize) / 512U); - hmmc->MmcCard.LogBlockSize = 512U; - - pCSD->EraseGrSize = (tmp & 0x40U) >> 6U; - pCSD->EraseGrMul = (tmp & 0x3FU) << 1U; - - /* Byte 11 */ - tmp = (uint8_t)(hmmc->CSD[2U] & 0x000000FFU); - pCSD->EraseGrMul |= (tmp & 0x80U) >> 7U; - pCSD->WrProtectGrSize = (tmp & 0x7FU); - - /* Byte 12 */ - tmp = (uint8_t)((hmmc->CSD[3U] & 0xFF000000U) >> 24U); - pCSD->WrProtectGrEnable = (tmp & 0x80U) >> 7U; - pCSD->ManDeflECC = (tmp & 0x60U) >> 5U; - pCSD->WrSpeedFact = (tmp & 0x1CU) >> 2U; - pCSD->MaxWrBlockLen = (tmp & 0x03U) << 2U; - - /* Byte 13 */ - tmp = (uint8_t)((hmmc->CSD[3U] & 0x00FF0000U) >> 16U); - pCSD->MaxWrBlockLen |= (tmp & 0xC0U) >> 6U; - pCSD->WriteBlockPaPartial = (tmp & 0x20U) >> 5U; - pCSD->Reserved3 = 0U; - pCSD->ContentProtectAppli = (tmp & 0x01U); - - /* Byte 14 */ - tmp = (uint8_t)((hmmc->CSD[3U] & 0x0000FF00U) >> 8U); - pCSD->FileFormatGrouop = (tmp & 0x80U) >> 7U; - pCSD->CopyFlag = (tmp & 0x40U) >> 6U; - pCSD->PermWrProtect = (tmp & 0x20U) >> 5U; - pCSD->TempWrProtect = (tmp & 0x10U) >> 4U; - pCSD->FileFormat = (tmp & 0x0CU) >> 2U; - pCSD->ECC = (tmp & 0x03U); - - /* Byte 15 */ - tmp = (uint8_t)(hmmc->CSD[3U] & 0x000000FFU); - pCSD->CSD_CRC = (tmp & 0xFEU) >> 1U; - pCSD->Reserved4 = 1U; - - return HAL_OK; -} - -/** - * @brief Gets the MMC card info. - * @param hmmc: Pointer to MMC handle - * @param pCardInfo: Pointer to the HAL_MMC_CardInfoTypeDef structure that - * will contain the MMC card status information - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MMC_GetCardInfo(MMC_HandleTypeDef *hmmc, HAL_MMC_CardInfoTypeDef *pCardInfo) -{ - pCardInfo->CardType = (uint32_t)(hmmc->MmcCard.CardType); - pCardInfo->Class = (uint32_t)(hmmc->MmcCard.Class); - pCardInfo->RelCardAdd = (uint32_t)(hmmc->MmcCard.RelCardAdd); - pCardInfo->BlockNbr = (uint32_t)(hmmc->MmcCard.BlockNbr); - pCardInfo->BlockSize = (uint32_t)(hmmc->MmcCard.BlockSize); - pCardInfo->LogBlockNbr = (uint32_t)(hmmc->MmcCard.LogBlockNbr); - pCardInfo->LogBlockSize = (uint32_t)(hmmc->MmcCard.LogBlockSize); - - return HAL_OK; -} - -/** - * @brief Enables wide bus operation for the requested card if supported by - * card. - * @param hmmc: Pointer to MMC handle - * @param WideMode: Specifies the MMC card wide bus mode - * This parameter can be one of the following values: - * @arg SDIO_BUS_WIDE_8B: 8-bit data transfer - * @arg SDIO_BUS_WIDE_4B: 4-bit data transfer - * @arg SDIO_BUS_WIDE_1B: 1-bit data transfer - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MMC_ConfigWideBusOperation(MMC_HandleTypeDef *hmmc, uint32_t WideMode) -{ - __IO uint32_t count = 0U; - SDIO_InitTypeDef Init; - uint32_t errorstate = HAL_MMC_ERROR_NONE; - uint32_t response = 0U, busy = 0U; - - /* Check the parameters */ - assert_param(IS_SDIO_BUS_WIDE(WideMode)); - - /* Chnage Satte */ - hmmc->State = HAL_MMC_STATE_BUSY; - - /* Update Clock for Bus mode update */ - Init.ClockEdge = SDIO_CLOCK_EDGE_RISING; - Init.ClockBypass = SDIO_CLOCK_BYPASS_DISABLE; - Init.ClockPowerSave = SDIO_CLOCK_POWER_SAVE_DISABLE; - Init.BusWide = WideMode; - Init.HardwareFlowControl = SDIO_HARDWARE_FLOW_CONTROL_DISABLE; - Init.ClockDiv = SDIO_INIT_CLK_DIV; - /* Initialize SDIO*/ - SDIO_Init(hmmc->Instance, Init); - - if(WideMode == SDIO_BUS_WIDE_8B) - { - errorstate = SDMMC_CmdSwitch(hmmc->Instance, 0x03B70200U); - if(errorstate != HAL_MMC_ERROR_NONE) - { - hmmc->ErrorCode |= errorstate; - } - } - else if(WideMode == SDIO_BUS_WIDE_4B) - { - errorstate = SDMMC_CmdSwitch(hmmc->Instance, 0x03B70100U); - if(errorstate != HAL_MMC_ERROR_NONE) - { - hmmc->ErrorCode |= errorstate; - } - } - else if(WideMode == SDIO_BUS_WIDE_1B) - { - errorstate = SDMMC_CmdSwitch(hmmc->Instance, 0x03B70000U); - if(errorstate != HAL_MMC_ERROR_NONE) - { - hmmc->ErrorCode |= errorstate; - } - } - else - { - /* WideMode is not a valid argument*/ - hmmc->ErrorCode |= HAL_MMC_ERROR_PARAM; - } - - /* Check for switch error and violation of the trial number of sending CMD 13 */ - while(busy == 0U) - { - if(count++ == SDMMC_MAX_TRIAL) - { - hmmc->State = HAL_MMC_STATE_READY; - hmmc->ErrorCode |= HAL_MMC_ERROR_REQUEST_NOT_APPLICABLE; - return HAL_ERROR; - } - - /* While card is not ready for data and trial number for sending CMD13 is not exceeded */ - errorstate = SDMMC_CmdSendStatus(hmmc->Instance, (uint32_t)(((uint32_t)hmmc->MmcCard.RelCardAdd) << 16U)); - if(errorstate != HAL_MMC_ERROR_NONE) - { - hmmc->ErrorCode |= errorstate; - } - - /* Get command response */ - response = SDIO_GetResponse(hmmc->Instance, SDIO_RESP1); - - /* Get operating voltage*/ - busy = (((response >> 7U) == 1U) ? 0U : 1U); - } - - /* While card is not ready for data and trial number for sending CMD13 is not exceeded */ - count = SDMMC_DATATIMEOUT; - while((response & 0x00000100U) == 0U) - { - if(count-- == 0U) - { - hmmc->State = HAL_MMC_STATE_READY; - hmmc->ErrorCode |= HAL_MMC_ERROR_REQUEST_NOT_APPLICABLE; - return HAL_ERROR; - } - - /* While card is not ready for data and trial number for sending CMD13 is not exceeded */ - errorstate = SDMMC_CmdSendStatus(hmmc->Instance, (uint32_t)(((uint32_t)hmmc->MmcCard.RelCardAdd) << 16U)); - if(errorstate != HAL_MMC_ERROR_NONE) - { - hmmc->ErrorCode |= errorstate; - } - - /* Get command response */ - response = SDIO_GetResponse(hmmc->Instance, SDIO_RESP1); - } - - if(hmmc->ErrorCode != HAL_MMC_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); - hmmc->State = HAL_MMC_STATE_READY; - return HAL_ERROR; - } - else - { - /* Configure the SDIO peripheral */ - Init.ClockEdge = hmmc->Init.ClockEdge; - Init.ClockBypass = hmmc->Init.ClockBypass; - Init.ClockPowerSave = hmmc->Init.ClockPowerSave; - Init.BusWide = WideMode; - Init.HardwareFlowControl = hmmc->Init.HardwareFlowControl; - Init.ClockDiv = hmmc->Init.ClockDiv; - SDIO_Init(hmmc->Instance, Init); - } - - /* Change State */ - hmmc->State = HAL_MMC_STATE_READY; - - return HAL_OK; -} - - -/** - * @brief Gets the current mmc card data state. - * @param hmmc: pointer to MMC handle - * @retval Card state - */ -HAL_MMC_CardStateTypeDef HAL_MMC_GetCardState(MMC_HandleTypeDef *hmmc) -{ - HAL_MMC_CardStateTypeDef cardstate = HAL_MMC_CARD_TRANSFER; - uint32_t errorstate = HAL_MMC_ERROR_NONE; - uint32_t resp1 = 0U; - - errorstate = MMC_SendStatus(hmmc, &resp1); - if(errorstate != HAL_OK) - { - hmmc->ErrorCode |= errorstate; - } - - cardstate = (HAL_MMC_CardStateTypeDef)((resp1 >> 9U) & 0x0FU); - - return cardstate; -} - -/** - * @brief Abort the current transfer and disable the MMC. - * @param hmmc: pointer to a MMC_HandleTypeDef structure that contains - * the configuration information for MMC module. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MMC_Abort(MMC_HandleTypeDef *hmmc) -{ - HAL_MMC_CardStateTypeDef CardState; - - /* DIsable All interrupts */ - __HAL_MMC_DISABLE_IT(hmmc, SDIO_IT_DATAEND | SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT|\ - SDIO_IT_TXUNDERR| SDIO_IT_RXOVERR); - - /* Clear All flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); - - if((hmmc->hdmatx != NULL) || (hmmc->hdmarx != NULL)) - { - /* Disable the MMC DMA request */ - hmmc->Instance->DCTRL &= (uint32_t)~((uint32_t)SDIO_DCTRL_DMAEN); - - /* Abort the MMC DMA Tx Stream */ - if(hmmc->hdmatx != NULL) - { - HAL_DMA_Abort(hmmc->hdmatx); - } - /* Abort the MMC DMA Rx Stream */ - if(hmmc->hdmarx != NULL) - { - HAL_DMA_Abort(hmmc->hdmarx); - } - } - - hmmc->State = HAL_MMC_STATE_READY; - CardState = HAL_MMC_GetCardState(hmmc); - if((CardState == HAL_MMC_CARD_RECEIVING) || (CardState == HAL_MMC_CARD_SENDING)) - { - hmmc->ErrorCode = SDMMC_CmdStopTransfer(hmmc->Instance); - } - if(hmmc->ErrorCode != HAL_MMC_ERROR_NONE) - { - return HAL_ERROR; - } - return HAL_OK; -} - -/** - * @brief Abort the current transfer and disable the MMC (IT mode). - * @param hmmc: pointer to a MMC_HandleTypeDef structure that contains - * the configuration information for MMC module. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_MMC_Abort_IT(MMC_HandleTypeDef *hmmc) -{ - HAL_MMC_CardStateTypeDef CardState; - - /* DIsable All interrupts */ - __HAL_MMC_DISABLE_IT(hmmc, SDIO_IT_DATAEND | SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT|\ - SDIO_IT_TXUNDERR| SDIO_IT_RXOVERR); - - /* Clear All flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); - - if((hmmc->hdmatx != NULL) || (hmmc->hdmarx != NULL)) - { - /* Disable the MMC DMA request */ - hmmc->Instance->DCTRL &= (uint32_t)~((uint32_t)SDIO_DCTRL_DMAEN); - - /* Abort the MMC DMA Tx Stream */ - if(hmmc->hdmatx != NULL) - { - hmmc->hdmatx->XferAbortCallback = MMC_DMATxAbort; - if(HAL_DMA_Abort_IT(hmmc->hdmatx) != HAL_OK) - { - hmmc->hdmatx = NULL; - } - } - /* Abort the MMC DMA Rx Stream */ - if(hmmc->hdmarx != NULL) - { - hmmc->hdmarx->XferAbortCallback = MMC_DMARxAbort; - if(HAL_DMA_Abort_IT(hmmc->hdmarx) != HAL_OK) - { - hmmc->hdmarx = NULL; - } - } - } - - /* No transfer ongoing on both DMA channels*/ - if((hmmc->hdmatx == NULL) && (hmmc->hdmarx == NULL)) - { - CardState = HAL_MMC_GetCardState(hmmc); - hmmc->State = HAL_MMC_STATE_READY; - if((CardState == HAL_MMC_CARD_RECEIVING) || (CardState == HAL_MMC_CARD_SENDING)) - { - hmmc->ErrorCode = SDMMC_CmdStopTransfer(hmmc->Instance); - } - if(hmmc->ErrorCode != HAL_MMC_ERROR_NONE) - { - return HAL_ERROR; - } - else - { - HAL_MMC_AbortCallback(hmmc); - } - } - - return HAL_OK; -} - -/** - * @} - */ - -/** - * @} - */ - -/* Private function ----------------------------------------------------------*/ -/** @addtogroup MMC_Private_Functions - * @{ - */ - -/** - * @brief DMA MMC transmit process complete callback - * @param hdma: DMA handle - * @retval None - */ -static void MMC_DMATransmitCplt(DMA_HandleTypeDef *hdma) -{ - MMC_HandleTypeDef* hmmc = (MMC_HandleTypeDef* )(hdma->Parent); - - /* Enable DATAEND Interrupt */ - __HAL_MMC_ENABLE_IT(hmmc, (SDIO_IT_DATAEND)); -} - -/** - * @brief DMA MMC receive process complete callback - * @param hdma: DMA handle - * @retval None - */ -static void MMC_DMAReceiveCplt(DMA_HandleTypeDef *hdma) -{ - MMC_HandleTypeDef* hmmc = (MMC_HandleTypeDef* )(hdma->Parent); - uint32_t errorstate = HAL_MMC_ERROR_NONE; - - /* Send stop command in multiblock write */ - if(hmmc->Context == (MMC_CONTEXT_READ_MULTIPLE_BLOCK | MMC_CONTEXT_DMA)) - { - errorstate = SDMMC_CmdStopTransfer(hmmc->Instance); - if(errorstate != HAL_MMC_ERROR_NONE) - { - hmmc->ErrorCode |= errorstate; - HAL_MMC_ErrorCallback(hmmc); - } - } - - /* Disable the DMA transfer for transmit request by setting the DMAEN bit - in the MMC DCTRL register */ - hmmc->Instance->DCTRL &= (uint32_t)~((uint32_t)SDIO_DCTRL_DMAEN); - - /* Clear all the static flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); - - hmmc->State = HAL_MMC_STATE_READY; - - HAL_MMC_RxCpltCallback(hmmc); -} - -/** - * @brief DMA MMC communication error callback - * @param hdma: DMA handle - * @retval None - */ -static void MMC_DMAError(DMA_HandleTypeDef *hdma) -{ - MMC_HandleTypeDef* hmmc = (MMC_HandleTypeDef* )(hdma->Parent); - HAL_MMC_CardStateTypeDef CardState; - - if((hmmc->hdmarx->ErrorCode == HAL_DMA_ERROR_TE) || (hmmc->hdmatx->ErrorCode == HAL_DMA_ERROR_TE)) - { - /* Clear All flags */ - __HAL_MMC_CLEAR_FLAG(hmmc, SDIO_STATIC_FLAGS); - - /* Disable All interrupts */ - __HAL_MMC_DISABLE_IT(hmmc, SDIO_IT_DATAEND | SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT|\ - SDIO_IT_TXUNDERR| SDIO_IT_RXOVERR); - - hmmc->ErrorCode |= HAL_MMC_ERROR_DMA; - CardState = HAL_MMC_GetCardState(hmmc); - if((CardState == HAL_MMC_CARD_RECEIVING) || (CardState == HAL_MMC_CARD_SENDING)) - { - hmmc->ErrorCode |= SDMMC_CmdStopTransfer(hmmc->Instance); - } - - hmmc->State= HAL_MMC_STATE_READY; - } - - HAL_MMC_ErrorCallback(hmmc); -} - -/** - * @brief DMA MMC Tx Abort callback - * @param hdma: DMA handle - * @retval None - */ -static void MMC_DMATxAbort(DMA_HandleTypeDef *hdma) -{ - MMC_HandleTypeDef* hmmc = (MMC_HandleTypeDef* )(hdma->Parent); - HAL_MMC_CardStateTypeDef CardState; - - if(hmmc->hdmatx != NULL) - { - hmmc->hdmatx = NULL; - } - - /* All DMA channels are aborted */ - if(hmmc->hdmarx == NULL) - { - CardState = HAL_MMC_GetCardState(hmmc); - hmmc->ErrorCode = HAL_MMC_ERROR_NONE; - hmmc->State = HAL_MMC_STATE_READY; - if((CardState == HAL_MMC_CARD_RECEIVING) || (CardState == HAL_MMC_CARD_SENDING)) - { - hmmc->ErrorCode |= SDMMC_CmdStopTransfer(hmmc->Instance); - - if(hmmc->ErrorCode != HAL_MMC_ERROR_NONE) - { - HAL_MMC_AbortCallback(hmmc); - } - else - { - HAL_MMC_ErrorCallback(hmmc); - } - } - } -} - -/** - * @brief DMA MMC Rx Abort callback - * @param hdma: DMA handle - * @retval None - */ -static void MMC_DMARxAbort(DMA_HandleTypeDef *hdma) -{ - MMC_HandleTypeDef* hmmc = (MMC_HandleTypeDef* )(hdma->Parent); - HAL_MMC_CardStateTypeDef CardState; - - if(hmmc->hdmarx != NULL) - { - hmmc->hdmarx = NULL; - } - - /* All DMA channels are aborted */ - if(hmmc->hdmatx == NULL) - { - CardState = HAL_MMC_GetCardState(hmmc); - hmmc->ErrorCode = HAL_MMC_ERROR_NONE; - hmmc->State = HAL_MMC_STATE_READY; - if((CardState == HAL_MMC_CARD_RECEIVING) || (CardState == HAL_MMC_CARD_SENDING)) - { - hmmc->ErrorCode |= SDMMC_CmdStopTransfer(hmmc->Instance); - - if(hmmc->ErrorCode != HAL_MMC_ERROR_NONE) - { - HAL_MMC_AbortCallback(hmmc); - } - else - { - HAL_MMC_ErrorCallback(hmmc); - } - } - } -} - - -/** - * @brief Initializes the mmc card. - * @param hmmc: Pointer to MMC handle - * @retval MMC Card error state - */ -static uint32_t MMC_InitCard(MMC_HandleTypeDef *hmmc) -{ - HAL_MMC_CardCSDTypeDef CSD; - uint32_t errorstate = HAL_MMC_ERROR_NONE; - uint16_t mmc_rca = 1; - - /* Check the power State */ - if(SDIO_GetPowerState(hmmc->Instance) == 0U) - { - /* Power off */ - return HAL_MMC_ERROR_REQUEST_NOT_APPLICABLE; - } - - /* Send CMD2 ALL_SEND_CID */ - errorstate = SDMMC_CmdSendCID(hmmc->Instance); - if(errorstate != HAL_MMC_ERROR_NONE) - { - return errorstate; - } - else - { - /* Get Card identification number data */ - hmmc->CID[0U] = SDIO_GetResponse(hmmc->Instance, SDIO_RESP1); - hmmc->CID[1U] = SDIO_GetResponse(hmmc->Instance, SDIO_RESP2); - hmmc->CID[2U] = SDIO_GetResponse(hmmc->Instance, SDIO_RESP3); - hmmc->CID[3U] = SDIO_GetResponse(hmmc->Instance, SDIO_RESP4); - } - - /* Send CMD3 SET_REL_ADDR with argument 0 */ - /* MMC Card publishes its RCA. */ - errorstate = SDMMC_CmdSetRelAdd(hmmc->Instance, &mmc_rca); - if(errorstate != HAL_MMC_ERROR_NONE) - { - return errorstate; - } - - /* Get the MMC card RCA */ - hmmc->MmcCard.RelCardAdd = mmc_rca; - - /* Send CMD9 SEND_CSD with argument as card's RCA */ - errorstate = SDMMC_CmdSendCSD(hmmc->Instance, (uint32_t)(hmmc->MmcCard.RelCardAdd << 16U)); - if(errorstate != HAL_MMC_ERROR_NONE) - { - return errorstate; - } - else - { - /* Get Card Specific Data */ - hmmc->CSD[0U] = SDIO_GetResponse(hmmc->Instance, SDIO_RESP1); - hmmc->CSD[1U] = SDIO_GetResponse(hmmc->Instance, SDIO_RESP2); - hmmc->CSD[2U] = SDIO_GetResponse(hmmc->Instance, SDIO_RESP3); - hmmc->CSD[3U] = SDIO_GetResponse(hmmc->Instance, SDIO_RESP4); - } - - /* Get the Card Class */ - hmmc->MmcCard.Class = (SDIO_GetResponse(hmmc->Instance, SDIO_RESP2) >> 20U); - - /* Get CSD parameters */ - HAL_MMC_GetCardCSD(hmmc, &CSD); - - /* Select the Card */ - errorstate = SDMMC_CmdSelDesel(hmmc->Instance, (uint32_t)(((uint32_t)hmmc->MmcCard.RelCardAdd) << 16U)); - if(errorstate != HAL_MMC_ERROR_NONE) - { - return errorstate; - } - - /* Configure SDIO peripheral interface */ - SDIO_Init(hmmc->Instance, hmmc->Init); - - /* All cards are initialized */ - return HAL_MMC_ERROR_NONE; -} - -/** - * @brief Enquires cards about their operating voltage and configures clock - * controls and stores MMC information that will be needed in future - * in the MMC handle. - * @param hmmc: Pointer to MMC handle - * @retval error state - */ -static uint32_t MMC_PowerON(MMC_HandleTypeDef *hmmc) -{ - __IO uint32_t count = 0U; - uint32_t response = 0U, validvoltage = 0U; - uint32_t errorstate = HAL_MMC_ERROR_NONE; - - /* CMD0: GO_IDLE_STATE */ - errorstate = SDMMC_CmdGoIdleState(hmmc->Instance); - if(errorstate != HAL_MMC_ERROR_NONE) - { - return errorstate; - } - - while(validvoltage == 0U) - { - if(count++ == SDMMC_MAX_VOLT_TRIAL) - { - return HAL_MMC_ERROR_INVALID_VOLTRANGE; - } - - /* SEND CMD1 APP_CMD with MMC_HIGH_VOLTAGE_RANGE(0xC0FF8000) as argument */ - errorstate = SDMMC_CmdOpCondition(hmmc->Instance, eMMC_HIGH_VOLTAGE_RANGE); - if(errorstate != HAL_MMC_ERROR_NONE) - { - return HAL_MMC_ERROR_UNSUPPORTED_FEATURE; - } - - /* Get command response */ - response = SDIO_GetResponse(hmmc->Instance, SDIO_RESP1); - - /* Get operating voltage*/ - validvoltage = (((response >> 31U) == 1U) ? 1U : 0U); - } - - /* When power routine is finished and command returns valid voltage */ - if ((response & eMMC_HIGH_VOLTAGE_RANGE) == MMC_HIGH_VOLTAGE_RANGE) - { - /* When voltage range of the card is within 2.7V and 3.6V */ - hmmc->MmcCard.CardType = MMC_HIGH_VOLTAGE_CARD; - } - else - { - /* When voltage range of the card is within 1.65V and 1.95V or 2.7V and 3.6V */ - hmmc->MmcCard.CardType = MMC_DUAL_VOLTAGE_CARD; - } - - return HAL_MMC_ERROR_NONE; -} - -/** - * @brief Turns the SDIO output signals off. - * @param hmmc: Pointer to MMC handle - * @retval HAL status - */ -static HAL_StatusTypeDef MMC_PowerOFF(MMC_HandleTypeDef *hmmc) -{ - /* Set Power State to OFF */ - SDIO_PowerState_OFF(hmmc->Instance); - - return HAL_OK; -} - -/** - * @brief Returns the current card's status. - * @param hmmc: Pointer to MMC handle - * @param pCardStatus: pointer to the buffer that will contain the MMC card - * status (Card Status register) - * @retval error state - */ -static uint32_t MMC_SendStatus(MMC_HandleTypeDef *hmmc, uint32_t *pCardStatus) -{ - uint32_t errorstate = HAL_MMC_ERROR_NONE; - - if(pCardStatus == NULL) - { - return HAL_MMC_ERROR_PARAM; - } - - /* Send Status command */ - errorstate = SDMMC_CmdSendStatus(hmmc->Instance, (uint32_t)(hmmc->MmcCard.RelCardAdd << 16U)); - if(errorstate != HAL_OK) - { - return errorstate; - } - - /* Get MMC card status */ - *pCardStatus = SDIO_GetResponse(hmmc->Instance, SDIO_RESP1); - - return HAL_MMC_ERROR_NONE; -} - -/** - * @brief Wrap up reading in non-blocking mode. - * @param hmmc: pointer to a MMC_HandleTypeDef structure that contains - * the configuration information. - * @retval HAL status - */ -static HAL_StatusTypeDef MMC_Read_IT(MMC_HandleTypeDef *hmmc) -{ - uint32_t count = 0U; - uint32_t* tmp; - - tmp = (uint32_t*)hmmc->pRxBuffPtr; - - /* Read data from SDMMC Rx FIFO */ - for(count = 0U; count < 8U; count++) - { - *(tmp + count) = SDIO_ReadFIFO(hmmc->Instance); - } - - hmmc->pRxBuffPtr += 8U; - - return HAL_OK; -} - -/** - * @brief Wrap up writing in non-blocking mode. - * @param hmmc: pointer to a MMC_HandleTypeDef structure that contains - * the configuration information. - * @retval HAL status - */ -static HAL_StatusTypeDef MMC_Write_IT(MMC_HandleTypeDef *hmmc) -{ - uint32_t count = 0U; - uint32_t* tmp; - - tmp = (uint32_t*)hmmc->pTxBuffPtr; - - /* Write data to SDMMC Tx FIFO */ - for(count = 0U; count < 8U; count++) - { - SDIO_WriteFIFO(hmmc->Instance, (tmp + count)); - } - - hmmc->pTxBuffPtr += 8U; - - return HAL_OK; -} - -/** - * @} - */ - -#endif /* STM32F103xE || STM32F103xG */ - -#endif /* HAL_MMC_MODULE_ENABLED */ - -/** - * @} - */ - -/** - * @} - */ - -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_mmc.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_mmc.h deleted file mode 100644 index 7fa628e88ef..00000000000 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_mmc.h +++ /dev/null @@ -1,718 +0,0 @@ -/** - ****************************************************************************** - * @file stm32f1xx_hal_mmc.h - * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 - * @brief Header file of MMC HAL module. - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2017 STMicroelectronics

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ - -/* Define to prevent recursive inclusion -------------------------------------*/ -#ifndef __STM32F1xx_HAL_MMC_H -#define __STM32F1xx_HAL_MMC_H - -#ifdef __cplusplus - extern "C" { -#endif - -#if defined(STM32F103xE) || defined(STM32F103xG) - -/* Includes ------------------------------------------------------------------*/ -#include "stm32f1xx_ll_sdmmc.h" - -/** @addtogroup STM32F1xx_HAL_Driver - * @{ - */ - -/** @defgroup MMC MMC - * @brief MMC HAL module driver - * @{ - */ - -/* Exported types ------------------------------------------------------------*/ -/** @defgroup MMC_Exported_Types MMC Exported Types - * @{ - */ - -/** @defgroup MMC_Exported_Types_Group1 MMC State enumeration structure - * @{ - */ -typedef enum -{ - HAL_MMC_STATE_RESET = 0x00000000U, /*!< MMC not yet initialized or disabled */ - HAL_MMC_STATE_READY = 0x00000001U, /*!< MMC initialized and ready for use */ - HAL_MMC_STATE_TIMEOUT = 0x00000002U, /*!< MMC Timeout state */ - HAL_MMC_STATE_BUSY = 0x00000003U, /*!< MMC process ongoing */ - HAL_MMC_STATE_PROGRAMMING = 0x00000004U, /*!< MMC Programming State */ - HAL_MMC_STATE_RECEIVING = 0x00000005U, /*!< MMC Receinving State */ - HAL_MMC_STATE_TRANSFER = 0x00000006U, /*!< MMC Transfert State */ - HAL_MMC_STATE_ERROR = 0x0000000FU /*!< MMC is in error state */ -}HAL_MMC_StateTypeDef; -/** - * @} - */ - -/** @defgroup MMC_Exported_Types_Group2 MMC Card State enumeration structure - * @{ - */ -typedef enum -{ - HAL_MMC_CARD_READY = 0x00000001U, /*!< Card state is ready */ - HAL_MMC_CARD_IDENTIFICATION = 0x00000002U, /*!< Card is in identification state */ - HAL_MMC_CARD_STANDBY = 0x00000003U, /*!< Card is in standby state */ - HAL_MMC_CARD_TRANSFER = 0x00000004U, /*!< Card is in transfer state */ - HAL_MMC_CARD_SENDING = 0x00000005U, /*!< Card is sending an operation */ - HAL_MMC_CARD_RECEIVING = 0x00000006U, /*!< Card is receiving operation information */ - HAL_MMC_CARD_PROGRAMMING = 0x00000007U, /*!< Card is in programming state */ - HAL_MMC_CARD_DISCONNECTED = 0x00000008U, /*!< Card is disconnected */ - HAL_MMC_CARD_ERROR = 0x000000FFU /*!< Card response Error */ -}HAL_MMC_CardStateTypeDef; -/** - * @} - */ - -/** @defgroup MMC_Exported_Types_Group3 MMC Handle Structure definition - * @{ - */ -#define MMC_InitTypeDef SDIO_InitTypeDef -#define MMC_TypeDef SDIO_TypeDef - -/** - * @brief MMC Card Information Structure definition - */ -typedef struct -{ - uint32_t CardType; /*!< Specifies the card Type */ - - uint32_t Class; /*!< Specifies the class of the card class */ - - uint32_t RelCardAdd; /*!< Specifies the Relative Card Address */ - - uint32_t BlockNbr; /*!< Specifies the Card Capacity in blocks */ - - uint32_t BlockSize; /*!< Specifies one block size in bytes */ - - uint32_t LogBlockNbr; /*!< Specifies the Card logical Capacity in blocks */ - - uint32_t LogBlockSize; /*!< Specifies logical block size in bytes */ - -}HAL_MMC_CardInfoTypeDef; - -/** - * @brief MMC handle Structure definition - */ -typedef struct -{ - MMC_TypeDef *Instance; /*!< MMC registers base address */ - - MMC_InitTypeDef Init; /*!< MMC required parameters */ - - HAL_LockTypeDef Lock; /*!< MMC locking object */ - - uint32_t *pTxBuffPtr; /*!< Pointer to MMC Tx transfer Buffer */ - - uint32_t TxXferSize; /*!< MMC Tx Transfer size */ - - uint32_t *pRxBuffPtr; /*!< Pointer to MMC Rx transfer Buffer */ - - uint32_t RxXferSize; /*!< MMC Rx Transfer size */ - - __IO uint32_t Context; /*!< MMC transfer context */ - - __IO HAL_MMC_StateTypeDef State; /*!< MMC card State */ - - __IO uint32_t ErrorCode; /*!< MMC Card Error codes */ - - DMA_HandleTypeDef *hdmarx; /*!< MMC Rx DMA handle parameters */ - - DMA_HandleTypeDef *hdmatx; /*!< MMC Tx DMA handle parameters */ - - HAL_MMC_CardInfoTypeDef MmcCard; /*!< MMC Card information */ - - uint32_t CSD[4U]; /*!< MMC card specific data table */ - - uint32_t CID[4U]; /*!< MMC card identification number table */ - -}MMC_HandleTypeDef; - -/** - * @} - */ - -/** @defgroup MMC_Exported_Types_Group4 Card Specific Data: CSD Register - * @{ - */ -typedef struct -{ - __IO uint8_t CSDStruct; /*!< CSD structure */ - __IO uint8_t SysSpecVersion; /*!< System specification version */ - __IO uint8_t Reserved1; /*!< Reserved */ - __IO uint8_t TAAC; /*!< Data read access time 1 */ - __IO uint8_t NSAC; /*!< Data read access time 2 in CLK cycles */ - __IO uint8_t MaxBusClkFrec; /*!< Max. bus clock frequency */ - __IO uint16_t CardComdClasses; /*!< Card command classes */ - __IO uint8_t RdBlockLen; /*!< Max. read data block length */ - __IO uint8_t PartBlockRead; /*!< Partial blocks for read allowed */ - __IO uint8_t WrBlockMisalign; /*!< Write block misalignment */ - __IO uint8_t RdBlockMisalign; /*!< Read block misalignment */ - __IO uint8_t DSRImpl; /*!< DSR implemented */ - __IO uint8_t Reserved2; /*!< Reserved */ - __IO uint32_t DeviceSize; /*!< Device Size */ - __IO uint8_t MaxRdCurrentVDDMin; /*!< Max. read current @ VDD min */ - __IO uint8_t MaxRdCurrentVDDMax; /*!< Max. read current @ VDD max */ - __IO uint8_t MaxWrCurrentVDDMin; /*!< Max. write current @ VDD min */ - __IO uint8_t MaxWrCurrentVDDMax; /*!< Max. write current @ VDD max */ - __IO uint8_t DeviceSizeMul; /*!< Device size multiplier */ - __IO uint8_t EraseGrSize; /*!< Erase group size */ - __IO uint8_t EraseGrMul; /*!< Erase group size multiplier */ - __IO uint8_t WrProtectGrSize; /*!< Write protect group size */ - __IO uint8_t WrProtectGrEnable; /*!< Write protect group enable */ - __IO uint8_t ManDeflECC; /*!< Manufacturer default ECC */ - __IO uint8_t WrSpeedFact; /*!< Write speed factor */ - __IO uint8_t MaxWrBlockLen; /*!< Max. write data block length */ - __IO uint8_t WriteBlockPaPartial; /*!< Partial blocks for write allowed */ - __IO uint8_t Reserved3; /*!< Reserved */ - __IO uint8_t ContentProtectAppli; /*!< Content protection application */ - __IO uint8_t FileFormatGrouop; /*!< File format group */ - __IO uint8_t CopyFlag; /*!< Copy flag (OTP) */ - __IO uint8_t PermWrProtect; /*!< Permanent write protection */ - __IO uint8_t TempWrProtect; /*!< Temporary write protection */ - __IO uint8_t FileFormat; /*!< File format */ - __IO uint8_t ECC; /*!< ECC code */ - __IO uint8_t CSD_CRC; /*!< CSD CRC */ - __IO uint8_t Reserved4; /*!< Always 1 */ - -}HAL_MMC_CardCSDTypeDef; -/** - * @} - */ - -/** @defgroup MMC_Exported_Types_Group5 Card Identification Data: CID Register - * @{ - */ -typedef struct -{ - __IO uint8_t ManufacturerID; /*!< Manufacturer ID */ - __IO uint16_t OEM_AppliID; /*!< OEM/Application ID */ - __IO uint32_t ProdName1; /*!< Product Name part1 */ - __IO uint8_t ProdName2; /*!< Product Name part2 */ - __IO uint8_t ProdRev; /*!< Product Revision */ - __IO uint32_t ProdSN; /*!< Product Serial Number */ - __IO uint8_t Reserved1; /*!< Reserved1 */ - __IO uint16_t ManufactDate; /*!< Manufacturing Date */ - __IO uint8_t CID_CRC; /*!< CID CRC */ - __IO uint8_t Reserved2; /*!< Always 1 */ - -}HAL_MMC_CardCIDTypeDef; -/** - * @} - */ - -/** @defgroup MMC_Exported_Types_Group6 MMC Card Status returned by ACMD13 - * @{ - */ -typedef struct -{ - __IO uint8_t DataBusWidth; /*!< Shows the currently defined data bus width */ - __IO uint8_t SecuredMode; /*!< Card is in secured mode of operation */ - __IO uint16_t CardType; /*!< Carries information about card type */ - __IO uint32_t ProtectedAreaSize; /*!< Carries information about the capacity of protected area */ - __IO uint8_t SpeedClass; /*!< Carries information about the speed class of the card */ - __IO uint8_t PerformanceMove; /*!< Carries information about the card's performance move */ - __IO uint8_t AllocationUnitSize; /*!< Carries information about the card's allocation unit size */ - __IO uint16_t EraseSize; /*!< Determines the number of AUs to be erased in one operation */ - __IO uint8_t EraseTimeout; /*!< Determines the timeout for any number of AU erase */ - __IO uint8_t EraseOffset; /*!< Carries information about the erase offset */ - -}HAL_MMC_CardStatusTypeDef; -/** - * @} - */ - -/** - * @} - */ - -/* Exported constants --------------------------------------------------------*/ -/** @defgroup MMC_Exported_Constants Exported Constants - * @{ - */ - -#define BLOCKSIZE 512U /*!< Block size is 512 bytes */ - -#define CAPACITY 0x400000U /*!< Log Block Nuumber for 2 G bytes Cards */ - -/** @defgroup MMC_Exported_Constansts_Group1 MMC Error status enumeration Structure definition - * @{ - */ -#define HAL_MMC_ERROR_NONE SDMMC_ERROR_NONE /*!< No error */ -#define HAL_MMC_ERROR_CMD_CRC_FAIL SDMMC_ERROR_CMD_CRC_FAIL /*!< Command response received (but CRC check failed) */ -#define HAL_MMC_ERROR_DATA_CRC_FAIL SDMMC_ERROR_DATA_CRC_FAIL /*!< Data block sent/received (CRC check failed) */ -#define HAL_MMC_ERROR_CMD_RSP_TIMEOUT SDMMC_ERROR_CMD_RSP_TIMEOUT /*!< Command response timeout */ -#define HAL_MMC_ERROR_DATA_TIMEOUT SDMMC_ERROR_DATA_TIMEOUT /*!< Data timeout */ -#define HAL_MMC_ERROR_TX_UNDERRUN SDMMC_ERROR_TX_UNDERRUN /*!< Transmit FIFO underrun */ -#define HAL_MMC_ERROR_RX_OVERRUN SDMMC_ERROR_RX_OVERRUN /*!< Receive FIFO overrun */ -#define HAL_MMC_ERROR_ADDR_MISALIGNED SDMMC_ERROR_ADDR_MISALIGNED /*!< Misaligned address */ -#define HAL_MMC_ERROR_BLOCK_LEN_ERR SDMMC_ERROR_BLOCK_LEN_ERR /*!< Transferred block length is not allowed for the card or the - number of transferred bytes does not match the block length */ -#define HAL_MMC_ERROR_ERASE_SEQ_ERR SDMMC_ERROR_ERASE_SEQ_ERR /*!< An error in the sequence of erase command occurs */ -#define HAL_MMC_ERROR_BAD_ERASE_PARAM SDMMC_ERROR_BAD_ERASE_PARAM /*!< An invalid selection for erase groups */ -#define HAL_MMC_ERROR_WRITE_PROT_VIOLATION SDMMC_ERROR_WRITE_PROT_VIOLATION /*!< Attempt to program a write protect block */ -#define HAL_MMC_ERROR_LOCK_UNLOCK_FAILED SDMMC_ERROR_LOCK_UNLOCK_FAILED /*!< Sequence or password error has been detected in unlock - command or if there was an attempt to access a locked card */ -#define HAL_MMC_ERROR_COM_CRC_FAILED SDMMC_ERROR_COM_CRC_FAILED /*!< CRC check of the previous command failed */ -#define HAL_MMC_ERROR_ILLEGAL_CMD SDMMC_ERROR_ILLEGAL_CMD /*!< Command is not legal for the card state */ -#define HAL_MMC_ERROR_CARD_ECC_FAILED SDMMC_ERROR_CARD_ECC_FAILED /*!< Card internal ECC was applied but failed to correct the data */ -#define HAL_MMC_ERROR_CC_ERR SDMMC_ERROR_CC_ERR /*!< Internal card controller error */ -#define HAL_MMC_ERROR_GENERAL_UNKNOWN_ERR SDMMC_ERROR_GENERAL_UNKNOWN_ERR /*!< General or unknown error */ -#define HAL_MMC_ERROR_STREAM_READ_UNDERRUN SDMMC_ERROR_STREAM_READ_UNDERRUN /*!< The card could not sustain data reading in stream rmode */ -#define HAL_MMC_ERROR_STREAM_WRITE_OVERRUN SDMMC_ERROR_STREAM_WRITE_OVERRUN /*!< The card could not sustain data programming in stream mode */ -#define HAL_MMC_ERROR_CID_CSD_OVERWRITE SDMMC_ERROR_CID_CSD_OVERWRITE /*!< CID/CSD overwrite error */ -#define HAL_MMC_ERROR_WP_ERASE_SKIP SDMMC_ERROR_WP_ERASE_SKIP /*!< Only partial address space was erased */ -#define HAL_MMC_ERROR_CARD_ECC_DISABLED SDMMC_ERROR_CARD_ECC_DISABLED /*!< Command has been executed without using internal ECC */ -#define HAL_MMC_ERROR_ERASE_RESET SDMMC_ERROR_ERASE_RESET /*!< Erase sequence was cleared before executing because an out - of erase sequence command was received */ -#define HAL_MMC_ERROR_AKE_SEQ_ERR SDMMC_ERROR_AKE_SEQ_ERR /*!< Error in sequence of authentication */ -#define HAL_MMC_ERROR_INVALID_VOLTRANGE SDMMC_ERROR_INVALID_VOLTRANGE /*!< Error in case of invalid voltage range */ -#define HAL_MMC_ERROR_ADDR_OUT_OF_RANGE SDMMC_ERROR_ADDR_OUT_OF_RANGE /*!< Error when addressed block is out of range */ -#define HAL_MMC_ERROR_REQUEST_NOT_APPLICABLE SDMMC_ERROR_REQUEST_NOT_APPLICABLE /*!< Error when command request is not applicable */ -#define HAL_MMC_ERROR_PARAM SDMMC_ERROR_INVALID_PARAMETER /*!< the used parameter is not valid */ -#define HAL_MMC_ERROR_UNSUPPORTED_FEATURE SDMMC_ERROR_UNSUPPORTED_FEATURE /*!< Error when feature is not insupported */ -#define HAL_MMC_ERROR_BUSY SDMMC_ERROR_BUSY /*!< Error when transfer process is busy */ -#define HAL_MMC_ERROR_DMA SDMMC_ERROR_DMA /*!< Error while DMA transfer */ -#define HAL_MMC_ERROR_TIMEOUT SDMMC_ERROR_TIMEOUT /*!< Timeout error */ -/** - * @} - */ - -/** @defgroup MMC_Exported_Constansts_Group2 MMC context enumeration structure - * @{ - */ -#define MMC_CONTEXT_NONE 0x00000000U /*!< None */ -#define MMC_CONTEXT_READ_SINGLE_BLOCK 0x00000001U /*!< Read single block operation */ -#define MMC_CONTEXT_READ_MULTIPLE_BLOCK 0x00000002U /*!< Read multiple blocks operation */ -#define MMC_CONTEXT_WRITE_SINGLE_BLOCK 0x00000010U /*!< Write single block operation */ -#define MMC_CONTEXT_WRITE_MULTIPLE_BLOCK 0x00000020U /*!< Write multiple blocks operation */ -#define MMC_CONTEXT_IT 0x00000008U /*!< Process in Interrupt mode */ -#define MMC_CONTEXT_DMA 0x00000080U /*!< Process in DMA mode */ -/** - * @} - */ - -/** @defgroup MMC_Exported_Constansts_Group3 MMC Voltage mode - * @{ - */ -/** - * @brief - */ -#define MMC_HIGH_VOLTAGE_RANGE 0x80FF8000U /*!< VALUE OF ARGUMENT */ -#define MMC_DUAL_VOLTAGE_RANGE 0x80FF8080U /*!< VALUE OF ARGUMENT */ -#define eMMC_HIGH_VOLTAGE_RANGE 0xC0FF8000U /*!< for eMMC > 2Gb sector mode */ -#define eMMC_DUAL_VOLTAGE_RANGE 0xC0FF8080U /*!< for eMMC > 2Gb sector mode */ -#define MMC_INVALID_VOLTAGE_RANGE 0x0001FF01U -/** - * @} - */ - -/** @defgroup MMC_Exported_Constansts_Group4 MMC Memory Cards - * @{ - */ -#define MMC_HIGH_VOLTAGE_CARD 0x00000000U -#define MMC_DUAL_VOLTAGE_CARD 0x00000001U -/** - * @} - */ - -/** - * @} - */ - -/* Exported macro ------------------------------------------------------------*/ -/** @defgroup MMC_Exported_macros MMC Exported Macros - * @brief macros to handle interrupts and specific clock configurations - * @{ - */ - -/** - * @brief Enable the MMC device. - * @retval None - */ -#define __HAL_MMC_ENABLE(__HANDLE__) __SDIO_ENABLE((__HANDLE__)->Instance) - -/** - * @brief Disable the MMC device. - * @retval None - */ -#define __HAL_MMC_DISABLE(__HANDLE__) __SDIO_DISABLE((__HANDLE__)->Instance) - -/** - * @brief Enable the SDMMC DMA transfer. - * @retval None - */ -#define __HAL_MMC_DMA_ENABLE(__HANDLE__) __SDIO_DMA_ENABLE((__HANDLE__)->Instance) - -/** - * @brief Disable the SDMMC DMA transfer. - * @retval None - */ -#define __HAL_MMC_DMA_DISABLE(__HANDLE__) __SDIO_DMA_DISABLE((__HANDLE__)->Instance) - -/** - * @brief Enable the MMC device interrupt. - * @param __HANDLE__: MMC Handle - * @param __INTERRUPT__: specifies the SDMMC interrupt sources to be enabled. - * This parameter can be one or a combination of the following values: - * @arg SDIO_IT_CCRCFAIL: Command response received (CRC check failed) interrupt - * @arg SDIO_IT_DCRCFAIL: Data block sent/received (CRC check failed) interrupt - * @arg SDIO_IT_CTIMEOUT: Command response timeout interrupt - * @arg SDIO_IT_DTIMEOUT: Data timeout interrupt - * @arg SDIO_IT_TXUNDERR: Transmit FIFO underrun error interrupt - * @arg SDIO_IT_RXOVERR: Received FIFO overrun error interrupt - * @arg SDIO_IT_CMDREND: Command response received (CRC check passed) interrupt - * @arg SDIO_IT_CMDSENT: Command sent (no response required) interrupt - * @arg SDIO_IT_DATAEND: Data end (data counter, SDIDCOUNT, is zero) interrupt - * @arg SDIO_IT_DBCKEND: Data block sent/received (CRC check passed) interrupt - * @arg SDIO_IT_CMDACT: Command transfer in progress interrupt - * @arg SDIO_IT_TXACT: Data transmit in progress interrupt - * @arg SDIO_IT_RXACT: Data receive in progress interrupt - * @arg SDIO_IT_TXFIFOHE: Transmit FIFO Half Empty interrupt - * @arg SDIO_IT_RXFIFOHF: Receive FIFO Half Full interrupt - * @arg SDIO_IT_TXFIFOF: Transmit FIFO full interrupt - * @arg SDIO_IT_RXFIFOF: Receive FIFO full interrupt - * @arg SDIO_IT_TXFIFOE: Transmit FIFO empty interrupt - * @arg SDIO_IT_RXFIFOE: Receive FIFO empty interrupt - * @arg SDIO_IT_TXDAVL: Data available in transmit FIFO interrupt - * @arg SDIO_IT_RXDAVL: Data available in receive FIFO interrupt - * @arg SDIO_IT_SDIOIT: SD I/O interrupt received interrupt - * @retval None - */ -#define __HAL_MMC_ENABLE_IT(__HANDLE__, __INTERRUPT__) __SDIO_ENABLE_IT((__HANDLE__)->Instance, (__INTERRUPT__)) - -/** - * @brief Disable the MMC device interrupt. - * @param __HANDLE__: MMC Handle - * @param __INTERRUPT__: specifies the SDMMC interrupt sources to be disabled. - * This parameter can be one or a combination of the following values: - * @arg SDIO_IT_CCRCFAIL: Command response received (CRC check failed) interrupt - * @arg SDIO_IT_DCRCFAIL: Data block sent/received (CRC check failed) interrupt - * @arg SDIO_IT_CTIMEOUT: Command response timeout interrupt - * @arg SDIO_IT_DTIMEOUT: Data timeout interrupt - * @arg SDIO_IT_TXUNDERR: Transmit FIFO underrun error interrupt - * @arg SDIO_IT_RXOVERR: Received FIFO overrun error interrupt - * @arg SDIO_IT_CMDREND: Command response received (CRC check passed) interrupt - * @arg SDIO_IT_CMDSENT: Command sent (no response required) interrupt - * @arg SDIO_IT_DATAEND: Data end (data counter, SDIDCOUNT, is zero) interrupt - * @arg SDIO_IT_DBCKEND: Data block sent/received (CRC check passed) interrupt - * @arg SDIO_IT_CMDACT: Command transfer in progress interrupt - * @arg SDIO_IT_TXACT: Data transmit in progress interrupt - * @arg SDIO_IT_RXACT: Data receive in progress interrupt - * @arg SDIO_IT_TXFIFOHE: Transmit FIFO Half Empty interrupt - * @arg SDIO_IT_RXFIFOHF: Receive FIFO Half Full interrupt - * @arg SDIO_IT_TXFIFOF: Transmit FIFO full interrupt - * @arg SDIO_IT_RXFIFOF: Receive FIFO full interrupt - * @arg SDIO_IT_TXFIFOE: Transmit FIFO empty interrupt - * @arg SDIO_IT_RXFIFOE: Receive FIFO empty interrupt - * @arg SDIO_IT_TXDAVL: Data available in transmit FIFO interrupt - * @arg SDIO_IT_RXDAVL: Data available in receive FIFO interrupt - * @arg SDIO_IT_SDIOIT: SD I/O interrupt received interrupt - * @retval None - */ -#define __HAL_MMC_DISABLE_IT(__HANDLE__, __INTERRUPT__) __SDIO_DISABLE_IT((__HANDLE__)->Instance, (__INTERRUPT__)) - -/** - * @brief Check whether the specified MMC flag is set or not. - * @param __HANDLE__: MMC Handle - * @param __FLAG__: specifies the flag to check. - * This parameter can be one of the following values: - * @arg SDIO_FLAG_CCRCFAIL: Command response received (CRC check failed) - * @arg SDIO_FLAG_DCRCFAIL: Data block sent/received (CRC check failed) - * @arg SDIO_FLAG_CTIMEOUT: Command response timeout - * @arg SDIO_FLAG_DTIMEOUT: Data timeout - * @arg SDIO_FLAG_TXUNDERR: Transmit FIFO underrun error - * @arg SDIO_FLAG_RXOVERR: Received FIFO overrun error - * @arg SDIO_FLAG_CMDREND: Command response received (CRC check passed) - * @arg SDIO_FLAG_CMDSENT: Command sent (no response required) - * @arg SDIO_FLAG_DATAEND: Data end (data counter, SDIDCOUNT, is zero) - * @arg SDIO_FLAG_DBCKEND: Data block sent/received (CRC check passed) - * @arg SDIO_FLAG_CMDACT: Command transfer in progress - * @arg SDIO_FLAG_TXACT: Data transmit in progress - * @arg SDIO_FLAG_RXACT: Data receive in progress - * @arg SDIO_FLAG_TXFIFOHE: Transmit FIFO Half Empty - * @arg SDIO_FLAG_RXFIFOHF: Receive FIFO Half Full - * @arg SDIO_FLAG_TXFIFOF: Transmit FIFO full - * @arg SDIO_FLAG_RXFIFOF: Receive FIFO full - * @arg SDIO_FLAG_TXFIFOE: Transmit FIFO empty - * @arg SDIO_FLAG_RXFIFOE: Receive FIFO empty - * @arg SDIO_FLAG_TXDAVL: Data available in transmit FIFO - * @arg SDIO_FLAG_RXDAVL: Data available in receive FIFO - * @arg SDIO_FLAG_SDIOIT: SD I/O interrupt received - * @retval The new state of MMC FLAG (SET or RESET). - */ -#define __HAL_MMC_GET_FLAG(__HANDLE__, __FLAG__) __SDIO_GET_FLAG((__HANDLE__)->Instance, (__FLAG__)) - -/** - * @brief Clear the MMC's pending flags. - * @param __HANDLE__: MMC Handle - * @param __FLAG__: specifies the flag to clear. - * This parameter can be one or a combination of the following values: - * @arg SDIO_FLAG_CCRCFAIL: Command response received (CRC check failed) - * @arg SDIO_FLAG_DCRCFAIL: Data block sent/received (CRC check failed) - * @arg SDIO_FLAG_CTIMEOUT: Command response timeout - * @arg SDIO_FLAG_DTIMEOUT: Data timeout - * @arg SDIO_FLAG_TXUNDERR: Transmit FIFO underrun error - * @arg SDIO_FLAG_RXOVERR: Received FIFO overrun error - * @arg SDIO_FLAG_CMDREND: Command response received (CRC check passed) - * @arg SDIO_FLAG_CMDSENT: Command sent (no response required) - * @arg SDIO_FLAG_DATAEND: Data end (data counter, SDIDCOUNT, is zero) - * @arg SDIO_FLAG_DBCKEND: Data block sent/received (CRC check passed) - * @arg SDIO_FLAG_SDIOIT: SD I/O interrupt received - * @retval None - */ -#define __HAL_MMC_CLEAR_FLAG(__HANDLE__, __FLAG__) __SDIO_CLEAR_FLAG((__HANDLE__)->Instance, (__FLAG__)) - -/** - * @brief Check whether the specified MMC interrupt has occurred or not. - * @param __HANDLE__: MMC Handle - * @param __INTERRUPT__: specifies the SDMMC interrupt source to check. - * This parameter can be one of the following values: - * @arg SDIO_IT_CCRCFAIL: Command response received (CRC check failed) interrupt - * @arg SDIO_IT_DCRCFAIL: Data block sent/received (CRC check failed) interrupt - * @arg SDIO_IT_CTIMEOUT: Command response timeout interrupt - * @arg SDIO_IT_DTIMEOUT: Data timeout interrupt - * @arg SDIO_IT_TXUNDERR: Transmit FIFO underrun error interrupt - * @arg SDIO_IT_RXOVERR: Received FIFO overrun error interrupt - * @arg SDIO_IT_CMDREND: Command response received (CRC check passed) interrupt - * @arg SDIO_IT_CMDSENT: Command sent (no response required) interrupt - * @arg SDIO_IT_DATAEND: Data end (data counter, SDIDCOUNT, is zero) interrupt - * @arg SDIO_IT_DBCKEND: Data block sent/received (CRC check passed) interrupt - * @arg SDIO_IT_CMDACT: Command transfer in progress interrupt - * @arg SDIO_IT_TXACT: Data transmit in progress interrupt - * @arg SDIO_IT_RXACT: Data receive in progress interrupt - * @arg SDIO_IT_TXFIFOHE: Transmit FIFO Half Empty interrupt - * @arg SDIO_IT_RXFIFOHF: Receive FIFO Half Full interrupt - * @arg SDIO_IT_TXFIFOF: Transmit FIFO full interrupt - * @arg SDIO_IT_RXFIFOF: Receive FIFO full interrupt - * @arg SDIO_IT_TXFIFOE: Transmit FIFO empty interrupt - * @arg SDIO_IT_RXFIFOE: Receive FIFO empty interrupt - * @arg SDIO_IT_TXDAVL: Data available in transmit FIFO interrupt - * @arg SDIO_IT_RXDAVL: Data available in receive FIFO interrupt - * @arg SDIO_IT_SDIOIT: SD I/O interrupt received interrupt - * @retval The new state of MMC IT (SET or RESET). - */ -#define __HAL_MMC_GET_IT(__HANDLE__, __INTERRUPT__) __SDIO_GET_IT((__HANDLE__)->Instance, (__INTERRUPT__)) - -/** - * @brief Clear the MMC's interrupt pending bits. - * @param __HANDLE__: MMC Handle - * @param __INTERRUPT__: specifies the interrupt pending bit to clear. - * This parameter can be one or a combination of the following values: - * @arg SDIO_IT_CCRCFAIL: Command response received (CRC check failed) interrupt - * @arg SDIO_IT_DCRCFAIL: Data block sent/received (CRC check failed) interrupt - * @arg SDIO_IT_CTIMEOUT: Command response timeout interrupt - * @arg SDIO_IT_DTIMEOUT: Data timeout interrupt - * @arg SDIO_IT_TXUNDERR: Transmit FIFO underrun error interrupt - * @arg SDIO_IT_RXOVERR: Received FIFO overrun error interrupt - * @arg SDIO_IT_CMDREND: Command response received (CRC check passed) interrupt - * @arg SDIO_IT_CMDSENT: Command sent (no response required) interrupt - * @arg SDIO_IT_DATAEND: Data end (data counter, SDMMC_DCOUNT, is zero) interrupt - * @arg SDIO_IT_SDIOIT: SD I/O interrupt received interrupt - * @retval None - */ -#define __HAL_MMC_CLEAR_IT(__HANDLE__, __INTERRUPT__) __SDIO_CLEAR_IT((__HANDLE__)->Instance, (__INTERRUPT__)) - -/** - * @} - */ - -/* Exported functions --------------------------------------------------------*/ -/** @defgroup MMC_Exported_Functions MMC Exported Functions - * @{ - */ - -/** @defgroup MMC_Exported_Functions_Group1 Initialization and de-initialization functions - * @{ - */ -HAL_StatusTypeDef HAL_MMC_Init(MMC_HandleTypeDef *hmmc); -HAL_StatusTypeDef HAL_MMC_InitCard(MMC_HandleTypeDef *hmmc); -HAL_StatusTypeDef HAL_MMC_DeInit (MMC_HandleTypeDef *hmmc); -void HAL_MMC_MspInit(MMC_HandleTypeDef *hmmc); -void HAL_MMC_MspDeInit(MMC_HandleTypeDef *hmmc); -/** - * @} - */ - -/** @defgroup MMC_Exported_Functions_Group2 Input and Output operation functions - * @{ - */ -/* Blocking mode: Polling */ -HAL_StatusTypeDef HAL_MMC_ReadBlocks(MMC_HandleTypeDef *hmmc, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks, uint32_t Timeout); -HAL_StatusTypeDef HAL_MMC_WriteBlocks(MMC_HandleTypeDef *hmmc, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks, uint32_t Timeout); -HAL_StatusTypeDef HAL_MMC_Erase(MMC_HandleTypeDef *hmmc, uint32_t BlockStartAdd, uint32_t BlockEndAdd); -/* Non-Blocking mode: IT */ -HAL_StatusTypeDef HAL_MMC_ReadBlocks_IT(MMC_HandleTypeDef *hmmc, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks); -HAL_StatusTypeDef HAL_MMC_WriteBlocks_IT(MMC_HandleTypeDef *hmmc, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks); -/* Non-Blocking mode: DMA */ -HAL_StatusTypeDef HAL_MMC_ReadBlocks_DMA(MMC_HandleTypeDef *hmmc, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks); -HAL_StatusTypeDef HAL_MMC_WriteBlocks_DMA(MMC_HandleTypeDef *hmmc, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks); - -void HAL_MMC_IRQHandler(MMC_HandleTypeDef *hmmc); - -/* Callback in non blocking modes (DMA) */ -void HAL_MMC_TxCpltCallback(MMC_HandleTypeDef *hmmc); -void HAL_MMC_RxCpltCallback(MMC_HandleTypeDef *hmmc); -void HAL_MMC_ErrorCallback(MMC_HandleTypeDef *hmmc); -void HAL_MMC_AbortCallback(MMC_HandleTypeDef *hmmc); -/** - * @} - */ - -/** @defgroup MMC_Exported_Functions_Group3 Peripheral Control functions - * @{ - */ -HAL_StatusTypeDef HAL_MMC_ConfigWideBusOperation(MMC_HandleTypeDef *hmmc, uint32_t WideMode); -/** - * @} - */ - -/** @defgroup MMC_Exported_Functions_Group4 MMC card related functions - * @{ - */ -HAL_MMC_CardStateTypeDef HAL_MMC_GetCardState(MMC_HandleTypeDef *hmmc); -HAL_StatusTypeDef HAL_MMC_GetCardCID(MMC_HandleTypeDef *hmmc, HAL_MMC_CardCIDTypeDef *pCID); -HAL_StatusTypeDef HAL_MMC_GetCardCSD(MMC_HandleTypeDef *hmmc, HAL_MMC_CardCSDTypeDef *pCSD); -HAL_StatusTypeDef HAL_MMC_GetCardInfo(MMC_HandleTypeDef *hmmc, HAL_MMC_CardInfoTypeDef *pCardInfo); -/** - * @} - */ - -/** @defgroup MMC_Exported_Functions_Group5 Peripheral State and Errors functions - * @{ - */ -HAL_MMC_StateTypeDef HAL_MMC_GetState(MMC_HandleTypeDef *hmmc); -uint32_t HAL_MMC_GetError(MMC_HandleTypeDef *hmmc); -/** - * @} - */ - -/** @defgroup MMC_Exported_Functions_Group6 Perioheral Abort management - * @{ - */ -HAL_StatusTypeDef HAL_MMC_Abort(MMC_HandleTypeDef *hmmc); -HAL_StatusTypeDef HAL_MMC_Abort_IT(MMC_HandleTypeDef *hmmc); -/** - * @} - */ - -/* Private types -------------------------------------------------------------*/ -/** @defgroup MMC_Private_Types MMC Private Types - * @{ - */ - -/** - * @} - */ - -/* Private defines -----------------------------------------------------------*/ -/** @defgroup MMC_Private_Defines MMC Private Defines - * @{ - */ - -/** - * @} - */ - -/* Private variables ---------------------------------------------------------*/ -/** @defgroup MMC_Private_Variables MMC Private Variables - * @{ - */ - -/** - * @} - */ - -/* Private constants ---------------------------------------------------------*/ -/** @defgroup MMC_Private_Constants MMC Private Constants - * @{ - */ - -/** - * @} - */ - -/* Private macros ------------------------------------------------------------*/ -/** @defgroup MMC_Private_Macros MMC Private Macros - * @{ - */ - -/** - * @} - */ - -/* Private functions prototypes ----------------------------------------------*/ -/** @defgroup MMC_Private_Functions_Prototypes MMC Private Functions Prototypes - * @{ - */ - -/** - * @} - */ - -/* Private functions ---------------------------------------------------------*/ -/** @defgroup MMC_Private_Functions MMC Private Functions - * @{ - */ - -/** - * @} - */ - -/** - * @} - */ - -/** - * @} - */ - -/** - * @} - */ - -#endif /* STM32F103xE || STM32F103xG */ - -#ifdef __cplusplus -} -#endif - - -#endif /* __STM32F1xx_HAL_MMC_H */ - -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_nand.c b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_nand.c index 0509cb6cf12..1896069e27b 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_nand.c +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_nand.c @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_hal_nand.c * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief NAND HAL module driver. * This file provides a generic firmware to drive NAND memories mounted * as external device. @@ -14,7 +14,7 @@ ============================================================================== [..] This driver is a generic layered driver which contains a set of APIs used to - control NAND flash memories. It uses the FSMC layer functions to interface + control NAND flash memories. It uses the FSMC/FSMC layer functions to interface with NAND devices. This driver is used as follows: (+) NAND flash memory configuration sequence using the function HAL_NAND_Init() @@ -25,12 +25,9 @@ structure declared by the function caller. (+) Access NAND flash memory by read/write operations using the functions - HAL_NAND_Read_Page_8b()/HAL_NAND_Read_SpareArea_8b(), - HAL_NAND_Write_Page_8b()/HAL_NAND_Write_SpareArea_8b(), - HAL_NAND_Read_Page_16b()/HAL_NAND_Read_SpareArea_16b(), - HAL_NAND_Write_Page_16b()/HAL_NAND_Write_SpareArea_16b() + HAL_NAND_Read_Page()/HAL_NAND_Read_SpareArea(), HAL_NAND_Write_Page()/HAL_NAND_Write_SpareArea() to read/write page(s)/spare area(s). These functions use specific device - information (Block, page size..) predefined by the user in the NAND_DeviceConfigTypeDef + information (Block, page size..) predefined by the user in the HAL_NAND_Info_TypeDef structure. The read/write address information is contained by the Nand_Address_Typedef structure passed as parameter. @@ -58,7 +55,7 @@ ****************************************************************************** * @attention * - *

© COPYRIGHT(c) 2017 STMicroelectronics

+ *

© COPYRIGHT(c) 2016 STMicroelectronics

* * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: @@ -122,7 +119,16 @@ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ -/* Exported functions --------------------------------------------------------*/ +/** @defgroup NAND_Private_Functions NAND Private Functions + * @{ + */ +static uint32_t NAND_AddressIncrement(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef* Address); +/** + * @} + */ + +/* Exported functions ---------------------------------------------------------*/ + /** @defgroup NAND_Exported_Functions NAND Exported Functions * @{ */ @@ -162,6 +168,7 @@ HAL_StatusTypeDef HAL_NAND_Init(NAND_HandleTypeDef *hnand, FSMC_NAND_PCC_Timing { /* Allocate lock resource and initialize it */ hnand->Lock = HAL_UNLOCKED; + /* Initialize the low level hardware (MSP) */ HAL_NAND_MspInit(hnand); } @@ -284,7 +291,8 @@ void HAL_NAND_IRQHandler(NAND_HandleTypeDef *hnand) /* Clear NAND interrupt FIFO empty pending bit */ __FSMC_NAND_CLEAR_FLAG(hnand->Instance, hnand->Init.NandBank, FSMC_FLAG_FEMPT); - } + } + } /** @@ -330,9 +338,8 @@ __weak void HAL_NAND_ITCallback(NAND_HandleTypeDef *hnand) */ HAL_StatusTypeDef HAL_NAND_Read_ID(NAND_HandleTypeDef *hnand, NAND_IDTypeDef *pNAND_ID) { - __IO uint32_t data = 0U; - __IO uint32_t data1 = 0U; - uint32_t deviceaddress = 0U; + __IO uint32_t data = 0; + uint32_t deviceaddress = 0; /* Process Locked */ __HAL_LOCK(hnand); @@ -360,34 +367,20 @@ HAL_StatusTypeDef HAL_NAND_Read_ID(NAND_HandleTypeDef *hnand, NAND_IDTypeDef *pN *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_READID; *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00; - /* Read the electronic signature from NAND flash */ - if (hnand->Init.MemoryDataWidth == FSMC_NAND_PCC_MEM_BUS_WIDTH_8) - { - data = *(__IO uint32_t *)deviceaddress; - - /* Return the data read */ - pNAND_ID->Maker_Id = ADDR_1ST_CYCLE(data); - pNAND_ID->Device_Id = ADDR_2ND_CYCLE(data); - pNAND_ID->Third_Id = ADDR_3RD_CYCLE(data); - pNAND_ID->Fourth_Id = ADDR_4TH_CYCLE(data); - } - else - { - data = *(__IO uint32_t *)deviceaddress; - data1 = *((__IO uint32_t *)deviceaddress + 4U); - - /* Return the data read */ - pNAND_ID->Maker_Id = ADDR_1ST_CYCLE(data); - pNAND_ID->Device_Id = ADDR_3RD_CYCLE(data); - pNAND_ID->Third_Id = ADDR_1ST_CYCLE(data1); - pNAND_ID->Fourth_Id = ADDR_3RD_CYCLE(data1); - } + /* Read the electronic signature from NAND flash */ + data = *(__IO uint32_t *)deviceaddress; + + /* Return the data read */ + pNAND_ID->Maker_Id = ADDR_1st_CYCLE(data); + pNAND_ID->Device_Id = ADDR_2nd_CYCLE(data); + pNAND_ID->Third_Id = ADDR_3rd_CYCLE(data); + pNAND_ID->Fourth_Id = ADDR_4th_CYCLE(data); /* Update the NAND controller state */ hnand->State = HAL_NAND_STATE_READY; /* Process unlocked */ - __HAL_UNLOCK(hnand); + __HAL_UNLOCK(hnand); return HAL_OK; } @@ -400,18 +393,18 @@ HAL_StatusTypeDef HAL_NAND_Read_ID(NAND_HandleTypeDef *hnand, NAND_IDTypeDef *pN */ HAL_StatusTypeDef HAL_NAND_Reset(NAND_HandleTypeDef *hnand) { - uint32_t deviceaddress = 0U; - + uint32_t deviceaddress = 0; + /* Process Locked */ __HAL_LOCK(hnand); - + /* Check the NAND controller state */ if(hnand->State == HAL_NAND_STATE_BUSY) { return HAL_BUSY; } - /* Identify the device address */ + /* Identify the device address */ if(hnand->Init.NandBank == FSMC_NAND_BANK2) { deviceaddress = NAND_DEVICE1; @@ -421,45 +414,25 @@ HAL_StatusTypeDef HAL_NAND_Reset(NAND_HandleTypeDef *hnand) deviceaddress = NAND_DEVICE2; } - /* Update the NAND controller state */ + /* Update the NAND controller state */ hnand->State = HAL_NAND_STATE_BUSY; /* Send NAND reset command */ *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = 0xFF; - - - /* Update the NAND controller state */ + + + /* Update the NAND controller state */ hnand->State = HAL_NAND_STATE_READY; /* Process unlocked */ - __HAL_UNLOCK(hnand); - - return HAL_OK; - -} - -/** - * @brief Configure the device: Enter the physical parameters of the device - * @param hnand: pointer to a NAND_HandleTypeDef structure that contains - * the configuration information for NAND module. - * @param pDeviceConfig : pointer to NAND_DeviceConfigTypeDef structure - * @retval HAL status - */ -HAL_StatusTypeDef HAL_NAND_ConfigDevice(NAND_HandleTypeDef *hnand, NAND_DeviceConfigTypeDef *pDeviceConfig) -{ - hnand->Config.PageSize = pDeviceConfig->PageSize; - hnand->Config.SpareAreaSize = pDeviceConfig->SpareAreaSize; - hnand->Config.BlockSize = pDeviceConfig->BlockSize; - hnand->Config.BlockNbr = pDeviceConfig->BlockNbr; - hnand->Config.PlaneSize = pDeviceConfig->PlaneSize; - hnand->Config.PlaneNbr = pDeviceConfig->PlaneNbr; - hnand->Config.ExtraCommandEnable = pDeviceConfig->ExtraCommandEnable; + __HAL_UNLOCK(hnand); return HAL_OK; + } /** - * @brief Read Page(s) from NAND memory block (8-bits addressing) + * @brief Read Page(s) from NAND memory block * @param hnand: pointer to a NAND_HandleTypeDef structure that contains * the configuration information for NAND module. * @param pAddress : pointer to NAND address structure @@ -467,142 +440,12 @@ HAL_StatusTypeDef HAL_NAND_ConfigDevice(NAND_HandleTypeDef *hnand, NAND_DeviceC * @param NumPageToRead : number of pages to read from block * @retval HAL status */ -HAL_StatusTypeDef HAL_NAND_Read_Page_8b(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, uint8_t *pBuffer, uint32_t NumPageToRead) +HAL_StatusTypeDef HAL_NAND_Read_Page(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, uint8_t *pBuffer, uint32_t NumPageToRead) { - __IO uint32_t index = 0U; - uint32_t tickstart = 0U; - uint32_t deviceaddress = 0U, size = 0U, numPagesRead = 0U, nandaddress = 0U; - - /* Process Locked */ - __HAL_LOCK(hnand); - - /* Check the NAND controller state */ - if(hnand->State == HAL_NAND_STATE_BUSY) - { - return HAL_BUSY; - } - - /* Identify the device address */ - if(hnand->Init.NandBank == FSMC_NAND_BANK2) - { - deviceaddress = NAND_DEVICE1; - } - else - { - deviceaddress = NAND_DEVICE2; - } - - /* Update the NAND controller state */ - hnand->State = HAL_NAND_STATE_BUSY; - - /* NAND raw address calculation */ - nandaddress = ARRAY_ADDRESS(pAddress, hnand); - - /* Page(s) read loop */ - while((NumPageToRead != 0U) && (nandaddress < ((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)))) - { - /* update the buffer size */ - size = (hnand->Config.PageSize) + ((hnand->Config.PageSize) * numPagesRead); - - /* Send read page command sequence */ - *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_A; - - /* Cards with page size <= 512 bytes */ - if((hnand->Config.PageSize) <= 512U) - { - if (((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) <= 65535U) - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00; - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - } - else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00; - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); - } - } - else /* (hnand->Config.PageSize) > 512 */ - { - if (((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) <= 65535U) - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00; - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00; - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - } - else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00; - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00; - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); - } - } - - *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_TRUE1; - - /* Check if an extra command is needed for reading pages */ - if(hnand->Config.ExtraCommandEnable == ENABLE) - { - /* Get tick */ - tickstart = HAL_GetTick(); - - /* Read status until NAND is ready */ - while(HAL_NAND_Read_Status(hnand) != NAND_READY) - { - if((HAL_GetTick() - tickstart ) > NAND_WRITE_TIMEOUT) - { - return HAL_TIMEOUT; - } - } - - /* Go back to read mode */ - *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = ((uint8_t)0x00); - } - - /* Get Data into Buffer */ - for(; index < size; index++) - { - *(uint8_t *)pBuffer++ = *(uint8_t *)deviceaddress; - } - - /* Increment read pages number */ - numPagesRead++; - - /* Decrement pages to read */ - NumPageToRead--; - - /* Increment the NAND address */ - nandaddress = (uint32_t)(nandaddress + 1U); - } - - /* Update the NAND controller state */ - hnand->State = HAL_NAND_STATE_READY; - - /* Process unlocked */ - __HAL_UNLOCK(hnand); - - return HAL_OK; -} - -/** - * @brief Read Page(s) from NAND memory block (16-bits addressing) - * @param hnand: pointer to a NAND_HandleTypeDef structure that contains - * the configuration information for NAND module. - * @param pAddress : pointer to NAND address structure - * @param pBuffer : pointer to destination read buffer. pBuffer should be 16bits aligned - * @param NumPageToRead : number of pages to read from block - * @retval HAL status - */ -HAL_StatusTypeDef HAL_NAND_Read_Page_16b(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, uint16_t *pBuffer, uint32_t NumPageToRead) -{ - __IO uint32_t index = 0U; - uint32_t tickstart = 0U; - uint32_t deviceaddress = 0U, size = 0U, numPagesRead = 0U, nandaddress = 0U; + __IO uint32_t index = 0; + uint32_t deviceaddress = 0, size = 0, numpagesread = 0, addressstatus = NAND_VALID_ADDRESS; + NAND_AddressTypeDef nandaddress; + uint32_t addressoffset = 0; /* Process Locked */ __HAL_LOCK(hnand); @@ -626,88 +469,50 @@ HAL_StatusTypeDef HAL_NAND_Read_Page_16b(NAND_HandleTypeDef *hnand, NAND_Address /* Update the NAND controller state */ hnand->State = HAL_NAND_STATE_BUSY; - /* NAND raw address calculation */ - nandaddress = ARRAY_ADDRESS(pAddress, hnand); + /* Save the content of pAddress as it will be modified */ + nandaddress.Block = pAddress->Block; + nandaddress.Page = pAddress->Page; + nandaddress.Zone = pAddress->Zone; /* Page(s) read loop */ - while((NumPageToRead != 0U) && (nandaddress < ((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)))) - { + while((NumPageToRead != 0) && (addressstatus == NAND_VALID_ADDRESS)) + { /* update the buffer size */ - size = (hnand->Config.PageSize) + ((hnand->Config.PageSize) * numPagesRead); + size = hnand->Info.PageSize + ((hnand->Info.PageSize) * numpagesread); + + /* Get the address offset */ + addressoffset = ARRAY_ADDRESS(&nandaddress, hnand); /* Send read page command sequence */ *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_A; - - /* Cards with page size <= 512 bytes */ - if((hnand->Config.PageSize) <= 512U) - { - if (((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) <= 65535U) - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00; - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - } - else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00; - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); - } - } - else /* (hnand->Config.PageSize) > 512 */ + + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00; + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1st_CYCLE(addressoffset); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2nd_CYCLE(addressoffset); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3rd_CYCLE(addressoffset); + + /* for 512 and 1 GB devices, 4th cycle is required */ + if(hnand->Info.BlockNbr >= 1024) { - if (((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) <= 65535U) - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00; - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00; - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - } - else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00; - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00; - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); - } + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_4th_CYCLE(addressoffset); } *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_TRUE1; - - if(hnand->Config.ExtraCommandEnable == ENABLE) - { - /* Get tick */ - tickstart = HAL_GetTick(); - - /* Read status until NAND is ready */ - while(HAL_NAND_Read_Status(hnand) != NAND_READY) - { - if((HAL_GetTick() - tickstart ) > NAND_WRITE_TIMEOUT) - { - return HAL_TIMEOUT; - } - } - /* Go back to read mode */ - *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = ((uint8_t)0x00); - } - /* Get Data into Buffer */ for(; index < size; index++) { - *(uint16_t *)pBuffer++ = *(uint16_t *)deviceaddress; + *(uint8_t *)pBuffer++ = *(uint8_t *)deviceaddress; } /* Increment read pages number */ - numPagesRead++; + numpagesread++; /* Decrement pages to read */ NumPageToRead--; /* Increment the NAND address */ - nandaddress = (uint32_t)(nandaddress + 1U); + addressstatus = NAND_AddressIncrement(hnand, &nandaddress); } /* Update the NAND controller state */ @@ -717,10 +522,11 @@ HAL_StatusTypeDef HAL_NAND_Read_Page_16b(NAND_HandleTypeDef *hnand, NAND_Address __HAL_UNLOCK(hnand); return HAL_OK; + } /** - * @brief Write Page(s) to NAND memory block (8-bits addressing) + * @brief Write Page(s) to NAND memory block * @param hnand: pointer to a NAND_HandleTypeDef structure that contains * the configuration information for NAND module. * @param pAddress : pointer to NAND address structure @@ -728,11 +534,13 @@ HAL_StatusTypeDef HAL_NAND_Read_Page_16b(NAND_HandleTypeDef *hnand, NAND_Address * @param NumPageToWrite : number of pages to write to block * @retval HAL status */ -HAL_StatusTypeDef HAL_NAND_Write_Page_8b(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, uint8_t *pBuffer, uint32_t NumPageToWrite) +HAL_StatusTypeDef HAL_NAND_Write_Page(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, uint8_t *pBuffer, uint32_t NumPageToWrite) { - __IO uint32_t index = 0U; - uint32_t tickstart = 0U; - uint32_t deviceaddress = 0U, size = 0U, numPagesWritten = 0U, nandaddress = 0U; + __IO uint32_t index = 0; + uint32_t tickstart = 0; + uint32_t deviceaddress = 0 , size = 0, numpageswritten = 0, addressstatus = NAND_VALID_ADDRESS; + NAND_AddressTypeDef nandaddress; + uint32_t addressoffset = 0; /* Process Locked */ __HAL_LOCK(hnand); @@ -756,56 +564,35 @@ HAL_StatusTypeDef HAL_NAND_Write_Page_8b(NAND_HandleTypeDef *hnand, NAND_Address /* Update the NAND controller state */ hnand->State = HAL_NAND_STATE_BUSY; - /* NAND raw address calculation */ - nandaddress = ARRAY_ADDRESS(pAddress, hnand); + /* Save the content of pAddress as it will be modified */ + nandaddress.Block = pAddress->Block; + nandaddress.Page = pAddress->Page; + nandaddress.Zone = pAddress->Zone; /* Page(s) write loop */ - while((NumPageToWrite != 0U) && (nandaddress < ((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)))) - { + while((NumPageToWrite != 0) && (addressstatus == NAND_VALID_ADDRESS)) + { /* update the buffer size */ - size = hnand->Config.PageSize + ((hnand->Config.PageSize) * numPagesWritten); + size = hnand->Info.PageSize + ((hnand->Info.PageSize) * numpageswritten); + + /* Get the address offset */ + addressoffset = ARRAY_ADDRESS(&nandaddress, hnand); /* Send write page command sequence */ *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_A; *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_WRITE0; - /* Cards with page size <= 512 bytes */ - if((hnand->Config.PageSize) <= 512U) - { - if (((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) <= 65535U) - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00; - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - } - else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00; - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); - } - } - else /* (hnand->Config.PageSize) > 512 */ + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00; + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1st_CYCLE(addressoffset); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2nd_CYCLE(addressoffset); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3rd_CYCLE(addressoffset); + + /* for 512 and 1 GB devices, 4th cycle is required */ + if(hnand->Info.BlockNbr >= 1024) { - if (((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) <= 65535U) - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00; - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00; - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - } - else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00; - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00; - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); - } + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_4th_CYCLE(addressoffset); } - /* Write data to memory */ for(; index < size; index++) { @@ -814,164 +601,39 @@ HAL_StatusTypeDef HAL_NAND_Write_Page_8b(NAND_HandleTypeDef *hnand, NAND_Address *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_WRITE_TRUE1; - /* Read status until NAND is ready */ - while(HAL_NAND_Read_Status(hnand) != NAND_READY) - { - /* Get tick */ - tickstart = HAL_GetTick(); - - if((HAL_GetTick() - tickstart ) > NAND_WRITE_TIMEOUT) - { - return HAL_TIMEOUT; - } - } - - /* Increment written pages number */ - numPagesWritten++; - - /* Decrement pages to write */ - NumPageToWrite--; - - /* Increment the NAND address */ - nandaddress = (uint32_t)(nandaddress + 1U); - } - - /* Update the NAND controller state */ - hnand->State = HAL_NAND_STATE_READY; - - /* Process unlocked */ - __HAL_UNLOCK(hnand); - - return HAL_OK; -} - -/** - * @brief Write Page(s) to NAND memory block (16-bits addressing) - * @param hnand: pointer to a NAND_HandleTypeDef structure that contains - * the configuration information for NAND module. - * @param pAddress : pointer to NAND address structure - * @param pBuffer : pointer to source buffer to write. pBuffer should be 16bits aligned - * @param NumPageToWrite : number of pages to write to block - * @retval HAL status - */ -HAL_StatusTypeDef HAL_NAND_Write_Page_16b(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, uint16_t *pBuffer, uint32_t NumPageToWrite) -{ - __IO uint32_t index = 0U; - uint32_t tickstart = 0U; - uint32_t deviceaddress = 0U, size = 0U, numPagesWritten = 0U, nandaddress = 0U; - - /* Process Locked */ - __HAL_LOCK(hnand); - - /* Check the NAND controller state */ - if(hnand->State == HAL_NAND_STATE_BUSY) - { - return HAL_BUSY; - } - - /* Identify the device address */ - if(hnand->Init.NandBank == FSMC_NAND_BANK2) - { - deviceaddress = NAND_DEVICE1; - } - else - { - deviceaddress = NAND_DEVICE2; - } - - /* Update the NAND controller state */ - hnand->State = HAL_NAND_STATE_BUSY; - - /* NAND raw address calculation */ - nandaddress = ARRAY_ADDRESS(pAddress, hnand); - - /* Page(s) write loop */ - while((NumPageToWrite != 0U) && (nandaddress < ((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)))) - { - /* update the buffer size */ - size = (hnand->Config.PageSize) + ((hnand->Config.PageSize) * numPagesWritten); - - /* Send write page command sequence */ - *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_A; - *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_WRITE0; - - /* Cards with page size <= 512 bytes */ - if((hnand->Config.PageSize) <= 512U) - { - if (((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) <= 65535U) - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00; - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - } - else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00; - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); - } - } - else /* (hnand->Config.PageSize) > 512 */ - { - if (((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) <= 65535U) - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00; - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00; - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - } - else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00; - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00; - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); - } - } - - /* Write data to memory */ - for(; index < size; index++) - { - *(__IO uint16_t *)deviceaddress = *(uint16_t *)pBuffer++; - } - - *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_WRITE_TRUE1; + /* Get tick */ + tickstart = HAL_GetTick(); /* Read status until NAND is ready */ while(HAL_NAND_Read_Status(hnand) != NAND_READY) { - /* Get tick */ - tickstart = HAL_GetTick(); - if((HAL_GetTick() - tickstart ) > NAND_WRITE_TIMEOUT) { return HAL_TIMEOUT; } - } + } /* Increment written pages number */ - numPagesWritten++; + numpageswritten++; /* Decrement pages to write */ NumPageToWrite--; /* Increment the NAND address */ - nandaddress = (uint32_t)(nandaddress + 1U); + addressstatus = NAND_AddressIncrement(hnand, &nandaddress); } /* Update the NAND controller state */ hnand->State = HAL_NAND_STATE_READY; /* Process unlocked */ - __HAL_UNLOCK(hnand); + __HAL_UNLOCK(hnand); return HAL_OK; } /** - * @brief Read Spare area(s) from NAND memory (8-bits addressing) + * @brief Read Spare area(s) from NAND memory * @param hnand: pointer to a NAND_HandleTypeDef structure that contains * the configuration information for NAND module. * @param pAddress : pointer to NAND address structure @@ -979,11 +641,12 @@ HAL_StatusTypeDef HAL_NAND_Write_Page_16b(NAND_HandleTypeDef *hnand, NAND_Addres * @param NumSpareAreaToRead: Number of spare area to read * @retval HAL status */ -HAL_StatusTypeDef HAL_NAND_Read_SpareArea_8b(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, uint8_t *pBuffer, uint32_t NumSpareAreaToRead) +HAL_StatusTypeDef HAL_NAND_Read_SpareArea(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, uint8_t *pBuffer, uint32_t NumSpareAreaToRead) { - __IO uint32_t index = 0U; - uint32_t tickstart = 0U; - uint32_t deviceaddress = 0U, size = 0U, numSpareAreaRead = 0U, nandaddress = 0U, columnaddress = 0U; + __IO uint32_t index = 0; + uint32_t deviceaddress = 0, size = 0, num_spare_area_read = 0, addressstatus = NAND_VALID_ADDRESS; + NAND_AddressTypeDef nandaddress; + uint32_t addressoffset = 0; /* Process Locked */ __HAL_LOCK(hnand); @@ -1007,230 +670,50 @@ HAL_StatusTypeDef HAL_NAND_Read_SpareArea_8b(NAND_HandleTypeDef *hnand, NAND_Add /* Update the NAND controller state */ hnand->State = HAL_NAND_STATE_BUSY; - /* NAND raw address calculation */ - nandaddress = ARRAY_ADDRESS(pAddress, hnand); - - /* Column in page address */ - columnaddress = COLUMN_ADDRESS(hnand); + /* Save the content of pAddress as it will be modified */ + nandaddress.Block = pAddress->Block; + nandaddress.Page = pAddress->Page; + nandaddress.Zone = pAddress->Zone; /* Spare area(s) read loop */ - while((NumSpareAreaToRead != 0U) && (nandaddress < ((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)))) + while((NumSpareAreaToRead != 0) && (addressstatus == NAND_VALID_ADDRESS)) { /* update the buffer size */ - size = (hnand->Config.SpareAreaSize) + ((hnand->Config.SpareAreaSize) * numSpareAreaRead); - - /* Cards with page size <= 512 bytes */ - if((hnand->Config.PageSize) <= 512U) - { - /* Send read spare area command sequence */ - *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_C; - - if (((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) <= 65535U) - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00; - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - } - else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00; - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); - } - } - else /* (hnand->Config.PageSize) > 512 */ - { - /* Send read spare area command sequence */ - *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_A; - - if (((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) <= 65535U) - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_1ST_CYCLE(columnaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_2ND_CYCLE(columnaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - } - else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_1ST_CYCLE(columnaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_2ND_CYCLE(columnaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); - } - } + size = (hnand->Info.SpareAreaSize) + ((hnand->Info.SpareAreaSize) * num_spare_area_read); - *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_TRUE1; - - if(hnand->Config.ExtraCommandEnable == ENABLE) - { - /* Get tick */ - tickstart = HAL_GetTick(); - - /* Read status until NAND is ready */ - while(HAL_NAND_Read_Status(hnand) != NAND_READY) - { - if((HAL_GetTick() - tickstart ) > NAND_WRITE_TIMEOUT) - { - return HAL_TIMEOUT; - } - } - - /* Go back to read mode */ - *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = ((uint8_t)0x00); - } + /* Get the address offset */ + addressoffset = ARRAY_ADDRESS(&nandaddress, hnand); - /* Get Data into Buffer */ - for(; index < size; index++) - { - *(uint8_t *)pBuffer++ = *(uint8_t *)deviceaddress; - } - - /* Increment read spare areas number */ - numSpareAreaRead++; - - /* Decrement spare areas to read */ - NumSpareAreaToRead--; - - /* Increment the NAND address */ - nandaddress = (uint32_t)(nandaddress + 1U); - } - - /* Update the NAND controller state */ - hnand->State = HAL_NAND_STATE_READY; - - /* Process unlocked */ - __HAL_UNLOCK(hnand); - - return HAL_OK; -} + /* Send read spare area command sequence */ + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_C; -/** - * @brief Read Spare area(s) from NAND memory (16-bits addressing) - * @param hnand: pointer to a NAND_HandleTypeDef structure that contains - * the configuration information for NAND module. - * @param pAddress : pointer to NAND address structure - * @param pBuffer: pointer to source buffer to write. pBuffer should be 16bits aligned. - * @param NumSpareAreaToRead: Number of spare area to read - * @retval HAL status -*/ -HAL_StatusTypeDef HAL_NAND_Read_SpareArea_16b(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, uint16_t *pBuffer, uint32_t NumSpareAreaToRead) -{ - __IO uint32_t index = 0U; - uint32_t tickstart = 0U; - uint32_t deviceaddress = 0U, size = 0U, numSpareAreaRead = 0U, nandaddress = 0U, columnaddress = 0U; - - /* Process Locked */ - __HAL_LOCK(hnand); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00; + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1st_CYCLE(addressoffset); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2nd_CYCLE(addressoffset); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3rd_CYCLE(addressoffset); - /* Check the NAND controller state */ - if(hnand->State == HAL_NAND_STATE_BUSY) - { - return HAL_BUSY; - } - - /* Identify the device address */ - if(hnand->Init.NandBank == FSMC_NAND_BANK2) - { - deviceaddress = NAND_DEVICE1; - } - else - { - deviceaddress = NAND_DEVICE2; - } - - /* Update the NAND controller state */ - hnand->State = HAL_NAND_STATE_BUSY; - - /* NAND raw address calculation */ - nandaddress = ARRAY_ADDRESS(pAddress, hnand); - - /* Column in page address */ - columnaddress = (uint32_t)(COLUMN_ADDRESS(hnand) * 2U); - - /* Spare area(s) read loop */ - while((NumSpareAreaToRead != 0U) && (nandaddress < ((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)))) - { - /* update the buffer size */ - size = (hnand->Config.SpareAreaSize) + ((hnand->Config.SpareAreaSize) * numSpareAreaRead); - - /* Cards with page size <= 512 bytes */ - if((hnand->Config.PageSize) <= 512U) - { - /* Send read spare area command sequence */ - *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_C; - - if (((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) <= 65535U) - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00; - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - } - else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00; - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); - } - } - else /* (hnand->Config.PageSize) > 512 */ + /* for 512 and 1 GB devices, 4th cycle is required */ + if(hnand->Info.BlockNbr >= 1024) { - /* Send read spare area command sequence */ - *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_A; - - if (((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) <= 65535U) - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_1ST_CYCLE(columnaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_2ND_CYCLE(columnaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - } - else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_1ST_CYCLE(columnaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_2ND_CYCLE(columnaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); - } - } - - *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_TRUE1; + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_4th_CYCLE(addressoffset); + } - if(hnand->Config.ExtraCommandEnable == ENABLE) - { - /* Get tick */ - tickstart = HAL_GetTick(); - - /* Read status until NAND is ready */ - while(HAL_NAND_Read_Status(hnand) != NAND_READY) - { - if((HAL_GetTick() - tickstart ) > NAND_WRITE_TIMEOUT) - { - return HAL_TIMEOUT; - } - } - - /* Go back to read mode */ - *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = ((uint8_t)0x00); - } + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_TRUE1; /* Get Data into Buffer */ - for(; index < size; index++) + for ( ;index < size; index++) { - *(uint16_t *)pBuffer++ = *(uint16_t *)deviceaddress; + *(uint8_t *)pBuffer++ = *(uint8_t *)deviceaddress; } /* Increment read spare areas number */ - numSpareAreaRead++; + num_spare_area_read++; /* Decrement spare areas to read */ NumSpareAreaToRead--; /* Increment the NAND address */ - nandaddress = (uint32_t)(nandaddress + 1U); + addressstatus = NAND_AddressIncrement(hnand, &nandaddress); } /* Update the NAND controller state */ @@ -1243,7 +726,7 @@ HAL_StatusTypeDef HAL_NAND_Read_SpareArea_16b(NAND_HandleTypeDef *hnand, NAND_Ad } /** - * @brief Write Spare area(s) to NAND memory (8-bits addressing) + * @brief Write Spare area(s) to NAND memory * @param hnand: pointer to a NAND_HandleTypeDef structure that contains * the configuration information for NAND module. * @param pAddress : pointer to NAND address structure @@ -1251,11 +734,13 @@ HAL_StatusTypeDef HAL_NAND_Read_SpareArea_16b(NAND_HandleTypeDef *hnand, NAND_Ad * @param NumSpareAreaTowrite : number of spare areas to write to block * @retval HAL status */ -HAL_StatusTypeDef HAL_NAND_Write_SpareArea_8b(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, uint8_t *pBuffer, uint32_t NumSpareAreaTowrite) +HAL_StatusTypeDef HAL_NAND_Write_SpareArea(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, uint8_t *pBuffer, uint32_t NumSpareAreaTowrite) { - __IO uint32_t index = 0U; - uint32_t tickstart = 0U; - uint32_t deviceaddress = 0U, size = 0U, numSpareAreaWritten = 0U, nandaddress = 0U, columnaddress = 0U; + __IO uint32_t index = 0; + uint32_t tickstart = 0; + uint32_t deviceaddress = 0, size = 0, num_spare_area_written = 0, addressstatus = NAND_VALID_ADDRESS; + NAND_AddressTypeDef nandaddress; + uint32_t addressoffset = 0; /* Process Locked */ __HAL_LOCK(hnand); @@ -1279,60 +764,33 @@ HAL_StatusTypeDef HAL_NAND_Write_SpareArea_8b(NAND_HandleTypeDef *hnand, NAND_Ad /* Update the FSMC_NAND controller state */ hnand->State = HAL_NAND_STATE_BUSY; - /* Page address calculation */ - nandaddress = ARRAY_ADDRESS(pAddress, hnand); - - /* Column in page address */ - columnaddress = COLUMN_ADDRESS(hnand); + /* Save the content of pAddress as it will be modified */ + nandaddress.Block = pAddress->Block; + nandaddress.Page = pAddress->Page; + nandaddress.Zone = pAddress->Zone; /* Spare area(s) write loop */ - while((NumSpareAreaTowrite != 0U) && (nandaddress < ((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)))) - { + while((NumSpareAreaTowrite != 0) && (addressstatus == NAND_VALID_ADDRESS)) + { /* update the buffer size */ - size = (hnand->Config.SpareAreaSize) + ((hnand->Config.SpareAreaSize) * numSpareAreaWritten); + size = (hnand->Info.SpareAreaSize) + ((hnand->Info.SpareAreaSize) * num_spare_area_written); - /* Cards with page size <= 512 bytes */ - if((hnand->Config.PageSize) <= 512U) - { - /* Send write Spare area command sequence */ - *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_C; - *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_WRITE0; - - if (((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) <= 65535U) - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00; - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - } - else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00; - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); - } - } - else /* (hnand->Config.PageSize) > 512 */ - { - /* Send write Spare area command sequence */ - *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_A; - *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_WRITE0; + /* Get the address offset */ + addressoffset = ARRAY_ADDRESS(&nandaddress, hnand); - if (((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) <= 65535U) - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_1ST_CYCLE(columnaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_2ND_CYCLE(columnaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - } - else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_1ST_CYCLE(columnaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_2ND_CYCLE(columnaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); - } + /* Send write Spare area command sequence */ + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_C; + *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_WRITE0; + + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00; + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1st_CYCLE(addressoffset); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2nd_CYCLE(addressoffset); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3rd_CYCLE(addressoffset); + + /* for 512 and 1 GB devices, 4th cycle is required */ + if(hnand->Info.BlockNbr >= 1024) + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_4th_CYCLE(addressoffset); } /* Write data to memory */ @@ -1356,13 +814,13 @@ HAL_StatusTypeDef HAL_NAND_Write_SpareArea_8b(NAND_HandleTypeDef *hnand, NAND_Ad } /* Increment written spare areas number */ - numSpareAreaWritten++; + num_spare_area_written++; /* Decrement spare areas to write */ NumSpareAreaTowrite--; /* Increment the NAND address */ - nandaddress = (uint32_t)(nandaddress + 1U); + addressstatus = NAND_AddressIncrement(hnand, &nandaddress); } /* Update the NAND controller state */ @@ -1371,138 +829,6 @@ HAL_StatusTypeDef HAL_NAND_Write_SpareArea_8b(NAND_HandleTypeDef *hnand, NAND_Ad /* Process unlocked */ __HAL_UNLOCK(hnand); - return HAL_OK; -} - -/** - * @brief Write Spare area(s) to NAND memory (16-bits addressing) - * @param hnand: pointer to a NAND_HandleTypeDef structure that contains - * the configuration information for NAND module. - * @param pAddress : pointer to NAND address structure - * @param pBuffer : pointer to source buffer to write. pBuffer should be 16bits aligned. - * @param NumSpareAreaTowrite : number of spare areas to write to block - * @retval HAL status - */ -HAL_StatusTypeDef HAL_NAND_Write_SpareArea_16b(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, uint16_t *pBuffer, uint32_t NumSpareAreaTowrite) -{ - __IO uint32_t index = 0U; - uint32_t tickstart = 0U; - uint32_t deviceaddress = 0U, size = 0U, numSpareAreaWritten = 0U, nandaddress = 0U, columnaddress = 0U; - - /* Process Locked */ - __HAL_LOCK(hnand); - - /* Check the NAND controller state */ - if(hnand->State == HAL_NAND_STATE_BUSY) - { - return HAL_BUSY; - } - - /* Identify the device address */ - if(hnand->Init.NandBank == FSMC_NAND_BANK2) - { - deviceaddress = NAND_DEVICE1; - } - else - { - deviceaddress = NAND_DEVICE2; - } - - /* Update the FSMC_NAND controller state */ - hnand->State = HAL_NAND_STATE_BUSY; - - /* NAND raw address calculation */ - nandaddress = ARRAY_ADDRESS(pAddress, hnand); - - /* Column in page address */ - columnaddress = (uint32_t)(COLUMN_ADDRESS(hnand) * 2U); - - /* Spare area(s) write loop */ - while((NumSpareAreaTowrite != 0U) && (nandaddress < ((hnand->Config.BlockSize) * (hnand->Config.BlockNbr)))) - { - /* update the buffer size */ - size = (hnand->Config.SpareAreaSize) + ((hnand->Config.SpareAreaSize) * numSpareAreaWritten); - - /* Cards with page size <= 512 bytes */ - if((hnand->Config.PageSize) <= 512U) - { - /* Send write Spare area command sequence */ - *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_C; - *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_WRITE0; - - if (((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) <= 65535U) - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00; - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - } - else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00; - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); - } - } - else /* (hnand->Config.PageSize) > 512 */ - { - /* Send write Spare area command sequence */ - *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_A; - *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_WRITE0; - - if (((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) <= 65535U) - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_1ST_CYCLE(columnaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_2ND_CYCLE(columnaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - } - else /* ((hnand->Config.BlockSize)*(hnand->Config.BlockNbr)) > 65535 */ - { - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_1ST_CYCLE(columnaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = COLUMN_2ND_CYCLE(columnaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(nandaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(nandaddress); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(nandaddress); - } - } - - /* Write data to memory */ - for(; index < size; index++) - { - *(__IO uint16_t *)deviceaddress = *(uint16_t *)pBuffer++; - } - - *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_WRITE_TRUE1; - - /* Read status until NAND is ready */ - while(HAL_NAND_Read_Status(hnand) != NAND_READY) - { - /* Get tick */ - tickstart = HAL_GetTick(); - - if((HAL_GetTick() - tickstart ) > NAND_WRITE_TIMEOUT) - { - return HAL_TIMEOUT; - } - } - - /* Increment written spare areas number */ - numSpareAreaWritten++; - - /* Decrement spare areas to write */ - NumSpareAreaTowrite--; - - /* Increment the NAND address */ - nandaddress = (uint32_t)(nandaddress + 1U); - } - - /* Update the NAND controller state */ - hnand->State = HAL_NAND_STATE_READY; - - /* Process unlocked */ - __HAL_UNLOCK(hnand); - return HAL_OK; } @@ -1515,8 +841,8 @@ HAL_StatusTypeDef HAL_NAND_Write_SpareArea_16b(NAND_HandleTypeDef *hnand, NAND_A */ HAL_StatusTypeDef HAL_NAND_Erase_Block(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress) { - uint32_t deviceaddress = 0U; - uint32_t tickstart = 0U; + uint32_t deviceaddress = 0; + uint32_t tickstart = 0; /* Process Locked */ __HAL_LOCK(hnand); @@ -1543,9 +869,15 @@ HAL_StatusTypeDef HAL_NAND_Erase_Block(NAND_HandleTypeDef *hnand, NAND_AddressTy /* Send Erase block command sequence */ *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_ERASE0; - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1ST_CYCLE(ARRAY_ADDRESS(pAddress, hnand)); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2ND_CYCLE(ARRAY_ADDRESS(pAddress, hnand)); - *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3RD_CYCLE(ARRAY_ADDRESS(pAddress, hnand)); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1st_CYCLE(ARRAY_ADDRESS(pAddress, hnand)); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2nd_CYCLE(ARRAY_ADDRESS(pAddress, hnand)); + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3rd_CYCLE(ARRAY_ADDRESS(pAddress, hnand)); + + /* for 512 and 1 GB devices, 4th cycle is required */ + if(hnand->Info.BlockNbr >= 1024) + { + *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_4th_CYCLE(ARRAY_ADDRESS(pAddress, hnand)); + } *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_ERASE1; @@ -1581,8 +913,8 @@ HAL_StatusTypeDef HAL_NAND_Erase_Block(NAND_HandleTypeDef *hnand, NAND_AddressTy */ uint32_t HAL_NAND_Read_Status(NAND_HandleTypeDef *hnand) { - uint32_t data = 0U; - uint32_t deviceaddress = 0U; + uint32_t data = 0; + uint32_t deviceaddress = 0; /* Identify the device address */ if(hnand->Init.NandBank == FSMC_NAND_BANK2) @@ -1630,17 +962,17 @@ uint32_t HAL_NAND_Address_Inc(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pA pAddress->Page++; /* Check NAND address is valid */ - if(pAddress->Page == hnand->Config.BlockSize) + if(pAddress->Page == hnand->Info.BlockSize) { - pAddress->Page = 0U; + pAddress->Page = 0; pAddress->Block++; - if(pAddress->Block == hnand->Config.PlaneSize) + if(pAddress->Block == hnand->Info.ZoneSize) { - pAddress->Block = 0U; - pAddress->Plane++; + pAddress->Block = 0; + pAddress->Zone++; - if(pAddress->Plane == (hnand->Config.PlaneNbr)) + if(pAddress->Zone == (hnand->Info.ZoneSize/ hnand->Info.BlockNbr)) { status = NAND_INVALID_ADDRESS; } @@ -1692,7 +1024,7 @@ HAL_StatusTypeDef HAL_NAND_ECC_Enable(NAND_HandleTypeDef *hnand) /* Update the NAND state */ hnand->State = HAL_NAND_STATE_READY; - return HAL_OK; + return HAL_OK; } /** @@ -1701,7 +1033,7 @@ HAL_StatusTypeDef HAL_NAND_ECC_Enable(NAND_HandleTypeDef *hnand) * the configuration information for NAND module. * @retval HAL status */ -HAL_StatusTypeDef HAL_NAND_ECC_Disable(NAND_HandleTypeDef *hnand) +HAL_StatusTypeDef HAL_NAND_ECC_Disable(NAND_HandleTypeDef *hnand) { /* Check the NAND controller state */ if(hnand->State == HAL_NAND_STATE_BUSY) @@ -1750,7 +1082,7 @@ HAL_StatusTypeDef HAL_NAND_GetECC(NAND_HandleTypeDef *hnand, uint32_t *ECCval, return status; } - + /** * @} */ @@ -1786,6 +1118,49 @@ HAL_NAND_StateTypeDef HAL_NAND_GetState(NAND_HandleTypeDef *hnand) * @} */ +/** + * @} + */ + +/** @addtogroup NAND_Private_Functions + * @{ + */ + +/** + * @brief Increment the NAND memory address. + * @param hnand: pointer to a NAND_HandleTypeDef structure that contains + * the configuration information for NAND module. + * @param Address: address to be incremented. + * @retval The new status of the increment address operation. It can be: + * - NAND_VALID_ADDRESS: When the new address is valid address + * - NAND_INVALID_ADDRESS: When the new address is invalid address + */ +static uint32_t NAND_AddressIncrement(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef* Address) +{ + uint32_t status = NAND_VALID_ADDRESS; + + Address->Page++; + + if(Address->Page == hnand->Info.BlockSize) + { + Address->Page = 0; + Address->Block++; + + if(Address->Block == hnand->Info.ZoneSize) + { + Address->Block = 0; + Address->Zone++; + + if(Address->Zone == hnand->Info.BlockNbr) + { + status = NAND_INVALID_ADDRESS; + } + } + } + + return (status); +} + /** * @} */ diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_nand.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_nand.h index 88eb5485e4d..0e37fb1fcfb 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_nand.h +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_nand.h @@ -2,13 +2,13 @@ ****************************************************************************** * @file stm32f1xx_hal_nand.h * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief Header file of NAND HAL module. ****************************************************************************** * @attention * - *

© COPYRIGHT(c) 2017 STMicroelectronics

+ *

© COPYRIGHT(c) 2016 STMicroelectronics

* * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: @@ -55,6 +55,69 @@ * @{ */ +/** @addtogroup NAND_Private_Constants + * @{ + */ + +#define NAND_DEVICE1 FSMC_BANK2 +#define NAND_DEVICE2 FSMC_BANK3 +#define NAND_WRITE_TIMEOUT ((uint32_t)1000) + +#define CMD_AREA ((uint32_t)(1<<16)) /* A16 = CLE high */ +#define ADDR_AREA ((uint32_t)(1<<17)) /* A17 = ALE high */ + +#define NAND_CMD_AREA_A ((uint8_t)0x00) +#define NAND_CMD_AREA_B ((uint8_t)0x01) +#define NAND_CMD_AREA_C ((uint8_t)0x50) +#define NAND_CMD_AREA_TRUE1 ((uint8_t)0x30) + +#define NAND_CMD_WRITE0 ((uint8_t)0x80) +#define NAND_CMD_WRITE_TRUE1 ((uint8_t)0x10) +#define NAND_CMD_ERASE0 ((uint8_t)0x60) +#define NAND_CMD_ERASE1 ((uint8_t)0xD0) +#define NAND_CMD_READID ((uint8_t)0x90) +#define NAND_CMD_STATUS ((uint8_t)0x70) +#define NAND_CMD_LOCK_STATUS ((uint8_t)0x7A) +#define NAND_CMD_RESET ((uint8_t)0xFF) + +/* NAND memory status */ +#define NAND_VALID_ADDRESS ((uint32_t)0x00000100) +#define NAND_INVALID_ADDRESS ((uint32_t)0x00000200) +#define NAND_TIMEOUT_ERROR ((uint32_t)0x00000400) +#define NAND_BUSY ((uint32_t)0x00000000) +#define NAND_ERROR ((uint32_t)0x00000001) +#define NAND_READY ((uint32_t)0x00000040) + +/** + * @} + */ + +/** @addtogroup NAND_Private_Macros + * @{ + */ + +/** + * @brief NAND memory address computation. + * @param __ADDRESS__: NAND memory address. + * @param __HANDLE__ : NAND handle. + * @retval NAND Raw address value + */ +#define ARRAY_ADDRESS(__ADDRESS__ , __HANDLE__) ((__ADDRESS__)->Page + \ + (((__ADDRESS__)->Block + (((__ADDRESS__)->Zone) * ((__HANDLE__)->Info.ZoneSize)))* ((__HANDLE__)->Info.BlockSize))) + +/** + * @brief NAND memory address cycling. + * @param __ADDRESS__: NAND memory address. + * @retval NAND address cycling value. + */ +#define ADDR_1st_CYCLE(__ADDRESS__) (uint8_t)(__ADDRESS__) /* 1st addressing cycle */ +#define ADDR_2nd_CYCLE(__ADDRESS__) (uint8_t)((__ADDRESS__) >> 8) /* 2nd addressing cycle */ +#define ADDR_3rd_CYCLE(__ADDRESS__) (uint8_t)((__ADDRESS__) >> 16) /* 3rd addressing cycle */ +#define ADDR_4th_CYCLE(__ADDRESS__) (uint8_t)((__ADDRESS__) >> 24) /* 4th addressing cycle */ + +/** + * @} + */ /* Exported typedef ----------------------------------------------------------*/ /* Exported types ------------------------------------------------------------*/ @@ -67,10 +130,10 @@ */ typedef enum { - HAL_NAND_STATE_RESET = 0x00U, /*!< NAND not yet initialized or disabled */ - HAL_NAND_STATE_READY = 0x01U, /*!< NAND initialized and ready for use */ - HAL_NAND_STATE_BUSY = 0x02U, /*!< NAND internal process is ongoing */ - HAL_NAND_STATE_ERROR = 0x03U /*!< NAND error state */ + HAL_NAND_STATE_RESET = 0x00, /*!< NAND not yet initialized or disabled */ + HAL_NAND_STATE_READY = 0x01, /*!< NAND initialized and ready for use */ + HAL_NAND_STATE_BUSY = 0x02, /*!< NAND internal process is ongoing */ + HAL_NAND_STATE_ERROR = 0x03 /*!< NAND error state */ }HAL_NAND_StateTypeDef; /** @@ -94,11 +157,11 @@ typedef struct */ typedef struct { - uint16_t Page; /*!< NAND memory Page address */ + uint16_t Page; /*!< NAND memory Page address */ - uint16_t Plane; /*!< NAND memory Plane address */ + uint16_t Zone; /*!< NAND memory Zone address */ - uint16_t Block; /*!< NAND memory Block address */ + uint16_t Block; /*!< NAND memory Block address */ }NAND_AddressTypeDef; @@ -107,43 +170,31 @@ typedef struct */ typedef struct { - uint32_t PageSize; /*!< NAND memory page (without spare area) size measured in bytes - for 8 bits adressing or words for 16 bits addressing */ + uint32_t PageSize; /*!< NAND memory page (without spare area) size measured in K. bytes */ - uint32_t SpareAreaSize; /*!< NAND memory spare area size measured in bytes - for 8 bits adressing or words for 16 bits addressing */ - - uint32_t BlockSize; /*!< NAND memory block size measured in number of pages */ + uint32_t SpareAreaSize; /*!< NAND memory spare area size measured in K. bytes */ - uint32_t BlockNbr; /*!< NAND memory number of total blocks */ - - uint32_t PlaneNbr; /*!< NAND memory number of planes */ + uint32_t BlockSize; /*!< NAND memory block size number of pages */ - uint32_t PlaneSize; /*!< NAND memory plane size measured in number of blocks */ + uint32_t BlockNbr; /*!< NAND memory number of blocks */ - FunctionalState ExtraCommandEnable; /*!< NAND extra command needed for Page reading mode. This - parameter is mandatory for some NAND parts after the read - command (NAND_CMD_AREA_TRUE1) and before DATA reading sequence. - Example: Toshiba THTH58BYG3S0HBAI6. - This parameter could be ENABLE or DISABLE - Please check the Read Mode sequnece in the NAND device datasheet */ -}NAND_DeviceConfigTypeDef; + uint32_t ZoneSize; /*!< NAND memory zone size measured in number of blocks */ +}NAND_InfoTypeDef; /** * @brief NAND handle Structure definition */ typedef struct { - FSMC_NAND_TypeDef *Instance; /*!< Register base address */ + FSMC_NAND_TypeDef *Instance; /*!< Register base address */ - FSMC_NAND_InitTypeDef Init; /*!< NAND device control configuration parameters */ - - HAL_LockTypeDef Lock; /*!< NAND locking object */ + FSMC_NAND_InitTypeDef Init; /*!< NAND device control configuration parameters */ - __IO HAL_NAND_StateTypeDef State; /*!< NAND device access state */ + HAL_LockTypeDef Lock; /*!< NAND locking object */ - NAND_DeviceConfigTypeDef Config; /*!< NAND phusical characteristic information structure */ + __IO HAL_NAND_StateTypeDef State; /*!< NAND device access state */ + NAND_InfoTypeDef Info; /*!< NAND characteristic information structure */ }NAND_HandleTypeDef; /** @@ -151,10 +202,10 @@ typedef struct */ /* Exported constants --------------------------------------------------------*/ -/* Exported macros -----------------------------------------------------------*/ +/* Exported macro ------------------------------------------------------------*/ /** @defgroup NAND_Exported_Macros NAND Exported Macros - * @{ - */ + * @{ + */ /** @brief Reset NAND handle state * @param __HANDLE__: specifies the NAND handle. @@ -178,15 +229,10 @@ typedef struct /* Initialization/de-initialization functions ********************************/ HAL_StatusTypeDef HAL_NAND_Init(NAND_HandleTypeDef *hnand, FSMC_NAND_PCC_TimingTypeDef *ComSpace_Timing, FSMC_NAND_PCC_TimingTypeDef *AttSpace_Timing); HAL_StatusTypeDef HAL_NAND_DeInit(NAND_HandleTypeDef *hnand); - -HAL_StatusTypeDef HAL_NAND_ConfigDevice(NAND_HandleTypeDef *hnand, NAND_DeviceConfigTypeDef *pDeviceConfig); - -HAL_StatusTypeDef HAL_NAND_Read_ID(NAND_HandleTypeDef *hnand, NAND_IDTypeDef *pNAND_ID); - -void HAL_NAND_MspInit(NAND_HandleTypeDef *hnand); -void HAL_NAND_MspDeInit(NAND_HandleTypeDef *hnand); -void HAL_NAND_IRQHandler(NAND_HandleTypeDef *hnand); -void HAL_NAND_ITCallback(NAND_HandleTypeDef *hnand); +void HAL_NAND_MspInit(NAND_HandleTypeDef *hnand); +void HAL_NAND_MspDeInit(NAND_HandleTypeDef *hnand); +void HAL_NAND_IRQHandler(NAND_HandleTypeDef *hnand); +void HAL_NAND_ITCallback(NAND_HandleTypeDef *hnand); /** * @} @@ -197,22 +243,15 @@ void HAL_NAND_ITCallback(NAND_HandleTypeDef *hnand); */ /* IO operation functions ****************************************************/ - -HAL_StatusTypeDef HAL_NAND_Reset(NAND_HandleTypeDef *hnand); - -HAL_StatusTypeDef HAL_NAND_Read_Page_8b(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, uint8_t *pBuffer, uint32_t NumPageToRead); -HAL_StatusTypeDef HAL_NAND_Write_Page_8b(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, uint8_t *pBuffer, uint32_t NumPageToWrite); -HAL_StatusTypeDef HAL_NAND_Read_SpareArea_8b(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, uint8_t *pBuffer, uint32_t NumSpareAreaToRead); -HAL_StatusTypeDef HAL_NAND_Write_SpareArea_8b(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, uint8_t *pBuffer, uint32_t NumSpareAreaTowrite); - -HAL_StatusTypeDef HAL_NAND_Read_Page_16b(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, uint16_t *pBuffer, uint32_t NumPageToRead); -HAL_StatusTypeDef HAL_NAND_Write_Page_16b(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, uint16_t *pBuffer, uint32_t NumPageToWrite); -HAL_StatusTypeDef HAL_NAND_Read_SpareArea_16b(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, uint16_t *pBuffer, uint32_t NumSpareAreaToRead); -HAL_StatusTypeDef HAL_NAND_Write_SpareArea_16b(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, uint16_t *pBuffer, uint32_t NumSpareAreaTowrite); - -HAL_StatusTypeDef HAL_NAND_Erase_Block(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress); -uint32_t HAL_NAND_Read_Status(NAND_HandleTypeDef *hnand); -uint32_t HAL_NAND_Address_Inc(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress); +HAL_StatusTypeDef HAL_NAND_Read_ID(NAND_HandleTypeDef *hnand, NAND_IDTypeDef *pNAND_ID); +HAL_StatusTypeDef HAL_NAND_Reset(NAND_HandleTypeDef *hnand); +HAL_StatusTypeDef HAL_NAND_Read_Page(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, uint8_t *pBuffer, uint32_t NumPageToRead); +HAL_StatusTypeDef HAL_NAND_Write_Page(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, uint8_t *pBuffer, uint32_t NumPageToWrite); +HAL_StatusTypeDef HAL_NAND_Read_SpareArea(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, uint8_t *pBuffer, uint32_t NumSpareAreaToRead); +HAL_StatusTypeDef HAL_NAND_Write_SpareArea(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, uint8_t *pBuffer, uint32_t NumSpareAreaTowrite); +HAL_StatusTypeDef HAL_NAND_Erase_Block(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress); +uint32_t HAL_NAND_Read_Status(NAND_HandleTypeDef *hnand); +uint32_t HAL_NAND_Address_Inc(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress); /** * @} @@ -223,9 +262,9 @@ uint32_t HAL_NAND_Address_Inc(NAND_HandleTypeDef *hnand, NAND_AddressT */ /* NAND Control functions ****************************************************/ -HAL_StatusTypeDef HAL_NAND_ECC_Enable(NAND_HandleTypeDef *hnand); -HAL_StatusTypeDef HAL_NAND_ECC_Disable(NAND_HandleTypeDef *hnand); -HAL_StatusTypeDef HAL_NAND_GetECC(NAND_HandleTypeDef *hnand, uint32_t *ECCval, uint32_t Timeout); +HAL_StatusTypeDef HAL_NAND_ECC_Enable(NAND_HandleTypeDef *hnand); +HAL_StatusTypeDef HAL_NAND_ECC_Disable(NAND_HandleTypeDef *hnand); +HAL_StatusTypeDef HAL_NAND_GetECC(NAND_HandleTypeDef *hnand, uint32_t *ECCval, uint32_t Timeout); /** * @} @@ -243,88 +282,6 @@ uint32_t HAL_NAND_Read_Status(NAND_HandleTypeDef *hnand); * @} */ -/** - * @} - */ -/* Private types -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private constants ---------------------------------------------------------*/ -/** @addtogroup NAND_Private_Constants - * @{ - */ - -#define NAND_DEVICE1 FSMC_BANK2 -#define NAND_DEVICE2 FSMC_BANK3 -#define NAND_WRITE_TIMEOUT 1000U - -#define CMD_AREA (1U<<16U) /* A16 = CLE high */ -#define ADDR_AREA (1U<<17U) /* A17 = ALE high */ - -#define NAND_CMD_AREA_A ((uint8_t)0x00) -#define NAND_CMD_AREA_B ((uint8_t)0x01) -#define NAND_CMD_AREA_C ((uint8_t)0x50) -#define NAND_CMD_AREA_TRUE1 ((uint8_t)0x30) - -#define NAND_CMD_WRITE0 ((uint8_t)0x80) -#define NAND_CMD_WRITE_TRUE1 ((uint8_t)0x10) -#define NAND_CMD_ERASE0 ((uint8_t)0x60) -#define NAND_CMD_ERASE1 ((uint8_t)0xD0) -#define NAND_CMD_READID ((uint8_t)0x90) -#define NAND_CMD_STATUS ((uint8_t)0x70) -#define NAND_CMD_LOCK_STATUS ((uint8_t)0x7A) -#define NAND_CMD_RESET ((uint8_t)0xFF) - -/* NAND memory status */ -#define NAND_VALID_ADDRESS 0x00000100U -#define NAND_INVALID_ADDRESS 0x00000200U -#define NAND_TIMEOUT_ERROR 0x00000400U -#define NAND_BUSY 0x00000000U -#define NAND_ERROR 0x00000001U -#define NAND_READY 0x00000040U - -/** - * @} - */ - -/* Private macros ------------------------------------------------------------*/ -/** @addtogroup NAND_Private_Macros - * @{ - */ - -/** - * @brief NAND memory address computation. - * @param __ADDRESS__: NAND memory address. - * @param __HANDLE__ : NAND handle. - * @retval NAND Raw address value - */ -#define ARRAY_ADDRESS(__ADDRESS__ , __HANDLE__) ((__ADDRESS__)->Page + \ - (((__ADDRESS__)->Block + (((__ADDRESS__)->Plane) * ((__HANDLE__)->Config.PlaneSize)))* ((__HANDLE__)->Config.BlockSize))) - -/** - * @brief NAND memory Column address computation. - * @param __HANDLE__: NAND handle. - * @retval NAND Raw address value - */ -#define COLUMN_ADDRESS( __HANDLE__) ((__HANDLE__)->Config.PageSize) - -/** - * @brief NAND memory address cycling. - * @param __ADDRESS__: NAND memory address. - * @retval NAND address cycling value. - */ -#define ADDR_1ST_CYCLE(__ADDRESS__) (uint8_t)(__ADDRESS__) /* 1st addressing cycle */ -#define ADDR_2ND_CYCLE(__ADDRESS__) (uint8_t)((__ADDRESS__) >> 8U) /* 2nd addressing cycle */ -#define ADDR_3RD_CYCLE(__ADDRESS__) (uint8_t)((__ADDRESS__) >> 16U) /* 3rd addressing cycle */ -#define ADDR_4TH_CYCLE(__ADDRESS__) (uint8_t)((__ADDRESS__) >> 24U) /* 4th addressing cycle */ - -/** - * @brief NAND memory Columns cycling. - * @param __ADDRESS__: NAND memory address. - * @retval NAND Column address cycling value. - */ -#define COLUMN_1ST_CYCLE(__ADDRESS__) (uint8_t)(__ADDRESS__) /* 1st Column addressing cycle */ -#define COLUMN_2ND_CYCLE(__ADDRESS__) (uint8_t)((__ADDRESS__) >> 8U) /* 2nd Column addressing cycle */ - /** * @} */ diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_nor.c b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_nor.c index 9aa2df5633e..a6d9ad74ee2 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_nor.c +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_nor.c @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_hal_nor.c * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief NOR HAL module driver. * This file provides a generic firmware to drive NOR memories mounted * as external device. @@ -295,7 +295,6 @@ __weak void HAL_NOR_MspWait(NOR_HandleTypeDef *hnor, uint32_t Timeout) { /* Prevent unused argument(s) compilation warning */ UNUSED(hnor); - UNUSED(Timeout); /* NOTE : This function Should not be modified, when the callback is needed, the HAL_NOR_MspWait could be implemented in the user file */ @@ -328,7 +327,7 @@ __weak void HAL_NOR_MspWait(NOR_HandleTypeDef *hnor, uint32_t Timeout) */ HAL_StatusTypeDef HAL_NOR_Read_ID(NOR_HandleTypeDef *hnor, NOR_IDTypeDef *pNOR_ID) { - uint32_t deviceaddress = 0U; + uint32_t deviceaddress = 0; /* Process Locked */ __HAL_LOCK(hnor); @@ -388,7 +387,7 @@ HAL_StatusTypeDef HAL_NOR_Read_ID(NOR_HandleTypeDef *hnor, NOR_IDTypeDef *pNOR_I */ HAL_StatusTypeDef HAL_NOR_ReturnToReadMode(NOR_HandleTypeDef *hnor) { - uint32_t deviceaddress = 0U; + uint32_t deviceaddress = 0; /* Process Locked */ __HAL_LOCK(hnor); @@ -438,7 +437,7 @@ HAL_StatusTypeDef HAL_NOR_ReturnToReadMode(NOR_HandleTypeDef *hnor) */ HAL_StatusTypeDef HAL_NOR_Read(NOR_HandleTypeDef *hnor, uint32_t *pAddress, uint16_t *pData) { - uint32_t deviceaddress = 0U; + uint32_t deviceaddress = 0; /* Process Locked */ __HAL_LOCK(hnor); @@ -497,7 +496,7 @@ HAL_StatusTypeDef HAL_NOR_Read(NOR_HandleTypeDef *hnor, uint32_t *pAddress, uint */ HAL_StatusTypeDef HAL_NOR_Program(NOR_HandleTypeDef *hnor, uint32_t *pAddress, uint16_t *pData) { - uint32_t deviceaddress = 0U; + uint32_t deviceaddress = 0; /* Process Locked */ __HAL_LOCK(hnor); @@ -558,7 +557,7 @@ HAL_StatusTypeDef HAL_NOR_Program(NOR_HandleTypeDef *hnor, uint32_t *pAddress, u */ HAL_StatusTypeDef HAL_NOR_ReadBuffer(NOR_HandleTypeDef *hnor, uint32_t uwAddress, uint16_t *pData, uint32_t uwBufferSize) { - uint32_t deviceaddress = 0U; + uint32_t deviceaddress = 0; /* Process Locked */ __HAL_LOCK(hnor); @@ -596,10 +595,10 @@ HAL_StatusTypeDef HAL_NOR_ReadBuffer(NOR_HandleTypeDef *hnor, uint32_t uwAddress NOR_WRITE(uwAddress, NOR_CMD_DATA_READ_RESET); /* Read buffer */ - while( uwBufferSize > 0U) + while( uwBufferSize > 0) { *pData++ = *(__IO uint16_t *)uwAddress; - uwAddress += 2U; + uwAddress += 2; uwBufferSize--; } @@ -630,7 +629,7 @@ HAL_StatusTypeDef HAL_NOR_ProgramBuffer(NOR_HandleTypeDef *hnor, uint32_t uwAddr { uint16_t * p_currentaddress = (uint16_t *)NULL; uint16_t * p_endaddress = (uint16_t *)NULL; - uint32_t lastloadedaddress = 0U, deviceaddress = 0U; + uint32_t lastloadedaddress = 0, deviceaddress = 0; /* Process Locked */ __HAL_LOCK(hnor); @@ -664,7 +663,7 @@ HAL_StatusTypeDef HAL_NOR_ProgramBuffer(NOR_HandleTypeDef *hnor, uint32_t uwAddr /* Initialize variables */ p_currentaddress = (uint16_t*)((uint32_t)(uwAddress)); - p_endaddress = p_currentaddress + (uwBufferSize-1U); + p_endaddress = p_currentaddress + (uwBufferSize-1); lastloadedaddress = (uint32_t)(uwAddress); /* Issue unlock command sequence */ @@ -673,7 +672,7 @@ HAL_StatusTypeDef HAL_NOR_ProgramBuffer(NOR_HandleTypeDef *hnor, uint32_t uwAddr /* Write Buffer Load Command */ NOR_WRITE((uint32_t)(p_currentaddress), NOR_CMD_DATA_BUFFER_AND_PROG); - NOR_WRITE((uint32_t)(p_currentaddress), (uwBufferSize-1U)); + NOR_WRITE((uint32_t)(p_currentaddress), (uwBufferSize-1)); /* Load Data into NOR Buffer */ while(p_currentaddress <= p_endaddress) @@ -708,7 +707,7 @@ HAL_StatusTypeDef HAL_NOR_ProgramBuffer(NOR_HandleTypeDef *hnor, uint32_t uwAddr */ HAL_StatusTypeDef HAL_NOR_Erase_Block(NOR_HandleTypeDef *hnor, uint32_t BlockAddress, uint32_t Address) { - uint32_t deviceaddress = 0U; + uint32_t deviceaddress = 0; /* Process Locked */ __HAL_LOCK(hnor); @@ -767,10 +766,7 @@ HAL_StatusTypeDef HAL_NOR_Erase_Block(NOR_HandleTypeDef *hnor, uint32_t BlockAdd */ HAL_StatusTypeDef HAL_NOR_Erase_Chip(NOR_HandleTypeDef *hnor, uint32_t Address) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(Address); - - uint32_t deviceaddress = 0U; + uint32_t deviceaddress = 0; /* Process Locked */ __HAL_LOCK(hnor); @@ -828,7 +824,7 @@ HAL_StatusTypeDef HAL_NOR_Erase_Chip(NOR_HandleTypeDef *hnor, uint32_t Address) */ HAL_StatusTypeDef HAL_NOR_Read_CFI(NOR_HandleTypeDef *hnor, NOR_CFITypeDef *pNOR_CFI) { - uint32_t deviceaddress = 0U; + uint32_t deviceaddress = 0; /* Process Locked */ __HAL_LOCK(hnor); @@ -989,7 +985,7 @@ HAL_NOR_StatusTypeDef HAL_NOR_GetStatus(NOR_HandleTypeDef *hnor, uint32_t Addres { HAL_NOR_StatusTypeDef status = HAL_NOR_STATUS_ONGOING; uint16_t tmp_sr1 = 0, tmp_sr2 = 0; - uint32_t tickstart = 0U; + uint32_t tickstart = 0; /* Poll on NOR memory Ready/Busy signal ------------------------------------*/ HAL_NOR_MspWait(hnor, Timeout); @@ -1001,7 +997,7 @@ HAL_NOR_StatusTypeDef HAL_NOR_GetStatus(NOR_HandleTypeDef *hnor, uint32_t Addres /* Check for the Timeout */ if(Timeout != HAL_MAX_DELAY) { - if((Timeout == 0U)||((HAL_GetTick() - tickstart ) > Timeout)) + if((Timeout == 0)||((HAL_GetTick() - tickstart ) > Timeout)) { status = HAL_NOR_STATUS_TIMEOUT; } diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_nor.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_nor.h index a577715d22a..fc0b0ffea6e 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_nor.h +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_nor.h @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_hal_nor.h * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief Header file of NOR HAL module. ****************************************************************************** * @attention @@ -101,7 +101,7 @@ */ #define NOR_ADDR_SHIFT(__NOR_ADDRESS, __NOR_MEMORY_WIDTH_, __ADDRESS__) \ ((uint32_t)(((__NOR_MEMORY_WIDTH_) == NOR_MEMORY_16B)? \ - ((uint32_t)((__NOR_ADDRESS) + (2U * (__ADDRESS__)))): \ + ((uint32_t)((__NOR_ADDRESS) + (2 * (__ADDRESS__)))): \ ((uint32_t)((__NOR_ADDRESS) + (__ADDRESS__))))) /** @@ -126,11 +126,11 @@ */ typedef enum { - HAL_NOR_STATE_RESET = 0x00U, /*!< NOR not yet initialized or disabled */ - HAL_NOR_STATE_READY = 0x01U, /*!< NOR initialized and ready for use */ - HAL_NOR_STATE_BUSY = 0x02U, /*!< NOR internal processing is ongoing */ - HAL_NOR_STATE_ERROR = 0x03U, /*!< NOR error state */ - HAL_NOR_STATE_PROTECTED = 0x04U /*!< NOR NORSRAM device write protected */ + HAL_NOR_STATE_RESET = 0x00, /*!< NOR not yet initialized or disabled */ + HAL_NOR_STATE_READY = 0x01, /*!< NOR initialized and ready for use */ + HAL_NOR_STATE_BUSY = 0x02, /*!< NOR internal processing is ongoing */ + HAL_NOR_STATE_ERROR = 0x03, /*!< NOR error state */ + HAL_NOR_STATE_PROTECTED = 0x04 /*!< NOR NORSRAM device write protected */ }HAL_NOR_StateTypeDef; /** @@ -138,7 +138,7 @@ typedef enum */ typedef enum { - HAL_NOR_STATUS_SUCCESS = 0U, + HAL_NOR_STATUS_SUCCESS = 0, HAL_NOR_STATUS_ONGOING, HAL_NOR_STATUS_ERROR, HAL_NOR_STATUS_TIMEOUT diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_pccard.c b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_pccard.c index 198e8041f73..558a9b0a850 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_pccard.c +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_pccard.c @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_hal_pccard.c * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief PCCARD HAL module driver. * This file provides a generic firmware to drive PCCARD memories mounted * as external device. @@ -95,9 +95,9 @@ * @{ */ -#define PCCARD_TIMEOUT_READ_ID 0x0000FFFFU -#define PCCARD_TIMEOUT_SECTOR 0x0000FFFFU -#define PCCARD_TIMEOUT_STATUS 0x01000000U +#define PCCARD_TIMEOUT_READ_ID (uint32_t)0x0000FFFF +#define PCCARD_TIMEOUT_SECTOR (uint32_t)0x0000FFFF +#define PCCARD_TIMEOUT_STATUS (uint32_t)0x01000000 #define PCCARD_STATUS_OK (uint8_t)0x58 #define PCCARD_STATUS_WRITE_OK (uint8_t)0x50 @@ -262,8 +262,8 @@ __weak void HAL_PCCARD_MspDeInit(PCCARD_HandleTypeDef *hpccard) */ HAL_StatusTypeDef HAL_PCCARD_Read_ID(PCCARD_HandleTypeDef *hpccard, uint8_t CompactFlash_ID[], uint8_t *pStatus) { - uint32_t timeout = PCCARD_TIMEOUT_READ_ID, index = 0U; - uint8_t status = 0U; + uint32_t timeout = PCCARD_TIMEOUT_READ_ID, index = 0; + uint8_t status = 0; /* Process Locked */ __HAL_LOCK(hpccard); @@ -281,7 +281,7 @@ HAL_StatusTypeDef HAL_PCCARD_Read_ID(PCCARD_HandleTypeDef *hpccard, uint8_t Comp *pStatus = PCCARD_READY; /* Send the Identify Command */ - *(__IO uint16_t *)(PCCARD_IO_SPACE_PRIMARY_ADDR | ATA_STATUS_CMD) = 0xECECU; + *(__IO uint16_t *)(PCCARD_IO_SPACE_PRIMARY_ADDR | ATA_STATUS_CMD) = 0xECEC; /* Read CF IDs and timeout treatment */ do @@ -292,14 +292,14 @@ HAL_StatusTypeDef HAL_PCCARD_Read_ID(PCCARD_HandleTypeDef *hpccard, uint8_t Comp timeout--; }while((status != PCCARD_STATUS_OK) && timeout); - if(timeout == 0U) + if(timeout == 0) { *pStatus = PCCARD_TIMEOUT_ERROR; } else { /* Read CF ID bytes */ - for(index = 0U; index < 16U; index++) + for(index = 0; index < 16; index++) { CompactFlash_ID[index] = *(__IO uint8_t *)(PCCARD_IO_SPACE_PRIMARY_ADDR | ATA_DATA); } @@ -325,8 +325,8 @@ HAL_StatusTypeDef HAL_PCCARD_Read_ID(PCCARD_HandleTypeDef *hpccard, uint8_t Comp */ HAL_StatusTypeDef HAL_PCCARD_Read_Sector(PCCARD_HandleTypeDef *hpccard, uint16_t *pBuffer, uint16_t SectorAddress, uint8_t *pStatus) { - uint32_t timeout = PCCARD_TIMEOUT_SECTOR, index = 0U; - uint8_t status = 0U; + uint32_t timeout = PCCARD_TIMEOUT_SECTOR, index = 0; + uint8_t status = 0; /* Process Locked */ __HAL_LOCK(hpccard); @@ -345,22 +345,22 @@ HAL_StatusTypeDef HAL_PCCARD_Read_Sector(PCCARD_HandleTypeDef *hpccard, uint16_t /* Set the parameters to write a sector */ *(__IO uint16_t *)(PCCARD_IO_SPACE_PRIMARY_ADDR | ATA_CYLINDER_HIGH) = (uint16_t)0x00; - *(__IO uint16_t *)(PCCARD_IO_SPACE_PRIMARY_ADDR | ATA_SECTOR_COUNT) = ((uint16_t)0x0100) | ((uint16_t)SectorAddress); - *(__IO uint16_t *)(PCCARD_IO_SPACE_PRIMARY_ADDR | ATA_STATUS_CMD) = (uint16_t)0xE4A0; + *(__IO uint16_t *)(PCCARD_IO_SPACE_PRIMARY_ADDR | ATA_SECTOR_COUNT) = ((uint16_t)0x0100 ) | ((uint16_t)SectorAddress); + *(__IO uint16_t *)(PCCARD_IO_SPACE_PRIMARY_ADDR | ATA_STATUS_CMD) = (uint16_t)0xE4A0; do { /* wait till the Status = 0x80 */ status = *(__IO uint16_t *)(PCCARD_IO_SPACE_PRIMARY_ADDR | ATA_STATUS_CMD_ALTERNATE); timeout--; - }while((status == 0x80U) && timeout); + }while((status == 0x80) && timeout); - if(timeout == 0U) + if(timeout == 0) { *pStatus = PCCARD_TIMEOUT_ERROR; } - timeout = 0xFFFFU; + timeout = 0xFFFF; do { @@ -369,7 +369,7 @@ HAL_StatusTypeDef HAL_PCCARD_Read_Sector(PCCARD_HandleTypeDef *hpccard, uint16_t timeout--; }while((status != PCCARD_STATUS_OK) && timeout); - if(timeout == 0U) + if(timeout == 0) { *pStatus = PCCARD_TIMEOUT_ERROR; } @@ -401,8 +401,8 @@ HAL_StatusTypeDef HAL_PCCARD_Read_Sector(PCCARD_HandleTypeDef *hpccard, uint16_t */ HAL_StatusTypeDef HAL_PCCARD_Write_Sector(PCCARD_HandleTypeDef *hpccard, uint16_t *pBuffer, uint16_t SectorAddress, uint8_t *pStatus) { - uint32_t timeout = PCCARD_TIMEOUT_SECTOR, index = 0U; - uint8_t status = 0U; + uint32_t timeout = PCCARD_TIMEOUT_SECTOR, index = 0; + uint8_t status = 0; /* Process Locked */ __HAL_LOCK(hpccard); @@ -421,7 +421,7 @@ HAL_StatusTypeDef HAL_PCCARD_Write_Sector(PCCARD_HandleTypeDef *hpccard, uint16_ /* Set the parameters to write a sector */ *(__IO uint16_t *)(PCCARD_IO_SPACE_PRIMARY_ADDR | ATA_CYLINDER_HIGH) = (uint16_t)0x00; - *(__IO uint16_t *)(PCCARD_IO_SPACE_PRIMARY_ADDR | ATA_SECTOR_COUNT) = ((uint16_t)0x0100) | ((uint16_t)SectorAddress); + *(__IO uint16_t *)(PCCARD_IO_SPACE_PRIMARY_ADDR | ATA_SECTOR_COUNT) = ((uint16_t)0x0100 ) | ((uint16_t)SectorAddress); *(__IO uint16_t *)(PCCARD_IO_SPACE_PRIMARY_ADDR | ATA_STATUS_CMD) = (uint16_t)0x30A0; do @@ -431,7 +431,7 @@ HAL_StatusTypeDef HAL_PCCARD_Write_Sector(PCCARD_HandleTypeDef *hpccard, uint16_ timeout--; }while((status != PCCARD_STATUS_OK) && timeout); - if(timeout == 0U) + if(timeout == 0) { *pStatus = PCCARD_TIMEOUT_ERROR; } @@ -449,7 +449,7 @@ HAL_StatusTypeDef HAL_PCCARD_Write_Sector(PCCARD_HandleTypeDef *hpccard, uint16_ timeout--; }while((status != PCCARD_STATUS_WRITE_OK) && timeout); - if(timeout == 0U) + if(timeout == 0) { *pStatus = PCCARD_TIMEOUT_ERROR; } @@ -474,7 +474,7 @@ HAL_StatusTypeDef HAL_PCCARD_Write_Sector(PCCARD_HandleTypeDef *hpccard, uint16_ */ HAL_StatusTypeDef HAL_PCCARD_Erase_Sector(PCCARD_HandleTypeDef *hpccard, uint16_t SectorAddress, uint8_t *pStatus) { - uint32_t timeout = 0x400U; + uint32_t timeout = 0x400; uint8_t status = 0; /* Process Locked */ @@ -509,7 +509,7 @@ HAL_StatusTypeDef HAL_PCCARD_Erase_Sector(PCCARD_HandleTypeDef *hpccard, uint16 timeout--; } - if(timeout == 0U) + if(timeout == 0) { *pStatus = PCCARD_TIMEOUT_ERROR; } @@ -684,7 +684,7 @@ HAL_PCCARD_StatusTypeDef HAL_PCCARD_GetStatus(PCCARD_HandleTypeDef *hpccard) timeout--; } - if(timeout == 0U) + if(timeout == 0) { status_cf = PCCARD_TIMEOUT_ERROR; } @@ -704,7 +704,7 @@ HAL_PCCARD_StatusTypeDef HAL_PCCARD_GetStatus(PCCARD_HandleTypeDef *hpccard) */ HAL_PCCARD_StatusTypeDef HAL_PCCARD_ReadStatus(PCCARD_HandleTypeDef *hpccard) { - uint8_t data = 0U, status_cf = PCCARD_BUSY; + uint8_t data = 0, status_cf = PCCARD_BUSY; /* Check the PCCARD controller state */ if(hpccard->State == HAL_PCCARD_STATE_BUSY) diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_pccard.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_pccard.h index e76a882f370..38a916f3cc7 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_pccard.h +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_pccard.h @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_hal_pccard.h * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief Header file of PCCARD HAL module. ****************************************************************************** * @attention @@ -60,10 +60,10 @@ */ #define PCCARD_DEVICE_ADDRESS FSMC_BANK4 -#define PCCARD_ATTRIBUTE_SPACE_ADDRESS ((uint32_t)(FSMC_BANK4 + 0x08000000U)) /* Attribute space size to @0x9BFF FFFF */ +#define PCCARD_ATTRIBUTE_SPACE_ADDRESS ((uint32_t)(FSMC_BANK4 + 0x08000000)) /* Attribute space size to @0x9BFF FFFF */ #define PCCARD_COMMON_SPACE_ADDRESS PCCARD_DEVICE_ADDRESS /* Common space size to @0x93FF FFFF */ -#define PCCARD_IO_SPACE_ADDRESS ((uint32_t)(FSMC_BANK4 + 0x0C000000U)) /* IO space size to @0x9FFF FFFF */ -#define PCCARD_IO_SPACE_PRIMARY_ADDR ((uint32_t)(FSMC_BANK4 + 0x0C0001F0U)) /* IO space size to @0x9FFF FFFF */ +#define PCCARD_IO_SPACE_ADDRESS ((uint32_t)(FSMC_BANK4 + 0x0C000000)) /* IO space size to @0x9FFF FFFF */ +#define PCCARD_IO_SPACE_PRIMARY_ADDR ((uint32_t)(FSMC_BANK4 + 0x0C0001F0)) /* IO space size to @0x9FFF FFFF */ /* Compact Flash-ATA registers description */ #define ATA_DATA ((uint8_t)0x00) /* Data register */ @@ -89,7 +89,7 @@ #define PCCARD_PROGR ((uint8_t)0x01) #define PCCARD_READY ((uint8_t)0x40) -#define PCCARD_SECTOR_SIZE 255U /* In half words */ +#define PCCARD_SECTOR_SIZE ((uint32_t)255) /* In half words */ /* Compact Flash redefinition */ @@ -98,17 +98,18 @@ #define HAL_CF_Read_Sector HAL_PCCARD_Read_Sector #define HAL_CF_Erase_Sector HAL_PCCARD_Erase_Sector #define HAL_CF_Reset HAL_PCCARD_Reset - + #define HAL_CF_GetStatus HAL_PCCARD_GetStatus #define HAL_CF_ReadStatus HAL_PCCARD_ReadStatus - + #define CF_SUCCESS HAL_PCCARD_STATUS_SUCCESS #define CF_ONGOING HAL_PCCARD_STATUS_ONGOING #define CF_ERROR HAL_PCCARD_STATUS_ERROR #define CF_TIMEOUT HAL_PCCARD_STATUS_TIMEOUT #define CF_StatusTypedef HAL_PCCARD_StatusTypeDef -#define CF_DEVICE_ADDRESS PCCARD_DEVICE_ADDRESS + +#define CF_DEVICE_ADDRESS PCCARD_DEVICE_ADDRESS #define CF_ATTRIBUTE_SPACE_ADDRESS PCCARD_ATTRIBUTE_SPACE_ADDRESS #define CF_COMMON_SPACE_ADDRESS PCCARD_COMMON_SPACE_ADDRESS #define CF_IO_SPACE_ADDRESS PCCARD_IO_SPACE_ADDRESS @@ -135,15 +136,15 @@ */ typedef enum { - HAL_PCCARD_STATE_RESET = 0x00U, /*!< PCCARD peripheral not yet initialized or disabled */ - HAL_PCCARD_STATE_READY = 0x01U, /*!< PCCARD peripheral ready */ - HAL_PCCARD_STATE_BUSY = 0x02U, /*!< PCCARD peripheral busy */ - HAL_PCCARD_STATE_ERROR = 0x04U /*!< PCCARD peripheral error */ + HAL_PCCARD_STATE_RESET = 0x00, /*!< PCCARD peripheral not yet initialized or disabled */ + HAL_PCCARD_STATE_READY = 0x01, /*!< PCCARD peripheral ready */ + HAL_PCCARD_STATE_BUSY = 0x02, /*!< PCCARD peripheral busy */ + HAL_PCCARD_STATE_ERROR = 0x04 /*!< PCCARD peripheral error */ }HAL_PCCARD_StateTypeDef; typedef enum { - HAL_PCCARD_STATUS_SUCCESS = 0U, + HAL_PCCARD_STATUS_SUCCESS = 0, HAL_PCCARD_STATUS_ONGOING, HAL_PCCARD_STATUS_ERROR, HAL_PCCARD_STATUS_TIMEOUT diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_pcd.c b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_pcd.c index 8e0ddbe30bd..fe6211b1d5c 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_pcd.c +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_pcd.c @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_hal_pcd.c * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief PCD HAL module driver. * This file provides firmware functions to manage the following * functionalities of the USB Peripheral Controller: @@ -149,7 +149,7 @@ static HAL_StatusTypeDef PCD_EP_ISR_Handler(PCD_HandleTypeDef *hpcd); */ HAL_StatusTypeDef HAL_PCD_Init(PCD_HandleTypeDef *hpcd) { - uint32_t index = 0U; + uint32_t index = 0; /* Check the PCD handle allocation */ if(hpcd == NULL) @@ -173,7 +173,7 @@ HAL_StatusTypeDef HAL_PCD_Init(PCD_HandleTypeDef *hpcd) /* Disable the Interrupts */ __HAL_PCD_DISABLE(hpcd); - + /*Init the Core (common init.) */ USB_CoreInit(hpcd->Instance, hpcd->Init); @@ -181,35 +181,35 @@ HAL_StatusTypeDef HAL_PCD_Init(PCD_HandleTypeDef *hpcd) USB_SetCurrentMode(hpcd->Instance , USB_DEVICE_MODE); /* Init endpoints structures */ - for (index = 0U; index < 15U ; index++) + for (index = 0; index < 15 ; index++) { /* Init ep structure */ - hpcd->IN_ep[index].is_in = 1U; + hpcd->IN_ep[index].is_in = 1; hpcd->IN_ep[index].num = index; hpcd->IN_ep[index].tx_fifo_num = index; /* Control until ep is actvated */ hpcd->IN_ep[index].type = EP_TYPE_CTRL; - hpcd->IN_ep[index].maxpacket = 0U; - hpcd->IN_ep[index].xfer_buff = 0U; - hpcd->IN_ep[index].xfer_len = 0U; + hpcd->IN_ep[index].maxpacket = 0; + hpcd->IN_ep[index].xfer_buff = 0; + hpcd->IN_ep[index].xfer_len = 0; } - - for (index = 0U; index < 15U ; index++) + + for (index = 0; index < 15 ; index++) { - hpcd->OUT_ep[index].is_in = 0U; + hpcd->OUT_ep[index].is_in = 0; hpcd->OUT_ep[index].num = index; hpcd->IN_ep[index].tx_fifo_num = index; /* Control until ep is activated */ hpcd->OUT_ep[index].type = EP_TYPE_CTRL; - hpcd->OUT_ep[index].maxpacket = 0U; - hpcd->OUT_ep[index].xfer_buff = 0U; - hpcd->OUT_ep[index].xfer_len = 0U; + hpcd->OUT_ep[index].maxpacket = 0; + hpcd->OUT_ep[index].xfer_buff = 0; + hpcd->OUT_ep[index].xfer_len = 0; } /* Init Device */ USB_DevInit(hpcd->Instance, hpcd->Init); - hpcd->USB_Address = 0U; + hpcd->USB_Address = 0; hpcd->State= HAL_PCD_STATE_READY; USB_DevDisconnect (hpcd->Instance); @@ -228,7 +228,7 @@ HAL_StatusTypeDef HAL_PCD_DeInit(PCD_HandleTypeDef *hpcd) { return HAL_ERROR; } - + hpcd->State = HAL_PCD_STATE_BUSY; /* Stop Device */ @@ -310,7 +310,7 @@ HAL_StatusTypeDef HAL_PCD_Start(PCD_HandleTypeDef *hpcd) * @retval HAL status */ HAL_StatusTypeDef HAL_PCD_Stop(PCD_HandleTypeDef *hpcd) -{ +{ __HAL_LOCK(hpcd); __HAL_PCD_DISABLE(hpcd); USB_StopDevice(hpcd->Instance); @@ -328,8 +328,8 @@ HAL_StatusTypeDef HAL_PCD_Stop(PCD_HandleTypeDef *hpcd) void HAL_PCD_IRQHandler(PCD_HandleTypeDef *hpcd) { USB_OTG_GlobalTypeDef *USBx = hpcd->Instance; - uint32_t index = 0U, ep_intr = 0U, epint = 0U, epnum = 0U; - uint32_t fifoemptymsk = 0U, temp = 0U; + uint32_t index = 0, ep_intr = 0, epint = 0, epnum = 0; + uint32_t fifoemptymsk = 0, temp = 0; USB_OTG_EPTypeDef *ep = NULL; /* ensure that we are in device mode */ @@ -349,14 +349,14 @@ void HAL_PCD_IRQHandler(PCD_HandleTypeDef *hpcd) if(__HAL_PCD_GET_FLAG(hpcd, USB_OTG_GINTSTS_OEPINT)) { - epnum = 0U; + epnum = 0; /* Read in the device interrupt bits */ ep_intr = USB_ReadDevAllOutEpInterrupt(hpcd->Instance); while ( ep_intr ) { - if (ep_intr & 0x1U) + if (ep_intr & 0x1) { epint = USB_ReadDevOutEPInterrupt(hpcd->Instance, epnum); @@ -380,7 +380,7 @@ void HAL_PCD_IRQHandler(PCD_HandleTypeDef *hpcd) } } epnum++; - ep_intr >>= 1U; + ep_intr >>= 1; } } @@ -389,17 +389,17 @@ void HAL_PCD_IRQHandler(PCD_HandleTypeDef *hpcd) /* Read in the device interrupt bits */ ep_intr = USB_ReadDevAllInEpInterrupt(hpcd->Instance); - epnum = 0U; + epnum = 0; while ( ep_intr ) { - if (ep_intr & 0x1U) /* In ITR */ + if (ep_intr & 0x1) /* In ITR */ { epint = USB_ReadDevInEPInterrupt(hpcd->Instance, epnum); - + if(( epint & USB_OTG_DIEPINT_XFRC) == USB_OTG_DIEPINT_XFRC) { - fifoemptymsk = 0x1U << epnum; + fifoemptymsk = 0x1 << epnum; USBx_DEVICE->DIEPEMPMSK &= ~fifoemptymsk; CLEAR_IN_EP_INTR(epnum, USB_OTG_DIEPINT_XFRC); @@ -428,7 +428,7 @@ void HAL_PCD_IRQHandler(PCD_HandleTypeDef *hpcd) } } epnum++; - ep_intr >>= 1U; + ep_intr >>= 1; } } @@ -453,20 +453,20 @@ void HAL_PCD_IRQHandler(PCD_HandleTypeDef *hpcd) } __HAL_PCD_CLEAR_FLAG(hpcd, USB_OTG_GINTSTS_USBSUSP); } - + /* Handle Reset Interrupt */ if(__HAL_PCD_GET_FLAG(hpcd, USB_OTG_GINTSTS_USBRST)) { USBx_DEVICE->DCTL &= ~USB_OTG_DCTL_RWUSIG; - USB_FlushTxFifo(hpcd->Instance , 0x10U); + USB_FlushTxFifo(hpcd->Instance , 0 ); - for (index = 0U; index < hpcd->Init.dev_endpoints ; index++) + for (index = 0; index < hpcd->Init.dev_endpoints ; index++) { - USBx_INEP(index)->DIEPINT = 0xFFU; - USBx_OUTEP(index)->DOEPINT = 0xFFU; + USBx_INEP(index)->DIEPINT = 0xFF; + USBx_OUTEP(index)->DOEPINT = 0xFF; } - USBx_DEVICE->DAINT = 0xFFFFFFFFU; - USBx_DEVICE->DAINTMSK |= 0x10001U; + USBx_DEVICE->DAINT = 0xFFFFFFFF; + USBx_DEVICE->DAINTMSK |= 0x10001; USBx_DEVICE->DOEPMSK |= (USB_OTG_DOEPMSK_STUPM | USB_OTG_DOEPMSK_XFRCM | USB_OTG_DOEPMSK_EPDM); USBx_DEVICE->DIEPMSK |= (USB_OTG_DIEPMSK_TOM | USB_OTG_DIEPMSK_XFRCM | USB_OTG_DIEPMSK_EPDM); @@ -488,13 +488,13 @@ void HAL_PCD_IRQHandler(PCD_HandleTypeDef *hpcd) hpcd->Init.speed = USB_OTG_SPEED_FULL; hpcd->Init.ep0_mps = USB_OTG_FS_MAX_PACKET_SIZE ; - hpcd->Instance->GUSBCFG |= (uint32_t)((USBD_FS_TRDT_VALUE << 10U) & USB_OTG_GUSBCFG_TRDT); + hpcd->Instance->GUSBCFG |= (uint32_t)((USBD_FS_TRDT_VALUE << 10) & USB_OTG_GUSBCFG_TRDT); HAL_PCD_ResetCallback(hpcd); __HAL_PCD_CLEAR_FLAG(hpcd, USB_OTG_GINTSTS_ENUMDNE); } - + /* Handle RxQLevel Interrupt */ if(__HAL_PCD_GET_FLAG(hpcd, USB_OTG_GINTSTS_RXFLVL)) { @@ -502,19 +502,19 @@ void HAL_PCD_IRQHandler(PCD_HandleTypeDef *hpcd) temp = USBx->GRXSTSP; ep = &hpcd->OUT_ep[temp & USB_OTG_GRXSTSP_EPNUM]; - if(((temp & USB_OTG_GRXSTSP_PKTSTS) >> 17U) == STS_DATA_UPDT) + if(((temp & USB_OTG_GRXSTSP_PKTSTS) >> 17) == STS_DATA_UPDT) { - if((temp & USB_OTG_GRXSTSP_BCNT) != 0U) + if((temp & USB_OTG_GRXSTSP_BCNT) != 0) { - USB_ReadPacket(USBx, ep->xfer_buff, (temp & USB_OTG_GRXSTSP_BCNT) >> 4U); - ep->xfer_buff += (temp & USB_OTG_GRXSTSP_BCNT) >> 4U; - ep->xfer_count += (temp & USB_OTG_GRXSTSP_BCNT) >> 4U; + USB_ReadPacket(USBx, ep->xfer_buff, (temp & USB_OTG_GRXSTSP_BCNT) >> 4); + ep->xfer_buff += (temp & USB_OTG_GRXSTSP_BCNT) >> 4; + ep->xfer_count += (temp & USB_OTG_GRXSTSP_BCNT) >> 4; } } - else if (((temp & USB_OTG_GRXSTSP_PKTSTS) >> 17U) == STS_SETUP_UPDT) + else if (((temp & USB_OTG_GRXSTSP_PKTSTS) >> 17) == STS_SETUP_UPDT) { - USB_ReadPacket(USBx, (uint8_t *)hpcd->Setup, 8U); - ep->xfer_count += (temp & USB_OTG_GRXSTSP_BCNT) >> 4U; + USB_ReadPacket(USBx, (uint8_t *)hpcd->Setup, 8); + ep->xfer_count += (temp & USB_OTG_GRXSTSP_BCNT) >> 4; } USB_UNMASK_INTERRUPT(hpcd->Instance, USB_OTG_GINTSTS_RXFLVL); } @@ -569,7 +569,9 @@ void HAL_PCD_IRQHandler(PCD_HandleTypeDef *hpcd) * @retval HAL status */ void HAL_PCD_IRQHandler(PCD_HandleTypeDef *hpcd) -{ +{ + uint32_t wInterrupt_Mask = 0; + if (__HAL_PCD_GET_FLAG (hpcd, USB_ISTR_CTR)) { /* servicing of the endpoint correct transfer interrupt */ @@ -581,7 +583,7 @@ void HAL_PCD_IRQHandler(PCD_HandleTypeDef *hpcd) { __HAL_PCD_CLEAR_FLAG(hpcd, USB_ISTR_RESET); HAL_PCD_ResetCallback(hpcd); - HAL_PCD_SetAddress(hpcd, 0U); + HAL_PCD_SetAddress(hpcd, 0); } if (__HAL_PCD_GET_FLAG (hpcd, USB_ISTR_PMAOVR)) @@ -594,25 +596,30 @@ void HAL_PCD_IRQHandler(PCD_HandleTypeDef *hpcd) } if (__HAL_PCD_GET_FLAG (hpcd, USB_ISTR_WKUP)) - { + { hpcd->Instance->CNTR &= ~(USB_CNTR_LP_MODE); - hpcd->Instance->CNTR &= ~(USB_CNTR_FSUSP); + + /*set wInterrupt_Mask global variable*/ + wInterrupt_Mask = USB_CNTR_CTRM | USB_CNTR_WKUPM | USB_CNTR_SUSPM | USB_CNTR_ERRM \ + | USB_CNTR_ESOFM | USB_CNTR_RESETM; + + /*Set interrupt mask*/ + hpcd->Instance->CNTR = wInterrupt_Mask; HAL_PCD_ResumeCallback(hpcd); - + __HAL_PCD_CLEAR_FLAG(hpcd, USB_ISTR_WKUP); } if (__HAL_PCD_GET_FLAG (hpcd, USB_ISTR_SUSP)) - { - /* Force low-power mode in the macrocell */ - hpcd->Instance->CNTR |= USB_CNTR_FSUSP; - + { /* clear of the ISTR bit must be done after setting of CNTR_FSUSP */ __HAL_PCD_CLEAR_FLAG(hpcd, USB_ISTR_SUSP); - + + /* Force low-power mode in the macrocell */ + hpcd->Instance->CNTR |= USB_CNTR_FSUSP; hpcd->Instance->CNTR |= USB_CNTR_LP_MODE; - if (__HAL_PCD_GET_FLAG (hpcd, USB_ISTR_WKUP) == 0U) + if (__HAL_PCD_GET_FLAG (hpcd, USB_ISTR_WKUP) == 0) { HAL_PCD_SuspendCallback(hpcd); } @@ -834,7 +841,7 @@ HAL_StatusTypeDef HAL_PCD_DevConnect(PCD_HandleTypeDef *hpcd) HAL_StatusTypeDef HAL_PCD_DevDisconnect(PCD_HandleTypeDef *hpcd) { __HAL_LOCK(hpcd); - HAL_PCDEx_SetConnectionState (hpcd, 0U); + HAL_PCDEx_SetConnectionState (hpcd, 0); USB_DevDisconnect(hpcd->Instance); __HAL_UNLOCK(hpcd); return HAL_OK; @@ -867,17 +874,17 @@ HAL_StatusTypeDef HAL_PCD_EP_Open(PCD_HandleTypeDef *hpcd, uint8_t ep_addr, uint HAL_StatusTypeDef ret = HAL_OK; PCD_EPTypeDef *ep = NULL; - if ((ep_addr & 0x80U) == 0x80U) + if ((ep_addr & 0x80) == 0x80) { - ep = &hpcd->IN_ep[ep_addr & 0x7FU]; + ep = &hpcd->IN_ep[ep_addr & 0x7F]; } else { - ep = &hpcd->OUT_ep[ep_addr & 0x7FU]; + ep = &hpcd->OUT_ep[ep_addr & 0x7F]; } - ep->num = ep_addr & 0x7FU; + ep->num = ep_addr & 0x7F; - ep->is_in = (0x80U & ep_addr) != 0U; + ep->is_in = (0x80 & ep_addr) != 0; ep->maxpacket = ep_mps; ep->type = ep_type; @@ -897,17 +904,17 @@ HAL_StatusTypeDef HAL_PCD_EP_Close(PCD_HandleTypeDef *hpcd, uint8_t ep_addr) { PCD_EPTypeDef *ep = NULL; - if ((ep_addr & 0x80U) == 0x80U) + if ((ep_addr & 0x80) == 0x80) { - ep = &hpcd->IN_ep[ep_addr & 0x7FU]; + ep = &hpcd->IN_ep[ep_addr & 0x7F]; } else { - ep = &hpcd->OUT_ep[ep_addr & 0x7FU]; + ep = &hpcd->OUT_ep[ep_addr & 0x7F]; } - ep->num = ep_addr & 0x7FU; + ep->num = ep_addr & 0x7F; - ep->is_in = (0x80U & ep_addr) != 0U; + ep->is_in = (0x80 & ep_addr) != 0; __HAL_LOCK(hpcd); USB_DeactivateEndpoint(hpcd->Instance , ep); @@ -928,16 +935,18 @@ HAL_StatusTypeDef HAL_PCD_EP_Receive(PCD_HandleTypeDef *hpcd, uint8_t ep_addr, u { PCD_EPTypeDef *ep = NULL; - ep = &hpcd->OUT_ep[ep_addr & 0x7FU]; + ep = &hpcd->OUT_ep[ep_addr & 0x7F]; /*setup and start the Xfer */ ep->xfer_buff = pBuf; ep->xfer_len = len; - ep->xfer_count = 0U; - ep->is_in = 0U; - ep->num = ep_addr & 0x7FU; - - if ((ep_addr & 0x7FU) == 0U) + ep->xfer_count = 0; + ep->is_in = 0; + ep->num = ep_addr & 0x7F; + + __HAL_LOCK(hpcd); + + if ((ep_addr & 0x7F) == 0 ) { USB_EP0StartXfer(hpcd->Instance , ep); } @@ -945,7 +954,8 @@ HAL_StatusTypeDef HAL_PCD_EP_Receive(PCD_HandleTypeDef *hpcd, uint8_t ep_addr, u { USB_EPStartXfer(hpcd->Instance , ep); } - + __HAL_UNLOCK(hpcd); + return HAL_OK; } @@ -957,7 +967,7 @@ HAL_StatusTypeDef HAL_PCD_EP_Receive(PCD_HandleTypeDef *hpcd, uint8_t ep_addr, u */ uint16_t HAL_PCD_EP_GetRxCount(PCD_HandleTypeDef *hpcd, uint8_t ep_addr) { - return hpcd->OUT_ep[ep_addr & 0xF].xfer_count; + return hpcd->OUT_ep[ep_addr & 0x7F].xfer_count; } /** * @brief Send an amount of data @@ -971,16 +981,18 @@ HAL_StatusTypeDef HAL_PCD_EP_Transmit(PCD_HandleTypeDef *hpcd, uint8_t ep_addr, { PCD_EPTypeDef *ep = NULL; - ep = &hpcd->IN_ep[ep_addr & 0x7FU]; + ep = &hpcd->IN_ep[ep_addr & 0x7F]; /*setup and start the Xfer */ ep->xfer_buff = pBuf; ep->xfer_len = len; - ep->xfer_count = 0U; - ep->is_in = 1U; - ep->num = ep_addr & 0x7FU; - - if ((ep_addr & 0x7FU) == 0U) + ep->xfer_count = 0; + ep->is_in = 1; + ep->num = ep_addr & 0x7F; + + __HAL_LOCK(hpcd); + + if ((ep_addr & 0x7F) == 0 ) { USB_EP0StartXfer(hpcd->Instance , ep); } @@ -988,7 +1000,9 @@ HAL_StatusTypeDef HAL_PCD_EP_Transmit(PCD_HandleTypeDef *hpcd, uint8_t ep_addr, { USB_EPStartXfer(hpcd->Instance , ep); } - + + __HAL_UNLOCK(hpcd); + return HAL_OK; } @@ -1002,22 +1016,22 @@ HAL_StatusTypeDef HAL_PCD_EP_SetStall(PCD_HandleTypeDef *hpcd, uint8_t ep_addr) { PCD_EPTypeDef *ep = NULL; - if ((0x80U & ep_addr) == 0x80U) + if ((0x80 & ep_addr) == 0x80) { - ep = &hpcd->IN_ep[ep_addr & 0x7FU]; + ep = &hpcd->IN_ep[ep_addr & 0x7F]; } else { ep = &hpcd->OUT_ep[ep_addr]; } - ep->is_stall = 1U; - ep->num = ep_addr & 0x7FU; - ep->is_in = ((ep_addr & 0x80U) == 0x80U); + ep->is_stall = 1; + ep->num = ep_addr & 0x7F; + ep->is_in = ((ep_addr & 0x80) == 0x80); __HAL_LOCK(hpcd); USB_EPSetStall(hpcd->Instance , ep); - if((ep_addr & 0x7FU) == 0U) + if((ep_addr & 0x7F) == 0) { USB_EP0_OutStart(hpcd->Instance, (uint8_t *)hpcd->Setup); } @@ -1036,18 +1050,18 @@ HAL_StatusTypeDef HAL_PCD_EP_ClrStall(PCD_HandleTypeDef *hpcd, uint8_t ep_addr) { PCD_EPTypeDef *ep = NULL; - if ((0x80U & ep_addr) == 0x80U) + if ((0x80 & ep_addr) == 0x80) { - ep = &hpcd->IN_ep[ep_addr & 0x7FU]; + ep = &hpcd->IN_ep[ep_addr & 0x7F]; } else { ep = &hpcd->OUT_ep[ep_addr]; } - ep->is_stall = 0U; - ep->num = ep_addr & 0x7FU; - ep->is_in = ((ep_addr & 0x80U) == 0x80U); + ep->is_stall = 0; + ep->num = ep_addr & 0x7F; + ep->is_in = ((ep_addr & 0x80) == 0x80); __HAL_LOCK(hpcd); USB_EPClearStall(hpcd->Instance , ep); @@ -1066,9 +1080,9 @@ HAL_StatusTypeDef HAL_PCD_EP_Flush(PCD_HandleTypeDef *hpcd, uint8_t ep_addr) { __HAL_LOCK(hpcd); - if ((ep_addr & 0x80U) == 0x80U) + if ((ep_addr & 0x80) == 0x80) { - USB_FlushTxFifo(hpcd->Instance, ep_addr & 0x7FU); + USB_FlushTxFifo(hpcd->Instance, ep_addr & 0x7F); } else { @@ -1153,8 +1167,8 @@ static HAL_StatusTypeDef PCD_WriteEmptyTxFifo(PCD_HandleTypeDef *hpcd, uint32_t USB_OTG_GlobalTypeDef *USBx = hpcd->Instance; USB_OTG_EPTypeDef *ep = NULL; int32_t len = 0; - uint32_t len32b = 0U; - uint32_t fifoemptymsk = 0U; + uint32_t len32b = 0; + uint32_t fifoemptymsk = 0; ep = &hpcd->IN_ep[epnum]; len = ep->xfer_len - ep->xfer_count; @@ -1164,20 +1178,20 @@ static HAL_StatusTypeDef PCD_WriteEmptyTxFifo(PCD_HandleTypeDef *hpcd, uint32_t len = ep->maxpacket; } - len32b = (len + 3U) / 4U; + len32b = (len + 3) / 4; while ((USBx_INEP(epnum)->DTXFSTS & USB_OTG_DTXFSTS_INEPTFSAV) > len32b && ep->xfer_count < ep->xfer_len && - ep->xfer_len != 0U) + ep->xfer_len != 0) { /* Write the FIFO */ len = ep->xfer_len - ep->xfer_count; - if ((uint32_t)len > ep->maxpacket) + if (len > ep->maxpacket) { len = ep->maxpacket; } - len32b = (len + 3U) / 4U; + len32b = (len + 3) / 4; USB_WritePacket(USBx, ep->xfer_buff, epnum, len); @@ -1187,7 +1201,7 @@ static HAL_StatusTypeDef PCD_WriteEmptyTxFifo(PCD_HandleTypeDef *hpcd, uint32_t if(len <= 0) { - fifoemptymsk = 0x01U << epnum; + fifoemptymsk = 0x1 << epnum; USBx_DEVICE->DIEPEMPMSK &= ~fifoemptymsk; } @@ -1234,13 +1248,13 @@ static HAL_StatusTypeDef PCD_EP_ISR_Handler(PCD_HandleTypeDef *hpcd) ep->xfer_buff += ep->xfer_count; /* TX COMPLETE */ - HAL_PCD_DataInStageCallback(hpcd, 0U); + HAL_PCD_DataInStageCallback(hpcd, 0); - if((hpcd->USB_Address > 0U)&& ( ep->xfer_len == 0U)) + if((hpcd->USB_Address > 0)&& ( ep->xfer_len == 0)) { hpcd->Instance->DADDR = (hpcd->USB_Address | USB_DADDR_EF); - hpcd->USB_Address = 0U; + hpcd->USB_Address = 0; } } @@ -1250,10 +1264,10 @@ static HAL_StatusTypeDef PCD_EP_ISR_Handler(PCD_HandleTypeDef *hpcd) /* DIR = 1 & CTR_RX => SETUP or OUT int */ /* DIR = 1 & (CTR_TX | CTR_RX) => 2 int pending */ - ep = &hpcd->OUT_ep[0U]; + ep = &hpcd->OUT_ep[0]; wEPVal = PCD_GET_ENDPOINT(hpcd->Instance, PCD_ENDP0); - if ((wEPVal & USB_EP_SETUP) != 0U) + if ((wEPVal & USB_EP_SETUP) != 0) { /* Get SETUP Packet*/ ep->xfer_count = PCD_GET_EP_RX_CNT(hpcd->Instance, ep->num); @@ -1265,20 +1279,20 @@ static HAL_StatusTypeDef PCD_EP_ISR_Handler(PCD_HandleTypeDef *hpcd) HAL_PCD_SetupStageCallback(hpcd); } - else if ((wEPVal & USB_EP_CTR_RX) != 0U) + else if ((wEPVal & USB_EP_CTR_RX) != 0) { PCD_CLEAR_RX_EP_CTR(hpcd->Instance, PCD_ENDP0); /* Get Control Data OUT Packet*/ ep->xfer_count = PCD_GET_EP_RX_CNT(hpcd->Instance, ep->num); - if (ep->xfer_count != 0U) + if (ep->xfer_count != 0) { USB_ReadPMA(hpcd->Instance, ep->xfer_buff, ep->pmaadress, ep->xfer_count); ep->xfer_buff+=ep->xfer_count; } /* Process Control Data OUT Packet*/ - HAL_PCD_DataOutStageCallback(hpcd, 0U); + HAL_PCD_DataOutStageCallback(hpcd, 0); PCD_SET_EP_RX_CNT(hpcd->Instance, PCD_ENDP0, ep->maxpacket); PCD_SET_EP_RX_STATUS(hpcd->Instance, PCD_ENDP0, USB_EP_RX_VALID); @@ -1291,17 +1305,17 @@ static HAL_StatusTypeDef PCD_EP_ISR_Handler(PCD_HandleTypeDef *hpcd) /* process related endpoint register */ wEPVal = PCD_GET_ENDPOINT(hpcd->Instance, epindex); - if ((wEPVal & USB_EP_CTR_RX) != 0U) + if ((wEPVal & USB_EP_CTR_RX) != 0) { /* clear int flag */ PCD_CLEAR_RX_EP_CTR(hpcd->Instance, epindex); ep = &hpcd->OUT_ep[epindex]; /* OUT double Buffering*/ - if (ep->doublebuffer == 0U) + if (ep->doublebuffer == 0) { count = PCD_GET_EP_RX_CNT(hpcd->Instance, ep->num); - if (count != 0U) + if (count != 0) { USB_ReadPMA(hpcd->Instance, ep->xfer_buff, ep->pmaadress, count); } @@ -1312,7 +1326,7 @@ static HAL_StatusTypeDef PCD_EP_ISR_Handler(PCD_HandleTypeDef *hpcd) { /*read from endpoint BUF0Addr buffer*/ count = PCD_GET_EP_DBUF0_CNT(hpcd->Instance, ep->num); - if (count != 0U) + if (count != 0) { USB_ReadPMA(hpcd->Instance, ep->xfer_buff, ep->pmaaddr0, count); } @@ -1321,7 +1335,7 @@ static HAL_StatusTypeDef PCD_EP_ISR_Handler(PCD_HandleTypeDef *hpcd) { /*read from endpoint BUF1Addr buffer*/ count = PCD_GET_EP_DBUF1_CNT(hpcd->Instance, ep->num); - if (count != 0U) + if (count != 0) { USB_ReadPMA(hpcd->Instance, ep->xfer_buff, ep->pmaaddr1, count); } @@ -1332,7 +1346,7 @@ static HAL_StatusTypeDef PCD_EP_ISR_Handler(PCD_HandleTypeDef *hpcd) ep->xfer_count+=count; ep->xfer_buff+=count; - if ((ep->xfer_len == 0U) || (count < ep->maxpacket)) + if ((ep->xfer_len == 0) || (count < ep->maxpacket)) { /* RX COMPLETE */ HAL_PCD_DataOutStageCallback(hpcd, ep->num); @@ -1344,7 +1358,7 @@ static HAL_StatusTypeDef PCD_EP_ISR_Handler(PCD_HandleTypeDef *hpcd) } /* if((wEPVal & EP_CTR_RX) */ - if ((wEPVal & USB_EP_CTR_TX) != 0U) + if ((wEPVal & USB_EP_CTR_TX) != 0) { ep = &hpcd->IN_ep[epindex]; @@ -1352,10 +1366,10 @@ static HAL_StatusTypeDef PCD_EP_ISR_Handler(PCD_HandleTypeDef *hpcd) PCD_CLEAR_TX_EP_CTR(hpcd->Instance, epindex); /* IN double Buffering*/ - if (ep->doublebuffer == 0U) + if (ep->doublebuffer == 0) { ep->xfer_count = PCD_GET_EP_TX_CNT(hpcd->Instance, ep->num); - if (ep->xfer_count != 0U) + if (ep->xfer_count != 0) { USB_WritePMA(hpcd->Instance, ep->xfer_buff, ep->pmaadress, ep->xfer_count); } @@ -1366,7 +1380,7 @@ static HAL_StatusTypeDef PCD_EP_ISR_Handler(PCD_HandleTypeDef *hpcd) { /*read from endpoint BUF0Addr buffer*/ ep->xfer_count = PCD_GET_EP_DBUF0_CNT(hpcd->Instance, ep->num); - if (ep->xfer_count != 0U) + if (ep->xfer_count != 0) { USB_WritePMA(hpcd->Instance, ep->xfer_buff, ep->pmaaddr0, ep->xfer_count); } @@ -1375,7 +1389,7 @@ static HAL_StatusTypeDef PCD_EP_ISR_Handler(PCD_HandleTypeDef *hpcd) { /*read from endpoint BUF1Addr buffer*/ ep->xfer_count = PCD_GET_EP_DBUF1_CNT(hpcd->Instance, ep->num); - if (ep->xfer_count != 0U) + if (ep->xfer_count != 0) { USB_WritePMA(hpcd->Instance, ep->xfer_buff, ep->pmaaddr1, ep->xfer_count); } @@ -1387,7 +1401,7 @@ static HAL_StatusTypeDef PCD_EP_ISR_Handler(PCD_HandleTypeDef *hpcd) ep->xfer_buff+=ep->xfer_count; /* Zero Length Packet? */ - if (ep->xfer_len == 0U) + if (ep->xfer_len == 0) { /* TX COMPLETE */ HAL_PCD_DataInStageCallback(hpcd, ep->num); diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_pcd.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_pcd.h index d92c82fdcd6..87f186eafdb 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_pcd.h +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_pcd.h @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_hal_pcd.h * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief Header file of PCD HAL module. ****************************************************************************** * @attention @@ -69,11 +69,11 @@ */ typedef enum { - HAL_PCD_STATE_RESET = 0x00U, - HAL_PCD_STATE_READY = 0x01U, - HAL_PCD_STATE_ERROR = 0x02U, - HAL_PCD_STATE_BUSY = 0x03U, - HAL_PCD_STATE_TIMEOUT = 0x04U + HAL_PCD_STATE_RESET = 0x00, + HAL_PCD_STATE_READY = 0x01, + HAL_PCD_STATE_ERROR = 0x02, + HAL_PCD_STATE_BUSY = 0x03, + HAL_PCD_STATE_TIMEOUT = 0x04 } PCD_StateTypeDef; #if defined (USB) @@ -118,11 +118,11 @@ typedef struct PCD_TypeDef *Instance; /*!< Register base address */ PCD_InitTypeDef Init; /*!< PCD required parameters */ __IO uint8_t USB_Address; /*!< USB Address: not used by USB OTG FS */ - PCD_EPTypeDef IN_ep[16]; /*!< IN endpoint parameters */ - PCD_EPTypeDef OUT_ep[16]; /*!< OUT endpoint parameters */ + PCD_EPTypeDef IN_ep[15]; /*!< IN endpoint parameters */ + PCD_EPTypeDef OUT_ep[15]; /*!< OUT endpoint parameters */ HAL_LockTypeDef Lock; /*!< PCD peripheral status */ __IO PCD_StateTypeDef State; /*!< PCD communication state */ - uint32_t Setup[12U]; /*!< Setup packet buffer */ + uint32_t Setup[12]; /*!< Setup packet buffer */ void *pData; /*!< Pointer to upper stack Handler */ } PCD_HandleTypeDef; @@ -141,9 +141,9 @@ typedef struct /** @defgroup PCD_Speed PCD Speed * @{ */ -#define PCD_SPEED_HIGH 0U /* Not Supported */ -#define PCD_SPEED_HIGH_IN_FULL 1U /* Not Supported */ -#define PCD_SPEED_FULL 2U +#define PCD_SPEED_HIGH 0 /* Not Supported */ +#define PCD_SPEED_HIGH_IN_FULL 1 /* Not Supported */ +#define PCD_SPEED_FULL 2 /** * @} */ @@ -151,7 +151,7 @@ typedef struct /** @defgroup PCD_PHY_Module PCD PHY Module * @{ */ -#define PCD_PHY_EMBEDDED 2U +#define PCD_PHY_EMBEDDED 2 /** * @} */ @@ -160,7 +160,7 @@ typedef struct * @{ */ #ifndef USBD_FS_TRDT_VALUE - #define USBD_FS_TRDT_VALUE 5U + #define USBD_FS_TRDT_VALUE 5 #endif /* USBD_FS_TRDT_VALUE */ /** * @} @@ -182,14 +182,14 @@ typedef struct #define __HAL_PCD_GET_FLAG(__HANDLE__, __INTERRUPT__) ((USB_ReadInterrupts((__HANDLE__)->Instance) & (__INTERRUPT__)) == (__INTERRUPT__)) #define __HAL_PCD_CLEAR_FLAG(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->GINTSTS) = (__INTERRUPT__)) -#define __HAL_PCD_IS_INVALID_INTERRUPT(__HANDLE__) (USB_ReadInterrupts((__HANDLE__)->Instance) == 0U) +#define __HAL_PCD_IS_INVALID_INTERRUPT(__HANDLE__) (USB_ReadInterrupts((__HANDLE__)->Instance) == 0) #define __HAL_PCD_UNGATE_PHYCLOCK(__HANDLE__) *(__IO uint32_t *)((uint32_t)((__HANDLE__)->Instance) + USB_OTG_PCGCCTL_BASE) &= \ ~(USB_OTG_PCGCCTL_STOPCLK) #define __HAL_PCD_GATE_PHYCLOCK(__HANDLE__) *(__IO uint32_t *)((uint32_t)((__HANDLE__)->Instance) + USB_OTG_PCGCCTL_BASE) |= USB_OTG_PCGCCTL_STOPCLK -#define __HAL_PCD_IS_PHY_SUSPENDED(__HANDLE__) ((*(__IO uint32_t *)((uint32_t)((__HANDLE__)->Instance) + USB_OTG_PCGCCTL_BASE)) & 0x10U) +#define __HAL_PCD_IS_PHY_SUSPENDED(__HANDLE__) ((*(__IO uint32_t *)((uint32_t)((__HANDLE__)->Instance) + USB_OTG_PCGCCTL_BASE))&0x10) #define __HAL_USB_OTG_FS_WAKEUP_EXTI_ENABLE_IT() EXTI->IMR |= USB_OTG_FS_WAKEUP_EXTI_LINE #define __HAL_USB_OTG_FS_WAKEUP_EXTI_DISABLE_IT() EXTI->IMR &= ~(USB_OTG_FS_WAKEUP_EXTI_LINE) @@ -200,13 +200,13 @@ typedef struct do{ \ EXTI->FTSR &= ~(USB_OTG_FS_WAKEUP_EXTI_LINE); \ EXTI->RTSR |= USB_OTG_FS_WAKEUP_EXTI_LINE; \ - } while(0U) + } while(0) #define __HAL_USB_OTG_FS_WAKEUP_EXTI_ENABLE_FALLING_EDGE() \ do{ \ EXTI->FTSR |= (USB_OTG_FS_WAKEUP_EXTI_LINE); \ EXTI->RTSR &= ~(USB_OTG_FS_WAKEUP_EXTI_LINE); \ - } while(0U) + } while(0) #define __HAL_USB_OTG_FS_WAKEUP_EXTI_ENABLE_RISING_FALLING_EDGE() \ do{ \ @@ -214,7 +214,7 @@ typedef struct EXTI->FTSR &= ~(USB_OTG_FS_WAKEUP_EXTI_LINE); \ EXTI->RTSR |= USB_OTG_FS_WAKEUP_EXTI_LINE; \ EXTI->FTSR |= USB_OTG_FS_WAKEUP_EXTI_LINE; \ - } while(0U) + } while(0) #define __HAL_USB_OTG_FS_WAKEUP_EXTI_GENERATE_SWIT() (EXTI->SWIER |= USB_OTG_FS_WAKEUP_EXTI_LINE) #endif /* USB_OTG_FS */ @@ -234,13 +234,13 @@ typedef struct do{ \ EXTI->FTSR &= ~(USB_WAKEUP_EXTI_LINE); \ EXTI->RTSR |= USB_WAKEUP_EXTI_LINE; \ - } while(0U) + } while(0) #define __HAL_USB_WAKEUP_EXTI_ENABLE_FALLING_EDGE() \ do{ \ EXTI->FTSR |= (USB_WAKEUP_EXTI_LINE); \ EXTI->RTSR &= ~(USB_WAKEUP_EXTI_LINE); \ - } while(0U) + } while(0) #define __HAL_USB_WAKEUP_EXTI_ENABLE_RISING_FALLING_EDGE() \ do{ \ @@ -248,7 +248,7 @@ typedef struct EXTI->FTSR &= ~(USB_WAKEUP_EXTI_LINE); \ EXTI->RTSR |= USB_WAKEUP_EXTI_LINE; \ EXTI->FTSR |= USB_WAKEUP_EXTI_LINE; \ - } while(0U) + } while(0) #endif /* USB */ /** @@ -338,15 +338,15 @@ PCD_StateTypeDef HAL_PCD_GetState(PCD_HandleTypeDef *hpcd); * @{ */ #if defined (USB_OTG_FS) -#define USB_OTG_FS_WAKEUP_EXTI_RISING_EDGE 0x08U -#define USB_OTG_FS_WAKEUP_EXTI_FALLING_EDGE 0x0CU -#define USB_OTG_FS_WAKEUP_EXTI_RISING_FALLING_EDGE 0x10U +#define USB_OTG_FS_WAKEUP_EXTI_RISING_EDGE ((uint32_t)0x08) +#define USB_OTG_FS_WAKEUP_EXTI_FALLING_EDGE ((uint32_t)0x0C) +#define USB_OTG_FS_WAKEUP_EXTI_RISING_FALLING_EDGE ((uint32_t)0x10) -#define USB_OTG_FS_WAKEUP_EXTI_LINE 0x00040000U /*!< External interrupt line 18 Connected to the USB EXTI Line */ +#define USB_OTG_FS_WAKEUP_EXTI_LINE ((uint32_t)0x00040000) /*!< External interrupt line 18 Connected to the USB EXTI Line */ #endif /* USB_OTG_FS */ #if defined (USB) -#define USB_WAKEUP_EXTI_LINE 0x00040000U /*!< External interrupt line 18 Connected to the USB EXTI Line */ +#define USB_WAKEUP_EXTI_LINE ((uint32_t)0x00040000) /*!< External interrupt line 18 Connected to the USB EXTI Line */ #endif /* USB */ /** * @} @@ -382,8 +382,8 @@ PCD_StateTypeDef HAL_PCD_GetState(PCD_HandleTypeDef *hpcd); /** @defgroup PCD_ENDP_Kind PCD Endpoint Kind * @{ */ -#define PCD_SNG_BUF 0U -#define PCD_DBL_BUF 1U +#define PCD_SNG_BUF 0 +#define PCD_DBL_BUF 1 /** * @} */ @@ -398,10 +398,10 @@ PCD_StateTypeDef HAL_PCD_GetState(PCD_HandleTypeDef *hpcd); */ #if defined (USB) /* SetENDPOINT */ -#define PCD_SET_ENDPOINT(USBx, bEpNum,wRegValue) (*(&(USBx)->EP0R + (bEpNum) * 2U)= (uint16_t)(wRegValue)) +#define PCD_SET_ENDPOINT(USBx, bEpNum,wRegValue) (*(&(USBx)->EP0R + (bEpNum) * 2)= (uint16_t)(wRegValue)) /* GetENDPOINT */ -#define PCD_GET_ENDPOINT(USBx, bEpNum) (*(&(USBx)->EP0R + (bEpNum) * 2U)) +#define PCD_GET_ENDPOINT(USBx, bEpNum) (*(&(USBx)->EP0R + (bEpNum) * 2)) /* ENDPOINT transfer */ #define USB_EP0StartXfer USB_EPStartXfer @@ -414,7 +414,7 @@ PCD_StateTypeDef HAL_PCD_GetState(PCD_HandleTypeDef *hpcd); * @retval None */ #define PCD_SET_EPTYPE(USBx, bEpNum,wType) (PCD_SET_ENDPOINT((USBx), (bEpNum),\ - ((PCD_GET_ENDPOINT((USBx), (bEpNum)) & USB_EP_T_MASK) | (wType) ))) + ((PCD_GET_ENDPOINT((USBx), (bEpNum)) & USB_EP_T_MASK) | (wType) ))) /** * @brief gets the type in the endpoint register(bits EP_TYPE[1:0]) @@ -472,12 +472,12 @@ PCD_StateTypeDef HAL_PCD_GetState(PCD_HandleTypeDef *hpcd); \ _wRegVal = PCD_GET_ENDPOINT((USBx), (bEpNum)) & USB_EPTX_DTOGMASK;\ /* toggle first bit ? */ \ - if((USB_EPTX_DTOG1 & (wState))!= 0U)\ + if((USB_EPTX_DTOG1 & (wState))!= 0)\ { \ _wRegVal ^= USB_EPTX_DTOG1; \ } \ /* toggle second bit ? */ \ - if((USB_EPTX_DTOG2 & (wState))!= 0U) \ + if((USB_EPTX_DTOG2 & (wState))!= 0) \ { \ _wRegVal ^= USB_EPTX_DTOG2; \ } \ @@ -496,12 +496,12 @@ PCD_StateTypeDef HAL_PCD_GetState(PCD_HandleTypeDef *hpcd); \ _wRegVal = PCD_GET_ENDPOINT((USBx), (bEpNum)) & USB_EPRX_DTOGMASK;\ /* toggle first bit ? */ \ - if((USB_EPRX_DTOG1 & (wState))!= 0U) \ + if((USB_EPRX_DTOG1 & (wState))!= 0) \ { \ _wRegVal ^= USB_EPRX_DTOG1; \ } \ /* toggle second bit ? */ \ - if((USB_EPRX_DTOG2 & (wState))!= 0U) \ + if((USB_EPRX_DTOG2 & (wState))!= 0) \ { \ _wRegVal ^= USB_EPRX_DTOG2; \ } \ @@ -521,22 +521,22 @@ PCD_StateTypeDef HAL_PCD_GetState(PCD_HandleTypeDef *hpcd); \ _wRegVal = PCD_GET_ENDPOINT((USBx), (bEpNum)) & (USB_EPRX_DTOGMASK |USB_EPTX_STAT) ;\ /* toggle first bit ? */ \ - if((USB_EPRX_DTOG1 & ((wStaterx)))!= 0U) \ + if((USB_EPRX_DTOG1 & ((wStaterx)))!= 0) \ { \ _wRegVal ^= USB_EPRX_DTOG1; \ } \ /* toggle second bit ? */ \ - if((USB_EPRX_DTOG2 & (wStaterx))!= 0U) \ + if((USB_EPRX_DTOG2 & (wStaterx))!= 0) \ { \ _wRegVal ^= USB_EPRX_DTOG2; \ } \ /* toggle first bit ? */ \ - if((USB_EPTX_DTOG1 & (wStatetx))!= 0U) \ + if((USB_EPTX_DTOG1 & (wStatetx))!= 0) \ { \ _wRegVal ^= USB_EPTX_DTOG1; \ } \ /* toggle second bit ? */ \ - if((USB_EPTX_DTOG2 & (wStatetx))!= 0U) \ + if((USB_EPTX_DTOG2 & (wStatetx))!= 0) \ { \ _wRegVal ^= USB_EPTX_DTOG2; \ } \ @@ -609,9 +609,9 @@ PCD_StateTypeDef HAL_PCD_GetState(PCD_HandleTypeDef *hpcd); * @retval None */ #define PCD_CLEAR_RX_EP_CTR(USBx, bEpNum) (PCD_SET_ENDPOINT((USBx), (bEpNum),\ - PCD_GET_ENDPOINT((USBx), (bEpNum)) & 0x7FFFU & USB_EPREG_MASK)) + PCD_GET_ENDPOINT((USBx), (bEpNum)) & 0x7FFF & USB_EPREG_MASK)) #define PCD_CLEAR_TX_EP_CTR(USBx, bEpNum) (PCD_SET_ENDPOINT((USBx), (bEpNum),\ - PCD_GET_ENDPOINT((USBx), (bEpNum)) & 0xFF7FU & USB_EPREG_MASK)) + PCD_GET_ENDPOINT((USBx), (bEpNum)) & 0xFF7F & USB_EPREG_MASK)) /** * @brief Toggles DTOG_RX / DTOG_TX bit in the endpoint register. @@ -630,11 +630,11 @@ PCD_StateTypeDef HAL_PCD_GetState(PCD_HandleTypeDef *hpcd); * @param bEpNum: Endpoint Number. * @retval None */ -#define PCD_CLEAR_RX_DTOG(USBx, bEpNum) if((PCD_GET_ENDPOINT((USBx), (bEpNum)) & USB_EP_DTOG_RX) != 0U)\ +#define PCD_CLEAR_RX_DTOG(USBx, bEpNum) if((PCD_GET_ENDPOINT((USBx), (bEpNum)) & USB_EP_DTOG_RX) != 0)\ { \ PCD_RX_DTOG((USBx), (bEpNum)); \ } -#define PCD_CLEAR_TX_DTOG(USBx, bEpNum) if((PCD_GET_ENDPOINT((USBx), (bEpNum)) & USB_EP_DTOG_TX) != 0U)\ +#define PCD_CLEAR_TX_DTOG(USBx, bEpNum) if((PCD_GET_ENDPOINT((USBx), (bEpNum)) & USB_EP_DTOG_TX) != 0)\ { \ PCD_TX_DTOG((USBx), (bEpNum)); \ } @@ -651,10 +651,10 @@ PCD_StateTypeDef HAL_PCD_GetState(PCD_HandleTypeDef *hpcd); #define PCD_GET_EP_ADDRESS(USBx, bEpNum) ((uint8_t)(PCD_GET_ENDPOINT((USBx), (bEpNum)) & USB_EPADDR_FIELD)) -#define PCD_EP_TX_ADDRESS(USBx, bEpNum) ((uint32_t *)(((USBx)->BTABLE+(bEpNum)*8U)*2U+ ((uint32_t)(USBx) + 0x400U))) -#define PCD_EP_TX_CNT(USBx, bEpNum) ((uint32_t *)(((USBx)->BTABLE+(bEpNum)*8U+2U)*2U+ ((uint32_t)(USBx) + 0x400U))) -#define PCD_EP_RX_ADDRESS(USBx, bEpNum) ((uint32_t *)(((USBx)->BTABLE+(bEpNum)*8U+4U)*2U+ ((uint32_t)(USBx) + 0x400U))) -#define PCD_EP_RX_CNT(USBx, bEpNum) ((uint32_t *)(((USBx)->BTABLE+(bEpNum)*8U+6U)*2U+ ((uint32_t)(USBx) + 0x400U))) +#define PCD_EP_TX_ADDRESS(USBx, bEpNum) ((uint32_t *)(((USBx)->BTABLE+(bEpNum)*8)*2+ ((uint32_t)(USBx) + 0x400))) +#define PCD_EP_TX_CNT(USBx, bEpNum) ((uint32_t *)(((USBx)->BTABLE+(bEpNum)*8+2)*2+ ((uint32_t)(USBx) + 0x400))) +#define PCD_EP_RX_ADDRESS(USBx, bEpNum) ((uint32_t *)(((USBx)->BTABLE+(bEpNum)*8+4)*2+ ((uint32_t)(USBx) + 0x400))) +#define PCD_EP_RX_CNT(USBx, bEpNum) ((uint32_t *)(((USBx)->BTABLE+(bEpNum)*8+6)*2+ ((uint32_t)(USBx) + 0x400))) #define PCD_SET_EP_RX_CNT(USBx, bEpNum,wCount) {\ uint32_t *pdwReg = PCD_EP_RX_CNT((USBx), (bEpNum)); \ @@ -668,8 +668,8 @@ PCD_StateTypeDef HAL_PCD_GetState(PCD_HandleTypeDef *hpcd); * @param wAddr: address to be set (must be word aligned). * @retval None */ -#define PCD_SET_EP_TX_ADDRESS(USBx, bEpNum,wAddr) (*PCD_EP_TX_ADDRESS((USBx), (bEpNum)) = (((wAddr) >> 1U) << 1U)) -#define PCD_SET_EP_RX_ADDRESS(USBx, bEpNum,wAddr) (*PCD_EP_RX_ADDRESS((USBx), (bEpNum)) = (((wAddr) >> 1U) << 1U)) +#define PCD_SET_EP_TX_ADDRESS(USBx, bEpNum,wAddr) (*PCD_EP_TX_ADDRESS((USBx), (bEpNum)) = (((wAddr) >> 1) << 1)) +#define PCD_SET_EP_RX_ADDRESS(USBx, bEpNum,wAddr) (*PCD_EP_RX_ADDRESS((USBx), (bEpNum)) = (((wAddr) >> 1) << 1)) /** * @brief Gets address of the tx/rx buffer. @@ -688,26 +688,26 @@ PCD_StateTypeDef HAL_PCD_GetState(PCD_HandleTypeDef *hpcd); * @retval None */ #define PCD_CALC_BLK32(dwReg,wCount,wNBlocks) {\ - (wNBlocks) = (wCount) >> 5U;\ - if(((wCount) & 0x1FU) == 0U)\ + (wNBlocks) = (wCount) >> 5;\ + if(((wCount) & 0x1f) == 0)\ { \ (wNBlocks)--;\ } \ - *pdwReg = (uint16_t)((uint16_t)((wNBlocks) << 10U) | 0x8000U); \ + *pdwReg = (uint16_t)((uint16_t)((wNBlocks) << 10) | 0x8000); \ }/* PCD_CALC_BLK32 */ #define PCD_CALC_BLK2(dwReg,wCount,wNBlocks) {\ - (wNBlocks) = (wCount) >> 1U;\ - if(((wCount) & 0x01U) != 0U)\ + (wNBlocks) = (wCount) >> 1;\ + if(((wCount) & 0x1) != 0)\ { \ (wNBlocks)++;\ } \ - *pdwReg = (uint16_t)((wNBlocks) << 10U);\ + *pdwReg = (uint16_t)((wNBlocks) << 10);\ }/* PCD_CALC_BLK2 */ #define PCD_SET_EP_CNT_RX_REG(dwReg,wCount) {\ uint16_t wNBlocks;\ - if((wCount) > 62U) \ + if((wCount) > 62) \ { \ PCD_CALC_BLK32((dwReg),(wCount),wNBlocks); \ } \ @@ -738,8 +738,8 @@ PCD_StateTypeDef HAL_PCD_GetState(PCD_HandleTypeDef *hpcd); * @param bEpNum: Endpoint Number. * @retval Counter value */ -#define PCD_GET_EP_TX_CNT(USBx, bEpNum) ((uint16_t)(*PCD_EP_TX_CNT((USBx), (bEpNum))) & 0x3FFU) -#define PCD_GET_EP_RX_CNT(USBx, bEpNum) ((uint16_t)(*PCD_EP_RX_CNT((USBx), (bEpNum))) & 0x3FFU) +#define PCD_GET_EP_TX_CNT(USBx, bEpNum) ((uint16_t)(*PCD_EP_TX_CNT((USBx), (bEpNum))) & 0x3ff) +#define PCD_GET_EP_RX_CNT(USBx, bEpNum) ((uint16_t)(*PCD_EP_RX_CNT((USBx), (bEpNum))) & 0x3ff) /** * @brief Sets buffer 0/1 address in a double buffer endpoint. diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_pcd_ex.c b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_pcd_ex.c index edadc8fb529..b26902f2b5d 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_pcd_ex.c +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_pcd_ex.c @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_hal_pcd_ex.c * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief Extended PCD HAL module driver. * This file provides firmware functions to manage the following * functionalities of the USB Peripheral Controller: @@ -97,7 +97,7 @@ HAL_StatusTypeDef HAL_PCDEx_SetTxFiFo(PCD_HandleTypeDef *hpcd, uint8_t fifo, uint16_t size) { uint8_t index = 0; - uint32_t Tx_Offset = 0U; + uint32_t Tx_Offset = 0; /* TXn min size = 16 words. (n : Transmit FIFO index) When a TxFIFO is not used, the Configuration should be as follows: @@ -111,20 +111,20 @@ HAL_StatusTypeDef HAL_PCDEx_SetTxFiFo(PCD_HandleTypeDef *hpcd, uint8_t fifo, uin Tx_Offset = hpcd->Instance->GRXFSIZ; - if(fifo == 0U) + if(fifo == 0) { - hpcd->Instance->DIEPTXF0_HNPTXFSIZ = (size << 16U) | Tx_Offset; + hpcd->Instance->DIEPTXF0_HNPTXFSIZ = (size << 16) | Tx_Offset; } else { - Tx_Offset += (hpcd->Instance->DIEPTXF0_HNPTXFSIZ) >> 16U; - for(index = 0; index < (fifo - 1); index++) + Tx_Offset += (hpcd->Instance->DIEPTXF0_HNPTXFSIZ) >> 16; + for (index = 0; index < (fifo - 1); index++) { - Tx_Offset += (hpcd->Instance->DIEPTXF[index] >> 16U); + Tx_Offset += (hpcd->Instance->DIEPTXF[index] >> 16); } /* Multiply Tx_Size by 2 to get higher performance */ - hpcd->Instance->DIEPTXF[fifo - 1U] = (size << 16U) | Tx_Offset; + hpcd->Instance->DIEPTXF[fifo - 1] = (size << 16) | Tx_Offset; } @@ -171,9 +171,9 @@ HAL_StatusTypeDef HAL_PCDEx_PMAConfig(PCD_HandleTypeDef *hpcd, PCD_EPTypeDef *ep = NULL; /* initialize ep structure*/ - if ((ep_addr & 0x80U) == 0x80U) + if ((0x80 & ep_addr) == 0x80) { - ep = &hpcd->IN_ep[ep_addr & 0x7FU]; + ep = &hpcd->IN_ep[ep_addr & 0x7F]; } else { @@ -184,17 +184,17 @@ HAL_StatusTypeDef HAL_PCDEx_PMAConfig(PCD_HandleTypeDef *hpcd, if (ep_kind == PCD_SNG_BUF) { /*Single Buffer*/ - ep->doublebuffer = 0U; + ep->doublebuffer = 0; /*Configure te PMA*/ ep->pmaadress = (uint16_t)pmaadress; } else /*USB_DBL_BUF*/ { /*Double Buffer Endpoint*/ - ep->doublebuffer = 1U; + ep->doublebuffer = 1; /*Configure the PMA*/ - ep->pmaaddr0 = pmaadress & 0x0000FFFFU; - ep->pmaaddr1 = (pmaadress & 0xFFFF0000U) >> 16U; + ep->pmaaddr0 = pmaadress & 0xFFFF; + ep->pmaaddr1 = (pmaadress & 0xFFFF0000) >> 16; } return HAL_OK; diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_pcd_ex.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_pcd_ex.h index 09aae9018f9..54d52ddada5 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_pcd_ex.h +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_pcd_ex.h @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_hal_pcd_ex.h * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief Header file of Extended PCD HAL module. ****************************************************************************** * @attention diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_pwr.c b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_pwr.c index 84b2d130d3c..71ab9a39955 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_pwr.c +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_pwr.c @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_hal_pwr.c * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief PWR HAL module driver. * * This file provides firmware functions to manage the following @@ -65,10 +65,10 @@ /** @defgroup PWR_PVD_Mode_Mask PWR PVD Mode Mask * @{ */ -#define PVD_MODE_IT 0x00010000U -#define PVD_MODE_EVT 0x00020000U -#define PVD_RISING_EDGE 0x00000001U -#define PVD_FALLING_EDGE 0x00000002U +#define PVD_MODE_IT ((uint32_t)0x00010000) +#define PVD_MODE_EVT ((uint32_t)0x00020000) +#define PVD_RISING_EDGE ((uint32_t)0x00000001) +#define PVD_FALLING_EDGE ((uint32_t)0x00000002) /** * @} */ @@ -79,8 +79,8 @@ */ /* ------------- PWR registers bit address in the alias region ---------------*/ #define PWR_OFFSET (PWR_BASE - PERIPH_BASE) -#define PWR_CR_OFFSET 0x00U -#define PWR_CSR_OFFSET 0x04U +#define PWR_CR_OFFSET 0x00 +#define PWR_CSR_OFFSET 0x04 #define PWR_CR_OFFSET_BB (PWR_OFFSET + PWR_CR_OFFSET) #define PWR_CSR_OFFSET_BB (PWR_OFFSET + PWR_CSR_OFFSET) /** @@ -92,16 +92,16 @@ */ /* --- CR Register ---*/ /* Alias word address of LPSDSR bit */ -#define LPSDSR_BIT_NUMBER PWR_CR_LPDS_Pos -#define CR_LPSDSR_BB ((uint32_t)(PERIPH_BB_BASE + (PWR_CR_OFFSET_BB * 32U) + (LPSDSR_BIT_NUMBER * 4U))) +#define LPSDSR_BIT_NUMBER POSITION_VAL(PWR_CR_LPDS) +#define CR_LPSDSR_BB ((uint32_t)(PERIPH_BB_BASE + (PWR_CR_OFFSET_BB * 32) + (LPSDSR_BIT_NUMBER * 4))) /* Alias word address of DBP bit */ -#define DBP_BIT_NUMBER PWR_CR_DBP_Pos -#define CR_DBP_BB ((uint32_t)(PERIPH_BB_BASE + (PWR_CR_OFFSET_BB * 32U) + (DBP_BIT_NUMBER * 4U))) +#define DBP_BIT_NUMBER POSITION_VAL(PWR_CR_DBP) +#define CR_DBP_BB ((uint32_t)(PERIPH_BB_BASE + (PWR_CR_OFFSET_BB * 32) + (DBP_BIT_NUMBER * 4))) /* Alias word address of PVDE bit */ -#define PVDE_BIT_NUMBER PWR_CR_PVDE_Pos -#define CR_PVDE_BB ((uint32_t)(PERIPH_BB_BASE + (PWR_CR_OFFSET_BB * 32U) + (PVDE_BIT_NUMBER * 4U))) +#define PVDE_BIT_NUMBER POSITION_VAL(PWR_CR_PVDE) +#define CR_PVDE_BB ((uint32_t)(PERIPH_BB_BASE + (PWR_CR_OFFSET_BB * 32) + (PVDE_BIT_NUMBER * 4))) /** * @} @@ -113,7 +113,7 @@ /* --- CSR Register ---*/ /* Alias word address of EWUP1 bit */ -#define CSR_EWUP_BB(VAL) ((uint32_t)(PERIPH_BB_BASE + (PWR_CSR_OFFSET_BB * 32U) + (POSITION_VAL(VAL) * 4U))) +#define CSR_EWUP_BB(VAL) ((uint32_t)(PERIPH_BB_BASE + (PWR_CSR_OFFSET_BB * 32) + (POSITION_VAL(VAL) * 4))) /** * @} */ @@ -436,9 +436,6 @@ void HAL_PWR_EnterSLEEPMode(uint32_t Regulator, uint8_t SLEEPEntry) { /* Check the parameters */ /* No check on Regulator because parameter not used in SLEEP mode */ - /* Prevent unused argument(s) compilation warning */ - UNUSED(Regulator); - assert_param(IS_PWR_SLEEP_ENTRY(SLEEPEntry)); /* Clear SLEEPDEEP bit of Cortex System Control Register */ diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_pwr.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_pwr.h index af065b89d57..db20f8b95f5 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_pwr.h +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_pwr.h @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_hal_pwr.h * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief Header file of PWR HAL module. ****************************************************************************** * @attention @@ -116,13 +116,13 @@ typedef struct /** @defgroup PWR_PVD_Mode PWR PVD Mode * @{ */ -#define PWR_PVD_MODE_NORMAL 0x00000000U /*!< basic mode is used */ -#define PWR_PVD_MODE_IT_RISING 0x00010001U /*!< External Interrupt Mode with Rising edge trigger detection */ -#define PWR_PVD_MODE_IT_FALLING 0x00010002U /*!< External Interrupt Mode with Falling edge trigger detection */ -#define PWR_PVD_MODE_IT_RISING_FALLING 0x00010003U /*!< External Interrupt Mode with Rising/Falling edge trigger detection */ -#define PWR_PVD_MODE_EVENT_RISING 0x00020001U /*!< Event Mode with Rising edge trigger detection */ -#define PWR_PVD_MODE_EVENT_FALLING 0x00020002U /*!< Event Mode with Falling edge trigger detection */ -#define PWR_PVD_MODE_EVENT_RISING_FALLING 0x00020003U /*!< Event Mode with Rising/Falling edge trigger detection */ +#define PWR_PVD_MODE_NORMAL ((uint32_t)0x00000000) /*!< basic mode is used */ +#define PWR_PVD_MODE_IT_RISING ((uint32_t)0x00010001) /*!< External Interrupt Mode with Rising edge trigger detection */ +#define PWR_PVD_MODE_IT_FALLING ((uint32_t)0x00010002) /*!< External Interrupt Mode with Falling edge trigger detection */ +#define PWR_PVD_MODE_IT_RISING_FALLING ((uint32_t)0x00010003) /*!< External Interrupt Mode with Rising/Falling edge trigger detection */ +#define PWR_PVD_MODE_EVENT_RISING ((uint32_t)0x00020001) /*!< Event Mode with Rising edge trigger detection */ +#define PWR_PVD_MODE_EVENT_FALLING ((uint32_t)0x00020002) /*!< Event Mode with Falling edge trigger detection */ +#define PWR_PVD_MODE_EVENT_RISING_FALLING ((uint32_t)0x00020003) /*!< Event Mode with Rising/Falling edge trigger detection */ /** * @} @@ -142,7 +142,7 @@ typedef struct /** @defgroup PWR_Regulator_state_in_SLEEP_STOP_mode PWR Regulator state in SLEEP/STOP mode * @{ */ -#define PWR_MAINREGULATOR_ON 0x00000000U +#define PWR_MAINREGULATOR_ON ((uint32_t)0x00000000) #define PWR_LOWPOWERREGULATOR_ON PWR_CR_LPDS /** diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_rcc.c b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_rcc.c index 5d6e69f1bd7..868908a35f2 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_rcc.c +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_rcc.c @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_hal_rcc.c * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief RCC HAL module driver. * This file provides firmware functions to manage the following * functionalities of the Reset and Clock Control (RCC) peripheral: @@ -96,6 +96,10 @@ /** @defgroup RCC_Private_Constants RCC Private Constants * @{ */ +/* Bits position in in the CFGR register */ +#define RCC_CFGR_HPRE_BITNUMBER POSITION_VAL(RCC_CFGR_HPRE) +#define RCC_CFGR_PPRE1_BITNUMBER POSITION_VAL(RCC_CFGR_PPRE1) +#define RCC_CFGR_PPRE2_BITNUMBER POSITION_VAL(RCC_CFGR_PPRE2) /** * @} */ @@ -121,9 +125,7 @@ */ /* Private function prototypes -----------------------------------------------*/ -static void RCC_Delay(uint32_t mdelay); - -/* Exported functions --------------------------------------------------------*/ +/* Exported functions ---------------------------------------------------------*/ /** @defgroup RCC_Exported_Functions RCC Exported Functions * @{ @@ -231,13 +233,13 @@ void HAL_RCC_DeInit(void) CLEAR_REG(RCC->CFGR); /* Set HSITRIM bits to the reset value */ - MODIFY_REG(RCC->CR, RCC_CR_HSITRIM, (0x10U << RCC_CR_HSITRIM_Pos)); + MODIFY_REG(RCC->CR, RCC_CR_HSITRIM, ((uint32_t)0x10 << POSITION_VAL(RCC_CR_HSITRIM))); -#if defined(RCC_CFGR2_SUPPORT) +#if (defined(STM32F105xC) || defined(STM32F107xC) || defined (STM32F100xB) || defined (STM32F100xE)) /* Reset CFGR2 register */ CLEAR_REG(RCC->CFGR2); -#endif /* RCC_CFGR2_SUPPORT */ +#endif /* STM32F105xC || STM32F107xC || STM32F100xB || STM32F100xE */ /* Disable all interrupts */ CLEAR_REG(RCC->CIR); @@ -262,7 +264,7 @@ void HAL_RCC_DeInit(void) */ HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) { - uint32_t tickstart = 0U; + uint32_t tickstart = 0; /* Check the parameters */ assert_param(RCC_OscInitStruct != NULL); @@ -410,7 +412,7 @@ HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) } /* To have a fully stabilized clock in the specified range, a software delay of 1ms should be added.*/ - RCC_Delay(1); + HAL_Delay(1); } else { @@ -433,35 +435,25 @@ HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) /*------------------------------ LSE Configuration -------------------------*/ if(((RCC_OscInitStruct->OscillatorType) & RCC_OSCILLATORTYPE_LSE) == RCC_OSCILLATORTYPE_LSE) { - FlagStatus pwrclkchanged = RESET; - /* Check the parameters */ assert_param(IS_RCC_LSE(RCC_OscInitStruct->LSEState)); - /* Update LSE configuration in Backup Domain control register */ - /* Requires to enable write access to Backup Domain of necessary */ - if(__HAL_RCC_PWR_IS_CLK_DISABLED()) - { + /* Enable Power Clock*/ __HAL_RCC_PWR_CLK_ENABLE(); - pwrclkchanged = SET; - } - if(HAL_IS_BIT_CLR(PWR->CR, PWR_CR_DBP)) - { /* Enable write access to Backup domain */ SET_BIT(PWR->CR, PWR_CR_DBP); /* Wait for Backup domain Write protection disable */ tickstart = HAL_GetTick(); - while(HAL_IS_BIT_CLR(PWR->CR, PWR_CR_DBP)) + while((PWR->CR & PWR_CR_DBP) == RESET) { if((HAL_GetTick() - tickstart) > RCC_DBP_TIMEOUT_VALUE) { return HAL_TIMEOUT; } } - } /* Set the new LSE configuration -----------------------------------------*/ __HAL_RCC_LSE_CONFIG(RCC_OscInitStruct->LSEState); @@ -494,12 +486,6 @@ HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) } } } - - /* Require to disable power clock if necessary */ - if(pwrclkchanged == SET) - { - __HAL_RCC_PWR_CLK_DISABLE(); - } } #if defined(RCC_CR_PLL2ON) @@ -708,7 +694,7 @@ HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) */ HAL_StatusTypeDef HAL_RCC_ClockConfig(RCC_ClkInitTypeDef *RCC_ClkInitStruct, uint32_t FLatency) { - uint32_t tickstart = 0U; + uint32_t tickstart = 0; /* Check the parameters */ assert_param(RCC_ClkInitStruct != NULL); @@ -841,7 +827,7 @@ HAL_StatusTypeDef HAL_RCC_ClockConfig(RCC_ClkInitTypeDef *RCC_ClkInitStruct, ui } /* Update the SystemCoreClock global variable */ - SystemCoreClock = HAL_RCC_GetSysClockFreq() >> AHBPrescTable[(RCC->CFGR & RCC_CFGR_HPRE)>> RCC_CFGR_HPRE_Pos]; + SystemCoreClock = HAL_RCC_GetSysClockFreq() >> AHBPrescTable[(RCC->CFGR & RCC_CFGR_HPRE)>> RCC_CFGR_HPRE_BITNUMBER]; /* Configure the source of time base considering new system clocks settings*/ HAL_InitTick (TICK_INT_PRIORITY); @@ -901,17 +887,13 @@ HAL_StatusTypeDef HAL_RCC_ClockConfig(RCC_ClkInitTypeDef *RCC_ClkInitStruct, ui */ void HAL_RCC_MCOConfig(uint32_t RCC_MCOx, uint32_t RCC_MCOSource, uint32_t RCC_MCODiv) { - GPIO_InitTypeDef gpio = {0U}; + GPIO_InitTypeDef gpio = {0}; /* Check the parameters */ assert_param(IS_RCC_MCO(RCC_MCOx)); assert_param(IS_RCC_MCODIV(RCC_MCODiv)); assert_param(IS_RCC_MCO1SOURCE(RCC_MCOSource)); - - /* Prevent unused argument(s) compilation warning */ - UNUSED(RCC_MCOx); - UNUSED(RCC_MCODiv); - + /* Configure the MCO1 pin in alternate function mode */ gpio.Mode = GPIO_MODE_AF_PP; gpio.Speed = GPIO_SPEED_FREQ_HIGH; @@ -920,9 +902,9 @@ void HAL_RCC_MCOConfig(uint32_t RCC_MCOx, uint32_t RCC_MCOSource, uint32_t RCC_M /* MCO1 Clock Enable */ MCO1_CLK_ENABLE(); - + HAL_GPIO_Init(MCO1_GPIO_PORT, &gpio); - + /* Configure the MCO clock source */ __HAL_RCC_MCO1_CONFIG(RCC_MCOSource, RCC_MCODiv); } @@ -981,22 +963,22 @@ void HAL_RCC_DisableCSS(void) */ uint32_t HAL_RCC_GetSysClockFreq(void) { -#if defined(RCC_CFGR2_PREDIV1SRC) - const uint8_t aPLLMULFactorTable[14] = {0, 0, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 13}; - const uint8_t aPredivFactorTable[16] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; +#if defined(RCC_CFGR2_PREDIV1SRC) + const uint8_t aPLLMULFactorTable[12] = {0, 0, 4, 5, 6, 7, 8, 9, 0, 0, 0, 13}; + const uint8_t aPredivFactorTable[16] = { 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11, 12, 13, 14, 15, 16}; #else - const uint8_t aPLLMULFactorTable[16] = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 16}; + const uint8_t aPLLMULFactorTable[16] = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 16}; #if defined(RCC_CFGR2_PREDIV1) - const uint8_t aPredivFactorTable[16] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; + const uint8_t aPredivFactorTable[16] = { 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11, 12, 13, 14, 15, 16}; #else - const uint8_t aPredivFactorTable[2] = {1, 2}; + const uint8_t aPredivFactorTable[2] = { 1, 2}; #endif /*RCC_CFGR2_PREDIV1*/ #endif - uint32_t tmpreg = 0U, prediv = 0U, pllclk = 0U, pllmul = 0U; - uint32_t sysclockfreq = 0U; + uint32_t tmpreg = 0, prediv = 0, pllclk = 0, pllmul = 0; + uint32_t sysclockfreq = 0; #if defined(RCC_CFGR2_PREDIV1SRC) - uint32_t prediv2 = 0U, pll2mul = 0U; + uint32_t prediv2 = 0, pll2mul = 0; #endif /*RCC_CFGR2_PREDIV1SRC*/ tmpreg = RCC->CFGR; @@ -1011,13 +993,13 @@ uint32_t HAL_RCC_GetSysClockFreq(void) } case RCC_SYSCLKSOURCE_STATUS_PLLCLK: /* PLL used as system clock */ { - pllmul = aPLLMULFactorTable[(uint32_t)(tmpreg & RCC_CFGR_PLLMULL) >> RCC_CFGR_PLLMULL_Pos]; + pllmul = aPLLMULFactorTable[(uint32_t)(tmpreg & RCC_CFGR_PLLMULL) >> POSITION_VAL(RCC_CFGR_PLLMULL)]; if ((tmpreg & RCC_CFGR_PLLSRC) != RCC_PLLSOURCE_HSI_DIV2) { #if defined(RCC_CFGR2_PREDIV1) - prediv = aPredivFactorTable[(uint32_t)(RCC->CFGR2 & RCC_CFGR2_PREDIV1) >> RCC_CFGR2_PREDIV1_Pos]; + prediv = aPredivFactorTable[(uint32_t)(RCC->CFGR2 & RCC_CFGR2_PREDIV1) >> POSITION_VAL(RCC_CFGR2_PREDIV1)]; #else - prediv = aPredivFactorTable[(uint32_t)(RCC->CFGR & RCC_CFGR_PLLXTPRE) >> RCC_CFGR_PLLXTPRE_Pos]; + prediv = aPredivFactorTable[(uint32_t)(RCC->CFGR & RCC_CFGR_PLLXTPRE) >> POSITION_VAL(RCC_CFGR_PLLXTPRE)]; #endif /*RCC_CFGR2_PREDIV1*/ #if defined(RCC_CFGR2_PREDIV1SRC) @@ -1025,8 +1007,8 @@ uint32_t HAL_RCC_GetSysClockFreq(void) { /* PLL2 selected as Prediv1 source */ /* PLLCLK = PLL2CLK / PREDIV1 * PLLMUL with PLL2CLK = HSE/PREDIV2 * PLL2MUL */ - prediv2 = ((RCC->CFGR2 & RCC_CFGR2_PREDIV2) >> RCC_CFGR2_PREDIV2_Pos) + 1; - pll2mul = ((RCC->CFGR2 & RCC_CFGR2_PLL2MUL) >> RCC_CFGR2_PLL2MUL_Pos) + 2; + prediv2 = ((RCC->CFGR2 & RCC_CFGR2_PREDIV2) >> POSITION_VAL(RCC_CFGR2_PREDIV2)) + 1; + pll2mul = ((RCC->CFGR2 & RCC_CFGR2_PLL2MUL) >> POSITION_VAL(RCC_CFGR2_PLL2MUL)) + 2; pllclk = (uint32_t)((((HSE_VALUE / prediv2) * pll2mul) / prediv) * pllmul); } else @@ -1037,7 +1019,7 @@ uint32_t HAL_RCC_GetSysClockFreq(void) /* If PLLMUL was set to 13 means that it was to cover the case PLLMUL 6.5 (avoid using float) */ /* In this case need to divide pllclk by 2 */ - if (pllmul == aPLLMULFactorTable[(uint32_t)(RCC_CFGR_PLLMULL6_5) >> RCC_CFGR_PLLMULL_Pos]) + if (pllmul == aPLLMULFactorTable[(uint32_t)(RCC_CFGR_PLLMULL6_5) >> POSITION_VAL(RCC_CFGR_PLLMULL)]) { pllclk = pllclk / 2; } @@ -1087,7 +1069,7 @@ uint32_t HAL_RCC_GetHCLKFreq(void) uint32_t HAL_RCC_GetPCLK1Freq(void) { /* Get HCLK source and Compute PCLK1 frequency ---------------------------*/ - return (HAL_RCC_GetHCLKFreq() >> APBPrescTable[(RCC->CFGR & RCC_CFGR_PPRE1) >> RCC_CFGR_PPRE1_Pos]); + return (HAL_RCC_GetHCLKFreq() >> APBPrescTable[(RCC->CFGR & RCC_CFGR_PPRE1) >> RCC_CFGR_PPRE1_BITNUMBER]); } /** @@ -1099,7 +1081,7 @@ uint32_t HAL_RCC_GetPCLK1Freq(void) uint32_t HAL_RCC_GetPCLK2Freq(void) { /* Get HCLK source and Compute PCLK2 frequency ---------------------------*/ - return (HAL_RCC_GetHCLKFreq()>> APBPrescTable[(RCC->CFGR & RCC_CFGR_PPRE2) >> RCC_CFGR_PPRE2_Pos]); + return (HAL_RCC_GetHCLKFreq()>> APBPrescTable[(RCC->CFGR & RCC_CFGR_PPRE2) >> RCC_CFGR_PPRE2_BITNUMBER]); } /** @@ -1148,7 +1130,7 @@ void HAL_RCC_GetOscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) RCC_OscInitStruct->HSIState = RCC_HSI_OFF; } - RCC_OscInitStruct->HSICalibrationValue = (uint32_t)((RCC->CR & RCC_CR_HSITRIM) >> RCC_CR_HSITRIM_Pos); + RCC_OscInitStruct->HSICalibrationValue = (uint32_t)((RCC->CR & RCC_CR_HSITRIM) >> POSITION_VAL(RCC_CR_HSITRIM)); /* Get the LSE configuration -----------------------------------------------*/ if((RCC->BDCR &RCC_BDCR_LSEBYP) == RCC_BDCR_LSEBYP) @@ -1257,21 +1239,6 @@ void HAL_RCC_NMI_IRQHandler(void) } } -/** - * @brief This function provides delay (in milliseconds) based on CPU cycles method. - * @param mdelay: specifies the delay time length, in milliseconds. - * @retval None - */ -static void RCC_Delay(uint32_t mdelay) -{ - __IO uint32_t Delay = mdelay * (SystemCoreClock / 8U / 1000U); - do - { - __NOP(); - } - while (Delay --); -} - /** * @brief RCC Clock Security System interrupt callback * @retval none diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_rcc.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_rcc.h index ebfc2805e64..f91c2737827 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_rcc.h +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_rcc.h @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_hal_rcc.h * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief Header file of RCC HAL module. ****************************************************************************** * @attention @@ -54,6 +54,176 @@ * @{ */ +/** @addtogroup RCC_Private_Constants + * @{ + */ + +/** @defgroup RCC_Timeout RCC Timeout + * @{ + */ + +/* Disable Backup domain write protection state change timeout */ +#define RCC_DBP_TIMEOUT_VALUE ((uint32_t)100) /* 100 ms */ +/* LSE state change timeout */ +#define RCC_LSE_TIMEOUT_VALUE LSE_STARTUP_TIMEOUT +#define CLOCKSWITCH_TIMEOUT_VALUE ((uint32_t)5000) /* 5 s */ +#define HSE_TIMEOUT_VALUE HSE_STARTUP_TIMEOUT +#define HSI_TIMEOUT_VALUE ((uint32_t)2) /* 2 ms (minimum Tick + 1) */ +#define LSI_TIMEOUT_VALUE ((uint32_t)2) /* 2 ms (minimum Tick + 1) */ +#define PLL_TIMEOUT_VALUE ((uint32_t)2) /* 2 ms (minimum Tick + 1) */ +#define LSI_VALUE ((uint32_t)40000) /* 40kHz */ +/** + * @} + */ + +/** @defgroup RCC_Register_Offset Register offsets + * @{ + */ +#define RCC_OFFSET (RCC_BASE - PERIPH_BASE) +#define RCC_CR_OFFSET 0x00 +#define RCC_CFGR_OFFSET 0x04 +#define RCC_CIR_OFFSET 0x08 +#define RCC_BDCR_OFFSET 0x20 +#define RCC_CSR_OFFSET 0x24 + +/** + * @} + */ + +/** @defgroup RCC_BitAddress_AliasRegion BitAddress AliasRegion + * @brief RCC registers bit address in the alias region + * @{ + */ +#define RCC_CR_OFFSET_BB (RCC_OFFSET + RCC_CR_OFFSET) +#define RCC_CFGR_OFFSET_BB (RCC_OFFSET + RCC_CFGR_OFFSET) +#define RCC_CIR_OFFSET_BB (RCC_OFFSET + RCC_CIR_OFFSET) +#define RCC_BDCR_OFFSET_BB (RCC_OFFSET + RCC_BDCR_OFFSET) +#define RCC_CSR_OFFSET_BB (RCC_OFFSET + RCC_CSR_OFFSET) + +/* --- CR Register ---*/ +/* Alias word address of HSION bit */ +#define RCC_HSION_BIT_NUMBER POSITION_VAL(RCC_CR_HSION) +#define RCC_CR_HSION_BB ((uint32_t)(PERIPH_BB_BASE + (RCC_CR_OFFSET_BB * 32) + (RCC_HSION_BIT_NUMBER * 4))) +/* Alias word address of HSEON bit */ +#define RCC_HSEON_BIT_NUMBER POSITION_VAL(RCC_CR_HSEON) +#define RCC_CR_HSEON_BB ((uint32_t)(PERIPH_BB_BASE + (RCC_CR_OFFSET_BB * 32) + (RCC_HSEON_BIT_NUMBER * 4))) +/* Alias word address of CSSON bit */ +#define RCC_CSSON_BIT_NUMBER POSITION_VAL(RCC_CR_CSSON) +#define RCC_CR_CSSON_BB ((uint32_t)(PERIPH_BB_BASE + (RCC_CR_OFFSET_BB * 32) + (RCC_CSSON_BIT_NUMBER * 4))) +/* Alias word address of PLLON bit */ +#define RCC_PLLON_BIT_NUMBER POSITION_VAL(RCC_CR_PLLON) +#define RCC_CR_PLLON_BB ((uint32_t)(PERIPH_BB_BASE + (RCC_CR_OFFSET_BB * 32) + (RCC_PLLON_BIT_NUMBER * 4))) + +/* --- CSR Register ---*/ +/* Alias word address of LSION bit */ +#define RCC_LSION_BIT_NUMBER POSITION_VAL(RCC_CSR_LSION) +#define RCC_CSR_LSION_BB ((uint32_t)(PERIPH_BB_BASE + (RCC_CSR_OFFSET_BB * 32) + (RCC_LSION_BIT_NUMBER * 4))) + +/* Alias word address of RMVF bit */ +#define RCC_RMVF_BIT_NUMBER POSITION_VAL(RCC_CSR_RMVF) +#define RCC_CSR_RMVF_BB ((uint32_t)(PERIPH_BB_BASE + (RCC_CSR_OFFSET_BB * 32) + (RCC_RMVF_BIT_NUMBER * 4))) + +/* --- BDCR Registers ---*/ +/* Alias word address of LSEON bit */ +#define RCC_LSEON_BIT_NUMBER POSITION_VAL(RCC_BDCR_LSEON) +#define RCC_BDCR_LSEON_BB ((uint32_t)(PERIPH_BB_BASE + (RCC_BDCR_OFFSET_BB * 32) + (RCC_LSEON_BIT_NUMBER * 4))) + +/* Alias word address of LSEON bit */ +#define RCC_LSEBYP_BIT_NUMBER POSITION_VAL(RCC_BDCR_LSEBYP) +#define RCC_BDCR_LSEBYP_BB ((uint32_t)(PERIPH_BB_BASE + (RCC_BDCR_OFFSET_BB * 32) + (RCC_LSEBYP_BIT_NUMBER * 4))) + +/* Alias word address of RTCEN bit */ +#define RCC_RTCEN_BIT_NUMBER POSITION_VAL(RCC_BDCR_RTCEN) +#define RCC_BDCR_RTCEN_BB ((uint32_t)(PERIPH_BB_BASE + (RCC_BDCR_OFFSET_BB * 32) + (RCC_RTCEN_BIT_NUMBER * 4))) + +/* Alias word address of BDRST bit */ +#define RCC_BDRST_BIT_NUMBER POSITION_VAL(RCC_BDCR_BDRST) +#define RCC_BDCR_BDRST_BB ((uint32_t)(PERIPH_BB_BASE + (RCC_BDCR_OFFSET_BB * 32) + (RCC_BDRST_BIT_NUMBER * 4))) + +/** + * @} + */ + +/* CR register byte 2 (Bits[23:16]) base address */ +#define RCC_CR_BYTE2_ADDRESS ((uint32_t)(RCC_BASE + RCC_CR_OFFSET + 0x02)) + +/* CIR register byte 1 (Bits[15:8]) base address */ +#define RCC_CIR_BYTE1_ADDRESS ((uint32_t)(RCC_BASE + RCC_CIR_OFFSET + 0x01)) + +/* CIR register byte 2 (Bits[23:16]) base address */ +#define RCC_CIR_BYTE2_ADDRESS ((uint32_t)(RCC_BASE + RCC_CIR_OFFSET + 0x02)) + +/* Defines used for Flags */ +#define CR_REG_INDEX ((uint8_t)1) +#define BDCR_REG_INDEX ((uint8_t)2) +#define CSR_REG_INDEX ((uint8_t)3) + +#define RCC_FLAG_MASK ((uint8_t)0x1F) + +/** + * @} + */ + +/** @addtogroup RCC_Private_Macros + * @{ + */ +/** @defgroup RCC_Alias_For_Legacy Alias define maintained for legacy + * @{ + */ +#define __HAL_RCC_SYSCFG_CLK_DISABLE __HAL_RCC_AFIO_CLK_DISABLE +#define __HAL_RCC_SYSCFG_CLK_ENABLE __HAL_RCC_AFIO_CLK_ENABLE +#define __HAL_RCC_SYSCFG_FORCE_RESET __HAL_RCC_AFIO_FORCE_RESET +#define __HAL_RCC_SYSCFG_RELEASE_RESET __HAL_RCC_AFIO_RELEASE_RESET +/** + * @} + */ + +#define IS_RCC_PLLSOURCE(__SOURCE__) (((__SOURCE__) == RCC_PLLSOURCE_HSI_DIV2) || \ + ((__SOURCE__) == RCC_PLLSOURCE_HSE)) +#define IS_RCC_OSCILLATORTYPE(__OSCILLATOR__) (((__OSCILLATOR__) == RCC_OSCILLATORTYPE_NONE) || \ + (((__OSCILLATOR__) & RCC_OSCILLATORTYPE_HSE) == RCC_OSCILLATORTYPE_HSE) || \ + (((__OSCILLATOR__) & RCC_OSCILLATORTYPE_HSI) == RCC_OSCILLATORTYPE_HSI) || \ + (((__OSCILLATOR__) & RCC_OSCILLATORTYPE_LSI) == RCC_OSCILLATORTYPE_LSI) || \ + (((__OSCILLATOR__) & RCC_OSCILLATORTYPE_LSE) == RCC_OSCILLATORTYPE_LSE)) +#define IS_RCC_HSE(__HSE__) (((__HSE__) == RCC_HSE_OFF) || ((__HSE__) == RCC_HSE_ON) || \ + ((__HSE__) == RCC_HSE_BYPASS)) +#define IS_RCC_LSE(__LSE__) (((__LSE__) == RCC_LSE_OFF) || ((__LSE__) == RCC_LSE_ON) || \ + ((__LSE__) == RCC_LSE_BYPASS)) +#define IS_RCC_HSI(__HSI__) (((__HSI__) == RCC_HSI_OFF) || ((__HSI__) == RCC_HSI_ON)) +#define IS_RCC_CALIBRATION_VALUE(__VALUE__) ((__VALUE__) <= 0x1F) +#define IS_RCC_LSI(__LSI__) (((__LSI__) == RCC_LSI_OFF) || ((__LSI__) == RCC_LSI_ON)) +#define IS_RCC_PLL(__PLL__) (((__PLL__) == RCC_PLL_NONE) || ((__PLL__) == RCC_PLL_OFF) || \ + ((__PLL__) == RCC_PLL_ON)) + +#define IS_RCC_CLOCKTYPE(CLK) ((((CLK) & RCC_CLOCKTYPE_SYSCLK) == RCC_CLOCKTYPE_SYSCLK) || \ + (((CLK) & RCC_CLOCKTYPE_HCLK) == RCC_CLOCKTYPE_HCLK) || \ + (((CLK) & RCC_CLOCKTYPE_PCLK1) == RCC_CLOCKTYPE_PCLK1) || \ + (((CLK) & RCC_CLOCKTYPE_PCLK2) == RCC_CLOCKTYPE_PCLK2)) +#define IS_RCC_SYSCLKSOURCE(__SOURCE__) (((__SOURCE__) == RCC_SYSCLKSOURCE_HSI) || \ + ((__SOURCE__) == RCC_SYSCLKSOURCE_HSE) || \ + ((__SOURCE__) == RCC_SYSCLKSOURCE_PLLCLK)) +#define IS_RCC_SYSCLKSOURCE_STATUS(__SOURCE__) (((__SOURCE__) == RCC_SYSCLKSOURCE_STATUS_HSI) || \ + ((__SOURCE__) == RCC_SYSCLKSOURCE_STATUS_HSE) || \ + ((__SOURCE__) == RCC_SYSCLKSOURCE_STATUS_PLLCLK)) +#define IS_RCC_HCLK(__HCLK__) (((__HCLK__) == RCC_SYSCLK_DIV1) || ((__HCLK__) == RCC_SYSCLK_DIV2) || \ + ((__HCLK__) == RCC_SYSCLK_DIV4) || ((__HCLK__) == RCC_SYSCLK_DIV8) || \ + ((__HCLK__) == RCC_SYSCLK_DIV16) || ((__HCLK__) == RCC_SYSCLK_DIV64) || \ + ((__HCLK__) == RCC_SYSCLK_DIV128) || ((__HCLK__) == RCC_SYSCLK_DIV256) || \ + ((__HCLK__) == RCC_SYSCLK_DIV512)) +#define IS_RCC_PCLK(__PCLK__) (((__PCLK__) == RCC_HCLK_DIV1) || ((__PCLK__) == RCC_HCLK_DIV2) || \ + ((__PCLK__) == RCC_HCLK_DIV4) || ((__PCLK__) == RCC_HCLK_DIV8) || \ + ((__PCLK__) == RCC_HCLK_DIV16)) +#define IS_RCC_MCO(__MCO__) ((__MCO__) == RCC_MCO) +#define IS_RCC_MCODIV(__DIV__) (((__DIV__) == RCC_MCODIV_1)) +#define IS_RCC_RTCCLKSOURCE(__SOURCE__) (((__SOURCE__) == RCC_RTCCLKSOURCE_NO_CLK) || \ + ((__SOURCE__) == RCC_RTCCLKSOURCE_LSE) || \ + ((__SOURCE__) == RCC_RTCCLKSOURCE_LSI) || \ + ((__SOURCE__) == RCC_RTCCLKSOURCE_HSE_DIV128)) + +/** + * @} + */ + /* Exported types ------------------------------------------------------------*/ /** @defgroup RCC_Exported_Types RCC Exported Types @@ -109,7 +279,7 @@ typedef struct * @{ */ -#define RCC_PLLSOURCE_HSI_DIV2 0x00000000U /*!< HSI clock divided by 2 selected as PLL entry clock source */ +#define RCC_PLLSOURCE_HSI_DIV2 ((uint32_t)0x00000000) /*!< HSI clock divided by 2 selected as PLL entry clock source */ #define RCC_PLLSOURCE_HSE RCC_CFGR_PLLSRC /*!< HSE clock selected as PLL entry clock source */ /** @@ -119,11 +289,11 @@ typedef struct /** @defgroup RCC_Oscillator_Type Oscillator Type * @{ */ -#define RCC_OSCILLATORTYPE_NONE 0x00000000U -#define RCC_OSCILLATORTYPE_HSE 0x00000001U -#define RCC_OSCILLATORTYPE_HSI 0x00000002U -#define RCC_OSCILLATORTYPE_LSE 0x00000004U -#define RCC_OSCILLATORTYPE_LSI 0x00000008U +#define RCC_OSCILLATORTYPE_NONE ((uint32_t)0x00000000) +#define RCC_OSCILLATORTYPE_HSE ((uint32_t)0x00000001) +#define RCC_OSCILLATORTYPE_HSI ((uint32_t)0x00000002) +#define RCC_OSCILLATORTYPE_LSE ((uint32_t)0x00000004) +#define RCC_OSCILLATORTYPE_LSI ((uint32_t)0x00000008) /** * @} */ @@ -131,7 +301,7 @@ typedef struct /** @defgroup RCC_HSE_Config HSE Config * @{ */ -#define RCC_HSE_OFF 0x00000000U /*!< HSE clock deactivation */ +#define RCC_HSE_OFF ((uint32_t)0x00000000) /*!< HSE clock deactivation */ #define RCC_HSE_ON RCC_CR_HSEON /*!< HSE clock activation */ #define RCC_HSE_BYPASS ((uint32_t)(RCC_CR_HSEBYP | RCC_CR_HSEON)) /*!< External clock source for HSE clock */ /** @@ -141,8 +311,8 @@ typedef struct /** @defgroup RCC_LSE_Config LSE Config * @{ */ -#define RCC_LSE_OFF 0x00000000U /*!< LSE clock deactivation */ -#define RCC_LSE_ON RCC_BDCR_LSEON /*!< LSE clock activation */ +#define RCC_LSE_OFF ((uint32_t)0x00000000) /*!< LSE clock deactivation */ +#define RCC_LSE_ON RCC_BDCR_LSEON /*!< LSE clock activation */ #define RCC_LSE_BYPASS ((uint32_t)(RCC_BDCR_LSEBYP | RCC_BDCR_LSEON)) /*!< External clock source for LSE clock */ /** @@ -152,10 +322,10 @@ typedef struct /** @defgroup RCC_HSI_Config HSI Config * @{ */ -#define RCC_HSI_OFF 0x00000000U /*!< HSI clock deactivation */ +#define RCC_HSI_OFF ((uint32_t)0x00000000) /*!< HSI clock deactivation */ #define RCC_HSI_ON RCC_CR_HSION /*!< HSI clock activation */ -#define RCC_HSICALIBRATION_DEFAULT 0x10U /* Default HSI calibration trimming value */ +#define RCC_HSICALIBRATION_DEFAULT ((uint32_t)0x10) /* Default HSI calibration trimming value */ /** * @} @@ -164,7 +334,7 @@ typedef struct /** @defgroup RCC_LSI_Config LSI Config * @{ */ -#define RCC_LSI_OFF 0x00000000U /*!< LSI clock deactivation */ +#define RCC_LSI_OFF ((uint32_t)0x00000000) /*!< LSI clock deactivation */ #define RCC_LSI_ON RCC_CSR_LSION /*!< LSI clock activation */ /** @@ -174,9 +344,9 @@ typedef struct /** @defgroup RCC_PLL_Config PLL Config * @{ */ -#define RCC_PLL_NONE 0x00000000U /*!< PLL is not configured */ -#define RCC_PLL_OFF 0x00000001U /*!< PLL deactivation */ -#define RCC_PLL_ON 0x00000002U /*!< PLL activation */ +#define RCC_PLL_NONE ((uint32_t)0x00000000) /*!< PLL is not configured */ +#define RCC_PLL_OFF ((uint32_t)0x00000001) /*!< PLL deactivation */ +#define RCC_PLL_ON ((uint32_t)0x00000002) /*!< PLL activation */ /** * @} @@ -185,10 +355,10 @@ typedef struct /** @defgroup RCC_System_Clock_Type System Clock Type * @{ */ -#define RCC_CLOCKTYPE_SYSCLK 0x00000001U /*!< SYSCLK to configure */ -#define RCC_CLOCKTYPE_HCLK 0x00000002U /*!< HCLK to configure */ -#define RCC_CLOCKTYPE_PCLK1 0x00000004U /*!< PCLK1 to configure */ -#define RCC_CLOCKTYPE_PCLK2 0x00000008U /*!< PCLK2 to configure */ +#define RCC_CLOCKTYPE_SYSCLK ((uint32_t)0x00000001) /*!< SYSCLK to configure */ +#define RCC_CLOCKTYPE_HCLK ((uint32_t)0x00000002) /*!< HCLK to configure */ +#define RCC_CLOCKTYPE_PCLK1 ((uint32_t)0x00000004) /*!< PCLK1 to configure */ +#define RCC_CLOCKTYPE_PCLK2 ((uint32_t)0x00000008) /*!< PCLK2 to configure */ /** * @} @@ -249,7 +419,7 @@ typedef struct /** @defgroup RCC_RTC_Clock_Source RTC Clock Source * @{ */ -#define RCC_RTCCLKSOURCE_NO_CLK 0x00000000U /*!< No clock */ +#define RCC_RTCCLKSOURCE_NO_CLK ((uint32_t)0x00000000) /*!< No clock */ #define RCC_RTCCLKSOURCE_LSE RCC_BDCR_RTCSEL_LSE /*!< LSE oscillator clock used as RTC clock */ #define RCC_RTCCLKSOURCE_LSI RCC_BDCR_RTCSEL_LSI /*!< LSI oscillator clock used as RTC clock */ #define RCC_RTCCLKSOURCE_HSE_DIV128 RCC_BDCR_RTCSEL_HSE /*!< HSE oscillator clock divided by 128 used as RTC clock */ @@ -261,7 +431,7 @@ typedef struct /** @defgroup RCC_MCO_Index MCO Index * @{ */ -#define RCC_MCO1 0x00000000U +#define RCC_MCO1 ((uint32_t)0x00000000) #define RCC_MCO RCC_MCO1 /*!< MCO1 to be compliant with other families with 2 MCOs*/ /** @@ -271,7 +441,7 @@ typedef struct /** @defgroup RCC_MCOx_Clock_Prescaler MCO Clock Prescaler * @{ */ -#define RCC_MCODIV_1 0x00000000U +#define RCC_MCODIV_1 ((uint32_t)0x00000000) /** * @} @@ -300,21 +470,21 @@ typedef struct * @{ */ /* Flags in the CR register */ -#define RCC_FLAG_HSIRDY ((uint8_t)((CR_REG_INDEX << 5U) | RCC_CR_HSIRDY_Pos)) /*!< Internal High Speed clock ready flag */ -#define RCC_FLAG_HSERDY ((uint8_t)((CR_REG_INDEX << 5U) | RCC_CR_HSERDY_Pos)) /*!< External High Speed clock ready flag */ -#define RCC_FLAG_PLLRDY ((uint8_t)((CR_REG_INDEX << 5U) | RCC_CR_PLLRDY_Pos)) /*!< PLL clock ready flag */ +#define RCC_FLAG_HSIRDY ((uint8_t)((CR_REG_INDEX << 5) | POSITION_VAL(RCC_CR_HSIRDY))) /*!< Internal High Speed clock ready flag */ +#define RCC_FLAG_HSERDY ((uint8_t)((CR_REG_INDEX << 5) | POSITION_VAL(RCC_CR_HSERDY))) /*!< External High Speed clock ready flag */ +#define RCC_FLAG_PLLRDY ((uint8_t)((CR_REG_INDEX << 5) | POSITION_VAL(RCC_CR_PLLRDY))) /*!< PLL clock ready flag */ /* Flags in the CSR register */ -#define RCC_FLAG_LSIRDY ((uint8_t)((CSR_REG_INDEX << 5U) | RCC_CSR_LSIRDY_Pos)) /*!< Internal Low Speed oscillator Ready */ -#define RCC_FLAG_PINRST ((uint8_t)((CSR_REG_INDEX << 5U) | RCC_CSR_PINRSTF_Pos)) /*!< PIN reset flag */ -#define RCC_FLAG_PORRST ((uint8_t)((CSR_REG_INDEX << 5U) | RCC_CSR_PORRSTF_Pos)) /*!< POR/PDR reset flag */ -#define RCC_FLAG_SFTRST ((uint8_t)((CSR_REG_INDEX << 5U) | RCC_CSR_SFTRSTF_Pos)) /*!< Software Reset flag */ -#define RCC_FLAG_IWDGRST ((uint8_t)((CSR_REG_INDEX << 5U) | RCC_CSR_IWDGRSTF_Pos)) /*!< Independent Watchdog reset flag */ -#define RCC_FLAG_WWDGRST ((uint8_t)((CSR_REG_INDEX << 5U) | RCC_CSR_WWDGRSTF_Pos)) /*!< Window watchdog reset flag */ -#define RCC_FLAG_LPWRRST ((uint8_t)((CSR_REG_INDEX << 5U) | RCC_CSR_LPWRRSTF_Pos)) /*!< Low-Power reset flag */ +#define RCC_FLAG_LSIRDY ((uint8_t)((CSR_REG_INDEX << 5) | POSITION_VAL(RCC_CSR_LSIRDY))) /*!< Internal Low Speed oscillator Ready */ +#define RCC_FLAG_PINRST ((uint8_t)((CSR_REG_INDEX << 5) | POSITION_VAL(RCC_CSR_PINRSTF))) /*!< PIN reset flag */ +#define RCC_FLAG_PORRST ((uint8_t)((CSR_REG_INDEX << 5) | POSITION_VAL(RCC_CSR_PORRSTF))) /*!< POR/PDR reset flag */ +#define RCC_FLAG_SFTRST ((uint8_t)((CSR_REG_INDEX << 5) | POSITION_VAL(RCC_CSR_SFTRSTF))) /*!< Software Reset flag */ +#define RCC_FLAG_IWDGRST ((uint8_t)((CSR_REG_INDEX << 5) | POSITION_VAL(RCC_CSR_IWDGRSTF))) /*!< Independent Watchdog reset flag */ +#define RCC_FLAG_WWDGRST ((uint8_t)((CSR_REG_INDEX << 5) | POSITION_VAL(RCC_CSR_WWDGRSTF))) /*!< Window watchdog reset flag */ +#define RCC_FLAG_LPWRRST ((uint8_t)((CSR_REG_INDEX << 5) | POSITION_VAL(RCC_CSR_LPWRRSTF))) /*!< Low-Power reset flag */ /* Flags in the BDCR register */ -#define RCC_FLAG_LSERDY ((uint8_t)((BDCR_REG_INDEX << 5U) | RCC_BDCR_LSERDY_Pos)) /*!< External Low Speed oscillator Ready */ +#define RCC_FLAG_LSERDY ((uint8_t)((BDCR_REG_INDEX << 5) | POSITION_VAL(RCC_BDCR_LSERDY))) /*!< External Low Speed oscillator Ready */ /** * @} @@ -343,7 +513,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */\ tmpreg = READ_BIT(RCC->AHBENR, RCC_AHBENR_DMA1EN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_SRAM_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ @@ -351,7 +521,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */\ tmpreg = READ_BIT(RCC->AHBENR, RCC_AHBENR_SRAMEN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_FLITF_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ @@ -359,7 +529,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */\ tmpreg = READ_BIT(RCC->AHBENR, RCC_AHBENR_FLITFEN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_CRC_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ @@ -367,7 +537,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */\ tmpreg = READ_BIT(RCC->AHBENR, RCC_AHBENR_CRCEN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_DMA1_CLK_DISABLE() (RCC->AHBENR &= ~(RCC_AHBENR_DMA1EN)) #define __HAL_RCC_SRAM_CLK_DISABLE() (RCC->AHBENR &= ~(RCC_AHBENR_SRAMEN)) @@ -412,7 +582,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */\ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM2EN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_TIM3_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ @@ -420,7 +590,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */\ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM3EN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_WWDG_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ @@ -428,7 +598,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */\ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_WWDGEN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_USART2_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ @@ -436,7 +606,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */\ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_USART2EN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_I2C1_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ @@ -444,7 +614,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */\ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C1EN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_BKP_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ @@ -452,7 +622,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */\ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_BKPEN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_PWR_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ @@ -460,7 +630,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */\ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_PWREN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_TIM2_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM2EN)) #define __HAL_RCC_TIM3_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM3EN)) @@ -489,14 +659,14 @@ typedef struct #define __HAL_RCC_TIM3_IS_CLK_DISABLED() ((RCC->APB1ENR & (RCC_APB1ENR_TIM3EN)) == RESET) #define __HAL_RCC_WWDG_IS_CLK_ENABLED() ((RCC->APB1ENR & (RCC_APB1ENR_WWDGEN)) != RESET) #define __HAL_RCC_WWDG_IS_CLK_DISABLED() ((RCC->APB1ENR & (RCC_APB1ENR_WWDGEN)) == RESET) -#define __HAL_RCC_USART2_IS_CLK_ENABLED() ((RCC->APB1ENR & (RCC_APB1ENR_USART2EN)) != RESET) -#define __HAL_RCC_USART2_IS_CLK_DISABLED() ((RCC->APB1ENR & (RCC_APB1ENR_USART2EN)) == RESET) +#define __HAL_RCC_USART2_IS_CLK_ENABLED() ((RCC->APB1ENR & (RCC_APB1ENR_USART2EN)) != RESET) +#define __HAL_RCC_USART2_IS_CLK_DISABLED() ((RCC->APB1ENR & (RCC_APB1ENR_USART2EN)) == RESET) #define __HAL_RCC_I2C1_IS_CLK_ENABLED() ((RCC->APB1ENR & (RCC_APB1ENR_I2C1EN)) != RESET) #define __HAL_RCC_I2C1_IS_CLK_DISABLED() ((RCC->APB1ENR & (RCC_APB1ENR_I2C1EN)) == RESET) -#define __HAL_RCC_BKP_IS_CLK_ENABLED() ((RCC->APB1ENR & (RCC_APB1ENR_BKPEN)) != RESET) -#define __HAL_RCC_BKP_IS_CLK_DISABLED() ((RCC->APB1ENR & (RCC_APB1ENR_BKPEN)) == RESET) -#define __HAL_RCC_PWR_IS_CLK_ENABLED() ((RCC->APB1ENR & (RCC_APB1ENR_PWREN)) != RESET) -#define __HAL_RCC_PWR_IS_CLK_DISABLED() ((RCC->APB1ENR & (RCC_APB1ENR_PWREN)) == RESET) +#define __HAL_RCC_BKP_IS_CLK_ENABLED() ((RCC->APB1ENR & (RCC_APB1ENR_BKPEN)) != RESET) +#define __HAL_RCC_BKP_IS_CLK_DISABLED() ((RCC->APB1ENR & (RCC_APB1ENR_BKPEN)) == RESET) +#define __HAL_RCC_PWR_IS_CLK_ENABLED() ((RCC->APB1ENR & (RCC_APB1ENR_PWREN)) != RESET) +#define __HAL_RCC_PWR_IS_CLK_DISABLED() ((RCC->APB1ENR & (RCC_APB1ENR_PWREN)) == RESET) /** * @} @@ -515,7 +685,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */\ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_AFIOEN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_GPIOA_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ @@ -523,7 +693,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */\ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_IOPAEN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_GPIOB_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ @@ -531,7 +701,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */\ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_IOPBEN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_GPIOC_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ @@ -539,7 +709,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */\ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_IOPCEN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_GPIOD_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ @@ -547,7 +717,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */\ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_IOPDEN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_ADC1_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ @@ -555,7 +725,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */\ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC1EN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_TIM1_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ @@ -563,7 +733,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */\ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM1EN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_SPI1_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ @@ -571,7 +741,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */\ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SPI1EN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_USART1_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ @@ -579,7 +749,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */\ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_USART1EN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_AFIO_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_AFIOEN)) #define __HAL_RCC_GPIOA_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_IOPAEN)) @@ -606,22 +776,22 @@ typedef struct #define __HAL_RCC_AFIO_IS_CLK_ENABLED() ((RCC->APB2ENR & (RCC_APB2ENR_AFIOEN)) != RESET) #define __HAL_RCC_AFIO_IS_CLK_DISABLED() ((RCC->APB2ENR & (RCC_APB2ENR_AFIOEN)) == RESET) -#define __HAL_RCC_GPIOA_IS_CLK_ENABLED() ((RCC->APB2ENR & (RCC_APB2ENR_IOPAEN)) != RESET) -#define __HAL_RCC_GPIOA_IS_CLK_DISABLED() ((RCC->APB2ENR & (RCC_APB2ENR_IOPAEN)) == RESET) -#define __HAL_RCC_GPIOB_IS_CLK_ENABLED() ((RCC->APB2ENR & (RCC_APB2ENR_IOPBEN)) != RESET) -#define __HAL_RCC_GPIOB_IS_CLK_DISABLED() ((RCC->APB2ENR & (RCC_APB2ENR_IOPBEN)) == RESET) -#define __HAL_RCC_GPIOC_IS_CLK_ENABLED() ((RCC->APB2ENR & (RCC_APB2ENR_IOPCEN)) != RESET) -#define __HAL_RCC_GPIOC_IS_CLK_DISABLED() ((RCC->APB2ENR & (RCC_APB2ENR_IOPCEN)) == RESET) -#define __HAL_RCC_GPIOD_IS_CLK_ENABLED() ((RCC->APB2ENR & (RCC_APB2ENR_IOPDEN)) != RESET) -#define __HAL_RCC_GPIOD_IS_CLK_DISABLED() ((RCC->APB2ENR & (RCC_APB2ENR_IOPDEN)) == RESET) +#define __HAL_RCC_GPIOA_IS_CLK_ENABLED() ((RCC->APB2ENR & (RCC_APB2ENR_IOPAEN)) != RESET) +#define __HAL_RCC_GPIOA_IS_CLK_DISABLED() ((RCC->APB2ENR & (RCC_APB2ENR_IOPAEN)) == RESET) +#define __HAL_RCC_GPIOB_IS_CLK_ENABLED() ((RCC->APB2ENR & (RCC_APB2ENR_IOPBEN)) != RESET) +#define __HAL_RCC_GPIOB_IS_CLK_DISABLED() ((RCC->APB2ENR & (RCC_APB2ENR_IOPBEN)) == RESET) +#define __HAL_RCC_GPIOC_IS_CLK_ENABLED() ((RCC->APB2ENR & (RCC_APB2ENR_IOPCEN)) != RESET) +#define __HAL_RCC_GPIOC_IS_CLK_DISABLED() ((RCC->APB2ENR & (RCC_APB2ENR_IOPCEN)) == RESET) +#define __HAL_RCC_GPIOD_IS_CLK_ENABLED() ((RCC->APB2ENR & (RCC_APB2ENR_IOPDEN)) != RESET) +#define __HAL_RCC_GPIOD_IS_CLK_DISABLED() ((RCC->APB2ENR & (RCC_APB2ENR_IOPDEN)) == RESET) #define __HAL_RCC_ADC1_IS_CLK_ENABLED() ((RCC->APB2ENR & (RCC_APB2ENR_ADC1EN)) != RESET) #define __HAL_RCC_ADC1_IS_CLK_DISABLED() ((RCC->APB2ENR & (RCC_APB2ENR_ADC1EN)) == RESET) #define __HAL_RCC_TIM1_IS_CLK_ENABLED() ((RCC->APB2ENR & (RCC_APB2ENR_TIM1EN)) != RESET) #define __HAL_RCC_TIM1_IS_CLK_DISABLED() ((RCC->APB2ENR & (RCC_APB2ENR_TIM1EN)) == RESET) #define __HAL_RCC_SPI1_IS_CLK_ENABLED() ((RCC->APB2ENR & (RCC_APB2ENR_SPI1EN)) != RESET) #define __HAL_RCC_SPI1_IS_CLK_DISABLED() ((RCC->APB2ENR & (RCC_APB2ENR_SPI1EN)) == RESET) -#define __HAL_RCC_USART1_IS_CLK_ENABLED() ((RCC->APB2ENR & (RCC_APB2ENR_USART1EN)) != RESET) -#define __HAL_RCC_USART1_IS_CLK_DISABLED() ((RCC->APB2ENR & (RCC_APB2ENR_USART1EN)) == RESET) +#define __HAL_RCC_USART1_IS_CLK_ENABLED() ((RCC->APB2ENR & (RCC_APB2ENR_USART1EN)) != RESET) +#define __HAL_RCC_USART1_IS_CLK_DISABLED() ((RCC->APB2ENR & (RCC_APB2ENR_USART1EN)) == RESET) /** * @} @@ -712,7 +882,7 @@ typedef struct * This parameter must be a number between 0 and 0x1F. */ #define __HAL_RCC_HSI_CALIBRATIONVALUE_ADJUST(_HSICALIBRATIONVALUE_) \ - (MODIFY_REG(RCC->CR, RCC_CR_HSITRIM, (uint32_t)(_HSICALIBRATIONVALUE_) << RCC_CR_HSITRIM_Pos)) + (MODIFY_REG(RCC->CR, RCC_CR_HSITRIM, (uint32_t)(_HSICALIBRATIONVALUE_) << POSITION_VAL(RCC_CR_HSITRIM))) /** * @} @@ -787,7 +957,7 @@ typedef struct CLEAR_BIT(RCC->CR, RCC_CR_HSEON); \ CLEAR_BIT(RCC->CR, RCC_CR_HSEBYP); \ } \ - }while(0U) + }while(0) /** * @} @@ -835,7 +1005,7 @@ typedef struct CLEAR_BIT(RCC->BDCR, RCC_BDCR_LSEON); \ CLEAR_BIT(RCC->BDCR, RCC_BDCR_LSEBYP); \ } \ - }while(0U) + }while(0) /** * @} @@ -1145,9 +1315,9 @@ typedef struct * @arg @ref RCC_FLAG_LPWRRST Low Power reset. * @retval The new state of __FLAG__ (TRUE or FALSE). */ -#define __HAL_RCC_GET_FLAG(__FLAG__) (((((__FLAG__) >> 5U) == CR_REG_INDEX)? RCC->CR : \ - ((((__FLAG__) >> 5U) == BDCR_REG_INDEX)? RCC->BDCR : \ - RCC->CSR)) & (1U << ((__FLAG__) & RCC_FLAG_MASK))) +#define __HAL_RCC_GET_FLAG(__FLAG__) (((((__FLAG__) >> 5) == CR_REG_INDEX)? RCC->CR : \ + ((((__FLAG__) >> 5) == BDCR_REG_INDEX)? RCC->BDCR : \ + RCC->CSR)) & ((uint32_t)1 << ((__FLAG__) & RCC_FLAG_MASK))) /** * @} @@ -1207,176 +1377,6 @@ void HAL_RCC_CSSCallback(void); * @} */ -/** @addtogroup RCC_Private_Constants - * @{ - */ - -/** @defgroup RCC_Timeout RCC Timeout - * @{ - */ - -/* Disable Backup domain write protection state change timeout */ -#define RCC_DBP_TIMEOUT_VALUE 100U /* 100 ms */ -/* LSE state change timeout */ -#define RCC_LSE_TIMEOUT_VALUE LSE_STARTUP_TIMEOUT -#define CLOCKSWITCH_TIMEOUT_VALUE 5000 /* 5 s */ -#define HSE_TIMEOUT_VALUE HSE_STARTUP_TIMEOUT -#define HSI_TIMEOUT_VALUE 2U /* 2 ms (minimum Tick + 1) */ -#define LSI_TIMEOUT_VALUE 2U /* 2 ms (minimum Tick + 1) */ -#define PLL_TIMEOUT_VALUE 2U /* 2 ms (minimum Tick + 1) */ - -/** - * @} - */ - -/** @defgroup RCC_Register_Offset Register offsets - * @{ - */ -#define RCC_OFFSET (RCC_BASE - PERIPH_BASE) -#define RCC_CR_OFFSET 0x00U -#define RCC_CFGR_OFFSET 0x04U -#define RCC_CIR_OFFSET 0x08U -#define RCC_BDCR_OFFSET 0x20U -#define RCC_CSR_OFFSET 0x24U - -/** - * @} - */ - -/** @defgroup RCC_BitAddress_AliasRegion BitAddress AliasRegion - * @brief RCC registers bit address in the alias region - * @{ - */ -#define RCC_CR_OFFSET_BB (RCC_OFFSET + RCC_CR_OFFSET) -#define RCC_CFGR_OFFSET_BB (RCC_OFFSET + RCC_CFGR_OFFSET) -#define RCC_CIR_OFFSET_BB (RCC_OFFSET + RCC_CIR_OFFSET) -#define RCC_BDCR_OFFSET_BB (RCC_OFFSET + RCC_BDCR_OFFSET) -#define RCC_CSR_OFFSET_BB (RCC_OFFSET + RCC_CSR_OFFSET) - -/* --- CR Register ---*/ -/* Alias word address of HSION bit */ -#define RCC_HSION_BIT_NUMBER RCC_CR_HSION_Pos -#define RCC_CR_HSION_BB ((uint32_t)(PERIPH_BB_BASE + (RCC_CR_OFFSET_BB * 32U) + (RCC_HSION_BIT_NUMBER * 4U))) -/* Alias word address of HSEON bit */ -#define RCC_HSEON_BIT_NUMBER RCC_CR_HSEON_Pos -#define RCC_CR_HSEON_BB ((uint32_t)(PERIPH_BB_BASE + (RCC_CR_OFFSET_BB * 32U) + (RCC_HSEON_BIT_NUMBER * 4U))) -/* Alias word address of CSSON bit */ -#define RCC_CSSON_BIT_NUMBER RCC_CR_CSSON_Pos -#define RCC_CR_CSSON_BB ((uint32_t)(PERIPH_BB_BASE + (RCC_CR_OFFSET_BB * 32U) + (RCC_CSSON_BIT_NUMBER * 4U))) -/* Alias word address of PLLON bit */ -#define RCC_PLLON_BIT_NUMBER RCC_CR_PLLON_Pos -#define RCC_CR_PLLON_BB ((uint32_t)(PERIPH_BB_BASE + (RCC_CR_OFFSET_BB * 32U) + (RCC_PLLON_BIT_NUMBER * 4U))) - -/* --- CSR Register ---*/ -/* Alias word address of LSION bit */ -#define RCC_LSION_BIT_NUMBER RCC_CSR_LSION_Pos -#define RCC_CSR_LSION_BB ((uint32_t)(PERIPH_BB_BASE + (RCC_CSR_OFFSET_BB * 32U) + (RCC_LSION_BIT_NUMBER * 4U))) - -/* Alias word address of RMVF bit */ -#define RCC_RMVF_BIT_NUMBER RCC_CSR_RMVF_Pos -#define RCC_CSR_RMVF_BB ((uint32_t)(PERIPH_BB_BASE + (RCC_CSR_OFFSET_BB * 32U) + (RCC_RMVF_BIT_NUMBER * 4U))) - -/* --- BDCR Registers ---*/ -/* Alias word address of LSEON bit */ -#define RCC_LSEON_BIT_NUMBER RCC_BDCR_LSEON_Pos -#define RCC_BDCR_LSEON_BB ((uint32_t)(PERIPH_BB_BASE + (RCC_BDCR_OFFSET_BB * 32U) + (RCC_LSEON_BIT_NUMBER * 4U))) - -/* Alias word address of LSEON bit */ -#define RCC_LSEBYP_BIT_NUMBER RCC_BDCR_LSEBYP_Pos -#define RCC_BDCR_LSEBYP_BB ((uint32_t)(PERIPH_BB_BASE + (RCC_BDCR_OFFSET_BB * 32U) + (RCC_LSEBYP_BIT_NUMBER * 4U))) - -/* Alias word address of RTCEN bit */ -#define RCC_RTCEN_BIT_NUMBER RCC_BDCR_RTCEN_Pos -#define RCC_BDCR_RTCEN_BB ((uint32_t)(PERIPH_BB_BASE + (RCC_BDCR_OFFSET_BB * 32U) + (RCC_RTCEN_BIT_NUMBER * 4U))) - -/* Alias word address of BDRST bit */ -#define RCC_BDRST_BIT_NUMBER RCC_BDCR_BDRST_Pos -#define RCC_BDCR_BDRST_BB ((uint32_t)(PERIPH_BB_BASE + (RCC_BDCR_OFFSET_BB * 32U) + (RCC_BDRST_BIT_NUMBER * 4U))) - -/** - * @} - */ - -/* CR register byte 2 (Bits[23:16]) base address */ -#define RCC_CR_BYTE2_ADDRESS ((uint32_t)(RCC_BASE + RCC_CR_OFFSET + 0x02U)) - -/* CIR register byte 1 (Bits[15:8]) base address */ -#define RCC_CIR_BYTE1_ADDRESS ((uint32_t)(RCC_BASE + RCC_CIR_OFFSET + 0x01U)) - -/* CIR register byte 2 (Bits[23:16]) base address */ -#define RCC_CIR_BYTE2_ADDRESS ((uint32_t)(RCC_BASE + RCC_CIR_OFFSET + 0x02U)) - -/* Defines used for Flags */ -#define CR_REG_INDEX ((uint8_t)1) -#define BDCR_REG_INDEX ((uint8_t)2) -#define CSR_REG_INDEX ((uint8_t)3) - -#define RCC_FLAG_MASK ((uint8_t)0x1F) - -/** - * @} - */ - -/** @addtogroup RCC_Private_Macros - * @{ - */ -/** @defgroup RCC_Alias_For_Legacy Alias define maintained for legacy - * @{ - */ -#define __HAL_RCC_SYSCFG_CLK_DISABLE __HAL_RCC_AFIO_CLK_DISABLE -#define __HAL_RCC_SYSCFG_CLK_ENABLE __HAL_RCC_AFIO_CLK_ENABLE -#define __HAL_RCC_SYSCFG_FORCE_RESET __HAL_RCC_AFIO_FORCE_RESET -#define __HAL_RCC_SYSCFG_RELEASE_RESET __HAL_RCC_AFIO_RELEASE_RESET -/** - * @} - */ - -#define IS_RCC_PLLSOURCE(__SOURCE__) (((__SOURCE__) == RCC_PLLSOURCE_HSI_DIV2) || \ - ((__SOURCE__) == RCC_PLLSOURCE_HSE)) -#define IS_RCC_OSCILLATORTYPE(__OSCILLATOR__) (((__OSCILLATOR__) == RCC_OSCILLATORTYPE_NONE) || \ - (((__OSCILLATOR__) & RCC_OSCILLATORTYPE_HSE) == RCC_OSCILLATORTYPE_HSE) || \ - (((__OSCILLATOR__) & RCC_OSCILLATORTYPE_HSI) == RCC_OSCILLATORTYPE_HSI) || \ - (((__OSCILLATOR__) & RCC_OSCILLATORTYPE_LSI) == RCC_OSCILLATORTYPE_LSI) || \ - (((__OSCILLATOR__) & RCC_OSCILLATORTYPE_LSE) == RCC_OSCILLATORTYPE_LSE)) -#define IS_RCC_HSE(__HSE__) (((__HSE__) == RCC_HSE_OFF) || ((__HSE__) == RCC_HSE_ON) || \ - ((__HSE__) == RCC_HSE_BYPASS)) -#define IS_RCC_LSE(__LSE__) (((__LSE__) == RCC_LSE_OFF) || ((__LSE__) == RCC_LSE_ON) || \ - ((__LSE__) == RCC_LSE_BYPASS)) -#define IS_RCC_HSI(__HSI__) (((__HSI__) == RCC_HSI_OFF) || ((__HSI__) == RCC_HSI_ON)) -#define IS_RCC_CALIBRATION_VALUE(__VALUE__) ((__VALUE__) <= 0x1FU) -#define IS_RCC_LSI(__LSI__) (((__LSI__) == RCC_LSI_OFF) || ((__LSI__) == RCC_LSI_ON)) -#define IS_RCC_PLL(__PLL__) (((__PLL__) == RCC_PLL_NONE) || ((__PLL__) == RCC_PLL_OFF) || \ - ((__PLL__) == RCC_PLL_ON)) - -#define IS_RCC_CLOCKTYPE(CLK) ((((CLK) & RCC_CLOCKTYPE_SYSCLK) == RCC_CLOCKTYPE_SYSCLK) || \ - (((CLK) & RCC_CLOCKTYPE_HCLK) == RCC_CLOCKTYPE_HCLK) || \ - (((CLK) & RCC_CLOCKTYPE_PCLK1) == RCC_CLOCKTYPE_PCLK1) || \ - (((CLK) & RCC_CLOCKTYPE_PCLK2) == RCC_CLOCKTYPE_PCLK2)) -#define IS_RCC_SYSCLKSOURCE(__SOURCE__) (((__SOURCE__) == RCC_SYSCLKSOURCE_HSI) || \ - ((__SOURCE__) == RCC_SYSCLKSOURCE_HSE) || \ - ((__SOURCE__) == RCC_SYSCLKSOURCE_PLLCLK)) -#define IS_RCC_SYSCLKSOURCE_STATUS(__SOURCE__) (((__SOURCE__) == RCC_SYSCLKSOURCE_STATUS_HSI) || \ - ((__SOURCE__) == RCC_SYSCLKSOURCE_STATUS_HSE) || \ - ((__SOURCE__) == RCC_SYSCLKSOURCE_STATUS_PLLCLK)) -#define IS_RCC_HCLK(__HCLK__) (((__HCLK__) == RCC_SYSCLK_DIV1) || ((__HCLK__) == RCC_SYSCLK_DIV2) || \ - ((__HCLK__) == RCC_SYSCLK_DIV4) || ((__HCLK__) == RCC_SYSCLK_DIV8) || \ - ((__HCLK__) == RCC_SYSCLK_DIV16) || ((__HCLK__) == RCC_SYSCLK_DIV64) || \ - ((__HCLK__) == RCC_SYSCLK_DIV128) || ((__HCLK__) == RCC_SYSCLK_DIV256) || \ - ((__HCLK__) == RCC_SYSCLK_DIV512)) -#define IS_RCC_PCLK(__PCLK__) (((__PCLK__) == RCC_HCLK_DIV1) || ((__PCLK__) == RCC_HCLK_DIV2) || \ - ((__PCLK__) == RCC_HCLK_DIV4) || ((__PCLK__) == RCC_HCLK_DIV8) || \ - ((__PCLK__) == RCC_HCLK_DIV16)) -#define IS_RCC_MCO(__MCO__) ((__MCO__) == RCC_MCO) -#define IS_RCC_MCODIV(__DIV__) (((__DIV__) == RCC_MCODIV_1)) -#define IS_RCC_RTCCLKSOURCE(__SOURCE__) (((__SOURCE__) == RCC_RTCCLKSOURCE_NO_CLK) || \ - ((__SOURCE__) == RCC_RTCCLKSOURCE_LSE) || \ - ((__SOURCE__) == RCC_RTCCLKSOURCE_LSI) || \ - ((__SOURCE__) == RCC_RTCCLKSOURCE_HSE_DIV128)) - -/** - * @} - */ - /** * @} */ diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_rcc_ex.c b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_rcc_ex.c index 65114651c58..d2c21ba1ee2 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_rcc_ex.c +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_rcc_ex.c @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_hal_rcc_ex.c * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief Extended RCC HAL module driver. * This file provides firmware functions to manage the following * functionalities RCC extension peripheral: @@ -56,16 +56,16 @@ /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /** @defgroup RCCEx_Private_Constants RCCEx Private Constants - * @{ - */ + * @{ + */ /** * @} */ /* Private macro -------------------------------------------------------------*/ /** @defgroup RCCEx_Private_Macros RCCEx Private Macros - * @{ - */ + * @{ + */ /** * @} */ @@ -79,8 +79,8 @@ */ /** @defgroup RCCEx_Exported_Functions_Group1 Peripheral Control functions - * @brief Extended Peripheral Control functions - * + * @brief Extended Peripheral Control functions + * @verbatim =============================================================================== ##### Extended Peripheral Control functions ##### @@ -117,9 +117,9 @@ */ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClkInit) { - uint32_t tickstart = 0U, temp_reg = 0U; + uint32_t tickstart = 0, temp_reg = 0; #if defined(STM32F105xC) || defined(STM32F107xC) - uint32_t pllactive = 0U; + uint32_t pllactive = 0; #endif /* STM32F105xC || STM32F107xC */ /* Check the parameters */ @@ -131,32 +131,21 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /* check for RTC Parameters used to output RTCCLK */ assert_param(IS_RCC_RTCCLKSOURCE(PeriphClkInit->RTCClockSelection)); - FlagStatus pwrclkchanged = RESET; - - /* As soon as function is called to change RTC clock source, activation of the - power domain is done. */ - /* Requires to enable write access to Backup Domain of necessary */ - if(__HAL_RCC_PWR_IS_CLK_DISABLED()) - { + /* Enable Power Clock*/ __HAL_RCC_PWR_CLK_ENABLE(); - pwrclkchanged = SET; - } - if(HAL_IS_BIT_CLR(PWR->CR, PWR_CR_DBP)) + /* Enable write access to Backup domain */ + SET_BIT(PWR->CR, PWR_CR_DBP); + + /* Wait for Backup domain Write protection disable */ + tickstart = HAL_GetTick(); + + while((PWR->CR & PWR_CR_DBP) == RESET) { - /* Enable write access to Backup domain */ - SET_BIT(PWR->CR, PWR_CR_DBP); - - /* Wait for Backup domain Write protection disable */ - tickstart = HAL_GetTick(); - - while(HAL_IS_BIT_CLR(PWR->CR, PWR_CR_DBP)) + if((HAL_GetTick() - tickstart) > RCC_DBP_TIMEOUT_VALUE) { - if((HAL_GetTick() - tickstart) > RCC_DBP_TIMEOUT_VALUE) - { - return HAL_TIMEOUT; - } - } + return HAL_TIMEOUT; + } } /* Reset the Backup domain only if the RTC Clock source selection is modified from reset value */ @@ -174,7 +163,7 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk /* Wait for LSERDY if LSE was enabled */ if (HAL_IS_BIT_SET(temp_reg, RCC_BDCR_LSEON)) { - /* Get Start Tick */ + /* Get timeout */ tickstart = HAL_GetTick(); /* Wait till LSE is ready */ @@ -188,12 +177,6 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk } } __HAL_RCC_RTC_CONFIG(PeriphClkInit->RTCClockSelection); - - /* Require to disable power clock if necessary */ - if(pwrclkchanged == SET) - { - __HAL_RCC_PWR_CLK_DISABLE(); - } } /*------------------------------ ADC clock Configuration ------------------*/ @@ -311,7 +294,7 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk */ void HAL_RCCEx_GetPeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClkInit) { - uint32_t srcclk = 0U; + uint32_t srcclk = 0; /* Set all possible values for the extended clock type parameter------------*/ PeriphClkInit->PeriphClockSelection = RCC_PERIPHCLK_RTC; @@ -404,21 +387,26 @@ void HAL_RCCEx_GetPeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClkInit) */ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) { +#if defined(STM32F102x6) || defined(STM32F102xB) || defined(STM32F103x6)\ + || defined(STM32F103xB) || defined(STM32F103xE) || defined(STM32F103xG)\ + || defined(STM32F105xC) || defined(STM32F107xC) #if defined(STM32F105xC) || defined(STM32F107xC) - const uint8_t aPLLMULFactorTable[14] = {0, 0, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 13}; - const uint8_t aPredivFactorTable[16] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; - - uint32_t prediv1 = 0U, pllclk = 0U, pllmul = 0U; - uint32_t pll2mul = 0U, pll3mul = 0U, prediv2 = 0U; + const uint8_t aPLLMULFactorTable[12] = {0, 0, 4, 5, 6, 7, 8, 9, 0, 0, 0, 13}; + const uint8_t aPredivFactorTable[16] = { 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11, 12, 13, 14, 15, 16}; +#else + const uint8_t aPLLMULFactorTable[16] = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 16}; + const uint8_t aPredivFactorTable[2] = { 1, 2}; +#endif +#endif + uint32_t temp_reg = 0, frequency = 0; +#if defined(STM32F102x6) || defined(STM32F102xB) || defined(STM32F103x6)\ + || defined(STM32F103xB) || defined(STM32F103xE) || defined(STM32F103xG)\ + || defined(STM32F105xC) || defined(STM32F107xC) + uint32_t prediv1 = 0, pllclk = 0, pllmul = 0; +#endif /* STM32F102x6 || STM32F102xB || STM32F103x6 || STM32F103xB || STM32F103xE || STM32F103xG || STM32F105xC || STM32F107xC */ +#if defined(STM32F105xC) || defined(STM32F107xC) + uint32_t pll2mul = 0, pll3mul = 0, prediv2 = 0; #endif /* STM32F105xC || STM32F107xC */ -#if defined(STM32F102x6) || defined(STM32F102xB) || defined(STM32F103x6) || \ - defined(STM32F103xB) || defined(STM32F103xE) || defined(STM32F103xG) - const uint8_t aPLLMULFactorTable[16] = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 16}; - const uint8_t aPredivFactorTable[2] = {1, 2}; - - uint32_t prediv1 = 0U, pllclk = 0U, pllmul = 0U; -#endif /* STM32F102x6 || STM32F102xB || STM32F103x6 || STM32F103xB || STM32F103xE || STM32F103xG */ - uint32_t temp_reg = 0U, frequency = 0U; /* Check the parameters */ assert_param(IS_RCC_PERIPHCLOCK(PeriphClk)); @@ -436,14 +424,14 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) /* Check if PLL is enabled */ if (HAL_IS_BIT_SET(RCC->CR,RCC_CR_PLLON)) { - pllmul = aPLLMULFactorTable[(uint32_t)(temp_reg & RCC_CFGR_PLLMULL) >> RCC_CFGR_PLLMULL_Pos]; + pllmul = aPLLMULFactorTable[(uint32_t)(temp_reg & RCC_CFGR_PLLMULL) >> POSITION_VAL(RCC_CFGR_PLLMULL)]; if ((temp_reg & RCC_CFGR_PLLSRC) != RCC_PLLSOURCE_HSI_DIV2) { #if defined(STM32F105xC) || defined(STM32F107xC) || defined(STM32F100xB)\ || defined(STM32F100xE) - prediv1 = aPredivFactorTable[(uint32_t)(RCC->CFGR2 & RCC_CFGR2_PREDIV1) >> RCC_CFGR2_PREDIV1_Pos]; + prediv1 = aPredivFactorTable[(uint32_t)(RCC->CFGR2 & RCC_CFGR2_PREDIV1) >> POSITION_VAL(RCC_CFGR2_PREDIV1)]; #else - prediv1 = aPredivFactorTable[(uint32_t)(RCC->CFGR & RCC_CFGR_PLLXTPRE) >> RCC_CFGR_PLLXTPRE_Pos]; + prediv1 = aPredivFactorTable[(uint32_t)(RCC->CFGR & RCC_CFGR_PLLXTPRE) >> POSITION_VAL(RCC_CFGR_PLLXTPRE)]; #endif /* STM32F105xC || STM32F107xC || STM32F100xB || STM32F100xE */ #if defined(STM32F105xC) || defined(STM32F107xC) @@ -451,8 +439,8 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) { /* PLL2 selected as Prediv1 source */ /* PLLCLK = PLL2CLK / PREDIV1 * PLLMUL with PLL2CLK = HSE/PREDIV2 * PLL2MUL */ - prediv2 = ((RCC->CFGR2 & RCC_CFGR2_PREDIV2) >> RCC_CFGR2_PREDIV2_Pos) + 1; - pll2mul = ((RCC->CFGR2 & RCC_CFGR2_PLL2MUL) >> RCC_CFGR2_PLL2MUL_Pos) + 2; + prediv2 = ((RCC->CFGR2 & RCC_CFGR2_PREDIV2) >> POSITION_VAL(RCC_CFGR2_PREDIV2)) + 1; + pll2mul = ((RCC->CFGR2 & RCC_CFGR2_PLL2MUL) >> POSITION_VAL(RCC_CFGR2_PLL2MUL)) + 2; pllclk = (uint32_t)((((HSE_VALUE / prediv2) * pll2mul) / prediv1) * pllmul); } else @@ -463,7 +451,7 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) /* If PLLMUL was set to 13 means that it was to cover the case PLLMUL 6.5 (avoid using float) */ /* In this case need to divide pllclk by 2 */ - if (pllmul == aPLLMULFactorTable[(uint32_t)(RCC_CFGR_PLLMULL6_5) >> RCC_CFGR_PLLMULL_Pos]) + if (pllmul == aPLLMULFactorTable[(uint32_t)(RCC_CFGR_PLLMULL6_5) >> POSITION_VAL(RCC_CFGR_PLLMULL)]) { pllclk = pllclk / 2; } @@ -511,7 +499,8 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) break; } #endif /* STM32F102x6 || STM32F102xB || STM32F103x6 || STM32F103xB || STM32F103xE || STM32F103xG || STM32F105xC || STM32F107xC */ -#if defined(STM32F103xE) || defined(STM32F103xG) || defined(STM32F105xC) || defined(STM32F107xC) +#if defined(STM32F103xE) || defined(STM32F103xG) || defined(STM32F105xC)\ + || defined(STM32F107xC) case RCC_PERIPHCLK_I2S2: { #if defined(STM32F103xE) || defined(STM32F103xG) @@ -529,8 +518,8 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) if (HAL_IS_BIT_SET(RCC->CR, RCC_CR_PLL3ON)) { /* PLLI2SVCO = 2 * PLLI2SCLK = 2 * (HSE/PREDIV2 * PLL3MUL) */ - prediv2 = ((RCC->CFGR2 & RCC_CFGR2_PREDIV2) >> RCC_CFGR2_PREDIV2_Pos) + 1; - pll3mul = ((RCC->CFGR2 & RCC_CFGR2_PLL3MUL) >> RCC_CFGR2_PLL3MUL_Pos) + 2; + prediv2 = ((RCC->CFGR2 & RCC_CFGR2_PREDIV2) >> POSITION_VAL(RCC_CFGR2_PREDIV2)) + 1; + pll3mul = ((RCC->CFGR2 & RCC_CFGR2_PLL3MUL) >> POSITION_VAL(RCC_CFGR2_PLL3MUL)) + 2; frequency = (uint32_t)(2 * ((HSE_VALUE / prediv2) * pll3mul)); } } @@ -554,8 +543,8 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) if (HAL_IS_BIT_SET(RCC->CR, RCC_CR_PLL3ON)) { /* PLLI2SVCO = 2 * PLLI2SCLK = 2 * (HSE/PREDIV2 * PLL3MUL) */ - prediv2 = ((RCC->CFGR2 & RCC_CFGR2_PREDIV2) >> RCC_CFGR2_PREDIV2_Pos) + 1; - pll3mul = ((RCC->CFGR2 & RCC_CFGR2_PLL3MUL) >> RCC_CFGR2_PLL3MUL_Pos) + 2; + prediv2 = ((RCC->CFGR2 & RCC_CFGR2_PREDIV2) >> POSITION_VAL(RCC_CFGR2_PREDIV2)) + 1; + pll3mul = ((RCC->CFGR2 & RCC_CFGR2_PLL3MUL) >> POSITION_VAL(RCC_CFGR2_PLL3MUL)) + 2; frequency = (uint32_t)(2 * ((HSE_VALUE / prediv2) * pll3mul)); } } @@ -580,18 +569,18 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) } else if (((temp_reg & RCC_BDCR_RTCSEL) == RCC_RTCCLKSOURCE_HSE_DIV128) && (HAL_IS_BIT_SET(RCC->CR, RCC_CR_HSERDY))) { - frequency = HSE_VALUE / 128U; + frequency = HSE_VALUE / 128; } /* Clock not enabled for RTC*/ else { - frequency = 0U; + frequency = 0; } break; } case RCC_PERIPHCLK_ADC: { - frequency = HAL_RCC_GetPCLK2Freq() / (((__HAL_RCC_GET_ADC_SOURCE() >> RCC_CFGR_ADCPRE_Pos) + 1) * 2); + frequency = HAL_RCC_GetPCLK2Freq() / (((__HAL_RCC_GET_ADC_SOURCE() >> POSITION_VAL(RCC_CFGR_ADCPRE_DIV4)) + 1) * 2); break; } default: @@ -608,8 +597,8 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) #if defined(STM32F105xC) || defined(STM32F107xC) /** @defgroup RCCEx_Exported_Functions_Group2 PLLI2S Management function - * @brief PLLI2S Management functions - * + * @brief PLLI2S Management functions + * @verbatim =============================================================================== ##### Extended PLLI2S Management functions ##### @@ -630,7 +619,7 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) */ HAL_StatusTypeDef HAL_RCCEx_EnablePLLI2S(RCC_PLLI2SInitTypeDef *PLLI2SInit) { - uint32_t tickstart = 0U; + uint32_t tickstart = 0; /* Check that PLL I2S has not been already enabled by I2S2 or I2S3*/ if (HAL_IS_BIT_CLR(RCC->CFGR2, RCC_CFGR2_I2S2SRC) && HAL_IS_BIT_CLR(RCC->CFGR2, RCC_CFGR2_I2S3SRC)) @@ -700,7 +689,7 @@ HAL_StatusTypeDef HAL_RCCEx_EnablePLLI2S(RCC_PLLI2SInitTypeDef *PLLI2SInit) */ HAL_StatusTypeDef HAL_RCCEx_DisablePLLI2S(void) { - uint32_t tickstart = 0U; + uint32_t tickstart = 0; /* Disable PLL I2S as not requested by I2S2 or I2S3*/ if (HAL_IS_BIT_CLR(RCC->CFGR2, RCC_CFGR2_I2S2SRC) && HAL_IS_BIT_CLR(RCC->CFGR2, RCC_CFGR2_I2S3SRC)) @@ -734,8 +723,8 @@ HAL_StatusTypeDef HAL_RCCEx_DisablePLLI2S(void) */ /** @defgroup RCCEx_Exported_Functions_Group3 PLL2 Management function - * @brief PLL2 Management functions - * + * @brief PLL2 Management functions + * @verbatim =============================================================================== ##### Extended PLL2 Management functions ##### @@ -756,7 +745,7 @@ HAL_StatusTypeDef HAL_RCCEx_DisablePLLI2S(void) */ HAL_StatusTypeDef HAL_RCCEx_EnablePLL2(RCC_PLL2InitTypeDef *PLL2Init) { - uint32_t tickstart = 0U; + uint32_t tickstart = 0; /* This bit can not be cleared if the PLL2 clock is used indirectly as system clock (i.e. it is used as PLL clock entry that is used as system clock). */ @@ -827,7 +816,7 @@ HAL_StatusTypeDef HAL_RCCEx_EnablePLL2(RCC_PLL2InitTypeDef *PLL2Init) */ HAL_StatusTypeDef HAL_RCCEx_DisablePLL2(void) { - uint32_t tickstart = 0U; + uint32_t tickstart = 0; /* This bit can not be cleared if the PLL2 clock is used indirectly as system clock (i.e. it is used as PLL clock entry that is used as system clock). */ diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_rcc_ex.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_rcc_ex.h index 098ecd762e4..fbd5772b699 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_rcc_ex.h +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_rcc_ex.h @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_hal_rcc_ex.h * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief Header file of RCC HAL Extension module. ****************************************************************************** * @attention @@ -61,14 +61,14 @@ #if defined(STM32F105xC) || defined(STM32F107xC) /* Alias word address of PLLI2SON bit */ -#define PLLI2SON_BITNUMBER RCC_CR_PLL3ON_Pos -#define RCC_CR_PLLI2SON_BB ((uint32_t)(PERIPH_BB_BASE + (RCC_CR_OFFSET_BB * 32U) + (PLLI2SON_BITNUMBER * 4U))) +#define PLLI2SON_BITNUMBER POSITION_VAL(RCC_CR_PLL3ON) +#define RCC_CR_PLLI2SON_BB ((uint32_t)(PERIPH_BB_BASE + (RCC_CR_OFFSET_BB * 32) + (PLLI2SON_BITNUMBER * 4))) /* Alias word address of PLL2ON bit */ -#define PLL2ON_BITNUMBER RCC_CR_PLL2ON_Pos -#define RCC_CR_PLL2ON_BB ((uint32_t)(PERIPH_BB_BASE + (RCC_CR_OFFSET_BB * 32U) + (PLL2ON_BITNUMBER * 4U))) +#define PLL2ON_BITNUMBER POSITION_VAL(RCC_CR_PLL2ON) +#define RCC_CR_PLL2ON_BB ((uint32_t)(PERIPH_BB_BASE + (RCC_CR_OFFSET_BB * 32) + (PLL2ON_BITNUMBER * 4))) -#define PLLI2S_TIMEOUT_VALUE 100U /* 100 ms */ -#define PLL2_TIMEOUT_VALUE 100U /* 100 ms */ +#define PLLI2S_TIMEOUT_VALUE ((uint32_t)100) /* 100 ms */ +#define PLL2_TIMEOUT_VALUE ((uint32_t)100) /* 100 ms */ #endif /* STM32F105xC || STM32F107xC */ @@ -346,17 +346,17 @@ typedef struct /** @defgroup RCCEx_Periph_Clock_Selection Periph Clock Selection * @{ */ -#define RCC_PERIPHCLK_RTC 0x00000001U -#define RCC_PERIPHCLK_ADC 0x00000002U +#define RCC_PERIPHCLK_RTC ((uint32_t)0x00000001) +#define RCC_PERIPHCLK_ADC ((uint32_t)0x00000002) #if defined(STM32F103xE) || defined(STM32F103xG) || defined(STM32F105xC)\ || defined(STM32F107xC) -#define RCC_PERIPHCLK_I2S2 0x00000004U -#define RCC_PERIPHCLK_I2S3 0x00000008U +#define RCC_PERIPHCLK_I2S2 ((uint32_t)0x00000004) +#define RCC_PERIPHCLK_I2S3 ((uint32_t)0x00000008) #endif /* STM32F103xE || STM32F103xG || STM32F105xC || STM32F107xC */ #if defined(STM32F102x6) || defined(STM32F102xB) || defined(STM32F103x6)\ || defined(STM32F103xB) || defined(STM32F103xE) || defined(STM32F103xG)\ || defined(STM32F105xC) || defined(STM32F107xC) -#define RCC_PERIPHCLK_USB 0x00000010U +#define RCC_PERIPHCLK_USB ((uint32_t)0x00000010) #endif /* STM32F102x6 || STM32F102xB || STM32F103x6 || STM32F103xB || STM32F103xE || STM32F103xG || STM32F105xC || STM32F107xC */ /** @@ -380,9 +380,9 @@ typedef struct /** @defgroup RCCEx_I2S2_Clock_Source I2S2 Clock Source * @{ */ -#define RCC_I2S2CLKSOURCE_SYSCLK 0x00000000U +#define RCC_I2S2CLKSOURCE_SYSCLK ((uint32_t)0x00000000) #if defined(STM32F105xC) || defined(STM32F107xC) -#define RCC_I2S2CLKSOURCE_PLLI2S_VCO RCC_CFGR2_I2S2SRC +#define RCC_I2S2CLKSOURCE_PLLI2S_VCO RCC_CFGR2_I2S2SRC #endif /* STM32F105xC || STM32F107xC */ /** @@ -392,9 +392,9 @@ typedef struct /** @defgroup RCCEx_I2S3_Clock_Source I2S3 Clock Source * @{ */ -#define RCC_I2S3CLKSOURCE_SYSCLK 0x00000000U +#define RCC_I2S3CLKSOURCE_SYSCLK ((uint32_t)0x00000000) #if defined(STM32F105xC) || defined(STM32F107xC) -#define RCC_I2S3CLKSOURCE_PLLI2S_VCO RCC_CFGR2_I2S3SRC +#define RCC_I2S3CLKSOURCE_PLLI2S_VCO RCC_CFGR2_I2S3SRC #endif /* STM32F105xC || STM32F107xC */ /** @@ -410,7 +410,7 @@ typedef struct * @{ */ #define RCC_USBCLKSOURCE_PLL RCC_CFGR_USBPRE -#define RCC_USBCLKSOURCE_PLL_DIV1_5 0x00000000U +#define RCC_USBCLKSOURCE_PLL_DIV1_5 ((uint32_t)0x00000000) /** * @} @@ -424,7 +424,7 @@ typedef struct * @{ */ #define RCC_USBCLKSOURCE_PLL_DIV2 RCC_CFGR_OTGFSPRE -#define RCC_USBCLKSOURCE_PLL_DIV3 0x00000000U +#define RCC_USBCLKSOURCE_PLL_DIV3 ((uint32_t)0x00000000) /** * @} @@ -466,7 +466,7 @@ typedef struct * @{ */ -#define RCC_HSE_PREDIV_DIV1 0x00000000U +#define RCC_HSE_PREDIV_DIV1 ((uint32_t)0x00000000) #if defined(STM32F105xC) || defined(STM32F107xC) || defined(STM32F100xB)\ || defined(STM32F100xE) @@ -522,9 +522,9 @@ typedef struct /** @defgroup RCCEx_PLL2_Config PLL Config * @{ */ -#define RCC_PLL2_NONE 0x00000000U -#define RCC_PLL2_OFF 0x00000001U -#define RCC_PLL2_ON 0x00000002U +#define RCC_PLL2_NONE ((uint32_t)0x00000000) +#define RCC_PLL2_OFF ((uint32_t)0x00000001) +#define RCC_PLL2_ON ((uint32_t)0x00000002) /** * @} @@ -617,8 +617,8 @@ typedef struct * @{ */ /* Flags in the CR register */ -#define RCC_FLAG_PLL2RDY ((uint8_t)((CR_REG_INDEX << 5U) | RCC_CR_PLL2RDY_Pos)) -#define RCC_FLAG_PLLI2SRDY ((uint8_t)((CR_REG_INDEX << 5U) | RCC_CR_PLL3RDY_Pos)) +#define RCC_FLAG_PLL2RDY ((uint8_t)((CR_REG_INDEX << 5) | POSITION_VAL(RCC_CR_PLL2RDY))) +#define RCC_FLAG_PLLI2SRDY ((uint8_t)((CR_REG_INDEX << 5) | POSITION_VAL(RCC_CR_PLL3RDY))) /** * @} */ @@ -650,7 +650,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHBENR, RCC_AHBENR_DMA2EN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_DMA2_CLK_DISABLE() (RCC->AHBENR &= ~(RCC_AHBENR_DMA2EN)) #endif /* STM32F101xE || STM32F103xE || STM32F101xG || STM32F103xG || STM32F105xC || STM32F107xC || STM32F100xE */ @@ -663,7 +663,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHBENR, RCC_AHBENR_FSMCEN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_FSMC_CLK_DISABLE() (RCC->AHBENR &= ~(RCC_AHBENR_FSMCEN)) #endif /* STM32F101xE || STM32F103xE || STM32F101xG || STM32F103xG || STM32F100xE */ @@ -675,7 +675,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHBENR, RCC_AHBENR_SDIOEN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_SDIO_CLK_DISABLE() (RCC->AHBENR &= ~(RCC_AHBENR_SDIOEN)) @@ -688,7 +688,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHBENR, RCC_AHBENR_OTGFSEN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_USB_OTG_FS_CLK_DISABLE() (RCC->AHBENR &= ~(RCC_AHBENR_OTGFSEN)) @@ -701,7 +701,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHBENR, RCC_AHBENR_ETHMACEN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_ETHMACTX_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ @@ -709,7 +709,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHBENR, RCC_AHBENR_ETHMACTXEN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_ETHMACRX_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ @@ -717,7 +717,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->AHBENR, RCC_AHBENR_ETHMACRXEN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_ETHMAC_CLK_DISABLE() (RCC->AHBENR &= ~(RCC_AHBENR_ETHMACEN)) #define __HAL_RCC_ETHMACTX_CLK_DISABLE() (RCC->AHBENR &= ~(RCC_AHBENR_ETHMACTXEN)) @@ -730,7 +730,7 @@ typedef struct __HAL_RCC_ETHMAC_CLK_ENABLE(); \ __HAL_RCC_ETHMACTX_CLK_ENABLE(); \ __HAL_RCC_ETHMACRX_CLK_ENABLE(); \ - } while(0U) + } while(0) /** * @brief Disable ETHERNET clock. */ @@ -738,7 +738,7 @@ typedef struct __HAL_RCC_ETHMACTX_CLK_DISABLE(); \ __HAL_RCC_ETHMACRX_CLK_DISABLE(); \ __HAL_RCC_ETHMAC_CLK_DISABLE(); \ - } while(0U) + } while(0) #endif /* STM32F107xC*/ @@ -802,7 +802,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN1EN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_CAN1_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_CAN1EN)) #endif /* STM32F103x6 || STM32F103xB || STM32F103xE || STM32F103xG || STM32F105xC || STM32F107xC */ @@ -817,7 +817,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM4EN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_SPI2_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ @@ -825,7 +825,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_SPI2EN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_USART3_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ @@ -833,7 +833,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_USART3EN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_I2C2_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ @@ -841,7 +841,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_I2C2EN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_TIM4_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM4EN)) #define __HAL_RCC_SPI2_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_SPI2EN)) @@ -857,7 +857,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_USBEN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_USB_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_USBEN)) #endif /* STM32F102x6 || STM32F102xB || STM32F103x6 || STM32F103xB || STM32F103xE || STM32F103xG */ @@ -870,7 +870,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM5EN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_TIM6_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ @@ -878,7 +878,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM6EN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_TIM7_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ @@ -886,7 +886,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM7EN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_SPI3_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ @@ -894,7 +894,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_SPI3EN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_UART4_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ @@ -902,7 +902,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_UART4EN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_UART5_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ @@ -910,7 +910,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_UART5EN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_DAC_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ @@ -918,7 +918,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_DACEN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_TIM5_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM5EN)) #define __HAL_RCC_TIM6_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM6EN)) @@ -936,7 +936,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM6EN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_TIM7_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ @@ -944,7 +944,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM7EN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_DAC_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ @@ -952,7 +952,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_DACEN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_CEC_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ @@ -960,7 +960,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_CECEN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_TIM6_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM6EN)) #define __HAL_RCC_TIM7_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM7EN)) @@ -975,7 +975,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM5EN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_TIM12_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ @@ -983,7 +983,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM12EN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_TIM13_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ @@ -991,7 +991,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM13EN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_TIM14_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ @@ -999,7 +999,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM14EN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_SPI3_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ @@ -1007,7 +1007,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_SPI3EN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_UART4_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ @@ -1015,7 +1015,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_UART4EN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_UART5_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ @@ -1023,7 +1023,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_UART5EN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_TIM5_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM5EN)) #define __HAL_RCC_TIM12_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM12EN)) @@ -1041,7 +1041,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_CAN2EN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_CAN2_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_CAN2EN)) #endif /* STM32F105xC || STM32F107xC */ @@ -1053,7 +1053,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM12EN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_TIM13_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ @@ -1061,7 +1061,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM13EN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_TIM14_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ @@ -1069,7 +1069,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_TIM14EN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_TIM12_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM12EN)) #define __HAL_RCC_TIM13_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM13EN)) @@ -1188,7 +1188,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC2EN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_ADC2_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_ADC2EN)) #endif /* STM32F101xG || STM32F103x6 || STM32F103xB || STM32F105xC || STM32F107xC || STM32F103xE || STM32F103xG */ @@ -1200,7 +1200,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM15EN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_TIM16_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ @@ -1208,7 +1208,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM16EN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_TIM17_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ @@ -1216,7 +1216,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM17EN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_TIM15_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_TIM15EN)) #define __HAL_RCC_TIM16_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_TIM16EN)) @@ -1233,7 +1233,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_IOPEEN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_GPIOE_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_IOPEEN)) #endif /* STM32F101x6 || STM32F101xB || STM32F101xE || (...) || STM32F105xC || STM32F107xC */ @@ -1246,7 +1246,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_IOPFEN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_GPIOG_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ @@ -1254,7 +1254,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_IOPGEN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_GPIOF_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_IOPFEN)) #define __HAL_RCC_GPIOG_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_IOPGEN)) @@ -1267,7 +1267,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM8EN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_ADC3_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ @@ -1275,7 +1275,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_ADC3EN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_TIM8_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_TIM8EN)) #define __HAL_RCC_ADC3_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_ADC3EN)) @@ -1288,7 +1288,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_IOPFEN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_GPIOG_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ @@ -1296,7 +1296,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_IOPGEN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_GPIOF_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_IOPFEN)) #define __HAL_RCC_GPIOG_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_IOPGEN)) @@ -1309,7 +1309,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM9EN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_TIM10_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ @@ -1317,7 +1317,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM10EN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_TIM11_CLK_ENABLE() do { \ __IO uint32_t tmpreg; \ @@ -1325,7 +1325,7 @@ typedef struct /* Delay after an RCC peripheral clock enabling */ \ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_TIM11EN);\ UNUSED(tmpreg); \ - } while(0U) + } while(0) #define __HAL_RCC_TIM9_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_TIM9EN)) #define __HAL_RCC_TIM10_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_TIM10EN)) diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_rtc.c b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_rtc.c index 2f609f4d855..331d428e995 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_rtc.c +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_rtc.c @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_hal_rtc.c * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief RTC HAL module driver. * This file provides firmware functions to manage the following * functionalities of the Real Time Clock (RTC) peripheral: @@ -171,7 +171,7 @@ * @{ */ #define RTC_ALARM_RESETVALUE_REGISTER (uint16_t)0xFFFF -#define RTC_ALARM_RESETVALUE 0xFFFFFFFFU +#define RTC_ALARM_RESETVALUE (uint32_t)0xFFFFFFFF /** * @} @@ -243,7 +243,7 @@ static uint8_t RTC_WeekDayNum(uint32_t nYear, uint8_t nMonth, uint8_t */ HAL_StatusTypeDef HAL_RTC_Init(RTC_HandleTypeDef *hrtc) { - uint32_t prescaler = 0U; + uint32_t prescaler = 0; /* Check input parameters */ if(hrtc == NULL) { @@ -310,7 +310,7 @@ HAL_StatusTypeDef HAL_RTC_Init(RTC_HandleTypeDef *hrtc) prescaler = HAL_RCCEx_GetPeriphCLKFreq(RCC_PERIPHCLK_RTC); /* Check that RTC clock is enabled*/ - if (prescaler == 0U) + if (prescaler == 0) { /* Should not happen. Frequency is not available*/ hrtc->State = HAL_RTC_STATE_ERROR; @@ -319,12 +319,12 @@ HAL_StatusTypeDef HAL_RTC_Init(RTC_HandleTypeDef *hrtc) else { /* RTC period = RTCCLK/(RTC_PR + 1) */ - prescaler = prescaler - 1U; + prescaler = prescaler - 1; } } /* Configure the RTC_PRLH / RTC_PRLL */ - MODIFY_REG(hrtc->Instance->PRLH, RTC_PRLH_PRL, (prescaler >> 16U)); + MODIFY_REG(hrtc->Instance->PRLH, RTC_PRLH_PRL, (prescaler >> 16)); MODIFY_REG(hrtc->Instance->PRLL, RTC_PRLL_PRL, (prescaler & RTC_PRLL_PRL)); /* Wait for synchro */ @@ -336,9 +336,9 @@ HAL_StatusTypeDef HAL_RTC_Init(RTC_HandleTypeDef *hrtc) } /* Initialize date to 1st of January 2000 */ - hrtc->DateToUpdate.Year = 0x00U; + hrtc->DateToUpdate.Year = 0x00; hrtc->DateToUpdate.Month = RTC_MONTH_JANUARY; - hrtc->DateToUpdate.Date = 0x01U; + hrtc->DateToUpdate.Date = 0x01; /* Set RTC state */ hrtc->State = HAL_RTC_STATE_READY; @@ -383,7 +383,7 @@ HAL_StatusTypeDef HAL_RTC_DeInit(RTC_HandleTypeDef *hrtc) { CLEAR_REG(hrtc->Instance->CNTL); CLEAR_REG(hrtc->Instance->CNTH); - WRITE_REG(hrtc->Instance->PRLL, 0x00008000U); + WRITE_REG(hrtc->Instance->PRLL, 0x00008000); CLEAR_REG(hrtc->Instance->PRLH); /* Reset All CRH/CRL bits */ @@ -479,7 +479,7 @@ __weak void HAL_RTC_MspDeInit(RTC_HandleTypeDef* hrtc) */ HAL_StatusTypeDef HAL_RTC_SetTime(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTime, uint32_t Format) { - uint32_t counter_time = 0U, counter_alarm = 0U; + uint32_t counter_time = 0, counter_alarm = 0; /* Check input parameters */ if((hrtc == NULL) || (sTime == NULL)) @@ -501,8 +501,8 @@ HAL_StatusTypeDef HAL_RTC_SetTime(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTim assert_param(IS_RTC_MINUTES(sTime->Minutes)); assert_param(IS_RTC_SECONDS(sTime->Seconds)); - counter_time = (uint32_t)(((uint32_t)sTime->Hours * 3600U) + \ - ((uint32_t)sTime->Minutes * 60U) + \ + counter_time = (uint32_t)(((uint32_t)sTime->Hours * 3600) + \ + ((uint32_t)sTime->Minutes * 60) + \ ((uint32_t)sTime->Seconds)); } else @@ -511,8 +511,8 @@ HAL_StatusTypeDef HAL_RTC_SetTime(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTim assert_param(IS_RTC_MINUTES(RTC_Bcd2ToByte(sTime->Minutes))); assert_param(IS_RTC_SECONDS(RTC_Bcd2ToByte(sTime->Seconds))); - counter_time = (((uint32_t)(RTC_Bcd2ToByte(sTime->Hours)) * 3600U) + \ - ((uint32_t)(RTC_Bcd2ToByte(sTime->Minutes)) * 60U) + \ + counter_time = (((uint32_t)(RTC_Bcd2ToByte(sTime->Hours)) * 3600) + \ + ((uint32_t)(RTC_Bcd2ToByte(sTime->Minutes)) * 60) + \ ((uint32_t)(RTC_Bcd2ToByte(sTime->Seconds)))); } @@ -541,7 +541,7 @@ HAL_StatusTypeDef HAL_RTC_SetTime(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTim if(counter_alarm < counter_time) { /* Add 1 day to alarm counter*/ - counter_alarm += (uint32_t)(24U * 3600U); + counter_alarm += (uint32_t)(24 * 3600); /* Write new Alarm counter in RTC registers */ if (RTC_WriteAlarmCounter(hrtc, counter_alarm) != HAL_OK) @@ -578,7 +578,7 @@ HAL_StatusTypeDef HAL_RTC_SetTime(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTim */ HAL_StatusTypeDef HAL_RTC_GetTime(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTime, uint32_t Format) { - uint32_t counter_time = 0U, counter_alarm = 0U, days_elapsed = 0U, hours = 0U; + uint32_t counter_time = 0, counter_alarm = 0, days_elapsed = 0, hours = 0; /* Check input parameters */ if((hrtc == NULL) || (sTime == NULL)) @@ -599,17 +599,17 @@ HAL_StatusTypeDef HAL_RTC_GetTime(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTim counter_time = RTC_ReadTimeCounter(hrtc); /* Fill the structure fields with the read parameters */ - hours = counter_time / 3600U; - sTime->Minutes = (uint8_t)((counter_time % 3600U) / 60U); - sTime->Seconds = (uint8_t)((counter_time % 3600U) % 60U); + hours = counter_time / 3600; + sTime->Minutes = (uint8_t)((counter_time % 3600) / 60); + sTime->Seconds = (uint8_t)((counter_time % 3600) % 60); - if (hours >= 24U) + if (hours >= 24) { /* Get number of days elapsed from last calculation */ - days_elapsed = (hours / 24U); + days_elapsed = (hours / 24); /* Set Hours in RTC_TimeTypeDef structure*/ - sTime->Hours = (hours % 24U); + sTime->Hours = (hours % 24); /* Read Alarm counter in RTC registers */ counter_alarm = RTC_ReadAlarmCounter(hrtc); @@ -627,7 +627,7 @@ HAL_StatusTypeDef HAL_RTC_GetTime(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTim } /* Set updated time in decreasing counter by number of days elapsed */ - counter_time -= (days_elapsed * 24U * 3600U); + counter_time -= (days_elapsed * 24 * 3600); /* Write time counter in RTC registers */ if (RTC_WriteTimeCounter(hrtc, counter_time) != HAL_OK) @@ -689,7 +689,7 @@ HAL_StatusTypeDef HAL_RTC_GetTime(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTim */ HAL_StatusTypeDef HAL_RTC_SetDate(RTC_HandleTypeDef *hrtc, RTC_DateTypeDef *sDate, uint32_t Format) { - uint32_t counter_time = 0U, counter_alarm = 0U, hours = 0U; + uint32_t counter_time = 0, counter_alarm = 0, hours = 0; /* Check input parameters */ if((hrtc == NULL) || (sDate == NULL)) @@ -737,11 +737,11 @@ HAL_StatusTypeDef HAL_RTC_SetDate(RTC_HandleTypeDef *hrtc, RTC_DateTypeDef *sDat counter_time = RTC_ReadTimeCounter(hrtc); /* Fill the structure fields with the read parameters */ - hours = counter_time / 3600U; - if (hours > 24U) + hours = counter_time / 3600; + if (hours > 24) { /* Set updated time in decreasing counter by number of days elapsed */ - counter_time -= ((hours / 24U) * 24U * 3600U); + counter_time -= ((hours / 24) * 24 * 3600); /* Write time counter in RTC registers */ if (RTC_WriteTimeCounter(hrtc, counter_time) != HAL_OK) { @@ -763,7 +763,7 @@ HAL_StatusTypeDef HAL_RTC_SetDate(RTC_HandleTypeDef *hrtc, RTC_DateTypeDef *sDat if(counter_alarm < counter_time) { /* Add 1 day to alarm counter*/ - counter_alarm += (uint32_t)(24U * 3600U); + counter_alarm += (uint32_t)(24 * 3600); /* Write new Alarm counter in RTC registers */ if (RTC_WriteAlarmCounter(hrtc, counter_alarm) != HAL_OK) @@ -803,7 +803,7 @@ HAL_StatusTypeDef HAL_RTC_SetDate(RTC_HandleTypeDef *hrtc, RTC_DateTypeDef *sDat */ HAL_StatusTypeDef HAL_RTC_GetDate(RTC_HandleTypeDef *hrtc, RTC_DateTypeDef *sDate, uint32_t Format) { - RTC_TimeTypeDef stime = {0U}; + RTC_TimeTypeDef stime = {0}; /* Check input parameters */ if((hrtc == NULL) || (sDate == NULL)) @@ -868,8 +868,8 @@ HAL_StatusTypeDef HAL_RTC_GetDate(RTC_HandleTypeDef *hrtc, RTC_DateTypeDef *sDat */ HAL_StatusTypeDef HAL_RTC_SetAlarm(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sAlarm, uint32_t Format) { - uint32_t counter_alarm = 0U, counter_time; - RTC_TimeTypeDef stime = {0U}; + uint32_t counter_alarm = 0, counter_time; + RTC_TimeTypeDef stime = {0}; /* Check input parameters */ if((hrtc == NULL) || (sAlarm == NULL)) @@ -893,8 +893,8 @@ HAL_StatusTypeDef HAL_RTC_SetAlarm(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sA } /* Convert time in seconds */ - counter_time = (uint32_t)(((uint32_t)stime.Hours * 3600U) + \ - ((uint32_t)stime.Minutes * 60U) + \ + counter_time = (uint32_t)(((uint32_t)stime.Hours * 3600) + \ + ((uint32_t)stime.Minutes * 60) + \ ((uint32_t)stime.Seconds)); if(Format == RTC_FORMAT_BIN) @@ -903,8 +903,8 @@ HAL_StatusTypeDef HAL_RTC_SetAlarm(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sA assert_param(IS_RTC_MINUTES(sAlarm->AlarmTime.Minutes)); assert_param(IS_RTC_SECONDS(sAlarm->AlarmTime.Seconds)); - counter_alarm = (uint32_t)(((uint32_t)sAlarm->AlarmTime.Hours * 3600U) + \ - ((uint32_t)sAlarm->AlarmTime.Minutes * 60U) + \ + counter_alarm = (uint32_t)(((uint32_t)sAlarm->AlarmTime.Hours * 3600) + \ + ((uint32_t)sAlarm->AlarmTime.Minutes * 60) + \ ((uint32_t)sAlarm->AlarmTime.Seconds)); } else @@ -913,8 +913,8 @@ HAL_StatusTypeDef HAL_RTC_SetAlarm(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sA assert_param(IS_RTC_MINUTES(RTC_Bcd2ToByte(sAlarm->AlarmTime.Minutes))); assert_param(IS_RTC_SECONDS(RTC_Bcd2ToByte(sAlarm->AlarmTime.Seconds))); - counter_alarm = (((uint32_t)(RTC_Bcd2ToByte(sAlarm->AlarmTime.Hours)) * 3600U) + \ - ((uint32_t)(RTC_Bcd2ToByte(sAlarm->AlarmTime.Minutes)) * 60U) + \ + counter_alarm = (((uint32_t)(RTC_Bcd2ToByte(sAlarm->AlarmTime.Hours)) * 3600) + \ + ((uint32_t)(RTC_Bcd2ToByte(sAlarm->AlarmTime.Minutes)) * 60) + \ ((uint32_t)RTC_Bcd2ToByte(sAlarm->AlarmTime.Seconds))); } @@ -922,7 +922,7 @@ HAL_StatusTypeDef HAL_RTC_SetAlarm(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sA if (counter_alarm < counter_time) { /* Add 1 day to alarm counter*/ - counter_alarm += (uint32_t)(24U * 3600U); + counter_alarm += (uint32_t)(24 * 3600); } /* Write Alarm counter in RTC registers */ @@ -960,8 +960,8 @@ HAL_StatusTypeDef HAL_RTC_SetAlarm(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sA */ HAL_StatusTypeDef HAL_RTC_SetAlarm_IT(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sAlarm, uint32_t Format) { - uint32_t counter_alarm = 0U, counter_time; - RTC_TimeTypeDef stime = {0U}; + uint32_t counter_alarm = 0, counter_time; + RTC_TimeTypeDef stime = {0}; /* Check input parameters */ if((hrtc == NULL) || (sAlarm == NULL)) @@ -985,8 +985,8 @@ HAL_StatusTypeDef HAL_RTC_SetAlarm_IT(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef } /* Convert time in seconds */ - counter_time = (uint32_t)(((uint32_t)stime.Hours * 3600U) + \ - ((uint32_t)stime.Minutes * 60U) + \ + counter_time = (uint32_t)(((uint32_t)stime.Hours * 3600) + \ + ((uint32_t)stime.Minutes * 60) + \ ((uint32_t)stime.Seconds)); if(Format == RTC_FORMAT_BIN) @@ -995,8 +995,8 @@ HAL_StatusTypeDef HAL_RTC_SetAlarm_IT(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef assert_param(IS_RTC_MINUTES(sAlarm->AlarmTime.Minutes)); assert_param(IS_RTC_SECONDS(sAlarm->AlarmTime.Seconds)); - counter_alarm = (uint32_t)(((uint32_t)sAlarm->AlarmTime.Hours * 3600U) + \ - ((uint32_t)sAlarm->AlarmTime.Minutes * 60U) + \ + counter_alarm = (uint32_t)(((uint32_t)sAlarm->AlarmTime.Hours * 3600) + \ + ((uint32_t)sAlarm->AlarmTime.Minutes * 60) + \ ((uint32_t)sAlarm->AlarmTime.Seconds)); } else @@ -1005,16 +1005,16 @@ HAL_StatusTypeDef HAL_RTC_SetAlarm_IT(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef assert_param(IS_RTC_MINUTES(RTC_Bcd2ToByte(sAlarm->AlarmTime.Minutes))); assert_param(IS_RTC_SECONDS(RTC_Bcd2ToByte(sAlarm->AlarmTime.Seconds))); - counter_alarm = (((uint32_t)(RTC_Bcd2ToByte(sAlarm->AlarmTime.Hours)) * 3600U) + \ - ((uint32_t)(RTC_Bcd2ToByte(sAlarm->AlarmTime.Minutes)) * 60U) + \ - ((uint32_t)RTC_Bcd2ToByte(sAlarm->AlarmTime.Seconds))); + counter_alarm = (((uint32_t)(RTC_Bcd2ToByte(sAlarm->AlarmTime.Hours)) * 3600) + \ + ((uint32_t)(RTC_Bcd2ToByte(sAlarm->AlarmTime.Minutes)) * 60) + \ + ((uint32_t)RTC_Bcd2ToByte(sAlarm->AlarmTime.Seconds))); } /* Check that requested alarm should expire in the same day (otherwise add 1 day) */ if (counter_alarm < counter_time) { /* Add 1 day to alarm counter*/ - counter_alarm += (uint32_t)(24U * 3600U); + counter_alarm += (uint32_t)(24 * 3600); } /* Write alarm counter in RTC registers */ @@ -1065,15 +1065,12 @@ HAL_StatusTypeDef HAL_RTC_SetAlarm_IT(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef */ HAL_StatusTypeDef HAL_RTC_GetAlarm(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sAlarm, uint32_t Alarm, uint32_t Format) { - uint32_t counter_alarm = 0U; - - /* Prevent unused argument(s) compilation warning */ - UNUSED(Alarm); + uint32_t counter_alarm = 0; /* Check input parameters */ if((hrtc == NULL) || (sAlarm == NULL)) { - return HAL_ERROR; + return HAL_ERROR; } /* Check the parameters */ @@ -1085,9 +1082,9 @@ HAL_StatusTypeDef HAL_RTC_GetAlarm(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sA /* Fill the structure with the read parameters */ /* Set hours in a day range (between 0 to 24)*/ - sAlarm->AlarmTime.Hours = (uint32_t)((counter_alarm / 3600U) % 24U); - sAlarm->AlarmTime.Minutes = (uint32_t)((counter_alarm % 3600U) / 60U); - sAlarm->AlarmTime.Seconds = (uint32_t)((counter_alarm % 3600U) % 60U); + sAlarm->AlarmTime.Hours = (uint32_t)((counter_alarm / 3600) % 24); + sAlarm->AlarmTime.Minutes = (uint32_t)((counter_alarm % 3600) / 60); + sAlarm->AlarmTime.Seconds = (uint32_t)((counter_alarm % 3600) % 60); if(Format != RTC_FORMAT_BIN) { @@ -1110,9 +1107,6 @@ HAL_StatusTypeDef HAL_RTC_GetAlarm(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sA */ HAL_StatusTypeDef HAL_RTC_DeactivateAlarm(RTC_HandleTypeDef *hrtc, uint32_t Alarm) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(Alarm); - /* Check the parameters */ assert_param(IS_RTC_ALARM(Alarm)); @@ -1312,7 +1306,7 @@ HAL_RTCStateTypeDef HAL_RTC_GetState(RTC_HandleTypeDef* hrtc) */ HAL_StatusTypeDef HAL_RTC_WaitForSynchro(RTC_HandleTypeDef* hrtc) { - uint32_t tickstart = 0U; + uint32_t tickstart = 0; /* Check input parameters */ if(hrtc == NULL) @@ -1359,8 +1353,8 @@ HAL_StatusTypeDef HAL_RTC_WaitForSynchro(RTC_HandleTypeDef* hrtc) */ static uint32_t RTC_ReadTimeCounter(RTC_HandleTypeDef* hrtc) { - uint16_t high1 = 0U, high2 = 0U, low = 0U; - uint32_t timecounter = 0U; + uint16_t high1 = 0, high2 = 0, low = 0; + uint32_t timecounter = 0; high1 = READ_REG(hrtc->Instance->CNTH & RTC_CNTH_RTC_CNT); low = READ_REG(hrtc->Instance->CNTL & RTC_CNTL_RTC_CNT); @@ -1369,12 +1363,12 @@ static uint32_t RTC_ReadTimeCounter(RTC_HandleTypeDef* hrtc) if (high1 != high2) { /* In this case the counter roll over during reading of CNTL and CNTH registers, read again CNTL register then return the counter value */ - timecounter = (((uint32_t) high2 << 16U) | READ_REG(hrtc->Instance->CNTL & RTC_CNTL_RTC_CNT)); + timecounter = (((uint32_t) high2 << 16 ) | READ_REG(hrtc->Instance->CNTL & RTC_CNTL_RTC_CNT)); } else { /* No counter roll over during reading of CNTL and CNTH registers, counter value is equal to first value of CNTL and CNTH */ - timecounter = (((uint32_t) high1 << 16U) | low); + timecounter = (((uint32_t) high1 << 16 ) | low); } return timecounter; @@ -1399,7 +1393,7 @@ static HAL_StatusTypeDef RTC_WriteTimeCounter(RTC_HandleTypeDef* hrtc, uint32_t else { /* Set RTC COUNTER MSB word */ - WRITE_REG(hrtc->Instance->CNTH, (TimeCounter >> 16U)); + WRITE_REG(hrtc->Instance->CNTH, (TimeCounter >> 16)); /* Set RTC COUNTER LSB word */ WRITE_REG(hrtc->Instance->CNTL, (TimeCounter & RTC_CNTL_RTC_CNT)); @@ -1421,12 +1415,12 @@ static HAL_StatusTypeDef RTC_WriteTimeCounter(RTC_HandleTypeDef* hrtc, uint32_t */ static uint32_t RTC_ReadAlarmCounter(RTC_HandleTypeDef* hrtc) { - uint16_t high1 = 0U, low = 0U; + uint16_t high1 = 0, low = 0; high1 = READ_REG(hrtc->Instance->ALRH & RTC_CNTH_RTC_CNT); low = READ_REG(hrtc->Instance->ALRL & RTC_CNTL_RTC_CNT); - return (((uint32_t) high1 << 16U) | low); + return (((uint32_t) high1 << 16 ) | low); } /** @@ -1448,7 +1442,7 @@ static HAL_StatusTypeDef RTC_WriteAlarmCounter(RTC_HandleTypeDef* hrtc, uint32_t else { /* Set RTC COUNTER MSB word */ - WRITE_REG(hrtc->Instance->ALRH, (AlarmCounter >> 16U)); + WRITE_REG(hrtc->Instance->ALRH, (AlarmCounter >> 16)); /* Set RTC COUNTER LSB word */ WRITE_REG(hrtc->Instance->ALRL, (AlarmCounter & RTC_ALRL_RTC_ALR)); @@ -1470,7 +1464,7 @@ static HAL_StatusTypeDef RTC_WriteAlarmCounter(RTC_HandleTypeDef* hrtc, uint32_t */ static HAL_StatusTypeDef RTC_EnterInitMode(RTC_HandleTypeDef* hrtc) { - uint32_t tickstart = 0U; + uint32_t tickstart = 0; tickstart = HAL_GetTick(); /* Wait till RTC is in INIT state and if Time out is reached exit */ @@ -1497,7 +1491,7 @@ static HAL_StatusTypeDef RTC_EnterInitMode(RTC_HandleTypeDef* hrtc) */ static HAL_StatusTypeDef RTC_ExitInitMode(RTC_HandleTypeDef* hrtc) { - uint32_t tickstart = 0U; + uint32_t tickstart = 0; /* Disable the write protection for RTC registers */ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); @@ -1522,15 +1516,15 @@ static HAL_StatusTypeDef RTC_ExitInitMode(RTC_HandleTypeDef* hrtc) */ static uint8_t RTC_ByteToBcd2(uint8_t Value) { - uint32_t bcdhigh = 0U; + uint32_t bcdhigh = 0; - while(Value >= 10U) + while(Value >= 10) { bcdhigh++; - Value -= 10U; + Value -= 10; } - return ((uint8_t)(bcdhigh << 4U) | Value); + return ((uint8_t)(bcdhigh << 4) | Value); } /** @@ -1540,8 +1534,8 @@ static uint8_t RTC_ByteToBcd2(uint8_t Value) */ static uint8_t RTC_Bcd2ToByte(uint8_t Value) { - uint32_t tmp = 0U; - tmp = ((uint8_t)(Value & (uint8_t)0xF0) >> (uint8_t)0x4) * 10U; + uint32_t tmp = 0; + tmp = ((uint8_t)(Value & (uint8_t)0xF0) >> (uint8_t)0x4) * 10; return (tmp + (Value & (uint8_t)0x0F)); } @@ -1554,8 +1548,8 @@ static uint8_t RTC_Bcd2ToByte(uint8_t Value) */ static void RTC_DateUpdate(RTC_HandleTypeDef* hrtc, uint32_t DayElapsed) { - uint32_t year = 0U, month = 0U, day = 0U; - uint32_t loop = 0U; + uint32_t year = 0, month = 0, day = 0; + uint32_t loop = 0; /* Get the current year*/ year = hrtc->DateToUpdate.Year; @@ -1564,35 +1558,35 @@ static void RTC_DateUpdate(RTC_HandleTypeDef* hrtc, uint32_t DayElapsed) month = hrtc->DateToUpdate.Month; day = hrtc->DateToUpdate.Date; - for (loop = 0U; loop < DayElapsed; loop++) + for (loop = 0; loop < DayElapsed; loop++) { - if((month == 1U) || (month == 3U) || (month == 5U) || (month == 7U) || \ - (month == 8U) || (month == 10U) || (month == 12U)) + if((month == 1) || (month == 3) || (month == 5) || (month == 7) || \ + (month == 8) || (month == 10) || (month == 12)) { - if(day < 31U) + if(day < 31) { day++; } /* Date structure member: day = 31 */ else { - if(month != 12U) + if(month != 12) { month++; - day = 1U; + day = 1; } /* Date structure member: day = 31 & month =12 */ else { - month = 1U; - day = 1U; + month = 1; + day = 1; year++; } } } - else if((month == 4U) || (month == 6U) || (month == 9U) || (month == 11U)) + else if((month == 4) || (month == 6) || (month == 9) || (month == 11)) { - if(day < 30U) + if(day < 30) { day++; } @@ -1600,16 +1594,16 @@ static void RTC_DateUpdate(RTC_HandleTypeDef* hrtc, uint32_t DayElapsed) else { month++; - day = 1U; + day = 1; } } - else if(month == 2U) + else if(month == 2) { - if(day < 28U) + if(day < 28) { day++; } - else if(day == 28U) + else if(day == 28) { /* Leap year */ if(RTC_IsLeapYear(year)) @@ -1619,13 +1613,13 @@ static void RTC_DateUpdate(RTC_HandleTypeDef* hrtc, uint32_t DayElapsed) else { month++; - day = 1U; + day = 1; } } - else if(day == 29U) + else if(day == 29) { month++; - day = 1U; + day = 1; } } } @@ -1649,23 +1643,23 @@ static void RTC_DateUpdate(RTC_HandleTypeDef* hrtc, uint32_t DayElapsed) */ static uint8_t RTC_IsLeapYear(uint16_t nYear) { - if((nYear % 4U) != 0U) + if((nYear % 4) != 0) { - return 0U; + return 0; } - if((nYear % 100U) != 0U) + if((nYear % 100) != 0) { - return 1U; + return 1; } - if((nYear % 400U) == 0U) + if((nYear % 400) == 0) { - return 1U; + return 1; } else { - return 0U; + return 0; } } @@ -1686,19 +1680,19 @@ static uint8_t RTC_IsLeapYear(uint16_t nYear) */ static uint8_t RTC_WeekDayNum(uint32_t nYear, uint8_t nMonth, uint8_t nDay) { - uint32_t year = 0U, weekday = 0U; + uint32_t year = 0, weekday = 0; - year = 2000U + nYear; + year = 2000 + nYear; - if(nMonth < 3U) + if(nMonth < 3) { /*D = { [(23 x month)/9] + day + 4 + year + [(year-1)/4] - [(year-1)/100] + [(year-1)/400] } mod 7*/ - weekday = (((23U * nMonth)/9U) + nDay + 4U + year + ((year-1U)/4U) - ((year-1U)/100U) + ((year-1U)/400U)) % 7U; + weekday = (((23 * nMonth)/9) + nDay + 4 + year + ((year-1)/4) - ((year-1)/100) + ((year-1)/400)) % 7; } else { /*D = { [(23 x month)/9] + day + 4 + year + [year/4] - [year/100] + [year/400] - 2 } mod 7*/ - weekday = (((23U * nMonth)/9U) + nDay + 4U + year + (year/4U) - (year/100U) + (year/400U) - 2U ) % 7U; + weekday = (((23 * nMonth)/9) + nDay + 4 + year + (year/4) - (year/100) + (year/400) - 2 ) % 7; } return (uint8_t)weekday; diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_rtc.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_rtc.h index 1889c0ca20c..b81c1f16117 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_rtc.h +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_rtc.h @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_hal_rtc.h * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief Header file of RTC HAL module. ****************************************************************************** * @attention @@ -58,14 +58,14 @@ * @{ */ -#define IS_RTC_ASYNCH_PREDIV(PREDIV) (((PREDIV) <= 0xFFFFFU) || ((PREDIV) == RTC_AUTO_1_SECOND)) -#define IS_RTC_HOUR24(HOUR) ((HOUR) <= 23U) -#define IS_RTC_MINUTES(MINUTES) ((MINUTES) <= 59U) -#define IS_RTC_SECONDS(SECONDS) ((SECONDS) <= 59U) +#define IS_RTC_ASYNCH_PREDIV(PREDIV) (((PREDIV) <= (uint32_t)0xFFFFF) || ((PREDIV) == RTC_AUTO_1_SECOND)) +#define IS_RTC_HOUR24(HOUR) ((HOUR) <= (uint32_t)23) +#define IS_RTC_MINUTES(MINUTES) ((MINUTES) <= (uint32_t)59) +#define IS_RTC_SECONDS(SECONDS) ((SECONDS) <= (uint32_t)59) #define IS_RTC_FORMAT(FORMAT) (((FORMAT) == RTC_FORMAT_BIN) || ((FORMAT) == RTC_FORMAT_BCD)) -#define IS_RTC_YEAR(YEAR) ((YEAR) <= 99U) -#define IS_RTC_MONTH(MONTH) (((MONTH) >= 1U) && ((MONTH) <= 12U)) -#define IS_RTC_DATE(DATE) (((DATE) >= 1U) && ((DATE) <= 31U)) +#define IS_RTC_YEAR(YEAR) ((YEAR) <= (uint32_t)99) +#define IS_RTC_MONTH(MONTH) (((MONTH) >= (uint32_t)1) && ((MONTH) <= (uint32_t)12)) +#define IS_RTC_DATE(DATE) (((DATE) >= (uint32_t)1) && ((DATE) <= (uint32_t)31)) #define IS_RTC_ALARM(ALARM) ((ALARM) == RTC_ALARM_A) #define IS_RTC_CALIB_OUTPUT(__OUTPUT__) (((__OUTPUT__) == RTC_OUTPUTSOURCE_NONE) || \ ((__OUTPUT__) == RTC_OUTPUTSOURCE_CALIBCLOCK) || \ @@ -83,7 +83,7 @@ /** @defgroup RTC_Timeout_Value Default Timeout Value * @{ */ -#define RTC_TIMEOUT_VALUE 1000U +#define RTC_TIMEOUT_VALUE 1000 /** * @} */ @@ -137,11 +137,11 @@ typedef struct */ typedef enum { - HAL_RTC_STATE_RESET = 0x00U, /*!< RTC not yet initialized or disabled */ - HAL_RTC_STATE_READY = 0x01U, /*!< RTC initialized and ready for use */ - HAL_RTC_STATE_BUSY = 0x02U, /*!< RTC process is ongoing */ - HAL_RTC_STATE_TIMEOUT = 0x03U, /*!< RTC timeout state */ - HAL_RTC_STATE_ERROR = 0x04U /*!< RTC error state */ + HAL_RTC_STATE_RESET = 0x00, /*!< RTC not yet initialized or disabled */ + HAL_RTC_STATE_READY = 0x01, /*!< RTC initialized and ready for use */ + HAL_RTC_STATE_BUSY = 0x02, /*!< RTC process is ongoing */ + HAL_RTC_STATE_TIMEOUT = 0x03, /*!< RTC timeout state */ + HAL_RTC_STATE_ERROR = 0x04 /*!< RTC error state */ }HAL_RTCStateTypeDef; @@ -207,7 +207,7 @@ typedef struct /** @defgroup RTC_Automatic_Prediv_1_Second Automatic calculation of prediv for 1sec timebase * @{ */ -#define RTC_AUTO_1_SECOND 0xFFFFFFFFU +#define RTC_AUTO_1_SECOND ((uint32_t)0xFFFFFFFF) /** * @} @@ -216,8 +216,8 @@ typedef struct /** @defgroup RTC_Input_parameter_format_definitions Input Parameter Format * @{ */ -#define RTC_FORMAT_BIN 0x000000000U -#define RTC_FORMAT_BCD 0x000000001U +#define RTC_FORMAT_BIN ((uint32_t)0x000000000) +#define RTC_FORMAT_BCD ((uint32_t)0x000000001) /** * @} @@ -263,7 +263,7 @@ typedef struct /** @defgroup RTC_Alarms_Definitions Alarms Definitions * @{ */ -#define RTC_ALARM_A 0U /*!< Specify alarm ID (mainly for legacy purposes) */ +#define RTC_ALARM_A 0 /*!< Specify alarm ID (mainly for legacy purposes) */ /** * @} @@ -274,7 +274,7 @@ typedef struct * @{ */ -#define RTC_OUTPUTSOURCE_NONE 0x00000000U /*!< No output on the TAMPER pin */ +#define RTC_OUTPUTSOURCE_NONE ((uint32_t)0x00000000) /*!< No output on the TAMPER pin */ #define RTC_OUTPUTSOURCE_CALIBCLOCK BKP_RTCCR_CCO /*!< RTC clock with a frequency divided by 64 on the TAMPER pin */ #define RTC_OUTPUTSOURCE_ALARM BKP_RTCCR_ASOE /*!< Alarm pulse signal on the TAMPER pin */ #define RTC_OUTPUTSOURCE_SECOND (BKP_RTCCR_ASOS | BKP_RTCCR_ASOE) /*!< Second pulse signal on the TAMPER pin */ @@ -453,22 +453,14 @@ typedef struct * @brief ALARM EXTI line configuration: set rising & falling edge trigger. * @retval None. */ -#define __HAL_RTC_ALARM_EXTI_ENABLE_RISING_FALLING_EDGE() \ -do{ \ - __HAL_RTC_ALARM_EXTI_ENABLE_RISING_EDGE(); \ - __HAL_RTC_ALARM_EXTI_ENABLE_FALLING_EDGE(); \ - } while(0U) +#define __HAL_RTC_ALARM_EXTI_ENABLE_RISING_FALLING_EDGE() __HAL_RTC_ALARM_EXTI_ENABLE_RISING_EDGE();__HAL_RTC_ALARM_EXTI_ENABLE_FALLING_EDGE(); /** * @brief Disable the ALARM Extended Interrupt Rising & Falling Trigger. * This parameter can be: * @retval None. */ -#define __HAL_RTC_ALARM_EXTI_DISABLE_RISING_FALLING_EDGE() \ -do{ \ - __HAL_RTC_ALARM_EXTI_DISABLE_RISING_EDGE(); \ - __HAL_RTC_ALARM_EXTI_DISABLE_FALLING_EDGE(); \ - } while(0U) +#define __HAL_RTC_ALARM_EXTI_DISABLE_RISING_FALLING_EDGE() __HAL_RTC_ALARM_EXTI_DISABLE_RISING_EDGE();__HAL_RTC_ALARM_EXTI_DISABLE_FALLING_EDGE()(); /** * @brief Check whether the specified ALARM EXTI interrupt flag is set or not. diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_rtc_ex.c b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_rtc_ex.c index 1a8d9dca54b..8d90e937d6b 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_rtc_ex.c +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_rtc_ex.c @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_hal_rtc_ex.c * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief Extended RTC HAL module driver. * This file provides firmware functions to manage the following * functionalities of the Real Time Clock (RTC) Extension peripheral: @@ -197,9 +197,7 @@ HAL_StatusTypeDef HAL_RTCEx_DeactivateTamper(RTC_HandleTypeDef *hrtc, uint32_t T { return HAL_ERROR; } - /* Prevent unused argument(s) compilation warning */ - UNUSED(Tamper); - + assert_param(IS_RTC_TAMPER(Tamper)); /* Process Locked */ @@ -289,7 +287,7 @@ HAL_StatusTypeDef HAL_RTCEx_PollForTamper1Event(RTC_HandleTypeDef *hrtc, uint32_ { if(Timeout != HAL_MAX_DELAY) { - if((Timeout == 0U)||((HAL_GetTick() - tickstart ) > Timeout)) + if((Timeout == 0)||((HAL_GetTick() - tickstart ) > Timeout)) { hrtc->State = HAL_RTC_STATE_TIMEOUT; return HAL_TIMEOUT; @@ -487,16 +485,13 @@ __weak void HAL_RTCEx_RTCEventErrorCallback(RTC_HandleTypeDef *hrtc) */ void HAL_RTCEx_BKUPWrite(RTC_HandleTypeDef *hrtc, uint32_t BackupRegister, uint32_t Data) { - uint32_t tmp = 0U; - - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); + uint32_t tmp = 0; /* Check the parameters */ assert_param(IS_RTC_BKP(BackupRegister)); tmp = (uint32_t)BKP_BASE; - tmp += (BackupRegister * 4U); + tmp += (BackupRegister * 4); *(__IO uint32_t *) tmp = (Data & BKP_DR1_D); } @@ -512,17 +507,14 @@ void HAL_RTCEx_BKUPWrite(RTC_HandleTypeDef *hrtc, uint32_t BackupRegister, uint3 */ uint32_t HAL_RTCEx_BKUPRead(RTC_HandleTypeDef *hrtc, uint32_t BackupRegister) { - uint32_t backupregister = 0U; - uint32_t pvalue = 0U; - - /* Prevent unused argument(s) compilation warning */ - UNUSED(hrtc); + uint32_t backupregister = 0; + uint32_t pvalue = 0; /* Check the parameters */ assert_param(IS_RTC_BKP(BackupRegister)); backupregister = (uint32_t)BKP_BASE; - backupregister += (BackupRegister * 4U); + backupregister += (BackupRegister * 4); pvalue = (*(__IO uint32_t *)(backupregister)) & BKP_DR1_D; @@ -547,10 +539,7 @@ HAL_StatusTypeDef HAL_RTCEx_SetSmoothCalib(RTC_HandleTypeDef* hrtc, uint32_t Smo { return HAL_ERROR; } - /* Prevent unused argument(s) compilation warning */ - UNUSED(SmoothCalibPeriod); - UNUSED(SmoothCalibPlusPulses); - + /* Check the parameters */ assert_param(IS_RTC_SMOOTH_CALIB_MINUS(SmouthCalibMinusPulsesValue)); diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_rtc_ex.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_rtc_ex.h index d6b8d437bc4..25d18442595 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_rtc_ex.h +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_rtc_ex.h @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_hal_rtc_ex.h * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief Header file of RTC HAL Extension module. ****************************************************************************** * @attention @@ -73,14 +73,14 @@ #define IS_RTC_TAMPER(__TAMPER__) ((__TAMPER__) == RTC_TAMPER_1) #define IS_RTC_TAMPER_TRIGGER(__TRIGGER__) (((__TRIGGER__) == RTC_TAMPERTRIGGER_LOWLEVEL) || \ - ((__TRIGGER__) == RTC_TAMPERTRIGGER_HIGHLEVEL)) + ((__TRIGGER__) == RTC_TAMPERTRIGGER_HIGHLEVEL)) -#if RTC_BKP_NUMBER > 10U -#define IS_RTC_BKP(BKP) (((BKP) <= (uint32_t)RTC_BKP_DR10) || (((BKP) >= (uint32_t)RTC_BKP_DR11) && ((BKP) <= (uint32_t)RTC_BKP_DR42))) +#if RTC_BKP_NUMBER > 10 +#define IS_RTC_BKP(BKP) (((BKP) <= (uint32_t) RTC_BKP_DR10) || (((BKP) >= (uint32_t) RTC_BKP_DR11) && ((BKP) <= (uint32_t) RTC_BKP_DR42))) #else -#define IS_RTC_BKP(BKP) ((BKP) <= (uint32_t)RTC_BKP_NUMBER) +#define IS_RTC_BKP(BKP) ((BKP) <= (uint32_t) RTC_BKP_NUMBER) #endif -#define IS_RTC_SMOOTH_CALIB_MINUS(__VALUE__) ((__VALUE__) <= 0x0000007FU) +#define IS_RTC_SMOOTH_CALIB_MINUS(__VALUE__) ((__VALUE__) <= 0x0000007F) /** * @} @@ -129,7 +129,7 @@ typedef struct * @{ */ #define RTC_TAMPERTRIGGER_LOWLEVEL BKP_CR_TPAL /*!< A high level on the TAMPER pin resets all data backup registers (if TPE bit is set) */ -#define RTC_TAMPERTRIGGER_HIGHLEVEL 0x00000000U /*!< A low level on the TAMPER pin resets all data backup registers (if TPE bit is set) */ +#define RTC_TAMPERTRIGGER_HIGHLEVEL ((uint32_t)0x00000000) /*!< A low level on the TAMPER pin resets all data backup registers (if TPE bit is set) */ /** * @} @@ -138,52 +138,52 @@ typedef struct /** @defgroup RTCEx_Backup_Registers_Definitions Backup Registers Definitions * @{ */ -#if RTC_BKP_NUMBER > 0U -#define RTC_BKP_DR1 0x00000001U -#define RTC_BKP_DR2 0x00000002U -#define RTC_BKP_DR3 0x00000003U -#define RTC_BKP_DR4 0x00000004U -#define RTC_BKP_DR5 0x00000005U -#define RTC_BKP_DR6 0x00000006U -#define RTC_BKP_DR7 0x00000007U -#define RTC_BKP_DR8 0x00000008U -#define RTC_BKP_DR9 0x00000009U -#define RTC_BKP_DR10 0x0000000AU +#if RTC_BKP_NUMBER > 0 +#define RTC_BKP_DR1 ((uint32_t)0x00000001) +#define RTC_BKP_DR2 ((uint32_t)0x00000002) +#define RTC_BKP_DR3 ((uint32_t)0x00000003) +#define RTC_BKP_DR4 ((uint32_t)0x00000004) +#define RTC_BKP_DR5 ((uint32_t)0x00000005) +#define RTC_BKP_DR6 ((uint32_t)0x00000006) +#define RTC_BKP_DR7 ((uint32_t)0x00000007) +#define RTC_BKP_DR8 ((uint32_t)0x00000008) +#define RTC_BKP_DR9 ((uint32_t)0x00000009) +#define RTC_BKP_DR10 ((uint32_t)0x0000000A) #endif /* RTC_BKP_NUMBER > 0 */ -#if RTC_BKP_NUMBER > 10U -#define RTC_BKP_DR11 0x00000010U -#define RTC_BKP_DR12 0x00000011U -#define RTC_BKP_DR13 0x00000012U -#define RTC_BKP_DR14 0x00000013U -#define RTC_BKP_DR15 0x00000014U -#define RTC_BKP_DR16 0x00000015U -#define RTC_BKP_DR17 0x00000016U -#define RTC_BKP_DR18 0x00000017U -#define RTC_BKP_DR19 0x00000018U -#define RTC_BKP_DR20 0x00000019U -#define RTC_BKP_DR21 0x0000001AU -#define RTC_BKP_DR22 0x0000001BU -#define RTC_BKP_DR23 0x0000001CU -#define RTC_BKP_DR24 0x0000001DU -#define RTC_BKP_DR25 0x0000001EU -#define RTC_BKP_DR26 0x0000001FU -#define RTC_BKP_DR27 0x00000020U -#define RTC_BKP_DR28 0x00000021U -#define RTC_BKP_DR29 0x00000022U -#define RTC_BKP_DR30 0x00000023U -#define RTC_BKP_DR31 0x00000024U -#define RTC_BKP_DR32 0x00000025U -#define RTC_BKP_DR33 0x00000026U -#define RTC_BKP_DR34 0x00000027U -#define RTC_BKP_DR35 0x00000028U -#define RTC_BKP_DR36 0x00000029U -#define RTC_BKP_DR37 0x0000002AU -#define RTC_BKP_DR38 0x0000002BU -#define RTC_BKP_DR39 0x0000002CU -#define RTC_BKP_DR40 0x0000002DU -#define RTC_BKP_DR41 0x0000002EU -#define RTC_BKP_DR42 0x0000002FU +#if RTC_BKP_NUMBER > 10 +#define RTC_BKP_DR11 ((uint32_t)0x00000010) +#define RTC_BKP_DR12 ((uint32_t)0x00000011) +#define RTC_BKP_DR13 ((uint32_t)0x00000012) +#define RTC_BKP_DR14 ((uint32_t)0x00000013) +#define RTC_BKP_DR15 ((uint32_t)0x00000014) +#define RTC_BKP_DR16 ((uint32_t)0x00000015) +#define RTC_BKP_DR17 ((uint32_t)0x00000016) +#define RTC_BKP_DR18 ((uint32_t)0x00000017) +#define RTC_BKP_DR19 ((uint32_t)0x00000018) +#define RTC_BKP_DR20 ((uint32_t)0x00000019) +#define RTC_BKP_DR21 ((uint32_t)0x0000001A) +#define RTC_BKP_DR22 ((uint32_t)0x0000001B) +#define RTC_BKP_DR23 ((uint32_t)0x0000001C) +#define RTC_BKP_DR24 ((uint32_t)0x0000001D) +#define RTC_BKP_DR25 ((uint32_t)0x0000001E) +#define RTC_BKP_DR26 ((uint32_t)0x0000001F) +#define RTC_BKP_DR27 ((uint32_t)0x00000020) +#define RTC_BKP_DR28 ((uint32_t)0x00000021) +#define RTC_BKP_DR29 ((uint32_t)0x00000022) +#define RTC_BKP_DR30 ((uint32_t)0x00000023) +#define RTC_BKP_DR31 ((uint32_t)0x00000024) +#define RTC_BKP_DR32 ((uint32_t)0x00000025) +#define RTC_BKP_DR33 ((uint32_t)0x00000026) +#define RTC_BKP_DR34 ((uint32_t)0x00000027) +#define RTC_BKP_DR35 ((uint32_t)0x00000028) +#define RTC_BKP_DR36 ((uint32_t)0x00000029) +#define RTC_BKP_DR37 ((uint32_t)0x0000002A) +#define RTC_BKP_DR38 ((uint32_t)0x0000002B) +#define RTC_BKP_DR39 ((uint32_t)0x0000002C) +#define RTC_BKP_DR40 ((uint32_t)0x0000002D) +#define RTC_BKP_DR41 ((uint32_t)0x0000002E) +#define RTC_BKP_DR42 ((uint32_t)0x0000002F) #endif /* RTC_BKP_NUMBER > 10 */ /** diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_sd.c b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_sd.c index 4a26b229d48..f5443003a55 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_sd.c +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_sd.c @@ -2,15 +2,15 @@ ****************************************************************************** * @file stm32f1xx_hal_sd.c * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief SD card HAL module driver. * This file provides firmware functions to manage the following * functionalities of the Secure Digital (SD) peripheral: * + Initialization and de-initialization functions * + IO operation functions * + Peripheral Control functions - * + SD card Control functions + * + Peripheral State functions * @verbatim ============================================================================== @@ -43,58 +43,45 @@ (+++) Configure the SDIO and DMA interrupt priorities using functions HAL_NVIC_SetPriority(); DMA priority is superior to SDIO's priority (+++) Enable the NVIC DMA and SDIO IRQs using function HAL_NVIC_EnableIRQ() - (+++) SDIO interrupts are managed using the macros __HAL_SD_ENABLE_IT() - and __HAL_SD_DISABLE_IT() inside the communication process. - (+++) SDIO interrupts pending bits are managed using the macros __HAL_SD_GET_IT() - and __HAL_SD_CLEAR_IT() - (##) NVIC configuration if you need to use interrupt process (HAL_SD_ReadBlocks_IT() - and HAL_SD_WriteBlocks_IT() APIs). - (+++) Configure the SDIO interrupt priorities using function - HAL_NVIC_SetPriority(); - (+++) Enable the NVIC SDIO IRQs using function HAL_NVIC_EnableIRQ() - (+++) SDIO interrupts are managed using the macros __HAL_SD_ENABLE_IT() - and __HAL_SD_DISABLE_IT() inside the communication process. - (+++) SDIO interrupts pending bits are managed using the macros __HAL_SD_GET_IT() - and __HAL_SD_CLEAR_IT() + (+++) SDIO interrupts are managed using the macros __HAL_SD_SDIO_ENABLE_IT() + and __HAL_SD_SDIO_DISABLE_IT() inside the communication process. + (+++) SDIO interrupts pending bits are managed using the macros __HAL_SD_SDIO_GET_IT() + and __HAL_SD_SDIO_CLEAR_IT() (#) At this stage, you can perform SD read/write/erase operations after SD card initialization *** SD Card Initialization and configuration *** ================================================ [..] - To initialize the SD Card, use the HAL_SD_Init() function. It Initializes - SDIO IP(STM32 side) and the SD Card, and put it into StandBy State (Ready for data transfer). + To initialize the SD Card, use the HAL_SD_Init() function. It Initializes + the SD Card and put it into StandBy State (Ready for data transfer). This function provide the following operations: - - (#) Initialize the SDIO peripheral interface with defaullt configuration. - The initialization process is done at 400KHz. You can change or adapt - this frequency by adjusting the "ClockDiv" field. + + (#) Apply the SD Card initialization process at 400KHz and check the SD Card + type (Standard Capacity or High Capacity). You can change or adapt this + frequency by adjusting the "ClockDiv" field. The SD Card frequency (SDIO_CK) is computed as follows: SDIO_CK = SDIOCLK / (ClockDiv + 2) In initialization mode and according to the SD Card standard, make sure that the SDIO_CK frequency doesn't exceed 400KHz. - - This phase of initialization is done through SDIO_Init() and - SDIO_PowerState_ON() SDIO low level APIs. - - (#) Initialize the SD card. The API used is HAL_SD_InitCard(). - This phase allows the card initialization and identification - and check the SD Card type (Standard Capacity or High Capacity) - The initialization flow is compatible with SD standard. - - This API (HAL_SD_InitCard()) could be used also to reinitialize the card in case - of plug-off plug-in. - (#) Configure the SD Card Data transfer frequency. By Default, the card transfer - frequency is set to 24MHz. You can change or adapt this frequency by adjusting + (#) Get the SD CID and CSD data. All these information are managed by the SDCardInfo + structure. This structure provide also ready computed SD Card capacity + and Block size. + + -@- These information are stored in SD handle structure in case of future use. + + (#) Configure the SD Card Data transfer frequency. The card transfer + frequency is set to SDIOCLK / (SDIO_TRANSFER_CLK_DIV + 2). You can change or adapt this frequency by adjusting the "ClockDiv" field. + The SD Card frequency (SDIO_CK) is computed as follows: + + SDIO_CK = SDIOCLK / (ClockDiv + 2) + In transfer mode and according to the SD Card standard, make sure that the SDIO_CK frequency doesn't exceed 25MHz and 50MHz in High-speed mode switch. - To be able to use a frequency higher than 24MHz, you should use the SDIO - peripheral in bypass mode. Refer to the corresponding reference manual - for more details. (#) Select the corresponding SD Card according to the address read with the step 2. @@ -104,101 +91,65 @@ ============================== [..] (+) You can read from SD card in polling mode by using function HAL_SD_ReadBlocks(). - This function allows the read of 512 bytes blocks. + This function support only 512-bytes block length (the block size should be + chosen as 512 bytes). You can choose either one block read operation or multiple block read operation by adjusting the "NumberOfBlocks" parameter. - After this, you have to ensure that the transfer is done correctly. The check is done - through HAL_SD_GetCardState() function for SD card state. (+) You can read from SD card in DMA mode by using function HAL_SD_ReadBlocks_DMA(). - This function allows the read of 512 bytes blocks. - You can choose either one block read operation or multiple block read operation - by adjusting the "NumberOfBlocks" parameter. - After this, you have to ensure that the transfer is done correctly. The check is done - through HAL_SD_GetCardState() function for SD card state. - You could also check the DMA transfer process through the SD Rx interrupt event. - - (+) You can read from SD card in Interrupt mode by using function HAL_SD_ReadBlocks_IT(). - This function allows the read of 512 bytes blocks. + This function support only 512-bytes block length (the block size should be + chosen as 512 bytes). You can choose either one block read operation or multiple block read operation by adjusting the "NumberOfBlocks" parameter. - After this, you have to ensure that the transfer is done correctly. The check is done - through HAL_SD_GetCardState() function for SD card state. - You could also check the IT transfer process through the SD Rx interrupt event. + After this, you have to call the function HAL_SD_CheckReadOperation(), to insure + that the read transfer is done correctly in both DMA and SD sides. *** SD Card Write operation *** =============================== [..] (+) You can write to SD card in polling mode by using function HAL_SD_WriteBlocks(). - This function allows the read of 512 bytes blocks. + This function support only 512-bytes block length (the block size should be + chosen as 512 bytes). You can choose either one block read operation or multiple block read operation by adjusting the "NumberOfBlocks" parameter. - After this, you have to ensure that the transfer is done correctly. The check is done - through HAL_SD_GetCardState() function for SD card state. (+) You can write to SD card in DMA mode by using function HAL_SD_WriteBlocks_DMA(). - This function allows the read of 512 bytes blocks. - You can choose either one block read operation or multiple block read operation - by adjusting the "NumberOfBlocks" parameter. - After this, you have to ensure that the transfer is done correctly. The check is done - through HAL_SD_GetCardState() function for SD card state. - You could also check the DMA transfer process through the SD Tx interrupt event. - - (+) You can write to SD card in Interrupt mode by using function HAL_SD_WriteBlocks_IT(). - This function allows the read of 512 bytes blocks. + This function support only 512-bytes block length (the block size should be + chosen as 512 byte). You can choose either one block read operation or multiple block read operation by adjusting the "NumberOfBlocks" parameter. - After this, you have to ensure that the transfer is done correctly. The check is done - through HAL_SD_GetCardState() function for SD card state. - You could also check the IT transfer process through the SD Tx interrupt event. + After this, you have to call the function HAL_SD_CheckWriteOperation(), to insure + that the write transfer is done correctly in both DMA and SD sides. *** SD card status *** ====================== [..] - (+) The SD Status contains status bits that are related to the SD Memory - Card proprietary features. To get SD card status use the HAL_SD_GetCardStatus(). - - *** SD card information *** - =========================== - [..] - (+) To get SD card information, you can use the function HAL_SD_GetCardInfo(). - It returns useful information about the SD card such as block size, card type, - block number ... - - *** SD card CSD register *** - ============================ - [..] - (+) The HAL_SD_GetCardCSD() API allows to get the parameters of the CSD register. - Some of the CSD parameters are useful for card initialization and identification. - - *** SD card CID register *** - ============================ - [..] - (+) The HAL_SD_GetCardCID() API allows to get the parameters of the CID register. - Some of the CSD parameters are useful for card initialization and identification. + (+) At any time, you can check the SD Card status and get the SD card state + by using the HAL_SD_GetStatus() function. This function checks first if the + SD card is still connected and then get the internal SD Card transfer state. + (+) You can also get the SD card SD Status register by using the HAL_SD_SendSDStatus() + function. *** SD HAL driver macros list *** ================================== [..] Below the list of most used macros in SD HAL driver. - - (+) __HAL_SD_ENABLE : Enable the SD device - (+) __HAL_SD_DISABLE : Disable the SD device - (+) __HAL_SD_DMA_ENABLE: Enable the SDIO DMA transfer - (+) __HAL_SD_DMA_DISABLE: Disable the SDIO DMA transfer - (+) __HAL_SD_ENABLE_IT: Enable the SD device interrupt - (+) __HAL_SD_DISABLE_IT: Disable the SD device interrupt - (+) __HAL_SD_GET_FLAG:Check whether the specified SD flag is set or not - (+) __HAL_SD_CLEAR_FLAG: Clear the SD's pending flags - - [..] - (@) You can refer to the SD HAL driver header file for more useful macros + (+) __HAL_SD_SDIO_ENABLE : Enable the SD device + (+) __HAL_SD_SDIO_DISABLE : Disable the SD device + (+) __HAL_SD_SDIO_DMA_ENABLE: Enable the SDIO DMA transfer + (+) __HAL_SD_SDIO_DMA_DISABLE: Disable the SDIO DMA transfer + (+) __HAL_SD_SDIO_ENABLE_IT: Enable the SD device interrupt + (+) __HAL_SD_SDIO_DISABLE_IT: Disable the SD device interrupt + (+) __HAL_SD_SDIO_GET_FLAG:Check whether the specified SD flag is set or not + (+) __HAL_SD_SDIO_CLEAR_FLAG: Clear the SD's pending flags + -@- You can refer to the SD HAL driver header file for more useful macros + @endverbatim ****************************************************************************** * @attention * - *

© COPYRIGHT(c) 2017 STMicroelectronics

+ *

© COPYRIGHT(c) 2016 STMicroelectronics

* * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: @@ -228,23 +179,105 @@ /* Includes ------------------------------------------------------------------*/ #include "stm32f1xx_hal.h" +#ifdef HAL_SD_MODULE_ENABLED + #if defined(STM32F103xE) || defined(STM32F103xG) /** @addtogroup STM32F1xx_HAL_Driver * @{ */ -/** @addtogroup SD +/** @defgroup SD SD + * @brief SD HAL module driver * @{ */ -#ifdef HAL_SD_MODULE_ENABLED /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ -/** @addtogroup SD_Private_Defines + +/** @defgroup SD_Private_Define SD Private Constant * @{ */ - +/** + * @brief SDIO Data block size + */ +#define DATA_BLOCK_SIZE ((uint32_t)(9 << 4)) +/** + * @brief SDIO Static flags, TimeOut, FIFO Address + */ +#define SDIO_STATIC_FLAGS ((uint32_t)(SDIO_FLAG_CCRCFAIL | SDIO_FLAG_DCRCFAIL | SDIO_FLAG_CTIMEOUT |\ + SDIO_FLAG_DTIMEOUT | SDIO_FLAG_TXUNDERR | SDIO_FLAG_RXOVERR |\ + SDIO_FLAG_CMDREND | SDIO_FLAG_CMDSENT | SDIO_FLAG_DATAEND |\ + SDIO_FLAG_DBCKEND)) + +#define SDIO_CMD0TIMEOUT ((uint32_t)0x00010000) + +/** + * @brief Mask for errors Card Status R1 (OCR Register) + */ +#define SD_OCR_ADDR_OUT_OF_RANGE ((uint32_t)0x80000000) +#define SD_OCR_ADDR_MISALIGNED ((uint32_t)0x40000000) +#define SD_OCR_BLOCK_LEN_ERR ((uint32_t)0x20000000) +#define SD_OCR_ERASE_SEQ_ERR ((uint32_t)0x10000000) +#define SD_OCR_BAD_ERASE_PARAM ((uint32_t)0x08000000) +#define SD_OCR_WRITE_PROT_VIOLATION ((uint32_t)0x04000000) +#define SD_OCR_LOCK_UNLOCK_FAILED ((uint32_t)0x01000000) +#define SD_OCR_COM_CRC_FAILED ((uint32_t)0x00800000) +#define SD_OCR_ILLEGAL_CMD ((uint32_t)0x00400000) +#define SD_OCR_CARD_ECC_FAILED ((uint32_t)0x00200000) +#define SD_OCR_CC_ERROR ((uint32_t)0x00100000) +#define SD_OCR_GENERAL_UNKNOWN_ERROR ((uint32_t)0x00080000) +#define SD_OCR_STREAM_READ_UNDERRUN ((uint32_t)0x00040000) +#define SD_OCR_STREAM_WRITE_OVERRUN ((uint32_t)0x00020000) +#define SD_OCR_CID_CSD_OVERWRITE ((uint32_t)0x00010000) +#define SD_OCR_WP_ERASE_SKIP ((uint32_t)0x00008000) +#define SD_OCR_CARD_ECC_DISABLED ((uint32_t)0x00004000) +#define SD_OCR_ERASE_RESET ((uint32_t)0x00002000) +#define SD_OCR_AKE_SEQ_ERROR ((uint32_t)0x00000008) +#define SD_OCR_ERRORBITS ((uint32_t)0xFDFFE008) + +/** + * @brief Masks for R6 Response + */ +#define SD_R6_GENERAL_UNKNOWN_ERROR ((uint32_t)0x00002000) +#define SD_R6_ILLEGAL_CMD ((uint32_t)0x00004000) +#define SD_R6_COM_CRC_FAILED ((uint32_t)0x00008000) + +#define SD_VOLTAGE_WINDOW_SD ((uint32_t)0x80100000) +#define SD_HIGH_CAPACITY ((uint32_t)0x40000000) +#define SD_STD_CAPACITY ((uint32_t)0x00000000) +#define SD_CHECK_PATTERN ((uint32_t)0x000001AA) + +#define SD_MAX_VOLT_TRIAL ((uint32_t)0x0000FFFF) +#define SD_ALLZERO ((uint32_t)0x00000000) + +#define SD_WIDE_BUS_SUPPORT ((uint32_t)0x00040000) +#define SD_SINGLE_BUS_SUPPORT ((uint32_t)0x00010000) +#define SD_CARD_LOCKED ((uint32_t)0x02000000) + +#define SD_DATATIMEOUT ((uint32_t)0xFFFFFFFF) +#define SD_0TO7BITS ((uint32_t)0x000000FF) +#define SD_8TO15BITS ((uint32_t)0x0000FF00) +#define SD_16TO23BITS ((uint32_t)0x00FF0000) +#define SD_24TO31BITS ((uint32_t)0xFF000000) +#define SD_MAX_DATA_LENGTH ((uint32_t)0x01FFFFFF) + +#define SD_HALFFIFO ((uint32_t)0x00000008) +#define SD_HALFFIFOBYTES ((uint32_t)0x00000020) + +/** + * @brief Command Class Supported + */ +#define SD_CCCC_LOCK_UNLOCK ((uint32_t)0x00000080) +#define SD_CCCC_WRITE_PROT ((uint32_t)0x00000040) +#define SD_CCCC_ERASE ((uint32_t)0x00000020) + +/** + * @brief Following commands are SD Card Specific commands. + * SDIO_APP_CMD should be sent before sending these commands. + */ +#define SD_SDIO_SEND_IF_COND ((uint32_t)SD_CMD_HS_SEND_EXT_CSD) + /** * @} */ @@ -253,170 +286,120 @@ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ + /** @defgroup SD_Private_Functions SD Private Functions * @{ */ -static uint32_t SD_InitCard(SD_HandleTypeDef *hsd); -static uint32_t SD_PowerON(SD_HandleTypeDef *hsd); -static uint32_t SD_SendSDStatus(SD_HandleTypeDef *hsd, uint32_t *pSDstatus); -static uint32_t SD_SendStatus(SD_HandleTypeDef *hsd, uint32_t *pCardStatus); -static uint32_t SD_WideBus_Enable(SD_HandleTypeDef *hsd); -static uint32_t SD_WideBus_Disable(SD_HandleTypeDef *hsd); -static uint32_t SD_FindSCR(SD_HandleTypeDef *hsd, uint32_t *pSCR); -static HAL_StatusTypeDef SD_PowerOFF(SD_HandleTypeDef *hsd); -static HAL_StatusTypeDef SD_Write_IT(SD_HandleTypeDef *hsd); -static HAL_StatusTypeDef SD_Read_IT(SD_HandleTypeDef *hsd); -static void SD_DMATransmitCplt(DMA_HandleTypeDef *hdma); -static void SD_DMAReceiveCplt(DMA_HandleTypeDef *hdma); -static void SD_DMAError(DMA_HandleTypeDef *hdma); -static void SD_DMATxAbort(DMA_HandleTypeDef *hdma); -static void SD_DMARxAbort(DMA_HandleTypeDef *hdma); + +static HAL_SD_ErrorTypedef SD_Initialize_Cards(SD_HandleTypeDef *hsd); +static HAL_SD_ErrorTypedef SD_Select_Deselect(SD_HandleTypeDef *hsd, uint64_t Addr); +static HAL_SD_ErrorTypedef SD_PowerON(SD_HandleTypeDef *hsd); +static HAL_SD_ErrorTypedef SD_PowerOFF(SD_HandleTypeDef *hsd); +static HAL_SD_ErrorTypedef SD_SendStatus(SD_HandleTypeDef *hsd, uint32_t *pCardStatus); +static HAL_SD_CardStateTypedef SD_GetState(SD_HandleTypeDef *hsd); +static HAL_SD_ErrorTypedef SD_IsCardProgramming(SD_HandleTypeDef *hsd, uint8_t *pStatus); +static HAL_SD_ErrorTypedef SD_CmdError(SD_HandleTypeDef *hsd); +static HAL_SD_ErrorTypedef SD_CmdResp1Error(SD_HandleTypeDef *hsd, uint8_t SD_CMD); +static HAL_SD_ErrorTypedef SD_CmdResp7Error(SD_HandleTypeDef *hsd); +static HAL_SD_ErrorTypedef SD_CmdResp3Error(SD_HandleTypeDef *hsd); +static HAL_SD_ErrorTypedef SD_CmdResp2Error(SD_HandleTypeDef *hsd); +static HAL_SD_ErrorTypedef SD_CmdResp6Error(SD_HandleTypeDef *hsd, uint8_t SD_CMD, uint16_t *pRCA); +static HAL_SD_ErrorTypedef SD_WideBus_Enable(SD_HandleTypeDef *hsd); +static HAL_SD_ErrorTypedef SD_WideBus_Disable(SD_HandleTypeDef *hsd); +static HAL_SD_ErrorTypedef SD_FindSCR(SD_HandleTypeDef *hsd, uint32_t *pSCR); +static void SD_DMA_RxCplt(DMA_HandleTypeDef *hdma); +static void SD_DMA_RxError(DMA_HandleTypeDef *hdma); +static void SD_DMA_TxCplt(DMA_HandleTypeDef *hdma); +static void SD_DMA_TxError(DMA_HandleTypeDef *hdma); + /** * @} */ - -/* Exported functions --------------------------------------------------------*/ -/** @addtogroup SD_Exported_Functions + +/** @defgroup SD_Exported_Functions SD Exported Functions * @{ */ -/** @addtogroup SD_Exported_Functions_Group1 - * @brief Initialization and de-initialization functions +/** @defgroup SD_Exported_Functions_Group1 Initialization and de-initialization functions + * @brief Initialization and Configuration functions * @verbatim - ============================================================================== - ##### Initialization and de-initialization functions ##### - ============================================================================== + =============================================================================== + ##### Initialization and de-initialization functions ##### + =============================================================================== [..] This section provides functions allowing to initialize/de-initialize the SD card device to be ready for use. - + + @endverbatim * @{ */ /** - * @brief Initializes the SD according to the specified parameters in the + * @brief Initializes the SD card according to the specified parameters in the SD_HandleTypeDef and create the associated handle. - * @param hsd: Pointer to the SD handle - * @retval HAL status + * @param hsd: SD handle + * @param SDCardInfo: HAL_SD_CardInfoTypedef structure for SD card information + * @retval HAL SD error state */ -HAL_StatusTypeDef HAL_SD_Init(SD_HandleTypeDef *hsd) -{ - /* Check the SD handle allocation */ - if(hsd == NULL) - { - return HAL_ERROR; - } - - /* Check the parameters */ - assert_param(IS_SDIO_ALL_INSTANCE(hsd->Instance)); - assert_param(IS_SDIO_CLOCK_EDGE(hsd->Init.ClockEdge)); - assert_param(IS_SDIO_CLOCK_BYPASS(hsd->Init.ClockBypass)); - assert_param(IS_SDIO_CLOCK_POWER_SAVE(hsd->Init.ClockPowerSave)); - assert_param(IS_SDIO_BUS_WIDE(hsd->Init.BusWide)); - assert_param(IS_SDIO_HARDWARE_FLOW_CONTROL(hsd->Init.HardwareFlowControl)); - assert_param(IS_SDIO_CLKDIV(hsd->Init.ClockDiv)); - - if(hsd->State == HAL_SD_STATE_RESET) - { - /* Allocate lock resource and initialize it */ - hsd->Lock = HAL_UNLOCKED; - /* Init the low level hardware : GPIO, CLOCK, CORTEX...etc */ - HAL_SD_MspInit(hsd); - } - - hsd->State = HAL_SD_STATE_BUSY; - - /* Initialize the Card parameters */ - HAL_SD_InitCard(hsd); - - /* Initialize the error code */ - hsd->ErrorCode = HAL_DMA_ERROR_NONE; +HAL_SD_ErrorTypedef HAL_SD_Init(SD_HandleTypeDef *hsd, HAL_SD_CardInfoTypedef *SDCardInfo) +{ + __IO HAL_SD_ErrorTypedef errorstate = SD_OK; + SD_InitTypeDef tmpinit = {0}; - /* Initialize the SD operation */ - hsd->Context = SD_CONTEXT_NONE; - - /* Initialize the SD state */ - hsd->State = HAL_SD_STATE_READY; - - return HAL_OK; -} - -/** - * @brief Initializes the SD Card. - * @param hsd: Pointer to SD handle - * @note This function initializes the SD card. It could be used when a card - re-initialization is needed. - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SD_InitCard(SD_HandleTypeDef *hsd) -{ - uint32_t errorstate = HAL_SD_ERROR_NONE; - SD_InitTypeDef Init; + /* Initialize the low level hardware (MSP) */ + HAL_SD_MspInit(hsd); /* Default SDIO peripheral configuration for SD card initialization */ - Init.ClockEdge = SDIO_CLOCK_EDGE_RISING; - Init.ClockBypass = SDIO_CLOCK_BYPASS_DISABLE; - Init.ClockPowerSave = SDIO_CLOCK_POWER_SAVE_DISABLE; - Init.BusWide = SDIO_BUS_WIDE_1B; - Init.HardwareFlowControl = SDIO_HARDWARE_FLOW_CONTROL_DISABLE; - Init.ClockDiv = SDIO_INIT_CLK_DIV; - + tmpinit.ClockEdge = SDIO_CLOCK_EDGE_RISING; + tmpinit.ClockBypass = SDIO_CLOCK_BYPASS_DISABLE; + tmpinit.ClockPowerSave = SDIO_CLOCK_POWER_SAVE_DISABLE; + tmpinit.BusWide = SDIO_BUS_WIDE_1B; + tmpinit.HardwareFlowControl = SDIO_HARDWARE_FLOW_CONTROL_DISABLE; + tmpinit.ClockDiv = SDIO_INIT_CLK_DIV; + /* Initialize SDIO peripheral interface with default configuration */ - SDIO_Init(hsd->Instance, Init); - - /* Disable SDIO Clock */ - __HAL_SD_DISABLE(hsd); + SDIO_Init(hsd->Instance, tmpinit); - /* Set Power State to ON */ - SDIO_PowerState_ON(hsd->Instance); + /* Identify card operating voltage */ + errorstate = SD_PowerON(hsd); - /* Enable SDIO Clock */ - __HAL_SD_ENABLE(hsd); + if(errorstate != SD_OK) + { + return errorstate; + } - /* Required power up waiting time before starting the SD initialization - sequence */ - HAL_Delay(2U); + /* Initialize the present SDIO card(s) and put them in idle state */ + errorstate = SD_Initialize_Cards(hsd); - /* Identify card operating voltage */ - errorstate = SD_PowerON(hsd); - if(errorstate != HAL_SD_ERROR_NONE) + if (errorstate != SD_OK) { - hsd->State = HAL_SD_STATE_READY; - hsd->ErrorCode |= errorstate; - return HAL_ERROR; + return errorstate; } - - /* Card initialization */ - errorstate = SD_InitCard(hsd); - if(errorstate != HAL_SD_ERROR_NONE) + + /* Read CSD/CID MSD registers */ + errorstate = HAL_SD_Get_CardInfo(hsd, SDCardInfo); + + if (errorstate == SD_OK) { - hsd->State = HAL_SD_STATE_READY; - hsd->ErrorCode |= errorstate; - return HAL_ERROR; + /* Select the Card */ + errorstate = SD_Select_Deselect(hsd, (uint32_t)(((uint32_t)SDCardInfo->RCA) << 16)); } - - return HAL_OK; + + /* Configure SDIO peripheral interface */ + SDIO_Init(hsd->Instance, hsd->Init); + + return errorstate; } /** * @brief De-Initializes the SD card. - * @param hsd: Pointer to SD handle + * @param hsd: SD handle * @retval HAL status */ HAL_StatusTypeDef HAL_SD_DeInit(SD_HandleTypeDef *hsd) { - /* Check the SD handle allocation */ - if(hsd == NULL) - { - return HAL_ERROR; - } - - /* Check the parameters */ - assert_param(IS_SDIO_ALL_INSTANCE(hsd->Instance)); - - hsd->State = HAL_SD_STATE_BUSY; /* Set SD power state to off */ SD_PowerOFF(hsd); @@ -424,23 +407,19 @@ HAL_StatusTypeDef HAL_SD_DeInit(SD_HandleTypeDef *hsd) /* De-Initialize the MSP layer */ HAL_SD_MspDeInit(hsd); - hsd->ErrorCode = HAL_SD_ERROR_NONE; - hsd->State = HAL_SD_STATE_RESET; - return HAL_OK; } /** * @brief Initializes the SD MSP. - * @param hsd: Pointer to SD handle + * @param hsd: SD handle * @retval None */ __weak void HAL_SD_MspInit(SD_HandleTypeDef *hsd) { /* Prevent unused argument(s) compilation warning */ UNUSED(hsd); - /* NOTE : This function Should not be modified, when the callback is needed, the HAL_SD_MspInit could be implemented in the user file */ @@ -448,14 +427,13 @@ __weak void HAL_SD_MspInit(SD_HandleTypeDef *hsd) /** * @brief De-Initialize SD MSP. - * @param hsd: Pointer to SD handle + * @param hsd: SD handle * @retval None */ __weak void HAL_SD_MspDeInit(SD_HandleTypeDef *hsd) { /* Prevent unused argument(s) compilation warning */ UNUSED(hsd); - /* NOTE : This function Should not be modified, when the callback is needed, the HAL_SD_MspDeInit could be implemented in the user file */ @@ -465,13 +443,13 @@ __weak void HAL_SD_MspDeInit(SD_HandleTypeDef *hsd) * @} */ -/** @addtogroup SD_Exported_Functions_Group2 +/** @defgroup SD_Exported_Functions_Group2 IO operation functions * @brief Data transfer functions * @verbatim - ============================================================================== - ##### IO operation functions ##### - ============================================================================== + =============================================================================== + ##### IO operation functions ##### + =============================================================================== [..] This subsection provides a set of functions allowing to manage the data transfer from/to SD card. @@ -482,2433 +460,2989 @@ __weak void HAL_SD_MspDeInit(SD_HandleTypeDef *hsd) /** * @brief Reads block(s) from a specified address in a card. The Data transfer - * is managed by polling mode. - * @note This API should be followed by a check on the card state through - * HAL_SD_GetCardState(). - * @param hsd: Pointer to SD handle - * @param pData: pointer to the buffer that will contain the received data - * @param BlockAdd: Block Address from where data is to be read - * @param NumberOfBlocks: Number of SD blocks to read - * @param Timeout: Specify timeout value - * @retval HAL status + * is managed by polling mode. + * @param hsd: SD handle + * @param pReadBuffer: pointer to the buffer that will contain the received data + * @param ReadAddr: Address from where data is to be read + * @param BlockSize: SD card Data block size (in bytes) + * This parameter should be 512 + * @param NumberOfBlocks: Number of SD blocks to read + * @retval SD Card error state */ -HAL_StatusTypeDef HAL_SD_ReadBlocks(SD_HandleTypeDef *hsd, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks, uint32_t Timeout) +HAL_SD_ErrorTypedef HAL_SD_ReadBlocks(SD_HandleTypeDef *hsd, uint32_t *pReadBuffer, uint64_t ReadAddr, uint32_t BlockSize, uint32_t NumberOfBlocks) { - SDIO_DataInitTypeDef config; - uint32_t errorstate = HAL_SD_ERROR_NONE; - uint32_t tickstart = HAL_GetTick(); - uint32_t count = 0U, *tempbuff = (uint32_t *)pData; + SDIO_CmdInitTypeDef sdio_cmdinitstructure = {0}; + SDIO_DataInitTypeDef sdio_datainitstructure = {0}; + HAL_SD_ErrorTypedef errorstate = SD_OK; + uint32_t count = 0, *tempbuff = (uint32_t *)pReadBuffer; - if(NULL == pData) + /* Initialize data control register */ + hsd->Instance->DCTRL = 0; + + if (hsd->CardType == HIGH_CAPACITY_SD_CARD) { - hsd->ErrorCode |= HAL_SD_ERROR_PARAM; - return HAL_ERROR; + BlockSize = 512; + ReadAddr /= 512; } - - if(hsd->State == HAL_SD_STATE_READY) + + /* Set Block Size for Card */ + sdio_cmdinitstructure.Argument = (uint32_t) BlockSize; + sdio_cmdinitstructure.CmdIndex = SD_CMD_SET_BLOCKLEN; + sdio_cmdinitstructure.Response = SDIO_RESPONSE_SHORT; + sdio_cmdinitstructure.WaitForInterrupt = SDIO_WAIT_NO; + sdio_cmdinitstructure.CPSM = SDIO_CPSM_ENABLE; + SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure); + + /* Check for error conditions */ + errorstate = SD_CmdResp1Error(hsd, SD_CMD_SET_BLOCKLEN); + + if (errorstate != SD_OK) { - hsd->ErrorCode = HAL_DMA_ERROR_NONE; - - if((BlockAdd + NumberOfBlocks) > (hsd->SdCard.LogBlockNbr)) - { - hsd->ErrorCode |= HAL_SD_ERROR_ADDR_OUT_OF_RANGE; - return HAL_ERROR; - } - - hsd->State = HAL_SD_STATE_BUSY; - - /* Initialize data control register */ - hsd->Instance->DCTRL = 0U; + return errorstate; + } + + /* Configure the SD DPSM (Data Path State Machine) */ + sdio_datainitstructure.DataTimeOut = SD_DATATIMEOUT; + sdio_datainitstructure.DataLength = NumberOfBlocks * BlockSize; + sdio_datainitstructure.DataBlockSize = DATA_BLOCK_SIZE; + sdio_datainitstructure.TransferDir = SDIO_TRANSFER_DIR_TO_SDIO; + sdio_datainitstructure.TransferMode = SDIO_TRANSFER_MODE_BLOCK; + sdio_datainitstructure.DPSM = SDIO_DPSM_ENABLE; + SDIO_DataConfig(hsd->Instance, &sdio_datainitstructure); + + if(NumberOfBlocks > 1) + { + /* Send CMD18 READ_MULT_BLOCK with argument data address */ + sdio_cmdinitstructure.CmdIndex = SD_CMD_READ_MULT_BLOCK; + } + else + { + /* Send CMD17 READ_SINGLE_BLOCK */ + sdio_cmdinitstructure.CmdIndex = SD_CMD_READ_SINGLE_BLOCK; + } + + sdio_cmdinitstructure.Argument = (uint32_t)ReadAddr; + SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure); + + /* Read block(s) in polling mode */ + if(NumberOfBlocks > 1) + { + /* Check for error conditions */ + errorstate = SD_CmdResp1Error(hsd, SD_CMD_READ_MULT_BLOCK); - if(hsd->SdCard.CardType != CARD_SDHC_SDXC) + if (errorstate != SD_OK) { - BlockAdd *= 512U; - } - - /* Set Block Size for Card */ - errorstate = SDMMC_CmdBlockLength(hsd->Instance, BLOCKSIZE); - if(errorstate != HAL_SD_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); - hsd->ErrorCode |= errorstate; - hsd->State = HAL_SD_STATE_READY; - return HAL_ERROR; + return errorstate; } - /* Configure the SD DPSM (Data Path State Machine) */ - config.DataTimeOut = SDMMC_DATATIMEOUT; - config.DataLength = NumberOfBlocks * BLOCKSIZE; - config.DataBlockSize = SDIO_DATABLOCK_SIZE_512B; - config.TransferDir = SDIO_TRANSFER_DIR_TO_SDIO; - config.TransferMode = SDIO_TRANSFER_MODE_BLOCK; - config.DPSM = SDIO_DPSM_ENABLE; - SDIO_ConfigData(hsd->Instance, &config); - - /* Read block(s) in polling mode */ - if(NumberOfBlocks > 1U) - { - hsd->Context = SD_CONTEXT_READ_MULTIPLE_BLOCK; - - /* Read Multi Block command */ - errorstate = SDMMC_CmdReadMultiBlock(hsd->Instance, BlockAdd); - } - else - { - hsd->Context = SD_CONTEXT_READ_SINGLE_BLOCK; - - /* Read Single Block command */ - errorstate = SDMMC_CmdReadSingleBlock(hsd->Instance, BlockAdd); - } - if(errorstate != HAL_SD_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); - hsd->ErrorCode |= errorstate; - hsd->State = HAL_SD_STATE_READY; - return HAL_ERROR; - } - /* Poll on SDIO flags */ - while(!__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_RXOVERR | SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DTIMEOUT | SDIO_FLAG_DATAEND | SDIO_STA_STBITERR)) + while(!__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_RXOVERR | SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DTIMEOUT | SDIO_FLAG_DATAEND | SDIO_FLAG_STBITERR)) { - if(__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_RXFIFOHF)) + if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_RXFIFOHF)) { /* Read data from SDIO Rx FIFO */ - for(count = 0U; count < 8U; count++) + for (count = 0; count < 8; count++) { *(tempbuff + count) = SDIO_ReadFIFO(hsd->Instance); } - tempbuff += 8U; - } - - if((Timeout == 0U)||((HAL_GetTick()-tickstart) >= Timeout)) - { - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); - hsd->ErrorCode |= HAL_SD_ERROR_TIMEOUT; - hsd->State= HAL_SD_STATE_READY; - return HAL_TIMEOUT; + + tempbuff += 8; } - } + } + } + else + { + /* Check for error conditions */ + errorstate = SD_CmdResp1Error(hsd, SD_CMD_READ_SINGLE_BLOCK); - /* Send stop transmission command in case of multiblock read */ - if(__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_DATAEND) && (NumberOfBlocks > 1U)) - { - if(hsd->SdCard.CardType != CARD_SECURED) + if (errorstate != SD_OK) + { + return errorstate; + } + + /* In case of single block transfer, no need of stop transfer at all */ + while(!__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_RXOVERR | SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DTIMEOUT | SDIO_FLAG_DBCKEND | SDIO_FLAG_STBITERR)) + { + if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_RXFIFOHF)) { - /* Send stop transmission command */ - errorstate = SDMMC_CmdStopTransfer(hsd->Instance); - if(errorstate != HAL_SD_ERROR_NONE) + /* Read data from SDIO Rx FIFO */ + for (count = 0; count < 8; count++) { - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); - hsd->ErrorCode |= errorstate; - hsd->State = HAL_SD_STATE_READY; - return HAL_ERROR; + *(tempbuff + count) = SDIO_ReadFIFO(hsd->Instance); } + + tempbuff += 8; } } - - /* Get error state */ - if(__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_DTIMEOUT)) - { - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); - hsd->ErrorCode |= HAL_SD_ERROR_DATA_TIMEOUT; - hsd->State = HAL_SD_STATE_READY; - return HAL_ERROR; - } - else if(__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_DCRCFAIL)) - { - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); - hsd->ErrorCode |= HAL_SD_ERROR_DATA_CRC_FAIL; - hsd->State = HAL_SD_STATE_READY; - return HAL_ERROR; - } - else if(__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_RXOVERR)) + } + + /* Send stop transmission command in case of multiblock read */ + if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_DATAEND) && (NumberOfBlocks > 1)) + { + if ((hsd->CardType == STD_CAPACITY_SD_CARD_V1_1) ||\ + (hsd->CardType == STD_CAPACITY_SD_CARD_V2_0) ||\ + (hsd->CardType == HIGH_CAPACITY_SD_CARD)) { - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); - hsd->ErrorCode |= HAL_SD_ERROR_RX_OVERRUN; - hsd->State = HAL_SD_STATE_READY; - return HAL_ERROR; + /* Send stop transmission command */ + errorstate = HAL_SD_StopTransfer(hsd); } + } + + /* Get error state */ + if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_DTIMEOUT)) + { + __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_DTIMEOUT); - /* Empty FIFO if there is still any data */ - while ((__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_RXDAVL))) - { - *tempbuff = SDIO_ReadFIFO(hsd->Instance); - tempbuff++; - - if((Timeout == 0U)||((HAL_GetTick()-tickstart) >= Timeout)) - { - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); - hsd->ErrorCode |= HAL_SD_ERROR_TIMEOUT; - hsd->State= HAL_SD_STATE_READY; - return HAL_ERROR; - } - } + errorstate = SD_DATA_TIMEOUT; - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); + return errorstate; + } + else if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_DCRCFAIL)) + { + __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_DCRCFAIL); + + errorstate = SD_DATA_CRC_FAIL; + + return errorstate; + } + else if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_RXOVERR)) + { + __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_RXOVERR); + + errorstate = SD_RX_OVERRUN; + + return errorstate; + } + else if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_STBITERR)) + { + __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_STBITERR); - hsd->State = HAL_SD_STATE_READY; + errorstate = SD_START_BIT_ERR; - return HAL_OK; + return errorstate; } else { - hsd->ErrorCode |= HAL_SD_ERROR_BUSY; - return HAL_ERROR; + /* No error flag set */ + } + + count = SD_DATATIMEOUT; + + /* Empty FIFO if there is still any data */ + while ((__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_RXDAVL)) && (count > 0)) + { + *tempbuff = SDIO_ReadFIFO(hsd->Instance); + tempbuff++; + count--; } + + /* Clear all the static flags */ + __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); + + return errorstate; } /** * @brief Allows to write block(s) to a specified address in a card. The Data - * transfer is managed by polling mode. - * @note This API should be followed by a check on the card state through - * HAL_SD_GetCardState(). - * @param hsd: Pointer to SD handle - * @param pData: pointer to the buffer that will contain the data to transmit - * @param BlockAdd: Block Address where data will be written - * @param NumberOfBlocks: Number of SD blocks to write - * @param Timeout: Specify timeout value - * @retval HAL status + * transfer is managed by polling mode. + * @param hsd: SD handle + * @param pWriteBuffer: pointer to the buffer that will contain the data to transmit + * @param WriteAddr: Address from where data is to be written + * @param BlockSize: SD card Data block size (in bytes) + * This parameter should be 512. + * @param NumberOfBlocks: Number of SD blocks to write + * @retval SD Card error state */ -HAL_StatusTypeDef HAL_SD_WriteBlocks(SD_HandleTypeDef *hsd, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks, uint32_t Timeout) +HAL_SD_ErrorTypedef HAL_SD_WriteBlocks(SD_HandleTypeDef *hsd, uint32_t *pWriteBuffer, uint64_t WriteAddr, uint32_t BlockSize, uint32_t NumberOfBlocks) { - SDIO_DataInitTypeDef config; - uint32_t errorstate = HAL_SD_ERROR_NONE; - uint32_t tickstart = HAL_GetTick(); - uint32_t count = 0U; - uint32_t *tempbuff = (uint32_t *)pData; + SDIO_CmdInitTypeDef sdio_cmdinitstructure = {0}; + SDIO_DataInitTypeDef sdio_datainitstructure = {0}; + HAL_SD_ErrorTypedef errorstate = SD_OK; + uint32_t totalnumberofbytes = 0, bytestransferred = 0, count = 0, restwords = 0; + uint32_t *tempbuff = (uint32_t *)pWriteBuffer; + uint8_t cardstate = 0; + + /* Initialize data control register */ + hsd->Instance->DCTRL = 0; - if(NULL == pData) + if (hsd->CardType == HIGH_CAPACITY_SD_CARD) { - hsd->ErrorCode |= HAL_SD_ERROR_PARAM; - return HAL_ERROR; + BlockSize = 512; + WriteAddr /= 512; } - - if(hsd->State == HAL_SD_STATE_READY) + + /* Set Block Size for Card */ + sdio_cmdinitstructure.Argument = (uint32_t)BlockSize; + sdio_cmdinitstructure.CmdIndex = SD_CMD_SET_BLOCKLEN; + sdio_cmdinitstructure.Response = SDIO_RESPONSE_SHORT; + sdio_cmdinitstructure.WaitForInterrupt = SDIO_WAIT_NO; + sdio_cmdinitstructure.CPSM = SDIO_CPSM_ENABLE; + SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure); + + /* Check for error conditions */ + errorstate = SD_CmdResp1Error(hsd, SD_CMD_SET_BLOCKLEN); + + if (errorstate != SD_OK) { - hsd->ErrorCode = HAL_DMA_ERROR_NONE; - - if((BlockAdd + NumberOfBlocks) > (hsd->SdCard.LogBlockNbr)) - { - hsd->ErrorCode |= HAL_SD_ERROR_ADDR_OUT_OF_RANGE; - return HAL_ERROR; - } - - hsd->State = HAL_SD_STATE_BUSY; - - /* Initialize data control register */ - hsd->Instance->DCTRL = 0U; - - if(hsd->SdCard.CardType != CARD_SDHC_SDXC) - { - BlockAdd *= 512U; - } - - /* Set Block Size for Card */ - errorstate = SDMMC_CmdBlockLength(hsd->Instance, BLOCKSIZE); - if(errorstate != HAL_SD_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); - hsd->ErrorCode |= errorstate; - hsd->State = HAL_SD_STATE_READY; - return HAL_ERROR; - } - - /* Write Blocks in Polling mode */ - if(NumberOfBlocks > 1U) - { - hsd->Context = SD_CONTEXT_WRITE_MULTIPLE_BLOCK; - - /* Write Multi Block command */ - errorstate = SDMMC_CmdWriteMultiBlock(hsd->Instance, BlockAdd); - } - else - { - hsd->Context = SD_CONTEXT_WRITE_SINGLE_BLOCK; - - /* Write Single Block command */ - errorstate = SDMMC_CmdWriteSingleBlock(hsd->Instance, BlockAdd); - } - if(errorstate != HAL_SD_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); - hsd->ErrorCode |= errorstate; - hsd->State = HAL_SD_STATE_READY; - return HAL_ERROR; - } - - /* Configure the SD DPSM (Data Path State Machine) */ - config.DataTimeOut = SDMMC_DATATIMEOUT; - config.DataLength = NumberOfBlocks * BLOCKSIZE; - config.DataBlockSize = SDIO_DATABLOCK_SIZE_512B; - config.TransferDir = SDIO_TRANSFER_DIR_TO_CARD; - config.TransferMode = SDIO_TRANSFER_MODE_BLOCK; - config.DPSM = SDIO_DPSM_ENABLE; - SDIO_ConfigData(hsd->Instance, &config); - - /* Write block(s) in polling mode */ - while(!__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_TXUNDERR | SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DTIMEOUT | SDIO_FLAG_DATAEND | SDIO_FLAG_STBITERR)) + return errorstate; + } + + if(NumberOfBlocks > 1) + { + /* Send CMD25 WRITE_MULT_BLOCK with argument data address */ + sdio_cmdinitstructure.CmdIndex = SD_CMD_WRITE_MULT_BLOCK; + } + else + { + /* Send CMD24 WRITE_SINGLE_BLOCK */ + sdio_cmdinitstructure.CmdIndex = SD_CMD_WRITE_SINGLE_BLOCK; + } + + sdio_cmdinitstructure.Argument = (uint32_t)WriteAddr; + SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure); + + /* Check for error conditions */ + if(NumberOfBlocks > 1) + { + errorstate = SD_CmdResp1Error(hsd, SD_CMD_WRITE_MULT_BLOCK); + } + else + { + errorstate = SD_CmdResp1Error(hsd, SD_CMD_WRITE_SINGLE_BLOCK); + } + + if (errorstate != SD_OK) + { + return errorstate; + } + + /* Set total number of bytes to write */ + totalnumberofbytes = NumberOfBlocks * BlockSize; + + /* Configure the SD DPSM (Data Path State Machine) */ + sdio_datainitstructure.DataTimeOut = SD_DATATIMEOUT; + sdio_datainitstructure.DataLength = NumberOfBlocks * BlockSize; + sdio_datainitstructure.DataBlockSize = SDIO_DATABLOCK_SIZE_512B; + sdio_datainitstructure.TransferDir = SDIO_TRANSFER_DIR_TO_CARD; + sdio_datainitstructure.TransferMode = SDIO_TRANSFER_MODE_BLOCK; + sdio_datainitstructure.DPSM = SDIO_DPSM_ENABLE; + SDIO_DataConfig(hsd->Instance, &sdio_datainitstructure); + + /* Write block(s) in polling mode */ + if(NumberOfBlocks > 1) + { + while(!__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_TXUNDERR | SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DTIMEOUT | SDIO_FLAG_DATAEND | SDIO_FLAG_STBITERR)) { - if(__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_TXFIFOHE)) + if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_TXFIFOHE)) { - /* Write data to SDIO Tx FIFO */ - for(count = 0U; count < 8U; count++) + if ((totalnumberofbytes - bytestransferred) < 32) { - SDIO_WriteFIFO(hsd->Instance, (tempbuff + count)); + restwords = ((totalnumberofbytes - bytestransferred) % 4 == 0) ? ((totalnumberofbytes - bytestransferred) / 4) : (( totalnumberofbytes - bytestransferred) / 4 + 1); + + /* Write data to SDIO Tx FIFO */ + for (count = 0; count < restwords; count++) + { + SDIO_WriteFIFO(hsd->Instance, tempbuff); + tempbuff++; + bytestransferred += 4; + } + } + else + { + /* Write data to SDIO Tx FIFO */ + for (count = 0; count < 8; count++) + { + SDIO_WriteFIFO(hsd->Instance, (tempbuff + count)); + } + + tempbuff += 8; + bytestransferred += 32; } - tempbuff += 8U; - } - - if((Timeout == 0U)||((HAL_GetTick()-tickstart) >= Timeout)) - { - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); - hsd->ErrorCode |= errorstate; - hsd->State = HAL_SD_STATE_READY; - return HAL_TIMEOUT; } - } - - /* Send stop transmission command in case of multiblock write */ - if(__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_DATAEND) && (NumberOfBlocks > 1U)) - { - if(hsd->SdCard.CardType != CARD_SECURED) + } + } + else + { + /* In case of single data block transfer no need of stop command at all */ + while(!__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_TXUNDERR | SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DTIMEOUT | SDIO_FLAG_DBCKEND | SDIO_FLAG_STBITERR)) + { + if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_TXFIFOHE)) { - /* Send stop transmission command */ - errorstate = SDMMC_CmdStopTransfer(hsd->Instance); - if(errorstate != HAL_SD_ERROR_NONE) + if ((totalnumberofbytes - bytestransferred) < 32) + { + restwords = ((totalnumberofbytes - bytestransferred) % 4 == 0) ? ((totalnumberofbytes - bytestransferred) / 4) : (( totalnumberofbytes - bytestransferred) / 4 + 1); + + /* Write data to SDIO Tx FIFO */ + for (count = 0; count < restwords; count++) + { + SDIO_WriteFIFO(hsd->Instance, tempbuff); + tempbuff++; + bytestransferred += 4; + } + } + else { - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); - hsd->ErrorCode |= errorstate; - hsd->State = HAL_SD_STATE_READY; - return HAL_ERROR; + /* Write data to SDIO Tx FIFO */ + for (count = 0; count < 8; count++) + { + SDIO_WriteFIFO(hsd->Instance, (tempbuff + count)); + } + + tempbuff += 8; + bytestransferred += 32; } } - } - - /* Get error state */ - if(__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_DTIMEOUT)) - { - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); - hsd->ErrorCode |= HAL_SD_ERROR_DATA_TIMEOUT; - hsd->State = HAL_SD_STATE_READY; - return HAL_ERROR; - } - else if(__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_DCRCFAIL)) - { - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); - hsd->ErrorCode |= HAL_SD_ERROR_DATA_CRC_FAIL; - hsd->State = HAL_SD_STATE_READY; - return HAL_ERROR; - } - else if(__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_TXUNDERR)) + } + } + + /* Send stop transmission command in case of multiblock write */ + if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_DATAEND) && (NumberOfBlocks > 1)) + { + if ((hsd->CardType == STD_CAPACITY_SD_CARD_V1_1) || (hsd->CardType == STD_CAPACITY_SD_CARD_V2_0) ||\ + (hsd->CardType == HIGH_CAPACITY_SD_CARD)) { - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); - hsd->ErrorCode |= HAL_SD_ERROR_TX_UNDERRUN; - hsd->State = HAL_SD_STATE_READY; - return HAL_ERROR; + /* Send stop transmission command */ + errorstate = HAL_SD_StopTransfer(hsd); } + } + + /* Get error state */ + if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_DTIMEOUT)) + { + __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_DTIMEOUT); - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); + errorstate = SD_DATA_TIMEOUT; + + return errorstate; + } + else if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_DCRCFAIL)) + { + __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_DCRCFAIL); + + errorstate = SD_DATA_CRC_FAIL; + + return errorstate; + } + else if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_TXUNDERR)) + { + __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_TXUNDERR); - hsd->State = HAL_SD_STATE_READY; + errorstate = SD_TX_UNDERRUN; - return HAL_OK; + return errorstate; + } + else if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_STBITERR)) + { + __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_STBITERR); + + errorstate = SD_START_BIT_ERR; + + return errorstate; } else { - hsd->ErrorCode |= HAL_SD_ERROR_BUSY; - return HAL_ERROR; + /* No error flag set */ } + + /* Clear all the static flags */ + __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); + + /* Wait till the card is in programming state */ + errorstate = SD_IsCardProgramming(hsd, &cardstate); + + while ((errorstate == SD_OK) && ((cardstate == SD_CARD_PROGRAMMING) || (cardstate == SD_CARD_RECEIVING))) + { + errorstate = SD_IsCardProgramming(hsd, &cardstate); + } + + return errorstate; } /** * @brief Reads block(s) from a specified address in a card. The Data transfer - * is managed in interrupt mode. - * @note This API should be followed by a check on the card state through - * HAL_SD_GetCardState(). - * @note You could also check the IT transfer process through the SD Rx - * interrupt event. - * @param hsd: Pointer to SD handle - * @param pData: Pointer to the buffer that will contain the received data - * @param BlockAdd: Block Address from where data is to be read + * is managed by DMA mode. + * @note This API should be followed by the function HAL_SD_CheckReadOperation() + * to check the completion of the read process + * @param hsd: SD handle + * @param pReadBuffer: Pointer to the buffer that will contain the received data + * @param ReadAddr: Address from where data is to be read + * @param BlockSize: SD card Data block size + * @note BlockSize must be 512 bytes. * @param NumberOfBlocks: Number of blocks to read. - * @retval HAL status + * @retval SD Card error state */ -HAL_StatusTypeDef HAL_SD_ReadBlocks_IT(SD_HandleTypeDef *hsd, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks) +HAL_SD_ErrorTypedef HAL_SD_ReadBlocks_DMA(SD_HandleTypeDef *hsd, uint32_t *pReadBuffer, uint64_t ReadAddr, uint32_t BlockSize, uint32_t NumberOfBlocks) { - SDIO_DataInitTypeDef config; - uint32_t errorstate = HAL_SD_ERROR_NONE; + SDIO_CmdInitTypeDef sdio_cmdinitstructure = {0}; + SDIO_DataInitTypeDef sdio_datainitstructure = {0}; + HAL_SD_ErrorTypedef errorstate = SD_OK; + + /* Initialize data control register */ + hsd->Instance->DCTRL = 0; - if(NULL == pData) + /* Initialize handle flags */ + hsd->SdTransferCplt = 0; + hsd->DmaTransferCplt = 0; + hsd->SdTransferErr = SD_OK; + + /* Initialize SD Read operation */ + if(NumberOfBlocks > 1) { - hsd->ErrorCode |= HAL_SD_ERROR_PARAM; - return HAL_ERROR; + hsd->SdOperation = SD_READ_MULTIPLE_BLOCK; } + else + { + hsd->SdOperation = SD_READ_SINGLE_BLOCK; + } + + /* Enable transfer interrupts */ + __HAL_SD_SDIO_ENABLE_IT(hsd, (SDIO_IT_DCRCFAIL |\ + SDIO_IT_DTIMEOUT |\ + SDIO_IT_DATAEND |\ + SDIO_IT_RXOVERR |\ + SDIO_IT_STBITERR)); + + /* Enable SDIO DMA transfer */ + __HAL_SD_SDIO_DMA_ENABLE(hsd); + + /* Configure DMA user callbacks */ + hsd->hdmarx->XferCpltCallback = SD_DMA_RxCplt; + hsd->hdmarx->XferErrorCallback = SD_DMA_RxError; - if(hsd->State == HAL_SD_STATE_READY) + /* Enable the DMA Channel */ + HAL_DMA_Start_IT(hsd->hdmarx, (uint32_t)&hsd->Instance->FIFO, (uint32_t)pReadBuffer, (uint32_t)(BlockSize * NumberOfBlocks)/4); + + if (hsd->CardType == HIGH_CAPACITY_SD_CARD) { - hsd->ErrorCode = HAL_DMA_ERROR_NONE; - - if((BlockAdd + NumberOfBlocks) > (hsd->SdCard.LogBlockNbr)) - { - hsd->ErrorCode |= HAL_SD_ERROR_ADDR_OUT_OF_RANGE; - return HAL_ERROR; - } - - hsd->State = HAL_SD_STATE_BUSY; - - /* Initialize data control register */ - hsd->Instance->DCTRL = 0U; - - hsd->pRxBuffPtr = (uint32_t *)pData; - hsd->RxXferSize = BLOCKSIZE * NumberOfBlocks; - - __HAL_SD_ENABLE_IT(hsd, (SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_RXOVERR | SDIO_IT_DATAEND | SDIO_FLAG_RXFIFOHF | SDIO_IT_STBITERR)); - - if(hsd->SdCard.CardType != CARD_SDHC_SDXC) - { - BlockAdd *= 512U; - } - - /* Configure the SD DPSM (Data Path State Machine) */ - config.DataTimeOut = SDMMC_DATATIMEOUT; - config.DataLength = BLOCKSIZE * NumberOfBlocks; - config.DataBlockSize = SDIO_DATABLOCK_SIZE_512B; - config.TransferDir = SDIO_TRANSFER_DIR_TO_SDIO; - config.TransferMode = SDIO_TRANSFER_MODE_BLOCK; - config.DPSM = SDIO_DPSM_ENABLE; - SDIO_ConfigData(hsd->Instance, &config); - - /* Set Block Size for Card */ - errorstate = SDMMC_CmdBlockLength(hsd->Instance, BLOCKSIZE); - if(errorstate != HAL_SD_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); - hsd->ErrorCode |= errorstate; - hsd->State = HAL_SD_STATE_READY; - return HAL_ERROR; - } - - /* Read Blocks in IT mode */ - if(NumberOfBlocks > 1U) - { - hsd->Context = (SD_CONTEXT_READ_MULTIPLE_BLOCK | SD_CONTEXT_IT); - - /* Read Multi Block command */ - errorstate = SDMMC_CmdReadMultiBlock(hsd->Instance, BlockAdd); - } - else - { - hsd->Context = (SD_CONTEXT_READ_SINGLE_BLOCK | SD_CONTEXT_IT); - - /* Read Single Block command */ - errorstate = SDMMC_CmdReadSingleBlock(hsd->Instance, BlockAdd); - } - if(errorstate != HAL_SD_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); - hsd->ErrorCode |= errorstate; - hsd->State = HAL_SD_STATE_READY; - return HAL_ERROR; - } - - return HAL_OK; + BlockSize = 512; + ReadAddr /= 512; + } + + /* Set Block Size for Card */ + sdio_cmdinitstructure.Argument = (uint32_t)BlockSize; + sdio_cmdinitstructure.CmdIndex = SD_CMD_SET_BLOCKLEN; + sdio_cmdinitstructure.Response = SDIO_RESPONSE_SHORT; + sdio_cmdinitstructure.WaitForInterrupt = SDIO_WAIT_NO; + sdio_cmdinitstructure.CPSM = SDIO_CPSM_ENABLE; + SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure); + + /* Check for error conditions */ + errorstate = SD_CmdResp1Error(hsd, SD_CMD_SET_BLOCKLEN); + + if (errorstate != SD_OK) + { + return errorstate; + } + + /* Configure the SD DPSM (Data Path State Machine) */ + sdio_datainitstructure.DataTimeOut = SD_DATATIMEOUT; + sdio_datainitstructure.DataLength = BlockSize * NumberOfBlocks; + sdio_datainitstructure.DataBlockSize = SDIO_DATABLOCK_SIZE_512B; + sdio_datainitstructure.TransferDir = SDIO_TRANSFER_DIR_TO_SDIO; + sdio_datainitstructure.TransferMode = SDIO_TRANSFER_MODE_BLOCK; + sdio_datainitstructure.DPSM = SDIO_DPSM_ENABLE; + SDIO_DataConfig(hsd->Instance, &sdio_datainitstructure); + + /* Check number of blocks command */ + if(NumberOfBlocks > 1) + { + /* Send CMD18 READ_MULT_BLOCK with argument data address */ + sdio_cmdinitstructure.CmdIndex = SD_CMD_READ_MULT_BLOCK; } else { - return HAL_BUSY; + /* Send CMD17 READ_SINGLE_BLOCK */ + sdio_cmdinitstructure.CmdIndex = SD_CMD_READ_SINGLE_BLOCK; } + + sdio_cmdinitstructure.Argument = (uint32_t)ReadAddr; + SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure); + + /* Check for error conditions */ + if(NumberOfBlocks > 1) + { + errorstate = SD_CmdResp1Error(hsd, SD_CMD_READ_MULT_BLOCK); + } + else + { + errorstate = SD_CmdResp1Error(hsd, SD_CMD_READ_SINGLE_BLOCK); + } + + /* Update the SD transfer error in SD handle */ + hsd->SdTransferErr = errorstate; + + return errorstate; } + /** * @brief Writes block(s) to a specified address in a card. The Data transfer - * is managed in interrupt mode. - * @note This API should be followed by a check on the card state through - * HAL_SD_GetCardState(). - * @note You could also check the IT transfer process through the SD Tx - * interrupt event. - * @param hsd: Pointer to SD handle - * @param pData: Pointer to the buffer that will contain the data to transmit - * @param BlockAdd: Block Address where data will be written + * is managed by DMA mode. + * @note This API should be followed by the function HAL_SD_CheckWriteOperation() + * to check the completion of the write process (by SD current status polling). + * @param hsd: SD handle + * @param pWriteBuffer: pointer to the buffer that will contain the data to transmit + * @param WriteAddr: Address from where data is to be read + * @param BlockSize: the SD card Data block size + * @note BlockSize must be 512 bytes. * @param NumberOfBlocks: Number of blocks to write - * @retval HAL status + * @retval SD Card error state */ -HAL_StatusTypeDef HAL_SD_WriteBlocks_IT(SD_HandleTypeDef *hsd, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks) +HAL_SD_ErrorTypedef HAL_SD_WriteBlocks_DMA(SD_HandleTypeDef *hsd, uint32_t *pWriteBuffer, uint64_t WriteAddr, uint32_t BlockSize, uint32_t NumberOfBlocks) { - SDIO_DataInitTypeDef config; - uint32_t errorstate = HAL_SD_ERROR_NONE; + SDIO_CmdInitTypeDef sdio_cmdinitstructure = {0}; + SDIO_DataInitTypeDef sdio_datainitstructure = {0}; + HAL_SD_ErrorTypedef errorstate = SD_OK; + + /* Initialize data control register */ + hsd->Instance->DCTRL = 0; + + /* Initialize handle flags */ + hsd->SdTransferCplt = 0; + hsd->DmaTransferCplt = 0; + hsd->SdTransferErr = SD_OK; + + /* Initialize SD Write operation */ + if(NumberOfBlocks > 1) + { + hsd->SdOperation = SD_WRITE_MULTIPLE_BLOCK; + } + else + { + hsd->SdOperation = SD_WRITE_SINGLE_BLOCK; + } + + /* Enable transfer interrupts */ + __HAL_SD_SDIO_ENABLE_IT(hsd, (SDIO_IT_DCRCFAIL |\ + SDIO_IT_DTIMEOUT |\ + SDIO_IT_DATAEND |\ + SDIO_IT_TXUNDERR |\ + SDIO_IT_STBITERR)); + + /* Configure DMA user callbacks */ + hsd->hdmatx->XferCpltCallback = SD_DMA_TxCplt; + hsd->hdmatx->XferErrorCallback = SD_DMA_TxError; + + /* Enable the DMA Channel */ + HAL_DMA_Start_IT(hsd->hdmatx, (uint32_t)pWriteBuffer, (uint32_t)&hsd->Instance->FIFO, (uint32_t)(BlockSize * NumberOfBlocks)/4); + + /* Enable SDIO DMA transfer */ + __HAL_SD_SDIO_DMA_ENABLE(hsd); + + if (hsd->CardType == HIGH_CAPACITY_SD_CARD) + { + BlockSize = 512; + WriteAddr /= 512; + } + + /* Set Block Size for Card */ + sdio_cmdinitstructure.Argument = (uint32_t)BlockSize; + sdio_cmdinitstructure.CmdIndex = SD_CMD_SET_BLOCKLEN; + sdio_cmdinitstructure.Response = SDIO_RESPONSE_SHORT; + sdio_cmdinitstructure.WaitForInterrupt = SDIO_WAIT_NO; + sdio_cmdinitstructure.CPSM = SDIO_CPSM_ENABLE; + SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure); + + /* Check for error conditions */ + errorstate = SD_CmdResp1Error(hsd, SD_CMD_SET_BLOCKLEN); + + if (errorstate != SD_OK) + { + return errorstate; + } - if(NULL == pData) + /* Check number of blocks command */ + if(NumberOfBlocks <= 1) + { + /* Send CMD24 WRITE_SINGLE_BLOCK */ + sdio_cmdinitstructure.CmdIndex = SD_CMD_WRITE_SINGLE_BLOCK; + } + else + { + /* Send CMD25 WRITE_MULT_BLOCK with argument data address */ + sdio_cmdinitstructure.CmdIndex = SD_CMD_WRITE_MULT_BLOCK; + } + + sdio_cmdinitstructure.Argument = (uint32_t)WriteAddr; + SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure); + + /* Check for error conditions */ + if(NumberOfBlocks > 1) { - hsd->ErrorCode |= HAL_SD_ERROR_PARAM; - return HAL_ERROR; + errorstate = SD_CmdResp1Error(hsd, SD_CMD_WRITE_MULT_BLOCK); + } + else + { + errorstate = SD_CmdResp1Error(hsd, SD_CMD_WRITE_SINGLE_BLOCK); } - if(hsd->State == HAL_SD_STATE_READY) + if (errorstate != SD_OK) { - hsd->ErrorCode = HAL_DMA_ERROR_NONE; + return errorstate; + } + + /* Configure the SD DPSM (Data Path State Machine) */ + sdio_datainitstructure.DataTimeOut = SD_DATATIMEOUT; + sdio_datainitstructure.DataLength = BlockSize * NumberOfBlocks; + sdio_datainitstructure.DataBlockSize = SDIO_DATABLOCK_SIZE_512B; + sdio_datainitstructure.TransferDir = SDIO_TRANSFER_DIR_TO_CARD; + sdio_datainitstructure.TransferMode = SDIO_TRANSFER_MODE_BLOCK; + sdio_datainitstructure.DPSM = SDIO_DPSM_ENABLE; + SDIO_DataConfig(hsd->Instance, &sdio_datainitstructure); + + hsd->SdTransferErr = errorstate; + + return errorstate; +} + +/** + * @brief This function waits until the SD DMA data read transfer is finished. + * This API should be called after HAL_SD_ReadBlocks_DMA() function + * to insure that all data sent by the card is already transferred by the + * DMA controller. + * @param hsd: SD handle + * @param Timeout: Timeout duration + * @retval SD Card error state + */ +HAL_SD_ErrorTypedef HAL_SD_CheckReadOperation(SD_HandleTypeDef *hsd, uint32_t Timeout) +{ + HAL_SD_ErrorTypedef errorstate = SD_OK; + uint32_t timeout = Timeout; + uint32_t tmp1, tmp2; + HAL_SD_ErrorTypedef tmp3; + + /* Wait for DMA/SD transfer end or SD error variables to be in SD handle */ + tmp1 = hsd->DmaTransferCplt; + tmp2 = hsd->SdTransferCplt; + tmp3 = (HAL_SD_ErrorTypedef)hsd->SdTransferErr; - if((BlockAdd + NumberOfBlocks) > (hsd->SdCard.LogBlockNbr)) - { - hsd->ErrorCode |= HAL_SD_ERROR_ADDR_OUT_OF_RANGE; - return HAL_ERROR; - } + while (((tmp1 & tmp2) == 0) && (tmp3 == SD_OK) && (timeout > 0)) + { + tmp1 = hsd->DmaTransferCplt; + tmp2 = hsd->SdTransferCplt; + tmp3 = (HAL_SD_ErrorTypedef)hsd->SdTransferErr; + timeout--; + } + + timeout = Timeout; + + /* Wait until the Rx transfer is no longer active */ + while((__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_RXACT)) && (timeout > 0)) + { + timeout--; + } + + /* Send stop command in multiblock read */ + if (hsd->SdOperation == SD_READ_MULTIPLE_BLOCK) + { + errorstate = HAL_SD_StopTransfer(hsd); + } + + if ((timeout == 0) && (errorstate == SD_OK)) + { + errorstate = SD_DATA_TIMEOUT; + } + + /* Clear all the static flags */ + __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); + + /* Return error state */ + if (hsd->SdTransferErr != SD_OK) + { + return (HAL_SD_ErrorTypedef)(hsd->SdTransferErr); + } + + return errorstate; +} + +/** + * @brief This function waits until the SD DMA data write transfer is finished. + * This API should be called after HAL_SD_WriteBlocks_DMA() function + * to insure that all data sent by the card is already transferred by the + * DMA controller. + * @param hsd: SD handle + * @param Timeout: Timeout duration + * @retval SD Card error state + */ +HAL_SD_ErrorTypedef HAL_SD_CheckWriteOperation(SD_HandleTypeDef *hsd, uint32_t Timeout) +{ + HAL_SD_ErrorTypedef errorstate = SD_OK; + uint32_t timeout = Timeout; + uint32_t tmp1, tmp2; + HAL_SD_ErrorTypedef tmp3; + + /* Wait for DMA/SD transfer end or SD error variables to be in SD handle */ + tmp1 = hsd->DmaTransferCplt; + tmp2 = hsd->SdTransferCplt; + tmp3 = (HAL_SD_ErrorTypedef)hsd->SdTransferErr; - hsd->State = HAL_SD_STATE_BUSY; + while (((tmp1 & tmp2) == 0) && (tmp3 == SD_OK) && (timeout > 0)) + { + tmp1 = hsd->DmaTransferCplt; + tmp2 = hsd->SdTransferCplt; + tmp3 = (HAL_SD_ErrorTypedef)hsd->SdTransferErr; + timeout--; + } + + timeout = Timeout; + + /* Wait until the Tx transfer is no longer active */ + while((__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_TXACT)) && (timeout > 0)) + { + timeout--; + } + + /* Send stop command in multiblock write */ + if (hsd->SdOperation == SD_WRITE_MULTIPLE_BLOCK) + { + errorstate = HAL_SD_StopTransfer(hsd); + } + + if ((timeout == 0) && (errorstate == SD_OK)) + { + errorstate = SD_DATA_TIMEOUT; + } + + /* Clear all the static flags */ + __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); + + /* Return error state */ + if (hsd->SdTransferErr != SD_OK) + { + return (HAL_SD_ErrorTypedef)(hsd->SdTransferErr); + } + + /* Wait until write is complete */ + while(HAL_SD_GetStatus(hsd) != SD_TRANSFER_OK) + { + } + + return errorstate; +} + +/** + * @brief Erases the specified memory area of the given SD card. + * @param hsd: SD handle + * @param Startaddr: Start byte address + * @param Endaddr: End byte address + * @retval SD Card error state + */ +HAL_SD_ErrorTypedef HAL_SD_Erase(SD_HandleTypeDef *hsd, uint64_t Startaddr, uint64_t Endaddr) +{ + HAL_SD_ErrorTypedef errorstate = SD_OK; + SDIO_CmdInitTypeDef sdio_cmdinitstructure = {0}; + + uint32_t delay = 0; + __IO uint32_t maxdelay = 0; + uint8_t cardstate = 0; + + /* Check if the card command class supports erase command */ + if (((hsd->CSD[1] >> 20) & SD_CCCC_ERASE) == 0) + { + errorstate = SD_REQUEST_NOT_APPLICABLE; - /* Initialize data control register */ - hsd->Instance->DCTRL = 0U; + return errorstate; + } + + /* Get max delay value */ + maxdelay = 120000 / (((hsd->Instance->CLKCR) & 0xFF) + 2); + + if((SDIO_GetResponse(hsd->Instance, SDIO_RESP1) & SD_CARD_LOCKED) == SD_CARD_LOCKED) + { + errorstate = SD_LOCK_UNLOCK_FAILED; - hsd->pTxBuffPtr = (uint32_t *)pData; - hsd->TxXferSize = BLOCKSIZE * NumberOfBlocks; + return errorstate; + } + + /* Get start and end block for high capacity cards */ + if (hsd->CardType == HIGH_CAPACITY_SD_CARD) + { + Startaddr /= 512; + Endaddr /= 512; + } + + /* According to sd-card spec 1.0 ERASE_GROUP_START (CMD32) and erase_group_end(CMD33) */ + if ((hsd->CardType == STD_CAPACITY_SD_CARD_V1_1) || (hsd->CardType == STD_CAPACITY_SD_CARD_V2_0) ||\ + (hsd->CardType == HIGH_CAPACITY_SD_CARD)) + { + /* Send CMD32 SD_ERASE_GRP_START with argument as addr */ + sdio_cmdinitstructure.Argument =(uint32_t)Startaddr; + sdio_cmdinitstructure.CmdIndex = SD_CMD_SD_ERASE_GRP_START; + sdio_cmdinitstructure.Response = SDIO_RESPONSE_SHORT; + sdio_cmdinitstructure.WaitForInterrupt = SDIO_WAIT_NO; + sdio_cmdinitstructure.CPSM = SDIO_CPSM_ENABLE; + SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure); - /* Enable transfer interrupts */ - __HAL_SD_ENABLE_IT(hsd, (SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_TXUNDERR | SDIO_IT_DATAEND | SDIO_FLAG_TXFIFOHE | SDIO_IT_STBITERR)); + /* Check for error conditions */ + errorstate = SD_CmdResp1Error(hsd, SD_CMD_SD_ERASE_GRP_START); - if(hsd->SdCard.CardType != CARD_SDHC_SDXC) + if (errorstate != SD_OK) { - BlockAdd *= 512U; + return errorstate; } - /* Set Block Size for Card */ - errorstate = SDMMC_CmdBlockLength(hsd->Instance, BLOCKSIZE); - if(errorstate != HAL_SD_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); - hsd->ErrorCode |= errorstate; - hsd->State = HAL_SD_STATE_READY; - return HAL_ERROR; - } + /* Send CMD33 SD_ERASE_GRP_END with argument as addr */ + sdio_cmdinitstructure.Argument = (uint32_t)Endaddr; + sdio_cmdinitstructure.CmdIndex = SD_CMD_SD_ERASE_GRP_END; + SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure); - /* Write Blocks in Polling mode */ - if(NumberOfBlocks > 1U) + /* Check for error conditions */ + errorstate = SD_CmdResp1Error(hsd, SD_CMD_SD_ERASE_GRP_END); + + if (errorstate != SD_OK) { - hsd->Context = (SD_CONTEXT_WRITE_MULTIPLE_BLOCK| SD_CONTEXT_IT); - - /* Write Multi Block command */ - errorstate = SDMMC_CmdWriteMultiBlock(hsd->Instance, BlockAdd); + return errorstate; } - else - { - hsd->Context = (SD_CONTEXT_WRITE_SINGLE_BLOCK | SD_CONTEXT_IT); + } + + /* Send CMD38 ERASE */ + sdio_cmdinitstructure.Argument = 0; + sdio_cmdinitstructure.CmdIndex = SD_CMD_ERASE; + SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure); + + /* Check for error conditions */ + errorstate = SD_CmdResp1Error(hsd, SD_CMD_ERASE); + + if (errorstate != SD_OK) + { + return errorstate; + } + + for (; delay < maxdelay; delay++) + { + } + + /* Wait untill the card is in programming state */ + errorstate = SD_IsCardProgramming(hsd, &cardstate); + + delay = SD_DATATIMEOUT; + + while ((delay > 0) && (errorstate == SD_OK) && ((cardstate == SD_CARD_PROGRAMMING) || (cardstate == SD_CARD_RECEIVING))) + { + errorstate = SD_IsCardProgramming(hsd, &cardstate); + delay--; + } + + return errorstate; +} + +/** + * @brief This function handles SD card interrupt request. + * @param hsd: SD handle + * @retval None + */ +void HAL_SD_IRQHandler(SD_HandleTypeDef *hsd) +{ + /* Check for SDIO interrupt flags */ + if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_IT_DATAEND)) + { + __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_IT_DATAEND); - /* Write Single Block command */ - errorstate = SDMMC_CmdWriteSingleBlock(hsd->Instance, BlockAdd); - } - if(errorstate != HAL_SD_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); - hsd->ErrorCode |= errorstate; - hsd->State = HAL_SD_STATE_READY; - return HAL_ERROR; - } + /* SD transfer is complete */ + hsd->SdTransferCplt = 1; + + /* No transfer error */ + hsd->SdTransferErr = SD_OK; + + HAL_SD_XferCpltCallback(hsd); + } + else if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_IT_DCRCFAIL)) + { + __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_DCRCFAIL); + + hsd->SdTransferErr = SD_DATA_CRC_FAIL; + + HAL_SD_XferErrorCallback(hsd); + + } + else if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_IT_DTIMEOUT)) + { + __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_DTIMEOUT); - /* Configure the SD DPSM (Data Path State Machine) */ - config.DataTimeOut = SDMMC_DATATIMEOUT; - config.DataLength = BLOCKSIZE * NumberOfBlocks; - config.DataBlockSize = SDIO_DATABLOCK_SIZE_512B; - config.TransferDir = SDIO_TRANSFER_DIR_TO_CARD; - config.TransferMode = SDIO_TRANSFER_MODE_BLOCK; - config.DPSM = SDIO_DPSM_ENABLE; - SDIO_ConfigData(hsd->Instance, &config); + hsd->SdTransferErr = SD_DATA_TIMEOUT; - return HAL_OK; + HAL_SD_XferErrorCallback(hsd); + } + else if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_IT_RXOVERR)) + { + __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_RXOVERR); + + hsd->SdTransferErr = SD_RX_OVERRUN; + + HAL_SD_XferErrorCallback(hsd); + } + else if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_IT_TXUNDERR)) + { + __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_TXUNDERR); + + hsd->SdTransferErr = SD_TX_UNDERRUN; + + HAL_SD_XferErrorCallback(hsd); + } + else if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_IT_STBITERR)) + { + __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_STBITERR); + + hsd->SdTransferErr = SD_START_BIT_ERR; + + HAL_SD_XferErrorCallback(hsd); } else { - return HAL_BUSY; + /* No error flag set */ } + + /* Disable all SDIO peripheral interrupt sources */ + __HAL_SD_SDIO_DISABLE_IT(hsd, SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_DATAEND |\ + SDIO_IT_TXFIFOHE | SDIO_IT_RXFIFOHF | SDIO_IT_TXUNDERR |\ + SDIO_IT_RXOVERR | SDIO_IT_STBITERR); } + /** - * @brief Reads block(s) from a specified address in a card. The Data transfer - * is managed by DMA mode. - * @note This API should be followed by a check on the card state through - * HAL_SD_GetCardState(). - * @note You could also check the DMA transfer process through the SD Rx - * interrupt event. - * @param hsd: Pointer SD handle - * @param pData: Pointer to the buffer that will contain the received data - * @param BlockAdd: Block Address from where data is to be read - * @param NumberOfBlocks: Number of blocks to read. - * @retval HAL status + * @brief SD end of transfer callback. + * @param hsd: SD handle + * @retval None + */ +__weak void HAL_SD_XferCpltCallback(SD_HandleTypeDef *hsd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsd); + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_SD_XferCpltCallback could be implemented in the user file + */ +} + +/** + * @brief SD Transfer Error callback. + * @param hsd: SD handle + * @retval None + */ +__weak void HAL_SD_XferErrorCallback(SD_HandleTypeDef *hsd) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsd); + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_SD_XferErrorCallback could be implemented in the user file + */ +} + +/** + * @brief SD Transfer complete Rx callback in non blocking mode. + * @param hdma: pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +__weak void HAL_SD_DMA_RxCpltCallback(DMA_HandleTypeDef *hdma) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hdma); + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_SD_DMA_RxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief SD DMA transfer complete Rx error callback. + * @param hdma: pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +__weak void HAL_SD_DMA_RxErrorCallback(DMA_HandleTypeDef *hdma) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hdma); + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_SD_DMA_RxErrorCallback could be implemented in the user file + */ +} + +/** + * @brief SD Transfer complete Tx callback in non blocking mode. + * @param hdma: pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None */ -HAL_StatusTypeDef HAL_SD_ReadBlocks_DMA(SD_HandleTypeDef *hsd, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks) +__weak void HAL_SD_DMA_TxCpltCallback(DMA_HandleTypeDef *hdma) { - SDIO_DataInitTypeDef config; - uint32_t errorstate = HAL_SD_ERROR_NONE; + /* Prevent unused argument(s) compilation warning */ + UNUSED(hdma); + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_SD_DMA_TxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief SD DMA transfer complete error Tx callback. + * @param hdma: pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +__weak void HAL_SD_DMA_TxErrorCallback(DMA_HandleTypeDef *hdma) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hdma); + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_SD_DMA_TxErrorCallback could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup SD_Exported_Functions_Group3 Peripheral Control functions + * @brief management functions + * +@verbatim + ============================================================================== + ##### Peripheral Control functions ##### + ============================================================================== + [..] + This subsection provides a set of functions allowing to control the SD card + operations. + +@endverbatim + * @{ + */ + +/** + * @brief Returns information about specific card. + * @param hsd: SD handle + * @param pCardInfo: Pointer to a HAL_SD_CardInfoTypedef structure that + * contains all SD cardinformation + * @retval SD Card error state + */ +HAL_SD_ErrorTypedef HAL_SD_Get_CardInfo(SD_HandleTypeDef *hsd, HAL_SD_CardInfoTypedef *pCardInfo) +{ + HAL_SD_ErrorTypedef errorstate = SD_OK; + uint32_t tmp = 0; - if(NULL == pData) - { - hsd->ErrorCode |= HAL_SD_ERROR_PARAM; - return HAL_ERROR; - } + pCardInfo->CardType = (uint8_t)(hsd->CardType); + pCardInfo->RCA = (uint16_t)(hsd->RCA); + + /* Byte 0 */ + tmp = (hsd->CSD[0] & 0xFF000000) >> 24; + pCardInfo->SD_csd.CSDStruct = (uint8_t)((tmp & 0xC0) >> 6); + pCardInfo->SD_csd.SysSpecVersion = (uint8_t)((tmp & 0x3C) >> 2); + pCardInfo->SD_csd.Reserved1 = tmp & 0x03; + + /* Byte 1 */ + tmp = (hsd->CSD[0] & 0x00FF0000) >> 16; + pCardInfo->SD_csd.TAAC = (uint8_t)tmp; + + /* Byte 2 */ + tmp = (hsd->CSD[0] & 0x0000FF00) >> 8; + pCardInfo->SD_csd.NSAC = (uint8_t)tmp; + + /* Byte 3 */ + tmp = hsd->CSD[0] & 0x000000FF; + pCardInfo->SD_csd.MaxBusClkFrec = (uint8_t)tmp; + + /* Byte 4 */ + tmp = (hsd->CSD[1] & 0xFF000000) >> 24; + pCardInfo->SD_csd.CardComdClasses = (uint16_t)(tmp << 4); + + /* Byte 5 */ + tmp = (hsd->CSD[1] & 0x00FF0000) >> 16; + pCardInfo->SD_csd.CardComdClasses |= (uint16_t)((tmp & 0xF0) >> 4); + pCardInfo->SD_csd.RdBlockLen = (uint8_t)(tmp & 0x0F); + + /* Byte 6 */ + tmp = (hsd->CSD[1] & 0x0000FF00) >> 8; + pCardInfo->SD_csd.PartBlockRead = (uint8_t)((tmp & 0x80) >> 7); + pCardInfo->SD_csd.WrBlockMisalign = (uint8_t)((tmp & 0x40) >> 6); + pCardInfo->SD_csd.RdBlockMisalign = (uint8_t)((tmp & 0x20) >> 5); + pCardInfo->SD_csd.DSRImpl = (uint8_t)((tmp & 0x10) >> 4); + pCardInfo->SD_csd.Reserved2 = 0; /*!< Reserved */ - if(hsd->State == HAL_SD_STATE_READY) + if ((hsd->CardType == STD_CAPACITY_SD_CARD_V1_1) || (hsd->CardType == STD_CAPACITY_SD_CARD_V2_0)) { - hsd->ErrorCode = HAL_DMA_ERROR_NONE; + pCardInfo->SD_csd.DeviceSize = (tmp & 0x03) << 10; - if((BlockAdd + NumberOfBlocks) > (hsd->SdCard.LogBlockNbr)) - { - hsd->ErrorCode |= HAL_SD_ERROR_ADDR_OUT_OF_RANGE; - return HAL_ERROR; - } + /* Byte 7 */ + tmp = (uint8_t)(hsd->CSD[1] & 0x000000FF); + pCardInfo->SD_csd.DeviceSize |= (tmp) << 2; - hsd->State = HAL_SD_STATE_BUSY; + /* Byte 8 */ + tmp = (uint8_t)((hsd->CSD[2] & 0xFF000000) >> 24); + pCardInfo->SD_csd.DeviceSize |= (tmp & 0xC0) >> 6; - /* Initialize data control register */ - hsd->Instance->DCTRL = 0U; + pCardInfo->SD_csd.MaxRdCurrentVDDMin = (tmp & 0x38) >> 3; + pCardInfo->SD_csd.MaxRdCurrentVDDMax = (tmp & 0x07); - __HAL_SD_ENABLE_IT(hsd, (SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_RXOVERR | SDIO_IT_DATAEND | SDIO_IT_STBITERR)); + /* Byte 9 */ + tmp = (uint8_t)((hsd->CSD[2] & 0x00FF0000) >> 16); + pCardInfo->SD_csd.MaxWrCurrentVDDMin = (tmp & 0xE0) >> 5; + pCardInfo->SD_csd.MaxWrCurrentVDDMax = (tmp & 0x1C) >> 2; + pCardInfo->SD_csd.DeviceSizeMul = (tmp & 0x03) << 1; + /* Byte 10 */ + tmp = (uint8_t)((hsd->CSD[2] & 0x0000FF00) >> 8); + pCardInfo->SD_csd.DeviceSizeMul |= (tmp & 0x80) >> 7; - /* Set the DMA transfer complete callback */ - hsd->hdmarx->XferCpltCallback = SD_DMAReceiveCplt; + pCardInfo->CardCapacity = (pCardInfo->SD_csd.DeviceSize + 1) ; + pCardInfo->CardCapacity *= (1 << (pCardInfo->SD_csd.DeviceSizeMul + 2)); + pCardInfo->CardBlockSize = 1 << (pCardInfo->SD_csd.RdBlockLen); + pCardInfo->CardCapacity *= pCardInfo->CardBlockSize; + } + else if (hsd->CardType == HIGH_CAPACITY_SD_CARD) + { + /* Byte 7 */ + tmp = (uint8_t)(hsd->CSD[1] & 0x000000FF); + pCardInfo->SD_csd.DeviceSize = (tmp & 0x3F) << 16; - /* Set the DMA error callback */ - hsd->hdmarx->XferErrorCallback = SD_DMAError; + /* Byte 8 */ + tmp = (uint8_t)((hsd->CSD[2] & 0xFF000000) >> 24); - /* Set the DMA Abort callback */ - hsd->hdmarx->XferAbortCallback = NULL; + pCardInfo->SD_csd.DeviceSize |= (tmp << 8); - /* Enable the DMA Channel */ - HAL_DMA_Start_IT(hsd->hdmarx, (uint32_t)&hsd->Instance->FIFO, (uint32_t)pData, (uint32_t)(BLOCKSIZE * NumberOfBlocks)/4); + /* Byte 9 */ + tmp = (uint8_t)((hsd->CSD[2] & 0x00FF0000) >> 16); - /* Enable SD DMA transfer */ - __HAL_SD_DMA_ENABLE(hsd); + pCardInfo->SD_csd.DeviceSize |= (tmp); - if(hsd->SdCard.CardType != CARD_SDHC_SDXC) + /* Byte 10 */ + tmp = (uint8_t)((hsd->CSD[2] & 0x0000FF00) >> 8); + + pCardInfo->CardCapacity = (uint64_t)(((uint64_t)pCardInfo->SD_csd.DeviceSize + 1) * 512 * 1024); + pCardInfo->CardBlockSize = 512; + } + else + { + /* Not supported card type */ + errorstate = SD_ERROR; + } + + pCardInfo->SD_csd.EraseGrSize = (tmp & 0x40) >> 6; + pCardInfo->SD_csd.EraseGrMul = (tmp & 0x3F) << 1; + + /* Byte 11 */ + tmp = (uint8_t)(hsd->CSD[2] & 0x000000FF); + pCardInfo->SD_csd.EraseGrMul |= (tmp & 0x80) >> 7; + pCardInfo->SD_csd.WrProtectGrSize = (tmp & 0x7F); + + /* Byte 12 */ + tmp = (uint8_t)((hsd->CSD[3] & 0xFF000000) >> 24); + pCardInfo->SD_csd.WrProtectGrEnable = (tmp & 0x80) >> 7; + pCardInfo->SD_csd.ManDeflECC = (tmp & 0x60) >> 5; + pCardInfo->SD_csd.WrSpeedFact = (tmp & 0x1C) >> 2; + pCardInfo->SD_csd.MaxWrBlockLen = (tmp & 0x03) << 2; + + /* Byte 13 */ + tmp = (uint8_t)((hsd->CSD[3] & 0x00FF0000) >> 16); + pCardInfo->SD_csd.MaxWrBlockLen |= (tmp & 0xC0) >> 6; + pCardInfo->SD_csd.WriteBlockPaPartial = (tmp & 0x20) >> 5; + pCardInfo->SD_csd.Reserved3 = 0; + pCardInfo->SD_csd.ContentProtectAppli = (tmp & 0x01); + + /* Byte 14 */ + tmp = (uint8_t)((hsd->CSD[3] & 0x0000FF00) >> 8); + pCardInfo->SD_csd.FileFormatGrouop = (tmp & 0x80) >> 7; + pCardInfo->SD_csd.CopyFlag = (tmp & 0x40) >> 6; + pCardInfo->SD_csd.PermWrProtect = (tmp & 0x20) >> 5; + pCardInfo->SD_csd.TempWrProtect = (tmp & 0x10) >> 4; + pCardInfo->SD_csd.FileFormat = (tmp & 0x0C) >> 2; + pCardInfo->SD_csd.ECC = (tmp & 0x03); + + /* Byte 15 */ + tmp = (uint8_t)(hsd->CSD[3] & 0x000000FF); + pCardInfo->SD_csd.CSD_CRC = (tmp & 0xFE) >> 1; + pCardInfo->SD_csd.Reserved4 = 1; + + /* Byte 0 */ + tmp = (uint8_t)((hsd->CID[0] & 0xFF000000) >> 24); + pCardInfo->SD_cid.ManufacturerID = tmp; + + /* Byte 1 */ + tmp = (uint8_t)((hsd->CID[0] & 0x00FF0000) >> 16); + pCardInfo->SD_cid.OEM_AppliID = tmp << 8; + + /* Byte 2 */ + tmp = (uint8_t)((hsd->CID[0] & 0x000000FF00) >> 8); + pCardInfo->SD_cid.OEM_AppliID |= tmp; + + /* Byte 3 */ + tmp = (uint8_t)(hsd->CID[0] & 0x000000FF); + pCardInfo->SD_cid.ProdName1 = tmp << 24; + + /* Byte 4 */ + tmp = (uint8_t)((hsd->CID[1] & 0xFF000000) >> 24); + pCardInfo->SD_cid.ProdName1 |= tmp << 16; + + /* Byte 5 */ + tmp = (uint8_t)((hsd->CID[1] & 0x00FF0000) >> 16); + pCardInfo->SD_cid.ProdName1 |= tmp << 8; + + /* Byte 6 */ + tmp = (uint8_t)((hsd->CID[1] & 0x0000FF00) >> 8); + pCardInfo->SD_cid.ProdName1 |= tmp; + + /* Byte 7 */ + tmp = (uint8_t)(hsd->CID[1] & 0x000000FF); + pCardInfo->SD_cid.ProdName2 = tmp; + + /* Byte 8 */ + tmp = (uint8_t)((hsd->CID[2] & 0xFF000000) >> 24); + pCardInfo->SD_cid.ProdRev = tmp; + + /* Byte 9 */ + tmp = (uint8_t)((hsd->CID[2] & 0x00FF0000) >> 16); + pCardInfo->SD_cid.ProdSN = tmp << 24; + + /* Byte 10 */ + tmp = (uint8_t)((hsd->CID[2] & 0x0000FF00) >> 8); + pCardInfo->SD_cid.ProdSN |= tmp << 16; + + /* Byte 11 */ + tmp = (uint8_t)(hsd->CID[2] & 0x000000FF); + pCardInfo->SD_cid.ProdSN |= tmp << 8; + + /* Byte 12 */ + tmp = (uint8_t)((hsd->CID[3] & 0xFF000000) >> 24); + pCardInfo->SD_cid.ProdSN |= tmp; + + /* Byte 13 */ + tmp = (uint8_t)((hsd->CID[3] & 0x00FF0000) >> 16); + pCardInfo->SD_cid.Reserved1 |= (tmp & 0xF0) >> 4; + pCardInfo->SD_cid.ManufactDate = (tmp & 0x0F) << 8; + + /* Byte 14 */ + tmp = (uint8_t)((hsd->CID[3] & 0x0000FF00) >> 8); + pCardInfo->SD_cid.ManufactDate |= tmp; + + /* Byte 15 */ + tmp = (uint8_t)(hsd->CID[3] & 0x000000FF); + pCardInfo->SD_cid.CID_CRC = (tmp & 0xFE) >> 1; + pCardInfo->SD_cid.Reserved2 = 1; + + return errorstate; +} + +/** + * @brief Enables wide bus operation for the requested card if supported by + * card. + * @param hsd: SD handle + * @param WideMode: Specifies the SD card wide bus mode + * This parameter can be one of the following values: + * @arg SDIO_BUS_WIDE_8B: 8-bit data transfer (Only for MMC) + * @arg SDIO_BUS_WIDE_4B: 4-bit data transfer + * @arg SDIO_BUS_WIDE_1B: 1-bit data transfer + * @retval SD Card error state + */ +HAL_SD_ErrorTypedef HAL_SD_WideBusOperation_Config(SD_HandleTypeDef *hsd, uint32_t WideMode) +{ + HAL_SD_ErrorTypedef errorstate = SD_OK; + SDIO_InitTypeDef init = {0}; + + /* MMC Card does not support this feature */ + if (hsd->CardType == MULTIMEDIA_CARD) + { + errorstate = SD_UNSUPPORTED_FEATURE; + } + else if ((hsd->CardType == STD_CAPACITY_SD_CARD_V1_1) || (hsd->CardType == STD_CAPACITY_SD_CARD_V2_0) ||\ + (hsd->CardType == HIGH_CAPACITY_SD_CARD)) + { + if (WideMode == SDIO_BUS_WIDE_8B) { - BlockAdd *= 512U; + errorstate = SD_UNSUPPORTED_FEATURE; } - - /* Configure the SD DPSM (Data Path State Machine) */ - config.DataTimeOut = SDMMC_DATATIMEOUT; - config.DataLength = BLOCKSIZE * NumberOfBlocks; - config.DataBlockSize = SDIO_DATABLOCK_SIZE_512B; - config.TransferDir = SDIO_TRANSFER_DIR_TO_SDIO; - config.TransferMode = SDIO_TRANSFER_MODE_BLOCK; - config.DPSM = SDIO_DPSM_ENABLE; - SDIO_ConfigData(hsd->Instance, &config); - - /* Set Block Size for Card */ - errorstate = SDMMC_CmdBlockLength(hsd->Instance, BLOCKSIZE); - if(errorstate != HAL_SD_ERROR_NONE) + else if (WideMode == SDIO_BUS_WIDE_4B) { - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); - hsd->ErrorCode |= errorstate; - hsd->State = HAL_SD_STATE_READY; - return HAL_ERROR; + errorstate = SD_WideBus_Enable(hsd); } - - /* Read Blocks in DMA mode */ - if(NumberOfBlocks > 1U) + else if (WideMode == SDIO_BUS_WIDE_1B) { - hsd->Context = (SD_CONTEXT_READ_MULTIPLE_BLOCK | SD_CONTEXT_DMA); - - /* Read Multi Block command */ - errorstate = SDMMC_CmdReadMultiBlock(hsd->Instance, BlockAdd); + errorstate = SD_WideBus_Disable(hsd); } else { - hsd->Context = (SD_CONTEXT_READ_SINGLE_BLOCK | SD_CONTEXT_DMA); + /* WideMode is not a valid argument*/ + errorstate = SD_INVALID_PARAMETER; + } - /* Read Single Block command */ - errorstate = SDMMC_CmdReadSingleBlock(hsd->Instance, BlockAdd); + if (errorstate == SD_OK) + { + /* Configure the SDIO peripheral */ + init.ClockEdge = hsd->Init.ClockEdge; + init.ClockBypass = hsd->Init.ClockBypass; + init.ClockPowerSave = hsd->Init.ClockPowerSave; + init.BusWide = WideMode; + init.HardwareFlowControl = hsd->Init.HardwareFlowControl; + init.ClockDiv = hsd->Init.ClockDiv; + + /* Configure SDIO peripheral interface */ + SDIO_Init(hsd->Instance, init); } - if(errorstate != HAL_SD_ERROR_NONE) + else { - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); - hsd->ErrorCode |= errorstate; - hsd->State = HAL_SD_STATE_READY; - return HAL_ERROR; + /* An error occured while enabling/disabling the wide bus*/ } - - return HAL_OK; } else { - return HAL_BUSY; + /* Not supported card type */ + errorstate = SD_ERROR; } + + return errorstate; } /** - * @brief Writes block(s) to a specified address in a card. The Data transfer - * is managed by DMA mode. - * @note This API should be followed by a check on the card state through - * HAL_SD_GetCardState(). - * @note You could also check the DMA transfer process through the SD Tx - * interrupt event. - * @param hsd: Pointer to SD handle - * @param pData: Pointer to the buffer that will contain the data to transmit - * @param BlockAdd: Block Address where data will be written - * @param NumberOfBlocks: Number of blocks to write - * @retval HAL status + * @brief Aborts an ongoing data transfer. + * @param hsd: SD handle + * @retval SD Card error state + */ +HAL_SD_ErrorTypedef HAL_SD_StopTransfer(SD_HandleTypeDef *hsd) +{ + SDIO_CmdInitTypeDef sdio_cmdinitstructure = {0}; + HAL_SD_ErrorTypedef errorstate = SD_OK; + + /* Send CMD12 STOP_TRANSMISSION */ + sdio_cmdinitstructure.Argument = 0; + sdio_cmdinitstructure.CmdIndex = SD_CMD_STOP_TRANSMISSION; + sdio_cmdinitstructure.Response = SDIO_RESPONSE_SHORT; + sdio_cmdinitstructure.WaitForInterrupt = SDIO_WAIT_NO; + sdio_cmdinitstructure.CPSM = SDIO_CPSM_ENABLE; + SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure); + + /* Check for error conditions */ + errorstate = SD_CmdResp1Error(hsd, SD_CMD_STOP_TRANSMISSION); + + return errorstate; +} + +/** + * @brief Switches the SD card to High Speed mode. + * This API must be used after "Transfer State" + * @note This operation should be followed by the configuration + * of PLL to have SDIOCK clock between 67 and 75 MHz + * @param hsd: SD handle + * @retval SD Card error state */ -HAL_StatusTypeDef HAL_SD_WriteBlocks_DMA(SD_HandleTypeDef *hsd, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks) +HAL_SD_ErrorTypedef HAL_SD_HighSpeed (SD_HandleTypeDef *hsd) { - SDIO_DataInitTypeDef config; - uint32_t errorstate = HAL_SD_ERROR_NONE; + HAL_SD_ErrorTypedef errorstate = SD_OK; + SDIO_CmdInitTypeDef sdio_cmdinitstructure = {0}; + SDIO_DataInitTypeDef sdio_datainitstructure = {0}; + + uint8_t SD_hs[64] = {0}; + uint32_t SD_scr[2] = {0, 0}; + uint32_t SD_SPEC = 0 ; + uint32_t count = 0, *tempbuff = (uint32_t *)SD_hs; + + /* Initialize the Data control register */ + hsd->Instance->DCTRL = 0; + + /* Get SCR Register */ + errorstate = SD_FindSCR(hsd, SD_scr); - if(NULL == pData) + if (errorstate != SD_OK) { - hsd->ErrorCode |= HAL_SD_ERROR_PARAM; - return HAL_ERROR; + return errorstate; } - if(hsd->State == HAL_SD_STATE_READY) + /* Test the Version supported by the card*/ + SD_SPEC = (SD_scr[1] & 0x01000000) | (SD_scr[1] & 0x02000000); + + if (SD_SPEC != SD_ALLZERO) { - hsd->ErrorCode = HAL_DMA_ERROR_NONE; + /* Set Block Size for Card */ + sdio_cmdinitstructure.Argument = (uint32_t)64; + sdio_cmdinitstructure.CmdIndex = SD_CMD_SET_BLOCKLEN; + sdio_cmdinitstructure.Response = SDIO_RESPONSE_SHORT; + sdio_cmdinitstructure.WaitForInterrupt = SDIO_WAIT_NO; + sdio_cmdinitstructure.CPSM = SDIO_CPSM_ENABLE; + SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure); + + /* Check for error conditions */ + errorstate = SD_CmdResp1Error(hsd, SD_CMD_SET_BLOCKLEN); - if((BlockAdd + NumberOfBlocks) > (hsd->SdCard.LogBlockNbr)) + if (errorstate != SD_OK) { - hsd->ErrorCode |= HAL_SD_ERROR_ADDR_OUT_OF_RANGE; - return HAL_ERROR; + return errorstate; } - hsd->State = HAL_SD_STATE_BUSY; - - /* Initialize data control register */ - hsd->Instance->DCTRL = 0U; - - /* Enable SD Error interrupts */ - __HAL_SD_ENABLE_IT(hsd, (SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_TXUNDERR | SDIO_IT_STBITERR)); - - /* Set the DMA transfer complete callback */ - hsd->hdmatx->XferCpltCallback = SD_DMATransmitCplt; + /* Configure the SD DPSM (Data Path State Machine) */ + sdio_datainitstructure.DataTimeOut = SD_DATATIMEOUT; + sdio_datainitstructure.DataLength = 64; + sdio_datainitstructure.DataBlockSize = SDIO_DATABLOCK_SIZE_64B ; + sdio_datainitstructure.TransferDir = SDIO_TRANSFER_DIR_TO_SDIO; + sdio_datainitstructure.TransferMode = SDIO_TRANSFER_MODE_BLOCK; + sdio_datainitstructure.DPSM = SDIO_DPSM_ENABLE; + SDIO_DataConfig(hsd->Instance, &sdio_datainitstructure); - /* Set the DMA error callback */ - hsd->hdmatx->XferErrorCallback = SD_DMAError; + /* Send CMD6 switch mode */ + sdio_cmdinitstructure.Argument = 0x80FFFF01; + sdio_cmdinitstructure.CmdIndex = SD_CMD_HS_SWITCH; + SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure); - /* Set the DMA Abort callback */ - hsd->hdmatx->XferAbortCallback = NULL; + /* Check for error conditions */ + errorstate = SD_CmdResp1Error(hsd, SD_CMD_HS_SWITCH); - if(hsd->SdCard.CardType != CARD_SDHC_SDXC) + if (errorstate != SD_OK) { - BlockAdd *= 512U; + return errorstate; } - - /* Set Block Size for Card */ - errorstate = SDMMC_CmdBlockLength(hsd->Instance, BLOCKSIZE); - if(errorstate != HAL_SD_ERROR_NONE) + + while(!__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_RXOVERR | SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DTIMEOUT | SDIO_FLAG_DBCKEND | SDIO_FLAG_STBITERR)) { - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); - hsd->ErrorCode |= errorstate; - hsd->State = HAL_SD_STATE_READY; - return HAL_ERROR; + if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_RXFIFOHF)) + { + for (count = 0; count < 8; count++) + { + *(tempbuff + count) = SDIO_ReadFIFO(hsd->Instance); + } + + tempbuff += 8; + } } - /* Write Blocks in Polling mode */ - if(NumberOfBlocks > 1U) + if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_DTIMEOUT)) { - hsd->Context = (SD_CONTEXT_WRITE_MULTIPLE_BLOCK | SD_CONTEXT_DMA); + __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_DTIMEOUT); - /* Write Multi Block command */ - errorstate = SDMMC_CmdWriteMultiBlock(hsd->Instance, BlockAdd); - } - else - { - hsd->Context = (SD_CONTEXT_WRITE_SINGLE_BLOCK | SD_CONTEXT_DMA); + errorstate = SD_DATA_TIMEOUT; - /* Write Single Block command */ - errorstate = SDMMC_CmdWriteSingleBlock(hsd->Instance, BlockAdd); + return errorstate; } - if(errorstate != HAL_SD_ERROR_NONE) + else if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_DCRCFAIL)) { - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); - hsd->ErrorCode |= errorstate; - hsd->State = HAL_SD_STATE_READY; - return HAL_ERROR; + __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_DCRCFAIL); + + errorstate = SD_DATA_CRC_FAIL; + + return errorstate; } - - /* Enable SDIO DMA transfer */ - __HAL_SD_DMA_ENABLE(hsd); - - /* Enable the DMA Channel */ - HAL_DMA_Start_IT(hsd->hdmatx, (uint32_t)pData, (uint32_t)&hsd->Instance->FIFO, (uint32_t)(BLOCKSIZE * NumberOfBlocks)/4); - - /* Configure the SD DPSM (Data Path State Machine) */ - config.DataTimeOut = SDMMC_DATATIMEOUT; - config.DataLength = BLOCKSIZE * NumberOfBlocks; - config.DataBlockSize = SDIO_DATABLOCK_SIZE_512B; - config.TransferDir = SDIO_TRANSFER_DIR_TO_CARD; - config.TransferMode = SDIO_TRANSFER_MODE_BLOCK; - config.DPSM = SDIO_DPSM_ENABLE; - SDIO_ConfigData(hsd->Instance, &config); - - return HAL_OK; - } - else - { - return HAL_BUSY; - } -} - -/** - * @brief Erases the specified memory area of the given SD card. - * @note This API should be followed by a check on the card state through - * HAL_SD_GetCardState(). - * @param hsd: Pointer to SD handle - * @param BlockStartAdd: Start Block address - * @param BlockEndAdd: End Block address - * @retval HAL status - */ -HAL_StatusTypeDef HAL_SD_Erase(SD_HandleTypeDef *hsd, uint32_t BlockStartAdd, uint32_t BlockEndAdd) -{ - uint32_t errorstate = HAL_SD_ERROR_NONE; - - if(hsd->State == HAL_SD_STATE_READY) - { - hsd->ErrorCode = HAL_DMA_ERROR_NONE; - - if(BlockEndAdd < BlockStartAdd) + else if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_RXOVERR)) { - hsd->ErrorCode |= HAL_SD_ERROR_PARAM; - return HAL_ERROR; + __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_RXOVERR); + + errorstate = SD_RX_OVERRUN; + + return errorstate; } - - if(BlockEndAdd > (hsd->SdCard.LogBlockNbr)) + else if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_STBITERR)) { - hsd->ErrorCode |= HAL_SD_ERROR_ADDR_OUT_OF_RANGE; - return HAL_ERROR; + __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_STBITERR); + + errorstate = SD_START_BIT_ERR; + + return errorstate; } - - hsd->State = HAL_SD_STATE_BUSY; - - /* Check if the card command class supports erase command */ - if(((hsd->SdCard.Class) & SDIO_CCCC_ERASE) == 0U) + else { - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); - hsd->ErrorCode |= HAL_SD_ERROR_REQUEST_NOT_APPLICABLE; - hsd->State = HAL_SD_STATE_READY; - return HAL_ERROR; + /* No error flag set */ } - if((SDIO_GetResponse(hsd->Instance, SDIO_RESP1) & SDMMC_CARD_LOCKED) == SDMMC_CARD_LOCKED) - { - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); - hsd->ErrorCode |= HAL_SD_ERROR_LOCK_UNLOCK_FAILED; - hsd->State = HAL_SD_STATE_READY; - return HAL_ERROR; - } + count = SD_DATATIMEOUT; - /* Get start and end block for high capacity cards */ - if(hsd->SdCard.CardType != CARD_SDHC_SDXC) + while ((__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_RXDAVL)) && (count > 0)) { - BlockStartAdd *= 512U; - BlockEndAdd *= 512U; + *tempbuff = SDIO_ReadFIFO(hsd->Instance); + tempbuff++; + count--; } - /* According to sd-card spec 1.0 ERASE_GROUP_START (CMD32) and erase_group_end(CMD33) */ - if(hsd->SdCard.CardType != CARD_SECURED) - { - /* Send CMD32 SD_ERASE_GRP_START with argument as addr */ - errorstate = SDMMC_CmdSDEraseStartAdd(hsd->Instance, BlockStartAdd); - if(errorstate != HAL_SD_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); - hsd->ErrorCode |= errorstate; - hsd->State = HAL_SD_STATE_READY; - return HAL_ERROR; - } - - /* Send CMD33 SD_ERASE_GRP_END with argument as addr */ - errorstate = SDMMC_CmdSDEraseEndAdd(hsd->Instance, BlockEndAdd); - if(errorstate != HAL_SD_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); - hsd->ErrorCode |= errorstate; - hsd->State = HAL_SD_STATE_READY; - return HAL_ERROR; - } - } + /* Clear all the static flags */ + __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); - /* Send CMD38 ERASE */ - errorstate = SDMMC_CmdErase(hsd->Instance); - if(errorstate != HAL_SD_ERROR_NONE) + /* Test if the switch mode HS is ok */ + if ((SD_hs[13]& 2) != 2) { - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); - hsd->ErrorCode |= errorstate; - hsd->State = HAL_SD_STATE_READY; - return HAL_ERROR; - } - - hsd->State = HAL_SD_STATE_READY; - - return HAL_OK; - } - else - { - return HAL_BUSY; + errorstate = SD_UNSUPPORTED_FEATURE; + } } + + return errorstate; } /** - * @brief This function handles SD card interrupt request. - * @param hsd: Pointer to SD handle - * @retval None + * @} */ -void HAL_SD_IRQHandler(SD_HandleTypeDef *hsd) + +/** @defgroup SD_Exported_Functions_Group4 Peripheral State functions + * @brief Peripheral State functions + * +@verbatim + ============================================================================== + ##### Peripheral State functions ##### + ============================================================================== + [..] + This subsection permits to get in runtime the status of the peripheral + and the data flow. + +@endverbatim + * @{ + */ + +/** + * @brief Returns the current SD card's status. + * @param hsd: SD handle + * @param pSDstatus: Pointer to the buffer that will contain the SD card status + * SD Status register) + * @retval SD Card error state + */ +HAL_SD_ErrorTypedef HAL_SD_SendSDStatus(SD_HandleTypeDef *hsd, uint32_t *pSDstatus) { - uint32_t errorstate = HAL_SD_ERROR_NONE; + SDIO_CmdInitTypeDef sdio_cmdinitstructure = {0}; + SDIO_DataInitTypeDef sdio_datainitstructure = {0}; + HAL_SD_ErrorTypedef errorstate = SD_OK; + uint32_t count = 0; - /* Check for SDIO interrupt flags */ - if(__HAL_SD_GET_FLAG(hsd, SDIO_IT_DATAEND) != RESET) + /* Check SD response */ + if ((SDIO_GetResponse(hsd->Instance, SDIO_RESP1) & SD_CARD_LOCKED) == SD_CARD_LOCKED) { - __HAL_SD_CLEAR_FLAG(hsd, SDIO_FLAG_DATAEND); + errorstate = SD_LOCK_UNLOCK_FAILED; - __HAL_SD_DISABLE_IT(hsd, SDIO_IT_DATAEND | SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT|\ - SDIO_IT_TXUNDERR| SDIO_IT_RXOVERR | SDIO_IT_STBITERR); - - if((hsd->Context & SD_CONTEXT_IT) != RESET) + return errorstate; + } + + /* Set block size for card if it is not equal to current block size for card */ + sdio_cmdinitstructure.Argument = 64; + sdio_cmdinitstructure.CmdIndex = SD_CMD_SET_BLOCKLEN; + sdio_cmdinitstructure.Response = SDIO_RESPONSE_SHORT; + sdio_cmdinitstructure.WaitForInterrupt = SDIO_WAIT_NO; + sdio_cmdinitstructure.CPSM = SDIO_CPSM_ENABLE; + SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure); + + /* Check for error conditions */ + errorstate = SD_CmdResp1Error(hsd, SD_CMD_SET_BLOCKLEN); + + if (errorstate != SD_OK) + { + return errorstate; + } + + /* Send CMD55 */ + sdio_cmdinitstructure.Argument = (uint32_t)(hsd->RCA << 16); + sdio_cmdinitstructure.CmdIndex = SD_CMD_APP_CMD; + SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure); + + /* Check for error conditions */ + errorstate = SD_CmdResp1Error(hsd, SD_CMD_APP_CMD); + + if (errorstate != SD_OK) + { + return errorstate; + } + + /* Configure the SD DPSM (Data Path State Machine) */ + sdio_datainitstructure.DataTimeOut = SD_DATATIMEOUT; + sdio_datainitstructure.DataLength = 64; + sdio_datainitstructure.DataBlockSize = SDIO_DATABLOCK_SIZE_64B; + sdio_datainitstructure.TransferDir = SDIO_TRANSFER_DIR_TO_SDIO; + sdio_datainitstructure.TransferMode = SDIO_TRANSFER_MODE_BLOCK; + sdio_datainitstructure.DPSM = SDIO_DPSM_ENABLE; + SDIO_DataConfig(hsd->Instance, &sdio_datainitstructure); + + /* Send ACMD13 (SD_APP_STAUS) with argument as card's RCA */ + sdio_cmdinitstructure.Argument = 0; + sdio_cmdinitstructure.CmdIndex = SD_CMD_SD_APP_STATUS; + SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure); + + /* Check for error conditions */ + errorstate = SD_CmdResp1Error(hsd, SD_CMD_SD_APP_STATUS); + + if (errorstate != SD_OK) + { + return errorstate; + } + + /* Get status data */ + while(!__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_RXOVERR | SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DTIMEOUT | SDIO_FLAG_DBCKEND | SDIO_FLAG_STBITERR)) + { + if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_RXFIFOHF)) { - if(((hsd->Context & SD_CONTEXT_READ_MULTIPLE_BLOCK) != RESET) || ((hsd->Context & SD_CONTEXT_WRITE_MULTIPLE_BLOCK) != RESET)) + for (count = 0; count < 8; count++) { - errorstate = SDMMC_CmdStopTransfer(hsd->Instance); - if(errorstate != HAL_SD_ERROR_NONE) - { - hsd->ErrorCode |= errorstate; - HAL_SD_ErrorCallback(hsd); - } + *(pSDstatus + count) = SDIO_ReadFIFO(hsd->Instance); } - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); - - hsd->State = HAL_SD_STATE_READY; - if(((hsd->Context & SD_CONTEXT_READ_SINGLE_BLOCK) != RESET) || ((hsd->Context & SD_CONTEXT_READ_MULTIPLE_BLOCK) != RESET)) - { - HAL_SD_RxCpltCallback(hsd); - } - else - { - HAL_SD_TxCpltCallback(hsd); - } - } - else if((hsd->Context & SD_CONTEXT_DMA) != RESET) - { - if((hsd->Context & SD_CONTEXT_WRITE_MULTIPLE_BLOCK) != RESET) - { - errorstate = SDMMC_CmdStopTransfer(hsd->Instance); - if(errorstate != HAL_SD_ERROR_NONE) - { - hsd->ErrorCode |= errorstate; - HAL_SD_ErrorCallback(hsd); - } - } - if(((hsd->Context & SD_CONTEXT_READ_SINGLE_BLOCK) == RESET) && ((hsd->Context & SD_CONTEXT_READ_MULTIPLE_BLOCK) == RESET)) - { - /* Disable the DMA transfer for transmit request by setting the DMAEN bit - in the SD DCTRL register */ - hsd->Instance->DCTRL &= (uint32_t)~((uint32_t)SDIO_DCTRL_DMAEN); - - hsd->State = HAL_SD_STATE_READY; - - HAL_SD_TxCpltCallback(hsd); - } + pSDstatus += 8; } } - else if(__HAL_SD_GET_FLAG(hsd, SDIO_IT_TXFIFOHE) != RESET) + if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_DTIMEOUT)) { - __HAL_SD_CLEAR_FLAG(hsd, SDIO_FLAG_TXFIFOHE); + __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_DTIMEOUT); + + errorstate = SD_DATA_TIMEOUT; - SD_Write_IT(hsd); + return errorstate; } - - else if(__HAL_SD_GET_FLAG(hsd, SDIO_IT_RXFIFOHF) != RESET) + else if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_DCRCFAIL)) { - __HAL_SD_CLEAR_FLAG(hsd, SDIO_FLAG_RXFIFOHF); + __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_DCRCFAIL); - SD_Read_IT(hsd); + errorstate = SD_DATA_CRC_FAIL; + + return errorstate; } - - else if(__HAL_SD_GET_FLAG(hsd, SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT | SDIO_IT_RXOVERR | SDIO_IT_TXUNDERR | SDIO_IT_STBITERR) != RESET) + else if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_RXOVERR)) { - /* Set Error code */ - if(__HAL_SD_GET_FLAG(hsd, SDIO_IT_DCRCFAIL) != RESET) - { - hsd->ErrorCode |= HAL_SD_ERROR_DATA_CRC_FAIL; - } - if(__HAL_SD_GET_FLAG(hsd, SDIO_IT_DTIMEOUT) != RESET) - { - hsd->ErrorCode |= HAL_SD_ERROR_DATA_TIMEOUT; - } - if(__HAL_SD_GET_FLAG(hsd, SDIO_IT_RXOVERR) != RESET) - { - hsd->ErrorCode |= HAL_SD_ERROR_RX_OVERRUN; - } - if(__HAL_SD_GET_FLAG(hsd, SDIO_IT_TXUNDERR) != RESET) - { - hsd->ErrorCode |= HAL_SD_ERROR_TX_UNDERRUN; - } - if(__HAL_SD_GET_FLAG(hsd, SDIO_IT_STBITERR) != RESET) - { - hsd->ErrorCode |= HAL_SD_ERROR_DATA_TIMEOUT; - } - - /* Clear All flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS | SDIO_FLAG_STBITERR); + __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_RXOVERR); - /* Disable all interrupts */ - __HAL_SD_DISABLE_IT(hsd, SDIO_IT_DATAEND | SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT|\ - SDIO_IT_TXUNDERR| SDIO_IT_RXOVERR |SDIO_IT_STBITERR); + errorstate = SD_RX_OVERRUN; - if((hsd->Context & SD_CONTEXT_DMA) != RESET) - { - /* Abort the SD DMA Streams */ - if(hsd->hdmatx != NULL) - { - /* Set the DMA Tx abort callback */ - hsd->hdmatx->XferAbortCallback = SD_DMATxAbort; - /* Abort DMA in IT mode */ - if(HAL_DMA_Abort_IT(hsd->hdmatx) != HAL_OK) - { - SD_DMATxAbort(hsd->hdmatx); - } - } - else if(hsd->hdmarx != NULL) - { - /* Set the DMA Rx abort callback */ - hsd->hdmarx->XferAbortCallback = SD_DMARxAbort; - /* Abort DMA in IT mode */ - if(HAL_DMA_Abort_IT(hsd->hdmarx) != HAL_OK) - { - SD_DMARxAbort(hsd->hdmarx); - } - } - else - { - hsd->ErrorCode = HAL_SD_ERROR_NONE; - hsd->State = HAL_SD_STATE_READY; - HAL_SD_AbortCallback(hsd); - } - } - else if((hsd->Context & SD_CONTEXT_IT) != RESET) - { - /* Set the SD state to ready to be able to start again the process */ - hsd->State = HAL_SD_STATE_READY; - HAL_SD_ErrorCallback(hsd); - } + return errorstate; } + else if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_STBITERR)) + { + __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_STBITERR); + + errorstate = SD_START_BIT_ERR; + + return errorstate; + } + else + { + /* No error flag set */ + } + + count = SD_DATATIMEOUT; + while ((__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_RXDAVL)) && (count > 0)) + { + *pSDstatus = SDIO_ReadFIFO(hsd->Instance); + pSDstatus++; + count--; + } + + /* Clear all the static status flags*/ + __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); + + return errorstate; } /** - * @brief return the SD state - * @param hsd: Pointer to sd handle - * @retval HAL state - */ -HAL_SD_StateTypeDef HAL_SD_GetState(SD_HandleTypeDef *hsd) -{ - return hsd->State; -} - -/** -* @brief Return the SD error code -* @param hsd : Pointer to a SD_HandleTypeDef structure that contains - * the configuration information. -* @retval SD Error Code -*/ -uint32_t HAL_SD_GetError(SD_HandleTypeDef *hsd) -{ - return hsd->ErrorCode; -} - -/** - * @brief Tx Transfer completed callbacks - * @param hsd: Pointer to SD handle - * @retval None - */ - __weak void HAL_SD_TxCpltCallback(SD_HandleTypeDef *hsd) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hsd); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_SD_TxCpltCallback can be implemented in the user file - */ -} - -/** - * @brief Rx Transfer completed callbacks - * @param hsd: Pointer SD handle - * @retval None - */ -__weak void HAL_SD_RxCpltCallback(SD_HandleTypeDef *hsd) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hsd); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_SD_RxCpltCallback can be implemented in the user file - */ -} - -/** - * @brief SD error callbacks - * @param hsd: Pointer SD handle - * @retval None - */ -__weak void HAL_SD_ErrorCallback(SD_HandleTypeDef *hsd) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hsd); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_SD_ErrorCallback can be implemented in the user file - */ -} - -/** - * @brief SD Abort callbacks - * @param hsd: Pointer SD handle - * @retval None + * @brief Gets the current sd card data status. + * @param hsd: SD handle + * @retval Data Transfer state */ -__weak void HAL_SD_AbortCallback(SD_HandleTypeDef *hsd) +HAL_SD_TransferStateTypedef HAL_SD_GetStatus(SD_HandleTypeDef *hsd) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(hsd); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_SD_ErrorCallback can be implemented in the user file - */ -} - - -/** - * @} - */ + HAL_SD_CardStateTypedef cardstate = SD_CARD_TRANSFER; -/** @addtogroup SD_Exported_Functions_Group3 - * @brief management functions - * -@verbatim - ============================================================================== - ##### Peripheral Control functions ##### - ============================================================================== - [..] - This subsection provides a set of functions allowing to control the SD card - operations and get the related information - -@endverbatim - * @{ - */ + /* Get SD card state */ + cardstate = SD_GetState(hsd); + + /* Find SD status according to card state*/ + if (cardstate == SD_CARD_TRANSFER) + { + return SD_TRANSFER_OK; + } + else if(cardstate == SD_CARD_ERROR) + { + return SD_TRANSFER_ERROR; + } + else + { + return SD_TRANSFER_BUSY; + } +} /** - * @brief Returns information the information of the card which are stored on - * the CID register. - * @param hsd: Pointer to SD handle - * @param pCID: Pointer to a HAL_SD_CIDTypeDef structure that - * contains all CID register parameters - * @retval HAL status + * @brief Gets the SD card status. + * @param hsd: SD handle + * @param pCardStatus: Pointer to the HAL_SD_CardStatusTypedef structure that + * will contain the SD card status information + * @retval SD Card error state */ -HAL_StatusTypeDef HAL_SD_GetCardCID(SD_HandleTypeDef *hsd, HAL_SD_CardCIDTypeDef *pCID) +HAL_SD_ErrorTypedef HAL_SD_GetCardStatus(SD_HandleTypeDef *hsd, HAL_SD_CardStatusTypedef *pCardStatus) { - uint32_t tmp = 0U; + HAL_SD_ErrorTypedef errorstate = SD_OK; + uint32_t tmp = 0; + uint32_t sd_status[16]; + + errorstate = HAL_SD_SendSDStatus(hsd, sd_status); + + if (errorstate != SD_OK) + { + return errorstate; + } /* Byte 0 */ - tmp = (uint8_t)((hsd->CID[0U] & 0xFF000000U) >> 24U); - pCID->ManufacturerID = tmp; + tmp = (sd_status[0] & 0xC0) >> 6; + pCardStatus->DAT_BUS_WIDTH = (uint8_t)tmp; - /* Byte 1 */ - tmp = (uint8_t)((hsd->CID[0U] & 0x00FF0000U) >> 16U); - pCID->OEM_AppliID = tmp << 8U; + /* Byte 0 */ + tmp = (sd_status[0] & 0x20) >> 5; + pCardStatus->SECURED_MODE = (uint8_t)tmp; /* Byte 2 */ - tmp = (uint8_t)((hsd->CID[0U] & 0x000000FF00U) >> 8U); - pCID->OEM_AppliID |= tmp; + tmp = (sd_status[2] & 0xFF); + pCardStatus->SD_CARD_TYPE = (uint8_t)(tmp << 8); /* Byte 3 */ - tmp = (uint8_t)(hsd->CID[0U] & 0x000000FFU); - pCID->ProdName1 = tmp << 24U; + tmp = (sd_status[3] & 0xFF); + pCardStatus->SD_CARD_TYPE |= (uint8_t)tmp; /* Byte 4 */ - tmp = (uint8_t)((hsd->CID[1U] & 0xFF000000U) >> 24U); - pCID->ProdName1 |= tmp << 16; + tmp = (sd_status[4] & 0xFF); + pCardStatus->SIZE_OF_PROTECTED_AREA = (uint8_t)(tmp << 24); /* Byte 5 */ - tmp = (uint8_t)((hsd->CID[1U] & 0x00FF0000U) >> 16U); - pCID->ProdName1 |= tmp << 8U; + tmp = (sd_status[5] & 0xFF); + pCardStatus->SIZE_OF_PROTECTED_AREA |= (uint8_t)(tmp << 16); /* Byte 6 */ - tmp = (uint8_t)((hsd->CID[1U] & 0x0000FF00U) >> 8U); - pCID->ProdName1 |= tmp; + tmp = (sd_status[6] & 0xFF); + pCardStatus->SIZE_OF_PROTECTED_AREA |= (uint8_t)(tmp << 8); /* Byte 7 */ - tmp = (uint8_t)(hsd->CID[1U] & 0x000000FFU); - pCID->ProdName2 = tmp; + tmp = (sd_status[7] & 0xFF); + pCardStatus->SIZE_OF_PROTECTED_AREA |= (uint8_t)tmp; /* Byte 8 */ - tmp = (uint8_t)((hsd->CID[2U] & 0xFF000000U) >> 24U); - pCID->ProdRev = tmp; + tmp = (sd_status[8] & 0xFF); + pCardStatus->SPEED_CLASS = (uint8_t)tmp; /* Byte 9 */ - tmp = (uint8_t)((hsd->CID[2U] & 0x00FF0000U) >> 16U); - pCID->ProdSN = tmp << 24U; + tmp = (sd_status[9] & 0xFF); + pCardStatus->PERFORMANCE_MOVE = (uint8_t)tmp; /* Byte 10 */ - tmp = (uint8_t)((hsd->CID[2U] & 0x0000FF00U) >> 8U); - pCID->ProdSN |= tmp << 16U; + tmp = (sd_status[10] & 0xF0) >> 4; + pCardStatus->AU_SIZE = (uint8_t)tmp; /* Byte 11 */ - tmp = (uint8_t)(hsd->CID[2U] & 0x000000FFU); - pCID->ProdSN |= tmp << 8U; + tmp = (sd_status[11] & 0xFF); + pCardStatus->ERASE_SIZE = (uint8_t)(tmp << 8); /* Byte 12 */ - tmp = (uint8_t)((hsd->CID[3U] & 0xFF000000U) >> 24U); - pCID->ProdSN |= tmp; + tmp = (sd_status[12] & 0xFF); + pCardStatus->ERASE_SIZE |= (uint8_t)tmp; /* Byte 13 */ - tmp = (uint8_t)((hsd->CID[3U] & 0x00FF0000U) >> 16U); - pCID->Reserved1 |= (tmp & 0xF0U) >> 4U; - pCID->ManufactDate = (tmp & 0x0FU) << 8U; + tmp = (sd_status[13] & 0xFC) >> 2; + pCardStatus->ERASE_TIMEOUT = (uint8_t)tmp; - /* Byte 14 */ - tmp = (uint8_t)((hsd->CID[3U] & 0x0000FF00U) >> 8U); - pCID->ManufactDate |= tmp; + /* Byte 13 */ + tmp = (sd_status[13] & 0x3); + pCardStatus->ERASE_OFFSET = (uint8_t)tmp; - /* Byte 15 */ - tmp = (uint8_t)(hsd->CID[3U] & 0x000000FFU); - pCID->CID_CRC = (tmp & 0xFEU) >> 1U; - pCID->Reserved2 = 1U; - - return HAL_OK; + return errorstate; } + +/** + * @} + */ + +/** + * @} + */ + +/** @addtogroup SD_Private_Functions + * @{ + */ /** - * @brief Returns information the information of the card which are stored on - * the CSD register. - * @param hsd: Pointer to SD handle - * @param pCSD: Pointer to a HAL_SD_CardCSDTypeDef structure that - * contains all CSD register parameters - * @retval HAL status + * @brief SD DMA transfer complete Rx callback. + * @param hdma: pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None */ -HAL_StatusTypeDef HAL_SD_GetCardCSD(SD_HandleTypeDef *hsd, HAL_SD_CardCSDTypeDef *pCSD) +static void SD_DMA_RxCplt(DMA_HandleTypeDef *hdma) { - uint32_t tmp = 0U; - - /* Byte 0 */ - tmp = (hsd->CSD[0U] & 0xFF000000U) >> 24U; - pCSD->CSDStruct = (uint8_t)((tmp & 0xC0U) >> 6U); - pCSD->SysSpecVersion = (uint8_t)((tmp & 0x3CU) >> 2U); - pCSD->Reserved1 = tmp & 0x03U; + SD_HandleTypeDef *hsd = (SD_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent; - /* Byte 1 */ - tmp = (hsd->CSD[0U] & 0x00FF0000U) >> 16U; - pCSD->TAAC = (uint8_t)tmp; + /* DMA transfer is complete */ + hsd->DmaTransferCplt = 1; - /* Byte 2 */ - tmp = (hsd->CSD[0U] & 0x0000FF00U) >> 8U; - pCSD->NSAC = (uint8_t)tmp; + /* Wait until SD transfer is complete */ + while(hsd->SdTransferCplt == 0) + { + } - /* Byte 3 */ - tmp = hsd->CSD[0U] & 0x000000FFU; - pCSD->MaxBusClkFrec = (uint8_t)tmp; + /* Transfer complete user callback */ + HAL_SD_DMA_RxCpltCallback(hsd->hdmarx); +} + +/** + * @brief SD DMA transfer Error Rx callback. + * @param hdma: pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void SD_DMA_RxError(DMA_HandleTypeDef *hdma) +{ + SD_HandleTypeDef *hsd = (SD_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent; - /* Byte 4 */ - tmp = (hsd->CSD[1U] & 0xFF000000U) >> 24U; - pCSD->CardComdClasses = (uint16_t)(tmp << 4U); + /* Transfer complete user callback */ + HAL_SD_DMA_RxErrorCallback(hsd->hdmarx); +} + +/** + * @brief SD DMA transfer complete Tx callback. + * @param hdma: pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void SD_DMA_TxCplt(DMA_HandleTypeDef *hdma) +{ + SD_HandleTypeDef *hsd = (SD_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent; - /* Byte 5 */ - tmp = (hsd->CSD[1U] & 0x00FF0000U) >> 16U; - pCSD->CardComdClasses |= (uint16_t)((tmp & 0xF0U) >> 4U); - pCSD->RdBlockLen = (uint8_t)(tmp & 0x0FU); + /* DMA transfer is complete */ + hsd->DmaTransferCplt = 1; - /* Byte 6 */ - tmp = (hsd->CSD[1U] & 0x0000FF00U) >> 8U; - pCSD->PartBlockRead = (uint8_t)((tmp & 0x80U) >> 7U); - pCSD->WrBlockMisalign = (uint8_t)((tmp & 0x40U) >> 6U); - pCSD->RdBlockMisalign = (uint8_t)((tmp & 0x20U) >> 5U); - pCSD->DSRImpl = (uint8_t)((tmp & 0x10U) >> 4U); - pCSD->Reserved2 = 0U; /*!< Reserved */ - - if(hsd->SdCard.CardType == CARD_SDSC) + /* Wait until SD transfer is complete */ + while(hsd->SdTransferCplt == 0) { - pCSD->DeviceSize = (tmp & 0x03U) << 10U; - - /* Byte 7 */ - tmp = (uint8_t)(hsd->CSD[1U] & 0x000000FFU); - pCSD->DeviceSize |= (tmp) << 2U; - - /* Byte 8 */ - tmp = (uint8_t)((hsd->CSD[2U] & 0xFF000000U) >> 24U); - pCSD->DeviceSize |= (tmp & 0xC0U) >> 6U; - - pCSD->MaxRdCurrentVDDMin = (tmp & 0x38U) >> 3U; - pCSD->MaxRdCurrentVDDMax = (tmp & 0x07U); - - /* Byte 9 */ - tmp = (uint8_t)((hsd->CSD[2U] & 0x00FF0000U) >> 16U); - pCSD->MaxWrCurrentVDDMin = (tmp & 0xE0U) >> 5U; - pCSD->MaxWrCurrentVDDMax = (tmp & 0x1CU) >> 2U; - pCSD->DeviceSizeMul = (tmp & 0x03U) << 1U; - /* Byte 10 */ - tmp = (uint8_t)((hsd->CSD[2U] & 0x0000FF00U) >> 8U); - pCSD->DeviceSizeMul |= (tmp & 0x80U) >> 7U; - - hsd->SdCard.BlockNbr = (pCSD->DeviceSize + 1U) ; - hsd->SdCard.BlockNbr *= (1U << (pCSD->DeviceSizeMul + 2U)); - hsd->SdCard.BlockSize = 1U << (pCSD->RdBlockLen); - - hsd->SdCard.LogBlockNbr = (hsd->SdCard.BlockNbr) * ((hsd->SdCard.BlockSize) / 512U); - hsd->SdCard.LogBlockSize = 512U; } - else if(hsd->SdCard.CardType == CARD_SDHC_SDXC) + + /* Transfer complete user callback */ + HAL_SD_DMA_TxCpltCallback(hsd->hdmatx); +} + +/** + * @brief SD DMA transfer Error Tx callback. + * @param hdma: pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void SD_DMA_TxError(DMA_HandleTypeDef *hdma) +{ + SD_HandleTypeDef *hsd = ( SD_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + + /* Transfer complete user callback */ + HAL_SD_DMA_TxErrorCallback(hsd->hdmatx); +} + +/** + * @brief Returns the SD current state. + * @param hsd: SD handle + * @retval SD card current state + */ +static HAL_SD_CardStateTypedef SD_GetState(SD_HandleTypeDef *hsd) +{ + uint32_t resp1 = 0; + + if (SD_SendStatus(hsd, &resp1) != SD_OK) { - /* Byte 7 */ - tmp = (uint8_t)(hsd->CSD[1U] & 0x000000FFU); - pCSD->DeviceSize = (tmp & 0x3FU) << 16U; - - /* Byte 8 */ - tmp = (uint8_t)((hsd->CSD[2U] & 0xFF000000U) >> 24U); - - pCSD->DeviceSize |= (tmp << 8U); - - /* Byte 9 */ - tmp = (uint8_t)((hsd->CSD[2U] & 0x00FF0000U) >> 16U); - - pCSD->DeviceSize |= (tmp); - - /* Byte 10 */ - tmp = (uint8_t)((hsd->CSD[2U] & 0x0000FF00U) >> 8U); - - hsd->SdCard.LogBlockNbr = hsd->SdCard.BlockNbr = (((uint64_t)pCSD->DeviceSize + 1U) * 1024U); - hsd->SdCard.LogBlockSize = hsd->SdCard.BlockSize = 512U; + return SD_CARD_ERROR; } else { - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); - hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE; - hsd->State = HAL_SD_STATE_READY; - return HAL_ERROR; + return (HAL_SD_CardStateTypedef)((resp1 >> 9) & 0x0F); } - - pCSD->EraseGrSize = (tmp & 0x40U) >> 6U; - pCSD->EraseGrMul = (tmp & 0x3FU) << 1U; - - /* Byte 11 */ - tmp = (uint8_t)(hsd->CSD[2U] & 0x000000FFU); - pCSD->EraseGrMul |= (tmp & 0x80U) >> 7U; - pCSD->WrProtectGrSize = (tmp & 0x7FU); - - /* Byte 12 */ - tmp = (uint8_t)((hsd->CSD[3U] & 0xFF000000U) >> 24U); - pCSD->WrProtectGrEnable = (tmp & 0x80U) >> 7U; - pCSD->ManDeflECC = (tmp & 0x60U) >> 5U; - pCSD->WrSpeedFact = (tmp & 0x1CU) >> 2U; - pCSD->MaxWrBlockLen = (tmp & 0x03U) << 2U; - - /* Byte 13 */ - tmp = (uint8_t)((hsd->CSD[3U] & 0x00FF0000U) >> 16U); - pCSD->MaxWrBlockLen |= (tmp & 0xC0U) >> 6U; - pCSD->WriteBlockPaPartial = (tmp & 0x20U) >> 5U; - pCSD->Reserved3 = 0U; - pCSD->ContentProtectAppli = (tmp & 0x01U); - - /* Byte 14 */ - tmp = (uint8_t)((hsd->CSD[3U] & 0x0000FF00U) >> 8U); - pCSD->FileFormatGrouop = (tmp & 0x80U) >> 7U; - pCSD->CopyFlag = (tmp & 0x40U) >> 6U; - pCSD->PermWrProtect = (tmp & 0x20U) >> 5U; - pCSD->TempWrProtect = (tmp & 0x10U) >> 4U; - pCSD->FileFormat = (tmp & 0x0CU) >> 2U; - pCSD->ECC = (tmp & 0x03U); - - /* Byte 15 */ - tmp = (uint8_t)(hsd->CSD[3U] & 0x000000FFU); - pCSD->CSD_CRC = (tmp & 0xFEU) >> 1U; - pCSD->Reserved4 = 1U; - - return HAL_OK; } /** - * @brief Gets the SD status info. - * @param hsd: Pointer to SD handle - * @param pStatus: Pointer to the HAL_SD_CardStatusTypeDef structure that - * will contain the SD card status information - * @retval HAL status + * @brief Initializes all cards or single card as the case may be Card(s) come + * into standby state. + * @param hsd: SD handle + * @retval SD Card error state */ -HAL_StatusTypeDef HAL_SD_GetCardStatus(SD_HandleTypeDef *hsd, HAL_SD_CardStatusTypeDef *pStatus) +static HAL_SD_ErrorTypedef SD_Initialize_Cards(SD_HandleTypeDef *hsd) { - uint32_t tmp = 0U; - uint32_t sd_status[16U]; - uint32_t errorstate = HAL_SD_ERROR_NONE; + SDIO_CmdInitTypeDef sdio_cmdinitstructure = {0}; + HAL_SD_ErrorTypedef errorstate = SD_OK; + uint16_t sd_rca = 1; - errorstate = SD_SendSDStatus(hsd, sd_status); - if(errorstate != HAL_OK) + if(SDIO_GetPowerState(hsd->Instance) == 0) /* Power off */ { - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); - hsd->ErrorCode |= errorstate; - hsd->State = HAL_SD_STATE_READY; - return HAL_ERROR; + errorstate = SD_REQUEST_NOT_APPLICABLE; + + return errorstate; } - else + + if(hsd->CardType != SECURE_DIGITAL_IO_CARD) { - /* Byte 0 */ - tmp = (sd_status[0U] & 0xC0U) >> 6U; - pStatus->DataBusWidth = (uint8_t)tmp; - - /* Byte 0 */ - tmp = (sd_status[0U] & 0x20U) >> 5U; - pStatus->SecuredMode = (uint8_t)tmp; - - /* Byte 2 */ - tmp = (sd_status[0U] & 0x00FF0000U) >> 16U; - pStatus->CardType = (uint16_t)(tmp << 8U); - - /* Byte 3 */ - tmp = (sd_status[0U] & 0xFF000000U) >> 24U; - pStatus->CardType |= (uint16_t)tmp; - - /* Byte 4 */ - tmp = (sd_status[1U] & 0xFFU); - pStatus->ProtectedAreaSize = (uint32_t)(tmp << 24U); - - /* Byte 5 */ - tmp = (sd_status[1U] & 0xFF00U) >> 8U; - pStatus->ProtectedAreaSize |= (uint32_t)(tmp << 16U); + /* Send CMD2 ALL_SEND_CID */ + sdio_cmdinitstructure.Argument = 0; + sdio_cmdinitstructure.CmdIndex = SD_CMD_ALL_SEND_CID; + sdio_cmdinitstructure.Response = SDIO_RESPONSE_LONG; + sdio_cmdinitstructure.WaitForInterrupt = SDIO_WAIT_NO; + sdio_cmdinitstructure.CPSM = SDIO_CPSM_ENABLE; + SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure); - /* Byte 6 */ - tmp = (sd_status[1U] & 0xFF0000U) >> 16U; - pStatus->ProtectedAreaSize |= (uint32_t)(tmp << 8U); + /* Check for error conditions */ + errorstate = SD_CmdResp2Error(hsd); - /* Byte 7 */ - tmp = (sd_status[1U] & 0xFF000000U) >> 24U; - pStatus->ProtectedAreaSize |= (uint32_t)tmp; + if(errorstate != SD_OK) + { + return errorstate; + } - /* Byte 8 */ - tmp = (sd_status[2U] & 0xFFU); - pStatus->SpeedClass = (uint8_t)tmp; + /* Get Card identification number data */ + hsd->CID[0] = SDIO_GetResponse(hsd->Instance, SDIO_RESP1); + hsd->CID[1] = SDIO_GetResponse(hsd->Instance, SDIO_RESP2); + hsd->CID[2] = SDIO_GetResponse(hsd->Instance, SDIO_RESP3); + hsd->CID[3] = SDIO_GetResponse(hsd->Instance, SDIO_RESP4); + } + + if((hsd->CardType == STD_CAPACITY_SD_CARD_V1_1) || (hsd->CardType == STD_CAPACITY_SD_CARD_V2_0) ||\ + (hsd->CardType == SECURE_DIGITAL_IO_COMBO_CARD) || (hsd->CardType == HIGH_CAPACITY_SD_CARD)) + { + /* Send CMD3 SET_REL_ADDR with argument 0 */ + /* SD Card publishes its RCA. */ + sdio_cmdinitstructure.CmdIndex = SD_CMD_SET_REL_ADDR; + sdio_cmdinitstructure.Response = SDIO_RESPONSE_SHORT; + SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure); - /* Byte 9 */ - tmp = (sd_status[2U] & 0xFF00U) >> 8U; - pStatus->PerformanceMove = (uint8_t)tmp; + /* Check for error conditions */ + errorstate = SD_CmdResp6Error(hsd, SD_CMD_SET_REL_ADDR, &sd_rca); - /* Byte 10 */ - tmp = (sd_status[2U] & 0xF00000U) >> 20U; - pStatus->AllocationUnitSize = (uint8_t)tmp; + if(errorstate != SD_OK) + { + return errorstate; + } + } + + if (hsd->CardType != SECURE_DIGITAL_IO_CARD) + { + /* Get the SD card RCA */ + hsd->RCA = sd_rca; - /* Byte 11 */ - tmp = (sd_status[2U] & 0xFF000000U) >> 24U; - pStatus->EraseSize = (uint16_t)(tmp << 8U); + /* Send CMD9 SEND_CSD with argument as card's RCA */ + sdio_cmdinitstructure.Argument = (uint32_t)(hsd->RCA << 16); + sdio_cmdinitstructure.CmdIndex = SD_CMD_SEND_CSD; + sdio_cmdinitstructure.Response = SDIO_RESPONSE_LONG; + SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure); - /* Byte 12 */ - tmp = (sd_status[3U] & 0xFFU); - pStatus->EraseSize |= (uint16_t)tmp; + /* Check for error conditions */ + errorstate = SD_CmdResp2Error(hsd); - /* Byte 13 */ - tmp = (sd_status[3U] & 0xFC00U) >> 10U; - pStatus->EraseTimeout = (uint8_t)tmp; + if(errorstate != SD_OK) + { + return errorstate; + } - /* Byte 13 */ - tmp = (sd_status[3U] & 0x0300U) >> 8U; - pStatus->EraseOffset = (uint8_t)tmp; + /* Get Card Specific Data */ + hsd->CSD[0] = SDIO_GetResponse(hsd->Instance, SDIO_RESP1); + hsd->CSD[1] = SDIO_GetResponse(hsd->Instance, SDIO_RESP2); + hsd->CSD[2] = SDIO_GetResponse(hsd->Instance, SDIO_RESP3); + hsd->CSD[3] = SDIO_GetResponse(hsd->Instance, SDIO_RESP4); } - return HAL_OK; + /* All cards are initialized */ + return errorstate; } /** - * @brief Gets the SD card info. - * @param hsd: Pointer to SD handle - * @param pCardInfo: Pointer to the HAL_SD_CardInfoTypeDef structure that - * will contain the SD card status information - * @retval HAL status + * @brief Selects od Deselects the corresponding card. + * @param hsd: SD handle + * @param Addr: Address of the card to be selected + * @retval SD Card error state */ -HAL_StatusTypeDef HAL_SD_GetCardInfo(SD_HandleTypeDef *hsd, HAL_SD_CardInfoTypeDef *pCardInfo) +static HAL_SD_ErrorTypedef SD_Select_Deselect(SD_HandleTypeDef *hsd, uint64_t Addr) { - pCardInfo->CardType = (uint32_t)(hsd->SdCard.CardType); - pCardInfo->CardVersion = (uint32_t)(hsd->SdCard.CardVersion); - pCardInfo->Class = (uint32_t)(hsd->SdCard.Class); - pCardInfo->RelCardAdd = (uint32_t)(hsd->SdCard.RelCardAdd); - pCardInfo->BlockNbr = (uint32_t)(hsd->SdCard.BlockNbr); - pCardInfo->BlockSize = (uint32_t)(hsd->SdCard.BlockSize); - pCardInfo->LogBlockNbr = (uint32_t)(hsd->SdCard.LogBlockNbr); - pCardInfo->LogBlockSize = (uint32_t)(hsd->SdCard.LogBlockSize); + SDIO_CmdInitTypeDef sdio_cmdinitstructure = {0}; + HAL_SD_ErrorTypedef errorstate = SD_OK; - return HAL_OK; + /* Send CMD7 SDIO_SEL_DESEL_CARD */ + sdio_cmdinitstructure.Argument = (uint32_t)Addr; + sdio_cmdinitstructure.CmdIndex = SD_CMD_SEL_DESEL_CARD; + sdio_cmdinitstructure.Response = SDIO_RESPONSE_SHORT; + sdio_cmdinitstructure.WaitForInterrupt = SDIO_WAIT_NO; + sdio_cmdinitstructure.CPSM = SDIO_CPSM_ENABLE; + SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure); + + /* Check for error conditions */ + errorstate = SD_CmdResp1Error(hsd, SD_CMD_SEL_DESEL_CARD); + + return errorstate; } /** - * @brief Enables wide bus operation for the requested card if supported by - * card. - * @param hsd: Pointer to SD handle - * @param WideMode: Specifies the SD card wide bus mode - * This parameter can be one of the following values: - * @arg SDIO_BUS_WIDE_8B: 8-bit data transfer - * @arg SDIO_BUS_WIDE_4B: 4-bit data transfer - * @arg SDIO_BUS_WIDE_1B: 1-bit data transfer - * @retval HAL status + * @brief Enquires cards about their operating voltage and configures clock + * controls and stores SD information that will be needed in future + * in the SD handle. + * @param hsd: SD handle + * @retval SD Card error state */ -HAL_StatusTypeDef HAL_SD_ConfigWideBusOperation(SD_HandleTypeDef *hsd, uint32_t WideMode) +static HAL_SD_ErrorTypedef SD_PowerON(SD_HandleTypeDef *hsd) { - SDIO_InitTypeDef Init; - uint32_t errorstate = HAL_SD_ERROR_NONE; + SDIO_CmdInitTypeDef sdio_cmdinitstructure = {0}; + __IO HAL_SD_ErrorTypedef errorstate = SD_OK; + uint32_t response = 0, count = 0, validvoltage = 0; + uint32_t sdtype = SD_STD_CAPACITY; + + /* Power ON Sequence -------------------------------------------------------*/ + /* Disable SDIO Clock */ + __HAL_SD_SDIO_DISABLE(hsd); + + /* Set Power State to ON */ + SDIO_PowerState_ON(hsd->Instance); + + /* 1ms: required power up waiting time before starting the SD initialization + sequence */ + HAL_Delay(1); + + /* Enable SDIO Clock */ + __HAL_SD_SDIO_ENABLE(hsd); - /* Check the parameters */ - assert_param(IS_SDIO_BUS_WIDE(WideMode)); + /* CMD0: GO_IDLE_STATE -----------------------------------------------------*/ + /* No CMD response required */ + sdio_cmdinitstructure.Argument = 0; + sdio_cmdinitstructure.CmdIndex = SD_CMD_GO_IDLE_STATE; + sdio_cmdinitstructure.Response = SDIO_RESPONSE_NO; + sdio_cmdinitstructure.WaitForInterrupt = SDIO_WAIT_NO; + sdio_cmdinitstructure.CPSM = SDIO_CPSM_ENABLE; + SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure); - /* Chnage Satte */ - hsd->State = HAL_SD_STATE_BUSY; + /* Check for error conditions */ + errorstate = SD_CmdError(hsd); - if(hsd->SdCard.CardType != CARD_SECURED) + if(errorstate != SD_OK) { - if(WideMode == SDIO_BUS_WIDE_8B) - { - hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE; - } - else if(WideMode == SDIO_BUS_WIDE_4B) + /* CMD Response TimeOut (wait for CMDSENT flag) */ + return errorstate; + } + + /* CMD8: SEND_IF_COND ------------------------------------------------------*/ + /* Send CMD8 to verify SD card interface operating condition */ + /* Argument: - [31:12]: Reserved (shall be set to '0') + - [11:8]: Supply Voltage (VHS) 0x1 (Range: 2.7-3.6 V) + - [7:0]: Check Pattern (recommended 0xAA) */ + /* CMD Response: R7 */ + sdio_cmdinitstructure.Argument = SD_CHECK_PATTERN; + sdio_cmdinitstructure.CmdIndex = SD_SDIO_SEND_IF_COND; + sdio_cmdinitstructure.Response = SDIO_RESPONSE_SHORT; + SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure); + + /* Check for error conditions */ + errorstate = SD_CmdResp7Error(hsd); + + if (errorstate == SD_OK) + { + /* SD Card 2.0 */ + hsd->CardType = STD_CAPACITY_SD_CARD_V2_0; + sdtype = SD_HIGH_CAPACITY; + } + + /* Send CMD55 */ + sdio_cmdinitstructure.Argument = 0; + sdio_cmdinitstructure.CmdIndex = SD_CMD_APP_CMD; + SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure); + + /* Check for error conditions */ + errorstate = SD_CmdResp1Error(hsd, SD_CMD_APP_CMD); + + /* If errorstate is Command TimeOut, it is a MMC card */ + /* If errorstate is SD_OK it is a SD card: SD card 2.0 (voltage range mismatch) + or SD card 1.x */ + if(errorstate == SD_OK) + { + /* SD CARD */ + /* Send ACMD41 SD_APP_OP_COND with Argument 0x80100000 */ + while((!validvoltage) && (count < SD_MAX_VOLT_TRIAL)) { - errorstate = SD_WideBus_Enable(hsd); - hsd->ErrorCode |= errorstate; - } - else if(WideMode == SDIO_BUS_WIDE_1B) - { - errorstate = SD_WideBus_Disable(hsd); + /* SEND CMD55 APP_CMD with RCA as 0 */ + sdio_cmdinitstructure.Argument = 0; + sdio_cmdinitstructure.CmdIndex = SD_CMD_APP_CMD; + sdio_cmdinitstructure.Response = SDIO_RESPONSE_SHORT; + sdio_cmdinitstructure.WaitForInterrupt = SDIO_WAIT_NO; + sdio_cmdinitstructure.CPSM = SDIO_CPSM_ENABLE; + SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure); + + /* Check for error conditions */ + errorstate = SD_CmdResp1Error(hsd, SD_CMD_APP_CMD); + + if(errorstate != SD_OK) + { + return errorstate; + } + + /* Send CMD41 */ + sdio_cmdinitstructure.Argument = SD_VOLTAGE_WINDOW_SD | sdtype; + sdio_cmdinitstructure.CmdIndex = SD_CMD_SD_APP_OP_COND; + sdio_cmdinitstructure.Response = SDIO_RESPONSE_SHORT; + sdio_cmdinitstructure.WaitForInterrupt = SDIO_WAIT_NO; + sdio_cmdinitstructure.CPSM = SDIO_CPSM_ENABLE; + SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure); + + /* Check for error conditions */ + errorstate = SD_CmdResp3Error(hsd); + + if(errorstate != SD_OK) + { + return errorstate; + } + + /* Get command response */ + response = SDIO_GetResponse(hsd->Instance, SDIO_RESP1); - hsd->ErrorCode |= errorstate; + /* Get operating voltage*/ + validvoltage = (((response >> 31) == 1) ? 1 : 0); + + count++; } - else + + if(count >= SD_MAX_VOLT_TRIAL) { - /* WideMode is not a valid argument*/ - hsd->ErrorCode |= HAL_SD_ERROR_PARAM; + errorstate = SD_INVALID_VOLTRANGE; + + return errorstate; } - } - else - { - /* MMC Card does not support this feature */ - hsd->ErrorCode |= HAL_SD_ERROR_UNSUPPORTED_FEATURE; - } - - if(hsd->ErrorCode != HAL_SD_ERROR_NONE) - { - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); - hsd->State = HAL_SD_STATE_READY; - return HAL_ERROR; - } - else - { - /* Configure the SDIO peripheral */ - Init.ClockEdge = hsd->Init.ClockEdge; - Init.ClockBypass = hsd->Init.ClockBypass; - Init.ClockPowerSave = hsd->Init.ClockPowerSave; - Init.BusWide = WideMode; - Init.HardwareFlowControl = hsd->Init.HardwareFlowControl; - Init.ClockDiv = hsd->Init.ClockDiv; - SDIO_Init(hsd->Instance, Init); - } - - /* Change State */ - hsd->State = HAL_SD_STATE_READY; + + if((response & SD_HIGH_CAPACITY) == SD_HIGH_CAPACITY) /* (response &= SD_HIGH_CAPACITY) */ + { + hsd->CardType = HIGH_CAPACITY_SD_CARD; + } + + } /* else MMC Card */ - return HAL_OK; + return errorstate; } - /** - * @brief Gets the current sd card data state. - * @param hsd: pointer to SD handle - * @retval Card state + * @brief Turns the SDIO output signals off. + * @param hsd: SD handle + * @retval SD Card error state */ -HAL_SD_CardStateTypeDef HAL_SD_GetCardState(SD_HandleTypeDef *hsd) +static HAL_SD_ErrorTypedef SD_PowerOFF(SD_HandleTypeDef *hsd) { - HAL_SD_CardStateTypeDef cardstate = HAL_SD_CARD_TRANSFER; - uint32_t errorstate = HAL_SD_ERROR_NONE; - uint32_t resp1 = 0; + HAL_SD_ErrorTypedef errorstate = SD_OK; - errorstate = SD_SendStatus(hsd, &resp1); - if(errorstate != HAL_OK) - { - hsd->ErrorCode |= errorstate; - } - - cardstate = (HAL_SD_CardStateTypeDef)((resp1 >> 9U) & 0x0FU); + /* Set Power State to OFF */ + SDIO_PowerState_OFF(hsd->Instance); - return cardstate; + return errorstate; } /** - * @brief Abort the current transfer and disable the SD. - * @param hsd: pointer to a SD_HandleTypeDef structure that contains - * the configuration information for SD module. - * @retval HAL status + * @brief Returns the current card's status. + * @param hsd: SD handle + * @param pCardStatus: pointer to the buffer that will contain the SD card + * status (Card Status register) + * @retval SD Card error state */ -HAL_StatusTypeDef HAL_SD_Abort(SD_HandleTypeDef *hsd) +static HAL_SD_ErrorTypedef SD_SendStatus(SD_HandleTypeDef *hsd, uint32_t *pCardStatus) { - HAL_SD_CardStateTypeDef CardState; - - /* DIsable All interrupts */ - __HAL_SD_DISABLE_IT(hsd, SDIO_IT_DATAEND | SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT|\ - SDIO_IT_TXUNDERR| SDIO_IT_RXOVERR); - - /* Clear All flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); + SDIO_CmdInitTypeDef sdio_cmdinitstructure = {0}; + HAL_SD_ErrorTypedef errorstate = SD_OK; - if((hsd->hdmatx != NULL) || (hsd->hdmarx != NULL)) + if(pCardStatus == NULL) { - /* Disable the SD DMA request */ - hsd->Instance->DCTRL &= (uint32_t)~((uint32_t)SDIO_DCTRL_DMAEN); + errorstate = SD_INVALID_PARAMETER; - /* Abort the SD DMA Tx Stream */ - if(hsd->hdmatx != NULL) - { - HAL_DMA_Abort(hsd->hdmatx); - } - /* Abort the SD DMA Rx Stream */ - if(hsd->hdmarx != NULL) - { - HAL_DMA_Abort(hsd->hdmarx); - } + return errorstate; } - hsd->State = HAL_SD_STATE_READY; - CardState = HAL_SD_GetCardState(hsd); - if((CardState == HAL_SD_CARD_RECEIVING) || (CardState == HAL_SD_CARD_SENDING)) - { - hsd->ErrorCode = SDMMC_CmdStopTransfer(hsd->Instance); - } - if(hsd->ErrorCode != HAL_SD_ERROR_NONE) + /* Send Status command */ + sdio_cmdinitstructure.Argument = (uint32_t)(hsd->RCA << 16); + sdio_cmdinitstructure.CmdIndex = SD_CMD_SEND_STATUS; + sdio_cmdinitstructure.Response = SDIO_RESPONSE_SHORT; + sdio_cmdinitstructure.WaitForInterrupt = SDIO_WAIT_NO; + sdio_cmdinitstructure.CPSM = SDIO_CPSM_ENABLE; + SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure); + + /* Check for error conditions */ + errorstate = SD_CmdResp1Error(hsd, SD_CMD_SEND_STATUS); + + if(errorstate != SD_OK) { - return HAL_ERROR; + return errorstate; } - return HAL_OK; + + /* Get SD card status */ + *pCardStatus = SDIO_GetResponse(hsd->Instance, SDIO_RESP1); + + return errorstate; } /** - * @brief Abort the current transfer and disable the SD (IT mode). - * @param hsd: pointer to a SD_HandleTypeDef structure that contains - * the configuration information for SD module. - * @retval HAL status + * @brief Checks for error conditions for CMD0. + * @param hsd: SD handle + * @retval SD Card error state */ -HAL_StatusTypeDef HAL_SD_Abort_IT(SD_HandleTypeDef *hsd) +static HAL_SD_ErrorTypedef SD_CmdError(SD_HandleTypeDef *hsd) { - HAL_SD_CardStateTypeDef CardState; - - /* DIsable All interrupts */ - __HAL_SD_DISABLE_IT(hsd, SDIO_IT_DATAEND | SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT|\ - SDIO_IT_TXUNDERR| SDIO_IT_RXOVERR); + HAL_SD_ErrorTypedef errorstate = SD_OK; + uint32_t timeout = SDIO_CMD0TIMEOUT, tmp; - /* Clear All flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); - - if((hsd->hdmatx != NULL) || (hsd->hdmarx != NULL)) - { - /* Disable the SD DMA request */ - hsd->Instance->DCTRL &= (uint32_t)~((uint32_t)SDIO_DCTRL_DMAEN); + tmp = __HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_CMDSENT); - /* Abort the SD DMA Tx Stream */ - if(hsd->hdmatx != NULL) - { - hsd->hdmatx->XferAbortCallback = SD_DMATxAbort; - if(HAL_DMA_Abort_IT(hsd->hdmatx) != HAL_OK) - { - hsd->hdmatx = NULL; - } - } - /* Abort the SD DMA Rx Stream */ - if(hsd->hdmarx != NULL) - { - hsd->hdmarx->XferAbortCallback = SD_DMARxAbort; - if(HAL_DMA_Abort_IT(hsd->hdmarx) != HAL_OK) - { - hsd->hdmarx = NULL; - } - } + while((timeout > 0) && (!tmp)) + { + tmp = __HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_CMDSENT); + timeout--; } - /* No transfer ongoing on both DMA channels*/ - if((hsd->hdmatx == NULL) && (hsd->hdmarx == NULL)) + if(timeout == 0) { - CardState = HAL_SD_GetCardState(hsd); - hsd->State = HAL_SD_STATE_READY; - if((CardState == HAL_SD_CARD_RECEIVING) || (CardState == HAL_SD_CARD_SENDING)) - { - hsd->ErrorCode = SDMMC_CmdStopTransfer(hsd->Instance); - } - if(hsd->ErrorCode != HAL_SD_ERROR_NONE) - { - return HAL_ERROR; - } - else - { - HAL_SD_AbortCallback(hsd); - } + errorstate = SD_CMD_RSP_TIMEOUT; + return errorstate; } - return HAL_OK; -} - -/** - * @} - */ - -/** - * @} - */ - -/* Private function ----------------------------------------------------------*/ -/** @addtogroup SD_Private_Functions - * @{ - */ - -/** - * @brief DMA SD transmit process complete callback - * @param hdma: DMA handle - * @retval None - */ -static void SD_DMATransmitCplt(DMA_HandleTypeDef *hdma) -{ - SD_HandleTypeDef* hsd = (SD_HandleTypeDef* )(hdma->Parent); + /* Clear all the static flags */ + __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); - /* Enable DATAEND Interrupt */ - __HAL_SD_ENABLE_IT(hsd, (SDIO_IT_DATAEND)); + return errorstate; } /** - * @brief DMA SD receive process complete callback - * @param hdma: DMA handle - * @retval None + * @brief Checks for error conditions for R7 response. + * @param hsd: SD handle + * @retval SD Card error state */ -static void SD_DMAReceiveCplt(DMA_HandleTypeDef *hdma) +static HAL_SD_ErrorTypedef SD_CmdResp7Error(SD_HandleTypeDef *hsd) { - SD_HandleTypeDef* hsd = (SD_HandleTypeDef* )(hdma->Parent); - uint32_t errorstate = HAL_SD_ERROR_NONE; + HAL_SD_ErrorTypedef errorstate = SD_ERROR; + uint32_t timeout = SDIO_CMD0TIMEOUT, tmp; - /* Send stop command in multiblock write */ - if(hsd->Context == (SD_CONTEXT_READ_MULTIPLE_BLOCK | SD_CONTEXT_DMA)) + tmp = __HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_CCRCFAIL | SDIO_FLAG_CMDREND | SDIO_FLAG_CTIMEOUT); + + while((!tmp) && (timeout > 0)) { - errorstate = SDMMC_CmdStopTransfer(hsd->Instance); - if(errorstate != HAL_SD_ERROR_NONE) - { - hsd->ErrorCode |= errorstate; - HAL_SD_ErrorCallback(hsd); - } + tmp = __HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_CCRCFAIL | SDIO_FLAG_CMDREND | SDIO_FLAG_CTIMEOUT); + timeout--; } - /* Disable the DMA transfer for transmit request by setting the DMAEN bit - in the SD DCTRL register */ - hsd->Instance->DCTRL &= (uint32_t)~((uint32_t)SDIO_DCTRL_DMAEN); + tmp = __HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_CTIMEOUT); - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); + if((timeout == 0) || tmp) + { + /* Card is not V2.0 compliant or card does not support the set voltage range */ + errorstate = SD_CMD_RSP_TIMEOUT; + + __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_CTIMEOUT); + + return errorstate; + } - hsd->State = HAL_SD_STATE_READY; - - HAL_SD_RxCpltCallback(hsd); + if(__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_CMDREND)) + { + /* Card is SD V2.0 compliant */ + errorstate = SD_OK; + + __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_CMDREND); + + return errorstate; + } + + return errorstate; } /** - * @brief DMA SD communication error callback - * @param hdma: DMA handle - * @retval None + * @brief Checks for error conditions for R1 response. + * @param hsd: SD handle + * @param SD_CMD: The sent command index + * @retval SD Card error state */ -static void SD_DMAError(DMA_HandleTypeDef *hdma) +static HAL_SD_ErrorTypedef SD_CmdResp1Error(SD_HandleTypeDef *hsd, uint8_t SD_CMD) { - SD_HandleTypeDef* hsd = (SD_HandleTypeDef* )(hdma->Parent); - HAL_SD_CardStateTypeDef CardState; + HAL_SD_ErrorTypedef errorstate = SD_OK; + uint32_t response_r1 = 0; - if((hsd->hdmarx->ErrorCode == HAL_DMA_ERROR_TE) || (hsd->hdmatx->ErrorCode == HAL_DMA_ERROR_TE)) + while(!__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_CCRCFAIL | SDIO_FLAG_CMDREND | SDIO_FLAG_CTIMEOUT)) { - /* Clear All flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); + } + + if(__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_CTIMEOUT)) + { + errorstate = SD_CMD_RSP_TIMEOUT; - /* Disable All interrupts */ - __HAL_SD_DISABLE_IT(hsd, SDIO_IT_DATAEND | SDIO_IT_DCRCFAIL | SDIO_IT_DTIMEOUT|\ - SDIO_IT_TXUNDERR| SDIO_IT_RXOVERR); + __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_CTIMEOUT); - hsd->ErrorCode |= HAL_SD_ERROR_DMA; - CardState = HAL_SD_GetCardState(hsd); - if((CardState == HAL_SD_CARD_RECEIVING) || (CardState == HAL_SD_CARD_SENDING)) - { - hsd->ErrorCode |= SDMMC_CmdStopTransfer(hsd->Instance); - } + return errorstate; + } + else if(__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_CCRCFAIL)) + { + errorstate = SD_CMD_CRC_FAIL; - hsd->State= HAL_SD_STATE_READY; + __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_CCRCFAIL); + + return errorstate; + } + else + { + /* No error flag set */ } - - HAL_SD_ErrorCallback(hsd); -} - -/** - * @brief DMA SD Tx Abort callback - * @param hdma: DMA handle - * @retval None - */ -static void SD_DMATxAbort(DMA_HandleTypeDef *hdma) -{ - SD_HandleTypeDef* hsd = (SD_HandleTypeDef* )(hdma->Parent); - HAL_SD_CardStateTypeDef CardState; - if(hsd->hdmatx != NULL) + /* Check response received is of desired command */ + if(SDIO_GetCommandResponse(hsd->Instance) != SD_CMD) { - hsd->hdmatx = NULL; + errorstate = SD_ILLEGAL_CMD; + + return errorstate; } - /* All DMA channels are aborted */ - if(hsd->hdmarx == NULL) + /* Clear all the static flags */ + __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); + + /* We have received response, retrieve it for analysis */ + response_r1 = SDIO_GetResponse(hsd->Instance, SDIO_RESP1); + + if((response_r1 & SD_OCR_ERRORBITS) == SD_ALLZERO) { - CardState = HAL_SD_GetCardState(hsd); - hsd->ErrorCode = HAL_SD_ERROR_NONE; - hsd->State = HAL_SD_STATE_READY; - if((CardState == HAL_SD_CARD_RECEIVING) || (CardState == HAL_SD_CARD_SENDING)) - { - hsd->ErrorCode |= SDMMC_CmdStopTransfer(hsd->Instance); - - if(hsd->ErrorCode != HAL_SD_ERROR_NONE) - { - HAL_SD_AbortCallback(hsd); - } - else - { - HAL_SD_ErrorCallback(hsd); - } - } + return errorstate; } -} - -/** - * @brief DMA SD Rx Abort callback - * @param hdma: DMA handle - * @retval None - */ -static void SD_DMARxAbort(DMA_HandleTypeDef *hdma) -{ - SD_HandleTypeDef* hsd = (SD_HandleTypeDef* )(hdma->Parent); - HAL_SD_CardStateTypeDef CardState; - if(hsd->hdmarx != NULL) + if((response_r1 & SD_OCR_ADDR_OUT_OF_RANGE) == SD_OCR_ADDR_OUT_OF_RANGE) { - hsd->hdmarx = NULL; + return(SD_ADDR_OUT_OF_RANGE); } - /* All DMA channels are aborted */ - if(hsd->hdmatx == NULL) + if((response_r1 & SD_OCR_ADDR_MISALIGNED) == SD_OCR_ADDR_MISALIGNED) { - CardState = HAL_SD_GetCardState(hsd); - hsd->ErrorCode = HAL_SD_ERROR_NONE; - hsd->State = HAL_SD_STATE_READY; - if((CardState == HAL_SD_CARD_RECEIVING) || (CardState == HAL_SD_CARD_SENDING)) - { - hsd->ErrorCode |= SDMMC_CmdStopTransfer(hsd->Instance); - - if(hsd->ErrorCode != HAL_SD_ERROR_NONE) - { - HAL_SD_AbortCallback(hsd); - } - else - { - HAL_SD_ErrorCallback(hsd); - } - } + return(SD_ADDR_MISALIGNED); } -} - - -/** - * @brief Initializes the sd card. - * @param hsd: Pointer to SD handle - * @retval SD Card error state - */ -static uint32_t SD_InitCard(SD_HandleTypeDef *hsd) -{ - HAL_SD_CardCSDTypeDef CSD; - uint32_t errorstate = HAL_SD_ERROR_NONE; - uint16_t sd_rca = 1U; - /* Check the power State */ - if(SDIO_GetPowerState(hsd->Instance) == 0U) + if((response_r1 & SD_OCR_BLOCK_LEN_ERR) == SD_OCR_BLOCK_LEN_ERR) { - /* Power off */ - return HAL_SD_ERROR_REQUEST_NOT_APPLICABLE; + return(SD_BLOCK_LEN_ERR); } - if(hsd->SdCard.CardType != CARD_SECURED) + if((response_r1 & SD_OCR_ERASE_SEQ_ERR) == SD_OCR_ERASE_SEQ_ERR) { - /* Send CMD2 ALL_SEND_CID */ - errorstate = SDMMC_CmdSendCID(hsd->Instance); - if(errorstate != HAL_SD_ERROR_NONE) - { - return errorstate; - } - else - { - /* Get Card identification number data */ - hsd->CID[0U] = SDIO_GetResponse(hsd->Instance, SDIO_RESP1); - hsd->CID[1U] = SDIO_GetResponse(hsd->Instance, SDIO_RESP2); - hsd->CID[2U] = SDIO_GetResponse(hsd->Instance, SDIO_RESP3); - hsd->CID[3U] = SDIO_GetResponse(hsd->Instance, SDIO_RESP4); - } + return(SD_ERASE_SEQ_ERR); } - if(hsd->SdCard.CardType != CARD_SECURED) + if((response_r1 & SD_OCR_BAD_ERASE_PARAM) == SD_OCR_BAD_ERASE_PARAM) { - /* Send CMD3 SET_REL_ADDR with argument 0 */ - /* SD Card publishes its RCA. */ - errorstate = SDMMC_CmdSetRelAdd(hsd->Instance, &sd_rca); - if(errorstate != HAL_SD_ERROR_NONE) - { - return errorstate; - } + return(SD_BAD_ERASE_PARAM); } - if(hsd->SdCard.CardType != CARD_SECURED) + + if((response_r1 & SD_OCR_WRITE_PROT_VIOLATION) == SD_OCR_WRITE_PROT_VIOLATION) { - /* Get the SD card RCA */ - hsd->SdCard.RelCardAdd = sd_rca; - - /* Send CMD9 SEND_CSD with argument as card's RCA */ - errorstate = SDMMC_CmdSendCSD(hsd->Instance, (uint32_t)(hsd->SdCard.RelCardAdd << 16U)); - if(errorstate != HAL_SD_ERROR_NONE) - { - return errorstate; - } - else - { - /* Get Card Specific Data */ - hsd->CSD[0U] = SDIO_GetResponse(hsd->Instance, SDIO_RESP1); - hsd->CSD[1U] = SDIO_GetResponse(hsd->Instance, SDIO_RESP2); - hsd->CSD[2U] = SDIO_GetResponse(hsd->Instance, SDIO_RESP3); - hsd->CSD[3U] = SDIO_GetResponse(hsd->Instance, SDIO_RESP4); - } + return(SD_WRITE_PROT_VIOLATION); } - /* Get the Card Class */ - hsd->SdCard.Class = (SDIO_GetResponse(hsd->Instance, SDIO_RESP2) >> 20U); + if((response_r1 & SD_OCR_LOCK_UNLOCK_FAILED) == SD_OCR_LOCK_UNLOCK_FAILED) + { + return(SD_LOCK_UNLOCK_FAILED); + } - /* Get CSD parameters */ - HAL_SD_GetCardCSD(hsd, &CSD); - - /* Select the Card */ - errorstate = SDMMC_CmdSelDesel(hsd->Instance, (uint32_t)(((uint32_t)hsd->SdCard.RelCardAdd) << 16U)); - if(errorstate != HAL_SD_ERROR_NONE) + if((response_r1 & SD_OCR_COM_CRC_FAILED) == SD_OCR_COM_CRC_FAILED) { - return errorstate; + return(SD_COM_CRC_FAILED); } - - /* Configure SDIO peripheral interface */ - SDIO_Init(hsd->Instance, hsd->Init); - - /* All cards are initialized */ - return HAL_SD_ERROR_NONE; -} - -/** - * @brief Enquires cards about their operating voltage and configures clock - * controls and stores SD information that will be needed in future - * in the SD handle. - * @param hsd: Pointer to SD handle - * @retval error state - */ -static uint32_t SD_PowerON(SD_HandleTypeDef *hsd) -{ - __IO uint32_t count = 0U; - uint32_t response = 0U, validvoltage = 0U; - uint32_t errorstate = HAL_SD_ERROR_NONE; - /* CMD0: GO_IDLE_STATE */ - errorstate = SDMMC_CmdGoIdleState(hsd->Instance); - if(errorstate != HAL_SD_ERROR_NONE) + if((response_r1 & SD_OCR_ILLEGAL_CMD) == SD_OCR_ILLEGAL_CMD) { - return errorstate; + return(SD_ILLEGAL_CMD); } - /* CMD8: SEND_IF_COND: Command available only on V2.0 cards */ - errorstate = SDMMC_CmdOperCond(hsd->Instance); - if(errorstate != HAL_SD_ERROR_NONE) + if((response_r1 & SD_OCR_CARD_ECC_FAILED) == SD_OCR_CARD_ECC_FAILED) { - hsd->SdCard.CardVersion = CARD_V1_X; - - /* Send ACMD41 SD_APP_OP_COND with Argument 0x80100000 */ - while(validvoltage == 0U) - { - if(count++ == SDMMC_MAX_VOLT_TRIAL) - { - return HAL_SD_ERROR_INVALID_VOLTRANGE; - } - - /* SEND CMD55 APP_CMD with RCA as 0 */ - errorstate = SDMMC_CmdAppCommand(hsd->Instance, 0U); - if(errorstate != HAL_SD_ERROR_NONE) - { - return HAL_SD_ERROR_UNSUPPORTED_FEATURE; - } - - /* Send CMD41 */ - errorstate = SDMMC_CmdAppOperCommand(hsd->Instance, SDMMC_STD_CAPACITY); - if(errorstate != HAL_SD_ERROR_NONE) - { - return HAL_SD_ERROR_UNSUPPORTED_FEATURE; - } - - /* Get command response */ - response = SDIO_GetResponse(hsd->Instance, SDIO_RESP1); - - /* Get operating voltage*/ - validvoltage = (((response >> 31U) == 1U) ? 1U : 0U); - } - /* Card type is SDSC */ - hsd->SdCard.CardType = CARD_SDSC; + return(SD_CARD_ECC_FAILED); } - else + + if((response_r1 & SD_OCR_CC_ERROR) == SD_OCR_CC_ERROR) { - hsd->SdCard.CardVersion = CARD_V2_X; - - /* Send ACMD41 SD_APP_OP_COND with Argument 0x80100000 */ - while(validvoltage == 0U) - { - if(count++ == SDMMC_MAX_VOLT_TRIAL) - { - return HAL_SD_ERROR_INVALID_VOLTRANGE; - } - - /* SEND CMD55 APP_CMD with RCA as 0 */ - errorstate = SDMMC_CmdAppCommand(hsd->Instance, 0U); - if(errorstate != HAL_SD_ERROR_NONE) - { - return errorstate; - } - - /* Send CMD41 */ - errorstate = SDMMC_CmdAppOperCommand(hsd->Instance, SDMMC_HIGH_CAPACITY); - if(errorstate != HAL_SD_ERROR_NONE) - { - return errorstate; - } - - /* Get command response */ - response = SDIO_GetResponse(hsd->Instance, SDIO_RESP1); - - /* Get operating voltage*/ - validvoltage = (((response >> 31U) == 1U) ? 1U : 0U); - } - - if((response & SDMMC_HIGH_CAPACITY) == SDMMC_HIGH_CAPACITY) /* (response &= SD_HIGH_CAPACITY) */ - { - hsd->SdCard.CardType = CARD_SDHC_SDXC; - } - else - { - hsd->SdCard.CardType = CARD_SDSC; - } + return(SD_CC_ERROR); + } + + if((response_r1 & SD_OCR_GENERAL_UNKNOWN_ERROR) == SD_OCR_GENERAL_UNKNOWN_ERROR) + { + return(SD_GENERAL_UNKNOWN_ERROR); + } + + if((response_r1 & SD_OCR_STREAM_READ_UNDERRUN) == SD_OCR_STREAM_READ_UNDERRUN) + { + return(SD_STREAM_READ_UNDERRUN); + } + + if((response_r1 & SD_OCR_STREAM_WRITE_OVERRUN) == SD_OCR_STREAM_WRITE_OVERRUN) + { + return(SD_STREAM_WRITE_OVERRUN); + } + + if((response_r1 & SD_OCR_CID_CSD_OVERWRITE) == SD_OCR_CID_CSD_OVERWRITE) + { + return(SD_CID_CSD_OVERWRITE); + } + + if((response_r1 & SD_OCR_WP_ERASE_SKIP) == SD_OCR_WP_ERASE_SKIP) + { + return(SD_WP_ERASE_SKIP); + } + + if((response_r1 & SD_OCR_CARD_ECC_DISABLED) == SD_OCR_CARD_ECC_DISABLED) + { + return(SD_CARD_ECC_DISABLED); + } + + if((response_r1 & SD_OCR_ERASE_RESET) == SD_OCR_ERASE_RESET) + { + return(SD_ERASE_RESET); + } + + if((response_r1 & SD_OCR_AKE_SEQ_ERROR) == SD_OCR_AKE_SEQ_ERROR) + { + return(SD_AKE_SEQ_ERROR); } - return HAL_SD_ERROR_NONE; + return errorstate; } /** - * @brief Turns the SDIO output signals off. - * @param hsd: Pointer to SD handle - * @retval HAL status + * @brief Checks for error conditions for R3 (OCR) response. + * @param hsd: SD handle + * @retval SD Card error state */ -static HAL_StatusTypeDef SD_PowerOFF(SD_HandleTypeDef *hsd) +static HAL_SD_ErrorTypedef SD_CmdResp3Error(SD_HandleTypeDef *hsd) { - /* Set Power State to OFF */ - SDIO_PowerState_OFF(hsd->Instance); + HAL_SD_ErrorTypedef errorstate = SD_OK; - return HAL_OK; + while (!__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_CCRCFAIL | SDIO_FLAG_CMDREND | SDIO_FLAG_CTIMEOUT)) + { + } + + if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_CTIMEOUT)) + { + errorstate = SD_CMD_RSP_TIMEOUT; + + __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_CTIMEOUT); + + return errorstate; + } + + /* Clear all the static flags */ + __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); + + return errorstate; } /** - * @brief Send Status info command. - * @param hsd: pointer to SD handle - * @param pSDstatus: Pointer to the buffer that will contain the SD card status - * SD Status register) - * @retval error state + * @brief Checks for error conditions for R2 (CID or CSD) response. + * @param hsd: SD handle + * @retval SD Card error state */ -static uint32_t SD_SendSDStatus(SD_HandleTypeDef *hsd, uint32_t *pSDstatus) +static HAL_SD_ErrorTypedef SD_CmdResp2Error(SD_HandleTypeDef *hsd) { - SDIO_DataInitTypeDef config; - uint32_t errorstate = HAL_SD_ERROR_NONE; - uint32_t tickstart = HAL_GetTick(); - uint32_t count = 0U; + HAL_SD_ErrorTypedef errorstate = SD_OK; - /* Check SD response */ - if((SDIO_GetResponse(hsd->Instance, SDIO_RESP1) & SDMMC_CARD_LOCKED) == SDMMC_CARD_LOCKED) + while (!__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_CCRCFAIL | SDIO_FLAG_CMDREND | SDIO_FLAG_CTIMEOUT)) { - return HAL_SD_ERROR_LOCK_UNLOCK_FAILED; } - - /* Set block size for card if it is not equal to current block size for card */ - errorstate = SDMMC_CmdBlockLength(hsd->Instance, 64U); - if(errorstate != HAL_SD_ERROR_NONE) + + if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_CTIMEOUT)) { - hsd->ErrorCode |= HAL_SD_ERROR_NONE; + errorstate = SD_CMD_RSP_TIMEOUT; + + __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_CTIMEOUT); + return errorstate; } - - /* Send CMD55 */ - errorstate = SDMMC_CmdAppCommand(hsd->Instance, (uint32_t)(hsd->SdCard.RelCardAdd << 16U)); - if(errorstate != HAL_SD_ERROR_NONE) + else if (__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_CCRCFAIL)) { - hsd->ErrorCode |= HAL_SD_ERROR_NONE; + errorstate = SD_CMD_CRC_FAIL; + + __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_CCRCFAIL); + return errorstate; } - - /* Configure the SD DPSM (Data Path State Machine) */ - config.DataTimeOut = SDMMC_DATATIMEOUT; - config.DataLength = 64U; - config.DataBlockSize = SDIO_DATABLOCK_SIZE_64B; - config.TransferDir = SDIO_TRANSFER_DIR_TO_SDIO; - config.TransferMode = SDIO_TRANSFER_MODE_BLOCK; - config.DPSM = SDIO_DPSM_ENABLE; - SDIO_ConfigData(hsd->Instance, &config); - - /* Send ACMD13 (SD_APP_STAUS) with argument as card's RCA */ - errorstate = SDMMC_CmdStatusRegister(hsd->Instance); - if(errorstate != HAL_SD_ERROR_NONE) + else { - hsd->ErrorCode |= HAL_SD_ERROR_NONE; - return errorstate; + /* No error flag set */ } - /* Get status data */ - while(!__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_RXOVERR | SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DTIMEOUT | SDIO_FLAG_DBCKEND)) + /* Clear all the static flags */ + __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); + + return errorstate; +} + +/** + * @brief Checks for error conditions for R6 (RCA) response. + * @param hsd: SD handle + * @param SD_CMD: The sent command index + * @param pRCA: Pointer to the variable that will contain the SD card relative + * address RCA + * @retval SD Card error state + */ +static HAL_SD_ErrorTypedef SD_CmdResp6Error(SD_HandleTypeDef *hsd, uint8_t SD_CMD, uint16_t *pRCA) +{ + HAL_SD_ErrorTypedef errorstate = SD_OK; + uint32_t response_r1 = 0; + + while(!__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_CCRCFAIL | SDIO_FLAG_CMDREND | SDIO_FLAG_CTIMEOUT)) { - if(__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_RXFIFOHF)) - { - for(count = 0U; count < 8U; count++) - { - *(pSDstatus + count) = SDIO_ReadFIFO(hsd->Instance); - } - - pSDstatus += 8U; - } - - if((HAL_GetTick() - tickstart) >= SDMMC_DATATIMEOUT) - { - return HAL_SD_ERROR_TIMEOUT; - } } - if(__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_DTIMEOUT)) + if(__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_CTIMEOUT)) { - return HAL_SD_ERROR_DATA_TIMEOUT; + errorstate = SD_CMD_RSP_TIMEOUT; + + __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_CTIMEOUT); + + return errorstate; } - else if(__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_DCRCFAIL)) + else if(__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_CCRCFAIL)) { - return HAL_SD_ERROR_DATA_CRC_FAIL; + errorstate = SD_CMD_CRC_FAIL; + + __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_CCRCFAIL); + + return errorstate; } - else if(__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_RXOVERR)) + else { - return HAL_SD_ERROR_RX_OVERRUN; + /* No error flag set */ } - - while ((__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_RXDAVL))) + + /* Check response received is of desired command */ + if(SDIO_GetCommandResponse(hsd->Instance) != SD_CMD) { - *pSDstatus = SDIO_ReadFIFO(hsd->Instance); - pSDstatus++; + errorstate = SD_ILLEGAL_CMD; - if((HAL_GetTick() - tickstart) >= SDMMC_DATATIMEOUT) - { - return HAL_SD_ERROR_TIMEOUT; - } + return errorstate; } - /* Clear all the static status flags*/ - __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); + /* Clear all the static flags */ + __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); - return HAL_SD_ERROR_NONE; -} - -/** - * @brief Returns the current card's status. - * @param hsd: Pointer to SD handle - * @param pCardStatus: pointer to the buffer that will contain the SD card - * status (Card Status register) - * @retval error state - */ -static uint32_t SD_SendStatus(SD_HandleTypeDef *hsd, uint32_t *pCardStatus) -{ - uint32_t errorstate = HAL_SD_ERROR_NONE; + /* We have received response, retrieve it. */ + response_r1 = SDIO_GetResponse(hsd->Instance, SDIO_RESP1); - if(pCardStatus == NULL) + if((response_r1 & (SD_R6_GENERAL_UNKNOWN_ERROR | SD_R6_ILLEGAL_CMD | SD_R6_COM_CRC_FAILED)) == SD_ALLZERO) { - return HAL_SD_ERROR_PARAM; + *pRCA = (uint16_t) (response_r1 >> 16); + + return errorstate; } - /* Send Status command */ - errorstate = SDMMC_CmdSendStatus(hsd->Instance, (uint32_t)(hsd->SdCard.RelCardAdd << 16U)); - if(errorstate != HAL_OK) + if((response_r1 & SD_R6_GENERAL_UNKNOWN_ERROR) == SD_R6_GENERAL_UNKNOWN_ERROR) { - return errorstate; + return(SD_GENERAL_UNKNOWN_ERROR); } - /* Get SD card status */ - *pCardStatus = SDIO_GetResponse(hsd->Instance, SDIO_RESP1); + if((response_r1 & SD_R6_ILLEGAL_CMD) == SD_R6_ILLEGAL_CMD) + { + return(SD_ILLEGAL_CMD); + } + + if((response_r1 & SD_R6_COM_CRC_FAILED) == SD_R6_COM_CRC_FAILED) + { + return(SD_COM_CRC_FAILED); + } - return HAL_SD_ERROR_NONE; + return errorstate; } /** * @brief Enables the SDIO wide bus mode. - * @param hsd: pointer to SD handle - * @retval error state + * @param hsd: SD handle + * @retval SD Card error state */ -static uint32_t SD_WideBus_Enable(SD_HandleTypeDef *hsd) +static HAL_SD_ErrorTypedef SD_WideBus_Enable(SD_HandleTypeDef *hsd) { - uint32_t scr[2U] = {0U, 0U}; - uint32_t errorstate = HAL_SD_ERROR_NONE; + SDIO_CmdInitTypeDef sdio_cmdinitstructure = {0}; + HAL_SD_ErrorTypedef errorstate = SD_OK; - if((SDIO_GetResponse(hsd->Instance, SDIO_RESP1) & SDMMC_CARD_LOCKED) == SDMMC_CARD_LOCKED) + uint32_t scr[2] = {0, 0}; + + if((SDIO_GetResponse(hsd->Instance, SDIO_RESP1) & SD_CARD_LOCKED) == SD_CARD_LOCKED) { - return HAL_SD_ERROR_LOCK_UNLOCK_FAILED; + errorstate = SD_LOCK_UNLOCK_FAILED; + + return errorstate; } /* Get SCR Register */ errorstate = SD_FindSCR(hsd, scr); - if(errorstate != HAL_OK) + + if(errorstate != SD_OK) { return errorstate; } /* If requested card supports wide bus operation */ - if((scr[1U] & SDMMC_WIDE_BUS_SUPPORT) != SDMMC_ALLZERO) + if((scr[1] & SD_WIDE_BUS_SUPPORT) != SD_ALLZERO) { /* Send CMD55 APP_CMD with argument as card's RCA.*/ - errorstate = SDMMC_CmdAppCommand(hsd->Instance, (uint32_t)(hsd->SdCard.RelCardAdd << 16U)); - if(errorstate != HAL_OK) + sdio_cmdinitstructure.Argument = (uint32_t)(hsd->RCA << 16); + sdio_cmdinitstructure.CmdIndex = SD_CMD_APP_CMD; + sdio_cmdinitstructure.Response = SDIO_RESPONSE_SHORT; + sdio_cmdinitstructure.WaitForInterrupt = SDIO_WAIT_NO; + sdio_cmdinitstructure.CPSM = SDIO_CPSM_ENABLE; + SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure); + + /* Check for error conditions */ + errorstate = SD_CmdResp1Error(hsd, SD_CMD_APP_CMD); + + if(errorstate != SD_OK) { return errorstate; } /* Send ACMD6 APP_CMD with argument as 2 for wide bus mode */ - errorstate = SDMMC_CmdBusWidth(hsd->Instance, 2U); - if(errorstate != HAL_OK) + sdio_cmdinitstructure.Argument = 2; + sdio_cmdinitstructure.CmdIndex = SD_CMD_APP_SD_SET_BUSWIDTH; + SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure); + + /* Check for error conditions */ + errorstate = SD_CmdResp1Error(hsd, SD_CMD_APP_SD_SET_BUSWIDTH); + + if(errorstate != SD_OK) { return errorstate; } - - return HAL_SD_ERROR_NONE; + + return errorstate; } else { - return HAL_SD_ERROR_REQUEST_NOT_APPLICABLE; + errorstate = SD_REQUEST_NOT_APPLICABLE; + + return errorstate; } -} +} /** * @brief Disables the SDIO wide bus mode. - * @param hsd: Pointer to SD handle - * @retval error state + * @param hsd: SD handle + * @retval SD Card error state */ -static uint32_t SD_WideBus_Disable(SD_HandleTypeDef *hsd) +static HAL_SD_ErrorTypedef SD_WideBus_Disable(SD_HandleTypeDef *hsd) { - uint32_t scr[2U] = {0U, 0U}; - uint32_t errorstate = HAL_SD_ERROR_NONE; + SDIO_CmdInitTypeDef sdio_cmdinitstructure = {0}; + HAL_SD_ErrorTypedef errorstate = SD_OK; + + uint32_t scr[2] = {0, 0}; - if((SDIO_GetResponse(hsd->Instance, SDIO_RESP1) & SDMMC_CARD_LOCKED) == SDMMC_CARD_LOCKED) + if((SDIO_GetResponse(hsd->Instance, SDIO_RESP1) & SD_CARD_LOCKED) == SD_CARD_LOCKED) { - return HAL_SD_ERROR_LOCK_UNLOCK_FAILED; + errorstate = SD_LOCK_UNLOCK_FAILED; + + return errorstate; } /* Get SCR Register */ errorstate = SD_FindSCR(hsd, scr); - if(errorstate != HAL_OK) + + if(errorstate != SD_OK) { return errorstate; } /* If requested card supports 1 bit mode operation */ - if((scr[1U] & SDMMC_SINGLE_BUS_SUPPORT) != SDMMC_ALLZERO) + if((scr[1] & SD_SINGLE_BUS_SUPPORT) != SD_ALLZERO) { /* Send CMD55 APP_CMD with argument as card's RCA */ - errorstate = SDMMC_CmdAppCommand(hsd->Instance, (uint32_t)(hsd->SdCard.RelCardAdd << 16U)); - if(errorstate != HAL_OK) + sdio_cmdinitstructure.Argument = (uint32_t)(hsd->RCA << 16); + sdio_cmdinitstructure.CmdIndex = SD_CMD_APP_CMD; + sdio_cmdinitstructure.Response = SDIO_RESPONSE_SHORT; + sdio_cmdinitstructure.WaitForInterrupt = SDIO_WAIT_NO; + sdio_cmdinitstructure.CPSM = SDIO_CPSM_ENABLE; + SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure); + + /* Check for error conditions */ + errorstate = SD_CmdResp1Error(hsd, SD_CMD_APP_CMD); + + if(errorstate != SD_OK) { return errorstate; } /* Send ACMD6 APP_CMD with argument as 0 for single bus mode */ - errorstate = SDMMC_CmdBusWidth(hsd->Instance, 0U); - if(errorstate != HAL_OK) + sdio_cmdinitstructure.Argument = 0; + sdio_cmdinitstructure.CmdIndex = SD_CMD_APP_SD_SET_BUSWIDTH; + SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure); + + /* Check for error conditions */ + errorstate = SD_CmdResp1Error(hsd, SD_CMD_APP_SD_SET_BUSWIDTH); + + if(errorstate != SD_OK) { return errorstate; } - return HAL_SD_ERROR_NONE; + return errorstate; } else { - return HAL_SD_ERROR_REQUEST_NOT_APPLICABLE; + errorstate = SD_REQUEST_NOT_APPLICABLE; + + return errorstate; } } /** * @brief Finds the SD card SCR register value. - * @param hsd: Pointer to SD handle + * @param hsd: SD handle * @param pSCR: pointer to the buffer that will contain the SCR value - * @retval error state + * @retval SD Card error state */ -static uint32_t SD_FindSCR(SD_HandleTypeDef *hsd, uint32_t *pSCR) +static HAL_SD_ErrorTypedef SD_FindSCR(SD_HandleTypeDef *hsd, uint32_t *pSCR) { - SDIO_DataInitTypeDef config; - uint32_t errorstate = HAL_SD_ERROR_NONE; - uint32_t tickstart = HAL_GetTick(); - uint32_t index = 0U; - uint32_t tempscr[2U] = {0U, 0U}; + SDIO_CmdInitTypeDef sdio_cmdinitstructure = {0}; + SDIO_DataInitTypeDef sdio_datainitstructure = {0}; + HAL_SD_ErrorTypedef errorstate = SD_OK; + uint32_t index = 0; + uint32_t tempscr[2] = {0, 0}; /* Set Block Size To 8 Bytes */ - errorstate = SDMMC_CmdBlockLength(hsd->Instance, 8U); - if(errorstate != HAL_OK) + /* Send CMD55 APP_CMD with argument as card's RCA */ + sdio_cmdinitstructure.Argument = (uint32_t)8; + sdio_cmdinitstructure.CmdIndex = SD_CMD_SET_BLOCKLEN; + sdio_cmdinitstructure.Response = SDIO_RESPONSE_SHORT; + sdio_cmdinitstructure.WaitForInterrupt = SDIO_WAIT_NO; + sdio_cmdinitstructure.CPSM = SDIO_CPSM_ENABLE; + SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure); + + /* Check for error conditions */ + errorstate = SD_CmdResp1Error(hsd, SD_CMD_SET_BLOCKLEN); + + if(errorstate != SD_OK) { return errorstate; } - + /* Send CMD55 APP_CMD with argument as card's RCA */ - errorstate = SDMMC_CmdAppCommand(hsd->Instance, (uint32_t)((hsd->SdCard.RelCardAdd) << 16U)); - if(errorstate != HAL_OK) + sdio_cmdinitstructure.Argument = (uint32_t)((hsd->RCA) << 16); + sdio_cmdinitstructure.CmdIndex = SD_CMD_APP_CMD; + SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure); + + /* Check for error conditions */ + errorstate = SD_CmdResp1Error(hsd, SD_CMD_APP_CMD); + + if(errorstate != SD_OK) { return errorstate; } - - config.DataTimeOut = SDMMC_DATATIMEOUT; - config.DataLength = 8U; - config.DataBlockSize = SDIO_DATABLOCK_SIZE_8B; - config.TransferDir = SDIO_TRANSFER_DIR_TO_SDIO; - config.TransferMode = SDIO_TRANSFER_MODE_BLOCK; - config.DPSM = SDIO_DPSM_ENABLE; - SDIO_ConfigData(hsd->Instance, &config); + sdio_datainitstructure.DataTimeOut = SD_DATATIMEOUT; + sdio_datainitstructure.DataLength = 8; + sdio_datainitstructure.DataBlockSize = SDIO_DATABLOCK_SIZE_8B; + sdio_datainitstructure.TransferDir = SDIO_TRANSFER_DIR_TO_SDIO; + sdio_datainitstructure.TransferMode = SDIO_TRANSFER_MODE_BLOCK; + sdio_datainitstructure.DPSM = SDIO_DPSM_ENABLE; + SDIO_DataConfig(hsd->Instance, &sdio_datainitstructure); /* Send ACMD51 SD_APP_SEND_SCR with argument as 0 */ - errorstate = SDMMC_CmdSendSCR(hsd->Instance); - if(errorstate != HAL_OK) + sdio_cmdinitstructure.Argument = 0; + sdio_cmdinitstructure.CmdIndex = SD_CMD_SD_APP_SEND_SCR; + SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure); + + /* Check for error conditions */ + errorstate = SD_CmdResp1Error(hsd, SD_CMD_SD_APP_SEND_SCR); + + if(errorstate != SD_OK) { return errorstate; } - while(!__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_RXOVERR | SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DTIMEOUT | SDIO_FLAG_DBCKEND)) + while(!__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_RXOVERR | SDIO_FLAG_DCRCFAIL | SDIO_FLAG_DTIMEOUT | SDIO_FLAG_DBCKEND | SDIO_FLAG_STBITERR)) { - if(__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_RXDAVL)) + if(__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_RXDAVL)) { *(tempscr + index) = SDIO_ReadFIFO(hsd->Instance); index++; } - - if((HAL_GetTick() - tickstart) >= SDMMC_DATATIMEOUT) - { - return HAL_SD_ERROR_TIMEOUT; - } } - if(__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_DTIMEOUT)) + if(__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_DTIMEOUT)) + { + __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_DTIMEOUT); + + errorstate = SD_DATA_TIMEOUT; + + return errorstate; + } + else if(__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_DCRCFAIL)) { - __HAL_SD_CLEAR_FLAG(hsd, SDIO_FLAG_DTIMEOUT); + __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_DCRCFAIL); + + errorstate = SD_DATA_CRC_FAIL; - return HAL_SD_ERROR_DATA_TIMEOUT; + return errorstate; } - else if(__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_DCRCFAIL)) + else if(__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_RXOVERR)) { - __HAL_SD_CLEAR_FLAG(hsd, SDIO_FLAG_DCRCFAIL); + __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_RXOVERR); + + errorstate = SD_RX_OVERRUN; - return HAL_SD_ERROR_DATA_CRC_FAIL; + return errorstate; } - else if(__HAL_SD_GET_FLAG(hsd, SDIO_FLAG_RXOVERR)) + else if(__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_STBITERR)) { - __HAL_SD_CLEAR_FLAG(hsd, SDIO_FLAG_RXOVERR); + __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_STBITERR); + + errorstate = SD_START_BIT_ERR; - return HAL_SD_ERROR_RX_OVERRUN; + return errorstate; } else { /* No error flag set */ - /* Clear all the static flags */ - __HAL_SD_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); - - *(pSCR + 1U) = ((tempscr[0U] & SDMMC_0TO7BITS) << 24U) | ((tempscr[0U] & SDMMC_8TO15BITS) << 8U) |\ - ((tempscr[0U] & SDMMC_16TO23BITS) >> 8U) | ((tempscr[0U] & SDMMC_24TO31BITS) >> 24U); - - *(pSCR) = ((tempscr[1U] & SDMMC_0TO7BITS) << 24U) | ((tempscr[1U] & SDMMC_8TO15BITS) << 8U) |\ - ((tempscr[1U] & SDMMC_16TO23BITS) >> 8U) | ((tempscr[1U] & SDMMC_24TO31BITS) >> 24U); } - - return HAL_SD_ERROR_NONE; + + /* Clear all the static flags */ + __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); + + *(pSCR + 1) = ((tempscr[0] & SD_0TO7BITS) << 24) | ((tempscr[0] & SD_8TO15BITS) << 8) |\ + ((tempscr[0] & SD_16TO23BITS) >> 8) | ((tempscr[0] & SD_24TO31BITS) >> 24); + + *(pSCR) = ((tempscr[1] & SD_0TO7BITS) << 24) | ((tempscr[1] & SD_8TO15BITS) << 8) |\ + ((tempscr[1] & SD_16TO23BITS) >> 8) | ((tempscr[1] & SD_24TO31BITS) >> 24); + + return errorstate; } /** - * @brief Wrap up reading in non-blocking mode. - * @param hsd: pointer to a SD_HandleTypeDef structure that contains - * the configuration information. - * @retval HAL status + * @brief Checks if the SD card is in programming state. + * @param hsd: SD handle + * @param pStatus: pointer to the variable that will contain the SD card state + * @retval SD Card error state */ -static HAL_StatusTypeDef SD_Read_IT(SD_HandleTypeDef *hsd) +static HAL_SD_ErrorTypedef SD_IsCardProgramming(SD_HandleTypeDef *hsd, uint8_t *pStatus) { - uint32_t count = 0U; - uint32_t* tmp; - - tmp = (uint32_t*)hsd->pRxBuffPtr; + SDIO_CmdInitTypeDef sdio_cmdinitstructure = {0}; + HAL_SD_ErrorTypedef errorstate = SD_OK; + __IO uint32_t responseR1 = 0; + + sdio_cmdinitstructure.Argument = (uint32_t)(hsd->RCA << 16); + sdio_cmdinitstructure.CmdIndex = SD_CMD_SEND_STATUS; + sdio_cmdinitstructure.Response = SDIO_RESPONSE_SHORT; + sdio_cmdinitstructure.WaitForInterrupt = SDIO_WAIT_NO; + sdio_cmdinitstructure.CPSM = SDIO_CPSM_ENABLE; + SDIO_SendCommand(hsd->Instance, &sdio_cmdinitstructure); + + while(!__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_CCRCFAIL | SDIO_FLAG_CMDREND | SDIO_FLAG_CTIMEOUT)) + { + } - /* Read data from SDIO Rx FIFO */ - for(count = 0U; count < 8U; count++) + if(__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_CTIMEOUT)) + { + errorstate = SD_CMD_RSP_TIMEOUT; + + __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_CTIMEOUT); + + return errorstate; + } + else if(__HAL_SD_SDIO_GET_FLAG(hsd, SDIO_FLAG_CCRCFAIL)) + { + errorstate = SD_CMD_CRC_FAIL; + + __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_FLAG_CCRCFAIL); + + return errorstate; + } + else { - *(tmp + count) = SDIO_ReadFIFO(hsd->Instance); + /* No error flag set */ } - hsd->pRxBuffPtr += 8U; + /* Check response received is of desired command */ + if((uint32_t)SDIO_GetCommandResponse(hsd->Instance) != SD_CMD_SEND_STATUS) + { + errorstate = SD_ILLEGAL_CMD; + + return errorstate; + } + + /* Clear all the static flags */ + __HAL_SD_SDIO_CLEAR_FLAG(hsd, SDIO_STATIC_FLAGS); - return HAL_OK; -} - -/** - * @brief Wrap up writing in non-blocking mode. - * @param hsd: pointer to a SD_HandleTypeDef structure that contains - * the configuration information. - * @retval HAL status - */ -static HAL_StatusTypeDef SD_Write_IT(SD_HandleTypeDef *hsd) -{ - uint32_t count = 0U; - uint32_t* tmp; - tmp = (uint32_t*)hsd->pTxBuffPtr; + /* We have received response, retrieve it for analysis */ + responseR1 = SDIO_GetResponse(hsd->Instance, SDIO_RESP1); - /* Write data to SDIO Tx FIFO */ - for(count = 0U; count < 8U; count++) + /* Find out card status */ + *pStatus = (uint8_t)((responseR1 >> 9) & 0x0000000F); + + if((responseR1 & SD_OCR_ERRORBITS) == SD_ALLZERO) { - SDIO_WriteFIFO(hsd->Instance, (tmp + count)); + return errorstate; } - hsd->pTxBuffPtr += 8U; + if((responseR1 & SD_OCR_ADDR_OUT_OF_RANGE) == SD_OCR_ADDR_OUT_OF_RANGE) + { + return(SD_ADDR_OUT_OF_RANGE); + } - return HAL_OK; -} + if((responseR1 & SD_OCR_ADDR_MISALIGNED) == SD_OCR_ADDR_MISALIGNED) + { + return(SD_ADDR_MISALIGNED); + } + + if((responseR1 & SD_OCR_BLOCK_LEN_ERR) == SD_OCR_BLOCK_LEN_ERR) + { + return(SD_BLOCK_LEN_ERR); + } + + if((responseR1 & SD_OCR_ERASE_SEQ_ERR) == SD_OCR_ERASE_SEQ_ERR) + { + return(SD_ERASE_SEQ_ERR); + } + + if((responseR1 & SD_OCR_BAD_ERASE_PARAM) == SD_OCR_BAD_ERASE_PARAM) + { + return(SD_BAD_ERASE_PARAM); + } + + if((responseR1 & SD_OCR_WRITE_PROT_VIOLATION) == SD_OCR_WRITE_PROT_VIOLATION) + { + return(SD_WRITE_PROT_VIOLATION); + } + + if((responseR1 & SD_OCR_LOCK_UNLOCK_FAILED) == SD_OCR_LOCK_UNLOCK_FAILED) + { + return(SD_LOCK_UNLOCK_FAILED); + } + + if((responseR1 & SD_OCR_COM_CRC_FAILED) == SD_OCR_COM_CRC_FAILED) + { + return(SD_COM_CRC_FAILED); + } + + if((responseR1 & SD_OCR_ILLEGAL_CMD) == SD_OCR_ILLEGAL_CMD) + { + return(SD_ILLEGAL_CMD); + } + + if((responseR1 & SD_OCR_CARD_ECC_FAILED) == SD_OCR_CARD_ECC_FAILED) + { + return(SD_CARD_ECC_FAILED); + } + + if((responseR1 & SD_OCR_CC_ERROR) == SD_OCR_CC_ERROR) + { + return(SD_CC_ERROR); + } + + if((responseR1 & SD_OCR_GENERAL_UNKNOWN_ERROR) == SD_OCR_GENERAL_UNKNOWN_ERROR) + { + return(SD_GENERAL_UNKNOWN_ERROR); + } + + if((responseR1 & SD_OCR_STREAM_READ_UNDERRUN) == SD_OCR_STREAM_READ_UNDERRUN) + { + return(SD_STREAM_READ_UNDERRUN); + } + + if((responseR1 & SD_OCR_STREAM_WRITE_OVERRUN) == SD_OCR_STREAM_WRITE_OVERRUN) + { + return(SD_STREAM_WRITE_OVERRUN); + } + + if((responseR1 & SD_OCR_CID_CSD_OVERWRITE) == SD_OCR_CID_CSD_OVERWRITE) + { + return(SD_CID_CSD_OVERWRITE); + } + + if((responseR1 & SD_OCR_WP_ERASE_SKIP) == SD_OCR_WP_ERASE_SKIP) + { + return(SD_WP_ERASE_SKIP); + } + + if((responseR1 & SD_OCR_CARD_ECC_DISABLED) == SD_OCR_CARD_ECC_DISABLED) + { + return(SD_CARD_ECC_DISABLED); + } + + if((responseR1 & SD_OCR_ERASE_RESET) == SD_OCR_ERASE_RESET) + { + return(SD_ERASE_RESET); + } + + if((responseR1 & SD_OCR_AKE_SEQ_ERROR) == SD_OCR_AKE_SEQ_ERROR) + { + return(SD_AKE_SEQ_ERROR); + } + + return errorstate; +} /** * @} */ - + #endif /* STM32F103xE || STM32F103xG */ #endif /* HAL_SD_MODULE_ENABLED */ diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_sd.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_sd.h index 1084d683c41..a57a7a384b5 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_sd.h +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_sd.h @@ -2,13 +2,13 @@ ****************************************************************************** * @file stm32f1xx_hal_sd.h * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief Header file of SD HAL module. ****************************************************************************** * @attention * - *

© COPYRIGHT(c) 2017 STMicroelectronics

+ *

© COPYRIGHT(c) 2016 STMicroelectronics

* * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: @@ -52,8 +52,7 @@ * @{ */ -/** @defgroup SD SD - * @brief SD HAL module driver +/** @addtogroup SD * @{ */ @@ -62,116 +61,45 @@ * @{ */ -/** @defgroup SD_Exported_Types_Group1 SD State enumeration structure - * @{ - */ -typedef enum -{ - HAL_SD_STATE_RESET = 0x00000000U, /*!< SD not yet initialized or disabled */ - HAL_SD_STATE_READY = 0x00000001U, /*!< SD initialized and ready for use */ - HAL_SD_STATE_TIMEOUT = 0x00000002U, /*!< SD Timeout state */ - HAL_SD_STATE_BUSY = 0x00000003U, /*!< SD process ongoing */ - HAL_SD_STATE_PROGRAMMING = 0x00000004U, /*!< SD Programming State */ - HAL_SD_STATE_RECEIVING = 0x00000005U, /*!< SD Receinving State */ - HAL_SD_STATE_TRANSFER = 0x00000006U, /*!< SD Transfert State */ - HAL_SD_STATE_ERROR = 0x0000000FU /*!< SD is in error state */ -}HAL_SD_StateTypeDef; -/** - * @} - */ - -/** @defgroup SD_Exported_Types_Group2 SD Card State enumeration structure - * @{ - */ -typedef enum -{ - HAL_SD_CARD_READY = 0x00000001U, /*!< Card state is ready */ - HAL_SD_CARD_IDENTIFICATION = 0x00000002U, /*!< Card is in identification state */ - HAL_SD_CARD_STANDBY = 0x00000003U, /*!< Card is in standby state */ - HAL_SD_CARD_TRANSFER = 0x00000004U, /*!< Card is in transfer state */ - HAL_SD_CARD_SENDING = 0x00000005U, /*!< Card is sending an operation */ - HAL_SD_CARD_RECEIVING = 0x00000006U, /*!< Card is receiving operation information */ - HAL_SD_CARD_PROGRAMMING = 0x00000007U, /*!< Card is in programming state */ - HAL_SD_CARD_DISCONNECTED = 0x00000008U, /*!< Card is disconnected */ - HAL_SD_CARD_ERROR = 0x000000FFU /*!< Card response Error */ -}HAL_SD_CardStateTypeDef; -/** - * @} - */ - -/** @defgroup SD_Exported_Types_Group3 SD Handle Structure definition - * @{ - */ #define SD_InitTypeDef SDIO_InitTypeDef #define SD_TypeDef SDIO_TypeDef /** - * @brief SD Card Information Structure definition + * @brief SDIO Handle Structure definition */ typedef struct { - uint32_t CardType; /*!< Specifies the card Type */ + SD_TypeDef *Instance; /*!< SDIO register base address */ - uint32_t CardVersion; /*!< Specifies the card version */ - - uint32_t Class; /*!< Specifies the class of the card class */ - - uint32_t RelCardAdd; /*!< Specifies the Relative Card Address */ + SD_InitTypeDef Init; /*!< SD required parameters */ - uint32_t BlockNbr; /*!< Specifies the Card Capacity in blocks */ - - uint32_t BlockSize; /*!< Specifies one block size in bytes */ + HAL_LockTypeDef Lock; /*!< SD locking object */ - uint32_t LogBlockNbr; /*!< Specifies the Card logical Capacity in blocks */ - - uint32_t LogBlockSize; /*!< Specifies logical block size in bytes */ - -}HAL_SD_CardInfoTypeDef; - -/** - * @brief SD handle Structure definition - */ -typedef struct -{ - SD_TypeDef *Instance; /*!< SD registers base address */ + uint32_t CardType; /*!< SD card type */ - SD_InitTypeDef Init; /*!< SD required parameters */ + uint32_t RCA; /*!< SD relative card address */ - HAL_LockTypeDef Lock; /*!< SD locking object */ + uint32_t CSD[4]; /*!< SD card specific data table */ - uint32_t *pTxBuffPtr; /*!< Pointer to SD Tx transfer Buffer */ - - uint32_t TxXferSize; /*!< SD Tx Transfer size */ - - uint32_t *pRxBuffPtr; /*!< Pointer to SD Rx transfer Buffer */ - - uint32_t RxXferSize; /*!< SD Rx Transfer size */ + uint32_t CID[4]; /*!< SD card identification number table */ - __IO uint32_t Context; /*!< SD transfer context */ - - __IO HAL_SD_StateTypeDef State; /*!< SD card State */ + __IO uint32_t SdTransferCplt; /*!< SD transfer complete flag in non blocking mode */ - __IO uint32_t ErrorCode; /*!< SD Card Error codes */ - - DMA_HandleTypeDef *hdmarx; /*!< SD Rx DMA handle parameters */ + __IO uint32_t SdTransferErr; /*!< SD transfer error flag in non blocking mode */ - DMA_HandleTypeDef *hdmatx; /*!< SD Tx DMA handle parameters */ + __IO uint32_t DmaTransferCplt; /*!< SD DMA transfer complete flag */ - HAL_SD_CardInfoTypeDef SdCard; /*!< SD Card information */ + __IO uint32_t SdOperation; /*!< SD transfer operation (read/write) */ - uint32_t CSD[4]; /*!< SD card specific data table */ + DMA_HandleTypeDef *hdmarx; /*!< SD Rx DMA handle parameters */ - uint32_t CID[4]; /*!< SD card identification number table */ + DMA_HandleTypeDef *hdmatx; /*!< SD Tx DMA handle parameters */ }SD_HandleTypeDef; /** - * @} - */ - -/** @defgroup SD_Exported_Types_Group4 Card Specific Data: CSD Register - * @{ - */ + * @brief Card Specific Data: CSD Register + */ typedef struct { __IO uint8_t CSDStruct; /*!< CSD structure */ @@ -211,14 +139,11 @@ typedef struct __IO uint8_t ECC; /*!< ECC code */ __IO uint8_t CSD_CRC; /*!< CSD CRC */ __IO uint8_t Reserved4; /*!< Always 1 */ - -}HAL_SD_CardCSDTypeDef; -/** - * @} - */ -/** @defgroup SD_Exported_Types_Group5 Card Identification Data: CID Register - * @{ +}HAL_SD_CSDTypedef; + +/** + * @brief Card Identification Data: CID Register */ typedef struct { @@ -233,160 +158,287 @@ typedef struct __IO uint8_t CID_CRC; /*!< CID CRC */ __IO uint8_t Reserved2; /*!< Always 1 */ -}HAL_SD_CardCIDTypeDef; +}HAL_SD_CIDTypedef; + /** - * @} + * @brief SD Card Status returned by ACMD13 */ +typedef struct +{ + __IO uint8_t DAT_BUS_WIDTH; /*!< Shows the currently defined data bus width */ + __IO uint8_t SECURED_MODE; /*!< Card is in secured mode of operation */ + __IO uint16_t SD_CARD_TYPE; /*!< Carries information about card type */ + __IO uint32_t SIZE_OF_PROTECTED_AREA; /*!< Carries information about the capacity of protected area */ + __IO uint8_t SPEED_CLASS; /*!< Carries information about the speed class of the card */ + __IO uint8_t PERFORMANCE_MOVE; /*!< Carries information about the card's performance move */ + __IO uint8_t AU_SIZE; /*!< Carries information about the card's allocation unit size */ + __IO uint16_t ERASE_SIZE; /*!< Determines the number of AUs to be erased in one operation */ + __IO uint8_t ERASE_TIMEOUT; /*!< Determines the timeout for any number of AU erase */ + __IO uint8_t ERASE_OFFSET; /*!< Carries information about the erase offset */ + +}HAL_SD_CardStatusTypedef; -/** @defgroup SD_Exported_Types_Group6 SD Card Status returned by ACMD13 - * @{ +/** + * @brief SD Card information structure */ typedef struct { - __IO uint8_t DataBusWidth; /*!< Shows the currently defined data bus width */ - __IO uint8_t SecuredMode; /*!< Card is in secured mode of operation */ - __IO uint16_t CardType; /*!< Carries information about card type */ - __IO uint32_t ProtectedAreaSize; /*!< Carries information about the capacity of protected area */ - __IO uint8_t SpeedClass; /*!< Carries information about the speed class of the card */ - __IO uint8_t PerformanceMove; /*!< Carries information about the card's performance move */ - __IO uint8_t AllocationUnitSize; /*!< Carries information about the card's allocation unit size */ - __IO uint16_t EraseSize; /*!< Determines the number of AUs to be erased in one operation */ - __IO uint8_t EraseTimeout; /*!< Determines the timeout for any number of AU erase */ - __IO uint8_t EraseOffset; /*!< Carries information about the erase offset */ - -}HAL_SD_CardStatusTypeDef; + HAL_SD_CSDTypedef SD_csd; /*!< SD card specific data register */ + HAL_SD_CIDTypedef SD_cid; /*!< SD card identification number register */ + uint64_t CardCapacity; /*!< Card capacity */ + uint32_t CardBlockSize; /*!< Card block size */ + uint16_t RCA; /*!< SD relative card address */ + uint8_t CardType; /*!< SD card type */ + +}HAL_SD_CardInfoTypedef; + /** - * @} + * @brief SD Error status enumeration Structure definition */ +typedef enum +{ +/** + * @brief SD specific error defines + */ + SD_CMD_CRC_FAIL = (1), /*!< Command response received (but CRC check failed) */ + SD_DATA_CRC_FAIL = (2), /*!< Data block sent/received (CRC check failed) */ + SD_CMD_RSP_TIMEOUT = (3), /*!< Command response timeout */ + SD_DATA_TIMEOUT = (4), /*!< Data timeout */ + SD_TX_UNDERRUN = (5), /*!< Transmit FIFO underrun */ + SD_RX_OVERRUN = (6), /*!< Receive FIFO overrun */ + SD_START_BIT_ERR = (7), /*!< Start bit not detected on all data signals in wide bus mode */ + SD_CMD_OUT_OF_RANGE = (8), /*!< Command's argument was out of range. */ + SD_ADDR_MISALIGNED = (9), /*!< Misaligned address */ + SD_BLOCK_LEN_ERR = (10), /*!< Transferred block length is not allowed for the card or the number of transferred bytes does not match the block length */ + SD_ERASE_SEQ_ERR = (11), /*!< An error in the sequence of erase command occurs. */ + SD_BAD_ERASE_PARAM = (12), /*!< An invalid selection for erase groups */ + SD_WRITE_PROT_VIOLATION = (13), /*!< Attempt to program a write protect block */ + SD_LOCK_UNLOCK_FAILED = (14), /*!< Sequence or password error has been detected in unlock command or if there was an attempt to access a locked card */ + SD_COM_CRC_FAILED = (15), /*!< CRC check of the previous command failed */ + SD_ILLEGAL_CMD = (16), /*!< Command is not legal for the card state */ + SD_CARD_ECC_FAILED = (17), /*!< Card internal ECC was applied but failed to correct the data */ + SD_CC_ERROR = (18), /*!< Internal card controller error */ + SD_GENERAL_UNKNOWN_ERROR = (19), /*!< General or unknown error */ + SD_STREAM_READ_UNDERRUN = (20), /*!< The card could not sustain data transfer in stream read operation. */ + SD_STREAM_WRITE_OVERRUN = (21), /*!< The card could not sustain data programming in stream mode */ + SD_CID_CSD_OVERWRITE = (22), /*!< CID/CSD overwrite error */ + SD_WP_ERASE_SKIP = (23), /*!< Only partial address space was erased */ + SD_CARD_ECC_DISABLED = (24), /*!< Command has been executed without using internal ECC */ + SD_ERASE_RESET = (25), /*!< Erase sequence was cleared before executing because an out of erase sequence command was received */ + SD_AKE_SEQ_ERROR = (26), /*!< Error in sequence of authentication. */ + SD_INVALID_VOLTRANGE = (27), + SD_ADDR_OUT_OF_RANGE = (28), + SD_SWITCH_ERROR = (29), + SD_SDIO_DISABLED = (30), + SD_SDIO_FUNCTION_BUSY = (31), + SD_SDIO_FUNCTION_FAILED = (32), + SD_SDIO_UNKNOWN_FUNCTION = (33), /** - * @} - */ + * @brief Standard error defines + */ + SD_INTERNAL_ERROR = (34), + SD_NOT_CONFIGURED = (35), + SD_REQUEST_PENDING = (36), + SD_REQUEST_NOT_APPLICABLE = (37), + SD_INVALID_PARAMETER = (38), + SD_UNSUPPORTED_FEATURE = (39), + SD_UNSUPPORTED_HW = (40), + SD_ERROR = (41), + SD_OK = (0) + +}HAL_SD_ErrorTypedef; -/* Exported constants --------------------------------------------------------*/ -/** @defgroup SD_Exported_Constants Exported Constants - * @{ - */ +/** + * @brief SD Transfer state enumeration structure + */ +typedef enum +{ + SD_TRANSFER_OK = 0, /*!< Transfer success */ + SD_TRANSFER_BUSY = 1, /*!< Transfer is occurring */ + SD_TRANSFER_ERROR = 2 /*!< Transfer failed */ -#define BLOCKSIZE 512U /*!< Block size is 512 bytes */ +}HAL_SD_TransferStateTypedef; -/** @defgroup SD_Exported_Constansts_Group1 SD Error status enumeration Structure definition - * @{ - */ -#define HAL_SD_ERROR_NONE SDMMC_ERROR_NONE /*!< No error */ -#define HAL_SD_ERROR_CMD_CRC_FAIL SDMMC_ERROR_CMD_CRC_FAIL /*!< Command response received (but CRC check failed) */ -#define HAL_SD_ERROR_DATA_CRC_FAIL SDMMC_ERROR_DATA_CRC_FAIL /*!< Data block sent/received (CRC check failed) */ -#define HAL_SD_ERROR_CMD_RSP_TIMEOUT SDMMC_ERROR_CMD_RSP_TIMEOUT /*!< Command response timeout */ -#define HAL_SD_ERROR_DATA_TIMEOUT SDMMC_ERROR_DATA_TIMEOUT /*!< Data timeout */ -#define HAL_SD_ERROR_TX_UNDERRUN SDMMC_ERROR_TX_UNDERRUN /*!< Transmit FIFO underrun */ -#define HAL_SD_ERROR_RX_OVERRUN SDMMC_ERROR_RX_OVERRUN /*!< Receive FIFO overrun */ -#define HAL_SD_ERROR_ADDR_MISALIGNED SDMMC_ERROR_ADDR_MISALIGNED /*!< Misaligned address */ -#define HAL_SD_ERROR_BLOCK_LEN_ERR SDMMC_ERROR_BLOCK_LEN_ERR /*!< Transferred block length is not allowed for the card or the - number of transferred bytes does not match the block length */ -#define HAL_SD_ERROR_ERASE_SEQ_ERR SDMMC_ERROR_ERASE_SEQ_ERR /*!< An error in the sequence of erase command occurs */ -#define HAL_SD_ERROR_BAD_ERASE_PARAM SDMMC_ERROR_BAD_ERASE_PARAM /*!< An invalid selection for erase groups */ -#define HAL_SD_ERROR_WRITE_PROT_VIOLATION SDMMC_ERROR_WRITE_PROT_VIOLATION /*!< Attempt to program a write protect block */ -#define HAL_SD_ERROR_LOCK_UNLOCK_FAILED SDMMC_ERROR_LOCK_UNLOCK_FAILED /*!< Sequence or password error has been detected in unlock - command or if there was an attempt to access a locked card */ -#define HAL_SD_ERROR_COM_CRC_FAILED SDMMC_ERROR_COM_CRC_FAILED /*!< CRC check of the previous command failed */ -#define HAL_SD_ERROR_ILLEGAL_CMD SDMMC_ERROR_ILLEGAL_CMD /*!< Command is not legal for the card state */ -#define HAL_SD_ERROR_CARD_ECC_FAILED SDMMC_ERROR_CARD_ECC_FAILED /*!< Card internal ECC was applied but failed to correct the data */ -#define HAL_SD_ERROR_CC_ERR SDMMC_ERROR_CC_ERR /*!< Internal card controller error */ -#define HAL_SD_ERROR_GENERAL_UNKNOWN_ERR SDMMC_ERROR_GENERAL_UNKNOWN_ERR /*!< General or unknown error */ -#define HAL_SD_ERROR_STREAM_READ_UNDERRUN SDMMC_ERROR_STREAM_READ_UNDERRUN /*!< The card could not sustain data reading in stream rmode */ -#define HAL_SD_ERROR_STREAM_WRITE_OVERRUN SDMMC_ERROR_STREAM_WRITE_OVERRUN /*!< The card could not sustain data programming in stream mode */ -#define HAL_SD_ERROR_CID_CSD_OVERWRITE SDMMC_ERROR_CID_CSD_OVERWRITE /*!< CID/CSD overwrite error */ -#define HAL_SD_ERROR_WP_ERASE_SKIP SDMMC_ERROR_WP_ERASE_SKIP /*!< Only partial address space was erased */ -#define HAL_SD_ERROR_CARD_ECC_DISABLED SDMMC_ERROR_CARD_ECC_DISABLED /*!< Command has been executed without using internal ECC */ -#define HAL_SD_ERROR_ERASE_RESET SDMMC_ERROR_ERASE_RESET /*!< Erase sequence was cleared before executing because an out - of erase sequence command was received */ -#define HAL_SD_ERROR_AKE_SEQ_ERR SDMMC_ERROR_AKE_SEQ_ERR /*!< Error in sequence of authentication */ -#define HAL_SD_ERROR_INVALID_VOLTRANGE SDMMC_ERROR_INVALID_VOLTRANGE /*!< Error in case of invalid voltage range */ -#define HAL_SD_ERROR_ADDR_OUT_OF_RANGE SDMMC_ERROR_ADDR_OUT_OF_RANGE /*!< Error when addressed block is out of range */ -#define HAL_SD_ERROR_REQUEST_NOT_APPLICABLE SDMMC_ERROR_REQUEST_NOT_APPLICABLE /*!< Error when command request is not applicable */ -#define HAL_SD_ERROR_PARAM SDMMC_ERROR_INVALID_PARAMETER /*!< the used parameter is not valid */ -#define HAL_SD_ERROR_UNSUPPORTED_FEATURE SDMMC_ERROR_UNSUPPORTED_FEATURE /*!< Error when feature is not insupported */ -#define HAL_SD_ERROR_BUSY SDMMC_ERROR_BUSY /*!< Error when transfer process is busy */ -#define HAL_SD_ERROR_DMA SDMMC_ERROR_DMA /*!< Error while DMA transfer */ -#define HAL_SD_ERROR_TIMEOUT SDMMC_ERROR_TIMEOUT /*!< Timeout error */ - /** - * @} - */ - -/** @defgroup SD_Exported_Constansts_Group2 SD context enumeration - * @{ - */ -#define SD_CONTEXT_NONE 0x00000000U /*!< None */ -#define SD_CONTEXT_READ_SINGLE_BLOCK 0x00000001U /*!< Read single block operation */ -#define SD_CONTEXT_READ_MULTIPLE_BLOCK 0x00000002U /*!< Read multiple blocks operation */ -#define SD_CONTEXT_WRITE_SINGLE_BLOCK 0x00000010U /*!< Write single block operation */ -#define SD_CONTEXT_WRITE_MULTIPLE_BLOCK 0x00000020U /*!< Write multiple blocks operation */ -#define SD_CONTEXT_IT 0x00000008U /*!< Process in Interrupt mode */ -#define SD_CONTEXT_DMA 0x00000080U /*!< Process in DMA mode */ + * @brief SD Card State enumeration structure + */ +typedef enum +{ + SD_CARD_READY = ((uint32_t)0x00000001), /*!< Card state is ready */ + SD_CARD_IDENTIFICATION = ((uint32_t)0x00000002), /*!< Card is in identification state */ + SD_CARD_STANDBY = ((uint32_t)0x00000003), /*!< Card is in standby state */ + SD_CARD_TRANSFER = ((uint32_t)0x00000004), /*!< Card is in transfer state */ + SD_CARD_SENDING = ((uint32_t)0x00000005), /*!< Card is sending an operation */ + SD_CARD_RECEIVING = ((uint32_t)0x00000006), /*!< Card is receiving operation information */ + SD_CARD_PROGRAMMING = ((uint32_t)0x00000007), /*!< Card is in programming state */ + SD_CARD_DISCONNECTED = ((uint32_t)0x00000008), /*!< Card is disconnected */ + SD_CARD_ERROR = ((uint32_t)0x000000FF) /*!< Card is in error state */ + +}HAL_SD_CardStateTypedef; -/** - * @} - */ +/** + * @brief SD Operation enumeration structure + */ +typedef enum +{ + SD_READ_SINGLE_BLOCK = 0, /*!< Read single block operation */ + SD_READ_MULTIPLE_BLOCK = 1, /*!< Read multiple blocks operation */ + SD_WRITE_SINGLE_BLOCK = 2, /*!< Write single block operation */ + SD_WRITE_MULTIPLE_BLOCK = 3 /*!< Write multiple blocks operation */ + +}HAL_SD_OperationTypedef; -/** @defgroup SD_Exported_Constansts_Group3 SD Supported Memory Cards - * @{ - */ -#define CARD_SDSC 0x00000000U -#define CARD_SDHC_SDXC 0x00000001U -#define CARD_SECURED 0x00000003U - /** * @} */ -/** @defgroup SD_Exported_Constansts_Group4 SD Supported Version +/* Exported constants --------------------------------------------------------*/ +/** @defgroup SD_Exported_Constants SD Exported Constants * @{ */ -#define CARD_V1_X 0x00000000U -#define CARD_V2_X 0x00000001U -/** - * @} + +/** + * @brief SD Commands Index + */ +#define SD_CMD_GO_IDLE_STATE ((uint8_t)0) /*!< Resets the SD memory card. */ +#define SD_CMD_SEND_OP_COND ((uint8_t)1) /*!< Sends host capacity support information and activates the card's initialization process. */ +#define SD_CMD_ALL_SEND_CID ((uint8_t)2) /*!< Asks any card connected to the host to send the CID numbers on the CMD line. */ +#define SD_CMD_SET_REL_ADDR ((uint8_t)3) /*!< Asks the card to publish a new relative address (RCA). */ +#define SD_CMD_SET_DSR ((uint8_t)4) /*!< Programs the DSR of all cards. */ +#define SD_CMD_SDIO_SEN_OP_COND ((uint8_t)5) /*!< Sends host capacity support information (HCS) and asks the accessed card to send its + operating condition register (OCR) content in the response on the CMD line. */ +#define SD_CMD_HS_SWITCH ((uint8_t)6) /*!< Checks switchable function (mode 0) and switch card function (mode 1). */ +#define SD_CMD_SEL_DESEL_CARD ((uint8_t)7) /*!< Selects the card by its own relative address and gets deselected by any other address */ +#define SD_CMD_HS_SEND_EXT_CSD ((uint8_t)8) /*!< Sends SD Memory Card interface condition, which includes host supply voltage information + and asks the card whether card supports voltage. */ +#define SD_CMD_SEND_CSD ((uint8_t)9) /*!< Addressed card sends its card specific data (CSD) on the CMD line. */ +#define SD_CMD_SEND_CID ((uint8_t)10) /*!< Addressed card sends its card identification (CID) on the CMD line. */ +#define SD_CMD_READ_DAT_UNTIL_STOP ((uint8_t)11) /*!< SD card doesn't support it. */ +#define SD_CMD_STOP_TRANSMISSION ((uint8_t)12) /*!< Forces the card to stop transmission. */ +#define SD_CMD_SEND_STATUS ((uint8_t)13) /*!< Addressed card sends its status register. */ +#define SD_CMD_HS_BUSTEST_READ ((uint8_t)14) +#define SD_CMD_GO_INACTIVE_STATE ((uint8_t)15) /*!< Sends an addressed card into the inactive state. */ +#define SD_CMD_SET_BLOCKLEN ((uint8_t)16) /*!< Sets the block length (in bytes for SDSC) for all following block commands + (read, write, lock). Default block length is fixed to 512 Bytes. Not effective + for SDHS and SDXC. */ +#define SD_CMD_READ_SINGLE_BLOCK ((uint8_t)17) /*!< Reads single block of size selected by SET_BLOCKLEN in case of SDSC, and a block of + fixed 512 bytes in case of SDHC and SDXC. */ +#define SD_CMD_READ_MULT_BLOCK ((uint8_t)18) /*!< Continuously transfers data blocks from card to host until interrupted by + STOP_TRANSMISSION command. */ +#define SD_CMD_HS_BUSTEST_WRITE ((uint8_t)19) /*!< 64 bytes tuning pattern is sent for SDR50 and SDR104. */ +#define SD_CMD_WRITE_DAT_UNTIL_STOP ((uint8_t)20) /*!< Speed class control command. */ +#define SD_CMD_SET_BLOCK_COUNT ((uint8_t)23) /*!< Specify block count for CMD18 and CMD25. */ +#define SD_CMD_WRITE_SINGLE_BLOCK ((uint8_t)24) /*!< Writes single block of size selected by SET_BLOCKLEN in case of SDSC, and a block of + fixed 512 bytes in case of SDHC and SDXC. */ +#define SD_CMD_WRITE_MULT_BLOCK ((uint8_t)25) /*!< Continuously writes blocks of data until a STOP_TRANSMISSION follows. */ +#define SD_CMD_PROG_CID ((uint8_t)26) /*!< Reserved for manufacturers. */ +#define SD_CMD_PROG_CSD ((uint8_t)27) /*!< Programming of the programmable bits of the CSD. */ +#define SD_CMD_SET_WRITE_PROT ((uint8_t)28) /*!< Sets the write protection bit of the addressed group. */ +#define SD_CMD_CLR_WRITE_PROT ((uint8_t)29) /*!< Clears the write protection bit of the addressed group. */ +#define SD_CMD_SEND_WRITE_PROT ((uint8_t)30) /*!< Asks the card to send the status of the write protection bits. */ +#define SD_CMD_SD_ERASE_GRP_START ((uint8_t)32) /*!< Sets the address of the first write block to be erased. (For SD card only). */ +#define SD_CMD_SD_ERASE_GRP_END ((uint8_t)33) /*!< Sets the address of the last write block of the continuous range to be erased. */ +#define SD_CMD_ERASE_GRP_START ((uint8_t)35) /*!< Sets the address of the first write block to be erased. Reserved for each command + system set by switch function command (CMD6). */ +#define SD_CMD_ERASE_GRP_END ((uint8_t)36) /*!< Sets the address of the last write block of the continuous range to be erased. + Reserved for each command system set by switch function command (CMD6). */ +#define SD_CMD_ERASE ((uint8_t)38) /*!< Reserved for SD security applications. */ +#define SD_CMD_FAST_IO ((uint8_t)39) /*!< SD card doesn't support it (Reserved). */ +#define SD_CMD_GO_IRQ_STATE ((uint8_t)40) /*!< SD card doesn't support it (Reserved). */ +#define SD_CMD_LOCK_UNLOCK ((uint8_t)42) /*!< Sets/resets the password or lock/unlock the card. The size of the data block is set by + the SET_BLOCK_LEN command. */ +#define SD_CMD_APP_CMD ((uint8_t)55) /*!< Indicates to the card that the next command is an application specific command rather + than a standard command. */ +#define SD_CMD_GEN_CMD ((uint8_t)56) /*!< Used either to transfer a data block to the card or to get a data block from the card + for general purpose/application specific commands. */ +#define SD_CMD_NO_CMD ((uint8_t)64) + +/** + * @brief Following commands are SD Card Specific commands. + * SDIO_APP_CMD should be sent before sending these commands. + */ +#define SD_CMD_APP_SD_SET_BUSWIDTH ((uint8_t)6) /*!< (ACMD6) Defines the data bus width to be used for data transfer. The allowed data bus + widths are given in SCR register. */ +#define SD_CMD_SD_APP_STATUS ((uint8_t)13) /*!< (ACMD13) Sends the SD status. */ +#define SD_CMD_SD_APP_SEND_NUM_WRITE_BLOCKS ((uint8_t)22) /*!< (ACMD22) Sends the number of the written (without errors) write blocks. Responds with + 32bit+CRC data block. */ +#define SD_CMD_SD_APP_OP_COND ((uint8_t)41) /*!< (ACMD41) Sends host capacity support information (HCS) and asks the accessed card to + send its operating condition register (OCR) content in the response on the CMD line. */ +#define SD_CMD_SD_APP_SET_CLR_CARD_DETECT ((uint8_t)42) /*!< (ACMD42) Connects/Disconnects the 50 KOhm pull-up resistor on CD/DAT3 (pin 1) of the card. */ +#define SD_CMD_SD_APP_SEND_SCR ((uint8_t)51) /*!< Reads the SD Configuration Register (SCR). */ +#define SD_CMD_SDIO_RW_DIRECT ((uint8_t)52) /*!< For SD I/O card only, reserved for security specification. */ +#define SD_CMD_SDIO_RW_EXTENDED ((uint8_t)53) /*!< For SD I/O card only, reserved for security specification. */ + +/** + * @brief Following commands are SD Card Specific security commands. + * SD_CMD_APP_CMD should be sent before sending these commands. + */ +#define SD_CMD_SD_APP_GET_MKB ((uint8_t)43) /*!< For SD card only */ +#define SD_CMD_SD_APP_GET_MID ((uint8_t)44) /*!< For SD card only */ +#define SD_CMD_SD_APP_SET_CER_RN1 ((uint8_t)45) /*!< For SD card only */ +#define SD_CMD_SD_APP_GET_CER_RN2 ((uint8_t)46) /*!< For SD card only */ +#define SD_CMD_SD_APP_SET_CER_RES2 ((uint8_t)47) /*!< For SD card only */ +#define SD_CMD_SD_APP_GET_CER_RES1 ((uint8_t)48) /*!< For SD card only */ +#define SD_CMD_SD_APP_SECURE_READ_MULTIPLE_BLOCK ((uint8_t)18) /*!< For SD card only */ +#define SD_CMD_SD_APP_SECURE_WRITE_MULTIPLE_BLOCK ((uint8_t)25) /*!< For SD card only */ +#define SD_CMD_SD_APP_SECURE_ERASE ((uint8_t)38) /*!< For SD card only */ +#define SD_CMD_SD_APP_CHANGE_SECURE_AREA ((uint8_t)49) /*!< For SD card only */ +#define SD_CMD_SD_APP_SECURE_WRITE_MKB ((uint8_t)48) /*!< For SD card only */ + +/** + * @brief Supported SD Memory Cards */ - +#define STD_CAPACITY_SD_CARD_V1_1 ((uint32_t)0x00000000) +#define STD_CAPACITY_SD_CARD_V2_0 ((uint32_t)0x00000001) +#define HIGH_CAPACITY_SD_CARD ((uint32_t)0x00000002) +#define MULTIMEDIA_CARD ((uint32_t)0x00000003) +#define SECURE_DIGITAL_IO_CARD ((uint32_t)0x00000004) +#define HIGH_SPEED_MULTIMEDIA_CARD ((uint32_t)0x00000005) +#define SECURE_DIGITAL_IO_COMBO_CARD ((uint32_t)0x00000006) +#define HIGH_CAPACITY_MMC_CARD ((uint32_t)0x00000007) /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup SD_Exported_macros SD Exported Macros - * @brief macros to handle interrupts and specific clock configurations - * @{ - */ + * @brief macros to handle interrupts and specific clock configurations + * @{ + */ /** * @brief Enable the SD device. + * @param __HANDLE__: SD Handle * @retval None */ -#define __HAL_SD_ENABLE(__HANDLE__) __SDIO_ENABLE((__HANDLE__)->Instance) +#define __HAL_SD_SDIO_ENABLE(__HANDLE__) __SDIO_ENABLE((__HANDLE__)->Instance) /** * @brief Disable the SD device. + * @param __HANDLE__: SD Handle * @retval None */ -#define __HAL_SD_DISABLE(__HANDLE__) __SDIO_DISABLE((__HANDLE__)->Instance) +#define __HAL_SD_SDIO_DISABLE(__HANDLE__) __SDIO_DISABLE((__HANDLE__)->Instance) /** - * @brief Enable the SDMMC DMA transfer. + * @brief Enable the SDIO DMA transfer. + * @param __HANDLE__: SD Handle * @retval None */ -#define __HAL_SD_DMA_ENABLE(__HANDLE__) __SDIO_DMA_ENABLE((__HANDLE__)->Instance) +#define __HAL_SD_SDIO_DMA_ENABLE(__HANDLE__) __SDIO_DMA_ENABLE((__HANDLE__)->Instance) /** - * @brief Disable the SDMMC DMA transfer. + * @brief Disable the SDIO DMA transfer. + * @param __HANDLE__: SD Handle * @retval None */ -#define __HAL_SD_DMA_DISABLE(__HANDLE__) __SDIO_DMA_DISABLE((__HANDLE__)->Instance) +#define __HAL_SD_SDIO_DMA_DISABLE(__HANDLE__) __SDIO_DMA_DISABLE((__HANDLE__)->Instance) /** * @brief Enable the SD device interrupt. * @param __HANDLE__: SD Handle - * @param __INTERRUPT__: specifies the SDMMC interrupt sources to be enabled. + * @param __INTERRUPT__: specifies the SDIO interrupt sources to be enabled. * This parameter can be one or a combination of the following values: * @arg SDIO_IT_CCRCFAIL: Command response received (CRC check failed) interrupt * @arg SDIO_IT_DCRCFAIL: Data block sent/received (CRC check failed) interrupt @@ -397,6 +449,8 @@ typedef struct * @arg SDIO_IT_CMDREND: Command response received (CRC check passed) interrupt * @arg SDIO_IT_CMDSENT: Command sent (no response required) interrupt * @arg SDIO_IT_DATAEND: Data end (data counter, SDIDCOUNT, is zero) interrupt + * @arg SDIO_IT_STBITERR: Start bit not detected on all data signals in wide + * bus mode interrupt * @arg SDIO_IT_DBCKEND: Data block sent/received (CRC check passed) interrupt * @arg SDIO_IT_CMDACT: Command transfer in progress interrupt * @arg SDIO_IT_TXACT: Data transmit in progress interrupt @@ -410,14 +464,15 @@ typedef struct * @arg SDIO_IT_TXDAVL: Data available in transmit FIFO interrupt * @arg SDIO_IT_RXDAVL: Data available in receive FIFO interrupt * @arg SDIO_IT_SDIOIT: SD I/O interrupt received interrupt + * @arg SDIO_IT_CEATAEND: CE-ATA command completion signal received for CMD61 interrupt * @retval None */ -#define __HAL_SD_ENABLE_IT(__HANDLE__, __INTERRUPT__) __SDIO_ENABLE_IT((__HANDLE__)->Instance, (__INTERRUPT__)) +#define __HAL_SD_SDIO_ENABLE_IT(__HANDLE__, __INTERRUPT__) __SDIO_ENABLE_IT((__HANDLE__)->Instance, (__INTERRUPT__)) /** * @brief Disable the SD device interrupt. * @param __HANDLE__: SD Handle - * @param __INTERRUPT__: specifies the SDMMC interrupt sources to be disabled. + * @param __INTERRUPT__: specifies the SDIO interrupt sources to be disabled. * This parameter can be one or a combination of the following values: * @arg SDIO_IT_CCRCFAIL: Command response received (CRC check failed) interrupt * @arg SDIO_IT_DCRCFAIL: Data block sent/received (CRC check failed) interrupt @@ -428,6 +483,8 @@ typedef struct * @arg SDIO_IT_CMDREND: Command response received (CRC check passed) interrupt * @arg SDIO_IT_CMDSENT: Command sent (no response required) interrupt * @arg SDIO_IT_DATAEND: Data end (data counter, SDIDCOUNT, is zero) interrupt + * @arg SDIO_IT_STBITERR: Start bit not detected on all data signals in wide + * bus mode interrupt * @arg SDIO_IT_DBCKEND: Data block sent/received (CRC check passed) interrupt * @arg SDIO_IT_CMDACT: Command transfer in progress interrupt * @arg SDIO_IT_TXACT: Data transmit in progress interrupt @@ -440,10 +497,11 @@ typedef struct * @arg SDIO_IT_RXFIFOE: Receive FIFO empty interrupt * @arg SDIO_IT_TXDAVL: Data available in transmit FIFO interrupt * @arg SDIO_IT_RXDAVL: Data available in receive FIFO interrupt - * @arg SDIO_IT_SDIOIT: SD I/O interrupt received interrupt + * @arg SDIO_IT_SDIOIT: SD I/O interrupt received interrupt + * @arg SDIO_IT_CEATAEND: CE-ATA command completion signal received for CMD61 interrupt * @retval None */ -#define __HAL_SD_DISABLE_IT(__HANDLE__, __INTERRUPT__) __SDIO_DISABLE_IT((__HANDLE__)->Instance, (__INTERRUPT__)) +#define __HAL_SD_SDIO_DISABLE_IT(__HANDLE__, __INTERRUPT__) __SDIO_DISABLE_IT((__HANDLE__)->Instance, (__INTERRUPT__)) /** * @brief Check whether the specified SD flag is set or not. @@ -459,6 +517,7 @@ typedef struct * @arg SDIO_FLAG_CMDREND: Command response received (CRC check passed) * @arg SDIO_FLAG_CMDSENT: Command sent (no response required) * @arg SDIO_FLAG_DATAEND: Data end (data counter, SDIDCOUNT, is zero) + * @arg SDIO_FLAG_STBITERR: Start bit not detected on all data signals in wide bus mode. * @arg SDIO_FLAG_DBCKEND: Data block sent/received (CRC check passed) * @arg SDIO_FLAG_CMDACT: Command transfer in progress * @arg SDIO_FLAG_TXACT: Data transmit in progress @@ -472,9 +531,10 @@ typedef struct * @arg SDIO_FLAG_TXDAVL: Data available in transmit FIFO * @arg SDIO_FLAG_RXDAVL: Data available in receive FIFO * @arg SDIO_FLAG_SDIOIT: SD I/O interrupt received + * @arg SDIO_FLAG_CEATAEND: CE-ATA command completion signal received for CMD61 * @retval The new state of SD FLAG (SET or RESET). */ -#define __HAL_SD_GET_FLAG(__HANDLE__, __FLAG__) __SDIO_GET_FLAG((__HANDLE__)->Instance, (__FLAG__)) +#define __HAL_SD_SDIO_GET_FLAG(__HANDLE__, __FLAG__) __SDIO_GET_FLAG((__HANDLE__)->Instance, (__FLAG__)) /** * @brief Clear the SD's pending flags. @@ -490,16 +550,18 @@ typedef struct * @arg SDIO_FLAG_CMDREND: Command response received (CRC check passed) * @arg SDIO_FLAG_CMDSENT: Command sent (no response required) * @arg SDIO_FLAG_DATAEND: Data end (data counter, SDIDCOUNT, is zero) + * @arg SDIO_FLAG_STBITERR: Start bit not detected on all data signals in wide bus mode * @arg SDIO_FLAG_DBCKEND: Data block sent/received (CRC check passed) * @arg SDIO_FLAG_SDIOIT: SD I/O interrupt received + * @arg SDIO_FLAG_CEATAEND: CE-ATA command completion signal received for CMD61 * @retval None */ -#define __HAL_SD_CLEAR_FLAG(__HANDLE__, __FLAG__) __SDIO_CLEAR_FLAG((__HANDLE__)->Instance, (__FLAG__)) +#define __HAL_SD_SDIO_CLEAR_FLAG(__HANDLE__, __FLAG__) __SDIO_CLEAR_FLAG((__HANDLE__)->Instance, (__FLAG__)) /** * @brief Check whether the specified SD interrupt has occurred or not. * @param __HANDLE__: SD Handle - * @param __INTERRUPT__: specifies the SDMMC interrupt source to check. + * @param __INTERRUPT__: specifies the SDIO interrupt source to check. * This parameter can be one of the following values: * @arg SDIO_IT_CCRCFAIL: Command response received (CRC check failed) interrupt * @arg SDIO_IT_DCRCFAIL: Data block sent/received (CRC check failed) interrupt @@ -510,6 +572,8 @@ typedef struct * @arg SDIO_IT_CMDREND: Command response received (CRC check passed) interrupt * @arg SDIO_IT_CMDSENT: Command sent (no response required) interrupt * @arg SDIO_IT_DATAEND: Data end (data counter, SDIDCOUNT, is zero) interrupt + * @arg SDIO_IT_STBITERR: Start bit not detected on all data signals in wide + * bus mode interrupt * @arg SDIO_IT_DBCKEND: Data block sent/received (CRC check passed) interrupt * @arg SDIO_IT_CMDACT: Command transfer in progress interrupt * @arg SDIO_IT_TXACT: Data transmit in progress interrupt @@ -523,13 +587,14 @@ typedef struct * @arg SDIO_IT_TXDAVL: Data available in transmit FIFO interrupt * @arg SDIO_IT_RXDAVL: Data available in receive FIFO interrupt * @arg SDIO_IT_SDIOIT: SD I/O interrupt received interrupt + * @arg SDIO_IT_CEATAEND: CE-ATA command completion signal received for CMD61 interrupt * @retval The new state of SD IT (SET or RESET). */ -#define __HAL_SD_GET_IT(__HANDLE__, __INTERRUPT__) __SDIO_GET_IT((__HANDLE__)->Instance, (__INTERRUPT__)) +#define __HAL_SD_SDIO_GET_IT (__HANDLE__, __INTERRUPT__) __SDIO_GET_IT ((__HANDLE__)->Instance, __INTERRUPT__) /** * @brief Clear the SD's interrupt pending bits. - * @param __HANDLE__: SD Handle + * @param __HANDLE__ : SD Handle * @param __INTERRUPT__: specifies the interrupt pending bit to clear. * This parameter can be one or a combination of the following values: * @arg SDIO_IT_CCRCFAIL: Command response received (CRC check failed) interrupt @@ -540,161 +605,91 @@ typedef struct * @arg SDIO_IT_RXOVERR: Received FIFO overrun error interrupt * @arg SDIO_IT_CMDREND: Command response received (CRC check passed) interrupt * @arg SDIO_IT_CMDSENT: Command sent (no response required) interrupt - * @arg SDIO_IT_DATAEND: Data end (data counter, SDMMC_DCOUNT, is zero) interrupt + * @arg SDIO_IT_DATAEND: Data end (data counter, SDIO_DCOUNT, is zero) interrupt + * @arg SDIO_IT_STBITERR: Start bit not detected on all data signals in wide + * bus mode interrupt * @arg SDIO_IT_SDIOIT: SD I/O interrupt received interrupt + * @arg SDIO_IT_CEATAEND: CE-ATA command completion signal received for CMD61 * @retval None */ -#define __HAL_SD_CLEAR_IT(__HANDLE__, __INTERRUPT__) __SDIO_CLEAR_IT((__HANDLE__)->Instance, (__INTERRUPT__)) - +#define __HAL_SD_SDIO_CLEAR_IT(__HANDLE__, __INTERRUPT__) __SDIO_CLEAR_IT((__HANDLE__)->Instance, (__INTERRUPT__)) /** * @} */ /* Exported functions --------------------------------------------------------*/ -/** @defgroup SD_Exported_Functions SD Exported Functions +/** @addtogroup SD_Exported_Functions * @{ */ - -/** @defgroup SD_Exported_Functions_Group1 Initialization and de-initialization functions + +/* Initialization and de-initialization functions **********************************/ +/** @addtogroup SD_Exported_Functions_Group1 * @{ */ -HAL_StatusTypeDef HAL_SD_Init(SD_HandleTypeDef *hsd); -HAL_StatusTypeDef HAL_SD_InitCard(SD_HandleTypeDef *hsd); -HAL_StatusTypeDef HAL_SD_DeInit (SD_HandleTypeDef *hsd); +HAL_SD_ErrorTypedef HAL_SD_Init(SD_HandleTypeDef *hsd, HAL_SD_CardInfoTypedef *SDCardInfo); +HAL_StatusTypeDef HAL_SD_DeInit (SD_HandleTypeDef *hsd); void HAL_SD_MspInit(SD_HandleTypeDef *hsd); void HAL_SD_MspDeInit(SD_HandleTypeDef *hsd); /** * @} */ - -/** @defgroup SD_Exported_Functions_Group2 Input and Output operation functions + +/* I/O operation functions *****************************************************/ +/** @addtogroup SD_Exported_Functions_Group2 * @{ */ /* Blocking mode: Polling */ -HAL_StatusTypeDef HAL_SD_ReadBlocks(SD_HandleTypeDef *hsd, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks, uint32_t Timeout); -HAL_StatusTypeDef HAL_SD_WriteBlocks(SD_HandleTypeDef *hsd, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks, uint32_t Timeout); -HAL_StatusTypeDef HAL_SD_Erase(SD_HandleTypeDef *hsd, uint32_t BlockStartAdd, uint32_t BlockEndAdd); -/* Non-Blocking mode: IT */ -HAL_StatusTypeDef HAL_SD_ReadBlocks_IT(SD_HandleTypeDef *hsd, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks); -HAL_StatusTypeDef HAL_SD_WriteBlocks_IT(SD_HandleTypeDef *hsd, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks); -/* Non-Blocking mode: DMA */ -HAL_StatusTypeDef HAL_SD_ReadBlocks_DMA(SD_HandleTypeDef *hsd, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks); -HAL_StatusTypeDef HAL_SD_WriteBlocks_DMA(SD_HandleTypeDef *hsd, uint8_t *pData, uint32_t BlockAdd, uint32_t NumberOfBlocks); +HAL_SD_ErrorTypedef HAL_SD_ReadBlocks(SD_HandleTypeDef *hsd, uint32_t *pReadBuffer, uint64_t ReadAddr, uint32_t BlockSize, uint32_t NumberOfBlocks); +HAL_SD_ErrorTypedef HAL_SD_WriteBlocks(SD_HandleTypeDef *hsd, uint32_t *pWriteBuffer, uint64_t WriteAddr, uint32_t BlockSize, uint32_t NumberOfBlocks); +HAL_SD_ErrorTypedef HAL_SD_Erase(SD_HandleTypeDef *hsd, uint64_t Startaddr, uint64_t Endaddr); +/* Non-Blocking mode: Interrupt */ void HAL_SD_IRQHandler(SD_HandleTypeDef *hsd); /* Callback in non blocking modes (DMA) */ -void HAL_SD_TxCpltCallback(SD_HandleTypeDef *hsd); -void HAL_SD_RxCpltCallback(SD_HandleTypeDef *hsd); -void HAL_SD_ErrorCallback(SD_HandleTypeDef *hsd); -void HAL_SD_AbortCallback(SD_HandleTypeDef *hsd); -/** - * @} - */ - -/** @defgroup SD_Exported_Functions_Group3 Peripheral Control functions - * @{ - */ -HAL_StatusTypeDef HAL_SD_ConfigWideBusOperation(SD_HandleTypeDef *hsd, uint32_t WideMode); -/** - * @} - */ - -/** @defgroup SD_Exported_Functions_Group4 SD card related functions - * @{ - */ -HAL_StatusTypeDef HAL_SD_SendSDStatus(SD_HandleTypeDef *hsd, uint32_t *pSDstatus); -HAL_SD_CardStateTypeDef HAL_SD_GetCardState(SD_HandleTypeDef *hsd); -HAL_StatusTypeDef HAL_SD_GetCardCID(SD_HandleTypeDef *hsd, HAL_SD_CardCIDTypeDef *pCID); -HAL_StatusTypeDef HAL_SD_GetCardCSD(SD_HandleTypeDef *hsd, HAL_SD_CardCSDTypeDef *pCSD); -HAL_StatusTypeDef HAL_SD_GetCardStatus(SD_HandleTypeDef *hsd, HAL_SD_CardStatusTypeDef *pStatus); -HAL_StatusTypeDef HAL_SD_GetCardInfo(SD_HandleTypeDef *hsd, HAL_SD_CardInfoTypeDef *pCardInfo); -/** - * @} - */ - -/** @defgroup SD_Exported_Functions_Group5 Peripheral State and Errors functions - * @{ - */ -HAL_SD_StateTypeDef HAL_SD_GetState(SD_HandleTypeDef *hsd); -uint32_t HAL_SD_GetError(SD_HandleTypeDef *hsd); -/** - * @} - */ - -/** @defgroup SD_Exported_Functions_Group6 Perioheral Abort management - * @{ - */ -HAL_StatusTypeDef HAL_SD_Abort(SD_HandleTypeDef *hsd); -HAL_StatusTypeDef HAL_SD_Abort_IT(SD_HandleTypeDef *hsd); -/** - * @} - */ - -/* Private types -------------------------------------------------------------*/ -/** @defgroup SD_Private_Types SD Private Types - * @{ - */ - -/** - * @} - */ - -/* Private defines -----------------------------------------------------------*/ -/** @defgroup SD_Private_Defines SD Private Defines - * @{ - */ - -/** - * @} - */ - -/* Private variables ---------------------------------------------------------*/ -/** @defgroup SD_Private_Variables SD Private Variables - * @{ - */ +void HAL_SD_DMA_RxCpltCallback(DMA_HandleTypeDef *hdma); +void HAL_SD_DMA_RxErrorCallback(DMA_HandleTypeDef *hdma); +void HAL_SD_DMA_TxCpltCallback(DMA_HandleTypeDef *hdma); +void HAL_SD_DMA_TxErrorCallback(DMA_HandleTypeDef *hdma); +void HAL_SD_XferCpltCallback(SD_HandleTypeDef *hsd); +void HAL_SD_XferErrorCallback(SD_HandleTypeDef *hsd); +/* Non-Blocking mode: DMA */ +HAL_SD_ErrorTypedef HAL_SD_ReadBlocks_DMA(SD_HandleTypeDef *hsd, uint32_t *pReadBuffer, uint64_t ReadAddr, uint32_t BlockSize, uint32_t NumberOfBlocks); +HAL_SD_ErrorTypedef HAL_SD_WriteBlocks_DMA(SD_HandleTypeDef *hsd, uint32_t *pWriteBuffer, uint64_t WriteAddr, uint32_t BlockSize, uint32_t NumberOfBlocks); +HAL_SD_ErrorTypedef HAL_SD_CheckWriteOperation(SD_HandleTypeDef *hsd, uint32_t Timeout); +HAL_SD_ErrorTypedef HAL_SD_CheckReadOperation(SD_HandleTypeDef *hsd, uint32_t Timeout); /** * @} - */ - -/* Private constants ---------------------------------------------------------*/ -/** @defgroup SD_Private_Constants SD Private Constants - * @{ */ - -/** - * @} - */ - -/* Private macros ------------------------------------------------------------*/ -/** @defgroup SD_Private_Macros SD Private Macros + +/* Peripheral Control functions ************************************************/ +/** @addtogroup SD_Exported_Functions_Group3 * @{ */ - +HAL_SD_ErrorTypedef HAL_SD_Get_CardInfo(SD_HandleTypeDef *hsd, HAL_SD_CardInfoTypedef *pCardInfo); +HAL_SD_ErrorTypedef HAL_SD_WideBusOperation_Config(SD_HandleTypeDef *hsd, uint32_t WideMode); +HAL_SD_ErrorTypedef HAL_SD_StopTransfer(SD_HandleTypeDef *hsd); +HAL_SD_ErrorTypedef HAL_SD_HighSpeed (SD_HandleTypeDef *hsd); /** * @} */ - -/* Private functions prototypes ----------------------------------------------*/ -/** @defgroup SD_Private_Functions_Prototypes SD Private Functions Prototypes + +/* Peripheral State functions **************************************************/ +/** @addtogroup SD_Exported_Functions_Group4 * @{ */ - +HAL_SD_ErrorTypedef HAL_SD_SendSDStatus(SD_HandleTypeDef *hsd, uint32_t *pSDstatus); +HAL_SD_ErrorTypedef HAL_SD_GetCardStatus(SD_HandleTypeDef *hsd, HAL_SD_CardStatusTypedef *pCardStatus); +HAL_SD_TransferStateTypedef HAL_SD_GetStatus(SD_HandleTypeDef *hsd); /** * @} */ -/* Private functions ---------------------------------------------------------*/ -/** @defgroup SD_Private_Functions SD Private Functions - * @{ - */ - /** * @} */ - - + /** * @} */ @@ -703,9 +698,6 @@ HAL_StatusTypeDef HAL_SD_Abort_IT(SD_HandleTypeDef *hsd); * @} */ -/** - * @} - */ #ifdef __cplusplus } #endif diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_smartcard.c b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_smartcard.c index bec0085ea28..d25afce9c43 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_smartcard.c +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_smartcard.c @@ -2,15 +2,16 @@ ****************************************************************************** * @file stm32f1xx_hal_smartcard.c * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief SMARTCARD HAL module driver. * This file provides firmware functions to manage the following * functionalities of the SMARTCARD peripheral: * + Initialization and de-initialization functions * + IO operation functions - * + Peripheral Control functions * + Peripheral State and Errors functions + * + Peripheral Control functions + * @verbatim ============================================================================== ##### How to use this driver ##### @@ -20,10 +21,10 @@ (#) Declare a SMARTCARD_HandleTypeDef handle structure. (#) Initialize the SMARTCARD low level resources by implementing the HAL_SMARTCARD_MspInit() API: - (##) Enable the USARTx interface clock. + (##) Enable the interface clock of the USARTx associated to the SMARTCARD. (##) SMARTCARD pins configuration: (+++) Enable the clock for the SMARTCARD GPIOs. - (+++) Configure the SMARTCARD pins as alternate function pull-up. + (+++) Configure the USART pins (TX as alternate function pull-up, RX as alternate function Input). (##) NVIC configuration if you need to use interrupt process (HAL_SMARTCARD_Transmit_IT() and HAL_SMARTCARD_Receive_IT() APIs): (+++) Configure the USARTx interrupt priority. @@ -34,84 +35,75 @@ (+++) Enable the DMAx interface clock. (+++) Configure the declared DMA handle structure with the required Tx/Rx parameters. (+++) Configure the DMA Tx/Rx channel. - (+++) Associate the initialized DMA handle to the SMARTCARD DMA Tx/Rx handle. + (+++) Associate the initilalized DMA handle to the SMARTCARD DMA Tx/Rx handle. (+++) Configure the priority and enable the NVIC for the transfer complete interrupt on the DMA Tx/Rx channel. (+++) Configure the USARTx interrupt priority and enable the NVIC USART IRQ handle (used for last byte sending completion detection in DMA non circular mode) - (#) Program the Baud Rate, Word Length, Stop Bit, Parity, Hardware + (#) Program the Baud Rate, Word Length , Stop Bit, Parity, Hardware flow control and Mode(Receiver/Transmitter) in the SMARTCARD Init structure. (#) Initialize the SMARTCARD registers by calling the HAL_SMARTCARD_Init() API: - (++) These APIs configure also the low level Hardware GPIO, CLOCK, CORTEX...etc) - by calling the customized HAL_SMARTCARD_MspInit() API. - [..] - (@)The specific SMARTCARD interrupts (Transmission complete interrupt, - RXNE interrupt and Error Interrupts) will be managed using the macros - __HAL_SMARTCARD_ENABLE_IT() and __HAL_SMARTCARD_DISABLE_IT() inside the transmit and receive process. + (++) This API configures also the low level Hardware GPIO, CLOCK, CORTEX...etc) + by calling the customed HAL_SMARTCARD_MspInit(&hsc) API. - [..] - Three operation modes are available within this driver: - - *** Polling mode IO operation *** - ================================= - [..] - (+) Send an amount of data in blocking mode using HAL_SMARTCARD_Transmit() - (+) Receive an amount of data in blocking mode using HAL_SMARTCARD_Receive() - *** Interrupt mode IO operation *** - =================================== - [..] - (+) Send an amount of data in non blocking mode using HAL_SMARTCARD_Transmit_IT() - (+) At transmission end of transfer HAL_SMARTCARD_TxCpltCallback is executed and user can - add his own code by customization of function pointer HAL_SMARTCARD_TxCpltCallback - (+) Receive an amount of data in non blocking mode using HAL_SMARTCARD_Receive_IT() - (+) At reception end of transfer HAL_SMARTCARD_RxCpltCallback is executed and user can - add his own code by customization of function pointer HAL_SMARTCARD_RxCpltCallback - (+) In case of transfer Error, HAL_SMARTCARD_ErrorCallback() function is executed and user can - add his own code by customization of function pointer HAL_SMARTCARD_ErrorCallback - - *** DMA mode IO operation *** - ============================== - [..] - (+) Send an amount of data in non blocking mode (DMA) using HAL_SMARTCARD_Transmit_DMA() - (+) At transmission end of transfer HAL_SMARTCARD_TxCpltCallback is executed and user can - add his own code by customization of function pointer HAL_SMARTCARD_TxCpltCallback - (+) Receive an amount of data in non blocking mode (DMA) using HAL_SMARTCARD_Receive_DMA() - (+) At reception end of transfer HAL_SMARTCARD_RxCpltCallback is executed and user can - add his own code by customization of function pointer HAL_SMARTCARD_RxCpltCallback - (+) In case of transfer Error, HAL_SMARTCARD_ErrorCallback() function is executed and user can - add his own code by customization of function pointer HAL_SMARTCARD_ErrorCallback - - *** SMARTCARD HAL driver macros list *** - ============================================= - [..] - Below the list of most used macros in SMARTCARD HAL driver. - - (+) __HAL_SMARTCARD_ENABLE: Enable the SMARTCARD peripheral - (+) __HAL_SMARTCARD_DISABLE: Disable the SMARTCARD peripheral - (+) __HAL_SMARTCARD_GET_FLAG : Check whether the specified SMARTCARD flag is set or not - (+) __HAL_SMARTCARD_CLEAR_FLAG : Clear the specified SMARTCARD pending flag - (+) __HAL_SMARTCARD_ENABLE_IT: Enable the specified SMARTCARD interrupt - (+) __HAL_SMARTCARD_DISABLE_IT: Disable the specified SMARTCARD interrupt - - [..] - (@) You can refer to the SMARTCARD HAL driver header file for more useful macros + -@@- The specific SMARTCARD interrupts (Transmission complete interrupt, + RXNE interrupt and Error Interrupts) will be managed using the macros + __HAL_SMARTCARD_ENABLE_IT() and __HAL_SMARTCARD_DISABLE_IT() inside the transmit and receive process. - @endverbatim + (#) Three operation modes are available within this driver : + + *** Polling mode IO operation *** + ================================= + [..] + (+) Send an amount of data in blocking mode using HAL_SMARTCARD_Transmit() + (+) Receive an amount of data in blocking mode using HAL_SMARTCARD_Receive() + + *** Interrupt mode IO operation *** + =================================== + [..] + (+) Send an amount of data in non blocking mode using HAL_SMARTCARD_Transmit_IT() + (+) At transmission end of transfer HAL_SMARTCARD_TxCpltCallback is executed and user can + add his own code by customization of function pointer HAL_SMARTCARD_TxCpltCallback + (+) Receive an amount of data in non blocking mode using HAL_SMARTCARD_Receive_IT() + (+) At reception end of transfer HAL_SMARTCARD_RxCpltCallback is executed and user can + add his own code by customization of function pointer HAL_SMARTCARD_RxCpltCallback + (+) In case of transfer Error, HAL_SMARTCARD_ErrorCallback() function is executed and user can + add his own code by customization of function pointer HAL_SMARTCARD_ErrorCallback + + *** DMA mode IO operation *** + ============================== + [..] + (+) Send an amount of data in non blocking mode (DMA) using HAL_SMARTCARD_Transmit_DMA() + (+) At transmission end of transfer HAL_SMARTCARD_TxCpltCallback is executed and user can + add his own code by customization of function pointer HAL_SMARTCARD_TxCpltCallback + (+) Receive an amount of data in non blocking mode (DMA) using HAL_SMARTCARD_Receive_DMA() + (+) At reception end of transfer HAL_SMARTCARD_RxCpltCallback is executed and user can + add his own code by customization of function pointer HAL_SMARTCARD_RxCpltCallback + (+) In case of transfer Error, HAL_SMARTCARD_ErrorCallback() function is executed and user can + add his own code by customization of function pointer HAL_SMARTCARD_ErrorCallback + + *** SMARTCARD HAL driver macros list *** + ======================================== [..] - (@) Additionnal remark: If the parity is enabled, then the MSB bit of the data written - in the data register is transmitted but is changed by the parity bit. - Depending on the frame length defined by the M bit (8-bits or 9-bits), - the possible SMARTCARD frame formats are as listed in the following table: - +-------------------------------------------------------------+ - | M bit | PCE bit | SMARTCARD frame | - |---------------------|---------------------------------------| - | 1 | 1 | | SB | 8 bit data | PB | STB | | - +-------------------------------------------------------------+ + Below the list of most used macros in SMARTCARD HAL driver. + + (+) __HAL_SMARTCARD_ENABLE: Enable the SMARTCARD peripheral + (+) __HAL_SMARTCARD_DISABLE: Disable the SMARTCARD peripheral + (+) __HAL_SMARTCARD_GET_FLAG : Check whether the specified SMARTCARD flag is set or not + (+) __HAL_SMARTCARD_CLEAR_FLAG : Clear the specified SMARTCARD pending flag + (+) __HAL_SMARTCARD_ENABLE_IT: Enable the specified SMARTCARD interrupt + (+) __HAL_SMARTCARD_DISABLE_IT: Disable the specified SMARTCARD interrupt + (+) __HAL_SMARTCARD_GET_IT_SOURCE: Check whether the specified SMARTCARD interrupt has occurred or not + + [..] + (@) You can refer to the SMARTCARD HAL driver header file for more useful macros + + @endverbatim ****************************************************************************** * @attention * - *

© COPYRIGHT(c) 2017 STMicroelectronics

+ *

© COPYRIGHT(c) 2016 STMicroelectronics

* * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: @@ -149,50 +141,42 @@ * @brief HAL SMARTCARD module driver * @{ */ + #ifdef HAL_SMARTCARD_MODULE_ENABLED + /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ -/** @addtogroup SMARTCARD_Private_Constants - * @{ - */ -/** - * @} - */ -/* Private macro -------------------------------------------------------------*/ +/* Private macros --------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ -/** @addtogroup SMARTCARD_Private_Functions +/** @addtogroup SMARTCARD_Private_Functions SMARTCARD Private Functions * @{ */ -static void SMARTCARD_EndTxTransfer(SMARTCARD_HandleTypeDef *hsc); -static void SMARTCARD_EndRxTransfer(SMARTCARD_HandleTypeDef *hsc); -static void SMARTCARD_SetConfig (SMARTCARD_HandleTypeDef *hsc); static HAL_StatusTypeDef SMARTCARD_Transmit_IT(SMARTCARD_HandleTypeDef *hsc); static HAL_StatusTypeDef SMARTCARD_EndTransmit_IT(SMARTCARD_HandleTypeDef *hsmartcard); static HAL_StatusTypeDef SMARTCARD_Receive_IT(SMARTCARD_HandleTypeDef *hsc); +static void SMARTCARD_SetConfig (SMARTCARD_HandleTypeDef *hsc); static void SMARTCARD_DMATransmitCplt(DMA_HandleTypeDef *hdma); static void SMARTCARD_DMAReceiveCplt(DMA_HandleTypeDef *hdma); static void SMARTCARD_DMAError(DMA_HandleTypeDef *hdma); -static void SMARTCARD_DMAAbortOnError(DMA_HandleTypeDef *hdma); -static void SMARTCARD_DMATxAbortCallback(DMA_HandleTypeDef *hdma); -static void SMARTCARD_DMARxAbortCallback(DMA_HandleTypeDef *hdma); -static void SMARTCARD_DMATxOnlyAbortCallback(DMA_HandleTypeDef *hdma); -static void SMARTCARD_DMARxOnlyAbortCallback(DMA_HandleTypeDef *hdma); -static HAL_StatusTypeDef SMARTCARD_WaitOnFlagUntilTimeout(SMARTCARD_HandleTypeDef *hsc, uint32_t Flag, FlagStatus Status, uint32_t Tickstart, uint32_t Timeout); +static HAL_StatusTypeDef SMARTCARD_WaitOnFlagUntilTimeout(SMARTCARD_HandleTypeDef *hsc, uint32_t Flag, FlagStatus Status, uint32_t Timeout); /** * @} */ -/* Exported functions --------------------------------------------------------*/ + +/* Exported functions ---------------------------------------------------------*/ + /** @defgroup SMARTCARD_Exported_Functions SMARTCARD Exported Functions * @{ */ -/** @defgroup SMARTCARD_Exported_Functions_Group1 SmartCard Initialization and de-initialization functions +/** @defgroup SMARTCARD_Exported_Functions_Group1 Initialization and de-initialization functions * @brief Initialization and Configuration functions * @verbatim + ============================================================================== - ##### Initialization and Configuration functions ##### + ##### Initialization and Configuration functions ##### ============================================================================== [..] This subsection provides a set of functions allowing to initialize the USART @@ -209,7 +193,7 @@ static HAL_StatusTypeDef SMARTCARD_WaitOnFlagUntilTimeout(SMARTCARD_HandleTypeDe (++) Baud Rate (++) Word Length => Should be 9 bits (8 bits + parity) (++) Stop Bit - (++) Parity: => Should be enabled + (++) Parity: => Should be enabled (++) USART polarity (++) USART phase (++) USART LastBit @@ -227,23 +211,32 @@ static HAL_StatusTypeDef SMARTCARD_WaitOnFlagUntilTimeout(SMARTCARD_HandleTypeDe [..] Please refer to the ISO 7816-3 specification for more details. + (@) It is also possible to choose 0.5 stop bit for receiving but it is recommended + to use 1.5 stop bits for both transmitting and receiving to avoid switching + between the two configurations. [..] - (@) It is also possible to choose 0.5 stop bit for receiving but it is recommended - to use 1.5 stop bits for both transmitting and receiving to avoid switching - between the two configurations. - [..] - The HAL_SMARTCARD_Init() function follows the USART SmartCard configuration - procedure (details for the procedure are available in reference manual (RM0329)). + The HAL_SMARTCARD_Init() function follows the USART SmartCard configuration + procedure (details for the procedure are available in reference manuals + (RM0008 for STM32F10Xxx MCUs and RM0041 for STM32F100xx MCUs)). @endverbatim * @{ */ +/* + Additionnal remark on the smartcard frame: + +-------------------------------------------------------------+ + | M bit | PCE bit | SMARTCARD frame | + |---------------------|---------------------------------------| + | 1 | 1 | | SB | 8 bit data | PB | STB | | + +-------------------------------------------------------------+ +*/ + /** - * @brief Initializes the SmartCard mode according to the specified - * parameters in the SMARTCARD_InitTypeDef and create the associated handle. - * @param hsc: pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for SMARTCARD module. + * @brief Initializes the SmartCard mode according to the specified + * parameters in the SMARTCARD_HandleTypeDef and create the associated handle. + * @param hsc: Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. * @retval HAL status */ HAL_StatusTypeDef HAL_SMARTCARD_Init(SMARTCARD_HandleTypeDef *hsc) @@ -254,26 +247,38 @@ HAL_StatusTypeDef HAL_SMARTCARD_Init(SMARTCARD_HandleTypeDef *hsc) return HAL_ERROR; } + /* Check Wordlength, Parity and Stop bits parameters */ + if ( (!(IS_SMARTCARD_WORD_LENGTH(hsc->Init.WordLength))) + ||(!(IS_SMARTCARD_STOPBITS(hsc->Init.StopBits))) + ||(!(IS_SMARTCARD_PARITY(hsc->Init.Parity))) ) + { + return HAL_ERROR; + } + /* Check the parameters */ assert_param(IS_SMARTCARD_INSTANCE(hsc->Instance)); + assert_param(IS_SMARTCARD_NACK_STATE(hsc->Init.NACKState)); + assert_param(IS_SMARTCARD_PRESCALER(hsc->Init.Prescaler)); - - if(hsc->gState == HAL_SMARTCARD_STATE_RESET) + if(hsc->State == HAL_SMARTCARD_STATE_RESET) { /* Allocate lock resource and initialize it */ hsc->Lock = HAL_UNLOCKED; - - /* Init the low level hardware : GPIO, CLOCK, CORTEX...etc */ + + /* Init the low level hardware */ HAL_SMARTCARD_MspInit(hsc); } + + hsc->State = HAL_SMARTCARD_STATE_BUSY; - hsc->gState = HAL_SMARTCARD_STATE_BUSY; - + /* Disable the Peripheral */ + __HAL_SMARTCARD_DISABLE(hsc); + /* Set the Prescaler */ MODIFY_REG(hsc->Instance->GTPR, USART_GTPR_PSC, hsc->Init.Prescaler); /* Set the Guard Time */ - MODIFY_REG(hsc->Instance->GTPR, USART_GTPR_GT, ((hsc->Init.GuardTime)<<8U)); + MODIFY_REG(hsc->Instance->GTPR, USART_GTPR_GT, ((hsc->Init.GuardTime)<<8)); /* Set the Smartcard Communication parameters */ SMARTCARD_SetConfig(hsc); @@ -284,33 +289,26 @@ HAL_StatusTypeDef HAL_SMARTCARD_Init(SMARTCARD_HandleTypeDef *hsc) CLEAR_BIT(hsc->Instance->CR2, USART_CR2_LINEN); CLEAR_BIT(hsc->Instance->CR3, (USART_CR3_IREN | USART_CR3_HDSEL)); - /* Enable the SMARTCARD Parity Error Interrupt */ - SET_BIT(hsc->Instance->CR1, USART_CR1_PEIE); - - /* Enable the SMARTCARD Framing Error Interrupt */ - SET_BIT(hsc->Instance->CR3, USART_CR3_EIE); - - /* Enable the Peripheral */ + /* Enable the Peripharal */ __HAL_SMARTCARD_ENABLE(hsc); /* Configure the Smartcard NACK state */ MODIFY_REG(hsc->Instance->CR3, USART_CR3_NACK, hsc->Init.NACKState); /* Enable the SC mode by setting the SCEN bit in the CR3 register */ - hsc->Instance->CR3 |= (USART_CR3_SCEN); + SET_BIT(hsc->Instance->CR3, USART_CR3_SCEN); /* Initialize the SMARTCARD state*/ hsc->ErrorCode = HAL_SMARTCARD_ERROR_NONE; - hsc->gState= HAL_SMARTCARD_STATE_READY; - hsc->RxState= HAL_SMARTCARD_STATE_READY; + hsc->State= HAL_SMARTCARD_STATE_READY; return HAL_OK; } /** - * @brief DeInitializes the USART SmartCard peripheral - * @param hsc: pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for SMARTCARD module. + * @brief DeInitializes the SMARTCARD peripheral + * @param hsc: Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. * @retval HAL status */ HAL_StatusTypeDef HAL_SMARTCARD_DeInit(SMARTCARD_HandleTypeDef *hsc) @@ -324,14 +322,22 @@ HAL_StatusTypeDef HAL_SMARTCARD_DeInit(SMARTCARD_HandleTypeDef *hsc) /* Check the parameters */ assert_param(IS_SMARTCARD_INSTANCE(hsc->Instance)); - hsc->gState = HAL_SMARTCARD_STATE_BUSY; + hsc->State = HAL_SMARTCARD_STATE_BUSY; + /* Disable the Peripheral */ + __HAL_SMARTCARD_DISABLE(hsc); + + hsc->Instance->CR1 = 0x0; + hsc->Instance->CR2 = 0x0; + hsc->Instance->CR3 = 0x0; + hsc->Instance->BRR = 0x0; + hsc->Instance->GTPR = 0x0; + /* DeInit the low level hardware */ HAL_SMARTCARD_MspDeInit(hsc); hsc->ErrorCode = HAL_SMARTCARD_ERROR_NONE; - hsc->gState = HAL_SMARTCARD_STATE_RESET; - hsc->RxState = HAL_SMARTCARD_STATE_RESET; + hsc->State = HAL_SMARTCARD_STATE_RESET; /* Release Lock */ __HAL_UNLOCK(hsc); @@ -340,33 +346,33 @@ HAL_StatusTypeDef HAL_SMARTCARD_DeInit(SMARTCARD_HandleTypeDef *hsc) } /** - * @brief SMARTCARD MSP Init. - * @param hsc: pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for SMARTCARD module. + * @brief SMARTCARD MSP Init. + * @param hsc: Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. * @retval None */ -__weak void HAL_SMARTCARD_MspInit(SMARTCARD_HandleTypeDef *hsc) + __weak void HAL_SMARTCARD_MspInit(SMARTCARD_HandleTypeDef *hsc) { /* Prevent unused argument(s) compilation warning */ UNUSED(hsc); /* NOTE: This function should not be modified, when the callback is needed, - the HAL_SMARTCARD_MspInit could be implemented in the user file - */ + the HAL_SMARTCARD_MspInit can be implemented in the user file + */ } /** - * @brief SMARTCARD MSP DeInit - * @param hsc: pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for SMARTCARD module. + * @brief SMARTCARD MSP DeInit. + * @param hsc: Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. * @retval None */ -__weak void HAL_SMARTCARD_MspDeInit(SMARTCARD_HandleTypeDef *hsc) + __weak void HAL_SMARTCARD_MspDeInit(SMARTCARD_HandleTypeDef *hsc) { /* Prevent unused argument(s) compilation warning */ UNUSED(hsc); /* NOTE: This function should not be modified, when the callback is needed, - the HAL_SMARTCARD_MspDeInit could be implemented in the user file - */ + the HAL_SMARTCARD_MspDeInit can be implemented in the user file + */ } /** @@ -377,32 +383,33 @@ __weak void HAL_SMARTCARD_MspDeInit(SMARTCARD_HandleTypeDef *hsc) * @brief SMARTCARD Transmit and Receive functions * @verbatim - =============================================================================== - ##### IO operation functions ##### - =============================================================================== - [..] - This subsection provides a set of functions allowing to manage the SMARTCARD data transfers. + ============================================================================== + ##### IO operation functions ##### + ============================================================================== + [..] + This subsection provides a set of functions allowing to manage the SMARTCARD data transfers. - [..] + [..] (#) Smartcard is a single wire half duplex communication protocol. The Smartcard interface is designed to support asynchronous protocol Smartcards as defined in the ISO 7816-3 standard. (#) The USART should be configured as: - (++) 8 bits plus parity: where M=1 and PCE=1 in the USART_CR1 register - (++) 1.5 stop bits when transmitting and receiving: where STOP=11 in the USART_CR2 register. + (++) 8 bits plus parity: where M=1 and PCE=1 in the USART_CR1 register + (++) 1.5 stop bits when transmitting and receiving: where STOP=11 in the USART_CR2 register. (#) There are two modes of transfer: - (++) Blocking mode: The communication is performed in polling mode. - The HAL status of all data processing is returned by the same function - after finishing transfer. - (++) Non Blocking mode: The communication is performed using Interrupts - or DMA, These APIs return the HAL status. - The end of the data processing will be indicated through the - dedicated SMARTCARD IRQ when using Interrupt mode or the DMA IRQ when - using DMA mode. - The HAL_SMARTCARD_TxCpltCallback(), HAL_SMARTCARD_RxCpltCallback() user callbacks - will be executed respectively at the end of the Transmit or Receive process - The HAL_SMARTCARD_ErrorCallback() user callback will be executed when a communication error is detected + (++) Blocking mode: The communication is performed in polling mode. + The HAL status of all data processing is returned by the same function + after finishing transfer. + (++) No-Blocking mode: The communication is performed using Interrupts + or DMA, the relevant API's return the HAL status. + The end of the data processing will be indicated through the + dedicated SMARTCARD IRQ when using Interrupt mode or the DMA IRQ when + using DMA mode. + The HAL_SMARTCARD_TxCpltCallback(), HAL_SMARTCARD_RxCpltCallback() user callbacks + will be executed respectively at the end of the Transmit or Receive process + The HAL_SMARTCARD_ErrorCallback() user callback will be executed when a communication + error is detected. (#) Blocking mode APIs are : (++) HAL_SMARTCARD_Transmit() @@ -427,22 +434,22 @@ __weak void HAL_SMARTCARD_MspDeInit(SMARTCARD_HandleTypeDef *hsc) */ /** - * @brief Send an amount of data in blocking mode - * @param hsc: pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for SMARTCARD module. - * @param pData: pointer to data buffer - * @param Size: amount of data to be sent - * @param Timeout: Timeout duration + * @brief Sends an amount of data in blocking mode. + * @param hsc: Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. + * @param pData: Pointer to data buffer + * @param Size: Amount of data to be sent + * @param Timeout: Specify timeout value * @retval HAL status */ HAL_StatusTypeDef HAL_SMARTCARD_Transmit(SMARTCARD_HandleTypeDef *hsc, uint8_t *pData, uint16_t Size, uint32_t Timeout) { - uint16_t* tmp; - uint32_t tickstart = 0U; + uint32_t tmp_state = 0; - if(hsc->gState == HAL_SMARTCARD_STATE_READY) + tmp_state = hsc->State; + if((tmp_state == HAL_SMARTCARD_STATE_READY) || (tmp_state == HAL_SMARTCARD_STATE_BUSY_RX)) { - if((pData == NULL) || (Size == 0U)) + if((pData == NULL) || (Size == 0)) { return HAL_ERROR; } @@ -451,33 +458,42 @@ HAL_StatusTypeDef HAL_SMARTCARD_Transmit(SMARTCARD_HandleTypeDef *hsc, uint8_t * __HAL_LOCK(hsc); hsc->ErrorCode = HAL_SMARTCARD_ERROR_NONE; - hsc->gState = HAL_SMARTCARD_STATE_BUSY_TX; - - /* Init tickstart for timeout managment */ - tickstart = HAL_GetTick(); - + /* Check if a non-blocking receive process is ongoing or not */ + if(hsc->State == HAL_SMARTCARD_STATE_BUSY_RX) + { + hsc->State = HAL_SMARTCARD_STATE_BUSY_TX_RX; + } + else + { + hsc->State = HAL_SMARTCARD_STATE_BUSY_TX; + } + hsc->TxXferSize = Size; hsc->TxXferCount = Size; - while(hsc->TxXferCount > 0U) + while(hsc->TxXferCount > 0) { - hsc->TxXferCount--; - if(SMARTCARD_WaitOnFlagUntilTimeout(hsc, SMARTCARD_FLAG_TXE, RESET, tickstart, Timeout) != HAL_OK) + if(SMARTCARD_WaitOnFlagUntilTimeout(hsc, SMARTCARD_FLAG_TXE, RESET, Timeout) != HAL_OK) { return HAL_TIMEOUT; } - tmp = (uint16_t*) pData; - hsc->Instance->DR = (*tmp & (uint16_t)0x01FF); - pData +=1U; + WRITE_REG(hsc->Instance->DR, (*pData++ & (uint8_t)0xFF)); + hsc->TxXferCount--; } - - if(SMARTCARD_WaitOnFlagUntilTimeout(hsc, SMARTCARD_FLAG_TC, RESET, tickstart, Timeout) != HAL_OK) + + if(SMARTCARD_WaitOnFlagUntilTimeout(hsc, SMARTCARD_FLAG_TC, RESET, Timeout) != HAL_OK) { return HAL_TIMEOUT; } - /* At end of Tx process, restore hsc->gState to Ready */ - hsc->gState = HAL_SMARTCARD_STATE_READY; - + /* Check if a non-blocking receive process is ongoing or not */ + if(hsc->State == HAL_SMARTCARD_STATE_BUSY_TX_RX) + { + hsc->State = HAL_SMARTCARD_STATE_BUSY_RX; + } + else + { + hsc->State = HAL_SMARTCARD_STATE_READY; + } /* Process Unlocked */ __HAL_UNLOCK(hsc); @@ -490,22 +506,22 @@ HAL_StatusTypeDef HAL_SMARTCARD_Transmit(SMARTCARD_HandleTypeDef *hsc, uint8_t * } /** - * @brief Receive an amount of data in blocking mode - * @param hsc: pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for SMARTCARD module. - * @param pData: pointer to data buffer - * @param Size: amount of data to be received - * @param Timeout: Timeout duration + * @brief Receive an amount of data in blocking mode. + * @param hsc: Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. + * @param pData: Pointer to data buffer + * @param Size: Amount of data to be received + * @param Timeout: Specify timeout value * @retval HAL status */ HAL_StatusTypeDef HAL_SMARTCARD_Receive(SMARTCARD_HandleTypeDef *hsc, uint8_t *pData, uint16_t Size, uint32_t Timeout) { - uint16_t* tmp; - uint32_t tickstart = 0U; + uint32_t tmp_state = 0; - if(hsc->RxState == HAL_SMARTCARD_STATE_READY) + tmp_state = hsc->State; + if((tmp_state == HAL_SMARTCARD_STATE_READY) || (tmp_state == HAL_SMARTCARD_STATE_BUSY_TX)) { - if((pData == NULL) || (Size == 0U)) + if((pData == NULL) || (Size == 0)) { return HAL_ERROR; } @@ -514,30 +530,40 @@ HAL_StatusTypeDef HAL_SMARTCARD_Receive(SMARTCARD_HandleTypeDef *hsc, uint8_t *p __HAL_LOCK(hsc); hsc->ErrorCode = HAL_SMARTCARD_ERROR_NONE; - hsc->RxState = HAL_SMARTCARD_STATE_BUSY_RX; - /* Init tickstart for timeout managment */ - tickstart = HAL_GetTick(); + /* Check if a non-blocking transmit process is ongoing or not */ + if(hsc->State == HAL_SMARTCARD_STATE_BUSY_TX) + { + hsc->State = HAL_SMARTCARD_STATE_BUSY_TX_RX; + } + else + { + hsc->State = HAL_SMARTCARD_STATE_BUSY_RX; + } hsc->RxXferSize = Size; hsc->RxXferCount = Size; - /* Check the remain data to be received */ - while(hsc->RxXferCount > 0U) + while(hsc->RxXferCount > 0) { - hsc->RxXferCount--; - if(SMARTCARD_WaitOnFlagUntilTimeout(hsc, SMARTCARD_FLAG_RXNE, RESET, tickstart, Timeout) != HAL_OK) + if(SMARTCARD_WaitOnFlagUntilTimeout(hsc, SMARTCARD_FLAG_RXNE, RESET, Timeout) != HAL_OK) { return HAL_TIMEOUT; } - tmp = (uint16_t*) pData; - *tmp = (uint8_t)(hsc->Instance->DR & (uint8_t)0xFF); - pData +=1U; + *pData++ = (uint8_t)(hsc->Instance->DR & (uint8_t)0x00FF); + hsc->RxXferCount--; + } + + /* Check if a non-blocking transmit process is ongoing or not */ + if(hsc->State == HAL_SMARTCARD_STATE_BUSY_TX_RX) + { + hsc->State = HAL_SMARTCARD_STATE_BUSY_TX; + } + else + { + hsc->State = HAL_SMARTCARD_STATE_READY; } - /* At end of Rx process, restore hsc->RxState to Ready */ - hsc->RxState = HAL_SMARTCARD_STATE_READY; - /* Process Unlocked */ __HAL_UNLOCK(hsc); @@ -550,22 +576,25 @@ HAL_StatusTypeDef HAL_SMARTCARD_Receive(SMARTCARD_HandleTypeDef *hsc, uint8_t *p } /** - * @brief Send an amount of data in non blocking mode - * @param hsc: pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for SMARTCARD module. - * @param pData: pointer to data buffer - * @param Size: amount of data to be sent + * @brief Sends an amount of data in non-blocking mode. + * @param hsc: Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. + * @param pData: Pointer to data buffer + * @param Size: Amount of data to be sent * @retval HAL status */ HAL_StatusTypeDef HAL_SMARTCARD_Transmit_IT(SMARTCARD_HandleTypeDef *hsc, uint8_t *pData, uint16_t Size) { - /* Check that a Tx process is not already ongoing */ - if(hsc->gState == HAL_SMARTCARD_STATE_READY) + uint32_t tmp_state = 0; + + tmp_state = hsc->State; + if((tmp_state == HAL_SMARTCARD_STATE_READY) || (tmp_state == HAL_SMARTCARD_STATE_BUSY_RX)) { - if((pData == NULL) || (Size == 0U)) + if((pData == NULL) || (Size == 0)) { return HAL_ERROR; } + /* Process Locked */ __HAL_LOCK(hsc); @@ -574,19 +603,24 @@ HAL_StatusTypeDef HAL_SMARTCARD_Transmit_IT(SMARTCARD_HandleTypeDef *hsc, uint8_ hsc->TxXferCount = Size; hsc->ErrorCode = HAL_SMARTCARD_ERROR_NONE; - hsc->gState = HAL_SMARTCARD_STATE_BUSY_TX; + /* Check if a non-blocking receive process is ongoing or not */ + if(hsc->State == HAL_SMARTCARD_STATE_BUSY_RX) + { + hsc->State = HAL_SMARTCARD_STATE_BUSY_TX_RX; + } + else + { + hsc->State = HAL_SMARTCARD_STATE_BUSY_TX; + } /* Process Unlocked */ __HAL_UNLOCK(hsc); - - /* Enable the SMARTCARD Parity Error Interrupt */ - SET_BIT(hsc->Instance->CR1, USART_CR1_PEIE); - /* Disable the SMARTCARD Error Interrupt: (Frame error, noise error, overrun error) */ - CLEAR_BIT(hsc->Instance->CR3, USART_CR3_EIE); + /* Enable the SMARTCARD Error Interrupt: (Frame error, noise error, overrun error) */ + __HAL_SMARTCARD_ENABLE_IT(hsc, SMARTCARD_IT_ERR); /* Enable the SMARTCARD Transmit data register empty Interrupt */ - SET_BIT(hsc->Instance->CR1, USART_CR1_TXEIE); + __HAL_SMARTCARD_ENABLE_IT(hsc, SMARTCARD_IT_TXE); return HAL_OK; } @@ -597,19 +631,21 @@ HAL_StatusTypeDef HAL_SMARTCARD_Transmit_IT(SMARTCARD_HandleTypeDef *hsc, uint8_ } /** - * @brief Receive an amount of data in non blocking mode - * @param hsc: pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for SMARTCARD module. - * @param pData: pointer to data buffer - * @param Size: amount of data to be received + * @brief Receives an amount of data in non-blocking mode. + * @param hsc: Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. + * @param pData: Pointer to data buffer + * @param Size: Amount of data to be received * @retval HAL status */ HAL_StatusTypeDef HAL_SMARTCARD_Receive_IT(SMARTCARD_HandleTypeDef *hsc, uint8_t *pData, uint16_t Size) { - /* Check that a Rx process is not already ongoing */ - if(hsc->RxState == HAL_SMARTCARD_STATE_READY) + uint32_t tmp_state = 0; + + tmp_state = hsc->State; + if((tmp_state == HAL_SMARTCARD_STATE_READY) || (tmp_state == HAL_SMARTCARD_STATE_BUSY_TX)) { - if((pData == NULL) || (Size == 0U)) + if((pData == NULL) || (Size == 0)) { return HAL_ERROR; } @@ -622,16 +658,27 @@ HAL_StatusTypeDef HAL_SMARTCARD_Receive_IT(SMARTCARD_HandleTypeDef *hsc, uint8_t hsc->RxXferCount = Size; hsc->ErrorCode = HAL_SMARTCARD_ERROR_NONE; - hsc->RxState = HAL_SMARTCARD_STATE_BUSY_RX; - + /* Check if a non-blocking transmit process is ongoing or not */ + if(hsc->State == HAL_SMARTCARD_STATE_BUSY_TX) + { + hsc->State = HAL_SMARTCARD_STATE_BUSY_TX_RX; + } + else + { + hsc->State = HAL_SMARTCARD_STATE_BUSY_RX; + } + /* Process Unlocked */ __HAL_UNLOCK(hsc); - /* Enable the SMARTCARD Parity Error and Data Register not empty Interrupts */ - SET_BIT(hsc->Instance->CR1, USART_CR1_PEIE| USART_CR1_RXNEIE); + /* Enable the SMARTCARD Data Register not empty Interrupt */ + __HAL_SMARTCARD_ENABLE_IT(hsc, SMARTCARD_IT_RXNE); + + /* Enable the SMARTCARD Parity Error Interrupt */ + __HAL_SMARTCARD_ENABLE_IT(hsc, SMARTCARD_IT_PE); /* Enable the SMARTCARD Error Interrupt: (Frame error, noise error, overrun error) */ - SET_BIT(hsc->Instance->CR3, USART_CR3_EIE); + __HAL_SMARTCARD_ENABLE_IT(hsc, SMARTCARD_IT_ERR); return HAL_OK; } @@ -642,21 +689,22 @@ HAL_StatusTypeDef HAL_SMARTCARD_Receive_IT(SMARTCARD_HandleTypeDef *hsc, uint8_t } /** - * @brief Send an amount of data in non blocking mode - * @param hsc: pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for SMARTCARD module. - * @param pData: pointer to data buffer - * @param Size: amount of data to be sent + * @brief Sends an amount of data in non-blocking mode. + * @param hsc: Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. + * @param pData: Pointer to data buffer + * @param Size: Amount of data to be sent * @retval HAL status */ HAL_StatusTypeDef HAL_SMARTCARD_Transmit_DMA(SMARTCARD_HandleTypeDef *hsc, uint8_t *pData, uint16_t Size) { - uint32_t *tmp; + uint32_t *tmp = 0; + uint32_t tmp_state = 0; - /* Check that a Tx process is not already ongoing */ - if(hsc->gState == HAL_SMARTCARD_STATE_READY) + tmp_state = hsc->State; + if((tmp_state == HAL_SMARTCARD_STATE_READY) || (tmp_state == HAL_SMARTCARD_STATE_BUSY_RX)) { - if((pData == NULL) || (Size == 0U)) + if((pData == NULL) || (Size == 0)) { return HAL_ERROR; } @@ -669,7 +717,15 @@ HAL_StatusTypeDef HAL_SMARTCARD_Transmit_DMA(SMARTCARD_HandleTypeDef *hsc, uint8 hsc->TxXferCount = Size; hsc->ErrorCode = HAL_SMARTCARD_ERROR_NONE; - hsc->gState = HAL_SMARTCARD_STATE_BUSY_TX; + /* Check if a non-blocking receive process is ongoing or not */ + if(hsc->State == HAL_SMARTCARD_STATE_BUSY_RX) + { + hsc->State = HAL_SMARTCARD_STATE_BUSY_TX_RX; + } + else + { + hsc->State = HAL_SMARTCARD_STATE_BUSY_TX; + } /* Set the SMARTCARD DMA transfer complete callback */ hsc->hdmatx->XferCpltCallback = SMARTCARD_DMATransmitCplt; @@ -677,22 +733,19 @@ HAL_StatusTypeDef HAL_SMARTCARD_Transmit_DMA(SMARTCARD_HandleTypeDef *hsc, uint8 /* Set the DMA error callback */ hsc->hdmatx->XferErrorCallback = SMARTCARD_DMAError; - /* Set the DMA abort callback */ - hsc->hdmatx->XferAbortCallback = NULL; - - /* Enable the SMARTCARD transmit DMA Channel */ + /* Enable the SMARTCARD transmit DMA channel */ tmp = (uint32_t*)&pData; HAL_DMA_Start_IT(hsc->hdmatx, *(uint32_t*)tmp, (uint32_t)&hsc->Instance->DR, Size); - /* Clear the TC flag in the SR register by writing 0 to it */ + /* Clear the TC flag in the SR register by writing 0 to it */ __HAL_SMARTCARD_CLEAR_FLAG(hsc, SMARTCARD_FLAG_TC); - /* Process Unlocked */ - __HAL_UNLOCK(hsc); - /* Enable the DMA transfer for transmit request by setting the DMAT bit in the SMARTCARD CR3 register */ - SET_BIT(hsc->Instance->CR3, USART_CR3_DMAT); + SET_BIT(hsc->Instance->CR3,USART_CR3_DMAT); + + /* Process Unlocked */ + __HAL_UNLOCK(hsc); return HAL_OK; } @@ -703,22 +756,23 @@ HAL_StatusTypeDef HAL_SMARTCARD_Transmit_DMA(SMARTCARD_HandleTypeDef *hsc, uint8 } /** - * @brief Receive an amount of data in non blocking mode - * @param hsc: pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for SMARTCARD module. - * @param pData: pointer to data buffer - * @param Size: amount of data to be received - * @note When the SMARTCARD parity is enabled (PCE = 1) the data received contain the parity bit.s + * @brief Receive an amount of data in non-blocking mode. + * @param hsc: Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. + * @param pData: Pointer to data buffer + * @param Size: Amount of data to be received + * @note When the SMARTCARD parity is enabled (PCE = 1) the data received contain the parity bit. * @retval HAL status */ HAL_StatusTypeDef HAL_SMARTCARD_Receive_DMA(SMARTCARD_HandleTypeDef *hsc, uint8_t *pData, uint16_t Size) { - uint32_t *tmp; + uint32_t *tmp = 0; + uint32_t tmp_state = 0; - /* Check that a Rx process is not already ongoing */ - if(hsc->RxState == HAL_SMARTCARD_STATE_READY) + tmp_state = hsc->State; + if((tmp_state == HAL_SMARTCARD_STATE_READY) || (tmp_state == HAL_SMARTCARD_STATE_BUSY_TX)) { - if((pData == NULL) || (Size == 0U)) + if((pData == NULL) || (Size == 0)) { return HAL_ERROR; } @@ -730,7 +784,15 @@ HAL_StatusTypeDef HAL_SMARTCARD_Receive_DMA(SMARTCARD_HandleTypeDef *hsc, uint8_ hsc->RxXferSize = Size; hsc->ErrorCode = HAL_SMARTCARD_ERROR_NONE; - hsc->RxState = HAL_SMARTCARD_STATE_BUSY_RX; + /* Check if a non-blocking transmit process is ongoing or not */ + if(hsc->State == HAL_SMARTCARD_STATE_BUSY_TX) + { + hsc->State = HAL_SMARTCARD_STATE_BUSY_TX_RX; + } + else + { + hsc->State = HAL_SMARTCARD_STATE_BUSY_RX; + } /* Set the SMARTCARD DMA transfer complete callback */ hsc->hdmarx->XferCpltCallback = SMARTCARD_DMAReceiveCplt; @@ -738,29 +800,17 @@ HAL_StatusTypeDef HAL_SMARTCARD_Receive_DMA(SMARTCARD_HandleTypeDef *hsc, uint8_ /* Set the DMA error callback */ hsc->hdmarx->XferErrorCallback = SMARTCARD_DMAError; - /* Set the DMA abort callback */ - hsc->hdmatx->XferAbortCallback = NULL; - - /* Enable the DMA Channel */ + /* Enable the DMA channel */ tmp = (uint32_t*)&pData; HAL_DMA_Start_IT(hsc->hdmarx, (uint32_t)&hsc->Instance->DR, *(uint32_t*)tmp, Size); - /* Clear the Overrun flag just before enabling the DMA Rx request: can be mandatory for the second transfer */ - __HAL_SMARTCARD_CLEAR_OREFLAG(hsc); + /* Enable the DMA transfer for the receiver request by setting the DMAR bit + in the SMARTCARD CR3 register */ + SET_BIT(hsc->Instance->CR3,USART_CR3_DMAR); /* Process Unlocked */ __HAL_UNLOCK(hsc); - /* Enable the SMARTCARD Parity Error Interrupt */ - SET_BIT(hsc->Instance->CR1, USART_CR1_PEIE); - - /* Enable the SMARTCARD Error Interrupt: (Frame error, noise error, overrun error) */ - SET_BIT(hsc->Instance->CR3, USART_CR3_EIE); - - /* Enable the DMA transfer for the receiver request by setting the DMAR bit - in the SMARTCARD CR3 register */ - SET_BIT(hsc->Instance->CR3, USART_CR3_DMAR); - return HAL_OK; } else @@ -770,976 +820,342 @@ HAL_StatusTypeDef HAL_SMARTCARD_Receive_DMA(SMARTCARD_HandleTypeDef *hsc, uint8_ } /** - * @brief Abort ongoing transfers (blocking mode). - * @param hsc SMARTCARD handle. - * @note This procedure could be used for aborting any ongoing transfer started in Interrupt or DMA mode. - * This procedure performs following operations : - * - Disable PPP Interrupts - * - Disable the DMA transfer in the peripheral register (if enabled) - * - Abort DMA transfer by calling HAL_DMA_Abort (in case of transfer in DMA mode) - * - Set handle State to READY - * @note This procedure is executed in blocking mode : when exiting function, Abort is considered as completed. - * @retval HAL status -*/ -HAL_StatusTypeDef HAL_SMARTCARD_Abort(SMARTCARD_HandleTypeDef *hsc) + * @brief This function handles SMARTCARD interrupt request. + * @param hsc: Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. + * @retval None + */ +void HAL_SMARTCARD_IRQHandler(SMARTCARD_HandleTypeDef *hsc) { - /* Disable TXEIE, TCIE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */ - CLEAR_BIT(hsc->Instance->CR1, (USART_CR1_RXNEIE | USART_CR1_PEIE | USART_CR1_TXEIE | USART_CR1_TCIE)); - CLEAR_BIT(hsc->Instance->CR3, USART_CR3_EIE); + uint32_t tmp_flag = 0, tmp_it_source = 0; - /* Disable the SMARTCARD DMA Tx request if enabled */ - if(HAL_IS_BIT_SET(hsc->Instance->CR3, USART_CR3_DMAT)) + tmp_flag = __HAL_SMARTCARD_GET_FLAG(hsc, SMARTCARD_FLAG_PE); + tmp_it_source = __HAL_SMARTCARD_GET_IT_SOURCE(hsc, SMARTCARD_IT_PE); + /* SMARTCARD parity error interrupt occurred -----------------------------------*/ + if((tmp_flag != RESET) && (tmp_it_source != RESET)) { - CLEAR_BIT(hsc->Instance->CR3, USART_CR3_DMAT); - - /* Abort the SMARTCARD DMA Tx channel: use blocking DMA Abort API (no callback) */ - if(hsc->hdmatx != NULL) - { - /* Set the SMARTCARD DMA Abort callback to Null. - No call back execution at end of DMA abort procedure */ - hsc->hdmatx->XferAbortCallback = NULL; - - HAL_DMA_Abort(hsc->hdmatx); - } + hsc->ErrorCode |= HAL_SMARTCARD_ERROR_PE; } - /* Disable the SMARTCARD DMA Rx request if enabled */ - if(HAL_IS_BIT_SET(hsc->Instance->CR3, USART_CR3_DMAR)) + tmp_flag = __HAL_SMARTCARD_GET_FLAG(hsc, SMARTCARD_FLAG_FE); + tmp_it_source = __HAL_SMARTCARD_GET_IT_SOURCE(hsc, SMARTCARD_IT_ERR); + /* SMARTCARD frame error interrupt occurred ------------------------------------*/ + if((tmp_flag != RESET) && (tmp_it_source != RESET)) { - CLEAR_BIT(hsc->Instance->CR3, USART_CR3_DMAR); - - /* Abort the SMARTCARD DMA Rx channel: use blocking DMA Abort API (no callback) */ - if(hsc->hdmarx != NULL) - { - /* Set the SMARTCARD DMA Abort callback to Null. - No call back execution at end of DMA abort procedure */ - hsc->hdmarx->XferAbortCallback = NULL; + hsc->ErrorCode |= HAL_SMARTCARD_ERROR_FE; + } - HAL_DMA_Abort(hsc->hdmarx); - } + tmp_flag = __HAL_SMARTCARD_GET_FLAG(hsc, SMARTCARD_FLAG_NE); + /* SMARTCARD noise error interrupt occurred ------------------------------------*/ + if((tmp_flag != RESET) && (tmp_it_source != RESET)) + { + hsc->ErrorCode |= HAL_SMARTCARD_ERROR_NE; } - /* Reset Tx and Rx transfer counters */ - hsc->TxXferCount = 0x00U; - hsc->RxXferCount = 0x00U; + tmp_flag = __HAL_SMARTCARD_GET_FLAG(hsc, SMARTCARD_FLAG_ORE); + /* SMARTCARD Over-Run interrupt occurred ---------------------------------------*/ + if((tmp_flag != RESET) && (tmp_it_source != RESET)) + { + hsc->ErrorCode |= HAL_SMARTCARD_ERROR_ORE; + } + + tmp_flag = __HAL_SMARTCARD_GET_FLAG(hsc, SMARTCARD_FLAG_RXNE); + tmp_it_source = __HAL_SMARTCARD_GET_IT_SOURCE(hsc, SMARTCARD_IT_RXNE); + /* SMARTCARD in mode Receiver --------------------------------------------------*/ + if((tmp_flag != RESET) && (tmp_it_source != RESET)) + { + SMARTCARD_Receive_IT(hsc); + } - /* Reset ErrorCode */ - hsc->ErrorCode = HAL_SMARTCARD_ERROR_NONE; + tmp_flag = __HAL_SMARTCARD_GET_FLAG(hsc, SMARTCARD_FLAG_TXE); + tmp_it_source = __HAL_SMARTCARD_GET_IT_SOURCE(hsc, SMARTCARD_IT_TXE); + /* SMARTCARD in mode Transmitter -----------------------------------------------*/ + if((tmp_flag != RESET) && (tmp_it_source != RESET)) + { + SMARTCARD_Transmit_IT(hsc); + } + + tmp_flag = __HAL_SMARTCARD_GET_FLAG(hsc, SMARTCARD_FLAG_TC); + tmp_it_source = __HAL_SMARTCARD_GET_IT_SOURCE(hsc, SMARTCARD_IT_TC); + /* SMARTCARD in mode Transmitter (transmission end) ------------------------*/ + if((tmp_flag != RESET) && (tmp_it_source != RESET)) + { + SMARTCARD_EndTransmit_IT(hsc); + } - /* Restore hsc->RxState and hsc->gState to Ready */ - hsc->RxState = HAL_SMARTCARD_STATE_READY; - hsc->gState = HAL_SMARTCARD_STATE_READY; + /* Call the Error call Back in case of Errors */ + if(hsc->ErrorCode != HAL_SMARTCARD_ERROR_NONE) + { + /* Clear all the error flag at once */ + __HAL_SMARTCARD_CLEAR_PEFLAG(hsc); - return HAL_OK; + /* Set the SMARTCARD state ready to be able to start again the process */ + hsc->State= HAL_SMARTCARD_STATE_READY; + HAL_SMARTCARD_ErrorCallback(hsc); + } } /** - * @brief Abort ongoing Transmit transfer (blocking mode). - * @param hsc SMARTCARD handle. - * @note This procedure could be used for aborting any ongoing transfer started in Interrupt or DMA mode. - * This procedure performs following operations : - * - Disable PPP Interrupts - * - Disable the DMA transfer in the peripheral register (if enabled) - * - Abort DMA transfer by calling HAL_DMA_Abort (in case of transfer in DMA mode) - * - Set handle State to READY - * @note This procedure is executed in blocking mode : when exiting function, Abort is considered as completed. - * @retval HAL status -*/ -HAL_StatusTypeDef HAL_SMARTCARD_AbortTransmit(SMARTCARD_HandleTypeDef *hsc) + * @brief Tx Transfer completed callback. + * @param hsc: Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. + * @retval None + */ + __weak void HAL_SMARTCARD_TxCpltCallback(SMARTCARD_HandleTypeDef *hsc) { - /* Disable TXEIE and TCIE interrupts */ - CLEAR_BIT(hsc->Instance->CR1, (USART_CR1_TXEIE | USART_CR1_TCIE)); + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsc); + /* NOTE: This function should not be modified, when the callback is needed, + the HAL_SMARTCARD_TxCpltCallback can be implemented in the user file + */ +} - /* Disable the SMARTCARD DMA Tx request if enabled */ - if(HAL_IS_BIT_SET(hsc->Instance->CR3, USART_CR3_DMAT)) - { - CLEAR_BIT(hsc->Instance->CR3, USART_CR3_DMAT); +/** + * @brief Rx Transfer completed callback. + * @param hsc: Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. + * @retval None + */ +__weak void HAL_SMARTCARD_RxCpltCallback(SMARTCARD_HandleTypeDef *hsc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsc); + /* NOTE: This function should not be modified, when the callback is needed, + the HAL_SMARTCARD_RxCpltCallback can be implemented in the user file + */ +} - /* Abort the SMARTCARD DMA Tx channel: use blocking DMA Abort API (no callback) */ - if(hsc->hdmatx != NULL) - { - /* Set the SMARTCARD DMA Abort callback to Null. - No call back execution at end of DMA abort procedure */ - hsc->hdmatx->XferAbortCallback = NULL; +/** + * @brief SMARTCARD error callback. + * @param hsc: Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. + * @retval None + */ + __weak void HAL_SMARTCARD_ErrorCallback(SMARTCARD_HandleTypeDef *hsc) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hsc); + /* NOTE: This function should not be modified, when the callback is needed, + the HAL_SMARTCARD_ErrorCallback can be implemented in the user file + */ +} - HAL_DMA_Abort(hsc->hdmatx); - } - } +/** + * @} + */ - /* Reset Tx transfer counter */ - hsc->TxXferCount = 0x00U; +/** @defgroup SMARTCARD_Exported_Functions_Group3 Peripheral State and Errors functions + * @brief SMARTCARD State and Errors functions + * +@verbatim + ============================================================================== + ##### Peripheral State and Errors functions ##### + ============================================================================== + [..] + This subsection provides a set of functions allowing to return the State of SmartCard + communication process and also return Peripheral Errors occurred during communication process + (+) HAL_SMARTCARD_GetState() API can be helpful to check in run-time the state + of the SMARTCARD peripheral. + (+) HAL_SMARTCARD_GetError() check in run-time errors that could be occurred during + communication. - /* Restore hsc->gState to Ready */ - hsc->gState = HAL_SMARTCARD_STATE_READY; +@endverbatim + * @{ + */ - return HAL_OK; +/** + * @brief Returns the SMARTCARD state. + * @param hsc: Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. + * @retval HAL state + */ +HAL_SMARTCARD_StateTypeDef HAL_SMARTCARD_GetState(SMARTCARD_HandleTypeDef *hsc) +{ + return hsc->State; } /** - * @brief Abort ongoing Receive transfer (blocking mode). - * @param hsc SMARTCARD handle. - * @note This procedure could be used for aborting any ongoing transfer started in Interrupt or DMA mode. - * This procedure performs following operations : - * - Disable PPP Interrupts - * - Disable the DMA transfer in the peripheral register (if enabled) - * - Abort DMA transfer by calling HAL_DMA_Abort (in case of transfer in DMA mode) - * - Set handle State to READY - * @note This procedure is executed in blocking mode : when exiting function, Abort is considered as completed. - * @retval HAL status -*/ -HAL_StatusTypeDef HAL_SMARTCARD_AbortReceive(SMARTCARD_HandleTypeDef *hsc) + * @brief Return the SMARTCARD error code + * @param hsc: Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. + * @retval SMARTCARD Error Code + */ +uint32_t HAL_SMARTCARD_GetError(SMARTCARD_HandleTypeDef *hsc) { - /* Disable RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */ - CLEAR_BIT(hsc->Instance->CR1, (USART_CR1_RXNEIE | USART_CR1_PEIE)); - CLEAR_BIT(hsc->Instance->CR3, USART_CR3_EIE); - - /* Disable the SMARTCARD DMA Rx request if enabled */ - if(HAL_IS_BIT_SET(hsc->Instance->CR3, USART_CR3_DMAR)) - { - CLEAR_BIT(hsc->Instance->CR3, USART_CR3_DMAR); + return hsc->ErrorCode; +} - /* Abort the SMARTCARD DMA Rx channel: use blocking DMA Abort API (no callback) */ - if(hsc->hdmarx != NULL) - { - /* Set the SMARTCARD DMA Abort callback to Null. - No call back execution at end of DMA abort procedure */ - hsc->hdmarx->XferAbortCallback = NULL; +/** + * @} + */ + +/** + * @} + */ - HAL_DMA_Abort(hsc->hdmarx); - } - } +/** @defgroup SMARTCARD_Private_Functions SMARTCARD Private Functions + * @brief SMARTCARD Private functions + * @{ + */ +/** + * @brief DMA SMARTCARD transmit process complete callback. + * @param hdma: Pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void SMARTCARD_DMATransmitCplt(DMA_HandleTypeDef *hdma) +{ + SMARTCARD_HandleTypeDef* hsc = ( SMARTCARD_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; - /* Reset Rx transfer counter */ - hsc->RxXferCount = 0x00U; + hsc->TxXferCount = 0; - /* Restore hsc->RxState to Ready */ - hsc->RxState = HAL_SMARTCARD_STATE_READY; + /* Disable the DMA transfer for transmit request by setting the DMAT bit + in the SMARTCARD CR3 register */ + CLEAR_BIT(hsc->Instance->CR3, USART_CR3_DMAT); - return HAL_OK; + /* Enable the SMARTCARD Transmit Complete Interrupt */ + __HAL_SMARTCARD_ENABLE_IT(hsc, SMARTCARD_IT_TC); } /** - * @brief Abort ongoing transfers (Interrupt mode). - * @param hsc SMARTCARD handle. - * @note This procedure could be used for aborting any ongoing transfer started in Interrupt or DMA mode. - * This procedure performs following operations : - * - Disable PPP Interrupts - * - Disable the DMA transfer in the peripheral register (if enabled) - * - Abort DMA transfer by calling HAL_DMA_Abort_IT (in case of transfer in DMA mode) - * - Set handle State to READY - * - At abort completion, call user abort complete callback - * @note This procedure is executed in Interrupt mode, meaning that abort procedure could be - * considered as completed only when user abort complete callback is executed (not when exiting function). - * @retval HAL status -*/ -HAL_StatusTypeDef HAL_SMARTCARD_Abort_IT(SMARTCARD_HandleTypeDef *hsc) -{ - uint32_t AbortCplt = 0x01U; - - /* Disable TXEIE, TCIE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */ - CLEAR_BIT(hsc->Instance->CR1, (USART_CR1_RXNEIE | USART_CR1_PEIE | USART_CR1_TXEIE | USART_CR1_TCIE)); - CLEAR_BIT(hsc->Instance->CR3, USART_CR3_EIE); - - /* If DMA Tx and/or DMA Rx Handles are associated to SMARTCARD Handle, DMA Abort complete callbacks should be initialised - before any call to DMA Abort functions */ - /* DMA Tx Handle is valid */ - if(hsc->hdmatx != NULL) - { - /* Set DMA Abort Complete callback if SMARTCARD DMA Tx request if enabled. - Otherwise, set it to NULL */ - if(HAL_IS_BIT_SET(hsc->Instance->CR3, USART_CR3_DMAT)) - { - hsc->hdmatx->XferAbortCallback = SMARTCARD_DMATxAbortCallback; - } - else - { - hsc->hdmatx->XferAbortCallback = NULL; - } - } - /* DMA Rx Handle is valid */ - if(hsc->hdmarx != NULL) - { - /* Set DMA Abort Complete callback if SMARTCARD DMA Rx request if enabled. - Otherwise, set it to NULL */ - if(HAL_IS_BIT_SET(hsc->Instance->CR3, USART_CR3_DMAR)) - { - hsc->hdmarx->XferAbortCallback = SMARTCARD_DMARxAbortCallback; - } - else - { - hsc->hdmarx->XferAbortCallback = NULL; - } - } - - /* Disable the SMARTCARD DMA Tx request if enabled */ - if(HAL_IS_BIT_SET(hsc->Instance->CR3, USART_CR3_DMAT)) - { - /* Disable DMA Tx at SMARTCARD level */ - CLEAR_BIT(hsc->Instance->CR3, USART_CR3_DMAT); - - /* Abort the SMARTCARD DMA Tx channel : use non blocking DMA Abort API (callback) */ - if(hsc->hdmatx != NULL) - { - /* SMARTCARD Tx DMA Abort callback has already been initialised : - will lead to call HAL_SMARTCARD_AbortCpltCallback() at end of DMA abort procedure */ - - /* Abort DMA TX */ - if(HAL_DMA_Abort_IT(hsc->hdmatx) != HAL_OK) - { - hsc->hdmatx->XferAbortCallback = NULL; - } - else - { - AbortCplt = 0x00U; - } - } - } - - /* Disable the SMARTCARD DMA Rx request if enabled */ - if(HAL_IS_BIT_SET(hsc->Instance->CR3, USART_CR3_DMAR)) - { - CLEAR_BIT(hsc->Instance->CR3, USART_CR3_DMAR); - - /* Abort the SMARTCARD DMA Rx channel : use non blocking DMA Abort API (callback) */ - if(hsc->hdmarx != NULL) - { - /* SMARTCARD Rx DMA Abort callback has already been initialised : - will lead to call HAL_SMARTCARD_AbortCpltCallback() at end of DMA abort procedure */ - - /* Abort DMA RX */ - if(HAL_DMA_Abort_IT(hsc->hdmarx) != HAL_OK) - { - hsc->hdmarx->XferAbortCallback = NULL; - AbortCplt = 0x01U; - } - else - { - AbortCplt = 0x00U; - } - } - } - - /* if no DMA abort complete callback execution is required => call user Abort Complete callback */ - if(AbortCplt == 0x01U) - { - /* Reset Tx and Rx transfer counters */ - hsc->TxXferCount = 0x00U; - hsc->RxXferCount = 0x00U; - - /* Reset ErrorCode */ - hsc->ErrorCode = HAL_SMARTCARD_ERROR_NONE; - - /* Restore hsc->gState and hsc->RxState to Ready */ - hsc->gState = HAL_SMARTCARD_STATE_READY; - hsc->RxState = HAL_SMARTCARD_STATE_READY; - - /* As no DMA to be aborted, call directly user Abort complete callback */ - HAL_SMARTCARD_AbortCpltCallback(hsc); - } - return HAL_OK; -} - -/** - * @brief Abort ongoing Transmit transfer (Interrupt mode). - * @param hsc SMARTCARD handle. - * @note This procedure could be used for aborting any ongoing transfer started in Interrupt or DMA mode. - * This procedure performs following operations : - * - Disable PPP Interrupts - * - Disable the DMA transfer in the peripheral register (if enabled) - * - Abort DMA transfer by calling HAL_DMA_Abort_IT (in case of transfer in DMA mode) - * - Set handle State to READY - * - At abort completion, call user abort complete callback - * @note This procedure is executed in Interrupt mode, meaning that abort procedure could be - * considered as completed only when user abort complete callback is executed (not when exiting function). - * @retval HAL status -*/ -HAL_StatusTypeDef HAL_SMARTCARD_AbortTransmit_IT(SMARTCARD_HandleTypeDef *hsc) -{ - /* Disable TXEIE and TCIE interrupts */ - CLEAR_BIT(hsc->Instance->CR1, (USART_CR1_TXEIE | USART_CR1_TCIE)); - - /* Disable the SMARTCARD DMA Tx request if enabled */ - if(HAL_IS_BIT_SET(hsc->Instance->CR3, USART_CR3_DMAT)) - { - CLEAR_BIT(hsc->Instance->CR3, USART_CR3_DMAT); - - /* Abort the SMARTCARD DMA Tx channel : use blocking DMA Abort API (no callback) */ - if(hsc->hdmatx != NULL) - { - /* Set the SMARTCARD DMA Abort callback : - will lead to call HAL_SMARTCARD_AbortCpltCallback() at end of DMA abort procedure */ - hsc->hdmatx->XferAbortCallback = SMARTCARD_DMATxOnlyAbortCallback; - - /* Abort DMA TX */ - if(HAL_DMA_Abort_IT(hsc->hdmatx) != HAL_OK) - { - /* Call Directly hsc->hdmatx->XferAbortCallback function in case of error */ - hsc->hdmatx->XferAbortCallback(hsc->hdmatx); - } - } - else - { - /* Reset Tx transfer counter */ - hsc->TxXferCount = 0x00U; - - /* Restore hsc->gState to Ready */ - hsc->gState = HAL_SMARTCARD_STATE_READY; - - /* As no DMA to be aborted, call directly user Abort complete callback */ - HAL_SMARTCARD_AbortTransmitCpltCallback(hsc); - } - } - else - { - /* Reset Tx transfer counter */ - hsc->TxXferCount = 0x00U; - - /* Restore hsc->gState to Ready */ - hsc->gState = HAL_SMARTCARD_STATE_READY; - - /* As no DMA to be aborted, call directly user Abort complete callback */ - HAL_SMARTCARD_AbortTransmitCpltCallback(hsc); - } - - return HAL_OK; -} - -/** - * @brief Abort ongoing Receive transfer (Interrupt mode). - * @param hsc SMARTCARD handle. - * @note This procedure could be used for aborting any ongoing transfer started in Interrupt or DMA mode. - * This procedure performs following operations : - * - Disable PPP Interrupts - * - Disable the DMA transfer in the peripheral register (if enabled) - * - Abort DMA transfer by calling HAL_DMA_Abort_IT (in case of transfer in DMA mode) - * - Set handle State to READY - * - At abort completion, call user abort complete callback - * @note This procedure is executed in Interrupt mode, meaning that abort procedure could be - * considered as completed only when user abort complete callback is executed (not when exiting function). - * @retval HAL status -*/ -HAL_StatusTypeDef HAL_SMARTCARD_AbortReceive_IT(SMARTCARD_HandleTypeDef *hsc) -{ - /* Disable RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */ - CLEAR_BIT(hsc->Instance->CR1, (USART_CR1_RXNEIE | USART_CR1_PEIE)); - CLEAR_BIT(hsc->Instance->CR3, USART_CR3_EIE); - - /* Disable the SMARTCARD DMA Rx request if enabled */ - if(HAL_IS_BIT_SET(hsc->Instance->CR3, USART_CR3_DMAR)) - { - CLEAR_BIT(hsc->Instance->CR3, USART_CR3_DMAR); - - /* Abort the SMARTCARD DMA Rx channel : use blocking DMA Abort API (no callback) */ - if(hsc->hdmarx != NULL) - { - /* Set the SMARTCARD DMA Abort callback : - will lead to call HAL_SMARTCARD_AbortCpltCallback() at end of DMA abort procedure */ - hsc->hdmarx->XferAbortCallback = SMARTCARD_DMARxOnlyAbortCallback; - - /* Abort DMA RX */ - if(HAL_DMA_Abort_IT(hsc->hdmarx) != HAL_OK) - { - /* Call Directly hsc->hdmarx->XferAbortCallback function in case of error */ - hsc->hdmarx->XferAbortCallback(hsc->hdmarx); - } - } - else - { - /* Reset Rx transfer counter */ - hsc->RxXferCount = 0x00U; - - /* Restore hsc->RxState to Ready */ - hsc->RxState = HAL_SMARTCARD_STATE_READY; - - /* As no DMA to be aborted, call directly user Abort complete callback */ - HAL_SMARTCARD_AbortReceiveCpltCallback(hsc); - } - } - else - { - /* Reset Rx transfer counter */ - hsc->RxXferCount = 0x00U; - - /* Restore hsc->RxState to Ready */ - hsc->RxState = HAL_SMARTCARD_STATE_READY; - - /* As no DMA to be aborted, call directly user Abort complete callback */ - HAL_SMARTCARD_AbortReceiveCpltCallback(hsc); - } - - return HAL_OK; -} - -/** - * @brief This function handles SMARTCARD interrupt request. - * @param hsc: pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for SMARTCARD module. + * @brief DMA SMARTCARD receive process complete callback. + * @param hdma: Pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. * @retval None */ -void HAL_SMARTCARD_IRQHandler(SMARTCARD_HandleTypeDef *hsc) +static void SMARTCARD_DMAReceiveCplt(DMA_HandleTypeDef *hdma) { - uint32_t isrflags = READ_REG(hsc->Instance->SR); - uint32_t cr1its = READ_REG(hsc->Instance->CR1); - uint32_t cr3its = READ_REG(hsc->Instance->CR3); - uint32_t dmarequest = 0x00U; - uint32_t errorflags = 0x00U; - - /* If no error occurs */ - errorflags = (isrflags & (uint32_t)(USART_SR_PE | USART_SR_FE | USART_SR_ORE | USART_SR_NE)); - if(errorflags == RESET) - { - /* SMARTCARD in mode Receiver -------------------------------------------------*/ - if(((isrflags & USART_SR_RXNE) != RESET) && ((cr1its & USART_CR1_RXNEIE) != RESET)) - { - SMARTCARD_Receive_IT(hsc); - return; - } - } - - /* If some errors occur */ - if((errorflags != RESET) && (((cr3its & USART_CR3_EIE) != RESET) || ((cr1its & (USART_CR1_RXNEIE | USART_CR1_PEIE)) != RESET))) - { - /* SMARTCARD parity error interrupt occurred ---------------------------*/ - if(((isrflags & SMARTCARD_FLAG_PE) != RESET) && ((cr1its & USART_CR1_PEIE) != RESET)) - { - hsc->ErrorCode |= HAL_SMARTCARD_ERROR_PE; - } - - /* SMARTCARD noise error interrupt occurred ----------------------------*/ - if(((isrflags & SMARTCARD_FLAG_NE) != RESET) && ((cr3its & USART_CR3_EIE) != RESET)) - { - hsc->ErrorCode |= HAL_SMARTCARD_ERROR_NE; - } - - /* SMARTCARD frame error interrupt occurred ----------------------------*/ - if(((isrflags & SMARTCARD_FLAG_FE) != RESET) && ((cr3its & USART_CR3_EIE) != RESET)) - { - hsc->ErrorCode |= HAL_SMARTCARD_ERROR_FE; - } + SMARTCARD_HandleTypeDef* hsc = ( SMARTCARD_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; - /* SMARTCARD Over-Run interrupt occurred -------------------------------*/ - if(((isrflags & SMARTCARD_FLAG_ORE) != RESET) && ((cr3its & USART_CR3_EIE) != RESET)) - { - hsc->ErrorCode |= HAL_SMARTCARD_ERROR_ORE; - } + hsc->RxXferCount = 0; - /* Call SMARTCARD Error Call back function if need be ------------------*/ - if(hsc->ErrorCode != HAL_SMARTCARD_ERROR_NONE) - { - /* SMARTCARD in mode Receiver ----------------------------------------*/ - if(((isrflags & USART_SR_RXNE) != RESET) && ((cr1its & USART_CR1_RXNEIE) != RESET)) - { - SMARTCARD_Receive_IT(hsc); - } - - /* If Overrun error occurs, or if any error occurs in DMA mode reception, - consider error as blocking */ - dmarequest = HAL_IS_BIT_SET(hsc->Instance->CR3, USART_CR3_DMAR); - if(((hsc->ErrorCode & HAL_SMARTCARD_ERROR_ORE) != RESET) || dmarequest) - { - /* Blocking error : transfer is aborted - Set the SMARTCARD state ready to be able to start again the process, - Disable Rx Interrupts, and disable Rx DMA request, if ongoing */ - SMARTCARD_EndRxTransfer(hsc); + /* Disable the DMA transfer for the receiver request by setting the DMAR bit + in the USART CR3 register */ + CLEAR_BIT(hsc->Instance->CR3, USART_CR3_DMAR); - /* Disable the SMARTCARD DMA Rx request if enabled */ - if(HAL_IS_BIT_SET(hsc->Instance->CR3, USART_CR3_DMAR)) - { - CLEAR_BIT(hsc->Instance->CR3, USART_CR3_DMAR); - - /* Abort the SMARTCARD DMA Rx channel */ - if(hsc->hdmarx != NULL) - { - /* Set the SMARTCARD DMA Abort callback : - will lead to call HAL_SMARTCARD_ErrorCallback() at end of DMA abort procedure */ - hsc->hdmarx->XferAbortCallback = SMARTCARD_DMAAbortOnError; - if(HAL_DMA_Abort_IT(hsc->hdmarx) != HAL_OK) - { - /* Call Directly XferAbortCallback function in case of error */ - hsc->hdmarx->XferAbortCallback(hsc->hdmarx); - } - } - else - { - /* Call user error callback */ - HAL_SMARTCARD_ErrorCallback(hsc); - } - } - else - { - /* Call user error callback */ - HAL_SMARTCARD_ErrorCallback(hsc); - } - } - else - { - /* Non Blocking error : transfer could go on. - Error is notified to user through user error callback */ - HAL_SMARTCARD_ErrorCallback(hsc); - hsc->ErrorCode = HAL_SMARTCARD_ERROR_NONE; - } - } - return; - } /* End if some error occurs */ - - /* SMARTCARD in mode Transmitter -------------------------------------------*/ - if(((isrflags & SMARTCARD_FLAG_TXE) != RESET) && ((cr1its & USART_CR1_TXEIE) != RESET)) + /* Check if a non-blocking transmit process is ongoing or not */ + if(hsc->State == HAL_SMARTCARD_STATE_BUSY_TX_RX) { - SMARTCARD_Transmit_IT(hsc); - return; + hsc->State = HAL_SMARTCARD_STATE_BUSY_TX; } - - /* SMARTCARD in mode Transmitter (transmission end) ------------------------*/ - if(((isrflags & SMARTCARD_FLAG_TC) != RESET) && ((cr1its & USART_CR1_TCIE) != RESET)) + else { - SMARTCARD_EndTransmit_IT(hsc); - return; + hsc->State = HAL_SMARTCARD_STATE_READY; } -} - -/** - * @brief Tx Transfer completed callbacks - * @param hsc: pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for SMARTCARD module. - * @retval None - */ -__weak void HAL_SMARTCARD_TxCpltCallback(SMARTCARD_HandleTypeDef *hsc) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hsc); - /* NOTE : This function Should not be modified, when the callback is needed, - the HAL_SMARTCARD_TxCpltCallback could be implemented in the user file - */ -} - -/** - * @brief Rx Transfer completed callbacks - * @param hsc: pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for SMARTCARD module. - * @retval None - */ -__weak void HAL_SMARTCARD_RxCpltCallback(SMARTCARD_HandleTypeDef *hsc) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hsc); - /* NOTE : This function Should not be modified, when the callback is needed, - the HAL_SMARTCARD_RxCpltCallback could be implemented in the user file - */ -} - -/** - * @brief SMARTCARD error callbacks - * @param hsc: pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for SMARTCARD module. - * @retval None - */ -__weak void HAL_SMARTCARD_ErrorCallback(SMARTCARD_HandleTypeDef *hsc) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hsc); - /* NOTE : This function Should not be modified, when the callback is needed, - the HAL_SMARTCARD_ErrorCallback could be implemented in the user file - */ -} - -/** - * @brief SMARTCARD Abort Complete callback. - * @param hsc SMARTCARD handle. - * @retval None - */ -__weak void HAL_SMARTCARD_AbortCpltCallback (SMARTCARD_HandleTypeDef *hsc) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hsc); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_SMARTCARD_AbortCpltCallback can be implemented in the user file. - */ -} - -/** - * @brief SMARTCARD Abort Transmit Complete callback. - * @param hsc SMARTCARD handle. - * @retval None - */ -__weak void HAL_SMARTCARD_AbortTransmitCpltCallback (SMARTCARD_HandleTypeDef *hsc) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hsc); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_SMARTCARD_AbortTransmitCpltCallback can be implemented in the user file. - */ -} - -/** - * @brief SMARTCARD Abort ReceiveComplete callback. - * @param hsc SMARTCARD handle. - * @retval None - */ -__weak void HAL_SMARTCARD_AbortReceiveCpltCallback (SMARTCARD_HandleTypeDef *hsc) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hsc); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_SMARTCARD_AbortReceiveCpltCallback can be implemented in the user file. - */ -} -/** - * @} - */ - -/** @defgroup SMARTCARD_Exported_Functions_Group3 Peripheral State and Errors functions - * @brief SMARTCARD State and Errors functions - * -@verbatim - =============================================================================== - ##### Peripheral State and Errors functions ##### - =============================================================================== - [..] - This subsection provides a set of functions allowing to control the SmartCard. - (+) HAL_SMARTCARD_GetState() API can be helpful to check in run-time the state of the SmartCard peripheral. - (+) HAL_SMARTCARD_GetError() check in run-time errors that could be occurred during communication. -@endverbatim - * @{ - */ - -/** - * @brief return the SMARTCARD state - * @param hsc: pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for SMARTCARD module. - * @retval HAL state - */ -HAL_SMARTCARD_StateTypeDef HAL_SMARTCARD_GetState(SMARTCARD_HandleTypeDef *hsc) -{ - uint32_t temp1= 0x00U, temp2 = 0x00U; - temp1 = hsc->gState; - temp2 = hsc->RxState; - - return (HAL_SMARTCARD_StateTypeDef)(temp1 | temp2); -} - -/** - * @brief Return the SMARTCARD error code - * @param hsc : pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for the specified SMARTCARD. - * @retval SMARTCARD Error Code - */ -uint32_t HAL_SMARTCARD_GetError(SMARTCARD_HandleTypeDef *hsc) -{ - return hsc->ErrorCode; -} - -/** - * @} - */ - -/** - * @brief DMA SMARTCARD transmit process complete callback - * @param hdma: pointer to a DMA_HandleTypeDef structure that contains - * the configuration information for the specified DMA module. - * @retval None - */ -static void SMARTCARD_DMATransmitCplt(DMA_HandleTypeDef *hdma) -{ - SMARTCARD_HandleTypeDef* hsc = ( SMARTCARD_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; - - hsc->TxXferCount = 0U; - - /* Disable the DMA transfer for transmit request by setting the DMAT bit - in the USART CR3 register */ - CLEAR_BIT(hsc->Instance->CR3, USART_CR3_DMAT); - - /* Enable the SMARTCARD Transmit Complete Interrupt */ - SET_BIT(hsc->Instance->CR1, USART_CR1_TCIE); -} - -/** - * @brief DMA SMARTCARD receive process complete callback - * @param hdma: pointer to a DMA_HandleTypeDef structure that contains - * the configuration information for the specified DMA module. - * @retval None - */ -static void SMARTCARD_DMAReceiveCplt(DMA_HandleTypeDef *hdma) -{ - SMARTCARD_HandleTypeDef* hsc = ( SMARTCARD_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; - - hsc->RxXferCount = 0U; - - /* Disable RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */ - CLEAR_BIT(hsc->Instance->CR1, (USART_CR1_RXNEIE | USART_CR1_PEIE)); - CLEAR_BIT(hsc->Instance->CR3, USART_CR3_EIE); - - /* Disable the DMA transfer for the receiver request by setting the DMAR bit - in the USART CR3 register */ - CLEAR_BIT(hsc->Instance->CR3, USART_CR3_DMAR); - - /* At end of Rx process, restore hsc->RxState to Ready */ - hsc->RxState = HAL_SMARTCARD_STATE_READY; - HAL_SMARTCARD_RxCpltCallback(hsc); } /** - * @brief DMA SMARTCARD communication error callback - * @param hdma: pointer to a DMA_HandleTypeDef structure that contains - * the configuration information for the specified DMA module. + * @brief DMA SMARTCARD communication error callback. + * @param hdma: Pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. * @retval None */ static void SMARTCARD_DMAError(DMA_HandleTypeDef *hdma) { - uint32_t dmarequest = 0x00U; SMARTCARD_HandleTypeDef* hsc = ( SMARTCARD_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; - hsc->RxXferCount = 0U; - hsc->TxXferCount = 0U; - hsc->ErrorCode = HAL_SMARTCARD_ERROR_DMA; - /* Stop SMARTCARD DMA Tx request if ongoing */ - dmarequest = HAL_IS_BIT_SET(hsc->Instance->CR3, USART_CR3_DMAT); - if((hsc->gState == HAL_SMARTCARD_STATE_BUSY_TX) && dmarequest) - { - SMARTCARD_EndTxTransfer(hsc); - } - - /* Stop SMARTCARD DMA Rx request if ongoing */ - dmarequest = HAL_IS_BIT_SET(hsc->Instance->CR3, USART_CR3_DMAR); - if((hsc->RxState == HAL_SMARTCARD_STATE_BUSY_RX) && dmarequest) - { - SMARTCARD_EndRxTransfer(hsc); - } - + hsc->RxXferCount = 0; + hsc->TxXferCount = 0; + hsc->ErrorCode = HAL_SMARTCARD_ERROR_DMA; + hsc->State= HAL_SMARTCARD_STATE_READY; + HAL_SMARTCARD_ErrorCallback(hsc); } /** * @brief This function handles SMARTCARD Communication Timeout. - * @param hsc: SMARTCARD handle + * @param hsc: Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. * @param Flag: specifies the SMARTCARD flag to check. * @param Status: The new Flag status (SET or RESET). * @param Timeout: Timeout duration - * @param Tickstart: tick start value * @retval HAL status */ -static HAL_StatusTypeDef SMARTCARD_WaitOnFlagUntilTimeout(SMARTCARD_HandleTypeDef *hsc, uint32_t Flag, FlagStatus Status, uint32_t Tickstart, uint32_t Timeout) +static HAL_StatusTypeDef SMARTCARD_WaitOnFlagUntilTimeout(SMARTCARD_HandleTypeDef *hsc, uint32_t Flag, FlagStatus Status, uint32_t Timeout) { + uint32_t tickstart = 0; + + /* Get tick */ + tickstart = HAL_GetTick(); + /* Wait until flag is set */ - while((__HAL_SMARTCARD_GET_FLAG(hsc, Flag) ? SET : RESET) == Status) + if(Status == RESET) { - /* Check for the Timeout */ - if(Timeout != HAL_MAX_DELAY) + while(__HAL_SMARTCARD_GET_FLAG(hsc, Flag) == RESET) { - if((Timeout == 0U)||((HAL_GetTick() - Tickstart ) > Timeout)) + /* Check for the Timeout */ + if(Timeout != HAL_MAX_DELAY) { - /* Disable TXE and RXNE interrupts for the interrupt process */ - CLEAR_BIT(hsc->Instance->CR1, USART_CR1_TXEIE); - CLEAR_BIT(hsc->Instance->CR1, USART_CR1_RXNEIE); - - hsc->gState= HAL_SMARTCARD_STATE_READY; - hsc->RxState= HAL_SMARTCARD_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(hsc); - - return HAL_TIMEOUT; - } - } - } - return HAL_OK; -} - -/** - * @brief End ongoing Tx transfer on SMARTCARD peripheral (following error detection or Transmit completion). - * @param hsc: SMARTCARD handle. - * @retval None - */ -static void SMARTCARD_EndTxTransfer(SMARTCARD_HandleTypeDef *hsc) -{ - /* At end of Tx process, restore hsc->gState to Ready */ - hsc->gState = HAL_SMARTCARD_STATE_READY; - - /* Disable TXEIE and TCIE interrupts */ - CLEAR_BIT(hsc->Instance->CR1, (USART_CR1_TXEIE | USART_CR1_TCIE)); -} - - -/** - * @brief End ongoing Rx transfer on SMARTCARD peripheral (following error detection or Reception completion). - * @param hsc: SMARTCARD handle. - * @retval None - */ -static void SMARTCARD_EndRxTransfer(SMARTCARD_HandleTypeDef *hsc) -{ - /* At end of Rx process, restore hsc->RxState to Ready */ - hsc->RxState = HAL_SMARTCARD_STATE_READY; - - /* Disable RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */ - CLEAR_BIT(hsc->Instance->CR1, (USART_CR1_RXNEIE | USART_CR1_PEIE)); - CLEAR_BIT(hsc->Instance->CR3, USART_CR3_EIE); -} - - - -/** - * @brief DMA SMARTCARD communication abort callback, when initiated by HAL services on Error - * (To be called at end of DMA Abort procedure following error occurrence). - * @param hdma DMA handle. - * @retval None - */ -static void SMARTCARD_DMAAbortOnError(DMA_HandleTypeDef *hdma) -{ - SMARTCARD_HandleTypeDef* hsc = (SMARTCARD_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; - hsc->RxXferCount = 0x00U; - hsc->TxXferCount = 0x00U; + if((Timeout == 0)||((HAL_GetTick() - tickstart ) > Timeout)) + { + /* Disable TXE and RXNE interrupts for the interrupt process */ + __HAL_SMARTCARD_DISABLE_IT(hsc, SMARTCARD_IT_TXE); + __HAL_SMARTCARD_DISABLE_IT(hsc, SMARTCARD_IT_RXNE); - HAL_SMARTCARD_ErrorCallback(hsc); -} + hsc->State= HAL_SMARTCARD_STATE_READY; -/** - * @brief DMA SMARTCARD Tx communication abort callback, when initiated by user - * (To be called at end of DMA Tx Abort procedure following user abort request). - * @note When this callback is executed, User Abort complete call back is called only if no - * Abort still ongoing for Rx DMA Handle. - * @param hdma DMA handle. - * @retval None - */ -static void SMARTCARD_DMATxAbortCallback(DMA_HandleTypeDef *hdma) -{ - SMARTCARD_HandleTypeDef* hsc = ( SMARTCARD_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; - - hsc->hdmatx->XferAbortCallback = NULL; + /* Process Unlocked */ + __HAL_UNLOCK(hsc); - /* Check if an Abort process is still ongoing */ - if(hsc->hdmarx != NULL) - { - if(hsc->hdmarx->XferAbortCallback != NULL) - { - return; + return HAL_TIMEOUT; + } + } } } - - /* No Abort process still ongoing : All DMA channels are aborted, call user Abort Complete callback */ - hsc->TxXferCount = 0x00U; - hsc->RxXferCount = 0x00U; - - /* Reset ErrorCode */ - hsc->ErrorCode = HAL_SMARTCARD_ERROR_NONE; - - /* Restore hsc->gState and hsc->RxState to Ready */ - hsc->gState = HAL_SMARTCARD_STATE_READY; - hsc->RxState = HAL_SMARTCARD_STATE_READY; - - /* Call user Abort complete callback */ - HAL_SMARTCARD_AbortCpltCallback(hsc); -} - -/** - * @brief DMA SMARTCARD Rx communication abort callback, when initiated by user - * (To be called at end of DMA Rx Abort procedure following user abort request). - * @note When this callback is executed, User Abort complete call back is called only if no - * Abort still ongoing for Tx DMA Handle. - * @param hdma DMA handle. - * @retval None - */ -static void SMARTCARD_DMARxAbortCallback(DMA_HandleTypeDef *hdma) -{ - SMARTCARD_HandleTypeDef* hsc = ( SMARTCARD_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; - - hsc->hdmarx->XferAbortCallback = NULL; - - /* Check if an Abort process is still ongoing */ - if(hsc->hdmatx != NULL) + else { - if(hsc->hdmatx->XferAbortCallback != NULL) + while(__HAL_SMARTCARD_GET_FLAG(hsc, Flag) != RESET) { - return; - } - } - - /* No Abort process still ongoing : All DMA channels are aborted, call user Abort Complete callback */ - hsc->TxXferCount = 0x00U; - hsc->RxXferCount = 0x00U; - - /* Reset ErrorCode */ - hsc->ErrorCode = HAL_SMARTCARD_ERROR_NONE; - - /* Restore hsc->gState and hsc->RxState to Ready */ - hsc->gState = HAL_SMARTCARD_STATE_READY; - hsc->RxState = HAL_SMARTCARD_STATE_READY; - - /* Call user Abort complete callback */ - HAL_SMARTCARD_AbortCpltCallback(hsc); -} - -/** - * @brief DMA SMARTCARD Tx communication abort callback, when initiated by user by a call to - * HAL_SMARTCARD_AbortTransmit_IT API (Abort only Tx transfer) - * (This callback is executed at end of DMA Tx Abort procedure following user abort request, - * and leads to user Tx Abort Complete callback execution). - * @param hdma DMA handle. - * @retval None - */ -static void SMARTCARD_DMATxOnlyAbortCallback(DMA_HandleTypeDef *hdma) -{ - SMARTCARD_HandleTypeDef* hsc = ( SMARTCARD_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; - - hsc->TxXferCount = 0x00U; - - /* Restore hsc->gState to Ready */ - hsc->gState = HAL_SMARTCARD_STATE_READY; - - /* Call user Abort complete callback */ - HAL_SMARTCARD_AbortTransmitCpltCallback(hsc); -} - -/** - * @brief DMA SMARTCARD Rx communication abort callback, when initiated by user by a call to - * HAL_SMARTCARD_AbortReceive_IT API (Abort only Rx transfer) - * (This callback is executed at end of DMA Rx Abort procedure following user abort request, - * and leads to user Rx Abort Complete callback execution). - * @param hdma DMA handle. - * @retval None - */ -static void SMARTCARD_DMARxOnlyAbortCallback(DMA_HandleTypeDef *hdma) -{ - SMARTCARD_HandleTypeDef* hsc = ( SMARTCARD_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; - - hsc->RxXferCount = 0x00U; + /* Check for the Timeout */ + if(Timeout != HAL_MAX_DELAY) + { + if((Timeout == 0)||((HAL_GetTick() - tickstart ) > Timeout)) + { + /* Disable TXE and RXNE interrupts for the interrupt process */ + __HAL_SMARTCARD_DISABLE_IT(hsc, SMARTCARD_IT_TXE); + __HAL_SMARTCARD_DISABLE_IT(hsc, SMARTCARD_IT_RXNE); - /* Restore hsc->RxState to Ready */ - hsc->RxState = HAL_SMARTCARD_STATE_READY; + hsc->State= HAL_SMARTCARD_STATE_READY; - /* Call user Abort complete callback */ - HAL_SMARTCARD_AbortReceiveCpltCallback(hsc); + /* Process Unlocked */ + __HAL_UNLOCK(hsc); + + return HAL_TIMEOUT; + } + } + } + } + return HAL_OK; } /** - * @brief Send an amount of data in non blocking mode - * @param hsc: pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for SMARTCARD module. + * @brief Send an amount of data in non-blocking mode. + * @param hsc: Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. + * Function called under interruption only, once + * interruptions have been enabled by HAL_SMARTCARD_Transmit_IT() * @retval HAL status */ static HAL_StatusTypeDef SMARTCARD_Transmit_IT(SMARTCARD_HandleTypeDef *hsc) { - uint16_t* tmp; - - /* Check that a Tx process is ongoing */ - if(hsc->gState == HAL_SMARTCARD_STATE_BUSY_TX) + uint32_t tmp_state = 0; + + tmp_state = hsc->State; + if((tmp_state == HAL_SMARTCARD_STATE_BUSY_TX) || (tmp_state == HAL_SMARTCARD_STATE_BUSY_TX_RX)) { - tmp = (uint16_t*) hsc->pTxBuffPtr; - hsc->Instance->DR = (uint16_t)(*tmp & (uint16_t)0x01FF); - hsc->pTxBuffPtr += 1U; + WRITE_REG(hsc->Instance->DR, (*hsc->pTxBuffPtr++ & (uint8_t)0xFF)); - if(--hsc->TxXferCount == 0U) + if(--hsc->TxXferCount == 0) { - /* Disable the SMARTCARD Transmit data register empty Interrupt */ - CLEAR_BIT(hsc->Instance->CR1, USART_CR1_TXEIE); + /* Disable the SMARTCARD Transmit Data Register Empty Interrupt */ + __HAL_SMARTCARD_DISABLE_IT(hsc, SMARTCARD_IT_TXE); - /* Enable the SMARTCARD Transmit Complete Interrupt */ - SET_BIT(hsc->Instance->CR1, USART_CR1_TCIE); + /* Enable the SMARTCARD Transmit Complete Interrupt */ + __HAL_SMARTCARD_ENABLE_IT(hsc, SMARTCARD_IT_TC); } - + return HAL_OK; } else @@ -1748,6 +1164,7 @@ static HAL_StatusTypeDef SMARTCARD_Transmit_IT(SMARTCARD_HandleTypeDef *hsc) } } + /** * @brief Wraps up transmission in non blocking mode. * @param hsmartcard: pointer to a SMARTCARD_HandleTypeDef structure that contains @@ -1756,49 +1173,62 @@ static HAL_StatusTypeDef SMARTCARD_Transmit_IT(SMARTCARD_HandleTypeDef *hsc) */ static HAL_StatusTypeDef SMARTCARD_EndTransmit_IT(SMARTCARD_HandleTypeDef *hsmartcard) { - /* Disable the SMARTCARD Transmit Complete Interrupt */ - CLEAR_BIT(hsmartcard->Instance->CR1, USART_CR1_TCIE); + /* Disable the SMARTCARD Transmit Complete Interrupt */ + __HAL_SMARTCARD_DISABLE_IT(hsmartcard, SMARTCARD_IT_TC); + + /* Check if a receive process is ongoing or not */ + if(hsmartcard->State == HAL_SMARTCARD_STATE_BUSY_TX_RX) + { + hsmartcard->State = HAL_SMARTCARD_STATE_BUSY_RX; + } + else + { + /* Disable the SMARTCARD Error Interrupt: (Frame error, noise error, overrun error) */ + __HAL_SMARTCARD_DISABLE_IT(hsmartcard, SMARTCARD_IT_ERR); + + hsmartcard->State = HAL_SMARTCARD_STATE_READY; + } - /* Disable the SMARTCARD Error Interrupt: (Frame error, noise error, overrun error) */ - CLEAR_BIT(hsmartcard->Instance->CR3, USART_CR3_EIE); - - /* Tx process is ended, restore hsmartcard->gState to Ready */ - hsmartcard->gState = HAL_SMARTCARD_STATE_READY; - HAL_SMARTCARD_TxCpltCallback(hsmartcard); return HAL_OK; } + /** - * @brief Receive an amount of data in non blocking mode - * @param hsc: pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for SMARTCARD module. + * @brief Receive an amount of data in non-blocking mode. + * @param hsc: Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. * @retval HAL status */ static HAL_StatusTypeDef SMARTCARD_Receive_IT(SMARTCARD_HandleTypeDef *hsc) { - uint16_t* tmp; - - /* Check that a Rx process is ongoing */ - if(hsc->RxState == HAL_SMARTCARD_STATE_BUSY_RX) + uint32_t tmp_state = 0; + + tmp_state = hsc->State; + if((tmp_state == HAL_SMARTCARD_STATE_BUSY_RX) || (tmp_state == HAL_SMARTCARD_STATE_BUSY_TX_RX)) { - tmp = (uint16_t*) hsc->pRxBuffPtr; - *tmp = (uint8_t)(hsc->Instance->DR & (uint8_t)0x00FF); - hsc->pRxBuffPtr += 1U; + *hsc->pRxBuffPtr++ = (uint8_t)(hsc->Instance->DR & (uint8_t)0xFF); - if(--hsc->RxXferCount == 0U) + if(--hsc->RxXferCount == 0) { - CLEAR_BIT(hsc->Instance->CR1, USART_CR1_RXNEIE); + __HAL_SMARTCARD_DISABLE_IT(hsc, SMARTCARD_IT_RXNE); /* Disable the SMARTCARD Parity Error Interrupt */ - CLEAR_BIT(hsc->Instance->CR1, USART_CR1_PEIE); - + __HAL_SMARTCARD_DISABLE_IT(hsc, SMARTCARD_IT_PE); + /* Disable the SMARTCARD Error Interrupt: (Frame error, noise error, overrun error) */ - CLEAR_BIT(hsc->Instance->CR3, USART_CR3_EIE); + __HAL_SMARTCARD_DISABLE_IT(hsc, SMARTCARD_IT_ERR); - /* Rx process is completed, restore hsc->RxState to Ready */ - hsc->RxState = HAL_SMARTCARD_STATE_READY; + /* Check if a non-blocking transmit process is ongoing or not */ + if(hsc->State == HAL_SMARTCARD_STATE_BUSY_TX_RX) + { + hsc->State = HAL_SMARTCARD_STATE_BUSY_TX; + } + else + { + hsc->State = HAL_SMARTCARD_STATE_READY; + } HAL_SMARTCARD_RxCpltCallback(hsc); @@ -1808,22 +1238,19 @@ static HAL_StatusTypeDef SMARTCARD_Receive_IT(SMARTCARD_HandleTypeDef *hsc) } else { - return HAL_BUSY; + return HAL_BUSY; } } /** - * @brief Configure the SMARTCARD peripheral - * @param hsc: pointer to a SMARTCARD_HandleTypeDef structure that contains - * the configuration information for SMARTCARD module. + * @brief Configures the SMARTCARD peripheral. + * @param hsc: Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. * @retval None */ static void SMARTCARD_SetConfig(SMARTCARD_HandleTypeDef *hsc) { - uint32_t tmpreg = 0x00U; - /* Check the parameters */ - assert_param(IS_SMARTCARD_INSTANCE(hsc->Instance)); assert_param(IS_SMARTCARD_POLARITY(hsc->Init.CLKPolarity)); assert_param(IS_SMARTCARD_PHASE(hsc->Init.CLKPhase)); assert_param(IS_SMARTCARD_LASTBIT(hsc->Init.CLKLastBit)); @@ -1834,58 +1261,38 @@ static void SMARTCARD_SetConfig(SMARTCARD_HandleTypeDef *hsc) assert_param(IS_SMARTCARD_MODE(hsc->Init.Mode)); assert_param(IS_SMARTCARD_NACK_STATE(hsc->Init.NACKState)); - /* The LBCL, CPOL and CPHA bits have to be selected when both the transmitter and the receiver are disabled (TE=RE=0) to ensure that the clock pulses function correctly. */ - CLEAR_BIT(hsc->Instance->CR1, (USART_CR1_TE | USART_CR1_RE)); + CLEAR_BIT(hsc->Instance->CR1, (uint32_t)(USART_CR1_TE | USART_CR1_RE)); - /*---------------------------- USART CR2 Configuration ---------------------*/ - tmpreg = hsc->Instance->CR2; + /*------ SMARTCARD-associated USART registers setting : CR2 Configuration ------*/ /* Clear CLKEN, CPOL, CPHA and LBCL bits */ - tmpreg &= (uint32_t)~((uint32_t)(USART_CR2_CPHA | USART_CR2_CPOL | USART_CR2_CLKEN | USART_CR2_LBCL)); /* Configure the SMARTCARD Clock, CPOL, CPHA and LastBit -----------------------*/ /* Set CPOL bit according to hsc->Init.CLKPolarity value */ /* Set CPHA bit according to hsc->Init.CLKPhase value */ /* Set LBCL bit according to hsc->Init.CLKLastBit value */ - /* Set Stop Bits: Set STOP[13:12] bits according to hsc->Init.StopBits value */ - tmpreg |= (uint32_t)(USART_CR2_CLKEN | hsc->Init.CLKPolarity | - hsc->Init.CLKPhase| hsc->Init.CLKLastBit | hsc->Init.StopBits); - /* Write to USART CR2 */ - WRITE_REG(hsc->Instance->CR2, (uint32_t)tmpreg); + MODIFY_REG(hsc->Instance->CR2, + ((uint32_t)(USART_CR2_CPHA | USART_CR2_CPOL | USART_CR2_CLKEN | USART_CR2_LBCL)), + ((uint32_t)(USART_CR2_CLKEN | hsc->Init.CLKPolarity | hsc->Init.CLKPhase| hsc->Init.CLKLastBit)) ); - tmpreg = hsc->Instance->CR2; - - /* Clear STOP[13:12] bits */ - tmpreg &= (uint32_t)~((uint32_t)USART_CR2_STOP); - /* Set Stop Bits: Set STOP[13:12] bits according to hsc->Init.StopBits value */ - tmpreg |= (uint32_t)(hsc->Init.StopBits); - - /* Write to USART CR2 */ - WRITE_REG(hsc->Instance->CR2, (uint32_t)tmpreg); - - /*-------------------------- USART CR1 Configuration -----------------------*/ - tmpreg = hsc->Instance->CR1; + MODIFY_REG(hsc->Instance->CR2, USART_CR2_STOP,(uint32_t)(hsc->Init.StopBits)); + /*------ SMARTCARD-associated USART registers setting : CR1 Configuration ------*/ /* Clear M, PCE, PS, TE and RE bits */ - tmpreg &= (uint32_t)~((uint32_t)(USART_CR1_M | USART_CR1_PCE | USART_CR1_PS | USART_CR1_TE | \ - USART_CR1_RE)); - /* Configure the SMARTCARD Word Length, Parity and mode: - Set the M bits according to hsc->Init.WordLength value - Set PCE and PS bits according to hsc->Init.Parity value + Set the M according to hsc->Init.WordLength value (forced to 1 as 9B data frame should be selected) + Set PCE and PS bits according to hsc->Init.Parity value (PCE bit forced to 1 as parity control should always be enabled) Set TE and RE bits according to hsc->Init.Mode value */ - tmpreg |= (uint32_t)hsc->Init.WordLength | hsc->Init.Parity | hsc->Init.Mode; - - /* Write to USART CR1 */ - WRITE_REG(hsc->Instance->CR1, (uint32_t)tmpreg); + MODIFY_REG(hsc->Instance->CR1, + ((uint32_t)(USART_CR1_M | USART_CR1_PCE | USART_CR1_PS | USART_CR1_TE | USART_CR1_RE)), + ((uint32_t)(USART_CR1_M | USART_CR1_PCE | hsc->Init.Parity | hsc->Init.Mode)) ); - /*-------------------------- USART CR3 Configuration -----------------------*/ + /*------ SMARTCARD-associated USART registers setting : CR3 Configuration ------*/ /* Clear CTSE and RTSE bits */ CLEAR_BIT(hsc->Instance->CR3, (USART_CR3_RTSE | USART_CR3_CTSE)); - /*-------------------------- USART BRR Configuration -----------------------*/ - + /*------ SMARTCARD-associated USART registers setting : BRR Configuration ------*/ if(hsc->Instance == USART1) { hsc->Instance->BRR = SMARTCARD_BRR(HAL_RCC_GetPCLK2Freq(), hsc->Init.BaudRate); diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_smartcard.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_smartcard.h index 0e6a1dde19d..d139575ddcd 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_smartcard.h +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_smartcard.h @@ -2,13 +2,13 @@ ****************************************************************************** * @file stm32f1xx_hal_smartcard.h * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief Header file of SMARTCARD HAL module. ****************************************************************************** * @attention * - *

© COPYRIGHT(c) 2017 STMicroelectronics

+ *

© COPYRIGHT(c) 2016 STMicroelectronics

* * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: @@ -57,9 +57,10 @@ /* Exported types ------------------------------------------------------------*/ /** @defgroup SMARTCARD_Exported_Types SMARTCARD Exported Types * @{ - */ + */ -/** + +/** * @brief SMARTCARD Init Structure definition */ typedef struct @@ -107,65 +108,21 @@ typedef struct }SMARTCARD_InitTypeDef; /** - * @brief HAL SMARTCARD State structures definition - * @note HAL SMARTCARD State value is a combination of 2 different substates: gState and RxState. - * - gState contains SMARTCARD state information related to global Handle management - * and also information related to Tx operations. - * gState value coding follow below described bitmap : - * b7-b6 Error information - * 00 : No Error - * 01 : (Not Used) - * 10 : Timeout - * 11 : Error - * b5 IP initilisation status - * 0 : Reset (IP not initialized) - * 1 : Init done (IP not initialized. HAL SMARTCARD Init function already called) - * b4-b3 (not used) - * xx : Should be set to 00 - * b2 Intrinsic process state - * 0 : Ready - * 1 : Busy (IP busy with some configuration or internal operations) - * b1 (not used) - * x : Should be set to 0 - * b0 Tx state - * 0 : Ready (no Tx operation ongoing) - * 1 : Busy (Tx operation ongoing) - * - RxState contains information related to Rx operations. - * RxState value coding follow below described bitmap : - * b7-b6 (not used) - * xx : Should be set to 00 - * b5 IP initilisation status - * 0 : Reset (IP not initialized) - * 1 : Init done (IP not initialized) - * b4-b2 (not used) - * xxx : Should be set to 000 - * b1 Rx state - * 0 : Ready (no Rx operation ongoing) - * 1 : Busy (Rx operation ongoing) - * b0 (not used) - * x : Should be set to 0. + * @brief HAL State structures definition */ typedef enum { - HAL_SMARTCARD_STATE_RESET = 0x00U, /*!< Peripheral is not yet Initialized - Value is allowed for gState and RxState */ - HAL_SMARTCARD_STATE_READY = 0x20U, /*!< Peripheral Initialized and ready for use - Value is allowed for gState and RxState */ - HAL_SMARTCARD_STATE_BUSY = 0x24U, /*!< an internal process is ongoing - Value is allowed for gState only */ - HAL_SMARTCARD_STATE_BUSY_TX = 0x21U, /*!< Data Transmission process is ongoing - Value is allowed for gState only */ - HAL_SMARTCARD_STATE_BUSY_RX = 0x22U, /*!< Data Reception process is ongoing - Value is allowed for RxState only */ - HAL_SMARTCARD_STATE_BUSY_TX_RX = 0x23U, /*!< Data Transmission and Reception process is ongoing - Not to be used for neither gState nor RxState. - Value is result of combination (Or) between gState and RxState values */ - HAL_SMARTCARD_STATE_TIMEOUT = 0xA0U, /*!< Timeout state - Value is allowed for gState only */ - HAL_SMARTCARD_STATE_ERROR = 0xE0U /*!< Error - Value is allowed for gState only */ + HAL_SMARTCARD_STATE_RESET = 0x00, /*!< Peripheral is not yet Initialized */ + HAL_SMARTCARD_STATE_READY = 0x01, /*!< Peripheral Initialized and ready for use */ + HAL_SMARTCARD_STATE_BUSY = 0x02, /*!< an internal process is ongoing */ + HAL_SMARTCARD_STATE_BUSY_TX = 0x12, /*!< Data Transmission process is ongoing */ + HAL_SMARTCARD_STATE_BUSY_RX = 0x22, /*!< Data Reception process is ongoing */ + HAL_SMARTCARD_STATE_BUSY_TX_RX = 0x32, /*!< Data Transmission and Reception process is ongoing */ + HAL_SMARTCARD_STATE_TIMEOUT = 0x03, /*!< Timeout state */ + HAL_SMARTCARD_STATE_ERROR = 0x04 /*!< Error */ }HAL_SMARTCARD_StateTypeDef; + /** * @brief SMARTCARD handle Structure definition */ @@ -179,13 +136,13 @@ typedef struct uint16_t TxXferSize; /*!< SmartCard Tx Transfer size */ - __IO uint16_t TxXferCount; /*!< SmartCard Tx Transfer Counter */ + uint16_t TxXferCount; /*!< SmartCard Tx Transfer Counter */ uint8_t *pRxBuffPtr; /*!< Pointer to SmartCard Rx transfer Buffer */ uint16_t RxXferSize; /*!< SmartCard Rx Transfer size */ - __IO uint16_t RxXferCount; /*!< SmartCard Rx Transfer Counter */ + uint16_t RxXferCount; /*!< SmartCard Rx Transfer Counter */ DMA_HandleTypeDef *hdmatx; /*!< SmartCard Tx DMA Handle parameters */ @@ -193,14 +150,9 @@ typedef struct HAL_LockTypeDef Lock; /*!< Locking object */ - __IO HAL_SMARTCARD_StateTypeDef gState; /*!< SmartCard state information related to global Handle management - and also related to Tx operations. - This parameter can be a value of @ref HAL_SMARTCARD_StateTypeDef */ - - __IO HAL_SMARTCARD_StateTypeDef RxState; /*!< SmartCard state information related to Rx operations. - This parameter can be a value of @ref HAL_SMARTCARD_StateTypeDef */ + __IO HAL_SMARTCARD_StateTypeDef State; /*!< SmartCard communication state */ - __IO uint32_t ErrorCode; /*!< SmartCard Error code */ + __IO uint32_t ErrorCode; /*!< SmartCard Error code */ }SMARTCARD_HandleTypeDef; /** @@ -212,23 +164,26 @@ typedef struct * @{ */ -/** @defgroup SMARTCARD_Error_Code SMARTCARD Error Code +/** @defgroup SMARTCARD_Error_Codes SMARTCARD Error Codes * @{ */ -#define HAL_SMARTCARD_ERROR_NONE 0x00000000U /*!< No error */ -#define HAL_SMARTCARD_ERROR_PE 0x00000001U /*!< Parity error */ -#define HAL_SMARTCARD_ERROR_NE 0x00000002U /*!< Noise error */ -#define HAL_SMARTCARD_ERROR_FE 0x00000004U /*!< Frame error */ -#define HAL_SMARTCARD_ERROR_ORE 0x00000008U /*!< OverRun error */ -#define HAL_SMARTCARD_ERROR_DMA 0x00000010U /*!< DMA transfer error */ +#define HAL_SMARTCARD_ERROR_NONE ((uint32_t)0x00) /*!< No error */ +#define HAL_SMARTCARD_ERROR_PE ((uint32_t)0x01) /*!< Parity error */ +#define HAL_SMARTCARD_ERROR_NE ((uint32_t)0x02) /*!< Noise error */ +#define HAL_SMARTCARD_ERROR_FE ((uint32_t)0x04) /*!< frame error */ +#define HAL_SMARTCARD_ERROR_ORE ((uint32_t)0x08) /*!< Overrun error */ +#define HAL_SMARTCARD_ERROR_DMA ((uint32_t)0x10) /*!< DMA transfer error */ + /** * @} */ + /** @defgroup SMARTCARD_Word_Length SMARTCARD Word Length * @{ */ #define SMARTCARD_WORDLENGTH_9B ((uint32_t)USART_CR1_M) + /** * @} */ @@ -264,16 +219,16 @@ typedef struct /** @defgroup SMARTCARD_Clock_Polarity SMARTCARD Clock Polarity * @{ */ -#define SMARTCARD_POLARITY_LOW 0x00000000U +#define SMARTCARD_POLARITY_LOW ((uint32_t)0x00000000) #define SMARTCARD_POLARITY_HIGH ((uint32_t)USART_CR2_CPOL) /** * @} */ -/** @defgroup SMARTCARD_Clock_Phase SMARTCARD Clock Phase +/** @defgroup SMARTCARD_Clock_Phase SMARTCARD Clock Phase * @{ */ -#define SMARTCARD_PHASE_1EDGE 0x00000000U +#define SMARTCARD_PHASE_1EDGE ((uint32_t)0x00000000) #define SMARTCARD_PHASE_2EDGE ((uint32_t)USART_CR2_CPHA) /** * @} @@ -282,73 +237,78 @@ typedef struct /** @defgroup SMARTCARD_Last_Bit SMARTCARD Last Bit * @{ */ -#define SMARTCARD_LASTBIT_DISABLE 0x00000000U +#define SMARTCARD_LASTBIT_DISABLE ((uint32_t)0x00000000) #define SMARTCARD_LASTBIT_ENABLE ((uint32_t)USART_CR2_LBCL) /** * @} */ -/** @defgroup SMARTCARD_NACK_State SMARTCARD NACK State +/** @defgroup SMARTCARD_NACK_State SMARTCARD NACK State * @{ */ -#define SMARTCARD_NACK_ENABLE ((uint32_t)USART_CR3_NACK) -#define SMARTCARD_NACK_DISABLE 0x00000000U +#define SMARTCARD_NACK_ENABLE ((uint32_t)USART_CR3_NACK) +#define SMARTCARD_NACK_DISABLE ((uint32_t)0x00000000) /** * @} */ -/** @defgroup SMARTCARD_DMA_Requests SMARTCARD DMA requests +/** @defgroup SMARTCARD_DMA_Requests SMARTCARD DMA requests * @{ */ -#define SMARTCARD_DMAREQ_TX ((uint32_t)USART_CR3_DMAT) -#define SMARTCARD_DMAREQ_RX ((uint32_t)USART_CR3_DMAR) + +#define SMARTCARD_DMAREQ_TX ((uint32_t)USART_CR3_DMAT) +#define SMARTCARD_DMAREQ_RX ((uint32_t)USART_CR3_DMAR) + /** * @} */ -/** @defgroup SMARTCARD_Prescaler SMARTCARD Prescaler +/** @defgroup SMARTCARD_Prescaler SMARTCARD Prescaler * @{ */ -#define SMARTCARD_PRESCALER_SYSCLK_DIV2 0x00000001U /*!< SYSCLK divided by 2 */ -#define SMARTCARD_PRESCALER_SYSCLK_DIV4 0x00000002U /*!< SYSCLK divided by 4 */ -#define SMARTCARD_PRESCALER_SYSCLK_DIV6 0x00000003U /*!< SYSCLK divided by 6 */ -#define SMARTCARD_PRESCALER_SYSCLK_DIV8 0x00000004U /*!< SYSCLK divided by 8 */ -#define SMARTCARD_PRESCALER_SYSCLK_DIV10 0x00000005U /*!< SYSCLK divided by 10 */ -#define SMARTCARD_PRESCALER_SYSCLK_DIV12 0x00000006U /*!< SYSCLK divided by 12 */ -#define SMARTCARD_PRESCALER_SYSCLK_DIV14 0x00000007U /*!< SYSCLK divided by 14 */ -#define SMARTCARD_PRESCALER_SYSCLK_DIV16 0x00000008U /*!< SYSCLK divided by 16 */ -#define SMARTCARD_PRESCALER_SYSCLK_DIV18 0x00000009U /*!< SYSCLK divided by 18 */ -#define SMARTCARD_PRESCALER_SYSCLK_DIV20 0x0000000AU /*!< SYSCLK divided by 20 */ -#define SMARTCARD_PRESCALER_SYSCLK_DIV22 0x0000000BU /*!< SYSCLK divided by 22 */ -#define SMARTCARD_PRESCALER_SYSCLK_DIV24 0x0000000CU /*!< SYSCLK divided by 24 */ -#define SMARTCARD_PRESCALER_SYSCLK_DIV26 0x0000000DU /*!< SYSCLK divided by 26 */ -#define SMARTCARD_PRESCALER_SYSCLK_DIV28 0x0000000EU /*!< SYSCLK divided by 28 */ -#define SMARTCARD_PRESCALER_SYSCLK_DIV30 0x0000000FU /*!< SYSCLK divided by 30 */ -#define SMARTCARD_PRESCALER_SYSCLK_DIV32 0x00000010U /*!< SYSCLK divided by 32 */ -#define SMARTCARD_PRESCALER_SYSCLK_DIV34 0x00000011U /*!< SYSCLK divided by 34 */ -#define SMARTCARD_PRESCALER_SYSCLK_DIV36 0x00000012U /*!< SYSCLK divided by 36 */ -#define SMARTCARD_PRESCALER_SYSCLK_DIV38 0x00000013U /*!< SYSCLK divided by 38 */ -#define SMARTCARD_PRESCALER_SYSCLK_DIV40 0x00000014U /*!< SYSCLK divided by 40 */ -#define SMARTCARD_PRESCALER_SYSCLK_DIV42 0x00000015U /*!< SYSCLK divided by 42 */ -#define SMARTCARD_PRESCALER_SYSCLK_DIV44 0x00000016U /*!< SYSCLK divided by 44 */ -#define SMARTCARD_PRESCALER_SYSCLK_DIV46 0x00000017U /*!< SYSCLK divided by 46 */ -#define SMARTCARD_PRESCALER_SYSCLK_DIV48 0x00000018U /*!< SYSCLK divided by 48 */ -#define SMARTCARD_PRESCALER_SYSCLK_DIV50 0x00000019U /*!< SYSCLK divided by 50 */ -#define SMARTCARD_PRESCALER_SYSCLK_DIV52 0x0000001AU /*!< SYSCLK divided by 52 */ -#define SMARTCARD_PRESCALER_SYSCLK_DIV54 0x0000001BU /*!< SYSCLK divided by 54 */ -#define SMARTCARD_PRESCALER_SYSCLK_DIV56 0x0000001CU /*!< SYSCLK divided by 56 */ -#define SMARTCARD_PRESCALER_SYSCLK_DIV58 0x0000001DU /*!< SYSCLK divided by 58 */ -#define SMARTCARD_PRESCALER_SYSCLK_DIV60 0x0000001EU /*!< SYSCLK divided by 60 */ -#define SMARTCARD_PRESCALER_SYSCLK_DIV62 0x0000001FU /*!< SYSCLK divided by 62 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV2 ((uint32_t)0x00000001) /*!< SYSCLK divided by 2 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV4 ((uint32_t)0x00000002) /*!< SYSCLK divided by 4 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV6 ((uint32_t)0x00000003) /*!< SYSCLK divided by 6 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV8 ((uint32_t)0x00000004) /*!< SYSCLK divided by 8 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV10 ((uint32_t)0x00000005) /*!< SYSCLK divided by 10 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV12 ((uint32_t)0x00000006) /*!< SYSCLK divided by 12 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV14 ((uint32_t)0x00000007) /*!< SYSCLK divided by 14 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV16 ((uint32_t)0x00000008) /*!< SYSCLK divided by 16 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV18 ((uint32_t)0x00000009) /*!< SYSCLK divided by 18 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV20 ((uint32_t)0x0000000A) /*!< SYSCLK divided by 20 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV22 ((uint32_t)0x0000000B) /*!< SYSCLK divided by 22 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV24 ((uint32_t)0x0000000C) /*!< SYSCLK divided by 24 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV26 ((uint32_t)0x0000000D) /*!< SYSCLK divided by 26 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV28 ((uint32_t)0x0000000E) /*!< SYSCLK divided by 28 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV30 ((uint32_t)0x0000000F) /*!< SYSCLK divided by 30 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV32 ((uint32_t)0x00000010) /*!< SYSCLK divided by 32 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV34 ((uint32_t)0x00000011) /*!< SYSCLK divided by 34 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV36 ((uint32_t)0x00000012) /*!< SYSCLK divided by 36 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV38 ((uint32_t)0x00000013) /*!< SYSCLK divided by 38 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV40 ((uint32_t)0x00000014) /*!< SYSCLK divided by 40 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV42 ((uint32_t)0x00000015) /*!< SYSCLK divided by 42 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV44 ((uint32_t)0x00000016) /*!< SYSCLK divided by 44 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV46 ((uint32_t)0x00000017) /*!< SYSCLK divided by 46 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV48 ((uint32_t)0x00000018) /*!< SYSCLK divided by 48 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV50 ((uint32_t)0x00000019) /*!< SYSCLK divided by 50 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV52 ((uint32_t)0x0000001A) /*!< SYSCLK divided by 52 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV54 ((uint32_t)0x0000001B) /*!< SYSCLK divided by 54 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV56 ((uint32_t)0x0000001C) /*!< SYSCLK divided by 56 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV58 ((uint32_t)0x0000001D) /*!< SYSCLK divided by 58 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV60 ((uint32_t)0x0000001E) /*!< SYSCLK divided by 60 */ +#define SMARTCARD_PRESCALER_SYSCLK_DIV62 ((uint32_t)0x0000001F) /*!< SYSCLK divided by 62 */ /** * @} */ -/** @defgroup SmartCard_Flags SMARTCARD Flags + + +/** @defgroup SMARTCARD_Flags SMARTCARD Flags * Elements values convention: 0xXXXX * - 0xXXXX : Flag mask in the SR register * @{ */ + #define SMARTCARD_FLAG_TXE ((uint32_t)USART_SR_TXE) #define SMARTCARD_FLAG_TC ((uint32_t)USART_SR_TC) #define SMARTCARD_FLAG_RXNE ((uint32_t)USART_SR_RXNE) @@ -361,20 +321,24 @@ typedef struct * @} */ -/** @defgroup SmartCard_Interrupt_definition SMARTCARD Interrupts Definition +/** @defgroup SMARTCARD_Interrupt_definition SMARTCARD Interrupts Definition * Elements values convention: 0xY000XXXX - * - XXXX : Interrupt mask in the XX register - * - Y : Interrupt source register (2bits) - * - 01: CR1 register - * - 11: CR3 register + * - XXXX : Interrupt mask (16 bits) in the Y register + * - Y : Interrupt source register (4 bits) + * - 0001: CR1 register + * - 0010: CR3 register + + * * @{ */ -#define SMARTCARD_IT_PE ((uint32_t)(SMARTCARD_CR1_REG_INDEX << 28U | USART_CR1_PEIE)) -#define SMARTCARD_IT_TXE ((uint32_t)(SMARTCARD_CR1_REG_INDEX << 28U | USART_CR1_TXEIE)) -#define SMARTCARD_IT_TC ((uint32_t)(SMARTCARD_CR1_REG_INDEX << 28U | USART_CR1_TCIE)) -#define SMARTCARD_IT_RXNE ((uint32_t)(SMARTCARD_CR1_REG_INDEX << 28U | USART_CR1_RXNEIE)) -#define SMARTCARD_IT_IDLE ((uint32_t)(SMARTCARD_CR1_REG_INDEX << 28U | USART_CR1_IDLEIE)) -#define SMARTCARD_IT_ERR ((uint32_t)(SMARTCARD_CR3_REG_INDEX << 28U | USART_CR3_EIE)) + +#define SMARTCARD_IT_PE ((uint32_t)(SMARTCARD_CR1_REG_INDEX << 28 | USART_CR1_PEIE)) +#define SMARTCARD_IT_TXE ((uint32_t)(SMARTCARD_CR1_REG_INDEX << 28 | USART_CR1_TXEIE)) +#define SMARTCARD_IT_TC ((uint32_t)(SMARTCARD_CR1_REG_INDEX << 28 | USART_CR1_TCIE)) +#define SMARTCARD_IT_RXNE ((uint32_t)(SMARTCARD_CR1_REG_INDEX << 28 | USART_CR1_RXNEIE)) +#define SMARTCARD_IT_IDLE ((uint32_t)(SMARTCARD_CR1_REG_INDEX << 28 | USART_CR1_IDLEIE)) +#define SMARTCARD_IT_ERR ((uint32_t)(SMARTCARD_CR3_REG_INDEX << 28 | USART_CR3_EIE)) + /** * @} */ @@ -383,26 +347,27 @@ typedef struct * @} */ + /* Exported macro ------------------------------------------------------------*/ -/** @defgroup SMARTCARD_Exported_Macros SMARTCARD Exported Macros +/** @defgroup SMARTCARD_Exported_Macros SMARTCARD Exported Macros * @{ */ -/** @brief Reset SMARTCARD handle gstate & RxState + +/** @brief Reset SMARTCARD handle state * @param __HANDLE__: specifies the SMARTCARD Handle. * SMARTCARD Handle selects the USARTx peripheral (USART availability and x value depending on device). + * @retval None */ -#define __HAL_SMARTCARD_RESET_HANDLE_STATE(__HANDLE__) do{ \ - (__HANDLE__)->gState = HAL_SMARTCARD_STATE_RESET; \ - (__HANDLE__)->RxState = HAL_SMARTCARD_STATE_RESET; \ - } while(0U) +#define __HAL_SMARTCARD_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_SMARTCARD_STATE_RESET) /** @brief Flush the Smartcard DR register * @param __HANDLE__: specifies the SMARTCARD Handle. * SMARTCARD Handle selects the USARTx peripheral (USART availability and x value depending on device). + * @retval None */ #define __HAL_SMARTCARD_FLUSH_DRREGISTER(__HANDLE__) ((__HANDLE__)->Instance->DR) - + /** @brief Check whether the specified Smartcard flag is set or not. * @param __HANDLE__: specifies the SMARTCARD Handle. * SMARTCARD Handle selects the USARTx peripheral (USART availability and x value depending on device). @@ -427,6 +392,7 @@ typedef struct * This parameter can be any combination of the following values: * @arg SMARTCARD_FLAG_TC: Transmission Complete flag. * @arg SMARTCARD_FLAG_RXNE: Receive data register not empty flag. + * @retval None * * @note PE (Parity error), FE (Framing error), NE (Noise error) and ORE (OverRun * error) flags are cleared by software sequence: a read operation to @@ -435,42 +401,51 @@ typedef struct * @note TC flag can be also cleared by software sequence: a read operation to * USART_SR register followed by a write operation to USART_DR register. * @note TXE flag is cleared only by a write to the USART_DR register. + * + * @retval None */ #define __HAL_SMARTCARD_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->SR = ~(__FLAG__)) /** @brief Clear the SMARTCARD PE pending flag. * @param __HANDLE__: specifies the USART Handle. * SMARTCARD Handle selects the USARTx peripheral (USART availability and x value depending on device). + * @retval None */ -#define __HAL_SMARTCARD_CLEAR_PEFLAG(__HANDLE__) \ - do{ \ - __IO uint32_t tmpreg = 0x00U; \ - tmpreg = (__HANDLE__)->Instance->SR; \ - tmpreg = (__HANDLE__)->Instance->DR; \ - UNUSED(tmpreg); \ - } while(0U) +#define __HAL_SMARTCARD_CLEAR_PEFLAG(__HANDLE__) \ +do{ \ + __IO uint32_t tmpreg; \ + tmpreg = (__HANDLE__)->Instance->SR; \ + tmpreg = (__HANDLE__)->Instance->DR; \ + UNUSED(tmpreg); \ +}while(0) + + /** @brief Clear the SMARTCARD FE pending flag. * @param __HANDLE__: specifies the USART Handle. * SMARTCARD Handle selects the USARTx peripheral (USART availability and x value depending on device). + * @retval None */ #define __HAL_SMARTCARD_CLEAR_FEFLAG(__HANDLE__) __HAL_SMARTCARD_CLEAR_PEFLAG(__HANDLE__) /** @brief Clear the SMARTCARD NE pending flag. * @param __HANDLE__: specifies the USART Handle. * SMARTCARD Handle selects the USARTx peripheral (USART availability and x value depending on device). + * @retval None */ #define __HAL_SMARTCARD_CLEAR_NEFLAG(__HANDLE__) __HAL_SMARTCARD_CLEAR_PEFLAG(__HANDLE__) /** @brief Clear the SMARTCARD ORE pending flag. * @param __HANDLE__: specifies the USART Handle. * SMARTCARD Handle selects the USARTx peripheral (USART availability and x value depending on device). + * @retval None */ #define __HAL_SMARTCARD_CLEAR_OREFLAG(__HANDLE__) __HAL_SMARTCARD_CLEAR_PEFLAG(__HANDLE__) /** @brief Clear the SMARTCARD IDLE pending flag. * @param __HANDLE__: specifies the USART Handle. * SMARTCARD Handle selects the USARTx peripheral (USART availability and x value depending on device). + * @retval None */ #define __HAL_SMARTCARD_CLEAR_IDLEFLAG(__HANDLE__) __HAL_SMARTCARD_CLEAR_PEFLAG(__HANDLE__) @@ -484,12 +459,13 @@ typedef struct * @arg SMARTCARD_IT_RXNE: Receive Data register not empty interrupt * @arg SMARTCARD_IT_IDLE: Idle line detection interrupt * @arg SMARTCARD_IT_PE: Parity Error interrupt - * @arg SMARTCARD_IT_ERR: Error interrupt(Frame error, noise error, overRun error) + * @arg SMARTCARD_IT_ERR: Error interrupt(Frame error, noise error, overrun error) + * @retval None */ -#define __HAL_SMARTCARD_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((((__INTERRUPT__) >> 28U) == SMARTCARD_CR1_REG_INDEX)? ((__HANDLE__)->Instance->CR1 |= ((__INTERRUPT__) & SMARTCARD_IT_MASK)): \ - ((__HANDLE__)->Instance->CR3 |= ((__INTERRUPT__) & SMARTCARD_IT_MASK))) +#define __HAL_SMARTCARD_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((((__INTERRUPT__) >> 28) == SMARTCARD_CR1_REG_INDEX)? ((__HANDLE__)->Instance->CR1 |= ((__INTERRUPT__) & SMARTCARD_IT_MASK)): \ + ((__HANDLE__)->Instance->CR3 |= ((__INTERRUPT__) & SMARTCARD_IT_MASK))) -/** @brief Disable the specified SmartCard interrupt. +/** @brief Disable the specified SmartCard interrupts. * @param __HANDLE__: specifies the SMARTCARD Handle. * SMARTCARD Handle selects the USARTx peripheral (USART availability and x value depending on device). * @param __INTERRUPT__: specifies the SMARTCARD interrupt to disable. @@ -499,13 +475,14 @@ typedef struct * @arg SMARTCARD_IT_RXNE: Receive Data register not empty interrupt * @arg SMARTCARD_IT_IDLE: Idle line detection interrupt * @arg SMARTCARD_IT_PE: Parity Error interrupt - * @arg SMARTCARD_IT_ERR: Error interrupt(Frame error, noise error, overRun error) + * @arg SMARTCARD_IT_ERR: Error interrupt(Frame error, noise error, overrun error) */ -#define __HAL_SMARTCARD_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((((__INTERRUPT__) >> 28U) == SMARTCARD_CR1_REG_INDEX)? ((__HANDLE__)->Instance->CR1 &= ~((__INTERRUPT__) & SMARTCARD_IT_MASK)): \ - ((__HANDLE__)->Instance->CR3 &= ~ ((__INTERRUPT__) & SMARTCARD_IT_MASK))) +#define __HAL_SMARTCARD_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((((__INTERRUPT__) >> 28) == SMARTCARD_CR1_REG_INDEX)? ((__HANDLE__)->Instance->CR1 &= ~((__INTERRUPT__) & SMARTCARD_IT_MASK)): \ + ((__HANDLE__)->Instance->CR3 &= ~ ((__INTERRUPT__) & SMARTCARD_IT_MASK))) -/** @brief Checks whether the specified SmartCard interrupt has occurred or not. - * @param __HANDLE__: specifies the SmartCard Handle. +/** @brief Check whether the specified SmartCard interrupt has occurred or not. + * @param __HANDLE__: specifies the SMARTCARD Handle. + * SMARTCARD Handle selects the USARTx peripheral (USART availability and x value depending on device). * @param __IT__: specifies the SMARTCARD interrupt source to check. * This parameter can be one of the following values: * @arg SMARTCARD_IT_TXE: Transmit Data Register empty interrupt @@ -516,62 +493,135 @@ typedef struct * @arg SMARTCARD_IT_PE: Parity Error interrupt * @retval The new state of __IT__ (TRUE or FALSE). */ -#define __HAL_SMARTCARD_GET_IT_SOURCE(__HANDLE__, __IT__) (((((__IT__) >> 28U) == SMARTCARD_CR1_REG_INDEX)? (__HANDLE__)->Instance->CR1: (__HANDLE__)->Instance->CR3) & (((uint32_t)(__IT__)) & SMARTCARD_IT_MASK)) +#define __HAL_SMARTCARD_GET_IT_SOURCE(__HANDLE__, __IT__) (((((__IT__) >> 28) == SMARTCARD_CR1_REG_INDEX)? (__HANDLE__)->Instance->CR1: (__HANDLE__)->Instance->CR3) & (((uint32_t)(__IT__)) & SMARTCARD_IT_MASK)) /** @brief Enable the USART associated to the SMARTCARD Handle * @param __HANDLE__: specifies the SMARTCARD Handle. * SMARTCARD Handle selects the USARTx peripheral (USART availability and x value depending on device). - */ -#define __HAL_SMARTCARD_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 |= USART_CR1_UE) + * @retval None + */ +#define __HAL_SMARTCARD_ENABLE(__HANDLE__) (SET_BIT((__HANDLE__)->Instance->CR1, USART_CR1_UE)) /** @brief Disable the USART associated to the SMARTCARD Handle * @param __HANDLE__: specifies the SMARTCARD Handle. * SMARTCARD Handle selects the USARTx peripheral (USART availability and x value depending on device). - */ -#define __HAL_SMARTCARD_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 &= ~USART_CR1_UE) + * @retval None + */ +#define __HAL_SMARTCARD_DISABLE(__HANDLE__) (CLEAR_BIT((__HANDLE__)->Instance->CR1, USART_CR1_UE)) -/** @brief Macros to enable the SmartCard DMA request. +/** @brief Enable the SmartCard DMA request. * @param __HANDLE__: specifies the SmartCard Handle. + * SMARTCARD Handle selects the USARTx peripheral (USART availability and x value depending on device). * @param __REQUEST__: specifies the SmartCard DMA request. - * This parameter can be one of the following values: + * This parameter can be one of the following values: * @arg SMARTCARD_DMAREQ_TX: SmartCard DMA transmit request * @arg SMARTCARD_DMAREQ_RX: SmartCard DMA receive request + * @retval None */ -#define __HAL_SMARTCARD_DMA_REQUEST_ENABLE(__HANDLE__, __REQUEST__) ((__HANDLE__)->Instance->CR3 |= (__REQUEST__)) +#define __HAL_SMARTCARD_DMA_REQUEST_ENABLE(__HANDLE__, __REQUEST__) (SET_BIT((__HANDLE__)->Instance->CR3, (__REQUEST__))) -/** @brief Macros to disable the SmartCard DMA request. +/** @brief Disable the SmartCard DMA request. * @param __HANDLE__: specifies the SmartCard Handle. + * SMARTCARD Handle selects the USARTx peripheral (USART availability and x value depending on device). * @param __REQUEST__: specifies the SmartCard DMA request. - * This parameter can be one of the following values: + * This parameter can be one of the following values: * @arg SMARTCARD_DMAREQ_TX: SmartCard DMA transmit request * @arg SMARTCARD_DMAREQ_RX: SmartCard DMA receive request + * @retval None */ -#define __HAL_SMARTCARD_DMA_REQUEST_DISABLE(__HANDLE__, __REQUEST__) ((__HANDLE__)->Instance->CR3 &= ~(__REQUEST__)) +#define __HAL_SMARTCARD_DMA_REQUEST_DISABLE(__HANDLE__, __REQUEST__) (CLEAR_BIT((__HANDLE__)->Instance->CR3, (__REQUEST__))) + /** * @} */ -/* Exported functions --------------------------------------------------------*/ -/** @addtogroup SMARTCARD_Exported_Functions + + +/* Private macros --------------------------------------------------------*/ +/** @defgroup SMARTCARD_Private_Macros SMARTCARD Private Macros * @{ */ -/** @addtogroup SMARTCARD_Exported_Functions_Group1 +#define SMARTCARD_CR1_REG_INDEX 1 +#define SMARTCARD_CR3_REG_INDEX 3 + +#define SMARTCARD_DIV(__PCLK__, __BAUD__) (((__PCLK__)*25)/(4*(__BAUD__))) +#define SMARTCARD_DIVMANT(__PCLK__, __BAUD__) (SMARTCARD_DIV((__PCLK__), (__BAUD__))/100) +#define SMARTCARD_DIVFRAQ(__PCLK__, __BAUD__) (((SMARTCARD_DIV((__PCLK__), (__BAUD__)) - (SMARTCARD_DIVMANT((__PCLK__), (__BAUD__)) * 100)) * 16 + 50) / 100) +/* UART BRR = mantissa + overflow + fraction + = (UART DIVMANT << 4) + (UART DIVFRAQ & 0xF0) + (UART DIVFRAQ & 0x0F) */ +#define SMARTCARD_BRR(_PCLK_, _BAUD_) (((SMARTCARD_DIVMANT((_PCLK_), (_BAUD_)) << 4) + \ + (SMARTCARD_DIVFRAQ((_PCLK_), (_BAUD_)) & 0xF0)) + \ + (SMARTCARD_DIVFRAQ((_PCLK_), (_BAUD_)) & 0x0F)) + +/** Check the Baud rate range. + * The maximum Baud Rate is derived from the maximum clock on APB (i.e. 72 MHz) + * divided by the smallest oversampling used on the USART (i.e. 16) + * __BAUDRATE__: Baud rate set by the configuration function. + * Return : TRUE or FALSE + */ +#define IS_SMARTCARD_BAUDRATE(__BAUDRATE__) ((__BAUDRATE__) < 4500001) + +#define IS_SMARTCARD_WORD_LENGTH(LENGTH) ((LENGTH) == SMARTCARD_WORDLENGTH_9B) + +#define IS_SMARTCARD_STOPBITS(STOPBITS) (((STOPBITS) == SMARTCARD_STOPBITS_0_5) || \ + ((STOPBITS) == SMARTCARD_STOPBITS_1_5)) + +#define IS_SMARTCARD_PARITY(PARITY) (((PARITY) == SMARTCARD_PARITY_EVEN) || \ + ((PARITY) == SMARTCARD_PARITY_ODD)) + +#define IS_SMARTCARD_MODE(MODE) ((((MODE) & (~((uint32_t)SMARTCARD_MODE_TX_RX))) == 0x00) && \ + ((MODE) != (uint32_t)0x00000000)) + +#define IS_SMARTCARD_POLARITY(CPOL) (((CPOL) == SMARTCARD_POLARITY_LOW) || ((CPOL) == SMARTCARD_POLARITY_HIGH)) + +#define IS_SMARTCARD_PHASE(CPHA) (((CPHA) == SMARTCARD_PHASE_1EDGE) || ((CPHA) == SMARTCARD_PHASE_2EDGE)) + +#define IS_SMARTCARD_LASTBIT(LASTBIT) (((LASTBIT) == SMARTCARD_LASTBIT_DISABLE) || \ + ((LASTBIT) == SMARTCARD_LASTBIT_ENABLE)) + +#define IS_SMARTCARD_NACK_STATE(NACK) (((NACK) == SMARTCARD_NACK_ENABLE) || \ + ((NACK) == SMARTCARD_NACK_DISABLE)) + +#define IS_SMARTCARD_PRESCALER(PRESCALER) (((PRESCALER) >= SMARTCARD_PRESCALER_SYSCLK_DIV2) && \ + ((PRESCALER) <= SMARTCARD_PRESCALER_SYSCLK_DIV62) ) + +/** SMARTCARD interruptions flag mask + * + */ +#define SMARTCARD_IT_MASK ((uint32_t) USART_CR1_PEIE | USART_CR1_TXEIE | USART_CR1_TCIE | USART_CR1_RXNEIE | \ + USART_CR1_IDLEIE | USART_CR3_EIE ) + + +/** + * @} + */ + + +/* Exported functions --------------------------------------------------------*/ + +/** @addtogroup SMARTCARD_Exported_Functions SMARTCARD Exported Functions * @{ */ + +/** @addtogroup SMARTCARD_Exported_Functions_Group1 Initialization and de-initialization functions + * @{ + */ + /* Initialization/de-initialization functions **********************************/ HAL_StatusTypeDef HAL_SMARTCARD_Init(SMARTCARD_HandleTypeDef *hsc); -HAL_StatusTypeDef HAL_SMARTCARD_ReInit(SMARTCARD_HandleTypeDef *hsc); HAL_StatusTypeDef HAL_SMARTCARD_DeInit(SMARTCARD_HandleTypeDef *hsc); void HAL_SMARTCARD_MspInit(SMARTCARD_HandleTypeDef *hsc); void HAL_SMARTCARD_MspDeInit(SMARTCARD_HandleTypeDef *hsc); + /** * @} */ -/** @addtogroup SMARTCARD_Exported_Functions_Group2 +/** @addtogroup SMARTCARD_Exported_Functions_Group2 IO operation functions * @{ */ + /* IO operation functions *******************************************************/ HAL_StatusTypeDef HAL_SMARTCARD_Transmit(SMARTCARD_HandleTypeDef *hsc, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_SMARTCARD_Receive(SMARTCARD_HandleTypeDef *hsc, uint8_t *pData, uint16_t Size, uint32_t Timeout); @@ -579,91 +629,27 @@ HAL_StatusTypeDef HAL_SMARTCARD_Transmit_IT(SMARTCARD_HandleTypeDef *hsc, uint8_ HAL_StatusTypeDef HAL_SMARTCARD_Receive_IT(SMARTCARD_HandleTypeDef *hsc, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_SMARTCARD_Transmit_DMA(SMARTCARD_HandleTypeDef *hsc, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_SMARTCARD_Receive_DMA(SMARTCARD_HandleTypeDef *hsc, uint8_t *pData, uint16_t Size); -/* Transfer Abort functions */ -HAL_StatusTypeDef HAL_SMARTCARD_Abort(SMARTCARD_HandleTypeDef *hsc); -HAL_StatusTypeDef HAL_SMARTCARD_AbortTransmit(SMARTCARD_HandleTypeDef *hsc); -HAL_StatusTypeDef HAL_SMARTCARD_AbortReceive(SMARTCARD_HandleTypeDef *hsc); -HAL_StatusTypeDef HAL_SMARTCARD_Abort_IT(SMARTCARD_HandleTypeDef *hsc); -HAL_StatusTypeDef HAL_SMARTCARD_AbortTransmit_IT(SMARTCARD_HandleTypeDef *hsc); -HAL_StatusTypeDef HAL_SMARTCARD_AbortReceive_IT(SMARTCARD_HandleTypeDef *hsc); - void HAL_SMARTCARD_IRQHandler(SMARTCARD_HandleTypeDef *hsc); void HAL_SMARTCARD_TxCpltCallback(SMARTCARD_HandleTypeDef *hsc); void HAL_SMARTCARD_RxCpltCallback(SMARTCARD_HandleTypeDef *hsc); void HAL_SMARTCARD_ErrorCallback(SMARTCARD_HandleTypeDef *hsc); -void HAL_SMARTCARD_AbortCpltCallback(SMARTCARD_HandleTypeDef *hsc); -void HAL_SMARTCARD_AbortTransmitCpltCallback(SMARTCARD_HandleTypeDef *hsc); -void HAL_SMARTCARD_AbortReceiveCpltCallback(SMARTCARD_HandleTypeDef *hsc); -/** - * @} - */ -/** @addtogroup SMARTCARD_Exported_Functions_Group3 - * @{ - */ -/* Peripheral State functions **************************************************/ -HAL_SMARTCARD_StateTypeDef HAL_SMARTCARD_GetState(SMARTCARD_HandleTypeDef *hsc); -uint32_t HAL_SMARTCARD_GetError(SMARTCARD_HandleTypeDef *hsc); /** * @} */ -/** - * @} - */ -/* Private types -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private constants ---------------------------------------------------------*/ -/** @defgroup SMARTCARD_Private_Constants SMARTCARD Private Constants +/** @addtogroup SMARTCARD_Exported_Functions_Group3 Peripheral State and Errors functions * @{ */ -/** @brief SMARTCARD interruptions flag mask - * - */ -#define SMARTCARD_IT_MASK 0x0000FFFFU - -#define SMARTCARD_CR1_REG_INDEX 1U -#define SMARTCARD_CR3_REG_INDEX 3U -/** - * @} - */ +/* Peripheral State and Errors functions functions *****************************/ +HAL_SMARTCARD_StateTypeDef HAL_SMARTCARD_GetState(SMARTCARD_HandleTypeDef *hsc); +uint32_t HAL_SMARTCARD_GetError(SMARTCARD_HandleTypeDef *hsc); -/* Private macros --------------------------------------------------------*/ -/** @defgroup SMARTCARD_Private_Macros SMARTCARD Private Macros - * @{ - */ -#define IS_SMARTCARD_WORD_LENGTH(LENGTH) ((LENGTH) == SMARTCARD_WORDLENGTH_9B) -#define IS_SMARTCARD_STOPBITS(STOPBITS) (((STOPBITS) == SMARTCARD_STOPBITS_0_5) || \ - ((STOPBITS) == SMARTCARD_STOPBITS_1_5)) -#define IS_SMARTCARD_PARITY(PARITY) (((PARITY) == SMARTCARD_PARITY_EVEN) || \ - ((PARITY) == SMARTCARD_PARITY_ODD)) -#define IS_SMARTCARD_MODE(MODE) ((((MODE) & 0x0000FFF3U) == 0x00U) && ((MODE) != 0x000000U)) -#define IS_SMARTCARD_POLARITY(CPOL) (((CPOL) == SMARTCARD_POLARITY_LOW) || ((CPOL) == SMARTCARD_POLARITY_HIGH)) -#define IS_SMARTCARD_PHASE(CPHA) (((CPHA) == SMARTCARD_PHASE_1EDGE) || ((CPHA) == SMARTCARD_PHASE_2EDGE)) -#define IS_SMARTCARD_LASTBIT(LASTBIT) (((LASTBIT) == SMARTCARD_LASTBIT_DISABLE) || \ - ((LASTBIT) == SMARTCARD_LASTBIT_ENABLE)) -#define IS_SMARTCARD_NACK_STATE(NACK) (((NACK) == SMARTCARD_NACK_ENABLE) || \ - ((NACK) == SMARTCARD_NACK_DISABLE)) -#define IS_SMARTCARD_BAUDRATE(BAUDRATE) ((BAUDRATE) < 4500001U) - -#define SMARTCARD_DIV(_PCLK_, _BAUD_) (((_PCLK_)*25U)/(4U*(_BAUD_))) -#define SMARTCARD_DIVMANT(_PCLK_, _BAUD_) (SMARTCARD_DIV((_PCLK_), (_BAUD_))/100U) -#define SMARTCARD_DIVFRAQ(_PCLK_, _BAUD_) (((SMARTCARD_DIV((_PCLK_), (_BAUD_)) - (SMARTCARD_DIVMANT((_PCLK_), (_BAUD_)) * 100U)) * 16U + 50U) / 100U) -/* SMARTCARD BRR = mantissa + overflow + fraction - = (SMARTCARD DIVMANT << 4) + (SMARTCARD DIVFRAQ & 0xF0) + (SMARTCARD DIVFRAQ & 0x0FU) */ -#define SMARTCARD_BRR(_PCLK_, _BAUD_) (((SMARTCARD_DIVMANT((_PCLK_), (_BAUD_)) << 4U) + \ - (SMARTCARD_DIVFRAQ((_PCLK_), (_BAUD_)) & 0xF0U)) + \ - (SMARTCARD_DIVFRAQ((_PCLK_), (_BAUD_)) & 0x0FU)) /** * @} */ -/* Private functions ---------------------------------------------------------*/ -/** @defgroup SMARTCARD_Private_Functions SMARTCARD Private Functions - * @{ - */ - /** * @} */ diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_spi.c b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_spi.c index 798545eee1c..6e8607150a1 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_spi.c +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_spi.c @@ -2,16 +2,16 @@ ****************************************************************************** * @file stm32f1xx_hal_spi.c * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief SPI HAL module driver. - * This file provides firmware functions to manage the following + * + * This file provides firmware functions to manage the following * functionalities of the Serial Peripheral Interface (SPI) peripheral: * + Initialization and de-initialization functions * + IO operation functions - * + Peripheral Control functions + * + Peripheral Control functions * + Peripheral State functions - * @verbatim ============================================================================== ##### How to use this driver ##### @@ -20,12 +20,12 @@ The SPI HAL driver can be used as follows: (#) Declare a SPI_HandleTypeDef handle structure, for example: - SPI_HandleTypeDef hspi; + SPI_HandleTypeDef hspi; - (#)Initialize the SPI low level resources by implementing the HAL_SPI_MspInit() API: - (##) Enable the SPIx interface clock + (#)Initialize the SPI low level resources by implementing the HAL_SPI_MspInit ()API: + (##) Enable the SPIx interface clock (##) SPI pins configuration - (+++) Enable the clock for the SPI GPIOs + (+++) Enable the clock for the SPI GPIOs (+++) Configure these SPI pins as alternate function push-pull (##) NVIC configuration if you need to use interrupt process (+++) Configure the SPIx interrupt priority @@ -38,119 +38,117 @@ (+++) Associate the initilalized hdma_tx(or _rx) handle to the hspi DMA Tx (or Rx) handle (+++) Configure the priority and enable the NVIC for the transfer complete interrupt on the DMA Tx or Rx Channel - (#) Program the Mode, BidirectionalMode , Data size, Baudrate Prescaler, NSS + (#) Program the Mode, Direction , Data size, Baudrate Prescaler, NSS management, Clock polarity and phase, FirstBit and CRC configuration in the hspi Init structure. (#) Initialize the SPI registers by calling the HAL_SPI_Init() API: (++) This API configures also the low level Hardware GPIO, CLOCK, CORTEX...etc) - by calling the customized HAL_SPI_MspInit() API. + by calling the customed HAL_SPI_MspInit() API. [..] Circular mode restriction: (#) The DMA circular mode cannot be used when the SPI is configured in these modes: (##) Master 2Lines RxOnly (##) Master 1Line Rx (#) The CRC feature is not managed when the DMA circular mode is enabled - (#) When the SPI DMA Pause/Stop features are used, we must use the following APIs + (#) When the SPI DMA Pause/Stop features are used, we must use the following APIs the HAL_SPI_DMAPause()/ HAL_SPI_DMAStop() only under the SPI callbacks - [..] - Master Receive mode restriction: - (#) In Master unidirectional receive-only mode (MSTR =1, BIDIMODE=0, RXONLY=0) or - bidirectional receive mode (MSTR=1, BIDIMODE=1, BIDIOE=0), to ensure that the SPI - does not initiate a new transfer the following procedure has to be respected: - (##) HAL_SPI_DeInit() - (##) HAL_SPI_Init() @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2016 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ +/* Using the HAL it is not possible to reach all supported SPI frequency with the differents SPI Modes, - the following tables resume the max SPI frequency reached with data size 8bits/16bits, + the following table resume the max SPI frequency reached with data size 8bits/16bits, according to frequency used on APBx Peripheral Clock (fPCLK) used by the SPI instance : - - DataSize = SPI_DATASIZE_8BIT: + + For 8 bits SPI data size transfers : +--------------------------------------------------------------------------------------------------+ | | | 2Lines Fullduplex | 2Lines RxOnly | 1Line | | Process | Tranfert mode |-----------------------|-----------------------|-----------------------| | | | Master | Slave | Master | Slave | Master | Slave | |==================================================================================================| - | T | Polling | fPCLK/2 | fPCLK/16 | NA | NA | NA | NA | + | T | Polling | fPCLK/8 | fPCLK/8 | NA | NA | NA | NA | | X |----------------|-----------|-----------|-----------|-----------|-----------|-----------| - | / | Interrupt | fPCLK/8 | fPCLK/32 | NA | NA | NA | NA | + | / | Interrupt | fPCLK/32 | fPCLK/32 | NA | NA | NA | NA | | R |----------------|-----------|-----------|-----------|-----------|-----------|-----------| | X | DMA | fPCLK/2 | fPCLK/4 | NA | NA | NA | NA | |=========|================|===========|===========|===========|===========|===========|===========| - | | Polling | fPCLK/4 | fPCLK/8 | fPCLK/8 | fPCLK/16 | fPCLK/64 | fPCLK/2 | + | | Polling | fPCLK/4 | fPCLK/8 | fPCLK/128 | fPCLK/16 | fPCLK/128 | fPCLK/8 | | |----------------|-----------|-----------|-----------|-----------|-----------|-----------| - | R | Interrupt | fPCLK/8 | fPCLK/16 | fPCLK/32 | fPCLK/16 | fPCLK/64 | fPCLK/4 | + | R | Interrupt | fPCLK/32 | fPCLK/16 | fPCLK/128 | fPCLK/16 | fPCLK/128 | fPCLK/16 | | X |----------------|-----------|-----------|-----------|-----------|-----------|-----------| - | | DMA | fPCLK/2 | fPCLK/16 | fPCLK/8 | fPCLK/16 | fPCLK/64 | fPCLK/2 | + | | DMA | fPCLK/2 | fPCLK/2 | fPCLK/128 | fPCLK/16 | fPCLK/128 | fPCLK/2 | |=========|================|===========|===========|===========|===========|===========|===========| - | | Polling | fPCLK/2 | fPCLK/2 | NA | NA | fPCLK/2 | fPCLK/32 | + | | Polling | fPCLK/4 | fPCLK/4 | NA | NA | fPCLK/4 | fPCLK/64 | | |----------------|-----------|-----------|-----------|-----------|-----------|-----------| - | T | Interrupt | fPCLK/8 | fPCLK/16 | NA | NA | fPCLK/2 | fPCLK/64 | + | T | Interrupt | fPCLK/8 | fPCLK/16 | NA | NA | fPCLK/8 | fPCLK/128 | | X |----------------|-----------|-----------|-----------|-----------|-----------|-----------| - | | DMA | fPCLK/2 | fPCLK/4 | NA | NA | fPCLK/2 | fPCLK/32 | + | | DMA | fPCLK/2 | fPCLK/4 | NA | NA | fPCLK/2 | fPCLK/64 | +--------------------------------------------------------------------------------------------------+ - DataSize = SPI_DATASIZE_16BIT: + For 16 bits SPI data size transfers : +--------------------------------------------------------------------------------------------------+ | | | 2Lines Fullduplex | 2Lines RxOnly | 1Line | | Process | Tranfert mode |-----------------------|-----------------------|-----------------------| | | | Master | Slave | Master | Slave | Master | Slave | |==================================================================================================| - | T | Polling | fPCLK/4 | fPCLK/4 | NA | NA | NA | NA | + | T | Polling | fPCLK/2 | fPCLK/4 | NA | NA | NA | NA | | X |----------------|-----------|-----------|-----------|-----------|-----------|-----------| - | / | Interrupt | fPCLK/8 | fPCLK/16 | NA | NA | NA | NA | + | / | Interrupt | fPCLK/16 | fPCLK/16 | NA | NA | NA | NA | | R |----------------|-----------|-----------|-----------|-----------|-----------|-----------| | X | DMA | fPCLK/2 | fPCLK/4 | NA | NA | NA | NA | |=========|================|===========|===========|===========|===========|===========|===========| - | | Polling | fPCLK/4 | fPCLK/8 | fPCLK/4 | fPCLK/8 | fPCLK/64 | fPCLK/2 | + | | Polling | fPCLK/2 | fPCLK/4 | fPCLK/64 | fPCLK/8 | fPCLK/64 | fPCLK/4 | | |----------------|-----------|-----------|-----------|-----------|-----------|-----------| - | R | Interrupt | fPCLK/8 | fPCLK/8 | fPCLK/128 | fPCLK/8 | fPCLK/128 | fPCLK/4 | + | R | Interrupt | fPCLK/16 | fPCLK/8 | fPCLK/128 | fPCLK/8 | fPCLK/128 | fPCLK/8 | | X |----------------|-----------|-----------|-----------|-----------|-----------|-----------| - | | DMA | fPCLK/2 | fPCLK/2 | fPCLK/128 | fPCLK/16 | fPCLK/64 | fPCLK/2 | + | | DMA | fPCLK/2 | fPCLK/2 | fPCLK/128 | fPCLK/8 | fPCLK/128 | fPCLK/2 | |=========|================|===========|===========|===========|===========|===========|===========| - | | Polling | fPCLK/2 | fPCLK/4 | NA | NA | fPCLK/4 | fPCLK/8 | + | | Polling | fPCLK/2 | fPCLK/4 | NA | NA | fPCLK/2 | fPCLK/64 | | |----------------|-----------|-----------|-----------|-----------|-----------|-----------| - | T | Interrupt | fPCLK/4 | fPCLK/8 | NA | NA | fPCLK/4 | fPCLK/4 | + | T | Interrupt | fPCLK/4 | fPCLK/8 | NA | NA | fPCLK/4 | fPCLK/256 | | X |----------------|-----------|-----------|-----------|-----------|-----------|-----------| - | | DMA | fPCLK/2 | fPCLK/2 | NA | NA | fPCLK/4 | fPCLK/8 | + | | DMA | fPCLK/2 | fPCLK/4 | NA | NA | fPCLK/2 | fPCLK/32 | +--------------------------------------------------------------------------------------------------+ - [..] - (@) The max SPI frequency depend on SPI data size (8bits, 16bits), - SPI mode(2 Lines fullduplex, 2 lines RxOnly, 1 line TX/RX) and Process mode (Polling, IT, DMA). - (@) - (+@) TX/RX processes are HAL_SPI_TransmitReceive(), HAL_SPI_TransmitReceive_IT() and HAL_SPI_TransmitReceive_DMA() - (+@) RX processes are HAL_SPI_Receive(), HAL_SPI_Receive_IT() and HAL_SPI_Receive_DMA() - (+@) TX processes are HAL_SPI_Transmit(), HAL_SPI_Transmit_IT() and HAL_SPI_Transmit_DMA() - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2017 STMicroelectronics

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ + + note: + The max SPI frequency depend on SPI data size (8bits, 16bits), + SPI mode(2 Lines fullduplex, 2 lines RxOnly, 1 line TX/RX) and Process mode (Polling, IT, DMA). + + note: + TX/RX processes are HAL_SPI_TransmitReceive(), HAL_SPI_TransmitReceive_IT() and HAL_SPI_TransmitReceive_DMA() + RX processes are HAL_SPI_Receive(), HAL_SPI_Receive_IT() and HAL_SPI_Receive_DMA() + TX processes are HAL_SPI_Transmit(), HAL_SPI_Transmit_IT() and HAL_SPI_Transmit_DMA() + +*/ /* Includes ------------------------------------------------------------------*/ #include "stm32f1xx_hal.h" @@ -158,28 +156,35 @@ /** @addtogroup STM32F1xx_HAL_Driver * @{ */ + /** @defgroup SPI SPI * @brief SPI HAL module driver * @{ */ + #ifdef HAL_SPI_MODULE_ENABLED /* Private typedef -----------------------------------------------------------*/ -/* Private defines -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ /** @defgroup SPI_Private_Constants SPI Private Constants * @{ */ -#define SPI_DEFAULT_TIMEOUT 100U +#define SPI_TIMEOUT_VALUE 10 /** * @} */ -/* Private macros ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ -/** @addtogroup SPI_Private_Functions +/** @defgroup SPI_Private_Functions SPI Private Functions * @{ */ +static void SPI_TxCloseIRQHandler(SPI_HandleTypeDef *hspi); +static void SPI_TxISR(SPI_HandleTypeDef *hspi); +static void SPI_RxCloseIRQHandler(SPI_HandleTypeDef *hspi); +static void SPI_2LinesRxISR(SPI_HandleTypeDef *hspi); +static void SPI_RxISR(SPI_HandleTypeDef *hspi); static void SPI_DMATransmitCplt(DMA_HandleTypeDef *hdma); static void SPI_DMAReceiveCplt(DMA_HandleTypeDef *hdma); static void SPI_DMATransmitReceiveCplt(DMA_HandleTypeDef *hdma); @@ -187,56 +192,34 @@ static void SPI_DMAHalfTransmitCplt(DMA_HandleTypeDef *hdma); static void SPI_DMAHalfReceiveCplt(DMA_HandleTypeDef *hdma); static void SPI_DMAHalfTransmitReceiveCplt(DMA_HandleTypeDef *hdma); static void SPI_DMAError(DMA_HandleTypeDef *hdma); -static void SPI_DMAAbortOnError(DMA_HandleTypeDef *hdma); -static void SPI_DMATxAbortCallback(DMA_HandleTypeDef *hdma); -static void SPI_DMARxAbortCallback(DMA_HandleTypeDef *hdma); -static HAL_StatusTypeDef SPI_WaitFlagStateUntilTimeout(SPI_HandleTypeDef *hspi, uint32_t Flag, uint32_t State, uint32_t Timeout, uint32_t Tickstart); -static void SPI_TxISR_8BIT(struct __SPI_HandleTypeDef *hspi); -static void SPI_TxISR_16BIT(struct __SPI_HandleTypeDef *hspi); -static void SPI_RxISR_8BIT(struct __SPI_HandleTypeDef *hspi); -static void SPI_RxISR_16BIT(struct __SPI_HandleTypeDef *hspi); -static void SPI_2linesRxISR_8BIT(struct __SPI_HandleTypeDef *hspi); -static void SPI_2linesTxISR_8BIT(struct __SPI_HandleTypeDef *hspi); -static void SPI_2linesTxISR_16BIT(struct __SPI_HandleTypeDef *hspi); -static void SPI_2linesRxISR_16BIT(struct __SPI_HandleTypeDef *hspi); -#if (USE_SPI_CRC != 0U) -static void SPI_RxISR_8BITCRC(struct __SPI_HandleTypeDef *hspi); -static void SPI_RxISR_16BITCRC(struct __SPI_HandleTypeDef *hspi); -static void SPI_2linesRxISR_8BITCRC(struct __SPI_HandleTypeDef *hspi); -static void SPI_2linesRxISR_16BITCRC(struct __SPI_HandleTypeDef *hspi); -#endif /* USE_SPI_CRC */ -static void SPI_AbortRx_ISR(SPI_HandleTypeDef *hspi); -static void SPI_AbortTx_ISR(SPI_HandleTypeDef *hspi); -static void SPI_CloseRxTx_ISR(SPI_HandleTypeDef *hspi); -static void SPI_CloseRx_ISR(SPI_HandleTypeDef *hspi); -static void SPI_CloseTx_ISR(SPI_HandleTypeDef *hspi); -static HAL_StatusTypeDef SPI_CheckFlag_BSY(SPI_HandleTypeDef *hspi, uint32_t Timeout, uint32_t Tickstart); +static HAL_StatusTypeDef SPI_WaitOnFlagUntilTimeout(SPI_HandleTypeDef *hspi, uint32_t Flag, FlagStatus Status, uint32_t Timeout); /** * @} */ -/* Exported functions --------------------------------------------------------*/ +/* Exported functions ---------------------------------------------------------*/ + /** @defgroup SPI_Exported_Functions SPI Exported Functions * @{ */ -/** @defgroup SPI_Exported_Functions_Group1 Initialization and de-initialization functions - * @brief Initialization and Configuration functions +/** @defgroup SPI_Exported_Functions_Group1 Initialization and de-initialization functions + * @brief Initialization and Configuration functions * @verbatim =============================================================================== ##### Initialization and de-initialization functions ##### =============================================================================== - [..] This subsection provides a set of functions allowing to initialize and - de-initialize the SPIx peripheral: + [..] This subsection provides a set of functions allowing to initialize and + de-initialiaze the SPIx peripheral: - (+) User must implement HAL_SPI_MspInit() function in which he configures + (+) User must implement HAL_SPI_MspInit() function in which he configures all related peripherals resources (CLOCK, GPIO, DMA, IT and NVIC ). - (+) Call the function HAL_SPI_Init() to configure the selected device with + (+) Call the function HAL_SPI_Init() to configure the selected device with the selected configuration: (++) Mode - (++) Direction + (++) Direction (++) Data Size (++) Clock Polarity and Phase (++) NSS Management @@ -246,18 +229,18 @@ static HAL_StatusTypeDef SPI_CheckFlag_BSY(SPI_HandleTypeDef *hspi, uint32_t Tim (++) CRC Calculation (++) CRC Polynomial if CRC enabled - (+) Call the function HAL_SPI_DeInit() to restore the default configuration - of the selected SPIx peripheral. + (+) Call the function HAL_SPI_DeInit() to restore the default configuration + of the selected SPIx periperal. @endverbatim * @{ */ /** - * @brief Initialize the SPI according to the specified parameters - * in the SPI_InitTypeDef and initialize the associated handle. + * @brief Initializes the SPI according to the specified parameters + * in the SPI_InitTypeDef and create the associated handle. * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. + * the configuration information for SPI module. * @retval HAL status */ __weak HAL_StatusTypeDef HAL_SPI_Init(SPI_HandleTypeDef *hspi) @@ -271,36 +254,29 @@ __weak HAL_StatusTypeDef HAL_SPI_Init(SPI_HandleTypeDef *hspi) /* Check the parameters */ assert_param(IS_SPI_ALL_INSTANCE(hspi->Instance)); assert_param(IS_SPI_MODE(hspi->Init.Mode)); - assert_param(IS_SPI_DIRECTION(hspi->Init.Direction)); + assert_param(IS_SPI_DIRECTION_MODE(hspi->Init.Direction)); assert_param(IS_SPI_DATASIZE(hspi->Init.DataSize)); assert_param(IS_SPI_CPOL(hspi->Init.CLKPolarity)); assert_param(IS_SPI_CPHA(hspi->Init.CLKPhase)); assert_param(IS_SPI_NSS(hspi->Init.NSS)); assert_param(IS_SPI_BAUDRATE_PRESCALER(hspi->Init.BaudRatePrescaler)); assert_param(IS_SPI_FIRST_BIT(hspi->Init.FirstBit)); - -#if (USE_SPI_CRC != 0U) + assert_param(IS_SPI_TIMODE(hspi->Init.TIMode)); assert_param(IS_SPI_CRC_CALCULATION(hspi->Init.CRCCalculation)); - if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) - { - assert_param(IS_SPI_CRC_POLYNOMIAL(hspi->Init.CRCPolynomial)); - } -#else - hspi->Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE; -#endif /* USE_SPI_CRC */ + assert_param(IS_SPI_CRC_POLYNOMIAL(hspi->Init.CRCPolynomial)); if(hspi->State == HAL_SPI_STATE_RESET) { /* Allocate lock resource and initialize it */ hspi->Lock = HAL_UNLOCKED; - + /* Init the low level hardware : GPIO, CLOCK, NVIC... */ HAL_SPI_MspInit(hspi); } - + hspi->State = HAL_SPI_STATE_BUSY; - /* Disable the selected SPI peripheral */ + /* Disble the selected SPI peripheral */ __HAL_SPI_DISABLE(hspi); /*----------------------- SPIx CR1 & CR2 Configuration ---------------------*/ @@ -311,32 +287,22 @@ __weak HAL_StatusTypeDef HAL_SPI_Init(SPI_HandleTypeDef *hspi) hspi->Init.BaudRatePrescaler | hspi->Init.FirstBit | hspi->Init.CRCCalculation) ); /* Configure : NSS management */ - WRITE_REG(hspi->Instance->CR2, (((hspi->Init.NSS >> 16U) & SPI_CR2_SSOE) | hspi->Init.TIMode)); + WRITE_REG(hspi->Instance->CR2, (((hspi->Init.NSS >> 16) & SPI_CR2_SSOE) | hspi->Init.TIMode)); -#if (USE_SPI_CRC != 0U) /*---------------------------- SPIx CRCPOLY Configuration ------------------*/ /* Configure : CRC Polynomial */ - if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) - { - WRITE_REG(hspi->Instance->CRCPR, hspi->Init.CRCPolynomial); - } -#endif /* USE_SPI_CRC */ - -#if defined(SPI_I2SCFGR_I2SMOD) - /* Activate the SPI mode (Make sure that I2SMOD bit in I2SCFGR register is reset) */ - CLEAR_BIT(hspi->Instance->I2SCFGR, SPI_I2SCFGR_I2SMOD); -#endif /* SPI_I2SCFGR_I2SMOD */ + WRITE_REG(hspi->Instance->CRCPR, hspi->Init.CRCPolynomial); hspi->ErrorCode = HAL_SPI_ERROR_NONE; - hspi->State = HAL_SPI_STATE_READY; - + hspi->State = HAL_SPI_STATE_READY; + return HAL_OK; } /** - * @brief De Initialize the SPI peripheral. + * @brief DeInitializes the SPI peripheral * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. + * the configuration information for SPI module. * @retval HAL status */ HAL_StatusTypeDef HAL_SPI_DeInit(SPI_HandleTypeDef *hspi) @@ -347,9 +313,6 @@ HAL_StatusTypeDef HAL_SPI_DeInit(SPI_HandleTypeDef *hspi) return HAL_ERROR; } - /* Check SPI Instance parameter */ - assert_param(IS_SPI_ALL_INSTANCE(hspi->Instance)); - hspi->State = HAL_SPI_STATE_BUSY; /* Disable the SPI Peripheral Clock */ @@ -368,33 +331,33 @@ HAL_StatusTypeDef HAL_SPI_DeInit(SPI_HandleTypeDef *hspi) } /** - * @brief Initialize the SPI MSP. + * @brief SPI MSP Init * @param hspi: pointer to a SPI_HandleTypeDef structure that contains * the configuration information for SPI module. * @retval None */ -__weak void HAL_SPI_MspInit(SPI_HandleTypeDef *hspi) -{ + __weak void HAL_SPI_MspInit(SPI_HandleTypeDef *hspi) + { /* Prevent unused argument(s) compilation warning */ UNUSED(hspi); - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_SPI_MspInit should be implemented in the user file - */ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_SPI_MspInit could be implenetd in the user file + */ } /** - * @brief De-Initialize the SPI MSP. + * @brief SPI MSP DeInit * @param hspi: pointer to a SPI_HandleTypeDef structure that contains * the configuration information for SPI module. * @retval None */ -__weak void HAL_SPI_MspDeInit(SPI_HandleTypeDef *hspi) + __weak void HAL_SPI_MspDeInit(SPI_HandleTypeDef *hspi) { /* Prevent unused argument(s) compilation warning */ UNUSED(hspi); - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_SPI_MspDeInit should be implemented in the user file - */ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_SPI_MspDeInit could be implenetd in the user file + */ } /** @@ -408,7 +371,6 @@ __weak void HAL_SPI_MspDeInit(SPI_HandleTypeDef *hspi) ============================================================================== ##### IO operation functions ##### =============================================================================== - [..] This subsection provides a set of functions allowing to manage the SPI data transfers. @@ -420,11 +382,11 @@ __weak void HAL_SPI_MspDeInit(SPI_HandleTypeDef *hspi) after finishing transfer. (++) No-Blocking mode: The communication is performed using Interrupts or DMA, These APIs return the HAL status. - The end of the data processing will be indicated through the - dedicated SPI IRQ when using Interrupt mode or the DMA IRQ when + The end of the data processing will be indicated through the + dedicated SPI IRQ when using Interrupt mode or the DMA IRQ when using DMA mode. - The HAL_SPI_TxCpltCallback(), HAL_SPI_RxCpltCallback() and HAL_SPI_TxRxCpltCallback() user callbacks - will be executed respectively at the end of the transmit or Receive process + The HAL_SPI_TxCpltCallback(), HAL_SPI_RxCpltCallback() and HAL_SPI_TxRxCpltCallback() user callbacks + will be executed respectivelly at the end of the transmit or Receive process The HAL_SPI_ErrorCallback()user callback will be executed when a communication error is detected (#) APIs provided for these 2 transfer modes (Blocking mode or Non blocking mode using either Interrupt or DMA) @@ -435,9 +397,9 @@ __weak void HAL_SPI_MspDeInit(SPI_HandleTypeDef *hspi) */ /** - * @brief Transmit an amount of data in blocking mode. + * @brief Transmit an amount of data in blocking mode * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. + * the configuration information for SPI module. * @param pData: pointer to data buffer * @param Size: amount of data to be sent * @param Timeout: Timeout duration @@ -445,345 +407,293 @@ __weak void HAL_SPI_MspDeInit(SPI_HandleTypeDef *hspi) */ HAL_StatusTypeDef HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size, uint32_t Timeout) { - uint32_t tickstart = 0U; - HAL_StatusTypeDef errorcode = HAL_OK; - /* Check Direction parameter */ - assert_param(IS_SPI_DIRECTION_2LINES_OR_1LINE(hspi->Init.Direction)); + if(hspi->State == HAL_SPI_STATE_READY) + { + if((pData == NULL ) || (Size == 0)) + { + return HAL_ERROR; + } - /* Process Locked */ - __HAL_LOCK(hspi); + /* Check the parameters */ + assert_param(IS_SPI_DIRECTION_2LINES_OR_1LINE(hspi->Init.Direction)); - /* Init tickstart for timeout management*/ - tickstart = HAL_GetTick(); + /* Process Locked */ + __HAL_LOCK(hspi); - if(hspi->State != HAL_SPI_STATE_READY) - { - errorcode = HAL_BUSY; - goto error; - } + /* Configure communication */ + hspi->State = HAL_SPI_STATE_BUSY_TX; + hspi->ErrorCode = HAL_SPI_ERROR_NONE; - if((pData == NULL ) || (Size == 0U)) - { - errorcode = HAL_ERROR; - goto error; - } + hspi->pTxBuffPtr = pData; + hspi->TxXferSize = Size; + hspi->TxXferCount = Size; - /* Set the transaction information */ - hspi->State = HAL_SPI_STATE_BUSY_TX; - hspi->ErrorCode = HAL_SPI_ERROR_NONE; - hspi->pTxBuffPtr = (uint8_t *)pData; - hspi->TxXferSize = Size; - hspi->TxXferCount = Size; - - /*Init field not used in handle to zero */ - hspi->pRxBuffPtr = (uint8_t *)NULL; - hspi->RxXferSize = 0U; - hspi->RxXferCount = 0U; - hspi->TxISR = NULL; - hspi->RxISR = NULL; - - /* Configure communication direction : 1Line */ - if(hspi->Init.Direction == SPI_DIRECTION_1LINE) - { - SPI_1LINE_TX(hspi); - } + /*Init field not used in handle to zero */ + hspi->TxISR = 0; + hspi->RxISR = 0; + hspi->pRxBuffPtr = NULL; + hspi->RxXferSize = 0; + hspi->RxXferCount = 0; -#if (USE_SPI_CRC != 0U) - /* Reset CRC Calculation */ - if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) - { - SPI_RESET_CRC(hspi); - } -#endif /* USE_SPI_CRC */ + /* Reset CRC Calculation */ + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) + { + SPI_RESET_CRC(hspi); + } - /* Check if the SPI is already enabled */ - if((hspi->Instance->CR1 & SPI_CR1_SPE) != SPI_CR1_SPE) - { - /* Enable SPI peripheral */ - __HAL_SPI_ENABLE(hspi); - } + if(hspi->Init.Direction == SPI_DIRECTION_1LINE) + { + /* Configure communication direction : 1Line */ + SPI_1LINE_TX(hspi); + } - /* Transmit data in 16 Bit mode */ - if(hspi->Init.DataSize == SPI_DATASIZE_16BIT) - { - if((hspi->Init.Mode == SPI_MODE_SLAVE) || (hspi->TxXferCount == 0x01)) + /* Check if the SPI is already enabled */ + if((hspi->Instance->CR1 &SPI_CR1_SPE) != SPI_CR1_SPE) { - hspi->Instance->DR = *((uint16_t *)pData); - pData += sizeof(uint16_t); - hspi->TxXferCount--; + /* Enable SPI peripheral */ + __HAL_SPI_ENABLE(hspi); } - /* Transmit data in 16 Bit mode */ - while (hspi->TxXferCount > 0U) + + /* Transmit data in 8 Bit mode */ + if(hspi->Init.DataSize == SPI_DATASIZE_8BIT) { - /* Wait until TXE flag is set to send data */ - if(__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_TXE)) + if((hspi->Init.Mode == SPI_MODE_SLAVE)|| (hspi->TxXferCount == 0x01)) { - hspi->Instance->DR = *((uint16_t *)pData); - pData += sizeof(uint16_t); - hspi->TxXferCount--; + hspi->Instance->DR = (*hspi->pTxBuffPtr++); + hspi->TxXferCount--; } - else + + while(hspi->TxXferCount > 0) { - /* Timeout management */ - if((Timeout == 0U) || ((Timeout != HAL_MAX_DELAY) && ((HAL_GetTick()-tickstart) >= Timeout))) - { - errorcode = HAL_TIMEOUT; - goto error; + /* Wait until TXE flag is set to send data */ + if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_TXE, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; } + hspi->Instance->DR = (*hspi->pTxBuffPtr++); + hspi->TxXferCount--; + } + /* Enable CRC Transmission */ + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) + { + SET_BIT(hspi->Instance->CR1, SPI_CR1_CRCNEXT); } } - } - /* Transmit data in 8 Bit mode */ - else - { - if((hspi->Init.Mode == SPI_MODE_SLAVE)|| (hspi->TxXferCount == 0x01)) - { - *((__IO uint8_t*)&hspi->Instance->DR) = (*pData); - pData += sizeof(uint8_t); - hspi->TxXferCount--; - } - while (hspi->TxXferCount > 0U) + /* Transmit data in 16 Bit mode */ + else { - /* Wait until TXE flag is set to send data */ - if(__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_TXE)) + if((hspi->Init.Mode == SPI_MODE_SLAVE) || (hspi->TxXferCount == 0x01)) { - *((__IO uint8_t*)&hspi->Instance->DR) = (*pData); - pData += sizeof(uint8_t); + hspi->Instance->DR = *((uint16_t*)hspi->pTxBuffPtr); + hspi->pTxBuffPtr+=2; hspi->TxXferCount--; } - else + + while(hspi->TxXferCount > 0) { - /* Timeout management */ - if((Timeout == 0U) || ((Timeout != HAL_MAX_DELAY) && ((HAL_GetTick()-tickstart) >= Timeout))) - { - errorcode = HAL_TIMEOUT; - goto error; + /* Wait until TXE flag is set to send data */ + if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_TXE, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; } + hspi->Instance->DR = *((uint16_t*)hspi->pTxBuffPtr); + hspi->pTxBuffPtr+=2; + hspi->TxXferCount--; + } + /* Enable CRC Transmission */ + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) + { + SET_BIT(hspi->Instance->CR1, SPI_CR1_CRCNEXT); } } - } - /* Wait until TXE flag */ - if(SPI_WaitFlagStateUntilTimeout(hspi, SPI_FLAG_TXE, SET, Timeout, tickstart) != HAL_OK) - { - errorcode = HAL_TIMEOUT; - goto error; - } - - /* Check Busy flag */ - if(SPI_CheckFlag_BSY(hspi, Timeout, tickstart) != HAL_OK) - { - errorcode = HAL_ERROR; - hspi->ErrorCode = HAL_SPI_ERROR_FLAG; - goto error; - } + /* Wait until TXE flag is set to send data */ + if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_TXE, RESET, Timeout) != HAL_OK) + { + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_FLAG); + return HAL_TIMEOUT; + } - /* Clear overrun flag in 2 Lines communication mode because received is not read */ - if(hspi->Init.Direction == SPI_DIRECTION_2LINES) - { - __HAL_SPI_CLEAR_OVRFLAG(hspi); - } -#if (USE_SPI_CRC != 0U) - /* Enable CRC Transmission */ - if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) - { - SET_BIT(hspi->Instance->CR1, SPI_CR1_CRCNEXT); - } -#endif /* USE_SPI_CRC */ + /* Wait until Busy flag is reset before disabling SPI */ + if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_BSY, SET, Timeout) != HAL_OK) + { + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_FLAG); + return HAL_TIMEOUT; + } + + /* Clear OVERUN flag in 2 Lines communication mode because received is not read */ + if(hspi->Init.Direction == SPI_DIRECTION_2LINES) + { + __HAL_SPI_CLEAR_OVRFLAG(hspi); + } - if(hspi->ErrorCode != HAL_SPI_ERROR_NONE) + hspi->State = HAL_SPI_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + + return HAL_OK; + } + else { - errorcode = HAL_ERROR; + return HAL_BUSY; } - -error: - hspi->State = HAL_SPI_STATE_READY; - /* Process Unlocked */ - __HAL_UNLOCK(hspi); - return errorcode; } /** - * @brief Receive an amount of data in blocking mode. + * @brief Receive an amount of data in blocking mode * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. + * the configuration information for SPI module. * @param pData: pointer to data buffer - * @param Size: amount of data to be received + * @param Size: amount of data to be sent * @param Timeout: Timeout duration * @retval HAL status */ HAL_StatusTypeDef HAL_SPI_Receive(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size, uint32_t Timeout) { -#if (USE_SPI_CRC != 0U) - __IO uint16_t tmpreg = 0U; -#endif /* USE_SPI_CRC */ - uint32_t tickstart = 0U; - HAL_StatusTypeDef errorcode = HAL_OK; + __IO uint16_t tmpreg = 0; - if((hspi->Init.Mode == SPI_MODE_MASTER) && (hspi->Init.Direction == SPI_DIRECTION_2LINES)) + if(hspi->State == HAL_SPI_STATE_READY) { - hspi->State = HAL_SPI_STATE_BUSY_RX; - /* Call transmit-receive function to send Dummy data on Tx line and generate clock on CLK line */ - return HAL_SPI_TransmitReceive(hspi,pData,pData,Size,Timeout); - } + if((pData == NULL ) || (Size == 0)) + { + return HAL_ERROR; + } - /* Process Locked */ - __HAL_LOCK(hspi); + /* Process Locked */ + __HAL_LOCK(hspi); - /* Init tickstart for timeout management*/ - tickstart = HAL_GetTick(); + /* Configure communication */ + hspi->State = HAL_SPI_STATE_BUSY_RX; + hspi->ErrorCode = HAL_SPI_ERROR_NONE; - if(hspi->State != HAL_SPI_STATE_READY) - { - errorcode = HAL_BUSY; - goto error; - } + hspi->pRxBuffPtr = pData; + hspi->RxXferSize = Size; + hspi->RxXferCount = Size; - if((pData == NULL ) || (Size == 0U)) - { - errorcode = HAL_ERROR; - goto error; - } + /*Init field not used in handle to zero */ + hspi->RxISR = 0; + hspi->TxISR = 0; + hspi->pTxBuffPtr = NULL; + hspi->TxXferSize = 0; + hspi->TxXferCount = 0; - /* Set the transaction information */ - hspi->State = HAL_SPI_STATE_BUSY_RX; - hspi->ErrorCode = HAL_SPI_ERROR_NONE; - hspi->pRxBuffPtr = (uint8_t *)pData; - hspi->RxXferSize = Size; - hspi->RxXferCount = Size; - - /*Init field not used in handle to zero */ - hspi->pTxBuffPtr = (uint8_t *)NULL; - hspi->TxXferSize = 0U; - hspi->TxXferCount = 0U; - hspi->RxISR = NULL; - hspi->TxISR = NULL; - -#if (USE_SPI_CRC != 0U) - /* Reset CRC Calculation */ - if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) - { - SPI_RESET_CRC(hspi); - /* this is done to handle the CRCNEXT before the latest data */ - hspi->RxXferCount--; - } -#endif /* USE_SPI_CRC */ + /* Configure communication direction : 1Line */ + if(hspi->Init.Direction == SPI_DIRECTION_1LINE) + { + SPI_1LINE_RX(hspi); + } - /* Configure communication direction: 1Line */ - if(hspi->Init.Direction == SPI_DIRECTION_1LINE) - { - SPI_1LINE_RX(hspi); - } + /* Reset CRC Calculation */ + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) + { + SPI_RESET_CRC(hspi); + } + + if((hspi->Init.Mode == SPI_MODE_MASTER) && (hspi->Init.Direction == SPI_DIRECTION_2LINES)) + { + /* Process Unlocked */ + __HAL_UNLOCK(hspi); - /* Check if the SPI is already enabled */ - if((hspi->Instance->CR1 & SPI_CR1_SPE) != SPI_CR1_SPE) - { - /* Enable SPI peripheral */ - __HAL_SPI_ENABLE(hspi); - } + /* Call transmit-receive function to send Dummy data on Tx line and generate clock on CLK line */ + return HAL_SPI_TransmitReceive(hspi, pData, pData, Size, Timeout); + } + + /* Check if the SPI is already enabled */ + if((hspi->Instance->CR1 &SPI_CR1_SPE) != SPI_CR1_SPE) + { + /* Enable SPI peripheral */ + __HAL_SPI_ENABLE(hspi); + } /* Receive data in 8 Bit mode */ - if(hspi->Init.DataSize == SPI_DATASIZE_8BIT) - { - /* Transfer loop */ - while(hspi->RxXferCount > 0U) + if(hspi->Init.DataSize == SPI_DATASIZE_8BIT) { - /* Check the RXNE flag */ - if(__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_RXNE)) + while(hspi->RxXferCount > 1) { - /* read the received data */ - (* (uint8_t *)pData)= *(__IO uint8_t *)&hspi->Instance->DR; - pData += sizeof(uint8_t); + /* Wait until RXNE flag is set */ + if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + (*hspi->pRxBuffPtr++) = hspi->Instance->DR; hspi->RxXferCount--; } - else + /* Enable CRC Reception */ + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) { - /* Timeout management */ - if((Timeout == 0U) || ((Timeout != HAL_MAX_DELAY) && ((HAL_GetTick()-tickstart) >= Timeout))) - { - errorcode = HAL_TIMEOUT; - goto error; - } + SET_BIT(hspi->Instance->CR1, SPI_CR1_CRCNEXT); } } - } - else - { - /* Transfer loop */ - while(hspi->RxXferCount > 0U) + /* Receive data in 16 Bit mode */ + else { - /* Check the RXNE flag */ - if(__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_RXNE)) + while(hspi->RxXferCount > 1) { - *((uint16_t*)pData) = hspi->Instance->DR; - pData += sizeof(uint16_t); + /* Wait until RXNE flag is set to read data */ + if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + *((uint16_t*)hspi->pRxBuffPtr) = hspi->Instance->DR; + hspi->pRxBuffPtr+=2; hspi->RxXferCount--; } - else + /* Enable CRC Reception */ + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) { - /* Timeout management */ - if((Timeout == 0U) || ((Timeout != HAL_MAX_DELAY) && ((HAL_GetTick()-tickstart) >= Timeout))) - { - errorcode = HAL_TIMEOUT; - goto error; - } + SET_BIT(hspi->Instance->CR1, SPI_CR1_CRCNEXT); } } - } - -#if (USE_SPI_CRC != 0U) - /* Handle the CRC Transmission */ - if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) - { - /* freeze the CRC before the latest data */ - SET_BIT(hspi->Instance->CR1, SPI_CR1_CRCNEXT); - /* Read the latest data */ - if(SPI_WaitFlagStateUntilTimeout(hspi, SPI_FLAG_RXNE, SET, Timeout, tickstart) != HAL_OK) - { - /* the latest data has not been received */ - errorcode = HAL_TIMEOUT; - goto error; + /* Wait until RXNE flag is set */ + if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; } - /* Receive last data in 16 Bit mode */ - if(hspi->Init.DataSize == SPI_DATASIZE_16BIT) + /* Receive last data in 8 Bit mode */ + if(hspi->Init.DataSize == SPI_DATASIZE_8BIT) { - *((uint16_t*)pData) = hspi->Instance->DR; + (*hspi->pRxBuffPtr++) = hspi->Instance->DR; } - /* Receive last data in 8 Bit mode */ + /* Receive last data in 16 Bit mode */ else { - (*(uint8_t *)pData) = *(__IO uint8_t *)&hspi->Instance->DR; + *((uint16_t*)hspi->pRxBuffPtr) = hspi->Instance->DR; + hspi->pRxBuffPtr+=2; } + hspi->RxXferCount--; - /* Wait the CRC data */ - if(SPI_WaitFlagStateUntilTimeout(hspi, SPI_FLAG_RXNE, SET, Timeout, tickstart) != HAL_OK) + /* If CRC computation is enabled */ + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) { - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_CRC); - errorcode = HAL_TIMEOUT; - goto error; - } - - /* Read CRC to Flush DR and RXNE flag */ - tmpreg = hspi->Instance->DR; - /* To avoid GCC warning */ - UNUSED(tmpreg); - } -#endif /* USE_SPI_CRC */ - - /* Check the end of the transaction */ - if((hspi->Init.Mode == SPI_MODE_MASTER)&&((hspi->Init.Direction == SPI_DIRECTION_1LINE)||(hspi->Init.Direction == SPI_DIRECTION_2LINES_RXONLY))) - { - /* Disable SPI peripheral */ - __HAL_SPI_DISABLE(hspi); - } + /* Wait until RXNE flag is set: CRC Received */ + if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, RESET, Timeout) != HAL_OK) + { + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_CRC); + return HAL_TIMEOUT; + } -#if (USE_SPI_CRC != 0U) - /* Check if CRC error occurred */ - if(__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_CRCERR) != RESET) + /* Read CRC to clear RXNE flag */ + tmpreg = hspi->Instance->DR; + UNUSED(tmpreg); + } + + if((hspi->Init.Mode == SPI_MODE_MASTER)&&((hspi->Init.Direction == SPI_DIRECTION_1LINE)||(hspi->Init.Direction == SPI_DIRECTION_2LINES_RXONLY))) { + /* Disable SPI peripheral */ + __HAL_SPI_DISABLE(hspi); + } + + hspi->State = HAL_SPI_STATE_READY; + + /* Check if CRC error occurred */ + if((hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) && (__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_CRCERR) != RESET)) + { /* Check if CRC error is valid or not (workaround to be applied or not) */ if (SPI_ISCRCErrorValid(hspi) == SPI_VALID_CRC_ERROR) { @@ -791,1126 +701,838 @@ HAL_StatusTypeDef HAL_SPI_Receive(SPI_HandleTypeDef *hspi, uint8_t *pData, uint1 /* Reset CRC Calculation */ SPI_RESET_CRC(hspi); + + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + + return HAL_ERROR; } else { __HAL_SPI_CLEAR_CRCERRFLAG(hspi); } } -#endif /* USE_SPI_CRC */ - if(hspi->ErrorCode != HAL_SPI_ERROR_NONE) + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + + return HAL_OK; + } + else { - errorcode = HAL_ERROR; + return HAL_BUSY; } - -error : - hspi->State = HAL_SPI_STATE_READY; - __HAL_UNLOCK(hspi); - return errorcode; } /** - * @brief Transmit and Receive an amount of data in blocking mode. + * @brief Transmit and Receive an amount of data in blocking mode * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. + * the configuration information for SPI module. * @param pTxData: pointer to transmission data buffer - * @param pRxData: pointer to reception data buffer - * @param Size: amount of data to be sent and received + * @param pRxData: pointer to reception data buffer to be + * @param Size: amount of data to be sent * @param Timeout: Timeout duration * @retval HAL status */ HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size, uint32_t Timeout) { - uint32_t tmp = 0U, tmp1 = 0U; -#if (USE_SPI_CRC != 0U) - __IO uint16_t tmpreg1 = 0U; -#endif /* USE_SPI_CRC */ - uint32_t tickstart = 0U; - /* Variable used to alternate Rx and Tx during transfer */ - uint32_t txallowed = 1U; - HAL_StatusTypeDef errorcode = HAL_OK; - - /* Check Direction parameter */ - assert_param(IS_SPI_DIRECTION_2LINES(hspi->Init.Direction)); + __IO uint16_t tmpreg = 0; - /* Process Locked */ - __HAL_LOCK(hspi); - - /* Init tickstart for timeout management*/ - tickstart = HAL_GetTick(); - - tmp = hspi->State; - tmp1 = hspi->Init.Mode; - - if(!((tmp == HAL_SPI_STATE_READY) || \ - ((tmp1 == SPI_MODE_MASTER) && (hspi->Init.Direction == SPI_DIRECTION_2LINES) && (tmp == HAL_SPI_STATE_BUSY_RX)))) + if((hspi->State == HAL_SPI_STATE_READY) || (hspi->State == HAL_SPI_STATE_BUSY_RX)) { - errorcode = HAL_BUSY; - goto error; - } + if((pTxData == NULL ) || (pRxData == NULL ) || (Size == 0)) + { + return HAL_ERROR; + } - if((pTxData == NULL) || (pRxData == NULL) || (Size == 0U)) - { - errorcode = HAL_ERROR; - goto error; - } + /* Check the parameters */ + assert_param(IS_SPI_DIRECTION_2LINES(hspi->Init.Direction)); - /* Don't overwrite in case of HAL_SPI_STATE_BUSY_RX */ - if(hspi->State == HAL_SPI_STATE_READY) - { - hspi->State = HAL_SPI_STATE_BUSY_TX_RX; - } + /* Process Locked */ + __HAL_LOCK(hspi); + + /* Don't overwrite in case of HAL_SPI_STATE_BUSY_RX */ + if(hspi->State == HAL_SPI_STATE_READY) + { + hspi->State = HAL_SPI_STATE_BUSY_TX_RX; + } - /* Set the transaction information */ - hspi->ErrorCode = HAL_SPI_ERROR_NONE; - hspi->pRxBuffPtr = (uint8_t *)pRxData; - hspi->RxXferCount = Size; - hspi->RxXferSize = Size; - hspi->pTxBuffPtr = (uint8_t *)pTxData; - hspi->TxXferCount = Size; - hspi->TxXferSize = Size; - - /*Init field not used in handle to zero */ - hspi->RxISR = NULL; - hspi->TxISR = NULL; - -#if (USE_SPI_CRC != 0U) - /* Reset CRC Calculation */ - if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) - { - SPI_RESET_CRC(hspi); - } -#endif /* USE_SPI_CRC */ + /* Configure communication */ + hspi->ErrorCode = HAL_SPI_ERROR_NONE; - /* Check if the SPI is already enabled */ - if((hspi->Instance->CR1 &SPI_CR1_SPE) != SPI_CR1_SPE) - { - /* Enable SPI peripheral */ - __HAL_SPI_ENABLE(hspi); - } + hspi->pRxBuffPtr = pRxData; + hspi->RxXferSize = Size; + hspi->RxXferCount = Size; + + hspi->pTxBuffPtr = pTxData; + hspi->TxXferSize = Size; + hspi->TxXferCount = Size; - /* Transmit and Receive data in 16 Bit mode */ - if(hspi->Init.DataSize == SPI_DATASIZE_16BIT) - { - if((hspi->Init.Mode == SPI_MODE_SLAVE) || (hspi->TxXferCount == 0x01U)) + /*Init field not used in handle to zero */ + hspi->RxISR = 0; + hspi->TxISR = 0; + + /* Reset CRC Calculation */ + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) + { + SPI_RESET_CRC(hspi); + } + + /* Check if the SPI is already enabled */ + if((hspi->Instance->CR1 &SPI_CR1_SPE) != SPI_CR1_SPE) { - hspi->Instance->DR = *((uint16_t *)pTxData); - pTxData += sizeof(uint16_t); - hspi->TxXferCount--; + /* Enable SPI peripheral */ + __HAL_SPI_ENABLE(hspi); } - while ((hspi->TxXferCount > 0U) || (hspi->RxXferCount > 0U)) + + /* Transmit and Receive data in 16 Bit mode */ + if(hspi->Init.DataSize == SPI_DATASIZE_16BIT) { - /* Check TXE flag */ - if(txallowed && (hspi->TxXferCount > 0U) && (__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_TXE))) + if((hspi->Init.Mode == SPI_MODE_SLAVE) || ((hspi->Init.Mode == SPI_MODE_MASTER) && (hspi->TxXferCount == 0x01))) { - hspi->Instance->DR = *((uint16_t *)pTxData); - pTxData += sizeof(uint16_t); + hspi->Instance->DR = *((uint16_t*)hspi->pTxBuffPtr); + hspi->pTxBuffPtr+=2; hspi->TxXferCount--; - /* Next Data is a reception (Rx). Tx not allowed */ - txallowed = 0U; - -#if (USE_SPI_CRC != 0U) + } + if(hspi->TxXferCount == 0) + { /* Enable CRC Transmission */ - if((hspi->TxXferCount == 0U) && (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)) + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) { SET_BIT(hspi->Instance->CR1, SPI_CR1_CRCNEXT); } -#endif /* USE_SPI_CRC */ - } - /* Check RXNE flag */ - if((hspi->RxXferCount > 0U) && (__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_RXNE))) - { - *((uint16_t *)pRxData) = hspi->Instance->DR; - pRxData += sizeof(uint16_t); + /* Wait until RXNE flag is set */ + if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + *((uint16_t*)hspi->pRxBuffPtr) = hspi->Instance->DR; + hspi->pRxBuffPtr+=2; hspi->RxXferCount--; - /* Next Data is a Transmission (Tx). Tx is allowed */ - txallowed = 1U; } - if((Timeout != HAL_MAX_DELAY) && ((HAL_GetTick()-tickstart) >= Timeout)) + else { - errorcode = HAL_TIMEOUT; - goto error; + while(hspi->TxXferCount > 0) + { + /* Wait until TXE flag is set to send data */ + if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_TXE, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + hspi->Instance->DR = *((uint16_t*)hspi->pTxBuffPtr); + hspi->pTxBuffPtr+=2; + hspi->TxXferCount--; + + /* Enable CRC Transmission */ + if((hspi->TxXferCount == 0) && (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)) + { + SET_BIT(hspi->Instance->CR1, SPI_CR1_CRCNEXT); + } + + /* Wait until RXNE flag is set */ + if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + *((uint16_t*)hspi->pRxBuffPtr) = hspi->Instance->DR; + hspi->pRxBuffPtr+=2; + hspi->RxXferCount--; + } + /* Receive the last byte */ + if(hspi->Init.Mode == SPI_MODE_SLAVE) + { + /* Wait until RXNE flag is set */ + if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + *((uint16_t*)hspi->pRxBuffPtr) = hspi->Instance->DR; + hspi->pRxBuffPtr+=2; + hspi->RxXferCount--; + } } } - } - /* Transmit and Receive data in 8 Bit mode */ - else - { - if((hspi->Init.Mode == SPI_MODE_SLAVE) || (hspi->TxXferCount == 0x01U)) - { - *((__IO uint8_t*)&hspi->Instance->DR) = (*pTxData); - pTxData += sizeof(uint8_t); - hspi->TxXferCount--; - } - while((hspi->TxXferCount > 0U) || (hspi->RxXferCount > 0U)) + /* Transmit and Receive data in 8 Bit mode */ + else { - /* check TXE flag */ - if(txallowed && (hspi->TxXferCount > 0U) && (__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_TXE))) + if((hspi->Init.Mode == SPI_MODE_SLAVE) || ((hspi->Init.Mode == SPI_MODE_MASTER) && (hspi->TxXferCount == 0x01))) { - *(__IO uint8_t *)&hspi->Instance->DR = (*pTxData++); + hspi->Instance->DR = (*hspi->pTxBuffPtr++); hspi->TxXferCount--; - /* Next Data is a reception (Rx). Tx not allowed */ - txallowed = 0U; - -#if (USE_SPI_CRC != 0U) + } + if(hspi->TxXferCount == 0) + { /* Enable CRC Transmission */ - if((hspi->TxXferCount == 0U) && (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)) + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) { SET_BIT(hspi->Instance->CR1, SPI_CR1_CRCNEXT); } -#endif /* USE_SPI_CRC */ - } - /* Wait until RXNE flag is reset */ - if((hspi->RxXferCount > 0U) && (__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_RXNE))) - { - (*(uint8_t *)pRxData++) = hspi->Instance->DR; + /* Wait until RXNE flag is set */ + if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + (*hspi->pRxBuffPtr) = hspi->Instance->DR; hspi->RxXferCount--; - /* Next Data is a Transmission (Tx). Tx is allowed */ - txallowed = 1U; } - if((Timeout != HAL_MAX_DELAY) && ((HAL_GetTick()-tickstart) >= Timeout)) + else + { + while(hspi->TxXferCount > 0) + { + /* Wait until TXE flag is set to send data */ + if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_TXE, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + hspi->Instance->DR = (*hspi->pTxBuffPtr++); + hspi->TxXferCount--; + + /* Enable CRC Transmission */ + if((hspi->TxXferCount == 0) && (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)) + { + SET_BIT(hspi->Instance->CR1, SPI_CR1_CRCNEXT); + } + + /* Wait until RXNE flag is set */ + if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + (*hspi->pRxBuffPtr++) = hspi->Instance->DR; + hspi->RxXferCount--; + } + if(hspi->Init.Mode == SPI_MODE_SLAVE) + { + /* Wait until RXNE flag is set */ + if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + (*hspi->pRxBuffPtr++) = hspi->Instance->DR; + hspi->RxXferCount--; + } + } + } + + /* Read CRC from DR to close CRC calculation process */ + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) + { + /* Wait until RXNE flag is set */ + if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, RESET, Timeout) != HAL_OK) { - errorcode = HAL_TIMEOUT; - goto error; + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_CRC); + return HAL_TIMEOUT; } + /* Read CRC */ + tmpreg = hspi->Instance->DR; + UNUSED(tmpreg); } - } -#if (USE_SPI_CRC != 0U) - /* Read CRC from DR to close CRC calculation process */ - if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) - { - /* Wait until TXE flag */ - if(SPI_WaitFlagStateUntilTimeout(hspi, SPI_FLAG_RXNE, SET, Timeout, tickstart) != HAL_OK) + /* Wait until Busy flag is reset before disabling SPI */ + if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_BSY, SET, Timeout) != HAL_OK) { - /* Error on the CRC reception */ - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_CRC); - errorcode = HAL_TIMEOUT; - goto error; + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_FLAG); + return HAL_TIMEOUT; } - /* Read CRC */ - tmpreg1 = hspi->Instance->DR; - /* To avoid GCC warning */ - UNUSED(tmpreg1); - } + + hspi->State = HAL_SPI_STATE_READY; - /* Check if CRC error occurred */ - if(__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_CRCERR) != RESET) - { - /* Check if CRC error is valid or not (workaround to be applied or not) */ - if (SPI_ISCRCErrorValid(hspi) == SPI_VALID_CRC_ERROR) + /* Check if CRC error occurred */ + if((hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) && (__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_CRCERR) != RESET)) { SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_CRC); - /* Reset CRC Calculation */ SPI_RESET_CRC(hspi); - errorcode = HAL_ERROR; - } - else - { - __HAL_SPI_CLEAR_CRCERRFLAG(hspi); + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + + return HAL_ERROR; } - } -#endif /* USE_SPI_CRC */ - /* Wait until TXE flag */ - if(SPI_WaitFlagStateUntilTimeout(hspi, SPI_FLAG_TXE, SET, Timeout, tickstart) != HAL_OK) - { - errorcode = HAL_TIMEOUT; - goto error; - } - - /* Check Busy flag */ - if(SPI_CheckFlag_BSY(hspi, Timeout, tickstart) != HAL_OK) - { - errorcode = HAL_ERROR; - hspi->ErrorCode = HAL_SPI_ERROR_FLAG; - goto error; - } + /* Process Unlocked */ + __HAL_UNLOCK(hspi); - /* Clear overrun flag in 2 Lines communication mode because received is not read */ - if(hspi->Init.Direction == SPI_DIRECTION_2LINES) + return HAL_OK; + } + else { - __HAL_SPI_CLEAR_OVRFLAG(hspi); + return HAL_BUSY; } - -error : - hspi->State = HAL_SPI_STATE_READY; - __HAL_UNLOCK(hspi); - return errorcode; } /** - * @brief Transmit an amount of data in non-blocking mode with Interrupt. + * @brief Transmit an amount of data in no-blocking mode with Interrupt * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. + * the configuration information for SPI module. * @param pData: pointer to data buffer * @param Size: amount of data to be sent * @retval HAL status */ HAL_StatusTypeDef HAL_SPI_Transmit_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size) { - HAL_StatusTypeDef errorcode = HAL_OK; + if(hspi->State == HAL_SPI_STATE_READY) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } - /* Check Direction parameter */ - assert_param(IS_SPI_DIRECTION_2LINES_OR_1LINE(hspi->Init.Direction)); + /* Check the parameters */ + assert_param(IS_SPI_DIRECTION_2LINES_OR_1LINE(hspi->Init.Direction)); - /* Process Locked */ - __HAL_LOCK(hspi); + /* Process Locked */ + __HAL_LOCK(hspi); - if((pData == NULL) || (Size == 0U)) - { - errorcode = HAL_ERROR; - goto error; - } + /* Configure communication */ + hspi->State = HAL_SPI_STATE_BUSY_TX; + hspi->ErrorCode = HAL_SPI_ERROR_NONE; - if(hspi->State != HAL_SPI_STATE_READY) - { - errorcode = HAL_BUSY; - goto error; - } + hspi->TxISR = &SPI_TxISR; + hspi->pTxBuffPtr = pData; + hspi->TxXferSize = Size; + hspi->TxXferCount = Size; - /* Set the transaction information */ - hspi->State = HAL_SPI_STATE_BUSY_TX; - hspi->ErrorCode = HAL_SPI_ERROR_NONE; - hspi->pTxBuffPtr = (uint8_t *)pData; - hspi->TxXferSize = Size; - hspi->TxXferCount = Size; - - /* Init field not used in handle to zero */ - hspi->pRxBuffPtr = (uint8_t *)NULL; - hspi->RxXferSize = 0U; - hspi->RxXferCount = 0U; - hspi->RxISR = NULL; - - /* Set the function for IT treatment */ - if(hspi->Init.DataSize > SPI_DATASIZE_8BIT ) - { - hspi->TxISR = SPI_TxISR_16BIT; - } - else - { - hspi->TxISR = SPI_TxISR_8BIT; - } + /*Init field not used in handle to zero */ + hspi->RxISR = 0; + hspi->pRxBuffPtr = NULL; + hspi->RxXferSize = 0; + hspi->RxXferCount = 0; - /* Configure communication direction : 1Line */ - if(hspi->Init.Direction == SPI_DIRECTION_1LINE) - { - SPI_1LINE_TX(hspi); - } + /* Configure communication direction : 1Line */ + if(hspi->Init.Direction == SPI_DIRECTION_1LINE) + { + SPI_1LINE_TX(hspi); + } -#if (USE_SPI_CRC != 0U) - /* Reset CRC Calculation */ - if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) - { - SPI_RESET_CRC(hspi); - } -#endif /* USE_SPI_CRC */ + /* Reset CRC Calculation */ + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) + { + SPI_RESET_CRC(hspi); + } - if (hspi->Init.Direction == SPI_DIRECTION_2LINES) - { - /* Enable TXE interrupt */ - __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_TXE)); + if (hspi->Init.Direction == SPI_DIRECTION_2LINES) + { + __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_TXE)); + } + else + { + /* Enable TXE and ERR interrupt */ + __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_TXE | SPI_IT_ERR)); + } + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + + /* Check if the SPI is already enabled */ + if((hspi->Instance->CR1 &SPI_CR1_SPE) != SPI_CR1_SPE) + { + /* Enable SPI peripheral */ + __HAL_SPI_ENABLE(hspi); + } + + return HAL_OK; } else { - /* Enable TXE and ERR interrupt */ - __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_TXE | SPI_IT_ERR)); - } - - /* Check if the SPI is already enabled */ - if((hspi->Instance->CR1 &SPI_CR1_SPE) != SPI_CR1_SPE) - { - /* Enable SPI peripheral */ - __HAL_SPI_ENABLE(hspi); + return HAL_BUSY; } - -error : - __HAL_UNLOCK(hspi); - return errorcode; } /** - * @brief Receive an amount of data in non-blocking mode with Interrupt. + * @brief Receive an amount of data in no-blocking mode with Interrupt * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. + * the configuration information for SPI module. * @param pData: pointer to data buffer * @param Size: amount of data to be sent * @retval HAL status */ HAL_StatusTypeDef HAL_SPI_Receive_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size) { - HAL_StatusTypeDef errorcode = HAL_OK; - - if((hspi->Init.Direction == SPI_DIRECTION_2LINES) && (hspi->Init.Mode == SPI_MODE_MASTER)) + if(hspi->State == HAL_SPI_STATE_READY) { - hspi->State = HAL_SPI_STATE_BUSY_RX; - /* Call transmit-receive function to send Dummy data on Tx line and generate clock on CLK line */ - return HAL_SPI_TransmitReceive_IT(hspi, pData, pData, Size); - } + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } - /* Process Locked */ - __HAL_LOCK(hspi); + /* Process Locked */ + __HAL_LOCK(hspi); - if(hspi->State != HAL_SPI_STATE_READY) - { - errorcode = HAL_BUSY; - goto error; - } + /* Configure communication */ + hspi->State = HAL_SPI_STATE_BUSY_RX; + hspi->ErrorCode = HAL_SPI_ERROR_NONE; - if((pData == NULL) || (Size == 0U)) - { - errorcode = HAL_ERROR; - goto error; - } + hspi->RxISR = &SPI_RxISR; + hspi->pRxBuffPtr = pData; + hspi->RxXferSize = Size; + hspi->RxXferCount = Size ; - /* Set the transaction information */ - hspi->State = HAL_SPI_STATE_BUSY_RX; - hspi->ErrorCode = HAL_SPI_ERROR_NONE; - hspi->pRxBuffPtr = (uint8_t *)pData; - hspi->RxXferSize = Size; - hspi->RxXferCount = Size; - - /* Init field not used in handle to zero */ - hspi->pTxBuffPtr = (uint8_t *)NULL; - hspi->TxXferSize = 0U; - hspi->TxXferCount = 0U; - hspi->TxISR = NULL; - - /* Set the function for IT treatment */ - if(hspi->Init.DataSize > SPI_DATASIZE_8BIT ) - { - hspi->RxISR = SPI_RxISR_16BIT; - } - else - { - hspi->RxISR = SPI_RxISR_8BIT; - } + /*Init field not used in handle to zero */ + hspi->TxISR = 0; + hspi->pTxBuffPtr = NULL; + hspi->TxXferSize = 0; + hspi->TxXferCount = 0; - /* Configure communication direction : 1Line */ - if(hspi->Init.Direction == SPI_DIRECTION_1LINE) - { - SPI_1LINE_RX(hspi); - } + /* Configure communication direction : 1Line */ + if(hspi->Init.Direction == SPI_DIRECTION_1LINE) + { + SPI_1LINE_RX(hspi); + } + else if((hspi->Init.Direction == SPI_DIRECTION_2LINES) && (hspi->Init.Mode == SPI_MODE_MASTER)) + { + /* Process Unlocked */ + __HAL_UNLOCK(hspi); -#if (USE_SPI_CRC != 0U) - /* Reset CRC Calculation */ - if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) - { - SPI_RESET_CRC(hspi); - } -#endif /* USE_SPI_CRC */ + /* Call transmit-receive function to send Dummy data on Tx line and generate clock on CLK line */ + return HAL_SPI_TransmitReceive_IT(hspi, pData, pData, Size); + } + + /* Reset CRC Calculation */ + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) + { + SPI_RESET_CRC(hspi); + } + + /* Enable TXE and ERR interrupt */ + __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_RXNE | SPI_IT_ERR)); - /* Enable TXE and ERR interrupt */ - __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_RXNE | SPI_IT_ERR)); + /* Process Unlocked */ + __HAL_UNLOCK(hspi); - /* Note : The SPI must be enabled after unlocking current process - to avoid the risk of SPI interrupt handle execution before current - process unlock */ + /* Note : The SPI must be enabled after unlocking current process + to avoid the risk of SPI interrupt handle execution before current + process unlock */ - /* Check if the SPI is already enabled */ - if((hspi->Instance->CR1 &SPI_CR1_SPE) != SPI_CR1_SPE) + /* Check if the SPI is already enabled */ + if((hspi->Instance->CR1 &SPI_CR1_SPE) != SPI_CR1_SPE) + { + /* Enable SPI peripheral */ + __HAL_SPI_ENABLE(hspi); + } + + return HAL_OK; + } + else { - /* Enable SPI peripheral */ - __HAL_SPI_ENABLE(hspi); + return HAL_BUSY; } - -error : - /* Process Unlocked */ - __HAL_UNLOCK(hspi); - return errorcode; } /** - * @brief Transmit and Receive an amount of data in non-blocking mode with Interrupt. + * @brief Transmit and Receive an amount of data in no-blocking mode with Interrupt * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. + * the configuration information for SPI module. * @param pTxData: pointer to transmission data buffer - * @param pRxData: pointer to reception data buffer - * @param Size: amount of data to be sent and received + * @param pRxData: pointer to reception data buffer to be + * @param Size: amount of data to be sent * @retval HAL status */ HAL_StatusTypeDef HAL_SPI_TransmitReceive_IT(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size) { - uint32_t tmp = 0U, tmp1 = 0U; - HAL_StatusTypeDef errorcode = HAL_OK; - /* Check Direction parameter */ - assert_param(IS_SPI_DIRECTION_2LINES(hspi->Init.Direction)); + if((hspi->State == HAL_SPI_STATE_READY) || \ + ((hspi->Init.Mode == SPI_MODE_MASTER) && (hspi->Init.Direction == SPI_DIRECTION_2LINES) && (hspi->State == HAL_SPI_STATE_BUSY_RX))) + { + if((pTxData == NULL ) || (pRxData == NULL ) || (Size == 0)) + { + return HAL_ERROR; + } - /* Process locked */ - __HAL_LOCK(hspi); + /* Check the parameters */ + assert_param(IS_SPI_DIRECTION_2LINES(hspi->Init.Direction)); - tmp = hspi->State; - tmp1 = hspi->Init.Mode; - - if(!((tmp == HAL_SPI_STATE_READY) || \ - ((tmp1 == SPI_MODE_MASTER) && (hspi->Init.Direction == SPI_DIRECTION_2LINES) && (tmp == HAL_SPI_STATE_BUSY_RX)))) - { - errorcode = HAL_BUSY; - goto error; - } + /* Process locked */ + __HAL_LOCK(hspi); - if((pTxData == NULL ) || (pRxData == NULL ) || (Size == 0U)) - { - errorcode = HAL_ERROR; - goto error; - } + /* Don't overwrite in case of HAL_SPI_STATE_BUSY_RX */ + if(hspi->State != HAL_SPI_STATE_BUSY_RX) + { + hspi->State = HAL_SPI_STATE_BUSY_TX_RX; + } - /* Don't overwrite in case of HAL_SPI_STATE_BUSY_RX */ - if(hspi->State == HAL_SPI_STATE_READY) - { - hspi->State = HAL_SPI_STATE_BUSY_TX_RX; - } + /* Configure communication */ + hspi->ErrorCode = HAL_SPI_ERROR_NONE; - /* Set the transaction information */ - hspi->ErrorCode = HAL_SPI_ERROR_NONE; - hspi->pTxBuffPtr = (uint8_t *)pTxData; - hspi->TxXferSize = Size; - hspi->TxXferCount = Size; - hspi->pRxBuffPtr = (uint8_t *)pRxData; - hspi->RxXferSize = Size; - hspi->RxXferCount = Size; - - /* Set the function for IT treatment */ - if(hspi->Init.DataSize > SPI_DATASIZE_8BIT ) - { - hspi->RxISR = SPI_2linesRxISR_16BIT; - hspi->TxISR = SPI_2linesTxISR_16BIT; + hspi->TxISR = &SPI_TxISR; + hspi->pTxBuffPtr = pTxData; + hspi->TxXferSize = Size; + hspi->TxXferCount = Size; + + hspi->RxISR = &SPI_2LinesRxISR; + hspi->pRxBuffPtr = pRxData; + hspi->RxXferSize = Size; + hspi->RxXferCount = Size; + + /* Reset CRC Calculation */ + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) + { + SPI_RESET_CRC(hspi); + } + + /* Enable TXE, RXNE and ERR interrupt */ + __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_TXE | SPI_IT_RXNE | SPI_IT_ERR)); + + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + + /* Check if the SPI is already enabled */ + if((hspi->Instance->CR1 &SPI_CR1_SPE) != SPI_CR1_SPE) + { + /* Enable SPI peripheral */ + __HAL_SPI_ENABLE(hspi); + } + + return HAL_OK; } else { - hspi->RxISR = SPI_2linesRxISR_8BIT; - hspi->TxISR = SPI_2linesTxISR_8BIT; + return HAL_BUSY; } - -#if (USE_SPI_CRC != 0U) - /* Reset CRC Calculation */ - if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) - { - SPI_RESET_CRC(hspi); - } -#endif /* USE_SPI_CRC */ - - /* Enable TXE, RXNE and ERR interrupt */ - __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_TXE | SPI_IT_RXNE | SPI_IT_ERR)); - - /* Check if the SPI is already enabled */ - if((hspi->Instance->CR1 &SPI_CR1_SPE) != SPI_CR1_SPE) - { - /* Enable SPI peripheral */ - __HAL_SPI_ENABLE(hspi); - } - -error : - /* Process Unlocked */ - __HAL_UNLOCK(hspi); - return errorcode; -} +} /** - * @brief Transmit an amount of data in non-blocking mode with DMA. + * @brief Transmit an amount of data in no-blocking mode with DMA * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. + * the configuration information for SPI module. * @param pData: pointer to data buffer * @param Size: amount of data to be sent * @retval HAL status */ HAL_StatusTypeDef HAL_SPI_Transmit_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size) { - HAL_StatusTypeDef errorcode = HAL_OK; + if(hspi->State == HAL_SPI_STATE_READY) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } - /* Check Direction parameter */ - assert_param(IS_SPI_DIRECTION_2LINES_OR_1LINE(hspi->Init.Direction)); + /* Check the parameters */ + assert_param(IS_SPI_DIRECTION_2LINES_OR_1LINE(hspi->Init.Direction)); - /* Process Locked */ - __HAL_LOCK(hspi); + /* Process Locked */ + __HAL_LOCK(hspi); - if(hspi->State != HAL_SPI_STATE_READY) - { - errorcode = HAL_BUSY; - goto error; - } + /* Configure communication */ + hspi->State = HAL_SPI_STATE_BUSY_TX; + hspi->ErrorCode = HAL_SPI_ERROR_NONE; - if((pData == NULL) || (Size == 0U)) - { - errorcode = HAL_ERROR; - goto error; - } + hspi->pTxBuffPtr = pData; + hspi->TxXferSize = Size; + hspi->TxXferCount = Size; - /* Set the transaction information */ - hspi->State = HAL_SPI_STATE_BUSY_TX; - hspi->ErrorCode = HAL_SPI_ERROR_NONE; - hspi->pTxBuffPtr = (uint8_t *)pData; - hspi->TxXferSize = Size; - hspi->TxXferCount = Size; - - /* Init field not used in handle to zero */ - hspi->pRxBuffPtr = (uint8_t *)NULL; - hspi->TxISR = NULL; - hspi->RxISR = NULL; - hspi->RxXferSize = 0U; - hspi->RxXferCount = 0U; - - /* Configure communication direction : 1Line */ - if(hspi->Init.Direction == SPI_DIRECTION_1LINE) - { - SPI_1LINE_TX(hspi); - } + /*Init field not used in handle to zero */ + hspi->TxISR = 0; + hspi->RxISR = 0; + hspi->pRxBuffPtr = NULL; + hspi->RxXferSize = 0; + hspi->RxXferCount = 0; -#if (USE_SPI_CRC != 0U) - /* Reset CRC Calculation */ - if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) - { - SPI_RESET_CRC(hspi); - } -#endif /* USE_SPI_CRC */ + /* Configure communication direction : 1Line */ + if(hspi->Init.Direction == SPI_DIRECTION_1LINE) + { + SPI_1LINE_TX(hspi); + } - /* Set the SPI TxDMA Half transfer complete callback */ - hspi->hdmatx->XferHalfCpltCallback = SPI_DMAHalfTransmitCplt; + /* Reset CRC Calculation */ + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) + { + SPI_RESET_CRC(hspi); + } - /* Set the SPI TxDMA transfer complete callback */ - hspi->hdmatx->XferCpltCallback = SPI_DMATransmitCplt; + /* Set the SPI TxDMA Half transfer complete callback */ + hspi->hdmatx->XferHalfCpltCallback = SPI_DMAHalfTransmitCplt; - /* Set the DMA error callback */ - hspi->hdmatx->XferErrorCallback = SPI_DMAError; + /* Set the SPI TxDMA transfer complete callback */ + hspi->hdmatx->XferCpltCallback = SPI_DMATransmitCplt; - /* Set the DMA AbortCpltCallback */ - hspi->hdmatx->XferAbortCallback = NULL; + /* Set the DMA error callback */ + hspi->hdmatx->XferErrorCallback = SPI_DMAError; - /* Enable the Tx DMA Stream */ - HAL_DMA_Start_IT(hspi->hdmatx, (uint32_t)hspi->pTxBuffPtr, (uint32_t)&hspi->Instance->DR, hspi->TxXferCount); + /* Enable the Tx DMA Channel */ + HAL_DMA_Start_IT(hspi->hdmatx, (uint32_t)hspi->pTxBuffPtr, (uint32_t)&hspi->Instance->DR, hspi->TxXferCount); - /* Check if the SPI is already enabled */ - if((hspi->Instance->CR1 &SPI_CR1_SPE) != SPI_CR1_SPE) - { - /* Enable SPI peripheral */ - __HAL_SPI_ENABLE(hspi); - } + /* Enable Tx DMA Request */ + SET_BIT(hspi->Instance->CR2, SPI_CR2_TXDMAEN); - /* Enable the SPI Error Interrupt Bit */ - SET_BIT(hspi->Instance->CR2, SPI_CR2_ERRIE); + /* Process Unlocked */ + __HAL_UNLOCK(hspi); - /* Enable Tx DMA Request */ - SET_BIT(hspi->Instance->CR2, SPI_CR2_TXDMAEN); + /* Check if the SPI is already enabled */ + if((hspi->Instance->CR1 &SPI_CR1_SPE) != SPI_CR1_SPE) + { + /* Enable SPI peripheral */ + __HAL_SPI_ENABLE(hspi); + } -error : - /* Process Unlocked */ - __HAL_UNLOCK(hspi); - return errorcode; + return HAL_OK; + } + else + { + return HAL_BUSY; + } } /** - * @brief Receive an amount of data in non-blocking mode with DMA. + * @brief Receive an amount of data in no-blocking mode with DMA * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. + * the configuration information for SPI module. * @param pData: pointer to data buffer - * @note When the CRC feature is enabled the pData Length must be Size + 1. + * @note When the CRC feature is enabled the pData Length must be Size + 1. * @param Size: amount of data to be sent * @retval HAL status */ HAL_StatusTypeDef HAL_SPI_Receive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size) { - HAL_StatusTypeDef errorcode = HAL_OK; - - if((hspi->Init.Direction == SPI_DIRECTION_2LINES)&&(hspi->Init.Mode == SPI_MODE_MASTER)) + if(hspi->State == HAL_SPI_STATE_READY) { - hspi->State = HAL_SPI_STATE_BUSY_RX; - /* Call transmit-receive function to send Dummy data on Tx line and generate clock on CLK line */ - return HAL_SPI_TransmitReceive_DMA(hspi, pData, pData, Size); - } + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } - /* Process Locked */ - __HAL_LOCK(hspi); + /* Process Locked */ + __HAL_LOCK(hspi); - if(hspi->State != HAL_SPI_STATE_READY) - { - errorcode = HAL_BUSY; - goto error; - } + /* Configure communication */ + hspi->State = HAL_SPI_STATE_BUSY_RX; + hspi->ErrorCode = HAL_SPI_ERROR_NONE; - if((pData == NULL) || (Size == 0U)) - { - errorcode = HAL_ERROR; - goto error; - } + hspi->pRxBuffPtr = pData; + hspi->RxXferSize = Size; + hspi->RxXferCount = Size; - /* Set the transaction information */ - hspi->State = HAL_SPI_STATE_BUSY_RX; - hspi->ErrorCode = HAL_SPI_ERROR_NONE; - hspi->pRxBuffPtr = (uint8_t *)pData; - hspi->RxXferSize = Size; - hspi->RxXferCount = Size; - - /*Init field not used in handle to zero */ - hspi->RxISR = NULL; - hspi->TxISR = NULL; - hspi->TxXferSize = 0U; - hspi->TxXferCount = 0U; - - /* Configure communication direction : 1Line */ - if(hspi->Init.Direction == SPI_DIRECTION_1LINE) - { - SPI_1LINE_RX(hspi); - } + /*Init field not used in handle to zero */ + hspi->RxISR = 0; + hspi->TxISR = 0; + hspi->pTxBuffPtr = NULL; + hspi->TxXferSize = 0; + hspi->TxXferCount = 0; -#if (USE_SPI_CRC != 0U) - /* Reset CRC Calculation */ - if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) - { - SPI_RESET_CRC(hspi); - } -#endif /* USE_SPI_CRC */ + /* Configure communication direction : 1Line */ + if(hspi->Init.Direction == SPI_DIRECTION_1LINE) + { + SPI_1LINE_RX(hspi); + } + else if((hspi->Init.Direction == SPI_DIRECTION_2LINES)&&(hspi->Init.Mode == SPI_MODE_MASTER)) + { + /* Process Unlocked */ + __HAL_UNLOCK(hspi); - /* Set the SPI RxDMA Half transfer complete callback */ - hspi->hdmarx->XferHalfCpltCallback = SPI_DMAHalfReceiveCplt; + /* Call transmit-receive function to send Dummy data on Tx line and generate clock on CLK line */ + return HAL_SPI_TransmitReceive_DMA(hspi, pData, pData, Size); + } - /* Set the SPI Rx DMA transfer complete callback */ - hspi->hdmarx->XferCpltCallback = SPI_DMAReceiveCplt; + /* Reset CRC Calculation */ + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) + { + SPI_RESET_CRC(hspi); + } - /* Set the DMA error callback */ - hspi->hdmarx->XferErrorCallback = SPI_DMAError; + /* Set the SPI RxDMA Half transfer complete callback */ + hspi->hdmarx->XferHalfCpltCallback = SPI_DMAHalfReceiveCplt; - /* Set the DMA AbortCpltCallback */ - hspi->hdmarx->XferAbortCallback = NULL; + /* Set the SPI Rx DMA transfer complete callback */ + hspi->hdmarx->XferCpltCallback = SPI_DMAReceiveCplt; - /* Enable the Rx DMA Stream */ - HAL_DMA_Start_IT(hspi->hdmarx, (uint32_t)&hspi->Instance->DR, (uint32_t)hspi->pRxBuffPtr, hspi->RxXferCount); + /* Set the DMA error callback */ + hspi->hdmarx->XferErrorCallback = SPI_DMAError; - /* Check if the SPI is already enabled */ - if((hspi->Instance->CR1 &SPI_CR1_SPE) != SPI_CR1_SPE) - { - /* Enable SPI peripheral */ - __HAL_SPI_ENABLE(hspi); - } + /* Enable the Rx DMA Channel */ + HAL_DMA_Start_IT(hspi->hdmarx, (uint32_t)&hspi->Instance->DR, (uint32_t)hspi->pRxBuffPtr, hspi->RxXferCount); - /* Enable the SPI Error Interrupt Bit */ - SET_BIT(hspi->Instance->CR2, SPI_CR2_ERRIE); + /* Enable Rx DMA Request */ + SET_BIT(hspi->Instance->CR2, SPI_CR2_RXDMAEN); - /* Enable Rx DMA Request */ - SET_BIT(hspi->Instance->CR2, SPI_CR2_RXDMAEN); + /* Process Unlocked */ + __HAL_UNLOCK(hspi); -error: - /* Process Unlocked */ - __HAL_UNLOCK(hspi); - return errorcode; + /* Check if the SPI is already enabled */ + if((hspi->Instance->CR1 &SPI_CR1_SPE) != SPI_CR1_SPE) + { + /* Enable SPI peripheral */ + __HAL_SPI_ENABLE(hspi); + } + + return HAL_OK; + } + else + { + return HAL_BUSY; + } } /** - * @brief Transmit and Receive an amount of data in non-blocking mode with DMA. + * @brief Transmit and Receive an amount of data in no-blocking mode with DMA * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. + * the configuration information for SPI module. * @param pTxData: pointer to transmission data buffer * @param pRxData: pointer to reception data buffer - * @note When the CRC feature is enabled the pRxData Length must be Size + 1 + * @note When the CRC feature is enabled the pRxData Length must be Size + 1 * @param Size: amount of data to be sent * @retval HAL status */ HAL_StatusTypeDef HAL_SPI_TransmitReceive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size) { - uint32_t tmp = 0U, tmp1 = 0U; - HAL_StatusTypeDef errorcode = HAL_OK; - - /* Check Direction parameter */ - assert_param(IS_SPI_DIRECTION_2LINES(hspi->Init.Direction)); - - /* Process locked */ - __HAL_LOCK(hspi); - - tmp = hspi->State; - tmp1 = hspi->Init.Mode; - if(!((tmp == HAL_SPI_STATE_READY) || - ((tmp1 == SPI_MODE_MASTER) && (hspi->Init.Direction == SPI_DIRECTION_2LINES) && (tmp == HAL_SPI_STATE_BUSY_RX)))) - { - errorcode = HAL_BUSY; - goto error; - } - - if((pTxData == NULL ) || (pRxData == NULL ) || (Size == 0U)) - { - errorcode = HAL_ERROR; - goto error; - } - - /* Don't overwrite in case of HAL_SPI_STATE_BUSY_RX */ - if(hspi->State == HAL_SPI_STATE_READY) - { - hspi->State = HAL_SPI_STATE_BUSY_TX_RX; - } - - /* Set the transaction information */ - hspi->ErrorCode = HAL_SPI_ERROR_NONE; - hspi->pTxBuffPtr = (uint8_t*)pTxData; - hspi->TxXferSize = Size; - hspi->TxXferCount = Size; - hspi->pRxBuffPtr = (uint8_t*)pRxData; - hspi->RxXferSize = Size; - hspi->RxXferCount = Size; - - /* Init field not used in handle to zero */ - hspi->RxISR = NULL; - hspi->TxISR = NULL; - -#if (USE_SPI_CRC != 0U) - /* Reset CRC Calculation */ - if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) - { - SPI_RESET_CRC(hspi); - } -#endif /* USE_SPI_CRC */ - - /* Check if we are in Rx only or in Rx/Tx Mode and configure the DMA transfer complete callback */ - if(hspi->State == HAL_SPI_STATE_BUSY_RX) - { - /* Set the SPI Rx DMA Half transfer complete callback */ - hspi->hdmarx->XferHalfCpltCallback = SPI_DMAHalfReceiveCplt; - hspi->hdmarx->XferCpltCallback = SPI_DMAReceiveCplt; - } - else - { - /* Set the SPI Tx/Rx DMA Half transfer complete callback */ - hspi->hdmarx->XferHalfCpltCallback = SPI_DMAHalfTransmitReceiveCplt; - hspi->hdmarx->XferCpltCallback = SPI_DMATransmitReceiveCplt; - } - - /* Set the DMA error callback */ - hspi->hdmarx->XferErrorCallback = SPI_DMAError; - - /* Set the DMA AbortCpltCallback */ - hspi->hdmarx->XferAbortCallback = NULL; - - /* Enable the Rx DMA Stream */ - HAL_DMA_Start_IT(hspi->hdmarx, (uint32_t)&hspi->Instance->DR, (uint32_t)hspi->pRxBuffPtr, hspi->RxXferCount); - - /* Enable Rx DMA Request */ - SET_BIT(hspi->Instance->CR2, SPI_CR2_RXDMAEN); - - /* Set the SPI Tx DMA transfer complete callback as NULL because the communication closing - is performed in DMA reception complete callback */ - hspi->hdmatx->XferHalfCpltCallback = NULL; - hspi->hdmatx->XferCpltCallback = NULL; - hspi->hdmatx->XferErrorCallback = NULL; - hspi->hdmatx->XferAbortCallback = NULL; - - /* Enable the Tx DMA Stream */ - HAL_DMA_Start_IT(hspi->hdmatx, (uint32_t)hspi->pTxBuffPtr, (uint32_t)&hspi->Instance->DR, hspi->TxXferCount); - - /* Check if the SPI is already enabled */ - if((hspi->Instance->CR1 &SPI_CR1_SPE) != SPI_CR1_SPE) - { - /* Enable SPI peripheral */ - __HAL_SPI_ENABLE(hspi); - } - /* Enable the SPI Error Interrupt Bit */ - SET_BIT(hspi->Instance->CR2, SPI_CR2_ERRIE); - - /* Enable Tx DMA Request */ - SET_BIT(hspi->Instance->CR2, SPI_CR2_TXDMAEN); - -error : - /* Process Unlocked */ - __HAL_UNLOCK(hspi); - return errorcode; -} - -/** - * @brief Abort ongoing transfer (blocking mode). - * @param hspi SPI handle. - * @note This procedure could be used for aborting any ongoing transfer (Tx and Rx), - * started in Interrupt or DMA mode. - * This procedure performs following operations : - * - Disable SPI Interrupts (depending of transfer direction) - * - Disable the DMA transfer in the peripheral register (if enabled) - * - Abort DMA transfer by calling HAL_DMA_Abort (in case of transfer in DMA mode) - * - Set handle State to READY - * @note This procedure is executed in blocking mode : when exiting function, Abort is considered as completed. - * @note Once transfer is aborted, the __HAL_SPI_CLEAR_OVRFLAG() macro must be called in user application - * before starting new SPI receive process. - * @retval HAL status -*/ -HAL_StatusTypeDef HAL_SPI_Abort(SPI_HandleTypeDef *hspi) -{ - __IO uint32_t count = SPI_DEFAULT_TIMEOUT * (SystemCoreClock / 24U / 1000U); - - /* Disable TXEIE, RXNEIE and ERRIE(mode fault event, overrun error, TI frame error) interrupts */ - if(HAL_IS_BIT_SET(hspi->Instance->CR2, SPI_CR2_TXEIE)) - { - hspi->TxISR = SPI_AbortTx_ISR; - } - - if(HAL_IS_BIT_SET(hspi->Instance->CR2, SPI_CR2_RXNEIE)) - { - hspi->RxISR = SPI_AbortRx_ISR; - } - - /* Clear ERRIE interrupts in case of DMA Mode */ - CLEAR_BIT(hspi->Instance->CR2, SPI_CR2_ERRIE); - - /* Disable the SPI DMA Tx or SPI DMA Rx request if enabled */ - if ((HAL_IS_BIT_SET(hspi->Instance->CR2, SPI_CR2_TXDMAEN)) || (HAL_IS_BIT_SET(hspi->Instance->CR2, SPI_CR2_RXDMAEN))) + if((hspi->State == HAL_SPI_STATE_READY) || \ + ((hspi->Init.Mode == SPI_MODE_MASTER) && (hspi->Init.Direction == SPI_DIRECTION_2LINES) && (hspi->State == HAL_SPI_STATE_BUSY_RX))) { - /* Abort the SPI DMA Tx channel : use blocking DMA Abort API (no callback) */ - if(hspi->hdmatx != NULL) + if((pTxData == NULL ) || (pRxData == NULL ) || (Size == 0)) { - /* Set the SPI DMA Abort callback : - will lead to call HAL_SPI_AbortCpltCallback() at end of DMA abort procedure */ - hspi->hdmatx->XferAbortCallback = NULL; - - /* Abort DMA Tx Handle linked to SPI Peripheral */ - HAL_DMA_Abort(hspi->hdmatx); - - /* Disable Tx DMA Request */ - CLEAR_BIT(hspi->Instance->CR2, (SPI_CR2_TXDMAEN)); - - /* Wait until TXE flag is set */ - do - { - if(count-- == 0U) - { - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_FLAG); - break; - } - } - while((hspi->Instance->SR & SPI_FLAG_TXE) == RESET); + return HAL_ERROR; } - /* Abort the SPI DMA Rx channel : use blocking DMA Abort API (no callback) */ - if(hspi->hdmarx != NULL) - { - /* Set the SPI DMA Abort callback : - will lead to call HAL_SPI_AbortCpltCallback() at end of DMA abort procedure */ - hspi->hdmarx->XferAbortCallback = NULL; - - /* Abort DMA Rx Handle linked to SPI Peripheral */ - HAL_DMA_Abort(hspi->hdmarx); - /* Disable peripheral */ - __HAL_SPI_DISABLE(hspi); + /* Check the parameters */ + assert_param(IS_SPI_DIRECTION_2LINES(hspi->Init.Direction)); + + /* Process locked */ + __HAL_LOCK(hspi); - /* Disable Rx DMA Request */ - CLEAR_BIT(hspi->Instance->CR2, (SPI_CR2_RXDMAEN)); - + /* Don't overwrite in case of HAL_SPI_STATE_BUSY_RX */ + if(hspi->State != HAL_SPI_STATE_BUSY_RX) + { + hspi->State = HAL_SPI_STATE_BUSY_TX_RX; } - } - /* Reset Tx and Rx transfer counters */ - hspi->RxXferCount = 0U; - hspi->TxXferCount = 0U; - - /* Reset errorCode */ - hspi->ErrorCode = HAL_SPI_ERROR_NONE; - /* Clear the Error flags in the SR register */ - __HAL_SPI_CLEAR_OVRFLAG(hspi); - - /* Restore hspi->state to ready */ - hspi->State = HAL_SPI_STATE_READY; - - return HAL_OK; -} - -/** - * @brief Abort ongoing transfer (Interrupt mode). - * @param hspi SPI handle. - * @note This procedure could be used for aborting any ongoing transfer (Tx and Rx), - * started in Interrupt or DMA mode. - * This procedure performs following operations : - * - Disable SPI Interrupts (depending of transfer direction) - * - Disable the DMA transfer in the peripheral register (if enabled) - * - Abort DMA transfer by calling HAL_DMA_Abort_IT (in case of transfer in DMA mode) - * - Set handle State to READY - * - At abort completion, call user abort complete callback - * @note This procedure is executed in Interrupt mode, meaning that abort procedure could be - * considered as completed only when user abort complete callback is executed (not when exiting function). - * @note Once transfer is aborted, the __HAL_SPI_CLEAR_OVRFLAG() macro must be called in user application - * before starting new SPI receive process. - * @retval HAL status -*/ -HAL_StatusTypeDef HAL_SPI_Abort_IT(SPI_HandleTypeDef *hspi) -{ - uint32_t abortcplt; + /* Configure communication */ + hspi->ErrorCode = HAL_SPI_ERROR_NONE; - /* Change Rx and Tx Irq Handler to Disable TXEIE, RXNEIE and ERRIE interrupts */ - if(HAL_IS_BIT_SET(hspi->Instance->CR2, SPI_CR2_TXEIE)) - { - hspi->TxISR = SPI_AbortTx_ISR; - } + hspi->pTxBuffPtr = (uint8_t*)pTxData; + hspi->TxXferSize = Size; + hspi->TxXferCount = Size; - if(HAL_IS_BIT_SET(hspi->Instance->CR2, SPI_CR2_RXNEIE)) - { - hspi->RxISR = SPI_AbortRx_ISR; - } + hspi->pRxBuffPtr = (uint8_t*)pRxData; + hspi->RxXferSize = Size; + hspi->RxXferCount = Size; - /* Clear ERRIE interrupts in case of DMA Mode */ - CLEAR_BIT(hspi->Instance->CR2, SPI_CR2_ERRIE); + /*Init field not used in handle to zero */ + hspi->RxISR = 0; + hspi->TxISR = 0; - abortcplt = 1U; - - /* If DMA Tx and/or DMA Rx Handles are associated to SPI Handle, DMA Abort complete callbacks should be initialised - before any call to DMA Abort functions */ - /* DMA Tx Handle is valid */ - if(hspi->hdmatx != NULL) - { - /* Set DMA Abort Complete callback if UART DMA Tx request if enabled. - Otherwise, set it to NULL */ - if(HAL_IS_BIT_SET(hspi->Instance->CR2, SPI_CR2_TXDMAEN)) - { - hspi->hdmatx->XferAbortCallback = SPI_DMATxAbortCallback; - } - else + /* Reset CRC Calculation */ + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) { - hspi->hdmatx->XferAbortCallback = NULL; + SPI_RESET_CRC(hspi); } - } - /* DMA Rx Handle is valid */ - if(hspi->hdmarx != NULL) - { - /* Set DMA Abort Complete callback if UART DMA Rx request if enabled. - Otherwise, set it to NULL */ - if(HAL_IS_BIT_SET(hspi->Instance->CR2, SPI_CR2_RXDMAEN)) + + /* Check if we are in Rx only or in Rx/Tx Mode and configure the DMA transfer complete callback */ + if(hspi->State == HAL_SPI_STATE_BUSY_RX) { - hspi->hdmarx->XferAbortCallback = SPI_DMARxAbortCallback; + /* Set the SPI Rx DMA Half transfer complete callback */ + hspi->hdmarx->XferHalfCpltCallback = SPI_DMAHalfReceiveCplt; + + hspi->hdmarx->XferCpltCallback = SPI_DMAReceiveCplt; } else { - hspi->hdmarx->XferAbortCallback = NULL; + /* Set the SPI Tx/Rx DMA Half transfer complete callback */ + hspi->hdmarx->XferHalfCpltCallback = SPI_DMAHalfTransmitReceiveCplt; + + hspi->hdmarx->XferCpltCallback = SPI_DMATransmitReceiveCplt; } - } - /* Disable the SPI DMA Tx or the SPI Rx request if enabled */ - if((HAL_IS_BIT_SET(hspi->Instance->CR2, SPI_CR2_TXDMAEN)) && (HAL_IS_BIT_SET(hspi->Instance->CR2, SPI_CR2_RXDMAEN))) - { - /* Abort the SPI DMA Tx channel */ - if(hspi->hdmatx != NULL) + /* Set the DMA error callback */ + hspi->hdmarx->XferErrorCallback = SPI_DMAError; + + /* Enable the Rx DMA Channel */ + HAL_DMA_Start_IT(hspi->hdmarx, (uint32_t)&hspi->Instance->DR, (uint32_t)hspi->pRxBuffPtr, hspi->RxXferCount); + + /* Enable Rx DMA Request */ + SET_BIT(hspi->Instance->CR2, SPI_CR2_RXDMAEN); + + /* Set the SPI Tx DMA transfer complete callback as NULL because the communication closing + is performed in DMA reception complete callback */ + if(hspi->State == HAL_SPI_STATE_BUSY_TX_RX) { - /* Abort DMA Tx Handle linked to SPI Peripheral */ - if(HAL_DMA_Abort_IT(hspi->hdmatx) != HAL_OK) - { - hspi->hdmatx->XferAbortCallback = NULL; - } - else - { - abortcplt = 0U; - } + /* Set the DMA error callback */ + hspi->hdmatx->XferErrorCallback = SPI_DMAError; } - /* Abort the SPI DMA Rx channel */ - if(hspi->hdmarx != NULL) + else { - /* Abort DMA Rx Handle linked to SPI Peripheral */ - if(HAL_DMA_Abort_IT(hspi->hdmarx)!= HAL_OK) - { - hspi->hdmarx->XferAbortCallback = NULL; - abortcplt = 1U; - } - else - { - abortcplt = 0U; - } + hspi->hdmatx->XferErrorCallback = NULL; } - } + + /* Enable the Tx DMA Channel */ + HAL_DMA_Start_IT(hspi->hdmatx, (uint32_t)hspi->pTxBuffPtr, (uint32_t)&hspi->Instance->DR, hspi->TxXferCount); - /* Disable the SPI DMA Tx or the SPI Rx request if enabled */ - if (HAL_IS_BIT_SET(hspi->Instance->CR2, SPI_CR2_TXDMAEN)) - { - /* Abort the SPI DMA Tx channel */ - if(hspi->hdmatx != NULL) - { - /* Abort DMA Tx Handle linked to SPI Peripheral */ - if(HAL_DMA_Abort_IT(hspi->hdmatx) != HAL_OK) - { - hspi->hdmatx->XferAbortCallback = NULL; - } - else - { - abortcplt = 0U; - } - } - } - /* Disable the SPI DMA Tx or the SPI Rx request if enabled */ - if (HAL_IS_BIT_SET(hspi->Instance->CR2, SPI_CR2_RXDMAEN)) - { - /* Abort the SPI DMA Rx channel */ - if(hspi->hdmarx != NULL) + /* Check if the SPI is already enabled */ + if((hspi->Instance->CR1 & SPI_CR1_SPE) != SPI_CR1_SPE) { - /* Abort DMA Rx Handle linked to SPI Peripheral */ - if(HAL_DMA_Abort_IT(hspi->hdmarx)!= HAL_OK) - { - hspi->hdmarx->XferAbortCallback = NULL; - } - else - { - abortcplt = 0U; - } + /* Enable SPI peripheral */ + __HAL_SPI_ENABLE(hspi); } - } - - if(abortcplt == 1U) - { - /* Reset Tx and Rx transfer counters */ - hspi->RxXferCount = 0U; - hspi->TxXferCount = 0U; - - /* Reset errorCode */ - hspi->ErrorCode = HAL_SPI_ERROR_NONE; - /* Clear the Error flags in the SR register */ - __HAL_SPI_CLEAR_OVRFLAG(hspi); + /* Enable Tx DMA Request */ + SET_BIT(hspi->Instance->CR2, SPI_CR2_TXDMAEN); - /* Restore hspi->State to Ready */ - hspi->State = HAL_SPI_STATE_READY; + /* Process Unlocked */ + __HAL_UNLOCK(hspi); - /* As no DMA to be aborted, call directly user Abort complete callback */ - HAL_SPI_AbortCpltCallback(hspi); + return HAL_OK; + } + else + { + return HAL_BUSY; } - return HAL_OK; } + /** - * @brief Pause the DMA Transfer. + * @brief Pauses the DMA Transfer. * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for the specified SPI module. + * the configuration information for the specified SPI module. * @retval HAL status */ HAL_StatusTypeDef HAL_SPI_DMAPause(SPI_HandleTypeDef *hspi) { /* Process Locked */ __HAL_LOCK(hspi); - + /* Disable the SPI DMA Tx & Rx requests */ - CLEAR_BIT(hspi->Instance->CR2, SPI_CR2_TXDMAEN | SPI_CR2_RXDMAEN); - + CLEAR_BIT(hspi->Instance->CR2, SPI_CR2_TXDMAEN); + CLEAR_BIT(hspi->Instance->CR2, SPI_CR2_RXDMAEN); + /* Process Unlocked */ __HAL_UNLOCK(hspi); - - return HAL_OK; + + return HAL_OK; } /** - * @brief Resume the DMA Transfer. + * @brief Resumes the DMA Transfer. * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for the specified SPI module. + * the configuration information for the specified SPI module. * @retval HAL status */ HAL_StatusTypeDef HAL_SPI_DMAResume(SPI_HandleTypeDef *hspi) { /* Process Locked */ __HAL_LOCK(hspi); - + /* Enable the SPI DMA Tx & Rx requests */ - SET_BIT(hspi->Instance->CR2, SPI_CR2_TXDMAEN | SPI_CR2_RXDMAEN); - + SET_BIT(hspi->Instance->CR2, SPI_CR2_TXDMAEN); + SET_BIT(hspi->Instance->CR2, SPI_CR2_RXDMAEN); + /* Process Unlocked */ __HAL_UNLOCK(hspi); - + return HAL_OK; } /** - * @brief Stop the DMA Transfer. + * @brief Stops the DMA Transfer. * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for the specified SPI module. + * the configuration information for the specified SPI module. * @retval HAL status */ HAL_StatusTypeDef HAL_SPI_DMAStop(SPI_HandleTypeDef *hspi) @@ -1920,233 +1542,188 @@ HAL_StatusTypeDef HAL_SPI_DMAStop(SPI_HandleTypeDef *hspi) when calling HAL_DMA_Abort() API the DMA TX/RX Transfer complete interrupt is generated and the correspond call back is executed HAL_SPI_TxCpltCallback() or HAL_SPI_RxCpltCallback() or HAL_SPI_TxRxCpltCallback() */ - - /* Abort the SPI DMA tx Stream */ + + /* Abort the SPI DMA tx Channel */ if(hspi->hdmatx != NULL) { HAL_DMA_Abort(hspi->hdmatx); } - /* Abort the SPI DMA rx Stream */ + /* Abort the SPI DMA rx Channel */ if(hspi->hdmarx != NULL) { HAL_DMA_Abort(hspi->hdmarx); } - + /* Disable the SPI DMA Tx & Rx requests */ - CLEAR_BIT(hspi->Instance->CR2, SPI_CR2_TXDMAEN | SPI_CR2_RXDMAEN); + CLEAR_BIT(hspi->Instance->CR2, SPI_CR2_TXDMAEN); + CLEAR_BIT(hspi->Instance->CR2, SPI_CR2_RXDMAEN); + hspi->State = HAL_SPI_STATE_READY; + return HAL_OK; } /** - * @brief Handle SPI interrupt request. + * @brief This function handles SPI interrupt request. * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for the specified SPI module. + * the configuration information for SPI module. * @retval None */ void HAL_SPI_IRQHandler(SPI_HandleTypeDef *hspi) { - uint32_t itsource = hspi->Instance->CR2; - uint32_t itflag = hspi->Instance->SR; - - /* SPI in mode Receiver ----------------------------------------------------*/ - if(((itflag & SPI_FLAG_OVR) == RESET) && - ((itflag & SPI_FLAG_RXNE) != RESET) && ((itsource & SPI_IT_RXNE) != RESET)) + /* SPI in mode Receiver and Overrun not occurred ---------------------------*/ + if((__HAL_SPI_GET_IT_SOURCE(hspi, SPI_IT_RXNE) != RESET) && (__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_RXNE) != RESET) && (__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_OVR) == RESET)) { hspi->RxISR(hspi); return; } - /* SPI in mode Transmitter -------------------------------------------------*/ - if(((itflag & SPI_FLAG_TXE) != RESET) && ((itsource & SPI_IT_TXE) != RESET)) + /* SPI in mode Tramitter ---------------------------------------------------*/ + if((__HAL_SPI_GET_IT_SOURCE(hspi, SPI_IT_TXE) != RESET) && (__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_TXE) != RESET)) { hspi->TxISR(hspi); return; } - /* SPI in Error Treatment --------------------------------------------------*/ - if(((itflag & (SPI_FLAG_MODF | SPI_FLAG_OVR)) != RESET) && ((itsource & SPI_IT_ERR) != RESET)) + if(__HAL_SPI_GET_IT_SOURCE(hspi, SPI_IT_ERR) != RESET) { - /* SPI Overrun error interrupt occurred ----------------------------------*/ - if((itflag & SPI_FLAG_OVR) != RESET) + /* SPI CRC error interrupt occurred ---------------------------------------*/ + if(__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_CRCERR) != RESET) { - if(hspi->State != HAL_SPI_STATE_BUSY_TX) - { - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_OVR); - __HAL_SPI_CLEAR_OVRFLAG(hspi); - } - else - { - __HAL_SPI_CLEAR_OVRFLAG(hspi); - return; - } - } - - /* SPI Mode Fault error interrupt occurred -------------------------------*/ - if((itflag & SPI_FLAG_MODF) != RESET) + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_CRC); + __HAL_SPI_CLEAR_CRCERRFLAG(hspi); + } + /* SPI Mode Fault error interrupt occurred --------------------------------*/ + if(__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_MODF) != RESET) { SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_MODF); __HAL_SPI_CLEAR_MODFFLAG(hspi); } + + /* SPI Overrun error interrupt occurred -----------------------------------*/ + if(__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_OVR) != RESET) + { + if(hspi->State != HAL_SPI_STATE_BUSY_TX) + { + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_OVR); + __HAL_SPI_CLEAR_OVRFLAG(hspi); + } + } - if(hspi->ErrorCode != HAL_SPI_ERROR_NONE) + /* Call the Error call Back in case of Errors */ + if(hspi->ErrorCode!=HAL_SPI_ERROR_NONE) { - /* Disable all interrupts */ __HAL_SPI_DISABLE_IT(hspi, SPI_IT_RXNE | SPI_IT_TXE | SPI_IT_ERR); - hspi->State = HAL_SPI_STATE_READY; - /* Disable the SPI DMA requests if enabled */ - if ((HAL_IS_BIT_SET(itsource, SPI_CR2_TXDMAEN))||(HAL_IS_BIT_SET(itsource, SPI_CR2_RXDMAEN))) - { - CLEAR_BIT(hspi->Instance->CR2, (SPI_CR2_TXDMAEN | SPI_CR2_RXDMAEN)); - - /* Abort the SPI DMA Rx channel */ - if(hspi->hdmarx != NULL) - { - /* Set the SPI DMA Abort callback : - will lead to call HAL_SPI_ErrorCallback() at end of DMA abort procedure */ - hspi->hdmarx->XferAbortCallback = SPI_DMAAbortOnError; - HAL_DMA_Abort_IT(hspi->hdmarx); - } - /* Abort the SPI DMA Tx channel */ - if(hspi->hdmatx != NULL) - { - /* Set the SPI DMA Abort callback : - will lead to call HAL_SPI_ErrorCallback() at end of DMA abort procedure */ - hspi->hdmatx->XferAbortCallback = SPI_DMAAbortOnError; - HAL_DMA_Abort_IT(hspi->hdmatx); - } - } - else - { - /* Call user error callback */ - HAL_SPI_ErrorCallback(hspi); - } + HAL_SPI_ErrorCallback(hspi); } - return; } } /** - * @brief Tx Transfer completed callback. + * @brief Tx Transfer completed callbacks * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. + * the configuration information for SPI module. * @retval None */ __weak void HAL_SPI_TxCpltCallback(SPI_HandleTypeDef *hspi) { /* Prevent unused argument(s) compilation warning */ UNUSED(hspi); - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_SPI_TxCpltCallback should be implemented in the user file - */ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_SPI_TxCpltCallback could be implenetd in the user file + */ } /** - * @brief Rx Transfer completed callback. + * @brief Rx Transfer completed callbacks * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. + * the configuration information for SPI module. * @retval None */ __weak void HAL_SPI_RxCpltCallback(SPI_HandleTypeDef *hspi) { /* Prevent unused argument(s) compilation warning */ UNUSED(hspi); - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_SPI_RxCpltCallback should be implemented in the user file - */ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_SPI_RxCpltCallback() could be implenetd in the user file + */ } /** - * @brief Tx and Rx Transfer completed callback. + * @brief Tx and Rx Transfer completed callbacks * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. + * the configuration information for SPI module. * @retval None */ __weak void HAL_SPI_TxRxCpltCallback(SPI_HandleTypeDef *hspi) { /* Prevent unused argument(s) compilation warning */ UNUSED(hspi); - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_SPI_TxRxCpltCallback should be implemented in the user file - */ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_SPI_TxRxCpltCallback() could be implenetd in the user file + */ } /** - * @brief Tx Half Transfer completed callback. + * @brief Tx Half Transfer completed callbacks * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. + * the configuration information for SPI module. * @retval None */ __weak void HAL_SPI_TxHalfCpltCallback(SPI_HandleTypeDef *hspi) { /* Prevent unused argument(s) compilation warning */ UNUSED(hspi); - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_SPI_TxHalfCpltCallback should be implemented in the user file - */ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_SPI_TxHalfCpltCallback could be implenetd in the user file + */ } /** - * @brief Rx Half Transfer completed callback. + * @brief Rx Half Transfer completed callbacks * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. + * the configuration information for SPI module. * @retval None */ __weak void HAL_SPI_RxHalfCpltCallback(SPI_HandleTypeDef *hspi) { /* Prevent unused argument(s) compilation warning */ UNUSED(hspi); - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_SPI_RxHalfCpltCallback() should be implemented in the user file - */ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_SPI_RxHalfCpltCallback() could be implenetd in the user file + */ } /** - * @brief Tx and Rx Half Transfer callback. + * @brief Tx and Rx Transfer completed callbacks * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. + * the configuration information for SPI module. * @retval None */ __weak void HAL_SPI_TxRxHalfCpltCallback(SPI_HandleTypeDef *hspi) { /* Prevent unused argument(s) compilation warning */ UNUSED(hspi); - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_SPI_TxRxHalfCpltCallback() should be implemented in the user file - */ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_SPI_TxRxHalfCpltCallback() could be implenetd in the user file + */ } /** - * @brief SPI error callback. + * @brief SPI error callbacks * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. + * the configuration information for SPI module. * @retval None */ __weak void HAL_SPI_ErrorCallback(SPI_HandleTypeDef *hspi) { /* Prevent unused argument(s) compilation warning */ UNUSED(hspi); - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_SPI_ErrorCallback should be implemented in the user file - */ - /* NOTE : The ErrorCode parameter in the hspi handle is updated by the SPI processes - and user can use HAL_SPI_GetError() API to check the latest error occurred - */ -} - -/** - * @brief SPI Abort Complete callback. - * @param hspi SPI handle. - * @retval None - */ -__weak void HAL_SPI_AbortCpltCallback(SPI_HandleTypeDef *hspi) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(hspi); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_SPI_AbortCpltCallback can be implemented in the user file. + /* NOTE : - This function Should not be modified, when the callback is needed, + the HAL_SPI_ErrorCallback() could be implenetd in the user file. + - The ErrorCode parameter in the hspi handle is updated by the SPI processes + and user can use HAL_SPI_GetError() API to check the latest error occurred. */ } @@ -2154,13 +1731,13 @@ __weak void HAL_SPI_AbortCpltCallback(SPI_HandleTypeDef *hspi) * @} */ -/** @defgroup SPI_Exported_Functions_Group3 Peripheral State and Errors functions - * @brief SPI control functions +/** @defgroup SPI_Exported_Functions_Group3 Peripheral State and Errors functions + * @brief SPI control functions * @verbatim =============================================================================== ##### Peripheral State and Errors functions ##### - =============================================================================== + =============================================================================== [..] This subsection provides a set of functions allowing to control the SPI. (+) HAL_SPI_GetState() API can be helpful to check in run-time the state of the SPI peripheral @@ -2170,1071 +1747,640 @@ __weak void HAL_SPI_AbortCpltCallback(SPI_HandleTypeDef *hspi) */ /** - * @brief Return the SPI handle state. + * @brief Return the SPI state * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. + * the configuration information for SPI module. * @retval SPI state */ HAL_SPI_StateTypeDef HAL_SPI_GetState(SPI_HandleTypeDef *hspi) { - /* Return SPI handle state */ return hspi->State; } /** - * @brief Return the SPI error code. + * @brief Return the SPI error code * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. - * @retval SPI error code in bitmap format + * the configuration information for SPI module. + * @retval SPI Error Code */ uint32_t HAL_SPI_GetError(SPI_HandleTypeDef *hspi) { - /* Return SPI ErrorCode */ return hspi->ErrorCode; } /** * @} */ - + /** - * @} - */ + * @} + */ + + /** @addtogroup SPI_Private_Functions - * @brief Private functions - * @{ - */ + * @{ + */ -/** - * @brief DMA SPI transmit process complete callback. - * @param hdma: pointer to a DMA_HandleTypeDef structure that contains - * the configuration information for the specified DMA module. + + /** + * @brief Interrupt Handler to close Tx transfer + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. * @retval None */ -static void SPI_DMATransmitCplt(DMA_HandleTypeDef *hdma) +static void SPI_TxCloseIRQHandler(SPI_HandleTypeDef *hspi) { - SPI_HandleTypeDef* hspi = ( SPI_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; - uint32_t tickstart = 0U; + /* Wait until TXE flag is set to send data */ + if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_TXE, RESET, SPI_TIMEOUT_VALUE) != HAL_OK) + { + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_FLAG); + } - /* Init tickstart for timeout managment*/ - tickstart = HAL_GetTick(); + /* Disable TXE interrupt */ + __HAL_SPI_DISABLE_IT(hspi, (SPI_IT_TXE)); - /* DMA Normal Mode */ - if((hdma->Instance->CCR & DMA_CCR_CIRC) != DMA_CCR_CIRC) + /* Disable ERR interrupt if Receive process is finished */ + if(__HAL_SPI_GET_IT_SOURCE(hspi, SPI_IT_RXNE) == RESET) { - /* Disable Tx DMA Request */ - CLEAR_BIT(hspi->Instance->CR2, SPI_CR2_TXDMAEN); + __HAL_SPI_DISABLE_IT(hspi, (SPI_IT_ERR)); - /* Check the end of the transaction */ - if(SPI_CheckFlag_BSY(hspi, SPI_DEFAULT_TIMEOUT, tickstart) != HAL_OK) + /* Wait until Busy flag is reset before disabling SPI */ + if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_BSY, SET, SPI_TIMEOUT_VALUE) != HAL_OK) { SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_FLAG); } - /* Clear overrun flag in 2 Lines communication mode because received data is not read */ + /* Clear OVERUN flag in 2 Lines communication mode because received is not read */ if(hspi->Init.Direction == SPI_DIRECTION_2LINES) { __HAL_SPI_CLEAR_OVRFLAG(hspi); } - - hspi->TxXferCount = 0U; - hspi->State = HAL_SPI_STATE_READY; - - if(hspi->ErrorCode != HAL_SPI_ERROR_NONE) + + /* Check if Errors has been detected during transfer */ + if(hspi->ErrorCode == HAL_SPI_ERROR_NONE) + { + /* Check if we are in Tx or in Rx/Tx Mode */ + if(hspi->State == HAL_SPI_STATE_BUSY_TX_RX) + { + /* Set state to READY before run the Callback Complete */ + hspi->State = HAL_SPI_STATE_READY; + HAL_SPI_TxRxCpltCallback(hspi); + } + else + { + /* Set state to READY before run the Callback Complete */ + hspi->State = HAL_SPI_STATE_READY; + HAL_SPI_TxCpltCallback(hspi); + } + } + else { + /* Set state to READY before run the Callback Complete */ + hspi->State = HAL_SPI_STATE_READY; + /* Call Error call back in case of Error */ HAL_SPI_ErrorCallback(hspi); - return; } } - HAL_SPI_TxCpltCallback(hspi); } /** - * @brief DMA SPI receive process complete callback. - * @param hdma: pointer to a DMA_HandleTypeDef structure that contains - * the configuration information for the specified DMA module. + * @brief Interrupt Handler to transmit amount of data in no-blocking mode + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. * @retval None */ -static void SPI_DMAReceiveCplt(DMA_HandleTypeDef *hdma) +static void SPI_TxISR(SPI_HandleTypeDef *hspi) { - SPI_HandleTypeDef* hspi = ( SPI_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; -#if (USE_SPI_CRC != 0U) - uint32_t tickstart = 0U; - __IO uint16_t tmpreg = 0U; + /* Transmit data in 8 Bit mode */ + if(hspi->Init.DataSize == SPI_DATASIZE_8BIT) + { + hspi->Instance->DR = (*hspi->pTxBuffPtr++); + } + /* Transmit data in 16 Bit mode */ + else + { + hspi->Instance->DR = *((uint16_t*)hspi->pTxBuffPtr); + hspi->pTxBuffPtr+=2; + } + hspi->TxXferCount--; - /* Init tickstart for timeout management*/ - tickstart = HAL_GetTick(); -#endif /* USE_SPI_CRC */ - - if((hdma->Instance->CCR & DMA_CCR_CIRC) != DMA_CCR_CIRC) + if(hspi->TxXferCount == 0) { -#if (USE_SPI_CRC != 0U) - /* CRC handling */ if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) { - /* Wait until RXNE flag */ - if(SPI_WaitFlagStateUntilTimeout(hspi, SPI_FLAG_RXNE, SPI_FLAG_RXNE, SPI_DEFAULT_TIMEOUT, tickstart) != HAL_OK) - { - /* Error on the CRC reception */ - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_CRC); - } - /* Read CRC */ - tmpreg = hspi->Instance->DR; - /* To avoid GCC warning */ - UNUSED(tmpreg); + /* calculate and transfer CRC on Tx line */ + SET_BIT(hspi->Instance->CR1, SPI_CR1_CRCNEXT); } -#endif /* USE_SPI_CRC */ + SPI_TxCloseIRQHandler(hspi); + } +} - /* Disable Rx/Tx DMA Request (done by default to handle the case master rx direction 2 lines) */ - CLEAR_BIT(hspi->Instance->CR2, SPI_CR2_TXDMAEN | SPI_CR2_RXDMAEN); +/** + * @brief Interrupt Handler to close Rx transfer + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval None + */ +static void SPI_RxCloseIRQHandler(SPI_HandleTypeDef *hspi) +{ + __IO uint16_t tmpreg = 0; - /* Check the end of the transaction */ - if((hspi->Init.Mode == SPI_MODE_MASTER)&&((hspi->Init.Direction == SPI_DIRECTION_1LINE)||(hspi->Init.Direction == SPI_DIRECTION_2LINES_RXONLY))) + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) + { + /* Wait until RXNE flag is set to read CRC data */ + if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, RESET, SPI_TIMEOUT_VALUE) != HAL_OK) { - /* Disable SPI peripheral */ - __HAL_SPI_DISABLE(hspi); + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_FLAG); } - hspi->RxXferCount = 0U; - hspi->State = HAL_SPI_STATE_READY; + /* Read CRC to reset RXNE flag */ + tmpreg = hspi->Instance->DR; + UNUSED(tmpreg); + + /* Wait until RXNE flag is reset */ + if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, SET, SPI_TIMEOUT_VALUE) != HAL_OK) + { + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_FLAG); + } -#if (USE_SPI_CRC != 0U) /* Check if CRC error occurred */ if(__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_CRCERR) != RESET) { /* Check if CRC error is valid or not (workaround to be applied or not) */ - if (SPI_ISCRCErrorValid(hspi) == SPI_VALID_CRC_ERROR) + if ( (hspi->State != HAL_SPI_STATE_BUSY_RX) + || (SPI_ISCRCErrorValid(hspi) == SPI_VALID_CRC_ERROR) ) { SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_CRC); /* Reset CRC Calculation */ SPI_RESET_CRC(hspi); - } + } else { __HAL_SPI_CLEAR_CRCERRFLAG(hspi); } } -#endif /* USE_SPI_CRC */ - - if(hspi->ErrorCode != HAL_SPI_ERROR_NONE) - { - HAL_SPI_ErrorCallback(hspi); - return; - } } - HAL_SPI_RxCpltCallback(hspi); -} -/** - * @brief DMA SPI transmit receive process complete callback. - * @param hdma: pointer to a DMA_HandleTypeDef structure that contains - * the configuration information for the specified DMA module. - * @retval None - */ -static void SPI_DMATransmitReceiveCplt(DMA_HandleTypeDef *hdma) -{ - SPI_HandleTypeDef* hspi = ( SPI_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; - uint32_t tickstart = 0U; -#if (USE_SPI_CRC != 0U) - __IO int16_t tmpreg = 0U; -#endif /* USE_SPI_CRC */ - /* Init tickstart for timeout management*/ - tickstart = HAL_GetTick(); + /* Disable RXNE interrupt */ + __HAL_SPI_DISABLE_IT(hspi, (SPI_IT_RXNE)); - if((hdma->Instance->CCR & DMA_CCR_CIRC) != DMA_CCR_CIRC) + /* if Transmit process is finished */ + if(__HAL_SPI_GET_IT_SOURCE(hspi, SPI_IT_TXE) == RESET) { -#if (USE_SPI_CRC != 0U) - /* CRC handling */ - if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) - { - /* Wait the CRC data */ - if(SPI_WaitFlagStateUntilTimeout(hspi, SPI_FLAG_RXNE, SET, SPI_DEFAULT_TIMEOUT, tickstart) != HAL_OK) - { - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_CRC); - } - /* Read CRC to Flush DR and RXNE flag */ - tmpreg = hspi->Instance->DR; - /* To avoid GCC warning */ - UNUSED(tmpreg); - } -#endif /* USE_SPI_CRC */ - /* Check the end of the transaction */ - if(SPI_CheckFlag_BSY(hspi, SPI_DEFAULT_TIMEOUT, tickstart) != HAL_OK) + /* Disable ERR interrupt */ + __HAL_SPI_DISABLE_IT(hspi, (SPI_IT_ERR)); + + if((hspi->Init.Mode == SPI_MODE_MASTER)&&((hspi->Init.Direction == SPI_DIRECTION_1LINE)||(hspi->Init.Direction == SPI_DIRECTION_2LINES_RXONLY))) { - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_FLAG); + /* Disable SPI peripheral */ + __HAL_SPI_DISABLE(hspi); } - - /* Disable Rx/Tx DMA Request */ - CLEAR_BIT(hspi->Instance->CR2, SPI_CR2_TXDMAEN | SPI_CR2_RXDMAEN); - - hspi->TxXferCount = 0U; - hspi->RxXferCount = 0U; - hspi->State = HAL_SPI_STATE_READY; - -#if (USE_SPI_CRC != 0U) - /* Check if CRC error occurred */ - if(__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_CRCERR) != RESET) + + /* Check if Errors has been detected during transfer */ + if(hspi->ErrorCode == HAL_SPI_ERROR_NONE) { - /* Check if CRC error is valid or not (workaround to be applied or not) */ - if (SPI_ISCRCErrorValid(hspi) == SPI_VALID_CRC_ERROR) + /* Check if we are in Rx or in Rx/Tx Mode */ + if(hspi->State == HAL_SPI_STATE_BUSY_TX_RX) { - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_CRC); - - /* Reset CRC Calculation */ - SPI_RESET_CRC(hspi); - } + /* Set state to READY before run the Callback Complete */ + hspi->State = HAL_SPI_STATE_READY; + HAL_SPI_TxRxCpltCallback(hspi); + } else { - __HAL_SPI_CLEAR_CRCERRFLAG(hspi); + /* Set state to READY before run the Callback Complete */ + hspi->State = HAL_SPI_STATE_READY; + HAL_SPI_RxCpltCallback(hspi); } } -#endif /* USE_SPI_CRC */ - - if(hspi->ErrorCode != HAL_SPI_ERROR_NONE) + else { + /* Set state to READY before run the Callback Complete */ + hspi->State = HAL_SPI_STATE_READY; + /* Call Error call back in case of Error */ HAL_SPI_ErrorCallback(hspi); - return; } } - HAL_SPI_TxRxCpltCallback(hspi); } /** - * @brief DMA SPI half transmit process complete callback. - * @param hdma: pointer to a DMA_HandleTypeDef structure that contains - * the configuration information for the specified DMA module. + * @brief Interrupt Handler to receive amount of data in 2Lines mode + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. * @retval None */ -static void SPI_DMAHalfTransmitCplt(DMA_HandleTypeDef *hdma) +static void SPI_2LinesRxISR(SPI_HandleTypeDef *hspi) { - SPI_HandleTypeDef* hspi = ( SPI_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + /* Receive data in 8 Bit mode */ + if(hspi->Init.DataSize == SPI_DATASIZE_8BIT) + { + (*hspi->pRxBuffPtr++) = hspi->Instance->DR; + } + /* Receive data in 16 Bit mode */ + else + { + *((uint16_t*)hspi->pRxBuffPtr) = hspi->Instance->DR; + hspi->pRxBuffPtr+=2; + } + hspi->RxXferCount--; - HAL_SPI_TxHalfCpltCallback(hspi); + if(hspi->RxXferCount==0) + { + SPI_RxCloseIRQHandler(hspi); + } } /** - * @brief DMA SPI half receive process complete callback - * @param hdma: pointer to a DMA_HandleTypeDef structure that contains - * the configuration information for the specified DMA module. + * @brief Interrupt Handler to receive amount of data in no-blocking mode + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. * @retval None */ -static void SPI_DMAHalfReceiveCplt(DMA_HandleTypeDef *hdma) +static void SPI_RxISR(SPI_HandleTypeDef *hspi) { - SPI_HandleTypeDef* hspi = ( SPI_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + /* Receive data in 8 Bit mode */ + if(hspi->Init.DataSize == SPI_DATASIZE_8BIT) + { + (*hspi->pRxBuffPtr++) = hspi->Instance->DR; + } + /* Receive data in 16 Bit mode */ + else + { + *((uint16_t*)hspi->pRxBuffPtr) = hspi->Instance->DR; + hspi->pRxBuffPtr+=2; + } + hspi->RxXferCount--; - HAL_SPI_RxHalfCpltCallback(hspi); + /* Enable CRC Transmission */ + if((hspi->RxXferCount == 1) && (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)) + { + /* Set CRC Next to calculate CRC on Rx side */ + SET_BIT(hspi->Instance->CR1, SPI_CR1_CRCNEXT); + } + + if(hspi->RxXferCount == 0) + { + SPI_RxCloseIRQHandler(hspi); + } } /** - * @brief DMA SPI half transmit receive process complete callback. + * @brief DMA SPI transmit process complete callback * @param hdma: pointer to a DMA_HandleTypeDef structure that contains - * the configuration information for the specified DMA module. + * the configuration information for the specified DMA module. * @retval None */ -static void SPI_DMAHalfTransmitReceiveCplt(DMA_HandleTypeDef *hdma) +static void SPI_DMATransmitCplt(DMA_HandleTypeDef *hdma) { SPI_HandleTypeDef* hspi = ( SPI_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; - HAL_SPI_TxRxHalfCpltCallback(hspi); + /* DMA Normal Mode */ + if((hdma->Instance->CCR & DMA_CIRCULAR) == 0) + { + /* Wait until TXE flag is set to send data */ + if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_TXE, RESET, SPI_TIMEOUT_VALUE) != HAL_OK) + { + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_FLAG); + } + + /* Disable Tx DMA Request */ + CLEAR_BIT(hspi->Instance->CR2, SPI_CR2_TXDMAEN); + + /* Wait until Busy flag is reset before disabling SPI */ + if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_BSY, SET, SPI_TIMEOUT_VALUE) != HAL_OK) + { + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_FLAG); + } + + hspi->TxXferCount = 0; + hspi->State = HAL_SPI_STATE_READY; + } + + /* Clear OVERUN flag in 2 Lines communication mode because received is not read */ + if(hspi->Init.Direction == SPI_DIRECTION_2LINES) + { + __HAL_SPI_CLEAR_OVRFLAG(hspi); + } + + /* Check if Errors has been detected during transfer */ + if(hspi->ErrorCode != HAL_SPI_ERROR_NONE) + { + HAL_SPI_ErrorCallback(hspi); + } + else + { + HAL_SPI_TxCpltCallback(hspi); + } } /** - * @brief DMA SPI communication error callback. + * @brief DMA SPI receive process complete callback * @param hdma: pointer to a DMA_HandleTypeDef structure that contains - * the configuration information for the specified DMA module. + * the configuration information for the specified DMA module. * @retval None */ -static void SPI_DMAError(DMA_HandleTypeDef *hdma) -{ - SPI_HandleTypeDef* hspi = (SPI_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; - -/* Stop the disable DMA transfer on SPI side */ - CLEAR_BIT(hspi->Instance->CR2, SPI_CR2_TXDMAEN | SPI_CR2_RXDMAEN); - - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_DMA); - hspi->State = HAL_SPI_STATE_READY; - HAL_SPI_ErrorCallback(hspi); -} - -/** - * @brief DMA SPI communication abort callback, when initiated by HAL services on Error - * (To be called at end of DMA Abort procedure following error occurrence). - * @param hdma DMA handle. - * @retval None - */ -static void SPI_DMAAbortOnError(DMA_HandleTypeDef *hdma) +static void SPI_DMAReceiveCplt(DMA_HandleTypeDef *hdma) { + __IO uint16_t tmpreg = 0; SPI_HandleTypeDef* hspi = ( SPI_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; - hspi->RxXferCount = 0U; - hspi->TxXferCount = 0U; - - HAL_SPI_ErrorCallback(hspi); -} - -/** - * @brief DMA SPI Tx communication abort callback, when initiated by user - * (To be called at end of DMA Tx Abort procedure following user abort request). - * @note When this callback is executed, User Abort complete call back is called only if no - * Abort still ongoing for Rx DMA Handle. - * @param hdma DMA handle. - * @retval None - */ -static void SPI_DMATxAbortCallback(DMA_HandleTypeDef *hdma) -{ - __IO uint32_t count = SPI_DEFAULT_TIMEOUT * (SystemCoreClock / 24U / 1000U); - SPI_HandleTypeDef* hspi = ( SPI_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; - - hspi->hdmatx->XferAbortCallback = NULL; - - /* Disable Tx DMA Request */ - CLEAR_BIT(hspi->Instance->CR2, SPI_CR2_TXDMAEN ); - - /* Wait until TXE flag is set */ - do - { - if(count-- == 0U) - { - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_FLAG); - break; - } - } - while((hspi->Instance->SR & SPI_FLAG_TXE) == RESET); - /* Check if an Abort process is still ongoing */ - if(hspi->hdmarx != NULL) + /* DMA Normal mode */ + if((hdma->Instance->CCR & DMA_CIRCULAR) == 0) { - if(hspi->hdmarx->XferAbortCallback != NULL) - { - return; - } - } - - /* No Abort process still ongoing : All DMA channels are aborted, call user Abort Complete callback */ - hspi->RxXferCount = 0U; - hspi->TxXferCount = 0U; - - /* Reset errorCode */ - hspi->ErrorCode = HAL_SPI_ERROR_NONE; - - /* Restore hspi->State to Ready */ - hspi->State = HAL_SPI_STATE_READY; + /* Disable Rx DMA Request */ + CLEAR_BIT(hspi->Instance->CR2, SPI_CR2_RXDMAEN); - /* Call user Abort complete callback */ - HAL_SPI_AbortCpltCallback(hspi); -} + /* Disable Tx DMA Request (done by default to handle the case Master RX direction 2 lines) */ + CLEAR_BIT(hspi->Instance->CR2, SPI_CR2_TXDMAEN); -/** - * @brief DMA SPI Rx communication abort callback, when initiated by user - * (To be called at end of DMA Rx Abort procedure following user abort request). - * @note When this callback is executed, User Abort complete call back is called only if no - * Abort still ongoing for Tx DMA Handle. - * @param hdma DMA handle. - * @retval None - */ -static void SPI_DMARxAbortCallback(DMA_HandleTypeDef *hdma) -{ - SPI_HandleTypeDef* hspi = ( SPI_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + /* CRC Calculation handling */ + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) + { + /* Wait until RXNE flag is set (CRC ready) */ + if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, RESET, SPI_TIMEOUT_VALUE) != HAL_OK) + { + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_FLAG); + } - /* Disable SPI Peripheral */ - __HAL_SPI_DISABLE(hspi); + /* Read CRC */ + tmpreg = hspi->Instance->DR; + UNUSED(tmpreg); - hspi->hdmarx->XferAbortCallback = NULL; + /* Wait until RXNE flag is reset */ + if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, SET, SPI_TIMEOUT_VALUE) != HAL_OK) + { + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_FLAG); + } - /* Disable Rx DMA Request */ - CLEAR_BIT(hspi->Instance->CR2, SPI_CR2_RXDMAEN); + /* Check if CRC error occurred */ + if(__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_CRCERR) != RESET) + { + /* Check if CRC error is valid or not (workaround to be applied or not) */ + if (SPI_ISCRCErrorValid(hspi) == SPI_VALID_CRC_ERROR) + { + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_CRC); + + /* Reset CRC Calculation */ + SPI_RESET_CRC(hspi); + } + __HAL_SPI_CLEAR_CRCERRFLAG(hspi); + } + } - /* Check if an Abort process is still ongoing */ - if(hspi->hdmatx != NULL) - { - if(hspi->hdmatx->XferAbortCallback != NULL) + if((hspi->Init.Mode == SPI_MODE_MASTER)&&((hspi->Init.Direction == SPI_DIRECTION_1LINE)||(hspi->Init.Direction == SPI_DIRECTION_2LINES_RXONLY))) { - return; + /* Disable SPI peripheral */ + __HAL_SPI_DISABLE(hspi); } - } - - /* No Abort process still ongoing : All DMA channels are aborted, call user Abort Complete callback */ - hspi->RxXferCount = 0U; - hspi->TxXferCount = 0U; - - /* Reset errorCode */ - hspi->ErrorCode = HAL_SPI_ERROR_NONE; - - /* Clear the Error flags in the SR register */ - __HAL_SPI_CLEAR_OVRFLAG(hspi); - /* Restore hspi->State to Ready */ - hspi->State = HAL_SPI_STATE_READY; - - /* Call user Abort complete callback */ - HAL_SPI_AbortCpltCallback(hspi); -} - -/** - * @brief Rx 8-bit handler for Transmit and Receive in Interrupt mode. - * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. - * @retval None - */ -static void SPI_2linesRxISR_8BIT(struct __SPI_HandleTypeDef *hspi) -{ - /* Receive data in 8bit mode */ - *hspi->pRxBuffPtr++ = *((__IO uint8_t *)&hspi->Instance->DR); - hspi->RxXferCount--; + hspi->RxXferCount = 0; + hspi->State = HAL_SPI_STATE_READY; - /* check end of the reception */ - if(hspi->RxXferCount == 0U) - { -#if (USE_SPI_CRC != 0U) - if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) + /* Check if Errors has been detected during transfer */ + if(hspi->ErrorCode != HAL_SPI_ERROR_NONE) { - hspi->RxISR = SPI_2linesRxISR_8BITCRC; - return; + HAL_SPI_ErrorCallback(hspi); } -#endif /* USE_SPI_CRC */ - - /* Disable RXNE interrupt */ - __HAL_SPI_DISABLE_IT(hspi, (SPI_IT_RXNE | SPI_IT_ERR)); - - if(hspi->TxXferCount == 0U) + else { - SPI_CloseRxTx_ISR(hspi); + HAL_SPI_RxCpltCallback(hspi); } } -} - -#if (USE_SPI_CRC != 0U) -/** - * @brief Rx 8-bit handler for Transmit and Receive in Interrupt mode. - * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. - * @retval None - */ -static void SPI_2linesRxISR_8BITCRC(struct __SPI_HandleTypeDef *hspi) -{ - __IO uint8_t tmpreg = 0U; - - /* Read data register to flush CRC */ - tmpreg = *((__IO uint8_t *)&hspi->Instance->DR); - - /* To avoid GCC warning */ - - UNUSED(tmpreg); - - /* Disable RXNE interrupt */ - __HAL_SPI_DISABLE_IT(hspi, (SPI_IT_RXNE | SPI_IT_ERR)); - - if(hspi->TxXferCount == 0U) + else { - SPI_CloseRxTx_ISR(hspi); + HAL_SPI_RxCpltCallback(hspi); } } -#endif /* USE_SPI_CRC */ /** - * @brief Tx 8-bit handler for Transmit and Receive in Interrupt mode. - * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. + * @brief DMA SPI transmit receive process complete callback + * @param hdma: pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. * @retval None */ -static void SPI_2linesTxISR_8BIT(struct __SPI_HandleTypeDef *hspi) +static void SPI_DMATransmitReceiveCplt(DMA_HandleTypeDef *hdma) { - *(__IO uint8_t *)&hspi->Instance->DR = (*hspi->pTxBuffPtr++); - hspi->TxXferCount--; + __IO uint16_t tmpreg = 0; + + SPI_HandleTypeDef* hspi = ( SPI_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; - /* check the end of the transmission */ - if(hspi->TxXferCount == 0U) + if((hdma->Instance->CCR & DMA_CIRCULAR) == 0) { -#if (USE_SPI_CRC != 0U) + /* CRC Calculation handling */ if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) { - SET_BIT(hspi->Instance->CR1, SPI_CR1_CRCNEXT); - __HAL_SPI_DISABLE_IT(hspi, SPI_IT_TXE); - return; - } -#endif /* USE_SPI_CRC */ - - /* Disable TXE interrupt */ - __HAL_SPI_DISABLE_IT(hspi, SPI_IT_TXE); + /* Check if CRC is done on going (RXNE flag set) */ + if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, SET, SPI_TIMEOUT_VALUE) == HAL_OK) + { + /* Wait until RXNE flag is set to send data */ + if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, RESET, SPI_TIMEOUT_VALUE) != HAL_OK) + { + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_FLAG); + } + } + /* Read CRC */ + tmpreg = hspi->Instance->DR; + UNUSED(tmpreg); - if(hspi->RxXferCount == 0U) - { - SPI_CloseRxTx_ISR(hspi); + /* Check if CRC error occurred */ + if(__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_CRCERR) != RESET) + { + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_CRC); + __HAL_SPI_CLEAR_CRCERRFLAG(hspi); + } } - } -} -/** - * @brief Rx 16-bit handler for Transmit and Receive in Interrupt mode. - * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. - * @retval None - */ -static void SPI_2linesRxISR_16BIT(struct __SPI_HandleTypeDef *hspi) -{ - /* Receive data in 16 Bit mode */ - *((uint16_t*)hspi->pRxBuffPtr) = hspi->Instance->DR; - hspi->pRxBuffPtr += sizeof(uint16_t); - hspi->RxXferCount--; - - if(hspi->RxXferCount == 0U) - { -#if (USE_SPI_CRC != 0U) - if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) + /* Wait until TXE flag is set to send data */ + if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_TXE, RESET, SPI_TIMEOUT_VALUE) != HAL_OK) { - hspi->RxISR = SPI_2linesRxISR_16BITCRC; - return; + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_FLAG); } -#endif /* USE_SPI_CRC */ - - /* Disable RXNE interrupt */ - __HAL_SPI_DISABLE_IT(hspi, SPI_IT_RXNE); + + /* Disable Tx DMA Request */ + CLEAR_BIT(hspi->Instance->CR2, SPI_CR2_TXDMAEN); - if(hspi->TxXferCount == 0U) + /* Wait until Busy flag is reset before disabling SPI */ + if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_BSY, SET, SPI_TIMEOUT_VALUE) != HAL_OK) { - SPI_CloseRxTx_ISR(hspi); + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_FLAG); } - } -} - -#if (USE_SPI_CRC != 0U) -/** - * @brief Manage the CRC 16-bit receive for Transmit and Receive in Interrupt mode. - * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. - * @retval None - */ -static void SPI_2linesRxISR_16BITCRC(struct __SPI_HandleTypeDef *hspi) -{ - /* Receive data in 16 Bit mode */ - __IO uint16_t tmpreg = 0U; - - /* Read data register to flush CRC */ - tmpreg = hspi->Instance->DR; - - /* To avoid GCC warning */ - UNUSED(tmpreg); - /* Disable RXNE interrupt */ - __HAL_SPI_DISABLE_IT(hspi, SPI_IT_RXNE); + /* Disable Rx DMA Request */ + CLEAR_BIT(hspi->Instance->CR2, SPI_CR2_RXDMAEN); - SPI_CloseRxTx_ISR(hspi); -} -#endif /* USE_SPI_CRC */ + hspi->TxXferCount = 0; + hspi->RxXferCount = 0; -/** - * @brief Tx 16-bit handler for Transmit and Receive in Interrupt mode. - * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. - * @retval None - */ -static void SPI_2linesTxISR_16BIT(struct __SPI_HandleTypeDef *hspi) -{ - /* Transmit data in 16 Bit mode */ - hspi->Instance->DR = *((uint16_t *)hspi->pTxBuffPtr); - hspi->pTxBuffPtr += sizeof(uint16_t); - hspi->TxXferCount--; + hspi->State = HAL_SPI_STATE_READY; - /* Enable CRC Transmission */ - if(hspi->TxXferCount == 0U) - { -#if (USE_SPI_CRC != 0U) - if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) + /* Check if Errors has been detected during transfer */ + if(hspi->ErrorCode != HAL_SPI_ERROR_NONE) { - SET_BIT(hspi->Instance->CR1, SPI_CR1_CRCNEXT); - __HAL_SPI_DISABLE_IT(hspi, SPI_IT_TXE); - return; + HAL_SPI_ErrorCallback(hspi); } -#endif /* USE_SPI_CRC */ - - /* Disable TXE interrupt */ - __HAL_SPI_DISABLE_IT(hspi, SPI_IT_TXE); - - if(hspi->RxXferCount == 0U) + else { - SPI_CloseRxTx_ISR(hspi); + HAL_SPI_TxRxCpltCallback(hspi); } } -} - -#if (USE_SPI_CRC != 0U) -/** - * @brief Manage the CRC 8-bit receive in Interrupt context. - * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. - * @retval None - */ -static void SPI_RxISR_8BITCRC(struct __SPI_HandleTypeDef *hspi) -{ - __IO uint8_t tmpreg = 0U; - - /* Read data register to flush CRC */ - tmpreg = *((__IO uint8_t*)&hspi->Instance->DR); - - /* To avoid GCC warning */ - UNUSED(tmpreg); - - SPI_CloseRx_ISR(hspi); -} -#endif /* USE_SPI_CRC */ - -/** - * @brief Manage the receive 8-bit in Interrupt context. - * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. - * @retval None - */ -static void SPI_RxISR_8BIT(struct __SPI_HandleTypeDef *hspi) -{ - *hspi->pRxBuffPtr++ = (*(__IO uint8_t *)&hspi->Instance->DR); - hspi->RxXferCount--; - -#if (USE_SPI_CRC != 0U) - /* Enable CRC Transmission */ - if((hspi->RxXferCount == 1U) && (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)) - { - SET_BIT(hspi->Instance->CR1, SPI_CR1_CRCNEXT); - } -#endif /* USE_SPI_CRC */ - - if(hspi->RxXferCount == 0U) + else { -#if (USE_SPI_CRC != 0U) - if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) - { - hspi->RxISR = SPI_RxISR_8BITCRC; - return; - } -#endif /* USE_SPI_CRC */ - SPI_CloseRx_ISR(hspi); + HAL_SPI_TxRxCpltCallback(hspi); } } -#if (USE_SPI_CRC != 0U) /** - * @brief Manage the CRC 16-bit receive in Interrupt context. - * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. + * @brief DMA SPI half transmit process complete callback + * @param hdma: pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. * @retval None */ -static void SPI_RxISR_16BITCRC(struct __SPI_HandleTypeDef *hspi) +static void SPI_DMAHalfTransmitCplt(DMA_HandleTypeDef *hdma) { - __IO uint16_t tmpreg = 0U; - - /* Read data register to flush CRC */ - tmpreg = hspi->Instance->DR; - - /* To avoid GCC warning */ - UNUSED(tmpreg); - - /* Disable RXNE and ERR interrupt */ - __HAL_SPI_DISABLE_IT(hspi, (SPI_IT_RXNE | SPI_IT_ERR)); + SPI_HandleTypeDef* hspi = ( SPI_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; - SPI_CloseRx_ISR(hspi); + HAL_SPI_TxHalfCpltCallback(hspi); } -#endif /* USE_SPI_CRC */ /** - * @brief Manage the 16-bit receive in Interrupt context. - * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. + * @brief DMA SPI half receive process complete callback + * @param hdma: pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. * @retval None */ -static void SPI_RxISR_16BIT(struct __SPI_HandleTypeDef *hspi) +static void SPI_DMAHalfReceiveCplt(DMA_HandleTypeDef *hdma) { - *((uint16_t *)hspi->pRxBuffPtr) = hspi->Instance->DR; - hspi->pRxBuffPtr += sizeof(uint16_t); - hspi->RxXferCount--; - -#if (USE_SPI_CRC != 0U) - /* Enable CRC Transmission */ - if((hspi->RxXferCount == 1U) && (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)) - { - SET_BIT(hspi->Instance->CR1, SPI_CR1_CRCNEXT); - } -#endif /* USE_SPI_CRC */ + SPI_HandleTypeDef* hspi = ( SPI_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; - if(hspi->RxXferCount == 0U) - { -#if (USE_SPI_CRC != 0U) - if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) - { - hspi->RxISR = SPI_RxISR_16BITCRC; - return; - } -#endif /* USE_SPI_CRC */ - SPI_CloseRx_ISR(hspi); - } + HAL_SPI_RxHalfCpltCallback(hspi); } /** - * @brief Handle the data 8-bit transmit in Interrupt mode. - * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. + * @brief DMA SPI Half transmit receive process complete callback + * @param hdma: pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. * @retval None */ -static void SPI_TxISR_8BIT(struct __SPI_HandleTypeDef *hspi) +static void SPI_DMAHalfTransmitReceiveCplt(DMA_HandleTypeDef *hdma) { - *(__IO uint8_t *)&hspi->Instance->DR = (*hspi->pTxBuffPtr++); - hspi->TxXferCount--; + SPI_HandleTypeDef* hspi = ( SPI_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; - if(hspi->TxXferCount == 0U) - { -#if (USE_SPI_CRC != 0U) - if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) - { - /* Enable CRC Transmission */ - SET_BIT(hspi->Instance->CR1, SPI_CR1_CRCNEXT); - } -#endif /* USE_SPI_CRC */ - SPI_CloseTx_ISR(hspi); - } + HAL_SPI_TxRxHalfCpltCallback(hspi); } /** - * @brief Handle the data 16-bit transmit in Interrupt mode. - * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. + * @brief DMA SPI communication error callback + * @param hdma: pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. * @retval None */ -static void SPI_TxISR_16BIT(struct __SPI_HandleTypeDef *hspi) +static void SPI_DMAError(DMA_HandleTypeDef *hdma) { - /* Transmit data in 16 Bit mode */ - hspi->Instance->DR = *((uint16_t *)hspi->pTxBuffPtr); - hspi->pTxBuffPtr += sizeof(uint16_t); - hspi->TxXferCount--; - - if(hspi->TxXferCount == 0U) - { -#if (USE_SPI_CRC != 0U) - if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) - { - /* Enable CRC Transmission */ - SET_BIT(hspi->Instance->CR1, SPI_CR1_CRCNEXT); - } -#endif /* USE_SPI_CRC */ - SPI_CloseTx_ISR(hspi); - } + SPI_HandleTypeDef* hspi = (SPI_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + hspi->TxXferCount = 0; + hspi->RxXferCount = 0; + hspi->State= HAL_SPI_STATE_READY; + SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_DMA); + HAL_SPI_ErrorCallback(hspi); } /** - * @brief Handle SPI Communication Timeout. - * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. - * @param Flag: SPI flag to check - * @param State: flag state to check - * @param Timeout: Timeout duration - * @param Tickstart: tick start value + * @brief This function handles SPI Communication Timeout. + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @param Flag: SPI flag to check + * @param Status: Flag status to check: RESET or set + * @param Timeout: Timeout duration * @retval HAL status */ -static HAL_StatusTypeDef SPI_WaitFlagStateUntilTimeout(SPI_HandleTypeDef *hspi, uint32_t Flag, uint32_t State, uint32_t Timeout, uint32_t Tickstart) +static HAL_StatusTypeDef SPI_WaitOnFlagUntilTimeout(SPI_HandleTypeDef *hspi, uint32_t Flag, FlagStatus Status, uint32_t Timeout) { - while((((hspi->Instance->SR & Flag) == (Flag)) ? SET : RESET) != State) + uint32_t tickstart = 0; + + /* Get tick */ + tickstart = HAL_GetTick(); + + /* Wait until flag is set */ + if(Status == RESET) { - if(Timeout != HAL_MAX_DELAY) + while(__HAL_SPI_GET_FLAG(hspi, Flag) == RESET) { - if((Timeout == 0U) || ((HAL_GetTick()-Tickstart) >= Timeout)) + if(Timeout != HAL_MAX_DELAY) { - /* Disable the SPI and reset the CRC: the CRC value should be cleared - on both master and slave sides in order to resynchronize the master - and slave for their respective CRC calculation */ + if((Timeout == 0) || ((HAL_GetTick() - tickstart ) > Timeout)) + { + /* Disable the SPI and reset the CRC: the CRC value should be cleared + on both master and slave sides in order to resynchronize the master + and slave for their respective CRC calculation */ - /* Disable TXE, RXNE and ERR interrupts for the interrupt process */ - __HAL_SPI_DISABLE_IT(hspi, (SPI_IT_TXE | SPI_IT_RXNE | SPI_IT_ERR)); + /* Disable TXE, RXNE and ERR interrupts for the interrupt process */ + __HAL_SPI_DISABLE_IT(hspi, (SPI_IT_TXE | SPI_IT_RXNE | SPI_IT_ERR)); - if((hspi->Init.Mode == SPI_MODE_MASTER)&&((hspi->Init.Direction == SPI_DIRECTION_1LINE)||(hspi->Init.Direction == SPI_DIRECTION_2LINES_RXONLY))) - { /* Disable SPI peripheral */ __HAL_SPI_DISABLE(hspi); - } - /* Reset CRC Calculation */ - if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) - { - SPI_RESET_CRC(hspi); - } + /* Reset CRC Calculation */ + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) + { + SPI_RESET_CRC(hspi); + } - hspi->State= HAL_SPI_STATE_READY; + hspi->State= HAL_SPI_STATE_READY; - /* Process Unlocked */ - __HAL_UNLOCK(hspi); + /* Process Unlocked */ + __HAL_UNLOCK(hspi); - return HAL_TIMEOUT; + return HAL_TIMEOUT; + } } } } - - return HAL_OK; -} -/** - * @brief Handle to check BSY flag before start a new transaction. - * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. - * @param Timeout: Timeout duration - * @param Tickstart: tick start value - * @retval HAL status - */ -static HAL_StatusTypeDef SPI_CheckFlag_BSY(SPI_HandleTypeDef *hspi, uint32_t Timeout, uint32_t Tickstart) -{ - /* Control the BSY flag */ - if(SPI_WaitFlagStateUntilTimeout(hspi, SPI_FLAG_BSY, RESET, Timeout, Tickstart) != HAL_OK) - { - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_FLAG); - return HAL_TIMEOUT; - } - return HAL_OK; -} - -/** - * @brief Handle the end of the RXTX transaction. - * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. - * @retval None - */ -static void SPI_CloseRxTx_ISR(SPI_HandleTypeDef *hspi) -{ - uint32_t tickstart = 0U; - __IO uint32_t count = SPI_DEFAULT_TIMEOUT * (SystemCoreClock / 24U / 1000U); - /* Init tickstart for timeout managment*/ - tickstart = HAL_GetTick(); - - /* Disable ERR interrupt */ - __HAL_SPI_DISABLE_IT(hspi, SPI_IT_ERR); - - /* Wait until TXE flag is set */ - do - { - if(count-- == 0U) - { - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_FLAG); - break; - } - } - while((hspi->Instance->SR & SPI_FLAG_TXE) == RESET); - - /* Check the end of the transaction */ - if(SPI_CheckFlag_BSY(hspi, SPI_DEFAULT_TIMEOUT, tickstart)!=HAL_OK) - { - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_FLAG); - } - - /* Clear overrun flag in 2 Lines communication mode because received is not read */ - if(hspi->Init.Direction == SPI_DIRECTION_2LINES) - { - __HAL_SPI_CLEAR_OVRFLAG(hspi); - } - -#if (USE_SPI_CRC != 0U) - /* Check if CRC error occurred */ - if(__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_CRCERR) != RESET) - { - /* Check if CRC error is valid or not (workaround to be applied or not) */ - if (SPI_ISCRCErrorValid(hspi) == SPI_VALID_CRC_ERROR) - { - hspi->State = HAL_SPI_STATE_READY; - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_CRC); - - /* Reset CRC Calculation */ - SPI_RESET_CRC(hspi); - - HAL_SPI_ErrorCallback(hspi); - } - else - { - __HAL_SPI_CLEAR_CRCERRFLAG(hspi); - } - } else { -#endif /* USE_SPI_CRC */ - if(hspi->ErrorCode == HAL_SPI_ERROR_NONE) + while(__HAL_SPI_GET_FLAG(hspi, Flag) != RESET) { - if(hspi->State == HAL_SPI_STATE_BUSY_RX) + if(Timeout != HAL_MAX_DELAY) { - hspi->State = HAL_SPI_STATE_READY; - HAL_SPI_RxCpltCallback(hspi); - } - else - { - hspi->State = HAL_SPI_STATE_READY; - HAL_SPI_TxRxCpltCallback(hspi); - } - } - else - { - hspi->State = HAL_SPI_STATE_READY; - HAL_SPI_ErrorCallback(hspi); - } -#if (USE_SPI_CRC != 0U) - } -#endif /* USE_SPI_CRC */ -} + if((Timeout == 0) || ((HAL_GetTick() - tickstart ) > Timeout)) + { + /* Disable the SPI and reset the CRC: the CRC value should be cleared + on both master and slave sides in order to resynchronize the master + and slave for their respective CRC calculation */ -/** - * @brief Handle the end of the RX transaction. - * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. - * @retval None - */ -static void SPI_CloseRx_ISR(SPI_HandleTypeDef *hspi) -{ - /* Disable RXNE and ERR interrupt */ - __HAL_SPI_DISABLE_IT(hspi, (SPI_IT_RXNE | SPI_IT_ERR)); + /* Disable TXE, RXNE and ERR interrupts for the interrupt process */ + __HAL_SPI_DISABLE_IT(hspi, (SPI_IT_TXE | SPI_IT_RXNE | SPI_IT_ERR)); - /* Check the end of the transaction */ - if((hspi->Init.Mode == SPI_MODE_MASTER)&&((hspi->Init.Direction == SPI_DIRECTION_1LINE)||(hspi->Init.Direction == SPI_DIRECTION_2LINES_RXONLY))) - { - /* Disable SPI peripheral */ - __HAL_SPI_DISABLE(hspi); - } + /* Disable SPI peripheral */ + __HAL_SPI_DISABLE(hspi); - /* Clear overrun flag in 2 Lines communication mode because received is not read */ - if(hspi->Init.Direction == SPI_DIRECTION_2LINES) - { - __HAL_SPI_CLEAR_OVRFLAG(hspi); - } - hspi->State = HAL_SPI_STATE_READY; + /* Reset CRC Calculation */ + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) + { + SPI_RESET_CRC(hspi); + } -#if (USE_SPI_CRC != 0U) - /* Check if CRC error occurred */ - if(__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_CRCERR) != RESET) - { - /* Check if CRC error is valid or not (workaround to be applied or not) */ - if (SPI_ISCRCErrorValid(hspi) == SPI_VALID_CRC_ERROR) - { - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_CRC); + hspi->State= HAL_SPI_STATE_READY; - /* Reset CRC Calculation */ - SPI_RESET_CRC(hspi); + /* Process Unlocked */ + __HAL_UNLOCK(hspi); - HAL_SPI_ErrorCallback(hspi); - } - else - { - __HAL_SPI_CLEAR_CRCERRFLAG(hspi); - } - } - else - { -#endif /* USE_SPI_CRC */ - if(hspi->ErrorCode == HAL_SPI_ERROR_NONE) - { - HAL_SPI_RxCpltCallback(hspi); - } - else - { - HAL_SPI_ErrorCallback(hspi); + return HAL_TIMEOUT; + } } -#if (USE_SPI_CRC != 0U) - } -#endif /* USE_SPI_CRC */ -} - -/** - * @brief Handle the end of the TX transaction. - * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. - * @retval None - */ -static void SPI_CloseTx_ISR(SPI_HandleTypeDef *hspi) -{ - uint32_t tickstart = 0U; - __IO uint32_t count = SPI_DEFAULT_TIMEOUT * (SystemCoreClock / 24U / 1000U); - - /* Init tickstart for timeout management*/ - tickstart = HAL_GetTick(); - - /* Wait until TXE flag is set */ - do - { - if(count-- == 0U) - { - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_FLAG); - break; } } - while((hspi->Instance->SR & SPI_FLAG_TXE) == RESET); - - /* Disable TXE and ERR interrupt */ - __HAL_SPI_DISABLE_IT(hspi, (SPI_IT_TXE | SPI_IT_ERR)); - - /* Check Busy flag */ - if(SPI_CheckFlag_BSY(hspi, SPI_DEFAULT_TIMEOUT, tickstart) != HAL_OK) - { - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_FLAG); - } - - /* Clear overrun flag in 2 Lines communication mode because received is not read */ - if(hspi->Init.Direction == SPI_DIRECTION_2LINES) - { - __HAL_SPI_CLEAR_OVRFLAG(hspi); - } - - hspi->State = HAL_SPI_STATE_READY; - if(hspi->ErrorCode != HAL_SPI_ERROR_NONE) - { - HAL_SPI_ErrorCallback(hspi); - } - else - { - HAL_SPI_TxCpltCallback(hspi); - } + return HAL_OK; } /** * @} */ -/** - * @brief Handle abort a Tx or Rx transaction. - * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. - * @retval None - */ -static void SPI_AbortRx_ISR(SPI_HandleTypeDef *hspi) -{ - __IO uint32_t tmpreg = 0U; - __IO uint32_t count = SPI_DEFAULT_TIMEOUT * (SystemCoreClock / 24U / 1000U); - - /* Wait until TXE flag is set */ - do - { - if(count-- == 0U) - { - SET_BIT(hspi->ErrorCode, HAL_SPI_ERROR_FLAG); - break; - } - } - while((hspi->Instance->SR & SPI_FLAG_TXE) == RESET); - - /* Disable SPI Peripheral */ - __HAL_SPI_DISABLE(hspi); - - /* Disable TXEIE, RXNEIE and ERRIE(mode fault event, overrun error, TI frame error) interrupts */ - CLEAR_BIT(hspi->Instance->CR2, (SPI_CR2_TXEIE | SPI_CR2_RXNEIE | SPI_CR2_ERRIE)); - - /* Flush DR Register */ - tmpreg = (*(__IO uint32_t *)&hspi->Instance->DR); - - /* To avoid GCC warning */ - UNUSED(tmpreg); -} - -/** - * @brief Handle abort a Tx or Rx transaction. - * @param hspi: pointer to a SPI_HandleTypeDef structure that contains - * the configuration information for SPI module. - * @retval None +/** @addtogroup SPI_Private_Functions + * @{ */ -static void SPI_AbortTx_ISR(SPI_HandleTypeDef *hspi) -{ - /* Disable TXEIE, RXNEIE and ERRIE(mode fault event, overrun error, TI frame error) interrupts */ - CLEAR_BIT(hspi->Instance->CR2, (SPI_CR2_TXEIE | SPI_CR2_RXNEIE | SPI_CR2_ERRIE)); - - /* Disable SPI Peripheral */ - __HAL_SPI_DISABLE(hspi); -} /** * @brief Checks if encountered CRC error could be corresponding to wrongly detected errors @@ -3245,16 +2391,14 @@ static void SPI_AbortTx_ISR(SPI_HandleTypeDef *hspi) */ __weak uint8_t SPI_ISCRCErrorValid(SPI_HandleTypeDef *hspi) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(hspi); - return (SPI_VALID_CRC_ERROR); } /** * @} */ -#endif /* HAL_SPI_MODULE_ENABLED */ + +#endif /* HAL_SPI_MODULE_ENABLED */ /** * @} */ diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_spi.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_spi.h index d152d74affd..1bc59de0b60 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_spi.h +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_spi.h @@ -2,13 +2,13 @@ ****************************************************************************** * @file stm32f1xx_hal_spi.h * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief Header file of SPI HAL module. ****************************************************************************** * @attention * - *

© COPYRIGHT(c) 2017 STMicroelectronics

+ *

© COPYRIGHT(c) 2016 STMicroelectronics

* * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: @@ -33,7 +33,7 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** - */ + */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F1xx_HAL_SPI_H @@ -59,19 +59,19 @@ * @{ */ -/** - * @brief SPI Configuration Structure definition +/** + * @brief SPI Configuration Structure definition */ typedef struct { uint32_t Mode; /*!< Specifies the SPI operating mode. - This parameter can be a value of @ref SPI_Mode */ + This parameter can be a value of @ref SPI_mode */ uint32_t Direction; /*!< Specifies the SPI Directional mode state. - This parameter can be a value of @ref SPI_Direction */ + This parameter can be a value of @ref SPI_Direction_mode */ uint32_t DataSize; /*!< Specifies the SPI data size. - This parameter can be a value of @ref SPI_Data_Size */ + This parameter can be a value of @ref SPI_data_size */ uint32_t CLKPolarity; /*!< Specifies the serial clock steady state. This parameter can be a value of @ref SPI_Clock_Polarity */ @@ -87,7 +87,7 @@ typedef struct used to configure the transmit and receive SCK clock. This parameter can be a value of @ref SPI_BaudRate_Prescaler @note The communication clock is derived from the master - clock. The slave clock does not need to be set. */ + clock. The slave clock does not need to be set */ uint32_t FirstBit; /*!< Specifies whether data transfers start from MSB or LSB bit. This parameter can be a value of @ref SPI_MSB_LSB_transmission */ @@ -100,6 +100,7 @@ typedef struct uint32_t CRCPolynomial; /*!< Specifies the polynomial used for the CRC calculation. This parameter must be a number between Min_Data = 0 and Max_Data = 65535 */ + }SPI_InitTypeDef; /** @@ -107,16 +108,18 @@ typedef struct */ typedef enum { - HAL_SPI_STATE_RESET = 0x00U, /*!< Peripheral not Initialized */ - HAL_SPI_STATE_READY = 0x01U, /*!< Peripheral Initialized and ready for use */ - HAL_SPI_STATE_BUSY = 0x02U, /*!< an internal process is ongoing */ - HAL_SPI_STATE_BUSY_TX = 0x03U, /*!< Data Transmission process is ongoing */ - HAL_SPI_STATE_BUSY_RX = 0x04U, /*!< Data Reception process is ongoing */ - HAL_SPI_STATE_BUSY_TX_RX = 0x05U, /*!< Data Transmission and Reception process is ongoing */ - HAL_SPI_STATE_ERROR = 0x06U /*!< SPI error state */ + HAL_SPI_STATE_RESET = 0x00, /*!< SPI not yet initialized or disabled */ + HAL_SPI_STATE_READY = 0x01, /*!< SPI initialized and ready for use */ + HAL_SPI_STATE_BUSY = 0x02, /*!< SPI process is ongoing */ + HAL_SPI_STATE_BUSY_TX = 0x12, /*!< Data Transmission process is ongoing */ + HAL_SPI_STATE_BUSY_RX = 0x22, /*!< Data Reception process is ongoing */ + HAL_SPI_STATE_BUSY_TX_RX = 0x32, /*!< Data Transmission and Reception process is ongoing */ + HAL_SPI_STATE_ERROR = 0x03 /*!< SPI error state */ + }HAL_SPI_StateTypeDef; -/** + +/** * @brief SPI handle Structure definition */ typedef struct __SPI_HandleTypeDef @@ -127,88 +130,95 @@ typedef struct __SPI_HandleTypeDef uint8_t *pTxBuffPtr; /*!< Pointer to SPI Tx transfer Buffer */ - uint16_t TxXferSize; /*!< SPI Tx Transfer size */ - - __IO uint16_t TxXferCount; /*!< SPI Tx Transfer Counter */ + uint16_t TxXferSize; /*!< SPI Tx transfer size */ + + uint16_t TxXferCount; /*!< SPI Tx Transfer Counter */ uint8_t *pRxBuffPtr; /*!< Pointer to SPI Rx transfer Buffer */ - uint16_t RxXferSize; /*!< SPI Rx Transfer size */ + uint16_t RxXferSize; /*!< SPI Rx transfer size */ - __IO uint16_t RxXferCount; /*!< SPI Rx Transfer Counter */ + uint16_t RxXferCount; /*!< SPI Rx Transfer Counter */ - void (*RxISR)(struct __SPI_HandleTypeDef * hspi); /*!< function pointer on Rx ISR */ + DMA_HandleTypeDef *hdmatx; /*!< SPI Tx DMA handle parameters */ - void (*TxISR)(struct __SPI_HandleTypeDef * hspi); /*!< function pointer on Tx ISR */ + DMA_HandleTypeDef *hdmarx; /*!< SPI Rx DMA handle parameters */ - DMA_HandleTypeDef *hdmatx; /*!< SPI Tx DMA Handle parameters */ + void (*RxISR)(struct __SPI_HandleTypeDef * hspi); /*!< function pointer on Rx ISR */ - DMA_HandleTypeDef *hdmarx; /*!< SPI Rx DMA Handle parameters */ + void (*TxISR)(struct __SPI_HandleTypeDef * hspi); /*!< function pointer on Tx ISR */ - HAL_LockTypeDef Lock; /*!< Locking object */ + HAL_LockTypeDef Lock; /*!< SPI locking object */ __IO HAL_SPI_StateTypeDef State; /*!< SPI communication state */ - __IO uint32_t ErrorCode; /*!< SPI Error code */ + __IO uint32_t ErrorCode; /*!< SPI Error code */ }SPI_HandleTypeDef; - /** * @} */ + /* Exported constants --------------------------------------------------------*/ + /** @defgroup SPI_Exported_Constants SPI Exported Constants * @{ */ -/** @defgroup SPI_Error_Code SPI Error Code +/** @defgroup SPI_Error_Codes SPI Error Codes * @{ - */ -#define HAL_SPI_ERROR_NONE 0x00000000U /*!< No error */ -#define HAL_SPI_ERROR_MODF 0x00000001U /*!< MODF error */ -#define HAL_SPI_ERROR_CRC 0x00000002U /*!< CRC error */ -#define HAL_SPI_ERROR_OVR 0x00000004U /*!< OVR error */ -#define HAL_SPI_ERROR_FRE 0x00000008U /*!< FRE error */ -#define HAL_SPI_ERROR_DMA 0x00000010U /*!< DMA transfer error */ -#define HAL_SPI_ERROR_FLAG 0x00000020U /*!< Flag: RXNE,TXE, BSY */ + */ +#define HAL_SPI_ERROR_NONE ((uint32_t)0x00) /*!< No error */ +#define HAL_SPI_ERROR_MODF ((uint32_t)0x01) /*!< MODF error */ +#define HAL_SPI_ERROR_CRC ((uint32_t)0x02) /*!< CRC error */ +#define HAL_SPI_ERROR_OVR ((uint32_t)0x04) /*!< OVR error */ +#define HAL_SPI_ERROR_DMA ((uint32_t)0x08) /*!< DMA transfer error */ +#define HAL_SPI_ERROR_FLAG ((uint32_t)0x10) /*!< Flag: RXNE,TXE, BSY */ /** * @} */ -/** @defgroup SPI_Mode SPI Mode + + + +/** @defgroup SPI_mode SPI mode * @{ */ -#define SPI_MODE_SLAVE 0x00000000U +#define SPI_MODE_SLAVE ((uint32_t)0x00000000) #define SPI_MODE_MASTER (SPI_CR1_MSTR | SPI_CR1_SSI) + /** * @} */ -/** @defgroup SPI_Direction SPI Direction Mode +/** @defgroup SPI_Direction_mode SPI Direction mode * @{ */ -#define SPI_DIRECTION_2LINES 0x00000000U +#define SPI_DIRECTION_2LINES ((uint32_t)0x00000000) #define SPI_DIRECTION_2LINES_RXONLY SPI_CR1_RXONLY #define SPI_DIRECTION_1LINE SPI_CR1_BIDIMODE + /** * @} */ -/** @defgroup SPI_Data_Size SPI Data Size +/** @defgroup SPI_data_size SPI data size * @{ */ -#define SPI_DATASIZE_8BIT 0x00000000U +#define SPI_DATASIZE_8BIT ((uint32_t)0x00000000) #define SPI_DATASIZE_16BIT SPI_CR1_DFF + /** * @} - */ + */ /** @defgroup SPI_Clock_Polarity SPI Clock Polarity * @{ */ -#define SPI_POLARITY_LOW 0x00000000U +#define SPI_POLARITY_LOW ((uint32_t)0x00000000) #define SPI_POLARITY_HIGH SPI_CR1_CPOL + /** * @} */ @@ -216,65 +226,71 @@ typedef struct __SPI_HandleTypeDef /** @defgroup SPI_Clock_Phase SPI Clock Phase * @{ */ -#define SPI_PHASE_1EDGE 0x00000000U +#define SPI_PHASE_1EDGE ((uint32_t)0x00000000) #define SPI_PHASE_2EDGE SPI_CR1_CPHA + /** * @} */ -/** @defgroup SPI_Slave_Select_management SPI Slave Select Management +/** @defgroup SPI_Slave_Select_management SPI Slave Select management * @{ */ #define SPI_NSS_SOFT SPI_CR1_SSM -#define SPI_NSS_HARD_INPUT 0x00000000U +#define SPI_NSS_HARD_INPUT ((uint32_t)0x00000000) #define SPI_NSS_HARD_OUTPUT ((uint32_t)(SPI_CR2_SSOE << 16)) + /** * @} - */ + */ /** @defgroup SPI_BaudRate_Prescaler SPI BaudRate Prescaler * @{ */ -#define SPI_BAUDRATEPRESCALER_2 0x00000000U -#define SPI_BAUDRATEPRESCALER_4 SPI_CR1_BR_0 -#define SPI_BAUDRATEPRESCALER_8 SPI_CR1_BR_1 -#define SPI_BAUDRATEPRESCALER_16 (uint32_t)(SPI_CR1_BR_1 | SPI_CR1_BR_0) -#define SPI_BAUDRATEPRESCALER_32 SPI_CR1_BR_2 -#define SPI_BAUDRATEPRESCALER_64 (uint32_t)(SPI_CR1_BR_2 | SPI_CR1_BR_0) -#define SPI_BAUDRATEPRESCALER_128 (uint32_t)(SPI_CR1_BR_2 | SPI_CR1_BR_1) -#define SPI_BAUDRATEPRESCALER_256 (uint32_t)(SPI_CR1_BR_2 | SPI_CR1_BR_1 | SPI_CR1_BR_0) +#define SPI_BAUDRATEPRESCALER_2 ((uint32_t)0x00000000) +#define SPI_BAUDRATEPRESCALER_4 ((uint32_t)SPI_CR1_BR_0) +#define SPI_BAUDRATEPRESCALER_8 ((uint32_t)SPI_CR1_BR_1) +#define SPI_BAUDRATEPRESCALER_16 ((uint32_t)SPI_CR1_BR_1 | SPI_CR1_BR_0) +#define SPI_BAUDRATEPRESCALER_32 ((uint32_t)SPI_CR1_BR_2) +#define SPI_BAUDRATEPRESCALER_64 ((uint32_t)SPI_CR1_BR_2 | SPI_CR1_BR_0) +#define SPI_BAUDRATEPRESCALER_128 ((uint32_t)SPI_CR1_BR_2 | SPI_CR1_BR_1) +#define SPI_BAUDRATEPRESCALER_256 ((uint32_t)SPI_CR1_BR_2 | SPI_CR1_BR_1 | SPI_CR1_BR_0) /** * @} - */ + */ -/** @defgroup SPI_MSB_LSB_transmission SPI MSB LSB Transmission +/** @defgroup SPI_MSB_LSB_transmission SPI MSB LSB transmission * @{ */ -#define SPI_FIRSTBIT_MSB 0x00000000U +#define SPI_FIRSTBIT_MSB ((uint32_t)0x00000000) #define SPI_FIRSTBIT_LSB SPI_CR1_LSBFIRST + /** * @} */ -/** @defgroup SPI_TI_mode SPI TI Mode +/** @defgroup SPI_TI_mode SPI TI mode disable + * @brief SPI TI Mode not supported for STM32F1xx family * @{ */ -#define SPI_TIMODE_DISABLE 0x00000000U +#define SPI_TIMODE_DISABLE ((uint32_t)0x00000000) + /** * @} */ - + /** @defgroup SPI_CRC_Calculation SPI CRC Calculation * @{ */ -#define SPI_CRCCALCULATION_DISABLE 0x00000000U -#define SPI_CRCCALCULATION_ENABLE SPI_CR1_CRCEN +#define SPI_CRCCALCULATION_DISABLE ((uint32_t)0x00000000) +#define SPI_CRCCALCULATION_ENABLE SPI_CR1_CRCEN + /** * @} */ -/** @defgroup SPI_Interrupt_definition SPI Interrupt Definition +/** @defgroup SPI_Interrupt_configuration_definition SPI Interrupt configuration definition * @{ */ #define SPI_IT_TXE SPI_CR2_TXEIE @@ -284,15 +300,16 @@ typedef struct __SPI_HandleTypeDef * @} */ -/** @defgroup SPI_Flags_definition SPI Flags Definition +/** @defgroup SPI_Flag_definition SPI Flag definition * @{ */ -#define SPI_FLAG_RXNE SPI_SR_RXNE /* SPI status flag: Rx buffer not empty flag */ -#define SPI_FLAG_TXE SPI_SR_TXE /* SPI status flag: Tx buffer empty flag */ -#define SPI_FLAG_BSY SPI_SR_BSY /* SPI status flag: Busy flag */ -#define SPI_FLAG_CRCERR SPI_SR_CRCERR /* SPI Error flag: CRC error flag */ -#define SPI_FLAG_MODF SPI_SR_MODF /* SPI Error flag: Mode fault flag */ -#define SPI_FLAG_OVR SPI_SR_OVR /* SPI Error flag: Overrun flag */ +#define SPI_FLAG_RXNE SPI_SR_RXNE +#define SPI_FLAG_TXE SPI_SR_TXE +#define SPI_FLAG_CRCERR SPI_SR_CRCERR +#define SPI_FLAG_MODF SPI_SR_MODF +#define SPI_FLAG_OVR SPI_SR_OVR +#define SPI_FLAG_BSY SPI_SR_BSY + /** * @} */ @@ -301,13 +318,25 @@ typedef struct __SPI_HandleTypeDef * @} */ + +/* Private constants ---------------------------------------------------------*/ +/** @defgroup SPI_Private_Constants SPI Private Constants + * @{ + */ +#define SPI_INVALID_CRC_ERROR 0 /* CRC error wrongly detected */ +#define SPI_VALID_CRC_ERROR 1 /* CRC error is true */ +/** + * @} + */ + + /* Exported macro ------------------------------------------------------------*/ /** @defgroup SPI_Exported_Macros SPI Exported Macros * @{ */ -/** @brief Reset SPI handle state. - * @param __HANDLE__: specifies the SPI Handle. +/** @brief Reset SPI handle state + * @param __HANDLE__: specifies the SPI handle. * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. * @retval None */ @@ -323,7 +352,7 @@ typedef struct __SPI_HandleTypeDef * @arg SPI_IT_ERR: Error interrupt enable * @retval None */ -#define __HAL_SPI_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR2 |= (__INTERRUPT__)) +#define __HAL_SPI_ENABLE_IT(__HANDLE__, __INTERRUPT__) SET_BIT((__HANDLE__)->Instance->CR2, (__INTERRUPT__)) /** @brief Disable the specified SPI interrupts. * @param __HANDLE__: specifies the SPI handle. @@ -335,10 +364,10 @@ typedef struct __SPI_HandleTypeDef * @arg SPI_IT_ERR: Error interrupt enable * @retval None */ -#define __HAL_SPI_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR2 &= (~(__INTERRUPT__))) +#define __HAL_SPI_DISABLE_IT(__HANDLE__, __INTERRUPT__) CLEAR_BIT((__HANDLE__)->Instance->CR2, (__INTERRUPT__)) -/** @brief Check whether the specified SPI interrupt source is enabled or not. - * @param __HANDLE__: specifies the SPI Handle. +/** @brief Check if the specified SPI interrupt source is enabled or disabled. + * @param __HANDLE__: specifies the SPI handle. * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. * @param __INTERRUPT__: specifies the SPI interrupt source to check. * This parameter can be one of the following values: @@ -350,7 +379,7 @@ typedef struct __SPI_HandleTypeDef #define __HAL_SPI_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->CR2 & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET) /** @brief Check whether the specified SPI flag is set or not. - * @param __HANDLE__: specifies the SPI Handle. + * @param __HANDLE__: specifies the SPI handle. * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: @@ -365,52 +394,191 @@ typedef struct __SPI_HandleTypeDef #define __HAL_SPI_GET_FLAG(__HANDLE__, __FLAG__) ((((__HANDLE__)->Instance->SR) & (__FLAG__)) == (__FLAG__)) /** @brief Clear the SPI CRCERR pending flag. - * @param __HANDLE__: specifies the SPI Handle. + * @param __HANDLE__: specifies the SPI handle. * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. * @retval None */ -#define __HAL_SPI_CLEAR_CRCERRFLAG(__HANDLE__) ((__HANDLE__)->Instance->SR = (uint16_t)(~SPI_FLAG_CRCERR)) +#define __HAL_SPI_CLEAR_CRCERRFLAG(__HANDLE__) ((__HANDLE__)->Instance->SR = ~(SPI_FLAG_CRCERR)) /** @brief Clear the SPI MODF pending flag. - * @param __HANDLE__: specifies the SPI Handle. - * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. + * @param __HANDLE__: specifies the SPI handle. + * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. * @retval None */ -#define __HAL_SPI_CLEAR_MODFFLAG(__HANDLE__) \ -do{ \ - __IO uint32_t tmpreg_modf = 0x00U; \ - tmpreg_modf = (__HANDLE__)->Instance->SR; \ - (__HANDLE__)->Instance->CR1 &= (~SPI_CR1_SPE); \ - UNUSED(tmpreg_modf); \ - } while(0U) +#define __HAL_SPI_CLEAR_MODFFLAG(__HANDLE__) \ +do{ \ + __IO uint32_t tmpreg; \ + tmpreg = (__HANDLE__)->Instance->SR; \ + tmpreg = CLEAR_BIT((__HANDLE__)->Instance->CR1, SPI_CR1_SPE); \ + UNUSED(tmpreg); \ +}while(0) /** @brief Clear the SPI OVR pending flag. + * @param __HANDLE__: specifies the SPI handle. + * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. + * @retval None + */ +#define __HAL_SPI_CLEAR_OVRFLAG(__HANDLE__) \ +do{ \ + __IO uint32_t tmpreg; \ + tmpreg = (__HANDLE__)->Instance->DR; \ + tmpreg = (__HANDLE__)->Instance->SR; \ + UNUSED(tmpreg); \ +}while(0) + + +/** @brief Enables the SPI. * @param __HANDLE__: specifies the SPI Handle. * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. * @retval None + */ +#define __HAL_SPI_ENABLE(__HANDLE__) SET_BIT((__HANDLE__)->Instance->CR1, SPI_CR1_SPE) + +/** @brief Disables the SPI. + * @param __HANDLE__: specifies the SPI Handle. + * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. + * @retval None + */ +#define __HAL_SPI_DISABLE(__HANDLE__) CLEAR_BIT((__HANDLE__)->Instance->CR1, SPI_CR1_SPE) + +/** + * @} + */ + + +/* Private macros -----------------------------------------------------------*/ +/** @defgroup SPI_Private_Macros SPI Private Macros + * @{ + */ + +/** @brief Checks if SPI Mode parameter is in allowed range. + * @param __MODE__: specifies the SPI Mode. + * This parameter can be a value of @ref SPI_mode + * @retval None + */ +#define IS_SPI_MODE(__MODE__) (((__MODE__) == SPI_MODE_SLAVE) || ((__MODE__) == SPI_MODE_MASTER)) + +/** @brief Checks if SPI Direction Mode parameter is in allowed range. + * @param __MODE__: specifies the SPI Direction Mode. + * This parameter can be a value of @ref SPI_Direction_mode + * @retval None + */ +#define IS_SPI_DIRECTION_MODE(__MODE__) (((__MODE__) == SPI_DIRECTION_2LINES) || \ + ((__MODE__) == SPI_DIRECTION_2LINES_RXONLY) || \ + ((__MODE__) == SPI_DIRECTION_1LINE)) + +/** @brief Checks if SPI Direction Mode parameter is 1 or 2 lines. + * @param __MODE__: specifies the SPI Direction Mode. + * @retval None + */ +#define IS_SPI_DIRECTION_2LINES_OR_1LINE(__MODE__) (((__MODE__) == SPI_DIRECTION_2LINES) || \ + ((__MODE__) == SPI_DIRECTION_1LINE)) + +/** @brief Checks if SPI Direction Mode parameter is 2 lines. + * @param __MODE__: specifies the SPI Direction Mode. + * @retval None + */ +#define IS_SPI_DIRECTION_2LINES(__MODE__) ((__MODE__) == SPI_DIRECTION_2LINES) + +/** @brief Checks if SPI Data Size parameter is in allowed range. + * @param __DATASIZE__: specifies the SPI Data Size. + * This parameter can be a value of @ref SPI_data_size + * @retval None + */ +#define IS_SPI_DATASIZE(__DATASIZE__) (((__DATASIZE__) == SPI_DATASIZE_16BIT) || \ + ((__DATASIZE__) == SPI_DATASIZE_8BIT)) + +/** @brief Checks if SPI Serial clock steady state parameter is in allowed range. + * @param __CPOL__: specifies the SPI serial clock steady state. + * This parameter can be a value of @ref SPI_Clock_Polarity + * @retval None + */ +#define IS_SPI_CPOL(__CPOL__) (((__CPOL__) == SPI_POLARITY_LOW) || \ + ((__CPOL__) == SPI_POLARITY_HIGH)) + +/** @brief Checks if SPI Clock Phase parameter is in allowed range. + * @param __CPHA__: specifies the SPI Clock Phase. + * This parameter can be a value of @ref SPI_Clock_Phase + * @retval None + */ +#define IS_SPI_CPHA(__CPHA__) (((__CPHA__) == SPI_PHASE_1EDGE) || \ + ((__CPHA__) == SPI_PHASE_2EDGE)) + +/** @brief Checks if SPI Slave select parameter is in allowed range. + * @param __NSS__: specifies the SPI Slave Slelect management parameter. + * This parameter can be a value of @ref SPI_Slave_Select_management + * @retval None + */ +#define IS_SPI_NSS(__NSS__) (((__NSS__) == SPI_NSS_SOFT) || \ + ((__NSS__) == SPI_NSS_HARD_INPUT) || \ + ((__NSS__) == SPI_NSS_HARD_OUTPUT)) + +/** @brief Checks if SPI Baudrate prescaler parameter is in allowed range. + * @param __PRESCALER__: specifies the SPI Baudrate prescaler. + * This parameter can be a value of @ref SPI_BaudRate_Prescaler + * @retval None + */ +#define IS_SPI_BAUDRATE_PRESCALER(__PRESCALER__) (((__PRESCALER__) == SPI_BAUDRATEPRESCALER_2) || \ + ((__PRESCALER__) == SPI_BAUDRATEPRESCALER_4) || \ + ((__PRESCALER__) == SPI_BAUDRATEPRESCALER_8) || \ + ((__PRESCALER__) == SPI_BAUDRATEPRESCALER_16) || \ + ((__PRESCALER__) == SPI_BAUDRATEPRESCALER_32) || \ + ((__PRESCALER__) == SPI_BAUDRATEPRESCALER_64) || \ + ((__PRESCALER__) == SPI_BAUDRATEPRESCALER_128) || \ + ((__PRESCALER__) == SPI_BAUDRATEPRESCALER_256)) + +/** @brief Checks if SPI MSB LSB transmission parameter is in allowed range. + * @param __BIT__: specifies the SPI MSB LSB transmission (whether data transfer starts from MSB or LSB bit). + * This parameter can be a value of @ref SPI_MSB_LSB_transmission + * @retval None + */ +#define IS_SPI_FIRST_BIT(__BIT__) (((__BIT__) == SPI_FIRSTBIT_MSB) || \ + ((__BIT__) == SPI_FIRSTBIT_LSB)) + +/** @brief Checks if SPI TI mode parameter is in allowed range. + * @param __MODE__: specifies the SPI TI mode. + * This parameter can be a value of @ref SPI_TI_mode + * @retval None + */ +#define IS_SPI_TIMODE(__MODE__) ((__MODE__) == SPI_TIMODE_DISABLE) + +/** @brief Checks if SPI CRC calculation enabled state is in allowed range. + * @param __CALCULATION__: specifies the SPI CRC calculation enable state. + * This parameter can be a value of @ref SPI_CRC_Calculation + * @retval None */ -#define __HAL_SPI_CLEAR_OVRFLAG(__HANDLE__) \ -do{ \ - __IO uint32_t tmpreg_ovr = 0x00U; \ - tmpreg_ovr = (__HANDLE__)->Instance->DR; \ - tmpreg_ovr = (__HANDLE__)->Instance->SR; \ - UNUSED(tmpreg_ovr); \ - } while(0U) +#define IS_SPI_CRC_CALCULATION(__CALCULATION__) (((__CALCULATION__) == SPI_CRCCALCULATION_DISABLE) || \ + ((__CALCULATION__) == SPI_CRCCALCULATION_ENABLE)) +/** @brief Checks if SPI polynomial value to be used for the CRC calculation, is in allowed range. + * @param __POLYNOMIAL__: specifies the SPI polynomial value to be used for the CRC calculation. + * This parameter must be a number between Min_Data = 0 and Max_Data = 65535 + * @retval None + */ +#define IS_SPI_CRC_POLYNOMIAL(__POLYNOMIAL__) (((__POLYNOMIAL__) >= 0x1) && ((__POLYNOMIAL__) <= 0xFFFF)) -/** @brief Enable the SPI peripheral. +/** @brief Sets the SPI transmit-only mode. * @param __HANDLE__: specifies the SPI Handle. * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. * @retval None */ -#define __HAL_SPI_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 |= SPI_CR1_SPE) +#define SPI_1LINE_TX(__HANDLE__) SET_BIT((__HANDLE__)->Instance->CR1, SPI_CR1_BIDIOE) + +/** @brief Sets the SPI receive-only mode. + * @param __HANDLE__: specifies the SPI Handle. + * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. + * @retval None + */ +#define SPI_1LINE_RX(__HANDLE__) CLEAR_BIT((__HANDLE__)->Instance->CR1, SPI_CR1_BIDIOE) -/** @brief Disable the SPI peripheral. +/** @brief Resets the CRC calculation of the SPI. * @param __HANDLE__: specifies the SPI Handle. * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. * @retval None */ -#define __HAL_SPI_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 &= (~SPI_CR1_SPE)) +#define SPI_RESET_CRC(__HANDLE__) do{CLEAR_BIT((__HANDLE__)->Instance->CR1, SPI_CR1_CRCEN);\ + SET_BIT((__HANDLE__)->Instance->CR1, SPI_CR1_CRCEN);}while(0) + /** * @} */ @@ -420,10 +588,10 @@ do{ \ * @{ */ +/* Initialization/de-initialization functions **********************************/ /** @addtogroup SPI_Exported_Functions_Group1 * @{ */ -/* Initialization/de-initialization functions **********************************/ HAL_StatusTypeDef HAL_SPI_Init(SPI_HandleTypeDef *hspi); HAL_StatusTypeDef HAL_SPI_DeInit (SPI_HandleTypeDef *hspi); void HAL_SPI_MspInit(SPI_HandleTypeDef *hspi); @@ -432,10 +600,10 @@ void HAL_SPI_MspDeInit(SPI_HandleTypeDef *hspi); * @} */ +/* I/O operation functions *****************************************************/ /** @addtogroup SPI_Exported_Functions_Group2 * @{ */ -/* I/O operation functions *****************************************************/ HAL_StatusTypeDef HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_SPI_Receive(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size, uint32_t Timeout); @@ -448,138 +616,55 @@ HAL_StatusTypeDef HAL_SPI_TransmitReceive_DMA(SPI_HandleTypeDef *hspi, uint8_t * HAL_StatusTypeDef HAL_SPI_DMAPause(SPI_HandleTypeDef *hspi); HAL_StatusTypeDef HAL_SPI_DMAResume(SPI_HandleTypeDef *hspi); HAL_StatusTypeDef HAL_SPI_DMAStop(SPI_HandleTypeDef *hspi); -/* Transfer Abort functions */ -HAL_StatusTypeDef HAL_SPI_Abort(SPI_HandleTypeDef *hspi); -HAL_StatusTypeDef HAL_SPI_Abort_IT(SPI_HandleTypeDef *hspi); void HAL_SPI_IRQHandler(SPI_HandleTypeDef *hspi); void HAL_SPI_TxCpltCallback(SPI_HandleTypeDef *hspi); void HAL_SPI_RxCpltCallback(SPI_HandleTypeDef *hspi); void HAL_SPI_TxRxCpltCallback(SPI_HandleTypeDef *hspi); +void HAL_SPI_ErrorCallback(SPI_HandleTypeDef *hspi); void HAL_SPI_TxHalfCpltCallback(SPI_HandleTypeDef *hspi); void HAL_SPI_RxHalfCpltCallback(SPI_HandleTypeDef *hspi); void HAL_SPI_TxRxHalfCpltCallback(SPI_HandleTypeDef *hspi); -void HAL_SPI_ErrorCallback(SPI_HandleTypeDef *hspi); -void HAL_SPI_AbortCpltCallback(SPI_HandleTypeDef *hspi); /** * @} */ + +/* Peripheral State and Control functions **************************************/ /** @addtogroup SPI_Exported_Functions_Group3 * @{ */ -/* Peripheral State and Error functions ***************************************/ HAL_SPI_StateTypeDef HAL_SPI_GetState(SPI_HandleTypeDef *hspi); -uint32_t HAL_SPI_GetError(SPI_HandleTypeDef *hspi); -/** - * @} - */ +uint32_t HAL_SPI_GetError(SPI_HandleTypeDef *hspi); /** * @} */ -/* Private types -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private constants ---------------------------------------------------------*/ -/** @defgroup SPI_Private_Constants SPI Private Constants - * @{ - */ -#define SPI_INVALID_CRC_ERROR 0U /* CRC error wrongly detected */ -#define SPI_VALID_CRC_ERROR 1U /* CRC error is true */ /** * @} */ -/* Private macros ------------------------------------------------------------*/ -/** @defgroup SPI_Private_Macros SPI Private Macros - * @{ - */ - -/** @brief Set the SPI transmit-only mode. - * @param __HANDLE__: specifies the SPI Handle. - * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. - * @retval None - */ -#define SPI_1LINE_TX(__HANDLE__) ((__HANDLE__)->Instance->CR1 |= SPI_CR1_BIDIOE) - -/** @brief Set the SPI receive-only mode. - * @param __HANDLE__: specifies the SPI Handle. - * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. - * @retval None - */ -#define SPI_1LINE_RX(__HANDLE__) ((__HANDLE__)->Instance->CR1 &= (~SPI_CR1_BIDIOE)) - -/** @brief Reset the CRC calculation of the SPI. - * @param __HANDLE__: specifies the SPI Handle. - * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. - * @retval None - */ -#define SPI_RESET_CRC(__HANDLE__) do{(__HANDLE__)->Instance->CR1 &= (uint16_t)(~SPI_CR1_CRCEN);\ - (__HANDLE__)->Instance->CR1 |= SPI_CR1_CRCEN;}while(0U) - -#define IS_SPI_MODE(MODE) (((MODE) == SPI_MODE_SLAVE) || \ - ((MODE) == SPI_MODE_MASTER)) - -#define IS_SPI_DIRECTION(MODE) (((MODE) == SPI_DIRECTION_2LINES) || \ - ((MODE) == SPI_DIRECTION_2LINES_RXONLY) || \ - ((MODE) == SPI_DIRECTION_1LINE)) - -#define IS_SPI_DIRECTION_2LINES(MODE) ((MODE) == SPI_DIRECTION_2LINES) - -#define IS_SPI_DIRECTION_2LINES_OR_1LINE(MODE) (((MODE) == SPI_DIRECTION_2LINES) || \ - ((MODE) == SPI_DIRECTION_1LINE)) - -#define IS_SPI_DATASIZE(DATASIZE) (((DATASIZE) == SPI_DATASIZE_16BIT) || \ - ((DATASIZE) == SPI_DATASIZE_8BIT)) - -#define IS_SPI_CPOL(CPOL) (((CPOL) == SPI_POLARITY_LOW) || \ - ((CPOL) == SPI_POLARITY_HIGH)) - -#define IS_SPI_CPHA(CPHA) (((CPHA) == SPI_PHASE_1EDGE) || \ - ((CPHA) == SPI_PHASE_2EDGE)) - -#define IS_SPI_NSS(NSS) (((NSS) == SPI_NSS_SOFT) || \ - ((NSS) == SPI_NSS_HARD_INPUT) || \ - ((NSS) == SPI_NSS_HARD_OUTPUT)) - -#define IS_SPI_BAUDRATE_PRESCALER(PRESCALER) (((PRESCALER) == SPI_BAUDRATEPRESCALER_2) || \ - ((PRESCALER) == SPI_BAUDRATEPRESCALER_4) || \ - ((PRESCALER) == SPI_BAUDRATEPRESCALER_8) || \ - ((PRESCALER) == SPI_BAUDRATEPRESCALER_16) || \ - ((PRESCALER) == SPI_BAUDRATEPRESCALER_32) || \ - ((PRESCALER) == SPI_BAUDRATEPRESCALER_64) || \ - ((PRESCALER) == SPI_BAUDRATEPRESCALER_128) || \ - ((PRESCALER) == SPI_BAUDRATEPRESCALER_256)) -#define IS_SPI_FIRST_BIT(BIT) (((BIT) == SPI_FIRSTBIT_MSB) || \ - ((BIT) == SPI_FIRSTBIT_LSB)) -#define IS_SPI_CRC_CALCULATION(CALCULATION) (((CALCULATION) == SPI_CRCCALCULATION_DISABLE) || \ - ((CALCULATION) == SPI_CRCCALCULATION_ENABLE)) - -#define IS_SPI_CRC_POLYNOMIAL(POLYNOMIAL) (((POLYNOMIAL) >= 0x01U) && ((POLYNOMIAL) <= 0xFFFFU)) - -/** - * @} - */ - -/* Private functions ---------------------------------------------------------*/ -/** @defgroup SPI_Private_Functions SPI Private Functions +/* Private functions --------------------------------------------------------*/ +/** @addtogroup SPI_Private_Functions * @{ */ uint8_t SPI_ISCRCErrorValid(SPI_HandleTypeDef *hspi); + /** * @} */ + /** * @} - */ + */ /** * @} */ - + #ifdef __cplusplus } #endif diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_spi_ex.c b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_spi_ex.c index 8ae2f75b434..7659fc4c87b 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_spi_ex.c +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_spi_ex.c @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_hal_spi_ex.c * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief Extended SPI HAL module driver. * * This file provides firmware functions to manage the following @@ -53,9 +53,8 @@ #ifdef HAL_SPI_MODULE_ENABLED /** @defgroup SPI_Private_Variables SPI Private Variables - * @{ - */ -#if (USE_SPI_CRC != 0U) + * @{ + */ /* Variable used to determine if device is impacted by implementation of workaround related to wrong CRC errors detection on SPI2. Conditions in which this workaround has to be applied, are: - STM32F101CDE/STM32F103CDE @@ -67,8 +66,7 @@ + Otherwise, one or more errors have been detected during the data transfer by CPU or DMA. If CRCERR is found reset, the complete data transfer is considered successful. */ -uint8_t uCRCErrorWorkaroundCheck = 0U; -#endif /* USE_SPI_CRC */ +uint8_t uCRCErrorWorkaroundCheck = 0; /** * @} */ @@ -86,7 +84,7 @@ uint8_t uCRCErrorWorkaroundCheck = 0U; */ /** @addtogroup SPI_Exported_Functions_Group1 - * + * * @{ */ @@ -108,23 +106,16 @@ HAL_StatusTypeDef HAL_SPI_Init(SPI_HandleTypeDef *hspi) /* Check the parameters */ assert_param(IS_SPI_ALL_INSTANCE(hspi->Instance)); assert_param(IS_SPI_MODE(hspi->Init.Mode)); - assert_param(IS_SPI_DIRECTION(hspi->Init.Direction)); + assert_param(IS_SPI_DIRECTION_MODE(hspi->Init.Direction)); assert_param(IS_SPI_DATASIZE(hspi->Init.DataSize)); assert_param(IS_SPI_CPOL(hspi->Init.CLKPolarity)); assert_param(IS_SPI_CPHA(hspi->Init.CLKPhase)); assert_param(IS_SPI_NSS(hspi->Init.NSS)); assert_param(IS_SPI_BAUDRATE_PRESCALER(hspi->Init.BaudRatePrescaler)); assert_param(IS_SPI_FIRST_BIT(hspi->Init.FirstBit)); - -#if (USE_SPI_CRC != 0U) + assert_param(IS_SPI_TIMODE(hspi->Init.TIMode)); assert_param(IS_SPI_CRC_CALCULATION(hspi->Init.CRCCalculation)); - if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) - { - assert_param(IS_SPI_CRC_POLYNOMIAL(hspi->Init.CRCPolynomial)); - } -#else - hspi->Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE; -#endif /* USE_SPI_CRC */ + assert_param(IS_SPI_CRC_POLYNOMIAL(hspi->Init.CRCPolynomial)); if(hspi->State == HAL_SPI_STATE_RESET) { @@ -145,18 +136,17 @@ HAL_StatusTypeDef HAL_SPI_Init(SPI_HandleTypeDef *hspi) hspi->Init.BaudRatePrescaler | hspi->Init.FirstBit | hspi->Init.CRCCalculation) ); /* Configure : NSS management */ - WRITE_REG(hspi->Instance->CR2, (((hspi->Init.NSS >> 16U) & SPI_CR2_SSOE) | hspi->Init.TIMode)); + WRITE_REG(hspi->Instance->CR2, (((hspi->Init.NSS >> 16) & SPI_CR2_SSOE) | hspi->Init.TIMode)); /*---------------------------- SPIx CRCPOLY Configuration ------------------*/ /* Configure : CRC Polynomial */ WRITE_REG(hspi->Instance->CRCPR, hspi->Init.CRCPolynomial); -#if defined(SPI_I2SCFGR_I2SMOD) +#if defined (STM32F101x6) || defined (STM32F101xB) || defined (STM32F101xE) || defined (STM32F101xG) || defined (STM32F102x6) || defined (STM32F102xB) || defined (STM32F103x6) || defined (STM32F103xB) || defined (STM32F103xE) || defined (STM32F103xG) || defined (STM32F105xC) || defined (STM32F107xC) /* Activate the SPI mode (Make sure that I2SMOD bit in I2SCFGR register is reset) */ CLEAR_BIT(hspi->Instance->I2SCFGR, SPI_I2SCFGR_I2SMOD); -#endif /* SPI_I2SCFGR_I2SMOD */ +#endif -#if (USE_SPI_CRC != 0U) #if defined (STM32F101xE) || defined (STM32F103xE) /* Check RevisionID value for identifying if Device is Rev Z (0x0001) in order to enable workaround for CRC errors wrongly detected */ @@ -164,11 +154,10 @@ HAL_StatusTypeDef HAL_SPI_Init(SPI_HandleTypeDef *hspi) Revision ID information is only available in Debug mode, so Workaround could not be implemented to distinguish Rev Z devices (issue present) from more recent version (issue fixed). So, in case of Revison Z F101 or F103 devices, below variable should be assigned to 1 */ - uCRCErrorWorkaroundCheck = 0U; + uCRCErrorWorkaroundCheck = 0; #else - uCRCErrorWorkaroundCheck = 0U; -#endif /* STM32F101xE || STM32F103xE */ -#endif /* USE_SPI_CRC */ + uCRCErrorWorkaroundCheck = 0; +#endif hspi->ErrorCode = HAL_SPI_ERROR_NONE; hspi->State = HAL_SPI_STATE_READY; @@ -187,7 +176,7 @@ HAL_StatusTypeDef HAL_SPI_Init(SPI_HandleTypeDef *hspi) /** @addtogroup SPI_Private_Functions * @{ */ -#if (USE_SPI_CRC != 0U) + /** * @brief Checks if encountered CRC error could be corresponding to wrongly detected errors * according to SPI instance, Device type, and revision ID. @@ -197,26 +186,21 @@ HAL_StatusTypeDef HAL_SPI_Init(SPI_HandleTypeDef *hspi) */ uint8_t SPI_ISCRCErrorValid(SPI_HandleTypeDef *hspi) { -#if defined(STM32F101xE) || defined(STM32F103xE) +#if defined (STM32F101xE) || defined (STM32F103xE) /* Check how to handle this CRC error (workaround to be applied or not) */ /* If CRC errors could be wrongly detected (issue 2.15.2 in STM32F10xxC/D/E silicon limitations ES (DocID14732 Rev 13) */ - if((uCRCErrorWorkaroundCheck != 0U) && (hspi->Instance == SPI2)) + if ( (uCRCErrorWorkaroundCheck != 0) && (hspi->Instance == SPI2) ) { - if(hspi->Instance->RXCRCR == 0U) + if (hspi->Instance->RXCRCR == 0) { return (SPI_INVALID_CRC_ERROR); } } return (SPI_VALID_CRC_ERROR); #else - /* Prevent unused argument(s) compilation warning */ - UNUSED(hspi); - return (SPI_VALID_CRC_ERROR); #endif } -#endif /* USE_SPI_CRC */ - /** * @} */ diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_sram.c b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_sram.c index 156faaf03a9..c94bf7a41ed 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_sram.c +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_sram.c @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_hal_sram.c * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief SRAM HAL module driver. * This file provides a generic firmware to drive SRAM memories * mounted as external device. @@ -291,7 +291,7 @@ HAL_StatusTypeDef HAL_SRAM_Read_8b(SRAM_HandleTypeDef *hsram, uint32_t *pAddress hsram->State = HAL_SRAM_STATE_BUSY; /* Read data from memory */ - for(; BufferSize != 0U; BufferSize--) + for(; BufferSize != 0; BufferSize--) { *pDstBuffer = *(__IO uint8_t *)psramaddress; pDstBuffer++; @@ -333,7 +333,7 @@ HAL_StatusTypeDef HAL_SRAM_Write_8b(SRAM_HandleTypeDef *hsram, uint32_t *pAddres hsram->State = HAL_SRAM_STATE_BUSY; /* Write data to memory */ - for(; BufferSize != 0U; BufferSize--) + for(; BufferSize != 0; BufferSize--) { *(__IO uint8_t *)psramaddress = *pSrcBuffer; pSrcBuffer++; @@ -369,7 +369,7 @@ HAL_StatusTypeDef HAL_SRAM_Read_16b(SRAM_HandleTypeDef *hsram, uint32_t *pAddres hsram->State = HAL_SRAM_STATE_BUSY; /* Read data from memory */ - for(; BufferSize != 0U; BufferSize--) + for(; BufferSize != 0; BufferSize--) { *pDstBuffer = *(__IO uint16_t *)psramaddress; pDstBuffer++; @@ -411,7 +411,7 @@ HAL_StatusTypeDef HAL_SRAM_Write_16b(SRAM_HandleTypeDef *hsram, uint32_t *pAddre hsram->State = HAL_SRAM_STATE_BUSY; /* Write data to memory */ - for(; BufferSize != 0U; BufferSize--) + for(; BufferSize != 0; BufferSize--) { *(__IO uint16_t *)psramaddress = *pSrcBuffer; pSrcBuffer++; @@ -445,7 +445,7 @@ HAL_StatusTypeDef HAL_SRAM_Read_32b(SRAM_HandleTypeDef *hsram, uint32_t *pAddres hsram->State = HAL_SRAM_STATE_BUSY; /* Read data from memory */ - for(; BufferSize != 0U; BufferSize--) + for(; BufferSize != 0; BufferSize--) { *pDstBuffer = *(__IO uint32_t *)pAddress; pDstBuffer++; @@ -485,7 +485,7 @@ HAL_StatusTypeDef HAL_SRAM_Write_32b(SRAM_HandleTypeDef *hsram, uint32_t *pAddre hsram->State = HAL_SRAM_STATE_BUSY; /* Write data to memory */ - for(; BufferSize != 0U; BufferSize--) + for(; BufferSize != 0; BufferSize--) { *(__IO uint32_t *)pAddress = *pSrcBuffer; pSrcBuffer++; diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_sram.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_sram.h index c096f1b9df2..ba2891aa6ec 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_sram.h +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_sram.h @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_hal_sram.h * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief Header file of SRAM HAL module. ****************************************************************************** * @attention @@ -66,11 +66,11 @@ */ typedef enum { - HAL_SRAM_STATE_RESET = 0x00U, /*!< SRAM not yet initialized or disabled */ - HAL_SRAM_STATE_READY = 0x01U, /*!< SRAM initialized and ready for use */ - HAL_SRAM_STATE_BUSY = 0x02U, /*!< SRAM internal process is ongoing */ - HAL_SRAM_STATE_ERROR = 0x03U, /*!< SRAM error state */ - HAL_SRAM_STATE_PROTECTED = 0x04U /*!< SRAM peripheral NORSRAM device write protected */ + HAL_SRAM_STATE_RESET = 0x00, /*!< SRAM not yet initialized or disabled */ + HAL_SRAM_STATE_READY = 0x01, /*!< SRAM initialized and ready for use */ + HAL_SRAM_STATE_BUSY = 0x02, /*!< SRAM internal process is ongoing */ + HAL_SRAM_STATE_ERROR = 0x03, /*!< SRAM error state */ + HAL_SRAM_STATE_PROTECTED = 0x04 /*!< SRAM peripheral NORSRAM device write protected */ }HAL_SRAM_StateTypeDef; diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_tim.c b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_tim.c index 3e6bd1bbe74..e47d6797ba5 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_tim.c +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_tim.c @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_hal_tim.c * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief TIM HAL module driver * This file provides firmware functions to manage the following * functionalities of the Timer (TIM) peripheral: @@ -215,7 +215,6 @@ HAL_StatusTypeDef HAL_TIM_Base_Init(TIM_HandleTypeDef *htim) assert_param(IS_TIM_INSTANCE(htim->Instance)); assert_param(IS_TIM_COUNTER_MODE(htim->Init.CounterMode)); assert_param(IS_TIM_CLOCKDIVISION_DIV(htim->Init.ClockDivision)); - assert_param(IS_TIM_AUTORELOAD_PRELOAD(htim->Init.AutoReloadPreload)); if(htim->State == HAL_TIM_STATE_RESET) { @@ -397,7 +396,7 @@ HAL_StatusTypeDef HAL_TIM_Base_Start_DMA(TIM_HandleTypeDef *htim, uint32_t *pDat } else if((htim->State == HAL_TIM_STATE_READY)) { - if((pData == 0U) && (Length > 0U)) + if((pData == 0 ) && (Length > 0)) { return HAL_ERROR; } @@ -491,7 +490,6 @@ HAL_StatusTypeDef HAL_TIM_OC_Init(TIM_HandleTypeDef* htim) assert_param(IS_TIM_INSTANCE(htim->Instance)); assert_param(IS_TIM_COUNTER_MODE(htim->Init.CounterMode)); assert_param(IS_TIM_CLOCKDIVISION_DIV(htim->Init.ClockDivision)); - assert_param(IS_TIM_AUTORELOAD_PRELOAD(htim->Init.AutoReloadPreload)); if(htim->State == HAL_TIM_STATE_RESET) { @@ -789,7 +787,7 @@ HAL_StatusTypeDef HAL_TIM_OC_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel } else if((htim->State == HAL_TIM_STATE_READY)) { - if(((uint32_t)pData == 0U) && (Length > 0U)) + if(((uint32_t)pData == 0 ) && (Length > 0)) { return HAL_ERROR; } @@ -996,7 +994,6 @@ HAL_StatusTypeDef HAL_TIM_PWM_Init(TIM_HandleTypeDef *htim) assert_param(IS_TIM_INSTANCE(htim->Instance)); assert_param(IS_TIM_COUNTER_MODE(htim->Init.CounterMode)); assert_param(IS_TIM_CLOCKDIVISION_DIV(htim->Init.ClockDivision)); - assert_param(IS_TIM_AUTORELOAD_PRELOAD(htim->Init.AutoReloadPreload)); if(htim->State == HAL_TIM_STATE_RESET) { @@ -1144,7 +1141,7 @@ HAL_StatusTypeDef HAL_TIM_PWM_Stop(TIM_HandleTypeDef *htim, uint32_t Channel) /** * @brief Starts the PWM signal generation in interrupt mode. * @param htim : TIM handle - * @param Channel : TIM Channel to be enabled + * @param Channel : TIM Channel to be disabled * This parameter can be one of the following values: * @arg TIM_CHANNEL_1: TIM Channel 1 selected * @arg TIM_CHANNEL_2: TIM Channel 2 selected @@ -1297,7 +1294,7 @@ HAL_StatusTypeDef HAL_TIM_PWM_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channe } else if((htim->State == HAL_TIM_STATE_READY)) { - if(((uint32_t)pData == 0U) && (Length > 0U)) + if(((uint32_t)pData == 0 ) && (Length > 0)) { return HAL_ERROR; } @@ -1504,7 +1501,6 @@ HAL_StatusTypeDef HAL_TIM_IC_Init(TIM_HandleTypeDef *htim) assert_param(IS_TIM_INSTANCE(htim->Instance)); assert_param(IS_TIM_COUNTER_MODE(htim->Init.CounterMode)); assert_param(IS_TIM_CLOCKDIVISION_DIV(htim->Init.ClockDivision)); - assert_param(IS_TIM_AUTORELOAD_PRELOAD(htim->Init.AutoReloadPreload)); if(htim->State == HAL_TIM_STATE_RESET) { @@ -1778,7 +1774,7 @@ HAL_StatusTypeDef HAL_TIM_IC_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel } else if((htim->State == HAL_TIM_STATE_READY)) { - if((pData == 0U) && (Length > 0U)) + if((pData == 0 ) && (Length > 0)) { return HAL_ERROR; } @@ -1978,7 +1974,6 @@ HAL_StatusTypeDef HAL_TIM_OnePulse_Init(TIM_HandleTypeDef *htim, uint32_t OnePul assert_param(IS_TIM_INSTANCE(htim->Instance)); assert_param(IS_TIM_COUNTER_MODE(htim->Init.CounterMode)); assert_param(IS_TIM_CLOCKDIVISION_DIV(htim->Init.ClockDivision)); - assert_param(IS_TIM_AUTORELOAD_PRELOAD(htim->Init.AutoReloadPreload)); assert_param(IS_TIM_OPM_MODE(OnePulseMode)); if(htim->State == HAL_TIM_STATE_RESET) @@ -2074,9 +2069,6 @@ __weak void HAL_TIM_OnePulse_MspDeInit(TIM_HandleTypeDef *htim) */ HAL_StatusTypeDef HAL_TIM_OnePulse_Start(TIM_HandleTypeDef *htim, uint32_t OutputChannel) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(OutputChannel); - /* Enable the Capture compare and the Input Capture channels (in the OPM Mode the two possible channels that can be used are TIM_CHANNEL_1 and TIM_CHANNEL_2) if TIM_CHANNEL_1 is used as output, the TIM_CHANNEL_2 will be used as input and @@ -2110,9 +2102,6 @@ HAL_StatusTypeDef HAL_TIM_OnePulse_Start(TIM_HandleTypeDef *htim, uint32_t Outpu */ HAL_StatusTypeDef HAL_TIM_OnePulse_Stop(TIM_HandleTypeDef *htim, uint32_t OutputChannel) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(OutputChannel); - /* Disable the Capture compare and the Input Capture channels (in the OPM Mode the two possible channels that can be used are TIM_CHANNEL_1 and TIM_CHANNEL_2) if TIM_CHANNEL_1 is used as output, the TIM_CHANNEL_2 will be used as input and @@ -2146,9 +2135,6 @@ HAL_StatusTypeDef HAL_TIM_OnePulse_Stop(TIM_HandleTypeDef *htim, uint32_t Output */ HAL_StatusTypeDef HAL_TIM_OnePulse_Start_IT(TIM_HandleTypeDef *htim, uint32_t OutputChannel) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(OutputChannel); - /* Enable the Capture compare and the Input Capture channels (in the OPM Mode the two possible channels that can be used are TIM_CHANNEL_1 and TIM_CHANNEL_2) if TIM_CHANNEL_1 is used as output, the TIM_CHANNEL_2 will be used as input and @@ -2188,9 +2174,6 @@ HAL_StatusTypeDef HAL_TIM_OnePulse_Start_IT(TIM_HandleTypeDef *htim, uint32_t Ou */ HAL_StatusTypeDef HAL_TIM_OnePulse_Stop_IT(TIM_HandleTypeDef *htim, uint32_t OutputChannel) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(OutputChannel); - /* Disable the TIM Capture/Compare 1 interrupt */ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC1); @@ -2251,9 +2234,9 @@ HAL_StatusTypeDef HAL_TIM_OnePulse_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Out */ HAL_StatusTypeDef HAL_TIM_Encoder_Init(TIM_HandleTypeDef *htim, TIM_Encoder_InitTypeDef* sConfig) { - uint32_t tmpsmcr = 0U; - uint32_t tmpccmr1 = 0U; - uint32_t tmpccer = 0U; + uint32_t tmpsmcr = 0; + uint32_t tmpccmr1 = 0; + uint32_t tmpccer = 0; /* Check the TIM handle allocation */ if(htim == NULL) @@ -2263,9 +2246,6 @@ HAL_StatusTypeDef HAL_TIM_Encoder_Init(TIM_HandleTypeDef *htim, TIM_Encoder_Ini /* Check the parameters */ assert_param(IS_TIM_CC2_INSTANCE(htim->Instance)); - assert_param(IS_TIM_COUNTER_MODE(htim->Init.CounterMode)); - assert_param(IS_TIM_CLOCKDIVISION_DIV(htim->Init.ClockDivision)); - assert_param(IS_TIM_AUTORELOAD_PRELOAD(htim->Init.AutoReloadPreload)); assert_param(IS_TIM_ENCODER_MODE(sConfig->EncoderMode)); assert_param(IS_TIM_IC_SELECTION(sConfig->IC1Selection)); assert_param(IS_TIM_IC_SELECTION(sConfig->IC2Selection)); @@ -2308,18 +2288,18 @@ HAL_StatusTypeDef HAL_TIM_Encoder_Init(TIM_HandleTypeDef *htim, TIM_Encoder_Ini /* Select the Capture Compare 1 and the Capture Compare 2 as input */ tmpccmr1 &= ~(TIM_CCMR1_CC1S | TIM_CCMR1_CC2S); - tmpccmr1 |= (sConfig->IC1Selection | (sConfig->IC2Selection << 8U)); + tmpccmr1 |= (sConfig->IC1Selection | (sConfig->IC2Selection << 8)); /* Set the the Capture Compare 1 and the Capture Compare 2 prescalers and filters */ tmpccmr1 &= ~(TIM_CCMR1_IC1PSC | TIM_CCMR1_IC2PSC); tmpccmr1 &= ~(TIM_CCMR1_IC1F | TIM_CCMR1_IC2F); - tmpccmr1 |= sConfig->IC1Prescaler | (sConfig->IC2Prescaler << 8U); - tmpccmr1 |= (sConfig->IC1Filter << 4U) | (sConfig->IC2Filter << 12U); + tmpccmr1 |= sConfig->IC1Prescaler | (sConfig->IC2Prescaler << 8); + tmpccmr1 |= (sConfig->IC1Filter << 4) | (sConfig->IC2Filter << 12); /* Set the TI1 and the TI2 Polarities */ tmpccer &= ~(TIM_CCER_CC1P | TIM_CCER_CC2P); tmpccer &= ~(TIM_CCER_CC1NP | TIM_CCER_CC2NP); - tmpccer |= sConfig->IC1Polarity | (sConfig->IC2Polarity << 4U); + tmpccer |= sConfig->IC1Polarity | (sConfig->IC2Polarity << 4); /* Write to TIMx SMCR */ htim->Instance->SMCR = tmpsmcr; @@ -2601,7 +2581,7 @@ HAL_StatusTypeDef HAL_TIM_Encoder_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Ch } else if((htim->State == HAL_TIM_STATE_READY)) { - if((((pData1 == 0U) || (pData2 == 0U) )) && (Length > 0U)) + if((((pData1 == 0) || (pData2 == 0) )) && (Length > 0)) { return HAL_ERROR; } @@ -2781,7 +2761,7 @@ void HAL_TIM_IRQHandler(TIM_HandleTypeDef *htim) htim->Channel = HAL_TIM_ACTIVE_CHANNEL_1; /* Input capture event */ - if((htim->Instance->CCMR1 & TIM_CCMR1_CC1S) != 0x00U) + if((htim->Instance->CCMR1 & TIM_CCMR1_CC1S) != 0x00) { HAL_TIM_IC_CaptureCallback(htim); } @@ -2803,7 +2783,7 @@ void HAL_TIM_IRQHandler(TIM_HandleTypeDef *htim) __HAL_TIM_CLEAR_IT(htim, TIM_IT_CC2); htim->Channel = HAL_TIM_ACTIVE_CHANNEL_2; /* Input capture event */ - if((htim->Instance->CCMR1 & TIM_CCMR1_CC2S) != 0x00U) + if((htim->Instance->CCMR1 & TIM_CCMR1_CC2S) != 0x00) { HAL_TIM_IC_CaptureCallback(htim); } @@ -2824,7 +2804,7 @@ void HAL_TIM_IRQHandler(TIM_HandleTypeDef *htim) __HAL_TIM_CLEAR_IT(htim, TIM_IT_CC3); htim->Channel = HAL_TIM_ACTIVE_CHANNEL_3; /* Input capture event */ - if((htim->Instance->CCMR2 & TIM_CCMR2_CC3S) != 0x00U) + if((htim->Instance->CCMR2 & TIM_CCMR2_CC3S) != 0x00) { HAL_TIM_IC_CaptureCallback(htim); } @@ -2845,7 +2825,7 @@ void HAL_TIM_IRQHandler(TIM_HandleTypeDef *htim) __HAL_TIM_CLEAR_IT(htim, TIM_IT_CC4); htim->Channel = HAL_TIM_ACTIVE_CHANNEL_4; /* Input capture event */ - if((htim->Instance->CCMR2 & TIM_CCMR2_CC4S) != 0x00U) + if((htim->Instance->CCMR2 & TIM_CCMR2_CC4S) != 0x00) { HAL_TIM_IC_CaptureCallback(htim); } @@ -3042,7 +3022,7 @@ HAL_StatusTypeDef HAL_TIM_IC_ConfigChannel(TIM_HandleTypeDef *htim, TIM_IC_InitT htim->Instance->CCMR1 &= ~TIM_CCMR1_IC2PSC; /* Set the IC2PSC value */ - htim->Instance->CCMR1 |= (sConfig->ICPrescaler << 8U); + htim->Instance->CCMR1 |= (sConfig->ICPrescaler << 8); } else if (Channel == TIM_CHANNEL_3) { @@ -3074,7 +3054,7 @@ HAL_StatusTypeDef HAL_TIM_IC_ConfigChannel(TIM_HandleTypeDef *htim, TIM_IC_InitT htim->Instance->CCMR2 &= ~TIM_CCMR2_IC4PSC; /* Set the IC4PSC value */ - htim->Instance->CCMR2 |= (sConfig->ICPrescaler << 8U); + htim->Instance->CCMR2 |= (sConfig->ICPrescaler << 8); } htim->State = HAL_TIM_STATE_READY; @@ -3348,7 +3328,7 @@ HAL_StatusTypeDef HAL_TIM_DMABurst_WriteStart(TIM_HandleTypeDef *htim, uint32_t } else if((htim->State == HAL_TIM_STATE_READY)) { - if((BurstBuffer == 0U) && (BurstLength > 0U)) + if((BurstBuffer == 0 ) && (BurstLength > 0)) { return HAL_ERROR; } @@ -3368,7 +3348,7 @@ HAL_StatusTypeDef HAL_TIM_DMABurst_WriteStart(TIM_HandleTypeDef *htim, uint32_t htim->hdma[TIM_DMA_ID_UPDATE]->XferErrorCallback = TIM_DMAError ; /* Enable the DMA channel */ - HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_UPDATE], (uint32_t)BurstBuffer, (uint32_t)&htim->Instance->DMAR, ((BurstLength) >> 8U) + 1U); + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_UPDATE], (uint32_t)BurstBuffer, (uint32_t)&htim->Instance->DMAR, ((BurstLength) >> 8) + 1); } break; case TIM_DMA_CC1: @@ -3380,7 +3360,7 @@ HAL_StatusTypeDef HAL_TIM_DMABurst_WriteStart(TIM_HandleTypeDef *htim, uint32_t htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = TIM_DMAError ; /* Enable the DMA channel */ - HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)BurstBuffer, (uint32_t)&htim->Instance->DMAR, ((BurstLength) >> 8U) + 1U); + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)BurstBuffer, (uint32_t)&htim->Instance->DMAR, ((BurstLength) >> 8) + 1); } break; case TIM_DMA_CC2: @@ -3392,7 +3372,7 @@ HAL_StatusTypeDef HAL_TIM_DMABurst_WriteStart(TIM_HandleTypeDef *htim, uint32_t htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = TIM_DMAError ; /* Enable the DMA channel */ - HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)BurstBuffer, (uint32_t)&htim->Instance->DMAR, ((BurstLength) >> 8U) + 1U); + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)BurstBuffer, (uint32_t)&htim->Instance->DMAR, ((BurstLength) >> 8) + 1); } break; case TIM_DMA_CC3: @@ -3404,7 +3384,7 @@ HAL_StatusTypeDef HAL_TIM_DMABurst_WriteStart(TIM_HandleTypeDef *htim, uint32_t htim->hdma[TIM_DMA_ID_CC3]->XferErrorCallback = TIM_DMAError ; /* Enable the DMA channel */ - HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)BurstBuffer, (uint32_t)&htim->Instance->DMAR, ((BurstLength) >> 8U) + 1U); + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)BurstBuffer, (uint32_t)&htim->Instance->DMAR, ((BurstLength) >> 8) + 1); } break; case TIM_DMA_CC4: @@ -3416,7 +3396,7 @@ HAL_StatusTypeDef HAL_TIM_DMABurst_WriteStart(TIM_HandleTypeDef *htim, uint32_t htim->hdma[TIM_DMA_ID_CC4]->XferErrorCallback = TIM_DMAError ; /* Enable the DMA channel */ - HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC4], (uint32_t)BurstBuffer, (uint32_t)&htim->Instance->DMAR, ((BurstLength) >> 8U) + 1U); + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC4], (uint32_t)BurstBuffer, (uint32_t)&htim->Instance->DMAR, ((BurstLength) >> 8) + 1); } break; case TIM_DMA_COM: @@ -3428,7 +3408,7 @@ HAL_StatusTypeDef HAL_TIM_DMABurst_WriteStart(TIM_HandleTypeDef *htim, uint32_t htim->hdma[TIM_DMA_ID_COMMUTATION]->XferErrorCallback = TIM_DMAError ; /* Enable the DMA channel */ - HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_COMMUTATION], (uint32_t)BurstBuffer, (uint32_t)&htim->Instance->DMAR, ((BurstLength) >> 8U) + 1U); + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_COMMUTATION], (uint32_t)BurstBuffer, (uint32_t)&htim->Instance->DMAR, ((BurstLength) >> 8) + 1); } break; case TIM_DMA_TRIGGER: @@ -3440,7 +3420,7 @@ HAL_StatusTypeDef HAL_TIM_DMABurst_WriteStart(TIM_HandleTypeDef *htim, uint32_t htim->hdma[TIM_DMA_ID_TRIGGER]->XferErrorCallback = TIM_DMAError ; /* Enable the DMA channel */ - HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_TRIGGER], (uint32_t)BurstBuffer, (uint32_t)&htim->Instance->DMAR, ((BurstLength) >> 8U) + 1U); + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_TRIGGER], (uint32_t)BurstBuffer, (uint32_t)&htim->Instance->DMAR, ((BurstLength) >> 8) + 1); } break; default: @@ -3571,7 +3551,7 @@ HAL_StatusTypeDef HAL_TIM_DMABurst_ReadStart(TIM_HandleTypeDef *htim, uint32_t B } else if((htim->State == HAL_TIM_STATE_READY)) { - if((BurstBuffer == 0U) && (BurstLength > 0U)) + if((BurstBuffer == 0 ) && (BurstLength > 0)) { return HAL_ERROR; } @@ -3591,7 +3571,7 @@ HAL_StatusTypeDef HAL_TIM_DMABurst_ReadStart(TIM_HandleTypeDef *htim, uint32_t B htim->hdma[TIM_DMA_ID_UPDATE]->XferErrorCallback = TIM_DMAError ; /* Enable the DMA channel */ - HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_UPDATE], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, ((BurstLength) >> 8U) + 1U); + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_UPDATE], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, ((BurstLength) >> 8) + 1); } break; case TIM_DMA_CC1: @@ -3603,7 +3583,7 @@ HAL_StatusTypeDef HAL_TIM_DMABurst_ReadStart(TIM_HandleTypeDef *htim, uint32_t B htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = TIM_DMAError ; /* Enable the DMA channel */ - HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, ((BurstLength) >> 8U) + 1U); + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, ((BurstLength) >> 8) + 1); } break; case TIM_DMA_CC2: @@ -3615,7 +3595,7 @@ HAL_StatusTypeDef HAL_TIM_DMABurst_ReadStart(TIM_HandleTypeDef *htim, uint32_t B htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = TIM_DMAError ; /* Enable the DMA channel */ - HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, ((BurstLength) >> 8U) + 1U); + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, ((BurstLength) >> 8) + 1); } break; case TIM_DMA_CC3: @@ -3627,7 +3607,7 @@ HAL_StatusTypeDef HAL_TIM_DMABurst_ReadStart(TIM_HandleTypeDef *htim, uint32_t B htim->hdma[TIM_DMA_ID_CC3]->XferErrorCallback = TIM_DMAError ; /* Enable the DMA channel */ - HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, ((BurstLength) >> 8U) + 1U); + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, ((BurstLength) >> 8) + 1); } break; case TIM_DMA_CC4: @@ -3639,7 +3619,7 @@ HAL_StatusTypeDef HAL_TIM_DMABurst_ReadStart(TIM_HandleTypeDef *htim, uint32_t B htim->hdma[TIM_DMA_ID_CC4]->XferErrorCallback = TIM_DMAError ; /* Enable the DMA channel */ - HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC4], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, ((BurstLength) >> 8U) + 1U); + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC4], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, ((BurstLength) >> 8) + 1); } break; case TIM_DMA_COM: @@ -3651,7 +3631,7 @@ HAL_StatusTypeDef HAL_TIM_DMABurst_ReadStart(TIM_HandleTypeDef *htim, uint32_t B htim->hdma[TIM_DMA_ID_COMMUTATION]->XferErrorCallback = TIM_DMAError ; /* Enable the DMA channel */ - HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_COMMUTATION], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, ((BurstLength) >> 8U) + 1U); + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_COMMUTATION], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, ((BurstLength) >> 8) + 1); } break; case TIM_DMA_TRIGGER: @@ -3663,7 +3643,7 @@ HAL_StatusTypeDef HAL_TIM_DMABurst_ReadStart(TIM_HandleTypeDef *htim, uint32_t B htim->hdma[TIM_DMA_ID_TRIGGER]->XferErrorCallback = TIM_DMAError ; /* Enable the DMA channel */ - HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_TRIGGER], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, ((BurstLength) >> 8U) + 1U); + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_TRIGGER], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, ((BurstLength) >> 8) + 1); } break; default: @@ -3799,7 +3779,7 @@ HAL_StatusTypeDef HAL_TIM_GenerateEvent(TIM_HandleTypeDef *htim, uint32_t EventS */ HAL_StatusTypeDef HAL_TIM_ConfigOCrefClear(TIM_HandleTypeDef *htim, TIM_ClearInputConfigTypeDef * sClearInputConfig, uint32_t Channel) { - uint32_t tmpsmcr = 0U; + uint32_t tmpsmcr = 0; /* Check the parameters */ assert_param(IS_TIM_OCXREF_CLEAR_INSTANCE(htim->Instance)); @@ -3817,6 +3797,8 @@ HAL_StatusTypeDef HAL_TIM_ConfigOCrefClear(TIM_HandleTypeDef *htim, TIM_ClearInp { case TIM_CLEARINPUTSOURCE_NONE: { + /* Clear the OCREF clear selection bit */ + tmpsmcr &= ~TIM_SMCR_OCCS; /* Clear the ETR Bits */ tmpsmcr &= ~(TIM_SMCR_ETF | TIM_SMCR_ETPS | TIM_SMCR_ECE | TIM_SMCR_ETP); @@ -3833,6 +3815,8 @@ HAL_StatusTypeDef HAL_TIM_ConfigOCrefClear(TIM_HandleTypeDef *htim, TIM_ClearInp sClearInputConfig->ClearInputPolarity, sClearInputConfig->ClearInputFilter); + /* Set the OCREF clear selection bit */ + htim->Instance->SMCR |= TIM_SMCR_OCCS; } break; default: @@ -3920,7 +3904,7 @@ HAL_StatusTypeDef HAL_TIM_ConfigOCrefClear(TIM_HandleTypeDef *htim, TIM_ClearInp */ HAL_StatusTypeDef HAL_TIM_ConfigClockSource(TIM_HandleTypeDef *htim, TIM_ClockConfigTypeDef * sClockSourceConfig) { - uint32_t tmpsmcr = 0U; + uint32_t tmpsmcr = 0; /* Process Locked */ __HAL_LOCK(htim); @@ -4094,7 +4078,7 @@ HAL_StatusTypeDef HAL_TIM_ConfigClockSource(TIM_HandleTypeDef *htim, TIM_ClockCo */ HAL_StatusTypeDef HAL_TIM_ConfigTI1Input(TIM_HandleTypeDef *htim, uint32_t TI1_Selection) { - uint32_t tmpcr2 = 0U; + uint32_t tmpcr2 = 0; /* Check the parameters */ assert_param(IS_TIM_XOR_INSTANCE(htim->Instance)); @@ -4199,7 +4183,7 @@ HAL_StatusTypeDef HAL_TIM_SlaveConfigSynchronization_IT(TIM_HandleTypeDef *htim, */ uint32_t HAL_TIM_ReadCapturedValue(TIM_HandleTypeDef *htim, uint32_t Channel) { - uint32_t tmpreg = 0U; + uint32_t tmpreg = 0; __HAL_LOCK(htim); @@ -4568,7 +4552,7 @@ static void TIM_DMATriggerCplt(DMA_HandleTypeDef *hdma) */ void TIM_Base_SetConfig(TIM_TypeDef *TIMx, TIM_Base_InitTypeDef *Structure) { - uint32_t tmpcr1 = 0U; + uint32_t tmpcr1 = 0; tmpcr1 = TIMx->CR1; /* Set TIM Time Base Unit parameters ---------------------------------------*/ @@ -4586,10 +4570,6 @@ void TIM_Base_SetConfig(TIM_TypeDef *TIMx, TIM_Base_InitTypeDef *Structure) tmpcr1 |= (uint32_t)Structure->ClockDivision; } - /* Set the auto-reload preload */ - tmpcr1 &= ~TIM_CR1_ARPE; - tmpcr1 |= (uint32_t)Structure->AutoReloadPreload; - TIMx->CR1 = tmpcr1; /* Set the Autoreload value */ @@ -4617,9 +4597,9 @@ void TIM_Base_SetConfig(TIM_TypeDef *TIMx, TIM_Base_InitTypeDef *Structure) */ static void TIM_OC1_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config) { - uint32_t tmpccmrx = 0U; - uint32_t tmpccer = 0U; - uint32_t tmpcr2 = 0U; + uint32_t tmpccmrx = 0; + uint32_t tmpccer = 0; + uint32_t tmpcr2 = 0; /* Disable the Channel 1: Reset the CC1E Bit */ TIMx->CCER &= ~TIM_CCER_CC1E; @@ -4691,9 +4671,9 @@ static void TIM_OC1_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config) */ void TIM_OC2_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config) { - uint32_t tmpccmrx = 0U; - uint32_t tmpccer = 0U; - uint32_t tmpcr2 = 0U; + uint32_t tmpccmrx = 0; + uint32_t tmpccer = 0; + uint32_t tmpcr2 = 0; /* Disable the Channel 2: Reset the CC2E Bit */ TIMx->CCER &= ~TIM_CCER_CC2E; @@ -4711,12 +4691,12 @@ void TIM_OC2_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config) tmpccmrx &= ~TIM_CCMR1_CC2S; /* Select the Output Compare Mode */ - tmpccmrx |= (OC_Config->OCMode << 8U); + tmpccmrx |= (OC_Config->OCMode << 8); /* Reset the Output Polarity level */ tmpccer &= ~TIM_CCER_CC2P; /* Set the Output Compare Polarity */ - tmpccer |= (OC_Config->OCPolarity << 4U); + tmpccer |= (OC_Config->OCPolarity << 4); if(IS_TIM_CCXN_INSTANCE(TIMx, TIM_CHANNEL_2)) { @@ -4725,7 +4705,7 @@ void TIM_OC2_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config) /* Reset the Output N Polarity level */ tmpccer &= ~TIM_CCER_CC2NP; /* Set the Output N Polarity */ - tmpccer |= (OC_Config->OCNPolarity << 4U); + tmpccer |= (OC_Config->OCNPolarity << 4); /* Reset the Output N State */ tmpccer &= ~TIM_CCER_CC2NE; @@ -4767,9 +4747,9 @@ void TIM_OC2_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config) */ static void TIM_OC3_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config) { - uint32_t tmpccmrx = 0U; - uint32_t tmpccer = 0U; - uint32_t tmpcr2 = 0U; + uint32_t tmpccmrx = 0; + uint32_t tmpccer = 0; + uint32_t tmpcr2 = 0; /* Disable the Channel 3: Reset the CC2E Bit */ TIMx->CCER &= ~TIM_CCER_CC3E; @@ -4791,7 +4771,7 @@ static void TIM_OC3_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config) /* Reset the Output Polarity level */ tmpccer &= ~TIM_CCER_CC3P; /* Set the Output Compare Polarity */ - tmpccer |= (OC_Config->OCPolarity << 8U); + tmpccer |= (OC_Config->OCPolarity << 8); if(IS_TIM_CCXN_INSTANCE(TIMx, TIM_CHANNEL_3)) { @@ -4800,7 +4780,7 @@ static void TIM_OC3_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config) /* Reset the Output N Polarity level */ tmpccer &= ~TIM_CCER_CC3NP; /* Set the Output N Polarity */ - tmpccer |= (OC_Config->OCNPolarity << 8U); + tmpccer |= (OC_Config->OCNPolarity << 8); /* Reset the Output N State */ tmpccer &= ~TIM_CCER_CC3NE; } @@ -4815,9 +4795,9 @@ static void TIM_OC3_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config) tmpcr2 &= ~TIM_CR2_OIS3; tmpcr2 &= ~TIM_CR2_OIS3N; /* Set the Output Idle state */ - tmpcr2 |= (OC_Config->OCIdleState << 4U); + tmpcr2 |= (OC_Config->OCIdleState << 4); /* Set the Output N Idle state */ - tmpcr2 |= (OC_Config->OCNIdleState << 4U); + tmpcr2 |= (OC_Config->OCNIdleState << 4); } /* Write to TIMx CR2 */ @@ -4841,9 +4821,9 @@ static void TIM_OC3_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config) */ static void TIM_OC4_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config) { - uint32_t tmpccmrx = 0U; - uint32_t tmpccer = 0U; - uint32_t tmpcr2 = 0U; + uint32_t tmpccmrx = 0; + uint32_t tmpccer = 0; + uint32_t tmpcr2 = 0; /* Disable the Channel 4: Reset the CC4E Bit */ TIMx->CCER &= ~TIM_CCER_CC4E; @@ -4861,12 +4841,12 @@ static void TIM_OC4_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config) tmpccmrx &= ~TIM_CCMR2_CC4S; /* Select the Output Compare Mode */ - tmpccmrx |= (OC_Config->OCMode << 8U); + tmpccmrx |= (OC_Config->OCMode << 8); /* Reset the Output Polarity level */ tmpccer &= ~TIM_CCER_CC4P; /* Set the Output Compare Polarity */ - tmpccer |= (OC_Config->OCPolarity << 12U); + tmpccer |= (OC_Config->OCPolarity << 12); if(IS_TIM_BREAK_INSTANCE(TIMx)) { @@ -4902,9 +4882,9 @@ static void TIM_OC4_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config) static void TIM_SlaveTimer_SetConfig(TIM_HandleTypeDef *htim, TIM_SlaveConfigTypeDef * sSlaveConfig) { - uint32_t tmpsmcr = 0U; - uint32_t tmpccmr1 = 0U; - uint32_t tmpccer = 0U; + uint32_t tmpsmcr = 0; + uint32_t tmpccmr1 = 0; + uint32_t tmpccer = 0; /* Get the TIMx SMCR register value */ tmpsmcr = htim->Instance->SMCR; @@ -4953,7 +4933,7 @@ static void TIM_SlaveTimer_SetConfig(TIM_HandleTypeDef *htim, /* Set the filter */ tmpccmr1 &= ~TIM_CCMR1_IC1F; - tmpccmr1 |= ((sSlaveConfig->TriggerFilter) << 4U); + tmpccmr1 |= ((sSlaveConfig->TriggerFilter) << 4); /* Write to TIMx CCMR1 and CCER registers */ htim->Instance->CCMR1 = tmpccmr1; @@ -5030,6 +5010,7 @@ static void TIM_SlaveTimer_SetConfig(TIM_HandleTypeDef *htim, * This parameter can be one of the following values: * @arg TIM_ICPOLARITY_RISING * @arg TIM_ICPOLARITY_FALLING + * @arg TIM_ICPOLARITY_BOTHEDGE * @param TIM_ICSelection : specifies the input to be used. * This parameter can be one of the following values: * @arg TIM_ICSELECTION_DIRECTTI: TIM Input 1 is selected to be connected to IC1. @@ -5045,8 +5026,8 @@ static void TIM_SlaveTimer_SetConfig(TIM_HandleTypeDef *htim, void TIM_TI1_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection, uint32_t TIM_ICFilter) { - uint32_t tmpccmr1 = 0U; - uint32_t tmpccer = 0U; + uint32_t tmpccmr1 = 0; + uint32_t tmpccer = 0; /* Disable the Channel 1: Reset the CC1E Bit */ TIMx->CCER &= ~TIM_CCER_CC1E; @@ -5066,7 +5047,7 @@ void TIM_TI1_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ /* Set the filter */ tmpccmr1 &= ~TIM_CCMR1_IC1F; - tmpccmr1 |= ((TIM_ICFilter << 4U) & TIM_CCMR1_IC1F); + tmpccmr1 |= ((TIM_ICFilter << 4) & TIM_CCMR1_IC1F); /* Select the Polarity and set the CC1E Bit */ tmpccer &= ~(TIM_CCER_CC1P | TIM_CCER_CC1NP); @@ -5083,15 +5064,16 @@ void TIM_TI1_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ * @param TIM_ICPolarity : The Input Polarity. * This parameter can be one of the following values: * @arg TIM_ICPOLARITY_RISING - * @arg TIM_ICPOLARITY_FALLING + * @arg TIM_ICPOLARITY_FALLING + * @arg TIM_ICPOLARITY_BOTHEDGE * @param TIM_ICFilter : Specifies the Input Capture Filter. * This parameter must be a value between 0x00 and 0x0F. * @retval None */ static void TIM_TI1_ConfigInputStage(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICFilter) { - uint32_t tmpccmr1 = 0U; - uint32_t tmpccer = 0U; + uint32_t tmpccmr1 = 0; + uint32_t tmpccer = 0; /* Disable the Channel 1: Reset the CC1E Bit */ tmpccer = TIMx->CCER; @@ -5100,7 +5082,7 @@ static void TIM_TI1_ConfigInputStage(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, /* Set the filter */ tmpccmr1 &= ~TIM_CCMR1_IC1F; - tmpccmr1 |= (TIM_ICFilter << 4U); + tmpccmr1 |= (TIM_ICFilter << 4); /* Select the Polarity and set the CC1E Bit */ tmpccer &= ~(TIM_CCER_CC1P | TIM_CCER_CC1NP); @@ -5117,7 +5099,8 @@ static void TIM_TI1_ConfigInputStage(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, * @param TIM_ICPolarity : The Input Polarity. * This parameter can be one of the following values: * @arg TIM_ICPOLARITY_RISING - * @arg TIM_ICPOLARITY_FALLING + * @arg TIM_ICPOLARITY_FALLING + * @arg TIM_ICPOLARITY_BOTHEDGE * @param TIM_ICSelection : specifies the input to be used. * This parameter can be one of the following values: * @arg TIM_ICSELECTION_DIRECTTI: TIM Input 2 is selected to be connected to IC2. @@ -5133,8 +5116,8 @@ static void TIM_TI1_ConfigInputStage(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, static void TIM_TI2_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection, uint32_t TIM_ICFilter) { - uint32_t tmpccmr1 = 0U; - uint32_t tmpccer = 0U; + uint32_t tmpccmr1 = 0; + uint32_t tmpccer = 0; /* Disable the Channel 2: Reset the CC2E Bit */ TIMx->CCER &= ~TIM_CCER_CC2E; @@ -5143,15 +5126,15 @@ static void TIM_TI2_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32 /* Select the Input */ tmpccmr1 &= ~TIM_CCMR1_CC2S; - tmpccmr1 |= (TIM_ICSelection << 8U); + tmpccmr1 |= (TIM_ICSelection << 8); /* Set the filter */ tmpccmr1 &= ~TIM_CCMR1_IC2F; - tmpccmr1 |= ((TIM_ICFilter << 12U) & TIM_CCMR1_IC2F); + tmpccmr1 |= ((TIM_ICFilter << 12) & TIM_CCMR1_IC2F); /* Select the Polarity and set the CC2E Bit */ tmpccer &= ~(TIM_CCER_CC2P | TIM_CCER_CC2NP); - tmpccer |= ((TIM_ICPolarity << 4U) & (TIM_CCER_CC2P | TIM_CCER_CC2NP)); + tmpccer |= ((TIM_ICPolarity << 4) & (TIM_CCER_CC2P | TIM_CCER_CC2NP)); /* Write to TIMx CCMR1 and CCER registers */ TIMx->CCMR1 = tmpccmr1 ; @@ -5164,15 +5147,16 @@ static void TIM_TI2_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32 * @param TIM_ICPolarity : The Input Polarity. * This parameter can be one of the following values: * @arg TIM_ICPOLARITY_RISING - * @arg TIM_ICPOLARITY_FALLING + * @arg TIM_ICPOLARITY_FALLING + * @arg TIM_ICPOLARITY_BOTHEDGE * @param TIM_ICFilter : Specifies the Input Capture Filter. * This parameter must be a value between 0x00 and 0x0F. * @retval None */ static void TIM_TI2_ConfigInputStage(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICFilter) { - uint32_t tmpccmr1 = 0U; - uint32_t tmpccer = 0U; + uint32_t tmpccmr1 = 0; + uint32_t tmpccer = 0; /* Disable the Channel 2: Reset the CC2E Bit */ TIMx->CCER &= ~TIM_CCER_CC2E; @@ -5181,11 +5165,11 @@ static void TIM_TI2_ConfigInputStage(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, /* Set the filter */ tmpccmr1 &= ~TIM_CCMR1_IC2F; - tmpccmr1 |= (TIM_ICFilter << 12U); + tmpccmr1 |= (TIM_ICFilter << 12); /* Select the Polarity and set the CC2E Bit */ tmpccer &= ~(TIM_CCER_CC2P | TIM_CCER_CC2NP); - tmpccer |= (TIM_ICPolarity << 4U); + tmpccer |= (TIM_ICPolarity << 4); /* Write to TIMx CCMR1 and CCER registers */ TIMx->CCMR1 = tmpccmr1 ; @@ -5198,7 +5182,8 @@ static void TIM_TI2_ConfigInputStage(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, * @param TIM_ICPolarity : The Input Polarity. * This parameter can be one of the following values: * @arg TIM_ICPOLARITY_RISING - * @arg TIM_ICPOLARITY_FALLING + * @arg TIM_ICPOLARITY_FALLING + * @arg TIM_ICPOLARITY_BOTHEDGE * @param TIM_ICSelection : specifies the input to be used. * This parameter can be one of the following values: * @arg TIM_ICSELECTION_DIRECTTI: TIM Input 3 is selected to be connected to IC3. @@ -5214,8 +5199,8 @@ static void TIM_TI2_ConfigInputStage(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, static void TIM_TI3_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection, uint32_t TIM_ICFilter) { - uint32_t tmpccmr2 = 0U; - uint32_t tmpccer = 0U; + uint32_t tmpccmr2 = 0; + uint32_t tmpccer = 0; /* Disable the Channel 3: Reset the CC3E Bit */ TIMx->CCER &= ~TIM_CCER_CC3E; @@ -5228,11 +5213,11 @@ static void TIM_TI3_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32 /* Set the filter */ tmpccmr2 &= ~TIM_CCMR2_IC3F; - tmpccmr2 |= ((TIM_ICFilter << 4U) & TIM_CCMR2_IC3F); + tmpccmr2 |= ((TIM_ICFilter << 4) & TIM_CCMR2_IC3F); /* Select the Polarity and set the CC3E Bit */ tmpccer &= ~(TIM_CCER_CC3P | TIM_CCER_CC3NP); - tmpccer |= ((TIM_ICPolarity << 8U) & (TIM_CCER_CC3P | TIM_CCER_CC3NP)); + tmpccer |= ((TIM_ICPolarity << 8) & (TIM_CCER_CC3P | TIM_CCER_CC3NP)); /* Write to TIMx CCMR2 and CCER registers */ TIMx->CCMR2 = tmpccmr2; @@ -5245,7 +5230,8 @@ static void TIM_TI3_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32 * @param TIM_ICPolarity : The Input Polarity. * This parameter can be one of the following values: * @arg TIM_ICPOLARITY_RISING - * @arg TIM_ICPOLARITY_FALLING + * @arg TIM_ICPOLARITY_FALLING + * @arg TIM_ICPOLARITY_BOTHEDGE * @param TIM_ICSelection : specifies the input to be used. * This parameter can be one of the following values: * @arg TIM_ICSELECTION_DIRECTTI: TIM Input 4 is selected to be connected to IC4. @@ -5261,8 +5247,8 @@ static void TIM_TI3_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32 static void TIM_TI4_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection, uint32_t TIM_ICFilter) { - uint32_t tmpccmr2 = 0U; - uint32_t tmpccer = 0U; + uint32_t tmpccmr2 = 0; + uint32_t tmpccer = 0; /* Disable the Channel 4: Reset the CC4E Bit */ TIMx->CCER &= ~TIM_CCER_CC4E; @@ -5271,15 +5257,15 @@ static void TIM_TI4_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32 /* Select the Input */ tmpccmr2 &= ~TIM_CCMR2_CC4S; - tmpccmr2 |= (TIM_ICSelection << 8U); + tmpccmr2 |= (TIM_ICSelection << 8); /* Set the filter */ tmpccmr2 &= ~TIM_CCMR2_IC4F; - tmpccmr2 |= ((TIM_ICFilter << 12U) & TIM_CCMR2_IC4F); + tmpccmr2 |= ((TIM_ICFilter << 12) & TIM_CCMR2_IC4F); /* Select the Polarity and set the CC4E Bit */ - tmpccer &= ~TIM_CCER_CC4P; - tmpccer |= ((TIM_ICPolarity << 12U) & TIM_CCER_CC4P); + tmpccer &= ~(TIM_CCER_CC4P | TIM_CCER_CC4NP); + tmpccer |= ((TIM_ICPolarity << 12) & (TIM_CCER_CC4P | TIM_CCER_CC4NP)); /* Write to TIMx CCMR2 and CCER registers */ TIMx->CCMR2 = tmpccmr2; @@ -5303,7 +5289,7 @@ static void TIM_TI4_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32 */ static void TIM_ITRx_SetConfig(TIM_TypeDef *TIMx, uint16_t InputTriggerSource) { - uint32_t tmpsmcr = 0U; + uint32_t tmpsmcr = 0; /* Get the TIMx SMCR register value */ tmpsmcr = TIMx->SMCR; @@ -5334,7 +5320,7 @@ static void TIM_ITRx_SetConfig(TIM_TypeDef *TIMx, uint16_t InputTriggerSource) static void TIM_ETR_SetConfig(TIM_TypeDef* TIMx, uint32_t TIM_ExtTRGPrescaler, uint32_t TIM_ExtTRGPolarity, uint32_t ExtTRGFilter) { - uint32_t tmpsmcr = 0U; + uint32_t tmpsmcr = 0; tmpsmcr = TIMx->SMCR; @@ -5342,7 +5328,7 @@ static void TIM_ETR_SetConfig(TIM_TypeDef* TIMx, uint32_t TIM_ExtTRGPrescaler, tmpsmcr &= ~(TIM_SMCR_ETF | TIM_SMCR_ETPS | TIM_SMCR_ECE | TIM_SMCR_ETP); /* Set the Prescaler, the Filter value and the Polarity */ - tmpsmcr |= (uint32_t)(TIM_ExtTRGPrescaler | (TIM_ExtTRGPolarity | (ExtTRGFilter << 8U))); + tmpsmcr |= (uint32_t)(TIM_ExtTRGPrescaler | (TIM_ExtTRGPolarity | (ExtTRGFilter << 8))); /* Write to TIMx SMCR */ TIMx->SMCR = tmpsmcr; @@ -5363,7 +5349,7 @@ static void TIM_ETR_SetConfig(TIM_TypeDef* TIMx, uint32_t TIM_ExtTRGPrescaler, */ void TIM_CCxChannelCmd(TIM_TypeDef* TIMx, uint32_t Channel, uint32_t ChannelState) { - uint32_t tmp = 0U; + uint32_t tmp = 0; /* Check the parameters */ assert_param(IS_TIM_CC1_INSTANCE(TIMx)); diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_tim.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_tim.h index ad4d8853321..91d0a07aa81 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_tim.h +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_tim.h @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_hal_tim.h * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief Header file of TIM HAL module. ****************************************************************************** * @attention @@ -84,9 +84,6 @@ typedef struct - the number of half PWM period in center-aligned mode This parameter must be a number between Min_Data = 0x00 and Max_Data = 0xFF. @note This parameter is valid only for TIM1 and TIM8. */ - - uint32_t AutoReloadPreload; /*!< Specifies the auto-reload preload. - This parameter can be a value of @ref TIM_AutoReloadPreload */ } TIM_Base_InitTypeDef; /** @@ -264,11 +261,11 @@ typedef struct { */ typedef enum { - HAL_TIM_STATE_RESET = 0x00U, /*!< Peripheral not yet initialized or disabled */ - HAL_TIM_STATE_READY = 0x01U, /*!< Peripheral Initialized and ready for use */ - HAL_TIM_STATE_BUSY = 0x02U, /*!< An internal process is ongoing */ - HAL_TIM_STATE_TIMEOUT = 0x03U, /*!< Timeout state */ - HAL_TIM_STATE_ERROR = 0x04U /*!< Reception process is ongoing */ + HAL_TIM_STATE_RESET = 0x00, /*!< Peripheral not yet initialized or disabled */ + HAL_TIM_STATE_READY = 0x01, /*!< Peripheral Initialized and ready for use */ + HAL_TIM_STATE_BUSY = 0x02, /*!< An internal process is ongoing */ + HAL_TIM_STATE_TIMEOUT = 0x03, /*!< Timeout state */ + HAL_TIM_STATE_ERROR = 0x04 /*!< Reception process is ongoing */ }HAL_TIM_StateTypeDef; /** @@ -276,11 +273,11 @@ typedef enum */ typedef enum { - HAL_TIM_ACTIVE_CHANNEL_1 = 0x01U, /*!< The active channel is 1 */ - HAL_TIM_ACTIVE_CHANNEL_2 = 0x02U, /*!< The active channel is 2 */ - HAL_TIM_ACTIVE_CHANNEL_3 = 0x04U, /*!< The active channel is 3 */ - HAL_TIM_ACTIVE_CHANNEL_4 = 0x08U, /*!< The active channel is 4 */ - HAL_TIM_ACTIVE_CHANNEL_CLEARED = 0x00U /*!< All active channels cleared */ + HAL_TIM_ACTIVE_CHANNEL_1 = 0x01, /*!< The active channel is 1 */ + HAL_TIM_ACTIVE_CHANNEL_2 = 0x02, /*!< The active channel is 2 */ + HAL_TIM_ACTIVE_CHANNEL_3 = 0x04, /*!< The active channel is 3 */ + HAL_TIM_ACTIVE_CHANNEL_4 = 0x08, /*!< The active channel is 4 */ + HAL_TIM_ACTIVE_CHANNEL_CLEARED = 0x00 /*!< All active channels cleared */ }HAL_TIM_ActiveChannel; /** @@ -288,12 +285,12 @@ typedef enum */ typedef struct { - TIM_TypeDef *Instance; /*!< Register base address */ - TIM_Base_InitTypeDef Init; /*!< TIM Time Base required parameters */ - HAL_TIM_ActiveChannel Channel; /*!< Active channel */ - DMA_HandleTypeDef *hdma[7U]; /*!< DMA Handlers array - This array is accessed by a @ref TIM_DMA_Handle_index */ - HAL_LockTypeDef Lock; /*!< Locking object */ + TIM_TypeDef *Instance; /*!< Register base address */ + TIM_Base_InitTypeDef Init; /*!< TIM Time Base required parameters */ + HAL_TIM_ActiveChannel Channel; /*!< Active channel */ + DMA_HandleTypeDef *hdma[7]; /*!< DMA Handlers array + This array is accessed by a @ref TIM_DMA_Handle_index */ + HAL_LockTypeDef Lock; /*!< Locking object */ __IO HAL_TIM_StateTypeDef State; /*!< TIM operation state */ }TIM_HandleTypeDef; @@ -309,7 +306,7 @@ typedef struct /** @defgroup TIM_Input_Channel_Polarity TIM Input Channel Polarity * @{ */ -#define TIM_INPUTCHANNELPOLARITY_RISING 0x00000000U /*!< Polarity for TIx source */ +#define TIM_INPUTCHANNELPOLARITY_RISING ((uint32_t)0x00000000) /*!< Polarity for TIx source */ #define TIM_INPUTCHANNELPOLARITY_FALLING (TIM_CCER_CC1P) /*!< Polarity for TIx source */ #define TIM_INPUTCHANNELPOLARITY_BOTHEDGE (TIM_CCER_CC1P | TIM_CCER_CC1NP) /*!< Polarity for TIx source */ /** @@ -320,7 +317,7 @@ typedef struct * @{ */ #define TIM_ETRPOLARITY_INVERTED (TIM_SMCR_ETP) /*!< Polarity for ETR source */ -#define TIM_ETRPOLARITY_NONINVERTED 0x00000000U /*!< Polarity for ETR source */ +#define TIM_ETRPOLARITY_NONINVERTED ((uint32_t)0x0000) /*!< Polarity for ETR source */ /** * @} */ @@ -328,7 +325,7 @@ typedef struct /** @defgroup TIM_ETR_Prescaler TIM ETR Prescaler * @{ */ -#define TIM_ETRPRESCALER_DIV1 0x00000000U /*!< No prescaler is used */ +#define TIM_ETRPRESCALER_DIV1 ((uint32_t)0x0000) /*!< No prescaler is used */ #define TIM_ETRPRESCALER_DIV2 (TIM_SMCR_ETPS_0) /*!< ETR input source is divided by 2 */ #define TIM_ETRPRESCALER_DIV4 (TIM_SMCR_ETPS_1) /*!< ETR input source is divided by 4 */ #define TIM_ETRPRESCALER_DIV8 (TIM_SMCR_ETPS) /*!< ETR input source is divided by 8 */ @@ -339,7 +336,7 @@ typedef struct /** @defgroup TIM_Counter_Mode TIM Counter Mode * @{ */ -#define TIM_COUNTERMODE_UP 0x00000000U +#define TIM_COUNTERMODE_UP ((uint32_t)0x0000) #define TIM_COUNTERMODE_DOWN TIM_CR1_DIR #define TIM_COUNTERMODE_CENTERALIGNED1 TIM_CR1_CMS_0 #define TIM_COUNTERMODE_CENTERALIGNED2 TIM_CR1_CMS_1 @@ -351,26 +348,17 @@ typedef struct /** @defgroup TIM_ClockDivision TIM ClockDivision * @{ */ -#define TIM_CLOCKDIVISION_DIV1 0x00000000U +#define TIM_CLOCKDIVISION_DIV1 ((uint32_t)0x0000) #define TIM_CLOCKDIVISION_DIV2 (TIM_CR1_CKD_0) #define TIM_CLOCKDIVISION_DIV4 (TIM_CR1_CKD_1) /** * @} */ -/** @defgroup TIM_AutoReloadPreload TIM Auto-Reload Preload - * @{ - */ -#define TIM_AUTORELOAD_PRELOAD_DISABLE 0x0000U /*!< TIMx_ARR register is not buffered */ -#define TIM_AUTORELOAD_PRELOAD_ENABLE (TIM_CR1_ARPE) /*!< TIMx_ARR register is buffered */ -/** - * @} - */ - /** @defgroup TIM_Output_Compare_and_PWM_modes TIM Output Compare and PWM modes * @{ */ -#define TIM_OCMODE_TIMING 0x00000000U +#define TIM_OCMODE_TIMING ((uint32_t)0x0000) #define TIM_OCMODE_ACTIVE (TIM_CCMR1_OC1M_0) #define TIM_OCMODE_INACTIVE (TIM_CCMR1_OC1M_1) #define TIM_OCMODE_TOGGLE (TIM_CCMR1_OC1M_0 | TIM_CCMR1_OC1M_1) @@ -385,7 +373,7 @@ typedef struct /** @defgroup TIM_Output_Compare_State TIM Output Compare State * @{ */ -#define TIM_OUTPUTSTATE_DISABLE 0x00000000U +#define TIM_OUTPUTSTATE_DISABLE ((uint32_t)0x0000) #define TIM_OUTPUTSTATE_ENABLE (TIM_CCER_CC1E) /** * @} @@ -394,7 +382,7 @@ typedef struct /** @defgroup TIM_Output_Fast_State TIM Output Fast State * @{ */ -#define TIM_OCFAST_DISABLE 0x00000000U +#define TIM_OCFAST_DISABLE ((uint32_t)0x0000) #define TIM_OCFAST_ENABLE (TIM_CCMR1_OC1FE) /** * @} @@ -403,7 +391,7 @@ typedef struct /** @defgroup TIM_Output_Compare_N_State TIM Complementary Output Compare State * @{ */ -#define TIM_OUTPUTNSTATE_DISABLE 0x00000000U +#define TIM_OUTPUTNSTATE_DISABLE ((uint32_t)0x0000) #define TIM_OUTPUTNSTATE_ENABLE (TIM_CCER_CC1NE) /** * @} @@ -412,7 +400,7 @@ typedef struct /** @defgroup TIM_Output_Compare_Polarity TIM Output Compare Polarity * @{ */ -#define TIM_OCPOLARITY_HIGH 0x00000000U +#define TIM_OCPOLARITY_HIGH ((uint32_t)0x0000) #define TIM_OCPOLARITY_LOW (TIM_CCER_CC1P) /** * @} @@ -421,7 +409,7 @@ typedef struct /** @defgroup TIM_Output_Compare_N_Polarity TIM Complementary Output Compare Polarity * @{ */ -#define TIM_OCNPOLARITY_HIGH 0x00000000U +#define TIM_OCNPOLARITY_HIGH ((uint32_t)0x0000) #define TIM_OCNPOLARITY_LOW (TIM_CCER_CC1NP) /** * @} @@ -431,7 +419,7 @@ typedef struct * @{ */ #define TIM_OCIDLESTATE_SET (TIM_CR2_OIS1) -#define TIM_OCIDLESTATE_RESET 0x00000000U +#define TIM_OCIDLESTATE_RESET ((uint32_t)0x0000) /** * @} */ @@ -440,7 +428,7 @@ typedef struct * @{ */ #define TIM_OCNIDLESTATE_SET (TIM_CR2_OIS1N) -#define TIM_OCNIDLESTATE_RESET 0x00000000U +#define TIM_OCNIDLESTATE_RESET ((uint32_t)0x0000) /** * @} */ @@ -448,11 +436,11 @@ typedef struct /** @defgroup TIM_Channel TIM Channel * @{ */ -#define TIM_CHANNEL_1 0x00000000U -#define TIM_CHANNEL_2 0x00000004U -#define TIM_CHANNEL_3 0x00000008U -#define TIM_CHANNEL_4 0x0000000CU -#define TIM_CHANNEL_ALL 0x00000018U +#define TIM_CHANNEL_1 ((uint32_t)0x0000) +#define TIM_CHANNEL_2 ((uint32_t)0x0004) +#define TIM_CHANNEL_3 ((uint32_t)0x0008) +#define TIM_CHANNEL_4 ((uint32_t)0x000C) +#define TIM_CHANNEL_ALL ((uint32_t)0x0018) /** * @} */ @@ -462,6 +450,7 @@ typedef struct */ #define TIM_ICPOLARITY_RISING TIM_INPUTCHANNELPOLARITY_RISING #define TIM_ICPOLARITY_FALLING TIM_INPUTCHANNELPOLARITY_FALLING +#define TIM_ICPOLARITY_BOTHEDGE TIM_INPUTCHANNELPOLARITY_BOTHEDGE /** * @} */ @@ -481,7 +470,7 @@ typedef struct /** @defgroup TIM_Input_Capture_Prescaler TIM Input Capture Prescaler * @{ */ -#define TIM_ICPSC_DIV1 0x00000000U /*!< Capture performed each time an edge is detected on the capture input */ +#define TIM_ICPSC_DIV1 ((uint32_t)0x0000) /*!< Capture performed each time an edge is detected on the capture input */ #define TIM_ICPSC_DIV2 (TIM_CCMR1_IC1PSC_0) /*!< Capture performed once every 2 events */ #define TIM_ICPSC_DIV4 (TIM_CCMR1_IC1PSC_1) /*!< Capture performed once every 4 events */ #define TIM_ICPSC_DIV8 (TIM_CCMR1_IC1PSC) /*!< Capture performed once every 8 events */ @@ -493,7 +482,7 @@ typedef struct * @{ */ #define TIM_OPMODE_SINGLE (TIM_CR1_OPM) -#define TIM_OPMODE_REPETITIVE 0x00000000U +#define TIM_OPMODE_REPETITIVE ((uint32_t)0x0000) /** * @} */ @@ -527,7 +516,7 @@ typedef struct * @{ */ #define TIM_COMMUTATION_TRGI (TIM_CR2_CCUS) -#define TIM_COMMUTATION_SOFTWARE 0x00000000U +#define TIM_COMMUTATION_SOFTWARE ((uint32_t)0x0000) /** * @} @@ -601,9 +590,9 @@ typedef struct /** @defgroup TIM_Clock_Polarity TIM Clock Polarity * @{ */ -#define TIM_CLOCKPOLARITY_INVERTED TIM_ETRPOLARITY_INVERTED /*!< Polarity for ETRx clock sources */ -#define TIM_CLOCKPOLARITY_NONINVERTED TIM_ETRPOLARITY_NONINVERTED /*!< Polarity for ETRx clock sources */ -#define TIM_CLOCKPOLARITY_RISING TIM_INPUTCHANNELPOLARITY_RISING /*!< Polarity for TIx clock sources */ +#define TIM_CLOCKPOLARITY_INVERTED TIM_ETRPOLARITY_INVERTED /*!< Polarity for ETRx clock sources */ +#define TIM_CLOCKPOLARITY_NONINVERTED TIM_ETRPOLARITY_NONINVERTED /*!< Polarity for ETRx clock sources */ +#define TIM_CLOCKPOLARITY_RISING TIM_INPUTCHANNELPOLARITY_RISING /*!< Polarity for TIx clock sources */ #define TIM_CLOCKPOLARITY_FALLING TIM_INPUTCHANNELPOLARITY_FALLING /*!< Polarity for TIx clock sources */ #define TIM_CLOCKPOLARITY_BOTHEDGE TIM_INPUTCHANNELPOLARITY_BOTHEDGE /*!< Polarity for TIx clock sources */ /** @@ -624,8 +613,9 @@ typedef struct /** @defgroup TIM_ClearInput_Source TIM ClearInput Source * @{ */ -#define TIM_CLEARINPUTSOURCE_ETR 0x00000001U -#define TIM_CLEARINPUTSOURCE_NONE 0x00000000U +#define TIM_CLEARINPUTSOURCE_ETR ((uint32_t)0x0001) +#define TIM_CLEARINPUTSOURCE_OCREFCLR ((uint32_t)0x0002) +#define TIM_CLEARINPUTSOURCE_NONE ((uint32_t)0x0000) /** * @} */ @@ -634,7 +624,7 @@ typedef struct * @{ */ #define TIM_CLEARINPUTPOLARITY_INVERTED TIM_ETRPOLARITY_INVERTED /*!< Polarity for ETRx pin */ -#define TIM_CLEARINPUTPOLARITY_NONINVERTED TIM_ETRPOLARITY_NONINVERTED /*!< Polarity for ETRx pin */ +#define TIM_CLEARINPUTPOLARITY_NONINVERTED TIM_ETRPOLARITY_NONINVERTED /*!< Polarity for ETRx pin */ /** * @} */ @@ -654,7 +644,7 @@ typedef struct * @{ */ #define TIM_OSSR_ENABLE (TIM_BDTR_OSSR) -#define TIM_OSSR_DISABLE 0x00000000U +#define TIM_OSSR_DISABLE ((uint32_t)0x0000) /** * @} */ @@ -663,7 +653,7 @@ typedef struct * @{ */ #define TIM_OSSI_ENABLE (TIM_BDTR_OSSI) -#define TIM_OSSI_DISABLE 0x00000000U +#define TIM_OSSI_DISABLE ((uint32_t)0x0000) /** * @} */ @@ -671,7 +661,7 @@ typedef struct /** @defgroup TIM_Lock_level TIM Lock level * @{ */ -#define TIM_LOCKLEVEL_OFF 0x00000000U +#define TIM_LOCKLEVEL_OFF ((uint32_t)0x0000) #define TIM_LOCKLEVEL_1 (TIM_BDTR_LOCK_0) #define TIM_LOCKLEVEL_2 (TIM_BDTR_LOCK_1) #define TIM_LOCKLEVEL_3 (TIM_BDTR_LOCK) @@ -683,7 +673,7 @@ typedef struct * @{ */ #define TIM_BREAK_ENABLE (TIM_BDTR_BKE) -#define TIM_BREAK_DISABLE 0x00000000U +#define TIM_BREAK_DISABLE ((uint32_t)0x0000) /** * @} */ @@ -691,7 +681,7 @@ typedef struct /** @defgroup TIM_Break_Polarity TIM Break Input Polarity * @{ */ -#define TIM_BREAKPOLARITY_LOW 0x00000000U +#define TIM_BREAKPOLARITY_LOW ((uint32_t)0x0000) #define TIM_BREAKPOLARITY_HIGH (TIM_BDTR_BKP) /** * @} @@ -700,7 +690,7 @@ typedef struct * @{ */ #define TIM_AUTOMATICOUTPUT_ENABLE (TIM_BDTR_AOE) -#define TIM_AUTOMATICOUTPUT_DISABLE 0x00000000U +#define TIM_AUTOMATICOUTPUT_DISABLE ((uint32_t)0x0000) /** * @} */ @@ -708,7 +698,7 @@ typedef struct /** @defgroup TIM_Master_Mode_Selection TIM Master Mode Selection * @{ */ -#define TIM_TRGO_RESET 0x00000000U +#define TIM_TRGO_RESET ((uint32_t)0x0000) #define TIM_TRGO_ENABLE (TIM_CR2_MMS_0) #define TIM_TRGO_UPDATE (TIM_CR2_MMS_1) #define TIM_TRGO_OC1 ((TIM_CR2_MMS_1 | TIM_CR2_MMS_0)) @@ -723,11 +713,11 @@ typedef struct /** @defgroup TIM_Slave_Mode TIM Slave Mode * @{ */ -#define TIM_SLAVEMODE_DISABLE 0x00000000U -#define TIM_SLAVEMODE_RESET 0x00000004U -#define TIM_SLAVEMODE_GATED 0x00000005U -#define TIM_SLAVEMODE_TRIGGER 0x00000006U -#define TIM_SLAVEMODE_EXTERNAL1 0x00000007U +#define TIM_SLAVEMODE_DISABLE ((uint32_t)0x0000) +#define TIM_SLAVEMODE_RESET ((uint32_t)0x0004) +#define TIM_SLAVEMODE_GATED ((uint32_t)0x0005) +#define TIM_SLAVEMODE_TRIGGER ((uint32_t)0x0006) +#define TIM_SLAVEMODE_EXTERNAL1 ((uint32_t)0x0007) /** * @} */ @@ -735,8 +725,8 @@ typedef struct /** @defgroup TIM_Master_Slave_Mode TIM Master Slave Mode * @{ */ -#define TIM_MASTERSLAVEMODE_ENABLE 0x00000080U -#define TIM_MASTERSLAVEMODE_DISABLE 0x00000000U +#define TIM_MASTERSLAVEMODE_ENABLE ((uint32_t)0x0080) +#define TIM_MASTERSLAVEMODE_DISABLE ((uint32_t)0x0000) /** * @} */ @@ -744,15 +734,15 @@ typedef struct /** @defgroup TIM_Trigger_Selection TIM Trigger Selection * @{ */ -#define TIM_TS_ITR0 0x00000000U -#define TIM_TS_ITR1 0x00000010U -#define TIM_TS_ITR2 0x00000020U -#define TIM_TS_ITR3 0x00000030U -#define TIM_TS_TI1F_ED 0x00000040U -#define TIM_TS_TI1FP1 0x00000050U -#define TIM_TS_TI2FP2 0x00000060U -#define TIM_TS_ETRF 0x00000070U -#define TIM_TS_NONE 0x0000FFFFU +#define TIM_TS_ITR0 ((uint32_t)0x0000) +#define TIM_TS_ITR1 ((uint32_t)0x0010) +#define TIM_TS_ITR2 ((uint32_t)0x0020) +#define TIM_TS_ITR3 ((uint32_t)0x0030) +#define TIM_TS_TI1F_ED ((uint32_t)0x0040) +#define TIM_TS_TI1FP1 ((uint32_t)0x0050) +#define TIM_TS_TI2FP2 ((uint32_t)0x0060) +#define TIM_TS_ETRF ((uint32_t)0x0070) +#define TIM_TS_NONE ((uint32_t)0xFFFF) /** * @} */ @@ -783,7 +773,7 @@ typedef struct /** @defgroup TIM_TI1_Selection TIM TI1 Input Selection * @{ */ -#define TIM_TI1SELECTION_CH1 0x00000000U +#define TIM_TI1SELECTION_CH1 ((uint32_t)0x0000) #define TIM_TI1SELECTION_XORCOMBINATION (TIM_CR2_TI1S) /** * @} @@ -792,25 +782,25 @@ typedef struct /** @defgroup TIM_DMA_Base_address TIM DMA Base Address * @{ */ -#define TIM_DMABASE_CR1 0x00000000U -#define TIM_DMABASE_CR2 0x00000001U -#define TIM_DMABASE_SMCR 0x00000002U -#define TIM_DMABASE_DIER 0x00000003U -#define TIM_DMABASE_SR 0x00000004U -#define TIM_DMABASE_EGR 0x00000005U -#define TIM_DMABASE_CCMR1 0x00000006U -#define TIM_DMABASE_CCMR2 0x00000007U -#define TIM_DMABASE_CCER 0x00000008U -#define TIM_DMABASE_CNT 0x00000009U -#define TIM_DMABASE_PSC 0x0000000AU -#define TIM_DMABASE_ARR 0x0000000BU -#define TIM_DMABASE_RCR 0x0000000CU -#define TIM_DMABASE_CCR1 0x0000000DU -#define TIM_DMABASE_CCR2 0x0000000EU -#define TIM_DMABASE_CCR3 0x0000000FU -#define TIM_DMABASE_CCR4 0x00000010U -#define TIM_DMABASE_BDTR 0x00000011U -#define TIM_DMABASE_DCR 0x00000012U +#define TIM_DMABASE_CR1 (0x00000000) +#define TIM_DMABASE_CR2 (0x00000001) +#define TIM_DMABASE_SMCR (0x00000002) +#define TIM_DMABASE_DIER (0x00000003) +#define TIM_DMABASE_SR (0x00000004) +#define TIM_DMABASE_EGR (0x00000005) +#define TIM_DMABASE_CCMR1 (0x00000006) +#define TIM_DMABASE_CCMR2 (0x00000007) +#define TIM_DMABASE_CCER (0x00000008) +#define TIM_DMABASE_CNT (0x00000009) +#define TIM_DMABASE_PSC (0x0000000A) +#define TIM_DMABASE_ARR (0x0000000B) +#define TIM_DMABASE_RCR (0x0000000C) +#define TIM_DMABASE_CCR1 (0x0000000D) +#define TIM_DMABASE_CCR2 (0x0000000E) +#define TIM_DMABASE_CCR3 (0x0000000F) +#define TIM_DMABASE_CCR4 (0x00000010) +#define TIM_DMABASE_BDTR (0x00000011) +#define TIM_DMABASE_DCR (0x00000012) /** * @} */ @@ -818,24 +808,24 @@ typedef struct /** @defgroup TIM_DMA_Burst_Length TIM DMA Burst Length * @{ */ -#define TIM_DMABURSTLENGTH_1TRANSFER 0x00000000U -#define TIM_DMABURSTLENGTH_2TRANSFERS 0x00000100U -#define TIM_DMABURSTLENGTH_3TRANSFERS 0x00000200U -#define TIM_DMABURSTLENGTH_4TRANSFERS 0x00000300U -#define TIM_DMABURSTLENGTH_5TRANSFERS 0x00000400U -#define TIM_DMABURSTLENGTH_6TRANSFERS 0x00000500U -#define TIM_DMABURSTLENGTH_7TRANSFERS 0x00000600U -#define TIM_DMABURSTLENGTH_8TRANSFERS 0x00000700U -#define TIM_DMABURSTLENGTH_9TRANSFERS 0x00000800U -#define TIM_DMABURSTLENGTH_10TRANSFERS 0x00000900U -#define TIM_DMABURSTLENGTH_11TRANSFERS 0x00000A00U -#define TIM_DMABURSTLENGTH_12TRANSFERS 0x00000B00U -#define TIM_DMABURSTLENGTH_13TRANSFERS 0x00000C00U -#define TIM_DMABURSTLENGTH_14TRANSFERS 0x00000D00U -#define TIM_DMABURSTLENGTH_15TRANSFERS 0x00000E00U -#define TIM_DMABURSTLENGTH_16TRANSFERS 0x00000F00U -#define TIM_DMABURSTLENGTH_17TRANSFERS 0x00001000U -#define TIM_DMABURSTLENGTH_18TRANSFERS 0x00001100U +#define TIM_DMABURSTLENGTH_1TRANSFER (0x00000000) +#define TIM_DMABURSTLENGTH_2TRANSFERS (0x00000100) +#define TIM_DMABURSTLENGTH_3TRANSFERS (0x00000200) +#define TIM_DMABURSTLENGTH_4TRANSFERS (0x00000300) +#define TIM_DMABURSTLENGTH_5TRANSFERS (0x00000400) +#define TIM_DMABURSTLENGTH_6TRANSFERS (0x00000500) +#define TIM_DMABURSTLENGTH_7TRANSFERS (0x00000600) +#define TIM_DMABURSTLENGTH_8TRANSFERS (0x00000700) +#define TIM_DMABURSTLENGTH_9TRANSFERS (0x00000800) +#define TIM_DMABURSTLENGTH_10TRANSFERS (0x00000900) +#define TIM_DMABURSTLENGTH_11TRANSFERS (0x00000A00) +#define TIM_DMABURSTLENGTH_12TRANSFERS (0x00000B00) +#define TIM_DMABURSTLENGTH_13TRANSFERS (0x00000C00) +#define TIM_DMABURSTLENGTH_14TRANSFERS (0x00000D00) +#define TIM_DMABURSTLENGTH_15TRANSFERS (0x00000E00) +#define TIM_DMABURSTLENGTH_16TRANSFERS (0x00000F00) +#define TIM_DMABURSTLENGTH_17TRANSFERS (0x00001000) +#define TIM_DMABURSTLENGTH_18TRANSFERS (0x00001100) /** * @} */ @@ -843,13 +833,13 @@ typedef struct /** @defgroup TIM_DMA_Handle_index TIM DMA Handle Index * @{ */ -#define TIM_DMA_ID_UPDATE ((uint16_t)0x0) /*!< Index of the DMA handle used for Update DMA requests */ -#define TIM_DMA_ID_CC1 ((uint16_t)0x1) /*!< Index of the DMA handle used for Capture/Compare 1 DMA requests */ -#define TIM_DMA_ID_CC2 ((uint16_t)0x2) /*!< Index of the DMA handle used for Capture/Compare 2 DMA requests */ -#define TIM_DMA_ID_CC3 ((uint16_t)0x3) /*!< Index of the DMA handle used for Capture/Compare 3 DMA requests */ -#define TIM_DMA_ID_CC4 ((uint16_t)0x4) /*!< Index of the DMA handle used for Capture/Compare 4 DMA requests */ -#define TIM_DMA_ID_COMMUTATION ((uint16_t)0x5) /*!< Index of the DMA handle used for Commutation DMA requests */ -#define TIM_DMA_ID_TRIGGER ((uint16_t)0x6) /*!< Index of the DMA handle used for Trigger DMA requests */ +#define TIM_DMA_ID_UPDATE ((uint16_t) 0x0) /*!< Index of the DMA handle used for Update DMA requests */ +#define TIM_DMA_ID_CC1 ((uint16_t) 0x1) /*!< Index of the DMA handle used for Capture/Compare 1 DMA requests */ +#define TIM_DMA_ID_CC2 ((uint16_t) 0x2) /*!< Index of the DMA handle used for Capture/Compare 2 DMA requests */ +#define TIM_DMA_ID_CC3 ((uint16_t) 0x3) /*!< Index of the DMA handle used for Capture/Compare 3 DMA requests */ +#define TIM_DMA_ID_CC4 ((uint16_t) 0x4) /*!< Index of the DMA handle used for Capture/Compare 4 DMA requests */ +#define TIM_DMA_ID_COMMUTATION ((uint16_t) 0x5) /*!< Index of the DMA handle used for Commutation DMA requests */ +#define TIM_DMA_ID_TRIGGER ((uint16_t) 0x6) /*!< Index of the DMA handle used for Trigger DMA requests */ /** * @} */ @@ -857,10 +847,10 @@ typedef struct /** @defgroup TIM_Channel_CC_State TIM Capture/Compare Channel State * @{ */ -#define TIM_CCx_ENABLE 0x00000001U -#define TIM_CCx_DISABLE 0x00000000U -#define TIM_CCxN_ENABLE 0x00000004U -#define TIM_CCxN_DISABLE 0x00000000U +#define TIM_CCx_ENABLE ((uint32_t)0x0001) +#define TIM_CCx_DISABLE ((uint32_t)0x0000) +#define TIM_CCxN_ENABLE ((uint32_t)0x0004) +#define TIM_CCxN_DISABLE ((uint32_t)0x0000) /** * @} */ @@ -898,9 +888,6 @@ typedef struct ((DIV) == TIM_CLOCKDIVISION_DIV2) || \ ((DIV) == TIM_CLOCKDIVISION_DIV4)) -#define IS_TIM_AUTORELOAD_PRELOAD(PRELOAD) (((PRELOAD) == TIM_AUTORELOAD_PRELOAD_DISABLE) || \ - ((PRELOAD) == TIM_AUTORELOAD_PRELOAD_ENABLE)) - #define IS_TIM_PWM_MODE(MODE) (((MODE) == TIM_OCMODE_PWM1) || \ ((MODE) == TIM_OCMODE_PWM2)) @@ -931,16 +918,17 @@ typedef struct ((CHANNEL) == TIM_CHANNEL_3) || \ ((CHANNEL) == TIM_CHANNEL_4) || \ ((CHANNEL) == TIM_CHANNEL_ALL)) - + #define IS_TIM_OPM_CHANNELS(CHANNEL) (((CHANNEL) == TIM_CHANNEL_1) || \ - ((CHANNEL) == TIM_CHANNEL_2)) - + ((CHANNEL) == TIM_CHANNEL_2)) + #define IS_TIM_COMPLEMENTARY_CHANNELS(CHANNEL) (((CHANNEL) == TIM_CHANNEL_1) || \ ((CHANNEL) == TIM_CHANNEL_2) || \ ((CHANNEL) == TIM_CHANNEL_3)) #define IS_TIM_IC_POLARITY(POLARITY) (((POLARITY) == TIM_ICPOLARITY_RISING) || \ - ((POLARITY) == TIM_ICPOLARITY_FALLING)) + ((POLARITY) == TIM_ICPOLARITY_FALLING) || \ + ((POLARITY) == TIM_ICPOLARITY_BOTHEDGE)) #define IS_TIM_IC_SELECTION(SELECTION) (((SELECTION) == TIM_ICSELECTION_DIRECTTI) || \ ((SELECTION) == TIM_ICSELECTION_INDIRECTTI) || \ @@ -958,9 +946,9 @@ typedef struct ((MODE) == TIM_ENCODERMODE_TI2) || \ ((MODE) == TIM_ENCODERMODE_TI12)) -#define IS_TIM_DMA_SOURCE(SOURCE) ((((SOURCE) & 0xFFFF80FFU) == 0x00000000U) && ((SOURCE) != 0x00000000U)) +#define IS_TIM_DMA_SOURCE(SOURCE) ((((SOURCE) & 0xFFFF80FF) == 0x00000000) && ((SOURCE) != 0x00000000)) -#define IS_TIM_EVENT_SOURCE(SOURCE) ((((SOURCE) & 0xFFFFFF00U) == 0x00000000U) && ((SOURCE) != 0x00000000U)) +#define IS_TIM_EVENT_SOURCE(SOURCE) ((((SOURCE) & 0xFFFFFF00) == 0x00000000) && ((SOURCE) != 0x00000000)) #define IS_TIM_CLOCKSOURCE(CLOCK) (((CLOCK) == TIM_CLOCKSOURCE_INTERNAL) || \ ((CLOCK) == TIM_CLOCKSOURCE_ETRMODE2) || \ @@ -984,9 +972,10 @@ typedef struct ((PRESCALER) == TIM_CLOCKPRESCALER_DIV4) || \ ((PRESCALER) == TIM_CLOCKPRESCALER_DIV8)) -#define IS_TIM_CLOCKFILTER(ICFILTER) ((ICFILTER) <= 0x0FU) +#define IS_TIM_CLOCKFILTER(ICFILTER) ((ICFILTER) <= 0xF) #define IS_TIM_CLEARINPUT_SOURCE(SOURCE) (((SOURCE) == TIM_CLEARINPUTSOURCE_ETR) || \ + ((SOURCE) == TIM_CLEARINPUTSOURCE_OCREFCLR) || \ ((SOURCE) == TIM_CLEARINPUTSOURCE_NONE)) #define IS_TIM_CLEARINPUT_POLARITY(POLARITY) (((POLARITY) == TIM_CLEARINPUTPOLARITY_INVERTED) || \ @@ -997,7 +986,7 @@ typedef struct ((PRESCALER) == TIM_CLEARINPUTPRESCALER_DIV4) || \ ((PRESCALER) == TIM_CLEARINPUTPRESCALER_DIV8)) -#define IS_TIM_CLEARINPUT_FILTER(ICFILTER) ((ICFILTER) <= 0x0FU) +#define IS_TIM_CLEARINPUT_FILTER(ICFILTER) ((ICFILTER) <= 0xF) #define IS_TIM_OSSR_STATE(STATE) (((STATE) == TIM_OSSR_ENABLE) || \ ((STATE) == TIM_OSSR_DISABLE)) @@ -1063,7 +1052,7 @@ typedef struct ((PRESCALER) == TIM_TRIGGERPRESCALER_DIV4) || \ ((PRESCALER) == TIM_TRIGGERPRESCALER_DIV8)) -#define IS_TIM_TRIGGERFILTER(ICFILTER) ((ICFILTER) <= 0x0FU) +#define IS_TIM_TRIGGERFILTER(ICFILTER) ((ICFILTER) <= 0xF) #define IS_TIM_TI1SELECTION(TI1SELECTION) (((TI1SELECTION) == TIM_TI1SELECTION_CH1) || \ ((TI1SELECTION) == TIM_TI1SELECTION_XORCOMBINATION)) @@ -1107,7 +1096,7 @@ typedef struct ((LENGTH) == TIM_DMABURSTLENGTH_17TRANSFERS) || \ ((LENGTH) == TIM_DMABURSTLENGTH_18TRANSFERS)) -#define IS_TIM_IC_FILTER(ICFILTER) ((ICFILTER) <= 0x0FU) +#define IS_TIM_IC_FILTER(ICFILTER) ((ICFILTER) <= 0xF) /** @brief Set TIM IC prescaler * @param __HANDLE__: TIM handle @@ -1117,9 +1106,9 @@ typedef struct */ #define TIM_SET_ICPRESCALERVALUE(__HANDLE__, __CHANNEL__, __ICPSC__) \ (((__CHANNEL__) == TIM_CHANNEL_1) ? ((__HANDLE__)->Instance->CCMR1 |= (__ICPSC__)) :\ - ((__CHANNEL__) == TIM_CHANNEL_2) ? ((__HANDLE__)->Instance->CCMR1 |= ((__ICPSC__) << 8U)) :\ + ((__CHANNEL__) == TIM_CHANNEL_2) ? ((__HANDLE__)->Instance->CCMR1 |= ((__ICPSC__) << 8)) :\ ((__CHANNEL__) == TIM_CHANNEL_3) ? ((__HANDLE__)->Instance->CCMR2 |= (__ICPSC__)) :\ - ((__HANDLE__)->Instance->CCMR2 |= ((__ICPSC__) << 8U))) + ((__HANDLE__)->Instance->CCMR2 |= ((__ICPSC__) << 8))) /** @brief Reset TIM IC prescaler * @param __HANDLE__: TIM handle @@ -1141,9 +1130,9 @@ typedef struct */ #define TIM_SET_CAPTUREPOLARITY(__HANDLE__, __CHANNEL__, __POLARITY__) \ (((__CHANNEL__) == TIM_CHANNEL_1) ? ((__HANDLE__)->Instance->CCER |= (__POLARITY__)) :\ - ((__CHANNEL__) == TIM_CHANNEL_2) ? ((__HANDLE__)->Instance->CCER |= ((__POLARITY__) << 4U)) :\ - ((__CHANNEL__) == TIM_CHANNEL_3) ? ((__HANDLE__)->Instance->CCER |= ((__POLARITY__) << 8U)) :\ - ((__HANDLE__)->Instance->CCER |= (((__POLARITY__) << 12U) & TIM_CCER_CC4P))) + ((__CHANNEL__) == TIM_CHANNEL_2) ? ((__HANDLE__)->Instance->CCER |= ((__POLARITY__) << 4)) :\ + ((__CHANNEL__) == TIM_CHANNEL_3) ? ((__HANDLE__)->Instance->CCER |= ((__POLARITY__) << 8)) :\ + ((__HANDLE__)->Instance->CCER |= (((__POLARITY__) << 12) & TIM_CCER_CC4P))) /** @brief Reset TIM IC polarity * @param __HANDLE__: TIM handle @@ -1207,14 +1196,14 @@ void TIM_CCxChannelCmd(TIM_TypeDef* TIMx, uint32_t Channel, uint32_t ChannelStat */ #define __HAL_TIM_DISABLE(__HANDLE__) \ do { \ - if (((__HANDLE__)->Instance->CCER & TIM_CCER_CCxE_MASK) == 0U) \ + if (((__HANDLE__)->Instance->CCER & TIM_CCER_CCxE_MASK) == 0) \ { \ - if(((__HANDLE__)->Instance->CCER & TIM_CCER_CCxNE_MASK) == 0U) \ + if(((__HANDLE__)->Instance->CCER & TIM_CCER_CCxNE_MASK) == 0) \ { \ (__HANDLE__)->Instance->CR1 &= ~(TIM_CR1_CEN); \ } \ } \ - } while(0U) + } while(0) /* The Main Output Enable of a timer instance is disabled only if all the CCx and CCxN channels have been disabled */ /** @@ -1225,22 +1214,14 @@ void TIM_CCxChannelCmd(TIM_TypeDef* TIMx, uint32_t Channel, uint32_t ChannelStat */ #define __HAL_TIM_MOE_DISABLE(__HANDLE__) \ do { \ - if (((__HANDLE__)->Instance->CCER & TIM_CCER_CCxE_MASK) == 0U) \ + if (((__HANDLE__)->Instance->CCER & TIM_CCER_CCxE_MASK) == 0) \ { \ - if(((__HANDLE__)->Instance->CCER & TIM_CCER_CCxNE_MASK) == 0U) \ + if(((__HANDLE__)->Instance->CCER & TIM_CCER_CCxNE_MASK) == 0) \ { \ (__HANDLE__)->Instance->BDTR &= ~(TIM_BDTR_MOE); \ } \ } \ - } while(0U) - -/** - * @brief Disable the TIM main Output. - * @param __HANDLE__: TIM handle - * @retval None - * @note The Main Output Enable of a timer instance is disabled unconditionally - */ -#define __HAL_TIM_MOE_DISABLE_UNCONDITIONALLY(__HANDLE__) (__HANDLE__)->Instance->BDTR &= ~(TIM_BDTR_MOE) + } while(0) /** * @brief Enables the specified TIM interrupt. @@ -1248,11 +1229,11 @@ void TIM_CCxChannelCmd(TIM_TypeDef* TIMx, uint32_t Channel, uint32_t ChannelStat * @param __INTERRUPT__: specifies the TIM interrupt source to enable. * This parameter can be one of the following values: * @arg TIM_IT_UPDATE: Update interrupt - * @arg TIM_IT_CC1: Capture/Compare 1 interrupt + * @arg TIM_IT_CC1: Capture/Compare 1 interrupt * @arg TIM_IT_CC2: Capture/Compare 2 interrupt * @arg TIM_IT_CC3: Capture/Compare 3 interrupt * @arg TIM_IT_CC4: Capture/Compare 4 interrupt - * @arg TIM_IT_COM: Commutation interrupt + * @arg TIM_IT_COM: Commutation interrupt * @arg TIM_IT_TRIGGER: Trigger interrupt * @arg TIM_IT_BREAK: Break interrupt * @retval None @@ -1265,11 +1246,11 @@ void TIM_CCxChannelCmd(TIM_TypeDef* TIMx, uint32_t Channel, uint32_t ChannelStat * @param __INTERRUPT__: specifies the TIM interrupt source to disable. * This parameter can be one of the following values: * @arg TIM_IT_UPDATE: Update interrupt - * @arg TIM_IT_CC1: Capture/Compare 1 interrupt + * @arg TIM_IT_CC1: Capture/Compare 1 interrupt * @arg TIM_IT_CC2: Capture/Compare 2 interrupt * @arg TIM_IT_CC3: Capture/Compare 3 interrupt * @arg TIM_IT_CC4: Capture/Compare 4 interrupt - * @arg TIM_IT_COM: Commutation interrupt + * @arg TIM_IT_COM: Commutation interrupt * @arg TIM_IT_TRIGGER: Trigger interrupt * @arg TIM_IT_BREAK: Break interrupt * @retval None @@ -1282,11 +1263,11 @@ void TIM_CCxChannelCmd(TIM_TypeDef* TIMx, uint32_t Channel, uint32_t ChannelStat * @param __DMA__: specifies the TIM DMA request to enable. * This parameter can be one of the following values: * @arg TIM_DMA_UPDATE: Update DMA request - * @arg TIM_DMA_CC1: Capture/Compare 1 DMA request + * @arg TIM_DMA_CC1: Capture/Compare 1 DMA request * @arg TIM_DMA_CC2: Capture/Compare 2 DMA request * @arg TIM_DMA_CC3: Capture/Compare 3 DMA request * @arg TIM_DMA_CC4: Capture/Compare 4 DMA request - * @arg TIM_DMA_COM: Commutation DMA request + * @arg TIM_DMA_COM: Commutation DMA request * @arg TIM_DMA_TRIGGER: Trigger DMA request * @retval None */ @@ -1298,11 +1279,11 @@ void TIM_CCxChannelCmd(TIM_TypeDef* TIMx, uint32_t Channel, uint32_t ChannelStat * @param __DMA__: specifies the TIM DMA request to disable. * This parameter can be one of the following values: * @arg TIM_DMA_UPDATE: Update DMA request - * @arg TIM_DMA_CC1: Capture/Compare 1 DMA request + * @arg TIM_DMA_CC1: Capture/Compare 1 DMA request * @arg TIM_DMA_CC2: Capture/Compare 2 DMA request * @arg TIM_DMA_CC3: Capture/Compare 3 DMA request * @arg TIM_DMA_CC4: Capture/Compare 4 DMA request - * @arg TIM_DMA_COM: Commutation DMA request + * @arg TIM_DMA_COM: Commutation DMA request * @arg TIM_DMA_TRIGGER: Trigger DMA request * @retval None */ @@ -1397,7 +1378,7 @@ mode. * @retval None */ #define __HAL_TIM_SET_COMPARE(__HANDLE__, __CHANNEL__, __COMPARE__) \ -(*(__IO uint32_t *)(&((__HANDLE__)->Instance->CCR1) + ((__CHANNEL__) >> 2U)) = (__COMPARE__)) +(*(__IO uint32_t *)(&((__HANDLE__)->Instance->CCR1) + ((__CHANNEL__) >> 2)) = (__COMPARE__)) /** * @brief Gets the TIM Capture Compare Register value on runtime @@ -1408,10 +1389,10 @@ mode. * @arg TIM_CHANNEL_2: get capture/compare 2 register value * @arg TIM_CHANNEL_3: get capture/compare 3 register value * @arg TIM_CHANNEL_4: get capture/compare 4 register value - * @retval 16-bit or 32-bit value of the capture/compare register (TIMx_CCRy) + * @retval None */ #define __HAL_TIM_GET_COMPARE(__HANDLE__, __CHANNEL__) \ - (*(__IO uint32_t *)(&((__HANDLE__)->Instance->CCR1) + ((__CHANNEL__) >> 2U))) + (*(__IO uint32_t *)(&((__HANDLE__)->Instance->CCR1) + ((__CHANNEL__) >> 2))) /** * @brief Sets the TIM Counter Register value on runtime. @@ -1424,7 +1405,7 @@ mode. /** * @brief Gets the TIM Counter Register value on runtime. * @param __HANDLE__: TIM handle. - * @retval 16-bit or 32-bit value of the timer counter register (TIMx_CNT) + * @retval None */ #define __HAL_TIM_GET_COUNTER(__HANDLE__) \ ((__HANDLE__)->Instance->CNT) @@ -1440,12 +1421,12 @@ mode. do{ \ (__HANDLE__)->Instance->ARR = (__AUTORELOAD__); \ (__HANDLE__)->Init.Period = (__AUTORELOAD__); \ - } while(0U) + } while(0) /** * @brief Gets the TIM Autoreload Register value on runtime * @param __HANDLE__: TIM handle. - * @retval @retval 16-bit or 32-bit value of the timer auto-reload register(TIMx_ARR) + * @retval None */ #define __HAL_TIM_GET_AUTORELOAD(__HANDLE__) \ ((__HANDLE__)->Instance->ARR) @@ -1456,25 +1437,22 @@ mode. * @param __HANDLE__: TIM handle. * @param __CKD__: specifies the clock division value. * This parameter can be one of the following value: - * @arg TIM_CLOCKDIVISION_DIV1: tDTS=tCK_INT - * @arg TIM_CLOCKDIVISION_DIV2: tDTS=2*tCK_INT - * @arg TIM_CLOCKDIVISION_DIV4: tDTS=4*tCK_INT + * @arg TIM_CLOCKDIVISION_DIV1 + * @arg TIM_CLOCKDIVISION_DIV2 + * @arg TIM_CLOCKDIVISION_DIV4 * @retval None */ #define __HAL_TIM_SET_CLOCKDIVISION(__HANDLE__, __CKD__) \ - do{ \ + do{ \ (__HANDLE__)->Instance->CR1 &= (uint16_t)(~TIM_CR1_CKD); \ - (__HANDLE__)->Instance->CR1 |= (__CKD__); \ + (__HANDLE__)->Instance->CR1 |= (__CKD__); \ (__HANDLE__)->Init.ClockDivision = (__CKD__); \ - } while(0U) + } while(0) /** * @brief Gets the TIM Clock Division value on runtime * @param __HANDLE__: TIM handle. - * @retval The clock division can be one of the following values: - * @arg TIM_CLOCKDIVISION_DIV1: tDTS=tCK_INT - * @arg TIM_CLOCKDIVISION_DIV2: tDTS=2*tCK_INT - * @arg TIM_CLOCKDIVISION_DIV4: tDTS=4*tCK_INT + * @retval None */ #define __HAL_TIM_GET_CLOCKDIVISION(__HANDLE__) \ ((__HANDLE__)->Instance->CR1 & TIM_CR1_CKD) @@ -1501,7 +1479,7 @@ mode. do{ \ TIM_RESET_ICPRESCALERVALUE((__HANDLE__), (__CHANNEL__)); \ TIM_SET_ICPRESCALERVALUE((__HANDLE__), (__CHANNEL__), (__ICPSC__)); \ - } while(0U) + } while(0) /** * @brief Gets the TIM Input Capture prescaler on runtime @@ -1512,17 +1490,13 @@ mode. * @arg TIM_CHANNEL_2: get input capture 2 prescaler value * @arg TIM_CHANNEL_3: get input capture 3 prescaler value * @arg TIM_CHANNEL_4: get input capture 4 prescaler value - * @retval The input capture prescaler can be one of the following values: - * @arg TIM_ICPSC_DIV1: no prescaler - * @arg TIM_ICPSC_DIV2: capture is done once every 2 events - * @arg TIM_ICPSC_DIV4: capture is done once every 4 events - * @arg TIM_ICPSC_DIV8: capture is done once every 8 events + * @retval None */ #define __HAL_TIM_GET_ICPRESCALER(__HANDLE__, __CHANNEL__) \ (((__CHANNEL__) == TIM_CHANNEL_1) ? ((__HANDLE__)->Instance->CCMR1 & TIM_CCMR1_IC1PSC) :\ - ((__CHANNEL__) == TIM_CHANNEL_2) ? (((__HANDLE__)->Instance->CCMR1 & TIM_CCMR1_IC2PSC) >> 8U) :\ + ((__CHANNEL__) == TIM_CHANNEL_2) ? (((__HANDLE__)->Instance->CCMR1 & TIM_CCMR1_IC2PSC) >> 8) :\ ((__CHANNEL__) == TIM_CHANNEL_3) ? ((__HANDLE__)->Instance->CCMR2 & TIM_CCMR2_IC3PSC) :\ - (((__HANDLE__)->Instance->CCMR2 & TIM_CCMR2_IC4PSC)) >> 8U) + (((__HANDLE__)->Instance->CCMR2 & TIM_CCMR2_IC4PSC)) >> 8) /** * @brief Set the Update Request Source (URS) bit of the TIMx_CR1 register @@ -1569,7 +1543,7 @@ mode. do{ \ TIM_RESET_CAPTUREPOLARITY((__HANDLE__), (__CHANNEL__)); \ TIM_SET_CAPTUREPOLARITY((__HANDLE__), (__CHANNEL__), (__POLARITY__)); \ - }while(0U) + }while(0) /** * @} diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_tim_ex.c b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_tim_ex.c index 9fae96da0d3..1a0daa6696f 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_tim_ex.c +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_tim_ex.c @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_hal_tim_ex.c * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief TIM HAL module driver. * This file provides firmware functions to manage the following * functionalities of the Timer Extended peripheral: @@ -177,7 +177,6 @@ HAL_StatusTypeDef HAL_TIMEx_HallSensor_Init(TIM_HandleTypeDef *htim, TIM_HallSen assert_param(IS_TIM_XOR_INSTANCE(htim->Instance)); assert_param(IS_TIM_COUNTER_MODE(htim->Init.CounterMode)); assert_param(IS_TIM_CLOCKDIVISION_DIV(htim->Init.ClockDivision)); - assert_param(IS_TIM_AUTORELOAD_PRELOAD(htim->Init.AutoReloadPreload)); assert_param(IS_TIM_IC_POLARITY(sConfig->IC1Polarity)); assert_param(IS_TIM_IC_PRESCALER(sConfig->IC1Prescaler)); assert_param(IS_TIM_IC_FILTER(sConfig->IC1Filter)); @@ -401,7 +400,7 @@ HAL_StatusTypeDef HAL_TIMEx_HallSensor_Start_DMA(TIM_HandleTypeDef *htim, uint32 } else if((htim->State == HAL_TIM_STATE_READY)) { - if(((uint32_t)pData == 0U) && (Length > 0U)) + if(((uint32_t)pData == 0 ) && (Length > 0)) { return HAL_ERROR; } @@ -626,7 +625,7 @@ HAL_StatusTypeDef HAL_TIMEx_OCN_Start_IT(TIM_HandleTypeDef *htim, uint32_t Chann */ HAL_StatusTypeDef HAL_TIMEx_OCN_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel) { - uint32_t tmpccer = 0U; + uint32_t tmpccer = 0; /* Check the parameters */ assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel)); @@ -710,7 +709,7 @@ HAL_StatusTypeDef HAL_TIMEx_OCN_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Chan } else if((htim->State == HAL_TIM_STATE_READY)) { - if(((uint32_t)pData == 0U) && (Length > 0U)) + if(((uint32_t)pData == 0 ) && (Length > 0)) { return HAL_ERROR; } @@ -1042,7 +1041,7 @@ HAL_StatusTypeDef HAL_TIMEx_PWMN_Start_IT(TIM_HandleTypeDef *htim, uint32_t Chan */ HAL_StatusTypeDef HAL_TIMEx_PWMN_Stop_IT (TIM_HandleTypeDef *htim, uint32_t Channel) { - uint32_t tmpccer = 0U; + uint32_t tmpccer = 0; /* Check the parameters */ assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel)); @@ -1126,7 +1125,7 @@ HAL_StatusTypeDef HAL_TIMEx_PWMN_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Cha } else if((htim->State == HAL_TIM_STATE_READY)) { - if(((uint32_t)pData == 0U) && (Length > 0U)) + if(((uint32_t)pData == 0 ) && (Length > 0)) { return HAL_ERROR; } @@ -1626,8 +1625,6 @@ HAL_StatusTypeDef HAL_TIMEx_ConfigCommutationEvent_DMA(TIM_HandleTypeDef *htim, HAL_StatusTypeDef HAL_TIMEx_ConfigBreakDeadTime(TIM_HandleTypeDef *htim, TIM_BreakDeadTimeConfigTypeDef *sBreakDeadTimeConfig) { - uint32_t tmpbdtr = 0U; - /* Check the parameters */ assert_param(IS_TIM_BREAK_INSTANCE(htim->Instance)); assert_param(IS_TIM_OSSR_STATE(sBreakDeadTimeConfig->OffStateRunMode)); @@ -1641,22 +1638,21 @@ HAL_StatusTypeDef HAL_TIMEx_ConfigBreakDeadTime(TIM_HandleTypeDef *htim, /* Process Locked */ __HAL_LOCK(htim); + htim->State = HAL_TIM_STATE_BUSY; + /* Set the Lock level, the Break enable Bit and the Polarity, the OSSR State, the OSSI State, the dead time value and the Automatic Output Enable Bit */ - - /* Set the BDTR bits */ - MODIFY_REG(tmpbdtr, TIM_BDTR_DTG, sBreakDeadTimeConfig->DeadTime); - MODIFY_REG(tmpbdtr, TIM_BDTR_LOCK, sBreakDeadTimeConfig->LockLevel); - MODIFY_REG(tmpbdtr, TIM_BDTR_OSSI, sBreakDeadTimeConfig->OffStateIDLEMode); - MODIFY_REG(tmpbdtr, TIM_BDTR_OSSR, sBreakDeadTimeConfig->OffStateRunMode); - MODIFY_REG(tmpbdtr, TIM_BDTR_BKE, sBreakDeadTimeConfig->BreakState); - MODIFY_REG(tmpbdtr, TIM_BDTR_BKP, sBreakDeadTimeConfig->BreakPolarity); - MODIFY_REG(tmpbdtr, TIM_BDTR_AOE, sBreakDeadTimeConfig->AutomaticOutput); - MODIFY_REG(tmpbdtr, TIM_BDTR_MOE, sBreakDeadTimeConfig->AutomaticOutput); - - /* Set TIMx_BDTR */ - htim->Instance->BDTR = tmpbdtr; - + htim->Instance->BDTR = (uint32_t)sBreakDeadTimeConfig->OffStateRunMode | + sBreakDeadTimeConfig->OffStateIDLEMode | + sBreakDeadTimeConfig->LockLevel | + sBreakDeadTimeConfig->DeadTime | + sBreakDeadTimeConfig->BreakState | + sBreakDeadTimeConfig->BreakPolarity | + sBreakDeadTimeConfig->AutomaticOutput; + + + htim->State = HAL_TIM_STATE_READY; + __HAL_UNLOCK(htim); return HAL_OK; @@ -1830,7 +1826,7 @@ HAL_TIM_StateTypeDef HAL_TIMEx_HallSensor_GetState(TIM_HandleTypeDef *htim) */ static void TIM_CCxNChannelCmd(TIM_TypeDef* TIMx, uint32_t Channel, uint32_t ChannelNState) { - uint32_t tmp = 0U; + uint32_t tmp = 0; tmp = TIM_CCER_CC1NE << Channel; diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_tim_ex.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_tim_ex.h index 1e2d4a54634..29380e8f6a8 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_tim_ex.h +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_tim_ex.h @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_hal_tim_ex.h * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief Header file of TIM HAL Extension module. ****************************************************************************** * @attention @@ -66,17 +66,17 @@ typedef struct { - + uint32_t IC1Polarity; /*!< Specifies the active edge of the input signal. This parameter can be a value of @ref TIM_Input_Capture_Polarity */ - + uint32_t IC1Prescaler; /*!< Specifies the Input Capture Prescaler. This parameter can be a value of @ref TIM_Input_Capture_Prescaler */ - + uint32_t IC1Filter; /*!< Specifies the input capture filter. This parameter can be a number between Min_Data = 0x0 and Max_Data = 0xF */ uint32_t Commutation_Delay; /*!< Specifies the pulse value to be loaded into the Capture Compare Register. - This parameter can be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF */ + This parameter can be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF */ } TIM_HallSensor_InitTypeDef; @@ -134,7 +134,7 @@ typedef struct { /** @defgroup TIMEx_Clock_Filter TIMEx Clock Filter * @{ */ -#define IS_TIM_DEADTIME(DEADTIME) ((DEADTIME) <= 0xFFU) /*!< BreakDead Time */ +#define IS_TIM_DEADTIME(DEADTIME) ((DEADTIME) <= 0xFF) /*!< BreakDead Time */ /** * @} */ @@ -147,39 +147,6 @@ typedef struct { /* defined(STM32F105xC) || defined(STM32F107xC) */ /* Exported macro ------------------------------------------------------------*/ -/** - * @brief Sets the TIM Output compare preload. - * @param __HANDLE__: TIM handle. - * @param __CHANNEL__: TIM Channels to be configured. - * This parameter can be one of the following values: - * @arg TIM_CHANNEL_1: TIM Channel 1 selected - * @arg TIM_CHANNEL_2: TIM Channel 2 selected - * @arg TIM_CHANNEL_3: TIM Channel 3 selected - * @arg TIM_CHANNEL_4: TIM Channel 4 selected - * @retval None - */ -#define __HAL_TIM_ENABLE_OCxPRELOAD(__HANDLE__, __CHANNEL__) \ - (((__CHANNEL__) == TIM_CHANNEL_1) ? ((__HANDLE__)->Instance->CCMR1 |= TIM_CCMR1_OC1PE) :\ - ((__CHANNEL__) == TIM_CHANNEL_2) ? ((__HANDLE__)->Instance->CCMR1 |= TIM_CCMR1_OC2PE) :\ - ((__CHANNEL__) == TIM_CHANNEL_3) ? ((__HANDLE__)->Instance->CCMR2 |= TIM_CCMR2_OC3PE) :\ - ((__HANDLE__)->Instance->CCMR2 |= TIM_CCMR2_OC4PE)) - -/** - * @brief Resets the TIM Output compare preload. - * @param __HANDLE__: TIM handle. - * @param __CHANNEL__: TIM Channels to be configured. - * This parameter can be one of the following values: - * @arg TIM_CHANNEL_1: TIM Channel 1 selected - * @arg TIM_CHANNEL_2: TIM Channel 2 selected - * @arg TIM_CHANNEL_3: TIM Channel 3 selected - * @arg TIM_CHANNEL_4: TIM Channel 4 selected - * @retval None - */ -#define __HAL_TIM_DISABLE_OCxPRELOAD(__HANDLE__, __CHANNEL__) \ - (((__CHANNEL__) == TIM_CHANNEL_1) ? ((__HANDLE__)->Instance->CCMR1 &= (uint16_t)~TIM_CCMR1_OC1PE) :\ - ((__CHANNEL__) == TIM_CHANNEL_2) ? ((__HANDLE__)->Instance->CCMR1 &= (uint16_t)~TIM_CCMR1_OC2PE) :\ - ((__CHANNEL__) == TIM_CHANNEL_3) ? ((__HANDLE__)->Instance->CCMR2 &= (uint16_t)~TIM_CCMR2_OC3PE) :\ - ((__HANDLE__)->Instance->CCMR2 &= (uint16_t)~TIM_CCMR2_OC4PE)) /* Exported functions --------------------------------------------------------*/ /** @addtogroup TIMEx_Exported_Functions diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_uart.c b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_uart.c index 0e3e8603e72..b437ce83934 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_uart.c +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_uart.c @@ -2,28 +2,29 @@ ****************************************************************************** * @file stm32f1xx_hal_uart.c * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief UART HAL module driver. * This file provides firmware functions to manage the following * functionalities of the Universal Asynchronous Receiver Transmitter (UART) peripheral: * + Initialization and de-initialization functions * + IO operation functions - * + Peripheral Control functions - * + Peripheral State and Errors functions + * + Peripheral Control functions + * + Peripheral State and Errors functions @verbatim ============================================================================== ##### How to use this driver ##### ============================================================================== [..] The UART HAL driver can be used as follows: - + (#) Declare a UART_HandleTypeDef handle structure. + (#) Initialize the UART low level resources by implementing the HAL_UART_MspInit() API: (##) Enable the USARTx interface clock. (##) UART pins configuration: (+++) Enable the clock for the UART GPIOs. - (+++) Configure the UART pins (TX as alternate function pull-up, RX as alternate function Input). + (+++) Configure the USART pins (TX as alternate function pull-up, RX as alternate function Input). (##) NVIC configuration if you need to use interrupt process (HAL_UART_Transmit_IT() and HAL_UART_Receive_IT() APIs): (+++) Configure the USARTx interrupt priority. @@ -63,18 +64,18 @@ [..] (@) These APIs (HAL_UART_Init() and HAL_HalfDuplex_Init()) configure also the - low level Hardware GPIO, CLOCK, CORTEX...etc) by calling the customized + low level Hardware GPIO, CLOCK, CORTEX...etc) by calling the customed HAL_UART_MspInit() API. - [..] - Three operation modes are available within this driver: + [..] + Three operation modes are available within this driver : *** Polling mode IO operation *** ================================= - [..] - (+) Send an amount of data in blocking mode using HAL_UART_Transmit() + [..] + (+) Send an amount of data in blocking mode using HAL_UART_Transmit() (+) Receive an amount of data in blocking mode using HAL_UART_Receive() - + *** Interrupt mode IO operation *** =================================== [..] @@ -121,27 +122,12 @@ [..] (@) You can refer to the UART HAL driver header file for more useful macros + @endverbatim - [..] - (@) Additionnal remark: If the parity is enabled, then the MSB bit of the data written - in the data register is transmitted but is changed by the parity bit. - Depending on the frame length defined by the M bit (8-bits or 9-bits), - the possible UART frame formats are as listed in the following table: - +-------------------------------------------------------------+ - | M bit | PCE bit | UART frame | - |---------------------|---------------------------------------| - | 0 | 0 | | SB | 8 bit data | STB | | - |---------|-----------|---------------------------------------| - | 0 | 1 | | SB | 7 bit data | PB | STB | | - |---------|-----------|---------------------------------------| - | 1 | 0 | | SB | 9 bit data | STB | | - |---------|-----------|---------------------------------------| - | 1 | 1 | | SB | 8 bit data | PB | STB | | - +-------------------------------------------------------------+ ****************************************************************************** * @attention * - *

© COPYRIGHT(c) 2017 STMicroelectronics

+ *

© COPYRIGHT(c) 2016 STMicroelectronics

* * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: @@ -180,42 +166,31 @@ * @{ */ #ifdef HAL_UART_MODULE_ENABLED - + /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ -/** @addtogroup UART_Private_Constants - * @{ - */ -/** - * @} - */ -/* Private macro -------------------------------------------------------------*/ +/* Private macros ------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ -/** @addtogroup UART_Private_Functions +/** @addtogroup UART_Private_Functions UART Private Functions * @{ */ -static void UART_EndTxTransfer(UART_HandleTypeDef *huart); -static void UART_EndRxTransfer(UART_HandleTypeDef *huart); -static void UART_DMATransmitCplt(DMA_HandleTypeDef *hdma); -static void UART_DMAReceiveCplt(DMA_HandleTypeDef *hdma); -static void UART_DMATxHalfCplt(DMA_HandleTypeDef *hdma); -static void UART_DMARxHalfCplt(DMA_HandleTypeDef *hdma); -static void UART_DMAError(DMA_HandleTypeDef *hdma); -static void UART_DMAAbortOnError(DMA_HandleTypeDef *hdma); -static void UART_DMATxAbortCallback(DMA_HandleTypeDef *hdma); -static void UART_DMARxAbortCallback(DMA_HandleTypeDef *hdma); -static void UART_DMATxOnlyAbortCallback(DMA_HandleTypeDef *hdma); -static void UART_DMARxOnlyAbortCallback(DMA_HandleTypeDef *hdma); +static void UART_SetConfig (UART_HandleTypeDef *huart); static HAL_StatusTypeDef UART_Transmit_IT(UART_HandleTypeDef *huart); static HAL_StatusTypeDef UART_EndTransmit_IT(UART_HandleTypeDef *huart); static HAL_StatusTypeDef UART_Receive_IT(UART_HandleTypeDef *huart); -static HAL_StatusTypeDef UART_WaitOnFlagUntilTimeout(UART_HandleTypeDef *huart, uint32_t Flag, FlagStatus Status, uint32_t Tickstart, uint32_t Timeout); -static void UART_SetConfig (UART_HandleTypeDef *huart); +static void UART_DMATransmitCplt(DMA_HandleTypeDef *hdma); +static void UART_DMATxHalfCplt(DMA_HandleTypeDef *hdma); +static void UART_DMAReceiveCplt(DMA_HandleTypeDef *hdma); +static void UART_DMARxHalfCplt(DMA_HandleTypeDef *hdma); +static void UART_DMAError(DMA_HandleTypeDef *hdma); +static HAL_StatusTypeDef UART_WaitOnFlagUntilTimeout(UART_HandleTypeDef *huart, uint32_t Flag, FlagStatus Status, uint32_t Timeout); /** * @} */ + /* Exported functions ---------------------------------------------------------*/ + /** @defgroup UART_Exported_Functions UART Exported Functions * @{ */ @@ -224,9 +199,9 @@ static void UART_SetConfig (UART_HandleTypeDef *huart); * @brief Initialization and Configuration functions * @verbatim - ============================================================================== +=============================================================================== ##### Initialization and Configuration functions ##### - ============================================================================== + =============================================================================== [..] This subsection provides a set of functions allowing to initialize the USARTx or the UARTy in asynchronous mode. @@ -234,27 +209,42 @@ static void UART_SetConfig (UART_HandleTypeDef *huart); (++) Baud Rate (++) Word Length (++) Stop Bit - (++) Parity: If the parity is enabled, then the MSB bit of the data written - in the data register is transmitted but is changed by the parity bit. - Depending on the frame length defined by the M bit (8-bits or 9-bits), - please refer to Reference manual for possible UART frame formats. + (++) Parity (++) Hardware flow control (++) Receiver/transmitter modes - (++) Over Sampling Method [..] The HAL_UART_Init(), HAL_HalfDuplex_Init(), HAL_LIN_Init() and HAL_MultiProcessor_Init() APIs follow respectively the UART asynchronous, UART Half duplex, LIN and Multi-Processor configuration procedures (details for the procedures are available in reference manuals (RM0008 for STM32F10Xxx MCUs and RM0041 for STM32F100xx MCUs)). + @endverbatim * @{ */ +/* + Additionnal remark: If the parity is enabled, then the MSB bit of the data written + in the data register is transmitted but is changed by the parity bit. + Depending on the frame length defined by the M bit (8-bits or 9-bits), + the possible UART frame formats are as listed in the following table: + +-------------------------------------------------------------+ + | M bit | PCE bit | UART frame | + |---------------------|---------------------------------------| + | 0 | 0 | | SB | 8 bit data | STB | | + |---------|-----------|---------------------------------------| + | 0 | 1 | | SB | 7 bit data | PB | STB | | + |---------|-----------|---------------------------------------| + | 1 | 0 | | SB | 9 bit data | STB | | + |---------|-----------|---------------------------------------| + | 1 | 1 | | SB | 8 bit data | PB | STB | | + +-------------------------------------------------------------+ +*/ + /** * @brief Initializes the UART mode according to the specified parameters in * the UART_InitTypeDef and create the associated handle. - * @param huart: pointer to a UART_HandleTypeDef structure that contains + * @param huart: Pointer to a UART_HandleTypeDef structure that contains * the configuration information for the specified UART module. * @retval HAL status */ @@ -278,20 +268,18 @@ HAL_StatusTypeDef HAL_UART_Init(UART_HandleTypeDef *huart) assert_param(IS_UART_INSTANCE(huart->Instance)); } assert_param(IS_UART_WORD_LENGTH(huart->Init.WordLength)); -#if defined(USART_CR1_OVER8) assert_param(IS_UART_OVERSAMPLING(huart->Init.OverSampling)); -#endif /* USART_CR1_OVER8 */ - if(huart->gState == HAL_UART_STATE_RESET) + if(huart->State == HAL_UART_STATE_RESET) { /* Allocate lock resource and initialize it */ huart->Lock = HAL_UNLOCKED; - + /* Init the low level hardware */ HAL_UART_MspInit(huart); } - huart->gState = HAL_UART_STATE_BUSY; + huart->State = HAL_UART_STATE_BUSY; /* Disable the peripheral */ __HAL_UART_DISABLE(huart); @@ -310,8 +298,7 @@ HAL_StatusTypeDef HAL_UART_Init(UART_HandleTypeDef *huart) /* Initialize the UART state */ huart->ErrorCode = HAL_UART_ERROR_NONE; - huart->gState= HAL_UART_STATE_READY; - huart->RxState= HAL_UART_STATE_READY; + huart->State= HAL_UART_STATE_READY; return HAL_OK; } @@ -319,7 +306,7 @@ HAL_StatusTypeDef HAL_UART_Init(UART_HandleTypeDef *huart) /** * @brief Initializes the half-duplex mode according to the specified * parameters in the UART_InitTypeDef and create the associated handle. - * @param huart: pointer to a UART_HandleTypeDef structure that contains + * @param huart: Pointer to a UART_HandleTypeDef structure that contains * the configuration information for the specified UART module. * @retval HAL status */ @@ -330,22 +317,22 @@ HAL_StatusTypeDef HAL_HalfDuplex_Init(UART_HandleTypeDef *huart) { return HAL_ERROR; } - - /* Check the parameters */ + + /* Check UART instance */ assert_param(IS_UART_HALFDUPLEX_INSTANCE(huart->Instance)); assert_param(IS_UART_WORD_LENGTH(huart->Init.WordLength)); -#if defined(USART_CR1_OVER8) assert_param(IS_UART_OVERSAMPLING(huart->Init.OverSampling)); -#endif /* USART_CR1_OVER8 */ - if(huart->gState == HAL_UART_STATE_RESET) - { + + if(huart->State == HAL_UART_STATE_RESET) + { /* Allocate lock resource and initialize it */ huart->Lock = HAL_UNLOCKED; + /* Init the low level hardware */ HAL_UART_MspInit(huart); } - huart->gState = HAL_UART_STATE_BUSY; + huart->State = HAL_UART_STATE_BUSY; /* Disable the peripheral */ __HAL_UART_DISABLE(huart); @@ -353,7 +340,7 @@ HAL_StatusTypeDef HAL_HalfDuplex_Init(UART_HandleTypeDef *huart) /* Set the UART Communication parameters */ UART_SetConfig(huart); - /* In half-duplex mode, the following bits must be kept cleared: + /* In half-duplex mode, the following bits must be kept cleared: - LINEN and CLKEN bits in the USART_CR2 register, - SCEN and IREN bits in the USART_CR3 register.*/ CLEAR_BIT(huart->Instance->CR2, (USART_CR2_LINEN | USART_CR2_CLKEN)); @@ -367,8 +354,7 @@ HAL_StatusTypeDef HAL_HalfDuplex_Init(UART_HandleTypeDef *huart) /* Initialize the UART state*/ huart->ErrorCode = HAL_UART_ERROR_NONE; - huart->gState= HAL_UART_STATE_READY; - huart->RxState= HAL_UART_STATE_READY; + huart->State= HAL_UART_STATE_READY; return HAL_OK; } @@ -376,7 +362,7 @@ HAL_StatusTypeDef HAL_HalfDuplex_Init(UART_HandleTypeDef *huart) /** * @brief Initializes the LIN mode according to the specified * parameters in the UART_InitTypeDef and create the associated handle. - * @param huart: pointer to a UART_HandleTypeDef structure that contains + * @param huart: Pointer to a UART_HandleTypeDef structure that contains * the configuration information for the specified UART module. * @param BreakDetectLength: Specifies the LIN break detection length. * This parameter can be one of the following values: @@ -397,19 +383,18 @@ HAL_StatusTypeDef HAL_LIN_Init(UART_HandleTypeDef *huart, uint32_t BreakDetectLe /* Check the Break detection length parameter */ assert_param(IS_UART_LIN_BREAK_DETECT_LENGTH(BreakDetectLength)); assert_param(IS_UART_LIN_WORD_LENGTH(huart->Init.WordLength)); -#if defined(USART_CR1_OVER8) assert_param(IS_UART_LIN_OVERSAMPLING(huart->Init.OverSampling)); -#endif /* USART_CR1_OVER8 */ - if(huart->gState == HAL_UART_STATE_RESET) - { + if(huart->State == HAL_UART_STATE_RESET) + { /* Allocate lock resource and initialize it */ - huart->Lock = HAL_UNLOCKED; + huart->Lock = HAL_UNLOCKED; + /* Init the low level hardware */ HAL_UART_MspInit(huart); } - huart->gState = HAL_UART_STATE_BUSY; + huart->State = HAL_UART_STATE_BUSY; /* Disable the peripheral */ __HAL_UART_DISABLE(huart); @@ -434,8 +419,7 @@ HAL_StatusTypeDef HAL_LIN_Init(UART_HandleTypeDef *huart, uint32_t BreakDetectLe /* Initialize the UART state*/ huart->ErrorCode = HAL_UART_ERROR_NONE; - huart->gState= HAL_UART_STATE_READY; - huart->RxState= HAL_UART_STATE_READY; + huart->State= HAL_UART_STATE_READY; return HAL_OK; } @@ -443,13 +427,13 @@ HAL_StatusTypeDef HAL_LIN_Init(UART_HandleTypeDef *huart, uint32_t BreakDetectLe /** * @brief Initializes the Multi-Processor mode according to the specified * parameters in the UART_InitTypeDef and create the associated handle. - * @param huart: pointer to a UART_HandleTypeDef structure that contains + * @param huart: Pointer to a UART_HandleTypeDef structure that contains * the configuration information for the specified UART module. - * @param Address: USART address - * @param WakeUpMethod: specifies the USART wake-up method. + * @param Address: UART node address + * @param WakeUpMethod: specifies the UART wakeup method. * This parameter can be one of the following values: - * @arg UART_WAKEUPMETHOD_IDLELINE: Wake-up by an idle line detection - * @arg UART_WAKEUPMETHOD_ADDRESSMARK: Wake-up by an address mark + * @arg UART_WAKEUPMETHOD_IDLELINE: Wakeup by an idle line detection + * @arg UART_WAKEUPMETHOD_ADDRESSMARK: Wakeup by an address mark * @retval HAL status */ HAL_StatusTypeDef HAL_MultiProcessor_Init(UART_HandleTypeDef *huart, uint8_t Address, uint32_t WakeUpMethod) @@ -467,19 +451,18 @@ HAL_StatusTypeDef HAL_MultiProcessor_Init(UART_HandleTypeDef *huart, uint8_t Add assert_param(IS_UART_WAKEUPMETHOD(WakeUpMethod)); assert_param(IS_UART_ADDRESS(Address)); assert_param(IS_UART_WORD_LENGTH(huart->Init.WordLength)); -#if defined(USART_CR1_OVER8) assert_param(IS_UART_OVERSAMPLING(huart->Init.OverSampling)); -#endif /* USART_CR1_OVER8 */ - if(huart->gState == HAL_UART_STATE_RESET) - { + if(huart->State == HAL_UART_STATE_RESET) + { /* Allocate lock resource and initialize it */ huart->Lock = HAL_UNLOCKED; + /* Init the low level hardware */ HAL_UART_MspInit(huart); } - huart->gState = HAL_UART_STATE_BUSY; + huart->State = HAL_UART_STATE_BUSY; /* Disable the peripheral */ __HAL_UART_DISABLE(huart); @@ -504,15 +487,14 @@ HAL_StatusTypeDef HAL_MultiProcessor_Init(UART_HandleTypeDef *huart, uint8_t Add /* Initialize the UART state */ huart->ErrorCode = HAL_UART_ERROR_NONE; - huart->gState = HAL_UART_STATE_READY; - huart->RxState = HAL_UART_STATE_READY; + huart->State= HAL_UART_STATE_READY; return HAL_OK; } /** * @brief DeInitializes the UART peripheral. - * @param huart: pointer to a UART_HandleTypeDef structure that contains + * @param huart: Pointer to a UART_HandleTypeDef structure that contains * the configuration information for the specified UART module. * @retval HAL status */ @@ -523,18 +505,24 @@ HAL_StatusTypeDef HAL_UART_DeInit(UART_HandleTypeDef *huart) { return HAL_ERROR; } - + /* Check the parameters */ assert_param(IS_UART_INSTANCE(huart->Instance)); - huart->gState = HAL_UART_STATE_BUSY; - + huart->State = HAL_UART_STATE_BUSY; + + /* Disable the Peripheral */ + __HAL_UART_DISABLE(huart); + + huart->Instance->CR1 = 0x0; + huart->Instance->CR2 = 0x0; + huart->Instance->CR3 = 0x0; + /* DeInit the low level hardware */ HAL_UART_MspDeInit(huart); huart->ErrorCode = HAL_UART_ERROR_NONE; - huart->gState = HAL_UART_STATE_RESET; - huart->RxState = HAL_UART_STATE_RESET; + huart->State = HAL_UART_STATE_RESET; /* Process Unlock */ __HAL_UNLOCK(huart); @@ -544,32 +532,32 @@ HAL_StatusTypeDef HAL_UART_DeInit(UART_HandleTypeDef *huart) /** * @brief UART MSP Init. - * @param huart: pointer to a UART_HandleTypeDef structure that contains + * @param huart: Pointer to a UART_HandleTypeDef structure that contains * the configuration information for the specified UART module. * @retval None */ -__weak void HAL_UART_MspInit(UART_HandleTypeDef *huart) + __weak void HAL_UART_MspInit(UART_HandleTypeDef *huart) { /* Prevent unused argument(s) compilation warning */ UNUSED(huart); /* NOTE: This function should not be modified, when the callback is needed, - the HAL_UART_MspInit could be implemented in the user file - */ + the HAL_UART_MspInit can be implemented in the user file + */ } /** * @brief UART MSP DeInit. - * @param huart: pointer to a UART_HandleTypeDef structure that contains + * @param huart: Pointer to a UART_HandleTypeDef structure that contains * the configuration information for the specified UART module. * @retval None */ -__weak void HAL_UART_MspDeInit(UART_HandleTypeDef *huart) + __weak void HAL_UART_MspDeInit(UART_HandleTypeDef *huart) { /* Prevent unused argument(s) compilation warning */ UNUSED(huart); /* NOTE: This function should not be modified, when the callback is needed, - the HAL_UART_MspDeInit could be implemented in the user file - */ + the HAL_UART_MspDeInit can be implemented in the user file + */ } /** @@ -582,7 +570,7 @@ __weak void HAL_UART_MspDeInit(UART_HandleTypeDef *huart) @verbatim ============================================================================== ##### IO operation functions ##### - ============================================================================== + ============================================================================== [..] This subsection provides a set of functions allowing to manage the UART asynchronous and Half duplex data transfers. @@ -624,18 +612,18 @@ __weak void HAL_UART_MspDeInit(UART_HandleTypeDef *huart) (++) HAL_UART_RxCpltCallback() (++) HAL_UART_ErrorCallback() - [..] + [..] (@) In the Half duplex communication, it is forbidden to run the transmit - and receive process in parallel, the UART state HAL_UART_STATE_BUSY_TX_RX + and receive process in parallel, the UART state HAL_UART_STATE_BUSY_TX_RX can't be useful. - + @endverbatim * @{ */ /** - * @brief Sends an amount of data in blocking mode. - * @param huart: pointer to a UART_HandleTypeDef structure that contains + * @brief Sends an amount of data in blocking mode. + * @param huart: Pointer to a UART_HandleTypeDef structure that contains * the configuration information for the specified UART module. * @param pData: Pointer to data buffer * @param Size: Amount of data to be sent @@ -645,12 +633,12 @@ __weak void HAL_UART_MspDeInit(UART_HandleTypeDef *huart) HAL_StatusTypeDef HAL_UART_Transmit(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size, uint32_t Timeout) { uint16_t* tmp; - uint32_t tickstart = 0U; + uint32_t tmp_state = 0; - /* Check that a Tx process is not already ongoing */ - if(huart->gState == HAL_UART_STATE_READY) + tmp_state = huart->State; + if((tmp_state == HAL_UART_STATE_READY) || (tmp_state == HAL_UART_STATE_BUSY_RX)) { - if((pData == NULL) || (Size == 0U)) + if((pData == NULL) || (Size == 0)) { return HAL_ERROR; } @@ -659,19 +647,24 @@ HAL_StatusTypeDef HAL_UART_Transmit(UART_HandleTypeDef *huart, uint8_t *pData, u __HAL_LOCK(huart); huart->ErrorCode = HAL_UART_ERROR_NONE; - huart->gState = HAL_UART_STATE_BUSY_TX; - - /* Init tickstart for timeout managment */ - tickstart = HAL_GetTick(); + /* Check if a non-blocking receive process is ongoing or not */ + if(huart->State == HAL_UART_STATE_BUSY_RX) + { + huart->State = HAL_UART_STATE_BUSY_TX_RX; + } + else + { + huart->State = HAL_UART_STATE_BUSY_TX; + } huart->TxXferSize = Size; huart->TxXferCount = Size; - while(huart->TxXferCount > 0U) + while(huart->TxXferCount > 0) { huart->TxXferCount--; if(huart->Init.WordLength == UART_WORDLENGTH_9B) { - if(UART_WaitOnFlagUntilTimeout(huart, UART_FLAG_TXE, RESET, tickstart, Timeout) != HAL_OK) + if(UART_WaitOnFlagUntilTimeout(huart, UART_FLAG_TXE, RESET, Timeout) != HAL_OK) { return HAL_TIMEOUT; } @@ -679,16 +672,16 @@ HAL_StatusTypeDef HAL_UART_Transmit(UART_HandleTypeDef *huart, uint8_t *pData, u huart->Instance->DR = (*tmp & (uint16_t)0x01FF); if(huart->Init.Parity == UART_PARITY_NONE) { - pData +=2U; + pData +=2; } else - { - pData +=1U; + { + pData +=1; } - } + } else { - if(UART_WaitOnFlagUntilTimeout(huart, UART_FLAG_TXE, RESET, tickstart, Timeout) != HAL_OK) + if(UART_WaitOnFlagUntilTimeout(huart, UART_FLAG_TXE, RESET, Timeout) != HAL_OK) { return HAL_TIMEOUT; } @@ -696,13 +689,20 @@ HAL_StatusTypeDef HAL_UART_Transmit(UART_HandleTypeDef *huart, uint8_t *pData, u } } - if(UART_WaitOnFlagUntilTimeout(huart, UART_FLAG_TC, RESET, tickstart, Timeout) != HAL_OK) - { + if(UART_WaitOnFlagUntilTimeout(huart, UART_FLAG_TC, RESET, Timeout) != HAL_OK) + { return HAL_TIMEOUT; } - /* At end of Tx process, restore huart->gState to Ready */ - huart->gState = HAL_UART_STATE_READY; + /* Check if a non-blocking receive process is ongoing or not */ + if(huart->State == HAL_UART_STATE_BUSY_TX_RX) + { + huart->State = HAL_UART_STATE_BUSY_RX; + } + else + { + huart->State = HAL_UART_STATE_READY; + } /* Process Unlocked */ __HAL_UNLOCK(huart); @@ -716,8 +716,8 @@ HAL_StatusTypeDef HAL_UART_Transmit(UART_HandleTypeDef *huart, uint8_t *pData, u } /** - * @brief Receive an amount of data in blocking mode. - * @param huart: pointer to a UART_HandleTypeDef structure that contains + * @brief Receives an amount of data in blocking mode. + * @param huart: Pointer to a UART_HandleTypeDef structure that contains * the configuration information for the specified UART module. * @param pData: Pointer to data buffer * @param Size: Amount of data to be received @@ -727,54 +727,59 @@ HAL_StatusTypeDef HAL_UART_Transmit(UART_HandleTypeDef *huart, uint8_t *pData, u HAL_StatusTypeDef HAL_UART_Receive(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size, uint32_t Timeout) { uint16_t* tmp; - uint32_t tickstart = 0U; - - /* Check that a Rx process is not already ongoing */ - if(huart->RxState == HAL_UART_STATE_READY) + uint32_t tmp_state = 0; + + tmp_state = huart->State; + if((tmp_state == HAL_UART_STATE_READY) || (tmp_state == HAL_UART_STATE_BUSY_TX)) { - if((pData == NULL) || (Size == 0U)) + if((pData == NULL ) || (Size == 0)) { return HAL_ERROR; } /* Process Locked */ __HAL_LOCK(huart); - - huart->ErrorCode = HAL_UART_ERROR_NONE; - huart->RxState = HAL_UART_STATE_BUSY_RX; - /* Init tickstart for timeout managment */ - tickstart = HAL_GetTick(); + huart->ErrorCode = HAL_UART_ERROR_NONE; + /* Check if a non-blocking transmit process is ongoing or not */ + if(huart->State == HAL_UART_STATE_BUSY_TX) + { + huart->State = HAL_UART_STATE_BUSY_TX_RX; + } + else + { + huart->State = HAL_UART_STATE_BUSY_RX; + } huart->RxXferSize = Size; huart->RxXferCount = Size; /* Check the remain data to be received */ - while(huart->RxXferCount > 0U) + while(huart->RxXferCount > 0) { huart->RxXferCount--; if(huart->Init.WordLength == UART_WORDLENGTH_9B) { - if(UART_WaitOnFlagUntilTimeout(huart, UART_FLAG_RXNE, RESET, tickstart, Timeout) != HAL_OK) + if(UART_WaitOnFlagUntilTimeout(huart, UART_FLAG_RXNE, RESET, Timeout) != HAL_OK) { return HAL_TIMEOUT; } - tmp = (uint16_t*)pData; + tmp = (uint16_t*) pData ; if(huart->Init.Parity == UART_PARITY_NONE) { *tmp = (uint16_t)(huart->Instance->DR & (uint16_t)0x01FF); - pData +=2U; + pData +=2; } else { *tmp = (uint16_t)(huart->Instance->DR & (uint16_t)0x00FF); - pData +=1U; + pData +=1; } - } + } else { - if(UART_WaitOnFlagUntilTimeout(huart, UART_FLAG_RXNE, RESET, tickstart, Timeout) != HAL_OK) + if(UART_WaitOnFlagUntilTimeout(huart, UART_FLAG_RXNE, RESET, Timeout) != HAL_OK) { return HAL_TIMEOUT; } @@ -790,9 +795,15 @@ HAL_StatusTypeDef HAL_UART_Receive(UART_HandleTypeDef *huart, uint8_t *pData, ui } } - /* At end of Rx process, restore huart->RxState to Ready */ - huart->RxState = HAL_UART_STATE_READY; - + /* Check if a non-blocking transmit process is ongoing or not */ + if(huart->State == HAL_UART_STATE_BUSY_TX_RX) + { + huart->State = HAL_UART_STATE_BUSY_TX; + } + else + { + huart->State = HAL_UART_STATE_READY; + } /* Process Unlocked */ __HAL_UNLOCK(huart); @@ -806,7 +817,7 @@ HAL_StatusTypeDef HAL_UART_Receive(UART_HandleTypeDef *huart, uint8_t *pData, ui /** * @brief Sends an amount of data in non blocking mode. - * @param huart: pointer to a UART_HandleTypeDef structure that contains + * @param huart: Pointer to a UART_HandleTypeDef structure that contains * the configuration information for the specified UART module. * @param pData: Pointer to data buffer * @param Size: Amount of data to be sent @@ -814,29 +825,40 @@ HAL_StatusTypeDef HAL_UART_Receive(UART_HandleTypeDef *huart, uint8_t *pData, ui */ HAL_StatusTypeDef HAL_UART_Transmit_IT(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size) { - /* Check that a Tx process is not already ongoing */ - if(huart->gState == HAL_UART_STATE_READY) + uint32_t tmp_state = 0; + + tmp_state = huart->State; + if((tmp_state == HAL_UART_STATE_READY) || (tmp_state == HAL_UART_STATE_BUSY_RX)) { - if((pData == NULL) || (Size == 0U)) + if((pData == NULL ) || (Size == 0)) { return HAL_ERROR; } + /* Process Locked */ __HAL_LOCK(huart); - + huart->pTxBuffPtr = pData; huart->TxXferSize = Size; huart->TxXferCount = Size; huart->ErrorCode = HAL_UART_ERROR_NONE; - huart->gState = HAL_UART_STATE_BUSY_TX; + /* Check if a receive process is ongoing or not */ + if(huart->State == HAL_UART_STATE_BUSY_RX) + { + huart->State = HAL_UART_STATE_BUSY_TX_RX; + } + else + { + huart->State = HAL_UART_STATE_BUSY_TX; + } /* Process Unlocked */ __HAL_UNLOCK(huart); /* Enable the UART Transmit data register empty Interrupt */ __HAL_UART_ENABLE_IT(huart, UART_IT_TXE); - + return HAL_OK; } else @@ -846,8 +868,8 @@ HAL_StatusTypeDef HAL_UART_Transmit_IT(UART_HandleTypeDef *huart, uint8_t *pData } /** - * @brief Receives an amount of data in non blocking mode. - * @param huart: pointer to a UART_HandleTypeDef structure that contains + * @brief Receives an amount of data in non blocking mode + * @param huart: Pointer to a UART_HandleTypeDef structure that contains * the configuration information for the specified UART module. * @param pData: Pointer to data buffer * @param Size: Amount of data to be received @@ -855,10 +877,12 @@ HAL_StatusTypeDef HAL_UART_Transmit_IT(UART_HandleTypeDef *huart, uint8_t *pData */ HAL_StatusTypeDef HAL_UART_Receive_IT(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size) { - /* Check that a Rx process is not already ongoing */ - if(huart->RxState == HAL_UART_STATE_READY) + uint32_t tmp_state = 0; + + tmp_state = huart->State; + if((tmp_state == HAL_UART_STATE_READY) || (tmp_state == HAL_UART_STATE_BUSY_TX)) { - if((pData == NULL) || (Size == 0U)) + if((pData == NULL ) || (Size == 0)) { return HAL_ERROR; } @@ -871,8 +895,16 @@ HAL_StatusTypeDef HAL_UART_Receive_IT(UART_HandleTypeDef *huart, uint8_t *pData, huart->RxXferCount = Size; huart->ErrorCode = HAL_UART_ERROR_NONE; - huart->RxState = HAL_UART_STATE_BUSY_RX; - + /* Check if a transmit process is ongoing or not */ + if(huart->State == HAL_UART_STATE_BUSY_TX) + { + huart->State = HAL_UART_STATE_BUSY_TX_RX; + } + else + { + huart->State = HAL_UART_STATE_BUSY_RX; + } + /* Process Unlocked */ __HAL_UNLOCK(huart); @@ -895,7 +927,7 @@ HAL_StatusTypeDef HAL_UART_Receive_IT(UART_HandleTypeDef *huart, uint8_t *pData, /** * @brief Sends an amount of data in non blocking mode. - * @param huart: pointer to a UART_HandleTypeDef structure that contains + * @param huart: Pointer to a UART_HandleTypeDef structure that contains * the configuration information for the specified UART module. * @param pData: Pointer to data buffer * @param Size: Amount of data to be sent @@ -904,11 +936,12 @@ HAL_StatusTypeDef HAL_UART_Receive_IT(UART_HandleTypeDef *huart, uint8_t *pData, HAL_StatusTypeDef HAL_UART_Transmit_DMA(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size) { uint32_t *tmp; - - /* Check that a Tx process is not already ongoing */ - if(huart->gState == HAL_UART_STATE_READY) + uint32_t tmp_state = 0; + + tmp_state = huart->State; + if((tmp_state == HAL_UART_STATE_READY) || (tmp_state == HAL_UART_STATE_BUSY_RX)) { - if((pData == NULL) || (Size == 0U)) + if((pData == NULL ) || (Size == 0)) { return HAL_ERROR; } @@ -921,7 +954,15 @@ HAL_StatusTypeDef HAL_UART_Transmit_DMA(UART_HandleTypeDef *huart, uint8_t *pDat huart->TxXferCount = Size; huart->ErrorCode = HAL_UART_ERROR_NONE; - huart->gState = HAL_UART_STATE_BUSY_TX; + /* Check if a receive process is ongoing or not */ + if(huart->State == HAL_UART_STATE_BUSY_RX) + { + huart->State = HAL_UART_STATE_BUSY_TX_RX; + } + else + { + huart->State = HAL_UART_STATE_BUSY_TX; + } /* Set the UART DMA transfer complete callback */ huart->hdmatx->XferCpltCallback = UART_DMATransmitCplt; @@ -932,9 +973,6 @@ HAL_StatusTypeDef HAL_UART_Transmit_DMA(UART_HandleTypeDef *huart, uint8_t *pDat /* Set the DMA error callback */ huart->hdmatx->XferErrorCallback = UART_DMAError; - /* Set the DMA abort callback */ - huart->hdmatx->XferAbortCallback = NULL; - /* Enable the UART transmit DMA channel */ tmp = (uint32_t*)&pData; HAL_DMA_Start_IT(huart->hdmatx, *(uint32_t*)tmp, (uint32_t)&huart->Instance->DR, Size); @@ -942,13 +980,13 @@ HAL_StatusTypeDef HAL_UART_Transmit_DMA(UART_HandleTypeDef *huart, uint8_t *pDat /* Clear the TC flag in the SR register by writing 0 to it */ __HAL_UART_CLEAR_FLAG(huart, UART_FLAG_TC); - /* Process Unlocked */ - __HAL_UNLOCK(huart); - /* Enable the DMA transfer for transmit request by setting the DMAT bit in the UART CR3 register */ SET_BIT(huart->Instance->CR3, USART_CR3_DMAT); + /* Process Unlocked */ + __HAL_UNLOCK(huart); + return HAL_OK; } else @@ -959,21 +997,23 @@ HAL_StatusTypeDef HAL_UART_Transmit_DMA(UART_HandleTypeDef *huart, uint8_t *pDat /** * @brief Receives an amount of data in non blocking mode. - * @param huart: pointer to a UART_HandleTypeDef structure that contains + * @param huart: Pointer to a UART_HandleTypeDef structure that contains * the configuration information for the specified UART module. * @param pData: Pointer to data buffer * @param Size: Amount of data to be received - * @note When the UART parity is enabled (PCE = 1) the data received contain the parity bit. + * @note When the UART parity is enabled (PCE = 1), the received data contain + * the parity bit (MSB position) * @retval HAL status */ HAL_StatusTypeDef HAL_UART_Receive_DMA(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size) { uint32_t *tmp; - - /* Check that a Rx process is not already ongoing */ - if(huart->RxState == HAL_UART_STATE_READY) + uint32_t tmp_state = 0; + + tmp_state = huart->State; + if((tmp_state == HAL_UART_STATE_READY) || (tmp_state == HAL_UART_STATE_BUSY_TX)) { - if((pData == NULL) || (Size == 0U)) + if((pData == NULL ) || (Size == 0)) { return HAL_ERROR; } @@ -985,7 +1025,15 @@ HAL_StatusTypeDef HAL_UART_Receive_DMA(UART_HandleTypeDef *huart, uint8_t *pData huart->RxXferSize = Size; huart->ErrorCode = HAL_UART_ERROR_NONE; - huart->RxState = HAL_UART_STATE_BUSY_RX; + /* Check if a transmit process is ongoing or not */ + if(huart->State == HAL_UART_STATE_BUSY_TX) + { + huart->State = HAL_UART_STATE_BUSY_TX_RX; + } + else + { + huart->State = HAL_UART_STATE_BUSY_RX; + } /* Set the UART DMA transfer complete callback */ huart->hdmarx->XferCpltCallback = UART_DMAReceiveCplt; @@ -996,29 +1044,17 @@ HAL_StatusTypeDef HAL_UART_Receive_DMA(UART_HandleTypeDef *huart, uint8_t *pData /* Set the DMA error callback */ huart->hdmarx->XferErrorCallback = UART_DMAError; - /* Set the DMA abort callback */ - huart->hdmarx->XferAbortCallback = NULL; - /* Enable the DMA channel */ tmp = (uint32_t*)&pData; HAL_DMA_Start_IT(huart->hdmarx, (uint32_t)&huart->Instance->DR, *(uint32_t*)tmp, Size); - /* Clear the Overrun flag just before enabling the DMA Rx request: can be mandatory for the second transfer */ - __HAL_UART_CLEAR_OREFLAG(huart); + /* Enable the DMA transfer for the receiver request by setting the DMAR bit + in the UART CR3 register */ + SET_BIT(huart->Instance->CR3, USART_CR3_DMAR); /* Process Unlocked */ __HAL_UNLOCK(huart); - /* Enable the UART Parity Error Interrupt */ - SET_BIT(huart->Instance->CR1, USART_CR1_PEIE); - - /* Enable the UART Error Interrupt: (Frame error, noise error, overrun error) */ - SET_BIT(huart->Instance->CR3, USART_CR3_EIE); - - /* Enable the DMA transfer for the receiver request by setting the DMAR bit - in the UART CR3 register */ - SET_BIT(huart->Instance->CR3, USART_CR3_DMAR); - return HAL_OK; } else @@ -1026,47 +1062,50 @@ HAL_StatusTypeDef HAL_UART_Receive_DMA(UART_HandleTypeDef *huart, uint8_t *pData return HAL_BUSY; } } - + /** * @brief Pauses the DMA Transfer. - * @param huart: pointer to a UART_HandleTypeDef structure that contains + * @param huart: Pointer to a UART_HandleTypeDef structure that contains * the configuration information for the specified UART module. * @retval HAL status */ HAL_StatusTypeDef HAL_UART_DMAPause(UART_HandleTypeDef *huart) { - uint32_t dmarequest = 0x00U; - /* Process Locked */ __HAL_LOCK(huart); - - dmarequest = HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAT); - if((huart->gState == HAL_UART_STATE_BUSY_TX) && dmarequest) + + if(huart->State == HAL_UART_STATE_BUSY_TX) { /* Disable the UART DMA Tx request */ CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAT); } - - dmarequest = HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAR); - if((huart->RxState == HAL_UART_STATE_BUSY_RX) && dmarequest) + else if(huart->State == HAL_UART_STATE_BUSY_RX) { - /* Disable RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */ - CLEAR_BIT(huart->Instance->CR1, USART_CR1_PEIE); - CLEAR_BIT(huart->Instance->CR3, USART_CR3_EIE); - /* Disable the UART DMA Rx request */ CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAR); } - + else if (huart->State == HAL_UART_STATE_BUSY_TX_RX) + { + /* Disable the UART DMA Tx & Rx requests */ + CLEAR_BIT(huart->Instance->CR3, (USART_CR3_DMAT | USART_CR3_DMAR)); + } + else + { + /* Process Unlocked */ + __HAL_UNLOCK(huart); + + return HAL_ERROR; + } + /* Process Unlocked */ __HAL_UNLOCK(huart); - - return HAL_OK; + + return HAL_OK; } /** * @brief Resumes the DMA Transfer. - * @param huart: pointer to a UART_HandleTypeDef structure that contains + * @param huart: Pointer to a UART_HandleTypeDef structure that contains * the configuration information for the specified UART module. * @retval HAL status */ @@ -1074,610 +1113,152 @@ HAL_StatusTypeDef HAL_UART_DMAResume(UART_HandleTypeDef *huart) { /* Process Locked */ __HAL_LOCK(huart); - - if(huart->gState == HAL_UART_STATE_BUSY_TX) + + if(huart->State == HAL_UART_STATE_BUSY_TX) { /* Enable the UART DMA Tx request */ SET_BIT(huart->Instance->CR3, USART_CR3_DMAT); } - - if(huart->RxState == HAL_UART_STATE_BUSY_RX) + else if(huart->State == HAL_UART_STATE_BUSY_RX) { - /* Clear the Overrun flag before resuming the Rx transfer*/ + /* Clear the Overrun flag before resumming the Rx transfer*/ __HAL_UART_CLEAR_OREFLAG(huart); - - /* Reenable PE and ERR (Frame error, noise error, overrun error) interrupts */ - SET_BIT(huart->Instance->CR1, USART_CR1_PEIE); - SET_BIT(huart->Instance->CR3, USART_CR3_EIE); - /* Enable the UART DMA Rx request */ SET_BIT(huart->Instance->CR3, USART_CR3_DMAR); } + else if(huart->State == HAL_UART_STATE_BUSY_TX_RX) + { + /* Clear the Overrun flag before resumming the Rx transfer*/ + __HAL_UART_CLEAR_OREFLAG(huart); + /* Enable the UART DMA Tx & Rx request */ + SET_BIT(huart->Instance->CR3, (USART_CR3_DMAT | USART_CR3_DMAR)); + } + else + { + /* Process Unlocked */ + __HAL_UNLOCK(huart); + + return HAL_ERROR; + } /* Process Unlocked */ __HAL_UNLOCK(huart); - + return HAL_OK; } /** * @brief Stops the DMA Transfer. - * @param huart: pointer to a UART_HandleTypeDef structure that contains + * @param huart: Pointer to a UART_HandleTypeDef structure that contains * the configuration information for the specified UART module. * @retval HAL status */ HAL_StatusTypeDef HAL_UART_DMAStop(UART_HandleTypeDef *huart) { - uint32_t dmarequest = 0x00U; /* The Lock is not implemented on this API to allow the user application to call the HAL UART API under callbacks HAL_UART_TxCpltCallback() / HAL_UART_RxCpltCallback(): when calling HAL_DMA_Abort() API the DMA TX/RX Transfer complete interrupt is generated and the correspond call back is executed HAL_UART_TxCpltCallback() / HAL_UART_RxCpltCallback() */ - - /* Stop UART DMA Tx request if ongoing */ - dmarequest = HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAT); - if((huart->gState == HAL_UART_STATE_BUSY_TX) && dmarequest) + + /* Disable the UART Tx/Rx DMA requests */ + CLEAR_BIT(huart->Instance->CR3, (USART_CR3_DMAT | USART_CR3_DMAR)); + + /* Abort the UART DMA tx channel */ + if(huart->hdmatx != NULL) { - CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAT); - - /* Abort the UART DMA Tx channel */ - if(huart->hdmatx != NULL) - { - HAL_DMA_Abort(huart->hdmatx); - } - UART_EndTxTransfer(huart); + HAL_DMA_Abort(huart->hdmatx); } - - /* Stop UART DMA Rx request if ongoing */ - dmarequest = HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAR); - if((huart->RxState == HAL_UART_STATE_BUSY_RX) && dmarequest) + /* Abort the UART DMA rx channel */ + if(huart->hdmarx != NULL) { - CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAR); - - /* Abort the UART DMA Rx channel */ - if(huart->hdmarx != NULL) - { - HAL_DMA_Abort(huart->hdmarx); - } - UART_EndRxTransfer(huart); + HAL_DMA_Abort(huart->hdmarx); } - - return HAL_OK; -} - -/** - * @brief Abort ongoing transfers (blocking mode). - * @param huart UART handle. - * @note This procedure could be used for aborting any ongoing transfer started in Interrupt or DMA mode. - * This procedure performs following operations : - * - Disable PPP Interrupts - * - Disable the DMA transfer in the peripheral register (if enabled) - * - Abort DMA transfer by calling HAL_DMA_Abort (in case of transfer in DMA mode) - * - Set handle State to READY - * @note This procedure is executed in blocking mode : when exiting function, Abort is considered as completed. - * @retval HAL status -*/ -HAL_StatusTypeDef HAL_UART_Abort(UART_HandleTypeDef *huart) -{ - /* Disable TXEIE, TCIE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */ - CLEAR_BIT(huart->Instance->CR1, (USART_CR1_RXNEIE | USART_CR1_PEIE | USART_CR1_TXEIE | USART_CR1_TCIE)); - CLEAR_BIT(huart->Instance->CR3, USART_CR3_EIE); - - /* Disable the UART DMA Tx request if enabled */ - if(HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAT)) - { - CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAT); - - /* Abort the UART DMA Tx channel: use blocking DMA Abort API (no callback) */ - if(huart->hdmatx != NULL) - { - /* Set the UART DMA Abort callback to Null. - No call back execution at end of DMA abort procedure */ - huart->hdmatx->XferAbortCallback = NULL; - - HAL_DMA_Abort(huart->hdmatx); - } - } - - /* Disable the UART DMA Rx request if enabled */ - if(HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAR)) - { - CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAR); - - /* Abort the UART DMA Rx channel: use blocking DMA Abort API (no callback) */ - if(huart->hdmarx != NULL) - { - /* Set the UART DMA Abort callback to Null. - No call back execution at end of DMA abort procedure */ - huart->hdmarx->XferAbortCallback = NULL; - - HAL_DMA_Abort(huart->hdmarx); - } - } - - /* Reset Tx and Rx transfer counters */ - huart->TxXferCount = 0x00U; - huart->RxXferCount = 0x00U; - - /* Reset ErrorCode */ - huart->ErrorCode = HAL_UART_ERROR_NONE; - - /* Restore huart->RxState and huart->gState to Ready */ - huart->RxState = HAL_UART_STATE_READY; - huart->gState = HAL_UART_STATE_READY; - - return HAL_OK; -} - -/** - * @brief Abort ongoing Transmit transfer (blocking mode). - * @param huart UART handle. - * @note This procedure could be used for aborting any ongoing transfer started in Interrupt or DMA mode. - * This procedure performs following operations : - * - Disable PPP Interrupts - * - Disable the DMA transfer in the peripheral register (if enabled) - * - Abort DMA transfer by calling HAL_DMA_Abort (in case of transfer in DMA mode) - * - Set handle State to READY - * @note This procedure is executed in blocking mode : when exiting function, Abort is considered as completed. - * @retval HAL status -*/ -HAL_StatusTypeDef HAL_UART_AbortTransmit(UART_HandleTypeDef *huart) -{ - /* Disable TXEIE and TCIE interrupts */ - CLEAR_BIT(huart->Instance->CR1, (USART_CR1_TXEIE | USART_CR1_TCIE)); - - /* Disable the UART DMA Tx request if enabled */ - if(HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAT)) - { - CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAT); - - /* Abort the UART DMA Tx channel : use blocking DMA Abort API (no callback) */ - if(huart->hdmatx != NULL) - { - /* Set the UART DMA Abort callback to Null. - No call back execution at end of DMA abort procedure */ - huart->hdmatx->XferAbortCallback = NULL; - - HAL_DMA_Abort(huart->hdmatx); - } - } - - /* Reset Tx transfer counter */ - huart->TxXferCount = 0x00U; - - /* Restore huart->gState to Ready */ - huart->gState = HAL_UART_STATE_READY; - - return HAL_OK; -} - -/** - * @brief Abort ongoing Receive transfer (blocking mode). - * @param huart UART handle. - * @note This procedure could be used for aborting any ongoing transfer started in Interrupt or DMA mode. - * This procedure performs following operations : - * - Disable PPP Interrupts - * - Disable the DMA transfer in the peripheral register (if enabled) - * - Abort DMA transfer by calling HAL_DMA_Abort (in case of transfer in DMA mode) - * - Set handle State to READY - * @note This procedure is executed in blocking mode : when exiting function, Abort is considered as completed. - * @retval HAL status -*/ -HAL_StatusTypeDef HAL_UART_AbortReceive(UART_HandleTypeDef *huart) -{ - /* Disable RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */ - CLEAR_BIT(huart->Instance->CR1, (USART_CR1_RXNEIE | USART_CR1_PEIE)); - CLEAR_BIT(huart->Instance->CR3, USART_CR3_EIE); - - /* Disable the UART DMA Rx request if enabled */ - if(HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAR)) - { - CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAR); - - /* Abort the UART DMA Rx channel : use blocking DMA Abort API (no callback) */ - if(huart->hdmarx != NULL) - { - /* Set the UART DMA Abort callback to Null. - No call back execution at end of DMA abort procedure */ - huart->hdmarx->XferAbortCallback = NULL; - - HAL_DMA_Abort(huart->hdmarx); - } - } - - /* Reset Rx transfer counter */ - huart->RxXferCount = 0x00U; - - /* Restore huart->RxState to Ready */ - huart->RxState = HAL_UART_STATE_READY; - - return HAL_OK; -} - -/** - * @brief Abort ongoing transfers (Interrupt mode). - * @param huart UART handle. - * @note This procedure could be used for aborting any ongoing transfer started in Interrupt or DMA mode. - * This procedure performs following operations : - * - Disable PPP Interrupts - * - Disable the DMA transfer in the peripheral register (if enabled) - * - Abort DMA transfer by calling HAL_DMA_Abort_IT (in case of transfer in DMA mode) - * - Set handle State to READY - * - At abort completion, call user abort complete callback - * @note This procedure is executed in Interrupt mode, meaning that abort procedure could be - * considered as completed only when user abort complete callback is executed (not when exiting function). - * @retval HAL status -*/ -HAL_StatusTypeDef HAL_UART_Abort_IT(UART_HandleTypeDef *huart) -{ - uint32_t AbortCplt = 0x01U; - - /* Disable TXEIE, TCIE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */ - CLEAR_BIT(huart->Instance->CR1, (USART_CR1_RXNEIE | USART_CR1_PEIE | USART_CR1_TXEIE | USART_CR1_TCIE)); - CLEAR_BIT(huart->Instance->CR3, USART_CR3_EIE); - - /* If DMA Tx and/or DMA Rx Handles are associated to UART Handle, DMA Abort complete callbacks should be initialised - before any call to DMA Abort functions */ - /* DMA Tx Handle is valid */ - if(huart->hdmatx != NULL) - { - /* Set DMA Abort Complete callback if UART DMA Tx request if enabled. - Otherwise, set it to NULL */ - if(HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAT)) - { - huart->hdmatx->XferAbortCallback = UART_DMATxAbortCallback; - } - else - { - huart->hdmatx->XferAbortCallback = NULL; - } - } - /* DMA Rx Handle is valid */ - if(huart->hdmarx != NULL) - { - /* Set DMA Abort Complete callback if UART DMA Rx request if enabled. - Otherwise, set it to NULL */ - if(HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAR)) - { - huart->hdmarx->XferAbortCallback = UART_DMARxAbortCallback; - } - else - { - huart->hdmarx->XferAbortCallback = NULL; - } - } - - /* Disable the UART DMA Tx request if enabled */ - if(HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAT)) - { - /* Disable DMA Tx at UART level */ - CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAT); - - /* Abort the UART DMA Tx channel : use non blocking DMA Abort API (callback) */ - if(huart->hdmatx != NULL) - { - /* UART Tx DMA Abort callback has already been initialised : - will lead to call HAL_UART_AbortCpltCallback() at end of DMA abort procedure */ - - /* Abort DMA TX */ - if(HAL_DMA_Abort_IT(huart->hdmatx) != HAL_OK) - { - huart->hdmatx->XferAbortCallback = NULL; - } - else - { - AbortCplt = 0x00U; - } - } - } - - /* Disable the UART DMA Rx request if enabled */ - if(HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAR)) - { - CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAR); - - /* Abort the UART DMA Rx channel : use non blocking DMA Abort API (callback) */ - if(huart->hdmarx != NULL) - { - /* UART Rx DMA Abort callback has already been initialised : - will lead to call HAL_UART_AbortCpltCallback() at end of DMA abort procedure */ - - /* Abort DMA RX */ - if(HAL_DMA_Abort_IT(huart->hdmarx) != HAL_OK) - { - huart->hdmarx->XferAbortCallback = NULL; - AbortCplt = 0x01U; - } - else - { - AbortCplt = 0x00U; - } - } - } - - /* if no DMA abort complete callback execution is required => call user Abort Complete callback */ - if(AbortCplt == 0x01U) - { - /* Reset Tx and Rx transfer counters */ - huart->TxXferCount = 0x00U; - huart->RxXferCount = 0x00U; - - /* Reset ErrorCode */ - huart->ErrorCode = HAL_UART_ERROR_NONE; - - /* Restore huart->gState and huart->RxState to Ready */ - huart->gState = HAL_UART_STATE_READY; - huart->RxState = HAL_UART_STATE_READY; - - /* As no DMA to be aborted, call directly user Abort complete callback */ - HAL_UART_AbortCpltCallback(huart); - } - - return HAL_OK; -} - -/** - * @brief Abort ongoing Transmit transfer (Interrupt mode). - * @param huart UART handle. - * @note This procedure could be used for aborting any ongoing transfer started in Interrupt or DMA mode. - * This procedure performs following operations : - * - Disable PPP Interrupts - * - Disable the DMA transfer in the peripheral register (if enabled) - * - Abort DMA transfer by calling HAL_DMA_Abort_IT (in case of transfer in DMA mode) - * - Set handle State to READY - * - At abort completion, call user abort complete callback - * @note This procedure is executed in Interrupt mode, meaning that abort procedure could be - * considered as completed only when user abort complete callback is executed (not when exiting function). - * @retval HAL status -*/ -HAL_StatusTypeDef HAL_UART_AbortTransmit_IT(UART_HandleTypeDef *huart) -{ - /* Disable TXEIE and TCIE interrupts */ - CLEAR_BIT(huart->Instance->CR1, (USART_CR1_TXEIE | USART_CR1_TCIE)); - - /* Disable the UART DMA Tx request if enabled */ - if(HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAT)) - { - CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAT); - - /* Abort the UART DMA Tx channel : use blocking DMA Abort API (no callback) */ - if(huart->hdmatx != NULL) - { - /* Set the UART DMA Abort callback : - will lead to call HAL_UART_AbortCpltCallback() at end of DMA abort procedure */ - huart->hdmatx->XferAbortCallback = UART_DMATxOnlyAbortCallback; - - /* Abort DMA TX */ - if(HAL_DMA_Abort_IT(huart->hdmatx) != HAL_OK) - { - /* Call Directly huart->hdmatx->XferAbortCallback function in case of error */ - huart->hdmatx->XferAbortCallback(huart->hdmatx); - } - } - else - { - /* Reset Tx transfer counter */ - huart->TxXferCount = 0x00U; - - /* Restore huart->gState to Ready */ - huart->gState = HAL_UART_STATE_READY; - - /* As no DMA to be aborted, call directly user Abort complete callback */ - HAL_UART_AbortTransmitCpltCallback(huart); - } - } - else - { - /* Reset Tx transfer counter */ - huart->TxXferCount = 0x00U; - - /* Restore huart->gState to Ready */ - huart->gState = HAL_UART_STATE_READY; - - /* As no DMA to be aborted, call directly user Abort complete callback */ - HAL_UART_AbortTransmitCpltCallback(huart); - } - - return HAL_OK; -} - -/** - * @brief Abort ongoing Receive transfer (Interrupt mode). - * @param huart UART handle. - * @note This procedure could be used for aborting any ongoing transfer started in Interrupt or DMA mode. - * This procedure performs following operations : - * - Disable PPP Interrupts - * - Disable the DMA transfer in the peripheral register (if enabled) - * - Abort DMA transfer by calling HAL_DMA_Abort_IT (in case of transfer in DMA mode) - * - Set handle State to READY - * - At abort completion, call user abort complete callback - * @note This procedure is executed in Interrupt mode, meaning that abort procedure could be - * considered as completed only when user abort complete callback is executed (not when exiting function). - * @retval HAL status -*/ -HAL_StatusTypeDef HAL_UART_AbortReceive_IT(UART_HandleTypeDef *huart) -{ - /* Disable RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */ - CLEAR_BIT(huart->Instance->CR1, (USART_CR1_RXNEIE | USART_CR1_PEIE)); - CLEAR_BIT(huart->Instance->CR3, USART_CR3_EIE); - - /* Disable the UART DMA Rx request if enabled */ - if(HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAR)) - { - CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAR); - - /* Abort the UART DMA Rx channel : use blocking DMA Abort API (no callback) */ - if(huart->hdmarx != NULL) - { - /* Set the UART DMA Abort callback : - will lead to call HAL_UART_AbortCpltCallback() at end of DMA abort procedure */ - huart->hdmarx->XferAbortCallback = UART_DMARxOnlyAbortCallback; - - /* Abort DMA RX */ - if(HAL_DMA_Abort_IT(huart->hdmarx) != HAL_OK) - { - /* Call Directly huart->hdmarx->XferAbortCallback function in case of error */ - huart->hdmarx->XferAbortCallback(huart->hdmarx); - } - } - else - { - /* Reset Rx transfer counter */ - huart->RxXferCount = 0x00U; - - /* Restore huart->RxState to Ready */ - huart->RxState = HAL_UART_STATE_READY; - - /* As no DMA to be aborted, call directly user Abort complete callback */ - HAL_UART_AbortReceiveCpltCallback(huart); - } - } - else - { - /* Reset Rx transfer counter */ - huart->RxXferCount = 0x00U; - - /* Restore huart->RxState to Ready */ - huart->RxState = HAL_UART_STATE_READY; - - /* As no DMA to be aborted, call directly user Abort complete callback */ - HAL_UART_AbortReceiveCpltCallback(huart); - } - + + huart->State = HAL_UART_STATE_READY; + return HAL_OK; } /** * @brief This function handles UART interrupt request. - * @param huart: pointer to a UART_HandleTypeDef structure that contains + * @param huart: Pointer to a UART_HandleTypeDef structure that contains * the configuration information for the specified UART module. * @retval None */ void HAL_UART_IRQHandler(UART_HandleTypeDef *huart) { - uint32_t isrflags = READ_REG(huart->Instance->SR); - uint32_t cr1its = READ_REG(huart->Instance->CR1); - uint32_t cr3its = READ_REG(huart->Instance->CR3); - uint32_t errorflags = 0x00U; - uint32_t dmarequest = 0x00U; - - /* If no error occurs */ - errorflags = (isrflags & (uint32_t)(USART_SR_PE | USART_SR_FE | USART_SR_ORE | USART_SR_NE)); - if(errorflags == RESET) - { - /* UART in mode Receiver -------------------------------------------------*/ - if(((isrflags & USART_SR_RXNE) != RESET) && ((cr1its & USART_CR1_RXNEIE) != RESET)) - { - UART_Receive_IT(huart); - return; - } + uint32_t tmp_flag = 0, tmp_it_source = 0; + + tmp_flag = __HAL_UART_GET_FLAG(huart, UART_FLAG_PE); + tmp_it_source = __HAL_UART_GET_IT_SOURCE(huart, UART_IT_PE); + /* UART parity error interrupt occurred ------------------------------------*/ + if((tmp_flag != RESET) && (tmp_it_source != RESET)) + { + huart->ErrorCode |= HAL_UART_ERROR_PE; } - - /* If some errors occur */ - if((errorflags != RESET) && (((cr3its & USART_CR3_EIE) != RESET) || ((cr1its & (USART_CR1_RXNEIE | USART_CR1_PEIE)) != RESET))) - { - /* UART parity error interrupt occurred ----------------------------------*/ - if(((isrflags & USART_SR_PE) != RESET) && ((cr1its & USART_CR1_PEIE) != RESET)) - { - huart->ErrorCode |= HAL_UART_ERROR_PE; - } - - /* UART noise error interrupt occurred -----------------------------------*/ - if(((isrflags & USART_SR_NE) != RESET) && ((cr3its & USART_CR3_EIE) != RESET)) - { - huart->ErrorCode |= HAL_UART_ERROR_NE; - } - - /* UART frame error interrupt occurred -----------------------------------*/ - if(((isrflags & USART_SR_FE) != RESET) && ((cr3its & USART_CR3_EIE) != RESET)) - { - huart->ErrorCode |= HAL_UART_ERROR_FE; - } - - /* UART Over-Run interrupt occurred --------------------------------------*/ - if(((isrflags & USART_SR_ORE) != RESET) && ((cr3its & USART_CR3_EIE) != RESET)) - { - huart->ErrorCode |= HAL_UART_ERROR_ORE; - } - - /* Call UART Error Call back function if need be --------------------------*/ - if(huart->ErrorCode != HAL_UART_ERROR_NONE) - { - /* UART in mode Receiver -----------------------------------------------*/ - if(((isrflags & USART_SR_RXNE) != RESET) && ((cr1its & USART_CR1_RXNEIE) != RESET)) - { - UART_Receive_IT(huart); - } - - /* If Overrun error occurs, or if any error occurs in DMA mode reception, - consider error as blocking */ - dmarequest = HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAR); - if(((huart->ErrorCode & HAL_UART_ERROR_ORE) != RESET) || dmarequest) - { - /* Blocking error : transfer is aborted - Set the UART state ready to be able to start again the process, - Disable Rx Interrupts, and disable Rx DMA request, if ongoing */ - UART_EndRxTransfer(huart); - - /* Disable the UART DMA Rx request if enabled */ - if(HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAR)) - { - CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAR); - - /* Abort the UART DMA Rx channel */ - if(huart->hdmarx != NULL) - { - /* Set the UART DMA Abort callback : - will lead to call HAL_UART_ErrorCallback() at end of DMA abort procedure */ - huart->hdmarx->XferAbortCallback = UART_DMAAbortOnError; - if(HAL_DMA_Abort_IT(huart->hdmarx) != HAL_OK) - { - /* Call Directly XferAbortCallback function in case of error */ - huart->hdmarx->XferAbortCallback(huart->hdmarx); - } - } - else - { - /* Call user error callback */ - HAL_UART_ErrorCallback(huart); - } - } - else - { - /* Call user error callback */ - HAL_UART_ErrorCallback(huart); - } - } - else - { - /* Non Blocking error : transfer could go on. - Error is notified to user through user error callback */ - HAL_UART_ErrorCallback(huart); - huart->ErrorCode = HAL_UART_ERROR_NONE; - } - } - return; - } /* End if some error occurs */ - + + tmp_flag = __HAL_UART_GET_FLAG(huart, UART_FLAG_FE); + tmp_it_source = __HAL_UART_GET_IT_SOURCE(huart, UART_IT_ERR); + /* UART frame error interrupt occurred -------------------------------------*/ + if((tmp_flag != RESET) && (tmp_it_source != RESET)) + { + huart->ErrorCode |= HAL_UART_ERROR_FE; + } + + tmp_flag = __HAL_UART_GET_FLAG(huart, UART_FLAG_NE); + /* UART noise error interrupt occurred -------------------------------------*/ + if((tmp_flag != RESET) && (tmp_it_source != RESET)) + { + huart->ErrorCode |= HAL_UART_ERROR_NE; + } + + tmp_flag = __HAL_UART_GET_FLAG(huart, UART_FLAG_ORE); + /* UART Over-Run interrupt occurred ----------------------------------------*/ + if((tmp_flag != RESET) && (tmp_it_source != RESET)) + { + huart->ErrorCode |= HAL_UART_ERROR_ORE; + } + + tmp_flag = __HAL_UART_GET_FLAG(huart, UART_FLAG_RXNE); + tmp_it_source = __HAL_UART_GET_IT_SOURCE(huart, UART_IT_RXNE); + /* UART in mode Receiver ---------------------------------------------------*/ + if((tmp_flag != RESET) && (tmp_it_source != RESET)) + { + UART_Receive_IT(huart); + } + + tmp_flag = __HAL_UART_GET_FLAG(huart, UART_FLAG_TXE); + tmp_it_source = __HAL_UART_GET_IT_SOURCE(huart, UART_IT_TXE); /* UART in mode Transmitter ------------------------------------------------*/ - if(((isrflags & USART_SR_TXE) != RESET) && ((cr1its & USART_CR1_TXEIE) != RESET)) + if((tmp_flag != RESET) && (tmp_it_source != RESET)) { UART_Transmit_IT(huart); - return; } - + + tmp_flag = __HAL_UART_GET_FLAG(huart, UART_FLAG_TC); + tmp_it_source = __HAL_UART_GET_IT_SOURCE(huart, UART_IT_TC); /* UART in mode Transmitter end --------------------------------------------*/ - if(((isrflags & USART_SR_TC) != RESET) && ((cr1its & USART_CR1_TCIE) != RESET)) + if((tmp_flag != RESET) && (tmp_it_source != RESET)) { UART_EndTransmit_IT(huart); - return; - } + } + + if(huart->ErrorCode != HAL_UART_ERROR_NONE) + { + /* Clear all the error flag at once */ + __HAL_UART_CLEAR_PEFLAG(huart); + + /* Set the UART state ready to be able to start again the process */ + huart->State = HAL_UART_STATE_READY; + + HAL_UART_ErrorCallback(huart); + } } /** * @brief Tx Transfer completed callbacks. - * @param huart: pointer to a UART_HandleTypeDef structure that contains + * @param huart: Pointer to a UART_HandleTypeDef structure that contains * the configuration information for the specified UART module. * @retval None */ @@ -1685,14 +1266,14 @@ void HAL_UART_IRQHandler(UART_HandleTypeDef *huart) { /* Prevent unused argument(s) compilation warning */ UNUSED(huart); - /* NOTE: This function Should not be modified, when the callback is needed, - the HAL_UART_TxCpltCallback could be implemented in the user file + /* NOTE: This function should not be modified, when the callback is needed, + the HAL_UART_TxCpltCallback can be implemented in the user file */ } /** * @brief Tx Half Transfer completed callbacks. - * @param huart: pointer to a UART_HandleTypeDef structure that contains + * @param huart: Pointer to a UART_HandleTypeDef structure that contains * the configuration information for the specified UART module. * @retval None */ @@ -1700,14 +1281,14 @@ void HAL_UART_IRQHandler(UART_HandleTypeDef *huart) { /* Prevent unused argument(s) compilation warning */ UNUSED(huart); - /* NOTE: This function Should not be modified, when the callback is needed, - the HAL_UART_TxHalfCpltCallback could be implemented in the user file + /* NOTE: This function should not be modified, when the callback is needed, + the HAL_UART_TxHalfCpltCallback can be implemented in the user file */ } /** * @brief Rx Transfer completed callbacks. - * @param huart: pointer to a UART_HandleTypeDef structure that contains + * @param huart: Pointer to a UART_HandleTypeDef structure that contains * the configuration information for the specified UART module. * @retval None */ @@ -1715,14 +1296,14 @@ __weak void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) { /* Prevent unused argument(s) compilation warning */ UNUSED(huart); - /* NOTE: This function Should not be modified, when the callback is needed, - the HAL_UART_RxCpltCallback could be implemented in the user file + /* NOTE: This function should not be modified, when the callback is needed, + the HAL_UART_RxCpltCallback can be implemented in the user file */ } /** * @brief Rx Half Transfer completed callbacks. - * @param huart: pointer to a UART_HandleTypeDef structure that contains + * @param huart: Pointer to a UART_HandleTypeDef structure that contains * the configuration information for the specified UART module. * @retval None */ @@ -1730,68 +1311,24 @@ __weak void HAL_UART_RxHalfCpltCallback(UART_HandleTypeDef *huart) { /* Prevent unused argument(s) compilation warning */ UNUSED(huart); - /* NOTE: This function Should not be modified, when the callback is needed, - the HAL_UART_RxHalfCpltCallback could be implemented in the user file + /* NOTE: This function should not be modified, when the callback is needed, + the HAL_UART_RxHalfCpltCallback can be implemented in the user file */ } /** * @brief UART error callbacks. - * @param huart: pointer to a UART_HandleTypeDef structure that contains + * @param huart: Pointer to a UART_HandleTypeDef structure that contains * the configuration information for the specified UART module. * @retval None */ __weak void HAL_UART_ErrorCallback(UART_HandleTypeDef *huart) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(huart); - /* NOTE: This function Should not be modified, when the callback is needed, - the HAL_UART_ErrorCallback could be implemented in the user file - */ -} - -/** - * @brief UART Abort Complete callback. - * @param huart UART handle. - * @retval None - */ -__weak void HAL_UART_AbortCpltCallback (UART_HandleTypeDef *huart) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(huart); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_UART_AbortCpltCallback can be implemented in the user file. - */ -} -/** - * @brief UART Abort Complete callback. - * @param huart UART handle. - * @retval None - */ -__weak void HAL_UART_AbortTransmitCpltCallback (UART_HandleTypeDef *huart) { /* Prevent unused argument(s) compilation warning */ UNUSED(huart); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_UART_AbortTransmitCpltCallback can be implemented in the user file. - */ -} - -/** - * @brief UART Abort Receive Complete callback. - * @param huart UART handle. - * @retval None - */ -__weak void HAL_UART_AbortReceiveCpltCallback (UART_HandleTypeDef *huart) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(huart); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_UART_AbortReceiveCpltCallback can be implemented in the user file. - */ + /* NOTE: This function should not be modified, when the callback is needed, + the HAL_UART_ErrorCallback can be implemented in the user file + */ } /** @@ -1819,7 +1356,7 @@ __weak void HAL_UART_AbortReceiveCpltCallback (UART_HandleTypeDef *huart) /** * @brief Transmits break characters. - * @param huart: pointer to a UART_HandleTypeDef structure that contains + * @param huart: Pointer to a UART_HandleTypeDef structure that contains * the configuration information for the specified UART module. * @retval HAL status */ @@ -1831,12 +1368,12 @@ HAL_StatusTypeDef HAL_LIN_SendBreak(UART_HandleTypeDef *huart) /* Process Locked */ __HAL_LOCK(huart); - huart->gState = HAL_UART_STATE_BUSY; + huart->State = HAL_UART_STATE_BUSY; /* Send break characters */ SET_BIT(huart->Instance->CR1, USART_CR1_SBK); - huart->gState = HAL_UART_STATE_READY; + huart->State = HAL_UART_STATE_READY; /* Process Unlocked */ __HAL_UNLOCK(huart); @@ -1846,7 +1383,7 @@ HAL_StatusTypeDef HAL_LIN_SendBreak(UART_HandleTypeDef *huart) /** * @brief Enters the UART in mute mode. - * @param huart: pointer to a UART_HandleTypeDef structure that contains + * @param huart: Pointer to a UART_HandleTypeDef structure that contains * the configuration information for the specified UART module. * @retval HAL status */ @@ -1858,12 +1395,12 @@ HAL_StatusTypeDef HAL_MultiProcessor_EnterMuteMode(UART_HandleTypeDef *huart) /* Process Locked */ __HAL_LOCK(huart); - huart->gState = HAL_UART_STATE_BUSY; + huart->State = HAL_UART_STATE_BUSY; /* Enable the USART mute mode by setting the RWU bit in the CR1 register */ SET_BIT(huart->Instance->CR1, USART_CR1_RWU); - huart->gState = HAL_UART_STATE_READY; + huart->State = HAL_UART_STATE_READY; /* Process Unlocked */ __HAL_UNLOCK(huart); @@ -1873,7 +1410,7 @@ HAL_StatusTypeDef HAL_MultiProcessor_EnterMuteMode(UART_HandleTypeDef *huart) /** * @brief Exits the UART mute mode: wake up software. - * @param huart: pointer to a UART_HandleTypeDef structure that contains + * @param huart: Pointer to a UART_HandleTypeDef structure that contains * the configuration information for the specified UART module. * @retval HAL status */ @@ -1885,12 +1422,12 @@ HAL_StatusTypeDef HAL_MultiProcessor_ExitMuteMode(UART_HandleTypeDef *huart) /* Process Locked */ __HAL_LOCK(huart); - huart->gState = HAL_UART_STATE_BUSY; + huart->State = HAL_UART_STATE_BUSY; /* Disable the USART mute mode by clearing the RWU bit in the CR1 register */ CLEAR_BIT(huart->Instance->CR1, USART_CR1_RWU); - huart->gState = HAL_UART_STATE_READY; + huart->State = HAL_UART_STATE_READY; /* Process Unlocked */ __HAL_UNLOCK(huart); @@ -1900,32 +1437,23 @@ HAL_StatusTypeDef HAL_MultiProcessor_ExitMuteMode(UART_HandleTypeDef *huart) /** * @brief Enables the UART transmitter and disables the UART receiver. - * @param huart: pointer to a UART_HandleTypeDef structure that contains + * @param huart: Pointer to a UART_HandleTypeDef structure that contains * the configuration information for the specified UART module. * @retval HAL status */ HAL_StatusTypeDef HAL_HalfDuplex_EnableTransmitter(UART_HandleTypeDef *huart) { - uint32_t tmpreg = 0x00U; - /* Process Locked */ __HAL_LOCK(huart); - huart->gState = HAL_UART_STATE_BUSY; + huart->State = HAL_UART_STATE_BUSY; /*-------------------------- USART CR1 Configuration -----------------------*/ - tmpreg = huart->Instance->CR1; - /* Clear TE and RE bits */ - tmpreg &= (uint32_t)~((uint32_t)(USART_CR1_TE | USART_CR1_RE)); - /* Enable the USART's transmit interface by setting the TE bit in the USART CR1 register */ - tmpreg |= (uint32_t)USART_CR1_TE; - - /* Write to USART CR1 */ - WRITE_REG(huart->Instance->CR1, (uint32_t)tmpreg); - - huart->gState = HAL_UART_STATE_READY; + MODIFY_REG(huart->Instance->CR1, (uint32_t)(USART_CR1_TE | USART_CR1_RE), USART_CR1_TE); + + huart->State = HAL_UART_STATE_READY; /* Process Unlocked */ __HAL_UNLOCK(huart); @@ -1935,33 +1463,24 @@ HAL_StatusTypeDef HAL_HalfDuplex_EnableTransmitter(UART_HandleTypeDef *huart) /** * @brief Enables the UART receiver and disables the UART transmitter. - * @param huart: pointer to a UART_HandleTypeDef structure that contains + * @param huart: Pointer to a UART_HandleTypeDef structure that contains * the configuration information for the specified UART module. * @retval HAL status */ HAL_StatusTypeDef HAL_HalfDuplex_EnableReceiver(UART_HandleTypeDef *huart) { - uint32_t tmpreg = 0x00U; - /* Process Locked */ __HAL_LOCK(huart); - - huart->gState = HAL_UART_STATE_BUSY; + + huart->State = HAL_UART_STATE_BUSY; /*-------------------------- USART CR1 Configuration -----------------------*/ - tmpreg = huart->Instance->CR1; - /* Clear TE and RE bits */ - tmpreg &= (uint32_t)~((uint32_t)(USART_CR1_TE | USART_CR1_RE)); - /* Enable the USART's receive interface by setting the RE bit in the USART CR1 register */ - tmpreg |= (uint32_t)USART_CR1_RE; - - /* Write to USART CR1 */ - WRITE_REG(huart->Instance->CR1, (uint32_t)tmpreg); - - huart->gState = HAL_UART_STATE_READY; - + MODIFY_REG(huart->Instance->CR1, (uint32_t)(USART_CR1_TE | USART_CR1_RE), USART_CR1_RE); + + huart->State = HAL_UART_STATE_READY; + /* Process Unlocked */ __HAL_UNLOCK(huart); @@ -1992,25 +1511,21 @@ HAL_StatusTypeDef HAL_HalfDuplex_EnableReceiver(UART_HandleTypeDef *huart) /** * @brief Returns the UART state. - * @param huart: pointer to a UART_HandleTypeDef structure that contains + * @param huart: Pointer to a UART_HandleTypeDef structure that contains * the configuration information for the specified UART module. * @retval HAL state */ HAL_UART_StateTypeDef HAL_UART_GetState(UART_HandleTypeDef *huart) { - uint32_t temp1= 0x00U, temp2 = 0x00U; - temp1 = huart->gState; - temp2 = huart->RxState; - - return (HAL_UART_StateTypeDef)(temp1 | temp2); + return huart->State; } /** - * @brief Return the UART error code - * @param huart : pointer to a UART_HandleTypeDef structure that contains +* @brief Return the UART error code +* @param huart: Pointer to a UART_HandleTypeDef structure that contains * the configuration information for the specified UART. - * @retval UART Error Code - */ +* @retval UART Error Code +*/ uint32_t HAL_UART_GetError(UART_HandleTypeDef *huart) { return huart->ErrorCode; @@ -2020,26 +1535,34 @@ uint32_t HAL_UART_GetError(UART_HandleTypeDef *huart) * @} */ +/** + * @} + */ + +/** @defgroup UART_Private_Functions UART Private Functions + * @brief UART Private functions + * @{ + */ /** * @brief DMA UART transmit process complete callback. - * @param hdma: DMA handle + * @param hdma: Pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. * @retval None */ -static void UART_DMATransmitCplt(DMA_HandleTypeDef *hdma) +static void UART_DMATransmitCplt(DMA_HandleTypeDef *hdma) { UART_HandleTypeDef* huart = ( UART_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; /* DMA Normal mode*/ - if((hdma->Instance->CCR & DMA_CCR_CIRC) == 0U) + if ( HAL_IS_BIT_CLR(hdma->Instance->CCR, DMA_CCR_CIRC) ) { - huart->TxXferCount = 0U; + huart->TxXferCount = 0; /* Disable the DMA transfer for transmit request by setting the DMAT bit in the UART CR3 register */ CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAT); - /* Enable the UART Transmit Complete Interrupt */ - SET_BIT(huart->Instance->CR1, USART_CR1_TCIE); - + /* Enable the UART Transmit Complete Interrupt */ + __HAL_UART_ENABLE_IT(huart, UART_IT_TC); } /* DMA Circular mode */ else @@ -2050,8 +1573,8 @@ static void UART_DMATransmitCplt(DMA_HandleTypeDef *hdma) /** * @brief DMA UART transmit process half complete callback - * @param hdma: pointer to a DMA_HandleTypeDef structure that contains - * the configuration information for the specified DMA module. + * @param hdma: Pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. * @retval None */ static void UART_DMATxHalfCplt(DMA_HandleTypeDef *hdma) @@ -2063,271 +1586,132 @@ static void UART_DMATxHalfCplt(DMA_HandleTypeDef *hdma) /** * @brief DMA UART receive process complete callback. - * @param hdma: DMA handle + * @param hdma: Pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. * @retval None */ -static void UART_DMAReceiveCplt(DMA_HandleTypeDef *hdma) +static void UART_DMAReceiveCplt(DMA_HandleTypeDef *hdma) { UART_HandleTypeDef* huart = ( UART_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; /* DMA Normal mode*/ - if((hdma->Instance->CCR & DMA_CCR_CIRC) == 0U) + if ( HAL_IS_BIT_CLR(hdma->Instance->CCR, DMA_CCR_CIRC) ) { - huart->RxXferCount = 0U; + huart->RxXferCount = 0; - /* Disable RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */ - CLEAR_BIT(huart->Instance->CR1, USART_CR1_PEIE); - CLEAR_BIT(huart->Instance->CR3, USART_CR3_EIE); - /* Disable the DMA transfer for the receiver request by setting the DMAR bit in the UART CR3 register */ CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAR); - /* At end of Rx process, restore huart->RxState to Ready */ - huart->RxState = HAL_UART_STATE_READY; + /* Check if a transmit process is ongoing or not */ + if(huart->State == HAL_UART_STATE_BUSY_TX_RX) + { + huart->State = HAL_UART_STATE_BUSY_TX; + } + else + { + huart->State = HAL_UART_STATE_READY; + } } HAL_UART_RxCpltCallback(huart); } /** * @brief DMA UART receive process half complete callback - * @param hdma: pointer to a DMA_HandleTypeDef structure that contains - * the configuration information for the specified DMA module. + * @param hdma: Pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. * @retval None */ static void UART_DMARxHalfCplt(DMA_HandleTypeDef *hdma) { UART_HandleTypeDef* huart = (UART_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent; + HAL_UART_RxHalfCpltCallback(huart); } /** * @brief DMA UART communication error callback. - * @param hdma: DMA handle + * @param hdma: Pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. * @retval None */ -static void UART_DMAError(DMA_HandleTypeDef *hdma) +static void UART_DMAError(DMA_HandleTypeDef *hdma) { - uint32_t dmarequest = 0x00U; UART_HandleTypeDef* huart = ( UART_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; - - /* Stop UART DMA Tx request if ongoing */ - dmarequest = HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAT); - if((huart->gState == HAL_UART_STATE_BUSY_TX) && dmarequest) - { - huart->TxXferCount = 0U; - UART_EndTxTransfer(huart); - } - - /* Stop UART DMA Rx request if ongoing */ - dmarequest = HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAR); - if((huart->RxState == HAL_UART_STATE_BUSY_RX) && dmarequest) - { - huart->RxXferCount = 0U; - UART_EndRxTransfer(huart); - } - + huart->RxXferCount = 0; + huart->TxXferCount = 0; + huart->State= HAL_UART_STATE_READY; huart->ErrorCode |= HAL_UART_ERROR_DMA; HAL_UART_ErrorCallback(huart); } /** * @brief This function handles UART Communication Timeout. - * @param huart: pointer to a UART_HandleTypeDef structure that contains + * @param huart: Pointer to a UART_HandleTypeDef structure that contains * the configuration information for the specified UART module. * @param Flag: specifies the UART flag to check. * @param Status: The new Flag status (SET or RESET). - * @param Tickstart Tick start value * @param Timeout: Timeout duration * @retval HAL status */ -static HAL_StatusTypeDef UART_WaitOnFlagUntilTimeout(UART_HandleTypeDef *huart, uint32_t Flag, FlagStatus Status, uint32_t Tickstart, uint32_t Timeout) +static HAL_StatusTypeDef UART_WaitOnFlagUntilTimeout(UART_HandleTypeDef *huart, uint32_t Flag, FlagStatus Status, uint32_t Timeout) { + uint32_t tickstart = 0; + + /* Get tick */ + tickstart = HAL_GetTick(); + /* Wait until flag is set */ - while((__HAL_UART_GET_FLAG(huart, Flag) ? SET : RESET) == Status) + if(Status == RESET) { - /* Check for the Timeout */ - if(Timeout != HAL_MAX_DELAY) + while(__HAL_UART_GET_FLAG(huart, Flag) == RESET) { - if((Timeout == 0U)||((HAL_GetTick() - Tickstart ) > Timeout)) + /* Check for the Timeout */ + if(Timeout != HAL_MAX_DELAY) { - /* Disable TXE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts for the interrupt process */ - CLEAR_BIT(huart->Instance->CR1, (USART_CR1_RXNEIE | USART_CR1_PEIE | USART_CR1_TXEIE)); - CLEAR_BIT(huart->Instance->CR3, USART_CR3_EIE); - - huart->gState = HAL_UART_STATE_READY; - huart->RxState = HAL_UART_STATE_READY; - - /* Process Unlocked */ - __HAL_UNLOCK(huart); - - return HAL_TIMEOUT; - } - } - } - - return HAL_OK; -} - -/** - * @brief End ongoing Tx transfer on UART peripheral (following error detection or Transmit completion). - * @param huart: UART handle. - * @retval None - */ -static void UART_EndTxTransfer(UART_HandleTypeDef *huart) -{ - /* Disable TXEIE and TCIE interrupts */ - CLEAR_BIT(huart->Instance->CR1, (USART_CR1_TXEIE | USART_CR1_TCIE)); - - /* At end of Tx process, restore huart->gState to Ready */ - huart->gState = HAL_UART_STATE_READY; -} - -/** - * @brief End ongoing Rx transfer on UART peripheral (following error detection or Reception completion). - * @param huart: UART handle. - * @retval None - */ -static void UART_EndRxTransfer(UART_HandleTypeDef *huart) -{ - /* Disable RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */ - CLEAR_BIT(huart->Instance->CR1, (USART_CR1_RXNEIE | USART_CR1_PEIE)); - CLEAR_BIT(huart->Instance->CR3, USART_CR3_EIE); + if((Timeout == 0)||((HAL_GetTick() - tickstart ) > Timeout)) + { + /* Disable TXE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts for the interrupt process */ + __HAL_UART_DISABLE_IT(huart, UART_IT_TXE); + __HAL_UART_DISABLE_IT(huart, UART_IT_RXNE); + __HAL_UART_DISABLE_IT(huart, UART_IT_PE); + __HAL_UART_DISABLE_IT(huart, UART_IT_ERR); - /* At end of Rx process, restore huart->RxState to Ready */ - huart->RxState = HAL_UART_STATE_READY; -} + huart->State= HAL_UART_STATE_READY; -/** - * @brief DMA UART communication abort callback, when initiated by HAL services on Error - * (To be called at end of DMA Abort procedure following error occurrence). - * @param hdma DMA handle. - * @retval None - */ -static void UART_DMAAbortOnError(DMA_HandleTypeDef *hdma) -{ - UART_HandleTypeDef* huart = ( UART_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; - huart->RxXferCount = 0x00U; - huart->TxXferCount = 0x00U; + /* Process Unlocked */ + __HAL_UNLOCK(huart); - HAL_UART_ErrorCallback(huart); -} - -/** - * @brief DMA UART Tx communication abort callback, when initiated by user - * (To be called at end of DMA Tx Abort procedure following user abort request). - * @note When this callback is executed, User Abort complete call back is called only if no - * Abort still ongoing for Rx DMA Handle. - * @param hdma DMA handle. - * @retval None - */ -static void UART_DMATxAbortCallback(DMA_HandleTypeDef *hdma) -{ - UART_HandleTypeDef* huart = ( UART_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; - - huart->hdmatx->XferAbortCallback = NULL; - - /* Check if an Abort process is still ongoing */ - if(huart->hdmarx != NULL) - { - if(huart->hdmarx->XferAbortCallback != NULL) - { - return; + return HAL_TIMEOUT; + } + } } } - - /* No Abort process still ongoing : All DMA channels are aborted, call user Abort Complete callback */ - huart->TxXferCount = 0x00U; - huart->RxXferCount = 0x00U; - - /* Reset ErrorCode */ - huart->ErrorCode = HAL_UART_ERROR_NONE; - - /* Restore huart->gState and huart->RxState to Ready */ - huart->gState = HAL_UART_STATE_READY; - huart->RxState = HAL_UART_STATE_READY; - - /* Call user Abort complete callback */ - HAL_UART_AbortCpltCallback(huart); -} - -/** - * @brief DMA UART Rx communication abort callback, when initiated by user - * (To be called at end of DMA Rx Abort procedure following user abort request). - * @note When this callback is executed, User Abort complete call back is called only if no - * Abort still ongoing for Tx DMA Handle. - * @param hdma DMA handle. - * @retval None - */ -static void UART_DMARxAbortCallback(DMA_HandleTypeDef *hdma) -{ - UART_HandleTypeDef* huart = ( UART_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; - - huart->hdmarx->XferAbortCallback = NULL; - - /* Check if an Abort process is still ongoing */ - if(huart->hdmatx != NULL) + else { - if(huart->hdmatx->XferAbortCallback != NULL) + while(__HAL_UART_GET_FLAG(huart, Flag) != RESET) { - return; - } - } - - /* No Abort process still ongoing : All DMA channels are aborted, call user Abort Complete callback */ - huart->TxXferCount = 0x00U; - huart->RxXferCount = 0x00U; - - /* Reset ErrorCode */ - huart->ErrorCode = HAL_UART_ERROR_NONE; - - /* Restore huart->gState and huart->RxState to Ready */ - huart->gState = HAL_UART_STATE_READY; - huart->RxState = HAL_UART_STATE_READY; - - /* Call user Abort complete callback */ - HAL_UART_AbortCpltCallback(huart); -} - -/** - * @brief DMA UART Tx communication abort callback, when initiated by user by a call to - * HAL_UART_AbortTransmit_IT API (Abort only Tx transfer) - * (This callback is executed at end of DMA Tx Abort procedure following user abort request, - * and leads to user Tx Abort Complete callback execution). - * @param hdma DMA handle. - * @retval None - */ -static void UART_DMATxOnlyAbortCallback(DMA_HandleTypeDef *hdma) -{ - UART_HandleTypeDef* huart = ( UART_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; - - huart->TxXferCount = 0x00U; - - /* Restore huart->gState to Ready */ - huart->gState = HAL_UART_STATE_READY; - - /* Call user Abort complete callback */ - HAL_UART_AbortTransmitCpltCallback(huart); -} - -/** - * @brief DMA UART Rx communication abort callback, when initiated by user by a call to - * HAL_UART_AbortReceive_IT API (Abort only Rx transfer) - * (This callback is executed at end of DMA Rx Abort procedure following user abort request, - * and leads to user Rx Abort Complete callback execution). - * @param hdma DMA handle. - * @retval None - */ -static void UART_DMARxOnlyAbortCallback(DMA_HandleTypeDef *hdma) -{ - UART_HandleTypeDef* huart = ( UART_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + /* Check for the Timeout */ + if(Timeout != HAL_MAX_DELAY) + { + if((Timeout == 0)||((HAL_GetTick() - tickstart ) > Timeout)) + { + /* Disable TXE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts for the interrupt process */ + __HAL_UART_DISABLE_IT(huart, UART_IT_TXE); + __HAL_UART_DISABLE_IT(huart, UART_IT_RXNE); + __HAL_UART_DISABLE_IT(huart, UART_IT_PE); + __HAL_UART_DISABLE_IT(huart, UART_IT_ERR); - huart->RxXferCount = 0x00U; + huart->State= HAL_UART_STATE_READY; - /* Restore huart->RxState to Ready */ - huart->RxState = HAL_UART_STATE_READY; + /* Process Unlocked */ + __HAL_UNLOCK(huart); - /* Call user Abort complete callback */ - HAL_UART_AbortReceiveCpltCallback(huart); + return HAL_TIMEOUT; + } + } + } + } + return HAL_OK; } /** @@ -2339,9 +1723,10 @@ static void UART_DMARxOnlyAbortCallback(DMA_HandleTypeDef *hdma) static HAL_StatusTypeDef UART_Transmit_IT(UART_HandleTypeDef *huart) { uint16_t* tmp; + uint32_t tmp_state = 0; - /* Check that a Tx process is ongoing */ - if(huart->gState == HAL_UART_STATE_BUSY_TX) + tmp_state = huart->State; + if((tmp_state == HAL_UART_STATE_BUSY_TX) || (tmp_state == HAL_UART_STATE_BUSY_TX_RX)) { if(huart->Init.WordLength == UART_WORDLENGTH_9B) { @@ -2349,11 +1734,11 @@ static HAL_StatusTypeDef UART_Transmit_IT(UART_HandleTypeDef *huart) huart->Instance->DR = (uint16_t)(*tmp & (uint16_t)0x01FF); if(huart->Init.Parity == UART_PARITY_NONE) { - huart->pTxBuffPtr += 2U; + huart->pTxBuffPtr += 2; } else { - huart->pTxBuffPtr += 1U; + huart->pTxBuffPtr += 1; } } else @@ -2361,7 +1746,7 @@ static HAL_StatusTypeDef UART_Transmit_IT(UART_HandleTypeDef *huart) huart->Instance->DR = (uint8_t)(*huart->pTxBuffPtr++ & (uint8_t)0x00FF); } - if(--huart->TxXferCount == 0U) + if(--huart->TxXferCount == 0) { /* Disable the UART Transmit Complete Interrupt */ __HAL_UART_DISABLE_IT(huart, UART_IT_TXE); @@ -2377,6 +1762,7 @@ static HAL_StatusTypeDef UART_Transmit_IT(UART_HandleTypeDef *huart) } } + /** * @brief Wraps up transmission in non blocking mode. * @param huart: pointer to a UART_HandleTypeDef structure that contains @@ -2388,8 +1774,16 @@ static HAL_StatusTypeDef UART_EndTransmit_IT(UART_HandleTypeDef *huart) /* Disable the UART Transmit Complete Interrupt */ __HAL_UART_DISABLE_IT(huart, UART_IT_TC); - /* Tx process is ended, restore huart->gState to Ready */ - huart->gState = HAL_UART_STATE_READY; + /* Check if a receive process is ongoing or not */ + if(huart->State == HAL_UART_STATE_BUSY_TX_RX) + { + huart->State = HAL_UART_STATE_BUSY_RX; + } + else + { + huart->State = HAL_UART_STATE_READY; + } + HAL_UART_TxCpltCallback(huart); return HAL_OK; @@ -2397,16 +1791,17 @@ static HAL_StatusTypeDef UART_EndTransmit_IT(UART_HandleTypeDef *huart) /** * @brief Receives an amount of data in non blocking mode - * @param huart: pointer to a UART_HandleTypeDef structure that contains + * @param huart: Pointer to a UART_HandleTypeDef structure that contains * the configuration information for the specified UART module. * @retval HAL status */ static HAL_StatusTypeDef UART_Receive_IT(UART_HandleTypeDef *huart) { uint16_t* tmp; + uint32_t tmp_state = 0; - /* Check that a Rx process is ongoing */ - if(huart->RxState == HAL_UART_STATE_BUSY_RX) + tmp_state = huart->State; + if((tmp_state == HAL_UART_STATE_BUSY_RX) || (tmp_state == HAL_UART_STATE_BUSY_TX_RX)) { if(huart->Init.WordLength == UART_WORDLENGTH_9B) { @@ -2414,12 +1809,12 @@ static HAL_StatusTypeDef UART_Receive_IT(UART_HandleTypeDef *huart) if(huart->Init.Parity == UART_PARITY_NONE) { *tmp = (uint16_t)(huart->Instance->DR & (uint16_t)0x01FF); - huart->pRxBuffPtr += 2U; + huart->pRxBuffPtr += 2; } else { *tmp = (uint16_t)(huart->Instance->DR & (uint16_t)0x00FF); - huart->pRxBuffPtr += 1U; + huart->pRxBuffPtr += 1; } } else @@ -2434,19 +1829,25 @@ static HAL_StatusTypeDef UART_Receive_IT(UART_HandleTypeDef *huart) } } - if(--huart->RxXferCount == 0U) + if(--huart->RxXferCount == 0) { - /* Disable the IRDA Data Register not empty Interrupt */ __HAL_UART_DISABLE_IT(huart, UART_IT_RXNE); - /* Disable the UART Parity Error Interrupt */ - __HAL_UART_DISABLE_IT(huart, UART_IT_PE); + /* Check if a transmit process is ongoing or not */ + if(huart->State == HAL_UART_STATE_BUSY_TX_RX) + { + huart->State = HAL_UART_STATE_BUSY_TX; + } + else + { + /* Disable the UART Parity Error Interrupt */ + __HAL_UART_DISABLE_IT(huart, UART_IT_PE); + /* Disable the UART Error Interrupt: (Frame error, noise error, overrun error) */ __HAL_UART_DISABLE_IT(huart, UART_IT_ERR); - /* Rx process is completed, restore huart->RxState to Ready */ - huart->RxState = HAL_UART_STATE_READY; - + huart->State = HAL_UART_STATE_READY; + } HAL_UART_RxCpltCallback(huart); return HAL_OK; @@ -2455,22 +1856,22 @@ static HAL_StatusTypeDef UART_Receive_IT(UART_HandleTypeDef *huart) } else { - return HAL_BUSY; + return HAL_BUSY; } } /** * @brief Configures the UART peripheral. - * @param huart: pointer to a UART_HandleTypeDef structure that contains + * @param huart: Pointer to a UART_HandleTypeDef structure that contains * the configuration information for the specified UART module. * @retval None */ static void UART_SetConfig(UART_HandleTypeDef *huart) { - uint32_t tmpreg = 0x00U; - + uint32_t tmpreg = 0x00; + /* Check the parameters */ - assert_param(IS_UART_BAUDRATE(huart->Init.BaudRate)); + assert_param(IS_UART_BAUDRATE(huart->Init.BaudRate)); assert_param(IS_UART_STOPBITS(huart->Init.StopBits)); assert_param(IS_UART_PARITY(huart->Init.Parity)); assert_param(IS_UART_MODE(huart->Init.Mode)); @@ -2484,54 +1885,18 @@ static void UART_SetConfig(UART_HandleTypeDef *huart) /* Configure the UART Word Length, Parity and mode: Set the M bits according to huart->Init.WordLength value Set PCE and PS bits according to huart->Init.Parity value - Set TE and RE bits according to huart->Init.Mode value - Set OVER8 bit according to huart->Init.OverSampling value */ - -#if defined(USART_CR1_OVER8) - tmpreg |= (uint32_t)huart->Init.WordLength | huart->Init.Parity | huart->Init.Mode | huart->Init.OverSampling; - MODIFY_REG(huart->Instance->CR1, - (uint32_t)(USART_CR1_M | USART_CR1_PCE | USART_CR1_PS | USART_CR1_TE | USART_CR1_RE | USART_CR1_OVER8), - tmpreg); -#else - tmpreg |= (uint32_t)huart->Init.WordLength | huart->Init.Parity | huart->Init.Mode; + Set TE and RE bits according to huart->Init.Mode value */ + tmpreg = (uint32_t)huart->Init.WordLength | huart->Init.Parity | huart->Init.Mode ; MODIFY_REG(huart->Instance->CR1, (uint32_t)(USART_CR1_M | USART_CR1_PCE | USART_CR1_PS | USART_CR1_TE | USART_CR1_RE), tmpreg); -#endif /* USART_CR1_OVER8 */ - + /*------- UART-associated USART registers setting : CR3 Configuration ------*/ /* Configure the UART HFC: Set CTSE and RTSE bits according to huart->Init.HwFlowCtl value */ MODIFY_REG(huart->Instance->CR3, (USART_CR3_RTSE | USART_CR3_CTSE), huart->Init.HwFlowCtl); - -#if defined(USART_CR1_OVER8) - /* Check the Over Sampling */ - if(huart->Init.OverSampling == UART_OVERSAMPLING_8) - { - /*-------------------------- USART BRR Configuration ---------------------*/ - if(huart->Instance == USART1) - { - huart->Instance->BRR = UART_BRR_SAMPLING8(HAL_RCC_GetPCLK2Freq(), huart->Init.BaudRate); - } - else - { - huart->Instance->BRR = UART_BRR_SAMPLING8(HAL_RCC_GetPCLK1Freq(), huart->Init.BaudRate); - } - } - else - { - /*-------------------------- USART BRR Configuration ---------------------*/ - if(huart->Instance == USART1) - { - huart->Instance->BRR = UART_BRR_SAMPLING16(HAL_RCC_GetPCLK2Freq(), huart->Init.BaudRate); - } - else - { - huart->Instance->BRR = UART_BRR_SAMPLING16(HAL_RCC_GetPCLK1Freq(), huart->Init.BaudRate); - } - } -#else - /*-------------------------- USART BRR Configuration ---------------------*/ - if(huart->Instance == USART1) + + /*------- UART-associated USART registers setting : BRR Configuration ------*/ + if((huart->Instance == USART1)) { huart->Instance->BRR = UART_BRR_SAMPLING16(HAL_RCC_GetPCLK2Freq(), huart->Init.BaudRate); } @@ -2539,9 +1904,7 @@ static void UART_SetConfig(UART_HandleTypeDef *huart) { huart->Instance->BRR = UART_BRR_SAMPLING16(HAL_RCC_GetPCLK1Freq(), huart->Init.BaudRate); } -#endif /* USART_CR1_OVER8 */ } - /** * @} */ diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_uart.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_uart.h index a8639814cbc..03c2d80b532 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_uart.h +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_uart.h @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_hal_uart.h * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief Header file of UART HAL module. ****************************************************************************** * @attention @@ -33,7 +33,7 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** - */ + */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F1xx_HAL_UART_H @@ -52,16 +52,17 @@ /** @addtogroup UART * @{ - */ + */ /* Exported types ------------------------------------------------------------*/ /** @defgroup UART_Exported_Types UART Exported Types * @{ - */ + */ -/** + +/** * @brief UART Init Structure definition - */ + */ typedef struct { uint32_t BaudRate; /*!< This member configures the UART communication baud rate. @@ -81,81 +82,38 @@ typedef struct at the MSB position of the transmitted data (9th bit when the word length is set to 9 data bits; 8th bit when the word length is set to 8 data bits). */ - - uint32_t Mode; /*!< Specifies whether the Receive or Transmit mode is enabled or disabled. + + uint32_t Mode; /*!< Specifies wether the Receive or Transmit mode is enabled or disabled. This parameter can be a value of @ref UART_Mode */ - uint32_t HwFlowCtl; /*!< Specifies whether the hardware flow control mode is enabled or disabled. + uint32_t HwFlowCtl; /*!< Specifies wether the hardware flow control mode is enabled + or disabled. This parameter can be a value of @ref UART_Hardware_Flow_Control */ - + uint32_t OverSampling; /*!< Specifies whether the Over sampling 8 is enabled or disabled, to achieve higher speed (up to fPCLK/8). - This parameter can be a value of @ref UART_Over_Sampling. This feature is only available - on STM32F100xx family, so OverSampling parameter should always be set to 16. */ + This parameter can be a value of @ref UART_Over_Sampling. This feature is not available + on STM32F1xx family, so OverSampling parameter should always be set to 16. */ }UART_InitTypeDef; /** - * @brief HAL UART State structures definition - * @note HAL UART State value is a combination of 2 different substates: gState and RxState. - * - gState contains UART state information related to global Handle management - * and also information related to Tx operations. - * gState value coding follow below described bitmap : - * b7-b6 Error information - * 00 : No Error - * 01 : (Not Used) - * 10 : Timeout - * 11 : Error - * b5 IP initilisation status - * 0 : Reset (IP not initialized) - * 1 : Init done (IP not initialized. HAL UART Init function already called) - * b4-b3 (not used) - * xx : Should be set to 00 - * b2 Intrinsic process state - * 0 : Ready - * 1 : Busy (IP busy with some configuration or internal operations) - * b1 (not used) - * x : Should be set to 0 - * b0 Tx state - * 0 : Ready (no Tx operation ongoing) - * 1 : Busy (Tx operation ongoing) - * - RxState contains information related to Rx operations. - * RxState value coding follow below described bitmap : - * b7-b6 (not used) - * xx : Should be set to 00 - * b5 IP initilisation status - * 0 : Reset (IP not initialized) - * 1 : Init done (IP not initialized) - * b4-b2 (not used) - * xxx : Should be set to 000 - * b1 Rx state - * 0 : Ready (no Rx operation ongoing) - * 1 : Busy (Rx operation ongoing) - * b0 (not used) - * x : Should be set to 0. - */ + * @brief HAL UART State structures definition + */ typedef enum { - HAL_UART_STATE_RESET = 0x00U, /*!< Peripheral is not yet Initialized - Value is allowed for gState and RxState */ - HAL_UART_STATE_READY = 0x20U, /*!< Peripheral Initialized and ready for use - Value is allowed for gState and RxState */ - HAL_UART_STATE_BUSY = 0x24U, /*!< an internal process is ongoing - Value is allowed for gState only */ - HAL_UART_STATE_BUSY_TX = 0x21U, /*!< Data Transmission process is ongoing - Value is allowed for gState only */ - HAL_UART_STATE_BUSY_RX = 0x22U, /*!< Data Reception process is ongoing - Value is allowed for RxState only */ - HAL_UART_STATE_BUSY_TX_RX = 0x23U, /*!< Data Transmission and Reception process is ongoing - Not to be used for neither gState nor RxState. - Value is result of combination (Or) between gState and RxState values */ - HAL_UART_STATE_TIMEOUT = 0xA0U, /*!< Timeout state - Value is allowed for gState only */ - HAL_UART_STATE_ERROR = 0xE0U /*!< Error - Value is allowed for gState only */ + HAL_UART_STATE_RESET = 0x00, /*!< Peripheral is not initialized */ + HAL_UART_STATE_READY = 0x01, /*!< Peripheral Initialized and ready for use */ + HAL_UART_STATE_BUSY = 0x02, /*!< an internal process is ongoing */ + HAL_UART_STATE_BUSY_TX = 0x12, /*!< Data Transmission process is ongoing */ + HAL_UART_STATE_BUSY_RX = 0x22, /*!< Data Reception process is ongoing */ + HAL_UART_STATE_BUSY_TX_RX = 0x32, /*!< Data Transmission and Reception process is ongoing */ + HAL_UART_STATE_TIMEOUT = 0x03, /*!< Timeout state */ + HAL_UART_STATE_ERROR = 0x04 /*!< Error */ }HAL_UART_StateTypeDef; + /** - * @brief UART handle Structure definition - */ + * @brief UART handle Structure definition + */ typedef struct { USART_TypeDef *Instance; /*!< UART registers base address */ @@ -166,13 +124,13 @@ typedef struct uint16_t TxXferSize; /*!< UART Tx Transfer size */ - __IO uint16_t TxXferCount; /*!< UART Tx Transfer Counter */ + uint16_t TxXferCount; /*!< UART Tx Transfer Counter */ uint8_t *pRxBuffPtr; /*!< Pointer to UART Rx transfer Buffer */ uint16_t RxXferSize; /*!< UART Rx Transfer size */ - __IO uint16_t RxXferCount; /*!< UART Rx Transfer Counter */ + uint16_t RxXferCount; /*!< UART Rx Transfer Counter */ DMA_HandleTypeDef *hdmatx; /*!< UART Tx DMA Handle parameters */ @@ -180,14 +138,10 @@ typedef struct HAL_LockTypeDef Lock; /*!< Locking object */ - __IO HAL_UART_StateTypeDef gState; /*!< UART state information related to global Handle management - and also related to Tx operations. - This parameter can be a value of @ref HAL_UART_StateTypeDef */ + __IO HAL_UART_StateTypeDef State; /*!< UART communication state */ - __IO HAL_UART_StateTypeDef RxState; /*!< UART state information related to Rx operations. - This parameter can be a value of @ref HAL_UART_StateTypeDef */ - __IO uint32_t ErrorCode; /*!< UART Error code */ + }UART_HandleTypeDef; /** @@ -199,51 +153,56 @@ typedef struct * @{ */ -/** @defgroup UART_Error_Code UART Error Code +/** @defgroup UART_Error_Codes UART Error Codes * @{ */ -#define HAL_UART_ERROR_NONE 0x00000000U /*!< No error */ -#define HAL_UART_ERROR_PE 0x00000001U /*!< Parity error */ -#define HAL_UART_ERROR_NE 0x00000002U /*!< Noise error */ -#define HAL_UART_ERROR_FE 0x00000004U /*!< Frame error */ -#define HAL_UART_ERROR_ORE 0x00000008U /*!< Overrun error */ -#define HAL_UART_ERROR_DMA 0x00000010U /*!< DMA transfer error */ + +#define HAL_UART_ERROR_NONE ((uint32_t)0x00) /*!< No error */ +#define HAL_UART_ERROR_PE ((uint32_t)0x01) /*!< Parity error */ +#define HAL_UART_ERROR_NE ((uint32_t)0x02) /*!< Noise error */ +#define HAL_UART_ERROR_FE ((uint32_t)0x04) /*!< frame error */ +#define HAL_UART_ERROR_ORE ((uint32_t)0x08) /*!< Overrun error */ +#define HAL_UART_ERROR_DMA ((uint32_t)0x10) /*!< DMA transfer error */ + /** * @} */ -/** @defgroup UART_Word_Length UART Word Length + + + +/** @defgroup UART_Word_Length UART Word Length * @{ */ -#define UART_WORDLENGTH_8B 0x00000000U +#define UART_WORDLENGTH_8B ((uint32_t)0x00000000) #define UART_WORDLENGTH_9B ((uint32_t)USART_CR1_M) /** * @} */ -/** @defgroup UART_Stop_Bits UART Number of Stop Bits +/** @defgroup UART_Stop_Bits UART Number of Stop Bits * @{ */ -#define UART_STOPBITS_1 0x00000000U +#define UART_STOPBITS_1 ((uint32_t)0x00000000) #define UART_STOPBITS_2 ((uint32_t)USART_CR2_STOP_1) /** * @} - */ + */ /** @defgroup UART_Parity UART Parity * @{ - */ -#define UART_PARITY_NONE 0x00000000U + */ +#define UART_PARITY_NONE ((uint32_t)0x00000000) #define UART_PARITY_EVEN ((uint32_t)USART_CR1_PCE) #define UART_PARITY_ODD ((uint32_t)(USART_CR1_PCE | USART_CR1_PS)) /** * @} - */ + */ /** @defgroup UART_Hardware_Flow_Control UART Hardware Flow Control * @{ - */ -#define UART_HWCONTROL_NONE 0x00000000U + */ +#define UART_HWCONTROL_NONE ((uint32_t)0x00000000) #define UART_HWCONTROL_RTS ((uint32_t)USART_CR3_RTSE) #define UART_HWCONTROL_CTS ((uint32_t)USART_CR3_CTSE) #define UART_HWCONTROL_RTS_CTS ((uint32_t)(USART_CR3_RTSE | USART_CR3_CTSE)) @@ -257,44 +216,41 @@ typedef struct #define UART_MODE_RX ((uint32_t)USART_CR1_RE) #define UART_MODE_TX ((uint32_t)USART_CR1_TE) #define UART_MODE_TX_RX ((uint32_t)(USART_CR1_TE |USART_CR1_RE)) + /** * @} */ - -/** @defgroup UART_State UART State + + /** @defgroup UART_State UART State * @{ - */ -#define UART_STATE_DISABLE 0x00000000U + */ +#define UART_STATE_DISABLE ((uint32_t)0x00000000) #define UART_STATE_ENABLE ((uint32_t)USART_CR1_UE) /** * @} */ - /** @defgroup UART_Over_Sampling UART Over Sampling * @{ */ -#define UART_OVERSAMPLING_16 0x00000000U -#if defined(USART_CR1_OVER8) -#define UART_OVERSAMPLING_8 ((uint32_t)USART_CR1_OVER8) -#endif /* USART_CR1_OVER8 */ +#define UART_OVERSAMPLING_16 ((uint32_t)0x00000000) /** * @} */ - /** @defgroup UART_LIN_Break_Detection_Length UART LIN Break Detection Length * @{ */ -#define UART_LINBREAKDETECTLENGTH_10B 0x00000000U +#define UART_LINBREAKDETECTLENGTH_10B ((uint32_t)0x00000000) #define UART_LINBREAKDETECTLENGTH_11B ((uint32_t)USART_CR2_LBDL) /** * @} */ -/** @defgroup UART_WakeUp_functions UART Wakeup Functions + +/** @defgroup UART_WakeUp_functions UART Wakeup Functions * @{ */ -#define UART_WAKEUPMETHOD_IDLELINE 0x00000000U +#define UART_WAKEUPMETHOD_IDLELINE ((uint32_t)0x00000000) #define UART_WAKEUPMETHOD_ADDRESSMARK ((uint32_t)USART_CR1_WAKE) /** * @} @@ -323,22 +279,24 @@ typedef struct * Elements values convention: 0xY000XXXX * - XXXX : Interrupt mask (16 bits) in the Y register * - Y : Interrupt source register (2bits) - * - 01: CR1 register - * - 10: CR2 register - * - 11: CR3 register + * - 0001: CR1 register + * - 0010: CR2 register + * - 0011: CR3 register + * * @{ - */ + */ + +#define UART_IT_PE ((uint32_t)(UART_CR1_REG_INDEX << 28 | USART_CR1_PEIE)) +#define UART_IT_TXE ((uint32_t)(UART_CR1_REG_INDEX << 28 | USART_CR1_TXEIE)) +#define UART_IT_TC ((uint32_t)(UART_CR1_REG_INDEX << 28 | USART_CR1_TCIE)) +#define UART_IT_RXNE ((uint32_t)(UART_CR1_REG_INDEX << 28 | USART_CR1_RXNEIE)) +#define UART_IT_IDLE ((uint32_t)(UART_CR1_REG_INDEX << 28 | USART_CR1_IDLEIE)) -#define UART_IT_PE ((uint32_t)(UART_CR1_REG_INDEX << 28U | USART_CR1_PEIE)) -#define UART_IT_TXE ((uint32_t)(UART_CR1_REG_INDEX << 28U | USART_CR1_TXEIE)) -#define UART_IT_TC ((uint32_t)(UART_CR1_REG_INDEX << 28U | USART_CR1_TCIE)) -#define UART_IT_RXNE ((uint32_t)(UART_CR1_REG_INDEX << 28U | USART_CR1_RXNEIE)) -#define UART_IT_IDLE ((uint32_t)(UART_CR1_REG_INDEX << 28U | USART_CR1_IDLEIE)) +#define UART_IT_LBD ((uint32_t)(UART_CR2_REG_INDEX << 28 | USART_CR2_LBDIE)) -#define UART_IT_LBD ((uint32_t)(UART_CR2_REG_INDEX << 28U | USART_CR2_LBDIE)) +#define UART_IT_CTS ((uint32_t)(UART_CR3_REG_INDEX << 28 | USART_CR3_CTSIE)) +#define UART_IT_ERR ((uint32_t)(UART_CR3_REG_INDEX << 28 | USART_CR3_EIE)) -#define UART_IT_CTS ((uint32_t)(UART_CR3_REG_INDEX << 28U | USART_CR3_CTSIE)) -#define UART_IT_ERR ((uint32_t)(UART_CR3_REG_INDEX << 28U | USART_CR3_EIE)) /** * @} */ @@ -347,32 +305,32 @@ typedef struct * @} */ + /* Exported macro ------------------------------------------------------------*/ /** @defgroup UART_Exported_Macros UART Exported Macros * @{ */ -/** @brief Reset UART handle gstate & RxState + +/** @brief Reset UART handle state * @param __HANDLE__: specifies the UART Handle. * UART Handle selects the USARTx or UARTy peripheral * (USART,UART availability and x,y values depending on device). + * @retval None */ -#define __HAL_UART_RESET_HANDLE_STATE(__HANDLE__) do{ \ - (__HANDLE__)->gState = HAL_UART_STATE_RESET; \ - (__HANDLE__)->RxState = HAL_UART_STATE_RESET; \ - } while(0U) +#define __HAL_UART_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_UART_STATE_RESET) -/** @brief Flushs the UART DR register +/** @brief Flush the UART DR register * @param __HANDLE__: specifies the UART Handle. * UART Handle selects the USARTx or UARTy peripheral * (USART,UART availability and x,y values depending on device). */ #define __HAL_UART_FLUSH_DRREGISTER(__HANDLE__) ((__HANDLE__)->Instance->DR) -/** @brief Checks whether the specified UART flag is set or not. +/** @brief Check whether the specified UART flag is set or not. * @param __HANDLE__: specifies the UART Handle. - * This parameter can be UARTx where x: 1, 2, 3, 4 or 5 to select the USART or - * UART peripheral. + * UART Handle selects the USARTx or UARTy peripheral + * (USART,UART availability and x,y values depending on device). * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg UART_FLAG_CTS: CTS Change flag (not available for UART4 and UART5) @@ -389,7 +347,7 @@ typedef struct */ #define __HAL_UART_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->SR & (__FLAG__)) == (__FLAG__)) -/** @brief Clears the specified UART pending flag. +/** @brief Clear the specified UART pending flag. * @param __HANDLE__: specifies the UART Handle. * UART Handle selects the USARTx or UARTy peripheral * (USART,UART availability and x,y values depending on device). @@ -409,50 +367,58 @@ typedef struct * USART_SR register followed by a write operation to USART_DR register. * @note TXE flag is cleared only by a write to the USART_DR register. * + * @retval None */ #define __HAL_UART_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->SR = ~(__FLAG__)) -/** @brief Clears the UART PE pending flag. +/** @brief Clear the UART PE pending flag. * @param __HANDLE__: specifies the UART Handle. * UART Handle selects the USARTx or UARTy peripheral * (USART,UART availability and x,y values depending on device). + * @retval None */ -#define __HAL_UART_CLEAR_PEFLAG(__HANDLE__) \ - do{ \ - __IO uint32_t tmpreg = 0x00U; \ - tmpreg = (__HANDLE__)->Instance->SR; \ - tmpreg = (__HANDLE__)->Instance->DR; \ - UNUSED(tmpreg); \ - } while(0U) +#define __HAL_UART_CLEAR_PEFLAG(__HANDLE__) \ +do{ \ + __IO uint32_t tmpreg; \ + tmpreg = (__HANDLE__)->Instance->SR; \ + tmpreg = (__HANDLE__)->Instance->DR; \ + UNUSED(tmpreg); \ +}while(0) + -/** @brief Clears the UART FE pending flag. + +/** @brief Clear the UART FE pending flag. * @param __HANDLE__: specifies the UART Handle. * UART Handle selects the USARTx or UARTy peripheral * (USART,UART availability and x,y values depending on device). + * @retval None */ #define __HAL_UART_CLEAR_FEFLAG(__HANDLE__) __HAL_UART_CLEAR_PEFLAG(__HANDLE__) -/** @brief Clears the UART NE pending flag. +/** @brief Clear the UART NE pending flag. * @param __HANDLE__: specifies the UART Handle. * UART Handle selects the USARTx or UARTy peripheral * (USART,UART availability and x,y values depending on device). + * @retval None */ #define __HAL_UART_CLEAR_NEFLAG(__HANDLE__) __HAL_UART_CLEAR_PEFLAG(__HANDLE__) -/** @brief Clears the UART ORE pending flag. +/** @brief Clear the UART ORE pending flag. * @param __HANDLE__: specifies the UART Handle. * UART Handle selects the USARTx or UARTy peripheral * (USART,UART availability and x,y values depending on device). + * @retval None */ #define __HAL_UART_CLEAR_OREFLAG(__HANDLE__) __HAL_UART_CLEAR_PEFLAG(__HANDLE__) -/** @brief Clears the UART IDLE pending flag. +/** @brief Clear the UART IDLE pending flag. * @param __HANDLE__: specifies the UART Handle. * UART Handle selects the USARTx or UARTy peripheral * (USART,UART availability and x,y values depending on device). + * @retval None */ #define __HAL_UART_CLEAR_IDLEFLAG(__HANDLE__) __HAL_UART_CLEAR_PEFLAG(__HANDLE__) - + /** @brief Enable the specified UART interrupt. * @param __HANDLE__: specifies the UART Handle. * UART Handle selects the USARTx or UARTy peripheral @@ -467,11 +433,13 @@ typedef struct * @arg UART_IT_IDLE: Idle line detection interrupt * @arg UART_IT_PE: Parity Error interrupt * @arg UART_IT_ERR: Error interrupt(Frame error, noise error, overrun error) + * @retval None */ -#define __HAL_UART_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((((__INTERRUPT__) >> 28U) == UART_CR1_REG_INDEX)? ((__HANDLE__)->Instance->CR1 |= ((__INTERRUPT__) & UART_IT_MASK)): \ - (((__INTERRUPT__) >> 28U) == UART_CR2_REG_INDEX)? ((__HANDLE__)->Instance->CR2 |= ((__INTERRUPT__) & UART_IT_MASK)): \ +#define __HAL_UART_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((((__INTERRUPT__) >> 28) == UART_CR1_REG_INDEX)? ((__HANDLE__)->Instance->CR1 |= ((__INTERRUPT__) & UART_IT_MASK)): \ + (((__INTERRUPT__) >> 28) == UART_CR2_REG_INDEX)? ((__HANDLE__)->Instance->CR2 |= ((__INTERRUPT__) & UART_IT_MASK)): \ ((__HANDLE__)->Instance->CR3 |= ((__INTERRUPT__) & UART_IT_MASK))) + /** @brief Disable the specified UART interrupt. * @param __HANDLE__: specifies the UART Handle. * UART Handle selects the USARTx or UARTy peripheral @@ -486,12 +454,13 @@ typedef struct * @arg UART_IT_IDLE: Idle line detection interrupt * @arg UART_IT_PE: Parity Error interrupt * @arg UART_IT_ERR: Error interrupt(Frame error, noise error, overrun error) + * @retval None */ -#define __HAL_UART_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((((__INTERRUPT__) >> 28U) == UART_CR1_REG_INDEX)? ((__HANDLE__)->Instance->CR1 &= ~((__INTERRUPT__) & UART_IT_MASK)): \ - (((__INTERRUPT__) >> 28U) == UART_CR2_REG_INDEX)? ((__HANDLE__)->Instance->CR2 &= ~((__INTERRUPT__) & UART_IT_MASK)): \ +#define __HAL_UART_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((((__INTERRUPT__) >> 28) == UART_CR1_REG_INDEX)? ((__HANDLE__)->Instance->CR1 &= ~((__INTERRUPT__) & UART_IT_MASK)): \ + (((__INTERRUPT__) >> 28) == UART_CR2_REG_INDEX)? ((__HANDLE__)->Instance->CR2 &= ~((__INTERRUPT__) & UART_IT_MASK)): \ ((__HANDLE__)->Instance->CR3 &= ~ ((__INTERRUPT__) & UART_IT_MASK))) - -/** @brief Checks whether the specified UART interrupt has occurred or not. + +/** @brief Check whether the specified UART interrupt has occurred or not. * @param __HANDLE__: specifies the UART Handle. * UART Handle selects the USARTx or UARTy peripheral * (USART,UART availability and x,y values depending on device). @@ -506,7 +475,7 @@ typedef struct * @arg UART_IT_ERR: Error interrupt * @retval The new state of __IT__ (TRUE or FALSE). */ -#define __HAL_UART_GET_IT_SOURCE(__HANDLE__, __IT__) (((((__IT__) >> 28U) == UART_CR1_REG_INDEX)? (__HANDLE__)->Instance->CR1:(((((uint32_t)(__IT__)) >> 28U) == UART_CR2_REG_INDEX)? \ +#define __HAL_UART_GET_IT_SOURCE(__HANDLE__, __IT__) (((((__IT__) >> 28) == UART_CR1_REG_INDEX)? (__HANDLE__)->Instance->CR1:(((((uint32_t)(__IT__)) >> 28) == UART_CR2_REG_INDEX)? \ (__HANDLE__)->Instance->CR2 : (__HANDLE__)->Instance->CR3)) & (((uint32_t)(__IT__)) & UART_IT_MASK)) /** @brief Enable CTS flow control @@ -519,14 +488,15 @@ typedef struct * - macro could only be called when corresponding UART instance is disabled (i.e __HAL_UART_DISABLE(__HANDLE__)) * and should be followed by an Enable macro (i.e __HAL_UART_ENABLE(__HANDLE__)). * @param __HANDLE__: specifies the UART Handle. - * The Handle Instance can be any USARTx (supporting the HW Flow control feature). + * This parameter can be any USARTx (supporting the HW Flow control feature). * It is used to select the USART peripheral (USART availability and x value depending on device). + * @retval None */ #define __HAL_UART_HWCONTROL_CTS_ENABLE(__HANDLE__) \ do{ \ SET_BIT((__HANDLE__)->Instance->CR3, USART_CR3_CTSE); \ (__HANDLE__)->Init.HwFlowCtl |= USART_CR3_CTSE; \ - } while(0U) + } while(0) /** @brief Disable CTS flow control * This macro allows to disable CTS hardware flow control for a given UART instance, @@ -538,14 +508,15 @@ typedef struct * - macro could only be called when corresponding UART instance is disabled (i.e __HAL_UART_DISABLE(__HANDLE__)) * and should be followed by an Enable macro (i.e __HAL_UART_ENABLE(__HANDLE__)). * @param __HANDLE__: specifies the UART Handle. - * The Handle Instance can be any USARTx (supporting the HW Flow control feature). + * This parameter can be any USARTx (supporting the HW Flow control feature). * It is used to select the USART peripheral (USART availability and x value depending on device). + * @retval None */ #define __HAL_UART_HWCONTROL_CTS_DISABLE(__HANDLE__) \ do{ \ CLEAR_BIT((__HANDLE__)->Instance->CR3, USART_CR3_CTSE); \ (__HANDLE__)->Init.HwFlowCtl &= ~(USART_CR3_CTSE); \ - } while(0U) + } while(0) /** @brief Enable RTS flow control * This macro allows to enable RTS hardware flow control for a given UART instance, @@ -557,14 +528,15 @@ typedef struct * - macro could only be called when corresponding UART instance is disabled (i.e __HAL_UART_DISABLE(__HANDLE__)) * and should be followed by an Enable macro (i.e __HAL_UART_ENABLE(__HANDLE__)). * @param __HANDLE__: specifies the UART Handle. - * The Handle Instance can be any USARTx (supporting the HW Flow control feature). + * This parameter can be any USARTx (supporting the HW Flow control feature). * It is used to select the USART peripheral (USART availability and x value depending on device). + * @retval None */ #define __HAL_UART_HWCONTROL_RTS_ENABLE(__HANDLE__) \ do{ \ SET_BIT((__HANDLE__)->Instance->CR3, USART_CR3_RTSE); \ (__HANDLE__)->Init.HwFlowCtl |= USART_CR3_RTSE; \ - } while(0U) + } while(0) /** @brief Disable RTS flow control * This macro allows to disable RTS hardware flow control for a given UART instance, @@ -576,49 +548,124 @@ typedef struct * - macro could only be called when corresponding UART instance is disabled (i.e __HAL_UART_DISABLE(__HANDLE__)) * and should be followed by an Enable macro (i.e __HAL_UART_ENABLE(__HANDLE__)). * @param __HANDLE__: specifies the UART Handle. - * The Handle Instance can be any USARTx (supporting the HW Flow control feature). + * This parameter can be any USARTx (supporting the HW Flow control feature). * It is used to select the USART peripheral (USART availability and x value depending on device). + * @retval None */ #define __HAL_UART_HWCONTROL_RTS_DISABLE(__HANDLE__) \ do{ \ CLEAR_BIT((__HANDLE__)->Instance->CR3, USART_CR3_RTSE);\ (__HANDLE__)->Init.HwFlowCtl &= ~(USART_CR3_RTSE); \ - } while(0U) - -#if defined(USART_CR3_ONEBIT) -/** @brief macros to enables the UART's one bit sample method - * @param __HANDLE__: specifies the UART Handle. - */ -#define __HAL_UART_ONE_BIT_SAMPLE_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR3|= USART_CR3_ONEBIT) + } while(0) -/** @brief macros to disables the UART's one bit sample method - * @param __HANDLE__: specifies the UART Handle. - * @retval None - */ -#define __HAL_UART_ONE_BIT_SAMPLE_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR3 &= (uint16_t)~((uint16_t)USART_CR3_ONEBIT)) -#endif /* USART_CR3_ONEBIT */ /** @brief Enable UART * @param __HANDLE__: specifies the UART Handle. - */ + * UART Handle selects the USARTx or UARTy peripheral + * (USART,UART availability and x,y values depending on device). + * @retval None + */ #define __HAL_UART_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 |= USART_CR1_UE) /** @brief Disable UART - * @param __HANDLE__: specifies the UART Handle. + * UART Handle selects the USARTx or UARTy peripheral + * (USART,UART availability and x,y values depending on device). + * @retval None */ #define __HAL_UART_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 &= ~USART_CR1_UE) + /** * @} */ -/* Exported functions --------------------------------------------------------*/ -/** @addtogroup UART_Exported_Functions + + +/* Private macros --------------------------------------------------------*/ +/** @defgroup UART_Private_Macros UART Private Macros * @{ */ -/** @addtogroup UART_Exported_Functions_Group1 +#define UART_CR1_REG_INDEX 1 +#define UART_CR2_REG_INDEX 2 +#define UART_CR3_REG_INDEX 3 + +#define UART_DIV_SAMPLING16(_PCLK_, _BAUD_) (((_PCLK_)*25)/(4*(_BAUD_))) +#define UART_DIVMANT_SAMPLING16(_PCLK_, _BAUD_) (UART_DIV_SAMPLING16((_PCLK_), (_BAUD_))/100) +#define UART_DIVFRAQ_SAMPLING16(_PCLK_, _BAUD_) (((UART_DIV_SAMPLING16((_PCLK_), (_BAUD_)) - (UART_DIVMANT_SAMPLING16((_PCLK_), (_BAUD_)) * 100)) * 16 + 50) / 100) +/* UART BRR = mantissa + overflow + fraction + = (UART DIVMANT << 4) + (UART DIVFRAQ & 0xF0) + (UART DIVFRAQ & 0x0F) */ +#define UART_BRR_SAMPLING16(_PCLK_, _BAUD_) (((UART_DIVMANT_SAMPLING16((_PCLK_), (_BAUD_)) << 4) + \ + (UART_DIVFRAQ_SAMPLING16((_PCLK_), (_BAUD_)) & 0xF0)) + \ + (UART_DIVFRAQ_SAMPLING16((_PCLK_), (_BAUD_)) & 0x0F)) +#define IS_UART_WORD_LENGTH(LENGTH) (((LENGTH) == UART_WORDLENGTH_8B) || \ + ((LENGTH) == UART_WORDLENGTH_9B)) +#define IS_UART_LIN_WORD_LENGTH(LENGTH) ((LENGTH) == UART_WORDLENGTH_8B) + +#define IS_UART_STOPBITS(STOPBITS) (((STOPBITS) == UART_STOPBITS_1) || \ + ((STOPBITS) == UART_STOPBITS_2)) + +#define IS_UART_PARITY(PARITY) (((PARITY) == UART_PARITY_NONE) || \ + ((PARITY) == UART_PARITY_EVEN) || \ + ((PARITY) == UART_PARITY_ODD)) + +#define IS_UART_HARDWARE_FLOW_CONTROL(CONTROL)\ + (((CONTROL) == UART_HWCONTROL_NONE) || \ + ((CONTROL) == UART_HWCONTROL_RTS) || \ + ((CONTROL) == UART_HWCONTROL_CTS) || \ + ((CONTROL) == UART_HWCONTROL_RTS_CTS)) + +#define IS_UART_MODE(MODE) ((((MODE) & (~((uint32_t)UART_MODE_TX_RX))) == 0x00) && \ + ((MODE) != (uint32_t)0x00000000)) + +#define IS_UART_STATE(STATE) (((STATE) == UART_STATE_DISABLE) || \ + ((STATE) == UART_STATE_ENABLE)) + +#define IS_UART_OVERSAMPLING(SAMPLING) ((SAMPLING) == UART_OVERSAMPLING_16) +#define IS_UART_LIN_OVERSAMPLING(SAMPLING) ((SAMPLING) == UART_OVERSAMPLING_16) + +#define IS_UART_LIN_BREAK_DETECT_LENGTH(LENGTH) (((LENGTH) == UART_LINBREAKDETECTLENGTH_10B) || \ + ((LENGTH) == UART_LINBREAKDETECTLENGTH_11B)) + +#define IS_UART_WAKEUPMETHOD(WAKEUP) (((WAKEUP) == UART_WAKEUPMETHOD_IDLELINE) || \ + ((WAKEUP) == UART_WAKEUPMETHOD_ADDRESSMARK)) + + +/** Check UART Baud rate + * __BAUDRATE__: Baudrate specified by the user + * The maximum Baud Rate is derived from the maximum clock on APB (i.e. 72 MHz) + * divided by the smallest oversampling used on the USART (i.e. 16) + * Retrun : TRUE or FALSE + */ +#define IS_UART_BAUDRATE(__BAUDRATE__) ((__BAUDRATE__) < 4500001) + +/** Check UART Node Address + * __ADDRESS__: UART Node address specified by the user + * UART Node address is used in Multi processor communication for wakeup + * with address mark detection. + * This parameter must be a number between Min_Data = 0 and Max_Data = 15 + * Return : TRUE or FALSE + */ +#define IS_UART_ADDRESS(__ADDRESS__) ((__ADDRESS__) <= 0xF) + +/** UART interruptions flag mask + */ +#define UART_IT_MASK ((uint32_t) USART_CR1_PEIE | USART_CR1_TXEIE | USART_CR1_TCIE | USART_CR1_RXNEIE | \ + USART_CR1_IDLEIE | USART_CR2_LBDIE | USART_CR3_CTSIE | USART_CR3_EIE ) + +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ + +/** @addtogroup UART_Exported_Functions UART Exported Functions + * @{ + */ + +/** @addtogroup UART_Exported_Functions_Group1 Initialization and de-initialization functions * @{ */ -/* Initialization/de-initialization functions **********************************/ + +/* Initialization and de-initialization functions ****************************/ HAL_StatusTypeDef HAL_UART_Init(UART_HandleTypeDef *huart); HAL_StatusTypeDef HAL_HalfDuplex_Init(UART_HandleTypeDef *huart); HAL_StatusTypeDef HAL_LIN_Init(UART_HandleTypeDef *huart, uint32_t BreakDetectLength); @@ -626,14 +673,16 @@ HAL_StatusTypeDef HAL_MultiProcessor_Init(UART_HandleTypeDef *huart, uint8_t Add HAL_StatusTypeDef HAL_UART_DeInit (UART_HandleTypeDef *huart); void HAL_UART_MspInit(UART_HandleTypeDef *huart); void HAL_UART_MspDeInit(UART_HandleTypeDef *huart); + /** * @} */ -/** @addtogroup UART_Exported_Functions_Group2 +/** @addtogroup UART_Exported_Functions_Group2 IO operation functions * @{ */ -/* IO operation functions *******************************************************/ + +/* IO operation functions *****************************************************/ HAL_StatusTypeDef HAL_UART_Transmit(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_UART_Receive(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_UART_Transmit_IT(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size); @@ -643,129 +692,44 @@ HAL_StatusTypeDef HAL_UART_Receive_DMA(UART_HandleTypeDef *huart, uint8_t *pData HAL_StatusTypeDef HAL_UART_DMAPause(UART_HandleTypeDef *huart); HAL_StatusTypeDef HAL_UART_DMAResume(UART_HandleTypeDef *huart); HAL_StatusTypeDef HAL_UART_DMAStop(UART_HandleTypeDef *huart); -/* Transfer Abort functions */ -HAL_StatusTypeDef HAL_UART_Abort(UART_HandleTypeDef *huart); -HAL_StatusTypeDef HAL_UART_AbortTransmit(UART_HandleTypeDef *huart); -HAL_StatusTypeDef HAL_UART_AbortReceive(UART_HandleTypeDef *huart); -HAL_StatusTypeDef HAL_UART_Abort_IT(UART_HandleTypeDef *huart); -HAL_StatusTypeDef HAL_UART_AbortTransmit_IT(UART_HandleTypeDef *huart); -HAL_StatusTypeDef HAL_UART_AbortReceive_IT(UART_HandleTypeDef *huart); - void HAL_UART_IRQHandler(UART_HandleTypeDef *huart); void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart); void HAL_UART_TxHalfCpltCallback(UART_HandleTypeDef *huart); void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart); void HAL_UART_RxHalfCpltCallback(UART_HandleTypeDef *huart); void HAL_UART_ErrorCallback(UART_HandleTypeDef *huart); -void HAL_UART_AbortCpltCallback (UART_HandleTypeDef *huart); -void HAL_UART_AbortTransmitCpltCallback (UART_HandleTypeDef *huart); -void HAL_UART_AbortReceiveCpltCallback (UART_HandleTypeDef *huart); + /** * @} */ -/** @addtogroup UART_Exported_Functions_Group3 +/** @addtogroup UART_Exported_Functions_Group3 Peripheral Control functions * @{ */ + /* Peripheral Control functions ************************************************/ HAL_StatusTypeDef HAL_LIN_SendBreak(UART_HandleTypeDef *huart); HAL_StatusTypeDef HAL_MultiProcessor_EnterMuteMode(UART_HandleTypeDef *huart); HAL_StatusTypeDef HAL_MultiProcessor_ExitMuteMode(UART_HandleTypeDef *huart); HAL_StatusTypeDef HAL_HalfDuplex_EnableTransmitter(UART_HandleTypeDef *huart); HAL_StatusTypeDef HAL_HalfDuplex_EnableReceiver(UART_HandleTypeDef *huart); -/** - * @} - */ -/** @addtogroup UART_Exported_Functions_Group4 - * @{ - */ -/* Peripheral State functions **************************************************/ -HAL_UART_StateTypeDef HAL_UART_GetState(UART_HandleTypeDef *huart); -uint32_t HAL_UART_GetError(UART_HandleTypeDef *huart); /** * @} */ -/** - * @} - */ -/* Private types -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private constants ---------------------------------------------------------*/ -/** @defgroup UART_Private_Constants UART Private Constants +/** @addtogroup UART_Exported_Functions_Group4 Peripheral State and Errors functions * @{ */ -/** @brief UART interruptions flag mask - * - */ -#define UART_IT_MASK 0x0000FFFFU -#define UART_CR1_REG_INDEX 1U -#define UART_CR2_REG_INDEX 2U -#define UART_CR3_REG_INDEX 3U -/** - * @} - */ +/* Peripheral State and Errors functions **************************************************/ +HAL_UART_StateTypeDef HAL_UART_GetState(UART_HandleTypeDef *huart); +uint32_t HAL_UART_GetError(UART_HandleTypeDef *huart); -/* Private macros ------------------------------------------------------------*/ -/** @defgroup UART_Private_Macros UART Private Macros - * @{ - */ -#define IS_UART_WORD_LENGTH(LENGTH) (((LENGTH) == UART_WORDLENGTH_8B) || \ - ((LENGTH) == UART_WORDLENGTH_9B)) -#define IS_UART_LIN_WORD_LENGTH(LENGTH) (((LENGTH) == UART_WORDLENGTH_8B)) -#define IS_UART_STOPBITS(STOPBITS) (((STOPBITS) == UART_STOPBITS_1) || \ - ((STOPBITS) == UART_STOPBITS_2)) -#define IS_UART_PARITY(PARITY) (((PARITY) == UART_PARITY_NONE) || \ - ((PARITY) == UART_PARITY_EVEN) || \ - ((PARITY) == UART_PARITY_ODD)) -#define IS_UART_HARDWARE_FLOW_CONTROL(CONTROL)\ - (((CONTROL) == UART_HWCONTROL_NONE) || \ - ((CONTROL) == UART_HWCONTROL_RTS) || \ - ((CONTROL) == UART_HWCONTROL_CTS) || \ - ((CONTROL) == UART_HWCONTROL_RTS_CTS)) -#define IS_UART_MODE(MODE) ((((MODE) & 0x0000FFF3U) == 0x00U) && ((MODE) != 0x00U)) -#define IS_UART_STATE(STATE) (((STATE) == UART_STATE_DISABLE) || \ - ((STATE) == UART_STATE_ENABLE)) -#if defined(USART_CR1_OVER8) -#define IS_UART_OVERSAMPLING(SAMPLING) (((SAMPLING) == UART_OVERSAMPLING_16) || \ - ((SAMPLING) == UART_OVERSAMPLING_8)) -#endif /* USART_CR1_OVER8 */ -#define IS_UART_LIN_OVERSAMPLING(SAMPLING) (((SAMPLING) == UART_OVERSAMPLING_16)) -#define IS_UART_LIN_BREAK_DETECT_LENGTH(LENGTH) (((LENGTH) == UART_LINBREAKDETECTLENGTH_10B) || \ - ((LENGTH) == UART_LINBREAKDETECTLENGTH_11B)) -#define IS_UART_WAKEUPMETHOD(WAKEUP) (((WAKEUP) == UART_WAKEUPMETHOD_IDLELINE) || \ - ((WAKEUP) == UART_WAKEUPMETHOD_ADDRESSMARK)) -#define IS_UART_BAUDRATE(BAUDRATE) ((BAUDRATE) < 4500001U) -#define IS_UART_ADDRESS(ADDRESS) ((ADDRESS) <= 0x0FU) - -#define UART_DIV_SAMPLING16(_PCLK_, _BAUD_) (((_PCLK_)*25U)/(4U*(_BAUD_))) -#define UART_DIVMANT_SAMPLING16(_PCLK_, _BAUD_) (UART_DIV_SAMPLING16((_PCLK_), (_BAUD_))/100U) -#define UART_DIVFRAQ_SAMPLING16(_PCLK_, _BAUD_) (((UART_DIV_SAMPLING16((_PCLK_), (_BAUD_)) - (UART_DIVMANT_SAMPLING16((_PCLK_), (_BAUD_)) * 100U)) * 16U + 50U) / 100U) -/* UART BRR = mantissa + overflow + fraction - = (UART DIVMANT << 4) + (UART DIVFRAQ & 0xF0) + (UART DIVFRAQ & 0x0FU) */ -#define UART_BRR_SAMPLING16(_PCLK_, _BAUD_) (((UART_DIVMANT_SAMPLING16((_PCLK_), (_BAUD_)) << 4U) + \ - (UART_DIVFRAQ_SAMPLING16((_PCLK_), (_BAUD_)) & 0xF0U)) + \ - (UART_DIVFRAQ_SAMPLING16((_PCLK_), (_BAUD_)) & 0x0FU)) - -#define UART_DIV_SAMPLING8(_PCLK_, _BAUD_) (((_PCLK_)*25U)/(2U*(_BAUD_))) -#define UART_DIVMANT_SAMPLING8(_PCLK_, _BAUD_) (UART_DIV_SAMPLING8((_PCLK_), (_BAUD_))/100U) -#define UART_DIVFRAQ_SAMPLING8(_PCLK_, _BAUD_) (((UART_DIV_SAMPLING8((_PCLK_), (_BAUD_)) - (UART_DIVMANT_SAMPLING8((_PCLK_), (_BAUD_)) * 100U)) * 8U + 50U) / 100U) -/* UART BRR = mantissa + overflow + fraction - = (UART DIVMANT << 4) + ((UART DIVFRAQ & 0xF8) << 1) + (UART DIVFRAQ & 0x07U) */ -#define UART_BRR_SAMPLING8(_PCLK_, _BAUD_) (((UART_DIVMANT_SAMPLING8((_PCLK_), (_BAUD_)) << 4U) + \ - ((UART_DIVFRAQ_SAMPLING8((_PCLK_), (_BAUD_)) & 0xF8U) << 1U)) + \ - (UART_DIVFRAQ_SAMPLING8((_PCLK_), (_BAUD_)) & 0x07U)) /** * @} */ -/* Private functions ---------------------------------------------------------*/ -/** @defgroup UART_Private_Functions UART Private Functions - * @{ - */ - /** * @} */ diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_usart.c b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_usart.c index a6d19e9f99e..5ecfcf102a3 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_usart.c +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_usart.c @@ -2,14 +2,15 @@ ****************************************************************************** * @file stm32f1xx_hal_usart.c * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief USART HAL module driver. - * This file provides firmware functions to manage the following + * This file provides firmware functions to manage the following * functionalities of the Universal Synchronous Asynchronous Receiver Transmitter (USART) peripheral: * + Initialization and de-initialization functions * + IO operation functions - * + Peripheral Control functions + * + Peripheral Control functions + * + Peripheral State and Errors functions @verbatim ============================================================================== ##### How to use this driver ##### @@ -18,7 +19,7 @@ The USART HAL driver can be used as follows: (#) Declare a USART_HandleTypeDef handle structure. - (#) Initialize the USART low level resources by implementing the HAL_USART_MspInit () API: + (#) Initialize the USART low level resources by implementing the HAL_USART_MspInit() API: (##) Enable the USARTx interface clock. (##) USART pins configuration: (+++) Enable the clock for the USART GPIOs. @@ -33,99 +34,82 @@ (+++) Enable the DMAx interface clock. (+++) Configure the declared DMA handle structure with the required Tx/Rx parameters. (+++) Configure the DMA Tx/Rx channel. - (+++) Associate the initialized DMA handle to the USART DMA Tx/Rx handle. + (+++) Associate the initilalized DMA handle to the USART DMA Tx/Rx handle. (+++) Configure the priority and enable the NVIC for the transfer complete interrupt on the DMA Tx/Rx channel. - (+++) Configure the priority and enable the NVIC for the transfer complete - interrupt on the DMA Tx/Rx channel. (+++) Configure the USARTx interrupt priority and enable the NVIC USART IRQ handle - (used for last byte sending completion detection in DMA non circular mode) + (used for last byte sending completion detection in DMA non circular mode) - (#) Program the Baud Rate, Word Length, Stop Bit, Parity, Hardware + (#) Program the Baud Rate, Word Length, Stop Bit, Parity, Hardware flow control and Mode(Receiver/Transmitter) in the husart Init structure. (#) Initialize the USART registers by calling the HAL_USART_Init() API: (++) These APIs configures also the low level Hardware GPIO, CLOCK, CORTEX...etc) - by calling the customized HAL_USART_MspInit(&husart) API. - - -@@- The specific USART interrupts (Transmission complete interrupt, + by calling the customed HAL_USART_MspInit(&husart) API. + + -@@- The specific USART interrupts (Transmission complete interrupt, RXNE interrupt and Error Interrupts) will be managed using the macros __HAL_USART_ENABLE_IT() and __HAL_USART_DISABLE_IT() inside the transmit and receive process. - - (#) Three operation modes are available within this driver : - + + (#) Three operation modes are available within this driver : + *** Polling mode IO operation *** ================================= - [..] - (+) Send an amount of data in blocking mode using HAL_USART_Transmit() + [..] + (+) Send an amount of data in blocking mode using HAL_USART_Transmit() (+) Receive an amount of data in blocking mode using HAL_USART_Receive() - - *** Interrupt mode IO operation *** + + *** Interrupt mode IO operation *** =================================== - [..] - (+) Send an amount of data in non blocking mode using HAL_USART_Transmit_IT() - (+) At transmission end of transfer HAL_USART_TxHalfCpltCallback is executed and user can + [..] + (+) Send an amount of data in non blocking mode using HAL_USART_Transmit_IT() + (+) At transmission end of transfer HAL_USART_TxCpltCallback is executed and user can add his own code by customization of function pointer HAL_USART_TxCpltCallback - (+) Receive an amount of data in non blocking mode using HAL_USART_Receive_IT() - (+) At reception end of transfer HAL_USART_RxCpltCallback is executed and user can - add his own code by customization of function pointer HAL_USART_RxCpltCallback - (+) In case of transfer Error, HAL_USART_ErrorCallback() function is executed and user can + (+) Receive an amount of data in non blocking mode using HAL_USART_Receive_IT() + (+) At reception end of transfer HAL_USART_RxCpltCallback is executed and user can + add his own code by customization of function pointer HAL_USART_RxCpltCallback + (+) In case of transfer Error, HAL_USART_ErrorCallback() function is executed and user can add his own code by customization of function pointer HAL_USART_ErrorCallback - - *** DMA mode IO operation *** + + *** DMA mode IO operation *** ============================== - [..] - (+) Send an amount of data in non blocking mode (DMA) using HAL_USART_Transmit_DMA() - (+) At transmission end of half transfer HAL_USART_TxHalfCpltCallback is executed and user can - add his own code by customization of function pointer HAL_USART_TxHalfCpltCallback - (+) At transmission end of transfer HAL_USART_TxCpltCallback is executed and user can + [..] + (+) Send an amount of data in non blocking mode (DMA) using HAL_USART_Transmit_DMA() + (+) At transmission end of half transfer HAL_USART_TxHalfCpltCallback is executed and user can + add his own code by customization of function pointer HAL_USART_TxHalfCpltCallback + (+) At transmission end of transfer HAL_USART_TxCpltCallback is executed and user can add his own code by customization of function pointer HAL_USART_TxCpltCallback - (+) Receive an amount of data in non blocking mode (DMA) using HAL_USART_Receive_DMA() - (+) At reception end of half transfer HAL_USART_RxHalfCpltCallback is executed and user can - add his own code by customization of function pointer HAL_USART_RxHalfCpltCallback - (+) At reception end of transfer HAL_USART_RxCpltCallback is executed and user can - add his own code by customization of function pointer HAL_USART_RxCpltCallback - (+) In case of transfer Error, HAL_USART_ErrorCallback() function is executed and user can + (+) Receive an amount of data in non blocking mode (DMA) using HAL_USART_Receive_DMA() + (+) At reception end of half transfer HAL_USART_RxHalfCpltCallback is executed and user can + add his own code by customization of function pointer HAL_USART_RxHalfCpltCallback + (+) At reception end of transfer HAL_USART_RxCpltCallback is executed and user can + add his own code by customization of function pointer HAL_USART_RxCpltCallback + (+) In case of transfer Error, HAL_USART_ErrorCallback() function is executed and user can add his own code by customization of function pointer HAL_USART_ErrorCallback - (+) Pause the DMA Transfer using HAL_USART_DMAPause() - (+) Resume the DMA Transfer using HAL_USART_DMAResume() - (+) Stop the DMA Transfer using HAL_USART_DMAStop() - + (+) Pause the DMA Transfer using HAL_USART_DMAPause() + (+) Resume the DMA Transfer using HAL_USART_DMAResume() + (+) Stop the DMA Transfer using HAL_USART_DMAStop() + *** USART HAL driver macros list *** - ============================================= + ============================================= [..] Below the list of most used macros in USART HAL driver. - - (+) __HAL_USART_ENABLE: Enable the USART peripheral - (+) __HAL_USART_DISABLE: Disable the USART peripheral + + (+) __HAL_USART_ENABLE: Enable the USART peripheral + (+) __HAL_USART_DISABLE: Disable the USART peripheral (+) __HAL_USART_GET_FLAG : Check whether the specified USART flag is set or not (+) __HAL_USART_CLEAR_FLAG : Clear the specified USART pending flag (+) __HAL_USART_ENABLE_IT: Enable the specified USART interrupt (+) __HAL_USART_DISABLE_IT: Disable the specified USART interrupt - - [..] + (+) __HAL_USART_GET_IT_SOURCE: Check whether the specified USART interrupt has occurred or not + + [..] (@) You can refer to the USART HAL driver header file for more useful macros @endverbatim - [..] - (@) Additionnal remark: If the parity is enabled, then the MSB bit of the data written - in the data register is transmitted but is changed by the parity bit. - Depending on the frame length defined by the M bit (8-bits or 9-bits), - the possible USART frame formats are as listed in the following table: - +-------------------------------------------------------------+ - | M bit | PCE bit | USART frame | - |---------------------|---------------------------------------| - | 0 | 0 | | SB | 8 bit data | STB | | - |---------|-----------|---------------------------------------| - | 0 | 1 | | SB | 7 bit data | PB | STB | | - |---------|-----------|---------------------------------------| - | 1 | 0 | | SB | 9 bit data | STB | | - |---------|-----------|---------------------------------------| - | 1 | 1 | | SB | 8 bit data | PB | STB | | - +-------------------------------------------------------------+ ****************************************************************************** * @attention * - *

© COPYRIGHT(c) 2017 STMicroelectronics

+ *

© COPYRIGHT(c) 2016 STMicroelectronics

* * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: @@ -164,26 +148,22 @@ * @{ */ #ifdef HAL_USART_MODULE_ENABLED - /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ -/** @addtogroup USART_Private_Constants +/** @defgroup USART_Private_Constants USART Private Constants * @{ */ -#define DUMMY_DATA 0xFFFFU -#define USART_TIMEOUT_VALUE 22000U +#define DUMMY_DATA 0xFFFF /** * @} */ -/* Private macro -------------------------------------------------------------*/ + +/* Private macros --------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ -/* Private functions ---------------------------------------------------------*/ -/** @addtogroup USART_Private_Functions +/** @addtogroup USART_Private_Functions USART Private Functions * @{ */ -static void USART_EndTxTransfer(USART_HandleTypeDef *husart); -static void USART_EndRxTransfer(USART_HandleTypeDef *husart); static HAL_StatusTypeDef USART_Transmit_IT(USART_HandleTypeDef *husart); static HAL_StatusTypeDef USART_EndTransmit_IT(USART_HandleTypeDef *husart); static HAL_StatusTypeDef USART_Receive_IT(USART_HandleTypeDef *husart); @@ -193,57 +173,70 @@ static void USART_DMATransmitCplt(DMA_HandleTypeDef *hdma); static void USART_DMATxHalfCplt(DMA_HandleTypeDef *hdma); static void USART_DMAReceiveCplt(DMA_HandleTypeDef *hdma); static void USART_DMARxHalfCplt(DMA_HandleTypeDef *hdma); -static void USART_DMAError(DMA_HandleTypeDef *hdma); -static void USART_DMAAbortOnError(DMA_HandleTypeDef *hdma); -static void USART_DMATxAbortCallback(DMA_HandleTypeDef *hdma); -static void USART_DMARxAbortCallback(DMA_HandleTypeDef *hdma); - -static HAL_StatusTypeDef USART_WaitOnFlagUntilTimeout(USART_HandleTypeDef *husart, uint32_t Flag, FlagStatus Status, uint32_t Tickstart, uint32_t Timeout); +static void USART_DMAError(DMA_HandleTypeDef *hdma); +static HAL_StatusTypeDef USART_WaitOnFlagUntilTimeout(USART_HandleTypeDef *husart, uint32_t Flag, FlagStatus Status, uint32_t Timeout); /** * @} */ -/* Exported functions --------------------------------------------------------*/ +/* Exported functions ---------------------------------------------------------*/ + + /** @defgroup USART_Exported_Functions USART Exported Functions * @{ */ -/** @defgroup USART_Exported_Functions_Group1 USART Initialization and de-initialization functions - * @brief Initialization and Configuration functions +/** @defgroup USART_Exported_Functions_Group1 Initialization and de-initialization functions + * @brief Initialization and Configuration functions * @verbatim ============================================================================== - ##### Initialization and Configuration functions ##### + ##### Initialization and Configuration functions ##### ============================================================================== [..] - This subsection provides a set of functions allowing to initialize the USART + This subsection provides a set of functions allowing to initialize the USART in asynchronous and in synchronous modes. - (+) For the asynchronous mode only these parameters can be configured: + (+) For the asynchronous mode only these parameters can be configured: (++) Baud Rate - (++) Word Length + (++) Word Length (++) Stop Bit - (++) Parity: If the parity is enabled, then the MSB bit of the data written - in the data register is transmitted but is changed by the parity bit. - Depending on the frame length defined by the M bit (8-bits or 9-bits), - please refer to Reference manual for possible USART frame formats. + (++) Parity (++) USART polarity (++) USART phase (++) USART LastBit (++) Receiver/transmitter modes [..] - The HAL_USART_Init() function follows the USART synchronous configuration + The HAL_USART_Init() function follows the USART synchronous configuration procedure (details for the procedure are available in reference manuals (RM0008 for STM32F10Xxx MCUs and RM0041 for STM32F100xx MCUs)). @endverbatim * @{ */ + +/* + Additionnal remark: If the parity is enabled, then the MSB bit of the data written + in the data register is transmitted but is changed by the parity bit. + Depending on the frame length defined by the M bit (8-bits or 9-bits), + the possible USART frame formats are as listed in the following table: + +-------------------------------------------------------------+ + | M bit | PCE bit | USART frame | + |---------------------|---------------------------------------| + | 0 | 0 | | SB | 8 bit data | STB | | + |---------|-----------|---------------------------------------| + | 0 | 1 | | SB | 7 bit data | PB | STB | | + |---------|-----------|---------------------------------------| + | 1 | 0 | | SB | 9 bit data | STB | | + |---------|-----------|---------------------------------------| + | 1 | 1 | | SB | 8 bit data | PB | STB | | + +-------------------------------------------------------------+ +*/ /** * @brief Initializes the USART mode according to the specified * parameters in the USART_InitTypeDef and create the associated handle. - * @param husart: pointer to a USART_HandleTypeDef structure that contains + * @param husart: Pointer to a USART_HandleTypeDef structure that contains * the configuration information for the specified USART module. * @retval HAL status */ @@ -262,7 +255,7 @@ HAL_StatusTypeDef HAL_USART_Init(USART_HandleTypeDef *husart) { /* Allocate lock resource and initialize it */ husart->Lock = HAL_UNLOCKED; - + /* Init the low level hardware */ HAL_USART_MspInit(husart); } @@ -272,11 +265,11 @@ HAL_StatusTypeDef HAL_USART_Init(USART_HandleTypeDef *husart) /* Set the USART Communication parameters */ USART_SetConfig(husart); - /* In USART mode, the following bits must be kept cleared: + /* In USART mode, the following bits must be kept cleared: - LINEN bit in the USART_CR2 register - HDSEL, SCEN and IREN bits in the USART_CR3 register */ CLEAR_BIT(husart->Instance->CR2, USART_CR2_LINEN); - CLEAR_BIT(husart->Instance->CR3, (USART_CR3_SCEN | USART_CR3_HDSEL | USART_CR3_IREN)); + CLEAR_BIT(husart->Instance->CR3, (USART_CR3_IREN | USART_CR3_SCEN | USART_CR3_HDSEL)); /* Enable the Peripheral */ __HAL_USART_ENABLE(husart); @@ -290,13 +283,13 @@ HAL_StatusTypeDef HAL_USART_Init(USART_HandleTypeDef *husart) /** * @brief DeInitializes the USART peripheral. - * @param husart: pointer to a USART_HandleTypeDef structure that contains + * @param husart: Pointer to a USART_HandleTypeDef structure that contains * the configuration information for the specified USART module. * @retval HAL status */ HAL_StatusTypeDef HAL_USART_DeInit(USART_HandleTypeDef *husart) { - /* Check the USART handle allocation */ + /* Check the USART handle allocation */ if(husart == NULL) { return HAL_ERROR; @@ -307,6 +300,9 @@ HAL_StatusTypeDef HAL_USART_DeInit(USART_HandleTypeDef *husart) husart->State = HAL_USART_STATE_BUSY; + /* Disable the Peripheral */ + __HAL_USART_DISABLE(husart); + /* DeInit the low level hardware */ HAL_USART_MspDeInit(husart); @@ -321,66 +317,66 @@ HAL_StatusTypeDef HAL_USART_DeInit(USART_HandleTypeDef *husart) /** * @brief USART MSP Init. - * @param husart: pointer to a USART_HandleTypeDef structure that contains + * @param husart: Pointer to a USART_HandleTypeDef structure that contains * the configuration information for the specified USART module. * @retval None */ -__weak void HAL_USART_MspInit(USART_HandleTypeDef *husart) + __weak void HAL_USART_MspInit(USART_HandleTypeDef *husart) { /* Prevent unused argument(s) compilation warning */ UNUSED(husart); /* NOTE: This function should not be modified, when the callback is needed, - the HAL_USART_MspInit could be implemented in the user file - */ + the HAL_USART_MspInit can be implemented in the user file + */ } /** * @brief USART MSP DeInit. - * @param husart: pointer to a USART_HandleTypeDef structure that contains + * @param husart: Pointer to a USART_HandleTypeDef structure that contains * the configuration information for the specified USART module. * @retval None */ -__weak void HAL_USART_MspDeInit(USART_HandleTypeDef *husart) + __weak void HAL_USART_MspDeInit(USART_HandleTypeDef *husart) { /* Prevent unused argument(s) compilation warning */ UNUSED(husart); /* NOTE: This function should not be modified, when the callback is needed, - the HAL_USART_MspDeInit could be implemented in the user file - */ + the HAL_USART_MspDeInit can be implemented in the user file + */ } /** * @} */ -/** @defgroup USART_Exported_Functions_Group2 IO operation functions - * @brief USART Transmit and Receive functions +/** @defgroup USART_Exported_Functions_Group2 IO operation functions + * @brief USART Transmit and Receive functions * @verbatim ============================================================================== - ##### IO operation functions ##### + ##### IO operation functions ##### ============================================================================== [..] This subsection provides a set of functions allowing to manage the USART synchronous data transfers. - - [..] + + [..] The USART supports master mode only: it cannot receive or send data related to an input clock (SCLK is always an output). (#) There are two modes of transfer: - (++) Blocking mode: The communication is performed in polling mode. - The HAL status of all data processing is returned by the same function - after finishing transfer. - (++) No-Blocking mode: The communication is performed using Interrupts + (++) Blocking mode: The communication is performed in polling mode. + The HAL status of all data processing is returned by the same function + after finishing transfer. + (++) No-Blocking mode: The communication is performed using Interrupts or DMA, These API's return the HAL status. - The end of the data processing will be indicated through the - dedicated USART IRQ when using Interrupt mode or the DMA IRQ when + The end of the data processing will be indicated through the + dedicated USART IRQ when using Interrupt mode or the DMA IRQ when using DMA mode. - The HAL_USART_TxCpltCallback(), HAL_USART_RxCpltCallback() and HAL_USART_TxRxCpltCallback() - user callbacks + The HAL_USART_TxCpltCallback(), HAL_USART_RxCpltCallback() and HAL_USART_TxRxCpltCallback() + user callbacks will be executed respectively at the end of the transmit or Receive process - The HAL_USART_ErrorCallback() user callback will be executed when a communication + The HAL_USART_ErrorCallback() user callback will be executed when a communication error is detected (#) Blocking mode APIs are : @@ -415,8 +411,8 @@ __weak void HAL_USART_MspDeInit(USART_HandleTypeDef *husart) */ /** - * @brief Simplex Send an amount of data in blocking mode. - * @param husart: pointer to a USART_HandleTypeDef structure that contains + * @brief Simplex Send an amount of data in blocking mode. + * @param husart: Pointer to a USART_HandleTypeDef structure that contains * the configuration information for the specified USART module. * @param pTxData: Pointer to data buffer * @param Size: Amount of data to be sent @@ -425,12 +421,11 @@ __weak void HAL_USART_MspDeInit(USART_HandleTypeDef *husart) */ HAL_StatusTypeDef HAL_USART_Transmit(USART_HandleTypeDef *husart, uint8_t *pTxData, uint16_t Size, uint32_t Timeout) { - uint16_t* tmp; - uint32_t tickstart = 0U; + uint16_t* tmp=0; if(husart->State == HAL_USART_STATE_READY) { - if((pTxData == NULL) || (Size == 0U)) + if((pTxData == NULL) || (Size == 0)) { return HAL_ERROR; } @@ -441,18 +436,15 @@ HAL_StatusTypeDef HAL_USART_Transmit(USART_HandleTypeDef *husart, uint8_t *pTxDa husart->ErrorCode = HAL_USART_ERROR_NONE; husart->State = HAL_USART_STATE_BUSY_TX; - /* Init tickstart for timeout managment */ - tickstart = HAL_GetTick(); - husart->TxXferSize = Size; husart->TxXferCount = Size; - while(husart->TxXferCount > 0U) + while(husart->TxXferCount > 0) { husart->TxXferCount--; if(husart->Init.WordLength == USART_WORDLENGTH_9B) { /* Wait for TC flag in order to write data in DR */ - if(USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_TXE, RESET, tickstart, Timeout) != HAL_OK) + if(USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_TXE, RESET, Timeout) != HAL_OK) { return HAL_TIMEOUT; } @@ -460,16 +452,16 @@ HAL_StatusTypeDef HAL_USART_Transmit(USART_HandleTypeDef *husart, uint8_t *pTxDa WRITE_REG(husart->Instance->DR, (*tmp & (uint16_t)0x01FF)); if(husart->Init.Parity == USART_PARITY_NONE) { - pTxData += 2U; + pTxData += 2; } else { - pTxData += 1U; + pTxData += 1; } } else { - if(USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_TXE, RESET, tickstart, Timeout) != HAL_OK) + if(USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_TXE, RESET, Timeout) != HAL_OK) { return HAL_TIMEOUT; } @@ -477,8 +469,8 @@ HAL_StatusTypeDef HAL_USART_Transmit(USART_HandleTypeDef *husart, uint8_t *pTxDa } } - if(USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_TC, RESET, tickstart, Timeout) != HAL_OK) - { + if(USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_TC, RESET, Timeout) != HAL_OK) + { return HAL_TIMEOUT; } @@ -496,8 +488,8 @@ HAL_StatusTypeDef HAL_USART_Transmit(USART_HandleTypeDef *husart, uint8_t *pTxDa } /** - * @brief Full-Duplex Receive an amount of data in blocking mode. - * @param husart: pointer to a USART_HandleTypeDef structure that contains + * @brief Full-Duplex Receive an amount of data in blocking mode. + * @param husart: Pointer to a USART_HandleTypeDef structure that contains * the configuration information for the specified USART module. * @param pRxData: Pointer to data buffer * @param Size: Amount of data to be received @@ -506,62 +498,59 @@ HAL_StatusTypeDef HAL_USART_Transmit(USART_HandleTypeDef *husart, uint8_t *pTxDa */ HAL_StatusTypeDef HAL_USART_Receive(USART_HandleTypeDef *husart, uint8_t *pRxData, uint16_t Size, uint32_t Timeout) { - uint16_t* tmp; - uint32_t tickstart = 0U; + uint16_t* tmp=0; if(husart->State == HAL_USART_STATE_READY) { - if((pRxData == NULL) || (Size == 0U)) + if((pRxData == NULL) || (Size == 0)) { return HAL_ERROR; } + /* Process Locked */ __HAL_LOCK(husart); husart->ErrorCode = HAL_USART_ERROR_NONE; husart->State = HAL_USART_STATE_BUSY_RX; - /* Init tickstart for timeout managment */ - tickstart = HAL_GetTick(); - husart->RxXferSize = Size; husart->RxXferCount = Size; /* Check the remain data to be received */ - while(husart->RxXferCount > 0U) + while(husart->RxXferCount > 0) { husart->RxXferCount--; if(husart->Init.WordLength == USART_WORDLENGTH_9B) { /* Wait until TXE flag is set to send dummy byte in order to generate the clock for the slave to send data */ - if(USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_TXE, RESET, tickstart, Timeout) != HAL_OK) - { + if(USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_TXE, RESET, Timeout) != HAL_OK) + { return HAL_TIMEOUT; } /* Send dummy byte in order to generate clock */ WRITE_REG(husart->Instance->DR, (DUMMY_DATA & (uint16_t)0x01FF)); - + /* Wait for RXNE Flag */ - if(USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_RXNE, RESET, tickstart, Timeout) != HAL_OK) - { + if(USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_RXNE, RESET, Timeout) != HAL_OK) + { return HAL_TIMEOUT; } tmp = (uint16_t*) pRxData ; if(husart->Init.Parity == USART_PARITY_NONE) { *tmp = (uint16_t)(husart->Instance->DR & (uint16_t)0x01FF); - pRxData +=2U; + pRxData +=2; } else { *tmp = (uint16_t)(husart->Instance->DR & (uint16_t)0x00FF); - pRxData +=1U; + pRxData +=1; } } else { /* Wait until TXE flag is set to send dummy byte in order to generate the clock for the slave to send data */ - if(USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_TXE, RESET, tickstart, Timeout) != HAL_OK) - { + if(USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_TXE, RESET, Timeout) != HAL_OK) + { return HAL_TIMEOUT; } @@ -569,7 +558,7 @@ HAL_StatusTypeDef HAL_USART_Receive(USART_HandleTypeDef *husart, uint8_t *pRxDat WRITE_REG(husart->Instance->DR, (DUMMY_DATA & (uint16_t)0x00FF)); /* Wait until RXNE flag is set to receive the byte */ - if(USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_RXNE, RESET, tickstart, Timeout) != HAL_OK) + if(USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_RXNE, RESET, Timeout) != HAL_OK) { return HAL_TIMEOUT; } @@ -601,23 +590,22 @@ HAL_StatusTypeDef HAL_USART_Receive(USART_HandleTypeDef *husart, uint8_t *pRxDat } /** - * @brief Full-Duplex Send receive an amount of data in full-duplex mode (blocking mode). - * @param husart: pointer to a USART_HandleTypeDef structure that contains + * @brief Full-Duplex Send receive an amount of data in full-duplex mode (blocking mode). + * @param husart: Pointer to a USART_HandleTypeDef structure that contains * the configuration information for the specified USART module. * @param pTxData: Pointer to data transmitted buffer - * @param pRxData: Pointer to data received buffer + * @param pRxData: Pointer to data received buffer * @param Size: Amount of data to be sent * @param Timeout: Timeout duration * @retval HAL status */ HAL_StatusTypeDef HAL_USART_TransmitReceive(USART_HandleTypeDef *husart, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size, uint32_t Timeout) { - uint16_t* tmp; - uint32_t tickstart = 0U; + uint16_t* tmp=0; if(husart->State == HAL_USART_STATE_READY) { - if((pTxData == NULL) || (pRxData == NULL) || (Size == 0U)) + if((pTxData == NULL) || (pRxData == NULL) || (Size == 0)) { return HAL_ERROR; } @@ -627,23 +615,20 @@ HAL_StatusTypeDef HAL_USART_TransmitReceive(USART_HandleTypeDef *husart, uint8_t husart->ErrorCode = HAL_USART_ERROR_NONE; husart->State = HAL_USART_STATE_BUSY_RX; - /* Init tickstart for timeout managment */ - tickstart = HAL_GetTick(); - husart->RxXferSize = Size; husart->TxXferSize = Size; husart->TxXferCount = Size; husart->RxXferCount = Size; /* Check the remain data to be received */ - while(husart->TxXferCount > 0U) + while(husart->TxXferCount > 0) { husart->TxXferCount--; husart->RxXferCount--; if(husart->Init.WordLength == USART_WORDLENGTH_9B) { /* Wait for TC flag in order to write data in DR */ - if(USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_TXE, RESET, tickstart, Timeout) != HAL_OK) + if(USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_TXE, RESET, Timeout) != HAL_OK) { return HAL_TIMEOUT; } @@ -651,15 +636,15 @@ HAL_StatusTypeDef HAL_USART_TransmitReceive(USART_HandleTypeDef *husart, uint8_t WRITE_REG(husart->Instance->DR, (*tmp & (uint16_t)0x01FF)); if(husart->Init.Parity == USART_PARITY_NONE) { - pTxData += 2U; + pTxData += 2; } else { - pTxData += 1U; + pTxData += 1; } - + /* Wait for RXNE Flag */ - if(USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_RXNE, RESET, tickstart, Timeout) != HAL_OK) + if(USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_RXNE, RESET, Timeout) != HAL_OK) { return HAL_TIMEOUT; } @@ -667,25 +652,25 @@ HAL_StatusTypeDef HAL_USART_TransmitReceive(USART_HandleTypeDef *husart, uint8_t if(husart->Init.Parity == USART_PARITY_NONE) { *tmp = (uint16_t)(husart->Instance->DR & (uint16_t)0x01FF); - pRxData += 2U; + pRxData += 2; } else { *tmp = (uint16_t)(husart->Instance->DR & (uint16_t)0x00FF); - pRxData += 1U; + pRxData += 1; } - } + } else { /* Wait for TC flag in order to write data in DR */ - if(USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_TXE, RESET, tickstart, Timeout) != HAL_OK) + if(USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_TXE, RESET, Timeout) != HAL_OK) { return HAL_TIMEOUT; } WRITE_REG(husart->Instance->DR, (*pTxData++ & (uint8_t)0x00FF)); /* Wait for RXNE Flag */ - if(USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_RXNE, RESET, tickstart, Timeout) != HAL_OK) + if(USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_RXNE, RESET, Timeout) != HAL_OK) { return HAL_TIMEOUT; } @@ -716,8 +701,8 @@ HAL_StatusTypeDef HAL_USART_TransmitReceive(USART_HandleTypeDef *husart, uint8_t } /** - * @brief Simplex Send an amount of data in non-blocking mode. - * @param husart: pointer to a USART_HandleTypeDef structure that contains + * @brief Simplex Send an amount of data in non-blocking mode. + * @param husart: Pointer to a USART_HandleTypeDef structure that contains * the configuration information for the specified USART module. * @param pTxData: Pointer to data buffer * @param Size: Amount of data to be sent @@ -726,13 +711,13 @@ HAL_StatusTypeDef HAL_USART_TransmitReceive(USART_HandleTypeDef *husart, uint8_t */ HAL_StatusTypeDef HAL_USART_Transmit_IT(USART_HandleTypeDef *husart, uint8_t *pTxData, uint16_t Size) { - /* Check that a Tx process is not already ongoing */ if(husart->State == HAL_USART_STATE_READY) { - if((pTxData == NULL) || (Size == 0U)) + if((pTxData == NULL) || (Size == 0)) { return HAL_ERROR; } + /* Process Locked */ __HAL_LOCK(husart); @@ -743,7 +728,7 @@ HAL_StatusTypeDef HAL_USART_Transmit_IT(USART_HandleTypeDef *husart, uint8_t *pT husart->ErrorCode = HAL_USART_ERROR_NONE; husart->State = HAL_USART_STATE_BUSY_TX; - /* The USART Error Interrupts: (Frame error, Noise error, Overrun error) + /* The USART Error Interrupts: (Frame error, Noise error, Overrun error) are not managed by the USART transmit process to avoid the overrun interrupt when the USART mode is configured for transmit and receive "USART_MODE_TX_RX" to benefit for the frame error and noise interrupts the USART mode should be @@ -766,9 +751,9 @@ HAL_StatusTypeDef HAL_USART_Transmit_IT(USART_HandleTypeDef *husart, uint8_t *pT } /** - * @brief Simplex Receive an amount of data in non-blocking mode. - * @param husart: pointer to a USART_HandleTypeDef structure that contains - * the configuration information for the specified USART module. + * @brief Simplex Receive an amount of data in non-blocking mode. + * @param husart: Pointer to a USART_HandleTypeDef structure that contains + * the configuration information for the specified USART module. * @param pRxData: Pointer to data buffer * @param Size: Amount of data to be received * @retval HAL status @@ -777,7 +762,7 @@ HAL_StatusTypeDef HAL_USART_Receive_IT(USART_HandleTypeDef *husart, uint8_t *pRx { if(husart->State == HAL_USART_STATE_READY) { - if((pRxData == NULL) || (Size == 0U)) + if((pRxData == NULL) || (Size == 0)) { return HAL_ERROR; } @@ -815,11 +800,11 @@ HAL_StatusTypeDef HAL_USART_Receive_IT(USART_HandleTypeDef *husart, uint8_t *pRx } /** - * @brief Full-Duplex Send receive an amount of data in full-duplex mode (non-blocking). - * @param husart: pointer to a USART_HandleTypeDef structure that contains + * @brief Full-Duplex Send receive an amount of data in full-duplex mode (non-blocking). + * @param husart: Pointer to a USART_HandleTypeDef structure that contains * the configuration information for the specified USART module. * @param pTxData: Pointer to data transmitted buffer - * @param pRxData: Pointer to data received buffer + * @param pRxData: Pointer to data received buffer * @param Size: Amount of data to be received * @retval HAL status */ @@ -827,7 +812,7 @@ HAL_StatusTypeDef HAL_USART_TransmitReceive_IT(USART_HandleTypeDef *husart, uint { if(husart->State == HAL_USART_STATE_READY) { - if((pTxData == NULL) || (pRxData == NULL) || (Size == 0U)) + if((pTxData == NULL) || (pRxData == NULL) || (Size == 0)) { return HAL_ERROR; } @@ -863,13 +848,13 @@ HAL_StatusTypeDef HAL_USART_TransmitReceive_IT(USART_HandleTypeDef *husart, uint } else { - return HAL_BUSY; + return HAL_BUSY; } } /** - * @brief Simplex Send an amount of data in non-blocking mode. - * @param husart: pointer to a USART_HandleTypeDef structure that contains + * @brief Simplex Send an amount of data in non-blocking mode. + * @param husart: Pointer to a USART_HandleTypeDef structure that contains * the configuration information for the specified USART module. * @param pTxData: Pointer to data buffer * @param Size: Amount of data to be sent @@ -877,16 +862,16 @@ HAL_StatusTypeDef HAL_USART_TransmitReceive_IT(USART_HandleTypeDef *husart, uint */ HAL_StatusTypeDef HAL_USART_Transmit_DMA(USART_HandleTypeDef *husart, uint8_t *pTxData, uint16_t Size) { - uint32_t *tmp; + uint32_t *tmp=0; if(husart->State == HAL_USART_STATE_READY) { - if((pTxData == NULL) || (Size == 0U)) + if((pTxData == NULL) || (Size == 0)) { return HAL_ERROR; } /* Process Locked */ - __HAL_LOCK(husart); + __HAL_LOCK(husart); husart->pTxBuffPtr = pTxData; husart->TxXferSize = Size; @@ -904,9 +889,6 @@ HAL_StatusTypeDef HAL_USART_Transmit_DMA(USART_HandleTypeDef *husart, uint8_t *p /* Set the DMA error callback */ husart->hdmatx->XferErrorCallback = USART_DMAError; - /* Set the DMA abort callback */ - husart->hdmatx->XferAbortCallback = NULL; - /* Enable the USART transmit DMA channel */ tmp = (uint32_t*)&pTxData; HAL_DMA_Start_IT(husart->hdmatx, *(uint32_t*)tmp, (uint32_t)&husart->Instance->DR, Size); @@ -914,13 +896,13 @@ HAL_StatusTypeDef HAL_USART_Transmit_DMA(USART_HandleTypeDef *husart, uint8_t *p /* Clear the TC flag in the SR register by writing 0 to it */ __HAL_USART_CLEAR_FLAG(husart, USART_FLAG_TC); - /* Process Unlocked */ - __HAL_UNLOCK(husart); - /* Enable the DMA transfer for transmit request by setting the DMAT bit - in the USART CR3 register */ + in the USART CR3 register */ SET_BIT(husart->Instance->CR3, USART_CR3_DMAT); + /* Process Unlocked */ + __HAL_UNLOCK(husart); + return HAL_OK; } else @@ -930,8 +912,8 @@ HAL_StatusTypeDef HAL_USART_Transmit_DMA(USART_HandleTypeDef *husart, uint8_t *p } /** - * @brief Full-Duplex Receive an amount of data in non-blocking mode. - * @param husart: pointer to a USART_HandleTypeDef structure that contains + * @brief Full-Duplex Receive an amount of data in non-blocking mode. + * @param husart: Pointer to a USART_HandleTypeDef structure that contains * the configuration information for the specified USART module. * @param pRxData: Pointer to data buffer * @param Size: Amount of data to be received @@ -941,11 +923,11 @@ HAL_StatusTypeDef HAL_USART_Transmit_DMA(USART_HandleTypeDef *husart, uint8_t *p */ HAL_StatusTypeDef HAL_USART_Receive_DMA(USART_HandleTypeDef *husart, uint8_t *pRxData, uint16_t Size) { - uint32_t *tmp; - + uint32_t *tmp=0; + if(husart->State == HAL_USART_STATE_READY) { - if((pRxData == NULL) || (Size == 0U)) + if((pRxData == NULL) || (Size == 0)) { return HAL_ERROR; } @@ -970,42 +952,20 @@ HAL_StatusTypeDef HAL_USART_Receive_DMA(USART_HandleTypeDef *husart, uint8_t *pR /* Set the USART DMA Rx transfer error callback */ husart->hdmarx->XferErrorCallback = USART_DMAError; - /* Set the DMA abort callback */ - husart->hdmarx->XferAbortCallback = NULL; - - /* Set the USART Tx DMA transfer complete callback as NULL because the communication closing - is performed in DMA reception complete callback */ - husart->hdmatx->XferHalfCpltCallback = NULL; - husart->hdmatx->XferCpltCallback = NULL; - - /* Set the DMA error callback */ - husart->hdmatx->XferErrorCallback = USART_DMAError; - - /* Set the DMA AbortCpltCallback */ - husart->hdmatx->XferAbortCallback = NULL; - /* Enable the USART receive DMA channel */ tmp = (uint32_t*)&pRxData; HAL_DMA_Start_IT(husart->hdmarx, (uint32_t)&husart->Instance->DR, *(uint32_t*)tmp, Size); /* Enable the USART transmit DMA channel: the transmit channel is used in order - to generate in the non-blocking mode the clock to the slave device, + to generate in the non-blocking mode the clock to the slave device, this mode isn't a simplex receive mode but a full-duplex receive one */ HAL_DMA_Start_IT(husart->hdmatx, *(uint32_t*)tmp, (uint32_t)&husart->Instance->DR, Size); - /* Clear the Overrun flag just before enabling the DMA Rx request: mandatory for the second transfer */ + /* Clear the Overrun flag just before enabling the DMA Rx request: mandatory for the second transfer + when using the USART in circular mode */ __HAL_USART_CLEAR_OREFLAG(husart); - - /* Process Unlocked */ - __HAL_UNLOCK(husart); - - /* Enable the USART Parity Error Interrupt */ - SET_BIT(husart->Instance->CR1, USART_CR1_PEIE); - - /* Enable the USART Error Interrupt: (Frame error, noise error, overrun error) */ - SET_BIT(husart->Instance->CR3, USART_CR3_EIE); - - /* Enable the DMA transfer for the receiver request by setting the DMAR bit + + /* Enable the DMA transfer for the receiver request by setting the DMAR bit in the USART CR3 register */ SET_BIT(husart->Instance->CR3, USART_CR3_DMAR); @@ -1013,6 +973,9 @@ HAL_StatusTypeDef HAL_USART_Receive_DMA(USART_HandleTypeDef *husart, uint8_t *pR in the USART CR3 register */ SET_BIT(husart->Instance->CR3, USART_CR3_DMAT); + /* Process Unlocked */ + __HAL_UNLOCK(husart); + return HAL_OK; } else @@ -1022,22 +985,22 @@ HAL_StatusTypeDef HAL_USART_Receive_DMA(USART_HandleTypeDef *husart, uint8_t *pR } /** - * @brief Full-Duplex Transmit Receive an amount of data in non-blocking mode. - * @param husart: pointer to a USART_HandleTypeDef structure that contains + * @brief Full-Duplex Transmit Receive an amount of data in non-blocking mode. + * @param husart: Pointer to a USART_HandleTypeDef structure that contains * the configuration information for the specified USART module. * @param pTxData: Pointer to data transmitted buffer - * @param pRxData: Pointer to data received buffer + * @param pRxData: Pointer to data received buffer * @param Size: Amount of data to be received * @note When the USART parity is enabled (PCE = 1) the data received contain the parity bit. * @retval HAL status */ HAL_StatusTypeDef HAL_USART_TransmitReceive_DMA(USART_HandleTypeDef *husart, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size) { - uint32_t *tmp; + uint32_t *tmp=0; if(husart->State == HAL_USART_STATE_READY) { - if((pTxData == NULL) || (pRxData == NULL) || (Size == 0U)) + if((pTxData == NULL) || (pRxData == NULL) || (Size == 0)) { return HAL_ERROR; } @@ -1070,9 +1033,6 @@ HAL_StatusTypeDef HAL_USART_TransmitReceive_DMA(USART_HandleTypeDef *husart, uin /* Set the USART DMA Rx transfer error callback */ husart->hdmarx->XferErrorCallback = USART_DMAError; - /* Set the DMA abort callback */ - husart->hdmarx->XferAbortCallback = NULL; - /* Enable the USART receive DMA channel */ tmp = (uint32_t*)&pRxData; HAL_DMA_Start_IT(husart->hdmarx, (uint32_t)&husart->Instance->DR, *(uint32_t*)tmp, Size); @@ -1080,23 +1040,14 @@ HAL_StatusTypeDef HAL_USART_TransmitReceive_DMA(USART_HandleTypeDef *husart, uin /* Enable the USART transmit DMA channel */ tmp = (uint32_t*)&pTxData; HAL_DMA_Start_IT(husart->hdmatx, *(uint32_t*)tmp, (uint32_t)&husart->Instance->DR, Size); - + /* Clear the TC flag in the SR register by writing 0 to it */ __HAL_USART_CLEAR_FLAG(husart, USART_FLAG_TC); /* Clear the Overrun flag: mandatory for the second transfer in circular mode */ __HAL_USART_CLEAR_OREFLAG(husart); - - /* Process Unlocked */ - __HAL_UNLOCK(husart); - - /* Enable the USART Parity Error Interrupt */ - SET_BIT(husart->Instance->CR1, USART_CR1_PEIE); - - /* Enable the USART Error Interrupt: (Frame error, noise error, overrun error) */ - SET_BIT(husart->Instance->CR3, USART_CR3_EIE); - - /* Enable the DMA transfer for the receiver request by setting the DMAR bit + + /* Enable the DMA transfer for the receiver request by setting the DMAR bit in the USART CR3 register */ SET_BIT(husart->Instance->CR3, USART_CR3_DMAR); @@ -1104,6 +1055,9 @@ HAL_StatusTypeDef HAL_USART_TransmitReceive_DMA(USART_HandleTypeDef *husart, uin in the USART CR3 register */ SET_BIT(husart->Instance->CR3, USART_CR3_DMAT); + /* Process Unlocked */ + __HAL_UNLOCK(husart); + return HAL_OK; } else @@ -1114,7 +1068,7 @@ HAL_StatusTypeDef HAL_USART_TransmitReceive_DMA(USART_HandleTypeDef *husart, uin /** * @brief Pauses the DMA Transfer. - * @param husart: pointer to a USART_HandleTypeDef structure that contains + * @param husart: Pointer to a USART_HandleTypeDef structure that contains * the configuration information for the specified USART module. * @retval HAL status */ @@ -1122,19 +1076,19 @@ HAL_StatusTypeDef HAL_USART_DMAPause(USART_HandleTypeDef *husart) { /* Process Locked */ __HAL_LOCK(husart); - + /* Disable the USART DMA Tx request */ - CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAT); - + CLEAR_BIT(husart->Instance->CR3, (uint32_t)(USART_CR3_DMAT)); + /* Process Unlocked */ __HAL_UNLOCK(husart); - return HAL_OK; + return HAL_OK; } /** * @brief Resumes the DMA Transfer. - * @param husart: pointer to a USART_HandleTypeDef structure that contains + * @param husart: Pointer to a USART_HandleTypeDef structure that contains * the configuration information for the specified USART module. * @retval HAL status */ @@ -1142,10 +1096,10 @@ HAL_StatusTypeDef HAL_USART_DMAResume(USART_HandleTypeDef *husart) { /* Process Locked */ __HAL_LOCK(husart); - + /* Enable the USART DMA Tx request */ SET_BIT(husart->Instance->CR3, USART_CR3_DMAT); - + /* Process Unlocked */ __HAL_UNLOCK(husart); @@ -1154,364 +1108,107 @@ HAL_StatusTypeDef HAL_USART_DMAResume(USART_HandleTypeDef *husart) /** * @brief Stops the DMA Transfer. - * @param husart: pointer to a USART_HandleTypeDef structure that contains + * @param husart: Pointer to a USART_HandleTypeDef structure that contains * the configuration information for the specified USART module. * @retval HAL status */ HAL_StatusTypeDef HAL_USART_DMAStop(USART_HandleTypeDef *husart) { - uint32_t dmarequest = 0x00U; /* The Lock is not implemented on this API to allow the user application to call the HAL USART API under callbacks HAL_USART_TxCpltCallback() / HAL_USART_RxCpltCallback(): when calling HAL_DMA_Abort() API the DMA TX/RX Transfer complete interrupt is generated and the correspond call back is executed HAL_USART_TxCpltCallback() / HAL_USART_RxCpltCallback() */ - /* Stop USART DMA Tx request if ongoing */ - dmarequest = HAL_IS_BIT_SET(husart->Instance->CR3, USART_CR3_DMAT); - if((husart->State == HAL_USART_STATE_BUSY_TX) && dmarequest) - { - USART_EndTxTransfer(husart); - - /* Abort the USART DMA Tx channel */ - if(husart->hdmatx != NULL) - { - HAL_DMA_Abort(husart->hdmatx); - } - - /* Disable the USART Tx DMA request */ - CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAT); - } - - /* Stop USART DMA Rx request if ongoing */ - dmarequest = HAL_IS_BIT_SET(husart->Instance->CR3, USART_CR3_DMAR); - if((husart->State == HAL_USART_STATE_BUSY_RX) && dmarequest) - { - USART_EndRxTransfer(husart); - - /* Abort the USART DMA Rx channel */ - if(husart->hdmarx != NULL) - { - HAL_DMA_Abort(husart->hdmarx); - } - - /* Disable the USART Rx DMA request */ - CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAR); - } - - return HAL_OK; -} - -/** - * @brief Abort ongoing transfer (blocking mode). - * @param husart USART handle. - * @note This procedure could be used for aborting any ongoing transfer (either Tx or Rx, - * as described by TransferType parameter) started in Interrupt or DMA mode. - * This procedure performs following operations : - * - Disable PPP Interrupts (depending of transfer direction) - * - Disable the DMA transfer in the peripheral register (if enabled) - * - Abort DMA transfer by calling HAL_DMA_Abort (in case of transfer in DMA mode) - * - Set handle State to READY - * @note This procedure is executed in blocking mode : when exiting function, Abort is considered as completed. - * @retval HAL status -*/ -HAL_StatusTypeDef HAL_USART_Abort(USART_HandleTypeDef *husart) -{ - /* Disable TXEIE, TCIE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */ - CLEAR_BIT(husart->Instance->CR1, (USART_CR1_RXNEIE | USART_CR1_PEIE | USART_CR1_TXEIE | USART_CR1_TCIE)); - CLEAR_BIT(husart->Instance->CR3, USART_CR3_EIE); - - /* Disable the USART DMA Tx request if enabled */ - if(HAL_IS_BIT_SET(husart->Instance->CR3, USART_CR3_DMAT)) + /* Abort the USART DMA Tx channel */ + if(husart->hdmatx != NULL) { - CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAT); - - /* Abort the USART DMA Tx channel : use blocking DMA Abort API (no callback) */ - if(husart->hdmatx != NULL) - { - /* Set the USART DMA Abort callback to Null. - No call back execution at end of DMA abort procedure */ - husart->hdmatx->XferAbortCallback = NULL; - - HAL_DMA_Abort(husart->hdmatx); - } + HAL_DMA_Abort(husart->hdmatx); } - - /* Disable the USART DMA Rx request if enabled */ - if(HAL_IS_BIT_SET(husart->Instance->CR3, USART_CR3_DMAR)) - { - CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAR); - - /* Abort the USART DMA Rx channel : use blocking DMA Abort API (no callback) */ - if(husart->hdmarx != NULL) - { - /* Set the USART DMA Abort callback to Null. - No call back execution at end of DMA abort procedure */ - husart->hdmarx->XferAbortCallback = NULL; - - HAL_DMA_Abort(husart->hdmarx); - } + /* Abort the USART DMA Rx channel */ + if(husart->hdmarx != NULL) + { + HAL_DMA_Abort(husart->hdmarx); } + + /* Disable the USART Tx/Rx DMA requests */ + CLEAR_BIT(husart->Instance->CR3, (USART_CR3_DMAT | USART_CR3_DMAR)); - /* Reset Tx and Rx transfer counters */ - husart->TxXferCount = 0x00U; - husart->RxXferCount = 0x00U; - - /* Restore husart->State to Ready */ - husart->State = HAL_USART_STATE_READY; - - /* Reset Handle ErrorCode to No Error */ - husart->ErrorCode = HAL_USART_ERROR_NONE; + husart->State = HAL_USART_STATE_READY; return HAL_OK; } /** - * @brief Abort ongoing transfer (Interrupt mode). - * @param husart USART handle. - * @note This procedure could be used for aborting any ongoing transfer (either Tx or Rx, - * as described by TransferType parameter) started in Interrupt or DMA mode. - * This procedure performs following operations : - * - Disable PPP Interrupts (depending of transfer direction) - * - Disable the DMA transfer in the peripheral register (if enabled) - * - Abort DMA transfer by calling HAL_DMA_Abort_IT (in case of transfer in DMA mode) - * - Set handle State to READY - * - At abort completion, call user abort complete callback - * @note This procedure is executed in Interrupt mode, meaning that abort procedure could be - * considered as completed only when user abort complete callback is executed (not when exiting function). - * @retval HAL status -*/ -HAL_StatusTypeDef HAL_USART_Abort_IT(USART_HandleTypeDef *husart) + * @brief This function handles USART interrupt request. + * @param husart: Pointer to a USART_HandleTypeDef structure that contains + * the configuration information for the specified USART module. + * @retval None + */ +void HAL_USART_IRQHandler(USART_HandleTypeDef *husart) { - uint32_t AbortCplt = 0x01U; + uint32_t tmp_flag = 0, tmp_it_source = 0; - /* Disable TXEIE, TCIE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */ - CLEAR_BIT(husart->Instance->CR1, (USART_CR1_RXNEIE | USART_CR1_PEIE | USART_CR1_TXEIE | USART_CR1_TCIE)); - CLEAR_BIT(husart->Instance->CR3, USART_CR3_EIE); - - /* If DMA Tx and/or DMA Rx Handles are associated to USART Handle, DMA Abort complete callbacks should be initialised - before any call to DMA Abort functions */ - /* DMA Tx Handle is valid */ - if(husart->hdmatx != NULL) + tmp_flag = __HAL_USART_GET_FLAG(husart, USART_FLAG_PE); + tmp_it_source = __HAL_USART_GET_IT_SOURCE(husart, USART_IT_PE); + /* USART parity error interrupt occurred -----------------------------------*/ + if((tmp_flag != RESET) && (tmp_it_source != RESET)) { - /* Set DMA Abort Complete callback if USART DMA Tx request if enabled. - Otherwise, set it to NULL */ - if(HAL_IS_BIT_SET(husart->Instance->CR3, USART_CR3_DMAT)) - { - husart->hdmatx->XferAbortCallback = USART_DMATxAbortCallback; - } - else - { - husart->hdmatx->XferAbortCallback = NULL; - } + husart->ErrorCode |= HAL_USART_ERROR_PE; } - /* DMA Rx Handle is valid */ - if(husart->hdmarx != NULL) + + tmp_flag = __HAL_USART_GET_FLAG(husart, USART_FLAG_FE); + tmp_it_source = __HAL_USART_GET_IT_SOURCE(husart, USART_IT_ERR); + /* USART frame error interrupt occurred ------------------------------------*/ + if((tmp_flag != RESET) && (tmp_it_source != RESET)) { - /* Set DMA Abort Complete callback if USART DMA Rx request if enabled. - Otherwise, set it to NULL */ - if(HAL_IS_BIT_SET(husart->Instance->CR3, USART_CR3_DMAR)) - { - husart->hdmarx->XferAbortCallback = USART_DMARxAbortCallback; - } - else - { - husart->hdmarx->XferAbortCallback = NULL; - } + husart->ErrorCode |= HAL_USART_ERROR_FE; } - - /* Disable the USART DMA Tx request if enabled */ - if(HAL_IS_BIT_SET(husart->Instance->CR3, USART_CR3_DMAT)) - { - /* Disable DMA Tx at USART level */ - CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAT); - /* Abort the USART DMA Tx channel : use non blocking DMA Abort API (callback) */ - if(husart->hdmatx != NULL) - { - /* USART Tx DMA Abort callback has already been initialised : - will lead to call HAL_USART_AbortCpltCallback() at end of DMA abort procedure */ - - /* Abort DMA TX */ - if(HAL_DMA_Abort_IT(husart->hdmatx) != HAL_OK) - { - husart->hdmatx->XferAbortCallback = NULL; - } - else - { - AbortCplt = 0x00U; - } - } + tmp_flag = __HAL_USART_GET_FLAG(husart, USART_FLAG_NE); + /* USART noise error interrupt occurred ------------------------------------*/ + if((tmp_flag != RESET) && (tmp_it_source != RESET)) + { + husart->ErrorCode |= HAL_USART_ERROR_NE; } - /* Disable the USART DMA Rx request if enabled */ - if(HAL_IS_BIT_SET(husart->Instance->CR3, USART_CR3_DMAR)) + tmp_flag = __HAL_USART_GET_FLAG(husart, USART_FLAG_ORE); + /* USART Over-Run interrupt occurred ---------------------------------------*/ + if((tmp_flag != RESET) && (tmp_it_source != RESET)) { - CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAR); - - /* Abort the USART DMA Rx channel : use non blocking DMA Abort API (callback) */ - if(husart->hdmarx != NULL) - { - /* USART Rx DMA Abort callback has already been initialised : - will lead to call HAL_USART_AbortCpltCallback() at end of DMA abort procedure */ - - /* Abort DMA RX */ - if(HAL_DMA_Abort_IT(husart->hdmarx) != HAL_OK) - { - husart->hdmarx->XferAbortCallback = NULL; - AbortCplt = 0x01U; - } - else - { - AbortCplt = 0x00U; - } - } + husart->ErrorCode |= HAL_USART_ERROR_ORE; } - /* if no DMA abort complete callback execution is required => call user Abort Complete callback */ - if(AbortCplt == 0x01U) + if(husart->ErrorCode != HAL_USART_ERROR_NONE) { - /* Reset Tx and Rx transfer counters */ - husart->TxXferCount = 0x00U; - husart->RxXferCount = 0x00U; - - /* Reset errorCode */ - husart->ErrorCode = HAL_USART_ERROR_NONE; + /* Clear all the error flag at once */ + __HAL_USART_CLEAR_PEFLAG(husart); - /* Restore husart->State to Ready */ - husart->State = HAL_USART_STATE_READY; - - /* As no DMA to be aborted, call directly user Abort complete callback */ - HAL_USART_AbortCpltCallback(husart); + /* Set the USART state ready to be able to start again the process */ + husart->State = HAL_USART_STATE_READY; + + HAL_USART_ErrorCallback(husart); } - return HAL_OK; -} - -/** - * @brief This function handles USART interrupt request. - * @param husart: pointer to a USART_HandleTypeDef structure that contains - * the configuration information for the specified USART module. - * @retval None - */ -void HAL_USART_IRQHandler(USART_HandleTypeDef *husart) -{ - uint32_t isrflags = READ_REG(husart->Instance->SR); - uint32_t cr1its = READ_REG(husart->Instance->CR1); - uint32_t cr3its = READ_REG(husart->Instance->CR3); - uint32_t errorflags = 0x00U; - uint32_t dmarequest = 0x00U; - - /* If no error occurs */ - errorflags = (isrflags & (uint32_t)(USART_SR_PE | USART_SR_FE | USART_SR_ORE | USART_SR_NE)); - if(errorflags == RESET) - { - /* USART in mode Receiver -------------------------------------------------*/ - if(((isrflags & USART_SR_RXNE) != RESET) && ((cr1its & USART_CR1_RXNEIE) != RESET)) - { - if(husart->State == HAL_USART_STATE_BUSY_RX) - { - USART_Receive_IT(husart); - } - else - { - USART_TransmitReceive_IT(husart); - } - return; - } - } - /* If some errors occur */ - if((errorflags != RESET) && (((cr3its & USART_CR3_EIE) != RESET) || ((cr1its & (USART_CR1_RXNEIE | USART_CR1_PEIE)) != RESET))) + tmp_flag = __HAL_USART_GET_FLAG(husart, USART_FLAG_RXNE); + tmp_it_source = __HAL_USART_GET_IT_SOURCE(husart, USART_IT_RXNE); + /* USART in mode Receiver --------------------------------------------------*/ + if((tmp_flag != RESET) && (tmp_it_source != RESET)) { - /* USART parity error interrupt occurred ----------------------------------*/ - if(((isrflags & USART_SR_PE) != RESET) && ((cr1its & USART_CR1_PEIE) != RESET)) - { - husart->ErrorCode |= HAL_USART_ERROR_PE; - } - - /* USART noise error interrupt occurred --------------------------------*/ - if(((isrflags & USART_SR_NE) != RESET) && ((cr3its & USART_CR3_EIE) != RESET)) - { - husart->ErrorCode |= HAL_USART_ERROR_NE; - } - - /* USART frame error interrupt occurred --------------------------------*/ - if(((isrflags & USART_SR_FE) != RESET) && ((cr3its & USART_CR3_EIE) != RESET)) - { - husart->ErrorCode |= HAL_USART_ERROR_FE; - } - - /* USART Over-Run interrupt occurred -----------------------------------*/ - if(((isrflags & USART_SR_ORE) != RESET) && ((cr3its & USART_CR3_EIE) != RESET)) + if(husart->State == HAL_USART_STATE_BUSY_RX) { - husart->ErrorCode |= HAL_USART_ERROR_ORE; + USART_Receive_IT(husart); } - - if(husart->ErrorCode != HAL_USART_ERROR_NONE) + else { - /* USART in mode Receiver -----------------------------------------------*/ - if(((isrflags & USART_SR_RXNE) != RESET) && ((cr1its & USART_CR1_RXNEIE) != RESET)) - { - if(husart->State == HAL_USART_STATE_BUSY_RX) - { - USART_Receive_IT(husart); - } - else - { - USART_TransmitReceive_IT(husart); - } - } - /* If Overrun error occurs, or if any error occurs in DMA mode reception, - consider error as blocking */ - dmarequest = HAL_IS_BIT_SET(husart->Instance->CR3, USART_CR3_DMAR); - if(((husart->ErrorCode & HAL_USART_ERROR_ORE) != RESET) || dmarequest) - { - /* Set the USART state ready to be able to start again the process, - Disable Rx Interrupts, and disable Rx DMA request, if ongoing */ - USART_EndRxTransfer(husart); - - /* Disable the USART DMA Rx request if enabled */ - if (HAL_IS_BIT_SET(husart->Instance->CR3, USART_CR3_DMAR)) - { - CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAR); - - /* Abort the USART DMA Rx channel */ - if(husart->hdmarx != NULL) - { - /* Set the USART DMA Abort callback : - will lead to call HAL_USART_ErrorCallback() at end of DMA abort procedure */ - husart->hdmarx->XferAbortCallback = USART_DMAAbortOnError; - - if(HAL_DMA_Abort_IT(husart->hdmarx) != HAL_OK) - { - /* Call Directly XferAbortCallback function in case of error */ - husart->hdmarx->XferAbortCallback(husart->hdmarx); - } - } - else - { - /* Call user error callback */ - HAL_USART_ErrorCallback(husart); - } - } - else - { - /* Call user error callback */ - HAL_USART_ErrorCallback(husart); - } - } - else - { - /* Call user error callback */ - HAL_USART_ErrorCallback(husart); - husart->ErrorCode = HAL_USART_ERROR_NONE; - } + USART_TransmitReceive_IT(husart); } - return; } + tmp_flag = __HAL_USART_GET_FLAG(husart, USART_FLAG_TXE); + tmp_it_source = __HAL_USART_GET_IT_SOURCE(husart, USART_IT_TXE); /* USART in mode Transmitter -----------------------------------------------*/ - if(((isrflags & USART_SR_TXE) != RESET) && ((cr1its & USART_CR1_TXEIE) != RESET)) + if((tmp_flag != RESET) && (tmp_it_source != RESET)) { if(husart->State == HAL_USART_STATE_BUSY_TX) { @@ -1521,50 +1218,52 @@ void HAL_USART_IRQHandler(USART_HandleTypeDef *husart) { USART_TransmitReceive_IT(husart); } - return; } - - /* USART in mode Transmitter (transmission end) ----------------------------*/ - if(((isrflags & USART_SR_TC) != RESET) && ((cr1its & USART_CR1_TCIE) != RESET)) + + tmp_flag = __HAL_USART_GET_FLAG(husart, USART_FLAG_TC); + tmp_it_source = __HAL_USART_GET_IT_SOURCE(husart, USART_IT_TC); + /* USART in mode Transmitter (transmission end) -----------------------------*/ + if((tmp_flag != RESET) && (tmp_it_source != RESET)) { USART_EndTransmit_IT(husart); - return; - } + } + } + /** * @brief Tx Transfer completed callbacks. - * @param husart: pointer to a USART_HandleTypeDef structure that contains + * @param husart: Pointer to a USART_HandleTypeDef structure that contains * the configuration information for the specified USART module. * @retval None */ -__weak void HAL_USART_TxCpltCallback(USART_HandleTypeDef *husart) + __weak void HAL_USART_TxCpltCallback(USART_HandleTypeDef *husart) { /* Prevent unused argument(s) compilation warning */ UNUSED(husart); /* NOTE: This function should not be modified, when the callback is needed, - the HAL_USART_TxCpltCallback could be implemented in the user file + the HAL_USART_TxCpltCallback can be implemented in the user file */ } /** * @brief Tx Half Transfer completed callbacks. - * @param husart: pointer to a USART_HandleTypeDef structure that contains + * @param husart: Pointer to a USART_HandleTypeDef structure that contains * the configuration information for the specified USART module. * @retval None */ -__weak void HAL_USART_TxHalfCpltCallback(USART_HandleTypeDef *husart) + __weak void HAL_USART_TxHalfCpltCallback(USART_HandleTypeDef *husart) { /* Prevent unused argument(s) compilation warning */ UNUSED(husart); /* NOTE: This function should not be modified, when the callback is needed, - the HAL_USART_TxHalfCpltCallback could be implemented in the user file + the HAL_USART_TxHalfCpltCallback can be implemented in the user file */ } /** * @brief Rx Transfer completed callbacks. - * @param husart: pointer to a USART_HandleTypeDef structure that contains + * @param husart: Pointer to a USART_HandleTypeDef structure that contains * the configuration information for the specified USART module. * @retval None */ @@ -1573,13 +1272,13 @@ __weak void HAL_USART_RxCpltCallback(USART_HandleTypeDef *husart) /* Prevent unused argument(s) compilation warning */ UNUSED(husart); /* NOTE: This function should not be modified, when the callback is needed, - the HAL_USART_RxCpltCallback could be implemented in the user file + the HAL_USART_RxCpltCallback can be implemented in the user file */ } /** * @brief Rx Half Transfer completed callbacks. - * @param husart: pointer to a USART_HandleTypeDef structure that contains + * @param husart: Pointer to a USART_HandleTypeDef structure that contains * the configuration information for the specified USART module. * @retval None */ @@ -1588,13 +1287,13 @@ __weak void HAL_USART_RxHalfCpltCallback(USART_HandleTypeDef *husart) /* Prevent unused argument(s) compilation warning */ UNUSED(husart); /* NOTE: This function should not be modified, when the callback is needed, - the HAL_USART_RxHalfCpltCallback could be implemented in the user file + the HAL_USART_RxHalfCpltCallback can be implemented in the user file */ } /** * @brief Tx/Rx Transfers completed callback for the non-blocking process. - * @param husart: pointer to a USART_HandleTypeDef structure that contains + * @param husart: Pointer to a USART_HandleTypeDef structure that contains * the configuration information for the specified USART module. * @retval None */ @@ -1603,66 +1302,51 @@ __weak void HAL_USART_TxRxCpltCallback(USART_HandleTypeDef *husart) /* Prevent unused argument(s) compilation warning */ UNUSED(husart); /* NOTE: This function should not be modified, when the callback is needed, - the HAL_USART_TxRxCpltCallback could be implemented in the user file + the HAL_USART_TxRxCpltCallback can be implemented in the user file */ } /** * @brief USART error callbacks. - * @param husart: pointer to a USART_HandleTypeDef structure that contains + * @param husart: Pointer to a USART_HandleTypeDef structure that contains * the configuration information for the specified USART module. * @retval None */ -__weak void HAL_USART_ErrorCallback(USART_HandleTypeDef *husart) + __weak void HAL_USART_ErrorCallback(USART_HandleTypeDef *husart) { /* Prevent unused argument(s) compilation warning */ UNUSED(husart); /* NOTE: This function should not be modified, when the callback is needed, - the HAL_USART_ErrorCallback could be implemented in the user file - */ -} - -/** - * @brief USART Abort Complete callback. - * @param husart USART handle. - * @retval None - */ -__weak void HAL_USART_AbortCpltCallback (USART_HandleTypeDef *husart) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(husart); - - /* NOTE : This function should not be modified, when the callback is needed, - the HAL_USART_AbortCpltCallback can be implemented in the user file. - */ + the HAL_USART_ErrorCallback can be implemented in the user file + */ } /** * @} */ -/** @defgroup USART_Exported_Functions_Group3 Peripheral State and Errors functions - * @brief USART State and Errors functions +/** @defgroup USART_Exported_Functions_Group3 Peripheral State and Errors functions + * @brief USART State and Errors functions * -@verbatim +@verbatim ============================================================================== ##### Peripheral State and Errors functions ##### - ============================================================================== + ============================================================================== [..] - This subsection provides a set of functions allowing to return the State of + This subsection provides a set of functions allowing to return the State of USART communication process, return Peripheral Errors occurred during communication process - (+) HAL_USART_GetState() API can be helpful to check in run-time the state + (+) HAL_USART_GetState() API can be helpful to check in run-time the state of the USART peripheral. - (+) HAL_USART_GetError() check in run-time errors that could be occurred during - communication. + (+) HAL_USART_GetError() check in run-time errors that could be occurred during + communication. @endverbatim * @{ */ /** * @brief Returns the USART state. - * @param husart: pointer to a USART_HandleTypeDef structure that contains + * @param husart: Pointer to a USART_HandleTypeDef structure that contains * the configuration information for the specified USART module. * @retval HAL state */ @@ -1695,8 +1379,7 @@ uint32_t HAL_USART_GetError(USART_HandleTypeDef *husart) * @{ */ /** - * @brief DMA USART transmit process complete callback. - * @param hdma: DMA handle + * @brief DMA USART transmit process complete callback. * @param hdma: Pointer to a DMA_HandleTypeDef structure that contains * the configuration information for the specified DMA module. * @retval None @@ -1704,17 +1387,19 @@ uint32_t HAL_USART_GetError(USART_HandleTypeDef *husart) static void USART_DMATransmitCplt(DMA_HandleTypeDef *hdma) { USART_HandleTypeDef* husart = ( USART_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + /* DMA Normal mode */ - if(HAL_IS_BIT_CLR(hdma->Instance->CCR, DMA_CCR_CIRC)) + if ( HAL_IS_BIT_CLR(hdma->Instance->CCR, DMA_CCR_CIRC) ) { - husart->TxXferCount = 0U; + husart->TxXferCount = 0; + if(husart->State == HAL_USART_STATE_BUSY_TX) { /* Disable the DMA transfer for transmit request by resetting the DMAT bit in the USART CR3 register */ CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAT); - /* Enable the USART Transmit Complete Interrupt */ + /* Enable the USART Transmit Complete Interrupt */ __HAL_USART_ENABLE_IT(husart, USART_IT_TC); } } @@ -1729,8 +1414,8 @@ static void USART_DMATransmitCplt(DMA_HandleTypeDef *hdma) } /** - * @brief DMA USART transmit process half complete callback - * @param hdma: pointer to a DMA_HandleTypeDef structure that contains + * @brief DMA USART transmit process half complete callback + * @param hdma: Pointer to a DMA_HandleTypeDef structure that contains * the configuration information for the specified DMA module. * @retval None */ @@ -1742,35 +1427,32 @@ static void USART_DMATxHalfCplt(DMA_HandleTypeDef *hdma) } /** - * @brief DMA USART receive process complete callback. - * @param hdma: DMA handle + * @brief DMA USART receive process complete callback. + * @param hdma: Pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. * @retval None */ static void USART_DMAReceiveCplt(DMA_HandleTypeDef *hdma) { USART_HandleTypeDef* husart = ( USART_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + /* DMA Normal mode */ - if(HAL_IS_BIT_CLR(hdma->Instance->CCR, DMA_CCR_CIRC)) + if ( HAL_IS_BIT_CLR(hdma->Instance->CCR, DMA_CCR_CIRC) ) { - husart->RxXferCount = 0x00U; - - /* Disable RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */ - CLEAR_BIT(husart->Instance->CR1, USART_CR1_PEIE); - CLEAR_BIT(husart->Instance->CR3, USART_CR3_EIE); - + husart->RxXferCount = 0; if(husart->State == HAL_USART_STATE_BUSY_RX) { - /* Disable the DMA transfer for the Transmit/Receiver requests by setting the DMAT/DMAR bit + /* Disable the DMA transfer for the receiver requests by setting the DMAR bit in the USART CR3 register */ CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAR); husart->State= HAL_USART_STATE_READY; HAL_USART_RxCpltCallback(husart); } - /* The USART state is HAL_USART_STATE_BUSY_TX_RX */ + /* the usart state is HAL_USART_STATE_BUSY_TX_RX*/ else { - /* Disable the DMA transfer for the Transmit/receiver requests by setting the DMAT/DMAR bit + /* Disable the DMA transfer for the Transmit/receiver requests by setting the DMAT/DMAR bit in the USART CR3 register */ CLEAR_BIT(husart->Instance->CR3, (USART_CR3_DMAT | USART_CR3_DMAR)); @@ -1785,7 +1467,7 @@ static void USART_DMAReceiveCplt(DMA_HandleTypeDef *hdma) { HAL_USART_RxCpltCallback(husart); } - /* The USART state is HAL_USART_STATE_BUSY_TX_RX */ + /* the usart state is HAL_USART_STATE_BUSY_TX_RX*/ else { HAL_USART_TxRxCpltCallback(husart); @@ -1794,8 +1476,8 @@ static void USART_DMAReceiveCplt(DMA_HandleTypeDef *hdma) } /** - * @brief DMA USART receive process half complete callback - * @param hdma: pointer to a DMA_HandleTypeDef structure that contains + * @brief DMA USART receive process half complete callback + * @param hdma: Pointer to a DMA_HandleTypeDef structure that contains * the configuration information for the specified DMA module. * @retval None */ @@ -1803,208 +1485,108 @@ static void USART_DMARxHalfCplt(DMA_HandleTypeDef *hdma) { USART_HandleTypeDef* husart = (USART_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent; - HAL_USART_RxHalfCpltCallback(husart); + HAL_USART_RxHalfCpltCallback(husart); } /** - * @brief DMA USART communication error callback. - * @param hdma: DMA handle + * @brief DMA USART communication error callback. + * @param hdma: Pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. * @retval None */ -static void USART_DMAError(DMA_HandleTypeDef *hdma) +static void USART_DMAError(DMA_HandleTypeDef *hdma) { - uint32_t dmarequest = 0x00U; USART_HandleTypeDef* husart = ( USART_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; - husart->RxXferCount = 0x00U; - husart->TxXferCount = 0x00U; - - /* Stop USART DMA Tx request if ongoing */ - dmarequest = HAL_IS_BIT_SET(husart->Instance->CR3, USART_CR3_DMAT); - if((husart->State == HAL_USART_STATE_BUSY_TX) && dmarequest) - { - USART_EndTxTransfer(husart); - } - - /* Stop USART DMA Rx request if ongoing */ - dmarequest = HAL_IS_BIT_SET(husart->Instance->CR3, USART_CR3_DMAR); - if((husart->State == HAL_USART_STATE_BUSY_RX) && dmarequest) - { - USART_EndRxTransfer(husart); - } + husart->RxXferCount = 0; + husart->TxXferCount = 0; husart->ErrorCode |= HAL_USART_ERROR_DMA; husart->State= HAL_USART_STATE_READY; - + HAL_USART_ErrorCallback(husart); } /** * @brief This function handles USART Communication Timeout. - * @param husart: pointer to a USART_HandleTypeDef structure that contains + * @param husart: Pointer to a USART_HandleTypeDef structure that contains * the configuration information for the specified USART module. * @param Flag: specifies the USART flag to check. * @param Status: The new Flag status (SET or RESET). - * @param Tickstart: Tick start value. - * @param Timeout: Timeout duration. + * @param Timeout: Timeout duration * @retval HAL status */ -static HAL_StatusTypeDef USART_WaitOnFlagUntilTimeout(USART_HandleTypeDef *husart, uint32_t Flag, FlagStatus Status, uint32_t Tickstart, uint32_t Timeout) +static HAL_StatusTypeDef USART_WaitOnFlagUntilTimeout(USART_HandleTypeDef *husart, uint32_t Flag, FlagStatus Status, uint32_t Timeout) { + uint32_t tickstart = 0; + + /* Get tick */ + tickstart = HAL_GetTick(); + /* Wait until flag is set */ - while((__HAL_USART_GET_FLAG(husart, Flag) ? SET : RESET) == Status) + if(Status == RESET) { - /* Check for the Timeout */ - if(Timeout != HAL_MAX_DELAY) + while(__HAL_USART_GET_FLAG(husart, Flag) == RESET) { - if((Timeout == 0U)||((HAL_GetTick() - Tickstart ) > Timeout)) + /* Check for the Timeout */ + if(Timeout != HAL_MAX_DELAY) { + if((Timeout == 0)||((HAL_GetTick() - tickstart ) > Timeout)) + { /* Disable TXE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts for the interrupt process */ __HAL_USART_DISABLE_IT(husart, USART_IT_TXE); __HAL_USART_DISABLE_IT(husart, USART_IT_RXNE); __HAL_USART_DISABLE_IT(husart, USART_IT_PE); __HAL_USART_DISABLE_IT(husart, USART_IT_ERR); - husart->State= HAL_USART_STATE_READY; + husart->State= HAL_USART_STATE_READY; - /* Process Unlocked */ - __HAL_UNLOCK(husart); + /* Process Unlocked */ + __HAL_UNLOCK(husart); - return HAL_TIMEOUT; + return HAL_TIMEOUT; + } } } } - return HAL_OK; -} - -/** - * @brief End ongoing Tx transfer on USART peripheral (following error detection or Transmit completion). - * @param husart: USART handle. - * @retval None - */ -static void USART_EndTxTransfer(USART_HandleTypeDef *husart) -{ - /* Disable TXEIE and TCIE interrupts */ - CLEAR_BIT(husart->Instance->CR1, (USART_CR1_TXEIE | USART_CR1_TCIE)); - - /* At end of Tx process, restore husart->State to Ready */ - husart->State = HAL_USART_STATE_READY; -} - -/** - * @brief End ongoing Rx transfer on USART peripheral (following error detection or Reception completion). - * @param husart: USART handle. - * @retval None - */ -static void USART_EndRxTransfer(USART_HandleTypeDef *husart) -{ - /* Disable RXNE, PE and ERR interrupts */ - CLEAR_BIT(husart->Instance->CR1, (USART_CR1_RXNEIE | USART_CR1_PEIE)); - CLEAR_BIT(husart->Instance->CR3, USART_CR3_EIE); - - /* At end of Rx process, restore husart->State to Ready */ - husart->State = HAL_USART_STATE_READY; -} - -/** - * @brief DMA USART communication abort callback, when initiated by HAL services on Error - * (To be called at end of DMA Abort procedure following error occurrence). - * @param hdma DMA handle. - * @retval None - */ -static void USART_DMAAbortOnError(DMA_HandleTypeDef *hdma) -{ - USART_HandleTypeDef* husart = ( USART_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; - husart->RxXferCount = 0x00U; - husart->TxXferCount = 0x00U; - - HAL_USART_ErrorCallback(husart); -} - -/** - * @brief DMA USART Tx communication abort callback, when initiated by user - * (To be called at end of DMA Tx Abort procedure following user abort request). - * @note When this callback is executed, User Abort complete call back is called only if no - * Abort still ongoing for Rx DMA Handle. - * @param hdma DMA handle. - * @retval None - */ -static void USART_DMATxAbortCallback(DMA_HandleTypeDef *hdma) -{ - USART_HandleTypeDef* husart = ( USART_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; - - husart->hdmatx->XferAbortCallback = NULL; - - /* Check if an Abort process is still ongoing */ - if(husart->hdmarx != NULL) + else { - if(husart->hdmarx->XferAbortCallback != NULL) + while(__HAL_USART_GET_FLAG(husart, Flag) != RESET) { - return; - } - } - - /* No Abort process still ongoing : All DMA channels are aborted, call user Abort Complete callback */ - husart->TxXferCount = 0x00U; - husart->RxXferCount = 0x00U; - - /* Reset errorCode */ - husart->ErrorCode = HAL_USART_ERROR_NONE; + /* Check for the Timeout */ + if(Timeout != HAL_MAX_DELAY) + { + if((Timeout == 0)||((HAL_GetTick() - tickstart ) > Timeout)) + { + /* Disable TXE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts for the interrupt process */ + __HAL_USART_DISABLE_IT(husart, USART_IT_TXE); + __HAL_USART_DISABLE_IT(husart, USART_IT_RXNE); + __HAL_USART_DISABLE_IT(husart, USART_IT_PE); + __HAL_USART_DISABLE_IT(husart, USART_IT_ERR); - /* Restore husart->State to Ready */ - husart->State = HAL_USART_STATE_READY; + husart->State= HAL_USART_STATE_READY; - /* Call user Abort complete callback */ - HAL_USART_AbortCpltCallback(husart); -} + /* Process Unlocked */ + __HAL_UNLOCK(husart); -/** - * @brief DMA USART Rx communication abort callback, when initiated by user - * (To be called at end of DMA Rx Abort procedure following user abort request). - * @note When this callback is executed, User Abort complete call back is called only if no - * Abort still ongoing for Tx DMA Handle. - * @param hdma DMA handle. - * @retval None - */ -static void USART_DMARxAbortCallback(DMA_HandleTypeDef *hdma) -{ - USART_HandleTypeDef* husart = ( USART_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; - - husart->hdmarx->XferAbortCallback = NULL; - - /* Check if an Abort process is still ongoing */ - if(husart->hdmatx != NULL) - { - if(husart->hdmatx->XferAbortCallback != NULL) - { - return; + return HAL_TIMEOUT; + } + } } } - - /* No Abort process still ongoing : All DMA channels are aborted, call user Abort Complete callback */ - husart->TxXferCount = 0x00U; - husart->RxXferCount = 0x00U; - - /* Reset errorCode */ - husart->ErrorCode = HAL_USART_ERROR_NONE; - - /* Restore husart->State to Ready */ - husart->State = HAL_USART_STATE_READY; - - /* Call user Abort complete callback */ - HAL_USART_AbortCpltCallback(husart); + return HAL_OK; } /** - * @brief Simplex Send an amount of data in non-blocking mode. - * @param husart: pointer to a USART_HandleTypeDef structure that contains + * @brief Simplex Send an amount of data in non-blocking mode. + * @param husart: Pointer to a USART_HandleTypeDef structure that contains * the configuration information for the specified USART module. * @retval HAL status * @note The USART errors are not managed to avoid the overrun error. */ static HAL_StatusTypeDef USART_Transmit_IT(USART_HandleTypeDef *husart) { - uint16_t* tmp; - + uint16_t* tmp=0; + if(husart->State == HAL_USART_STATE_BUSY_TX) { if(husart->Init.WordLength == USART_WORDLENGTH_9B) @@ -2013,24 +1595,24 @@ static HAL_StatusTypeDef USART_Transmit_IT(USART_HandleTypeDef *husart) WRITE_REG(husart->Instance->DR, (uint16_t)(*tmp & (uint16_t)0x01FF)); if(husart->Init.Parity == USART_PARITY_NONE) { - husart->pTxBuffPtr += 2U; + husart->pTxBuffPtr += 2; } else { - husart->pTxBuffPtr += 1U; + husart->pTxBuffPtr += 1; } - } + } else - { + { WRITE_REG(husart->Instance->DR, (uint8_t)(*husart->pTxBuffPtr++ & (uint8_t)0x00FF)); } - - if(--husart->TxXferCount == 0U) + + if(--husart->TxXferCount == 0) { /* Disable the USART Transmit data register empty Interrupt */ __HAL_USART_DISABLE_IT(husart, USART_IT_TXE); - /* Enable the USART Transmit Complete Interrupt */ + /* Enable the USART Transmit Complete Interrupt */ __HAL_USART_ENABLE_IT(husart, USART_IT_TC); } return HAL_OK; @@ -2041,6 +1623,7 @@ static HAL_StatusTypeDef USART_Transmit_IT(USART_HandleTypeDef *husart) } } + /** * @brief Wraps up transmission in non blocking mode. * @param husart: pointer to a USART_HandleTypeDef structure that contains @@ -2049,28 +1632,29 @@ static HAL_StatusTypeDef USART_Transmit_IT(USART_HandleTypeDef *husart) */ static HAL_StatusTypeDef USART_EndTransmit_IT(USART_HandleTypeDef *husart) { - /* Disable the USART Transmit Complete Interrupt */ + /* Disable the USART Transmit Complete Interrupt */ __HAL_USART_DISABLE_IT(husart, USART_IT_TC); - + /* Disable the USART Error Interrupt: (Frame error, noise error, overrun error) */ __HAL_USART_DISABLE_IT(husart, USART_IT_ERR); - + husart->State = HAL_USART_STATE_READY; - + HAL_USART_TxCpltCallback(husart); - + return HAL_OK; } + /** - * @brief Simplex Receive an amount of data in non-blocking mode. - * @param husart: pointer to a USART_HandleTypeDef structure that contains + * @brief Simplex Receive an amount of data in non-blocking mode. + * @param husart: Pointer to a USART_HandleTypeDef structure that contains * the configuration information for the specified USART module. * @retval HAL status */ static HAL_StatusTypeDef USART_Receive_IT(USART_HandleTypeDef *husart) { - uint16_t* tmp; + uint16_t* tmp=0; if(husart->State == HAL_USART_STATE_BUSY_RX) { if(husart->Init.WordLength == USART_WORDLENGTH_9B) @@ -2079,19 +1663,19 @@ static HAL_StatusTypeDef USART_Receive_IT(USART_HandleTypeDef *husart) if(husart->Init.Parity == USART_PARITY_NONE) { *tmp = (uint16_t)(husart->Instance->DR & (uint16_t)0x01FF); - husart->pRxBuffPtr += 2U; + husart->pRxBuffPtr += 2; } else { *tmp = (uint16_t)(husart->Instance->DR & (uint16_t)0x00FF); - husart->pRxBuffPtr += 1U; + husart->pRxBuffPtr += 1; } - if(--husart->RxXferCount != 0x00U) + if(--husart->RxXferCount != 0x00) { /* Send dummy byte in order to generate the clock for the slave to send the next data */ WRITE_REG(husart->Instance->DR, (DUMMY_DATA & (uint16_t)0x01FF)); } - } + } else { if(husart->Init.Parity == USART_PARITY_NONE) @@ -2103,50 +1687,50 @@ static HAL_StatusTypeDef USART_Receive_IT(USART_HandleTypeDef *husart) *husart->pRxBuffPtr++ = (uint8_t)(husart->Instance->DR & (uint8_t)0x007F); } - if(--husart->RxXferCount != 0x00U) + if(--husart->RxXferCount != 0x00) { /* Send dummy byte in order to generate the clock for the slave to send the next data */ WRITE_REG(husart->Instance->DR, (DUMMY_DATA & (uint16_t)0x00FF)); } } - if(husart->RxXferCount == 0U) + if(husart->RxXferCount == 0) { /* Disable the USART RXNE Interrupt */ - CLEAR_BIT(husart->Instance->CR1, USART_CR1_RXNEIE); + __HAL_USART_DISABLE_IT(husart, USART_IT_RXNE); /* Disable the USART Parity Error Interrupt */ - CLEAR_BIT(husart->Instance->CR1, USART_CR1_PEIE); + __HAL_USART_DISABLE_IT(husart, USART_IT_PE); /* Disable the USART Error Interrupt: (Frame error, noise error, overrun error) */ - CLEAR_BIT(husart->Instance->CR3, USART_CR3_EIE); + __HAL_USART_DISABLE_IT(husart, USART_IT_ERR); husart->State = HAL_USART_STATE_READY; HAL_USART_RxCpltCallback(husart); - + return HAL_OK; } return HAL_OK; } else { - return HAL_BUSY; + return HAL_BUSY; } } /** - * @brief Full-Duplex Send receive an amount of data in full-duplex mode (non-blocking). - * @param husart: pointer to a USART_HandleTypeDef structure that contains + * @brief Full-Duplex Send receive an amount of data in full-duplex mode (non-blocking). + * @param husart: Pointer to a USART_HandleTypeDef structure that contains * the configuration information for the specified USART module. * @retval HAL status */ static HAL_StatusTypeDef USART_TransmitReceive_IT(USART_HandleTypeDef *husart) { - uint16_t* tmp; + uint16_t* tmp=0; if(husart->State == HAL_USART_STATE_BUSY_TX_RX) { - if(husart->TxXferCount != 0x00U) + if(husart->TxXferCount != 0x00) { if(__HAL_USART_GET_FLAG(husart, USART_FLAG_TXE) != RESET) { @@ -2156,13 +1740,13 @@ static HAL_StatusTypeDef USART_TransmitReceive_IT(USART_HandleTypeDef *husart) WRITE_REG(husart->Instance->DR, (uint16_t)(*tmp & (uint16_t)0x01FF)); if(husart->Init.Parity == USART_PARITY_NONE) { - husart->pTxBuffPtr += 2U; + husart->pTxBuffPtr += 2; } else { - husart->pTxBuffPtr += 1U; + husart->pTxBuffPtr += 1; } - } + } else { WRITE_REG(husart->Instance->DR, (uint8_t)(*husart->pTxBuffPtr++ & (uint8_t)0x00FF)); @@ -2170,14 +1754,14 @@ static HAL_StatusTypeDef USART_TransmitReceive_IT(USART_HandleTypeDef *husart) husart->TxXferCount--; /* Check the latest data transmitted */ - if(husart->TxXferCount == 0U) + if(husart->TxXferCount == 0) { - CLEAR_BIT(husart->Instance->CR1, USART_CR1_TXEIE); + __HAL_USART_DISABLE_IT(husart, USART_IT_TXE); } } } - if(husart->RxXferCount != 0x00U) + if(husart->RxXferCount != 0x00) { if(__HAL_USART_GET_FLAG(husart, USART_FLAG_RXNE) != RESET) { @@ -2187,14 +1771,14 @@ static HAL_StatusTypeDef USART_TransmitReceive_IT(USART_HandleTypeDef *husart) if(husart->Init.Parity == USART_PARITY_NONE) { *tmp = (uint16_t)(husart->Instance->DR & (uint16_t)0x01FF); - husart->pRxBuffPtr += 2U; + husart->pRxBuffPtr += 2; } else { *tmp = (uint16_t)(husart->Instance->DR & (uint16_t)0x00FF); - husart->pRxBuffPtr += 1U; + husart->pRxBuffPtr += 1; } - } + } else { if(husart->Init.Parity == USART_PARITY_NONE) @@ -2211,16 +1795,15 @@ static HAL_StatusTypeDef USART_TransmitReceive_IT(USART_HandleTypeDef *husart) } /* Check the latest data received */ - if(husart->RxXferCount == 0U) + if(husart->RxXferCount == 0) { - /* Disable the USART RXNE Interrupt */ - CLEAR_BIT(husart->Instance->CR1, USART_CR1_RXNEIE); + __HAL_USART_DISABLE_IT(husart, USART_IT_RXNE); /* Disable the USART Parity Error Interrupt */ - CLEAR_BIT(husart->Instance->CR1, USART_CR1_PEIE); + __HAL_USART_DISABLE_IT(husart, USART_IT_PE); /* Disable the USART Error Interrupt: (Frame error, noise error, overrun error) */ - CLEAR_BIT(husart->Instance->CR3, USART_CR3_EIE); + __HAL_USART_DISABLE_IT(husart, USART_IT_ERR); husart->State = HAL_USART_STATE_READY; @@ -2233,13 +1816,13 @@ static HAL_StatusTypeDef USART_TransmitReceive_IT(USART_HandleTypeDef *husart) } else { - return HAL_BUSY; + return HAL_BUSY; } } /** - * @brief Configures the USART pferipheral. - * @param husart: pointer to a USART_HandleTypeDef structure that contains + * @brief Configures the USART peripheral. + * @param husart: Pointer to a USART_HandleTypeDef structure that contains * the configuration information for the specified USART module. * @retval None */ diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_usart.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_usart.h index f88eb86fd54..6ba4f6a86f9 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_usart.h +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_usart.h @@ -2,13 +2,13 @@ ****************************************************************************** * @file stm32f1xx_hal_usart.h * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief Header file of USART HAL module. ****************************************************************************** * @attention * - *

© COPYRIGHT(c) 2017 STMicroelectronics

+ *

© COPYRIGHT(c) 2016 STMicroelectronics

* * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: @@ -33,7 +33,7 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** - */ + */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F1xx_HAL_USART_H @@ -52,16 +52,17 @@ /** @addtogroup USART * @{ - */ + */ /* Exported types ------------------------------------------------------------*/ /** @defgroup USART_Exported_Types USART Exported Types * @{ - */ + */ -/** + +/** * @brief USART Init Structure definition - */ + */ typedef struct { uint32_t BaudRate; /*!< This member configures the Usart communication baud rate. @@ -75,14 +76,14 @@ typedef struct uint32_t StopBits; /*!< Specifies the number of stop bits transmitted. This parameter can be a value of @ref USART_Stop_Bits */ - uint32_t Parity; /*!< Specifies the parity mode. + uint32_t Parity; /*!< Specifies the parity mode. This parameter can be a value of @ref USART_Parity @note When parity is enabled, the computed parity is inserted at the MSB position of the transmitted data (9th bit when the word length is set to 9 data bits; 8th bit when the word length is set to 8 data bits). */ - - uint32_t Mode; /*!< Specifies whether the Receive or Transmit mode is enabled or disabled. + + uint32_t Mode; /*!< Specifies wether the Receive or Transmit mode is enabled or disabled. This parameter can be a value of @ref USART_Mode */ uint32_t CLKPolarity; /*!< Specifies the steady state of the serial clock. @@ -101,66 +102,68 @@ typedef struct */ typedef enum { - HAL_USART_STATE_RESET = 0x00U, /*!< Peripheral is not yet initialized */ - HAL_USART_STATE_READY = 0x01U, /*!< Peripheral Initialized and ready for use */ - HAL_USART_STATE_BUSY = 0x02U, /*!< an internal process is ongoing */ - HAL_USART_STATE_BUSY_TX = 0x12U, /*!< Data Transmission process is ongoing */ - HAL_USART_STATE_BUSY_RX = 0x22U, /*!< Data Reception process is ongoing */ - HAL_USART_STATE_BUSY_TX_RX = 0x32U, /*!< Data Transmission Reception process is ongoing */ - HAL_USART_STATE_TIMEOUT = 0x03U, /*!< Timeout state */ - HAL_USART_STATE_ERROR = 0x04U /*!< Error */ + HAL_USART_STATE_RESET = 0x00, /*!< Peripheral is not initialized */ + HAL_USART_STATE_READY = 0x01, /*!< Peripheral Initialized and ready for use */ + HAL_USART_STATE_BUSY = 0x02, /*!< an internal process is ongoing */ + HAL_USART_STATE_BUSY_TX = 0x12, /*!< Data Transmission process is ongoing */ + HAL_USART_STATE_BUSY_RX = 0x22, /*!< Data Reception process is ongoing */ + HAL_USART_STATE_BUSY_TX_RX = 0x32, /*!< Data Transmission Reception process is ongoing */ + HAL_USART_STATE_TIMEOUT = 0x03, /*!< Timeout state */ + HAL_USART_STATE_ERROR = 0x04 /*!< Error */ }HAL_USART_StateTypeDef; + /** * @brief USART handle Structure definition */ typedef struct { USART_TypeDef *Instance; /*!< USART registers base address */ - - USART_InitTypeDef Init; /*!< Usart communication parameters */ - + + USART_InitTypeDef Init; /*!< Usart communication parameters */ + uint8_t *pTxBuffPtr; /*!< Pointer to Usart Tx transfer Buffer */ - - uint16_t TxXferSize; /*!< Usart Tx Transfer size */ - - __IO uint16_t TxXferCount; /*!< Usart Tx Transfer Counter */ - + + uint16_t TxXferSize; /*!< Usart Tx Transfer size */ + + __IO uint16_t TxXferCount; /*!< Usart Tx Transfer Counter */ + uint8_t *pRxBuffPtr; /*!< Pointer to Usart Rx transfer Buffer */ - - uint16_t RxXferSize; /*!< Usart Rx Transfer size */ - - __IO uint16_t RxXferCount; /*!< Usart Rx Transfer Counter */ - + + uint16_t RxXferSize; /*!< Usart Rx Transfer size */ + + __IO uint16_t RxXferCount; /*!< Usart Rx Transfer Counter */ + DMA_HandleTypeDef *hdmatx; /*!< Usart Tx DMA Handle parameters */ - + DMA_HandleTypeDef *hdmarx; /*!< Usart Rx DMA Handle parameters */ - - HAL_LockTypeDef Lock; /*!< Locking object */ - __IO HAL_USART_StateTypeDef State; /*!< Usart communication state */ + HAL_LockTypeDef Lock; /*!< Locking object */ + + __IO HAL_USART_StateTypeDef State; /*!< Usart communication state */ + + __IO uint32_t ErrorCode; /*!< USART Error code */ - __IO uint32_t ErrorCode; /*!< USART Error code */ }USART_HandleTypeDef; + /** * @} */ /* Exported constants --------------------------------------------------------*/ -/** @defgroup USART_Exported_Constants USART Exported Constants +/** @defgroup USART_Exported_Constants USART Exported constants * @{ */ -/** @defgroup USART_Error_Code USART Error Code - * @brief USART Error Code +/** @defgroup USART_Error_Codes USART Error Codes * @{ */ -#define HAL_USART_ERROR_NONE 0x00000000U /*!< No error */ -#define HAL_USART_ERROR_PE 0x00000001U /*!< Parity error */ -#define HAL_USART_ERROR_NE 0x00000002U /*!< Noise error */ -#define HAL_USART_ERROR_FE 0x00000004U /*!< Frame error */ -#define HAL_USART_ERROR_ORE 0x00000008U /*!< Overrun error */ -#define HAL_USART_ERROR_DMA 0x00000010U /*!< DMA transfer error */ +#define HAL_USART_ERROR_NONE ((uint32_t)0x00) /*!< No error */ +#define HAL_USART_ERROR_PE ((uint32_t)0x01) /*!< Parity error */ +#define HAL_USART_ERROR_NE ((uint32_t)0x02) /*!< Noise error */ +#define HAL_USART_ERROR_FE ((uint32_t)0x04) /*!< frame error */ +#define HAL_USART_ERROR_ORE ((uint32_t)0x08) /*!< Overrun error */ +#define HAL_USART_ERROR_DMA ((uint32_t)0x10) /*!< DMA transfer error */ /** * @} */ @@ -168,8 +171,8 @@ typedef struct /** @defgroup USART_Word_Length USART Word Length * @{ */ -#define USART_WORDLENGTH_8B 0x00000000U -#define USART_WORDLENGTH_9B ((uint32_t)USART_CR1_M) +#define USART_WORDLENGTH_8B ((uint32_t)0x00000000) +#define USART_WORDLENGTH_9B ((uint32_t)USART_CR1_M) /** * @} */ @@ -177,10 +180,10 @@ typedef struct /** @defgroup USART_Stop_Bits USART Number of Stop Bits * @{ */ -#define USART_STOPBITS_1 0x00000000U -#define USART_STOPBITS_0_5 ((uint32_t)USART_CR2_STOP_0) -#define USART_STOPBITS_2 ((uint32_t)USART_CR2_STOP_1) -#define USART_STOPBITS_1_5 ((uint32_t)(USART_CR2_STOP_0 | USART_CR2_STOP_1)) +#define USART_STOPBITS_1 ((uint32_t)0x00000000) +#define USART_STOPBITS_0_5 ((uint32_t)USART_CR2_STOP_0) +#define USART_STOPBITS_2 ((uint32_t)USART_CR2_STOP_1) +#define USART_STOPBITS_1_5 ((uint32_t)(USART_CR2_STOP_0 | USART_CR2_STOP_1)) /** * @} */ @@ -188,9 +191,9 @@ typedef struct /** @defgroup USART_Parity USART Parity * @{ */ -#define USART_PARITY_NONE 0x00000000U -#define USART_PARITY_EVEN ((uint32_t)USART_CR1_PCE) -#define USART_PARITY_ODD ((uint32_t)(USART_CR1_PCE | USART_CR1_PS)) +#define USART_PARITY_NONE ((uint32_t)0x00000000) +#define USART_PARITY_EVEN ((uint32_t)USART_CR1_PCE) +#define USART_PARITY_ODD ((uint32_t)(USART_CR1_PCE | USART_CR1_PS)) /** * @} */ @@ -198,9 +201,10 @@ typedef struct /** @defgroup USART_Mode USART Mode * @{ */ -#define USART_MODE_RX ((uint32_t)USART_CR1_RE) -#define USART_MODE_TX ((uint32_t)USART_CR1_TE) -#define USART_MODE_TX_RX ((uint32_t)(USART_CR1_TE |USART_CR1_RE)) +#define USART_MODE_RX ((uint32_t)USART_CR1_RE) +#define USART_MODE_TX ((uint32_t)USART_CR1_TE) +#define USART_MODE_TX_RX ((uint32_t)(USART_CR1_TE |USART_CR1_RE)) + /** * @} */ @@ -208,8 +212,8 @@ typedef struct /** @defgroup USART_Clock USART Clock * @{ */ -#define USART_CLOCK_DISABLE 0x00000000U -#define USART_CLOCK_ENABLE ((uint32_t)USART_CR2_CLKEN) +#define USART_CLOCK_DISABLE ((uint32_t)0x00000000) +#define USART_CLOCK_ENABLE ((uint32_t)USART_CR2_CLKEN) /** * @} */ @@ -217,8 +221,8 @@ typedef struct /** @defgroup USART_Clock_Polarity USART Clock Polarity * @{ */ -#define USART_POLARITY_LOW 0x00000000U -#define USART_POLARITY_HIGH ((uint32_t)USART_CR2_CPOL) +#define USART_POLARITY_LOW ((uint32_t)0x00000000) +#define USART_POLARITY_HIGH ((uint32_t)USART_CR2_CPOL) /** * @} */ @@ -226,8 +230,8 @@ typedef struct /** @defgroup USART_Clock_Phase USART Clock Phase * @{ */ -#define USART_PHASE_1EDGE 0x00000000U -#define USART_PHASE_2EDGE ((uint32_t)USART_CR2_CPHA) +#define USART_PHASE_1EDGE ((uint32_t)0x00000000) +#define USART_PHASE_2EDGE ((uint32_t)USART_CR2_CPHA) /** * @} */ @@ -235,8 +239,8 @@ typedef struct /** @defgroup USART_Last_Bit USART Last Bit * @{ */ -#define USART_LASTBIT_DISABLE 0x00000000U -#define USART_LASTBIT_ENABLE ((uint32_t)USART_CR2_LBCL) +#define USART_LASTBIT_DISABLE ((uint32_t)0x00000000) +#define USART_LASTBIT_ENABLE ((uint32_t)USART_CR2_LBCL) /** * @} */ @@ -244,8 +248,8 @@ typedef struct /** @defgroup USART_NACK_State USART NACK State * @{ */ -#define USART_NACK_ENABLE ((uint32_t)USART_CR3_NACK) -#define USART_NACK_DISABLE 0x00000000U +#define USART_NACK_ENABLE ((uint32_t)USART_CR3_NACK) +#define USART_NACK_DISABLE ((uint32_t)0x00000000) /** * @} */ @@ -255,6 +259,9 @@ typedef struct * - 0xXXXX : Flag mask in the SR register * @{ */ + +#define USART_FLAG_CTS ((uint32_t)USART_SR_CTS) +#define USART_FLAG_LBD ((uint32_t)USART_SR_LBD) #define USART_FLAG_TXE ((uint32_t)USART_SR_TXE) #define USART_FLAG_TC ((uint32_t)USART_SR_TC) #define USART_FLAG_RXNE ((uint32_t)USART_SR_RXNE) @@ -269,25 +276,27 @@ typedef struct /** @defgroup USART_Interrupt_definition USART Interrupts Definition * Elements values convention: 0xY000XXXX - * - XXXX : Interrupt mask in the XX register - * - Y : Interrupt source register (2bits) - * - 01: CR1 register - * - 10: CR2 register - * - 11: CR3 register + * - XXXX : Interrupt mask (16 bits) in the Y register + * - Y : Interrupt source register (4bits) + * - 0001: CR1 register + * - 0010: CR2 register + * - 0011: CR3 register * * @{ */ -#define USART_IT_PE ((uint32_t)(USART_CR1_REG_INDEX << 28U | USART_CR1_PEIE)) -#define USART_IT_TXE ((uint32_t)(USART_CR1_REG_INDEX << 28U | USART_CR1_TXEIE)) -#define USART_IT_TC ((uint32_t)(USART_CR1_REG_INDEX << 28U | USART_CR1_TCIE)) -#define USART_IT_RXNE ((uint32_t)(USART_CR1_REG_INDEX << 28U | USART_CR1_RXNEIE)) -#define USART_IT_IDLE ((uint32_t)(USART_CR1_REG_INDEX << 28U | USART_CR1_IDLEIE)) +#define USART_IT_PE ((uint32_t)(USART_CR1_REG_INDEX << 28 | USART_CR1_PEIE)) +#define USART_IT_TXE ((uint32_t)(USART_CR1_REG_INDEX << 28 | USART_CR1_TXEIE)) +#define USART_IT_TC ((uint32_t)(USART_CR1_REG_INDEX << 28 | USART_CR1_TCIE)) +#define USART_IT_RXNE ((uint32_t)(USART_CR1_REG_INDEX << 28 | USART_CR1_RXNEIE)) +#define USART_IT_IDLE ((uint32_t)(USART_CR1_REG_INDEX << 28 | USART_CR1_IDLEIE)) + +#define USART_IT_LBD ((uint32_t)(USART_CR2_REG_INDEX << 28 | USART_CR2_LBDIE)) + +#define USART_IT_CTS ((uint32_t)(USART_CR3_REG_INDEX << 28 | USART_CR3_CTSIE)) +#define USART_IT_ERR ((uint32_t)(USART_CR3_REG_INDEX << 28 | USART_CR3_EIE)) -#define USART_IT_LBD ((uint32_t)(USART_CR2_REG_INDEX << 28U | USART_CR2_LBDIE)) -#define USART_IT_CTS ((uint32_t)(USART_CR3_REG_INDEX << 28U | USART_CR3_CTSIE)) -#define USART_IT_ERR ((uint32_t)(USART_CR3_REG_INDEX << 28U | USART_CR3_EIE)) /** * @} */ @@ -296,18 +305,21 @@ typedef struct * @} */ + /* Exported macro ------------------------------------------------------------*/ /** @defgroup USART_Exported_Macros USART Exported Macros * @{ */ + /** @brief Reset USART handle state * @param __HANDLE__: specifies the USART Handle. * USART Handle selects the USARTx peripheral (USART availability and x value depending on device). + * @retval None */ #define __HAL_USART_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_USART_STATE_RESET) -/** @brief Checks whether the specified USART flag is set or not. +/** @brief Check whether the specified USART flag is set or not. * @param __HANDLE__: specifies the USART Handle. * USART Handle selects the USARTx peripheral (USART availability and x value depending on device). * @param __FLAG__: specifies the flag to check. @@ -322,9 +334,10 @@ typedef struct * @arg USART_FLAG_PE: Parity Error flag * @retval The new state of __FLAG__ (TRUE or FALSE). */ + #define __HAL_USART_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->SR & (__FLAG__)) == (__FLAG__)) -/** @brief Clears the specified USART pending flags. +/** @brief Clear the specified USART pending flags. * @param __HANDLE__: specifies the USART Handle. * USART Handle selects the USARTx peripheral (USART availability and x value depending on device). * @param __FLAG__: specifies the flag to check. @@ -332,56 +345,62 @@ typedef struct * @arg USART_FLAG_TC: Transmission Complete flag. * @arg USART_FLAG_RXNE: Receive data register not empty flag. * - * @note PE (Parity error), FE (Framing error), NE (Noise error), ORE (OverRun - * error) and IDLE (Idle line detected) flags are cleared by software + * @note PE (Parity error), FE (Framing error), NE (Noise error), ORE (OverRun + * error) and IDLE (Idle line detected) flags are cleared by software * sequence: a read operation to USART_SR register followed by a read * operation to USART_DR register. * @note RXNE flag can be also cleared by a read to the USART_DR register. - * @note TC flag can be also cleared by software sequence: a read operation to - * USART_SR register followed by a write operation to USART_DR register - * @note TXE flag is cleared only by a write to the USART_DR register + * @note TC flag can be also cleared by software sequence: a read operation to + * USART_SR register followed by a write operation to USART_DR register. + * @note TXE flag is cleared only by a write to the USART_DR register. * + * @retval None */ -#define __HAL_USART_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->SR = ~(__FLAG__)) +#define __HAL_USART_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->SR = ~(__FLAG__)) /** @brief Clear the USART PE pending flag. * @param __HANDLE__: specifies the USART Handle. * USART Handle selects the USARTx peripheral (USART availability and x value depending on device). + * @retval None */ -#define __HAL_USART_CLEAR_PEFLAG(__HANDLE__) \ - do{ \ - __IO uint32_t tmpreg = 0x00U; \ - tmpreg = (__HANDLE__)->Instance->SR; \ - tmpreg = (__HANDLE__)->Instance->DR; \ - UNUSED(tmpreg); \ - } while(0U) +#define __HAL_USART_CLEAR_PEFLAG(__HANDLE__) \ +do{ \ + __IO uint32_t tmpreg; \ + tmpreg = (__HANDLE__)->Instance->SR; \ + tmpreg = (__HANDLE__)->Instance->DR; \ + UNUSED(tmpreg); \ +}while(0) + /** @brief Clear the USART FE pending flag. * @param __HANDLE__: specifies the USART Handle. * USART Handle selects the USARTx peripheral (USART availability and x value depending on device). + * @retval None */ #define __HAL_USART_CLEAR_FEFLAG(__HANDLE__) __HAL_USART_CLEAR_PEFLAG(__HANDLE__) /** @brief Clear the USART NE pending flag. * @param __HANDLE__: specifies the USART Handle. * USART Handle selects the USARTx peripheral (USART availability and x value depending on device). + * @retval None */ #define __HAL_USART_CLEAR_NEFLAG(__HANDLE__) __HAL_USART_CLEAR_PEFLAG(__HANDLE__) /** @brief Clear the USART ORE pending flag. * @param __HANDLE__: specifies the USART Handle. * USART Handle selects the USARTx peripheral (USART availability and x value depending on device). - + * @retval None */ #define __HAL_USART_CLEAR_OREFLAG(__HANDLE__) __HAL_USART_CLEAR_PEFLAG(__HANDLE__) /** @brief Clear the USART IDLE pending flag. * @param __HANDLE__: specifies the USART Handle. * USART Handle selects the USARTx peripheral (USART availability and x value depending on device). + * @retval None */ #define __HAL_USART_CLEAR_IDLEFLAG(__HANDLE__) __HAL_USART_CLEAR_PEFLAG(__HANDLE__) -/** @brief Enable the specified USART interrupts. +/** @brief Enable the specified Usart interrupts. * @param __HANDLE__: specifies the USART Handle. * USART Handle selects the USARTx peripheral (USART availability and x value depending on device). * @param __INTERRUPT__: specifies the USART interrupt source to enable. @@ -392,13 +411,14 @@ typedef struct * @arg USART_IT_IDLE: Idle line detection interrupt * @arg USART_IT_PE: Parity Error interrupt * @arg USART_IT_ERR: Error interrupt(Frame error, noise error, overrun error) - * This parameter can be: ENABLE or DISABLE. + * @retval None */ -#define __HAL_USART_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((((__INTERRUPT__) >> 28U) == USART_CR1_REG_INDEX)? ((__HANDLE__)->Instance->CR1 |= ((__INTERRUPT__) & USART_IT_MASK)): \ - (((__INTERRUPT__) >> 28U) == USART_CR2_REG_INDEX)? ((__HANDLE__)->Instance->CR2 |= ((__INTERRUPT__) & USART_IT_MASK)): \ +#define __HAL_USART_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((((__INTERRUPT__) >> 28) == USART_CR1_REG_INDEX)? ((__HANDLE__)->Instance->CR1 |= ((__INTERRUPT__) & USART_IT_MASK)): \ + (((__INTERRUPT__) >> 28) == USART_CR2_REG_INDEX)? ((__HANDLE__)->Instance->CR2 |= ((__INTERRUPT__) & USART_IT_MASK)): \ ((__HANDLE__)->Instance->CR3 |= ((__INTERRUPT__) & USART_IT_MASK))) -/** @brief Disable the specified USART interrupts. + +/** @brief Disable the specified Usart interrupts. * @param __HANDLE__: specifies the USART Handle. * USART Handle selects the USARTx peripheral (USART availability and x value depending on device). * @param __INTERRUPT__: specifies the USART interrupt source to disable. @@ -409,13 +429,15 @@ typedef struct * @arg USART_IT_IDLE: Idle line detection interrupt * @arg USART_IT_PE: Parity Error interrupt * @arg USART_IT_ERR: Error interrupt(Frame error, noise error, overrun error) - * This parameter can be: ENABLE or DISABLE. + * @retval None */ -#define __HAL_USART_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((((__INTERRUPT__) >> 28U) == USART_CR1_REG_INDEX)? ((__HANDLE__)->Instance->CR1 &= ~((__INTERRUPT__) & USART_IT_MASK)): \ - (((__INTERRUPT__) >> 28U) == USART_CR2_REG_INDEX)? ((__HANDLE__)->Instance->CR2 &= ~((__INTERRUPT__) & USART_IT_MASK)): \ - ((__HANDLE__)->Instance->CR3 &= ~ ((__INTERRUPT__) & USART_IT_MASK))) +#define __HAL_USART_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((((__INTERRUPT__) >> 28) == USART_CR1_REG_INDEX)? ((__HANDLE__)->Instance->CR1 &= ~((__INTERRUPT__) & USART_IT_MASK)): \ + (((__INTERRUPT__) >> 28) == USART_CR2_REG_INDEX)? ((__HANDLE__)->Instance->CR2 &= ~((__INTERRUPT__) & USART_IT_MASK)): \ + ((__HANDLE__)->Instance->CR3 &= ~ ((__INTERRUPT__) & USART_IT_MASK))) -/** @brief Checks whether the specified USART interrupt has occurred or not. + + +/** @brief Check whether the specified Usart interrupt has occurred or not. * @param __HANDLE__: specifies the USART Handle. * USART Handle selects the USARTx peripheral (USART availability and x value depending on device). * @param __IT__: specifies the USART interrupt source to check. @@ -428,43 +450,113 @@ typedef struct * @arg USART_IT_PE: Parity Error interrupt * @retval The new state of __IT__ (TRUE or FALSE). */ -#define __HAL_USART_GET_IT_SOURCE(__HANDLE__, __IT__) (((((__IT__) >> 28U) == USART_CR1_REG_INDEX)? (__HANDLE__)->Instance->CR1:(((((uint32_t)(__IT__)) >> 28U) == USART_CR2_REG_INDEX)? \ +#define __HAL_USART_GET_IT_SOURCE(__HANDLE__, __IT__) (((((__IT__) >> 28) == USART_CR1_REG_INDEX)? (__HANDLE__)->Instance->CR1:(((((uint32_t)(__IT__)) >> 28) == USART_CR2_REG_INDEX)? \ (__HANDLE__)->Instance->CR2 : (__HANDLE__)->Instance->CR3)) & (((uint32_t)(__IT__)) & USART_IT_MASK)) /** @brief Enable USART * @param __HANDLE__: specifies the USART Handle. * USART Handle selects the USARTx peripheral (USART availability and x value depending on device). - */ + * @retval None + */ #define __HAL_USART_ENABLE(__HANDLE__) SET_BIT((__HANDLE__)->Instance->CR1,(USART_CR1_UE)) /** @brief Disable USART * @param __HANDLE__: specifies the USART Handle. * USART Handle selects the USARTx peripheral (USART availability and x value depending on device). + * @retval None */ #define __HAL_USART_DISABLE(__HANDLE__) CLEAR_BIT((__HANDLE__)->Instance->CR1,(USART_CR1_UE)) + + /** * @} */ -/* Exported functions --------------------------------------------------------*/ -/** @addtogroup USART_Exported_Functions + + +/* Private macros --------------------------------------------------------*/ +/** @defgroup USART_Private_Macros USART Private Macros * @{ */ -/** @addtogroup USART_Exported_Functions_Group1 +#define USART_CR1_REG_INDEX 1 +#define USART_CR2_REG_INDEX 2 +#define USART_CR3_REG_INDEX 3 + +#define USART_DIV(__PCLK__, __BAUD__) (((__PCLK__)*25)/(4*(__BAUD__))) +#define USART_DIVMANT(__PCLK__, __BAUD__) (USART_DIV((__PCLK__), (__BAUD__))/100) +#define USART_DIVFRAQ(__PCLK__, __BAUD__) (((USART_DIV((__PCLK__), (__BAUD__)) - (USART_DIVMANT((__PCLK__), (__BAUD__)) * 100)) * 16 + 50) / 100) +#define USART_BRR(__PCLK__, __BAUD__) ((USART_DIVMANT((__PCLK__), (__BAUD__)) << 4)|(USART_DIVFRAQ((__PCLK__), (__BAUD__)) & 0x0F)) + +/** Check USART Baud rate + * __BAUDRATE__: Baudrate specified by the user + * The maximum Baud Rate is derived from the maximum clock on APB (i.e. 72 MHz) + * divided by the smallest oversampling used on the USART (i.e. 16) + * return : TRUE or FALSE + */ +#define IS_USART_BAUDRATE(__BAUDRATE__) ((__BAUDRATE__) < 4500001) + +#define IS_USART_WORD_LENGTH(LENGTH) (((LENGTH) == USART_WORDLENGTH_8B) || \ + ((LENGTH) == USART_WORDLENGTH_9B)) + +#define IS_USART_STOPBITS(STOPBITS) (((STOPBITS) == USART_STOPBITS_1) || \ + ((STOPBITS) == USART_STOPBITS_0_5) || \ + ((STOPBITS) == USART_STOPBITS_1_5) || \ + ((STOPBITS) == USART_STOPBITS_2)) + +#define IS_USART_PARITY(PARITY) (((PARITY) == USART_PARITY_NONE) || \ + ((PARITY) == USART_PARITY_EVEN) || \ + ((PARITY) == USART_PARITY_ODD)) + +#define IS_USART_MODE(MODE) ((((MODE) & (~((uint32_t)USART_MODE_TX_RX))) == 0x00) && ((MODE) != (uint32_t)0x00000000)) + +#define IS_USART_CLOCK(CLOCK) (((CLOCK) == USART_CLOCK_DISABLE) || \ + ((CLOCK) == USART_CLOCK_ENABLE)) + +#define IS_USART_POLARITY(CPOL) (((CPOL) == USART_POLARITY_LOW) || ((CPOL) == USART_POLARITY_HIGH)) + +#define IS_USART_PHASE(CPHA) (((CPHA) == USART_PHASE_1EDGE) || ((CPHA) == USART_PHASE_2EDGE)) + +#define IS_USART_LASTBIT(LASTBIT) (((LASTBIT) == USART_LASTBIT_DISABLE) || \ + ((LASTBIT) == USART_LASTBIT_ENABLE)) + +#define IS_USART_NACK_STATE(NACK) (((NACK) == USART_NACK_ENABLE) || \ + ((NACK) == USART_NACK_DISABLE)) + +/** USART interruptions flag mask + * + */ +#define USART_IT_MASK ((uint32_t) USART_CR1_PEIE | USART_CR1_TXEIE | USART_CR1_TCIE | USART_CR1_RXNEIE | \ + USART_CR1_IDLEIE | USART_CR2_LBDIE | USART_CR3_CTSIE | USART_CR3_EIE ) + +/** + * @} + */ + + +/* Exported functions --------------------------------------------------------*/ + +/** @addtogroup USART_Exported_Functions USART Exported Functions * @{ */ -/* Initialization/de-initialization functions **********************************/ + +/** @addtogroup USART_Exported_Functions_Group1 Initialization and de-initialization functions + * @{ + */ + +/* Initialization and de-initialization functions ******************************/ HAL_StatusTypeDef HAL_USART_Init(USART_HandleTypeDef *husart); HAL_StatusTypeDef HAL_USART_DeInit(USART_HandleTypeDef *husart); void HAL_USART_MspInit(USART_HandleTypeDef *husart); void HAL_USART_MspDeInit(USART_HandleTypeDef *husart); + /** * @} */ -/** @addtogroup USART_Exported_Functions_Group2 +/** @addtogroup USART_Exported_Functions_Group2 IO operation functions * @{ */ + /* IO operation functions *******************************************************/ HAL_StatusTypeDef HAL_USART_Transmit(USART_HandleTypeDef *husart, uint8_t *pTxData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_USART_Receive(USART_HandleTypeDef *husart, uint8_t *pRxData, uint16_t Size, uint32_t Timeout); @@ -478,10 +570,6 @@ HAL_StatusTypeDef HAL_USART_TransmitReceive_DMA(USART_HandleTypeDef *husart, uin HAL_StatusTypeDef HAL_USART_DMAPause(USART_HandleTypeDef *husart); HAL_StatusTypeDef HAL_USART_DMAResume(USART_HandleTypeDef *husart); HAL_StatusTypeDef HAL_USART_DMAStop(USART_HandleTypeDef *husart); -/* Transfer Abort functions */ -HAL_StatusTypeDef HAL_USART_Abort(USART_HandleTypeDef *husart); -HAL_StatusTypeDef HAL_USART_Abort_IT(USART_HandleTypeDef *husart); - void HAL_USART_IRQHandler(USART_HandleTypeDef *husart); void HAL_USART_TxCpltCallback(USART_HandleTypeDef *husart); void HAL_USART_TxHalfCpltCallback(USART_HandleTypeDef *husart); @@ -489,91 +577,25 @@ void HAL_USART_RxCpltCallback(USART_HandleTypeDef *husart); void HAL_USART_RxHalfCpltCallback(USART_HandleTypeDef *husart); void HAL_USART_TxRxCpltCallback(USART_HandleTypeDef *husart); void HAL_USART_ErrorCallback(USART_HandleTypeDef *husart); -void HAL_USART_AbortCpltCallback (USART_HandleTypeDef *husart); -/** - * @} - */ - -/** @addtogroup USART_Exported_Functions_Group3 - * @{ - */ -/* Peripheral State functions ************************************************/ -HAL_USART_StateTypeDef HAL_USART_GetState(USART_HandleTypeDef *husart); -uint32_t HAL_USART_GetError(USART_HandleTypeDef *husart); -/** - * @} - */ /** * @} */ -/* Private types -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private constants ---------------------------------------------------------*/ -/** @defgroup USART_Private_Constants USART Private Constants - * @{ - */ -/** @brief USART interruptions flag mask - * - */ -#define USART_IT_MASK 0x0000FFFFU -#define USART_CR1_REG_INDEX 1U -#define USART_CR2_REG_INDEX 2U -#define USART_CR3_REG_INDEX 3U -/** - * @} - */ +/* Peripheral Control functions ***********************************************/ -/* Private macros ------------------------------------------------------------*/ -/** @defgroup USART_Private_Macros USART Private Macros +/** @addtogroup USART_Exported_Functions_Group3 Peripheral State and Errors functions * @{ */ -#define IS_USART_NACK_STATE(NACK) (((NACK) == USART_NACK_ENABLE) || \ - ((NACK) == USART_NACK_DISABLE)) - -#define IS_USART_LASTBIT(LASTBIT) (((LASTBIT) == USART_LASTBIT_DISABLE) || \ - ((LASTBIT) == USART_LASTBIT_ENABLE)) - -#define IS_USART_PHASE(CPHA) (((CPHA) == USART_PHASE_1EDGE) || ((CPHA) == USART_PHASE_2EDGE)) -#define IS_USART_POLARITY(CPOL) (((CPOL) == USART_POLARITY_LOW) || ((CPOL) == USART_POLARITY_HIGH)) - -#define IS_USART_CLOCK(CLOCK) (((CLOCK) == USART_CLOCK_DISABLE) || \ - ((CLOCK) == USART_CLOCK_ENABLE)) - -#define IS_USART_WORD_LENGTH(LENGTH) (((LENGTH) == USART_WORDLENGTH_8B) || \ - ((LENGTH) == USART_WORDLENGTH_9B)) - -#define IS_USART_STOPBITS(STOPBITS) (((STOPBITS) == USART_STOPBITS_1) || \ - ((STOPBITS) == USART_STOPBITS_0_5) || \ - ((STOPBITS) == USART_STOPBITS_1_5) || \ - ((STOPBITS) == USART_STOPBITS_2)) - -#define IS_USART_PARITY(PARITY) (((PARITY) == USART_PARITY_NONE) || \ - ((PARITY) == USART_PARITY_EVEN) || \ - ((PARITY) == USART_PARITY_ODD)) - -#define IS_USART_MODE(MODE) ((((MODE) & 0xFFF3U) == 0x00U) && ((MODE) != 0x00U)) - -#define IS_USART_BAUDRATE(BAUDRATE) ((BAUDRATE) < 4500001U) - -#define USART_DIV(_PCLK_, _BAUD_) (((_PCLK_)*25U)/(2U*(_BAUD_))) - -#define USART_DIVMANT(_PCLK_, _BAUD_) (USART_DIV((_PCLK_), (_BAUD_))/100U) - -#define USART_DIVFRAQ(_PCLK_, _BAUD_) (((USART_DIV((_PCLK_), (_BAUD_)) - (USART_DIVMANT((_PCLK_), (_BAUD_)) * 100U)) * 16U + 50U) / 100U) +/* Peripheral State and Error functions ***************************************/ +HAL_USART_StateTypeDef HAL_USART_GetState(USART_HandleTypeDef *husart); +uint32_t HAL_USART_GetError(USART_HandleTypeDef *husart); -#define USART_BRR(_PCLK_, _BAUD_) ((USART_DIVMANT((_PCLK_), (_BAUD_)) << 4U)|(USART_DIVFRAQ((_PCLK_), (_BAUD_)) & 0x0FU)) /** * @} */ -/* Private functions ---------------------------------------------------------*/ -/** @defgroup USART_Private_Functions USART Private Functions - * @{ - */ - /** * @} */ diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_wwdg.c b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_wwdg.c index aa435f318f0..128f16f2bc7 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_wwdg.c +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_wwdg.c @@ -2,21 +2,22 @@ ****************************************************************************** * @file stm32f1xx_hal_wwdg.c * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief WWDG HAL module driver. * This file provides firmware functions to manage the following * functionalities of the Window Watchdog (WWDG) peripheral: * + Initialization and de-initialization functions * + IO operation functions - * + Peripheral State functions + * + Peripheral State functions + * @verbatim ============================================================================== ##### WWDG specific features ##### ============================================================================== [..] Once enabled the WWDG generates a system reset on expiry of a programmed - time period, unless the program refreshes the counter (downcounter) + time period, unless the program refreshes the Counter (T[6;0] downcounter) before reaching 0x3F value (i.e. a reset is generated when the counter value rolls over from 0x40 to 0x3F). @@ -28,63 +29,43 @@ reset occurs. (+) The WWDG counter input clock is derived from the APB clock divided by a programmable prescaler. - (+) WWDG clock (Hz) = PCLK1 / (4096 * Prescaler) - (+) WWDG timeout (mS) = 1000 * Counter / WWDG clock + (+) WWDG clock (Hz) = PCLK / (4096 * Prescaler) + (+) WWDG timeout (mS) = 1000 * (T[5;0] + 1) / WWDG clock + where T[5;0] are the lowest 6 bits of Counter. (+) WWDG Counter refresh is allowed between the following limits : - (++) min time (mS) = 1000 * (Counter _ Window) / WWDG clock - (++) max time (mS) = 1000 * (Counter _ 0x40) / WWDG clock + (++) min time (mS) = 1000 * (Counter - Window) / WWDG clock + (++) max time (mS) = 1000 * (Counter - 0x40) / WWDG clock - (+) Min-max timeout value at 36 MHz(PCLK1): 910 us / 58.25 ms - - (+) The Early Wakeup Interrupt (EWI) can be used if specific safety - operations or data logging must be performed before the actual reset is - generated. When the downcounter reaches the value 0x40, an EWI interrupt - is generated and the corresponding interrupt service routine (ISR) can - be used to trigger specific actions (such as communications or data - logging), before resetting the device. - In some applications, the EWI interrupt can be used to manage a software - system check and/or system recovery/graceful degradation, without - generating a WWDG reset. In this case, the corresponding interrupt - service routine (ISR) should reload the WWDG counter to avoid the WWDG - reset, then trigger the required actions. - Note:When the EWI interrupt cannot be served, e.g. due to a system lock - in a higher priority task, the WWDG reset will eventually be generated. - - (+) Debug mode : When the microcontroller enters debug mode (core halted), - the WWDG counter either continues to work normally or stops, depending - on DBG_WWDG_STOP configuration bit in DBG module, accessible through - __HAL_DBGMCU_FREEZE_WWDG() and __HAL_DBGMCU_UNFREEZE_WWDG() macros + (+) Min-max timeout value @48 MHz(PCLK): ~85,3us / ~5,46 ms ##### How to use this driver ##### ============================================================================== [..] (+) Enable WWDG APB1 clock using __HAL_RCC_WWDG_CLK_ENABLE(). - - (+) Set the WWDG prescaler, refresh window, counter value and Early Wakeup - Interrupt mode using using HAL_WWDG_Init() function. - This enables WWDG peripheral and the downcounter starts downcounting - from given counter value. - Init function can be called again to modify all watchdog parameters, - however if EWI mode has been set once, it can't be clear until next - reset. - - (+) The application program must refresh the WWDG counter at regular - intervals during normal operation to prevent an MCU reset using + (+) Set the WWDG prescaler, refresh window and counter value + using HAL_WWDG_Init() function. + (+) Start the WWDG using HAL_WWDG_Start() function. + When the WWDG is enabled the counter value should be configured to + a value greater than 0x40 to prevent generating an immediate reset. + (+) Optionally you can enable the Early Wakeup Interrupt (EWI) which is + generated when the counter reaches 0x40, and then start the WWDG using + HAL_WWDG_Start_IT(). At EWI HAL_WWDG_WakeupCallback is executed and user can + add his own code by customization of function pointer HAL_WWDG_WakeupCallback + Once enabled, EWI interrupt cannot be disabled except by a system reset. + (+) Then the application program must refresh the WWDG counter at regular + intervals during normal operation to prevent an MCU reset, using HAL_WWDG_Refresh() function. This operation must occur only when - the counter is lower than the window value already programmed. - - (+) if Early Wakeup Interrupt mode is enable an interrupt is generated when - the counter reaches 0x40. User can add his own code in weak function - HAL_WWDG_EarlyWakeupCallback(). - + the counter is lower than the refresh window value already programmed. + *** WWDG HAL driver macros list *** ================================== [..] Below the list of most used macros in WWDG HAL driver. - - (+) __HAL_WWDG_GET_IT_SOURCE: Check the selected WWDG's interrupt source. - (+) __HAL_WWDG_GET_FLAG: Get the selected WWDG's flag status. - (+) __HAL_WWDG_CLEAR_FLAG: Clear the WWDG's pending flags. + + (+) __HAL_WWDG_ENABLE: Enable the WWDG peripheral + (+) __HAL_WWDG_GET_FLAG: Get the selected WWDG's flag status + (+) __HAL_WWDG_CLEAR_FLAG: Clear the WWDG's pending flags + (+) __HAL_WWDG_ENABLE_IT: Enables the WWDG early wakeup interrupt @endverbatim ****************************************************************************** @@ -115,7 +96,7 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** - */ + */ /* Includes ------------------------------------------------------------------*/ #include "stm32f1xx_hal.h" @@ -124,12 +105,13 @@ * @{ */ -#ifdef HAL_WWDG_MODULE_ENABLED /** @defgroup WWDG WWDG * @brief WWDG HAL module driver. * @{ */ +#ifdef HAL_WWDG_MODULE_ENABLED + /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ @@ -141,28 +123,30 @@ * @{ */ -/** @defgroup WWDG_Exported_Functions_Group1 Initialization and Configuration functions - * @brief Initialization and Configuration functions. - * -@verbatim +/** @defgroup WWDG_Exported_Functions_Group1 Initialization and de-initialization functions + * @brief Initialization and Configuration functions. + * +@verbatim ============================================================================== - ##### Initialization and Configuration functions ##### + ##### Initialization and de-initialization functions ##### ============================================================================== [..] This section provides functions allowing to: - (+) Initialize and start the WWDG according to the specified parameters - in the WWDG_InitTypeDef of associated handle. - (+) Initialize the WWDG MSP. - + (+) Initialize the WWDG according to the specified parameters + in the WWDG_InitTypeDef and create the associated handle + (+) DeInitialize the WWDG peripheral + (+) Initialize the WWDG MSP + (+) DeInitialize the WWDG MSP + @endverbatim * @{ */ /** - * @brief Initialize the WWDG according to the specified. - * parameters in the WWDG_InitTypeDef of associated handle. - * @param hwwdg pointer to a WWDG_HandleTypeDef structure that contains - * the configuration information for the specified WWDG module. + * @brief Initializes the WWDG according to the specified + * parameters in the WWDG_InitTypeDef and creates the associated handle. + * @param hwwdg: pointer to a WWDG_HandleTypeDef structure that contains + * the configuration information for the specified WWDG module. * @retval HAL status */ HAL_StatusTypeDef HAL_WWDG_Init(WWDG_HandleTypeDef *hwwdg) @@ -176,124 +160,290 @@ HAL_StatusTypeDef HAL_WWDG_Init(WWDG_HandleTypeDef *hwwdg) /* Check the parameters */ assert_param(IS_WWDG_ALL_INSTANCE(hwwdg->Instance)); assert_param(IS_WWDG_PRESCALER(hwwdg->Init.Prescaler)); - assert_param(IS_WWDG_WINDOW(hwwdg->Init.Window)); - assert_param(IS_WWDG_COUNTER(hwwdg->Init.Counter)); - assert_param(IS_WWDG_EWI_MODE(hwwdg->Init.EWIMode)); - - /* Init the low level hardware */ - HAL_WWDG_MspInit(hwwdg); + assert_param(IS_WWDG_WINDOW(hwwdg->Init.Window)); + assert_param(IS_WWDG_COUNTER(hwwdg->Init.Counter)); + + if(hwwdg->State == HAL_WWDG_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + hwwdg->Lock = HAL_UNLOCKED; + + /* Init the low level hardware */ + HAL_WWDG_MspInit(hwwdg); + } + + /* Change WWDG peripheral state */ + hwwdg->State = HAL_WWDG_STATE_BUSY; + /* Set WWDG Prescaler and Window */ + MODIFY_REG(hwwdg->Instance->CFR, (WWDG_CFR_WDGTB | WWDG_CFR_W), (hwwdg->Init.Prescaler | hwwdg->Init.Window)); + /* Set WWDG Counter */ - WRITE_REG(hwwdg->Instance->CR, (WWDG_CR_WDGA | hwwdg->Init.Counter)); + MODIFY_REG(hwwdg->Instance->CR, WWDG_CR_T, hwwdg->Init.Counter); - /* Set WWDG Prescaler and Window */ - WRITE_REG(hwwdg->Instance->CFR, (hwwdg->Init.EWIMode | hwwdg->Init.Prescaler | hwwdg->Init.Window)); + /* Change WWDG peripheral state */ + hwwdg->State = HAL_WWDG_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief DeInitializes the WWDG peripheral. + * @param hwwdg: pointer to a WWDG_HandleTypeDef structure that contains + * the configuration information for the specified WWDG module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_WWDG_DeInit(WWDG_HandleTypeDef *hwwdg) +{ + /* Check the WWDG handle allocation */ + if(hwwdg == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_WWDG_ALL_INSTANCE(hwwdg->Instance)); + + /* Change WWDG peripheral state */ + hwwdg->State = HAL_WWDG_STATE_BUSY; + + /* DeInit the low level hardware */ + HAL_WWDG_MspDeInit(hwwdg); + + /* Reset WWDG Control register */ + hwwdg->Instance->CR = (uint32_t)0x0000007F; + + /* Reset WWDG Configuration register */ + hwwdg->Instance->CFR = (uint32_t)0x0000007F; + + /* Reset WWDG Status register */ + hwwdg->Instance->SR = 0; + + /* Change WWDG peripheral state */ + hwwdg->State = HAL_WWDG_STATE_RESET; + + /* Release Lock */ + __HAL_UNLOCK(hwwdg); /* Return function status */ return HAL_OK; } /** - * @brief Initialize the WWDG MSP. - * @param hwwdg pointer to a WWDG_HandleTypeDef structure that contains - * the configuration information for the specified WWDG module. - * @note When rewriting this function in user file, mechanism may be added - * to avoid multiple initialize when HAL_WWDG_Init function is called - * again to change parameters. + * @brief Initializes the WWDG MSP. + * @param hwwdg: pointer to a WWDG_HandleTypeDef structure that contains + * the configuration information for the specified WWDG module. * @retval None */ __weak void HAL_WWDG_MspInit(WWDG_HandleTypeDef *hwwdg) { /* Prevent unused argument(s) compilation warning */ UNUSED(hwwdg); - - /* NOTE: This function should not be modified, when the callback is needed, + /* NOTE: This function Should not be modified, when the callback is needed, the HAL_WWDG_MspInit could be implemented in the user file */ } +/** + * @brief DeInitializes the WWDG MSP. + * @param hwwdg: pointer to a WWDG_HandleTypeDef structure that contains + * the configuration information for the specified WWDG module. + * @retval None + */ +__weak void HAL_WWDG_MspDeInit(WWDG_HandleTypeDef *hwwdg) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hwwdg); + /* NOTE: This function Should not be modified, when the callback is needed, + the HAL_WWDG_MspDeInit could be implemented in the user file + */ +} + /** * @} */ -/** @defgroup WWDG_Exported_Functions_Group2 IO operation functions - * @brief IO operation functions +/** @defgroup WWDG_Exported_Functions_Group2 IO operation functions + * @brief IO operation functions * -@verbatim +@verbatim ============================================================================== - ##### IO operation functions ##### + ##### IO operation functions ##### ============================================================================== - [..] + [..] This section provides functions allowing to: + (+) Start the WWDG. (+) Refresh the WWDG. - (+) Handle WWDG interrupt request and associated function callback. + (+) Handle WWDG interrupt request. @endverbatim * @{ */ /** - * @brief Refresh the WWDG. - * @param hwwdg pointer to a WWDG_HandleTypeDef structure that contains - * the configuration information for the specified WWDG module. + * @brief Starts the WWDG. + * @param hwwdg: pointer to a WWDG_HandleTypeDef structure that contains + * the configuration information for the specified WWDG module. * @retval HAL status */ -HAL_StatusTypeDef HAL_WWDG_Refresh(WWDG_HandleTypeDef *hwwdg) +HAL_StatusTypeDef HAL_WWDG_Start(WWDG_HandleTypeDef *hwwdg) { - /* Write to WWDG CR the WWDG Counter value to refresh with */ - WRITE_REG(hwwdg->Instance->CR, (hwwdg->Init.Counter)); + /* Process Locked */ + __HAL_LOCK(hwwdg); + + /* Change WWDG peripheral state */ + hwwdg->State = HAL_WWDG_STATE_BUSY; + + /* Enable the peripheral */ + __HAL_WWDG_ENABLE(hwwdg); + + /* Change WWDG peripheral state */ + hwwdg->State = HAL_WWDG_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hwwdg); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts the WWDG with interrupt enabled. + * @param hwwdg: pointer to a WWDG_HandleTypeDef structure that contains + * the configuration information for the specified WWDG module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_WWDG_Start_IT(WWDG_HandleTypeDef *hwwdg) +{ + /* Process Locked */ + __HAL_LOCK(hwwdg); + + /* Change WWDG peripheral state */ + hwwdg->State = HAL_WWDG_STATE_BUSY; + + /* Enable the Early Wakeup Interrupt */ + __HAL_WWDG_ENABLE_IT(hwwdg, WWDG_IT_EWI); + + /* Enable the peripheral */ + __HAL_WWDG_ENABLE(hwwdg); /* Return function status */ return HAL_OK; } /** - * @brief Handle WWDG interrupt request. - * @note The Early Wakeup Interrupt (EWI) can be used if specific safety operations - * or data logging must be performed before the actual reset is generated. - * The EWI interrupt is enabled by calling HAL_WWDG_Init function with - * EWIMode set to WWDG_EWI_ENABLE. - * When the downcounter reaches the value 0x40, and EWI interrupt is - * generated and the corresponding Interrupt Service Routine (ISR) can - * be used to trigger specific actions (such as communications or data - * logging), before resetting the device. - * @param hwwdg pointer to a WWDG_HandleTypeDef structure that contains - * the configuration information for the specified WWDG module. + * @brief Refreshes the WWDG. + * @param hwwdg: pointer to a WWDG_HandleTypeDef structure that contains + * the configuration information for the specified WWDG module. + * @param Counter: value of counter to put in WWDG counter + * @retval HAL status + */ +HAL_StatusTypeDef HAL_WWDG_Refresh(WWDG_HandleTypeDef *hwwdg, uint32_t Counter) +{ + /* Process Locked */ + __HAL_LOCK(hwwdg); + + /* Change WWDG peripheral state */ + hwwdg->State = HAL_WWDG_STATE_BUSY; + + /* Check the parameters */ + assert_param(IS_WWDG_COUNTER(Counter)); + + /* Write to WWDG CR the WWDG Counter value to refresh with */ + MODIFY_REG(hwwdg->Instance->CR, (uint32_t)WWDG_CR_T, Counter); + + /* Change WWDG peripheral state */ + hwwdg->State = HAL_WWDG_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hwwdg); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Handles WWDG interrupt request. + * @note The Early Wakeup Interrupt (EWI) can be used if specific safety operations + * or data logging must be performed before the actual reset is generated. + * The EWI interrupt is enabled when calling HAL_WWDG_Start_IT function. + * When the downcounter reaches the value 0x40, and EWI interrupt is + * generated and the corresponding Interrupt Service Routine (ISR) can + * be used to trigger specific actions (such as communications or data + * logging), before resetting the device. + * @param hwwdg: pointer to a WWDG_HandleTypeDef structure that contains + * the configuration information for the specified WWDG module. * @retval None */ void HAL_WWDG_IRQHandler(WWDG_HandleTypeDef *hwwdg) -{ +{ /* Check if Early Wakeup Interrupt is enable */ if(__HAL_WWDG_GET_IT_SOURCE(hwwdg, WWDG_IT_EWI) != RESET) { - /* Check if WWDG Early Wakeup Interrupt occurred */ - if(__HAL_WWDG_GET_FLAG(hwwdg, WWDG_FLAG_EWIF) != RESET) - { + /* Wheck if WWDG Early Wakeup Interrupt occurred */ + if(__HAL_WWDG_GET_FLAG(hwwdg, WWDG_FLAG_EWIF) != RESET) + { + /* Early Wakeup callback */ + HAL_WWDG_WakeupCallback(hwwdg); + + /* Change WWDG peripheral state */ + hwwdg->State = HAL_WWDG_STATE_READY; + /* Clear the WWDG Early Wakeup flag */ - __HAL_WWDG_CLEAR_FLAG(hwwdg, WWDG_FLAG_EWIF); - - /* Early Wakeup callback */ - HAL_WWDG_EarlyWakeupCallback(hwwdg); - } + __HAL_WWDG_CLEAR_FLAG(hwwdg, WWDG_FLAG_EWIF); + + /* Process Unlocked */ + __HAL_UNLOCK(hwwdg); } +} } /** - * @brief WWDG Early Wakeup callback. - * @param hwwdg : pointer to a WWDG_HandleTypeDef structure that contains - * the configuration information for the specified WWDG module. + * @brief Early Wakeup WWDG callback. + * @param hwwdg: pointer to a WWDG_HandleTypeDef structure that contains + * the configuration information for the specified WWDG module. * @retval None */ -__weak void HAL_WWDG_EarlyWakeupCallback(WWDG_HandleTypeDef* hwwdg) +__weak void HAL_WWDG_WakeupCallback(WWDG_HandleTypeDef* hwwdg) { /* Prevent unused argument(s) compilation warning */ UNUSED(hwwdg); - - /* NOTE: This function should not be modified, when the callback is needed, - the HAL_WWDG_EarlyWakeupCallback could be implemented in the user file + /* NOTE: This function Should not be modified, when the callback is needed, + the HAL_WWDG_WakeupCallback could be implemented in the user file */ } +/** + * @} + */ + +/** @defgroup WWDG_Exported_Functions_Group3 Peripheral State functions + * @brief Peripheral State functions. + * +@verbatim + ============================================================================== + ##### Peripheral State functions ##### + ============================================================================== + [..] + This subsection permits to get in run-time the status of the peripheral + and the data flow. + +@endverbatim + * @{ + */ + +/** + * @brief Returns the WWDG state. + * @param hwwdg: pointer to a WWDG_HandleTypeDef structure that contains + * the configuration information for the specified WWDG module. + * @retval HAL state + */ +HAL_WWDG_StateTypeDef HAL_WWDG_GetState(WWDG_HandleTypeDef *hwwdg) +{ + return hwwdg->State; +} + /** * @} */ diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_wwdg.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_wwdg.h index 4f6510af0f2..e4fb044b22a 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_wwdg.h +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_wwdg.h @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_hal_wwdg.h * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief Header file of WWDG HAL module. ****************************************************************************** * @attention @@ -55,39 +55,54 @@ */ /* Exported types ------------------------------------------------------------*/ + /** @defgroup WWDG_Exported_Types WWDG Exported Types * @{ */ -/** - * @brief WWDG Init structure definition +/** + * @brief WWDG HAL State Structure definition */ -typedef struct +typedef enum { - uint32_t Prescaler; /*!< Specifies the prescaler value of the WWDG. - This parameter can be a value of @ref WWDG_Prescaler */ - - uint32_t Window; /*!< Specifies the WWDG window value to be compared to the downcounter. - This parameter must be a number Min_Data = 0x40 and Max_Data = 0x7F */ + HAL_WWDG_STATE_RESET = 0x00, /*!< WWDG not yet initialized or disabled */ + HAL_WWDG_STATE_READY = 0x01, /*!< WWDG initialized and ready for use */ + HAL_WWDG_STATE_BUSY = 0x02, /*!< WWDG internal process is ongoing */ + HAL_WWDG_STATE_TIMEOUT = 0x03, /*!< WWDG timeout state */ + HAL_WWDG_STATE_ERROR = 0x04 /*!< WWDG error state */ +}HAL_WWDG_StateTypeDef; - uint32_t Counter; /*!< Specifies the WWDG free-running downcounter value. - This parameter must be a number between Min_Data = 0x40 and Max_Data = 0x7F */ - - uint32_t EWIMode ; /*!< Specifies if WWDG Early Wakeup Interupt is enable or not. - This parameter can be a value of @ref WWDG_EWI_Mode */ +/** + * @brief WWDG Init structure definition + */ +typedef struct +{ + uint32_t Prescaler; /*!< Specifies the prescaler value of the WWDG. + This parameter can be a value of @ref WWDG_Prescaler */ + + uint32_t Window; /*!< Specifies the WWDG window value to be compared to the downcounter. + This parameter must be a number lower than Max_Data = 0x80 */ + + uint32_t Counter; /*!< Specifies the WWDG free-running downcounter value. + This parameter must be a number between Min_Data = 0x40 and Max_Data = 0x7F */ }WWDG_InitTypeDef; -/** - * @brief WWDG handle Structure definition - */ +/** + * @brief WWDG handle Structure definition + */ typedef struct { WWDG_TypeDef *Instance; /*!< Register base address */ - + WWDG_InitTypeDef Init; /*!< WWDG required parameters */ - + + HAL_LockTypeDef Lock; /*!< WWDG locking object */ + + __IO HAL_WWDG_StateTypeDef State; /*!< WWDG communication state */ + }WWDG_HandleTypeDef; + /** * @} */ @@ -100,8 +115,8 @@ typedef struct /** @defgroup WWDG_Interrupt_definition WWDG Interrupt definition * @{ - */ -#define WWDG_IT_EWI WWDG_CFR_EWI /*!< Early wakeup interrupt */ + */ +#define WWDG_IT_EWI WWDG_CFR_EWI /*!< Early wakeup interrupt */ /** * @} */ @@ -109,8 +124,8 @@ typedef struct /** @defgroup WWDG_Flag_definition WWDG Flag definition * @brief WWDG Flag definition * @{ - */ -#define WWDG_FLAG_EWIF WWDG_SR_EWIF /*!< Early wakeup interrupt flag */ + */ +#define WWDG_FLAG_EWIF WWDG_SR_EWIF /*!< Early wakeup interrupt flag */ /** * @} */ @@ -118,43 +133,33 @@ typedef struct /** @defgroup WWDG_Prescaler WWDG Prescaler * @{ */ -#define WWDG_PRESCALER_1 0x00000000U /*!< WWDG counter clock = (PCLK1/4096)/1 */ +#define WWDG_PRESCALER_1 ((uint32_t)0x00000000) /*!< WWDG counter clock = (PCLK1/4096)/1 */ #define WWDG_PRESCALER_2 WWDG_CFR_WDGTB0 /*!< WWDG counter clock = (PCLK1/4096)/2 */ #define WWDG_PRESCALER_4 WWDG_CFR_WDGTB1 /*!< WWDG counter clock = (PCLK1/4096)/4 */ #define WWDG_PRESCALER_8 WWDG_CFR_WDGTB /*!< WWDG counter clock = (PCLK1/4096)/8 */ -/** - * @} - */ -/** @defgroup WWDG_EWI_Mode WWDG Early Wakeup Interrupt Mode - * @{ - */ -#define WWDG_EWI_DISABLE 0x00000000U /*!< EWI Disable */ -#define WWDG_EWI_ENABLE WWDG_CFR_EWI /*!< EWI Enable */ /** * @} - */ + */ /** * @} - */ + */ /* Private macros ------------------------------------------------------------*/ /** @defgroup WWDG_Private_Macros WWDG Private Macros * @{ */ -#define IS_WWDG_PRESCALER(__PRESCALER__) (((__PRESCALER__) == WWDG_PRESCALER_1) || \ - ((__PRESCALER__) == WWDG_PRESCALER_2) || \ - ((__PRESCALER__) == WWDG_PRESCALER_4) || \ - ((__PRESCALER__) == WWDG_PRESCALER_8)) +#define IS_WWDG_PRESCALER(__PRESCALER__) (((__PRESCALER__) == WWDG_PRESCALER_1) || \ + ((__PRESCALER__) == WWDG_PRESCALER_2) || \ + ((__PRESCALER__) == WWDG_PRESCALER_4) || \ + ((__PRESCALER__) == WWDG_PRESCALER_8)) -#define IS_WWDG_WINDOW(__WINDOW__) (((__WINDOW__) >= WWDG_CFR_W_6) && ((__WINDOW__) <= WWDG_CFR_W)) +#define IS_WWDG_WINDOW(__WINDOW__) ((__WINDOW__) <= 0x7F) -#define IS_WWDG_COUNTER(__COUNTER__) (((__COUNTER__) >= WWDG_CR_T_6) && ((__COUNTER__) <= WWDG_CR_T)) - -#define IS_WWDG_EWI_MODE(__MODE__) (((__MODE__) == WWDG_EWI_ENABLE) || \ - ((__MODE__) == WWDG_EWI_DISABLE)) + +#define IS_WWDG_COUNTER(__COUNTER__) (((__COUNTER__) >= 0x40) && ((__COUNTER__) <= 0x7F)) /** * @} */ @@ -166,28 +171,55 @@ typedef struct * @{ */ +/** @brief Reset WWDG handle state + * @param __HANDLE__: WWDG handle + * @retval None + */ +#define __HAL_WWDG_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_WWDG_STATE_RESET) + /** * @brief Enables the WWDG peripheral. * @param __HANDLE__: WWDG handle * @retval None */ -#define __HAL_WWDG_ENABLE(__HANDLE__) SET_BIT((__HANDLE__)->Instance->CR, WWDG_CR_WDGA) +#define __HAL_WWDG_ENABLE(__HANDLE__) SET_BIT((__HANDLE__)->Instance->CR, WWDG_CR_WDGA) + +/** + * @brief Disables the WWDG peripheral. + * @param __HANDLE__: WWDG handle + * @note WARNING: This is a dummy macro for HAL code alignment. + * Once enable, WWDG Peripheral cannot be disabled except by a system reset. + * @retval None + */ +#define __HAL_WWDG_DISABLE(__HANDLE__) /* dummy macro */ /** * @brief Enables the WWDG early wakeup interrupt. * @param __HANDLE__: WWDG handle - * @param __INTERRUPT__ specifies the interrupt to enable. + * @param __INTERRUPT__: specifies the interrupt to enable. * This parameter can be one of the following values: * @arg WWDG_IT_EWI: Early wakeup interrupt * @note Once enabled this interrupt cannot be disabled except by a system reset. * @retval None */ -#define __HAL_WWDG_ENABLE_IT(__HANDLE__, __INTERRUPT__) SET_BIT((__HANDLE__)->Instance->CFR, (__INTERRUPT__)) +#define __HAL_WWDG_ENABLE_IT(__HANDLE__, __INTERRUPT__) SET_BIT((__HANDLE__)->Instance->CFR, (__INTERRUPT__)) /** - * @brief Checks whether the selected WWDG interrupt has occurred or not. - * @param __HANDLE__ WWDG handle - * @param __INTERRUPT__ specifies the it to check. + * @brief Disables the WWDG early wakeup interrupt. + * @param __HANDLE__: WWDG handle + * @param __INTERRUPT__: specifies the interrupt to disable. + * This parameter can be one of the following values: + * @arg WWDG_IT_EWI: Early wakeup interrupt + * @note WARNING: This is a dummy macro for HAL code alignment. + * Once enabled this interrupt cannot be disabled except by a system reset. + * @retval None + */ +#define __HAL_WWDG_DISABLE_IT(__HANDLE__, __INTERRUPT__) /* dummy macro */ + +/** + * @brief Gets the selected WWDG's it status. + * @param __HANDLE__: WWDG handle + * @param __INTERRUPT__: specifies the it to check. * This parameter can be one of the following values: * @arg WWDG_FLAG_EWIF: Early wakeup interrupt IT * @retval The new state of WWDG_FLAG (SET or RESET). @@ -204,9 +236,9 @@ typedef struct #define __HAL_WWDG_CLEAR_IT(__HANDLE__, __INTERRUPT__) __HAL_WWDG_CLEAR_FLAG((__HANDLE__), (__INTERRUPT__)) /** - * @brief Check whether the specified WWDG flag is set or not. - * @param __HANDLE__ WWDG handle - * @param __FLAG__ specifies the flag to check. + * @brief Gets the selected WWDG's flag status. + * @param __HANDLE__: WWDG handle + * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg WWDG_FLAG_EWIF: Early wakeup interrupt flag * @retval The new state of WWDG_FLAG (SET or RESET). @@ -221,7 +253,7 @@ typedef struct * @arg WWDG_FLAG_EWIF: Early wakeup interrupt flag * @retval None */ -#define __HAL_WWDG_CLEAR_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->SR) = ~(__FLAG__)) +#define __HAL_WWDG_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->SR = ~(__FLAG__)) /** @brief Checks if the specified WWDG interrupt source is enabled or disabled. * @param __HANDLE__: WWDG Handle. @@ -234,9 +266,10 @@ typedef struct /** * @} - */ + */ /* Exported functions --------------------------------------------------------*/ + /** @addtogroup WWDG_Exported_Functions * @{ */ @@ -245,35 +278,51 @@ typedef struct * @{ */ /* Initialization/de-initialization functions **********************************/ -HAL_StatusTypeDef HAL_WWDG_Init(WWDG_HandleTypeDef *hwwdg); -void HAL_WWDG_MspInit(WWDG_HandleTypeDef *hwwdg); +HAL_StatusTypeDef HAL_WWDG_Init(WWDG_HandleTypeDef *hwwdg); +HAL_StatusTypeDef HAL_WWDG_DeInit(WWDG_HandleTypeDef *hwwdg); +void HAL_WWDG_MspInit(WWDG_HandleTypeDef *hwwdg); +void HAL_WWDG_MspDeInit(WWDG_HandleTypeDef *hwwdg); +void HAL_WWDG_WakeupCallback(WWDG_HandleTypeDef* hwwdg); + /** * @} */ - + /** @addtogroup WWDG_Exported_Functions_Group2 * @{ */ /* I/O operation functions ******************************************************/ -HAL_StatusTypeDef HAL_WWDG_Refresh(WWDG_HandleTypeDef *hwwdg); -void HAL_WWDG_IRQHandler(WWDG_HandleTypeDef *hwwdg); -void HAL_WWDG_EarlyWakeupCallback(WWDG_HandleTypeDef* hwwdg); +HAL_StatusTypeDef HAL_WWDG_Start(WWDG_HandleTypeDef *hwwdg); +HAL_StatusTypeDef HAL_WWDG_Start_IT(WWDG_HandleTypeDef *hwwdg); +HAL_StatusTypeDef HAL_WWDG_Refresh(WWDG_HandleTypeDef *hwwdg, uint32_t Counter); +void HAL_WWDG_IRQHandler(WWDG_HandleTypeDef *hwwdg); + /** * @} */ +/** @addtogroup WWDG_Exported_Functions_Group3 + * @{ + */ +/* Peripheral State functions **************************************************/ +HAL_WWDG_StateTypeDef HAL_WWDG_GetState(WWDG_HandleTypeDef *hwwdg); + /** * @} - */ + */ /** * @} - */ + */ /** * @} - */ + */ +/** + * @} + */ + #ifdef __cplusplus } #endif diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_adc.c b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_adc.c deleted file mode 100644 index 24ff8f3713e..00000000000 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_adc.c +++ /dev/null @@ -1,903 +0,0 @@ -/** - ****************************************************************************** - * @file stm32f1xx_ll_adc.c - * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 - * @brief ADC LL module driver - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2017 STMicroelectronics

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ -#if defined(USE_FULL_LL_DRIVER) - -/* Includes ------------------------------------------------------------------*/ -#include "stm32f1xx_ll_adc.h" -#include "stm32f1xx_ll_bus.h" - -#ifdef USE_FULL_ASSERT - #include "stm32_assert.h" -#else - #define assert_param(expr) ((void)0U) -#endif - -/** @addtogroup STM32F1xx_LL_Driver - * @{ - */ - -#if defined (ADC1) || defined (ADC2) || defined (ADC3) - -/** @addtogroup ADC_LL ADC - * @{ - */ - -/* Private types -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private constants ---------------------------------------------------------*/ -/* Private macros ------------------------------------------------------------*/ - -/** @addtogroup ADC_LL_Private_Macros - * @{ - */ - -/* Check of parameters for configuration of ADC hierarchical scope: */ -/* common to several ADC instances. */ -/* Check of parameters for configuration of ADC hierarchical scope: */ -/* ADC instance. */ -#define IS_LL_ADC_DATA_ALIGN(__DATA_ALIGN__) \ - ( ((__DATA_ALIGN__) == LL_ADC_DATA_ALIGN_RIGHT) \ - || ((__DATA_ALIGN__) == LL_ADC_DATA_ALIGN_LEFT) \ - ) - -#define IS_LL_ADC_SCAN_SELECTION(__SCAN_SELECTION__) \ - ( ((__SCAN_SELECTION__) == LL_ADC_SEQ_SCAN_DISABLE) \ - || ((__SCAN_SELECTION__) == LL_ADC_SEQ_SCAN_ENABLE) \ - ) - -#define IS_LL_ADC_SEQ_SCAN_MODE(__SEQ_SCAN_MODE__) \ - ( ((__SCAN_MODE__) == LL_ADC_SEQ_SCAN_DISABLE) \ - || ((__SCAN_MODE__) == LL_ADC_SEQ_SCAN_ENABLE) \ - ) - -/* Check of parameters for configuration of ADC hierarchical scope: */ -/* ADC group regular */ -#if defined(ADC3) -#define IS_LL_ADC_REG_TRIG_SOURCE(__ADC_INSTANCE__, __REG_TRIG_SOURCE__) \ - ((((__ADC_INSTANCE__) == ADC1) || ((__ADC_INSTANCE__) == ADC2)) \ - ? ( ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_SOFTWARE) \ - || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM1_CH3) \ - || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM1_CH1) \ - || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM1_CH2) \ - || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM2_CH2) \ - || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM3_TRGO) \ - || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM4_CH4) \ - || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_EXTI_LINE11) \ - || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM8_TRGO) \ - ) \ - : \ - ( ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_SOFTWARE) \ - || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM1_CH3) \ - || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM3_CH1) \ - || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM2_CH3) \ - || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM8_CH1) \ - || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM8_TRGO_ADC3) \ - || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM5_CH1) \ - || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM5_CH3) \ - ) \ - ) -#else -#if defined (STM32F101xE) || defined (STM32F105xC) || defined (STM32F107xC) -#define IS_LL_ADC_REG_TRIG_SOURCE(__REG_TRIG_SOURCE__) \ - ( ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_SOFTWARE) \ - || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM1_CH3) \ - || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM1_CH1) \ - || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM1_CH2) \ - || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM2_CH2) \ - || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM3_TRGO) \ - || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM4_CH4) \ - || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_EXTI_LINE11) \ - || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM8_TRGO) \ - ) -#else -#define IS_LL_ADC_REG_TRIG_SOURCE(__REG_TRIG_SOURCE__) \ - ( ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_SOFTWARE) \ - || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM1_CH3) \ - || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM1_CH1) \ - || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM1_CH2) \ - || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM2_CH2) \ - || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM3_TRGO) \ - || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM4_CH4) \ - || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_EXTI_LINE11) \ - ) -#endif -#endif -#define IS_LL_ADC_REG_CONTINUOUS_MODE(__REG_CONTINUOUS_MODE__) \ - ( ((__REG_CONTINUOUS_MODE__) == LL_ADC_REG_CONV_SINGLE) \ - || ((__REG_CONTINUOUS_MODE__) == LL_ADC_REG_CONV_CONTINUOUS) \ - ) - -#define IS_LL_ADC_REG_DMA_TRANSFER(__REG_DMA_TRANSFER__) \ - ( ((__REG_DMA_TRANSFER__) == LL_ADC_REG_DMA_TRANSFER_NONE) \ - || ((__REG_DMA_TRANSFER__) == LL_ADC_REG_DMA_TRANSFER_UNLIMITED) \ - ) - -#define IS_LL_ADC_REG_SEQ_SCAN_LENGTH(__REG_SEQ_SCAN_LENGTH__) \ - ( ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_DISABLE) \ - || ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_2RANKS) \ - || ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_3RANKS) \ - || ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_4RANKS) \ - || ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_5RANKS) \ - || ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_6RANKS) \ - || ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_7RANKS) \ - || ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_8RANKS) \ - || ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_9RANKS) \ - || ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_10RANKS) \ - || ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_11RANKS) \ - || ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_12RANKS) \ - || ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_13RANKS) \ - || ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_14RANKS) \ - || ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_15RANKS) \ - || ((__REG_SEQ_SCAN_LENGTH__) == LL_ADC_REG_SEQ_SCAN_ENABLE_16RANKS) \ - ) - -#define IS_LL_ADC_REG_SEQ_SCAN_DISCONT_MODE(__REG_SEQ_DISCONT_MODE__) \ - ( ((__REG_SEQ_DISCONT_MODE__) == LL_ADC_REG_SEQ_DISCONT_DISABLE) \ - || ((__REG_SEQ_DISCONT_MODE__) == LL_ADC_REG_SEQ_DISCONT_1RANK) \ - || ((__REG_SEQ_DISCONT_MODE__) == LL_ADC_REG_SEQ_DISCONT_2RANKS) \ - || ((__REG_SEQ_DISCONT_MODE__) == LL_ADC_REG_SEQ_DISCONT_3RANKS) \ - || ((__REG_SEQ_DISCONT_MODE__) == LL_ADC_REG_SEQ_DISCONT_4RANKS) \ - || ((__REG_SEQ_DISCONT_MODE__) == LL_ADC_REG_SEQ_DISCONT_5RANKS) \ - || ((__REG_SEQ_DISCONT_MODE__) == LL_ADC_REG_SEQ_DISCONT_6RANKS) \ - || ((__REG_SEQ_DISCONT_MODE__) == LL_ADC_REG_SEQ_DISCONT_7RANKS) \ - || ((__REG_SEQ_DISCONT_MODE__) == LL_ADC_REG_SEQ_DISCONT_8RANKS) \ - ) - -/* Check of parameters for configuration of ADC hierarchical scope: */ -/* ADC group injected */ -#if defined(ADC3) -#define IS_LL_ADC_INJ_TRIG_SOURCE(__ADC_INSTANCE__, __INJ_TRIG_SOURCE__) \ - ((((__ADC_INSTANCE__) == ADC1) || ((__ADC_INSTANCE__) == ADC2)) \ - ? ( ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_SOFTWARE) \ - || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM1_TRGO) \ - || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM1_CH4) \ - || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM2_TRGO) \ - || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM2_CH1) \ - || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM3_CH4) \ - || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM4_TRGO) \ - || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_EXTI_LINE15) \ - || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM8_CH4) \ - ) \ - : \ - ( ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_SOFTWARE) \ - || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM1_TRGO) \ - || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM1_CH4) \ - || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM4_CH3) \ - || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM8_CH2) \ - || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM8_CH4_ADC3) \ - || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM5_TRGO) \ - || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM5_CH4) \ - ) \ - ) -#else -#if defined (STM32F101xE) || defined (STM32F105xC) || defined (STM32F107xC) -#define IS_LL_ADC_INJ_TRIG_SOURCE(__INJ_TRIG_SOURCE__) \ - ( ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_SOFTWARE) \ - || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM1_TRGO) \ - || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM1_CH4) \ - || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM2_TRGO) \ - || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM2_CH1) \ - || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM3_CH4) \ - || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM4_TRGO) \ - || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_EXTI_LINE15) \ - || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM8_CH4) \ - ) -#else -#define IS_LL_ADC_INJ_TRIG_SOURCE(__INJ_TRIG_SOURCE__) \ - ( ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_SOFTWARE) \ - || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM1_TRGO) \ - || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM1_CH4) \ - || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM2_TRGO) \ - || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM2_CH1) \ - || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM3_CH4) \ - || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_TIM4_TRGO) \ - || ((__INJ_TRIG_SOURCE__) == LL_ADC_INJ_TRIG_EXT_EXTI_LINE15) \ - ) -#endif -#endif -#define IS_LL_ADC_INJ_TRIG_AUTO(__INJ_TRIG_AUTO__) \ - ( ((__INJ_TRIG_AUTO__) == LL_ADC_INJ_TRIG_INDEPENDENT) \ - || ((__INJ_TRIG_AUTO__) == LL_ADC_INJ_TRIG_FROM_GRP_REGULAR) \ - ) - -#define IS_LL_ADC_INJ_SEQ_SCAN_LENGTH(__INJ_SEQ_SCAN_LENGTH__) \ - ( ((__INJ_SEQ_SCAN_LENGTH__) == LL_ADC_INJ_SEQ_SCAN_DISABLE) \ - || ((__INJ_SEQ_SCAN_LENGTH__) == LL_ADC_INJ_SEQ_SCAN_ENABLE_2RANKS) \ - || ((__INJ_SEQ_SCAN_LENGTH__) == LL_ADC_INJ_SEQ_SCAN_ENABLE_3RANKS) \ - || ((__INJ_SEQ_SCAN_LENGTH__) == LL_ADC_INJ_SEQ_SCAN_ENABLE_4RANKS) \ - ) - -#define IS_LL_ADC_INJ_SEQ_SCAN_DISCONT_MODE(__INJ_SEQ_DISCONT_MODE__) \ - ( ((__INJ_SEQ_DISCONT_MODE__) == LL_ADC_INJ_SEQ_DISCONT_DISABLE) \ - || ((__INJ_SEQ_DISCONT_MODE__) == LL_ADC_INJ_SEQ_DISCONT_1RANK) \ - ) - -#if defined(ADC_MULTIMODE_SUPPORT) -/* Check of parameters for configuration of ADC hierarchical scope: */ -/* multimode. */ -#define IS_LL_ADC_MULTI_MODE(__MULTI_MODE__) \ - ( ((__MULTI_MODE__) == LL_ADC_MULTI_INDEPENDENT) \ - || ((__MULTI_MODE__) == LL_ADC_MULTI_DUAL_REG_SIMULT) \ - || ((__MULTI_MODE__) == LL_ADC_MULTI_DUAL_REG_INTERL_FAST) \ - || ((__MULTI_MODE__) == LL_ADC_MULTI_DUAL_REG_INTERL_SLOW) \ - || ((__MULTI_MODE__) == LL_ADC_MULTI_DUAL_INJ_SIMULT) \ - || ((__MULTI_MODE__) == LL_ADC_MULTI_DUAL_INJ_ALTERN) \ - || ((__MULTI_MODE__) == LL_ADC_MULTI_DUAL_REG_SIM_INJ_SIM) \ - || ((__MULTI_MODE__) == LL_ADC_MULTI_DUAL_REG_SIM_INJ_ALT) \ - || ((__MULTI_MODE__) == LL_ADC_MULTI_DUAL_REG_INTFAST_INJ_SIM) \ - || ((__MULTI_MODE__) == LL_ADC_MULTI_DUAL_REG_INTSLOW_INJ_SIM) \ - ) - -#define IS_LL_ADC_MULTI_MASTER_SLAVE(__MULTI_MASTER_SLAVE__) \ - ( ((__MULTI_MASTER_SLAVE__) == LL_ADC_MULTI_MASTER) \ - || ((__MULTI_MASTER_SLAVE__) == LL_ADC_MULTI_SLAVE) \ - || ((__MULTI_MASTER_SLAVE__) == LL_ADC_MULTI_MASTER_SLAVE) \ - ) - -#endif /* ADC_MULTIMODE_SUPPORT */ -/** - * @} - */ - - -/* Private function prototypes -----------------------------------------------*/ - -/* Exported functions --------------------------------------------------------*/ -/** @addtogroup ADC_LL_Exported_Functions - * @{ - */ - -/** @addtogroup ADC_LL_EF_Init - * @{ - */ - -/** - * @brief De-initialize registers of all ADC instances belonging to - * the same ADC common instance to their default reset values. - * @param ADCxy_COMMON ADC common instance - * (can be set directly from CMSIS definition or by using helper macro @ref __LL_ADC_COMMON_INSTANCE() ) - * @retval An ErrorStatus enumeration value: - * - SUCCESS: ADC common registers are de-initialized - * - ERROR: not applicable - */ -ErrorStatus LL_ADC_CommonDeInit(ADC_Common_TypeDef *ADCxy_COMMON) -{ - /* Check the parameters */ - assert_param(IS_ADC_COMMON_INSTANCE(ADCxy_COMMON)); - - /* Force reset of ADC clock (core clock) */ - LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_ADC1); - - /* Release reset of ADC clock (core clock) */ - LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_ADC1); - - return SUCCESS; -} - -/** - * @brief Initialize some features of ADC common parameters - * (all ADC instances belonging to the same ADC common instance) - * and multimode (for devices with several ADC instances available). - * @note The setting of ADC common parameters is conditioned to - * ADC instances state: - * All ADC instances belonging to the same ADC common instance - * must be disabled. - * @param ADCxy_COMMON ADC common instance - * (can be set directly from CMSIS definition or by using helper macro @ref __LL_ADC_COMMON_INSTANCE() ) - * @param ADC_CommonInitStruct Pointer to a @ref LL_ADC_CommonInitTypeDef structure - * @retval An ErrorStatus enumeration value: - * - SUCCESS: ADC common registers are initialized - * - ERROR: ADC common registers are not initialized - */ -ErrorStatus LL_ADC_CommonInit(ADC_Common_TypeDef *ADCxy_COMMON, LL_ADC_CommonInitTypeDef *ADC_CommonInitStruct) -{ - ErrorStatus status = SUCCESS; - - /* Check the parameters */ - assert_param(IS_ADC_COMMON_INSTANCE(ADCxy_COMMON)); -#if defined(ADC_MULTIMODE_SUPPORT) - assert_param(IS_LL_ADC_MULTI_MODE(ADC_CommonInitStruct->Multimode)); -#endif /* ADC_MULTIMODE_SUPPORT */ - - /* Note: Hardware constraint (refer to description of functions */ - /* "LL_ADC_SetCommonXXX()" and "LL_ADC_SetMultiXXX()"): */ - /* On this STM32 serie, setting of these features is conditioned to */ - /* ADC state: */ - /* All ADC instances of the ADC common group must be disabled. */ - if(__LL_ADC_IS_ENABLED_ALL_COMMON_INSTANCE(ADCxy_COMMON) == 0U) - { - /* Configuration of ADC hierarchical scope: */ - /* - common to several ADC */ - /* (all ADC instances belonging to the same ADC common instance) */ - /* - multimode (if several ADC instances available on the */ - /* selected device) */ - /* - Set ADC multimode configuration */ - /* - Set ADC multimode DMA transfer */ - /* - Set ADC multimode: delay between 2 sampling phases */ -#if defined(ADC_MULTIMODE_SUPPORT) - if(ADC_CommonInitStruct->Multimode != LL_ADC_MULTI_INDEPENDENT) - { - MODIFY_REG(ADCxy_COMMON->CR1, - ADC_CR1_DUALMOD, - ADC_CommonInitStruct->Multimode - ); - } - else - { - MODIFY_REG(ADCxy_COMMON->CR1, - ADC_CR1_DUALMOD, - LL_ADC_MULTI_INDEPENDENT - ); - } -#endif - } - else - { - /* Initialization error: One or several ADC instances belonging to */ - /* the same ADC common instance are not disabled. */ - status = ERROR; - } - - return status; -} - -/** - * @brief Set each @ref LL_ADC_CommonInitTypeDef field to default value. - * @param ADC_CommonInitStruct Pointer to a @ref LL_ADC_CommonInitTypeDef structure - * whose fields will be set to default values. - * @retval None - */ -void LL_ADC_CommonStructInit(LL_ADC_CommonInitTypeDef *ADC_CommonInitStruct) -{ - /* Set ADC_CommonInitStruct fields to default values */ - /* Set fields of ADC common */ - /* (all ADC instances belonging to the same ADC common instance) */ - -#if defined(ADC_MULTIMODE_SUPPORT) - /* Set fields of ADC multimode */ - ADC_CommonInitStruct->Multimode = LL_ADC_MULTI_INDEPENDENT; -#endif /* ADC_MULTIMODE_SUPPORT */ -} - -/** - * @brief De-initialize registers of the selected ADC instance - * to their default reset values. - * @note To reset all ADC instances quickly (perform a hard reset), - * use function @ref LL_ADC_CommonDeInit(). - * @param ADCx ADC instance - * @retval An ErrorStatus enumeration value: - * - SUCCESS: ADC registers are de-initialized - * - ERROR: ADC registers are not de-initialized - */ -ErrorStatus LL_ADC_DeInit(ADC_TypeDef *ADCx) -{ - ErrorStatus status = SUCCESS; - - /* Check the parameters */ - assert_param(IS_ADC_ALL_INSTANCE(ADCx)); - - /* Disable ADC instance if not already disabled. */ - if(LL_ADC_IsEnabled(ADCx) == 1U) - { - /* Set ADC group regular trigger source to SW start to ensure to not */ - /* have an external trigger event occurring during the conversion stop */ - /* ADC disable process. */ - LL_ADC_REG_SetTriggerSource(ADCx, LL_ADC_REG_TRIG_SOFTWARE); - - /* Set ADC group injected trigger source to SW start to ensure to not */ - /* have an external trigger event occurring during the conversion stop */ - /* ADC disable process. */ - LL_ADC_INJ_SetTriggerSource(ADCx, LL_ADC_INJ_TRIG_SOFTWARE); - - /* Disable the ADC instance */ - LL_ADC_Disable(ADCx); - } - - /* Check whether ADC state is compliant with expected state */ - /* (hardware requirements of bits state to reset registers below) */ - if(READ_BIT(ADCx->CR2, ADC_CR2_ADON) == 0U) - { - /* ========== Reset ADC registers ========== */ - /* Reset register SR */ - CLEAR_BIT(ADCx->SR, - ( LL_ADC_FLAG_STRT - | LL_ADC_FLAG_JSTRT - | LL_ADC_FLAG_EOS - | LL_ADC_FLAG_JEOS - | LL_ADC_FLAG_AWD1 ) - ); - - /* Reset register CR1 */ - #if defined (STM32F103x6) || defined (STM32F103xB) || defined (STM32F105xC) || defined (STM32F107xC) || defined (STM32F103xE) || defined (STM32F103xG) - - CLEAR_BIT(ADCx->CR1, - ( ADC_CR1_AWDEN | ADC_CR1_JAWDEN | ADC_CR1_DUALMOD - | ADC_CR1_DISCNUM | ADC_CR1_JDISCEN | ADC_CR1_DISCEN - | ADC_CR1_JAUTO | ADC_CR1_AWDSGL | ADC_CR1_SCAN - | ADC_CR1_JEOCIE | ADC_CR1_AWDIE | ADC_CR1_EOCIE - | ADC_CR1_AWDCH ) - ); - #else - - CLEAR_BIT(ADCx->CR1, - ( ADC_CR1_AWDEN | ADC_CR1_JAWDEN | ADC_CR1_DISCNUM - | ADC_CR1_JDISCEN | ADC_CR1_DISCEN | ADC_CR1_JAUTO - | ADC_CR1_AWDSGL | ADC_CR1_SCAN | ADC_CR1_JEOCIE - | ADC_CR1_AWDIE | ADC_CR1_EOCIE | ADC_CR1_AWDCH ) - ); - #endif - - /* Reset register CR2 */ - CLEAR_BIT(ADCx->CR2, - ( ADC_CR2_TSVREFE - | ADC_CR2_SWSTART | ADC_CR2_EXTTRIG | ADC_CR2_EXTSEL - | ADC_CR2_JSWSTART | ADC_CR2_JEXTTRIG | ADC_CR2_JEXTSEL - | ADC_CR2_ALIGN | ADC_CR2_DMA - | ADC_CR2_RSTCAL | ADC_CR2_CAL - | ADC_CR2_CONT | ADC_CR2_ADON ) - ); - - /* Reset register SMPR1 */ - CLEAR_BIT(ADCx->SMPR1, - ( ADC_SMPR1_SMP17 | ADC_SMPR1_SMP16 - | ADC_SMPR1_SMP15 | ADC_SMPR1_SMP14 | ADC_SMPR1_SMP13 - | ADC_SMPR1_SMP12 | ADC_SMPR1_SMP11 | ADC_SMPR1_SMP10) - ); - - /* Reset register SMPR2 */ - CLEAR_BIT(ADCx->SMPR2, - ( ADC_SMPR2_SMP9 - | ADC_SMPR2_SMP8 | ADC_SMPR2_SMP7 | ADC_SMPR2_SMP6 - | ADC_SMPR2_SMP5 | ADC_SMPR2_SMP4 | ADC_SMPR2_SMP3 - | ADC_SMPR2_SMP2 | ADC_SMPR2_SMP1 | ADC_SMPR2_SMP0) - ); - - /* Reset register JOFR1 */ - CLEAR_BIT(ADCx->JOFR1, ADC_JOFR1_JOFFSET1); - /* Reset register JOFR2 */ - CLEAR_BIT(ADCx->JOFR2, ADC_JOFR2_JOFFSET2); - /* Reset register JOFR3 */ - CLEAR_BIT(ADCx->JOFR3, ADC_JOFR3_JOFFSET3); - /* Reset register JOFR4 */ - CLEAR_BIT(ADCx->JOFR4, ADC_JOFR4_JOFFSET4); - - /* Reset register HTR */ - SET_BIT(ADCx->HTR, ADC_HTR_HT); - /* Reset register LTR */ - CLEAR_BIT(ADCx->LTR, ADC_LTR_LT); - - /* Reset register SQR1 */ - CLEAR_BIT(ADCx->SQR1, - ( ADC_SQR1_L - | ADC_SQR1_SQ16 - | ADC_SQR1_SQ15 | ADC_SQR1_SQ14 | ADC_SQR1_SQ13) - ); - - /* Reset register SQR2 */ - CLEAR_BIT(ADCx->SQR2, - ( ADC_SQR2_SQ12 | ADC_SQR2_SQ11 | ADC_SQR2_SQ10 - | ADC_SQR2_SQ9 | ADC_SQR2_SQ8 | ADC_SQR2_SQ7) - ); - - - /* Reset register JSQR */ - CLEAR_BIT(ADCx->JSQR, - ( ADC_JSQR_JL - | ADC_JSQR_JSQ4 | ADC_JSQR_JSQ3 - | ADC_JSQR_JSQ2 | ADC_JSQR_JSQ1 ) - ); - - /* Reset register DR */ - /* bits in access mode read only, no direct reset applicable */ - - /* Reset registers JDR1, JDR2, JDR3, JDR4 */ - /* bits in access mode read only, no direct reset applicable */ - - } - - return status; -} - -/** - * @brief Initialize some features of ADC instance. - * @note These parameters have an impact on ADC scope: ADC instance. - * Affects both group regular and group injected (availability - * of ADC group injected depends on STM32 families). - * Refer to corresponding unitary functions into - * @ref ADC_LL_EF_Configuration_ADC_Instance . - * @note The setting of these parameters by function @ref LL_ADC_Init() - * is conditioned to ADC state: - * ADC instance must be disabled. - * This condition is applied to all ADC features, for efficiency - * and compatibility over all STM32 families. However, the different - * features can be set under different ADC state conditions - * (setting possible with ADC enabled without conversion on going, - * ADC enabled with conversion on going, ...) - * Each feature can be updated afterwards with a unitary function - * and potentially with ADC in a different state than disabled, - * refer to description of each function for setting - * conditioned to ADC state. - * @note After using this function, some other features must be configured - * using LL unitary functions. - * The minimum configuration remaining to be done is: - * - Set ADC group regular or group injected sequencer: - * map channel on the selected sequencer rank. - * Refer to function @ref LL_ADC_REG_SetSequencerRanks(). - * - Set ADC channel sampling time - * Refer to function LL_ADC_SetChannelSamplingTime(); - * @param ADCx ADC instance - * @param ADC_InitStruct Pointer to a @ref LL_ADC_REG_InitTypeDef structure - * @retval An ErrorStatus enumeration value: - * - SUCCESS: ADC registers are initialized - * - ERROR: ADC registers are not initialized - */ -ErrorStatus LL_ADC_Init(ADC_TypeDef *ADCx, LL_ADC_InitTypeDef *ADC_InitStruct) -{ - ErrorStatus status = SUCCESS; - - /* Check the parameters */ - assert_param(IS_ADC_ALL_INSTANCE(ADCx)); - - assert_param(IS_LL_ADC_DATA_ALIGN(ADC_InitStruct->DataAlignment)); - assert_param(IS_LL_ADC_SCAN_SELECTION(ADC_InitStruct->SequencersScanMode)); - - /* Note: Hardware constraint (refer to description of this function): */ - /* ADC instance must be disabled. */ - if(LL_ADC_IsEnabled(ADCx) == 0U) - { - /* Configuration of ADC hierarchical scope: */ - /* - ADC instance */ - /* - Set ADC conversion data alignment */ - MODIFY_REG(ADCx->CR1, - ADC_CR1_SCAN - , - ADC_InitStruct->SequencersScanMode - ); - - MODIFY_REG(ADCx->CR2, - ADC_CR2_ALIGN - , - ADC_InitStruct->DataAlignment - ); - - } - else - { - /* Initialization error: ADC instance is not disabled. */ - status = ERROR; - } - return status; -} - -/** - * @brief Set each @ref LL_ADC_InitTypeDef field to default value. - * @param ADC_InitStruct Pointer to a @ref LL_ADC_InitTypeDef structure - * whose fields will be set to default values. - * @retval None - */ -void LL_ADC_StructInit(LL_ADC_InitTypeDef *ADC_InitStruct) -{ - /* Set ADC_InitStruct fields to default values */ - /* Set fields of ADC instance */ - ADC_InitStruct->DataAlignment = LL_ADC_DATA_ALIGN_RIGHT; - - /* Enable scan mode to have a generic behavior with ADC of other */ - /* STM32 families, without this setting available: */ - /* ADC group regular sequencer and ADC group injected sequencer depend */ - /* only of their own configuration. */ - ADC_InitStruct->SequencersScanMode = LL_ADC_SEQ_SCAN_ENABLE; - -} - -/** - * @brief Initialize some features of ADC group regular. - * @note These parameters have an impact on ADC scope: ADC group regular. - * Refer to corresponding unitary functions into - * @ref ADC_LL_EF_Configuration_ADC_Group_Regular - * (functions with prefix "REG"). - * @note The setting of these parameters by function @ref LL_ADC_Init() - * is conditioned to ADC state: - * ADC instance must be disabled. - * This condition is applied to all ADC features, for efficiency - * and compatibility over all STM32 families. However, the different - * features can be set under different ADC state conditions - * (setting possible with ADC enabled without conversion on going, - * ADC enabled with conversion on going, ...) - * Each feature can be updated afterwards with a unitary function - * and potentially with ADC in a different state than disabled, - * refer to description of each function for setting - * conditioned to ADC state. - * @note After using this function, other features must be configured - * using LL unitary functions. - * The minimum configuration remaining to be done is: - * - Set ADC group regular or group injected sequencer: - * map channel on the selected sequencer rank. - * Refer to function @ref LL_ADC_REG_SetSequencerRanks(). - * - Set ADC channel sampling time - * Refer to function LL_ADC_SetChannelSamplingTime(); - * @param ADCx ADC instance - * @param ADC_REG_InitStruct Pointer to a @ref LL_ADC_REG_InitTypeDef structure - * @retval An ErrorStatus enumeration value: - * - SUCCESS: ADC registers are initialized - * - ERROR: ADC registers are not initialized - */ -ErrorStatus LL_ADC_REG_Init(ADC_TypeDef *ADCx, LL_ADC_REG_InitTypeDef *ADC_REG_InitStruct) -{ - ErrorStatus status = SUCCESS; - - /* Check the parameters */ - assert_param(IS_ADC_ALL_INSTANCE(ADCx)); -#if defined(ADC3) - assert_param(IS_LL_ADC_REG_TRIG_SOURCE(ADCx, ADC_REG_InitStruct->TriggerSource)); -#else - assert_param(IS_LL_ADC_REG_TRIG_SOURCE(ADC_REG_InitStruct->TriggerSource)); -#endif - assert_param(IS_LL_ADC_REG_SEQ_SCAN_LENGTH(ADC_REG_InitStruct->SequencerLength)); - if(ADC_REG_InitStruct->SequencerLength != LL_ADC_REG_SEQ_SCAN_DISABLE) - { - assert_param(IS_LL_ADC_REG_SEQ_SCAN_DISCONT_MODE(ADC_REG_InitStruct->SequencerDiscont)); - } - assert_param(IS_LL_ADC_REG_CONTINUOUS_MODE(ADC_REG_InitStruct->ContinuousMode)); - assert_param(IS_LL_ADC_REG_DMA_TRANSFER(ADC_REG_InitStruct->DMATransfer)); - - /* Note: Hardware constraint (refer to description of this function): */ - /* ADC instance must be disabled. */ - if(LL_ADC_IsEnabled(ADCx) == 0U) - { - /* Configuration of ADC hierarchical scope: */ - /* - ADC group regular */ - /* - Set ADC group regular trigger source */ - /* - Set ADC group regular sequencer length */ - /* - Set ADC group regular sequencer discontinuous mode */ - /* - Set ADC group regular continuous mode */ - /* - Set ADC group regular conversion data transfer: no transfer or */ - /* transfer by DMA, and DMA requests mode */ - /* Note: On this STM32 serie, ADC trigger edge is set when starting */ - /* ADC conversion. */ - /* Refer to function @ref LL_ADC_REG_StartConversionExtTrig(). */ - if(ADC_REG_InitStruct->SequencerLength != LL_ADC_REG_SEQ_SCAN_DISABLE) - { - MODIFY_REG(ADCx->CR1, - ADC_CR1_DISCEN - | ADC_CR1_DISCNUM - , - ADC_REG_InitStruct->SequencerLength - | ADC_REG_InitStruct->SequencerDiscont - ); - } - else - { - MODIFY_REG(ADCx->CR1, - ADC_CR1_DISCEN - | ADC_CR1_DISCNUM - , - ADC_REG_InitStruct->SequencerLength - | LL_ADC_REG_SEQ_DISCONT_DISABLE - ); - } - - MODIFY_REG(ADCx->CR2, - ADC_CR2_EXTSEL - | ADC_CR2_CONT - | ADC_CR2_DMA - , - ADC_REG_InitStruct->TriggerSource - | ADC_REG_InitStruct->ContinuousMode - | ADC_REG_InitStruct->DMATransfer - ); - - /* Set ADC group regular sequencer length and scan direction */ - /* Note: Hardware constraint (refer to description of this function): */ - /* Note: If ADC instance feature scan mode is disabled */ - /* (refer to ADC instance initialization structure */ - /* parameter @ref SequencersScanMode */ - /* or function @ref LL_ADC_SetSequencersScanMode() ), */ - /* this parameter is discarded. */ - LL_ADC_REG_SetSequencerLength(ADCx, ADC_REG_InitStruct->SequencerLength); - } - else - { - /* Initialization error: ADC instance is not disabled. */ - status = ERROR; - } - return status; -} - -/** - * @brief Set each @ref LL_ADC_REG_InitTypeDef field to default value. - * @param ADC_REG_InitStruct Pointer to a @ref LL_ADC_REG_InitTypeDef structure - * whose fields will be set to default values. - * @retval None - */ -void LL_ADC_REG_StructInit(LL_ADC_REG_InitTypeDef *ADC_REG_InitStruct) -{ - /* Set ADC_REG_InitStruct fields to default values */ - /* Set fields of ADC group regular */ - /* Note: On this STM32 serie, ADC trigger edge is set when starting */ - /* ADC conversion. */ - /* Refer to function @ref LL_ADC_REG_StartConversionExtTrig(). */ - ADC_REG_InitStruct->TriggerSource = LL_ADC_REG_TRIG_SOFTWARE; - ADC_REG_InitStruct->SequencerLength = LL_ADC_REG_SEQ_SCAN_DISABLE; - ADC_REG_InitStruct->SequencerDiscont = LL_ADC_REG_SEQ_DISCONT_DISABLE; - ADC_REG_InitStruct->ContinuousMode = LL_ADC_REG_CONV_SINGLE; - ADC_REG_InitStruct->DMATransfer = LL_ADC_REG_DMA_TRANSFER_NONE; -} - -/** - * @brief Initialize some features of ADC group injected. - * @note These parameters have an impact on ADC scope: ADC group injected. - * Refer to corresponding unitary functions into - * @ref ADC_LL_EF_Configuration_ADC_Group_Regular - * (functions with prefix "INJ"). - * @note The setting of these parameters by function @ref LL_ADC_Init() - * is conditioned to ADC state: - * ADC instance must be disabled. - * This condition is applied to all ADC features, for efficiency - * and compatibility over all STM32 families. However, the different - * features can be set under different ADC state conditions - * (setting possible with ADC enabled without conversion on going, - * ADC enabled with conversion on going, ...) - * Each feature can be updated afterwards with a unitary function - * and potentially with ADC in a different state than disabled, - * refer to description of each function for setting - * conditioned to ADC state. - * @note After using this function, other features must be configured - * using LL unitary functions. - * The minimum configuration remaining to be done is: - * - Set ADC group injected sequencer: - * map channel on the selected sequencer rank. - * Refer to function @ref LL_ADC_INJ_SetSequencerRanks(). - * - Set ADC channel sampling time - * Refer to function LL_ADC_SetChannelSamplingTime(); - * @param ADCx ADC instance - * @param ADC_INJ_InitStruct Pointer to a @ref LL_ADC_INJ_InitTypeDef structure - * @retval An ErrorStatus enumeration value: - * - SUCCESS: ADC registers are initialized - * - ERROR: ADC registers are not initialized - */ -ErrorStatus LL_ADC_INJ_Init(ADC_TypeDef *ADCx, LL_ADC_INJ_InitTypeDef *ADC_INJ_InitStruct) -{ - ErrorStatus status = SUCCESS; - - /* Check the parameters */ - assert_param(IS_ADC_ALL_INSTANCE(ADCx)); -#if defined(ADC3) - assert_param(IS_LL_ADC_INJ_TRIG_SOURCE(ADCx, ADC_INJ_InitStruct->TriggerSource)); -#else - assert_param(IS_LL_ADC_INJ_TRIG_SOURCE(ADC_INJ_InitStruct->TriggerSource)); -#endif - assert_param(IS_LL_ADC_INJ_SEQ_SCAN_LENGTH(ADC_INJ_InitStruct->SequencerLength)); - if(ADC_INJ_InitStruct->SequencerLength != LL_ADC_INJ_SEQ_SCAN_DISABLE) - { - assert_param(IS_LL_ADC_INJ_SEQ_SCAN_DISCONT_MODE(ADC_INJ_InitStruct->SequencerDiscont)); - } - assert_param(IS_LL_ADC_INJ_TRIG_AUTO(ADC_INJ_InitStruct->TrigAuto)); - - /* Note: Hardware constraint (refer to description of this function): */ - /* ADC instance must be disabled. */ - if(LL_ADC_IsEnabled(ADCx) == 0U) - { - /* Configuration of ADC hierarchical scope: */ - /* - ADC group injected */ - /* - Set ADC group injected trigger source */ - /* - Set ADC group injected sequencer length */ - /* - Set ADC group injected sequencer discontinuous mode */ - /* - Set ADC group injected conversion trigger: independent or */ - /* from ADC group regular */ - /* Note: On this STM32 serie, ADC trigger edge is set when starting */ - /* ADC conversion. */ - /* Refer to function @ref LL_ADC_INJ_StartConversionExtTrig(). */ - if(ADC_INJ_InitStruct->SequencerLength != LL_ADC_REG_SEQ_SCAN_DISABLE) - { - MODIFY_REG(ADCx->CR1, - ADC_CR1_JDISCEN - | ADC_CR1_JAUTO - , - ADC_INJ_InitStruct->SequencerDiscont - | ADC_INJ_InitStruct->TrigAuto - ); - } - else - { - MODIFY_REG(ADCx->CR1, - ADC_CR1_JDISCEN - | ADC_CR1_JAUTO - , - LL_ADC_REG_SEQ_DISCONT_DISABLE - | ADC_INJ_InitStruct->TrigAuto - ); - } - - MODIFY_REG(ADCx->CR2, - ADC_CR2_JEXTSEL - , - ADC_INJ_InitStruct->TriggerSource - ); - - /* Note: Hardware constraint (refer to description of this function): */ - /* Note: If ADC instance feature scan mode is disabled */ - /* (refer to ADC instance initialization structure */ - /* parameter @ref SequencersScanMode */ - /* or function @ref LL_ADC_SetSequencersScanMode() ), */ - /* this parameter is discarded. */ - LL_ADC_INJ_SetSequencerLength(ADCx, ADC_INJ_InitStruct->SequencerLength); - } - else - { - /* Initialization error: ADC instance is not disabled. */ - status = ERROR; - } - return status; -} - -/** - * @brief Set each @ref LL_ADC_INJ_InitTypeDef field to default value. - * @param ADC_INJ_InitStruct Pointer to a @ref LL_ADC_INJ_InitTypeDef structure - * whose fields will be set to default values. - * @retval None - */ -void LL_ADC_INJ_StructInit(LL_ADC_INJ_InitTypeDef *ADC_INJ_InitStruct) -{ - /* Set ADC_INJ_InitStruct fields to default values */ - /* Set fields of ADC group injected */ - ADC_INJ_InitStruct->TriggerSource = LL_ADC_INJ_TRIG_SOFTWARE; - ADC_INJ_InitStruct->SequencerLength = LL_ADC_INJ_SEQ_SCAN_DISABLE; - ADC_INJ_InitStruct->SequencerDiscont = LL_ADC_INJ_SEQ_DISCONT_DISABLE; - ADC_INJ_InitStruct->TrigAuto = LL_ADC_INJ_TRIG_INDEPENDENT; -} - -/** - * @} - */ - -/** - * @} - */ - -/** - * @} - */ - -#endif /* ADC1 || ADC2 || ADC3 */ - -/** - * @} - */ - -#endif /* USE_FULL_LL_DRIVER */ - -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_adc.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_adc.h deleted file mode 100644 index b0c7a490dcf..00000000000 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_adc.h +++ /dev/null @@ -1,3950 +0,0 @@ -/** - ****************************************************************************** - * @file stm32f1xx_ll_adc.h - * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 - * @brief Header file of ADC LL module. - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2017 STMicroelectronics

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ - -/* Define to prevent recursive inclusion -------------------------------------*/ -#ifndef __STM32F1xx_LL_ADC_H -#define __STM32F1xx_LL_ADC_H - -#ifdef __cplusplus -extern "C" { -#endif - -/* Includes ------------------------------------------------------------------*/ -#include "stm32f1xx.h" - -/** @addtogroup STM32F1xx_LL_Driver - * @{ - */ - -#if defined (ADC1) || defined (ADC2) || defined (ADC3) - -/** @defgroup ADC_LL ADC - * @{ - */ - -/* Private types -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ - -/* Private constants ---------------------------------------------------------*/ -/** @defgroup ADC_LL_Private_Constants ADC Private Constants - * @{ - */ - -/* Internal mask for ADC group regular sequencer: */ -/* To select into literal LL_ADC_REG_RANK_x the relevant bits for: */ -/* - sequencer register offset */ -/* - sequencer rank bits position into the selected register */ - -/* Internal register offset for ADC group regular sequencer configuration */ -/* (offset placed into a spare area of literal definition) */ -#define ADC_SQR1_REGOFFSET 0x00000000U -#define ADC_SQR2_REGOFFSET 0x00000100U -#define ADC_SQR3_REGOFFSET 0x00000200U -#define ADC_SQR4_REGOFFSET 0x00000300U - -#define ADC_REG_SQRX_REGOFFSET_MASK (ADC_SQR1_REGOFFSET | ADC_SQR2_REGOFFSET | ADC_SQR3_REGOFFSET | ADC_SQR4_REGOFFSET) -#define ADC_REG_RANK_ID_SQRX_MASK (ADC_CHANNEL_ID_NUMBER_MASK_POSBIT0) - -/* Definition of ADC group regular sequencer bits information to be inserted */ -/* into ADC group regular sequencer ranks literals definition. */ -#define ADC_REG_RANK_1_SQRX_BITOFFSET_POS ( 0U) /* Value equivalent to POSITION_VAL(ADC_SQR3_SQ1) */ -#define ADC_REG_RANK_2_SQRX_BITOFFSET_POS ( 5U) /* Value equivalent to POSITION_VAL(ADC_SQR3_SQ2) */ -#define ADC_REG_RANK_3_SQRX_BITOFFSET_POS (10U) /* Value equivalent to POSITION_VAL(ADC_SQR3_SQ3) */ -#define ADC_REG_RANK_4_SQRX_BITOFFSET_POS (15U) /* Value equivalent to POSITION_VAL(ADC_SQR3_SQ4) */ -#define ADC_REG_RANK_5_SQRX_BITOFFSET_POS (20U) /* Value equivalent to POSITION_VAL(ADC_SQR3_SQ5) */ -#define ADC_REG_RANK_6_SQRX_BITOFFSET_POS (25U) /* Value equivalent to POSITION_VAL(ADC_SQR3_SQ6) */ -#define ADC_REG_RANK_7_SQRX_BITOFFSET_POS ( 0U) /* Value equivalent to POSITION_VAL(ADC_SQR2_SQ7) */ -#define ADC_REG_RANK_8_SQRX_BITOFFSET_POS ( 5U) /* Value equivalent to POSITION_VAL(ADC_SQR2_SQ8) */ -#define ADC_REG_RANK_9_SQRX_BITOFFSET_POS (10U) /* Value equivalent to POSITION_VAL(ADC_SQR2_SQ9) */ -#define ADC_REG_RANK_10_SQRX_BITOFFSET_POS (15U) /* Value equivalent to POSITION_VAL(ADC_SQR2_SQ10) */ -#define ADC_REG_RANK_11_SQRX_BITOFFSET_POS (20U) /* Value equivalent to POSITION_VAL(ADC_SQR2_SQ11) */ -#define ADC_REG_RANK_12_SQRX_BITOFFSET_POS (25U) /* Value equivalent to POSITION_VAL(ADC_SQR2_SQ12) */ -#define ADC_REG_RANK_13_SQRX_BITOFFSET_POS ( 0U) /* Value equivalent to POSITION_VAL(ADC_SQR1_SQ13) */ -#define ADC_REG_RANK_14_SQRX_BITOFFSET_POS ( 5U) /* Value equivalent to POSITION_VAL(ADC_SQR1_SQ14) */ -#define ADC_REG_RANK_15_SQRX_BITOFFSET_POS (10U) /* Value equivalent to POSITION_VAL(ADC_SQR1_SQ15) */ -#define ADC_REG_RANK_16_SQRX_BITOFFSET_POS (15U) /* Value equivalent to POSITION_VAL(ADC_SQR1_SQ16) */ - -/* Internal mask for ADC group injected sequencer: */ -/* To select into literal LL_ADC_INJ_RANK_x the relevant bits for: */ -/* - data register offset */ -/* - offset register offset */ -/* - sequencer rank bits position into the selected register */ - -/* Internal register offset for ADC group injected data register */ -/* (offset placed into a spare area of literal definition) */ -#define ADC_JDR1_REGOFFSET 0x00000000U -#define ADC_JDR2_REGOFFSET 0x00000100U -#define ADC_JDR3_REGOFFSET 0x00000200U -#define ADC_JDR4_REGOFFSET 0x00000300U - -/* Internal register offset for ADC group injected offset configuration */ -/* (offset placed into a spare area of literal definition) */ -#define ADC_JOFR1_REGOFFSET 0x00000000U -#define ADC_JOFR2_REGOFFSET 0x00001000U -#define ADC_JOFR3_REGOFFSET 0x00002000U -#define ADC_JOFR4_REGOFFSET 0x00003000U - -#define ADC_INJ_JDRX_REGOFFSET_MASK (ADC_JDR1_REGOFFSET | ADC_JDR2_REGOFFSET | ADC_JDR3_REGOFFSET | ADC_JDR4_REGOFFSET) -#define ADC_INJ_JOFRX_REGOFFSET_MASK (ADC_JOFR1_REGOFFSET | ADC_JOFR2_REGOFFSET | ADC_JOFR3_REGOFFSET | ADC_JOFR4_REGOFFSET) -#define ADC_INJ_RANK_ID_JSQR_MASK (ADC_CHANNEL_ID_NUMBER_MASK_POSBIT0) - -/* Internal mask for ADC channel: */ -/* To select into literal LL_ADC_CHANNEL_x the relevant bits for: */ -/* - channel identifier defined by number */ -/* - channel differentiation between external channels (connected to */ -/* GPIO pins) and internal channels (connected to internal paths) */ -/* - channel sampling time defined by SMPRx register offset */ -/* and SMPx bits positions into SMPRx register */ -#define ADC_CHANNEL_ID_NUMBER_MASK (ADC_CR1_AWDCH) -#define ADC_CHANNEL_ID_NUMBER_BITOFFSET_POS ( 0U)/* Value equivalent to POSITION_VAL(ADC_CHANNEL_ID_NUMBER_MASK) */ -#define ADC_CHANNEL_ID_MASK (ADC_CHANNEL_ID_NUMBER_MASK | ADC_CHANNEL_ID_INTERNAL_CH_MASK) -/* Equivalent mask of ADC_CHANNEL_NUMBER_MASK aligned on register LSB (bit 0) */ -#define ADC_CHANNEL_ID_NUMBER_MASK_POSBIT0 0x0000001FU /* Equivalent to shift: (ADC_CHANNEL_NUMBER_MASK >> POSITION_VAL(ADC_CHANNEL_NUMBER_MASK)) */ - -/* Channel differentiation between external and internal channels */ -#define ADC_CHANNEL_ID_INTERNAL_CH 0x80000000U /* Marker of internal channel */ -#define ADC_CHANNEL_ID_INTERNAL_CH_2 0x40000000U /* Marker of internal channel for other ADC instances, in case of different ADC internal channels mapped on same channel number on different ADC instances */ -#define ADC_CHANNEL_ID_INTERNAL_CH_MASK (ADC_CHANNEL_ID_INTERNAL_CH | ADC_CHANNEL_ID_INTERNAL_CH_2) - -/* Internal register offset for ADC channel sampling time configuration */ -/* (offset placed into a spare area of literal definition) */ -#define ADC_SMPR1_REGOFFSET 0x00000000U -#define ADC_SMPR2_REGOFFSET 0x02000000U -#define ADC_CHANNEL_SMPRX_REGOFFSET_MASK (ADC_SMPR1_REGOFFSET | ADC_SMPR2_REGOFFSET) - -#define ADC_CHANNEL_SMPx_BITOFFSET_MASK 0x01F00000U -#define ADC_CHANNEL_SMPx_BITOFFSET_POS (20U) /* Value equivalent to POSITION_VAL(ADC_CHANNEL_SMPx_BITOFFSET_MASK) */ - -/* Definition of channels ID number information to be inserted into */ -/* channels literals definition. */ -#define ADC_CHANNEL_0_NUMBER 0x00000000U -#define ADC_CHANNEL_1_NUMBER ( ADC_CR1_AWDCH_0) -#define ADC_CHANNEL_2_NUMBER ( ADC_CR1_AWDCH_1 ) -#define ADC_CHANNEL_3_NUMBER ( ADC_CR1_AWDCH_1 | ADC_CR1_AWDCH_0) -#define ADC_CHANNEL_4_NUMBER ( ADC_CR1_AWDCH_2 ) -#define ADC_CHANNEL_5_NUMBER ( ADC_CR1_AWDCH_2 | ADC_CR1_AWDCH_0) -#define ADC_CHANNEL_6_NUMBER ( ADC_CR1_AWDCH_2 | ADC_CR1_AWDCH_1 ) -#define ADC_CHANNEL_7_NUMBER ( ADC_CR1_AWDCH_2 | ADC_CR1_AWDCH_1 | ADC_CR1_AWDCH_0) -#define ADC_CHANNEL_8_NUMBER ( ADC_CR1_AWDCH_3 ) -#define ADC_CHANNEL_9_NUMBER ( ADC_CR1_AWDCH_3 | ADC_CR1_AWDCH_0) -#define ADC_CHANNEL_10_NUMBER ( ADC_CR1_AWDCH_3 | ADC_CR1_AWDCH_1 ) -#define ADC_CHANNEL_11_NUMBER ( ADC_CR1_AWDCH_3 | ADC_CR1_AWDCH_1 | ADC_CR1_AWDCH_0) -#define ADC_CHANNEL_12_NUMBER ( ADC_CR1_AWDCH_3 | ADC_CR1_AWDCH_2 ) -#define ADC_CHANNEL_13_NUMBER ( ADC_CR1_AWDCH_3 | ADC_CR1_AWDCH_2 | ADC_CR1_AWDCH_0) -#define ADC_CHANNEL_14_NUMBER ( ADC_CR1_AWDCH_3 | ADC_CR1_AWDCH_2 | ADC_CR1_AWDCH_1 ) -#define ADC_CHANNEL_15_NUMBER ( ADC_CR1_AWDCH_3 | ADC_CR1_AWDCH_2 | ADC_CR1_AWDCH_1 | ADC_CR1_AWDCH_0) -#define ADC_CHANNEL_16_NUMBER (ADC_CR1_AWDCH_4 ) -#define ADC_CHANNEL_17_NUMBER (ADC_CR1_AWDCH_4 | ADC_CR1_AWDCH_0) - -/* Definition of channels sampling time information to be inserted into */ -/* channels literals definition. */ -#define ADC_CHANNEL_0_SMP (ADC_SMPR2_REGOFFSET | (( 0U) << ADC_CHANNEL_SMPx_BITOFFSET_POS)) /* Value shifted is equivalent to POSITION_VAL(ADC_SMPR2_SMP0) */ -#define ADC_CHANNEL_1_SMP (ADC_SMPR2_REGOFFSET | (( 3U) << ADC_CHANNEL_SMPx_BITOFFSET_POS)) /* Value shifted is equivalent to POSITION_VAL(ADC_SMPR2_SMP1) */ -#define ADC_CHANNEL_2_SMP (ADC_SMPR2_REGOFFSET | (( 6U) << ADC_CHANNEL_SMPx_BITOFFSET_POS)) /* Value shifted is equivalent to POSITION_VAL(ADC_SMPR2_SMP2) */ -#define ADC_CHANNEL_3_SMP (ADC_SMPR2_REGOFFSET | (( 9U) << ADC_CHANNEL_SMPx_BITOFFSET_POS)) /* Value shifted is equivalent to POSITION_VAL(ADC_SMPR2_SMP3) */ -#define ADC_CHANNEL_4_SMP (ADC_SMPR2_REGOFFSET | ((12U) << ADC_CHANNEL_SMPx_BITOFFSET_POS)) /* Value shifted is equivalent to POSITION_VAL(ADC_SMPR2_SMP4) */ -#define ADC_CHANNEL_5_SMP (ADC_SMPR2_REGOFFSET | ((15U) << ADC_CHANNEL_SMPx_BITOFFSET_POS)) /* Value shifted is equivalent to POSITION_VAL(ADC_SMPR2_SMP5) */ -#define ADC_CHANNEL_6_SMP (ADC_SMPR2_REGOFFSET | ((18U) << ADC_CHANNEL_SMPx_BITOFFSET_POS)) /* Value shifted is equivalent to POSITION_VAL(ADC_SMPR2_SMP6) */ -#define ADC_CHANNEL_7_SMP (ADC_SMPR2_REGOFFSET | ((21U) << ADC_CHANNEL_SMPx_BITOFFSET_POS)) /* Value shifted is equivalent to POSITION_VAL(ADC_SMPR2_SMP7) */ -#define ADC_CHANNEL_8_SMP (ADC_SMPR2_REGOFFSET | ((24U) << ADC_CHANNEL_SMPx_BITOFFSET_POS)) /* Value shifted is equivalent to POSITION_VAL(ADC_SMPR2_SMP8) */ -#define ADC_CHANNEL_9_SMP (ADC_SMPR2_REGOFFSET | ((27U) << ADC_CHANNEL_SMPx_BITOFFSET_POS)) /* Value shifted is equivalent to POSITION_VAL(ADC_SMPR2_SMP9) */ -#define ADC_CHANNEL_10_SMP (ADC_SMPR1_REGOFFSET | (( 0U) << ADC_CHANNEL_SMPx_BITOFFSET_POS)) /* Value shifted is equivalent to POSITION_VAL(ADC_SMPR1_SMP10) */ -#define ADC_CHANNEL_11_SMP (ADC_SMPR1_REGOFFSET | (( 3U) << ADC_CHANNEL_SMPx_BITOFFSET_POS)) /* Value shifted is equivalent to POSITION_VAL(ADC_SMPR1_SMP11) */ -#define ADC_CHANNEL_12_SMP (ADC_SMPR1_REGOFFSET | (( 6U) << ADC_CHANNEL_SMPx_BITOFFSET_POS)) /* Value shifted is equivalent to POSITION_VAL(ADC_SMPR1_SMP12) */ -#define ADC_CHANNEL_13_SMP (ADC_SMPR1_REGOFFSET | (( 9U) << ADC_CHANNEL_SMPx_BITOFFSET_POS)) /* Value shifted is equivalent to POSITION_VAL(ADC_SMPR1_SMP13) */ -#define ADC_CHANNEL_14_SMP (ADC_SMPR1_REGOFFSET | ((12U) << ADC_CHANNEL_SMPx_BITOFFSET_POS)) /* Value shifted is equivalent to POSITION_VAL(ADC_SMPR1_SMP14) */ -#define ADC_CHANNEL_15_SMP (ADC_SMPR1_REGOFFSET | ((15U) << ADC_CHANNEL_SMPx_BITOFFSET_POS)) /* Value shifted is equivalent to POSITION_VAL(ADC_SMPR1_SMP15) */ -#define ADC_CHANNEL_16_SMP (ADC_SMPR1_REGOFFSET | ((18U) << ADC_CHANNEL_SMPx_BITOFFSET_POS)) /* Value shifted is equivalent to POSITION_VAL(ADC_SMPR1_SMP16) */ -#define ADC_CHANNEL_17_SMP (ADC_SMPR1_REGOFFSET | ((21U) << ADC_CHANNEL_SMPx_BITOFFSET_POS)) /* Value shifted is equivalent to POSITION_VAL(ADC_SMPR1_SMP17) */ - -/* Internal mask for ADC analog watchdog: */ -/* To select into literals LL_ADC_AWD_CHANNELx_xxx the relevant bits for: */ -/* (concatenation of multiple bits used in different analog watchdogs, */ -/* (feature of several watchdogs not available on all STM32 families)). */ -/* - analog watchdog 1: monitored channel defined by number, */ -/* selection of ADC group (ADC groups regular and-or injected). */ - -/* Internal register offset for ADC analog watchdog channel configuration */ -#define ADC_AWD_CR1_REGOFFSET 0x00000000U - -#define ADC_AWD_CRX_REGOFFSET_MASK (ADC_AWD_CR1_REGOFFSET) - -#define ADC_AWD_CR1_CHANNEL_MASK (ADC_CR1_AWDCH | ADC_CR1_JAWDEN | ADC_CR1_AWDEN | ADC_CR1_AWDSGL) -#define ADC_AWD_CR_ALL_CHANNEL_MASK (ADC_AWD_CR1_CHANNEL_MASK) - -/* Internal register offset for ADC analog watchdog threshold configuration */ -#define ADC_AWD_TR1_HIGH_REGOFFSET 0x00000000U -#define ADC_AWD_TR1_LOW_REGOFFSET 0x00000001U -#define ADC_AWD_TRX_REGOFFSET_MASK (ADC_AWD_TR1_HIGH_REGOFFSET | ADC_AWD_TR1_LOW_REGOFFSET) - -/* ADC registers bits positions */ -#define ADC_CR1_DUALMOD_BITOFFSET_POS (16U) /* Value equivalent to POSITION_VAL(ADC_CR1_DUALMOD) */ - -/** - * @} - */ - - -/* Private macros ------------------------------------------------------------*/ -/** @defgroup ADC_LL_Private_Macros ADC Private Macros - * @{ - */ - -/** - * @brief Driver macro reserved for internal use: isolate bits with the - * selected mask and shift them to the register LSB - * (shift mask on register position bit 0). - * @param __BITS__ Bits in register 32 bits - * @param __MASK__ Mask in register 32 bits - * @retval Bits in register 32 bits - */ -#define __ADC_MASK_SHIFT(__BITS__, __MASK__) \ - (((__BITS__) & (__MASK__)) >> POSITION_VAL((__MASK__))) - -/** - * @brief Driver macro reserved for internal use: set a pointer to - * a register from a register basis from which an offset - * is applied. - * @param __REG__ Register basis from which the offset is applied. - * @param __REG_OFFFSET__ Offset to be applied (unit: number of registers). - * @retval Pointer to register address - */ -#define __ADC_PTR_REG_OFFSET(__REG__, __REG_OFFFSET__) \ - ((uint32_t *)((uint32_t) ((uint32_t)(&(__REG__)) + ((__REG_OFFFSET__) << 2U)))) - -/** - * @} - */ - - -/* Exported types ------------------------------------------------------------*/ -#if defined(USE_FULL_LL_DRIVER) -/** @defgroup ADC_LL_ES_INIT ADC Exported Init structure - * @{ - */ - -/** - * @brief Structure definition of some features of ADC common parameters - * and multimode - * (all ADC instances belonging to the same ADC common instance). - * @note The setting of these parameters by function @ref LL_ADC_CommonInit() - * is conditioned to ADC instances state (all ADC instances - * sharing the same ADC common instance): - * All ADC instances sharing the same ADC common instance must be - * disabled. - */ -typedef struct -{ - uint32_t Multimode; /*!< Set ADC multimode configuration to operate in independent mode or multimode (for devices with several ADC instances). - This parameter can be a value of @ref ADC_LL_EC_MULTI_MODE - - This feature can be modified afterwards using unitary function @ref LL_ADC_SetMultimode(). */ -} LL_ADC_CommonInitTypeDef; -/** - * @brief Structure definition of some features of ADC instance. - * @note These parameters have an impact on ADC scope: ADC instance. - * Affects both group regular and group injected (availability - * of ADC group injected depends on STM32 families). - * Refer to corresponding unitary functions into - * @ref ADC_LL_EF_Configuration_ADC_Instance . - * @note The setting of these parameters by function @ref LL_ADC_Init() - * is conditioned to ADC state: - * ADC instance must be disabled. - * This condition is applied to all ADC features, for efficiency - * and compatibility over all STM32 families. However, the different - * features can be set under different ADC state conditions - * (setting possible with ADC enabled without conversion on going, - * ADC enabled with conversion on going, ...) - * Each feature can be updated afterwards with a unitary function - * and potentially with ADC in a different state than disabled, - * refer to description of each function for setting - * conditioned to ADC state. - */ -typedef struct -{ - uint32_t DataAlignment; /*!< Set ADC conversion data alignment. - This parameter can be a value of @ref ADC_LL_EC_DATA_ALIGN - - This feature can be modified afterwards using unitary function @ref LL_ADC_SetDataAlignment(). */ - - uint32_t SequencersScanMode; /*!< Set ADC scan selection. - This parameter can be a value of @ref ADC_LL_EC_SCAN_SELECTION - - This feature can be modified afterwards using unitary function @ref LL_ADC_SetSequencersScanMode(). */ - -} LL_ADC_InitTypeDef; - -/** - * @brief Structure definition of some features of ADC group regular. - * @note These parameters have an impact on ADC scope: ADC group regular. - * Refer to corresponding unitary functions into - * @ref ADC_LL_EF_Configuration_ADC_Group_Regular - * (functions with prefix "REG"). - * @note The setting of these parameters by function @ref LL_ADC_REG_Init() - * is conditioned to ADC state: - * ADC instance must be disabled. - * This condition is applied to all ADC features, for efficiency - * and compatibility over all STM32 families. However, the different - * features can be set under different ADC state conditions - * (setting possible with ADC enabled without conversion on going, - * ADC enabled with conversion on going, ...) - * Each feature can be updated afterwards with a unitary function - * and potentially with ADC in a different state than disabled, - * refer to description of each function for setting - * conditioned to ADC state. - */ -typedef struct -{ - uint32_t TriggerSource; /*!< Set ADC group regular conversion trigger source: internal (SW start) or from external IP (timer event, external interrupt line). - This parameter can be a value of @ref ADC_LL_EC_REG_TRIGGER_SOURCE - @note On this STM32 serie, external trigger is set with trigger polarity: rising edge - (only trigger polarity available on this STM32 serie). - - This feature can be modified afterwards using unitary function @ref LL_ADC_REG_SetTriggerSource(). */ - - uint32_t SequencerLength; /*!< Set ADC group regular sequencer length. - This parameter can be a value of @ref ADC_LL_EC_REG_SEQ_SCAN_LENGTH - @note This parameter is discarded if scan mode is disabled (refer to parameter 'ADC_SequencersScanMode'). - - This feature can be modified afterwards using unitary function @ref LL_ADC_REG_SetSequencerLength(). */ - - uint32_t SequencerDiscont; /*!< Set ADC group regular sequencer discontinuous mode: sequence subdivided and scan conversions interrupted every selected number of ranks. - This parameter can be a value of @ref ADC_LL_EC_REG_SEQ_DISCONT_MODE - @note This parameter has an effect only if group regular sequencer is enabled - (scan length of 2 ranks or more). - - This feature can be modified afterwards using unitary function @ref LL_ADC_REG_SetSequencerDiscont(). */ - - uint32_t ContinuousMode; /*!< Set ADC continuous conversion mode on ADC group regular, whether ADC conversions are performed in single mode (one conversion per trigger) or in continuous mode (after the first trigger, following conversions launched successively automatically). - This parameter can be a value of @ref ADC_LL_EC_REG_CONTINUOUS_MODE - Note: It is not possible to enable both ADC group regular continuous mode and discontinuous mode. - - This feature can be modified afterwards using unitary function @ref LL_ADC_REG_SetContinuousMode(). */ - - uint32_t DMATransfer; /*!< Set ADC group regular conversion data transfer: no transfer or transfer by DMA, and DMA requests mode. - This parameter can be a value of @ref ADC_LL_EC_REG_DMA_TRANSFER - - This feature can be modified afterwards using unitary function @ref LL_ADC_REG_SetDMATransfer(). */ - -} LL_ADC_REG_InitTypeDef; - -/** - * @brief Structure definition of some features of ADC group injected. - * @note These parameters have an impact on ADC scope: ADC group injected. - * Refer to corresponding unitary functions into - * @ref ADC_LL_EF_Configuration_ADC_Group_Regular - * (functions with prefix "INJ"). - * @note The setting of these parameters by function @ref LL_ADC_INJ_Init() - * is conditioned to ADC state: - * ADC instance must be disabled. - * This condition is applied to all ADC features, for efficiency - * and compatibility over all STM32 families. However, the different - * features can be set under different ADC state conditions - * (setting possible with ADC enabled without conversion on going, - * ADC enabled with conversion on going, ...) - * Each feature can be updated afterwards with a unitary function - * and potentially with ADC in a different state than disabled, - * refer to description of each function for setting - * conditioned to ADC state. - */ -typedef struct -{ - uint32_t TriggerSource; /*!< Set ADC group injected conversion trigger source: internal (SW start) or from external IP (timer event, external interrupt line). - This parameter can be a value of @ref ADC_LL_EC_INJ_TRIGGER_SOURCE - @note On this STM32 serie, external trigger is set with trigger polarity: rising edge - (only trigger polarity available on this STM32 serie). - - This feature can be modified afterwards using unitary function @ref LL_ADC_INJ_SetTriggerSource(). */ - - uint32_t SequencerLength; /*!< Set ADC group injected sequencer length. - This parameter can be a value of @ref ADC_LL_EC_INJ_SEQ_SCAN_LENGTH - @note This parameter is discarded if scan mode is disabled (refer to parameter 'ADC_SequencersScanMode'). - - This feature can be modified afterwards using unitary function @ref LL_ADC_INJ_SetSequencerLength(). */ - - uint32_t SequencerDiscont; /*!< Set ADC group injected sequencer discontinuous mode: sequence subdivided and scan conversions interrupted every selected number of ranks. - This parameter can be a value of @ref ADC_LL_EC_INJ_SEQ_DISCONT_MODE - @note This parameter has an effect only if group injected sequencer is enabled - (scan length of 2 ranks or more). - - This feature can be modified afterwards using unitary function @ref LL_ADC_INJ_SetSequencerDiscont(). */ - - uint32_t TrigAuto; /*!< Set ADC group injected conversion trigger: independent or from ADC group regular. - This parameter can be a value of @ref ADC_LL_EC_INJ_TRIG_AUTO - Note: This parameter must be set to set to independent trigger if injected trigger source is set to an external trigger. - - This feature can be modified afterwards using unitary function @ref LL_ADC_INJ_SetTrigAuto(). */ - -} LL_ADC_INJ_InitTypeDef; - -/** - * @} - */ -#endif /* USE_FULL_LL_DRIVER */ - -/* Exported constants --------------------------------------------------------*/ -/** @defgroup ADC_LL_Exported_Constants ADC Exported Constants - * @{ - */ - -/** @defgroup ADC_LL_EC_FLAG ADC flags - * @brief Flags defines which can be used with LL_ADC_ReadReg function - * @{ - */ -#define LL_ADC_FLAG_STRT ADC_SR_STRT /*!< ADC flag ADC group regular conversion start */ -#define LL_ADC_FLAG_EOS ADC_SR_EOC /*!< ADC flag ADC group regular end of sequence conversions (Note: on this STM32 serie, there is no flag ADC group regular end of unitary conversion. Flag noted as "EOC" is corresponding to flag "EOS" in other STM32 families) */ -#define LL_ADC_FLAG_JSTRT ADC_SR_JSTRT /*!< ADC flag ADC group injected conversion start */ -#define LL_ADC_FLAG_JEOS ADC_SR_JEOC /*!< ADC flag ADC group injected end of sequence conversions (Note: on this STM32 serie, there is no flag ADC group injected end of unitary conversion. Flag noted as "JEOC" is corresponding to flag "JEOS" in other STM32 families) */ -#define LL_ADC_FLAG_AWD1 ADC_SR_AWD /*!< ADC flag ADC analog watchdog 1 */ -#if defined(ADC_MULTIMODE_SUPPORT) -#define LL_ADC_FLAG_EOS_MST ADC_SR_EOC /*!< ADC flag ADC multimode master group regular end of sequence conversions (Note: on this STM32 serie, there is no flag ADC group regular end of unitary conversion. Flag noted as "EOC" is corresponding to flag "EOS" in other STM32 families) */ -#define LL_ADC_FLAG_EOS_SLV ADC_SR_EOC /*!< ADC flag ADC multimode slave group regular end of sequence conversions (Note: on this STM32 serie, there is no flag ADC group regular end of unitary conversion. Flag noted as "EOC" is corresponding to flag "EOS" in other STM32 families) (on STM32F1, this flag must be read from ADC instance slave: ADC2) */ -#define LL_ADC_FLAG_JEOS_MST ADC_SR_JEOC /*!< ADC flag ADC multimode master group injected end of sequence conversions (Note: on this STM32 serie, there is no flag ADC group injected end of unitary conversion. Flag noted as "JEOC" is corresponding to flag "JEOS" in other STM32 families) */ -#define LL_ADC_FLAG_JEOS_SLV ADC_SR_JEOC /*!< ADC flag ADC multimode slave group injected end of sequence conversions (Note: on this STM32 serie, there is no flag ADC group injected end of unitary conversion. Flag noted as "JEOC" is corresponding to flag "JEOS" in other STM32 families) (on STM32F1, this flag must be read from ADC instance slave: ADC2) */ -#define LL_ADC_FLAG_AWD1_MST ADC_SR_AWD /*!< ADC flag ADC multimode master analog watchdog 1 of the ADC master */ -#define LL_ADC_FLAG_AWD1_SLV ADC_SR_AWD /*!< ADC flag ADC multimode slave analog watchdog 1 of the ADC slave (on STM32F1, this flag must be read from ADC instance slave: ADC2) */ -#endif -/** - * @} - */ - -/** @defgroup ADC_LL_EC_IT ADC interruptions for configuration (interruption enable or disable) - * @brief IT defines which can be used with LL_ADC_ReadReg and LL_ADC_WriteReg functions - * @{ - */ -#define LL_ADC_IT_EOS ADC_CR1_EOCIE /*!< ADC interruption ADC group regular end of sequence conversions (Note: on this STM32 serie, there is no flag ADC group regular end of unitary conversion. Flag noted as "EOC" is corresponding to flag "EOS" in other STM32 families) */ -#define LL_ADC_IT_JEOS ADC_CR1_JEOCIE /*!< ADC interruption ADC group injected end of sequence conversions (Note: on this STM32 serie, there is no flag ADC group injected end of unitary conversion. Flag noted as "JEOC" is corresponding to flag "JEOS" in other STM32 families) */ -#define LL_ADC_IT_AWD1 ADC_CR1_AWDIE /*!< ADC interruption ADC analog watchdog 1 */ -/** - * @} - */ - -/** @defgroup ADC_LL_EC_REGISTERS ADC registers compliant with specific purpose - * @{ - */ -/* List of ADC registers intended to be used (most commonly) with */ -/* DMA transfer. */ -/* Refer to function @ref LL_ADC_DMA_GetRegAddr(). */ -#define LL_ADC_DMA_REG_REGULAR_DATA 0x00000000U /* ADC group regular conversion data register (corresponding to register DR) to be used with ADC configured in independent mode. Without DMA transfer, register accessed by LL function @ref LL_ADC_REG_ReadConversionData32() and other functions @ref LL_ADC_REG_ReadConversionDatax() */ -#if defined(ADC_MULTIMODE_SUPPORT) -#define LL_ADC_DMA_REG_REGULAR_DATA_MULTI 0x00000001U /* ADC group regular conversion data register (corresponding to register CDR) to be used with ADC configured in multimode (available on STM32 devices with several ADC instances). Without DMA transfer, register accessed by LL function @ref LL_ADC_REG_ReadMultiConversionData32() */ -#endif -/** - * @} - */ - -/** @defgroup ADC_LL_EC_COMMON_PATH_INTERNAL ADC common - Measurement path to internal channels - * @{ - */ -/* Note: Other measurement paths to internal channels may be available */ -/* (connections to other peripherals). */ -/* If they are not listed below, they do not require any specific */ -/* path enable. In this case, Access to measurement path is done */ -/* only by selecting the corresponding ADC internal channel. */ -#define LL_ADC_PATH_INTERNAL_NONE 0x00000000U /*!< ADC measurement pathes all disabled */ -#define LL_ADC_PATH_INTERNAL_VREFINT (ADC_CR2_TSVREFE) /*!< ADC measurement path to internal channel VrefInt */ -#define LL_ADC_PATH_INTERNAL_TEMPSENSOR (ADC_CR2_TSVREFE) /*!< ADC measurement path to internal channel temperature sensor */ -/** - * @} - */ - -/** @defgroup ADC_LL_EC_RESOLUTION ADC instance - Resolution - * @{ - */ -#define LL_ADC_RESOLUTION_12B 0x00000000U /*!< ADC resolution 12 bits */ -/** - * @} - */ - -/** @defgroup ADC_LL_EC_DATA_ALIGN ADC instance - Data alignment - * @{ - */ -#define LL_ADC_DATA_ALIGN_RIGHT 0x00000000U /*!< ADC conversion data alignment: right aligned (alignment on data register LSB bit 0)*/ -#define LL_ADC_DATA_ALIGN_LEFT (ADC_CR2_ALIGN) /*!< ADC conversion data alignment: left aligned (aligment on data register MSB bit 15)*/ -/** - * @} - */ - -/** @defgroup ADC_LL_EC_SCAN_SELECTION ADC instance - Scan selection - * @{ - */ -#define LL_ADC_SEQ_SCAN_DISABLE 0x00000000U /*!< ADC conversion is performed in unitary conversion mode (one channel converted, that defined in rank 1). Configuration of both groups regular and injected sequencers (sequence length, ...) is discarded: equivalent to length of 1 rank.*/ -#define LL_ADC_SEQ_SCAN_ENABLE (ADC_CR1_SCAN) /*!< ADC conversions are performed in sequence conversions mode, according to configuration of both groups regular and injected sequencers (sequence length, ...). */ -/** - * @} - */ - -/** @defgroup ADC_LL_EC_GROUPS ADC instance - Groups - * @{ - */ -#define LL_ADC_GROUP_REGULAR 0x00000001U /*!< ADC group regular (available on all STM32 devices) */ -#define LL_ADC_GROUP_INJECTED 0x00000002U /*!< ADC group injected (not available on all STM32 devices)*/ -#define LL_ADC_GROUP_REGULAR_INJECTED 0x00000003U /*!< ADC both groups regular and injected */ -/** - * @} - */ - -/** @defgroup ADC_LL_EC_CHANNEL ADC instance - Channel number - * @{ - */ -#define LL_ADC_CHANNEL_0 (ADC_CHANNEL_0_NUMBER | ADC_CHANNEL_0_SMP) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN0 */ -#define LL_ADC_CHANNEL_1 (ADC_CHANNEL_1_NUMBER | ADC_CHANNEL_1_SMP) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN1 */ -#define LL_ADC_CHANNEL_2 (ADC_CHANNEL_2_NUMBER | ADC_CHANNEL_2_SMP) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN2 */ -#define LL_ADC_CHANNEL_3 (ADC_CHANNEL_3_NUMBER | ADC_CHANNEL_3_SMP) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN3 */ -#define LL_ADC_CHANNEL_4 (ADC_CHANNEL_4_NUMBER | ADC_CHANNEL_4_SMP) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN4 */ -#define LL_ADC_CHANNEL_5 (ADC_CHANNEL_5_NUMBER | ADC_CHANNEL_5_SMP) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN5 */ -#define LL_ADC_CHANNEL_6 (ADC_CHANNEL_6_NUMBER | ADC_CHANNEL_6_SMP) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN6 */ -#define LL_ADC_CHANNEL_7 (ADC_CHANNEL_7_NUMBER | ADC_CHANNEL_7_SMP) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN7 */ -#define LL_ADC_CHANNEL_8 (ADC_CHANNEL_8_NUMBER | ADC_CHANNEL_8_SMP) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN8 */ -#define LL_ADC_CHANNEL_9 (ADC_CHANNEL_9_NUMBER | ADC_CHANNEL_9_SMP) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN9 */ -#define LL_ADC_CHANNEL_10 (ADC_CHANNEL_10_NUMBER | ADC_CHANNEL_10_SMP) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN10 */ -#define LL_ADC_CHANNEL_11 (ADC_CHANNEL_11_NUMBER | ADC_CHANNEL_11_SMP) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN11 */ -#define LL_ADC_CHANNEL_12 (ADC_CHANNEL_12_NUMBER | ADC_CHANNEL_12_SMP) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN12 */ -#define LL_ADC_CHANNEL_13 (ADC_CHANNEL_13_NUMBER | ADC_CHANNEL_13_SMP) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN13 */ -#define LL_ADC_CHANNEL_14 (ADC_CHANNEL_14_NUMBER | ADC_CHANNEL_14_SMP) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN14 */ -#define LL_ADC_CHANNEL_15 (ADC_CHANNEL_15_NUMBER | ADC_CHANNEL_15_SMP) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN15 */ -#define LL_ADC_CHANNEL_16 (ADC_CHANNEL_16_NUMBER | ADC_CHANNEL_16_SMP) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN16 */ -#define LL_ADC_CHANNEL_17 (ADC_CHANNEL_17_NUMBER | ADC_CHANNEL_17_SMP) /*!< ADC external channel (channel connected to GPIO pin) ADCx_IN17 */ -#define LL_ADC_CHANNEL_VREFINT (LL_ADC_CHANNEL_17 | ADC_CHANNEL_ID_INTERNAL_CH) /*!< ADC internal channel connected to VrefInt: Internal voltage reference. On STM32F1, ADC channel available only on ADC instance: ADC1. */ -#define LL_ADC_CHANNEL_TEMPSENSOR (LL_ADC_CHANNEL_16 | ADC_CHANNEL_ID_INTERNAL_CH) /*!< ADC internal channel connected to Temperature sensor. */ -/** - * @} - */ - -/** @defgroup ADC_LL_EC_REG_TRIGGER_SOURCE ADC group regular - Trigger source - * @{ - */ -/* ADC group regular external triggers for ADC instances: ADC1, ADC2, ADC3 (for ADC instances ADCx available on the selected device) */ -#define LL_ADC_REG_TRIG_SOFTWARE (ADC_CR2_EXTSEL_2 | ADC_CR2_EXTSEL_1 | ADC_CR2_EXTSEL_0) /*!< ADC group regular conversion trigger internal: SW start. */ -#define LL_ADC_REG_TRIG_EXT_TIM1_CH3 (ADC_CR2_EXTSEL_1) /*!< ADC group regular conversion trigger from external IP: TIM1 channel 3 event (capture compare: input capture or output capture). Trigger edge set to rising edge (default setting). */ -/* ADC group regular external triggers for ADC instances: ADC1, ADC2 (for ADC instances ADCx available on the selected device) */ -#define LL_ADC_REG_TRIG_EXT_TIM1_CH1 0x00000000U /*!< ADC group regular conversion trigger from external IP: TIM1 channel 1 event (capture compare: input capture or output capture). Trigger edge set to rising edge (default setting). */ -#define LL_ADC_REG_TRIG_EXT_TIM1_CH2 (ADC_CR2_EXTSEL_0) /*!< ADC group regular conversion trigger from external IP: TIM1 channel 2 event (capture compare: input capture or output capture). Trigger edge set to rising edge (default setting). */ -#define LL_ADC_REG_TRIG_EXT_TIM2_CH2 (ADC_CR2_EXTSEL_1 | ADC_CR2_EXTSEL_0) /*!< ADC group regular conversion trigger from external IP: TIM2 channel 2 event (capture compare: input capture or output capture). Trigger edge set to rising edge (default setting). */ -#define LL_ADC_REG_TRIG_EXT_TIM3_TRGO (ADC_CR2_EXTSEL_2) /*!< ADC group regular conversion trigger from external IP: TIM3 TRGO. Trigger edge set to rising edge (default setting). */ -#define LL_ADC_REG_TRIG_EXT_TIM4_CH4 (ADC_CR2_EXTSEL_2 | ADC_CR2_EXTSEL_0) /*!< ADC group regular conversion trigger from external IP: TIM4 channel 4 event (capture compare: input capture or output capture). Trigger edge set to rising edge (default setting). */ -#define LL_ADC_REG_TRIG_EXT_EXTI_LINE11 (ADC_CR2_EXTSEL_2 | ADC_CR2_EXTSEL_1) /*!< ADC group regular conversion trigger from external IP: external interrupt line 11. Trigger edge set to rising edge (default setting). */ -#if defined (STM32F101xE) || defined (STM32F103xE) || defined (STM32F103xG) || defined (STM32F105xC) || defined (STM32F107xC) -/* Note: TIM8_TRGO is available on ADC1 and ADC2 only in high-density and */ -/* XL-density devices. */ -/* Note: To use TIM8_TRGO on ADC1 or ADC2, a remap of trigger must be done */ -/* A remap of trigger must be done at top level (refer to */ -/* AFIO peripheral). */ -#define LL_ADC_REG_TRIG_EXT_TIM8_TRGO (LL_ADC_REG_TRIG_EXT_EXTI_LINE11) /*!< ADC group regular conversion trigger from external IP: TIM8 TRGO. Trigger edge set to rising edge (default setting). Available only on high-density and XL-density devices. A remap of trigger must be done at top level (refer to AFIO peripheral).*/ -#endif /* STM32F101xE || STM32F103xE || STM32F103xG || STM32F105xC || STM32F107xC */ -#if defined (STM32F103xE) || defined (STM32F103xG) -/* ADC group regular external triggers for ADC instances: ADC3 (for ADC instances ADCx available on the selected device) */ -#define LL_ADC_REG_TRIG_EXT_TIM3_CH1 (LL_ADC_REG_TRIG_EXT_TIM1_CH1) /*!< ADC group regular conversion trigger from external IP: TIM3 channel 1 event (capture compare: input capture or output capture). Trigger edge set to rising edge (default setting). */ -#define LL_ADC_REG_TRIG_EXT_TIM2_CH3 (LL_ADC_REG_TRIG_EXT_TIM1_CH2) /*!< ADC group regular conversion trigger from external IP: TIM2 channel 3 event (capture compare: input capture or output capture). Trigger edge set to rising edge (default setting). */ -#define LL_ADC_REG_TRIG_EXT_TIM8_CH1 (LL_ADC_REG_TRIG_EXT_TIM2_CH2) /*!< ADC group regular conversion trigger from external IP: TIM8 channel 1 event (capture compare: input capture or output capture). Trigger edge set to rising edge (default setting). */ -#define LL_ADC_REG_TRIG_EXT_TIM8_TRGO_ADC3 (LL_ADC_REG_TRIG_EXT_TIM3_TRGO) /*!< ADC group regular conversion trigger from external IP: TIM8 TRGO. Trigger edge set to rising edge (default setting). */ -#define LL_ADC_REG_TRIG_EXT_TIM5_CH1 (LL_ADC_REG_TRIG_EXT_TIM4_CH4) /*!< ADC group regular conversion trigger from external IP: TIM5 channel 1 event (capture compare: input capture or output capture). Trigger edge set to rising edge (default setting). */ -#define LL_ADC_REG_TRIG_EXT_TIM5_CH3 (LL_ADC_REG_TRIG_EXT_EXTI_LINE11) /*!< ADC group regular conversion trigger from external IP: TIM5 channel 3 event (capture compare: input capture or output capture). Trigger edge set to rising edge (default setting). */ -#endif -/** - * @} - */ - -/** @defgroup ADC_LL_EC_REG_TRIGGER_EDGE ADC group regular - Trigger edge - * @{ - */ -#define LL_ADC_REG_TRIG_EXT_RISING ADC_CR2_EXTTRIG /*!< ADC group regular conversion trigger polarity set to rising edge */ -/** - * @} - */ - -/** @defgroup ADC_LL_EC_REG_CONTINUOUS_MODE ADC group regular - Continuous mode -* @{ -*/ -#define LL_ADC_REG_CONV_SINGLE 0x00000000U /*!< ADC conversions are performed in single mode: one conversion per trigger */ -#define LL_ADC_REG_CONV_CONTINUOUS (ADC_CR2_CONT) /*!< ADC conversions are performed in continuous mode: after the first trigger, following conversions launched successively automatically */ -/** - * @} - */ - -/** @defgroup ADC_LL_EC_REG_DMA_TRANSFER ADC group regular - DMA transfer of ADC conversion data - * @{ - */ -#define LL_ADC_REG_DMA_TRANSFER_NONE 0x00000000U /*!< ADC conversions are not transferred by DMA */ -#define LL_ADC_REG_DMA_TRANSFER_UNLIMITED (ADC_CR2_DMA) /*!< ADC conversion data are transferred by DMA, in unlimited mode: DMA transfer requests are unlimited, whatever number of DMA data transferred (number of ADC conversions). This ADC mode is intended to be used with DMA mode circular. */ -/** - * @} - */ - -/** @defgroup ADC_LL_EC_REG_SEQ_SCAN_LENGTH ADC group regular - Sequencer scan length - * @{ - */ -#define LL_ADC_REG_SEQ_SCAN_DISABLE 0x00000000U /*!< ADC group regular sequencer disable (equivalent to sequencer of 1 rank: ADC conversion on only 1 channel) */ -#define LL_ADC_REG_SEQ_SCAN_ENABLE_2RANKS ( ADC_SQR1_L_0) /*!< ADC group regular sequencer enable with 2 ranks in the sequence */ -#define LL_ADC_REG_SEQ_SCAN_ENABLE_3RANKS ( ADC_SQR1_L_1 ) /*!< ADC group regular sequencer enable with 3 ranks in the sequence */ -#define LL_ADC_REG_SEQ_SCAN_ENABLE_4RANKS ( ADC_SQR1_L_1 | ADC_SQR1_L_0) /*!< ADC group regular sequencer enable with 4 ranks in the sequence */ -#define LL_ADC_REG_SEQ_SCAN_ENABLE_5RANKS ( ADC_SQR1_L_2 ) /*!< ADC group regular sequencer enable with 5 ranks in the sequence */ -#define LL_ADC_REG_SEQ_SCAN_ENABLE_6RANKS ( ADC_SQR1_L_2 | ADC_SQR1_L_0) /*!< ADC group regular sequencer enable with 6 ranks in the sequence */ -#define LL_ADC_REG_SEQ_SCAN_ENABLE_7RANKS ( ADC_SQR1_L_2 | ADC_SQR1_L_1 ) /*!< ADC group regular sequencer enable with 7 ranks in the sequence */ -#define LL_ADC_REG_SEQ_SCAN_ENABLE_8RANKS ( ADC_SQR1_L_2 | ADC_SQR1_L_1 | ADC_SQR1_L_0) /*!< ADC group regular sequencer enable with 8 ranks in the sequence */ -#define LL_ADC_REG_SEQ_SCAN_ENABLE_9RANKS (ADC_SQR1_L_3 ) /*!< ADC group regular sequencer enable with 9 ranks in the sequence */ -#define LL_ADC_REG_SEQ_SCAN_ENABLE_10RANKS (ADC_SQR1_L_3 | ADC_SQR1_L_0) /*!< ADC group regular sequencer enable with 10 ranks in the sequence */ -#define LL_ADC_REG_SEQ_SCAN_ENABLE_11RANKS (ADC_SQR1_L_3 | ADC_SQR1_L_1 ) /*!< ADC group regular sequencer enable with 11 ranks in the sequence */ -#define LL_ADC_REG_SEQ_SCAN_ENABLE_12RANKS (ADC_SQR1_L_3 | ADC_SQR1_L_1 | ADC_SQR1_L_0) /*!< ADC group regular sequencer enable with 12 ranks in the sequence */ -#define LL_ADC_REG_SEQ_SCAN_ENABLE_13RANKS (ADC_SQR1_L_3 | ADC_SQR1_L_2 ) /*!< ADC group regular sequencer enable with 13 ranks in the sequence */ -#define LL_ADC_REG_SEQ_SCAN_ENABLE_14RANKS (ADC_SQR1_L_3 | ADC_SQR1_L_2 | ADC_SQR1_L_0) /*!< ADC group regular sequencer enable with 14 ranks in the sequence */ -#define LL_ADC_REG_SEQ_SCAN_ENABLE_15RANKS (ADC_SQR1_L_3 | ADC_SQR1_L_2 | ADC_SQR1_L_1 ) /*!< ADC group regular sequencer enable with 15 ranks in the sequence */ -#define LL_ADC_REG_SEQ_SCAN_ENABLE_16RANKS (ADC_SQR1_L_3 | ADC_SQR1_L_2 | ADC_SQR1_L_1 | ADC_SQR1_L_0) /*!< ADC group regular sequencer enable with 16 ranks in the sequence */ -/** - * @} - */ - -/** @defgroup ADC_LL_EC_REG_SEQ_DISCONT_MODE ADC group regular - Sequencer discontinuous mode - * @{ - */ -#define LL_ADC_REG_SEQ_DISCONT_DISABLE 0x00000000U /*!< ADC group regular sequencer discontinuous mode disable */ -#define LL_ADC_REG_SEQ_DISCONT_1RANK ( ADC_CR1_DISCEN) /*!< ADC group regular sequencer discontinuous mode enable with sequence interruption every rank */ -#define LL_ADC_REG_SEQ_DISCONT_2RANKS ( ADC_CR1_DISCNUM_0 | ADC_CR1_DISCEN) /*!< ADC group regular sequencer discontinuous mode enabled with sequence interruption every 2 ranks */ -#define LL_ADC_REG_SEQ_DISCONT_3RANKS ( ADC_CR1_DISCNUM_1 | ADC_CR1_DISCEN) /*!< ADC group regular sequencer discontinuous mode enable with sequence interruption every 3 ranks */ -#define LL_ADC_REG_SEQ_DISCONT_4RANKS ( ADC_CR1_DISCNUM_1 | ADC_CR1_DISCNUM_0 | ADC_CR1_DISCEN) /*!< ADC group regular sequencer discontinuous mode enable with sequence interruption every 4 ranks */ -#define LL_ADC_REG_SEQ_DISCONT_5RANKS (ADC_CR1_DISCNUM_2 | ADC_CR1_DISCEN) /*!< ADC group regular sequencer discontinuous mode enable with sequence interruption every 5 ranks */ -#define LL_ADC_REG_SEQ_DISCONT_6RANKS (ADC_CR1_DISCNUM_2 | ADC_CR1_DISCNUM_0 | ADC_CR1_DISCEN) /*!< ADC group regular sequencer discontinuous mode enable with sequence interruption every 6 ranks */ -#define LL_ADC_REG_SEQ_DISCONT_7RANKS (ADC_CR1_DISCNUM_2 | ADC_CR1_DISCNUM_1 | ADC_CR1_DISCEN) /*!< ADC group regular sequencer discontinuous mode enable with sequence interruption every 7 ranks */ -#define LL_ADC_REG_SEQ_DISCONT_8RANKS (ADC_CR1_DISCNUM_2 | ADC_CR1_DISCNUM_1 | ADC_CR1_DISCNUM_0 | ADC_CR1_DISCEN) /*!< ADC group regular sequencer discontinuous mode enable with sequence interruption every 8 ranks */ -/** - * @} - */ - -/** @defgroup ADC_LL_EC_REG_SEQ_RANKS ADC group regular - Sequencer ranks - * @{ - */ -#define LL_ADC_REG_RANK_1 (ADC_SQR3_REGOFFSET | ADC_REG_RANK_1_SQRX_BITOFFSET_POS) /*!< ADC group regular sequencer rank 1 */ -#define LL_ADC_REG_RANK_2 (ADC_SQR3_REGOFFSET | ADC_REG_RANK_2_SQRX_BITOFFSET_POS) /*!< ADC group regular sequencer rank 2 */ -#define LL_ADC_REG_RANK_3 (ADC_SQR3_REGOFFSET | ADC_REG_RANK_3_SQRX_BITOFFSET_POS) /*!< ADC group regular sequencer rank 3 */ -#define LL_ADC_REG_RANK_4 (ADC_SQR3_REGOFFSET | ADC_REG_RANK_4_SQRX_BITOFFSET_POS) /*!< ADC group regular sequencer rank 4 */ -#define LL_ADC_REG_RANK_5 (ADC_SQR3_REGOFFSET | ADC_REG_RANK_5_SQRX_BITOFFSET_POS) /*!< ADC group regular sequencer rank 5 */ -#define LL_ADC_REG_RANK_6 (ADC_SQR3_REGOFFSET | ADC_REG_RANK_6_SQRX_BITOFFSET_POS) /*!< ADC group regular sequencer rank 6 */ -#define LL_ADC_REG_RANK_7 (ADC_SQR2_REGOFFSET | ADC_REG_RANK_7_SQRX_BITOFFSET_POS) /*!< ADC group regular sequencer rank 7 */ -#define LL_ADC_REG_RANK_8 (ADC_SQR2_REGOFFSET | ADC_REG_RANK_8_SQRX_BITOFFSET_POS) /*!< ADC group regular sequencer rank 8 */ -#define LL_ADC_REG_RANK_9 (ADC_SQR2_REGOFFSET | ADC_REG_RANK_9_SQRX_BITOFFSET_POS) /*!< ADC group regular sequencer rank 9 */ -#define LL_ADC_REG_RANK_10 (ADC_SQR2_REGOFFSET | ADC_REG_RANK_10_SQRX_BITOFFSET_POS) /*!< ADC group regular sequencer rank 10 */ -#define LL_ADC_REG_RANK_11 (ADC_SQR2_REGOFFSET | ADC_REG_RANK_11_SQRX_BITOFFSET_POS) /*!< ADC group regular sequencer rank 11 */ -#define LL_ADC_REG_RANK_12 (ADC_SQR2_REGOFFSET | ADC_REG_RANK_12_SQRX_BITOFFSET_POS) /*!< ADC group regular sequencer rank 12 */ -#define LL_ADC_REG_RANK_13 (ADC_SQR1_REGOFFSET | ADC_REG_RANK_13_SQRX_BITOFFSET_POS) /*!< ADC group regular sequencer rank 13 */ -#define LL_ADC_REG_RANK_14 (ADC_SQR1_REGOFFSET | ADC_REG_RANK_14_SQRX_BITOFFSET_POS) /*!< ADC group regular sequencer rank 14 */ -#define LL_ADC_REG_RANK_15 (ADC_SQR1_REGOFFSET | ADC_REG_RANK_15_SQRX_BITOFFSET_POS) /*!< ADC group regular sequencer rank 15 */ -#define LL_ADC_REG_RANK_16 (ADC_SQR1_REGOFFSET | ADC_REG_RANK_16_SQRX_BITOFFSET_POS) /*!< ADC group regular sequencer rank 16 */ -/** - * @} - */ - -/** @defgroup ADC_LL_EC_INJ_TRIGGER_SOURCE ADC group injected - Trigger source - * @{ - */ -/* ADC group injected external triggers for ADC instances: ADC1, ADC2, ADC3 (for ADC instances ADCx available on the selected device) */ -#define LL_ADC_INJ_TRIG_SOFTWARE (ADC_CR2_JEXTSEL_2 | ADC_CR2_JEXTSEL_1 | ADC_CR2_JEXTSEL_0) /*!< ADC group injected conversion trigger internal: SW start. */ -#define LL_ADC_INJ_TRIG_EXT_TIM1_TRGO 0x00000000U /*!< ADC group injected conversion trigger from external IP: TIM1 TRGO. Trigger edge set to rising edge (default setting). */ -#define LL_ADC_INJ_TRIG_EXT_TIM1_CH4 (ADC_CR2_JEXTSEL_0) /*!< ADC group injected conversion trigger from external IP: TIM1 channel 4 event (capture compare: input capture or output capture). Trigger edge set to rising edge (default setting). */ -/* ADC group injected external triggers for ADC instances: ADC1, ADC2 (for ADC instances ADCx available on the selected device) */ -#define LL_ADC_INJ_TRIG_EXT_TIM2_TRGO (ADC_CR2_JEXTSEL_1) /*!< ADC group injected conversion trigger from external IP: TIM2 TRGO. Trigger edge set to rising edge (default setting). */ -#define LL_ADC_INJ_TRIG_EXT_TIM2_CH1 (ADC_CR2_JEXTSEL_1 | ADC_CR2_JEXTSEL_0) /*!< ADC group injected conversion trigger from external IP: TIM2 channel 1 event (capture compare: input capture or output capture). Trigger edge set to rising edge (default setting). */ -#define LL_ADC_INJ_TRIG_EXT_TIM3_CH4 (ADC_CR2_JEXTSEL_2) /*!< ADC group injected conversion trigger from external IP: TIM3 channel 4 event (capture compare: input capture or output capture). Trigger edge set to rising edge (default setting). */ -#define LL_ADC_INJ_TRIG_EXT_TIM4_TRGO (ADC_CR2_JEXTSEL_2 | ADC_CR2_JEXTSEL_0) /*!< ADC group injected conversion trigger from external IP: TIM4 TRGO. Trigger edge set to rising edge (default setting). */ -#define LL_ADC_INJ_TRIG_EXT_EXTI_LINE15 (ADC_CR2_JEXTSEL_2 | ADC_CR2_JEXTSEL_1) /*!< ADC group injected conversion trigger from external IP: external interrupt line 15. Trigger edge set to rising edge (default setting). */ -#if defined (STM32F101xE) || defined (STM32F103xE) || defined (STM32F103xG) || defined (STM32F105xC) || defined (STM32F107xC) -/* Note: TIM8_CH4 is available on ADC1 and ADC2 only in high-density and */ -/* XL-density devices. */ -/* Note: To use TIM8_TRGO on ADC1 or ADC2, a remap of trigger must be done */ -/* A remap of trigger must be done at top level (refer to */ -/* AFIO peripheral). */ -#define LL_ADC_INJ_TRIG_EXT_TIM8_CH4 (LL_ADC_INJ_TRIG_EXT_EXTI_LINE15) /*!< ADC group injected conversion trigger from external IP: TIM8 channel 4 event (capture compare: input capture or output capture). Trigger edge set to rising edge (default setting). Available only on high-density and XL-density devices. A remap of trigger must be done at top level (refer to AFIO peripheral). */ -#endif /* STM32F101xE || STM32F103xE || STM32F103xG || STM32F105xC || STM32F107xC */ -#if defined (STM32F103xE) || defined (STM32F103xG) -/* ADC group injected external triggers for ADC instances: ADC3 (for ADC instances ADCx available on the selected device) */ -#define LL_ADC_INJ_TRIG_EXT_TIM4_CH3 (LL_ADC_INJ_TRIG_EXT_TIM2_TRGO) /*!< ADC group injected conversion trigger from external IP: TIM4 channel 3 event (capture compare: input capture or output capture). Trigger edge set to rising edge (default setting). */ -#define LL_ADC_INJ_TRIG_EXT_TIM8_CH2 (LL_ADC_INJ_TRIG_EXT_TIM2_CH1) /*!< ADC group injected conversion trigger from external IP: TIM8 channel 2 event (capture compare: input capture or output capture). Trigger edge set to rising edge (default setting). */ -#define LL_ADC_INJ_TRIG_EXT_TIM8_CH4_ADC3 (LL_ADC_INJ_TRIG_EXT_TIM3_CH4) /*!< ADC group injected conversion trigger from external IP: TIM8 channel 4 event (capture compare: input capture or output capture). Trigger edge set to rising edge (default setting). */ -#define LL_ADC_INJ_TRIG_EXT_TIM5_TRGO (LL_ADC_INJ_TRIG_EXT_TIM4_TRGO) /*!< ADC group injected conversion trigger from external IP: TIM5 TRGO. Trigger edge set to rising edge (default setting). */ -#define LL_ADC_INJ_TRIG_EXT_TIM5_CH4 (LL_ADC_INJ_TRIG_EXT_EXTI_LINE15) /*!< ADC group injected conversion trigger from external IP: TIM5 channel 4 event (capture compare: input capture or output capture). Trigger edge set to rising edge (default setting). */ -#endif -/** - * @} - */ - -/** @defgroup ADC_LL_EC_INJ_TRIGGER_EDGE ADC group injected - Trigger edge - * @{ - */ -#define LL_ADC_INJ_TRIG_EXT_RISING ADC_CR2_JEXTTRIG /*!< ADC group injected conversion trigger polarity set to rising edge */ -/** - * @} - */ - -/** @defgroup ADC_LL_EC_INJ_TRIG_AUTO ADC group injected - Automatic trigger mode -* @{ -*/ -#define LL_ADC_INJ_TRIG_INDEPENDENT 0x00000000U /*!< ADC group injected conversion trigger independent. Setting mandatory if ADC group injected injected trigger source is set to an external trigger. */ -#define LL_ADC_INJ_TRIG_FROM_GRP_REGULAR (ADC_CR1_JAUTO) /*!< ADC group injected conversion trigger from ADC group regular. Setting compliant only with group injected trigger source set to SW start, without any further action on ADC group injected conversion start or stop: in this case, ADC group injected is controlled only from ADC group regular. */ -/** - * @} - */ - - -/** @defgroup ADC_LL_EC_INJ_SEQ_SCAN_LENGTH ADC group injected - Sequencer scan length - * @{ - */ -#define LL_ADC_INJ_SEQ_SCAN_DISABLE 0x00000000U /*!< ADC group injected sequencer disable (equivalent to sequencer of 1 rank: ADC conversion on only 1 channel) */ -#define LL_ADC_INJ_SEQ_SCAN_ENABLE_2RANKS ( ADC_JSQR_JL_0) /*!< ADC group injected sequencer enable with 2 ranks in the sequence */ -#define LL_ADC_INJ_SEQ_SCAN_ENABLE_3RANKS (ADC_JSQR_JL_1 ) /*!< ADC group injected sequencer enable with 3 ranks in the sequence */ -#define LL_ADC_INJ_SEQ_SCAN_ENABLE_4RANKS (ADC_JSQR_JL_1 | ADC_JSQR_JL_0) /*!< ADC group injected sequencer enable with 4 ranks in the sequence */ -/** - * @} - */ - -/** @defgroup ADC_LL_EC_INJ_SEQ_DISCONT_MODE ADC group injected - Sequencer discontinuous mode - * @{ - */ -#define LL_ADC_INJ_SEQ_DISCONT_DISABLE 0x00000000U /*!< ADC group injected sequencer discontinuous mode disable */ -#define LL_ADC_INJ_SEQ_DISCONT_1RANK (ADC_CR1_JDISCEN) /*!< ADC group injected sequencer discontinuous mode enable with sequence interruption every rank */ -/** - * @} - */ - -/** @defgroup ADC_LL_EC_INJ_SEQ_RANKS ADC group injected - Sequencer ranks - * @{ - */ -#define LL_ADC_INJ_RANK_1 (ADC_JDR1_REGOFFSET | ADC_JOFR1_REGOFFSET | 0x00000001U) /*!< ADC group injected sequencer rank 1 */ -#define LL_ADC_INJ_RANK_2 (ADC_JDR2_REGOFFSET | ADC_JOFR2_REGOFFSET | 0x00000002U) /*!< ADC group injected sequencer rank 2 */ -#define LL_ADC_INJ_RANK_3 (ADC_JDR3_REGOFFSET | ADC_JOFR3_REGOFFSET | 0x00000003U) /*!< ADC group injected sequencer rank 3 */ -#define LL_ADC_INJ_RANK_4 (ADC_JDR4_REGOFFSET | ADC_JOFR4_REGOFFSET | 0x00000004U) /*!< ADC group injected sequencer rank 4 */ -/** - * @} - */ - -/** @defgroup ADC_LL_EC_CHANNEL_SAMPLINGTIME Channel - Sampling time - * @{ - */ -#define LL_ADC_SAMPLINGTIME_1CYCLE_5 0x00000000U /*!< Sampling time 1.5 ADC clock cycle */ -#define LL_ADC_SAMPLINGTIME_7CYCLES_5 (ADC_SMPR2_SMP0_0) /*!< Sampling time 7.5 ADC clock cycles */ -#define LL_ADC_SAMPLINGTIME_13CYCLES_5 (ADC_SMPR2_SMP0_1) /*!< Sampling time 13.5 ADC clock cycles */ -#define LL_ADC_SAMPLINGTIME_28CYCLES_5 (ADC_SMPR2_SMP0_1 | ADC_SMPR2_SMP0_0) /*!< Sampling time 28.5 ADC clock cycles */ -#define LL_ADC_SAMPLINGTIME_41CYCLES_5 (ADC_SMPR2_SMP0_2) /*!< Sampling time 41.5 ADC clock cycles */ -#define LL_ADC_SAMPLINGTIME_55CYCLES_5 (ADC_SMPR2_SMP0_2 | ADC_SMPR2_SMP0_0) /*!< Sampling time 55.5 ADC clock cycles */ -#define LL_ADC_SAMPLINGTIME_71CYCLES_5 (ADC_SMPR2_SMP0_2 | ADC_SMPR2_SMP0_1) /*!< Sampling time 71.5 ADC clock cycles */ -#define LL_ADC_SAMPLINGTIME_239CYCLES_5 (ADC_SMPR2_SMP0_2 | ADC_SMPR2_SMP0_1 | ADC_SMPR2_SMP0_0) /*!< Sampling time 239.5 ADC clock cycles */ -/** - * @} - */ - -/** @defgroup ADC_LL_EC_AWD_NUMBER Analog watchdog - Analog watchdog number - * @{ - */ -#define LL_ADC_AWD1 (ADC_AWD_CR1_CHANNEL_MASK | ADC_AWD_CR1_REGOFFSET) /*!< ADC analog watchdog number 1 */ -/** - * @} - */ - -/** @defgroup ADC_LL_EC_AWD_CHANNELS Analog watchdog - Monitored channels - * @{ - */ -#define LL_ADC_AWD_DISABLE 0x00000000U /*!< ADC analog watchdog monitoring disabled */ -#define LL_ADC_AWD_ALL_CHANNELS_REG ( ADC_CR1_AWDEN ) /*!< ADC analog watchdog monitoring of all channels, converted by group regular only */ -#define LL_ADC_AWD_ALL_CHANNELS_INJ ( ADC_CR1_JAWDEN ) /*!< ADC analog watchdog monitoring of all channels, converted by group injected only */ -#define LL_ADC_AWD_ALL_CHANNELS_REG_INJ ( ADC_CR1_JAWDEN | ADC_CR1_AWDEN ) /*!< ADC analog watchdog monitoring of all channels, converted by either group regular or injected */ -#define LL_ADC_AWD_CHANNEL_0_REG ((LL_ADC_CHANNEL_0 & ADC_CHANNEL_ID_MASK) | ADC_CR1_AWDEN | ADC_CR1_AWDSGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN0, converted by group regular only */ -#define LL_ADC_AWD_CHANNEL_0_INJ ((LL_ADC_CHANNEL_0 & ADC_CHANNEL_ID_MASK) | ADC_CR1_JAWDEN | ADC_CR1_AWDSGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN0, converted by group injected only */ -#define LL_ADC_AWD_CHANNEL_0_REG_INJ ((LL_ADC_CHANNEL_0 & ADC_CHANNEL_ID_MASK) | ADC_CR1_JAWDEN | ADC_CR1_AWDEN | ADC_CR1_AWDSGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN0, converted by either group regular or injected */ -#define LL_ADC_AWD_CHANNEL_1_REG ((LL_ADC_CHANNEL_1 & ADC_CHANNEL_ID_MASK) | ADC_CR1_AWDEN | ADC_CR1_AWDSGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN1, converted by group regular only */ -#define LL_ADC_AWD_CHANNEL_1_INJ ((LL_ADC_CHANNEL_1 & ADC_CHANNEL_ID_MASK) | ADC_CR1_JAWDEN | ADC_CR1_AWDSGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN1, converted by group injected only */ -#define LL_ADC_AWD_CHANNEL_1_REG_INJ ((LL_ADC_CHANNEL_1 & ADC_CHANNEL_ID_MASK) | ADC_CR1_JAWDEN | ADC_CR1_AWDEN | ADC_CR1_AWDSGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN1, converted by either group regular or injected */ -#define LL_ADC_AWD_CHANNEL_2_REG ((LL_ADC_CHANNEL_2 & ADC_CHANNEL_ID_MASK) | ADC_CR1_AWDEN | ADC_CR1_AWDSGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN2, converted by group regular only */ -#define LL_ADC_AWD_CHANNEL_2_INJ ((LL_ADC_CHANNEL_2 & ADC_CHANNEL_ID_MASK) | ADC_CR1_JAWDEN | ADC_CR1_AWDSGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN2, converted by group injected only */ -#define LL_ADC_AWD_CHANNEL_2_REG_INJ ((LL_ADC_CHANNEL_2 & ADC_CHANNEL_ID_MASK) | ADC_CR1_JAWDEN | ADC_CR1_AWDEN | ADC_CR1_AWDSGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN2, converted by either group regular or injected */ -#define LL_ADC_AWD_CHANNEL_3_REG ((LL_ADC_CHANNEL_3 & ADC_CHANNEL_ID_MASK) | ADC_CR1_AWDEN | ADC_CR1_AWDSGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN3, converted by group regular only */ -#define LL_ADC_AWD_CHANNEL_3_INJ ((LL_ADC_CHANNEL_3 & ADC_CHANNEL_ID_MASK) | ADC_CR1_JAWDEN | ADC_CR1_AWDSGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN3, converted by group injected only */ -#define LL_ADC_AWD_CHANNEL_3_REG_INJ ((LL_ADC_CHANNEL_3 & ADC_CHANNEL_ID_MASK) | ADC_CR1_JAWDEN | ADC_CR1_AWDEN | ADC_CR1_AWDSGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN3, converted by either group regular or injected */ -#define LL_ADC_AWD_CHANNEL_4_REG ((LL_ADC_CHANNEL_4 & ADC_CHANNEL_ID_MASK) | ADC_CR1_AWDEN | ADC_CR1_AWDSGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN4, converted by group regular only */ -#define LL_ADC_AWD_CHANNEL_4_INJ ((LL_ADC_CHANNEL_4 & ADC_CHANNEL_ID_MASK) | ADC_CR1_JAWDEN | ADC_CR1_AWDSGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN4, converted by group injected only */ -#define LL_ADC_AWD_CHANNEL_4_REG_INJ ((LL_ADC_CHANNEL_4 & ADC_CHANNEL_ID_MASK) | ADC_CR1_JAWDEN | ADC_CR1_AWDEN | ADC_CR1_AWDSGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN4, converted by either group regular or injected */ -#define LL_ADC_AWD_CHANNEL_5_REG ((LL_ADC_CHANNEL_5 & ADC_CHANNEL_ID_MASK) | ADC_CR1_AWDEN | ADC_CR1_AWDSGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN5, converted by group regular only */ -#define LL_ADC_AWD_CHANNEL_5_INJ ((LL_ADC_CHANNEL_5 & ADC_CHANNEL_ID_MASK) | ADC_CR1_JAWDEN | ADC_CR1_AWDSGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN5, converted by group injected only */ -#define LL_ADC_AWD_CHANNEL_5_REG_INJ ((LL_ADC_CHANNEL_5 & ADC_CHANNEL_ID_MASK) | ADC_CR1_JAWDEN | ADC_CR1_AWDEN | ADC_CR1_AWDSGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN5, converted by either group regular or injected */ -#define LL_ADC_AWD_CHANNEL_6_REG ((LL_ADC_CHANNEL_6 & ADC_CHANNEL_ID_MASK) | ADC_CR1_AWDEN | ADC_CR1_AWDSGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN6, converted by group regular only */ -#define LL_ADC_AWD_CHANNEL_6_INJ ((LL_ADC_CHANNEL_6 & ADC_CHANNEL_ID_MASK) | ADC_CR1_JAWDEN | ADC_CR1_AWDSGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN6, converted by group injected only */ -#define LL_ADC_AWD_CHANNEL_6_REG_INJ ((LL_ADC_CHANNEL_6 & ADC_CHANNEL_ID_MASK) | ADC_CR1_JAWDEN | ADC_CR1_AWDEN | ADC_CR1_AWDSGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN6, converted by either group regular or injected */ -#define LL_ADC_AWD_CHANNEL_7_REG ((LL_ADC_CHANNEL_7 & ADC_CHANNEL_ID_MASK) | ADC_CR1_AWDEN | ADC_CR1_AWDSGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN7, converted by group regular only */ -#define LL_ADC_AWD_CHANNEL_7_INJ ((LL_ADC_CHANNEL_7 & ADC_CHANNEL_ID_MASK) | ADC_CR1_JAWDEN | ADC_CR1_AWDSGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN7, converted by group injected only */ -#define LL_ADC_AWD_CHANNEL_7_REG_INJ ((LL_ADC_CHANNEL_7 & ADC_CHANNEL_ID_MASK) | ADC_CR1_JAWDEN | ADC_CR1_AWDEN | ADC_CR1_AWDSGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN7, converted by either group regular or injected */ -#define LL_ADC_AWD_CHANNEL_8_REG ((LL_ADC_CHANNEL_8 & ADC_CHANNEL_ID_MASK) | ADC_CR1_AWDEN | ADC_CR1_AWDSGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN8, converted by group regular only */ -#define LL_ADC_AWD_CHANNEL_8_INJ ((LL_ADC_CHANNEL_8 & ADC_CHANNEL_ID_MASK) | ADC_CR1_JAWDEN | ADC_CR1_AWDSGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN8, converted by group injected only */ -#define LL_ADC_AWD_CHANNEL_8_REG_INJ ((LL_ADC_CHANNEL_8 & ADC_CHANNEL_ID_MASK) | ADC_CR1_JAWDEN | ADC_CR1_AWDEN | ADC_CR1_AWDSGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN8, converted by either group regular or injected */ -#define LL_ADC_AWD_CHANNEL_9_REG ((LL_ADC_CHANNEL_9 & ADC_CHANNEL_ID_MASK) | ADC_CR1_AWDEN | ADC_CR1_AWDSGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN9, converted by group regular only */ -#define LL_ADC_AWD_CHANNEL_9_INJ ((LL_ADC_CHANNEL_9 & ADC_CHANNEL_ID_MASK) | ADC_CR1_JAWDEN | ADC_CR1_AWDSGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN9, converted by group injected only */ -#define LL_ADC_AWD_CHANNEL_9_REG_INJ ((LL_ADC_CHANNEL_9 & ADC_CHANNEL_ID_MASK) | ADC_CR1_JAWDEN | ADC_CR1_AWDEN | ADC_CR1_AWDSGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN9, converted by either group regular or injected */ -#define LL_ADC_AWD_CHANNEL_10_REG ((LL_ADC_CHANNEL_10 & ADC_CHANNEL_ID_MASK) | ADC_CR1_AWDEN | ADC_CR1_AWDSGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN10, converted by group regular only */ -#define LL_ADC_AWD_CHANNEL_10_INJ ((LL_ADC_CHANNEL_10 & ADC_CHANNEL_ID_MASK) | ADC_CR1_JAWDEN | ADC_CR1_AWDSGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN10, converted by group injected only */ -#define LL_ADC_AWD_CHANNEL_10_REG_INJ ((LL_ADC_CHANNEL_10 & ADC_CHANNEL_ID_MASK) | ADC_CR1_JAWDEN | ADC_CR1_AWDEN | ADC_CR1_AWDSGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN10, converted by either group regular or injected */ -#define LL_ADC_AWD_CHANNEL_11_REG ((LL_ADC_CHANNEL_11 & ADC_CHANNEL_ID_MASK) | ADC_CR1_AWDEN | ADC_CR1_AWDSGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN11, converted by group regular only */ -#define LL_ADC_AWD_CHANNEL_11_INJ ((LL_ADC_CHANNEL_11 & ADC_CHANNEL_ID_MASK) | ADC_CR1_JAWDEN | ADC_CR1_AWDSGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN11, converted by group injected only */ -#define LL_ADC_AWD_CHANNEL_11_REG_INJ ((LL_ADC_CHANNEL_11 & ADC_CHANNEL_ID_MASK) | ADC_CR1_JAWDEN | ADC_CR1_AWDEN | ADC_CR1_AWDSGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN11, converted by either group regular or injected */ -#define LL_ADC_AWD_CHANNEL_12_REG ((LL_ADC_CHANNEL_12 & ADC_CHANNEL_ID_MASK) | ADC_CR1_AWDEN | ADC_CR1_AWDSGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN12, converted by group regular only */ -#define LL_ADC_AWD_CHANNEL_12_INJ ((LL_ADC_CHANNEL_12 & ADC_CHANNEL_ID_MASK) | ADC_CR1_JAWDEN | ADC_CR1_AWDSGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN12, converted by group injected only */ -#define LL_ADC_AWD_CHANNEL_12_REG_INJ ((LL_ADC_CHANNEL_12 & ADC_CHANNEL_ID_MASK) | ADC_CR1_JAWDEN | ADC_CR1_AWDEN | ADC_CR1_AWDSGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN12, converted by either group regular or injected */ -#define LL_ADC_AWD_CHANNEL_13_REG ((LL_ADC_CHANNEL_13 & ADC_CHANNEL_ID_MASK) | ADC_CR1_AWDEN | ADC_CR1_AWDSGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN13, converted by group regular only */ -#define LL_ADC_AWD_CHANNEL_13_INJ ((LL_ADC_CHANNEL_13 & ADC_CHANNEL_ID_MASK) | ADC_CR1_JAWDEN | ADC_CR1_AWDSGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN13, converted by group injected only */ -#define LL_ADC_AWD_CHANNEL_13_REG_INJ ((LL_ADC_CHANNEL_13 & ADC_CHANNEL_ID_MASK) | ADC_CR1_JAWDEN | ADC_CR1_AWDEN | ADC_CR1_AWDSGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN13, converted by either group regular or injected */ -#define LL_ADC_AWD_CHANNEL_14_REG ((LL_ADC_CHANNEL_14 & ADC_CHANNEL_ID_MASK) | ADC_CR1_AWDEN | ADC_CR1_AWDSGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN14, converted by group regular only */ -#define LL_ADC_AWD_CHANNEL_14_INJ ((LL_ADC_CHANNEL_14 & ADC_CHANNEL_ID_MASK) | ADC_CR1_JAWDEN | ADC_CR1_AWDSGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN14, converted by group injected only */ -#define LL_ADC_AWD_CHANNEL_14_REG_INJ ((LL_ADC_CHANNEL_14 & ADC_CHANNEL_ID_MASK) | ADC_CR1_JAWDEN | ADC_CR1_AWDEN | ADC_CR1_AWDSGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN14, converted by either group regular or injected */ -#define LL_ADC_AWD_CHANNEL_15_REG ((LL_ADC_CHANNEL_15 & ADC_CHANNEL_ID_MASK) | ADC_CR1_AWDEN | ADC_CR1_AWDSGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN15, converted by group regular only */ -#define LL_ADC_AWD_CHANNEL_15_INJ ((LL_ADC_CHANNEL_15 & ADC_CHANNEL_ID_MASK) | ADC_CR1_JAWDEN | ADC_CR1_AWDSGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN15, converted by group injected only */ -#define LL_ADC_AWD_CHANNEL_15_REG_INJ ((LL_ADC_CHANNEL_15 & ADC_CHANNEL_ID_MASK) | ADC_CR1_JAWDEN | ADC_CR1_AWDEN | ADC_CR1_AWDSGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN15, converted by either group regular or injected */ -#define LL_ADC_AWD_CHANNEL_16_REG ((LL_ADC_CHANNEL_16 & ADC_CHANNEL_ID_MASK) | ADC_CR1_AWDEN | ADC_CR1_AWDSGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN16, converted by group regular only */ -#define LL_ADC_AWD_CHANNEL_16_INJ ((LL_ADC_CHANNEL_16 & ADC_CHANNEL_ID_MASK) | ADC_CR1_JAWDEN | ADC_CR1_AWDSGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN16, converted by group injected only */ -#define LL_ADC_AWD_CHANNEL_16_REG_INJ ((LL_ADC_CHANNEL_16 & ADC_CHANNEL_ID_MASK) | ADC_CR1_JAWDEN | ADC_CR1_AWDEN | ADC_CR1_AWDSGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN16, converted by either group regular or injected */ -#define LL_ADC_AWD_CHANNEL_17_REG ((LL_ADC_CHANNEL_17 & ADC_CHANNEL_ID_MASK) | ADC_CR1_AWDEN | ADC_CR1_AWDSGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN17, converted by group regular only */ -#define LL_ADC_AWD_CHANNEL_17_INJ ((LL_ADC_CHANNEL_17 & ADC_CHANNEL_ID_MASK) | ADC_CR1_JAWDEN | ADC_CR1_AWDSGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN17, converted by group injected only */ -#define LL_ADC_AWD_CHANNEL_17_REG_INJ ((LL_ADC_CHANNEL_17 & ADC_CHANNEL_ID_MASK) | ADC_CR1_JAWDEN | ADC_CR1_AWDEN | ADC_CR1_AWDSGL) /*!< ADC analog watchdog monitoring of ADC external channel (channel connected to GPIO pin) ADCx_IN17, converted by either group regular or injected */ -#define LL_ADC_AWD_CH_VREFINT_REG ((LL_ADC_CHANNEL_VREFINT & ADC_CHANNEL_ID_MASK) | ADC_CR1_AWDEN | ADC_CR1_AWDSGL) /*!< ADC analog watchdog monitoring of ADC internal channel connected to VrefInt: Internal voltage reference, converted by group regular only */ -#define LL_ADC_AWD_CH_VREFINT_INJ ((LL_ADC_CHANNEL_VREFINT & ADC_CHANNEL_ID_MASK) | ADC_CR1_JAWDEN | ADC_CR1_AWDSGL) /*!< ADC analog watchdog monitoring of ADC internal channel connected to VrefInt: Internal voltage reference, converted by group injected only */ -#define LL_ADC_AWD_CH_VREFINT_REG_INJ ((LL_ADC_CHANNEL_VREFINT & ADC_CHANNEL_ID_MASK) | ADC_CR1_JAWDEN | ADC_CR1_AWDEN | ADC_CR1_AWDSGL) /*!< ADC analog watchdog monitoring of ADC internal channel connected to VrefInt: Internal voltage reference, converted by either group regular or injected */ -#define LL_ADC_AWD_CH_TEMPSENSOR_REG ((LL_ADC_CHANNEL_TEMPSENSOR & ADC_CHANNEL_ID_MASK) | ADC_CR1_AWDEN | ADC_CR1_AWDSGL) /*!< ADC analog watchdog monitoring of ADC internal channel connected to Temperature sensor, converted by group regular only */ -#define LL_ADC_AWD_CH_TEMPSENSOR_INJ ((LL_ADC_CHANNEL_TEMPSENSOR & ADC_CHANNEL_ID_MASK) | ADC_CR1_JAWDEN | ADC_CR1_AWDSGL) /*!< ADC analog watchdog monitoring of ADC internal channel connected to Temperature sensor, converted by group injected only */ -#define LL_ADC_AWD_CH_TEMPSENSOR_REG_INJ ((LL_ADC_CHANNEL_TEMPSENSOR & ADC_CHANNEL_ID_MASK) | ADC_CR1_JAWDEN | ADC_CR1_AWDEN | ADC_CR1_AWDSGL) /*!< ADC analog watchdog monitoring of ADC internal channel connected to Temperature sensor, converted by either group regular or injected */ -/** - * @} - */ - -/** @defgroup ADC_LL_EC_AWD_THRESHOLDS Analog watchdog - Thresholds - * @{ - */ -#define LL_ADC_AWD_THRESHOLD_HIGH (ADC_AWD_TR1_HIGH_REGOFFSET) /*!< ADC analog watchdog threshold high */ -#define LL_ADC_AWD_THRESHOLD_LOW (ADC_AWD_TR1_LOW_REGOFFSET) /*!< ADC analog watchdog threshold low */ -/** - * @} - */ - -#if !defined(ADC_MULTIMODE_SUPPORT) -/** @defgroup ADC_LL_EC_MULTI_MODE Multimode - Mode - * @{ - */ -#define LL_ADC_MULTI_INDEPENDENT 0x00000000U /*!< ADC dual mode disabled (ADC independent mode) */ -/** - * @} - */ -#endif -#if defined(ADC_MULTIMODE_SUPPORT) -/** @defgroup ADC_LL_EC_MULTI_MODE Multimode - Mode - * @{ - */ -#define LL_ADC_MULTI_INDEPENDENT 0x00000000U /*!< ADC dual mode disabled (ADC independent mode) */ -#define LL_ADC_MULTI_DUAL_REG_SIMULT ( ADC_CR1_DUALMOD_2 | ADC_CR1_DUALMOD_1 ) /*!< ADC dual mode enabled: group regular simultaneous */ -#define LL_ADC_MULTI_DUAL_REG_INTERL_FAST ( ADC_CR1_DUALMOD_2 | ADC_CR1_DUALMOD_1 | ADC_CR1_DUALMOD_0) /*!< ADC dual mode enabled: Combined group regular interleaved fast (delay between ADC sampling phases: 7 ADC clock cycles) (equivalent to multimode sampling delay set to "LL_ADC_MULTI_TWOSMP_DELAY_7CYCLES" on other STM32 devices)) */ -#define LL_ADC_MULTI_DUAL_REG_INTERL_SLOW (ADC_CR1_DUALMOD_3 ) /*!< ADC dual mode enabled: Combined group regular interleaved slow (delay between ADC sampling phases: 14 ADC clock cycles) (equivalent to multimode sampling delay set to "LL_ADC_MULTI_TWOSMP_DELAY_14CYCLES" on other STM32 devices)) */ -#define LL_ADC_MULTI_DUAL_INJ_SIMULT ( ADC_CR1_DUALMOD_2 | ADC_CR1_DUALMOD_0) /*!< ADC dual mode enabled: group injected simultaneous slow (delay between ADC sampling phases: 14 ADC clock cycles) (equivalent to multimode sampling delay set to "LL_ADC_MULTI_TWOSMP_DELAY_14CYCLES" on other STM32 devices)) */ -#define LL_ADC_MULTI_DUAL_INJ_ALTERN (ADC_CR1_DUALMOD_3 | ADC_CR1_DUALMOD_0) /*!< ADC dual mode enabled: group injected alternate trigger. Works only with external triggers (not internal SW start) */ -#define LL_ADC_MULTI_DUAL_REG_SIM_INJ_SIM ( ADC_CR1_DUALMOD_0) /*!< ADC dual mode enabled: Combined group regular simultaneous + group injected simultaneous */ -#define LL_ADC_MULTI_DUAL_REG_SIM_INJ_ALT ( ADC_CR1_DUALMOD_1 ) /*!< ADC dual mode enabled: Combined group regular simultaneous + group injected alternate trigger */ -#define LL_ADC_MULTI_DUAL_REG_INTFAST_INJ_SIM ( ADC_CR1_DUALMOD_1 | ADC_CR1_DUALMOD_0) /*!< ADC dual mode enabled: Combined group regular interleaved fast (delay between ADC sampling phases: 7 ADC clock cycles) + group injected simultaneous */ -#define LL_ADC_MULTI_DUAL_REG_INTSLOW_INJ_SIM ( ADC_CR1_DUALMOD_2 ) /*!< ADC dual mode enabled: Combined group regular interleaved slow (delay between ADC sampling phases: 14 ADC clock cycles) + group injected simultaneous */ - -/** - * @} - */ - -/** @defgroup ADC_LL_EC_MULTI_MASTER_SLAVE Multimode - ADC master or slave - * @{ - */ -#define LL_ADC_MULTI_MASTER ( ADC_DR_DATA) /*!< In multimode, selection among several ADC instances: ADC master */ -#define LL_ADC_MULTI_SLAVE (ADC_DR_ADC2DATA ) /*!< In multimode, selection among several ADC instances: ADC slave */ -#define LL_ADC_MULTI_MASTER_SLAVE (ADC_DR_ADC2DATA | ADC_DR_DATA) /*!< In multimode, selection among several ADC instances: both ADC master and ADC slave */ -/** - * @} - */ - -#endif /* ADC_MULTIMODE_SUPPORT */ - - -/** @defgroup ADC_LL_EC_HW_DELAYS Definitions of ADC hardware constraints delays - * @note Only ADC IP HW delays are defined in ADC LL driver driver, - * not timeout values. - * For details on delays values, refer to descriptions in source code - * above each literal definition. - * @{ - */ - -/* Note: Only ADC IP HW delays are defined in ADC LL driver driver, */ -/* not timeout values. */ -/* Timeout values for ADC operations are dependent to device clock */ -/* configuration (system clock versus ADC clock), */ -/* and therefore must be defined in user application. */ -/* Indications for estimation of ADC timeout delays, for this */ -/* STM32 serie: */ -/* - ADC enable time: maximum delay is 1us */ -/* (refer to device datasheet, parameter "tSTAB") */ -/* - ADC conversion time: duration depending on ADC clock and ADC */ -/* configuration. */ -/* (refer to device reference manual, section "Timing") */ - -/* Delay for temperature sensor stabilization time. */ -/* Literal set to maximum value (refer to device datasheet, */ -/* parameter "tSTART"). */ -/* Unit: us */ -#define LL_ADC_DELAY_TEMPSENSOR_STAB_US (10U) /*!< Delay for internal voltage reference stabilization time */ - -/* Delay required between ADC disable and ADC calibration start. */ -/* Note: On this STM32 serie, before starting a calibration, */ -/* ADC must be disabled. */ -/* A minimum number of ADC clock cycles are required */ -/* between ADC disable state and calibration start. */ -/* Refer to literal @ref LL_ADC_DELAY_ENABLE_CALIB_ADC_CYCLES. */ -/* Wait time can be computed in user application by waiting for the */ -/* equivalent number of CPU cycles, by taking into account */ -/* ratio of CPU clock versus ADC clock prescalers. */ -/* Unit: ADC clock cycles. */ -#define LL_ADC_DELAY_DISABLE_CALIB_ADC_CYCLES (2U) /*!< Delay required between ADC disable and ADC calibration start */ - -/* Delay required between end of ADC Enable and the start of ADC calibration. */ -/* Note: On this STM32 serie, a minimum number of ADC clock cycles */ -/* are required between the end of ADC enable and the start of ADC */ -/* calibration. */ -/* Wait time can be computed in user application by waiting for the */ -/* equivalent number of CPU cycles, by taking into account */ -/* ratio of CPU clock versus ADC clock prescalers. */ -/* Unit: ADC clock cycles. */ -#define LL_ADC_DELAY_ENABLE_CALIB_ADC_CYCLES (2U) /*!< Delay required between end of ADC enable and the start of ADC calibration */ - -/** - * @} - */ - -/** - * @} - */ - - -/* Exported macro ------------------------------------------------------------*/ -/** @defgroup ADC_LL_Exported_Macros ADC Exported Macros - * @{ - */ - -/** @defgroup ADC_LL_EM_WRITE_READ Common write and read registers Macros - * @{ - */ - -/** - * @brief Write a value in ADC register - * @param __INSTANCE__ ADC Instance - * @param __REG__ Register to be written - * @param __VALUE__ Value to be written in the register - * @retval None - */ -#define LL_ADC_WriteReg(__INSTANCE__, __REG__, __VALUE__) WRITE_REG(__INSTANCE__->__REG__, (__VALUE__)) - -/** - * @brief Read a value in ADC register - * @param __INSTANCE__ ADC Instance - * @param __REG__ Register to be read - * @retval Register value - */ -#define LL_ADC_ReadReg(__INSTANCE__, __REG__) READ_REG(__INSTANCE__->__REG__) -/** - * @} - */ - -/** @defgroup ADC_LL_EM_HELPER_MACRO ADC helper macro - * @{ - */ - -/** - * @brief Helper macro to get ADC channel number in decimal format - * from literals LL_ADC_CHANNEL_x. - * @note Example: - * __LL_ADC_CHANNEL_TO_DECIMAL_NB(LL_ADC_CHANNEL_4) - * will return decimal number "4". - * @note The input can be a value from functions where a channel - * number is returned, either defined with number - * or with bitfield (only one bit must be set). - * @param __CHANNEL__ This parameter can be one of the following values: - * @arg @ref LL_ADC_CHANNEL_0 - * @arg @ref LL_ADC_CHANNEL_1 - * @arg @ref LL_ADC_CHANNEL_2 - * @arg @ref LL_ADC_CHANNEL_3 - * @arg @ref LL_ADC_CHANNEL_4 - * @arg @ref LL_ADC_CHANNEL_5 - * @arg @ref LL_ADC_CHANNEL_6 - * @arg @ref LL_ADC_CHANNEL_7 - * @arg @ref LL_ADC_CHANNEL_8 - * @arg @ref LL_ADC_CHANNEL_9 - * @arg @ref LL_ADC_CHANNEL_10 - * @arg @ref LL_ADC_CHANNEL_11 - * @arg @ref LL_ADC_CHANNEL_12 - * @arg @ref LL_ADC_CHANNEL_13 - * @arg @ref LL_ADC_CHANNEL_14 - * @arg @ref LL_ADC_CHANNEL_15 - * @arg @ref LL_ADC_CHANNEL_16 - * @arg @ref LL_ADC_CHANNEL_17 - * @arg @ref LL_ADC_CHANNEL_VREFINT (1) - * @arg @ref LL_ADC_CHANNEL_TEMPSENSOR (1) - * - * (1) On STM32F1, parameter available only on ADC instance: ADC1. - * @retval Value between Min_Data=0 and Max_Data=18 - */ -#define __LL_ADC_CHANNEL_TO_DECIMAL_NB(__CHANNEL__) \ - (((__CHANNEL__) & ADC_CHANNEL_ID_NUMBER_MASK) >> ADC_CHANNEL_ID_NUMBER_BITOFFSET_POS) - -/** - * @brief Helper macro to get ADC channel in literal format LL_ADC_CHANNEL_x - * from number in decimal format. - * @note Example: - * __LL_ADC_DECIMAL_NB_TO_CHANNEL(4) - * will return a data equivalent to "LL_ADC_CHANNEL_4". - * @param __DECIMAL_NB__: Value between Min_Data=0 and Max_Data=18 - * @retval Returned value can be one of the following values: - * @arg @ref LL_ADC_CHANNEL_0 - * @arg @ref LL_ADC_CHANNEL_1 - * @arg @ref LL_ADC_CHANNEL_2 - * @arg @ref LL_ADC_CHANNEL_3 - * @arg @ref LL_ADC_CHANNEL_4 - * @arg @ref LL_ADC_CHANNEL_5 - * @arg @ref LL_ADC_CHANNEL_6 - * @arg @ref LL_ADC_CHANNEL_7 - * @arg @ref LL_ADC_CHANNEL_8 - * @arg @ref LL_ADC_CHANNEL_9 - * @arg @ref LL_ADC_CHANNEL_10 - * @arg @ref LL_ADC_CHANNEL_11 - * @arg @ref LL_ADC_CHANNEL_12 - * @arg @ref LL_ADC_CHANNEL_13 - * @arg @ref LL_ADC_CHANNEL_14 - * @arg @ref LL_ADC_CHANNEL_15 - * @arg @ref LL_ADC_CHANNEL_16 - * @arg @ref LL_ADC_CHANNEL_17 - * @arg @ref LL_ADC_CHANNEL_VREFINT (1) - * @arg @ref LL_ADC_CHANNEL_TEMPSENSOR (1) - * - * (1) On STM32F1, parameter available only on ADC instance: ADC1.\n - * (1) For ADC channel read back from ADC register, - * comparison with internal channel parameter to be done - * using helper macro @ref __LL_ADC_CHANNEL_INTERNAL_TO_EXTERNAL(). - */ -#define __LL_ADC_DECIMAL_NB_TO_CHANNEL(__DECIMAL_NB__) \ - (((__DECIMAL_NB__) <= 9U) \ - ? ( \ - ((__DECIMAL_NB__) << ADC_CHANNEL_ID_NUMBER_BITOFFSET_POS) | \ - (ADC_SMPR2_REGOFFSET | (((uint32_t) (3U * (__DECIMAL_NB__))) << ADC_CHANNEL_SMPx_BITOFFSET_POS)) \ - ) \ - : \ - ( \ - ((__DECIMAL_NB__) << ADC_CHANNEL_ID_NUMBER_BITOFFSET_POS) | \ - (ADC_SMPR1_REGOFFSET | (((uint32_t) (3U * ((__DECIMAL_NB__) - 10U))) << ADC_CHANNEL_SMPx_BITOFFSET_POS)) \ - ) \ - ) - -/** - * @brief Helper macro to determine whether the selected channel - * corresponds to literal definitions of driver. - * @note The different literal definitions of ADC channels are: - * - ADC internal channel: - * LL_ADC_CHANNEL_VREFINT, LL_ADC_CHANNEL_TEMPSENSOR, ... - * - ADC external channel (channel connected to a GPIO pin): - * LL_ADC_CHANNEL_1, LL_ADC_CHANNEL_2, ... - * @note The channel parameter must be a value defined from literal - * definition of a ADC internal channel (LL_ADC_CHANNEL_VREFINT, - * LL_ADC_CHANNEL_TEMPSENSOR, ...), - * ADC external channel (LL_ADC_CHANNEL_1, LL_ADC_CHANNEL_2, ...), - * must not be a value from functions where a channel number is - * returned from ADC registers, - * because internal and external channels share the same channel - * number in ADC registers. The differentiation is made only with - * parameters definitions of driver. - * @param __CHANNEL__ This parameter can be one of the following values: - * @arg @ref LL_ADC_CHANNEL_0 - * @arg @ref LL_ADC_CHANNEL_1 - * @arg @ref LL_ADC_CHANNEL_2 - * @arg @ref LL_ADC_CHANNEL_3 - * @arg @ref LL_ADC_CHANNEL_4 - * @arg @ref LL_ADC_CHANNEL_5 - * @arg @ref LL_ADC_CHANNEL_6 - * @arg @ref LL_ADC_CHANNEL_7 - * @arg @ref LL_ADC_CHANNEL_8 - * @arg @ref LL_ADC_CHANNEL_9 - * @arg @ref LL_ADC_CHANNEL_10 - * @arg @ref LL_ADC_CHANNEL_11 - * @arg @ref LL_ADC_CHANNEL_12 - * @arg @ref LL_ADC_CHANNEL_13 - * @arg @ref LL_ADC_CHANNEL_14 - * @arg @ref LL_ADC_CHANNEL_15 - * @arg @ref LL_ADC_CHANNEL_16 - * @arg @ref LL_ADC_CHANNEL_17 - * @arg @ref LL_ADC_CHANNEL_VREFINT (1) - * @arg @ref LL_ADC_CHANNEL_TEMPSENSOR (1) - * - * (1) On STM32F1, parameter available only on ADC instance: ADC1. - * @retval Value "0" if the channel corresponds to a parameter definition of a ADC external channel (channel connected to a GPIO pin). - * Value "1" if the channel corresponds to a parameter definition of a ADC internal channel. - */ -#define __LL_ADC_IS_CHANNEL_INTERNAL(__CHANNEL__) \ - (((__CHANNEL__) & ADC_CHANNEL_ID_INTERNAL_CH_MASK) != 0U) - -/** - * @brief Helper macro to convert a channel defined from parameter - * definition of a ADC internal channel (LL_ADC_CHANNEL_VREFINT, - * LL_ADC_CHANNEL_TEMPSENSOR, ...), - * to its equivalent parameter definition of a ADC external channel - * (LL_ADC_CHANNEL_1, LL_ADC_CHANNEL_2, ...). - * @note The channel parameter can be, additionally to a value - * defined from parameter definition of a ADC internal channel - * (LL_ADC_CHANNEL_VREFINT, LL_ADC_CHANNEL_TEMPSENSOR, ...), - * a value defined from parameter definition of - * ADC external channel (LL_ADC_CHANNEL_1, LL_ADC_CHANNEL_2, ...) - * or a value from functions where a channel number is returned - * from ADC registers. - * @param __CHANNEL__ This parameter can be one of the following values: - * @arg @ref LL_ADC_CHANNEL_0 - * @arg @ref LL_ADC_CHANNEL_1 - * @arg @ref LL_ADC_CHANNEL_2 - * @arg @ref LL_ADC_CHANNEL_3 - * @arg @ref LL_ADC_CHANNEL_4 - * @arg @ref LL_ADC_CHANNEL_5 - * @arg @ref LL_ADC_CHANNEL_6 - * @arg @ref LL_ADC_CHANNEL_7 - * @arg @ref LL_ADC_CHANNEL_8 - * @arg @ref LL_ADC_CHANNEL_9 - * @arg @ref LL_ADC_CHANNEL_10 - * @arg @ref LL_ADC_CHANNEL_11 - * @arg @ref LL_ADC_CHANNEL_12 - * @arg @ref LL_ADC_CHANNEL_13 - * @arg @ref LL_ADC_CHANNEL_14 - * @arg @ref LL_ADC_CHANNEL_15 - * @arg @ref LL_ADC_CHANNEL_16 - * @arg @ref LL_ADC_CHANNEL_17 - * @arg @ref LL_ADC_CHANNEL_VREFINT (1) - * @arg @ref LL_ADC_CHANNEL_TEMPSENSOR (1) - * - * (1) On STM32F1, parameter available only on ADC instance: ADC1. - * @retval Returned value can be one of the following values: - * @arg @ref LL_ADC_CHANNEL_0 - * @arg @ref LL_ADC_CHANNEL_1 - * @arg @ref LL_ADC_CHANNEL_2 - * @arg @ref LL_ADC_CHANNEL_3 - * @arg @ref LL_ADC_CHANNEL_4 - * @arg @ref LL_ADC_CHANNEL_5 - * @arg @ref LL_ADC_CHANNEL_6 - * @arg @ref LL_ADC_CHANNEL_7 - * @arg @ref LL_ADC_CHANNEL_8 - * @arg @ref LL_ADC_CHANNEL_9 - * @arg @ref LL_ADC_CHANNEL_10 - * @arg @ref LL_ADC_CHANNEL_11 - * @arg @ref LL_ADC_CHANNEL_12 - * @arg @ref LL_ADC_CHANNEL_13 - * @arg @ref LL_ADC_CHANNEL_14 - * @arg @ref LL_ADC_CHANNEL_15 - * @arg @ref LL_ADC_CHANNEL_16 - * @arg @ref LL_ADC_CHANNEL_17 - */ -#define __LL_ADC_CHANNEL_INTERNAL_TO_EXTERNAL(__CHANNEL__) \ - ((__CHANNEL__) & ~ADC_CHANNEL_ID_INTERNAL_CH_MASK) - -/** - * @brief Helper macro to determine whether the internal channel - * selected is available on the ADC instance selected. - * @note The channel parameter must be a value defined from parameter - * definition of a ADC internal channel (LL_ADC_CHANNEL_VREFINT, - * LL_ADC_CHANNEL_TEMPSENSOR, ...), - * must not be a value defined from parameter definition of - * ADC external channel (LL_ADC_CHANNEL_1, LL_ADC_CHANNEL_2, ...) - * or a value from functions where a channel number is - * returned from ADC registers, - * because internal and external channels share the same channel - * number in ADC registers. The differentiation is made only with - * parameters definitions of driver. - * @param __ADC_INSTANCE__ ADC instance - * @param __CHANNEL__ This parameter can be one of the following values: - * @arg @ref LL_ADC_CHANNEL_VREFINT (1) - * @arg @ref LL_ADC_CHANNEL_TEMPSENSOR (1) - * - * (1) On STM32F1, parameter available only on ADC instance: ADC1. - * @retval Value "0" if the internal channel selected is not available on the ADC instance selected. - * Value "1" if the internal channel selected is available on the ADC instance selected. - */ -#define __LL_ADC_IS_CHANNEL_INTERNAL_AVAILABLE(__ADC_INSTANCE__, __CHANNEL__) \ - (((__ADC_INSTANCE__) == ADC1) \ - ? ( \ - ((__CHANNEL__) == LL_ADC_CHANNEL_VREFINT) || \ - ((__CHANNEL__) == LL_ADC_CHANNEL_TEMPSENSOR) \ - ) \ - : \ - (0U) \ - ) - -/** - * @brief Helper macro to define ADC analog watchdog parameter: - * define a single channel to monitor with analog watchdog - * from sequencer channel and groups definition. - * @note To be used with function @ref LL_ADC_SetAnalogWDMonitChannels(). - * Example: - * LL_ADC_SetAnalogWDMonitChannels( - * ADC1, LL_ADC_AWD1, - * __LL_ADC_ANALOGWD_CHANNEL_GROUP(LL_ADC_CHANNEL4, LL_ADC_GROUP_REGULAR)) - * @param __CHANNEL__ This parameter can be one of the following values: - * @arg @ref LL_ADC_CHANNEL_0 - * @arg @ref LL_ADC_CHANNEL_1 - * @arg @ref LL_ADC_CHANNEL_2 - * @arg @ref LL_ADC_CHANNEL_3 - * @arg @ref LL_ADC_CHANNEL_4 - * @arg @ref LL_ADC_CHANNEL_5 - * @arg @ref LL_ADC_CHANNEL_6 - * @arg @ref LL_ADC_CHANNEL_7 - * @arg @ref LL_ADC_CHANNEL_8 - * @arg @ref LL_ADC_CHANNEL_9 - * @arg @ref LL_ADC_CHANNEL_10 - * @arg @ref LL_ADC_CHANNEL_11 - * @arg @ref LL_ADC_CHANNEL_12 - * @arg @ref LL_ADC_CHANNEL_13 - * @arg @ref LL_ADC_CHANNEL_14 - * @arg @ref LL_ADC_CHANNEL_15 - * @arg @ref LL_ADC_CHANNEL_16 - * @arg @ref LL_ADC_CHANNEL_17 - * @arg @ref LL_ADC_CHANNEL_VREFINT (1) - * @arg @ref LL_ADC_CHANNEL_TEMPSENSOR (1) - * - * (1) On STM32F1, parameter available only on ADC instance: ADC1.\n - * (1) For ADC channel read back from ADC register, - * comparison with internal channel parameter to be done - * using helper macro @ref __LL_ADC_CHANNEL_INTERNAL_TO_EXTERNAL(). - * @param __GROUP__ This parameter can be one of the following values: - * @arg @ref LL_ADC_GROUP_REGULAR - * @arg @ref LL_ADC_GROUP_INJECTED - * @arg @ref LL_ADC_GROUP_REGULAR_INJECTED - * @retval Returned value can be one of the following values: - * @arg @ref LL_ADC_AWD_DISABLE - * @arg @ref LL_ADC_AWD_ALL_CHANNELS_REG - * @arg @ref LL_ADC_AWD_ALL_CHANNELS_INJ - * @arg @ref LL_ADC_AWD_ALL_CHANNELS_REG_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_0_REG - * @arg @ref LL_ADC_AWD_CHANNEL_0_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_0_REG_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_1_REG - * @arg @ref LL_ADC_AWD_CHANNEL_1_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_1_REG_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_2_REG - * @arg @ref LL_ADC_AWD_CHANNEL_2_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_2_REG_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_3_REG - * @arg @ref LL_ADC_AWD_CHANNEL_3_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_3_REG_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_4_REG - * @arg @ref LL_ADC_AWD_CHANNEL_4_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_4_REG_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_5_REG - * @arg @ref LL_ADC_AWD_CHANNEL_5_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_5_REG_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_6_REG - * @arg @ref LL_ADC_AWD_CHANNEL_6_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_6_REG_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_7_REG - * @arg @ref LL_ADC_AWD_CHANNEL_7_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_7_REG_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_8_REG - * @arg @ref LL_ADC_AWD_CHANNEL_8_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_8_REG_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_9_REG - * @arg @ref LL_ADC_AWD_CHANNEL_9_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_9_REG_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_10_REG - * @arg @ref LL_ADC_AWD_CHANNEL_10_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_10_REG_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_11_REG - * @arg @ref LL_ADC_AWD_CHANNEL_11_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_11_REG_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_12_REG - * @arg @ref LL_ADC_AWD_CHANNEL_12_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_12_REG_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_13_REG - * @arg @ref LL_ADC_AWD_CHANNEL_13_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_13_REG_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_14_REG - * @arg @ref LL_ADC_AWD_CHANNEL_14_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_14_REG_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_15_REG - * @arg @ref LL_ADC_AWD_CHANNEL_15_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_15_REG_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_16_REG - * @arg @ref LL_ADC_AWD_CHANNEL_16_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_16_REG_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_17_REG - * @arg @ref LL_ADC_AWD_CHANNEL_17_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_17_REG_INJ - * @arg @ref LL_ADC_AWD_CH_VREFINT_REG (1) - * @arg @ref LL_ADC_AWD_CH_VREFINT_INJ (1) - * @arg @ref LL_ADC_AWD_CH_VREFINT_REG_INJ (1) - * @arg @ref LL_ADC_AWD_CH_TEMPSENSOR_REG (1) - * @arg @ref LL_ADC_AWD_CH_TEMPSENSOR_INJ (1) - * @arg @ref LL_ADC_AWD_CH_TEMPSENSOR_REG_INJ (1) - * - * (1) On STM32F1, parameter available only on ADC instance: ADC1. - */ -#define __LL_ADC_ANALOGWD_CHANNEL_GROUP(__CHANNEL__, __GROUP__) \ - (((__GROUP__) == LL_ADC_GROUP_REGULAR) \ - ? (((__CHANNEL__) & ADC_CHANNEL_ID_MASK) | ADC_CR1_AWDEN | ADC_CR1_AWDSGL) \ - : \ - ((__GROUP__) == LL_ADC_GROUP_INJECTED) \ - ? (((__CHANNEL__) & ADC_CHANNEL_ID_MASK) | ADC_CR1_JAWDEN | ADC_CR1_AWDSGL) \ - : \ - (((__CHANNEL__) & ADC_CHANNEL_ID_MASK) | ADC_CR1_JAWDEN | ADC_CR1_AWDEN | ADC_CR1_AWDSGL) \ - ) - -/** - * @brief Helper macro to set the value of ADC analog watchdog threshold high - * or low in function of ADC resolution, when ADC resolution is - * different of 12 bits. - * @note To be used with function @ref LL_ADC_SetAnalogWDThresholds(). - * Example, with a ADC resolution of 8 bits, to set the value of - * analog watchdog threshold high (on 8 bits): - * LL_ADC_SetAnalogWDThresholds - * (< ADCx param >, - * __LL_ADC_ANALOGWD_SET_THRESHOLD_RESOLUTION(LL_ADC_RESOLUTION_8B, ) - * ); - * @param __ADC_RESOLUTION__ This parameter can be one of the following values: - * @arg @ref LL_ADC_RESOLUTION_12B - * @param __AWD_THRESHOLD__ Value between Min_Data=0x000 and Max_Data=0xFFF - * @retval Value between Min_Data=0x000 and Max_Data=0xFFF - */ -/* Note: On this STM32 serie, ADC is fixed to resolution 12 bits. */ -/* This macro has been kept anyway for compatibility with other */ -/* STM32 families featuring different ADC resolutions. */ -#define __LL_ADC_ANALOGWD_SET_THRESHOLD_RESOLUTION(__ADC_RESOLUTION__, __AWD_THRESHOLD__) \ - ((__AWD_THRESHOLD__) << (0U)) - -/** - * @brief Helper macro to get the value of ADC analog watchdog threshold high - * or low in function of ADC resolution, when ADC resolution is - * different of 12 bits. - * @note To be used with function @ref LL_ADC_GetAnalogWDThresholds(). - * Example, with a ADC resolution of 8 bits, to get the value of - * analog watchdog threshold high (on 8 bits): - * < threshold_value_6_bits > = __LL_ADC_ANALOGWD_GET_THRESHOLD_RESOLUTION - * (LL_ADC_RESOLUTION_8B, - * LL_ADC_GetAnalogWDThresholds(, LL_ADC_AWD_THRESHOLD_HIGH) - * ); - * @param __ADC_RESOLUTION__ This parameter can be one of the following values: - * @arg @ref LL_ADC_RESOLUTION_12B - * @param __AWD_THRESHOLD_12_BITS__ Value between Min_Data=0x000 and Max_Data=0xFFF - * @retval Value between Min_Data=0x000 and Max_Data=0xFFF - */ -/* Note: On this STM32 serie, ADC is fixed to resolution 12 bits. */ -/* This macro has been kept anyway for compatibility with other */ -/* STM32 families featuring different ADC resolutions. */ -#define __LL_ADC_ANALOGWD_GET_THRESHOLD_RESOLUTION(__ADC_RESOLUTION__, __AWD_THRESHOLD_12_BITS__) \ - (__AWD_THRESHOLD_12_BITS__) - -#if defined(ADC_MULTIMODE_SUPPORT) -/** - * @brief Helper macro to get the ADC multimode conversion data of ADC master - * or ADC slave from raw value with both ADC conversion data concatenated. - * @note This macro is intended to be used when multimode transfer by DMA - * is enabled. - * In this case the transferred data need to processed with this macro - * to separate the conversion data of ADC master and ADC slave. - * @param __ADC_MULTI_MASTER_SLAVE__ This parameter can be one of the following values: - * @arg @ref LL_ADC_MULTI_MASTER - * @arg @ref LL_ADC_MULTI_SLAVE - * @param __ADC_MULTI_CONV_DATA__ Value between Min_Data=0x000 and Max_Data=0xFFF - * @retval Value between Min_Data=0x000 and Max_Data=0xFFF - */ -#define __LL_ADC_MULTI_CONV_DATA_MASTER_SLAVE(__ADC_MULTI_MASTER_SLAVE__, __ADC_MULTI_CONV_DATA__) \ - (((__ADC_MULTI_CONV_DATA__) >> POSITION_VAL((__ADC_MULTI_MASTER_SLAVE__))) & ADC_DR_DATA) -#endif - -/** - * @brief Helper macro to select the ADC common instance - * to which is belonging the selected ADC instance. - * @note ADC common register instance can be used for: - * - Set parameters common to several ADC instances - * - Multimode (for devices with several ADC instances) - * Refer to functions having argument "ADCxy_COMMON" as parameter. - * @note On STM32F1, there is no common ADC instance. - * However, ADC instance ADC1 has a role of common ADC instance - * for ADC1 and ADC2: - * this instance is used to manage internal channels - * and multimode (these features are managed in ADC common - * instances on some other STM32 devices). - * ADC instance ADC3 (if available on the selected device) - * has no ADC common instance. - * @param __ADCx__ ADC instance - * @retval ADC common register instance - */ -#if defined(ADC1) && defined(ADC2) && defined(ADC3) -#define __LL_ADC_COMMON_INSTANCE(__ADCx__) \ - ((((__ADCx__) == ADC1) || ((__ADCx__) == ADC2)) \ - ? ( \ - (ADC12_COMMON) \ - ) \ - : \ - ( \ - (0U) \ - ) \ - ) -#elif defined(ADC1) && defined(ADC2) -#define __LL_ADC_COMMON_INSTANCE(__ADCx__) \ - (ADC12_COMMON) -#else -#define __LL_ADC_COMMON_INSTANCE(__ADCx__) \ - (ADC1_COMMON) -#endif - -/** - * @brief Helper macro to check if all ADC instances sharing the same - * ADC common instance are disabled. - * @note This check is required by functions with setting conditioned to - * ADC state: - * All ADC instances of the ADC common group must be disabled. - * Refer to functions having argument "ADCxy_COMMON" as parameter. - * @note On devices with only 1 ADC common instance, parameter of this macro - * is useless and can be ignored (parameter kept for compatibility - * with devices featuring several ADC common instances). - * @note On STM32F1, there is no common ADC instance. - * However, ADC instance ADC1 has a role of common ADC instance - * for ADC1 and ADC2: - * this instance is used to manage internal channels - * and multimode (these features are managed in ADC common - * instances on some other STM32 devices). - * ADC instance ADC3 (if available on the selected device) - * has no ADC common instance. - * @param __ADCXY_COMMON__ ADC common instance - * (can be set directly from CMSIS definition or by using helper macro @ref __LL_ADC_COMMON_INSTANCE() ) - * @retval Value "0" if all ADC instances sharing the same ADC common instance - * are disabled. - * Value "1" if at least one ADC instance sharing the same ADC common instance - * is enabled. - */ -#if defined(ADC1) && defined(ADC2) && defined(ADC3) -#define __LL_ADC_IS_ENABLED_ALL_COMMON_INSTANCE(__ADCXY_COMMON__) \ - (((__ADCXY_COMMON__) == ADC12_COMMON) \ - ? ( \ - (LL_ADC_IsEnabled(ADC1) | \ - LL_ADC_IsEnabled(ADC2) ) \ - ) \ - : \ - ( \ - LL_ADC_IsEnabled(ADC3) \ - ) \ - ) -#elif defined(ADC1) && defined(ADC2) -#define __LL_ADC_IS_ENABLED_ALL_COMMON_INSTANCE(__ADCXY_COMMON__) \ - (LL_ADC_IsEnabled(ADC1) | \ - LL_ADC_IsEnabled(ADC2) ) -#else -#define __LL_ADC_IS_ENABLED_ALL_COMMON_INSTANCE(__ADCXY_COMMON__) \ - LL_ADC_IsEnabled(ADC1) -#endif - -/** - * @brief Helper macro to define the ADC conversion data full-scale digital - * value corresponding to the selected ADC resolution. - * @note ADC conversion data full-scale corresponds to voltage range - * determined by analog voltage references Vref+ and Vref- - * (refer to reference manual). - * @param __ADC_RESOLUTION__ This parameter can be one of the following values: - * @arg @ref LL_ADC_RESOLUTION_12B - * @retval ADC conversion data equivalent voltage value (unit: mVolt) - */ -#define __LL_ADC_DIGITAL_SCALE(__ADC_RESOLUTION__) \ - (0xFFFU) - - -/** - * @brief Helper macro to calculate the voltage (unit: mVolt) - * corresponding to a ADC conversion data (unit: digital value). - * @note Analog reference voltage (Vref+) must be known from - * user board environment or can be calculated using ADC measurement. - * @param __VREFANALOG_VOLTAGE__ Analog reference voltage (unit: mV) - * @param __ADC_DATA__ ADC conversion data (resolution 12 bits) - * (unit: digital value). - * @param __ADC_RESOLUTION__ This parameter can be one of the following values: - * @arg @ref LL_ADC_RESOLUTION_12B - * @retval ADC conversion data equivalent voltage value (unit: mVolt) - */ -#define __LL_ADC_CALC_DATA_TO_VOLTAGE(__VREFANALOG_VOLTAGE__,\ - __ADC_DATA__,\ - __ADC_RESOLUTION__) \ - ((__ADC_DATA__) * (__VREFANALOG_VOLTAGE__) \ - / __LL_ADC_DIGITAL_SCALE(__ADC_RESOLUTION__) \ - ) - - -/** - * @brief Helper macro to calculate the temperature (unit: degree Celsius) - * from ADC conversion data of internal temperature sensor. - * @note Computation is using temperature sensor typical values - * (refer to device datasheet). - * @note Calculation formula: - * Temperature = (TS_TYP_CALx_VOLT(uV) - TS_ADC_DATA * Conversion_uV) - * / Avg_Slope + CALx_TEMP - * with TS_ADC_DATA = temperature sensor raw data measured by ADC - * (unit: digital value) - * Avg_Slope = temperature sensor slope - * (unit: uV/Degree Celsius) - * TS_TYP_CALx_VOLT = temperature sensor digital value at - * temperature CALx_TEMP (unit: mV) - * Caution: Calculation relevancy under reserve the temperature sensor - * of the current device has characteristics in line with - * datasheet typical values. - * If temperature sensor calibration values are available on - * on this device (presence of macro __LL_ADC_CALC_TEMPERATURE()), - * temperature calculation will be more accurate using - * helper macro @ref __LL_ADC_CALC_TEMPERATURE(). - * @note As calculation input, the analog reference voltage (Vref+) must be - * defined as it impacts the ADC LSB equivalent voltage. - * @note Analog reference voltage (Vref+) must be known from - * user board environment or can be calculated using ADC measurement. - * @note ADC measurement data must correspond to a resolution of 12bits - * (full scale digital value 4095). If not the case, the data must be - * preliminarily rescaled to an equivalent resolution of 12 bits. - * @param __TEMPSENSOR_TYP_AVGSLOPE__ Device datasheet data: Temperature sensor slope typical value (unit: uV/DegCelsius). - * On STM32F1, refer to device datasheet parameter "Avg_Slope". - * @param __TEMPSENSOR_TYP_CALX_V__ Device datasheet data: Temperature sensor voltage typical value (at temperature and Vref+ defined in parameters below) (unit: mV). - * On STM32F1, refer to device datasheet parameter "V25". - * @param __TEMPSENSOR_CALX_TEMP__ Device datasheet data: Temperature at which temperature sensor voltage (see parameter above) is corresponding (unit: mV) - * @param __VREFANALOG_VOLTAGE__ Analog voltage reference (Vref+) voltage (unit: mV) - * @param __TEMPSENSOR_ADC_DATA__ ADC conversion data of internal temperature sensor (unit: digital value). - * @param __ADC_RESOLUTION__ ADC resolution at which internal temperature sensor voltage has been measured. - * This parameter can be one of the following values: - * @arg @ref LL_ADC_RESOLUTION_12B - * @retval Temperature (unit: degree Celsius) - */ -#define __LL_ADC_CALC_TEMPERATURE_TYP_PARAMS(__TEMPSENSOR_TYP_AVGSLOPE__,\ - __TEMPSENSOR_TYP_CALX_V__,\ - __TEMPSENSOR_CALX_TEMP__,\ - __VREFANALOG_VOLTAGE__,\ - __TEMPSENSOR_ADC_DATA__,\ - __ADC_RESOLUTION__) \ - ((( ( \ - (int32_t)(((__TEMPSENSOR_TYP_CALX_V__)) \ - * 1000) \ - - \ - (int32_t)((((__TEMPSENSOR_ADC_DATA__) * (__VREFANALOG_VOLTAGE__)) \ - / __LL_ADC_DIGITAL_SCALE(__ADC_RESOLUTION__)) \ - * 1000) \ - ) \ - ) / (__TEMPSENSOR_TYP_AVGSLOPE__) \ - ) + (__TEMPSENSOR_CALX_TEMP__) \ - ) - -/** - * @} - */ - -/** - * @} - */ - - -/* Exported functions --------------------------------------------------------*/ -/** @defgroup ADC_LL_Exported_Functions ADC Exported Functions - * @{ - */ - -/** @defgroup ADC_LL_EF_DMA_Management ADC DMA management - * @{ - */ -/* Note: LL ADC functions to set DMA transfer are located into sections of */ -/* configuration of ADC instance, groups and multimode (if available): */ -/* @ref LL_ADC_REG_SetDMATransfer(), ... */ - -/** - * @brief Function to help to configure DMA transfer from ADC: retrieve the - * ADC register address from ADC instance and a list of ADC registers - * intended to be used (most commonly) with DMA transfer. - * @note These ADC registers are data registers: - * when ADC conversion data is available in ADC data registers, - * ADC generates a DMA transfer request. - * @note This macro is intended to be used with LL DMA driver, refer to - * function "LL_DMA_ConfigAddresses()". - * Example: - * LL_DMA_ConfigAddresses(DMA1, - * LL_DMA_CHANNEL_1, - * LL_ADC_DMA_GetRegAddr(ADC1, LL_ADC_DMA_REG_REGULAR_DATA), - * (uint32_t)&< array or variable >, - * LL_DMA_DIRECTION_PERIPH_TO_MEMORY); - * @note For devices with several ADC: in multimode, some devices - * use a different data register outside of ADC instance scope - * (common data register). This macro manages this register difference, - * only ADC instance has to be set as parameter. - * @note On STM32F1, only ADC instances ADC1 and ADC3 have DMA transfer - * capability, not ADC2 (ADC2 and ADC3 instances not available on - * all devices). - * @note On STM32F1, multimode can be used only with ADC1 and ADC2, not ADC3. - * Therefore, the corresponding parameter of data transfer - * for multimode can be used only with ADC1 and ADC2. - * (ADC2 and ADC3 instances not available on all devices). - * @rmtoll DR DATA LL_ADC_DMA_GetRegAddr - * @param ADCx ADC instance - * @param Register This parameter can be one of the following values: - * @arg @ref LL_ADC_DMA_REG_REGULAR_DATA - * @arg @ref LL_ADC_DMA_REG_REGULAR_DATA_MULTI (1) - * - * (1) Available on devices with several ADC instances. - * @retval ADC register address - */ -#if defined(ADC_MULTIMODE_SUPPORT) -__STATIC_INLINE uint32_t LL_ADC_DMA_GetRegAddr(ADC_TypeDef *ADCx, uint32_t Register) -{ - register uint32_t data_reg_addr = 0U; - - if (Register == LL_ADC_DMA_REG_REGULAR_DATA) - { - /* Retrieve address of register DR */ - data_reg_addr = (uint32_t)&(ADCx->DR); - } - else /* (Register == LL_ADC_DMA_REG_REGULAR_DATA_MULTI) */ - { - /* Retrieve address of register of multimode data */ - data_reg_addr = (uint32_t)&(ADC12_COMMON->DR); - } - - return data_reg_addr; -} -#else -__STATIC_INLINE uint32_t LL_ADC_DMA_GetRegAddr(ADC_TypeDef *ADCx, uint32_t Register) -{ - /* Retrieve address of register DR */ - return (uint32_t)&(ADCx->DR); -} -#endif - -/** - * @} - */ - -/** @defgroup ADC_LL_EF_Configuration_ADC_Common Configuration of ADC hierarchical scope: common to several ADC instances - * @{ - */ - -/** - * @brief Set parameter common to several ADC: measurement path to internal - * channels (VrefInt, temperature sensor, ...). - * @note One or several values can be selected. - * Example: (LL_ADC_PATH_INTERNAL_VREFINT | - * LL_ADC_PATH_INTERNAL_TEMPSENSOR) - * @note Stabilization time of measurement path to internal channel: - * After enabling internal paths, before starting ADC conversion, - * a delay is required for internal voltage reference and - * temperature sensor stabilization time. - * Refer to device datasheet. - * Refer to literal @ref LL_ADC_DELAY_TEMPSENSOR_STAB_US. - * @note ADC internal channel sampling time constraint: - * For ADC conversion of internal channels, - * a sampling time minimum value is required. - * Refer to device datasheet. - * @rmtoll CR2 TSVREFE LL_ADC_SetCommonPathInternalCh - * @param ADCxy_COMMON ADC common instance - * (can be set directly from CMSIS definition or by using helper macro @ref __LL_ADC_COMMON_INSTANCE() ) - * @param PathInternal This parameter can be a combination of the following values: - * @arg @ref LL_ADC_PATH_INTERNAL_NONE - * @arg @ref LL_ADC_PATH_INTERNAL_VREFINT - * @arg @ref LL_ADC_PATH_INTERNAL_TEMPSENSOR - * @retval None - */ -__STATIC_INLINE void LL_ADC_SetCommonPathInternalCh(ADC_Common_TypeDef *ADCxy_COMMON, uint32_t PathInternal) -{ - MODIFY_REG(ADCxy_COMMON->CR2, (ADC_CR2_TSVREFE), PathInternal); -} - -/** - * @brief Get parameter common to several ADC: measurement path to internal - * channels (VrefInt, temperature sensor, ...). - * @note One or several values can be selected. - * Example: (LL_ADC_PATH_INTERNAL_VREFINT | - * LL_ADC_PATH_INTERNAL_TEMPSENSOR) - * @rmtoll CR2 TSVREFE LL_ADC_GetCommonPathInternalCh - * @param ADCxy_COMMON ADC common instance - * (can be set directly from CMSIS definition or by using helper macro @ref __LL_ADC_COMMON_INSTANCE() ) - * @retval Returned value can be a combination of the following values: - * @arg @ref LL_ADC_PATH_INTERNAL_NONE - * @arg @ref LL_ADC_PATH_INTERNAL_VREFINT - * @arg @ref LL_ADC_PATH_INTERNAL_TEMPSENSOR - */ -__STATIC_INLINE uint32_t LL_ADC_GetCommonPathInternalCh(ADC_Common_TypeDef *ADCxy_COMMON) -{ - return (uint32_t)(READ_BIT(ADCxy_COMMON->CR2, ADC_CR2_TSVREFE)); -} - -/** - * @} - */ - -/** @defgroup ADC_LL_EF_Configuration_ADC_Instance Configuration of ADC hierarchical scope: ADC instance - * @{ - */ - -/** - * @brief Set ADC conversion data alignment. - * @note Refer to reference manual for alignments formats - * dependencies to ADC resolutions. - * @rmtoll CR2 ALIGN LL_ADC_SetDataAlignment - * @param ADCx ADC instance - * @param DataAlignment This parameter can be one of the following values: - * @arg @ref LL_ADC_DATA_ALIGN_RIGHT - * @arg @ref LL_ADC_DATA_ALIGN_LEFT - * @retval None - */ -__STATIC_INLINE void LL_ADC_SetDataAlignment(ADC_TypeDef *ADCx, uint32_t DataAlignment) -{ - MODIFY_REG(ADCx->CR2, ADC_CR2_ALIGN, DataAlignment); -} - -/** - * @brief Get ADC conversion data alignment. - * @note Refer to reference manual for alignments formats - * dependencies to ADC resolutions. - * @rmtoll CR2 ALIGN LL_ADC_SetDataAlignment - * @param ADCx ADC instance - * @retval Returned value can be one of the following values: - * @arg @ref LL_ADC_DATA_ALIGN_RIGHT - * @arg @ref LL_ADC_DATA_ALIGN_LEFT - */ -__STATIC_INLINE uint32_t LL_ADC_GetDataAlignment(ADC_TypeDef *ADCx) -{ - return (uint32_t)(READ_BIT(ADCx->CR2, ADC_CR2_ALIGN)); -} - -/** - * @brief Set ADC sequencers scan mode, for all ADC groups - * (group regular, group injected). - * @note According to sequencers scan mode : - * - If disabled: ADC conversion is performed in unitary conversion - * mode (one channel converted, that defined in rank 1). - * Configuration of sequencers of all ADC groups - * (sequencer scan length, ...) is discarded: equivalent to - * scan length of 1 rank. - * - If enabled: ADC conversions are performed in sequence conversions - * mode, according to configuration of sequencers of - * each ADC group (sequencer scan length, ...). - * Refer to function @ref LL_ADC_REG_SetSequencerLength() - * and to function @ref LL_ADC_INJ_SetSequencerLength(). - * @rmtoll CR1 SCAN LL_ADC_SetSequencersScanMode - * @param ADCx ADC instance - * @param ScanMode This parameter can be one of the following values: - * @arg @ref LL_ADC_SEQ_SCAN_DISABLE - * @arg @ref LL_ADC_SEQ_SCAN_ENABLE - * @retval None - */ -__STATIC_INLINE void LL_ADC_SetSequencersScanMode(ADC_TypeDef *ADCx, uint32_t ScanMode) -{ - MODIFY_REG(ADCx->CR1, ADC_CR1_SCAN, ScanMode); -} - -/** - * @brief Get ADC sequencers scan mode, for all ADC groups - * (group regular, group injected). - * @note According to sequencers scan mode : - * - If disabled: ADC conversion is performed in unitary conversion - * mode (one channel converted, that defined in rank 1). - * Configuration of sequencers of all ADC groups - * (sequencer scan length, ...) is discarded: equivalent to - * scan length of 1 rank. - * - If enabled: ADC conversions are performed in sequence conversions - * mode, according to configuration of sequencers of - * each ADC group (sequencer scan length, ...). - * Refer to function @ref LL_ADC_REG_SetSequencerLength() - * and to function @ref LL_ADC_INJ_SetSequencerLength(). - * @rmtoll CR1 SCAN LL_ADC_GetSequencersScanMode - * @param ADCx ADC instance - * @retval Returned value can be one of the following values: - * @arg @ref LL_ADC_SEQ_SCAN_DISABLE - * @arg @ref LL_ADC_SEQ_SCAN_ENABLE - */ -__STATIC_INLINE uint32_t LL_ADC_GetSequencersScanMode(ADC_TypeDef *ADCx) -{ - return (uint32_t)(READ_BIT(ADCx->CR1, ADC_CR1_SCAN)); -} - -/** - * @} - */ - -/** @defgroup ADC_LL_EF_Configuration_ADC_Group_Regular Configuration of ADC hierarchical scope: group regular - * @{ - */ - -/** - * @brief Set ADC group regular conversion trigger source: - * internal (SW start) or from external IP (timer event, - * external interrupt line). - * @note On this STM32 serie, external trigger is set with trigger polarity: - * rising edge (only trigger polarity available on this STM32 serie). - * @note Availability of parameters of trigger sources from timer - * depends on timers availability on the selected device. - * @rmtoll CR2 EXTSEL LL_ADC_REG_SetTriggerSource - * @param ADCx ADC instance - * @param TriggerSource This parameter can be one of the following values: - * @arg @ref LL_ADC_REG_TRIG_SOFTWARE - * @arg @ref LL_ADC_REG_TRIG_EXT_TIM1_CH3 (1) - * @arg @ref LL_ADC_REG_TRIG_EXT_TIM1_CH1 (2) - * @arg @ref LL_ADC_REG_TRIG_EXT_TIM1_CH2 (2) - * @arg @ref LL_ADC_REG_TRIG_EXT_TIM2_CH2 (2) - * @arg @ref LL_ADC_REG_TRIG_EXT_TIM3_TRGO (2) - * @arg @ref LL_ADC_REG_TRIG_EXT_TIM4_CH4 (2) - * @arg @ref LL_ADC_REG_TRIG_EXT_EXTI_LINE11 (2) - * @arg @ref LL_ADC_REG_TRIG_EXT_TIM8_TRGO (2)(4) - * @arg @ref LL_ADC_REG_TRIG_EXT_TIM8_TRGO_ADC3 (3) - * @arg @ref LL_ADC_REG_TRIG_EXT_TIM3_CH1 (3) - * @arg @ref LL_ADC_REG_TRIG_EXT_TIM2_CH3 (3) - * @arg @ref LL_ADC_REG_TRIG_EXT_TIM8_CH1 (3) - * @arg @ref LL_ADC_REG_TRIG_EXT_TIM8_TRGO (3) - * @arg @ref LL_ADC_REG_TRIG_EXT_TIM5_CH1 (3) - * @arg @ref LL_ADC_REG_TRIG_EXT_TIM5_CH3 (3) - * - * (1) On STM32F1, parameter available on all ADC instances: ADC1, ADC2, ADC3 (for ADC instances ADCx available on the selected device).\n - * (2) On STM32F1, parameter available only on ADC instances: ADC1, ADC2 (for ADC instances ADCx available on the selected device).\n - * (3) On STM32F1, parameter available only on ADC instances: ADC3 (for ADC instances ADCx available on the selected device).\n - * (4) On STM32F1, parameter available only on high-density and XL-density devices. A remap of trigger must be done at top level (refer to AFIO peripheral). - * @retval None - */ -__STATIC_INLINE void LL_ADC_REG_SetTriggerSource(ADC_TypeDef *ADCx, uint32_t TriggerSource) -{ -/* Note: On this STM32 serie, ADC group regular external trigger edge */ -/* is used to perform a ADC conversion start. */ -/* This function does not set external trigger edge. */ -/* This feature is set using function */ -/* @ref LL_ADC_REG_StartConversionExtTrig(). */ - MODIFY_REG(ADCx->CR2, ADC_CR2_EXTSEL, (TriggerSource & ADC_CR2_EXTSEL)); -} - -/** - * @brief Get ADC group regular conversion trigger source: - * internal (SW start) or from external IP (timer event, - * external interrupt line). - * @note To determine whether group regular trigger source is - * internal (SW start) or external, without detail - * of which peripheral is selected as external trigger, - * (equivalent to - * "if(LL_ADC_REG_GetTriggerSource(ADC1) == LL_ADC_REG_TRIG_SOFTWARE)") - * use function @ref LL_ADC_REG_IsTriggerSourceSWStart. - * @note Availability of parameters of trigger sources from timer - * depends on timers availability on the selected device. - * @rmtoll CR2 EXTSEL LL_ADC_REG_GetTriggerSource - * @param ADCx ADC instance - * @retval Returned value can be one of the following values: - * @arg @ref LL_ADC_REG_TRIG_SOFTWARE - * @arg @ref LL_ADC_REG_TRIG_EXT_TIM1_CH3 (1) - * @arg @ref LL_ADC_REG_TRIG_EXT_TIM1_CH1 (2) - * @arg @ref LL_ADC_REG_TRIG_EXT_TIM1_CH2 (2) - * @arg @ref LL_ADC_REG_TRIG_EXT_TIM2_CH2 (2) - * @arg @ref LL_ADC_REG_TRIG_EXT_TIM3_TRGO (2) - * @arg @ref LL_ADC_REG_TRIG_EXT_TIM4_CH4 (2) - * @arg @ref LL_ADC_REG_TRIG_EXT_EXTI_LINE11 (2) - * @arg @ref LL_ADC_REG_TRIG_EXT_TIM8_TRGO (2)(4) - * @arg @ref LL_ADC_REG_TRIG_EXT_TIM8_TRGO_ADC3 (3) - * @arg @ref LL_ADC_REG_TRIG_EXT_TIM3_CH1 (3) - * @arg @ref LL_ADC_REG_TRIG_EXT_TIM2_CH3 (3) - * @arg @ref LL_ADC_REG_TRIG_EXT_TIM8_CH1 (3) - * @arg @ref LL_ADC_REG_TRIG_EXT_TIM8_TRGO (3) - * @arg @ref LL_ADC_REG_TRIG_EXT_TIM5_CH1 (3) - * @arg @ref LL_ADC_REG_TRIG_EXT_TIM5_CH3 (3) - * - * (1) On STM32F1, parameter available on all ADC instances: ADC1, ADC2, ADC3 (for ADC instances ADCx available on the selected device).\n - * (2) On STM32F1, parameter available only on ADC instances: ADC1, ADC2 (for ADC instances ADCx available on the selected device).\n - * (3) On STM32F1, parameter available only on ADC instances: ADC3 (for ADC instances ADCx available on the selected device).\n - * (4) On STM32F1, parameter available only on high-density and XL-density devices. A remap of trigger must be done at top level (refer to AFIO peripheral). - */ -__STATIC_INLINE uint32_t LL_ADC_REG_GetTriggerSource(ADC_TypeDef *ADCx) -{ - return (uint32_t)(READ_BIT(ADCx->CR2, ADC_CR2_EXTSEL)); -} - -/** - * @brief Get ADC group regular conversion trigger source internal (SW start) - or external. - * @note In case of group regular trigger source set to external trigger, - * to determine which peripheral is selected as external trigger, - * use function @ref LL_ADC_REG_GetTriggerSource(). - * @rmtoll CR2 EXTSEL LL_ADC_REG_IsTriggerSourceSWStart - * @param ADCx ADC instance - * @retval Value "0" if trigger source external trigger - * Value "1" if trigger source SW start. - */ -__STATIC_INLINE uint32_t LL_ADC_REG_IsTriggerSourceSWStart(ADC_TypeDef *ADCx) -{ - return (READ_BIT(ADCx->CR2, ADC_CR2_EXTSEL) == (LL_ADC_REG_TRIG_SOFTWARE)); -} - - -/** - * @brief Set ADC group regular sequencer length and scan direction. - * @note Description of ADC group regular sequencer features: - * - For devices with sequencer fully configurable - * (function "LL_ADC_REG_SetSequencerRanks()" available): - * sequencer length and each rank affectation to a channel - * are configurable. - * This function performs configuration of: - * - Sequence length: Number of ranks in the scan sequence. - * - Sequence direction: Unless specified in parameters, sequencer - * scan direction is forward (from rank 1 to rank n). - * Sequencer ranks are selected using - * function "LL_ADC_REG_SetSequencerRanks()". - * - For devices with sequencer not fully configurable - * (function "LL_ADC_REG_SetSequencerChannels()" available): - * sequencer length and each rank affectation to a channel - * are defined by channel number. - * This function performs configuration of: - * - Sequence length: Number of ranks in the scan sequence is - * defined by number of channels set in the sequence, - * rank of each channel is fixed by channel HW number. - * (channel 0 fixed on rank 0, channel 1 fixed on rank1, ...). - * - Sequence direction: Unless specified in parameters, sequencer - * scan direction is forward (from lowest channel number to - * highest channel number). - * Sequencer ranks are selected using - * function "LL_ADC_REG_SetSequencerChannels()". - * @note On this STM32 serie, group regular sequencer configuration - * is conditioned to ADC instance sequencer mode. - * If ADC instance sequencer mode is disabled, sequencers of - * all groups (group regular, group injected) can be configured - * but their execution is disabled (limited to rank 1). - * Refer to function @ref LL_ADC_SetSequencersScanMode(). - * @note Sequencer disabled is equivalent to sequencer of 1 rank: - * ADC conversion on only 1 channel. - * @rmtoll SQR1 L LL_ADC_REG_SetSequencerLength - * @param ADCx ADC instance - * @param SequencerNbRanks This parameter can be one of the following values: - * @arg @ref LL_ADC_REG_SEQ_SCAN_DISABLE - * @arg @ref LL_ADC_REG_SEQ_SCAN_ENABLE_2RANKS - * @arg @ref LL_ADC_REG_SEQ_SCAN_ENABLE_3RANKS - * @arg @ref LL_ADC_REG_SEQ_SCAN_ENABLE_4RANKS - * @arg @ref LL_ADC_REG_SEQ_SCAN_ENABLE_5RANKS - * @arg @ref LL_ADC_REG_SEQ_SCAN_ENABLE_6RANKS - * @arg @ref LL_ADC_REG_SEQ_SCAN_ENABLE_7RANKS - * @arg @ref LL_ADC_REG_SEQ_SCAN_ENABLE_8RANKS - * @arg @ref LL_ADC_REG_SEQ_SCAN_ENABLE_9RANKS - * @arg @ref LL_ADC_REG_SEQ_SCAN_ENABLE_10RANKS - * @arg @ref LL_ADC_REG_SEQ_SCAN_ENABLE_11RANKS - * @arg @ref LL_ADC_REG_SEQ_SCAN_ENABLE_12RANKS - * @arg @ref LL_ADC_REG_SEQ_SCAN_ENABLE_13RANKS - * @arg @ref LL_ADC_REG_SEQ_SCAN_ENABLE_14RANKS - * @arg @ref LL_ADC_REG_SEQ_SCAN_ENABLE_15RANKS - * @arg @ref LL_ADC_REG_SEQ_SCAN_ENABLE_16RANKS - * @retval None - */ -__STATIC_INLINE void LL_ADC_REG_SetSequencerLength(ADC_TypeDef *ADCx, uint32_t SequencerNbRanks) -{ - MODIFY_REG(ADCx->SQR1, ADC_SQR1_L, SequencerNbRanks); -} - -/** - * @brief Get ADC group regular sequencer length and scan direction. - * @note Description of ADC group regular sequencer features: - * - For devices with sequencer fully configurable - * (function "LL_ADC_REG_SetSequencerRanks()" available): - * sequencer length and each rank affectation to a channel - * are configurable. - * This function retrieves: - * - Sequence length: Number of ranks in the scan sequence. - * - Sequence direction: Unless specified in parameters, sequencer - * scan direction is forward (from rank 1 to rank n). - * Sequencer ranks are selected using - * function "LL_ADC_REG_SetSequencerRanks()". - * - For devices with sequencer not fully configurable - * (function "LL_ADC_REG_SetSequencerChannels()" available): - * sequencer length and each rank affectation to a channel - * are defined by channel number. - * This function retrieves: - * - Sequence length: Number of ranks in the scan sequence is - * defined by number of channels set in the sequence, - * rank of each channel is fixed by channel HW number. - * (channel 0 fixed on rank 0, channel 1 fixed on rank1, ...). - * - Sequence direction: Unless specified in parameters, sequencer - * scan direction is forward (from lowest channel number to - * highest channel number). - * Sequencer ranks are selected using - * function "LL_ADC_REG_SetSequencerChannels()". - * @note On this STM32 serie, group regular sequencer configuration - * is conditioned to ADC instance sequencer mode. - * If ADC instance sequencer mode is disabled, sequencers of - * all groups (group regular, group injected) can be configured - * but their execution is disabled (limited to rank 1). - * Refer to function @ref LL_ADC_SetSequencersScanMode(). - * @note Sequencer disabled is equivalent to sequencer of 1 rank: - * ADC conversion on only 1 channel. - * @rmtoll SQR1 L LL_ADC_REG_SetSequencerLength - * @param ADCx ADC instance - * @retval Returned value can be one of the following values: - * @arg @ref LL_ADC_REG_SEQ_SCAN_DISABLE - * @arg @ref LL_ADC_REG_SEQ_SCAN_ENABLE_2RANKS - * @arg @ref LL_ADC_REG_SEQ_SCAN_ENABLE_3RANKS - * @arg @ref LL_ADC_REG_SEQ_SCAN_ENABLE_4RANKS - * @arg @ref LL_ADC_REG_SEQ_SCAN_ENABLE_5RANKS - * @arg @ref LL_ADC_REG_SEQ_SCAN_ENABLE_6RANKS - * @arg @ref LL_ADC_REG_SEQ_SCAN_ENABLE_7RANKS - * @arg @ref LL_ADC_REG_SEQ_SCAN_ENABLE_8RANKS - * @arg @ref LL_ADC_REG_SEQ_SCAN_ENABLE_9RANKS - * @arg @ref LL_ADC_REG_SEQ_SCAN_ENABLE_10RANKS - * @arg @ref LL_ADC_REG_SEQ_SCAN_ENABLE_11RANKS - * @arg @ref LL_ADC_REG_SEQ_SCAN_ENABLE_12RANKS - * @arg @ref LL_ADC_REG_SEQ_SCAN_ENABLE_13RANKS - * @arg @ref LL_ADC_REG_SEQ_SCAN_ENABLE_14RANKS - * @arg @ref LL_ADC_REG_SEQ_SCAN_ENABLE_15RANKS - * @arg @ref LL_ADC_REG_SEQ_SCAN_ENABLE_16RANKS - */ -__STATIC_INLINE uint32_t LL_ADC_REG_GetSequencerLength(ADC_TypeDef *ADCx) -{ - return (uint32_t)(READ_BIT(ADCx->SQR1, ADC_SQR1_L)); -} - -/** - * @brief Set ADC group regular sequencer discontinuous mode: - * sequence subdivided and scan conversions interrupted every selected - * number of ranks. - * @note It is not possible to enable both ADC group regular - * continuous mode and sequencer discontinuous mode. - * @note It is not possible to enable both ADC auto-injected mode - * and ADC group regular sequencer discontinuous mode. - * @rmtoll CR1 DISCEN LL_ADC_REG_SetSequencerDiscont\n - * CR1 DISCNUM LL_ADC_REG_SetSequencerDiscont - * @param ADCx ADC instance - * @param SeqDiscont This parameter can be one of the following values: - * @arg @ref LL_ADC_REG_SEQ_DISCONT_DISABLE - * @arg @ref LL_ADC_REG_SEQ_DISCONT_1RANK - * @arg @ref LL_ADC_REG_SEQ_DISCONT_2RANKS - * @arg @ref LL_ADC_REG_SEQ_DISCONT_3RANKS - * @arg @ref LL_ADC_REG_SEQ_DISCONT_4RANKS - * @arg @ref LL_ADC_REG_SEQ_DISCONT_5RANKS - * @arg @ref LL_ADC_REG_SEQ_DISCONT_6RANKS - * @arg @ref LL_ADC_REG_SEQ_DISCONT_7RANKS - * @arg @ref LL_ADC_REG_SEQ_DISCONT_8RANKS - * @retval None - */ -__STATIC_INLINE void LL_ADC_REG_SetSequencerDiscont(ADC_TypeDef *ADCx, uint32_t SeqDiscont) -{ - MODIFY_REG(ADCx->CR1, ADC_CR1_DISCEN | ADC_CR1_DISCNUM, SeqDiscont); -} - -/** - * @brief Get ADC group regular sequencer discontinuous mode: - * sequence subdivided and scan conversions interrupted every selected - * number of ranks. - * @rmtoll CR1 DISCEN LL_ADC_REG_GetSequencerDiscont\n - * CR1 DISCNUM LL_ADC_REG_GetSequencerDiscont - * @param ADCx ADC instance - * @retval Returned value can be one of the following values: - * @arg @ref LL_ADC_REG_SEQ_DISCONT_DISABLE - * @arg @ref LL_ADC_REG_SEQ_DISCONT_1RANK - * @arg @ref LL_ADC_REG_SEQ_DISCONT_2RANKS - * @arg @ref LL_ADC_REG_SEQ_DISCONT_3RANKS - * @arg @ref LL_ADC_REG_SEQ_DISCONT_4RANKS - * @arg @ref LL_ADC_REG_SEQ_DISCONT_5RANKS - * @arg @ref LL_ADC_REG_SEQ_DISCONT_6RANKS - * @arg @ref LL_ADC_REG_SEQ_DISCONT_7RANKS - * @arg @ref LL_ADC_REG_SEQ_DISCONT_8RANKS - */ -__STATIC_INLINE uint32_t LL_ADC_REG_GetSequencerDiscont(ADC_TypeDef *ADCx) -{ - return (uint32_t)(READ_BIT(ADCx->CR1, ADC_CR1_DISCEN | ADC_CR1_DISCNUM)); -} - -/** - * @brief Set ADC group regular sequence: channel on the selected - * scan sequence rank. - * @note This function performs configuration of: - * - Channels ordering into each rank of scan sequence: - * whatever channel can be placed into whatever rank. - * @note On this STM32 serie, ADC group regular sequencer is - * fully configurable: sequencer length and each rank - * affectation to a channel are configurable. - * Refer to description of function @ref LL_ADC_REG_SetSequencerLength(). - * @note Depending on devices and packages, some channels may not be available. - * Refer to device datasheet for channels availability. - * @note On this STM32 serie, to measure internal channels (VrefInt, - * TempSensor, ...), measurement paths to internal channels must be - * enabled separately. - * This can be done using function @ref LL_ADC_SetCommonPathInternalCh(). - * @rmtoll SQR3 SQ1 LL_ADC_REG_SetSequencerRanks\n - * SQR3 SQ2 LL_ADC_REG_SetSequencerRanks\n - * SQR3 SQ3 LL_ADC_REG_SetSequencerRanks\n - * SQR3 SQ4 LL_ADC_REG_SetSequencerRanks\n - * SQR3 SQ5 LL_ADC_REG_SetSequencerRanks\n - * SQR3 SQ6 LL_ADC_REG_SetSequencerRanks\n - * SQR2 SQ7 LL_ADC_REG_SetSequencerRanks\n - * SQR2 SQ8 LL_ADC_REG_SetSequencerRanks\n - * SQR2 SQ9 LL_ADC_REG_SetSequencerRanks\n - * SQR2 SQ10 LL_ADC_REG_SetSequencerRanks\n - * SQR2 SQ11 LL_ADC_REG_SetSequencerRanks\n - * SQR2 SQ12 LL_ADC_REG_SetSequencerRanks\n - * SQR1 SQ13 LL_ADC_REG_SetSequencerRanks\n - * SQR1 SQ14 LL_ADC_REG_SetSequencerRanks\n - * SQR1 SQ15 LL_ADC_REG_SetSequencerRanks\n - * SQR1 SQ16 LL_ADC_REG_SetSequencerRanks - * @param ADCx ADC instance - * @param Rank This parameter can be one of the following values: - * @arg @ref LL_ADC_REG_RANK_1 - * @arg @ref LL_ADC_REG_RANK_2 - * @arg @ref LL_ADC_REG_RANK_3 - * @arg @ref LL_ADC_REG_RANK_4 - * @arg @ref LL_ADC_REG_RANK_5 - * @arg @ref LL_ADC_REG_RANK_6 - * @arg @ref LL_ADC_REG_RANK_7 - * @arg @ref LL_ADC_REG_RANK_8 - * @arg @ref LL_ADC_REG_RANK_9 - * @arg @ref LL_ADC_REG_RANK_10 - * @arg @ref LL_ADC_REG_RANK_11 - * @arg @ref LL_ADC_REG_RANK_12 - * @arg @ref LL_ADC_REG_RANK_13 - * @arg @ref LL_ADC_REG_RANK_14 - * @arg @ref LL_ADC_REG_RANK_15 - * @arg @ref LL_ADC_REG_RANK_16 - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_ADC_CHANNEL_0 - * @arg @ref LL_ADC_CHANNEL_1 - * @arg @ref LL_ADC_CHANNEL_2 - * @arg @ref LL_ADC_CHANNEL_3 - * @arg @ref LL_ADC_CHANNEL_4 - * @arg @ref LL_ADC_CHANNEL_5 - * @arg @ref LL_ADC_CHANNEL_6 - * @arg @ref LL_ADC_CHANNEL_7 - * @arg @ref LL_ADC_CHANNEL_8 - * @arg @ref LL_ADC_CHANNEL_9 - * @arg @ref LL_ADC_CHANNEL_10 - * @arg @ref LL_ADC_CHANNEL_11 - * @arg @ref LL_ADC_CHANNEL_12 - * @arg @ref LL_ADC_CHANNEL_13 - * @arg @ref LL_ADC_CHANNEL_14 - * @arg @ref LL_ADC_CHANNEL_15 - * @arg @ref LL_ADC_CHANNEL_16 - * @arg @ref LL_ADC_CHANNEL_17 - * @arg @ref LL_ADC_CHANNEL_VREFINT (1) - * @arg @ref LL_ADC_CHANNEL_TEMPSENSOR (1) - * - * (1) On STM32F1, parameter available only on ADC instance: ADC1. - * @retval None - */ -__STATIC_INLINE void LL_ADC_REG_SetSequencerRanks(ADC_TypeDef *ADCx, uint32_t Rank, uint32_t Channel) -{ - /* Set bits with content of parameter "Channel" with bits position */ - /* in register and register position depending on parameter "Rank". */ - /* Parameters "Rank" and "Channel" are used with masks because containing */ - /* other bits reserved for other purpose. */ - register uint32_t *preg = __ADC_PTR_REG_OFFSET(ADCx->SQR1, __ADC_MASK_SHIFT(Rank, ADC_REG_SQRX_REGOFFSET_MASK)); - - MODIFY_REG(*preg, - ADC_CHANNEL_ID_NUMBER_MASK << (Rank & ADC_REG_RANK_ID_SQRX_MASK), - (Channel & ADC_CHANNEL_ID_NUMBER_MASK) << (Rank & ADC_REG_RANK_ID_SQRX_MASK)); -} - -/** - * @brief Get ADC group regular sequence: channel on the selected - * scan sequence rank. - * @note On this STM32 serie, ADC group regular sequencer is - * fully configurable: sequencer length and each rank - * affectation to a channel are configurable. - * Refer to description of function @ref LL_ADC_REG_SetSequencerLength(). - * @note Depending on devices and packages, some channels may not be available. - * Refer to device datasheet for channels availability. - * @note Usage of the returned channel number: - * - To reinject this channel into another function LL_ADC_xxx: - * the returned channel number is only partly formatted on definition - * of literals LL_ADC_CHANNEL_x. Therefore, it has to be compared - * with parts of literals LL_ADC_CHANNEL_x or using - * helper macro @ref __LL_ADC_CHANNEL_TO_DECIMAL_NB(). - * Then the selected literal LL_ADC_CHANNEL_x can be used - * as parameter for another function. - * - To get the channel number in decimal format: - * process the returned value with the helper macro - * @ref __LL_ADC_CHANNEL_TO_DECIMAL_NB(). - * @rmtoll SQR3 SQ1 LL_ADC_REG_GetSequencerRanks\n - * SQR3 SQ2 LL_ADC_REG_GetSequencerRanks\n - * SQR3 SQ3 LL_ADC_REG_GetSequencerRanks\n - * SQR3 SQ4 LL_ADC_REG_GetSequencerRanks\n - * SQR3 SQ5 LL_ADC_REG_GetSequencerRanks\n - * SQR3 SQ6 LL_ADC_REG_GetSequencerRanks\n - * SQR2 SQ7 LL_ADC_REG_GetSequencerRanks\n - * SQR2 SQ8 LL_ADC_REG_GetSequencerRanks\n - * SQR2 SQ9 LL_ADC_REG_GetSequencerRanks\n - * SQR2 SQ10 LL_ADC_REG_GetSequencerRanks\n - * SQR2 SQ11 LL_ADC_REG_GetSequencerRanks\n - * SQR2 SQ12 LL_ADC_REG_GetSequencerRanks\n - * SQR1 SQ13 LL_ADC_REG_GetSequencerRanks\n - * SQR1 SQ14 LL_ADC_REG_GetSequencerRanks\n - * SQR1 SQ15 LL_ADC_REG_GetSequencerRanks\n - * SQR1 SQ16 LL_ADC_REG_GetSequencerRanks - * @param ADCx ADC instance - * @param Rank This parameter can be one of the following values: - * @arg @ref LL_ADC_REG_RANK_1 - * @arg @ref LL_ADC_REG_RANK_2 - * @arg @ref LL_ADC_REG_RANK_3 - * @arg @ref LL_ADC_REG_RANK_4 - * @arg @ref LL_ADC_REG_RANK_5 - * @arg @ref LL_ADC_REG_RANK_6 - * @arg @ref LL_ADC_REG_RANK_7 - * @arg @ref LL_ADC_REG_RANK_8 - * @arg @ref LL_ADC_REG_RANK_9 - * @arg @ref LL_ADC_REG_RANK_10 - * @arg @ref LL_ADC_REG_RANK_11 - * @arg @ref LL_ADC_REG_RANK_12 - * @arg @ref LL_ADC_REG_RANK_13 - * @arg @ref LL_ADC_REG_RANK_14 - * @arg @ref LL_ADC_REG_RANK_15 - * @arg @ref LL_ADC_REG_RANK_16 - * @retval Returned value can be one of the following values: - * @arg @ref LL_ADC_CHANNEL_0 - * @arg @ref LL_ADC_CHANNEL_1 - * @arg @ref LL_ADC_CHANNEL_2 - * @arg @ref LL_ADC_CHANNEL_3 - * @arg @ref LL_ADC_CHANNEL_4 - * @arg @ref LL_ADC_CHANNEL_5 - * @arg @ref LL_ADC_CHANNEL_6 - * @arg @ref LL_ADC_CHANNEL_7 - * @arg @ref LL_ADC_CHANNEL_8 - * @arg @ref LL_ADC_CHANNEL_9 - * @arg @ref LL_ADC_CHANNEL_10 - * @arg @ref LL_ADC_CHANNEL_11 - * @arg @ref LL_ADC_CHANNEL_12 - * @arg @ref LL_ADC_CHANNEL_13 - * @arg @ref LL_ADC_CHANNEL_14 - * @arg @ref LL_ADC_CHANNEL_15 - * @arg @ref LL_ADC_CHANNEL_16 - * @arg @ref LL_ADC_CHANNEL_17 - * @arg @ref LL_ADC_CHANNEL_VREFINT (1) - * @arg @ref LL_ADC_CHANNEL_TEMPSENSOR (1) - * - * (1) On STM32F1, parameter available only on ADC instance: ADC1.\n - * (1) For ADC channel read back from ADC register, - * comparison with internal channel parameter to be done - * using helper macro @ref __LL_ADC_CHANNEL_INTERNAL_TO_EXTERNAL(). - */ -__STATIC_INLINE uint32_t LL_ADC_REG_GetSequencerRanks(ADC_TypeDef *ADCx, uint32_t Rank) -{ - register uint32_t *preg = __ADC_PTR_REG_OFFSET(ADCx->SQR1, __ADC_MASK_SHIFT(Rank, ADC_REG_SQRX_REGOFFSET_MASK)); - - return (uint32_t) (READ_BIT(*preg, - ADC_CHANNEL_ID_NUMBER_MASK << (Rank & ADC_REG_RANK_ID_SQRX_MASK)) - >> (Rank & ADC_REG_RANK_ID_SQRX_MASK) - ); -} - -/** - * @brief Set ADC continuous conversion mode on ADC group regular. - * @note Description of ADC continuous conversion mode: - * - single mode: one conversion per trigger - * - continuous mode: after the first trigger, following - * conversions launched successively automatically. - * @note It is not possible to enable both ADC group regular - * continuous mode and sequencer discontinuous mode. - * @rmtoll CR2 CONT LL_ADC_REG_SetContinuousMode - * @param ADCx ADC instance - * @param Continuous This parameter can be one of the following values: - * @arg @ref LL_ADC_REG_CONV_SINGLE - * @arg @ref LL_ADC_REG_CONV_CONTINUOUS - * @retval None - */ -__STATIC_INLINE void LL_ADC_REG_SetContinuousMode(ADC_TypeDef *ADCx, uint32_t Continuous) -{ - MODIFY_REG(ADCx->CR2, ADC_CR2_CONT, Continuous); -} - -/** - * @brief Get ADC continuous conversion mode on ADC group regular. - * @note Description of ADC continuous conversion mode: - * - single mode: one conversion per trigger - * - continuous mode: after the first trigger, following - * conversions launched successively automatically. - * @rmtoll CR2 CONT LL_ADC_REG_GetContinuousMode - * @param ADCx ADC instance - * @retval Returned value can be one of the following values: - * @arg @ref LL_ADC_REG_CONV_SINGLE - * @arg @ref LL_ADC_REG_CONV_CONTINUOUS - */ -__STATIC_INLINE uint32_t LL_ADC_REG_GetContinuousMode(ADC_TypeDef *ADCx) -{ - return (uint32_t)(READ_BIT(ADCx->CR2, ADC_CR2_CONT)); -} - -/** - * @brief Set ADC group regular conversion data transfer: no transfer or - * transfer by DMA, and DMA requests mode. - * @note If transfer by DMA selected, specifies the DMA requests - * mode: - * - Limited mode (One shot mode): DMA transfer requests are stopped - * when number of DMA data transfers (number of - * ADC conversions) is reached. - * This ADC mode is intended to be used with DMA mode non-circular. - * - Unlimited mode: DMA transfer requests are unlimited, - * whatever number of DMA data transfers (number of - * ADC conversions). - * This ADC mode is intended to be used with DMA mode circular. - * @note If ADC DMA requests mode is set to unlimited and DMA is set to - * mode non-circular: - * when DMA transfers size will be reached, DMA will stop transfers of - * ADC conversions data ADC will raise an overrun error - * (overrun flag and interruption if enabled). - * @note To configure DMA source address (peripheral address), - * use function @ref LL_ADC_DMA_GetRegAddr(). - * @rmtoll CR2 DMA LL_ADC_REG_SetDMATransfer - * @param ADCx ADC instance - * @param DMATransfer This parameter can be one of the following values: - * @arg @ref LL_ADC_REG_DMA_TRANSFER_NONE - * @arg @ref LL_ADC_REG_DMA_TRANSFER_UNLIMITED - * @retval None - */ -__STATIC_INLINE void LL_ADC_REG_SetDMATransfer(ADC_TypeDef *ADCx, uint32_t DMATransfer) -{ - MODIFY_REG(ADCx->CR2, ADC_CR2_DMA, DMATransfer); -} - -/** - * @brief Get ADC group regular conversion data transfer: no transfer or - * transfer by DMA, and DMA requests mode. - * @note If transfer by DMA selected, specifies the DMA requests - * mode: - * - Limited mode (One shot mode): DMA transfer requests are stopped - * when number of DMA data transfers (number of - * ADC conversions) is reached. - * This ADC mode is intended to be used with DMA mode non-circular. - * - Unlimited mode: DMA transfer requests are unlimited, - * whatever number of DMA data transfers (number of - * ADC conversions). - * This ADC mode is intended to be used with DMA mode circular. - * @note If ADC DMA requests mode is set to unlimited and DMA is set to - * mode non-circular: - * when DMA transfers size will be reached, DMA will stop transfers of - * ADC conversions data ADC will raise an overrun error - * (overrun flag and interruption if enabled). - * @note To configure DMA source address (peripheral address), - * use function @ref LL_ADC_DMA_GetRegAddr(). - * @rmtoll CR2 DMA LL_ADC_REG_GetDMATransfer - * @param ADCx ADC instance - * @retval Returned value can be one of the following values: - * @arg @ref LL_ADC_REG_DMA_TRANSFER_NONE - * @arg @ref LL_ADC_REG_DMA_TRANSFER_UNLIMITED - */ -__STATIC_INLINE uint32_t LL_ADC_REG_GetDMATransfer(ADC_TypeDef *ADCx) -{ - return (uint32_t)(READ_BIT(ADCx->CR2, ADC_CR2_DMA)); -} - -/** - * @} - */ - -/** @defgroup ADC_LL_EF_Configuration_ADC_Group_Injected Configuration of ADC hierarchical scope: group injected - * @{ - */ - -/** - * @brief Set ADC group injected conversion trigger source: - * internal (SW start) or from external IP (timer event, - * external interrupt line). - * @note On this STM32 serie, external trigger is set with trigger polarity: - * rising edge (only trigger polarity available on this STM32 serie). - * @note Availability of parameters of trigger sources from timer - * depends on timers availability on the selected device. - * @rmtoll CR2 JEXTSEL LL_ADC_INJ_SetTriggerSource - * @param ADCx ADC instance - * @param TriggerSource This parameter can be one of the following values: - * @arg @ref LL_ADC_INJ_TRIG_SOFTWARE - * @arg @ref LL_ADC_INJ_TRIG_EXT_TIM1_TRGO (1) - * @arg @ref LL_ADC_INJ_TRIG_EXT_TIM1_CH4 (1) - * @arg @ref LL_ADC_INJ_TRIG_EXT_TIM2_TRGO (2) - * @arg @ref LL_ADC_INJ_TRIG_EXT_TIM2_CH1 (2) - * @arg @ref LL_ADC_INJ_TRIG_EXT_TIM3_CH4 (2) - * @arg @ref LL_ADC_INJ_TRIG_EXT_TIM4_TRGO (2) - * @arg @ref LL_ADC_INJ_TRIG_EXT_EXTI_LINE15 (2) - * @arg @ref LL_ADC_INJ_TRIG_EXT_TIM8_CH4 (2)(4) - * @arg @ref LL_ADC_INJ_TRIG_EXT_TIM8_CH4_ADC3 (3) - * @arg @ref LL_ADC_INJ_TRIG_EXT_TIM4_CH3 (3) - * @arg @ref LL_ADC_INJ_TRIG_EXT_TIM8_CH2 (3) - * @arg @ref LL_ADC_INJ_TRIG_EXT_TIM8_CH4 (3) - * @arg @ref LL_ADC_INJ_TRIG_EXT_TIM5_TRGO (3) - * @arg @ref LL_ADC_INJ_TRIG_EXT_TIM5_CH4 (3) - * - * (1) On STM32F1, parameter available on all ADC instances: ADC1, ADC2, ADC3 (for ADC instances ADCx available on the selected device).\n - * (2) On STM32F1, parameter available only on ADC instances: ADC1, ADC2 (for ADC instances ADCx available on the selected device).\n - * (3) On STM32F1, parameter available only on ADC instances: ADC3 (for ADC instances ADCx available on the selected device).\n - * (4) On STM32F1, parameter available only on high-density and XL-density devices. A remap of trigger must be done at top level (refer to AFIO peripheral). - * @retval None - */ -__STATIC_INLINE void LL_ADC_INJ_SetTriggerSource(ADC_TypeDef *ADCx, uint32_t TriggerSource) -{ -/* Note: On this STM32 serie, ADC group injected external trigger edge */ -/* is used to perform a ADC conversion start. */ -/* This function does not set external trigger edge. */ -/* This feature is set using function */ -/* @ref LL_ADC_INJ_StartConversionExtTrig(). */ - MODIFY_REG(ADCx->CR2, ADC_CR2_JEXTSEL, (TriggerSource & ADC_CR2_JEXTSEL)); -} - -/** - * @brief Get ADC group injected conversion trigger source: - * internal (SW start) or from external IP (timer event, - * external interrupt line). - * @note To determine whether group injected trigger source is - * internal (SW start) or external, without detail - * of which peripheral is selected as external trigger, - * (equivalent to - * "if(LL_ADC_INJ_GetTriggerSource(ADC1) == LL_ADC_INJ_TRIG_SOFTWARE)") - * use function @ref LL_ADC_INJ_IsTriggerSourceSWStart. - * @note Availability of parameters of trigger sources from timer - * depends on timers availability on the selected device. - * @rmtoll CR2 JEXTSEL LL_ADC_INJ_GetTriggerSource - * @param ADCx ADC instance - * @retval Returned value can be one of the following values: - * @arg @ref LL_ADC_INJ_TRIG_SOFTWARE - * @arg @ref LL_ADC_INJ_TRIG_EXT_TIM1_TRGO (1) - * @arg @ref LL_ADC_INJ_TRIG_EXT_TIM1_CH4 (1) - * @arg @ref LL_ADC_INJ_TRIG_EXT_TIM2_TRGO (2) - * @arg @ref LL_ADC_INJ_TRIG_EXT_TIM2_CH1 (2) - * @arg @ref LL_ADC_INJ_TRIG_EXT_TIM3_CH4 (2) - * @arg @ref LL_ADC_INJ_TRIG_EXT_TIM4_TRGO (2) - * @arg @ref LL_ADC_INJ_TRIG_EXT_EXTI_LINE15 (2) - * @arg @ref LL_ADC_INJ_TRIG_EXT_TIM8_CH4 (2)(4) - * @arg @ref LL_ADC_INJ_TRIG_EXT_TIM8_CH4_ADC3 (3) - * @arg @ref LL_ADC_INJ_TRIG_EXT_TIM4_CH3 (3) - * @arg @ref LL_ADC_INJ_TRIG_EXT_TIM8_CH2 (3) - * @arg @ref LL_ADC_INJ_TRIG_EXT_TIM8_CH4 (3) - * @arg @ref LL_ADC_INJ_TRIG_EXT_TIM5_TRGO (3) - * @arg @ref LL_ADC_INJ_TRIG_EXT_TIM5_CH4 (3) - * - * (1) On STM32F1, parameter available on all ADC instances: ADC1, ADC2, ADC3 (for ADC instances ADCx available on the selected device).\n - * (2) On STM32F1, parameter available only on ADC instances: ADC1, ADC2 (for ADC instances ADCx available on the selected device).\n - * (3) On STM32F1, parameter available only on ADC instances: ADC3 (for ADC instances ADCx available on the selected device).\n - * (4) On STM32F1, parameter available only on high-density and XL-density devices. A remap of trigger must be done at top level (refer to AFIO peripheral). - */ -__STATIC_INLINE uint32_t LL_ADC_INJ_GetTriggerSource(ADC_TypeDef *ADCx) -{ - return (uint32_t)(READ_BIT(ADCx->CR2, ADC_CR2_JEXTSEL)); -} - -/** - * @brief Get ADC group injected conversion trigger source internal (SW start) - or external - * @note In case of group injected trigger source set to external trigger, - * to determine which peripheral is selected as external trigger, - * use function @ref LL_ADC_INJ_GetTriggerSource. - * @rmtoll CR2 JEXTSEL LL_ADC_INJ_IsTriggerSourceSWStart - * @param ADCx ADC instance - * @retval Value "0" if trigger source external trigger - * Value "1" if trigger source SW start. - */ -__STATIC_INLINE uint32_t LL_ADC_INJ_IsTriggerSourceSWStart(ADC_TypeDef *ADCx) -{ - return (READ_BIT(ADCx->CR2, ADC_CR2_JEXTSEL) == LL_ADC_INJ_TRIG_SOFTWARE); -} - -/** - * @brief Set ADC group injected sequencer length and scan direction. - * @note This function performs configuration of: - * - Sequence length: Number of ranks in the scan sequence. - * - Sequence direction: Unless specified in parameters, sequencer - * scan direction is forward (from rank 1 to rank n). - * @note On this STM32 serie, group injected sequencer configuration - * is conditioned to ADC instance sequencer mode. - * If ADC instance sequencer mode is disabled, sequencers of - * all groups (group regular, group injected) can be configured - * but their execution is disabled (limited to rank 1). - * Refer to function @ref LL_ADC_SetSequencersScanMode(). - * @note Sequencer disabled is equivalent to sequencer of 1 rank: - * ADC conversion on only 1 channel. - * @rmtoll JSQR JL LL_ADC_INJ_SetSequencerLength - * @param ADCx ADC instance - * @param SequencerNbRanks This parameter can be one of the following values: - * @arg @ref LL_ADC_INJ_SEQ_SCAN_DISABLE - * @arg @ref LL_ADC_INJ_SEQ_SCAN_ENABLE_2RANKS - * @arg @ref LL_ADC_INJ_SEQ_SCAN_ENABLE_3RANKS - * @arg @ref LL_ADC_INJ_SEQ_SCAN_ENABLE_4RANKS - * @retval None - */ -__STATIC_INLINE void LL_ADC_INJ_SetSequencerLength(ADC_TypeDef *ADCx, uint32_t SequencerNbRanks) -{ - MODIFY_REG(ADCx->JSQR, ADC_JSQR_JL, SequencerNbRanks); -} - -/** - * @brief Get ADC group injected sequencer length and scan direction. - * @note This function retrieves: - * - Sequence length: Number of ranks in the scan sequence. - * - Sequence direction: Unless specified in parameters, sequencer - * scan direction is forward (from rank 1 to rank n). - * @note On this STM32 serie, group injected sequencer configuration - * is conditioned to ADC instance sequencer mode. - * If ADC instance sequencer mode is disabled, sequencers of - * all groups (group regular, group injected) can be configured - * but their execution is disabled (limited to rank 1). - * Refer to function @ref LL_ADC_SetSequencersScanMode(). - * @note Sequencer disabled is equivalent to sequencer of 1 rank: - * ADC conversion on only 1 channel. - * @rmtoll JSQR JL LL_ADC_INJ_GetSequencerLength - * @param ADCx ADC instance - * @retval Returned value can be one of the following values: - * @arg @ref LL_ADC_INJ_SEQ_SCAN_DISABLE - * @arg @ref LL_ADC_INJ_SEQ_SCAN_ENABLE_2RANKS - * @arg @ref LL_ADC_INJ_SEQ_SCAN_ENABLE_3RANKS - * @arg @ref LL_ADC_INJ_SEQ_SCAN_ENABLE_4RANKS - */ -__STATIC_INLINE uint32_t LL_ADC_INJ_GetSequencerLength(ADC_TypeDef *ADCx) -{ - return (uint32_t)(READ_BIT(ADCx->JSQR, ADC_JSQR_JL)); -} - -/** - * @brief Set ADC group injected sequencer discontinuous mode: - * sequence subdivided and scan conversions interrupted every selected - * number of ranks. - * @note It is not possible to enable both ADC group injected - * auto-injected mode and sequencer discontinuous mode. - * @rmtoll CR1 DISCEN LL_ADC_INJ_SetSequencerDiscont - * @param ADCx ADC instance - * @param SeqDiscont This parameter can be one of the following values: - * @arg @ref LL_ADC_INJ_SEQ_DISCONT_DISABLE - * @arg @ref LL_ADC_INJ_SEQ_DISCONT_1RANK - * @retval None - */ -__STATIC_INLINE void LL_ADC_INJ_SetSequencerDiscont(ADC_TypeDef *ADCx, uint32_t SeqDiscont) -{ - MODIFY_REG(ADCx->CR1, ADC_CR1_JDISCEN, SeqDiscont); -} - -/** - * @brief Get ADC group injected sequencer discontinuous mode: - * sequence subdivided and scan conversions interrupted every selected - * number of ranks. - * @rmtoll CR1 DISCEN LL_ADC_REG_GetSequencerDiscont - * @param ADCx ADC instance - * @retval Returned value can be one of the following values: - * @arg @ref LL_ADC_INJ_SEQ_DISCONT_DISABLE - * @arg @ref LL_ADC_INJ_SEQ_DISCONT_1RANK - */ -__STATIC_INLINE uint32_t LL_ADC_INJ_GetSequencerDiscont(ADC_TypeDef *ADCx) -{ - return (uint32_t)(READ_BIT(ADCx->CR1, ADC_CR1_JDISCEN)); -} - -/** - * @brief Set ADC group injected sequence: channel on the selected - * sequence rank. - * @note Depending on devices and packages, some channels may not be available. - * Refer to device datasheet for channels availability. - * @note On this STM32 serie, to measure internal channels (VrefInt, - * TempSensor, ...), measurement paths to internal channels must be - * enabled separately. - * This can be done using function @ref LL_ADC_SetCommonPathInternalCh(). - * @rmtoll JSQR JSQ1 LL_ADC_INJ_SetSequencerRanks\n - * JSQR JSQ2 LL_ADC_INJ_SetSequencerRanks\n - * JSQR JSQ3 LL_ADC_INJ_SetSequencerRanks\n - * JSQR JSQ4 LL_ADC_INJ_SetSequencerRanks - * @param ADCx ADC instance - * @param Rank This parameter can be one of the following values: - * @arg @ref LL_ADC_INJ_RANK_1 - * @arg @ref LL_ADC_INJ_RANK_2 - * @arg @ref LL_ADC_INJ_RANK_3 - * @arg @ref LL_ADC_INJ_RANK_4 - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_ADC_CHANNEL_0 - * @arg @ref LL_ADC_CHANNEL_1 - * @arg @ref LL_ADC_CHANNEL_2 - * @arg @ref LL_ADC_CHANNEL_3 - * @arg @ref LL_ADC_CHANNEL_4 - * @arg @ref LL_ADC_CHANNEL_5 - * @arg @ref LL_ADC_CHANNEL_6 - * @arg @ref LL_ADC_CHANNEL_7 - * @arg @ref LL_ADC_CHANNEL_8 - * @arg @ref LL_ADC_CHANNEL_9 - * @arg @ref LL_ADC_CHANNEL_10 - * @arg @ref LL_ADC_CHANNEL_11 - * @arg @ref LL_ADC_CHANNEL_12 - * @arg @ref LL_ADC_CHANNEL_13 - * @arg @ref LL_ADC_CHANNEL_14 - * @arg @ref LL_ADC_CHANNEL_15 - * @arg @ref LL_ADC_CHANNEL_16 - * @arg @ref LL_ADC_CHANNEL_17 - * @arg @ref LL_ADC_CHANNEL_VREFINT (1) - * @arg @ref LL_ADC_CHANNEL_TEMPSENSOR (1) - * - * (1) On STM32F1, parameter available only on ADC instance: ADC1. - * @retval None - */ -__STATIC_INLINE void LL_ADC_INJ_SetSequencerRanks(ADC_TypeDef *ADCx, uint32_t Rank, uint32_t Channel) -{ - /* Set bits with content of parameter "Channel" with bits position */ - /* in register depending on parameter "Rank". */ - /* Parameters "Rank" and "Channel" are used with masks because containing */ - /* other bits reserved for other purpose. */ - register uint32_t tmpreg1 = (READ_BIT(ADCx->JSQR, ADC_JSQR_JL) >> ADC_JSQR_JL_Pos) + 1U; - - MODIFY_REG(ADCx->JSQR, - ADC_CHANNEL_ID_NUMBER_MASK << (5U * (uint8_t)(((Rank) + 3U) - (tmpreg1))), - (Channel & ADC_CHANNEL_ID_NUMBER_MASK) << (5U * (uint8_t)(((Rank) + 3U) - (tmpreg1)))); -} - -/** - * @brief Get ADC group injected sequence: channel on the selected - * sequence rank. - * @note Depending on devices and packages, some channels may not be available. - * Refer to device datasheet for channels availability. - * @note Usage of the returned channel number: - * - To reinject this channel into another function LL_ADC_xxx: - * the returned channel number is only partly formatted on definition - * of literals LL_ADC_CHANNEL_x. Therefore, it has to be compared - * with parts of literals LL_ADC_CHANNEL_x or using - * helper macro @ref __LL_ADC_CHANNEL_TO_DECIMAL_NB(). - * Then the selected literal LL_ADC_CHANNEL_x can be used - * as parameter for another function. - * - To get the channel number in decimal format: - * process the returned value with the helper macro - * @ref __LL_ADC_CHANNEL_TO_DECIMAL_NB(). - * @rmtoll JSQR JSQ1 LL_ADC_INJ_SetSequencerRanks\n - * JSQR JSQ2 LL_ADC_INJ_SetSequencerRanks\n - * JSQR JSQ3 LL_ADC_INJ_SetSequencerRanks\n - * JSQR JSQ4 LL_ADC_INJ_SetSequencerRanks - * @param ADCx ADC instance - * @param Rank This parameter can be one of the following values: - * @arg @ref LL_ADC_INJ_RANK_1 - * @arg @ref LL_ADC_INJ_RANK_2 - * @arg @ref LL_ADC_INJ_RANK_3 - * @arg @ref LL_ADC_INJ_RANK_4 - * @retval Returned value can be one of the following values: - * @arg @ref LL_ADC_CHANNEL_0 - * @arg @ref LL_ADC_CHANNEL_1 - * @arg @ref LL_ADC_CHANNEL_2 - * @arg @ref LL_ADC_CHANNEL_3 - * @arg @ref LL_ADC_CHANNEL_4 - * @arg @ref LL_ADC_CHANNEL_5 - * @arg @ref LL_ADC_CHANNEL_6 - * @arg @ref LL_ADC_CHANNEL_7 - * @arg @ref LL_ADC_CHANNEL_8 - * @arg @ref LL_ADC_CHANNEL_9 - * @arg @ref LL_ADC_CHANNEL_10 - * @arg @ref LL_ADC_CHANNEL_11 - * @arg @ref LL_ADC_CHANNEL_12 - * @arg @ref LL_ADC_CHANNEL_13 - * @arg @ref LL_ADC_CHANNEL_14 - * @arg @ref LL_ADC_CHANNEL_15 - * @arg @ref LL_ADC_CHANNEL_16 - * @arg @ref LL_ADC_CHANNEL_17 - * @arg @ref LL_ADC_CHANNEL_VREFINT (1) - * @arg @ref LL_ADC_CHANNEL_TEMPSENSOR (1) - * - * (1) On STM32F1, parameter available only on ADC instance: ADC1.\n - * (1) For ADC channel read back from ADC register, - * comparison with internal channel parameter to be done - * using helper macro @ref __LL_ADC_CHANNEL_INTERNAL_TO_EXTERNAL(). - */ -__STATIC_INLINE uint32_t LL_ADC_INJ_GetSequencerRanks(ADC_TypeDef *ADCx, uint32_t Rank) -{ - register uint32_t tmpreg1 = (READ_BIT(ADCx->JSQR, ADC_JSQR_JL) >> ADC_JSQR_JL_Pos) + 1U; - - return (uint32_t)(READ_BIT(ADCx->JSQR, - ADC_CHANNEL_ID_NUMBER_MASK << (5U * (uint8_t)(((Rank) + 3U) - (tmpreg1)))) - >> (5U * (uint8_t)(((Rank) + 3U) - (tmpreg1))) - ); -} - -/** - * @brief Set ADC group injected conversion trigger: - * independent or from ADC group regular. - * @note This mode can be used to extend number of data registers - * updated after one ADC conversion trigger and with data - * permanently kept (not erased by successive conversions of scan of - * ADC sequencer ranks), up to 5 data registers: - * 1 data register on ADC group regular, 4 data registers - * on ADC group injected. - * @note If ADC group injected injected trigger source is set to an - * external trigger, this feature must be must be set to - * independent trigger. - * ADC group injected automatic trigger is compliant only with - * group injected trigger source set to SW start, without any - * further action on ADC group injected conversion start or stop: - * in this case, ADC group injected is controlled only - * from ADC group regular. - * @note It is not possible to enable both ADC group injected - * auto-injected mode and sequencer discontinuous mode. - * @rmtoll CR1 JAUTO LL_ADC_INJ_SetTrigAuto - * @param ADCx ADC instance - * @param TrigAuto This parameter can be one of the following values: - * @arg @ref LL_ADC_INJ_TRIG_INDEPENDENT - * @arg @ref LL_ADC_INJ_TRIG_FROM_GRP_REGULAR - * @retval None - */ -__STATIC_INLINE void LL_ADC_INJ_SetTrigAuto(ADC_TypeDef *ADCx, uint32_t TrigAuto) -{ - MODIFY_REG(ADCx->CR1, ADC_CR1_JAUTO, TrigAuto); -} - -/** - * @brief Get ADC group injected conversion trigger: - * independent or from ADC group regular. - * @rmtoll CR1 JAUTO LL_ADC_INJ_GetTrigAuto - * @param ADCx ADC instance - * @retval Returned value can be one of the following values: - * @arg @ref LL_ADC_INJ_TRIG_INDEPENDENT - * @arg @ref LL_ADC_INJ_TRIG_FROM_GRP_REGULAR - */ -__STATIC_INLINE uint32_t LL_ADC_INJ_GetTrigAuto(ADC_TypeDef *ADCx) -{ - return (uint32_t)(READ_BIT(ADCx->CR1, ADC_CR1_JAUTO)); -} - -/** - * @brief Set ADC group injected offset. - * @note It sets: - * - ADC group injected rank to which the offset programmed - * will be applied - * - Offset level (offset to be subtracted from the raw - * converted data). - * Caution: Offset format is dependent to ADC resolution: - * offset has to be left-aligned on bit 11, the LSB (right bits) - * are set to 0. - * @note Offset cannot be enabled or disabled. - * To emulate offset disabled, set an offset value equal to 0. - * @rmtoll JOFR1 JOFFSET1 LL_ADC_INJ_SetOffset\n - * JOFR2 JOFFSET2 LL_ADC_INJ_SetOffset\n - * JOFR3 JOFFSET3 LL_ADC_INJ_SetOffset\n - * JOFR4 JOFFSET4 LL_ADC_INJ_SetOffset - * @param ADCx ADC instance - * @param Rank This parameter can be one of the following values: - * @arg @ref LL_ADC_INJ_RANK_1 - * @arg @ref LL_ADC_INJ_RANK_2 - * @arg @ref LL_ADC_INJ_RANK_3 - * @arg @ref LL_ADC_INJ_RANK_4 - * @param OffsetLevel Value between Min_Data=0x000 and Max_Data=0xFFF - * @retval None - */ -__STATIC_INLINE void LL_ADC_INJ_SetOffset(ADC_TypeDef *ADCx, uint32_t Rank, uint32_t OffsetLevel) -{ - register uint32_t *preg = __ADC_PTR_REG_OFFSET(ADCx->JOFR1, __ADC_MASK_SHIFT(Rank, ADC_INJ_JOFRX_REGOFFSET_MASK)); - - MODIFY_REG(*preg, - ADC_JOFR1_JOFFSET1, - OffsetLevel); -} - -/** - * @brief Get ADC group injected offset. - * @note It gives offset level (offset to be subtracted from the raw converted data). - * Caution: Offset format is dependent to ADC resolution: - * offset has to be left-aligned on bit 11, the LSB (right bits) - * are set to 0. - * @rmtoll JOFR1 JOFFSET1 LL_ADC_INJ_GetOffset\n - * JOFR2 JOFFSET2 LL_ADC_INJ_GetOffset\n - * JOFR3 JOFFSET3 LL_ADC_INJ_GetOffset\n - * JOFR4 JOFFSET4 LL_ADC_INJ_GetOffset - * @param ADCx ADC instance - * @param Rank This parameter can be one of the following values: - * @arg @ref LL_ADC_INJ_RANK_1 - * @arg @ref LL_ADC_INJ_RANK_2 - * @arg @ref LL_ADC_INJ_RANK_3 - * @arg @ref LL_ADC_INJ_RANK_4 - * @retval Value between Min_Data=0x000 and Max_Data=0xFFF - */ -__STATIC_INLINE uint32_t LL_ADC_INJ_GetOffset(ADC_TypeDef *ADCx, uint32_t Rank) -{ - register uint32_t *preg = __ADC_PTR_REG_OFFSET(ADCx->JOFR1, __ADC_MASK_SHIFT(Rank, ADC_INJ_JOFRX_REGOFFSET_MASK)); - - return (uint32_t)(READ_BIT(*preg, - ADC_JOFR1_JOFFSET1) - ); -} - -/** - * @} - */ - -/** @defgroup ADC_LL_EF_Configuration_Channels Configuration of ADC hierarchical scope: channels - * @{ - */ - -/** - * @brief Set sampling time of the selected ADC channel - * Unit: ADC clock cycles. - * @note On this device, sampling time is on channel scope: independently - * of channel mapped on ADC group regular or injected. - * @note In case of internal channel (VrefInt, TempSensor, ...) to be - * converted: - * sampling time constraints must be respected (sampling time can be - * adjusted in function of ADC clock frequency and sampling time - * setting). - * Refer to device datasheet for timings values (parameters TS_vrefint, - * TS_temp, ...). - * @note Conversion time is the addition of sampling time and processing time. - * Refer to reference manual for ADC processing time of - * this STM32 serie. - * @note In case of ADC conversion of internal channel (VrefInt, - * temperature sensor, ...), a sampling time minimum value - * is required. - * Refer to device datasheet. - * @rmtoll SMPR1 SMP17 LL_ADC_SetChannelSamplingTime\n - * SMPR1 SMP16 LL_ADC_SetChannelSamplingTime\n - * SMPR1 SMP15 LL_ADC_SetChannelSamplingTime\n - * SMPR1 SMP14 LL_ADC_SetChannelSamplingTime\n - * SMPR1 SMP13 LL_ADC_SetChannelSamplingTime\n - * SMPR1 SMP12 LL_ADC_SetChannelSamplingTime\n - * SMPR1 SMP11 LL_ADC_SetChannelSamplingTime\n - * SMPR1 SMP10 LL_ADC_SetChannelSamplingTime\n - * SMPR2 SMP9 LL_ADC_SetChannelSamplingTime\n - * SMPR2 SMP8 LL_ADC_SetChannelSamplingTime\n - * SMPR2 SMP7 LL_ADC_SetChannelSamplingTime\n - * SMPR2 SMP6 LL_ADC_SetChannelSamplingTime\n - * SMPR2 SMP5 LL_ADC_SetChannelSamplingTime\n - * SMPR2 SMP4 LL_ADC_SetChannelSamplingTime\n - * SMPR2 SMP3 LL_ADC_SetChannelSamplingTime\n - * SMPR2 SMP2 LL_ADC_SetChannelSamplingTime\n - * SMPR2 SMP1 LL_ADC_SetChannelSamplingTime\n - * SMPR2 SMP0 LL_ADC_SetChannelSamplingTime - * @param ADCx ADC instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_ADC_CHANNEL_0 - * @arg @ref LL_ADC_CHANNEL_1 - * @arg @ref LL_ADC_CHANNEL_2 - * @arg @ref LL_ADC_CHANNEL_3 - * @arg @ref LL_ADC_CHANNEL_4 - * @arg @ref LL_ADC_CHANNEL_5 - * @arg @ref LL_ADC_CHANNEL_6 - * @arg @ref LL_ADC_CHANNEL_7 - * @arg @ref LL_ADC_CHANNEL_8 - * @arg @ref LL_ADC_CHANNEL_9 - * @arg @ref LL_ADC_CHANNEL_10 - * @arg @ref LL_ADC_CHANNEL_11 - * @arg @ref LL_ADC_CHANNEL_12 - * @arg @ref LL_ADC_CHANNEL_13 - * @arg @ref LL_ADC_CHANNEL_14 - * @arg @ref LL_ADC_CHANNEL_15 - * @arg @ref LL_ADC_CHANNEL_16 - * @arg @ref LL_ADC_CHANNEL_17 - * @arg @ref LL_ADC_CHANNEL_VREFINT (1) - * @arg @ref LL_ADC_CHANNEL_TEMPSENSOR (1) - * - * (1) On STM32F1, parameter available only on ADC instance: ADC1. - * @param SamplingTime This parameter can be one of the following values: - * @arg @ref LL_ADC_SAMPLINGTIME_1CYCLE_5 - * @arg @ref LL_ADC_SAMPLINGTIME_7CYCLES_5 - * @arg @ref LL_ADC_SAMPLINGTIME_13CYCLES_5 - * @arg @ref LL_ADC_SAMPLINGTIME_28CYCLES_5 - * @arg @ref LL_ADC_SAMPLINGTIME_41CYCLES_5 - * @arg @ref LL_ADC_SAMPLINGTIME_55CYCLES_5 - * @arg @ref LL_ADC_SAMPLINGTIME_71CYCLES_5 - * @arg @ref LL_ADC_SAMPLINGTIME_239CYCLES_5 - * @retval None - */ -__STATIC_INLINE void LL_ADC_SetChannelSamplingTime(ADC_TypeDef *ADCx, uint32_t Channel, uint32_t SamplingTime) -{ - /* Set bits with content of parameter "SamplingTime" with bits position */ - /* in register and register position depending on parameter "Channel". */ - /* Parameter "Channel" is used with masks because containing */ - /* other bits reserved for other purpose. */ - register uint32_t *preg = __ADC_PTR_REG_OFFSET(ADCx->SMPR1, __ADC_MASK_SHIFT(Channel, ADC_CHANNEL_SMPRX_REGOFFSET_MASK)); - - MODIFY_REG(*preg, - ADC_SMPR2_SMP0 << __ADC_MASK_SHIFT(Channel, ADC_CHANNEL_SMPx_BITOFFSET_MASK), - SamplingTime << __ADC_MASK_SHIFT(Channel, ADC_CHANNEL_SMPx_BITOFFSET_MASK)); -} - -/** - * @brief Get sampling time of the selected ADC channel - * Unit: ADC clock cycles. - * @note On this device, sampling time is on channel scope: independently - * of channel mapped on ADC group regular or injected. - * @note Conversion time is the addition of sampling time and processing time. - * Refer to reference manual for ADC processing time of - * this STM32 serie. - * @rmtoll SMPR1 SMP17 LL_ADC_GetChannelSamplingTime\n - * SMPR1 SMP16 LL_ADC_GetChannelSamplingTime\n - * SMPR1 SMP15 LL_ADC_GetChannelSamplingTime\n - * SMPR1 SMP14 LL_ADC_GetChannelSamplingTime\n - * SMPR1 SMP13 LL_ADC_GetChannelSamplingTime\n - * SMPR1 SMP12 LL_ADC_GetChannelSamplingTime\n - * SMPR1 SMP11 LL_ADC_GetChannelSamplingTime\n - * SMPR1 SMP10 LL_ADC_GetChannelSamplingTime\n - * SMPR2 SMP9 LL_ADC_GetChannelSamplingTime\n - * SMPR2 SMP8 LL_ADC_GetChannelSamplingTime\n - * SMPR2 SMP7 LL_ADC_GetChannelSamplingTime\n - * SMPR2 SMP6 LL_ADC_GetChannelSamplingTime\n - * SMPR2 SMP5 LL_ADC_GetChannelSamplingTime\n - * SMPR2 SMP4 LL_ADC_GetChannelSamplingTime\n - * SMPR2 SMP3 LL_ADC_GetChannelSamplingTime\n - * SMPR2 SMP2 LL_ADC_GetChannelSamplingTime\n - * SMPR2 SMP1 LL_ADC_GetChannelSamplingTime\n - * SMPR2 SMP0 LL_ADC_GetChannelSamplingTime - * @param ADCx ADC instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_ADC_CHANNEL_0 - * @arg @ref LL_ADC_CHANNEL_1 - * @arg @ref LL_ADC_CHANNEL_2 - * @arg @ref LL_ADC_CHANNEL_3 - * @arg @ref LL_ADC_CHANNEL_4 - * @arg @ref LL_ADC_CHANNEL_5 - * @arg @ref LL_ADC_CHANNEL_6 - * @arg @ref LL_ADC_CHANNEL_7 - * @arg @ref LL_ADC_CHANNEL_8 - * @arg @ref LL_ADC_CHANNEL_9 - * @arg @ref LL_ADC_CHANNEL_10 - * @arg @ref LL_ADC_CHANNEL_11 - * @arg @ref LL_ADC_CHANNEL_12 - * @arg @ref LL_ADC_CHANNEL_13 - * @arg @ref LL_ADC_CHANNEL_14 - * @arg @ref LL_ADC_CHANNEL_15 - * @arg @ref LL_ADC_CHANNEL_16 - * @arg @ref LL_ADC_CHANNEL_17 - * @arg @ref LL_ADC_CHANNEL_VREFINT (1) - * @arg @ref LL_ADC_CHANNEL_TEMPSENSOR (1) - * - * (1) On STM32F1, parameter available only on ADC instance: ADC1. - * @retval Returned value can be one of the following values: - * @arg @ref LL_ADC_SAMPLINGTIME_1CYCLE_5 - * @arg @ref LL_ADC_SAMPLINGTIME_7CYCLES_5 - * @arg @ref LL_ADC_SAMPLINGTIME_13CYCLES_5 - * @arg @ref LL_ADC_SAMPLINGTIME_28CYCLES_5 - * @arg @ref LL_ADC_SAMPLINGTIME_41CYCLES_5 - * @arg @ref LL_ADC_SAMPLINGTIME_55CYCLES_5 - * @arg @ref LL_ADC_SAMPLINGTIME_71CYCLES_5 - * @arg @ref LL_ADC_SAMPLINGTIME_239CYCLES_5 - */ -__STATIC_INLINE uint32_t LL_ADC_GetChannelSamplingTime(ADC_TypeDef *ADCx, uint32_t Channel) -{ - register uint32_t *preg = __ADC_PTR_REG_OFFSET(ADCx->SMPR1, __ADC_MASK_SHIFT(Channel, ADC_CHANNEL_SMPRX_REGOFFSET_MASK)); - - return (uint32_t)(READ_BIT(*preg, - ADC_SMPR2_SMP0 << __ADC_MASK_SHIFT(Channel, ADC_CHANNEL_SMPx_BITOFFSET_MASK)) - >> __ADC_MASK_SHIFT(Channel, ADC_CHANNEL_SMPx_BITOFFSET_MASK) - ); -} - -/** - * @} - */ - -/** @defgroup ADC_LL_EF_Configuration_ADC_AnalogWatchdog Configuration of ADC transversal scope: analog watchdog - * @{ - */ - -/** - * @brief Set ADC analog watchdog monitored channels: - * a single channel or all channels, - * on ADC groups regular and-or injected. - * @note Once monitored channels are selected, analog watchdog - * is enabled. - * @note In case of need to define a single channel to monitor - * with analog watchdog from sequencer channel definition, - * use helper macro @ref __LL_ADC_ANALOGWD_CHANNEL_GROUP(). - * @note On this STM32 serie, there is only 1 kind of analog watchdog - * instance: - * - AWD standard (instance AWD1): - * - channels monitored: can monitor 1 channel or all channels. - * - groups monitored: ADC groups regular and-or injected. - * - resolution: resolution is not limited (corresponds to - * ADC resolution configured). - * @rmtoll CR1 AWD1CH LL_ADC_SetAnalogWDMonitChannels\n - * CR1 AWD1SGL LL_ADC_SetAnalogWDMonitChannels\n - * CR1 AWD1EN LL_ADC_SetAnalogWDMonitChannels - * @param ADCx ADC instance - * @param AWDChannelGroup This parameter can be one of the following values: - * @arg @ref LL_ADC_AWD_DISABLE - * @arg @ref LL_ADC_AWD_ALL_CHANNELS_REG - * @arg @ref LL_ADC_AWD_ALL_CHANNELS_INJ - * @arg @ref LL_ADC_AWD_ALL_CHANNELS_REG_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_0_REG - * @arg @ref LL_ADC_AWD_CHANNEL_0_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_0_REG_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_1_REG - * @arg @ref LL_ADC_AWD_CHANNEL_1_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_1_REG_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_2_REG - * @arg @ref LL_ADC_AWD_CHANNEL_2_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_2_REG_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_3_REG - * @arg @ref LL_ADC_AWD_CHANNEL_3_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_3_REG_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_4_REG - * @arg @ref LL_ADC_AWD_CHANNEL_4_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_4_REG_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_5_REG - * @arg @ref LL_ADC_AWD_CHANNEL_5_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_5_REG_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_6_REG - * @arg @ref LL_ADC_AWD_CHANNEL_6_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_6_REG_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_7_REG - * @arg @ref LL_ADC_AWD_CHANNEL_7_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_7_REG_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_8_REG - * @arg @ref LL_ADC_AWD_CHANNEL_8_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_8_REG_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_9_REG - * @arg @ref LL_ADC_AWD_CHANNEL_9_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_9_REG_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_10_REG - * @arg @ref LL_ADC_AWD_CHANNEL_10_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_10_REG_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_11_REG - * @arg @ref LL_ADC_AWD_CHANNEL_11_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_11_REG_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_12_REG - * @arg @ref LL_ADC_AWD_CHANNEL_12_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_12_REG_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_13_REG - * @arg @ref LL_ADC_AWD_CHANNEL_13_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_13_REG_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_14_REG - * @arg @ref LL_ADC_AWD_CHANNEL_14_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_14_REG_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_15_REG - * @arg @ref LL_ADC_AWD_CHANNEL_15_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_15_REG_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_16_REG - * @arg @ref LL_ADC_AWD_CHANNEL_16_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_16_REG_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_17_REG - * @arg @ref LL_ADC_AWD_CHANNEL_17_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_17_REG_INJ - * @arg @ref LL_ADC_AWD_CH_VREFINT_REG (1) - * @arg @ref LL_ADC_AWD_CH_VREFINT_INJ (1) - * @arg @ref LL_ADC_AWD_CH_VREFINT_REG_INJ (1) - * @arg @ref LL_ADC_AWD_CH_TEMPSENSOR_REG (1) - * @arg @ref LL_ADC_AWD_CH_TEMPSENSOR_INJ (1) - * @arg @ref LL_ADC_AWD_CH_TEMPSENSOR_REG_INJ (1) - * - * (1) On STM32F1, parameter available only on ADC instance: ADC1. - * @retval None - */ -__STATIC_INLINE void LL_ADC_SetAnalogWDMonitChannels(ADC_TypeDef *ADCx, uint32_t AWDChannelGroup) -{ - MODIFY_REG(ADCx->CR1, - (ADC_CR1_AWDEN | ADC_CR1_JAWDEN | ADC_CR1_AWDSGL | ADC_CR1_AWDCH), - AWDChannelGroup); -} - -/** - * @brief Get ADC analog watchdog monitored channel. - * @note Usage of the returned channel number: - * - To reinject this channel into another function LL_ADC_xxx: - * the returned channel number is only partly formatted on definition - * of literals LL_ADC_CHANNEL_x. Therefore, it has to be compared - * with parts of literals LL_ADC_CHANNEL_x or using - * helper macro @ref __LL_ADC_CHANNEL_TO_DECIMAL_NB(). - * Then the selected literal LL_ADC_CHANNEL_x can be used - * as parameter for another function. - * - To get the channel number in decimal format: - * process the returned value with the helper macro - * @ref __LL_ADC_CHANNEL_TO_DECIMAL_NB(). - * Applicable only when the analog watchdog is set to monitor - * one channel. - * @note On this STM32 serie, there is only 1 kind of analog watchdog - * instance: - * - AWD standard (instance AWD1): - * - channels monitored: can monitor 1 channel or all channels. - * - groups monitored: ADC groups regular and-or injected. - * - resolution: resolution is not limited (corresponds to - * ADC resolution configured). - * @rmtoll CR1 AWD1CH LL_ADC_GetAnalogWDMonitChannels\n - * CR1 AWD1SGL LL_ADC_GetAnalogWDMonitChannels\n - * CR1 AWD1EN LL_ADC_GetAnalogWDMonitChannels - * @param ADCx ADC instance - * @retval Returned value can be one of the following values: - * @arg @ref LL_ADC_AWD_DISABLE - * @arg @ref LL_ADC_AWD_ALL_CHANNELS_REG - * @arg @ref LL_ADC_AWD_ALL_CHANNELS_INJ - * @arg @ref LL_ADC_AWD_ALL_CHANNELS_REG_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_0_REG - * @arg @ref LL_ADC_AWD_CHANNEL_0_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_0_REG_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_1_REG - * @arg @ref LL_ADC_AWD_CHANNEL_1_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_1_REG_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_2_REG - * @arg @ref LL_ADC_AWD_CHANNEL_2_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_2_REG_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_3_REG - * @arg @ref LL_ADC_AWD_CHANNEL_3_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_3_REG_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_4_REG - * @arg @ref LL_ADC_AWD_CHANNEL_4_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_4_REG_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_5_REG - * @arg @ref LL_ADC_AWD_CHANNEL_5_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_5_REG_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_6_REG - * @arg @ref LL_ADC_AWD_CHANNEL_6_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_6_REG_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_7_REG - * @arg @ref LL_ADC_AWD_CHANNEL_7_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_7_REG_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_8_REG - * @arg @ref LL_ADC_AWD_CHANNEL_8_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_8_REG_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_9_REG - * @arg @ref LL_ADC_AWD_CHANNEL_9_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_9_REG_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_10_REG - * @arg @ref LL_ADC_AWD_CHANNEL_10_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_10_REG_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_11_REG - * @arg @ref LL_ADC_AWD_CHANNEL_11_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_11_REG_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_12_REG - * @arg @ref LL_ADC_AWD_CHANNEL_12_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_12_REG_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_13_REG - * @arg @ref LL_ADC_AWD_CHANNEL_13_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_13_REG_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_14_REG - * @arg @ref LL_ADC_AWD_CHANNEL_14_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_14_REG_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_15_REG - * @arg @ref LL_ADC_AWD_CHANNEL_15_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_15_REG_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_16_REG - * @arg @ref LL_ADC_AWD_CHANNEL_16_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_16_REG_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_17_REG - * @arg @ref LL_ADC_AWD_CHANNEL_17_INJ - * @arg @ref LL_ADC_AWD_CHANNEL_17_REG_INJ - */ -__STATIC_INLINE uint32_t LL_ADC_GetAnalogWDMonitChannels(ADC_TypeDef *ADCx) -{ - return (uint32_t)(READ_BIT(ADCx->CR1, (ADC_CR1_AWDEN | ADC_CR1_JAWDEN | ADC_CR1_AWDSGL | ADC_CR1_AWDCH))); -} - -/** - * @brief Set ADC analog watchdog threshold value of threshold - * high or low. - * @note On this STM32 serie, there is only 1 kind of analog watchdog - * instance: - * - AWD standard (instance AWD1): - * - channels monitored: can monitor 1 channel or all channels. - * - groups monitored: ADC groups regular and-or injected. - * - resolution: resolution is not limited (corresponds to - * ADC resolution configured). - * @rmtoll HTR HT LL_ADC_SetAnalogWDThresholds\n - * LTR LT LL_ADC_SetAnalogWDThresholds - * @param ADCx ADC instance - * @param AWDThresholdsHighLow This parameter can be one of the following values: - * @arg @ref LL_ADC_AWD_THRESHOLD_HIGH - * @arg @ref LL_ADC_AWD_THRESHOLD_LOW - * @param AWDThresholdValue: Value between Min_Data=0x000 and Max_Data=0xFFF - * @retval None - */ -__STATIC_INLINE void LL_ADC_SetAnalogWDThresholds(ADC_TypeDef *ADCx, uint32_t AWDThresholdsHighLow, uint32_t AWDThresholdValue) -{ - register uint32_t *preg = __ADC_PTR_REG_OFFSET(ADCx->HTR, AWDThresholdsHighLow); - - MODIFY_REG(*preg, - ADC_HTR_HT, - AWDThresholdValue); -} - -/** - * @brief Get ADC analog watchdog threshold value of threshold high or - * threshold low. - * @note In case of ADC resolution different of 12 bits, - * analog watchdog thresholds data require a specific shift. - * Use helper macro @ref __LL_ADC_ANALOGWD_GET_THRESHOLD_RESOLUTION(). - * @rmtoll HTR HT LL_ADC_GetAnalogWDThresholds\n - * LTR LT LL_ADC_GetAnalogWDThresholds - * @param ADCx ADC instance - * @param AWDThresholdsHighLow This parameter can be one of the following values: - * @arg @ref LL_ADC_AWD_THRESHOLD_HIGH - * @arg @ref LL_ADC_AWD_THRESHOLD_LOW - * @retval Value between Min_Data=0x000 and Max_Data=0xFFF -*/ -__STATIC_INLINE uint32_t LL_ADC_GetAnalogWDThresholds(ADC_TypeDef *ADCx, uint32_t AWDThresholdsHighLow) -{ - register uint32_t *preg = __ADC_PTR_REG_OFFSET(ADCx->HTR, AWDThresholdsHighLow); - - return (uint32_t)(READ_BIT(*preg, ADC_HTR_HT)); -} - -/** - * @} - */ - -/** @defgroup ADC_LL_EF_Configuration_ADC_Multimode Configuration of ADC hierarchical scope: multimode - * @{ - */ - -#if defined(ADC_MULTIMODE_SUPPORT) -/** - * @brief Set ADC multimode configuration to operate in independent mode - * or multimode (for devices with several ADC instances). - * @note If multimode configuration: the selected ADC instance is - * either master or slave depending on hardware. - * Refer to reference manual. - * @rmtoll CR1 DUALMOD LL_ADC_SetMultimode - * @param ADCxy_COMMON ADC common instance - * (can be set directly from CMSIS definition or by using helper macro @ref __LL_ADC_COMMON_INSTANCE() ) - * @param Multimode This parameter can be one of the following values: - * @arg @ref LL_ADC_MULTI_INDEPENDENT - * @arg @ref LL_ADC_MULTI_DUAL_REG_SIMULT - * @arg @ref LL_ADC_MULTI_DUAL_REG_INTERL_FAST - * @arg @ref LL_ADC_MULTI_DUAL_REG_INTERL_SLOW - * @arg @ref LL_ADC_MULTI_DUAL_INJ_SIMULT - * @arg @ref LL_ADC_MULTI_DUAL_INJ_ALTERN - * @arg @ref LL_ADC_MULTI_DUAL_REG_SIM_INJ_SIM - * @arg @ref LL_ADC_MULTI_DUAL_REG_SIM_INJ_ALT - * @arg @ref LL_ADC_MULTI_DUAL_REG_INTFAST_INJ_SIM - * @arg @ref LL_ADC_MULTI_DUAL_REG_INTSLOW_INJ_SIM - * @retval None - */ -__STATIC_INLINE void LL_ADC_SetMultimode(ADC_Common_TypeDef *ADCxy_COMMON, uint32_t Multimode) -{ - MODIFY_REG(ADCxy_COMMON->CR1, ADC_CR1_DUALMOD, Multimode); -} - -/** - * @brief Get ADC multimode configuration to operate in independent mode - * or multimode (for devices with several ADC instances). - * @note If multimode configuration: the selected ADC instance is - * either master or slave depending on hardware. - * Refer to reference manual. - * @rmtoll CR1 DUALMOD LL_ADC_GetMultimode - * @param ADCxy_COMMON ADC common instance - * (can be set directly from CMSIS definition or by using helper macro @ref __LL_ADC_COMMON_INSTANCE() ) - * @retval Returned value can be one of the following values: - * @arg @ref LL_ADC_MULTI_INDEPENDENT - * @arg @ref LL_ADC_MULTI_DUAL_REG_SIMULT - * @arg @ref LL_ADC_MULTI_DUAL_REG_INTERL_FAST - * @arg @ref LL_ADC_MULTI_DUAL_REG_INTERL_SLOW - * @arg @ref LL_ADC_MULTI_DUAL_INJ_SIMULT - * @arg @ref LL_ADC_MULTI_DUAL_INJ_ALTERN - * @arg @ref LL_ADC_MULTI_DUAL_REG_SIM_INJ_SIM - * @arg @ref LL_ADC_MULTI_DUAL_REG_SIM_INJ_ALT - * @arg @ref LL_ADC_MULTI_DUAL_REG_INTFAST_INJ_SIM - * @arg @ref LL_ADC_MULTI_DUAL_REG_INTSLOW_INJ_SIM - */ -__STATIC_INLINE uint32_t LL_ADC_GetMultimode(ADC_Common_TypeDef *ADCxy_COMMON) -{ - return (uint32_t)(READ_BIT(ADCxy_COMMON->CR1, ADC_CR1_DUALMOD)); -} - -#endif /* ADC_MULTIMODE_SUPPORT */ - -/** - * @} - */ -/** @defgroup ADC_LL_EF_Operation_ADC_Instance Operation on ADC hierarchical scope: ADC instance - * @{ - */ - -/** - * @brief Enable the selected ADC instance. - * @note On this STM32 serie, after ADC enable, a delay for - * ADC internal analog stabilization is required before performing a - * ADC conversion start. - * Refer to device datasheet, parameter tSTAB. - * @rmtoll CR2 ADON LL_ADC_Enable - * @param ADCx ADC instance - * @retval None - */ -__STATIC_INLINE void LL_ADC_Enable(ADC_TypeDef *ADCx) -{ - SET_BIT(ADCx->CR2, ADC_CR2_ADON); -} - -/** - * @brief Disable the selected ADC instance. - * @rmtoll CR2 ADON LL_ADC_Disable - * @param ADCx ADC instance - * @retval None - */ -__STATIC_INLINE void LL_ADC_Disable(ADC_TypeDef *ADCx) -{ - CLEAR_BIT(ADCx->CR2, ADC_CR2_ADON); -} - -/** - * @brief Get the selected ADC instance enable state. - * @rmtoll CR2 ADON LL_ADC_IsEnabled - * @param ADCx ADC instance - * @retval 0: ADC is disabled, 1: ADC is enabled. - */ -__STATIC_INLINE uint32_t LL_ADC_IsEnabled(ADC_TypeDef *ADCx) -{ - return (READ_BIT(ADCx->CR2, ADC_CR2_ADON) == (ADC_CR2_ADON)); -} - -/** - * @brief Start ADC calibration in the mode single-ended - * or differential (for devices with differential mode available). - * @note On this STM32 serie, before starting a calibration, - * ADC must be disabled. - * A minimum number of ADC clock cycles are required - * between ADC disable state and calibration start. - * Refer to literal @ref LL_ADC_DELAY_DISABLE_CALIB_ADC_CYCLES. - * @note On this STM32 serie, hardware prerequisite before starting a calibration: - the ADC must have been in power-on state for at least - two ADC clock cycles. - * @rmtoll CR2 CAL LL_ADC_StartCalibration - * @param ADCx ADC instance - * @retval None - */ -__STATIC_INLINE void LL_ADC_StartCalibration(ADC_TypeDef *ADCx) -{ - SET_BIT(ADCx->CR2, ADC_CR2_CAL); -} - -/** - * @brief Get ADC calibration state. - * @rmtoll CR2 CAL LL_ADC_IsCalibrationOnGoing - * @param ADCx ADC instance - * @retval 0: calibration complete, 1: calibration in progress. - */ -__STATIC_INLINE uint32_t LL_ADC_IsCalibrationOnGoing(ADC_TypeDef *ADCx) -{ - return (READ_BIT(ADCx->CR2, ADC_CR2_CAL) == (ADC_CR2_CAL)); -} - -/** - * @} - */ - -/** @defgroup ADC_LL_EF_Operation_ADC_Group_Regular Operation on ADC hierarchical scope: group regular - * @{ - */ - -/** - * @brief Start ADC group regular conversion. - * @note On this STM32 serie, this function is relevant only for - * internal trigger (SW start), not for external trigger: - * - If ADC trigger has been set to software start, ADC conversion - * starts immediately. - * - If ADC trigger has been set to external trigger, ADC conversion - * start must be performed using function - * @ref LL_ADC_REG_StartConversionExtTrig(). - * (if external trigger edge would have been set during ADC other - * settings, ADC conversion would start at trigger event - * as soon as ADC is enabled). - * @rmtoll CR2 SWSTART LL_ADC_REG_StartConversionSWStart - * @param ADCx ADC instance - * @retval None - */ -__STATIC_INLINE void LL_ADC_REG_StartConversionSWStart(ADC_TypeDef *ADCx) -{ - SET_BIT(ADCx->CR2, (ADC_CR2_SWSTART | ADC_CR2_EXTTRIG)); -} - -/** - * @brief Start ADC group regular conversion from external trigger. - * @note ADC conversion will start at next trigger event (on the selected - * trigger edge) following the ADC start conversion command. - * @note On this STM32 serie, this function is relevant for - * ADC conversion start from external trigger. - * If internal trigger (SW start) is needed, perform ADC conversion - * start using function @ref LL_ADC_REG_StartConversionSWStart(). - * @rmtoll CR2 EXTEN LL_ADC_REG_StartConversionExtTrig - * @param ExternalTriggerEdge This parameter can be one of the following values: - * @arg @ref LL_ADC_REG_TRIG_EXT_RISING - * @param ADCx ADC instance - * @retval None - */ -__STATIC_INLINE void LL_ADC_REG_StartConversionExtTrig(ADC_TypeDef *ADCx, uint32_t ExternalTriggerEdge) -{ - SET_BIT(ADCx->CR2, ExternalTriggerEdge); -} - -/** - * @brief Stop ADC group regular conversion from external trigger. - * @note No more ADC conversion will start at next trigger event - * following the ADC stop conversion command. - * If a conversion is on-going, it will be completed. - * @note On this STM32 serie, there is no specific command - * to stop a conversion on-going or to stop ADC converting - * in continuous mode. These actions can be performed - * using function @ref LL_ADC_Disable(). - * @rmtoll CR2 EXTSEL LL_ADC_REG_StopConversionExtTrig - * @param ADCx ADC instance - * @retval None - */ -__STATIC_INLINE void LL_ADC_REG_StopConversionExtTrig(ADC_TypeDef *ADCx) -{ - CLEAR_BIT(ADCx->CR2, ADC_CR2_EXTSEL); -} - -/** - * @brief Get ADC group regular conversion data, range fit for - * all ADC configurations: all ADC resolutions and - * all oversampling increased data width (for devices - * with feature oversampling). - * @rmtoll DR RDATA LL_ADC_REG_ReadConversionData32 - * @param ADCx ADC instance - * @retval Value between Min_Data=0x00000000 and Max_Data=0xFFFFFFFF - */ -__STATIC_INLINE uint32_t LL_ADC_REG_ReadConversionData32(ADC_TypeDef *ADCx) -{ - return (uint16_t)(READ_BIT(ADCx->DR, ADC_DR_DATA)); -} - -/** - * @brief Get ADC group regular conversion data, range fit for - * ADC resolution 12 bits. - * @note For devices with feature oversampling: Oversampling - * can increase data width, function for extended range - * may be needed: @ref LL_ADC_REG_ReadConversionData32. - * @rmtoll DR RDATA LL_ADC_REG_ReadConversionData12 - * @param ADCx ADC instance - * @retval Value between Min_Data=0x000 and Max_Data=0xFFF - */ -__STATIC_INLINE uint16_t LL_ADC_REG_ReadConversionData12(ADC_TypeDef *ADCx) -{ - return (uint16_t)(READ_BIT(ADCx->DR, ADC_DR_DATA)); -} - -#if defined(ADC_MULTIMODE_SUPPORT) -/** - * @brief Get ADC multimode conversion data of ADC master, ADC slave - * or raw data with ADC master and slave concatenated. - * @note If raw data with ADC master and slave concatenated is retrieved, - * a macro is available to get the conversion data of - * ADC master or ADC slave: see helper macro - * @ref __LL_ADC_MULTI_CONV_DATA_MASTER_SLAVE(). - * (however this macro is mainly intended for multimode - * transfer by DMA, because this function can do the same - * by getting multimode conversion data of ADC master or ADC slave - * separately). - * @rmtoll DR DATA LL_ADC_REG_ReadMultiConversionData32\n - * DR ADC2DATA LL_ADC_REG_ReadMultiConversionData32 - * @param ADCx ADC instance - * (can be set directly from CMSIS definition or by using helper macro @ref __LL_ADC_COMMON_INSTANCE() ) - * @param ConversionData This parameter can be one of the following values: - * @arg @ref LL_ADC_MULTI_MASTER - * @arg @ref LL_ADC_MULTI_SLAVE - * @arg @ref LL_ADC_MULTI_MASTER_SLAVE - * @retval Value between Min_Data=0x00000000 and Max_Data=0xFFFFFFFF - */ -__STATIC_INLINE uint32_t LL_ADC_REG_ReadMultiConversionData32(ADC_TypeDef *ADCx, uint32_t ConversionData) -{ - return (uint32_t)(READ_BIT(ADCx->DR, - ADC_DR_ADC2DATA) - >> POSITION_VAL(ConversionData) - ); -} -#endif /* ADC_MULTIMODE_SUPPORT */ - -/** - * @} - */ - -/** @defgroup ADC_LL_EF_Operation_ADC_Group_Injected Operation on ADC hierarchical scope: group injected - * @{ - */ - -/** - * @brief Start ADC group injected conversion. - * @note On this STM32 serie, this function is relevant only for - * internal trigger (SW start), not for external trigger: - * - If ADC trigger has been set to software start, ADC conversion - * starts immediately. - * - If ADC trigger has been set to external trigger, ADC conversion - * start must be performed using function - * @ref LL_ADC_INJ_StartConversionExtTrig(). - * (if external trigger edge would have been set during ADC other - * settings, ADC conversion would start at trigger event - * as soon as ADC is enabled). - * @rmtoll CR2 JSWSTART LL_ADC_INJ_StartConversionSWStart - * @param ADCx ADC instance - * @retval None - */ -__STATIC_INLINE void LL_ADC_INJ_StartConversionSWStart(ADC_TypeDef *ADCx) -{ - SET_BIT(ADCx->CR2, (ADC_CR2_JSWSTART | ADC_CR2_JEXTTRIG)); -} - -/** - * @brief Start ADC group injected conversion from external trigger. - * @note ADC conversion will start at next trigger event (on the selected - * trigger edge) following the ADC start conversion command. - * @note On this STM32 serie, this function is relevant for - * ADC conversion start from external trigger. - * If internal trigger (SW start) is needed, perform ADC conversion - * start using function @ref LL_ADC_INJ_StartConversionSWStart(). - * @rmtoll CR2 JEXTEN LL_ADC_INJ_StartConversionExtTrig - * @param ExternalTriggerEdge This parameter can be one of the following values: - * @arg @ref LL_ADC_INJ_TRIG_EXT_RISING - * @param ADCx ADC instance - * @retval None - */ -__STATIC_INLINE void LL_ADC_INJ_StartConversionExtTrig(ADC_TypeDef *ADCx, uint32_t ExternalTriggerEdge) -{ - SET_BIT(ADCx->CR2, ExternalTriggerEdge); -} - -/** - * @brief Stop ADC group injected conversion from external trigger. - * @note No more ADC conversion will start at next trigger event - * following the ADC stop conversion command. - * If a conversion is on-going, it will be completed. - * @note On this STM32 serie, there is no specific command - * to stop a conversion on-going or to stop ADC converting - * in continuous mode. These actions can be performed - * using function @ref LL_ADC_Disable(). - * @rmtoll CR2 JEXTSEL LL_ADC_INJ_StopConversionExtTrig - * @param ADCx ADC instance - * @retval None - */ -__STATIC_INLINE void LL_ADC_INJ_StopConversionExtTrig(ADC_TypeDef *ADCx) -{ - CLEAR_BIT(ADCx->CR2, ADC_CR2_JEXTSEL); -} - -/** - * @brief Get ADC group regular conversion data, range fit for - * all ADC configurations: all ADC resolutions and - * all oversampling increased data width (for devices - * with feature oversampling). - * @rmtoll JDR1 JDATA LL_ADC_INJ_ReadConversionData32\n - * JDR2 JDATA LL_ADC_INJ_ReadConversionData32\n - * JDR3 JDATA LL_ADC_INJ_ReadConversionData32\n - * JDR4 JDATA LL_ADC_INJ_ReadConversionData32 - * @param ADCx ADC instance - * @param Rank This parameter can be one of the following values: - * @arg @ref LL_ADC_INJ_RANK_1 - * @arg @ref LL_ADC_INJ_RANK_2 - * @arg @ref LL_ADC_INJ_RANK_3 - * @arg @ref LL_ADC_INJ_RANK_4 - * @retval Value between Min_Data=0x00000000 and Max_Data=0xFFFFFFFF - */ -__STATIC_INLINE uint32_t LL_ADC_INJ_ReadConversionData32(ADC_TypeDef *ADCx, uint32_t Rank) -{ - register uint32_t *preg = __ADC_PTR_REG_OFFSET(ADCx->JDR1, __ADC_MASK_SHIFT(Rank, ADC_INJ_JDRX_REGOFFSET_MASK)); - - return (uint32_t)(READ_BIT(*preg, - ADC_JDR1_JDATA) - ); -} - -/** - * @brief Get ADC group injected conversion data, range fit for - * ADC resolution 12 bits. - * @note For devices with feature oversampling: Oversampling - * can increase data width, function for extended range - * may be needed: @ref LL_ADC_INJ_ReadConversionData32. - * @rmtoll JDR1 JDATA LL_ADC_INJ_ReadConversionData12\n - * JDR2 JDATA LL_ADC_INJ_ReadConversionData12\n - * JDR3 JDATA LL_ADC_INJ_ReadConversionData12\n - * JDR4 JDATA LL_ADC_INJ_ReadConversionData12 - * @param ADCx ADC instance - * @param Rank This parameter can be one of the following values: - * @arg @ref LL_ADC_INJ_RANK_1 - * @arg @ref LL_ADC_INJ_RANK_2 - * @arg @ref LL_ADC_INJ_RANK_3 - * @arg @ref LL_ADC_INJ_RANK_4 - * @retval Value between Min_Data=0x000 and Max_Data=0xFFF - */ -__STATIC_INLINE uint16_t LL_ADC_INJ_ReadConversionData12(ADC_TypeDef *ADCx, uint32_t Rank) -{ - register uint32_t *preg = __ADC_PTR_REG_OFFSET(ADCx->JDR1, __ADC_MASK_SHIFT(Rank, ADC_INJ_JDRX_REGOFFSET_MASK)); - - return (uint16_t)(READ_BIT(*preg, - ADC_JDR1_JDATA) - ); -} - -/** - * @} - */ - -/** @defgroup ADC_LL_EF_FLAG_Management ADC flag management - * @{ - */ - -/** - * @brief Get flag ADC group regular end of sequence conversions. - * @rmtoll SR EOC LL_ADC_IsActiveFlag_EOS - * @param ADCx ADC instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_ADC_IsActiveFlag_EOS(ADC_TypeDef *ADCx) -{ - /* Note: on this STM32 serie, there is no flag ADC group regular */ - /* end of unitary conversion. */ - /* Flag noted as "EOC" is corresponding to flag "EOS" */ - /* in other STM32 families). */ - return (READ_BIT(ADCx->SR, LL_ADC_FLAG_EOS) == (LL_ADC_FLAG_EOS)); -} - - -/** - * @brief Get flag ADC group injected end of sequence conversions. - * @rmtoll SR JEOC LL_ADC_IsActiveFlag_JEOS - * @param ADCx ADC instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_ADC_IsActiveFlag_JEOS(ADC_TypeDef *ADCx) -{ - /* Note: on this STM32 serie, there is no flag ADC group injected */ - /* end of unitary conversion. */ - /* Flag noted as "JEOC" is corresponding to flag "JEOS" */ - /* in other STM32 families). */ - return (READ_BIT(ADCx->SR, LL_ADC_FLAG_JEOS) == (LL_ADC_FLAG_JEOS)); -} - -/** - * @brief Get flag ADC analog watchdog 1 flag - * @rmtoll SR AWD LL_ADC_IsActiveFlag_AWD1 - * @param ADCx ADC instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_ADC_IsActiveFlag_AWD1(ADC_TypeDef *ADCx) -{ - return (READ_BIT(ADCx->SR, LL_ADC_FLAG_AWD1) == (LL_ADC_FLAG_AWD1)); -} - -/** - * @brief Clear flag ADC group regular end of sequence conversions. - * @rmtoll SR EOC LL_ADC_ClearFlag_EOS - * @param ADCx ADC instance - * @retval None - */ -__STATIC_INLINE void LL_ADC_ClearFlag_EOS(ADC_TypeDef *ADCx) -{ - /* Note: on this STM32 serie, there is no flag ADC group regular */ - /* end of unitary conversion. */ - /* Flag noted as "EOC" is corresponding to flag "EOS" */ - /* in other STM32 families). */ - WRITE_REG(ADCx->SR, ~LL_ADC_FLAG_EOS); -} - - -/** - * @brief Clear flag ADC group injected end of sequence conversions. - * @rmtoll SR JEOC LL_ADC_ClearFlag_JEOS - * @param ADCx ADC instance - * @retval None - */ -__STATIC_INLINE void LL_ADC_ClearFlag_JEOS(ADC_TypeDef *ADCx) -{ - /* Note: on this STM32 serie, there is no flag ADC group injected */ - /* end of unitary conversion. */ - /* Flag noted as "JEOC" is corresponding to flag "JEOS" */ - /* in other STM32 families). */ - WRITE_REG(ADCx->SR, ~LL_ADC_FLAG_JEOS); -} - -/** - * @brief Clear flag ADC analog watchdog 1. - * @rmtoll SR AWD LL_ADC_ClearFlag_AWD1 - * @param ADCx ADC instance - * @retval None - */ -__STATIC_INLINE void LL_ADC_ClearFlag_AWD1(ADC_TypeDef *ADCx) -{ - WRITE_REG(ADCx->SR, ~LL_ADC_FLAG_AWD1); -} - -#if defined(ADC_MULTIMODE_SUPPORT) -/** - * @brief Get flag multimode ADC group regular end of sequence conversions of the ADC master. - * @rmtoll SR EOC LL_ADC_IsActiveFlag_MST_EOS - * @param ADCxy_COMMON ADC common instance - * (can be set directly from CMSIS definition or by using helper macro @ref __LL_ADC_COMMON_INSTANCE() ) - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_ADC_IsActiveFlag_MST_EOS(ADC_Common_TypeDef *ADCxy_COMMON) -{ - /* Note: on this STM32 serie, there is no flag ADC group regular */ - /* end of unitary conversion. */ - /* Flag noted as "EOC" is corresponding to flag "EOS" */ - /* in other STM32 families). */ - return (READ_BIT(ADCxy_COMMON->SR, ADC_SR_EOC) == (ADC_SR_EOC)); -} - -/** - * @brief Get flag multimode ADC group regular end of sequence conversions of the ADC slave. - * @rmtoll SR EOC LL_ADC_IsActiveFlag_SLV_EOS - * @param ADCxy_COMMON ADC common instance - * (can be set directly from CMSIS definition or by using helper macro @ref __LL_ADC_COMMON_INSTANCE() ) - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_ADC_IsActiveFlag_SLV_EOS(ADC_Common_TypeDef *ADCxy_COMMON) -{ - /* Note: on this STM32 serie, there is no flag ADC group regular */ - /* end of unitary conversion. */ - /* Flag noted as "EOC" is corresponding to flag "EOS" */ - /* in other STM32 families). */ - - register uint32_t *preg = __ADC_PTR_REG_OFFSET(ADCxy_COMMON->SR, 1U); - - return (READ_BIT(*preg, LL_ADC_FLAG_EOS_SLV) == (LL_ADC_FLAG_EOS_SLV)); -} - - -/** - * @brief Get flag multimode ADC group injected end of sequence conversions of the ADC master. - * @rmtoll SR JEOC LL_ADC_IsActiveFlag_MST_JEOS - * @param ADCxy_COMMON ADC common instance - * (can be set directly from CMSIS definition or by using helper macro @ref __LL_ADC_COMMON_INSTANCE() ) - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_ADC_IsActiveFlag_MST_JEOS(ADC_Common_TypeDef *ADCxy_COMMON) -{ - /* Note: on this STM32 serie, there is no flag ADC group injected */ - /* end of unitary conversion. */ - /* Flag noted as "JEOC" is corresponding to flag "JEOS" */ - /* in other STM32 families). */ - return (READ_BIT(ADC1->SR, ADC_SR_JEOC) == (ADC_SR_JEOC)); -} - -/** - * @brief Get flag multimode ADC group injected end of sequence conversions of the ADC slave. - * @rmtoll SR JEOC LL_ADC_IsActiveFlag_SLV_JEOS - * @param ADCxy_COMMON ADC common instance - * (can be set directly from CMSIS definition or by using helper macro @ref __LL_ADC_COMMON_INSTANCE() ) - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_ADC_IsActiveFlag_SLV_JEOS(ADC_Common_TypeDef *ADCxy_COMMON) -{ - /* Note: on this STM32 serie, there is no flag ADC group injected */ - /* end of unitary conversion. */ - /* Flag noted as "JEOC" is corresponding to flag "JEOS" */ - /* in other STM32 families). */ - - register uint32_t *preg = __ADC_PTR_REG_OFFSET(ADCxy_COMMON->SR, 1U); - - return (READ_BIT(*preg, LL_ADC_FLAG_JEOS_SLV) == (LL_ADC_FLAG_JEOS_SLV)); -} - -/** - * @brief Get flag multimode ADC analog watchdog 1 of the ADC master. - * @rmtoll SR AWD LL_ADC_IsActiveFlag_MST_AWD1 - * @param ADCxy_COMMON ADC common instance - * (can be set directly from CMSIS definition or by using helper macro @ref __LL_ADC_COMMON_INSTANCE() ) - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_ADC_IsActiveFlag_MST_AWD1(ADC_Common_TypeDef *ADCxy_COMMON) -{ - return (READ_BIT(ADC1->SR, LL_ADC_FLAG_AWD1) == (LL_ADC_FLAG_AWD1)); -} - -/** - * @brief Get flag multimode analog watchdog 1 of the ADC slave. - * @rmtoll SR AWD LL_ADC_IsActiveFlag_SLV_AWD1 - * @param ADCxy_COMMON ADC common instance - * (can be set directly from CMSIS definition or by using helper macro @ref __LL_ADC_COMMON_INSTANCE() ) - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_ADC_IsActiveFlag_SLV_AWD1(ADC_Common_TypeDef *ADCxy_COMMON) -{ - register uint32_t *preg = __ADC_PTR_REG_OFFSET(ADCxy_COMMON->SR, 1U); - - return (READ_BIT(*preg, LL_ADC_FLAG_AWD1) == (LL_ADC_FLAG_AWD1)); -} - -#endif /* ADC_MULTIMODE_SUPPORT */ - -/** - * @} - */ - -/** @defgroup ADC_LL_EF_IT_Management ADC IT management - * @{ - */ - -/** - * @brief Enable interruption ADC group regular end of sequence conversions. - * @rmtoll CR1 EOCIE LL_ADC_EnableIT_EOS - * @param ADCx ADC instance - * @retval None - */ -__STATIC_INLINE void LL_ADC_EnableIT_EOS(ADC_TypeDef *ADCx) -{ - /* Note: on this STM32 serie, there is no flag ADC group regular */ - /* end of unitary conversion. */ - /* Flag noted as "EOC" is corresponding to flag "EOS" */ - /* in other STM32 families). */ - SET_BIT(ADCx->CR1, ADC_CR1_EOCIE); -} - - -/** - * @brief Enable interruption ADC group injected end of sequence conversions. - * @rmtoll CR1 JEOCIE LL_ADC_EnableIT_JEOS - * @param ADCx ADC instance - * @retval None - */ -__STATIC_INLINE void LL_ADC_EnableIT_JEOS(ADC_TypeDef *ADCx) -{ - /* Note: on this STM32 serie, there is no flag ADC group injected */ - /* end of unitary conversion. */ - /* Flag noted as "JEOC" is corresponding to flag "JEOS" */ - /* in other STM32 families). */ - SET_BIT(ADCx->CR1, LL_ADC_IT_JEOS); -} - -/** - * @brief Enable interruption ADC analog watchdog 1. - * @rmtoll CR1 AWDIE LL_ADC_EnableIT_AWD1 - * @param ADCx ADC instance - * @retval None - */ -__STATIC_INLINE void LL_ADC_EnableIT_AWD1(ADC_TypeDef *ADCx) -{ - SET_BIT(ADCx->CR1, LL_ADC_IT_AWD1); -} - -/** - * @brief Disable interruption ADC group regular end of sequence conversions. - * @rmtoll CR1 EOCIE LL_ADC_DisableIT_EOS - * @param ADCx ADC instance - * @retval None - */ -__STATIC_INLINE void LL_ADC_DisableIT_EOS(ADC_TypeDef *ADCx) -{ - /* Note: on this STM32 serie, there is no flag ADC group regular */ - /* end of unitary conversion. */ - /* Flag noted as "EOC" is corresponding to flag "EOS" */ - /* in other STM32 families). */ - CLEAR_BIT(ADCx->CR1, ADC_CR1_EOCIE); -} - - -/** - * @brief Disable interruption ADC group injected end of sequence conversions. - * @rmtoll CR1 JEOCIE LL_ADC_EnableIT_JEOS - * @param ADCx ADC instance - * @retval None - */ -__STATIC_INLINE void LL_ADC_DisableIT_JEOS(ADC_TypeDef *ADCx) -{ - /* Note: on this STM32 serie, there is no flag ADC group injected */ - /* end of unitary conversion. */ - /* Flag noted as "JEOC" is corresponding to flag "JEOS" */ - /* in other STM32 families). */ - CLEAR_BIT(ADCx->CR1, LL_ADC_IT_JEOS); -} - -/** - * @brief Disable interruption ADC analog watchdog 1. - * @rmtoll CR1 AWDIE LL_ADC_EnableIT_AWD1 - * @param ADCx ADC instance - * @retval None - */ -__STATIC_INLINE void LL_ADC_DisableIT_AWD1(ADC_TypeDef *ADCx) -{ - CLEAR_BIT(ADCx->CR1, LL_ADC_IT_AWD1); -} - -/** - * @brief Get state of interruption ADC group regular end of sequence conversions - * (0: interrupt disabled, 1: interrupt enabled). - * @rmtoll CR1 EOCIE LL_ADC_IsEnabledIT_EOS - * @param ADCx ADC instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_ADC_IsEnabledIT_EOS(ADC_TypeDef *ADCx) -{ - /* Note: on this STM32 serie, there is no flag ADC group regular */ - /* end of unitary conversion. */ - /* Flag noted as "EOC" is corresponding to flag "EOS" */ - /* in other STM32 families). */ - return (READ_BIT(ADCx->CR1, LL_ADC_IT_EOS) == (LL_ADC_IT_EOS)); -} - - -/** - * @brief Get state of interruption ADC group injected end of sequence conversions - * (0: interrupt disabled, 1: interrupt enabled). - * @rmtoll CR1 JEOCIE LL_ADC_EnableIT_JEOS - * @param ADCx ADC instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_ADC_IsEnabledIT_JEOS(ADC_TypeDef *ADCx) -{ - /* Note: on this STM32 serie, there is no flag ADC group injected */ - /* end of unitary conversion. */ - /* Flag noted as "JEOC" is corresponding to flag "JEOS" */ - /* in other STM32 families). */ - return (READ_BIT(ADCx->CR1, LL_ADC_IT_JEOS) == (LL_ADC_IT_JEOS)); -} - -/** - * @brief Get state of interruption ADC analog watchdog 1 - * (0: interrupt disabled, 1: interrupt enabled). - * @rmtoll CR1 AWDIE LL_ADC_EnableIT_AWD1 - * @param ADCx ADC instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_ADC_IsEnabledIT_AWD1(ADC_TypeDef *ADCx) -{ - return (READ_BIT(ADCx->CR1, LL_ADC_IT_AWD1) == (LL_ADC_IT_AWD1)); -} - -/** - * @} - */ - -#if defined(USE_FULL_LL_DRIVER) -/** @defgroup ADC_LL_EF_Init Initialization and de-initialization functions - * @{ - */ - -/* Initialization of some features of ADC common parameters and multimode */ -ErrorStatus LL_ADC_CommonDeInit(ADC_Common_TypeDef *ADCxy_COMMON); -ErrorStatus LL_ADC_CommonInit(ADC_Common_TypeDef *ADCxy_COMMON, LL_ADC_CommonInitTypeDef *ADC_CommonInitStruct); -void LL_ADC_CommonStructInit(LL_ADC_CommonInitTypeDef *ADC_CommonInitStruct); - -/* De-initialization of ADC instance, ADC group regular and ADC group injected */ -/* (availability of ADC group injected depends on STM32 families) */ -ErrorStatus LL_ADC_DeInit(ADC_TypeDef *ADCx); - -/* Initialization of some features of ADC instance */ -ErrorStatus LL_ADC_Init(ADC_TypeDef *ADCx, LL_ADC_InitTypeDef *ADC_InitStruct); -void LL_ADC_StructInit(LL_ADC_InitTypeDef *ADC_InitStruct); - -/* Initialization of some features of ADC instance and ADC group regular */ -ErrorStatus LL_ADC_REG_Init(ADC_TypeDef *ADCx, LL_ADC_REG_InitTypeDef *ADC_REG_InitStruct); -void LL_ADC_REG_StructInit(LL_ADC_REG_InitTypeDef *ADC_REG_InitStruct); - -/* Initialization of some features of ADC instance and ADC group injected */ -ErrorStatus LL_ADC_INJ_Init(ADC_TypeDef *ADCx, LL_ADC_INJ_InitTypeDef *ADC_INJ_InitStruct); -void LL_ADC_INJ_StructInit(LL_ADC_INJ_InitTypeDef *ADC_INJ_InitStruct); - -/** - * @} - */ -#endif /* USE_FULL_LL_DRIVER */ - -/** - * @} - */ - -/** - * @} - */ - -#endif /* ADC1 || ADC2 || ADC3 */ - -/** - * @} - */ - -#ifdef __cplusplus -} -#endif - -#endif /* __STM32F1xx_LL_ADC_H */ - -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_bus.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_bus.h index c28b643b287..d715aa491af 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_bus.h +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_bus.h @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_ll_bus.h * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version $VERSION$ + * @date $DATE$ * @brief Header file of BUS LL module. @verbatim diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_cortex.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_cortex.h index 74a32036730..c682cb74894 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_cortex.h +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_cortex.h @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_ll_cortex.h * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version $VERSION$ + * @date $DATE$ * @brief Header file of CORTEX LL module. @verbatim ============================================================================== @@ -86,8 +86,8 @@ extern "C" { /** @defgroup CORTEX_LL_EC_CLKSOURCE_HCLK SYSTICK Clock Source * @{ */ -#define LL_SYSTICK_CLKSOURCE_HCLK_DIV8 0x00000000U /*!< AHB clock divided by 8 selected as SysTick clock source.*/ -#define LL_SYSTICK_CLKSOURCE_HCLK SysTick_CTRL_CLKSOURCE_Msk /*!< AHB clock selected as SysTick clock source. */ +#define LL_SYSTICK_CLKSOURCE_HCLK_DIV8 ((uint32_t)0x00000000U) /*!< AHB clock divided by 8 selected as SysTick clock source.*/ +#define LL_SYSTICK_CLKSOURCE_HCLK ((uint32_t)SysTick_CTRL_CLKSOURCE_Msk) /*!< AHB clock selected as SysTick clock source. */ /** * @} */ @@ -107,7 +107,7 @@ extern "C" { /** @defgroup CORTEX_LL_EC_CTRL_HFNMI_PRIVDEF MPU Control * @{ */ -#define LL_MPU_CTRL_HFNMI_PRIVDEF_NONE 0x00000000U /*!< Disable NMI and privileged SW access */ +#define LL_MPU_CTRL_HFNMI_PRIVDEF_NONE ((uint32_t)0x00000000U) /*!< Disable NMI and privileged SW access */ #define LL_MPU_CTRL_HARDFAULT_NMI MPU_CTRL_HFNMIENA_Msk /*!< Enables the operation of MPU during hard fault, NMI, and FAULTMASK handlers */ #define LL_MPU_CTRL_PRIVILEGED_DEFAULT MPU_CTRL_PRIVDEFENA_Msk /*!< Enable privileged software access to default memory map */ #define LL_MPU_CTRL_HFNMI_PRIVDEF (MPU_CTRL_HFNMIENA_Msk | MPU_CTRL_PRIVDEFENA_Msk) /*!< Enable NMI and privileged SW access */ @@ -118,14 +118,14 @@ extern "C" { /** @defgroup CORTEX_LL_EC_REGION MPU Region Number * @{ */ -#define LL_MPU_REGION_NUMBER0 0x00U /*!< REGION Number 0 */ -#define LL_MPU_REGION_NUMBER1 0x01U /*!< REGION Number 1 */ -#define LL_MPU_REGION_NUMBER2 0x02U /*!< REGION Number 2 */ -#define LL_MPU_REGION_NUMBER3 0x03U /*!< REGION Number 3 */ -#define LL_MPU_REGION_NUMBER4 0x04U /*!< REGION Number 4 */ -#define LL_MPU_REGION_NUMBER5 0x05U /*!< REGION Number 5 */ -#define LL_MPU_REGION_NUMBER6 0x06U /*!< REGION Number 6 */ -#define LL_MPU_REGION_NUMBER7 0x07U /*!< REGION Number 7 */ +#define LL_MPU_REGION_NUMBER0 ((uint32_t)0x00U) /*!< REGION Number 0 */ +#define LL_MPU_REGION_NUMBER1 ((uint32_t)0x01U) /*!< REGION Number 1 */ +#define LL_MPU_REGION_NUMBER2 ((uint32_t)0x02U) /*!< REGION Number 2 */ +#define LL_MPU_REGION_NUMBER3 ((uint32_t)0x03U) /*!< REGION Number 3 */ +#define LL_MPU_REGION_NUMBER4 ((uint32_t)0x04U) /*!< REGION Number 4 */ +#define LL_MPU_REGION_NUMBER5 ((uint32_t)0x05U) /*!< REGION Number 5 */ +#define LL_MPU_REGION_NUMBER6 ((uint32_t)0x06U) /*!< REGION Number 6 */ +#define LL_MPU_REGION_NUMBER7 ((uint32_t)0x07U) /*!< REGION Number 7 */ /** * @} */ @@ -133,34 +133,34 @@ extern "C" { /** @defgroup CORTEX_LL_EC_REGION_SIZE MPU Region Size * @{ */ -#define LL_MPU_REGION_SIZE_32B (0x04U << MPU_RASR_SIZE_Pos) /*!< 32B Size of the MPU protection region */ -#define LL_MPU_REGION_SIZE_64B (0x05U << MPU_RASR_SIZE_Pos) /*!< 64B Size of the MPU protection region */ -#define LL_MPU_REGION_SIZE_128B (0x06U << MPU_RASR_SIZE_Pos) /*!< 128B Size of the MPU protection region */ -#define LL_MPU_REGION_SIZE_256B (0x07U << MPU_RASR_SIZE_Pos) /*!< 256B Size of the MPU protection region */ -#define LL_MPU_REGION_SIZE_512B (0x08U << MPU_RASR_SIZE_Pos) /*!< 512B Size of the MPU protection region */ -#define LL_MPU_REGION_SIZE_1KB (0x09U << MPU_RASR_SIZE_Pos) /*!< 1KB Size of the MPU protection region */ -#define LL_MPU_REGION_SIZE_2KB (0x0AU << MPU_RASR_SIZE_Pos) /*!< 2KB Size of the MPU protection region */ -#define LL_MPU_REGION_SIZE_4KB (0x0BU << MPU_RASR_SIZE_Pos) /*!< 4KB Size of the MPU protection region */ -#define LL_MPU_REGION_SIZE_8KB (0x0CU << MPU_RASR_SIZE_Pos) /*!< 8KB Size of the MPU protection region */ -#define LL_MPU_REGION_SIZE_16KB (0x0DU << MPU_RASR_SIZE_Pos) /*!< 16KB Size of the MPU protection region */ -#define LL_MPU_REGION_SIZE_32KB (0x0EU << MPU_RASR_SIZE_Pos) /*!< 32KB Size of the MPU protection region */ -#define LL_MPU_REGION_SIZE_64KB (0x0FU << MPU_RASR_SIZE_Pos) /*!< 64KB Size of the MPU protection region */ -#define LL_MPU_REGION_SIZE_128KB (0x10U << MPU_RASR_SIZE_Pos) /*!< 128KB Size of the MPU protection region */ -#define LL_MPU_REGION_SIZE_256KB (0x11U << MPU_RASR_SIZE_Pos) /*!< 256KB Size of the MPU protection region */ -#define LL_MPU_REGION_SIZE_512KB (0x12U << MPU_RASR_SIZE_Pos) /*!< 512KB Size of the MPU protection region */ -#define LL_MPU_REGION_SIZE_1MB (0x13U << MPU_RASR_SIZE_Pos) /*!< 1MB Size of the MPU protection region */ -#define LL_MPU_REGION_SIZE_2MB (0x14U << MPU_RASR_SIZE_Pos) /*!< 2MB Size of the MPU protection region */ -#define LL_MPU_REGION_SIZE_4MB (0x15U << MPU_RASR_SIZE_Pos) /*!< 4MB Size of the MPU protection region */ -#define LL_MPU_REGION_SIZE_8MB (0x16U << MPU_RASR_SIZE_Pos) /*!< 8MB Size of the MPU protection region */ -#define LL_MPU_REGION_SIZE_16MB (0x17U << MPU_RASR_SIZE_Pos) /*!< 16MB Size of the MPU protection region */ -#define LL_MPU_REGION_SIZE_32MB (0x18U << MPU_RASR_SIZE_Pos) /*!< 32MB Size of the MPU protection region */ -#define LL_MPU_REGION_SIZE_64MB (0x19U << MPU_RASR_SIZE_Pos) /*!< 64MB Size of the MPU protection region */ -#define LL_MPU_REGION_SIZE_128MB (0x1AU << MPU_RASR_SIZE_Pos) /*!< 128MB Size of the MPU protection region */ -#define LL_MPU_REGION_SIZE_256MB (0x1BU << MPU_RASR_SIZE_Pos) /*!< 256MB Size of the MPU protection region */ -#define LL_MPU_REGION_SIZE_512MB (0x1CU << MPU_RASR_SIZE_Pos) /*!< 512MB Size of the MPU protection region */ -#define LL_MPU_REGION_SIZE_1GB (0x1DU << MPU_RASR_SIZE_Pos) /*!< 1GB Size of the MPU protection region */ -#define LL_MPU_REGION_SIZE_2GB (0x1EU << MPU_RASR_SIZE_Pos) /*!< 2GB Size of the MPU protection region */ -#define LL_MPU_REGION_SIZE_4GB (0x1FU << MPU_RASR_SIZE_Pos) /*!< 4GB Size of the MPU protection region */ +#define LL_MPU_REGION_SIZE_32B ((uint32_t)(0x04U << MPU_RASR_SIZE_Pos)) /*!< 32B Size of the MPU protection region */ +#define LL_MPU_REGION_SIZE_64B ((uint32_t)(0x05U << MPU_RASR_SIZE_Pos)) /*!< 64B Size of the MPU protection region */ +#define LL_MPU_REGION_SIZE_128B ((uint32_t)(0x06U << MPU_RASR_SIZE_Pos)) /*!< 128B Size of the MPU protection region */ +#define LL_MPU_REGION_SIZE_256B ((uint32_t)(0x07U << MPU_RASR_SIZE_Pos)) /*!< 256B Size of the MPU protection region */ +#define LL_MPU_REGION_SIZE_512B ((uint32_t)(0x08U << MPU_RASR_SIZE_Pos)) /*!< 512B Size of the MPU protection region */ +#define LL_MPU_REGION_SIZE_1KB ((uint32_t)(0x09U << MPU_RASR_SIZE_Pos)) /*!< 1KB Size of the MPU protection region */ +#define LL_MPU_REGION_SIZE_2KB ((uint32_t)(0x0AU << MPU_RASR_SIZE_Pos)) /*!< 2KB Size of the MPU protection region */ +#define LL_MPU_REGION_SIZE_4KB ((uint32_t)(0x0BU << MPU_RASR_SIZE_Pos)) /*!< 4KB Size of the MPU protection region */ +#define LL_MPU_REGION_SIZE_8KB ((uint32_t)(0x0CU << MPU_RASR_SIZE_Pos)) /*!< 8KB Size of the MPU protection region */ +#define LL_MPU_REGION_SIZE_16KB ((uint32_t)(0x0DU << MPU_RASR_SIZE_Pos)) /*!< 16KB Size of the MPU protection region */ +#define LL_MPU_REGION_SIZE_32KB ((uint32_t)(0x0EU << MPU_RASR_SIZE_Pos)) /*!< 32KB Size of the MPU protection region */ +#define LL_MPU_REGION_SIZE_64KB ((uint32_t)(0x0FU << MPU_RASR_SIZE_Pos)) /*!< 64KB Size of the MPU protection region */ +#define LL_MPU_REGION_SIZE_128KB ((uint32_t)(0x10U << MPU_RASR_SIZE_Pos)) /*!< 128KB Size of the MPU protection region */ +#define LL_MPU_REGION_SIZE_256KB ((uint32_t)(0x11U << MPU_RASR_SIZE_Pos)) /*!< 256KB Size of the MPU protection region */ +#define LL_MPU_REGION_SIZE_512KB ((uint32_t)(0x12U << MPU_RASR_SIZE_Pos)) /*!< 512KB Size of the MPU protection region */ +#define LL_MPU_REGION_SIZE_1MB ((uint32_t)(0x13U << MPU_RASR_SIZE_Pos)) /*!< 1MB Size of the MPU protection region */ +#define LL_MPU_REGION_SIZE_2MB ((uint32_t)(0x14U << MPU_RASR_SIZE_Pos)) /*!< 2MB Size of the MPU protection region */ +#define LL_MPU_REGION_SIZE_4MB ((uint32_t)(0x15U << MPU_RASR_SIZE_Pos)) /*!< 4MB Size of the MPU protection region */ +#define LL_MPU_REGION_SIZE_8MB ((uint32_t)(0x16U << MPU_RASR_SIZE_Pos)) /*!< 8MB Size of the MPU protection region */ +#define LL_MPU_REGION_SIZE_16MB ((uint32_t)(0x17U << MPU_RASR_SIZE_Pos)) /*!< 16MB Size of the MPU protection region */ +#define LL_MPU_REGION_SIZE_32MB ((uint32_t)(0x18U << MPU_RASR_SIZE_Pos)) /*!< 32MB Size of the MPU protection region */ +#define LL_MPU_REGION_SIZE_64MB ((uint32_t)(0x19U << MPU_RASR_SIZE_Pos)) /*!< 64MB Size of the MPU protection region */ +#define LL_MPU_REGION_SIZE_128MB ((uint32_t)(0x1AU << MPU_RASR_SIZE_Pos)) /*!< 128MB Size of the MPU protection region */ +#define LL_MPU_REGION_SIZE_256MB ((uint32_t)(0x1BU << MPU_RASR_SIZE_Pos)) /*!< 256MB Size of the MPU protection region */ +#define LL_MPU_REGION_SIZE_512MB ((uint32_t)(0x1CU << MPU_RASR_SIZE_Pos)) /*!< 512MB Size of the MPU protection region */ +#define LL_MPU_REGION_SIZE_1GB ((uint32_t)(0x1DU << MPU_RASR_SIZE_Pos)) /*!< 1GB Size of the MPU protection region */ +#define LL_MPU_REGION_SIZE_2GB ((uint32_t)(0x1EU << MPU_RASR_SIZE_Pos)) /*!< 2GB Size of the MPU protection region */ +#define LL_MPU_REGION_SIZE_4GB ((uint32_t)(0x1FU << MPU_RASR_SIZE_Pos)) /*!< 4GB Size of the MPU protection region */ /** * @} */ @@ -168,12 +168,12 @@ extern "C" { /** @defgroup CORTEX_LL_EC_REGION_PRIVILEDGES MPU Region Privileges * @{ */ -#define LL_MPU_REGION_NO_ACCESS (0x00U << MPU_RASR_AP_Pos) /*!< No access*/ -#define LL_MPU_REGION_PRIV_RW (0x01U << MPU_RASR_AP_Pos) /*!< RW privileged (privileged access only)*/ -#define LL_MPU_REGION_PRIV_RW_URO (0x02U << MPU_RASR_AP_Pos) /*!< RW privileged - RO user (Write in a user program generates a fault) */ -#define LL_MPU_REGION_FULL_ACCESS (0x03U << MPU_RASR_AP_Pos) /*!< RW privileged & user (Full access) */ -#define LL_MPU_REGION_PRIV_RO (0x05U << MPU_RASR_AP_Pos) /*!< RO privileged (privileged read only)*/ -#define LL_MPU_REGION_PRIV_RO_URO (0x06U << MPU_RASR_AP_Pos) /*!< RO privileged & user (read only) */ +#define LL_MPU_REGION_NO_ACCESS ((uint32_t)(0x00U << MPU_RASR_AP_Pos)) /*!< No access*/ +#define LL_MPU_REGION_PRIV_RW ((uint32_t)(0x01U << MPU_RASR_AP_Pos)) /*!< RW privileged (privileged access only)*/ +#define LL_MPU_REGION_PRIV_RW_URO ((uint32_t)(0x02U << MPU_RASR_AP_Pos)) /*!< RW privileged - RO user (Write in a user program generates a fault) */ +#define LL_MPU_REGION_FULL_ACCESS ((uint32_t)(0x03U << MPU_RASR_AP_Pos)) /*!< RW privileged & user (Full access) */ +#define LL_MPU_REGION_PRIV_RO ((uint32_t)(0x05U << MPU_RASR_AP_Pos)) /*!< RO privileged (privileged read only)*/ +#define LL_MPU_REGION_PRIV_RO_URO ((uint32_t)(0x06U << MPU_RASR_AP_Pos)) /*!< RO privileged & user (read only) */ /** * @} */ @@ -181,10 +181,10 @@ extern "C" { /** @defgroup CORTEX_LL_EC_TEX MPU TEX Level * @{ */ -#define LL_MPU_TEX_LEVEL0 (0x00U << MPU_RASR_TEX_Pos) /*!< b000 for TEX bits */ -#define LL_MPU_TEX_LEVEL1 (0x01U << MPU_RASR_TEX_Pos) /*!< b001 for TEX bits */ -#define LL_MPU_TEX_LEVEL2 (0x02U << MPU_RASR_TEX_Pos) /*!< b010 for TEX bits */ -#define LL_MPU_TEX_LEVEL4 (0x04U << MPU_RASR_TEX_Pos) /*!< b100 for TEX bits */ +#define LL_MPU_TEX_LEVEL0 ((uint32_t)(0x00U << MPU_RASR_TEX_Pos)) /*!< b000 for TEX bits */ +#define LL_MPU_TEX_LEVEL1 ((uint32_t)(0x01U << MPU_RASR_TEX_Pos)) /*!< b001 for TEX bits */ +#define LL_MPU_TEX_LEVEL2 ((uint32_t)(0x02U << MPU_RASR_TEX_Pos)) /*!< b010 for TEX bits */ +#define LL_MPU_TEX_LEVEL4 ((uint32_t)(0x04U << MPU_RASR_TEX_Pos)) /*!< b100 for TEX bits */ /** * @} */ @@ -192,7 +192,7 @@ extern "C" { /** @defgroup CORTEX_LL_EC_INSTRUCTION_ACCESS MPU Instruction Access * @{ */ -#define LL_MPU_INSTRUCTION_ACCESS_ENABLE 0x00U /*!< Instruction fetches enabled */ +#define LL_MPU_INSTRUCTION_ACCESS_ENABLE ((uint32_t)0x00U) /*!< Instruction fetches enabled */ #define LL_MPU_INSTRUCTION_ACCESS_DISABLE MPU_RASR_XN_Msk /*!< Instruction fetches disabled*/ /** * @} @@ -202,7 +202,7 @@ extern "C" { * @{ */ #define LL_MPU_ACCESS_SHAREABLE MPU_RASR_S_Msk /*!< Shareable memory attribute */ -#define LL_MPU_ACCESS_NOT_SHAREABLE 0x00U /*!< Not Shareable memory attribute */ +#define LL_MPU_ACCESS_NOT_SHAREABLE ((uint32_t)0x00U) /*!< Not Shareable memory attribute */ /** * @} */ @@ -211,7 +211,7 @@ extern "C" { * @{ */ #define LL_MPU_ACCESS_CACHEABLE MPU_RASR_C_Msk /*!< Cacheable memory attribute */ -#define LL_MPU_ACCESS_NOT_CACHEABLE 0x00U /*!< Not Cacheable memory attribute */ +#define LL_MPU_ACCESS_NOT_CACHEABLE ((uint32_t)0x00U) /*!< Not Cacheable memory attribute */ /** * @} */ @@ -220,7 +220,7 @@ extern "C" { * @{ */ #define LL_MPU_ACCESS_BUFFERABLE MPU_RASR_B_Msk /*!< Bufferable memory attribute */ -#define LL_MPU_ACCESS_NOT_BUFFERABLE 0x00U /*!< Not Bufferable memory attribute */ +#define LL_MPU_ACCESS_NOT_BUFFERABLE ((uint32_t)0x00U) /*!< Not Bufferable memory attribute */ /** * @} */ diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_crc.c b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_crc.c index 7d07f8fe745..de4e3c24a6e 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_crc.c +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_crc.c @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_ll_crc.c * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version $VERSION$ + * @date $DATE$ * @brief CRC LL module driver. ****************************************************************************** * @attention diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_crc.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_crc.h index e6bc9b33d64..8155b0d1f84 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_crc.h +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_crc.h @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_ll_crc.h * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version $VERSION$ + * @date $DATE$ * @brief Header file of CRC LL module. ****************************************************************************** * @attention diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_dac.c b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_dac.c deleted file mode 100644 index 60b8730367f..00000000000 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_dac.c +++ /dev/null @@ -1,274 +0,0 @@ -/** - ****************************************************************************** - * @file stm32f1xx_ll_dac.c - * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 - * @brief DAC LL module driver - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2016 STMicroelectronics

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ -#if defined(USE_FULL_LL_DRIVER) - -/* Includes ------------------------------------------------------------------*/ -#include "stm32f1xx_ll_dac.h" -#include "stm32f1xx_ll_bus.h" - -#ifdef USE_FULL_ASSERT - #include "stm32_assert.h" -#else - #define assert_param(expr) ((void)0U) -#endif - -/** @addtogroup STM32F1xx_LL_Driver - * @{ - */ - -#if defined (DAC) - -/** @addtogroup DAC_LL DAC - * @{ - */ - -/* Private types -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private constants ---------------------------------------------------------*/ -/* Private macros ------------------------------------------------------------*/ - -/** @addtogroup DAC_LL_Private_Macros - * @{ - */ - -#define IS_LL_DAC_CHANNEL(__DACX__, __DAC_CHANNEL__) \ - ( \ - ((__DAC_CHANNEL__) == LL_DAC_CHANNEL_1) \ - || ((__DAC_CHANNEL__) == LL_DAC_CHANNEL_2) \ - ) - -#define IS_LL_DAC_TRIGGER_SOURCE(__TRIGGER_SOURCE__) \ - ( ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_SOFTWARE) \ - || ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM3_TRGO) \ - || ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM15_TRGO) \ - || ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM2_TRGO) \ - || ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM4_TRGO) \ - || ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM5_TRGO) \ - || ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM6_TRGO) \ - || ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM7_TRGO) \ - || ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM8_TRGO) \ - || ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_EXTI_LINE9) \ - ) -#define IS_LL_DAC_WAVE_AUTO_GENER_MODE(__WAVE_AUTO_GENERATION_MODE__) \ - ( ((__WAVE_AUTO_GENERATION_MODE__) == LL_DAC_WAVE_AUTO_GENERATION_NONE) \ - || ((__WAVE_AUTO_GENERATION_MODE__) == LL_DAC_WAVE_AUTO_GENERATION_NOISE) \ - || ((__WAVE_AUTO_GENERATION_MODE__) == LL_DAC_WAVE_AUTO_GENERATION_TRIANGLE) \ - ) - -#define IS_LL_DAC_WAVE_AUTO_GENER_CONFIG(__WAVE_AUTO_GENERATION_CONFIG__) \ - ( ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_NOISE_LFSR_UNMASK_BIT0) \ - || ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_NOISE_LFSR_UNMASK_BITS1_0) \ - || ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_NOISE_LFSR_UNMASK_BITS2_0) \ - || ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_NOISE_LFSR_UNMASK_BITS3_0) \ - || ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_NOISE_LFSR_UNMASK_BITS4_0) \ - || ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_NOISE_LFSR_UNMASK_BITS5_0) \ - || ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_NOISE_LFSR_UNMASK_BITS6_0) \ - || ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_NOISE_LFSR_UNMASK_BITS7_0) \ - || ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_NOISE_LFSR_UNMASK_BITS8_0) \ - || ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_NOISE_LFSR_UNMASK_BITS9_0) \ - || ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_NOISE_LFSR_UNMASK_BITS10_0) \ - || ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_NOISE_LFSR_UNMASK_BITS11_0) \ - || ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_TRIANGLE_AMPLITUDE_1) \ - || ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_TRIANGLE_AMPLITUDE_3) \ - || ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_TRIANGLE_AMPLITUDE_7) \ - || ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_TRIANGLE_AMPLITUDE_15) \ - || ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_TRIANGLE_AMPLITUDE_31) \ - || ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_TRIANGLE_AMPLITUDE_63) \ - || ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_TRIANGLE_AMPLITUDE_127) \ - || ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_TRIANGLE_AMPLITUDE_255) \ - || ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_TRIANGLE_AMPLITUDE_511) \ - || ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_TRIANGLE_AMPLITUDE_1023) \ - || ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_TRIANGLE_AMPLITUDE_2047) \ - || ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_TRIANGLE_AMPLITUDE_4095) \ - ) - -#define IS_LL_DAC_OUTPUT_BUFFER(__OUTPUT_BUFFER__) \ - ( ((__OUTPUT_BUFFER__) == LL_DAC_OUTPUT_BUFFER_ENABLE) \ - || ((__OUTPUT_BUFFER__) == LL_DAC_OUTPUT_BUFFER_DISABLE) \ - ) - -/** - * @} - */ - - -/* Private function prototypes -----------------------------------------------*/ - -/* Exported functions --------------------------------------------------------*/ -/** @addtogroup DAC_LL_Exported_Functions - * @{ - */ - -/** @addtogroup DAC_LL_EF_Init - * @{ - */ - -/** - * @brief De-initialize registers of the selected DAC instance - * to their default reset values. - * @param DACx DAC instance - * @retval An ErrorStatus enumeration value: - * - SUCCESS: DAC registers are de-initialized - * - ERROR: not applicable - */ -ErrorStatus LL_DAC_DeInit(DAC_TypeDef *DACx) -{ - /* Check the parameters */ - assert_param(IS_DAC_ALL_INSTANCE(DACx)); - - /* Force reset of DAC1 clock */ - LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_DAC1); - - /* Release reset of DAC1 clock */ - LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_DAC1); - return SUCCESS; -} - -/** - * @brief Initialize some features of DAC instance. - * @note The setting of these parameters by function @ref LL_DAC_Init() - * is conditioned to DAC state: - * DAC instance must be disabled. - * @param DACx DAC instance - * @param DAC_Channel This parameter can be one of the following values: - * @arg @ref LL_DAC_CHANNEL_1 - * @arg @ref LL_DAC_CHANNEL_2 - * @param DAC_InitStruct Pointer to a @ref LL_DAC_InitTypeDef structure - * @retval An ErrorStatus enumeration value: - * - SUCCESS: DAC registers are initialized - * - ERROR: DAC registers are not initialized - */ -ErrorStatus LL_DAC_Init(DAC_TypeDef *DACx, uint32_t DAC_Channel, LL_DAC_InitTypeDef *DAC_InitStruct) -{ - ErrorStatus status = SUCCESS; - - /* Check the parameters */ - assert_param(IS_DAC_ALL_INSTANCE(DACx)); - assert_param(IS_LL_DAC_CHANNEL(DACx, DAC_Channel)); - assert_param(IS_LL_DAC_TRIGGER_SOURCE(DAC_InitStruct->TriggerSource)); - assert_param(IS_LL_DAC_OUTPUT_BUFFER(DAC_InitStruct->OutputBuffer)); - assert_param(IS_LL_DAC_WAVE_AUTO_GENER_MODE(DAC_InitStruct->WaveAutoGeneration)); - if (DAC_InitStruct->WaveAutoGeneration != LL_DAC_WAVE_AUTO_GENERATION_NONE) - { - assert_param(IS_LL_DAC_WAVE_AUTO_GENER_CONFIG(DAC_InitStruct->WaveAutoGenerationConfig)); - } - - /* Note: Hardware constraint (refer to description of this function) */ - /* DAC instance must be disabled. */ - if(LL_DAC_IsEnabled(DACx, DAC_Channel) == 0U) - { - /* Configuration of DAC channel: */ - /* - TriggerSource */ - /* - WaveAutoGeneration */ - /* - OutputBuffer */ - if (DAC_InitStruct->WaveAutoGeneration != LL_DAC_WAVE_AUTO_GENERATION_NONE) - { - MODIFY_REG(DACx->CR, - ( DAC_CR_TSEL1 - | DAC_CR_WAVE1 - | DAC_CR_MAMP1 - | DAC_CR_BOFF1 - ) << (DAC_Channel & DAC_CR_CHX_BITOFFSET_MASK) - , - ( DAC_InitStruct->TriggerSource - | DAC_InitStruct->WaveAutoGeneration - | DAC_InitStruct->WaveAutoGenerationConfig - | DAC_InitStruct->OutputBuffer - ) << (DAC_Channel & DAC_CR_CHX_BITOFFSET_MASK) - ); - } - else - { - MODIFY_REG(DACx->CR, - ( DAC_CR_TSEL1 - | DAC_CR_WAVE1 - | DAC_CR_BOFF1 - ) << (DAC_Channel & DAC_CR_CHX_BITOFFSET_MASK) - , - ( DAC_InitStruct->TriggerSource - | LL_DAC_WAVE_AUTO_GENERATION_NONE - | DAC_InitStruct->OutputBuffer - ) << (DAC_Channel & DAC_CR_CHX_BITOFFSET_MASK) - ); - } - } - else - { - /* Initialization error: DAC instance is not disabled. */ - status = ERROR; - } - return status; -} - -/** - * @brief Set each @ref LL_DAC_InitTypeDef field to default value. - * @param DAC_InitStruct pointer to a @ref LL_DAC_InitTypeDef structure - * whose fields will be set to default values. - * @retval None - */ -void LL_DAC_StructInit(LL_DAC_InitTypeDef *DAC_InitStruct) -{ - /* Set DAC_InitStruct fields to default values */ - DAC_InitStruct->TriggerSource = LL_DAC_TRIG_SOFTWARE; - DAC_InitStruct->WaveAutoGeneration = LL_DAC_WAVE_AUTO_GENERATION_NONE; - /* Note: Parameter discarded if wave auto generation is disabled, */ - /* set anyway to its default value. */ - DAC_InitStruct->WaveAutoGenerationConfig = LL_DAC_NOISE_LFSR_UNMASK_BIT0; - DAC_InitStruct->OutputBuffer = LL_DAC_OUTPUT_BUFFER_ENABLE; -} - -/** - * @} - */ - -/** - * @} - */ - -/** - * @} - */ - -#endif /* DAC */ - -/** - * @} - */ - -#endif /* USE_FULL_LL_DRIVER */ - -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_dac.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_dac.h deleted file mode 100644 index d3a3b7d0fe4..00000000000 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_dac.h +++ /dev/null @@ -1,1349 +0,0 @@ -/** - ****************************************************************************** - * @file stm32f1xx_ll_dac.h - * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 - * @brief Header file of DAC LL module. - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2016 STMicroelectronics

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ - -/* Define to prevent recursive inclusion -------------------------------------*/ -#ifndef __STM32F1xx_LL_DAC_H -#define __STM32F1xx_LL_DAC_H - -#ifdef __cplusplus -extern "C" { -#endif - -/* Includes ------------------------------------------------------------------*/ -#include "stm32f1xx.h" - -/** @addtogroup STM32F1xx_LL_Driver - * @{ - */ - -#if defined (DAC) - -/** @defgroup DAC_LL DAC - * @{ - */ - -/* Private types -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ - -/* Private constants ---------------------------------------------------------*/ -/** @defgroup DAC_LL_Private_Constants DAC Private Constants - * @{ - */ - -/* Internal masks for DAC channels definition */ -/* To select into literal LL_DAC_CHANNEL_x the relevant bits for: */ -/* - channel bits position into register CR */ -/* - channel bits position into register SWTRIG */ -/* - channel register offset of data holding register DHRx */ -/* - channel register offset of data output register DORx */ -#define DAC_CR_CH1_BITOFFSET 0U /* Position of channel bits into registers CR, MCR, CCR, SHHR, SHRR of channel 1 */ -#define DAC_CR_CH2_BITOFFSET 16U /* Position of channel bits into registers CR, MCR, CCR, SHHR, SHRR of channel 2 */ -#define DAC_CR_CHX_BITOFFSET_MASK (DAC_CR_CH1_BITOFFSET | DAC_CR_CH2_BITOFFSET) - -#define DAC_SWTR_CH1 (DAC_SWTRIGR_SWTRIG1) /* Channel bit into register SWTRIGR of channel 1. This bit is into area of LL_DAC_CR_CHx_BITOFFSET but excluded by mask DAC_CR_CHX_BITOFFSET_MASK (done to be enable to trig SW start of both DAC channels simultaneously). */ -#define DAC_SWTR_CH2 (DAC_SWTRIGR_SWTRIG2) /* Channel bit into register SWTRIGR of channel 2. This bit is into area of LL_DAC_CR_CHx_BITOFFSET but excluded by mask DAC_CR_CHX_BITOFFSET_MASK (done to be enable to trig SW start of both DAC channels simultaneously). */ -#define DAC_SWTR_CHX_MASK (DAC_SWTR_CH1 | DAC_SWTR_CH2) - -#define DAC_REG_DHR12R1_REGOFFSET 0x00000000U /* Register DHR12Rx channel 1 taken as reference */ -#define DAC_REG_DHR12L1_REGOFFSET 0x00100000U /* Register offset of DHR12Lx channel 1 versus DHR12Rx channel 1 (shifted left of 20 bits) */ -#define DAC_REG_DHR8R1_REGOFFSET 0x02000000U /* Register offset of DHR8Rx channel 1 versus DHR12Rx channel 1 (shifted left of 24 bits) */ -#define DAC_REG_DHR12R2_REGOFFSET 0x00030000U /* Register offset of DHR12Rx channel 2 versus DHR12Rx channel 1 (shifted left of 16 bits) */ -#define DAC_REG_DHR12L2_REGOFFSET 0x00400000U /* Register offset of DHR12Lx channel 2 versus DHR12Rx channel 1 (shifted left of 20 bits) */ -#define DAC_REG_DHR8R2_REGOFFSET 0x05000000U /* Register offset of DHR8Rx channel 2 versus DHR12Rx channel 1 (shifted left of 24 bits) */ -#define DAC_REG_DHR12RX_REGOFFSET_MASK 0x000F0000U -#define DAC_REG_DHR12LX_REGOFFSET_MASK 0x00F00000U -#define DAC_REG_DHR8RX_REGOFFSET_MASK 0x0F000000U -#define DAC_REG_DHRX_REGOFFSET_MASK (DAC_REG_DHR12RX_REGOFFSET_MASK | DAC_REG_DHR12LX_REGOFFSET_MASK | DAC_REG_DHR8RX_REGOFFSET_MASK) - -#define DAC_REG_DOR1_REGOFFSET 0x00000000U /* Register DORx channel 1 taken as reference */ -#define DAC_REG_DOR2_REGOFFSET 0x10000000U /* Register offset of DORx channel 1 versus DORx channel 2 (shifted left of 28 bits) */ -#define DAC_REG_DORX_REGOFFSET_MASK (DAC_REG_DOR1_REGOFFSET | DAC_REG_DOR2_REGOFFSET) - -/* DAC registers bits positions */ -#define DAC_DHR12RD_DACC2DHR_BITOFFSET_POS 16U /* Value equivalent to POSITION_VAL(DAC_DHR12RD_DACC2DHR) */ -#define DAC_DHR12LD_DACC2DHR_BITOFFSET_POS 20U /* Value equivalent to POSITION_VAL(DAC_DHR12LD_DACC2DHR) */ -#define DAC_DHR8RD_DACC2DHR_BITOFFSET_POS 8U /* Value equivalent to POSITION_VAL(DAC_DHR8RD_DACC2DHR) */ - -/* Miscellaneous data */ -#define DAC_DIGITAL_SCALE_12BITS 4095U /* Full-scale digital value with a resolution of 12 bits (voltage range determined by analog voltage references Vref+ and Vref-, refer to reference manual) */ - -/** - * @} - */ - - -/* Private macros ------------------------------------------------------------*/ -/** @defgroup DAC_LL_Private_Macros DAC Private Macros - * @{ - */ - -/** - * @brief Driver macro reserved for internal use: isolate bits with the - * selected mask and shift them to the register LSB - * (shift mask on register position bit 0). - * @param __BITS__ Bits in register 32 bits - * @param __MASK__ Mask in register 32 bits - * @retval Bits in register 32 bits -*/ -#define __DAC_MASK_SHIFT(__BITS__, __MASK__) \ - (((__BITS__) & (__MASK__)) >> POSITION_VAL((__MASK__))) - -/** - * @brief Driver macro reserved for internal use: set a pointer to - * a register from a register basis from which an offset - * is applied. - * @param __REG__ Register basis from which the offset is applied. - * @param __REG_OFFFSET__ Offset to be applied (unit: number of registers). - * @retval Pointer to register address -*/ -#define __DAC_PTR_REG_OFFSET(__REG__, __REG_OFFFSET__) \ - ((uint32_t *)((uint32_t) ((uint32_t)(&(__REG__)) + ((__REG_OFFFSET__) << 2U)))) - -/** - * @} - */ - - -/* Exported types ------------------------------------------------------------*/ -#if defined(USE_FULL_LL_DRIVER) -/** @defgroup DAC_LL_ES_INIT DAC Exported Init structure - * @{ - */ - -/** - * @brief Structure definition of some features of DAC instance. - */ -typedef struct -{ - uint32_t TriggerSource; /*!< Set the conversion trigger source for the selected DAC channel: internal (SW start) or from external IP (timer event, external interrupt line). - This parameter can be a value of @ref DAC_LL_EC_TRIGGER_SOURCE - - This feature can be modified afterwards using unitary function @ref LL_DAC_SetTriggerSource(). */ - - uint32_t WaveAutoGeneration; /*!< Set the waveform automatic generation mode for the selected DAC channel. - This parameter can be a value of @ref DAC_LL_EC_WAVE_AUTO_GENERATION_MODE - - This feature can be modified afterwards using unitary function @ref LL_DAC_SetWaveAutoGeneration(). */ - - uint32_t WaveAutoGenerationConfig; /*!< Set the waveform automatic generation mode for the selected DAC channel. - If waveform automatic generation mode is set to noise, this parameter can be a value of @ref DAC_LL_EC_WAVE_NOISE_LFSR_UNMASK_BITS - If waveform automatic generation mode is set to triangle, this parameter can be a value of @ref DAC_LL_EC_WAVE_TRIANGLE_AMPLITUDE - @note If waveform automatic generation mode is disabled, this parameter is discarded. - - This feature can be modified afterwards using unitary function @ref LL_DAC_SetWaveNoiseLFSR() or @ref LL_DAC_SetWaveTriangleAmplitude(), depending on the wave automatic generation selected. */ - - uint32_t OutputBuffer; /*!< Set the output buffer for the selected DAC channel. - This parameter can be a value of @ref DAC_LL_EC_OUTPUT_BUFFER - - This feature can be modified afterwards using unitary function @ref LL_DAC_SetOutputBuffer(). */ - -} LL_DAC_InitTypeDef; - -/** - * @} - */ -#endif /* USE_FULL_LL_DRIVER */ - -/* Exported constants --------------------------------------------------------*/ -/** @defgroup DAC_LL_Exported_Constants DAC Exported Constants - * @{ - */ - -/** @defgroup DAC_LL_EC_GET_FLAG DAC flags - * @brief Flags defines which can be used with LL_DAC_ReadReg function - * @{ - */ -/* DAC channel 1 flags */ -#if defined(DAC_SR_DMAUDR1) -#define LL_DAC_FLAG_DMAUDR1 (DAC_SR_DMAUDR1) /*!< DAC channel 1 flag DMA underrun */ -#endif /* DAC_SR_DMAUDR1 */ - -/* DAC channel 2 flags */ -#if defined(DAC_SR_DMAUDR2) -#define LL_DAC_FLAG_DMAUDR2 (DAC_SR_DMAUDR2) /*!< DAC channel 2 flag DMA underrun */ -#endif /* DAC_SR_DMAUDR2 */ -/** - * @} - */ - -/** @defgroup DAC_LL_EC_IT DAC interruptions - * @brief IT defines which can be used with LL_DAC_ReadReg and LL_DAC_WriteReg functions - * @{ - */ -#if defined(DAC_CR_DMAUDRIE1) -#define LL_DAC_IT_DMAUDRIE1 (DAC_CR_DMAUDRIE1) /*!< DAC channel 1 interruption DMA underrun */ -#endif /* DAC_CR_DMAUDRIE1 */ -#if defined(DAC_CR_DMAUDRIE2) -#define LL_DAC_IT_DMAUDRIE2 (DAC_CR_DMAUDRIE2) /*!< DAC channel 2 interruption DMA underrun */ -#endif /* DAC_CR_DMAUDRIE2 */ -/** - * @} - */ - -/** @defgroup DAC_LL_EC_CHANNEL DAC channels - * @{ - */ -#define LL_DAC_CHANNEL_1 (DAC_REG_DOR1_REGOFFSET | DAC_REG_DHR12R1_REGOFFSET | DAC_REG_DHR12L1_REGOFFSET | DAC_REG_DHR8R1_REGOFFSET | DAC_CR_CH1_BITOFFSET | DAC_SWTR_CH1) /*!< DAC channel 1 */ -#define LL_DAC_CHANNEL_2 (DAC_REG_DOR2_REGOFFSET | DAC_REG_DHR12R2_REGOFFSET | DAC_REG_DHR12L2_REGOFFSET | DAC_REG_DHR8R2_REGOFFSET | DAC_CR_CH2_BITOFFSET | DAC_SWTR_CH2) /*!< DAC channel 2 */ -/** - * @} - */ - -/** @defgroup DAC_LL_EC_TRIGGER_SOURCE DAC trigger source - * @{ - */ -#define LL_DAC_TRIG_SOFTWARE (DAC_CR_TSEL1_2 | DAC_CR_TSEL1_1 | DAC_CR_TSEL1_0) /*!< DAC channel conversion trigger internal (SW start) */ -#define LL_DAC_TRIG_EXT_TIM3_TRGO ( DAC_CR_TSEL1_0) /*!< DAC channel conversion trigger from external IP: TIM3 TRGO. */ -#define LL_DAC_TRIG_EXT_TIM15_TRGO ( DAC_CR_TSEL1_1 | DAC_CR_TSEL1_0) /*!< DAC channel conversion trigger from external IP: TIM15 TRGO. */ -#define LL_DAC_TRIG_EXT_TIM2_TRGO (DAC_CR_TSEL1_2 ) /*!< DAC channel conversion trigger from external IP: TIM2 TRGO. */ -#define LL_DAC_TRIG_EXT_TIM8_TRGO ( DAC_CR_TSEL1_0) /*!< DAC channel conversion trigger from external IP: TIM8 TRGO. */ -#define LL_DAC_TRIG_EXT_TIM4_TRGO (DAC_CR_TSEL1_2 | DAC_CR_TSEL1_0) /*!< DAC channel conversion trigger from external IP: TIM4 TRGO. */ -#define LL_DAC_TRIG_EXT_TIM6_TRGO 0x00000000U /*!< DAC channel conversion trigger from external IP: TIM6 TRGO. */ -#define LL_DAC_TRIG_EXT_TIM7_TRGO ( DAC_CR_TSEL1_1 ) /*!< DAC channel conversion trigger from external IP: TIM7 TRGO. */ -#define LL_DAC_TRIG_EXT_TIM5_TRGO ( DAC_CR_TSEL1_1 | DAC_CR_TSEL1_0) /*!< DAC channel conversion trigger from external IP: TIM5 TRGO. */ -#define LL_DAC_TRIG_EXT_EXTI_LINE9 (DAC_CR_TSEL1_2 | DAC_CR_TSEL1_1 ) /*!< DAC channel conversion trigger from external IP: external interrupt line 9. */ -/** - * @} - */ - -/** @defgroup DAC_LL_EC_WAVE_AUTO_GENERATION_MODE DAC waveform automatic generation mode - * @{ - */ -#define LL_DAC_WAVE_AUTO_GENERATION_NONE 0x00000000U /*!< DAC channel wave auto generation mode disabled. */ -#define LL_DAC_WAVE_AUTO_GENERATION_NOISE (DAC_CR_WAVE1_0) /*!< DAC channel wave auto generation mode enabled, set generated noise waveform. */ -#define LL_DAC_WAVE_AUTO_GENERATION_TRIANGLE (DAC_CR_WAVE1_1) /*!< DAC channel wave auto generation mode enabled, set generated triangle waveform. */ -/** - * @} - */ - -/** @defgroup DAC_LL_EC_WAVE_NOISE_LFSR_UNMASK_BITS DAC wave generation - Noise LFSR unmask bits - * @{ - */ -#define LL_DAC_NOISE_LFSR_UNMASK_BIT0 0x00000000U /*!< Noise wave generation, unmask LFSR bit0, for the selected DAC channel */ -#define LL_DAC_NOISE_LFSR_UNMASK_BITS1_0 ( DAC_CR_MAMP1_0) /*!< Noise wave generation, unmask LFSR bits[1:0], for the selected DAC channel */ -#define LL_DAC_NOISE_LFSR_UNMASK_BITS2_0 ( DAC_CR_MAMP1_1 ) /*!< Noise wave generation, unmask LFSR bits[2:0], for the selected DAC channel */ -#define LL_DAC_NOISE_LFSR_UNMASK_BITS3_0 ( DAC_CR_MAMP1_1 | DAC_CR_MAMP1_0) /*!< Noise wave generation, unmask LFSR bits[3:0], for the selected DAC channel */ -#define LL_DAC_NOISE_LFSR_UNMASK_BITS4_0 ( DAC_CR_MAMP1_2 ) /*!< Noise wave generation, unmask LFSR bits[4:0], for the selected DAC channel */ -#define LL_DAC_NOISE_LFSR_UNMASK_BITS5_0 ( DAC_CR_MAMP1_2 | DAC_CR_MAMP1_0) /*!< Noise wave generation, unmask LFSR bits[5:0], for the selected DAC channel */ -#define LL_DAC_NOISE_LFSR_UNMASK_BITS6_0 ( DAC_CR_MAMP1_2 | DAC_CR_MAMP1_1 ) /*!< Noise wave generation, unmask LFSR bits[6:0], for the selected DAC channel */ -#define LL_DAC_NOISE_LFSR_UNMASK_BITS7_0 ( DAC_CR_MAMP1_2 | DAC_CR_MAMP1_1 | DAC_CR_MAMP1_0) /*!< Noise wave generation, unmask LFSR bits[7:0], for the selected DAC channel */ -#define LL_DAC_NOISE_LFSR_UNMASK_BITS8_0 (DAC_CR_MAMP1_3 ) /*!< Noise wave generation, unmask LFSR bits[8:0], for the selected DAC channel */ -#define LL_DAC_NOISE_LFSR_UNMASK_BITS9_0 (DAC_CR_MAMP1_3 | DAC_CR_MAMP1_0) /*!< Noise wave generation, unmask LFSR bits[9:0], for the selected DAC channel */ -#define LL_DAC_NOISE_LFSR_UNMASK_BITS10_0 (DAC_CR_MAMP1_3 | DAC_CR_MAMP1_1 ) /*!< Noise wave generation, unmask LFSR bits[10:0], for the selected DAC channel */ -#define LL_DAC_NOISE_LFSR_UNMASK_BITS11_0 (DAC_CR_MAMP1_3 | DAC_CR_MAMP1_1 | DAC_CR_MAMP1_0) /*!< Noise wave generation, unmask LFSR bits[11:0], for the selected DAC channel */ -/** - * @} - */ - -/** @defgroup DAC_LL_EC_WAVE_TRIANGLE_AMPLITUDE DAC wave generation - Triangle amplitude - * @{ - */ -#define LL_DAC_TRIANGLE_AMPLITUDE_1 0x00000000U /*!< Triangle wave generation, amplitude of 1 LSB of DAC output range, for the selected DAC channel */ -#define LL_DAC_TRIANGLE_AMPLITUDE_3 ( DAC_CR_MAMP1_0) /*!< Triangle wave generation, amplitude of 3 LSB of DAC output range, for the selected DAC channel */ -#define LL_DAC_TRIANGLE_AMPLITUDE_7 ( DAC_CR_MAMP1_1 ) /*!< Triangle wave generation, amplitude of 7 LSB of DAC output range, for the selected DAC channel */ -#define LL_DAC_TRIANGLE_AMPLITUDE_15 ( DAC_CR_MAMP1_1 | DAC_CR_MAMP1_0) /*!< Triangle wave generation, amplitude of 15 LSB of DAC output range, for the selected DAC channel */ -#define LL_DAC_TRIANGLE_AMPLITUDE_31 ( DAC_CR_MAMP1_2 ) /*!< Triangle wave generation, amplitude of 31 LSB of DAC output range, for the selected DAC channel */ -#define LL_DAC_TRIANGLE_AMPLITUDE_63 ( DAC_CR_MAMP1_2 | DAC_CR_MAMP1_0) /*!< Triangle wave generation, amplitude of 63 LSB of DAC output range, for the selected DAC channel */ -#define LL_DAC_TRIANGLE_AMPLITUDE_127 ( DAC_CR_MAMP1_2 | DAC_CR_MAMP1_1 ) /*!< Triangle wave generation, amplitude of 127 LSB of DAC output range, for the selected DAC channel */ -#define LL_DAC_TRIANGLE_AMPLITUDE_255 ( DAC_CR_MAMP1_2 | DAC_CR_MAMP1_1 | DAC_CR_MAMP1_0) /*!< Triangle wave generation, amplitude of 255 LSB of DAC output range, for the selected DAC channel */ -#define LL_DAC_TRIANGLE_AMPLITUDE_511 (DAC_CR_MAMP1_3 ) /*!< Triangle wave generation, amplitude of 512 LSB of DAC output range, for the selected DAC channel */ -#define LL_DAC_TRIANGLE_AMPLITUDE_1023 (DAC_CR_MAMP1_3 | DAC_CR_MAMP1_0) /*!< Triangle wave generation, amplitude of 1023 LSB of DAC output range, for the selected DAC channel */ -#define LL_DAC_TRIANGLE_AMPLITUDE_2047 (DAC_CR_MAMP1_3 | DAC_CR_MAMP1_1 ) /*!< Triangle wave generation, amplitude of 2047 LSB of DAC output range, for the selected DAC channel */ -#define LL_DAC_TRIANGLE_AMPLITUDE_4095 (DAC_CR_MAMP1_3 | DAC_CR_MAMP1_1 | DAC_CR_MAMP1_0) /*!< Triangle wave generation, amplitude of 4095 LSB of DAC output range, for the selected DAC channel */ -/** - * @} - */ - -/** @defgroup DAC_LL_EC_OUTPUT_BUFFER DAC channel output buffer - * @{ - */ -#define LL_DAC_OUTPUT_BUFFER_ENABLE 0x00000000U /*!< The selected DAC channel output is buffered: higher drive current capability, but also higher current consumption */ -#define LL_DAC_OUTPUT_BUFFER_DISABLE (DAC_CR_BOFF1) /*!< The selected DAC channel output is not buffered: lower drive current capability, but also lower current consumption */ -/** - * @} - */ - - -/** @defgroup DAC_LL_EC_RESOLUTION DAC channel output resolution - * @{ - */ -#define LL_DAC_RESOLUTION_12B 0x00000000U /*!< DAC channel resolution 12 bits */ -#define LL_DAC_RESOLUTION_8B 0x00000002U /*!< DAC channel resolution 8 bits */ -/** - * @} - */ - -/** @defgroup DAC_LL_EC_REGISTERS DAC registers compliant with specific purpose - * @{ - */ -/* List of DAC registers intended to be used (most commonly) with */ -/* DMA transfer. */ -/* Refer to function @ref LL_DAC_DMA_GetRegAddr(). */ -#define LL_DAC_DMA_REG_DATA_12BITS_RIGHT_ALIGNED DAC_REG_DHR12RX_REGOFFSET_MASK /*!< DAC channel data holding register 12 bits right aligned */ -#define LL_DAC_DMA_REG_DATA_12BITS_LEFT_ALIGNED DAC_REG_DHR12LX_REGOFFSET_MASK /*!< DAC channel data holding register 12 bits left aligned */ -#define LL_DAC_DMA_REG_DATA_8BITS_RIGHT_ALIGNED DAC_REG_DHR8RX_REGOFFSET_MASK /*!< DAC channel data holding register 8 bits right aligned */ -/** - * @} - */ - -/** @defgroup DAC_LL_EC_HW_DELAYS Definitions of DAC hardware constraints delays - * @note Only DAC IP HW delays are defined in DAC LL driver driver, - * not timeout values. - * For details on delays values, refer to descriptions in source code - * above each literal definition. - * @{ - */ - -/* Delay for DAC channel voltage settling time from DAC channel startup */ -/* (transition from disable to enable). */ -/* Note: DAC channel startup time depends on board application environment: */ -/* impedance connected to DAC channel output. */ -/* The delay below is specified under conditions: */ -/* - voltage maximum transition (lowest to highest value) */ -/* - until voltage reaches final value +-1LSB */ -/* - DAC channel output buffer enabled */ -/* - load impedance of 5kOhm (min), 50pF (max) */ -/* Literal set to maximum value (refer to device datasheet, */ -/* parameter "tWAKEUP"). */ -/* Unit: us */ -#define LL_DAC_DELAY_STARTUP_VOLTAGE_SETTLING_US 15U /*!< Delay for DAC channel voltage settling time from DAC channel startup (transition from disable to enable) */ - -/* Delay for DAC channel voltage settling time. */ -/* Note: DAC channel startup time depends on board application environment: */ -/* impedance connected to DAC channel output. */ -/* The delay below is specified under conditions: */ -/* - voltage maximum transition (lowest to highest value) */ -/* - until voltage reaches final value +-1LSB */ -/* - DAC channel output buffer enabled */ -/* - load impedance of 5kOhm min, 50pF max */ -/* Literal set to maximum value (refer to device datasheet, */ -/* parameter "tSETTLING"). */ -/* Unit: us */ -#define LL_DAC_DELAY_VOLTAGE_SETTLING_US 12U /*!< Delay for DAC channel voltage settling time */ -/** - * @} - */ - -/** - * @} - */ - -/* Exported macro ------------------------------------------------------------*/ -/** @defgroup DAC_LL_Exported_Macros DAC Exported Macros - * @{ - */ - -/** @defgroup DAC_LL_EM_WRITE_READ Common write and read registers macros - * @{ - */ - -/** - * @brief Write a value in DAC register - * @param __INSTANCE__ DAC Instance - * @param __REG__ Register to be written - * @param __VALUE__ Value to be written in the register - * @retval None - */ -#define LL_DAC_WriteReg(__INSTANCE__, __REG__, __VALUE__) WRITE_REG(__INSTANCE__->__REG__, (__VALUE__)) - -/** - * @brief Read a value in DAC register - * @param __INSTANCE__ DAC Instance - * @param __REG__ Register to be read - * @retval Register value - */ -#define LL_DAC_ReadReg(__INSTANCE__, __REG__) READ_REG(__INSTANCE__->__REG__) - -/** - * @} - */ - -/** @defgroup DAC_LL_EM_HELPER_MACRO DAC helper macro - * @{ - */ - -/** - * @brief Helper macro to get DAC channel number in decimal format - * from literals LL_DAC_CHANNEL_x. - * Example: - * __LL_DAC_CHANNEL_TO_DECIMAL_NB(LL_DAC_CHANNEL_1) - * will return decimal number "1". - * @note The input can be a value from functions where a channel - * number is returned. - * @param __CHANNEL__ This parameter can be one of the following values: - * @arg @ref LL_DAC_CHANNEL_1 - * @arg @ref LL_DAC_CHANNEL_2 - * @retval 1...2 - */ -#define __LL_DAC_CHANNEL_TO_DECIMAL_NB(__CHANNEL__) \ - ((__CHANNEL__) & DAC_SWTR_CHX_MASK) - -/** - * @brief Helper macro to get DAC channel in literal format LL_DAC_CHANNEL_x - * from number in decimal format. - * Example: - * __LL_DAC_DECIMAL_NB_TO_CHANNEL(1) - * will return a data equivalent to "LL_DAC_CHANNEL_1". - * @note If the input parameter does not correspond to a DAC channel, - * this macro returns value '0'. - * @param __DECIMAL_NB__ 1...2 - * @retval Returned value can be one of the following values: - * @arg @ref LL_DAC_CHANNEL_1 - * @arg @ref LL_DAC_CHANNEL_2 - */ -#define __LL_DAC_DECIMAL_NB_TO_CHANNEL(__DECIMAL_NB__) \ - (((__DECIMAL_NB__) == 1U) \ - ? ( \ - LL_DAC_CHANNEL_1 \ - ) \ - : \ - (((__DECIMAL_NB__) == 2U) \ - ? ( \ - LL_DAC_CHANNEL_2 \ - ) \ - : \ - ( \ - 0 \ - ) \ - ) \ - ) - -/** - * @brief Helper macro to define the DAC conversion data full-scale digital - * value corresponding to the selected DAC resolution. - * @note DAC conversion data full-scale corresponds to voltage range - * determined by analog voltage references Vref+ and Vref- - * (refer to reference manual). - * @param __DAC_RESOLUTION__ This parameter can be one of the following values: - * @arg @ref LL_DAC_RESOLUTION_12B - * @arg @ref LL_DAC_RESOLUTION_8B - * @retval ADC conversion data equivalent voltage value (unit: mVolt) - */ -#define __LL_DAC_DIGITAL_SCALE(__DAC_RESOLUTION__) \ - ((0x00000FFFU) >> ((__DAC_RESOLUTION__) << 1U)) - -/** - * @brief Helper macro to calculate the DAC conversion data (unit: digital - * value) corresponding to a voltage (unit: mVolt). - * @note This helper macro is intended to provide input data in voltage - * rather than digital value, - * to be used with LL DAC functions such as - * @ref LL_DAC_ConvertData12RightAligned(). - * @note Analog reference voltage (Vref+) must be either known from - * user board environment or can be calculated using ADC measurement - * and ADC helper macro @ref __LL_ADC_CALC_VREFANALOG_VOLTAGE(). - * @param __VREFANALOG_VOLTAGE__ Analog reference voltage (unit: mV) - * @param __DAC_VOLTAGE__ Voltage to be generated by DAC channel - * (unit: mVolt). - * @param __DAC_RESOLUTION__ This parameter can be one of the following values: - * @arg @ref LL_DAC_RESOLUTION_12B - * @arg @ref LL_DAC_RESOLUTION_8B - * @retval DAC conversion data (unit: digital value) - */ -#define __LL_DAC_CALC_VOLTAGE_TO_DATA(__VREFANALOG_VOLTAGE__,\ - __DAC_VOLTAGE__,\ - __DAC_RESOLUTION__) \ - ((__DAC_VOLTAGE__) * __LL_DAC_DIGITAL_SCALE(__DAC_RESOLUTION__) \ - / (__VREFANALOG_VOLTAGE__) \ - ) - -/** - * @} - */ - -/** - * @} - */ - - -/* Exported functions --------------------------------------------------------*/ -/** @defgroup DAC_LL_Exported_Functions DAC Exported Functions - * @{ - */ -/** @defgroup DAC_LL_EF_Configuration Configuration of DAC channels - * @{ - */ - -/** - * @brief Set the conversion trigger source for the selected DAC channel. - * @note For conversion trigger source to be effective, DAC trigger - * must be enabled using function @ref LL_DAC_EnableTrigger(). - * @note To set conversion trigger source, DAC channel must be disabled. - * Otherwise, the setting is discarded. - * @note Availability of parameters of trigger sources from timer - * depends on timers availability on the selected device. - * @rmtoll CR TSEL1 LL_DAC_SetTriggerSource\n - * CR TSEL2 LL_DAC_SetTriggerSource - * @param DACx DAC instance - * @param DAC_Channel This parameter can be one of the following values: - * @arg @ref LL_DAC_CHANNEL_1 - * @arg @ref LL_DAC_CHANNEL_2 - * @param TriggerSource This parameter can be one of the following values: - * @arg @ref LL_DAC_TRIG_SOFTWARE - * @arg @ref LL_DAC_TRIG_EXT_TIM3_TRGO - * @arg @ref LL_DAC_TRIG_EXT_TIM15_TRGO - * @arg @ref LL_DAC_TRIG_EXT_TIM8_TRGO - * @arg @ref LL_DAC_TRIG_EXT_TIM7_TRGO - * @arg @ref LL_DAC_TRIG_EXT_TIM6_TRGO - * @arg @ref LL_DAC_TRIG_EXT_TIM5_TRGO - * @arg @ref LL_DAC_TRIG_EXT_TIM4_TRGO - * @arg @ref LL_DAC_TRIG_EXT_TIM2_TRGO - * @arg @ref LL_DAC_TRIG_EXT_EXTI_LINE9 - * @retval None - */ -__STATIC_INLINE void LL_DAC_SetTriggerSource(DAC_TypeDef *DACx, uint32_t DAC_Channel, uint32_t TriggerSource) -{ - MODIFY_REG(DACx->CR, - DAC_CR_TSEL1 << (DAC_Channel & DAC_CR_CHX_BITOFFSET_MASK), - TriggerSource << (DAC_Channel & DAC_CR_CHX_BITOFFSET_MASK)); -} - -/** - * @brief Get the conversion trigger source for the selected DAC channel. - * @note For conversion trigger source to be effective, DAC trigger - * must be enabled using function @ref LL_DAC_EnableTrigger(). - * @note Availability of parameters of trigger sources from timer - * depends on timers availability on the selected device. - * @rmtoll CR TSEL1 LL_DAC_GetTriggerSource\n - * CR TSEL2 LL_DAC_GetTriggerSource - * @param DACx DAC instance - * @param DAC_Channel This parameter can be one of the following values: - * @arg @ref LL_DAC_CHANNEL_1 - * @arg @ref LL_DAC_CHANNEL_2 - * @retval Returned value can be one of the following values: - * @arg @ref LL_DAC_TRIG_SOFTWARE - * @arg @ref LL_DAC_TRIG_EXT_TIM3_TRGO - * @arg @ref LL_DAC_TRIG_EXT_TIM15_TRGO - * @arg @ref LL_DAC_TRIG_EXT_TIM8_TRGO - * @arg @ref LL_DAC_TRIG_EXT_TIM7_TRGO - * @arg @ref LL_DAC_TRIG_EXT_TIM6_TRGO - * @arg @ref LL_DAC_TRIG_EXT_TIM5_TRGO - * @arg @ref LL_DAC_TRIG_EXT_TIM4_TRGO - * @arg @ref LL_DAC_TRIG_EXT_TIM2_TRGO - * @arg @ref LL_DAC_TRIG_EXT_EXTI_LINE9 - */ -__STATIC_INLINE uint32_t LL_DAC_GetTriggerSource(DAC_TypeDef *DACx, uint32_t DAC_Channel) -{ - return (uint32_t)(READ_BIT(DACx->CR, DAC_CR_TSEL1 << (DAC_Channel & DAC_CR_CHX_BITOFFSET_MASK)) - >> (DAC_Channel & DAC_CR_CHX_BITOFFSET_MASK) - ); -} - -/** - * @brief Set the waveform automatic generation mode - * for the selected DAC channel. - * @rmtoll CR WAVE1 LL_DAC_SetWaveAutoGeneration\n - * CR WAVE2 LL_DAC_SetWaveAutoGeneration - * @param DACx DAC instance - * @param DAC_Channel This parameter can be one of the following values: - * @arg @ref LL_DAC_CHANNEL_1 - * @arg @ref LL_DAC_CHANNEL_2 - * @param WaveAutoGeneration This parameter can be one of the following values: - * @arg @ref LL_DAC_WAVE_AUTO_GENERATION_NONE - * @arg @ref LL_DAC_WAVE_AUTO_GENERATION_NOISE - * @arg @ref LL_DAC_WAVE_AUTO_GENERATION_TRIANGLE - * @retval None - */ -__STATIC_INLINE void LL_DAC_SetWaveAutoGeneration(DAC_TypeDef *DACx, uint32_t DAC_Channel, uint32_t WaveAutoGeneration) -{ - MODIFY_REG(DACx->CR, - DAC_CR_WAVE1 << (DAC_Channel & DAC_CR_CHX_BITOFFSET_MASK), - WaveAutoGeneration << (DAC_Channel & DAC_CR_CHX_BITOFFSET_MASK)); -} - -/** - * @brief Get the waveform automatic generation mode - * for the selected DAC channel. - * @rmtoll CR WAVE1 LL_DAC_GetWaveAutoGeneration\n - * CR WAVE2 LL_DAC_GetWaveAutoGeneration - * @param DACx DAC instance - * @param DAC_Channel This parameter can be one of the following values: - * @arg @ref LL_DAC_CHANNEL_1 - * @arg @ref LL_DAC_CHANNEL_2 - * @retval Returned value can be one of the following values: - * @arg @ref LL_DAC_WAVE_AUTO_GENERATION_NONE - * @arg @ref LL_DAC_WAVE_AUTO_GENERATION_NOISE - * @arg @ref LL_DAC_WAVE_AUTO_GENERATION_TRIANGLE - */ -__STATIC_INLINE uint32_t LL_DAC_GetWaveAutoGeneration(DAC_TypeDef *DACx, uint32_t DAC_Channel) -{ - return (uint32_t)(READ_BIT(DACx->CR, DAC_CR_WAVE1 << (DAC_Channel & DAC_CR_CHX_BITOFFSET_MASK)) - >> (DAC_Channel & DAC_CR_CHX_BITOFFSET_MASK) - ); -} - -/** - * @brief Set the noise waveform generation for the selected DAC channel: - * Noise mode and parameters LFSR (linear feedback shift register). - * @note For wave generation to be effective, DAC channel - * wave generation mode must be enabled using - * function @ref LL_DAC_SetWaveAutoGeneration(). - * @note This setting can be set when the selected DAC channel is disabled - * (otherwise, the setting operation is ignored). - * @rmtoll CR MAMP1 LL_DAC_SetWaveNoiseLFSR\n - * CR MAMP2 LL_DAC_SetWaveNoiseLFSR - * @param DACx DAC instance - * @param DAC_Channel This parameter can be one of the following values: - * @arg @ref LL_DAC_CHANNEL_1 - * @arg @ref LL_DAC_CHANNEL_2 - * @param NoiseLFSRMask This parameter can be one of the following values: - * @arg @ref LL_DAC_NOISE_LFSR_UNMASK_BIT0 - * @arg @ref LL_DAC_NOISE_LFSR_UNMASK_BITS1_0 - * @arg @ref LL_DAC_NOISE_LFSR_UNMASK_BITS2_0 - * @arg @ref LL_DAC_NOISE_LFSR_UNMASK_BITS3_0 - * @arg @ref LL_DAC_NOISE_LFSR_UNMASK_BITS4_0 - * @arg @ref LL_DAC_NOISE_LFSR_UNMASK_BITS5_0 - * @arg @ref LL_DAC_NOISE_LFSR_UNMASK_BITS6_0 - * @arg @ref LL_DAC_NOISE_LFSR_UNMASK_BITS7_0 - * @arg @ref LL_DAC_NOISE_LFSR_UNMASK_BITS8_0 - * @arg @ref LL_DAC_NOISE_LFSR_UNMASK_BITS9_0 - * @arg @ref LL_DAC_NOISE_LFSR_UNMASK_BITS10_0 - * @arg @ref LL_DAC_NOISE_LFSR_UNMASK_BITS11_0 - * @retval None - */ -__STATIC_INLINE void LL_DAC_SetWaveNoiseLFSR(DAC_TypeDef *DACx, uint32_t DAC_Channel, uint32_t NoiseLFSRMask) -{ - MODIFY_REG(DACx->CR, - DAC_CR_MAMP1 << (DAC_Channel & DAC_CR_CHX_BITOFFSET_MASK), - NoiseLFSRMask << (DAC_Channel & DAC_CR_CHX_BITOFFSET_MASK)); -} - -/** - * @brief Set the noise waveform generation for the selected DAC channel: - * Noise mode and parameters LFSR (linear feedback shift register). - * @rmtoll CR MAMP1 LL_DAC_GetWaveNoiseLFSR\n - * CR MAMP2 LL_DAC_GetWaveNoiseLFSR - * @param DACx DAC instance - * @param DAC_Channel This parameter can be one of the following values: - * @arg @ref LL_DAC_CHANNEL_1 - * @arg @ref LL_DAC_CHANNEL_2 - * @retval Returned value can be one of the following values: - * @arg @ref LL_DAC_NOISE_LFSR_UNMASK_BIT0 - * @arg @ref LL_DAC_NOISE_LFSR_UNMASK_BITS1_0 - * @arg @ref LL_DAC_NOISE_LFSR_UNMASK_BITS2_0 - * @arg @ref LL_DAC_NOISE_LFSR_UNMASK_BITS3_0 - * @arg @ref LL_DAC_NOISE_LFSR_UNMASK_BITS4_0 - * @arg @ref LL_DAC_NOISE_LFSR_UNMASK_BITS5_0 - * @arg @ref LL_DAC_NOISE_LFSR_UNMASK_BITS6_0 - * @arg @ref LL_DAC_NOISE_LFSR_UNMASK_BITS7_0 - * @arg @ref LL_DAC_NOISE_LFSR_UNMASK_BITS8_0 - * @arg @ref LL_DAC_NOISE_LFSR_UNMASK_BITS9_0 - * @arg @ref LL_DAC_NOISE_LFSR_UNMASK_BITS10_0 - * @arg @ref LL_DAC_NOISE_LFSR_UNMASK_BITS11_0 - */ -__STATIC_INLINE uint32_t LL_DAC_GetWaveNoiseLFSR(DAC_TypeDef *DACx, uint32_t DAC_Channel) -{ - return (uint32_t)(READ_BIT(DACx->CR, DAC_CR_MAMP1 << (DAC_Channel & DAC_CR_CHX_BITOFFSET_MASK)) - >> (DAC_Channel & DAC_CR_CHX_BITOFFSET_MASK) - ); -} - -/** - * @brief Set the triangle waveform generation for the selected DAC channel: - * triangle mode and amplitude. - * @note For wave generation to be effective, DAC channel - * wave generation mode must be enabled using - * function @ref LL_DAC_SetWaveAutoGeneration(). - * @note This setting can be set when the selected DAC channel is disabled - * (otherwise, the setting operation is ignored). - * @rmtoll CR MAMP1 LL_DAC_SetWaveTriangleAmplitude\n - * CR MAMP2 LL_DAC_SetWaveTriangleAmplitude - * @param DACx DAC instance - * @param DAC_Channel This parameter can be one of the following values: - * @arg @ref LL_DAC_CHANNEL_1 - * @arg @ref LL_DAC_CHANNEL_2 - * @param TriangleAmplitude This parameter can be one of the following values: - * @arg @ref LL_DAC_TRIANGLE_AMPLITUDE_1 - * @arg @ref LL_DAC_TRIANGLE_AMPLITUDE_3 - * @arg @ref LL_DAC_TRIANGLE_AMPLITUDE_7 - * @arg @ref LL_DAC_TRIANGLE_AMPLITUDE_15 - * @arg @ref LL_DAC_TRIANGLE_AMPLITUDE_31 - * @arg @ref LL_DAC_TRIANGLE_AMPLITUDE_63 - * @arg @ref LL_DAC_TRIANGLE_AMPLITUDE_127 - * @arg @ref LL_DAC_TRIANGLE_AMPLITUDE_255 - * @arg @ref LL_DAC_TRIANGLE_AMPLITUDE_511 - * @arg @ref LL_DAC_TRIANGLE_AMPLITUDE_1023 - * @arg @ref LL_DAC_TRIANGLE_AMPLITUDE_2047 - * @arg @ref LL_DAC_TRIANGLE_AMPLITUDE_4095 - * @retval None - */ -__STATIC_INLINE void LL_DAC_SetWaveTriangleAmplitude(DAC_TypeDef *DACx, uint32_t DAC_Channel, uint32_t TriangleAmplitude) -{ - MODIFY_REG(DACx->CR, - DAC_CR_MAMP1 << (DAC_Channel & DAC_CR_CHX_BITOFFSET_MASK), - TriangleAmplitude << (DAC_Channel & DAC_CR_CHX_BITOFFSET_MASK)); -} - -/** - * @brief Set the triangle waveform generation for the selected DAC channel: - * triangle mode and amplitude. - * @rmtoll CR MAMP1 LL_DAC_GetWaveTriangleAmplitude\n - * CR MAMP2 LL_DAC_GetWaveTriangleAmplitude - * @param DACx DAC instance - * @param DAC_Channel This parameter can be one of the following values: - * @arg @ref LL_DAC_CHANNEL_1 - * @arg @ref LL_DAC_CHANNEL_2 - * @retval Returned value can be one of the following values: - * @arg @ref LL_DAC_TRIANGLE_AMPLITUDE_1 - * @arg @ref LL_DAC_TRIANGLE_AMPLITUDE_3 - * @arg @ref LL_DAC_TRIANGLE_AMPLITUDE_7 - * @arg @ref LL_DAC_TRIANGLE_AMPLITUDE_15 - * @arg @ref LL_DAC_TRIANGLE_AMPLITUDE_31 - * @arg @ref LL_DAC_TRIANGLE_AMPLITUDE_63 - * @arg @ref LL_DAC_TRIANGLE_AMPLITUDE_127 - * @arg @ref LL_DAC_TRIANGLE_AMPLITUDE_255 - * @arg @ref LL_DAC_TRIANGLE_AMPLITUDE_511 - * @arg @ref LL_DAC_TRIANGLE_AMPLITUDE_1023 - * @arg @ref LL_DAC_TRIANGLE_AMPLITUDE_2047 - * @arg @ref LL_DAC_TRIANGLE_AMPLITUDE_4095 - */ -__STATIC_INLINE uint32_t LL_DAC_GetWaveTriangleAmplitude(DAC_TypeDef *DACx, uint32_t DAC_Channel) -{ - return (uint32_t)(READ_BIT(DACx->CR, DAC_CR_MAMP1 << (DAC_Channel & DAC_CR_CHX_BITOFFSET_MASK)) - >> (DAC_Channel & DAC_CR_CHX_BITOFFSET_MASK) - ); -} - -/** - * @brief Set the output buffer for the selected DAC channel. - * @rmtoll CR BOFF1 LL_DAC_SetOutputBuffer\n - * CR BOFF2 LL_DAC_SetOutputBuffer - * @param DACx DAC instance - * @param DAC_Channel This parameter can be one of the following values: - * @arg @ref LL_DAC_CHANNEL_1 - * @arg @ref LL_DAC_CHANNEL_2 - * @param OutputBuffer This parameter can be one of the following values: - * @arg @ref LL_DAC_OUTPUT_BUFFER_ENABLE - * @arg @ref LL_DAC_OUTPUT_BUFFER_DISABLE - * @retval None - */ -__STATIC_INLINE void LL_DAC_SetOutputBuffer(DAC_TypeDef *DACx, uint32_t DAC_Channel, uint32_t OutputBuffer) -{ - MODIFY_REG(DACx->CR, - DAC_CR_BOFF1 << (DAC_Channel & DAC_CR_CHX_BITOFFSET_MASK), - OutputBuffer << (DAC_Channel & DAC_CR_CHX_BITOFFSET_MASK)); -} - -/** - * @brief Get the output buffer state for the selected DAC channel. - * @rmtoll CR BOFF1 LL_DAC_GetOutputBuffer\n - * CR BOFF2 LL_DAC_GetOutputBuffer - * @param DACx DAC instance - * @param DAC_Channel This parameter can be one of the following values: - * @arg @ref LL_DAC_CHANNEL_1 - * @arg @ref LL_DAC_CHANNEL_2 - * @retval Returned value can be one of the following values: - * @arg @ref LL_DAC_OUTPUT_BUFFER_ENABLE - * @arg @ref LL_DAC_OUTPUT_BUFFER_DISABLE - */ -__STATIC_INLINE uint32_t LL_DAC_GetOutputBuffer(DAC_TypeDef *DACx, uint32_t DAC_Channel) -{ - return (uint32_t)(READ_BIT(DACx->CR, DAC_CR_BOFF1 << (DAC_Channel & DAC_CR_CHX_BITOFFSET_MASK)) - >> (DAC_Channel & DAC_CR_CHX_BITOFFSET_MASK) - ); -} - -/** - * @} - */ - -/** @defgroup DAC_LL_EF_DMA_Management DMA Management - * @{ - */ - -/** - * @brief Enable DAC DMA transfer request of the selected channel. - * @note To configure DMA source address (peripheral address), - * use function @ref LL_DAC_DMA_GetRegAddr(). - * @rmtoll CR DMAEN1 LL_DAC_EnableDMAReq\n - * CR DMAEN2 LL_DAC_EnableDMAReq - * @param DACx DAC instance - * @param DAC_Channel This parameter can be one of the following values: - * @arg @ref LL_DAC_CHANNEL_1 - * @arg @ref LL_DAC_CHANNEL_2 - * @retval None - */ -__STATIC_INLINE void LL_DAC_EnableDMAReq(DAC_TypeDef *DACx, uint32_t DAC_Channel) -{ - SET_BIT(DACx->CR, - DAC_CR_DMAEN1 << (DAC_Channel & DAC_CR_CHX_BITOFFSET_MASK)); -} - -/** - * @brief Disable DAC DMA transfer request of the selected channel. - * @note To configure DMA source address (peripheral address), - * use function @ref LL_DAC_DMA_GetRegAddr(). - * @rmtoll CR DMAEN1 LL_DAC_DisableDMAReq\n - * CR DMAEN2 LL_DAC_DisableDMAReq - * @param DACx DAC instance - * @param DAC_Channel This parameter can be one of the following values: - * @arg @ref LL_DAC_CHANNEL_1 - * @arg @ref LL_DAC_CHANNEL_2 - * @retval None - */ -__STATIC_INLINE void LL_DAC_DisableDMAReq(DAC_TypeDef *DACx, uint32_t DAC_Channel) -{ - CLEAR_BIT(DACx->CR, - DAC_CR_DMAEN1 << (DAC_Channel & DAC_CR_CHX_BITOFFSET_MASK)); -} - -/** - * @brief Get DAC DMA transfer request state of the selected channel. - * (0: DAC DMA transfer request is disabled, 1: DAC DMA transfer request is enabled) - * @rmtoll CR DMAEN1 LL_DAC_IsDMAReqEnabled\n - * CR DMAEN2 LL_DAC_IsDMAReqEnabled - * @param DACx DAC instance - * @param DAC_Channel This parameter can be one of the following values: - * @arg @ref LL_DAC_CHANNEL_1 - * @arg @ref LL_DAC_CHANNEL_2 - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_DAC_IsDMAReqEnabled(DAC_TypeDef *DACx, uint32_t DAC_Channel) -{ - return (READ_BIT(DACx->CR, - DAC_CR_DMAEN1 << (DAC_Channel & DAC_CR_CHX_BITOFFSET_MASK)) - == (DAC_CR_DMAEN1 << (DAC_Channel & DAC_CR_CHX_BITOFFSET_MASK))); -} - -/** - * @brief Function to help to configure DMA transfer to DAC: retrieve the - * DAC register address from DAC instance and a list of DAC registers - * intended to be used (most commonly) with DMA transfer. - * @note These DAC registers are data holding registers: - * when DAC conversion is requested, DAC generates a DMA transfer - * request to have data available in DAC data holding registers. - * @note This macro is intended to be used with LL DMA driver, refer to - * function "LL_DMA_ConfigAddresses()". - * Example: - * LL_DMA_ConfigAddresses(DMA1, - * LL_DMA_CHANNEL_1, - * (uint32_t)&< array or variable >, - * LL_DAC_DMA_GetRegAddr(DAC1, LL_DAC_CHANNEL_1, LL_DAC_DMA_REG_DATA_12BITS_RIGHT_ALIGNED), - * LL_DMA_DIRECTION_MEMORY_TO_PERIPH); - * @rmtoll DHR12R1 DACC1DHR LL_DAC_DMA_GetRegAddr\n - * DHR12L1 DACC1DHR LL_DAC_DMA_GetRegAddr\n - * DHR8R1 DACC1DHR LL_DAC_DMA_GetRegAddr\n - * DHR12R2 DACC2DHR LL_DAC_DMA_GetRegAddr\n - * DHR12L2 DACC2DHR LL_DAC_DMA_GetRegAddr\n - * DHR8R2 DACC2DHR LL_DAC_DMA_GetRegAddr - * @param DACx DAC instance - * @param DAC_Channel This parameter can be one of the following values: - * @arg @ref LL_DAC_CHANNEL_1 - * @arg @ref LL_DAC_CHANNEL_2 - * @param Register This parameter can be one of the following values: - * @arg @ref LL_DAC_DMA_REG_DATA_12BITS_RIGHT_ALIGNED - * @arg @ref LL_DAC_DMA_REG_DATA_12BITS_LEFT_ALIGNED - * @arg @ref LL_DAC_DMA_REG_DATA_8BITS_RIGHT_ALIGNED - * @retval DAC register address - */ -__STATIC_INLINE uint32_t LL_DAC_DMA_GetRegAddr(DAC_TypeDef *DACx, uint32_t DAC_Channel, uint32_t Register) -{ - /* Retrieve address of register DHR12Rx, DHR12Lx or DHR8Rx depending on */ - /* DAC channel selected. */ - return ((uint32_t)(__DAC_PTR_REG_OFFSET((DACx)->DHR12R1, __DAC_MASK_SHIFT(DAC_Channel, Register)))); -} -/** - * @} - */ - -/** @defgroup DAC_LL_EF_Operation Operation on DAC channels - * @{ - */ - -/** - * @brief Enable DAC selected channel. - * @rmtoll CR EN1 LL_DAC_Enable\n - * CR EN2 LL_DAC_Enable - * @note After enable from off state, DAC channel requires a delay - * for output voltage to reach accuracy +/- 1 LSB. - * Refer to device datasheet, parameter "tWAKEUP". - * @param DACx DAC instance - * @param DAC_Channel This parameter can be one of the following values: - * @arg @ref LL_DAC_CHANNEL_1 - * @arg @ref LL_DAC_CHANNEL_2 - * @retval None - */ -__STATIC_INLINE void LL_DAC_Enable(DAC_TypeDef *DACx, uint32_t DAC_Channel) -{ - SET_BIT(DACx->CR, - DAC_CR_EN1 << (DAC_Channel & DAC_CR_CHX_BITOFFSET_MASK)); -} - -/** - * @brief Disable DAC selected channel. - * @rmtoll CR EN1 LL_DAC_Disable\n - * CR EN2 LL_DAC_Disable - * @param DACx DAC instance - * @param DAC_Channel This parameter can be one of the following values: - * @arg @ref LL_DAC_CHANNEL_1 - * @arg @ref LL_DAC_CHANNEL_2 - * @retval None - */ -__STATIC_INLINE void LL_DAC_Disable(DAC_TypeDef *DACx, uint32_t DAC_Channel) -{ - CLEAR_BIT(DACx->CR, - DAC_CR_EN1 << (DAC_Channel & DAC_CR_CHX_BITOFFSET_MASK)); -} - -/** - * @brief Get DAC enable state of the selected channel. - * (0: DAC channel is disabled, 1: DAC channel is enabled) - * @rmtoll CR EN1 LL_DAC_IsEnabled\n - * CR EN2 LL_DAC_IsEnabled - * @param DACx DAC instance - * @param DAC_Channel This parameter can be one of the following values: - * @arg @ref LL_DAC_CHANNEL_1 - * @arg @ref LL_DAC_CHANNEL_2 - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_DAC_IsEnabled(DAC_TypeDef *DACx, uint32_t DAC_Channel) -{ - return (READ_BIT(DACx->CR, - DAC_CR_EN1 << (DAC_Channel & DAC_CR_CHX_BITOFFSET_MASK)) - == (DAC_CR_EN1 << (DAC_Channel & DAC_CR_CHX_BITOFFSET_MASK))); -} - -/** - * @brief Enable DAC trigger of the selected channel. - * @note - If DAC trigger is disabled, DAC conversion is performed - * automatically once the data holding register is updated, - * using functions "LL_DAC_ConvertData{8; 12}{Right; Left} Aligned()": - * @ref LL_DAC_ConvertData12RightAligned(), ... - * - If DAC trigger is enabled, DAC conversion is performed - * only when a hardware of software trigger event is occurring. - * Select trigger source using - * function @ref LL_DAC_SetTriggerSource(). - * @rmtoll CR TEN1 LL_DAC_EnableTrigger\n - * CR TEN2 LL_DAC_EnableTrigger - * @param DACx DAC instance - * @param DAC_Channel This parameter can be one of the following values: - * @arg @ref LL_DAC_CHANNEL_1 - * @arg @ref LL_DAC_CHANNEL_2 - * @retval None - */ -__STATIC_INLINE void LL_DAC_EnableTrigger(DAC_TypeDef *DACx, uint32_t DAC_Channel) -{ - SET_BIT(DACx->CR, - DAC_CR_TEN1 << (DAC_Channel & DAC_CR_CHX_BITOFFSET_MASK)); -} - -/** - * @brief Disable DAC trigger of the selected channel. - * @rmtoll CR TEN1 LL_DAC_DisableTrigger\n - * CR TEN2 LL_DAC_DisableTrigger - * @param DACx DAC instance - * @param DAC_Channel This parameter can be one of the following values: - * @arg @ref LL_DAC_CHANNEL_1 - * @arg @ref LL_DAC_CHANNEL_2 - * @retval None - */ -__STATIC_INLINE void LL_DAC_DisableTrigger(DAC_TypeDef *DACx, uint32_t DAC_Channel) -{ - CLEAR_BIT(DACx->CR, - DAC_CR_TEN1 << (DAC_Channel & DAC_CR_CHX_BITOFFSET_MASK)); -} - -/** - * @brief Get DAC trigger state of the selected channel. - * (0: DAC trigger is disabled, 1: DAC trigger is enabled) - * @rmtoll CR TEN1 LL_DAC_IsTriggerEnabled\n - * CR TEN2 LL_DAC_IsTriggerEnabled - * @param DACx DAC instance - * @param DAC_Channel This parameter can be one of the following values: - * @arg @ref LL_DAC_CHANNEL_1 - * @arg @ref LL_DAC_CHANNEL_2 - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_DAC_IsTriggerEnabled(DAC_TypeDef *DACx, uint32_t DAC_Channel) -{ - return (READ_BIT(DACx->CR, - DAC_CR_TEN1 << (DAC_Channel & DAC_CR_CHX_BITOFFSET_MASK)) - == (DAC_CR_TEN1 << (DAC_Channel & DAC_CR_CHX_BITOFFSET_MASK))); -} - -/** - * @brief Trig DAC conversion by software for the selected DAC channel. - * @note Preliminarily, DAC trigger must be set to software trigger - * using function @ref LL_DAC_SetTriggerSource() - * with parameter "LL_DAC_TRIGGER_SOFTWARE". - * and DAC trigger must be enabled using - * function @ref LL_DAC_EnableTrigger(). - * @note For devices featuring DAC with 2 channels: this function - * can perform a SW start of both DAC channels simultaneously. - * Two channels can be selected as parameter. - * Example: (LL_DAC_CHANNEL_1 | LL_DAC_CHANNEL_2) - * @rmtoll SWTRIGR SWTRIG1 LL_DAC_TrigSWConversion\n - * SWTRIGR SWTRIG2 LL_DAC_TrigSWConversion - * @param DACx DAC instance - * @param DAC_Channel This parameter can a combination of the following values: - * @arg @ref LL_DAC_CHANNEL_1 - * @arg @ref LL_DAC_CHANNEL_2 - * @retval None - */ -__STATIC_INLINE void LL_DAC_TrigSWConversion(DAC_TypeDef *DACx, uint32_t DAC_Channel) -{ - SET_BIT(DACx->SWTRIGR, - (DAC_Channel & DAC_SWTR_CHX_MASK)); -} - -/** - * @brief Set the data to be loaded in the data holding register - * in format 12 bits left alignment (LSB aligned on bit 0), - * for the selected DAC channel. - * @rmtoll DHR12R1 DACC1DHR LL_DAC_ConvertData12RightAligned\n - * DHR12R2 DACC2DHR LL_DAC_ConvertData12RightAligned - * @param DACx DAC instance - * @param DAC_Channel This parameter can be one of the following values: - * @arg @ref LL_DAC_CHANNEL_1 - * @arg @ref LL_DAC_CHANNEL_2 - * @param Data Value between Min_Data=0x000 and Max_Data=0xFFF - * @retval None - */ -__STATIC_INLINE void LL_DAC_ConvertData12RightAligned(DAC_TypeDef *DACx, uint32_t DAC_Channel, uint32_t Data) -{ - register uint32_t *preg = __DAC_PTR_REG_OFFSET(DACx->DHR12R1, __DAC_MASK_SHIFT(DAC_Channel, DAC_REG_DHR12RX_REGOFFSET_MASK)); - - MODIFY_REG(*preg, - DAC_DHR12R1_DACC1DHR, - Data); -} - -/** - * @brief Set the data to be loaded in the data holding register - * in format 12 bits left alignment (MSB aligned on bit 15), - * for the selected DAC channel. - * @rmtoll DHR12L1 DACC1DHR LL_DAC_ConvertData12LeftAligned\n - * DHR12L2 DACC2DHR LL_DAC_ConvertData12LeftAligned - * @param DACx DAC instance - * @param DAC_Channel This parameter can be one of the following values: - * @arg @ref LL_DAC_CHANNEL_1 - * @arg @ref LL_DAC_CHANNEL_2 - * @param Data Value between Min_Data=0x000 and Max_Data=0xFFF - * @retval None - */ -__STATIC_INLINE void LL_DAC_ConvertData12LeftAligned(DAC_TypeDef *DACx, uint32_t DAC_Channel, uint32_t Data) -{ - register uint32_t *preg = __DAC_PTR_REG_OFFSET(DACx->DHR12R1, __DAC_MASK_SHIFT(DAC_Channel, DAC_REG_DHR12LX_REGOFFSET_MASK)); - - MODIFY_REG(*preg, - DAC_DHR12L1_DACC1DHR, - Data); -} - -/** - * @brief Set the data to be loaded in the data holding register - * in format 8 bits left alignment (LSB aligned on bit 0), - * for the selected DAC channel. - * @rmtoll DHR8R1 DACC1DHR LL_DAC_ConvertData8RightAligned\n - * DHR8R2 DACC2DHR LL_DAC_ConvertData8RightAligned - * @param DACx DAC instance - * @param DAC_Channel This parameter can be one of the following values: - * @arg @ref LL_DAC_CHANNEL_1 - * @arg @ref LL_DAC_CHANNEL_2 - * @param Data Value between Min_Data=0x00 and Max_Data=0xFF - * @retval None - */ -__STATIC_INLINE void LL_DAC_ConvertData8RightAligned(DAC_TypeDef *DACx, uint32_t DAC_Channel, uint32_t Data) -{ - register uint32_t *preg = __DAC_PTR_REG_OFFSET(DACx->DHR12R1, __DAC_MASK_SHIFT(DAC_Channel, DAC_REG_DHR8RX_REGOFFSET_MASK)); - - MODIFY_REG(*preg, - DAC_DHR8R1_DACC1DHR, - Data); -} - -/** - * @brief Set the data to be loaded in the data holding register - * in format 12 bits left alignment (LSB aligned on bit 0), - * for both DAC channels. - * @rmtoll DHR12RD DACC1DHR LL_DAC_ConvertDualData12RightAligned\n - * DHR12RD DACC2DHR LL_DAC_ConvertDualData12RightAligned - * @param DACx DAC instance - * @param DataChannel1 Value between Min_Data=0x000 and Max_Data=0xFFF - * @param DataChannel2 Value between Min_Data=0x000 and Max_Data=0xFFF - * @retval None - */ -__STATIC_INLINE void LL_DAC_ConvertDualData12RightAligned(DAC_TypeDef *DACx, uint32_t DataChannel1, uint32_t DataChannel2) -{ - MODIFY_REG(DACx->DHR12RD, - (DAC_DHR12RD_DACC2DHR | DAC_DHR12RD_DACC1DHR), - ((DataChannel2 << DAC_DHR12RD_DACC2DHR_BITOFFSET_POS) | DataChannel1)); -} - -/** - * @brief Set the data to be loaded in the data holding register - * in format 12 bits left alignment (MSB aligned on bit 15), - * for both DAC channels. - * @rmtoll DHR12LD DACC1DHR LL_DAC_ConvertDualData12LeftAligned\n - * DHR12LD DACC2DHR LL_DAC_ConvertDualData12LeftAligned - * @param DACx DAC instance - * @param DataChannel1 Value between Min_Data=0x000 and Max_Data=0xFFF - * @param DataChannel2 Value between Min_Data=0x000 and Max_Data=0xFFF - * @retval None - */ -__STATIC_INLINE void LL_DAC_ConvertDualData12LeftAligned(DAC_TypeDef *DACx, uint32_t DataChannel1, uint32_t DataChannel2) -{ - /* Note: Data of DAC channel 2 shift value subtracted of 4 because */ - /* data on 16 bits and DAC channel 2 bits field is on the 12 MSB, */ - /* the 4 LSB must be taken into account for the shift value. */ - MODIFY_REG(DACx->DHR12LD, - (DAC_DHR12LD_DACC2DHR | DAC_DHR12LD_DACC1DHR), - ((DataChannel2 << (DAC_DHR12LD_DACC2DHR_BITOFFSET_POS - 4U)) | DataChannel1)); -} - -/** - * @brief Set the data to be loaded in the data holding register - * in format 8 bits left alignment (LSB aligned on bit 0), - * for both DAC channels. - * @rmtoll DHR8RD DACC1DHR LL_DAC_ConvertDualData8RightAligned\n - * DHR8RD DACC2DHR LL_DAC_ConvertDualData8RightAligned - * @param DACx DAC instance - * @param DataChannel1 Value between Min_Data=0x00 and Max_Data=0xFF - * @param DataChannel2 Value between Min_Data=0x00 and Max_Data=0xFF - * @retval None - */ -__STATIC_INLINE void LL_DAC_ConvertDualData8RightAligned(DAC_TypeDef *DACx, uint32_t DataChannel1, uint32_t DataChannel2) -{ - MODIFY_REG(DACx->DHR8RD, - (DAC_DHR8RD_DACC2DHR | DAC_DHR8RD_DACC1DHR), - ((DataChannel2 << DAC_DHR8RD_DACC2DHR_BITOFFSET_POS) | DataChannel1)); -} - -/** - * @brief Retrieve output data currently generated for the selected DAC channel. - * @note Whatever alignment and resolution settings - * (using functions "LL_DAC_ConvertData{8; 12}{Right; Left} Aligned()": - * @ref LL_DAC_ConvertData12RightAligned(), ...), - * output data format is 12 bits right aligned (LSB aligned on bit 0). - * @rmtoll DOR1 DACC1DOR LL_DAC_RetrieveOutputData\n - * DOR2 DACC2DOR LL_DAC_RetrieveOutputData - * @param DACx DAC instance - * @param DAC_Channel This parameter can be one of the following values: - * @arg @ref LL_DAC_CHANNEL_1 - * @arg @ref LL_DAC_CHANNEL_2 - * @retval Value between Min_Data=0x000 and Max_Data=0xFFF - */ -__STATIC_INLINE uint32_t LL_DAC_RetrieveOutputData(DAC_TypeDef *DACx, uint32_t DAC_Channel) -{ - register uint32_t *preg = __DAC_PTR_REG_OFFSET(DACx->DOR1, __DAC_MASK_SHIFT(DAC_Channel, DAC_REG_DORX_REGOFFSET_MASK)); - - return (uint16_t) READ_BIT(*preg, DAC_DOR1_DACC1DOR); -} - -/** - * @} - */ - -/** @defgroup DAC_LL_EF_FLAG_Management FLAG Management - * @{ - */ -#if defined(DAC_SR_DMAUDR1) -/** - * @brief Get DAC underrun flag for DAC channel 1 - * @rmtoll SR DMAUDR1 LL_DAC_IsActiveFlag_DMAUDR1 - * @param DACx DAC instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_DAC_IsActiveFlag_DMAUDR1(DAC_TypeDef *DACx) -{ - return (READ_BIT(DACx->SR, LL_DAC_FLAG_DMAUDR1) == (LL_DAC_FLAG_DMAUDR1)); -} -#endif /* DAC_SR_DMAUDR1 */ - -#if defined(DAC_SR_DMAUDR2) -/** - * @brief Get DAC underrun flag for DAC channel 2 - * @rmtoll SR DMAUDR2 LL_DAC_IsActiveFlag_DMAUDR2 - * @param DACx DAC instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_DAC_IsActiveFlag_DMAUDR2(DAC_TypeDef *DACx) -{ - return (READ_BIT(DACx->SR, LL_DAC_FLAG_DMAUDR2) == (LL_DAC_FLAG_DMAUDR2)); -} -#endif /* DAC_SR_DMAUDR2 */ - -#if defined(DAC_SR_DMAUDR1) -/** - * @brief Clear DAC underrun flag for DAC channel 1 - * @rmtoll SR DMAUDR1 LL_DAC_ClearFlag_DMAUDR1 - * @param DACx DAC instance - * @retval None - */ -__STATIC_INLINE void LL_DAC_ClearFlag_DMAUDR1(DAC_TypeDef *DACx) -{ - WRITE_REG(DACx->SR, LL_DAC_FLAG_DMAUDR1); -} -#endif /* DAC_SR_DMAUDR1 */ - -#if defined(DAC_SR_DMAUDR2) -/** - * @brief Clear DAC underrun flag for DAC channel 2 - * @rmtoll SR DMAUDR2 LL_DAC_ClearFlag_DMAUDR2 - * @param DACx DAC instance - * @retval None - */ -__STATIC_INLINE void LL_DAC_ClearFlag_DMAUDR2(DAC_TypeDef *DACx) -{ - WRITE_REG(DACx->SR, LL_DAC_FLAG_DMAUDR2); -} -#endif /* DAC_SR_DMAUDR2 */ - -/** - * @} - */ -/** @defgroup DAC_LL_EF_IT_Management IT management - * @{ - */ - -#if defined(DAC_CR_DMAUDRIE1) -/** - * @brief Enable DMA underrun interrupt for DAC channel 1 - * @rmtoll CR DMAUDRIE1 LL_DAC_EnableIT_DMAUDR1 - * @param DACx DAC instance - * @retval None - */ -__STATIC_INLINE void LL_DAC_EnableIT_DMAUDR1(DAC_TypeDef *DACx) -{ - SET_BIT(DACx->CR, LL_DAC_IT_DMAUDRIE1); -} -#endif /* DAC_CR_DMAUDRIE1 */ - -#if defined(DAC_CR_DMAUDRIE2) -/** - * @brief Enable DMA underrun interrupt for DAC channel 2 - * @rmtoll CR DMAUDRIE2 LL_DAC_EnableIT_DMAUDR2 - * @param DACx DAC instance - * @retval None - */ -__STATIC_INLINE void LL_DAC_EnableIT_DMAUDR2(DAC_TypeDef *DACx) -{ - SET_BIT(DACx->CR, LL_DAC_IT_DMAUDRIE2); -} -#endif /* DAC_CR_DMAUDRIE2 */ - -#if defined(DAC_CR_DMAUDRIE1) -/** - * @brief Disable DMA underrun interrupt for DAC channel 1 - * @rmtoll CR DMAUDRIE1 LL_DAC_DisableIT_DMAUDR1 - * @param DACx DAC instance - * @retval None - */ -__STATIC_INLINE void LL_DAC_DisableIT_DMAUDR1(DAC_TypeDef *DACx) -{ - CLEAR_BIT(DACx->CR, LL_DAC_IT_DMAUDRIE1); -} -#endif /* DAC_CR_DMAUDRIE1 */ - -#if defined(DAC_CR_DMAUDRIE2) -/** - * @brief Disable DMA underrun interrupt for DAC channel 2 - * @rmtoll CR DMAUDRIE2 LL_DAC_DisableIT_DMAUDR2 - * @param DACx DAC instance - * @retval None - */ -__STATIC_INLINE void LL_DAC_DisableIT_DMAUDR2(DAC_TypeDef *DACx) -{ - CLEAR_BIT(DACx->CR, LL_DAC_IT_DMAUDRIE2); -} -#endif /* DAC_CR_DMAUDRIE2 */ - -#if defined(DAC_CR_DMAUDRIE1) -/** - * @brief Get DMA underrun interrupt for DAC channel 1 - * @rmtoll CR DMAUDRIE1 LL_DAC_IsEnabledIT_DMAUDR1 - * @param DACx DAC instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_DAC_IsEnabledIT_DMAUDR1(DAC_TypeDef *DACx) -{ - return (READ_BIT(DACx->CR, LL_DAC_IT_DMAUDRIE1) == (LL_DAC_IT_DMAUDRIE1)); -} -#endif /* DAC_CR_DMAUDRIE1 */ - -#if defined(DAC_CR_DMAUDRIE2) -/** - * @brief Get DMA underrun interrupt for DAC channel 2 - * @rmtoll CR DMAUDRIE2 LL_DAC_IsEnabledIT_DMAUDR2 - * @param DACx DAC instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_DAC_IsEnabledIT_DMAUDR2(DAC_TypeDef *DACx) -{ - return (READ_BIT(DACx->CR, LL_DAC_IT_DMAUDRIE2) == (LL_DAC_IT_DMAUDRIE2)); -} -#endif /* DAC_CR_DMAUDRIE2 */ - -/** - * @} - */ - -#if defined(USE_FULL_LL_DRIVER) -/** @defgroup DAC_LL_EF_Init Initialization and de-initialization functions - * @{ - */ - -ErrorStatus LL_DAC_DeInit(DAC_TypeDef* DACx); -ErrorStatus LL_DAC_Init(DAC_TypeDef* DACx, uint32_t DAC_Channel, LL_DAC_InitTypeDef* DAC_InitStruct); -void LL_DAC_StructInit(LL_DAC_InitTypeDef* DAC_InitStruct); - -/** - * @} - */ -#endif /* USE_FULL_LL_DRIVER */ - -/** - * @} - */ - -/** - * @} - */ - -#endif /* DAC */ - -/** - * @} - */ - -#ifdef __cplusplus -} -#endif - -#endif /* __STM32F1xx_LL_DAC_H */ - -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_dma.c b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_dma.c deleted file mode 100644 index d90bfa04f01..00000000000 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_dma.c +++ /dev/null @@ -1,331 +0,0 @@ -/** - ****************************************************************************** - * @file stm32f1xx_ll_dma.c - * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 - * @brief DMA LL module driver. - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2016 STMicroelectronics

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ -#if defined(USE_FULL_LL_DRIVER) - -/* Includes ------------------------------------------------------------------*/ -#include "stm32f1xx_ll_dma.h" -#include "stm32f1xx_ll_bus.h" -#ifdef USE_FULL_ASSERT -#include "stm32_assert.h" -#else -#define assert_param(expr) ((void)0U) -#endif - -/** @addtogroup STM32F1xx_LL_Driver - * @{ - */ - -#if defined (DMA1) || defined (DMA2) - -/** @defgroup DMA_LL DMA - * @{ - */ - -/* Private types -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private constants ---------------------------------------------------------*/ -/* Private macros ------------------------------------------------------------*/ -/** @addtogroup DMA_LL_Private_Macros - * @{ - */ -#define IS_LL_DMA_DIRECTION(__VALUE__) (((__VALUE__) == LL_DMA_DIRECTION_PERIPH_TO_MEMORY) || \ - ((__VALUE__) == LL_DMA_DIRECTION_MEMORY_TO_PERIPH) || \ - ((__VALUE__) == LL_DMA_DIRECTION_MEMORY_TO_MEMORY)) - -#define IS_LL_DMA_MODE(__VALUE__) (((__VALUE__) == LL_DMA_MODE_NORMAL) || \ - ((__VALUE__) == LL_DMA_MODE_CIRCULAR)) - -#define IS_LL_DMA_PERIPHINCMODE(__VALUE__) (((__VALUE__) == LL_DMA_PERIPH_INCREMENT) || \ - ((__VALUE__) == LL_DMA_PERIPH_NOINCREMENT)) - -#define IS_LL_DMA_MEMORYINCMODE(__VALUE__) (((__VALUE__) == LL_DMA_MEMORY_INCREMENT) || \ - ((__VALUE__) == LL_DMA_MEMORY_NOINCREMENT)) - -#define IS_LL_DMA_PERIPHDATASIZE(__VALUE__) (((__VALUE__) == LL_DMA_PDATAALIGN_BYTE) || \ - ((__VALUE__) == LL_DMA_PDATAALIGN_HALFWORD) || \ - ((__VALUE__) == LL_DMA_PDATAALIGN_WORD)) - -#define IS_LL_DMA_MEMORYDATASIZE(__VALUE__) (((__VALUE__) == LL_DMA_MDATAALIGN_BYTE) || \ - ((__VALUE__) == LL_DMA_MDATAALIGN_HALFWORD) || \ - ((__VALUE__) == LL_DMA_MDATAALIGN_WORD)) - -#define IS_LL_DMA_NBDATA(__VALUE__) ((__VALUE__) <= 0x0000FFFFU) - -#define IS_LL_DMA_PRIORITY(__VALUE__) (((__VALUE__) == LL_DMA_PRIORITY_LOW) || \ - ((__VALUE__) == LL_DMA_PRIORITY_MEDIUM) || \ - ((__VALUE__) == LL_DMA_PRIORITY_HIGH) || \ - ((__VALUE__) == LL_DMA_PRIORITY_VERYHIGH)) - -#if defined (DMA2) -#define IS_LL_DMA_ALL_CHANNEL_INSTANCE(INSTANCE, CHANNEL) ((((INSTANCE) == DMA1) && \ - (((CHANNEL) == LL_DMA_CHANNEL_1) || \ - ((CHANNEL) == LL_DMA_CHANNEL_2) || \ - ((CHANNEL) == LL_DMA_CHANNEL_3) || \ - ((CHANNEL) == LL_DMA_CHANNEL_4) || \ - ((CHANNEL) == LL_DMA_CHANNEL_5) || \ - ((CHANNEL) == LL_DMA_CHANNEL_6) || \ - ((CHANNEL) == LL_DMA_CHANNEL_7))) || \ - (((INSTANCE) == DMA2) && \ - (((CHANNEL) == LL_DMA_CHANNEL_1) || \ - ((CHANNEL) == LL_DMA_CHANNEL_2) || \ - ((CHANNEL) == LL_DMA_CHANNEL_3) || \ - ((CHANNEL) == LL_DMA_CHANNEL_4) || \ - ((CHANNEL) == LL_DMA_CHANNEL_5)))) -#else -#define IS_LL_DMA_ALL_CHANNEL_INSTANCE(INSTANCE, CHANNEL) ((((INSTANCE) == DMA1) && \ - (((CHANNEL) == LL_DMA_CHANNEL_1) || \ - ((CHANNEL) == LL_DMA_CHANNEL_2) || \ - ((CHANNEL) == LL_DMA_CHANNEL_3) || \ - ((CHANNEL) == LL_DMA_CHANNEL_4) || \ - ((CHANNEL) == LL_DMA_CHANNEL_5) || \ - ((CHANNEL) == LL_DMA_CHANNEL_6) || \ - ((CHANNEL) == LL_DMA_CHANNEL_7)))) -#endif -/** - * @} - */ - -/* Private function prototypes -----------------------------------------------*/ -/* Exported functions --------------------------------------------------------*/ -/** @addtogroup DMA_LL_Exported_Functions - * @{ - */ - -/** @addtogroup DMA_LL_EF_Init - * @{ - */ - -/** - * @brief De-initialize the DMA registers to their default reset values. - * @param DMAx DMAx Instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_DMA_CHANNEL_1 - * @arg @ref LL_DMA_CHANNEL_2 - * @arg @ref LL_DMA_CHANNEL_3 - * @arg @ref LL_DMA_CHANNEL_4 - * @arg @ref LL_DMA_CHANNEL_5 - * @arg @ref LL_DMA_CHANNEL_6 - * @arg @ref LL_DMA_CHANNEL_7 - * @retval An ErrorStatus enumeration value: - * - SUCCESS: DMA registers are de-initialized - * - ERROR: DMA registers are not de-initialized - */ -uint32_t LL_DMA_DeInit(DMA_TypeDef *DMAx, uint32_t Channel) -{ - DMA_Channel_TypeDef *tmp = (DMA_Channel_TypeDef *)DMA1_Channel1; - ErrorStatus status = SUCCESS; - - /* Check the DMA Instance DMAx and Channel parameters*/ - assert_param(IS_LL_DMA_ALL_CHANNEL_INSTANCE(DMAx, Channel)); - - tmp = (DMA_Channel_TypeDef *)(__LL_DMA_GET_CHANNEL_INSTANCE(DMAx, Channel)); - - /* Disable the selected DMAx_Channely */ - CLEAR_BIT(tmp->CCR, DMA_CCR_EN); - - /* Reset DMAx_Channely control register */ - LL_DMA_WriteReg(tmp, CCR, 0U); - - /* Reset DMAx_Channely remaining bytes register */ - LL_DMA_WriteReg(tmp, CNDTR, 0U); - - /* Reset DMAx_Channely peripheral address register */ - LL_DMA_WriteReg(tmp, CPAR, 0U); - - /* Reset DMAx_Channely memory address register */ - LL_DMA_WriteReg(tmp, CMAR, 0U); - - if (Channel == LL_DMA_CHANNEL_1) - { - /* Reset interrupt pending bits for DMAx Channel1 */ - LL_DMA_ClearFlag_GI1(DMAx); - } - else if (Channel == LL_DMA_CHANNEL_2) - { - /* Reset interrupt pending bits for DMAx Channel2 */ - LL_DMA_ClearFlag_GI2(DMAx); - } - else if (Channel == LL_DMA_CHANNEL_3) - { - /* Reset interrupt pending bits for DMAx Channel3 */ - LL_DMA_ClearFlag_GI3(DMAx); - } - else if (Channel == LL_DMA_CHANNEL_4) - { - /* Reset interrupt pending bits for DMAx Channel4 */ - LL_DMA_ClearFlag_GI4(DMAx); - } - else if (Channel == LL_DMA_CHANNEL_5) - { - /* Reset interrupt pending bits for DMAx Channel5 */ - LL_DMA_ClearFlag_GI5(DMAx); - } - - else if (Channel == LL_DMA_CHANNEL_6) - { - /* Reset interrupt pending bits for DMAx Channel6 */ - LL_DMA_ClearFlag_GI6(DMAx); - } - else if (Channel == LL_DMA_CHANNEL_7) - { - /* Reset interrupt pending bits for DMAx Channel7 */ - LL_DMA_ClearFlag_GI7(DMAx); - } - else - { - status = ERROR; - } - - return status; -} - -/** - * @brief Initialize the DMA registers according to the specified parameters in DMA_InitStruct. - * @note To convert DMAx_Channely Instance to DMAx Instance and Channely, use helper macros : - * @arg @ref __LL_DMA_GET_INSTANCE - * @arg @ref __LL_DMA_GET_CHANNEL - * @param DMAx DMAx Instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_DMA_CHANNEL_1 - * @arg @ref LL_DMA_CHANNEL_2 - * @arg @ref LL_DMA_CHANNEL_3 - * @arg @ref LL_DMA_CHANNEL_4 - * @arg @ref LL_DMA_CHANNEL_5 - * @arg @ref LL_DMA_CHANNEL_6 - * @arg @ref LL_DMA_CHANNEL_7 - * @param DMA_InitStruct pointer to a @ref LL_DMA_InitTypeDef structure. - * @retval An ErrorStatus enumeration value: - * - SUCCESS: DMA registers are initialized - * - ERROR: Not applicable - */ -uint32_t LL_DMA_Init(DMA_TypeDef *DMAx, uint32_t Channel, LL_DMA_InitTypeDef *DMA_InitStruct) -{ - /* Check the DMA Instance DMAx and Channel parameters*/ - assert_param(IS_LL_DMA_ALL_CHANNEL_INSTANCE(DMAx, Channel)); - - /* Check the DMA parameters from DMA_InitStruct */ - assert_param(IS_LL_DMA_DIRECTION(DMA_InitStruct->Direction)); - assert_param(IS_LL_DMA_MODE(DMA_InitStruct->Mode)); - assert_param(IS_LL_DMA_PERIPHINCMODE(DMA_InitStruct->PeriphOrM2MSrcIncMode)); - assert_param(IS_LL_DMA_MEMORYINCMODE(DMA_InitStruct->MemoryOrM2MDstIncMode)); - assert_param(IS_LL_DMA_PERIPHDATASIZE(DMA_InitStruct->PeriphOrM2MSrcDataSize)); - assert_param(IS_LL_DMA_MEMORYDATASIZE(DMA_InitStruct->MemoryOrM2MDstDataSize)); - assert_param(IS_LL_DMA_NBDATA(DMA_InitStruct->NbData)); - assert_param(IS_LL_DMA_PRIORITY(DMA_InitStruct->Priority)); - - /*---------------------------- DMAx CCR Configuration ------------------------ - * Configure DMAx_Channely: data transfer direction, data transfer mode, - * peripheral and memory increment mode, - * data size alignment and priority level with parameters : - * - Direction: DMA_CCR_DIR and DMA_CCR_MEM2MEM bits - * - Mode: DMA_CCR_CIRC bit - * - PeriphOrM2MSrcIncMode: DMA_CCR_PINC bit - * - MemoryOrM2MDstIncMode: DMA_CCR_MINC bit - * - PeriphOrM2MSrcDataSize: DMA_CCR_PSIZE[1:0] bits - * - MemoryOrM2MDstDataSize: DMA_CCR_MSIZE[1:0] bits - * - Priority: DMA_CCR_PL[1:0] bits - */ - LL_DMA_ConfigTransfer(DMAx, Channel, DMA_InitStruct->Direction | \ - DMA_InitStruct->Mode | \ - DMA_InitStruct->PeriphOrM2MSrcIncMode | \ - DMA_InitStruct->MemoryOrM2MDstIncMode | \ - DMA_InitStruct->PeriphOrM2MSrcDataSize | \ - DMA_InitStruct->MemoryOrM2MDstDataSize | \ - DMA_InitStruct->Priority); - - /*-------------------------- DMAx CMAR Configuration ------------------------- - * Configure the memory or destination base address with parameter : - * - MemoryOrM2MDstAddress: DMA_CMAR_MA[31:0] bits - */ - LL_DMA_SetMemoryAddress(DMAx, Channel, DMA_InitStruct->MemoryOrM2MDstAddress); - - /*-------------------------- DMAx CPAR Configuration ------------------------- - * Configure the peripheral or source base address with parameter : - * - PeriphOrM2MSrcAddress: DMA_CPAR_PA[31:0] bits - */ - LL_DMA_SetPeriphAddress(DMAx, Channel, DMA_InitStruct->PeriphOrM2MSrcAddress); - - /*--------------------------- DMAx CNDTR Configuration ----------------------- - * Configure the peripheral base address with parameter : - * - NbData: DMA_CNDTR_NDT[15:0] bits - */ - LL_DMA_SetDataLength(DMAx, Channel, DMA_InitStruct->NbData); - - return SUCCESS; -} - -/** - * @brief Set each @ref LL_DMA_InitTypeDef field to default value. - * @param DMA_InitStruct Pointer to a @ref LL_DMA_InitTypeDef structure. - * @retval None - */ -void LL_DMA_StructInit(LL_DMA_InitTypeDef *DMA_InitStruct) -{ - /* Set DMA_InitStruct fields to default values */ - DMA_InitStruct->PeriphOrM2MSrcAddress = 0x00000000U; - DMA_InitStruct->MemoryOrM2MDstAddress = 0x00000000U; - DMA_InitStruct->Direction = LL_DMA_DIRECTION_PERIPH_TO_MEMORY; - DMA_InitStruct->Mode = LL_DMA_MODE_NORMAL; - DMA_InitStruct->PeriphOrM2MSrcIncMode = LL_DMA_PERIPH_NOINCREMENT; - DMA_InitStruct->MemoryOrM2MDstIncMode = LL_DMA_MEMORY_NOINCREMENT; - DMA_InitStruct->PeriphOrM2MSrcDataSize = LL_DMA_PDATAALIGN_BYTE; - DMA_InitStruct->MemoryOrM2MDstDataSize = LL_DMA_MDATAALIGN_BYTE; - DMA_InitStruct->NbData = 0x00000000U; - DMA_InitStruct->Priority = LL_DMA_PRIORITY_LOW; -} - -/** - * @} - */ - -/** - * @} - */ - -/** - * @} - */ - -#endif /* DMA1 || DMA2 */ - -/** - * @} - */ - -#endif /* USE_FULL_LL_DRIVER */ - -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_dma.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_dma.h deleted file mode 100644 index fda0a074889..00000000000 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_dma.h +++ /dev/null @@ -1,1978 +0,0 @@ -/** - ****************************************************************************** - * @file stm32f1xx_ll_dma.h - * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 - * @brief Header file of DMA LL module. - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2016 STMicroelectronics

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ - -/* Define to prevent recursive inclusion -------------------------------------*/ -#ifndef __STM32F1xx_LL_DMA_H -#define __STM32F1xx_LL_DMA_H - -#ifdef __cplusplus -extern "C" { -#endif - -/* Includes ------------------------------------------------------------------*/ -#include "stm32f1xx.h" - -/** @addtogroup STM32F1xx_LL_Driver - * @{ - */ - -#if defined (DMA1) || defined (DMA2) - -/** @defgroup DMA_LL DMA - * @{ - */ - -/* Private types -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/** @defgroup DMA_LL_Private_Variables DMA Private Variables - * @{ - */ -/* Array used to get the DMA channel register offset versus channel index LL_DMA_CHANNEL_x */ -static const uint8_t CHANNEL_OFFSET_TAB[] = -{ - (uint8_t)(DMA1_Channel1_BASE - DMA1_BASE), - (uint8_t)(DMA1_Channel2_BASE - DMA1_BASE), - (uint8_t)(DMA1_Channel3_BASE - DMA1_BASE), - (uint8_t)(DMA1_Channel4_BASE - DMA1_BASE), - (uint8_t)(DMA1_Channel5_BASE - DMA1_BASE), - (uint8_t)(DMA1_Channel6_BASE - DMA1_BASE), - (uint8_t)(DMA1_Channel7_BASE - DMA1_BASE) -}; -/** - * @} - */ -/* Private constants ---------------------------------------------------------*/ -/* Private macros ------------------------------------------------------------*/ -#if defined(USE_FULL_LL_DRIVER) -/** @defgroup DMA_LL_Private_Macros DMA Private Macros - * @{ - */ -/** - * @} - */ -#endif /*USE_FULL_LL_DRIVER*/ - -/* Exported types ------------------------------------------------------------*/ -#if defined(USE_FULL_LL_DRIVER) -/** @defgroup DMA_LL_ES_INIT DMA Exported Init structure - * @{ - */ -typedef struct -{ - uint32_t PeriphOrM2MSrcAddress; /*!< Specifies the peripheral base address for DMA transfer - or as Source base address in case of memory to memory transfer direction. - - This parameter must be a value between Min_Data = 0 and Max_Data = 0xFFFFFFFF. */ - - uint32_t MemoryOrM2MDstAddress; /*!< Specifies the memory base address for DMA transfer - or as Destination base address in case of memory to memory transfer direction. - - This parameter must be a value between Min_Data = 0 and Max_Data = 0xFFFFFFFF. */ - - uint32_t Direction; /*!< Specifies if the data will be transferred from memory to peripheral, - from memory to memory or from peripheral to memory. - This parameter can be a value of @ref DMA_LL_EC_DIRECTION - - This feature can be modified afterwards using unitary function @ref LL_DMA_SetDataTransferDirection(). */ - - uint32_t Mode; /*!< Specifies the normal or circular operation mode. - This parameter can be a value of @ref DMA_LL_EC_MODE - @note: The circular buffer mode cannot be used if the memory to memory - data transfer direction is configured on the selected Channel - - This feature can be modified afterwards using unitary function @ref LL_DMA_SetMode(). */ - - uint32_t PeriphOrM2MSrcIncMode; /*!< Specifies whether the Peripheral address or Source address in case of memory to memory transfer direction - is incremented or not. - This parameter can be a value of @ref DMA_LL_EC_PERIPH - - This feature can be modified afterwards using unitary function @ref LL_DMA_SetPeriphIncMode(). */ - - uint32_t MemoryOrM2MDstIncMode; /*!< Specifies whether the Memory address or Destination address in case of memory to memory transfer direction - is incremented or not. - This parameter can be a value of @ref DMA_LL_EC_MEMORY - - This feature can be modified afterwards using unitary function @ref LL_DMA_SetMemoryIncMode(). */ - - uint32_t PeriphOrM2MSrcDataSize; /*!< Specifies the Peripheral data size alignment or Source data size alignment (byte, half word, word) - in case of memory to memory transfer direction. - This parameter can be a value of @ref DMA_LL_EC_PDATAALIGN - - This feature can be modified afterwards using unitary function @ref LL_DMA_SetPeriphSize(). */ - - uint32_t MemoryOrM2MDstDataSize; /*!< Specifies the Memory data size alignment or Destination data size alignment (byte, half word, word) - in case of memory to memory transfer direction. - This parameter can be a value of @ref DMA_LL_EC_MDATAALIGN - - This feature can be modified afterwards using unitary function @ref LL_DMA_SetMemorySize(). */ - - uint32_t NbData; /*!< Specifies the number of data to transfer, in data unit. - The data unit is equal to the source buffer configuration set in PeripheralSize - or MemorySize parameters depending in the transfer direction. - This parameter must be a value between Min_Data = 0 and Max_Data = 0x0000FFFF - - This feature can be modified afterwards using unitary function @ref LL_DMA_SetDataLength(). */ - - uint32_t Priority; /*!< Specifies the channel priority level. - This parameter can be a value of @ref DMA_LL_EC_PRIORITY - - This feature can be modified afterwards using unitary function @ref LL_DMA_SetChannelPriorityLevel(). */ - -} LL_DMA_InitTypeDef; -/** - * @} - */ -#endif /*USE_FULL_LL_DRIVER*/ - -/* Exported constants --------------------------------------------------------*/ -/** @defgroup DMA_LL_Exported_Constants DMA Exported Constants - * @{ - */ -/** @defgroup DMA_LL_EC_CLEAR_FLAG Clear Flags Defines - * @brief Flags defines which can be used with LL_DMA_WriteReg function - * @{ - */ -#define LL_DMA_IFCR_CGIF1 DMA_IFCR_CGIF1 /*!< Channel 1 global flag */ -#define LL_DMA_IFCR_CTCIF1 DMA_IFCR_CTCIF1 /*!< Channel 1 transfer complete flag */ -#define LL_DMA_IFCR_CHTIF1 DMA_IFCR_CHTIF1 /*!< Channel 1 half transfer flag */ -#define LL_DMA_IFCR_CTEIF1 DMA_IFCR_CTEIF1 /*!< Channel 1 transfer error flag */ -#define LL_DMA_IFCR_CGIF2 DMA_IFCR_CGIF2 /*!< Channel 2 global flag */ -#define LL_DMA_IFCR_CTCIF2 DMA_IFCR_CTCIF2 /*!< Channel 2 transfer complete flag */ -#define LL_DMA_IFCR_CHTIF2 DMA_IFCR_CHTIF2 /*!< Channel 2 half transfer flag */ -#define LL_DMA_IFCR_CTEIF2 DMA_IFCR_CTEIF2 /*!< Channel 2 transfer error flag */ -#define LL_DMA_IFCR_CGIF3 DMA_IFCR_CGIF3 /*!< Channel 3 global flag */ -#define LL_DMA_IFCR_CTCIF3 DMA_IFCR_CTCIF3 /*!< Channel 3 transfer complete flag */ -#define LL_DMA_IFCR_CHTIF3 DMA_IFCR_CHTIF3 /*!< Channel 3 half transfer flag */ -#define LL_DMA_IFCR_CTEIF3 DMA_IFCR_CTEIF3 /*!< Channel 3 transfer error flag */ -#define LL_DMA_IFCR_CGIF4 DMA_IFCR_CGIF4 /*!< Channel 4 global flag */ -#define LL_DMA_IFCR_CTCIF4 DMA_IFCR_CTCIF4 /*!< Channel 4 transfer complete flag */ -#define LL_DMA_IFCR_CHTIF4 DMA_IFCR_CHTIF4 /*!< Channel 4 half transfer flag */ -#define LL_DMA_IFCR_CTEIF4 DMA_IFCR_CTEIF4 /*!< Channel 4 transfer error flag */ -#define LL_DMA_IFCR_CGIF5 DMA_IFCR_CGIF5 /*!< Channel 5 global flag */ -#define LL_DMA_IFCR_CTCIF5 DMA_IFCR_CTCIF5 /*!< Channel 5 transfer complete flag */ -#define LL_DMA_IFCR_CHTIF5 DMA_IFCR_CHTIF5 /*!< Channel 5 half transfer flag */ -#define LL_DMA_IFCR_CTEIF5 DMA_IFCR_CTEIF5 /*!< Channel 5 transfer error flag */ -#define LL_DMA_IFCR_CGIF6 DMA_IFCR_CGIF6 /*!< Channel 6 global flag */ -#define LL_DMA_IFCR_CTCIF6 DMA_IFCR_CTCIF6 /*!< Channel 6 transfer complete flag */ -#define LL_DMA_IFCR_CHTIF6 DMA_IFCR_CHTIF6 /*!< Channel 6 half transfer flag */ -#define LL_DMA_IFCR_CTEIF6 DMA_IFCR_CTEIF6 /*!< Channel 6 transfer error flag */ -#define LL_DMA_IFCR_CGIF7 DMA_IFCR_CGIF7 /*!< Channel 7 global flag */ -#define LL_DMA_IFCR_CTCIF7 DMA_IFCR_CTCIF7 /*!< Channel 7 transfer complete flag */ -#define LL_DMA_IFCR_CHTIF7 DMA_IFCR_CHTIF7 /*!< Channel 7 half transfer flag */ -#define LL_DMA_IFCR_CTEIF7 DMA_IFCR_CTEIF7 /*!< Channel 7 transfer error flag */ -/** - * @} - */ - -/** @defgroup DMA_LL_EC_GET_FLAG Get Flags Defines - * @brief Flags defines which can be used with LL_DMA_ReadReg function - * @{ - */ -#define LL_DMA_ISR_GIF1 DMA_ISR_GIF1 /*!< Channel 1 global flag */ -#define LL_DMA_ISR_TCIF1 DMA_ISR_TCIF1 /*!< Channel 1 transfer complete flag */ -#define LL_DMA_ISR_HTIF1 DMA_ISR_HTIF1 /*!< Channel 1 half transfer flag */ -#define LL_DMA_ISR_TEIF1 DMA_ISR_TEIF1 /*!< Channel 1 transfer error flag */ -#define LL_DMA_ISR_GIF2 DMA_ISR_GIF2 /*!< Channel 2 global flag */ -#define LL_DMA_ISR_TCIF2 DMA_ISR_TCIF2 /*!< Channel 2 transfer complete flag */ -#define LL_DMA_ISR_HTIF2 DMA_ISR_HTIF2 /*!< Channel 2 half transfer flag */ -#define LL_DMA_ISR_TEIF2 DMA_ISR_TEIF2 /*!< Channel 2 transfer error flag */ -#define LL_DMA_ISR_GIF3 DMA_ISR_GIF3 /*!< Channel 3 global flag */ -#define LL_DMA_ISR_TCIF3 DMA_ISR_TCIF3 /*!< Channel 3 transfer complete flag */ -#define LL_DMA_ISR_HTIF3 DMA_ISR_HTIF3 /*!< Channel 3 half transfer flag */ -#define LL_DMA_ISR_TEIF3 DMA_ISR_TEIF3 /*!< Channel 3 transfer error flag */ -#define LL_DMA_ISR_GIF4 DMA_ISR_GIF4 /*!< Channel 4 global flag */ -#define LL_DMA_ISR_TCIF4 DMA_ISR_TCIF4 /*!< Channel 4 transfer complete flag */ -#define LL_DMA_ISR_HTIF4 DMA_ISR_HTIF4 /*!< Channel 4 half transfer flag */ -#define LL_DMA_ISR_TEIF4 DMA_ISR_TEIF4 /*!< Channel 4 transfer error flag */ -#define LL_DMA_ISR_GIF5 DMA_ISR_GIF5 /*!< Channel 5 global flag */ -#define LL_DMA_ISR_TCIF5 DMA_ISR_TCIF5 /*!< Channel 5 transfer complete flag */ -#define LL_DMA_ISR_HTIF5 DMA_ISR_HTIF5 /*!< Channel 5 half transfer flag */ -#define LL_DMA_ISR_TEIF5 DMA_ISR_TEIF5 /*!< Channel 5 transfer error flag */ -#define LL_DMA_ISR_GIF6 DMA_ISR_GIF6 /*!< Channel 6 global flag */ -#define LL_DMA_ISR_TCIF6 DMA_ISR_TCIF6 /*!< Channel 6 transfer complete flag */ -#define LL_DMA_ISR_HTIF6 DMA_ISR_HTIF6 /*!< Channel 6 half transfer flag */ -#define LL_DMA_ISR_TEIF6 DMA_ISR_TEIF6 /*!< Channel 6 transfer error flag */ -#define LL_DMA_ISR_GIF7 DMA_ISR_GIF7 /*!< Channel 7 global flag */ -#define LL_DMA_ISR_TCIF7 DMA_ISR_TCIF7 /*!< Channel 7 transfer complete flag */ -#define LL_DMA_ISR_HTIF7 DMA_ISR_HTIF7 /*!< Channel 7 half transfer flag */ -#define LL_DMA_ISR_TEIF7 DMA_ISR_TEIF7 /*!< Channel 7 transfer error flag */ -/** - * @} - */ - -/** @defgroup DMA_LL_EC_IT IT Defines - * @brief IT defines which can be used with LL_DMA_ReadReg and LL_DMA_WriteReg functions - * @{ - */ -#define LL_DMA_CCR_TCIE DMA_CCR_TCIE /*!< Transfer complete interrupt */ -#define LL_DMA_CCR_HTIE DMA_CCR_HTIE /*!< Half Transfer interrupt */ -#define LL_DMA_CCR_TEIE DMA_CCR_TEIE /*!< Transfer error interrupt */ -/** - * @} - */ - -/** @defgroup DMA_LL_EC_CHANNEL CHANNEL - * @{ - */ -#define LL_DMA_CHANNEL_1 0x00000001U /*!< DMA Channel 1 */ -#define LL_DMA_CHANNEL_2 0x00000002U /*!< DMA Channel 2 */ -#define LL_DMA_CHANNEL_3 0x00000003U /*!< DMA Channel 3 */ -#define LL_DMA_CHANNEL_4 0x00000004U /*!< DMA Channel 4 */ -#define LL_DMA_CHANNEL_5 0x00000005U /*!< DMA Channel 5 */ -#define LL_DMA_CHANNEL_6 0x00000006U /*!< DMA Channel 6 */ -#define LL_DMA_CHANNEL_7 0x00000007U /*!< DMA Channel 7 */ -#if defined(USE_FULL_LL_DRIVER) -#define LL_DMA_CHANNEL_ALL 0xFFFF0000U /*!< DMA Channel all (used only for function @ref LL_DMA_DeInit(). */ -#endif /*USE_FULL_LL_DRIVER*/ -/** - * @} - */ - -/** @defgroup DMA_LL_EC_DIRECTION Transfer Direction - * @{ - */ -#define LL_DMA_DIRECTION_PERIPH_TO_MEMORY 0x00000000U /*!< Peripheral to memory direction */ -#define LL_DMA_DIRECTION_MEMORY_TO_PERIPH DMA_CCR_DIR /*!< Memory to peripheral direction */ -#define LL_DMA_DIRECTION_MEMORY_TO_MEMORY DMA_CCR_MEM2MEM /*!< Memory to memory direction */ -/** - * @} - */ - -/** @defgroup DMA_LL_EC_MODE Transfer mode - * @{ - */ -#define LL_DMA_MODE_NORMAL 0x00000000U /*!< Normal Mode */ -#define LL_DMA_MODE_CIRCULAR DMA_CCR_CIRC /*!< Circular Mode */ -/** - * @} - */ - -/** @defgroup DMA_LL_EC_PERIPH Peripheral increment mode - * @{ - */ -#define LL_DMA_PERIPH_INCREMENT DMA_CCR_PINC /*!< Peripheral increment mode Enable */ -#define LL_DMA_PERIPH_NOINCREMENT 0x00000000U /*!< Peripheral increment mode Disable */ -/** - * @} - */ - -/** @defgroup DMA_LL_EC_MEMORY Memory increment mode - * @{ - */ -#define LL_DMA_MEMORY_INCREMENT DMA_CCR_MINC /*!< Memory increment mode Enable */ -#define LL_DMA_MEMORY_NOINCREMENT 0x00000000U /*!< Memory increment mode Disable */ -/** - * @} - */ - -/** @defgroup DMA_LL_EC_PDATAALIGN Peripheral data alignment - * @{ - */ -#define LL_DMA_PDATAALIGN_BYTE 0x00000000U /*!< Peripheral data alignment : Byte */ -#define LL_DMA_PDATAALIGN_HALFWORD DMA_CCR_PSIZE_0 /*!< Peripheral data alignment : HalfWord */ -#define LL_DMA_PDATAALIGN_WORD DMA_CCR_PSIZE_1 /*!< Peripheral data alignment : Word */ -/** - * @} - */ - -/** @defgroup DMA_LL_EC_MDATAALIGN Memory data alignment - * @{ - */ -#define LL_DMA_MDATAALIGN_BYTE 0x00000000U /*!< Memory data alignment : Byte */ -#define LL_DMA_MDATAALIGN_HALFWORD DMA_CCR_MSIZE_0 /*!< Memory data alignment : HalfWord */ -#define LL_DMA_MDATAALIGN_WORD DMA_CCR_MSIZE_1 /*!< Memory data alignment : Word */ -/** - * @} - */ - -/** @defgroup DMA_LL_EC_PRIORITY Transfer Priority level - * @{ - */ -#define LL_DMA_PRIORITY_LOW 0x00000000U /*!< Priority level : Low */ -#define LL_DMA_PRIORITY_MEDIUM DMA_CCR_PL_0 /*!< Priority level : Medium */ -#define LL_DMA_PRIORITY_HIGH DMA_CCR_PL_1 /*!< Priority level : High */ -#define LL_DMA_PRIORITY_VERYHIGH DMA_CCR_PL /*!< Priority level : Very_High */ -/** - * @} - */ - -/** - * @} - */ - -/* Exported macro ------------------------------------------------------------*/ -/** @defgroup DMA_LL_Exported_Macros DMA Exported Macros - * @{ - */ - -/** @defgroup DMA_LL_EM_WRITE_READ Common Write and read registers macros - * @{ - */ -/** - * @brief Write a value in DMA register - * @param __INSTANCE__ DMA Instance - * @param __REG__ Register to be written - * @param __VALUE__ Value to be written in the register - * @retval None - */ -#define LL_DMA_WriteReg(__INSTANCE__, __REG__, __VALUE__) WRITE_REG(__INSTANCE__->__REG__, (__VALUE__)) - -/** - * @brief Read a value in DMA register - * @param __INSTANCE__ DMA Instance - * @param __REG__ Register to be read - * @retval Register value - */ -#define LL_DMA_ReadReg(__INSTANCE__, __REG__) READ_REG(__INSTANCE__->__REG__) -/** - * @} - */ - -/** @defgroup DMA_LL_EM_CONVERT_DMAxCHANNELy Convert DMAxChannely - * @{ - */ - -/** - * @brief Convert DMAx_Channely into DMAx - * @param __CHANNEL_INSTANCE__ DMAx_Channely - * @retval DMAx - */ -#if defined(DMA2) -#define __LL_DMA_GET_INSTANCE(__CHANNEL_INSTANCE__) \ -(((uint32_t)(__CHANNEL_INSTANCE__) > ((uint32_t)DMA1_Channel7)) ? DMA2 : DMA1) -#else -#define __LL_DMA_GET_INSTANCE(__CHANNEL_INSTANCE__) (DMA1) -#endif - -/** - * @brief Convert DMAx_Channely into LL_DMA_CHANNEL_y - * @param __CHANNEL_INSTANCE__ DMAx_Channely - * @retval LL_DMA_CHANNEL_y - */ -#if defined (DMA2) -#define __LL_DMA_GET_CHANNEL(__CHANNEL_INSTANCE__) \ -(((uint32_t)(__CHANNEL_INSTANCE__) == ((uint32_t)DMA1_Channel1)) ? LL_DMA_CHANNEL_1 : \ - ((uint32_t)(__CHANNEL_INSTANCE__) == ((uint32_t)DMA2_Channel1)) ? LL_DMA_CHANNEL_1 : \ - ((uint32_t)(__CHANNEL_INSTANCE__) == ((uint32_t)DMA1_Channel2)) ? LL_DMA_CHANNEL_2 : \ - ((uint32_t)(__CHANNEL_INSTANCE__) == ((uint32_t)DMA2_Channel2)) ? LL_DMA_CHANNEL_2 : \ - ((uint32_t)(__CHANNEL_INSTANCE__) == ((uint32_t)DMA1_Channel3)) ? LL_DMA_CHANNEL_3 : \ - ((uint32_t)(__CHANNEL_INSTANCE__) == ((uint32_t)DMA2_Channel3)) ? LL_DMA_CHANNEL_3 : \ - ((uint32_t)(__CHANNEL_INSTANCE__) == ((uint32_t)DMA1_Channel4)) ? LL_DMA_CHANNEL_4 : \ - ((uint32_t)(__CHANNEL_INSTANCE__) == ((uint32_t)DMA2_Channel4)) ? LL_DMA_CHANNEL_4 : \ - ((uint32_t)(__CHANNEL_INSTANCE__) == ((uint32_t)DMA1_Channel5)) ? LL_DMA_CHANNEL_5 : \ - ((uint32_t)(__CHANNEL_INSTANCE__) == ((uint32_t)DMA2_Channel5)) ? LL_DMA_CHANNEL_5 : \ - ((uint32_t)(__CHANNEL_INSTANCE__) == ((uint32_t)DMA1_Channel6)) ? LL_DMA_CHANNEL_6 : \ - LL_DMA_CHANNEL_7) -#else -#define __LL_DMA_GET_CHANNEL(__CHANNEL_INSTANCE__) \ -(((uint32_t)(__CHANNEL_INSTANCE__) == ((uint32_t)DMA1_Channel1)) ? LL_DMA_CHANNEL_1 : \ - ((uint32_t)(__CHANNEL_INSTANCE__) == ((uint32_t)DMA1_Channel2)) ? LL_DMA_CHANNEL_2 : \ - ((uint32_t)(__CHANNEL_INSTANCE__) == ((uint32_t)DMA1_Channel3)) ? LL_DMA_CHANNEL_3 : \ - ((uint32_t)(__CHANNEL_INSTANCE__) == ((uint32_t)DMA1_Channel4)) ? LL_DMA_CHANNEL_4 : \ - ((uint32_t)(__CHANNEL_INSTANCE__) == ((uint32_t)DMA1_Channel5)) ? LL_DMA_CHANNEL_5 : \ - ((uint32_t)(__CHANNEL_INSTANCE__) == ((uint32_t)DMA1_Channel6)) ? LL_DMA_CHANNEL_6 : \ - LL_DMA_CHANNEL_7) -#endif - -/** - * @brief Convert DMA Instance DMAx and LL_DMA_CHANNEL_y into DMAx_Channely - * @param __DMA_INSTANCE__ DMAx - * @param __CHANNEL__ LL_DMA_CHANNEL_y - * @retval DMAx_Channely - */ -#if defined (DMA2) -#define __LL_DMA_GET_CHANNEL_INSTANCE(__DMA_INSTANCE__, __CHANNEL__) \ -((((uint32_t)(__DMA_INSTANCE__) == ((uint32_t)DMA1)) && ((uint32_t)(__CHANNEL__) == ((uint32_t)LL_DMA_CHANNEL_1))) ? DMA1_Channel1 : \ - (((uint32_t)(__DMA_INSTANCE__) == ((uint32_t)DMA2)) && ((uint32_t)(__CHANNEL__) == ((uint32_t)LL_DMA_CHANNEL_1))) ? DMA2_Channel1 : \ - (((uint32_t)(__DMA_INSTANCE__) == ((uint32_t)DMA1)) && ((uint32_t)(__CHANNEL__) == ((uint32_t)LL_DMA_CHANNEL_2))) ? DMA1_Channel2 : \ - (((uint32_t)(__DMA_INSTANCE__) == ((uint32_t)DMA2)) && ((uint32_t)(__CHANNEL__) == ((uint32_t)LL_DMA_CHANNEL_2))) ? DMA2_Channel2 : \ - (((uint32_t)(__DMA_INSTANCE__) == ((uint32_t)DMA1)) && ((uint32_t)(__CHANNEL__) == ((uint32_t)LL_DMA_CHANNEL_3))) ? DMA1_Channel3 : \ - (((uint32_t)(__DMA_INSTANCE__) == ((uint32_t)DMA2)) && ((uint32_t)(__CHANNEL__) == ((uint32_t)LL_DMA_CHANNEL_3))) ? DMA2_Channel3 : \ - (((uint32_t)(__DMA_INSTANCE__) == ((uint32_t)DMA1)) && ((uint32_t)(__CHANNEL__) == ((uint32_t)LL_DMA_CHANNEL_4))) ? DMA1_Channel4 : \ - (((uint32_t)(__DMA_INSTANCE__) == ((uint32_t)DMA2)) && ((uint32_t)(__CHANNEL__) == ((uint32_t)LL_DMA_CHANNEL_4))) ? DMA2_Channel4 : \ - (((uint32_t)(__DMA_INSTANCE__) == ((uint32_t)DMA1)) && ((uint32_t)(__CHANNEL__) == ((uint32_t)LL_DMA_CHANNEL_5))) ? DMA1_Channel5 : \ - (((uint32_t)(__DMA_INSTANCE__) == ((uint32_t)DMA2)) && ((uint32_t)(__CHANNEL__) == ((uint32_t)LL_DMA_CHANNEL_5))) ? DMA2_Channel5 : \ - (((uint32_t)(__DMA_INSTANCE__) == ((uint32_t)DMA1)) && ((uint32_t)(__CHANNEL__) == ((uint32_t)LL_DMA_CHANNEL_6))) ? DMA1_Channel6 : \ - DMA1_Channel7) -#else -#define __LL_DMA_GET_CHANNEL_INSTANCE(__DMA_INSTANCE__, __CHANNEL__) \ -((((uint32_t)(__DMA_INSTANCE__) == ((uint32_t)DMA1)) && ((uint32_t)(__CHANNEL__) == ((uint32_t)LL_DMA_CHANNEL_1))) ? DMA1_Channel1 : \ - (((uint32_t)(__DMA_INSTANCE__) == ((uint32_t)DMA1)) && ((uint32_t)(__CHANNEL__) == ((uint32_t)LL_DMA_CHANNEL_2))) ? DMA1_Channel2 : \ - (((uint32_t)(__DMA_INSTANCE__) == ((uint32_t)DMA1)) && ((uint32_t)(__CHANNEL__) == ((uint32_t)LL_DMA_CHANNEL_3))) ? DMA1_Channel3 : \ - (((uint32_t)(__DMA_INSTANCE__) == ((uint32_t)DMA1)) && ((uint32_t)(__CHANNEL__) == ((uint32_t)LL_DMA_CHANNEL_4))) ? DMA1_Channel4 : \ - (((uint32_t)(__DMA_INSTANCE__) == ((uint32_t)DMA1)) && ((uint32_t)(__CHANNEL__) == ((uint32_t)LL_DMA_CHANNEL_5))) ? DMA1_Channel5 : \ - (((uint32_t)(__DMA_INSTANCE__) == ((uint32_t)DMA1)) && ((uint32_t)(__CHANNEL__) == ((uint32_t)LL_DMA_CHANNEL_6))) ? DMA1_Channel6 : \ - DMA1_Channel7) -#endif - -/** - * @} - */ - -/** - * @} - */ - -/* Exported functions --------------------------------------------------------*/ -/** @defgroup DMA_LL_Exported_Functions DMA Exported Functions - * @{ - */ - -/** @defgroup DMA_LL_EF_Configuration Configuration - * @{ - */ -/** - * @brief Enable DMA channel. - * @rmtoll CCR EN LL_DMA_EnableChannel - * @param DMAx DMAx Instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_DMA_CHANNEL_1 - * @arg @ref LL_DMA_CHANNEL_2 - * @arg @ref LL_DMA_CHANNEL_3 - * @arg @ref LL_DMA_CHANNEL_4 - * @arg @ref LL_DMA_CHANNEL_5 - * @arg @ref LL_DMA_CHANNEL_6 - * @arg @ref LL_DMA_CHANNEL_7 - * @retval None - */ -__STATIC_INLINE void LL_DMA_EnableChannel(DMA_TypeDef *DMAx, uint32_t Channel) -{ - SET_BIT(((DMA_Channel_TypeDef *)((uint32_t)((uint32_t)DMAx + CHANNEL_OFFSET_TAB[Channel - 1U])))->CCR, DMA_CCR_EN); -} - -/** - * @brief Disable DMA channel. - * @rmtoll CCR EN LL_DMA_DisableChannel - * @param DMAx DMAx Instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_DMA_CHANNEL_1 - * @arg @ref LL_DMA_CHANNEL_2 - * @arg @ref LL_DMA_CHANNEL_3 - * @arg @ref LL_DMA_CHANNEL_4 - * @arg @ref LL_DMA_CHANNEL_5 - * @arg @ref LL_DMA_CHANNEL_6 - * @arg @ref LL_DMA_CHANNEL_7 - * @retval None - */ -__STATIC_INLINE void LL_DMA_DisableChannel(DMA_TypeDef *DMAx, uint32_t Channel) -{ - CLEAR_BIT(((DMA_Channel_TypeDef *)((uint32_t)((uint32_t)DMAx + CHANNEL_OFFSET_TAB[Channel - 1U])))->CCR, DMA_CCR_EN); -} - -/** - * @brief Check if DMA channel is enabled or disabled. - * @rmtoll CCR EN LL_DMA_IsEnabledChannel - * @param DMAx DMAx Instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_DMA_CHANNEL_1 - * @arg @ref LL_DMA_CHANNEL_2 - * @arg @ref LL_DMA_CHANNEL_3 - * @arg @ref LL_DMA_CHANNEL_4 - * @arg @ref LL_DMA_CHANNEL_5 - * @arg @ref LL_DMA_CHANNEL_6 - * @arg @ref LL_DMA_CHANNEL_7 - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_DMA_IsEnabledChannel(DMA_TypeDef *DMAx, uint32_t Channel) -{ - return (READ_BIT(((DMA_Channel_TypeDef *)((uint32_t)((uint32_t)DMAx + CHANNEL_OFFSET_TAB[Channel - 1U])))->CCR, - DMA_CCR_EN) == (DMA_CCR_EN)); -} - -/** - * @brief Configure all parameters link to DMA transfer. - * @rmtoll CCR DIR LL_DMA_ConfigTransfer\n - * CCR MEM2MEM LL_DMA_ConfigTransfer\n - * CCR CIRC LL_DMA_ConfigTransfer\n - * CCR PINC LL_DMA_ConfigTransfer\n - * CCR MINC LL_DMA_ConfigTransfer\n - * CCR PSIZE LL_DMA_ConfigTransfer\n - * CCR MSIZE LL_DMA_ConfigTransfer\n - * CCR PL LL_DMA_ConfigTransfer - * @param DMAx DMAx Instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_DMA_CHANNEL_1 - * @arg @ref LL_DMA_CHANNEL_2 - * @arg @ref LL_DMA_CHANNEL_3 - * @arg @ref LL_DMA_CHANNEL_4 - * @arg @ref LL_DMA_CHANNEL_5 - * @arg @ref LL_DMA_CHANNEL_6 - * @arg @ref LL_DMA_CHANNEL_7 - * @param Configuration This parameter must be a combination of all the following values: - * @arg @ref LL_DMA_DIRECTION_PERIPH_TO_MEMORY or @ref LL_DMA_DIRECTION_MEMORY_TO_PERIPH or @ref LL_DMA_DIRECTION_MEMORY_TO_MEMORY - * @arg @ref LL_DMA_MODE_NORMAL or @ref LL_DMA_MODE_CIRCULAR - * @arg @ref LL_DMA_PERIPH_INCREMENT or @ref LL_DMA_PERIPH_NOINCREMENT - * @arg @ref LL_DMA_MEMORY_INCREMENT or @ref LL_DMA_MEMORY_NOINCREMENT - * @arg @ref LL_DMA_PDATAALIGN_BYTE or @ref LL_DMA_PDATAALIGN_HALFWORD or @ref LL_DMA_PDATAALIGN_WORD - * @arg @ref LL_DMA_MDATAALIGN_BYTE or @ref LL_DMA_MDATAALIGN_HALFWORD or @ref LL_DMA_MDATAALIGN_WORD - * @arg @ref LL_DMA_PRIORITY_LOW or @ref LL_DMA_PRIORITY_MEDIUM or @ref LL_DMA_PRIORITY_HIGH or @ref LL_DMA_PRIORITY_VERYHIGH - * @retval None - */ -__STATIC_INLINE void LL_DMA_ConfigTransfer(DMA_TypeDef *DMAx, uint32_t Channel, uint32_t Configuration) -{ - MODIFY_REG(((DMA_Channel_TypeDef *)((uint32_t)((uint32_t)DMAx + CHANNEL_OFFSET_TAB[Channel - 1U])))->CCR, - DMA_CCR_DIR | DMA_CCR_MEM2MEM | DMA_CCR_CIRC | DMA_CCR_PINC | DMA_CCR_MINC | DMA_CCR_PSIZE | DMA_CCR_MSIZE | DMA_CCR_PL, - Configuration); -} - -/** - * @brief Set Data transfer direction (read from peripheral or from memory). - * @rmtoll CCR DIR LL_DMA_SetDataTransferDirection\n - * CCR MEM2MEM LL_DMA_SetDataTransferDirection - * @param DMAx DMAx Instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_DMA_CHANNEL_1 - * @arg @ref LL_DMA_CHANNEL_2 - * @arg @ref LL_DMA_CHANNEL_3 - * @arg @ref LL_DMA_CHANNEL_4 - * @arg @ref LL_DMA_CHANNEL_5 - * @arg @ref LL_DMA_CHANNEL_6 - * @arg @ref LL_DMA_CHANNEL_7 - * @param Direction This parameter can be one of the following values: - * @arg @ref LL_DMA_DIRECTION_PERIPH_TO_MEMORY - * @arg @ref LL_DMA_DIRECTION_MEMORY_TO_PERIPH - * @arg @ref LL_DMA_DIRECTION_MEMORY_TO_MEMORY - * @retval None - */ -__STATIC_INLINE void LL_DMA_SetDataTransferDirection(DMA_TypeDef *DMAx, uint32_t Channel, uint32_t Direction) -{ - MODIFY_REG(((DMA_Channel_TypeDef *)((uint32_t)((uint32_t)DMAx + CHANNEL_OFFSET_TAB[Channel - 1U])))->CCR, - DMA_CCR_DIR | DMA_CCR_MEM2MEM, Direction); -} - -/** - * @brief Get Data transfer direction (read from peripheral or from memory). - * @rmtoll CCR DIR LL_DMA_GetDataTransferDirection\n - * CCR MEM2MEM LL_DMA_GetDataTransferDirection - * @param DMAx DMAx Instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_DMA_CHANNEL_1 - * @arg @ref LL_DMA_CHANNEL_2 - * @arg @ref LL_DMA_CHANNEL_3 - * @arg @ref LL_DMA_CHANNEL_4 - * @arg @ref LL_DMA_CHANNEL_5 - * @arg @ref LL_DMA_CHANNEL_6 - * @arg @ref LL_DMA_CHANNEL_7 - * @retval Returned value can be one of the following values: - * @arg @ref LL_DMA_DIRECTION_PERIPH_TO_MEMORY - * @arg @ref LL_DMA_DIRECTION_MEMORY_TO_PERIPH - * @arg @ref LL_DMA_DIRECTION_MEMORY_TO_MEMORY - */ -__STATIC_INLINE uint32_t LL_DMA_GetDataTransferDirection(DMA_TypeDef *DMAx, uint32_t Channel) -{ - return (READ_BIT(((DMA_Channel_TypeDef *)((uint32_t)((uint32_t)DMAx + CHANNEL_OFFSET_TAB[Channel - 1U])))->CCR, - DMA_CCR_DIR | DMA_CCR_MEM2MEM)); -} - -/** - * @brief Set DMA mode circular or normal. - * @note The circular buffer mode cannot be used if the memory-to-memory - * data transfer is configured on the selected Channel. - * @rmtoll CCR CIRC LL_DMA_SetMode - * @param DMAx DMAx Instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_DMA_CHANNEL_1 - * @arg @ref LL_DMA_CHANNEL_2 - * @arg @ref LL_DMA_CHANNEL_3 - * @arg @ref LL_DMA_CHANNEL_4 - * @arg @ref LL_DMA_CHANNEL_5 - * @arg @ref LL_DMA_CHANNEL_6 - * @arg @ref LL_DMA_CHANNEL_7 - * @param Mode This parameter can be one of the following values: - * @arg @ref LL_DMA_MODE_NORMAL - * @arg @ref LL_DMA_MODE_CIRCULAR - * @retval None - */ -__STATIC_INLINE void LL_DMA_SetMode(DMA_TypeDef *DMAx, uint32_t Channel, uint32_t Mode) -{ - MODIFY_REG(((DMA_Channel_TypeDef *)((uint32_t)((uint32_t)DMAx + CHANNEL_OFFSET_TAB[Channel - 1U])))->CCR, DMA_CCR_CIRC, - Mode); -} - -/** - * @brief Get DMA mode circular or normal. - * @rmtoll CCR CIRC LL_DMA_GetMode - * @param DMAx DMAx Instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_DMA_CHANNEL_1 - * @arg @ref LL_DMA_CHANNEL_2 - * @arg @ref LL_DMA_CHANNEL_3 - * @arg @ref LL_DMA_CHANNEL_4 - * @arg @ref LL_DMA_CHANNEL_5 - * @arg @ref LL_DMA_CHANNEL_6 - * @arg @ref LL_DMA_CHANNEL_7 - * @retval Returned value can be one of the following values: - * @arg @ref LL_DMA_MODE_NORMAL - * @arg @ref LL_DMA_MODE_CIRCULAR - */ -__STATIC_INLINE uint32_t LL_DMA_GetMode(DMA_TypeDef *DMAx, uint32_t Channel) -{ - return (READ_BIT(((DMA_Channel_TypeDef *)((uint32_t)((uint32_t)DMAx + CHANNEL_OFFSET_TAB[Channel - 1U])))->CCR, - DMA_CCR_CIRC)); -} - -/** - * @brief Set Peripheral increment mode. - * @rmtoll CCR PINC LL_DMA_SetPeriphIncMode - * @param DMAx DMAx Instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_DMA_CHANNEL_1 - * @arg @ref LL_DMA_CHANNEL_2 - * @arg @ref LL_DMA_CHANNEL_3 - * @arg @ref LL_DMA_CHANNEL_4 - * @arg @ref LL_DMA_CHANNEL_5 - * @arg @ref LL_DMA_CHANNEL_6 - * @arg @ref LL_DMA_CHANNEL_7 - * @param PeriphOrM2MSrcIncMode This parameter can be one of the following values: - * @arg @ref LL_DMA_PERIPH_INCREMENT - * @arg @ref LL_DMA_PERIPH_NOINCREMENT - * @retval None - */ -__STATIC_INLINE void LL_DMA_SetPeriphIncMode(DMA_TypeDef *DMAx, uint32_t Channel, uint32_t PeriphOrM2MSrcIncMode) -{ - MODIFY_REG(((DMA_Channel_TypeDef *)((uint32_t)((uint32_t)DMAx + CHANNEL_OFFSET_TAB[Channel - 1U])))->CCR, DMA_CCR_PINC, - PeriphOrM2MSrcIncMode); -} - -/** - * @brief Get Peripheral increment mode. - * @rmtoll CCR PINC LL_DMA_GetPeriphIncMode - * @param DMAx DMAx Instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_DMA_CHANNEL_1 - * @arg @ref LL_DMA_CHANNEL_2 - * @arg @ref LL_DMA_CHANNEL_3 - * @arg @ref LL_DMA_CHANNEL_4 - * @arg @ref LL_DMA_CHANNEL_5 - * @arg @ref LL_DMA_CHANNEL_6 - * @arg @ref LL_DMA_CHANNEL_7 - * @retval Returned value can be one of the following values: - * @arg @ref LL_DMA_PERIPH_INCREMENT - * @arg @ref LL_DMA_PERIPH_NOINCREMENT - */ -__STATIC_INLINE uint32_t LL_DMA_GetPeriphIncMode(DMA_TypeDef *DMAx, uint32_t Channel) -{ - return (READ_BIT(((DMA_Channel_TypeDef *)((uint32_t)((uint32_t)DMAx + CHANNEL_OFFSET_TAB[Channel - 1U])))->CCR, - DMA_CCR_PINC)); -} - -/** - * @brief Set Memory increment mode. - * @rmtoll CCR MINC LL_DMA_SetMemoryIncMode - * @param DMAx DMAx Instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_DMA_CHANNEL_1 - * @arg @ref LL_DMA_CHANNEL_2 - * @arg @ref LL_DMA_CHANNEL_3 - * @arg @ref LL_DMA_CHANNEL_4 - * @arg @ref LL_DMA_CHANNEL_5 - * @arg @ref LL_DMA_CHANNEL_6 - * @arg @ref LL_DMA_CHANNEL_7 - * @param MemoryOrM2MDstIncMode This parameter can be one of the following values: - * @arg @ref LL_DMA_MEMORY_INCREMENT - * @arg @ref LL_DMA_MEMORY_NOINCREMENT - * @retval None - */ -__STATIC_INLINE void LL_DMA_SetMemoryIncMode(DMA_TypeDef *DMAx, uint32_t Channel, uint32_t MemoryOrM2MDstIncMode) -{ - MODIFY_REG(((DMA_Channel_TypeDef *)((uint32_t)((uint32_t)DMAx + CHANNEL_OFFSET_TAB[Channel - 1U])))->CCR, DMA_CCR_MINC, - MemoryOrM2MDstIncMode); -} - -/** - * @brief Get Memory increment mode. - * @rmtoll CCR MINC LL_DMA_GetMemoryIncMode - * @param DMAx DMAx Instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_DMA_CHANNEL_1 - * @arg @ref LL_DMA_CHANNEL_2 - * @arg @ref LL_DMA_CHANNEL_3 - * @arg @ref LL_DMA_CHANNEL_4 - * @arg @ref LL_DMA_CHANNEL_5 - * @arg @ref LL_DMA_CHANNEL_6 - * @arg @ref LL_DMA_CHANNEL_7 - * @retval Returned value can be one of the following values: - * @arg @ref LL_DMA_MEMORY_INCREMENT - * @arg @ref LL_DMA_MEMORY_NOINCREMENT - */ -__STATIC_INLINE uint32_t LL_DMA_GetMemoryIncMode(DMA_TypeDef *DMAx, uint32_t Channel) -{ - return (READ_BIT(((DMA_Channel_TypeDef *)((uint32_t)((uint32_t)DMAx + CHANNEL_OFFSET_TAB[Channel - 1U])))->CCR, - DMA_CCR_MINC)); -} - -/** - * @brief Set Peripheral size. - * @rmtoll CCR PSIZE LL_DMA_SetPeriphSize - * @param DMAx DMAx Instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_DMA_CHANNEL_1 - * @arg @ref LL_DMA_CHANNEL_2 - * @arg @ref LL_DMA_CHANNEL_3 - * @arg @ref LL_DMA_CHANNEL_4 - * @arg @ref LL_DMA_CHANNEL_5 - * @arg @ref LL_DMA_CHANNEL_6 - * @arg @ref LL_DMA_CHANNEL_7 - * @param PeriphOrM2MSrcDataSize This parameter can be one of the following values: - * @arg @ref LL_DMA_PDATAALIGN_BYTE - * @arg @ref LL_DMA_PDATAALIGN_HALFWORD - * @arg @ref LL_DMA_PDATAALIGN_WORD - * @retval None - */ -__STATIC_INLINE void LL_DMA_SetPeriphSize(DMA_TypeDef *DMAx, uint32_t Channel, uint32_t PeriphOrM2MSrcDataSize) -{ - MODIFY_REG(((DMA_Channel_TypeDef *)((uint32_t)((uint32_t)DMAx + CHANNEL_OFFSET_TAB[Channel - 1U])))->CCR, DMA_CCR_PSIZE, - PeriphOrM2MSrcDataSize); -} - -/** - * @brief Get Peripheral size. - * @rmtoll CCR PSIZE LL_DMA_GetPeriphSize - * @param DMAx DMAx Instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_DMA_CHANNEL_1 - * @arg @ref LL_DMA_CHANNEL_2 - * @arg @ref LL_DMA_CHANNEL_3 - * @arg @ref LL_DMA_CHANNEL_4 - * @arg @ref LL_DMA_CHANNEL_5 - * @arg @ref LL_DMA_CHANNEL_6 - * @arg @ref LL_DMA_CHANNEL_7 - * @retval Returned value can be one of the following values: - * @arg @ref LL_DMA_PDATAALIGN_BYTE - * @arg @ref LL_DMA_PDATAALIGN_HALFWORD - * @arg @ref LL_DMA_PDATAALIGN_WORD - */ -__STATIC_INLINE uint32_t LL_DMA_GetPeriphSize(DMA_TypeDef *DMAx, uint32_t Channel) -{ - return (READ_BIT(((DMA_Channel_TypeDef *)((uint32_t)((uint32_t)DMAx + CHANNEL_OFFSET_TAB[Channel - 1U])))->CCR, - DMA_CCR_PSIZE)); -} - -/** - * @brief Set Memory size. - * @rmtoll CCR MSIZE LL_DMA_SetMemorySize - * @param DMAx DMAx Instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_DMA_CHANNEL_1 - * @arg @ref LL_DMA_CHANNEL_2 - * @arg @ref LL_DMA_CHANNEL_3 - * @arg @ref LL_DMA_CHANNEL_4 - * @arg @ref LL_DMA_CHANNEL_5 - * @arg @ref LL_DMA_CHANNEL_6 - * @arg @ref LL_DMA_CHANNEL_7 - * @param MemoryOrM2MDstDataSize This parameter can be one of the following values: - * @arg @ref LL_DMA_MDATAALIGN_BYTE - * @arg @ref LL_DMA_MDATAALIGN_HALFWORD - * @arg @ref LL_DMA_MDATAALIGN_WORD - * @retval None - */ -__STATIC_INLINE void LL_DMA_SetMemorySize(DMA_TypeDef *DMAx, uint32_t Channel, uint32_t MemoryOrM2MDstDataSize) -{ - MODIFY_REG(((DMA_Channel_TypeDef *)((uint32_t)((uint32_t)DMAx + CHANNEL_OFFSET_TAB[Channel - 1U])))->CCR, DMA_CCR_MSIZE, - MemoryOrM2MDstDataSize); -} - -/** - * @brief Get Memory size. - * @rmtoll CCR MSIZE LL_DMA_GetMemorySize - * @param DMAx DMAx Instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_DMA_CHANNEL_1 - * @arg @ref LL_DMA_CHANNEL_2 - * @arg @ref LL_DMA_CHANNEL_3 - * @arg @ref LL_DMA_CHANNEL_4 - * @arg @ref LL_DMA_CHANNEL_5 - * @arg @ref LL_DMA_CHANNEL_6 - * @arg @ref LL_DMA_CHANNEL_7 - * @retval Returned value can be one of the following values: - * @arg @ref LL_DMA_MDATAALIGN_BYTE - * @arg @ref LL_DMA_MDATAALIGN_HALFWORD - * @arg @ref LL_DMA_MDATAALIGN_WORD - */ -__STATIC_INLINE uint32_t LL_DMA_GetMemorySize(DMA_TypeDef *DMAx, uint32_t Channel) -{ - return (READ_BIT(((DMA_Channel_TypeDef *)((uint32_t)((uint32_t)DMAx + CHANNEL_OFFSET_TAB[Channel - 1U])))->CCR, - DMA_CCR_MSIZE)); -} - -/** - * @brief Set Channel priority level. - * @rmtoll CCR PL LL_DMA_SetChannelPriorityLevel - * @param DMAx DMAx Instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_DMA_CHANNEL_1 - * @arg @ref LL_DMA_CHANNEL_2 - * @arg @ref LL_DMA_CHANNEL_3 - * @arg @ref LL_DMA_CHANNEL_4 - * @arg @ref LL_DMA_CHANNEL_5 - * @arg @ref LL_DMA_CHANNEL_6 - * @arg @ref LL_DMA_CHANNEL_7 - * @param Priority This parameter can be one of the following values: - * @arg @ref LL_DMA_PRIORITY_LOW - * @arg @ref LL_DMA_PRIORITY_MEDIUM - * @arg @ref LL_DMA_PRIORITY_HIGH - * @arg @ref LL_DMA_PRIORITY_VERYHIGH - * @retval None - */ -__STATIC_INLINE void LL_DMA_SetChannelPriorityLevel(DMA_TypeDef *DMAx, uint32_t Channel, uint32_t Priority) -{ - MODIFY_REG(((DMA_Channel_TypeDef *)((uint32_t)((uint32_t)DMAx + CHANNEL_OFFSET_TAB[Channel - 1U])))->CCR, DMA_CCR_PL, - Priority); -} - -/** - * @brief Get Channel priority level. - * @rmtoll CCR PL LL_DMA_GetChannelPriorityLevel - * @param DMAx DMAx Instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_DMA_CHANNEL_1 - * @arg @ref LL_DMA_CHANNEL_2 - * @arg @ref LL_DMA_CHANNEL_3 - * @arg @ref LL_DMA_CHANNEL_4 - * @arg @ref LL_DMA_CHANNEL_5 - * @arg @ref LL_DMA_CHANNEL_6 - * @arg @ref LL_DMA_CHANNEL_7 - * @retval Returned value can be one of the following values: - * @arg @ref LL_DMA_PRIORITY_LOW - * @arg @ref LL_DMA_PRIORITY_MEDIUM - * @arg @ref LL_DMA_PRIORITY_HIGH - * @arg @ref LL_DMA_PRIORITY_VERYHIGH - */ -__STATIC_INLINE uint32_t LL_DMA_GetChannelPriorityLevel(DMA_TypeDef *DMAx, uint32_t Channel) -{ - return (READ_BIT(((DMA_Channel_TypeDef *)((uint32_t)((uint32_t)DMAx + CHANNEL_OFFSET_TAB[Channel - 1U])))->CCR, - DMA_CCR_PL)); -} - -/** - * @brief Set Number of data to transfer. - * @note This action has no effect if - * channel is enabled. - * @rmtoll CNDTR NDT LL_DMA_SetDataLength - * @param DMAx DMAx Instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_DMA_CHANNEL_1 - * @arg @ref LL_DMA_CHANNEL_2 - * @arg @ref LL_DMA_CHANNEL_3 - * @arg @ref LL_DMA_CHANNEL_4 - * @arg @ref LL_DMA_CHANNEL_5 - * @arg @ref LL_DMA_CHANNEL_6 - * @arg @ref LL_DMA_CHANNEL_7 - * @param NbData Between Min_Data = 0 and Max_Data = 0x0000FFFF - * @retval None - */ -__STATIC_INLINE void LL_DMA_SetDataLength(DMA_TypeDef *DMAx, uint32_t Channel, uint32_t NbData) -{ - MODIFY_REG(((DMA_Channel_TypeDef *)((uint32_t)((uint32_t)DMAx + CHANNEL_OFFSET_TAB[Channel - 1U])))->CNDTR, - DMA_CNDTR_NDT, NbData); -} - -/** - * @brief Get Number of data to transfer. - * @note Once the channel is enabled, the return value indicate the - * remaining bytes to be transmitted. - * @rmtoll CNDTR NDT LL_DMA_GetDataLength - * @param DMAx DMAx Instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_DMA_CHANNEL_1 - * @arg @ref LL_DMA_CHANNEL_2 - * @arg @ref LL_DMA_CHANNEL_3 - * @arg @ref LL_DMA_CHANNEL_4 - * @arg @ref LL_DMA_CHANNEL_5 - * @arg @ref LL_DMA_CHANNEL_6 - * @arg @ref LL_DMA_CHANNEL_7 - * @retval Between Min_Data = 0 and Max_Data = 0xFFFFFFFF - */ -__STATIC_INLINE uint32_t LL_DMA_GetDataLength(DMA_TypeDef *DMAx, uint32_t Channel) -{ - return (READ_BIT(((DMA_Channel_TypeDef *)((uint32_t)((uint32_t)DMAx + CHANNEL_OFFSET_TAB[Channel - 1U])))->CNDTR, - DMA_CNDTR_NDT)); -} - -/** - * @brief Configure the Source and Destination addresses. - * @note This API must not be called when the DMA channel is enabled. - * @note Each IP using DMA provides an API to get directly the register adress (LL_PPP_DMA_GetRegAddr). - * @rmtoll CPAR PA LL_DMA_ConfigAddresses\n - * CMAR MA LL_DMA_ConfigAddresses - * @param DMAx DMAx Instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_DMA_CHANNEL_1 - * @arg @ref LL_DMA_CHANNEL_2 - * @arg @ref LL_DMA_CHANNEL_3 - * @arg @ref LL_DMA_CHANNEL_4 - * @arg @ref LL_DMA_CHANNEL_5 - * @arg @ref LL_DMA_CHANNEL_6 - * @arg @ref LL_DMA_CHANNEL_7 - * @param SrcAddress Between Min_Data = 0 and Max_Data = 0xFFFFFFFF - * @param DstAddress Between Min_Data = 0 and Max_Data = 0xFFFFFFFF - * @param Direction This parameter can be one of the following values: - * @arg @ref LL_DMA_DIRECTION_PERIPH_TO_MEMORY - * @arg @ref LL_DMA_DIRECTION_MEMORY_TO_PERIPH - * @arg @ref LL_DMA_DIRECTION_MEMORY_TO_MEMORY - * @retval None - */ -__STATIC_INLINE void LL_DMA_ConfigAddresses(DMA_TypeDef *DMAx, uint32_t Channel, uint32_t SrcAddress, - uint32_t DstAddress, uint32_t Direction) -{ - /* Direction Memory to Periph */ - if (Direction == LL_DMA_DIRECTION_MEMORY_TO_PERIPH) - { - WRITE_REG(((DMA_Channel_TypeDef *)((uint32_t)((uint32_t)DMAx + CHANNEL_OFFSET_TAB[Channel - 1U])))->CMAR, SrcAddress); - WRITE_REG(((DMA_Channel_TypeDef *)((uint32_t)((uint32_t)DMAx + CHANNEL_OFFSET_TAB[Channel - 1U])))->CPAR, DstAddress); - } - /* Direction Periph to Memory and Memory to Memory */ - else - { - WRITE_REG(((DMA_Channel_TypeDef *)((uint32_t)((uint32_t)DMAx + CHANNEL_OFFSET_TAB[Channel - 1U])))->CPAR, SrcAddress); - WRITE_REG(((DMA_Channel_TypeDef *)((uint32_t)((uint32_t)DMAx + CHANNEL_OFFSET_TAB[Channel - 1U])))->CMAR, DstAddress); - } -} - -/** - * @brief Set the Memory address. - * @note Interface used for direction LL_DMA_DIRECTION_PERIPH_TO_MEMORY or LL_DMA_DIRECTION_MEMORY_TO_PERIPH only. - * @note This API must not be called when the DMA channel is enabled. - * @rmtoll CMAR MA LL_DMA_SetMemoryAddress - * @param DMAx DMAx Instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_DMA_CHANNEL_1 - * @arg @ref LL_DMA_CHANNEL_2 - * @arg @ref LL_DMA_CHANNEL_3 - * @arg @ref LL_DMA_CHANNEL_4 - * @arg @ref LL_DMA_CHANNEL_5 - * @arg @ref LL_DMA_CHANNEL_6 - * @arg @ref LL_DMA_CHANNEL_7 - * @param MemoryAddress Between Min_Data = 0 and Max_Data = 0xFFFFFFFF - * @retval None - */ -__STATIC_INLINE void LL_DMA_SetMemoryAddress(DMA_TypeDef *DMAx, uint32_t Channel, uint32_t MemoryAddress) -{ - WRITE_REG(((DMA_Channel_TypeDef *)((uint32_t)((uint32_t)DMAx + CHANNEL_OFFSET_TAB[Channel - 1U])))->CMAR, MemoryAddress); -} - -/** - * @brief Set the Peripheral address. - * @note Interface used for direction LL_DMA_DIRECTION_PERIPH_TO_MEMORY or LL_DMA_DIRECTION_MEMORY_TO_PERIPH only. - * @note This API must not be called when the DMA channel is enabled. - * @rmtoll CPAR PA LL_DMA_SetPeriphAddress - * @param DMAx DMAx Instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_DMA_CHANNEL_1 - * @arg @ref LL_DMA_CHANNEL_2 - * @arg @ref LL_DMA_CHANNEL_3 - * @arg @ref LL_DMA_CHANNEL_4 - * @arg @ref LL_DMA_CHANNEL_5 - * @arg @ref LL_DMA_CHANNEL_6 - * @arg @ref LL_DMA_CHANNEL_7 - * @param PeriphAddress Between Min_Data = 0 and Max_Data = 0xFFFFFFFF - * @retval None - */ -__STATIC_INLINE void LL_DMA_SetPeriphAddress(DMA_TypeDef *DMAx, uint32_t Channel, uint32_t PeriphAddress) -{ - WRITE_REG(((DMA_Channel_TypeDef *)((uint32_t)((uint32_t)DMAx + CHANNEL_OFFSET_TAB[Channel - 1U])))->CPAR, PeriphAddress); -} - -/** - * @brief Get Memory address. - * @note Interface used for direction LL_DMA_DIRECTION_PERIPH_TO_MEMORY or LL_DMA_DIRECTION_MEMORY_TO_PERIPH only. - * @rmtoll CMAR MA LL_DMA_GetMemoryAddress - * @param DMAx DMAx Instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_DMA_CHANNEL_1 - * @arg @ref LL_DMA_CHANNEL_2 - * @arg @ref LL_DMA_CHANNEL_3 - * @arg @ref LL_DMA_CHANNEL_4 - * @arg @ref LL_DMA_CHANNEL_5 - * @arg @ref LL_DMA_CHANNEL_6 - * @arg @ref LL_DMA_CHANNEL_7 - * @retval Between Min_Data = 0 and Max_Data = 0xFFFFFFFF - */ -__STATIC_INLINE uint32_t LL_DMA_GetMemoryAddress(DMA_TypeDef *DMAx, uint32_t Channel) -{ - return (READ_REG(((DMA_Channel_TypeDef *)((uint32_t)((uint32_t)DMAx + CHANNEL_OFFSET_TAB[Channel - 1U])))->CMAR)); -} - -/** - * @brief Get Peripheral address. - * @note Interface used for direction LL_DMA_DIRECTION_PERIPH_TO_MEMORY or LL_DMA_DIRECTION_MEMORY_TO_PERIPH only. - * @rmtoll CPAR PA LL_DMA_GetPeriphAddress - * @param DMAx DMAx Instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_DMA_CHANNEL_1 - * @arg @ref LL_DMA_CHANNEL_2 - * @arg @ref LL_DMA_CHANNEL_3 - * @arg @ref LL_DMA_CHANNEL_4 - * @arg @ref LL_DMA_CHANNEL_5 - * @arg @ref LL_DMA_CHANNEL_6 - * @arg @ref LL_DMA_CHANNEL_7 - * @retval Between Min_Data = 0 and Max_Data = 0xFFFFFFFF - */ -__STATIC_INLINE uint32_t LL_DMA_GetPeriphAddress(DMA_TypeDef *DMAx, uint32_t Channel) -{ - return (READ_REG(((DMA_Channel_TypeDef *)((uint32_t)((uint32_t)DMAx + CHANNEL_OFFSET_TAB[Channel - 1U])))->CPAR)); -} - -/** - * @brief Set the Memory to Memory Source address. - * @note Interface used for direction LL_DMA_DIRECTION_MEMORY_TO_MEMORY only. - * @note This API must not be called when the DMA channel is enabled. - * @rmtoll CPAR PA LL_DMA_SetM2MSrcAddress - * @param DMAx DMAx Instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_DMA_CHANNEL_1 - * @arg @ref LL_DMA_CHANNEL_2 - * @arg @ref LL_DMA_CHANNEL_3 - * @arg @ref LL_DMA_CHANNEL_4 - * @arg @ref LL_DMA_CHANNEL_5 - * @arg @ref LL_DMA_CHANNEL_6 - * @arg @ref LL_DMA_CHANNEL_7 - * @param MemoryAddress Between Min_Data = 0 and Max_Data = 0xFFFFFFFF - * @retval None - */ -__STATIC_INLINE void LL_DMA_SetM2MSrcAddress(DMA_TypeDef *DMAx, uint32_t Channel, uint32_t MemoryAddress) -{ - WRITE_REG(((DMA_Channel_TypeDef *)((uint32_t)((uint32_t)DMAx + CHANNEL_OFFSET_TAB[Channel - 1U])))->CPAR, MemoryAddress); -} - -/** - * @brief Set the Memory to Memory Destination address. - * @note Interface used for direction LL_DMA_DIRECTION_MEMORY_TO_MEMORY only. - * @note This API must not be called when the DMA channel is enabled. - * @rmtoll CMAR MA LL_DMA_SetM2MDstAddress - * @param DMAx DMAx Instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_DMA_CHANNEL_1 - * @arg @ref LL_DMA_CHANNEL_2 - * @arg @ref LL_DMA_CHANNEL_3 - * @arg @ref LL_DMA_CHANNEL_4 - * @arg @ref LL_DMA_CHANNEL_5 - * @arg @ref LL_DMA_CHANNEL_6 - * @arg @ref LL_DMA_CHANNEL_7 - * @param MemoryAddress Between Min_Data = 0 and Max_Data = 0xFFFFFFFF - * @retval None - */ -__STATIC_INLINE void LL_DMA_SetM2MDstAddress(DMA_TypeDef *DMAx, uint32_t Channel, uint32_t MemoryAddress) -{ - WRITE_REG(((DMA_Channel_TypeDef *)((uint32_t)((uint32_t)DMAx + CHANNEL_OFFSET_TAB[Channel - 1U])))->CMAR, MemoryAddress); -} - -/** - * @brief Get the Memory to Memory Source address. - * @note Interface used for direction LL_DMA_DIRECTION_MEMORY_TO_MEMORY only. - * @rmtoll CPAR PA LL_DMA_GetM2MSrcAddress - * @param DMAx DMAx Instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_DMA_CHANNEL_1 - * @arg @ref LL_DMA_CHANNEL_2 - * @arg @ref LL_DMA_CHANNEL_3 - * @arg @ref LL_DMA_CHANNEL_4 - * @arg @ref LL_DMA_CHANNEL_5 - * @arg @ref LL_DMA_CHANNEL_6 - * @arg @ref LL_DMA_CHANNEL_7 - * @retval Between Min_Data = 0 and Max_Data = 0xFFFFFFFF - */ -__STATIC_INLINE uint32_t LL_DMA_GetM2MSrcAddress(DMA_TypeDef *DMAx, uint32_t Channel) -{ - return (READ_REG(((DMA_Channel_TypeDef *)((uint32_t)((uint32_t)DMAx + CHANNEL_OFFSET_TAB[Channel - 1U])))->CPAR)); -} - -/** - * @brief Get the Memory to Memory Destination address. - * @note Interface used for direction LL_DMA_DIRECTION_MEMORY_TO_MEMORY only. - * @rmtoll CMAR MA LL_DMA_GetM2MDstAddress - * @param DMAx DMAx Instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_DMA_CHANNEL_1 - * @arg @ref LL_DMA_CHANNEL_2 - * @arg @ref LL_DMA_CHANNEL_3 - * @arg @ref LL_DMA_CHANNEL_4 - * @arg @ref LL_DMA_CHANNEL_5 - * @arg @ref LL_DMA_CHANNEL_6 - * @arg @ref LL_DMA_CHANNEL_7 - * @retval Between Min_Data = 0 and Max_Data = 0xFFFFFFFF - */ -__STATIC_INLINE uint32_t LL_DMA_GetM2MDstAddress(DMA_TypeDef *DMAx, uint32_t Channel) -{ - return (READ_REG(((DMA_Channel_TypeDef *)((uint32_t)((uint32_t)DMAx + CHANNEL_OFFSET_TAB[Channel - 1U])))->CMAR)); -} - -/** - * @} - */ - -/** @defgroup DMA_LL_EF_FLAG_Management FLAG_Management - * @{ - */ - -/** - * @brief Get Channel 1 global interrupt flag. - * @rmtoll ISR GIF1 LL_DMA_IsActiveFlag_GI1 - * @param DMAx DMAx Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_DMA_IsActiveFlag_GI1(DMA_TypeDef *DMAx) -{ - return (READ_BIT(DMAx->ISR, DMA_ISR_GIF1) == (DMA_ISR_GIF1)); -} - -/** - * @brief Get Channel 2 global interrupt flag. - * @rmtoll ISR GIF2 LL_DMA_IsActiveFlag_GI2 - * @param DMAx DMAx Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_DMA_IsActiveFlag_GI2(DMA_TypeDef *DMAx) -{ - return (READ_BIT(DMAx->ISR, DMA_ISR_GIF2) == (DMA_ISR_GIF2)); -} - -/** - * @brief Get Channel 3 global interrupt flag. - * @rmtoll ISR GIF3 LL_DMA_IsActiveFlag_GI3 - * @param DMAx DMAx Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_DMA_IsActiveFlag_GI3(DMA_TypeDef *DMAx) -{ - return (READ_BIT(DMAx->ISR, DMA_ISR_GIF3) == (DMA_ISR_GIF3)); -} - -/** - * @brief Get Channel 4 global interrupt flag. - * @rmtoll ISR GIF4 LL_DMA_IsActiveFlag_GI4 - * @param DMAx DMAx Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_DMA_IsActiveFlag_GI4(DMA_TypeDef *DMAx) -{ - return (READ_BIT(DMAx->ISR, DMA_ISR_GIF4) == (DMA_ISR_GIF4)); -} - -/** - * @brief Get Channel 5 global interrupt flag. - * @rmtoll ISR GIF5 LL_DMA_IsActiveFlag_GI5 - * @param DMAx DMAx Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_DMA_IsActiveFlag_GI5(DMA_TypeDef *DMAx) -{ - return (READ_BIT(DMAx->ISR, DMA_ISR_GIF5) == (DMA_ISR_GIF5)); -} - -/** - * @brief Get Channel 6 global interrupt flag. - * @rmtoll ISR GIF6 LL_DMA_IsActiveFlag_GI6 - * @param DMAx DMAx Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_DMA_IsActiveFlag_GI6(DMA_TypeDef *DMAx) -{ - return (READ_BIT(DMAx->ISR, DMA_ISR_GIF6) == (DMA_ISR_GIF6)); -} - -/** - * @brief Get Channel 7 global interrupt flag. - * @rmtoll ISR GIF7 LL_DMA_IsActiveFlag_GI7 - * @param DMAx DMAx Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_DMA_IsActiveFlag_GI7(DMA_TypeDef *DMAx) -{ - return (READ_BIT(DMAx->ISR, DMA_ISR_GIF7) == (DMA_ISR_GIF7)); -} - -/** - * @brief Get Channel 1 transfer complete flag. - * @rmtoll ISR TCIF1 LL_DMA_IsActiveFlag_TC1 - * @param DMAx DMAx Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_DMA_IsActiveFlag_TC1(DMA_TypeDef *DMAx) -{ - return (READ_BIT(DMAx->ISR, DMA_ISR_TCIF1) == (DMA_ISR_TCIF1)); -} - -/** - * @brief Get Channel 2 transfer complete flag. - * @rmtoll ISR TCIF2 LL_DMA_IsActiveFlag_TC2 - * @param DMAx DMAx Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_DMA_IsActiveFlag_TC2(DMA_TypeDef *DMAx) -{ - return (READ_BIT(DMAx->ISR, DMA_ISR_TCIF2) == (DMA_ISR_TCIF2)); -} - -/** - * @brief Get Channel 3 transfer complete flag. - * @rmtoll ISR TCIF3 LL_DMA_IsActiveFlag_TC3 - * @param DMAx DMAx Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_DMA_IsActiveFlag_TC3(DMA_TypeDef *DMAx) -{ - return (READ_BIT(DMAx->ISR, DMA_ISR_TCIF3) == (DMA_ISR_TCIF3)); -} - -/** - * @brief Get Channel 4 transfer complete flag. - * @rmtoll ISR TCIF4 LL_DMA_IsActiveFlag_TC4 - * @param DMAx DMAx Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_DMA_IsActiveFlag_TC4(DMA_TypeDef *DMAx) -{ - return (READ_BIT(DMAx->ISR, DMA_ISR_TCIF4) == (DMA_ISR_TCIF4)); -} - -/** - * @brief Get Channel 5 transfer complete flag. - * @rmtoll ISR TCIF5 LL_DMA_IsActiveFlag_TC5 - * @param DMAx DMAx Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_DMA_IsActiveFlag_TC5(DMA_TypeDef *DMAx) -{ - return (READ_BIT(DMAx->ISR, DMA_ISR_TCIF5) == (DMA_ISR_TCIF5)); -} - -/** - * @brief Get Channel 6 transfer complete flag. - * @rmtoll ISR TCIF6 LL_DMA_IsActiveFlag_TC6 - * @param DMAx DMAx Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_DMA_IsActiveFlag_TC6(DMA_TypeDef *DMAx) -{ - return (READ_BIT(DMAx->ISR, DMA_ISR_TCIF6) == (DMA_ISR_TCIF6)); -} - -/** - * @brief Get Channel 7 transfer complete flag. - * @rmtoll ISR TCIF7 LL_DMA_IsActiveFlag_TC7 - * @param DMAx DMAx Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_DMA_IsActiveFlag_TC7(DMA_TypeDef *DMAx) -{ - return (READ_BIT(DMAx->ISR, DMA_ISR_TCIF7) == (DMA_ISR_TCIF7)); -} - -/** - * @brief Get Channel 1 half transfer flag. - * @rmtoll ISR HTIF1 LL_DMA_IsActiveFlag_HT1 - * @param DMAx DMAx Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_DMA_IsActiveFlag_HT1(DMA_TypeDef *DMAx) -{ - return (READ_BIT(DMAx->ISR, DMA_ISR_HTIF1) == (DMA_ISR_HTIF1)); -} - -/** - * @brief Get Channel 2 half transfer flag. - * @rmtoll ISR HTIF2 LL_DMA_IsActiveFlag_HT2 - * @param DMAx DMAx Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_DMA_IsActiveFlag_HT2(DMA_TypeDef *DMAx) -{ - return (READ_BIT(DMAx->ISR, DMA_ISR_HTIF2) == (DMA_ISR_HTIF2)); -} - -/** - * @brief Get Channel 3 half transfer flag. - * @rmtoll ISR HTIF3 LL_DMA_IsActiveFlag_HT3 - * @param DMAx DMAx Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_DMA_IsActiveFlag_HT3(DMA_TypeDef *DMAx) -{ - return (READ_BIT(DMAx->ISR, DMA_ISR_HTIF3) == (DMA_ISR_HTIF3)); -} - -/** - * @brief Get Channel 4 half transfer flag. - * @rmtoll ISR HTIF4 LL_DMA_IsActiveFlag_HT4 - * @param DMAx DMAx Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_DMA_IsActiveFlag_HT4(DMA_TypeDef *DMAx) -{ - return (READ_BIT(DMAx->ISR, DMA_ISR_HTIF4) == (DMA_ISR_HTIF4)); -} - -/** - * @brief Get Channel 5 half transfer flag. - * @rmtoll ISR HTIF5 LL_DMA_IsActiveFlag_HT5 - * @param DMAx DMAx Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_DMA_IsActiveFlag_HT5(DMA_TypeDef *DMAx) -{ - return (READ_BIT(DMAx->ISR, DMA_ISR_HTIF5) == (DMA_ISR_HTIF5)); -} - -/** - * @brief Get Channel 6 half transfer flag. - * @rmtoll ISR HTIF6 LL_DMA_IsActiveFlag_HT6 - * @param DMAx DMAx Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_DMA_IsActiveFlag_HT6(DMA_TypeDef *DMAx) -{ - return (READ_BIT(DMAx->ISR, DMA_ISR_HTIF6) == (DMA_ISR_HTIF6)); -} - -/** - * @brief Get Channel 7 half transfer flag. - * @rmtoll ISR HTIF7 LL_DMA_IsActiveFlag_HT7 - * @param DMAx DMAx Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_DMA_IsActiveFlag_HT7(DMA_TypeDef *DMAx) -{ - return (READ_BIT(DMAx->ISR, DMA_ISR_HTIF7) == (DMA_ISR_HTIF7)); -} - -/** - * @brief Get Channel 1 transfer error flag. - * @rmtoll ISR TEIF1 LL_DMA_IsActiveFlag_TE1 - * @param DMAx DMAx Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_DMA_IsActiveFlag_TE1(DMA_TypeDef *DMAx) -{ - return (READ_BIT(DMAx->ISR, DMA_ISR_TEIF1) == (DMA_ISR_TEIF1)); -} - -/** - * @brief Get Channel 2 transfer error flag. - * @rmtoll ISR TEIF2 LL_DMA_IsActiveFlag_TE2 - * @param DMAx DMAx Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_DMA_IsActiveFlag_TE2(DMA_TypeDef *DMAx) -{ - return (READ_BIT(DMAx->ISR, DMA_ISR_TEIF2) == (DMA_ISR_TEIF2)); -} - -/** - * @brief Get Channel 3 transfer error flag. - * @rmtoll ISR TEIF3 LL_DMA_IsActiveFlag_TE3 - * @param DMAx DMAx Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_DMA_IsActiveFlag_TE3(DMA_TypeDef *DMAx) -{ - return (READ_BIT(DMAx->ISR, DMA_ISR_TEIF3) == (DMA_ISR_TEIF3)); -} - -/** - * @brief Get Channel 4 transfer error flag. - * @rmtoll ISR TEIF4 LL_DMA_IsActiveFlag_TE4 - * @param DMAx DMAx Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_DMA_IsActiveFlag_TE4(DMA_TypeDef *DMAx) -{ - return (READ_BIT(DMAx->ISR, DMA_ISR_TEIF4) == (DMA_ISR_TEIF4)); -} - -/** - * @brief Get Channel 5 transfer error flag. - * @rmtoll ISR TEIF5 LL_DMA_IsActiveFlag_TE5 - * @param DMAx DMAx Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_DMA_IsActiveFlag_TE5(DMA_TypeDef *DMAx) -{ - return (READ_BIT(DMAx->ISR, DMA_ISR_TEIF5) == (DMA_ISR_TEIF5)); -} - -/** - * @brief Get Channel 6 transfer error flag. - * @rmtoll ISR TEIF6 LL_DMA_IsActiveFlag_TE6 - * @param DMAx DMAx Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_DMA_IsActiveFlag_TE6(DMA_TypeDef *DMAx) -{ - return (READ_BIT(DMAx->ISR, DMA_ISR_TEIF6) == (DMA_ISR_TEIF6)); -} - -/** - * @brief Get Channel 7 transfer error flag. - * @rmtoll ISR TEIF7 LL_DMA_IsActiveFlag_TE7 - * @param DMAx DMAx Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_DMA_IsActiveFlag_TE7(DMA_TypeDef *DMAx) -{ - return (READ_BIT(DMAx->ISR, DMA_ISR_TEIF7) == (DMA_ISR_TEIF7)); -} - -/** - * @brief Clear Channel 1 global interrupt flag. - * @rmtoll IFCR CGIF1 LL_DMA_ClearFlag_GI1 - * @param DMAx DMAx Instance - * @retval None - */ -__STATIC_INLINE void LL_DMA_ClearFlag_GI1(DMA_TypeDef *DMAx) -{ - WRITE_REG(DMAx->IFCR, DMA_IFCR_CGIF1); -} - -/** - * @brief Clear Channel 2 global interrupt flag. - * @rmtoll IFCR CGIF2 LL_DMA_ClearFlag_GI2 - * @param DMAx DMAx Instance - * @retval None - */ -__STATIC_INLINE void LL_DMA_ClearFlag_GI2(DMA_TypeDef *DMAx) -{ - WRITE_REG(DMAx->IFCR, DMA_IFCR_CGIF2); -} - -/** - * @brief Clear Channel 3 global interrupt flag. - * @rmtoll IFCR CGIF3 LL_DMA_ClearFlag_GI3 - * @param DMAx DMAx Instance - * @retval None - */ -__STATIC_INLINE void LL_DMA_ClearFlag_GI3(DMA_TypeDef *DMAx) -{ - WRITE_REG(DMAx->IFCR, DMA_IFCR_CGIF3); -} - -/** - * @brief Clear Channel 4 global interrupt flag. - * @rmtoll IFCR CGIF4 LL_DMA_ClearFlag_GI4 - * @param DMAx DMAx Instance - * @retval None - */ -__STATIC_INLINE void LL_DMA_ClearFlag_GI4(DMA_TypeDef *DMAx) -{ - WRITE_REG(DMAx->IFCR, DMA_IFCR_CGIF4); -} - -/** - * @brief Clear Channel 5 global interrupt flag. - * @rmtoll IFCR CGIF5 LL_DMA_ClearFlag_GI5 - * @param DMAx DMAx Instance - * @retval None - */ -__STATIC_INLINE void LL_DMA_ClearFlag_GI5(DMA_TypeDef *DMAx) -{ - WRITE_REG(DMAx->IFCR, DMA_IFCR_CGIF5); -} - -/** - * @brief Clear Channel 6 global interrupt flag. - * @rmtoll IFCR CGIF6 LL_DMA_ClearFlag_GI6 - * @param DMAx DMAx Instance - * @retval None - */ -__STATIC_INLINE void LL_DMA_ClearFlag_GI6(DMA_TypeDef *DMAx) -{ - WRITE_REG(DMAx->IFCR, DMA_IFCR_CGIF6); -} - -/** - * @brief Clear Channel 7 global interrupt flag. - * @rmtoll IFCR CGIF7 LL_DMA_ClearFlag_GI7 - * @param DMAx DMAx Instance - * @retval None - */ -__STATIC_INLINE void LL_DMA_ClearFlag_GI7(DMA_TypeDef *DMAx) -{ - WRITE_REG(DMAx->IFCR, DMA_IFCR_CGIF7); -} - -/** - * @brief Clear Channel 1 transfer complete flag. - * @rmtoll IFCR CTCIF1 LL_DMA_ClearFlag_TC1 - * @param DMAx DMAx Instance - * @retval None - */ -__STATIC_INLINE void LL_DMA_ClearFlag_TC1(DMA_TypeDef *DMAx) -{ - WRITE_REG(DMAx->IFCR, DMA_IFCR_CTCIF1); -} - -/** - * @brief Clear Channel 2 transfer complete flag. - * @rmtoll IFCR CTCIF2 LL_DMA_ClearFlag_TC2 - * @param DMAx DMAx Instance - * @retval None - */ -__STATIC_INLINE void LL_DMA_ClearFlag_TC2(DMA_TypeDef *DMAx) -{ - WRITE_REG(DMAx->IFCR, DMA_IFCR_CTCIF2); -} - -/** - * @brief Clear Channel 3 transfer complete flag. - * @rmtoll IFCR CTCIF3 LL_DMA_ClearFlag_TC3 - * @param DMAx DMAx Instance - * @retval None - */ -__STATIC_INLINE void LL_DMA_ClearFlag_TC3(DMA_TypeDef *DMAx) -{ - WRITE_REG(DMAx->IFCR, DMA_IFCR_CTCIF3); -} - -/** - * @brief Clear Channel 4 transfer complete flag. - * @rmtoll IFCR CTCIF4 LL_DMA_ClearFlag_TC4 - * @param DMAx DMAx Instance - * @retval None - */ -__STATIC_INLINE void LL_DMA_ClearFlag_TC4(DMA_TypeDef *DMAx) -{ - WRITE_REG(DMAx->IFCR, DMA_IFCR_CTCIF4); -} - -/** - * @brief Clear Channel 5 transfer complete flag. - * @rmtoll IFCR CTCIF5 LL_DMA_ClearFlag_TC5 - * @param DMAx DMAx Instance - * @retval None - */ -__STATIC_INLINE void LL_DMA_ClearFlag_TC5(DMA_TypeDef *DMAx) -{ - WRITE_REG(DMAx->IFCR, DMA_IFCR_CTCIF5); -} - -/** - * @brief Clear Channel 6 transfer complete flag. - * @rmtoll IFCR CTCIF6 LL_DMA_ClearFlag_TC6 - * @param DMAx DMAx Instance - * @retval None - */ -__STATIC_INLINE void LL_DMA_ClearFlag_TC6(DMA_TypeDef *DMAx) -{ - WRITE_REG(DMAx->IFCR, DMA_IFCR_CTCIF6); -} - -/** - * @brief Clear Channel 7 transfer complete flag. - * @rmtoll IFCR CTCIF7 LL_DMA_ClearFlag_TC7 - * @param DMAx DMAx Instance - * @retval None - */ -__STATIC_INLINE void LL_DMA_ClearFlag_TC7(DMA_TypeDef *DMAx) -{ - WRITE_REG(DMAx->IFCR, DMA_IFCR_CTCIF7); -} - -/** - * @brief Clear Channel 1 half transfer flag. - * @rmtoll IFCR CHTIF1 LL_DMA_ClearFlag_HT1 - * @param DMAx DMAx Instance - * @retval None - */ -__STATIC_INLINE void LL_DMA_ClearFlag_HT1(DMA_TypeDef *DMAx) -{ - WRITE_REG(DMAx->IFCR, DMA_IFCR_CHTIF1); -} - -/** - * @brief Clear Channel 2 half transfer flag. - * @rmtoll IFCR CHTIF2 LL_DMA_ClearFlag_HT2 - * @param DMAx DMAx Instance - * @retval None - */ -__STATIC_INLINE void LL_DMA_ClearFlag_HT2(DMA_TypeDef *DMAx) -{ - WRITE_REG(DMAx->IFCR, DMA_IFCR_CHTIF2); -} - -/** - * @brief Clear Channel 3 half transfer flag. - * @rmtoll IFCR CHTIF3 LL_DMA_ClearFlag_HT3 - * @param DMAx DMAx Instance - * @retval None - */ -__STATIC_INLINE void LL_DMA_ClearFlag_HT3(DMA_TypeDef *DMAx) -{ - WRITE_REG(DMAx->IFCR, DMA_IFCR_CHTIF3); -} - -/** - * @brief Clear Channel 4 half transfer flag. - * @rmtoll IFCR CHTIF4 LL_DMA_ClearFlag_HT4 - * @param DMAx DMAx Instance - * @retval None - */ -__STATIC_INLINE void LL_DMA_ClearFlag_HT4(DMA_TypeDef *DMAx) -{ - WRITE_REG(DMAx->IFCR, DMA_IFCR_CHTIF4); -} - -/** - * @brief Clear Channel 5 half transfer flag. - * @rmtoll IFCR CHTIF5 LL_DMA_ClearFlag_HT5 - * @param DMAx DMAx Instance - * @retval None - */ -__STATIC_INLINE void LL_DMA_ClearFlag_HT5(DMA_TypeDef *DMAx) -{ - WRITE_REG(DMAx->IFCR, DMA_IFCR_CHTIF5); -} - -/** - * @brief Clear Channel 6 half transfer flag. - * @rmtoll IFCR CHTIF6 LL_DMA_ClearFlag_HT6 - * @param DMAx DMAx Instance - * @retval None - */ -__STATIC_INLINE void LL_DMA_ClearFlag_HT6(DMA_TypeDef *DMAx) -{ - WRITE_REG(DMAx->IFCR, DMA_IFCR_CHTIF6); -} - -/** - * @brief Clear Channel 7 half transfer flag. - * @rmtoll IFCR CHTIF7 LL_DMA_ClearFlag_HT7 - * @param DMAx DMAx Instance - * @retval None - */ -__STATIC_INLINE void LL_DMA_ClearFlag_HT7(DMA_TypeDef *DMAx) -{ - WRITE_REG(DMAx->IFCR, DMA_IFCR_CHTIF7); -} - -/** - * @brief Clear Channel 1 transfer error flag. - * @rmtoll IFCR CTEIF1 LL_DMA_ClearFlag_TE1 - * @param DMAx DMAx Instance - * @retval None - */ -__STATIC_INLINE void LL_DMA_ClearFlag_TE1(DMA_TypeDef *DMAx) -{ - WRITE_REG(DMAx->IFCR, DMA_IFCR_CTEIF1); -} - -/** - * @brief Clear Channel 2 transfer error flag. - * @rmtoll IFCR CTEIF2 LL_DMA_ClearFlag_TE2 - * @param DMAx DMAx Instance - * @retval None - */ -__STATIC_INLINE void LL_DMA_ClearFlag_TE2(DMA_TypeDef *DMAx) -{ - WRITE_REG(DMAx->IFCR, DMA_IFCR_CTEIF2); -} - -/** - * @brief Clear Channel 3 transfer error flag. - * @rmtoll IFCR CTEIF3 LL_DMA_ClearFlag_TE3 - * @param DMAx DMAx Instance - * @retval None - */ -__STATIC_INLINE void LL_DMA_ClearFlag_TE3(DMA_TypeDef *DMAx) -{ - WRITE_REG(DMAx->IFCR, DMA_IFCR_CTEIF3); -} - -/** - * @brief Clear Channel 4 transfer error flag. - * @rmtoll IFCR CTEIF4 LL_DMA_ClearFlag_TE4 - * @param DMAx DMAx Instance - * @retval None - */ -__STATIC_INLINE void LL_DMA_ClearFlag_TE4(DMA_TypeDef *DMAx) -{ - WRITE_REG(DMAx->IFCR, DMA_IFCR_CTEIF4); -} - -/** - * @brief Clear Channel 5 transfer error flag. - * @rmtoll IFCR CTEIF5 LL_DMA_ClearFlag_TE5 - * @param DMAx DMAx Instance - * @retval None - */ -__STATIC_INLINE void LL_DMA_ClearFlag_TE5(DMA_TypeDef *DMAx) -{ - WRITE_REG(DMAx->IFCR, DMA_IFCR_CTEIF5); -} - -/** - * @brief Clear Channel 6 transfer error flag. - * @rmtoll IFCR CTEIF6 LL_DMA_ClearFlag_TE6 - * @param DMAx DMAx Instance - * @retval None - */ -__STATIC_INLINE void LL_DMA_ClearFlag_TE6(DMA_TypeDef *DMAx) -{ - WRITE_REG(DMAx->IFCR, DMA_IFCR_CTEIF6); -} - -/** - * @brief Clear Channel 7 transfer error flag. - * @rmtoll IFCR CTEIF7 LL_DMA_ClearFlag_TE7 - * @param DMAx DMAx Instance - * @retval None - */ -__STATIC_INLINE void LL_DMA_ClearFlag_TE7(DMA_TypeDef *DMAx) -{ - WRITE_REG(DMAx->IFCR, DMA_IFCR_CTEIF7); -} - -/** - * @} - */ - -/** @defgroup DMA_LL_EF_IT_Management IT_Management - * @{ - */ - -/** - * @brief Enable Transfer complete interrupt. - * @rmtoll CCR TCIE LL_DMA_EnableIT_TC - * @param DMAx DMAx Instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_DMA_CHANNEL_1 - * @arg @ref LL_DMA_CHANNEL_2 - * @arg @ref LL_DMA_CHANNEL_3 - * @arg @ref LL_DMA_CHANNEL_4 - * @arg @ref LL_DMA_CHANNEL_5 - * @arg @ref LL_DMA_CHANNEL_6 - * @arg @ref LL_DMA_CHANNEL_7 - * @retval None - */ -__STATIC_INLINE void LL_DMA_EnableIT_TC(DMA_TypeDef *DMAx, uint32_t Channel) -{ - SET_BIT(((DMA_Channel_TypeDef *)((uint32_t)((uint32_t)DMAx + CHANNEL_OFFSET_TAB[Channel - 1U])))->CCR, DMA_CCR_TCIE); -} - -/** - * @brief Enable Half transfer interrupt. - * @rmtoll CCR HTIE LL_DMA_EnableIT_HT - * @param DMAx DMAx Instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_DMA_CHANNEL_1 - * @arg @ref LL_DMA_CHANNEL_2 - * @arg @ref LL_DMA_CHANNEL_3 - * @arg @ref LL_DMA_CHANNEL_4 - * @arg @ref LL_DMA_CHANNEL_5 - * @arg @ref LL_DMA_CHANNEL_6 - * @arg @ref LL_DMA_CHANNEL_7 - * @retval None - */ -__STATIC_INLINE void LL_DMA_EnableIT_HT(DMA_TypeDef *DMAx, uint32_t Channel) -{ - SET_BIT(((DMA_Channel_TypeDef *)((uint32_t)((uint32_t)DMAx + CHANNEL_OFFSET_TAB[Channel - 1U])))->CCR, DMA_CCR_HTIE); -} - -/** - * @brief Enable Transfer error interrupt. - * @rmtoll CCR TEIE LL_DMA_EnableIT_TE - * @param DMAx DMAx Instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_DMA_CHANNEL_1 - * @arg @ref LL_DMA_CHANNEL_2 - * @arg @ref LL_DMA_CHANNEL_3 - * @arg @ref LL_DMA_CHANNEL_4 - * @arg @ref LL_DMA_CHANNEL_5 - * @arg @ref LL_DMA_CHANNEL_6 - * @arg @ref LL_DMA_CHANNEL_7 - * @retval None - */ -__STATIC_INLINE void LL_DMA_EnableIT_TE(DMA_TypeDef *DMAx, uint32_t Channel) -{ - SET_BIT(((DMA_Channel_TypeDef *)((uint32_t)((uint32_t)DMAx + CHANNEL_OFFSET_TAB[Channel - 1U])))->CCR, DMA_CCR_TEIE); -} - -/** - * @brief Disable Transfer complete interrupt. - * @rmtoll CCR TCIE LL_DMA_DisableIT_TC - * @param DMAx DMAx Instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_DMA_CHANNEL_1 - * @arg @ref LL_DMA_CHANNEL_2 - * @arg @ref LL_DMA_CHANNEL_3 - * @arg @ref LL_DMA_CHANNEL_4 - * @arg @ref LL_DMA_CHANNEL_5 - * @arg @ref LL_DMA_CHANNEL_6 - * @arg @ref LL_DMA_CHANNEL_7 - * @retval None - */ -__STATIC_INLINE void LL_DMA_DisableIT_TC(DMA_TypeDef *DMAx, uint32_t Channel) -{ - CLEAR_BIT(((DMA_Channel_TypeDef *)((uint32_t)((uint32_t)DMAx + CHANNEL_OFFSET_TAB[Channel - 1U])))->CCR, DMA_CCR_TCIE); -} - -/** - * @brief Disable Half transfer interrupt. - * @rmtoll CCR HTIE LL_DMA_DisableIT_HT - * @param DMAx DMAx Instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_DMA_CHANNEL_1 - * @arg @ref LL_DMA_CHANNEL_2 - * @arg @ref LL_DMA_CHANNEL_3 - * @arg @ref LL_DMA_CHANNEL_4 - * @arg @ref LL_DMA_CHANNEL_5 - * @arg @ref LL_DMA_CHANNEL_6 - * @arg @ref LL_DMA_CHANNEL_7 - * @retval None - */ -__STATIC_INLINE void LL_DMA_DisableIT_HT(DMA_TypeDef *DMAx, uint32_t Channel) -{ - CLEAR_BIT(((DMA_Channel_TypeDef *)((uint32_t)((uint32_t)DMAx + CHANNEL_OFFSET_TAB[Channel - 1U])))->CCR, DMA_CCR_HTIE); -} - -/** - * @brief Disable Transfer error interrupt. - * @rmtoll CCR TEIE LL_DMA_DisableIT_TE - * @param DMAx DMAx Instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_DMA_CHANNEL_1 - * @arg @ref LL_DMA_CHANNEL_2 - * @arg @ref LL_DMA_CHANNEL_3 - * @arg @ref LL_DMA_CHANNEL_4 - * @arg @ref LL_DMA_CHANNEL_5 - * @arg @ref LL_DMA_CHANNEL_6 - * @arg @ref LL_DMA_CHANNEL_7 - * @retval None - */ -__STATIC_INLINE void LL_DMA_DisableIT_TE(DMA_TypeDef *DMAx, uint32_t Channel) -{ - CLEAR_BIT(((DMA_Channel_TypeDef *)((uint32_t)((uint32_t)DMAx + CHANNEL_OFFSET_TAB[Channel - 1U])))->CCR, DMA_CCR_TEIE); -} - -/** - * @brief Check if Transfer complete Interrupt is enabled. - * @rmtoll CCR TCIE LL_DMA_IsEnabledIT_TC - * @param DMAx DMAx Instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_DMA_CHANNEL_1 - * @arg @ref LL_DMA_CHANNEL_2 - * @arg @ref LL_DMA_CHANNEL_3 - * @arg @ref LL_DMA_CHANNEL_4 - * @arg @ref LL_DMA_CHANNEL_5 - * @arg @ref LL_DMA_CHANNEL_6 - * @arg @ref LL_DMA_CHANNEL_7 - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_DMA_IsEnabledIT_TC(DMA_TypeDef *DMAx, uint32_t Channel) -{ - return (READ_BIT(((DMA_Channel_TypeDef *)((uint32_t)((uint32_t)DMAx + CHANNEL_OFFSET_TAB[Channel - 1U])))->CCR, - DMA_CCR_TCIE) == (DMA_CCR_TCIE)); -} - -/** - * @brief Check if Half transfer Interrupt is enabled. - * @rmtoll CCR HTIE LL_DMA_IsEnabledIT_HT - * @param DMAx DMAx Instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_DMA_CHANNEL_1 - * @arg @ref LL_DMA_CHANNEL_2 - * @arg @ref LL_DMA_CHANNEL_3 - * @arg @ref LL_DMA_CHANNEL_4 - * @arg @ref LL_DMA_CHANNEL_5 - * @arg @ref LL_DMA_CHANNEL_6 - * @arg @ref LL_DMA_CHANNEL_7 - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_DMA_IsEnabledIT_HT(DMA_TypeDef *DMAx, uint32_t Channel) -{ - return (READ_BIT(((DMA_Channel_TypeDef *)((uint32_t)((uint32_t)DMAx + CHANNEL_OFFSET_TAB[Channel - 1U])))->CCR, - DMA_CCR_HTIE) == (DMA_CCR_HTIE)); -} - -/** - * @brief Check if Transfer error Interrupt is enabled. - * @rmtoll CCR TEIE LL_DMA_IsEnabledIT_TE - * @param DMAx DMAx Instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_DMA_CHANNEL_1 - * @arg @ref LL_DMA_CHANNEL_2 - * @arg @ref LL_DMA_CHANNEL_3 - * @arg @ref LL_DMA_CHANNEL_4 - * @arg @ref LL_DMA_CHANNEL_5 - * @arg @ref LL_DMA_CHANNEL_6 - * @arg @ref LL_DMA_CHANNEL_7 - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_DMA_IsEnabledIT_TE(DMA_TypeDef *DMAx, uint32_t Channel) -{ - return (READ_BIT(((DMA_Channel_TypeDef *)((uint32_t)((uint32_t)DMAx + CHANNEL_OFFSET_TAB[Channel - 1U])))->CCR, - DMA_CCR_TEIE) == (DMA_CCR_TEIE)); -} - -/** - * @} - */ - -#if defined(USE_FULL_LL_DRIVER) -/** @defgroup DMA_LL_EF_Init Initialization and de-initialization functions - * @{ - */ - -uint32_t LL_DMA_Init(DMA_TypeDef *DMAx, uint32_t Channel, LL_DMA_InitTypeDef *DMA_InitStruct); -uint32_t LL_DMA_DeInit(DMA_TypeDef *DMAx, uint32_t Channel); -void LL_DMA_StructInit(LL_DMA_InitTypeDef *DMA_InitStruct); - -/** - * @} - */ -#endif /* USE_FULL_LL_DRIVER */ - -/** - * @} - */ - -/** - * @} - */ - -#endif /* DMA1 || DMA2 */ - -/** - * @} - */ - -#ifdef __cplusplus -} -#endif - -#endif /* __STM32F1xx_LL_DMA_H */ - -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_exti.c b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_exti.c index c3d094ad66d..2715899a428 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_exti.c +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_exti.c @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_ll_exti.c * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version $VERSION$ + * @date $DATE$ * @brief EXTI LL module driver. ****************************************************************************** * @attention @@ -107,7 +107,7 @@ uint32_t LL_EXTI_DeInit(void) LL_EXTI_WriteReg(FTSR, 0x00000000U); /* Software interrupt event register set to default reset values */ LL_EXTI_WriteReg(SWIER, 0x00000000U); - /* Pending register clear */ + /* Pending register set to default reset values */ LL_EXTI_WriteReg(PR, 0x000FFFFFU); return SUCCESS; diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_exti.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_exti.h index 38e337815db..5146fc04c82 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_exti.h +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_exti.h @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_ll_exti.h * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version $VERSION$ + * @date $DATE$ * @brief Header file of EXTI LL module. ****************************************************************************** * @attention @@ -167,10 +167,10 @@ typedef struct #define LL_EXTI_LINE_ALL_0_31 EXTI_IMR_IM /*!< All Extended line not reserved*/ -#define LL_EXTI_LINE_ALL (0xFFFFFFFFU) /*!< All Extended line */ +#define LL_EXTI_LINE_ALL ((uint32_t)0xFFFFFFFFU) /*!< All Extended line */ #if defined(USE_FULL_LL_DRIVER) -#define LL_EXTI_LINE_NONE (0x00000000U) /*!< None Extended line */ +#define LL_EXTI_LINE_NONE ((uint32_t)0x00000000U) /*!< None Extended line */ #endif /*USE_FULL_LL_DRIVER*/ /** @@ -181,9 +181,9 @@ typedef struct /** @defgroup EXTI_LL_EC_MODE Mode * @{ */ -#define LL_EXTI_MODE_IT ((uint8_t)0x00) /*!< Interrupt Mode */ -#define LL_EXTI_MODE_EVENT ((uint8_t)0x01) /*!< Event Mode */ -#define LL_EXTI_MODE_IT_EVENT ((uint8_t)0x02) /*!< Interrupt & Event Mode */ +#define LL_EXTI_MODE_IT ((uint8_t)0x00U) /*!< Interrupt Mode */ +#define LL_EXTI_MODE_EVENT ((uint8_t)0x01U) /*!< Event Mode */ +#define LL_EXTI_MODE_IT_EVENT ((uint8_t)0x02U) /*!< Interrupt & Event Mode */ /** * @} */ @@ -191,10 +191,10 @@ typedef struct /** @defgroup EXTI_LL_EC_TRIGGER Edge Trigger * @{ */ -#define LL_EXTI_TRIGGER_NONE ((uint8_t)0x00) /*!< No Trigger Mode */ -#define LL_EXTI_TRIGGER_RISING ((uint8_t)0x01) /*!< Trigger Rising Mode */ -#define LL_EXTI_TRIGGER_FALLING ((uint8_t)0x02) /*!< Trigger Falling Mode */ -#define LL_EXTI_TRIGGER_RISING_FALLING ((uint8_t)0x03) /*!< Trigger Rising & Falling Mode */ +#define LL_EXTI_TRIGGER_NONE ((uint8_t)0x00U) /*!< No Trigger Mode */ +#define LL_EXTI_TRIGGER_RISING ((uint8_t)0x01U) /*!< Trigger Rising Mode */ +#define LL_EXTI_TRIGGER_FALLING ((uint8_t)0x02U) /*!< Trigger Falling Mode */ +#define LL_EXTI_TRIGGER_RISING_FALLING ((uint8_t)0x03U) /*!< Trigger Rising & Falling Mode */ /** * @} diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_fsmc.c b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_fsmc.c index ecff5920e37..16da9a93273 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_fsmc.c +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_fsmc.c @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_ll_fsmc.c * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief FSMC Low Layer HAL module driver. * * This file provides firmware functions to manage the following @@ -35,17 +35,17 @@ (++) Static random access memory (SRAM). (++) NOR Flash memory. (++) PSRAM (4 memory banks). - (++) 16-bit PC Card compatible devices. + (++) 16-bit PC Card compatible devices (++) Two banks of NAND Flash memory with ECC hardware to check up to 8 Kbytes of - data. - (+) Independent Chip Select control for each memory bank. - (+) Independent configuration for each memory bank. - + data + (+) Independent Chip Select control for each memory bank + (+) Independent configuration for each memory bank + @endverbatim ****************************************************************************** * @attention * - *

© COPYRIGHT(c) 2017 STMicroelectronics

+ *

© COPYRIGHT(c) 2016 STMicroelectronics

* * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: @@ -79,10 +79,10 @@ * @{ */ -#if defined(FSMC_BANK1) - #if defined(HAL_SRAM_MODULE_ENABLED) || defined(HAL_NOR_MODULE_ENABLED) || defined(HAL_PCCARD_MODULE_ENABLED) || defined(HAL_NAND_MODULE_ENABLED) +#if defined(FSMC_BANK1) + /** @defgroup FSMC_LL FSMC Low Layer * @brief FSMC driver modules * @{ @@ -90,7 +90,78 @@ /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ +/** @defgroup FSMC_LL_Private_Constants FSMC Low Layer Private Constants + * @{ + */ + +/* ----------------------- FSMC registers bit mask --------------------------- */ +/* --- PCR Register ---*/ +/* PCR register clear mask */ +#define PCR_CLEAR_MASK ((uint32_t)(FSMC_PCRx_PWAITEN | FSMC_PCRx_PBKEN | \ + FSMC_PCRx_PTYP | FSMC_PCRx_PWID | \ + FSMC_PCRx_ECCEN | FSMC_PCRx_TCLR | \ + FSMC_PCRx_TAR | FSMC_PCRx_ECCPS)) + +/* --- SR Register ---*/ +/* SR register clear mask */ +#define SR_CLEAR_MASK ((uint32_t)(FSMC_SRx_IRS | FSMC_SRx_ILS | FSMC_SRx_IFS | \ + FSMC_SRx_IREN | FSMC_SRx_ILEN | FSMC_SRx_IFEN)) + +/* --- PMEM Register ---*/ +/* PMEM register clear mask */ +#define PMEM_CLEAR_MASK ((uint32_t)(FSMC_PMEMx_MEMSETx | FSMC_PMEMx_MEMWAITx |\ + FSMC_PMEMx_MEMHOLDx | FSMC_PMEMx_MEMHIZx)) + +/* --- PATT Register ---*/ +/* PATT register clear mask */ +#define PATT_CLEAR_MASK ((uint32_t)(FSMC_PATTx_ATTSETx | FSMC_PATTx_ATTWAITx |\ + FSMC_PATTx_ATTHOLDx | FSMC_PATTx_ATTHIZx)) + +/* --- BCR Register ---*/ +/* BCR register clear mask */ +#define BCR_CLEAR_MASK ((uint32_t)(FSMC_BCRx_FACCEN | FSMC_BCRx_MUXEN | \ + FSMC_BCRx_MTYP | FSMC_BCRx_MWID | \ + FSMC_BCRx_BURSTEN | FSMC_BCRx_WAITPOL | \ + FSMC_BCRx_WRAPMOD | FSMC_BCRx_WAITCFG | \ + FSMC_BCRx_WREN | FSMC_BCRx_WAITEN | \ + FSMC_BCRx_EXTMOD | FSMC_BCRx_ASYNCWAIT | \ + FSMC_BCRx_CBURSTRW)) +/* --- BTR Register ---*/ +/* BTR register clear mask */ +#define BTR_CLEAR_MASK ((uint32_t)(FSMC_BTRx_ADDSET | FSMC_BTRx_ADDHLD |\ + FSMC_BTRx_DATAST | FSMC_BTRx_BUSTURN |\ + FSMC_BTRx_CLKDIV | FSMC_BTRx_DATLAT |\ + FSMC_BTRx_ACCMOD)) + +/* --- BWTR Register ---*/ +/* BWTR register clear mask */ +#if (defined(STM32F101xE) || defined(STM32F103xE) || defined(STM32F101xG) || defined(STM32F103xG)) +#define BWTR_CLEAR_MASK ((uint32_t)(FSMC_BWTRx_ADDSET | FSMC_BWTRx_ADDHLD | \ + FSMC_BWTRx_DATAST | FSMC_BWTRx_ACCMOD | \ + FSMC_BWTRx_BUSTURN)) +#else +#define BWTR_CLEAR_MASK ((uint32_t)(FSMC_BWTRx_ADDSET | FSMC_BWTRx_ADDHLD | \ + FSMC_BWTRx_DATAST | FSMC_BWTRx_ACCMOD | \ + FSMC_BWTRx_CLKDIV | FSMC_BWTRx_DATLAT)) +#endif /* STM32F101xE || STM32F103xE || STM32F101xG || STM32F103xG */ + +/* --- PIO4 Register ---*/ +/* PIO4 register clear mask */ +#define PIO4_CLEAR_MASK ((uint32_t)(FSMC_PIO4_IOSET4 | FSMC_PIO4_IOWAIT4 | \ + FSMC_PIO4_IOHOLD4 | FSMC_PIO4_IOHIZ4)) +/** + * @} + */ + /* Private macro -------------------------------------------------------------*/ +/** @defgroup FSMC_LL_Private_Macros FSMC Low Layer Private Macros + * @{ + */ + +/** + * @} + */ + /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ @@ -119,12 +190,13 @@ (+) FSMC NORSRAM bank enable/disable write operation using the functions FSMC_NORSRAM_WriteOperation_Enable()/FSMC_NORSRAM_WriteOperation_Disable() + @endverbatim * @{ */ - -/** @addtogroup FSMC_LL_NORSRAM_Private_Functions_Group1 - * @brief Initialization and Configuration functions + +/** @defgroup FSMC_NORSRAM_Group1 Initialization/de-initialization functions + * @brief Initialization and Configuration functions * @verbatim ============================================================================== @@ -209,11 +281,12 @@ HAL_StatusTypeDef FSMC_NORSRAM_Init(FSMC_NORSRAM_TypeDef *Device, FSMC_NORSRAM_ return HAL_OK; } + /** - * @brief DeInitialize the FSMC_NORSRAM peripheral + * @brief DeInitialize the FSMC_NORSRAM peripheral * @param Device: Pointer to NORSRAM device instance * @param ExDevice: Pointer to NORSRAM extended mode device instance - * @param Bank: NORSRAM bank number + * @param Bank: NORSRAM bank number * @retval HAL status */ HAL_StatusTypeDef FSMC_NORSRAM_DeInit(FSMC_NORSRAM_TypeDef *Device, FSMC_NORSRAM_EXTENDED_TypeDef *ExDevice, uint32_t Bank) @@ -228,19 +301,19 @@ HAL_StatusTypeDef FSMC_NORSRAM_DeInit(FSMC_NORSRAM_TypeDef *Device, FSMC_NORSRAM /* De-initialize the FSMC_NORSRAM device */ /* FSMC_NORSRAM_BANK1 */ - if(Bank == FSMC_NORSRAM_BANK1) + if (Bank == FSMC_NORSRAM_BANK1) { - Device->BTCR[Bank] = 0x000030DBU; + Device->BTCR[Bank] = 0x000030DB; } /* FSMC_NORSRAM_BANK2, FSMC_NORSRAM_BANK3 or FSMC_NORSRAM_BANK4 */ else - { - Device->BTCR[Bank] = 0x000030D2U; + { + Device->BTCR[Bank] = 0x000030D2; } - - Device->BTCR[Bank + 1U] = 0x0FFFFFFFU; - ExDevice->BWTR[Bank] = 0x0FFFFFFFU; - + + Device->BTCR[Bank + 1] = 0x0FFFFFFF; + ExDevice->BWTR[Bank] = 0x0FFFFFFF; + return HAL_OK; } @@ -267,14 +340,14 @@ HAL_StatusTypeDef FSMC_NORSRAM_Timing_Init(FSMC_NORSRAM_TypeDef *Device, FSMC_NO assert_param(IS_FSMC_NORSRAM_BANK(Bank)); /* Set FSMC_NORSRAM device timing parameters */ - MODIFY_REG(Device->BTCR[Bank + 1U], \ - BTR_CLEAR_MASK, \ - (uint32_t)(Timing->AddressSetupTime | \ - ((Timing->AddressHoldTime) << FSMC_BTRx_ADDHLD_Pos) | \ - ((Timing->DataSetupTime) << FSMC_BTRx_DATAST_Pos) | \ - ((Timing->BusTurnAroundDuration) << FSMC_BTRx_BUSTURN_Pos) | \ - (((Timing->CLKDivision) - 1U) << FSMC_BTRx_CLKDIV_Pos) | \ - (((Timing->DataLatency) - 2U) << FSMC_BTRx_DATLAT_Pos) | \ + MODIFY_REG(Device->BTCR[Bank + 1], \ + BTR_CLEAR_MASK, \ + (uint32_t)(Timing->AddressSetupTime | \ + ((Timing->AddressHoldTime) << POSITION_VAL(FSMC_BTRx_ADDHLD)) | \ + ((Timing->DataSetupTime) << POSITION_VAL(FSMC_BTRx_DATAST)) | \ + ((Timing->BusTurnAroundDuration) << POSITION_VAL(FSMC_BTRx_BUSTURN)) | \ + (((Timing->CLKDivision) - 1) << POSITION_VAL(FSMC_BTRx_CLKDIV)) | \ + (((Timing->DataLatency) - 2) << POSITION_VAL(FSMC_BTRx_DATLAT)) | \ (Timing->AccessMode))); return HAL_OK; @@ -286,7 +359,7 @@ HAL_StatusTypeDef FSMC_NORSRAM_Timing_Init(FSMC_NORSRAM_TypeDef *Device, FSMC_NO * @param Device: Pointer to NORSRAM device instance * @param Timing: Pointer to NORSRAM Timing structure * @param Bank: NORSRAM bank number - * @param ExtendedMode FSMC Extended Mode + * @param ExtendedMode: FSMC Extended Mode * This parameter can be one of the following values: * @arg FSMC_EXTENDED_MODE_DISABLE * @arg FSMC_EXTENDED_MODE_ENABLE @@ -298,14 +371,14 @@ HAL_StatusTypeDef FSMC_NORSRAM_Extended_Timing_Init(FSMC_NORSRAM_EXTENDED_TypeD assert_param(IS_FSMC_EXTENDED_MODE(ExtendedMode)); /* Set NORSRAM device timing register for write configuration, if extended mode is used */ - if(ExtendedMode == FSMC_EXTENDED_MODE_ENABLE) + if (ExtendedMode == FSMC_EXTENDED_MODE_ENABLE) { /* Check the parameters */ assert_param(IS_FSMC_NORSRAM_EXTENDED_DEVICE(Device)); assert_param(IS_FSMC_ADDRESS_SETUP_TIME(Timing->AddressSetupTime)); assert_param(IS_FSMC_ADDRESS_HOLD_TIME(Timing->AddressHoldTime)); assert_param(IS_FSMC_DATASETUP_TIME(Timing->DataSetupTime)); -#if defined(STM32F101xE) || defined(STM32F103xE) || defined(STM32F101xG) || defined(STM32F103xG) +#if (defined(STM32F101xE) || defined(STM32F103xE) || defined(STM32F101xG) || defined(STM32F103xG)) assert_param(IS_FSMC_TURNAROUND_TIME(Timing->BusTurnAroundDuration)); #else assert_param(IS_FSMC_CLK_DIV(Timing->CLKDivision)); @@ -315,39 +388,42 @@ HAL_StatusTypeDef FSMC_NORSRAM_Extended_Timing_Init(FSMC_NORSRAM_EXTENDED_TypeD assert_param(IS_FSMC_NORSRAM_BANK(Bank)); /* Set NORSRAM device timing register for write configuration, if extended mode is used */ -#if defined(STM32F101xE) || defined(STM32F103xE) || defined(STM32F101xG) || defined(STM32F103xG) - MODIFY_REG(Device->BWTR[Bank], \ - BWTR_CLEAR_MASK, \ - (uint32_t)(Timing->AddressSetupTime | \ - ((Timing->AddressHoldTime) << FSMC_BWTRx_ADDHLD_Pos) | \ - ((Timing->DataSetupTime) << FSMC_BWTRx_DATAST_Pos) | \ - Timing->AccessMode | \ - ((Timing->BusTurnAroundDuration) << FSMC_BWTRx_BUSTURN_Pos))); +#if (defined(STM32F101xE) || defined(STM32F103xE) || defined(STM32F101xG) || defined(STM32F103xG)) + MODIFY_REG(Device->BWTR[Bank], \ + BWTR_CLEAR_MASK, \ + (uint32_t)(Timing->AddressSetupTime | \ + ((Timing->AddressHoldTime) << POSITION_VAL(FSMC_BWTRx_ADDHLD)) | \ + ((Timing->DataSetupTime) << POSITION_VAL(FSMC_BWTRx_DATAST)) | \ + Timing->AccessMode | \ + ((Timing->BusTurnAroundDuration) << POSITION_VAL(FSMC_BWTRx_BUSTURN)))); #else - MODIFY_REG(Device->BWTR[Bank], \ - BWTR_CLEAR_MASK, \ - (uint32_t)(Timing->AddressSetupTime | \ - ((Timing->AddressHoldTime) << FSMC_BWTRx_ADDHLD_Pos) | \ - ((Timing->DataSetupTime) << FSMC_BWTRx_DATAST_Pos) | \ - Timing->AccessMode | \ - (((Timing->CLKDivision) - 1U) << FSMC_BTRx_CLKDIV_Pos) | \ - (((Timing->DataLatency) - 2U) << FSMC_BWTRx_DATLAT_Pos))); + MODIFY_REG(Device->BWTR[Bank], \ + BWTR_CLEAR_MASK, \ + (uint32_t)(Timing->AddressSetupTime | \ + ((Timing->AddressHoldTime) << POSITION_VAL(FSMC_BWTRx_ADDHLD)) | \ + ((Timing->DataSetupTime) << POSITION_VAL(FSMC_BWTRx_DATAST)) | \ + Timing->AccessMode | \ + (((Timing->CLKDivision) - 1) << POSITION_VAL(FSMC_BTRx_CLKDIV)) | \ + (((Timing->DataLatency) - 2) << POSITION_VAL(FSMC_BWTRx_DATLAT)))); #endif /* STM32F101xE || STM32F103xE || STM32F101xG || STM32F103xG */ } else { - Device->BWTR[Bank] = 0x0FFFFFFFU; + Device->BWTR[Bank] = 0x0FFFFFFF; } return HAL_OK; } + + /** * @} */ + /** @defgroup FSMC_NORSRAM_Group2 Control functions - * @brief management functions - * + * @brief management functions + * @verbatim ============================================================================== ##### FSMC_NORSRAM Control functions ##### @@ -395,6 +471,7 @@ HAL_StatusTypeDef FSMC_NORSRAM_WriteOperation_Disable(FSMC_NORSRAM_TypeDef *Devi return HAL_OK; } + /** * @} */ @@ -402,7 +479,6 @@ HAL_StatusTypeDef FSMC_NORSRAM_WriteOperation_Disable(FSMC_NORSRAM_TypeDef *Devi /** * @} */ - #if (defined (STM32F101xE) || defined(STM32F103xE) || defined(STM32F101xG) || defined(STM32F103xG)) /** @defgroup FSMC_NAND FSMC NAND Controller functions * @brief NAND Controller functions @@ -430,8 +506,8 @@ HAL_StatusTypeDef FSMC_NORSRAM_WriteOperation_Disable(FSMC_NORSRAM_TypeDef *Devi */ /** @defgroup FSMC_NAND_Exported_Functions_Group1 Initialization and de-initialization functions - * @brief Initialization and Configuration functions - * + * @brief Initialization and Configuration functions + * @verbatim ============================================================================== ##### Initialization and de_initialization functions ##### @@ -469,27 +545,28 @@ HAL_StatusTypeDef FSMC_NAND_Init(FSMC_NAND_TypeDef *Device, FSMC_NAND_InitTypeDe if (Init->NandBank == FSMC_NAND_BANK2) { /* NAND bank 2 registers configuration */ - MODIFY_REG(Device->PCR2, PCR_CLEAR_MASK, (Init->Waitfeature | - FSMC_PCR_MEMORY_TYPE_NAND | - Init->MemoryDataWidth | - Init->EccComputation | - Init->ECCPageSize | - ((Init->TCLRSetupTime) << FSMC_PCRx_TCLR_Pos) | - ((Init->TARSetupTime) << FSMC_PCRx_TAR_Pos))); + MODIFY_REG(Device->PCR2, PCR_CLEAR_MASK, (Init->Waitfeature | \ + FSMC_PCR_MEMORY_TYPE_NAND | \ + Init->MemoryDataWidth | \ + Init->EccComputation | \ + Init->ECCPageSize | \ + ((Init->TCLRSetupTime) << POSITION_VAL(FSMC_PCRx_TCLR)) | \ + ((Init->TARSetupTime) << POSITION_VAL(FSMC_PCRx_TAR)))); } else { /* NAND bank 3 registers configuration */ - MODIFY_REG(Device->PCR3, PCR_CLEAR_MASK, (Init->Waitfeature | - FSMC_PCR_MEMORY_TYPE_NAND | - Init->MemoryDataWidth | - Init->EccComputation | - Init->ECCPageSize | - ((Init->TCLRSetupTime) << FSMC_PCRx_TCLR_Pos) | - ((Init->TARSetupTime) << FSMC_PCRx_TAR_Pos))); + MODIFY_REG(Device->PCR3, PCR_CLEAR_MASK, (Init->Waitfeature | \ + FSMC_PCR_MEMORY_TYPE_NAND | \ + Init->MemoryDataWidth | \ + Init->EccComputation | \ + Init->ECCPageSize | \ + ((Init->TCLRSetupTime) << POSITION_VAL(FSMC_PCRx_TCLR)) | \ + ((Init->TARSetupTime) << POSITION_VAL(FSMC_PCRx_TAR)))); } return HAL_OK; + } /** @@ -511,21 +588,21 @@ HAL_StatusTypeDef FSMC_NAND_CommonSpace_Timing_Init(FSMC_NAND_TypeDef *Device, F assert_param(IS_FSMC_NAND_BANK(Bank)); /* Set FMC_NAND device timing parameters */ - if(Bank == FSMC_NAND_BANK2) + if (Bank == FSMC_NAND_BANK2) { /* NAND bank 2 registers configuration */ - MODIFY_REG(Device->PMEM2, PMEM_CLEAR_MASK, (Timing->SetupTime | \ - ((Timing->WaitSetupTime) << FSMC_PMEMx_MEMWAITx_Pos) | \ - ((Timing->HoldSetupTime) << FSMC_PMEMx_MEMHOLDx_Pos) | \ - ((Timing->HiZSetupTime) << FSMC_PMEMx_MEMHIZx_Pos))); + MODIFY_REG(Device->PMEM2, PMEM_CLEAR_MASK, (Timing->SetupTime | \ + ((Timing->WaitSetupTime) << POSITION_VAL(FSMC_PMEMx_MEMWAITx)) | \ + ((Timing->HoldSetupTime) << POSITION_VAL(FSMC_PMEMx_MEMHOLDx)) | \ + ((Timing->HiZSetupTime) << POSITION_VAL(FSMC_PMEMx_MEMHIZx)))); } else { /* NAND bank 3 registers configuration */ - MODIFY_REG(Device->PMEM3, PMEM_CLEAR_MASK, (Timing->SetupTime | \ - ((Timing->WaitSetupTime) << FSMC_PMEMx_MEMWAITx_Pos) | \ - ((Timing->HoldSetupTime) << FSMC_PMEMx_MEMHOLDx_Pos) | \ - ((Timing->HiZSetupTime) << FSMC_PMEMx_MEMHIZx_Pos))); + MODIFY_REG(Device->PMEM3, PMEM_CLEAR_MASK, (Timing->SetupTime | \ + ((Timing->WaitSetupTime) << POSITION_VAL(FSMC_PMEMx_MEMWAITx)) | \ + ((Timing->HoldSetupTime) << POSITION_VAL(FSMC_PMEMx_MEMHOLDx)) | \ + ((Timing->HiZSetupTime) << POSITION_VAL(FSMC_PMEMx_MEMHIZx)))); } return HAL_OK; @@ -550,21 +627,21 @@ HAL_StatusTypeDef FSMC_NAND_AttributeSpace_Timing_Init(FSMC_NAND_TypeDef *Device assert_param(IS_FSMC_NAND_BANK(Bank)); /* Set FMC_NAND device timing parameters */ - if(Bank == FSMC_NAND_BANK2) + if (Bank == FSMC_NAND_BANK2) { /* NAND bank 2 registers configuration */ - MODIFY_REG(Device->PATT2, PATT_CLEAR_MASK, (Timing->SetupTime | \ - ((Timing->WaitSetupTime) << FSMC_PATTx_ATTWAITx_Pos) | \ - ((Timing->HoldSetupTime) << FSMC_PATTx_ATTHOLDx_Pos) | \ - ((Timing->HiZSetupTime) << FSMC_PATTx_ATTHIZx_Pos))); + MODIFY_REG(Device->PATT2, PATT_CLEAR_MASK, (Timing->SetupTime | \ + ((Timing->WaitSetupTime) << POSITION_VAL(FSMC_PATTx_ATTWAITx)) | \ + ((Timing->HoldSetupTime) << POSITION_VAL(FSMC_PATTx_ATTHOLDx)) | \ + ((Timing->HiZSetupTime) << POSITION_VAL(FSMC_PATTx_ATTHIZx)))); } else { /* NAND bank 3 registers configuration */ - MODIFY_REG(Device->PATT3, PATT_CLEAR_MASK, (Timing->SetupTime | \ - ((Timing->WaitSetupTime) << FSMC_PATTx_ATTWAITx_Pos) | \ - ((Timing->HoldSetupTime) << FSMC_PATTx_ATTHOLDx_Pos) | \ - ((Timing->HiZSetupTime) << FSMC_PATTx_ATTHIZx_Pos))); + MODIFY_REG(Device->PATT3, PATT_CLEAR_MASK, (Timing->SetupTime | \ + ((Timing->WaitSetupTime) << POSITION_VAL(FSMC_PATTx_ATTWAITx)) | \ + ((Timing->HoldSetupTime) << POSITION_VAL(FSMC_PATTx_ATTHOLDx)) | \ + ((Timing->HiZSetupTime) << POSITION_VAL(FSMC_PATTx_ATTHIZx)))); } return HAL_OK; @@ -572,7 +649,7 @@ HAL_StatusTypeDef FSMC_NAND_AttributeSpace_Timing_Init(FSMC_NAND_TypeDef *Device /** - * @brief DeInitializes the FSMC_NAND device + * @brief DeInitializes the FSMC_NAND device * @param Device: Pointer to NAND device instance * @param Bank: NAND bank number * @retval HAL status @@ -587,22 +664,22 @@ HAL_StatusTypeDef FSMC_NAND_DeInit(FSMC_NAND_TypeDef *Device, uint32_t Bank) __FSMC_NAND_DISABLE(Device, Bank); /* De-initialize the NAND Bank */ - if(Bank == FSMC_NAND_BANK2) + if (Bank == FSMC_NAND_BANK2) { /* Set the FSMC_NAND_BANK2 registers to their reset values */ - WRITE_REG(Device->PCR2, 0x00000018U); - WRITE_REG(Device->SR2, 0x00000040U); - WRITE_REG(Device->PMEM2, 0xFCFCFCFCU); - WRITE_REG(Device->PATT2, 0xFCFCFCFCU); + WRITE_REG(Device->PCR2, 0x00000018); + WRITE_REG(Device->SR2, 0x00000040); + WRITE_REG(Device->PMEM2, 0xFCFCFCFC); + WRITE_REG(Device->PATT2, 0xFCFCFCFC); } /* FSMC_Bank3_NAND */ else { /* Set the FSMC_NAND_BANK3 registers to their reset values */ - WRITE_REG(Device->PCR3, 0x00000018U); - WRITE_REG(Device->SR3, 0x00000040U); - WRITE_REG(Device->PMEM3, 0xFCFCFCFCU); - WRITE_REG(Device->PATT3, 0xFCFCFCFCU); + WRITE_REG(Device->PCR3, 0x00000018); + WRITE_REG(Device->SR3, 0x00000040); + WRITE_REG(Device->PMEM3, 0xFCFCFCFC); + WRITE_REG(Device->PATT3, 0xFCFCFCFC); } return HAL_OK; @@ -614,8 +691,8 @@ HAL_StatusTypeDef FSMC_NAND_DeInit(FSMC_NAND_TypeDef *Device, uint32_t Bank) /** @defgroup FSMC_NAND_Exported_Functions_Group2 Peripheral Control functions - * @brief management functions - * + * @brief management functions + * @verbatim ============================================================================== ##### FSMC_NAND Control functions ##### @@ -628,6 +705,7 @@ HAL_StatusTypeDef FSMC_NAND_DeInit(FSMC_NAND_TypeDef *Device, uint32_t Bank) * @{ */ + /** * @brief Enables dynamically FSMC_NAND ECC feature. * @param Device: Pointer to NAND device instance @@ -641,7 +719,7 @@ HAL_StatusTypeDef FSMC_NAND_ECC_Enable(FSMC_NAND_TypeDef *Device, uint32_t Bank) assert_param(IS_FSMC_NAND_BANK(Bank)); /* Enable ECC feature */ - if(Bank == FSMC_NAND_BANK2) + if (Bank == FSMC_NAND_BANK2) { SET_BIT(Device->PCR2, FSMC_PCRx_ECCEN); } @@ -653,6 +731,7 @@ HAL_StatusTypeDef FSMC_NAND_ECC_Enable(FSMC_NAND_TypeDef *Device, uint32_t Bank) return HAL_OK; } + /** * @brief Disables dynamically FSMC_NAND ECC feature. * @param Device: Pointer to NAND device instance @@ -666,7 +745,7 @@ HAL_StatusTypeDef FSMC_NAND_ECC_Disable(FSMC_NAND_TypeDef *Device, uint32_t Bank assert_param(IS_FSMC_NAND_BANK(Bank)); /* Disable ECC feature */ - if(Bank == FSMC_NAND_BANK2) + if (Bank == FSMC_NAND_BANK2) { CLEAR_BIT(Device->PCR2, FSMC_PCRx_ECCEN); } @@ -683,13 +762,13 @@ HAL_StatusTypeDef FSMC_NAND_ECC_Disable(FSMC_NAND_TypeDef *Device, uint32_t Bank * @param Device: Pointer to NAND device instance * @param ECCval: Pointer to ECC value * @param Bank: NAND bank number - * @param Timeout: Timeout wait value + * @param Timeout: Timeout wait value * @retval HAL status */ HAL_StatusTypeDef FSMC_NAND_GetECC(FSMC_NAND_TypeDef *Device, uint32_t *ECCval, uint32_t Bank, uint32_t Timeout) { - uint32_t tickstart = 0U; - + uint32_t tickstart = 0; + /* Check the parameters */ assert_param(IS_FSMC_NAND_DEVICE(Device)); assert_param(IS_FSMC_NAND_BANK(Bank)); @@ -697,20 +776,20 @@ HAL_StatusTypeDef FSMC_NAND_GetECC(FSMC_NAND_TypeDef *Device, uint32_t *ECCval, /* Get tick */ tickstart = HAL_GetTick(); - /* Wait until FIFO is empty */ - while(__FSMC_NAND_GET_FLAG(Device, Bank, FSMC_FLAG_FEMPT) == RESET) + /* Wait untill FIFO is empty */ + while (__FSMC_NAND_GET_FLAG(Device, Bank, FSMC_FLAG_FEMPT) == RESET) { /* Check for the Timeout */ - if(Timeout != HAL_MAX_DELAY) + if (Timeout != HAL_MAX_DELAY) { - if((Timeout == 0U)||((HAL_GetTick() - tickstart ) > Timeout)) + if ((Timeout == 0) || ((HAL_GetTick() - tickstart) > Timeout)) { return HAL_TIMEOUT; } } } - if(Bank == FSMC_NAND_BANK2) + if (Bank == FSMC_NAND_BANK2) { /* Get the ECCR2 register value */ *ECCval = (uint32_t)Device->ECCR2; @@ -732,6 +811,8 @@ HAL_StatusTypeDef FSMC_NAND_GetECC(FSMC_NAND_TypeDef *Device, uint32_t *ECCval, * @} */ +#endif /* STM32F101xE || STM32F103xE || STM32F101xG || STM32F103xG */ +#if (defined (STM32F101xE) || defined(STM32F103xE) || defined(STM32F101xG) || defined(STM32F103xG)) /** @defgroup FSMC_PCCARD FSMC PCCARD Controller functions * @brief PCCARD Controller functions * @@ -752,13 +833,14 @@ HAL_StatusTypeDef FSMC_NAND_GetECC(FSMC_NAND_TypeDef *Device, uint32_t *ECCval, (+) FSMC PCCARD bank IO space timing configuration using the function FSMC_PCCARD_IOSpace_Timing_Init() + @endverbatim * @{ */ /** @defgroup FSMC_PCCARD_Exported_Functions_Group1 Initialization and de-initialization functions - * @brief Initialization and Configuration functions - * + * @brief Initialization and Configuration functions + * @verbatim ============================================================================== ##### Initialization and de_initialization functions ##### @@ -789,14 +871,14 @@ HAL_StatusTypeDef FSMC_PCCARD_Init(FSMC_PCCARD_TypeDef *Device, FSMC_PCCARD_Init assert_param(IS_FSMC_TAR_TIME(Init->TARSetupTime)); /* Set FSMC_PCCARD device control parameters */ - MODIFY_REG(Device->PCR4, + MODIFY_REG(Device->PCR4, \ (FSMC_PCRx_PTYP | FSMC_PCRx_PWAITEN | FSMC_PCRx_PWID | - FSMC_PCRx_TCLR | FSMC_PCRx_TAR), - (FSMC_PCR_MEMORY_TYPE_PCCARD | - Init->Waitfeature | - FSMC_NAND_PCC_MEM_BUS_WIDTH_16 | - (Init->TCLRSetupTime << FSMC_PCRx_TCLR_Pos) | - (Init->TARSetupTime << FSMC_PCRx_TAR_Pos))); + FSMC_PCRx_TCLR | FSMC_PCRx_TAR), \ + (FSMC_PCR_MEMORY_TYPE_PCCARD | \ + Init->Waitfeature | \ + FSMC_NAND_PCC_MEM_BUS_WIDTH_16 | \ + (Init->TCLRSetupTime << POSITION_VAL(FSMC_PCRx_TCLR)) | \ + (Init->TARSetupTime << POSITION_VAL(FSMC_PCRx_TAR)))); return HAL_OK; @@ -819,11 +901,11 @@ HAL_StatusTypeDef FSMC_PCCARD_CommonSpace_Timing_Init(FSMC_PCCARD_TypeDef *Devic assert_param(IS_FSMC_HIZ_TIME(Timing->HiZSetupTime)); /* Set PCCARD timing parameters */ - MODIFY_REG(Device->PMEM4, PMEM_CLEAR_MASK, - (Timing->SetupTime | - ((Timing->WaitSetupTime) << FSMC_PMEMx_MEMWAITx_Pos) | - ((Timing->HoldSetupTime) << FSMC_PMEMx_MEMHOLDx_Pos) | - ((Timing->HiZSetupTime) << FSMC_PMEMx_MEMHIZx_Pos))); + MODIFY_REG(Device->PMEM4, PMEM_CLEAR_MASK, \ + (Timing->SetupTime | \ + ((Timing->WaitSetupTime) << POSITION_VAL(FSMC_PMEMx_MEMWAITx)) | \ + ((Timing->HoldSetupTime) << POSITION_VAL(FSMC_PMEMx_MEMHOLDx)) | \ + ((Timing->HiZSetupTime) << POSITION_VAL(FSMC_PMEMx_MEMHIZx)))); return HAL_OK; } @@ -846,10 +928,10 @@ HAL_StatusTypeDef FSMC_PCCARD_AttributeSpace_Timing_Init(FSMC_PCCARD_TypeDef *De /* Set PCCARD timing parameters */ MODIFY_REG(Device->PATT4, PATT_CLEAR_MASK, \ - (Timing->SetupTime | \ - ((Timing->WaitSetupTime) << FSMC_PATTx_ATTWAITx_Pos) | \ - ((Timing->HoldSetupTime) << FSMC_PATTx_ATTHOLDx_Pos) | \ - ((Timing->HiZSetupTime) << FSMC_PATTx_ATTHIZx_Pos))); + (Timing->SetupTime | \ + ((Timing->WaitSetupTime) << POSITION_VAL(FSMC_PATTx_ATTWAITx)) | \ + ((Timing->HoldSetupTime) << POSITION_VAL(FSMC_PATTx_ATTHOLDx)) | \ + ((Timing->HiZSetupTime) << POSITION_VAL(FSMC_PATTx_ATTHIZx)))); return HAL_OK; } @@ -871,11 +953,11 @@ HAL_StatusTypeDef FSMC_PCCARD_IOSpace_Timing_Init(FSMC_PCCARD_TypeDef *Device, F assert_param(IS_FSMC_HIZ_TIME(Timing->HiZSetupTime)); /* Set FSMC_PCCARD device timing parameters */ - MODIFY_REG(Device->PIO4, PIO4_CLEAR_MASK, \ - (Timing->SetupTime | \ - (Timing->WaitSetupTime << FSMC_PIO4_IOWAIT4_Pos) | \ - (Timing->HoldSetupTime << FSMC_PIO4_IOHOLD4_Pos) | \ - (Timing->HiZSetupTime << FSMC_PIO4_IOHIZ4_Pos))); + MODIFY_REG(Device->PIO4, PIO4_CLEAR_MASK, \ + (Timing->SetupTime | \ + (Timing->WaitSetupTime << POSITION_VAL(FSMC_PIO4_IOWAIT4)) | \ + (Timing->HoldSetupTime << POSITION_VAL(FSMC_PIO4_IOHOLD4)) | \ + (Timing->HiZSetupTime << POSITION_VAL(FSMC_PIO4_IOHIZ4)))); return HAL_OK; } @@ -894,11 +976,11 @@ HAL_StatusTypeDef FSMC_PCCARD_DeInit(FSMC_PCCARD_TypeDef *Device) __FSMC_PCCARD_DISABLE(Device); /* De-initialize the FSMC_PCCARD device */ - WRITE_REG(Device->PCR4, 0x00000018U); - WRITE_REG(Device->SR4, 0x00000040U); - WRITE_REG(Device->PMEM4, 0xFCFCFCFCU); - WRITE_REG(Device->PATT4, 0xFCFCFCFCU); - WRITE_REG(Device->PIO4, 0xFCFCFCFCU); + WRITE_REG(Device->PCR4, 0x00000018); + WRITE_REG(Device->SR4, 0x00000040); + WRITE_REG(Device->PMEM4, 0xFCFCFCFC); + WRITE_REG(Device->PATT4, 0xFCFCFCFC); + WRITE_REG(Device->PIO4, 0xFCFCFCFC); return HAL_OK; } @@ -920,10 +1002,10 @@ HAL_StatusTypeDef FSMC_PCCARD_DeInit(FSMC_PCCARD_TypeDef *Device) * @} */ -#endif /* HAL_SRAM_MODULE_ENABLED || HAL_NOR_MODULE_ENABLED || HAL_NAND_MODULE_ENABLED || HAL_PCCARD_MODULE_ENABLED */ - #endif /* FSMC_BANK1 */ +#endif /* defined(HAL_SRAM_MODULE_ENABLED) || defined(HAL_NOR_MODULE_ENABLED) || defined(HAL_PCCARD_MODULE_ENABLED) || defined(HAL_NAND_MODULE_ENABLED) */ + /** * @} */ diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_fsmc.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_fsmc.h index b04c4a7d4dc..d3c77504d8e 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_fsmc.h +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_fsmc.h @@ -2,13 +2,13 @@ ****************************************************************************** * @file stm32f1xx_ll_fsmc.h * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief Header file of FSMC HAL module. ****************************************************************************** * @attention * - *

© COPYRIGHT(c) 2017 STMicroelectronics

+ *

© COPYRIGHT(c) 2016 STMicroelectronics

* * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: @@ -56,6 +56,206 @@ extern "C" { * @{ */ +/** @addtogroup FSMC_LL_Private_Macros + * @{ + */ + +#define IS_FSMC_NORSRAM_BANK(__BANK__) (((__BANK__) == FSMC_NORSRAM_BANK1) || \ + ((__BANK__) == FSMC_NORSRAM_BANK2) || \ + ((__BANK__) == FSMC_NORSRAM_BANK3) || \ + ((__BANK__) == FSMC_NORSRAM_BANK4)) + +#define IS_FSMC_MUX(__MUX__) (((__MUX__) == FSMC_DATA_ADDRESS_MUX_DISABLE) || \ + ((__MUX__) == FSMC_DATA_ADDRESS_MUX_ENABLE)) + +#define IS_FSMC_MEMORY(__MEMORY__) (((__MEMORY__) == FSMC_MEMORY_TYPE_SRAM) || \ + ((__MEMORY__) == FSMC_MEMORY_TYPE_PSRAM)|| \ + ((__MEMORY__) == FSMC_MEMORY_TYPE_NOR)) + +#define IS_FSMC_NORSRAM_MEMORY_WIDTH(__WIDTH__) (((__WIDTH__) == FSMC_NORSRAM_MEM_BUS_WIDTH_8) || \ + ((__WIDTH__) == FSMC_NORSRAM_MEM_BUS_WIDTH_16) || \ + ((__WIDTH__) == FSMC_NORSRAM_MEM_BUS_WIDTH_32)) + +#define IS_FSMC_WRITE_BURST(__BURST__) (((__BURST__) == FSMC_WRITE_BURST_DISABLE) || \ + ((__BURST__) == FSMC_WRITE_BURST_ENABLE)) + +#define IS_FSMC_ACCESS_MODE(__MODE__) (((__MODE__) == FSMC_ACCESS_MODE_A) || \ + ((__MODE__) == FSMC_ACCESS_MODE_B) || \ + ((__MODE__) == FSMC_ACCESS_MODE_C) || \ + ((__MODE__) == FSMC_ACCESS_MODE_D)) + +#define IS_FSMC_NAND_BANK(__BANK__) (((__BANK__) == FSMC_NAND_BANK2) || \ + ((__BANK__) == FSMC_NAND_BANK3)) + +#define IS_FSMC_WAIT_FEATURE(__FEATURE__) (((__FEATURE__) == FSMC_NAND_PCC_WAIT_FEATURE_DISABLE) || \ + ((__FEATURE__) == FSMC_NAND_PCC_WAIT_FEATURE_ENABLE)) + +#define IS_FSMC_NAND_MEMORY_WIDTH(__WIDTH__) (((__WIDTH__) == FSMC_NAND_PCC_MEM_BUS_WIDTH_8) || \ + ((__WIDTH__) == FSMC_NAND_PCC_MEM_BUS_WIDTH_16)) + +#define IS_FSMC_ECC_STATE(__STATE__) (((__STATE__) == FSMC_NAND_ECC_DISABLE) || \ + ((__STATE__) == FSMC_NAND_ECC_ENABLE)) + +#define IS_FSMC_ECCPAGE_SIZE(__SIZE__) (((__SIZE__) == FSMC_NAND_ECC_PAGE_SIZE_256BYTE) || \ + ((__SIZE__) == FSMC_NAND_ECC_PAGE_SIZE_512BYTE) || \ + ((__SIZE__) == FSMC_NAND_ECC_PAGE_SIZE_1024BYTE) || \ + ((__SIZE__) == FSMC_NAND_ECC_PAGE_SIZE_2048BYTE) || \ + ((__SIZE__) == FSMC_NAND_ECC_PAGE_SIZE_4096BYTE) || \ + ((__SIZE__) == FSMC_NAND_ECC_PAGE_SIZE_8192BYTE)) + +/** @defgroup FSMC_TCLR_Setup_Time FSMC_TCLR_Setup_Time + * @{ + */ +#define IS_FSMC_TCLR_TIME(__TIME__) ((__TIME__) <= 255) +/** + * @} + */ + +/** @defgroup FSMC_TAR_Setup_Time FSMC_TAR_Setup_Time + * @{ + */ +#define IS_FSMC_TAR_TIME(__TIME__) ((__TIME__) <= 255) +/** + * @} + */ + +/** @defgroup FSMC_Setup_Time FSMC_Setup_Time + * @{ + */ +#define IS_FSMC_SETUP_TIME(__TIME__) ((__TIME__) <= 255) +/** + * @} + */ + +/** @defgroup FSMC_Wait_Setup_Time FSMC_Wait_Setup_Time + * @{ + */ +#define IS_FSMC_WAIT_TIME(__TIME__) ((__TIME__) <= 255) +/** + * @} + */ + +/** @defgroup FSMC_Hold_Setup_Time FSMC_Hold_Setup_Time + * @{ + */ +#define IS_FSMC_HOLD_TIME(__TIME__) ((__TIME__) <= 255) +/** + * @} + */ + +/** @defgroup FSMC_HiZ_Setup_Time FSMC_HiZ_Setup_Time + * @{ + */ +#define IS_FSMC_HIZ_TIME(__TIME__) ((__TIME__) <= 255) +/** + * @} + */ + +/** @defgroup FSMC_NORSRAM_Device_Instance FSMC NOR/SRAM Device Instance + * @{ + */ + +#define IS_FSMC_NORSRAM_DEVICE(__INSTANCE__) ((__INSTANCE__) == FSMC_NORSRAM_DEVICE) + +/** + * @} + */ + +/** @defgroup FSMC_NORSRAM_EXTENDED_Device_Instance FSMC NOR/SRAM EXTENDED Device Instance + * @{ + */ + +#define IS_FSMC_NORSRAM_EXTENDED_DEVICE(__INSTANCE__) ((__INSTANCE__) == FSMC_NORSRAM_EXTENDED_DEVICE) + +/** + * @} + */ + +/** @defgroup FSMC_NAND_Device_Instance FSMC NAND Device Instance + * @{ + */ +#define IS_FSMC_NAND_DEVICE(__INSTANCE__) ((__INSTANCE__) == FSMC_NAND_DEVICE) +/** + * @} + */ + +/** @defgroup FSMC_PCCARD_Device_Instance FSMC PCCARD Device Instance + * @{ + */ +#define IS_FSMC_PCCARD_DEVICE(__INSTANCE__) ((__INSTANCE__) == FSMC_PCCARD_DEVICE) + +/** + * @} + */ +#define IS_FSMC_BURSTMODE(__STATE__) (((__STATE__) == FSMC_BURST_ACCESS_MODE_DISABLE) || \ + ((__STATE__) == FSMC_BURST_ACCESS_MODE_ENABLE)) + +#define IS_FSMC_WAIT_POLARITY(__POLARITY__) (((__POLARITY__) == FSMC_WAIT_SIGNAL_POLARITY_LOW) || \ + ((__POLARITY__) == FSMC_WAIT_SIGNAL_POLARITY_HIGH)) + +#define IS_FSMC_WRAP_MODE(__MODE__) (((__MODE__) == FSMC_WRAP_MODE_DISABLE) || \ + ((__MODE__) == FSMC_WRAP_MODE_ENABLE)) + +#define IS_FSMC_WAIT_SIGNAL_ACTIVE(__ACTIVE__) (((__ACTIVE__) == FSMC_WAIT_TIMING_BEFORE_WS) || \ + ((__ACTIVE__) == FSMC_WAIT_TIMING_DURING_WS)) + +#define IS_FSMC_WRITE_OPERATION(__OPERATION__) (((__OPERATION__) == FSMC_WRITE_OPERATION_DISABLE) || \ + ((__OPERATION__) == FSMC_WRITE_OPERATION_ENABLE)) + +#define IS_FSMC_WAITE_SIGNAL(__SIGNAL__) (((__SIGNAL__) == FSMC_WAIT_SIGNAL_DISABLE) || \ + ((__SIGNAL__) == FSMC_WAIT_SIGNAL_ENABLE)) + +#define IS_FSMC_EXTENDED_MODE(__MODE__) (((__MODE__) == FSMC_EXTENDED_MODE_DISABLE) || \ + ((__MODE__) == FSMC_EXTENDED_MODE_ENABLE)) + +#define IS_FSMC_ASYNWAIT(__STATE__) (((__STATE__) == FSMC_ASYNCHRONOUS_WAIT_DISABLE) || \ + ((__STATE__) == FSMC_ASYNCHRONOUS_WAIT_ENABLE)) + +#define IS_FSMC_CLK_DIV(__DIV__) (((__DIV__) > 1) && ((__DIV__) <= 16)) + +/** @defgroup FSMC_Data_Latency FSMC Data Latency + * @{ + */ +#define IS_FSMC_DATA_LATENCY(__LATENCY__) (((__LATENCY__) > 1) && ((__LATENCY__) <= 17)) +/** + * @} + */ + +/** @defgroup FSMC_Address_Setup_Time FSMC Address Setup Time + * @{ + */ +#define IS_FSMC_ADDRESS_SETUP_TIME(__TIME__) ((__TIME__) <= 15) +/** + * @} + */ + +/** @defgroup FSMC_Address_Hold_Time FSMC Address Hold Time + * @{ + */ +#define IS_FSMC_ADDRESS_HOLD_TIME(__TIME__) (((__TIME__) > 0) && ((__TIME__) <= 15)) +/** + * @} + */ + +/** @defgroup FSMC_Data_Setup_Time FSMC Data Setup Time + * @{ + */ +#define IS_FSMC_DATASETUP_TIME(__TIME__) (((__TIME__) > 0) && ((__TIME__) <= 255)) +/** + * @} + */ + +/** @defgroup FSMC_Bus_Turn_around_Duration FSMC Bus Turn around Duration + * @{ + */ +#define IS_FSMC_TURNAROUND_TIME(__TIME__) ((__TIME__) <= 15) +/** + * @} + */ + +/** + * @} + */ /* Exported typedef ----------------------------------------------------------*/ @@ -63,8 +263,18 @@ extern "C" { * @{ */ +#define FSMC_NORSRAM_TypeDef FSMC_Bank1_TypeDef +#define FSMC_NORSRAM_EXTENDED_TypeDef FSMC_Bank1E_TypeDef +#define FSMC_NAND_TypeDef FSMC_Bank2_3_TypeDef +#define FSMC_PCCARD_TypeDef FSMC_Bank4_TypeDef + +#define FSMC_NORSRAM_DEVICE FSMC_Bank1 +#define FSMC_NORSRAM_EXTENDED_DEVICE FSMC_Bank1E +#define FSMC_NAND_DEVICE FSMC_Bank2_3 +#define FSMC_PCCARD_DEVICE FSMC_Bank4 + /** - * @brief FSMC NORSRAM Configuration Structure definition + * @brief FSMC_NORSRAM Configuration Structure definition */ typedef struct { @@ -119,7 +329,7 @@ typedef struct }FSMC_NORSRAM_InitTypeDef; /** - * @brief FSMC NORSRAM Timing parameters structure definition + * @brief FSMC_NORSRAM Timing parameters structure definition */ typedef struct { @@ -158,30 +368,30 @@ typedef struct with synchronous burst mode enable */ uint32_t AccessMode; /*!< Specifies the asynchronous access mode. - This parameter can be a value of @ref FSMC_Access_Mode */ + This parameter can be a value of @ref FSMC_Access_Mode */ }FSMC_NORSRAM_TimingTypeDef; #if (defined(STM32F101xE) || defined(STM32F103xE) || defined(STM32F101xG) || defined(STM32F103xG)) /** - * @brief FSMC NAND Configuration Structure definition + * @brief FSMC_NAND Configuration Structure definition */ typedef struct { uint32_t NandBank; /*!< Specifies the NAND memory device that will be used. - This parameter can be a value of @ref FSMC_NAND_Bank */ + This parameter can be a value of @ref FSMC_NAND_Bank */ uint32_t Waitfeature; /*!< Enables or disables the Wait feature for the NAND Memory device. - This parameter can be any value of @ref FSMC_Wait_feature */ + This parameter can be any value of @ref FSMC_Wait_feature */ uint32_t MemoryDataWidth; /*!< Specifies the external memory device width. - This parameter can be any value of @ref FSMC_NAND_Data_Width */ + This parameter can be any value of @ref FSMC_NAND_Data_Width */ uint32_t EccComputation; /*!< Enables or disables the ECC computation. - This parameter can be any value of @ref FSMC_ECC */ + This parameter can be any value of @ref FSMC_ECC */ uint32_t ECCPageSize; /*!< Defines the page size for the extended ECC. - This parameter can be any value of @ref FSMC_ECC_Page_Size */ + This parameter can be any value of @ref FSMC_ECC_Page_Size */ uint32_t TCLRSetupTime; /*!< Defines the number of HCLK cycles to configure the delay between CLE low and RE low. @@ -194,7 +404,7 @@ typedef struct }FSMC_NAND_InitTypeDef; /** - * @brief FSMC NAND/PCCARD Timing parameters structure definition + * @brief FSMC_NAND_PCCARD Timing parameters structure definition */ typedef struct { @@ -225,13 +435,15 @@ typedef struct }FSMC_NAND_PCC_TimingTypeDef; +#endif /* STM32F101xE || STM32F103xE || STM32F101xG || STM32F103xG */ +#if (defined(STM32F101xE) || defined(STM32F103xE) || defined(STM32F101xG) || defined(STM32F103xG)) /** - * @brief FSMC NAND Configuration Structure definition + * @brief FSMC_NAND Configuration Structure definition */ typedef struct { uint32_t Waitfeature; /*!< Enables or disables the Wait feature for the PCCARD Memory device. - This parameter can be any value of @ref FSMC_Wait_feature */ + This parameter can be any value of @ref FSMC_Wait_feature */ uint32_t TCLRSetupTime; /*!< Defines the number of HCLK cycles to configure the delay between CLE low and RE low. @@ -242,6 +454,7 @@ typedef struct This parameter can be a number between Min_Data = 0 and Max_Data = 255 */ }FSMC_PCCARD_InitTypeDef; + #endif /* STM32F101xE || STM32F103xE || STM32F101xG || STM32F103xG */ /** * @} @@ -256,13 +469,15 @@ typedef struct /** @defgroup FSMC_NORSRAM_Exported_constants FSMC NOR/SRAM Exported constants * @{ */ + /** @defgroup FSMC_NORSRAM_Bank FSMC NOR/SRAM Bank * @{ */ -#define FSMC_NORSRAM_BANK1 0x00000000U -#define FSMC_NORSRAM_BANK2 0x00000002U -#define FSMC_NORSRAM_BANK3 0x00000004U -#define FSMC_NORSRAM_BANK4 0x00000006U +#define FSMC_NORSRAM_BANK1 ((uint32_t)0x00000000) +#define FSMC_NORSRAM_BANK2 ((uint32_t)0x00000002) +#define FSMC_NORSRAM_BANK3 ((uint32_t)0x00000004) +#define FSMC_NORSRAM_BANK4 ((uint32_t)0x00000006) + /** * @} */ @@ -270,8 +485,10 @@ typedef struct /** @defgroup FSMC_Data_Address_Bus_Multiplexing FSMC Data Address Bus Multiplexing * @{ */ -#define FSMC_DATA_ADDRESS_MUX_DISABLE 0x00000000U + +#define FSMC_DATA_ADDRESS_MUX_DISABLE ((uint32_t)0x00000000) #define FSMC_DATA_ADDRESS_MUX_ENABLE ((uint32_t)FSMC_BCRx_MUXEN) + /** * @} */ @@ -279,9 +496,11 @@ typedef struct /** @defgroup FSMC_Memory_Type FSMC Memory Type * @{ */ -#define FSMC_MEMORY_TYPE_SRAM 0x00000000U + +#define FSMC_MEMORY_TYPE_SRAM ((uint32_t)0x00000000) #define FSMC_MEMORY_TYPE_PSRAM ((uint32_t)FSMC_BCRx_MTYP_0) #define FSMC_MEMORY_TYPE_NOR ((uint32_t)FSMC_BCRx_MTYP_1) + /** * @} */ @@ -289,9 +508,11 @@ typedef struct /** @defgroup FSMC_NORSRAM_Data_Width FSMC NOR/SRAM Data Width * @{ */ -#define FSMC_NORSRAM_MEM_BUS_WIDTH_8 0x00000000U + +#define FSMC_NORSRAM_MEM_BUS_WIDTH_8 ((uint32_t)0x00000000) #define FSMC_NORSRAM_MEM_BUS_WIDTH_16 ((uint32_t)FSMC_BCRx_MWID_0) #define FSMC_NORSRAM_MEM_BUS_WIDTH_32 ((uint32_t)FSMC_BCRx_MWID_1) + /** * @} */ @@ -299,8 +520,9 @@ typedef struct /** @defgroup FSMC_NORSRAM_Flash_Access FSMC NOR/SRAM Flash Access * @{ */ + #define FSMC_NORSRAM_FLASH_ACCESS_ENABLE ((uint32_t)FSMC_BCRx_FACCEN) -#define FSMC_NORSRAM_FLASH_ACCESS_DISABLE 0x00000000U +#define FSMC_NORSRAM_FLASH_ACCESS_DISABLE ((uint32_t)0x00000000) /** * @} */ @@ -308,17 +530,22 @@ typedef struct /** @defgroup FSMC_Burst_Access_Mode FSMC Burst Access Mode * @{ */ -#define FSMC_BURST_ACCESS_MODE_DISABLE 0x00000000U + +#define FSMC_BURST_ACCESS_MODE_DISABLE ((uint32_t)0x00000000) #define FSMC_BURST_ACCESS_MODE_ENABLE ((uint32_t)FSMC_BCRx_BURSTEN) + /** * @} */ + /** @defgroup FSMC_Wait_Signal_Polarity FSMC Wait Signal Polarity * @{ */ -#define FSMC_WAIT_SIGNAL_POLARITY_LOW 0x00000000U + +#define FSMC_WAIT_SIGNAL_POLARITY_LOW ((uint32_t)0x00000000) #define FSMC_WAIT_SIGNAL_POLARITY_HIGH ((uint32_t)FSMC_BCRx_WAITPOL) + /** * @} */ @@ -326,8 +553,10 @@ typedef struct /** @defgroup FSMC_Wrap_Mode FSMC Wrap Mode * @{ */ -#define FSMC_WRAP_MODE_DISABLE 0x00000000U + +#define FSMC_WRAP_MODE_DISABLE ((uint32_t)0x00000000) #define FSMC_WRAP_MODE_ENABLE ((uint32_t)FSMC_BCRx_WRAPMOD) + /** * @} */ @@ -335,8 +564,10 @@ typedef struct /** @defgroup FSMC_Wait_Timing FSMC Wait Timing * @{ */ -#define FSMC_WAIT_TIMING_BEFORE_WS 0x00000000U + +#define FSMC_WAIT_TIMING_BEFORE_WS ((uint32_t)0x00000000) #define FSMC_WAIT_TIMING_DURING_WS ((uint32_t)FSMC_BCRx_WAITCFG) + /** * @} */ @@ -344,8 +575,10 @@ typedef struct /** @defgroup FSMC_Write_Operation FSMC Write Operation * @{ */ -#define FSMC_WRITE_OPERATION_DISABLE 0x00000000U + +#define FSMC_WRITE_OPERATION_DISABLE ((uint32_t)0x00000000) #define FSMC_WRITE_OPERATION_ENABLE ((uint32_t)FSMC_BCRx_WREN) + /** * @} */ @@ -353,8 +586,10 @@ typedef struct /** @defgroup FSMC_Wait_Signal FSMC Wait Signal * @{ */ -#define FSMC_WAIT_SIGNAL_DISABLE 0x00000000U + +#define FSMC_WAIT_SIGNAL_DISABLE ((uint32_t)0x00000000) #define FSMC_WAIT_SIGNAL_ENABLE ((uint32_t)FSMC_BCRx_WAITEN) + /** * @} */ @@ -362,8 +597,10 @@ typedef struct /** @defgroup FSMC_Extended_Mode FSMC Extended Mode * @{ */ -#define FSMC_EXTENDED_MODE_DISABLE 0x00000000U + +#define FSMC_EXTENDED_MODE_DISABLE ((uint32_t)0x00000000) #define FSMC_EXTENDED_MODE_ENABLE ((uint32_t)FSMC_BCRx_EXTMOD) + /** * @} */ @@ -371,8 +608,10 @@ typedef struct /** @defgroup FSMC_AsynchronousWait FSMC Asynchronous Wait * @{ */ -#define FSMC_ASYNCHRONOUS_WAIT_DISABLE 0x00000000U + +#define FSMC_ASYNCHRONOUS_WAIT_DISABLE ((uint32_t)0x00000000) #define FSMC_ASYNCHRONOUS_WAIT_ENABLE ((uint32_t)FSMC_BCRx_ASYNCWAIT) + /** * @} */ @@ -380,8 +619,10 @@ typedef struct /** @defgroup FSMC_Write_Burst FSMC Write Burst * @{ */ -#define FSMC_WRITE_BURST_DISABLE 0x00000000U + +#define FSMC_WRITE_BURST_DISABLE ((uint32_t)0x00000000) #define FSMC_WRITE_BURST_ENABLE ((uint32_t)FSMC_BCRx_CBURSTRW) + /** * @} */ @@ -389,10 +630,12 @@ typedef struct /** @defgroup FSMC_Access_Mode FSMC Access Mode * @{ */ -#define FSMC_ACCESS_MODE_A 0x00000000U + +#define FSMC_ACCESS_MODE_A ((uint32_t)0x00000000) #define FSMC_ACCESS_MODE_B ((uint32_t)FSMC_BTRx_ACCMOD_0) #define FSMC_ACCESS_MODE_C ((uint32_t)FSMC_BTRx_ACCMOD_1) #define FSMC_ACCESS_MODE_D ((uint32_t)(FSMC_BTRx_ACCMOD_0 | FSMC_BTRx_ACCMOD_1)) + /** * @} */ @@ -405,11 +648,13 @@ typedef struct /** @defgroup FSMC_NAND_Controller FSMC NAND and PCCARD Controller * @{ */ + /** @defgroup FSMC_NAND_Bank FSMC NAND Bank * @{ */ -#define FSMC_NAND_BANK2 0x00000010U -#define FSMC_NAND_BANK3 0x00000100U +#define FSMC_NAND_BANK2 ((uint32_t)0x00000010) +#define FSMC_NAND_BANK3 ((uint32_t)0x00000100) + /** * @} */ @@ -417,8 +662,9 @@ typedef struct /** @defgroup FSMC_Wait_feature FSMC Wait feature * @{ */ -#define FSMC_NAND_PCC_WAIT_FEATURE_DISABLE 0x00000000U +#define FSMC_NAND_PCC_WAIT_FEATURE_DISABLE ((uint32_t)0x00000000) #define FSMC_NAND_PCC_WAIT_FEATURE_ENABLE ((uint32_t)FSMC_PCRx_PWAITEN) + /** * @} */ @@ -426,7 +672,7 @@ typedef struct /** @defgroup FSMC_PCR_Memory_Type FSMC PCR Memory Type * @{ */ -#define FSMC_PCR_MEMORY_TYPE_PCCARD 0x00000000U +#define FSMC_PCR_MEMORY_TYPE_PCCARD ((uint32_t)0x00000000) #define FSMC_PCR_MEMORY_TYPE_NAND ((uint32_t)FSMC_PCRx_PTYP) /** * @} @@ -435,8 +681,9 @@ typedef struct /** @defgroup FSMC_NAND_Data_Width FSMC NAND Data Width * @{ */ -#define FSMC_NAND_PCC_MEM_BUS_WIDTH_8 0x00000000U +#define FSMC_NAND_PCC_MEM_BUS_WIDTH_8 ((uint32_t)0x00000000) #define FSMC_NAND_PCC_MEM_BUS_WIDTH_16 ((uint32_t)FSMC_PCRx_PWID_0) + /** * @} */ @@ -444,8 +691,9 @@ typedef struct /** @defgroup FSMC_ECC FSMC NAND ECC * @{ */ -#define FSMC_NAND_ECC_DISABLE 0x00000000U +#define FSMC_NAND_ECC_DISABLE ((uint32_t)0x00000000) #define FSMC_NAND_ECC_ENABLE ((uint32_t)FSMC_PCRx_ECCEN) + /** * @} */ @@ -453,33 +701,30 @@ typedef struct /** @defgroup FSMC_ECC_Page_Size FSMC ECC Page Size * @{ */ -#define FSMC_NAND_ECC_PAGE_SIZE_256BYTE 0x00000000U +#define FSMC_NAND_ECC_PAGE_SIZE_256BYTE ((uint32_t)0x00000000) #define FSMC_NAND_ECC_PAGE_SIZE_512BYTE ((uint32_t)FSMC_PCRx_ECCPS_0) #define FSMC_NAND_ECC_PAGE_SIZE_1024BYTE ((uint32_t)FSMC_PCRx_ECCPS_1) #define FSMC_NAND_ECC_PAGE_SIZE_2048BYTE ((uint32_t)FSMC_PCRx_ECCPS_0|FSMC_PCRx_ECCPS_1) #define FSMC_NAND_ECC_PAGE_SIZE_4096BYTE ((uint32_t)FSMC_PCRx_ECCPS_2) #define FSMC_NAND_ECC_PAGE_SIZE_8192BYTE ((uint32_t)FSMC_PCRx_ECCPS_0|FSMC_PCRx_ECCPS_2) -/** - * @} - */ /** * @} */ -#endif /* STM32F101xE || STM32F103xE || STM32F101xG || STM32F103xG */ -/** @defgroup FSMC_LL_Interrupt_definition FSMC Interrupt definition +/** @defgroup FSMC_Interrupt_definition FSMC Interrupt definition * @brief FSMC Interrupt definition * @{ */ #define FSMC_IT_RISING_EDGE ((uint32_t)FSMC_SRx_IREN) #define FSMC_IT_LEVEL ((uint32_t)FSMC_SRx_ILEN) #define FSMC_IT_FALLING_EDGE ((uint32_t)FSMC_SRx_IFEN) + /** * @} */ -/** @defgroup FSMC_LL_Flag_definition FSMC Flag definition +/** @defgroup FSMC_Flag_definition FSMC Flag definition * @brief FSMC Flag definition * @{ */ @@ -487,52 +732,43 @@ typedef struct #define FSMC_FLAG_LEVEL ((uint32_t)FSMC_SRx_ILS) #define FSMC_FLAG_FALLING_EDGE ((uint32_t)FSMC_SRx_IFS) #define FSMC_FLAG_FEMPT ((uint32_t)FSMC_SRx_FEMPT) + /** * @} */ -/** @defgroup FSMC_LL_Alias_definition FSMC Alias definition - * @{ - */ -#define FSMC_NORSRAM_TypeDef FSMC_Bank1_TypeDef -#define FSMC_NORSRAM_EXTENDED_TypeDef FSMC_Bank1E_TypeDef -#define FSMC_NAND_TypeDef FSMC_Bank2_3_TypeDef -#define FSMC_PCCARD_TypeDef FSMC_Bank4_TypeDef - -#define FSMC_NORSRAM_DEVICE FSMC_Bank1 -#define FSMC_NORSRAM_EXTENDED_DEVICE FSMC_Bank1E -#define FSMC_NAND_DEVICE FSMC_Bank2_3 -#define FSMC_PCCARD_DEVICE FSMC_Bank4 /** * @} */ +#endif /* STM32F101xE || STM32F103xE || STM32F101xG || STM32F103xG */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ + /** @defgroup FSMC_Exported_Macros FSMC Low Layer Exported Macros * @{ */ -/** @defgroup FSMC_LL_NOR_Macros FSMC NOR/SRAM Exported Macros - * @brief macros to handle NOR device enable/disable and read/write operations - * @{ - */ +/** @defgroup FSMC_NOR_Macros FSMC NOR/SRAM Exported Macros + * @brief macros to handle NOR device enable/disable and read/write operations + * @{ + */ /** * @brief Enable the NORSRAM device access. - * @param __INSTANCE__: FSMC_NORSRAM Instance - * @param __BANK__: FSMC_NORSRAM Bank + * @param __INSTANCE__ FSMC_NORSRAM Instance + * @param __BANK__ FSMC_NORSRAM Bank * @retval none */ #define __FSMC_NORSRAM_ENABLE(__INSTANCE__, __BANK__) SET_BIT((__INSTANCE__)->BTCR[(__BANK__)], FSMC_BCRx_MBKEN) /** * @brief Disable the NORSRAM device access. - * @param __INSTANCE__: FSMC_NORSRAM Instance - * @param __BANK__: FSMC_NORSRAM Bank + * @param __INSTANCE__ FSMC_NORSRAM Instance + * @param __BANK__ FSMC_NORSRAM Bank * @retval none */ #define __FSMC_NORSRAM_DISABLE(__INSTANCE__, __BANK__) CLEAR_BIT((__INSTANCE__)->BTCR[(__BANK__)], FSMC_BCRx_MBKEN) @@ -542,46 +778,48 @@ typedef struct */ #if (defined(STM32F101xE) || defined(STM32F103xE) || defined(STM32F101xG) || defined(STM32F103xG)) -/** @defgroup FSMC_LL_NAND_Macros FSMC NAND Macros - * @brief macros to handle NAND device enable/disable - * @{ - */ +/** @defgroup FSMC_NAND_Macros FSMC NAND Macros + * @brief macros to handle NAND device enable/disable + * @{ + */ /** * @brief Enable the NAND device access. - * @param __INSTANCE__: FSMC_NAND Instance - * @param __BANK__: FSMC_NAND Bank + * @param __INSTANCE__ FSMC_NAND Instance + * @param __BANK__ FSMC_NAND Bank * @retval None */ #define __FSMC_NAND_ENABLE(__INSTANCE__, __BANK__) (((__BANK__) == FSMC_NAND_BANK2)? SET_BIT((__INSTANCE__)->PCR2, FSMC_PCRx_PBKEN): \ - SET_BIT((__INSTANCE__)->PCR3, FSMC_PCRx_PBKEN)) + SET_BIT((__INSTANCE__)->PCR3, FSMC_PCRx_PBKEN)) /** * @brief Disable the NAND device access. - * @param __INSTANCE__: FSMC_NAND Instance - * @param __BANK__: FSMC_NAND Bank + * @param __INSTANCE__ FSMC_NAND Instance + * @param __BANK__ FSMC_NAND Bank * @retval None */ #define __FSMC_NAND_DISABLE(__INSTANCE__, __BANK__) (((__BANK__) == FSMC_NAND_BANK2)? CLEAR_BIT((__INSTANCE__)->PCR2, FSMC_PCRx_PBKEN): \ - CLEAR_BIT((__INSTANCE__)->PCR3, FSMC_PCRx_PBKEN)) + CLEAR_BIT((__INSTANCE__)->PCR3, FSMC_PCRx_PBKEN)) + /** * @} */ -/** @defgroup FSMC_LL_PCCARD_Macros FSMC PCCARD Macros - * @brief macros to handle PCCARD read/write operations - * @{ - */ +/** @defgroup FSMC_PCCARD_Macros FSMC PCCARD Macros + * @brief macros to handle PCCARD read/write operations + * @{ + */ + /** * @brief Enable the PCCARD device access. - * @param __INSTANCE__: FSMC_PCCARD Instance + * @param __INSTANCE__ FSMC_PCCARD Instance * @retval None */ #define __FSMC_PCCARD_ENABLE(__INSTANCE__) SET_BIT((__INSTANCE__)->PCR4, FSMC_PCRx_PBKEN) /** * @brief Disable the PCCARD device access. - * @param __INSTANCE__: FSMC_PCCARD Instance + * @param __INSTANCE__ FSMC_PCCARD Instance * @retval None */ #define __FSMC_PCCARD_DISABLE(__INSTANCE__) CLEAR_BIT((__INSTANCE__)->PCR4, FSMC_PCRx_PBKEN) @@ -589,20 +827,20 @@ typedef struct * @} */ -/** @defgroup FSMC_LL_Flag_Interrupt_Macros FSMC Flag&Interrupt Macros - * @brief macros to handle FSMC flags and interrupts - * @{ - */ +/** @defgroup FSMC_Interrupt FSMC Interrupt + * @brief macros to handle FSMC interrupts + * @{ + */ /** * @brief Enable the NAND device interrupt. - * @param __INSTANCE__: FSMC_NAND Instance - * @param __BANK__: FSMC_NAND Bank - * @param __INTERRUPT__: FSMC_NAND interrupt + * @param __INSTANCE__ FSMC_NAND Instance + * @param __BANK__ FSMC_NAND Bank + * @param __INTERRUPT__ FSMC_NAND interrupt * This parameter can be any combination of the following values: - * @arg FSMC_IT_RISING_EDGE: Interrupt rising edge. - * @arg FSMC_IT_LEVEL: Interrupt level. - * @arg FSMC_IT_FALLING_EDGE: Interrupt falling edge. + * @arg FSMC_IT_RISING_EDGE Interrupt rising edge. + * @arg FSMC_IT_LEVEL Interrupt level. + * @arg FSMC_IT_FALLING_EDGE Interrupt falling edge. * @retval None */ #define __FSMC_NAND_ENABLE_IT(__INSTANCE__, __BANK__, __INTERRUPT__) (((__BANK__) == FSMC_NAND_BANK2)? SET_BIT((__INSTANCE__)->SR2, (__INTERRUPT__)): \ @@ -610,13 +848,13 @@ typedef struct /** * @brief Disable the NAND device interrupt. - * @param __INSTANCE__: FSMC_NAND Instance - * @param __BANK__: FSMC_NAND Bank - * @param __INTERRUPT__: FSMC_NAND interrupt + * @param __INSTANCE__ FSMC_NAND Instance + * @param __BANK__ FSMC_NAND Bank + * @param __INTERRUPT__ FSMC_NAND interrupt * This parameter can be any combination of the following values: - * @arg FSMC_IT_RISING_EDGE: Interrupt rising edge. - * @arg FSMC_IT_LEVEL: Interrupt level. - * @arg FSMC_IT_FALLING_EDGE: Interrupt falling edge. + * @arg FSMC_IT_RISING_EDGE Interrupt rising edge. + * @arg FSMC_IT_LEVEL Interrupt level. + * @arg FSMC_IT_FALLING_EDGE Interrupt falling edge. * @retval None */ #define __FSMC_NAND_DISABLE_IT(__INSTANCE__, __BANK__, __INTERRUPT__) (((__BANK__) == FSMC_NAND_BANK2)? CLEAR_BIT((__INSTANCE__)->SR2, (__INTERRUPT__)): \ @@ -624,28 +862,29 @@ typedef struct /** * @brief Get flag status of the NAND device. - * @param __INSTANCE__: FSMC_NAND Instance - * @param __BANK__ : FSMC_NAND Bank - * @param __FLAG__ : FSMC_NAND flag + * @param __INSTANCE__ FSMC_NAND Instance + * @param __BANK__ FSMC_NAND Bank + * @param __FLAG__ FSMC_NAND flag * This parameter can be any combination of the following values: - * @arg FSMC_FLAG_RISING_EDGE: Interrupt rising edge flag. - * @arg FSMC_FLAG_LEVEL: Interrupt level edge flag. - * @arg FSMC_FLAG_FALLING_EDGE: Interrupt falling edge flag. - * @arg FSMC_FLAG_FEMPT: FIFO empty flag. + * @arg FSMC_FLAG_RISING_EDGE Interrupt rising edge flag. + * @arg FSMC_FLAG_LEVEL Interrupt level edge flag. + * @arg FSMC_FLAG_FALLING_EDGE Interrupt falling edge flag. + * @arg FSMC_FLAG_FEMPT FIFO empty flag. * @retval The state of FLAG (SET or RESET). */ #define __FSMC_NAND_GET_FLAG(__INSTANCE__, __BANK__, __FLAG__) (((__BANK__) == FSMC_NAND_BANK2)? (((__INSTANCE__)->SR2 &(__FLAG__)) == (__FLAG__)): \ (((__INSTANCE__)->SR3 &(__FLAG__)) == (__FLAG__))) + /** * @brief Clear flag status of the NAND device. - * @param __INSTANCE__: FSMC_NAND Instance - * @param __BANK__: FSMC_NAND Bank - * @param __FLAG__: FSMC_NAND flag + * @param __INSTANCE__ FSMC_NAND Instance + * @param __BANK__ FSMC_NAND Bank + * @param __FLAG__ FSMC_NAND flag * This parameter can be any combination of the following values: - * @arg FSMC_FLAG_RISING_EDGE: Interrupt rising edge flag. - * @arg FSMC_FLAG_LEVEL: Interrupt level edge flag. - * @arg FSMC_FLAG_FALLING_EDGE: Interrupt falling edge flag. - * @arg FSMC_FLAG_FEMPT: FIFO empty flag. + * @arg FSMC_FLAG_RISING_EDGE Interrupt rising edge flag. + * @arg FSMC_FLAG_LEVEL Interrupt level edge flag. + * @arg FSMC_FLAG_FALLING_EDGE Interrupt falling edge flag. + * @arg FSMC_FLAG_FEMPT FIFO empty flag. * @retval None */ #define __FSMC_NAND_CLEAR_FLAG(__INSTANCE__, __BANK__, __FLAG__) (((__BANK__) == FSMC_NAND_BANK2)? CLEAR_BIT((__INSTANCE__)->SR2, (__FLAG__)): \ @@ -653,50 +892,50 @@ typedef struct /** * @brief Enable the PCCARD device interrupt. - * @param __INSTANCE__: FSMC_PCCARD Instance - * @param __INTERRUPT__: FSMC_PCCARD interrupt + * @param __INSTANCE__ FSMC_PCCARD Instance + * @param __INTERRUPT__ FSMC_PCCARD interrupt * This parameter can be any combination of the following values: - * @arg FSMC_IT_RISING_EDGE: Interrupt rising edge. - * @arg FSMC_IT_LEVEL: Interrupt level. - * @arg FSMC_IT_FALLING_EDGE: Interrupt falling edge. + * @arg FSMC_IT_RISING_EDGE Interrupt rising edge. + * @arg FSMC_IT_LEVEL Interrupt level. + * @arg FSMC_IT_FALLING_EDGE Interrupt falling edge. * @retval None */ #define __FSMC_PCCARD_ENABLE_IT(__INSTANCE__, __INTERRUPT__) SET_BIT((__INSTANCE__)->SR4, (__INTERRUPT__)) /** * @brief Disable the PCCARD device interrupt. - * @param __INSTANCE__: FSMC_PCCARD Instance - * @param __INTERRUPT__: FSMC_PCCARD interrupt + * @param __INSTANCE__ FSMC_PCCARD Instance + * @param __INTERRUPT__ FSMC_PCCARD interrupt * This parameter can be any combination of the following values: - * @arg FSMC_IT_RISING_EDGE: Interrupt rising edge. - * @arg FSMC_IT_LEVEL: Interrupt level. - * @arg FSMC_IT_FALLING_EDGE: Interrupt falling edge. + * @arg FSMC_IT_RISING_EDGE Interrupt rising edge. + * @arg FSMC_IT_LEVEL Interrupt level. + * @arg FSMC_IT_FALLING_EDGE Interrupt falling edge. * @retval None */ #define __FSMC_PCCARD_DISABLE_IT(__INSTANCE__, __INTERRUPT__) CLEAR_BIT((__INSTANCE__)->SR4, (__INTERRUPT__)) /** * @brief Get flag status of the PCCARD device. - * @param __INSTANCE__: FSMC_PCCARD Instance - * @param __FLAG__: FSMC_PCCARD flag + * @param __INSTANCE__ FSMC_PCCARD Instance + * @param __FLAG__ FSMC_PCCARD flag * This parameter can be any combination of the following values: - * @arg FSMC_FLAG_RISING_EDGE: Interrupt rising edge flag. - * @arg FSMC_FLAG_LEVEL: Interrupt level edge flag. - * @arg FSMC_FLAG_FALLING_EDGE: Interrupt falling edge flag. - * @arg FSMC_FLAG_FEMPT: FIFO empty flag. + * @arg FSMC_FLAG_RISING_EDGE Interrupt rising edge flag. + * @arg FSMC_FLAG_LEVEL Interrupt level edge flag. + * @arg FSMC_FLAG_FALLING_EDGE Interrupt falling edge flag. + * @arg FSMC_FLAG_FEMPT FIFO empty flag. * @retval The state of FLAG (SET or RESET). */ #define __FSMC_PCCARD_GET_FLAG(__INSTANCE__, __FLAG__) (((__INSTANCE__)->SR4 &(__FLAG__)) == (__FLAG__)) /** * @brief Clear flag status of the PCCARD device. - * @param __INSTANCE__: FSMC_PCCARD Instance - * @param __FLAG__: FSMC_PCCARD flag + * @param __INSTANCE__ FSMC_PCCARD Instance + * @param __FLAG__ FSMC_PCCARD flag * This parameter can be any combination of the following values: - * @arg FSMC_FLAG_RISING_EDGE: Interrupt rising edge flag. - * @arg FSMC_FLAG_LEVEL: Interrupt level edge flag. - * @arg FSMC_FLAG_FALLING_EDGE: Interrupt falling edge flag. - * @arg FSMC_FLAG_FEMPT: FIFO empty flag. + * @arg FSMC_FLAG_RISING_EDGE Interrupt rising edge flag. + * @arg FSMC_FLAG_LEVEL Interrupt level edge flag. + * @arg FSMC_FLAG_FALLING_EDGE Interrupt falling edge flag. + * @arg FSMC_FLAG_FEMPT FIFO empty flag. * @retval None */ #define __FSMC_PCCARD_CLEAR_FLAG(__INSTANCE__, __FLAG__) CLEAR_BIT((__INSTANCE__)->SR4, (__FLAG__)) @@ -704,296 +943,46 @@ typedef struct /** * @} */ -#endif /* STM32F101xE || STM32F103xE || STM32F101xG || STM32F103xG */ - -/** - * @} - */ - -/** @defgroup FSMC_LL_Private_Macros FSMC Low Layer Private Macros - * @{ - */ -#define IS_FSMC_NORSRAM_BANK(__BANK__) (((__BANK__) == FSMC_NORSRAM_BANK1) || \ - ((__BANK__) == FSMC_NORSRAM_BANK2) || \ - ((__BANK__) == FSMC_NORSRAM_BANK3) || \ - ((__BANK__) == FSMC_NORSRAM_BANK4)) - -#define IS_FSMC_MUX(__MUX__) (((__MUX__) == FSMC_DATA_ADDRESS_MUX_DISABLE) || \ - ((__MUX__) == FSMC_DATA_ADDRESS_MUX_ENABLE)) - -#define IS_FSMC_MEMORY(__MEMORY__) (((__MEMORY__) == FSMC_MEMORY_TYPE_SRAM) || \ - ((__MEMORY__) == FSMC_MEMORY_TYPE_PSRAM)|| \ - ((__MEMORY__) == FSMC_MEMORY_TYPE_NOR)) - -#define IS_FSMC_NORSRAM_MEMORY_WIDTH(__WIDTH__) (((__WIDTH__) == FSMC_NORSRAM_MEM_BUS_WIDTH_8) || \ - ((__WIDTH__) == FSMC_NORSRAM_MEM_BUS_WIDTH_16) || \ - ((__WIDTH__) == FSMC_NORSRAM_MEM_BUS_WIDTH_32)) - -#define IS_FSMC_WRITE_BURST(__BURST__) (((__BURST__) == FSMC_WRITE_BURST_DISABLE) || \ - ((__BURST__) == FSMC_WRITE_BURST_ENABLE)) - -#define IS_FSMC_ACCESS_MODE(__MODE__) (((__MODE__) == FSMC_ACCESS_MODE_A) || \ - ((__MODE__) == FSMC_ACCESS_MODE_B) || \ - ((__MODE__) == FSMC_ACCESS_MODE_C) || \ - ((__MODE__) == FSMC_ACCESS_MODE_D)) - -#define IS_FSMC_NAND_BANK(__BANK__) (((__BANK__) == FSMC_NAND_BANK2) || \ - ((__BANK__) == FSMC_NAND_BANK3)) - -#define IS_FSMC_WAIT_FEATURE(__FEATURE__) (((__FEATURE__) == FSMC_NAND_PCC_WAIT_FEATURE_DISABLE) || \ - ((__FEATURE__) == FSMC_NAND_PCC_WAIT_FEATURE_ENABLE)) - -#define IS_FSMC_NAND_MEMORY_WIDTH(__WIDTH__) (((__WIDTH__) == FSMC_NAND_PCC_MEM_BUS_WIDTH_8) || \ - ((__WIDTH__) == FSMC_NAND_PCC_MEM_BUS_WIDTH_16)) - -#define IS_FSMC_ECC_STATE(__STATE__) (((__STATE__) == FSMC_NAND_ECC_DISABLE) || \ - ((__STATE__) == FSMC_NAND_ECC_ENABLE)) - -#define IS_FSMC_ECCPAGE_SIZE(__SIZE__) (((__SIZE__) == FSMC_NAND_ECC_PAGE_SIZE_256BYTE) || \ - ((__SIZE__) == FSMC_NAND_ECC_PAGE_SIZE_512BYTE) || \ - ((__SIZE__) == FSMC_NAND_ECC_PAGE_SIZE_1024BYTE) || \ - ((__SIZE__) == FSMC_NAND_ECC_PAGE_SIZE_2048BYTE) || \ - ((__SIZE__) == FSMC_NAND_ECC_PAGE_SIZE_4096BYTE) || \ - ((__SIZE__) == FSMC_NAND_ECC_PAGE_SIZE_8192BYTE)) - -/** @defgroup FSMC_TCLR_Setup_Time FSMC_TCLR_Setup_Time - * @{ - */ -#define IS_FSMC_TCLR_TIME(__TIME__) ((__TIME__) <= 255U) -/** - * @} - */ - -/** @defgroup FSMC_TAR_Setup_Time FSMC_TAR_Setup_Time - * @{ - */ -#define IS_FSMC_TAR_TIME(__TIME__) ((__TIME__) <= 255U) -/** - * @} - */ - -/** @defgroup FSMC_Setup_Time FSMC_Setup_Time - * @{ - */ -#define IS_FSMC_SETUP_TIME(__TIME__) ((__TIME__) <= 255U) -/** - * @} - */ - -/** @defgroup FSMC_Wait_Setup_Time FSMC_Wait_Setup_Time - * @{ - */ -#define IS_FSMC_WAIT_TIME(__TIME__) ((__TIME__) <= 255U) -/** - * @} - */ - -/** @defgroup FSMC_Hold_Setup_Time FSMC_Hold_Setup_Time - * @{ - */ -#define IS_FSMC_HOLD_TIME(__TIME__) ((__TIME__) <= 255U) -/** - * @} - */ - -/** @defgroup FSMC_HiZ_Setup_Time FSMC_HiZ_Setup_Time - * @{ - */ -#define IS_FSMC_HIZ_TIME(__TIME__) ((__TIME__) <= 255U) -/** - * @} - */ - -/** @defgroup FSMC_NORSRAM_Device_Instance FSMC NOR/SRAM Device Instance - * @{ - */ -#define IS_FSMC_NORSRAM_DEVICE(__INSTANCE__) ((__INSTANCE__) == FSMC_NORSRAM_DEVICE) -/** - * @} - */ - -/** @defgroup FSMC_NORSRAM_EXTENDED_Device_Instance FSMC NOR/SRAM EXTENDED Device Instance - * @{ - */ -#define IS_FSMC_NORSRAM_EXTENDED_DEVICE(__INSTANCE__) ((__INSTANCE__) == FSMC_NORSRAM_EXTENDED_DEVICE) -/** - * @} - */ - -/** @defgroup FSMC_NAND_Device_Instance FSMC NAND Device Instance - * @{ - */ -#define IS_FSMC_NAND_DEVICE(__INSTANCE__) ((__INSTANCE__) == FSMC_NAND_DEVICE) -/** - * @} - */ - -/** @defgroup FSMC_PCCARD_Device_Instance FSMC PCCARD Device Instance - * @{ - */ -#define IS_FSMC_PCCARD_DEVICE(__INSTANCE__) ((__INSTANCE__) == FSMC_PCCARD_DEVICE) - -/** - * @} - */ -#define IS_FSMC_BURSTMODE(__STATE__) (((__STATE__) == FSMC_BURST_ACCESS_MODE_DISABLE) || \ - ((__STATE__) == FSMC_BURST_ACCESS_MODE_ENABLE)) - -#define IS_FSMC_WAIT_POLARITY(__POLARITY__) (((__POLARITY__) == FSMC_WAIT_SIGNAL_POLARITY_LOW) || \ - ((__POLARITY__) == FSMC_WAIT_SIGNAL_POLARITY_HIGH)) - -#define IS_FSMC_WRAP_MODE(__MODE__) (((__MODE__) == FSMC_WRAP_MODE_DISABLE) || \ - ((__MODE__) == FSMC_WRAP_MODE_ENABLE)) - -#define IS_FSMC_WAIT_SIGNAL_ACTIVE(__ACTIVE__) (((__ACTIVE__) == FSMC_WAIT_TIMING_BEFORE_WS) || \ - ((__ACTIVE__) == FSMC_WAIT_TIMING_DURING_WS)) - -#define IS_FSMC_WRITE_OPERATION(__OPERATION__) (((__OPERATION__) == FSMC_WRITE_OPERATION_DISABLE) || \ - ((__OPERATION__) == FSMC_WRITE_OPERATION_ENABLE)) -#define IS_FSMC_WAITE_SIGNAL(__SIGNAL__) (((__SIGNAL__) == FSMC_WAIT_SIGNAL_DISABLE) || \ - ((__SIGNAL__) == FSMC_WAIT_SIGNAL_ENABLE)) - -#define IS_FSMC_EXTENDED_MODE(__MODE__) (((__MODE__) == FSMC_EXTENDED_MODE_DISABLE) || \ - ((__MODE__) == FSMC_EXTENDED_MODE_ENABLE)) - -#define IS_FSMC_ASYNWAIT(__STATE__) (((__STATE__) == FSMC_ASYNCHRONOUS_WAIT_DISABLE) || \ - ((__STATE__) == FSMC_ASYNCHRONOUS_WAIT_ENABLE)) - -#define IS_FSMC_CLK_DIV(__DIV__) (((__DIV__) > 1U) && ((__DIV__) <= 16U)) - -/** @defgroup FSMC_Data_Latency FSMC Data Latency - * @{ - */ -#define IS_FSMC_DATA_LATENCY(__LATENCY__) (((__LATENCY__) > 1U) && ((__LATENCY__) <= 17U)) -/** - * @} - */ - -/** @defgroup FSMC_Address_Setup_Time FSMC Address Setup Time - * @{ - */ -#define IS_FSMC_ADDRESS_SETUP_TIME(__TIME__) ((__TIME__) <= 15U) -/** - * @} - */ - -/** @defgroup FSMC_Address_Hold_Time FSMC Address Hold Time - * @{ - */ -#define IS_FSMC_ADDRESS_HOLD_TIME(__TIME__) (((__TIME__) > 0U) && ((__TIME__) <= 15U)) -/** - * @} - */ - -/** @defgroup FSMC_Data_Setup_Time FSMC Data Setup Time - * @{ - */ -#define IS_FSMC_DATASETUP_TIME(__TIME__) (((__TIME__) > 0U) && ((__TIME__) <= 255U)) -/** - * @} - */ - -/** @defgroup FSMC_Bus_Turn_around_Duration FSMC Bus Turn around Duration - * @{ - */ -#define IS_FSMC_TURNAROUND_TIME(__TIME__) ((__TIME__) <= 15U) -/** - * @} - */ - -/** - * @} - */ - -/** @defgroup FSMC_LL_Private_Constants FSMC Low Layer Private Constants - * @{ - */ - -/* ----------------------- FSMC registers bit mask --------------------------- */ -#if (defined (STM32F101xE) || defined(STM32F103xE) || defined(STM32F101xG) || defined(STM32F103xG)) -/* --- PCR Register ---*/ -/* PCR register clear mask */ -#define PCR_CLEAR_MASK ((uint32_t)(FSMC_PCRx_PWAITEN | FSMC_PCRx_PBKEN | \ - FSMC_PCRx_PTYP | FSMC_PCRx_PWID | \ - FSMC_PCRx_ECCEN | FSMC_PCRx_TCLR | \ - FSMC_PCRx_TAR | FSMC_PCRx_ECCPS)) - -/* --- PMEM Register ---*/ -/* PMEM register clear mask */ -#define PMEM_CLEAR_MASK ((uint32_t)(FSMC_PMEMx_MEMSETx | FSMC_PMEMx_MEMWAITx |\ - FSMC_PMEMx_MEMHOLDx | FSMC_PMEMx_MEMHIZx)) - -/* --- PATT Register ---*/ -/* PATT register clear mask */ -#define PATT_CLEAR_MASK ((uint32_t)(FSMC_PATTx_ATTSETx | FSMC_PATTx_ATTWAITx |\ - FSMC_PATTx_ATTHOLDx | FSMC_PATTx_ATTHIZx)) - -#endif /* STM32F101xE || STM32F103xE || STM32F101xG || STM32F103xG */ -/* --- BCR Register ---*/ -/* BCR register clear mask */ -#define BCR_CLEAR_MASK ((uint32_t)(FSMC_BCRx_FACCEN | FSMC_BCRx_MUXEN | \ - FSMC_BCRx_MTYP | FSMC_BCRx_MWID | \ - FSMC_BCRx_BURSTEN | FSMC_BCRx_WAITPOL | \ - FSMC_BCRx_WRAPMOD | FSMC_BCRx_WAITCFG | \ - FSMC_BCRx_WREN | FSMC_BCRx_WAITEN | \ - FSMC_BCRx_EXTMOD | FSMC_BCRx_ASYNCWAIT | \ - FSMC_BCRx_CBURSTRW)) -/* --- BTR Register ---*/ -/* BTR register clear mask */ -#define BTR_CLEAR_MASK ((uint32_t)(FSMC_BTRx_ADDSET | FSMC_BTRx_ADDHLD |\ - FSMC_BTRx_DATAST | FSMC_BTRx_BUSTURN |\ - FSMC_BTRx_CLKDIV | FSMC_BTRx_DATLAT |\ - FSMC_BTRx_ACCMOD)) - -/* --- BWTR Register ---*/ -/* BWTR register clear mask */ -#if (defined(STM32F101xE) || defined(STM32F103xE) || defined(STM32F101xG) || defined(STM32F103xG)) -#define BWTR_CLEAR_MASK ((uint32_t)(FSMC_BWTRx_ADDSET | FSMC_BWTRx_ADDHLD | \ - FSMC_BWTRx_DATAST | FSMC_BWTRx_ACCMOD | \ - FSMC_BWTRx_BUSTURN)) -#else -#define BWTR_CLEAR_MASK ((uint32_t)(FSMC_BWTRx_ADDSET | FSMC_BWTRx_ADDHLD | \ - FSMC_BWTRx_DATAST | FSMC_BWTRx_ACCMOD | \ - FSMC_BWTRx_CLKDIV | FSMC_BWTRx_DATLAT)) #endif /* STM32F101xE || STM32F103xE || STM32F101xG || STM32F103xG */ -/* --- PIO4 Register ---*/ -/* PIO4 register clear mask */ -#define PIO4_CLEAR_MASK ((uint32_t)(FSMC_PIO4_IOSET4 | FSMC_PIO4_IOWAIT4 | \ - FSMC_PIO4_IOHOLD4 | FSMC_PIO4_IOHIZ4)) /** * @} */ + /* Exported functions --------------------------------------------------------*/ /** @addtogroup FSMC_LL_Exported_Functions - * @{ - */ + * @{ + */ /** @addtogroup FSMC_NORSRAM - * @{ - */ + * @{ + */ /** @addtogroup FSMC_NORSRAM_Group1 - * @{ - */ + * @{ + */ + /* FSMC_NORSRAM Controller functions ******************************************/ /* Initialization/de-initialization functions */ HAL_StatusTypeDef FSMC_NORSRAM_Init(FSMC_NORSRAM_TypeDef *Device, FSMC_NORSRAM_InitTypeDef *Init); HAL_StatusTypeDef FSMC_NORSRAM_Timing_Init(FSMC_NORSRAM_TypeDef *Device, FSMC_NORSRAM_TimingTypeDef *Timing, uint32_t Bank); HAL_StatusTypeDef FSMC_NORSRAM_Extended_Timing_Init(FSMC_NORSRAM_EXTENDED_TypeDef *Device, FSMC_NORSRAM_TimingTypeDef *Timing, uint32_t Bank, uint32_t ExtendedMode); HAL_StatusTypeDef FSMC_NORSRAM_DeInit(FSMC_NORSRAM_TypeDef *Device, FSMC_NORSRAM_EXTENDED_TypeDef *ExDevice, uint32_t Bank); + /** * @} */ /** @addtogroup FSMC_NORSRAM_Group2 - * @{ - */ + * @{ + */ + /* FSMC_NORSRAM Control functions */ HAL_StatusTypeDef FSMC_NORSRAM_WriteOperation_Enable(FSMC_NORSRAM_TypeDef *Device, uint32_t Bank); HAL_StatusTypeDef FSMC_NORSRAM_WriteOperation_Disable(FSMC_NORSRAM_TypeDef *Device, uint32_t Bank); + /** * @} */ @@ -1004,29 +993,33 @@ HAL_StatusTypeDef FSMC_NORSRAM_WriteOperation_Disable(FSMC_NORSRAM_TypeDef *Dev #if (defined(STM32F101xE) || defined(STM32F103xE) || defined(STM32F101xG) || defined(STM32F103xG)) /** @addtogroup FSMC_NAND - * @{ - */ + * @{ + */ /* FSMC_NAND Controller functions **********************************************/ /* Initialization/de-initialization functions */ /** @addtogroup FSMC_NAND_Exported_Functions_Group1 - * @{ - */ + * @{ + */ + HAL_StatusTypeDef FSMC_NAND_Init(FSMC_NAND_TypeDef *Device, FSMC_NAND_InitTypeDef *Init); HAL_StatusTypeDef FSMC_NAND_CommonSpace_Timing_Init(FSMC_NAND_TypeDef *Device, FSMC_NAND_PCC_TimingTypeDef *Timing, uint32_t Bank); HAL_StatusTypeDef FSMC_NAND_AttributeSpace_Timing_Init(FSMC_NAND_TypeDef *Device, FSMC_NAND_PCC_TimingTypeDef *Timing, uint32_t Bank); HAL_StatusTypeDef FSMC_NAND_DeInit(FSMC_NAND_TypeDef *Device, uint32_t Bank); + /** * @} */ /* FSMC_NAND Control functions */ /** @addtogroup FSMC_NAND_Exported_Functions_Group2 - * @{ - */ + * @{ + */ + HAL_StatusTypeDef FSMC_NAND_ECC_Enable(FSMC_NAND_TypeDef *Device, uint32_t Bank); HAL_StatusTypeDef FSMC_NAND_ECC_Disable(FSMC_NAND_TypeDef *Device, uint32_t Bank); HAL_StatusTypeDef FSMC_NAND_GetECC(FSMC_NAND_TypeDef *Device, uint32_t *ECCval, uint32_t Bank, uint32_t Timeout); + /** * @} */ @@ -1036,19 +1029,21 @@ HAL_StatusTypeDef FSMC_NAND_GetECC(FSMC_NAND_TypeDef *Device, uint32_t *ECCval, */ /** @addtogroup FSMC_PCCARD - * @{ - */ + * @{ + */ /* FSMC_PCCARD Controller functions ********************************************/ /* Initialization/de-initialization functions */ /** @addtogroup FSMC_PCCARD_Exported_Functions_Group1 - * @{ - */ + * @{ + */ + HAL_StatusTypeDef FSMC_PCCARD_Init(FSMC_PCCARD_TypeDef *Device, FSMC_PCCARD_InitTypeDef *Init); HAL_StatusTypeDef FSMC_PCCARD_CommonSpace_Timing_Init(FSMC_PCCARD_TypeDef *Device, FSMC_NAND_PCC_TimingTypeDef *Timing); HAL_StatusTypeDef FSMC_PCCARD_AttributeSpace_Timing_Init(FSMC_PCCARD_TypeDef *Device, FSMC_NAND_PCC_TimingTypeDef *Timing); HAL_StatusTypeDef FSMC_PCCARD_IOSpace_Timing_Init(FSMC_PCCARD_TypeDef *Device, FSMC_NAND_PCC_TimingTypeDef *Timing); HAL_StatusTypeDef FSMC_PCCARD_DeInit(FSMC_PCCARD_TypeDef *Device); + /** * @} */ @@ -1056,8 +1051,8 @@ HAL_StatusTypeDef FSMC_PCCARD_DeInit(FSMC_PCCARD_TypeDef *Device); /** * @} */ -#endif /* STM32F101xE || STM32F103xE || STM32F101xG || STM32F103xG */ +#endif /* STM32F101xE || STM32F103xE || STM32F101xG || STM32F103xG */ /** * @} */ @@ -1065,6 +1060,7 @@ HAL_StatusTypeDef FSMC_PCCARD_DeInit(FSMC_PCCARD_TypeDef *Device); /** * @} */ + #endif /* FSMC_BANK1 */ /** diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_gpio.c b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_gpio.c index 43360fa9d68..ee061717120 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_gpio.c +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_gpio.c @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_ll_gpio.c * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version $VERSION$ + * @date $DATE$ * @brief GPIO LL module driver. ****************************************************************************** * @attention diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_gpio.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_gpio.h index 6035560fe4b..91af0dac53c 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_gpio.h +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_gpio.h @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_ll_gpio.h * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version $VERSION$ + * @date $DATE$ * @brief Header file of GPIO LL module. ****************************************************************************** * @attention @@ -127,28 +127,28 @@ typedef struct /** @defgroup GPIO_LL_EC_PIN PIN * @{ */ -#define LL_GPIO_PIN_0 (GPIO_BSRR_BS0 << 8) | 0x00000001U /*!< Select pin 0 */ -#define LL_GPIO_PIN_1 (GPIO_BSRR_BS1 << 8) | 0x00000002U /*!< Select pin 1 */ -#define LL_GPIO_PIN_2 (GPIO_BSRR_BS2 << 8) | 0x00000004U /*!< Select pin 2 */ -#define LL_GPIO_PIN_3 (GPIO_BSRR_BS3 << 8) | 0x00000008U /*!< Select pin 3 */ -#define LL_GPIO_PIN_4 (GPIO_BSRR_BS4 << 8) | 0x00000010U /*!< Select pin 4 */ -#define LL_GPIO_PIN_5 (GPIO_BSRR_BS5 << 8) | 0x00000020U /*!< Select pin 5 */ -#define LL_GPIO_PIN_6 (GPIO_BSRR_BS6 << 8) | 0x00000040U /*!< Select pin 6 */ -#define LL_GPIO_PIN_7 (GPIO_BSRR_BS7 << 8) | 0x00000080U /*!< Select pin 7 */ -#define LL_GPIO_PIN_8 (GPIO_BSRR_BS8 << 8) | 0x04000001U /*!< Select pin 8 */ -#define LL_GPIO_PIN_9 (GPIO_BSRR_BS9 << 8) | 0x04000002U /*!< Select pin 9 */ -#define LL_GPIO_PIN_10 (GPIO_BSRR_BS10 << 8) | 0x04000004U /*!< Select pin 10 */ -#define LL_GPIO_PIN_11 (GPIO_BSRR_BS11 << 8) | 0x04000008U /*!< Select pin 11 */ -#define LL_GPIO_PIN_12 (GPIO_BSRR_BS12 << 8) | 0x04000010U /*!< Select pin 12 */ -#define LL_GPIO_PIN_13 (GPIO_BSRR_BS13 << 8) | 0x04000020U /*!< Select pin 13 */ -#define LL_GPIO_PIN_14 (GPIO_BSRR_BS14 << 8) | 0x04000040U /*!< Select pin 14 */ -#define LL_GPIO_PIN_15 (GPIO_BSRR_BS15 << 8) | 0x04000080U /*!< Select pin 15 */ -#define LL_GPIO_PIN_ALL (LL_GPIO_PIN_0 | LL_GPIO_PIN_1 | LL_GPIO_PIN_2 | \ - LL_GPIO_PIN_3 | LL_GPIO_PIN_4 | LL_GPIO_PIN_5 | \ - LL_GPIO_PIN_6 | LL_GPIO_PIN_7 | LL_GPIO_PIN_8 | \ - LL_GPIO_PIN_9 | LL_GPIO_PIN_10 | LL_GPIO_PIN_11 | \ - LL_GPIO_PIN_12 | LL_GPIO_PIN_13 | LL_GPIO_PIN_14 | \ - LL_GPIO_PIN_15) /*!< Select all pins */ +#define LL_GPIO_PIN_0 (GPIO_BSRR_BS0 << 8) | 0x00000001U /*!< Select pin 0 */ +#define LL_GPIO_PIN_1 (GPIO_BSRR_BS1 << 8) | 0x00000002U /*!< Select pin 1 */ +#define LL_GPIO_PIN_2 (GPIO_BSRR_BS2 << 8) | 0x00000004U /*!< Select pin 2 */ +#define LL_GPIO_PIN_3 (GPIO_BSRR_BS3 << 8) | 0x00000008U /*!< Select pin 3 */ +#define LL_GPIO_PIN_4 (GPIO_BSRR_BS4 << 8) | 0x00000010U /*!< Select pin 4 */ +#define LL_GPIO_PIN_5 (GPIO_BSRR_BS5 << 8) | 0x00000020U /*!< Select pin 5 */ +#define LL_GPIO_PIN_6 (GPIO_BSRR_BS6 << 8) | 0x00000040U /*!< Select pin 6 */ +#define LL_GPIO_PIN_7 (GPIO_BSRR_BS7 << 8) | 0x00000080U /*!< Select pin 7 */ +#define LL_GPIO_PIN_8 (GPIO_BSRR_BS8 << 8) | 0x04000001U /*!< Select pin 8 */ +#define LL_GPIO_PIN_9 (GPIO_BSRR_BS9 << 8) | 0x04000002U /*!< Select pin 9 */ +#define LL_GPIO_PIN_10 (GPIO_BSRR_BS10 << 8) | 0x04000004U /*!< Select pin 10 */ +#define LL_GPIO_PIN_11 (GPIO_BSRR_BS11 << 8) | 0x04000008U /*!< Select pin 11 */ +#define LL_GPIO_PIN_12 (GPIO_BSRR_BS12 << 8) | 0x04000010U /*!< Select pin 12 */ +#define LL_GPIO_PIN_13 (GPIO_BSRR_BS13 << 8) | 0x04000020U /*!< Select pin 13 */ +#define LL_GPIO_PIN_14 (GPIO_BSRR_BS14 << 8) | 0x04000040U /*!< Select pin 14 */ +#define LL_GPIO_PIN_15 (GPIO_BSRR_BS15 << 8) | 0x04000080U /*!< Select pin 15 */ +#define LL_GPIO_PIN_ALL (LL_GPIO_PIN_0 | LL_GPIO_PIN_1 | LL_GPIO_PIN_2 | \ + LL_GPIO_PIN_3 | LL_GPIO_PIN_4 | LL_GPIO_PIN_5 | \ + LL_GPIO_PIN_6 | LL_GPIO_PIN_7 | LL_GPIO_PIN_8 | \ + LL_GPIO_PIN_9 | LL_GPIO_PIN_10 | LL_GPIO_PIN_11 | \ + LL_GPIO_PIN_12 | LL_GPIO_PIN_13 | LL_GPIO_PIN_14 | \ + LL_GPIO_PIN_15) /*!< Select all pins */ /** * @} */ @@ -202,22 +202,22 @@ typedef struct * @{ */ -#define LL_GPIO_AF_EVENTOUT_PIN_0 AFIO_EVCR_PIN_PX0 /*!< EVENTOUT on pin 0 */ -#define LL_GPIO_AF_EVENTOUT_PIN_1 AFIO_EVCR_PIN_PX1 /*!< EVENTOUT on pin 1 */ -#define LL_GPIO_AF_EVENTOUT_PIN_2 AFIO_EVCR_PIN_PX2 /*!< EVENTOUT on pin 2 */ -#define LL_GPIO_AF_EVENTOUT_PIN_3 AFIO_EVCR_PIN_PX3 /*!< EVENTOUT on pin 3 */ -#define LL_GPIO_AF_EVENTOUT_PIN_4 AFIO_EVCR_PIN_PX4 /*!< EVENTOUT on pin 4 */ -#define LL_GPIO_AF_EVENTOUT_PIN_5 AFIO_EVCR_PIN_PX5 /*!< EVENTOUT on pin 5 */ -#define LL_GPIO_AF_EVENTOUT_PIN_6 AFIO_EVCR_PIN_PX6 /*!< EVENTOUT on pin 6 */ -#define LL_GPIO_AF_EVENTOUT_PIN_7 AFIO_EVCR_PIN_PX7 /*!< EVENTOUT on pin 7 */ -#define LL_GPIO_AF_EVENTOUT_PIN_8 AFIO_EVCR_PIN_PX8 /*!< EVENTOUT on pin 8 */ -#define LL_GPIO_AF_EVENTOUT_PIN_9 AFIO_EVCR_PIN_PX9 /*!< EVENTOUT on pin 9 */ -#define LL_GPIO_AF_EVENTOUT_PIN_10 AFIO_EVCR_PIN_PX10 /*!< EVENTOUT on pin 10 */ -#define LL_GPIO_AF_EVENTOUT_PIN_11 AFIO_EVCR_PIN_PX11 /*!< EVENTOUT on pin 11 */ -#define LL_GPIO_AF_EVENTOUT_PIN_12 AFIO_EVCR_PIN_PX12 /*!< EVENTOUT on pin 12 */ -#define LL_GPIO_AF_EVENTOUT_PIN_13 AFIO_EVCR_PIN_PX13 /*!< EVENTOUT on pin 13 */ -#define LL_GPIO_AF_EVENTOUT_PIN_14 AFIO_EVCR_PIN_PX14 /*!< EVENTOUT on pin 14 */ -#define LL_GPIO_AF_EVENTOUT_PIN_15 AFIO_EVCR_PIN_PX15 /*!< EVENTOUT on pin 15 */ +#define LL_GPIO_AFIO_EVENTOUT_PIN_0 AFIO_EVCR_PIN_PX0 /*!< EVENTOUT on pin 0 */ +#define LL_GPIO_AFIO_EVENTOUT_PIN_1 AFIO_EVCR_PIN_PX1 /*!< EVENTOUT on pin 1 */ +#define LL_GPIO_AFIO_EVENTOUT_PIN_2 AFIO_EVCR_PIN_PX2 /*!< EVENTOUT on pin 2 */ +#define LL_GPIO_AFIO_EVENTOUT_PIN_3 AFIO_EVCR_PIN_PX3 /*!< EVENTOUT on pin 3 */ +#define LL_GPIO_AFIO_EVENTOUT_PIN_4 AFIO_EVCR_PIN_PX4 /*!< EVENTOUT on pin 4 */ +#define LL_GPIO_AFIO_EVENTOUT_PIN_5 AFIO_EVCR_PIN_PX5 /*!< EVENTOUT on pin 5 */ +#define LL_GPIO_AFIO_EVENTOUT_PIN_6 AFIO_EVCR_PIN_PX6 /*!< EVENTOUT on pin 6 */ +#define LL_GPIO_AFIO_EVENTOUT_PIN_7 AFIO_EVCR_PIN_PX7 /*!< EVENTOUT on pin 7 */ +#define LL_GPIO_AFIO_EVENTOUT_PIN_8 AFIO_EVCR_PIN_PX8 /*!< EVENTOUT on pin 8 */ +#define LL_GPIO_AFIO_EVENTOUT_PIN_9 AFIO_EVCR_PIN_PX9 /*!< EVENTOUT on pin 9 */ +#define LL_GPIO_AFIO_EVENTOUT_PIN_10 AFIO_EVCR_PIN_PX10 /*!< EVENTOUT on pin 10 */ +#define LL_GPIO_AFIO_EVENTOUT_PIN_11 AFIO_EVCR_PIN_PX11 /*!< EVENTOUT on pin 11 */ +#define LL_GPIO_AFIO_EVENTOUT_PIN_12 AFIO_EVCR_PIN_PX12 /*!< EVENTOUT on pin 12 */ +#define LL_GPIO_AFIO_EVENTOUT_PIN_13 AFIO_EVCR_PIN_PX13 /*!< EVENTOUT on pin 13 */ +#define LL_GPIO_AFIO_EVENTOUT_PIN_14 AFIO_EVCR_PIN_PX14 /*!< EVENTOUT on pin 14 */ +#define LL_GPIO_AFIO_EVENTOUT_PIN_15 AFIO_EVCR_PIN_PX15 /*!< EVENTOUT on pin 15 */ /** * @} @@ -227,11 +227,11 @@ typedef struct * @{ */ -#define LL_GPIO_AF_EVENTOUT_PORT_A AFIO_EVCR_PORT_PA /*!< EVENTOUT on port A */ -#define LL_GPIO_AF_EVENTOUT_PORT_B AFIO_EVCR_PORT_PB /*!< EVENTOUT on port B */ -#define LL_GPIO_AF_EVENTOUT_PORT_C AFIO_EVCR_PORT_PC /*!< EVENTOUT on port C */ -#define LL_GPIO_AF_EVENTOUT_PORT_D AFIO_EVCR_PORT_PD /*!< EVENTOUT on port D */ -#define LL_GPIO_AF_EVENTOUT_PORT_E AFIO_EVCR_PORT_PE /*!< EVENTOUT on port E */ +#define LL_GPIO_AFIO_EVENTOUT_PORT_A AFIO_EVCR_PORT_PA /*!< EVENTOUT on port A */ +#define LL_GPIO_AFIO_EVENTOUT_PORT_B AFIO_EVCR_PORT_PB /*!< EVENTOUT on port B */ +#define LL_GPIO_AFIO_EVENTOUT_PORT_C AFIO_EVCR_PORT_PC /*!< EVENTOUT on port C */ +#define LL_GPIO_AFIO_EVENTOUT_PORT_D AFIO_EVCR_PORT_PD /*!< EVENTOUT on port D */ +#define LL_GPIO_AFIO_EVENTOUT_PORT_E AFIO_EVCR_PORT_PE /*!< EVENTOUT on port E */ /** * @} @@ -240,13 +240,13 @@ typedef struct /** @defgroup GPIO_LL_EC_EXTI_PORT GPIO EXTI PORT * @{ */ -#define LL_GPIO_AF_EXTI_PORTA (uint32_t)0 /*!< EXTI PORT A */ -#define LL_GPIO_AF_EXTI_PORTB (uint32_t)1 /*!< EXTI PORT B */ -#define LL_GPIO_AF_EXTI_PORTC (uint32_t)2 /*!< EXTI PORT C */ -#define LL_GPIO_AF_EXTI_PORTD (uint32_t)3 /*!< EXTI PORT D */ -#define LL_GPIO_AF_EXTI_PORTE (uint32_t)4 /*!< EXTI PORT E */ -#define LL_GPIO_AF_EXTI_PORTF (uint32_t)5 /*!< EXTI PORT F */ -#define LL_GPIO_AF_EXTI_PORTG (uint32_t)6 /*!< EXTI PORT G */ +#define LL_GPIO_AFIO_EXTI_PORTA (uint32_t)0 /*!< EXTI PORT A */ +#define LL_GPIO_AFIO_EXTI_PORTB (uint32_t)1 /*!< EXTI PORT B */ +#define LL_GPIO_AFIO_EXTI_PORTC (uint32_t)2 /*!< EXTI PORT C */ +#define LL_GPIO_AFIO_EXTI_PORTD (uint32_t)3 /*!< EXTI PORT D */ +#define LL_GPIO_AFIO_EXTI_PORTE (uint32_t)4 /*!< EXTI PORT E */ +#define LL_GPIO_AFIO_EXTI_PORTF (uint32_t)5 /*!< EXTI PORT F */ +#define LL_GPIO_AFIO_EXTI_PORTG (uint32_t)6 /*!< EXTI PORT G */ /** * @} */ @@ -254,22 +254,22 @@ typedef struct /** @defgroup GPIO_LL_EC_EXTI_LINE GPIO EXTI LINE * @{ */ -#define LL_GPIO_AF_EXTI_LINE0 (uint32_t)(0x000FU << 16 | 0) /*!< EXTI_POSITION_0 | EXTICR[0] */ -#define LL_GPIO_AF_EXTI_LINE1 (uint32_t)(0x00F0U << 16 | 0) /*!< EXTI_POSITION_4 | EXTICR[0] */ -#define LL_GPIO_AF_EXTI_LINE2 (uint32_t)(0x0F00U << 16 | 0) /*!< EXTI_POSITION_8 | EXTICR[0] */ -#define LL_GPIO_AF_EXTI_LINE3 (uint32_t)(0xF000U << 16 | 0) /*!< EXTI_POSITION_12 | EXTICR[0] */ -#define LL_GPIO_AF_EXTI_LINE4 (uint32_t)(0x000FU << 16 | 1) /*!< EXTI_POSITION_0 | EXTICR[1] */ -#define LL_GPIO_AF_EXTI_LINE5 (uint32_t)(0x00F0U << 16 | 1) /*!< EXTI_POSITION_4 | EXTICR[1] */ -#define LL_GPIO_AF_EXTI_LINE6 (uint32_t)(0x0F00U << 16 | 1) /*!< EXTI_POSITION_8 | EXTICR[1] */ -#define LL_GPIO_AF_EXTI_LINE7 (uint32_t)(0xF000U << 16 | 1) /*!< EXTI_POSITION_12 | EXTICR[1] */ -#define LL_GPIO_AF_EXTI_LINE8 (uint32_t)(0x000FU << 16 | 2) /*!< EXTI_POSITION_0 | EXTICR[2] */ -#define LL_GPIO_AF_EXTI_LINE9 (uint32_t)(0x00F0U << 16 | 2) /*!< EXTI_POSITION_4 | EXTICR[2] */ -#define LL_GPIO_AF_EXTI_LINE10 (uint32_t)(0x0F00U << 16 | 2) /*!< EXTI_POSITION_8 | EXTICR[2] */ -#define LL_GPIO_AF_EXTI_LINE11 (uint32_t)(0xF000U << 16 | 2) /*!< EXTI_POSITION_12 | EXTICR[2] */ -#define LL_GPIO_AF_EXTI_LINE12 (uint32_t)(0x000FU << 16 | 3) /*!< EXTI_POSITION_0 | EXTICR[3] */ -#define LL_GPIO_AF_EXTI_LINE13 (uint32_t)(0x00F0U << 16 | 3) /*!< EXTI_POSITION_4 | EXTICR[3] */ -#define LL_GPIO_AF_EXTI_LINE14 (uint32_t)(0x0F00U << 16 | 3) /*!< EXTI_POSITION_8 | EXTICR[3] */ -#define LL_GPIO_AF_EXTI_LINE15 (uint32_t)(0xF000U << 16 | 3) /*!< EXTI_POSITION_12 | EXTICR[3] */ +#define LL_GPIO_AFIO_EXTI_LINE0 (uint32_t)(0x000FU << 16 | 0) /*!< EXTI_POSITION_0 | EXTICR[0] */ +#define LL_GPIO_AFIO_EXTI_LINE1 (uint32_t)(0x00F0U << 16 | 0) /*!< EXTI_POSITION_4 | EXTICR[0] */ +#define LL_GPIO_AFIO_EXTI_LINE2 (uint32_t)(0x0F00U << 16 | 0) /*!< EXTI_POSITION_8 | EXTICR[0] */ +#define LL_GPIO_AFIO_EXTI_LINE3 (uint32_t)(0xF000U << 16 | 0) /*!< EXTI_POSITION_12 | EXTICR[0] */ +#define LL_GPIO_AFIO_EXTI_LINE4 (uint32_t)(0x000FU << 16 | 1) /*!< EXTI_POSITION_0 | EXTICR[1] */ +#define LL_GPIO_AFIO_EXTI_LINE5 (uint32_t)(0x00F0U << 16 | 1) /*!< EXTI_POSITION_4 | EXTICR[1] */ +#define LL_GPIO_AFIO_EXTI_LINE6 (uint32_t)(0x0F00U << 16 | 1) /*!< EXTI_POSITION_8 | EXTICR[1] */ +#define LL_GPIO_AFIO_EXTI_LINE7 (uint32_t)(0xF000U << 16 | 1) /*!< EXTI_POSITION_12 | EXTICR[1] */ +#define LL_GPIO_AFIO_EXTI_LINE8 (uint32_t)(0x000FU << 16 | 2) /*!< EXTI_POSITION_0 | EXTICR[2] */ +#define LL_GPIO_AFIO_EXTI_LINE9 (uint32_t)(0x00F0U << 16 | 2) /*!< EXTI_POSITION_4 | EXTICR[2] */ +#define LL_GPIO_AFIO_EXTI_LINE10 (uint32_t)(0x0F00U << 16 | 2) /*!< EXTI_POSITION_8 | EXTICR[2] */ +#define LL_GPIO_AFIO_EXTI_LINE11 (uint32_t)(0xF000U << 16 | 2) /*!< EXTI_POSITION_12 | EXTICR[2] */ +#define LL_GPIO_AFIO_EXTI_LINE12 (uint32_t)(0x000FU << 16 | 3) /*!< EXTI_POSITION_0 | EXTICR[3] */ +#define LL_GPIO_AFIO_EXTI_LINE13 (uint32_t)(0x00F0U << 16 | 3) /*!< EXTI_POSITION_4 | EXTICR[3] */ +#define LL_GPIO_AFIO_EXTI_LINE14 (uint32_t)(0x0F00U << 16 | 3) /*!< EXTI_POSITION_8 | EXTICR[3] */ +#define LL_GPIO_AFIO_EXTI_LINE15 (uint32_t)(0xF000U << 16 | 3) /*!< EXTI_POSITION_12 | EXTICR[3] */ /** * @} */ @@ -888,371 +888,305 @@ __STATIC_INLINE void LL_GPIO_TogglePin(GPIO_TypeDef *GPIOx, uint32_t PinMask) * @} */ -/** @defgroup GPIO_AF_REMAPPING Alternate Function Remapping +/** @defgroup GPIO_AFIO_AF_REMAPPING Alternate Function Remapping * @brief This section propose definition to remap the alternate function to some other port/pins. * @{ */ /** * @brief Enable the remapping of SPI1 alternate function NSS, SCK, MISO and MOSI. - * @rmtoll MAPR SPI1_REMAP LL_GPIO_AF_EnableRemap_SPI1 + * @rmtoll MAPR SPI1_REMAP LL_GPIO_AFIO_REMAP_SPI1_ENABLE * @note ENABLE: Remap (NSS/PA15, SCK/PB3, MISO/PB4, MOSI/PB5) * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_EnableRemap_SPI1(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_SPI1_ENABLE(void) { SET_BIT(AFIO->MAPR, AFIO_MAPR_SPI1_REMAP); } /** * @brief Disable the remapping of SPI1 alternate function NSS, SCK, MISO and MOSI. - * @rmtoll MAPR SPI1_REMAP LL_GPIO_AF_DisableRemap_SPI1 + * @rmtoll MAPR SPI1_REMAP LL_GPIO_AFIO_REMAP_SPI1_DISABLE * @note DISABLE: No remap (NSS/PA4, SCK/PA5, MISO/PA6, MOSI/PA7) * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_DisableRemap_SPI1(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_SPI1_DISABLE(void) { CLEAR_BIT(AFIO->MAPR, AFIO_MAPR_SPI1_REMAP); } -/** - * @brief Check if SPI1 has been remaped or not - * @rmtoll MAPR SPI1_REMAP LL_GPIO_AF_IsEnabledRemap_SPI1 - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_GPIO_AF_IsEnabledRemap_SPI1(void) -{ - return (READ_BIT(AFIO->MAPR, AFIO_MAPR_SPI1_REMAP) == (AFIO_MAPR_SPI1_REMAP)); -} - /** * @brief Enable the remapping of I2C1 alternate function SCL and SDA. - * @rmtoll MAPR I2C1_REMAP LL_GPIO_AF_EnableRemap_I2C1 + * @rmtoll MAPR I2C1_REMAP LL_GPIO_AFIO_REMAP_I2C1_ENABLE * @note ENABLE: Remap (SCL/PB8, SDA/PB9) * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_EnableRemap_I2C1(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_I2C1_ENABLE(void) { SET_BIT(AFIO->MAPR, AFIO_MAPR_I2C1_REMAP); } /** * @brief Disable the remapping of I2C1 alternate function SCL and SDA. - * @rmtoll MAPR I2C1_REMAP LL_GPIO_AF_DisableRemap_I2C1 + * @rmtoll MAPR I2C1_REMAP LL_GPIO_AFIO_REMAP_I2C1_DISABLE * @note DISABLE: No remap (SCL/PB6, SDA/PB7) * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_DisableRemap_I2C1(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_I2C1_DISABLE(void) { CLEAR_BIT(AFIO->MAPR, AFIO_MAPR_I2C1_REMAP); } -/** - * @brief Check if I2C1 has been remaped or not - * @rmtoll MAPR I2C1_REMAP LL_GPIO_AF_IsEnabledRemap_I2C1 - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_GPIO_AF_IsEnabledRemap_I2C1(void) -{ - return (READ_BIT(AFIO->MAPR, AFIO_MAPR_I2C1_REMAP) == (AFIO_MAPR_I2C1_REMAP)); -} - /** * @brief Enable the remapping of USART1 alternate function TX and RX. - * @rmtoll MAPR USART1_REMAP LL_GPIO_AF_EnableRemap_USART1 + * @rmtoll MAPR USART1_REMAP LL_GPIO_AFIO_REMAP_USART1_ENABLE * @note ENABLE: Remap (TX/PB6, RX/PB7) * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_EnableRemap_USART1(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_USART1_ENABLE(void) { SET_BIT(AFIO->MAPR, AFIO_MAPR_USART1_REMAP); } /** * @brief Disable the remapping of USART1 alternate function TX and RX. - * @rmtoll MAPR USART1_REMAP LL_GPIO_AF_DisableRemap_USART1 + * @rmtoll MAPR USART1_REMAP LL_GPIO_AFIO_REMAP_USART1_DISABLE * @note DISABLE: No remap (TX/PA9, RX/PA10) * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_DisableRemap_USART1(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_USART1_DISABLE(void) { CLEAR_BIT(AFIO->MAPR, AFIO_MAPR_USART1_REMAP); } -/** - * @brief Check if USART1 has been remaped or not - * @rmtoll MAPR USART1_REMAP LL_GPIO_AF_IsEnabledRemap_USART1 - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_GPIO_AF_IsEnabledRemap_USART1(void) -{ - return (READ_BIT(AFIO->MAPR, AFIO_MAPR_USART1_REMAP) == (AFIO_MAPR_USART1_REMAP)); -} - /** * @brief Enable the remapping of USART2 alternate function CTS, RTS, CK, TX and RX. - * @rmtoll MAPR USART2_REMAP LL_GPIO_AF_EnableRemap_USART2 + * @rmtoll MAPR USART2_REMAP LL_GPIO_AFIO_REMAP_USART2_ENABLE * @note ENABLE: Remap (CTS/PD3, RTS/PD4, TX/PD5, RX/PD6, CK/PD7) * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_EnableRemap_USART2(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_USART2_ENABLE(void) { SET_BIT(AFIO->MAPR, AFIO_MAPR_USART2_REMAP); } /** * @brief Disable the remapping of USART2 alternate function CTS, RTS, CK, TX and RX. - * @rmtoll MAPR USART2_REMAP LL_GPIO_AF_DisableRemap_USART2 + * @rmtoll MAPR USART2_REMAP LL_GPIO_AFIO_REMAP_USART2_DISABLE * @note DISABLE: No remap (CTS/PA0, RTS/PA1, TX/PA2, RX/PA3, CK/PA4) * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_DisableRemap_USART2(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_USART2_DISABLE(void) { CLEAR_BIT(AFIO->MAPR, AFIO_MAPR_USART2_REMAP); } -/** - * @brief Check if USART2 has been remaped or not - * @rmtoll MAPR USART2_REMAP LL_GPIO_AF_IsEnabledRemap_USART2 - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_GPIO_AF_IsEnabledRemap_USART2(void) -{ - return (READ_BIT(AFIO->MAPR, AFIO_MAPR_USART2_REMAP) == (AFIO_MAPR_USART2_REMAP)); -} - #if defined (AFIO_MAPR_USART3_REMAP) /** * @brief Enable the remapping of USART3 alternate function CTS, RTS, CK, TX and RX. - * @rmtoll MAPR USART3_REMAP LL_GPIO_AF_EnableRemap_USART3 + * @rmtoll MAPR USART3_REMAP LL_GPIO_AFIO_REMAP_USART3_ENABLE * @note ENABLE: Full remap (TX/PD8, RX/PD9, CK/PD10, CTS/PD11, RTS/PD12) * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_EnableRemap_USART3(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_USART3_ENABLE(void) { - CLEAR_BIT(AFIO->MAPR, AFIO_MAPR_USART3_REMAP); - SET_BIT(AFIO->MAPR, AFIO_MAPR_USART3_REMAP_FULLREMAP); + MODIFY_REG(AFIO->MAPR, AFIO_MAPR_USART3_REMAP, AFIO_MAPR_USART3_REMAP_FULLREMAP); } /** * @brief Enable the remapping of USART3 alternate function CTS, RTS, CK, TX and RX. - * @rmtoll MAPR USART3_REMAP LL_GPIO_AF_RemapPartial_USART3 + * @rmtoll MAPR USART3_REMAP LL_GPIO_AFIO_REMAP_USART3_PARTIAL * @note PARTIAL: Partial remap (TX/PC10, RX/PC11, CK/PC12, CTS/PB13, RTS/PB14) * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_RemapPartial_USART3(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_USART3_PARTIAL(void) { - CLEAR_BIT(AFIO->MAPR, AFIO_MAPR_USART3_REMAP); - SET_BIT(AFIO->MAPR, AFIO_MAPR_USART3_REMAP_PARTIALREMAP); + MODIFY_REG(AFIO->MAPR, AFIO_MAPR_USART3_REMAP, AFIO_MAPR_USART3_REMAP_PARTIALREMAP); } /** * @brief Disable the remapping of USART3 alternate function CTS, RTS, CK, TX and RX. - * @rmtoll MAPR USART3_REMAP LL_GPIO_AF_DisableRemap_USART3 + * @rmtoll MAPR USART3_REMAP LL_GPIO_AFIO_REMAP_USART3_DISABLE * @note DISABLE: No remap (TX/PB10, RX/PB11, CK/PB12, CTS/PB13, RTS/PB14) * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_DisableRemap_USART3(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_USART3_DISABLE(void) { - CLEAR_BIT(AFIO->MAPR, AFIO_MAPR_USART3_REMAP); - SET_BIT(AFIO->MAPR, AFIO_MAPR_USART3_REMAP_NOREMAP); + MODIFY_REG(AFIO->MAPR, AFIO_MAPR_USART3_REMAP, AFIO_MAPR_USART3_REMAP_NOREMAP); } #endif /** * @brief Enable the remapping of TIM1 alternate function channels 1 to 4, 1N to 3N, external trigger (ETR) and Break input (BKIN) - * @rmtoll MAPR TIM1_REMAP LL_GPIO_AF_EnableRemap_TIM1 + * @rmtoll MAPR TIM1_REMAP LL_GPIO_AFIO_REMAP_TIM1_ENABLE * @note ENABLE: Full remap (ETR/PE7, CH1/PE9, CH2/PE11, CH3/PE13, CH4/PE14, BKIN/PE15, CH1N/PE8, CH2N/PE10, CH3N/PE12) * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_EnableRemap_TIM1(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_TIM1_ENABLE(void) { - CLEAR_BIT(AFIO->MAPR, AFIO_MAPR_TIM1_REMAP); - SET_BIT(AFIO->MAPR, AFIO_MAPR_TIM1_REMAP_FULLREMAP); + MODIFY_REG(AFIO->MAPR, AFIO_MAPR_TIM1_REMAP, AFIO_MAPR_TIM1_REMAP_FULLREMAP); } /** * @brief Enable the remapping of TIM1 alternate function channels 1 to 4, 1N to 3N, external trigger (ETR) and Break input (BKIN) - * @rmtoll MAPR TIM1_REMAP LL_GPIO_AF_RemapPartial_TIM1 + * @rmtoll MAPR TIM1_REMAP LL_GPIO_AFIO_REMAP_TIM1_PARTIAL * @note PARTIAL: Partial remap (ETR/PA12, CH1/PA8, CH2/PA9, CH3/PA10, CH4/PA11, BKIN/PA6, CH1N/PA7, CH2N/PB0, CH3N/PB1) * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_RemapPartial_TIM1(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_TIM1_PARTIAL(void) { - CLEAR_BIT(AFIO->MAPR, AFIO_MAPR_TIM1_REMAP); - SET_BIT(AFIO->MAPR, AFIO_MAPR_TIM1_REMAP_PARTIALREMAP); + MODIFY_REG(AFIO->MAPR, AFIO_MAPR_TIM1_REMAP, AFIO_MAPR_TIM1_REMAP_PARTIALREMAP); } /** * @brief Disable the remapping of TIM1 alternate function channels 1 to 4, 1N to 3N, external trigger (ETR) and Break input (BKIN) - * @rmtoll MAPR TIM1_REMAP LL_GPIO_AF_DisableRemap_TIM1 + * @rmtoll MAPR TIM1_REMAP LL_GPIO_AFIO_REMAP_TIM1_DISABLE * @note DISABLE: No remap (ETR/PA12, CH1/PA8, CH2/PA9, CH3/PA10, CH4/PA11, BKIN/PB12, CH1N/PB13, CH2N/PB14, CH3N/PB15) * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_DisableRemap_TIM1(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_TIM1_DISABLE(void) { - CLEAR_BIT(AFIO->MAPR, AFIO_MAPR_TIM1_REMAP); - SET_BIT(AFIO->MAPR, AFIO_MAPR_TIM1_REMAP_NOREMAP); + MODIFY_REG(AFIO->MAPR, AFIO_MAPR_TIM1_REMAP, AFIO_MAPR_TIM1_REMAP_NOREMAP); } /** * @brief Enable the remapping of TIM2 alternate function channels 1 to 4 and external trigger (ETR) - * @rmtoll MAPR TIM2_REMAP LL_GPIO_AF_EnableRemap_TIM2 + * @rmtoll MAPR TIM2_REMAP LL_GPIO_AFIO_REMAP_TIM2_ENABLE * @note ENABLE: Full remap (CH1/ETR/PA15, CH2/PB3, CH3/PB10, CH4/PB11) * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_EnableRemap_TIM2(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_TIM2_ENABLE(void) { - CLEAR_BIT(AFIO->MAPR, AFIO_MAPR_TIM2_REMAP); - SET_BIT(AFIO->MAPR, AFIO_MAPR_TIM2_REMAP_FULLREMAP); + MODIFY_REG(AFIO->MAPR, AFIO_MAPR_TIM2_REMAP, AFIO_MAPR_TIM2_REMAP_FULLREMAP); } /** * @brief Enable the remapping of TIM2 alternate function channels 1 to 4 and external trigger (ETR) - * @rmtoll MAPR TIM2_REMAP LL_GPIO_AF_RemapPartial2_TIM2 + * @rmtoll MAPR TIM2_REMAP LL_GPIO_AFIO_REMAP_TIM2_PARTIAL_2 * @note PARTIAL_2: Partial remap (CH1/ETR/PA0, CH2/PA1, CH3/PB10, CH4/PB11) * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_RemapPartial2_TIM2(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_TIM2_PARTIAL_2(void) { - CLEAR_BIT(AFIO->MAPR, AFIO_MAPR_TIM2_REMAP); - SET_BIT(AFIO->MAPR, AFIO_MAPR_TIM2_REMAP_PARTIALREMAP2); + MODIFY_REG(AFIO->MAPR, AFIO_MAPR_TIM2_REMAP, AFIO_MAPR_TIM2_REMAP_PARTIALREMAP2); } /** * @brief Enable the remapping of TIM2 alternate function channels 1 to 4 and external trigger (ETR) - * @rmtoll MAPR TIM2_REMAP LL_GPIO_AF_RemapPartial1_TIM2 + * @rmtoll MAPR TIM2_REMAP LL_GPIO_AFIO_REMAP_TIM2_PARTIAL_1 * @note PARTIAL_1: Partial remap (CH1/ETR/PA15, CH2/PB3, CH3/PA2, CH4/PA3) * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_RemapPartial1_TIM2(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_TIM2_PARTIAL_1(void) { - CLEAR_BIT(AFIO->MAPR, AFIO_MAPR_TIM2_REMAP); - SET_BIT(AFIO->MAPR, AFIO_MAPR_TIM2_REMAP_PARTIALREMAP1); + MODIFY_REG(AFIO->MAPR, AFIO_MAPR_TIM2_REMAP, AFIO_MAPR_TIM2_REMAP_PARTIALREMAP1); } /** * @brief Disable the remapping of TIM2 alternate function channels 1 to 4 and external trigger (ETR) - * @rmtoll MAPR TIM2_REMAP LL_GPIO_AF_DisableRemap_TIM2 + * @rmtoll MAPR TIM2_REMAP LL_GPIO_AFIO_REMAP_TIM2_PARTIAL_1 * @note DISABLE: No remap (CH1/ETR/PA0, CH2/PA1, CH3/PA2, CH4/PA3) * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_DisableRemap_TIM2(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_TIM2_DISABLE(void) { - CLEAR_BIT(AFIO->MAPR, AFIO_MAPR_TIM2_REMAP); - SET_BIT(AFIO->MAPR, AFIO_MAPR_TIM2_REMAP_NOREMAP); + MODIFY_REG(AFIO->MAPR, AFIO_MAPR_TIM2_REMAP, AFIO_MAPR_TIM2_REMAP_NOREMAP); } /** * @brief Enable the remapping of TIM3 alternate function channels 1 to 4 - * @rmtoll MAPR TIM3_REMAP LL_GPIO_AF_EnableRemap_TIM3 + * @rmtoll MAPR TIM3_REMAP LL_GPIO_AFIO_REMAP_TIM3_ENABLE * @note ENABLE: Full remap (CH1/PC6, CH2/PC7, CH3/PC8, CH4/PC9) * @note TIM3_ETR on PE0 is not re-mapped. * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_EnableRemap_TIM3(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_TIM3_ENABLE(void) { - CLEAR_BIT(AFIO->MAPR, AFIO_MAPR_TIM3_REMAP); - SET_BIT(AFIO->MAPR, AFIO_MAPR_TIM3_REMAP_FULLREMAP); + MODIFY_REG(AFIO->MAPR, AFIO_MAPR_TIM3_REMAP, AFIO_MAPR_TIM3_REMAP_FULLREMAP); } /** * @brief Enable the remapping of TIM3 alternate function channels 1 to 4 - * @rmtoll MAPR TIM3_REMAP LL_GPIO_AF_RemapPartial_TIM3 + * @rmtoll MAPR TIM3_REMAP LL_GPIO_AFIO_REMAP_TIM3_PARTIAL * @note PARTIAL: Partial remap (CH1/PB4, CH2/PB5, CH3/PB0, CH4/PB1) * @note TIM3_ETR on PE0 is not re-mapped. * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_RemapPartial_TIM3(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_TIM3_PARTIAL(void) { - CLEAR_BIT(AFIO->MAPR, AFIO_MAPR_TIM3_REMAP); - SET_BIT(AFIO->MAPR, AFIO_MAPR_TIM3_REMAP_PARTIALREMAP); + MODIFY_REG(AFIO->MAPR, AFIO_MAPR_TIM3_REMAP, AFIO_MAPR_TIM3_REMAP_PARTIALREMAP); } /** * @brief Disable the remapping of TIM3 alternate function channels 1 to 4 - * @rmtoll MAPR TIM3_REMAP LL_GPIO_AF_DisableRemap_TIM3 + * @rmtoll MAPR TIM3_REMAP LL_GPIO_AFIO_REMAP_TIM3_DISABLE * @note DISABLE: No remap (CH1/PA6, CH2/PA7, CH3/PB0, CH4/PB1) * @note TIM3_ETR on PE0 is not re-mapped. * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_DisableRemap_TIM3(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_TIM3_DISABLE(void) { - CLEAR_BIT(AFIO->MAPR, AFIO_MAPR_TIM3_REMAP); - SET_BIT(AFIO->MAPR, AFIO_MAPR_TIM3_REMAP_NOREMAP); + MODIFY_REG(AFIO->MAPR, AFIO_MAPR_TIM3_REMAP, AFIO_MAPR_TIM3_REMAP_NOREMAP); } #if defined(AFIO_MAPR_TIM4_REMAP) /** * @brief Enable the remapping of TIM4 alternate function channels 1 to 4. - * @rmtoll MAPR TIM4_REMAP LL_GPIO_AF_EnableRemap_TIM4 + * @rmtoll MAPR TIM4_REMAP LL_GPIO_AFIO_REMAP_TIM4_ENABLE * @note ENABLE: Full remap (TIM4_CH1/PD12, TIM4_CH2/PD13, TIM4_CH3/PD14, TIM4_CH4/PD15) * @note TIM4_ETR on PE0 is not re-mapped. * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_EnableRemap_TIM4(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_TIM4_ENABLE(void) { SET_BIT(AFIO->MAPR, AFIO_MAPR_TIM4_REMAP); } /** * @brief Disable the remapping of TIM4 alternate function channels 1 to 4. - * @rmtoll MAPR TIM4_REMAP LL_GPIO_AF_DisableRemap_TIM4 + * @rmtoll MAPR TIM4_REMAP LL_GPIO_AFIO_REMAP_TIM4_DISABLE * @note DISABLE: No remap (TIM4_CH1/PB6, TIM4_CH2/PB7, TIM4_CH3/PB8, TIM4_CH4/PB9) * @note TIM4_ETR on PE0 is not re-mapped. * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_DisableRemap_TIM4(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_TIM4_DISABLE(void) { CLEAR_BIT(AFIO->MAPR, AFIO_MAPR_TIM4_REMAP); } - -/** - * @brief Check if TIM4 has been remaped or not - * @rmtoll MAPR TIM4_REMAP LL_GPIO_AF_IsEnabledRemap_TIM4 - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_GPIO_AF_IsEnabledRemap_TIM4(void) -{ - return (READ_BIT(AFIO->MAPR, AFIO_MAPR_TIM4_REMAP) == (AFIO_MAPR_TIM4_REMAP)); -} #endif #if defined(AFIO_MAPR_CAN_REMAP_REMAP1) /** * @brief Enable or disable the remapping of CAN alternate function CAN_RX and CAN_TX in devices with a single CAN interface. - * @rmtoll MAPR CAN_REMAP LL_GPIO_AF_RemapPartial1_CAN1 + * @rmtoll MAPR CAN_REMAP LL_GPIO_AFIO_REMAP_CAN1_1 * @note CASE 1: CAN_RX mapped to PA11, CAN_TX mapped to PA12 * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_RemapPartial1_CAN1(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_CAN1_1(void) { - CLEAR_BIT(AFIO->MAPR, AFIO_MAPR_CAN_REMAP); - SET_BIT(AFIO->MAPR, AFIO_MAPR_CAN_REMAP_REMAP1); + MODIFY_REG(AFIO->MAPR, AFIO_MAPR_CAN_REMAP, AFIO_MAPR_CAN_REMAP_REMAP1); } /** * @brief Enable or disable the remapping of CAN alternate function CAN_RX and CAN_TX in devices with a single CAN interface. - * @rmtoll MAPR CAN_REMAP LL_GPIO_AF_RemapPartial2_CAN1 + * @rmtoll MAPR CAN_REMAP LL_GPIO_AFIO_REMAP_CAN1_2 * @note CASE 2: CAN_RX mapped to PB8, CAN_TX mapped to PB9 (not available on 36-pin package) * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_RemapPartial2_CAN1(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_CAN1_2(void) { - CLEAR_BIT(AFIO->MAPR, AFIO_MAPR_CAN_REMAP); - SET_BIT(AFIO->MAPR, AFIO_MAPR_CAN_REMAP_REMAP2); + MODIFY_REG(AFIO->MAPR, AFIO_MAPR_CAN_REMAP, AFIO_MAPR_CAN_REMAP_REMAP2); } /** * @brief Enable or disable the remapping of CAN alternate function CAN_RX and CAN_TX in devices with a single CAN interface. - * @rmtoll MAPR CAN_REMAP LL_GPIO_AF_RemapPartial3_CAN1 + * @rmtoll MAPR CAN_REMAP LL_GPIO_AFIO_REMAP_CAN1_3 * @note CASE 3: CAN_RX mapped to PD0, CAN_TX mapped to PD1 * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_RemapPartial3_CAN1(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_CAN1_3(void) { - CLEAR_BIT(AFIO->MAPR, AFIO_MAPR_CAN_REMAP); - SET_BIT(AFIO->MAPR, AFIO_MAPR_CAN_REMAP_REMAP3); + MODIFY_REG(AFIO->MAPR, AFIO_MAPR_CAN_REMAP, AFIO_MAPR_CAN_REMAP_REMAP3); } #endif @@ -1261,11 +1195,11 @@ __STATIC_INLINE void LL_GPIO_AF_RemapPartial3_CAN1(void) * (application running on internal 8 MHz RC) PD0 and PD1 can be mapped on OSC_IN and * OSC_OUT. This is available only on 36, 48 and 64 pins packages (PD0 and PD1 are available * on 100-pin and 144-pin packages, no need for remapping). - * @rmtoll MAPR PD01_REMAP LL_GPIO_AF_EnableRemap_PD01 + * @rmtoll MAPR PD01_REMAP LL_GPIO_AFIO_REMAP_PD01_ENABLE * @note ENABLE: PD0 remapped on OSC_IN, PD1 remapped on OSC_OUT. * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_EnableRemap_PD01(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_PD01_ENABLE(void) { SET_BIT(AFIO->MAPR, AFIO_MAPR_PD01_REMAP); } @@ -1275,154 +1209,114 @@ __STATIC_INLINE void LL_GPIO_AF_EnableRemap_PD01(void) * (application running on internal 8 MHz RC) PD0 and PD1 can be mapped on OSC_IN and * OSC_OUT. This is available only on 36, 48 and 64 pins packages (PD0 and PD1 are available * on 100-pin and 144-pin packages, no need for remapping). - * @rmtoll MAPR PD01_REMAP LL_GPIO_AF_DisableRemap_PD01 + * @rmtoll MAPR PD01_REMAP LL_GPIO_AFIO_REMAP_PD01_DISABLE * @note DISABLE: No remapping of PD0 and PD1 * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_DisableRemap_PD01(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_PD01_DISABLE(void) { CLEAR_BIT(AFIO->MAPR, AFIO_MAPR_PD01_REMAP); } -/** - * @brief Check if PD01 has been remaped or not - * @rmtoll MAPR PD01_REMAP LL_GPIO_AF_IsEnabledRemap_PD01 - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_GPIO_AF_IsEnabledRemap_PD01(void) -{ - return (READ_BIT(AFIO->MAPR, AFIO_MAPR_PD01_REMAP) == (AFIO_MAPR_PD01_REMAP)); -} - #if defined(AFIO_MAPR_TIM5CH4_IREMAP) /** * @brief Enable the remapping of TIM5CH4. - * @rmtoll MAPR TIM5CH4_IREMAP LL_GPIO_AF_EnableRemap_TIM5CH4 + * @rmtoll MAPR TIM5CH4_IREMAP LL_GPIO_AFIO_REMAP_TIM5CH4_ENABLE * @note ENABLE: LSI internal clock is connected to TIM5_CH4 input for calibration purpose. * @note This function is available only in high density value line devices. * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_EnableRemap_TIM5CH4(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_TIM5CH4_ENABLE(void) { SET_BIT(AFIO->MAPR, AFIO_MAPR_TIM5CH4_IREMAP); } /** * @brief Disable the remapping of TIM5CH4. - * @rmtoll MAPR TIM5CH4_IREMAP LL_GPIO_AF_DisableRemap_TIM5CH4 + * @rmtoll MAPR TIM5CH4_IREMAP LL_GPIO_AFIO_REMAP_TIM5CH4_DISABLE * @note DISABLE: TIM5_CH4 is connected to PA3 * @note This function is available only in high density value line devices. * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_DisableRemap_TIM5CH4(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_TIM5CH4_DISABLE(void) { CLEAR_BIT(AFIO->MAPR, AFIO_MAPR_TIM5CH4_IREMAP); } - -/** - * @brief Check if TIM5CH4 has been remaped or not - * @rmtoll MAPR TIM5CH4_IREMAP LL_GPIO_AF_IsEnabledRemap_TIM5CH4 - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_GPIO_AF_IsEnabledRemap_TIM5CH4(void) -{ - return (READ_BIT(AFIO->MAPR, AFIO_MAPR_TIM5CH4_IREMAP) == (AFIO_MAPR_TIM5CH4_IREMAP)); -} #endif #if defined(AFIO_MAPR_ETH_REMAP) /** * @brief Enable the remapping of Ethernet MAC connections with the PHY. - * @rmtoll MAPR ETH_REMAP LL_GPIO_AF_EnableRemap_ETH + * @rmtoll MAPR ETH_REMAP LL_GPIO_AFIO_REMAP_ETH_ENABLE * @note ENABLE: Remap (RX_DV-CRS_DV/PD8, RXD0/PD9, RXD1/PD10, RXD2/PD11, RXD3/PD12) * @note This bit is available only in connectivity line devices and is reserved otherwise. * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_EnableRemap_ETH(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_ETH_ENABLE(void) { SET_BIT(AFIO->MAPR, AFIO_MAPR_ETH_REMAP); } /** * @brief Disable the remapping of Ethernet MAC connections with the PHY. - * @rmtoll MAPR ETH_REMAP LL_GPIO_AF_DisableRemap_ETH + * @rmtoll MAPR ETH_REMAP LL_GPIO_AFIO_REMAP_ETH_DISABLE * @note DISABLE: No remap (RX_DV-CRS_DV/PA7, RXD0/PC4, RXD1/PC5, RXD2/PB0, RXD3/PB1) * @note This bit is available only in connectivity line devices and is reserved otherwise. * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_DisableRemap_ETH(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_ETH_DISABLE(void) { CLEAR_BIT(AFIO->MAPR, AFIO_MAPR_ETH_REMAP); } - -/** - * @brief Check if ETH has been remaped or not - * @rmtoll MAPR ETH_REMAP LL_GPIO_AF_IsEnabledRemap_ETH - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_GPIO_AF_IsEnabledRemap_ETH(void) -{ - return (READ_BIT(AFIO->MAPR, AFIO_MAPR_ETH_REMAP) == (AFIO_MAPR_ETH_REMAP)); -} #endif #if defined(AFIO_MAPR_CAN2_REMAP) /** * @brief Enable the remapping of CAN2 alternate function CAN2_RX and CAN2_TX. - * @rmtoll MAPR CAN2_REMAP LL_GPIO_AF_EnableRemap_CAN2 + * @rmtoll MAPR CAN2_REMAP LL_GPIO_AFIO_REMAP_CAN2_ENABLE * @note ENABLE: Remap (CAN2_RX/PB5, CAN2_TX/PB6) * @note This bit is available only in connectivity line devices and is reserved otherwise. * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_EnableRemap_CAN2(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_CAN2_ENABLE(void) { SET_BIT(AFIO->MAPR, AFIO_MAPR_CAN2_REMAP); } /** * @brief Disable the remapping of CAN2 alternate function CAN2_RX and CAN2_TX. - * @rmtoll MAPR CAN2_REMAP LL_GPIO_AF_DisableRemap_CAN2 + * @rmtoll MAPR CAN2_REMAP LL_GPIO_AFIO_REMAP_CAN2_DISABLE * @note DISABLE: No remap (CAN2_RX/PB12, CAN2_TX/PB13) * @note This bit is available only in connectivity line devices and is reserved otherwise. * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_DisableRemap_CAN2(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_CAN2_DISABLE(void) { CLEAR_BIT(AFIO->MAPR, AFIO_MAPR_CAN2_REMAP); } - -/** - * @brief Check if CAN2 has been remaped or not - * @rmtoll MAPR CAN2_REMAP LL_GPIO_AF_IsEnabledRemap_CAN2 - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_GPIO_AF_IsEnabledRemap_CAN2(void) -{ - return (READ_BIT(AFIO->MAPR, AFIO_MAPR_CAN2_REMAP) == (AFIO_MAPR_CAN2_REMAP)); -} #endif #if defined(AFIO_MAPR_MII_RMII_SEL) /** * @brief Configures the Ethernet MAC internally for use with an external MII or RMII PHY. - * @rmtoll MAPR MII_RMII_SEL LL_GPIO_AF_Select_ETH_RMII + * @rmtoll MAPR MII_RMII_SEL LL_GPIO_AFIO_REMAP_ETH_RMII * @note ETH_RMII: Configure Ethernet MAC for connection with an RMII PHY * @note This bit is available only in connectivity line devices and is reserved otherwise. * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_Select_ETH_RMII(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_ETH_RMII(void) { SET_BIT(AFIO->MAPR, AFIO_MAPR_MII_RMII_SEL); } /** * @brief Configures the Ethernet MAC internally for use with an external MII or RMII PHY. - * @rmtoll MAPR MII_RMII_SEL LL_GPIO_AF_Select_ETH_MII + * @rmtoll MAPR MII_RMII_SEL LL_GPIO_AFIO_REMAP_ETH_MII * @note ETH_MII: Configure Ethernet MAC for connection with an MII PHY * @note This bit is available only in connectivity line devices and is reserved otherwise. * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_Select_ETH_MII(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_ETH_MII(void) { CLEAR_BIT(AFIO->MAPR, AFIO_MAPR_MII_RMII_SEL); } @@ -1431,248 +1325,194 @@ __STATIC_INLINE void LL_GPIO_AF_Select_ETH_MII(void) #if defined(AFIO_MAPR_ADC1_ETRGINJ_REMAP) /** * @brief Enable the remapping of ADC1_ETRGINJ (ADC 1 External trigger injected conversion). - * @rmtoll MAPR ADC1_ETRGINJ_REMAP LL_GPIO_AF_EnableRemap_ADC1_ETRGINJ + * @rmtoll MAPR ADC1_ETRGINJ_REMAP LL_GPIO_AFIO_REMAP_ADC1_ETRGINJ_ENABLE * @note ENABLE: ADC1 External Event injected conversion is connected to TIM8 Channel4. * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_EnableRemap_ADC1_ETRGINJ(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_ADC1_ETRGINJ_ENABLE(void) { SET_BIT(AFIO->MAPR, AFIO_MAPR_ADC1_ETRGINJ_REMAP); } /** * @brief Disable the remapping of ADC1_ETRGINJ (ADC 1 External trigger injected conversion). - * @rmtoll MAPR ADC1_ETRGINJ_REMAP LL_GPIO_AF_DisableRemap_ADC1_ETRGINJ + * @rmtoll MAPR ADC1_ETRGINJ_REMAP LL_GPIO_AFIO_REMAP_ADC1_ETRGINJ_DISABLE * @note DISABLE: ADC1 External trigger injected conversion is connected to EXTI15 * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_DisableRemap_ADC1_ETRGINJ(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_ADC1_ETRGINJ_DISABLE(void) { CLEAR_BIT(AFIO->MAPR, AFIO_MAPR_ADC1_ETRGINJ_REMAP); } - -/** - * @brief Check if ADC1_ETRGINJ has been remaped or not - * @rmtoll MAPR ADC1_ETRGINJ_REMAP LL_GPIO_AF_IsEnabledRemap_ADC1_ETRGINJ - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_GPIO_AF_IsEnabledRemap_ADC1_ETRGINJ(void) -{ - return (READ_BIT(AFIO->MAPR, AFIO_MAPR_ADC1_ETRGINJ_REMAP) == (AFIO_MAPR_ADC1_ETRGINJ_REMAP)); -} #endif #if defined(AFIO_MAPR_ADC1_ETRGREG_REMAP) /** * @brief Enable the remapping of ADC1_ETRGREG (ADC 1 External trigger regular conversion). - * @rmtoll MAPR ADC1_ETRGREG_REMAP LL_GPIO_AF_EnableRemap_ADC1_ETRGREG + * @rmtoll MAPR ADC1_ETRGREG_REMAP LL_GPIO_AFIO_REMAP_ADC1_ETRGREG_ENABLE * @note ENABLE: ADC1 External Event regular conversion is connected to TIM8 TRG0. * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_EnableRemap_ADC1_ETRGREG(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_ADC1_ETRGREG_ENABLE(void) { SET_BIT(AFIO->MAPR, AFIO_MAPR_ADC1_ETRGREG_REMAP); } /** * @brief Disable the remapping of ADC1_ETRGREG (ADC 1 External trigger regular conversion). - * @rmtoll MAPR ADC1_ETRGREG_REMAP LL_GPIO_AF_DisableRemap_ADC1_ETRGREG + * @rmtoll MAPR ADC1_ETRGREG_REMAP LL_GPIO_AFIO_REMAP_ADC1_ETRGREG_DISABLE * @note DISABLE: ADC1 External trigger regular conversion is connected to EXTI11 * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_DisableRemap_ADC1_ETRGREG(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_ADC1_ETRGREG_DISABLE(void) { CLEAR_BIT(AFIO->MAPR, AFIO_MAPR_ADC1_ETRGREG_REMAP); } - -/** - * @brief Check if ADC1_ETRGREG has been remaped or not - * @rmtoll MAPR ADC1_ETRGREG_REMAP LL_GPIO_AF_IsEnabledRemap_ADC1_ETRGREG - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_GPIO_AF_IsEnabledRemap_ADC1_ETRGREG(void) -{ - return (READ_BIT(AFIO->MAPR, AFIO_MAPR_ADC1_ETRGREG_REMAP) == (AFIO_MAPR_ADC1_ETRGREG_REMAP)); -} #endif #if defined(AFIO_MAPR_ADC2_ETRGINJ_REMAP) /** * @brief Enable the remapping of ADC2_ETRGREG (ADC 2 External trigger injected conversion). - * @rmtoll MAPR ADC2_ETRGINJ_REMAP LL_GPIO_AF_EnableRemap_ADC2_ETRGINJ + * @rmtoll MAPR ADC2_ETRGINJ_REMAP LL_GPIO_AFIO_REMAP_ADC2_ETRGINJ_ENABLE * @note ENABLE: ADC2 External Event injected conversion is connected to TIM8 Channel4. * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_EnableRemap_ADC2_ETRGINJ(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_ADC2_ETRGINJ_ENABLE(void) { SET_BIT(AFIO->MAPR, AFIO_MAPR_ADC2_ETRGINJ_REMAP); } /** * @brief Disable the remapping of ADC2_ETRGREG (ADC 2 External trigger injected conversion). - * @rmtoll MAPR ADC2_ETRGINJ_REMAP LL_GPIO_AF_DisableRemap_ADC2_ETRGINJ + * @rmtoll MAPR ADC2_ETRGINJ_REMAP LL_GPIO_AFIO_REMAP_ADC2_ETRGINJ_DISABLE * @note DISABLE: ADC2 External trigger injected conversion is connected to EXTI15 * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_DisableRemap_ADC2_ETRGINJ(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_ADC2_ETRGINJ_DISABLE(void) { CLEAR_BIT(AFIO->MAPR, AFIO_MAPR_ADC2_ETRGINJ_REMAP); } - -/** - * @brief Check if ADC2_ETRGINJ has been remaped or not - * @rmtoll MAPR ADC2_ETRGINJ_REMAP LL_GPIO_AF_IsEnabledRemap_ADC2_ETRGINJ - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_GPIO_AF_IsEnabledRemap_ADC2_ETRGINJ(void) -{ - return (READ_BIT(AFIO->MAPR, AFIO_MAPR_ADC2_ETRGINJ_REMAP) == (AFIO_MAPR_ADC2_ETRGINJ_REMAP)); -} #endif #if defined (AFIO_MAPR_ADC2_ETRGREG_REMAP) /** * @brief Enable the remapping of ADC2_ETRGREG (ADC 2 External trigger regular conversion). - * @rmtoll MAPR ADC2_ETRGREG_REMAP LL_GPIO_AF_EnableRemap_ADC2_ETRGREG + * @rmtoll MAPR ADC2_ETRGREG_REMAP LL_GPIO_AFIO_REMAP_ADC2_ETRGREG_ENABLE * @note ENABLE: ADC2 External Event regular conversion is connected to TIM8 TRG0. * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_EnableRemap_ADC2_ETRGREG(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_ADC2_ETRGREG_ENABLE(void) { SET_BIT(AFIO->MAPR, AFIO_MAPR_ADC2_ETRGREG_REMAP); } /** * @brief Disable the remapping of ADC2_ETRGREG (ADC 2 External trigger regular conversion). - * @rmtoll MAPR ADC2_ETRGREG_REMAP LL_GPIO_AF_DisableRemap_ADC2_ETRGREG + * @rmtoll MAPR ADC2_ETRGREG_REMAP LL_GPIO_AFIO_REMAP_ADC2_ETRGREG_DISABLE * @note DISABLE: ADC2 External trigger regular conversion is connected to EXTI11 * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_DisableRemap_ADC2_ETRGREG(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_ADC2_ETRGREG_DISABLE(void) { CLEAR_BIT(AFIO->MAPR, AFIO_MAPR_ADC2_ETRGREG_REMAP); } - -/** - * @brief Check if ADC2_ETRGREG has been remaped or not - * @rmtoll MAPR ADC2_ETRGREG_REMAP LL_GPIO_AF_IsEnabledRemap_ADC2_ETRGREG - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_GPIO_AF_IsEnabledRemap_ADC2_ETRGREG(void) -{ - return (READ_BIT(AFIO->MAPR, AFIO_MAPR_ADC2_ETRGREG_REMAP) == (AFIO_MAPR_ADC2_ETRGREG_REMAP)); -} #endif /** * @brief Enable the Serial wire JTAG configuration - * @rmtoll MAPR SWJ_CFG LL_GPIO_AF_EnableRemap_SWJ + * @rmtoll MAPR SWJ_CFG LL_GPIO_AFIO_REMAP_SWJ_ENABLE * @note ENABLE: Full SWJ (JTAG-DP + SW-DP): Reset State * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_EnableRemap_SWJ(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_SWJ_ENABLE(void) { - CLEAR_BIT(AFIO->MAPR,AFIO_MAPR_SWJ_CFG); - SET_BIT(AFIO->MAPR, AFIO_MAPR_SWJ_CFG_RESET); + MODIFY_REG(AFIO->MAPR, AFIO_MAPR_SWJ_CFG, AFIO_MAPR_SWJ_CFG_RESET); } /** * @brief Enable the Serial wire JTAG configuration - * @rmtoll MAPR SWJ_CFG LL_GPIO_AF_Remap_SWJ_NONJTRST + * @rmtoll MAPR SWJ_CFG LL_GPIO_AFIO_REMAP_SWJ_NONJTRST * @note NONJTRST: Full SWJ (JTAG-DP + SW-DP) but without NJTRST * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_Remap_SWJ_NONJTRST(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_SWJ_NONJTRST(void) { - CLEAR_BIT(AFIO->MAPR,AFIO_MAPR_SWJ_CFG); - SET_BIT(AFIO->MAPR, AFIO_MAPR_SWJ_CFG_NOJNTRST); + MODIFY_REG(AFIO->MAPR, AFIO_MAPR_SWJ_CFG, AFIO_MAPR_SWJ_CFG_NOJNTRST); } /** * @brief Enable the Serial wire JTAG configuration - * @rmtoll MAPR SWJ_CFG LL_GPIO_AF_Remap_SWJ_NOJTAG + * @rmtoll MAPR SWJ_CFG LL_GPIO_AFIO_REMAP_SWJ_NOJTAG * @note NOJTAG: JTAG-DP Disabled and SW-DP Enabled * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_Remap_SWJ_NOJTAG(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_SWJ_NOJTAG(void) { - CLEAR_BIT(AFIO->MAPR,AFIO_MAPR_SWJ_CFG); - SET_BIT(AFIO->MAPR, AFIO_MAPR_SWJ_CFG_JTAGDISABLE); + MODIFY_REG(AFIO->MAPR, AFIO_MAPR_SWJ_CFG, AFIO_MAPR_SWJ_CFG_JTAGDISABLE); } /** * @brief Disable the Serial wire JTAG configuration - * @rmtoll MAPR SWJ_CFG LL_GPIO_AF_DisableRemap_SWJ + * @rmtoll MAPR SWJ_CFG LL_GPIO_AFIO_REMAP_SWJ_DISABLE * @note DISABLE: JTAG-DP Disabled and SW-DP Disabled * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_DisableRemap_SWJ(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_SWJ_DISABLE(void) { - CLEAR_BIT(AFIO->MAPR,AFIO_MAPR_SWJ_CFG); - SET_BIT(AFIO->MAPR, AFIO_MAPR_SWJ_CFG_DISABLE); + MODIFY_REG(AFIO->MAPR, AFIO_MAPR_SWJ_CFG, AFIO_MAPR_SWJ_CFG_DISABLE); } #if defined(AFIO_MAPR_SPI3_REMAP) /** * @brief Enable the remapping of SPI3 alternate functions SPI3_NSS/I2S3_WS, SPI3_SCK/I2S3_CK, SPI3_MISO, SPI3_MOSI/I2S3_SD. - * @rmtoll MAPR SPI3_REMAP LL_GPIO_AF_EnableRemap_SPI3 + * @rmtoll MAPR SPI3_REMAP LL_GPIO_AFIO_REMAP_SPI3_ENABLE * @note ENABLE: Remap (SPI3_NSS-I2S3_WS/PA4, SPI3_SCK-I2S3_CK/PC10, SPI3_MISO/PC11, SPI3_MOSI-I2S3_SD/PC12) * @note This bit is available only in connectivity line devices and is reserved otherwise. * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_EnableRemap_SPI3(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_SPI3_ENABLE(void) { SET_BIT(AFIO->MAPR, AFIO_MAPR_SPI3_REMAP); } /** * @brief Disable the remapping of SPI3 alternate functions SPI3_NSS/I2S3_WS, SPI3_SCK/I2S3_CK, SPI3_MISO, SPI3_MOSI/I2S3_SD. - * @rmtoll MAPR SPI3_REMAP LL_GPIO_AF_DisableRemap_SPI3 + * @rmtoll MAPR SPI3_REMAP LL_GPIO_AFIO_REMAP_SPI3_DISABLE * @note DISABLE: No remap (SPI3_NSS-I2S3_WS/PA15, SPI3_SCK-I2S3_CK/PB3, SPI3_MISO/PB4, SPI3_MOSI-I2S3_SD/PB5). * @note This bit is available only in connectivity line devices and is reserved otherwise. * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_DisableRemap_SPI3(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_SPI3_DISABLE(void) { CLEAR_BIT(AFIO->MAPR, AFIO_MAPR_SPI3_REMAP); } - -/** - * @brief Check if SPI3 has been remaped or not - * @rmtoll MAPR SPI3_REMAP LL_GPIO_AF_IsEnabledRemap_SPI3_REMAP - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_GPIO_AF_IsEnabledRemap_SPI3(void) -{ - return (READ_BIT(AFIO->MAPR, AFIO_MAPR_SPI3_REMAP) == (AFIO_MAPR_SPI3_REMAP)); -} #endif #if defined(AFIO_MAPR_TIM2ITR1_IREMAP) /** * @brief Control of TIM2_ITR1 internal mapping. - * @rmtoll MAPR TIM2ITR1_IREMAP LL_GPIO_AF_Remap_TIM2ITR1_TO_USB + * @rmtoll MAPR TIM2ITR1_IREMAP LL_GPIO_AFIO_TIM2ITR1_TO_USB * @note TO_USB: Connect USB OTG SOF (Start of Frame) output to TIM2_ITR1 for calibration purposes. * @note This bit is available only in connectivity line devices and is reserved otherwise. * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_Remap_TIM2ITR1_TO_USB(void) +__STATIC_INLINE void LL_GPIO_AFIO_TIM2ITR1_TO_USB(void) { SET_BIT(AFIO->MAPR, AFIO_MAPR_TIM2ITR1_IREMAP); } /** * @brief Control of TIM2_ITR1 internal mapping. - * @rmtoll MAPR TIM2ITR1_IREMAP LL_GPIO_AF_Remap_TIM2ITR1_TO_ETH + * @rmtoll MAPR TIM2ITR1_IREMAP LL_GPIO_AFIO_TIM2ITR1_TO_ETH * @note TO_ETH: Connect TIM2_ITR1 internally to the Ethernet PTP output for calibration purposes. * @note This bit is available only in connectivity line devices and is reserved otherwise. * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_Remap_TIM2ITR1_TO_ETH(void) +__STATIC_INLINE void LL_GPIO_AFIO_TIM2ITR1_TO_ETH(void) { CLEAR_BIT(AFIO->MAPR, AFIO_MAPR_TIM2ITR1_IREMAP); } @@ -1682,24 +1522,24 @@ __STATIC_INLINE void LL_GPIO_AF_Remap_TIM2ITR1_TO_ETH(void) /** * @brief Enable the remapping of ADC2_ETRGREG (ADC 2 External trigger regular conversion). - * @rmtoll MAPR PTP_PPS_REMAP LL_GPIO_AF_EnableRemap_ETH_PTP_PPS + * @rmtoll MAPR PTP_PPS_REMAP LL_GPIO_AFIO_ETH_PTP_PPS_ENABLE * @note ENABLE: PTP_PPS is output on PB5 pin. * @note This bit is available only in connectivity line devices and is reserved otherwise. * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_EnableRemap_ETH_PTP_PPS(void) +__STATIC_INLINE void LL_GPIO_AFIO_ETH_PTP_PPS_ENABLE(void) { SET_BIT(AFIO->MAPR, AFIO_MAPR_PTP_PPS_REMAP); } /** * @brief Disable the remapping of ADC2_ETRGREG (ADC 2 External trigger regular conversion). - * @rmtoll MAPR PTP_PPS_REMAP LL_GPIO_AF_DisableRemap_ETH_PTP_PPS + * @rmtoll MAPR PTP_PPS_REMAP LL_GPIO_AFIO_ETH_PTP_PPS_DISABLE * @note DISABLE: PTP_PPS not output on PB5 pin. * @note This bit is available only in connectivity line devices and is reserved otherwise. * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_DisableRemap_ETH_PTP_PPS(void) +__STATIC_INLINE void LL_GPIO_AFIO_ETH_PTP_PPS_DISABLE(void) { CLEAR_BIT(AFIO->MAPR, AFIO_MAPR_PTP_PPS_REMAP); } @@ -1709,196 +1549,146 @@ __STATIC_INLINE void LL_GPIO_AF_DisableRemap_ETH_PTP_PPS(void) /** * @brief Enable the remapping of TIM9_CH1 and TIM9_CH2. - * @rmtoll MAPR2 TIM9_REMAP LL_GPIO_AF_EnableRemap_TIM9 + * @rmtoll MAPR TIM9_REMAP LL_GPIO_AFIO_REMAP_TIM9_ENABLE * @note ENABLE: Remap (TIM9_CH1 on PE5 and TIM9_CH2 on PE6). * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_EnableRemap_TIM9(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_TIM9_ENABLE(void) { SET_BIT(AFIO->MAPR2, AFIO_MAPR2_TIM9_REMAP); } /** * @brief Disable the remapping of TIM9_CH1 and TIM9_CH2. - * @rmtoll MAPR2 TIM9_REMAP LL_GPIO_AF_DisableRemap_TIM9 + * @rmtoll MAPR TIM9_REMAP LL_GPIO_AFIO_REMAP_TIM9_ENABLE * @note DISABLE: No remap (TIM9_CH1 on PA2 and TIM9_CH2 on PA3). * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_DisableRemap_TIM9(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_TIM9_DISABLE(void) { CLEAR_BIT(AFIO->MAPR2, AFIO_MAPR2_TIM9_REMAP); } - -/** - * @brief Check if TIM9_CH1 and TIM9_CH2 have been remaped or not - * @rmtoll MAPR2 TIM9_REMAP LL_GPIO_AF_IsEnabledRemap_TIM9 - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_GPIO_AF_IsEnabledRemap_TIM9(void) -{ - return (READ_BIT(AFIO->MAPR2, AFIO_MAPR2_TIM9_REMAP) == (AFIO_MAPR2_TIM9_REMAP)); -} #endif #if defined(AFIO_MAPR2_TIM10_REMAP) /** * @brief Enable the remapping of TIM10_CH1. - * @rmtoll MAPR2 TIM10_REMAP LL_GPIO_AF_EnableRemap_TIM10 + * @rmtoll MAPR TIM10_REMAP LL_GPIO_AFIO_REMAP_TIM10_ENABLE * @note ENABLE: Remap (TIM10_CH1 on PF6). * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_EnableRemap_TIM10(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_TIM10_ENABLE(void) { SET_BIT(AFIO->MAPR2, AFIO_MAPR2_TIM10_REMAP); } /** * @brief Disable the remapping of TIM10_CH1. - * @rmtoll MAPR2 TIM10_REMAP LL_GPIO_AF_DisableRemap_TIM10 + * @rmtoll MAPR TIM10_REMAP LL_GPIO_AFIO_REMAP_TIM10_DISABLE * @note DISABLE: No remap (TIM10_CH1 on PB8). * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_DisableRemap_TIM10(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_TIM10_DISABLE(void) { CLEAR_BIT(AFIO->MAPR2, AFIO_MAPR2_TIM10_REMAP); } - -/** - * @brief Check if TIM10_CH1 has been remaped or not - * @rmtoll MAPR2 TIM10_REMAP LL_GPIO_AF_IsEnabledRemap_TIM10 - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_GPIO_AF_IsEnabledRemap_TIM10(void) -{ - return (READ_BIT(AFIO->MAPR2, AFIO_MAPR2_TIM10_REMAP) == (AFIO_MAPR2_TIM10_REMAP)); -} #endif #if defined(AFIO_MAPR2_TIM11_REMAP) /** * @brief Enable the remapping of TIM11_CH1. - * @rmtoll MAPR2 TIM11_REMAP LL_GPIO_AF_EnableRemap_TIM11 + * @rmtoll MAPR TIM11_REMAP LL_GPIO_AFIO_REMAP_TIM11_ENABLE * @note ENABLE: Remap (TIM11_CH1 on PF7). * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_EnableRemap_TIM11(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_TIM11_ENABLE(void) { SET_BIT(AFIO->MAPR2, AFIO_MAPR2_TIM11_REMAP); } /** * @brief Disable the remapping of TIM11_CH1. - * @rmtoll MAPR2 TIM11_REMAP LL_GPIO_AF_DisableRemap_TIM11 + * @rmtoll MAPR TIM11_REMAP LL_GPIO_AFIO_REMAP_TIM11_DISABLE * @note DISABLE: No remap (TIM11_CH1 on PB9). * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_DisableRemap_TIM11(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_TIM11_DISABLE(void) { CLEAR_BIT(AFIO->MAPR2, AFIO_MAPR2_TIM11_REMAP); } - -/** - * @brief Check if TIM11_CH1 has been remaped or not - * @rmtoll MAPR2 TIM11_REMAP LL_GPIO_AF_IsEnabledRemap_TIM11 - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_GPIO_AF_IsEnabledRemap_TIM11(void) -{ - return (READ_BIT(AFIO->MAPR2, AFIO_MAPR2_TIM11_REMAP) == (AFIO_MAPR2_TIM11_REMAP)); -} #endif #if defined(AFIO_MAPR2_TIM13_REMAP) /** * @brief Enable the remapping of TIM13_CH1. - * @rmtoll MAPR2 TIM13_REMAP LL_GPIO_AF_EnableRemap_TIM13 + * @rmtoll MAPR TIM13_REMAP LL_GPIO_AFIO_REMAP_TIM13_ENABLE * @note ENABLE: Remap STM32F100:(TIM13_CH1 on PF8). Others:(TIM13_CH1 on PB0). * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_EnableRemap_TIM13(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_TIM13_ENABLE(void) { SET_BIT(AFIO->MAPR2, AFIO_MAPR2_TIM13_REMAP); } /** * @brief Disable the remapping of TIM13_CH1. - * @rmtoll MAPR2 TIM13_REMAP LL_GPIO_AF_DisableRemap_TIM13 + * @rmtoll MAPR TIM13_REMAP LL_GPIO_AFIO_REMAP_TIM13_DISABLE * @note DISABLE: No remap STM32F100:(TIM13_CH1 on PA6). Others:(TIM13_CH1 on PC8). * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_DisableRemap_TIM13(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_TIM13_DISABLE(void) { CLEAR_BIT(AFIO->MAPR2, AFIO_MAPR2_TIM13_REMAP); } - -/** - * @brief Check if TIM13_CH1 has been remaped or not - * @rmtoll MAPR2 TIM13_REMAP LL_GPIO_AF_IsEnabledRemap_TIM13 - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_GPIO_AF_IsEnabledRemap_TIM13(void) -{ - return (READ_BIT(AFIO->MAPR2, AFIO_MAPR2_TIM13_REMAP) == (AFIO_MAPR2_TIM13_REMAP)); -} #endif #if defined(AFIO_MAPR2_TIM14_REMAP) /** * @brief Enable the remapping of TIM14_CH1. - * @rmtoll MAPR2 TIM14_REMAP LL_GPIO_AF_EnableRemap_TIM14 + * @rmtoll MAPR TIM14_REMAP LL_GPIO_AFIO_REMAP_TIM14_ENABLE * @note ENABLE: Remap STM32F100:(TIM14_CH1 on PB1). Others:(TIM14_CH1 on PF9). * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_EnableRemap_TIM14(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_TIM14_ENABLE(void) { SET_BIT(AFIO->MAPR2, AFIO_MAPR2_TIM14_REMAP); } /** * @brief Disable the remapping of TIM14_CH1. - * @rmtoll MAPR2 TIM14_REMAP LL_GPIO_AF_DisableRemap_TIM14 + * @rmtoll MAPR TIM14_REMAP LL_GPIO_AFIO_REMAP_TIM14_DISABLE * @note DISABLE: No remap STM32F100:(TIM14_CH1 on PC9). Others:(TIM14_CH1 on PA7). * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_DisableRemap_TIM14(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_TIM14_DISABLE(void) { CLEAR_BIT(AFIO->MAPR2, AFIO_MAPR2_TIM14_REMAP); } - -/** - * @brief Check if TIM14_CH1 has been remaped or not - * @rmtoll MAPR2 TIM14_REMAP LL_GPIO_AF_IsEnabledRemap_TIM14 - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_GPIO_AF_IsEnabledRemap_TIM14(void) -{ - return (READ_BIT(AFIO->MAPR2, AFIO_MAPR2_TIM14_REMAP) == (AFIO_MAPR2_TIM14_REMAP)); -} #endif #if defined(AFIO_MAPR2_FSMC_NADV_REMAP) /** * @brief Controls the use of the optional FSMC_NADV signal. - * @rmtoll MAPR2 FSMC_NADV LL_GPIO_AF_Disconnect_FSMCNADV + * @rmtoll MAPR FSMC_NADV LL_GPIO_AFIO_FSMCNADV_DISCONNECTED * @note DISCONNECTED: The NADV signal is not connected. The I/O pin can be used by another peripheral. * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_Disconnect_FSMCNADV(void) +__STATIC_INLINE void LL_GPIO_AFIO_FSMCNADV_DISCONNECTED(void) { SET_BIT(AFIO->MAPR2, AFIO_MAPR2_FSMC_NADV_REMAP); } /** * @brief Controls the use of the optional FSMC_NADV signal. - * @rmtoll MAPR2 FSMC_NADV LL_GPIO_AF_Connect_FSMCNADV + * @rmtoll MAPR FSMC_NADV LL_GPIO_AFIO_FSMCNADV_CONNECTED * @note CONNECTED: The NADV signal is connected to the output (default). * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_Connect_FSMCNADV(void) +__STATIC_INLINE void LL_GPIO_AFIO_FSMCNADV_CONNECTED(void) { CLEAR_BIT(AFIO->MAPR2, AFIO_MAPR2_FSMC_NADV_REMAP); } @@ -1908,246 +1698,176 @@ __STATIC_INLINE void LL_GPIO_AF_Connect_FSMCNADV(void) /** * @brief Enable the remapping of TIM15_CH1 and TIM15_CH2. - * @rmtoll MAPR2 TIM15_REMAP LL_GPIO_AF_EnableRemap_TIM15 + * @rmtoll MAPR TIM15_REMAP LL_GPIO_AFIO_REMAP_TIM15_ENABLE * @note ENABLE: Remap (TIM15_CH1 on PB14 and TIM15_CH2 on PB15). * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_EnableRemap_TIM15(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_TIM15_ENABLE(void) { SET_BIT(AFIO->MAPR2, AFIO_MAPR2_TIM15_REMAP); } /** * @brief Disable the remapping of TIM15_CH1 and TIM15_CH2. - * @rmtoll MAPR2 TIM15_REMAP LL_GPIO_AF_DisableRemap_TIM15 + * @rmtoll MAPR TIM15_REMAP LL_GPIO_AFIO_REMAP_TIM15_DISABLE * @note DISABLE: No remap (TIM15_CH1 on PA2 and TIM15_CH2 on PA3). * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_DisableRemap_TIM15(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_TIM15_DISABLE(void) { CLEAR_BIT(AFIO->MAPR2, AFIO_MAPR2_TIM15_REMAP); } - -/** - * @brief Check if TIM15_CH1 has been remaped or not - * @rmtoll MAPR2 TIM15_REMAP LL_GPIO_AF_IsEnabledRemap_TIM15 - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_GPIO_AF_IsEnabledRemap_TIM15(void) -{ - return (READ_BIT(AFIO->MAPR2, AFIO_MAPR2_TIM15_REMAP) == (AFIO_MAPR2_TIM15_REMAP)); -} #endif #if defined(AFIO_MAPR2_TIM16_REMAP) /** * @brief Enable the remapping of TIM16_CH1. - * @rmtoll MAPR2 TIM16_REMAP LL_GPIO_AF_EnableRemap_TIM16 + * @rmtoll MAPR TIM16_REMAP LL_GPIO_AFIO_REMAP_TIM16_ENABLE * @note ENABLE: Remap (TIM16_CH1 on PA6). * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_EnableRemap_TIM16(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_TIM16_ENABLE(void) { SET_BIT(AFIO->MAPR2, AFIO_MAPR2_TIM16_REMAP); } /** * @brief Disable the remapping of TIM16_CH1. - * @rmtoll MAPR2 TIM16_REMAP LL_GPIO_AF_DisableRemap_TIM16 + * @rmtoll MAPR TIM16_REMAP LL_GPIO_AFIO_REMAP_TIM16_DISABLE * @note DISABLE: No remap (TIM16_CH1 on PB8). * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_DisableRemap_TIM16(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_TIM16_DISABLE(void) { CLEAR_BIT(AFIO->MAPR2, AFIO_MAPR2_TIM16_REMAP); } - -/** - * @brief Check if TIM16_CH1 has been remaped or not - * @rmtoll MAPR2 TIM16_REMAP LL_GPIO_AF_IsEnabledRemap_TIM16 - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_GPIO_AF_IsEnabledRemap_TIM16(void) -{ - return (READ_BIT(AFIO->MAPR2, AFIO_MAPR2_TIM16_REMAP) == (AFIO_MAPR2_TIM16_REMAP)); -} #endif #if defined(AFIO_MAPR2_TIM17_REMAP) /** * @brief Enable the remapping of TIM17_CH1. - * @rmtoll MAPR2 TIM17_REMAP LL_GPIO_AF_EnableRemap_TIM17 + * @rmtoll MAPR TIM17_REMAP LL_GPIO_AFIO_REMAP_TIM17_ENABLE * @note ENABLE: Remap (TIM17_CH1 on PA7). * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_EnableRemap_TIM17(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_TIM17_ENABLE(void) { SET_BIT(AFIO->MAPR2, AFIO_MAPR2_TIM17_REMAP); } /** * @brief Disable the remapping of TIM17_CH1. - * @rmtoll MAPR2 TIM17_REMAP LL_GPIO_AF_DisableRemap_TIM17 + * @rmtoll MAPR TIM17_REMAP LL_GPIO_AFIO_REMAP_TIM17_DISABLE * @note DISABLE: No remap (TIM17_CH1 on PB9). * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_DisableRemap_TIM17(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_TIM17_DISABLE(void) { CLEAR_BIT(AFIO->MAPR2, AFIO_MAPR2_TIM17_REMAP); } - -/** - * @brief Check if TIM17_CH1 has been remaped or not - * @rmtoll MAPR2 TIM17_REMAP LL_GPIO_AF_IsEnabledRemap_TIM17 - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_GPIO_AF_IsEnabledRemap_TIM17(void) -{ - return (READ_BIT(AFIO->MAPR2, AFIO_MAPR2_TIM17_REMAP) == (AFIO_MAPR2_TIM17_REMAP)); -} #endif #if defined(AFIO_MAPR2_CEC_REMAP) /** * @brief Enable the remapping of CEC. - * @rmtoll MAPR2 CEC_REMAP LL_GPIO_AF_EnableRemap_CEC + * @rmtoll MAPR CEC_REMAP LL_GPIO_AFIO_REMAP_CEC_ENABLE * @note ENABLE: Remap (CEC on PB10). * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_EnableRemap_CEC(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_CEC_ENABLE(void) { SET_BIT(AFIO->MAPR2, AFIO_MAPR2_CEC_REMAP); } /** * @brief Disable the remapping of CEC. - * @rmtoll MAPR2 CEC_REMAP LL_GPIO_AF_DisableRemap_CEC + * @rmtoll MAPR CEC_REMAP LL_GPIO_AFIO_REMAP_CEC_DISABLE * @note DISABLE: No remap (CEC on PB8). * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_DisableRemap_CEC(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_CEC_DISABLE(void) { CLEAR_BIT(AFIO->MAPR2, AFIO_MAPR2_CEC_REMAP); } - -/** - * @brief Check if CEC has been remaped or not - * @rmtoll MAPR2 CEC_REMAP LL_GPIO_AF_IsEnabledRemap_CEC - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_GPIO_AF_IsEnabledRemap_CEC(void) -{ - return (READ_BIT(AFIO->MAPR2, AFIO_MAPR2_CEC_REMAP) == (AFIO_MAPR2_CEC_REMAP)); -} #endif #if defined(AFIO_MAPR2_TIM1_DMA_REMAP) /** * @brief Controls the mapping of the TIM1_CH1 TIM1_CH2 DMA requests onto the DMA1 channels. - * @rmtoll MAPR2 TIM1_DMA_REMAP LL_GPIO_AF_EnableRemap_TIM1DMA + * @rmtoll MAPR TIM1_DMA_REMAP LL_GPIO_AFIO_REMAP_TIM1DMA_ENABLE * @note ENABLE: Remap (TIM1_CH1 DMA request/DMA1 Channel6, TIM1_CH2 DMA request/DMA1 Channel6) * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_EnableRemap_TIM1DMA(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_TIM1DMA_ENABLE(void) { SET_BIT(AFIO->MAPR2, AFIO_MAPR2_TIM1_DMA_REMAP); } /** * @brief Controls the mapping of the TIM1_CH1 TIM1_CH2 DMA requests onto the DMA1 channels. - * @rmtoll MAPR2 TIM1_DMA_REMAP LL_GPIO_AF_DisableRemap_TIM1DMA + * @rmtoll MAPR TIM1_DMA_REMAP LL_GPIO_AFIO_REMAP_TIM1DMA_DISABLE * @note DISABLE: No remap (TIM1_CH1 DMA request/DMA1 Channel2, TIM1_CH2 DMA request/DMA1 Channel3). * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_DisableRemap_TIM1DMA(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_TIM1DMA_DISABLE(void) { CLEAR_BIT(AFIO->MAPR2, AFIO_MAPR2_TIM1_DMA_REMAP); } - -/** - * @brief Check if TIM1DMA has been remaped or not - * @rmtoll MAPR2 TIM1_DMA_REMAP LL_GPIO_AF_IsEnabledRemap_TIM1DMA - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_GPIO_AF_IsEnabledRemap_TIM1DMA(void) -{ - return (READ_BIT(AFIO->MAPR2, AFIO_MAPR2_TIM1_DMA_REMAP) == (AFIO_MAPR2_TIM1_DMA_REMAP)); -} #endif #if defined(AFIO_MAPR2_TIM67_DAC_DMA_REMAP) /** * @brief Controls the mapping of the TIM6_DAC1 and TIM7_DAC2 DMA requests onto the DMA1 channels. - * @rmtoll MAPR2 TIM76_DAC_DMA_REMAP LL_GPIO_AF_EnableRemap_TIM67DACDMA + * @rmtoll MAPR TIM76_DAC_DMA_REMAP LL_GPIO_AFIO_REMAP_TIM67DACDMA_ENABLE * @note ENABLE: Remap (TIM6_DAC1 DMA request/DMA1 Channel3, TIM7_DAC2 DMA request/DMA1 Channel4) * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_EnableRemap_TIM67DACDMA(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_TIM67DACDMA_ENABLE(void) { SET_BIT(AFIO->MAPR2, AFIO_MAPR2_TIM67_DAC_DMA_REMAP); } /** * @brief Controls the mapping of the TIM6_DAC1 and TIM7_DAC2 DMA requests onto the DMA1 channels. - * @rmtoll MAPR2 TIM76_DAC_DMA_REMAP LL_GPIO_AF_DisableRemap_TIM67DACDMA + * @rmtoll MAPR TIM76_DAC_DMA_REMAP LL_GPIO_AFIO_REMAP_TIM67DACDMA_DISABLE * @note DISABLE: No remap (TIM6_DAC1 DMA request/DMA2 Channel3, TIM7_DAC2 DMA request/DMA2 Channel4) * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_DisableRemap_TIM67DACDMA(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_TIM67DACDMA_DISABLE(void) { CLEAR_BIT(AFIO->MAPR2, AFIO_MAPR2_TIM67_DAC_DMA_REMAP); } - -/** - * @brief Check if TIM67DACDMA has been remaped or not - * @rmtoll MAPR2 TIM76_DAC_DMA_REMAP LL_GPIO_AF_IsEnabledRemap_TIM67DACDMA - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_GPIO_AF_IsEnabledRemap_TIM67DACDMA(void) -{ - return (READ_BIT(AFIO->MAPR2, AFIO_MAPR2_TIM67_DAC_DMA_REMAP) == (AFIO_MAPR2_TIM67_DAC_DMA_REMAP)); -} #endif #if defined(AFIO_MAPR2_TIM12_REMAP) /** * @brief Enable the remapping of TIM12_CH1 and TIM12_CH2. - * @rmtoll MAPR2 TIM12_REMAP LL_GPIO_AF_EnableRemap_TIM12 + * @rmtoll MAPR TIM12_REMAP LL_GPIO_AFIO_REMAP_TIM12_ENABLE * @note ENABLE: Remap (TIM12_CH1 on PB12 and TIM12_CH2 on PB13). * @note This bit is available only in high density value line devices. * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_EnableRemap_TIM12(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_TIM12_ENABLE(void) { SET_BIT(AFIO->MAPR2, AFIO_MAPR2_TIM12_REMAP); } /** * @brief Disable the remapping of TIM12_CH1 and TIM12_CH2. - * @rmtoll MAPR2 TIM12_REMAP LL_GPIO_AF_DisableRemap_TIM12 + * @rmtoll MAPR TIM12_REMAP LL_GPIO_AFIO_REMAP_TIM12_DISABLE * @note DISABLE: No remap (TIM12_CH1 on PC4 and TIM12_CH2 on PC5). * @note This bit is available only in high density value line devices. * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_DisableRemap_TIM12(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_TIM12_DISABLE(void) { CLEAR_BIT(AFIO->MAPR2, AFIO_MAPR2_TIM12_REMAP); } - -/** - * @brief Check if TIM12_CH1 has been remaped or not - * @rmtoll MAPR2 TIM12_REMAP LL_GPIO_AF_IsEnabledRemap_TIM12 - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_GPIO_AF_IsEnabledRemap_TIM12(void) -{ - return (READ_BIT(AFIO->MAPR2, AFIO_MAPR2_TIM12_REMAP) == (AFIO_MAPR2_TIM12_REMAP)); -} #endif #if defined(AFIO_MAPR2_MISC_REMAP) @@ -2157,13 +1877,13 @@ __STATIC_INLINE uint32_t LL_GPIO_AF_IsEnabledRemap_TIM12(void) * This bit is set and cleared by software. It controls miscellaneous features. * The DMA2 channel 5 interrupt position in the vector table. * The timer selection for DAC trigger 3 (TSEL[2:0] = 011, for more details refer to the DAC_CR register). - * @rmtoll MAPR2 MISC_REMAP LL_GPIO_AF_EnableRemap_MISC + * @rmtoll MAPR MISC_REMAP LL_GPIO_AFIO_REMAP_MISC_ENABLE * @note ENABLE: DMA2 channel 5 interrupt is mapped separately at position 60 and TIM15 TRGO event is * selected as DAC Trigger 3, TIM15 triggers TIM1/3. * @note This bit is available only in high density value line devices. * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_EnableRemap_MISC(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_MISC_ENABLE(void) { SET_BIT(AFIO->MAPR2, AFIO_MAPR2_MISC_REMAP); } @@ -2173,87 +1893,77 @@ __STATIC_INLINE void LL_GPIO_AF_EnableRemap_MISC(void) * This bit is set and cleared by software. It controls miscellaneous features. * The DMA2 channel 5 interrupt position in the vector table. * The timer selection for DAC trigger 3 (TSEL[2:0] = 011, for more details refer to the DAC_CR register). - * @rmtoll MAPR2 MISC_REMAP LL_GPIO_AF_DisableRemap_MISC + * @rmtoll MAPR MISC_REMAP LL_GPIO_AFIO_REMAP_MISC_DISABLE * @note DISABLE: DMA2 channel 5 interrupt is mapped with DMA2 channel 4 at position 59, TIM5 TRGO * event is selected as DAC Trigger 3, TIM5 triggers TIM1/3. * @note This bit is available only in high density value line devices. * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_DisableRemap_MISC(void) +__STATIC_INLINE void LL_GPIO_AFIO_REMAP_MISC_DISABLE(void) { CLEAR_BIT(AFIO->MAPR2, AFIO_MAPR2_MISC_REMAP); } - -/** - * @brief Check if MISC has been remaped or not - * @rmtoll MAPR2 MISC_REMAP LL_GPIO_AF_IsEnabledRemap_MISC - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_GPIO_AF_IsEnabledRemap_MISC(void) -{ - return (READ_BIT(AFIO->MAPR2, AFIO_MAPR2_MISC_REMAP) == (AFIO_MAPR2_MISC_REMAP)); -} #endif /** * @} */ -/** @defgroup GPIO_AF_LL_EVENTOUT Output Event configuration +/** @defgroup GPIO_AFIO_LL_EVENTOUT Output Event configuration * @brief This section propose definition to Configure EVENTOUT Cortex feature . * @{ */ /** * @brief Configures the port and pin on which the EVENTOUT Cortex signal will be connected. - * @rmtoll EVCR PORT LL_GPIO_AF_ConfigEventout\n - * EVCR PIN LL_GPIO_AF_ConfigEventout + * @rmtoll EVCR PORT LL_GPIO_AFIO_ConfigEventout\n + * EVCR PIN LL_GPIO_AFIO_ConfigEventout * @param LL_GPIO_PortSource This parameter can be one of the following values: - * @arg @ref LL_GPIO_AF_EVENTOUT_PORT_A - * @arg @ref LL_GPIO_AF_EVENTOUT_PORT_B - * @arg @ref LL_GPIO_AF_EVENTOUT_PORT_C - * @arg @ref LL_GPIO_AF_EVENTOUT_PORT_D - * @arg @ref LL_GPIO_AF_EVENTOUT_PORT_E + * @arg @ref LL_GPIO_AFIO_EVENTOUT_PORT_A + * @arg @ref LL_GPIO_AFIO_EVENTOUT_PORT_B + * @arg @ref LL_GPIO_AFIO_EVENTOUT_PORT_C + * @arg @ref LL_GPIO_AFIO_EVENTOUT_PORT_D + * @arg @ref LL_GPIO_AFIO_EVENTOUT_PORT_E * @param LL_GPIO_PinSource This parameter can be one of the following values: - * @arg @ref LL_GPIO_AF_EVENTOUT_PIN_0 - * @arg @ref LL_GPIO_AF_EVENTOUT_PIN_1 - * @arg @ref LL_GPIO_AF_EVENTOUT_PIN_2 - * @arg @ref LL_GPIO_AF_EVENTOUT_PIN_3 - * @arg @ref LL_GPIO_AF_EVENTOUT_PIN_4 - * @arg @ref LL_GPIO_AF_EVENTOUT_PIN_5 - * @arg @ref LL_GPIO_AF_EVENTOUT_PIN_6 - * @arg @ref LL_GPIO_AF_EVENTOUT_PIN_7 - * @arg @ref LL_GPIO_AF_EVENTOUT_PIN_8 - * @arg @ref LL_GPIO_AF_EVENTOUT_PIN_9 - * @arg @ref LL_GPIO_AF_EVENTOUT_PIN_10 - * @arg @ref LL_GPIO_AF_EVENTOUT_PIN_11 - * @arg @ref LL_GPIO_AF_EVENTOUT_PIN_12 - * @arg @ref LL_GPIO_AF_EVENTOUT_PIN_13 - * @arg @ref LL_GPIO_AF_EVENTOUT_PIN_14 - * @arg @ref LL_GPIO_AF_EVENTOUT_PIN_15 + * @arg @ref LL_GPIO_AFIO_EVENTOUT_PIN_0 + * @arg @ref LL_GPIO_AFIO_EVENTOUT_PIN_1 + * @arg @ref LL_GPIO_AFIO_EVENTOUT_PIN_2 + * @arg @ref LL_GPIO_AFIO_EVENTOUT_PIN_3 + * @arg @ref LL_GPIO_AFIO_EVENTOUT_PIN_4 + * @arg @ref LL_GPIO_AFIO_EVENTOUT_PIN_5 + * @arg @ref LL_GPIO_AFIO_EVENTOUT_PIN_6 + * @arg @ref LL_GPIO_AFIO_EVENTOUT_PIN_7 + * @arg @ref LL_GPIO_AFIO_EVENTOUT_PIN_8 + * @arg @ref LL_GPIO_AFIO_EVENTOUT_PIN_9 + * @arg @ref LL_GPIO_AFIO_EVENTOUT_PIN_10 + * @arg @ref LL_GPIO_AFIO_EVENTOUT_PIN_11 + * @arg @ref LL_GPIO_AFIO_EVENTOUT_PIN_12 + * @arg @ref LL_GPIO_AFIO_EVENTOUT_PIN_13 + * @arg @ref LL_GPIO_AFIO_EVENTOUT_PIN_14 + * @arg @ref LL_GPIO_AFIO_EVENTOUT_PIN_15 * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_ConfigEventout(uint32_t LL_GPIO_PortSource, uint32_t LL_GPIO_PinSource) +__STATIC_INLINE void LL_GPIO_AFIO_ConfigEventout(uint32_t LL_GPIO_PortSource, uint32_t LL_GPIO_PinSource) { MODIFY_REG(AFIO->EVCR, (AFIO_EVCR_PORT) | (AFIO_EVCR_PIN), (LL_GPIO_PortSource) | (LL_GPIO_PinSource)); } /** * @brief Enables the Event Output. - * @rmtoll EVCR EVOE LL_GPIO_AF_EnableEventout + * @rmtoll EVCR EVOE LL_GPIO_AFIO_EnableEventout * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_EnableEventout(void) +__STATIC_INLINE void LL_GPIO_AFIO_EnableEventout(void) { SET_BIT(AFIO->EVCR, AFIO_EVCR_EVOE); } /** * @brief Disables the Event Output. - * @rmtoll EVCR EVOE LL_GPIO_AF_DisableEventout + * @rmtoll EVCR EVOE LL_GPIO_AFIO_DisableEventout * @retval None */ -__STATIC_INLINE void LL_GPIO_AF_DisableEventout(void) +__STATIC_INLINE void LL_GPIO_AFIO_DisableEventout(void) { CLEAR_BIT(AFIO->EVCR, AFIO_EVCR_EVOE); } @@ -2261,82 +1971,82 @@ __STATIC_INLINE void LL_GPIO_AF_DisableEventout(void) /** * @} */ -/** @defgroup GPIO_AF_LL_EXTI EXTI external interrupt +/** @defgroup GPIO_AFIO_LL_EXTI EXTI external interrupt * @brief This section Configure source input for the EXTI external interrupt . * @{ */ /** * @brief Configure source input for the EXTI external interrupt. - * @rmtoll AFIO_EXTICR1 EXTIx LL_GPIO_AF_SetEXTISource\n - * AFIO_EXTICR2 EXTIx LL_GPIO_AF_SetEXTISource\n - * AFIO_EXTICR3 EXTIx LL_GPIO_AF_SetEXTISource\n - * AFIO_EXTICR4 EXTIx LL_GPIO_AF_SetEXTISource + * @rmtoll AFIO_EXTICR1 EXTIx LL_GPIO_AFIO_SetEXTISource\n + * AFIO_EXTICR2 EXTIx LL_GPIO_AFIO_SetEXTISource\n + * AFIO_EXTICR3 EXTIx LL_GPIO_AFIO_SetEXTISource\n + * AFIO_EXTICR4 EXTIx LL_GPIO_AFIO_SetEXTISource * @param Port This parameter can be one of the following values: - * @arg @ref LL_GPIO_AF_EXTI_PORTA - * @arg @ref LL_GPIO_AF_EXTI_PORTB - * @arg @ref LL_GPIO_AF_EXTI_PORTC - * @arg @ref LL_GPIO_AF_EXTI_PORTD - * @arg @ref LL_GPIO_AF_EXTI_PORTE - * @arg @ref LL_GPIO_AF_EXTI_PORTF - * @arg @ref LL_GPIO_AF_EXTI_PORTG + * @arg @ref LL_GPIO_AFIO_EXTI_PORTA + * @arg @ref LL_GPIO_AFIO_EXTI_PORTB + * @arg @ref LL_GPIO_AFIO_EXTI_PORTC + * @arg @ref LL_GPIO_AFIO_EXTI_PORTD + * @arg @ref LL_GPIO_AFIO_EXTI_PORTE + * @arg @ref LL_GPIO_AFIO_EXTI_PORTF + * @arg @ref LL_GPIO_AFIO_EXTI_PORTG * @param Line This parameter can be one of the following values: - * @arg @ref LL_GPIO_AF_EXTI_LINE0 - * @arg @ref LL_GPIO_AF_EXTI_LINE1 - * @arg @ref LL_GPIO_AF_EXTI_LINE2 - * @arg @ref LL_GPIO_AF_EXTI_LINE3 - * @arg @ref LL_GPIO_AF_EXTI_LINE4 - * @arg @ref LL_GPIO_AF_EXTI_LINE5 - * @arg @ref LL_GPIO_AF_EXTI_LINE6 - * @arg @ref LL_GPIO_AF_EXTI_LINE7 - * @arg @ref LL_GPIO_AF_EXTI_LINE8 - * @arg @ref LL_GPIO_AF_EXTI_LINE9 - * @arg @ref LL_GPIO_AF_EXTI_LINE10 - * @arg @ref LL_GPIO_AF_EXTI_LINE11 - * @arg @ref LL_GPIO_AF_EXTI_LINE12 - * @arg @ref LL_GPIO_AF_EXTI_LINE13 - * @arg @ref LL_GPIO_AF_EXTI_LINE14 - * @arg @ref LL_GPIO_AF_EXTI_LINE15 - * @retval None - */ -__STATIC_INLINE void LL_GPIO_AF_SetEXTISource(uint32_t Port, uint32_t Line) + * @arg @ref LL_GPIO_AFIO_EXTI_LINE0 + * @arg @ref LL_GPIO_AFIO_EXTI_LINE1 + * @arg @ref LL_GPIO_AFIO_EXTI_LINE2 + * @arg @ref LL_GPIO_AFIO_EXTI_LINE3 + * @arg @ref LL_GPIO_AFIO_EXTI_LINE4 + * @arg @ref LL_GPIO_AFIO_EXTI_LINE5 + * @arg @ref LL_GPIO_AFIO_EXTI_LINE6 + * @arg @ref LL_GPIO_AFIO_EXTI_LINE7 + * @arg @ref LL_GPIO_AFIO_EXTI_LINE8 + * @arg @ref LL_GPIO_AFIO_EXTI_LINE9 + * @arg @ref LL_GPIO_AFIO_EXTI_LINE10 + * @arg @ref LL_GPIO_AFIO_EXTI_LINE11 + * @arg @ref LL_GPIO_AFIO_EXTI_LINE12 + * @arg @ref LL_GPIO_AFIO_EXTI_LINE13 + * @arg @ref LL_GPIO_AFIO_EXTI_LINE14 + * @arg @ref LL_GPIO_AFIO_EXTI_LINE15 + * @retval None + */ +__STATIC_INLINE void LL_GPIO_AFIO_SetEXTISource(uint32_t Port, uint32_t Line) { MODIFY_REG(AFIO->EXTICR[Line & 0xFF], (Line >> 16), Port << POSITION_VAL((Line >> 16))); } /** * @brief Get the configured defined for specific EXTI Line - * @rmtoll AFIO_EXTICR1 EXTIx LL_GPIO_AF_GetEXTISource\n - * AFIO_EXTICR2 EXTIx LL_GPIO_AF_GetEXTISource\n - * AFIO_EXTICR3 EXTIx LL_GPIO_AF_GetEXTISource\n - * AFIO_EXTICR4 EXTIx LL_GPIO_AF_GetEXTISource + * @rmtoll AFIO_EXTICR1 EXTIx LL_GPIO_AFIO_GetEXTISource\n + * AFIO_EXTICR2 EXTIx LL_GPIO_AFIO_GetEXTISource\n + * AFIO_EXTICR3 EXTIx LL_GPIO_AFIO_GetEXTISource\n + * AFIO_EXTICR4 EXTIx LL_GPIO_AFIO_GetEXTISource * @param Line This parameter can be one of the following values: - * @arg @ref LL_GPIO_AF_EXTI_LINE0 - * @arg @ref LL_GPIO_AF_EXTI_LINE1 - * @arg @ref LL_GPIO_AF_EXTI_LINE2 - * @arg @ref LL_GPIO_AF_EXTI_LINE3 - * @arg @ref LL_GPIO_AF_EXTI_LINE4 - * @arg @ref LL_GPIO_AF_EXTI_LINE5 - * @arg @ref LL_GPIO_AF_EXTI_LINE6 - * @arg @ref LL_GPIO_AF_EXTI_LINE7 - * @arg @ref LL_GPIO_AF_EXTI_LINE8 - * @arg @ref LL_GPIO_AF_EXTI_LINE9 - * @arg @ref LL_GPIO_AF_EXTI_LINE10 - * @arg @ref LL_GPIO_AF_EXTI_LINE11 - * @arg @ref LL_GPIO_AF_EXTI_LINE12 - * @arg @ref LL_GPIO_AF_EXTI_LINE13 - * @arg @ref LL_GPIO_AF_EXTI_LINE14 - * @arg @ref LL_GPIO_AF_EXTI_LINE15 + * @arg @ref LL_GPIO_AFIO_EXTI_LINE0 + * @arg @ref LL_GPIO_AFIO_EXTI_LINE1 + * @arg @ref LL_GPIO_AFIO_EXTI_LINE2 + * @arg @ref LL_GPIO_AFIO_EXTI_LINE3 + * @arg @ref LL_GPIO_AFIO_EXTI_LINE4 + * @arg @ref LL_GPIO_AFIO_EXTI_LINE5 + * @arg @ref LL_GPIO_AFIO_EXTI_LINE6 + * @arg @ref LL_GPIO_AFIO_EXTI_LINE7 + * @arg @ref LL_GPIO_AFIO_EXTI_LINE8 + * @arg @ref LL_GPIO_AFIO_EXTI_LINE9 + * @arg @ref LL_GPIO_AFIO_EXTI_LINE10 + * @arg @ref LL_GPIO_AFIO_EXTI_LINE11 + * @arg @ref LL_GPIO_AFIO_EXTI_LINE12 + * @arg @ref LL_GPIO_AFIO_EXTI_LINE13 + * @arg @ref LL_GPIO_AFIO_EXTI_LINE14 + * @arg @ref LL_GPIO_AFIO_EXTI_LINE15 * @retval Returned value can be one of the following values: - * @arg @ref LL_GPIO_AF_EXTI_PORTA - * @arg @ref LL_GPIO_AF_EXTI_PORTB - * @arg @ref LL_GPIO_AF_EXTI_PORTC - * @arg @ref LL_GPIO_AF_EXTI_PORTD - * @arg @ref LL_GPIO_AF_EXTI_PORTE - * @arg @ref LL_GPIO_AF_EXTI_PORTF - * @arg @ref LL_GPIO_AF_EXTI_PORTG - */ -__STATIC_INLINE uint32_t LL_GPIO_AF_GetEXTISource(uint32_t Line) + * @arg @ref LL_GPIO_AFIO_EXTI_PORTA + * @arg @ref LL_GPIO_AFIO_EXTI_PORTB + * @arg @ref LL_GPIO_AFIO_EXTI_PORTC + * @arg @ref LL_GPIO_AFIO_EXTI_PORTD + * @arg @ref LL_GPIO_AFIO_EXTI_PORTE + * @arg @ref LL_GPIO_AFIO_EXTI_PORTF + * @arg @ref LL_GPIO_AFIO_EXTI_PORTG + */ +__STATIC_INLINE uint32_t LL_GPIO_AFIO_GetEXTISource(uint32_t Line) { return (uint32_t)(READ_BIT(AFIO->EXTICR[Line & 0xFF], (Line >> 16)) >> POSITION_VAL(Line >> 16)); } diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_i2c.c b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_i2c.c deleted file mode 100644 index 0a882f75435..00000000000 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_i2c.c +++ /dev/null @@ -1,239 +0,0 @@ -/** - ****************************************************************************** - * @file stm32f1xx_ll_i2c.c - * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 - * @brief I2C LL module driver. - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2016 STMicroelectronics

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ -#if defined(USE_FULL_LL_DRIVER) - -/* Includes ------------------------------------------------------------------*/ -#include "stm32f1xx_ll_i2c.h" -#include "stm32f1xx_ll_bus.h" -#include "stm32f1xx_ll_rcc.h" -#ifdef USE_FULL_ASSERT -#include "stm32_assert.h" -#else -#define assert_param(expr) ((void)0U) -#endif - -/** @addtogroup STM32F1xx_LL_Driver - * @{ - */ - -#if defined (I2C1) || defined (I2C2) - -/** @defgroup I2C_LL I2C - * @{ - */ - -/* Private types -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private constants ---------------------------------------------------------*/ -/* Private macros ------------------------------------------------------------*/ -/** @addtogroup I2C_LL_Private_Macros - * @{ - */ - -#define IS_LL_I2C_PERIPHERAL_MODE(__VALUE__) (((__VALUE__) == LL_I2C_MODE_I2C) || \ - ((__VALUE__) == LL_I2C_MODE_SMBUS_HOST) || \ - ((__VALUE__) == LL_I2C_MODE_SMBUS_DEVICE) || \ - ((__VALUE__) == LL_I2C_MODE_SMBUS_DEVICE_ARP)) - -#define IS_I2C_CLOCK_SPEED(__VALUE__) (((__VALUE__) > 0U) && ((__VALUE__) <= LL_I2C_MAX_SPEED_FAST)) - -#define IS_I2C_DUTY_CYCLE(__VALUE__) (((__VALUE__) == LL_I2C_DUTYCYCLE_2) || \ - ((__VALUE__) == LL_I2C_DUTYCYCLE_16_9)) - -#define IS_LL_I2C_OWN_ADDRESS1(__VALUE__) ((__VALUE__) <= 0x000003FFU) - -#define IS_LL_I2C_TYPE_ACKNOWLEDGE(__VALUE__) (((__VALUE__) == LL_I2C_ACK) || \ - ((__VALUE__) == LL_I2C_NACK)) - -#define IS_LL_I2C_OWN_ADDRSIZE(__VALUE__) (((__VALUE__) == LL_I2C_OWNADDRESS1_7BIT) || \ - ((__VALUE__) == LL_I2C_OWNADDRESS1_10BIT)) -/** - * @} - */ - -/* Private function prototypes -----------------------------------------------*/ - -/* Exported functions --------------------------------------------------------*/ -/** @addtogroup I2C_LL_Exported_Functions - * @{ - */ - -/** @addtogroup I2C_LL_EF_Init - * @{ - */ - -/** - * @brief De-initialize the I2C registers to their default reset values. - * @param I2Cx I2C Instance. - * @retval An ErrorStatus enumeration value: - * - SUCCESS: I2C registers are de-initialized - * - ERROR: I2C registers are not de-initialized - */ -uint32_t LL_I2C_DeInit(I2C_TypeDef *I2Cx) -{ - ErrorStatus status = SUCCESS; - - /* Check the I2C Instance I2Cx */ - assert_param(IS_I2C_ALL_INSTANCE(I2Cx)); - - if (I2Cx == I2C1) - { - /* Force reset of I2C clock */ - LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_I2C1); - - /* Release reset of I2C clock */ - LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_I2C1); - } -#if defined(I2C2) - else if (I2Cx == I2C2) - { - /* Force reset of I2C clock */ - LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_I2C2); - - /* Release reset of I2C clock */ - LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_I2C2); - - } -#endif /* I2C2 */ - else - { - status = ERROR; - } - - return status; -} - -/** - * @brief Initialize the I2C registers according to the specified parameters in I2C_InitStruct. - * @param I2Cx I2C Instance. - * @param I2C_InitStruct pointer to a @ref LL_I2C_InitTypeDef structure. - * @retval An ErrorStatus enumeration value: - * - SUCCESS: I2C registers are initialized - * - ERROR: Not applicable - */ -uint32_t LL_I2C_Init(I2C_TypeDef *I2Cx, LL_I2C_InitTypeDef *I2C_InitStruct) -{ - LL_RCC_ClocksTypeDef rcc_clocks; - - /* Check the I2C Instance I2Cx */ - assert_param(IS_I2C_ALL_INSTANCE(I2Cx)); - - /* Check the I2C parameters from I2C_InitStruct */ - assert_param(IS_LL_I2C_PERIPHERAL_MODE(I2C_InitStruct->PeripheralMode)); - assert_param(IS_I2C_CLOCK_SPEED(I2C_InitStruct->ClockSpeed)); - assert_param(IS_I2C_DUTY_CYCLE(I2C_InitStruct->DutyCycle)); - assert_param(IS_LL_I2C_OWN_ADDRESS1(I2C_InitStruct->OwnAddress1)); - assert_param(IS_LL_I2C_TYPE_ACKNOWLEDGE(I2C_InitStruct->TypeAcknowledge)); - assert_param(IS_LL_I2C_OWN_ADDRSIZE(I2C_InitStruct->OwnAddrSize)); - - /* Disable the selected I2Cx Peripheral */ - LL_I2C_Disable(I2Cx); - - /* Retrieve Clock frequencies */ - LL_RCC_GetSystemClocksFreq(&rcc_clocks); - - /*---------------------------- I2Cx SCL Clock Speed Configuration ------------ - * Configure the SCL speed : - * - ClockSpeed: I2C_CR2_FREQ[5:0], I2C_TRISE_TRISE[5:0], I2C_CCR_FS, - * and I2C_CCR_CCR[11:0] bits - * - DutyCycle: I2C_CCR_DUTY[7:0] bits - */ - LL_I2C_ConfigSpeed(I2Cx, rcc_clocks.PCLK1_Frequency, I2C_InitStruct->ClockSpeed, I2C_InitStruct->DutyCycle); - - /*---------------------------- I2Cx OAR1 Configuration ----------------------- - * Disable, Configure and Enable I2Cx device own address 1 with parameters : - * - OwnAddress1: I2C_OAR1_ADD[9:8], I2C_OAR1_ADD[7:1] and I2C_OAR1_ADD0 bits - * - OwnAddrSize: I2C_OAR1_ADDMODE bit - */ - LL_I2C_SetOwnAddress1(I2Cx, I2C_InitStruct->OwnAddress1, I2C_InitStruct->OwnAddrSize); - - /*---------------------------- I2Cx MODE Configuration ----------------------- - * Configure I2Cx peripheral mode with parameter : - * - PeripheralMode: I2C_CR1_SMBUS, I2C_CR1_SMBTYPE and I2C_CR1_ENARP bits - */ - LL_I2C_SetMode(I2Cx, I2C_InitStruct->PeripheralMode); - - /* Enable the selected I2Cx Peripheral */ - LL_I2C_Enable(I2Cx); - - /*---------------------------- I2Cx CR2 Configuration ------------------------ - * Configure the ACKnowledge or Non ACKnowledge condition - * after the address receive match code or next received byte with parameter : - * - TypeAcknowledge: I2C_CR2_NACK bit - */ - LL_I2C_AcknowledgeNextData(I2Cx, I2C_InitStruct->TypeAcknowledge); - - return SUCCESS; -} - -/** - * @brief Set each @ref LL_I2C_InitTypeDef field to default value. - * @param I2C_InitStruct Pointer to a @ref LL_I2C_InitTypeDef structure. - * @retval None - */ -void LL_I2C_StructInit(LL_I2C_InitTypeDef *I2C_InitStruct) -{ - /* Set I2C_InitStruct fields to default values */ - I2C_InitStruct->PeripheralMode = LL_I2C_MODE_I2C; - I2C_InitStruct->ClockSpeed = 5000U; - I2C_InitStruct->DutyCycle = LL_I2C_DUTYCYCLE_2; - I2C_InitStruct->OwnAddress1 = 0U; - I2C_InitStruct->TypeAcknowledge = LL_I2C_NACK; - I2C_InitStruct->OwnAddrSize = LL_I2C_OWNADDRESS1_7BIT; -} - -/** - * @} - */ - -/** - * @} - */ - -/** - * @} - */ - -#endif /* I2C1 || I2C2 */ - -/** - * @} - */ - -#endif /* USE_FULL_LL_DRIVER */ - -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_i2c.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_i2c.h deleted file mode 100644 index 98081ddc45a..00000000000 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_i2c.h +++ /dev/null @@ -1,1802 +0,0 @@ -/** - ****************************************************************************** - * @file stm32f1xx_ll_i2c.h - * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 - * @brief Header file of I2C LL module. - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2016 STMicroelectronics

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ - -/* Define to prevent recursive inclusion -------------------------------------*/ -#ifndef __STM32F1xx_LL_I2C_H -#define __STM32F1xx_LL_I2C_H - -#ifdef __cplusplus -extern "C" { -#endif - -/* Includes ------------------------------------------------------------------*/ -#include "stm32f1xx.h" - -/** @addtogroup STM32F1xx_LL_Driver - * @{ - */ - -#if defined (I2C1) || defined (I2C2) - -/** @defgroup I2C_LL I2C - * @{ - */ - -/* Private types -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ - -/* Private constants ---------------------------------------------------------*/ -/** @defgroup I2C_LL_Private_Constants I2C Private Constants - * @{ - */ - -/* Defines used to perform compute and check in the macros */ -#define LL_I2C_MAX_SPEED_STANDARD 100000U -#define LL_I2C_MAX_SPEED_FAST 400000U -/** - * @} - */ - -/* Private macros ------------------------------------------------------------*/ -#if defined(USE_FULL_LL_DRIVER) -/** @defgroup I2C_LL_Private_Macros I2C Private Macros - * @{ - */ -/** - * @} - */ -#endif /*USE_FULL_LL_DRIVER*/ - -/* Exported types ------------------------------------------------------------*/ -#if defined(USE_FULL_LL_DRIVER) -/** @defgroup I2C_LL_ES_INIT I2C Exported Init structure - * @{ - */ -typedef struct -{ - uint32_t PeripheralMode; /*!< Specifies the peripheral mode. - This parameter can be a value of @ref I2C_LL_EC_PERIPHERAL_MODE - - This feature can be modified afterwards using unitary function @ref LL_I2C_SetMode(). */ - - uint32_t ClockSpeed; /*!< Specifies the clock frequency. - This parameter must be set to a value lower than 400kHz (in Hz) - - This feature can be modified afterwards using unitary function @ref LL_I2C_SetClockPeriod() - or @ref LL_I2C_SetDutyCycle() or @ref LL_I2C_SetClockSpeedMode() or @ref LL_I2C_ConfigSpeed(). */ - - uint32_t DutyCycle; /*!< Specifies the I2C fast mode duty cycle. - This parameter can be a value of @ref I2C_LL_EC_DUTYCYCLE - - This feature can be modified afterwards using unitary function @ref LL_I2C_SetDutyCycle(). */ - - uint32_t OwnAddress1; /*!< Specifies the device own address 1. - This parameter must be a value between Min_Data = 0x00 and Max_Data = 0x3FF - - This feature can be modified afterwards using unitary function @ref LL_I2C_SetOwnAddress1(). */ - - uint32_t TypeAcknowledge; /*!< Specifies the ACKnowledge or Non ACKnowledge condition after the address receive match code or next received byte. - This parameter can be a value of @ref I2C_LL_EC_I2C_ACKNOWLEDGE - - This feature can be modified afterwards using unitary function @ref LL_I2C_AcknowledgeNextData(). */ - - uint32_t OwnAddrSize; /*!< Specifies the device own address 1 size (7-bit or 10-bit). - This parameter can be a value of @ref I2C_LL_EC_OWNADDRESS1 - - This feature can be modified afterwards using unitary function @ref LL_I2C_SetOwnAddress1(). */ -} LL_I2C_InitTypeDef; -/** - * @} - */ -#endif /*USE_FULL_LL_DRIVER*/ - -/* Exported constants --------------------------------------------------------*/ -/** @defgroup I2C_LL_Exported_Constants I2C Exported Constants - * @{ - */ - -/** @defgroup I2C_LL_EC_GET_FLAG Get Flags Defines - * @brief Flags defines which can be used with LL_I2C_ReadReg function - * @{ - */ -#define LL_I2C_SR1_SB I2C_SR1_SB /*!< Start Bit (master mode) */ -#define LL_I2C_SR1_ADDR I2C_SR1_ADDR /*!< Address sent (master mode) or - Address matched flag (slave mode) */ -#define LL_I2C_SR1_BTF I2C_SR1_BTF /*!< Byte Transfer Finished flag */ -#define LL_I2C_SR1_ADD10 I2C_SR1_ADD10 /*!< 10-bit header sent (master mode) */ -#define LL_I2C_SR1_STOPF I2C_SR1_STOPF /*!< Stop detection flag (slave mode) */ -#define LL_I2C_SR1_RXNE I2C_SR1_RXNE /*!< Data register not empty (receivers) */ -#define LL_I2C_SR1_TXE I2C_SR1_TXE /*!< Data register empty (transmitters) */ -#define LL_I2C_SR1_BERR I2C_SR1_BERR /*!< Bus error */ -#define LL_I2C_SR1_ARLO I2C_SR1_ARLO /*!< Arbitration lost */ -#define LL_I2C_SR1_AF I2C_SR1_AF /*!< Acknowledge failure flag */ -#define LL_I2C_SR1_OVR I2C_SR1_OVR /*!< Overrun/Underrun */ -#define LL_I2C_SR1_PECERR I2C_ISR_PECERR /*!< PEC Error in reception (SMBus mode) */ -#define LL_I2C_SR1_TIMEOUT I2C_ISR_TIMEOUT /*!< Timeout detection flag (SMBus mode) */ -#define LL_I2C_SR1_SMALERT I2C_ISR_SMALERT /*!< SMBus alert (SMBus mode) */ -#define LL_I2C_SR2_MSL I2C_SR2_MSL /*!< Master/Slave flag */ -#define LL_I2C_SR2_BUSY I2C_SR2_BUSY /*!< Bus busy flag */ -#define LL_I2C_SR2_TRA I2C_SR2_TRA /*!< Transmitter/receiver direction */ -#define LL_I2C_SR2_GENCALL I2C_SR2_GENCALL /*!< General call address (Slave mode) */ -#define LL_I2C_SR2_SMBDEFAULT I2C_SR2_SMBDEFAULT /*!< SMBus Device default address (Slave mode) */ -#define LL_I2C_SR2_SMBHOST I2C_SR2_SMBHOST /*!< SMBus Host address (Slave mode) */ -#define LL_I2C_SR2_DUALF I2C_SR2_DUALF /*!< Dual flag (Slave mode) */ -/** - * @} - */ - -/** @defgroup I2C_LL_EC_IT IT Defines - * @brief IT defines which can be used with LL_I2C_ReadReg and LL_I2C_WriteReg functions - * @{ - */ -#define LL_I2C_CR2_ITEVTEN I2C_CR2_ITEVTEN /*!< Events interrupts enable */ -#define LL_I2C_CR2_ITBUFEN I2C_CR2_ITBUFEN /*!< Buffer interrupts enable */ -#define LL_I2C_CR2_ITERREN I2C_CR2_ITERREN /*!< Error interrupts enable */ -/** - * @} - */ - -/** @defgroup I2C_LL_EC_OWNADDRESS1 Own Address 1 Length - * @{ - */ -#define LL_I2C_OWNADDRESS1_7BIT 0x00004000U /*!< Own address 1 is a 7-bit address. */ -#define LL_I2C_OWNADDRESS1_10BIT (uint32_t)(I2C_OAR1_ADDMODE | 0x00004000U) /*!< Own address 1 is a 10-bit address. */ -/** - * @} - */ - -/** @defgroup I2C_LL_EC_DUTYCYCLE Fast Mode Duty Cycle - * @{ - */ -#define LL_I2C_DUTYCYCLE_2 0x00000000U /*!< I2C fast mode Tlow/Thigh = 2 */ -#define LL_I2C_DUTYCYCLE_16_9 I2C_CCR_DUTY /*!< I2C fast mode Tlow/Thigh = 16/9 */ -/** - * @} - */ - -/** @defgroup I2C_LL_EC_CLOCK_SPEED_MODE Master Clock Speed Mode - * @{ - */ -#define LL_I2C_CLOCK_SPEED_STANDARD_MODE 0x00000000U /*!< Master clock speed range is standard mode */ -#define LL_I2C_CLOCK_SPEED_FAST_MODE I2C_CCR_FS /*!< Master clock speed range is fast mode */ -/** - * @} - */ - -/** @defgroup I2C_LL_EC_PERIPHERAL_MODE Peripheral Mode - * @{ - */ -#define LL_I2C_MODE_I2C 0x00000000U /*!< I2C Master or Slave mode */ -#define LL_I2C_MODE_SMBUS_HOST (uint32_t)(I2C_CR1_SMBUS | I2C_CR1_SMBTYPE | I2C_CR1_ENARP) /*!< SMBus Host address acknowledge */ -#define LL_I2C_MODE_SMBUS_DEVICE I2C_CR1_SMBUS /*!< SMBus Device default mode (Default address not acknowledge) */ -#define LL_I2C_MODE_SMBUS_DEVICE_ARP (uint32_t)(I2C_CR1_SMBUS | I2C_CR1_ENARP) /*!< SMBus Device Default address acknowledge */ -/** - * @} - */ - -/** @defgroup I2C_LL_EC_I2C_ACKNOWLEDGE Acknowledge Generation - * @{ - */ -#define LL_I2C_ACK I2C_CR1_ACK /*!< ACK is sent after current received byte. */ -#define LL_I2C_NACK 0x00000000U /*!< NACK is sent after current received byte.*/ -/** - * @} - */ - -/** @defgroup I2C_LL_EC_DIRECTION Read Write Direction - * @{ - */ -#define LL_I2C_DIRECTION_WRITE I2C_SR2_TRA /*!< Bus is in write transfer */ -#define LL_I2C_DIRECTION_READ 0x00000000U /*!< Bus is in read transfer */ -/** - * @} - */ - -/** - * @} - */ - -/* Exported macro ------------------------------------------------------------*/ -/** @defgroup I2C_LL_Exported_Macros I2C Exported Macros - * @{ - */ - -/** @defgroup I2C_LL_EM_WRITE_READ Common Write and read registers Macros - * @{ - */ - -/** - * @brief Write a value in I2C register - * @param __INSTANCE__ I2C Instance - * @param __REG__ Register to be written - * @param __VALUE__ Value to be written in the register - * @retval None - */ -#define LL_I2C_WriteReg(__INSTANCE__, __REG__, __VALUE__) WRITE_REG(__INSTANCE__->__REG__, (__VALUE__)) - -/** - * @brief Read a value in I2C register - * @param __INSTANCE__ I2C Instance - * @param __REG__ Register to be read - * @retval Register value - */ -#define LL_I2C_ReadReg(__INSTANCE__, __REG__) READ_REG(__INSTANCE__->__REG__) -/** - * @} - */ - -/** @defgroup I2C_LL_EM_Exported_Macros_Helper Exported_Macros_Helper - * @{ - */ - -/** - * @brief Convert Peripheral Clock Frequency in Mhz. - * @param __PCLK__ This parameter must be a value of peripheral clock (in Hz). - * @retval Value of peripheral clock (in Mhz) - */ -#define __LL_I2C_FREQ_HZ_TO_MHZ(__PCLK__) (uint32_t)((__PCLK__)/1000000U) - -/** - * @brief Convert Peripheral Clock Frequency in Hz. - * @param __PCLK__ This parameter must be a value of peripheral clock (in Mhz). - * @retval Value of peripheral clock (in Hz) - */ -#define __LL_I2C_FREQ_MHZ_TO_HZ(__PCLK__) (uint32_t)((__PCLK__)*1000000U) - -/** - * @brief Compute I2C Clock rising time. - * @param __FREQRANGE__ This parameter must be a value of peripheral clock (in Mhz). - * @param __SPEED__ This parameter must be a value lower than 400kHz (in Hz). - * @retval Value between Min_Data=0x02 and Max_Data=0x3F - */ -#define __LL_I2C_RISE_TIME(__FREQRANGE__, __SPEED__) (uint32_t)(((__SPEED__) <= LL_I2C_MAX_SPEED_STANDARD) ? ((__FREQRANGE__) + 1U) : ((((__FREQRANGE__) * 300U) / 1000U) + 1U)) - -/** - * @brief Compute Speed clock range to a Clock Control Register (I2C_CCR_CCR) value. - * @param __PCLK__ This parameter must be a value of peripheral clock (in Hz). - * @param __SPEED__ This parameter must be a value lower than 400kHz (in Hz). - * @param __DUTYCYCLE__ This parameter can be one of the following values: - * @arg @ref LL_I2C_DUTYCYCLE_2 - * @arg @ref LL_I2C_DUTYCYCLE_16_9 - * @retval Value between Min_Data=0x004 and Max_Data=0xFFF, except in FAST DUTY mode where Min_Data=0x001. - */ -#define __LL_I2C_SPEED_TO_CCR(__PCLK__, __SPEED__, __DUTYCYCLE__) (uint32_t)(((__SPEED__) <= LL_I2C_MAX_SPEED_STANDARD)? \ - (__LL_I2C_SPEED_STANDARD_TO_CCR((__PCLK__), (__SPEED__))) : \ - (__LL_I2C_SPEED_FAST_TO_CCR((__PCLK__), (__SPEED__), (__DUTYCYCLE__)))) - -/** - * @brief Compute Speed Standard clock range to a Clock Control Register (I2C_CCR_CCR) value. - * @param __PCLK__ This parameter must be a value of peripheral clock (in Hz). - * @param __SPEED__ This parameter must be a value lower than 100kHz (in Hz). - * @retval Value between Min_Data=0x004 and Max_Data=0xFFF. - */ -#define __LL_I2C_SPEED_STANDARD_TO_CCR(__PCLK__, __SPEED__) (uint32_t)(((((__PCLK__)/((__SPEED__) << 1U)) & I2C_CCR_CCR) < 4U)? 4U:((__PCLK__) / ((__SPEED__) << 1U))) - -/** - * @brief Compute Speed Fast clock range to a Clock Control Register (I2C_CCR_CCR) value. - * @param __PCLK__ This parameter must be a value of peripheral clock (in Hz). - * @param __SPEED__ This parameter must be a value between Min_Data=100Khz and Max_Data=400Khz (in Hz). - * @param __DUTYCYCLE__ This parameter can be one of the following values: - * @arg @ref LL_I2C_DUTYCYCLE_2 - * @arg @ref LL_I2C_DUTYCYCLE_16_9 - * @retval Value between Min_Data=0x001 and Max_Data=0xFFF - */ -#define __LL_I2C_SPEED_FAST_TO_CCR(__PCLK__, __SPEED__, __DUTYCYCLE__) (uint32_t)(((__DUTYCYCLE__) == LL_I2C_DUTYCYCLE_2)? \ - (((((__PCLK__) / ((__SPEED__) * 3U)) & I2C_CCR_CCR) == 0U)? 1U:((__PCLK__) / ((__SPEED__) * 3U))) : \ - (((((__PCLK__) / ((__SPEED__) * 25U)) & I2C_CCR_CCR) == 0U)? 1U:((__PCLK__) / ((__SPEED__) * 25U)))) - -/** - * @brief Get the Least significant bits of a 10-Bits address. - * @param __ADDRESS__ This parameter must be a value of a 10-Bits slave address. - * @retval Value between Min_Data=0x00 and Max_Data=0xFF - */ -#define __LL_I2C_10BIT_ADDRESS(__ADDRESS__) ((uint8_t)((uint16_t)((__ADDRESS__) & (uint16_t)(0x00FF)))) - -/** - * @brief Convert a 10-Bits address to a 10-Bits header with Write direction. - * @param __ADDRESS__ This parameter must be a value of a 10-Bits slave address. - * @retval Value between Min_Data=0xF0 and Max_Data=0xF6 - */ -#define __LL_I2C_10BIT_HEADER_WRITE(__ADDRESS__) ((uint8_t)((uint16_t)((uint16_t)(((uint16_t)((__ADDRESS__) & (uint16_t)(0x0300))) >> 7) | (uint16_t)(0xF0)))) - -/** - * @brief Convert a 10-Bits address to a 10-Bits header with Read direction. - * @param __ADDRESS__ This parameter must be a value of a 10-Bits slave address. - * @retval Value between Min_Data=0xF1 and Max_Data=0xF7 - */ -#define __LL_I2C_10BIT_HEADER_READ(__ADDRESS__) ((uint8_t)((uint16_t)((uint16_t)(((uint16_t)((__ADDRESS__) & (uint16_t)(0x0300))) >> 7) | (uint16_t)(0xF1)))) - -/** - * @} - */ - -/** - * @} - */ - -/* Exported functions --------------------------------------------------------*/ - -/** @defgroup I2C_LL_Exported_Functions I2C Exported Functions - * @{ - */ - -/** @defgroup I2C_LL_EF_Configuration Configuration - * @{ - */ - -/** - * @brief Enable I2C peripheral (PE = 1). - * @rmtoll CR1 PE LL_I2C_Enable - * @param I2Cx I2C Instance. - * @retval None - */ -__STATIC_INLINE void LL_I2C_Enable(I2C_TypeDef *I2Cx) -{ - SET_BIT(I2Cx->CR1, I2C_CR1_PE); -} - -/** - * @brief Disable I2C peripheral (PE = 0). - * @rmtoll CR1 PE LL_I2C_Disable - * @param I2Cx I2C Instance. - * @retval None - */ -__STATIC_INLINE void LL_I2C_Disable(I2C_TypeDef *I2Cx) -{ - CLEAR_BIT(I2Cx->CR1, I2C_CR1_PE); -} - -/** - * @brief Check if the I2C peripheral is enabled or disabled. - * @rmtoll CR1 PE LL_I2C_IsEnabled - * @param I2Cx I2C Instance. - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_I2C_IsEnabled(I2C_TypeDef *I2Cx) -{ - return (READ_BIT(I2Cx->CR1, I2C_CR1_PE) == (I2C_CR1_PE)); -} - - -/** - * @brief Enable DMA transmission requests. - * @rmtoll CR2 DMAEN LL_I2C_EnableDMAReq_TX - * @param I2Cx I2C Instance. - * @retval None - */ -__STATIC_INLINE void LL_I2C_EnableDMAReq_TX(I2C_TypeDef *I2Cx) -{ - SET_BIT(I2Cx->CR2, I2C_CR2_DMAEN); -} - -/** - * @brief Disable DMA transmission requests. - * @rmtoll CR2 DMAEN LL_I2C_DisableDMAReq_TX - * @param I2Cx I2C Instance. - * @retval None - */ -__STATIC_INLINE void LL_I2C_DisableDMAReq_TX(I2C_TypeDef *I2Cx) -{ - CLEAR_BIT(I2Cx->CR2, I2C_CR2_DMAEN); -} - -/** - * @brief Check if DMA transmission requests are enabled or disabled. - * @rmtoll CR2 DMAEN LL_I2C_IsEnabledDMAReq_TX - * @param I2Cx I2C Instance. - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_I2C_IsEnabledDMAReq_TX(I2C_TypeDef *I2Cx) -{ - return (READ_BIT(I2Cx->CR2, I2C_CR2_DMAEN) == (I2C_CR2_DMAEN)); -} - -/** - * @brief Enable DMA reception requests. - * @rmtoll CR2 DMAEN LL_I2C_EnableDMAReq_RX - * @param I2Cx I2C Instance. - * @retval None - */ -__STATIC_INLINE void LL_I2C_EnableDMAReq_RX(I2C_TypeDef *I2Cx) -{ - SET_BIT(I2Cx->CR2, I2C_CR2_DMAEN); -} - -/** - * @brief Disable DMA reception requests. - * @rmtoll CR2 DMAEN LL_I2C_DisableDMAReq_RX - * @param I2Cx I2C Instance. - * @retval None - */ -__STATIC_INLINE void LL_I2C_DisableDMAReq_RX(I2C_TypeDef *I2Cx) -{ - CLEAR_BIT(I2Cx->CR2, I2C_CR2_DMAEN); -} - -/** - * @brief Check if DMA reception requests are enabled or disabled. - * @rmtoll CR2 DMAEN LL_I2C_IsEnabledDMAReq_RX - * @param I2Cx I2C Instance. - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_I2C_IsEnabledDMAReq_RX(I2C_TypeDef *I2Cx) -{ - return (READ_BIT(I2Cx->CR2, I2C_CR2_DMAEN) == (I2C_CR2_DMAEN)); -} - -/** - * @brief Get the data register address used for DMA transfer. - * @rmtoll DR DR LL_I2C_DMA_GetRegAddr - * @param I2Cx I2C Instance. - * @retval Address of data register - */ -__STATIC_INLINE uint32_t LL_I2C_DMA_GetRegAddr(I2C_TypeDef *I2Cx) -{ - return (uint32_t) & (I2Cx->DR); -} - -/** - * @brief Enable Clock stretching. - * @note This bit can only be programmed when the I2C is disabled (PE = 0). - * @rmtoll CR1 NOSTRETCH LL_I2C_EnableClockStretching - * @param I2Cx I2C Instance. - * @retval None - */ -__STATIC_INLINE void LL_I2C_EnableClockStretching(I2C_TypeDef *I2Cx) -{ - CLEAR_BIT(I2Cx->CR1, I2C_CR1_NOSTRETCH); -} - -/** - * @brief Disable Clock stretching. - * @note This bit can only be programmed when the I2C is disabled (PE = 0). - * @rmtoll CR1 NOSTRETCH LL_I2C_DisableClockStretching - * @param I2Cx I2C Instance. - * @retval None - */ -__STATIC_INLINE void LL_I2C_DisableClockStretching(I2C_TypeDef *I2Cx) -{ - SET_BIT(I2Cx->CR1, I2C_CR1_NOSTRETCH); -} - -/** - * @brief Check if Clock stretching is enabled or disabled. - * @rmtoll CR1 NOSTRETCH LL_I2C_IsEnabledClockStretching - * @param I2Cx I2C Instance. - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_I2C_IsEnabledClockStretching(I2C_TypeDef *I2Cx) -{ - return (READ_BIT(I2Cx->CR1, I2C_CR1_NOSTRETCH) != (I2C_CR1_NOSTRETCH)); -} - -/** - * @brief Enable General Call. - * @note When enabled the Address 0x00 is ACKed. - * @rmtoll CR1 ENGC LL_I2C_EnableGeneralCall - * @param I2Cx I2C Instance. - * @retval None - */ -__STATIC_INLINE void LL_I2C_EnableGeneralCall(I2C_TypeDef *I2Cx) -{ - SET_BIT(I2Cx->CR1, I2C_CR1_ENGC); -} - -/** - * @brief Disable General Call. - * @note When disabled the Address 0x00 is NACKed. - * @rmtoll CR1 ENGC LL_I2C_DisableGeneralCall - * @param I2Cx I2C Instance. - * @retval None - */ -__STATIC_INLINE void LL_I2C_DisableGeneralCall(I2C_TypeDef *I2Cx) -{ - CLEAR_BIT(I2Cx->CR1, I2C_CR1_ENGC); -} - -/** - * @brief Check if General Call is enabled or disabled. - * @rmtoll CR1 ENGC LL_I2C_IsEnabledGeneralCall - * @param I2Cx I2C Instance. - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_I2C_IsEnabledGeneralCall(I2C_TypeDef *I2Cx) -{ - return (READ_BIT(I2Cx->CR1, I2C_CR1_ENGC) == (I2C_CR1_ENGC)); -} - -/** - * @brief Set the Own Address1. - * @rmtoll OAR1 ADD0 LL_I2C_SetOwnAddress1\n - * OAR1 ADD1_7 LL_I2C_SetOwnAddress1\n - * OAR1 ADD8_9 LL_I2C_SetOwnAddress1\n - * OAR1 ADDMODE LL_I2C_SetOwnAddress1 - * @param I2Cx I2C Instance. - * @param OwnAddress1 This parameter must be a value between Min_Data=0 and Max_Data=0x3FF. - * @param OwnAddrSize This parameter can be one of the following values: - * @arg @ref LL_I2C_OWNADDRESS1_7BIT - * @arg @ref LL_I2C_OWNADDRESS1_10BIT - * @retval None - */ -__STATIC_INLINE void LL_I2C_SetOwnAddress1(I2C_TypeDef *I2Cx, uint32_t OwnAddress1, uint32_t OwnAddrSize) -{ - MODIFY_REG(I2Cx->OAR1, I2C_OAR1_ADD0 | I2C_OAR1_ADD1_7 | I2C_OAR1_ADD8_9 | I2C_OAR1_ADDMODE, OwnAddress1 | OwnAddrSize); -} - -/** - * @brief Set the 7bits Own Address2. - * @note This action has no effect if own address2 is enabled. - * @rmtoll OAR2 ADD2 LL_I2C_SetOwnAddress2 - * @param I2Cx I2C Instance. - * @param OwnAddress2 This parameter must be a value between Min_Data=0 and Max_Data=0x7F. - * @retval None - */ -__STATIC_INLINE void LL_I2C_SetOwnAddress2(I2C_TypeDef *I2Cx, uint32_t OwnAddress2) -{ - MODIFY_REG(I2Cx->OAR2, I2C_OAR2_ADD2, OwnAddress2); -} - -/** - * @brief Enable acknowledge on Own Address2 match address. - * @rmtoll OAR2 ENDUAL LL_I2C_EnableOwnAddress2 - * @param I2Cx I2C Instance. - * @retval None - */ -__STATIC_INLINE void LL_I2C_EnableOwnAddress2(I2C_TypeDef *I2Cx) -{ - SET_BIT(I2Cx->OAR2, I2C_OAR2_ENDUAL); -} - -/** - * @brief Disable acknowledge on Own Address2 match address. - * @rmtoll OAR2 ENDUAL LL_I2C_DisableOwnAddress2 - * @param I2Cx I2C Instance. - * @retval None - */ -__STATIC_INLINE void LL_I2C_DisableOwnAddress2(I2C_TypeDef *I2Cx) -{ - CLEAR_BIT(I2Cx->OAR2, I2C_OAR2_ENDUAL); -} - -/** - * @brief Check if Own Address1 acknowledge is enabled or disabled. - * @rmtoll OAR2 ENDUAL LL_I2C_IsEnabledOwnAddress2 - * @param I2Cx I2C Instance. - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_I2C_IsEnabledOwnAddress2(I2C_TypeDef *I2Cx) -{ - return (READ_BIT(I2Cx->OAR2, I2C_OAR2_ENDUAL) == (I2C_OAR2_ENDUAL)); -} - -/** - * @brief Configure the Peripheral clock frequency. - * @rmtoll CR2 FREQ LL_I2C_SetPeriphClock - * @param I2Cx I2C Instance. - * @param PeriphClock Peripheral Clock (in Hz) - * @retval None - */ -__STATIC_INLINE void LL_I2C_SetPeriphClock(I2C_TypeDef *I2Cx, uint32_t PeriphClock) -{ - MODIFY_REG(I2Cx->CR2, I2C_CR2_FREQ, __LL_I2C_FREQ_HZ_TO_MHZ(PeriphClock)); -} - -/** - * @brief Get the Peripheral clock frequency. - * @rmtoll CR2 FREQ LL_I2C_GetPeriphClock - * @param I2Cx I2C Instance. - * @retval Value of Peripheral Clock (in Hz) - */ -__STATIC_INLINE uint32_t LL_I2C_GetPeriphClock(I2C_TypeDef *I2Cx) -{ - return (uint32_t)(__LL_I2C_FREQ_MHZ_TO_HZ(READ_BIT(I2Cx->CR2, I2C_CR2_FREQ))); -} - -/** - * @brief Configure the Duty cycle (Fast mode only). - * @rmtoll CCR DUTY LL_I2C_SetDutyCycle - * @param I2Cx I2C Instance. - * @param DutyCycle This parameter can be one of the following values: - * @arg @ref LL_I2C_DUTYCYCLE_2 - * @arg @ref LL_I2C_DUTYCYCLE_16_9 - * @retval None - */ -__STATIC_INLINE void LL_I2C_SetDutyCycle(I2C_TypeDef *I2Cx, uint32_t DutyCycle) -{ - MODIFY_REG(I2Cx->CCR, I2C_CCR_DUTY, DutyCycle); -} - -/** - * @brief Get the Duty cycle (Fast mode only). - * @rmtoll CCR DUTY LL_I2C_GetDutyCycle - * @param I2Cx I2C Instance. - * @retval Returned value can be one of the following values: - * @arg @ref LL_I2C_DUTYCYCLE_2 - * @arg @ref LL_I2C_DUTYCYCLE_16_9 - */ -__STATIC_INLINE uint32_t LL_I2C_GetDutyCycle(I2C_TypeDef *I2Cx) -{ - return (uint32_t)(READ_BIT(I2Cx->CCR, I2C_CCR_DUTY)); -} - -/** - * @brief Configure the I2C master clock speed mode. - * @rmtoll CCR FS LL_I2C_SetClockSpeedMode - * @param I2Cx I2C Instance. - * @param ClockSpeedMode This parameter can be one of the following values: - * @arg @ref LL_I2C_CLOCK_SPEED_STANDARD_MODE - * @arg @ref LL_I2C_CLOCK_SPEED_FAST_MODE - * @retval None - */ -__STATIC_INLINE void LL_I2C_SetClockSpeedMode(I2C_TypeDef *I2Cx, uint32_t ClockSpeedMode) -{ - MODIFY_REG(I2Cx->CCR, I2C_CCR_FS, ClockSpeedMode); -} - -/** - * @brief Get the the I2C master speed mode. - * @rmtoll CCR FS LL_I2C_GetClockSpeedMode - * @param I2Cx I2C Instance. - * @retval Returned value can be one of the following values: - * @arg @ref LL_I2C_CLOCK_SPEED_STANDARD_MODE - * @arg @ref LL_I2C_CLOCK_SPEED_FAST_MODE - */ -__STATIC_INLINE uint32_t LL_I2C_GetClockSpeedMode(I2C_TypeDef *I2Cx) -{ - return (uint32_t)(READ_BIT(I2Cx->CCR, I2C_CCR_FS)); -} - -/** - * @brief Configure the SCL, SDA rising time. - * @note This bit can only be programmed when the I2C is disabled (PE = 0). - * @rmtoll TRISE TRISE LL_I2C_SetRiseTime - * @param I2Cx I2C Instance. - * @param RiseTime This parameter must be a value between Min_Data=0x02 and Max_Data=0x3F. - * @retval None - */ -__STATIC_INLINE void LL_I2C_SetRiseTime(I2C_TypeDef *I2Cx, uint32_t RiseTime) -{ - MODIFY_REG(I2Cx->TRISE, I2C_TRISE_TRISE, RiseTime); -} - -/** - * @brief Get the SCL, SDA rising time. - * @rmtoll TRISE TRISE LL_I2C_GetRiseTime - * @param I2Cx I2C Instance. - * @retval Value between Min_Data=0x02 and Max_Data=0x3F - */ -__STATIC_INLINE uint32_t LL_I2C_GetRiseTime(I2C_TypeDef *I2Cx) -{ - return (uint32_t)(READ_BIT(I2Cx->TRISE, I2C_TRISE_TRISE)); -} - -/** - * @brief Configure the SCL high and low period. - * @note This bit can only be programmed when the I2C is disabled (PE = 0). - * @rmtoll CCR CCR LL_I2C_SetClockPeriod - * @param I2Cx I2C Instance. - * @param ClockPeriod This parameter must be a value between Min_Data=0x004 and Max_Data=0xFFF, except in FAST DUTY mode where Min_Data=0x001. - * @retval None - */ -__STATIC_INLINE void LL_I2C_SetClockPeriod(I2C_TypeDef *I2Cx, uint32_t ClockPeriod) -{ - MODIFY_REG(I2Cx->CCR, I2C_CCR_CCR, ClockPeriod); -} - -/** - * @brief Get the SCL high and low period. - * @rmtoll CCR CCR LL_I2C_GetClockPeriod - * @param I2Cx I2C Instance. - * @retval Value between Min_Data=0x004 and Max_Data=0xFFF, except in FAST DUTY mode where Min_Data=0x001. - */ -__STATIC_INLINE uint32_t LL_I2C_GetClockPeriod(I2C_TypeDef *I2Cx) -{ - return (uint32_t)(READ_BIT(I2Cx->CCR, I2C_CCR_CCR)); -} - -/** - * @brief Configure the SCL speed. - * @note This bit can only be programmed when the I2C is disabled (PE = 0). - * @rmtoll CR2 FREQ LL_I2C_ConfigSpeed\n - * TRISE TRISE LL_I2C_ConfigSpeed\n - * CCR FS LL_I2C_ConfigSpeed\n - * CCR DUTY LL_I2C_ConfigSpeed\n - * CCR CCR LL_I2C_ConfigSpeed - * @param I2Cx I2C Instance. - * @param PeriphClock Peripheral Clock (in Hz) - * @param ClockSpeed This parameter must be a value lower than 400kHz (in Hz). - * @param DutyCycle This parameter can be one of the following values: - * @arg @ref LL_I2C_DUTYCYCLE_2 - * @arg @ref LL_I2C_DUTYCYCLE_16_9 - * @retval None - */ -__STATIC_INLINE void LL_I2C_ConfigSpeed(I2C_TypeDef *I2Cx, uint32_t PeriphClock, uint32_t ClockSpeed, - uint32_t DutyCycle) -{ - register uint32_t freqrange = 0x0U; - register uint32_t clockconfig = 0x0U; - - /* Compute frequency range */ - freqrange = __LL_I2C_FREQ_HZ_TO_MHZ(PeriphClock); - - /* Configure I2Cx: Frequency range register */ - MODIFY_REG(I2Cx->CR2, I2C_CR2_FREQ, freqrange); - - /* Configure I2Cx: Rise Time register */ - MODIFY_REG(I2Cx->TRISE, I2C_TRISE_TRISE, __LL_I2C_RISE_TIME(freqrange, ClockSpeed)); - - /* Configure Speed mode, Duty Cycle and Clock control register value */ - if (ClockSpeed > LL_I2C_MAX_SPEED_STANDARD) - { - /* Set Speed mode at fast and duty cycle for Clock Speed request in fast clock range */ - clockconfig = LL_I2C_CLOCK_SPEED_FAST_MODE | \ - __LL_I2C_SPEED_FAST_TO_CCR(PeriphClock, ClockSpeed, DutyCycle) | \ - DutyCycle; - } - else - { - /* Set Speed mode at standard for Clock Speed request in standard clock range */ - clockconfig = LL_I2C_CLOCK_SPEED_STANDARD_MODE | \ - __LL_I2C_SPEED_STANDARD_TO_CCR(PeriphClock, ClockSpeed); - } - - /* Configure I2Cx: Clock control register */ - MODIFY_REG(I2Cx->CCR, (I2C_CCR_FS | I2C_CCR_DUTY | I2C_CCR_CCR), clockconfig); -} - -/** - * @brief Configure peripheral mode. - * @note Macro @ref IS_SMBUS_ALL_INSTANCE(I2Cx) can be used to check whether or not - * SMBus feature is supported by the I2Cx Instance. - * @rmtoll CR1 SMBUS LL_I2C_SetMode\n - * CR1 SMBTYPE LL_I2C_SetMode\n - * CR1 ENARP LL_I2C_SetMode - * @param I2Cx I2C Instance. - * @param PeripheralMode This parameter can be one of the following values: - * @arg @ref LL_I2C_MODE_I2C - * @arg @ref LL_I2C_MODE_SMBUS_HOST - * @arg @ref LL_I2C_MODE_SMBUS_DEVICE - * @arg @ref LL_I2C_MODE_SMBUS_DEVICE_ARP - * @retval None - */ -__STATIC_INLINE void LL_I2C_SetMode(I2C_TypeDef *I2Cx, uint32_t PeripheralMode) -{ - MODIFY_REG(I2Cx->CR1, I2C_CR1_SMBUS | I2C_CR1_SMBTYPE | I2C_CR1_ENARP, PeripheralMode); -} - -/** - * @brief Get peripheral mode. - * @note Macro @ref IS_SMBUS_ALL_INSTANCE(I2Cx) can be used to check whether or not - * SMBus feature is supported by the I2Cx Instance. - * @rmtoll CR1 SMBUS LL_I2C_GetMode\n - * CR1 SMBTYPE LL_I2C_GetMode\n - * CR1 ENARP LL_I2C_GetMode - * @param I2Cx I2C Instance. - * @retval Returned value can be one of the following values: - * @arg @ref LL_I2C_MODE_I2C - * @arg @ref LL_I2C_MODE_SMBUS_HOST - * @arg @ref LL_I2C_MODE_SMBUS_DEVICE - * @arg @ref LL_I2C_MODE_SMBUS_DEVICE_ARP - */ -__STATIC_INLINE uint32_t LL_I2C_GetMode(I2C_TypeDef *I2Cx) -{ - return (uint32_t)(READ_BIT(I2Cx->CR1, I2C_CR1_SMBUS | I2C_CR1_SMBTYPE | I2C_CR1_ENARP)); -} - -/** - * @brief Enable SMBus alert (Host or Device mode) - * @note Macro @ref IS_SMBUS_ALL_INSTANCE(I2Cx) can be used to check whether or not - * SMBus feature is supported by the I2Cx Instance. - * @note SMBus Device mode: - * - SMBus Alert pin is drived low and - * Alert Response Address Header acknowledge is enabled. - * SMBus Host mode: - * - SMBus Alert pin management is supported. - * @rmtoll CR1 ALERT LL_I2C_EnableSMBusAlert - * @param I2Cx I2C Instance. - * @retval None - */ -__STATIC_INLINE void LL_I2C_EnableSMBusAlert(I2C_TypeDef *I2Cx) -{ - SET_BIT(I2Cx->CR1, I2C_CR1_ALERT); -} - -/** - * @brief Disable SMBus alert (Host or Device mode) - * @note Macro @ref IS_SMBUS_ALL_INSTANCE(I2Cx) can be used to check whether or not - * SMBus feature is supported by the I2Cx Instance. - * @note SMBus Device mode: - * - SMBus Alert pin is not drived (can be used as a standard GPIO) and - * Alert Response Address Header acknowledge is disabled. - * SMBus Host mode: - * - SMBus Alert pin management is not supported. - * @rmtoll CR1 ALERT LL_I2C_DisableSMBusAlert - * @param I2Cx I2C Instance. - * @retval None - */ -__STATIC_INLINE void LL_I2C_DisableSMBusAlert(I2C_TypeDef *I2Cx) -{ - CLEAR_BIT(I2Cx->CR1, I2C_CR1_ALERT); -} - -/** - * @brief Check if SMBus alert (Host or Device mode) is enabled or disabled. - * @note Macro @ref IS_SMBUS_ALL_INSTANCE(I2Cx) can be used to check whether or not - * SMBus feature is supported by the I2Cx Instance. - * @rmtoll CR1 ALERT LL_I2C_IsEnabledSMBusAlert - * @param I2Cx I2C Instance. - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_I2C_IsEnabledSMBusAlert(I2C_TypeDef *I2Cx) -{ - return (READ_BIT(I2Cx->CR1, I2C_CR1_ALERT) == (I2C_CR1_ALERT)); -} - -/** - * @brief Enable SMBus Packet Error Calculation (PEC). - * @note Macro @ref IS_SMBUS_ALL_INSTANCE(I2Cx) can be used to check whether or not - * SMBus feature is supported by the I2Cx Instance. - * @rmtoll CR1 ENPEC LL_I2C_EnableSMBusPEC - * @param I2Cx I2C Instance. - * @retval None - */ -__STATIC_INLINE void LL_I2C_EnableSMBusPEC(I2C_TypeDef *I2Cx) -{ - SET_BIT(I2Cx->CR1, I2C_CR1_ENPEC); -} - -/** - * @brief Disable SMBus Packet Error Calculation (PEC). - * @note Macro @ref IS_SMBUS_ALL_INSTANCE(I2Cx) can be used to check whether or not - * SMBus feature is supported by the I2Cx Instance. - * @rmtoll CR1 ENPEC LL_I2C_DisableSMBusPEC - * @param I2Cx I2C Instance. - * @retval None - */ -__STATIC_INLINE void LL_I2C_DisableSMBusPEC(I2C_TypeDef *I2Cx) -{ - CLEAR_BIT(I2Cx->CR1, I2C_CR1_ENPEC); -} - -/** - * @brief Check if SMBus Packet Error Calculation (PEC) is enabled or disabled. - * @note Macro @ref IS_SMBUS_ALL_INSTANCE(I2Cx) can be used to check whether or not - * SMBus feature is supported by the I2Cx Instance. - * @rmtoll CR1 ENPEC LL_I2C_IsEnabledSMBusPEC - * @param I2Cx I2C Instance. - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_I2C_IsEnabledSMBusPEC(I2C_TypeDef *I2Cx) -{ - return (READ_BIT(I2Cx->CR1, I2C_CR1_ENPEC) == (I2C_CR1_ENPEC)); -} - -/** - * @} - */ - -/** @defgroup I2C_LL_EF_IT_Management IT_Management - * @{ - */ - -/** - * @brief Enable TXE interrupt. - * @rmtoll CR2 ITEVTEN LL_I2C_EnableIT_TX\n - * CR2 ITBUFEN LL_I2C_EnableIT_TX - * @param I2Cx I2C Instance. - * @retval None - */ -__STATIC_INLINE void LL_I2C_EnableIT_TX(I2C_TypeDef *I2Cx) -{ - SET_BIT(I2Cx->CR2, I2C_CR2_ITEVTEN | I2C_CR2_ITBUFEN); -} - -/** - * @brief Disable TXE interrupt. - * @rmtoll CR2 ITEVTEN LL_I2C_DisableIT_TX\n - * CR2 ITBUFEN LL_I2C_DisableIT_TX - * @param I2Cx I2C Instance. - * @retval None - */ -__STATIC_INLINE void LL_I2C_DisableIT_TX(I2C_TypeDef *I2Cx) -{ - CLEAR_BIT(I2Cx->CR2, I2C_CR2_ITEVTEN | I2C_CR2_ITBUFEN); -} - -/** - * @brief Check if the TXE Interrupt is enabled or disabled. - * @rmtoll CR2 ITEVTEN LL_I2C_IsEnabledIT_TX\n - * CR2 ITBUFEN LL_I2C_IsEnabledIT_TX - * @param I2Cx I2C Instance. - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_I2C_IsEnabledIT_TX(I2C_TypeDef *I2Cx) -{ - return (READ_BIT(I2Cx->CR2, I2C_CR2_ITEVTEN | I2C_CR2_ITBUFEN) == (I2C_CR2_ITEVTEN | I2C_CR2_ITBUFEN)); -} - -/** - * @brief Enable RXNE interrupt. - * @rmtoll CR2 ITEVTEN LL_I2C_EnableIT_RX\n - * CR2 ITBUFEN LL_I2C_EnableIT_RX - * @param I2Cx I2C Instance. - * @retval None - */ -__STATIC_INLINE void LL_I2C_EnableIT_RX(I2C_TypeDef *I2Cx) -{ - SET_BIT(I2Cx->CR2, I2C_CR2_ITEVTEN | I2C_CR2_ITBUFEN); -} - -/** - * @brief Disable RXNE interrupt. - * @rmtoll CR2 ITEVTEN LL_I2C_DisableIT_RX\n - * CR2 ITBUFEN LL_I2C_DisableIT_RX - * @param I2Cx I2C Instance. - * @retval None - */ -__STATIC_INLINE void LL_I2C_DisableIT_RX(I2C_TypeDef *I2Cx) -{ - CLEAR_BIT(I2Cx->CR2, I2C_CR2_ITEVTEN | I2C_CR2_ITBUFEN); -} - -/** - * @brief Check if the RXNE Interrupt is enabled or disabled. - * @rmtoll CR2 ITEVTEN LL_I2C_IsEnabledIT_RX\n - * CR2 ITBUFEN LL_I2C_IsEnabledIT_RX - * @param I2Cx I2C Instance. - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_I2C_IsEnabledIT_RX(I2C_TypeDef *I2Cx) -{ - return (READ_BIT(I2Cx->CR2, I2C_CR2_ITEVTEN | I2C_CR2_ITBUFEN) == (I2C_CR2_ITEVTEN | I2C_CR2_ITBUFEN)); -} - -/** - * @brief Enable Events interrupts. - * @note Any of these events will generate interrupt : - * Start Bit (SB) - * Address sent, Address matched (ADDR) - * 10-bit header sent (ADD10) - * Stop detection (STOPF) - * Byte transfer finished (BTF) - * - * @note Any of these events will generate interrupt if Buffer interrupts are enabled too(using unitary function @ref LL_I2C_EnableIT_BUF()) : - * Receive buffer not empty (RXNE) - * Transmit buffer empty (TXE) - * @rmtoll CR2 ITEVTEN LL_I2C_EnableIT_EVT - * @param I2Cx I2C Instance. - * @retval None - */ -__STATIC_INLINE void LL_I2C_EnableIT_EVT(I2C_TypeDef *I2Cx) -{ - SET_BIT(I2Cx->CR2, I2C_CR2_ITEVTEN); -} - -/** - * @brief Disable Events interrupts. - * @note Any of these events will generate interrupt : - * Start Bit (SB) - * Address sent, Address matched (ADDR) - * 10-bit header sent (ADD10) - * Stop detection (STOPF) - * Byte transfer finished (BTF) - * Receive buffer not empty (RXNE) - * Transmit buffer empty (TXE) - * @rmtoll CR2 ITEVTEN LL_I2C_DisableIT_EVT - * @param I2Cx I2C Instance. - * @retval None - */ -__STATIC_INLINE void LL_I2C_DisableIT_EVT(I2C_TypeDef *I2Cx) -{ - CLEAR_BIT(I2Cx->CR2, I2C_CR2_ITEVTEN); -} - -/** - * @brief Check if Events interrupts are enabled or disabled. - * @rmtoll CR2 ITEVTEN LL_I2C_IsEnabledIT_EVT - * @param I2Cx I2C Instance. - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_I2C_IsEnabledIT_EVT(I2C_TypeDef *I2Cx) -{ - return (READ_BIT(I2Cx->CR2, I2C_CR2_ITEVTEN) == (I2C_CR2_ITEVTEN)); -} - -/** - * @brief Enable Buffer interrupts. - * @note Any of these Buffer events will generate interrupt if Events interrupts are enabled too(using unitary function @ref LL_I2C_EnableIT_EVT()) : - * Receive buffer not empty (RXNE) - * Transmit buffer empty (TXE) - * @rmtoll CR2 ITBUFEN LL_I2C_EnableIT_BUF - * @param I2Cx I2C Instance. - * @retval None - */ -__STATIC_INLINE void LL_I2C_EnableIT_BUF(I2C_TypeDef *I2Cx) -{ - SET_BIT(I2Cx->CR2, I2C_CR2_ITBUFEN); -} - -/** - * @brief Disable Buffer interrupts. - * @note Any of these Buffer events will generate interrupt : - * Receive buffer not empty (RXNE) - * Transmit buffer empty (TXE) - * @rmtoll CR2 ITBUFEN LL_I2C_DisableIT_BUF - * @param I2Cx I2C Instance. - * @retval None - */ -__STATIC_INLINE void LL_I2C_DisableIT_BUF(I2C_TypeDef *I2Cx) -{ - CLEAR_BIT(I2Cx->CR2, I2C_CR2_ITBUFEN); -} - -/** - * @brief Check if Buffer interrupts are enabled or disabled. - * @rmtoll CR2 ITBUFEN LL_I2C_IsEnabledIT_BUF - * @param I2Cx I2C Instance. - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_I2C_IsEnabledIT_BUF(I2C_TypeDef *I2Cx) -{ - return (READ_BIT(I2Cx->CR2, I2C_CR2_ITBUFEN) == (I2C_CR2_ITBUFEN)); -} - -/** - * @brief Enable Error interrupts. - * @note Macro @ref IS_SMBUS_ALL_INSTANCE(I2Cx) can be used to check whether or not - * SMBus feature is supported by the I2Cx Instance. - * @note Any of these errors will generate interrupt : - * Bus Error detection (BERR) - * Arbitration Loss (ARLO) - * Acknowledge Failure(AF) - * Overrun/Underrun (OVR) - * SMBus Timeout detection (TIMEOUT) - * SMBus PEC error detection (PECERR) - * SMBus Alert pin event detection (SMBALERT) - * @rmtoll CR2 ITERREN LL_I2C_EnableIT_ERR - * @param I2Cx I2C Instance. - * @retval None - */ -__STATIC_INLINE void LL_I2C_EnableIT_ERR(I2C_TypeDef *I2Cx) -{ - SET_BIT(I2Cx->CR2, I2C_CR2_ITERREN); -} - -/** - * @brief Disable Error interrupts. - * @note Macro @ref IS_SMBUS_ALL_INSTANCE(I2Cx) can be used to check whether or not - * SMBus feature is supported by the I2Cx Instance. - * @note Any of these errors will generate interrupt : - * Bus Error detection (BERR) - * Arbitration Loss (ARLO) - * Acknowledge Failure(AF) - * Overrun/Underrun (OVR) - * SMBus Timeout detection (TIMEOUT) - * SMBus PEC error detection (PECERR) - * SMBus Alert pin event detection (SMBALERT) - * @rmtoll CR2 ITERREN LL_I2C_DisableIT_ERR - * @param I2Cx I2C Instance. - * @retval None - */ -__STATIC_INLINE void LL_I2C_DisableIT_ERR(I2C_TypeDef *I2Cx) -{ - CLEAR_BIT(I2Cx->CR2, I2C_CR2_ITERREN); -} - -/** - * @brief Check if Error interrupts are enabled or disabled. - * @rmtoll CR2 ITERREN LL_I2C_IsEnabledIT_ERR - * @param I2Cx I2C Instance. - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_I2C_IsEnabledIT_ERR(I2C_TypeDef *I2Cx) -{ - return (READ_BIT(I2Cx->CR2, I2C_CR2_ITERREN) == (I2C_CR2_ITERREN)); -} - -/** - * @} - */ - -/** @defgroup I2C_LL_EF_FLAG_management FLAG_management - * @{ - */ - -/** - * @brief Indicate the status of Transmit data register empty flag. - * @note RESET: When next data is written in Transmit data register. - * SET: When Transmit data register is empty. - * @rmtoll SR1 TXE LL_I2C_IsActiveFlag_TXE - * @param I2Cx I2C Instance. - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_I2C_IsActiveFlag_TXE(I2C_TypeDef *I2Cx) -{ - return (READ_BIT(I2Cx->SR1, I2C_SR1_TXE) == (I2C_SR1_TXE)); -} - -/** - * @brief Indicate the status of Byte Transfer Finished flag. - * RESET: When Data byte transfer not done. - * SET: When Data byte transfer succeeded. - * @rmtoll SR1 BTF LL_I2C_IsActiveFlag_BTF - * @param I2Cx I2C Instance. - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_I2C_IsActiveFlag_BTF(I2C_TypeDef *I2Cx) -{ - return (READ_BIT(I2Cx->SR1, I2C_SR1_BTF) == (I2C_SR1_BTF)); -} - -/** - * @brief Indicate the status of Receive data register not empty flag. - * @note RESET: When Receive data register is read. - * SET: When the received data is copied in Receive data register. - * @rmtoll SR1 RXNE LL_I2C_IsActiveFlag_RXNE - * @param I2Cx I2C Instance. - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_I2C_IsActiveFlag_RXNE(I2C_TypeDef *I2Cx) -{ - return (READ_BIT(I2Cx->SR1, I2C_SR1_RXNE) == (I2C_SR1_RXNE)); -} - -/** - * @brief Indicate the status of Start Bit (master mode). - * @note RESET: When No Start condition. - * SET: When Start condition is generated. - * @rmtoll SR1 SB LL_I2C_IsActiveFlag_SB - * @param I2Cx I2C Instance. - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_I2C_IsActiveFlag_SB(I2C_TypeDef *I2Cx) -{ - return (READ_BIT(I2Cx->SR1, I2C_SR1_SB) == (I2C_SR1_SB)); -} - -/** - * @brief Indicate the status of Address sent (master mode) or Address matched flag (slave mode). - * @note RESET: Clear default value. - * SET: When the address is fully sent (master mode) or when the received slave address matched with one of the enabled slave address (slave mode). - * @rmtoll SR1 ADDR LL_I2C_IsActiveFlag_ADDR - * @param I2Cx I2C Instance. - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_I2C_IsActiveFlag_ADDR(I2C_TypeDef *I2Cx) -{ - return (READ_BIT(I2Cx->SR1, I2C_SR1_ADDR) == (I2C_SR1_ADDR)); -} - -/** - * @brief Indicate the status of 10-bit header sent (master mode). - * @note RESET: When no ADD10 event occured. - * SET: When the master has sent the first address byte (header). - * @rmtoll SR1 ADD10 LL_I2C_IsActiveFlag_ADD10 - * @param I2Cx I2C Instance. - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_I2C_IsActiveFlag_ADD10(I2C_TypeDef *I2Cx) -{ - return (READ_BIT(I2Cx->SR1, I2C_SR1_ADD10) == (I2C_SR1_ADD10)); -} - -/** - * @brief Indicate the status of Acknowledge failure flag. - * @note RESET: No acknowledge failure. - * SET: When an acknowledge failure is received after a byte transmission. - * @rmtoll SR1 AF LL_I2C_IsActiveFlag_AF - * @param I2Cx I2C Instance. - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_I2C_IsActiveFlag_AF(I2C_TypeDef *I2Cx) -{ - return (READ_BIT(I2Cx->SR1, I2C_SR1_AF) == (I2C_SR1_AF)); -} - -/** - * @brief Indicate the status of Stop detection flag (slave mode). - * @note RESET: Clear default value. - * SET: When a Stop condition is detected. - * @rmtoll SR1 STOPF LL_I2C_IsActiveFlag_STOP - * @param I2Cx I2C Instance. - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_I2C_IsActiveFlag_STOP(I2C_TypeDef *I2Cx) -{ - return (READ_BIT(I2Cx->SR1, I2C_SR1_STOPF) == (I2C_SR1_STOPF)); -} - -/** - * @brief Indicate the status of Bus error flag. - * @note RESET: Clear default value. - * SET: When a misplaced Start or Stop condition is detected. - * @rmtoll SR1 BERR LL_I2C_IsActiveFlag_BERR - * @param I2Cx I2C Instance. - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_I2C_IsActiveFlag_BERR(I2C_TypeDef *I2Cx) -{ - return (READ_BIT(I2Cx->SR1, I2C_SR1_BERR) == (I2C_SR1_BERR)); -} - -/** - * @brief Indicate the status of Arbitration lost flag. - * @note RESET: Clear default value. - * SET: When arbitration lost. - * @rmtoll SR1 ARLO LL_I2C_IsActiveFlag_ARLO - * @param I2Cx I2C Instance. - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_I2C_IsActiveFlag_ARLO(I2C_TypeDef *I2Cx) -{ - return (READ_BIT(I2Cx->SR1, I2C_SR1_ARLO) == (I2C_SR1_ARLO)); -} - -/** - * @brief Indicate the status of Overrun/Underrun flag. - * @note RESET: Clear default value. - * SET: When an overrun/underrun error occurs (Clock Stretching Disabled). - * @rmtoll SR1 OVR LL_I2C_IsActiveFlag_OVR - * @param I2Cx I2C Instance. - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_I2C_IsActiveFlag_OVR(I2C_TypeDef *I2Cx) -{ - return (READ_BIT(I2Cx->SR1, I2C_SR1_OVR) == (I2C_SR1_OVR)); -} - -/** - * @brief Indicate the status of SMBus PEC error flag in reception. - * @note Macro @ref IS_SMBUS_ALL_INSTANCE(I2Cx) can be used to check whether or not - * SMBus feature is supported by the I2Cx Instance. - * @rmtoll SR1 PECERR LL_I2C_IsActiveSMBusFlag_PECERR - * @param I2Cx I2C Instance. - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_I2C_IsActiveSMBusFlag_PECERR(I2C_TypeDef *I2Cx) -{ - return (READ_BIT(I2Cx->SR1, I2C_SR1_PECERR) == (I2C_SR1_PECERR)); -} - -/** - * @brief Indicate the status of SMBus Timeout detection flag. - * @note Macro @ref IS_SMBUS_ALL_INSTANCE(I2Cx) can be used to check whether or not - * SMBus feature is supported by the I2Cx Instance. - * @rmtoll SR1 TIMEOUT LL_I2C_IsActiveSMBusFlag_TIMEOUT - * @param I2Cx I2C Instance. - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_I2C_IsActiveSMBusFlag_TIMEOUT(I2C_TypeDef *I2Cx) -{ - return (READ_BIT(I2Cx->SR1, I2C_SR1_TIMEOUT) == (I2C_SR1_TIMEOUT)); -} - -/** - * @brief Indicate the status of SMBus alert flag. - * @note Macro @ref IS_SMBUS_ALL_INSTANCE(I2Cx) can be used to check whether or not - * SMBus feature is supported by the I2Cx Instance. - * @rmtoll SR1 SMBALERT LL_I2C_IsActiveSMBusFlag_ALERT - * @param I2Cx I2C Instance. - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_I2C_IsActiveSMBusFlag_ALERT(I2C_TypeDef *I2Cx) -{ - return (READ_BIT(I2Cx->SR1, I2C_SR1_SMBALERT) == (I2C_SR1_SMBALERT)); -} - -/** - * @brief Indicate the status of Bus Busy flag. - * @note RESET: Clear default value. - * SET: When a Start condition is detected. - * @rmtoll SR2 BUSY LL_I2C_IsActiveFlag_BUSY - * @param I2Cx I2C Instance. - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_I2C_IsActiveFlag_BUSY(I2C_TypeDef *I2Cx) -{ - return (READ_BIT(I2Cx->SR2, I2C_SR2_BUSY) == (I2C_SR2_BUSY)); -} - -/** - * @brief Indicate the status of Dual flag. - * @note RESET: Received address matched with OAR1. - * SET: Received address matched with OAR2. - * @rmtoll SR2 DUALF LL_I2C_IsActiveFlag_DUAL - * @param I2Cx I2C Instance. - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_I2C_IsActiveFlag_DUAL(I2C_TypeDef *I2Cx) -{ - return (READ_BIT(I2Cx->SR2, I2C_SR2_DUALF) == (I2C_SR2_DUALF)); -} - -/** - * @brief Indicate the status of SMBus Host address reception (Slave mode). - * @note Macro @ref IS_SMBUS_ALL_INSTANCE(I2Cx) can be used to check whether or not - * SMBus feature is supported by the I2Cx Instance. - * @note RESET: No SMBus Host address - * SET: SMBus Host address received. - * @note This status is cleared by hardware after a STOP condition or repeated START condition. - * @rmtoll SR2 SMBHOST LL_I2C_IsActiveSMBusFlag_SMBHOST - * @param I2Cx I2C Instance. - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_I2C_IsActiveSMBusFlag_SMBHOST(I2C_TypeDef *I2Cx) -{ - return (READ_BIT(I2Cx->SR2, I2C_SR2_SMBHOST) == (I2C_SR2_SMBHOST)); -} - -/** - * @brief Indicate the status of SMBus Device default address reception (Slave mode). - * @note Macro @ref IS_SMBUS_ALL_INSTANCE(I2Cx) can be used to check whether or not - * SMBus feature is supported by the I2Cx Instance. - * @note RESET: No SMBus Device default address - * SET: SMBus Device default address received. - * @note This status is cleared by hardware after a STOP condition or repeated START condition. - * @rmtoll SR2 SMBDEFAULT LL_I2C_IsActiveSMBusFlag_SMBDEFAULT - * @param I2Cx I2C Instance. - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_I2C_IsActiveSMBusFlag_SMBDEFAULT(I2C_TypeDef *I2Cx) -{ - return (READ_BIT(I2Cx->SR2, I2C_SR2_SMBDEFAULT) == (I2C_SR2_SMBDEFAULT)); -} - -/** - * @brief Indicate the status of General call address reception (Slave mode). - * @note RESET: No Generall call address - * SET: General call address received. - * @note This status is cleared by hardware after a STOP condition or repeated START condition. - * @rmtoll SR2 GENCALL LL_I2C_IsActiveFlag_GENCALL - * @param I2Cx I2C Instance. - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_I2C_IsActiveFlag_GENCALL(I2C_TypeDef *I2Cx) -{ - return (READ_BIT(I2Cx->SR2, I2C_SR2_GENCALL) == (I2C_SR2_GENCALL)); -} - -/** - * @brief Indicate the status of Master/Slave flag. - * @note RESET: Slave Mode. - * SET: Master Mode. - * @rmtoll SR2 MSL LL_I2C_IsActiveFlag_MSL - * @param I2Cx I2C Instance. - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_I2C_IsActiveFlag_MSL(I2C_TypeDef *I2Cx) -{ - return (READ_BIT(I2Cx->SR2, I2C_SR2_MSL) == (I2C_SR2_MSL)); -} - -/** - * @brief Clear Address Matched flag. - * @note Clearing this flag is done by a read access to the I2Cx_SR1 - * register followed by a read access to the I2Cx_SR2 register. - * @rmtoll SR1 ADDR LL_I2C_ClearFlag_ADDR - * @param I2Cx I2C Instance. - * @retval None - */ -__STATIC_INLINE void LL_I2C_ClearFlag_ADDR(I2C_TypeDef *I2Cx) -{ - __IO uint32_t tmpreg; - tmpreg = I2Cx->SR1; - (void) tmpreg; - tmpreg = I2Cx->SR2; - (void) tmpreg; -} - -/** - * @brief Clear Acknowledge failure flag. - * @rmtoll SR1 AF LL_I2C_ClearFlag_AF - * @param I2Cx I2C Instance. - * @retval None - */ -__STATIC_INLINE void LL_I2C_ClearFlag_AF(I2C_TypeDef *I2Cx) -{ - CLEAR_BIT(I2Cx->SR1, I2C_SR1_AF); -} - -/** - * @brief Clear Stop detection flag. - * @note Clearing this flag is done by a read access to the I2Cx_SR1 - * register followed by a write access to I2Cx_CR1 register. - * @rmtoll SR1 STOPF LL_I2C_ClearFlag_STOP\n - * CR1 PE LL_I2C_ClearFlag_STOP - * @param I2Cx I2C Instance. - * @retval None - */ -__STATIC_INLINE void LL_I2C_ClearFlag_STOP(I2C_TypeDef *I2Cx) -{ - __IO uint32_t tmpreg; - tmpreg = I2Cx->SR1; - (void) tmpreg; - SET_BIT(I2Cx->CR1, I2C_CR1_PE); -} - -/** - * @brief Clear Bus error flag. - * @rmtoll SR1 BERR LL_I2C_ClearFlag_BERR - * @param I2Cx I2C Instance. - * @retval None - */ -__STATIC_INLINE void LL_I2C_ClearFlag_BERR(I2C_TypeDef *I2Cx) -{ - CLEAR_BIT(I2Cx->SR1, I2C_SR1_BERR); -} - -/** - * @brief Clear Arbitration lost flag. - * @rmtoll SR1 ARLO LL_I2C_ClearFlag_ARLO - * @param I2Cx I2C Instance. - * @retval None - */ -__STATIC_INLINE void LL_I2C_ClearFlag_ARLO(I2C_TypeDef *I2Cx) -{ - CLEAR_BIT(I2Cx->SR1, I2C_SR1_ARLO); -} - -/** - * @brief Clear Overrun/Underrun flag. - * @rmtoll SR1 OVR LL_I2C_ClearFlag_OVR - * @param I2Cx I2C Instance. - * @retval None - */ -__STATIC_INLINE void LL_I2C_ClearFlag_OVR(I2C_TypeDef *I2Cx) -{ - CLEAR_BIT(I2Cx->SR1, I2C_SR1_OVR); -} - -/** - * @brief Clear SMBus PEC error flag. - * @rmtoll SR1 PECERR LL_I2C_ClearSMBusFlag_PECERR - * @param I2Cx I2C Instance. - * @retval None - */ -__STATIC_INLINE void LL_I2C_ClearSMBusFlag_PECERR(I2C_TypeDef *I2Cx) -{ - CLEAR_BIT(I2Cx->SR1, I2C_SR1_PECERR); -} - -/** - * @brief Clear SMBus Timeout detection flag. - * @note Macro @ref IS_SMBUS_ALL_INSTANCE(I2Cx) can be used to check whether or not - * SMBus feature is supported by the I2Cx Instance. - * @rmtoll SR1 TIMEOUT LL_I2C_ClearSMBusFlag_TIMEOUT - * @param I2Cx I2C Instance. - * @retval None - */ -__STATIC_INLINE void LL_I2C_ClearSMBusFlag_TIMEOUT(I2C_TypeDef *I2Cx) -{ - CLEAR_BIT(I2Cx->SR1, I2C_SR1_TIMEOUT); -} - -/** - * @brief Clear SMBus Alert flag. - * @note Macro @ref IS_SMBUS_ALL_INSTANCE(I2Cx) can be used to check whether or not - * SMBus feature is supported by the I2Cx Instance. - * @rmtoll SR1 SMBALERT LL_I2C_ClearSMBusFlag_ALERT - * @param I2Cx I2C Instance. - * @retval None - */ -__STATIC_INLINE void LL_I2C_ClearSMBusFlag_ALERT(I2C_TypeDef *I2Cx) -{ - CLEAR_BIT(I2Cx->SR1, I2C_SR1_SMBALERT); -} - -/** - * @} - */ - -/** @defgroup I2C_LL_EF_Data_Management Data_Management - * @{ - */ - -/** - * @brief Enable Reset of I2C peripheral. - * @rmtoll CR1 SWRST LL_I2C_EnableReset - * @param I2Cx I2C Instance. - * @retval None - */ -__STATIC_INLINE void LL_I2C_EnableReset(I2C_TypeDef *I2Cx) -{ - SET_BIT(I2Cx->CR1, I2C_CR1_SWRST); -} - -/** - * @brief Disable Reset of I2C peripheral. - * @rmtoll CR1 SWRST LL_I2C_DisableReset - * @param I2Cx I2C Instance. - * @retval None - */ -__STATIC_INLINE void LL_I2C_DisableReset(I2C_TypeDef *I2Cx) -{ - CLEAR_BIT(I2Cx->CR1, I2C_CR1_SWRST); -} - -/** - * @brief Check if the I2C peripheral is under reset state or not. - * @rmtoll CR1 SWRST LL_I2C_IsResetEnabled - * @param I2Cx I2C Instance. - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_I2C_IsResetEnabled(I2C_TypeDef *I2Cx) -{ - return (READ_BIT(I2Cx->CR1, I2C_CR1_SWRST) == (I2C_CR1_SWRST)); -} - -/** - * @brief Prepare the generation of a ACKnowledge or Non ACKnowledge condition after the address receive match code or next received byte. - * @note Usage in Slave or Master mode. - * @rmtoll CR1 ACK LL_I2C_AcknowledgeNextData - * @param I2Cx I2C Instance. - * @param TypeAcknowledge This parameter can be one of the following values: - * @arg @ref LL_I2C_ACK - * @arg @ref LL_I2C_NACK - * @retval None - */ -__STATIC_INLINE void LL_I2C_AcknowledgeNextData(I2C_TypeDef *I2Cx, uint32_t TypeAcknowledge) -{ - MODIFY_REG(I2Cx->CR1, I2C_CR1_ACK, TypeAcknowledge); -} - -/** - * @brief Generate a START or RESTART condition - * @note The START bit can be set even if bus is BUSY or I2C is in slave mode. - * This action has no effect when RELOAD is set. - * @rmtoll CR1 START LL_I2C_GenerateStartCondition - * @param I2Cx I2C Instance. - * @retval None - */ -__STATIC_INLINE void LL_I2C_GenerateStartCondition(I2C_TypeDef *I2Cx) -{ - SET_BIT(I2Cx->CR1, I2C_CR1_START); -} - -/** - * @brief Generate a STOP condition after the current byte transfer (master mode). - * @rmtoll CR1 STOP LL_I2C_GenerateStopCondition - * @param I2Cx I2C Instance. - * @retval None - */ -__STATIC_INLINE void LL_I2C_GenerateStopCondition(I2C_TypeDef *I2Cx) -{ - SET_BIT(I2Cx->CR1, I2C_CR1_STOP); -} - -/** - * @brief Enable bit POS (master/host mode). - * @note In that case, the ACK bit controls the (N)ACK of the next byte received or the PEC bit indicates that the next byte in shift register is a PEC. - * @rmtoll CR1 POS LL_I2C_EnableBitPOS - * @param I2Cx I2C Instance. - * @retval None - */ -__STATIC_INLINE void LL_I2C_EnableBitPOS(I2C_TypeDef *I2Cx) -{ - SET_BIT(I2Cx->CR1, I2C_CR1_POS); -} - -/** - * @brief Disable bit POS (master/host mode). - * @note In that case, the ACK bit controls the (N)ACK of the current byte received or the PEC bit indicates that the current byte in shift register is a PEC. - * @rmtoll CR1 POS LL_I2C_DisableBitPOS - * @param I2Cx I2C Instance. - * @retval None - */ -__STATIC_INLINE void LL_I2C_DisableBitPOS(I2C_TypeDef *I2Cx) -{ - CLEAR_BIT(I2Cx->CR1, I2C_CR1_POS); -} - -/** - * @brief Check if bit POS is enabled or disabled. - * @rmtoll CR1 POS LL_I2C_IsEnabledBitPOS - * @param I2Cx I2C Instance. - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_I2C_IsEnabledBitPOS(I2C_TypeDef *I2Cx) -{ - return (READ_BIT(I2Cx->CR1, I2C_CR1_POS) == (I2C_CR1_POS)); -} - -/** - * @brief Indicate the value of transfer direction. - * @note RESET: Bus is in read transfer (peripheral point of view). - * SET: Bus is in write transfer (peripheral point of view). - * @rmtoll SR2 TRA LL_I2C_GetTransferDirection - * @param I2Cx I2C Instance. - * @retval Returned value can be one of the following values: - * @arg @ref LL_I2C_DIRECTION_WRITE - * @arg @ref LL_I2C_DIRECTION_READ - */ -__STATIC_INLINE uint32_t LL_I2C_GetTransferDirection(I2C_TypeDef *I2Cx) -{ - return (uint32_t)(READ_BIT(I2Cx->SR2, I2C_SR2_TRA)); -} - -/** - * @brief Enable DMA last transfer. - * @note This action mean that next DMA EOT is the last transfer. - * @rmtoll CR2 LAST LL_I2C_EnableLastDMA - * @param I2Cx I2C Instance. - * @retval None - */ -__STATIC_INLINE void LL_I2C_EnableLastDMA(I2C_TypeDef *I2Cx) -{ - SET_BIT(I2Cx->CR2, I2C_CR2_LAST); -} - -/** - * @brief Disable DMA last transfer. - * @note This action mean that next DMA EOT is not the last transfer. - * @rmtoll CR2 LAST LL_I2C_DisableLastDMA - * @param I2Cx I2C Instance. - * @retval None - */ -__STATIC_INLINE void LL_I2C_DisableLastDMA(I2C_TypeDef *I2Cx) -{ - CLEAR_BIT(I2Cx->CR2, I2C_CR2_LAST); -} - -/** - * @brief Check if DMA last transfer is enabled or disabled. - * @rmtoll CR2 LAST LL_I2C_IsEnabledLastDMA - * @param I2Cx I2C Instance. - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_I2C_IsEnabledLastDMA(I2C_TypeDef *I2Cx) -{ - return (READ_BIT(I2Cx->CR2, I2C_CR2_LAST) == (I2C_CR2_LAST)); -} - -/** - * @brief Enable transfer or internal comparison of the SMBus Packet Error byte (transmission or reception mode). - * @note Macro @ref IS_SMBUS_ALL_INSTANCE(I2Cx) can be used to check whether or not - * SMBus feature is supported by the I2Cx Instance. - * @note This feature is cleared by hardware when the PEC byte is transferred or compared, - * or by a START or STOP condition, it is also cleared by software. - * @rmtoll CR1 PEC LL_I2C_EnableSMBusPECCompare - * @param I2Cx I2C Instance. - * @retval None - */ -__STATIC_INLINE void LL_I2C_EnableSMBusPECCompare(I2C_TypeDef *I2Cx) -{ - SET_BIT(I2Cx->CR1, I2C_CR1_PEC); -} - -/** - * @brief Disable transfer or internal comparison of the SMBus Packet Error byte (transmission or reception mode). - * @note Macro @ref IS_SMBUS_ALL_INSTANCE(I2Cx) can be used to check whether or not - * SMBus feature is supported by the I2Cx Instance. - * @rmtoll CR1 PEC LL_I2C_DisableSMBusPECCompare - * @param I2Cx I2C Instance. - * @retval None - */ -__STATIC_INLINE void LL_I2C_DisableSMBusPECCompare(I2C_TypeDef *I2Cx) -{ - CLEAR_BIT(I2Cx->CR1, I2C_CR1_PEC); -} - -/** - * @brief Check if the SMBus Packet Error byte transfer or internal comparison is requested or not. - * @note Macro @ref IS_SMBUS_ALL_INSTANCE(I2Cx) can be used to check whether or not - * SMBus feature is supported by the I2Cx Instance. - * @rmtoll CR1 PEC LL_I2C_IsEnabledSMBusPECCompare - * @param I2Cx I2C Instance. - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_I2C_IsEnabledSMBusPECCompare(I2C_TypeDef *I2Cx) -{ - return (READ_BIT(I2Cx->CR1, I2C_CR1_PEC) == (I2C_CR1_PEC)); -} - -/** - * @brief Get the SMBus Packet Error byte calculated. - * @note Macro @ref IS_SMBUS_ALL_INSTANCE(I2Cx) can be used to check whether or not - * SMBus feature is supported by the I2Cx Instance. - * @rmtoll SR2 PEC LL_I2C_GetSMBusPEC - * @param I2Cx I2C Instance. - * @retval Value between Min_Data=0x00 and Max_Data=0xFF - */ -__STATIC_INLINE uint32_t LL_I2C_GetSMBusPEC(I2C_TypeDef *I2Cx) -{ - return (uint32_t)(READ_BIT(I2Cx->SR2, I2C_SR2_PEC) >> I2C_SR2_PEC_Pos); -} - -/** - * @brief Read Receive Data register. - * @rmtoll DR DR LL_I2C_ReceiveData8 - * @param I2Cx I2C Instance. - * @retval Value between Min_Data=0x0 and Max_Data=0xFF - */ -__STATIC_INLINE uint8_t LL_I2C_ReceiveData8(I2C_TypeDef *I2Cx) -{ - return (uint8_t)(READ_BIT(I2Cx->DR, I2C_DR_DR)); -} - -/** - * @brief Write in Transmit Data Register . - * @rmtoll DR DR LL_I2C_TransmitData8 - * @param I2Cx I2C Instance. - * @param Data Value between Min_Data=0x0 and Max_Data=0xFF - * @retval None - */ -__STATIC_INLINE void LL_I2C_TransmitData8(I2C_TypeDef *I2Cx, uint8_t Data) -{ - MODIFY_REG(I2Cx->DR, I2C_DR_DR, Data); -} - -/** - * @} - */ - -#if defined(USE_FULL_LL_DRIVER) -/** @defgroup I2C_LL_EF_Init Initialization and de-initialization functions - * @{ - */ - -uint32_t LL_I2C_Init(I2C_TypeDef *I2Cx, LL_I2C_InitTypeDef *I2C_InitStruct); -uint32_t LL_I2C_DeInit(I2C_TypeDef *I2Cx); -void LL_I2C_StructInit(LL_I2C_InitTypeDef *I2C_InitStruct); - - -/** - * @} - */ -#endif /* USE_FULL_LL_DRIVER */ - -/** - * @} - */ - -/** - * @} - */ - -#endif /* I2C1 || I2C2 */ - -/** - * @} - */ - -#ifdef __cplusplus -} -#endif - -#endif /* __STM32F1xx_LL_I2C_H */ - -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_iwdg.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_iwdg.h deleted file mode 100644 index 2605939096b..00000000000 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_iwdg.h +++ /dev/null @@ -1,329 +0,0 @@ -/** - ****************************************************************************** - * @file stm32f1xx_ll_iwdg.h - * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 - * @brief Header file of IWDG LL module. - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2016 STMicroelectronics

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ - -/* Define to prevent recursive inclusion -------------------------------------*/ -#ifndef __STM32F1xx_LL_IWDG_H -#define __STM32F1xx_LL_IWDG_H - -#ifdef __cplusplus -extern "C" { -#endif - -/* Includes ------------------------------------------------------------------*/ -#include "stm32f1xx.h" - -/** @addtogroup STM32F1xx_LL_Driver - * @{ - */ - -#if defined(IWDG) - -/** @defgroup IWDG_LL IWDG - * @{ - */ - -/* Private types -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ - -/* Private constants ---------------------------------------------------------*/ -/** @defgroup IWDG_LL_Private_Constants IWDG Private Constants - * @{ - */ - -#define LL_IWDG_KEY_RELOAD 0x0000AAAAU /*!< IWDG Reload Counter Enable */ -#define LL_IWDG_KEY_ENABLE 0x0000CCCCU /*!< IWDG Peripheral Enable */ -#define LL_IWDG_KEY_WR_ACCESS_ENABLE 0x00005555U /*!< IWDG KR Write Access Enable */ -#define LL_IWDG_KEY_WR_ACCESS_DISABLE 0x00000000U /*!< IWDG KR Write Access Disable */ - -/** - * @} - */ - -/* Private macros ------------------------------------------------------------*/ - -/* Exported types ------------------------------------------------------------*/ -/* Exported constants --------------------------------------------------------*/ -/** @defgroup IWDG_LL_Exported_Constants IWDG Exported Constants - * @{ - */ - -/** @defgroup IWDG_LL_EC_GET_FLAG Get Flags Defines - * @brief Flags defines which can be used with LL_IWDG_ReadReg function - * @{ - */ -#define LL_IWDG_SR_PVU IWDG_SR_PVU /*!< Watchdog prescaler value update */ -#define LL_IWDG_SR_RVU IWDG_SR_RVU /*!< Watchdog counter reload value update */ - -/** - * @} - */ - -/** @defgroup IWDG_LL_EC_PRESCALER Prescaler Divider - * @{ - */ -#define LL_IWDG_PRESCALER_4 0x00000000U /*!< Divider by 4 */ -#define LL_IWDG_PRESCALER_8 (IWDG_PR_PR_0) /*!< Divider by 8 */ -#define LL_IWDG_PRESCALER_16 (IWDG_PR_PR_1) /*!< Divider by 16 */ -#define LL_IWDG_PRESCALER_32 (IWDG_PR_PR_1 | IWDG_PR_PR_0) /*!< Divider by 32 */ -#define LL_IWDG_PRESCALER_64 (IWDG_PR_PR_2) /*!< Divider by 64 */ -#define LL_IWDG_PRESCALER_128 (IWDG_PR_PR_2 | IWDG_PR_PR_0) /*!< Divider by 128 */ -#define LL_IWDG_PRESCALER_256 (IWDG_PR_PR_2 | IWDG_PR_PR_1) /*!< Divider by 256 */ -/** - * @} - */ - -/** - * @} - */ - -/* Exported macro ------------------------------------------------------------*/ -/** @defgroup IWDG_LL_Exported_Macros IWDG Exported Macros - * @{ - */ - -/** @defgroup IWDG_LL_EM_WRITE_READ Common Write and read registers Macros - * @{ - */ - -/** - * @brief Write a value in IWDG register - * @param __INSTANCE__ IWDG Instance - * @param __REG__ Register to be written - * @param __VALUE__ Value to be written in the register - * @retval None - */ -#define LL_IWDG_WriteReg(__INSTANCE__, __REG__, __VALUE__) WRITE_REG(__INSTANCE__->__REG__, (__VALUE__)) - -/** - * @brief Read a value in IWDG register - * @param __INSTANCE__ IWDG Instance - * @param __REG__ Register to be read - * @retval Register value - */ -#define LL_IWDG_ReadReg(__INSTANCE__, __REG__) READ_REG(__INSTANCE__->__REG__) -/** - * @} - */ - -/** - * @} - */ - - -/* Exported functions --------------------------------------------------------*/ -/** @defgroup IWDG_LL_Exported_Functions IWDG Exported Functions - * @{ - */ -/** @defgroup IWDG_LL_EF_Configuration Configuration - * @{ - */ - -/** - * @brief Start the Independent Watchdog - * @note Except if the hardware watchdog option is selected - * @rmtoll KR KEY LL_IWDG_Enable - * @param IWDGx IWDG Instance - * @retval None - */ -__STATIC_INLINE void LL_IWDG_Enable(IWDG_TypeDef *IWDGx) -{ - WRITE_REG(IWDG->KR, LL_IWDG_KEY_ENABLE); -} - -/** - * @brief Reloads IWDG counter with value defined in the reload register - * @rmtoll KR KEY LL_IWDG_ReloadCounter - * @param IWDGx IWDG Instance - * @retval None - */ -__STATIC_INLINE void LL_IWDG_ReloadCounter(IWDG_TypeDef *IWDGx) -{ - WRITE_REG(IWDG->KR, LL_IWDG_KEY_RELOAD); -} - -/** - * @brief Enable write access to IWDG_PR, IWDG_RLR and IWDG_WINR registers - * @rmtoll KR KEY LL_IWDG_EnableWriteAccess - * @param IWDGx IWDG Instance - * @retval None - */ -__STATIC_INLINE void LL_IWDG_EnableWriteAccess(IWDG_TypeDef *IWDGx) -{ - WRITE_REG(IWDG->KR, LL_IWDG_KEY_WR_ACCESS_ENABLE); -} - -/** - * @brief Disable write access to IWDG_PR, IWDG_RLR and IWDG_WINR registers - * @rmtoll KR KEY LL_IWDG_DisableWriteAccess - * @param IWDGx IWDG Instance - * @retval None - */ -__STATIC_INLINE void LL_IWDG_DisableWriteAccess(IWDG_TypeDef *IWDGx) -{ - WRITE_REG(IWDG->KR, LL_IWDG_KEY_WR_ACCESS_DISABLE); -} - -/** - * @brief Select the prescaler of the IWDG - * @rmtoll PR PR LL_IWDG_SetPrescaler - * @param IWDGx IWDG Instance - * @param Prescaler This parameter can be one of the following values: - * @arg @ref LL_IWDG_PRESCALER_4 - * @arg @ref LL_IWDG_PRESCALER_8 - * @arg @ref LL_IWDG_PRESCALER_16 - * @arg @ref LL_IWDG_PRESCALER_32 - * @arg @ref LL_IWDG_PRESCALER_64 - * @arg @ref LL_IWDG_PRESCALER_128 - * @arg @ref LL_IWDG_PRESCALER_256 - * @retval None - */ -__STATIC_INLINE void LL_IWDG_SetPrescaler(IWDG_TypeDef *IWDGx, uint32_t Prescaler) -{ - WRITE_REG(IWDGx->PR, IWDG_PR_PR & Prescaler); -} - -/** - * @brief Get the selected prescaler of the IWDG - * @rmtoll PR PR LL_IWDG_GetPrescaler - * @param IWDGx IWDG Instance - * @retval Returned value can be one of the following values: - * @arg @ref LL_IWDG_PRESCALER_4 - * @arg @ref LL_IWDG_PRESCALER_8 - * @arg @ref LL_IWDG_PRESCALER_16 - * @arg @ref LL_IWDG_PRESCALER_32 - * @arg @ref LL_IWDG_PRESCALER_64 - * @arg @ref LL_IWDG_PRESCALER_128 - * @arg @ref LL_IWDG_PRESCALER_256 - */ -__STATIC_INLINE uint32_t LL_IWDG_GetPrescaler(IWDG_TypeDef *IWDGx) -{ - return (uint32_t)(READ_REG(IWDGx->PR)); -} - -/** - * @brief Specify the IWDG down-counter reload value - * @rmtoll RLR RL LL_IWDG_SetReloadCounter - * @param IWDGx IWDG Instance - * @param Counter Value between Min_Data=0 and Max_Data=0x0FFF - * @retval None - */ -__STATIC_INLINE void LL_IWDG_SetReloadCounter(IWDG_TypeDef *IWDGx, uint32_t Counter) -{ - WRITE_REG(IWDGx->RLR, IWDG_RLR_RL & Counter); -} - -/** - * @brief Get the specified IWDG down-counter reload value - * @rmtoll RLR RL LL_IWDG_GetReloadCounter - * @param IWDGx IWDG Instance - * @retval Value between Min_Data=0 and Max_Data=0x0FFF - */ -__STATIC_INLINE uint32_t LL_IWDG_GetReloadCounter(IWDG_TypeDef *IWDGx) -{ - return (uint32_t)(READ_REG(IWDGx->RLR)); -} - - -/** - * @} - */ - -/** @defgroup IWDG_LL_EF_FLAG_Management FLAG_Management - * @{ - */ - -/** - * @brief Check if flag Prescaler Value Update is set or not - * @rmtoll SR PVU LL_IWDG_IsActiveFlag_PVU - * @param IWDGx IWDG Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_IWDG_IsActiveFlag_PVU(IWDG_TypeDef *IWDGx) -{ - return (READ_BIT(IWDGx->SR, IWDG_SR_PVU) == (IWDG_SR_PVU)); -} - -/** - * @brief Check if flag Reload Value Update is set or not - * @rmtoll SR RVU LL_IWDG_IsActiveFlag_RVU - * @param IWDGx IWDG Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_IWDG_IsActiveFlag_RVU(IWDG_TypeDef *IWDGx) -{ - return (READ_BIT(IWDGx->SR, IWDG_SR_RVU) == (IWDG_SR_RVU)); -} - - -/** - * @brief Check if all flags Prescaler, Reload & Window Value Update are reset or not - * @rmtoll SR PVU LL_IWDG_IsReady\n - * SR RVU LL_IWDG_IsReady - * @param IWDGx IWDG Instance - * @retval State of bits (1 or 0). - */ -__STATIC_INLINE uint32_t LL_IWDG_IsReady(IWDG_TypeDef *IWDGx) -{ - return (READ_BIT(IWDGx->SR, IWDG_SR_PVU | IWDG_SR_RVU) == 0U); -} - -/** - * @} - */ - - -/** - * @} - */ - -/** - * @} - */ - -#endif /* IWDG) */ - -/** - * @} - */ - -#ifdef __cplusplus -} -#endif - -#endif /* __STM32F1xx_LL_IWDG_H */ - -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_pwr.c b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_pwr.c index 947d47ac436..af58b118cd1 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_pwr.c +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_pwr.c @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_ll_pwr.c * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version $VERSION$ + * @date $DATE$ * @brief PWR LL module driver. ****************************************************************************** * @attention diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_pwr.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_pwr.h index a1ad470b15a..4c5c3455dc2 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_pwr.h +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_pwr.h @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_ll_pwr.h * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version $VERSION$ + * @date $DATE$ * @brief Header file of PWR LL module. ****************************************************************************** * @attention @@ -93,7 +93,7 @@ extern "C" { * @{ */ #define LL_PWR_MODE_STOP_MAINREGU 0x00000000U /*!< Enter Stop mode when the CPU enters deepsleep */ -#define LL_PWR_MODE_STOP_LPREGU (PWR_CR_LPDS) /*!< Enter Stop mode (with low power Regulator ON) when the CPU enters deepsleep */ +#define LL_PWR_MODE_STOP_LPREGU (PWR_CR_LPDS) /*!< Enter Stop mode (ith low power regulator ON) when the CPU enters deepsleep */ #define LL_PWR_MODE_STANDBY (PWR_CR_PDDS) /*!< Enter Standby mode when the CPU enters deepsleep */ /** * @} @@ -102,8 +102,8 @@ extern "C" { /** @defgroup PWR_LL_EC_REGU_MODE_DS_MODE Regulator Mode In Deep Sleep Mode * @{ */ -#define LL_PWR_REGU_DSMODE_MAIN 0x00000000U /*!< Voltage Regulator in main mode during deepsleep mode */ -#define LL_PWR_REGU_DSMODE_LOW_POWER (PWR_CR_LPDS) /*!< Voltage Regulator in low-power mode during deepsleep mode */ +#define LL_PWR_REGU_DSMODE_MAIN 0x00000000U /*!< Voltage regulator in main mode during deepsleep mode */ +#define LL_PWR_REGU_DSMODE_LOW_POWER (PWR_CR_LPDS) /*!< Voltage regulator in low-power mode during deepsleep mode */ /** * @} */ @@ -125,7 +125,7 @@ extern "C" { /** @defgroup PWR_LL_EC_WAKEUP_PIN Wakeup Pins * @{ */ -#define LL_PWR_WAKEUP_PIN1 (PWR_CSR_EWUP) /*!< WKUP pin 1 : PA0 */ +#define LL_PWR_WAKEUP_PIN1 (PWR_CSR_EWUP) /*!< WKUP pin 1 : PA0 */ /** * @} */ @@ -206,7 +206,7 @@ __STATIC_INLINE uint32_t LL_PWR_IsEnabledBkUpAccess(void) } /** - * @brief Set voltage Regulator mode during deep sleep mode + * @brief Set voltage regulator mode during deep sleep mode * @rmtoll CR LPDS LL_PWR_SetRegulModeDS * @param RegulMode This parameter can be one of the following values: * @arg @ref LL_PWR_REGU_DSMODE_MAIN @@ -219,7 +219,7 @@ __STATIC_INLINE void LL_PWR_SetRegulModeDS(uint32_t RegulMode) } /** - * @brief Get voltage Regulator mode during deep sleep mode + * @brief Get voltage regulator mode during deep sleep mode * @rmtoll CR LPDS LL_PWR_GetRegulModeDS * @retval Returned value can be one of the following values: * @arg @ref LL_PWR_REGU_DSMODE_MAIN @@ -231,7 +231,7 @@ __STATIC_INLINE uint32_t LL_PWR_GetRegulModeDS(void) } /** - * @brief Set Power Down mode when CPU enters deepsleep + * @brief Set power down mode when CPU enters deepsleep * @rmtoll CR PDDS LL_PWR_SetPowerMode\n * @rmtoll CR LPDS LL_PWR_SetPowerMode * @param PDMode This parameter can be one of the following values: @@ -246,7 +246,7 @@ __STATIC_INLINE void LL_PWR_SetPowerMode(uint32_t PDMode) } /** - * @brief Get Power Down mode when CPU enters deepsleep + * @brief Get power down mode when CPU enters deepsleep * @rmtoll CR PDDS LL_PWR_GetPowerMode\n * @rmtoll CR LPDS LL_PWR_GetPowerMode * @retval Returned value can be one of the following values: @@ -420,11 +420,6 @@ __STATIC_INLINE void LL_PWR_ClearFlag_WU(void) { SET_BIT(PWR->CR, PWR_CR_CWUF); } - -/** - * @} - */ - #if defined(USE_FULL_LL_DRIVER) /** @defgroup PWR_LL_EF_Init De-initialization function * @{ @@ -443,6 +438,10 @@ ErrorStatus LL_PWR_DeInit(void); * @} */ +/** + * @} + */ + #endif /* defined(PWR) */ /** diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_rcc.c b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_rcc.c index d931ff9b677..e13376a66f9 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_rcc.c +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_rcc.c @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_ll_rcc.c * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version $VERSION$ + * @date $DATE$ * @brief RCC LL module driver. ****************************************************************************** * @attention @@ -55,6 +55,7 @@ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ + /* Private constants ---------------------------------------------------------*/ /* Private macros ------------------------------------------------------------*/ /** @addtogroup RCC_LL_Private_Macros @@ -70,6 +71,7 @@ #endif /* USB */ #define IS_LL_RCC_ADC_CLKSOURCE(__VALUE__) (((__VALUE__) == LL_RCC_ADC_CLKSOURCE)) + /** * @} */ @@ -93,6 +95,7 @@ uint32_t RCC_PLL2_GetFreqClockFreq(void); * @} */ + /* Exported functions --------------------------------------------------------*/ /** @addtogroup RCC_LL_Exported_Functions * @{ @@ -160,13 +163,13 @@ ErrorStatus LL_RCC_DeInit(void) /* Reset PLL3ON bit */ CLEAR_BIT(vl_mask, RCC_CR_PLL3ON); #endif /* RCC_CR_PLL3ON */ - + LL_RCC_WriteReg(CR, vl_mask); /* Set HSITRIM bits to the reset value */ LL_RCC_HSI_SetCalibTrimming(0x10U); -#if defined(RCC_CFGR2_PREDIV1) +#if defined(RCC_PREDIV1_DIV_2_16_SUPPORT) /* Reset CFGR2 register */ vl_mask = 0x00000000U; @@ -181,7 +184,7 @@ ErrorStatus LL_RCC_DeInit(void) #endif /* RCC_PLLI2S_SUPPORT */ LL_RCC_WriteReg(CFGR2, vl_mask); -#endif /* RCC_CFGR2_PREDIV1 */ +#endif /* RCC_PREDIV1_DIV_2_16_SUPPORT */ /* Disable all interrupts */ LL_RCC_WriteReg(CIR, 0x00000000U); @@ -242,7 +245,7 @@ void LL_RCC_GetSystemClocksFreq(LL_RCC_ClocksTypeDef *RCC_Clocks) * @arg @ref LL_RCC_I2S2_CLKSOURCE * @arg @ref LL_RCC_I2S3_CLKSOURCE * @retval I2S clock frequency (in Hz) - */ + * @arg @ref LL_RCC_PERIPH_FREQUENCY_NA indicates that external clock is used */ uint32_t LL_RCC_GetI2SClockFreq(uint32_t I2SxSource) { uint32_t i2s_frequency = LL_RCC_PERIPH_FREQUENCY_NO; @@ -261,14 +264,13 @@ uint32_t LL_RCC_GetI2SClockFreq(uint32_t I2SxSource) case LL_RCC_I2S2_CLKSOURCE_PLLI2S_VCO: /*!< PLLI2S oscillator clock selected as I2S clock source */ case LL_RCC_I2S3_CLKSOURCE_PLLI2S_VCO: default: - i2s_frequency = RCC_PLLI2S_GetFreqDomain_I2S() * 2U; + i2s_frequency = RCC_PLLI2S_GetFreqDomain_I2S() * 2; break; } return i2s_frequency; } #endif /* RCC_CFGR2_I2S2SRC */ - #if defined(USB) || defined(USB_OTG_FS) /** * @brief Return USBx clock frequency @@ -276,6 +278,7 @@ uint32_t LL_RCC_GetI2SClockFreq(uint32_t I2SxSource) * @arg @ref LL_RCC_USB_CLKSOURCE * @retval USB clock frequency (in Hz) * @arg @ref LL_RCC_PERIPH_FREQUENCY_NO indicates that oscillator (HSI), HSE or PLL is not ready + * @arg @ref LL_RCC_PERIPH_FREQUENCY_NA indicates that no clock source selected */ uint32_t LL_RCC_GetUSBClockFreq(uint32_t USBxSource) { @@ -299,7 +302,7 @@ uint32_t LL_RCC_GetUSBClockFreq(uint32_t USBxSource) default: if (LL_RCC_PLL_IsReady()) { - usb_frequency = (RCC_PLL_GetFreqDomain_SYS() * 3U) / 2U; + usb_frequency = (RCC_PLL_GetFreqDomain_SYS() * 3) / 2; } break; #endif /* RCC_CFGR_USBPRE */ @@ -316,11 +319,11 @@ uint32_t LL_RCC_GetUSBClockFreq(uint32_t USBxSource) /* USBCLK = PLLVCO/3 = (2 x PLLCLK) / 3 */ - case LL_RCC_USB_CLKSOURCE_PLL_DIV_3: /* PLL clock divided by 3 used as USB clock source */ + case LL_RCC_USB_CLKSOURCE_PLL_DIV_3: /* PLL clock divided by 1.5 used as USB clock source */ default: if (LL_RCC_PLL_IsReady()) { - usb_frequency = (RCC_PLL_GetFreqDomain_SYS() * 2U) / 3U; + usb_frequency = (RCC_PLL_GetFreqDomain_SYS() * 2) / 3; } break; #endif /* RCC_CFGR_OTGFSPRE */ @@ -335,15 +338,16 @@ uint32_t LL_RCC_GetUSBClockFreq(uint32_t USBxSource) * @param ADCxSource This parameter can be one of the following values: * @arg @ref LL_RCC_ADC_CLKSOURCE * @retval ADC clock frequency (in Hz) + * - @ref LL_RCC_PERIPH_FREQUENCY_NO indicates that oscillator (HSI), HSE or PLL is not ready */ uint32_t LL_RCC_GetADCClockFreq(uint32_t ADCxSource) { uint32_t adc_prescaler = 0U; - uint32_t adc_frequency = 0U; + uint32_t adc_frequency = LL_RCC_PERIPH_FREQUENCY_NO; /* Check parameter */ assert_param(IS_LL_RCC_ADC_CLKSOURCE(ADCxSource)); - + /* Get ADC prescaler */ adc_prescaler = LL_RCC_GetADCClockSource(ADCxSource); @@ -446,21 +450,21 @@ uint32_t RCC_PLL_GetFreqDomain_SYS(void) switch (pllsource) { case LL_RCC_PLLSOURCE_HSI_DIV_2: /* HSI used as PLL clock source */ - pllinputfreq = HSI_VALUE / 2U; + pllinputfreq = HSI_VALUE / 2; break; case LL_RCC_PLLSOURCE_HSE: /* HSE used as PLL clock source */ - pllinputfreq = HSE_VALUE / (LL_RCC_PLL_GetPrediv() + 1U); + pllinputfreq = HSE_VALUE / (LL_RCC_PLL_GetPrediv() + 1); break; #if defined(RCC_PLL2_SUPPORT) case LL_RCC_PLLSOURCE_PLL2: /* PLL2 used as PLL clock source */ - pllinputfreq = RCC_PLL2_GetFreqClockFreq() / (LL_RCC_PLL_GetPrediv() + 1U); + pllinputfreq = RCC_PLL2_GetFreqClockFreq() / (LL_RCC_PLL_GetPrediv() + 1); break; #endif /* RCC_PLL2_SUPPORT */ default: - pllinputfreq = HSI_VALUE / 2U; + pllinputfreq = HSI_VALUE / 2; break; } return __LL_RCC_CALC_PLLCLK_FREQ(pllinputfreq, LL_RCC_PLL_GetMultiplicator()); diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_rcc.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_rcc.h index c87d5652063..de79141d041 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_rcc.h +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_rcc.h @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_ll_rcc.h * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version $VERSION$ + * @date $DATE$ * @brief Header file of RCC LL module. ****************************************************************************** * @attention @@ -58,7 +58,54 @@ extern "C" { /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ +/** @defgroup RCC_LL_Private_Variables RCC Private Variables + * @{ + */ + +/** + * @} + */ + /* Private constants ---------------------------------------------------------*/ +/** @defgroup RCC_LL_Private_Constants RCC Private Constants + * @{ + */ +/* Define used for feature activation */ +#if defined(RCC_CFGR2_PREDIV2) +#define RCC_PREDIV2_SUPPORT +#endif /* RCC_CFGR2_PREDIV2 */ + +#if defined(RCC_CR_PLL3ON) +#define RCC_PLLI2S_SUPPORT +#endif /* RCC_CR_PLL3ON */ + +#if defined(RCC_CR_PLL2ON) +#define RCC_PLL2_SUPPORT +#endif /* RCC_CR_PLL2ON */ + +#if defined(RCC_CFGR2_PREDIV1SRC) +#define RCC_SRC_PREDIV1_SUPPORT +#endif /* RCC_CFGR2_PREDIV1SRC */ + +#if defined(RCC_CFGR2_PREDIV1) +#define RCC_PREDIV1_DIV_2_16_SUPPORT +#endif /* RCC_CFGR2_PREDIV1 */ + + +/* Defines used for the bit position in the register and perform offsets*/ +#define RCC_POSITION_HPRE (uint32_t)POSITION_VAL(RCC_CFGR_HPRE) /*!< field position in register RCC_CFGR */ +#define RCC_POSITION_PPRE1 (uint32_t)POSITION_VAL(RCC_CFGR_PPRE1) /*!< field position in register RCC_CFGR */ +#define RCC_POSITION_PPRE2 (uint32_t)POSITION_VAL(RCC_CFGR_PPRE2) /*!< field position in register RCC_CFGR */ +#define RCC_POSITION_HSICAL (uint32_t)POSITION_VAL(RCC_CR_HSICAL) /*!< field position in register RCC_CR */ +#define RCC_POSITION_HSITRIM (uint32_t)POSITION_VAL(RCC_CR_HSITRIM) /*!< field position in register RCC_CR */ +#define RCC_POSITION_PLLMUL (uint32_t)POSITION_VAL(RCC_CFGR_PLLMULL) /*!< field position in register RCC_CFGR */ +#define RCC_POSITION_I2S2SRC 17U /*!< field position in register RCC_CFGR2 */ +#define RCC_POSITION_I2S3SRC 18U /*!< field position in register RCC_CFGR2 */ + +/** + * @} + */ + /* Private macros ------------------------------------------------------------*/ #if defined(USE_FULL_LL_DRIVER) /** @defgroup RCC_LL_Private_Macros RCC Private Macros @@ -110,19 +157,19 @@ typedef struct * @{ */ #if !defined (HSE_VALUE) -#define HSE_VALUE 8000000U /*!< Value of the HSE oscillator in Hz */ +#define HSE_VALUE ((uint32_t)8000000U) /*!< Value of the HSE oscillator in Hz */ #endif /* HSE_VALUE */ #if !defined (HSI_VALUE) -#define HSI_VALUE 8000000U /*!< Value of the HSI oscillator in Hz */ +#define HSI_VALUE ((uint32_t)8000000U) /*!< Value of the HSI oscillator in Hz */ #endif /* HSI_VALUE */ #if !defined (LSE_VALUE) -#define LSE_VALUE 32768U /*!< Value of the LSE oscillator in Hz */ +#define LSE_VALUE ((uint32_t)32768U) /*!< Value of the LSE oscillator in Hz */ #endif /* LSE_VALUE */ #if !defined (LSI_VALUE) -#define LSI_VALUE 32000U /*!< Value of the LSI oscillator in Hz */ +#define LSI_VALUE ((uint32_t)32000U) /*!< Value of the LSI oscillator in Hz */ #endif /* LSI_VALUE */ /** * @} @@ -155,13 +202,13 @@ typedef struct #define LL_RCC_CIR_PLLRDYF RCC_CIR_PLLRDYF /*!< PLL Ready Interrupt flag */ #define LL_RCC_CIR_PLL3RDYF RCC_CIR_PLL3RDYF /*!< PLL3(PLLI2S) Ready Interrupt flag */ #define LL_RCC_CIR_PLL2RDYF RCC_CIR_PLL2RDYF /*!< PLL2 Ready Interrupt flag */ -#define LL_RCC_CIR_CSSF RCC_CIR_CSSF /*!< Clock Security System Interrupt flag */ -#define LL_RCC_CSR_PINRSTF RCC_CSR_PINRSTF /*!< PIN reset flag */ -#define LL_RCC_CSR_PORRSTF RCC_CSR_PORRSTF /*!< POR/PDR reset flag */ -#define LL_RCC_CSR_SFTRSTF RCC_CSR_SFTRSTF /*!< Software Reset flag */ -#define LL_RCC_CSR_IWDGRSTF RCC_CSR_IWDGRSTF /*!< Independent Watchdog reset flag */ -#define LL_RCC_CSR_WWDGRSTF RCC_CSR_WWDGRSTF /*!< Window watchdog reset flag */ -#define LL_RCC_CSR_LPWRRSTF RCC_CSR_LPWRRSTF /*!< Low-Power reset flag */ +#define LL_RCC_CIR_CSSF RCC_CIR_CSSF /*!< Clock Security System Interrupt flag */ +#define LL_RCC_CSR_PINRSTF RCC_CSR_PINRSTF /*!< PIN reset flag */ +#define LL_RCC_CSR_PORRSTF RCC_CSR_PORRSTF /*!< POR/PDR reset flag */ +#define LL_RCC_CSR_SFTRSTF RCC_CSR_SFTRSTF /*!< Software Reset flag */ +#define LL_RCC_CSR_IWDGRSTF RCC_CSR_IWDGRSTF /*!< Independent Watchdog reset flag */ +#define LL_RCC_CSR_WWDGRSTF RCC_CSR_WWDGRSTF /*!< Window watchdog reset flag */ +#define LL_RCC_CSR_LPWRRSTF RCC_CSR_LPWRRSTF /*!< Low-Power reset flag */ /** * @} */ @@ -175,13 +222,13 @@ typedef struct #define LL_RCC_CIR_HSIRDYIE RCC_CIR_HSIRDYIE /*!< HSI Ready Interrupt Enable */ #define LL_RCC_CIR_HSERDYIE RCC_CIR_HSERDYIE /*!< HSE Ready Interrupt Enable */ #define LL_RCC_CIR_PLLRDYIE RCC_CIR_PLLRDYIE /*!< PLL Ready Interrupt Enable */ -#define LL_RCC_CIR_PLL3RDYIE RCC_CIR_PLL3RDYIE /*!< PLL3(PLLI2S) Ready Interrupt Enable */ -#define LL_RCC_CIR_PLL2RDYIE RCC_CIR_PLL2RDYIE /*!< PLL2 Ready Interrupt Enable */ +#define LL_RCC_CIR_PLL3RDYIE RCC_CIR_PLL3RDYIE /*!< PLL3(PLLI2S) Ready Interrupt Enable */ +#define LL_RCC_CIR_PLL2RDYIE RCC_CIR_PLL2RDYIE /*!< PLL2 Ready Interrupt Enable */ /** * @} */ -#if defined(RCC_CFGR2_PREDIV2) +#if defined(RCC_PREDIV2_SUPPORT) /** @defgroup RCC_LL_EC_HSE_PREDIV2_DIV HSE PREDIV2 Division factor * @{ */ @@ -205,7 +252,7 @@ typedef struct * @} */ -#endif /* RCC_CFGR2_PREDIV2 */ +#endif /* RCC_PREDIV2_SUPPORT */ /** @defgroup RCC_LL_EC_SYS_CLKSOURCE System clock switch * @{ @@ -285,7 +332,7 @@ typedef struct #define LL_RCC_MCO1SOURCE_EXT_HSE RCC_CFGR_MCOSEL_EXT_HSE /*!< XT1 external 3-25 MHz oscillator clock selected as MCO source */ #endif /* RCC_CFGR_MCOSEL_EXT_HSE */ #if defined(RCC_CFGR_MCOSEL_PLL3CLK) -#define LL_RCC_MCO1SOURCE_PLLI2SCLK RCC_CFGR_MCOSEL_PLL3CLK /*!< PLLI2S clock selected as MCO source */ +#define LL_RCC_MCO1SOURCE_PLLI2SCLK RCC_CFGR_MCOSEL_PLL3CLK /*!< PLLI2S clock selected as MCO source */ #endif /* RCC_CFGR_MCOSEL_PLL3CLK */ /** * @} @@ -295,8 +342,8 @@ typedef struct /** @defgroup RCC_LL_EC_PERIPH_FREQUENCY Peripheral clock frequency * @{ */ -#define LL_RCC_PERIPH_FREQUENCY_NO 0x00000000U /*!< No clock enabled for the peripheral */ -#define LL_RCC_PERIPH_FREQUENCY_NA 0xFFFFFFFFU /*!< Frequency cannot be provided as external clock */ +#define LL_RCC_PERIPH_FREQUENCY_NO (uint32_t)0x00000000U /*!< No clock enabled for the peripheral */ +#define LL_RCC_PERIPH_FREQUENCY_NA (uint32_t)0xFFFFFFFFU /*!< Frequency cannot be provided as external clock */ /** * @} */ @@ -306,13 +353,14 @@ typedef struct /** @defgroup RCC_LL_EC_I2S2CLKSOURCE Peripheral I2S clock source selection * @{ */ -#define LL_RCC_I2S2_CLKSOURCE_SYSCLK RCC_CFGR2_I2S2SRC /*!< System clock (SYSCLK) selected as I2S2 clock entry */ -#define LL_RCC_I2S2_CLKSOURCE_PLLI2S_VCO (uint32_t)(RCC_CFGR2_I2S2SRC | (RCC_CFGR2_I2S2SRC >> 16U)) /*!< PLLI2S VCO clock selected as I2S2 clock entry */ -#define LL_RCC_I2S3_CLKSOURCE_SYSCLK RCC_CFGR2_I2S3SRC /*!< System clock (SYSCLK) selected as I2S3 clock entry */ -#define LL_RCC_I2S3_CLKSOURCE_PLLI2S_VCO (uint32_t)(RCC_CFGR2_I2S3SRC | (RCC_CFGR2_I2S3SRC >> 16U)) /*!< PLLI2S VCO clock selected as I2S3 clock entry */ +#define LL_RCC_I2S2_CLKSOURCE_SYSCLK (uint32_t)(RCC_CFGR2_I2S2SRC | (0x00000000 >> 16)) /*!< System clock (SYSCLK) selected as I2S2 clock entry */ +#define LL_RCC_I2S2_CLKSOURCE_PLLI2S_VCO (uint32_t)(RCC_CFGR2_I2S2SRC | (RCC_CFGR2_I2S2SRC >> 16)) /*!< PLLI2S VCO clock selected as I2S2 clock entry */ +#define LL_RCC_I2S3_CLKSOURCE_SYSCLK (uint32_t)(RCC_CFGR2_I2S3SRC | (0x00000000 >> 16)) /*!< System clock (SYSCLK) selected as I2S3 clock entry */ +#define LL_RCC_I2S3_CLKSOURCE_PLLI2S_VCO (uint32_t)(RCC_CFGR2_I2S3SRC | (RCC_CFGR2_I2S3SRC >> 16)) /*!< PLLI2S VCO clock selected as I2S3 clock entry */ /** * @} */ + #endif /* RCC_CFGR2_I2S2SRC */ #if defined(USB_OTG_FS) || defined(USB) @@ -320,16 +368,17 @@ typedef struct * @{ */ #if defined(RCC_CFGR_USBPRE) -#define LL_RCC_USB_CLKSOURCE_PLL RCC_CFGR_USBPRE /*!< PLL clock is not divided */ -#define LL_RCC_USB_CLKSOURCE_PLL_DIV_1_5 0x00000000U /*!< PLL clock is divided by 1.5 */ -#endif /*RCC_CFGR_USBPRE*/ -#if defined(RCC_CFGR_OTGFSPRE) -#define LL_RCC_USB_CLKSOURCE_PLL_DIV_2 RCC_CFGR_OTGFSPRE /*!< PLL clock is divided by 2 */ -#define LL_RCC_USB_CLKSOURCE_PLL_DIV_3 0x00000000U /*!< PLL clock is divided by 3 */ +#define LL_RCC_USB_CLKSOURCE_PLL RCC_CFGR_USBPRE /*!< PLL clock is not divided */ +#define LL_RCC_USB_CLKSOURCE_PLL_DIV_1_5 ((uint32_t)0x00000000) /*!< PLL clock is divided by 1.5 */ +#endif /*RCC_CFGR_USBPRE*/ +#if defined(RCC_CFGR_OTGFSPRE) +#define LL_RCC_USB_CLKSOURCE_PLL_DIV_2 RCC_CFGR_OTGFSPRE /*!< PLL clock is divided by 2 */ +#define LL_RCC_USB_CLKSOURCE_PLL_DIV_3 ((uint32_t)0x00000000) /*!< PLL clock is divided by 3 */ #endif /*RCC_CFGR_OTGFSPRE*/ /** * @} */ + #endif /* USB_OTG_FS || USB */ /** @defgroup RCC_LL_EC_ADC_CLKSOURCE_PCLK2 Peripheral ADC clock source selection @@ -359,7 +408,7 @@ typedef struct /** @defgroup RCC_LL_EC_USB Peripheral USB get clock source * @{ */ -#define LL_RCC_USB_CLKSOURCE 0x00400000U /*!< USB Clock source selection */ +#define LL_RCC_USB_CLKSOURCE ((uint32_t)0x00400000) /*!< USB Clock source selection */ /** * @} */ @@ -377,10 +426,10 @@ typedef struct /** @defgroup RCC_LL_EC_RTC_CLKSOURCE RTC clock source selection * @{ */ -#define LL_RCC_RTC_CLKSOURCE_NONE 0x00000000U /*!< No clock used as RTC clock */ +#define LL_RCC_RTC_CLKSOURCE_NONE (uint32_t)0x00000000U /*!< No clock used as RTC clock */ #define LL_RCC_RTC_CLKSOURCE_LSE RCC_BDCR_RTCSEL_0 /*!< LSE oscillator clock used as RTC clock */ #define LL_RCC_RTC_CLKSOURCE_LSI RCC_BDCR_RTCSEL_1 /*!< LSI oscillator clock used as RTC clock */ -#define LL_RCC_RTC_CLKSOURCE_HSE_DIV128 RCC_BDCR_RTCSEL /*!< HSE oscillator clock divided by 128 used as RTC clock */ +#define LL_RCC_RTC_CLKSOURCE_HSE_DIV128 RCC_BDCR_RTCSEL /*!< HSE oscillator clock divided by 128 used as RTC clock */ /** * @} */ @@ -418,14 +467,14 @@ typedef struct /** @defgroup RCC_LL_EC_PLLSOURCE PLL SOURCE * @{ */ -#define LL_RCC_PLLSOURCE_HSI_DIV_2 0x00000000U /*!< HSI clock divided by 2 selected as PLL entry clock source */ -#define LL_RCC_PLLSOURCE_HSE RCC_CFGR_PLLSRC /*!< HSE/PREDIV1 clock selected as PLL entry clock source */ -#if defined(RCC_CFGR2_PREDIV1SRC) -#define LL_RCC_PLLSOURCE_PLL2 (RCC_CFGR_PLLSRC | RCC_CFGR2_PREDIV1SRC << 4U) /*!< PLL2/PREDIV1 clock selected as PLL entry clock source */ -#endif /*RCC_CFGR2_PREDIV1SRC*/ +#define LL_RCC_PLLSOURCE_HSI_DIV_2 ((uint32_t)0x00000000U) /*!< HSI clock divided by 2 selected as PLL entry clock source */ +#define LL_RCC_PLLSOURCE_HSE RCC_CFGR_PLLSRC /*!< HSE/PREDIV1 clock selected as PLL entry clock source */ +#if defined(RCC_SRC_PREDIV1_SUPPORT) +#define LL_RCC_PLLSOURCE_PLL2 (RCC_CFGR_PLLSRC | RCC_CFGR2_PREDIV1SRC << 4) /*!< PLL2/PREDIV1 clock selected as PLL entry clock source */ +#endif /*RCC_SRC_PREDIV1_SUPPORT*/ -#define LL_RCC_PLLSOURCE_HSE_DIV_1 RCC_CFGR_PLLSRC /*!< HSE clock selected as PLL entry clock source */ -#if defined(RCC_CFGR2_PREDIV1) +#define LL_RCC_PLLSOURCE_HSE_DIV_1 RCC_CFGR_PLLSRC /*!< HSE clock selected as PLL entry clock source */ +#if defined(RCC_PREDIV1_DIV_2_16_SUPPORT) #define LL_RCC_PLLSOURCE_HSE_DIV_2 (RCC_CFGR_PLLSRC | RCC_CFGR2_PREDIV1_DIV2) /*!< HSE/2 clock selected as PLL entry clock source */ #define LL_RCC_PLLSOURCE_HSE_DIV_3 (RCC_CFGR_PLLSRC | RCC_CFGR2_PREDIV1_DIV3) /*!< HSE/3 clock selected as PLL entry clock source */ #define LL_RCC_PLLSOURCE_HSE_DIV_4 (RCC_CFGR_PLLSRC | RCC_CFGR2_PREDIV1_DIV4) /*!< HSE/4 clock selected as PLL entry clock source */ @@ -441,26 +490,26 @@ typedef struct #define LL_RCC_PLLSOURCE_HSE_DIV_14 (RCC_CFGR_PLLSRC | RCC_CFGR2_PREDIV1_DIV14) /*!< HSE/14 clock selected as PLL entry clock source */ #define LL_RCC_PLLSOURCE_HSE_DIV_15 (RCC_CFGR_PLLSRC | RCC_CFGR2_PREDIV1_DIV15) /*!< HSE/15 clock selected as PLL entry clock source */ #define LL_RCC_PLLSOURCE_HSE_DIV_16 (RCC_CFGR_PLLSRC | RCC_CFGR2_PREDIV1_DIV16) /*!< HSE/16 clock selected as PLL entry clock source */ -#if defined(RCC_CFGR2_PREDIV1SRC) -#define LL_RCC_PLLSOURCE_PLL2_DIV_2 (RCC_CFGR_PLLSRC | RCC_CFGR2_PREDIV1_DIV2 | RCC_CFGR2_PREDIV1SRC << 4U) /*!< PLL2/2 clock selected as PLL entry clock source */ -#define LL_RCC_PLLSOURCE_PLL2_DIV_3 (RCC_CFGR_PLLSRC | RCC_CFGR2_PREDIV1_DIV3 | RCC_CFGR2_PREDIV1SRC << 4U) /*!< PLL2/3 clock selected as PLL entry clock source */ -#define LL_RCC_PLLSOURCE_PLL2_DIV_4 (RCC_CFGR_PLLSRC | RCC_CFGR2_PREDIV1_DIV4 | RCC_CFGR2_PREDIV1SRC << 4U) /*!< PLL2/4 clock selected as PLL entry clock source */ -#define LL_RCC_PLLSOURCE_PLL2_DIV_5 (RCC_CFGR_PLLSRC | RCC_CFGR2_PREDIV1_DIV5 | RCC_CFGR2_PREDIV1SRC << 4U) /*!< PLL2/5 clock selected as PLL entry clock source */ -#define LL_RCC_PLLSOURCE_PLL2_DIV_6 (RCC_CFGR_PLLSRC | RCC_CFGR2_PREDIV1_DIV6 | RCC_CFGR2_PREDIV1SRC << 4U) /*!< PLL2/6 clock selected as PLL entry clock source */ -#define LL_RCC_PLLSOURCE_PLL2_DIV_7 (RCC_CFGR_PLLSRC | RCC_CFGR2_PREDIV1_DIV7 | RCC_CFGR2_PREDIV1SRC << 4U) /*!< PLL2/7 clock selected as PLL entry clock source */ -#define LL_RCC_PLLSOURCE_PLL2_DIV_8 (RCC_CFGR_PLLSRC | RCC_CFGR2_PREDIV1_DIV8 | RCC_CFGR2_PREDIV1SRC << 4U) /*!< PLL2/8 clock selected as PLL entry clock source */ -#define LL_RCC_PLLSOURCE_PLL2_DIV_9 (RCC_CFGR_PLLSRC | RCC_CFGR2_PREDIV1_DIV9 | RCC_CFGR2_PREDIV1SRC << 4U) /*!< PLL2/9 clock selected as PLL entry clock source */ -#define LL_RCC_PLLSOURCE_PLL2_DIV_10 (RCC_CFGR_PLLSRC | RCC_CFGR2_PREDIV1_DIV10 | RCC_CFGR2_PREDIV1SRC << 4U) /*!< PLL2/10 clock selected as PLL entry clock source */ -#define LL_RCC_PLLSOURCE_PLL2_DIV_11 (RCC_CFGR_PLLSRC | RCC_CFGR2_PREDIV1_DIV11 | RCC_CFGR2_PREDIV1SRC << 4U) /*!< PLL2/11 clock selected as PLL entry clock source */ -#define LL_RCC_PLLSOURCE_PLL2_DIV_12 (RCC_CFGR_PLLSRC | RCC_CFGR2_PREDIV1_DIV12 | RCC_CFGR2_PREDIV1SRC << 4U) /*!< PLL2/12 clock selected as PLL entry clock source */ -#define LL_RCC_PLLSOURCE_PLL2_DIV_13 (RCC_CFGR_PLLSRC | RCC_CFGR2_PREDIV1_DIV13 | RCC_CFGR2_PREDIV1SRC << 4U) /*!< PLL2/13 clock selected as PLL entry clock source */ -#define LL_RCC_PLLSOURCE_PLL2_DIV_14 (RCC_CFGR_PLLSRC | RCC_CFGR2_PREDIV1_DIV14 | RCC_CFGR2_PREDIV1SRC << 4U) /*!< PLL2/14 clock selected as PLL entry clock source */ -#define LL_RCC_PLLSOURCE_PLL2_DIV_15 (RCC_CFGR_PLLSRC | RCC_CFGR2_PREDIV1_DIV15 | RCC_CFGR2_PREDIV1SRC << 4U) /*!< PLL2/15 clock selected as PLL entry clock source */ -#define LL_RCC_PLLSOURCE_PLL2_DIV_16 (RCC_CFGR_PLLSRC | RCC_CFGR2_PREDIV1_DIV16 | RCC_CFGR2_PREDIV1SRC << 4U) /*!< PLL2/16 clock selected as PLL entry clock source */ -#endif /*RCC_CFGR2_PREDIV1SRC*/ +#if defined(RCC_SRC_PREDIV1_SUPPORT) +#define LL_RCC_PLLSOURCE_PLL2_DIV_2 (RCC_CFGR_PLLSRC | RCC_CFGR2_PREDIV1_DIV2 | RCC_CFGR2_PREDIV1SRC << 4) /*!< PLL2/2 clock selected as PLL entry clock source */ +#define LL_RCC_PLLSOURCE_PLL2_DIV_3 (RCC_CFGR_PLLSRC | RCC_CFGR2_PREDIV1_DIV3 | RCC_CFGR2_PREDIV1SRC << 4) /*!< PLL2/3 clock selected as PLL entry clock source */ +#define LL_RCC_PLLSOURCE_PLL2_DIV_4 (RCC_CFGR_PLLSRC | RCC_CFGR2_PREDIV1_DIV4 | RCC_CFGR2_PREDIV1SRC << 4) /*!< PLL2/4 clock selected as PLL entry clock source */ +#define LL_RCC_PLLSOURCE_PLL2_DIV_5 (RCC_CFGR_PLLSRC | RCC_CFGR2_PREDIV1_DIV5 | RCC_CFGR2_PREDIV1SRC << 4) /*!< PLL2/5 clock selected as PLL entry clock source */ +#define LL_RCC_PLLSOURCE_PLL2_DIV_6 (RCC_CFGR_PLLSRC | RCC_CFGR2_PREDIV1_DIV6 | RCC_CFGR2_PREDIV1SRC << 4) /*!< PLL2/6 clock selected as PLL entry clock source */ +#define LL_RCC_PLLSOURCE_PLL2_DIV_7 (RCC_CFGR_PLLSRC | RCC_CFGR2_PREDIV1_DIV7 | RCC_CFGR2_PREDIV1SRC << 4) /*!< PLL2/7 clock selected as PLL entry clock source */ +#define LL_RCC_PLLSOURCE_PLL2_DIV_8 (RCC_CFGR_PLLSRC | RCC_CFGR2_PREDIV1_DIV8 | RCC_CFGR2_PREDIV1SRC << 4) /*!< PLL2/8 clock selected as PLL entry clock source */ +#define LL_RCC_PLLSOURCE_PLL2_DIV_9 (RCC_CFGR_PLLSRC | RCC_CFGR2_PREDIV1_DIV9 | RCC_CFGR2_PREDIV1SRC << 4) /*!< PLL2/9 clock selected as PLL entry clock source */ +#define LL_RCC_PLLSOURCE_PLL2_DIV_10 (RCC_CFGR_PLLSRC | RCC_CFGR2_PREDIV1_DIV10 | RCC_CFGR2_PREDIV1SRC << 4) /*!< PLL2/10 clock selected as PLL entry clock source */ +#define LL_RCC_PLLSOURCE_PLL2_DIV_11 (RCC_CFGR_PLLSRC | RCC_CFGR2_PREDIV1_DIV11 | RCC_CFGR2_PREDIV1SRC << 4) /*!< PLL2/11 clock selected as PLL entry clock source */ +#define LL_RCC_PLLSOURCE_PLL2_DIV_12 (RCC_CFGR_PLLSRC | RCC_CFGR2_PREDIV1_DIV12 | RCC_CFGR2_PREDIV1SRC << 4) /*!< PLL2/12 clock selected as PLL entry clock source */ +#define LL_RCC_PLLSOURCE_PLL2_DIV_13 (RCC_CFGR_PLLSRC | RCC_CFGR2_PREDIV1_DIV13 | RCC_CFGR2_PREDIV1SRC << 4) /*!< PLL2/13 clock selected as PLL entry clock source */ +#define LL_RCC_PLLSOURCE_PLL2_DIV_14 (RCC_CFGR_PLLSRC | RCC_CFGR2_PREDIV1_DIV14 | RCC_CFGR2_PREDIV1SRC << 4) /*!< PLL2/14 clock selected as PLL entry clock source */ +#define LL_RCC_PLLSOURCE_PLL2_DIV_15 (RCC_CFGR_PLLSRC | RCC_CFGR2_PREDIV1_DIV15 | RCC_CFGR2_PREDIV1SRC << 4) /*!< PLL2/15 clock selected as PLL entry clock source */ +#define LL_RCC_PLLSOURCE_PLL2_DIV_16 (RCC_CFGR_PLLSRC | RCC_CFGR2_PREDIV1_DIV16 | RCC_CFGR2_PREDIV1SRC << 4) /*!< PLL2/16 clock selected as PLL entry clock source */ +#endif /*RCC_SRC_PREDIV1_SUPPORT*/ #else #define LL_RCC_PLLSOURCE_HSE_DIV_2 (RCC_CFGR_PLLSRC | RCC_CFGR_PLLXTPRE) /*!< HSE/2 clock selected as PLL entry clock source */ -#endif /*RCC_CFGR2_PREDIV1*/ +#endif /*RCC_PREDIV1_DIV_2_16_SUPPORT*/ /** * @} */ @@ -468,7 +517,7 @@ typedef struct /** @defgroup RCC_LL_EC_PREDIV_DIV PREDIV Division factor * @{ */ -#if defined(RCC_CFGR2_PREDIV1) +#if defined(RCC_PREDIV1_DIV_2_16_SUPPORT) #define LL_RCC_PREDIV_DIV_1 RCC_CFGR2_PREDIV1_DIV1 /*!< PREDIV1 input clock not divided */ #define LL_RCC_PREDIV_DIV_2 RCC_CFGR2_PREDIV1_DIV2 /*!< PREDIV1 input clock divided by 2 */ #define LL_RCC_PREDIV_DIV_3 RCC_CFGR2_PREDIV1_DIV3 /*!< PREDIV1 input clock divided by 3 */ @@ -486,9 +535,9 @@ typedef struct #define LL_RCC_PREDIV_DIV_15 RCC_CFGR2_PREDIV1_DIV15 /*!< PREDIV1 input clock divided by 15 */ #define LL_RCC_PREDIV_DIV_16 RCC_CFGR2_PREDIV1_DIV16 /*!< PREDIV1 input clock divided by 16 */ #else -#define LL_RCC_PREDIV_DIV_1 0x00000000U /*!< HSE divider clock clock not divided */ -#define LL_RCC_PREDIV_DIV_2 RCC_CFGR_PLLXTPRE /*!< HSE divider clock divided by 2 for PLL entry */ -#endif /*RCC_CFGR2_PREDIV1*/ +#define LL_RCC_PREDIV_DIV_1 ((uint32_t)0x00000000U) /*!< HSE divider clock clock not divided */ +#define LL_RCC_PREDIV_DIV_2 RCC_CFGR_PLLXTPRE /*!< HSE divider clock divided by 2 for PLL entry */ +#endif /*RCC_PREDIV1_DIV_2_16_SUPPORT*/ /** * @} */ @@ -583,7 +632,7 @@ typedef struct */ #define __LL_RCC_CALC_PLLCLK_FREQ(__INPUTFREQ__, __PLLMUL__) \ (((__PLLMUL__) != RCC_CFGR_PLLMULL6_5) ? \ - ((__INPUTFREQ__) * ((((__PLLMUL__) & RCC_CFGR_PLLMULL) >> RCC_CFGR_PLLMULL_Pos) + 2U)) :\ + ((__INPUTFREQ__) * ((((__PLLMUL__) & RCC_CFGR_PLLMULL) >> RCC_POSITION_PLLMUL) + 2U)) :\ (((__INPUTFREQ__) * 13U) / 2U)) #else @@ -609,7 +658,7 @@ typedef struct * @arg @ref LL_RCC_PLL_MUL_16 * @retval PLL clock frequency (in Hz) */ -#define __LL_RCC_CALC_PLLCLK_FREQ(__INPUTFREQ__, __PLLMUL__) ((__INPUTFREQ__) * (((__PLLMUL__) >> RCC_CFGR_PLLMULL_Pos) + 2U)) +#define __LL_RCC_CALC_PLLCLK_FREQ(__INPUTFREQ__, __PLLMUL__) ((__INPUTFREQ__) * (((__PLLMUL__) >> RCC_POSITION_PLLMUL) + 2U)) #endif /* RCC_CFGR_PLLMULL6_5 */ #if defined(RCC_PLLI2S_SUPPORT) @@ -646,7 +695,7 @@ typedef struct * @arg @ref LL_RCC_HSE_PREDIV2_DIV_16 * @retval PLLI2S clock frequency (in Hz) */ -#define __LL_RCC_CALC_PLLI2SCLK_FREQ(__INPUTFREQ__, __PLLI2SMUL__, __PLLI2SDIV__) (((__INPUTFREQ__) * (((__PLLI2SMUL__) >> RCC_CFGR2_PLL3MUL_Pos) + 2U)) / (((__PLLI2SDIV__) >> RCC_CFGR2_PREDIV2_Pos) + 1U)) +#define __LL_RCC_CALC_PLLI2SCLK_FREQ(__INPUTFREQ__, __PLLI2SMUL__, __PLLI2SDIV__) (((__INPUTFREQ__) * (((__PLLI2SMUL__) >> POSITION_VAL(RCC_CFGR2_PLL3MUL)) + 2U)) / (((__PLLI2SDIV__) >> POSITION_VAL(RCC_CFGR2_PREDIV2)) + 1U)) #endif /* RCC_PLLI2S_SUPPORT */ #if defined(RCC_PLL2_SUPPORT) @@ -683,7 +732,7 @@ typedef struct * @arg @ref LL_RCC_HSE_PREDIV2_DIV_16 * @retval PLL2 clock frequency (in Hz) */ -#define __LL_RCC_CALC_PLL2CLK_FREQ(__INPUTFREQ__, __PLL2MUL__, __PLL2DIV__) (((__INPUTFREQ__) * (((__PLL2MUL__) >> RCC_CFGR2_PLL2MUL_Pos) + 2U)) / (((__PLL2DIV__) >> RCC_CFGR2_PREDIV2_Pos) + 1U)) +#define __LL_RCC_CALC_PLL2CLK_FREQ(__INPUTFREQ__, __PLL2MUL__, __PLL2DIV__) (((__INPUTFREQ__) * (((__PLL2MUL__) >> POSITION_VAL(RCC_CFGR2_PLL2MUL)) + 2U)) / (((__PLL2DIV__) >> POSITION_VAL(RCC_CFGR2_PREDIV2)) + 1U)) #endif /* RCC_PLL2_SUPPORT */ /** @@ -703,7 +752,7 @@ typedef struct * @arg @ref LL_RCC_SYSCLK_DIV_512 * @retval HCLK clock frequency (in Hz) */ -#define __LL_RCC_CALC_HCLK_FREQ(__SYSCLKFREQ__, __AHBPRESCALER__) ((__SYSCLKFREQ__) >> AHBPrescTable[((__AHBPRESCALER__) & RCC_CFGR_HPRE) >> RCC_CFGR_HPRE_Pos]) +#define __LL_RCC_CALC_HCLK_FREQ(__SYSCLKFREQ__, __AHBPRESCALER__) ((__SYSCLKFREQ__) >> AHBPrescTable[((__AHBPRESCALER__) & RCC_CFGR_HPRE) >> RCC_POSITION_HPRE]) /** * @brief Helper macro to calculate the PCLK1 frequency (ABP1) @@ -718,7 +767,7 @@ typedef struct * @arg @ref LL_RCC_APB1_DIV_16 * @retval PCLK1 clock frequency (in Hz) */ -#define __LL_RCC_CALC_PCLK1_FREQ(__HCLKFREQ__, __APB1PRESCALER__) ((__HCLKFREQ__) >> APBPrescTable[(__APB1PRESCALER__) >> RCC_CFGR_PPRE1_Pos]) +#define __LL_RCC_CALC_PCLK1_FREQ(__HCLKFREQ__, __APB1PRESCALER__) ((__HCLKFREQ__) >> APBPrescTable[(__APB1PRESCALER__) >> RCC_POSITION_PPRE1]) /** * @brief Helper macro to calculate the PCLK2 frequency (ABP2) @@ -733,7 +782,7 @@ typedef struct * @arg @ref LL_RCC_APB2_DIV_16 * @retval PCLK2 clock frequency (in Hz) */ -#define __LL_RCC_CALC_PCLK2_FREQ(__HCLKFREQ__, __APB2PRESCALER__) ((__HCLKFREQ__) >> APBPrescTable[(__APB2PRESCALER__) >> RCC_CFGR_PPRE2_Pos]) +#define __LL_RCC_CALC_PCLK2_FREQ(__HCLKFREQ__, __APB2PRESCALER__) ((__HCLKFREQ__) >> APBPrescTable[(__APB2PRESCALER__) >> RCC_POSITION_PPRE2]) /** * @} @@ -812,7 +861,7 @@ __STATIC_INLINE uint32_t LL_RCC_HSE_IsReady(void) return (READ_BIT(RCC->CR, RCC_CR_HSERDY) == (RCC_CR_HSERDY)); } -#if defined(RCC_CFGR2_PREDIV2) +#if defined(RCC_PREDIV2_SUPPORT) /** * @brief Get PREDIV2 division factor * @rmtoll CFGR2 PREDIV2 LL_RCC_HSE_GetPrediv2 @@ -838,7 +887,7 @@ __STATIC_INLINE uint32_t LL_RCC_HSE_GetPrediv2(void) { return (uint32_t)(READ_BIT(RCC->CFGR2, RCC_CFGR2_PREDIV2)); } -#endif /* RCC_CFGR2_PREDIV2 */ +#endif /* RCC_PREDIV2_SUPPORT */ /** * @} @@ -887,7 +936,7 @@ __STATIC_INLINE uint32_t LL_RCC_HSI_IsReady(void) */ __STATIC_INLINE uint32_t LL_RCC_HSI_GetCalibration(void) { - return (uint32_t)(READ_BIT(RCC->CR, RCC_CR_HSICAL) >> RCC_CR_HSICAL_Pos); + return (uint32_t)(READ_BIT(RCC->CR, RCC_CR_HSICAL) >> RCC_POSITION_HSICAL); } /** @@ -901,7 +950,7 @@ __STATIC_INLINE uint32_t LL_RCC_HSI_GetCalibration(void) */ __STATIC_INLINE void LL_RCC_HSI_SetCalibTrimming(uint32_t Value) { - MODIFY_REG(RCC->CR, RCC_CR_HSITRIM, Value << RCC_CR_HSITRIM_Pos); + MODIFY_REG(RCC->CR, RCC_CR_HSITRIM, Value << RCC_POSITION_HSITRIM); } /** @@ -911,7 +960,7 @@ __STATIC_INLINE void LL_RCC_HSI_SetCalibTrimming(uint32_t Value) */ __STATIC_INLINE uint32_t LL_RCC_HSI_GetCalibTrimming(void) { - return (uint32_t)(READ_BIT(RCC->CR, RCC_CR_HSITRIM) >> RCC_CR_HSITRIM_Pos); + return (uint32_t)(READ_BIT(RCC->CR, RCC_CR_HSITRIM) >> RCC_POSITION_HSITRIM); } /** @@ -1257,7 +1306,7 @@ __STATIC_INLINE void LL_RCC_SetADCClockSource(uint32_t ADCxSource) */ __STATIC_INLINE uint32_t LL_RCC_GetI2SClockSource(uint32_t I2Sx) { - return (uint32_t)(READ_BIT(RCC->CFGR2, I2Sx) >> 16U | I2Sx); + return (uint32_t)(READ_BIT(RCC->CFGR2, I2Sx) >> 16 | I2Sx); } #endif /* RCC_CFGR2_I2S2SRC */ @@ -1493,14 +1542,14 @@ __STATIC_INLINE void LL_RCC_PLL_ConfigDomain_SYS(uint32_t Source, uint32_t PLLMu { MODIFY_REG(RCC->CFGR, RCC_CFGR_PLLSRC | RCC_CFGR_PLLXTPRE | RCC_CFGR_PLLMULL, (Source & (RCC_CFGR_PLLSRC | RCC_CFGR_PLLXTPRE)) | PLLMul); -#if defined(RCC_CFGR2_PREDIV1) -#if defined(RCC_CFGR2_PREDIV1SRC) +#if defined(RCC_PREDIV1_DIV_2_16_SUPPORT) +#if defined(RCC_SRC_PREDIV1_SUPPORT) MODIFY_REG(RCC->CFGR2, (RCC_CFGR2_PREDIV1 | RCC_CFGR2_PREDIV1SRC), - (Source & RCC_CFGR2_PREDIV1) | ((Source & (RCC_CFGR2_PREDIV1SRC << 4U)) >> 4U)); + (Source & RCC_CFGR2_PREDIV1) | ((Source & (RCC_CFGR2_PREDIV1SRC << 4)) >> 4)); #else MODIFY_REG(RCC->CFGR2, RCC_CFGR2_PREDIV1, (Source & RCC_CFGR2_PREDIV1)); -#endif /*RCC_CFGR2_PREDIV1SRC*/ -#endif /*RCC_CFGR2_PREDIV1*/ +#endif /*RCC_SRC_PREDIV1_SUPPORT*/ +#endif /*RCC_PREDIV1_DIV_2_16_SUPPORT*/ } /** @@ -1516,13 +1565,11 @@ __STATIC_INLINE void LL_RCC_PLL_ConfigDomain_SYS(uint32_t Source, uint32_t PLLMu */ __STATIC_INLINE uint32_t LL_RCC_PLL_GetMainSource(void) { -#if defined(RCC_CFGR2_PREDIV1SRC) - register uint32_t pllsrc = READ_BIT(RCC->CFGR, RCC_CFGR_PLLSRC); - register uint32_t predivsrc = (uint32_t)(READ_BIT(RCC->CFGR2, RCC_CFGR2_PREDIV1SRC) << 4U); - return (uint32_t)(pllsrc | predivsrc); +#if defined(RCC_SRC_PREDIV1_SUPPORT) + return (uint32_t)(READ_BIT(RCC->CFGR, RCC_CFGR_PLLSRC) | (READ_BIT(RCC->CFGR2, RCC_CFGR2_PREDIV1SRC) << 4)); #else return (uint32_t)(READ_BIT(RCC->CFGR, RCC_CFGR_PLLSRC)); -#endif /*RCC_CFGR2_PREDIV1SRC*/ +#endif /*RCC_SRC_PREDIV1_SUPPORT*/ } /** @@ -1580,11 +1627,11 @@ __STATIC_INLINE uint32_t LL_RCC_PLL_GetMultiplicator(void) */ __STATIC_INLINE uint32_t LL_RCC_PLL_GetPrediv(void) { -#if defined(RCC_CFGR2_PREDIV1) +#if defined(RCC_PREDIV1_DIV_2_16_SUPPORT) return (uint32_t)(READ_BIT(RCC->CFGR2, RCC_CFGR2_PREDIV1)); #else return (uint32_t)(READ_BIT(RCC->CFGR, RCC_CFGR_PLLXTPRE)); -#endif /*RCC_CFGR2_PREDIV1*/ +#endif /*RCC_PREDIV1_DIV_2_16_SUPPORT*/ } /** @@ -2274,7 +2321,7 @@ ErrorStatus LL_RCC_DeInit(void); * @{ */ void LL_RCC_GetSystemClocksFreq(LL_RCC_ClocksTypeDef *RCC_Clocks); -#if defined(RCC_CFGR2_I2S2SRC) +#if defined(RCC_CFGR2_I2S2SRC) uint32_t LL_RCC_GetI2SClockFreq(uint32_t I2SxSource); #endif /* RCC_CFGR2_I2S2SRC */ #if defined(USB_OTG_FS) || defined(USB) diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_rtc.c b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_rtc.c deleted file mode 100644 index 48510d246e3..00000000000 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_rtc.c +++ /dev/null @@ -1,558 +0,0 @@ -/** - ****************************************************************************** - * @file stm32f1xx_ll_rtc.c - * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 - * @brief RTC LL module driver. - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2016 STMicroelectronics

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ -#if defined(USE_FULL_LL_DRIVER) - -/* Includes ------------------------------------------------------------------*/ -#include "stm32f1xx_ll_rtc.h" -#include "stm32f1xx_ll_cortex.h" -#ifdef USE_FULL_ASSERT -#include "stm32_assert.h" -#else -#define assert_param(expr) ((void)0U) -#endif - -/** @addtogroup STM32F1xx_LL_Driver - * @{ - */ - -#if defined(RTC) - -/** @addtogroup RTC_LL - * @{ - */ - -/* Private types -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private constants ---------------------------------------------------------*/ -/** @addtogroup RTC_LL_Private_Constants - * @{ - */ -/* Default values used for prescaler */ -#define RTC_ASYNCH_PRESC_DEFAULT 0x00007FFFU - -/* Values used for timeout */ -#define RTC_INITMODE_TIMEOUT 1000U /* 1s when tick set to 1ms */ -#define RTC_SYNCHRO_TIMEOUT 1000U /* 1s when tick set to 1ms */ -/** - * @} - */ - -/* Private macros ------------------------------------------------------------*/ -/** @addtogroup RTC_LL_Private_Macros - * @{ - */ - -#define IS_LL_RTC_ASYNCH_PREDIV(__VALUE__) ((__VALUE__) <= 0xFFFFFU) - -#define IS_LL_RTC_FORMAT(__VALUE__) (((__VALUE__) == LL_RTC_FORMAT_BIN) \ - || ((__VALUE__) == LL_RTC_FORMAT_BCD)) - -#define IS_LL_RTC_HOUR24(__HOUR__) ((__HOUR__) <= 23U) -#define IS_LL_RTC_MINUTES(__MINUTES__) ((__MINUTES__) <= 59U) -#define IS_LL_RTC_SECONDS(__SECONDS__) ((__SECONDS__) <= 59U) -#define IS_LL_RTC_CALIB_OUTPUT(__OUTPUT__) (((__OUTPUT__) == LL_RTC_CALIB_OUTPUT_NONE) || \ - ((__OUTPUT__) == LL_RTC_CALIB_OUTPUT_RTCCLOCK) || \ - ((__OUTPUT__) == LL_RTC_CALIB_OUTPUT_ALARM) || \ - ((__OUTPUT__) == LL_RTC_CALIB_OUTPUT_SECOND)) -/** - * @} - */ -/* Private function prototypes -----------------------------------------------*/ -/* Exported functions --------------------------------------------------------*/ -/** @addtogroup RTC_LL_Exported_Functions - * @{ - */ - -/** @addtogroup RTC_LL_EF_Init - * @{ - */ - -/** - * @brief De-Initializes the RTC registers to their default reset values. - * @note This function doesn't reset the RTC Clock source and RTC Backup Data - * registers. - * @param RTCx RTC Instance - * @retval An ErrorStatus enumeration value: - * - SUCCESS: RTC registers are de-initialized - * - ERROR: RTC registers are not de-initialized - */ -ErrorStatus LL_RTC_DeInit(RTC_TypeDef *RTCx) -{ - ErrorStatus status = ERROR; - - /* Check the parameter */ - assert_param(IS_RTC_ALL_INSTANCE(RTCx)); - - /* Disable the write protection for RTC registers */ - LL_RTC_DisableWriteProtection(RTCx); - - /* Set Initialization mode */ - if (LL_RTC_EnterInitMode(RTCx) != ERROR) - { - LL_RTC_WriteReg(RTCx,CNTL, 0x0000); - LL_RTC_WriteReg(RTCx,CNTH, 0x0000); - LL_RTC_WriteReg(RTCx,PRLH, 0x0000); - LL_RTC_WriteReg(RTCx,PRLL, 0x8000); - LL_RTC_WriteReg(RTCx,CRH, 0x0000); - LL_RTC_WriteReg(RTCx,CRL, 0x0020); - - /* Reset Tamper and alternate functions configuration register */ - LL_RTC_WriteReg(BKP,RTCCR, 0x00000000U); - LL_RTC_WriteReg(BKP,CR, 0x00000000U); - LL_RTC_WriteReg(BKP,CSR, 0x00000000U); - - /* Exit Initialization Mode */ - if(LL_RTC_ExitInitMode(RTCx) == ERROR) - { - return ERROR; - } - - /* Wait till the RTC RSF flag is set */ - status = LL_RTC_WaitForSynchro(RTCx); - - /* Clear RSF Flag */ - LL_RTC_ClearFlag_RS(RTCx); - } - - /* Enable the write protection for RTC registers */ - LL_RTC_EnableWriteProtection(RTCx); - - return status; -} - -/** - * @brief Initializes the RTC registers according to the specified parameters - * in RTC_InitStruct. - * @param RTCx RTC Instance - * @param RTC_InitStruct pointer to a @ref LL_RTC_InitTypeDef structure that contains - * the configuration information for the RTC peripheral. - * @note The RTC Prescaler register is write protected and can be written in - * initialization mode only. - * @note the user should call LL_RTC_StructInit() or the structure of Prescaler - * need to be initialized before RTC init() - * @retval An ErrorStatus enumeration value: - * - SUCCESS: RTC registers are initialized - * - ERROR: RTC registers are not initialized - */ -ErrorStatus LL_RTC_Init(RTC_TypeDef *RTCx, LL_RTC_InitTypeDef *RTC_InitStruct) -{ - ErrorStatus status = ERROR; - - /* Check the parameters */ - assert_param(IS_RTC_ALL_INSTANCE(RTCx)); - assert_param(IS_LL_RTC_ASYNCH_PREDIV(RTC_InitStruct->AsynchPrescaler)); - assert_param(IS_LL_RTC_CALIB_OUTPUT(RTC_InitStruct->OutPutSource)); - /* Waiting for synchro */ - if(LL_RTC_WaitForSynchro(RTCx) != ERROR) - { - /* Set Initialization mode */ - if (LL_RTC_EnterInitMode(RTCx) != ERROR) - { - /* Clear Flag Bits */ - LL_RTC_ClearFlag_ALR(RTCx); - LL_RTC_ClearFlag_OW(RTCx); - LL_RTC_ClearFlag_SEC(RTCx); - - if(RTC_InitStruct->OutPutSource != LL_RTC_CALIB_OUTPUT_NONE) - { - /* Disable the selected Tamper Pin */ - LL_RTC_TAMPER_Disable(BKP); - } - /* Set the signal which will be routed to RTC Tamper Pin */ - LL_RTC_SetOutputSource(BKP, RTC_InitStruct->OutPutSource); - - /* Configure Synchronous and Asynchronous prescaler factor */ - LL_RTC_SetAsynchPrescaler(RTCx, RTC_InitStruct->AsynchPrescaler); - - /* Exit Initialization Mode */ - LL_RTC_ExitInitMode(RTCx); - - status = SUCCESS; - } - } - return status; -} - -/** - * @brief Set each @ref LL_RTC_InitTypeDef field to default value. - * @param RTC_InitStruct pointer to a @ref LL_RTC_InitTypeDef structure which will be initialized. - * @retval None - */ -void LL_RTC_StructInit(LL_RTC_InitTypeDef *RTC_InitStruct) -{ - /* Set RTC_InitStruct fields to default values */ - RTC_InitStruct->AsynchPrescaler = RTC_ASYNCH_PRESC_DEFAULT; - RTC_InitStruct->OutPutSource = LL_RTC_CALIB_OUTPUT_NONE; -} - -/** - * @brief Set the RTC current time. - * @param RTCx RTC Instance - * @param RTC_Format This parameter can be one of the following values: - * @arg @ref LL_RTC_FORMAT_BIN - * @arg @ref LL_RTC_FORMAT_BCD - * @param RTC_TimeStruct pointer to a RTC_TimeTypeDef structure that contains - * the time configuration information for the RTC. - * @note The user should call LL_RTC_TIME_StructInit() or the structure - * of time need to be initialized before time init() - * @retval An ErrorStatus enumeration value: - * - SUCCESS: RTC Time register is configured - * - ERROR: RTC Time register is not configured - */ -ErrorStatus LL_RTC_TIME_Init(RTC_TypeDef *RTCx, uint32_t RTC_Format, LL_RTC_TimeTypeDef *RTC_TimeStruct) -{ - ErrorStatus status = ERROR; - uint32_t counter_time = 0U; - - /* Check the parameters */ - assert_param(IS_RTC_ALL_INSTANCE(RTCx)); - assert_param(IS_LL_RTC_FORMAT(RTC_Format)); - - if (RTC_Format == LL_RTC_FORMAT_BIN) - { - assert_param(IS_LL_RTC_HOUR24(RTC_TimeStruct->Hours)); - assert_param(IS_LL_RTC_MINUTES(RTC_TimeStruct->Minutes)); - assert_param(IS_LL_RTC_SECONDS(RTC_TimeStruct->Seconds)); - } - else - { - assert_param(IS_LL_RTC_HOUR24(__LL_RTC_CONVERT_BCD2BIN(RTC_TimeStruct->Hours))); - assert_param(IS_LL_RTC_MINUTES(__LL_RTC_CONVERT_BCD2BIN(RTC_TimeStruct->Minutes))); - assert_param(IS_LL_RTC_SECONDS(__LL_RTC_CONVERT_BCD2BIN(RTC_TimeStruct->Seconds))); - } - - /* Enter Initialization mode */ - if (LL_RTC_EnterInitMode(RTCx) != ERROR) - { - /* Check the input parameters format */ - if (RTC_Format != LL_RTC_FORMAT_BIN) - { - counter_time = (uint32_t)(((uint32_t)RTC_TimeStruct->Hours * 3600U) + \ - ((uint32_t)RTC_TimeStruct->Minutes * 60U) + \ - ((uint32_t)RTC_TimeStruct->Seconds)); - LL_RTC_TIME_Set(RTCx, counter_time); - } - else - { - counter_time = (((uint32_t)(__LL_RTC_CONVERT_BCD2BIN(RTC_TimeStruct->Hours)) * 3600U) + \ - ((uint32_t)(__LL_RTC_CONVERT_BCD2BIN(RTC_TimeStruct->Minutes)) * 60U) + \ - ((uint32_t)(__LL_RTC_CONVERT_BCD2BIN(RTC_TimeStruct->Seconds)))); - LL_RTC_TIME_Set(RTCx, counter_time); - } - status = SUCCESS; - } - /* Exit Initialization mode */ - LL_RTC_ExitInitMode(RTCx); - - return status; -} - -/** - * @brief Set each @ref LL_RTC_TimeTypeDef field to default value (Time = 00h:00min:00sec). - * @param RTC_TimeStruct pointer to a @ref LL_RTC_TimeTypeDef structure which will be initialized. - * @retval None - */ -void LL_RTC_TIME_StructInit(LL_RTC_TimeTypeDef *RTC_TimeStruct) -{ - /* Time = 00h:00min:00sec */ - RTC_TimeStruct->Hours = 0U; - RTC_TimeStruct->Minutes = 0U; - RTC_TimeStruct->Seconds = 0U; -} - -/** - * @brief Set the RTC Alarm. - * @param RTCx RTC Instance - * @param RTC_Format This parameter can be one of the following values: - * @arg @ref LL_RTC_FORMAT_BIN - * @arg @ref LL_RTC_FORMAT_BCD - * @param RTC_AlarmStruct pointer to a @ref LL_RTC_AlarmTypeDef structure that - * contains the alarm configuration parameters. - * @note the user should call LL_RTC_ALARM_StructInit() or the structure - * of Alarm need to be initialized before Alarm init() - * @retval An ErrorStatus enumeration value: - * - SUCCESS: ALARM registers are configured - * - ERROR: ALARM registers are not configured - */ -ErrorStatus LL_RTC_ALARM_Init(RTC_TypeDef *RTCx, uint32_t RTC_Format, LL_RTC_AlarmTypeDef *RTC_AlarmStruct) -{ - ErrorStatus status = ERROR; - uint32_t counter_alarm = 0U; - /* Check the parameters */ - assert_param(IS_RTC_ALL_INSTANCE(RTCx)); - assert_param(IS_LL_RTC_FORMAT(RTC_Format)); - - if (RTC_Format == LL_RTC_FORMAT_BIN) - { - assert_param(IS_LL_RTC_HOUR24(RTC_AlarmStruct->AlarmTime.Hours)); - assert_param(IS_LL_RTC_MINUTES(RTC_AlarmStruct->AlarmTime.Minutes)); - assert_param(IS_LL_RTC_SECONDS(RTC_AlarmStruct->AlarmTime.Seconds)); - } - else - { - assert_param(IS_LL_RTC_HOUR24(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Hours))); - assert_param(IS_LL_RTC_MINUTES(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Minutes))); - assert_param(IS_LL_RTC_SECONDS(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Seconds))); - } - - /* Enter Initialization mode */ - if (LL_RTC_EnterInitMode(RTCx) != ERROR) - { - /* Check the input parameters format */ - if (RTC_Format != LL_RTC_FORMAT_BIN) - { - counter_alarm = (uint32_t)(((uint32_t)RTC_AlarmStruct->AlarmTime.Hours * 3600U) + \ - ((uint32_t)RTC_AlarmStruct->AlarmTime.Minutes * 60U) + \ - ((uint32_t)RTC_AlarmStruct->AlarmTime.Seconds)); - LL_RTC_ALARM_Set(RTCx, counter_alarm); - } - else - { - counter_alarm = (((uint32_t)(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Hours)) * 3600U) + \ - ((uint32_t)(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Minutes)) * 60U) + \ - ((uint32_t)(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Seconds)))); - LL_RTC_ALARM_Set(RTCx, counter_alarm); - } - status = SUCCESS; - } - /* Exit Initialization mode */ - LL_RTC_ExitInitMode(RTCx); - - return status; -} - -/** - * @brief Set each @ref LL_RTC_AlarmTypeDef of ALARM field to default value (Time = 00h:00mn:00sec / - * Day = 1st day of the month/Mask = all fields are masked). - * @param RTC_AlarmStruct pointer to a @ref LL_RTC_AlarmTypeDef structure which will be initialized. - * @retval None - */ -void LL_RTC_ALARM_StructInit(LL_RTC_AlarmTypeDef *RTC_AlarmStruct) -{ - /* Alarm Time Settings : Time = 00h:00mn:00sec */ - RTC_AlarmStruct->AlarmTime.Hours = 0U; - RTC_AlarmStruct->AlarmTime.Minutes = 0U; - RTC_AlarmStruct->AlarmTime.Seconds = 0U; -} - -/** - * @brief Enters the RTC Initialization mode. - * @param RTCx RTC Instance - * @retval An ErrorStatus enumeration value: - * - SUCCESS: RTC is in Init mode - * - ERROR: RTC is not in Init mode - */ -ErrorStatus LL_RTC_EnterInitMode(RTC_TypeDef *RTCx) -{ - __IO uint32_t timeout = RTC_INITMODE_TIMEOUT; - ErrorStatus status = SUCCESS; - uint32_t tmp = 0U; - - /* Check the parameter */ - assert_param(IS_RTC_ALL_INSTANCE(RTCx)); - - /* Wait till RTC is in INIT state and if Time out is reached exit */ - tmp = LL_RTC_IsActiveFlag_RTOF(RTCx); - while ((timeout != 0U) && (tmp != 1U)) - { - if (LL_SYSTICK_IsActiveCounterFlag() == 1U) - { - timeout --; - } - tmp = LL_RTC_IsActiveFlag_RTOF(RTCx); - if (timeout == 0U) - { - status = ERROR; - } - } - - /* Disable the write protection for RTC registers */ - LL_RTC_DisableWriteProtection(RTCx); - - return status; -} - -/** - * @brief Exit the RTC Initialization mode. - * @note When the initialization sequence is complete, the calendar restarts - * counting after 4 RTCCLK cycles. - * @param RTCx RTC Instance - * @retval An ErrorStatus enumeration value: - * - SUCCESS: RTC exited from in Init mode - * - ERROR: Not applicable - */ -ErrorStatus LL_RTC_ExitInitMode(RTC_TypeDef *RTCx) -{ - __IO uint32_t timeout = RTC_INITMODE_TIMEOUT; - ErrorStatus status = SUCCESS; - uint32_t tmp = 0U; - - /* Check the parameter */ - assert_param(IS_RTC_ALL_INSTANCE(RTCx)); - - /* Disable initialization mode */ - LL_RTC_EnableWriteProtection(RTCx); - - /* Wait till RTC is in INIT state and if Time out is reached exit */ - tmp = LL_RTC_IsActiveFlag_RTOF(RTCx); - while ((timeout != 0U) && (tmp != 1U)) - { - if (LL_SYSTICK_IsActiveCounterFlag() == 1U) - { - timeout --; - } - tmp = LL_RTC_IsActiveFlag_RTOF(RTCx); - if (timeout == 0U) - { - status = ERROR; - } - } - return status; -} - -/** - * @brief Set the Time Counter - * @param RTCx RTC Instance - * @param TimeCounter this value can be from 0 to 0xFFFFFFFF - * @retval An ErrorStatus enumeration value: - * - SUCCESS: RTC Counter register configured - * - ERROR: Not applicable - */ -ErrorStatus LL_RTC_TIME_SetCounter(RTC_TypeDef *RTCx, uint32_t TimeCounter) -{ - ErrorStatus status = ERROR; - /* Check the parameter */ - assert_param(IS_RTC_ALL_INSTANCE(RTCx)); - - /* Enter Initialization mode */ - if (LL_RTC_EnterInitMode(RTCx) != ERROR) - { - LL_RTC_TIME_Set(RTCx, TimeCounter); - status = SUCCESS; - } - /* Exit Initialization mode */ - LL_RTC_ExitInitMode(RTCx); - - return status; -} - -/** - * @brief Set Alarm Counter. - * @param RTCx RTC Instance - * @param AlarmCounter this value can be from 0 to 0xFFFFFFFF - * @retval An ErrorStatus enumeration value: - * - SUCCESS: RTC exited from in Init mode - * - ERROR: Not applicable - */ -ErrorStatus LL_RTC_ALARM_SetCounter(RTC_TypeDef *RTCx, uint32_t AlarmCounter) -{ - ErrorStatus status = ERROR; - /* Check the parameter */ - assert_param(IS_RTC_ALL_INSTANCE(RTCx)); - - /* Enter Initialization mode */ - if (LL_RTC_EnterInitMode(RTCx) != ERROR) - { - LL_RTC_ALARM_Set(RTCx, AlarmCounter); - status = SUCCESS; - } - /* Exit Initialization mode */ - LL_RTC_ExitInitMode(RTCx); - - return status; -} - -/** - * @brief Waits until the RTC registers are synchronized with RTC APB clock. - * @note The RTC Resynchronization mode is write protected, use the - * @ref LL_RTC_DisableWriteProtection before calling this function. - * @param RTCx RTC Instance - * @retval An ErrorStatus enumeration value: - * - SUCCESS: RTC registers are synchronised - * - ERROR: RTC registers are not synchronised - */ -ErrorStatus LL_RTC_WaitForSynchro(RTC_TypeDef *RTCx) -{ - __IO uint32_t timeout = RTC_SYNCHRO_TIMEOUT; - ErrorStatus status = SUCCESS; - uint32_t tmp = 0U; - - /* Check the parameter */ - assert_param(IS_RTC_ALL_INSTANCE(RTCx)); - - /* Clear RSF flag */ - LL_RTC_ClearFlag_RS(RTCx); - - /* Wait the registers to be synchronised */ - tmp = LL_RTC_IsActiveFlag_RS(RTCx); - while ((timeout != 0U) && (tmp != 0U)) - { - if (LL_SYSTICK_IsActiveCounterFlag() == 1U) - { - timeout--; - } - tmp = LL_RTC_IsActiveFlag_RS(RTCx); - if (timeout == 0U) - { - status = ERROR; - } - } - - return (status); -} - -/** - * @} - */ - -/** - * @} - */ - -/** - * @} - */ - -#endif /* defined(RTC) */ - -/** - * @} - */ - -#endif /* USE_FULL_LL_DRIVER */ - -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_rtc.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_rtc.h deleted file mode 100644 index 4d157120be2..00000000000 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_rtc.h +++ /dev/null @@ -1,1021 +0,0 @@ -/** - ****************************************************************************** - * @file stm32f1xx_ll_rtc.h - * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 - * @brief Header file of RTC LL module. - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2016 STMicroelectronics

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ - -/* Define to prevent recursive inclusion -------------------------------------*/ -#ifndef __STM32F1xx_LL_RTC_H -#define __STM32F1xx_LL_RTC_H - -#ifdef __cplusplus -extern "C" { -#endif - -/* Includes ------------------------------------------------------------------*/ -#include "stm32f1xx.h" - -/** @addtogroup STM32F1xx_LL_Driver - * @{ - */ - -#if defined(RTC) - -/** @defgroup RTC_LL RTC - * @{ - */ - -/* Private types -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private constants ---------------------------------------------------------*/ - -/* Private macros ------------------------------------------------------------*/ -#if defined(USE_FULL_LL_DRIVER) -/** @defgroup RTC_LL_Private_Macros RTC Private Macros - * @{ - */ -/** - * @} - */ -#endif /*USE_FULL_LL_DRIVER*/ - -/* Exported types ------------------------------------------------------------*/ -#if defined(USE_FULL_LL_DRIVER) -/** @defgroup RTC_LL_ES_INIT RTC Exported Init structure - * @{ - */ - -/** - * @brief RTC Init structures definition - */ -typedef struct -{ - uint32_t AsynchPrescaler; /*!< Specifies the RTC Asynchronous Predivider value. - This parameter must be a number between Min_Data = 0x00 and Max_Data = 0xFFFFF - - This feature can be modified afterwards using unitary function - @ref LL_RTC_SetAsynchPrescaler(). */ - - uint32_t OutPutSource; /*!< Specifies which signal will be routed to the RTC Tamper pin. - This parameter can be a value of @ref LL_RTC_Output_Source - - This feature can be modified afterwards using unitary function - @ref LL_RTC_SetOutputSource(). */ - -} LL_RTC_InitTypeDef; - -/** - * @brief RTC Time structure definition - */ -typedef struct -{ - uint8_t Hours; /*!< Specifies the RTC Time Hours. - This parameter must be a number between Min_Data = 0 and Max_Data = 23 */ - - uint8_t Minutes; /*!< Specifies the RTC Time Minutes. - This parameter must be a number between Min_Data = 0 and Max_Data = 59 */ - - uint8_t Seconds; /*!< Specifies the RTC Time Seconds. - This parameter must be a number between Min_Data = 0 and Max_Data = 59 */ -} LL_RTC_TimeTypeDef; - - -/** - * @brief RTC Alarm structure definition - */ -typedef struct -{ - LL_RTC_TimeTypeDef AlarmTime; /*!< Specifies the RTC Alarm Time members. */ - -} LL_RTC_AlarmTypeDef; - -/** - * @} - */ -#endif /* USE_FULL_LL_DRIVER */ - -/* Exported constants --------------------------------------------------------*/ -/** @defgroup RTC_LL_Exported_Constants RTC Exported Constants - * @{ - */ - -#if defined(USE_FULL_LL_DRIVER) -/** @defgroup RTC_LL_EC_FORMAT FORMAT - * @{ - */ -#define LL_RTC_FORMAT_BIN (0x000000000U) /*!< Binary data format */ -#define LL_RTC_FORMAT_BCD (0x000000001U) /*!< BCD data format */ -/** - * @} - */ -#endif /* USE_FULL_LL_DRIVER */ - -/** @defgroup RTC_LL_EC_BKP BACKUP - * @{ - */ -#if RTC_BKP_NUMBER > 0 -#define LL_RTC_BKP_DR1 (0x00000001U) -#define LL_RTC_BKP_DR2 (0x00000002U) -#define LL_RTC_BKP_DR3 (0x00000003U) -#define LL_RTC_BKP_DR4 (0x00000004U) -#define LL_RTC_BKP_DR5 (0x00000005U) -#define LL_RTC_BKP_DR6 (0x00000006U) -#define LL_RTC_BKP_DR7 (0x00000007U) -#define LL_RTC_BKP_DR8 (0x00000008U) -#define LL_RTC_BKP_DR9 (0x00000009U) -#define LL_RTC_BKP_DR10 (0x0000000AU) -#endif /* RTC_BKP_NUMBER > 0 */ -#if RTC_BKP_NUMBER > 10 -#define LL_RTC_BKP_DR11 (0x0000000BU) -#define LL_RTC_BKP_DR12 (0x0000000CU) -#define LL_RTC_BKP_DR13 (0x0000000DU) -#define LL_RTC_BKP_DR14 (0x0000000EU) -#define LL_RTC_BKP_DR15 (0x0000000FU) -#define LL_RTC_BKP_DR16 (0x00000010U) -#define LL_RTC_BKP_DR17 (0x00000011U) -#define LL_RTC_BKP_DR18 (0x00000012U) -#define LL_RTC_BKP_DR19 (0x00000013U) -#define LL_RTC_BKP_DR20 (0x00000014U) -#define LL_RTC_BKP_DR21 (0x00000015U) -#define LL_RTC_BKP_DR22 (0x00000016U) -#define LL_RTC_BKP_DR23 (0x00000017U) -#define LL_RTC_BKP_DR24 (0x00000018U) -#define LL_RTC_BKP_DR25 (0x00000019U) -#define LL_RTC_BKP_DR26 (0x0000001AU) -#define LL_RTC_BKP_DR27 (0x0000001BU) -#define LL_RTC_BKP_DR28 (0x0000001CU) -#define LL_RTC_BKP_DR29 (0x0000001DU) -#define LL_RTC_BKP_DR30 (0x0000001EU) -#define LL_RTC_BKP_DR31 (0x0000001FU) -#define LL_RTC_BKP_DR32 (0x00000020U) -#define LL_RTC_BKP_DR33 (0x00000021U) -#define LL_RTC_BKP_DR34 (0x00000022U) -#define LL_RTC_BKP_DR35 (0x00000023U) -#define LL_RTC_BKP_DR36 (0x00000024U) -#define LL_RTC_BKP_DR37 (0x00000025U) -#define LL_RTC_BKP_DR38 (0x00000026U) -#define LL_RTC_BKP_DR39 (0x00000027U) -#define LL_RTC_BKP_DR40 (0x00000028U) -#define LL_RTC_BKP_DR41 (0x00000029U) -#define LL_RTC_BKP_DR42 (0x0000002AU) -#endif /* RTC_BKP_NUMBER > 10 */ - -/** - * @} - */ - -/** @defgroup RTC_LL_EC_TAMPLEVEL Tamper Active Level - * @{ - */ -#define LL_RTC_TAMPER_ACTIVELEVEL_LOW BKP_CR_TPAL /*!< A high level on the TAMPER pin resets all data backup registers (if TPE bit is set) */ -#define LL_RTC_TAMPER_ACTIVELEVEL_HIGH (0x00000000U) /*!< A low level on the TAMPER pin resets all data backup registers (if TPE bit is set) */ - -/** - * @} - */ - -/** @defgroup LL_RTC_Output_Source Clock Source to output on the Tamper Pin - * @{ - */ -#define LL_RTC_CALIB_OUTPUT_NONE (0x00000000U) /*!< Calibration output disabled */ -#define LL_RTC_CALIB_OUTPUT_RTCCLOCK BKP_RTCCR_CCO /*!< Calibration output is RTC Clock with a frequency divided by 64 on the TAMPER Pin */ -#define LL_RTC_CALIB_OUTPUT_ALARM BKP_RTCCR_ASOE /*!< Calibration output is Alarm pulse signal on the TAMPER pin */ -#define LL_RTC_CALIB_OUTPUT_SECOND (BKP_RTCCR_ASOS | BKP_RTCCR_ASOE) /*!< Calibration output is Second pulse signal on the TAMPER pin*/ -/** - * @} - */ - -/** - * @} - */ - -/* Exported macro ------------------------------------------------------------*/ -/** @defgroup RTC_LL_Exported_Macros RTC Exported Macros - * @{ - */ - -/** @defgroup RTC_LL_EM_WRITE_READ Common Write and read registers Macros - * @{ - */ - -/** - * @brief Write a value in RTC register - * @param __INSTANCE__ RTC Instance - * @param __REG__ Register to be written - * @param __VALUE__ Value to be written in the register - * @retval None - */ -#define LL_RTC_WriteReg(__INSTANCE__, __REG__, __VALUE__) WRITE_REG(__INSTANCE__->__REG__, (__VALUE__)) - -/** - * @brief Read a value in RTC register - * @param __INSTANCE__ RTC Instance - * @param __REG__ Register to be read - * @retval Register value - */ -#define LL_RTC_ReadReg(__INSTANCE__, __REG__) READ_REG(__INSTANCE__->__REG__) -/** - * @} - */ - -/** @defgroup RTC_LL_EM_Convert Convert helper Macros - * @{ - */ - -/** - * @brief Helper macro to convert a value from 2 digit decimal format to BCD format - * @param __VALUE__ Byte to be converted - * @retval Converted byte - */ -#define __LL_RTC_CONVERT_BIN2BCD(__VALUE__) (uint8_t)((((__VALUE__) / 10U) << 4U) | ((__VALUE__) % 10U)) - -/** - * @brief Helper macro to convert a value from BCD format to 2 digit decimal format - * @param __VALUE__ BCD value to be converted - * @retval Converted byte - */ -#define __LL_RTC_CONVERT_BCD2BIN(__VALUE__) (uint8_t)(((uint8_t)((__VALUE__) & (uint8_t)0xF0U) >> (uint8_t)0x4U) * 10U + ((__VALUE__) & (uint8_t)0x0FU)) - -/** - * @} - */ - -/** - * @} - */ - -/* Exported functions --------------------------------------------------------*/ -/** @defgroup RTC_LL_Exported_Functions RTC Exported Functions - * @{ - */ - -/** @defgroup RTC_LL_EF_Configuration Configuration - * @{ - */ - -/** - * @brief Set Asynchronous prescaler factor - * @rmtoll PRLH PRL LL_RTC_SetAsynchPrescaler\n - * @rmtoll PRLL PRL LL_RTC_SetAsynchPrescaler\n - * @param RTCx RTC Instance - * @param AsynchPrescaler Value between Min_Data = 0 and Max_Data = 0xFFFFF - * @retval None - */ -__STATIC_INLINE void LL_RTC_SetAsynchPrescaler(RTC_TypeDef *RTCx, uint32_t AsynchPrescaler) -{ - MODIFY_REG(RTCx->PRLH, RTC_PRLH_PRL, (AsynchPrescaler >> 16)); - MODIFY_REG(RTCx->PRLL, RTC_PRLL_PRL, (AsynchPrescaler & RTC_PRLL_PRL)); -} - -/** - * @brief Get Asynchronous prescaler factor - * @rmtoll DIVH DIV LL_RTC_GetDivider\n - * @rmtoll DIVL DIV LL_RTC_GetDivider\n - * @param RTCx RTC Instance - * @retval Value between Min_Data = 0 and Max_Data = 0xFFFFF - */ -__STATIC_INLINE uint32_t LL_RTC_GetDivider(RTC_TypeDef *RTCx) -{ - register uint16_t Highprescaler = 0 , Lowprescaler = 0; - Highprescaler = READ_REG(RTCx->DIVH & RTC_DIVH_RTC_DIV); - Lowprescaler = READ_REG(RTCx->DIVL & RTC_DIVL_RTC_DIV); - - return (((uint32_t) Highprescaler << 16U) | Lowprescaler); -} - -/** - * @brief Set Output Source - * @rmtoll RTCCR CCO LL_RTC_SetOutputSource - * @rmtoll RTCCR ASOE LL_RTC_SetOutputSource - * @rmtoll RTCCR ASOS LL_RTC_SetOutputSource - * @param BKPx BKP Instance - * @param OutputSource This parameter can be one of the following values: - * @arg @ref LL_RTC_CALIB_OUTPUT_NONE - * @arg @ref LL_RTC_CALIB_OUTPUT_RTCCLOCK - * @arg @ref LL_RTC_CALIB_OUTPUT_ALARM - * @arg @ref LL_RTC_CALIB_OUTPUT_SECOND - * @retval None - */ -__STATIC_INLINE void LL_RTC_SetOutputSource(BKP_TypeDef *BKPx, uint32_t OutputSource) -{ - MODIFY_REG(BKPx->RTCCR, (BKP_RTCCR_CCO | BKP_RTCCR_ASOE | BKP_RTCCR_ASOS), OutputSource); -} - -/** - * @brief Get Output Source - * @rmtoll RTCCR CCO LL_RTC_GetOutPutSource - * @rmtoll RTCCR ASOE LL_RTC_GetOutPutSource - * @rmtoll RTCCR ASOS LL_RTC_GetOutPutSource - * @param BKPx BKP Instance - * @retval Returned value can be one of the following values: - * @arg @ref LL_RTC_CALIB_OUTPUT_NONE - * @arg @ref LL_RTC_CALIB_OUTPUT_RTCCLOCK - * @arg @ref LL_RTC_CALIB_OUTPUT_ALARM - * @arg @ref LL_RTC_CALIB_OUTPUT_SECOND - */ -__STATIC_INLINE uint32_t LL_RTC_GetOutPutSource(BKP_TypeDef *BKPx) -{ - return (uint32_t)(READ_BIT(BKPx->RTCCR, (BKP_RTCCR_CCO | BKP_RTCCR_ASOE | BKP_RTCCR_ASOS))); -} - -/** - * @brief Enable the write protection for RTC registers. - * @rmtoll CRL CNF LL_RTC_EnableWriteProtection - * @param RTCx RTC Instance - * @retval None - */ -__STATIC_INLINE void LL_RTC_EnableWriteProtection(RTC_TypeDef *RTCx) -{ - CLEAR_BIT(RTCx->CRL, RTC_CRL_CNF); -} - -/** - * @brief Disable the write protection for RTC registers. - * @rmtoll CRL RTC_CRL_CNF LL_RTC_DisableWriteProtection - * @param RTCx RTC Instance - * @retval None - */ -__STATIC_INLINE void LL_RTC_DisableWriteProtection(RTC_TypeDef *RTCx) -{ - SET_BIT(RTCx->CRL, RTC_CRL_CNF); -} - -/** - * @} - */ - -/** @defgroup RTC_LL_EF_Time Time - * @{ - */ - -/** - * @brief Set time counter in BCD format - * @note Bit is write-protected. @ref LL_RTC_DisableWriteProtection function should be called before. - * @note It can be written in initialization mode only (@ref LL_RTC_EnterInitMode function) - * @rmtoll CNTH CNT LL_RTC_TIME_Set\n - * CNTL CNT LL_RTC_TIME_Set\n - * @param RTCx RTC Instance - * @param TimeCounter Value between Min_Data=0x00 and Max_Data=0xFFFFF - * @retval None - */ -__STATIC_INLINE void LL_RTC_TIME_Set(RTC_TypeDef *RTCx, uint32_t TimeCounter) -{ - /* Set RTC COUNTER MSB word */ - WRITE_REG(RTCx->CNTH, (TimeCounter >> 16U)); - /* Set RTC COUNTER LSB word */ - WRITE_REG(RTCx->CNTL, (TimeCounter & RTC_CNTL_RTC_CNT)); -} - -/** - * @brief Get time counter in BCD format - * @rmtoll CNTH CNT LL_RTC_TIME_Get\n - * CNTL CNT LL_RTC_TIME_Get\n - * @param RTCx RTC Instance - * @retval Value between Min_Data = 0 and Max_Data = 0xFFFFF - */ -__STATIC_INLINE uint32_t LL_RTC_TIME_Get(RTC_TypeDef *RTCx) -{ - register uint16_t high = 0, low = 0; - - high = READ_REG(RTCx->CNTH & RTC_CNTH_RTC_CNT); - low = READ_REG(RTCx->CNTL & RTC_CNTL_RTC_CNT); - return ((uint32_t)(((uint32_t) high << 16U) | low)); -} - -/** - * @} - */ - -/** @defgroup RTC_LL_EF_ALARM ALARM - * @{ - */ - -/** - * @brief Set Alarm Counter - * @note Bit is write-protected. @ref LL_RTC_DisableWriteProtection function should be called before. - * @rmtoll ALRH ALR LL_RTC_ALARM_Set\n - * @rmtoll ALRL ALR LL_RTC_ALARM_Set\n - * @param RTCx RTC Instance - * @param AlarmCounter Value between Min_Data=0x00 and Max_Data=0xFFFFF - * @retval None - */ -__STATIC_INLINE void LL_RTC_ALARM_Set(RTC_TypeDef *RTCx, uint32_t AlarmCounter) -{ - /* Set RTC COUNTER MSB word */ - WRITE_REG(RTCx->ALRH, (AlarmCounter >> 16)); - /* Set RTC COUNTER LSB word */ - WRITE_REG(RTCx->ALRL, (AlarmCounter & RTC_ALRL_RTC_ALR)); -} - -/** - * @brief Get Alarm Counter - * @note Bit is write-protected. @ref LL_RTC_DisableWriteProtection function should be called before. - * @rmtoll ALRH ALR LL_RTC_ALARM_Get\n - * @rmtoll ALRL ALR LL_RTC_ALARM_Get\n - * @param RTCx RTC Instance - * @retval None - */ -__STATIC_INLINE uint32_t LL_RTC_ALARM_Get(RTC_TypeDef *RTCx) -{ - register uint16_t high = 0, low = 0; - - high = READ_REG(RTCx->ALRH & RTC_ALRH_RTC_ALR); - low = READ_REG(RTCx->ALRL & RTC_ALRL_RTC_ALR); - - return (((uint32_t) high << 16U) | low); -} - -/** - * @} - */ - -/** @defgroup RTC_LL_EF_Tamper Tamper - * @{ - */ - -/** - * @brief Enable RTC_TAMPx input detection - * @rmtoll CR TPE LL_RTC_TAMPER_Enable\n - * @retval None - */ -__STATIC_INLINE void LL_RTC_TAMPER_Enable(BKP_TypeDef *BKPx) -{ - SET_BIT(BKPx->CR, BKP_CR_TPE); -} - -/** - * @brief Disable RTC_TAMPx Tamper - * @rmtoll CR TPE LL_RTC_TAMPER_Disable\n - * @retval None - */ -__STATIC_INLINE void LL_RTC_TAMPER_Disable(BKP_TypeDef *BKPx) -{ - CLEAR_BIT(BKP->CR, BKP_CR_TPE); -} - -/** - * @brief Enable Active level for Tamper input - * @rmtoll CR TPAL LL_RTC_TAMPER_SetActiveLevel\n - * @param BKPx BKP Instance - * @param Tamper This parameter can be a combination of the following values: - * @arg @ref LL_RTC_TAMPER_ACTIVELEVEL_LOW - * @arg @ref LL_RTC_TAMPER_ACTIVELEVEL_HIGH - * @retval None - */ -__STATIC_INLINE void LL_RTC_TAMPER_SetActiveLevel(BKP_TypeDef *BKPx, uint32_t Tamper) -{ - MODIFY_REG(BKPx->CR, BKP_CR_TPAL, Tamper); -} - -/** - * @brief Disable Active level for Tamper input - * @rmtoll CR TPAL LL_RTC_TAMPER_SetActiveLevel\n - * @retval None - */ -__STATIC_INLINE uint32_t LL_RTC_TAMPER_GetActiveLevel(BKP_TypeDef *BKPx) -{ - return (uint32_t)(READ_BIT(BKPx->CR, BKP_CR_TPAL)); -} - -/** - * @} - */ - -/** @defgroup RTC_LL_EF_Backup_Registers Backup_Registers - * @{ - */ - -/** - * @brief Writes a data in a specified RTC Backup data register. - * @rmtoll BKPDR DR LL_RTC_BKP_SetRegister - * @param BKPx BKP Instance - * @param BackupRegister This parameter can be one of the following values: - * @arg @ref LL_RTC_BKP_DR1 - * @arg @ref LL_RTC_BKP_DR2 - * @arg @ref LL_RTC_BKP_DR3 - * @arg @ref LL_RTC_BKP_DR4 - * @arg @ref LL_RTC_BKP_DR5 - * @arg @ref LL_RTC_BKP_DR6 - * @arg @ref LL_RTC_BKP_DR7 - * @arg @ref LL_RTC_BKP_DR8 - * @arg @ref LL_RTC_BKP_DR9 - * @arg @ref LL_RTC_BKP_DR10 - * @arg @ref LL_RTC_BKP_DR11 (*) - * @arg @ref LL_RTC_BKP_DR12 (*) - * @arg @ref LL_RTC_BKP_DR13 (*) - * @arg @ref LL_RTC_BKP_DR14 (*) - * @arg @ref LL_RTC_BKP_DR15 (*) - * @arg @ref LL_RTC_BKP_DR16 (*) - * @arg @ref LL_RTC_BKP_DR17 (*) - * @arg @ref LL_RTC_BKP_DR18 (*) - * @arg @ref LL_RTC_BKP_DR19 (*) - * @arg @ref LL_RTC_BKP_DR20 (*) - * @arg @ref LL_RTC_BKP_DR21 (*) - * @arg @ref LL_RTC_BKP_DR22 (*) - * @arg @ref LL_RTC_BKP_DR23 (*) - * @arg @ref LL_RTC_BKP_DR24 (*) - * @arg @ref LL_RTC_BKP_DR25 (*) - * @arg @ref LL_RTC_BKP_DR26 (*) - * @arg @ref LL_RTC_BKP_DR27 (*) - * @arg @ref LL_RTC_BKP_DR28 (*) - * @arg @ref LL_RTC_BKP_DR29 (*) - * @arg @ref LL_RTC_BKP_DR30 (*) - * @arg @ref LL_RTC_BKP_DR31 (*) - * @arg @ref LL_RTC_BKP_DR32 (*) - * @arg @ref LL_RTC_BKP_DR33 (*) - * @arg @ref LL_RTC_BKP_DR34 (*) - * @arg @ref LL_RTC_BKP_DR35 (*) - * @arg @ref LL_RTC_BKP_DR36 (*) - * @arg @ref LL_RTC_BKP_DR37 (*) - * @arg @ref LL_RTC_BKP_DR38 (*) - * @arg @ref LL_RTC_BKP_DR39 (*) - * @arg @ref LL_RTC_BKP_DR40 (*) - * @arg @ref LL_RTC_BKP_DR41 (*) - * @arg @ref LL_RTC_BKP_DR42 (*) - * (*) value not defined in all devices. - * @param Data Value between Min_Data=0x00 and Max_Data=0xFFFFFFFF - * @retval None - */ -__STATIC_INLINE void LL_RTC_BKP_SetRegister(BKP_TypeDef *BKPx, uint32_t BackupRegister, uint32_t Data) -{ - register uint32_t tmp = 0U; - - tmp = (uint32_t)BKP_BASE; - tmp += (BackupRegister * 4U); - - /* Write the specified register */ - *(__IO uint32_t *)tmp = (uint32_t)Data; -} - -/** - * @brief Reads data from the specified RTC Backup data Register. - * @rmtoll BKPDR DR LL_RTC_BKP_GetRegister - * @param BKPx BKP Instance - * @param BackupRegister This parameter can be one of the following values: - * @arg @ref LL_RTC_BKP_DR1 - * @arg @ref LL_RTC_BKP_DR2 - * @arg @ref LL_RTC_BKP_DR3 - * @arg @ref LL_RTC_BKP_DR4 - * @arg @ref LL_RTC_BKP_DR5 - * @arg @ref LL_RTC_BKP_DR6 - * @arg @ref LL_RTC_BKP_DR7 - * @arg @ref LL_RTC_BKP_DR8 - * @arg @ref LL_RTC_BKP_DR9 - * @arg @ref LL_RTC_BKP_DR10 - * @arg @ref LL_RTC_BKP_DR11 (*) - * @arg @ref LL_RTC_BKP_DR12 (*) - * @arg @ref LL_RTC_BKP_DR13 (*) - * @arg @ref LL_RTC_BKP_DR14 (*) - * @arg @ref LL_RTC_BKP_DR15 (*) - * @arg @ref LL_RTC_BKP_DR16 (*) - * @arg @ref LL_RTC_BKP_DR17 (*) - * @arg @ref LL_RTC_BKP_DR18 (*) - * @arg @ref LL_RTC_BKP_DR19 (*) - * @arg @ref LL_RTC_BKP_DR20 (*) - * @arg @ref LL_RTC_BKP_DR21 (*) - * @arg @ref LL_RTC_BKP_DR22 (*) - * @arg @ref LL_RTC_BKP_DR23 (*) - * @arg @ref LL_RTC_BKP_DR24 (*) - * @arg @ref LL_RTC_BKP_DR25 (*) - * @arg @ref LL_RTC_BKP_DR26 (*) - * @arg @ref LL_RTC_BKP_DR27 (*) - * @arg @ref LL_RTC_BKP_DR28 (*) - * @arg @ref LL_RTC_BKP_DR29 (*) - * @arg @ref LL_RTC_BKP_DR30 (*) - * @arg @ref LL_RTC_BKP_DR31 (*) - * @arg @ref LL_RTC_BKP_DR32 (*) - * @arg @ref LL_RTC_BKP_DR33 (*) - * @arg @ref LL_RTC_BKP_DR34 (*) - * @arg @ref LL_RTC_BKP_DR35 (*) - * @arg @ref LL_RTC_BKP_DR36 (*) - * @arg @ref LL_RTC_BKP_DR37 (*) - * @arg @ref LL_RTC_BKP_DR38 (*) - * @arg @ref LL_RTC_BKP_DR39 (*) - * @arg @ref LL_RTC_BKP_DR40 (*) - * @arg @ref LL_RTC_BKP_DR41 (*) - * @arg @ref LL_RTC_BKP_DR42 (*) - * @retval Value between Min_Data=0x00 and Max_Data=0xFFFFFFFF - */ -__STATIC_INLINE uint32_t LL_RTC_BKP_GetRegister(BKP_TypeDef *BKPx, uint32_t BackupRegister) -{ - register uint32_t tmp = 0U; - - tmp = (uint32_t)BKP_BASE; - tmp += (BackupRegister * 4U); - - /* Read the specified register */ - return ((*(__IO uint32_t *)tmp) & BKP_DR1_D); -} - -/** - * @} - */ - -/** @defgroup RTC_LL_EF_Calibration Calibration - * @{ - */ - -/** - * @brief Set the coarse digital calibration - * @note Bit is write-protected. @ref LL_RTC_DisableWriteProtection function should be called before. - * @note It can be written in initialization mode only (@ref LL_RTC_EnterInitMode function) - * @rmtoll RTCCR CAL LL_RTC_CAL_SetCoarseDigital\n - * @param BKPx RTC Instance - * @param Value value of coarse calibration expressed in ppm (coded on 5 bits) - * @note This Calibration value should be between 0 and 121 when using positive sign with a 4-ppm step. - * @retval None - */ -__STATIC_INLINE void LL_RTC_CAL_SetCoarseDigital(BKP_TypeDef* BKPx, uint32_t Value) -{ - MODIFY_REG(BKPx->RTCCR,BKP_RTCCR_CAL, Value); -} - -/** - * @brief Get the coarse digital calibration value - * @rmtoll RTCCR CAL LL_RTC_CAL_SetCoarseDigital\n - * @param BKPx BKP Instance - * @retval value of coarse calibration expressed in ppm (coded on 5 bits) - */ -__STATIC_INLINE uint32_t LL_RTC_CAL_GetCoarseDigital(BKP_TypeDef *BKPx) -{ - return (uint32_t)(READ_BIT(BKPx->RTCCR, BKP_RTCCR_CAL)); -} -/** - * @} - */ - -/** @defgroup RTC_LL_EF_FLAG_Management FLAG_Management - * @{ - */ - -/** - * @brief Get RTC_TAMPI Interruption detection flag - * @rmtoll CSR TIF LL_RTC_IsActiveFlag_TAMPI - * @param BKPx BKP Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_RTC_IsActiveFlag_TAMPI(BKP_TypeDef *BKPx) -{ - return (READ_BIT(BKPx->CSR, BKP_CSR_TIF) == (BKP_CSR_TIF)); -} - -/** - * @brief Clear RTC_TAMP Interruption detection flag - * @rmtoll CSR CTI LL_RTC_ClearFlag_TAMPI - * @param BKPx BKP Instance - * @retval None - */ -__STATIC_INLINE void LL_RTC_ClearFlag_TAMPI(BKP_TypeDef *BKPx) -{ - SET_BIT(BKPx->CSR, BKP_CSR_CTI); -} - -/** - * @brief Get RTC_TAMPE Event detection flag - * @rmtoll CSR TEF LL_RTC_IsActiveFlag_TAMPE - * @param BKPx BKP Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_RTC_IsActiveFlag_TAMPE(BKP_TypeDef *BKPx) -{ - return (READ_BIT(BKPx->CSR, BKP_CSR_TEF) == (BKP_CSR_TEF)); -} - -/** - * @brief Clear RTC_TAMPE Even detection flag - * @rmtoll CSR CTE LL_RTC_ClearFlag_TAMPE - * @param BKPx BKP Instance - * @retval None - */ -__STATIC_INLINE void LL_RTC_ClearFlag_TAMPE(BKP_TypeDef *BKPx) -{ - SET_BIT(BKPx->CSR, BKP_CSR_CTE); -} - -/** - * @brief Get Alarm flag - * @rmtoll CRL ALRF LL_RTC_IsActiveFlag_ALR - * @param RTCx RTC Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_RTC_IsActiveFlag_ALR(RTC_TypeDef *RTCx) -{ - return (READ_BIT(RTCx->CRL, RTC_CRL_ALRF) == (RTC_CRL_ALRF)); -} - -/** - * @brief Clear Alarm flag - * @rmtoll CRL ALRF LL_RTC_ClearFlag_ALR - * @param RTCx RTC Instance - * @retval None - */ -__STATIC_INLINE void LL_RTC_ClearFlag_ALR(RTC_TypeDef *RTCx) -{ - CLEAR_BIT(RTCx->CRL, RTC_CRL_ALRF); -} - -/** - * @brief Get Registers synchronization flag - * @rmtoll CRL RSF LL_RTC_IsActiveFlag_RS - * @param RTCx RTC Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_RTC_IsActiveFlag_RS(RTC_TypeDef *RTCx) -{ - return (READ_BIT(RTCx->CRL, RTC_CRL_RSF) == (RTC_CRL_RSF)); -} - -/** - * @brief Clear Registers synchronization flag - * @rmtoll CRL RSF LL_RTC_ClearFlag_RS - * @param RTCx RTC Instance - * @retval None - */ -__STATIC_INLINE void LL_RTC_ClearFlag_RS(RTC_TypeDef *RTCx) -{ - CLEAR_BIT(RTCx->CRL, RTC_CRL_RSF); -} - -/** - * @brief Get Registers OverFlow flag - * @rmtoll CRL OWF LL_RTC_IsActiveFlag_OW - * @param RTCx RTC Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_RTC_IsActiveFlag_OW(RTC_TypeDef *RTCx) -{ - return (READ_BIT(RTCx->CRL, RTC_CRL_OWF) == (RTC_CRL_OWF)); -} - -/** - * @brief Clear Registers OverFlow flag - * @rmtoll CRL OWF LL_RTC_ClearFlag_OW - * @param RTCx RTC Instance - * @retval None - */ -__STATIC_INLINE void LL_RTC_ClearFlag_OW(RTC_TypeDef *RTCx) -{ - CLEAR_BIT(RTCx->CRL, RTC_CRL_OWF); -} - -/** - * @brief Get Registers synchronization flag - * @rmtoll CRL SECF LL_RTC_IsActiveFlag_SEC - * @param RTCx RTC Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_RTC_IsActiveFlag_SEC(RTC_TypeDef *RTCx) -{ - return (READ_BIT(RTCx->CRL, RTC_CRL_SECF) == (RTC_CRL_SECF)); -} - -/** - * @brief Clear Registers synchronization flag - * @rmtoll CRL SECF LL_RTC_ClearFlag_SEC - * @param RTCx RTC Instance - * @retval None - */ -__STATIC_INLINE void LL_RTC_ClearFlag_SEC(RTC_TypeDef *RTCx) -{ - CLEAR_BIT(RTCx->CRL, RTC_CRL_SECF); -} - -/** - * @brief Get RTC Operation OFF status flag - * @rmtoll CRL RTOFF LL_RTC_IsActiveFlag_RTOF - * @param RTCx RTC Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_RTC_IsActiveFlag_RTOF(RTC_TypeDef *RTCx) -{ - return (READ_BIT(RTCx->CRL, RTC_CRL_RTOFF) == (RTC_CRL_RTOFF)); -} - -/** - * @} - */ - -/** @defgroup RTC_LL_EF_IT_Management IT_Management - * @{ - */ - -/** - * @brief Enable Alarm interrupt - * @note Bit is write-protected. @ref LL_RTC_DisableWriteProtection function should be called before. - * @rmtoll CRH ALRIE LL_RTC_EnableIT_ALR - * @param RTCx RTC Instance - * @retval None - */ -__STATIC_INLINE void LL_RTC_EnableIT_ALR(RTC_TypeDef *RTCx) -{ - SET_BIT(RTCx->CRH, RTC_CRH_ALRIE); -} - -/** - * @brief Disable Alarm interrupt - * @note Bit is write-protected. @ref LL_RTC_DisableWriteProtection function should be called before. - * @rmtoll CRH ALRIE LL_RTC_DisableIT_ALR - * @param RTCx RTC Instance - * @retval None - */ -__STATIC_INLINE void LL_RTC_DisableIT_ALR(RTC_TypeDef *RTCx) -{ - CLEAR_BIT(RTCx->CRH, RTC_CRH_ALRIE); -} - -/** - * @brief Check if Alarm interrupt is enabled or not - * @rmtoll CRH ALRIE LL_RTC_IsEnabledIT_ALR - * @param RTCx RTC Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_RTC_IsEnabledIT_ALR(RTC_TypeDef *RTCx) -{ - return (READ_BIT(RTCx->CRH, RTC_CRH_ALRIE) == (RTC_CRH_ALRIE)); -} - -/** - * @brief Enable Second Interrupt interrupt - * @note Bit is write-protected. @ref LL_RTC_DisableWriteProtection function should be called before. - * @rmtoll CRH SECIE LL_RTC_EnableIT_SEC - * @param RTCx RTC Instance - * @retval None - */ -__STATIC_INLINE void LL_RTC_EnableIT_SEC(RTC_TypeDef *RTCx) -{ - SET_BIT(RTCx->CRH, RTC_CRH_SECIE); -} - -/** - * @brief Disable Second interrupt - * @note Bit is write-protected. @ref LL_RTC_DisableWriteProtection function should be called before. - * @rmtoll CRH SECIE LL_RTC_DisableIT_SEC - * @param RTCx RTC Instance - * @retval None - */ -__STATIC_INLINE void LL_RTC_DisableIT_SEC(RTC_TypeDef *RTCx) -{ - CLEAR_BIT(RTCx->CRH, RTC_CRH_SECIE); -} - -/** - * @brief Check if Second interrupt is enabled or not - * @rmtoll CRH SECIE LL_RTC_IsEnabledIT_SEC - * @param RTCx RTC Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_RTC_IsEnabledIT_SEC(RTC_TypeDef *RTCx) -{ - return (READ_BIT(RTCx->CRH, RTC_CRH_SECIE) == (RTC_CRH_SECIE)); -} - -/** - * @brief Enable OverFlow interrupt - * @note Bit is write-protected. @ref LL_RTC_DisableWriteProtection function should be called before. - * @rmtoll CRH OWIE LL_RTC_EnableIT_OW - * @param RTCx RTC Instance - * @retval None - */ -__STATIC_INLINE void LL_RTC_EnableIT_OW(RTC_TypeDef *RTCx) -{ - SET_BIT(RTCx->CRH, RTC_CRH_OWIE); -} - -/** - * @brief Disable OverFlow interrupt - * @note Bit is write-protected. @ref LL_RTC_DisableWriteProtection function should be called before. - * @rmtoll CRH OWIE LL_RTC_DisableIT_OW - * @param RTCx RTC Instance - * @retval None - */ -__STATIC_INLINE void LL_RTC_DisableIT_OW(RTC_TypeDef *RTCx) -{ - CLEAR_BIT(RTCx->CRH, RTC_CRH_OWIE); -} - -/** - * @brief Check if OverFlow interrupt is enabled or not - * @rmtoll CRH OWIE LL_RTC_IsEnabledIT_OW - * @param RTCx RTC Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_RTC_IsEnabledIT_OW(RTC_TypeDef *RTCx) -{ - return (READ_BIT(RTCx->CRH, RTC_CRH_OWIE) == (RTC_CRH_OWIE)); -} - -/** - * @brief Enable Tamper interrupt - * @rmtoll CSR TPIE LL_RTC_EnableIT_TAMP - * @param BKPx BKP Instance - * @retval None - */ -__STATIC_INLINE void LL_RTC_EnableIT_TAMP(BKP_TypeDef *BKPx) -{ - SET_BIT(BKPx->CSR,BKP_CSR_TPIE); -} - -/** - * @brief Disable Tamper interrupt - * @rmtoll CSR TPIE LL_RTC_EnableIT_TAMP - * @param BKPx BKP Instance - * @retval None - */ -__STATIC_INLINE void LL_RTC_DisableIT_TAMP(BKP_TypeDef *BKPx) -{ - CLEAR_BIT(BKPx->CSR,BKP_CSR_TPIE); -} - -/** - * @brief Check if all the TAMPER interrupts are enabled or not - * @rmtoll CSR TPIE LL_RTC_IsEnabledIT_TAMP - * @param BKPx BKP Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_RTC_IsEnabledIT_TAMP(BKP_TypeDef *BKPx) -{ - return (READ_BIT(BKPx->CSR,BKP_CSR_TPIE) == BKP_CSR_TPIE); -} -/** - * @} - */ - -#if defined(USE_FULL_LL_DRIVER) -/** @defgroup RTC_LL_EF_Init Initialization and de-initialization functions - * @{ - */ - -ErrorStatus LL_RTC_DeInit(RTC_TypeDef *RTCx); -ErrorStatus LL_RTC_Init(RTC_TypeDef *RTCx, LL_RTC_InitTypeDef *RTC_InitStruct); -void LL_RTC_StructInit(LL_RTC_InitTypeDef *RTC_InitStruct); -ErrorStatus LL_RTC_TIME_Init(RTC_TypeDef *RTCx, uint32_t RTC_Format, LL_RTC_TimeTypeDef *RTC_TimeStruct); -void LL_RTC_TIME_StructInit(LL_RTC_TimeTypeDef *RTC_TimeStruct); -ErrorStatus LL_RTC_ALARM_Init(RTC_TypeDef *RTCx, uint32_t RTC_Format, LL_RTC_AlarmTypeDef *RTC_AlarmStruct); -void LL_RTC_ALARM_StructInit(LL_RTC_AlarmTypeDef *RTC_AlarmStruct); -ErrorStatus LL_RTC_EnterInitMode(RTC_TypeDef *RTCx); -ErrorStatus LL_RTC_ExitInitMode(RTC_TypeDef *RTCx); -ErrorStatus LL_RTC_WaitForSynchro(RTC_TypeDef *RTCx); -ErrorStatus LL_RTC_TIME_SetCounter(RTC_TypeDef *RTCx, uint32_t TimeCounter); -ErrorStatus LL_RTC_ALARM_SetCounter(RTC_TypeDef *RTCx, uint32_t AlarmCounter); - -/** - * @} - */ -#endif /* USE_FULL_LL_DRIVER */ - -/** - * @} - */ - -/** - * @} - */ - -/** - * @} - */ - -#endif /* defined(RTC) */ - -/** - * @} - */ - -#ifdef __cplusplus -} -#endif - -#endif /* __STM32F1xx_LL_RTC_H */ - -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_sdmmc.c b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_sdmmc.c index f8d04bc1171..d3eccbf236b 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_sdmmc.c +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_sdmmc.c @@ -2,12 +2,12 @@ ****************************************************************************** * @file stm32f1xx_ll_sdmmc.c * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 - * @brief SDIO Low Layer HAL module driver. + * @version V1.0.5 + * @date 06-December-2016 + * @brief SDMMC Low Layer HAL module driver. * * This file provides firmware functions to manage the following - * functionalities of the SDIO peripheral: + * functionalities of the SDMMC peripheral: * + Initialization/de-initialization functions * + I/O operation functions * + Peripheral Control functions @@ -17,11 +17,11 @@ ============================================================================== ##### SDMMC peripheral features ##### ============================================================================== - [..] The SD/SDMMC MMC card host interface (SDMMC) provides an interface between the APB2 - peripheral bus and MultiMedia cards (MMCs), SD memory cards, SDMMC cards and CE-ATA + [..] The SD/SDIO MMC card host interface (SDIO) provides an interface between the APB2 + peripheral bus and MultiMedia cards (MMCs), SD memory cards, SDIO cards and CE-ATA devices. - - [..] The SDMMC features include the following: + + [..] The SDIO features include the following: (+) Full compliance with MultiMedia Card System Specification Version 4.2. Card support for three different databus modes: 1-bit (default), 4-bit and 8-bit (+) Full compatibility with previous versions of MultiMedia Cards (forward compatibility) @@ -38,9 +38,9 @@ ============================================================================== [..] This driver is a considered as a driver of service for external devices drivers - that interfaces with the SDMMC peripheral. - According to the device used (SD card/ MMC card / SDMMC card ...), a set of APIs - is used in the device's driver to perform SDMMC operations and functionalities. + that interfaces with the SDIO peripheral. + According to the device used (SD card/ MMC card / SDIO card ...), a set of APIs + is used in the device's driver to perform SDIO operations and functionalities. This driver is almost transparent for the final user, it is only used to implement other functionalities of the external device. @@ -50,10 +50,10 @@ (++) SDIO adapter clock (SDIOCLK = HCLK) (++) AHB bus clock (HCLK/2) - -@@- PCLK2 and SDMMC_CK clock frequencies must respect the following condition: - Frequency(PCLK2) >= (3 / 8 x Frequency(SDMMC_CK)) + -@@- PCLK2 and SDIO_CK clock frequencies must respect the following condition: + Frequency(PCLK2) >= (3 / 8 x Frequency(SDIO_CK)) - (+) Enable/Disable peripheral clock using RCC peripheral macros related to SDMMC + (+) Enable/Disable peripheral clock using RCC peripheral macros related to SDIO peripheral. (+) Enable the Power ON State using the SDIO_PowerState_ON(SDIOx) @@ -84,11 +84,11 @@ -@@- To check if the command is well received, read the SDIO_CMDRESP register using the SDIO_GetCommandResponse(). - The SDMMC responses registers (SDIO_RESP1 to SDIO_RESP2), use the + The SDIO responses registers (SDIO_RESP1 to SDIO_RESP2), use the SDIO_GetResponse() function. (+) To control the DPSM (Data Path State Machine) and send/receive - data to/from the card use the SDIO_ConfigData(), SDIO_GetDataCounter(), + data to/from the card use the SDIO_DataConfig(), SDIO_GetDataCounter(), SDIO_ReadFIFO(), SDIO_WriteFIFO() and SDIO_GetFIFOCount() functions. *** Read Operations *** @@ -100,14 +100,14 @@ (++) Data TimeOut (++) Data Length (++) Data Block size - (++) Data Transfer direction: should be from card (To SDMMC) + (++) Data Transfer direction: should be from card (To SDIO) (++) Data Transfer mode (++) DPSM Status (Enable or Disable) - (#) Configure the SDMMC resources to receive the data from the card - according to selected transfer mode (Refer to Step 8, 9 and 10). + (#) Configure the SDIO resources to receive the data from the card + according to selected transfer mode. - (#) Send the selected Read command (refer to step 11). + (#) Send the selected Read command. (#) Use the SDIO flags/interrupts to check the transfer status. @@ -124,27 +124,18 @@ (++) Data Transfer mode (++) DPSM Status (Enable or Disable) - (#) Configure the SDMMC resources to send the data to the card according to + (#) Configure the SDIO resources to send the data to the card according to selected transfer mode. (#) Send the selected Write command. (#) Use the SDIO flags/interrupts to check the transfer status. - - *** Command management operations *** - ===================================== - [..] - (#) The commands used for Read/Write//Erase operations are managed in - separate functions. - Each function allows to send the needed command with the related argument, - then check the response. - By the same approach, you could implement a command and check the response. @endverbatim ****************************************************************************** * @attention * - *

© COPYRIGHT(c) 2017 STMicroelectronics

+ *

© COPYRIGHT(c) 2016 STMicroelectronics

* * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: @@ -174,6 +165,7 @@ /* Includes ------------------------------------------------------------------*/ #include "stm32f1xx_hal.h" +#if defined (HAL_SD_MODULE_ENABLED) || defined(HAL_MMC_MODULE_ENABLED) #if defined(STM32F103xE) || defined(STM32F103xG) @@ -182,30 +174,22 @@ */ /** @defgroup SDMMC_LL SDMMC Low Layer - * @brief Low layer module for SD + * @brief Low layer module for SD and MMC driver * @{ */ -#if defined (HAL_SD_MODULE_ENABLED) || defined(HAL_MMC_MODULE_ENABLED) /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ -static uint32_t SDMMC_GetCmdError(SDIO_TypeDef *SDIOx); -static uint32_t SDMMC_GetCmdResp1(SDIO_TypeDef *SDIOx, uint8_t SD_CMD, uint32_t Timeout); -static uint32_t SDMMC_GetCmdResp2(SDIO_TypeDef *SDIOx); -static uint32_t SDMMC_GetCmdResp3(SDIO_TypeDef *SDIOx); -static uint32_t SDMMC_GetCmdResp7(SDIO_TypeDef *SDIOx); -static uint32_t SDMMC_GetCmdResp6(SDIO_TypeDef *SDIOx, uint8_t SD_CMD, uint16_t *pRCA); - -/* Exported functions --------------------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ -/** @defgroup SDMMC_LL_Exported_Functions SDMMC Low Layer Exported Functions +/** @defgroup SDMMC_LL_Exported_Functions SDMMC_LL Exported Functions * @{ */ -/** @defgroup HAL_SDMMC_LL_Group1 Initialization de-initialization functions +/** @defgroup HAL_SDMMC_LL_Group1 Initialization and de-initialization functions * @brief Initialization and Configuration functions * @verbatim @@ -219,16 +203,14 @@ static uint32_t SDMMC_GetCmdResp6(SDIO_TypeDef *SDIOx, uint8_t SD_CMD, uint16_t */ /** - * @brief Initializes the SDMMC according to the specified - * parameters in the SDMMC_InitTypeDef and create the associated handle. - * @param SDIOx: Pointer to SDMMC register base - * @param Init: SDMMC initialization structure + * @brief Initializes the SDIO according to the specified + * parameters in the SDIO_InitTypeDef and create the associated handle. + * @param SDIOx: Pointer to SDIO register base + * @param Init: SDIO initialization structure * @retval HAL status */ HAL_StatusTypeDef SDIO_Init(SDIO_TypeDef *SDIOx, SDIO_InitTypeDef Init) { - uint32_t tmpreg = 0U; - /* Check the parameters */ assert_param(IS_SDIO_ALL_INSTANCE(SDIOx)); assert_param(IS_SDIO_CLOCK_EDGE(Init.ClockEdge)); @@ -238,22 +220,18 @@ HAL_StatusTypeDef SDIO_Init(SDIO_TypeDef *SDIOx, SDIO_InitTypeDef Init) assert_param(IS_SDIO_HARDWARE_FLOW_CONTROL(Init.HardwareFlowControl)); assert_param(IS_SDIO_CLKDIV(Init.ClockDiv)); - /* Set SDMMC configuration parameters */ - tmpreg |= (Init.ClockEdge |\ - Init.ClockBypass |\ - Init.ClockPowerSave |\ - Init.BusWide |\ - Init.HardwareFlowControl |\ - Init.ClockDiv - ); - - /* Write to SDMMC CLKCR */ - MODIFY_REG(SDIOx->CLKCR, CLKCR_CLEAR_MASK, tmpreg); + /* Set SDIO configuration parameters */ + /* Write to SDIO CLKCR */ + MODIFY_REG(SDIOx->CLKCR, CLKCR_CLEAR_MASK, Init.ClockEdge |\ + Init.ClockBypass |\ + Init.ClockPowerSave |\ + Init.BusWide |\ + Init.HardwareFlowControl |\ + Init.ClockDiv); return HAL_OK; } - /** * @} */ @@ -263,10 +241,10 @@ HAL_StatusTypeDef SDIO_Init(SDIO_TypeDef *SDIOx, SDIO_InitTypeDef Init) * @verbatim =============================================================================== - ##### I/O operation functions ##### - =============================================================================== + ##### IO operation functions ##### + =============================================================================== [..] - This subsection provides a set of functions allowing to manage the SDMMC data + This subsection provides a set of functions allowing to manage the SDIO data transfers. @endverbatim @@ -275,7 +253,7 @@ HAL_StatusTypeDef SDIO_Init(SDIO_TypeDef *SDIOx, SDIO_InitTypeDef Init) /** * @brief Read data (word) from Rx FIFO in blocking mode (polling) - * @param SDIOx: Pointer to SDMMC register base + * @param SDIOx: Pointer to SDIO register base * @retval HAL status */ uint32_t SDIO_ReadFIFO(SDIO_TypeDef *SDIOx) @@ -286,7 +264,7 @@ uint32_t SDIO_ReadFIFO(SDIO_TypeDef *SDIOx) /** * @brief Write data (word) to Tx FIFO in blocking mode (polling) - * @param SDIOx: Pointer to SDMMC register base + * @param SDIOx: Pointer to SDIO register base * @param pWriteData: pointer to data to write * @retval HAL status */ @@ -310,7 +288,7 @@ HAL_StatusTypeDef SDIO_WriteFIFO(SDIO_TypeDef *SDIOx, uint32_t *pWriteData) ##### Peripheral Control functions ##### =============================================================================== [..] - This subsection provides a set of functions allowing to control the SDMMC data + This subsection provides a set of functions allowing to control the SDIO data transfers. @endverbatim @@ -318,8 +296,8 @@ HAL_StatusTypeDef SDIO_WriteFIFO(SDIO_TypeDef *SDIOx, uint32_t *pWriteData) */ /** - * @brief Set SDMMC Power state to ON. - * @param SDIOx: Pointer to SDMMC register base + * @brief Set SDIO Power state to ON. + * @param SDIOx: Pointer to SDIO register base * @retval HAL status */ HAL_StatusTypeDef SDIO_PowerState_ON(SDIO_TypeDef *SDIOx) @@ -327,25 +305,25 @@ HAL_StatusTypeDef SDIO_PowerState_ON(SDIO_TypeDef *SDIOx) /* Set power state to ON */ SDIOx->POWER = SDIO_POWER_PWRCTRL; - return HAL_OK; + return HAL_OK; } /** - * @brief Set SDMMC Power state to OFF. - * @param SDIOx: Pointer to SDMMC register base + * @brief Set SDIO Power state to OFF. + * @param SDIOx: Pointer to SDIO register base * @retval HAL status */ HAL_StatusTypeDef SDIO_PowerState_OFF(SDIO_TypeDef *SDIOx) { /* Set power state to OFF */ - SDIOx->POWER = 0x00000000U; + SDIOx->POWER = (uint32_t)0x00000000; return HAL_OK; } /** - * @brief Get SDMMC Power state. - * @param SDIOx: Pointer to SDMMC register base + * @brief Get SDIO Power state. + * @param SDIOx: Pointer to SDIO register base * @retval Power status of the controller. The returned value can be one of the * following values: * - 0x00: Power OFF @@ -358,41 +336,37 @@ uint32_t SDIO_GetPowerState(SDIO_TypeDef *SDIOx) } /** - * @brief Configure the SDMMC command path according to the specified parameters in + * @brief Configure the SDIO command path according to the specified parameters in * SDIO_CmdInitTypeDef structure and send the command - * @param SDIOx: Pointer to SDMMC register base + * @param SDIOx: Pointer to SDIO register base * @param Command: pointer to a SDIO_CmdInitTypeDef structure that contains - * the configuration information for the SDMMC command + * the configuration information for the SDIO command * @retval HAL status */ HAL_StatusTypeDef SDIO_SendCommand(SDIO_TypeDef *SDIOx, SDIO_CmdInitTypeDef *Command) { - uint32_t tmpreg = 0U; - /* Check the parameters */ assert_param(IS_SDIO_CMD_INDEX(Command->CmdIndex)); assert_param(IS_SDIO_RESPONSE(Command->Response)); assert_param(IS_SDIO_WAIT(Command->WaitForInterrupt)); assert_param(IS_SDIO_CPSM(Command->CPSM)); - /* Set the SDMMC Argument value */ + /* Set the SDIO Argument value */ SDIOx->ARG = Command->Argument; - /* Set SDMMC command parameters */ - tmpreg |= (uint32_t)(Command->CmdIndex |\ - Command->Response |\ - Command->WaitForInterrupt |\ - Command->CPSM); - - /* Write to SDMMC CMD register */ - MODIFY_REG(SDIOx->CMD, CMD_CLEAR_MASK, tmpreg); + /* Set SDIO command parameters */ + /* Write to SDIO CMD register */ + MODIFY_REG(SDIOx->CMD, CMD_CLEAR_MASK, Command->CmdIndex |\ + Command->Response |\ + Command->WaitForInterrupt |\ + Command->CPSM); return HAL_OK; } /** * @brief Return the command index of last command for which response received - * @param SDIOx: Pointer to SDMMC register base + * @param SDIOx: Pointer to SDIO register base * @retval Command index of the last command response received */ uint8_t SDIO_GetCommandResponse(SDIO_TypeDef *SDIOx) @@ -403,8 +377,7 @@ uint8_t SDIO_GetCommandResponse(SDIO_TypeDef *SDIOx) /** * @brief Return the response received from the card for the last command - * @param SDIOx: Pointer to SDMMC register base - * @param Response: Specifies the SDMMC response register. + * @param SDIO_RESP: Specifies the SDIO response register. * This parameter can be one of the following values: * @arg SDIO_RESP1: Response Register 1 * @arg SDIO_RESP2: Response Register 2 @@ -414,29 +387,27 @@ uint8_t SDIO_GetCommandResponse(SDIO_TypeDef *SDIOx) */ uint32_t SDIO_GetResponse(SDIO_TypeDef *SDIOx, uint32_t Response) { - __IO uint32_t tmp = 0U; + __IO uint32_t tmp = 0; /* Check the parameters */ assert_param(IS_SDIO_RESP(Response)); /* Get the response */ - tmp = (uint32_t)&(SDIOx->RESP1) + Response; + tmp = SDIO_RESP_ADDR + Response; return (*(__IO uint32_t *) tmp); } /** - * @brief Configure the SDMMC data path according to the specified + * @brief Configure the SDIO data path according to the specified * parameters in the SDIO_DataInitTypeDef. - * @param SDIOx: Pointer to SDMMC register base + * @param SDIOx: Pointer to SDIO register base * @param Data : pointer to a SDIO_DataInitTypeDef structure - * that contains the configuration information for the SDMMC data. + * that contains the configuration information for the SDIO data. * @retval HAL status */ -HAL_StatusTypeDef SDIO_ConfigData(SDIO_TypeDef *SDIOx, SDIO_DataInitTypeDef* Data) +HAL_StatusTypeDef SDIO_DataConfig(SDIO_TypeDef *SDIOx, SDIO_DataInitTypeDef* Data) { - uint32_t tmpreg = 0U; - /* Check the parameters */ assert_param(IS_SDIO_DATA_LENGTH(Data->DataLength)); assert_param(IS_SDIO_BLOCK_SIZE(Data->DataBlockSize)); @@ -444,20 +415,18 @@ HAL_StatusTypeDef SDIO_ConfigData(SDIO_TypeDef *SDIOx, SDIO_DataInitTypeDef* Dat assert_param(IS_SDIO_TRANSFER_MODE(Data->TransferMode)); assert_param(IS_SDIO_DPSM(Data->DPSM)); - /* Set the SDMMC Data TimeOut value */ + /* Set the SDIO Data TimeOut value */ SDIOx->DTIMER = Data->DataTimeOut; - /* Set the SDMMC DataLength value */ + /* Set the SDIO DataLength value */ SDIOx->DLEN = Data->DataLength; - /* Set the SDMMC data configuration parameters */ - tmpreg |= (uint32_t)(Data->DataBlockSize |\ - Data->TransferDir |\ - Data->TransferMode |\ - Data->DPSM); - - /* Write to SDMMC DCTRL */ - MODIFY_REG(SDIOx->DCTRL, DCTRL_CLEAR_MASK, tmpreg); + /* Set the SDIO data configuration parameters */ + /* Write to SDIO DCTRL */ + MODIFY_REG(SDIOx->DCTRL, DCTRL_CLEAR_MASK, Data->DataBlockSize |\ + Data->TransferDir |\ + Data->TransferMode |\ + Data->DPSM); return HAL_OK; @@ -465,7 +434,7 @@ HAL_StatusTypeDef SDIO_ConfigData(SDIO_TypeDef *SDIOx, SDIO_DataInitTypeDef* Dat /** * @brief Returns number of remaining data bytes to be transferred. - * @param SDIOx: Pointer to SDMMC register base + * @param SDIOx: Pointer to SDIO register base * @retval Number of remaining data bytes to be transferred */ uint32_t SDIO_GetDataCounter(SDIO_TypeDef *SDIOx) @@ -475,7 +444,7 @@ uint32_t SDIO_GetDataCounter(SDIO_TypeDef *SDIOx) /** * @brief Get the FIFO data - * @param SDIOx: Pointer to SDMMC register base + * @param SDIOx: Pointer to SDIO register base * @retval Data received */ uint32_t SDIO_GetFIFOCount(SDIO_TypeDef *SDIOx) @@ -483,1001 +452,26 @@ uint32_t SDIO_GetFIFOCount(SDIO_TypeDef *SDIOx) return (SDIOx->FIFO); } + /** * @brief Sets one of the two options of inserting read wait interval. - * @param SDIOx: Pointer to SDMMC register base - * @param SDIO_ReadWaitMode: SDMMC Read Wait operation mode. + * @param SDIO_ReadWaitMode: SD I/O Read Wait operation mode. * This parameter can be: - * @arg SDIO_READ_WAIT_MODE_CLK: Read Wait control by stopping SDMMCCLK - * @arg SDIO_READ_WAIT_MODE_DATA2: Read Wait control using SDMMC_DATA2 + * @arg SDIO_READ_WAIT_MODE_CLK: Read Wait control by stopping SDIOCLK + * @arg SDIO_READ_WAIT_MODE_DATA2: Read Wait control using SDIO_DATA2 * @retval None */ -HAL_StatusTypeDef SDIO_SetSDMMCReadWaitMode(SDIO_TypeDef *SDIOx, uint32_t SDIO_ReadWaitMode) +HAL_StatusTypeDef SDIO_SetSDIOReadWaitMode(SDIO_TypeDef *SDIOx, uint32_t SDIO_ReadWaitMode) { /* Check the parameters */ assert_param(IS_SDIO_READWAIT_MODE(SDIO_ReadWaitMode)); - - /* Set SDMMC read wait mode */ - MODIFY_REG(SDIOx->DCTRL, SDIO_DCTRL_RWMOD, SDIO_ReadWaitMode); - - return HAL_OK; -} - -/** - * @} - */ - - -/** @defgroup HAL_SDMMC_LL_Group4 Command management functions - * @brief Data transfers functions - * -@verbatim - =============================================================================== - ##### Commands management functions ##### - =============================================================================== - [..] - This subsection provides a set of functions allowing to manage the needed commands. - -@endverbatim - * @{ - */ - -/** - * @brief Send the Data Block Lenght command and check the response - * @param SDIOx: Pointer to SDMMC register base - * @retval HAL status - */ -uint32_t SDMMC_CmdBlockLength(SDIO_TypeDef *SDIOx, uint32_t BlockSize) -{ - SDIO_CmdInitTypeDef sdmmc_cmdinit; - uint32_t errorstate = SDMMC_ERROR_NONE; - - /* Set Block Size for Card */ - sdmmc_cmdinit.Argument = (uint32_t)BlockSize; - sdmmc_cmdinit.CmdIndex = SDMMC_CMD_SET_BLOCKLEN; - sdmmc_cmdinit.Response = SDIO_RESPONSE_SHORT; - sdmmc_cmdinit.WaitForInterrupt = SDIO_WAIT_NO; - sdmmc_cmdinit.CPSM = SDIO_CPSM_ENABLE; - SDIO_SendCommand(SDIOx, &sdmmc_cmdinit); - - /* Check for error conditions */ - errorstate = SDMMC_GetCmdResp1(SDIOx, SDMMC_CMD_SET_BLOCKLEN, SDIO_CMDTIMEOUT); - - return errorstate; -} - -/** - * @brief Send the Read Single Block command and check the response - * @param SDIOx: Pointer to SDMMC register base - * @retval HAL status - */ -uint32_t SDMMC_CmdReadSingleBlock(SDIO_TypeDef *SDIOx, uint32_t ReadAdd) -{ - SDIO_CmdInitTypeDef sdmmc_cmdinit; - uint32_t errorstate = SDMMC_ERROR_NONE; - - /* Set Block Size for Card */ - sdmmc_cmdinit.Argument = (uint32_t)ReadAdd; - sdmmc_cmdinit.CmdIndex = SDMMC_CMD_READ_SINGLE_BLOCK; - sdmmc_cmdinit.Response = SDIO_RESPONSE_SHORT; - sdmmc_cmdinit.WaitForInterrupt = SDIO_WAIT_NO; - sdmmc_cmdinit.CPSM = SDIO_CPSM_ENABLE; - SDIO_SendCommand(SDIOx, &sdmmc_cmdinit); - - /* Check for error conditions */ - errorstate = SDMMC_GetCmdResp1(SDIOx, SDMMC_CMD_READ_SINGLE_BLOCK, SDIO_CMDTIMEOUT); - - return errorstate; -} - -/** - * @brief Send the Read Multi Block command and check the response - * @param SDIOx: Pointer to SDIO register base - * @retval HAL status - */ -uint32_t SDMMC_CmdReadMultiBlock(SDIO_TypeDef *SDIOx, uint32_t ReadAdd) -{ - SDIO_CmdInitTypeDef sdmmc_cmdinit; - uint32_t errorstate = SDMMC_ERROR_NONE; - - /* Set Block Size for Card */ - sdmmc_cmdinit.Argument = (uint32_t)ReadAdd; - sdmmc_cmdinit.CmdIndex = SDMMC_CMD_READ_MULT_BLOCK; - sdmmc_cmdinit.Response = SDIO_RESPONSE_SHORT; - sdmmc_cmdinit.WaitForInterrupt = SDIO_WAIT_NO; - sdmmc_cmdinit.CPSM = SDIO_CPSM_ENABLE; - SDIO_SendCommand(SDIOx, &sdmmc_cmdinit); - - /* Check for error conditions */ - errorstate = SDMMC_GetCmdResp1(SDIOx, SDMMC_CMD_READ_MULT_BLOCK, SDIO_CMDTIMEOUT); - - return errorstate; -} - -/** - * @brief Send the Write Single Block command and check the response - * @param SDIOx: Pointer to SDIO register base - * @retval HAL status - */ -uint32_t SDMMC_CmdWriteSingleBlock(SDIO_TypeDef *SDIOx, uint32_t WriteAdd) -{ - SDIO_CmdInitTypeDef sdmmc_cmdinit; - uint32_t errorstate = SDMMC_ERROR_NONE; - - /* Set Block Size for Card */ - sdmmc_cmdinit.Argument = (uint32_t)WriteAdd; - sdmmc_cmdinit.CmdIndex = SDMMC_CMD_WRITE_SINGLE_BLOCK; - sdmmc_cmdinit.Response = SDIO_RESPONSE_SHORT; - sdmmc_cmdinit.WaitForInterrupt = SDIO_WAIT_NO; - sdmmc_cmdinit.CPSM = SDIO_CPSM_ENABLE; - SDIO_SendCommand(SDIOx, &sdmmc_cmdinit); - - /* Check for error conditions */ - errorstate = SDMMC_GetCmdResp1(SDIOx, SDMMC_CMD_WRITE_SINGLE_BLOCK, SDIO_CMDTIMEOUT); - - return errorstate; -} - -/** - * @brief Send the Write Multi Block command and check the response - * @param SDIOx: Pointer to SDIO register base - * @retval HAL status - */ -uint32_t SDMMC_CmdWriteMultiBlock(SDIO_TypeDef *SDIOx, uint32_t WriteAdd) -{ - SDIO_CmdInitTypeDef sdmmc_cmdinit; - uint32_t errorstate = SDMMC_ERROR_NONE; - - /* Set Block Size for Card */ - sdmmc_cmdinit.Argument = (uint32_t)WriteAdd; - sdmmc_cmdinit.CmdIndex = SDMMC_CMD_WRITE_MULT_BLOCK; - sdmmc_cmdinit.Response = SDIO_RESPONSE_SHORT; - sdmmc_cmdinit.WaitForInterrupt = SDIO_WAIT_NO; - sdmmc_cmdinit.CPSM = SDIO_CPSM_ENABLE; - SDIO_SendCommand(SDIOx, &sdmmc_cmdinit); - - /* Check for error conditions */ - errorstate = SDMMC_GetCmdResp1(SDIOx, SDMMC_CMD_WRITE_MULT_BLOCK, SDIO_CMDTIMEOUT); - - return errorstate; -} - -/** - * @brief Send the Start Address Erase command for SD and check the response - * @param SDIOx: Pointer to SDIO register base - * @retval HAL status - */ -uint32_t SDMMC_CmdSDEraseStartAdd(SDIO_TypeDef *SDIOx, uint32_t StartAdd) -{ - SDIO_CmdInitTypeDef sdmmc_cmdinit; - uint32_t errorstate = SDMMC_ERROR_NONE; - - /* Set Block Size for Card */ - sdmmc_cmdinit.Argument = (uint32_t)StartAdd; - sdmmc_cmdinit.CmdIndex = SDMMC_CMD_SD_ERASE_GRP_START; - sdmmc_cmdinit.Response = SDIO_RESPONSE_SHORT; - sdmmc_cmdinit.WaitForInterrupt = SDIO_WAIT_NO; - sdmmc_cmdinit.CPSM = SDIO_CPSM_ENABLE; - SDIO_SendCommand(SDIOx, &sdmmc_cmdinit); - - /* Check for error conditions */ - errorstate = SDMMC_GetCmdResp1(SDIOx, SDMMC_CMD_SD_ERASE_GRP_START, SDIO_CMDTIMEOUT); - - return errorstate; -} - -/** - * @brief Send the End Address Erase command for SD and check the response - * @param SDIOx: Pointer to SDIO register base - * @retval HAL status - */ -uint32_t SDMMC_CmdSDEraseEndAdd(SDIO_TypeDef *SDIOx, uint32_t EndAdd) -{ - SDIO_CmdInitTypeDef sdmmc_cmdinit; - uint32_t errorstate = SDMMC_ERROR_NONE; - - /* Set Block Size for Card */ - sdmmc_cmdinit.Argument = (uint32_t)EndAdd; - sdmmc_cmdinit.CmdIndex = SDMMC_CMD_SD_ERASE_GRP_END; - sdmmc_cmdinit.Response = SDIO_RESPONSE_SHORT; - sdmmc_cmdinit.WaitForInterrupt = SDIO_WAIT_NO; - sdmmc_cmdinit.CPSM = SDIO_CPSM_ENABLE; - SDIO_SendCommand(SDIOx, &sdmmc_cmdinit); - - /* Check for error conditions */ - errorstate = SDMMC_GetCmdResp1(SDIOx, SDMMC_CMD_SD_ERASE_GRP_END, SDIO_CMDTIMEOUT); - - return errorstate; -} - -/** - * @brief Send the Start Address Erase command and check the response - * @param SDIOx: Pointer to SDIO register base - * @retval HAL status - */ -uint32_t SDMMC_CmdEraseStartAdd(SDIO_TypeDef *SDIOx, uint32_t StartAdd) -{ - SDIO_CmdInitTypeDef sdmmc_cmdinit; - uint32_t errorstate = SDMMC_ERROR_NONE; - - /* Set Block Size for Card */ - sdmmc_cmdinit.Argument = (uint32_t)StartAdd; - sdmmc_cmdinit.CmdIndex = SDMMC_CMD_ERASE_GRP_START; - sdmmc_cmdinit.Response = SDIO_RESPONSE_SHORT; - sdmmc_cmdinit.WaitForInterrupt = SDIO_WAIT_NO; - sdmmc_cmdinit.CPSM = SDIO_CPSM_ENABLE; - SDIO_SendCommand(SDIOx, &sdmmc_cmdinit); - - /* Check for error conditions */ - errorstate = SDMMC_GetCmdResp1(SDIOx, SDMMC_CMD_ERASE_GRP_START, SDIO_CMDTIMEOUT); - - return errorstate; -} - -/** - * @brief Send the End Address Erase command and check the response - * @param SDIOx: Pointer to SDIO register base - * @retval HAL status - */ -uint32_t SDMMC_CmdEraseEndAdd(SDIO_TypeDef *SDIOx, uint32_t EndAdd) -{ - SDIO_CmdInitTypeDef sdmmc_cmdinit; - uint32_t errorstate = SDMMC_ERROR_NONE; - - /* Set Block Size for Card */ - sdmmc_cmdinit.Argument = (uint32_t)EndAdd; - sdmmc_cmdinit.CmdIndex = SDMMC_CMD_ERASE_GRP_END; - sdmmc_cmdinit.Response = SDIO_RESPONSE_SHORT; - sdmmc_cmdinit.WaitForInterrupt = SDIO_WAIT_NO; - sdmmc_cmdinit.CPSM = SDIO_CPSM_ENABLE; - SDIO_SendCommand(SDIOx, &sdmmc_cmdinit); - - /* Check for error conditions */ - errorstate = SDMMC_GetCmdResp1(SDIOx, SDMMC_CMD_ERASE_GRP_END, SDIO_CMDTIMEOUT); - - return errorstate; -} - -/** - * @brief Send the Erase command and check the response - * @param SDIOx: Pointer to SDIO register base - * @retval HAL status - */ -uint32_t SDMMC_CmdErase(SDIO_TypeDef *SDIOx) -{ - SDIO_CmdInitTypeDef sdmmc_cmdinit; - uint32_t errorstate = SDMMC_ERROR_NONE; - - /* Set Block Size for Card */ - sdmmc_cmdinit.Argument = 0U; - sdmmc_cmdinit.CmdIndex = SDMMC_CMD_ERASE; - sdmmc_cmdinit.Response = SDIO_RESPONSE_SHORT; - sdmmc_cmdinit.WaitForInterrupt = SDIO_WAIT_NO; - sdmmc_cmdinit.CPSM = SDIO_CPSM_ENABLE; - SDIO_SendCommand(SDIOx, &sdmmc_cmdinit); - - /* Check for error conditions */ - errorstate = SDMMC_GetCmdResp1(SDIOx, SDMMC_CMD_ERASE, SDIO_MAXERASETIMEOUT); - - return errorstate; -} - -/** - * @brief Send the Stop Transfer command and check the response. - * @param SDIOx: Pointer to SDIO register base - * @retval HAL status - */ -uint32_t SDMMC_CmdStopTransfer(SDIO_TypeDef *SDIOx) -{ - SDIO_CmdInitTypeDef sdmmc_cmdinit; - uint32_t errorstate = SDMMC_ERROR_NONE; - - /* Send CMD12 STOP_TRANSMISSION */ - sdmmc_cmdinit.Argument = 0U; - sdmmc_cmdinit.CmdIndex = SDMMC_CMD_STOP_TRANSMISSION; - sdmmc_cmdinit.Response = SDIO_RESPONSE_SHORT; - sdmmc_cmdinit.WaitForInterrupt = SDIO_WAIT_NO; - sdmmc_cmdinit.CPSM = SDIO_CPSM_ENABLE; - SDIO_SendCommand(SDIOx, &sdmmc_cmdinit); - - /* Check for error conditions */ - errorstate = SDMMC_GetCmdResp1(SDIOx, SDMMC_CMD_STOP_TRANSMISSION, 100000000U); - - return errorstate; -} - -/** - * @brief Send the Select Deselect command and check the response. - * @param SDIOx: Pointer to SDIO register base - * @param addr: Address of the card to be selected - * @retval HAL status - */ -uint32_t SDMMC_CmdSelDesel(SDIO_TypeDef *SDIOx, uint64_t Addr) -{ - SDIO_CmdInitTypeDef sdmmc_cmdinit; - uint32_t errorstate = SDMMC_ERROR_NONE; - - /* Send CMD7 SDMMC_SEL_DESEL_CARD */ - sdmmc_cmdinit.Argument = (uint32_t)Addr; - sdmmc_cmdinit.CmdIndex = SDMMC_CMD_SEL_DESEL_CARD; - sdmmc_cmdinit.Response = SDIO_RESPONSE_SHORT; - sdmmc_cmdinit.WaitForInterrupt = SDIO_WAIT_NO; - sdmmc_cmdinit.CPSM = SDIO_CPSM_ENABLE; - SDIO_SendCommand(SDIOx, &sdmmc_cmdinit); - - /* Check for error conditions */ - errorstate = SDMMC_GetCmdResp1(SDIOx, SDMMC_CMD_SEL_DESEL_CARD, SDIO_CMDTIMEOUT); - - return errorstate; -} - -/** - * @brief Send the Go Idle State command and check the response. - * @param SDIOx: Pointer to SDIO register base - * @retval HAL status - */ -uint32_t SDMMC_CmdGoIdleState(SDIO_TypeDef *SDIOx) -{ - SDIO_CmdInitTypeDef sdmmc_cmdinit; - uint32_t errorstate = SDMMC_ERROR_NONE; - - sdmmc_cmdinit.Argument = 0U; - sdmmc_cmdinit.CmdIndex = SDMMC_CMD_GO_IDLE_STATE; - sdmmc_cmdinit.Response = SDIO_RESPONSE_NO; - sdmmc_cmdinit.WaitForInterrupt = SDIO_WAIT_NO; - sdmmc_cmdinit.CPSM = SDIO_CPSM_ENABLE; - SDIO_SendCommand(SDIOx, &sdmmc_cmdinit); - - /* Check for error conditions */ - errorstate = SDMMC_GetCmdError(SDIOx); - - return errorstate; -} - -/** - * @brief Send the Operating Condition command and check the response. - * @param SDIOx: Pointer to SDIO register base - * @retval HAL status - */ -uint32_t SDMMC_CmdOperCond(SDIO_TypeDef *SDIOx) -{ - SDIO_CmdInitTypeDef sdmmc_cmdinit; - uint32_t errorstate = SDMMC_ERROR_NONE; - - /* Send CMD8 to verify SD card interface operating condition */ - /* Argument: - [31:12]: Reserved (shall be set to '0') - - [11:8]: Supply Voltage (VHS) 0x1 (Range: 2.7-3.6 V) - - [7:0]: Check Pattern (recommended 0xAA) */ - /* CMD Response: R7 */ - sdmmc_cmdinit.Argument = SDMMC_CHECK_PATTERN; - sdmmc_cmdinit.CmdIndex = SDMMC_CMD_HS_SEND_EXT_CSD; - sdmmc_cmdinit.Response = SDIO_RESPONSE_SHORT; - sdmmc_cmdinit.WaitForInterrupt = SDIO_WAIT_NO; - sdmmc_cmdinit.CPSM = SDIO_CPSM_ENABLE; - SDIO_SendCommand(SDIOx, &sdmmc_cmdinit); - - /* Check for error conditions */ - errorstate = SDMMC_GetCmdResp7(SDIOx); - - return errorstate; -} - -/** - * @brief Send the Application command to verify that that the next command - * is an application specific com-mand rather than a standard command - * and check the response. - * @param SDIOx: Pointer to SDIO register base - * @retval HAL status - */ -uint32_t SDMMC_CmdAppCommand(SDIO_TypeDef *SDIOx, uint32_t Argument) -{ - SDIO_CmdInitTypeDef sdmmc_cmdinit; - uint32_t errorstate = SDMMC_ERROR_NONE; - sdmmc_cmdinit.Argument = (uint32_t)Argument; - sdmmc_cmdinit.CmdIndex = SDMMC_CMD_APP_CMD; - sdmmc_cmdinit.Response = SDIO_RESPONSE_SHORT; - sdmmc_cmdinit.WaitForInterrupt = SDIO_WAIT_NO; - sdmmc_cmdinit.CPSM = SDIO_CPSM_ENABLE; - SDIO_SendCommand(SDIOx, &sdmmc_cmdinit); - - /* Check for error conditions */ - /* If there is a HAL_ERROR, it is a MMC card, else - it is a SD card: SD card 2.0 (voltage range mismatch) - or SD card 1.x */ - errorstate = SDMMC_GetCmdResp1(SDIOx, SDMMC_CMD_APP_CMD, SDIO_CMDTIMEOUT); - - return errorstate; -} - -/** - * @brief Send the command asking the accessed card to send its operating - * condition register (OCR) - * @param SDIOx: Pointer to SDIO register base - * @retval HAL status - */ -uint32_t SDMMC_CmdAppOperCommand(SDIO_TypeDef *SDIOx, uint32_t SdType) -{ - SDIO_CmdInitTypeDef sdmmc_cmdinit; - uint32_t errorstate = SDMMC_ERROR_NONE; - - sdmmc_cmdinit.Argument = SDMMC_VOLTAGE_WINDOW_SD | SdType; - sdmmc_cmdinit.CmdIndex = SDMMC_CMD_SD_APP_OP_COND; - sdmmc_cmdinit.Response = SDIO_RESPONSE_SHORT; - sdmmc_cmdinit.WaitForInterrupt = SDIO_WAIT_NO; - sdmmc_cmdinit.CPSM = SDIO_CPSM_ENABLE; - SDIO_SendCommand(SDIOx, &sdmmc_cmdinit); - - /* Check for error conditions */ - errorstate = SDMMC_GetCmdResp3(SDIOx); - - return errorstate; -} - -/** - * @brief Send the Bus Width command and check the response. - * @param SDIOx: Pointer to SDIO register base - * @retval HAL status - */ -uint32_t SDMMC_CmdBusWidth(SDIO_TypeDef *SDIOx, uint32_t BusWidth) -{ - SDIO_CmdInitTypeDef sdmmc_cmdinit; - uint32_t errorstate = SDMMC_ERROR_NONE; - - sdmmc_cmdinit.Argument = (uint32_t)BusWidth; - sdmmc_cmdinit.CmdIndex = SDMMC_CMD_APP_SD_SET_BUSWIDTH; - sdmmc_cmdinit.Response = SDIO_RESPONSE_SHORT; - sdmmc_cmdinit.WaitForInterrupt = SDIO_WAIT_NO; - sdmmc_cmdinit.CPSM = SDIO_CPSM_ENABLE; - SDIO_SendCommand(SDIOx, &sdmmc_cmdinit); - - /* Check for error conditions */ - errorstate = SDMMC_GetCmdResp1(SDIOx, SDMMC_CMD_APP_SD_SET_BUSWIDTH, SDIO_CMDTIMEOUT); - - return errorstate; -} - -/** - * @brief Send the Send SCR command and check the response. - * @param SDIOx: Pointer to SDMMC register base - * @retval HAL status - */ -uint32_t SDMMC_CmdSendSCR(SDIO_TypeDef *SDIOx) -{ - SDIO_CmdInitTypeDef sdmmc_cmdinit; - uint32_t errorstate = SDMMC_ERROR_NONE; - - /* Send CMD51 SD_APP_SEND_SCR */ - sdmmc_cmdinit.Argument = 0U; - sdmmc_cmdinit.CmdIndex = SDMMC_CMD_SD_APP_SEND_SCR; - sdmmc_cmdinit.Response = SDIO_RESPONSE_SHORT; - sdmmc_cmdinit.WaitForInterrupt = SDIO_WAIT_NO; - sdmmc_cmdinit.CPSM = SDIO_CPSM_ENABLE; - SDIO_SendCommand(SDIOx, &sdmmc_cmdinit); - - /* Check for error conditions */ - errorstate = SDMMC_GetCmdResp1(SDIOx, SDMMC_CMD_SD_APP_SEND_SCR, SDIO_CMDTIMEOUT); - - return errorstate; -} - -/** - * @brief Send the Send CID command and check the response. - * @param SDIOx: Pointer to SDIO register base - * @retval HAL status - */ -uint32_t SDMMC_CmdSendCID(SDIO_TypeDef *SDIOx) -{ - SDIO_CmdInitTypeDef sdmmc_cmdinit; - uint32_t errorstate = SDMMC_ERROR_NONE; + /* Set SDIO read wait mode */ + MODIFY_REG(SDIO->DCTRL, SDIO_DCTRL_RWMOD, SDIO_ReadWaitMode); - /* Send CMD2 ALL_SEND_CID */ - sdmmc_cmdinit.Argument = 0U; - sdmmc_cmdinit.CmdIndex = SDMMC_CMD_ALL_SEND_CID; - sdmmc_cmdinit.Response = SDIO_RESPONSE_LONG; - sdmmc_cmdinit.WaitForInterrupt = SDIO_WAIT_NO; - sdmmc_cmdinit.CPSM = SDIO_CPSM_ENABLE; - SDIO_SendCommand(SDIOx, &sdmmc_cmdinit); - - /* Check for error conditions */ - errorstate = SDMMC_GetCmdResp2(SDIOx); - - return errorstate; -} - -/** - * @brief Send the Send CSD command and check the response. - * @param SDIOx: Pointer to SDIO register base - * @retval HAL status - */ -uint32_t SDMMC_CmdSendCSD(SDIO_TypeDef *SDIOx, uint32_t Argument) -{ - SDIO_CmdInitTypeDef sdmmc_cmdinit; - uint32_t errorstate = SDMMC_ERROR_NONE; - - /* Send CMD9 SEND_CSD */ - sdmmc_cmdinit.Argument = (uint32_t)Argument; - sdmmc_cmdinit.CmdIndex = SDMMC_CMD_SEND_CSD; - sdmmc_cmdinit.Response = SDIO_RESPONSE_LONG; - sdmmc_cmdinit.WaitForInterrupt = SDIO_WAIT_NO; - sdmmc_cmdinit.CPSM = SDIO_CPSM_ENABLE; - SDIO_SendCommand(SDIOx, &sdmmc_cmdinit); - - /* Check for error conditions */ - errorstate = SDMMC_GetCmdResp2(SDIOx); - - return errorstate; -} - -/** - * @brief Send the Send CSD command and check the response. - * @param SDIOx: Pointer to SDIO register base - * @retval HAL status - */ -uint32_t SDMMC_CmdSetRelAdd(SDIO_TypeDef *SDIOx, uint16_t *pRCA) -{ - SDIO_CmdInitTypeDef sdmmc_cmdinit; - uint32_t errorstate = SDMMC_ERROR_NONE; - - /* Send CMD3 SD_CMD_SET_REL_ADDR */ - sdmmc_cmdinit.Argument = 0U; - sdmmc_cmdinit.CmdIndex = SDMMC_CMD_SET_REL_ADDR; - sdmmc_cmdinit.Response = SDIO_RESPONSE_SHORT; - sdmmc_cmdinit.WaitForInterrupt = SDIO_WAIT_NO; - sdmmc_cmdinit.CPSM = SDIO_CPSM_ENABLE; - SDIO_SendCommand(SDIOx, &sdmmc_cmdinit); - - /* Check for error conditions */ - errorstate = SDMMC_GetCmdResp6(SDIOx, SDMMC_CMD_SET_REL_ADDR, pRCA); - - return errorstate; -} - -/** - * @brief Send the Status command and check the response. - * @param SDIOx: Pointer to SDIO register base - * @retval HAL status - */ -uint32_t SDMMC_CmdSendStatus(SDIO_TypeDef *SDIOx, uint32_t Argument) -{ - SDIO_CmdInitTypeDef sdmmc_cmdinit; - uint32_t errorstate = SDMMC_ERROR_NONE; - - sdmmc_cmdinit.Argument = (uint32_t)Argument; - sdmmc_cmdinit.CmdIndex = SDMMC_CMD_SEND_STATUS; - sdmmc_cmdinit.Response = SDIO_RESPONSE_SHORT; - sdmmc_cmdinit.WaitForInterrupt = SDIO_WAIT_NO; - sdmmc_cmdinit.CPSM = SDIO_CPSM_ENABLE; - SDIO_SendCommand(SDIOx, &sdmmc_cmdinit); - - /* Check for error conditions */ - errorstate = SDMMC_GetCmdResp1(SDIOx, SDMMC_CMD_SEND_STATUS, SDIO_CMDTIMEOUT); - - return errorstate; -} - -/** - * @brief Send the Status register command and check the response. - * @param SDIOx: Pointer to SDIO register base - * @retval HAL status - */ -uint32_t SDMMC_CmdStatusRegister(SDIO_TypeDef *SDIOx) -{ - SDIO_CmdInitTypeDef sdmmc_cmdinit; - uint32_t errorstate = SDMMC_ERROR_NONE; - - sdmmc_cmdinit.Argument = 0U; - sdmmc_cmdinit.CmdIndex = SDMMC_CMD_SD_APP_STATUS; - sdmmc_cmdinit.Response = SDIO_RESPONSE_SHORT; - sdmmc_cmdinit.WaitForInterrupt = SDIO_WAIT_NO; - sdmmc_cmdinit.CPSM = SDIO_CPSM_ENABLE; - SDIO_SendCommand(SDIOx, &sdmmc_cmdinit); - - /* Check for error conditions */ - errorstate = SDMMC_GetCmdResp1(SDIOx, SDMMC_CMD_SD_APP_STATUS, SDIO_CMDTIMEOUT); - - return errorstate; -} - -/** - * @brief Sends host capacity support information and activates the card's - * initialization process. Send SDMMC_CMD_SEND_OP_COND command - * @param SDIOx: Pointer to SDIO register base - * @parame Argument: Argument used for the command - * @retval HAL status - */ -uint32_t SDMMC_CmdOpCondition(SDIO_TypeDef *SDIOx, uint32_t Argument) -{ - SDIO_CmdInitTypeDef sdmmc_cmdinit; - uint32_t errorstate = SDMMC_ERROR_NONE; - - sdmmc_cmdinit.Argument = Argument; - sdmmc_cmdinit.CmdIndex = SDMMC_CMD_SEND_OP_COND; - sdmmc_cmdinit.Response = SDIO_RESPONSE_SHORT; - sdmmc_cmdinit.WaitForInterrupt = SDIO_WAIT_NO; - sdmmc_cmdinit.CPSM = SDIO_CPSM_ENABLE; - SDIO_SendCommand(SDIOx, &sdmmc_cmdinit); - - /* Check for error conditions */ - errorstate = SDMMC_GetCmdResp3(SDIOx); - - return errorstate; -} - -/** - * @brief Checks switchable function and switch card function. SDMMC_CMD_HS_SWITCH comand - * @param SDIOx: Pointer to SDIO register base - * @parame Argument: Argument used for the command - * @retval HAL status - */ -uint32_t SDMMC_CmdSwitch(SDIO_TypeDef *SDIOx, uint32_t Argument) -{ - SDIO_CmdInitTypeDef sdmmc_cmdinit; - uint32_t errorstate = SDMMC_ERROR_NONE; - - sdmmc_cmdinit.Argument = Argument; - sdmmc_cmdinit.CmdIndex = SDMMC_CMD_HS_SWITCH; - sdmmc_cmdinit.Response = SDIO_RESPONSE_SHORT; - sdmmc_cmdinit.WaitForInterrupt = SDIO_WAIT_NO; - sdmmc_cmdinit.CPSM = SDIO_CPSM_ENABLE; - SDIO_SendCommand(SDIOx, &sdmmc_cmdinit); - - /* Check for error conditions */ - errorstate = SDMMC_GetCmdResp1(SDIOx, SDMMC_CMD_HS_SWITCH, SDIO_CMDTIMEOUT); - - return errorstate; -} - -/** - * @} - */ - -/* Private function ----------------------------------------------------------*/ -/** @addtogroup SD_Private_Functions - * @{ - */ - -/** - * @brief Checks for error conditions for CMD0. - * @param hsd: SD handle - * @retval SD Card error state - */ -static uint32_t SDMMC_GetCmdError(SDIO_TypeDef *SDIOx) -{ - /* 8 is the number of required instructions cycles for the below loop statement. - The SDMMC_CMDTIMEOUT is expressed in ms */ - register uint32_t count = SDIO_CMDTIMEOUT * (SystemCoreClock / 8U /1000U); - - do - { - if (count-- == 0U) - { - return SDMMC_ERROR_TIMEOUT; - } - - }while(!__SDIO_GET_FLAG(SDIOx, SDIO_FLAG_CMDSENT)); - - /* Clear all the static flags */ - __SDIO_CLEAR_FLAG(SDIOx, SDIO_STATIC_FLAGS); - - return SDMMC_ERROR_NONE; -} - -/** - * @brief Checks for error conditions for R1 response. - * @param hsd: SD handle - * @param SD_CMD: The sent command index - * @retval SD Card error state - */ -static uint32_t SDMMC_GetCmdResp1(SDIO_TypeDef *SDIOx, uint8_t SD_CMD, uint32_t Timeout) -{ - uint32_t response_r1; - - /* 8 is the number of required instructions cycles for the below loop statement. - The Timeout is expressed in ms */ - register uint32_t count = Timeout * (SystemCoreClock / 8U /1000U); - - do - { - if (count-- == 0U) - { - return SDMMC_ERROR_TIMEOUT; - } - - }while(!__SDIO_GET_FLAG(SDIOx, SDIO_FLAG_CCRCFAIL | SDIO_FLAG_CMDREND | SDIO_FLAG_CTIMEOUT)); - - if(__SDIO_GET_FLAG(SDIOx, SDIO_FLAG_CTIMEOUT)) - { - __SDIO_CLEAR_FLAG(SDIOx, SDIO_FLAG_CTIMEOUT); - - return SDMMC_ERROR_CMD_RSP_TIMEOUT; - } - else if(__SDIO_GET_FLAG(SDIOx, SDIO_FLAG_CCRCFAIL)) - { - __SDIO_CLEAR_FLAG(SDIOx, SDIO_FLAG_CCRCFAIL); - - return SDMMC_ERROR_CMD_CRC_FAIL; - } - - /* Check response received is of desired command */ - if(SDIO_GetCommandResponse(SDIOx) != SD_CMD) - { - return SDMMC_ERROR_CMD_CRC_FAIL; - } - - /* Clear all the static flags */ - __SDIO_CLEAR_FLAG(SDIOx, SDIO_STATIC_FLAGS); - - /* We have received response, retrieve it for analysis */ - response_r1 = SDIO_GetResponse(SDIOx, SDIO_RESP1); - - if((response_r1 & SDMMC_OCR_ERRORBITS) == SDMMC_ALLZERO) - { - return SDMMC_ERROR_NONE; - } - else if((response_r1 & SDMMC_OCR_ADDR_OUT_OF_RANGE) == SDMMC_OCR_ADDR_OUT_OF_RANGE) - { - return SDMMC_ERROR_ADDR_OUT_OF_RANGE; - } - else if((response_r1 & SDMMC_OCR_ADDR_MISALIGNED) == SDMMC_OCR_ADDR_MISALIGNED) - { - return SDMMC_ERROR_ADDR_MISALIGNED; - } - else if((response_r1 & SDMMC_OCR_BLOCK_LEN_ERR) == SDMMC_OCR_BLOCK_LEN_ERR) - { - return SDMMC_ERROR_BLOCK_LEN_ERR; - } - else if((response_r1 & SDMMC_OCR_ERASE_SEQ_ERR) == SDMMC_OCR_ERASE_SEQ_ERR) - { - return SDMMC_ERROR_ERASE_SEQ_ERR; - } - else if((response_r1 & SDMMC_OCR_BAD_ERASE_PARAM) == SDMMC_OCR_BAD_ERASE_PARAM) - { - return SDMMC_ERROR_BAD_ERASE_PARAM; - } - else if((response_r1 & SDMMC_OCR_WRITE_PROT_VIOLATION) == SDMMC_OCR_WRITE_PROT_VIOLATION) - { - return SDMMC_ERROR_WRITE_PROT_VIOLATION; - } - else if((response_r1 & SDMMC_OCR_LOCK_UNLOCK_FAILED) == SDMMC_OCR_LOCK_UNLOCK_FAILED) - { - return SDMMC_ERROR_LOCK_UNLOCK_FAILED; - } - else if((response_r1 & SDMMC_OCR_COM_CRC_FAILED) == SDMMC_OCR_COM_CRC_FAILED) - { - return SDMMC_ERROR_COM_CRC_FAILED; - } - else if((response_r1 & SDMMC_OCR_ILLEGAL_CMD) == SDMMC_OCR_ILLEGAL_CMD) - { - return SDMMC_ERROR_ILLEGAL_CMD; - } - else if((response_r1 & SDMMC_OCR_CARD_ECC_FAILED) == SDMMC_OCR_CARD_ECC_FAILED) - { - return SDMMC_ERROR_CARD_ECC_FAILED; - } - else if((response_r1 & SDMMC_OCR_CC_ERROR) == SDMMC_OCR_CC_ERROR) - { - return SDMMC_ERROR_CC_ERR; - } - else if((response_r1 & SDMMC_OCR_STREAM_READ_UNDERRUN) == SDMMC_OCR_STREAM_READ_UNDERRUN) - { - return SDMMC_ERROR_STREAM_READ_UNDERRUN; - } - else if((response_r1 & SDMMC_OCR_STREAM_WRITE_OVERRUN) == SDMMC_OCR_STREAM_WRITE_OVERRUN) - { - return SDMMC_ERROR_STREAM_WRITE_OVERRUN; - } - else if((response_r1 & SDMMC_OCR_CID_CSD_OVERWRITE) == SDMMC_OCR_CID_CSD_OVERWRITE) - { - return SDMMC_ERROR_CID_CSD_OVERWRITE; - } - else if((response_r1 & SDMMC_OCR_WP_ERASE_SKIP) == SDMMC_OCR_WP_ERASE_SKIP) - { - return SDMMC_ERROR_WP_ERASE_SKIP; - } - else if((response_r1 & SDMMC_OCR_CARD_ECC_DISABLED) == SDMMC_OCR_CARD_ECC_DISABLED) - { - return SDMMC_ERROR_CARD_ECC_DISABLED; - } - else if((response_r1 & SDMMC_OCR_ERASE_RESET) == SDMMC_OCR_ERASE_RESET) - { - return SDMMC_ERROR_ERASE_RESET; - } - else if((response_r1 & SDMMC_OCR_AKE_SEQ_ERROR) == SDMMC_OCR_AKE_SEQ_ERROR) - { - return SDMMC_ERROR_AKE_SEQ_ERR; - } - else - { - return SDMMC_ERROR_GENERAL_UNKNOWN_ERR; - } -} - -/** - * @brief Checks for error conditions for R2 (CID or CSD) response. - * @param hsd: SD handle - * @retval SD Card error state - */ -static uint32_t SDMMC_GetCmdResp2(SDIO_TypeDef *SDIOx) -{ - /* 8 is the number of required instructions cycles for the below loop statement. - The SDMMC_CMDTIMEOUT is expressed in ms */ - register uint32_t count = SDIO_CMDTIMEOUT * (SystemCoreClock / 8U /1000U); - - do - { - if (count-- == 0U) - { - return SDMMC_ERROR_TIMEOUT; - } - - }while(!__SDIO_GET_FLAG(SDIOx, SDIO_FLAG_CCRCFAIL | SDIO_FLAG_CMDREND | SDIO_FLAG_CTIMEOUT)); - - if (__SDIO_GET_FLAG(SDIOx, SDIO_FLAG_CTIMEOUT)) - { - __SDIO_CLEAR_FLAG(SDIOx, SDIO_FLAG_CTIMEOUT); - - return SDMMC_ERROR_CMD_RSP_TIMEOUT; - } - else if (__SDIO_GET_FLAG(SDIOx, SDIO_FLAG_CCRCFAIL)) - { - __SDIO_CLEAR_FLAG(SDIOx, SDIO_FLAG_CCRCFAIL); - - return SDMMC_ERROR_CMD_CRC_FAIL; - } - else - { - /* No error flag set */ - /* Clear all the static flags */ - __SDIO_CLEAR_FLAG(SDIOx, SDIO_STATIC_FLAGS); - } - - return SDMMC_ERROR_NONE; -} - -/** - * @brief Checks for error conditions for R3 (OCR) response. - * @param hsd: SD handle - * @retval SD Card error state - */ -static uint32_t SDMMC_GetCmdResp3(SDIO_TypeDef *SDIOx) -{ - /* 8 is the number of required instructions cycles for the below loop statement. - The SDMMC_CMDTIMEOUT is expressed in ms */ - register uint32_t count = SDIO_CMDTIMEOUT * (SystemCoreClock / 8U /1000U); - - do - { - if (count-- == 0U) - { - return SDMMC_ERROR_TIMEOUT; - } - - }while(!__SDIO_GET_FLAG(SDIOx, SDIO_FLAG_CCRCFAIL | SDIO_FLAG_CMDREND | SDIO_FLAG_CTIMEOUT)); - - if(__SDIO_GET_FLAG(SDIOx, SDIO_FLAG_CTIMEOUT)) - { - __SDIO_CLEAR_FLAG(SDIOx, SDIO_FLAG_CTIMEOUT); - - return SDMMC_ERROR_CMD_RSP_TIMEOUT; - } - else - - { - /* Clear all the static flags */ - __SDIO_CLEAR_FLAG(SDIOx, SDIO_STATIC_FLAGS); - } - - return SDMMC_ERROR_NONE; -} - -/** - * @brief Checks for error conditions for R6 (RCA) response. - * @param hsd: SD handle - * @param SD_CMD: The sent command index - * @param pRCA: Pointer to the variable that will contain the SD card relative - * address RCA - * @retval SD Card error state - */ -static uint32_t SDMMC_GetCmdResp6(SDIO_TypeDef *SDIOx, uint8_t SD_CMD, uint16_t *pRCA) -{ - uint32_t response_r1; - - /* 8 is the number of required instructions cycles for the below loop statement. - The SDMMC_CMDTIMEOUT is expressed in ms */ - register uint32_t count = SDIO_CMDTIMEOUT * (SystemCoreClock / 8U /1000U); - - do - { - if (count-- == 0U) - { - return SDMMC_ERROR_TIMEOUT; - } - - }while(!__SDIO_GET_FLAG(SDIOx, SDIO_FLAG_CCRCFAIL | SDIO_FLAG_CMDREND | SDIO_FLAG_CTIMEOUT)); - - if(__SDIO_GET_FLAG(SDIOx, SDIO_FLAG_CTIMEOUT)) - { - __SDIO_CLEAR_FLAG(SDIOx, SDIO_FLAG_CTIMEOUT); - - return SDMMC_ERROR_CMD_RSP_TIMEOUT; - } - else if(__SDIO_GET_FLAG(SDIOx, SDIO_FLAG_CCRCFAIL)) - { - __SDIO_CLEAR_FLAG(SDIOx, SDIO_FLAG_CCRCFAIL); - - return SDMMC_ERROR_CMD_CRC_FAIL; - } - - /* Check response received is of desired command */ - if(SDIO_GetCommandResponse(SDIOx) != SD_CMD) - { - return SDMMC_ERROR_CMD_CRC_FAIL; - } - - /* Clear all the static flags */ - __SDIO_CLEAR_FLAG(SDIOx, SDIO_STATIC_FLAGS); - - /* We have received response, retrieve it. */ - response_r1 = SDIO_GetResponse(SDIOx, SDIO_RESP1); - - if((response_r1 & (SDMMC_R6_GENERAL_UNKNOWN_ERROR | SDMMC_R6_ILLEGAL_CMD | SDMMC_R6_COM_CRC_FAILED)) == SDMMC_ALLZERO) - { - *pRCA = (uint16_t) (response_r1 >> 16); - - return SDMMC_ERROR_NONE; - } - else if((response_r1 & SDMMC_R6_ILLEGAL_CMD) == SDMMC_R6_ILLEGAL_CMD) - { - return SDMMC_ERROR_ILLEGAL_CMD; - } - else if((response_r1 & SDMMC_R6_COM_CRC_FAILED) == SDMMC_R6_COM_CRC_FAILED) - { - return SDMMC_ERROR_COM_CRC_FAILED; - } - else - { - return SDMMC_ERROR_GENERAL_UNKNOWN_ERR; - } + return HAL_OK; } -/** - * @brief Checks for error conditions for R7 response. - * @param hsd: SD handle - * @retval SD Card error state - */ -static uint32_t SDMMC_GetCmdResp7(SDIO_TypeDef *SDIOx) -{ - /* 8 is the number of required instructions cycles for the below loop statement. - The SDIO_CMDTIMEOUT is expressed in ms */ - register uint32_t count = SDIO_CMDTIMEOUT * (SystemCoreClock / 8U /1000U); - - do - { - if (count-- == 0U) - { - return SDMMC_ERROR_TIMEOUT; - } - - }while(!__SDIO_GET_FLAG(SDIOx, SDIO_FLAG_CCRCFAIL | SDIO_FLAG_CMDREND | SDIO_FLAG_CTIMEOUT)); - - if(__SDIO_GET_FLAG(SDIOx, SDIO_FLAG_CTIMEOUT)) - { - /* Card is SD V2.0 compliant */ - __SDIO_CLEAR_FLAG(SDIOx, SDIO_FLAG_CMDREND); - - return SDMMC_ERROR_CMD_RSP_TIMEOUT; - } - - if(__SDIO_GET_FLAG(SDIOx, SDIO_FLAG_CMDREND)) - { - /* Card is SD V2.0 compliant */ - __SDIO_CLEAR_FLAG(SDIOx, SDIO_FLAG_CMDREND); - } - - return SDMMC_ERROR_NONE; - -} /** * @} diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_sdmmc.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_sdmmc.h index 7ff5f3784e8..22009d814ce 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_sdmmc.h +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_sdmmc.h @@ -2,13 +2,13 @@ ****************************************************************************** * @file stm32f1xx_ll_sdmmc.h * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief Header file of low layer SDMMC HAL module. ****************************************************************************** * @attention * - *

© COPYRIGHT(c) 2017 STMicroelectronics

+ *

© COPYRIGHT(c) 2016 STMicroelectronics

* * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: @@ -147,201 +147,11 @@ typedef struct /** @defgroup SDMMC_LL_Exported_Constants SDMMC_LL Exported Constants * @{ */ -#define SDMMC_ERROR_NONE 0x00000000U /*!< No error */ -#define SDMMC_ERROR_CMD_CRC_FAIL 0x00000001U /*!< Command response received (but CRC check failed) */ -#define SDMMC_ERROR_DATA_CRC_FAIL 0x00000002U /*!< Data block sent/received (CRC check failed) */ -#define SDMMC_ERROR_CMD_RSP_TIMEOUT 0x00000004U /*!< Command response timeout */ -#define SDMMC_ERROR_DATA_TIMEOUT 0x00000008U /*!< Data timeout */ -#define SDMMC_ERROR_TX_UNDERRUN 0x00000010U /*!< Transmit FIFO underrun */ -#define SDMMC_ERROR_RX_OVERRUN 0x00000020U /*!< Receive FIFO overrun */ -#define SDMMC_ERROR_ADDR_MISALIGNED 0x00000040U /*!< Misaligned address */ -#define SDMMC_ERROR_BLOCK_LEN_ERR 0x00000080U /*!< Transferred block length is not allowed for the card or the - number of transferred bytes does not match the block length */ -#define SDMMC_ERROR_ERASE_SEQ_ERR 0x00000100U /*!< An error in the sequence of erase command occurs */ -#define SDMMC_ERROR_BAD_ERASE_PARAM 0x00000200U /*!< An invalid selection for erase groups */ -#define SDMMC_ERROR_WRITE_PROT_VIOLATION 0x00000400U /*!< Attempt to program a write protect block */ -#define SDMMC_ERROR_LOCK_UNLOCK_FAILED 0x00000800U /*!< Sequence or password error has been detected in unlock - command or if there was an attempt to access a locked card */ -#define SDMMC_ERROR_COM_CRC_FAILED 0x00001000U /*!< CRC check of the previous command failed */ -#define SDMMC_ERROR_ILLEGAL_CMD 0x00002000U /*!< Command is not legal for the card state */ -#define SDMMC_ERROR_CARD_ECC_FAILED 0x00004000U /*!< Card internal ECC was applied but failed to correct the data */ -#define SDMMC_ERROR_CC_ERR 0x00008000U /*!< Internal card controller error */ -#define SDMMC_ERROR_GENERAL_UNKNOWN_ERR 0x00010000U /*!< General or unknown error */ -#define SDMMC_ERROR_STREAM_READ_UNDERRUN 0x00020000U /*!< The card could not sustain data reading in stream rmode */ -#define SDMMC_ERROR_STREAM_WRITE_OVERRUN 0x00040000U /*!< The card could not sustain data programming in stream mode */ -#define SDMMC_ERROR_CID_CSD_OVERWRITE 0x00080000U /*!< CID/CSD overwrite error */ -#define SDMMC_ERROR_WP_ERASE_SKIP 0x00100000U /*!< Only partial address space was erased */ -#define SDMMC_ERROR_CARD_ECC_DISABLED 0x00200000U /*!< Command has been executed without using internal ECC */ -#define SDMMC_ERROR_ERASE_RESET 0x00400000U /*!< Erase sequence was cleared before executing because an out - of erase sequence command was received */ -#define SDMMC_ERROR_AKE_SEQ_ERR 0x00800000U /*!< Error in sequence of authentication */ -#define SDMMC_ERROR_INVALID_VOLTRANGE 0x01000000U /*!< Error in case of invalid voltage range */ -#define SDMMC_ERROR_ADDR_OUT_OF_RANGE 0x02000000U /*!< Error when addressed block is out of range */ -#define SDMMC_ERROR_REQUEST_NOT_APPLICABLE 0x04000000U /*!< Error when command request is not applicable */ -#define SDMMC_ERROR_INVALID_PARAMETER 0x08000000U /*!< the used parameter is not valid */ -#define SDMMC_ERROR_UNSUPPORTED_FEATURE 0x10000000U /*!< Error when feature is not insupported */ -#define SDMMC_ERROR_BUSY 0x20000000U /*!< Error when transfer process is busy */ -#define SDMMC_ERROR_DMA 0x40000000U /*!< Error while DMA transfer */ -#define SDMMC_ERROR_TIMEOUT 0x80000000U /*!< Timeout error */ -/** - * @brief SDMMC Commands Index - */ -#define SDMMC_CMD_GO_IDLE_STATE ((uint8_t)0) /*!< Resets the SD memory card. */ -#define SDMMC_CMD_SEND_OP_COND ((uint8_t)1) /*!< Sends host capacity support information and activates the card's initialization process. */ -#define SDMMC_CMD_ALL_SEND_CID ((uint8_t)2) /*!< Asks any card connected to the host to send the CID numbers on the CMD line. */ -#define SDMMC_CMD_SET_REL_ADDR ((uint8_t)3) /*!< Asks the card to publish a new relative address (RCA). */ -#define SDMMC_CMD_SET_DSR ((uint8_t)4) /*!< Programs the DSR of all cards. */ -#define SDMMC_CMD_SDMMC_SEN_OP_COND ((uint8_t)5) /*!< Sends host capacity support information (HCS) and asks the accessed card to send its - operating condition register (OCR) content in the response on the CMD line. */ -#define SDMMC_CMD_HS_SWITCH ((uint8_t)6) /*!< Checks switchable function (mode 0) and switch card function (mode 1). */ -#define SDMMC_CMD_SEL_DESEL_CARD ((uint8_t)7) /*!< Selects the card by its own relative address and gets deselected by any other address */ -#define SDMMC_CMD_HS_SEND_EXT_CSD ((uint8_t)8) /*!< Sends SD Memory Card interface condition, which includes host supply voltage information - and asks the card whether card supports voltage. */ -#define SDMMC_CMD_SEND_CSD ((uint8_t)9) /*!< Addressed card sends its card specific data (CSD) on the CMD line. */ -#define SDMMC_CMD_SEND_CID ((uint8_t)10) /*!< Addressed card sends its card identification (CID) on the CMD line. */ -#define SDMMC_CMD_READ_DAT_UNTIL_STOP ((uint8_t)11) /*!< SD card doesn't support it. */ -#define SDMMC_CMD_STOP_TRANSMISSION ((uint8_t)12) /*!< Forces the card to stop transmission. */ -#define SDMMC_CMD_SEND_STATUS ((uint8_t)13) /*!< Addressed card sends its status register. */ -#define SDMMC_CMD_HS_BUSTEST_READ ((uint8_t)14) /*!< Reserved */ -#define SDMMC_CMD_GO_INACTIVE_STATE ((uint8_t)15) /*!< Sends an addressed card into the inactive state. */ -#define SDMMC_CMD_SET_BLOCKLEN ((uint8_t)16) /*!< Sets the block length (in bytes for SDSC) for all following block commands - (read, write, lock). Default block length is fixed to 512 Bytes. Not effective - for SDHS and SDXC. */ -#define SDMMC_CMD_READ_SINGLE_BLOCK ((uint8_t)17) /*!< Reads single block of size selected by SET_BLOCKLEN in case of SDSC, and a block of - fixed 512 bytes in case of SDHC and SDXC. */ -#define SDMMC_CMD_READ_MULT_BLOCK ((uint8_t)18) /*!< Continuously transfers data blocks from card to host until interrupted by - STOP_TRANSMISSION command. */ -#define SDMMC_CMD_HS_BUSTEST_WRITE ((uint8_t)19) /*!< 64 bytes tuning pattern is sent for SDR50 and SDR104. */ -#define SDMMC_CMD_WRITE_DAT_UNTIL_STOP ((uint8_t)20) /*!< Speed class control command. */ -#define SDMMC_CMD_SET_BLOCK_COUNT ((uint8_t)23) /*!< Specify block count for CMD18 and CMD25. */ -#define SDMMC_CMD_WRITE_SINGLE_BLOCK ((uint8_t)24) /*!< Writes single block of size selected by SET_BLOCKLEN in case of SDSC, and a block of - fixed 512 bytes in case of SDHC and SDXC. */ -#define SDMMC_CMD_WRITE_MULT_BLOCK ((uint8_t)25) /*!< Continuously writes blocks of data until a STOP_TRANSMISSION follows. */ -#define SDMMC_CMD_PROG_CID ((uint8_t)26) /*!< Reserved for manufacturers. */ -#define SDMMC_CMD_PROG_CSD ((uint8_t)27) /*!< Programming of the programmable bits of the CSD. */ -#define SDMMC_CMD_SET_WRITE_PROT ((uint8_t)28) /*!< Sets the write protection bit of the addressed group. */ -#define SDMMC_CMD_CLR_WRITE_PROT ((uint8_t)29) /*!< Clears the write protection bit of the addressed group. */ -#define SDMMC_CMD_SEND_WRITE_PROT ((uint8_t)30) /*!< Asks the card to send the status of the write protection bits. */ -#define SDMMC_CMD_SD_ERASE_GRP_START ((uint8_t)32) /*!< Sets the address of the first write block to be erased. (For SD card only). */ -#define SDMMC_CMD_SD_ERASE_GRP_END ((uint8_t)33) /*!< Sets the address of the last write block of the continuous range to be erased. */ -#define SDMMC_CMD_ERASE_GRP_START ((uint8_t)35) /*!< Sets the address of the first write block to be erased. Reserved for each command - system set by switch function command (CMD6). */ -#define SDMMC_CMD_ERASE_GRP_END ((uint8_t)36) /*!< Sets the address of the last write block of the continuous range to be erased. - Reserved for each command system set by switch function command (CMD6). */ -#define SDMMC_CMD_ERASE ((uint8_t)38) /*!< Reserved for SD security applications. */ -#define SDMMC_CMD_FAST_IO ((uint8_t)39) /*!< SD card doesn't support it (Reserved). */ -#define SDMMC_CMD_GO_IRQ_STATE ((uint8_t)40) /*!< SD card doesn't support it (Reserved). */ -#define SDMMC_CMD_LOCK_UNLOCK ((uint8_t)42) /*!< Sets/resets the password or lock/unlock the card. The size of the data block is set by - the SET_BLOCK_LEN command. */ -#define SDMMC_CMD_APP_CMD ((uint8_t)55) /*!< Indicates to the card that the next command is an application specific command rather - than a standard command. */ -#define SDMMC_CMD_GEN_CMD ((uint8_t)56) /*!< Used either to transfer a data block to the card or to get a data block from the card - for general purpose/application specific commands. */ -#define SDMMC_CMD_NO_CMD ((uint8_t)64) /*!< No command */ - -/** - * @brief Following commands are SD Card Specific commands. - * SDMMC_APP_CMD should be sent before sending these commands. - */ -#define SDMMC_CMD_APP_SD_SET_BUSWIDTH ((uint8_t)6) /*!< (ACMD6) Defines the data bus width to be used for data transfer. The allowed data bus - widths are given in SCR register. */ -#define SDMMC_CMD_SD_APP_STATUS ((uint8_t)13) /*!< (ACMD13) Sends the SD status. */ -#define SDMMC_CMD_SD_APP_SEND_NUM_WRITE_BLOCKS ((uint8_t)22) /*!< (ACMD22) Sends the number of the written (without errors) write blocks. Responds with - 32bit+CRC data block. */ -#define SDMMC_CMD_SD_APP_OP_COND ((uint8_t)41) /*!< (ACMD41) Sends host capacity support information (HCS) and asks the accessed card to - send its operating condition register (OCR) content in the response on the CMD line. */ -#define SDMMC_CMD_SD_APP_SET_CLR_CARD_DETECT ((uint8_t)42) /*!< (ACMD42) Connect/Disconnect the 50 KOhm pull-up resistor on CD/DAT3 (pin 1) of the card */ -#define SDMMC_CMD_SD_APP_SEND_SCR ((uint8_t)51) /*!< Reads the SD Configuration Register (SCR). */ -#define SDMMC_CMD_SDMMC_RW_DIRECT ((uint8_t)52) /*!< For SD I/O card only, reserved for security specification. */ -#define SDMMC_CMD_SDMMC_RW_EXTENDED ((uint8_t)53) /*!< For SD I/O card only, reserved for security specification. */ - -/** - * @brief Following commands are SD Card Specific security commands. - * SDMMC_CMD_APP_CMD should be sent before sending these commands. - */ -#define SDMMC_CMD_SD_APP_GET_MKB ((uint8_t)43) -#define SDMMC_CMD_SD_APP_GET_MID ((uint8_t)44) -#define SDMMC_CMD_SD_APP_SET_CER_RN1 ((uint8_t)45) -#define SDMMC_CMD_SD_APP_GET_CER_RN2 ((uint8_t)46) -#define SDMMC_CMD_SD_APP_SET_CER_RES2 ((uint8_t)47) -#define SDMMC_CMD_SD_APP_GET_CER_RES1 ((uint8_t)48) -#define SDMMC_CMD_SD_APP_SECURE_READ_MULTIPLE_BLOCK ((uint8_t)18) -#define SDMMC_CMD_SD_APP_SECURE_WRITE_MULTIPLE_BLOCK ((uint8_t)25) -#define SDMMC_CMD_SD_APP_SECURE_ERASE ((uint8_t)38) -#define SDMMC_CMD_SD_APP_CHANGE_SECURE_AREA ((uint8_t)49) -#define SDMMC_CMD_SD_APP_SECURE_WRITE_MKB ((uint8_t)48) - -/** - * @brief Masks for errors Card Status R1 (OCR Register) - */ -#define SDMMC_OCR_ADDR_OUT_OF_RANGE 0x80000000U -#define SDMMC_OCR_ADDR_MISALIGNED 0x40000000U -#define SDMMC_OCR_BLOCK_LEN_ERR 0x20000000U -#define SDMMC_OCR_ERASE_SEQ_ERR 0x10000000U -#define SDMMC_OCR_BAD_ERASE_PARAM 0x08000000U -#define SDMMC_OCR_WRITE_PROT_VIOLATION 0x04000000U -#define SDMMC_OCR_LOCK_UNLOCK_FAILED 0x01000000U -#define SDMMC_OCR_COM_CRC_FAILED 0x00800000U -#define SDMMC_OCR_ILLEGAL_CMD 0x00400000U -#define SDMMC_OCR_CARD_ECC_FAILED 0x00200000U -#define SDMMC_OCR_CC_ERROR 0x00100000U -#define SDMMC_OCR_GENERAL_UNKNOWN_ERROR 0x00080000U -#define SDMMC_OCR_STREAM_READ_UNDERRUN 0x00040000U -#define SDMMC_OCR_STREAM_WRITE_OVERRUN 0x00020000U -#define SDMMC_OCR_CID_CSD_OVERWRITE 0x00010000U -#define SDMMC_OCR_WP_ERASE_SKIP 0x00008000U -#define SDMMC_OCR_CARD_ECC_DISABLED 0x00004000U -#define SDMMC_OCR_ERASE_RESET 0x00002000U -#define SDMMC_OCR_AKE_SEQ_ERROR 0x00000008U -#define SDMMC_OCR_ERRORBITS 0xFDFFE008U - -/** - * @brief Masks for R6 Response - */ -#define SDMMC_R6_GENERAL_UNKNOWN_ERROR 0x00002000U -#define SDMMC_R6_ILLEGAL_CMD 0x00004000U -#define SDMMC_R6_COM_CRC_FAILED 0x00008000U - -#define SDMMC_VOLTAGE_WINDOW_SD 0x80100000U -#define SDMMC_HIGH_CAPACITY 0x40000000U -#define SDMMC_STD_CAPACITY 0x00000000U -#define SDMMC_CHECK_PATTERN 0x000001AAU - -#define SDMMC_MAX_VOLT_TRIAL 0x0000FFFFU - -#define SDMMC_MAX_TRIAL 0x0000FFFFU - -#define SDMMC_ALLZERO 0x00000000U - -#define SDMMC_WIDE_BUS_SUPPORT 0x00040000U -#define SDMMC_SINGLE_BUS_SUPPORT 0x00010000U -#define SDMMC_CARD_LOCKED 0x02000000U - -#define SDMMC_DATATIMEOUT 0xFFFFFFFFU - -#define SDMMC_0TO7BITS 0x000000FFU -#define SDMMC_8TO15BITS 0x0000FF00U -#define SDMMC_16TO23BITS 0x00FF0000U -#define SDMMC_24TO31BITS 0xFF000000U -#define SDMMC_MAX_DATA_LENGTH 0x01FFFFFFU - -#define SDMMC_HALFFIFO 0x00000008U -#define SDMMC_HALFFIFOBYTES 0x00000020U - -/** - * @brief Command Class supported - */ -#define SDIO_CCCC_ERASE 0x00000020U - -#define SDIO_CMDTIMEOUT 5000U /* Command send and response timeout */ -#define SDIO_MAXERASETIMEOUT 63000U /* Max erase Timeout 63 s */ - - -/** @defgroup SDIO_LL_Clock_Edge Clock Edge +/** @defgroup SDMMC_LL_Clock_Edge Clock Edge * @{ */ -#define SDIO_CLOCK_EDGE_RISING 0x00000000U +#define SDIO_CLOCK_EDGE_RISING ((uint32_t)0x00000000) #define SDIO_CLOCK_EDGE_FALLING SDIO_CLKCR_NEGEDGE #define IS_SDIO_CLOCK_EDGE(EDGE) (((EDGE) == SDIO_CLOCK_EDGE_RISING) || \ @@ -350,10 +160,10 @@ typedef struct * @} */ -/** @defgroup SDIO_LL_Clock_Bypass Clock Bypass +/** @defgroup SDMMC_LL_Clock_Bypass Clock Bypass * @{ */ -#define SDIO_CLOCK_BYPASS_DISABLE 0x00000000U +#define SDIO_CLOCK_BYPASS_DISABLE ((uint32_t)0x00000000) #define SDIO_CLOCK_BYPASS_ENABLE SDIO_CLKCR_BYPASS #define IS_SDIO_CLOCK_BYPASS(BYPASS) (((BYPASS) == SDIO_CLOCK_BYPASS_DISABLE) || \ @@ -362,10 +172,10 @@ typedef struct * @} */ -/** @defgroup SDIO_LL_Clock_Power_Save Clock Power Saving +/** @defgroup SDMMC_LL_Clock_Power_Save Clock Power Saving * @{ */ -#define SDIO_CLOCK_POWER_SAVE_DISABLE 0x00000000U +#define SDIO_CLOCK_POWER_SAVE_DISABLE ((uint32_t)0x00000000) #define SDIO_CLOCK_POWER_SAVE_ENABLE SDIO_CLKCR_PWRSAV #define IS_SDIO_CLOCK_POWER_SAVE(SAVE) (((SAVE) == SDIO_CLOCK_POWER_SAVE_DISABLE) || \ @@ -374,10 +184,10 @@ typedef struct * @} */ -/** @defgroup SDIO_LL_Bus_Wide Bus Width +/** @defgroup SDMMC_LL_Bus_Wide Bus Width * @{ */ -#define SDIO_BUS_WIDE_1B 0x00000000U +#define SDIO_BUS_WIDE_1B ((uint32_t)0x00000000) #define SDIO_BUS_WIDE_4B SDIO_CLKCR_WIDBUS_0 #define SDIO_BUS_WIDE_8B SDIO_CLKCR_WIDBUS_1 @@ -388,10 +198,10 @@ typedef struct * @} */ -/** @defgroup SDIO_LL_Hardware_Flow_Control Hardware Flow Control +/** @defgroup SDMMC_LL_Hardware_Flow_Control Hardware Flow Control * @{ */ -#define SDIO_HARDWARE_FLOW_CONTROL_DISABLE 0x00000000U +#define SDIO_HARDWARE_FLOW_CONTROL_DISABLE ((uint32_t)0x00000000) #define SDIO_HARDWARE_FLOW_CONTROL_ENABLE SDIO_CLKCR_HWFC_EN #define IS_SDIO_HARDWARE_FLOW_CONTROL(CONTROL) (((CONTROL) == SDIO_HARDWARE_FLOW_CONTROL_DISABLE) || \ @@ -400,26 +210,26 @@ typedef struct * @} */ -/** @defgroup SDIO_LL_Clock_Division Clock Division +/** @defgroup SDMMC_LL_Clock_Division Clock Division * @{ */ -#define IS_SDIO_CLKDIV(DIV) ((DIV) <= 0xFFU) +#define IS_SDIO_CLKDIV(DIV) ((DIV) <= 0xFF) /** * @} */ -/** @defgroup SDIO_LL_Command_Index Command Index +/** @defgroup SDMMC_LL_Command_Index Command Index * @{ */ -#define IS_SDIO_CMD_INDEX(INDEX) ((INDEX) < 0x40U) +#define IS_SDIO_CMD_INDEX(INDEX) ((INDEX) < 0x40) /** * @} */ -/** @defgroup SDIO_LL_Response_Type Response Type +/** @defgroup SDMMC_LL_Response_Type Response Type * @{ */ -#define SDIO_RESPONSE_NO 0x00000000U +#define SDIO_RESPONSE_NO ((uint32_t)0x00000000) #define SDIO_RESPONSE_SHORT SDIO_CMD_WAITRESP_0 #define SDIO_RESPONSE_LONG SDIO_CMD_WAITRESP @@ -430,10 +240,10 @@ typedef struct * @} */ -/** @defgroup SDIO_LL_Wait_Interrupt_State Wait Interrupt +/** @defgroup SDMMC_LL_Wait_Interrupt_State Wait Interrupt * @{ */ -#define SDIO_WAIT_NO 0x00000000U +#define SDIO_WAIT_NO ((uint32_t)0x00000000) #define SDIO_WAIT_IT SDIO_CMD_WAITINT #define SDIO_WAIT_PEND SDIO_CMD_WAITPEND @@ -444,10 +254,10 @@ typedef struct * @} */ -/** @defgroup SDIO_LL_CPSM_State CPSM State +/** @defgroup SDMMC_LL_CPSM_State CPSM State * @{ */ -#define SDIO_CPSM_DISABLE 0x00000000U +#define SDIO_CPSM_DISABLE ((uint32_t)0x00000000) #define SDIO_CPSM_ENABLE SDIO_CMD_CPSMEN #define IS_SDIO_CPSM(CPSM) (((CPSM) == SDIO_CPSM_DISABLE) || \ @@ -456,13 +266,13 @@ typedef struct * @} */ -/** @defgroup SDIO_LL_Response_Registers Response Register +/** @defgroup SDMMC_LL_Response_Registers Response Register * @{ */ -#define SDIO_RESP1 0x00000000U -#define SDIO_RESP2 0x00000004U -#define SDIO_RESP3 0x00000008U -#define SDIO_RESP4 0x0000000CU +#define SDIO_RESP1 ((uint32_t)0x00000000) +#define SDIO_RESP2 ((uint32_t)0x00000004) +#define SDIO_RESP3 ((uint32_t)0x00000008) +#define SDIO_RESP4 ((uint32_t)0x0000000C) #define IS_SDIO_RESP(RESP) (((RESP) == SDIO_RESP1) || \ ((RESP) == SDIO_RESP2) || \ @@ -472,18 +282,18 @@ typedef struct * @} */ -/** @defgroup SDIO_LL_Data_Length Data Lenght +/** @defgroup SDMMC_LL_Data_Length Data Lenght * @{ */ -#define IS_SDIO_DATA_LENGTH(LENGTH) ((LENGTH) <= 0x01FFFFFFU) +#define IS_SDIO_DATA_LENGTH(LENGTH) ((LENGTH) <= 0x01FFFFFF) /** * @} */ -/** @defgroup SDIO_LL_Data_Block_Size Data Block Size +/** @defgroup SDMMC_LL_Data_Block_Size Data Block Size * @{ */ -#define SDIO_DATABLOCK_SIZE_1B 0x00000000U +#define SDIO_DATABLOCK_SIZE_1B ((uint32_t)0x00000000) #define SDIO_DATABLOCK_SIZE_2B SDIO_DCTRL_DBLOCKSIZE_0 #define SDIO_DATABLOCK_SIZE_4B SDIO_DCTRL_DBLOCKSIZE_1 #define SDIO_DATABLOCK_SIZE_8B (SDIO_DCTRL_DBLOCKSIZE_0|SDIO_DCTRL_DBLOCKSIZE_1) @@ -518,10 +328,10 @@ typedef struct * @} */ -/** @defgroup SDIO_LL_Transfer_Direction Transfer Direction +/** @defgroup SDMMC_LL_Transfer_Direction Transfer Direction * @{ */ -#define SDIO_TRANSFER_DIR_TO_CARD 0x00000000U +#define SDIO_TRANSFER_DIR_TO_CARD ((uint32_t)0x00000000) #define SDIO_TRANSFER_DIR_TO_SDIO SDIO_DCTRL_DTDIR #define IS_SDIO_TRANSFER_DIR(DIR) (((DIR) == SDIO_TRANSFER_DIR_TO_CARD) || \ @@ -530,10 +340,10 @@ typedef struct * @} */ -/** @defgroup SDIO_LL_Transfer_Type Transfer Type +/** @defgroup SDMMC_LL_Transfer_Type Transfer Type * @{ */ -#define SDIO_TRANSFER_MODE_BLOCK 0x00000000U +#define SDIO_TRANSFER_MODE_BLOCK ((uint32_t)0x00000000) #define SDIO_TRANSFER_MODE_STREAM SDIO_DCTRL_DTMODE #define IS_SDIO_TRANSFER_MODE(MODE) (((MODE) == SDIO_TRANSFER_MODE_BLOCK) || \ @@ -542,10 +352,10 @@ typedef struct * @} */ -/** @defgroup SDIO_LL_DPSM_State DPSM State +/** @defgroup SDMMC_LL_DPSM_State DPSM State * @{ */ -#define SDIO_DPSM_DISABLE 0x00000000U +#define SDIO_DPSM_DISABLE ((uint32_t)0x00000000) #define SDIO_DPSM_ENABLE SDIO_DCTRL_DTEN #define IS_SDIO_DPSM(DPSM) (((DPSM) == SDIO_DPSM_DISABLE) ||\ @@ -554,10 +364,10 @@ typedef struct * @} */ -/** @defgroup SDIO_LL_Read_Wait_Mode Read Wait Mode +/** @defgroup SDMMC_LL_Read_Wait_Mode Read Wait Mode * @{ */ -#define SDIO_READ_WAIT_MODE_DATA2 0x00000000U +#define SDIO_READ_WAIT_MODE_DATA2 ((uint32_t)0x00000000) #define SDIO_READ_WAIT_MODE_CLK (SDIO_DCTRL_RWMOD) #define IS_SDIO_READWAIT_MODE(MODE) (((MODE) == SDIO_READ_WAIT_MODE_CLK) || \ @@ -566,7 +376,7 @@ typedef struct * @} */ -/** @defgroup SDIO_LL_Interrupt_sources Interrupt Sources +/** @defgroup SDMMC_LL_Interrupt_sources Interrupt Sources * @{ */ #define SDIO_IT_CCRCFAIL SDIO_STA_CCRCFAIL @@ -593,6 +403,7 @@ typedef struct #define SDIO_IT_RXDAVL SDIO_STA_RXDAVL #define SDIO_IT_SDIOIT SDIO_STA_SDIOIT #define SDIO_IT_CEATAEND SDIO_STA_CEATAEND + /** * @} */ @@ -624,82 +435,25 @@ typedef struct #define SDIO_FLAG_RXDAVL SDIO_STA_RXDAVL #define SDIO_FLAG_SDIOIT SDIO_STA_SDIOIT #define SDIO_FLAG_CEATAEND SDIO_STA_CEATAEND -#define SDIO_STATIC_FLAGS ((uint32_t)(SDIO_FLAG_CCRCFAIL | SDIO_FLAG_DCRCFAIL | SDIO_FLAG_CTIMEOUT |\ - SDIO_FLAG_DTIMEOUT | SDIO_FLAG_TXUNDERR | SDIO_FLAG_RXOVERR |\ - SDIO_FLAG_CMDREND | SDIO_FLAG_CMDSENT | SDIO_FLAG_DATAEND |\ - SDIO_FLAG_DBCKEND)) + /** * @} */ /** * @} - */ + */ /* Exported macro ------------------------------------------------------------*/ -/** @defgroup SDIO_LL_Exported_macros SDIO_LL Exported Macros - * @{ - */ - -/** @defgroup SDMMC_LL_Alias_Region Bit Address in the alias region +/** @defgroup SDMMC_LL_Exported_macros SDMMC_LL Exported Macros * @{ */ -/* ------------ SDIO registers bit address in the alias region -------------- */ -#define SDIO_OFFSET (SDIO_BASE - PERIPH_BASE) - -/* --- CLKCR Register ---*/ -/* Alias word address of CLKEN bit */ -#define CLKCR_OFFSET (SDIO_OFFSET + 0x04U) -#define CLKEN_BITNUMBER 0x08U -#define CLKCR_CLKEN_BB (PERIPH_BB_BASE + (CLKCR_OFFSET * 32U) + (CLKEN_BITNUMBER * 4U)) - -/* --- CMD Register ---*/ -/* Alias word address of SDIOSUSPEND bit */ -#define CMD_OFFSET (SDIO_OFFSET + 0x0CU) -#define SDIOSUSPEND_BITNUMBER 0x0BU -#define CMD_SDIOSUSPEND_BB (PERIPH_BB_BASE + (CMD_OFFSET * 32U) + (SDIOSUSPEND_BITNUMBER * 4U)) - -/* Alias word address of ENCMDCOMPL bit */ -#define ENCMDCOMPL_BITNUMBER 0x0CU -#define CMD_ENCMDCOMPL_BB (PERIPH_BB_BASE + (CMD_OFFSET * 32U) + (ENCMDCOMPL_BITNUMBER * 4U)) - -/* Alias word address of NIEN bit */ -#define NIEN_BITNUMBER 0x0DU -#define CMD_NIEN_BB (PERIPH_BB_BASE + (CMD_OFFSET * 32U) + (NIEN_BITNUMBER * 4U)) - -/* Alias word address of ATACMD bit */ -#define ATACMD_BITNUMBER 0x0EU -#define CMD_ATACMD_BB (PERIPH_BB_BASE + (CMD_OFFSET * 32U) + (ATACMD_BITNUMBER * 4U)) - -/* --- DCTRL Register ---*/ -/* Alias word address of DMAEN bit */ -#define DCTRL_OFFSET (SDIO_OFFSET + 0x2CU) -#define DMAEN_BITNUMBER 0x03U -#define DCTRL_DMAEN_BB (PERIPH_BB_BASE + (DCTRL_OFFSET * 32U) + (DMAEN_BITNUMBER * 4U)) - -/* Alias word address of RWSTART bit */ -#define RWSTART_BITNUMBER 0x08U -#define DCTRL_RWSTART_BB (PERIPH_BB_BASE + (DCTRL_OFFSET * 32U) + (RWSTART_BITNUMBER * 4U)) - -/* Alias word address of RWSTOP bit */ -#define RWSTOP_BITNUMBER 0x09U -#define DCTRL_RWSTOP_BB (PERIPH_BB_BASE + (DCTRL_OFFSET * 32U) + (RWSTOP_BITNUMBER * 4U)) - -/* Alias word address of RWMOD bit */ -#define RWMOD_BITNUMBER 0x0AU -#define DCTRL_RWMOD_BB (PERIPH_BB_BASE + (DCTRL_OFFSET * 32U) + (RWMOD_BITNUMBER * 4U)) - -/* Alias word address of SDIOEN bit */ -#define SDIOEN_BITNUMBER 0x0BU -#define DCTRL_SDIOEN_BB (PERIPH_BB_BASE + (DCTRL_OFFSET * 32U) + (SDIOEN_BITNUMBER * 4U)) -/** - * @} - */ - -/** @defgroup SDIO_LL_Register Bits And Addresses Definitions - * @brief SDIO_LL registers bit address in the alias region + +/** @defgroup SDMMC_LL_Register Bits And Addresses Definitions + * @brief SDMMC_LL registers bit address in the alias region * @{ */ + /* ---------------------- SDIO registers bit mask --------------------------- */ /* --- CLKCR Register ---*/ /* CLKCR register clear mask */ @@ -730,38 +484,38 @@ typedef struct /** * @} */ - -/** @defgroup SDIO_LL_Interrupt_Clock Interrupt And Clock Configuration - * @brief macros to handle interrupts and specific clock configurations - * @{ - */ + +/** @defgroup SDMMC_LL_Interrupt_Clock Interrupt And Clock Configuration + * @brief macros to handle interrupts and specific clock configurations + * @{ + */ /** * @brief Enable the SDIO device. * @param __INSTANCE__: SDIO Instance * @retval None */ -#define __SDIO_ENABLE(__INSTANCE__) (*(__IO uint32_t *)CLKCR_CLKEN_BB = ENABLE) +#define __SDIO_ENABLE(__INSTANCE__) ((__INSTANCE__)->CLKCR |= SDIO_CLKCR_CLKEN) /** * @brief Disable the SDIO device. * @param __INSTANCE__: SDIO Instance * @retval None */ -#define __SDIO_DISABLE(__INSTANCE__) (*(__IO uint32_t *)CLKCR_CLKEN_BB = DISABLE) +#define __SDIO_DISABLE(__INSTANCE__) ((__INSTANCE__)->CLKCR &= ~SDIO_CLKCR_CLKEN) /** * @brief Enable the SDIO DMA transfer. - * @param __INSTANCE__: SDIO Instance + * @param None * @retval None */ -#define __SDIO_DMA_ENABLE(__INSTANCE__) (*(__IO uint32_t *)DCTRL_DMAEN_BB = ENABLE) +#define __SDIO_DMA_ENABLE(__INSTANCE__) ((__INSTANCE__)->DCTRL |= SDIO_DCTRL_DMAEN) /** * @brief Disable the SDIO DMA transfer. - * @param __INSTANCE__: SDIO Instance + * @param None * @retval None */ -#define __SDIO_DMA_DISABLE(__INSTANCE__) (*(__IO uint32_t *)DCTRL_DMAEN_BB = DISABLE) +#define __SDIO_DMA_DISABLE(__INSTANCE__) ((__INSTANCE__)->DCTRL &= ~SDIO_DCTRL_DMAEN) /** * @brief Enable the SDIO device interrupt. @@ -777,6 +531,8 @@ typedef struct * @arg SDIO_IT_CMDREND: Command response received (CRC check passed) interrupt * @arg SDIO_IT_CMDSENT: Command sent (no response required) interrupt * @arg SDIO_IT_DATAEND: Data end (data counter, SDIDCOUNT, is zero) interrupt + * @arg SDIO_IT_STBITERR: Start bit not detected on all data signals in wide + * bus mode interrupt * @arg SDIO_IT_DBCKEND: Data block sent/received (CRC check passed) interrupt * @arg SDIO_IT_CMDACT: Command transfer in progress interrupt * @arg SDIO_IT_TXACT: Data transmit in progress interrupt @@ -789,7 +545,8 @@ typedef struct * @arg SDIO_IT_RXFIFOE: Receive FIFO empty interrupt * @arg SDIO_IT_TXDAVL: Data available in transmit FIFO interrupt * @arg SDIO_IT_RXDAVL: Data available in receive FIFO interrupt - * @arg SDIO_IT_SDIOIT: SD I/O interrupt received interrupt + * @arg SDIO_IT_SDIOIT: SD I/O interrupt received interrupt + * @arg SDIO_IT_CEATAEND: CE-ATA command completion signal received for CMD61 interrupt * @retval None */ #define __SDIO_ENABLE_IT(__INSTANCE__, __INTERRUPT__) ((__INSTANCE__)->MASK |= (__INTERRUPT__)) @@ -808,6 +565,8 @@ typedef struct * @arg SDIO_IT_CMDREND: Command response received (CRC check passed) interrupt * @arg SDIO_IT_CMDSENT: Command sent (no response required) interrupt * @arg SDIO_IT_DATAEND: Data end (data counter, SDIDCOUNT, is zero) interrupt + * @arg SDIO_IT_STBITERR: Start bit not detected on all data signals in wide + * bus mode interrupt * @arg SDIO_IT_DBCKEND: Data block sent/received (CRC check passed) interrupt * @arg SDIO_IT_CMDACT: Command transfer in progress interrupt * @arg SDIO_IT_TXACT: Data transmit in progress interrupt @@ -820,7 +579,8 @@ typedef struct * @arg SDIO_IT_RXFIFOE: Receive FIFO empty interrupt * @arg SDIO_IT_TXDAVL: Data available in transmit FIFO interrupt * @arg SDIO_IT_RXDAVL: Data available in receive FIFO interrupt - * @arg SDIO_IT_SDIOIT: SD I/O interrupt received interrupt + * @arg SDIO_IT_SDIOIT: SD I/O interrupt received interrupt + * @arg SDIO_IT_CEATAEND: CE-ATA command completion signal received for CMD61 interrupt * @retval None */ #define __SDIO_DISABLE_IT(__INSTANCE__, __INTERRUPT__) ((__INSTANCE__)->MASK &= ~(__INTERRUPT__)) @@ -839,6 +599,7 @@ typedef struct * @arg SDIO_FLAG_CMDREND: Command response received (CRC check passed) * @arg SDIO_FLAG_CMDSENT: Command sent (no response required) * @arg SDIO_FLAG_DATAEND: Data end (data counter, SDIDCOUNT, is zero) + * @arg SDIO_FLAG_STBITERR: Start bit not detected on all data signals in wide bus mode. * @arg SDIO_FLAG_DBCKEND: Data block sent/received (CRC check passed) * @arg SDIO_FLAG_CMDACT: Command transfer in progress * @arg SDIO_FLAG_TXACT: Data transmit in progress @@ -852,9 +613,10 @@ typedef struct * @arg SDIO_FLAG_TXDAVL: Data available in transmit FIFO * @arg SDIO_FLAG_RXDAVL: Data available in receive FIFO * @arg SDIO_FLAG_SDIOIT: SD I/O interrupt received + * @arg SDIO_FLAG_CEATAEND: CE-ATA command completion signal received for CMD61 * @retval The new state of SDIO_FLAG (SET or RESET). */ -#define __SDIO_GET_FLAG(__INSTANCE__, __FLAG__) (((__INSTANCE__)->STA &(__FLAG__)) != RESET) +#define __SDIO_GET_FLAG(__INSTANCE__, __FLAG__) (((__INSTANCE__)->STA &(__FLAG__)) != RESET) /** @@ -871,11 +633,13 @@ typedef struct * @arg SDIO_FLAG_CMDREND: Command response received (CRC check passed) * @arg SDIO_FLAG_CMDSENT: Command sent (no response required) * @arg SDIO_FLAG_DATAEND: Data end (data counter, SDIDCOUNT, is zero) + * @arg SDIO_FLAG_STBITERR: Start bit not detected on all data signals in wide bus mode * @arg SDIO_FLAG_DBCKEND: Data block sent/received (CRC check passed) * @arg SDIO_FLAG_SDIOIT: SD I/O interrupt received + * @arg SDIO_FLAG_CEATAEND: CE-ATA command completion signal received for CMD61 * @retval None */ -#define __SDIO_CLEAR_FLAG(__INSTANCE__, __FLAG__) ((__INSTANCE__)->ICR = (__FLAG__)) +#define __SDIO_CLEAR_FLAG(__INSTANCE__, __FLAG__) ((__INSTANCE__)->ICR = (__FLAG__)) /** * @brief Checks whether the specified SDIO interrupt has occurred or not. @@ -891,6 +655,8 @@ typedef struct * @arg SDIO_IT_CMDREND: Command response received (CRC check passed) interrupt * @arg SDIO_IT_CMDSENT: Command sent (no response required) interrupt * @arg SDIO_IT_DATAEND: Data end (data counter, SDIDCOUNT, is zero) interrupt + * @arg SDIO_IT_STBITERR: Start bit not detected on all data signals in wide + * bus mode interrupt * @arg SDIO_IT_DBCKEND: Data block sent/received (CRC check passed) interrupt * @arg SDIO_IT_CMDACT: Command transfer in progress interrupt * @arg SDIO_IT_TXACT: Data transmit in progress interrupt @@ -904,9 +670,10 @@ typedef struct * @arg SDIO_IT_TXDAVL: Data available in transmit FIFO interrupt * @arg SDIO_IT_RXDAVL: Data available in receive FIFO interrupt * @arg SDIO_IT_SDIOIT: SD I/O interrupt received interrupt + * @arg SDIO_IT_CEATAEND: CE-ATA command completion signal received for CMD61 interrupt * @retval The new state of SDIO_IT (SET or RESET). */ -#define __SDIO_GET_IT (__INSTANCE__, __INTERRUPT__) (((__INSTANCE__)->STA &(__INTERRUPT__)) == (__INTERRUPT__)) +#define __SDIO_GET_IT (__INSTANCE__, __INTERRUPT__) (((__INSTANCE__)->STA &(__INTERRUPT__)) == (__INTERRUPT__)) /** * @brief Clears the SDIO's interrupt pending bits. @@ -922,110 +689,120 @@ typedef struct * @arg SDIO_IT_CMDREND: Command response received (CRC check passed) interrupt * @arg SDIO_IT_CMDSENT: Command sent (no response required) interrupt * @arg SDIO_IT_DATAEND: Data end (data counter, SDIO_DCOUNT, is zero) interrupt + * @arg SDIO_IT_STBITERR: Start bit not detected on all data signals in wide + * bus mode interrupt * @arg SDIO_IT_SDIOIT: SD I/O interrupt received interrupt + * @arg SDIO_IT_CEATAEND: CE-ATA command completion signal received for CMD61 * @retval None */ -#define __SDIO_CLEAR_IT(__INSTANCE__, __INTERRUPT__) ((__INSTANCE__)->ICR = (__INTERRUPT__)) +#define __SDIO_CLEAR_IT(__INSTANCE__, __INTERRUPT__) ((__INSTANCE__)->ICR = (__INTERRUPT__)) /** * @brief Enable Start the SD I/O Read Wait operation. * @param __INSTANCE__ : Pointer to SDIO register base * @retval None */ -#define __SDIO_START_READWAIT_ENABLE(__INSTANCE__) (*(__IO uint32_t *) DCTRL_RWSTART_BB = ENABLE) +#define __SDIO_START_READWAIT_ENABLE(__INSTANCE__) ((__INSTANCE__)->DCTRL |= SDIO_DCTRL_RWSTART) /** * @brief Disable Start the SD I/O Read Wait operations. * @param __INSTANCE__ : Pointer to SDIO register base * @retval None */ -#define __SDIO_START_READWAIT_DISABLE(__INSTANCE__) (*(__IO uint32_t *) DCTRL_RWSTART_BB = DISABLE) +#define __SDIO_START_READWAIT_DISABLE(__INSTANCE__) ((__INSTANCE__)->DCTRL &= ~SDIO_DCTRL_RWSTART) /** * @brief Enable Start the SD I/O Read Wait operation. * @param __INSTANCE__ : Pointer to SDIO register base * @retval None */ -#define __SDIO_STOP_READWAIT_ENABLE(__INSTANCE__) (*(__IO uint32_t *) DCTRL_RWSTOP_BB = ENABLE) +#define __SDIO_STOP_READWAIT_ENABLE(__INSTANCE__) ((__INSTANCE__)->DCTRL |= SDIO_DCTRL_RWSTOP) /** * @brief Disable Stop the SD I/O Read Wait operations. * @param __INSTANCE__ : Pointer to SDIO register base * @retval None */ -#define __SDIO_STOP_READWAIT_DISABLE(__INSTANCE__) (*(__IO uint32_t *) DCTRL_RWSTOP_BB = DISABLE) +#define __SDIO_STOP_READWAIT_DISABLE(__INSTANCE__) ((__INSTANCE__)->DCTRL &= ~SDIO_DCTRL_RWSTOP) /** * @brief Enable the SD I/O Mode Operation. * @param __INSTANCE__ : Pointer to SDIO register base * @retval None */ -#define __SDIO_OPERATION_ENABLE(__INSTANCE__) (*(__IO uint32_t *) DCTRL_SDIOEN_BB = ENABLE) +#define __SDIO_OPERATION_ENABLE(__INSTANCE__) ((__INSTANCE__)->DCTRL |= SDIO_DCTRL_SDIOEN) /** * @brief Disable the SD I/O Mode Operation. * @param __INSTANCE__ : Pointer to SDIO register base * @retval None */ -#define __SDIO_OPERATION_DISABLE(__INSTANCE__) (*(__IO uint32_t *) DCTRL_SDIOEN_BB = DISABLE) +#define __SDIO_OPERATION_DISABLE(__INSTANCE__) ((__INSTANCE__)->DCTRL &= ~SDIO_DCTRL_SDIOEN) /** * @brief Enable the SD I/O Suspend command sending. * @param __INSTANCE__ : Pointer to SDIO register base * @retval None */ -#define __SDIO_SUSPEND_CMD_ENABLE(__INSTANCE__) (*(__IO uint32_t *) CMD_SDIOSUSPEND_BB = ENABLE) +#define __SDIO_SUSPEND_CMD_ENABLE(__INSTANCE__) ((__INSTANCE__)->CMD |= SDIO_CMD_SDIOSUSPEND) /** * @brief Disable the SD I/O Suspend command sending. * @param __INSTANCE__ : Pointer to SDIO register base * @retval None */ -#define __SDIO_SUSPEND_CMD_DISABLE(__INSTANCE__) (*(__IO uint32_t *) CMD_SDIOSUSPEND_BB = DISABLE) +#define __SDIO_SUSPEND_CMD_DISABLE(__INSTANCE__) ((__INSTANCE__)->CMD &= ~SDIO_CMD_SDIOSUSPEND) + /** * @brief Enable the command completion signal. + * @param __INSTANCE__ : Pointer to SDIO register base * @retval None */ -#define __SDIO_CEATA_CMD_COMPLETION_ENABLE() (*(__IO uint32_t *) CMD_ENCMDCOMPL_BB = ENABLE) +#define __SDIO_CEATA_CMD_COMPLETION_ENABLE(__INSTANCE__) ((__INSTANCE__)->CMD |= SDIO_CMD_ENCMDCOMPL) /** * @brief Disable the command completion signal. + * @param __INSTANCE__ : Pointer to SDIO register base * @retval None */ -#define __SDIO_CEATA_CMD_COMPLETION_DISABLE() (*(__IO uint32_t *) CMD_ENCMDCOMPL_BB = DISABLE) +#define __SDIO_CEATA_CMD_COMPLETION_DISABLE(__INSTANCE__) ((__INSTANCE__)->CMD &= ~SDIO_CMD_ENCMDCOMPL) /** * @brief Enable the CE-ATA interrupt. + * @param __INSTANCE__ : Pointer to SDIO register base * @retval None */ -#define __SDIO_CEATA_ENABLE_IT() (*(__IO uint32_t *) CMD_NIEN_BB = (uint32_t)0U) +#define __SDIO_CEATA_ENABLE_IT(__INSTANCE__) ((__INSTANCE__)->CMD &= ~SDIO_CMD_NIEN) /** * @brief Disable the CE-ATA interrupt. + * @param __INSTANCE__ : Pointer to SDIO register base * @retval None */ -#define __SDIO_CEATA_DISABLE_IT() (*(__IO uint32_t *) CMD_NIEN_BB = (uint32_t)1U) +#define __SDIO_CEATA_DISABLE_IT(__INSTANCE__) ((__INSTANCE__)->CMD |= SDIO_CMD_NIEN) /** * @brief Enable send CE-ATA command (CMD61). + * @param __INSTANCE__ : Pointer to SDIO register base * @retval None */ -#define __SDIO_CEATA_SENDCMD_ENABLE() (*(__IO uint32_t *) CMD_ATACMD_BB = ENABLE) +#define __SDIO_CEATA_SENDCMD_ENABLE(__INSTANCE__) ((__INSTANCE__)->CMD |= SDIO_CMD_CEATACMD) /** * @brief Disable send CE-ATA command (CMD61). + * @param __INSTANCE__ : Pointer to SDIO register base * @retval None */ -#define __SDIO_CEATA_SENDCMD_DISABLE() (*(__IO uint32_t *) CMD_ATACMD_BB = DISABLE) +#define __SDIO_CEATA_SENDCMD_DISABLE(__INSTANCE__) ((__INSTANCE__)->CMD &= ~SDIO_CMD_CEATACMD) /** * @} */ - + /** * @} */ - + /* Exported functions --------------------------------------------------------*/ /** @addtogroup SDMMC_LL_Exported_Functions * @{ @@ -1065,40 +842,12 @@ uint8_t SDIO_GetCommandResponse(SDIO_TypeDef *SDIOx); uint32_t SDIO_GetResponse(SDIO_TypeDef *SDIOx, uint32_t Response); /* Data path state machine (DPSM) management functions */ -HAL_StatusTypeDef SDIO_ConfigData(SDIO_TypeDef *SDIOx, SDIO_DataInitTypeDef* Data); +HAL_StatusTypeDef SDIO_DataConfig(SDIO_TypeDef *SDIOx, SDIO_DataInitTypeDef* Data); uint32_t SDIO_GetDataCounter(SDIO_TypeDef *SDIOx); uint32_t SDIO_GetFIFOCount(SDIO_TypeDef *SDIOx); -/* SDMMC Cards mode management functions */ -HAL_StatusTypeDef SDIO_SetSDMMCReadWaitMode(SDIO_TypeDef *SDIOx, uint32_t SDIO_ReadWaitMode); - -/* SDMMC Commands management functions */ -uint32_t SDMMC_CmdBlockLength(SDIO_TypeDef *SDIOx, uint32_t BlockSize); -uint32_t SDMMC_CmdReadSingleBlock(SDIO_TypeDef *SDIOx, uint32_t ReadAdd); -uint32_t SDMMC_CmdReadMultiBlock(SDIO_TypeDef *SDIOx, uint32_t ReadAdd); -uint32_t SDMMC_CmdWriteSingleBlock(SDIO_TypeDef *SDIOx, uint32_t WriteAdd); -uint32_t SDMMC_CmdWriteMultiBlock(SDIO_TypeDef *SDIOx, uint32_t WriteAdd); -uint32_t SDMMC_CmdSDEraseStartAdd(SDIO_TypeDef *SDIOx, uint32_t StartAdd); -uint32_t SDMMC_CmdSDEraseEndAdd(SDIO_TypeDef *SDIOx, uint32_t EndAdd); -uint32_t SDMMC_CmdErase(SDIO_TypeDef *SDIOx); -uint32_t SDMMC_CmdStopTransfer(SDIO_TypeDef *SDIOx); -uint32_t SDMMC_CmdSelDesel(SDIO_TypeDef *SDIOx, uint64_t Addr); -uint32_t SDMMC_CmdGoIdleState(SDIO_TypeDef *SDIOx); -uint32_t SDMMC_CmdOperCond(SDIO_TypeDef *SDIOx); -uint32_t SDMMC_CmdAppCommand(SDIO_TypeDef *SDIOx, uint32_t Argument); -uint32_t SDMMC_CmdAppOperCommand(SDIO_TypeDef *SDIOx, uint32_t SdType); -uint32_t SDMMC_CmdBusWidth(SDIO_TypeDef *SDIOx, uint32_t BusWidth); -uint32_t SDMMC_CmdSendSCR(SDIO_TypeDef *SDIOx); -uint32_t SDMMC_CmdSendCID(SDIO_TypeDef *SDIOx); -uint32_t SDMMC_CmdSendCSD(SDIO_TypeDef *SDIOx, uint32_t Argument); -uint32_t SDMMC_CmdSetRelAdd(SDIO_TypeDef *SDIOx, uint16_t *pRCA); -uint32_t SDMMC_CmdSendStatus(SDIO_TypeDef *SDIOx, uint32_t Argument); -uint32_t SDMMC_CmdStatusRegister(SDIO_TypeDef *SDIOx); - -uint32_t SDMMC_CmdOpCondition(SDIO_TypeDef *SDIOx, uint32_t Argument); -uint32_t SDMMC_CmdSwitch(SDIO_TypeDef *SDIOx, uint32_t Argument); -uint32_t SDMMC_CmdEraseStartAdd(SDIO_TypeDef *SDIOx, uint32_t StartAdd); -uint32_t SDMMC_CmdEraseEndAdd(SDIO_TypeDef *SDIOx, uint32_t EndAdd); +/* SDIO Cards mode management functions */ +HAL_StatusTypeDef SDIO_SetSDIOReadWaitMode(SDIO_TypeDef *SDIOx, uint32_t SDIO_ReadWaitMode); /** * @} diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_spi.c b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_spi.c deleted file mode 100644 index 67262c96e92..00000000000 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_spi.c +++ /dev/null @@ -1,562 +0,0 @@ -/** - ****************************************************************************** - * @file stm32f1xx_ll_spi.c - * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 - * @brief SPI LL module driver. - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2016 STMicroelectronics

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ -#if defined(USE_FULL_LL_DRIVER) - -/* Includes ------------------------------------------------------------------*/ -#include "stm32f1xx_ll_spi.h" -#include "stm32f1xx_ll_bus.h" -#include "stm32f1xx_ll_rcc.h" - -#ifdef USE_FULL_ASSERT -#include "stm32_assert.h" -#else -#define assert_param(expr) ((void)0U) -#endif - -/** @addtogroup STM32F1xx_LL_Driver - * @{ - */ - -#if defined (SPI1) || defined (SPI2) || defined (SPI3) - -/** @addtogroup SPI_LL - * @{ - */ - -/* Private types -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ - -/* Private constants ---------------------------------------------------------*/ -/** @defgroup SPI_LL_Private_Constants SPI Private Constants - * @{ - */ -/* SPI registers Masks */ -#define SPI_CR1_CLEAR_MASK (SPI_CR1_CPHA | SPI_CR1_CPOL | SPI_CR1_MSTR | \ - SPI_CR1_BR | SPI_CR1_LSBFIRST | SPI_CR1_SSI | \ - SPI_CR1_SSM | SPI_CR1_RXONLY | SPI_CR1_DFF | \ - SPI_CR1_CRCNEXT | SPI_CR1_CRCEN | SPI_CR1_BIDIOE | \ - SPI_CR1_BIDIMODE) -/** - * @} - */ - -/* Private macros ------------------------------------------------------------*/ -/** @defgroup SPI_LL_Private_Macros SPI Private Macros - * @{ - */ -#define IS_LL_SPI_TRANSFER_DIRECTION(__VALUE__) (((__VALUE__) == LL_SPI_FULL_DUPLEX) \ - || ((__VALUE__) == LL_SPI_SIMPLEX_RX) \ - || ((__VALUE__) == LL_SPI_HALF_DUPLEX_RX) \ - || ((__VALUE__) == LL_SPI_HALF_DUPLEX_TX)) - -#define IS_LL_SPI_MODE(__VALUE__) (((__VALUE__) == LL_SPI_MODE_MASTER) \ - || ((__VALUE__) == LL_SPI_MODE_SLAVE)) - -#define IS_LL_SPI_DATAWIDTH(__VALUE__) (((__VALUE__) == LL_SPI_DATAWIDTH_8BIT) \ - || ((__VALUE__) == LL_SPI_DATAWIDTH_16BIT)) - -#define IS_LL_SPI_POLARITY(__VALUE__) (((__VALUE__) == LL_SPI_POLARITY_LOW) \ - || ((__VALUE__) == LL_SPI_POLARITY_HIGH)) - -#define IS_LL_SPI_PHASE(__VALUE__) (((__VALUE__) == LL_SPI_PHASE_1EDGE) \ - || ((__VALUE__) == LL_SPI_PHASE_2EDGE)) - -#define IS_LL_SPI_NSS(__VALUE__) (((__VALUE__) == LL_SPI_NSS_SOFT) \ - || ((__VALUE__) == LL_SPI_NSS_HARD_INPUT) \ - || ((__VALUE__) == LL_SPI_NSS_HARD_OUTPUT)) - -#define IS_LL_SPI_BAUDRATE(__VALUE__) (((__VALUE__) == LL_SPI_BAUDRATEPRESCALER_DIV2) \ - || ((__VALUE__) == LL_SPI_BAUDRATEPRESCALER_DIV4) \ - || ((__VALUE__) == LL_SPI_BAUDRATEPRESCALER_DIV8) \ - || ((__VALUE__) == LL_SPI_BAUDRATEPRESCALER_DIV16) \ - || ((__VALUE__) == LL_SPI_BAUDRATEPRESCALER_DIV32) \ - || ((__VALUE__) == LL_SPI_BAUDRATEPRESCALER_DIV64) \ - || ((__VALUE__) == LL_SPI_BAUDRATEPRESCALER_DIV128) \ - || ((__VALUE__) == LL_SPI_BAUDRATEPRESCALER_DIV256)) - -#define IS_LL_SPI_BITORDER(__VALUE__) (((__VALUE__) == LL_SPI_LSB_FIRST) \ - || ((__VALUE__) == LL_SPI_MSB_FIRST)) - -#define IS_LL_SPI_CRCCALCULATION(__VALUE__) (((__VALUE__) == LL_SPI_CRCCALCULATION_ENABLE) \ - || ((__VALUE__) == LL_SPI_CRCCALCULATION_DISABLE)) - -#define IS_LL_SPI_CRC_POLYNOMIAL(__VALUE__) ((__VALUE__) >= 0x1U) - -/** - * @} - */ - -/* Private function prototypes -----------------------------------------------*/ - -/* Exported functions --------------------------------------------------------*/ -/** @addtogroup SPI_LL_Exported_Functions - * @{ - */ - -/** @addtogroup SPI_LL_EF_Init - * @{ - */ - -/** - * @brief De-initialize the SPI registers to their default reset values. - * @param SPIx SPI Instance - * @retval An ErrorStatus enumeration value: - * - SUCCESS: SPI registers are de-initialized - * - ERROR: SPI registers are not de-initialized - */ -ErrorStatus LL_SPI_DeInit(SPI_TypeDef *SPIx) -{ - ErrorStatus status = ERROR; - - /* Check the parameters */ - assert_param(IS_SPI_ALL_INSTANCE(SPIx)); - -#if defined(SPI1) - if (SPIx == SPI1) - { - /* Force reset of SPI clock */ - LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_SPI1); - - /* Release reset of SPI clock */ - LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_SPI1); - - status = SUCCESS; - } -#endif /* SPI1 */ -#if defined(SPI2) - if (SPIx == SPI2) - { - /* Force reset of SPI clock */ - LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_SPI2); - - /* Release reset of SPI clock */ - LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_SPI2); - - status = SUCCESS; - } -#endif /* SPI2 */ -#if defined(SPI3) - if (SPIx == SPI3) - { - /* Force reset of SPI clock */ - LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_SPI3); - - /* Release reset of SPI clock */ - LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_SPI3); - - status = SUCCESS; - } -#endif /* SPI3 */ - - return status; -} - -/** - * @brief Initialize the SPI registers according to the specified parameters in SPI_InitStruct. - * @note As some bits in SPI configuration registers can only be written when the SPI is disabled (SPI_CR1_SPE bit =0), - * SPI IP should be in disabled state prior calling this function. Otherwise, ERROR result will be returned. - * @param SPIx SPI Instance - * @param SPI_InitStruct pointer to a @ref LL_SPI_InitTypeDef structure - * @retval An ErrorStatus enumeration value. (Return always SUCCESS) - */ -ErrorStatus LL_SPI_Init(SPI_TypeDef *SPIx, LL_SPI_InitTypeDef *SPI_InitStruct) -{ - ErrorStatus status = ERROR; - - /* Check the SPI Instance SPIx*/ - assert_param(IS_SPI_ALL_INSTANCE(SPIx)); - - /* Check the SPI parameters from SPI_InitStruct*/ - assert_param(IS_LL_SPI_TRANSFER_DIRECTION(SPI_InitStruct->TransferDirection)); - assert_param(IS_LL_SPI_MODE(SPI_InitStruct->Mode)); - assert_param(IS_LL_SPI_DATAWIDTH(SPI_InitStruct->DataWidth)); - assert_param(IS_LL_SPI_POLARITY(SPI_InitStruct->ClockPolarity)); - assert_param(IS_LL_SPI_PHASE(SPI_InitStruct->ClockPhase)); - assert_param(IS_LL_SPI_NSS(SPI_InitStruct->NSS)); - assert_param(IS_LL_SPI_BAUDRATE(SPI_InitStruct->BaudRate)); - assert_param(IS_LL_SPI_BITORDER(SPI_InitStruct->BitOrder)); - assert_param(IS_LL_SPI_CRCCALCULATION(SPI_InitStruct->CRCCalculation)); - - if (LL_SPI_IsEnabled(SPIx) == 0x00000000U) - { - /*---------------------------- SPIx CR1 Configuration ------------------------ - * Configure SPIx CR1 with parameters: - * - TransferDirection: SPI_CR1_BIDIMODE, SPI_CR1_BIDIOE and SPI_CR1_RXONLY bits - * - Master/Slave Mode: SPI_CR1_MSTR bit - * - DataWidth: SPI_CR1_DFF bit - * - ClockPolarity: SPI_CR1_CPOL bit - * - ClockPhase: SPI_CR1_CPHA bit - * - NSS management: SPI_CR1_SSM bit - * - BaudRate prescaler: SPI_CR1_BR[2:0] bits - * - BitOrder: SPI_CR1_LSBFIRST bit - * - CRCCalculation: SPI_CR1_CRCEN bit - */ - MODIFY_REG(SPIx->CR1, - SPI_CR1_CLEAR_MASK, - SPI_InitStruct->TransferDirection | SPI_InitStruct->Mode | SPI_InitStruct->DataWidth | - SPI_InitStruct->ClockPolarity | SPI_InitStruct->ClockPhase | - SPI_InitStruct->NSS | SPI_InitStruct->BaudRate | - SPI_InitStruct->BitOrder | SPI_InitStruct->CRCCalculation); - - /*---------------------------- SPIx CR2 Configuration ------------------------ - * Configure SPIx CR2 with parameters: - * - NSS management: SSOE bit - */ - MODIFY_REG(SPIx->CR2, SPI_CR2_SSOE, (SPI_InitStruct->NSS >> 16U)); - - /*---------------------------- SPIx CRCPR Configuration ---------------------- - * Configure SPIx CRCPR with parameters: - * - CRCPoly: CRCPOLY[15:0] bits - */ - if (SPI_InitStruct->CRCCalculation == LL_SPI_CRCCALCULATION_ENABLE) - { - assert_param(IS_LL_SPI_CRC_POLYNOMIAL(SPI_InitStruct->CRCPoly)); - LL_SPI_SetCRCPolynomial(SPIx, SPI_InitStruct->CRCPoly); - } - status = SUCCESS; - } - -#if defined (SPI_I2S_SUPPORT) - /* Activate the SPI mode (Reset I2SMOD bit in I2SCFGR register) */ - CLEAR_BIT(SPIx->I2SCFGR, SPI_I2SCFGR_I2SMOD); -#endif /* SPI_I2S_SUPPORT */ - return status; -} - -/** - * @brief Set each @ref LL_SPI_InitTypeDef field to default value. - * @param SPI_InitStruct pointer to a @ref LL_SPI_InitTypeDef structure - * whose fields will be set to default values. - * @retval None - */ -void LL_SPI_StructInit(LL_SPI_InitTypeDef *SPI_InitStruct) -{ - /* Set SPI_InitStruct fields to default values */ - SPI_InitStruct->TransferDirection = LL_SPI_FULL_DUPLEX; - SPI_InitStruct->Mode = LL_SPI_MODE_SLAVE; - SPI_InitStruct->DataWidth = LL_SPI_DATAWIDTH_8BIT; - SPI_InitStruct->ClockPolarity = LL_SPI_POLARITY_LOW; - SPI_InitStruct->ClockPhase = LL_SPI_PHASE_1EDGE; - SPI_InitStruct->NSS = LL_SPI_NSS_HARD_INPUT; - SPI_InitStruct->BaudRate = LL_SPI_BAUDRATEPRESCALER_DIV2; - SPI_InitStruct->BitOrder = LL_SPI_MSB_FIRST; - SPI_InitStruct->CRCCalculation = LL_SPI_CRCCALCULATION_DISABLE; - SPI_InitStruct->CRCPoly = 7U; -} - -/** - * @} - */ - -/** - * @} - */ - -/** - * @} - */ - -#if defined(SPI_I2S_SUPPORT) -/** @addtogroup I2S_LL - * @{ - */ - -/* Private types -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private constants ---------------------------------------------------------*/ -/** @defgroup I2S_LL_Private_Constants I2S Private Constants - * @{ - */ -/* I2S registers Masks */ -#define I2S_I2SCFGR_CLEAR_MASK (SPI_I2SCFGR_CHLEN | SPI_I2SCFGR_DATLEN | \ - SPI_I2SCFGR_CKPOL | SPI_I2SCFGR_I2SSTD | \ - SPI_I2SCFGR_I2SCFG | SPI_I2SCFGR_I2SMOD ) - -#define I2S_I2SPR_CLEAR_MASK 0x0002U -/** - * @} - */ -/* Private macros ------------------------------------------------------------*/ -/** @defgroup I2S_LL_Private_Macros I2S Private Macros - * @{ - */ - -#define IS_LL_I2S_DATAFORMAT(__VALUE__) (((__VALUE__) == LL_I2S_DATAFORMAT_16B) \ - || ((__VALUE__) == LL_I2S_DATAFORMAT_16B_EXTENDED) \ - || ((__VALUE__) == LL_I2S_DATAFORMAT_24B) \ - || ((__VALUE__) == LL_I2S_DATAFORMAT_32B)) - -#define IS_LL_I2S_CPOL(__VALUE__) (((__VALUE__) == LL_I2S_POLARITY_LOW) \ - || ((__VALUE__) == LL_I2S_POLARITY_HIGH)) - -#define IS_LL_I2S_STANDARD(__VALUE__) (((__VALUE__) == LL_I2S_STANDARD_PHILIPS) \ - || ((__VALUE__) == LL_I2S_STANDARD_MSB) \ - || ((__VALUE__) == LL_I2S_STANDARD_LSB) \ - || ((__VALUE__) == LL_I2S_STANDARD_PCM_SHORT) \ - || ((__VALUE__) == LL_I2S_STANDARD_PCM_LONG)) - -#define IS_LL_I2S_MODE(__VALUE__) (((__VALUE__) == LL_I2S_MODE_SLAVE_TX) \ - || ((__VALUE__) == LL_I2S_MODE_SLAVE_RX) \ - || ((__VALUE__) == LL_I2S_MODE_MASTER_TX) \ - || ((__VALUE__) == LL_I2S_MODE_MASTER_RX)) - -#define IS_LL_I2S_MCLK_OUTPUT(__VALUE__) (((__VALUE__) == LL_I2S_MCLK_OUTPUT_ENABLE) \ - || ((__VALUE__) == LL_I2S_MCLK_OUTPUT_DISABLE)) - -#define IS_LL_I2S_AUDIO_FREQ(__VALUE__) ((((__VALUE__) >= LL_I2S_AUDIOFREQ_8K) \ - && ((__VALUE__) <= LL_I2S_AUDIOFREQ_192K)) \ - || ((__VALUE__) == LL_I2S_AUDIOFREQ_DEFAULT)) - -#define IS_LL_I2S_PRESCALER_LINEAR(__VALUE__) ((__VALUE__) >= 0x2U) - -#define IS_LL_I2S_PRESCALER_PARITY(__VALUE__) (((__VALUE__) == LL_I2S_PRESCALER_PARITY_EVEN) \ - || ((__VALUE__) == LL_I2S_PRESCALER_PARITY_ODD)) -/** - * @} - */ - -/* Private function prototypes -----------------------------------------------*/ - -/* Exported functions --------------------------------------------------------*/ -/** @addtogroup I2S_LL_Exported_Functions - * @{ - */ - -/** @addtogroup I2S_LL_EF_Init - * @{ - */ - -/** - * @brief De-initialize the SPI/I2S registers to their default reset values. - * @param SPIx SPI Instance - * @retval An ErrorStatus enumeration value: - * - SUCCESS: SPI registers are de-initialized - * - ERROR: SPI registers are not de-initialized - */ -ErrorStatus LL_I2S_DeInit(SPI_TypeDef *SPIx) -{ - return LL_SPI_DeInit(SPIx); -} - -/** - * @brief Initializes the SPI/I2S registers according to the specified parameters in I2S_InitStruct. - * @note As some bits in SPI configuration registers can only be written when the SPI is disabled (SPI_CR1_SPE bit =0), - * SPI IP should be in disabled state prior calling this function. Otherwise, ERROR result will be returned. - * @param SPIx SPI Instance - * @param I2S_InitStruct pointer to a @ref LL_I2S_InitTypeDef structure - * @retval An ErrorStatus enumeration value: - * - SUCCESS: SPI registers are Initialized - * - ERROR: SPI registers are not Initialized - */ -ErrorStatus LL_I2S_Init(SPI_TypeDef *SPIx, LL_I2S_InitTypeDef *I2S_InitStruct) -{ - uint16_t i2sdiv = 2U, i2sodd = 0U, packetlength = 1U; - uint32_t tmp = 0U; - uint32_t sourceclock = 0U; -#if defined(I2S2_I2S3_CLOCK_FEATURE) -#else - LL_RCC_ClocksTypeDef rcc_clocks; -#endif /* I2S2_I2S3_CLOCK_FEATURE */ - ErrorStatus status = ERROR; - - /* Check the I2S parameters */ - assert_param(IS_I2S_ALL_INSTANCE(SPIx)); - assert_param(IS_LL_I2S_MODE(I2S_InitStruct->Mode)); - assert_param(IS_LL_I2S_STANDARD(I2S_InitStruct->Standard)); - assert_param(IS_LL_I2S_DATAFORMAT(I2S_InitStruct->DataFormat)); - assert_param(IS_LL_I2S_MCLK_OUTPUT(I2S_InitStruct->MCLKOutput)); - assert_param(IS_LL_I2S_AUDIO_FREQ(I2S_InitStruct->AudioFreq)); - assert_param(IS_LL_I2S_CPOL(I2S_InitStruct->ClockPolarity)); - - if (LL_I2S_IsEnabled(SPIx) == 0x00000000U) - { - /*---------------------------- SPIx I2SCFGR Configuration -------------------- - * Configure SPIx I2SCFGR with parameters: - * - Mode: SPI_I2SCFGR_I2SCFG[1:0] bit - * - Standard: SPI_I2SCFGR_I2SSTD[1:0] and SPI_I2SCFGR_PCMSYNC bits - * - DataFormat: SPI_I2SCFGR_CHLEN and SPI_I2SCFGR_DATLEN bits - * - ClockPolarity: SPI_I2SCFGR_CKPOL bit - */ - - /* Write to SPIx I2SCFGR */ - MODIFY_REG(SPIx->I2SCFGR, - I2S_I2SCFGR_CLEAR_MASK, - I2S_InitStruct->Mode | I2S_InitStruct->Standard | - I2S_InitStruct->DataFormat | I2S_InitStruct->ClockPolarity | - SPI_I2SCFGR_I2SMOD); - - /*---------------------------- SPIx I2SPR Configuration ---------------------- - * Configure SPIx I2SPR with parameters: - * - MCLKOutput: SPI_I2SPR_MCKOE bit - * - AudioFreq: SPI_I2SPR_I2SDIV[7:0] and SPI_I2SPR_ODD bits - */ - - /* If the requested audio frequency is not the default, compute the prescaler (i2sodd, i2sdiv) - * else, default values are used: i2sodd = 0U, i2sdiv = 2U. - */ - if (I2S_InitStruct->AudioFreq != LL_I2S_AUDIOFREQ_DEFAULT) - { - /* Check the frame length (For the Prescaler computing) - * Default value: LL_I2S_DATAFORMAT_16B (packetlength = 1U). - */ - if (I2S_InitStruct->DataFormat != LL_I2S_DATAFORMAT_16B) - { - /* Packet length is 32 bits */ - packetlength = 2U; - } -#if defined(I2S2_I2S3_CLOCK_FEATURE) - /* If an external I2S clock has to be used, the specific define should be set - in the project configuration or in the stm32f1xx_ll_rcc.h file */ - if(SPIx == SPI2) - { - /* Get the I2S source clock value */ - sourceclock = LL_RCC_GetI2SClockFreq(LL_RCC_I2S2_CLKSOURCE); - } - else /* SPI3 */ - { - /* Get the I2S source clock value */ - sourceclock = LL_RCC_GetI2SClockFreq(LL_RCC_I2S3_CLKSOURCE); - } -#else - /* I2S Clock source is System clock: Get System Clock frequency */ - LL_RCC_GetSystemClocksFreq(&rcc_clocks); - - /* Get the source clock value: based on System Clock value */ - sourceclock = rcc_clocks.SYSCLK_Frequency; -#endif /* I2S2_I2S3_CLOCK_FEATURE */ - /* Compute the Real divider depending on the MCLK output state with a floating point */ - if (I2S_InitStruct->MCLKOutput == LL_I2S_MCLK_OUTPUT_ENABLE) - { - /* MCLK output is enabled */ - tmp = (uint16_t)(((((sourceclock / 256U) * 10U) / I2S_InitStruct->AudioFreq)) + 5U); - } - else - { - /* MCLK output is disabled */ - tmp = (uint16_t)(((((sourceclock / (32U * packetlength)) * 10U) / I2S_InitStruct->AudioFreq)) + 5U); - } - - /* Remove the floating point */ - tmp = tmp / 10U; - - /* Check the parity of the divider */ - i2sodd = (uint16_t)(tmp & (uint16_t)0x0001U); - - /* Compute the i2sdiv prescaler */ - i2sdiv = (uint16_t)((tmp - i2sodd) / 2U); - - /* Get the Mask for the Odd bit (SPI_I2SPR[8]) register */ - i2sodd = (uint16_t)(i2sodd << 8U); - } - - /* Test if the divider is 1 or 0 or greater than 0xFF */ - if ((i2sdiv < 2U) || (i2sdiv > 0xFFU)) - { - /* Set the default values */ - i2sdiv = 2U; - i2sodd = 0U; - } - - /* Write to SPIx I2SPR register the computed value */ - WRITE_REG(SPIx->I2SPR, i2sdiv | i2sodd | I2S_InitStruct->MCLKOutput); - - status = SUCCESS; - } - return status; -} - -/** - * @brief Set each @ref LL_I2S_InitTypeDef field to default value. - * @param I2S_InitStruct pointer to a @ref LL_I2S_InitTypeDef structure - * whose fields will be set to default values. - * @retval None - */ -void LL_I2S_StructInit(LL_I2S_InitTypeDef *I2S_InitStruct) -{ - /*--------------- Reset I2S init structure parameters values -----------------*/ - I2S_InitStruct->Mode = LL_I2S_MODE_SLAVE_TX; - I2S_InitStruct->Standard = LL_I2S_STANDARD_PHILIPS; - I2S_InitStruct->DataFormat = LL_I2S_DATAFORMAT_16B; - I2S_InitStruct->MCLKOutput = LL_I2S_MCLK_OUTPUT_DISABLE; - I2S_InitStruct->AudioFreq = LL_I2S_AUDIOFREQ_DEFAULT; - I2S_InitStruct->ClockPolarity = LL_I2S_POLARITY_LOW; -} - -/** - * @brief Set linear and parity prescaler. - * @note To calculate value of PrescalerLinear(I2SDIV[7:0] bits) and PrescalerParity(ODD bit)\n - * Check Audio frequency table and formulas inside Reference Manual (SPI/I2S). - * @param SPIx SPI Instance - * @param PrescalerLinear value: Min_Data=0x02 and Max_Data=0xFF. - * @param PrescalerParity This parameter can be one of the following values: - * @arg @ref LL_I2S_PRESCALER_PARITY_EVEN - * @arg @ref LL_I2S_PRESCALER_PARITY_ODD - * @retval None - */ -void LL_I2S_ConfigPrescaler(SPI_TypeDef *SPIx, uint32_t PrescalerLinear, uint32_t PrescalerParity) -{ - /* Check the I2S parameters */ - assert_param(IS_I2S_ALL_INSTANCE(SPIx)); - assert_param(IS_LL_I2S_PRESCALER_LINEAR(PrescalerLinear)); - assert_param(IS_LL_I2S_PRESCALER_PARITY(PrescalerParity)); - - /* Write to SPIx I2SPR */ - MODIFY_REG(SPIx->I2SPR, SPI_I2SPR_I2SDIV | SPI_I2SPR_ODD, PrescalerLinear | (PrescalerParity << 8U)); -} - -/** - * @} - */ - -/** - * @} - */ - -/** - * @} - */ -#endif /* SPI_I2S_SUPPORT */ - -#endif /* defined (SPI1) || defined (SPI2) || defined (SPI3) */ - -/** - * @} - */ - -#endif /* USE_FULL_LL_DRIVER */ - -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_spi.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_spi.h deleted file mode 100644 index c8c6061ee42..00000000000 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_spi.h +++ /dev/null @@ -1,1922 +0,0 @@ -/** - ****************************************************************************** - * @file stm32f1xx_ll_spi.h - * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 - * @brief Header file of SPI LL module. - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2016 STMicroelectronics

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ - -/* Define to prevent recursive inclusion -------------------------------------*/ -#ifndef __STM32F1xx_LL_SPI_H -#define __STM32F1xx_LL_SPI_H - -#ifdef __cplusplus -extern "C" { -#endif - -/* Includes ------------------------------------------------------------------*/ -#include "stm32f1xx.h" - -/** @addtogroup STM32F1xx_LL_Driver - * @{ - */ - -#if defined (SPI1) || defined (SPI2) || defined (SPI3) - -/** @defgroup SPI_LL SPI - * @{ - */ - -/* Private types -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private macros ------------------------------------------------------------*/ - -/* Exported types ------------------------------------------------------------*/ -#if defined(USE_FULL_LL_DRIVER) -/** @defgroup SPI_LL_ES_INIT SPI Exported Init structure - * @{ - */ - -/** - * @brief SPI Init structures definition - */ -typedef struct -{ - uint32_t TransferDirection; /*!< Specifies the SPI unidirectional or bidirectional data mode. - This parameter can be a value of @ref SPI_LL_EC_TRANSFER_MODE. - - This feature can be modified afterwards using unitary function @ref LL_SPI_SetTransferDirection().*/ - - uint32_t Mode; /*!< Specifies the SPI mode (Master/Slave). - This parameter can be a value of @ref SPI_LL_EC_MODE. - - This feature can be modified afterwards using unitary function @ref LL_SPI_SetMode().*/ - - uint32_t DataWidth; /*!< Specifies the SPI data width. - This parameter can be a value of @ref SPI_LL_EC_DATAWIDTH. - - This feature can be modified afterwards using unitary function @ref LL_SPI_SetDataWidth().*/ - - uint32_t ClockPolarity; /*!< Specifies the serial clock steady state. - This parameter can be a value of @ref SPI_LL_EC_POLARITY. - - This feature can be modified afterwards using unitary function @ref LL_SPI_SetClockPolarity().*/ - - uint32_t ClockPhase; /*!< Specifies the clock active edge for the bit capture. - This parameter can be a value of @ref SPI_LL_EC_PHASE. - - This feature can be modified afterwards using unitary function @ref LL_SPI_SetClockPhase().*/ - - uint32_t NSS; /*!< Specifies whether the NSS signal is managed by hardware (NSS pin) or by software using the SSI bit. - This parameter can be a value of @ref SPI_LL_EC_NSS_MODE. - - This feature can be modified afterwards using unitary function @ref LL_SPI_SetNSSMode().*/ - - uint32_t BaudRate; /*!< Specifies the BaudRate prescaler value which will be used to configure the transmit and receive SCK clock. - This parameter can be a value of @ref SPI_LL_EC_BAUDRATEPRESCALER. - @note The communication clock is derived from the master clock. The slave clock does not need to be set. - - This feature can be modified afterwards using unitary function @ref LL_SPI_SetBaudRatePrescaler().*/ - - uint32_t BitOrder; /*!< Specifies whether data transfers start from MSB or LSB bit. - This parameter can be a value of @ref SPI_LL_EC_BIT_ORDER. - - This feature can be modified afterwards using unitary function @ref LL_SPI_SetTransferBitOrder().*/ - - uint32_t CRCCalculation; /*!< Specifies if the CRC calculation is enabled or not. - This parameter can be a value of @ref SPI_LL_EC_CRC_CALCULATION. - - This feature can be modified afterwards using unitary functions @ref LL_SPI_EnableCRC() and @ref LL_SPI_DisableCRC().*/ - - uint32_t CRCPoly; /*!< Specifies the polynomial used for the CRC calculation. - This parameter must be a number between Min_Data = 0x00 and Max_Data = 0xFFFF. - - This feature can be modified afterwards using unitary function @ref LL_SPI_SetCRCPolynomial().*/ - -} LL_SPI_InitTypeDef; - -/** - * @} - */ -#endif /* USE_FULL_LL_DRIVER */ - -/* Exported constants --------------------------------------------------------*/ -/** @defgroup SPI_LL_Exported_Constants SPI Exported Constants - * @{ - */ - -/** @defgroup SPI_LL_EC_GET_FLAG Get Flags Defines - * @brief Flags defines which can be used with LL_SPI_ReadReg function - * @{ - */ -#define LL_SPI_SR_RXNE SPI_SR_RXNE /*!< Rx buffer not empty flag */ -#define LL_SPI_SR_TXE SPI_SR_TXE /*!< Tx buffer empty flag */ -#define LL_SPI_SR_BSY SPI_SR_BSY /*!< Busy flag */ -#define LL_SPI_SR_CRCERR SPI_SR_CRCERR /*!< CRC error flag */ -#define LL_SPI_SR_MODF SPI_SR_MODF /*!< Mode fault flag */ -#define LL_SPI_SR_OVR SPI_SR_OVR /*!< Overrun flag */ -#define LL_SPI_SR_FRE SPI_SR_FRE /*!< TI mode frame format error flag */ -/** - * @} - */ - -/** @defgroup SPI_LL_EC_IT IT Defines - * @brief IT defines which can be used with LL_SPI_ReadReg and LL_SPI_WriteReg functions - * @{ - */ -#define LL_SPI_CR2_RXNEIE SPI_CR2_RXNEIE /*!< Rx buffer not empty interrupt enable */ -#define LL_SPI_CR2_TXEIE SPI_CR2_TXEIE /*!< Tx buffer empty interrupt enable */ -#define LL_SPI_CR2_ERRIE SPI_CR2_ERRIE /*!< Error interrupt enable */ -/** - * @} - */ - -/** @defgroup SPI_LL_EC_MODE Operation Mode - * @{ - */ -#define LL_SPI_MODE_MASTER (SPI_CR1_MSTR | SPI_CR1_SSI) /*!< Master configuration */ -#define LL_SPI_MODE_SLAVE 0x00000000U /*!< Slave configuration */ -/** - * @} - */ - - -/** @defgroup SPI_LL_EC_PHASE Clock Phase - * @{ - */ -#define LL_SPI_PHASE_1EDGE 0x00000000U /*!< First clock transition is the first data capture edge */ -#define LL_SPI_PHASE_2EDGE (SPI_CR1_CPHA) /*!< Second clock transition is the first data capture edge */ -/** - * @} - */ - -/** @defgroup SPI_LL_EC_POLARITY Clock Polarity - * @{ - */ -#define LL_SPI_POLARITY_LOW 0x00000000U /*!< Clock to 0 when idle */ -#define LL_SPI_POLARITY_HIGH (SPI_CR1_CPOL) /*!< Clock to 1 when idle */ -/** - * @} - */ - -/** @defgroup SPI_LL_EC_BAUDRATEPRESCALER Baud Rate Prescaler - * @{ - */ -#define LL_SPI_BAUDRATEPRESCALER_DIV2 0x00000000U /*!< BaudRate control equal to fPCLK/2 */ -#define LL_SPI_BAUDRATEPRESCALER_DIV4 (SPI_CR1_BR_0) /*!< BaudRate control equal to fPCLK/4 */ -#define LL_SPI_BAUDRATEPRESCALER_DIV8 (SPI_CR1_BR_1) /*!< BaudRate control equal to fPCLK/8 */ -#define LL_SPI_BAUDRATEPRESCALER_DIV16 (SPI_CR1_BR_1 | SPI_CR1_BR_0) /*!< BaudRate control equal to fPCLK/16 */ -#define LL_SPI_BAUDRATEPRESCALER_DIV32 (SPI_CR1_BR_2) /*!< BaudRate control equal to fPCLK/32 */ -#define LL_SPI_BAUDRATEPRESCALER_DIV64 (SPI_CR1_BR_2 | SPI_CR1_BR_0) /*!< BaudRate control equal to fPCLK/64 */ -#define LL_SPI_BAUDRATEPRESCALER_DIV128 (SPI_CR1_BR_2 | SPI_CR1_BR_1) /*!< BaudRate control equal to fPCLK/128 */ -#define LL_SPI_BAUDRATEPRESCALER_DIV256 (SPI_CR1_BR_2 | SPI_CR1_BR_1 | SPI_CR1_BR_0) /*!< BaudRate control equal to fPCLK/256 */ -/** - * @} - */ - -/** @defgroup SPI_LL_EC_BIT_ORDER Transmission Bit Order - * @{ - */ -#define LL_SPI_LSB_FIRST (SPI_CR1_LSBFIRST) /*!< Data is transmitted/received with the LSB first */ -#define LL_SPI_MSB_FIRST 0x00000000U /*!< Data is transmitted/received with the MSB first */ -/** - * @} - */ - -/** @defgroup SPI_LL_EC_TRANSFER_MODE Transfer Mode - * @{ - */ -#define LL_SPI_FULL_DUPLEX 0x00000000U /*!< Full-Duplex mode. Rx and Tx transfer on 2 lines */ -#define LL_SPI_SIMPLEX_RX (SPI_CR1_RXONLY) /*!< Simplex Rx mode. Rx transfer only on 1 line */ -#define LL_SPI_HALF_DUPLEX_RX (SPI_CR1_BIDIMODE) /*!< Half-Duplex Rx mode. Rx transfer on 1 line */ -#define LL_SPI_HALF_DUPLEX_TX (SPI_CR1_BIDIMODE | SPI_CR1_BIDIOE) /*!< Half-Duplex Tx mode. Tx transfer on 1 line */ -/** - * @} - */ - -/** @defgroup SPI_LL_EC_NSS_MODE Slave Select Pin Mode - * @{ - */ -#define LL_SPI_NSS_SOFT (SPI_CR1_SSM) /*!< NSS managed internally. NSS pin not used and free */ -#define LL_SPI_NSS_HARD_INPUT 0x00000000U /*!< NSS pin used in Input. Only used in Master mode */ -#define LL_SPI_NSS_HARD_OUTPUT (((uint32_t)SPI_CR2_SSOE << 16U)) /*!< NSS pin used in Output. Only used in Slave mode as chip select */ -/** - * @} - */ - -/** @defgroup SPI_LL_EC_DATAWIDTH Datawidth - * @{ - */ -#define LL_SPI_DATAWIDTH_8BIT 0x00000000U /*!< Data length for SPI transfer: 8 bits */ -#define LL_SPI_DATAWIDTH_16BIT (SPI_CR1_DFF) /*!< Data length for SPI transfer: 16 bits */ -/** - * @} - */ -#if defined(USE_FULL_LL_DRIVER) - -/** @defgroup SPI_LL_EC_CRC_CALCULATION CRC Calculation - * @{ - */ -#define LL_SPI_CRCCALCULATION_DISABLE 0x00000000U /*!< CRC calculation disabled */ -#define LL_SPI_CRCCALCULATION_ENABLE (SPI_CR1_CRCEN) /*!< CRC calculation enabled */ -/** - * @} - */ -#endif /* USE_FULL_LL_DRIVER */ - -/** - * @} - */ - -/* Exported macro ------------------------------------------------------------*/ -/** @defgroup SPI_LL_Exported_Macros SPI Exported Macros - * @{ - */ - -/** @defgroup SPI_LL_EM_WRITE_READ Common Write and read registers Macros - * @{ - */ - -/** - * @brief Write a value in SPI register - * @param __INSTANCE__ SPI Instance - * @param __REG__ Register to be written - * @param __VALUE__ Value to be written in the register - * @retval None - */ -#define LL_SPI_WriteReg(__INSTANCE__, __REG__, __VALUE__) WRITE_REG(__INSTANCE__->__REG__, (__VALUE__)) - -/** - * @brief Read a value in SPI register - * @param __INSTANCE__ SPI Instance - * @param __REG__ Register to be read - * @retval Register value - */ -#define LL_SPI_ReadReg(__INSTANCE__, __REG__) READ_REG(__INSTANCE__->__REG__) -/** - * @} - */ - -/** - * @} - */ - -/* Exported functions --------------------------------------------------------*/ -/** @defgroup SPI_LL_Exported_Functions SPI Exported Functions - * @{ - */ - -/** @defgroup SPI_LL_EF_Configuration Configuration - * @{ - */ - -/** - * @brief Enable SPI peripheral - * @rmtoll CR1 SPE LL_SPI_Enable - * @param SPIx SPI Instance - * @retval None - */ -__STATIC_INLINE void LL_SPI_Enable(SPI_TypeDef *SPIx) -{ - SET_BIT(SPIx->CR1, SPI_CR1_SPE); -} - -/** - * @brief Disable SPI peripheral - * @note When disabling the SPI, follow the procedure described in the Reference Manual. - * @rmtoll CR1 SPE LL_SPI_Disable - * @param SPIx SPI Instance - * @retval None - */ -__STATIC_INLINE void LL_SPI_Disable(SPI_TypeDef *SPIx) -{ - CLEAR_BIT(SPIx->CR1, SPI_CR1_SPE); -} - -/** - * @brief Check if SPI peripheral is enabled - * @rmtoll CR1 SPE LL_SPI_IsEnabled - * @param SPIx SPI Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_SPI_IsEnabled(SPI_TypeDef *SPIx) -{ - return (READ_BIT(SPIx->CR1, SPI_CR1_SPE) == (SPI_CR1_SPE)); -} - -/** - * @brief Set SPI operation mode to Master or Slave - * @note This bit should not be changed when communication is ongoing. - * @rmtoll CR1 MSTR LL_SPI_SetMode\n - * CR1 SSI LL_SPI_SetMode - * @param SPIx SPI Instance - * @param Mode This parameter can be one of the following values: - * @arg @ref LL_SPI_MODE_MASTER - * @arg @ref LL_SPI_MODE_SLAVE - * @retval None - */ -__STATIC_INLINE void LL_SPI_SetMode(SPI_TypeDef *SPIx, uint32_t Mode) -{ - MODIFY_REG(SPIx->CR1, SPI_CR1_MSTR | SPI_CR1_SSI, Mode); -} - -/** - * @brief Get SPI operation mode (Master or Slave) - * @rmtoll CR1 MSTR LL_SPI_GetMode\n - * CR1 SSI LL_SPI_GetMode - * @param SPIx SPI Instance - * @retval Returned value can be one of the following values: - * @arg @ref LL_SPI_MODE_MASTER - * @arg @ref LL_SPI_MODE_SLAVE - */ -__STATIC_INLINE uint32_t LL_SPI_GetMode(SPI_TypeDef *SPIx) -{ - return (uint32_t)(READ_BIT(SPIx->CR1, SPI_CR1_MSTR | SPI_CR1_SSI)); -} - - -/** - * @brief Set clock phase - * @note This bit should not be changed when communication is ongoing. - * This bit is not used in SPI TI mode. - * @rmtoll CR1 CPHA LL_SPI_SetClockPhase - * @param SPIx SPI Instance - * @param ClockPhase This parameter can be one of the following values: - * @arg @ref LL_SPI_PHASE_1EDGE - * @arg @ref LL_SPI_PHASE_2EDGE - * @retval None - */ -__STATIC_INLINE void LL_SPI_SetClockPhase(SPI_TypeDef *SPIx, uint32_t ClockPhase) -{ - MODIFY_REG(SPIx->CR1, SPI_CR1_CPHA, ClockPhase); -} - -/** - * @brief Get clock phase - * @rmtoll CR1 CPHA LL_SPI_GetClockPhase - * @param SPIx SPI Instance - * @retval Returned value can be one of the following values: - * @arg @ref LL_SPI_PHASE_1EDGE - * @arg @ref LL_SPI_PHASE_2EDGE - */ -__STATIC_INLINE uint32_t LL_SPI_GetClockPhase(SPI_TypeDef *SPIx) -{ - return (uint32_t)(READ_BIT(SPIx->CR1, SPI_CR1_CPHA)); -} - -/** - * @brief Set clock polarity - * @note This bit should not be changed when communication is ongoing. - * This bit is not used in SPI TI mode. - * @rmtoll CR1 CPOL LL_SPI_SetClockPolarity - * @param SPIx SPI Instance - * @param ClockPolarity This parameter can be one of the following values: - * @arg @ref LL_SPI_POLARITY_LOW - * @arg @ref LL_SPI_POLARITY_HIGH - * @retval None - */ -__STATIC_INLINE void LL_SPI_SetClockPolarity(SPI_TypeDef *SPIx, uint32_t ClockPolarity) -{ - MODIFY_REG(SPIx->CR1, SPI_CR1_CPOL, ClockPolarity); -} - -/** - * @brief Get clock polarity - * @rmtoll CR1 CPOL LL_SPI_GetClockPolarity - * @param SPIx SPI Instance - * @retval Returned value can be one of the following values: - * @arg @ref LL_SPI_POLARITY_LOW - * @arg @ref LL_SPI_POLARITY_HIGH - */ -__STATIC_INLINE uint32_t LL_SPI_GetClockPolarity(SPI_TypeDef *SPIx) -{ - return (uint32_t)(READ_BIT(SPIx->CR1, SPI_CR1_CPOL)); -} - -/** - * @brief Set baud rate prescaler - * @note These bits should not be changed when communication is ongoing. SPI BaudRate = fPCLK/Prescaler. - * @rmtoll CR1 BR LL_SPI_SetBaudRatePrescaler - * @param SPIx SPI Instance - * @param BaudRate This parameter can be one of the following values: - * @arg @ref LL_SPI_BAUDRATEPRESCALER_DIV2 - * @arg @ref LL_SPI_BAUDRATEPRESCALER_DIV4 - * @arg @ref LL_SPI_BAUDRATEPRESCALER_DIV8 - * @arg @ref LL_SPI_BAUDRATEPRESCALER_DIV16 - * @arg @ref LL_SPI_BAUDRATEPRESCALER_DIV32 - * @arg @ref LL_SPI_BAUDRATEPRESCALER_DIV64 - * @arg @ref LL_SPI_BAUDRATEPRESCALER_DIV128 - * @arg @ref LL_SPI_BAUDRATEPRESCALER_DIV256 - * @retval None - */ -__STATIC_INLINE void LL_SPI_SetBaudRatePrescaler(SPI_TypeDef *SPIx, uint32_t BaudRate) -{ - MODIFY_REG(SPIx->CR1, SPI_CR1_BR, BaudRate); -} - -/** - * @brief Get baud rate prescaler - * @rmtoll CR1 BR LL_SPI_GetBaudRatePrescaler - * @param SPIx SPI Instance - * @retval Returned value can be one of the following values: - * @arg @ref LL_SPI_BAUDRATEPRESCALER_DIV2 - * @arg @ref LL_SPI_BAUDRATEPRESCALER_DIV4 - * @arg @ref LL_SPI_BAUDRATEPRESCALER_DIV8 - * @arg @ref LL_SPI_BAUDRATEPRESCALER_DIV16 - * @arg @ref LL_SPI_BAUDRATEPRESCALER_DIV32 - * @arg @ref LL_SPI_BAUDRATEPRESCALER_DIV64 - * @arg @ref LL_SPI_BAUDRATEPRESCALER_DIV128 - * @arg @ref LL_SPI_BAUDRATEPRESCALER_DIV256 - */ -__STATIC_INLINE uint32_t LL_SPI_GetBaudRatePrescaler(SPI_TypeDef *SPIx) -{ - return (uint32_t)(READ_BIT(SPIx->CR1, SPI_CR1_BR)); -} - -/** - * @brief Set transfer bit order - * @note This bit should not be changed when communication is ongoing. This bit is not used in SPI TI mode. - * @rmtoll CR1 LSBFIRST LL_SPI_SetTransferBitOrder - * @param SPIx SPI Instance - * @param BitOrder This parameter can be one of the following values: - * @arg @ref LL_SPI_LSB_FIRST - * @arg @ref LL_SPI_MSB_FIRST - * @retval None - */ -__STATIC_INLINE void LL_SPI_SetTransferBitOrder(SPI_TypeDef *SPIx, uint32_t BitOrder) -{ - MODIFY_REG(SPIx->CR1, SPI_CR1_LSBFIRST, BitOrder); -} - -/** - * @brief Get transfer bit order - * @rmtoll CR1 LSBFIRST LL_SPI_GetTransferBitOrder - * @param SPIx SPI Instance - * @retval Returned value can be one of the following values: - * @arg @ref LL_SPI_LSB_FIRST - * @arg @ref LL_SPI_MSB_FIRST - */ -__STATIC_INLINE uint32_t LL_SPI_GetTransferBitOrder(SPI_TypeDef *SPIx) -{ - return (uint32_t)(READ_BIT(SPIx->CR1, SPI_CR1_LSBFIRST)); -} - -/** - * @brief Set transfer direction mode - * @note For Half-Duplex mode, Rx Direction is set by default. - * In master mode, the MOSI pin is used and in slave mode, the MISO pin is used for Half-Duplex. - * @rmtoll CR1 RXONLY LL_SPI_SetTransferDirection\n - * CR1 BIDIMODE LL_SPI_SetTransferDirection\n - * CR1 BIDIOE LL_SPI_SetTransferDirection - * @param SPIx SPI Instance - * @param TransferDirection This parameter can be one of the following values: - * @arg @ref LL_SPI_FULL_DUPLEX - * @arg @ref LL_SPI_SIMPLEX_RX - * @arg @ref LL_SPI_HALF_DUPLEX_RX - * @arg @ref LL_SPI_HALF_DUPLEX_TX - * @retval None - */ -__STATIC_INLINE void LL_SPI_SetTransferDirection(SPI_TypeDef *SPIx, uint32_t TransferDirection) -{ - MODIFY_REG(SPIx->CR1, SPI_CR1_RXONLY | SPI_CR1_BIDIMODE | SPI_CR1_BIDIOE, TransferDirection); -} - -/** - * @brief Get transfer direction mode - * @rmtoll CR1 RXONLY LL_SPI_GetTransferDirection\n - * CR1 BIDIMODE LL_SPI_GetTransferDirection\n - * CR1 BIDIOE LL_SPI_GetTransferDirection - * @param SPIx SPI Instance - * @retval Returned value can be one of the following values: - * @arg @ref LL_SPI_FULL_DUPLEX - * @arg @ref LL_SPI_SIMPLEX_RX - * @arg @ref LL_SPI_HALF_DUPLEX_RX - * @arg @ref LL_SPI_HALF_DUPLEX_TX - */ -__STATIC_INLINE uint32_t LL_SPI_GetTransferDirection(SPI_TypeDef *SPIx) -{ - return (uint32_t)(READ_BIT(SPIx->CR1, SPI_CR1_RXONLY | SPI_CR1_BIDIMODE | SPI_CR1_BIDIOE)); -} - -/** - * @brief Set frame data width - * @rmtoll CR1 DFF LL_SPI_SetDataWidth - * @param SPIx SPI Instance - * @param DataWidth This parameter can be one of the following values: - * @arg @ref LL_SPI_DATAWIDTH_8BIT - * @arg @ref LL_SPI_DATAWIDTH_16BIT - * @retval None - */ -__STATIC_INLINE void LL_SPI_SetDataWidth(SPI_TypeDef *SPIx, uint32_t DataWidth) -{ - MODIFY_REG(SPIx->CR1, SPI_CR1_DFF, DataWidth); -} - -/** - * @brief Get frame data width - * @rmtoll CR1 DFF LL_SPI_GetDataWidth - * @param SPIx SPI Instance - * @retval Returned value can be one of the following values: - * @arg @ref LL_SPI_DATAWIDTH_8BIT - * @arg @ref LL_SPI_DATAWIDTH_16BIT - */ -__STATIC_INLINE uint32_t LL_SPI_GetDataWidth(SPI_TypeDef *SPIx) -{ - return (uint32_t)(READ_BIT(SPIx->CR1, SPI_CR1_DFF)); -} - -/** - * @} - */ - -/** @defgroup SPI_LL_EF_CRC_Management CRC Management - * @{ - */ - -/** - * @brief Enable CRC - * @note This bit should be written only when SPI is disabled (SPE = 0) for correct operation. - * @rmtoll CR1 CRCEN LL_SPI_EnableCRC - * @param SPIx SPI Instance - * @retval None - */ -__STATIC_INLINE void LL_SPI_EnableCRC(SPI_TypeDef *SPIx) -{ - SET_BIT(SPIx->CR1, SPI_CR1_CRCEN); -} - -/** - * @brief Disable CRC - * @note This bit should be written only when SPI is disabled (SPE = 0) for correct operation. - * @rmtoll CR1 CRCEN LL_SPI_DisableCRC - * @param SPIx SPI Instance - * @retval None - */ -__STATIC_INLINE void LL_SPI_DisableCRC(SPI_TypeDef *SPIx) -{ - CLEAR_BIT(SPIx->CR1, SPI_CR1_CRCEN); -} - -/** - * @brief Check if CRC is enabled - * @note This bit should be written only when SPI is disabled (SPE = 0) for correct operation. - * @rmtoll CR1 CRCEN LL_SPI_IsEnabledCRC - * @param SPIx SPI Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_SPI_IsEnabledCRC(SPI_TypeDef *SPIx) -{ - return (READ_BIT(SPIx->CR1, SPI_CR1_CRCEN) == (SPI_CR1_CRCEN)); -} - -/** - * @brief Set CRCNext to transfer CRC on the line - * @note This bit has to be written as soon as the last data is written in the SPIx_DR register. - * @rmtoll CR1 CRCNEXT LL_SPI_SetCRCNext - * @param SPIx SPI Instance - * @retval None - */ -__STATIC_INLINE void LL_SPI_SetCRCNext(SPI_TypeDef *SPIx) -{ - SET_BIT(SPIx->CR1, SPI_CR1_CRCNEXT); -} - -/** - * @brief Set polynomial for CRC calculation - * @rmtoll CRCPR CRCPOLY LL_SPI_SetCRCPolynomial - * @param SPIx SPI Instance - * @param CRCPoly This parameter must be a number between Min_Data = 0x00 and Max_Data = 0xFFFF - * @retval None - */ -__STATIC_INLINE void LL_SPI_SetCRCPolynomial(SPI_TypeDef *SPIx, uint32_t CRCPoly) -{ - WRITE_REG(SPIx->CRCPR, (uint16_t)CRCPoly); -} - -/** - * @brief Get polynomial for CRC calculation - * @rmtoll CRCPR CRCPOLY LL_SPI_GetCRCPolynomial - * @param SPIx SPI Instance - * @retval Returned value is a number between Min_Data = 0x00 and Max_Data = 0xFFFF - */ -__STATIC_INLINE uint32_t LL_SPI_GetCRCPolynomial(SPI_TypeDef *SPIx) -{ - return (uint32_t)(READ_REG(SPIx->CRCPR)); -} - -/** - * @brief Get Rx CRC - * @rmtoll RXCRCR RXCRC LL_SPI_GetRxCRC - * @param SPIx SPI Instance - * @retval Returned value is a number between Min_Data = 0x00 and Max_Data = 0xFFFF - */ -__STATIC_INLINE uint32_t LL_SPI_GetRxCRC(SPI_TypeDef *SPIx) -{ - return (uint32_t)(READ_REG(SPIx->RXCRCR)); -} - -/** - * @brief Get Tx CRC - * @rmtoll TXCRCR TXCRC LL_SPI_GetTxCRC - * @param SPIx SPI Instance - * @retval Returned value is a number between Min_Data = 0x00 and Max_Data = 0xFFFF - */ -__STATIC_INLINE uint32_t LL_SPI_GetTxCRC(SPI_TypeDef *SPIx) -{ - return (uint32_t)(READ_REG(SPIx->TXCRCR)); -} - -/** - * @} - */ - -/** @defgroup SPI_LL_EF_NSS_Management Slave Select Pin Management - * @{ - */ - -/** - * @brief Set NSS mode - * @note LL_SPI_NSS_SOFT Mode is not used in SPI TI mode. - * @rmtoll CR1 SSM LL_SPI_SetNSSMode\n - * @rmtoll CR2 SSOE LL_SPI_SetNSSMode - * @param SPIx SPI Instance - * @param NSS This parameter can be one of the following values: - * @arg @ref LL_SPI_NSS_SOFT - * @arg @ref LL_SPI_NSS_HARD_INPUT - * @arg @ref LL_SPI_NSS_HARD_OUTPUT - * @retval None - */ -__STATIC_INLINE void LL_SPI_SetNSSMode(SPI_TypeDef *SPIx, uint32_t NSS) -{ - MODIFY_REG(SPIx->CR1, SPI_CR1_SSM, NSS); - MODIFY_REG(SPIx->CR2, SPI_CR2_SSOE, ((uint32_t)(NSS >> 16U))); -} - -/** - * @brief Get NSS mode - * @rmtoll CR1 SSM LL_SPI_GetNSSMode\n - * @rmtoll CR2 SSOE LL_SPI_GetNSSMode - * @param SPIx SPI Instance - * @retval Returned value can be one of the following values: - * @arg @ref LL_SPI_NSS_SOFT - * @arg @ref LL_SPI_NSS_HARD_INPUT - * @arg @ref LL_SPI_NSS_HARD_OUTPUT - */ -__STATIC_INLINE uint32_t LL_SPI_GetNSSMode(SPI_TypeDef *SPIx) -{ - register uint32_t Ssm = (READ_BIT(SPIx->CR1, SPI_CR1_SSM)); - register uint32_t Ssoe = (READ_BIT(SPIx->CR2, SPI_CR2_SSOE) << 16U); - return (Ssm | Ssoe); -} - -/** - * @} - */ - -/** @defgroup SPI_LL_EF_FLAG_Management FLAG Management - * @{ - */ - -/** - * @brief Check if Rx buffer is not empty - * @rmtoll SR RXNE LL_SPI_IsActiveFlag_RXNE - * @param SPIx SPI Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_RXNE(SPI_TypeDef *SPIx) -{ - return (READ_BIT(SPIx->SR, SPI_SR_RXNE) == (SPI_SR_RXNE)); -} - -/** - * @brief Check if Tx buffer is empty - * @rmtoll SR TXE LL_SPI_IsActiveFlag_TXE - * @param SPIx SPI Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_TXE(SPI_TypeDef *SPIx) -{ - return (READ_BIT(SPIx->SR, SPI_SR_TXE) == (SPI_SR_TXE)); -} - -/** - * @brief Get CRC error flag - * @rmtoll SR CRCERR LL_SPI_IsActiveFlag_CRCERR - * @param SPIx SPI Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_CRCERR(SPI_TypeDef *SPIx) -{ - return (READ_BIT(SPIx->SR, SPI_SR_CRCERR) == (SPI_SR_CRCERR)); -} - -/** - * @brief Get mode fault error flag - * @rmtoll SR MODF LL_SPI_IsActiveFlag_MODF - * @param SPIx SPI Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_MODF(SPI_TypeDef *SPIx) -{ - return (READ_BIT(SPIx->SR, SPI_SR_MODF) == (SPI_SR_MODF)); -} - -/** - * @brief Get overrun error flag - * @rmtoll SR OVR LL_SPI_IsActiveFlag_OVR - * @param SPIx SPI Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_OVR(SPI_TypeDef *SPIx) -{ - return (READ_BIT(SPIx->SR, SPI_SR_OVR) == (SPI_SR_OVR)); -} - -/** - * @brief Get busy flag - * @note The BSY flag is cleared under any one of the following conditions: - * -When the SPI is correctly disabled - * -When a fault is detected in Master mode (MODF bit set to 1) - * -In Master mode, when it finishes a data transmission and no new data is ready to be - * sent - * -In Slave mode, when the BSY flag is set to '0' for at least one SPI clock cycle between - * each data transfer. - * @rmtoll SR BSY LL_SPI_IsActiveFlag_BSY - * @param SPIx SPI Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_SPI_IsActiveFlag_BSY(SPI_TypeDef *SPIx) -{ - return (READ_BIT(SPIx->SR, SPI_SR_BSY) == (SPI_SR_BSY)); -} - - -/** - * @brief Clear CRC error flag - * @rmtoll SR CRCERR LL_SPI_ClearFlag_CRCERR - * @param SPIx SPI Instance - * @retval None - */ -__STATIC_INLINE void LL_SPI_ClearFlag_CRCERR(SPI_TypeDef *SPIx) -{ - CLEAR_BIT(SPIx->SR, SPI_SR_CRCERR); -} - -/** - * @brief Clear mode fault error flag - * @note Clearing this flag is done by a read access to the SPIx_SR - * register followed by a write access to the SPIx_CR1 register - * @rmtoll SR MODF LL_SPI_ClearFlag_MODF - * @param SPIx SPI Instance - * @retval None - */ -__STATIC_INLINE void LL_SPI_ClearFlag_MODF(SPI_TypeDef *SPIx) -{ - __IO uint32_t tmpreg; - tmpreg = SPIx->SR; - (void) tmpreg; - tmpreg = CLEAR_BIT(SPIx->CR1, SPI_CR1_SPE); - (void) tmpreg; -} - -/** - * @brief Clear overrun error flag - * @note Clearing this flag is done by a read access to the SPIx_DR - * register followed by a read access to the SPIx_SR register - * @rmtoll SR OVR LL_SPI_ClearFlag_OVR - * @param SPIx SPI Instance - * @retval None - */ -__STATIC_INLINE void LL_SPI_ClearFlag_OVR(SPI_TypeDef *SPIx) -{ - __IO uint32_t tmpreg; - tmpreg = SPIx->DR; - (void) tmpreg; - tmpreg = SPIx->SR; - (void) tmpreg; -} - - -/** - * @} - */ - -/** @defgroup SPI_LL_EF_IT_Management Interrupt Management - * @{ - */ - -/** - * @brief Enable error interrupt - * @note This bit controls the generation of an interrupt when an error condition occurs (CRCERR, OVR, MODF in SPI mode, FRE at TI mode). - * @rmtoll CR2 ERRIE LL_SPI_EnableIT_ERR - * @param SPIx SPI Instance - * @retval None - */ -__STATIC_INLINE void LL_SPI_EnableIT_ERR(SPI_TypeDef *SPIx) -{ - SET_BIT(SPIx->CR2, SPI_CR2_ERRIE); -} - -/** - * @brief Enable Rx buffer not empty interrupt - * @rmtoll CR2 RXNEIE LL_SPI_EnableIT_RXNE - * @param SPIx SPI Instance - * @retval None - */ -__STATIC_INLINE void LL_SPI_EnableIT_RXNE(SPI_TypeDef *SPIx) -{ - SET_BIT(SPIx->CR2, SPI_CR2_RXNEIE); -} - -/** - * @brief Enable Tx buffer empty interrupt - * @rmtoll CR2 TXEIE LL_SPI_EnableIT_TXE - * @param SPIx SPI Instance - * @retval None - */ -__STATIC_INLINE void LL_SPI_EnableIT_TXE(SPI_TypeDef *SPIx) -{ - SET_BIT(SPIx->CR2, SPI_CR2_TXEIE); -} - -/** - * @brief Disable error interrupt - * @note This bit controls the generation of an interrupt when an error condition occurs (CRCERR, OVR, MODF in SPI mode, FRE at TI mode). - * @rmtoll CR2 ERRIE LL_SPI_DisableIT_ERR - * @param SPIx SPI Instance - * @retval None - */ -__STATIC_INLINE void LL_SPI_DisableIT_ERR(SPI_TypeDef *SPIx) -{ - CLEAR_BIT(SPIx->CR2, SPI_CR2_ERRIE); -} - -/** - * @brief Disable Rx buffer not empty interrupt - * @rmtoll CR2 RXNEIE LL_SPI_DisableIT_RXNE - * @param SPIx SPI Instance - * @retval None - */ -__STATIC_INLINE void LL_SPI_DisableIT_RXNE(SPI_TypeDef *SPIx) -{ - CLEAR_BIT(SPIx->CR2, SPI_CR2_RXNEIE); -} - -/** - * @brief Disable Tx buffer empty interrupt - * @rmtoll CR2 TXEIE LL_SPI_DisableIT_TXE - * @param SPIx SPI Instance - * @retval None - */ -__STATIC_INLINE void LL_SPI_DisableIT_TXE(SPI_TypeDef *SPIx) -{ - CLEAR_BIT(SPIx->CR2, SPI_CR2_TXEIE); -} - -/** - * @brief Check if error interrupt is enabled - * @rmtoll CR2 ERRIE LL_SPI_IsEnabledIT_ERR - * @param SPIx SPI Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_SPI_IsEnabledIT_ERR(SPI_TypeDef *SPIx) -{ - return (READ_BIT(SPIx->CR2, SPI_CR2_ERRIE) == (SPI_CR2_ERRIE)); -} - -/** - * @brief Check if Rx buffer not empty interrupt is enabled - * @rmtoll CR2 RXNEIE LL_SPI_IsEnabledIT_RXNE - * @param SPIx SPI Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_SPI_IsEnabledIT_RXNE(SPI_TypeDef *SPIx) -{ - return (READ_BIT(SPIx->CR2, SPI_CR2_RXNEIE) == (SPI_CR2_RXNEIE)); -} - -/** - * @brief Check if Tx buffer empty interrupt - * @rmtoll CR2 TXEIE LL_SPI_IsEnabledIT_TXE - * @param SPIx SPI Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_SPI_IsEnabledIT_TXE(SPI_TypeDef *SPIx) -{ - return (READ_BIT(SPIx->CR2, SPI_CR2_TXEIE) == (SPI_CR2_TXEIE)); -} - -/** - * @} - */ - -/** @defgroup SPI_LL_EF_DMA_Management DMA Management - * @{ - */ - -/** - * @brief Enable DMA Rx - * @rmtoll CR2 RXDMAEN LL_SPI_EnableDMAReq_RX - * @param SPIx SPI Instance - * @retval None - */ -__STATIC_INLINE void LL_SPI_EnableDMAReq_RX(SPI_TypeDef *SPIx) -{ - SET_BIT(SPIx->CR2, SPI_CR2_RXDMAEN); -} - -/** - * @brief Disable DMA Rx - * @rmtoll CR2 RXDMAEN LL_SPI_DisableDMAReq_RX - * @param SPIx SPI Instance - * @retval None - */ -__STATIC_INLINE void LL_SPI_DisableDMAReq_RX(SPI_TypeDef *SPIx) -{ - CLEAR_BIT(SPIx->CR2, SPI_CR2_RXDMAEN); -} - -/** - * @brief Check if DMA Rx is enabled - * @rmtoll CR2 RXDMAEN LL_SPI_IsEnabledDMAReq_RX - * @param SPIx SPI Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_SPI_IsEnabledDMAReq_RX(SPI_TypeDef *SPIx) -{ - return (READ_BIT(SPIx->CR2, SPI_CR2_RXDMAEN) == (SPI_CR2_RXDMAEN)); -} - -/** - * @brief Enable DMA Tx - * @rmtoll CR2 TXDMAEN LL_SPI_EnableDMAReq_TX - * @param SPIx SPI Instance - * @retval None - */ -__STATIC_INLINE void LL_SPI_EnableDMAReq_TX(SPI_TypeDef *SPIx) -{ - SET_BIT(SPIx->CR2, SPI_CR2_TXDMAEN); -} - -/** - * @brief Disable DMA Tx - * @rmtoll CR2 TXDMAEN LL_SPI_DisableDMAReq_TX - * @param SPIx SPI Instance - * @retval None - */ -__STATIC_INLINE void LL_SPI_DisableDMAReq_TX(SPI_TypeDef *SPIx) -{ - CLEAR_BIT(SPIx->CR2, SPI_CR2_TXDMAEN); -} - -/** - * @brief Check if DMA Tx is enabled - * @rmtoll CR2 TXDMAEN LL_SPI_IsEnabledDMAReq_TX - * @param SPIx SPI Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_SPI_IsEnabledDMAReq_TX(SPI_TypeDef *SPIx) -{ - return (READ_BIT(SPIx->CR2, SPI_CR2_TXDMAEN) == (SPI_CR2_TXDMAEN)); -} - -/** - * @brief Get the data register address used for DMA transfer - * @rmtoll DR DR LL_SPI_DMA_GetRegAddr - * @param SPIx SPI Instance - * @retval Address of data register - */ -__STATIC_INLINE uint32_t LL_SPI_DMA_GetRegAddr(SPI_TypeDef *SPIx) -{ - return (uint32_t) & (SPIx->DR); -} - -/** - * @} - */ - -/** @defgroup SPI_LL_EF_DATA_Management DATA Management - * @{ - */ - -/** - * @brief Read 8-Bits in the data register - * @rmtoll DR DR LL_SPI_ReceiveData8 - * @param SPIx SPI Instance - * @retval RxData Value between Min_Data=0x00 and Max_Data=0xFF - */ -__STATIC_INLINE uint8_t LL_SPI_ReceiveData8(SPI_TypeDef *SPIx) -{ - return (uint8_t)(READ_REG(SPIx->DR)); -} - -/** - * @brief Read 16-Bits in the data register - * @rmtoll DR DR LL_SPI_ReceiveData16 - * @param SPIx SPI Instance - * @retval RxData Value between Min_Data=0x00 and Max_Data=0xFFFF - */ -__STATIC_INLINE uint16_t LL_SPI_ReceiveData16(SPI_TypeDef *SPIx) -{ - return (uint16_t)(READ_REG(SPIx->DR)); -} - -/** - * @brief Write 8-Bits in the data register - * @rmtoll DR DR LL_SPI_TransmitData8 - * @param SPIx SPI Instance - * @param TxData Value between Min_Data=0x00 and Max_Data=0xFF - * @retval None - */ -__STATIC_INLINE void LL_SPI_TransmitData8(SPI_TypeDef *SPIx, uint8_t TxData) -{ - SPIx->DR = TxData; -} - -/** - * @brief Write 16-Bits in the data register - * @rmtoll DR DR LL_SPI_TransmitData16 - * @param SPIx SPI Instance - * @param TxData Value between Min_Data=0x00 and Max_Data=0xFFFF - * @retval None - */ -__STATIC_INLINE void LL_SPI_TransmitData16(SPI_TypeDef *SPIx, uint16_t TxData) -{ - SPIx->DR = TxData; -} - -/** - * @} - */ -#if defined(USE_FULL_LL_DRIVER) -/** @defgroup SPI_LL_EF_Init Initialization and de-initialization functions - * @{ - */ - -ErrorStatus LL_SPI_DeInit(SPI_TypeDef *SPIx); -ErrorStatus LL_SPI_Init(SPI_TypeDef *SPIx, LL_SPI_InitTypeDef *SPI_InitStruct); -void LL_SPI_StructInit(LL_SPI_InitTypeDef *SPI_InitStruct); - -/** - * @} - */ -#endif /* USE_FULL_LL_DRIVER */ -/** - * @} - */ - -/** - * @} - */ - -#if defined(SPI_I2S_SUPPORT) -/** @defgroup I2S_LL I2S - * @{ - */ - -/* Private variables ---------------------------------------------------------*/ -/* Private constants ---------------------------------------------------------*/ -/* Private macros ------------------------------------------------------------*/ - -/* Exported types ------------------------------------------------------------*/ -#if defined(USE_FULL_LL_DRIVER) -/** @defgroup I2S_LL_ES_INIT I2S Exported Init structure - * @{ - */ - -/** - * @brief I2S Init structure definition - */ - -typedef struct -{ - uint32_t Mode; /*!< Specifies the I2S operating mode. - This parameter can be a value of @ref I2S_LL_EC_MODE - - This feature can be modified afterwards using unitary function @ref LL_I2S_SetTransferMode().*/ - - uint32_t Standard; /*!< Specifies the standard used for the I2S communication. - This parameter can be a value of @ref I2S_LL_EC_STANDARD - - This feature can be modified afterwards using unitary function @ref LL_I2S_SetStandard().*/ - - - uint32_t DataFormat; /*!< Specifies the data format for the I2S communication. - This parameter can be a value of @ref I2S_LL_EC_DATA_FORMAT - - This feature can be modified afterwards using unitary function @ref LL_I2S_SetDataFormat().*/ - - - uint32_t MCLKOutput; /*!< Specifies whether the I2S MCLK output is enabled or not. - This parameter can be a value of @ref I2S_LL_EC_MCLK_OUTPUT - - This feature can be modified afterwards using unitary functions @ref LL_I2S_EnableMasterClock() or @ref LL_I2S_DisableMasterClock.*/ - - - uint32_t AudioFreq; /*!< Specifies the frequency selected for the I2S communication. - This parameter can be a value of @ref I2S_LL_EC_AUDIO_FREQ - - Audio Frequency can be modified afterwards using Reference manual formulas to calculate Prescaler Linear, Parity - and unitary functions @ref LL_I2S_SetPrescalerLinear() and @ref LL_I2S_SetPrescalerParity() to set it.*/ - - - uint32_t ClockPolarity; /*!< Specifies the idle state of the I2S clock. - This parameter can be a value of @ref I2S_LL_EC_POLARITY - - This feature can be modified afterwards using unitary function @ref LL_I2S_SetClockPolarity().*/ - -} LL_I2S_InitTypeDef; - -/** - * @} - */ -#endif /*USE_FULL_LL_DRIVER*/ - -/* Exported constants --------------------------------------------------------*/ -/** @defgroup I2S_LL_Exported_Constants I2S Exported Constants - * @{ - */ - -/** @defgroup I2S_LL_EC_GET_FLAG Get Flags Defines - * @brief Flags defines which can be used with LL_I2S_ReadReg function - * @{ - */ -#define LL_I2S_SR_RXNE LL_SPI_SR_RXNE /*!< Rx buffer not empty flag */ -#define LL_I2S_SR_TXE LL_SPI_SR_TXE /*!< Tx buffer empty flag */ -#define LL_I2S_SR_BSY LL_SPI_SR_BSY /*!< Busy flag */ -#define LL_I2S_SR_UDR SPI_SR_UDR /*!< Underrun flag */ -#define LL_I2S_SR_OVR LL_SPI_SR_OVR /*!< Overrun flag */ -#define LL_I2S_SR_FRE LL_SPI_SR_FRE /*!< TI mode frame format error flag */ -/** - * @} - */ - -/** @defgroup SPI_LL_EC_IT IT Defines - * @brief IT defines which can be used with LL_SPI_ReadReg and LL_SPI_WriteReg functions - * @{ - */ -#define LL_I2S_CR2_RXNEIE LL_SPI_CR2_RXNEIE /*!< Rx buffer not empty interrupt enable */ -#define LL_I2S_CR2_TXEIE LL_SPI_CR2_TXEIE /*!< Tx buffer empty interrupt enable */ -#define LL_I2S_CR2_ERRIE LL_SPI_CR2_ERRIE /*!< Error interrupt enable */ -/** - * @} - */ - -/** @defgroup I2S_LL_EC_DATA_FORMAT Data format - * @{ - */ -#define LL_I2S_DATAFORMAT_16B 0x00000000U /*!< Data length 16 bits, Channel lenght 16bit */ -#define LL_I2S_DATAFORMAT_16B_EXTENDED (SPI_I2SCFGR_CHLEN) /*!< Data length 16 bits, Channel lenght 32bit */ -#define LL_I2S_DATAFORMAT_24B (SPI_I2SCFGR_CHLEN | SPI_I2SCFGR_DATLEN_0) /*!< Data length 24 bits, Channel lenght 32bit */ -#define LL_I2S_DATAFORMAT_32B (SPI_I2SCFGR_CHLEN | SPI_I2SCFGR_DATLEN_1) /*!< Data length 16 bits, Channel lenght 32bit */ -/** - * @} - */ - -/** @defgroup I2S_LL_EC_POLARITY Clock Polarity - * @{ - */ -#define LL_I2S_POLARITY_LOW 0x00000000U /*!< Clock steady state is low level */ -#define LL_I2S_POLARITY_HIGH (SPI_I2SCFGR_CKPOL) /*!< Clock steady state is high level */ -/** - * @} - */ - -/** @defgroup I2S_LL_EC_STANDARD I2s Standard - * @{ - */ -#define LL_I2S_STANDARD_PHILIPS 0x00000000U /*!< I2S standard philips */ -#define LL_I2S_STANDARD_MSB (SPI_I2SCFGR_I2SSTD_0) /*!< MSB justified standard (left justified) */ -#define LL_I2S_STANDARD_LSB (SPI_I2SCFGR_I2SSTD_1) /*!< LSB justified standard (right justified) */ -#define LL_I2S_STANDARD_PCM_SHORT (SPI_I2SCFGR_I2SSTD_0 | SPI_I2SCFGR_I2SSTD_1) /*!< PCM standard, short frame synchronization */ -#define LL_I2S_STANDARD_PCM_LONG (SPI_I2SCFGR_I2SSTD_0 | SPI_I2SCFGR_I2SSTD_1 | SPI_I2SCFGR_PCMSYNC) /*!< PCM standard, long frame synchronization */ -/** - * @} - */ - -/** @defgroup I2S_LL_EC_MODE Operation Mode - * @{ - */ -#define LL_I2S_MODE_SLAVE_TX 0x00000000U /*!< Slave Tx configuration */ -#define LL_I2S_MODE_SLAVE_RX (SPI_I2SCFGR_I2SCFG_0) /*!< Slave Rx configuration */ -#define LL_I2S_MODE_MASTER_TX (SPI_I2SCFGR_I2SCFG_1) /*!< Master Tx configuration */ -#define LL_I2S_MODE_MASTER_RX (SPI_I2SCFGR_I2SCFG_0 | SPI_I2SCFGR_I2SCFG_1) /*!< Master Rx configuration */ -/** - * @} - */ - -/** @defgroup I2S_LL_EC_PRESCALER_FACTOR Prescaler Factor - * @{ - */ -#define LL_I2S_PRESCALER_PARITY_EVEN 0x00000000U /*!< Odd factor: Real divider value is = I2SDIV * 2 */ -#define LL_I2S_PRESCALER_PARITY_ODD (SPI_I2SPR_ODD >> 8U) /*!< Odd factor: Real divider value is = (I2SDIV * 2)+1 */ -/** - * @} - */ - -#if defined(USE_FULL_LL_DRIVER) - -/** @defgroup I2S_LL_EC_MCLK_OUTPUT MCLK Output - * @{ - */ -#define LL_I2S_MCLK_OUTPUT_DISABLE 0x00000000U /*!< Master clock output is disabled */ -#define LL_I2S_MCLK_OUTPUT_ENABLE (SPI_I2SPR_MCKOE) /*!< Master clock output is enabled */ -/** - * @} - */ - -/** @defgroup I2S_LL_EC_AUDIO_FREQ Audio Frequency - * @{ - */ - -#define LL_I2S_AUDIOFREQ_192K 192000U /*!< Audio Frequency configuration 192000 Hz */ -#define LL_I2S_AUDIOFREQ_96K 96000U /*!< Audio Frequency configuration 96000 Hz */ -#define LL_I2S_AUDIOFREQ_48K 48000U /*!< Audio Frequency configuration 48000 Hz */ -#define LL_I2S_AUDIOFREQ_44K 44100U /*!< Audio Frequency configuration 44100 Hz */ -#define LL_I2S_AUDIOFREQ_32K 32000U /*!< Audio Frequency configuration 32000 Hz */ -#define LL_I2S_AUDIOFREQ_22K 22050U /*!< Audio Frequency configuration 22050 Hz */ -#define LL_I2S_AUDIOFREQ_16K 16000U /*!< Audio Frequency configuration 16000 Hz */ -#define LL_I2S_AUDIOFREQ_11K 11025U /*!< Audio Frequency configuration 11025 Hz */ -#define LL_I2S_AUDIOFREQ_8K 8000U /*!< Audio Frequency configuration 8000 Hz */ -#define LL_I2S_AUDIOFREQ_DEFAULT 2U /*!< Audio Freq not specified. Register I2SDIV = 2 */ -/** - * @} - */ -#endif /* USE_FULL_LL_DRIVER */ - -/** - * @} - */ - -/* Exported macro ------------------------------------------------------------*/ -/** @defgroup I2S_LL_Exported_Macros I2S Exported Macros - * @{ - */ - -/** @defgroup I2S_LL_EM_WRITE_READ Common Write and read registers Macros - * @{ - */ - -/** - * @brief Write a value in I2S register - * @param __INSTANCE__ I2S Instance - * @param __REG__ Register to be written - * @param __VALUE__ Value to be written in the register - * @retval None - */ -#define LL_I2S_WriteReg(__INSTANCE__, __REG__, __VALUE__) WRITE_REG(__INSTANCE__->__REG__, (__VALUE__)) - -/** - * @brief Read a value in I2S register - * @param __INSTANCE__ I2S Instance - * @param __REG__ Register to be read - * @retval Register value - */ -#define LL_I2S_ReadReg(__INSTANCE__, __REG__) READ_REG(__INSTANCE__->__REG__) -/** - * @} - */ - -/** - * @} - */ - - -/* Exported functions --------------------------------------------------------*/ - -/** @defgroup I2S_LL_Exported_Functions I2S Exported Functions - * @{ - */ - -/** @defgroup I2S_LL_EF_Configuration Configuration - * @{ - */ - -/** - * @brief Select I2S mode and Enable I2S peripheral - * @rmtoll I2SCFGR I2SMOD LL_I2S_Enable\n - * I2SCFGR I2SE LL_I2S_Enable - * @param SPIx SPI Instance - * @retval None - */ -__STATIC_INLINE void LL_I2S_Enable(SPI_TypeDef *SPIx) -{ - SET_BIT(SPIx->I2SCFGR, SPI_I2SCFGR_I2SMOD | SPI_I2SCFGR_I2SE); -} - -/** - * @brief Disable I2S peripheral - * @rmtoll I2SCFGR I2SE LL_I2S_Disable - * @param SPIx SPI Instance - * @retval None - */ -__STATIC_INLINE void LL_I2S_Disable(SPI_TypeDef *SPIx) -{ - CLEAR_BIT(SPIx->I2SCFGR, SPI_I2SCFGR_I2SMOD | SPI_I2SCFGR_I2SE); -} - -/** - * @brief Check if I2S peripheral is enabled - * @rmtoll I2SCFGR I2SE LL_I2S_IsEnabled - * @param SPIx SPI Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_I2S_IsEnabled(SPI_TypeDef *SPIx) -{ - return (READ_BIT(SPIx->I2SCFGR, SPI_I2SCFGR_I2SE) == (SPI_I2SCFGR_I2SE)); -} - -/** - * @brief Set I2S data frame length - * @rmtoll I2SCFGR DATLEN LL_I2S_SetDataFormat\n - * I2SCFGR CHLEN LL_I2S_SetDataFormat - * @param SPIx SPI Instance - * @param DataFormat This parameter can be one of the following values: - * @arg @ref LL_I2S_DATAFORMAT_16B - * @arg @ref LL_I2S_DATAFORMAT_16B_EXTENDED - * @arg @ref LL_I2S_DATAFORMAT_24B - * @arg @ref LL_I2S_DATAFORMAT_32B - * @retval None - */ -__STATIC_INLINE void LL_I2S_SetDataFormat(SPI_TypeDef *SPIx, uint32_t DataFormat) -{ - MODIFY_REG(SPIx->I2SCFGR, SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN, DataFormat); -} - -/** - * @brief Get I2S data frame length - * @rmtoll I2SCFGR DATLEN LL_I2S_GetDataFormat\n - * I2SCFGR CHLEN LL_I2S_GetDataFormat - * @param SPIx SPI Instance - * @retval Returned value can be one of the following values: - * @arg @ref LL_I2S_DATAFORMAT_16B - * @arg @ref LL_I2S_DATAFORMAT_16B_EXTENDED - * @arg @ref LL_I2S_DATAFORMAT_24B - * @arg @ref LL_I2S_DATAFORMAT_32B - */ -__STATIC_INLINE uint32_t LL_I2S_GetDataFormat(SPI_TypeDef *SPIx) -{ - return (uint32_t)(READ_BIT(SPIx->I2SCFGR, SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN)); -} - -/** - * @brief Set I2S clock polarity - * @rmtoll I2SCFGR CKPOL LL_I2S_SetClockPolarity - * @param SPIx SPI Instance - * @param ClockPolarity This parameter can be one of the following values: - * @arg @ref LL_I2S_POLARITY_LOW - * @arg @ref LL_I2S_POLARITY_HIGH - * @retval None - */ -__STATIC_INLINE void LL_I2S_SetClockPolarity(SPI_TypeDef *SPIx, uint32_t ClockPolarity) -{ - SET_BIT(SPIx->I2SCFGR, ClockPolarity); -} - -/** - * @brief Get I2S clock polarity - * @rmtoll I2SCFGR CKPOL LL_I2S_GetClockPolarity - * @param SPIx SPI Instance - * @retval Returned value can be one of the following values: - * @arg @ref LL_I2S_POLARITY_LOW - * @arg @ref LL_I2S_POLARITY_HIGH - */ -__STATIC_INLINE uint32_t LL_I2S_GetClockPolarity(SPI_TypeDef *SPIx) -{ - return (uint32_t)(READ_BIT(SPIx->I2SCFGR, SPI_I2SCFGR_CKPOL)); -} - -/** - * @brief Set I2S standard protocol - * @rmtoll I2SCFGR I2SSTD LL_I2S_SetStandard\n - * I2SCFGR PCMSYNC LL_I2S_SetStandard - * @param SPIx SPI Instance - * @param Standard This parameter can be one of the following values: - * @arg @ref LL_I2S_STANDARD_PHILIPS - * @arg @ref LL_I2S_STANDARD_MSB - * @arg @ref LL_I2S_STANDARD_LSB - * @arg @ref LL_I2S_STANDARD_PCM_SHORT - * @arg @ref LL_I2S_STANDARD_PCM_LONG - * @retval None - */ -__STATIC_INLINE void LL_I2S_SetStandard(SPI_TypeDef *SPIx, uint32_t Standard) -{ - MODIFY_REG(SPIx->I2SCFGR, SPI_I2SCFGR_I2SSTD | SPI_I2SCFGR_PCMSYNC, Standard); -} - -/** - * @brief Get I2S standard protocol - * @rmtoll I2SCFGR I2SSTD LL_I2S_GetStandard\n - * I2SCFGR PCMSYNC LL_I2S_GetStandard - * @param SPIx SPI Instance - * @retval Returned value can be one of the following values: - * @arg @ref LL_I2S_STANDARD_PHILIPS - * @arg @ref LL_I2S_STANDARD_MSB - * @arg @ref LL_I2S_STANDARD_LSB - * @arg @ref LL_I2S_STANDARD_PCM_SHORT - * @arg @ref LL_I2S_STANDARD_PCM_LONG - */ -__STATIC_INLINE uint32_t LL_I2S_GetStandard(SPI_TypeDef *SPIx) -{ - return (uint32_t)(READ_BIT(SPIx->I2SCFGR, SPI_I2SCFGR_I2SSTD | SPI_I2SCFGR_PCMSYNC)); -} - -/** - * @brief Set I2S transfer mode - * @rmtoll I2SCFGR I2SCFG LL_I2S_SetTransferMode - * @param SPIx SPI Instance - * @param Mode This parameter can be one of the following values: - * @arg @ref LL_I2S_MODE_SLAVE_TX - * @arg @ref LL_I2S_MODE_SLAVE_RX - * @arg @ref LL_I2S_MODE_MASTER_TX - * @arg @ref LL_I2S_MODE_MASTER_RX - * @retval None - */ -__STATIC_INLINE void LL_I2S_SetTransferMode(SPI_TypeDef *SPIx, uint32_t Mode) -{ - MODIFY_REG(SPIx->I2SCFGR, SPI_I2SCFGR_I2SCFG, Mode); -} - -/** - * @brief Get I2S transfer mode - * @rmtoll I2SCFGR I2SCFG LL_I2S_GetTransferMode - * @param SPIx SPI Instance - * @retval Returned value can be one of the following values: - * @arg @ref LL_I2S_MODE_SLAVE_TX - * @arg @ref LL_I2S_MODE_SLAVE_RX - * @arg @ref LL_I2S_MODE_MASTER_TX - * @arg @ref LL_I2S_MODE_MASTER_RX - */ -__STATIC_INLINE uint32_t LL_I2S_GetTransferMode(SPI_TypeDef *SPIx) -{ - return (uint32_t)(READ_BIT(SPIx->I2SCFGR, SPI_I2SCFGR_I2SCFG)); -} - -/** - * @brief Set I2S linear prescaler - * @rmtoll I2SPR I2SDIV LL_I2S_SetPrescalerLinear - * @param SPIx SPI Instance - * @param PrescalerLinear Value between Min_Data=0x02 and Max_Data=0xFF - * @retval None - */ -__STATIC_INLINE void LL_I2S_SetPrescalerLinear(SPI_TypeDef *SPIx, uint8_t PrescalerLinear) -{ - MODIFY_REG(SPIx->I2SPR, SPI_I2SPR_I2SDIV, PrescalerLinear); -} - -/** - * @brief Get I2S linear prescaler - * @rmtoll I2SPR I2SDIV LL_I2S_GetPrescalerLinear - * @param SPIx SPI Instance - * @retval PrescalerLinear Value between Min_Data=0x02 and Max_Data=0xFF - */ -__STATIC_INLINE uint32_t LL_I2S_GetPrescalerLinear(SPI_TypeDef *SPIx) -{ - return (uint32_t)(READ_BIT(SPIx->I2SPR, SPI_I2SPR_I2SDIV)); -} - -/** - * @brief Set I2S parity prescaler - * @rmtoll I2SPR ODD LL_I2S_SetPrescalerParity - * @param SPIx SPI Instance - * @param PrescalerParity This parameter can be one of the following values: - * @arg @ref LL_I2S_PRESCALER_PARITY_EVEN - * @arg @ref LL_I2S_PRESCALER_PARITY_ODD - * @retval None - */ -__STATIC_INLINE void LL_I2S_SetPrescalerParity(SPI_TypeDef *SPIx, uint32_t PrescalerParity) -{ - MODIFY_REG(SPIx->I2SPR, SPI_I2SPR_ODD, PrescalerParity << 8U); -} - -/** - * @brief Get I2S parity prescaler - * @rmtoll I2SPR ODD LL_I2S_GetPrescalerParity - * @param SPIx SPI Instance - * @retval Returned value can be one of the following values: - * @arg @ref LL_I2S_PRESCALER_PARITY_EVEN - * @arg @ref LL_I2S_PRESCALER_PARITY_ODD - */ -__STATIC_INLINE uint32_t LL_I2S_GetPrescalerParity(SPI_TypeDef *SPIx) -{ - return (uint32_t)(READ_BIT(SPIx->I2SPR, SPI_I2SPR_ODD) >> 8U); -} - -/** - * @brief Enable the master clock ouput (Pin MCK) - * @rmtoll I2SPR MCKOE LL_I2S_EnableMasterClock - * @param SPIx SPI Instance - * @retval None - */ -__STATIC_INLINE void LL_I2S_EnableMasterClock(SPI_TypeDef *SPIx) -{ - SET_BIT(SPIx->I2SPR, SPI_I2SPR_MCKOE); -} - -/** - * @brief Disable the master clock ouput (Pin MCK) - * @rmtoll I2SPR MCKOE LL_I2S_DisableMasterClock - * @param SPIx SPI Instance - * @retval None - */ -__STATIC_INLINE void LL_I2S_DisableMasterClock(SPI_TypeDef *SPIx) -{ - CLEAR_BIT(SPIx->I2SPR, SPI_I2SPR_MCKOE); -} - -/** - * @brief Check if the master clock ouput (Pin MCK) is enabled - * @rmtoll I2SPR MCKOE LL_I2S_IsEnabledMasterClock - * @param SPIx SPI Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_I2S_IsEnabledMasterClock(SPI_TypeDef *SPIx) -{ - return (READ_BIT(SPIx->I2SPR, SPI_I2SPR_MCKOE) == (SPI_I2SPR_MCKOE)); -} - -/** - * @} - */ - -/** @defgroup I2S_LL_EF_FLAG FLAG Management - * @{ - */ - -/** - * @brief Check if Rx buffer is not empty - * @rmtoll SR RXNE LL_I2S_IsActiveFlag_RXNE - * @param SPIx SPI Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_RXNE(SPI_TypeDef *SPIx) -{ - return LL_SPI_IsActiveFlag_RXNE(SPIx); -} - -/** - * @brief Check if Tx buffer is empty - * @rmtoll SR TXE LL_I2S_IsActiveFlag_TXE - * @param SPIx SPI Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_TXE(SPI_TypeDef *SPIx) -{ - return LL_SPI_IsActiveFlag_TXE(SPIx); -} - -/** - * @brief Get busy flag - * @rmtoll SR BSY LL_I2S_IsActiveFlag_BSY - * @param SPIx SPI Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_BSY(SPI_TypeDef *SPIx) -{ - return LL_SPI_IsActiveFlag_BSY(SPIx); -} - -/** - * @brief Get overrun error flag - * @rmtoll SR OVR LL_I2S_IsActiveFlag_OVR - * @param SPIx SPI Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_OVR(SPI_TypeDef *SPIx) -{ - return LL_SPI_IsActiveFlag_OVR(SPIx); -} - -/** - * @brief Get underrun error flag - * @rmtoll SR UDR LL_I2S_IsActiveFlag_UDR - * @param SPIx SPI Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_UDR(SPI_TypeDef *SPIx) -{ - return (READ_BIT(SPIx->SR, SPI_SR_UDR) == (SPI_SR_UDR)); -} - -/** - * @brief Get channel side flag. - * @note 0: Channel Left has to be transmitted or has been received\n - * 1: Channel Right has to be transmitted or has been received\n - * It has no significance in PCM mode. - * @rmtoll SR CHSIDE LL_I2S_IsActiveFlag_CHSIDE - * @param SPIx SPI Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_I2S_IsActiveFlag_CHSIDE(SPI_TypeDef *SPIx) -{ - return (READ_BIT(SPIx->SR, SPI_SR_CHSIDE) == (SPI_SR_CHSIDE)); -} - -/** - * @brief Clear overrun error flag - * @rmtoll SR OVR LL_I2S_ClearFlag_OVR - * @param SPIx SPI Instance - * @retval None - */ -__STATIC_INLINE void LL_I2S_ClearFlag_OVR(SPI_TypeDef *SPIx) -{ - LL_SPI_ClearFlag_OVR(SPIx); -} - -/** - * @brief Clear underrun error flag - * @rmtoll SR UDR LL_I2S_ClearFlag_UDR - * @param SPIx SPI Instance - * @retval None - */ -__STATIC_INLINE void LL_I2S_ClearFlag_UDR(SPI_TypeDef *SPIx) -{ - __IO uint32_t tmpreg; - tmpreg = SPIx->SR; - (void)tmpreg; -} - -/** - * @} - */ - -/** @defgroup I2S_LL_EF_IT Interrupt Management - * @{ - */ - -/** - * @brief Enable error IT - * @note This bit controls the generation of an interrupt when an error condition occurs (OVR, UDR and FRE in I2S mode). - * @rmtoll CR2 ERRIE LL_I2S_EnableIT_ERR - * @param SPIx SPI Instance - * @retval None - */ -__STATIC_INLINE void LL_I2S_EnableIT_ERR(SPI_TypeDef *SPIx) -{ - LL_SPI_EnableIT_ERR(SPIx); -} - -/** - * @brief Enable Rx buffer not empty IT - * @rmtoll CR2 RXNEIE LL_I2S_EnableIT_RXNE - * @param SPIx SPI Instance - * @retval None - */ -__STATIC_INLINE void LL_I2S_EnableIT_RXNE(SPI_TypeDef *SPIx) -{ - LL_SPI_EnableIT_RXNE(SPIx); -} - -/** - * @brief Enable Tx buffer empty IT - * @rmtoll CR2 TXEIE LL_I2S_EnableIT_TXE - * @param SPIx SPI Instance - * @retval None - */ -__STATIC_INLINE void LL_I2S_EnableIT_TXE(SPI_TypeDef *SPIx) -{ - LL_SPI_EnableIT_TXE(SPIx); -} - -/** - * @brief Disable error IT - * @note This bit controls the generation of an interrupt when an error condition occurs (OVR, UDR and FRE in I2S mode). - * @rmtoll CR2 ERRIE LL_I2S_DisableIT_ERR - * @param SPIx SPI Instance - * @retval None - */ -__STATIC_INLINE void LL_I2S_DisableIT_ERR(SPI_TypeDef *SPIx) -{ - LL_SPI_DisableIT_ERR(SPIx); -} - -/** - * @brief Disable Rx buffer not empty IT - * @rmtoll CR2 RXNEIE LL_I2S_DisableIT_RXNE - * @param SPIx SPI Instance - * @retval None - */ -__STATIC_INLINE void LL_I2S_DisableIT_RXNE(SPI_TypeDef *SPIx) -{ - LL_SPI_DisableIT_RXNE(SPIx); -} - -/** - * @brief Disable Tx buffer empty IT - * @rmtoll CR2 TXEIE LL_I2S_DisableIT_TXE - * @param SPIx SPI Instance - * @retval None - */ -__STATIC_INLINE void LL_I2S_DisableIT_TXE(SPI_TypeDef *SPIx) -{ - LL_SPI_DisableIT_TXE(SPIx); -} - -/** - * @brief Check if ERR IT is enabled - * @rmtoll CR2 ERRIE LL_I2S_IsEnabledIT_ERR - * @param SPIx SPI Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_I2S_IsEnabledIT_ERR(SPI_TypeDef *SPIx) -{ - return LL_SPI_IsEnabledIT_ERR(SPIx); -} - -/** - * @brief Check if RXNE IT is enabled - * @rmtoll CR2 RXNEIE LL_I2S_IsEnabledIT_RXNE - * @param SPIx SPI Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_I2S_IsEnabledIT_RXNE(SPI_TypeDef *SPIx) -{ - return LL_SPI_IsEnabledIT_RXNE(SPIx); -} - -/** - * @brief Check if TXE IT is enabled - * @rmtoll CR2 TXEIE LL_I2S_IsEnabledIT_TXE - * @param SPIx SPI Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_I2S_IsEnabledIT_TXE(SPI_TypeDef *SPIx) -{ - return LL_SPI_IsEnabledIT_TXE(SPIx); -} - -/** - * @} - */ - -/** @defgroup I2S_LL_EF_DMA DMA Management - * @{ - */ - -/** - * @brief Enable DMA Rx - * @rmtoll CR2 RXDMAEN LL_I2S_EnableDMAReq_RX - * @param SPIx SPI Instance - * @retval None - */ -__STATIC_INLINE void LL_I2S_EnableDMAReq_RX(SPI_TypeDef *SPIx) -{ - LL_SPI_EnableDMAReq_RX(SPIx); -} - -/** - * @brief Disable DMA Rx - * @rmtoll CR2 RXDMAEN LL_I2S_DisableDMAReq_RX - * @param SPIx SPI Instance - * @retval None - */ -__STATIC_INLINE void LL_I2S_DisableDMAReq_RX(SPI_TypeDef *SPIx) -{ - LL_SPI_DisableDMAReq_RX(SPIx); -} - -/** - * @brief Check if DMA Rx is enabled - * @rmtoll CR2 RXDMAEN LL_I2S_IsEnabledDMAReq_RX - * @param SPIx SPI Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_I2S_IsEnabledDMAReq_RX(SPI_TypeDef *SPIx) -{ - return LL_SPI_IsEnabledDMAReq_RX(SPIx); -} - -/** - * @brief Enable DMA Tx - * @rmtoll CR2 TXDMAEN LL_I2S_EnableDMAReq_TX - * @param SPIx SPI Instance - * @retval None - */ -__STATIC_INLINE void LL_I2S_EnableDMAReq_TX(SPI_TypeDef *SPIx) -{ - LL_SPI_EnableDMAReq_TX(SPIx); -} - -/** - * @brief Disable DMA Tx - * @rmtoll CR2 TXDMAEN LL_I2S_DisableDMAReq_TX - * @param SPIx SPI Instance - * @retval None - */ -__STATIC_INLINE void LL_I2S_DisableDMAReq_TX(SPI_TypeDef *SPIx) -{ - LL_SPI_DisableDMAReq_TX(SPIx); -} - -/** - * @brief Check if DMA Tx is enabled - * @rmtoll CR2 TXDMAEN LL_I2S_IsEnabledDMAReq_TX - * @param SPIx SPI Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_I2S_IsEnabledDMAReq_TX(SPI_TypeDef *SPIx) -{ - return LL_SPI_IsEnabledDMAReq_TX(SPIx); -} - -/** - * @} - */ - -/** @defgroup I2S_LL_EF_DATA DATA Management - * @{ - */ - -/** - * @brief Read 16-Bits in data register - * @rmtoll DR DR LL_I2S_ReceiveData16 - * @param SPIx SPI Instance - * @retval RxData Value between Min_Data=0x0000 and Max_Data=0xFFFF - */ -__STATIC_INLINE uint16_t LL_I2S_ReceiveData16(SPI_TypeDef *SPIx) -{ - return LL_SPI_ReceiveData16(SPIx); -} - -/** - * @brief Write 16-Bits in data register - * @rmtoll DR DR LL_I2S_TransmitData16 - * @param SPIx SPI Instance - * @param TxData Value between Min_Data=0x0000 and Max_Data=0xFFFF - * @retval None - */ -__STATIC_INLINE void LL_I2S_TransmitData16(SPI_TypeDef *SPIx, uint16_t TxData) -{ - LL_SPI_TransmitData16(SPIx, TxData); -} - -/** - * @} - */ - -#if defined(USE_FULL_LL_DRIVER) -/** @defgroup I2S_LL_EF_Init Initialization and de-initialization functions - * @{ - */ - -ErrorStatus LL_I2S_DeInit(SPI_TypeDef *SPIx); -ErrorStatus LL_I2S_Init(SPI_TypeDef *SPIx, LL_I2S_InitTypeDef *I2S_InitStruct); -void LL_I2S_StructInit(LL_I2S_InitTypeDef *I2S_InitStruct); -void LL_I2S_ConfigPrescaler(SPI_TypeDef *SPIx, uint32_t PrescalerLinear, uint32_t PrescalerParity); - -/** - * @} - */ -#endif /* USE_FULL_LL_DRIVER */ - -/** - * @} - */ - -/** - * @} - */ -#endif /* SPI_I2S_SUPPORT */ - -#endif /* defined (SPI1) || defined (SPI2) || defined (SPI3) */ - -/** - * @} - */ - -#ifdef __cplusplus -} -#endif - -#endif /* __STM32F1xx_LL_SPI_H */ - -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_system.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_system.h index 7f204c23f4b..3f86e375bc0 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_system.h +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_system.h @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_ll_system.h * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version $VERSION$ + * @date $DATE$ * @brief Header file of SYSTEM LL module. @verbatim ============================================================================== @@ -76,6 +76,9 @@ extern "C" { * @{ */ +/* Defines used for position in the register */ +#define DBGMCU_REVID_POSITION (uint32_t)POSITION_VAL(DBGMCU_IDCODE_REV_ID) + /** * @} */ @@ -93,7 +96,7 @@ extern "C" { /** @defgroup SYSTEM_LL_EC_TRACE DBGMCU TRACE Pin Assignment * @{ */ -#define LL_DBGMCU_TRACE_NONE 0x00000000U /*!< TRACE pins not assigned (default state) */ +#define LL_DBGMCU_TRACE_NONE (uint32_t)0x00000000U /*!< TRACE pins not assigned (default state) */ #define LL_DBGMCU_TRACE_ASYNCH DBGMCU_CR_TRACE_IOEN /*!< TRACE pin assignment for Asynchronous Mode */ #define LL_DBGMCU_TRACE_SYNCH_SIZE1 (DBGMCU_CR_TRACE_IOEN | DBGMCU_CR_TRACE_MODE_0) /*!< TRACE pin assignment for Synchronous Mode with a TRACEDATA size of 1 */ #define LL_DBGMCU_TRACE_SYNCH_SIZE2 (DBGMCU_CR_TRACE_IOEN | DBGMCU_CR_TRACE_MODE_1) /*!< TRACE pin assignment for Synchronous Mode with a TRACEDATA size of 2 */ @@ -174,7 +177,7 @@ extern "C" { * @{ */ #if defined(FLASH_ACR_LATENCY) -#define LL_FLASH_LATENCY_0 0x00000000U /*!< FLASH Zero Latency cycle */ +#define LL_FLASH_LATENCY_0 ((uint32_t)0x00000000U) /*!< FLASH Zero Latency cycle */ #define LL_FLASH_LATENCY_1 FLASH_ACR_LATENCY_0 /*!< FLASH One Latency cycle */ #define LL_FLASH_LATENCY_2 FLASH_ACR_LATENCY_1 /*!< FLASH Two wait states */ #else @@ -228,7 +231,7 @@ __STATIC_INLINE uint32_t LL_DBGMCU_GetDeviceID(void) */ __STATIC_INLINE uint32_t LL_DBGMCU_GetRevisionID(void) { - return (uint32_t)(READ_BIT(DBGMCU->IDCODE, DBGMCU_IDCODE_REV_ID) >> DBGMCU_IDCODE_REV_ID_Pos); + return (uint32_t)(READ_BIT(DBGMCU->IDCODE, DBGMCU_IDCODE_REV_ID) >> DBGMCU_REVID_POSITION); } /** diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_tim.c b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_tim.c deleted file mode 100644 index ef5edc88885..00000000000 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_tim.c +++ /dev/null @@ -1,1216 +0,0 @@ -/** - ****************************************************************************** - * @file stm32f1xx_ll_tim.c - * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 - * @brief TIM LL module driver. - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2016 STMicroelectronics

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ -#if defined(USE_FULL_LL_DRIVER) - -/* Includes ------------------------------------------------------------------*/ -#include "stm32f1xx_ll_tim.h" -#include "stm32f1xx_ll_bus.h" - -#ifdef USE_FULL_ASSERT -#include "stm32_assert.h" -#else -#define assert_param(expr) ((void)0U) -#endif - -/** @addtogroup STM32F1xx_LL_Driver - * @{ - */ - -#if defined (TIM1) || defined (TIM2) || defined (TIM3) || defined (TIM4) || defined (TIM5) || defined (TIM6) || defined (TIM7) || defined (TIM8) || defined (TIM9) || defined (TIM10) || defined (TIM11) || defined (TIM12) || defined (TIM13) || defined (TIM14) || defined (TIM15) || defined (TIM16) || defined (TIM17) - -/** @addtogroup TIM_LL - * @{ - */ - -/* Private types -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private constants ---------------------------------------------------------*/ -/* Private macros ------------------------------------------------------------*/ -/** @addtogroup TIM_LL_Private_Macros - * @{ - */ -#define IS_LL_TIM_COUNTERMODE(__VALUE__) (((__VALUE__) == LL_TIM_COUNTERMODE_UP) \ - || ((__VALUE__) == LL_TIM_COUNTERMODE_DOWN) \ - || ((__VALUE__) == LL_TIM_COUNTERMODE_CENTER_UP) \ - || ((__VALUE__) == LL_TIM_COUNTERMODE_CENTER_DOWN) \ - || ((__VALUE__) == LL_TIM_COUNTERMODE_CENTER_UP_DOWN)) - -#define IS_LL_TIM_CLOCKDIVISION(__VALUE__) (((__VALUE__) == LL_TIM_CLOCKDIVISION_DIV1) \ - || ((__VALUE__) == LL_TIM_CLOCKDIVISION_DIV2) \ - || ((__VALUE__) == LL_TIM_CLOCKDIVISION_DIV4)) - -#define IS_LL_TIM_OCMODE(__VALUE__) (((__VALUE__) == LL_TIM_OCMODE_FROZEN) \ - || ((__VALUE__) == LL_TIM_OCMODE_ACTIVE) \ - || ((__VALUE__) == LL_TIM_OCMODE_INACTIVE) \ - || ((__VALUE__) == LL_TIM_OCMODE_TOGGLE) \ - || ((__VALUE__) == LL_TIM_OCMODE_FORCED_INACTIVE) \ - || ((__VALUE__) == LL_TIM_OCMODE_FORCED_ACTIVE) \ - || ((__VALUE__) == LL_TIM_OCMODE_PWM1) \ - || ((__VALUE__) == LL_TIM_OCMODE_PWM2)) - -#define IS_LL_TIM_OCSTATE(__VALUE__) (((__VALUE__) == LL_TIM_OCSTATE_DISABLE) \ - || ((__VALUE__) == LL_TIM_OCSTATE_ENABLE)) - -#define IS_LL_TIM_OCPOLARITY(__VALUE__) (((__VALUE__) == LL_TIM_OCPOLARITY_HIGH) \ - || ((__VALUE__) == LL_TIM_OCPOLARITY_LOW)) - -#define IS_LL_TIM_OCIDLESTATE(__VALUE__) (((__VALUE__) == LL_TIM_OCIDLESTATE_LOW) \ - || ((__VALUE__) == LL_TIM_OCIDLESTATE_HIGH)) - -#define IS_LL_TIM_ACTIVEINPUT(__VALUE__) (((__VALUE__) == LL_TIM_ACTIVEINPUT_DIRECTTI) \ - || ((__VALUE__) == LL_TIM_ACTIVEINPUT_INDIRECTTI) \ - || ((__VALUE__) == LL_TIM_ACTIVEINPUT_TRC)) - -#define IS_LL_TIM_ICPSC(__VALUE__) (((__VALUE__) == LL_TIM_ICPSC_DIV1) \ - || ((__VALUE__) == LL_TIM_ICPSC_DIV2) \ - || ((__VALUE__) == LL_TIM_ICPSC_DIV4) \ - || ((__VALUE__) == LL_TIM_ICPSC_DIV8)) - -#define IS_LL_TIM_IC_FILTER(__VALUE__) (((__VALUE__) == LL_TIM_IC_FILTER_FDIV1) \ - || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV1_N2) \ - || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV1_N4) \ - || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV1_N8) \ - || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV2_N6) \ - || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV2_N8) \ - || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV4_N6) \ - || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV4_N8) \ - || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV8_N6) \ - || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV8_N8) \ - || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV16_N5) \ - || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV16_N6) \ - || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV16_N8) \ - || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV32_N5) \ - || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV32_N6) \ - || ((__VALUE__) == LL_TIM_IC_FILTER_FDIV32_N8)) - -#define IS_LL_TIM_IC_POLARITY(__VALUE__) (((__VALUE__) == LL_TIM_IC_POLARITY_RISING) \ - || ((__VALUE__) == LL_TIM_IC_POLARITY_FALLING)) - -#define IS_LL_TIM_ENCODERMODE(__VALUE__) (((__VALUE__) == LL_TIM_ENCODERMODE_X2_TI1) \ - || ((__VALUE__) == LL_TIM_ENCODERMODE_X2_TI2) \ - || ((__VALUE__) == LL_TIM_ENCODERMODE_X4_TI12)) - -#define IS_LL_TIM_IC_POLARITY_ENCODER(__VALUE__) (((__VALUE__) == LL_TIM_IC_POLARITY_RISING) \ - || ((__VALUE__) == LL_TIM_IC_POLARITY_FALLING)) - -#define IS_LL_TIM_OSSR_STATE(__VALUE__) (((__VALUE__) == LL_TIM_OSSR_DISABLE) \ - || ((__VALUE__) == LL_TIM_OSSR_ENABLE)) - -#define IS_LL_TIM_OSSI_STATE(__VALUE__) (((__VALUE__) == LL_TIM_OSSI_DISABLE) \ - || ((__VALUE__) == LL_TIM_OSSI_ENABLE)) - -#define IS_LL_TIM_LOCK_LEVEL(__VALUE__) (((__VALUE__) == LL_TIM_LOCKLEVEL_OFF) \ - || ((__VALUE__) == LL_TIM_LOCKLEVEL_1) \ - || ((__VALUE__) == LL_TIM_LOCKLEVEL_2) \ - || ((__VALUE__) == LL_TIM_LOCKLEVEL_3)) - -#define IS_LL_TIM_BREAK_STATE(__VALUE__) (((__VALUE__) == LL_TIM_BREAK_DISABLE) \ - || ((__VALUE__) == LL_TIM_BREAK_ENABLE)) - -#define IS_LL_TIM_BREAK_POLARITY(__VALUE__) (((__VALUE__) == LL_TIM_BREAK_POLARITY_LOW) \ - || ((__VALUE__) == LL_TIM_BREAK_POLARITY_HIGH)) - -#define IS_LL_TIM_AUTOMATIC_OUTPUT_STATE(__VALUE__) (((__VALUE__) == LL_TIM_AUTOMATICOUTPUT_DISABLE) \ - || ((__VALUE__) == LL_TIM_AUTOMATICOUTPUT_ENABLE)) -/** - * @} - */ - - -/* Private function prototypes -----------------------------------------------*/ -/** @defgroup TIM_LL_Private_Functions TIM Private Functions - * @{ - */ -static ErrorStatus OC1Config(TIM_TypeDef *TIMx, LL_TIM_OC_InitTypeDef *TIM_OCInitStruct); -static ErrorStatus OC2Config(TIM_TypeDef *TIMx, LL_TIM_OC_InitTypeDef *TIM_OCInitStruct); -static ErrorStatus OC3Config(TIM_TypeDef *TIMx, LL_TIM_OC_InitTypeDef *TIM_OCInitStruct); -static ErrorStatus OC4Config(TIM_TypeDef *TIMx, LL_TIM_OC_InitTypeDef *TIM_OCInitStruct); -static ErrorStatus IC1Config(TIM_TypeDef *TIMx, LL_TIM_IC_InitTypeDef *TIM_ICInitStruct); -static ErrorStatus IC2Config(TIM_TypeDef *TIMx, LL_TIM_IC_InitTypeDef *TIM_ICInitStruct); -static ErrorStatus IC3Config(TIM_TypeDef *TIMx, LL_TIM_IC_InitTypeDef *TIM_ICInitStruct); -static ErrorStatus IC4Config(TIM_TypeDef *TIMx, LL_TIM_IC_InitTypeDef *TIM_ICInitStruct); -/** - * @} - */ - -/* Exported functions --------------------------------------------------------*/ -/** @addtogroup TIM_LL_Exported_Functions - * @{ - */ - -/** @addtogroup TIM_LL_EF_Init - * @{ - */ - -/** - * @brief Set TIMx registers to their reset values. - * @param TIMx Timer instance - * @retval An ErrorStatus enumeration value: - * - SUCCESS: TIMx registers are de-initialized - * - ERROR: invalid TIMx instance - */ -ErrorStatus LL_TIM_DeInit(TIM_TypeDef *TIMx) -{ - ErrorStatus result = SUCCESS; - - /* Check the parameters */ - assert_param(IS_TIM_INSTANCE(TIMx)); - - if (TIMx == TIM2) - { - LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_TIM2); - LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_TIM2); - } -#if defined(TIM1) - else if (TIMx == TIM1) - { - LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_TIM1); - LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_TIM1); - } -#endif -#if defined(TIM3) - else if (TIMx == TIM3) - { - LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_TIM3); - LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_TIM3); - } -#endif -#if defined(TIM4) - else if (TIMx == TIM4) - { - LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_TIM4); - LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_TIM4); - } -#endif -#if defined(TIM5) - else if (TIMx == TIM5) - { - LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_TIM5); - LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_TIM5); - } -#endif -#if defined(TIM6) - else if (TIMx == TIM6) - { - LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_TIM6); - LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_TIM6); - } -#endif -#if defined (TIM7) - else if (TIMx == TIM7) - { - LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_TIM7); - LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_TIM7); - } -#endif -#if defined(TIM8) - else if (TIMx == TIM8) - { - LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_TIM8); - LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_TIM8); - } -#endif -#if defined(TIM9) - else if (TIMx == TIM9) - { - LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_TIM9); - LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_TIM9); - } -#endif -#if defined(TIM10) - else if (TIMx == TIM10) - { - LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_TIM10); - LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_TIM10); - } -#endif -#if defined(TIM11) - else if (TIMx == TIM11) - { - LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_TIM11); - LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_TIM11); - } -#endif -#if defined(TIM12) - else if (TIMx == TIM12) - { - LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_TIM12); - LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_TIM12); - } -#endif -#if defined(TIM13) - else if (TIMx == TIM13) - { - LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_TIM13); - LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_TIM13); - } -#endif -#if defined(TIM14) - else if (TIMx == TIM14) - { - LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_TIM14); - LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_TIM14); - } -#endif -#if defined(TIM15) - else if (TIMx == TIM15) - { - LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_TIM15); - LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_TIM15); - } -#endif -#if defined(TIM16) - else if (TIMx == TIM16) - { - LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_TIM16); - LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_TIM16); - } -#endif -#if defined(TIM17) - else if (TIMx == TIM17) - { - LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_TIM17); - LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_TIM17); - } -#endif - else - { - result = ERROR; - } - - return result; -} - -/** - * @brief Set the fields of the time base unit configuration data structure - * to their default values. - * @param TIM_InitStruct pointer to a @ref LL_TIM_InitTypeDef structure (time base unit configuration data structure) - * @retval None - */ -void LL_TIM_StructInit(LL_TIM_InitTypeDef *TIM_InitStruct) -{ - /* Set the default configuration */ - TIM_InitStruct->Prescaler = (uint16_t)0x0000; - TIM_InitStruct->CounterMode = LL_TIM_COUNTERMODE_UP; - TIM_InitStruct->Autoreload = 0xFFFFFFFFU; - TIM_InitStruct->ClockDivision = LL_TIM_CLOCKDIVISION_DIV1; - TIM_InitStruct->RepetitionCounter = (uint8_t)0x00; -} - -/** - * @brief Configure the TIMx time base unit. - * @param TIMx Timer Instance - * @param TIM_InitStruct pointer to a @ref LL_TIM_InitTypeDef structure (TIMx time base unit configuration data structure) - * @retval An ErrorStatus enumeration value: - * - SUCCESS: TIMx registers are de-initialized - * - ERROR: not applicable - */ -ErrorStatus LL_TIM_Init(TIM_TypeDef *TIMx, LL_TIM_InitTypeDef *TIM_InitStruct) -{ - uint32_t tmpcr1 = 0U; - - /* Check the parameters */ - assert_param(IS_TIM_INSTANCE(TIMx)); - assert_param(IS_LL_TIM_COUNTERMODE(TIM_InitStruct->CounterMode)); - assert_param(IS_LL_TIM_CLOCKDIVISION(TIM_InitStruct->ClockDivision)); - - tmpcr1 = LL_TIM_ReadReg(TIMx, CR1); - - if (IS_TIM_COUNTER_MODE_SELECT_INSTANCE(TIMx)) - { - /* Select the Counter Mode */ - MODIFY_REG(tmpcr1, (TIM_CR1_DIR | TIM_CR1_CMS), TIM_InitStruct->CounterMode); - } - - if (IS_TIM_CLOCK_DIVISION_INSTANCE(TIMx)) - { - /* Set the clock division */ - MODIFY_REG(tmpcr1, TIM_CR1_CKD, TIM_InitStruct->ClockDivision); - } - - /* Write to TIMx CR1 */ - LL_TIM_WriteReg(TIMx, CR1, tmpcr1); - - /* Set the Autoreload value */ - LL_TIM_SetAutoReload(TIMx, TIM_InitStruct->Autoreload); - - /* Set the Prescaler value */ - LL_TIM_SetPrescaler(TIMx, TIM_InitStruct->Prescaler); - - if (IS_TIM_REPETITION_COUNTER_INSTANCE(TIMx)) - { - /* Set the Repetition Counter value */ - LL_TIM_SetRepetitionCounter(TIMx, TIM_InitStruct->RepetitionCounter); - } - - /* Generate an update event to reload the Prescaler - and the repetition counter value (if applicable) immediately */ - LL_TIM_GenerateEvent_UPDATE(TIMx); - - return SUCCESS; -} - -/** - * @brief Set the fields of the TIMx output channel configuration data - * structure to their default values. - * @param TIM_OC_InitStruct pointer to a @ref LL_TIM_OC_InitTypeDef structure (the output channel configuration data structure) - * @retval None - */ -void LL_TIM_OC_StructInit(LL_TIM_OC_InitTypeDef *TIM_OC_InitStruct) -{ - /* Set the default configuration */ - TIM_OC_InitStruct->OCMode = LL_TIM_OCMODE_FROZEN; - TIM_OC_InitStruct->OCState = LL_TIM_OCSTATE_DISABLE; - TIM_OC_InitStruct->OCNState = LL_TIM_OCSTATE_DISABLE; - TIM_OC_InitStruct->CompareValue = 0x00000000U; - TIM_OC_InitStruct->OCPolarity = LL_TIM_OCPOLARITY_HIGH; - TIM_OC_InitStruct->OCNPolarity = LL_TIM_OCPOLARITY_HIGH; - TIM_OC_InitStruct->OCIdleState = LL_TIM_OCIDLESTATE_LOW; - TIM_OC_InitStruct->OCNIdleState = LL_TIM_OCIDLESTATE_LOW; -} - -/** - * @brief Configure the TIMx output channel. - * @param TIMx Timer Instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_TIM_CHANNEL_CH1 - * @arg @ref LL_TIM_CHANNEL_CH2 - * @arg @ref LL_TIM_CHANNEL_CH3 - * @arg @ref LL_TIM_CHANNEL_CH4 - * @param TIM_OC_InitStruct pointer to a @ref LL_TIM_OC_InitTypeDef structure (TIMx output channel configuration data structure) - * @retval An ErrorStatus enumeration value: - * - SUCCESS: TIMx output channel is initialized - * - ERROR: TIMx output channel is not initialized - */ -ErrorStatus LL_TIM_OC_Init(TIM_TypeDef *TIMx, uint32_t Channel, LL_TIM_OC_InitTypeDef *TIM_OC_InitStruct) -{ - ErrorStatus result = ERROR; - - switch (Channel) - { - case LL_TIM_CHANNEL_CH1: - result = OC1Config(TIMx, TIM_OC_InitStruct); - break; - case LL_TIM_CHANNEL_CH2: - result = OC2Config(TIMx, TIM_OC_InitStruct); - break; - case LL_TIM_CHANNEL_CH3: - result = OC3Config(TIMx, TIM_OC_InitStruct); - break; - case LL_TIM_CHANNEL_CH4: - result = OC4Config(TIMx, TIM_OC_InitStruct); - break; - default: - break; - } - - return result; -} - -/** - * @brief Set the fields of the TIMx input channel configuration data - * structure to their default values. - * @param TIM_ICInitStruct pointer to a @ref LL_TIM_IC_InitTypeDef structure (the input channel configuration data structure) - * @retval None - */ -void LL_TIM_IC_StructInit(LL_TIM_IC_InitTypeDef *TIM_ICInitStruct) -{ - /* Set the default configuration */ - TIM_ICInitStruct->ICPolarity = LL_TIM_IC_POLARITY_RISING; - TIM_ICInitStruct->ICActiveInput = LL_TIM_ACTIVEINPUT_DIRECTTI; - TIM_ICInitStruct->ICPrescaler = LL_TIM_ICPSC_DIV1; - TIM_ICInitStruct->ICFilter = LL_TIM_IC_FILTER_FDIV1; -} - -/** - * @brief Configure the TIMx input channel. - * @param TIMx Timer Instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_TIM_CHANNEL_CH1 - * @arg @ref LL_TIM_CHANNEL_CH2 - * @arg @ref LL_TIM_CHANNEL_CH3 - * @arg @ref LL_TIM_CHANNEL_CH4 - * @param TIM_IC_InitStruct pointer to a @ref LL_TIM_IC_InitTypeDef structure (TIMx input channel configuration data structure) - * @retval An ErrorStatus enumeration value: - * - SUCCESS: TIMx output channel is initialized - * - ERROR: TIMx output channel is not initialized - */ -ErrorStatus LL_TIM_IC_Init(TIM_TypeDef *TIMx, uint32_t Channel, LL_TIM_IC_InitTypeDef *TIM_IC_InitStruct) -{ - ErrorStatus result = ERROR; - - switch (Channel) - { - case LL_TIM_CHANNEL_CH1: - result = IC1Config(TIMx, TIM_IC_InitStruct); - break; - case LL_TIM_CHANNEL_CH2: - result = IC2Config(TIMx, TIM_IC_InitStruct); - break; - case LL_TIM_CHANNEL_CH3: - result = IC3Config(TIMx, TIM_IC_InitStruct); - break; - case LL_TIM_CHANNEL_CH4: - result = IC4Config(TIMx, TIM_IC_InitStruct); - break; - default: - break; - } - - return result; -} - -/** - * @brief Fills each TIM_EncoderInitStruct field with its default value - * @param TIM_EncoderInitStruct pointer to a @ref LL_TIM_ENCODER_InitTypeDef structure (encoder interface configuration data structure) - * @retval None - */ -void LL_TIM_ENCODER_StructInit(LL_TIM_ENCODER_InitTypeDef *TIM_EncoderInitStruct) -{ - /* Set the default configuration */ - TIM_EncoderInitStruct->EncoderMode = LL_TIM_ENCODERMODE_X2_TI1; - TIM_EncoderInitStruct->IC1Polarity = LL_TIM_IC_POLARITY_RISING; - TIM_EncoderInitStruct->IC1ActiveInput = LL_TIM_ACTIVEINPUT_DIRECTTI; - TIM_EncoderInitStruct->IC1Prescaler = LL_TIM_ICPSC_DIV1; - TIM_EncoderInitStruct->IC1Filter = LL_TIM_IC_FILTER_FDIV1; - TIM_EncoderInitStruct->IC2Polarity = LL_TIM_IC_POLARITY_RISING; - TIM_EncoderInitStruct->IC2ActiveInput = LL_TIM_ACTIVEINPUT_DIRECTTI; - TIM_EncoderInitStruct->IC2Prescaler = LL_TIM_ICPSC_DIV1; - TIM_EncoderInitStruct->IC2Filter = LL_TIM_IC_FILTER_FDIV1; -} - -/** - * @brief Configure the encoder interface of the timer instance. - * @param TIMx Timer Instance - * @param TIM_EncoderInitStruct pointer to a @ref LL_TIM_ENCODER_InitTypeDef structure (TIMx encoder interface configuration data structure) - * @retval An ErrorStatus enumeration value: - * - SUCCESS: TIMx registers are de-initialized - * - ERROR: not applicable - */ -ErrorStatus LL_TIM_ENCODER_Init(TIM_TypeDef *TIMx, LL_TIM_ENCODER_InitTypeDef *TIM_EncoderInitStruct) -{ - uint32_t tmpccmr1 = 0U; - uint32_t tmpccer = 0U; - - /* Check the parameters */ - assert_param(IS_TIM_ENCODER_INTERFACE_INSTANCE(TIMx)); - assert_param(IS_LL_TIM_ENCODERMODE(TIM_EncoderInitStruct->EncoderMode)); - assert_param(IS_LL_TIM_IC_POLARITY_ENCODER(TIM_EncoderInitStruct->IC1Polarity)); - assert_param(IS_LL_TIM_ACTIVEINPUT(TIM_EncoderInitStruct->IC1ActiveInput)); - assert_param(IS_LL_TIM_ICPSC(TIM_EncoderInitStruct->IC1Prescaler)); - assert_param(IS_LL_TIM_IC_FILTER(TIM_EncoderInitStruct->IC1Filter)); - assert_param(IS_LL_TIM_IC_POLARITY_ENCODER(TIM_EncoderInitStruct->IC2Polarity)); - assert_param(IS_LL_TIM_ACTIVEINPUT(TIM_EncoderInitStruct->IC2ActiveInput)); - assert_param(IS_LL_TIM_ICPSC(TIM_EncoderInitStruct->IC2Prescaler)); - assert_param(IS_LL_TIM_IC_FILTER(TIM_EncoderInitStruct->IC2Filter)); - - /* Disable the CC1 and CC2: Reset the CC1E and CC2E Bits */ - TIMx->CCER &= (uint32_t)~(TIM_CCER_CC1E | TIM_CCER_CC2E); - - /* Get the TIMx CCMR1 register value */ - tmpccmr1 = LL_TIM_ReadReg(TIMx, CCMR1); - - /* Get the TIMx CCER register value */ - tmpccer = LL_TIM_ReadReg(TIMx, CCER); - - /* Configure TI1 */ - tmpccmr1 &= (uint32_t)~(TIM_CCMR1_CC1S | TIM_CCMR1_IC1F | TIM_CCMR1_IC1PSC); - tmpccmr1 |= (uint32_t)(TIM_EncoderInitStruct->IC1ActiveInput >> 16U); - tmpccmr1 |= (uint32_t)(TIM_EncoderInitStruct->IC1Filter >> 16U); - tmpccmr1 |= (uint32_t)(TIM_EncoderInitStruct->IC1Prescaler >> 16U); - - /* Configure TI2 */ - tmpccmr1 &= (uint32_t)~(TIM_CCMR1_CC2S | TIM_CCMR1_IC2F | TIM_CCMR1_IC2PSC); - tmpccmr1 |= (uint32_t)(TIM_EncoderInitStruct->IC2ActiveInput >> 8U); - tmpccmr1 |= (uint32_t)(TIM_EncoderInitStruct->IC2Filter >> 8U); - tmpccmr1 |= (uint32_t)(TIM_EncoderInitStruct->IC2Prescaler >> 8U); - - /* Set TI1 and TI2 polarity and enable TI1 and TI2 */ - tmpccer &= (uint32_t)~(TIM_CCER_CC1P | TIM_CCER_CC1NP | TIM_CCER_CC2P | TIM_CCER_CC2NP); - tmpccer |= (uint32_t)(TIM_EncoderInitStruct->IC1Polarity); - tmpccer |= (uint32_t)(TIM_EncoderInitStruct->IC2Polarity << 4U); - tmpccer |= (uint32_t)(TIM_CCER_CC1E | TIM_CCER_CC2E); - - /* Set encoder mode */ - LL_TIM_SetEncoderMode(TIMx, TIM_EncoderInitStruct->EncoderMode); - - /* Write to TIMx CCMR1 */ - LL_TIM_WriteReg(TIMx, CCMR1, tmpccmr1); - - /* Write to TIMx CCER */ - LL_TIM_WriteReg(TIMx, CCER, tmpccer); - - return SUCCESS; -} - -/** - * @brief Set the fields of the TIMx Hall sensor interface configuration data - * structure to their default values. - * @param TIM_HallSensorInitStruct pointer to a @ref LL_TIM_HALLSENSOR_InitTypeDef structure (HALL sensor interface configuration data structure) - * @retval None - */ -void LL_TIM_HALLSENSOR_StructInit(LL_TIM_HALLSENSOR_InitTypeDef *TIM_HallSensorInitStruct) -{ - /* Set the default configuration */ - TIM_HallSensorInitStruct->IC1Polarity = LL_TIM_IC_POLARITY_RISING; - TIM_HallSensorInitStruct->IC1Prescaler = LL_TIM_ICPSC_DIV1; - TIM_HallSensorInitStruct->IC1Filter = LL_TIM_IC_FILTER_FDIV1; - TIM_HallSensorInitStruct->CommutationDelay = 0U; -} - -/** - * @brief Configure the Hall sensor interface of the timer instance. - * @note TIMx CH1, CH2 and CH3 inputs connected through a XOR - * to the TI1 input channel - * @note TIMx slave mode controller is configured in reset mode. - Selected internal trigger is TI1F_ED. - * @note Channel 1 is configured as input, IC1 is mapped on TRC. - * @note Captured value stored in TIMx_CCR1 correspond to the time elapsed - * between 2 changes on the inputs. It gives information about motor speed. - * @note Channel 2 is configured in output PWM 2 mode. - * @note Compare value stored in TIMx_CCR2 corresponds to the commutation delay. - * @note OC2REF is selected as trigger output on TRGO. - * @param TIMx Timer Instance - * @param TIM_HallSensorInitStruct pointer to a @ref LL_TIM_HALLSENSOR_InitTypeDef structure (TIMx HALL sensor interface configuration data structure) - * @retval An ErrorStatus enumeration value: - * - SUCCESS: TIMx registers are de-initialized - * - ERROR: not applicable - */ -ErrorStatus LL_TIM_HALLSENSOR_Init(TIM_TypeDef *TIMx, LL_TIM_HALLSENSOR_InitTypeDef *TIM_HallSensorInitStruct) -{ - uint32_t tmpcr2 = 0U; - uint32_t tmpccmr1 = 0U; - uint32_t tmpccer = 0U; - uint32_t tmpsmcr = 0U; - - /* Check the parameters */ - assert_param(IS_TIM_HALL_SENSOR_INTERFACE_INSTANCE(TIMx)); - assert_param(IS_LL_TIM_IC_POLARITY_ENCODER(TIM_HallSensorInitStruct->IC1Polarity)); - assert_param(IS_LL_TIM_ICPSC(TIM_HallSensorInitStruct->IC1Prescaler)); - assert_param(IS_LL_TIM_IC_FILTER(TIM_HallSensorInitStruct->IC1Filter)); - - /* Disable the CC1 and CC2: Reset the CC1E and CC2E Bits */ - TIMx->CCER &= (uint32_t)~(TIM_CCER_CC1E | TIM_CCER_CC2E); - - /* Get the TIMx CR2 register value */ - tmpcr2 = LL_TIM_ReadReg(TIMx, CR2); - - /* Get the TIMx CCMR1 register value */ - tmpccmr1 = LL_TIM_ReadReg(TIMx, CCMR1); - - /* Get the TIMx CCER register value */ - tmpccer = LL_TIM_ReadReg(TIMx, CCER); - - /* Get the TIMx SMCR register value */ - tmpsmcr = LL_TIM_ReadReg(TIMx, SMCR); - - /* Connect TIMx_CH1, CH2 and CH3 pins to the TI1 input */ - tmpcr2 |= TIM_CR2_TI1S; - - /* OC2REF signal is used as trigger output (TRGO) */ - tmpcr2 |= LL_TIM_TRGO_OC2REF; - - /* Configure the slave mode controller */ - tmpsmcr &= (uint32_t)~(TIM_SMCR_TS | TIM_SMCR_SMS); - tmpsmcr |= LL_TIM_TS_TI1F_ED; - tmpsmcr |= LL_TIM_SLAVEMODE_RESET; - - /* Configure input channel 1 */ - tmpccmr1 &= (uint32_t)~(TIM_CCMR1_CC1S | TIM_CCMR1_IC1F | TIM_CCMR1_IC1PSC); - tmpccmr1 |= (uint32_t)(LL_TIM_ACTIVEINPUT_TRC >> 16U); - tmpccmr1 |= (uint32_t)(TIM_HallSensorInitStruct->IC1Filter >> 16U); - tmpccmr1 |= (uint32_t)(TIM_HallSensorInitStruct->IC1Prescaler >> 16U); - - /* Configure input channel 2 */ - tmpccmr1 &= (uint32_t)~(TIM_CCMR1_OC2M | TIM_CCMR1_OC2FE | TIM_CCMR1_OC2PE | TIM_CCMR1_OC2CE); - tmpccmr1 |= (uint32_t)(LL_TIM_OCMODE_PWM2 << 8U); - - /* Set Channel 1 polarity and enable Channel 1 and Channel2 */ - tmpccer &= (uint32_t)~(TIM_CCER_CC1P | TIM_CCER_CC1NP | TIM_CCER_CC2P | TIM_CCER_CC2NP); - tmpccer |= (uint32_t)(TIM_HallSensorInitStruct->IC1Polarity); - tmpccer |= (uint32_t)(TIM_CCER_CC1E | TIM_CCER_CC2E); - - /* Write to TIMx CR2 */ - LL_TIM_WriteReg(TIMx, CR2, tmpcr2); - - /* Write to TIMx SMCR */ - LL_TIM_WriteReg(TIMx, SMCR, tmpsmcr); - - /* Write to TIMx CCMR1 */ - LL_TIM_WriteReg(TIMx, CCMR1, tmpccmr1); - - /* Write to TIMx CCER */ - LL_TIM_WriteReg(TIMx, CCER, tmpccer); - - /* Write to TIMx CCR2 */ - LL_TIM_OC_SetCompareCH2(TIMx, TIM_HallSensorInitStruct->CommutationDelay); - - return SUCCESS; -} - -/** - * @brief Set the fields of the Break and Dead Time configuration data structure - * to their default values. - * @param TIM_BDTRInitStruct pointer to a @ref LL_TIM_BDTR_InitTypeDef structure (Break and Dead Time configuration data structure) - * @retval None - */ -void LL_TIM_BDTR_StructInit(LL_TIM_BDTR_InitTypeDef *TIM_BDTRInitStruct) -{ - /* Set the default configuration */ - TIM_BDTRInitStruct->OSSRState = LL_TIM_OSSR_DISABLE; - TIM_BDTRInitStruct->OSSIState = LL_TIM_OSSI_DISABLE; - TIM_BDTRInitStruct->LockLevel = LL_TIM_LOCKLEVEL_OFF; - TIM_BDTRInitStruct->DeadTime = (uint8_t)0x00; - TIM_BDTRInitStruct->BreakState = LL_TIM_BREAK_DISABLE; - TIM_BDTRInitStruct->BreakPolarity = LL_TIM_BREAK_POLARITY_LOW; - TIM_BDTRInitStruct->AutomaticOutput = LL_TIM_AUTOMATICOUTPUT_DISABLE; -} - -/** - * @brief Configure the Break and Dead Time feature of the timer instance. - * @note As the bits AOE, BKP, BKE, OSSR, OSSI and DTG[7:0] can be write-locked - * depending on the LOCK configuration, it can be necessary to configure all of - * them during the first write access to the TIMx_BDTR register. - * @note Macro @ref IS_TIM_BREAK_INSTANCE(TIMx) can be used to check whether or not - * a timer instance provides a break input. - * @param TIMx Timer Instance - * @param TIM_BDTRInitStruct pointer to a @ref LL_TIM_BDTR_InitTypeDef structure(Break and Dead Time configuration data structure) - * @retval An ErrorStatus enumeration value: - * - SUCCESS: Break and Dead Time is initialized - * - ERROR: not applicable - */ -ErrorStatus LL_TIM_BDTR_Init(TIM_TypeDef *TIMx, LL_TIM_BDTR_InitTypeDef *TIM_BDTRInitStruct) -{ - uint32_t tmpbdtr = 0; - - /* Check the parameters */ - assert_param(IS_TIM_BREAK_INSTANCE(TIMx)); - assert_param(IS_LL_TIM_OSSR_STATE(TIM_BDTRInitStruct->OSSRState)); - assert_param(IS_LL_TIM_OSSI_STATE(TIM_BDTRInitStruct->OSSIState)); - assert_param(IS_LL_TIM_LOCK_LEVEL(TIM_BDTRInitStruct->LockLevel)); - assert_param(IS_LL_TIM_BREAK_STATE(TIM_BDTRInitStruct->BreakState)); - assert_param(IS_LL_TIM_BREAK_POLARITY(TIM_BDTRInitStruct->BreakPolarity)); - assert_param(IS_LL_TIM_AUTOMATIC_OUTPUT_STATE(TIM_BDTRInitStruct->AutomaticOutput)); - - /* Set the Lock level, the Break enable Bit and the Polarity, the OSSR State, - the OSSI State, the dead time value and the Automatic Output Enable Bit */ - - /* Set the BDTR bits */ - MODIFY_REG(tmpbdtr, TIM_BDTR_DTG, TIM_BDTRInitStruct->DeadTime); - MODIFY_REG(tmpbdtr, TIM_BDTR_LOCK, TIM_BDTRInitStruct->LockLevel); - MODIFY_REG(tmpbdtr, TIM_BDTR_OSSI, TIM_BDTRInitStruct->OSSIState); - MODIFY_REG(tmpbdtr, TIM_BDTR_OSSR, TIM_BDTRInitStruct->OSSRState); - MODIFY_REG(tmpbdtr, TIM_BDTR_BKE, TIM_BDTRInitStruct->BreakState); - MODIFY_REG(tmpbdtr, TIM_BDTR_BKP, TIM_BDTRInitStruct->BreakPolarity); - MODIFY_REG(tmpbdtr, TIM_BDTR_AOE, TIM_BDTRInitStruct->AutomaticOutput); - MODIFY_REG(tmpbdtr, TIM_BDTR_MOE, TIM_BDTRInitStruct->AutomaticOutput); - - /* Set TIMx_BDTR */ - LL_TIM_WriteReg(TIMx, BDTR, tmpbdtr); - - return SUCCESS; -} -/** - * @} - */ - -/** - * @} - */ - -/** @addtogroup TIM_LL_Private_Functions TIM Private Functions - * @brief Private functions - * @{ - */ -/** - * @brief Configure the TIMx output channel 1. - * @param TIMx Timer Instance - * @param TIM_OCInitStruct pointer to the the TIMx output channel 1 configuration data structure - * @retval An ErrorStatus enumeration value: - * - SUCCESS: TIMx registers are de-initialized - * - ERROR: not applicable - */ -static ErrorStatus OC1Config(TIM_TypeDef *TIMx, LL_TIM_OC_InitTypeDef *TIM_OCInitStruct) -{ - uint32_t tmpccmr1 = 0U; - uint32_t tmpccer = 0U; - uint32_t tmpcr2 = 0U; - - /* Check the parameters */ - assert_param(IS_TIM_CC1_INSTANCE(TIMx)); - assert_param(IS_LL_TIM_OCMODE(TIM_OCInitStruct->OCMode)); - assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCState)); - assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCPolarity)); - assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCNState)); - assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCNPolarity)); - - /* Disable the Channel 1: Reset the CC1E Bit */ - CLEAR_BIT(TIMx->CCER, TIM_CCER_CC1E); - - /* Get the TIMx CCER register value */ - tmpccer = LL_TIM_ReadReg(TIMx, CCER); - - /* Get the TIMx CR2 register value */ - tmpcr2 = LL_TIM_ReadReg(TIMx, CR2); - - /* Get the TIMx CCMR1 register value */ - tmpccmr1 = LL_TIM_ReadReg(TIMx, CCMR1); - - /* Reset Capture/Compare selection Bits */ - CLEAR_BIT(tmpccmr1, TIM_CCMR1_CC1S); - - /* Set the Output Compare Mode */ - MODIFY_REG(tmpccmr1, TIM_CCMR1_OC1M, TIM_OCInitStruct->OCMode); - - /* Set the Output Compare Polarity */ - MODIFY_REG(tmpccer, TIM_CCER_CC1P, TIM_OCInitStruct->OCPolarity); - - /* Set the Output State */ - MODIFY_REG(tmpccer, TIM_CCER_CC1E, TIM_OCInitStruct->OCState); - - if (IS_TIM_BREAK_INSTANCE(TIMx)) - { - assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCNIdleState)); - assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCIdleState)); - - /* Set the complementary output Polarity */ - MODIFY_REG(tmpccer, TIM_CCER_CC1NP, TIM_OCInitStruct->OCNPolarity << 2U); - - /* Set the complementary output State */ - MODIFY_REG(tmpccer, TIM_CCER_CC1NE, TIM_OCInitStruct->OCNState << 2U); - - /* Set the Output Idle state */ - MODIFY_REG(tmpcr2, TIM_CR2_OIS1, TIM_OCInitStruct->OCIdleState); - - /* Set the complementary output Idle state */ - MODIFY_REG(tmpcr2, TIM_CR2_OIS1N, TIM_OCInitStruct->OCNIdleState << 1U); - } - - /* Write to TIMx CR2 */ - LL_TIM_WriteReg(TIMx, CR2, tmpcr2); - - /* Write to TIMx CCMR1 */ - LL_TIM_WriteReg(TIMx, CCMR1, tmpccmr1); - - /* Set the Capture Compare Register value */ - LL_TIM_OC_SetCompareCH1(TIMx, TIM_OCInitStruct->CompareValue); - - /* Write to TIMx CCER */ - LL_TIM_WriteReg(TIMx, CCER, tmpccer); - - return SUCCESS; -} - -/** - * @brief Configure the TIMx output channel 2. - * @param TIMx Timer Instance - * @param TIM_OCInitStruct pointer to the the TIMx output channel 2 configuration data structure - * @retval An ErrorStatus enumeration value: - * - SUCCESS: TIMx registers are de-initialized - * - ERROR: not applicable - */ -static ErrorStatus OC2Config(TIM_TypeDef *TIMx, LL_TIM_OC_InitTypeDef *TIM_OCInitStruct) -{ - uint32_t tmpccmr1 = 0U; - uint32_t tmpccer = 0U; - uint32_t tmpcr2 = 0U; - - /* Check the parameters */ - assert_param(IS_TIM_CC2_INSTANCE(TIMx)); - assert_param(IS_LL_TIM_OCMODE(TIM_OCInitStruct->OCMode)); - assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCState)); - assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCPolarity)); - assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCNState)); - assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCNPolarity)); - - /* Disable the Channel 2: Reset the CC2E Bit */ - CLEAR_BIT(TIMx->CCER, TIM_CCER_CC2E); - - /* Get the TIMx CCER register value */ - tmpccer = LL_TIM_ReadReg(TIMx, CCER); - - /* Get the TIMx CR2 register value */ - tmpcr2 = LL_TIM_ReadReg(TIMx, CR2); - - /* Get the TIMx CCMR1 register value */ - tmpccmr1 = LL_TIM_ReadReg(TIMx, CCMR1); - - /* Reset Capture/Compare selection Bits */ - CLEAR_BIT(tmpccmr1, TIM_CCMR1_CC2S); - - /* Select the Output Compare Mode */ - MODIFY_REG(tmpccmr1, TIM_CCMR1_OC2M, TIM_OCInitStruct->OCMode << 8U); - - /* Set the Output Compare Polarity */ - MODIFY_REG(tmpccer, TIM_CCER_CC2P, TIM_OCInitStruct->OCPolarity << 4U); - - /* Set the Output State */ - MODIFY_REG(tmpccer, TIM_CCER_CC2E, TIM_OCInitStruct->OCState << 4U); - - if (IS_TIM_BREAK_INSTANCE(TIMx)) - { - assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCNIdleState)); - assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCIdleState)); - - /* Set the complementary output Polarity */ - MODIFY_REG(tmpccer, TIM_CCER_CC2NP, TIM_OCInitStruct->OCNPolarity << 6U); - - /* Set the complementary output State */ - MODIFY_REG(tmpccer, TIM_CCER_CC2NE, TIM_OCInitStruct->OCNState << 6U); - - /* Set the Output Idle state */ - MODIFY_REG(tmpcr2, TIM_CR2_OIS2, TIM_OCInitStruct->OCIdleState << 2U); - - /* Set the complementary output Idle state */ - MODIFY_REG(tmpcr2, TIM_CR2_OIS2N, TIM_OCInitStruct->OCNIdleState << 3U); - } - - /* Write to TIMx CR2 */ - LL_TIM_WriteReg(TIMx, CR2, tmpcr2); - - /* Write to TIMx CCMR1 */ - LL_TIM_WriteReg(TIMx, CCMR1, tmpccmr1); - - /* Set the Capture Compare Register value */ - LL_TIM_OC_SetCompareCH2(TIMx, TIM_OCInitStruct->CompareValue); - - /* Write to TIMx CCER */ - LL_TIM_WriteReg(TIMx, CCER, tmpccer); - - return SUCCESS; -} - -/** - * @brief Configure the TIMx output channel 3. - * @param TIMx Timer Instance - * @param TIM_OCInitStruct pointer to the the TIMx output channel 3 configuration data structure - * @retval An ErrorStatus enumeration value: - * - SUCCESS: TIMx registers are de-initialized - * - ERROR: not applicable - */ -static ErrorStatus OC3Config(TIM_TypeDef *TIMx, LL_TIM_OC_InitTypeDef *TIM_OCInitStruct) -{ - uint32_t tmpccmr2 = 0U; - uint32_t tmpccer = 0U; - uint32_t tmpcr2 = 0U; - - /* Check the parameters */ - assert_param(IS_TIM_CC3_INSTANCE(TIMx)); - assert_param(IS_LL_TIM_OCMODE(TIM_OCInitStruct->OCMode)); - assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCState)); - assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCPolarity)); - assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCNState)); - assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCNPolarity)); - - /* Disable the Channel 3: Reset the CC3E Bit */ - CLEAR_BIT(TIMx->CCER, TIM_CCER_CC3E); - - /* Get the TIMx CCER register value */ - tmpccer = LL_TIM_ReadReg(TIMx, CCER); - - /* Get the TIMx CR2 register value */ - tmpcr2 = LL_TIM_ReadReg(TIMx, CR2); - - /* Get the TIMx CCMR2 register value */ - tmpccmr2 = LL_TIM_ReadReg(TIMx, CCMR2); - - /* Reset Capture/Compare selection Bits */ - CLEAR_BIT(tmpccmr2, TIM_CCMR2_CC3S); - - /* Select the Output Compare Mode */ - MODIFY_REG(tmpccmr2, TIM_CCMR2_OC3M, TIM_OCInitStruct->OCMode); - - /* Set the Output Compare Polarity */ - MODIFY_REG(tmpccer, TIM_CCER_CC3P, TIM_OCInitStruct->OCPolarity << 8U); - - /* Set the Output State */ - MODIFY_REG(tmpccer, TIM_CCER_CC3E, TIM_OCInitStruct->OCState << 8U); - - if (IS_TIM_BREAK_INSTANCE(TIMx)) - { - assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCNIdleState)); - assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCIdleState)); - - /* Set the complementary output Polarity */ - MODIFY_REG(tmpccer, TIM_CCER_CC3NP, TIM_OCInitStruct->OCNPolarity << 10U); - - /* Set the complementary output State */ - MODIFY_REG(tmpccer, TIM_CCER_CC3NE, TIM_OCInitStruct->OCNState << 10U); - - /* Set the Output Idle state */ - MODIFY_REG(tmpcr2, TIM_CR2_OIS3, TIM_OCInitStruct->OCIdleState << 4U); - - /* Set the complementary output Idle state */ - MODIFY_REG(tmpcr2, TIM_CR2_OIS3N, TIM_OCInitStruct->OCNIdleState << 5U); - } - - /* Write to TIMx CR2 */ - LL_TIM_WriteReg(TIMx, CR2, tmpcr2); - - /* Write to TIMx CCMR2 */ - LL_TIM_WriteReg(TIMx, CCMR2, tmpccmr2); - - /* Set the Capture Compare Register value */ - LL_TIM_OC_SetCompareCH3(TIMx, TIM_OCInitStruct->CompareValue); - - /* Write to TIMx CCER */ - LL_TIM_WriteReg(TIMx, CCER, tmpccer); - - return SUCCESS; -} - -/** - * @brief Configure the TIMx output channel 4. - * @param TIMx Timer Instance - * @param TIM_OCInitStruct pointer to the the TIMx output channel 4 configuration data structure - * @retval An ErrorStatus enumeration value: - * - SUCCESS: TIMx registers are de-initialized - * - ERROR: not applicable - */ -static ErrorStatus OC4Config(TIM_TypeDef *TIMx, LL_TIM_OC_InitTypeDef *TIM_OCInitStruct) -{ - uint32_t tmpccmr2 = 0U; - uint32_t tmpccer = 0U; - uint32_t tmpcr2 = 0U; - - /* Check the parameters */ - assert_param(IS_TIM_CC4_INSTANCE(TIMx)); - assert_param(IS_LL_TIM_OCMODE(TIM_OCInitStruct->OCMode)); - assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCState)); - assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCPolarity)); - assert_param(IS_LL_TIM_OCPOLARITY(TIM_OCInitStruct->OCNPolarity)); - assert_param(IS_LL_TIM_OCSTATE(TIM_OCInitStruct->OCNState)); - - /* Disable the Channel 4: Reset the CC4E Bit */ - CLEAR_BIT(TIMx->CCER, TIM_CCER_CC4E); - - /* Get the TIMx CCER register value */ - tmpccer = LL_TIM_ReadReg(TIMx, CCER); - - /* Get the TIMx CR2 register value */ - tmpcr2 = LL_TIM_ReadReg(TIMx, CR2); - - /* Get the TIMx CCMR2 register value */ - tmpccmr2 = LL_TIM_ReadReg(TIMx, CCMR2); - - /* Reset Capture/Compare selection Bits */ - CLEAR_BIT(tmpccmr2, TIM_CCMR2_CC4S); - - /* Select the Output Compare Mode */ - MODIFY_REG(tmpccmr2, TIM_CCMR2_OC4M, TIM_OCInitStruct->OCMode << 8U); - - /* Set the Output Compare Polarity */ - MODIFY_REG(tmpccer, TIM_CCER_CC4P, TIM_OCInitStruct->OCPolarity << 12U); - - /* Set the Output State */ - MODIFY_REG(tmpccer, TIM_CCER_CC4E, TIM_OCInitStruct->OCState << 12U); - - if (IS_TIM_BREAK_INSTANCE(TIMx)) - { - assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCNIdleState)); - assert_param(IS_LL_TIM_OCIDLESTATE(TIM_OCInitStruct->OCIdleState)); - - /* Set the Output Idle state */ - MODIFY_REG(tmpcr2, TIM_CR2_OIS4, TIM_OCInitStruct->OCIdleState << 6U); - } - - /* Write to TIMx CR2 */ - LL_TIM_WriteReg(TIMx, CR2, tmpcr2); - - /* Write to TIMx CCMR2 */ - LL_TIM_WriteReg(TIMx, CCMR2, tmpccmr2); - - /* Set the Capture Compare Register value */ - LL_TIM_OC_SetCompareCH4(TIMx, TIM_OCInitStruct->CompareValue); - - /* Write to TIMx CCER */ - LL_TIM_WriteReg(TIMx, CCER, tmpccer); - - return SUCCESS; -} - - -/** - * @brief Configure the TIMx input channel 1. - * @param TIMx Timer Instance - * @param TIM_ICInitStruct pointer to the the TIMx input channel 1 configuration data structure - * @retval An ErrorStatus enumeration value: - * - SUCCESS: TIMx registers are de-initialized - * - ERROR: not applicable - */ -static ErrorStatus IC1Config(TIM_TypeDef *TIMx, LL_TIM_IC_InitTypeDef *TIM_ICInitStruct) -{ - /* Check the parameters */ - assert_param(IS_TIM_CC1_INSTANCE(TIMx)); - assert_param(IS_LL_TIM_IC_POLARITY(TIM_ICInitStruct->ICPolarity)); - assert_param(IS_LL_TIM_ACTIVEINPUT(TIM_ICInitStruct->ICActiveInput)); - assert_param(IS_LL_TIM_ICPSC(TIM_ICInitStruct->ICPrescaler)); - assert_param(IS_LL_TIM_IC_FILTER(TIM_ICInitStruct->ICFilter)); - - /* Disable the Channel 1: Reset the CC1E Bit */ - TIMx->CCER &= (uint32_t)~TIM_CCER_CC1E; - - /* Select the Input and set the filter and the prescaler value */ - MODIFY_REG(TIMx->CCMR1, - (TIM_CCMR1_CC1S | TIM_CCMR1_IC1F | TIM_CCMR1_IC1PSC), - (TIM_ICInitStruct->ICActiveInput | TIM_ICInitStruct->ICFilter | TIM_ICInitStruct->ICPrescaler) >> 16U); - - /* Select the Polarity and set the CC1E Bit */ - MODIFY_REG(TIMx->CCER, - (TIM_CCER_CC1P | TIM_CCER_CC1NP), - (TIM_ICInitStruct->ICPolarity | TIM_CCER_CC1E)); - - return SUCCESS; -} - -/** - * @brief Configure the TIMx input channel 2. - * @param TIMx Timer Instance - * @param TIM_ICInitStruct pointer to the the TIMx input channel 2 configuration data structure - * @retval An ErrorStatus enumeration value: - * - SUCCESS: TIMx registers are de-initialized - * - ERROR: not applicable - */ -static ErrorStatus IC2Config(TIM_TypeDef *TIMx, LL_TIM_IC_InitTypeDef *TIM_ICInitStruct) -{ - /* Check the parameters */ - assert_param(IS_TIM_CC2_INSTANCE(TIMx)); - assert_param(IS_LL_TIM_IC_POLARITY(TIM_ICInitStruct->ICPolarity)); - assert_param(IS_LL_TIM_ACTIVEINPUT(TIM_ICInitStruct->ICActiveInput)); - assert_param(IS_LL_TIM_ICPSC(TIM_ICInitStruct->ICPrescaler)); - assert_param(IS_LL_TIM_IC_FILTER(TIM_ICInitStruct->ICFilter)); - - /* Disable the Channel 2: Reset the CC2E Bit */ - TIMx->CCER &= (uint32_t)~TIM_CCER_CC2E; - - /* Select the Input and set the filter and the prescaler value */ - MODIFY_REG(TIMx->CCMR1, - (TIM_CCMR1_CC2S | TIM_CCMR1_IC2F | TIM_CCMR1_IC2PSC), - (TIM_ICInitStruct->ICActiveInput | TIM_ICInitStruct->ICFilter | TIM_ICInitStruct->ICPrescaler) >> 8U); - - /* Select the Polarity and set the CC2E Bit */ - MODIFY_REG(TIMx->CCER, - (TIM_CCER_CC2P | TIM_CCER_CC2NP), - ((TIM_ICInitStruct->ICPolarity << 4U) | TIM_CCER_CC2E)); - - return SUCCESS; -} - -/** - * @brief Configure the TIMx input channel 3. - * @param TIMx Timer Instance - * @param TIM_ICInitStruct pointer to the the TIMx input channel 3 configuration data structure - * @retval An ErrorStatus enumeration value: - * - SUCCESS: TIMx registers are de-initialized - * - ERROR: not applicable - */ -static ErrorStatus IC3Config(TIM_TypeDef *TIMx, LL_TIM_IC_InitTypeDef *TIM_ICInitStruct) -{ - /* Check the parameters */ - assert_param(IS_TIM_CC3_INSTANCE(TIMx)); - assert_param(IS_LL_TIM_IC_POLARITY(TIM_ICInitStruct->ICPolarity)); - assert_param(IS_LL_TIM_ACTIVEINPUT(TIM_ICInitStruct->ICActiveInput)); - assert_param(IS_LL_TIM_ICPSC(TIM_ICInitStruct->ICPrescaler)); - assert_param(IS_LL_TIM_IC_FILTER(TIM_ICInitStruct->ICFilter)); - - /* Disable the Channel 3: Reset the CC3E Bit */ - TIMx->CCER &= (uint32_t)~TIM_CCER_CC3E; - - /* Select the Input and set the filter and the prescaler value */ - MODIFY_REG(TIMx->CCMR2, - (TIM_CCMR2_CC3S | TIM_CCMR2_IC3F | TIM_CCMR2_IC3PSC), - (TIM_ICInitStruct->ICActiveInput | TIM_ICInitStruct->ICFilter | TIM_ICInitStruct->ICPrescaler) >> 16U); - - /* Select the Polarity and set the CC3E Bit */ - MODIFY_REG(TIMx->CCER, - (TIM_CCER_CC3P | TIM_CCER_CC3NP), - ((TIM_ICInitStruct->ICPolarity << 8U) | TIM_CCER_CC3E)); - - return SUCCESS; -} - -/** - * @brief Configure the TIMx input channel 4. - * @param TIMx Timer Instance - * @param TIM_ICInitStruct pointer to the the TIMx input channel 4 configuration data structure - * @retval An ErrorStatus enumeration value: - * - SUCCESS: TIMx registers are de-initialized - * - ERROR: not applicable - */ -static ErrorStatus IC4Config(TIM_TypeDef *TIMx, LL_TIM_IC_InitTypeDef *TIM_ICInitStruct) -{ - /* Check the parameters */ - assert_param(IS_TIM_CC4_INSTANCE(TIMx)); - assert_param(IS_LL_TIM_IC_POLARITY(TIM_ICInitStruct->ICPolarity)); - assert_param(IS_LL_TIM_ACTIVEINPUT(TIM_ICInitStruct->ICActiveInput)); - assert_param(IS_LL_TIM_ICPSC(TIM_ICInitStruct->ICPrescaler)); - assert_param(IS_LL_TIM_IC_FILTER(TIM_ICInitStruct->ICFilter)); - - /* Disable the Channel 4: Reset the CC4E Bit */ - TIMx->CCER &= (uint32_t)~TIM_CCER_CC4E; - - /* Select the Input and set the filter and the prescaler value */ - MODIFY_REG(TIMx->CCMR2, - (TIM_CCMR2_CC4S | TIM_CCMR2_IC4F | TIM_CCMR2_IC4PSC), - (TIM_ICInitStruct->ICActiveInput | TIM_ICInitStruct->ICFilter | TIM_ICInitStruct->ICPrescaler) >> 8U); - - /* Select the Polarity and set the CC4E Bit */ - MODIFY_REG(TIMx->CCER, - TIM_CCER_CC4P, - ((TIM_ICInitStruct->ICPolarity << 12U) | TIM_CCER_CC4E)); - - return SUCCESS; -} - - -/** - * @} - */ - -/** - * @} - */ - -#endif /* TIM1 || TIM2 || TIM3 || TIM4 || TIM5 || TIM6 || TIM7 || TIM8 || TIM9 || TIM10 || TIM11 || TIM12 || TIM13 || TIM14 || TIM15 || TIM16 || TIM17 */ - -/** - * @} - */ - -#endif /* USE_FULL_LL_DRIVER */ - -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_tim.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_tim.h deleted file mode 100644 index 2f93fbd948a..00000000000 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_tim.h +++ /dev/null @@ -1,3837 +0,0 @@ -/** - ****************************************************************************** - * @file stm32f1xx_ll_tim.h - * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 - * @brief Header file of TIM LL module. - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2016 STMicroelectronics

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ - -/* Define to prevent recursive inclusion -------------------------------------*/ -#ifndef __STM32F1xx_LL_TIM_H -#define __STM32F1xx_LL_TIM_H - -#ifdef __cplusplus -extern "C" { -#endif - -/* Includes ------------------------------------------------------------------*/ -#include "stm32f1xx.h" - -/** @addtogroup STM32F1xx_LL_Driver - * @{ - */ - -#if defined (TIM1) || defined (TIM2) || defined (TIM3) || defined (TIM4) || defined (TIM5) || defined (TIM6) || defined (TIM7) || defined (TIM8) || defined (TIM9) || defined (TIM10) || defined (TIM11) || defined (TIM12) || defined (TIM13) || defined (TIM14) || defined (TIM15) || defined (TIM16) || defined (TIM17) - -/** @defgroup TIM_LL TIM - * @{ - */ - -/* Private types -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/** @defgroup TIM_LL_Private_Variables TIM Private Variables - * @{ - */ -static const uint8_t OFFSET_TAB_CCMRx[] = -{ - 0x00U, /* 0: TIMx_CH1 */ - 0x00U, /* 1: TIMx_CH1N */ - 0x00U, /* 2: TIMx_CH2 */ - 0x00U, /* 3: TIMx_CH2N */ - 0x04U, /* 4: TIMx_CH3 */ - 0x04U, /* 5: TIMx_CH3N */ - 0x04U /* 6: TIMx_CH4 */ -}; - -static const uint8_t SHIFT_TAB_OCxx[] = -{ - 0U, /* 0: OC1M, OC1FE, OC1PE */ - 0U, /* 1: - NA */ - 8U, /* 2: OC2M, OC2FE, OC2PE */ - 0U, /* 3: - NA */ - 0U, /* 4: OC3M, OC3FE, OC3PE */ - 0U, /* 5: - NA */ - 8U /* 6: OC4M, OC4FE, OC4PE */ -}; - -static const uint8_t SHIFT_TAB_ICxx[] = -{ - 0U, /* 0: CC1S, IC1PSC, IC1F */ - 0U, /* 1: - NA */ - 8U, /* 2: CC2S, IC2PSC, IC2F */ - 0U, /* 3: - NA */ - 0U, /* 4: CC3S, IC3PSC, IC3F */ - 0U, /* 5: - NA */ - 8U /* 6: CC4S, IC4PSC, IC4F */ -}; - -static const uint8_t SHIFT_TAB_CCxP[] = -{ - 0U, /* 0: CC1P */ - 2U, /* 1: CC1NP */ - 4U, /* 2: CC2P */ - 6U, /* 3: CC2NP */ - 8U, /* 4: CC3P */ - 10U, /* 5: CC3NP */ - 12U /* 6: CC4P */ -}; - -static const uint8_t SHIFT_TAB_OISx[] = -{ - 0U, /* 0: OIS1 */ - 1U, /* 1: OIS1N */ - 2U, /* 2: OIS2 */ - 3U, /* 3: OIS2N */ - 4U, /* 4: OIS3 */ - 5U, /* 5: OIS3N */ - 6U /* 6: OIS4 */ -}; -/** - * @} - */ - - -/* Private constants ---------------------------------------------------------*/ -/** @defgroup TIM_LL_Private_Constants TIM Private Constants - * @{ - */ - - - -/* Mask used to set the TDG[x:0] of the DTG bits of the TIMx_BDTR register */ -#define DT_DELAY_1 ((uint8_t)0x7F) -#define DT_DELAY_2 ((uint8_t)0x3F) -#define DT_DELAY_3 ((uint8_t)0x1F) -#define DT_DELAY_4 ((uint8_t)0x1F) - -/* Mask used to set the DTG[7:5] bits of the DTG bits of the TIMx_BDTR register */ -#define DT_RANGE_1 ((uint8_t)0x00) -#define DT_RANGE_2 ((uint8_t)0x80) -#define DT_RANGE_3 ((uint8_t)0xC0) -#define DT_RANGE_4 ((uint8_t)0xE0) - - -/** - * @} - */ - -/* Private macros ------------------------------------------------------------*/ -/** @defgroup TIM_LL_Private_Macros TIM Private Macros - * @{ - */ -/** @brief Convert channel id into channel index. - * @param __CHANNEL__ This parameter can be one of the following values: - * @arg @ref LL_TIM_CHANNEL_CH1 - * @arg @ref LL_TIM_CHANNEL_CH1N - * @arg @ref LL_TIM_CHANNEL_CH2 - * @arg @ref LL_TIM_CHANNEL_CH2N - * @arg @ref LL_TIM_CHANNEL_CH3 - * @arg @ref LL_TIM_CHANNEL_CH3N - * @arg @ref LL_TIM_CHANNEL_CH4 - * @retval none - */ -#define TIM_GET_CHANNEL_INDEX( __CHANNEL__) \ -(((__CHANNEL__) == LL_TIM_CHANNEL_CH1) ? 0U :\ -((__CHANNEL__) == LL_TIM_CHANNEL_CH1N) ? 1U :\ -((__CHANNEL__) == LL_TIM_CHANNEL_CH2) ? 2U :\ -((__CHANNEL__) == LL_TIM_CHANNEL_CH2N) ? 3U :\ -((__CHANNEL__) == LL_TIM_CHANNEL_CH3) ? 4U :\ -((__CHANNEL__) == LL_TIM_CHANNEL_CH3N) ? 5U : 6U) - -/** @brief Calculate the deadtime sampling period(in ps). - * @param __TIMCLK__ timer input clock frequency (in Hz). - * @param __CKD__ This parameter can be one of the following values: - * @arg @ref LL_TIM_CLOCKDIVISION_DIV1 - * @arg @ref LL_TIM_CLOCKDIVISION_DIV2 - * @arg @ref LL_TIM_CLOCKDIVISION_DIV4 - * @retval none - */ -#define TIM_CALC_DTS(__TIMCLK__, __CKD__) \ - (((__CKD__) == LL_TIM_CLOCKDIVISION_DIV1) ? ((uint64_t)1000000000000U/(__TIMCLK__)) : \ - ((__CKD__) == LL_TIM_CLOCKDIVISION_DIV2) ? ((uint64_t)1000000000000U/((__TIMCLK__) >> 1U)) : \ - ((uint64_t)1000000000000U/((__TIMCLK__) >> 2U))) -/** - * @} - */ - - -/* Exported types ------------------------------------------------------------*/ -#if defined(USE_FULL_LL_DRIVER) -/** @defgroup TIM_LL_ES_INIT TIM Exported Init structure - * @{ - */ - -/** - * @brief TIM Time Base configuration structure definition. - */ -typedef struct -{ - uint16_t Prescaler; /*!< Specifies the prescaler value used to divide the TIM clock. - This parameter can be a number between Min_Data=0x0000 and Max_Data=0xFFFF. - - This feature can be modified afterwards using unitary function @ref LL_TIM_SetPrescaler().*/ - - uint32_t CounterMode; /*!< Specifies the counter mode. - This parameter can be a value of @ref TIM_LL_EC_COUNTERMODE. - - This feature can be modified afterwards using unitary function @ref LL_TIM_SetCounterMode().*/ - - uint32_t Autoreload; /*!< Specifies the auto reload value to be loaded into the active - Auto-Reload Register at the next update event. - This parameter must be a number between Min_Data=0x0000 and Max_Data=0xFFFF. - Some timer instances may support 32 bits counters. In that case this parameter must be a number between 0x0000 and 0xFFFFFFFF. - - This feature can be modified afterwards using unitary function @ref LL_TIM_SetAutoReload().*/ - - uint32_t ClockDivision; /*!< Specifies the clock division. - This parameter can be a value of @ref TIM_LL_EC_CLOCKDIVISION. - - This feature can be modified afterwards using unitary function @ref LL_TIM_SetClockDivision().*/ - - uint8_t RepetitionCounter; /*!< Specifies the repetition counter value. Each time the RCR downcounter - reaches zero, an update event is generated and counting restarts - from the RCR value (N). - This means in PWM mode that (N+1) corresponds to: - - the number of PWM periods in edge-aligned mode - - the number of half PWM period in center-aligned mode - This parameter must be a number between 0x00 and 0xFF. - - This feature can be modified afterwards using unitary function @ref LL_TIM_SetRepetitionCounter().*/ -} LL_TIM_InitTypeDef; - -/** - * @brief TIM Output Compare configuration structure definition. - */ -typedef struct -{ - uint32_t OCMode; /*!< Specifies the output mode. - This parameter can be a value of @ref TIM_LL_EC_OCMODE. - - This feature can be modified afterwards using unitary function @ref LL_TIM_OC_SetMode().*/ - - uint32_t OCState; /*!< Specifies the TIM Output Compare state. - This parameter can be a value of @ref TIM_LL_EC_OCSTATE. - - This feature can be modified afterwards using unitary functions @ref LL_TIM_CC_EnableChannel() or @ref LL_TIM_CC_DisableChannel().*/ - - uint32_t OCNState; /*!< Specifies the TIM complementary Output Compare state. - This parameter can be a value of @ref TIM_LL_EC_OCSTATE. - - This feature can be modified afterwards using unitary functions @ref LL_TIM_CC_EnableChannel() or @ref LL_TIM_CC_DisableChannel().*/ - - uint32_t CompareValue; /*!< Specifies the Compare value to be loaded into the Capture Compare Register. - This parameter can be a number between Min_Data=0x0000 and Max_Data=0xFFFF. - - This feature can be modified afterwards using unitary function LL_TIM_OC_SetCompareCHx (x=1..6).*/ - - uint32_t OCPolarity; /*!< Specifies the output polarity. - This parameter can be a value of @ref TIM_LL_EC_OCPOLARITY. - - This feature can be modified afterwards using unitary function @ref LL_TIM_OC_SetPolarity().*/ - - uint32_t OCNPolarity; /*!< Specifies the complementary output polarity. - This parameter can be a value of @ref TIM_LL_EC_OCPOLARITY. - - This feature can be modified afterwards using unitary function @ref LL_TIM_OC_SetPolarity().*/ - - - uint32_t OCIdleState; /*!< Specifies the TIM Output Compare pin state during Idle state. - This parameter can be a value of @ref TIM_LL_EC_OCIDLESTATE. - - This feature can be modified afterwards using unitary function @ref LL_TIM_OC_SetIdleState().*/ - - uint32_t OCNIdleState; /*!< Specifies the TIM Output Compare pin state during Idle state. - This parameter can be a value of @ref TIM_LL_EC_OCIDLESTATE. - - This feature can be modified afterwards using unitary function @ref LL_TIM_OC_SetIdleState().*/ -} LL_TIM_OC_InitTypeDef; - -/** - * @brief TIM Input Capture configuration structure definition. - */ - -typedef struct -{ - - uint32_t ICPolarity; /*!< Specifies the active edge of the input signal. - This parameter can be a value of @ref TIM_LL_EC_IC_POLARITY. - - This feature can be modified afterwards using unitary function @ref LL_TIM_IC_SetPolarity().*/ - - uint32_t ICActiveInput; /*!< Specifies the input. - This parameter can be a value of @ref TIM_LL_EC_ACTIVEINPUT. - - This feature can be modified afterwards using unitary function @ref LL_TIM_IC_SetActiveInput().*/ - - uint32_t ICPrescaler; /*!< Specifies the Input Capture Prescaler. - This parameter can be a value of @ref TIM_LL_EC_ICPSC. - - This feature can be modified afterwards using unitary function @ref LL_TIM_IC_SetPrescaler().*/ - - uint32_t ICFilter; /*!< Specifies the input capture filter. - This parameter can be a value of @ref TIM_LL_EC_IC_FILTER. - - This feature can be modified afterwards using unitary function @ref LL_TIM_IC_SetFilter().*/ -} LL_TIM_IC_InitTypeDef; - - -/** - * @brief TIM Encoder interface configuration structure definition. - */ -typedef struct -{ - uint32_t EncoderMode; /*!< Specifies the encoder resolution (x2 or x4). - This parameter can be a value of @ref TIM_LL_EC_ENCODERMODE. - - This feature can be modified afterwards using unitary function @ref LL_TIM_SetEncoderMode().*/ - - uint32_t IC1Polarity; /*!< Specifies the active edge of TI1 input. - This parameter can be a value of @ref TIM_LL_EC_IC_POLARITY. - - This feature can be modified afterwards using unitary function @ref LL_TIM_IC_SetPolarity().*/ - - uint32_t IC1ActiveInput; /*!< Specifies the TI1 input source - This parameter can be a value of @ref TIM_LL_EC_ACTIVEINPUT. - - This feature can be modified afterwards using unitary function @ref LL_TIM_IC_SetActiveInput().*/ - - uint32_t IC1Prescaler; /*!< Specifies the TI1 input prescaler value. - This parameter can be a value of @ref TIM_LL_EC_ICPSC. - - This feature can be modified afterwards using unitary function @ref LL_TIM_IC_SetPrescaler().*/ - - uint32_t IC1Filter; /*!< Specifies the TI1 input filter. - This parameter can be a value of @ref TIM_LL_EC_IC_FILTER. - - This feature can be modified afterwards using unitary function @ref LL_TIM_IC_SetFilter().*/ - - uint32_t IC2Polarity; /*!< Specifies the active edge of TI2 input. - This parameter can be a value of @ref TIM_LL_EC_IC_POLARITY. - - This feature can be modified afterwards using unitary function @ref LL_TIM_IC_SetPolarity().*/ - - uint32_t IC2ActiveInput; /*!< Specifies the TI2 input source - This parameter can be a value of @ref TIM_LL_EC_ACTIVEINPUT. - - This feature can be modified afterwards using unitary function @ref LL_TIM_IC_SetActiveInput().*/ - - uint32_t IC2Prescaler; /*!< Specifies the TI2 input prescaler value. - This parameter can be a value of @ref TIM_LL_EC_ICPSC. - - This feature can be modified afterwards using unitary function @ref LL_TIM_IC_SetPrescaler().*/ - - uint32_t IC2Filter; /*!< Specifies the TI2 input filter. - This parameter can be a value of @ref TIM_LL_EC_IC_FILTER. - - This feature can be modified afterwards using unitary function @ref LL_TIM_IC_SetFilter().*/ - -} LL_TIM_ENCODER_InitTypeDef; - -/** - * @brief TIM Hall sensor interface configuration structure definition. - */ -typedef struct -{ - - uint32_t IC1Polarity; /*!< Specifies the active edge of TI1 input. - This parameter can be a value of @ref TIM_LL_EC_IC_POLARITY. - - This feature can be modified afterwards using unitary function @ref LL_TIM_IC_SetPolarity().*/ - - uint32_t IC1Prescaler; /*!< Specifies the TI1 input prescaler value. - Prescaler must be set to get a maximum counter period longer than the - time interval between 2 consecutive changes on the Hall inputs. - This parameter can be a value of @ref TIM_LL_EC_ICPSC. - - This feature can be modified afterwards using unitary function @ref LL_TIM_IC_SetPrescaler().*/ - - uint32_t IC1Filter; /*!< Specifies the TI1 input filter. - This parameter can be a value of @ref TIM_LL_EC_IC_FILTER. - - This feature can be modified afterwards using unitary function @ref LL_TIM_IC_SetFilter().*/ - - uint32_t CommutationDelay; /*!< Specifies the compare value to be loaded into the Capture Compare Register. - A positive pulse (TRGO event) is generated with a programmable delay every time - a change occurs on the Hall inputs. - This parameter can be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF. - - This feature can be modified afterwards using unitary function @ref LL_TIM_OC_SetCompareCH2().*/ -} LL_TIM_HALLSENSOR_InitTypeDef; - -/** - * @brief BDTR (Break and Dead Time) structure definition - */ -typedef struct -{ - uint32_t OSSRState; /*!< Specifies the Off-State selection used in Run mode. - This parameter can be a value of @ref TIM_LL_EC_OSSR - - This feature can be modified afterwards using unitary function @ref LL_TIM_SetOffStates() - - @note This bit-field cannot be modified as long as LOCK level 2 has been programmed. */ - - uint32_t OSSIState; /*!< Specifies the Off-State used in Idle state. - This parameter can be a value of @ref TIM_LL_EC_OSSI - - This feature can be modified afterwards using unitary function @ref LL_TIM_SetOffStates() - - @note This bit-field cannot be modified as long as LOCK level 2 has been programmed. */ - - uint32_t LockLevel; /*!< Specifies the LOCK level parameters. - This parameter can be a value of @ref TIM_LL_EC_LOCKLEVEL - - @note The LOCK bits can be written only once after the reset. Once the TIMx_BDTR register - has been written, their content is frozen until the next reset.*/ - - uint8_t DeadTime; /*!< Specifies the delay time between the switching-off and the - switching-on of the outputs. - This parameter can be a number between Min_Data = 0x00 and Max_Data = 0xFF. - - This feature can be modified afterwards using unitary function @ref LL_TIM_OC_SetDeadTime() - - @note This bit-field can not be modified as long as LOCK level 1, 2 or 3 has been programmed. */ - - uint16_t BreakState; /*!< Specifies whether the TIM Break input is enabled or not. - This parameter can be a value of @ref TIM_LL_EC_BREAK_ENABLE - - This feature can be modified afterwards using unitary functions @ref LL_TIM_EnableBRK() or @ref LL_TIM_DisableBRK() - - @note This bit-field can not be modified as long as LOCK level 1 has been programmed. */ - - uint32_t BreakPolarity; /*!< Specifies the TIM Break Input pin polarity. - This parameter can be a value of @ref TIM_LL_EC_BREAK_POLARITY - - This feature can be modified afterwards using unitary function @ref LL_TIM_ConfigBRK() - - @note This bit-field can not be modified as long as LOCK level 1 has been programmed. */ - - uint32_t AutomaticOutput; /*!< Specifies whether the TIM Automatic Output feature is enabled or not. - This parameter can be a value of @ref TIM_LL_EC_AUTOMATICOUTPUT_ENABLE - - This feature can be modified afterwards using unitary functions @ref LL_TIM_EnableAutomaticOutput() or @ref LL_TIM_DisableAutomaticOutput() - - @note This bit-field can not be modified as long as LOCK level 1 has been programmed. */ -} LL_TIM_BDTR_InitTypeDef; - -/** - * @} - */ -#endif /* USE_FULL_LL_DRIVER */ - -/* Exported constants --------------------------------------------------------*/ -/** @defgroup TIM_LL_Exported_Constants TIM Exported Constants - * @{ - */ - -/** @defgroup TIM_LL_EC_GET_FLAG Get Flags Defines - * @brief Flags defines which can be used with LL_TIM_ReadReg function. - * @{ - */ -#define LL_TIM_SR_UIF TIM_SR_UIF /*!< Update interrupt flag */ -#define LL_TIM_SR_CC1IF TIM_SR_CC1IF /*!< Capture/compare 1 interrupt flag */ -#define LL_TIM_SR_CC2IF TIM_SR_CC2IF /*!< Capture/compare 2 interrupt flag */ -#define LL_TIM_SR_CC3IF TIM_SR_CC3IF /*!< Capture/compare 3 interrupt flag */ -#define LL_TIM_SR_CC4IF TIM_SR_CC4IF /*!< Capture/compare 4 interrupt flag */ -#define LL_TIM_SR_COMIF TIM_SR_COMIF /*!< COM interrupt flag */ -#define LL_TIM_SR_TIF TIM_SR_TIF /*!< Trigger interrupt flag */ -#define LL_TIM_SR_BIF TIM_SR_BIF /*!< Break interrupt flag */ -#define LL_TIM_SR_CC1OF TIM_SR_CC1OF /*!< Capture/Compare 1 overcapture flag */ -#define LL_TIM_SR_CC2OF TIM_SR_CC2OF /*!< Capture/Compare 2 overcapture flag */ -#define LL_TIM_SR_CC3OF TIM_SR_CC3OF /*!< Capture/Compare 3 overcapture flag */ -#define LL_TIM_SR_CC4OF TIM_SR_CC4OF /*!< Capture/Compare 4 overcapture flag */ -/** - * @} - */ - -#if defined(USE_FULL_LL_DRIVER) -/** @defgroup TIM_LL_EC_BREAK_ENABLE Break Enable - * @{ - */ -#define LL_TIM_BREAK_DISABLE 0x00000000U /*!< Break function disabled */ -#define LL_TIM_BREAK_ENABLE TIM_BDTR_BKE /*!< Break function enabled */ -/** - * @} - */ - -/** @defgroup TIM_LL_EC_AUTOMATICOUTPUT_ENABLE Automatic output enable - * @{ - */ -#define LL_TIM_AUTOMATICOUTPUT_DISABLE 0x00000000U /*!< MOE can be set only by software */ -#define LL_TIM_AUTOMATICOUTPUT_ENABLE TIM_BDTR_AOE /*!< MOE can be set by software or automatically at the next update event */ -/** - * @} - */ -#endif /* USE_FULL_LL_DRIVER */ - -/** @defgroup TIM_LL_EC_IT IT Defines - * @brief IT defines which can be used with LL_TIM_ReadReg and LL_TIM_WriteReg functions. - * @{ - */ -#define LL_TIM_DIER_UIE TIM_DIER_UIE /*!< Update interrupt enable */ -#define LL_TIM_DIER_CC1IE TIM_DIER_CC1IE /*!< Capture/compare 1 interrupt enable */ -#define LL_TIM_DIER_CC2IE TIM_DIER_CC2IE /*!< Capture/compare 2 interrupt enable */ -#define LL_TIM_DIER_CC3IE TIM_DIER_CC3IE /*!< Capture/compare 3 interrupt enable */ -#define LL_TIM_DIER_CC4IE TIM_DIER_CC4IE /*!< Capture/compare 4 interrupt enable */ -#define LL_TIM_DIER_COMIE TIM_DIER_COMIE /*!< COM interrupt enable */ -#define LL_TIM_DIER_TIE TIM_DIER_TIE /*!< Trigger interrupt enable */ -#define LL_TIM_DIER_BIE TIM_DIER_BIE /*!< Break interrupt enable */ -/** - * @} - */ - -/** @defgroup TIM_LL_EC_UPDATESOURCE Update Source - * @{ - */ -#define LL_TIM_UPDATESOURCE_REGULAR 0x00000000U /*!< Counter overflow/underflow, Setting the UG bit or Update generation through the slave mode controller generates an update request */ -#define LL_TIM_UPDATESOURCE_COUNTER TIM_CR1_URS /*!< Only counter overflow/underflow generates an update request */ -/** - * @} - */ - -/** @defgroup TIM_LL_EC_ONEPULSEMODE One Pulse Mode - * @{ - */ -#define LL_TIM_ONEPULSEMODE_SINGLE TIM_CR1_OPM /*!< Counter is not stopped at update event */ -#define LL_TIM_ONEPULSEMODE_REPETITIVE 0x00000000U /*!< Counter stops counting at the next update event */ -/** - * @} - */ - -/** @defgroup TIM_LL_EC_COUNTERMODE Counter Mode - * @{ - */ -#define LL_TIM_COUNTERMODE_UP 0x00000000U /*!TIMx_CCRy else active.*/ -#define LL_TIM_OCMODE_PWM2 (TIM_CCMR1_OC1M_2 | TIM_CCMR1_OC1M_1 | TIM_CCMR1_OC1M_0) /*!TIMx_CCRy else inactive*/ -/** - * @} - */ - -/** @defgroup TIM_LL_EC_OCPOLARITY Output Configuration Polarity - * @{ - */ -#define LL_TIM_OCPOLARITY_HIGH 0x00000000U /*!< OCxactive high*/ -#define LL_TIM_OCPOLARITY_LOW TIM_CCER_CC1P /*!< OCxactive low*/ -/** - * @} - */ - -/** @defgroup TIM_LL_EC_OCIDLESTATE Output Configuration Idle State - * @{ - */ -#define LL_TIM_OCIDLESTATE_LOW 0x00000000U /*!__REG__, (__VALUE__)) - -/** - * @brief Read a value in TIM register. - * @param __INSTANCE__ TIM Instance - * @param __REG__ Register to be read - * @retval Register value - */ -#define LL_TIM_ReadReg(__INSTANCE__, __REG__) READ_REG(__INSTANCE__->__REG__) -/** - * @} - */ - -/** @defgroup TIM_LL_EM_Exported_Macros Exported_Macros - * @{ - */ - -/** - * @brief HELPER macro calculating DTG[0:7] in the TIMx_BDTR register to achieve the requested dead time duration. - * @note ex: @ref __LL_TIM_CALC_DEADTIME (80000000, @ref LL_TIM_GetClockDivision (), 120); - * @param __TIMCLK__ timer input clock frequency (in Hz) - * @param __CKD__ This parameter can be one of the following values: - * @arg @ref LL_TIM_CLOCKDIVISION_DIV1 - * @arg @ref LL_TIM_CLOCKDIVISION_DIV2 - * @arg @ref LL_TIM_CLOCKDIVISION_DIV4 - * @param __DT__ deadtime duration (in ns) - * @retval DTG[0:7] - */ -#define __LL_TIM_CALC_DEADTIME(__TIMCLK__, __CKD__, __DT__) \ - ( (((uint64_t)((__DT__)*1000U)) < ((DT_DELAY_1+1U) * TIM_CALC_DTS((__TIMCLK__), (__CKD__)))) ? (uint8_t)(((uint64_t)((__DT__)*1000U) / TIM_CALC_DTS((__TIMCLK__), (__CKD__))) & DT_DELAY_1) : \ - (((uint64_t)((__DT__)*1000U)) < (64U + (DT_DELAY_2+1U)) * 2U * TIM_CALC_DTS((__TIMCLK__), (__CKD__))) ? (uint8_t)(DT_RANGE_2 | ((uint8_t)((uint8_t)((((uint64_t)((__DT__)*1000U))/ TIM_CALC_DTS((__TIMCLK__), (__CKD__))) >> 1U) - (uint8_t) 64) & DT_DELAY_2)) :\ - (((uint64_t)((__DT__)*1000U)) < (32U + (DT_DELAY_3+1U)) * 8U * TIM_CALC_DTS((__TIMCLK__), (__CKD__))) ? (uint8_t)(DT_RANGE_3 | ((uint8_t)((uint8_t)(((((uint64_t)(__DT__)*1000U))/ TIM_CALC_DTS((__TIMCLK__), (__CKD__))) >> 3U) - (uint8_t) 32) & DT_DELAY_3)) :\ - (((uint64_t)((__DT__)*1000U)) < (32U + (DT_DELAY_4+1U)) * 16U * TIM_CALC_DTS((__TIMCLK__), (__CKD__))) ? (uint8_t)(DT_RANGE_4 | ((uint8_t)((uint8_t)(((((uint64_t)(__DT__)*1000U))/ TIM_CALC_DTS((__TIMCLK__), (__CKD__))) >> 4U) - (uint8_t) 32) & DT_DELAY_4)) :\ - 0U) - -/** - * @brief HELPER macro calculating the prescaler value to achieve the required counter clock frequency. - * @note ex: @ref __LL_TIM_CALC_PSC (80000000, 1000000); - * @param __TIMCLK__ timer input clock frequency (in Hz) - * @param __CNTCLK__ counter clock frequency (in Hz) - * @retval Prescaler value (between Min_Data=0 and Max_Data=65535) - */ -#define __LL_TIM_CALC_PSC(__TIMCLK__, __CNTCLK__) \ - ((__TIMCLK__) >= (__CNTCLK__)) ? (uint32_t)((__TIMCLK__)/(__CNTCLK__) - 1U) : 0U - -/** - * @brief HELPER macro calculating the auto-reload value to achieve the required output signal frequency. - * @note ex: @ref __LL_TIM_CALC_ARR (1000000, @ref LL_TIM_GetPrescaler (), 10000); - * @param __TIMCLK__ timer input clock frequency (in Hz) - * @param __PSC__ prescaler - * @param __FREQ__ output signal frequency (in Hz) - * @retval Auto-reload value (between Min_Data=0 and Max_Data=65535) - */ -#define __LL_TIM_CALC_ARR(__TIMCLK__, __PSC__, __FREQ__) \ - (((__TIMCLK__)/((__PSC__) + 1U)) >= (__FREQ__)) ? ((__TIMCLK__)/((__FREQ__) * ((__PSC__) + 1U)) - 1U) : 0U - -/** - * @brief HELPER macro calculating the compare value required to achieve the required timer output compare active/inactive delay. - * @note ex: @ref __LL_TIM_CALC_DELAY (1000000, @ref LL_TIM_GetPrescaler (), 10); - * @param __TIMCLK__ timer input clock frequency (in Hz) - * @param __PSC__ prescaler - * @param __DELAY__ timer output compare active/inactive delay (in us) - * @retval Compare value (between Min_Data=0 and Max_Data=65535) - */ -#define __LL_TIM_CALC_DELAY(__TIMCLK__, __PSC__, __DELAY__) \ -((uint32_t)(((uint64_t)(__TIMCLK__) * (uint64_t)(__DELAY__)) \ - / ((uint64_t)1000000U * (uint64_t)((__PSC__) + 1U)))) - -/** - * @brief HELPER macro calculating the auto-reload value to achieve the required pulse duration (when the timer operates in one pulse mode). - * @note ex: @ref __LL_TIM_CALC_PULSE (1000000, @ref LL_TIM_GetPrescaler (), 10, 20); - * @param __TIMCLK__ timer input clock frequency (in Hz) - * @param __PSC__ prescaler - * @param __DELAY__ timer output compare active/inactive delay (in us) - * @param __PULSE__ pulse duration (in us) - * @retval Auto-reload value (between Min_Data=0 and Max_Data=65535) - */ -#define __LL_TIM_CALC_PULSE(__TIMCLK__, __PSC__, __DELAY__, __PULSE__) \ - ((uint32_t)(__LL_TIM_CALC_DELAY((__TIMCLK__), (__PSC__), (__PULSE__)) \ - + __LL_TIM_CALC_DELAY((__TIMCLK__), (__PSC__), (__DELAY__)))) - -/** - * @brief HELPER macro retrieving the ratio of the input capture prescaler - * @note ex: @ref __LL_TIM_GET_ICPSC_RATIO (@ref LL_TIM_IC_GetPrescaler ()); - * @param __ICPSC__ This parameter can be one of the following values: - * @arg @ref LL_TIM_ICPSC_DIV1 - * @arg @ref LL_TIM_ICPSC_DIV2 - * @arg @ref LL_TIM_ICPSC_DIV4 - * @arg @ref LL_TIM_ICPSC_DIV8 - * @retval Input capture prescaler ratio (1, 2, 4 or 8) - */ -#define __LL_TIM_GET_ICPSC_RATIO(__ICPSC__) \ - ((uint32_t)(0x01U << (((__ICPSC__) >> 16U) >> TIM_CCMR1_IC1PSC_Pos))) - - -/** - * @} - */ - - -/** - * @} - */ - -/* Exported functions --------------------------------------------------------*/ -/** @defgroup TIM_LL_Exported_Functions TIM Exported Functions - * @{ - */ - -/** @defgroup TIM_LL_EF_Time_Base Time Base configuration - * @{ - */ -/** - * @brief Enable timer counter. - * @rmtoll CR1 CEN LL_TIM_EnableCounter - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_EnableCounter(TIM_TypeDef *TIMx) -{ - SET_BIT(TIMx->CR1, TIM_CR1_CEN); -} - -/** - * @brief Disable timer counter. - * @rmtoll CR1 CEN LL_TIM_DisableCounter - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_DisableCounter(TIM_TypeDef *TIMx) -{ - CLEAR_BIT(TIMx->CR1, TIM_CR1_CEN); -} - -/** - * @brief Indicates whether the timer counter is enabled. - * @rmtoll CR1 CEN LL_TIM_IsEnabledCounter - * @param TIMx Timer instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_TIM_IsEnabledCounter(TIM_TypeDef *TIMx) -{ - return (READ_BIT(TIMx->CR1, TIM_CR1_CEN) == (TIM_CR1_CEN)); -} - -/** - * @brief Enable update event generation. - * @rmtoll CR1 UDIS LL_TIM_EnableUpdateEvent - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_EnableUpdateEvent(TIM_TypeDef *TIMx) -{ - SET_BIT(TIMx->CR1, TIM_CR1_UDIS); -} - -/** - * @brief Disable update event generation. - * @rmtoll CR1 UDIS LL_TIM_DisableUpdateEvent - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_DisableUpdateEvent(TIM_TypeDef *TIMx) -{ - CLEAR_BIT(TIMx->CR1, TIM_CR1_UDIS); -} - -/** - * @brief Indicates whether update event generation is enabled. - * @rmtoll CR1 UDIS LL_TIM_IsEnabledUpdateEvent - * @param TIMx Timer instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_TIM_IsEnabledUpdateEvent(TIM_TypeDef *TIMx) -{ - return (READ_BIT(TIMx->CR1, TIM_CR1_UDIS) == (TIM_CR1_UDIS)); -} - -/** - * @brief Set update event source - * @note Update event source set to LL_TIM_UPDATESOURCE_REGULAR: any of the following events - * generate an update interrupt or DMA request if enabled: - * - Counter overflow/underflow - * - Setting the UG bit - * - Update generation through the slave mode controller - * @note Update event source set to LL_TIM_UPDATESOURCE_COUNTER: only counter - * overflow/underflow generates an update interrupt or DMA request if enabled. - * @rmtoll CR1 URS LL_TIM_SetUpdateSource - * @param TIMx Timer instance - * @param UpdateSource This parameter can be one of the following values: - * @arg @ref LL_TIM_UPDATESOURCE_REGULAR - * @arg @ref LL_TIM_UPDATESOURCE_COUNTER - * @retval None - */ -__STATIC_INLINE void LL_TIM_SetUpdateSource(TIM_TypeDef *TIMx, uint32_t UpdateSource) -{ - MODIFY_REG(TIMx->CR1, TIM_CR1_URS, UpdateSource); -} - -/** - * @brief Get actual event update source - * @rmtoll CR1 URS LL_TIM_GetUpdateSource - * @param TIMx Timer instance - * @retval Returned value can be one of the following values: - * @arg @ref LL_TIM_UPDATESOURCE_REGULAR - * @arg @ref LL_TIM_UPDATESOURCE_COUNTER - */ -__STATIC_INLINE uint32_t LL_TIM_GetUpdateSource(TIM_TypeDef *TIMx) -{ - return (uint32_t)(READ_BIT(TIMx->CR1, TIM_CR1_URS)); -} - -/** - * @brief Set one pulse mode (one shot v.s. repetitive). - * @rmtoll CR1 OPM LL_TIM_SetOnePulseMode - * @param TIMx Timer instance - * @param OnePulseMode This parameter can be one of the following values: - * @arg @ref LL_TIM_ONEPULSEMODE_SINGLE - * @arg @ref LL_TIM_ONEPULSEMODE_REPETITIVE - * @retval None - */ -__STATIC_INLINE void LL_TIM_SetOnePulseMode(TIM_TypeDef *TIMx, uint32_t OnePulseMode) -{ - MODIFY_REG(TIMx->CR1, TIM_CR1_OPM, OnePulseMode); -} - -/** - * @brief Get actual one pulse mode. - * @rmtoll CR1 OPM LL_TIM_GetOnePulseMode - * @param TIMx Timer instance - * @retval Returned value can be one of the following values: - * @arg @ref LL_TIM_ONEPULSEMODE_SINGLE - * @arg @ref LL_TIM_ONEPULSEMODE_REPETITIVE - */ -__STATIC_INLINE uint32_t LL_TIM_GetOnePulseMode(TIM_TypeDef *TIMx) -{ - return (uint32_t)(READ_BIT(TIMx->CR1, TIM_CR1_OPM)); -} - -/** - * @brief Set the timer counter counting mode. - * @note Macro @ref IS_TIM_COUNTER_MODE_SELECT_INSTANCE(TIMx) can be used to - * check whether or not the counter mode selection feature is supported - * by a timer instance. - * @rmtoll CR1 DIR LL_TIM_SetCounterMode\n - * CR1 CMS LL_TIM_SetCounterMode - * @param TIMx Timer instance - * @param CounterMode This parameter can be one of the following values: - * @arg @ref LL_TIM_COUNTERMODE_UP - * @arg @ref LL_TIM_COUNTERMODE_DOWN - * @arg @ref LL_TIM_COUNTERMODE_CENTER_UP - * @arg @ref LL_TIM_COUNTERMODE_CENTER_DOWN - * @arg @ref LL_TIM_COUNTERMODE_CENTER_UP_DOWN - * @retval None - */ -__STATIC_INLINE void LL_TIM_SetCounterMode(TIM_TypeDef *TIMx, uint32_t CounterMode) -{ - MODIFY_REG(TIMx->CR1, TIM_CR1_DIR | TIM_CR1_CMS, CounterMode); -} - -/** - * @brief Get actual counter mode. - * @note Macro @ref IS_TIM_COUNTER_MODE_SELECT_INSTANCE(TIMx) can be used to - * check whether or not the counter mode selection feature is supported - * by a timer instance. - * @rmtoll CR1 DIR LL_TIM_GetCounterMode\n - * CR1 CMS LL_TIM_GetCounterMode - * @param TIMx Timer instance - * @retval Returned value can be one of the following values: - * @arg @ref LL_TIM_COUNTERMODE_UP - * @arg @ref LL_TIM_COUNTERMODE_DOWN - * @arg @ref LL_TIM_COUNTERMODE_CENTER_UP - * @arg @ref LL_TIM_COUNTERMODE_CENTER_DOWN - * @arg @ref LL_TIM_COUNTERMODE_CENTER_UP_DOWN - */ -__STATIC_INLINE uint32_t LL_TIM_GetCounterMode(TIM_TypeDef *TIMx) -{ - return (uint32_t)(READ_BIT(TIMx->CR1, TIM_CR1_DIR | TIM_CR1_CMS)); -} - -/** - * @brief Enable auto-reload (ARR) preload. - * @rmtoll CR1 ARPE LL_TIM_EnableARRPreload - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_EnableARRPreload(TIM_TypeDef *TIMx) -{ - SET_BIT(TIMx->CR1, TIM_CR1_ARPE); -} - -/** - * @brief Disable auto-reload (ARR) preload. - * @rmtoll CR1 ARPE LL_TIM_DisableARRPreload - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_DisableARRPreload(TIM_TypeDef *TIMx) -{ - CLEAR_BIT(TIMx->CR1, TIM_CR1_ARPE); -} - -/** - * @brief Indicates whether auto-reload (ARR) preload is enabled. - * @rmtoll CR1 ARPE LL_TIM_IsEnabledARRPreload - * @param TIMx Timer instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_TIM_IsEnabledARRPreload(TIM_TypeDef *TIMx) -{ - return (READ_BIT(TIMx->CR1, TIM_CR1_ARPE) == (TIM_CR1_ARPE)); -} - -/** - * @brief Set the division ratio between the timer clock and the sampling clock used by the dead-time generators (when supported) and the digital filters. - * @note Macro @ref IS_TIM_CLOCK_DIVISION_INSTANCE(TIMx) can be used to check - * whether or not the clock division feature is supported by the timer - * instance. - * @rmtoll CR1 CKD LL_TIM_SetClockDivision - * @param TIMx Timer instance - * @param ClockDivision This parameter can be one of the following values: - * @arg @ref LL_TIM_CLOCKDIVISION_DIV1 - * @arg @ref LL_TIM_CLOCKDIVISION_DIV2 - * @arg @ref LL_TIM_CLOCKDIVISION_DIV4 - * @retval None - */ -__STATIC_INLINE void LL_TIM_SetClockDivision(TIM_TypeDef *TIMx, uint32_t ClockDivision) -{ - MODIFY_REG(TIMx->CR1, TIM_CR1_CKD, ClockDivision); -} - -/** - * @brief Get the actual division ratio between the timer clock and the sampling clock used by the dead-time generators (when supported) and the digital filters. - * @note Macro @ref IS_TIM_CLOCK_DIVISION_INSTANCE(TIMx) can be used to check - * whether or not the clock division feature is supported by the timer - * instance. - * @rmtoll CR1 CKD LL_TIM_GetClockDivision - * @param TIMx Timer instance - * @retval Returned value can be one of the following values: - * @arg @ref LL_TIM_CLOCKDIVISION_DIV1 - * @arg @ref LL_TIM_CLOCKDIVISION_DIV2 - * @arg @ref LL_TIM_CLOCKDIVISION_DIV4 - */ -__STATIC_INLINE uint32_t LL_TIM_GetClockDivision(TIM_TypeDef *TIMx) -{ - return (uint32_t)(READ_BIT(TIMx->CR1, TIM_CR1_CKD)); -} - -/** - * @brief Set the counter value. - * @rmtoll CNT CNT LL_TIM_SetCounter - * @param TIMx Timer instance - * @param Counter Counter value (between Min_Data=0 and Max_Data=0xFFFF) - * @retval None - */ -__STATIC_INLINE void LL_TIM_SetCounter(TIM_TypeDef *TIMx, uint32_t Counter) -{ - WRITE_REG(TIMx->CNT, Counter); -} - -/** - * @brief Get the counter value. - * @rmtoll CNT CNT LL_TIM_GetCounter - * @param TIMx Timer instance - * @retval Counter value (between Min_Data=0 and Max_Data=0xFFFF) - */ -__STATIC_INLINE uint32_t LL_TIM_GetCounter(TIM_TypeDef *TIMx) -{ - return (uint32_t)(READ_REG(TIMx->CNT)); -} - -/** - * @brief Get the current direction of the counter - * @rmtoll CR1 DIR LL_TIM_GetDirection - * @param TIMx Timer instance - * @retval Returned value can be one of the following values: - * @arg @ref LL_TIM_COUNTERDIRECTION_UP - * @arg @ref LL_TIM_COUNTERDIRECTION_DOWN - */ -__STATIC_INLINE uint32_t LL_TIM_GetDirection(TIM_TypeDef *TIMx) -{ - return (uint32_t)(READ_BIT(TIMx->CR1, TIM_CR1_DIR)); -} - -/** - * @brief Set the prescaler value. - * @note The counter clock frequency CK_CNT is equal to fCK_PSC / (PSC[15:0] + 1). - * @note The prescaler can be changed on the fly as this control register is buffered. The new - * prescaler ratio is taken into account at the next update event. - * @note Helper macro @ref __LL_TIM_CALC_PSC can be used to calculate the Prescaler parameter - * @rmtoll PSC PSC LL_TIM_SetPrescaler - * @param TIMx Timer instance - * @param Prescaler between Min_Data=0 and Max_Data=65535 - * @retval None - */ -__STATIC_INLINE void LL_TIM_SetPrescaler(TIM_TypeDef *TIMx, uint32_t Prescaler) -{ - WRITE_REG(TIMx->PSC, Prescaler); -} - -/** - * @brief Get the prescaler value. - * @rmtoll PSC PSC LL_TIM_GetPrescaler - * @param TIMx Timer instance - * @retval Prescaler value between Min_Data=0 and Max_Data=65535 - */ -__STATIC_INLINE uint32_t LL_TIM_GetPrescaler(TIM_TypeDef *TIMx) -{ - return (uint32_t)(READ_REG(TIMx->PSC)); -} - -/** - * @brief Set the auto-reload value. - * @note The counter is blocked while the auto-reload value is null. - * @note Helper macro @ref __LL_TIM_CALC_ARR can be used to calculate the AutoReload parameter - * @rmtoll ARR ARR LL_TIM_SetAutoReload - * @param TIMx Timer instance - * @param AutoReload between Min_Data=0 and Max_Data=65535 - * @retval None - */ -__STATIC_INLINE void LL_TIM_SetAutoReload(TIM_TypeDef *TIMx, uint32_t AutoReload) -{ - WRITE_REG(TIMx->ARR, AutoReload); -} - -/** - * @brief Get the auto-reload value. - * @rmtoll ARR ARR LL_TIM_GetAutoReload - * @param TIMx Timer instance - * @retval Auto-reload value - */ -__STATIC_INLINE uint32_t LL_TIM_GetAutoReload(TIM_TypeDef *TIMx) -{ - return (uint32_t)(READ_REG(TIMx->ARR)); -} - -/** - * @brief Set the repetition counter value. - * @note Macro @ref IS_TIM_REPETITION_COUNTER_INSTANCE(TIMx) can be used to check - * whether or not a timer instance supports a repetition counter. - * @rmtoll RCR REP LL_TIM_SetRepetitionCounter - * @param TIMx Timer instance - * @param RepetitionCounter between Min_Data=0 and Max_Data=255 - * @retval None - */ -__STATIC_INLINE void LL_TIM_SetRepetitionCounter(TIM_TypeDef *TIMx, uint32_t RepetitionCounter) -{ - WRITE_REG(TIMx->RCR, RepetitionCounter); -} - -/** - * @brief Get the repetition counter value. - * @note Macro @ref IS_TIM_REPETITION_COUNTER_INSTANCE(TIMx) can be used to check - * whether or not a timer instance supports a repetition counter. - * @rmtoll RCR REP LL_TIM_GetRepetitionCounter - * @param TIMx Timer instance - * @retval Repetition counter value - */ -__STATIC_INLINE uint32_t LL_TIM_GetRepetitionCounter(TIM_TypeDef *TIMx) -{ - return (uint32_t)(READ_REG(TIMx->RCR)); -} - -/** - * @} - */ - -/** @defgroup TIM_LL_EF_Capture_Compare Capture Compare configuration - * @{ - */ -/** - * @brief Enable the capture/compare control bits (CCxE, CCxNE and OCxM) preload. - * @note CCxE, CCxNE and OCxM bits are preloaded, after having been written, - * they are updated only when a commutation event (COM) occurs. - * @note Only on channels that have a complementary output. - * @note Macro @ref IS_TIM_COMMUTATION_EVENT_INSTANCE(TIMx) can be used to check - * whether or not a timer instance is able to generate a commutation event. - * @rmtoll CR2 CCPC LL_TIM_CC_EnablePreload - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_CC_EnablePreload(TIM_TypeDef *TIMx) -{ - SET_BIT(TIMx->CR2, TIM_CR2_CCPC); -} - -/** - * @brief Disable the capture/compare control bits (CCxE, CCxNE and OCxM) preload. - * @note Macro @ref IS_TIM_COMMUTATION_EVENT_INSTANCE(TIMx) can be used to check - * whether or not a timer instance is able to generate a commutation event. - * @rmtoll CR2 CCPC LL_TIM_CC_DisablePreload - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_CC_DisablePreload(TIM_TypeDef *TIMx) -{ - CLEAR_BIT(TIMx->CR2, TIM_CR2_CCPC); -} - -/** - * @brief Set the updated source of the capture/compare control bits (CCxE, CCxNE and OCxM). - * @note Macro @ref IS_TIM_COMMUTATION_EVENT_INSTANCE(TIMx) can be used to check - * whether or not a timer instance is able to generate a commutation event. - * @rmtoll CR2 CCUS LL_TIM_CC_SetUpdate - * @param TIMx Timer instance - * @param CCUpdateSource This parameter can be one of the following values: - * @arg @ref LL_TIM_CCUPDATESOURCE_COMG_ONLY - * @arg @ref LL_TIM_CCUPDATESOURCE_COMG_AND_TRGI - * @retval None - */ -__STATIC_INLINE void LL_TIM_CC_SetUpdate(TIM_TypeDef *TIMx, uint32_t CCUpdateSource) -{ - MODIFY_REG(TIMx->CR2, TIM_CR2_CCUS, CCUpdateSource); -} - -/** - * @brief Set the trigger of the capture/compare DMA request. - * @rmtoll CR2 CCDS LL_TIM_CC_SetDMAReqTrigger - * @param TIMx Timer instance - * @param DMAReqTrigger This parameter can be one of the following values: - * @arg @ref LL_TIM_CCDMAREQUEST_CC - * @arg @ref LL_TIM_CCDMAREQUEST_UPDATE - * @retval None - */ -__STATIC_INLINE void LL_TIM_CC_SetDMAReqTrigger(TIM_TypeDef *TIMx, uint32_t DMAReqTrigger) -{ - MODIFY_REG(TIMx->CR2, TIM_CR2_CCDS, DMAReqTrigger); -} - -/** - * @brief Get actual trigger of the capture/compare DMA request. - * @rmtoll CR2 CCDS LL_TIM_CC_GetDMAReqTrigger - * @param TIMx Timer instance - * @retval Returned value can be one of the following values: - * @arg @ref LL_TIM_CCDMAREQUEST_CC - * @arg @ref LL_TIM_CCDMAREQUEST_UPDATE - */ -__STATIC_INLINE uint32_t LL_TIM_CC_GetDMAReqTrigger(TIM_TypeDef *TIMx) -{ - return (uint32_t)(READ_BIT(TIMx->CR2, TIM_CR2_CCDS)); -} - -/** - * @brief Set the lock level to freeze the - * configuration of several capture/compare parameters. - * @note Macro @ref IS_TIM_BREAK_INSTANCE(TIMx) can be used to check whether or not - * the lock mechanism is supported by a timer instance. - * @rmtoll BDTR LOCK LL_TIM_CC_SetLockLevel - * @param TIMx Timer instance - * @param LockLevel This parameter can be one of the following values: - * @arg @ref LL_TIM_LOCKLEVEL_OFF - * @arg @ref LL_TIM_LOCKLEVEL_1 - * @arg @ref LL_TIM_LOCKLEVEL_2 - * @arg @ref LL_TIM_LOCKLEVEL_3 - * @retval None - */ -__STATIC_INLINE void LL_TIM_CC_SetLockLevel(TIM_TypeDef *TIMx, uint32_t LockLevel) -{ - MODIFY_REG(TIMx->BDTR, TIM_BDTR_LOCK, LockLevel); -} - -/** - * @brief Enable capture/compare channels. - * @rmtoll CCER CC1E LL_TIM_CC_EnableChannel\n - * CCER CC1NE LL_TIM_CC_EnableChannel\n - * CCER CC2E LL_TIM_CC_EnableChannel\n - * CCER CC2NE LL_TIM_CC_EnableChannel\n - * CCER CC3E LL_TIM_CC_EnableChannel\n - * CCER CC3NE LL_TIM_CC_EnableChannel\n - * CCER CC4E LL_TIM_CC_EnableChannel - * @param TIMx Timer instance - * @param Channels This parameter can be a combination of the following values: - * @arg @ref LL_TIM_CHANNEL_CH1 - * @arg @ref LL_TIM_CHANNEL_CH1N - * @arg @ref LL_TIM_CHANNEL_CH2 - * @arg @ref LL_TIM_CHANNEL_CH2N - * @arg @ref LL_TIM_CHANNEL_CH3 - * @arg @ref LL_TIM_CHANNEL_CH3N - * @arg @ref LL_TIM_CHANNEL_CH4 - * @retval None - */ -__STATIC_INLINE void LL_TIM_CC_EnableChannel(TIM_TypeDef *TIMx, uint32_t Channels) -{ - SET_BIT(TIMx->CCER, Channels); -} - -/** - * @brief Disable capture/compare channels. - * @rmtoll CCER CC1E LL_TIM_CC_DisableChannel\n - * CCER CC1NE LL_TIM_CC_DisableChannel\n - * CCER CC2E LL_TIM_CC_DisableChannel\n - * CCER CC2NE LL_TIM_CC_DisableChannel\n - * CCER CC3E LL_TIM_CC_DisableChannel\n - * CCER CC3NE LL_TIM_CC_DisableChannel\n - * CCER CC4E LL_TIM_CC_DisableChannel - * @param TIMx Timer instance - * @param Channels This parameter can be a combination of the following values: - * @arg @ref LL_TIM_CHANNEL_CH1 - * @arg @ref LL_TIM_CHANNEL_CH1N - * @arg @ref LL_TIM_CHANNEL_CH2 - * @arg @ref LL_TIM_CHANNEL_CH2N - * @arg @ref LL_TIM_CHANNEL_CH3 - * @arg @ref LL_TIM_CHANNEL_CH3N - * @arg @ref LL_TIM_CHANNEL_CH4 - * @retval None - */ -__STATIC_INLINE void LL_TIM_CC_DisableChannel(TIM_TypeDef *TIMx, uint32_t Channels) -{ - CLEAR_BIT(TIMx->CCER, Channels); -} - -/** - * @brief Indicate whether channel(s) is(are) enabled. - * @rmtoll CCER CC1E LL_TIM_CC_IsEnabledChannel\n - * CCER CC1NE LL_TIM_CC_IsEnabledChannel\n - * CCER CC2E LL_TIM_CC_IsEnabledChannel\n - * CCER CC2NE LL_TIM_CC_IsEnabledChannel\n - * CCER CC3E LL_TIM_CC_IsEnabledChannel\n - * CCER CC3NE LL_TIM_CC_IsEnabledChannel\n - * CCER CC4E LL_TIM_CC_IsEnabledChannel - * @param TIMx Timer instance - * @param Channels This parameter can be a combination of the following values: - * @arg @ref LL_TIM_CHANNEL_CH1 - * @arg @ref LL_TIM_CHANNEL_CH1N - * @arg @ref LL_TIM_CHANNEL_CH2 - * @arg @ref LL_TIM_CHANNEL_CH2N - * @arg @ref LL_TIM_CHANNEL_CH3 - * @arg @ref LL_TIM_CHANNEL_CH3N - * @arg @ref LL_TIM_CHANNEL_CH4 - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_TIM_CC_IsEnabledChannel(TIM_TypeDef *TIMx, uint32_t Channels) -{ - return (READ_BIT(TIMx->CCER, Channels) == (Channels)); -} - -/** - * @} - */ - -/** @defgroup TIM_LL_EF_Output_Channel Output channel configuration - * @{ - */ -/** - * @brief Configure an output channel. - * @rmtoll CCMR1 CC1S LL_TIM_OC_ConfigOutput\n - * CCMR1 CC2S LL_TIM_OC_ConfigOutput\n - * CCMR2 CC3S LL_TIM_OC_ConfigOutput\n - * CCMR2 CC4S LL_TIM_OC_ConfigOutput\n - * CCER CC1P LL_TIM_OC_ConfigOutput\n - * CCER CC2P LL_TIM_OC_ConfigOutput\n - * CCER CC3P LL_TIM_OC_ConfigOutput\n - * CCER CC4P LL_TIM_OC_ConfigOutput\n - * CR2 OIS1 LL_TIM_OC_ConfigOutput\n - * CR2 OIS2 LL_TIM_OC_ConfigOutput\n - * CR2 OIS3 LL_TIM_OC_ConfigOutput\n - * CR2 OIS4 LL_TIM_OC_ConfigOutput - * @param TIMx Timer instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_TIM_CHANNEL_CH1 - * @arg @ref LL_TIM_CHANNEL_CH2 - * @arg @ref LL_TIM_CHANNEL_CH3 - * @arg @ref LL_TIM_CHANNEL_CH4 - * @param Configuration This parameter must be a combination of all the following values: - * @arg @ref LL_TIM_OCPOLARITY_HIGH or @ref LL_TIM_OCPOLARITY_LOW - * @arg @ref LL_TIM_OCIDLESTATE_LOW or @ref LL_TIM_OCIDLESTATE_HIGH - * @retval None - */ -__STATIC_INLINE void LL_TIM_OC_ConfigOutput(TIM_TypeDef *TIMx, uint32_t Channel, uint32_t Configuration) -{ - register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel); - register uint32_t *pReg = (uint32_t *)((uint32_t)((uint32_t)(&TIMx->CCMR1) + OFFSET_TAB_CCMRx[iChannel])); - CLEAR_BIT(*pReg, (TIM_CCMR1_CC1S << SHIFT_TAB_OCxx[iChannel])); - MODIFY_REG(TIMx->CCER, (TIM_CCER_CC1P << SHIFT_TAB_CCxP[iChannel]), - (Configuration & TIM_CCER_CC1P) << SHIFT_TAB_CCxP[iChannel]); - MODIFY_REG(TIMx->CR2, (TIM_CR2_OIS1 << SHIFT_TAB_OISx[iChannel]), - (Configuration & TIM_CR2_OIS1) << SHIFT_TAB_OISx[iChannel]); -} - -/** - * @brief Define the behavior of the output reference signal OCxREF from which - * OCx and OCxN (when relevant) are derived. - * @rmtoll CCMR1 OC1M LL_TIM_OC_SetMode\n - * CCMR1 OC2M LL_TIM_OC_SetMode\n - * CCMR2 OC3M LL_TIM_OC_SetMode\n - * CCMR2 OC4M LL_TIM_OC_SetMode - * @param TIMx Timer instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_TIM_CHANNEL_CH1 - * @arg @ref LL_TIM_CHANNEL_CH2 - * @arg @ref LL_TIM_CHANNEL_CH3 - * @arg @ref LL_TIM_CHANNEL_CH4 - * @param Mode This parameter can be one of the following values: - * @arg @ref LL_TIM_OCMODE_FROZEN - * @arg @ref LL_TIM_OCMODE_ACTIVE - * @arg @ref LL_TIM_OCMODE_INACTIVE - * @arg @ref LL_TIM_OCMODE_TOGGLE - * @arg @ref LL_TIM_OCMODE_FORCED_INACTIVE - * @arg @ref LL_TIM_OCMODE_FORCED_ACTIVE - * @arg @ref LL_TIM_OCMODE_PWM1 - * @arg @ref LL_TIM_OCMODE_PWM2 - * @retval None - */ -__STATIC_INLINE void LL_TIM_OC_SetMode(TIM_TypeDef *TIMx, uint32_t Channel, uint32_t Mode) -{ - register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel); - register uint32_t *pReg = (uint32_t *)((uint32_t)((uint32_t)(&TIMx->CCMR1) + OFFSET_TAB_CCMRx[iChannel])); - MODIFY_REG(*pReg, ((TIM_CCMR1_OC1M | TIM_CCMR1_CC1S) << SHIFT_TAB_OCxx[iChannel]), Mode << SHIFT_TAB_OCxx[iChannel]); -} - -/** - * @brief Get the output compare mode of an output channel. - * @rmtoll CCMR1 OC1M LL_TIM_OC_GetMode\n - * CCMR1 OC2M LL_TIM_OC_GetMode\n - * CCMR2 OC3M LL_TIM_OC_GetMode\n - * CCMR2 OC4M LL_TIM_OC_GetMode - * @param TIMx Timer instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_TIM_CHANNEL_CH1 - * @arg @ref LL_TIM_CHANNEL_CH2 - * @arg @ref LL_TIM_CHANNEL_CH3 - * @arg @ref LL_TIM_CHANNEL_CH4 - * @retval Returned value can be one of the following values: - * @arg @ref LL_TIM_OCMODE_FROZEN - * @arg @ref LL_TIM_OCMODE_ACTIVE - * @arg @ref LL_TIM_OCMODE_INACTIVE - * @arg @ref LL_TIM_OCMODE_TOGGLE - * @arg @ref LL_TIM_OCMODE_FORCED_INACTIVE - * @arg @ref LL_TIM_OCMODE_FORCED_ACTIVE - * @arg @ref LL_TIM_OCMODE_PWM1 - * @arg @ref LL_TIM_OCMODE_PWM2 - */ -__STATIC_INLINE uint32_t LL_TIM_OC_GetMode(TIM_TypeDef *TIMx, uint32_t Channel) -{ - register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel); - register uint32_t *pReg = (uint32_t *)((uint32_t)((uint32_t)(&TIMx->CCMR1) + OFFSET_TAB_CCMRx[iChannel])); - return (READ_BIT(*pReg, ((TIM_CCMR1_OC1M | TIM_CCMR1_CC1S) << SHIFT_TAB_OCxx[iChannel])) >> SHIFT_TAB_OCxx[iChannel]); -} - -/** - * @brief Set the polarity of an output channel. - * @rmtoll CCER CC1P LL_TIM_OC_SetPolarity\n - * CCER CC1NP LL_TIM_OC_SetPolarity\n - * CCER CC2P LL_TIM_OC_SetPolarity\n - * CCER CC2NP LL_TIM_OC_SetPolarity\n - * CCER CC3P LL_TIM_OC_SetPolarity\n - * CCER CC3NP LL_TIM_OC_SetPolarity\n - * CCER CC4P LL_TIM_OC_SetPolarity - * @param TIMx Timer instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_TIM_CHANNEL_CH1 - * @arg @ref LL_TIM_CHANNEL_CH1N - * @arg @ref LL_TIM_CHANNEL_CH2 - * @arg @ref LL_TIM_CHANNEL_CH2N - * @arg @ref LL_TIM_CHANNEL_CH3 - * @arg @ref LL_TIM_CHANNEL_CH3N - * @arg @ref LL_TIM_CHANNEL_CH4 - * @param Polarity This parameter can be one of the following values: - * @arg @ref LL_TIM_OCPOLARITY_HIGH - * @arg @ref LL_TIM_OCPOLARITY_LOW - * @retval None - */ -__STATIC_INLINE void LL_TIM_OC_SetPolarity(TIM_TypeDef *TIMx, uint32_t Channel, uint32_t Polarity) -{ - register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel); - MODIFY_REG(TIMx->CCER, (TIM_CCER_CC1P << SHIFT_TAB_CCxP[iChannel]), Polarity << SHIFT_TAB_CCxP[iChannel]); -} - -/** - * @brief Get the polarity of an output channel. - * @rmtoll CCER CC1P LL_TIM_OC_GetPolarity\n - * CCER CC1NP LL_TIM_OC_GetPolarity\n - * CCER CC2P LL_TIM_OC_GetPolarity\n - * CCER CC2NP LL_TIM_OC_GetPolarity\n - * CCER CC3P LL_TIM_OC_GetPolarity\n - * CCER CC3NP LL_TIM_OC_GetPolarity\n - * CCER CC4P LL_TIM_OC_GetPolarity - * @param TIMx Timer instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_TIM_CHANNEL_CH1 - * @arg @ref LL_TIM_CHANNEL_CH1N - * @arg @ref LL_TIM_CHANNEL_CH2 - * @arg @ref LL_TIM_CHANNEL_CH2N - * @arg @ref LL_TIM_CHANNEL_CH3 - * @arg @ref LL_TIM_CHANNEL_CH3N - * @arg @ref LL_TIM_CHANNEL_CH4 - * @retval Returned value can be one of the following values: - * @arg @ref LL_TIM_OCPOLARITY_HIGH - * @arg @ref LL_TIM_OCPOLARITY_LOW - */ -__STATIC_INLINE uint32_t LL_TIM_OC_GetPolarity(TIM_TypeDef *TIMx, uint32_t Channel) -{ - register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel); - return (READ_BIT(TIMx->CCER, (TIM_CCER_CC1P << SHIFT_TAB_CCxP[iChannel])) >> SHIFT_TAB_CCxP[iChannel]); -} - -/** - * @brief Set the IDLE state of an output channel - * @note This function is significant only for the timer instances - * supporting the break feature. Macro @ref IS_TIM_BREAK_INSTANCE(TIMx) - * can be used to check whether or not a timer instance provides - * a break input. - * @rmtoll CR2 OIS1 LL_TIM_OC_SetIdleState\n - * CR2 OIS1N LL_TIM_OC_SetIdleState\n - * CR2 OIS2 LL_TIM_OC_SetIdleState\n - * CR2 OIS2N LL_TIM_OC_SetIdleState\n - * CR2 OIS3 LL_TIM_OC_SetIdleState\n - * CR2 OIS3N LL_TIM_OC_SetIdleState\n - * CR2 OIS4 LL_TIM_OC_SetIdleState - * @param TIMx Timer instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_TIM_CHANNEL_CH1 - * @arg @ref LL_TIM_CHANNEL_CH1N - * @arg @ref LL_TIM_CHANNEL_CH2 - * @arg @ref LL_TIM_CHANNEL_CH2N - * @arg @ref LL_TIM_CHANNEL_CH3 - * @arg @ref LL_TIM_CHANNEL_CH3N - * @arg @ref LL_TIM_CHANNEL_CH4 - * @param IdleState This parameter can be one of the following values: - * @arg @ref LL_TIM_OCIDLESTATE_LOW - * @arg @ref LL_TIM_OCIDLESTATE_HIGH - * @retval None - */ -__STATIC_INLINE void LL_TIM_OC_SetIdleState(TIM_TypeDef *TIMx, uint32_t Channel, uint32_t IdleState) -{ - register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel); - MODIFY_REG(TIMx->CR2, (TIM_CR2_OIS1 << SHIFT_TAB_OISx[iChannel]), IdleState << SHIFT_TAB_OISx[iChannel]); -} - -/** - * @brief Get the IDLE state of an output channel - * @rmtoll CR2 OIS1 LL_TIM_OC_GetIdleState\n - * CR2 OIS1N LL_TIM_OC_GetIdleState\n - * CR2 OIS2 LL_TIM_OC_GetIdleState\n - * CR2 OIS2N LL_TIM_OC_GetIdleState\n - * CR2 OIS3 LL_TIM_OC_GetIdleState\n - * CR2 OIS3N LL_TIM_OC_GetIdleState\n - * CR2 OIS4 LL_TIM_OC_GetIdleState - * @param TIMx Timer instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_TIM_CHANNEL_CH1 - * @arg @ref LL_TIM_CHANNEL_CH1N - * @arg @ref LL_TIM_CHANNEL_CH2 - * @arg @ref LL_TIM_CHANNEL_CH2N - * @arg @ref LL_TIM_CHANNEL_CH3 - * @arg @ref LL_TIM_CHANNEL_CH3N - * @arg @ref LL_TIM_CHANNEL_CH4 - * @retval Returned value can be one of the following values: - * @arg @ref LL_TIM_OCIDLESTATE_LOW - * @arg @ref LL_TIM_OCIDLESTATE_HIGH - */ -__STATIC_INLINE uint32_t LL_TIM_OC_GetIdleState(TIM_TypeDef *TIMx, uint32_t Channel) -{ - register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel); - return (READ_BIT(TIMx->CR2, (TIM_CR2_OIS1 << SHIFT_TAB_OISx[iChannel])) >> SHIFT_TAB_OISx[iChannel]); -} - -/** - * @brief Enable fast mode for the output channel. - * @note Acts only if the channel is configured in PWM1 or PWM2 mode. - * @rmtoll CCMR1 OC1FE LL_TIM_OC_EnableFast\n - * CCMR1 OC2FE LL_TIM_OC_EnableFast\n - * CCMR2 OC3FE LL_TIM_OC_EnableFast\n - * CCMR2 OC4FE LL_TIM_OC_EnableFast - * @param TIMx Timer instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_TIM_CHANNEL_CH1 - * @arg @ref LL_TIM_CHANNEL_CH2 - * @arg @ref LL_TIM_CHANNEL_CH3 - * @arg @ref LL_TIM_CHANNEL_CH4 - * @retval None - */ -__STATIC_INLINE void LL_TIM_OC_EnableFast(TIM_TypeDef *TIMx, uint32_t Channel) -{ - register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel); - register uint32_t *pReg = (uint32_t *)((uint32_t)((uint32_t)(&TIMx->CCMR1) + OFFSET_TAB_CCMRx[iChannel])); - SET_BIT(*pReg, (TIM_CCMR1_OC1FE << SHIFT_TAB_OCxx[iChannel])); - -} - -/** - * @brief Disable fast mode for the output channel. - * @rmtoll CCMR1 OC1FE LL_TIM_OC_DisableFast\n - * CCMR1 OC2FE LL_TIM_OC_DisableFast\n - * CCMR2 OC3FE LL_TIM_OC_DisableFast\n - * CCMR2 OC4FE LL_TIM_OC_DisableFast - * @param TIMx Timer instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_TIM_CHANNEL_CH1 - * @arg @ref LL_TIM_CHANNEL_CH2 - * @arg @ref LL_TIM_CHANNEL_CH3 - * @arg @ref LL_TIM_CHANNEL_CH4 - * @retval None - */ -__STATIC_INLINE void LL_TIM_OC_DisableFast(TIM_TypeDef *TIMx, uint32_t Channel) -{ - register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel); - register uint32_t *pReg = (uint32_t *)((uint32_t)((uint32_t)(&TIMx->CCMR1) + OFFSET_TAB_CCMRx[iChannel])); - CLEAR_BIT(*pReg, (TIM_CCMR1_OC1FE << SHIFT_TAB_OCxx[iChannel])); - -} - -/** - * @brief Indicates whether fast mode is enabled for the output channel. - * @rmtoll CCMR1 OC1FE LL_TIM_OC_IsEnabledFast\n - * CCMR1 OC2FE LL_TIM_OC_IsEnabledFast\n - * CCMR2 OC3FE LL_TIM_OC_IsEnabledFast\n - * CCMR2 OC4FE LL_TIM_OC_IsEnabledFast\n - * @param TIMx Timer instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_TIM_CHANNEL_CH1 - * @arg @ref LL_TIM_CHANNEL_CH2 - * @arg @ref LL_TIM_CHANNEL_CH3 - * @arg @ref LL_TIM_CHANNEL_CH4 - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_TIM_OC_IsEnabledFast(TIM_TypeDef *TIMx, uint32_t Channel) -{ - register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel); - register uint32_t *pReg = (uint32_t *)((uint32_t)((uint32_t)(&TIMx->CCMR1) + OFFSET_TAB_CCMRx[iChannel])); - register uint32_t bitfield = TIM_CCMR1_OC1FE << SHIFT_TAB_OCxx[iChannel]; - return (READ_BIT(*pReg, bitfield) == bitfield); -} - -/** - * @brief Enable compare register (TIMx_CCRx) preload for the output channel. - * @rmtoll CCMR1 OC1PE LL_TIM_OC_EnablePreload\n - * CCMR1 OC2PE LL_TIM_OC_EnablePreload\n - * CCMR2 OC3PE LL_TIM_OC_EnablePreload\n - * CCMR2 OC4PE LL_TIM_OC_EnablePreload - * @param TIMx Timer instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_TIM_CHANNEL_CH1 - * @arg @ref LL_TIM_CHANNEL_CH2 - * @arg @ref LL_TIM_CHANNEL_CH3 - * @arg @ref LL_TIM_CHANNEL_CH4 - * @retval None - */ -__STATIC_INLINE void LL_TIM_OC_EnablePreload(TIM_TypeDef *TIMx, uint32_t Channel) -{ - register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel); - register uint32_t *pReg = (uint32_t *)((uint32_t)((uint32_t)(&TIMx->CCMR1) + OFFSET_TAB_CCMRx[iChannel])); - SET_BIT(*pReg, (TIM_CCMR1_OC1PE << SHIFT_TAB_OCxx[iChannel])); -} - -/** - * @brief Disable compare register (TIMx_CCRx) preload for the output channel. - * @rmtoll CCMR1 OC1PE LL_TIM_OC_DisablePreload\n - * CCMR1 OC2PE LL_TIM_OC_DisablePreload\n - * CCMR2 OC3PE LL_TIM_OC_DisablePreload\n - * CCMR2 OC4PE LL_TIM_OC_DisablePreload - * @param TIMx Timer instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_TIM_CHANNEL_CH1 - * @arg @ref LL_TIM_CHANNEL_CH2 - * @arg @ref LL_TIM_CHANNEL_CH3 - * @arg @ref LL_TIM_CHANNEL_CH4 - * @retval None - */ -__STATIC_INLINE void LL_TIM_OC_DisablePreload(TIM_TypeDef *TIMx, uint32_t Channel) -{ - register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel); - register uint32_t *pReg = (uint32_t *)((uint32_t)((uint32_t)(&TIMx->CCMR1) + OFFSET_TAB_CCMRx[iChannel])); - CLEAR_BIT(*pReg, (TIM_CCMR1_OC1PE << SHIFT_TAB_OCxx[iChannel])); -} - -/** - * @brief Indicates whether compare register (TIMx_CCRx) preload is enabled for the output channel. - * @rmtoll CCMR1 OC1PE LL_TIM_OC_IsEnabledPreload\n - * CCMR1 OC2PE LL_TIM_OC_IsEnabledPreload\n - * CCMR2 OC3PE LL_TIM_OC_IsEnabledPreload\n - * CCMR2 OC4PE LL_TIM_OC_IsEnabledPreload\n - * @param TIMx Timer instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_TIM_CHANNEL_CH1 - * @arg @ref LL_TIM_CHANNEL_CH2 - * @arg @ref LL_TIM_CHANNEL_CH3 - * @arg @ref LL_TIM_CHANNEL_CH4 - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_TIM_OC_IsEnabledPreload(TIM_TypeDef *TIMx, uint32_t Channel) -{ - register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel); - register uint32_t *pReg = (uint32_t *)((uint32_t)((uint32_t)(&TIMx->CCMR1) + OFFSET_TAB_CCMRx[iChannel])); - register uint32_t bitfield = TIM_CCMR1_OC1PE << SHIFT_TAB_OCxx[iChannel]; - return (READ_BIT(*pReg, bitfield) == bitfield); -} - -/** - * @brief Enable clearing the output channel on an external event. - * @note This function can only be used in Output compare and PWM modes. It does not work in Forced mode. - * @note Macro @ref IS_TIM_OCXREF_CLEAR_INSTANCE(TIMx) can be used to check whether - * or not a timer instance can clear the OCxREF signal on an external event. - * @rmtoll CCMR1 OC1CE LL_TIM_OC_EnableClear\n - * CCMR1 OC2CE LL_TIM_OC_EnableClear\n - * CCMR2 OC3CE LL_TIM_OC_EnableClear\n - * CCMR2 OC4CE LL_TIM_OC_EnableClear - * @param TIMx Timer instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_TIM_CHANNEL_CH1 - * @arg @ref LL_TIM_CHANNEL_CH2 - * @arg @ref LL_TIM_CHANNEL_CH3 - * @arg @ref LL_TIM_CHANNEL_CH4 - * @retval None - */ -__STATIC_INLINE void LL_TIM_OC_EnableClear(TIM_TypeDef *TIMx, uint32_t Channel) -{ - register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel); - register uint32_t *pReg = (uint32_t *)((uint32_t)((uint32_t)(&TIMx->CCMR1) + OFFSET_TAB_CCMRx[iChannel])); - SET_BIT(*pReg, (TIM_CCMR1_OC1CE << SHIFT_TAB_OCxx[iChannel])); -} - -/** - * @brief Disable clearing the output channel on an external event. - * @note Macro @ref IS_TIM_OCXREF_CLEAR_INSTANCE(TIMx) can be used to check whether - * or not a timer instance can clear the OCxREF signal on an external event. - * @rmtoll CCMR1 OC1CE LL_TIM_OC_DisableClear\n - * CCMR1 OC2CE LL_TIM_OC_DisableClear\n - * CCMR2 OC3CE LL_TIM_OC_DisableClear\n - * CCMR2 OC4CE LL_TIM_OC_DisableClear - * @param TIMx Timer instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_TIM_CHANNEL_CH1 - * @arg @ref LL_TIM_CHANNEL_CH2 - * @arg @ref LL_TIM_CHANNEL_CH3 - * @arg @ref LL_TIM_CHANNEL_CH4 - * @retval None - */ -__STATIC_INLINE void LL_TIM_OC_DisableClear(TIM_TypeDef *TIMx, uint32_t Channel) -{ - register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel); - register uint32_t *pReg = (uint32_t *)((uint32_t)((uint32_t)(&TIMx->CCMR1) + OFFSET_TAB_CCMRx[iChannel])); - CLEAR_BIT(*pReg, (TIM_CCMR1_OC1CE << SHIFT_TAB_OCxx[iChannel])); -} - -/** - * @brief Indicates clearing the output channel on an external event is enabled for the output channel. - * @note This function enables clearing the output channel on an external event. - * @note This function can only be used in Output compare and PWM modes. It does not work in Forced mode. - * @note Macro @ref IS_TIM_OCXREF_CLEAR_INSTANCE(TIMx) can be used to check whether - * or not a timer instance can clear the OCxREF signal on an external event. - * @rmtoll CCMR1 OC1CE LL_TIM_OC_IsEnabledClear\n - * CCMR1 OC2CE LL_TIM_OC_IsEnabledClear\n - * CCMR2 OC3CE LL_TIM_OC_IsEnabledClear\n - * CCMR2 OC4CE LL_TIM_OC_IsEnabledClear\n - * @param TIMx Timer instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_TIM_CHANNEL_CH1 - * @arg @ref LL_TIM_CHANNEL_CH2 - * @arg @ref LL_TIM_CHANNEL_CH3 - * @arg @ref LL_TIM_CHANNEL_CH4 - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_TIM_OC_IsEnabledClear(TIM_TypeDef *TIMx, uint32_t Channel) -{ - register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel); - register uint32_t *pReg = (uint32_t *)((uint32_t)((uint32_t)(&TIMx->CCMR1) + OFFSET_TAB_CCMRx[iChannel])); - register uint32_t bitfield = TIM_CCMR1_OC1CE << SHIFT_TAB_OCxx[iChannel]; - return (READ_BIT(*pReg, bitfield) == bitfield); -} - -/** - * @brief Set the dead-time delay (delay inserted between the rising edge of the OCxREF signal and the rising edge if the Ocx and OCxN signals). - * @note Macro @ref IS_TIM_BREAK_INSTANCE(TIMx) can be used to check whether or not - * dead-time insertion feature is supported by a timer instance. - * @note Helper macro @ref __LL_TIM_CALC_DEADTIME can be used to calculate the DeadTime parameter - * @rmtoll BDTR DTG LL_TIM_OC_SetDeadTime - * @param TIMx Timer instance - * @param DeadTime between Min_Data=0 and Max_Data=255 - * @retval None - */ -__STATIC_INLINE void LL_TIM_OC_SetDeadTime(TIM_TypeDef *TIMx, uint32_t DeadTime) -{ - MODIFY_REG(TIMx->BDTR, TIM_BDTR_DTG, DeadTime); -} - -/** - * @brief Set compare value for output channel 1 (TIMx_CCR1). - * @note Macro @ref IS_TIM_CC1_INSTANCE(TIMx) can be used to check whether or not - * output channel 1 is supported by a timer instance. - * @rmtoll CCR1 CCR1 LL_TIM_OC_SetCompareCH1 - * @param TIMx Timer instance - * @param CompareValue between Min_Data=0 and Max_Data=65535 - * @retval None - */ -__STATIC_INLINE void LL_TIM_OC_SetCompareCH1(TIM_TypeDef *TIMx, uint32_t CompareValue) -{ - WRITE_REG(TIMx->CCR1, CompareValue); -} - -/** - * @brief Set compare value for output channel 2 (TIMx_CCR2). - * @note Macro @ref IS_TIM_CC2_INSTANCE(TIMx) can be used to check whether or not - * output channel 2 is supported by a timer instance. - * @rmtoll CCR2 CCR2 LL_TIM_OC_SetCompareCH2 - * @param TIMx Timer instance - * @param CompareValue between Min_Data=0 and Max_Data=65535 - * @retval None - */ -__STATIC_INLINE void LL_TIM_OC_SetCompareCH2(TIM_TypeDef *TIMx, uint32_t CompareValue) -{ - WRITE_REG(TIMx->CCR2, CompareValue); -} - -/** - * @brief Set compare value for output channel 3 (TIMx_CCR3). - * @note Macro @ref IS_TIM_CC3_INSTANCE(TIMx) can be used to check whether or not - * output channel is supported by a timer instance. - * @rmtoll CCR3 CCR3 LL_TIM_OC_SetCompareCH3 - * @param TIMx Timer instance - * @param CompareValue between Min_Data=0 and Max_Data=65535 - * @retval None - */ -__STATIC_INLINE void LL_TIM_OC_SetCompareCH3(TIM_TypeDef *TIMx, uint32_t CompareValue) -{ - WRITE_REG(TIMx->CCR3, CompareValue); -} - -/** - * @brief Set compare value for output channel 4 (TIMx_CCR4). - * @note Macro @ref IS_TIM_CC4_INSTANCE(TIMx) can be used to check whether or not - * output channel 4 is supported by a timer instance. - * @rmtoll CCR4 CCR4 LL_TIM_OC_SetCompareCH4 - * @param TIMx Timer instance - * @param CompareValue between Min_Data=0 and Max_Data=65535 - * @retval None - */ -__STATIC_INLINE void LL_TIM_OC_SetCompareCH4(TIM_TypeDef *TIMx, uint32_t CompareValue) -{ - WRITE_REG(TIMx->CCR4, CompareValue); -} - -/** - * @brief Get compare value (TIMx_CCR1) set for output channel 1. - * @note Macro @ref IS_TIM_CC1_INSTANCE(TIMx) can be used to check whether or not - * output channel 1 is supported by a timer instance. - * @rmtoll CCR1 CCR1 LL_TIM_OC_GetCompareCH1 - * @param TIMx Timer instance - * @retval CompareValue (between Min_Data=0 and Max_Data=65535) - */ -__STATIC_INLINE uint32_t LL_TIM_OC_GetCompareCH1(TIM_TypeDef *TIMx) -{ - return (uint32_t)(READ_REG(TIMx->CCR1)); -} - -/** - * @brief Get compare value (TIMx_CCR2) set for output channel 2. - * @note Macro @ref IS_TIM_CC2_INSTANCE(TIMx) can be used to check whether or not - * output channel 2 is supported by a timer instance. - * @rmtoll CCR2 CCR2 LL_TIM_OC_GetCompareCH2 - * @param TIMx Timer instance - * @retval CompareValue (between Min_Data=0 and Max_Data=65535) - */ -__STATIC_INLINE uint32_t LL_TIM_OC_GetCompareCH2(TIM_TypeDef *TIMx) -{ - return (uint32_t)(READ_REG(TIMx->CCR2)); -} - -/** - * @brief Get compare value (TIMx_CCR3) set for output channel 3. - * @note Macro @ref IS_TIM_CC3_INSTANCE(TIMx) can be used to check whether or not - * output channel 3 is supported by a timer instance. - * @rmtoll CCR3 CCR3 LL_TIM_OC_GetCompareCH3 - * @param TIMx Timer instance - * @retval CompareValue (between Min_Data=0 and Max_Data=65535) - */ -__STATIC_INLINE uint32_t LL_TIM_OC_GetCompareCH3(TIM_TypeDef *TIMx) -{ - return (uint32_t)(READ_REG(TIMx->CCR3)); -} - -/** - * @brief Get compare value (TIMx_CCR4) set for output channel 4. - * @note Macro @ref IS_TIM_CC4_INSTANCE(TIMx) can be used to check whether or not - * output channel 4 is supported by a timer instance. - * @rmtoll CCR4 CCR4 LL_TIM_OC_GetCompareCH4 - * @param TIMx Timer instance - * @retval CompareValue (between Min_Data=0 and Max_Data=65535) - */ -__STATIC_INLINE uint32_t LL_TIM_OC_GetCompareCH4(TIM_TypeDef *TIMx) -{ - return (uint32_t)(READ_REG(TIMx->CCR4)); -} - -/** - * @} - */ - -/** @defgroup TIM_LL_EF_Input_Channel Input channel configuration - * @{ - */ -/** - * @brief Configure input channel. - * @rmtoll CCMR1 CC1S LL_TIM_IC_Config\n - * CCMR1 IC1PSC LL_TIM_IC_Config\n - * CCMR1 IC1F LL_TIM_IC_Config\n - * CCMR1 CC2S LL_TIM_IC_Config\n - * CCMR1 IC2PSC LL_TIM_IC_Config\n - * CCMR1 IC2F LL_TIM_IC_Config\n - * CCMR2 CC3S LL_TIM_IC_Config\n - * CCMR2 IC3PSC LL_TIM_IC_Config\n - * CCMR2 IC3F LL_TIM_IC_Config\n - * CCMR2 CC4S LL_TIM_IC_Config\n - * CCMR2 IC4PSC LL_TIM_IC_Config\n - * CCMR2 IC4F LL_TIM_IC_Config\n - * CCER CC1P LL_TIM_IC_Config\n - * CCER CC1NP LL_TIM_IC_Config\n - * CCER CC2P LL_TIM_IC_Config\n - * CCER CC2NP LL_TIM_IC_Config\n - * CCER CC3P LL_TIM_IC_Config\n - * CCER CC3NP LL_TIM_IC_Config\n - * CCER CC4P LL_TIM_IC_Config\n - * @param TIMx Timer instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_TIM_CHANNEL_CH1 - * @arg @ref LL_TIM_CHANNEL_CH2 - * @arg @ref LL_TIM_CHANNEL_CH3 - * @arg @ref LL_TIM_CHANNEL_CH4 - * @param Configuration This parameter must be a combination of all the following values: - * @arg @ref LL_TIM_ACTIVEINPUT_DIRECTTI or @ref LL_TIM_ACTIVEINPUT_INDIRECTTI or @ref LL_TIM_ACTIVEINPUT_TRC - * @arg @ref LL_TIM_ICPSC_DIV1 or ... or @ref LL_TIM_ICPSC_DIV8 - * @arg @ref LL_TIM_IC_FILTER_FDIV1 or ... or @ref LL_TIM_IC_FILTER_FDIV32_N8 - * @arg @ref LL_TIM_IC_POLARITY_RISING or @ref LL_TIM_IC_POLARITY_FALLING - * @retval None - */ -__STATIC_INLINE void LL_TIM_IC_Config(TIM_TypeDef *TIMx, uint32_t Channel, uint32_t Configuration) -{ - register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel); - register uint32_t *pReg = (uint32_t *)((uint32_t)((uint32_t)(&TIMx->CCMR1) + OFFSET_TAB_CCMRx[iChannel])); - MODIFY_REG(*pReg, ((TIM_CCMR1_IC1F | TIM_CCMR1_IC1PSC | TIM_CCMR1_CC1S) << SHIFT_TAB_ICxx[iChannel]), - ((Configuration >> 16U) & (TIM_CCMR1_IC1F | TIM_CCMR1_IC1PSC | TIM_CCMR1_CC1S)) << SHIFT_TAB_ICxx[iChannel]); - MODIFY_REG(TIMx->CCER, ((TIM_CCER_CC1NP | TIM_CCER_CC1P) << SHIFT_TAB_CCxP[iChannel]), - (Configuration & (TIM_CCER_CC1NP | TIM_CCER_CC1P)) << SHIFT_TAB_CCxP[iChannel]); -} - -/** - * @brief Set the active input. - * @rmtoll CCMR1 CC1S LL_TIM_IC_SetActiveInput\n - * CCMR1 CC2S LL_TIM_IC_SetActiveInput\n - * CCMR2 CC3S LL_TIM_IC_SetActiveInput\n - * CCMR2 CC4S LL_TIM_IC_SetActiveInput - * @param TIMx Timer instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_TIM_CHANNEL_CH1 - * @arg @ref LL_TIM_CHANNEL_CH2 - * @arg @ref LL_TIM_CHANNEL_CH3 - * @arg @ref LL_TIM_CHANNEL_CH4 - * @param ICActiveInput This parameter can be one of the following values: - * @arg @ref LL_TIM_ACTIVEINPUT_DIRECTTI - * @arg @ref LL_TIM_ACTIVEINPUT_INDIRECTTI - * @arg @ref LL_TIM_ACTIVEINPUT_TRC - * @retval None - */ -__STATIC_INLINE void LL_TIM_IC_SetActiveInput(TIM_TypeDef *TIMx, uint32_t Channel, uint32_t ICActiveInput) -{ - register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel); - register uint32_t *pReg = (uint32_t *)((uint32_t)((uint32_t)(&TIMx->CCMR1) + OFFSET_TAB_CCMRx[iChannel])); - MODIFY_REG(*pReg, ((TIM_CCMR1_CC1S) << SHIFT_TAB_ICxx[iChannel]), (ICActiveInput >> 16U) << SHIFT_TAB_ICxx[iChannel]); -} - -/** - * @brief Get the current active input. - * @rmtoll CCMR1 CC1S LL_TIM_IC_GetActiveInput\n - * CCMR1 CC2S LL_TIM_IC_GetActiveInput\n - * CCMR2 CC3S LL_TIM_IC_GetActiveInput\n - * CCMR2 CC4S LL_TIM_IC_GetActiveInput - * @param TIMx Timer instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_TIM_CHANNEL_CH1 - * @arg @ref LL_TIM_CHANNEL_CH2 - * @arg @ref LL_TIM_CHANNEL_CH3 - * @arg @ref LL_TIM_CHANNEL_CH4 - * @retval Returned value can be one of the following values: - * @arg @ref LL_TIM_ACTIVEINPUT_DIRECTTI - * @arg @ref LL_TIM_ACTIVEINPUT_INDIRECTTI - * @arg @ref LL_TIM_ACTIVEINPUT_TRC - */ -__STATIC_INLINE uint32_t LL_TIM_IC_GetActiveInput(TIM_TypeDef *TIMx, uint32_t Channel) -{ - register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel); - register uint32_t *pReg = (uint32_t *)((uint32_t)((uint32_t)(&TIMx->CCMR1) + OFFSET_TAB_CCMRx[iChannel])); - return ((READ_BIT(*pReg, ((TIM_CCMR1_CC1S) << SHIFT_TAB_ICxx[iChannel])) >> SHIFT_TAB_ICxx[iChannel]) << 16U); -} - -/** - * @brief Set the prescaler of input channel. - * @rmtoll CCMR1 IC1PSC LL_TIM_IC_SetPrescaler\n - * CCMR1 IC2PSC LL_TIM_IC_SetPrescaler\n - * CCMR2 IC3PSC LL_TIM_IC_SetPrescaler\n - * CCMR2 IC4PSC LL_TIM_IC_SetPrescaler - * @param TIMx Timer instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_TIM_CHANNEL_CH1 - * @arg @ref LL_TIM_CHANNEL_CH2 - * @arg @ref LL_TIM_CHANNEL_CH3 - * @arg @ref LL_TIM_CHANNEL_CH4 - * @param ICPrescaler This parameter can be one of the following values: - * @arg @ref LL_TIM_ICPSC_DIV1 - * @arg @ref LL_TIM_ICPSC_DIV2 - * @arg @ref LL_TIM_ICPSC_DIV4 - * @arg @ref LL_TIM_ICPSC_DIV8 - * @retval None - */ -__STATIC_INLINE void LL_TIM_IC_SetPrescaler(TIM_TypeDef *TIMx, uint32_t Channel, uint32_t ICPrescaler) -{ - register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel); - register uint32_t *pReg = (uint32_t *)((uint32_t)((uint32_t)(&TIMx->CCMR1) + OFFSET_TAB_CCMRx[iChannel])); - MODIFY_REG(*pReg, ((TIM_CCMR1_IC1PSC) << SHIFT_TAB_ICxx[iChannel]), (ICPrescaler >> 16U) << SHIFT_TAB_ICxx[iChannel]); -} - -/** - * @brief Get the current prescaler value acting on an input channel. - * @rmtoll CCMR1 IC1PSC LL_TIM_IC_GetPrescaler\n - * CCMR1 IC2PSC LL_TIM_IC_GetPrescaler\n - * CCMR2 IC3PSC LL_TIM_IC_GetPrescaler\n - * CCMR2 IC4PSC LL_TIM_IC_GetPrescaler - * @param TIMx Timer instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_TIM_CHANNEL_CH1 - * @arg @ref LL_TIM_CHANNEL_CH2 - * @arg @ref LL_TIM_CHANNEL_CH3 - * @arg @ref LL_TIM_CHANNEL_CH4 - * @retval Returned value can be one of the following values: - * @arg @ref LL_TIM_ICPSC_DIV1 - * @arg @ref LL_TIM_ICPSC_DIV2 - * @arg @ref LL_TIM_ICPSC_DIV4 - * @arg @ref LL_TIM_ICPSC_DIV8 - */ -__STATIC_INLINE uint32_t LL_TIM_IC_GetPrescaler(TIM_TypeDef *TIMx, uint32_t Channel) -{ - register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel); - register uint32_t *pReg = (uint32_t *)((uint32_t)((uint32_t)(&TIMx->CCMR1) + OFFSET_TAB_CCMRx[iChannel])); - return ((READ_BIT(*pReg, ((TIM_CCMR1_IC1PSC) << SHIFT_TAB_ICxx[iChannel])) >> SHIFT_TAB_ICxx[iChannel]) << 16U); -} - -/** - * @brief Set the input filter duration. - * @rmtoll CCMR1 IC1F LL_TIM_IC_SetFilter\n - * CCMR1 IC2F LL_TIM_IC_SetFilter\n - * CCMR2 IC3F LL_TIM_IC_SetFilter\n - * CCMR2 IC4F LL_TIM_IC_SetFilter - * @param TIMx Timer instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_TIM_CHANNEL_CH1 - * @arg @ref LL_TIM_CHANNEL_CH2 - * @arg @ref LL_TIM_CHANNEL_CH3 - * @arg @ref LL_TIM_CHANNEL_CH4 - * @param ICFilter This parameter can be one of the following values: - * @arg @ref LL_TIM_IC_FILTER_FDIV1 - * @arg @ref LL_TIM_IC_FILTER_FDIV1_N2 - * @arg @ref LL_TIM_IC_FILTER_FDIV1_N4 - * @arg @ref LL_TIM_IC_FILTER_FDIV1_N8 - * @arg @ref LL_TIM_IC_FILTER_FDIV2_N6 - * @arg @ref LL_TIM_IC_FILTER_FDIV2_N8 - * @arg @ref LL_TIM_IC_FILTER_FDIV4_N6 - * @arg @ref LL_TIM_IC_FILTER_FDIV4_N8 - * @arg @ref LL_TIM_IC_FILTER_FDIV8_N6 - * @arg @ref LL_TIM_IC_FILTER_FDIV8_N8 - * @arg @ref LL_TIM_IC_FILTER_FDIV16_N5 - * @arg @ref LL_TIM_IC_FILTER_FDIV16_N6 - * @arg @ref LL_TIM_IC_FILTER_FDIV16_N8 - * @arg @ref LL_TIM_IC_FILTER_FDIV32_N5 - * @arg @ref LL_TIM_IC_FILTER_FDIV32_N6 - * @arg @ref LL_TIM_IC_FILTER_FDIV32_N8 - * @retval None - */ -__STATIC_INLINE void LL_TIM_IC_SetFilter(TIM_TypeDef *TIMx, uint32_t Channel, uint32_t ICFilter) -{ - register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel); - register uint32_t *pReg = (uint32_t *)((uint32_t)((uint32_t)(&TIMx->CCMR1) + OFFSET_TAB_CCMRx[iChannel])); - MODIFY_REG(*pReg, ((TIM_CCMR1_IC1F) << SHIFT_TAB_ICxx[iChannel]), (ICFilter >> 16U) << SHIFT_TAB_ICxx[iChannel]); -} - -/** - * @brief Get the input filter duration. - * @rmtoll CCMR1 IC1F LL_TIM_IC_GetFilter\n - * CCMR1 IC2F LL_TIM_IC_GetFilter\n - * CCMR2 IC3F LL_TIM_IC_GetFilter\n - * CCMR2 IC4F LL_TIM_IC_GetFilter - * @param TIMx Timer instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_TIM_CHANNEL_CH1 - * @arg @ref LL_TIM_CHANNEL_CH2 - * @arg @ref LL_TIM_CHANNEL_CH3 - * @arg @ref LL_TIM_CHANNEL_CH4 - * @retval Returned value can be one of the following values: - * @arg @ref LL_TIM_IC_FILTER_FDIV1 - * @arg @ref LL_TIM_IC_FILTER_FDIV1_N2 - * @arg @ref LL_TIM_IC_FILTER_FDIV1_N4 - * @arg @ref LL_TIM_IC_FILTER_FDIV1_N8 - * @arg @ref LL_TIM_IC_FILTER_FDIV2_N6 - * @arg @ref LL_TIM_IC_FILTER_FDIV2_N8 - * @arg @ref LL_TIM_IC_FILTER_FDIV4_N6 - * @arg @ref LL_TIM_IC_FILTER_FDIV4_N8 - * @arg @ref LL_TIM_IC_FILTER_FDIV8_N6 - * @arg @ref LL_TIM_IC_FILTER_FDIV8_N8 - * @arg @ref LL_TIM_IC_FILTER_FDIV16_N5 - * @arg @ref LL_TIM_IC_FILTER_FDIV16_N6 - * @arg @ref LL_TIM_IC_FILTER_FDIV16_N8 - * @arg @ref LL_TIM_IC_FILTER_FDIV32_N5 - * @arg @ref LL_TIM_IC_FILTER_FDIV32_N6 - * @arg @ref LL_TIM_IC_FILTER_FDIV32_N8 - */ -__STATIC_INLINE uint32_t LL_TIM_IC_GetFilter(TIM_TypeDef *TIMx, uint32_t Channel) -{ - register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel); - register uint32_t *pReg = (uint32_t *)((uint32_t)((uint32_t)(&TIMx->CCMR1) + OFFSET_TAB_CCMRx[iChannel])); - return ((READ_BIT(*pReg, ((TIM_CCMR1_IC1F) << SHIFT_TAB_ICxx[iChannel])) >> SHIFT_TAB_ICxx[iChannel]) << 16U); -} - -/** - * @brief Set the input channel polarity. - * @rmtoll CCER CC1P LL_TIM_IC_SetPolarity\n - * CCER CC1NP LL_TIM_IC_SetPolarity\n - * CCER CC2P LL_TIM_IC_SetPolarity\n - * CCER CC2NP LL_TIM_IC_SetPolarity\n - * CCER CC3P LL_TIM_IC_SetPolarity\n - * CCER CC3NP LL_TIM_IC_SetPolarity\n - * CCER CC4P LL_TIM_IC_SetPolarity\n - * @param TIMx Timer instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_TIM_CHANNEL_CH1 - * @arg @ref LL_TIM_CHANNEL_CH2 - * @arg @ref LL_TIM_CHANNEL_CH3 - * @arg @ref LL_TIM_CHANNEL_CH4 - * @param ICPolarity This parameter can be one of the following values: - * @arg @ref LL_TIM_IC_POLARITY_RISING - * @arg @ref LL_TIM_IC_POLARITY_FALLING - * @retval None - */ -__STATIC_INLINE void LL_TIM_IC_SetPolarity(TIM_TypeDef *TIMx, uint32_t Channel, uint32_t ICPolarity) -{ - register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel); - MODIFY_REG(TIMx->CCER, ((TIM_CCER_CC1NP | TIM_CCER_CC1P) << SHIFT_TAB_CCxP[iChannel]), - ICPolarity << SHIFT_TAB_CCxP[iChannel]); -} - -/** - * @brief Get the current input channel polarity. - * @rmtoll CCER CC1P LL_TIM_IC_GetPolarity\n - * CCER CC1NP LL_TIM_IC_GetPolarity\n - * CCER CC2P LL_TIM_IC_GetPolarity\n - * CCER CC2NP LL_TIM_IC_GetPolarity\n - * CCER CC3P LL_TIM_IC_GetPolarity\n - * CCER CC3NP LL_TIM_IC_GetPolarity\n - * CCER CC4P LL_TIM_IC_GetPolarity\n - * @param TIMx Timer instance - * @param Channel This parameter can be one of the following values: - * @arg @ref LL_TIM_CHANNEL_CH1 - * @arg @ref LL_TIM_CHANNEL_CH2 - * @arg @ref LL_TIM_CHANNEL_CH3 - * @arg @ref LL_TIM_CHANNEL_CH4 - * @retval Returned value can be one of the following values: - * @arg @ref LL_TIM_IC_POLARITY_RISING - * @arg @ref LL_TIM_IC_POLARITY_FALLING - */ -__STATIC_INLINE uint32_t LL_TIM_IC_GetPolarity(TIM_TypeDef *TIMx, uint32_t Channel) -{ - register uint8_t iChannel = TIM_GET_CHANNEL_INDEX(Channel); - return (READ_BIT(TIMx->CCER, ((TIM_CCER_CC1NP | TIM_CCER_CC1P) << SHIFT_TAB_CCxP[iChannel])) >> - SHIFT_TAB_CCxP[iChannel]); -} - -/** - * @brief Connect the TIMx_CH1, CH2 and CH3 pins to the TI1 input (XOR combination). - * @note Macro @ref IS_TIM_XOR_INSTANCE(TIMx) can be used to check whether or not - * a timer instance provides an XOR input. - * @rmtoll CR2 TI1S LL_TIM_IC_EnableXORCombination - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_IC_EnableXORCombination(TIM_TypeDef *TIMx) -{ - SET_BIT(TIMx->CR2, TIM_CR2_TI1S); -} - -/** - * @brief Disconnect the TIMx_CH1, CH2 and CH3 pins from the TI1 input. - * @note Macro @ref IS_TIM_XOR_INSTANCE(TIMx) can be used to check whether or not - * a timer instance provides an XOR input. - * @rmtoll CR2 TI1S LL_TIM_IC_DisableXORCombination - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_IC_DisableXORCombination(TIM_TypeDef *TIMx) -{ - CLEAR_BIT(TIMx->CR2, TIM_CR2_TI1S); -} - -/** - * @brief Indicates whether the TIMx_CH1, CH2 and CH3 pins are connectected to the TI1 input. - * @note Macro @ref IS_TIM_XOR_INSTANCE(TIMx) can be used to check whether or not - * a timer instance provides an XOR input. - * @rmtoll CR2 TI1S LL_TIM_IC_IsEnabledXORCombination - * @param TIMx Timer instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_TIM_IC_IsEnabledXORCombination(TIM_TypeDef *TIMx) -{ - return (READ_BIT(TIMx->CR2, TIM_CR2_TI1S) == (TIM_CR2_TI1S)); -} - -/** - * @brief Get captured value for input channel 1. - * @note Macro @ref IS_TIM_CC1_INSTANCE(TIMx) can be used to check whether or not - * input channel 1 is supported by a timer instance. - * @rmtoll CCR1 CCR1 LL_TIM_IC_GetCaptureCH1 - * @param TIMx Timer instance - * @retval CapturedValue (between Min_Data=0 and Max_Data=65535) - */ -__STATIC_INLINE uint32_t LL_TIM_IC_GetCaptureCH1(TIM_TypeDef *TIMx) -{ - return (uint32_t)(READ_REG(TIMx->CCR1)); -} - -/** - * @brief Get captured value for input channel 2. - * @note Macro @ref IS_TIM_CC2_INSTANCE(TIMx) can be used to check whether or not - * input channel 2 is supported by a timer instance. - * @rmtoll CCR2 CCR2 LL_TIM_IC_GetCaptureCH2 - * @param TIMx Timer instance - * @retval CapturedValue (between Min_Data=0 and Max_Data=65535) - */ -__STATIC_INLINE uint32_t LL_TIM_IC_GetCaptureCH2(TIM_TypeDef *TIMx) -{ - return (uint32_t)(READ_REG(TIMx->CCR2)); -} - -/** - * @brief Get captured value for input channel 3. - * @note Macro @ref IS_TIM_CC3_INSTANCE(TIMx) can be used to check whether or not - * input channel 3 is supported by a timer instance. - * @rmtoll CCR3 CCR3 LL_TIM_IC_GetCaptureCH3 - * @param TIMx Timer instance - * @retval CapturedValue (between Min_Data=0 and Max_Data=65535) - */ -__STATIC_INLINE uint32_t LL_TIM_IC_GetCaptureCH3(TIM_TypeDef *TIMx) -{ - return (uint32_t)(READ_REG(TIMx->CCR3)); -} - -/** - * @brief Get captured value for input channel 4. - * @note Macro @ref IS_TIM_CC4_INSTANCE(TIMx) can be used to check whether or not - * input channel 4 is supported by a timer instance. - * @rmtoll CCR4 CCR4 LL_TIM_IC_GetCaptureCH4 - * @param TIMx Timer instance - * @retval CapturedValue (between Min_Data=0 and Max_Data=65535) - */ -__STATIC_INLINE uint32_t LL_TIM_IC_GetCaptureCH4(TIM_TypeDef *TIMx) -{ - return (uint32_t)(READ_REG(TIMx->CCR4)); -} - -/** - * @} - */ - -/** @defgroup TIM_LL_EF_Clock_Selection Counter clock selection - * @{ - */ -/** - * @brief Enable external clock mode 2. - * @note When external clock mode 2 is enabled the counter is clocked by any active edge on the ETRF signal. - * @note Macro @ref IS_TIM_CLOCKSOURCE_ETRMODE2_INSTANCE(TIMx) can be used to check - * whether or not a timer instance supports external clock mode2. - * @rmtoll SMCR ECE LL_TIM_EnableExternalClock - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_EnableExternalClock(TIM_TypeDef *TIMx) -{ - SET_BIT(TIMx->SMCR, TIM_SMCR_ECE); -} - -/** - * @brief Disable external clock mode 2. - * @note Macro @ref IS_TIM_CLOCKSOURCE_ETRMODE2_INSTANCE(TIMx) can be used to check - * whether or not a timer instance supports external clock mode2. - * @rmtoll SMCR ECE LL_TIM_DisableExternalClock - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_DisableExternalClock(TIM_TypeDef *TIMx) -{ - CLEAR_BIT(TIMx->SMCR, TIM_SMCR_ECE); -} - -/** - * @brief Indicate whether external clock mode 2 is enabled. - * @note Macro @ref IS_TIM_CLOCKSOURCE_ETRMODE2_INSTANCE(TIMx) can be used to check - * whether or not a timer instance supports external clock mode2. - * @rmtoll SMCR ECE LL_TIM_IsEnabledExternalClock - * @param TIMx Timer instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_TIM_IsEnabledExternalClock(TIM_TypeDef *TIMx) -{ - return (READ_BIT(TIMx->SMCR, TIM_SMCR_ECE) == (TIM_SMCR_ECE)); -} - -/** - * @brief Set the clock source of the counter clock. - * @note when selected clock source is external clock mode 1, the timer input - * the external clock is applied is selected by calling the @ref LL_TIM_SetTriggerInput() - * function. This timer input must be configured by calling - * the @ref LL_TIM_IC_Config() function. - * @note Macro @ref IS_TIM_CLOCKSOURCE_ETRMODE1_INSTANCE(TIMx) can be used to check - * whether or not a timer instance supports external clock mode1. - * @note Macro @ref IS_TIM_CLOCKSOURCE_ETRMODE2_INSTANCE(TIMx) can be used to check - * whether or not a timer instance supports external clock mode2. - * @rmtoll SMCR SMS LL_TIM_SetClockSource\n - * SMCR ECE LL_TIM_SetClockSource - * @param TIMx Timer instance - * @param ClockSource This parameter can be one of the following values: - * @arg @ref LL_TIM_CLOCKSOURCE_INTERNAL - * @arg @ref LL_TIM_CLOCKSOURCE_EXT_MODE1 - * @arg @ref LL_TIM_CLOCKSOURCE_EXT_MODE2 - * @retval None - */ -__STATIC_INLINE void LL_TIM_SetClockSource(TIM_TypeDef *TIMx, uint32_t ClockSource) -{ - MODIFY_REG(TIMx->SMCR, TIM_SMCR_SMS | TIM_SMCR_ECE, ClockSource); -} - -/** - * @brief Set the encoder interface mode. - * @note Macro @ref IS_TIM_ENCODER_INTERFACE_INSTANCE(TIMx) can be used to check - * whether or not a timer instance supports the encoder mode. - * @rmtoll SMCR SMS LL_TIM_SetEncoderMode - * @param TIMx Timer instance - * @param EncoderMode This parameter can be one of the following values: - * @arg @ref LL_TIM_ENCODERMODE_X2_TI1 - * @arg @ref LL_TIM_ENCODERMODE_X2_TI2 - * @arg @ref LL_TIM_ENCODERMODE_X4_TI12 - * @retval None - */ -__STATIC_INLINE void LL_TIM_SetEncoderMode(TIM_TypeDef *TIMx, uint32_t EncoderMode) -{ - MODIFY_REG(TIMx->SMCR, TIM_SMCR_SMS, EncoderMode); -} - -/** - * @} - */ - -/** @defgroup TIM_LL_EF_Timer_Synchronization Timer synchronisation configuration - * @{ - */ -/** - * @brief Set the trigger output (TRGO) used for timer synchronization . - * @note Macro @ref IS_TIM_MASTER_INSTANCE(TIMx) can be used to check - * whether or not a timer instance can operate as a master timer. - * @rmtoll CR2 MMS LL_TIM_SetTriggerOutput - * @param TIMx Timer instance - * @param TimerSynchronization This parameter can be one of the following values: - * @arg @ref LL_TIM_TRGO_RESET - * @arg @ref LL_TIM_TRGO_ENABLE - * @arg @ref LL_TIM_TRGO_UPDATE - * @arg @ref LL_TIM_TRGO_CC1IF - * @arg @ref LL_TIM_TRGO_OC1REF - * @arg @ref LL_TIM_TRGO_OC2REF - * @arg @ref LL_TIM_TRGO_OC3REF - * @arg @ref LL_TIM_TRGO_OC4REF - * @retval None - */ -__STATIC_INLINE void LL_TIM_SetTriggerOutput(TIM_TypeDef *TIMx, uint32_t TimerSynchronization) -{ - MODIFY_REG(TIMx->CR2, TIM_CR2_MMS, TimerSynchronization); -} - -/** - * @brief Set the synchronization mode of a slave timer. - * @note Macro @ref IS_TIM_SLAVE_INSTANCE(TIMx) can be used to check whether or not - * a timer instance can operate as a slave timer. - * @rmtoll SMCR SMS LL_TIM_SetSlaveMode - * @param TIMx Timer instance - * @param SlaveMode This parameter can be one of the following values: - * @arg @ref LL_TIM_SLAVEMODE_DISABLED - * @arg @ref LL_TIM_SLAVEMODE_RESET - * @arg @ref LL_TIM_SLAVEMODE_GATED - * @arg @ref LL_TIM_SLAVEMODE_TRIGGER - * @retval None - */ -__STATIC_INLINE void LL_TIM_SetSlaveMode(TIM_TypeDef *TIMx, uint32_t SlaveMode) -{ - MODIFY_REG(TIMx->SMCR, TIM_SMCR_SMS, SlaveMode); -} - -/** - * @brief Set the selects the trigger input to be used to synchronize the counter. - * @note Macro @ref IS_TIM_SLAVE_INSTANCE(TIMx) can be used to check whether or not - * a timer instance can operate as a slave timer. - * @rmtoll SMCR TS LL_TIM_SetTriggerInput - * @param TIMx Timer instance - * @param TriggerInput This parameter can be one of the following values: - * @arg @ref LL_TIM_TS_ITR0 - * @arg @ref LL_TIM_TS_ITR1 - * @arg @ref LL_TIM_TS_ITR2 - * @arg @ref LL_TIM_TS_ITR3 - * @arg @ref LL_TIM_TS_TI1F_ED - * @arg @ref LL_TIM_TS_TI1FP1 - * @arg @ref LL_TIM_TS_TI2FP2 - * @arg @ref LL_TIM_TS_ETRF - * @retval None - */ -__STATIC_INLINE void LL_TIM_SetTriggerInput(TIM_TypeDef *TIMx, uint32_t TriggerInput) -{ - MODIFY_REG(TIMx->SMCR, TIM_SMCR_TS, TriggerInput); -} - -/** - * @brief Enable the Master/Slave mode. - * @note Macro @ref IS_TIM_SLAVE_INSTANCE(TIMx) can be used to check whether or not - * a timer instance can operate as a slave timer. - * @rmtoll SMCR MSM LL_TIM_EnableMasterSlaveMode - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_EnableMasterSlaveMode(TIM_TypeDef *TIMx) -{ - SET_BIT(TIMx->SMCR, TIM_SMCR_MSM); -} - -/** - * @brief Disable the Master/Slave mode. - * @note Macro @ref IS_TIM_SLAVE_INSTANCE(TIMx) can be used to check whether or not - * a timer instance can operate as a slave timer. - * @rmtoll SMCR MSM LL_TIM_DisableMasterSlaveMode - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_DisableMasterSlaveMode(TIM_TypeDef *TIMx) -{ - CLEAR_BIT(TIMx->SMCR, TIM_SMCR_MSM); -} - -/** - * @brief Indicates whether the Master/Slave mode is enabled. - * @note Macro @ref IS_TIM_SLAVE_INSTANCE(TIMx) can be used to check whether or not - * a timer instance can operate as a slave timer. - * @rmtoll SMCR MSM LL_TIM_IsEnabledMasterSlaveMode - * @param TIMx Timer instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_TIM_IsEnabledMasterSlaveMode(TIM_TypeDef *TIMx) -{ - return (READ_BIT(TIMx->SMCR, TIM_SMCR_MSM) == (TIM_SMCR_MSM)); -} - -/** - * @brief Configure the external trigger (ETR) input. - * @note Macro @ref IS_TIM_ETR_INSTANCE(TIMx) can be used to check whether or not - * a timer instance provides an external trigger input. - * @rmtoll SMCR ETP LL_TIM_ConfigETR\n - * SMCR ETPS LL_TIM_ConfigETR\n - * SMCR ETF LL_TIM_ConfigETR - * @param TIMx Timer instance - * @param ETRPolarity This parameter can be one of the following values: - * @arg @ref LL_TIM_ETR_POLARITY_NONINVERTED - * @arg @ref LL_TIM_ETR_POLARITY_INVERTED - * @param ETRPrescaler This parameter can be one of the following values: - * @arg @ref LL_TIM_ETR_PRESCALER_DIV1 - * @arg @ref LL_TIM_ETR_PRESCALER_DIV2 - * @arg @ref LL_TIM_ETR_PRESCALER_DIV4 - * @arg @ref LL_TIM_ETR_PRESCALER_DIV8 - * @param ETRFilter This parameter can be one of the following values: - * @arg @ref LL_TIM_ETR_FILTER_FDIV1 - * @arg @ref LL_TIM_ETR_FILTER_FDIV1_N2 - * @arg @ref LL_TIM_ETR_FILTER_FDIV1_N4 - * @arg @ref LL_TIM_ETR_FILTER_FDIV1_N8 - * @arg @ref LL_TIM_ETR_FILTER_FDIV2_N6 - * @arg @ref LL_TIM_ETR_FILTER_FDIV2_N8 - * @arg @ref LL_TIM_ETR_FILTER_FDIV4_N6 - * @arg @ref LL_TIM_ETR_FILTER_FDIV4_N8 - * @arg @ref LL_TIM_ETR_FILTER_FDIV8_N6 - * @arg @ref LL_TIM_ETR_FILTER_FDIV8_N8 - * @arg @ref LL_TIM_ETR_FILTER_FDIV16_N5 - * @arg @ref LL_TIM_ETR_FILTER_FDIV16_N6 - * @arg @ref LL_TIM_ETR_FILTER_FDIV16_N8 - * @arg @ref LL_TIM_ETR_FILTER_FDIV32_N5 - * @arg @ref LL_TIM_ETR_FILTER_FDIV32_N6 - * @arg @ref LL_TIM_ETR_FILTER_FDIV32_N8 - * @retval None - */ -__STATIC_INLINE void LL_TIM_ConfigETR(TIM_TypeDef *TIMx, uint32_t ETRPolarity, uint32_t ETRPrescaler, - uint32_t ETRFilter) -{ - MODIFY_REG(TIMx->SMCR, TIM_SMCR_ETP | TIM_SMCR_ETPS | TIM_SMCR_ETF, ETRPolarity | ETRPrescaler | ETRFilter); -} - -/** - * @} - */ - -/** @defgroup TIM_LL_EF_Break_Function Break function configuration - * @{ - */ -/** - * @brief Enable the break function. - * @note Macro @ref IS_TIM_BREAK_INSTANCE(TIMx) can be used to check whether or not - * a timer instance provides a break input. - * @rmtoll BDTR BKE LL_TIM_EnableBRK - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_EnableBRK(TIM_TypeDef *TIMx) -{ - SET_BIT(TIMx->BDTR, TIM_BDTR_BKE); -} - -/** - * @brief Disable the break function. - * @rmtoll BDTR BKE LL_TIM_DisableBRK - * @param TIMx Timer instance - * @note Macro @ref IS_TIM_BREAK_INSTANCE(TIMx) can be used to check whether or not - * a timer instance provides a break input. - * @retval None - */ -__STATIC_INLINE void LL_TIM_DisableBRK(TIM_TypeDef *TIMx) -{ - CLEAR_BIT(TIMx->BDTR, TIM_BDTR_BKE); -} - -/** - * @brief Configure the break input. - * @note Macro @ref IS_TIM_BREAK_INSTANCE(TIMx) can be used to check whether or not - * a timer instance provides a break input. - * @rmtoll BDTR BKP LL_TIM_ConfigBRK - * @param TIMx Timer instance - * @param BreakPolarity This parameter can be one of the following values: - * @arg @ref LL_TIM_BREAK_POLARITY_LOW - * @arg @ref LL_TIM_BREAK_POLARITY_HIGH - * @retval None - */ -__STATIC_INLINE void LL_TIM_ConfigBRK(TIM_TypeDef *TIMx, uint32_t BreakPolarity) -{ - MODIFY_REG(TIMx->BDTR, TIM_BDTR_BKP, BreakPolarity); -} - -/** - * @brief Select the outputs off state (enabled v.s. disabled) in Idle and Run modes. - * @note Macro @ref IS_TIM_BREAK_INSTANCE(TIMx) can be used to check whether or not - * a timer instance provides a break input. - * @rmtoll BDTR OSSI LL_TIM_SetOffStates\n - * BDTR OSSR LL_TIM_SetOffStates - * @param TIMx Timer instance - * @param OffStateIdle This parameter can be one of the following values: - * @arg @ref LL_TIM_OSSI_DISABLE - * @arg @ref LL_TIM_OSSI_ENABLE - * @param OffStateRun This parameter can be one of the following values: - * @arg @ref LL_TIM_OSSR_DISABLE - * @arg @ref LL_TIM_OSSR_ENABLE - * @retval None - */ -__STATIC_INLINE void LL_TIM_SetOffStates(TIM_TypeDef *TIMx, uint32_t OffStateIdle, uint32_t OffStateRun) -{ - MODIFY_REG(TIMx->BDTR, TIM_BDTR_OSSI | TIM_BDTR_OSSR, OffStateIdle | OffStateRun); -} - -/** - * @brief Enable automatic output (MOE can be set by software or automatically when a break input is active). - * @note Macro @ref IS_TIM_BREAK_INSTANCE(TIMx) can be used to check whether or not - * a timer instance provides a break input. - * @rmtoll BDTR AOE LL_TIM_EnableAutomaticOutput - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_EnableAutomaticOutput(TIM_TypeDef *TIMx) -{ - SET_BIT(TIMx->BDTR, TIM_BDTR_AOE); -} - -/** - * @brief Disable automatic output (MOE can be set only by software). - * @note Macro @ref IS_TIM_BREAK_INSTANCE(TIMx) can be used to check whether or not - * a timer instance provides a break input. - * @rmtoll BDTR AOE LL_TIM_DisableAutomaticOutput - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_DisableAutomaticOutput(TIM_TypeDef *TIMx) -{ - CLEAR_BIT(TIMx->BDTR, TIM_BDTR_AOE); -} - -/** - * @brief Indicate whether automatic output is enabled. - * @note Macro @ref IS_TIM_BREAK_INSTANCE(TIMx) can be used to check whether or not - * a timer instance provides a break input. - * @rmtoll BDTR AOE LL_TIM_IsEnabledAutomaticOutput - * @param TIMx Timer instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_TIM_IsEnabledAutomaticOutput(TIM_TypeDef *TIMx) -{ - return (READ_BIT(TIMx->BDTR, TIM_BDTR_AOE) == (TIM_BDTR_AOE)); -} - -/** - * @brief Enable the outputs (set the MOE bit in TIMx_BDTR register). - * @note The MOE bit in TIMx_BDTR register allows to enable /disable the outputs by - * software and is reset in case of break or break2 event - * @note Macro @ref IS_TIM_BREAK_INSTANCE(TIMx) can be used to check whether or not - * a timer instance provides a break input. - * @rmtoll BDTR MOE LL_TIM_EnableAllOutputs - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_EnableAllOutputs(TIM_TypeDef *TIMx) -{ - SET_BIT(TIMx->BDTR, TIM_BDTR_MOE); -} - -/** - * @brief Disable the outputs (reset the MOE bit in TIMx_BDTR register). - * @note The MOE bit in TIMx_BDTR register allows to enable /disable the outputs by - * software and is reset in case of break or break2 event. - * @note Macro @ref IS_TIM_BREAK_INSTANCE(TIMx) can be used to check whether or not - * a timer instance provides a break input. - * @rmtoll BDTR MOE LL_TIM_DisableAllOutputs - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_DisableAllOutputs(TIM_TypeDef *TIMx) -{ - CLEAR_BIT(TIMx->BDTR, TIM_BDTR_MOE); -} - -/** - * @brief Indicates whether outputs are enabled. - * @note Macro @ref IS_TIM_BREAK_INSTANCE(TIMx) can be used to check whether or not - * a timer instance provides a break input. - * @rmtoll BDTR MOE LL_TIM_IsEnabledAllOutputs - * @param TIMx Timer instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_TIM_IsEnabledAllOutputs(TIM_TypeDef *TIMx) -{ - return (READ_BIT(TIMx->BDTR, TIM_BDTR_MOE) == (TIM_BDTR_MOE)); -} - -/** - * @} - */ - -/** @defgroup TIM_LL_EF_DMA_Burst_Mode DMA burst mode configuration - * @{ - */ -/** - * @brief Configures the timer DMA burst feature. - * @note Macro @ref IS_TIM_DMABURST_INSTANCE(TIMx) can be used to check whether or - * not a timer instance supports the DMA burst mode. - * @rmtoll DCR DBL LL_TIM_ConfigDMABurst\n - * DCR DBA LL_TIM_ConfigDMABurst - * @param TIMx Timer instance - * @param DMABurstBaseAddress This parameter can be one of the following values: - * @arg @ref LL_TIM_DMABURST_BASEADDR_CR1 - * @arg @ref LL_TIM_DMABURST_BASEADDR_CR2 - * @arg @ref LL_TIM_DMABURST_BASEADDR_SMCR - * @arg @ref LL_TIM_DMABURST_BASEADDR_DIER - * @arg @ref LL_TIM_DMABURST_BASEADDR_SR - * @arg @ref LL_TIM_DMABURST_BASEADDR_EGR - * @arg @ref LL_TIM_DMABURST_BASEADDR_CCMR1 - * @arg @ref LL_TIM_DMABURST_BASEADDR_CCMR2 - * @arg @ref LL_TIM_DMABURST_BASEADDR_CCER - * @arg @ref LL_TIM_DMABURST_BASEADDR_CNT - * @arg @ref LL_TIM_DMABURST_BASEADDR_PSC - * @arg @ref LL_TIM_DMABURST_BASEADDR_ARR - * @arg @ref LL_TIM_DMABURST_BASEADDR_RCR - * @arg @ref LL_TIM_DMABURST_BASEADDR_CCR1 - * @arg @ref LL_TIM_DMABURST_BASEADDR_CCR2 - * @arg @ref LL_TIM_DMABURST_BASEADDR_CCR3 - * @arg @ref LL_TIM_DMABURST_BASEADDR_CCR4 - * @arg @ref LL_TIM_DMABURST_BASEADDR_BDTR - * @param DMABurstLength This parameter can be one of the following values: - * @arg @ref LL_TIM_DMABURST_LENGTH_1TRANSFER - * @arg @ref LL_TIM_DMABURST_LENGTH_2TRANSFERS - * @arg @ref LL_TIM_DMABURST_LENGTH_3TRANSFERS - * @arg @ref LL_TIM_DMABURST_LENGTH_4TRANSFERS - * @arg @ref LL_TIM_DMABURST_LENGTH_5TRANSFERS - * @arg @ref LL_TIM_DMABURST_LENGTH_6TRANSFERS - * @arg @ref LL_TIM_DMABURST_LENGTH_7TRANSFERS - * @arg @ref LL_TIM_DMABURST_LENGTH_8TRANSFERS - * @arg @ref LL_TIM_DMABURST_LENGTH_9TRANSFERS - * @arg @ref LL_TIM_DMABURST_LENGTH_10TRANSFERS - * @arg @ref LL_TIM_DMABURST_LENGTH_11TRANSFERS - * @arg @ref LL_TIM_DMABURST_LENGTH_12TRANSFERS - * @arg @ref LL_TIM_DMABURST_LENGTH_13TRANSFERS - * @arg @ref LL_TIM_DMABURST_LENGTH_14TRANSFERS - * @arg @ref LL_TIM_DMABURST_LENGTH_15TRANSFERS - * @arg @ref LL_TIM_DMABURST_LENGTH_16TRANSFERS - * @arg @ref LL_TIM_DMABURST_LENGTH_17TRANSFERS - * @arg @ref LL_TIM_DMABURST_LENGTH_18TRANSFERS - * @retval None - */ -__STATIC_INLINE void LL_TIM_ConfigDMABurst(TIM_TypeDef *TIMx, uint32_t DMABurstBaseAddress, uint32_t DMABurstLength) -{ - MODIFY_REG(TIMx->DCR, TIM_DCR_DBL | TIM_DCR_DBA, DMABurstBaseAddress | DMABurstLength); -} - -/** - * @} - */ - - -/** - * @} - */ - - -/** @defgroup TIM_LL_EF_FLAG_Management FLAG-Management - * @{ - */ -/** - * @brief Clear the update interrupt flag (UIF). - * @rmtoll SR UIF LL_TIM_ClearFlag_UPDATE - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_ClearFlag_UPDATE(TIM_TypeDef *TIMx) -{ - WRITE_REG(TIMx->SR, ~(TIM_SR_UIF)); -} - -/** - * @brief Indicate whether update interrupt flag (UIF) is set (update interrupt is pending). - * @rmtoll SR UIF LL_TIM_IsActiveFlag_UPDATE - * @param TIMx Timer instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_TIM_IsActiveFlag_UPDATE(TIM_TypeDef *TIMx) -{ - return (READ_BIT(TIMx->SR, TIM_SR_UIF) == (TIM_SR_UIF)); -} - -/** - * @brief Clear the Capture/Compare 1 interrupt flag (CC1F). - * @rmtoll SR CC1IF LL_TIM_ClearFlag_CC1 - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_ClearFlag_CC1(TIM_TypeDef *TIMx) -{ - WRITE_REG(TIMx->SR, ~(TIM_SR_CC1IF)); -} - -/** - * @brief Indicate whether Capture/Compare 1 interrupt flag (CC1F) is set (Capture/Compare 1 interrupt is pending). - * @rmtoll SR CC1IF LL_TIM_IsActiveFlag_CC1 - * @param TIMx Timer instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_TIM_IsActiveFlag_CC1(TIM_TypeDef *TIMx) -{ - return (READ_BIT(TIMx->SR, TIM_SR_CC1IF) == (TIM_SR_CC1IF)); -} - -/** - * @brief Clear the Capture/Compare 2 interrupt flag (CC2F). - * @rmtoll SR CC2IF LL_TIM_ClearFlag_CC2 - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_ClearFlag_CC2(TIM_TypeDef *TIMx) -{ - WRITE_REG(TIMx->SR, ~(TIM_SR_CC2IF)); -} - -/** - * @brief Indicate whether Capture/Compare 2 interrupt flag (CC2F) is set (Capture/Compare 2 interrupt is pending). - * @rmtoll SR CC2IF LL_TIM_IsActiveFlag_CC2 - * @param TIMx Timer instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_TIM_IsActiveFlag_CC2(TIM_TypeDef *TIMx) -{ - return (READ_BIT(TIMx->SR, TIM_SR_CC2IF) == (TIM_SR_CC2IF)); -} - -/** - * @brief Clear the Capture/Compare 3 interrupt flag (CC3F). - * @rmtoll SR CC3IF LL_TIM_ClearFlag_CC3 - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_ClearFlag_CC3(TIM_TypeDef *TIMx) -{ - WRITE_REG(TIMx->SR, ~(TIM_SR_CC3IF)); -} - -/** - * @brief Indicate whether Capture/Compare 3 interrupt flag (CC3F) is set (Capture/Compare 3 interrupt is pending). - * @rmtoll SR CC3IF LL_TIM_IsActiveFlag_CC3 - * @param TIMx Timer instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_TIM_IsActiveFlag_CC3(TIM_TypeDef *TIMx) -{ - return (READ_BIT(TIMx->SR, TIM_SR_CC3IF) == (TIM_SR_CC3IF)); -} - -/** - * @brief Clear the Capture/Compare 4 interrupt flag (CC4F). - * @rmtoll SR CC4IF LL_TIM_ClearFlag_CC4 - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_ClearFlag_CC4(TIM_TypeDef *TIMx) -{ - WRITE_REG(TIMx->SR, ~(TIM_SR_CC4IF)); -} - -/** - * @brief Indicate whether Capture/Compare 4 interrupt flag (CC4F) is set (Capture/Compare 4 interrupt is pending). - * @rmtoll SR CC4IF LL_TIM_IsActiveFlag_CC4 - * @param TIMx Timer instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_TIM_IsActiveFlag_CC4(TIM_TypeDef *TIMx) -{ - return (READ_BIT(TIMx->SR, TIM_SR_CC4IF) == (TIM_SR_CC4IF)); -} - -/** - * @brief Clear the commutation interrupt flag (COMIF). - * @rmtoll SR COMIF LL_TIM_ClearFlag_COM - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_ClearFlag_COM(TIM_TypeDef *TIMx) -{ - WRITE_REG(TIMx->SR, ~(TIM_SR_COMIF)); -} - -/** - * @brief Indicate whether commutation interrupt flag (COMIF) is set (commutation interrupt is pending). - * @rmtoll SR COMIF LL_TIM_IsActiveFlag_COM - * @param TIMx Timer instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_TIM_IsActiveFlag_COM(TIM_TypeDef *TIMx) -{ - return (READ_BIT(TIMx->SR, TIM_SR_COMIF) == (TIM_SR_COMIF)); -} - -/** - * @brief Clear the trigger interrupt flag (TIF). - * @rmtoll SR TIF LL_TIM_ClearFlag_TRIG - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_ClearFlag_TRIG(TIM_TypeDef *TIMx) -{ - WRITE_REG(TIMx->SR, ~(TIM_SR_TIF)); -} - -/** - * @brief Indicate whether trigger interrupt flag (TIF) is set (trigger interrupt is pending). - * @rmtoll SR TIF LL_TIM_IsActiveFlag_TRIG - * @param TIMx Timer instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_TIM_IsActiveFlag_TRIG(TIM_TypeDef *TIMx) -{ - return (READ_BIT(TIMx->SR, TIM_SR_TIF) == (TIM_SR_TIF)); -} - -/** - * @brief Clear the break interrupt flag (BIF). - * @rmtoll SR BIF LL_TIM_ClearFlag_BRK - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_ClearFlag_BRK(TIM_TypeDef *TIMx) -{ - WRITE_REG(TIMx->SR, ~(TIM_SR_BIF)); -} - -/** - * @brief Indicate whether break interrupt flag (BIF) is set (break interrupt is pending). - * @rmtoll SR BIF LL_TIM_IsActiveFlag_BRK - * @param TIMx Timer instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_TIM_IsActiveFlag_BRK(TIM_TypeDef *TIMx) -{ - return (READ_BIT(TIMx->SR, TIM_SR_BIF) == (TIM_SR_BIF)); -} - -/** - * @brief Clear the Capture/Compare 1 over-capture interrupt flag (CC1OF). - * @rmtoll SR CC1OF LL_TIM_ClearFlag_CC1OVR - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_ClearFlag_CC1OVR(TIM_TypeDef *TIMx) -{ - WRITE_REG(TIMx->SR, ~(TIM_SR_CC1OF)); -} - -/** - * @brief Indicate whether Capture/Compare 1 over-capture interrupt flag (CC1OF) is set (Capture/Compare 1 interrupt is pending). - * @rmtoll SR CC1OF LL_TIM_IsActiveFlag_CC1OVR - * @param TIMx Timer instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_TIM_IsActiveFlag_CC1OVR(TIM_TypeDef *TIMx) -{ - return (READ_BIT(TIMx->SR, TIM_SR_CC1OF) == (TIM_SR_CC1OF)); -} - -/** - * @brief Clear the Capture/Compare 2 over-capture interrupt flag (CC2OF). - * @rmtoll SR CC2OF LL_TIM_ClearFlag_CC2OVR - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_ClearFlag_CC2OVR(TIM_TypeDef *TIMx) -{ - WRITE_REG(TIMx->SR, ~(TIM_SR_CC2OF)); -} - -/** - * @brief Indicate whether Capture/Compare 2 over-capture interrupt flag (CC2OF) is set (Capture/Compare 2 over-capture interrupt is pending). - * @rmtoll SR CC2OF LL_TIM_IsActiveFlag_CC2OVR - * @param TIMx Timer instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_TIM_IsActiveFlag_CC2OVR(TIM_TypeDef *TIMx) -{ - return (READ_BIT(TIMx->SR, TIM_SR_CC2OF) == (TIM_SR_CC2OF)); -} - -/** - * @brief Clear the Capture/Compare 3 over-capture interrupt flag (CC3OF). - * @rmtoll SR CC3OF LL_TIM_ClearFlag_CC3OVR - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_ClearFlag_CC3OVR(TIM_TypeDef *TIMx) -{ - WRITE_REG(TIMx->SR, ~(TIM_SR_CC3OF)); -} - -/** - * @brief Indicate whether Capture/Compare 3 over-capture interrupt flag (CC3OF) is set (Capture/Compare 3 over-capture interrupt is pending). - * @rmtoll SR CC3OF LL_TIM_IsActiveFlag_CC3OVR - * @param TIMx Timer instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_TIM_IsActiveFlag_CC3OVR(TIM_TypeDef *TIMx) -{ - return (READ_BIT(TIMx->SR, TIM_SR_CC3OF) == (TIM_SR_CC3OF)); -} - -/** - * @brief Clear the Capture/Compare 4 over-capture interrupt flag (CC4OF). - * @rmtoll SR CC4OF LL_TIM_ClearFlag_CC4OVR - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_ClearFlag_CC4OVR(TIM_TypeDef *TIMx) -{ - WRITE_REG(TIMx->SR, ~(TIM_SR_CC4OF)); -} - -/** - * @brief Indicate whether Capture/Compare 4 over-capture interrupt flag (CC4OF) is set (Capture/Compare 4 over-capture interrupt is pending). - * @rmtoll SR CC4OF LL_TIM_IsActiveFlag_CC4OVR - * @param TIMx Timer instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_TIM_IsActiveFlag_CC4OVR(TIM_TypeDef *TIMx) -{ - return (READ_BIT(TIMx->SR, TIM_SR_CC4OF) == (TIM_SR_CC4OF)); -} - -/** - * @} - */ - -/** @defgroup TIM_LL_EF_IT_Management IT-Management - * @{ - */ -/** - * @brief Enable update interrupt (UIE). - * @rmtoll DIER UIE LL_TIM_EnableIT_UPDATE - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_EnableIT_UPDATE(TIM_TypeDef *TIMx) -{ - SET_BIT(TIMx->DIER, TIM_DIER_UIE); -} - -/** - * @brief Disable update interrupt (UIE). - * @rmtoll DIER UIE LL_TIM_DisableIT_UPDATE - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_DisableIT_UPDATE(TIM_TypeDef *TIMx) -{ - CLEAR_BIT(TIMx->DIER, TIM_DIER_UIE); -} - -/** - * @brief Indicates whether the update interrupt (UIE) is enabled. - * @rmtoll DIER UIE LL_TIM_IsEnabledIT_UPDATE - * @param TIMx Timer instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_TIM_IsEnabledIT_UPDATE(TIM_TypeDef *TIMx) -{ - return (READ_BIT(TIMx->DIER, TIM_DIER_UIE) == (TIM_DIER_UIE)); -} - -/** - * @brief Enable capture/compare 1 interrupt (CC1IE). - * @rmtoll DIER CC1IE LL_TIM_EnableIT_CC1 - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_EnableIT_CC1(TIM_TypeDef *TIMx) -{ - SET_BIT(TIMx->DIER, TIM_DIER_CC1IE); -} - -/** - * @brief Disable capture/compare 1 interrupt (CC1IE). - * @rmtoll DIER CC1IE LL_TIM_DisableIT_CC1 - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_DisableIT_CC1(TIM_TypeDef *TIMx) -{ - CLEAR_BIT(TIMx->DIER, TIM_DIER_CC1IE); -} - -/** - * @brief Indicates whether the capture/compare 1 interrupt (CC1IE) is enabled. - * @rmtoll DIER CC1IE LL_TIM_IsEnabledIT_CC1 - * @param TIMx Timer instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_TIM_IsEnabledIT_CC1(TIM_TypeDef *TIMx) -{ - return (READ_BIT(TIMx->DIER, TIM_DIER_CC1IE) == (TIM_DIER_CC1IE)); -} - -/** - * @brief Enable capture/compare 2 interrupt (CC2IE). - * @rmtoll DIER CC2IE LL_TIM_EnableIT_CC2 - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_EnableIT_CC2(TIM_TypeDef *TIMx) -{ - SET_BIT(TIMx->DIER, TIM_DIER_CC2IE); -} - -/** - * @brief Disable capture/compare 2 interrupt (CC2IE). - * @rmtoll DIER CC2IE LL_TIM_DisableIT_CC2 - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_DisableIT_CC2(TIM_TypeDef *TIMx) -{ - CLEAR_BIT(TIMx->DIER, TIM_DIER_CC2IE); -} - -/** - * @brief Indicates whether the capture/compare 2 interrupt (CC2IE) is enabled. - * @rmtoll DIER CC2IE LL_TIM_IsEnabledIT_CC2 - * @param TIMx Timer instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_TIM_IsEnabledIT_CC2(TIM_TypeDef *TIMx) -{ - return (READ_BIT(TIMx->DIER, TIM_DIER_CC2IE) == (TIM_DIER_CC2IE)); -} - -/** - * @brief Enable capture/compare 3 interrupt (CC3IE). - * @rmtoll DIER CC3IE LL_TIM_EnableIT_CC3 - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_EnableIT_CC3(TIM_TypeDef *TIMx) -{ - SET_BIT(TIMx->DIER, TIM_DIER_CC3IE); -} - -/** - * @brief Disable capture/compare 3 interrupt (CC3IE). - * @rmtoll DIER CC3IE LL_TIM_DisableIT_CC3 - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_DisableIT_CC3(TIM_TypeDef *TIMx) -{ - CLEAR_BIT(TIMx->DIER, TIM_DIER_CC3IE); -} - -/** - * @brief Indicates whether the capture/compare 3 interrupt (CC3IE) is enabled. - * @rmtoll DIER CC3IE LL_TIM_IsEnabledIT_CC3 - * @param TIMx Timer instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_TIM_IsEnabledIT_CC3(TIM_TypeDef *TIMx) -{ - return (READ_BIT(TIMx->DIER, TIM_DIER_CC3IE) == (TIM_DIER_CC3IE)); -} - -/** - * @brief Enable capture/compare 4 interrupt (CC4IE). - * @rmtoll DIER CC4IE LL_TIM_EnableIT_CC4 - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_EnableIT_CC4(TIM_TypeDef *TIMx) -{ - SET_BIT(TIMx->DIER, TIM_DIER_CC4IE); -} - -/** - * @brief Disable capture/compare 4 interrupt (CC4IE). - * @rmtoll DIER CC4IE LL_TIM_DisableIT_CC4 - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_DisableIT_CC4(TIM_TypeDef *TIMx) -{ - CLEAR_BIT(TIMx->DIER, TIM_DIER_CC4IE); -} - -/** - * @brief Indicates whether the capture/compare 4 interrupt (CC4IE) is enabled. - * @rmtoll DIER CC4IE LL_TIM_IsEnabledIT_CC4 - * @param TIMx Timer instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_TIM_IsEnabledIT_CC4(TIM_TypeDef *TIMx) -{ - return (READ_BIT(TIMx->DIER, TIM_DIER_CC4IE) == (TIM_DIER_CC4IE)); -} - -/** - * @brief Enable commutation interrupt (COMIE). - * @rmtoll DIER COMIE LL_TIM_EnableIT_COM - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_EnableIT_COM(TIM_TypeDef *TIMx) -{ - SET_BIT(TIMx->DIER, TIM_DIER_COMIE); -} - -/** - * @brief Disable commutation interrupt (COMIE). - * @rmtoll DIER COMIE LL_TIM_DisableIT_COM - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_DisableIT_COM(TIM_TypeDef *TIMx) -{ - CLEAR_BIT(TIMx->DIER, TIM_DIER_COMIE); -} - -/** - * @brief Indicates whether the commutation interrupt (COMIE) is enabled. - * @rmtoll DIER COMIE LL_TIM_IsEnabledIT_COM - * @param TIMx Timer instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_TIM_IsEnabledIT_COM(TIM_TypeDef *TIMx) -{ - return (READ_BIT(TIMx->DIER, TIM_DIER_COMIE) == (TIM_DIER_COMIE)); -} - -/** - * @brief Enable trigger interrupt (TIE). - * @rmtoll DIER TIE LL_TIM_EnableIT_TRIG - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_EnableIT_TRIG(TIM_TypeDef *TIMx) -{ - SET_BIT(TIMx->DIER, TIM_DIER_TIE); -} - -/** - * @brief Disable trigger interrupt (TIE). - * @rmtoll DIER TIE LL_TIM_DisableIT_TRIG - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_DisableIT_TRIG(TIM_TypeDef *TIMx) -{ - CLEAR_BIT(TIMx->DIER, TIM_DIER_TIE); -} - -/** - * @brief Indicates whether the trigger interrupt (TIE) is enabled. - * @rmtoll DIER TIE LL_TIM_IsEnabledIT_TRIG - * @param TIMx Timer instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_TIM_IsEnabledIT_TRIG(TIM_TypeDef *TIMx) -{ - return (READ_BIT(TIMx->DIER, TIM_DIER_TIE) == (TIM_DIER_TIE)); -} - -/** - * @brief Enable break interrupt (BIE). - * @rmtoll DIER BIE LL_TIM_EnableIT_BRK - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_EnableIT_BRK(TIM_TypeDef *TIMx) -{ - SET_BIT(TIMx->DIER, TIM_DIER_BIE); -} - -/** - * @brief Disable break interrupt (BIE). - * @rmtoll DIER BIE LL_TIM_DisableIT_BRK - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_DisableIT_BRK(TIM_TypeDef *TIMx) -{ - CLEAR_BIT(TIMx->DIER, TIM_DIER_BIE); -} - -/** - * @brief Indicates whether the break interrupt (BIE) is enabled. - * @rmtoll DIER BIE LL_TIM_IsEnabledIT_BRK - * @param TIMx Timer instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_TIM_IsEnabledIT_BRK(TIM_TypeDef *TIMx) -{ - return (READ_BIT(TIMx->DIER, TIM_DIER_BIE) == (TIM_DIER_BIE)); -} - -/** - * @} - */ - -/** @defgroup TIM_LL_EF_DMA_Management DMA-Management - * @{ - */ -/** - * @brief Enable update DMA request (UDE). - * @rmtoll DIER UDE LL_TIM_EnableDMAReq_UPDATE - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_EnableDMAReq_UPDATE(TIM_TypeDef *TIMx) -{ - SET_BIT(TIMx->DIER, TIM_DIER_UDE); -} - -/** - * @brief Disable update DMA request (UDE). - * @rmtoll DIER UDE LL_TIM_DisableDMAReq_UPDATE - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_DisableDMAReq_UPDATE(TIM_TypeDef *TIMx) -{ - CLEAR_BIT(TIMx->DIER, TIM_DIER_UDE); -} - -/** - * @brief Indicates whether the update DMA request (UDE) is enabled. - * @rmtoll DIER UDE LL_TIM_IsEnabledDMAReq_UPDATE - * @param TIMx Timer instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_TIM_IsEnabledDMAReq_UPDATE(TIM_TypeDef *TIMx) -{ - return (READ_BIT(TIMx->DIER, TIM_DIER_UDE) == (TIM_DIER_UDE)); -} - -/** - * @brief Enable capture/compare 1 DMA request (CC1DE). - * @rmtoll DIER CC1DE LL_TIM_EnableDMAReq_CC1 - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_EnableDMAReq_CC1(TIM_TypeDef *TIMx) -{ - SET_BIT(TIMx->DIER, TIM_DIER_CC1DE); -} - -/** - * @brief Disable capture/compare 1 DMA request (CC1DE). - * @rmtoll DIER CC1DE LL_TIM_DisableDMAReq_CC1 - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_DisableDMAReq_CC1(TIM_TypeDef *TIMx) -{ - CLEAR_BIT(TIMx->DIER, TIM_DIER_CC1DE); -} - -/** - * @brief Indicates whether the capture/compare 1 DMA request (CC1DE) is enabled. - * @rmtoll DIER CC1DE LL_TIM_IsEnabledDMAReq_CC1 - * @param TIMx Timer instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_TIM_IsEnabledDMAReq_CC1(TIM_TypeDef *TIMx) -{ - return (READ_BIT(TIMx->DIER, TIM_DIER_CC1DE) == (TIM_DIER_CC1DE)); -} - -/** - * @brief Enable capture/compare 2 DMA request (CC2DE). - * @rmtoll DIER CC2DE LL_TIM_EnableDMAReq_CC2 - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_EnableDMAReq_CC2(TIM_TypeDef *TIMx) -{ - SET_BIT(TIMx->DIER, TIM_DIER_CC2DE); -} - -/** - * @brief Disable capture/compare 2 DMA request (CC2DE). - * @rmtoll DIER CC2DE LL_TIM_DisableDMAReq_CC2 - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_DisableDMAReq_CC2(TIM_TypeDef *TIMx) -{ - CLEAR_BIT(TIMx->DIER, TIM_DIER_CC2DE); -} - -/** - * @brief Indicates whether the capture/compare 2 DMA request (CC2DE) is enabled. - * @rmtoll DIER CC2DE LL_TIM_IsEnabledDMAReq_CC2 - * @param TIMx Timer instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_TIM_IsEnabledDMAReq_CC2(TIM_TypeDef *TIMx) -{ - return (READ_BIT(TIMx->DIER, TIM_DIER_CC2DE) == (TIM_DIER_CC2DE)); -} - -/** - * @brief Enable capture/compare 3 DMA request (CC3DE). - * @rmtoll DIER CC3DE LL_TIM_EnableDMAReq_CC3 - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_EnableDMAReq_CC3(TIM_TypeDef *TIMx) -{ - SET_BIT(TIMx->DIER, TIM_DIER_CC3DE); -} - -/** - * @brief Disable capture/compare 3 DMA request (CC3DE). - * @rmtoll DIER CC3DE LL_TIM_DisableDMAReq_CC3 - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_DisableDMAReq_CC3(TIM_TypeDef *TIMx) -{ - CLEAR_BIT(TIMx->DIER, TIM_DIER_CC3DE); -} - -/** - * @brief Indicates whether the capture/compare 3 DMA request (CC3DE) is enabled. - * @rmtoll DIER CC3DE LL_TIM_IsEnabledDMAReq_CC3 - * @param TIMx Timer instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_TIM_IsEnabledDMAReq_CC3(TIM_TypeDef *TIMx) -{ - return (READ_BIT(TIMx->DIER, TIM_DIER_CC3DE) == (TIM_DIER_CC3DE)); -} - -/** - * @brief Enable capture/compare 4 DMA request (CC4DE). - * @rmtoll DIER CC4DE LL_TIM_EnableDMAReq_CC4 - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_EnableDMAReq_CC4(TIM_TypeDef *TIMx) -{ - SET_BIT(TIMx->DIER, TIM_DIER_CC4DE); -} - -/** - * @brief Disable capture/compare 4 DMA request (CC4DE). - * @rmtoll DIER CC4DE LL_TIM_DisableDMAReq_CC4 - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_DisableDMAReq_CC4(TIM_TypeDef *TIMx) -{ - CLEAR_BIT(TIMx->DIER, TIM_DIER_CC4DE); -} - -/** - * @brief Indicates whether the capture/compare 4 DMA request (CC4DE) is enabled. - * @rmtoll DIER CC4DE LL_TIM_IsEnabledDMAReq_CC4 - * @param TIMx Timer instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_TIM_IsEnabledDMAReq_CC4(TIM_TypeDef *TIMx) -{ - return (READ_BIT(TIMx->DIER, TIM_DIER_CC4DE) == (TIM_DIER_CC4DE)); -} - -/** - * @brief Enable commutation DMA request (COMDE). - * @rmtoll DIER COMDE LL_TIM_EnableDMAReq_COM - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_EnableDMAReq_COM(TIM_TypeDef *TIMx) -{ - SET_BIT(TIMx->DIER, TIM_DIER_COMDE); -} - -/** - * @brief Disable commutation DMA request (COMDE). - * @rmtoll DIER COMDE LL_TIM_DisableDMAReq_COM - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_DisableDMAReq_COM(TIM_TypeDef *TIMx) -{ - CLEAR_BIT(TIMx->DIER, TIM_DIER_COMDE); -} - -/** - * @brief Indicates whether the commutation DMA request (COMDE) is enabled. - * @rmtoll DIER COMDE LL_TIM_IsEnabledDMAReq_COM - * @param TIMx Timer instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_TIM_IsEnabledDMAReq_COM(TIM_TypeDef *TIMx) -{ - return (READ_BIT(TIMx->DIER, TIM_DIER_COMDE) == (TIM_DIER_COMDE)); -} - -/** - * @brief Enable trigger interrupt (TDE). - * @rmtoll DIER TDE LL_TIM_EnableDMAReq_TRIG - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_EnableDMAReq_TRIG(TIM_TypeDef *TIMx) -{ - SET_BIT(TIMx->DIER, TIM_DIER_TDE); -} - -/** - * @brief Disable trigger interrupt (TDE). - * @rmtoll DIER TDE LL_TIM_DisableDMAReq_TRIG - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_DisableDMAReq_TRIG(TIM_TypeDef *TIMx) -{ - CLEAR_BIT(TIMx->DIER, TIM_DIER_TDE); -} - -/** - * @brief Indicates whether the trigger interrupt (TDE) is enabled. - * @rmtoll DIER TDE LL_TIM_IsEnabledDMAReq_TRIG - * @param TIMx Timer instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_TIM_IsEnabledDMAReq_TRIG(TIM_TypeDef *TIMx) -{ - return (READ_BIT(TIMx->DIER, TIM_DIER_TDE) == (TIM_DIER_TDE)); -} - -/** - * @} - */ - -/** @defgroup TIM_LL_EF_EVENT_Management EVENT-Management - * @{ - */ -/** - * @brief Generate an update event. - * @rmtoll EGR UG LL_TIM_GenerateEvent_UPDATE - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_GenerateEvent_UPDATE(TIM_TypeDef *TIMx) -{ - SET_BIT(TIMx->EGR, TIM_EGR_UG); -} - -/** - * @brief Generate Capture/Compare 1 event. - * @rmtoll EGR CC1G LL_TIM_GenerateEvent_CC1 - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_GenerateEvent_CC1(TIM_TypeDef *TIMx) -{ - SET_BIT(TIMx->EGR, TIM_EGR_CC1G); -} - -/** - * @brief Generate Capture/Compare 2 event. - * @rmtoll EGR CC2G LL_TIM_GenerateEvent_CC2 - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_GenerateEvent_CC2(TIM_TypeDef *TIMx) -{ - SET_BIT(TIMx->EGR, TIM_EGR_CC2G); -} - -/** - * @brief Generate Capture/Compare 3 event. - * @rmtoll EGR CC3G LL_TIM_GenerateEvent_CC3 - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_GenerateEvent_CC3(TIM_TypeDef *TIMx) -{ - SET_BIT(TIMx->EGR, TIM_EGR_CC3G); -} - -/** - * @brief Generate Capture/Compare 4 event. - * @rmtoll EGR CC4G LL_TIM_GenerateEvent_CC4 - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_GenerateEvent_CC4(TIM_TypeDef *TIMx) -{ - SET_BIT(TIMx->EGR, TIM_EGR_CC4G); -} - -/** - * @brief Generate commutation event. - * @rmtoll EGR COMG LL_TIM_GenerateEvent_COM - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_GenerateEvent_COM(TIM_TypeDef *TIMx) -{ - SET_BIT(TIMx->EGR, TIM_EGR_COMG); -} - -/** - * @brief Generate trigger event. - * @rmtoll EGR TG LL_TIM_GenerateEvent_TRIG - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_GenerateEvent_TRIG(TIM_TypeDef *TIMx) -{ - SET_BIT(TIMx->EGR, TIM_EGR_TG); -} - -/** - * @brief Generate break event. - * @rmtoll EGR BG LL_TIM_GenerateEvent_BRK - * @param TIMx Timer instance - * @retval None - */ -__STATIC_INLINE void LL_TIM_GenerateEvent_BRK(TIM_TypeDef *TIMx) -{ - SET_BIT(TIMx->EGR, TIM_EGR_BG); -} - -/** - * @} - */ - -#if defined(USE_FULL_LL_DRIVER) -/** @defgroup TIM_LL_EF_Init Initialisation and deinitialisation functions - * @{ - */ - -ErrorStatus LL_TIM_DeInit(TIM_TypeDef *TIMx); -void LL_TIM_StructInit(LL_TIM_InitTypeDef *TIM_InitStruct); -ErrorStatus LL_TIM_Init(TIM_TypeDef *TIMx, LL_TIM_InitTypeDef *TIM_InitStruct); -void LL_TIM_OC_StructInit(LL_TIM_OC_InitTypeDef *TIM_OC_InitStruct); -ErrorStatus LL_TIM_OC_Init(TIM_TypeDef *TIMx, uint32_t Channel, LL_TIM_OC_InitTypeDef *TIM_OC_InitStruct); -void LL_TIM_IC_StructInit(LL_TIM_IC_InitTypeDef *TIM_ICInitStruct); -ErrorStatus LL_TIM_IC_Init(TIM_TypeDef *TIMx, uint32_t Channel, LL_TIM_IC_InitTypeDef *TIM_IC_InitStruct); -void LL_TIM_ENCODER_StructInit(LL_TIM_ENCODER_InitTypeDef *TIM_EncoderInitStruct); -ErrorStatus LL_TIM_ENCODER_Init(TIM_TypeDef *TIMx, LL_TIM_ENCODER_InitTypeDef *TIM_EncoderInitStruct); -void LL_TIM_HALLSENSOR_StructInit(LL_TIM_HALLSENSOR_InitTypeDef *TIM_HallSensorInitStruct); -ErrorStatus LL_TIM_HALLSENSOR_Init(TIM_TypeDef *TIMx, LL_TIM_HALLSENSOR_InitTypeDef *TIM_HallSensorInitStruct); -void LL_TIM_BDTR_StructInit(LL_TIM_BDTR_InitTypeDef *TIM_BDTRInitStruct); -ErrorStatus LL_TIM_BDTR_Init(TIM_TypeDef *TIMx, LL_TIM_BDTR_InitTypeDef *TIM_BDTRInitStruct); -/** - * @} - */ -#endif /* USE_FULL_LL_DRIVER */ - -/** - * @} - */ - -/** - * @} - */ - -#endif /* TIM1 || TIM2 || TIM3 || TIM4 || TIM5 || TIM6 || TIM7 || TIM8 || TIM9 || TIM10 || TIM11 || TIM12 || TIM13 || TIM14 || TIM15 || TIM16 || TIM17 */ - -/** - * @} - */ - -#ifdef __cplusplus -} -#endif - -#endif /* __STM32F1xx_LL_TIM_H */ -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_usart.c b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_usart.c deleted file mode 100644 index 04b047a0b2b..00000000000 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_usart.c +++ /dev/null @@ -1,451 +0,0 @@ -/** - ****************************************************************************** - * @file stm32f1xx_ll_usart.c - * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 - * @brief USART LL module driver. - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2016 STMicroelectronics

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ -#if defined(USE_FULL_LL_DRIVER) - -/* Includes ------------------------------------------------------------------*/ -#include "stm32f1xx_ll_usart.h" -#include "stm32f1xx_ll_rcc.h" -#include "stm32f1xx_ll_bus.h" -#ifdef USE_FULL_ASSERT -#include "stm32_assert.h" -#else -#define assert_param(expr) ((void)0U) -#endif - -/** @addtogroup STM32F1xx_LL_Driver - * @{ - */ - -#if defined (USART1) || defined (USART2) || defined (USART3) || defined (UART4) || defined (UART5) - -/** @addtogroup USART_LL - * @{ - */ - -/* Private types -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private constants ---------------------------------------------------------*/ -/** @addtogroup USART_LL_Private_Constants - * @{ - */ - -/** - * @} - */ - - -/* Private macros ------------------------------------------------------------*/ -/** @addtogroup USART_LL_Private_Macros - * @{ - */ - -/* __BAUDRATE__ The maximum Baud Rate is derived from the maximum clock available - * divided by the smallest oversampling used on the USART (i.e. 8) */ -#define IS_LL_USART_BAUDRATE(__BAUDRATE__) ((__BAUDRATE__) <= 10000000U) - -#define IS_LL_USART_DIRECTION(__VALUE__) (((__VALUE__) == LL_USART_DIRECTION_NONE) \ - || ((__VALUE__) == LL_USART_DIRECTION_RX) \ - || ((__VALUE__) == LL_USART_DIRECTION_TX) \ - || ((__VALUE__) == LL_USART_DIRECTION_TX_RX)) - -#define IS_LL_USART_PARITY(__VALUE__) (((__VALUE__) == LL_USART_PARITY_NONE) \ - || ((__VALUE__) == LL_USART_PARITY_EVEN) \ - || ((__VALUE__) == LL_USART_PARITY_ODD)) - -#define IS_LL_USART_DATAWIDTH(__VALUE__) (((__VALUE__) == LL_USART_DATAWIDTH_8B) \ - || ((__VALUE__) == LL_USART_DATAWIDTH_9B)) - -#define IS_LL_USART_OVERSAMPLING(__VALUE__) (((__VALUE__) == LL_USART_OVERSAMPLING_16) \ - || ((__VALUE__) == LL_USART_OVERSAMPLING_8)) - -#define IS_LL_USART_LASTBITCLKOUTPUT(__VALUE__) (((__VALUE__) == LL_USART_LASTCLKPULSE_NO_OUTPUT) \ - || ((__VALUE__) == LL_USART_LASTCLKPULSE_OUTPUT)) - -#define IS_LL_USART_CLOCKPHASE(__VALUE__) (((__VALUE__) == LL_USART_PHASE_1EDGE) \ - || ((__VALUE__) == LL_USART_PHASE_2EDGE)) - -#define IS_LL_USART_CLOCKPOLARITY(__VALUE__) (((__VALUE__) == LL_USART_POLARITY_LOW) \ - || ((__VALUE__) == LL_USART_POLARITY_HIGH)) - -#define IS_LL_USART_CLOCKOUTPUT(__VALUE__) (((__VALUE__) == LL_USART_CLOCK_DISABLE) \ - || ((__VALUE__) == LL_USART_CLOCK_ENABLE)) - -#define IS_LL_USART_STOPBITS(__VALUE__) (((__VALUE__) == LL_USART_STOPBITS_0_5) \ - || ((__VALUE__) == LL_USART_STOPBITS_1) \ - || ((__VALUE__) == LL_USART_STOPBITS_1_5) \ - || ((__VALUE__) == LL_USART_STOPBITS_2)) - -#define IS_LL_USART_HWCONTROL(__VALUE__) (((__VALUE__) == LL_USART_HWCONTROL_NONE) \ - || ((__VALUE__) == LL_USART_HWCONTROL_RTS) \ - || ((__VALUE__) == LL_USART_HWCONTROL_CTS) \ - || ((__VALUE__) == LL_USART_HWCONTROL_RTS_CTS)) - -/** - * @} - */ - -/* Private function prototypes -----------------------------------------------*/ - -/* Exported functions --------------------------------------------------------*/ -/** @addtogroup USART_LL_Exported_Functions - * @{ - */ - -/** @addtogroup USART_LL_EF_Init - * @{ - */ - -/** - * @brief De-initialize USART registers (Registers restored to their default values). - * @param USARTx USART Instance - * @retval An ErrorStatus enumeration value: - * - SUCCESS: USART registers are de-initialized - * - ERROR: USART registers are not de-initialized - */ -ErrorStatus LL_USART_DeInit(USART_TypeDef *USARTx) -{ - ErrorStatus status = SUCCESS; - - /* Check the parameters */ - assert_param(IS_UART_INSTANCE(USARTx)); - - if (USARTx == USART1) - { - /* Force reset of USART clock */ - LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_USART1); - - /* Release reset of USART clock */ - LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_USART1); - } - else if (USARTx == USART2) - { - /* Force reset of USART clock */ - LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_USART2); - - /* Release reset of USART clock */ - LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_USART2); - } -#if defined(USART3) - else if (USARTx == USART3) - { - /* Force reset of USART clock */ - LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_USART3); - - /* Release reset of USART clock */ - LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_USART3); - } -#endif /* USART3 */ -#if defined(UART4) - else if (USARTx == UART4) - { - /* Force reset of UART clock */ - LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_UART4); - - /* Release reset of UART clock */ - LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_UART4); - } -#endif /* UART4 */ -#if defined(UART5) - else if (USARTx == UART5) - { - /* Force reset of UART clock */ - LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_UART5); - - /* Release reset of UART clock */ - LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_UART5); - } -#endif /* UART5 */ - else - { - status = ERROR; - } - - return (status); -} - -/** - * @brief Initialize USART registers according to the specified - * parameters in USART_InitStruct. - * @note As some bits in USART configuration registers can only be written when the USART is disabled (USART_CR1_UE bit =0), - * USART IP should be in disabled state prior calling this function. Otherwise, ERROR result will be returned. - * @note Baud rate value stored in USART_InitStruct BaudRate field, should be valid (different from 0). - * @param USARTx USART Instance - * @param USART_InitStruct: pointer to a LL_USART_InitTypeDef structure - * that contains the configuration information for the specified USART peripheral. - * @retval An ErrorStatus enumeration value: - * - SUCCESS: USART registers are initialized according to USART_InitStruct content - * - ERROR: Problem occurred during USART Registers initialization - */ -ErrorStatus LL_USART_Init(USART_TypeDef *USARTx, LL_USART_InitTypeDef *USART_InitStruct) -{ - ErrorStatus status = ERROR; - uint32_t periphclk = LL_RCC_PERIPH_FREQUENCY_NO; - LL_RCC_ClocksTypeDef rcc_clocks; - - /* Check the parameters */ - assert_param(IS_UART_INSTANCE(USARTx)); - assert_param(IS_LL_USART_BAUDRATE(USART_InitStruct->BaudRate)); - assert_param(IS_LL_USART_DATAWIDTH(USART_InitStruct->DataWidth)); - assert_param(IS_LL_USART_STOPBITS(USART_InitStruct->StopBits)); - assert_param(IS_LL_USART_PARITY(USART_InitStruct->Parity)); - assert_param(IS_LL_USART_DIRECTION(USART_InitStruct->TransferDirection)); - assert_param(IS_LL_USART_HWCONTROL(USART_InitStruct->HardwareFlowControl)); -#if defined(USART_CR1_OVER8) - assert_param(IS_LL_USART_OVERSAMPLING(USART_InitStruct->OverSampling)); -#endif /* USART_OverSampling_Feature */ - - /* USART needs to be in disabled state, in order to be able to configure some bits in - CRx registers */ - if (LL_USART_IsEnabled(USARTx) == 0U) - { - /*---------------------------- USART CR1 Configuration ----------------------- - * Configure USARTx CR1 (USART Word Length, Parity, Mode and Oversampling bits) with parameters: - * - DataWidth: USART_CR1_M bits according to USART_InitStruct->DataWidth value - * - Parity: USART_CR1_PCE, USART_CR1_PS bits according to USART_InitStruct->Parity value - * - TransferDirection: USART_CR1_TE, USART_CR1_RE bits according to USART_InitStruct->TransferDirection value - * - Oversampling: USART_CR1_OVER8 bit according to USART_InitStruct->OverSampling value. - */ -#if defined(USART_CR1_OVER8) - MODIFY_REG(USARTx->CR1, - (USART_CR1_M | USART_CR1_PCE | USART_CR1_PS | - USART_CR1_TE | USART_CR1_RE | USART_CR1_OVER8), - (USART_InitStruct->DataWidth | USART_InitStruct->Parity | - USART_InitStruct->TransferDirection | USART_InitStruct->OverSampling)); -#else - MODIFY_REG(USARTx->CR1, - (USART_CR1_M | USART_CR1_PCE | USART_CR1_PS | - USART_CR1_TE | USART_CR1_RE), - (USART_InitStruct->DataWidth | USART_InitStruct->Parity | - USART_InitStruct->TransferDirection)); -#endif /* USART_OverSampling_Feature */ - - /*---------------------------- USART CR2 Configuration ----------------------- - * Configure USARTx CR2 (Stop bits) with parameters: - * - Stop Bits: USART_CR2_STOP bits according to USART_InitStruct->StopBits value. - * - CLKEN, CPOL, CPHA and LBCL bits are to be configured using LL_USART_ClockInit(). - */ - LL_USART_SetStopBitsLength(USARTx, USART_InitStruct->StopBits); - - /*---------------------------- USART CR3 Configuration ----------------------- - * Configure USARTx CR3 (Hardware Flow Control) with parameters: - * - HardwareFlowControl: USART_CR3_RTSE, USART_CR3_CTSE bits according to USART_InitStruct->HardwareFlowControl value. - */ - LL_USART_SetHWFlowCtrl(USARTx, USART_InitStruct->HardwareFlowControl); - - /*---------------------------- USART BRR Configuration ----------------------- - * Retrieve Clock frequency used for USART Peripheral - */ - LL_RCC_GetSystemClocksFreq(&rcc_clocks); - if (USARTx == USART1) - { - periphclk = rcc_clocks.PCLK2_Frequency; - } - else if (USARTx == USART2) - { - periphclk = rcc_clocks.PCLK1_Frequency; - } -#if defined(USART3) - else if (USARTx == USART3) - { - periphclk = rcc_clocks.PCLK1_Frequency; - } -#endif /* USART3 */ -#if defined(UART4) - else if (USARTx == UART4) - { - periphclk = rcc_clocks.PCLK1_Frequency; - } -#endif /* UART4 */ -#if defined(UART5) - else if (USARTx == UART5) - { - periphclk = rcc_clocks.PCLK1_Frequency; - } -#endif /* UART5 */ - else - { - /* Nothing to do, as error code is already assigned to ERROR value */ - } - - /* Configure the USART Baud Rate : - - valid baud rate value (different from 0) is required - - Peripheral clock as returned by RCC service, should be valid (different from 0). - */ - if ((periphclk != LL_RCC_PERIPH_FREQUENCY_NO) - && (USART_InitStruct->BaudRate != 0U)) - { - status = SUCCESS; -#if defined(USART_CR1_OVER8) - LL_USART_SetBaudRate(USARTx, - periphclk, - USART_InitStruct->OverSampling, - USART_InitStruct->BaudRate); -#else - LL_USART_SetBaudRate(USARTx, - periphclk, - USART_InitStruct->BaudRate); -#endif /* USART_OverSampling_Feature */ - } - } - /* Endif (=> USART not in Disabled state => return ERROR) */ - - return (status); -} - -/** - * @brief Set each @ref LL_USART_InitTypeDef field to default value. - * @param USART_InitStruct: pointer to a @ref LL_USART_InitTypeDef structure - * whose fields will be set to default values. - * @retval None - */ - -void LL_USART_StructInit(LL_USART_InitTypeDef *USART_InitStruct) -{ - /* Set USART_InitStruct fields to default values */ - USART_InitStruct->BaudRate = 9600U; - USART_InitStruct->DataWidth = LL_USART_DATAWIDTH_8B; - USART_InitStruct->StopBits = LL_USART_STOPBITS_1; - USART_InitStruct->Parity = LL_USART_PARITY_NONE ; - USART_InitStruct->TransferDirection = LL_USART_DIRECTION_TX_RX; - USART_InitStruct->HardwareFlowControl = LL_USART_HWCONTROL_NONE; -#if defined(USART_CR1_OVER8) - USART_InitStruct->OverSampling = LL_USART_OVERSAMPLING_16; -#endif /* USART_OverSampling_Feature */ -} - -/** - * @brief Initialize USART Clock related settings according to the - * specified parameters in the USART_ClockInitStruct. - * @note As some bits in USART configuration registers can only be written when the USART is disabled (USART_CR1_UE bit =0), - * USART IP should be in disabled state prior calling this function. Otherwise, ERROR result will be returned. - * @param USARTx USART Instance - * @param USART_ClockInitStruct: pointer to a @ref LL_USART_ClockInitTypeDef structure - * that contains the Clock configuration information for the specified USART peripheral. - * @retval An ErrorStatus enumeration value: - * - SUCCESS: USART registers related to Clock settings are initialized according to USART_ClockInitStruct content - * - ERROR: Problem occurred during USART Registers initialization - */ -ErrorStatus LL_USART_ClockInit(USART_TypeDef *USARTx, LL_USART_ClockInitTypeDef *USART_ClockInitStruct) -{ - ErrorStatus status = SUCCESS; - - /* Check USART Instance and Clock signal output parameters */ - assert_param(IS_UART_INSTANCE(USARTx)); - assert_param(IS_LL_USART_CLOCKOUTPUT(USART_ClockInitStruct->ClockOutput)); - - /* USART needs to be in disabled state, in order to be able to configure some bits in - CRx registers */ - if (LL_USART_IsEnabled(USARTx) == 0U) - { - /*---------------------------- USART CR2 Configuration -----------------------*/ - /* If Clock signal has to be output */ - if (USART_ClockInitStruct->ClockOutput == LL_USART_CLOCK_DISABLE) - { - /* Deactivate Clock signal delivery : - * - Disable Clock Output: USART_CR2_CLKEN cleared - */ - LL_USART_DisableSCLKOutput(USARTx); - } - else - { - /* Ensure USART instance is USART capable */ - assert_param(IS_USART_INSTANCE(USARTx)); - - /* Check clock related parameters */ - assert_param(IS_LL_USART_CLOCKPOLARITY(USART_ClockInitStruct->ClockPolarity)); - assert_param(IS_LL_USART_CLOCKPHASE(USART_ClockInitStruct->ClockPhase)); - assert_param(IS_LL_USART_LASTBITCLKOUTPUT(USART_ClockInitStruct->LastBitClockPulse)); - - /*---------------------------- USART CR2 Configuration ----------------------- - * Configure USARTx CR2 (Clock signal related bits) with parameters: - * - Enable Clock Output: USART_CR2_CLKEN set - * - Clock Polarity: USART_CR2_CPOL bit according to USART_ClockInitStruct->ClockPolarity value - * - Clock Phase: USART_CR2_CPHA bit according to USART_ClockInitStruct->ClockPhase value - * - Last Bit Clock Pulse Output: USART_CR2_LBCL bit according to USART_ClockInitStruct->LastBitClockPulse value. - */ - MODIFY_REG(USARTx->CR2, - USART_CR2_CLKEN | USART_CR2_CPHA | USART_CR2_CPOL | USART_CR2_LBCL, - USART_CR2_CLKEN | USART_ClockInitStruct->ClockPolarity | - USART_ClockInitStruct->ClockPhase | USART_ClockInitStruct->LastBitClockPulse); - } - } - /* Else (USART not in Disabled state => return ERROR */ - else - { - status = ERROR; - } - - return (status); -} - -/** - * @brief Set each field of a @ref LL_USART_ClockInitTypeDef type structure to default value. - * @param USART_ClockInitStruct: pointer to a @ref LL_USART_ClockInitTypeDef structure - * whose fields will be set to default values. - * @retval None - */ -void LL_USART_ClockStructInit(LL_USART_ClockInitTypeDef *USART_ClockInitStruct) -{ - /* Set LL_USART_ClockInitStruct fields with default values */ - USART_ClockInitStruct->ClockOutput = LL_USART_CLOCK_DISABLE; - USART_ClockInitStruct->ClockPolarity = LL_USART_POLARITY_LOW; /* Not relevant when ClockOutput = LL_USART_CLOCK_DISABLE */ - USART_ClockInitStruct->ClockPhase = LL_USART_PHASE_1EDGE; /* Not relevant when ClockOutput = LL_USART_CLOCK_DISABLE */ - USART_ClockInitStruct->LastBitClockPulse = LL_USART_LASTCLKPULSE_NO_OUTPUT; /* Not relevant when ClockOutput = LL_USART_CLOCK_DISABLE */ -} - -/** - * @} - */ - -/** - * @} - */ - -/** - * @} - */ - -#endif /* USART1 || USART2 || USART3 || UART4 || UART5 */ - -/** - * @} - */ - -#endif /* USE_FULL_LL_DRIVER */ - -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ - diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_usart.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_usart.h deleted file mode 100644 index 00983287a16..00000000000 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_usart.h +++ /dev/null @@ -1,2589 +0,0 @@ -/** - ****************************************************************************** - * @file stm32f1xx_ll_usart.h - * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 - * @brief Header file of USART LL module. - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2016 STMicroelectronics

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ - -/* Define to prevent recursive inclusion -------------------------------------*/ -#ifndef __STM32F1xx_LL_USART_H -#define __STM32F1xx_LL_USART_H - -#ifdef __cplusplus -extern "C" { -#endif - -/* Includes ------------------------------------------------------------------*/ -#include "stm32f1xx.h" - -/** @addtogroup STM32F1xx_LL_Driver - * @{ - */ - -#if defined (USART1) || defined (USART2) || defined (USART3) || defined (UART4) || defined (UART5) - -/** @defgroup USART_LL USART - * @{ - */ - -/* Private types -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ - -/* Private constants ---------------------------------------------------------*/ -/** @defgroup USART_LL_Private_Constants USART Private Constants - * @{ - */ - -/* Defines used for the bit position in the register and perform offsets*/ -#define USART_POSITION_GTPR_GT USART_GTPR_GT_Pos -/** - * @} - */ - -/* Private macros ------------------------------------------------------------*/ -#if defined(USE_FULL_LL_DRIVER) -/** @defgroup USART_LL_Private_Macros USART Private Macros - * @{ - */ -/** - * @} - */ -#endif /*USE_FULL_LL_DRIVER*/ - -/* Exported types ------------------------------------------------------------*/ -#if defined(USE_FULL_LL_DRIVER) -/** @defgroup USART_LL_ES_INIT USART Exported Init structures - * @{ - */ - -/** - * @brief LL USART Init Structure definition - */ -typedef struct -{ - uint32_t BaudRate; /*!< This field defines expected Usart communication baud rate. - - This feature can be modified afterwards using unitary function @ref LL_USART_SetBaudRate().*/ - - uint32_t DataWidth; /*!< Specifies the number of data bits transmitted or received in a frame. - This parameter can be a value of @ref USART_LL_EC_DATAWIDTH. - - This feature can be modified afterwards using unitary function @ref LL_USART_SetDataWidth().*/ - - uint32_t StopBits; /*!< Specifies the number of stop bits transmitted. - This parameter can be a value of @ref USART_LL_EC_STOPBITS. - - This feature can be modified afterwards using unitary function @ref LL_USART_SetStopBitsLength().*/ - - uint32_t Parity; /*!< Specifies the parity mode. - This parameter can be a value of @ref USART_LL_EC_PARITY. - - This feature can be modified afterwards using unitary function @ref LL_USART_SetParity().*/ - - uint32_t TransferDirection; /*!< Specifies whether the Receive and/or Transmit mode is enabled or disabled. - This parameter can be a value of @ref USART_LL_EC_DIRECTION. - - This feature can be modified afterwards using unitary function @ref LL_USART_SetTransferDirection().*/ - - uint32_t HardwareFlowControl; /*!< Specifies whether the hardware flow control mode is enabled or disabled. - This parameter can be a value of @ref USART_LL_EC_HWCONTROL. - - This feature can be modified afterwards using unitary function @ref LL_USART_SetHWFlowCtrl().*/ - -#if defined(USART_CR1_OVER8) - uint32_t OverSampling; /*!< Specifies whether USART oversampling mode is 16 or 8. - This parameter can be a value of @ref USART_LL_EC_OVERSAMPLING. - - This feature can be modified afterwards using unitary function @ref LL_USART_SetOverSampling().*/ - -#endif /* USART_OverSampling_Feature */ -} LL_USART_InitTypeDef; - -/** - * @brief LL USART Clock Init Structure definition - */ -typedef struct -{ - uint32_t ClockOutput; /*!< Specifies whether the USART clock is enabled or disabled. - This parameter can be a value of @ref USART_LL_EC_CLOCK. - - USART HW configuration can be modified afterwards using unitary functions - @ref LL_USART_EnableSCLKOutput() or @ref LL_USART_DisableSCLKOutput(). - For more details, refer to description of this function. */ - - uint32_t ClockPolarity; /*!< Specifies the steady state of the serial clock. - This parameter can be a value of @ref USART_LL_EC_POLARITY. - - USART HW configuration can be modified afterwards using unitary functions @ref LL_USART_SetClockPolarity(). - For more details, refer to description of this function. */ - - uint32_t ClockPhase; /*!< Specifies the clock transition on which the bit capture is made. - This parameter can be a value of @ref USART_LL_EC_PHASE. - - USART HW configuration can be modified afterwards using unitary functions @ref LL_USART_SetClockPhase(). - For more details, refer to description of this function. */ - - uint32_t LastBitClockPulse; /*!< Specifies whether the clock pulse corresponding to the last transmitted - data bit (MSB) has to be output on the SCLK pin in synchronous mode. - This parameter can be a value of @ref USART_LL_EC_LASTCLKPULSE. - - USART HW configuration can be modified afterwards using unitary functions @ref LL_USART_SetLastClkPulseOutput(). - For more details, refer to description of this function. */ - -} LL_USART_ClockInitTypeDef; - -/** - * @} - */ -#endif /* USE_FULL_LL_DRIVER */ - -/* Exported constants --------------------------------------------------------*/ -/** @defgroup USART_LL_Exported_Constants USART Exported Constants - * @{ - */ - -/** @defgroup USART_LL_EC_GET_FLAG Get Flags Defines - * @brief Flags defines which can be used with LL_USART_ReadReg function - * @{ - */ -#define LL_USART_SR_PE USART_SR_PE /*!< Parity error flag */ -#define LL_USART_SR_FE USART_SR_FE /*!< Framing error flag */ -#define LL_USART_SR_NE USART_SR_NE /*!< Noise detected flag */ -#define LL_USART_SR_ORE USART_SR_ORE /*!< Overrun error flag */ -#define LL_USART_SR_IDLE USART_SR_IDLE /*!< Idle line detected flag */ -#define LL_USART_SR_RXNE USART_SR_RXNE /*!< Read data register not empty flag */ -#define LL_USART_SR_TC USART_SR_TC /*!< Transmission complete flag */ -#define LL_USART_SR_TXE USART_SR_TXE /*!< Transmit data register empty flag */ -#define LL_USART_SR_LBD USART_SR_LBD /*!< LIN break detection flag */ -#define LL_USART_SR_CTS USART_SR_CTS /*!< CTS flag */ -/** - * @} - */ - -/** @defgroup USART_LL_EC_IT IT Defines - * @brief IT defines which can be used with LL_USART_ReadReg and LL_USART_WriteReg functions - * @{ - */ -#define LL_USART_CR1_IDLEIE USART_CR1_IDLEIE /*!< IDLE interrupt enable */ -#define LL_USART_CR1_RXNEIE USART_CR1_RXNEIE /*!< Read data register not empty interrupt enable */ -#define LL_USART_CR1_TCIE USART_CR1_TCIE /*!< Transmission complete interrupt enable */ -#define LL_USART_CR1_TXEIE USART_CR1_TXEIE /*!< Transmit data register empty interrupt enable */ -#define LL_USART_CR1_PEIE USART_CR1_PEIE /*!< Parity error */ -#define LL_USART_CR2_LBDIE USART_CR2_LBDIE /*!< LIN break detection interrupt enable */ -#define LL_USART_CR3_EIE USART_CR3_EIE /*!< Error interrupt enable */ -#define LL_USART_CR3_CTSIE USART_CR3_CTSIE /*!< CTS interrupt enable */ -/** - * @} - */ - -/** @defgroup USART_LL_EC_DIRECTION Communication Direction - * @{ - */ -#define LL_USART_DIRECTION_NONE 0x00000000U /*!< Transmitter and Receiver are disabled */ -#define LL_USART_DIRECTION_RX USART_CR1_RE /*!< Transmitter is disabled and Receiver is enabled */ -#define LL_USART_DIRECTION_TX USART_CR1_TE /*!< Transmitter is enabled and Receiver is disabled */ -#define LL_USART_DIRECTION_TX_RX (USART_CR1_TE |USART_CR1_RE) /*!< Transmitter and Receiver are enabled */ -/** - * @} - */ - -/** @defgroup USART_LL_EC_PARITY Parity Control - * @{ - */ -#define LL_USART_PARITY_NONE 0x00000000U /*!< Parity control disabled */ -#define LL_USART_PARITY_EVEN USART_CR1_PCE /*!< Parity control enabled and Even Parity is selected */ -#define LL_USART_PARITY_ODD (USART_CR1_PCE | USART_CR1_PS) /*!< Parity control enabled and Odd Parity is selected */ -/** - * @} - */ - -/** @defgroup USART_LL_EC_WAKEUP Wakeup - * @{ - */ -#define LL_USART_WAKEUP_IDLELINE 0x00000000U /*!< USART wake up from Mute mode on Idle Line */ -#define LL_USART_WAKEUP_ADDRESSMARK USART_CR1_WAKE /*!< USART wake up from Mute mode on Address Mark */ -/** - * @} - */ - -/** @defgroup USART_LL_EC_DATAWIDTH Datawidth - * @{ - */ -#define LL_USART_DATAWIDTH_8B 0x00000000U /*!< 8 bits word length : Start bit, 8 data bits, n stop bits */ -#define LL_USART_DATAWIDTH_9B USART_CR1_M /*!< 9 bits word length : Start bit, 9 data bits, n stop bits */ -/** - * @} - */ - -#if defined(USART_CR1_OVER8) -/** @defgroup USART_LL_EC_OVERSAMPLING Oversampling - * @{ - */ -#define LL_USART_OVERSAMPLING_16 0x00000000U /*!< Oversampling by 16 */ -#define LL_USART_OVERSAMPLING_8 USART_CR1_OVER8 /*!< Oversampling by 8 */ -/** - * @} - */ - -#endif /* USART_OverSampling_Feature */ -#if defined(USE_FULL_LL_DRIVER) -/** @defgroup USART_LL_EC_CLOCK Clock Signal - * @{ - */ - -#define LL_USART_CLOCK_DISABLE 0x00000000U /*!< Clock signal not provided */ -#define LL_USART_CLOCK_ENABLE USART_CR2_CLKEN /*!< Clock signal provided */ -/** - * @} - */ -#endif /*USE_FULL_LL_DRIVER*/ - -/** @defgroup USART_LL_EC_LASTCLKPULSE Last Clock Pulse - * @{ - */ -#define LL_USART_LASTCLKPULSE_NO_OUTPUT 0x00000000U /*!< The clock pulse of the last data bit is not output to the SCLK pin */ -#define LL_USART_LASTCLKPULSE_OUTPUT USART_CR2_LBCL /*!< The clock pulse of the last data bit is output to the SCLK pin */ -/** - * @} - */ - -/** @defgroup USART_LL_EC_PHASE Clock Phase - * @{ - */ -#define LL_USART_PHASE_1EDGE 0x00000000U /*!< The first clock transition is the first data capture edge */ -#define LL_USART_PHASE_2EDGE USART_CR2_CPHA /*!< The second clock transition is the first data capture edge */ -/** - * @} - */ - -/** @defgroup USART_LL_EC_POLARITY Clock Polarity - * @{ - */ -#define LL_USART_POLARITY_LOW 0x00000000U /*!< Steady low value on SCLK pin outside transmission window*/ -#define LL_USART_POLARITY_HIGH USART_CR2_CPOL /*!< Steady high value on SCLK pin outside transmission window */ -/** - * @} - */ - -/** @defgroup USART_LL_EC_STOPBITS Stop Bits - * @{ - */ -#define LL_USART_STOPBITS_0_5 USART_CR2_STOP_0 /*!< 0.5 stop bit */ -#define LL_USART_STOPBITS_1 0x00000000U /*!< 1 stop bit */ -#define LL_USART_STOPBITS_1_5 (USART_CR2_STOP_0 | USART_CR2_STOP_1) /*!< 1.5 stop bits */ -#define LL_USART_STOPBITS_2 USART_CR2_STOP_1 /*!< 2 stop bits */ -/** - * @} - */ - -/** @defgroup USART_LL_EC_HWCONTROL Hardware Control - * @{ - */ -#define LL_USART_HWCONTROL_NONE 0x00000000U /*!< CTS and RTS hardware flow control disabled */ -#define LL_USART_HWCONTROL_RTS USART_CR3_RTSE /*!< RTS output enabled, data is only requested when there is space in the receive buffer */ -#define LL_USART_HWCONTROL_CTS USART_CR3_CTSE /*!< CTS mode enabled, data is only transmitted when the nCTS input is asserted (tied to 0) */ -#define LL_USART_HWCONTROL_RTS_CTS (USART_CR3_RTSE | USART_CR3_CTSE) /*!< CTS and RTS hardware flow control enabled */ -/** - * @} - */ - -/** @defgroup USART_LL_EC_IRDA_POWER IrDA Power - * @{ - */ -#define LL_USART_IRDA_POWER_NORMAL 0x00000000U /*!< IrDA normal power mode */ -#define LL_USART_IRDA_POWER_LOW USART_CR3_IRLP /*!< IrDA low power mode */ -/** - * @} - */ - -/** @defgroup USART_LL_EC_LINBREAK_DETECT LIN Break Detection Length - * @{ - */ -#define LL_USART_LINBREAK_DETECT_10B 0x00000000U /*!< 10-bit break detection method selected */ -#define LL_USART_LINBREAK_DETECT_11B USART_CR2_LBDL /*!< 11-bit break detection method selected */ -/** - * @} - */ - -/** - * @} - */ - -/* Exported macro ------------------------------------------------------------*/ -/** @defgroup USART_LL_Exported_Macros USART Exported Macros - * @{ - */ - -/** @defgroup USART_LL_EM_WRITE_READ Common Write and read registers Macros - * @{ - */ - -/** - * @brief Write a value in USART register - * @param __INSTANCE__ USART Instance - * @param __REG__ Register to be written - * @param __VALUE__ Value to be written in the register - * @retval None - */ -#define LL_USART_WriteReg(__INSTANCE__, __REG__, __VALUE__) WRITE_REG(__INSTANCE__->__REG__, (__VALUE__)) - -/** - * @brief Read a value in USART register - * @param __INSTANCE__ USART Instance - * @param __REG__ Register to be read - * @retval Register value - */ -#define LL_USART_ReadReg(__INSTANCE__, __REG__) READ_REG(__INSTANCE__->__REG__) -/** - * @} - */ - -/** @defgroup USART_LL_EM_Exported_Macros_Helper Exported_Macros_Helper - * @{ - */ - -/** - * @brief Compute USARTDIV value according to Peripheral Clock and - * expected Baud Rate in 8 bits sampling mode (32 bits value of USARTDIV is returned) - * @param __PERIPHCLK__ Peripheral Clock frequency used for USART instance - * @param __BAUDRATE__ Baud rate value to achieve - * @retval USARTDIV value to be used for BRR register filling in OverSampling_8 case - */ -#define __LL_USART_DIV_SAMPLING8_100(__PERIPHCLK__, __BAUDRATE__) (((__PERIPHCLK__)*25)/(2*(__BAUDRATE__))) -#define __LL_USART_DIVMANT_SAMPLING8(__PERIPHCLK__, __BAUDRATE__) (__LL_USART_DIV_SAMPLING8_100((__PERIPHCLK__), (__BAUDRATE__))/100) -#define __LL_USART_DIVFRAQ_SAMPLING8(__PERIPHCLK__, __BAUDRATE__) (((__LL_USART_DIV_SAMPLING8_100((__PERIPHCLK__), (__BAUDRATE__)) - (__LL_USART_DIVMANT_SAMPLING8((__PERIPHCLK__), (__BAUDRATE__)) * 100)) * 8 + 50) / 100) -/* UART BRR = mantissa + overflow + fraction - = (UART DIVMANT << 4) + ((UART DIVFRAQ & 0xF8) << 1) + (UART DIVFRAQ & 0x07) */ -#define __LL_USART_DIV_SAMPLING8(__PERIPHCLK__, __BAUDRATE__) (((__LL_USART_DIVMANT_SAMPLING8((__PERIPHCLK__), (__BAUDRATE__)) << 4) + \ - ((__LL_USART_DIVFRAQ_SAMPLING8((__PERIPHCLK__), (__BAUDRATE__)) & 0xF8) << 1)) + \ - (__LL_USART_DIVFRAQ_SAMPLING8((__PERIPHCLK__), (__BAUDRATE__)) & 0x07)) - -/** - * @brief Compute USARTDIV value according to Peripheral Clock and - * expected Baud Rate in 16 bits sampling mode (32 bits value of USARTDIV is returned) - * @param __PERIPHCLK__ Peripheral Clock frequency used for USART instance - * @param __BAUDRATE__ Baud rate value to achieve - * @retval USARTDIV value to be used for BRR register filling in OverSampling_16 case - */ -#define __LL_USART_DIV_SAMPLING16_100(__PERIPHCLK__, __BAUDRATE__) (((__PERIPHCLK__)*25)/(4*(__BAUDRATE__))) -#define __LL_USART_DIVMANT_SAMPLING16(__PERIPHCLK__, __BAUDRATE__) (__LL_USART_DIV_SAMPLING16_100((__PERIPHCLK__), (__BAUDRATE__))/100) -#define __LL_USART_DIVFRAQ_SAMPLING16(__PERIPHCLK__, __BAUDRATE__) (((__LL_USART_DIV_SAMPLING16_100((__PERIPHCLK__), (__BAUDRATE__)) - (__LL_USART_DIVMANT_SAMPLING16((__PERIPHCLK__), (__BAUDRATE__)) * 100)) * 16 + 50) / 100) -/* USART BRR = mantissa + overflow + fraction - = (USART DIVMANT << 4) + (USART DIVFRAQ & 0xF0) + (USART DIVFRAQ & 0x0F) */ -#define __LL_USART_DIV_SAMPLING16(__PERIPHCLK__, __BAUDRATE__) (((__LL_USART_DIVMANT_SAMPLING16((__PERIPHCLK__), (__BAUDRATE__)) << 4) + \ - (__LL_USART_DIVFRAQ_SAMPLING16((__PERIPHCLK__), (__BAUDRATE__)) & 0xF0)) + \ - (__LL_USART_DIVFRAQ_SAMPLING16((__PERIPHCLK__), (__BAUDRATE__)) & 0x0F)) - -/** - * @} - */ - -/** - * @} - */ - -/* Exported functions --------------------------------------------------------*/ - -/** @defgroup USART_LL_Exported_Functions USART Exported Functions - * @{ - */ - -/** @defgroup USART_LL_EF_Configuration Configuration functions - * @{ - */ - -/** - * @brief USART Enable - * @rmtoll CR1 UE LL_USART_Enable - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_Enable(USART_TypeDef *USARTx) -{ - SET_BIT(USARTx->CR1, USART_CR1_UE); -} - -/** - * @brief USART Disable (all USART prescalers and outputs are disabled) - * @note When USART is disabled, USART prescalers and outputs are stopped immediately, - * and current operations are discarded. The configuration of the USART is kept, but all the status - * flags, in the USARTx_SR are set to their default values. - * @rmtoll CR1 UE LL_USART_Disable - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_Disable(USART_TypeDef *USARTx) -{ - CLEAR_BIT(USARTx->CR1, USART_CR1_UE); -} - -/** - * @brief Indicate if USART is enabled - * @rmtoll CR1 UE LL_USART_IsEnabled - * @param USARTx USART Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_USART_IsEnabled(USART_TypeDef *USARTx) -{ - return (READ_BIT(USARTx->CR1, USART_CR1_UE) == (USART_CR1_UE)); -} - -/** - * @brief Receiver Enable (Receiver is enabled and begins searching for a start bit) - * @rmtoll CR1 RE LL_USART_EnableDirectionRx - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_EnableDirectionRx(USART_TypeDef *USARTx) -{ - SET_BIT(USARTx->CR1, USART_CR1_RE); -} - -/** - * @brief Receiver Disable - * @rmtoll CR1 RE LL_USART_DisableDirectionRx - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_DisableDirectionRx(USART_TypeDef *USARTx) -{ - CLEAR_BIT(USARTx->CR1, USART_CR1_RE); -} - -/** - * @brief Transmitter Enable - * @rmtoll CR1 TE LL_USART_EnableDirectionTx - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_EnableDirectionTx(USART_TypeDef *USARTx) -{ - SET_BIT(USARTx->CR1, USART_CR1_TE); -} - -/** - * @brief Transmitter Disable - * @rmtoll CR1 TE LL_USART_DisableDirectionTx - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_DisableDirectionTx(USART_TypeDef *USARTx) -{ - CLEAR_BIT(USARTx->CR1, USART_CR1_TE); -} - -/** - * @brief Configure simultaneously enabled/disabled states - * of Transmitter and Receiver - * @rmtoll CR1 RE LL_USART_SetTransferDirection\n - * CR1 TE LL_USART_SetTransferDirection - * @param USARTx USART Instance - * @param TransferDirection This parameter can be one of the following values: - * @arg @ref LL_USART_DIRECTION_NONE - * @arg @ref LL_USART_DIRECTION_RX - * @arg @ref LL_USART_DIRECTION_TX - * @arg @ref LL_USART_DIRECTION_TX_RX - * @retval None - */ -__STATIC_INLINE void LL_USART_SetTransferDirection(USART_TypeDef *USARTx, uint32_t TransferDirection) -{ - MODIFY_REG(USARTx->CR1, USART_CR1_RE | USART_CR1_TE, TransferDirection); -} - -/** - * @brief Return enabled/disabled states of Transmitter and Receiver - * @rmtoll CR1 RE LL_USART_GetTransferDirection\n - * CR1 TE LL_USART_GetTransferDirection - * @param USARTx USART Instance - * @retval Returned value can be one of the following values: - * @arg @ref LL_USART_DIRECTION_NONE - * @arg @ref LL_USART_DIRECTION_RX - * @arg @ref LL_USART_DIRECTION_TX - * @arg @ref LL_USART_DIRECTION_TX_RX - */ -__STATIC_INLINE uint32_t LL_USART_GetTransferDirection(USART_TypeDef *USARTx) -{ - return (uint32_t)(READ_BIT(USARTx->CR1, USART_CR1_RE | USART_CR1_TE)); -} - -/** - * @brief Configure Parity (enabled/disabled and parity mode if enabled). - * @note This function selects if hardware parity control (generation and detection) is enabled or disabled. - * When the parity control is enabled (Odd or Even), computed parity bit is inserted at the MSB position - * (9th or 8th bit depending on data width) and parity is checked on the received data. - * @rmtoll CR1 PS LL_USART_SetParity\n - * CR1 PCE LL_USART_SetParity - * @param USARTx USART Instance - * @param Parity This parameter can be one of the following values: - * @arg @ref LL_USART_PARITY_NONE - * @arg @ref LL_USART_PARITY_EVEN - * @arg @ref LL_USART_PARITY_ODD - * @retval None - */ -__STATIC_INLINE void LL_USART_SetParity(USART_TypeDef *USARTx, uint32_t Parity) -{ - MODIFY_REG(USARTx->CR1, USART_CR1_PS | USART_CR1_PCE, Parity); -} - -/** - * @brief Return Parity configuration (enabled/disabled and parity mode if enabled) - * @rmtoll CR1 PS LL_USART_GetParity\n - * CR1 PCE LL_USART_GetParity - * @param USARTx USART Instance - * @retval Returned value can be one of the following values: - * @arg @ref LL_USART_PARITY_NONE - * @arg @ref LL_USART_PARITY_EVEN - * @arg @ref LL_USART_PARITY_ODD - */ -__STATIC_INLINE uint32_t LL_USART_GetParity(USART_TypeDef *USARTx) -{ - return (uint32_t)(READ_BIT(USARTx->CR1, USART_CR1_PS | USART_CR1_PCE)); -} - -/** - * @brief Set Receiver Wake Up method from Mute mode. - * @rmtoll CR1 WAKE LL_USART_SetWakeUpMethod - * @param USARTx USART Instance - * @param Method This parameter can be one of the following values: - * @arg @ref LL_USART_WAKEUP_IDLELINE - * @arg @ref LL_USART_WAKEUP_ADDRESSMARK - * @retval None - */ -__STATIC_INLINE void LL_USART_SetWakeUpMethod(USART_TypeDef *USARTx, uint32_t Method) -{ - MODIFY_REG(USARTx->CR1, USART_CR1_WAKE, Method); -} - -/** - * @brief Return Receiver Wake Up method from Mute mode - * @rmtoll CR1 WAKE LL_USART_GetWakeUpMethod - * @param USARTx USART Instance - * @retval Returned value can be one of the following values: - * @arg @ref LL_USART_WAKEUP_IDLELINE - * @arg @ref LL_USART_WAKEUP_ADDRESSMARK - */ -__STATIC_INLINE uint32_t LL_USART_GetWakeUpMethod(USART_TypeDef *USARTx) -{ - return (uint32_t)(READ_BIT(USARTx->CR1, USART_CR1_WAKE)); -} - -/** - * @brief Set Word length (i.e. nb of data bits, excluding start and stop bits) - * @rmtoll CR1 M LL_USART_SetDataWidth - * @param USARTx USART Instance - * @param DataWidth This parameter can be one of the following values: - * @arg @ref LL_USART_DATAWIDTH_8B - * @arg @ref LL_USART_DATAWIDTH_9B - * @retval None - */ -__STATIC_INLINE void LL_USART_SetDataWidth(USART_TypeDef *USARTx, uint32_t DataWidth) -{ - MODIFY_REG(USARTx->CR1, USART_CR1_M, DataWidth); -} - -/** - * @brief Return Word length (i.e. nb of data bits, excluding start and stop bits) - * @rmtoll CR1 M LL_USART_GetDataWidth - * @param USARTx USART Instance - * @retval Returned value can be one of the following values: - * @arg @ref LL_USART_DATAWIDTH_8B - * @arg @ref LL_USART_DATAWIDTH_9B - */ -__STATIC_INLINE uint32_t LL_USART_GetDataWidth(USART_TypeDef *USARTx) -{ - return (uint32_t)(READ_BIT(USARTx->CR1, USART_CR1_M)); -} - -#if defined(USART_CR1_OVER8) -/** - * @brief Set Oversampling to 8-bit or 16-bit mode - * @rmtoll CR1 OVER8 LL_USART_SetOverSampling - * @param USARTx USART Instance - * @param OverSampling This parameter can be one of the following values: - * @arg @ref LL_USART_OVERSAMPLING_16 - * @arg @ref LL_USART_OVERSAMPLING_8 - * @retval None - */ -__STATIC_INLINE void LL_USART_SetOverSampling(USART_TypeDef *USARTx, uint32_t OverSampling) -{ - MODIFY_REG(USARTx->CR1, USART_CR1_OVER8, OverSampling); -} - -/** - * @brief Return Oversampling mode - * @rmtoll CR1 OVER8 LL_USART_GetOverSampling - * @param USARTx USART Instance - * @retval Returned value can be one of the following values: - * @arg @ref LL_USART_OVERSAMPLING_16 - * @arg @ref LL_USART_OVERSAMPLING_8 - */ -__STATIC_INLINE uint32_t LL_USART_GetOverSampling(USART_TypeDef *USARTx) -{ - return (uint32_t)(READ_BIT(USARTx->CR1, USART_CR1_OVER8)); -} - -#endif /* USART_OverSampling_Feature */ -/** - * @brief Configure if Clock pulse of the last data bit is output to the SCLK pin or not - * @note Macro @ref IS_USART_INSTANCE(USARTx) can be used to check whether or not - * Synchronous mode is supported by the USARTx instance. - * @rmtoll CR2 LBCL LL_USART_SetLastClkPulseOutput - * @param USARTx USART Instance - * @param LastBitClockPulse This parameter can be one of the following values: - * @arg @ref LL_USART_LASTCLKPULSE_NO_OUTPUT - * @arg @ref LL_USART_LASTCLKPULSE_OUTPUT - * @retval None - */ -__STATIC_INLINE void LL_USART_SetLastClkPulseOutput(USART_TypeDef *USARTx, uint32_t LastBitClockPulse) -{ - MODIFY_REG(USARTx->CR2, USART_CR2_LBCL, LastBitClockPulse); -} - -/** - * @brief Retrieve Clock pulse of the last data bit output configuration - * (Last bit Clock pulse output to the SCLK pin or not) - * @note Macro @ref IS_USART_INSTANCE(USARTx) can be used to check whether or not - * Synchronous mode is supported by the USARTx instance. - * @rmtoll CR2 LBCL LL_USART_GetLastClkPulseOutput - * @param USARTx USART Instance - * @retval Returned value can be one of the following values: - * @arg @ref LL_USART_LASTCLKPULSE_NO_OUTPUT - * @arg @ref LL_USART_LASTCLKPULSE_OUTPUT - */ -__STATIC_INLINE uint32_t LL_USART_GetLastClkPulseOutput(USART_TypeDef *USARTx) -{ - return (uint32_t)(READ_BIT(USARTx->CR2, USART_CR2_LBCL)); -} - -/** - * @brief Select the phase of the clock output on the SCLK pin in synchronous mode - * @note Macro @ref IS_USART_INSTANCE(USARTx) can be used to check whether or not - * Synchronous mode is supported by the USARTx instance. - * @rmtoll CR2 CPHA LL_USART_SetClockPhase - * @param USARTx USART Instance - * @param ClockPhase This parameter can be one of the following values: - * @arg @ref LL_USART_PHASE_1EDGE - * @arg @ref LL_USART_PHASE_2EDGE - * @retval None - */ -__STATIC_INLINE void LL_USART_SetClockPhase(USART_TypeDef *USARTx, uint32_t ClockPhase) -{ - MODIFY_REG(USARTx->CR2, USART_CR2_CPHA, ClockPhase); -} - -/** - * @brief Return phase of the clock output on the SCLK pin in synchronous mode - * @note Macro @ref IS_USART_INSTANCE(USARTx) can be used to check whether or not - * Synchronous mode is supported by the USARTx instance. - * @rmtoll CR2 CPHA LL_USART_GetClockPhase - * @param USARTx USART Instance - * @retval Returned value can be one of the following values: - * @arg @ref LL_USART_PHASE_1EDGE - * @arg @ref LL_USART_PHASE_2EDGE - */ -__STATIC_INLINE uint32_t LL_USART_GetClockPhase(USART_TypeDef *USARTx) -{ - return (uint32_t)(READ_BIT(USARTx->CR2, USART_CR2_CPHA)); -} - -/** - * @brief Select the polarity of the clock output on the SCLK pin in synchronous mode - * @note Macro @ref IS_USART_INSTANCE(USARTx) can be used to check whether or not - * Synchronous mode is supported by the USARTx instance. - * @rmtoll CR2 CPOL LL_USART_SetClockPolarity - * @param USARTx USART Instance - * @param ClockPolarity This parameter can be one of the following values: - * @arg @ref LL_USART_POLARITY_LOW - * @arg @ref LL_USART_POLARITY_HIGH - * @retval None - */ -__STATIC_INLINE void LL_USART_SetClockPolarity(USART_TypeDef *USARTx, uint32_t ClockPolarity) -{ - MODIFY_REG(USARTx->CR2, USART_CR2_CPOL, ClockPolarity); -} - -/** - * @brief Return polarity of the clock output on the SCLK pin in synchronous mode - * @note Macro @ref IS_USART_INSTANCE(USARTx) can be used to check whether or not - * Synchronous mode is supported by the USARTx instance. - * @rmtoll CR2 CPOL LL_USART_GetClockPolarity - * @param USARTx USART Instance - * @retval Returned value can be one of the following values: - * @arg @ref LL_USART_POLARITY_LOW - * @arg @ref LL_USART_POLARITY_HIGH - */ -__STATIC_INLINE uint32_t LL_USART_GetClockPolarity(USART_TypeDef *USARTx) -{ - return (uint32_t)(READ_BIT(USARTx->CR2, USART_CR2_CPOL)); -} - -/** - * @brief Configure Clock signal format (Phase Polarity and choice about output of last bit clock pulse) - * @note Macro @ref IS_USART_INSTANCE(USARTx) can be used to check whether or not - * Synchronous mode is supported by the USARTx instance. - * @note Call of this function is equivalent to following function call sequence : - * - Clock Phase configuration using @ref LL_USART_SetClockPhase() function - * - Clock Polarity configuration using @ref LL_USART_SetClockPolarity() function - * - Output of Last bit Clock pulse configuration using @ref LL_USART_SetLastClkPulseOutput() function - * @rmtoll CR2 CPHA LL_USART_ConfigClock\n - * CR2 CPOL LL_USART_ConfigClock\n - * CR2 LBCL LL_USART_ConfigClock - * @param USARTx USART Instance - * @param Phase This parameter can be one of the following values: - * @arg @ref LL_USART_PHASE_1EDGE - * @arg @ref LL_USART_PHASE_2EDGE - * @param Polarity This parameter can be one of the following values: - * @arg @ref LL_USART_POLARITY_LOW - * @arg @ref LL_USART_POLARITY_HIGH - * @param LBCPOutput This parameter can be one of the following values: - * @arg @ref LL_USART_LASTCLKPULSE_NO_OUTPUT - * @arg @ref LL_USART_LASTCLKPULSE_OUTPUT - * @retval None - */ -__STATIC_INLINE void LL_USART_ConfigClock(USART_TypeDef *USARTx, uint32_t Phase, uint32_t Polarity, uint32_t LBCPOutput) -{ - MODIFY_REG(USARTx->CR2, USART_CR2_CPHA | USART_CR2_CPOL | USART_CR2_LBCL, Phase | Polarity | LBCPOutput); -} - -/** - * @brief Enable Clock output on SCLK pin - * @note Macro @ref IS_USART_INSTANCE(USARTx) can be used to check whether or not - * Synchronous mode is supported by the USARTx instance. - * @rmtoll CR2 CLKEN LL_USART_EnableSCLKOutput - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_EnableSCLKOutput(USART_TypeDef *USARTx) -{ - SET_BIT(USARTx->CR2, USART_CR2_CLKEN); -} - -/** - * @brief Disable Clock output on SCLK pin - * @note Macro @ref IS_USART_INSTANCE(USARTx) can be used to check whether or not - * Synchronous mode is supported by the USARTx instance. - * @rmtoll CR2 CLKEN LL_USART_DisableSCLKOutput - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_DisableSCLKOutput(USART_TypeDef *USARTx) -{ - CLEAR_BIT(USARTx->CR2, USART_CR2_CLKEN); -} - -/** - * @brief Indicate if Clock output on SCLK pin is enabled - * @note Macro @ref IS_USART_INSTANCE(USARTx) can be used to check whether or not - * Synchronous mode is supported by the USARTx instance. - * @rmtoll CR2 CLKEN LL_USART_IsEnabledSCLKOutput - * @param USARTx USART Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_USART_IsEnabledSCLKOutput(USART_TypeDef *USARTx) -{ - return (READ_BIT(USARTx->CR2, USART_CR2_CLKEN) == (USART_CR2_CLKEN)); -} - -/** - * @brief Set the length of the stop bits - * @rmtoll CR2 STOP LL_USART_SetStopBitsLength - * @param USARTx USART Instance - * @param StopBits This parameter can be one of the following values: - * @arg @ref LL_USART_STOPBITS_0_5 - * @arg @ref LL_USART_STOPBITS_1 - * @arg @ref LL_USART_STOPBITS_1_5 - * @arg @ref LL_USART_STOPBITS_2 - * @retval None - */ -__STATIC_INLINE void LL_USART_SetStopBitsLength(USART_TypeDef *USARTx, uint32_t StopBits) -{ - MODIFY_REG(USARTx->CR2, USART_CR2_STOP, StopBits); -} - -/** - * @brief Retrieve the length of the stop bits - * @rmtoll CR2 STOP LL_USART_GetStopBitsLength - * @param USARTx USART Instance - * @retval Returned value can be one of the following values: - * @arg @ref LL_USART_STOPBITS_0_5 - * @arg @ref LL_USART_STOPBITS_1 - * @arg @ref LL_USART_STOPBITS_1_5 - * @arg @ref LL_USART_STOPBITS_2 - */ -__STATIC_INLINE uint32_t LL_USART_GetStopBitsLength(USART_TypeDef *USARTx) -{ - return (uint32_t)(READ_BIT(USARTx->CR2, USART_CR2_STOP)); -} - -/** - * @brief Configure Character frame format (Datawidth, Parity control, Stop Bits) - * @note Call of this function is equivalent to following function call sequence : - * - Data Width configuration using @ref LL_USART_SetDataWidth() function - * - Parity Control and mode configuration using @ref LL_USART_SetParity() function - * - Stop bits configuration using @ref LL_USART_SetStopBitsLength() function - * @rmtoll CR1 PS LL_USART_ConfigCharacter\n - * CR1 PCE LL_USART_ConfigCharacter\n - * CR1 M LL_USART_ConfigCharacter\n - * CR2 STOP LL_USART_ConfigCharacter - * @param USARTx USART Instance - * @param DataWidth This parameter can be one of the following values: - * @arg @ref LL_USART_DATAWIDTH_8B - * @arg @ref LL_USART_DATAWIDTH_9B - * @param Parity This parameter can be one of the following values: - * @arg @ref LL_USART_PARITY_NONE - * @arg @ref LL_USART_PARITY_EVEN - * @arg @ref LL_USART_PARITY_ODD - * @param StopBits This parameter can be one of the following values: - * @arg @ref LL_USART_STOPBITS_0_5 - * @arg @ref LL_USART_STOPBITS_1 - * @arg @ref LL_USART_STOPBITS_1_5 - * @arg @ref LL_USART_STOPBITS_2 - * @retval None - */ -__STATIC_INLINE void LL_USART_ConfigCharacter(USART_TypeDef *USARTx, uint32_t DataWidth, uint32_t Parity, - uint32_t StopBits) -{ - MODIFY_REG(USARTx->CR1, USART_CR1_PS | USART_CR1_PCE | USART_CR1_M, Parity | DataWidth); - MODIFY_REG(USARTx->CR2, USART_CR2_STOP, StopBits); -} - -/** - * @brief Set Address of the USART node. - * @note This is used in multiprocessor communication during Mute mode or Stop mode, - * for wake up with address mark detection. - * @rmtoll CR2 ADD LL_USART_SetNodeAddress - * @param USARTx USART Instance - * @param NodeAddress 4 bit Address of the USART node. - * @retval None - */ -__STATIC_INLINE void LL_USART_SetNodeAddress(USART_TypeDef *USARTx, uint32_t NodeAddress) -{ - MODIFY_REG(USARTx->CR2, USART_CR2_ADD, (NodeAddress & USART_CR2_ADD)); -} - -/** - * @brief Return 4 bit Address of the USART node as set in ADD field of CR2. - * @note only 4bits (b3-b0) of returned value are relevant (b31-b4 are not relevant) - * @rmtoll CR2 ADD LL_USART_GetNodeAddress - * @param USARTx USART Instance - * @retval Address of the USART node (Value between Min_Data=0 and Max_Data=255) - */ -__STATIC_INLINE uint32_t LL_USART_GetNodeAddress(USART_TypeDef *USARTx) -{ - return (uint32_t)(READ_BIT(USARTx->CR2, USART_CR2_ADD)); -} - -/** - * @brief Enable RTS HW Flow Control - * @note Macro @ref IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not - * Hardware Flow control feature is supported by the USARTx instance. - * @rmtoll CR3 RTSE LL_USART_EnableRTSHWFlowCtrl - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_EnableRTSHWFlowCtrl(USART_TypeDef *USARTx) -{ - SET_BIT(USARTx->CR3, USART_CR3_RTSE); -} - -/** - * @brief Disable RTS HW Flow Control - * @note Macro @ref IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not - * Hardware Flow control feature is supported by the USARTx instance. - * @rmtoll CR3 RTSE LL_USART_DisableRTSHWFlowCtrl - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_DisableRTSHWFlowCtrl(USART_TypeDef *USARTx) -{ - CLEAR_BIT(USARTx->CR3, USART_CR3_RTSE); -} - -/** - * @brief Enable CTS HW Flow Control - * @note Macro @ref IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not - * Hardware Flow control feature is supported by the USARTx instance. - * @rmtoll CR3 CTSE LL_USART_EnableCTSHWFlowCtrl - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_EnableCTSHWFlowCtrl(USART_TypeDef *USARTx) -{ - SET_BIT(USARTx->CR3, USART_CR3_CTSE); -} - -/** - * @brief Disable CTS HW Flow Control - * @note Macro @ref IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not - * Hardware Flow control feature is supported by the USARTx instance. - * @rmtoll CR3 CTSE LL_USART_DisableCTSHWFlowCtrl - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_DisableCTSHWFlowCtrl(USART_TypeDef *USARTx) -{ - CLEAR_BIT(USARTx->CR3, USART_CR3_CTSE); -} - -/** - * @brief Configure HW Flow Control mode (both CTS and RTS) - * @note Macro @ref IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not - * Hardware Flow control feature is supported by the USARTx instance. - * @rmtoll CR3 RTSE LL_USART_SetHWFlowCtrl\n - * CR3 CTSE LL_USART_SetHWFlowCtrl - * @param USARTx USART Instance - * @param HardwareFlowControl This parameter can be one of the following values: - * @arg @ref LL_USART_HWCONTROL_NONE - * @arg @ref LL_USART_HWCONTROL_RTS - * @arg @ref LL_USART_HWCONTROL_CTS - * @arg @ref LL_USART_HWCONTROL_RTS_CTS - * @retval None - */ -__STATIC_INLINE void LL_USART_SetHWFlowCtrl(USART_TypeDef *USARTx, uint32_t HardwareFlowControl) -{ - MODIFY_REG(USARTx->CR3, USART_CR3_RTSE | USART_CR3_CTSE, HardwareFlowControl); -} - -/** - * @brief Return HW Flow Control configuration (both CTS and RTS) - * @note Macro @ref IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not - * Hardware Flow control feature is supported by the USARTx instance. - * @rmtoll CR3 RTSE LL_USART_GetHWFlowCtrl\n - * CR3 CTSE LL_USART_GetHWFlowCtrl - * @param USARTx USART Instance - * @retval Returned value can be one of the following values: - * @arg @ref LL_USART_HWCONTROL_NONE - * @arg @ref LL_USART_HWCONTROL_RTS - * @arg @ref LL_USART_HWCONTROL_CTS - * @arg @ref LL_USART_HWCONTROL_RTS_CTS - */ -__STATIC_INLINE uint32_t LL_USART_GetHWFlowCtrl(USART_TypeDef *USARTx) -{ - return (uint32_t)(READ_BIT(USARTx->CR3, USART_CR3_RTSE | USART_CR3_CTSE)); -} - -#if defined(USART_CR3_ONEBIT) -/** - * @brief Enable One bit sampling method - * @rmtoll CR3 ONEBIT LL_USART_EnableOneBitSamp - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_EnableOneBitSamp(USART_TypeDef *USARTx) -{ - SET_BIT(USARTx->CR3, USART_CR3_ONEBIT); -} - -/** - * @brief Disable One bit sampling method - * @rmtoll CR3 ONEBIT LL_USART_DisableOneBitSamp - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_DisableOneBitSamp(USART_TypeDef *USARTx) -{ - CLEAR_BIT(USARTx->CR3, USART_CR3_ONEBIT); -} - -/** - * @brief Indicate if One bit sampling method is enabled - * @rmtoll CR3 ONEBIT LL_USART_IsEnabledOneBitSamp - * @param USARTx USART Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_USART_IsEnabledOneBitSamp(USART_TypeDef *USARTx) -{ - return (READ_BIT(USARTx->CR3, USART_CR3_ONEBIT) == (USART_CR3_ONEBIT)); -} -#endif /* USART_OneBitSampling_Feature */ - -#if defined(USART_CR1_OVER8) -/** - * @brief Configure USART BRR register for achieving expected Baud Rate value. - * @note Compute and set USARTDIV value in BRR Register (full BRR content) - * according to used Peripheral Clock, Oversampling mode, and expected Baud Rate values - * @note Peripheral clock and Baud rate values provided as function parameters should be valid - * (Baud rate value != 0) - * @rmtoll BRR BRR LL_USART_SetBaudRate - * @param USARTx USART Instance - * @param PeriphClk Peripheral Clock - * @param OverSampling This parameter can be one of the following values: - * @arg @ref LL_USART_OVERSAMPLING_16 - * @arg @ref LL_USART_OVERSAMPLING_8 - * @param BaudRate Baud Rate - * @retval None - */ -__STATIC_INLINE void LL_USART_SetBaudRate(USART_TypeDef *USARTx, uint32_t PeriphClk, uint32_t OverSampling, - uint32_t BaudRate) -{ - if (OverSampling == LL_USART_OVERSAMPLING_8) - { - USARTx->BRR = (uint16_t)(__LL_USART_DIV_SAMPLING8(PeriphClk, BaudRate)); - } - else - { - USARTx->BRR = (uint16_t)(__LL_USART_DIV_SAMPLING16(PeriphClk, BaudRate)); - } -} - -/** - * @brief Return current Baud Rate value, according to USARTDIV present in BRR register - * (full BRR content), and to used Peripheral Clock and Oversampling mode values - * @note In case of non-initialized or invalid value stored in BRR register, value 0 will be returned. - * @rmtoll BRR BRR LL_USART_GetBaudRate - * @param USARTx USART Instance - * @param PeriphClk Peripheral Clock - * @param OverSampling This parameter can be one of the following values: - * @arg @ref LL_USART_OVERSAMPLING_16 - * @arg @ref LL_USART_OVERSAMPLING_8 - * @retval Baud Rate - */ -__STATIC_INLINE uint32_t LL_USART_GetBaudRate(USART_TypeDef *USARTx, uint32_t PeriphClk, uint32_t OverSampling) -{ - register uint32_t usartdiv = 0x0U; - register uint32_t brrresult = 0x0U; - - usartdiv = USARTx->BRR; - - if (OverSampling == LL_USART_OVERSAMPLING_8) - { - if ((usartdiv & 0xFFF7U) != 0U) - { - usartdiv = (uint16_t)((usartdiv & 0xFFF0U) | ((usartdiv & 0x0007U) << 1U)) ; - brrresult = (PeriphClk * 2U) / usartdiv; - } - } - else - { - if ((usartdiv & 0xFFFFU) != 0U) - { - brrresult = PeriphClk / usartdiv; - } - } - return (brrresult); -} -#else -/** - * @brief Configure USART BRR register for achieving expected Baud Rate value. - * @note Compute and set USARTDIV value in BRR Register (full BRR content) - * according to used Peripheral Clock, Oversampling mode, and expected Baud Rate values - * @note Peripheral clock and Baud rate values provided as function parameters should be valid - * (Baud rate value != 0) - * @rmtoll BRR BRR LL_USART_SetBaudRate - * @param USARTx USART Instance - * @param PeriphClk Peripheral Clock - * @param BaudRate Baud Rate - * @retval None - */ -__STATIC_INLINE void LL_USART_SetBaudRate(USART_TypeDef *USARTx, uint32_t PeriphClk, uint32_t BaudRate) -{ - USARTx->BRR = (uint16_t)(__LL_USART_DIV_SAMPLING16(PeriphClk, BaudRate)); -} - -/** - * @brief Return current Baud Rate value, according to USARTDIV present in BRR register - * (full BRR content), and to used Peripheral Clock and Oversampling mode values - * @note In case of non-initialized or invalid value stored in BRR register, value 0 will be returned. - * @rmtoll BRR BRR LL_USART_GetBaudRate - * @param USARTx USART Instance - * @param PeriphClk Peripheral Clock - * @retval Baud Rate - */ -__STATIC_INLINE uint32_t LL_USART_GetBaudRate(USART_TypeDef *USARTx, uint32_t PeriphClk) -{ - register uint32_t usartdiv = 0x0U; - register uint32_t brrresult = 0x0U; - - usartdiv = USARTx->BRR; - - if ((usartdiv & 0xFFFFU) != 0U) - { - brrresult = PeriphClk / usartdiv; - } - return (brrresult); -} -#endif /* USART_OverSampling_Feature */ - -/** - * @} - */ - -/** @defgroup USART_LL_EF_Configuration_IRDA Configuration functions related to Irda feature - * @{ - */ - -/** - * @brief Enable IrDA mode - * @note Macro @ref IS_IRDA_INSTANCE(USARTx) can be used to check whether or not - * IrDA feature is supported by the USARTx instance. - * @rmtoll CR3 IREN LL_USART_EnableIrda - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_EnableIrda(USART_TypeDef *USARTx) -{ - SET_BIT(USARTx->CR3, USART_CR3_IREN); -} - -/** - * @brief Disable IrDA mode - * @note Macro @ref IS_IRDA_INSTANCE(USARTx) can be used to check whether or not - * IrDA feature is supported by the USARTx instance. - * @rmtoll CR3 IREN LL_USART_DisableIrda - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_DisableIrda(USART_TypeDef *USARTx) -{ - CLEAR_BIT(USARTx->CR3, USART_CR3_IREN); -} - -/** - * @brief Indicate if IrDA mode is enabled - * @note Macro @ref IS_IRDA_INSTANCE(USARTx) can be used to check whether or not - * IrDA feature is supported by the USARTx instance. - * @rmtoll CR3 IREN LL_USART_IsEnabledIrda - * @param USARTx USART Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_USART_IsEnabledIrda(USART_TypeDef *USARTx) -{ - return (READ_BIT(USARTx->CR3, USART_CR3_IREN) == (USART_CR3_IREN)); -} - -/** - * @brief Configure IrDA Power Mode (Normal or Low Power) - * @note Macro @ref IS_IRDA_INSTANCE(USARTx) can be used to check whether or not - * IrDA feature is supported by the USARTx instance. - * @rmtoll CR3 IRLP LL_USART_SetIrdaPowerMode - * @param USARTx USART Instance - * @param PowerMode This parameter can be one of the following values: - * @arg @ref LL_USART_IRDA_POWER_NORMAL - * @arg @ref LL_USART_IRDA_POWER_LOW - * @retval None - */ -__STATIC_INLINE void LL_USART_SetIrdaPowerMode(USART_TypeDef *USARTx, uint32_t PowerMode) -{ - MODIFY_REG(USARTx->CR3, USART_CR3_IRLP, PowerMode); -} - -/** - * @brief Retrieve IrDA Power Mode configuration (Normal or Low Power) - * @note Macro @ref IS_IRDA_INSTANCE(USARTx) can be used to check whether or not - * IrDA feature is supported by the USARTx instance. - * @rmtoll CR3 IRLP LL_USART_GetIrdaPowerMode - * @param USARTx USART Instance - * @retval Returned value can be one of the following values: - * @arg @ref LL_USART_IRDA_POWER_NORMAL - * @arg @ref LL_USART_PHASE_2EDGE - */ -__STATIC_INLINE uint32_t LL_USART_GetIrdaPowerMode(USART_TypeDef *USARTx) -{ - return (uint32_t)(READ_BIT(USARTx->CR3, USART_CR3_IRLP)); -} - -/** - * @brief Set Irda prescaler value, used for dividing the USART clock source - * to achieve the Irda Low Power frequency (8 bits value) - * @note Macro @ref IS_IRDA_INSTANCE(USARTx) can be used to check whether or not - * IrDA feature is supported by the USARTx instance. - * @rmtoll GTPR PSC LL_USART_SetIrdaPrescaler - * @param USARTx USART Instance - * @param PrescalerValue Value between Min_Data=0x00 and Max_Data=0xFF - * @retval None - */ -__STATIC_INLINE void LL_USART_SetIrdaPrescaler(USART_TypeDef *USARTx, uint32_t PrescalerValue) -{ - MODIFY_REG(USARTx->GTPR, USART_GTPR_PSC, PrescalerValue); -} - -/** - * @brief Return Irda prescaler value, used for dividing the USART clock source - * to achieve the Irda Low Power frequency (8 bits value) - * @note Macro @ref IS_IRDA_INSTANCE(USARTx) can be used to check whether or not - * IrDA feature is supported by the USARTx instance. - * @rmtoll GTPR PSC LL_USART_GetIrdaPrescaler - * @param USARTx USART Instance - * @retval Irda prescaler value (Value between Min_Data=0x00 and Max_Data=0xFF) - */ -__STATIC_INLINE uint32_t LL_USART_GetIrdaPrescaler(USART_TypeDef *USARTx) -{ - return (uint32_t)(READ_BIT(USARTx->GTPR, USART_GTPR_PSC)); -} - -/** - * @} - */ - -/** @defgroup USART_LL_EF_Configuration_Smartcard Configuration functions related to Smartcard feature - * @{ - */ - -/** - * @brief Enable Smartcard NACK transmission - * @note Macro @ref IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not - * Smartcard feature is supported by the USARTx instance. - * @rmtoll CR3 NACK LL_USART_EnableSmartcardNACK - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_EnableSmartcardNACK(USART_TypeDef *USARTx) -{ - SET_BIT(USARTx->CR3, USART_CR3_NACK); -} - -/** - * @brief Disable Smartcard NACK transmission - * @note Macro @ref IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not - * Smartcard feature is supported by the USARTx instance. - * @rmtoll CR3 NACK LL_USART_DisableSmartcardNACK - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_DisableSmartcardNACK(USART_TypeDef *USARTx) -{ - CLEAR_BIT(USARTx->CR3, USART_CR3_NACK); -} - -/** - * @brief Indicate if Smartcard NACK transmission is enabled - * @note Macro @ref IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not - * Smartcard feature is supported by the USARTx instance. - * @rmtoll CR3 NACK LL_USART_IsEnabledSmartcardNACK - * @param USARTx USART Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_USART_IsEnabledSmartcardNACK(USART_TypeDef *USARTx) -{ - return (READ_BIT(USARTx->CR3, USART_CR3_NACK) == (USART_CR3_NACK)); -} - -/** - * @brief Enable Smartcard mode - * @note Macro @ref IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not - * Smartcard feature is supported by the USARTx instance. - * @rmtoll CR3 SCEN LL_USART_EnableSmartcard - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_EnableSmartcard(USART_TypeDef *USARTx) -{ - SET_BIT(USARTx->CR3, USART_CR3_SCEN); -} - -/** - * @brief Disable Smartcard mode - * @note Macro @ref IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not - * Smartcard feature is supported by the USARTx instance. - * @rmtoll CR3 SCEN LL_USART_DisableSmartcard - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_DisableSmartcard(USART_TypeDef *USARTx) -{ - CLEAR_BIT(USARTx->CR3, USART_CR3_SCEN); -} - -/** - * @brief Indicate if Smartcard mode is enabled - * @note Macro @ref IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not - * Smartcard feature is supported by the USARTx instance. - * @rmtoll CR3 SCEN LL_USART_IsEnabledSmartcard - * @param USARTx USART Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_USART_IsEnabledSmartcard(USART_TypeDef *USARTx) -{ - return (READ_BIT(USARTx->CR3, USART_CR3_SCEN) == (USART_CR3_SCEN)); -} - -/** - * @brief Set Smartcard prescaler value, used for dividing the USART clock - * source to provide the SMARTCARD Clock (5 bits value) - * @note Macro @ref IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not - * Smartcard feature is supported by the USARTx instance. - * @rmtoll GTPR PSC LL_USART_SetSmartcardPrescaler - * @param USARTx USART Instance - * @param PrescalerValue Value between Min_Data=0 and Max_Data=31 - * @retval None - */ -__STATIC_INLINE void LL_USART_SetSmartcardPrescaler(USART_TypeDef *USARTx, uint32_t PrescalerValue) -{ - MODIFY_REG(USARTx->GTPR, USART_GTPR_PSC, PrescalerValue); -} - -/** - * @brief Return Smartcard prescaler value, used for dividing the USART clock - * source to provide the SMARTCARD Clock (5 bits value) - * @note Macro @ref IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not - * Smartcard feature is supported by the USARTx instance. - * @rmtoll GTPR PSC LL_USART_GetSmartcardPrescaler - * @param USARTx USART Instance - * @retval Smartcard prescaler value (Value between Min_Data=0 and Max_Data=31) - */ -__STATIC_INLINE uint32_t LL_USART_GetSmartcardPrescaler(USART_TypeDef *USARTx) -{ - return (uint32_t)(READ_BIT(USARTx->GTPR, USART_GTPR_PSC)); -} - -/** - * @brief Set Smartcard Guard time value, expressed in nb of baud clocks periods - * (GT[7:0] bits : Guard time value) - * @note Macro @ref IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not - * Smartcard feature is supported by the USARTx instance. - * @rmtoll GTPR GT LL_USART_SetSmartcardGuardTime - * @param USARTx USART Instance - * @param GuardTime Value between Min_Data=0x00 and Max_Data=0xFF - * @retval None - */ -__STATIC_INLINE void LL_USART_SetSmartcardGuardTime(USART_TypeDef *USARTx, uint32_t GuardTime) -{ - MODIFY_REG(USARTx->GTPR, USART_GTPR_GT, GuardTime << USART_POSITION_GTPR_GT); -} - -/** - * @brief Return Smartcard Guard time value, expressed in nb of baud clocks periods - * (GT[7:0] bits : Guard time value) - * @note Macro @ref IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not - * Smartcard feature is supported by the USARTx instance. - * @rmtoll GTPR GT LL_USART_GetSmartcardGuardTime - * @param USARTx USART Instance - * @retval Smartcard Guard time value (Value between Min_Data=0x00 and Max_Data=0xFF) - */ -__STATIC_INLINE uint32_t LL_USART_GetSmartcardGuardTime(USART_TypeDef *USARTx) -{ - return (uint32_t)(READ_BIT(USARTx->GTPR, USART_GTPR_GT) >> USART_POSITION_GTPR_GT); -} - -/** - * @} - */ - -/** @defgroup USART_LL_EF_Configuration_HalfDuplex Configuration functions related to Half Duplex feature - * @{ - */ - -/** - * @brief Enable Single Wire Half-Duplex mode - * @note Macro @ref IS_UART_HALFDUPLEX_INSTANCE(USARTx) can be used to check whether or not - * Half-Duplex mode is supported by the USARTx instance. - * @rmtoll CR3 HDSEL LL_USART_EnableHalfDuplex - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_EnableHalfDuplex(USART_TypeDef *USARTx) -{ - SET_BIT(USARTx->CR3, USART_CR3_HDSEL); -} - -/** - * @brief Disable Single Wire Half-Duplex mode - * @note Macro @ref IS_UART_HALFDUPLEX_INSTANCE(USARTx) can be used to check whether or not - * Half-Duplex mode is supported by the USARTx instance. - * @rmtoll CR3 HDSEL LL_USART_DisableHalfDuplex - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_DisableHalfDuplex(USART_TypeDef *USARTx) -{ - CLEAR_BIT(USARTx->CR3, USART_CR3_HDSEL); -} - -/** - * @brief Indicate if Single Wire Half-Duplex mode is enabled - * @note Macro @ref IS_UART_HALFDUPLEX_INSTANCE(USARTx) can be used to check whether or not - * Half-Duplex mode is supported by the USARTx instance. - * @rmtoll CR3 HDSEL LL_USART_IsEnabledHalfDuplex - * @param USARTx USART Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_USART_IsEnabledHalfDuplex(USART_TypeDef *USARTx) -{ - return (READ_BIT(USARTx->CR3, USART_CR3_HDSEL) == (USART_CR3_HDSEL)); -} - -/** - * @} - */ - -/** @defgroup USART_LL_EF_Configuration_LIN Configuration functions related to LIN feature - * @{ - */ - -/** - * @brief Set LIN Break Detection Length - * @note Macro @ref IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not - * LIN feature is supported by the USARTx instance. - * @rmtoll CR2 LBDL LL_USART_SetLINBrkDetectionLen - * @param USARTx USART Instance - * @param LINBDLength This parameter can be one of the following values: - * @arg @ref LL_USART_LINBREAK_DETECT_10B - * @arg @ref LL_USART_LINBREAK_DETECT_11B - * @retval None - */ -__STATIC_INLINE void LL_USART_SetLINBrkDetectionLen(USART_TypeDef *USARTx, uint32_t LINBDLength) -{ - MODIFY_REG(USARTx->CR2, USART_CR2_LBDL, LINBDLength); -} - -/** - * @brief Return LIN Break Detection Length - * @note Macro @ref IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not - * LIN feature is supported by the USARTx instance. - * @rmtoll CR2 LBDL LL_USART_GetLINBrkDetectionLen - * @param USARTx USART Instance - * @retval Returned value can be one of the following values: - * @arg @ref LL_USART_LINBREAK_DETECT_10B - * @arg @ref LL_USART_LINBREAK_DETECT_11B - */ -__STATIC_INLINE uint32_t LL_USART_GetLINBrkDetectionLen(USART_TypeDef *USARTx) -{ - return (uint32_t)(READ_BIT(USARTx->CR2, USART_CR2_LBDL)); -} - -/** - * @brief Enable LIN mode - * @note Macro @ref IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not - * LIN feature is supported by the USARTx instance. - * @rmtoll CR2 LINEN LL_USART_EnableLIN - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_EnableLIN(USART_TypeDef *USARTx) -{ - SET_BIT(USARTx->CR2, USART_CR2_LINEN); -} - -/** - * @brief Disable LIN mode - * @note Macro @ref IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not - * LIN feature is supported by the USARTx instance. - * @rmtoll CR2 LINEN LL_USART_DisableLIN - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_DisableLIN(USART_TypeDef *USARTx) -{ - CLEAR_BIT(USARTx->CR2, USART_CR2_LINEN); -} - -/** - * @brief Indicate if LIN mode is enabled - * @note Macro @ref IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not - * LIN feature is supported by the USARTx instance. - * @rmtoll CR2 LINEN LL_USART_IsEnabledLIN - * @param USARTx USART Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_USART_IsEnabledLIN(USART_TypeDef *USARTx) -{ - return (READ_BIT(USARTx->CR2, USART_CR2_LINEN) == (USART_CR2_LINEN)); -} - -/** - * @} - */ - -/** @defgroup USART_LL_EF_AdvancedConfiguration Advanced Configurations services - * @{ - */ - -/** - * @brief Perform basic configuration of USART for enabling use in Asynchronous Mode (UART) - * @note In UART mode, the following bits must be kept cleared: - * - LINEN bit in the USART_CR2 register, - * - CLKEN bit in the USART_CR2 register, - * - SCEN bit in the USART_CR3 register, - * - IREN bit in the USART_CR3 register, - * - HDSEL bit in the USART_CR3 register. - * @note Call of this function is equivalent to following function call sequence : - * - Clear LINEN in CR2 using @ref LL_USART_DisableLIN() function - * - Clear CLKEN in CR2 using @ref LL_USART_DisableSCLKOutput() function - * - Clear SCEN in CR3 using @ref LL_USART_DisableSmartcard() function - * - Clear IREN in CR3 using @ref LL_USART_DisableIrda() function - * - Clear HDSEL in CR3 using @ref LL_USART_DisableHalfDuplex() function - * @note Other remaining configurations items related to Asynchronous Mode - * (as Baud Rate, Word length, Parity, ...) should be set using - * dedicated functions - * @rmtoll CR2 LINEN LL_USART_ConfigAsyncMode\n - * CR2 CLKEN LL_USART_ConfigAsyncMode\n - * CR3 SCEN LL_USART_ConfigAsyncMode\n - * CR3 IREN LL_USART_ConfigAsyncMode\n - * CR3 HDSEL LL_USART_ConfigAsyncMode - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_ConfigAsyncMode(USART_TypeDef *USARTx) -{ - /* In Asynchronous mode, the following bits must be kept cleared: - - LINEN, CLKEN bits in the USART_CR2 register, - - SCEN, IREN and HDSEL bits in the USART_CR3 register.*/ - CLEAR_BIT(USARTx->CR2, (USART_CR2_LINEN | USART_CR2_CLKEN)); - CLEAR_BIT(USARTx->CR3, (USART_CR3_SCEN | USART_CR3_IREN | USART_CR3_HDSEL)); -} - -/** - * @brief Perform basic configuration of USART for enabling use in Synchronous Mode - * @note In Synchronous mode, the following bits must be kept cleared: - * - LINEN bit in the USART_CR2 register, - * - SCEN bit in the USART_CR3 register, - * - IREN bit in the USART_CR3 register, - * - HDSEL bit in the USART_CR3 register. - * This function also sets the USART in Synchronous mode. - * @note Macro @ref IS_USART_INSTANCE(USARTx) can be used to check whether or not - * Synchronous mode is supported by the USARTx instance. - * @note Call of this function is equivalent to following function call sequence : - * - Clear LINEN in CR2 using @ref LL_USART_DisableLIN() function - * - Clear IREN in CR3 using @ref LL_USART_DisableIrda() function - * - Clear SCEN in CR3 using @ref LL_USART_DisableSmartcard() function - * - Clear HDSEL in CR3 using @ref LL_USART_DisableHalfDuplex() function - * - Set CLKEN in CR2 using @ref LL_USART_EnableSCLKOutput() function - * @note Other remaining configurations items related to Synchronous Mode - * (as Baud Rate, Word length, Parity, Clock Polarity, ...) should be set using - * dedicated functions - * @rmtoll CR2 LINEN LL_USART_ConfigSyncMode\n - * CR2 CLKEN LL_USART_ConfigSyncMode\n - * CR3 SCEN LL_USART_ConfigSyncMode\n - * CR3 IREN LL_USART_ConfigSyncMode\n - * CR3 HDSEL LL_USART_ConfigSyncMode - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_ConfigSyncMode(USART_TypeDef *USARTx) -{ - /* In Synchronous mode, the following bits must be kept cleared: - - LINEN bit in the USART_CR2 register, - - SCEN, IREN and HDSEL bits in the USART_CR3 register.*/ - CLEAR_BIT(USARTx->CR2, (USART_CR2_LINEN)); - CLEAR_BIT(USARTx->CR3, (USART_CR3_SCEN | USART_CR3_IREN | USART_CR3_HDSEL)); - /* set the UART/USART in Synchronous mode */ - SET_BIT(USARTx->CR2, USART_CR2_CLKEN); -} - -/** - * @brief Perform basic configuration of USART for enabling use in LIN Mode - * @note In LIN mode, the following bits must be kept cleared: - * - STOP and CLKEN bits in the USART_CR2 register, - * - SCEN bit in the USART_CR3 register, - * - IREN bit in the USART_CR3 register, - * - HDSEL bit in the USART_CR3 register. - * This function also set the UART/USART in LIN mode. - * @note Macro @ref IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not - * LIN feature is supported by the USARTx instance. - * @note Call of this function is equivalent to following function call sequence : - * - Clear CLKEN in CR2 using @ref LL_USART_DisableSCLKOutput() function - * - Clear STOP in CR2 using @ref LL_USART_SetStopBitsLength() function - * - Clear SCEN in CR3 using @ref LL_USART_DisableSmartcard() function - * - Clear IREN in CR3 using @ref LL_USART_DisableIrda() function - * - Clear HDSEL in CR3 using @ref LL_USART_DisableHalfDuplex() function - * - Set LINEN in CR2 using @ref LL_USART_EnableLIN() function - * @note Other remaining configurations items related to LIN Mode - * (as Baud Rate, Word length, LIN Break Detection Length, ...) should be set using - * dedicated functions - * @rmtoll CR2 CLKEN LL_USART_ConfigLINMode\n - * CR2 STOP LL_USART_ConfigLINMode\n - * CR2 LINEN LL_USART_ConfigLINMode\n - * CR3 IREN LL_USART_ConfigLINMode\n - * CR3 SCEN LL_USART_ConfigLINMode\n - * CR3 HDSEL LL_USART_ConfigLINMode - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_ConfigLINMode(USART_TypeDef *USARTx) -{ - /* In LIN mode, the following bits must be kept cleared: - - STOP and CLKEN bits in the USART_CR2 register, - - IREN, SCEN and HDSEL bits in the USART_CR3 register.*/ - CLEAR_BIT(USARTx->CR2, (USART_CR2_CLKEN | USART_CR2_STOP)); - CLEAR_BIT(USARTx->CR3, (USART_CR3_IREN | USART_CR3_SCEN | USART_CR3_HDSEL)); - /* Set the UART/USART in LIN mode */ - SET_BIT(USARTx->CR2, USART_CR2_LINEN); -} - -/** - * @brief Perform basic configuration of USART for enabling use in Half Duplex Mode - * @note In Half Duplex mode, the following bits must be kept cleared: - * - LINEN bit in the USART_CR2 register, - * - CLKEN bit in the USART_CR2 register, - * - SCEN bit in the USART_CR3 register, - * - IREN bit in the USART_CR3 register, - * This function also sets the UART/USART in Half Duplex mode. - * @note Macro @ref IS_UART_HALFDUPLEX_INSTANCE(USARTx) can be used to check whether or not - * Half-Duplex mode is supported by the USARTx instance. - * @note Call of this function is equivalent to following function call sequence : - * - Clear LINEN in CR2 using @ref LL_USART_DisableLIN() function - * - Clear CLKEN in CR2 using @ref LL_USART_DisableSCLKOutput() function - * - Clear SCEN in CR3 using @ref LL_USART_DisableSmartcard() function - * - Clear IREN in CR3 using @ref LL_USART_DisableIrda() function - * - Set HDSEL in CR3 using @ref LL_USART_EnableHalfDuplex() function - * @note Other remaining configurations items related to Half Duplex Mode - * (as Baud Rate, Word length, Parity, ...) should be set using - * dedicated functions - * @rmtoll CR2 LINEN LL_USART_ConfigHalfDuplexMode\n - * CR2 CLKEN LL_USART_ConfigHalfDuplexMode\n - * CR3 HDSEL LL_USART_ConfigHalfDuplexMode\n - * CR3 SCEN LL_USART_ConfigHalfDuplexMode\n - * CR3 IREN LL_USART_ConfigHalfDuplexMode - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_ConfigHalfDuplexMode(USART_TypeDef *USARTx) -{ - /* In Half Duplex mode, the following bits must be kept cleared: - - LINEN and CLKEN bits in the USART_CR2 register, - - SCEN and IREN bits in the USART_CR3 register.*/ - CLEAR_BIT(USARTx->CR2, (USART_CR2_LINEN | USART_CR2_CLKEN)); - CLEAR_BIT(USARTx->CR3, (USART_CR3_SCEN | USART_CR3_IREN)); - /* set the UART/USART in Half Duplex mode */ - SET_BIT(USARTx->CR3, USART_CR3_HDSEL); -} - -/** - * @brief Perform basic configuration of USART for enabling use in Smartcard Mode - * @note In Smartcard mode, the following bits must be kept cleared: - * - LINEN bit in the USART_CR2 register, - * - IREN bit in the USART_CR3 register, - * - HDSEL bit in the USART_CR3 register. - * This function also configures Stop bits to 1.5 bits and - * sets the USART in Smartcard mode (SCEN bit). - * Clock Output is also enabled (CLKEN). - * @note Macro @ref IS_SMARTCARD_INSTANCE(USARTx) can be used to check whether or not - * Smartcard feature is supported by the USARTx instance. - * @note Call of this function is equivalent to following function call sequence : - * - Clear LINEN in CR2 using @ref LL_USART_DisableLIN() function - * - Clear IREN in CR3 using @ref LL_USART_DisableIrda() function - * - Clear HDSEL in CR3 using @ref LL_USART_DisableHalfDuplex() function - * - Configure STOP in CR2 using @ref LL_USART_SetStopBitsLength() function - * - Set CLKEN in CR2 using @ref LL_USART_EnableSCLKOutput() function - * - Set SCEN in CR3 using @ref LL_USART_EnableSmartcard() function - * @note Other remaining configurations items related to Smartcard Mode - * (as Baud Rate, Word length, Parity, ...) should be set using - * dedicated functions - * @rmtoll CR2 LINEN LL_USART_ConfigSmartcardMode\n - * CR2 STOP LL_USART_ConfigSmartcardMode\n - * CR2 CLKEN LL_USART_ConfigSmartcardMode\n - * CR3 HDSEL LL_USART_ConfigSmartcardMode\n - * CR3 SCEN LL_USART_ConfigSmartcardMode - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_ConfigSmartcardMode(USART_TypeDef *USARTx) -{ - /* In Smartcard mode, the following bits must be kept cleared: - - LINEN bit in the USART_CR2 register, - - IREN and HDSEL bits in the USART_CR3 register.*/ - CLEAR_BIT(USARTx->CR2, (USART_CR2_LINEN)); - CLEAR_BIT(USARTx->CR3, (USART_CR3_IREN | USART_CR3_HDSEL)); - /* Configure Stop bits to 1.5 bits */ - /* Synchronous mode is activated by default */ - SET_BIT(USARTx->CR2, (USART_CR2_STOP_0 | USART_CR2_STOP_1 | USART_CR2_CLKEN)); - /* set the UART/USART in Smartcard mode */ - SET_BIT(USARTx->CR3, USART_CR3_SCEN); -} - -/** - * @brief Perform basic configuration of USART for enabling use in Irda Mode - * @note In IRDA mode, the following bits must be kept cleared: - * - LINEN bit in the USART_CR2 register, - * - STOP and CLKEN bits in the USART_CR2 register, - * - SCEN bit in the USART_CR3 register, - * - HDSEL bit in the USART_CR3 register. - * This function also sets the UART/USART in IRDA mode (IREN bit). - * @note Macro @ref IS_IRDA_INSTANCE(USARTx) can be used to check whether or not - * IrDA feature is supported by the USARTx instance. - * @note Call of this function is equivalent to following function call sequence : - * - Clear LINEN in CR2 using @ref LL_USART_DisableLIN() function - * - Clear CLKEN in CR2 using @ref LL_USART_DisableSCLKOutput() function - * - Clear SCEN in CR3 using @ref LL_USART_DisableSmartcard() function - * - Clear HDSEL in CR3 using @ref LL_USART_DisableHalfDuplex() function - * - Configure STOP in CR2 using @ref LL_USART_SetStopBitsLength() function - * - Set IREN in CR3 using @ref LL_USART_EnableIrda() function - * @note Other remaining configurations items related to Irda Mode - * (as Baud Rate, Word length, Power mode, ...) should be set using - * dedicated functions - * @rmtoll CR2 LINEN LL_USART_ConfigIrdaMode\n - * CR2 CLKEN LL_USART_ConfigIrdaMode\n - * CR2 STOP LL_USART_ConfigIrdaMode\n - * CR3 SCEN LL_USART_ConfigIrdaMode\n - * CR3 HDSEL LL_USART_ConfigIrdaMode\n - * CR3 IREN LL_USART_ConfigIrdaMode - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_ConfigIrdaMode(USART_TypeDef *USARTx) -{ - /* In IRDA mode, the following bits must be kept cleared: - - LINEN, STOP and CLKEN bits in the USART_CR2 register, - - SCEN and HDSEL bits in the USART_CR3 register.*/ - CLEAR_BIT(USARTx->CR2, (USART_CR2_LINEN | USART_CR2_CLKEN | USART_CR2_STOP)); - CLEAR_BIT(USARTx->CR3, (USART_CR3_SCEN | USART_CR3_HDSEL)); - /* set the UART/USART in IRDA mode */ - SET_BIT(USARTx->CR3, USART_CR3_IREN); -} - -/** - * @brief Perform basic configuration of USART for enabling use in Multi processor Mode - * (several USARTs connected in a network, one of the USARTs can be the master, - * its TX output connected to the RX inputs of the other slaves USARTs). - * @note In MultiProcessor mode, the following bits must be kept cleared: - * - LINEN bit in the USART_CR2 register, - * - CLKEN bit in the USART_CR2 register, - * - SCEN bit in the USART_CR3 register, - * - IREN bit in the USART_CR3 register, - * - HDSEL bit in the USART_CR3 register. - * @note Call of this function is equivalent to following function call sequence : - * - Clear LINEN in CR2 using @ref LL_USART_DisableLIN() function - * - Clear CLKEN in CR2 using @ref LL_USART_DisableSCLKOutput() function - * - Clear SCEN in CR3 using @ref LL_USART_DisableSmartcard() function - * - Clear IREN in CR3 using @ref LL_USART_DisableIrda() function - * - Clear HDSEL in CR3 using @ref LL_USART_DisableHalfDuplex() function - * @note Other remaining configurations items related to Multi processor Mode - * (as Baud Rate, Wake Up Method, Node address, ...) should be set using - * dedicated functions - * @rmtoll CR2 LINEN LL_USART_ConfigMultiProcessMode\n - * CR2 CLKEN LL_USART_ConfigMultiProcessMode\n - * CR3 SCEN LL_USART_ConfigMultiProcessMode\n - * CR3 HDSEL LL_USART_ConfigMultiProcessMode\n - * CR3 IREN LL_USART_ConfigMultiProcessMode - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_ConfigMultiProcessMode(USART_TypeDef *USARTx) -{ - /* In Multi Processor mode, the following bits must be kept cleared: - - LINEN and CLKEN bits in the USART_CR2 register, - - IREN, SCEN and HDSEL bits in the USART_CR3 register.*/ - CLEAR_BIT(USARTx->CR2, (USART_CR2_LINEN | USART_CR2_CLKEN)); - CLEAR_BIT(USARTx->CR3, (USART_CR3_SCEN | USART_CR3_HDSEL | USART_CR3_IREN)); -} - -/** - * @} - */ - -/** @defgroup USART_LL_EF_FLAG_Management FLAG_Management - * @{ - */ - -/** - * @brief Check if the USART Parity Error Flag is set or not - * @rmtoll SR PE LL_USART_IsActiveFlag_PE - * @param USARTx USART Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_USART_IsActiveFlag_PE(USART_TypeDef *USARTx) -{ - return (READ_BIT(USARTx->SR, USART_SR_PE) == (USART_SR_PE)); -} - -/** - * @brief Check if the USART Framing Error Flag is set or not - * @rmtoll SR FE LL_USART_IsActiveFlag_FE - * @param USARTx USART Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_USART_IsActiveFlag_FE(USART_TypeDef *USARTx) -{ - return (READ_BIT(USARTx->SR, USART_SR_FE) == (USART_SR_FE)); -} - -/** - * @brief Check if the USART Noise error detected Flag is set or not - * @rmtoll SR NF LL_USART_IsActiveFlag_NE - * @param USARTx USART Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_USART_IsActiveFlag_NE(USART_TypeDef *USARTx) -{ - return (READ_BIT(USARTx->SR, USART_SR_NE) == (USART_SR_NE)); -} - -/** - * @brief Check if the USART OverRun Error Flag is set or not - * @rmtoll SR ORE LL_USART_IsActiveFlag_ORE - * @param USARTx USART Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_USART_IsActiveFlag_ORE(USART_TypeDef *USARTx) -{ - return (READ_BIT(USARTx->SR, USART_SR_ORE) == (USART_SR_ORE)); -} - -/** - * @brief Check if the USART IDLE line detected Flag is set or not - * @rmtoll SR IDLE LL_USART_IsActiveFlag_IDLE - * @param USARTx USART Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_USART_IsActiveFlag_IDLE(USART_TypeDef *USARTx) -{ - return (READ_BIT(USARTx->SR, USART_SR_IDLE) == (USART_SR_IDLE)); -} - -/** - * @brief Check if the USART Read Data Register Not Empty Flag is set or not - * @rmtoll SR RXNE LL_USART_IsActiveFlag_RXNE - * @param USARTx USART Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_USART_IsActiveFlag_RXNE(USART_TypeDef *USARTx) -{ - return (READ_BIT(USARTx->SR, USART_SR_RXNE) == (USART_SR_RXNE)); -} - -/** - * @brief Check if the USART Transmission Complete Flag is set or not - * @rmtoll SR TC LL_USART_IsActiveFlag_TC - * @param USARTx USART Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_USART_IsActiveFlag_TC(USART_TypeDef *USARTx) -{ - return (READ_BIT(USARTx->SR, USART_SR_TC) == (USART_SR_TC)); -} - -/** - * @brief Check if the USART Transmit Data Register Empty Flag is set or not - * @rmtoll SR TXE LL_USART_IsActiveFlag_TXE - * @param USARTx USART Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_USART_IsActiveFlag_TXE(USART_TypeDef *USARTx) -{ - return (READ_BIT(USARTx->SR, USART_SR_TXE) == (USART_SR_TXE)); -} - -/** - * @brief Check if the USART LIN Break Detection Flag is set or not - * @note Macro @ref IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not - * LIN feature is supported by the USARTx instance. - * @rmtoll SR LBD LL_USART_IsActiveFlag_LBD - * @param USARTx USART Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_USART_IsActiveFlag_LBD(USART_TypeDef *USARTx) -{ - return (READ_BIT(USARTx->SR, USART_SR_LBD) == (USART_SR_LBD)); -} - -/** - * @brief Check if the USART CTS Flag is set or not - * @note Macro @ref IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not - * Hardware Flow control feature is supported by the USARTx instance. - * @rmtoll SR CTS LL_USART_IsActiveFlag_nCTS - * @param USARTx USART Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_USART_IsActiveFlag_nCTS(USART_TypeDef *USARTx) -{ - return (READ_BIT(USARTx->SR, USART_SR_CTS) == (USART_SR_CTS)); -} - -/** - * @brief Check if the USART Send Break Flag is set or not - * @rmtoll CR1 SBK LL_USART_IsActiveFlag_SBK - * @param USARTx USART Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_USART_IsActiveFlag_SBK(USART_TypeDef *USARTx) -{ - return (READ_BIT(USARTx->CR1, USART_CR1_SBK) == (USART_CR1_SBK)); -} - -/** - * @brief Check if the USART Receive Wake Up from mute mode Flag is set or not - * @rmtoll CR1 RWU LL_USART_IsActiveFlag_RWU - * @param USARTx USART Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_USART_IsActiveFlag_RWU(USART_TypeDef *USARTx) -{ - return (READ_BIT(USARTx->CR1, USART_CR1_RWU) == (USART_CR1_RWU)); -} - -/** - * @brief Clear Parity Error Flag - * @note Clearing this flag is done by a read access to the USARTx_SR - * register followed by a read access to the USARTx_DR register. - * @note Please also consider that when clearing this flag, other flags as - * NE, FE, ORE, IDLE would also be cleared. - * @rmtoll SR PE LL_USART_ClearFlag_PE - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_ClearFlag_PE(USART_TypeDef *USARTx) -{ - __IO uint32_t tmpreg; - tmpreg = USARTx->SR; - (void) tmpreg; - tmpreg = USARTx->DR; - (void) tmpreg; -} - -/** - * @brief Clear Framing Error Flag - * @note Clearing this flag is done by a read access to the USARTx_SR - * register followed by a read access to the USARTx_DR register. - * @note Please also consider that when clearing this flag, other flags as - * PE, NE, ORE, IDLE would also be cleared. - * @rmtoll SR FE LL_USART_ClearFlag_FE - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_ClearFlag_FE(USART_TypeDef *USARTx) -{ - __IO uint32_t tmpreg; - tmpreg = USARTx->SR; - (void) tmpreg; - tmpreg = USARTx->DR; - (void) tmpreg; -} - -/** - * @brief Clear Noise detected Flag - * @note Clearing this flag is done by a read access to the USARTx_SR - * register followed by a read access to the USARTx_DR register. - * @note Please also consider that when clearing this flag, other flags as - * PE, FE, ORE, IDLE would also be cleared. - * @rmtoll SR NF LL_USART_ClearFlag_NE - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_ClearFlag_NE(USART_TypeDef *USARTx) -{ - __IO uint32_t tmpreg; - tmpreg = USARTx->SR; - (void) tmpreg; - tmpreg = USARTx->DR; - (void) tmpreg; -} - -/** - * @brief Clear OverRun Error Flag - * @note Clearing this flag is done by a read access to the USARTx_SR - * register followed by a read access to the USARTx_DR register. - * @note Please also consider that when clearing this flag, other flags as - * PE, NE, FE, IDLE would also be cleared. - * @rmtoll SR ORE LL_USART_ClearFlag_ORE - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_ClearFlag_ORE(USART_TypeDef *USARTx) -{ - __IO uint32_t tmpreg; - tmpreg = USARTx->SR; - (void) tmpreg; - tmpreg = USARTx->DR; - (void) tmpreg; -} - -/** - * @brief Clear IDLE line detected Flag - * @note Clearing this flag is done by a read access to the USARTx_SR - * register followed by a read access to the USARTx_DR register. - * @note Please also consider that when clearing this flag, other flags as - * PE, NE, FE, ORE would also be cleared. - * @rmtoll SR IDLE LL_USART_ClearFlag_IDLE - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_ClearFlag_IDLE(USART_TypeDef *USARTx) -{ - __IO uint32_t tmpreg; - tmpreg = USARTx->SR; - (void) tmpreg; - tmpreg = USARTx->DR; - (void) tmpreg; -} - -/** - * @brief Clear Transmission Complete Flag - * @rmtoll SR TC LL_USART_ClearFlag_TC - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_ClearFlag_TC(USART_TypeDef *USARTx) -{ - WRITE_REG(USARTx->SR , ~(USART_SR_TC)); -} - -/** - * @brief Clear RX Not Empty Flag - * @rmtoll SR RXNE LL_USART_ClearFlag_RXNE - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_ClearFlag_RXNE(USART_TypeDef *USARTx) -{ - WRITE_REG(USARTx->SR , ~(USART_SR_RXNE)); -} - -/** - * @brief Clear LIN Break Detection Flag - * @note Macro @ref IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not - * LIN feature is supported by the USARTx instance. - * @rmtoll SR LBD LL_USART_ClearFlag_LBD - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_ClearFlag_LBD(USART_TypeDef *USARTx) -{ - WRITE_REG(USARTx->SR , ~(USART_SR_LBD)); -} - -/** - * @brief Clear CTS Interrupt Flag - * @note Macro @ref IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not - * Hardware Flow control feature is supported by the USARTx instance. - * @rmtoll SR CTS LL_USART_ClearFlag_nCTS - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_ClearFlag_nCTS(USART_TypeDef *USARTx) -{ - WRITE_REG(USARTx->SR , ~(USART_SR_CTS)); -} - -/** - * @} - */ - -/** @defgroup USART_LL_EF_IT_Management IT_Management - * @{ - */ - -/** - * @brief Enable IDLE Interrupt - * @rmtoll CR1 IDLEIE LL_USART_EnableIT_IDLE - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_EnableIT_IDLE(USART_TypeDef *USARTx) -{ - SET_BIT(USARTx->CR1, USART_CR1_IDLEIE); -} - -/** - * @brief Enable RX Not Empty Interrupt - * @rmtoll CR1 RXNEIE LL_USART_EnableIT_RXNE - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_EnableIT_RXNE(USART_TypeDef *USARTx) -{ - SET_BIT(USARTx->CR1, USART_CR1_RXNEIE); -} - -/** - * @brief Enable Transmission Complete Interrupt - * @rmtoll CR1 TCIE LL_USART_EnableIT_TC - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_EnableIT_TC(USART_TypeDef *USARTx) -{ - SET_BIT(USARTx->CR1, USART_CR1_TCIE); -} - -/** - * @brief Enable TX Empty Interrupt - * @rmtoll CR1 TXEIE LL_USART_EnableIT_TXE - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_EnableIT_TXE(USART_TypeDef *USARTx) -{ - SET_BIT(USARTx->CR1, USART_CR1_TXEIE); -} - -/** - * @brief Enable Parity Error Interrupt - * @rmtoll CR1 PEIE LL_USART_EnableIT_PE - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_EnableIT_PE(USART_TypeDef *USARTx) -{ - SET_BIT(USARTx->CR1, USART_CR1_PEIE); -} - -/** - * @brief Enable LIN Break Detection Interrupt - * @note Macro @ref IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not - * LIN feature is supported by the USARTx instance. - * @rmtoll CR2 LBDIE LL_USART_EnableIT_LBD - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_EnableIT_LBD(USART_TypeDef *USARTx) -{ - SET_BIT(USARTx->CR2, USART_CR2_LBDIE); -} - -/** - * @brief Enable Error Interrupt - * @note When set, Error Interrupt Enable Bit is enabling interrupt generation in case of a framing - * error, overrun error or noise flag (FE=1 or ORE=1 or NF=1 in the USARTx_SR register). - * 0: Interrupt is inhibited - * 1: An interrupt is generated when FE=1 or ORE=1 or NF=1 in the USARTx_SR register. - * @rmtoll CR3 EIE LL_USART_EnableIT_ERROR - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_EnableIT_ERROR(USART_TypeDef *USARTx) -{ - SET_BIT(USARTx->CR3, USART_CR3_EIE); -} - -/** - * @brief Enable CTS Interrupt - * @note Macro @ref IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not - * Hardware Flow control feature is supported by the USARTx instance. - * @rmtoll CR3 CTSIE LL_USART_EnableIT_CTS - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_EnableIT_CTS(USART_TypeDef *USARTx) -{ - SET_BIT(USARTx->CR3, USART_CR3_CTSIE); -} - -/** - * @brief Disable IDLE Interrupt - * @rmtoll CR1 IDLEIE LL_USART_DisableIT_IDLE - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_DisableIT_IDLE(USART_TypeDef *USARTx) -{ - CLEAR_BIT(USARTx->CR1, USART_CR1_IDLEIE); -} - -/** - * @brief Disable RX Not Empty Interrupt - * @rmtoll CR1 RXNEIE LL_USART_DisableIT_RXNE - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_DisableIT_RXNE(USART_TypeDef *USARTx) -{ - CLEAR_BIT(USARTx->CR1, USART_CR1_RXNEIE); -} - -/** - * @brief Disable Transmission Complete Interrupt - * @rmtoll CR1 TCIE LL_USART_DisableIT_TC - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_DisableIT_TC(USART_TypeDef *USARTx) -{ - CLEAR_BIT(USARTx->CR1, USART_CR1_TCIE); -} - -/** - * @brief Disable TX Empty Interrupt - * @rmtoll CR1 TXEIE LL_USART_DisableIT_TXE - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_DisableIT_TXE(USART_TypeDef *USARTx) -{ - CLEAR_BIT(USARTx->CR1, USART_CR1_TXEIE); -} - -/** - * @brief Disable Parity Error Interrupt - * @rmtoll CR1 PEIE LL_USART_DisableIT_PE - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_DisableIT_PE(USART_TypeDef *USARTx) -{ - CLEAR_BIT(USARTx->CR1, USART_CR1_PEIE); -} - -/** - * @brief Disable LIN Break Detection Interrupt - * @note Macro @ref IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not - * LIN feature is supported by the USARTx instance. - * @rmtoll CR2 LBDIE LL_USART_DisableIT_LBD - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_DisableIT_LBD(USART_TypeDef *USARTx) -{ - CLEAR_BIT(USARTx->CR2, USART_CR2_LBDIE); -} - -/** - * @brief Disable Error Interrupt - * @note When set, Error Interrupt Enable Bit is enabling interrupt generation in case of a framing - * error, overrun error or noise flag (FE=1 or ORE=1 or NF=1 in the USARTx_SR register). - * 0: Interrupt is inhibited - * 1: An interrupt is generated when FE=1 or ORE=1 or NF=1 in the USARTx_SR register. - * @rmtoll CR3 EIE LL_USART_DisableIT_ERROR - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_DisableIT_ERROR(USART_TypeDef *USARTx) -{ - CLEAR_BIT(USARTx->CR3, USART_CR3_EIE); -} - -/** - * @brief Disable CTS Interrupt - * @note Macro @ref IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not - * Hardware Flow control feature is supported by the USARTx instance. - * @rmtoll CR3 CTSIE LL_USART_DisableIT_CTS - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_DisableIT_CTS(USART_TypeDef *USARTx) -{ - CLEAR_BIT(USARTx->CR3, USART_CR3_CTSIE); -} - -/** - * @brief Check if the USART IDLE Interrupt source is enabled or disabled. - * @rmtoll CR1 IDLEIE LL_USART_IsEnabledIT_IDLE - * @param USARTx USART Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_USART_IsEnabledIT_IDLE(USART_TypeDef *USARTx) -{ - return (READ_BIT(USARTx->CR1, USART_CR1_IDLEIE) == (USART_CR1_IDLEIE)); -} - -/** - * @brief Check if the USART RX Not Empty Interrupt is enabled or disabled. - * @rmtoll CR1 RXNEIE LL_USART_IsEnabledIT_RXNE - * @param USARTx USART Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_USART_IsEnabledIT_RXNE(USART_TypeDef *USARTx) -{ - return (READ_BIT(USARTx->CR1, USART_CR1_RXNEIE) == (USART_CR1_RXNEIE)); -} - -/** - * @brief Check if the USART Transmission Complete Interrupt is enabled or disabled. - * @rmtoll CR1 TCIE LL_USART_IsEnabledIT_TC - * @param USARTx USART Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_USART_IsEnabledIT_TC(USART_TypeDef *USARTx) -{ - return (READ_BIT(USARTx->CR1, USART_CR1_TCIE) == (USART_CR1_TCIE)); -} - -/** - * @brief Check if the USART TX Empty Interrupt is enabled or disabled. - * @rmtoll CR1 TXEIE LL_USART_IsEnabledIT_TXE - * @param USARTx USART Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_USART_IsEnabledIT_TXE(USART_TypeDef *USARTx) -{ - return (READ_BIT(USARTx->CR1, USART_CR1_TXEIE) == (USART_CR1_TXEIE)); -} - -/** - * @brief Check if the USART Parity Error Interrupt is enabled or disabled. - * @rmtoll CR1 PEIE LL_USART_IsEnabledIT_PE - * @param USARTx USART Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_USART_IsEnabledIT_PE(USART_TypeDef *USARTx) -{ - return (READ_BIT(USARTx->CR1, USART_CR1_PEIE) == (USART_CR1_PEIE)); -} - -/** - * @brief Check if the USART LIN Break Detection Interrupt is enabled or disabled. - * @note Macro @ref IS_UART_LIN_INSTANCE(USARTx) can be used to check whether or not - * LIN feature is supported by the USARTx instance. - * @rmtoll CR2 LBDIE LL_USART_IsEnabledIT_LBD - * @param USARTx USART Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_USART_IsEnabledIT_LBD(USART_TypeDef *USARTx) -{ - return (READ_BIT(USARTx->CR2, USART_CR2_LBDIE) == (USART_CR2_LBDIE)); -} - -/** - * @brief Check if the USART Error Interrupt is enabled or disabled. - * @rmtoll CR3 EIE LL_USART_IsEnabledIT_ERROR - * @param USARTx USART Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_USART_IsEnabledIT_ERROR(USART_TypeDef *USARTx) -{ - return (READ_BIT(USARTx->CR3, USART_CR3_EIE) == (USART_CR3_EIE)); -} - -/** - * @brief Check if the USART CTS Interrupt is enabled or disabled. - * @note Macro @ref IS_UART_HWFLOW_INSTANCE(USARTx) can be used to check whether or not - * Hardware Flow control feature is supported by the USARTx instance. - * @rmtoll CR3 CTSIE LL_USART_IsEnabledIT_CTS - * @param USARTx USART Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_USART_IsEnabledIT_CTS(USART_TypeDef *USARTx) -{ - return (READ_BIT(USARTx->CR3, USART_CR3_CTSIE) == (USART_CR3_CTSIE)); -} - -/** - * @} - */ - -/** @defgroup USART_LL_EF_DMA_Management DMA_Management - * @{ - */ - -/** - * @brief Enable DMA Mode for reception - * @rmtoll CR3 DMAR LL_USART_EnableDMAReq_RX - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_EnableDMAReq_RX(USART_TypeDef *USARTx) -{ - SET_BIT(USARTx->CR3, USART_CR3_DMAR); -} - -/** - * @brief Disable DMA Mode for reception - * @rmtoll CR3 DMAR LL_USART_DisableDMAReq_RX - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_DisableDMAReq_RX(USART_TypeDef *USARTx) -{ - CLEAR_BIT(USARTx->CR3, USART_CR3_DMAR); -} - -/** - * @brief Check if DMA Mode is enabled for reception - * @rmtoll CR3 DMAR LL_USART_IsEnabledDMAReq_RX - * @param USARTx USART Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_USART_IsEnabledDMAReq_RX(USART_TypeDef *USARTx) -{ - return (READ_BIT(USARTx->CR3, USART_CR3_DMAR) == (USART_CR3_DMAR)); -} - -/** - * @brief Enable DMA Mode for transmission - * @rmtoll CR3 DMAT LL_USART_EnableDMAReq_TX - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_EnableDMAReq_TX(USART_TypeDef *USARTx) -{ - SET_BIT(USARTx->CR3, USART_CR3_DMAT); -} - -/** - * @brief Disable DMA Mode for transmission - * @rmtoll CR3 DMAT LL_USART_DisableDMAReq_TX - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_DisableDMAReq_TX(USART_TypeDef *USARTx) -{ - CLEAR_BIT(USARTx->CR3, USART_CR3_DMAT); -} - -/** - * @brief Check if DMA Mode is enabled for transmission - * @rmtoll CR3 DMAT LL_USART_IsEnabledDMAReq_TX - * @param USARTx USART Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_USART_IsEnabledDMAReq_TX(USART_TypeDef *USARTx) -{ - return (READ_BIT(USARTx->CR3, USART_CR3_DMAT) == (USART_CR3_DMAT)); -} - -/** - * @brief Get the data register address used for DMA transfer - * @rmtoll DR DR LL_USART_DMA_GetRegAddr - * @note Address of Data Register is valid for both Transmit and Receive transfers. - * @param USARTx USART Instance - * @retval Address of data register - */ -__STATIC_INLINE uint32_t LL_USART_DMA_GetRegAddr(USART_TypeDef *USARTx) -{ - /* return address of DR register */ - return ((uint32_t) &(USARTx->DR)); -} - -/** - * @} - */ - -/** @defgroup USART_LL_EF_Data_Management Data_Management - * @{ - */ - -/** - * @brief Read Receiver Data register (Receive Data value, 8 bits) - * @rmtoll DR DR LL_USART_ReceiveData8 - * @param USARTx USART Instance - * @retval Value between Min_Data=0x00 and Max_Data=0xFF - */ -__STATIC_INLINE uint8_t LL_USART_ReceiveData8(USART_TypeDef *USARTx) -{ - return (uint8_t)(READ_BIT(USARTx->DR, USART_DR_DR)); -} - -/** - * @brief Read Receiver Data register (Receive Data value, 9 bits) - * @rmtoll DR DR LL_USART_ReceiveData9 - * @param USARTx USART Instance - * @retval Value between Min_Data=0x00 and Max_Data=0x1FF - */ -__STATIC_INLINE uint16_t LL_USART_ReceiveData9(USART_TypeDef *USARTx) -{ - return (uint16_t)(READ_BIT(USARTx->DR, USART_DR_DR)); -} - -/** - * @brief Write in Transmitter Data Register (Transmit Data value, 8 bits) - * @rmtoll DR DR LL_USART_TransmitData8 - * @param USARTx USART Instance - * @param Value between Min_Data=0x00 and Max_Data=0xFF - * @retval None - */ -__STATIC_INLINE void LL_USART_TransmitData8(USART_TypeDef *USARTx, uint8_t Value) -{ - USARTx->DR = Value; -} - -/** - * @brief Write in Transmitter Data Register (Transmit Data value, 9 bits) - * @rmtoll DR DR LL_USART_TransmitData9 - * @param USARTx USART Instance - * @param Value between Min_Data=0x00 and Max_Data=0x1FF - * @retval None - */ -__STATIC_INLINE void LL_USART_TransmitData9(USART_TypeDef *USARTx, uint16_t Value) -{ - USARTx->DR = Value & 0x1FFU; -} - -/** - * @} - */ - -/** @defgroup USART_LL_EF_Execution Execution - * @{ - */ - -/** - * @brief Request Break sending - * @rmtoll CR1 SBK LL_USART_RequestBreakSending - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_RequestBreakSending(USART_TypeDef *USARTx) -{ - SET_BIT(USARTx->CR1, USART_CR1_SBK); -} - -/** - * @brief Put USART in Mute mode - * @rmtoll CR1 RWU LL_USART_RequestEnterMuteMode - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_RequestEnterMuteMode(USART_TypeDef *USARTx) -{ - SET_BIT(USARTx->CR1, USART_CR1_RWU); -} - -/** - * @brief Put USART in Active mode - * @rmtoll CR1 RWU LL_USART_RequestExitMuteMode - * @param USARTx USART Instance - * @retval None - */ -__STATIC_INLINE void LL_USART_RequestExitMuteMode(USART_TypeDef *USARTx) -{ - CLEAR_BIT(USARTx->CR1, USART_CR1_RWU); -} - -/** - * @} - */ - -#if defined(USE_FULL_LL_DRIVER) -/** @defgroup USART_LL_EF_Init Initialization and de-initialization functions - * @{ - */ -ErrorStatus LL_USART_DeInit(USART_TypeDef *USARTx); -ErrorStatus LL_USART_Init(USART_TypeDef *USARTx, LL_USART_InitTypeDef *USART_InitStruct); -void LL_USART_StructInit(LL_USART_InitTypeDef *USART_InitStruct); -ErrorStatus LL_USART_ClockInit(USART_TypeDef *USARTx, LL_USART_ClockInitTypeDef *USART_ClockInitStruct); -void LL_USART_ClockStructInit(LL_USART_ClockInitTypeDef *USART_ClockInitStruct); -/** - * @} - */ -#endif /* USE_FULL_LL_DRIVER */ - -/** - * @} - */ - -/** - * @} - */ - -#endif /* USART1 || USART2 || USART3 || UART4 || UART5 */ - -/** - * @} - */ - -#ifdef __cplusplus -} -#endif - -#endif /* __STM32F1xx_LL_USART_H */ - -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_usb.c b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_usb.c index 7cf32611ee7..a698106e451 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_usb.c +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_usb.c @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_ll_usb.c * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief USB Low Layer HAL module driver. * * This file provides firmware functions to manage the following @@ -123,9 +123,6 @@ static HAL_StatusTypeDef USB_CoreReset(USB_OTG_GlobalTypeDef *USBx); */ HAL_StatusTypeDef USB_CoreInit(USB_OTG_GlobalTypeDef *USBx, USB_OTG_CfgTypeDef cfg) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(cfg); - /* Select FS Embedded PHY */ USBx->GUSBCFG |= USB_OTG_GUSBCFG_PHYSEL; @@ -180,7 +177,7 @@ HAL_StatusTypeDef USB_SetCurrentMode(USB_OTG_GlobalTypeDef *USBx , USB_ModeTypeD { USBx->GUSBCFG |= USB_OTG_GUSBCFG_FHMOD; } - else if (mode == USB_DEVICE_MODE) + else if ( mode == USB_DEVICE_MODE) { USBx->GUSBCFG |= USB_OTG_GUSBCFG_FDMOD; } @@ -279,7 +276,7 @@ HAL_StatusTypeDef USB_DevInit (USB_OTG_GlobalTypeDef *USBx, USB_OTG_CfgTypeDef c { USBx->GINTMSK |= USB_OTG_GINTMSK_SOFM; } - + if (cfg.vbus_sensing_enable == ENABLE) { USBx->GINTMSK |= (USB_OTG_GINTMSK_SRQIM | USB_OTG_GINTMSK_OTGINT); @@ -300,7 +297,7 @@ HAL_StatusTypeDef USB_FlushTxFifo (USB_OTG_GlobalTypeDef *USBx, uint32_t num ) { uint32_t count = 0; - USBx->GRSTCTL = (USB_OTG_GRSTCTL_TXFFLSH |(uint32_t)(num << 6)); + USBx->GRSTCTL = ( USB_OTG_GRSTCTL_TXFFLSH |(uint32_t)( num << 6)); do { @@ -349,9 +346,6 @@ HAL_StatusTypeDef USB_FlushRxFifo(USB_OTG_GlobalTypeDef *USBx) */ HAL_StatusTypeDef USB_SetDevSpeed(USB_OTG_GlobalTypeDef *USBx , uint8_t speed) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(USBx); - USBx_DEVICE->DCFG |= speed; return HAL_OK; } @@ -367,9 +361,7 @@ HAL_StatusTypeDef USB_SetDevSpeed(USB_OTG_GlobalTypeDef *USBx , uint8_t speed) uint8_t USB_GetDevSpeed(USB_OTG_GlobalTypeDef *USBx) { uint8_t speed = 0; - /* Prevent unused argument(s) compilation warning */ - UNUSED(USBx); - + if (((USBx_DEVICE->DSTS & USB_OTG_DSTS_ENUMSPD) == DSTS_ENUMSPD_FS_PHY_30MHZ_OR_60MHZ)|| ((USBx_DEVICE->DSTS & USB_OTG_DSTS_ENUMSPD) == DSTS_ENUMSPD_FS_PHY_48MHZ)) { @@ -391,9 +383,6 @@ uint8_t USB_GetDevSpeed(USB_OTG_GlobalTypeDef *USBx) */ HAL_StatusTypeDef USB_ActivateEndpoint(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(USBx); - if (ep->is_in) { /* Assign a Tx FIFO */ @@ -408,7 +397,7 @@ HAL_StatusTypeDef USB_ActivateEndpoint(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTy if (ep->is_in == 1) { USBx_DEVICE->DAINTMSK |= USB_OTG_DAINTMSK_IEPM & ((1 << (ep->num))); - + if (((USBx_INEP(ep->num)->DIEPCTL) & USB_OTG_DIEPCTL_USBAEP) == 0) { USBx_INEP(ep->num)->DIEPCTL |= ((ep->maxpacket & USB_OTG_DIEPCTL_MPSIZ ) | (ep->type << 18 ) |\ @@ -437,9 +426,6 @@ HAL_StatusTypeDef USB_ActivateEndpoint(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTy */ HAL_StatusTypeDef USB_DeactivateEndpoint(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(USBx); - /* Read DEPCTLn register */ if (ep->is_in == 1) { @@ -465,9 +451,7 @@ HAL_StatusTypeDef USB_DeactivateEndpoint(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EP HAL_StatusTypeDef USB_EPStartXfer(USB_OTG_GlobalTypeDef *USBx , USB_OTG_EPTypeDef *ep) { uint16_t pktcnt = 0; - /* Prevent unused argument(s) compilation warning */ - UNUSED(USBx); - + /* IN endpoint */ if (ep->is_in == 1) { @@ -573,9 +557,6 @@ HAL_StatusTypeDef USB_EPStartXfer(USB_OTG_GlobalTypeDef *USBx , USB_OTG_EPTypeDe */ HAL_StatusTypeDef USB_EP0StartXfer(USB_OTG_GlobalTypeDef *USBx , USB_OTG_EPTypeDef *ep) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(USBx); - /* IN endpoint */ if (ep->is_in == 1) { @@ -649,9 +630,7 @@ HAL_StatusTypeDef USB_EP0StartXfer(USB_OTG_GlobalTypeDef *USBx , USB_OTG_EPTypeD HAL_StatusTypeDef USB_WritePacket(USB_OTG_GlobalTypeDef *USBx, uint8_t *src, uint8_t ch_ep_num, uint16_t len) { uint32_t count32b = 0 , index = 0; - /* Prevent unused argument(s) compilation warning */ - UNUSED(USBx); - + count32b = (len + 3) / 4; for (index = 0; index < count32b; index++, src += 4) { @@ -672,9 +651,7 @@ void *USB_ReadPacket(USB_OTG_GlobalTypeDef *USBx, uint8_t *dest, uint16_t len) { uint32_t index = 0; uint32_t count32b = (len + 3) / 4; - /* Prevent unused argument(s) compilation warning */ - UNUSED(USBx); - + for ( index = 0; index < count32b; index++, dest += 4 ) { *(__packed uint32_t *)dest = USBx_DFIFO(0); @@ -691,9 +668,6 @@ void *USB_ReadPacket(USB_OTG_GlobalTypeDef *USBx, uint8_t *dest, uint16_t len) */ HAL_StatusTypeDef USB_EPSetStall(USB_OTG_GlobalTypeDef *USBx , USB_OTG_EPTypeDef *ep) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(USBx); - if (ep->is_in == 1) { if (((USBx_INEP(ep->num)->DIEPCTL) & USB_OTG_DIEPCTL_EPENA) == 0) @@ -721,9 +695,6 @@ HAL_StatusTypeDef USB_EPSetStall(USB_OTG_GlobalTypeDef *USBx , USB_OTG_EPTypeDef */ HAL_StatusTypeDef USB_EPClearStall(USB_OTG_GlobalTypeDef *USBx, USB_OTG_EPTypeDef *ep) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(USBx); - if (ep->is_in == 1) { USBx_INEP(ep->num)->DIEPCTL &= ~USB_OTG_DIEPCTL_STALL; @@ -781,9 +752,6 @@ HAL_StatusTypeDef USB_StopDevice(USB_OTG_GlobalTypeDef *USBx) */ HAL_StatusTypeDef USB_SetDevAddress (USB_OTG_GlobalTypeDef *USBx, uint8_t address) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(USBx); - UNUSED(address); USBx_DEVICE->DCFG &= ~ (USB_OTG_DCFG_DAD); USBx_DEVICE->DCFG |= (address << 4) & USB_OTG_DCFG_DAD; @@ -797,9 +765,6 @@ HAL_StatusTypeDef USB_SetDevAddress (USB_OTG_GlobalTypeDef *USBx, uint8_t addre */ HAL_StatusTypeDef USB_DevConnect (USB_OTG_GlobalTypeDef *USBx) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(USBx); - USBx_DEVICE->DCTL &= ~USB_OTG_DCTL_SDIS ; HAL_Delay(3); @@ -813,9 +778,6 @@ HAL_StatusTypeDef USB_DevConnect (USB_OTG_GlobalTypeDef *USBx) */ HAL_StatusTypeDef USB_DevDisconnect (USB_OTG_GlobalTypeDef *USBx) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(USBx); - USBx_DEVICE->DCTL |= USB_OTG_DCTL_SDIS; HAL_Delay(3); @@ -844,9 +806,6 @@ uint32_t USB_ReadInterrupts (USB_OTG_GlobalTypeDef *USBx) uint32_t USB_ReadDevAllOutEpInterrupt (USB_OTG_GlobalTypeDef *USBx) { uint32_t tmpreg = 0; - /* Prevent unused argument(s) compilation warning */ - UNUSED(USBx); - tmpreg = USBx_DEVICE->DAINT; tmpreg &= USBx_DEVICE->DAINTMSK; return ((tmpreg & 0xffff0000) >> 16); @@ -860,9 +819,6 @@ uint32_t USB_ReadDevAllOutEpInterrupt (USB_OTG_GlobalTypeDef *USBx) uint32_t USB_ReadDevAllInEpInterrupt (USB_OTG_GlobalTypeDef *USBx) { uint32_t tmpreg = 0; - /* Prevent unused argument(s) compilation warning */ - UNUSED(USBx); - tmpreg = USBx_DEVICE->DAINT; tmpreg &= USBx_DEVICE->DAINTMSK; return ((tmpreg & 0xFFFF)); @@ -877,9 +833,6 @@ uint32_t USB_ReadDevAllInEpInterrupt (USB_OTG_GlobalTypeDef *USBx) */ uint32_t USB_ReadDevOutEPInterrupt (USB_OTG_GlobalTypeDef *USBx , uint8_t epnum) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(USBx); - uint32_t tmpreg = 0; tmpreg = USBx_OUTEP(epnum)->DOEPINT; tmpreg &= USBx_DEVICE->DOEPMSK; @@ -896,9 +849,7 @@ uint32_t USB_ReadDevOutEPInterrupt (USB_OTG_GlobalTypeDef *USBx , uint8_t epnum) uint32_t USB_ReadDevInEPInterrupt (USB_OTG_GlobalTypeDef *USBx , uint8_t epnum) { uint32_t tmpreg = 0, msk = 0, emp = 0; - /* Prevent unused argument(s) compilation warning */ - UNUSED(USBx); - + msk = USBx_DEVICE->DIEPMSK; emp = USBx_DEVICE->DIEPEMPMSK; msk |= ((emp >> epnum) & 0x1) << 7; @@ -927,9 +878,6 @@ void USB_ClearInterrupts (USB_OTG_GlobalTypeDef *USBx, uint32_t interrupt) */ uint32_t USB_GetMode(USB_OTG_GlobalTypeDef *USBx) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(USBx); - return ((USBx->GINTSTS ) & 0x1); } @@ -940,8 +888,6 @@ uint32_t USB_GetMode(USB_OTG_GlobalTypeDef *USBx) */ HAL_StatusTypeDef USB_ActivateSetup (USB_OTG_GlobalTypeDef *USBx) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(USBx); /* Set the MPS of the IN EP based on the enumeration speed */ USBx_INEP(0)->DIEPCTL &= ~USB_OTG_DIEPCTL_MPSIZ; @@ -962,9 +908,6 @@ HAL_StatusTypeDef USB_ActivateSetup (USB_OTG_GlobalTypeDef *USBx) */ HAL_StatusTypeDef USB_EP0_OutStart(USB_OTG_GlobalTypeDef *USBx, uint8_t *psetup) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(USBx); - UNUSED(psetup); USBx_OUTEP(0)->DOEPTSIZ = 0; USBx_OUTEP(0)->DOEPTSIZ |= (USB_OTG_DOEPTSIZ_PKTCNT & (1 << 19)); USBx_OUTEP(0)->DOEPTSIZ |= (3 * 8); @@ -1056,9 +999,6 @@ HAL_StatusTypeDef USB_HostInit (USB_OTG_GlobalTypeDef *USBx, USB_OTG_CfgTypeDef */ HAL_StatusTypeDef USB_InitFSLSPClkSel(USB_OTG_GlobalTypeDef *USBx , uint8_t freq) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(USBx); - USBx_HOST->HCFG &= ~(USB_OTG_HCFG_FSLSPCS); USBx_HOST->HCFG |= (freq & USB_OTG_HCFG_FSLSPCS); @@ -1083,9 +1023,7 @@ HAL_StatusTypeDef USB_InitFSLSPClkSel(USB_OTG_GlobalTypeDef *USBx , uint8_t freq HAL_StatusTypeDef USB_ResetPort(USB_OTG_GlobalTypeDef *USBx) { __IO uint32_t hprt0 = 0; - /* Prevent unused argument(s) compilation warning */ - UNUSED(USBx); - + hprt0 = USBx_HPRT0; hprt0 &= ~(USB_OTG_HPRT_PENA | USB_OTG_HPRT_PCDET |\ @@ -1108,9 +1046,7 @@ HAL_StatusTypeDef USB_ResetPort(USB_OTG_GlobalTypeDef *USBx) HAL_StatusTypeDef USB_DriveVbus (USB_OTG_GlobalTypeDef *USBx, uint8_t state) { __IO uint32_t hprt0 = 0; - /* Prevent unused argument(s) compilation warning */ - UNUSED(USBx); - + hprt0 = USBx_HPRT0; hprt0 &= ~(USB_OTG_HPRT_PENA | USB_OTG_HPRT_PCDET |\ USB_OTG_HPRT_PENCHNG | USB_OTG_HPRT_POCCHNG ); @@ -1137,9 +1073,7 @@ HAL_StatusTypeDef USB_DriveVbus (USB_OTG_GlobalTypeDef *USBx, uint8_t state) uint32_t USB_GetHostSpeed (USB_OTG_GlobalTypeDef *USBx) { __IO uint32_t hprt0 = 0; - /* Prevent unused argument(s) compilation warning */ - UNUSED(USBx); - + hprt0 = USBx_HPRT0; return ((hprt0 & USB_OTG_HPRT_PSPD) >> 17); } @@ -1151,9 +1085,6 @@ uint32_t USB_GetHostSpeed (USB_OTG_GlobalTypeDef *USBx) */ uint32_t USB_GetCurrentFrame (USB_OTG_GlobalTypeDef *USBx) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(USBx); - return (USBx_HOST->HFNUM & USB_OTG_HFNUM_FRNUM); } @@ -1361,9 +1292,6 @@ HAL_StatusTypeDef USB_HC_StartXfer(USB_OTG_GlobalTypeDef *USBx, USB_OTG_HCTypeDe */ uint32_t USB_HC_ReadInterrupt (USB_OTG_GlobalTypeDef *USBx) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(USBx); - return ((USBx_HOST->HAINT) & 0xFFFF); } @@ -1377,12 +1305,9 @@ uint32_t USB_HC_ReadInterrupt (USB_OTG_GlobalTypeDef *USBx) HAL_StatusTypeDef USB_HC_Halt(USB_OTG_GlobalTypeDef *USBx , uint8_t hc_num) { uint32_t count = 0; - /* Prevent unused argument(s) compilation warning */ - UNUSED(USBx); - + /* Check for space in the request queue to issue the halt. */ - if (((((USBx_HC(hc_num)->HCCHAR) & USB_OTG_HCCHAR_EPTYP) >> 18) == HCCHAR_CTRL) || - (((((USBx_HC(hc_num)->HCCHAR) & USB_OTG_HCCHAR_EPTYP) >> 18) == HCCHAR_BULK))) + if (((USBx_HC(hc_num)->HCCHAR) & (HCCHAR_CTRL << 18)) || ((USBx_HC(hc_num)->HCCHAR) & (HCCHAR_BULK << 18))) { USBx_HC(hc_num)->HCCHAR |= USB_OTG_HCCHAR_CHDIS; @@ -1443,9 +1368,7 @@ HAL_StatusTypeDef USB_DoPing(USB_OTG_GlobalTypeDef *USBx , uint8_t ch_num) { uint8_t num_packets = 1; uint32_t tmpreg = 0; - /* Prevent unused argument(s) compilation warning */ - UNUSED(USBx); - + USBx_HC(ch_num)->HCTSIZ = ((num_packets << 19) & USB_OTG_HCTSIZ_PKTCNT) |\ USB_OTG_HCTSIZ_DOPING; @@ -1519,8 +1442,6 @@ HAL_StatusTypeDef USB_StopHost(USB_OTG_GlobalTypeDef *USBx) */ HAL_StatusTypeDef USB_ActivateRemoteWakeup(USB_OTG_GlobalTypeDef *USBx) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(USBx); if((USBx_DEVICE->DSTS & USB_OTG_DSTS_SUSPSTS) == USB_OTG_DSTS_SUSPSTS) { /* active Remote wakeup signalling */ @@ -1536,8 +1457,6 @@ HAL_StatusTypeDef USB_ActivateRemoteWakeup(USB_OTG_GlobalTypeDef *USBx) */ HAL_StatusTypeDef USB_DeActivateRemoteWakeup(USB_OTG_GlobalTypeDef *USBx) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(USBx); /* active Remote wakeup signalling */ USBx_DEVICE->DCTL &= ~(USB_OTG_DCTL_RWUSIG); return HAL_OK; @@ -1558,9 +1477,6 @@ HAL_StatusTypeDef USB_DeActivateRemoteWakeup(USB_OTG_GlobalTypeDef *USBx) */ HAL_StatusTypeDef USB_CoreInit(USB_TypeDef *USBx, USB_CfgTypeDef cfg) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(USBx); - UNUSED(cfg); /* NOTE : - This function is not required by USB Device FS peripheral, it is used only by USB OTG FS peripheral. - This function is added to ensure compatibility across platforms. @@ -1580,7 +1496,7 @@ HAL_StatusTypeDef USB_EnableGlobalInt(USB_TypeDef *USBx) /* Set winterruptmask variable */ winterruptmask = USB_CNTR_CTRM | USB_CNTR_WKUPM | USB_CNTR_SUSPM | USB_CNTR_ERRM \ - | USB_CNTR_SOFM | USB_CNTR_ESOFM | USB_CNTR_RESETM; + | USB_CNTR_ESOFM | USB_CNTR_RESETM; /* Set interrupt mask */ USBx->CNTR |= winterruptmask; @@ -1618,9 +1534,6 @@ HAL_StatusTypeDef USB_DisableGlobalInt(USB_TypeDef *USBx) */ HAL_StatusTypeDef USB_SetCurrentMode(USB_TypeDef *USBx , USB_ModeTypeDef mode) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(USBx); - UNUSED(mode); /* NOTE : - This function is not required by USB Device FS peripheral, it is used only by USB OTG FS peripheral. - This function is added to ensure compatibility across platforms. @@ -1637,10 +1550,7 @@ HAL_StatusTypeDef USB_SetCurrentMode(USB_TypeDef *USBx , USB_ModeTypeDef mode) * @retval HAL status */ HAL_StatusTypeDef USB_DevInit (USB_TypeDef *USBx, USB_CfgTypeDef cfg) -{ - /* Prevent unused argument(s) compilation warning */ - UNUSED(cfg); - +{ /* Init Device */ /*CNTR_FRES = 1*/ USBx->CNTR = USB_CNTR_FRES; @@ -1653,9 +1563,6 @@ HAL_StatusTypeDef USB_DevInit (USB_TypeDef *USBx, USB_CfgTypeDef cfg) /*Set Btable Address*/ USBx->BTABLE = BTABLE_ADDRESS; - - /* Enable USB Device Interrupt mask */ - USB_EnableGlobalInt(USBx); return HAL_OK; } @@ -1668,11 +1575,8 @@ HAL_StatusTypeDef USB_DevInit (USB_TypeDef *USBx, USB_CfgTypeDef cfg) 15 means Flush all Tx FIFOs * @retval HAL status */ -HAL_StatusTypeDef USB_FlushTxFifo (USB_TypeDef *USBx, uint32_t num) +HAL_StatusTypeDef USB_FlushTxFifo (USB_TypeDef *USBx, uint32_t num ) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(USBx); - UNUSED(num); /* NOTE : - This function is not required by USB Device FS peripheral, it is used only by USB OTG FS peripheral. - This function is added to ensure compatibility across platforms. @@ -1687,8 +1591,6 @@ HAL_StatusTypeDef USB_FlushTxFifo (USB_TypeDef *USBx, uint32_t num) */ HAL_StatusTypeDef USB_FlushRxFifo(USB_TypeDef *USBx) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(USBx); /* NOTE : - This function is not required by USB Device FS peripheral, it is used only by USB OTG FS peripheral. - This function is added to ensure compatibility across platforms. @@ -1930,11 +1832,6 @@ HAL_StatusTypeDef USB_EPStartXfer(USB_TypeDef *USBx , USB_EPTypeDef *ep) */ HAL_StatusTypeDef USB_WritePacket(USB_TypeDef *USBx, uint8_t *src, uint8_t ch_ep_num, uint16_t len) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(USBx); - UNUSED(src); - UNUSED(ch_ep_num); - UNUSED(len); /* NOTE : - This function is not required by USB Device FS peripheral, it is used only by USB OTG FS peripheral. - This function is added to ensure compatibility across platforms. @@ -1952,10 +1849,6 @@ HAL_StatusTypeDef USB_WritePacket(USB_TypeDef *USBx, uint8_t *src, uint8_t ch_ep */ void *USB_ReadPacket(USB_TypeDef *USBx, uint8_t *dest, uint16_t len) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(USBx); - UNUSED(dest); - UNUSED(len); /* NOTE : - This function is not required by USB Device FS peripheral, it is used only by USB OTG FS peripheral. - This function is added to ensure compatibility across platforms. @@ -2055,8 +1948,6 @@ HAL_StatusTypeDef USB_SetDevAddress (USB_TypeDef *USBx, uint8_t address) */ HAL_StatusTypeDef USB_DevConnect (USB_TypeDef *USBx) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(USBx); /* NOTE : - This function is not required by USB Device FS peripheral, it is used only by USB OTG FS peripheral. - This function is added to ensure compatibility across platforms. @@ -2071,8 +1962,6 @@ HAL_StatusTypeDef USB_DevConnect (USB_TypeDef *USBx) */ HAL_StatusTypeDef USB_DevDisconnect (USB_TypeDef *USBx) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(USBx); /* NOTE : - This function is not required by USB Device FS peripheral, it is used only by USB OTG FS peripheral. - This function is added to ensure compatibility across platforms. @@ -2100,8 +1989,6 @@ uint32_t USB_ReadInterrupts (USB_TypeDef *USBx) */ uint32_t USB_ReadDevAllOutEpInterrupt (USB_TypeDef *USBx) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(USBx); /* NOTE : - This function is not required by USB Device FS peripheral, it is used only by USB OTG FS peripheral. - This function is added to ensure compatibility across platforms. @@ -2116,8 +2003,6 @@ uint32_t USB_ReadDevAllOutEpInterrupt (USB_TypeDef *USBx) */ uint32_t USB_ReadDevAllInEpInterrupt (USB_TypeDef *USBx) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(USBx); /* NOTE : - This function is not required by USB Device FS peripheral, it is used only by USB OTG FS peripheral. - This function is added to ensure compatibility across platforms. @@ -2134,9 +2019,6 @@ uint32_t USB_ReadDevAllInEpInterrupt (USB_TypeDef *USBx) */ uint32_t USB_ReadDevOutEPInterrupt (USB_TypeDef *USBx , uint8_t epnum) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(USBx); - UNUSED(epnum); /* NOTE : - This function is not required by USB Device FS peripheral, it is used only by USB OTG FS peripheral. - This function is added to ensure compatibility across platforms. @@ -2153,9 +2035,6 @@ uint32_t USB_ReadDevOutEPInterrupt (USB_TypeDef *USBx , uint8_t epnum) */ uint32_t USB_ReadDevInEPInterrupt (USB_TypeDef *USBx , uint8_t epnum) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(USBx); - UNUSED(epnum); /* NOTE : - This function is not required by USB Device FS peripheral, it is used only by USB OTG FS peripheral. - This function is added to ensure compatibility across platforms. @@ -2171,9 +2050,6 @@ uint32_t USB_ReadDevInEPInterrupt (USB_TypeDef *USBx , uint8_t epnum) */ void USB_ClearInterrupts (USB_TypeDef *USBx, uint32_t interrupt) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(USBx); - UNUSED(interrupt); /* NOTE : - This function is not required by USB Device FS peripheral, it is used only by USB OTG FS peripheral. - This function is added to ensure compatibility across platforms. @@ -2188,9 +2064,6 @@ void USB_ClearInterrupts (USB_TypeDef *USBx, uint32_t interrupt) */ HAL_StatusTypeDef USB_EP0_OutStart(USB_TypeDef *USBx, uint8_t *psetup) { - /* Prevent unused argument(s) compilation warning */ - UNUSED(USBx); - UNUSED(psetup); /* NOTE : - This function is not required by USB Device FS peripheral, it is used only by USB OTG FS peripheral. - This function is added to ensure compatibility across platforms. diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_usb.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_usb.h index 4538acba4c0..03adbeae2ae 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_usb.h +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_usb.h @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_ll_usb.h * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version V1.0.5 + * @date 06-December-2016 * @brief Header file of USB Low Layer HAL module. ****************************************************************************** * @attention diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_utils.c b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_utils.c index 91e071a15b7..9d68c2df4ad 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_utils.c +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_utils.c @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_ll_utils.c * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version $VERSION$ + * @date $DATE$ * @brief UTILS LL module driver. ****************************************************************************** * @attention @@ -128,7 +128,7 @@ || ((__VALUE__) == LL_RCC_PLL_MUL_16)) #endif /* RCC_CFGR_PLLMULL6_5 */ -#if defined(RCC_CFGR2_PREDIV1) +#if defined(RCC_PREDIV1_DIV_2_16_SUPPORT) #define IS_LL_UTILS_PREDIV_VALUE(__VALUE__) (((__VALUE__) == LL_RCC_PREDIV_DIV_1) || ((__VALUE__) == LL_RCC_PREDIV_DIV_2) || \ ((__VALUE__) == LL_RCC_PREDIV_DIV_3) || ((__VALUE__) == LL_RCC_PREDIV_DIV_4) || \ ((__VALUE__) == LL_RCC_PREDIV_DIV_5) || ((__VALUE__) == LL_RCC_PREDIV_DIV_6) || \ @@ -475,13 +475,13 @@ static uint32_t UTILS_GetPLLOutputFrequency(uint32_t PLL_InputFrequency, LL_UTIL assert_param(IS_LL_UTILS_PLLMUL_VALUE(UTILS_PLLInitStruct->PLLMul)); /* Check different PLL parameters according to RM */ -#if defined (RCC_CFGR2_PREDIV1) - pllfreq = __LL_RCC_CALC_PLLCLK_FREQ(PLL_InputFrequency / (UTILS_PLLInitStruct->Prediv + 1U), UTILS_PLLInitStruct->PLLMul); -#elif defined(RCC_CFGR2_PREDIV1SRC) +#if defined(RCC_PLLSRC_PREDIV1_SUPPORT) pllfreq = __LL_RCC_CALC_PLLCLK_FREQ(PLL_InputFrequency, UTILS_PLLInitStruct->PLLMul, UTILS_PLLInitStruct->PLLDiv); +#elif defined (RCC_PREDIV1_DIV_2_16_SUPPORT) + pllfreq = __LL_RCC_CALC_PLLCLK_FREQ(PLL_InputFrequency / (UTILS_PLLInitStruct->Prediv + 1U), UTILS_PLLInitStruct->PLLMul); #else pllfreq = __LL_RCC_CALC_PLLCLK_FREQ(PLL_InputFrequency / ((UTILS_PLLInitStruct->Prediv >> RCC_CFGR_PLLXTPRE_Pos) + 1U), UTILS_PLLInitStruct->PLLMul); -#endif /*RCC_CFGR2_PREDIV1SRC*/ +#endif /*RCC_PLLSRC_PREDIV1_SUPPORT*/ assert_param(IS_LL_UTILS_PLL_FREQUENCY(pllfreq)); return pllfreq; @@ -512,14 +512,14 @@ static ErrorStatus UTILS_PLL_IsBusy(void) } #endif /* RCC_PLL2_SUPPORT */ -#if defined(RCC_PLLI2S_SUPPORT) - /* Check if PLLI2S is busy*/ - if (LL_RCC_PLLI2S_IsReady() != 0U) +#if defined(RCC_PLL3_SUPPORT) + /* Check if PLL3 is busy*/ + if (LL_RCC_PLL3_IsReady() != 0U) { - /* PLLI2S configuration cannot be modified */ + /* PLL3 configuration cannot be modified */ status = ERROR; } -#endif /* RCC_PLLI2S_SUPPORT */ +#endif /* RCC_PLL3_SUPPORT */ return status; } @@ -536,18 +536,14 @@ static ErrorStatus UTILS_PLL_IsBusy(void) static ErrorStatus UTILS_EnablePLLAndSwitchSystem(uint32_t SYSCLK_Frequency, LL_UTILS_ClkInitTypeDef *UTILS_ClkInitStruct) { ErrorStatus status = SUCCESS; -#if defined(FLASH_ACR_LATENCY) uint32_t sysclk_frequency_current = 0U; -#endif /* FLASH_ACR_LATENCY */ assert_param(IS_LL_UTILS_SYSCLK_DIV(UTILS_ClkInitStruct->AHBCLKDivider)); assert_param(IS_LL_UTILS_APB1_DIV(UTILS_ClkInitStruct->APB1CLKDivider)); assert_param(IS_LL_UTILS_APB2_DIV(UTILS_ClkInitStruct->APB2CLKDivider)); -#if defined(FLASH_ACR_LATENCY) /* Calculate current SYSCLK frequency */ - sysclk_frequency_current = (SystemCoreClock << AHBPrescTable[LL_RCC_GetAHBPrescaler() >> RCC_CFGR_HPRE_Pos]); -#endif /* FLASH_ACR_LATENCY */ + sysclk_frequency_current = (SystemCoreClock << AHBPrescTable[(UTILS_ClkInitStruct->AHBCLKDivider & RCC_CFGR_HPRE) >> RCC_POSITION_HPRE]); /* Increasing the number of wait states because of higher CPU frequency */ #if defined (FLASH_ACR_LATENCY) diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_utils.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_utils.h index 1ac615c853d..c9a65233a7e 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_utils.h +++ b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_utils.h @@ -2,8 +2,8 @@ ****************************************************************************** * @file stm32f1xx_ll_utils.h * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 + * @version $VERSION$ + * @date $DATE$ * @brief Header file of UTILS LL module. @verbatim ============================================================================== diff --git a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_wwdg.h b/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_wwdg.h deleted file mode 100644 index 7330ac806af..00000000000 --- a/targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_ll_wwdg.h +++ /dev/null @@ -1,342 +0,0 @@ -/** - ****************************************************************************** - * @file stm32f1xx_ll_wwdg.h - * @author MCD Application Team - * @version V1.1.0 - * @date 14-April-2017 - * @brief Header file of WWDG LL module. - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2016 STMicroelectronics

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ - -/* Define to prevent recursive inclusion -------------------------------------*/ -#ifndef __STM32F1xx_LL_WWDG_H -#define __STM32F1xx_LL_WWDG_H - -#ifdef __cplusplus -extern "C" { -#endif - -/* Includes ------------------------------------------------------------------*/ -#include "stm32f1xx.h" - -/** @addtogroup STM32F1xx_LL_Driver - * @{ - */ - -#if defined (WWDG) - -/** @defgroup WWDG_LL WWDG - * @{ - */ - -/* Private types -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ - -/* Private constants ---------------------------------------------------------*/ - -/* Private macros ------------------------------------------------------------*/ - -/* Exported types ------------------------------------------------------------*/ -/* Exported constants --------------------------------------------------------*/ -/** @defgroup WWDG_LL_Exported_Constants WWDG Exported Constants - * @{ - */ - - -/** @defgroup WWDG_LL_EC_IT IT Defines - * @brief IT defines which can be used with LL_WWDG_ReadReg and LL_WWDG_WriteReg functions - * @{ - */ -#define LL_WWDG_CFR_EWI WWDG_CFR_EWI -/** - * @} - */ - -/** @defgroup WWDG_LL_EC_PRESCALER PRESCALER -* @{ -*/ -#define LL_WWDG_PRESCALER_1 0x00000000U /*!< WWDG counter clock = (PCLK1/4096)/1 */ -#define LL_WWDG_PRESCALER_2 WWDG_CFR_WDGTB_0 /*!< WWDG counter clock = (PCLK1/4096)/2 */ -#define LL_WWDG_PRESCALER_4 WWDG_CFR_WDGTB_1 /*!< WWDG counter clock = (PCLK1/4096)/4 */ -#define LL_WWDG_PRESCALER_8 (WWDG_CFR_WDGTB_0 | WWDG_CFR_WDGTB_1) /*!< WWDG counter clock = (PCLK1/4096)/8 */ -/** - * @} - */ - -/** - * @} - */ - -/* Exported macro ------------------------------------------------------------*/ -/** @defgroup WWDG_LL_Exported_Macros WWDG Exported Macros - * @{ - */ -/** @defgroup WWDG_LL_EM_WRITE_READ Common Write and read registers macros - * @{ - */ -/** - * @brief Write a value in WWDG register - * @param __INSTANCE__ WWDG Instance - * @param __REG__ Register to be written - * @param __VALUE__ Value to be written in the register - * @retval None - */ -#define LL_WWDG_WriteReg(__INSTANCE__, __REG__, __VALUE__) WRITE_REG(__INSTANCE__->__REG__, (__VALUE__)) - -/** - * @brief Read a value in WWDG register - * @param __INSTANCE__ WWDG Instance - * @param __REG__ Register to be read - * @retval Register value - */ -#define LL_WWDG_ReadReg(__INSTANCE__, __REG__) READ_REG(__INSTANCE__->__REG__) -/** - * @} - */ - - -/** - * @} - */ - -/* Exported functions --------------------------------------------------------*/ -/** @defgroup WWDG_LL_Exported_Functions WWDG Exported Functions - * @{ - */ - -/** @defgroup WWDG_LL_EF_Configuration Configuration - * @{ - */ -/** - * @brief Enable Window Watchdog. The watchdog is always disabled after a reset. - * @note It is enabled by setting the WDGA bit in the WWDG_CR register, - * then it cannot be disabled again except by a reset. - * This bit is set by software and only cleared by hardware after a reset. - * When WDGA = 1, the watchdog can generate a reset. - * @rmtoll CR WDGA LL_WWDG_Enable - * @param WWDGx WWDG Instance - * @retval None - */ -__STATIC_INLINE void LL_WWDG_Enable(WWDG_TypeDef *WWDGx) -{ - SET_BIT(WWDGx->CR, WWDG_CR_WDGA); -} - -/** - * @brief Checks if Window Watchdog is enabled - * @rmtoll CR WDGA LL_WWDG_IsEnabled - * @param WWDGx WWDG Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_WWDG_IsEnabled(WWDG_TypeDef *WWDGx) -{ - return (READ_BIT(WWDGx->CR, WWDG_CR_WDGA) == (WWDG_CR_WDGA)); -} - -/** - * @brief Set the Watchdog counter value to provided value (7-bits T[6:0]) - * @note When writing to the WWDG_CR register, always write 1 in the MSB b6 to avoid generating an immediate reset - * This counter is decremented every (4096 x 2expWDGTB) PCLK cycles - * A reset is produced when it rolls over from 0x40 to 0x3F (bit T6 becomes cleared) - * Setting the counter lower then 0x40 causes an immediate reset (if WWDG enabled) - * @rmtoll CR T LL_WWDG_SetCounter - * @param WWDGx WWDG Instance - * @param Counter 0..0x7F (7 bit counter value) - * @retval None - */ -__STATIC_INLINE void LL_WWDG_SetCounter(WWDG_TypeDef *WWDGx, uint32_t Counter) -{ - MODIFY_REG(WWDGx->CR, WWDG_CR_T, Counter); -} - -/** - * @brief Return current Watchdog Counter Value (7 bits counter value) - * @rmtoll CR T LL_WWDG_GetCounter - * @param WWDGx WWDG Instance - * @retval 7 bit Watchdog Counter value - */ -__STATIC_INLINE uint32_t LL_WWDG_GetCounter(WWDG_TypeDef *WWDGx) -{ - return (uint32_t)(READ_BIT(WWDGx->CR, WWDG_CR_T)); -} - -/** - * @brief Set the time base of the prescaler (WDGTB). - * @note Prescaler is used to apply ratio on PCLK clock, so that Watchdog counter - * is decremented every (4096 x 2expWDGTB) PCLK cycles - * @rmtoll CFR WDGTB LL_WWDG_SetPrescaler - * @param WWDGx WWDG Instance - * @param Prescaler This parameter can be one of the following values: - * @arg @ref LL_WWDG_PRESCALER_1 - * @arg @ref LL_WWDG_PRESCALER_2 - * @arg @ref LL_WWDG_PRESCALER_4 - * @arg @ref LL_WWDG_PRESCALER_8 - * @retval None - */ -__STATIC_INLINE void LL_WWDG_SetPrescaler(WWDG_TypeDef *WWDGx, uint32_t Prescaler) -{ - MODIFY_REG(WWDGx->CFR, WWDG_CFR_WDGTB, Prescaler); -} - -/** - * @brief Return current Watchdog Prescaler Value - * @rmtoll CFR WDGTB LL_WWDG_GetPrescaler - * @param WWDGx WWDG Instance - * @retval Returned value can be one of the following values: - * @arg @ref LL_WWDG_PRESCALER_1 - * @arg @ref LL_WWDG_PRESCALER_2 - * @arg @ref LL_WWDG_PRESCALER_4 - * @arg @ref LL_WWDG_PRESCALER_8 - */ -__STATIC_INLINE uint32_t LL_WWDG_GetPrescaler(WWDG_TypeDef *WWDGx) -{ - return (uint32_t)(READ_BIT(WWDGx->CFR, WWDG_CFR_WDGTB)); -} - -/** - * @brief Set the Watchdog Window value to be compared to the downcounter (7-bits W[6:0]). - * @note This window value defines when write in the WWDG_CR register - * to program Watchdog counter is allowed. - * Watchdog counter value update must occur only when the counter value - * is lower than the Watchdog window register value. - * Otherwise, a MCU reset is generated if the 7-bit Watchdog counter value - * (in the control register) is refreshed before the downcounter has reached - * the watchdog window register value. - * Physically is possible to set the Window lower then 0x40 but it is not recommended. - * To generate an immediate reset, it is possible to set the Counter lower than 0x40. - * @rmtoll CFR W LL_WWDG_SetWindow - * @param WWDGx WWDG Instance - * @param Window 0x00..0x7F (7 bit Window value) - * @retval None - */ -__STATIC_INLINE void LL_WWDG_SetWindow(WWDG_TypeDef *WWDGx, uint32_t Window) -{ - MODIFY_REG(WWDGx->CFR, WWDG_CFR_W, Window); -} - -/** - * @brief Return current Watchdog Window Value (7 bits value) - * @rmtoll CFR W LL_WWDG_GetWindow - * @param WWDGx WWDG Instance - * @retval 7 bit Watchdog Window value - */ -__STATIC_INLINE uint32_t LL_WWDG_GetWindow(WWDG_TypeDef *WWDGx) -{ - return (uint32_t)(READ_BIT(WWDGx->CFR, WWDG_CFR_W)); -} - -/** - * @} - */ - -/** @defgroup WWDG_LL_EF_FLAG_Management FLAG_Management - * @{ - */ -/** - * @brief Indicates if the WWDG Early Wakeup Interrupt Flag is set or not. - * @note This bit is set by hardware when the counter has reached the value 0x40. - * It must be cleared by software by writing 0. - * A write of 1 has no effect. This bit is also set if the interrupt is not enabled. - * @rmtoll SR EWIF LL_WWDG_IsActiveFlag_EWKUP - * @param WWDGx WWDG Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_WWDG_IsActiveFlag_EWKUP(WWDG_TypeDef *WWDGx) -{ - return (READ_BIT(WWDGx->SR, WWDG_SR_EWIF) == (WWDG_SR_EWIF)); -} - -/** - * @brief Clear WWDG Early Wakeup Interrupt Flag (EWIF) - * @rmtoll SR EWIF LL_WWDG_ClearFlag_EWKUP - * @param WWDGx WWDG Instance - * @retval None - */ -__STATIC_INLINE void LL_WWDG_ClearFlag_EWKUP(WWDG_TypeDef *WWDGx) -{ - WRITE_REG(WWDGx->SR, ~WWDG_SR_EWIF); -} - -/** - * @} - */ - -/** @defgroup WWDG_LL_EF_IT_Management IT_Management - * @{ - */ -/** - * @brief Enable the Early Wakeup Interrupt. - * @note When set, an interrupt occurs whenever the counter reaches value 0x40. - * This interrupt is only cleared by hardware after a reset - * @rmtoll CFR EWI LL_WWDG_EnableIT_EWKUP - * @param WWDGx WWDG Instance - * @retval None - */ -__STATIC_INLINE void LL_WWDG_EnableIT_EWKUP(WWDG_TypeDef *WWDGx) -{ - SET_BIT(WWDGx->CFR, WWDG_CFR_EWI); -} - -/** - * @brief Check if Early Wakeup Interrupt is enabled - * @rmtoll CFR EWI LL_WWDG_IsEnabledIT_EWKUP - * @param WWDGx WWDG Instance - * @retval State of bit (1 or 0). - */ -__STATIC_INLINE uint32_t LL_WWDG_IsEnabledIT_EWKUP(WWDG_TypeDef *WWDGx) -{ - return (READ_BIT(WWDGx->CFR, WWDG_CFR_EWI) == (WWDG_CFR_EWI)); -} - -/** - * @} - */ - -/** - * @} - */ - -/** - * @} - */ - -#endif /* WWDG */ - -/** - * @} - */ - -#ifdef __cplusplus -} -#endif - -#endif /* __STM32F1xx_LL_WWDG_H */ - -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/targets/TARGET_STM/TARGET_STM32F1/serial_api.c b/targets/TARGET_STM/TARGET_STM32F1/serial_api.c index cf0df17d7cb..8d7940508f4 100644 --- a/targets/TARGET_STM/TARGET_STM32F1/serial_api.c +++ b/targets/TARGET_STM/TARGET_STM32F1/serial_api.c @@ -158,19 +158,19 @@ void serial_free(serial_t *obj) // Reset UART and disable clock if (obj_s->uart == UART_1) { - __HAL_RCC_USART1_FORCE_RESET(); - __HAL_RCC_USART1_RELEASE_RESET(); - __HAL_RCC_USART1_CLK_DISABLE(); + __USART1_FORCE_RESET(); + __USART1_RELEASE_RESET(); + __USART1_CLK_DISABLE(); } if (obj_s->uart == UART_2) { - __HAL_RCC_USART2_FORCE_RESET(); - __HAL_RCC_USART2_RELEASE_RESET(); - __HAL_RCC_USART2_CLK_DISABLE(); + __USART2_FORCE_RESET(); + __USART2_RELEASE_RESET(); + __USART2_CLK_DISABLE(); } if (obj_s->uart == UART_3) { - __HAL_RCC_USART3_FORCE_RESET(); - __HAL_RCC_USART3_RELEASE_RESET(); - __HAL_RCC_USART3_CLK_DISABLE(); + __USART3_FORCE_RESET(); + __USART3_RELEASE_RESET(); + __USART3_CLK_DISABLE(); } // Configure GPIOs @@ -750,10 +750,10 @@ void serial_tx_abort_asynch(serial_t *obj) // reset states huart->TxXferCount = 0; // update handle state - if(huart->gState == HAL_UART_STATE_BUSY_TX_RX) { - huart->gState = HAL_UART_STATE_BUSY_RX; + if(huart->State == HAL_UART_STATE_BUSY_TX_RX) { + huart->State = HAL_UART_STATE_BUSY_RX; } else { - huart->gState = HAL_UART_STATE_READY; + huart->State = HAL_UART_STATE_READY; } } @@ -780,10 +780,10 @@ void serial_rx_abort_asynch(serial_t *obj) // reset states huart->RxXferCount = 0; // update handle state - if(huart->RxState == HAL_UART_STATE_BUSY_TX_RX) { - huart->RxState = HAL_UART_STATE_BUSY_TX; + if(huart->State == HAL_UART_STATE_BUSY_TX_RX) { + huart->State = HAL_UART_STATE_BUSY_TX; } else { - huart->RxState = HAL_UART_STATE_READY; + huart->State = HAL_UART_STATE_READY; } } diff --git a/targets/TARGET_STM/TARGET_STM32F2/TARGET_NUCLEO_F207ZG/PeripheralPins.c b/targets/TARGET_STM/TARGET_STM32F2/TARGET_NUCLEO_F207ZG/PeripheralPins.c index 9e2f6a80f00..fa19697262b 100644 --- a/targets/TARGET_STM/TARGET_STM32F2/TARGET_NUCLEO_F207ZG/PeripheralPins.c +++ b/targets/TARGET_STM/TARGET_STM32F2/TARGET_NUCLEO_F207ZG/PeripheralPins.c @@ -57,8 +57,8 @@ const PinMap PinMap_ADC[] = { {PA_5_ALT0, ADC_2, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 5, 0)}, // ADC2_IN5 // choice: PA_5 with ADC_1 {PA_6_ALT0, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 6, 0)}, // ADC1_IN6 // choice: PA_6 with ADC_2 {PA_6, ADC_2, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 6, 0)}, // ADC2_IN6 - {PA_7_ALT0, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 7, 0)}, // ADC1_IN7 // Ethernet RMII RX Data Valid - used when JP6 ON - choice: PA_7 with ADC_2 - {PA_7, ADC_2, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 7, 0)}, // ADC2_IN7 // Ethernet RMII RX Data Valid - used when JP6 ON - choice: PA_7 with ADC_2 +// {PA_7, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 7, 0)}, // ADC1_IN7 // Ethernet RMII RX Data Valid +// {PA_7, ADC_2, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 7, 0)}, // ADC2_IN7 // Ethernet RMII RX Data Valid // {PB_0, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 8, 0)}, // ADC1_IN8 // LED1 // {PB_0, ADC_2, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 8, 0)}, // ADC2_IN8 // LED1 {PB_1, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 9, 0)}, // ADC1_IN9 @@ -87,10 +87,6 @@ const PinMap PinMap_ADC[] = { {PF_8, ADC_3, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 6, 0)}, // ADC3_IN6 {PF_9, ADC_3, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 7, 0)}, // ADC3_IN7 {PF_10, ADC_3, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 8, 0)}, // ADC3_IN8 - {NC, NC, 0} -}; - -const PinMap PinMap_ADC_Internal[] = { {ADC_TEMP, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 16, 0)}, // See in analogin_api.c the correct ADC channel used {ADC_VREF, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 17, 0)}, // See in analogin_api.c the correct ADC channel used {ADC_VBAT, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 18, 0)}, // See in analogin_api.c the correct ADC channel used @@ -111,7 +107,7 @@ const PinMap PinMap_I2C_SDA[] = { // {PB_7, I2C_1 , STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C1)}, // LED2 {PB_9, I2C_1 , STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C1)}, {PB_11, I2C_2 , STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C2)}, -// {PC_9, I2C_3 , STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C3)}, // no I2C_3 SCL available + {PC_9, I2C_3 , STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C3)}, {PF_0, I2C_2 , STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C2)}, {NC, NC, 0} }; @@ -142,10 +138,10 @@ const PinMap PinMap_PWM[] = { {PA_5, PWM_8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 1, 1)}, // TIM8_CH1N {PA_6, PWM_13, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF9_TIM13, 1, 0)}, // TIM13_CH1 {PA_6_ALT0, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 1, 0)}, // TIM3_CH1 // choice: PA_6 with PWM_13 - {PA_7, PWM_14, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF9_TIM14, 1, 0)}, // TIM14_CH1 // Ethernet RMII RX Data Valid - used when JP6 ON - choice: PA_7 with PWM_14 - {PA_7_ALT0, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 1, 1)}, // TIM1_CH1N // Ethernet RMII RX Data Valid - used when JP6 ON - choice: PA_7 with PWM_14 - {PA_7_ALT1, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 2, 0)}, // TIM3_CH2 // Ethernet RMII RX Data Valid - used when JP6 ON - choice: PA_7 with PWM_14 - {PA_7_ALT2, PWM_8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 1, 1)}, // TIM8_CH1N // Ethernet RMII RX Data Valid - used when JP6 ON - choice: PA_7 with PWM_14 +// {PA_7, PWM_14, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF9_TIM14, 1, 0)}, // TIM14_CH1 // Ethernet RMII RX Data Valid +// {PA_7, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 1, 1)}, // TIM1_CH1N // Ethernet RMII RX Data Valid +// {PA_7, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 2, 0)}, // TIM3_CH2 // Ethernet RMII RX Data Valid +// {PA_7, PWM_8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 1, 1)}, // TIM8_CH1N // Ethernet RMII RX Data Valid // {PA_8, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 1, 0)}, // TIM1_CH1 // USB SOF // {PA_9, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 2, 0)}, // TIM1_CH2 // USB VBUS // {PA_10, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 3, 0)}, // TIM1_CH3 // USB ID @@ -263,10 +259,8 @@ const PinMap PinMap_UART_CTS[] = { //*** SPI *** const PinMap PinMap_SPI_MOSI[] = { - {PA_7, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI1)}, // Ethernet RMII RX Data Valid - used when JP6 ON - ARDUINO D11 (default configuration) - {PB_5, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI1)}, // ARDUINO D11 (need HW and SW updates) - // HW solder bridge update : SB121 off, SB122 on - // SW : config from json files + {PA_7, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI1)}, // Ethernet RMII RX Data Valid // D11 + {PB_5, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI1)}, // {PB_5, SPI_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_SPI3)}, // choice: PB_5 with SPI_1 {PB_15, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI2)}, {PC_3, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI2)}, diff --git a/targets/TARGET_STM/TARGET_STM32F2/TARGET_NUCLEO_F207ZG/PinNames.h b/targets/TARGET_STM/TARGET_STM32F2/TARGET_NUCLEO_F207ZG/PinNames.h index 71ae5402e34..90a2763da0f 100644 --- a/targets/TARGET_STM/TARGET_STM32F2/TARGET_NUCLEO_F207ZG/PinNames.h +++ b/targets/TARGET_STM/TARGET_STM32F2/TARGET_NUCLEO_F207ZG/PinNames.h @@ -58,9 +58,6 @@ typedef enum { PA_6 = 0x06, PA_6_ALT0 = 0x06|ALT0, PA_7 = 0x07, - PA_7_ALT0 = 0x07|ALT0, - PA_7_ALT1 = 0x07|ALT1, - PA_7_ALT2 = 0x07|ALT2, PA_8 = 0x08, PA_9 = 0x09, PA_10 = 0x0A, @@ -221,7 +218,7 @@ typedef enum { D8 = PF_12, D9 = PD_15, D10 = PD_14, - D11 = STM32_D11_SPI_ETHERNET_PIN, /* config in targets.json file */ + D11 = PA_7, D12 = PA_6, D13 = PA_5, D14 = PB_9, @@ -233,8 +230,6 @@ typedef enum { LED3 = PB_14, LED4 = LED1, USER_BUTTON = PC_13, - // Standardized button names - BUTTON1 = USER_BUTTON, SERIAL_TX = PD_8, SERIAL_RX = PD_9, USBTX = SERIAL_TX, diff --git a/features/unsupported/USBHost/USBHost/TARGET_STM/TARGET_STM32F2/TARGET_NUCLEO_F207ZG/USBHALHost_STM_TARGET.h b/targets/TARGET_STM/TARGET_STM32F2/TARGET_NUCLEO_F207ZG/USBHALHost_STM_TARGET.h similarity index 100% rename from features/unsupported/USBHost/USBHost/TARGET_STM/TARGET_STM32F2/TARGET_NUCLEO_F207ZG/USBHALHost_STM_TARGET.h rename to targets/TARGET_STM/TARGET_STM32F2/TARGET_NUCLEO_F207ZG/USBHALHost_STM_TARGET.h diff --git a/features/unsupported/USBDevice/USBDevice/TARGET_STM/TARGET_STM32F2/TARGET_NUCLEO_F207ZG/USBHAL_STM_TARGET.h b/targets/TARGET_STM/TARGET_STM32F2/TARGET_NUCLEO_F207ZG/USBHAL_STM_TARGET.h similarity index 100% rename from features/unsupported/USBDevice/USBDevice/TARGET_STM/TARGET_STM32F2/TARGET_NUCLEO_F207ZG/USBHAL_STM_TARGET.h rename to targets/TARGET_STM/TARGET_STM32F2/TARGET_NUCLEO_F207ZG/USBHAL_STM_TARGET.h diff --git a/targets/TARGET_STM/TARGET_STM32F2/analogin_api.c b/targets/TARGET_STM/TARGET_STM32F2/analogin_api.c index ba154c94f10..a71a4c285e0 100644 --- a/targets/TARGET_STM/TARGET_STM32F2/analogin_api.c +++ b/targets/TARGET_STM/TARGET_STM32F2/analogin_api.c @@ -40,9 +40,6 @@ ADC_HandleTypeDef AdcHandle; void analogin_init(analogin_t *obj, PinName pin) { - uint32_t function = (uint32_t)NC; - obj->adc = (ADCName)NC; - #if defined(ADC1) static int adc1_inited = 0; #endif @@ -52,28 +49,21 @@ void analogin_init(analogin_t *obj, PinName pin) #if defined(ADC3) static int adc3_inited = 0; #endif - // ADC Internal Channels "pins" (Temperature, Vref, Vbat, ...) - // are described in PinNames.h and PeripheralPins.c - // Pin value must be between 0xF0 and 0xFF - if ((pin < 0xF0) || (pin >= 0x100)) { - // Normal channels - // Get the peripheral name from the pin and assign it to the object - obj->adc = (ADCName)pinmap_peripheral(pin, PinMap_ADC); - // Get the functions (adc channel) from the pin and assign it to the object - function = pinmap_function(pin, PinMap_ADC); - // Configure GPIO - pinmap_pinout(pin, PinMap_ADC); - } else { - // Internal channels - obj->adc = (ADCName)pinmap_peripheral(pin, PinMap_ADC_Internal); - function = pinmap_function(pin, PinMap_ADC_Internal); - // No GPIO configuration for internal channels - } + // Get the peripheral name from the pin and assign it to the object + obj->adc = (ADCName)pinmap_peripheral(pin, PinMap_ADC); MBED_ASSERT(obj->adc != (ADCName)NC); - MBED_ASSERT(function != (uint32_t)NC); + // Get the functions (adc channel) from the pin and assign it to the object + uint32_t function = pinmap_function(pin, PinMap_ADC); + MBED_ASSERT(function != (uint32_t)NC); obj->channel = STM_PIN_CHANNEL(function); + // Configure GPIO excepted for internal channels (Temperature, Vref, Vbat, ...) + // ADC Internal Channels "pins" are described in PinNames.h and must have a value >= 0xF0 + if (pin < 0xF0) { + pinmap_pinout(pin, PinMap_ADC); + } + // Save pin number for the read function obj->pin = pin; diff --git a/targets/TARGET_STM/TARGET_STM32F2/device/stm32f2xx_hal_def.h b/targets/TARGET_STM/TARGET_STM32F2/device/stm32f2xx_hal_def.h index bec8dbaac37..d98baf61492 100644 --- a/targets/TARGET_STM/TARGET_STM32F2/device/stm32f2xx_hal_def.h +++ b/targets/TARGET_STM/TARGET_STM32F2/device/stm32f2xx_hal_def.h @@ -145,7 +145,7 @@ static inline void atomic_clr_u32(volatile uint32_t *ptr, uint32_t mask) } while (__STREXW(newValue,(volatile unsigned long*) ptr)); } -#if defined ( __GNUC__ ) && !defined ( __CC_ARM ) +#if defined ( __GNUC__ ) #ifndef __weak #define __weak __attribute__((weak)) #endif /* __weak */ diff --git a/targets/TARGET_STM/TARGET_STM32F2/device/stm32f2xx_hal_hcd.c b/targets/TARGET_STM/TARGET_STM32F2/device/stm32f2xx_hal_hcd.c index 1d1e0157214..4f49587a873 100644 --- a/targets/TARGET_STM/TARGET_STM32F2/device/stm32f2xx_hal_hcd.c +++ b/targets/TARGET_STM/TARGET_STM32F2/device/stm32f2xx_hal_hcd.c @@ -930,15 +930,11 @@ static void HCD_HC_IN_IRQHandler(HCD_HandleTypeDef *hhcd, uint8_t chnum) /* re-activate the channel */ tmpreg = USBx_HC(chnum)->HCCHAR; tmpreg &= ~USB_OTG_HCCHAR_CHDIS; - if ( hhcd->hc[chnum].urb_state != URB_ERROR) { - tmpreg |= USB_OTG_HCCHAR_CHENA; - reactivate = 1; - } + tmpreg |= USB_OTG_HCCHAR_CHENA; USBx_HC(chnum)->HCCHAR = tmpreg; + reactivate = 1; } __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_CHH); - if (hhcd->hc[chnum].state == 0) reactivate = 1; - if (reactivate == 0) HAL_HCD_HC_NotifyURBChange_Callback(hhcd, chnum, hhcd->hc[chnum].urb_state); } diff --git a/features/unsupported/USBDevice/USBDevice/TARGET_STM/TARGET_STM32F3/TARGET_STM32F303xE/TARGET_NUCLEO_F303ZE/USBHAL_STM32F303ZE.h b/targets/TARGET_STM/TARGET_STM32F3/TARGET_NUCLEO_F303ZE/USBHAL_STM32F303ZE.h similarity index 100% rename from features/unsupported/USBDevice/USBDevice/TARGET_STM/TARGET_STM32F3/TARGET_STM32F303xE/TARGET_NUCLEO_F303ZE/USBHAL_STM32F303ZE.h rename to targets/TARGET_STM/TARGET_STM32F3/TARGET_NUCLEO_F303ZE/USBHAL_STM32F303ZE.h diff --git a/features/unsupported/USBDevice/USBDevice/TARGET_STM/TARGET_STM32F3/TARGET_STM32F303xE/TARGET_NUCLEO_F303ZE/USBHAL_STM_TARGET.h b/targets/TARGET_STM/TARGET_STM32F3/TARGET_NUCLEO_F303ZE/USBHAL_STM_TARGET.h similarity index 100% rename from features/unsupported/USBDevice/USBDevice/TARGET_STM/TARGET_STM32F3/TARGET_STM32F303xE/TARGET_NUCLEO_F303ZE/USBHAL_STM_TARGET.h rename to targets/TARGET_STM/TARGET_STM32F3/TARGET_NUCLEO_F303ZE/USBHAL_STM_TARGET.h diff --git a/targets/TARGET_STM/TARGET_STM32F3/TARGET_STM32F302x8/TARGET_NUCLEO_F302R8/PinNames.h b/targets/TARGET_STM/TARGET_STM32F3/TARGET_STM32F302x8/TARGET_NUCLEO_F302R8/PinNames.h index 854619b50d2..e82e9d4c168 100644 --- a/targets/TARGET_STM/TARGET_STM32F3/TARGET_STM32F302x8/TARGET_NUCLEO_F302R8/PinNames.h +++ b/targets/TARGET_STM/TARGET_STM32F3/TARGET_STM32F302x8/TARGET_NUCLEO_F302R8/PinNames.h @@ -129,8 +129,6 @@ typedef enum { LED3 = PB_13, LED4 = PB_13, USER_BUTTON = PC_13, - // Standardized button names - BUTTON1 = USER_BUTTON, SERIAL_TX = PA_2, SERIAL_RX = PA_3, USBTX = PA_2, diff --git a/targets/TARGET_STM/TARGET_STM32F3/TARGET_STM32F303x8/TARGET_NUCLEO_F303K8/PinNames.h b/targets/TARGET_STM/TARGET_STM32F3/TARGET_STM32F303x8/TARGET_NUCLEO_F303K8/PinNames.h index c46b324dfc6..2251f447f6d 100644 --- a/targets/TARGET_STM/TARGET_STM32F3/TARGET_STM32F303x8/TARGET_NUCLEO_F303K8/PinNames.h +++ b/targets/TARGET_STM/TARGET_STM32F3/TARGET_STM32F303x8/TARGET_NUCLEO_F303K8/PinNames.h @@ -104,8 +104,6 @@ typedef enum { LED3 = PB_3, LED4 = PB_3, USER_BUTTON = 0x20, // no user button on the board - // Standardized button names - BUTTON1 = USER_BUTTON, SERIAL_TX = PA_2, SERIAL_RX = PA_15, USBTX = PA_2, diff --git a/targets/TARGET_STM/TARGET_STM32F3/TARGET_STM32F303xC/TARGET_DISCO_F303VC/PinNames.h b/targets/TARGET_STM/TARGET_STM32F3/TARGET_STM32F303xC/TARGET_DISCO_F303VC/PinNames.h index 5521861649b..006d53492c7 100644 --- a/targets/TARGET_STM/TARGET_STM32F3/TARGET_STM32F303xC/TARGET_DISCO_F303VC/PinNames.h +++ b/targets/TARGET_STM/TARGET_STM32F3/TARGET_STM32F303xC/TARGET_DISCO_F303VC/PinNames.h @@ -189,8 +189,6 @@ typedef enum { LED9 = PE_12, LED10 = PE_13, USER_BUTTON = PA_0, - // Standardized button names - BUTTON1 = USER_BUTTON, SERIAL_TX = PA_2, SERIAL_RX = PA_3, USBTX = PA_2, diff --git a/targets/TARGET_STM/TARGET_STM32F3/TARGET_STM32F303xE/TARGET_NUCLEO_F303RE/PinNames.h b/targets/TARGET_STM/TARGET_STM32F3/TARGET_STM32F303xE/TARGET_NUCLEO_F303RE/PinNames.h index c7386f06a5a..8eb572291a0 100644 --- a/targets/TARGET_STM/TARGET_STM32F3/TARGET_STM32F303xE/TARGET_NUCLEO_F303RE/PinNames.h +++ b/targets/TARGET_STM/TARGET_STM32F3/TARGET_STM32F303xE/TARGET_NUCLEO_F303RE/PinNames.h @@ -137,8 +137,6 @@ typedef enum { LED3 = PA_5, LED4 = PA_5, USER_BUTTON = PC_13, - // Standardized button names - BUTTON1 = USER_BUTTON, SERIAL_TX = PA_2, SERIAL_RX = PA_3, USBTX = PA_2, diff --git a/targets/TARGET_STM/TARGET_STM32F3/TARGET_STM32F303xE/TARGET_NUCLEO_F303ZE/PinNames.h b/targets/TARGET_STM/TARGET_STM32F3/TARGET_STM32F303xE/TARGET_NUCLEO_F303ZE/PinNames.h index 24c00b7ac17..7505f5f6378 100644 --- a/targets/TARGET_STM/TARGET_STM32F3/TARGET_STM32F303xE/TARGET_NUCLEO_F303ZE/PinNames.h +++ b/targets/TARGET_STM/TARGET_STM32F3/TARGET_STM32F303xE/TARGET_NUCLEO_F303ZE/PinNames.h @@ -204,8 +204,6 @@ typedef enum { LED3 = PB_14, LED4 = LED1, USER_BUTTON = PC_13, - // Standardized button names - BUTTON1 = USER_BUTTON, SERIAL_TX = PD_8, // Virtual Com Port SERIAL_RX = PD_9, // Virtual Com Port USBTX = SERIAL_TX, // Virtual Com Port diff --git a/targets/TARGET_STM/TARGET_STM32F3/TARGET_STM32F334x8/TARGET_DISCO_F334C8/PinNames.h b/targets/TARGET_STM/TARGET_STM32F3/TARGET_STM32F334x8/TARGET_DISCO_F334C8/PinNames.h index ea7db7d7507..673292d7c6b 100644 --- a/targets/TARGET_STM/TARGET_STM32F3/TARGET_STM32F334x8/TARGET_DISCO_F334C8/PinNames.h +++ b/targets/TARGET_STM/TARGET_STM32F3/TARGET_STM32F334x8/TARGET_DISCO_F334C8/PinNames.h @@ -119,8 +119,6 @@ typedef enum { LED3 = PB_8, LED4 = PB_9, USER_BUTTON = PA_0, - // Standardized button names - BUTTON1 = USER_BUTTON, SERIAL_TX = PB_3, SERIAL_RX = PB_4, USBTX = PB_3, diff --git a/targets/TARGET_STM/TARGET_STM32F3/TARGET_STM32F334x8/TARGET_NUCLEO_F334R8/PinNames.h b/targets/TARGET_STM/TARGET_STM32F3/TARGET_STM32F334x8/TARGET_NUCLEO_F334R8/PinNames.h index fce0ab472e9..f67d08ec9f5 100644 --- a/targets/TARGET_STM/TARGET_STM32F3/TARGET_STM32F334x8/TARGET_NUCLEO_F334R8/PinNames.h +++ b/targets/TARGET_STM/TARGET_STM32F3/TARGET_STM32F334x8/TARGET_NUCLEO_F334R8/PinNames.h @@ -132,8 +132,6 @@ typedef enum { LED3 = PA_5, LED4 = PA_5, USER_BUTTON = PC_13, - // Standardized button names - BUTTON1 = USER_BUTTON, SERIAL_TX = PA_2, SERIAL_RX = PA_3, USBTX = PA_2, diff --git a/targets/TARGET_STM/TARGET_STM32F3/device/stm32f3xx_hal_def.h b/targets/TARGET_STM/TARGET_STM32F3/device/stm32f3xx_hal_def.h index 757a6e8458d..0b61f946ece 100644 --- a/targets/TARGET_STM/TARGET_STM32F3/device/stm32f3xx_hal_def.h +++ b/targets/TARGET_STM/TARGET_STM32F3/device/stm32f3xx_hal_def.h @@ -144,7 +144,7 @@ static inline void atomic_clr_u32(volatile uint32_t *ptr, uint32_t mask) } while (__STREXW(newValue,(volatile unsigned long*) ptr)); } -#if defined ( __GNUC__ ) && !defined ( __CC_ARM ) +#if defined ( __GNUC__ ) #ifndef __weak #define __weak __attribute__((weak)) #endif /* __weak */ diff --git a/targets/TARGET_STM/TARGET_STM32F3/device/stm32f3xx_hal_pcd.h b/targets/TARGET_STM/TARGET_STM32F3/device/stm32f3xx_hal_pcd.h index 624dc3bd9bd..afc7234c16c 100644 --- a/targets/TARGET_STM/TARGET_STM32F3/device/stm32f3xx_hal_pcd.h +++ b/targets/TARGET_STM/TARGET_STM32F3/device/stm32f3xx_hal_pcd.h @@ -232,7 +232,7 @@ typedef struct * @{ */ #define __HAL_PCD_GET_FLAG(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->ISTR) & (__INTERRUPT__)) == (__INTERRUPT__)) -#define __HAL_PCD_CLEAR_FLAG(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->ISTR) = (uint16_t)(~(__INTERRUPT__)))) // MBED fix +#define __HAL_PCD_CLEAR_FLAG(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->ISTR) &= (uint16_t)(~(__INTERRUPT__)))) #define __HAL_USB_WAKEUP_EXTI_ENABLE_IT() EXTI->IMR |= USB_WAKEUP_EXTI_LINE #define __HAL_USB_WAKEUP_EXTI_DISABLE_IT() EXTI->IMR &= ~(USB_WAKEUP_EXTI_LINE) @@ -622,9 +622,9 @@ PCD_StateTypeDef HAL_PCD_GetState(PCD_HandleTypeDef *hpcd); * @retval None */ #define PCD_CLEAR_RX_EP_CTR(USBx, bEpNum) (PCD_SET_ENDPOINT((USBx), (bEpNum),\ - ( PCD_GET_ENDPOINT((USBx), (bEpNum)) | USB_EP_CTR_TX ) & ~USB_EP_CTR_RX & USB_EPREG_MASK)) // MBED fix + PCD_GET_ENDPOINT((USBx), (bEpNum)) & 0x7FFFU & USB_EPREG_MASK)) #define PCD_CLEAR_TX_EP_CTR(USBx, bEpNum) (PCD_SET_ENDPOINT((USBx), (bEpNum),\ - ( PCD_GET_ENDPOINT((USBx), (bEpNum)) | USB_EP_CTR_RX ) & ~USB_EP_CTR_TX & USB_EPREG_MASK)) // MBED fix + PCD_GET_ENDPOINT((USBx), (bEpNum)) & 0xFF7FU & USB_EPREG_MASK)) /** * @brief Toggles DTOG_RX / DTOG_TX bit in the endpoint register. diff --git a/features/unsupported/USBDevice/USBDevice/TARGET_STM/TARGET_STM32F4/TARGET_STM32F401xE/TARGET_NUCLEO_F401RE/USBHAL_STM_TARGET.h b/targets/TARGET_STM/TARGET_STM32F4/TARGET_DISCO_F407VG/USBHAL_STM_TARGET.h similarity index 100% rename from features/unsupported/USBDevice/USBDevice/TARGET_STM/TARGET_STM32F4/TARGET_STM32F401xE/TARGET_NUCLEO_F401RE/USBHAL_STM_TARGET.h rename to targets/TARGET_STM/TARGET_STM32F4/TARGET_DISCO_F407VG/USBHAL_STM_TARGET.h diff --git a/features/unsupported/USBHost/USBHost/TARGET_STM/TARGET_STM32F4/TARGET_STM32F429xI/TARGET_DISCO_F429ZI/USBHALHost_DISCOF429ZI.h b/targets/TARGET_STM/TARGET_STM32F4/TARGET_DISCO_F429ZI/USBHALHost_DISCOF429ZI.h similarity index 100% rename from features/unsupported/USBHost/USBHost/TARGET_STM/TARGET_STM32F4/TARGET_STM32F429xI/TARGET_DISCO_F429ZI/USBHALHost_DISCOF429ZI.h rename to targets/TARGET_STM/TARGET_STM32F4/TARGET_DISCO_F429ZI/USBHALHost_DISCOF429ZI.h diff --git a/features/unsupported/USBHost/USBHost/TARGET_STM/TARGET_STM32F4/TARGET_STM32F429xI/TARGET_DISCO_F429ZI/USBHALHost_STM_TARGET.h b/targets/TARGET_STM/TARGET_STM32F4/TARGET_DISCO_F429ZI/USBHALHost_STM_TARGET.h similarity index 100% rename from features/unsupported/USBHost/USBHost/TARGET_STM/TARGET_STM32F4/TARGET_STM32F429xI/TARGET_DISCO_F429ZI/USBHALHost_STM_TARGET.h rename to targets/TARGET_STM/TARGET_STM32F4/TARGET_DISCO_F429ZI/USBHALHost_STM_TARGET.h diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_MTS_DRAGONFLY_F411RE/PeripheralPins.c b/targets/TARGET_STM/TARGET_STM32F4/TARGET_MTS_DRAGONFLY_F411RE/PeripheralPins.c index 7c2b21786f6..eba4a75b06e 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_MTS_DRAGONFLY_F411RE/PeripheralPins.c +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_MTS_DRAGONFLY_F411RE/PeripheralPins.c @@ -55,10 +55,6 @@ const PinMap PinMap_ADC[] = { {PC_3, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 13, 0)}, // ADC1_IN13 {PC_4, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 14, 0)}, // ADC1_IN14 {PC_5, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 15, 0)}, // ADC1_IN15 - {NC, NC, 0} -}; - -const PinMap PinMap_ADC_Internal[] = { {ADC_TEMP, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 16, 0)}, // See in analogin_api.c the correct ADC channel used {ADC_VREF, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 17, 0)}, // See in analogin_api.c the correct ADC channel used {ADC_VBAT, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 18, 0)}, // See in analogin_api.c the correct ADC channel used diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_MTS_MDOT_F405RG/PeripheralPins.c b/targets/TARGET_STM/TARGET_STM32F4/TARGET_MTS_MDOT_F405RG/PeripheralPins.c index 1d9adc364c0..716dee971ca 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_MTS_MDOT_F405RG/PeripheralPins.c +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_MTS_MDOT_F405RG/PeripheralPins.c @@ -55,10 +55,6 @@ const PinMap PinMap_ADC[] = { {PC_3, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 13, 0)}, // ADC1_IN13 {PC_4, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 14, 0)}, // ADC1_IN14 {PC_5, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 15, 0)}, // ADC1_IN15 - {NC, NC, 0} -}; - -const PinMap PinMap_ADC_Internal[] = { {ADC_TEMP, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 16, 0)}, // See in analogin_api.c the correct ADC channel used {ADC_VREF, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 17, 0)}, // See in analogin_api.c the correct ADC channel used {ADC_VBAT, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 18, 0)}, // See in analogin_api.c the correct ADC channel used diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_MTS_MDOT_F411RE/PeripheralPins.c b/targets/TARGET_STM/TARGET_STM32F4/TARGET_MTS_MDOT_F411RE/PeripheralPins.c index 1665328970f..a2f41b5a53d 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_MTS_MDOT_F411RE/PeripheralPins.c +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_MTS_MDOT_F411RE/PeripheralPins.c @@ -50,10 +50,6 @@ const PinMap PinMap_ADC[] = { {PB_0, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 8, 0)}, // ADC1_IN8 {PB_1, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 9, 0)}, // ADC1_IN9 {PC_1, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 11, 0)}, // ADC1_IN11 - {NC, NC, 0} -}; - -const PinMap PinMap_ADC_Internal[] = { {ADC_TEMP, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 16, 0)}, // See in analogin_api.c the correct ADC channel used {ADC_VREF, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 17, 0)}, // See in analogin_api.c the correct ADC channel used {ADC_VBAT, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 18, 0)}, // See in analogin_api.c the correct ADC channel used diff --git a/features/unsupported/USBHost/USBHost/TARGET_STM/TARGET_STM32F4/TARGET_STM32F401xE/TARGET_NUCLEO_F401RE/USBHALHost_STM_TARGET.h b/targets/TARGET_STM/TARGET_STM32F4/TARGET_NUCLEO_F401RE/USBHALHost_STM_TARGET.h similarity index 100% rename from features/unsupported/USBHost/USBHost/TARGET_STM/TARGET_STM32F4/TARGET_STM32F401xE/TARGET_NUCLEO_F401RE/USBHALHost_STM_TARGET.h rename to targets/TARGET_STM/TARGET_STM32F4/TARGET_NUCLEO_F401RE/USBHALHost_STM_TARGET.h diff --git a/features/unsupported/USBDevice/USBDevice/TARGET_STM/TARGET_STM32F4/TARGET_STM32F407xG/TARGET_DISCO_F407VG/USBHAL_STM_TARGET.h b/targets/TARGET_STM/TARGET_STM32F4/TARGET_NUCLEO_F401RE/USBHAL_STM_TARGET.h similarity index 100% rename from features/unsupported/USBDevice/USBDevice/TARGET_STM/TARGET_STM32F4/TARGET_STM32F407xG/TARGET_DISCO_F407VG/USBHAL_STM_TARGET.h rename to targets/TARGET_STM/TARGET_STM32F4/TARGET_NUCLEO_F401RE/USBHAL_STM_TARGET.h diff --git a/features/unsupported/USBHost/USBHost/TARGET_STM/TARGET_STM32F4/TARGET_STM32F411xE/TARGET_NUCLEO_F411RE/USBHALHost_STM_TARGET.h b/targets/TARGET_STM/TARGET_STM32F4/TARGET_NUCLEO_F411RE/USBHALHost_STM_TARGET.h similarity index 100% rename from features/unsupported/USBHost/USBHost/TARGET_STM/TARGET_STM32F4/TARGET_STM32F411xE/TARGET_NUCLEO_F411RE/USBHALHost_STM_TARGET.h rename to targets/TARGET_STM/TARGET_STM32F4/TARGET_NUCLEO_F411RE/USBHALHost_STM_TARGET.h diff --git a/features/unsupported/USBDevice/USBDevice/TARGET_STM/TARGET_STM32F4/TARGET_STM32F411xE/TARGET_NUCLEO_F411RE/USBHAL_STM_TARGET.h b/targets/TARGET_STM/TARGET_STM32F4/TARGET_NUCLEO_F411RE/USBHAL_STM_TARGET.h similarity index 100% rename from features/unsupported/USBDevice/USBDevice/TARGET_STM/TARGET_STM32F4/TARGET_STM32F411xE/TARGET_NUCLEO_F411RE/USBHAL_STM_TARGET.h rename to targets/TARGET_STM/TARGET_STM32F4/TARGET_NUCLEO_F411RE/USBHAL_STM_TARGET.h diff --git a/features/unsupported/USBHost/USBHost/TARGET_STM/TARGET_STM32F4/TARGET_STM32F412xG/TARGET_NUCLEO_F412ZG/USBHALHost_STM_TARGET.h b/targets/TARGET_STM/TARGET_STM32F4/TARGET_NUCLEO_F412ZG/USBHALHost_STM_TARGET.h similarity index 100% rename from features/unsupported/USBHost/USBHost/TARGET_STM/TARGET_STM32F4/TARGET_STM32F412xG/TARGET_NUCLEO_F412ZG/USBHALHost_STM_TARGET.h rename to targets/TARGET_STM/TARGET_STM32F4/TARGET_NUCLEO_F412ZG/USBHALHost_STM_TARGET.h diff --git a/features/unsupported/USBDevice/USBDevice/TARGET_STM/TARGET_STM32F4/TARGET_STM32F412xG/TARGET_NUCLEO_F412ZG/USBHAL_STM_TARGET.h b/targets/TARGET_STM/TARGET_STM32F4/TARGET_NUCLEO_F412ZG/USBHAL_STM_TARGET.h similarity index 100% rename from features/unsupported/USBDevice/USBDevice/TARGET_STM/TARGET_STM32F4/TARGET_STM32F412xG/TARGET_NUCLEO_F412ZG/USBHAL_STM_TARGET.h rename to targets/TARGET_STM/TARGET_STM32F4/TARGET_NUCLEO_F412ZG/USBHAL_STM_TARGET.h diff --git a/features/unsupported/USBHost/USBHost/TARGET_STM/TARGET_STM32F4/TARGET_STM32F446xE/TARGET_NUCLEO_F446ZE/USBHALHost_STM_TARGET.h b/targets/TARGET_STM/TARGET_STM32F4/TARGET_NUCLEO_F446ZE/USBHALHost_STM_TARGET.h similarity index 100% rename from features/unsupported/USBHost/USBHost/TARGET_STM/TARGET_STM32F4/TARGET_STM32F446xE/TARGET_NUCLEO_F446ZE/USBHALHost_STM_TARGET.h rename to targets/TARGET_STM/TARGET_STM32F4/TARGET_NUCLEO_F446ZE/USBHALHost_STM_TARGET.h diff --git a/features/unsupported/USBDevice/USBDevice/TARGET_STM/TARGET_STM32F4/TARGET_STM32F429xI/TARGET_NUCLEO_F429ZI/USBHAL_STM_TARGET.h b/targets/TARGET_STM/TARGET_STM32F4/TARGET_NUCLEO_F446ZE/USBHAL_STM_TARGET.h similarity index 100% rename from features/unsupported/USBDevice/USBDevice/TARGET_STM/TARGET_STM32F4/TARGET_STM32F429xI/TARGET_NUCLEO_F429ZI/USBHAL_STM_TARGET.h rename to targets/TARGET_STM/TARGET_STM32F4/TARGET_NUCLEO_F446ZE/USBHAL_STM_TARGET.h diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F401xC/TARGET_DISCO_F401VC/PeripheralPins.c b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F401xC/TARGET_DISCO_F401VC/PeripheralPins.c index 560c62f8b46..d90ece65c16 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F401xC/TARGET_DISCO_F401VC/PeripheralPins.c +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F401xC/TARGET_DISCO_F401VC/PeripheralPins.c @@ -55,10 +55,6 @@ const PinMap PinMap_ADC[] = { {PC_3, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 13, 0)}, // ADC1_IN13 {PC_4, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 14, 0)}, // ADC1_IN14 {PC_5, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 15, 0)}, // ADC1_IN15 - {NC, NC, 0} -}; - -const PinMap PinMap_ADC_Internal[] = { {ADC_TEMP, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 16, 0)}, // See in analogin_api.c the correct ADC channel used {ADC_VREF, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 17, 0)}, // See in analogin_api.c the correct ADC channel used {ADC_VBAT, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 18, 0)}, // See in analogin_api.c the correct ADC channel used diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F401xC/TARGET_DISCO_F401VC/PinNames.h b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F401xC/TARGET_DISCO_F401VC/PinNames.h index e0387d2d82b..ed0b6786d6b 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F401xC/TARGET_DISCO_F401VC/PinNames.h +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F401xC/TARGET_DISCO_F401VC/PinNames.h @@ -120,8 +120,6 @@ typedef enum { LED4 = PD_15, LED_RED = LED1, USER_BUTTON = PA_0, - // Standardized button names - BUTTON1 = USER_BUTTON, SERIAL_TX = PA_2, SERIAL_RX = PA_3, USBTX = PA_2, diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F401xE/TARGET_NUCLEO_F401RE/PeripheralPins.c b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F401xE/TARGET_NUCLEO_F401RE/PeripheralPins.c index f25904562ca..74a04dc5c8c 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F401xE/TARGET_NUCLEO_F401RE/PeripheralPins.c +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F401xE/TARGET_NUCLEO_F401RE/PeripheralPins.c @@ -41,8 +41,8 @@ const PinMap PinMap_ADC[] = { {PA_0, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 0, 0)}, // ADC1_IN0 {PA_1, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 1, 0)}, // ADC1_IN1 -// {PA_2, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 2, 0)}, // ADC1_IN2 // SERIAL_TX -// {PA_3, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 3, 0)}, // ADC1_IN3 // SERIAL_RX + {PA_2, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 2, 0)}, // ADC1_IN2 + {PA_3, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 3, 0)}, // ADC1_IN3 {PA_4, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 4, 0)}, // ADC1_IN4 {PA_5, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 5, 0)}, // ADC1_IN5 {PA_6, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 6, 0)}, // ADC1_IN6 @@ -55,10 +55,6 @@ const PinMap PinMap_ADC[] = { {PC_3, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 13, 0)}, // ADC1_IN13 {PC_4, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 14, 0)}, // ADC1_IN14 {PC_5, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 15, 0)}, // ADC1_IN15 - {NC, NC, 0} -}; - -const PinMap PinMap_ADC_Internal[] = { {ADC_TEMP, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 16, 0)}, // See in analogin_api.c the correct ADC channel used {ADC_VREF, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 17, 0)}, // See in analogin_api.c the correct ADC channel used {ADC_VBAT, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 18, 0)}, // See in analogin_api.c the correct ADC channel used @@ -92,12 +88,12 @@ const PinMap PinMap_PWM[] = { // {PA_0, PWM_5, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM5, 1, 0)}, // TIM5_CH1 {PA_1, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 2, 0)}, // TIM2_CH2 // {PA_1, PWM_5, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM5, 2, 0)}, // TIM5_CH2 -// {PA_2, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 3, 0)}, // TIM2_CH3 // SERIAL_TX -// {PA_2, PWM_5, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM5, 3, 0)}, // TIM5_CH3 // SERIAL_TX -// {PA_2, PWM_9, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM9, 1, 0)}, // TIM9_CH1 // SERIAL_TX -// {PA_3, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 4, 0)}, // TIM2_CH4 // SERIAL_RX -// {PA_3, PWM_5, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM5, 4, 0)}, // TIM5_CH4 // SERIAL_RX -// {PA_3, PWM_9, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM9, 2, 0)}, // TIM9_CH2 // SERIAL_RX + {PA_2, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 3, 0)}, // TIM2_CH3 +// {PA_2, PWM_5, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM5, 3, 0)}, // TIM5_CH3 +// {PA_2, PWM_9, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM9, 1, 0)}, // TIM9_CH1 + {PA_3, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 4, 0)}, // TIM2_CH4 +// {PA_3, PWM_5, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM5, 4, 0)}, // TIM5_CH4 +// {PA_3, PWM_9, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM9, 2, 0)}, // TIM9_CH2 {PA_5, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 1, 0)}, // TIM2_CH1 {PA_6, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 1, 0)}, // TIM3_CH1 {PA_7, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 1, 1)}, // TIM1_CH1N - ARDUINO @@ -137,7 +133,7 @@ const PinMap PinMap_PWM[] = { //*** SERIAL *** const PinMap PinMap_UART_TX[] = { - {PA_2, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART2)}, // SERIAL_TX + {PA_2, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART2)}, {PA_9, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)}, {PA_11, UART_6, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_USART6)}, {PB_6, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)}, @@ -146,7 +142,7 @@ const PinMap PinMap_UART_TX[] = { }; const PinMap PinMap_UART_RX[] = { - {PA_3, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART2)}, // SERIAL_RX + {PA_3, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART2)}, {PA_10, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)}, {PA_12, UART_6, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_USART6)}, {PB_7, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)}, diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F401xE/TARGET_NUCLEO_F401RE/PinNames.h b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F401xE/TARGET_NUCLEO_F401RE/PinNames.h index 2a52e564564..e590f38f4bf 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F401xE/TARGET_NUCLEO_F401RE/PinNames.h +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F401xE/TARGET_NUCLEO_F401RE/PinNames.h @@ -129,8 +129,6 @@ typedef enum { LED4 = PA_5, LED_RED = LED1, USER_BUTTON = PC_13, - // Standardized button names - BUTTON1 = USER_BUTTON, SERIAL_TX = PA_2, SERIAL_RX = PA_3, USBTX = PA_2, diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F407xG/TARGET_ARCH_MAX/PeripheralPins.c b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F407xG/TARGET_ARCH_MAX/PeripheralPins.c index b0784180914..0257dbe1bee 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F407xG/TARGET_ARCH_MAX/PeripheralPins.c +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F407xG/TARGET_ARCH_MAX/PeripheralPins.c @@ -58,10 +58,6 @@ const PinMap PinMap_ADC[] = { {NC, NC, 0} }; -const PinMap PinMap_ADC_Internal[] = { - {NC, NC, 0} -}; - //*** DAC *** diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F407xG/TARGET_DISCO_F407VG/PeripheralPins.c b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F407xG/TARGET_DISCO_F407VG/PeripheralPins.c index 2b0f94469c4..c318000f344 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F407xG/TARGET_DISCO_F407VG/PeripheralPins.c +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F407xG/TARGET_DISCO_F407VG/PeripheralPins.c @@ -55,10 +55,6 @@ const PinMap PinMap_ADC[] = { {PC_3, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 13, 0)}, // ADC1_IN13 {PC_4, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 14, 0)}, // ADC1_IN14 {PC_5, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 15, 0)}, // ADC1_IN15 - {NC, NC, 0} -}; - -const PinMap PinMap_ADC_Internal[] = { {ADC_TEMP, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 16, 0)}, // See in analogin_api.c the correct ADC channel used {ADC_VREF, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 17, 0)}, // See in analogin_api.c the correct ADC channel used {ADC_VBAT, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 18, 0)}, // See in analogin_api.c the correct ADC channel used diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F407xG/TARGET_DISCO_F407VG/PinNames.h b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F407xG/TARGET_DISCO_F407VG/PinNames.h index bdddafbb16e..eadabe008dc 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F407xG/TARGET_DISCO_F407VG/PinNames.h +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F407xG/TARGET_DISCO_F407VG/PinNames.h @@ -205,8 +205,6 @@ typedef enum { LED6 = PD_15, LED_RED = LED1, USER_BUTTON = PA_0, - // Standardized button names - BUTTON1 = USER_BUTTON, SERIAL_TX = PA_2, /* USART2 */ SERIAL_RX = PA_3, USBTX = PA_2, /* USART2 */ diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F410xB/TARGET_NUCLEO_F410RB/PeripheralPins.c b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F410xB/TARGET_NUCLEO_F410RB/PeripheralPins.c index fa43ad0108a..07b4d11de60 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F410xB/TARGET_NUCLEO_F410RB/PeripheralPins.c +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F410xB/TARGET_NUCLEO_F410RB/PeripheralPins.c @@ -41,8 +41,8 @@ const PinMap PinMap_ADC[] = { {PA_0, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 0, 0)}, // ADC1_IN0 {PA_1, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 1, 0)}, // ADC1_IN1 -// {PA_2, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 2, 0)}, // ADC1_IN2 // SERIAL_TX -// {PA_3, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 3, 0)}, // ADC1_IN3 // SERIAL_RX + {PA_2, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 2, 0)}, // ADC1_IN2 + {PA_3, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 3, 0)}, // ADC1_IN3 {PA_4, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 4, 0)}, // ADC1_IN4 {PA_5, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 5, 0)}, // ADC1_IN5 {PA_6, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 6, 0)}, // ADC1_IN6 @@ -55,10 +55,6 @@ const PinMap PinMap_ADC[] = { {PC_3, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 13, 0)}, // ADC1_IN13 {PC_4, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 14, 0)}, // ADC1_IN14 {PC_5, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 15, 0)}, // ADC1_IN15 - {NC, NC, 0} -}; - -const PinMap PinMap_ADC_Internal[] = { {ADC_TEMP, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 16, 0)}, // See in analogin_api.c the correct ADC channel used {ADC_VREF, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 17, 0)}, // See in analogin_api.c the correct ADC channel used {ADC_VBAT, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 18, 0)}, // See in analogin_api.c the correct ADC channel used diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F410xB/TARGET_NUCLEO_F410RB/PinNames.h b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F410xB/TARGET_NUCLEO_F410RB/PinNames.h index da18af25922..39ff33b7277 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F410xB/TARGET_NUCLEO_F410RB/PinNames.h +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F410xB/TARGET_NUCLEO_F410RB/PinNames.h @@ -129,8 +129,6 @@ typedef enum { LED4 = PA_5, LED_RED = LED1, USER_BUTTON = PC_13, - // Standardized button names - BUTTON1 = USER_BUTTON, SERIAL_TX = PA_2, SERIAL_RX = PA_3, USBTX = PA_2, diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F411xE/TARGET_ELMO_F411RE/PeripheralPins.c b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F411xE/TARGET_ELMO_F411RE/PeripheralPins.c index 6bf66904cfc..f8f4654c527 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F411xE/TARGET_ELMO_F411RE/PeripheralPins.c +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F411xE/TARGET_ELMO_F411RE/PeripheralPins.c @@ -55,10 +55,6 @@ const PinMap PinMap_ADC[] = { {PC_3, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 13, 0)}, // ADC1_IN13 {PC_4, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 14, 0)}, // ADC1_IN14 {PC_5, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 15, 0)}, // ADC1_IN15 - {NC, NC, 0} -}; - -const PinMap PinMap_ADC_Internal[] = { {ADC_TEMP, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 16, 0)}, // See in analogin_api.c the correct ADC channel used {ADC_VREF, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 17, 0)}, // See in analogin_api.c the correct ADC channel used {ADC_VBAT, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 18, 0)}, // See in analogin_api.c the correct ADC channel used diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F411xE/TARGET_ELMO_F411RE/PinNames.h b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F411xE/TARGET_ELMO_F411RE/PinNames.h index 0b7c41698d3..be2de24b4ed 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F411xE/TARGET_ELMO_F411RE/PinNames.h +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F411xE/TARGET_ELMO_F411RE/PinNames.h @@ -131,8 +131,6 @@ typedef enum { LED3 = PB_0, LED4 = PB_1, USER_BUTTON = PB_7, - // Standardized button names - BUTTON1 = USER_BUTTON, SERIAL_TX = PA_9, SERIAL_RX = PA_10, USBTX = PA_9, diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F411xE/TARGET_NUCLEO_F411RE/PeripheralPins.c b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F411xE/TARGET_NUCLEO_F411RE/PeripheralPins.c index ab69388be67..0a4fd7d9cd8 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F411xE/TARGET_NUCLEO_F411RE/PeripheralPins.c +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F411xE/TARGET_NUCLEO_F411RE/PeripheralPins.c @@ -41,8 +41,8 @@ const PinMap PinMap_ADC[] = { {PA_0, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 0, 0)}, // ADC1_IN0 {PA_1, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 1, 0)}, // ADC1_IN1 -// {PA_2, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 2, 0)}, // ADC1_IN2 // SERIAL_TX -// {PA_3, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 3, 0)}, // ADC1_IN3 // SERIAL_RX + {PA_2, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 2, 0)}, // ADC1_IN2 + {PA_3, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 3, 0)}, // ADC1_IN3 {PA_4, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 4, 0)}, // ADC1_IN4 {PA_5, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 5, 0)}, // ADC1_IN5 {PA_6, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 6, 0)}, // ADC1_IN6 @@ -55,10 +55,6 @@ const PinMap PinMap_ADC[] = { {PC_3, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 13, 0)}, // ADC1_IN13 {PC_4, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 14, 0)}, // ADC1_IN14 {PC_5, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 15, 0)}, // ADC1_IN15 - {NC, NC, 0} -}; - -const PinMap PinMap_ADC_Internal[] = { {ADC_TEMP, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 16, 0)}, // See in analogin_api.c the correct ADC channel used {ADC_VREF, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 17, 0)}, // See in analogin_api.c the correct ADC channel used {ADC_VBAT, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 18, 0)}, // See in analogin_api.c the correct ADC channel used @@ -94,12 +90,12 @@ const PinMap PinMap_PWM[] = { // {PA_0, PWM_5, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM5, 1, 0)}, // TIM5_CH1 {PA_1, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 2, 0)}, // TIM2_CH2 // {PA_1, PWM_5, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM5, 2, 0)}, // TIM5_CH2 -// {PA_2, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 3, 0)}, // TIM2_CH3 // SERIAL_TX -// {PA_2, PWM_5, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM5, 3, 0)}, // TIM5_CH3 // SERIAL_TX -// {PA_2, PWM_9, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM9, 1, 0)}, // TIM9_CH1 // SERIAL_TX -// {PA_3, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 4, 0)}, // TIM2_CH4 // SERIAL_RX -// {PA_3, PWM_5, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM5, 4, 0)}, // TIM5_CH4 // SERIAL_RX -// {PA_3, PWM_9, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM9, 2, 0)}, // TIM9_CH2 // SERIAL_RX + {PA_2, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 3, 0)}, // TIM2_CH3 +// {PA_2, PWM_5, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM5, 3, 0)}, // TIM5_CH3 +// {PA_2, PWM_9, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM9, 1, 0)}, // TIM9_CH1 + {PA_3, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 4, 0)}, // TIM2_CH4 +// {PA_3, PWM_5, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM5, 4, 0)}, // TIM5_CH4 +// {PA_3, PWM_9, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM9, 2, 0)}, // TIM9_CH2 {PA_5, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 1, 0)}, // TIM2_CH1 {PA_6, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 1, 0)}, // TIM3_CH1 {PA_7, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 1, 1)}, // TIM1_CH1N - ARDUINO @@ -139,7 +135,7 @@ const PinMap PinMap_PWM[] = { //*** SERIAL *** const PinMap PinMap_UART_TX[] = { - {PA_2, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART2)}, // SERIAL_TX + {PA_2, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART2)}, {PA_9, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)}, {PA_11, UART_6, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_USART6)}, {PA_15, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)}, @@ -149,7 +145,7 @@ const PinMap PinMap_UART_TX[] = { }; const PinMap PinMap_UART_RX[] = { - {PA_3, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART2)}, // SERIAL_RX + {PA_3, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART2)}, {PA_10, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)}, {PA_12, UART_6, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_USART6)}, {PB_3, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)}, diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F411xE/TARGET_NUCLEO_F411RE/PinNames.h b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F411xE/TARGET_NUCLEO_F411RE/PinNames.h index 2a52e564564..e590f38f4bf 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F411xE/TARGET_NUCLEO_F411RE/PinNames.h +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F411xE/TARGET_NUCLEO_F411RE/PinNames.h @@ -129,8 +129,6 @@ typedef enum { LED4 = PA_5, LED_RED = LED1, USER_BUTTON = PC_13, - // Standardized button names - BUTTON1 = USER_BUTTON, SERIAL_TX = PA_2, SERIAL_RX = PA_3, USBTX = PA_2, diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F412xG/TARGET_NUCLEO_F412ZG/PeripheralPins.c b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F412xG/TARGET_NUCLEO_F412ZG/PeripheralPins.c index ad824e64986..43b507903b6 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F412xG/TARGET_NUCLEO_F412ZG/PeripheralPins.c +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F412xG/TARGET_NUCLEO_F412ZG/PeripheralPins.c @@ -40,10 +40,6 @@ const PinMap PinMap_ADC[] = { {PC_3, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 13, 0)}, // ADC1_IN13 - A2 {PC_4, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 14, 0)}, // ADC1_IN14 - A4 {PC_5, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 15, 0)}, // ADC1_IN15 - A5 - {NC, NC, 0} -}; - -const PinMap PinMap_ADC_Internal[] = { {ADC_TEMP, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 16, 0)}, // See in analogin_api.c the correct ADC channel used {ADC_VREF, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 17, 0)}, // See in analogin_api.c the correct ADC channel used {ADC_VBAT, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 18, 0)}, // See in analogin_api.c the correct ADC channel used diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F412xG/TARGET_NUCLEO_F412ZG/PinNames.h b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F412xG/TARGET_NUCLEO_F412ZG/PinNames.h index b82cadd19fa..be56a9d8ac6 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F412xG/TARGET_NUCLEO_F412ZG/PinNames.h +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F412xG/TARGET_NUCLEO_F412ZG/PinNames.h @@ -182,8 +182,6 @@ typedef enum { LED4 = LED1, LED_RED = LED1, USER_BUTTON = PC_13, - // Standardized button names - BUTTON1 = USER_BUTTON, SERIAL_TX = PD_8, SERIAL_RX = PD_9, USBTX = SERIAL_TX, diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F412xG/device/TOOLCHAIN_IAR/stm32f412xx.icf b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F412xG/device/TOOLCHAIN_IAR/stm32f412xx.icf index 279400bbe62..2e52e63ce61 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F412xG/device/TOOLCHAIN_IAR/stm32f412xx.icf +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F412xG/device/TOOLCHAIN_IAR/stm32f412xx.icf @@ -15,6 +15,7 @@ define region ROM_region = mem:[from __region_ROM_start__ to __region_ROM_end__] define region RAM_region = mem:[from __region_RAM_start__ to __region_RAM_end__]; /* Stack and Heap */ +/*Heap 1/4 of ram and stack 1/8*/ define symbol __size_cstack__ = 0x8000; define symbol __size_heap__ = 0x10000; define block CSTACK with alignment = 8, size = __size_cstack__ { }; diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F429xI/TARGET_DISCO_F429ZI/PeripheralPins.c b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F429xI/TARGET_DISCO_F429ZI/PeripheralPins.c index d45c6910076..e1c994d360f 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F429xI/TARGET_DISCO_F429ZI/PeripheralPins.c +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F429xI/TARGET_DISCO_F429ZI/PeripheralPins.c @@ -63,10 +63,6 @@ const PinMap PinMap_ADC[] = { {PF_8, ADC_3, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 6, 0)}, // ADC3_IN6 {PF_9, ADC_3, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 7, 0)}, // ADC3_IN7 {PF_10,ADC_3, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 8, 0)}, // ADC3_IN8 - {NC, NC, 0} -}; - -const PinMap PinMap_ADC_Internal[] = { {ADC_TEMP, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 16, 0)}, // See in analogin_api.c the correct ADC channel used {ADC_VREF, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 17, 0)}, // See in analogin_api.c the correct ADC channel used {ADC_VBAT, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 18, 0)}, // See in analogin_api.c the correct ADC channel used diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F429xI/TARGET_DISCO_F429ZI/PinNames.h b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F429xI/TARGET_DISCO_F429ZI/PinNames.h index 200360cc92c..a63a20d1051 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F429xI/TARGET_DISCO_F429ZI/PinNames.h +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F429xI/TARGET_DISCO_F429ZI/PinNames.h @@ -172,8 +172,6 @@ typedef enum { LED4 = PG_14, LED_RED = LED2, USER_BUTTON = PA_0, - // Standardized button names - BUTTON1 = USER_BUTTON, SERIAL_TX = PA_9, SERIAL_RX = PA_10, USBTX = PA_9, diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F429xI/TARGET_NUCLEO_F429ZI/PeripheralPins.c b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F429xI/TARGET_NUCLEO_F429ZI/PeripheralPins.c index 615052deff4..1193246c416 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F429xI/TARGET_NUCLEO_F429ZI/PeripheralPins.c +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F429xI/TARGET_NUCLEO_F429ZI/PeripheralPins.c @@ -57,8 +57,8 @@ const PinMap PinMap_ADC[] = { // {PA_5, ADC_2, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 5, 0)}, // ADC2_IN5 - ARDUINO D13 {PA_6, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 6, 0)}, // ADC1_IN6 - ARDUINO D12 // {PA_6, ADC_2, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 6, 0)}, // ADC2_IN6 - ARDUINO D12 -// {PA_7, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 7, 0)}, // ADC1_IN7 (pin used by ethernet when JP6 ON) - ARDUINO D11 (default configuration) - {PA_7, ADC_2, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 7, 0)}, // ADC2_IN7 (pin used by ethernet when JP6 ON) - ARDUINO D11 (default configuration) +// {PA_7, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 7, 0)}, // ADC1_IN7 (pin used by ethernet when JP6 ON) - ARDUINO D11 + {PA_7, ADC_2, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 7, 0)}, // ADC2_IN7 (pin used by ethernet when JP6 ON) - ARDUINO D11 // {PB_0, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 8, 0)}, // ADC1_IN8 (pin used by LED1) // {PB_0, ADC_2, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 8, 0)}, // ADC2_IN8 (pin used by LED1) {PB_1, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 9, 0)}, // ADC1_IN9 @@ -87,10 +87,6 @@ const PinMap PinMap_ADC[] = { {PF_8, ADC_3, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 6, 0)}, // ADC3_IN6 {PF_9, ADC_3, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 7, 0)}, // ADC3_IN7 {PF_10, ADC_3, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 8, 0)}, // ADC3_IN8 - ARDUINO A5 - {NC, NC, 0} -}; - -const PinMap PinMap_ADC_Internal[] = { {ADC_TEMP, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 16, 0)}, // See in analogin_api.c the correct ADC channel used {ADC_VREF, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 17, 0)}, // See in analogin_api.c the correct ADC channel used {ADC_VBAT, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 18, 0)}, // See in analogin_api.c the correct ADC channel used @@ -140,12 +136,12 @@ const PinMap PinMap_PWM[] = { // {PA_3, PWM_9, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM9, 2, 0)}, // TIM9_CH2 - ARDUINO A0 // {PA_5, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 1, 0)}, // TIM2_CH1 - ARDUINO D13 {PA_5, PWM_8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 1, 1)}, // TIM8_CH1N - ARDUINO D13 -// {PA_6, PWM_13, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF9_TIM13, 1, 0)}, // TIM13_CH1 - ARDUINO D12 +// {PA_6, PWM_13, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF9_TIM13, 1, 0)}, // TIM13_CH1 - ARDUINO D12 {PA_6, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 1, 0)}, // TIM3_CH1 - ARDUINO D12 - {PA_7, PWM_14, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF9_TIM14, 1, 0)}, // TIM14_CH1 (pin used by ethernet when JP6 ON) - ARDUINO D11 (default configuration) -// {PA_7, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 1, 1)}, // TIM1_CH1N (pin used by ethernet when JP6 ON) - ARDUINO D11 (default configuration) -// {PA_7, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 2, 0)}, // TIM3_CH2 (pin used by ethernet when JP6 ON) - ARDUINO D11 (default configuration) -// {PA_7, PWM_8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 1, 1)}, // TIM8_CH1N (pin used by ethernet when JP6 ON) - ARDUINO D11 (default configuration) + {PA_7, PWM_14, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF9_TIM14, 1, 0)}, // TIM14_CH1 (pin used by ethernet when JP6 ON) - ARDUINO D11 +// {PA_7, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 1, 1)}, // TIM1_CH1N (pin used by ethernet when JP6 ON) - ARDUINO D11 +// {PA_7, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 2, 0)}, // TIM3_CH2 (pin used by ethernet when JP6 ON) - ARDUINO D11 +// {PA_7, PWM_8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 1, 1)}, // TIM8_CH1N (pin used by ethernet when JP6 ON) - ARDUINO D11 {PA_8, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 1, 0)}, // TIM1_CH1 // {PA_9, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 2, 0)}, // TIM1_CH2 (pin used by usb) // {PA_10, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 3, 0)}, // TIM1_CH3 (pin used by usb) @@ -159,9 +155,7 @@ const PinMap PinMap_PWM[] = { {PB_1, PWM_8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 3, 1)}, // TIM8_CH3N {PB_3, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 2, 0)}, // TIM2_CH2 {PB_4, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 1, 0)}, // TIM3_CH1 - {PB_5, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 2, 0)}, // TIM3_CH2 - ARDUINO D11 (need HW and SW updates) - // HW solder bridge update : SB121 off, SB122 on - // SW : config from json files + {PB_5, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 2, 0)}, // TIM3_CH2 {PB_6, PWM_4, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM4, 1, 0)}, // TIM4_CH1 // {PB_7, PWM_4, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM4, 2, 0)}, // TIM4_CH2 (pin used by LED2) // {PB_8, PWM_10, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM10, 1, 0)}, // TIM10_CH1 - ARDUINO D15 @@ -270,10 +264,8 @@ const PinMap PinMap_UART_CTS[] = { //*** SPI *** const PinMap PinMap_SPI_MOSI[] = { - {PA_7, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI1)}, // pin used by ethernet when JP6 ON - ARDUINO D11 (default configuration) - {PB_5, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI1)}, // ARDUINO D11 (need HW and SW updates) - // HW solder bridge update : SB121 off, SB122 on - // SW : config from json files + {PA_7, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI1)}, // (pin used by ethernet when JP6 ON) - ARDUINO D11 + {PB_5, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI1)}, // {PB_5, SPI_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_SPI3)}, {PB_15, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI2)}, {PC_3, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI2)}, // ARDUINO A2 @@ -334,9 +326,7 @@ const PinMap PinMap_CAN_RD[] = { {PB_8, CAN_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF9_CAN1)}, {PB_12, CAN_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF9_CAN2)}, {PD_0, CAN_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF9_CAN1)}, - {PB_5 , CAN_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF9_CAN2)}, // ARDUINO D11 (need HW and SW updates) - // HW solder bridge update : SB121 off, SB122 on - // SW : config from json files + {PB_5 , CAN_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF9_CAN2)}, {PA_11, CAN_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF9_CAN1)}, {NC, NC, 0} }; diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F429xI/TARGET_NUCLEO_F429ZI/PinNames.h b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F429xI/TARGET_NUCLEO_F429ZI/PinNames.h index 85cb275a6fe..302c59e62ae 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F429xI/TARGET_NUCLEO_F429ZI/PinNames.h +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F429xI/TARGET_NUCLEO_F429ZI/PinNames.h @@ -183,7 +183,7 @@ typedef enum { D8 = PF_12, D9 = PD_15, D10 = PD_14, - D11 = STM32_D11_SPI_ETHERNET_PIN, /* config in targets.json file */ + D11 = PA_7, D12 = PA_6, D13 = PA_5, D14 = PB_9, @@ -196,8 +196,6 @@ typedef enum { LED4 = PB_0, LED_RED = LED2, USER_BUTTON = PC_13, - // Standardized button names - BUTTON1 = USER_BUTTON, SERIAL_TX = PD_8, // Virtual Com Port SERIAL_RX = PD_9, // Virtual Com Port USBTX = PD_8, // Virtual Com Port diff --git a/features/unsupported/USBHost/USBHost/TARGET_STM/TARGET_STM32F4/TARGET_STM32F429xI/TARGET_NUCLEO_F429ZI/USBHALHost_STM_TARGET.h b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F429xI/TARGET_NUCLEO_F429ZI/USBHALHost_STM_TARGET.h similarity index 100% rename from features/unsupported/USBHost/USBHost/TARGET_STM/TARGET_STM32F4/TARGET_STM32F429xI/TARGET_NUCLEO_F429ZI/USBHALHost_STM_TARGET.h rename to targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F429xI/TARGET_NUCLEO_F429ZI/USBHALHost_STM_TARGET.h diff --git a/features/unsupported/USBDevice/USBDevice/TARGET_STM/TARGET_STM32F4/TARGET_STM32F439xI/TARGET_NUCLEO_F439ZI/USBHAL_STM_TARGET.h b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F429xI/TARGET_NUCLEO_F429ZI/USBHAL_STM_TARGET.h similarity index 100% rename from features/unsupported/USBDevice/USBDevice/TARGET_STM/TARGET_STM32F4/TARGET_STM32F439xI/TARGET_NUCLEO_F439ZI/USBHAL_STM_TARGET.h rename to targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F429xI/TARGET_NUCLEO_F429ZI/USBHAL_STM_TARGET.h diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F429xI/device/TOOLCHAIN_IAR/stm32f429xx_flash.icf b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F429xI/device/TOOLCHAIN_IAR/stm32f429xx_flash.icf index 8dcb1a8fea4..94c7d061c01 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F429xI/device/TOOLCHAIN_IAR/stm32f429xx_flash.icf +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F429xI/device/TOOLCHAIN_IAR/stm32f429xx_flash.icf @@ -15,8 +15,8 @@ define symbol __ICFEDIT_region_RAM_end__ = 0x2002FFFF; define symbol __ICFEDIT_region_CCMRAM_start__ = 0x10000000; define symbol __ICFEDIT_region_CCMRAM_end__ = 0x1000FFFF; /*-Sizes-*/ -/*Heap 64K and stack 4K */ -define symbol __ICFEDIT_size_cstack__ = 0x1000; +/*Heap 64K and stack 24K */ +define symbol __ICFEDIT_size_cstack__ = 0x6000; define symbol __ICFEDIT_size_heap__ = 0x10000; /**** End of ICF editor section. ###ICF###*/ diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F429xI/device/flash_api.c b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F429xI/device/flash_api.c index af039e70b9b..584c0ea9890 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F429xI/device/flash_api.c +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F429xI/device/flash_api.c @@ -16,9 +16,9 @@ #include "flash_api.h" #include "flash_data.h" -#include "platform/mbed_critical.h" +#include "mbed_critical.h" -// This file is automatically generated +// This file is automagically generated #if DEVICE_FLASH diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/TARGET_UBLOX_C030/PeripheralNames.h b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/TARGET_UBLOX_C030/PeripheralNames.h deleted file mode 100644 index e818a08f300..00000000000 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/TARGET_UBLOX_C030/PeripheralNames.h +++ /dev/null @@ -1,104 +0,0 @@ -/* mbed Microcontroller Library - ******************************************************************************* - * Copyright (c) 2015, STMicroelectronics - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************* - */ -#ifndef MBED_PERIPHERALNAMES_H -#define MBED_PERIPHERALNAMES_H - -#include "cmsis.h" - -#ifdef __cplusplus -extern "C" { -#endif - -typedef enum { - ADC_1 = (int)ADC1_BASE, - ADC_2 = (int) ADC2_BASE, - ADC_3 = (int) ADC3_BASE -} ADCName; - - -typedef enum { - UART_1 = (int)USART1_BASE, - UART_2 = (int)USART2_BASE, - UART_3 = (int)USART3_BASE, - UART_4 = (int)UART4_BASE, - UART_5 = (int)UART5_BASE, - UART_6 = (int)USART6_BASE, - UART_7 = (int)UART7_BASE, - UART_8 = (int)UART8_BASE -} UARTName; - -#define STDIO_UART_TX PA_9 -#define STDIO_UART_RX PA_10 -#define STDIO_UART UART_1 - -typedef enum { - SPI_1 = (int)SPI1_BASE, - SPI_2 = (int)SPI2_BASE, - SPI_3 = (int)SPI3_BASE, - SPI_4 = (int)SPI4_BASE, - SPI_5 = (int)SPI5_BASE, - SPI_6 = (int)SPI6_BASE -} SPIName; - -typedef enum { - I2C_1 = (int)I2C1_BASE, - I2C_2 = (int)I2C2_BASE, - I2C_3 = (int)I2C3_BASE -} I2CName; - -typedef enum { - PWM_1 = (int)TIM1_BASE, - PWM_2 = (int)TIM2_BASE, - PWM_3 = (int)TIM3_BASE, - PWM_4 = (int)TIM4_BASE, - PWM_5 = (int)TIM5_BASE, - PWM_8 = (int)TIM8_BASE, - PWM_9 = (int)TIM9_BASE, - PWM_10 = (int)TIM10_BASE, - PWM_11 = (int)TIM11_BASE, - PWM_12 = (int)TIM12_BASE, - PWM_13 = (int)TIM13_BASE, - PWM_14 = (int)TIM14_BASE -} PWMName; - -typedef enum { - DAC_1 = (int)DAC_BASE -} DACName; - -typedef enum { - CAN_1 = (int)CAN1_BASE, - CAN_2 = (int)CAN2_BASE -} CANName; - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/TARGET_UBLOX_C030/PeripheralPins.c b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/TARGET_UBLOX_C030/PeripheralPins.c deleted file mode 100644 index 2c29059293d..00000000000 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/TARGET_UBLOX_C030/PeripheralPins.c +++ /dev/null @@ -1,124 +0,0 @@ -/* mbed Microcontroller Library - ******************************************************************************* - * Copyright (c) 2014, STMicroelectronics - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************* - */ - -#include "PeripheralPins.h" -// ===== -// Note: Commented lines are alternative possibilities which are not used per default. -// If you change them, you will have also to modify the corresponding xxx_api.c file -// for pwmout, analogin, analogout, ... -// ===== - -//*** ADC *** - -const PinMap PinMap_ADC[] = { - {PA_3, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 3, 0)}, // ADC1_IN3 - {PA_4, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 4, 0)}, // ADC1_IN4 - {PA_6, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 6, 0)}, // ADC1_IN6 - {PB_0, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 8, 0)}, // ADC1_IN8 - {PC_0, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 10, 0)}, // ADC1_IN10 - {PC_3, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 13, 0)}, // ADC1_IN13 - {NC, NC, 0} -}; - -const PinMap PinMap_ADC_Internal[] = { - {NC, NC, 0} -}; - -//*** I2C *** - - -const PinMap PinMap_I2C_SDA[] = { - {PB_7, I2C_1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C1)}, - {PC_9, I2C_3, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C3)}, - {NC, NC, 0} -}; - -const PinMap PinMap_I2C_SCL[] = { - {PB_6, I2C_1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C1)}, - {PA_8, I2C_3, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C3)}, - {NC, NC, 0} -}; - -const PinMap PinMap_DAC[] = { - {PA_5, DAC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 2, 0)}, // DAC_OUT2 - ARDUINO D13 - {NC, NC, 0} -}; - -//*** PWM *** - -const PinMap PinMap_PWM[] = { - {PE_13, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 3, 0)}, // TIM1_CH3 - {PE_9, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 1, 0)}, // TIM1_CH1N - {PB_1, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 4, 0)}, // TIM3_CH4 - {PD_12, PWM_4, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM4, 1, 0)}, // TIM4_CH1 - {PB_8, PWM_10, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM10, 1, 0)}, // TIM10_CH1 - {PB_15, PWM_12, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF9_TIM12, 2, 0)}, // TIM12_CH2 - {NC, NC, 0} -}; - -//*** SERIAL *** - -const PinMap PinMap_UART_TX[] = { - {PA_9, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)}, - {PD_5, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART2)}, - {PD_9, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)}, - {PC_6, UART_6, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_USART6)}, - {NC, NC, 0} -}; - -const PinMap PinMap_UART_RX[] = { - {PA_10, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)}, - {PD_6, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART2)}, - {PD_8, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)}, - {PC_7, UART_6, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_USART6)}, - {NC, NC, 0} -}; - -//*** SPI *** - -const PinMap PinMap_SPI_MOSI[] = { - {PE_6, SPI_4, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI4)}, - {NC, NC, 0} -}; - -const PinMap PinMap_SPI_MISO[] = { - {PE_5, SPI_4, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI4)}, - {NC, NC, 0} -}; - -const PinMap PinMap_SPI_SCLK[] = { - {PE_2, SPI_4, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI4)}, - {NC, NC, 0} -}; - -const PinMap PinMap_SPI_SSEL[] = { - {PE_11, SPI_4, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI4)}, - {NC, NC, 0} -}; diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/TARGET_UBLOX_C030/PinNames.h b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/TARGET_UBLOX_C030/PinNames.h deleted file mode 100644 index b2e1d86f000..00000000000 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/TARGET_UBLOX_C030/PinNames.h +++ /dev/null @@ -1,144 +0,0 @@ -/* mbed Microcontroller Library - ******************************************************************************* - * Copyright (c) 2014, STMicroelectronics - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************* - */ -#ifndef MBED_PINNAMES_H -#define MBED_PINNAMES_H - -#include "cmsis.h" -#include "PinNamesTypes.h" - -#ifdef __cplusplus -extern "C" { -#endif - -typedef enum { - PA_0 = 0x00, PA_1 = 0x01, PA_2 = 0x02, PA_3 = 0x03, - PA_4 = 0x04, PA_5 = 0x05, PA_6 = 0x06, PA_7 = 0x07, - PA_8 = 0x08, PA_9 = 0x09, PA_10 = 0x0A, PA_11 = 0x0B, - PA_12 = 0x0C, PA_13 = 0x0D, PA_14 = 0x0E, PA_15 = 0x0F, - - PB_0 = 0x10, PB_1 = 0x11, PB_2 = 0x12, PB_3 = 0x13, - PB_4 = 0x14, PB_5 = 0x15, PB_6 = 0x16, PB_7 = 0x17, - PB_8 = 0x18, PB_9 = 0x19, PB_10 = 0x1A, PB_11 = 0x1B, - PB_12 = 0x1C, PB_13 = 0x1D, PB_14 = 0x1E, PB_15 = 0x1F, - - PC_0 = 0x20, PC_1 = 0x21, PC_2 = 0x22, PC_3 = 0x23, - PC_4 = 0x24, PC_5 = 0x25, PC_6 = 0x26, PC_7 = 0x27, - PC_8 = 0x28, PC_9 = 0x29, PC_10 = 0x2A, PC_11 = 0x2B, - PC_12 = 0x2C, PC_13 = 0x2D, PC_14 = 0x2E, PC_15 = 0x2F, - - PD_0 = 0x30, PD_1 = 0x31, PD_2 = 0x32, PD_3 = 0x33, - PD_4 = 0x34, PD_5 = 0x35, PD_6 = 0x36, PD_7 = 0x37, - PD_8 = 0x38, PD_9 = 0x39, PD_10 = 0x3A, PD_11 = 0x3B, - PD_12 = 0x3C, PD_13 = 0x3D, PD_14 = 0x3E, PD_15 = 0x3F, - - PE_0 = 0x40, PE_1 = 0x41, PE_2 = 0x42, PE_3 = 0x43, - PE_4 = 0x44, PE_5 = 0x45, PE_6 = 0x46, PE_7 = 0x47, - PE_8 = 0x48, PE_9 = 0x49, PE_10 = 0x4A, PE_11 = 0x4B, - PE_12 = 0x4C, PE_13 = 0x4D, PE_14 = 0x4E, PE_15 = 0x4F, - - - PH_0 = 0x70, PH_1 = 0x71, - - // Not connected - NC = -1, - - GNSSTXD = PC_6, - GNSSRXD = PC_7, - // Control - GNSSRST = PC_10, // Reset (input to GPS, active low) - GNSSPWR = PE_0, // 2.8V rail, should be set to open drain output - GNSSEN = PA_15, // VCC_IO to GNSS, should be set to push-pull, no pull-up, output - // u-blox LISA/SARA cellular modem - // http://www.u-blox.com/wireless-modules.html - // ----------------------------------------------------------- - // UART (LISA/SARA = DCE) - MDMTXD = PD_5, // Transmit Data - MDMRXD = PD_6, // Receive Data - MDMCTS = PD_3, // Clear to Send - MDMRTS = PD_4, // Request to Send (set high or use handshake) - MDMDCD = NC, // DCD line not connecetd - - // USB - // Control - MDMEN = PC_2, // Supply Control (high = enabled) - MDMPWRON = PE_14, // - MDMGPIO2 = PD_1, // - MDMGPIO3 = PB_4, // - MDMRST = PB_5, // Reset (active low, set as open drain!) - - // Board Pins - // A0-A5 - A0 = PA_3, - A1 = PC_0, - A2 = PC_3, - A3 = PA_4, - A4 = PA_6, - A5 = PB_0, - // D0-D15 - D0 = PD_9, // UART3-RX - D1 = PD_8, // UART3-TX - D2 = PD_11, // UART3-CTS - D3 = PB_14, // UART3-RTS - D4 = PB_1, - D5 = PA_5, - D6 = PB_8, // UART3-CTS - D7 = PB_15, // UART3-RTS - D8 = PD_15, // UART1-TX - D9 = PD_12, // SDCard-CS - D10 = PE_11, // SSEL - D11 = PE_6, // MOSI - D12 = PE_5, // MISO - D13 = PE_2, // SCK - D14 = PB_7, // SDA - D15 = PB_6, // SCL - // Internal - LED1 = PE_3, // Red / Mode - LED2 = PE_4, // Green / Switch-1 - LED3 = PE_1, // Blue - LED4 = PE_7, // A definition is required by the mbed platform RTC test code, this is the Ethernet connector yellow LED - LED_RED = LED1, - SW0 = PC_13, // Switch-0 - - // ST-Link - USBRX = PA_10, - USBTX = PA_9, - SWDIO = PA_13, - SWCLK = PA_14, - NTRST = PB_4, -} PinName; - -#define GNSSBAUD 9600 // Default GNSS Baud Rate -#define MDMBAUD 115200 // Default Modem Baud Rate - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/TARGET_UBLOX_C030/system_stm32f4xx.c b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/TARGET_UBLOX_C030/system_stm32f4xx.c deleted file mode 100644 index 92c80d9f5ad..00000000000 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/TARGET_UBLOX_C030/system_stm32f4xx.c +++ /dev/null @@ -1,880 +0,0 @@ -/** - ****************************************************************************** - * @file system_stm32f4xx.c - * @author MCD Application Team - * @version V2.5.0 - * @date 22-April-2016 - * @brief CMSIS Cortex-M4 Device Peripheral Access Layer System Source File. - * - * This file provides two functions and one global variable to be called from - * user application: - * - SystemInit(): This function is called at startup just after reset and - * before branch to main program. This call is made inside - * the "startup_stm32f4xx.s" file. - * - * - SystemCoreClock variable: Contains the core clock (HCLK), it can be used - * by the user application to setup the SysTick - * timer or configure other parameters. - * - * - SystemCoreClockUpdate(): Updates the variable SystemCoreClock and must - * be called whenever the core clock is changed - * during program execution. - * - * This file configures the system clock as follows: - *---------------------------------------------------------------------------------------------------------------------------------------- - * System clock source | PLL_HSE_XTAL | PLL_HSE_XTAL | PLL_HSE_XTAL | PLL_HSE_XTAL - * | (external 8 MHz clock) | (external 8 MHz clock) | (external 12 MHz clock)| (external 12 MHz clock) - *---------------------------------------------------------------------------------------------------------------------------------------- - * SYSCLK(MHz) | 168 | 84 | 168 | 84 - *---------------------------------------------------------------------------------------------------------------------------------------- - * AHBCLK (MHz) | 168 | 84 | 168 | 84 - *---------------------------------------------------------------------------------------------------------------------------------------- - * APB1CLK (MHz) | 42 | 42 | 42 | 42 - *---------------------------------------------------------------------------------------------------------------------------------------- - * APB2CLK (MHz) | 84 | 84 | 84 | 84 - *---------------------------------------------------------------------------------------------------------------------------------------- - * USB capable (48 MHz precise clock) | YES | YES | YES | YES - *---------------------------------------------------------------------------------------------------------------------------------------- - ****************************************************************************** - * @attention - * - *

© COPYRIGHT 2016 STMicroelectronics

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ - -/** @addtogroup CMSIS - * @{ - */ - -/** @addtogroup stm32f4xx_system - * @{ - */ - -/** @addtogroup STM32F4xx_System_Private_Includes - * @{ - */ - - -#include "stm32f4xx.h" -#include "hal_tick.h" - -#if !defined (HSE_VALUE) - #define HSE_VALUE ((uint32_t)8000000) /*!< Default value of the External oscillator in Hz */ -#endif /* HSE_VALUE */ - -#if !defined (HSI_VALUE) - #define HSI_VALUE ((uint32_t)16000000) /*!< Value of the Internal oscillator in Hz*/ -#endif /* HSI_VALUE */ - -/** - * @} - */ - -/** @addtogroup STM32F4xx_System_Private_TypesDefinitions - * @{ - */ - -/** - * @} - */ - -/** @addtogroup STM32F4xx_System_Private_Defines - * @{ - */ - -/************************* Miscellaneous Configuration ************************/ -/*!< Uncomment the following line if you need to use external SRAM or SDRAM as data memory */ -#if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx)\ - || defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx)\ - || defined(STM32F469xx) || defined(STM32F479xx) || defined(STM32F412Zx) || defined(STM32F412Vx) -/* #define DATA_IN_ExtSRAM */ -#endif /* STM32F40xxx || STM32F41xxx || STM32F42xxx || STM32F43xxx || STM32F469xx || STM32F479xx ||\ - STM32F412Zx || STM32F412Vx */ - -#if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx)\ - || defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) -/* #define DATA_IN_ExtSDRAM */ -#endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx ||\ - STM32F479xx */ - -/*!< Uncomment the following line if you need to relocate your vector Table in - Internal SRAM. */ -/* #define VECT_TAB_SRAM */ -#define VECT_TAB_OFFSET 0x00 /*!< Vector Table base offset field. - This value must be a multiple of 0x200. */ -/******************************************************************************/ - -/** - * @} - */ - -/** @addtogroup STM32F4xx_System_Private_Macros - * @{ - */ - -/* Select the SYSCLOCK to start with (0=OFF, 1=ON) */ -#define USE_SYSCLOCK_168 (1) /* Use external 8MHz or 12 MHz xtal and sets SYSCLK to 168MHz */ -#define USE_SYSCLOCK_84 (0) /* Use external 8MHz or 12 MHz xtal and sets SYSCLK to 84MHz */ - -/** - * @} - */ - -/** @addtogroup STM32F4xx_System_Private_Variables - * @{ - */ - /* This variable is updated in three ways: - 1) by calling CMSIS function SystemCoreClockUpdate() - 2) by calling HAL API function HAL_RCC_GetHCLKFreq() - 3) each time HAL_RCC_ClockConfig() is called to configure the system clock frequency - Note: If you use this function to configure the system clock; then there - is no need to call the 2 first functions listed above, since SystemCoreClock - variable is updated automatically. - */ - uint32_t SystemCoreClock = 168000000; -const uint8_t AHBPrescTable[16] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 7, 8, 9}; - -/** - * @} - */ - -/** @addtogroup STM32F4xx_System_Private_FunctionPrototypes - * @{ - */ - -#if defined (DATA_IN_ExtSRAM) || defined (DATA_IN_ExtSDRAM) - static void SystemInit_ExtMemCtl(void); -#endif /* DATA_IN_ExtSRAM || DATA_IN_ExtSDRAM */ - -void SetSysClock(void); -/** - * @} - */ - -/** @addtogroup STM32F4xx_System_Private_Functions - * @{ - */ - -/** - * @brief Setup the microcontroller system - * Initialize the FPU setting, vector table location and External memory - * configuration. - * @param None - * @retval None - */ -void SystemInit(void) -{ - /* FPU settings ------------------------------------------------------------*/ - #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) - SCB->CPACR |= ((3UL << 10*2)|(3UL << 11*2)); /* set CP10 and CP11 Full Access */ - #endif - /* Reset the RCC clock configuration to the default reset state ------------*/ - /* Set HSION bit */ - RCC->CR |= (uint32_t)0x00000001; - - /* Reset CFGR register */ - RCC->CFGR = 0x00000000; - - /* Reset HSEON, CSSON and PLLON bits */ - RCC->CR &= (uint32_t)0xFEF6FFFF; - - /* Reset PLLCFGR register */ - RCC->PLLCFGR = 0x24003010; - - /* Reset HSEBYP bit */ - RCC->CR &= (uint32_t)0xFFFBFFFF; - - /* Disable all interrupts */ - RCC->CIR = 0x00000000; - -#if defined (DATA_IN_ExtSRAM) || defined (DATA_IN_ExtSDRAM) - SystemInit_ExtMemCtl(); -#endif /* DATA_IN_ExtSRAM || DATA_IN_ExtSDRAM */ - - /* Configure the Vector Table location add offset address ------------------*/ -#ifdef VECT_TAB_SRAM - SCB->VTOR = SRAM_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal SRAM */ -#else - SCB->VTOR = FLASH_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal FLASH */ -#endif - - /* Configure the Cube driver */ - SystemCoreClock = 16000000; // At this stage the HSI is used as system clock - HAL_Init(); - - /* Configure the System clock source, PLL Multiplier and Divider factors, - AHB/APBx prescalers and Flash settings */ - SetSysClock(); - SystemCoreClockUpdate(); - - /* Reset the timer to avoid issues after the RAM initialization */ - TIM_MST_RESET_ON; - TIM_MST_RESET_OFF; -} - -/** - * @brief Update SystemCoreClock variable according to Clock Register Values. - * The SystemCoreClock variable contains the core clock (HCLK), it can - * be used by the user application to setup the SysTick timer or configure - * other parameters. - * - * @note Each time the core clock (HCLK) changes, this function must be called - * to update SystemCoreClock variable value. Otherwise, any configuration - * based on this variable will be incorrect. - * - * @note - The system frequency computed by this function is not the real - * frequency in the chip. It is calculated based on the predefined - * constant and the selected clock source: - * - * - If SYSCLK source is HSI, SystemCoreClock will contain the HSI_VALUE(*) - * - * - If SYSCLK source is HSE, SystemCoreClock will contain the HSE_VALUE(**) - * - * - If SYSCLK source is PLL, SystemCoreClock will contain the HSE_VALUE(**) - * or HSI_VALUE(*) multiplied/divided by the PLL factors. - * - * (*) HSI_VALUE is a constant defined in stm32f4xx_hal_conf.h file (default value - * 16 MHz) but the real value may vary depending on the variations - * in voltage and temperature. - * - * (**) HSE_VALUE is a constant defined in stm32f4xx_hal_conf.h file (its value - * depends on the application requirements), user has to ensure that HSE_VALUE - * is same as the real frequency of the crystal used. Otherwise, this function - * may have wrong result. - * - * - The result of this function could be not correct when using fractional - * value for HSE crystal. - * - * @param None - * @retval None - */ -void SystemCoreClockUpdate(void) -{ - uint32_t tmp = 0, pllvco = 0, pllp = 2, pllsource = 0, pllm = 2; - - /* Get SYSCLK source -------------------------------------------------------*/ - tmp = RCC->CFGR & RCC_CFGR_SWS; - - switch (tmp) - { - case 0x00: /* HSI used as system clock source */ - SystemCoreClock = HSI_VALUE; - break; - case 0x04: /* HSE used as system clock source */ - SystemCoreClock = HSE_VALUE; - break; - case 0x08: /* PLL used as system clock source */ - - /* PLL_VCO = (HSE_VALUE or HSI_VALUE / PLL_M) * PLL_N - SYSCLK = PLL_VCO / PLL_P - */ - pllsource = (RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) >> 22; - pllm = RCC->PLLCFGR & RCC_PLLCFGR_PLLM; - - if (pllsource != 0) - { - /* HSE used as PLL clock source */ - pllvco = (HSE_VALUE / pllm) * ((RCC->PLLCFGR & RCC_PLLCFGR_PLLN) >> 6); - } - else - { - /* HSI used as PLL clock source */ - pllvco = (HSI_VALUE / pllm) * ((RCC->PLLCFGR & RCC_PLLCFGR_PLLN) >> 6); - } - - pllp = (((RCC->PLLCFGR & RCC_PLLCFGR_PLLP) >>16) + 1 ) *2; - SystemCoreClock = pllvco/pllp; - break; - default: - SystemCoreClock = HSI_VALUE; - break; - } - /* Compute HCLK frequency --------------------------------------------------*/ - /* Get HCLK prescaler */ - tmp = AHBPrescTable[((RCC->CFGR & RCC_CFGR_HPRE) >> 4)]; - /* HCLK frequency */ - SystemCoreClock >>= tmp; -} - -#if defined (DATA_IN_ExtSRAM) && defined (DATA_IN_ExtSDRAM) -#if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ - defined(STM32F469xx) || defined(STM32F479xx) -/** - * @brief Setup the external memory controller. - * Called in startup_stm32f4xx.s before jump to main. - * This function configures the external memories (SRAM/SDRAM) - * This SRAM/SDRAM will be used as program data memory (including heap and stack). - * @param None - * @retval None - */ -void SystemInit_ExtMemCtl(void) -{ - __IO uint32_t tmp = 0x00; - - register uint32_t tmpreg = 0, timeout = 0xFFFF; - register __IO uint32_t index; - - /* Enable GPIOC, GPIOD, GPIOE, GPIOF, GPIOG, GPIOH and GPIOI interface clock */ - RCC->AHB1ENR |= 0x000001F8; - - /* Delay after an RCC peripheral clock enabling */ - tmp = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOCEN); - - /* Connect PDx pins to FMC Alternate function */ - GPIOD->AFR[0] = 0x00CCC0CC; - GPIOD->AFR[1] = 0xCCCCCCCC; - /* Configure PDx pins in Alternate function mode */ - GPIOD->MODER = 0xAAAA0A8A; - /* Configure PDx pins speed to 100 MHz */ - GPIOD->OSPEEDR = 0xFFFF0FCF; - /* Configure PDx pins Output type to push-pull */ - GPIOD->OTYPER = 0x00000000; - /* No pull-up, pull-down for PDx pins */ - GPIOD->PUPDR = 0x00000000; - - /* Connect PEx pins to FMC Alternate function */ - GPIOE->AFR[0] = 0xC00CC0CC; - GPIOE->AFR[1] = 0xCCCCCCCC; - /* Configure PEx pins in Alternate function mode */ - GPIOE->MODER = 0xAAAA828A; - /* Configure PEx pins speed to 100 MHz */ - GPIOE->OSPEEDR = 0xFFFFC3CF; - /* Configure PEx pins Output type to push-pull */ - GPIOE->OTYPER = 0x00000000; - /* No pull-up, pull-down for PEx pins */ - GPIOE->PUPDR = 0x00000000; - - /* Connect PFx pins to FMC Alternate function */ - GPIOF->AFR[0] = 0xCCCCCCCC; - GPIOF->AFR[1] = 0xCCCCCCCC; - /* Configure PFx pins in Alternate function mode */ - GPIOF->MODER = 0xAA800AAA; - /* Configure PFx pins speed to 50 MHz */ - GPIOF->OSPEEDR = 0xAA800AAA; - /* Configure PFx pins Output type to push-pull */ - GPIOF->OTYPER = 0x00000000; - /* No pull-up, pull-down for PFx pins */ - GPIOF->PUPDR = 0x00000000; - - /* Connect PGx pins to FMC Alternate function */ - GPIOG->AFR[0] = 0xCCCCCCCC; - GPIOG->AFR[1] = 0xCCCCCCCC; - /* Configure PGx pins in Alternate function mode */ - GPIOG->MODER = 0xAAAAAAAA; - /* Configure PGx pins speed to 50 MHz */ - GPIOG->OSPEEDR = 0xAAAAAAAA; - /* Configure PGx pins Output type to push-pull */ - GPIOG->OTYPER = 0x00000000; - /* No pull-up, pull-down for PGx pins */ - GPIOG->PUPDR = 0x00000000; - - /* Connect PHx pins to FMC Alternate function */ - GPIOH->AFR[0] = 0x00C0CC00; - GPIOH->AFR[1] = 0xCCCCCCCC; - /* Configure PHx pins in Alternate function mode */ - GPIOH->MODER = 0xAAAA08A0; - /* Configure PHx pins speed to 50 MHz */ - GPIOH->OSPEEDR = 0xAAAA08A0; - /* Configure PHx pins Output type to push-pull */ - GPIOH->OTYPER = 0x00000000; - /* No pull-up, pull-down for PHx pins */ - GPIOH->PUPDR = 0x00000000; - - /* Connect PIx pins to FMC Alternate function */ - GPIOI->AFR[0] = 0xCCCCCCCC; - GPIOI->AFR[1] = 0x00000CC0; - /* Configure PIx pins in Alternate function mode */ - GPIOI->MODER = 0x0028AAAA; - /* Configure PIx pins speed to 50 MHz */ - GPIOI->OSPEEDR = 0x0028AAAA; - /* Configure PIx pins Output type to push-pull */ - GPIOI->OTYPER = 0x00000000; - /* No pull-up, pull-down for PIx pins */ - GPIOI->PUPDR = 0x00000000; - -/*-- FMC Configuration -------------------------------------------------------*/ - /* Enable the FMC interface clock */ - RCC->AHB3ENR |= 0x00000001; - /* Delay after an RCC peripheral clock enabling */ - tmp = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FMCEN); - - FMC_Bank5_6->SDCR[0] = 0x000019E4; - FMC_Bank5_6->SDTR[0] = 0x01115351; - - /* SDRAM initialization sequence */ - /* Clock enable command */ - FMC_Bank5_6->SDCMR = 0x00000011; - tmpreg = FMC_Bank5_6->SDSR & 0x00000020; - while((tmpreg != 0) && (timeout-- > 0)) - { - tmpreg = FMC_Bank5_6->SDSR & 0x00000020; - } - - /* Delay */ - for (index = 0; index<1000; index++); - - /* PALL command */ - FMC_Bank5_6->SDCMR = 0x00000012; - timeout = 0xFFFF; - while((tmpreg != 0) && (timeout-- > 0)) - { - tmpreg = FMC_Bank5_6->SDSR & 0x00000020; - } - - /* Auto refresh command */ - FMC_Bank5_6->SDCMR = 0x00000073; - timeout = 0xFFFF; - while((tmpreg != 0) && (timeout-- > 0)) - { - tmpreg = FMC_Bank5_6->SDSR & 0x00000020; - } - - /* MRD register program */ - FMC_Bank5_6->SDCMR = 0x00046014; - timeout = 0xFFFF; - while((tmpreg != 0) && (timeout-- > 0)) - { - tmpreg = FMC_Bank5_6->SDSR & 0x00000020; - } - - /* Set refresh count */ - tmpreg = FMC_Bank5_6->SDRTR; - FMC_Bank5_6->SDRTR = (tmpreg | (0x0000027C<<1)); - - /* Disable write protection */ - tmpreg = FMC_Bank5_6->SDCR[0]; - FMC_Bank5_6->SDCR[0] = (tmpreg & 0xFFFFFDFF); - -#if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) - /* Configure and enable Bank1_SRAM2 */ - FMC_Bank1->BTCR[2] = 0x00001011; - FMC_Bank1->BTCR[3] = 0x00000201; - FMC_Bank1E->BWTR[2] = 0x0fffffff; -#endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx */ -#if defined(STM32F469xx) || defined(STM32F479xx) - /* Configure and enable Bank1_SRAM2 */ - FMC_Bank1->BTCR[2] = 0x00001091; - FMC_Bank1->BTCR[3] = 0x00110212; - FMC_Bank1E->BWTR[2] = 0x0fffffff; -#endif /* STM32F469xx || STM32F479xx */ - - (void)(tmp); -} -#endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx */ -#elif defined (DATA_IN_ExtSRAM) || defined (DATA_IN_ExtSDRAM) -/** - * @brief Setup the external memory controller. - * Called in startup_stm32f4xx.s before jump to main. - * This function configures the external memories (SRAM/SDRAM) - * This SRAM/SDRAM will be used as program data memory (including heap and stack). - * @param None - * @retval None - */ -void SystemInit_ExtMemCtl(void) -{ - __IO uint32_t tmp = 0x00; -#if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx)\ - || defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) -#if defined (DATA_IN_ExtSDRAM) - register uint32_t tmpreg = 0, timeout = 0xFFFF; - register __IO uint32_t index; - -#if defined(STM32F446xx) - /* Enable GPIOA, GPIOC, GPIOD, GPIOE, GPIOF, GPIOG interface - clock */ - RCC->AHB1ENR |= 0x0000007D; -#else - /* Enable GPIOC, GPIOD, GPIOE, GPIOF, GPIOG, GPIOH and GPIOI interface - clock */ - RCC->AHB1ENR |= 0x000001F8; -#endif /* STM32F446xx */ - /* Delay after an RCC peripheral clock enabling */ - tmp = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOCEN); - -#if defined(STM32F446xx) - /* Connect PAx pins to FMC Alternate function */ - GPIOA->AFR[0] |= 0xC0000000; - GPIOA->AFR[1] |= 0x00000000; - /* Configure PDx pins in Alternate function mode */ - GPIOA->MODER |= 0x00008000; - /* Configure PDx pins speed to 50 MHz */ - GPIOA->OSPEEDR |= 0x00008000; - /* Configure PDx pins Output type to push-pull */ - GPIOA->OTYPER |= 0x00000000; - /* No pull-up, pull-down for PDx pins */ - GPIOA->PUPDR |= 0x00000000; - - /* Connect PCx pins to FMC Alternate function */ - GPIOC->AFR[0] |= 0x00CC0000; - GPIOC->AFR[1] |= 0x00000000; - /* Configure PDx pins in Alternate function mode */ - GPIOC->MODER |= 0x00000A00; - /* Configure PDx pins speed to 50 MHz */ - GPIOC->OSPEEDR |= 0x00000A00; - /* Configure PDx pins Output type to push-pull */ - GPIOC->OTYPER |= 0x00000000; - /* No pull-up, pull-down for PDx pins */ - GPIOC->PUPDR |= 0x00000000; -#endif /* STM32F446xx */ - - /* Connect PDx pins to FMC Alternate function */ - GPIOD->AFR[0] = 0x000000CC; - GPIOD->AFR[1] = 0xCC000CCC; - /* Configure PDx pins in Alternate function mode */ - GPIOD->MODER = 0xA02A000A; - /* Configure PDx pins speed to 50 MHz */ - GPIOD->OSPEEDR = 0xA02A000A; - /* Configure PDx pins Output type to push-pull */ - GPIOD->OTYPER = 0x00000000; - /* No pull-up, pull-down for PDx pins */ - GPIOD->PUPDR = 0x00000000; - - /* Connect PEx pins to FMC Alternate function */ - GPIOE->AFR[0] = 0xC00000CC; - GPIOE->AFR[1] = 0xCCCCCCCC; - /* Configure PEx pins in Alternate function mode */ - GPIOE->MODER = 0xAAAA800A; - /* Configure PEx pins speed to 50 MHz */ - GPIOE->OSPEEDR = 0xAAAA800A; - /* Configure PEx pins Output type to push-pull */ - GPIOE->OTYPER = 0x00000000; - /* No pull-up, pull-down for PEx pins */ - GPIOE->PUPDR = 0x00000000; - - /* Connect PFx pins to FMC Alternate function */ - GPIOF->AFR[0] = 0xCCCCCCCC; - GPIOF->AFR[1] = 0xCCCCCCCC; - /* Configure PFx pins in Alternate function mode */ - GPIOF->MODER = 0xAA800AAA; - /* Configure PFx pins speed to 50 MHz */ - GPIOF->OSPEEDR = 0xAA800AAA; - /* Configure PFx pins Output type to push-pull */ - GPIOF->OTYPER = 0x00000000; - /* No pull-up, pull-down for PFx pins */ - GPIOF->PUPDR = 0x00000000; - - /* Connect PGx pins to FMC Alternate function */ - GPIOG->AFR[0] = 0xCCCCCCCC; - GPIOG->AFR[1] = 0xCCCCCCCC; - /* Configure PGx pins in Alternate function mode */ - GPIOG->MODER = 0xAAAAAAAA; - /* Configure PGx pins speed to 50 MHz */ - GPIOG->OSPEEDR = 0xAAAAAAAA; - /* Configure PGx pins Output type to push-pull */ - GPIOG->OTYPER = 0x00000000; - /* No pull-up, pull-down for PGx pins */ - GPIOG->PUPDR = 0x00000000; - -#if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx)\ - || defined(STM32F469xx) || defined(STM32F479xx) - /* Connect PHx pins to FMC Alternate function */ - GPIOH->AFR[0] = 0x00C0CC00; - GPIOH->AFR[1] = 0xCCCCCCCC; - /* Configure PHx pins in Alternate function mode */ - GPIOH->MODER = 0xAAAA08A0; - /* Configure PHx pins speed to 50 MHz */ - GPIOH->OSPEEDR = 0xAAAA08A0; - /* Configure PHx pins Output type to push-pull */ - GPIOH->OTYPER = 0x00000000; - /* No pull-up, pull-down for PHx pins */ - GPIOH->PUPDR = 0x00000000; - - /* Connect PIx pins to FMC Alternate function */ - GPIOI->AFR[0] = 0xCCCCCCCC; - GPIOI->AFR[1] = 0x00000CC0; - /* Configure PIx pins in Alternate function mode */ - GPIOI->MODER = 0x0028AAAA; - /* Configure PIx pins speed to 50 MHz */ - GPIOI->OSPEEDR = 0x0028AAAA; - /* Configure PIx pins Output type to push-pull */ - GPIOI->OTYPER = 0x00000000; - /* No pull-up, pull-down for PIx pins */ - GPIOI->PUPDR = 0x00000000; -#endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx */ - -/*-- FMC Configuration -------------------------------------------------------*/ - /* Enable the FMC interface clock */ - RCC->AHB3ENR |= 0x00000001; - /* Delay after an RCC peripheral clock enabling */ - tmp = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FMCEN); - - /* Configure and enable SDRAM bank1 */ -#if defined(STM32F446xx) - FMC_Bank5_6->SDCR[0] = 0x00001954; -#else - FMC_Bank5_6->SDCR[0] = 0x000019E4; -#endif /* STM32F446xx */ - FMC_Bank5_6->SDTR[0] = 0x01115351; - - /* SDRAM initialization sequence */ - /* Clock enable command */ - FMC_Bank5_6->SDCMR = 0x00000011; - tmpreg = FMC_Bank5_6->SDSR & 0x00000020; - while((tmpreg != 0) && (timeout-- > 0)) - { - tmpreg = FMC_Bank5_6->SDSR & 0x00000020; - } - - /* Delay */ - for (index = 0; index<1000; index++); - - /* PALL command */ - FMC_Bank5_6->SDCMR = 0x00000012; - timeout = 0xFFFF; - while((tmpreg != 0) && (timeout-- > 0)) - { - tmpreg = FMC_Bank5_6->SDSR & 0x00000020; - } - - /* Auto refresh command */ -#if defined(STM32F446xx) - FMC_Bank5_6->SDCMR = 0x000000F3; -#else - FMC_Bank5_6->SDCMR = 0x00000073; -#endif /* STM32F446xx */ - timeout = 0xFFFF; - while((tmpreg != 0) && (timeout-- > 0)) - { - tmpreg = FMC_Bank5_6->SDSR & 0x00000020; - } - - /* MRD register program */ -#if defined(STM32F446xx) - FMC_Bank5_6->SDCMR = 0x00044014; -#else - FMC_Bank5_6->SDCMR = 0x00046014; -#endif /* STM32F446xx */ - timeout = 0xFFFF; - while((tmpreg != 0) && (timeout-- > 0)) - { - tmpreg = FMC_Bank5_6->SDSR & 0x00000020; - } - - /* Set refresh count */ - tmpreg = FMC_Bank5_6->SDRTR; -#if defined(STM32F446xx) - FMC_Bank5_6->SDRTR = (tmpreg | (0x0000050C<<1)); -#else - FMC_Bank5_6->SDRTR = (tmpreg | (0x0000027C<<1)); -#endif /* STM32F446xx */ - - /* Disable write protection */ - tmpreg = FMC_Bank5_6->SDCR[0]; - FMC_Bank5_6->SDCR[0] = (tmpreg & 0xFFFFFDFF); -#endif /* DATA_IN_ExtSDRAM */ -#endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx || STM32F479xx */ - -#if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx)\ - || defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx)\ - || defined(STM32F469xx) || defined(STM32F479xx) || defined(STM32F412Zx) || defined(STM32F412Vx) - -#if defined(DATA_IN_ExtSRAM) -/*-- GPIOs Configuration -----------------------------------------------------*/ - /* Enable GPIOD, GPIOE, GPIOF and GPIOG interface clock */ - RCC->AHB1ENR |= 0x00000078; - /* Delay after an RCC peripheral clock enabling */ - tmp = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIODEN); - - /* Connect PDx pins to FMC Alternate function */ - GPIOD->AFR[0] = 0x00CCC0CC; - GPIOD->AFR[1] = 0xCCCCCCCC; - /* Configure PDx pins in Alternate function mode */ - GPIOD->MODER = 0xAAAA0A8A; - /* Configure PDx pins speed to 100 MHz */ - GPIOD->OSPEEDR = 0xFFFF0FCF; - /* Configure PDx pins Output type to push-pull */ - GPIOD->OTYPER = 0x00000000; - /* No pull-up, pull-down for PDx pins */ - GPIOD->PUPDR = 0x00000000; - - /* Connect PEx pins to FMC Alternate function */ - GPIOE->AFR[0] = 0xC00CC0CC; - GPIOE->AFR[1] = 0xCCCCCCCC; - /* Configure PEx pins in Alternate function mode */ - GPIOE->MODER = 0xAAAA828A; - /* Configure PEx pins speed to 100 MHz */ - GPIOE->OSPEEDR = 0xFFFFC3CF; - /* Configure PEx pins Output type to push-pull */ - GPIOE->OTYPER = 0x00000000; - /* No pull-up, pull-down for PEx pins */ - GPIOE->PUPDR = 0x00000000; - - /* Connect PFx pins to FMC Alternate function */ - GPIOF->AFR[0] = 0x00CCCCCC; - GPIOF->AFR[1] = 0xCCCC0000; - /* Configure PFx pins in Alternate function mode */ - GPIOF->MODER = 0xAA000AAA; - /* Configure PFx pins speed to 100 MHz */ - GPIOF->OSPEEDR = 0xFF000FFF; - /* Configure PFx pins Output type to push-pull */ - GPIOF->OTYPER = 0x00000000; - /* No pull-up, pull-down for PFx pins */ - GPIOF->PUPDR = 0x00000000; - - /* Connect PGx pins to FMC Alternate function */ - GPIOG->AFR[0] = 0x00CCCCCC; - GPIOG->AFR[1] = 0x000000C0; - /* Configure PGx pins in Alternate function mode */ - GPIOG->MODER = 0x00085AAA; - /* Configure PGx pins speed to 100 MHz */ - GPIOG->OSPEEDR = 0x000CAFFF; - /* Configure PGx pins Output type to push-pull */ - GPIOG->OTYPER = 0x00000000; - /* No pull-up, pull-down for PGx pins */ - GPIOG->PUPDR = 0x00000000; - -/*-- FMC/FSMC Configuration --------------------------------------------------*/ - /* Enable the FMC/FSMC interface clock */ - RCC->AHB3ENR |= 0x00000001; - -#if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx)|| defined(STM32F439xx) - /* Configure and enable Bank1_SRAM2 */ - FMC_Bank1->BTCR[2] = 0x00001011; - FMC_Bank1->BTCR[3] = 0x00000201; - FMC_Bank1E->BWTR[2] = 0x0fffffff; -#endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx */ -#if defined(STM32F469xx) || defined(STM32F479xx) - /* Delay after an RCC peripheral clock enabling */ - tmp = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FMCEN); - /* Configure and enable Bank1_SRAM2 */ - FMC_Bank1->BTCR[2] = 0x00001091; - FMC_Bank1->BTCR[3] = 0x00110212; - FMC_Bank1E->BWTR[2] = 0x0fffffff; -#endif /* STM32F469xx || STM32F479xx */ -#if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx)|| defined(STM32F417xx)\ - || defined(STM32F412Zx) || defined(STM32F412Vx) - /* Delay after an RCC peripheral clock enabling */ - tmp = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FSMCEN); - /* Configure and enable Bank1_SRAM2 */ - FSMC_Bank1->BTCR[2] = 0x00001011; - FSMC_Bank1->BTCR[3] = 0x00000201; - FSMC_Bank1E->BWTR[2] = 0x0FFFFFFF; -#endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F412Zx || STM32F412Vx */ - -#endif /* DATA_IN_ExtSRAM */ -#endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx ||\ - STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx || STM32F412Zx || STM32F412Vx */ - (void)(tmp); -} -#endif /* DATA_IN_ExtSRAM && DATA_IN_ExtSDRAM */ - -/** System Clock Configuration -*/ -#if USE_SYSCLOCK_168 != 0 -/* - * Set SYSCLK=168MHZ - */ -void SetSysClock(void) -{ - - RCC_OscInitTypeDef RCC_OscInitStruct; - RCC_ClkInitTypeDef RCC_ClkInitStruct; - - __PWR_CLK_ENABLE(); - - __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1); - - RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE; - RCC_OscInitStruct.HSEState = RCC_HSE_ON; - RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; - RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; -#ifdef USE_DEBUG_8MHz_XTAL - RCC_OscInitStruct.PLL.PLLM = 8; -#else - RCC_OscInitStruct.PLL.PLLM = 12; -#endif - RCC_OscInitStruct.PLL.PLLN = 336; - RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2; - RCC_OscInitStruct.PLL.PLLQ = 7; - HAL_RCC_OscConfig(&RCC_OscInitStruct); - - RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_SYSCLK|RCC_CLOCKTYPE_PCLK1 - |RCC_CLOCKTYPE_PCLK2; - RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; - RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; - RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4; - RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2; - HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_5); - - // HAL_RCC_MCOConfig(RCC_MCO2, RCC_MCO2SOURCE_SYSCLK, RCC_MCODIV_3); - - -} - -#elif USE_SYSCLOCK_84 != 0 -/* -Set SYSCLK=84MHZ - */ -void SetSysClock(void) -{ - - RCC_OscInitTypeDef RCC_OscInitStruct; - RCC_ClkInitTypeDef RCC_ClkInitStruct; - - __PWR_CLK_ENABLE(); - - __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE3); - - RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE; - RCC_OscInitStruct.HSEState = RCC_HSE_ON; - RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; - RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; -#ifdef USE_DEBUG_8MHz_XTAL - RCC_OscInitStruct.PLL.PLLM = 8; -#else - RCC_OscInitStruct.PLL.PLLM = 12; -#endif - RCC_OscInitStruct.PLL.PLLN = 336; - RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV4; - RCC_OscInitStruct.PLL.PLLQ = 7; - HAL_RCC_OscConfig(&RCC_OscInitStruct); - - - RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_SYSCLK|RCC_CLOCKTYPE_PCLK1 - |RCC_CLOCKTYPE_PCLK2; - RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; - RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; - RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2; - RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; - HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2); - - // HAL_RCC_MCOConfig(RCC_MCO2, RCC_MCO2SOURCE_SYSCLK, RCC_MCODIV_3); - -} -#endif - -/** - * @} - */ - -/** - * @} - */ - -/** - * @} - */ -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ \ No newline at end of file diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/device/TOOLCHAIN_ARM_STD/startup_stm32f437xx.S b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/device/TOOLCHAIN_ARM_STD/startup_stm32f437xx.S deleted file mode 100644 index 934d3428f98..00000000000 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/device/TOOLCHAIN_ARM_STD/startup_stm32f437xx.S +++ /dev/null @@ -1,414 +0,0 @@ -;******************** (C) COPYRIGHT 2015 STMicroelectronics ******************** -;* File Name : startup_stm32f437xx.s -;* Author : MCD Application Team -;* Version : V2.4.0 -;* Date : 14-August-2015 -;* Description : STM32F437x devices vector table for MDK-ARM_STD toolchain. -;* This module performs: -;* - Set the initial SP -;* - Set the initial PC == Reset_Handler -;* - Set the vector table entries with the exceptions ISR address -;* - Branches to __main in the C library (which eventually -;* calls main()). -;* After Reset the CortexM4 processor is in Thread mode, -;* priority is Privileged, and the Stack is set to Main. -;* <<< Use Configuration Wizard in Context Menu >>> -;******************************************************************************* -; -;* Redistribution and use in source and binary forms, with or without modification, -;* are permitted provided that the following conditions are met: -;* 1. Redistributions of source code must retain the above copyright notice, -;* this list of conditions and the following disclaimer. -;* 2. Redistributions in binary form must reproduce the above copyright notice, -;* this list of conditions and the following disclaimer in the documentation -;* and/or other materials provided with the distribution. -;* 3. Neither the name of STMicroelectronics nor the names of its contributors -;* may be used to endorse or promote products derived from this software -;* without specific prior written permission. -;* -;* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -;* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -;* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -;* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -;* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -;* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -;* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -;* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -;* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -;* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -; -;******************************************************************************* - -__initial_sp EQU 0x20030000 ; Top of RAM - - PRESERVE8 - THUMB - - -; Vector Table Mapped to Address 0 at Reset - AREA RESET, DATA, READONLY - EXPORT __Vectors - EXPORT __Vectors_End - EXPORT __Vectors_Size - -__Vectors DCD __initial_sp ; Top of Stack - DCD Reset_Handler ; Reset Handler - DCD NMI_Handler ; NMI Handler - DCD HardFault_Handler ; Hard Fault Handler - DCD MemManage_Handler ; MPU Fault Handler - DCD BusFault_Handler ; Bus Fault Handler - DCD UsageFault_Handler ; Usage Fault Handler - DCD 0 ; Reserved - DCD 0 ; Reserved - DCD 0 ; Reserved - DCD 0 ; Reserved - DCD SVC_Handler ; SVCall Handler - DCD DebugMon_Handler ; Debug Monitor Handler - DCD 0 ; Reserved - DCD PendSV_Handler ; PendSV Handler - DCD SysTick_Handler ; SysTick Handler - - ; External Interrupts - DCD WWDG_IRQHandler ; Window WatchDog - DCD PVD_IRQHandler ; PVD through EXTI Line detection - DCD TAMP_STAMP_IRQHandler ; Tamper and TimeStamps through the EXTI line - DCD RTC_WKUP_IRQHandler ; RTC Wakeup through the EXTI line - DCD FLASH_IRQHandler ; FLASH - DCD RCC_IRQHandler ; RCC - DCD EXTI0_IRQHandler ; EXTI Line0 - DCD EXTI1_IRQHandler ; EXTI Line1 - DCD EXTI2_IRQHandler ; EXTI Line2 - DCD EXTI3_IRQHandler ; EXTI Line3 - DCD EXTI4_IRQHandler ; EXTI Line4 - DCD DMA1_Stream0_IRQHandler ; DMA1 Stream 0 - DCD DMA1_Stream1_IRQHandler ; DMA1 Stream 1 - DCD DMA1_Stream2_IRQHandler ; DMA1 Stream 2 - DCD DMA1_Stream3_IRQHandler ; DMA1 Stream 3 - DCD DMA1_Stream4_IRQHandler ; DMA1 Stream 4 - DCD DMA1_Stream5_IRQHandler ; DMA1 Stream 5 - DCD DMA1_Stream6_IRQHandler ; DMA1 Stream 6 - DCD ADC_IRQHandler ; ADC1, ADC2 and ADC3s - DCD CAN1_TX_IRQHandler ; CAN1 TX - DCD CAN1_RX0_IRQHandler ; CAN1 RX0 - DCD CAN1_RX1_IRQHandler ; CAN1 RX1 - DCD CAN1_SCE_IRQHandler ; CAN1 SCE - DCD EXTI9_5_IRQHandler ; External Line[9:5]s - DCD TIM1_BRK_TIM9_IRQHandler ; TIM1 Break and TIM9 - DCD TIM1_UP_TIM10_IRQHandler ; TIM1 Update and TIM10 - DCD TIM1_TRG_COM_TIM11_IRQHandler ; TIM1 Trigger and Commutation and TIM11 - DCD TIM1_CC_IRQHandler ; TIM1 Capture Compare - DCD TIM2_IRQHandler ; TIM2 - DCD TIM3_IRQHandler ; TIM3 - DCD TIM4_IRQHandler ; TIM4 - DCD I2C1_EV_IRQHandler ; I2C1 Event - DCD I2C1_ER_IRQHandler ; I2C1 Error - DCD I2C2_EV_IRQHandler ; I2C2 Event - DCD I2C2_ER_IRQHandler ; I2C2 Error - DCD SPI1_IRQHandler ; SPI1 - DCD SPI2_IRQHandler ; SPI2 - DCD USART1_IRQHandler ; USART1 - DCD USART2_IRQHandler ; USART2 - DCD USART3_IRQHandler ; USART3 - DCD EXTI15_10_IRQHandler ; External Line[15:10]s - DCD RTC_Alarm_IRQHandler ; RTC Alarm (A and B) through EXTI Line - DCD OTG_FS_WKUP_IRQHandler ; USB OTG FS Wakeup through EXTI line - DCD TIM8_BRK_TIM12_IRQHandler ; TIM8 Break and TIM12 - DCD TIM8_UP_TIM13_IRQHandler ; TIM8 Update and TIM13 - DCD TIM8_TRG_COM_TIM14_IRQHandler ; TIM8 Trigger and Commutation and TIM14 - DCD TIM8_CC_IRQHandler ; TIM8 Capture Compare - DCD DMA1_Stream7_IRQHandler ; DMA1 Stream7 - DCD FMC_IRQHandler ; FMC - DCD SDIO_IRQHandler ; SDIO - DCD TIM5_IRQHandler ; TIM5 - DCD SPI3_IRQHandler ; SPI3 - DCD UART4_IRQHandler ; UART4 - DCD UART5_IRQHandler ; UART5 - DCD TIM6_DAC_IRQHandler ; TIM6 and DAC1&2 underrun errors - DCD TIM7_IRQHandler ; TIM7 - DCD DMA2_Stream0_IRQHandler ; DMA2 Stream 0 - DCD DMA2_Stream1_IRQHandler ; DMA2 Stream 1 - DCD DMA2_Stream2_IRQHandler ; DMA2 Stream 2 - DCD DMA2_Stream3_IRQHandler ; DMA2 Stream 3 - DCD DMA2_Stream4_IRQHandler ; DMA2 Stream 4 - DCD ETH_IRQHandler ; Ethernet - DCD ETH_WKUP_IRQHandler ; Ethernet Wakeup through EXTI line - DCD CAN2_TX_IRQHandler ; CAN2 TX - DCD CAN2_RX0_IRQHandler ; CAN2 RX0 - DCD CAN2_RX1_IRQHandler ; CAN2 RX1 - DCD CAN2_SCE_IRQHandler ; CAN2 SCE - DCD OTG_FS_IRQHandler ; USB OTG FS - DCD DMA2_Stream5_IRQHandler ; DMA2 Stream 5 - DCD DMA2_Stream6_IRQHandler ; DMA2 Stream 6 - DCD DMA2_Stream7_IRQHandler ; DMA2 Stream 7 - DCD USART6_IRQHandler ; USART6 - DCD I2C3_EV_IRQHandler ; I2C3 event - DCD I2C3_ER_IRQHandler ; I2C3 error - DCD OTG_HS_EP1_OUT_IRQHandler ; USB OTG HS End Point 1 Out - DCD OTG_HS_EP1_IN_IRQHandler ; USB OTG HS End Point 1 In - DCD OTG_HS_WKUP_IRQHandler ; USB OTG HS Wakeup through EXTI - DCD OTG_HS_IRQHandler ; USB OTG HS - DCD DCMI_IRQHandler ; DCMI - DCD CRYP_IRQHandler ; CRYPTO - DCD HASH_RNG_IRQHandler ; Hash and Rng - DCD FPU_IRQHandler ; FPU - DCD UART7_IRQHandler ; UART7 - DCD UART8_IRQHandler ; UART8 - DCD SPI4_IRQHandler ; SPI4 - DCD SPI5_IRQHandler ; SPI5 - DCD SPI6_IRQHandler ; SPI6 - DCD SAI1_IRQHandler ; SAI1 - DCD 0 ; Reserved - DCD 0 ; Reserved - DCD DMA2D_IRQHandler ; DMA2D - -__Vectors_End - -__Vectors_Size EQU __Vectors_End - __Vectors - - AREA |.text|, CODE, READONLY - -; Reset handler -Reset_Handler PROC - EXPORT Reset_Handler [WEAK] - IMPORT SystemInit - IMPORT __main - - LDR R0, =SystemInit - BLX R0 - LDR R0, =__main - BX R0 - ENDP - -; Dummy Exception Handlers (infinite loops which can be modified) - -NMI_Handler PROC - EXPORT NMI_Handler [WEAK] - B . - ENDP -HardFault_Handler\ - PROC - EXPORT HardFault_Handler [WEAK] - B . - ENDP -MemManage_Handler\ - PROC - EXPORT MemManage_Handler [WEAK] - B . - ENDP -BusFault_Handler\ - PROC - EXPORT BusFault_Handler [WEAK] - B . - ENDP -UsageFault_Handler\ - PROC - EXPORT UsageFault_Handler [WEAK] - B . - ENDP -SVC_Handler PROC - EXPORT SVC_Handler [WEAK] - B . - ENDP -DebugMon_Handler\ - PROC - EXPORT DebugMon_Handler [WEAK] - B . - ENDP -PendSV_Handler PROC - EXPORT PendSV_Handler [WEAK] - B . - ENDP -SysTick_Handler PROC - EXPORT SysTick_Handler [WEAK] - B . - ENDP - -Default_Handler PROC - - EXPORT WWDG_IRQHandler [WEAK] - EXPORT PVD_IRQHandler [WEAK] - EXPORT TAMP_STAMP_IRQHandler [WEAK] - EXPORT RTC_WKUP_IRQHandler [WEAK] - EXPORT FLASH_IRQHandler [WEAK] - EXPORT RCC_IRQHandler [WEAK] - EXPORT EXTI0_IRQHandler [WEAK] - EXPORT EXTI1_IRQHandler [WEAK] - EXPORT EXTI2_IRQHandler [WEAK] - EXPORT EXTI3_IRQHandler [WEAK] - EXPORT EXTI4_IRQHandler [WEAK] - EXPORT DMA1_Stream0_IRQHandler [WEAK] - EXPORT DMA1_Stream1_IRQHandler [WEAK] - EXPORT DMA1_Stream2_IRQHandler [WEAK] - EXPORT DMA1_Stream3_IRQHandler [WEAK] - EXPORT DMA1_Stream4_IRQHandler [WEAK] - EXPORT DMA1_Stream5_IRQHandler [WEAK] - EXPORT DMA1_Stream6_IRQHandler [WEAK] - EXPORT ADC_IRQHandler [WEAK] - EXPORT CAN1_TX_IRQHandler [WEAK] - EXPORT CAN1_RX0_IRQHandler [WEAK] - EXPORT CAN1_RX1_IRQHandler [WEAK] - EXPORT CAN1_SCE_IRQHandler [WEAK] - EXPORT EXTI9_5_IRQHandler [WEAK] - EXPORT TIM1_BRK_TIM9_IRQHandler [WEAK] - EXPORT TIM1_UP_TIM10_IRQHandler [WEAK] - EXPORT TIM1_TRG_COM_TIM11_IRQHandler [WEAK] - EXPORT TIM1_CC_IRQHandler [WEAK] - EXPORT TIM2_IRQHandler [WEAK] - EXPORT TIM3_IRQHandler [WEAK] - EXPORT TIM4_IRQHandler [WEAK] - EXPORT I2C1_EV_IRQHandler [WEAK] - EXPORT I2C1_ER_IRQHandler [WEAK] - EXPORT I2C2_EV_IRQHandler [WEAK] - EXPORT I2C2_ER_IRQHandler [WEAK] - EXPORT SPI1_IRQHandler [WEAK] - EXPORT SPI2_IRQHandler [WEAK] - EXPORT USART1_IRQHandler [WEAK] - EXPORT USART2_IRQHandler [WEAK] - EXPORT USART3_IRQHandler [WEAK] - EXPORT EXTI15_10_IRQHandler [WEAK] - EXPORT RTC_Alarm_IRQHandler [WEAK] - EXPORT OTG_FS_WKUP_IRQHandler [WEAK] - EXPORT TIM8_BRK_TIM12_IRQHandler [WEAK] - EXPORT TIM8_UP_TIM13_IRQHandler [WEAK] - EXPORT TIM8_TRG_COM_TIM14_IRQHandler [WEAK] - EXPORT TIM8_CC_IRQHandler [WEAK] - EXPORT DMA1_Stream7_IRQHandler [WEAK] - EXPORT FMC_IRQHandler [WEAK] - EXPORT SDIO_IRQHandler [WEAK] - EXPORT TIM5_IRQHandler [WEAK] - EXPORT SPI3_IRQHandler [WEAK] - EXPORT UART4_IRQHandler [WEAK] - EXPORT UART5_IRQHandler [WEAK] - EXPORT TIM6_DAC_IRQHandler [WEAK] - EXPORT TIM7_IRQHandler [WEAK] - EXPORT DMA2_Stream0_IRQHandler [WEAK] - EXPORT DMA2_Stream1_IRQHandler [WEAK] - EXPORT DMA2_Stream2_IRQHandler [WEAK] - EXPORT DMA2_Stream3_IRQHandler [WEAK] - EXPORT DMA2_Stream4_IRQHandler [WEAK] - EXPORT ETH_IRQHandler [WEAK] - EXPORT ETH_WKUP_IRQHandler [WEAK] - EXPORT CAN2_TX_IRQHandler [WEAK] - EXPORT CAN2_RX0_IRQHandler [WEAK] - EXPORT CAN2_RX1_IRQHandler [WEAK] - EXPORT CAN2_SCE_IRQHandler [WEAK] - EXPORT OTG_FS_IRQHandler [WEAK] - EXPORT DMA2_Stream5_IRQHandler [WEAK] - EXPORT DMA2_Stream6_IRQHandler [WEAK] - EXPORT DMA2_Stream7_IRQHandler [WEAK] - EXPORT USART6_IRQHandler [WEAK] - EXPORT I2C3_EV_IRQHandler [WEAK] - EXPORT I2C3_ER_IRQHandler [WEAK] - EXPORT OTG_HS_EP1_OUT_IRQHandler [WEAK] - EXPORT OTG_HS_EP1_IN_IRQHandler [WEAK] - EXPORT OTG_HS_WKUP_IRQHandler [WEAK] - EXPORT OTG_HS_IRQHandler [WEAK] - EXPORT DCMI_IRQHandler [WEAK] - EXPORT CRYP_IRQHandler [WEAK] - EXPORT HASH_RNG_IRQHandler [WEAK] - EXPORT FPU_IRQHandler [WEAK] - EXPORT UART7_IRQHandler [WEAK] - EXPORT UART8_IRQHandler [WEAK] - EXPORT SPI4_IRQHandler [WEAK] - EXPORT SPI5_IRQHandler [WEAK] - EXPORT SPI6_IRQHandler [WEAK] - EXPORT SAI1_IRQHandler [WEAK] - EXPORT DMA2D_IRQHandler [WEAK] - -WWDG_IRQHandler -PVD_IRQHandler -TAMP_STAMP_IRQHandler -RTC_WKUP_IRQHandler -FLASH_IRQHandler -RCC_IRQHandler -EXTI0_IRQHandler -EXTI1_IRQHandler -EXTI2_IRQHandler -EXTI3_IRQHandler -EXTI4_IRQHandler -DMA1_Stream0_IRQHandler -DMA1_Stream1_IRQHandler -DMA1_Stream2_IRQHandler -DMA1_Stream3_IRQHandler -DMA1_Stream4_IRQHandler -DMA1_Stream5_IRQHandler -DMA1_Stream6_IRQHandler -ADC_IRQHandler -CAN1_TX_IRQHandler -CAN1_RX0_IRQHandler -CAN1_RX1_IRQHandler -CAN1_SCE_IRQHandler -EXTI9_5_IRQHandler -TIM1_BRK_TIM9_IRQHandler -TIM1_UP_TIM10_IRQHandler -TIM1_TRG_COM_TIM11_IRQHandler -TIM1_CC_IRQHandler -TIM2_IRQHandler -TIM3_IRQHandler -TIM4_IRQHandler -I2C1_EV_IRQHandler -I2C1_ER_IRQHandler -I2C2_EV_IRQHandler -I2C2_ER_IRQHandler -SPI1_IRQHandler -SPI2_IRQHandler -USART1_IRQHandler -USART2_IRQHandler -USART3_IRQHandler -EXTI15_10_IRQHandler -RTC_Alarm_IRQHandler -OTG_FS_WKUP_IRQHandler -TIM8_BRK_TIM12_IRQHandler -TIM8_UP_TIM13_IRQHandler -TIM8_TRG_COM_TIM14_IRQHandler -TIM8_CC_IRQHandler -DMA1_Stream7_IRQHandler -FMC_IRQHandler -SDIO_IRQHandler -TIM5_IRQHandler -SPI3_IRQHandler -UART4_IRQHandler -UART5_IRQHandler -TIM6_DAC_IRQHandler -TIM7_IRQHandler -DMA2_Stream0_IRQHandler -DMA2_Stream1_IRQHandler -DMA2_Stream2_IRQHandler -DMA2_Stream3_IRQHandler -DMA2_Stream4_IRQHandler -ETH_IRQHandler -ETH_WKUP_IRQHandler -CAN2_TX_IRQHandler -CAN2_RX0_IRQHandler -CAN2_RX1_IRQHandler -CAN2_SCE_IRQHandler -OTG_FS_IRQHandler -DMA2_Stream5_IRQHandler -DMA2_Stream6_IRQHandler -DMA2_Stream7_IRQHandler -USART6_IRQHandler -I2C3_EV_IRQHandler -I2C3_ER_IRQHandler -OTG_HS_EP1_OUT_IRQHandler -OTG_HS_EP1_IN_IRQHandler -OTG_HS_WKUP_IRQHandler -OTG_HS_IRQHandler -DCMI_IRQHandler -CRYP_IRQHandler -HASH_RNG_IRQHandler -FPU_IRQHandler -UART7_IRQHandler -UART8_IRQHandler -SPI4_IRQHandler -SPI5_IRQHandler -SPI6_IRQHandler -SAI1_IRQHandler -DMA2D_IRQHandler - B . - - ENDP - - ALIGN - END - -;************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE***** diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/device/TOOLCHAIN_ARM_STD/stm32f437xx.sct b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/device/TOOLCHAIN_ARM_STD/stm32f437xx.sct deleted file mode 100644 index a6be2a4097f..00000000000 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/device/TOOLCHAIN_ARM_STD/stm32f437xx.sct +++ /dev/null @@ -1,52 +0,0 @@ -#! armcc -E -; Scatter-Loading Description File -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -; Copyright (c) 2015, STMicroelectronics -; All rights reserved. -; -; Redistribution and use in source and binary forms, with or without -; modification, are permitted provided that the following conditions are met: -; -; 1. Redistributions of source code must retain the above copyright notice, -; this list of conditions and the following disclaimer. -; 2. Redistributions in binary form must reproduce the above copyright notice, -; this list of conditions and the following disclaimer in the documentation -; and/or other materials provided with the distribution. -; 3. Neither the name of STMicroelectronics nor the names of its contributors -; may be used to endorse or promote products derived from this software -; without specific prior written permission. -; -; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -; OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; - -; 1 MB FLASH (0x100000) + 192 KB SRAM (0x30000) + 64 KB CCBRAM (0x10000)+ 4 KB BKPSRAM -LR_IROM1 0x08000000 0x100000 { ; load region size_region - - ER_IROM1 0x08000000 0x100000 { ; load address = execution address - *.o (RESET, +First) - *(InRoot$$Sections) - .ANY (+RO) - } - - ; Total: 107 vectors = 428 bytes (0x1AC) to be reserved in RAM - RW_IRAM1 (0x20000000+0x1AC) (0x30000-0x1AC) { ; RW data - .ANY (+RW +ZI) - } - - RW_IRAM2 (0x10000000) (0x10000) { ; RW data - .ANY (CCMRAM) - } - - RW_IRAM3 0x40024000 4096 { ; 4 kbytes of Backup SRAM - .ANY (BKPSRAM) - } -} diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/device/TOOLCHAIN_ARM_STD/sys.cpp b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/device/TOOLCHAIN_ARM_STD/sys.cpp deleted file mode 100644 index bb665909b98..00000000000 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/device/TOOLCHAIN_ARM_STD/sys.cpp +++ /dev/null @@ -1,56 +0,0 @@ -/* mbed Microcontroller Library - stackheap - * Setup a fixed single stack/heap memory model, - * between the top of the RW/ZI region and the stackpointer - ******************************************************************************* - * Copyright (c) 2014, STMicroelectronics - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************* - */ - -#ifdef __cplusplus -extern "C" { -#endif - -#include -#include - -extern char Image$$RW_IRAM1$$ZI$$Limit[]; - -extern __value_in_regs struct __initial_stackheap __user_setup_stackheap(uint32_t R0, uint32_t R1, uint32_t R2, uint32_t R3) { - uint32_t zi_limit = (uint32_t)Image$$RW_IRAM1$$ZI$$Limit; - uint32_t sp_limit = __current_sp(); - - zi_limit = (zi_limit + 7) & ~0x7; // ensure zi_limit is 8-byte aligned - - struct __initial_stackheap r; - r.heap_base = zi_limit; - r.heap_limit = sp_limit; - return r; -} - -#ifdef __cplusplus -} -#endif diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/device/TOOLCHAIN_GCC_ARM/STM32F437xx.ld b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/device/TOOLCHAIN_GCC_ARM/STM32F437xx.ld deleted file mode 100644 index 43ec5682da6..00000000000 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/device/TOOLCHAIN_GCC_ARM/STM32F437xx.ld +++ /dev/null @@ -1,174 +0,0 @@ -/* Linker script to configure memory regions. */ -MEMORY -{ -RAM (xrw) : ORIGIN = 0x200001AC, LENGTH = 192K - 0x1AC /* 0x1AC is to leave room for vectors */ -CCM_RAM (rw) : ORIGIN = 0x10000000, LENGTH = 64K -BACKUP_SRAM (rw) : ORIGIN = 0x40024000, LENGTH = 4096 -FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 1024K -} - -/* Linker script to place sections and symbol values. Should be used together - * with other linker script that defines memory regions FLASH and RAM. - * It references following symbols, which must be defined in code: - * Reset_Handler : Entry of reset handler - * - * It defines following symbols, which code can use without definition: - * __exidx_start - * __exidx_end - * __etext - * __data_start__ - * __preinit_array_start - * __preinit_array_end - * __init_array_start - * __init_array_end - * __fini_array_start - * __fini_array_end - * __data_end__ - * __bss_start__ - * __bss_end__ - * __end__ - * end - * __HeapLimit - * __StackLimit - * __StackTop - * __stack - * _estack - */ -ENTRY(Reset_Handler) - -SECTIONS -{ - .text : - { - KEEP(*(.isr_vector)) - *(.text*) - KEEP(*(.init)) - KEEP(*(.fini)) - - /* .ctors */ - *crtbegin.o(.ctors) - *crtbegin?.o(.ctors) - *(EXCLUDE_FILE(*crtend?.o *crtend.o) .ctors) - *(SORT(.ctors.*)) - *(.ctors) - - /* .dtors */ - *crtbegin.o(.dtors) - *crtbegin?.o(.dtors) - *(EXCLUDE_FILE(*crtend?.o *crtend.o) .dtors) - *(SORT(.dtors.*)) - *(.dtors) - - *(.rodata*) - - KEEP(*(.eh_frame*)) - } > FLASH - - .ARM.extab : - { - *(.ARM.extab* .gnu.linkonce.armextab.*) - } > FLASH - - __exidx_start = .; - .ARM.exidx : - { - *(.ARM.exidx* .gnu.linkonce.armexidx.*) - } > FLASH - __exidx_end = .; - - __etext = .; - _sidata = .; - - .data : AT (__etext) - { - __data_start__ = .; - _sdata = .; - *(vtable) - *(.data*) - - . = ALIGN(4); - /* preinit data */ - PROVIDE_HIDDEN (__preinit_array_start = .); - KEEP(*(.preinit_array)) - PROVIDE_HIDDEN (__preinit_array_end = .); - - . = ALIGN(4); - /* init data */ - PROVIDE_HIDDEN (__init_array_start = .); - KEEP(*(SORT(.init_array.*))) - KEEP(*(.init_array)) - PROVIDE_HIDDEN (__init_array_end = .); - - - . = ALIGN(4); - /* finit data */ - PROVIDE_HIDDEN (__fini_array_start = .); - KEEP(*(SORT(.fini_array.*))) - KEEP(*(.fini_array)) - PROVIDE_HIDDEN (__fini_array_end = .); - - KEEP(*(.jcr*)) - . = ALIGN(4); - /* All data end */ - __data_end__ = .; - _edata = .; - - } > RAM - - .bss : - { - . = ALIGN(4); - __bss_start__ = .; - _sbss = .; - *(.bss*) - *(COMMON) - . = ALIGN(4); - __bss_end__ = .; - _ebss = .; - } > RAM - - .heap (COPY): - { - __end__ = .; - end = __end__; - *(.heap*) - __HeapLimit = .; - } > RAM - - /* .stack_dummy section doesn't contains any symbols. It is only - * used for linker to calculate size of stack sections, and assign - * values to stack symbols later */ - .stack_dummy (COPY): - { - *(.stack*) - } > RAM - - /* Set stack top to end of RAM, and stack limit move down by - * size of stack_dummy section */ - __StackTop = ORIGIN(RAM) + LENGTH(RAM); - _estack = __StackTop; - __StackLimit = __StackTop - SIZEOF(.stack_dummy); - PROVIDE(__stack = __StackTop); - - /* Check if data + heap + stack exceeds RAM limit */ - ASSERT(__StackLimit >= __HeapLimit, "region RAM overflowed with stack") - - /* Code can explicitly ask for data to be - placed into CCMRAM which will be left - uninitialized. - */ - .CCMRAM (NOLOAD): - { - Image$$RW_IRAM2$$Base = . ; - *(CCMRAM) - Image$$RW_IRAM2$$ZI$$Limit = .; - } > CCM_RAM - - /* Backup SRAM, requires unlocking before access */ - .BKPSRAM (NOLOAD): - { - Image$$RW_IRAM3$$Base = . ; - *(BKPSRAM) - Image$$RW_IRAM3$$ZI$$Limit = .; - } > BACKUP_SRAM -} diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/device/TOOLCHAIN_GCC_ARM/startup_stm32f437xx.s b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/device/TOOLCHAIN_GCC_ARM/startup_stm32f437xx.s deleted file mode 100644 index 73a6ee2530c..00000000000 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/device/TOOLCHAIN_GCC_ARM/startup_stm32f437xx.s +++ /dev/null @@ -1,554 +0,0 @@ -/** - ****************************************************************************** - * @file startup_stm32f437xx.s - * @author MCD Application Team - * @version V2.6.0 - * @date 04-November-2016 - * @brief STM32F437xx Devices vector table for GCC based toolchains. - * This module performs: - * - Set the initial SP - * - Set the initial PC == Reset_Handler, - * - Set the vector table entries with the exceptions ISR address - * - Branches to main in the C library (which eventually - * calls main()). - * After Reset the Cortex-M4 processor is in Thread mode, - * priority is Privileged, and the Stack is set to Main. - ****************************************************************************** - * @attention - * - *

© COPYRIGHT 2016 STMicroelectronics

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ - - .syntax unified - .cpu cortex-m4 - .fpu softvfp - .thumb - -.global g_pfnVectors -.global Default_Handler - -/* start address for the initialization values of the .data section. -defined in linker script */ -.word _sidata -/* start address for the .data section. defined in linker script */ -.word _sdata -/* end address for the .data section. defined in linker script */ -.word _edata -/* start address for the .bss section. defined in linker script */ -.word _sbss -/* end address for the .bss section. defined in linker script */ -.word _ebss -/* stack used for SystemInit_ExtMemCtl; always internal RAM used */ - -/** - * @brief This is the code that gets called when the processor first - * starts execution following a reset event. Only the absolutely - * necessary set is performed, after which the application - * supplied main() routine is called. - * @param None - * @retval : None -*/ - - .section .text.Reset_Handler - .weak Reset_Handler - .type Reset_Handler, %function -Reset_Handler: - ldr sp, =_estack /* set stack pointer */ - -/* Copy the data segment initializers from flash to SRAM */ - movs r1, #0 - b LoopCopyDataInit - -CopyDataInit: - ldr r3, =_sidata - ldr r3, [r3, r1] - str r3, [r0, r1] - adds r1, r1, #4 - -LoopCopyDataInit: - ldr r0, =_sdata - ldr r3, =_edata - adds r2, r0, r1 - cmp r2, r3 - bcc CopyDataInit - -/* Call the clock system intitialization function.*/ - bl SystemInit -/* Call static constructors */ - //bl __libc_init_array -/* Call the application's entry point.*/ - //bl main - // Calling the crt0 'cold-start' entry point. There __libc_init_array is called - // and when existing hardware_init_hook() and software_init_hook() before - // starting main(). software_init_hook() is available and has to be called due - // to initializsation when using rtos. - bl _start - bx lr -.size Reset_Handler, .-Reset_Handler - -/** - * @brief This is the code that gets called when the processor receives an - * unexpected interrupt. This simply enters an infinite loop, preserving - * the system state for examination by a debugger. - * @param None - * @retval None -*/ - .section .text.Default_Handler,"ax",%progbits -Default_Handler: -Infinite_Loop: - b Infinite_Loop - .size Default_Handler, .-Default_Handler -/****************************************************************************** -* -* The minimal vector table for a Cortex M3. Note that the proper constructs -* must be placed on this to ensure that it ends up at physical address -* 0x0000.0000. -* -*******************************************************************************/ - .section .isr_vector,"a",%progbits - .type g_pfnVectors, %object - .size g_pfnVectors, .-g_pfnVectors - -g_pfnVectors: - .word _estack - .word Reset_Handler - - .word NMI_Handler - .word HardFault_Handler - .word MemManage_Handler - .word BusFault_Handler - .word UsageFault_Handler - .word 0 - .word 0 - .word 0 - .word 0 - .word SVC_Handler - .word DebugMon_Handler - .word 0 - .word PendSV_Handler - .word SysTick_Handler - - /* External Interrupts */ - .word WWDG_IRQHandler /* Window WatchDog */ - .word PVD_IRQHandler /* PVD through EXTI Line detection */ - .word TAMP_STAMP_IRQHandler /* Tamper and TimeStamps through the EXTI line */ - .word RTC_WKUP_IRQHandler /* RTC Wakeup through the EXTI line */ - .word FLASH_IRQHandler /* FLASH */ - .word RCC_IRQHandler /* RCC */ - .word EXTI0_IRQHandler /* EXTI Line0 */ - .word EXTI1_IRQHandler /* EXTI Line1 */ - .word EXTI2_IRQHandler /* EXTI Line2 */ - .word EXTI3_IRQHandler /* EXTI Line3 */ - .word EXTI4_IRQHandler /* EXTI Line4 */ - .word DMA1_Stream0_IRQHandler /* DMA1 Stream 0 */ - .word DMA1_Stream1_IRQHandler /* DMA1 Stream 1 */ - .word DMA1_Stream2_IRQHandler /* DMA1 Stream 2 */ - .word DMA1_Stream3_IRQHandler /* DMA1 Stream 3 */ - .word DMA1_Stream4_IRQHandler /* DMA1 Stream 4 */ - .word DMA1_Stream5_IRQHandler /* DMA1 Stream 5 */ - .word DMA1_Stream6_IRQHandler /* DMA1 Stream 6 */ - .word ADC_IRQHandler /* ADC1, ADC2 and ADC3s */ - .word CAN1_TX_IRQHandler /* CAN1 TX */ - .word CAN1_RX0_IRQHandler /* CAN1 RX0 */ - .word CAN1_RX1_IRQHandler /* CAN1 RX1 */ - .word CAN1_SCE_IRQHandler /* CAN1 SCE */ - .word EXTI9_5_IRQHandler /* External Line[9:5]s */ - .word TIM1_BRK_TIM9_IRQHandler /* TIM1 Break and TIM9 */ - .word TIM1_UP_TIM10_IRQHandler /* TIM1 Update and TIM10 */ - .word TIM1_TRG_COM_TIM11_IRQHandler /* TIM1 Trigger and Commutation and TIM11 */ - .word TIM1_CC_IRQHandler /* TIM1 Capture Compare */ - .word TIM2_IRQHandler /* TIM2 */ - .word TIM3_IRQHandler /* TIM3 */ - .word TIM4_IRQHandler /* TIM4 */ - .word I2C1_EV_IRQHandler /* I2C1 Event */ - .word I2C1_ER_IRQHandler /* I2C1 Error */ - .word I2C2_EV_IRQHandler /* I2C2 Event */ - .word I2C2_ER_IRQHandler /* I2C2 Error */ - .word SPI1_IRQHandler /* SPI1 */ - .word SPI2_IRQHandler /* SPI2 */ - .word USART1_IRQHandler /* USART1 */ - .word USART2_IRQHandler /* USART2 */ - .word USART3_IRQHandler /* USART3 */ - .word EXTI15_10_IRQHandler /* External Line[15:10]s */ - .word RTC_Alarm_IRQHandler /* RTC Alarm (A and B) through EXTI Line */ - .word OTG_FS_WKUP_IRQHandler /* USB OTG FS Wakeup through EXTI line */ - .word TIM8_BRK_TIM12_IRQHandler /* TIM8 Break and TIM12 */ - .word TIM8_UP_TIM13_IRQHandler /* TIM8 Update and TIM13 */ - .word TIM8_TRG_COM_TIM14_IRQHandler /* TIM8 Trigger and Commutation and TIM14 */ - .word TIM8_CC_IRQHandler /* TIM8 Capture Compare */ - .word DMA1_Stream7_IRQHandler /* DMA1 Stream7 */ - .word FMC_IRQHandler /* FMC */ - .word SDIO_IRQHandler /* SDIO */ - .word TIM5_IRQHandler /* TIM5 */ - .word SPI3_IRQHandler /* SPI3 */ - .word UART4_IRQHandler /* UART4 */ - .word UART5_IRQHandler /* UART5 */ - .word TIM6_DAC_IRQHandler /* TIM6 and DAC1&2 underrun errors */ - .word TIM7_IRQHandler /* TIM7 */ - .word DMA2_Stream0_IRQHandler /* DMA2 Stream 0 */ - .word DMA2_Stream1_IRQHandler /* DMA2 Stream 1 */ - .word DMA2_Stream2_IRQHandler /* DMA2 Stream 2 */ - .word DMA2_Stream3_IRQHandler /* DMA2 Stream 3 */ - .word DMA2_Stream4_IRQHandler /* DMA2 Stream 4 */ - .word ETH_IRQHandler /* Ethernet */ - .word ETH_WKUP_IRQHandler /* Ethernet Wakeup through EXTI line */ - .word CAN2_TX_IRQHandler /* CAN2 TX */ - .word CAN2_RX0_IRQHandler /* CAN2 RX0 */ - .word CAN2_RX1_IRQHandler /* CAN2 RX1 */ - .word CAN2_SCE_IRQHandler /* CAN2 SCE */ - .word OTG_FS_IRQHandler /* USB OTG FS */ - .word DMA2_Stream5_IRQHandler /* DMA2 Stream 5 */ - .word DMA2_Stream6_IRQHandler /* DMA2 Stream 6 */ - .word DMA2_Stream7_IRQHandler /* DMA2 Stream 7 */ - .word USART6_IRQHandler /* USART6 */ - .word I2C3_EV_IRQHandler /* I2C3 event */ - .word I2C3_ER_IRQHandler /* I2C3 error */ - .word OTG_HS_EP1_OUT_IRQHandler /* USB OTG HS End Point 1 Out */ - .word OTG_HS_EP1_IN_IRQHandler /* USB OTG HS End Point 1 In */ - .word OTG_HS_WKUP_IRQHandler /* USB OTG HS Wakeup through EXTI */ - .word OTG_HS_IRQHandler /* USB OTG HS */ - .word DCMI_IRQHandler /* DCMI */ - .word CRYP_IRQHandler /* CRYP crypto */ - .word HASH_RNG_IRQHandler /* Hash and Rng */ - .word FPU_IRQHandler /* FPU */ - .word UART7_IRQHandler /* UART7 */ - .word UART8_IRQHandler /* UART8 */ - .word SPI4_IRQHandler /* SPI4 */ - .word SPI5_IRQHandler /* SPI5 */ - .word SPI6_IRQHandler /* SPI6 */ - .word SAI1_IRQHandler /* SAI1 */ - .word 0 /* Reserved */ - .word 0 /* Reserved */ - .word DMA2D_IRQHandler /* DMA2D */ - -/******************************************************************************* -* -* Provide weak aliases for each Exception handler to the Default_Handler. -* As they are weak aliases, any function with the same name will override -* this definition. -* -*******************************************************************************/ - .weak NMI_Handler - .thumb_set NMI_Handler,Default_Handler - - .weak HardFault_Handler - .thumb_set HardFault_Handler,Default_Handler - - .weak MemManage_Handler - .thumb_set MemManage_Handler,Default_Handler - - .weak BusFault_Handler - .thumb_set BusFault_Handler,Default_Handler - - .weak UsageFault_Handler - .thumb_set UsageFault_Handler,Default_Handler - - .weak SVC_Handler - .thumb_set SVC_Handler,Default_Handler - - .weak DebugMon_Handler - .thumb_set DebugMon_Handler,Default_Handler - - .weak PendSV_Handler - .thumb_set PendSV_Handler,Default_Handler - - .weak SysTick_Handler - .thumb_set SysTick_Handler,Default_Handler - - .weak WWDG_IRQHandler - .thumb_set WWDG_IRQHandler,Default_Handler - - .weak PVD_IRQHandler - .thumb_set PVD_IRQHandler,Default_Handler - - .weak TAMP_STAMP_IRQHandler - .thumb_set TAMP_STAMP_IRQHandler,Default_Handler - - .weak RTC_WKUP_IRQHandler - .thumb_set RTC_WKUP_IRQHandler,Default_Handler - - .weak FLASH_IRQHandler - .thumb_set FLASH_IRQHandler,Default_Handler - - .weak RCC_IRQHandler - .thumb_set RCC_IRQHandler,Default_Handler - - .weak EXTI0_IRQHandler - .thumb_set EXTI0_IRQHandler,Default_Handler - - .weak EXTI1_IRQHandler - .thumb_set EXTI1_IRQHandler,Default_Handler - - .weak EXTI2_IRQHandler - .thumb_set EXTI2_IRQHandler,Default_Handler - - .weak EXTI3_IRQHandler - .thumb_set EXTI3_IRQHandler,Default_Handler - - .weak EXTI4_IRQHandler - .thumb_set EXTI4_IRQHandler,Default_Handler - - .weak DMA1_Stream0_IRQHandler - .thumb_set DMA1_Stream0_IRQHandler,Default_Handler - - .weak DMA1_Stream1_IRQHandler - .thumb_set DMA1_Stream1_IRQHandler,Default_Handler - - .weak DMA1_Stream2_IRQHandler - .thumb_set DMA1_Stream2_IRQHandler,Default_Handler - - .weak DMA1_Stream3_IRQHandler - .thumb_set DMA1_Stream3_IRQHandler,Default_Handler - - .weak DMA1_Stream4_IRQHandler - .thumb_set DMA1_Stream4_IRQHandler,Default_Handler - - .weak DMA1_Stream5_IRQHandler - .thumb_set DMA1_Stream5_IRQHandler,Default_Handler - - .weak DMA1_Stream6_IRQHandler - .thumb_set DMA1_Stream6_IRQHandler,Default_Handler - - .weak ADC_IRQHandler - .thumb_set ADC_IRQHandler,Default_Handler - - .weak CAN1_TX_IRQHandler - .thumb_set CAN1_TX_IRQHandler,Default_Handler - - .weak CAN1_RX0_IRQHandler - .thumb_set CAN1_RX0_IRQHandler,Default_Handler - - .weak CAN1_RX1_IRQHandler - .thumb_set CAN1_RX1_IRQHandler,Default_Handler - - .weak CAN1_SCE_IRQHandler - .thumb_set CAN1_SCE_IRQHandler,Default_Handler - - .weak EXTI9_5_IRQHandler - .thumb_set EXTI9_5_IRQHandler,Default_Handler - - .weak TIM1_BRK_TIM9_IRQHandler - .thumb_set TIM1_BRK_TIM9_IRQHandler,Default_Handler - - .weak TIM1_UP_TIM10_IRQHandler - .thumb_set TIM1_UP_TIM10_IRQHandler,Default_Handler - - .weak TIM1_TRG_COM_TIM11_IRQHandler - .thumb_set TIM1_TRG_COM_TIM11_IRQHandler,Default_Handler - - .weak TIM1_CC_IRQHandler - .thumb_set TIM1_CC_IRQHandler,Default_Handler - - .weak TIM2_IRQHandler - .thumb_set TIM2_IRQHandler,Default_Handler - - .weak TIM3_IRQHandler - .thumb_set TIM3_IRQHandler,Default_Handler - - .weak TIM4_IRQHandler - .thumb_set TIM4_IRQHandler,Default_Handler - - .weak I2C1_EV_IRQHandler - .thumb_set I2C1_EV_IRQHandler,Default_Handler - - .weak I2C1_ER_IRQHandler - .thumb_set I2C1_ER_IRQHandler,Default_Handler - - .weak I2C2_EV_IRQHandler - .thumb_set I2C2_EV_IRQHandler,Default_Handler - - .weak I2C2_ER_IRQHandler - .thumb_set I2C2_ER_IRQHandler,Default_Handler - - .weak SPI1_IRQHandler - .thumb_set SPI1_IRQHandler,Default_Handler - - .weak SPI2_IRQHandler - .thumb_set SPI2_IRQHandler,Default_Handler - - .weak USART1_IRQHandler - .thumb_set USART1_IRQHandler,Default_Handler - - .weak USART2_IRQHandler - .thumb_set USART2_IRQHandler,Default_Handler - - .weak USART3_IRQHandler - .thumb_set USART3_IRQHandler,Default_Handler - - .weak EXTI15_10_IRQHandler - .thumb_set EXTI15_10_IRQHandler,Default_Handler - - .weak RTC_Alarm_IRQHandler - .thumb_set RTC_Alarm_IRQHandler,Default_Handler - - .weak OTG_FS_WKUP_IRQHandler - .thumb_set OTG_FS_WKUP_IRQHandler,Default_Handler - - .weak TIM8_BRK_TIM12_IRQHandler - .thumb_set TIM8_BRK_TIM12_IRQHandler,Default_Handler - - .weak TIM8_UP_TIM13_IRQHandler - .thumb_set TIM8_UP_TIM13_IRQHandler,Default_Handler - - .weak TIM8_TRG_COM_TIM14_IRQHandler - .thumb_set TIM8_TRG_COM_TIM14_IRQHandler,Default_Handler - - .weak TIM8_CC_IRQHandler - .thumb_set TIM8_CC_IRQHandler,Default_Handler - - .weak DMA1_Stream7_IRQHandler - .thumb_set DMA1_Stream7_IRQHandler,Default_Handler - - .weak FMC_IRQHandler - .thumb_set FMC_IRQHandler,Default_Handler - - .weak SDIO_IRQHandler - .thumb_set SDIO_IRQHandler,Default_Handler - - .weak TIM5_IRQHandler - .thumb_set TIM5_IRQHandler,Default_Handler - - .weak SPI3_IRQHandler - .thumb_set SPI3_IRQHandler,Default_Handler - - .weak UART4_IRQHandler - .thumb_set UART4_IRQHandler,Default_Handler - - .weak UART5_IRQHandler - .thumb_set UART5_IRQHandler,Default_Handler - - .weak TIM6_DAC_IRQHandler - .thumb_set TIM6_DAC_IRQHandler,Default_Handler - - .weak TIM7_IRQHandler - .thumb_set TIM7_IRQHandler,Default_Handler - - .weak DMA2_Stream0_IRQHandler - .thumb_set DMA2_Stream0_IRQHandler,Default_Handler - - .weak DMA2_Stream1_IRQHandler - .thumb_set DMA2_Stream1_IRQHandler,Default_Handler - - .weak DMA2_Stream2_IRQHandler - .thumb_set DMA2_Stream2_IRQHandler,Default_Handler - - .weak DMA2_Stream3_IRQHandler - .thumb_set DMA2_Stream3_IRQHandler,Default_Handler - - .weak DMA2_Stream4_IRQHandler - .thumb_set DMA2_Stream4_IRQHandler,Default_Handler - - .weak ETH_IRQHandler - .thumb_set ETH_IRQHandler,Default_Handler - - .weak ETH_WKUP_IRQHandler - .thumb_set ETH_WKUP_IRQHandler,Default_Handler - - .weak CAN2_TX_IRQHandler - .thumb_set CAN2_TX_IRQHandler,Default_Handler - - .weak CAN2_RX0_IRQHandler - .thumb_set CAN2_RX0_IRQHandler,Default_Handler - - .weak CAN2_RX1_IRQHandler - .thumb_set CAN2_RX1_IRQHandler,Default_Handler - - .weak CAN2_SCE_IRQHandler - .thumb_set CAN2_SCE_IRQHandler,Default_Handler - - .weak OTG_FS_IRQHandler - .thumb_set OTG_FS_IRQHandler,Default_Handler - - .weak DMA2_Stream5_IRQHandler - .thumb_set DMA2_Stream5_IRQHandler,Default_Handler - - .weak DMA2_Stream6_IRQHandler - .thumb_set DMA2_Stream6_IRQHandler,Default_Handler - - .weak DMA2_Stream7_IRQHandler - .thumb_set DMA2_Stream7_IRQHandler,Default_Handler - - .weak USART6_IRQHandler - .thumb_set USART6_IRQHandler,Default_Handler - - .weak I2C3_EV_IRQHandler - .thumb_set I2C3_EV_IRQHandler,Default_Handler - - .weak I2C3_ER_IRQHandler - .thumb_set I2C3_ER_IRQHandler,Default_Handler - - .weak OTG_HS_EP1_OUT_IRQHandler - .thumb_set OTG_HS_EP1_OUT_IRQHandler,Default_Handler - - .weak OTG_HS_EP1_IN_IRQHandler - .thumb_set OTG_HS_EP1_IN_IRQHandler,Default_Handler - - .weak OTG_HS_WKUP_IRQHandler - .thumb_set OTG_HS_WKUP_IRQHandler,Default_Handler - - .weak OTG_HS_IRQHandler - .thumb_set OTG_HS_IRQHandler,Default_Handler - - .weak DCMI_IRQHandler - .thumb_set DCMI_IRQHandler,Default_Handler - - .weak CRYP_IRQHandler - .thumb_set CRYP_IRQHandler,Default_Handler - - .weak HASH_RNG_IRQHandler - .thumb_set HASH_RNG_IRQHandler,Default_Handler - - .weak FPU_IRQHandler - .thumb_set FPU_IRQHandler,Default_Handler - - .weak UART7_IRQHandler - .thumb_set UART7_IRQHandler,Default_Handler - - .weak UART8_IRQHandler - .thumb_set UART8_IRQHandler,Default_Handler - - .weak SPI4_IRQHandler - .thumb_set SPI4_IRQHandler,Default_Handler - - .weak SPI5_IRQHandler - .thumb_set SPI5_IRQHandler,Default_Handler - - .weak SPI6_IRQHandler - .thumb_set SPI6_IRQHandler,Default_Handler - - .weak SAI1_IRQHandler - .thumb_set SAI1_IRQHandler,Default_Handler - - .weak DMA2D_IRQHandler - .thumb_set DMA2D_IRQHandler,Default_Handler - -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ - - - - - diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/device/TOOLCHAIN_IAR/startup_stm32f437xx.S b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/device/TOOLCHAIN_IAR/startup_stm32f437xx.S deleted file mode 100644 index 11221dd7e02..00000000000 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/device/TOOLCHAIN_IAR/startup_stm32f437xx.S +++ /dev/null @@ -1,688 +0,0 @@ -;/******************** (C) COPYRIGHT 2014 STMicroelectronics ******************** -;* File Name : startup_stm32f437xx.s -;* Author : MCD Application Team -;* Version : V2.1.0 -;* Date : 19-June-2014 -;* Description : STM32F437xx devices vector table for EWARM toolchain. -;* This module performs: -;* - Set the initial SP -;* - Set the initial PC == _iar_program_start, -;* - Set the vector table entries with the exceptions ISR -;* address. -;* - Branches to main in the C library (which eventually -;* calls main()). -;* After Reset the Cortex-M4 processor is in Thread mode, -;* priority is Privileged, and the Stack is set to Main. -;******************************************************************************** -;* -;* Redistribution and use in source and binary forms, with or without modification, -;* are permitted provided that the following conditions are met: -;* 1. Redistributions of source code must retain the above copyright notice, -;* this list of conditions and the following disclaimer. -;* 2. Redistributions in binary form must reproduce the above copyright notice, -;* this list of conditions and the following disclaimer in the documentation -;* and/or other materials provided with the distribution. -;* 3. Neither the name of STMicroelectronics nor the names of its contributors -;* may be used to endorse or promote products derived from this software -;* without specific prior written permission. -;* -;* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -;* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -;* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -;* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -;* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -;* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -;* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -;* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -;* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -;* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -;* -;******************************************************************************* -; -; -; The modules in this file are included in the libraries, and may be replaced -; by any user-defined modules that define the PUBLIC symbol _program_start or -; a user defined start symbol. -; To override the cstartup defined in the library, simply add your modified -; version to the workbench project. -; -; The vector table is normally located at address 0. -; When debugging in RAM, it can be located in RAM, aligned to at least 2^6. -; The name "__vector_table" has special meaning for C-SPY: -; it is where the SP start value is found, and the NVIC vector -; table register (VTOR) is initialized to this address if != 0. -; -; Cortex-M version -; - - MODULE ?cstartup - - ;; Forward declaration of sections. - SECTION CSTACK:DATA:NOROOT(3) - - SECTION .intvec:CODE:NOROOT(2) - - EXTERN __iar_program_start - EXTERN SystemInit - PUBLIC __vector_table - - DATA -__vector_table - DCD sfe(CSTACK) - DCD Reset_Handler ; Reset Handler - - DCD NMI_Handler ; NMI Handler - DCD HardFault_Handler ; Hard Fault Handler - DCD MemManage_Handler ; MPU Fault Handler - DCD BusFault_Handler ; Bus Fault Handler - DCD UsageFault_Handler ; Usage Fault Handler - DCD 0 ; Reserved - DCD 0 ; Reserved - DCD 0 ; Reserved - DCD 0 ; Reserved - DCD SVC_Handler ; SVCall Handler - DCD DebugMon_Handler ; Debug Monitor Handler - DCD 0 ; Reserved - DCD PendSV_Handler ; PendSV Handler - DCD SysTick_Handler ; SysTick Handler - - ; External Interrupts - DCD WWDG_IRQHandler ; Window WatchDog - DCD PVD_IRQHandler ; PVD through EXTI Line detection - DCD TAMP_STAMP_IRQHandler ; Tamper and TimeStamps through the EXTI line - DCD RTC_WKUP_IRQHandler ; RTC Wakeup through the EXTI line - DCD FLASH_IRQHandler ; FLASH - DCD RCC_IRQHandler ; RCC - DCD EXTI0_IRQHandler ; EXTI Line0 - DCD EXTI1_IRQHandler ; EXTI Line1 - DCD EXTI2_IRQHandler ; EXTI Line2 - DCD EXTI3_IRQHandler ; EXTI Line3 - DCD EXTI4_IRQHandler ; EXTI Line4 - DCD DMA1_Stream0_IRQHandler ; DMA1 Stream 0 - DCD DMA1_Stream1_IRQHandler ; DMA1 Stream 1 - DCD DMA1_Stream2_IRQHandler ; DMA1 Stream 2 - DCD DMA1_Stream3_IRQHandler ; DMA1 Stream 3 - DCD DMA1_Stream4_IRQHandler ; DMA1 Stream 4 - DCD DMA1_Stream5_IRQHandler ; DMA1 Stream 5 - DCD DMA1_Stream6_IRQHandler ; DMA1 Stream 6 - DCD ADC_IRQHandler ; ADC1, ADC2 and ADC3s - DCD CAN1_TX_IRQHandler ; CAN1 TX - DCD CAN1_RX0_IRQHandler ; CAN1 RX0 - DCD CAN1_RX1_IRQHandler ; CAN1 RX1 - DCD CAN1_SCE_IRQHandler ; CAN1 SCE - DCD EXTI9_5_IRQHandler ; External Line[9:5]s - DCD TIM1_BRK_TIM9_IRQHandler ; TIM1 Break and TIM9 - DCD TIM1_UP_TIM10_IRQHandler ; TIM1 Update and TIM10 - DCD TIM1_TRG_COM_TIM11_IRQHandler ; TIM1 Trigger and Commutation and TIM11 - DCD TIM1_CC_IRQHandler ; TIM1 Capture Compare - DCD TIM2_IRQHandler ; TIM2 - DCD TIM3_IRQHandler ; TIM3 - DCD TIM4_IRQHandler ; TIM4 - DCD I2C1_EV_IRQHandler ; I2C1 Event - DCD I2C1_ER_IRQHandler ; I2C1 Error - DCD I2C2_EV_IRQHandler ; I2C2 Event - DCD I2C2_ER_IRQHandler ; I2C2 Error - DCD SPI1_IRQHandler ; SPI1 - DCD SPI2_IRQHandler ; SPI2 - DCD USART1_IRQHandler ; USART1 - DCD USART2_IRQHandler ; USART2 - DCD USART3_IRQHandler ; USART3 - DCD EXTI15_10_IRQHandler ; External Line[15:10]s - DCD RTC_Alarm_IRQHandler ; RTC Alarm (A and B) through EXTI Line - DCD OTG_FS_WKUP_IRQHandler ; USB OTG FS Wakeup through EXTI line - DCD TIM8_BRK_TIM12_IRQHandler ; TIM8 Break and TIM12 - DCD TIM8_UP_TIM13_IRQHandler ; TIM8 Update and TIM13 - DCD TIM8_TRG_COM_TIM14_IRQHandler ; TIM8 Trigger and Commutation and TIM14 - DCD TIM8_CC_IRQHandler ; TIM8 Capture Compare - DCD DMA1_Stream7_IRQHandler ; DMA1 Stream7 - DCD FMC_IRQHandler ; FMC - DCD SDIO_IRQHandler ; SDIO - DCD TIM5_IRQHandler ; TIM5 - DCD SPI3_IRQHandler ; SPI3 - DCD UART4_IRQHandler ; UART4 - DCD UART5_IRQHandler ; UART5 - DCD TIM6_DAC_IRQHandler ; TIM6 and DAC1&2 underrun errors - DCD TIM7_IRQHandler ; TIM7 - DCD DMA2_Stream0_IRQHandler ; DMA2 Stream 0 - DCD DMA2_Stream1_IRQHandler ; DMA2 Stream 1 - DCD DMA2_Stream2_IRQHandler ; DMA2 Stream 2 - DCD DMA2_Stream3_IRQHandler ; DMA2 Stream 3 - DCD DMA2_Stream4_IRQHandler ; DMA2 Stream 4 - DCD ETH_IRQHandler ; Ethernet - DCD ETH_WKUP_IRQHandler ; Ethernet Wakeup through EXTI line - DCD CAN2_TX_IRQHandler ; CAN2 TX - DCD CAN2_RX0_IRQHandler ; CAN2 RX0 - DCD CAN2_RX1_IRQHandler ; CAN2 RX1 - DCD CAN2_SCE_IRQHandler ; CAN2 SCE - DCD OTG_FS_IRQHandler ; USB OTG FS - DCD DMA2_Stream5_IRQHandler ; DMA2 Stream 5 - DCD DMA2_Stream6_IRQHandler ; DMA2 Stream 6 - DCD DMA2_Stream7_IRQHandler ; DMA2 Stream 7 - DCD USART6_IRQHandler ; USART6 - DCD I2C3_EV_IRQHandler ; I2C3 event - DCD I2C3_ER_IRQHandler ; I2C3 error - DCD OTG_HS_EP1_OUT_IRQHandler ; USB OTG HS End Point 1 Out - DCD OTG_HS_EP1_IN_IRQHandler ; USB OTG HS End Point 1 In - DCD OTG_HS_WKUP_IRQHandler ; USB OTG HS Wakeup through EXTI - DCD OTG_HS_IRQHandler ; USB OTG HS - DCD DCMI_IRQHandler ; DCMI - DCD CRYP_IRQHandler ; CRYP crypto - DCD HASH_RNG_IRQHandler ; Hash and Rng - DCD FPU_IRQHandler ; FPU - DCD UART7_IRQHandler ; UART7 - DCD UART8_IRQHandler ; UART8 - DCD SPI4_IRQHandler ; SPI4 - DCD SPI5_IRQHandler ; SPI5 - DCD SPI6_IRQHandler ; SPI6 - DCD SAI1_IRQHandler ; SAI1 - DCD 0 ; Reserved - DCD 0 ; Reserved - DCD DMA2D_IRQHandler ; DMA2D - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; -;; Default interrupt handlers. -;; - THUMB - PUBWEAK Reset_Handler - SECTION .text:CODE:REORDER:NOROOT(2) -Reset_Handler - - LDR R0, =SystemInit - BLX R0 - LDR R0, =__iar_program_start - BX R0 - - PUBWEAK NMI_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -NMI_Handler - B NMI_Handler - - PUBWEAK HardFault_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -HardFault_Handler - B HardFault_Handler - - PUBWEAK MemManage_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -MemManage_Handler - B MemManage_Handler - - PUBWEAK BusFault_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -BusFault_Handler - B BusFault_Handler - - PUBWEAK UsageFault_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -UsageFault_Handler - B UsageFault_Handler - - PUBWEAK SVC_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -SVC_Handler - B SVC_Handler - - PUBWEAK DebugMon_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -DebugMon_Handler - B DebugMon_Handler - - PUBWEAK PendSV_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -PendSV_Handler - B PendSV_Handler - - PUBWEAK SysTick_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -SysTick_Handler - B SysTick_Handler - - PUBWEAK WWDG_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -WWDG_IRQHandler - B WWDG_IRQHandler - - PUBWEAK PVD_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -PVD_IRQHandler - B PVD_IRQHandler - - PUBWEAK TAMP_STAMP_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -TAMP_STAMP_IRQHandler - B TAMP_STAMP_IRQHandler - - PUBWEAK RTC_WKUP_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -RTC_WKUP_IRQHandler - B RTC_WKUP_IRQHandler - - PUBWEAK FLASH_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -FLASH_IRQHandler - B FLASH_IRQHandler - - PUBWEAK RCC_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -RCC_IRQHandler - B RCC_IRQHandler - - PUBWEAK EXTI0_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -EXTI0_IRQHandler - B EXTI0_IRQHandler - - PUBWEAK EXTI1_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -EXTI1_IRQHandler - B EXTI1_IRQHandler - - PUBWEAK EXTI2_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -EXTI2_IRQHandler - B EXTI2_IRQHandler - - PUBWEAK EXTI3_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -EXTI3_IRQHandler - B EXTI3_IRQHandler - - PUBWEAK EXTI4_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -EXTI4_IRQHandler - B EXTI4_IRQHandler - - PUBWEAK DMA1_Stream0_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -DMA1_Stream0_IRQHandler - B DMA1_Stream0_IRQHandler - - PUBWEAK DMA1_Stream1_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -DMA1_Stream1_IRQHandler - B DMA1_Stream1_IRQHandler - - PUBWEAK DMA1_Stream2_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -DMA1_Stream2_IRQHandler - B DMA1_Stream2_IRQHandler - - PUBWEAK DMA1_Stream3_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -DMA1_Stream3_IRQHandler - B DMA1_Stream3_IRQHandler - - PUBWEAK DMA1_Stream4_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -DMA1_Stream4_IRQHandler - B DMA1_Stream4_IRQHandler - - PUBWEAK DMA1_Stream5_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -DMA1_Stream5_IRQHandler - B DMA1_Stream5_IRQHandler - - PUBWEAK DMA1_Stream6_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -DMA1_Stream6_IRQHandler - B DMA1_Stream6_IRQHandler - - PUBWEAK ADC_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -ADC_IRQHandler - B ADC_IRQHandler - - PUBWEAK CAN1_TX_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -CAN1_TX_IRQHandler - B CAN1_TX_IRQHandler - - PUBWEAK CAN1_RX0_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -CAN1_RX0_IRQHandler - B CAN1_RX0_IRQHandler - - PUBWEAK CAN1_RX1_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -CAN1_RX1_IRQHandler - B CAN1_RX1_IRQHandler - - PUBWEAK CAN1_SCE_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -CAN1_SCE_IRQHandler - B CAN1_SCE_IRQHandler - - PUBWEAK EXTI9_5_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -EXTI9_5_IRQHandler - B EXTI9_5_IRQHandler - - PUBWEAK TIM1_BRK_TIM9_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -TIM1_BRK_TIM9_IRQHandler - B TIM1_BRK_TIM9_IRQHandler - - PUBWEAK TIM1_UP_TIM10_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -TIM1_UP_TIM10_IRQHandler - B TIM1_UP_TIM10_IRQHandler - - PUBWEAK TIM1_TRG_COM_TIM11_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -TIM1_TRG_COM_TIM11_IRQHandler - B TIM1_TRG_COM_TIM11_IRQHandler - - PUBWEAK TIM1_CC_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -TIM1_CC_IRQHandler - B TIM1_CC_IRQHandler - - PUBWEAK TIM2_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -TIM2_IRQHandler - B TIM2_IRQHandler - - PUBWEAK TIM3_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -TIM3_IRQHandler - B TIM3_IRQHandler - - PUBWEAK TIM4_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -TIM4_IRQHandler - B TIM4_IRQHandler - - PUBWEAK I2C1_EV_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -I2C1_EV_IRQHandler - B I2C1_EV_IRQHandler - - PUBWEAK I2C1_ER_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -I2C1_ER_IRQHandler - B I2C1_ER_IRQHandler - - PUBWEAK I2C2_EV_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -I2C2_EV_IRQHandler - B I2C2_EV_IRQHandler - - PUBWEAK I2C2_ER_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -I2C2_ER_IRQHandler - B I2C2_ER_IRQHandler - - PUBWEAK SPI1_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -SPI1_IRQHandler - B SPI1_IRQHandler - - PUBWEAK SPI2_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -SPI2_IRQHandler - B SPI2_IRQHandler - - PUBWEAK USART1_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -USART1_IRQHandler - B USART1_IRQHandler - - PUBWEAK USART2_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -USART2_IRQHandler - B USART2_IRQHandler - - PUBWEAK USART3_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -USART3_IRQHandler - B USART3_IRQHandler - - PUBWEAK EXTI15_10_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -EXTI15_10_IRQHandler - B EXTI15_10_IRQHandler - - PUBWEAK RTC_Alarm_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -RTC_Alarm_IRQHandler - B RTC_Alarm_IRQHandler - - PUBWEAK OTG_FS_WKUP_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -OTG_FS_WKUP_IRQHandler - B OTG_FS_WKUP_IRQHandler - - PUBWEAK TIM8_BRK_TIM12_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -TIM8_BRK_TIM12_IRQHandler - B TIM8_BRK_TIM12_IRQHandler - - PUBWEAK TIM8_UP_TIM13_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -TIM8_UP_TIM13_IRQHandler - B TIM8_UP_TIM13_IRQHandler - - PUBWEAK TIM8_TRG_COM_TIM14_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -TIM8_TRG_COM_TIM14_IRQHandler - B TIM8_TRG_COM_TIM14_IRQHandler - - PUBWEAK TIM8_CC_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -TIM8_CC_IRQHandler - B TIM8_CC_IRQHandler - - PUBWEAK DMA1_Stream7_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -DMA1_Stream7_IRQHandler - B DMA1_Stream7_IRQHandler - - PUBWEAK FMC_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -FMC_IRQHandler - B FMC_IRQHandler - - PUBWEAK SDIO_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -SDIO_IRQHandler - B SDIO_IRQHandler - - PUBWEAK TIM5_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -TIM5_IRQHandler - B TIM5_IRQHandler - - PUBWEAK SPI3_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -SPI3_IRQHandler - B SPI3_IRQHandler - - PUBWEAK UART4_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -UART4_IRQHandler - B UART4_IRQHandler - - PUBWEAK UART5_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -UART5_IRQHandler - B UART5_IRQHandler - - PUBWEAK TIM6_DAC_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -TIM6_DAC_IRQHandler - B TIM6_DAC_IRQHandler - - PUBWEAK TIM7_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -TIM7_IRQHandler - B TIM7_IRQHandler - - PUBWEAK DMA2_Stream0_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -DMA2_Stream0_IRQHandler - B DMA2_Stream0_IRQHandler - - PUBWEAK DMA2_Stream1_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -DMA2_Stream1_IRQHandler - B DMA2_Stream1_IRQHandler - - PUBWEAK DMA2_Stream2_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -DMA2_Stream2_IRQHandler - B DMA2_Stream2_IRQHandler - - PUBWEAK DMA2_Stream3_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -DMA2_Stream3_IRQHandler - B DMA2_Stream3_IRQHandler - - PUBWEAK DMA2_Stream4_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -DMA2_Stream4_IRQHandler - B DMA2_Stream4_IRQHandler - - PUBWEAK ETH_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -ETH_IRQHandler - B ETH_IRQHandler - - PUBWEAK ETH_WKUP_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -ETH_WKUP_IRQHandler - B ETH_WKUP_IRQHandler - - PUBWEAK CAN2_TX_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -CAN2_TX_IRQHandler - B CAN2_TX_IRQHandler - - PUBWEAK CAN2_RX0_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -CAN2_RX0_IRQHandler - B CAN2_RX0_IRQHandler - - PUBWEAK CAN2_RX1_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -CAN2_RX1_IRQHandler - B CAN2_RX1_IRQHandler - - PUBWEAK CAN2_SCE_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -CAN2_SCE_IRQHandler - B CAN2_SCE_IRQHandler - - PUBWEAK OTG_FS_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -OTG_FS_IRQHandler - B OTG_FS_IRQHandler - - PUBWEAK DMA2_Stream5_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -DMA2_Stream5_IRQHandler - B DMA2_Stream5_IRQHandler - - PUBWEAK DMA2_Stream6_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -DMA2_Stream6_IRQHandler - B DMA2_Stream6_IRQHandler - - PUBWEAK DMA2_Stream7_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -DMA2_Stream7_IRQHandler - B DMA2_Stream7_IRQHandler - - PUBWEAK USART6_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -USART6_IRQHandler - B USART6_IRQHandler - - PUBWEAK I2C3_EV_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -I2C3_EV_IRQHandler - B I2C3_EV_IRQHandler - - PUBWEAK I2C3_ER_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -I2C3_ER_IRQHandler - B I2C3_ER_IRQHandler - - PUBWEAK OTG_HS_EP1_OUT_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -OTG_HS_EP1_OUT_IRQHandler - B OTG_HS_EP1_OUT_IRQHandler - - PUBWEAK OTG_HS_EP1_IN_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -OTG_HS_EP1_IN_IRQHandler - B OTG_HS_EP1_IN_IRQHandler - - PUBWEAK OTG_HS_WKUP_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -OTG_HS_WKUP_IRQHandler - B OTG_HS_WKUP_IRQHandler - - PUBWEAK OTG_HS_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -OTG_HS_IRQHandler - B OTG_HS_IRQHandler - - PUBWEAK DCMI_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -DCMI_IRQHandler - B DCMI_IRQHandler - - PUBWEAK CRYP_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -CRYP_IRQHandler - B CRYP_IRQHandler - - PUBWEAK HASH_RNG_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -HASH_RNG_IRQHandler - B HASH_RNG_IRQHandler - - PUBWEAK FPU_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -FPU_IRQHandler - B FPU_IRQHandler - - PUBWEAK UART7_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -UART7_IRQHandler - B UART7_IRQHandler - - PUBWEAK UART8_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -UART8_IRQHandler - B UART8_IRQHandler - - PUBWEAK SPI4_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -SPI4_IRQHandler - B SPI4_IRQHandler - - PUBWEAK SPI5_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -SPI5_IRQHandler - B SPI5_IRQHandler - - PUBWEAK SPI6_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -SPI6_IRQHandler - B SPI6_IRQHandler - - PUBWEAK SAI1_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -SAI1_IRQHandler - B SAI1_IRQHandler - - PUBWEAK DMA2D_IRQHandler - SECTION .text:CODE:REORDER:NOROOT(1) -DMA2D_IRQHandler - B DMA2D_IRQHandler - - - END -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ \ No newline at end of file diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/device/TOOLCHAIN_IAR/stm32f437xx.icf b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/device/TOOLCHAIN_IAR/stm32f437xx.icf deleted file mode 100644 index 5187ce3419a..00000000000 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/device/TOOLCHAIN_IAR/stm32f437xx.icf +++ /dev/null @@ -1,44 +0,0 @@ -/*###ICF### Section handled by ICF editor, don't touch! ****/ -/*-Editor annotation file-*/ -/* IcfEditorFile="$TOOLKIT_DIR$\config\ide\IcfEditor\cortex_v1_0.xml" */ -/*-Specials-*/ -define symbol __ICFEDIT_intvec_start__ = 0x08000000; -/*-Memory Regions-*/ -define symbol __ICFEDIT_region_ROM_start__ = 0x08000000; -define symbol __ICFEDIT_region_ROM_end__ = 0x080FFFFF; -define symbol __ICFEDIT_region_NVIC_start__ = 0x20000000; -define symbol __ICFEDIT_region_NVIC_end__ = 0x200001AF; -define symbol __ICFEDIT_region_RAM_start__ = 0x200001B0; -define symbol __ICFEDIT_region_RAM_end__ = 0x2002FFFF; -define symbol __ICFEDIT_region_CCMRAM_start__ = 0x10000000; -define symbol __ICFEDIT_region_CCMRAM_end__ = 0x1000FFFF; -define symbol __ICFEDIT_region_BKPSRAM_start__ = 0x40024000; -define symbol __ICFEDIT_region_BKPSRAM_end__ = 0x40024FFF; -/*-Sizes-*/ -/*Heap 1/2 of ram and ISR stack 4 kbytes*/ -define symbol __ICFEDIT_size_cstack__ = 0x1000; -define symbol __ICFEDIT_size_heap__ = 0x18000; -/**** End of ICF editor section. ###ICF###*/ - - -define memory mem with size = 4G; -define region ROM_region = mem:[from __ICFEDIT_region_ROM_start__ to __ICFEDIT_region_ROM_end__]; -define region RAM_region = mem:[from __ICFEDIT_region_RAM_start__ to __ICFEDIT_region_RAM_end__]; -define region CCMRAM_region = mem:[from __ICFEDIT_region_CCMRAM_start__ to __ICFEDIT_region_CCMRAM_end__]; -define region BKPSRAM_region = mem:[from __ICFEDIT_region_BKPSRAM_start__ to __ICFEDIT_region_BKPSRAM_end__]; - -define block CSTACK with alignment = 8, size = __ICFEDIT_size_cstack__ { }; -define block HEAP with alignment = 8, size = __ICFEDIT_size_heap__ { }; - -initialize by copy { readwrite }; -do not initialize { section .noinit }; -do not initialize { section CCMRAM }; -do not initialize { section BKPSRAM }; - -place at address mem:__ICFEDIT_intvec_start__ { readonly section .intvec }; - -place in ROM_region { readonly }; -place in RAM_region { readwrite, - block CSTACK, block HEAP }; -place in CCMRAM_region { section CCMRAM }; -place in BKPSRAM_region { section BKPSRAM }; diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/device/cmsis.h b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/device/cmsis.h deleted file mode 100644 index f0c2b2a9071..00000000000 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/device/cmsis.h +++ /dev/null @@ -1,38 +0,0 @@ -/* mbed Microcontroller Library - * A generic CMSIS include header - ******************************************************************************* - * Copyright (c) 2014, STMicroelectronics - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************* - */ - -#ifndef MBED_CMSIS_H -#define MBED_CMSIS_H - -#include "stm32f4xx.h" -#include "cmsis_nvic.h" - -#endif diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/device/cmsis_nvic.c b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/device/cmsis_nvic.c deleted file mode 100644 index 2da63fc9af8..00000000000 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/device/cmsis_nvic.c +++ /dev/null @@ -1,55 +0,0 @@ -/* mbed Microcontroller Library - * CMSIS-style functionality to support dynamic vectors - ******************************************************************************* - * Copyright (c) 2014, STMicroelectronics - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************* - */ -#include "cmsis_nvic.h" - -#define NVIC_RAM_VECTOR_ADDRESS (0x20000000) // Vectors positioned at start of RAM -#define NVIC_FLASH_VECTOR_ADDRESS (0x08000000) // Initial vector position in flash - -void NVIC_SetVector(IRQn_Type IRQn, uint32_t vector) { - uint32_t *vectors = (uint32_t *)SCB->VTOR; - uint32_t i; - - // Copy and switch to dynamic vectors if the first time called - if (SCB->VTOR == NVIC_FLASH_VECTOR_ADDRESS) { - uint32_t *old_vectors = vectors; - vectors = (uint32_t*)NVIC_RAM_VECTOR_ADDRESS; - for (i=0; iVTOR = (uint32_t)NVIC_RAM_VECTOR_ADDRESS; - } - vectors[IRQn + NVIC_USER_IRQ_OFFSET] = vector; -} - -uint32_t NVIC_GetVector(IRQn_Type IRQn) { - uint32_t *vectors = (uint32_t*)SCB->VTOR; - return vectors[IRQn + NVIC_USER_IRQ_OFFSET]; -} diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/device/cmsis_nvic.h b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/device/cmsis_nvic.h deleted file mode 100644 index f924f58fe74..00000000000 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/device/cmsis_nvic.h +++ /dev/null @@ -1,55 +0,0 @@ -/* mbed Microcontroller Library - * CMSIS-style functionality to support dynamic vectors - ******************************************************************************* - * Copyright (c) 2014, STMicroelectronics - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************* - */ - -#ifndef MBED_CMSIS_NVIC_H -#define MBED_CMSIS_NVIC_H - -// STM32F437VG -// CORE: 16 vectors = 64 bytes from 0x00 to 0x3F -// MCU Peripherals: 91 vectors = 364 bytes from 0x40 to 0x1AB -// Total: 107 vectors = 428 bytes (0x1AC) to be reserved in RAM -#define NVIC_NUM_VECTORS 107 -#define NVIC_USER_IRQ_OFFSET 16 - -#include "cmsis.h" - -#ifdef __cplusplus -extern "C" { -#endif - -void NVIC_SetVector(IRQn_Type IRQn, uint32_t vector); -uint32_t NVIC_GetVector(IRQn_Type IRQn); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/device/hal_tick.h b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/device/hal_tick.h deleted file mode 100644 index 00546265377..00000000000 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/device/hal_tick.h +++ /dev/null @@ -1,66 +0,0 @@ -/** - ****************************************************************************** - * @file hal_tick.h - * @author MCD Application Team - * @brief Initialization of HAL tick - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2014 STMicroelectronics

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ -#ifndef __HAL_TICK_H -#define __HAL_TICK_H - -#ifdef __cplusplus - extern "C" { -#endif - -#include "stm32f4xx.h" -#include "cmsis_nvic.h" - -#define TIM_MST TIM5 -#define TIM_MST_IRQ TIM5_IRQn -#define TIM_MST_RCC __TIM5_CLK_ENABLE() - -#define TIM_MST_RESET_ON __TIM5_FORCE_RESET() -#define TIM_MST_RESET_OFF __TIM5_RELEASE_RESET() - -#define TIM_MST_16BIT 0 // 1=16-bit timer, 0=32-bit timer - -#define TIM_MST_PCLK 1 // Select the peripheral clock number (1 or 2) - -#define HAL_TICK_DELAY (1000) // 1 ms - -void HAL_SuspendTick(void); - -#ifdef __cplusplus -} -#endif - -#endif // __HAL_TICK_H - -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/device/stm32f437xx.h b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/device/stm32f437xx.h deleted file mode 100644 index ba77fae51a1..00000000000 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/device/stm32f437xx.h +++ /dev/null @@ -1,16964 +0,0 @@ -/** - ****************************************************************************** - * @file stm32f437xx.h - * @author MCD Application Team - * @version V2.6.0 - * @date 04-November-2016 - * @brief CMSIS STM32F437xx Device Peripheral Access Layer Header File. - * - * This file contains: - * - Data structures and the address mapping for all peripherals - * - peripherals registers declarations and bits definition - * - Macros to access peripheral’s registers hardware - * - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2016 STMicroelectronics

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ - -/** @addtogroup CMSIS_Device - * @{ - */ - -/** @addtogroup stm32f437xx - * @{ - */ - -#ifndef __STM32F437xx_H -#define __STM32F437xx_H - -#ifdef __cplusplus - extern "C" { -#endif /* __cplusplus */ - -/** @addtogroup Configuration_section_for_CMSIS - * @{ - */ - -/** - * @brief Configuration of the Cortex-M4 Processor and Core Peripherals - */ -#define __CM4_REV 0x0001U /*!< Core revision r0p1 */ -#define __MPU_PRESENT 1U /*!< STM32F4XX provides an MPU */ -#define __NVIC_PRIO_BITS 4U /*!< STM32F4XX uses 4 Bits for the Priority Levels */ -#define __Vendor_SysTickConfig 0U /*!< Set to 1 if different SysTick Config is used */ -#ifndef __FPU_PRESENT -#define __FPU_PRESENT 1U /*!< FPU present */ -#endif /* __FPU_PRESENT */ - -/** - * @} - */ - -/** @addtogroup Peripheral_interrupt_number_definition - * @{ - */ - -/** - * @brief STM32F4XX Interrupt Number Definition, according to the selected device - * in @ref Library_configuration_section - */ -typedef enum -{ -/****** Cortex-M4 Processor Exceptions Numbers ****************************************************************/ - NonMaskableInt_IRQn = -14, /*!< 2 Non Maskable Interrupt */ - MemoryManagement_IRQn = -12, /*!< 4 Cortex-M4 Memory Management Interrupt */ - BusFault_IRQn = -11, /*!< 5 Cortex-M4 Bus Fault Interrupt */ - UsageFault_IRQn = -10, /*!< 6 Cortex-M4 Usage Fault Interrupt */ - SVCall_IRQn = -5, /*!< 11 Cortex-M4 SV Call Interrupt */ - DebugMonitor_IRQn = -4, /*!< 12 Cortex-M4 Debug Monitor Interrupt */ - PendSV_IRQn = -2, /*!< 14 Cortex-M4 Pend SV Interrupt */ - SysTick_IRQn = -1, /*!< 15 Cortex-M4 System Tick Interrupt */ -/****** STM32 specific Interrupt Numbers **********************************************************************/ - WWDG_IRQn = 0, /*!< Window WatchDog Interrupt */ - PVD_IRQn = 1, /*!< PVD through EXTI Line detection Interrupt */ - TAMP_STAMP_IRQn = 2, /*!< Tamper and TimeStamp interrupts through the EXTI line */ - RTC_WKUP_IRQn = 3, /*!< RTC Wakeup interrupt through the EXTI line */ - FLASH_IRQn = 4, /*!< FLASH global Interrupt */ - RCC_IRQn = 5, /*!< RCC global Interrupt */ - EXTI0_IRQn = 6, /*!< EXTI Line0 Interrupt */ - EXTI1_IRQn = 7, /*!< EXTI Line1 Interrupt */ - EXTI2_IRQn = 8, /*!< EXTI Line2 Interrupt */ - EXTI3_IRQn = 9, /*!< EXTI Line3 Interrupt */ - EXTI4_IRQn = 10, /*!< EXTI Line4 Interrupt */ - DMA1_Stream0_IRQn = 11, /*!< DMA1 Stream 0 global Interrupt */ - DMA1_Stream1_IRQn = 12, /*!< DMA1 Stream 1 global Interrupt */ - DMA1_Stream2_IRQn = 13, /*!< DMA1 Stream 2 global Interrupt */ - DMA1_Stream3_IRQn = 14, /*!< DMA1 Stream 3 global Interrupt */ - DMA1_Stream4_IRQn = 15, /*!< DMA1 Stream 4 global Interrupt */ - DMA1_Stream5_IRQn = 16, /*!< DMA1 Stream 5 global Interrupt */ - DMA1_Stream6_IRQn = 17, /*!< DMA1 Stream 6 global Interrupt */ - ADC_IRQn = 18, /*!< ADC1, ADC2 and ADC3 global Interrupts */ - CAN1_TX_IRQn = 19, /*!< CAN1 TX Interrupt */ - CAN1_RX0_IRQn = 20, /*!< CAN1 RX0 Interrupt */ - CAN1_RX1_IRQn = 21, /*!< CAN1 RX1 Interrupt */ - CAN1_SCE_IRQn = 22, /*!< CAN1 SCE Interrupt */ - EXTI9_5_IRQn = 23, /*!< External Line[9:5] Interrupts */ - TIM1_BRK_TIM9_IRQn = 24, /*!< TIM1 Break interrupt and TIM9 global interrupt */ - TIM1_UP_TIM10_IRQn = 25, /*!< TIM1 Update Interrupt and TIM10 global interrupt */ - TIM1_TRG_COM_TIM11_IRQn = 26, /*!< TIM1 Trigger and Commutation Interrupt and TIM11 global interrupt */ - TIM1_CC_IRQn = 27, /*!< TIM1 Capture Compare Interrupt */ - TIM2_IRQn = 28, /*!< TIM2 global Interrupt */ - TIM3_IRQn = 29, /*!< TIM3 global Interrupt */ - TIM4_IRQn = 30, /*!< TIM4 global Interrupt */ - I2C1_EV_IRQn = 31, /*!< I2C1 Event Interrupt */ - I2C1_ER_IRQn = 32, /*!< I2C1 Error Interrupt */ - I2C2_EV_IRQn = 33, /*!< I2C2 Event Interrupt */ - I2C2_ER_IRQn = 34, /*!< I2C2 Error Interrupt */ - SPI1_IRQn = 35, /*!< SPI1 global Interrupt */ - SPI2_IRQn = 36, /*!< SPI2 global Interrupt */ - USART1_IRQn = 37, /*!< USART1 global Interrupt */ - USART2_IRQn = 38, /*!< USART2 global Interrupt */ - USART3_IRQn = 39, /*!< USART3 global Interrupt */ - EXTI15_10_IRQn = 40, /*!< External Line[15:10] Interrupts */ - RTC_Alarm_IRQn = 41, /*!< RTC Alarm (A and B) through EXTI Line Interrupt */ - OTG_FS_WKUP_IRQn = 42, /*!< USB OTG FS Wakeup through EXTI line interrupt */ - TIM8_BRK_TIM12_IRQn = 43, /*!< TIM8 Break Interrupt and TIM12 global interrupt */ - TIM8_UP_TIM13_IRQn = 44, /*!< TIM8 Update Interrupt and TIM13 global interrupt */ - TIM8_TRG_COM_TIM14_IRQn = 45, /*!< TIM8 Trigger and Commutation Interrupt and TIM14 global interrupt */ - TIM8_CC_IRQn = 46, /*!< TIM8 Capture Compare global interrupt */ - DMA1_Stream7_IRQn = 47, /*!< DMA1 Stream7 Interrupt */ - FMC_IRQn = 48, /*!< FMC global Interrupt */ - SDIO_IRQn = 49, /*!< SDIO global Interrupt */ - TIM5_IRQn = 50, /*!< TIM5 global Interrupt */ - SPI3_IRQn = 51, /*!< SPI3 global Interrupt */ - UART4_IRQn = 52, /*!< UART4 global Interrupt */ - UART5_IRQn = 53, /*!< UART5 global Interrupt */ - TIM6_DAC_IRQn = 54, /*!< TIM6 global and DAC1&2 underrun error interrupts */ - TIM7_IRQn = 55, /*!< TIM7 global interrupt */ - DMA2_Stream0_IRQn = 56, /*!< DMA2 Stream 0 global Interrupt */ - DMA2_Stream1_IRQn = 57, /*!< DMA2 Stream 1 global Interrupt */ - DMA2_Stream2_IRQn = 58, /*!< DMA2 Stream 2 global Interrupt */ - DMA2_Stream3_IRQn = 59, /*!< DMA2 Stream 3 global Interrupt */ - DMA2_Stream4_IRQn = 60, /*!< DMA2 Stream 4 global Interrupt */ - ETH_IRQn = 61, /*!< Ethernet global Interrupt */ - ETH_WKUP_IRQn = 62, /*!< Ethernet Wakeup through EXTI line Interrupt */ - CAN2_TX_IRQn = 63, /*!< CAN2 TX Interrupt */ - CAN2_RX0_IRQn = 64, /*!< CAN2 RX0 Interrupt */ - CAN2_RX1_IRQn = 65, /*!< CAN2 RX1 Interrupt */ - CAN2_SCE_IRQn = 66, /*!< CAN2 SCE Interrupt */ - OTG_FS_IRQn = 67, /*!< USB OTG FS global Interrupt */ - DMA2_Stream5_IRQn = 68, /*!< DMA2 Stream 5 global interrupt */ - DMA2_Stream6_IRQn = 69, /*!< DMA2 Stream 6 global interrupt */ - DMA2_Stream7_IRQn = 70, /*!< DMA2 Stream 7 global interrupt */ - USART6_IRQn = 71, /*!< USART6 global interrupt */ - I2C3_EV_IRQn = 72, /*!< I2C3 event interrupt */ - I2C3_ER_IRQn = 73, /*!< I2C3 error interrupt */ - OTG_HS_EP1_OUT_IRQn = 74, /*!< USB OTG HS End Point 1 Out global interrupt */ - OTG_HS_EP1_IN_IRQn = 75, /*!< USB OTG HS End Point 1 In global interrupt */ - OTG_HS_WKUP_IRQn = 76, /*!< USB OTG HS Wakeup through EXTI interrupt */ - OTG_HS_IRQn = 77, /*!< USB OTG HS global interrupt */ - DCMI_IRQn = 78, /*!< DCMI global interrupt */ - CRYP_IRQn = 79, /*!< CRYP crypto global interrupt */ - HASH_RNG_IRQn = 80, /*!< Hash and Rng global interrupt */ - FPU_IRQn = 81, /*!< FPU global interrupt */ - UART7_IRQn = 82, /*!< UART7 global interrupt */ - UART8_IRQn = 83, /*!< UART8 global interrupt */ - SPI4_IRQn = 84, /*!< SPI4 global Interrupt */ - SPI5_IRQn = 85, /*!< SPI5 global Interrupt */ - SPI6_IRQn = 86, /*!< SPI6 global Interrupt */ - SAI1_IRQn = 87, /*!< SAI1 global Interrupt */ - DMA2D_IRQn = 90 /*!< DMA2D global Interrupt */ -} IRQn_Type; - -/** - * @} - */ - -#include "core_cm4.h" /* Cortex-M4 processor and core peripherals */ -#include "system_stm32f4xx.h" -#include - -/** @addtogroup Peripheral_registers_structures - * @{ - */ - -/** - * @brief Analog to Digital Converter - */ - -typedef struct -{ - __IO uint32_t SR; /*!< ADC status register, Address offset: 0x00 */ - __IO uint32_t CR1; /*!< ADC control register 1, Address offset: 0x04 */ - __IO uint32_t CR2; /*!< ADC control register 2, Address offset: 0x08 */ - __IO uint32_t SMPR1; /*!< ADC sample time register 1, Address offset: 0x0C */ - __IO uint32_t SMPR2; /*!< ADC sample time register 2, Address offset: 0x10 */ - __IO uint32_t JOFR1; /*!< ADC injected channel data offset register 1, Address offset: 0x14 */ - __IO uint32_t JOFR2; /*!< ADC injected channel data offset register 2, Address offset: 0x18 */ - __IO uint32_t JOFR3; /*!< ADC injected channel data offset register 3, Address offset: 0x1C */ - __IO uint32_t JOFR4; /*!< ADC injected channel data offset register 4, Address offset: 0x20 */ - __IO uint32_t HTR; /*!< ADC watchdog higher threshold register, Address offset: 0x24 */ - __IO uint32_t LTR; /*!< ADC watchdog lower threshold register, Address offset: 0x28 */ - __IO uint32_t SQR1; /*!< ADC regular sequence register 1, Address offset: 0x2C */ - __IO uint32_t SQR2; /*!< ADC regular sequence register 2, Address offset: 0x30 */ - __IO uint32_t SQR3; /*!< ADC regular sequence register 3, Address offset: 0x34 */ - __IO uint32_t JSQR; /*!< ADC injected sequence register, Address offset: 0x38*/ - __IO uint32_t JDR1; /*!< ADC injected data register 1, Address offset: 0x3C */ - __IO uint32_t JDR2; /*!< ADC injected data register 2, Address offset: 0x40 */ - __IO uint32_t JDR3; /*!< ADC injected data register 3, Address offset: 0x44 */ - __IO uint32_t JDR4; /*!< ADC injected data register 4, Address offset: 0x48 */ - __IO uint32_t DR; /*!< ADC regular data register, Address offset: 0x4C */ -} ADC_TypeDef; - -typedef struct -{ - __IO uint32_t CSR; /*!< ADC Common status register, Address offset: ADC1 base address + 0x300 */ - __IO uint32_t CCR; /*!< ADC common control register, Address offset: ADC1 base address + 0x304 */ - __IO uint32_t CDR; /*!< ADC common regular data register for dual - AND triple modes, Address offset: ADC1 base address + 0x308 */ -} ADC_Common_TypeDef; - - -/** - * @brief Controller Area Network TxMailBox - */ - -typedef struct -{ - __IO uint32_t TIR; /*!< CAN TX mailbox identifier register */ - __IO uint32_t TDTR; /*!< CAN mailbox data length control and time stamp register */ - __IO uint32_t TDLR; /*!< CAN mailbox data low register */ - __IO uint32_t TDHR; /*!< CAN mailbox data high register */ -} CAN_TxMailBox_TypeDef; - -/** - * @brief Controller Area Network FIFOMailBox - */ - -typedef struct -{ - __IO uint32_t RIR; /*!< CAN receive FIFO mailbox identifier register */ - __IO uint32_t RDTR; /*!< CAN receive FIFO mailbox data length control and time stamp register */ - __IO uint32_t RDLR; /*!< CAN receive FIFO mailbox data low register */ - __IO uint32_t RDHR; /*!< CAN receive FIFO mailbox data high register */ -} CAN_FIFOMailBox_TypeDef; - -/** - * @brief Controller Area Network FilterRegister - */ - -typedef struct -{ - __IO uint32_t FR1; /*!< CAN Filter bank register 1 */ - __IO uint32_t FR2; /*!< CAN Filter bank register 1 */ -} CAN_FilterRegister_TypeDef; - -/** - * @brief Controller Area Network - */ - -typedef struct -{ - __IO uint32_t MCR; /*!< CAN master control register, Address offset: 0x00 */ - __IO uint32_t MSR; /*!< CAN master status register, Address offset: 0x04 */ - __IO uint32_t TSR; /*!< CAN transmit status register, Address offset: 0x08 */ - __IO uint32_t RF0R; /*!< CAN receive FIFO 0 register, Address offset: 0x0C */ - __IO uint32_t RF1R; /*!< CAN receive FIFO 1 register, Address offset: 0x10 */ - __IO uint32_t IER; /*!< CAN interrupt enable register, Address offset: 0x14 */ - __IO uint32_t ESR; /*!< CAN error status register, Address offset: 0x18 */ - __IO uint32_t BTR; /*!< CAN bit timing register, Address offset: 0x1C */ - uint32_t RESERVED0[88]; /*!< Reserved, 0x020 - 0x17F */ - CAN_TxMailBox_TypeDef sTxMailBox[3]; /*!< CAN Tx MailBox, Address offset: 0x180 - 0x1AC */ - CAN_FIFOMailBox_TypeDef sFIFOMailBox[2]; /*!< CAN FIFO MailBox, Address offset: 0x1B0 - 0x1CC */ - uint32_t RESERVED1[12]; /*!< Reserved, 0x1D0 - 0x1FF */ - __IO uint32_t FMR; /*!< CAN filter master register, Address offset: 0x200 */ - __IO uint32_t FM1R; /*!< CAN filter mode register, Address offset: 0x204 */ - uint32_t RESERVED2; /*!< Reserved, 0x208 */ - __IO uint32_t FS1R; /*!< CAN filter scale register, Address offset: 0x20C */ - uint32_t RESERVED3; /*!< Reserved, 0x210 */ - __IO uint32_t FFA1R; /*!< CAN filter FIFO assignment register, Address offset: 0x214 */ - uint32_t RESERVED4; /*!< Reserved, 0x218 */ - __IO uint32_t FA1R; /*!< CAN filter activation register, Address offset: 0x21C */ - uint32_t RESERVED5[8]; /*!< Reserved, 0x220-0x23F */ - CAN_FilterRegister_TypeDef sFilterRegister[28]; /*!< CAN Filter Register, Address offset: 0x240-0x31C */ -} CAN_TypeDef; - -/** - * @brief CRC calculation unit - */ - -typedef struct -{ - __IO uint32_t DR; /*!< CRC Data register, Address offset: 0x00 */ - __IO uint8_t IDR; /*!< CRC Independent data register, Address offset: 0x04 */ - uint8_t RESERVED0; /*!< Reserved, 0x05 */ - uint16_t RESERVED1; /*!< Reserved, 0x06 */ - __IO uint32_t CR; /*!< CRC Control register, Address offset: 0x08 */ -} CRC_TypeDef; - -/** - * @brief Digital to Analog Converter - */ - -typedef struct -{ - __IO uint32_t CR; /*!< DAC control register, Address offset: 0x00 */ - __IO uint32_t SWTRIGR; /*!< DAC software trigger register, Address offset: 0x04 */ - __IO uint32_t DHR12R1; /*!< DAC channel1 12-bit right-aligned data holding register, Address offset: 0x08 */ - __IO uint32_t DHR12L1; /*!< DAC channel1 12-bit left aligned data holding register, Address offset: 0x0C */ - __IO uint32_t DHR8R1; /*!< DAC channel1 8-bit right aligned data holding register, Address offset: 0x10 */ - __IO uint32_t DHR12R2; /*!< DAC channel2 12-bit right aligned data holding register, Address offset: 0x14 */ - __IO uint32_t DHR12L2; /*!< DAC channel2 12-bit left aligned data holding register, Address offset: 0x18 */ - __IO uint32_t DHR8R2; /*!< DAC channel2 8-bit right-aligned data holding register, Address offset: 0x1C */ - __IO uint32_t DHR12RD; /*!< Dual DAC 12-bit right-aligned data holding register, Address offset: 0x20 */ - __IO uint32_t DHR12LD; /*!< DUAL DAC 12-bit left aligned data holding register, Address offset: 0x24 */ - __IO uint32_t DHR8RD; /*!< DUAL DAC 8-bit right aligned data holding register, Address offset: 0x28 */ - __IO uint32_t DOR1; /*!< DAC channel1 data output register, Address offset: 0x2C */ - __IO uint32_t DOR2; /*!< DAC channel2 data output register, Address offset: 0x30 */ - __IO uint32_t SR; /*!< DAC status register, Address offset: 0x34 */ -} DAC_TypeDef; - -/** - * @brief Debug MCU - */ - -typedef struct -{ - __IO uint32_t IDCODE; /*!< MCU device ID code, Address offset: 0x00 */ - __IO uint32_t CR; /*!< Debug MCU configuration register, Address offset: 0x04 */ - __IO uint32_t APB1FZ; /*!< Debug MCU APB1 freeze register, Address offset: 0x08 */ - __IO uint32_t APB2FZ; /*!< Debug MCU APB2 freeze register, Address offset: 0x0C */ -}DBGMCU_TypeDef; - -/** - * @brief DCMI - */ - -typedef struct -{ - __IO uint32_t CR; /*!< DCMI control register 1, Address offset: 0x00 */ - __IO uint32_t SR; /*!< DCMI status register, Address offset: 0x04 */ - __IO uint32_t RISR; /*!< DCMI raw interrupt status register, Address offset: 0x08 */ - __IO uint32_t IER; /*!< DCMI interrupt enable register, Address offset: 0x0C */ - __IO uint32_t MISR; /*!< DCMI masked interrupt status register, Address offset: 0x10 */ - __IO uint32_t ICR; /*!< DCMI interrupt clear register, Address offset: 0x14 */ - __IO uint32_t ESCR; /*!< DCMI embedded synchronization code register, Address offset: 0x18 */ - __IO uint32_t ESUR; /*!< DCMI embedded synchronization unmask register, Address offset: 0x1C */ - __IO uint32_t CWSTRTR; /*!< DCMI crop window start, Address offset: 0x20 */ - __IO uint32_t CWSIZER; /*!< DCMI crop window size, Address offset: 0x24 */ - __IO uint32_t DR; /*!< DCMI data register, Address offset: 0x28 */ -} DCMI_TypeDef; - -/** - * @brief DMA Controller - */ - -typedef struct -{ - __IO uint32_t CR; /*!< DMA stream x configuration register */ - __IO uint32_t NDTR; /*!< DMA stream x number of data register */ - __IO uint32_t PAR; /*!< DMA stream x peripheral address register */ - __IO uint32_t M0AR; /*!< DMA stream x memory 0 address register */ - __IO uint32_t M1AR; /*!< DMA stream x memory 1 address register */ - __IO uint32_t FCR; /*!< DMA stream x FIFO control register */ -} DMA_Stream_TypeDef; - -typedef struct -{ - __IO uint32_t LISR; /*!< DMA low interrupt status register, Address offset: 0x00 */ - __IO uint32_t HISR; /*!< DMA high interrupt status register, Address offset: 0x04 */ - __IO uint32_t LIFCR; /*!< DMA low interrupt flag clear register, Address offset: 0x08 */ - __IO uint32_t HIFCR; /*!< DMA high interrupt flag clear register, Address offset: 0x0C */ -} DMA_TypeDef; - -/** - * @brief DMA2D Controller - */ - -typedef struct -{ - __IO uint32_t CR; /*!< DMA2D Control Register, Address offset: 0x00 */ - __IO uint32_t ISR; /*!< DMA2D Interrupt Status Register, Address offset: 0x04 */ - __IO uint32_t IFCR; /*!< DMA2D Interrupt Flag Clear Register, Address offset: 0x08 */ - __IO uint32_t FGMAR; /*!< DMA2D Foreground Memory Address Register, Address offset: 0x0C */ - __IO uint32_t FGOR; /*!< DMA2D Foreground Offset Register, Address offset: 0x10 */ - __IO uint32_t BGMAR; /*!< DMA2D Background Memory Address Register, Address offset: 0x14 */ - __IO uint32_t BGOR; /*!< DMA2D Background Offset Register, Address offset: 0x18 */ - __IO uint32_t FGPFCCR; /*!< DMA2D Foreground PFC Control Register, Address offset: 0x1C */ - __IO uint32_t FGCOLR; /*!< DMA2D Foreground Color Register, Address offset: 0x20 */ - __IO uint32_t BGPFCCR; /*!< DMA2D Background PFC Control Register, Address offset: 0x24 */ - __IO uint32_t BGCOLR; /*!< DMA2D Background Color Register, Address offset: 0x28 */ - __IO uint32_t FGCMAR; /*!< DMA2D Foreground CLUT Memory Address Register, Address offset: 0x2C */ - __IO uint32_t BGCMAR; /*!< DMA2D Background CLUT Memory Address Register, Address offset: 0x30 */ - __IO uint32_t OPFCCR; /*!< DMA2D Output PFC Control Register, Address offset: 0x34 */ - __IO uint32_t OCOLR; /*!< DMA2D Output Color Register, Address offset: 0x38 */ - __IO uint32_t OMAR; /*!< DMA2D Output Memory Address Register, Address offset: 0x3C */ - __IO uint32_t OOR; /*!< DMA2D Output Offset Register, Address offset: 0x40 */ - __IO uint32_t NLR; /*!< DMA2D Number of Line Register, Address offset: 0x44 */ - __IO uint32_t LWR; /*!< DMA2D Line Watermark Register, Address offset: 0x48 */ - __IO uint32_t AMTCR; /*!< DMA2D AHB Master Timer Configuration Register, Address offset: 0x4C */ - uint32_t RESERVED[236]; /*!< Reserved, 0x50-0x3FF */ - __IO uint32_t FGCLUT[256]; /*!< DMA2D Foreground CLUT, Address offset:400-7FF */ - __IO uint32_t BGCLUT[256]; /*!< DMA2D Background CLUT, Address offset:800-BFF */ -} DMA2D_TypeDef; - -/** - * @brief Ethernet MAC - */ - -typedef struct -{ - __IO uint32_t MACCR; - __IO uint32_t MACFFR; - __IO uint32_t MACHTHR; - __IO uint32_t MACHTLR; - __IO uint32_t MACMIIAR; - __IO uint32_t MACMIIDR; - __IO uint32_t MACFCR; - __IO uint32_t MACVLANTR; /* 8 */ - uint32_t RESERVED0[2]; - __IO uint32_t MACRWUFFR; /* 11 */ - __IO uint32_t MACPMTCSR; - uint32_t RESERVED1; - __IO uint32_t MACDBGR; - __IO uint32_t MACSR; /* 15 */ - __IO uint32_t MACIMR; - __IO uint32_t MACA0HR; - __IO uint32_t MACA0LR; - __IO uint32_t MACA1HR; - __IO uint32_t MACA1LR; - __IO uint32_t MACA2HR; - __IO uint32_t MACA2LR; - __IO uint32_t MACA3HR; - __IO uint32_t MACA3LR; /* 24 */ - uint32_t RESERVED2[40]; - __IO uint32_t MMCCR; /* 65 */ - __IO uint32_t MMCRIR; - __IO uint32_t MMCTIR; - __IO uint32_t MMCRIMR; - __IO uint32_t MMCTIMR; /* 69 */ - uint32_t RESERVED3[14]; - __IO uint32_t MMCTGFSCCR; /* 84 */ - __IO uint32_t MMCTGFMSCCR; - uint32_t RESERVED4[5]; - __IO uint32_t MMCTGFCR; - uint32_t RESERVED5[10]; - __IO uint32_t MMCRFCECR; - __IO uint32_t MMCRFAECR; - uint32_t RESERVED6[10]; - __IO uint32_t MMCRGUFCR; - uint32_t RESERVED7[334]; - __IO uint32_t PTPTSCR; - __IO uint32_t PTPSSIR; - __IO uint32_t PTPTSHR; - __IO uint32_t PTPTSLR; - __IO uint32_t PTPTSHUR; - __IO uint32_t PTPTSLUR; - __IO uint32_t PTPTSAR; - __IO uint32_t PTPTTHR; - __IO uint32_t PTPTTLR; - __IO uint32_t RESERVED8; - __IO uint32_t PTPTSSR; - uint32_t RESERVED9[565]; - __IO uint32_t DMABMR; - __IO uint32_t DMATPDR; - __IO uint32_t DMARPDR; - __IO uint32_t DMARDLAR; - __IO uint32_t DMATDLAR; - __IO uint32_t DMASR; - __IO uint32_t DMAOMR; - __IO uint32_t DMAIER; - __IO uint32_t DMAMFBOCR; - __IO uint32_t DMARSWTR; - uint32_t RESERVED10[8]; - __IO uint32_t DMACHTDR; - __IO uint32_t DMACHRDR; - __IO uint32_t DMACHTBAR; - __IO uint32_t DMACHRBAR; -} ETH_TypeDef; - -/** - * @brief External Interrupt/Event Controller - */ - -typedef struct -{ - __IO uint32_t IMR; /*!< EXTI Interrupt mask register, Address offset: 0x00 */ - __IO uint32_t EMR; /*!< EXTI Event mask register, Address offset: 0x04 */ - __IO uint32_t RTSR; /*!< EXTI Rising trigger selection register, Address offset: 0x08 */ - __IO uint32_t FTSR; /*!< EXTI Falling trigger selection register, Address offset: 0x0C */ - __IO uint32_t SWIER; /*!< EXTI Software interrupt event register, Address offset: 0x10 */ - __IO uint32_t PR; /*!< EXTI Pending register, Address offset: 0x14 */ -} EXTI_TypeDef; - -/** - * @brief FLASH Registers - */ - -typedef struct -{ - __IO uint32_t ACR; /*!< FLASH access control register, Address offset: 0x00 */ - __IO uint32_t KEYR; /*!< FLASH key register, Address offset: 0x04 */ - __IO uint32_t OPTKEYR; /*!< FLASH option key register, Address offset: 0x08 */ - __IO uint32_t SR; /*!< FLASH status register, Address offset: 0x0C */ - __IO uint32_t CR; /*!< FLASH control register, Address offset: 0x10 */ - __IO uint32_t OPTCR; /*!< FLASH option control register , Address offset: 0x14 */ - __IO uint32_t OPTCR1; /*!< FLASH option control register 1, Address offset: 0x18 */ -} FLASH_TypeDef; - -/** - * @brief Flexible Memory Controller - */ - -typedef struct -{ - __IO uint32_t BTCR[8]; /*!< NOR/PSRAM chip-select control register(BCR) and chip-select timing register(BTR), Address offset: 0x00-1C */ -} FMC_Bank1_TypeDef; - -/** - * @brief Flexible Memory Controller Bank1E - */ - -typedef struct -{ - __IO uint32_t BWTR[7]; /*!< NOR/PSRAM write timing registers, Address offset: 0x104-0x11C */ -} FMC_Bank1E_TypeDef; -/** - * @brief Flexible Memory Controller Bank2 - */ - -typedef struct -{ - __IO uint32_t PCR2; /*!< NAND Flash control register 2, Address offset: 0x60 */ - __IO uint32_t SR2; /*!< NAND Flash FIFO status and interrupt register 2, Address offset: 0x64 */ - __IO uint32_t PMEM2; /*!< NAND Flash Common memory space timing register 2, Address offset: 0x68 */ - __IO uint32_t PATT2; /*!< NAND Flash Attribute memory space timing register 2, Address offset: 0x6C */ - uint32_t RESERVED0; /*!< Reserved, 0x70 */ - __IO uint32_t ECCR2; /*!< NAND Flash ECC result registers 2, Address offset: 0x74 */ - uint32_t RESERVED1; /*!< Reserved, 0x78 */ - uint32_t RESERVED2; /*!< Reserved, 0x7C */ - __IO uint32_t PCR3; /*!< NAND Flash control register 3, Address offset: 0x80 */ - __IO uint32_t SR3; /*!< NAND Flash FIFO status and interrupt register 3, Address offset: 0x84 */ - __IO uint32_t PMEM3; /*!< NAND Flash Common memory space timing register 3, Address offset: 0x88 */ - __IO uint32_t PATT3; /*!< NAND Flash Attribute memory space timing register 3, Address offset: 0x8C */ - uint32_t RESERVED3; /*!< Reserved, 0x90 */ - __IO uint32_t ECCR3; /*!< NAND Flash ECC result registers 3, Address offset: 0x94 */ -} FMC_Bank2_3_TypeDef; - -/** - * @brief Flexible Memory Controller Bank4 - */ - -typedef struct -{ - __IO uint32_t PCR4; /*!< PC Card control register 4, Address offset: 0xA0 */ - __IO uint32_t SR4; /*!< PC Card FIFO status and interrupt register 4, Address offset: 0xA4 */ - __IO uint32_t PMEM4; /*!< PC Card Common memory space timing register 4, Address offset: 0xA8 */ - __IO uint32_t PATT4; /*!< PC Card Attribute memory space timing register 4, Address offset: 0xAC */ - __IO uint32_t PIO4; /*!< PC Card I/O space timing register 4, Address offset: 0xB0 */ -} FMC_Bank4_TypeDef; - -/** - * @brief Flexible Memory Controller Bank5_6 - */ - -typedef struct -{ - __IO uint32_t SDCR[2]; /*!< SDRAM Control registers , Address offset: 0x140-0x144 */ - __IO uint32_t SDTR[2]; /*!< SDRAM Timing registers , Address offset: 0x148-0x14C */ - __IO uint32_t SDCMR; /*!< SDRAM Command Mode register, Address offset: 0x150 */ - __IO uint32_t SDRTR; /*!< SDRAM Refresh Timer register, Address offset: 0x154 */ - __IO uint32_t SDSR; /*!< SDRAM Status register, Address offset: 0x158 */ -} FMC_Bank5_6_TypeDef; - -/** - * @brief General Purpose I/O - */ - -typedef struct -{ - __IO uint32_t MODER; /*!< GPIO port mode register, Address offset: 0x00 */ - __IO uint32_t OTYPER; /*!< GPIO port output type register, Address offset: 0x04 */ - __IO uint32_t OSPEEDR; /*!< GPIO port output speed register, Address offset: 0x08 */ - __IO uint32_t PUPDR; /*!< GPIO port pull-up/pull-down register, Address offset: 0x0C */ - __IO uint32_t IDR; /*!< GPIO port input data register, Address offset: 0x10 */ - __IO uint32_t ODR; /*!< GPIO port output data register, Address offset: 0x14 */ - __IO uint32_t BSRR; /*!< GPIO port bit set/reset register, Address offset: 0x18 */ - __IO uint32_t LCKR; /*!< GPIO port configuration lock register, Address offset: 0x1C */ - __IO uint32_t AFR[2]; /*!< GPIO alternate function registers, Address offset: 0x20-0x24 */ -} GPIO_TypeDef; - -/** - * @brief System configuration controller - */ - -typedef struct -{ - __IO uint32_t MEMRMP; /*!< SYSCFG memory remap register, Address offset: 0x00 */ - __IO uint32_t PMC; /*!< SYSCFG peripheral mode configuration register, Address offset: 0x04 */ - __IO uint32_t EXTICR[4]; /*!< SYSCFG external interrupt configuration registers, Address offset: 0x08-0x14 */ - uint32_t RESERVED[2]; /*!< Reserved, 0x18-0x1C */ - __IO uint32_t CMPCR; /*!< SYSCFG Compensation cell control register, Address offset: 0x20 */ -} SYSCFG_TypeDef; - -/** - * @brief Inter-integrated Circuit Interface - */ - -typedef struct -{ - __IO uint32_t CR1; /*!< I2C Control register 1, Address offset: 0x00 */ - __IO uint32_t CR2; /*!< I2C Control register 2, Address offset: 0x04 */ - __IO uint32_t OAR1; /*!< I2C Own address register 1, Address offset: 0x08 */ - __IO uint32_t OAR2; /*!< I2C Own address register 2, Address offset: 0x0C */ - __IO uint32_t DR; /*!< I2C Data register, Address offset: 0x10 */ - __IO uint32_t SR1; /*!< I2C Status register 1, Address offset: 0x14 */ - __IO uint32_t SR2; /*!< I2C Status register 2, Address offset: 0x18 */ - __IO uint32_t CCR; /*!< I2C Clock control register, Address offset: 0x1C */ - __IO uint32_t TRISE; /*!< I2C TRISE register, Address offset: 0x20 */ - __IO uint32_t FLTR; /*!< I2C FLTR register, Address offset: 0x24 */ -} I2C_TypeDef; - -/** - * @brief Independent WATCHDOG - */ - -typedef struct -{ - __IO uint32_t KR; /*!< IWDG Key register, Address offset: 0x00 */ - __IO uint32_t PR; /*!< IWDG Prescaler register, Address offset: 0x04 */ - __IO uint32_t RLR; /*!< IWDG Reload register, Address offset: 0x08 */ - __IO uint32_t SR; /*!< IWDG Status register, Address offset: 0x0C */ -} IWDG_TypeDef; - - -/** - * @brief Power Control - */ - -typedef struct -{ - __IO uint32_t CR; /*!< PWR power control register, Address offset: 0x00 */ - __IO uint32_t CSR; /*!< PWR power control/status register, Address offset: 0x04 */ -} PWR_TypeDef; - -/** - * @brief Reset and Clock Control - */ - -typedef struct -{ - __IO uint32_t CR; /*!< RCC clock control register, Address offset: 0x00 */ - __IO uint32_t PLLCFGR; /*!< RCC PLL configuration register, Address offset: 0x04 */ - __IO uint32_t CFGR; /*!< RCC clock configuration register, Address offset: 0x08 */ - __IO uint32_t CIR; /*!< RCC clock interrupt register, Address offset: 0x0C */ - __IO uint32_t AHB1RSTR; /*!< RCC AHB1 peripheral reset register, Address offset: 0x10 */ - __IO uint32_t AHB2RSTR; /*!< RCC AHB2 peripheral reset register, Address offset: 0x14 */ - __IO uint32_t AHB3RSTR; /*!< RCC AHB3 peripheral reset register, Address offset: 0x18 */ - uint32_t RESERVED0; /*!< Reserved, 0x1C */ - __IO uint32_t APB1RSTR; /*!< RCC APB1 peripheral reset register, Address offset: 0x20 */ - __IO uint32_t APB2RSTR; /*!< RCC APB2 peripheral reset register, Address offset: 0x24 */ - uint32_t RESERVED1[2]; /*!< Reserved, 0x28-0x2C */ - __IO uint32_t AHB1ENR; /*!< RCC AHB1 peripheral clock register, Address offset: 0x30 */ - __IO uint32_t AHB2ENR; /*!< RCC AHB2 peripheral clock register, Address offset: 0x34 */ - __IO uint32_t AHB3ENR; /*!< RCC AHB3 peripheral clock register, Address offset: 0x38 */ - uint32_t RESERVED2; /*!< Reserved, 0x3C */ - __IO uint32_t APB1ENR; /*!< RCC APB1 peripheral clock enable register, Address offset: 0x40 */ - __IO uint32_t APB2ENR; /*!< RCC APB2 peripheral clock enable register, Address offset: 0x44 */ - uint32_t RESERVED3[2]; /*!< Reserved, 0x48-0x4C */ - __IO uint32_t AHB1LPENR; /*!< RCC AHB1 peripheral clock enable in low power mode register, Address offset: 0x50 */ - __IO uint32_t AHB2LPENR; /*!< RCC AHB2 peripheral clock enable in low power mode register, Address offset: 0x54 */ - __IO uint32_t AHB3LPENR; /*!< RCC AHB3 peripheral clock enable in low power mode register, Address offset: 0x58 */ - uint32_t RESERVED4; /*!< Reserved, 0x5C */ - __IO uint32_t APB1LPENR; /*!< RCC APB1 peripheral clock enable in low power mode register, Address offset: 0x60 */ - __IO uint32_t APB2LPENR; /*!< RCC APB2 peripheral clock enable in low power mode register, Address offset: 0x64 */ - uint32_t RESERVED5[2]; /*!< Reserved, 0x68-0x6C */ - __IO uint32_t BDCR; /*!< RCC Backup domain control register, Address offset: 0x70 */ - __IO uint32_t CSR; /*!< RCC clock control & status register, Address offset: 0x74 */ - uint32_t RESERVED6[2]; /*!< Reserved, 0x78-0x7C */ - __IO uint32_t SSCGR; /*!< RCC spread spectrum clock generation register, Address offset: 0x80 */ - __IO uint32_t PLLI2SCFGR; /*!< RCC PLLI2S configuration register, Address offset: 0x84 */ - __IO uint32_t PLLSAICFGR; /*!< RCC PLLSAI configuration register, Address offset: 0x88 */ - __IO uint32_t DCKCFGR; /*!< RCC Dedicated Clocks configuration register, Address offset: 0x8C */ -} RCC_TypeDef; - -/** - * @brief Real-Time Clock - */ - -typedef struct -{ - __IO uint32_t TR; /*!< RTC time register, Address offset: 0x00 */ - __IO uint32_t DR; /*!< RTC date register, Address offset: 0x04 */ - __IO uint32_t CR; /*!< RTC control register, Address offset: 0x08 */ - __IO uint32_t ISR; /*!< RTC initialization and status register, Address offset: 0x0C */ - __IO uint32_t PRER; /*!< RTC prescaler register, Address offset: 0x10 */ - __IO uint32_t WUTR; /*!< RTC wakeup timer register, Address offset: 0x14 */ - __IO uint32_t CALIBR; /*!< RTC calibration register, Address offset: 0x18 */ - __IO uint32_t ALRMAR; /*!< RTC alarm A register, Address offset: 0x1C */ - __IO uint32_t ALRMBR; /*!< RTC alarm B register, Address offset: 0x20 */ - __IO uint32_t WPR; /*!< RTC write protection register, Address offset: 0x24 */ - __IO uint32_t SSR; /*!< RTC sub second register, Address offset: 0x28 */ - __IO uint32_t SHIFTR; /*!< RTC shift control register, Address offset: 0x2C */ - __IO uint32_t TSTR; /*!< RTC time stamp time register, Address offset: 0x30 */ - __IO uint32_t TSDR; /*!< RTC time stamp date register, Address offset: 0x34 */ - __IO uint32_t TSSSR; /*!< RTC time-stamp sub second register, Address offset: 0x38 */ - __IO uint32_t CALR; /*!< RTC calibration register, Address offset: 0x3C */ - __IO uint32_t TAFCR; /*!< RTC tamper and alternate function configuration register, Address offset: 0x40 */ - __IO uint32_t ALRMASSR;/*!< RTC alarm A sub second register, Address offset: 0x44 */ - __IO uint32_t ALRMBSSR;/*!< RTC alarm B sub second register, Address offset: 0x48 */ - uint32_t RESERVED7; /*!< Reserved, 0x4C */ - __IO uint32_t BKP0R; /*!< RTC backup register 1, Address offset: 0x50 */ - __IO uint32_t BKP1R; /*!< RTC backup register 1, Address offset: 0x54 */ - __IO uint32_t BKP2R; /*!< RTC backup register 2, Address offset: 0x58 */ - __IO uint32_t BKP3R; /*!< RTC backup register 3, Address offset: 0x5C */ - __IO uint32_t BKP4R; /*!< RTC backup register 4, Address offset: 0x60 */ - __IO uint32_t BKP5R; /*!< RTC backup register 5, Address offset: 0x64 */ - __IO uint32_t BKP6R; /*!< RTC backup register 6, Address offset: 0x68 */ - __IO uint32_t BKP7R; /*!< RTC backup register 7, Address offset: 0x6C */ - __IO uint32_t BKP8R; /*!< RTC backup register 8, Address offset: 0x70 */ - __IO uint32_t BKP9R; /*!< RTC backup register 9, Address offset: 0x74 */ - __IO uint32_t BKP10R; /*!< RTC backup register 10, Address offset: 0x78 */ - __IO uint32_t BKP11R; /*!< RTC backup register 11, Address offset: 0x7C */ - __IO uint32_t BKP12R; /*!< RTC backup register 12, Address offset: 0x80 */ - __IO uint32_t BKP13R; /*!< RTC backup register 13, Address offset: 0x84 */ - __IO uint32_t BKP14R; /*!< RTC backup register 14, Address offset: 0x88 */ - __IO uint32_t BKP15R; /*!< RTC backup register 15, Address offset: 0x8C */ - __IO uint32_t BKP16R; /*!< RTC backup register 16, Address offset: 0x90 */ - __IO uint32_t BKP17R; /*!< RTC backup register 17, Address offset: 0x94 */ - __IO uint32_t BKP18R; /*!< RTC backup register 18, Address offset: 0x98 */ - __IO uint32_t BKP19R; /*!< RTC backup register 19, Address offset: 0x9C */ -} RTC_TypeDef; - -/** - * @brief Serial Audio Interface - */ - -typedef struct -{ - __IO uint32_t GCR; /*!< SAI global configuration register, Address offset: 0x00 */ -} SAI_TypeDef; - -typedef struct -{ - __IO uint32_t CR1; /*!< SAI block x configuration register 1, Address offset: 0x04 */ - __IO uint32_t CR2; /*!< SAI block x configuration register 2, Address offset: 0x08 */ - __IO uint32_t FRCR; /*!< SAI block x frame configuration register, Address offset: 0x0C */ - __IO uint32_t SLOTR; /*!< SAI block x slot register, Address offset: 0x10 */ - __IO uint32_t IMR; /*!< SAI block x interrupt mask register, Address offset: 0x14 */ - __IO uint32_t SR; /*!< SAI block x status register, Address offset: 0x18 */ - __IO uint32_t CLRFR; /*!< SAI block x clear flag register, Address offset: 0x1C */ - __IO uint32_t DR; /*!< SAI block x data register, Address offset: 0x20 */ -} SAI_Block_TypeDef; - -/** - * @brief SD host Interface - */ - -typedef struct -{ - __IO uint32_t POWER; /*!< SDIO power control register, Address offset: 0x00 */ - __IO uint32_t CLKCR; /*!< SDI clock control register, Address offset: 0x04 */ - __IO uint32_t ARG; /*!< SDIO argument register, Address offset: 0x08 */ - __IO uint32_t CMD; /*!< SDIO command register, Address offset: 0x0C */ - __IO const uint32_t RESPCMD; /*!< SDIO command response register, Address offset: 0x10 */ - __IO const uint32_t RESP1; /*!< SDIO response 1 register, Address offset: 0x14 */ - __IO const uint32_t RESP2; /*!< SDIO response 2 register, Address offset: 0x18 */ - __IO const uint32_t RESP3; /*!< SDIO response 3 register, Address offset: 0x1C */ - __IO const uint32_t RESP4; /*!< SDIO response 4 register, Address offset: 0x20 */ - __IO uint32_t DTIMER; /*!< SDIO data timer register, Address offset: 0x24 */ - __IO uint32_t DLEN; /*!< SDIO data length register, Address offset: 0x28 */ - __IO uint32_t DCTRL; /*!< SDIO data control register, Address offset: 0x2C */ - __IO const uint32_t DCOUNT; /*!< SDIO data counter register, Address offset: 0x30 */ - __IO const uint32_t STA; /*!< SDIO status register, Address offset: 0x34 */ - __IO uint32_t ICR; /*!< SDIO interrupt clear register, Address offset: 0x38 */ - __IO uint32_t MASK; /*!< SDIO mask register, Address offset: 0x3C */ - uint32_t RESERVED0[2]; /*!< Reserved, 0x40-0x44 */ - __IO const uint32_t FIFOCNT; /*!< SDIO FIFO counter register, Address offset: 0x48 */ - uint32_t RESERVED1[13]; /*!< Reserved, 0x4C-0x7C */ - __IO uint32_t FIFO; /*!< SDIO data FIFO register, Address offset: 0x80 */ -} SDIO_TypeDef; - -/** - * @brief Serial Peripheral Interface - */ - -typedef struct -{ - __IO uint32_t CR1; /*!< SPI control register 1 (not used in I2S mode), Address offset: 0x00 */ - __IO uint32_t CR2; /*!< SPI control register 2, Address offset: 0x04 */ - __IO uint32_t SR; /*!< SPI status register, Address offset: 0x08 */ - __IO uint32_t DR; /*!< SPI data register, Address offset: 0x0C */ - __IO uint32_t CRCPR; /*!< SPI CRC polynomial register (not used in I2S mode), Address offset: 0x10 */ - __IO uint32_t RXCRCR; /*!< SPI RX CRC register (not used in I2S mode), Address offset: 0x14 */ - __IO uint32_t TXCRCR; /*!< SPI TX CRC register (not used in I2S mode), Address offset: 0x18 */ - __IO uint32_t I2SCFGR; /*!< SPI_I2S configuration register, Address offset: 0x1C */ - __IO uint32_t I2SPR; /*!< SPI_I2S prescaler register, Address offset: 0x20 */ -} SPI_TypeDef; - - -/** - * @brief TIM - */ - -typedef struct -{ - __IO uint32_t CR1; /*!< TIM control register 1, Address offset: 0x00 */ - __IO uint32_t CR2; /*!< TIM control register 2, Address offset: 0x04 */ - __IO uint32_t SMCR; /*!< TIM slave mode control register, Address offset: 0x08 */ - __IO uint32_t DIER; /*!< TIM DMA/interrupt enable register, Address offset: 0x0C */ - __IO uint32_t SR; /*!< TIM status register, Address offset: 0x10 */ - __IO uint32_t EGR; /*!< TIM event generation register, Address offset: 0x14 */ - __IO uint32_t CCMR1; /*!< TIM capture/compare mode register 1, Address offset: 0x18 */ - __IO uint32_t CCMR2; /*!< TIM capture/compare mode register 2, Address offset: 0x1C */ - __IO uint32_t CCER; /*!< TIM capture/compare enable register, Address offset: 0x20 */ - __IO uint32_t CNT; /*!< TIM counter register, Address offset: 0x24 */ - __IO uint32_t PSC; /*!< TIM prescaler, Address offset: 0x28 */ - __IO uint32_t ARR; /*!< TIM auto-reload register, Address offset: 0x2C */ - __IO uint32_t RCR; /*!< TIM repetition counter register, Address offset: 0x30 */ - __IO uint32_t CCR1; /*!< TIM capture/compare register 1, Address offset: 0x34 */ - __IO uint32_t CCR2; /*!< TIM capture/compare register 2, Address offset: 0x38 */ - __IO uint32_t CCR3; /*!< TIM capture/compare register 3, Address offset: 0x3C */ - __IO uint32_t CCR4; /*!< TIM capture/compare register 4, Address offset: 0x40 */ - __IO uint32_t BDTR; /*!< TIM break and dead-time register, Address offset: 0x44 */ - __IO uint32_t DCR; /*!< TIM DMA control register, Address offset: 0x48 */ - __IO uint32_t DMAR; /*!< TIM DMA address for full transfer, Address offset: 0x4C */ - __IO uint32_t OR; /*!< TIM option register, Address offset: 0x50 */ -} TIM_TypeDef; - -/** - * @brief Universal Synchronous Asynchronous Receiver Transmitter - */ - -typedef struct -{ - __IO uint32_t SR; /*!< USART Status register, Address offset: 0x00 */ - __IO uint32_t DR; /*!< USART Data register, Address offset: 0x04 */ - __IO uint32_t BRR; /*!< USART Baud rate register, Address offset: 0x08 */ - __IO uint32_t CR1; /*!< USART Control register 1, Address offset: 0x0C */ - __IO uint32_t CR2; /*!< USART Control register 2, Address offset: 0x10 */ - __IO uint32_t CR3; /*!< USART Control register 3, Address offset: 0x14 */ - __IO uint32_t GTPR; /*!< USART Guard time and prescaler register, Address offset: 0x18 */ -} USART_TypeDef; - -/** - * @brief Window WATCHDOG - */ - -typedef struct -{ - __IO uint32_t CR; /*!< WWDG Control register, Address offset: 0x00 */ - __IO uint32_t CFR; /*!< WWDG Configuration register, Address offset: 0x04 */ - __IO uint32_t SR; /*!< WWDG Status register, Address offset: 0x08 */ -} WWDG_TypeDef; - -/** - * @brief Crypto Processor - */ - -typedef struct -{ - __IO uint32_t CR; /*!< CRYP control register, Address offset: 0x00 */ - __IO uint32_t SR; /*!< CRYP status register, Address offset: 0x04 */ - __IO uint32_t DR; /*!< CRYP data input register, Address offset: 0x08 */ - __IO uint32_t DOUT; /*!< CRYP data output register, Address offset: 0x0C */ - __IO uint32_t DMACR; /*!< CRYP DMA control register, Address offset: 0x10 */ - __IO uint32_t IMSCR; /*!< CRYP interrupt mask set/clear register, Address offset: 0x14 */ - __IO uint32_t RISR; /*!< CRYP raw interrupt status register, Address offset: 0x18 */ - __IO uint32_t MISR; /*!< CRYP masked interrupt status register, Address offset: 0x1C */ - __IO uint32_t K0LR; /*!< CRYP key left register 0, Address offset: 0x20 */ - __IO uint32_t K0RR; /*!< CRYP key right register 0, Address offset: 0x24 */ - __IO uint32_t K1LR; /*!< CRYP key left register 1, Address offset: 0x28 */ - __IO uint32_t K1RR; /*!< CRYP key right register 1, Address offset: 0x2C */ - __IO uint32_t K2LR; /*!< CRYP key left register 2, Address offset: 0x30 */ - __IO uint32_t K2RR; /*!< CRYP key right register 2, Address offset: 0x34 */ - __IO uint32_t K3LR; /*!< CRYP key left register 3, Address offset: 0x38 */ - __IO uint32_t K3RR; /*!< CRYP key right register 3, Address offset: 0x3C */ - __IO uint32_t IV0LR; /*!< CRYP initialization vector left-word register 0, Address offset: 0x40 */ - __IO uint32_t IV0RR; /*!< CRYP initialization vector right-word register 0, Address offset: 0x44 */ - __IO uint32_t IV1LR; /*!< CRYP initialization vector left-word register 1, Address offset: 0x48 */ - __IO uint32_t IV1RR; /*!< CRYP initialization vector right-word register 1, Address offset: 0x4C */ - __IO uint32_t CSGCMCCM0R; /*!< CRYP GCM/GMAC or CCM/CMAC context swap register 0, Address offset: 0x50 */ - __IO uint32_t CSGCMCCM1R; /*!< CRYP GCM/GMAC or CCM/CMAC context swap register 1, Address offset: 0x54 */ - __IO uint32_t CSGCMCCM2R; /*!< CRYP GCM/GMAC or CCM/CMAC context swap register 2, Address offset: 0x58 */ - __IO uint32_t CSGCMCCM3R; /*!< CRYP GCM/GMAC or CCM/CMAC context swap register 3, Address offset: 0x5C */ - __IO uint32_t CSGCMCCM4R; /*!< CRYP GCM/GMAC or CCM/CMAC context swap register 4, Address offset: 0x60 */ - __IO uint32_t CSGCMCCM5R; /*!< CRYP GCM/GMAC or CCM/CMAC context swap register 5, Address offset: 0x64 */ - __IO uint32_t CSGCMCCM6R; /*!< CRYP GCM/GMAC or CCM/CMAC context swap register 6, Address offset: 0x68 */ - __IO uint32_t CSGCMCCM7R; /*!< CRYP GCM/GMAC or CCM/CMAC context swap register 7, Address offset: 0x6C */ - __IO uint32_t CSGCM0R; /*!< CRYP GCM/GMAC context swap register 0, Address offset: 0x70 */ - __IO uint32_t CSGCM1R; /*!< CRYP GCM/GMAC context swap register 1, Address offset: 0x74 */ - __IO uint32_t CSGCM2R; /*!< CRYP GCM/GMAC context swap register 2, Address offset: 0x78 */ - __IO uint32_t CSGCM3R; /*!< CRYP GCM/GMAC context swap register 3, Address offset: 0x7C */ - __IO uint32_t CSGCM4R; /*!< CRYP GCM/GMAC context swap register 4, Address offset: 0x80 */ - __IO uint32_t CSGCM5R; /*!< CRYP GCM/GMAC context swap register 5, Address offset: 0x84 */ - __IO uint32_t CSGCM6R; /*!< CRYP GCM/GMAC context swap register 6, Address offset: 0x88 */ - __IO uint32_t CSGCM7R; /*!< CRYP GCM/GMAC context swap register 7, Address offset: 0x8C */ -} CRYP_TypeDef; - -/** - * @brief HASH - */ - -typedef struct -{ - __IO uint32_t CR; /*!< HASH control register, Address offset: 0x00 */ - __IO uint32_t DIN; /*!< HASH data input register, Address offset: 0x04 */ - __IO uint32_t STR; /*!< HASH start register, Address offset: 0x08 */ - __IO uint32_t HR[5]; /*!< HASH digest registers, Address offset: 0x0C-0x1C */ - __IO uint32_t IMR; /*!< HASH interrupt enable register, Address offset: 0x20 */ - __IO uint32_t SR; /*!< HASH status register, Address offset: 0x24 */ - uint32_t RESERVED[52]; /*!< Reserved, 0x28-0xF4 */ - __IO uint32_t CSR[54]; /*!< HASH context swap registers, Address offset: 0x0F8-0x1CC */ -} HASH_TypeDef; - -/** - * @brief HASH_DIGEST - */ - -typedef struct -{ - __IO uint32_t HR[8]; /*!< HASH digest registers, Address offset: 0x310-0x32C */ -} HASH_DIGEST_TypeDef; - -/** - * @brief RNG - */ - -typedef struct -{ - __IO uint32_t CR; /*!< RNG control register, Address offset: 0x00 */ - __IO uint32_t SR; /*!< RNG status register, Address offset: 0x04 */ - __IO uint32_t DR; /*!< RNG data register, Address offset: 0x08 */ -} RNG_TypeDef; - -/** - * @brief USB_OTG_Core_Registers - */ -typedef struct -{ - __IO uint32_t GOTGCTL; /*!< USB_OTG Control and Status Register 000h */ - __IO uint32_t GOTGINT; /*!< USB_OTG Interrupt Register 004h */ - __IO uint32_t GAHBCFG; /*!< Core AHB Configuration Register 008h */ - __IO uint32_t GUSBCFG; /*!< Core USB Configuration Register 00Ch */ - __IO uint32_t GRSTCTL; /*!< Core Reset Register 010h */ - __IO uint32_t GINTSTS; /*!< Core Interrupt Register 014h */ - __IO uint32_t GINTMSK; /*!< Core Interrupt Mask Register 018h */ - __IO uint32_t GRXSTSR; /*!< Receive Sts Q Read Register 01Ch */ - __IO uint32_t GRXSTSP; /*!< Receive Sts Q Read & POP Register 020h */ - __IO uint32_t GRXFSIZ; /*!< Receive FIFO Size Register 024h */ - __IO uint32_t DIEPTXF0_HNPTXFSIZ; /*!< EP0 / Non Periodic Tx FIFO Size Register 028h */ - __IO uint32_t HNPTXSTS; /*!< Non Periodic Tx FIFO/Queue Sts reg 02Ch */ - uint32_t Reserved30[2]; /*!< Reserved 030h */ - __IO uint32_t GCCFG; /*!< General Purpose IO Register 038h */ - __IO uint32_t CID; /*!< User ID Register 03Ch */ - uint32_t Reserved40[48]; /*!< Reserved 0x40-0xFF */ - __IO uint32_t HPTXFSIZ; /*!< Host Periodic Tx FIFO Size Reg 100h */ - __IO uint32_t DIEPTXF[0x0F]; /*!< dev Periodic Transmit FIFO */ -} USB_OTG_GlobalTypeDef; - -/** - * @brief USB_OTG_device_Registers - */ -typedef struct -{ - __IO uint32_t DCFG; /*!< dev Configuration Register 800h */ - __IO uint32_t DCTL; /*!< dev Control Register 804h */ - __IO uint32_t DSTS; /*!< dev Status Register (RO) 808h */ - uint32_t Reserved0C; /*!< Reserved 80Ch */ - __IO uint32_t DIEPMSK; /*!< dev IN Endpoint Mask 810h */ - __IO uint32_t DOEPMSK; /*!< dev OUT Endpoint Mask 814h */ - __IO uint32_t DAINT; /*!< dev All Endpoints Itr Reg 818h */ - __IO uint32_t DAINTMSK; /*!< dev All Endpoints Itr Mask 81Ch */ - uint32_t Reserved20; /*!< Reserved 820h */ - uint32_t Reserved9; /*!< Reserved 824h */ - __IO uint32_t DVBUSDIS; /*!< dev VBUS discharge Register 828h */ - __IO uint32_t DVBUSPULSE; /*!< dev VBUS Pulse Register 82Ch */ - __IO uint32_t DTHRCTL; /*!< dev threshold 830h */ - __IO uint32_t DIEPEMPMSK; /*!< dev empty msk 834h */ - __IO uint32_t DEACHINT; /*!< dedicated EP interrupt 838h */ - __IO uint32_t DEACHMSK; /*!< dedicated EP msk 83Ch */ - uint32_t Reserved40; /*!< dedicated EP mask 840h */ - __IO uint32_t DINEP1MSK; /*!< dedicated EP mask 844h */ - uint32_t Reserved44[15]; /*!< Reserved 844-87Ch */ - __IO uint32_t DOUTEP1MSK; /*!< dedicated EP msk 884h */ -} USB_OTG_DeviceTypeDef; - -/** - * @brief USB_OTG_IN_Endpoint-Specific_Register - */ -typedef struct -{ - __IO uint32_t DIEPCTL; /*!< dev IN Endpoint Control Reg 900h + (ep_num * 20h) + 00h */ - uint32_t Reserved04; /*!< Reserved 900h + (ep_num * 20h) + 04h */ - __IO uint32_t DIEPINT; /*!< dev IN Endpoint Itr Reg 900h + (ep_num * 20h) + 08h */ - uint32_t Reserved0C; /*!< Reserved 900h + (ep_num * 20h) + 0Ch */ - __IO uint32_t DIEPTSIZ; /*!< IN Endpoint Txfer Size 900h + (ep_num * 20h) + 10h */ - __IO uint32_t DIEPDMA; /*!< IN Endpoint DMA Address Reg 900h + (ep_num * 20h) + 14h */ - __IO uint32_t DTXFSTS; /*!< IN Endpoint Tx FIFO Status Reg 900h + (ep_num * 20h) + 18h */ - uint32_t Reserved18; /*!< Reserved 900h+(ep_num*20h)+1Ch-900h+ (ep_num * 20h) + 1Ch */ -} USB_OTG_INEndpointTypeDef; - -/** - * @brief USB_OTG_OUT_Endpoint-Specific_Registers - */ -typedef struct -{ - __IO uint32_t DOEPCTL; /*!< dev OUT Endpoint Control Reg B00h + (ep_num * 20h) + 00h */ - uint32_t Reserved04; /*!< Reserved B00h + (ep_num * 20h) + 04h */ - __IO uint32_t DOEPINT; /*!< dev OUT Endpoint Itr Reg B00h + (ep_num * 20h) + 08h */ - uint32_t Reserved0C; /*!< Reserved B00h + (ep_num * 20h) + 0Ch */ - __IO uint32_t DOEPTSIZ; /*!< dev OUT Endpoint Txfer Size B00h + (ep_num * 20h) + 10h */ - __IO uint32_t DOEPDMA; /*!< dev OUT Endpoint DMA Address B00h + (ep_num * 20h) + 14h */ - uint32_t Reserved18[2]; /*!< Reserved B00h + (ep_num * 20h) + 18h - B00h + (ep_num * 20h) + 1Ch */ -} USB_OTG_OUTEndpointTypeDef; - -/** - * @brief USB_OTG_Host_Mode_Register_Structures - */ -typedef struct -{ - __IO uint32_t HCFG; /*!< Host Configuration Register 400h */ - __IO uint32_t HFIR; /*!< Host Frame Interval Register 404h */ - __IO uint32_t HFNUM; /*!< Host Frame Nbr/Frame Remaining 408h */ - uint32_t Reserved40C; /*!< Reserved 40Ch */ - __IO uint32_t HPTXSTS; /*!< Host Periodic Tx FIFO/ Queue Status 410h */ - __IO uint32_t HAINT; /*!< Host All Channels Interrupt Register 414h */ - __IO uint32_t HAINTMSK; /*!< Host All Channels Interrupt Mask 418h */ -} USB_OTG_HostTypeDef; - -/** - * @brief USB_OTG_Host_Channel_Specific_Registers - */ -typedef struct -{ - __IO uint32_t HCCHAR; /*!< Host Channel Characteristics Register 500h */ - __IO uint32_t HCSPLT; /*!< Host Channel Split Control Register 504h */ - __IO uint32_t HCINT; /*!< Host Channel Interrupt Register 508h */ - __IO uint32_t HCINTMSK; /*!< Host Channel Interrupt Mask Register 50Ch */ - __IO uint32_t HCTSIZ; /*!< Host Channel Transfer Size Register 510h */ - __IO uint32_t HCDMA; /*!< Host Channel DMA Address Register 514h */ - uint32_t Reserved[2]; /*!< Reserved */ -} USB_OTG_HostChannelTypeDef; - -/** - * @} - */ - -/** @addtogroup Peripheral_memory_map - * @{ - */ -#define FLASH_BASE 0x08000000U /*!< FLASH(up to 2 MB) base address in the alias region */ -#define CCMDATARAM_BASE 0x10000000U /*!< CCM(core coupled memory) data RAM(64 KB) base address in the alias region */ -#define SRAM1_BASE 0x20000000U /*!< SRAM1(112 KB) base address in the alias region */ -#define SRAM2_BASE 0x2001C000U /*!< SRAM2(16 KB) base address in the alias region */ -#define SRAM3_BASE 0x20020000U /*!< SRAM3(64 KB) base address in the alias region */ -#define PERIPH_BASE 0x40000000U /*!< Peripheral base address in the alias region */ -#define BKPSRAM_BASE 0x40024000U /*!< Backup SRAM(4 KB) base address in the alias region */ -#define FMC_R_BASE 0xA0000000U /*!< FMC registers base address */ -#define SRAM1_BB_BASE 0x22000000U /*!< SRAM1(112 KB) base address in the bit-band region */ -#define SRAM2_BB_BASE 0x22380000U /*!< SRAM2(16 KB) base address in the bit-band region */ -#define SRAM3_BB_BASE 0x22400000U /*!< SRAM3(64 KB) base address in the bit-band region */ -#define PERIPH_BB_BASE 0x42000000U /*!< Peripheral base address in the bit-band region */ -#define BKPSRAM_BB_BASE 0x42480000U /*!< Backup SRAM(4 KB) base address in the bit-band region */ -#define FLASH_END 0x081FFFFFU /*!< FLASH end address */ -#define CCMDATARAM_END 0x1000FFFFU /*!< CCM data RAM end address */ - -/* Legacy defines */ -#define SRAM_BASE SRAM1_BASE -#define SRAM_BB_BASE SRAM1_BB_BASE - - -/*!< Peripheral memory map */ -#define APB1PERIPH_BASE PERIPH_BASE -#define APB2PERIPH_BASE (PERIPH_BASE + 0x00010000U) -#define AHB1PERIPH_BASE (PERIPH_BASE + 0x00020000U) -#define AHB2PERIPH_BASE (PERIPH_BASE + 0x10000000U) - -/*!< APB1 peripherals */ -#define TIM2_BASE (APB1PERIPH_BASE + 0x0000U) -#define TIM3_BASE (APB1PERIPH_BASE + 0x0400U) -#define TIM4_BASE (APB1PERIPH_BASE + 0x0800U) -#define TIM5_BASE (APB1PERIPH_BASE + 0x0C00U) -#define TIM6_BASE (APB1PERIPH_BASE + 0x1000U) -#define TIM7_BASE (APB1PERIPH_BASE + 0x1400U) -#define TIM12_BASE (APB1PERIPH_BASE + 0x1800U) -#define TIM13_BASE (APB1PERIPH_BASE + 0x1C00U) -#define TIM14_BASE (APB1PERIPH_BASE + 0x2000U) -#define RTC_BASE (APB1PERIPH_BASE + 0x2800U) -#define WWDG_BASE (APB1PERIPH_BASE + 0x2C00U) -#define IWDG_BASE (APB1PERIPH_BASE + 0x3000U) -#define I2S2ext_BASE (APB1PERIPH_BASE + 0x3400U) -#define SPI2_BASE (APB1PERIPH_BASE + 0x3800U) -#define SPI3_BASE (APB1PERIPH_BASE + 0x3C00U) -#define I2S3ext_BASE (APB1PERIPH_BASE + 0x4000U) -#define USART2_BASE (APB1PERIPH_BASE + 0x4400U) -#define USART3_BASE (APB1PERIPH_BASE + 0x4800U) -#define UART4_BASE (APB1PERIPH_BASE + 0x4C00U) -#define UART5_BASE (APB1PERIPH_BASE + 0x5000U) -#define I2C1_BASE (APB1PERIPH_BASE + 0x5400U) -#define I2C2_BASE (APB1PERIPH_BASE + 0x5800U) -#define I2C3_BASE (APB1PERIPH_BASE + 0x5C00U) -#define CAN1_BASE (APB1PERIPH_BASE + 0x6400U) -#define CAN2_BASE (APB1PERIPH_BASE + 0x6800U) -#define PWR_BASE (APB1PERIPH_BASE + 0x7000U) -#define DAC_BASE (APB1PERIPH_BASE + 0x7400U) -#define UART7_BASE (APB1PERIPH_BASE + 0x7800U) -#define UART8_BASE (APB1PERIPH_BASE + 0x7C00U) - -/*!< APB2 peripherals */ -#define TIM1_BASE (APB2PERIPH_BASE + 0x0000U) -#define TIM8_BASE (APB2PERIPH_BASE + 0x0400U) -#define USART1_BASE (APB2PERIPH_BASE + 0x1000U) -#define USART6_BASE (APB2PERIPH_BASE + 0x1400U) -#define ADC1_BASE (APB2PERIPH_BASE + 0x2000U) -#define ADC2_BASE (APB2PERIPH_BASE + 0x2100U) -#define ADC3_BASE (APB2PERIPH_BASE + 0x2200U) -#define ADC_BASE (APB2PERIPH_BASE + 0x2300U) -#define SDIO_BASE (APB2PERIPH_BASE + 0x2C00U) -#define SPI1_BASE (APB2PERIPH_BASE + 0x3000U) -#define SPI4_BASE (APB2PERIPH_BASE + 0x3400U) -#define SYSCFG_BASE (APB2PERIPH_BASE + 0x3800U) -#define EXTI_BASE (APB2PERIPH_BASE + 0x3C00U) -#define TIM9_BASE (APB2PERIPH_BASE + 0x4000U) -#define TIM10_BASE (APB2PERIPH_BASE + 0x4400U) -#define TIM11_BASE (APB2PERIPH_BASE + 0x4800U) -#define SPI5_BASE (APB2PERIPH_BASE + 0x5000U) -#define SPI6_BASE (APB2PERIPH_BASE + 0x5400U) -#define SAI1_BASE (APB2PERIPH_BASE + 0x5800U) -#define SAI1_Block_A_BASE (SAI1_BASE + 0x004U) -#define SAI1_Block_B_BASE (SAI1_BASE + 0x024U) - -/*!< AHB1 peripherals */ -#define GPIOA_BASE (AHB1PERIPH_BASE + 0x0000U) -#define GPIOB_BASE (AHB1PERIPH_BASE + 0x0400U) -#define GPIOC_BASE (AHB1PERIPH_BASE + 0x0800U) -#define GPIOD_BASE (AHB1PERIPH_BASE + 0x0C00U) -#define GPIOE_BASE (AHB1PERIPH_BASE + 0x1000U) -#define GPIOF_BASE (AHB1PERIPH_BASE + 0x1400U) -#define GPIOG_BASE (AHB1PERIPH_BASE + 0x1800U) -#define GPIOH_BASE (AHB1PERIPH_BASE + 0x1C00U) -#define GPIOI_BASE (AHB1PERIPH_BASE + 0x2000U) -#define GPIOJ_BASE (AHB1PERIPH_BASE + 0x2400U) -#define GPIOK_BASE (AHB1PERIPH_BASE + 0x2800U) -#define CRC_BASE (AHB1PERIPH_BASE + 0x3000U) -#define RCC_BASE (AHB1PERIPH_BASE + 0x3800U) -#define FLASH_R_BASE (AHB1PERIPH_BASE + 0x3C00U) -#define DMA1_BASE (AHB1PERIPH_BASE + 0x6000U) -#define DMA1_Stream0_BASE (DMA1_BASE + 0x010U) -#define DMA1_Stream1_BASE (DMA1_BASE + 0x028U) -#define DMA1_Stream2_BASE (DMA1_BASE + 0x040U) -#define DMA1_Stream3_BASE (DMA1_BASE + 0x058U) -#define DMA1_Stream4_BASE (DMA1_BASE + 0x070U) -#define DMA1_Stream5_BASE (DMA1_BASE + 0x088U) -#define DMA1_Stream6_BASE (DMA1_BASE + 0x0A0U) -#define DMA1_Stream7_BASE (DMA1_BASE + 0x0B8U) -#define DMA2_BASE (AHB1PERIPH_BASE + 0x6400U) -#define DMA2_Stream0_BASE (DMA2_BASE + 0x010U) -#define DMA2_Stream1_BASE (DMA2_BASE + 0x028U) -#define DMA2_Stream2_BASE (DMA2_BASE + 0x040U) -#define DMA2_Stream3_BASE (DMA2_BASE + 0x058U) -#define DMA2_Stream4_BASE (DMA2_BASE + 0x070U) -#define DMA2_Stream5_BASE (DMA2_BASE + 0x088U) -#define DMA2_Stream6_BASE (DMA2_BASE + 0x0A0U) -#define DMA2_Stream7_BASE (DMA2_BASE + 0x0B8U) -#define ETH_BASE (AHB1PERIPH_BASE + 0x8000U) -#define ETH_MAC_BASE (ETH_BASE) -#define ETH_MMC_BASE (ETH_BASE + 0x0100U) -#define ETH_PTP_BASE (ETH_BASE + 0x0700U) -#define ETH_DMA_BASE (ETH_BASE + 0x1000U) -#define DMA2D_BASE (AHB1PERIPH_BASE + 0xB000U) - -/*!< AHB2 peripherals */ -#define DCMI_BASE (AHB2PERIPH_BASE + 0x50000U) -#define CRYP_BASE (AHB2PERIPH_BASE + 0x60000U) -#define HASH_BASE (AHB2PERIPH_BASE + 0x60400U) -#define HASH_DIGEST_BASE (AHB2PERIPH_BASE + 0x60710U) -#define RNG_BASE (AHB2PERIPH_BASE + 0x60800U) - -/*!< FMC Bankx registers base address */ -#define FMC_Bank1_R_BASE (FMC_R_BASE + 0x0000U) -#define FMC_Bank1E_R_BASE (FMC_R_BASE + 0x0104U) -#define FMC_Bank2_3_R_BASE (FMC_R_BASE + 0x0060U) -#define FMC_Bank4_R_BASE (FMC_R_BASE + 0x00A0U) -#define FMC_Bank5_6_R_BASE (FMC_R_BASE + 0x0140U) - - -/*!< Debug MCU registers base address */ -#define DBGMCU_BASE 0xE0042000U -/*!< USB registers base address */ -#define USB_OTG_HS_PERIPH_BASE 0x40040000U -#define USB_OTG_FS_PERIPH_BASE 0x50000000U - -#define USB_OTG_GLOBAL_BASE 0x000U -#define USB_OTG_DEVICE_BASE 0x800U -#define USB_OTG_IN_ENDPOINT_BASE 0x900U -#define USB_OTG_OUT_ENDPOINT_BASE 0xB00U -#define USB_OTG_EP_REG_SIZE 0x20U -#define USB_OTG_HOST_BASE 0x400U -#define USB_OTG_HOST_PORT_BASE 0x440U -#define USB_OTG_HOST_CHANNEL_BASE 0x500U -#define USB_OTG_HOST_CHANNEL_SIZE 0x20U -#define USB_OTG_PCGCCTL_BASE 0xE00U -#define USB_OTG_FIFO_BASE 0x1000U -#define USB_OTG_FIFO_SIZE 0x1000U - -#define UID_BASE 0x1FFF7A10U /*!< Unique device ID register base address */ -#define FLASHSIZE_BASE 0x1FFF7A22U /*!< FLASH Size register base address */ -#define PACKAGE_BASE 0x1FFF7BF0U /*!< Package size register base address */ -/** - * @} - */ - -/** @addtogroup Peripheral_declaration - * @{ - */ -#define TIM2 ((TIM_TypeDef *) TIM2_BASE) -#define TIM3 ((TIM_TypeDef *) TIM3_BASE) -#define TIM4 ((TIM_TypeDef *) TIM4_BASE) -#define TIM5 ((TIM_TypeDef *) TIM5_BASE) -#define TIM6 ((TIM_TypeDef *) TIM6_BASE) -#define TIM7 ((TIM_TypeDef *) TIM7_BASE) -#define TIM12 ((TIM_TypeDef *) TIM12_BASE) -#define TIM13 ((TIM_TypeDef *) TIM13_BASE) -#define TIM14 ((TIM_TypeDef *) TIM14_BASE) -#define RTC ((RTC_TypeDef *) RTC_BASE) -#define WWDG ((WWDG_TypeDef *) WWDG_BASE) -#define IWDG ((IWDG_TypeDef *) IWDG_BASE) -#define I2S2ext ((SPI_TypeDef *) I2S2ext_BASE) -#define SPI2 ((SPI_TypeDef *) SPI2_BASE) -#define SPI3 ((SPI_TypeDef *) SPI3_BASE) -#define I2S3ext ((SPI_TypeDef *) I2S3ext_BASE) -#define USART2 ((USART_TypeDef *) USART2_BASE) -#define USART3 ((USART_TypeDef *) USART3_BASE) -#define UART4 ((USART_TypeDef *) UART4_BASE) -#define UART5 ((USART_TypeDef *) UART5_BASE) -#define I2C1 ((I2C_TypeDef *) I2C1_BASE) -#define I2C2 ((I2C_TypeDef *) I2C2_BASE) -#define I2C3 ((I2C_TypeDef *) I2C3_BASE) -#define CAN1 ((CAN_TypeDef *) CAN1_BASE) -#define CAN2 ((CAN_TypeDef *) CAN2_BASE) -#define PWR ((PWR_TypeDef *) PWR_BASE) -#define DAC1 ((DAC_TypeDef *) DAC_BASE) -#define DAC ((DAC_TypeDef *) DAC_BASE) /* Kept for legacy purpose */ -#define UART7 ((USART_TypeDef *) UART7_BASE) -#define UART8 ((USART_TypeDef *) UART8_BASE) -#define TIM1 ((TIM_TypeDef *) TIM1_BASE) -#define TIM8 ((TIM_TypeDef *) TIM8_BASE) -#define USART1 ((USART_TypeDef *) USART1_BASE) -#define USART6 ((USART_TypeDef *) USART6_BASE) -#define ADC ((ADC_Common_TypeDef *) ADC_BASE) -#define ADC1 ((ADC_TypeDef *) ADC1_BASE) -#define ADC2 ((ADC_TypeDef *) ADC2_BASE) -#define ADC3 ((ADC_TypeDef *) ADC3_BASE) -#define SDIO ((SDIO_TypeDef *) SDIO_BASE) -#define SPI1 ((SPI_TypeDef *) SPI1_BASE) -#define SPI4 ((SPI_TypeDef *) SPI4_BASE) -#define SYSCFG ((SYSCFG_TypeDef *) SYSCFG_BASE) -#define EXTI ((EXTI_TypeDef *) EXTI_BASE) -#define TIM9 ((TIM_TypeDef *) TIM9_BASE) -#define TIM10 ((TIM_TypeDef *) TIM10_BASE) -#define TIM11 ((TIM_TypeDef *) TIM11_BASE) -#define SPI5 ((SPI_TypeDef *) SPI5_BASE) -#define SPI6 ((SPI_TypeDef *) SPI6_BASE) -#define SAI1 ((SAI_TypeDef *) SAI1_BASE) -#define SAI1_Block_A ((SAI_Block_TypeDef *)SAI1_Block_A_BASE) -#define SAI1_Block_B ((SAI_Block_TypeDef *)SAI1_Block_B_BASE) -#define GPIOA ((GPIO_TypeDef *) GPIOA_BASE) -#define GPIOB ((GPIO_TypeDef *) GPIOB_BASE) -#define GPIOC ((GPIO_TypeDef *) GPIOC_BASE) -#define GPIOD ((GPIO_TypeDef *) GPIOD_BASE) -#define GPIOE ((GPIO_TypeDef *) GPIOE_BASE) -#define GPIOF ((GPIO_TypeDef *) GPIOF_BASE) -#define GPIOG ((GPIO_TypeDef *) GPIOG_BASE) -#define GPIOH ((GPIO_TypeDef *) GPIOH_BASE) -#define GPIOI ((GPIO_TypeDef *) GPIOI_BASE) -#define GPIOJ ((GPIO_TypeDef *) GPIOJ_BASE) -#define GPIOK ((GPIO_TypeDef *) GPIOK_BASE) -#define CRC ((CRC_TypeDef *) CRC_BASE) -#define RCC ((RCC_TypeDef *) RCC_BASE) -#define FLASH ((FLASH_TypeDef *) FLASH_R_BASE) -#define DMA1 ((DMA_TypeDef *) DMA1_BASE) -#define DMA1_Stream0 ((DMA_Stream_TypeDef *) DMA1_Stream0_BASE) -#define DMA1_Stream1 ((DMA_Stream_TypeDef *) DMA1_Stream1_BASE) -#define DMA1_Stream2 ((DMA_Stream_TypeDef *) DMA1_Stream2_BASE) -#define DMA1_Stream3 ((DMA_Stream_TypeDef *) DMA1_Stream3_BASE) -#define DMA1_Stream4 ((DMA_Stream_TypeDef *) DMA1_Stream4_BASE) -#define DMA1_Stream5 ((DMA_Stream_TypeDef *) DMA1_Stream5_BASE) -#define DMA1_Stream6 ((DMA_Stream_TypeDef *) DMA1_Stream6_BASE) -#define DMA1_Stream7 ((DMA_Stream_TypeDef *) DMA1_Stream7_BASE) -#define DMA2 ((DMA_TypeDef *) DMA2_BASE) -#define DMA2_Stream0 ((DMA_Stream_TypeDef *) DMA2_Stream0_BASE) -#define DMA2_Stream1 ((DMA_Stream_TypeDef *) DMA2_Stream1_BASE) -#define DMA2_Stream2 ((DMA_Stream_TypeDef *) DMA2_Stream2_BASE) -#define DMA2_Stream3 ((DMA_Stream_TypeDef *) DMA2_Stream3_BASE) -#define DMA2_Stream4 ((DMA_Stream_TypeDef *) DMA2_Stream4_BASE) -#define DMA2_Stream5 ((DMA_Stream_TypeDef *) DMA2_Stream5_BASE) -#define DMA2_Stream6 ((DMA_Stream_TypeDef *) DMA2_Stream6_BASE) -#define DMA2_Stream7 ((DMA_Stream_TypeDef *) DMA2_Stream7_BASE) -#define ETH ((ETH_TypeDef *) ETH_BASE) -#define DMA2D ((DMA2D_TypeDef *)DMA2D_BASE) -#define DCMI ((DCMI_TypeDef *) DCMI_BASE) -#define CRYP ((CRYP_TypeDef *) CRYP_BASE) -#define HASH ((HASH_TypeDef *) HASH_BASE) -#define HASH_DIGEST ((HASH_DIGEST_TypeDef *) HASH_DIGEST_BASE) -#define RNG ((RNG_TypeDef *) RNG_BASE) -#define FMC_Bank1 ((FMC_Bank1_TypeDef *) FMC_Bank1_R_BASE) -#define FMC_Bank1E ((FMC_Bank1E_TypeDef *) FMC_Bank1E_R_BASE) -#define FMC_Bank2_3 ((FMC_Bank2_3_TypeDef *) FMC_Bank2_3_R_BASE) -#define FMC_Bank4 ((FMC_Bank4_TypeDef *) FMC_Bank4_R_BASE) -#define FMC_Bank5_6 ((FMC_Bank5_6_TypeDef *) FMC_Bank5_6_R_BASE) -#define DBGMCU ((DBGMCU_TypeDef *) DBGMCU_BASE) -#define USB_OTG_FS ((USB_OTG_GlobalTypeDef *) USB_OTG_FS_PERIPH_BASE) -#define USB_OTG_HS ((USB_OTG_GlobalTypeDef *) USB_OTG_HS_PERIPH_BASE) - -/** - * @} - */ - -/** @addtogroup Exported_constants - * @{ - */ - - /** @addtogroup Peripheral_Registers_Bits_Definition - * @{ - */ - -/******************************************************************************/ -/* Peripheral Registers_Bits_Definition */ -/******************************************************************************/ - -/******************************************************************************/ -/* */ -/* Analog to Digital Converter */ -/* */ -/******************************************************************************/ -/******************** Bit definition for ADC_SR register ********************/ -#define ADC_SR_AWD_Pos (0U) -#define ADC_SR_AWD_Msk (0x1U << ADC_SR_AWD_Pos) /*!< 0x00000001 */ -#define ADC_SR_AWD ADC_SR_AWD_Msk /*!
© COPYRIGHT(c) 2016 STMicroelectronics

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ - -/** @addtogroup CMSIS - * @{ - */ - -/** @addtogroup stm32f4xx - * @{ - */ - -#ifndef __STM32F4xx_H -#define __STM32F4xx_H - -#ifdef __cplusplus - extern "C" { -#endif /* __cplusplus */ - -/** @addtogroup Library_configuration_section - * @{ - */ - -/** - * @brief STM32 Family - */ -#if !defined (STM32F4) -#define STM32F4 -#endif /* STM32F4 */ - -/* Uncomment the line below according to the target STM32 device used in your - application - */ -#if !defined (STM32F405xx) && !defined (STM32F415xx) && !defined (STM32F407xx) && !defined (STM32F417xx) && \ - !defined (STM32F427xx) && !defined (STM32F437xx) && !defined (STM32F429xx) && !defined (STM32F439xx) && \ - !defined (STM32F401xC) && !defined (STM32F401xE) && !defined (STM32F410Tx) && !defined (STM32F410Cx) && \ - !defined (STM32F410Rx) && !defined (STM32F411xE) && !defined (STM32F446xx) && !defined (STM32F469xx) && \ - !defined (STM32F479xx) && !defined (STM32F412Cx) && !defined (STM32F412Rx) && !defined (STM32F412Vx) && \ - !defined (STM32F412Zx) && !defined (STM32F413xx) && !defined (STM32F423xx) - /* #define STM32F405xx */ /*!< STM32F405RG, STM32F405VG and STM32F405ZG Devices */ - /* #define STM32F415xx */ /*!< STM32F415RG, STM32F415VG and STM32F415ZG Devices */ - /* #define STM32F407xx */ /*!< STM32F407VG, STM32F407VE, STM32F407ZG, STM32F407ZE, STM32F407IG and STM32F407IE Devices */ - /* #define STM32F417xx */ /*!< STM32F417VG, STM32F417VE, STM32F417ZG, STM32F417ZE, STM32F417IG and STM32F417IE Devices */ - /* #define STM32F427xx */ /*!< STM32F427VG, STM32F427VI, STM32F427ZG, STM32F427ZI, STM32F427IG and STM32F427II Devices */ - #define STM32F437xx /*!< STM32F437VG, STM32F437VI, STM32F437ZG, STM32F437ZI, STM32F437IG and STM32F437II Devices */ - /* #define STM32F429xx */ /*!< STM32F429VG, STM32F429VI, STM32F429ZG, STM32F429ZI, STM32F429BG, STM32F429BI, STM32F429NG, - STM32F439NI, STM32F429IG and STM32F429II Devices */ - /* #define STM32F439xx */ /*!< STM32F439VG, STM32F439VI, STM32F439ZG, STM32F439ZI, STM32F439BG, STM32F439BI, STM32F439NG, - STM32F439NI, STM32F439IG and STM32F439II Devices */ - /* #define STM32F401xC */ /*!< STM32F401CB, STM32F401CC, STM32F401RB, STM32F401RC, STM32F401VB and STM32F401VC Devices */ - /* #define STM32F401xE */ /*!< STM32F401CD, STM32F401RD, STM32F401VD, STM32F401CE, STM32F401RE and STM32F401VE Devices */ - /* #define STM32F410Tx */ /*!< STM32F410T8 and STM32F410TB Devices */ - /* #define STM32F410Cx */ /*!< STM32F410C8 and STM32F410CB Devices */ - /* #define STM32F410Rx */ /*!< STM32F410R8 and STM32F410RB Devices */ - /* #define STM32F411xE */ /*!< STM32F411CC, STM32F411RC, STM32F411VC, STM32F411CE, STM32F411RE and STM32F411VE Devices */ - /* #define STM32F446xx */ /*!< STM32F446MC, STM32F446ME, STM32F446RC, STM32F446RE, STM32F446VC, STM32F446VE, STM32F446ZC, - and STM32F446ZE Devices */ - /* #define STM32F469xx */ /*!< STM32F469AI, STM32F469II, STM32F469BI, STM32F469NI, STM32F469AG, STM32F469IG, STM32F469BG, - STM32F469NG, STM32F469AE, STM32F469IE, STM32F469BE and STM32F469NE Devices */ - /* #define STM32F479xx */ /*!< STM32F479AI, STM32F479II, STM32F479BI, STM32F479NI, STM32F479AG, STM32F479IG, STM32F479BG - and STM32F479NG Devices */ - /* #define STM32F412Cx */ /*!< STM32F412CEU and STM32F412CGU Devices */ - /* #define STM32F412Zx */ /*!< STM32F412ZET, STM32F412ZGT, STM32F412ZEJ and STM32F412ZGJ Devices */ - /* #define STM32F412Vx */ /*!< STM32F412VET, STM32F412VGT, STM32F412VEH and STM32F412VGH Devices */ - /* #define STM32F412Rx */ /*!< STM32F412RET, STM32F412RGT, STM32F412REY and STM32F412RGY Devices */ - /* #define STM32F413xx */ /*!< STM32F413CH, STM32F413MH, STM32F413RH, STM32F413VH, STM32F413ZH, STM32F413CG, STM32F413MG, - STM32F413RG, STM32F413VG and STM32F413ZG Devices */ - /* #define STM32F423xx */ /*!< STM32F423CH, STM32F423RH, STM32F423VH and STM32F423ZH Devices */ -#endif - -/* Tip: To avoid modifying this file each time you need to switch between these - devices, you can define the device in your toolchain compiler preprocessor. - */ -#if !defined (USE_HAL_DRIVER) -/** - * @brief Comment the line below if you will not use the peripherals drivers. - In this case, these drivers will not be included and the application code will - be based on direct access to peripherals registers - */ - #define USE_HAL_DRIVER -#endif /* USE_HAL_DRIVER */ - -/** - * @brief CMSIS version number V2.5.0 - */ -#define __STM32F4xx_CMSIS_VERSION_MAIN (0x02U) /*!< [31:24] main version */ -#define __STM32F4xx_CMSIS_VERSION_SUB1 (0x05U) /*!< [23:16] sub1 version */ -#define __STM32F4xx_CMSIS_VERSION_SUB2 (0x00U) /*!< [15:8] sub2 version */ -#define __STM32F4xx_CMSIS_VERSION_RC (0x00U) /*!< [7:0] release candidate */ -#define __STM32F4xx_CMSIS_VERSION ((__STM32F4xx_CMSIS_VERSION_MAIN << 24)\ - |(__STM32F4xx_CMSIS_VERSION_SUB1 << 16)\ - |(__STM32F4xx_CMSIS_VERSION_SUB2 << 8 )\ - |(__STM32F4xx_CMSIS_VERSION)) - -/** - * @} - */ - -/** @addtogroup Device_Included - * @{ - */ - -#if defined(STM32F405xx) - #include "stm32f405xx.h" -#elif defined(STM32F415xx) - #include "stm32f415xx.h" -#elif defined(STM32F407xx) - #include "stm32f407xx.h" -#elif defined(STM32F417xx) - #include "stm32f417xx.h" -#elif defined(STM32F427xx) - #include "stm32f427xx.h" -#elif defined(STM32F437xx) - #include "stm32f437xx.h" -#elif defined(STM32F429xx) - #include "stm32f429xx.h" -#elif defined(STM32F439xx) - #include "stm32f439xx.h" -#elif defined(STM32F401xC) - #include "stm32f401xc.h" -#elif defined(STM32F401xE) - #include "stm32f401xe.h" -#elif defined(STM32F410Tx) - #include "stm32f410tx.h" -#elif defined(STM32F410Cx) - #include "stm32f410cx.h" -#elif defined(STM32F410Rx) - #include "stm32f410rx.h" -#elif defined(STM32F411xE) - #include "stm32f411xe.h" -#elif defined(STM32F446xx) - #include "stm32f446xx.h" -#elif defined(STM32F469xx) - #include "stm32f469xx.h" -#elif defined(STM32F479xx) - #include "stm32f479xx.h" -#elif defined(STM32F412Cx) - #include "stm32f412cx.h" -#elif defined(STM32F412Zx) - #include "stm32f412zx.h" -#elif defined(STM32F412Rx) - #include "stm32f412rx.h" -#elif defined(STM32F412Vx) - #include "stm32f412vx.h" -#elif defined(STM32F413xx) - #include "stm32f413xx.h" -#elif defined(STM32F423xx) - #include "stm32f423xx.h" -#else - #error "Please select first the target STM32F4xx device used in your application (in stm32f4xx.h file)" -#endif - -/** - * @} - */ - -/** @addtogroup Exported_types - * @{ - */ -typedef enum -{ - RESET = 0U, - SET = !RESET -} FlagStatus, ITStatus; - -typedef enum -{ - DISABLE = 0U, - ENABLE = !DISABLE -} FunctionalState; -#define IS_FUNCTIONAL_STATE(STATE) (((STATE) == DISABLE) || ((STATE) == ENABLE)) - -typedef enum -{ - ERROR = 0U, - SUCCESS = !ERROR -} ErrorStatus; - -/** - * @} - */ - - -/** @addtogroup Exported_macro - * @{ - */ -#define SET_BIT(REG, BIT) ((REG) |= (BIT)) - -#define CLEAR_BIT(REG, BIT) ((REG) &= ~(BIT)) - -#define READ_BIT(REG, BIT) ((REG) & (BIT)) - -#define CLEAR_REG(REG) ((REG) = (0x0)) - -#define WRITE_REG(REG, VAL) ((REG) = (VAL)) - -#define READ_REG(REG) ((REG)) - -#define MODIFY_REG(REG, CLEARMASK, SETMASK) WRITE_REG((REG), (((READ_REG(REG)) & (~(CLEARMASK))) | (SETMASK))) - -#define POSITION_VAL(VAL) (__CLZ(__RBIT(VAL))) - - -/** - * @} - */ - -#if defined (USE_HAL_DRIVER) - #include "stm32f4xx_hal.h" -#endif /* USE_HAL_DRIVER */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* __STM32F4xx_H */ -/** - * @} - */ - -/** - * @} - */ - - - - -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/device/system_stm32f4xx.h b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/device/system_stm32f4xx.h deleted file mode 100644 index 0b8a72d9efb..00000000000 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/device/system_stm32f4xx.h +++ /dev/null @@ -1,123 +0,0 @@ -/** - ****************************************************************************** - * @file system_stm32f4xx.h - * @author MCD Application Team - * @version V2.5.0 - * @date 22-April-2016 - * @brief CMSIS Cortex-M4 Device System Source File for STM32F4xx devices. - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2015 STMicroelectronics

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ - -/** @addtogroup CMSIS - * @{ - */ - -/** @addtogroup stm32f4xx_system - * @{ - */ - -/** - * @brief Define to prevent recursive inclusion - */ -#ifndef __SYSTEM_STM32F4XX_H -#define __SYSTEM_STM32F4XX_H - -#ifdef __cplusplus - extern "C" { -#endif - -/** @addtogroup STM32F4xx_System_Includes - * @{ - */ - -/** - * @} - */ - - -/** @addtogroup STM32F4xx_System_Exported_types - * @{ - */ - /* This variable is updated in three ways: - 1) by calling CMSIS function SystemCoreClockUpdate() - 2) by calling HAL API function HAL_RCC_GetSysClockFreq() - 3) each time HAL_RCC_ClockConfig() is called to configure the system clock frequency - Note: If you use this function to configure the system clock; then there - is no need to call the 2 first functions listed above, since SystemCoreClock - variable is updated automatically. - */ -extern uint32_t SystemCoreClock; /*!< System Clock Frequency (Core Clock) */ - - -/** - * @} - */ - -/** @addtogroup STM32F4xx_System_Exported_Constants - * @{ - */ - -/** - * @} - */ - -/** @addtogroup STM32F4xx_System_Exported_Macros - * @{ - */ - -/** - * @} - */ - -/** @addtogroup STM32F4xx_System_Exported_Functions - * @{ - */ - -extern void SystemInit(void); -extern void SystemCoreClockUpdate(void); -extern void SetSysClock(void); -/** - * @} - */ - -#ifdef __cplusplus -} -#endif - -#endif /*__SYSTEM_STM32F4XX_H */ - -/** - * @} - */ - -/** - * @} - */ -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/objects.h b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/objects.h deleted file mode 100644 index 581a5a1e716..00000000000 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F437xG/objects.h +++ /dev/null @@ -1,84 +0,0 @@ -/* mbed Microcontroller Library - ******************************************************************************* - * Copyright (c) 2015, STMicroelectronics - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************* - */ -#ifndef MBED_OBJECTS_H -#define MBED_OBJECTS_H - -#include "cmsis.h" -#include "PortNames.h" -#include "PeripheralNames.h" -#include "PinNames.h" - -#ifdef __cplusplus -extern "C" { -#endif - -struct gpio_irq_s { - IRQn_Type irq_n; - uint32_t irq_index; - uint32_t event; - PinName pin; -}; - -struct port_s { - PortName port; - uint32_t mask; - PinDirection direction; - __IO uint32_t *reg_in; - __IO uint32_t *reg_out; -}; - -struct analogin_s { - ADCName adc; - PinName pin; - uint8_t channel; -}; - -struct trng_s { - RNG_HandleTypeDef handle; -}; - -struct dac_s { - DACName dac; - uint8_t channel; -}; - -#include "common_objects.h" -struct can_s { - CANName can; - int index; -}; - -#include "gpio_object.h" - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F439xI/TARGET_NUCLEO_F439ZI/PeripheralPins.c b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F439xI/TARGET_NUCLEO_F439ZI/PeripheralPins.c index 615052deff4..1193246c416 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F439xI/TARGET_NUCLEO_F439ZI/PeripheralPins.c +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F439xI/TARGET_NUCLEO_F439ZI/PeripheralPins.c @@ -57,8 +57,8 @@ const PinMap PinMap_ADC[] = { // {PA_5, ADC_2, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 5, 0)}, // ADC2_IN5 - ARDUINO D13 {PA_6, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 6, 0)}, // ADC1_IN6 - ARDUINO D12 // {PA_6, ADC_2, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 6, 0)}, // ADC2_IN6 - ARDUINO D12 -// {PA_7, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 7, 0)}, // ADC1_IN7 (pin used by ethernet when JP6 ON) - ARDUINO D11 (default configuration) - {PA_7, ADC_2, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 7, 0)}, // ADC2_IN7 (pin used by ethernet when JP6 ON) - ARDUINO D11 (default configuration) +// {PA_7, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 7, 0)}, // ADC1_IN7 (pin used by ethernet when JP6 ON) - ARDUINO D11 + {PA_7, ADC_2, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 7, 0)}, // ADC2_IN7 (pin used by ethernet when JP6 ON) - ARDUINO D11 // {PB_0, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 8, 0)}, // ADC1_IN8 (pin used by LED1) // {PB_0, ADC_2, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 8, 0)}, // ADC2_IN8 (pin used by LED1) {PB_1, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 9, 0)}, // ADC1_IN9 @@ -87,10 +87,6 @@ const PinMap PinMap_ADC[] = { {PF_8, ADC_3, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 6, 0)}, // ADC3_IN6 {PF_9, ADC_3, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 7, 0)}, // ADC3_IN7 {PF_10, ADC_3, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 8, 0)}, // ADC3_IN8 - ARDUINO A5 - {NC, NC, 0} -}; - -const PinMap PinMap_ADC_Internal[] = { {ADC_TEMP, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 16, 0)}, // See in analogin_api.c the correct ADC channel used {ADC_VREF, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 17, 0)}, // See in analogin_api.c the correct ADC channel used {ADC_VBAT, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 18, 0)}, // See in analogin_api.c the correct ADC channel used @@ -140,12 +136,12 @@ const PinMap PinMap_PWM[] = { // {PA_3, PWM_9, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM9, 2, 0)}, // TIM9_CH2 - ARDUINO A0 // {PA_5, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 1, 0)}, // TIM2_CH1 - ARDUINO D13 {PA_5, PWM_8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 1, 1)}, // TIM8_CH1N - ARDUINO D13 -// {PA_6, PWM_13, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF9_TIM13, 1, 0)}, // TIM13_CH1 - ARDUINO D12 +// {PA_6, PWM_13, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF9_TIM13, 1, 0)}, // TIM13_CH1 - ARDUINO D12 {PA_6, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 1, 0)}, // TIM3_CH1 - ARDUINO D12 - {PA_7, PWM_14, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF9_TIM14, 1, 0)}, // TIM14_CH1 (pin used by ethernet when JP6 ON) - ARDUINO D11 (default configuration) -// {PA_7, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 1, 1)}, // TIM1_CH1N (pin used by ethernet when JP6 ON) - ARDUINO D11 (default configuration) -// {PA_7, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 2, 0)}, // TIM3_CH2 (pin used by ethernet when JP6 ON) - ARDUINO D11 (default configuration) -// {PA_7, PWM_8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 1, 1)}, // TIM8_CH1N (pin used by ethernet when JP6 ON) - ARDUINO D11 (default configuration) + {PA_7, PWM_14, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF9_TIM14, 1, 0)}, // TIM14_CH1 (pin used by ethernet when JP6 ON) - ARDUINO D11 +// {PA_7, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 1, 1)}, // TIM1_CH1N (pin used by ethernet when JP6 ON) - ARDUINO D11 +// {PA_7, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 2, 0)}, // TIM3_CH2 (pin used by ethernet when JP6 ON) - ARDUINO D11 +// {PA_7, PWM_8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 1, 1)}, // TIM8_CH1N (pin used by ethernet when JP6 ON) - ARDUINO D11 {PA_8, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 1, 0)}, // TIM1_CH1 // {PA_9, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 2, 0)}, // TIM1_CH2 (pin used by usb) // {PA_10, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 3, 0)}, // TIM1_CH3 (pin used by usb) @@ -159,9 +155,7 @@ const PinMap PinMap_PWM[] = { {PB_1, PWM_8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 3, 1)}, // TIM8_CH3N {PB_3, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 2, 0)}, // TIM2_CH2 {PB_4, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 1, 0)}, // TIM3_CH1 - {PB_5, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 2, 0)}, // TIM3_CH2 - ARDUINO D11 (need HW and SW updates) - // HW solder bridge update : SB121 off, SB122 on - // SW : config from json files + {PB_5, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 2, 0)}, // TIM3_CH2 {PB_6, PWM_4, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM4, 1, 0)}, // TIM4_CH1 // {PB_7, PWM_4, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM4, 2, 0)}, // TIM4_CH2 (pin used by LED2) // {PB_8, PWM_10, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM10, 1, 0)}, // TIM10_CH1 - ARDUINO D15 @@ -270,10 +264,8 @@ const PinMap PinMap_UART_CTS[] = { //*** SPI *** const PinMap PinMap_SPI_MOSI[] = { - {PA_7, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI1)}, // pin used by ethernet when JP6 ON - ARDUINO D11 (default configuration) - {PB_5, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI1)}, // ARDUINO D11 (need HW and SW updates) - // HW solder bridge update : SB121 off, SB122 on - // SW : config from json files + {PA_7, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI1)}, // (pin used by ethernet when JP6 ON) - ARDUINO D11 + {PB_5, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI1)}, // {PB_5, SPI_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_SPI3)}, {PB_15, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI2)}, {PC_3, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI2)}, // ARDUINO A2 @@ -334,9 +326,7 @@ const PinMap PinMap_CAN_RD[] = { {PB_8, CAN_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF9_CAN1)}, {PB_12, CAN_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF9_CAN2)}, {PD_0, CAN_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF9_CAN1)}, - {PB_5 , CAN_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF9_CAN2)}, // ARDUINO D11 (need HW and SW updates) - // HW solder bridge update : SB121 off, SB122 on - // SW : config from json files + {PB_5 , CAN_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF9_CAN2)}, {PA_11, CAN_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF9_CAN1)}, {NC, NC, 0} }; diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F439xI/TARGET_NUCLEO_F439ZI/PinNames.h b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F439xI/TARGET_NUCLEO_F439ZI/PinNames.h index 85cb275a6fe..302c59e62ae 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F439xI/TARGET_NUCLEO_F439ZI/PinNames.h +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F439xI/TARGET_NUCLEO_F439ZI/PinNames.h @@ -183,7 +183,7 @@ typedef enum { D8 = PF_12, D9 = PD_15, D10 = PD_14, - D11 = STM32_D11_SPI_ETHERNET_PIN, /* config in targets.json file */ + D11 = PA_7, D12 = PA_6, D13 = PA_5, D14 = PB_9, @@ -196,8 +196,6 @@ typedef enum { LED4 = PB_0, LED_RED = LED2, USER_BUTTON = PC_13, - // Standardized button names - BUTTON1 = USER_BUTTON, SERIAL_TX = PD_8, // Virtual Com Port SERIAL_RX = PD_9, // Virtual Com Port USBTX = PD_8, // Virtual Com Port diff --git a/features/unsupported/USBHost/USBHost/TARGET_STM/TARGET_STM32F4/TARGET_STM32F439xI/TARGET_NUCLEO_F439ZI/USBHALHost_STM_TARGET.h b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F439xI/TARGET_NUCLEO_F439ZI/USBHALHost_STM_TARGET.h similarity index 100% rename from features/unsupported/USBHost/USBHost/TARGET_STM/TARGET_STM32F4/TARGET_STM32F439xI/TARGET_NUCLEO_F439ZI/USBHALHost_STM_TARGET.h rename to targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F439xI/TARGET_NUCLEO_F439ZI/USBHALHost_STM_TARGET.h diff --git a/features/unsupported/USBDevice/USBDevice/TARGET_STM/TARGET_STM32F4/TARGET_STM32F446xE/TARGET_NUCLEO_F446RE/USBHAL_STM_TARGET.h b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F439xI/TARGET_NUCLEO_F439ZI/USBHAL_STM_TARGET.h similarity index 100% rename from features/unsupported/USBDevice/USBDevice/TARGET_STM/TARGET_STM32F4/TARGET_STM32F446xE/TARGET_NUCLEO_F446RE/USBHAL_STM_TARGET.h rename to targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F439xI/TARGET_NUCLEO_F439ZI/USBHAL_STM_TARGET.h diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F439xI/device/flash_api.c b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F439xI/device/flash_api.c index af039e70b9b..584c0ea9890 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F439xI/device/flash_api.c +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F439xI/device/flash_api.c @@ -16,9 +16,9 @@ #include "flash_api.h" #include "flash_data.h" -#include "platform/mbed_critical.h" +#include "mbed_critical.h" -// This file is automatically generated +// This file is automagically generated #if DEVICE_FLASH diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F446xE/TARGET_B96B_F446VE/PeripheralPins.c b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F446xE/TARGET_B96B_F446VE/PeripheralPins.c index 960548e48db..b07d4d9690e 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F446xE/TARGET_B96B_F446VE/PeripheralPins.c +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F446xE/TARGET_B96B_F446VE/PeripheralPins.c @@ -55,10 +55,6 @@ const PinMap PinMap_ADC[] = { {PC_3, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 13, 0)}, // ADC1_IN13 {PC_4, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 14, 0)}, // ADC1_IN14 {PC_5, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 15, 0)}, // ADC1_IN15 - {NC, NC, 0} -}; - -const PinMap PinMap_ADC_Internal[] = { {ADC_TEMP, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 16, 0)}, // See in analogin_api.c the correct ADC channel used {ADC_VREF, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 17, 0)}, // See in analogin_api.c the correct ADC channel used {ADC_VBAT, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 18, 0)}, // See in analogin_api.c the correct ADC channel used diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F446xE/TARGET_B96B_F446VE/PinNames.h b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F446xE/TARGET_B96B_F446VE/PinNames.h index 2204f063442..0dc11e6a250 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F446xE/TARGET_B96B_F446VE/PinNames.h +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F446xE/TARGET_B96B_F446VE/PinNames.h @@ -161,8 +161,6 @@ typedef enum { LED4 = PD_12, LED_RED = LED1, USER_BUTTON = PD_13, - // Standardized button names - BUTTON1 = USER_BUTTON, SERIAL_TX = PC_10, SERIAL_RX = PC_11, USBTX = SERIAL_TX, diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F446xE/TARGET_NUCLEO_F446RE/PeripheralPins.c b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F446xE/TARGET_NUCLEO_F446RE/PeripheralPins.c index cca40b64676..b7aa5019cd7 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F446xE/TARGET_NUCLEO_F446RE/PeripheralPins.c +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F446xE/TARGET_NUCLEO_F446RE/PeripheralPins.c @@ -41,8 +41,8 @@ const PinMap PinMap_ADC[] = { {PA_0, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 0, 0)}, // ADC1_IN0 - ARDUINO A0 {PA_1, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 1, 0)}, // ADC1_IN1 - ARDUINO A1 -// {PA_2, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 2, 0)}, // ADC1_IN2 // SERIAL_TX -// {PA_3, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 3, 0)}, // ADC1_IN3 // SERIAL_RX + {PA_2, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 2, 0)}, // ADC1_IN2 + {PA_3, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 3, 0)}, // ADC1_IN3 {PA_4, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 4, 0)}, // ADC1_IN4 - ARDUINO A2 {PA_5, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 5, 0)}, // ADC1_IN5 {PA_6, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 6, 0)}, // ADC1_IN6 @@ -55,10 +55,6 @@ const PinMap PinMap_ADC[] = { {PC_3, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 13, 0)}, // ADC1_IN13 {PC_4, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 14, 0)}, // ADC1_IN14 {PC_5, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 15, 0)}, // ADC1_IN15 - {NC, NC, 0} -}; - -const PinMap PinMap_ADC_Internal[] = { {ADC_TEMP, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 16, 0)}, // See in analogin_api.c the correct ADC channel used {ADC_VREF, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 17, 0)}, // See in analogin_api.c the correct ADC channel used {ADC_VBAT, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 18, 0)}, // See in analogin_api.c the correct ADC channel used @@ -103,12 +99,12 @@ const PinMap PinMap_PWM[] = { // {PA_0, PWM_5, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM5, 1, 0)}, // TIM5_CH1 {PA_1, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 2, 0)}, // TIM2_CH2 // {PA_1, PWM_5, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM5, 2, 0)}, // TIM5_CH2 -// {PA_2, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 3, 0)}, // TIM2_CH3 // SERIAL_TX -// {PA_2, PWM_5, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM5, 3, 0)}, // TIM5_CH3 // SERIAL_TX -// {PA_2, PWM_9, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM9, 1, 0)}, // TIM9_CH1 // SERIAL_TX -// {PA_3, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 4, 0)}, // TIM2_CH4 // SERIAL_RX -// {PA_3, PWM_5, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM5, 4, 0)}, // TIM5_CH4 // SERIAL_RX -// {PA_3, PWM_9, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM9, 2, 0)}, // TIM9_CH2 // SERIAL_RX + {PA_2, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 3, 0)}, // TIM2_CH3 +// {PA_2, PWM_5, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM5, 3, 0)}, // TIM5_CH3 +// {PA_2, PWM_9, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM9, 1, 0)}, // TIM9_CH1 + {PA_3, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 4, 0)}, // TIM2_CH4 +// {PA_3, PWM_5, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM5, 4, 0)}, // TIM5_CH4 +// {PA_3, PWM_9, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM9, 2, 0)}, // TIM9_CH2 {PA_5, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 1, 0)}, // TIM2_CH1 // {PA_5, PWM_8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 1, 1)}, // TIM8_CH1N {PA_6, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 1, 0)}, // TIM3_CH1 @@ -166,7 +162,7 @@ const PinMap PinMap_PWM[] = { const PinMap PinMap_UART_TX[] = { {PA_0, UART_4, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_UART4)}, - {PA_2, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART2)}, // SERIAL_TX + {PA_2, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART2)}, {PA_9, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)}, {PB_6, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)}, {PB_10, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)}, @@ -179,7 +175,7 @@ const PinMap PinMap_UART_TX[] = { const PinMap PinMap_UART_RX[] = { {PA_1, UART_4, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_UART4)}, - {PA_3, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART2)}, // SERIAL_RX + {PA_3, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART2)}, {PA_10, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)}, {PB_7, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)}, {PC_5, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)}, diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F446xE/TARGET_NUCLEO_F446RE/PinNames.h b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F446xE/TARGET_NUCLEO_F446RE/PinNames.h index 2a52e564564..e590f38f4bf 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F446xE/TARGET_NUCLEO_F446RE/PinNames.h +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F446xE/TARGET_NUCLEO_F446RE/PinNames.h @@ -129,8 +129,6 @@ typedef enum { LED4 = PA_5, LED_RED = LED1, USER_BUTTON = PC_13, - // Standardized button names - BUTTON1 = USER_BUTTON, SERIAL_TX = PA_2, SERIAL_RX = PA_3, USBTX = PA_2, diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F446xE/TARGET_NUCLEO_F446ZE/PeripheralPins.c b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F446xE/TARGET_NUCLEO_F446ZE/PeripheralPins.c index 270f06c2052..c36a61492cd 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F446xE/TARGET_NUCLEO_F446ZE/PeripheralPins.c +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F446xE/TARGET_NUCLEO_F446ZE/PeripheralPins.c @@ -89,10 +89,6 @@ const PinMap PinMap_ADC[] = { {PF_8, ADC_3, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 6, 0)}, // ADC3_IN6 {PF_9, ADC_3, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 7, 0)}, // ADC3_IN7 {PF_10, ADC_3, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 8, 0)}, // ADC3_IN8 - ARDUINO A5 - {NC, NC, 0} -}; - -const PinMap PinMap_ADC_Internal[] = { {ADC_TEMP, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 16, 0)}, // See in analogin_api.c the correct ADC channel used {ADC_VREF, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 17, 0)}, // See in analogin_api.c the correct ADC channel used {ADC_VBAT, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 18, 0)}, // See in analogin_api.c the correct ADC channel used @@ -111,12 +107,12 @@ const PinMap PinMap_DAC[] = { const PinMap PinMap_I2C_SDA[] = { {PB_3, I2C_2 , STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C2)}, - //{PB_4, I2C_3 , STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C3)}, // no I2C_3 SCL available + {PB_4, I2C_3 , STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C3)}, //{PB_7, I2C_1 , STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C1)}, // (used by LED2) {PB_9, I2C_1 , STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C1)}, {PB_11, I2C_2 , STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C2)}, //{PC_7, FMPI2C_1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_FMPI2C1)}, - //{PC_9, I2C_3 , STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C3)}, // no I2C_3 SCL available + {PC_9, I2C_3 , STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C3)}, {PC_12, I2C_2 , STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C2)}, //{PD_13, FMPI2C_1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_FMPI2C1)}, //{PD_15, FMPI2C_1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_FMPI2C1)}, diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F446xE/TARGET_NUCLEO_F446ZE/PinNames.h b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F446xE/TARGET_NUCLEO_F446ZE/PinNames.h index 72814149ac8..894669cae80 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F446xE/TARGET_NUCLEO_F446ZE/PinNames.h +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F446xE/TARGET_NUCLEO_F446ZE/PinNames.h @@ -197,8 +197,6 @@ typedef enum { LED4 = LED1, LED_RED = LED3, USER_BUTTON = PC_13, - // Standardized button names - BUTTON1 = USER_BUTTON, SERIAL_TX = PD_8, // Virtual Com Port SERIAL_RX = PD_9, // Virtual Com Port USBTX = SERIAL_TX, // Virtual Com Port diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F469xI/TARGET_DISCO_F469NI/PeripheralPins.c b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F469xI/TARGET_DISCO_F469NI/PeripheralPins.c index b84b8468777..4d0f00b350c 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F469xI/TARGET_DISCO_F469NI/PeripheralPins.c +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F469xI/TARGET_DISCO_F469NI/PeripheralPins.c @@ -63,10 +63,6 @@ const PinMap PinMap_ADC[] = { {PF_8, ADC_3, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 6, 0)}, // ADC3_IN6 {PF_9, ADC_3, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 7, 0)}, // ADC3_IN7 {PF_10,ADC_3, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 8, 0)}, // ADC3_IN8 - {NC, NC, 0} -}; - -const PinMap PinMap_ADC_Internal[] = { {ADC_TEMP, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 16, 0)}, // See in analogin_api.c the correct ADC channel used {ADC_VREF, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 17, 0)}, // See in analogin_api.c the correct ADC channel used {ADC_VBAT, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 18, 0)}, // See in analogin_api.c the correct ADC channel used @@ -88,7 +84,7 @@ const PinMap PinMap_DAC[] = { const PinMap PinMap_I2C_SDA[] = { {PB_7, I2C_1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C1)}, {PB_9, I2C_1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C1)}, -// {PB_11, I2C_2, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C2)}, // SERIAL_RX + {PB_11, I2C_2, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C2)}, {PC_9, I2C_3, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C3)}, {PF_0, I2C_2, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C2)}, {PH_5, I2C_2, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C2)}, @@ -100,7 +96,7 @@ const PinMap PinMap_I2C_SCL[] = { {PA_8, I2C_3, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C3)}, {PB_6, I2C_1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C1)}, {PB_8, I2C_1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C1)}, -// {PB_10, I2C_2, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C2)}, // SERIAL_TX + {PB_10, I2C_2, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C2)}, {PF_1, I2C_2, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C2)}, {PH_4, I2C_2, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C2)}, {PH_7, I2C_3, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C3)}, @@ -145,8 +141,8 @@ const PinMap PinMap_PWM[] = { // {PB_8, PWM_10,STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM10,1, 0)}, // TIM10_CH1 {PB_9, PWM_4, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM4, 4, 0)}, // TIM4_CH4 // {PB_9, PWM_11,STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM11,1, 0)}, // TIM11_CH1 -// {PB_10, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 3, 0)}, // TIM2_CH3 // SERIAL_TX -// {PB_11, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 4, 0)}, // TIM2_CH4 // SERIAL_RX + {PB_10, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 3, 0)}, // TIM2_CH3 + {PB_11, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 4, 0)}, // TIM2_CH4 {PB_13, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 1, 1)}, // TIM1_CH1N {PB_14, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 2, 1)}, // TIM1_CH2N // {PB_14, PWM_8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 2, 1)}, // TIM8_CH2N @@ -206,7 +202,7 @@ const PinMap PinMap_UART_TX[] = { {PA_2, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART2)}, {PA_9, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)}, {PB_6, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)}, - {PB_10, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)}, // SERIAL_TX + {PB_10, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)}, {PC_6, UART_6, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_USART6)}, {PC_10, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)}, // {PC_10, UART_4, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_UART4)}, @@ -225,7 +221,7 @@ const PinMap PinMap_UART_RX[] = { {PA_3, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART2)}, {PA_10, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)}, {PB_7, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)}, - {PB_11, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)}, // SERIAL_RX + {PB_11, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)}, {PC_7, UART_6, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_USART6)}, {PC_11, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)}, // {PC_11, UART_4, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_UART4)}, @@ -302,7 +298,7 @@ const PinMap PinMap_SPI_SCLK[] = { {PA_9, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI2)}, {PB_3, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI1)}, // {PB_3, SPI_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_SPI3)}, - // {PB_10, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI2)}, // SERIAL_TX + {PB_10, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI2)}, {PB_13, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI2)}, {PC_10, SPI_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_SPI3)}, {PD_3, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI2)}, diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F469xI/TARGET_DISCO_F469NI/PinNames.h b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F469xI/TARGET_DISCO_F469NI/PinNames.h index 889c3d42721..ed8ad27b01d 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F469xI/TARGET_DISCO_F469NI/PinNames.h +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F469xI/TARGET_DISCO_F469NI/PinNames.h @@ -246,8 +246,6 @@ typedef enum { LED7 = PD_3, LED_RED = LED1, USER_BUTTON = PA_0, - // Standardized button names - BUTTON1 = USER_BUTTON, SERIAL_TX = PB_10, SERIAL_RX = PB_11, USBTX = PB_10, diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F469xI/device/TOOLCHAIN_IAR/stm32f469xx.icf b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F469xI/device/TOOLCHAIN_IAR/stm32f469xx.icf index 0efe5d61476..4c2aa1be12d 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F469xI/device/TOOLCHAIN_IAR/stm32f469xx.icf +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F469xI/device/TOOLCHAIN_IAR/stm32f469xx.icf @@ -15,8 +15,9 @@ define region ROM_region = mem:[from __region_ROM_start__ to __region_ROM_end__] define region RAM_region = mem:[from __region_RAM_start__ to __region_RAM_end__]; /* Stack and Heap */ +/*Heap 1/4 of ram and stack 1/8*/ define symbol __size_cstack__ = 0x4000; -define symbol __size_heap__ = 0x10000; +define symbol __size_heap__ = 0x8000; define block CSTACK with alignment = 8, size = __size_cstack__ { }; define block HEAP with alignment = 8, size = __size_heap__ { }; define block STACKHEAP with fixed order { block HEAP, block CSTACK }; diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/PeripheralPins.c b/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/PeripheralPins.c index c299903bf8e..889a3f75794 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/PeripheralPins.c +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/PeripheralPins.c @@ -54,11 +54,6 @@ const PinMap PinMap_ADC[] = { {NC, NC, 0} }; -const PinMap PinMap_ADC_Internal[] = { - {NC, NC, 0} -}; - - //*** I2C *** const PinMap PinMap_I2C_SDA[] = { diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/flash_api.c b/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/flash_api.c index a37010ae5f0..584c0ea9890 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/flash_api.c +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/flash_api.c @@ -18,7 +18,7 @@ #include "flash_data.h" #include "mbed_critical.h" -// This file is automatically generated +// This file is automagically generated #if DEVICE_FLASH diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/TOOLCHAIN_ARM/libublox-odin-w2-driver.ar b/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/TOOLCHAIN_ARM/libublox-odin-w2-driver.ar index 02bb74ed986..dd60053c00c 100644 Binary files a/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/TOOLCHAIN_ARM/libublox-odin-w2-driver.ar and b/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/TOOLCHAIN_ARM/libublox-odin-w2-driver.ar differ diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/TOOLCHAIN_GCC_ARM/libublox-odin-w2-driver.a b/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/TOOLCHAIN_GCC_ARM/libublox-odin-w2-driver.a index bfac450c732..1925def5733 100644 Binary files a/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/TOOLCHAIN_GCC_ARM/libublox-odin-w2-driver.a and b/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/TOOLCHAIN_GCC_ARM/libublox-odin-w2-driver.a differ diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/TOOLCHAIN_IAR/libublox-odin-w2-driver.a b/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/TOOLCHAIN_IAR/libublox-odin-w2-driver.a index eff3e49dddf..63914a7e5e5 100644 Binary files a/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/TOOLCHAIN_IAR/libublox-odin-w2-driver.a and b/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/TOOLCHAIN_IAR/libublox-odin-w2-driver.a differ diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/ublox-odin-w2-drivers/OdinWiFiInterface.h b/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/ublox-odin-w2-drivers/OdinWiFiInterface.h index 24be80d57af..eef737b63ba 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/ublox-odin-w2-drivers/OdinWiFiInterface.h +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/ublox-odin-w2-drivers/OdinWiFiInterface.h @@ -18,26 +18,20 @@ #define ODIN_WIFI_INTERFACE_H #include "WiFiInterface.h" -#include "emac_api.h" +#include "Callback.h" +#include "mbed_events.h" -#include "mbed.h" -#include "netsocket/WiFiAccessPoint.h" +#include "rtos.h" +#include "cmsis_os.h" +#include "emac_api.h" #include "nsapi_types.h" #include "lwip/netif.h" -#include "rtos.h" -#include "cb_wlan.h" -#define ODIN_WIFI_MAX_MAC_ADDR_STR (18) -#define ODIN_WIFI_SCAN_CACHE_SIZE (5) +typedef Queue MsgQueue; + +class OdinWiFiInterface; -struct odin_wifi_msg_s; -struct user_connect_s; -struct user_scan_s; -struct user_ap_start_s; -struct wlan_status_started_s; -struct wlan_status_connected_s; -struct wlan_status_connection_failure_s; -struct wlan_scan_indication_s; +struct PrivContext; /** OdinWiFiInterface class * Implementation of the WiFiInterface for the ODIN-W2 module @@ -80,8 +74,7 @@ class OdinWiFiInterface : public WiFiInterface * @param channel Channel on which the connection is to be made, or 0 for any (Default: 0) * @return 0 on success, or error code on failure */ - virtual nsapi_error_t connect( - const char *ssid, + virtual nsapi_error_t connect(const char *ssid, const char *pass, nsapi_security_t security = NSAPI_SECURITY_NONE, uint8_t channel = 0); @@ -122,7 +115,7 @@ class OdinWiFiInterface : public WiFiInterface /** Get the local network mask * * @return Null-terminated representation of the local network mask - * or null if no network mask has been received + * or null if no network mask has been recieved */ virtual const char *get_netmask(); @@ -184,161 +177,44 @@ class OdinWiFiInterface : public WiFiInterface * specified since the Wi-Fi driver might need some time to finish and cleanup. * @return 0 on success, negative error code on failure */ - virtual nsapi_error_t set_timeout(int ms); + virtual void set_timeout(int timeout); virtual NetworkStack *get_stack(); protected: private: - - enum OdinWifiState { - S_NOT_INITIALISED = 1, - S_WAIT_START, - S_STARTED, - S_WAIT_STOP, - - S_STA_IDLE, - S_STA_WAIT_CONNECT, - S_STA_CONNECTED, - S_STA_DISCONNECTED_WAIT_CONNECT, - S_STA_CONNECTION_FAIL_WAIT_DISCONNECT, - //S_STA_LINK_LOSS_WAIT_DISCONNECT, - S_STA_WAIT_DISCONNECT, - - S_AP_IDLE, - S_AP_WAIT_START, - S_AP_STARTED, - S_AP_WAIT_STOP, - S_AP_FAIL_WAIT_STOP, - S_AP_WAIT_DRV_STOP, - S_AP_WAIT_DRV_START, - - S_INVALID - }; - - struct sta_s { - const char *ssid; - const char *passwd; - nsapi_security_t security; - uint8_t channel; - bool use_dhcp; - int timeout_ms; - char ip_address[IPADDR_STRLEN_MAX]; - char netmask[IPADDR_STRLEN_MAX]; - char gateway[IPADDR_STRLEN_MAX]; - }; - - struct ap_s { - const char *ssid; - const char *passwd; - nsapi_security_t security; - uint8_t channel; - bool use_dhcp; - - char ip_address[IPADDR_STRLEN_MAX]; - char netmask[IPADDR_STRLEN_MAX]; - char gateway[IPADDR_STRLEN_MAX]; - - int cnt_connected; - - nsapi_error_t error_code; - }; - - struct scan_cache_s { - int count; - uint8_t last_channel; - cbWLAN_MACAddress bssid[ODIN_WIFI_SCAN_CACHE_SIZE]; - }; - - OdinWifiState entry_connect_fail_wait_disconnect(); - OdinWifiState entry_wait_connect(); - OdinWifiState entry_wait_disconnect(); - //OdinWifiState entry_link_loss_wait_disconnect(void); - OdinWifiState entry_ap_wait_start(); - OdinWifiState entry_ap_started(); - OdinWifiState entry_ap_wait_stop(); - OdinWifiState entry_ap_fail_wait_stop(); - OdinWifiState entry_ap_wait_drv_stop(); - OdinWifiState entry_ap_wait_drv_start(); - - void handle_in_msg(); - void handle_cached_msg(); - - void handle_user_connect(user_connect_s *user_connect); - void handle_user_disconnect(); - void handle_user_scan(user_scan_s *user_scan); - void handle_user_connect_timeout(); - void handle_user_stop(); - - void handle_user_ap_start(user_ap_start_s *user_ap_start); - void handle_user_ap_stop(); - - void handle_wlan_status_started(wlan_status_started_s *start); - void handle_wlan_status_stopped(void); - void handle_wlan_status_error(void); - void handle_wlan_status_connecting(void); - void handle_wlan_status_connected(wlan_status_connected_s *wlan_connect); - void handle_wlan_status_connection_failure(wlan_status_connection_failure_s *connect_failure); - void handle_wlan_status_disconnected(void); - void handle_wlan_scan_indication(); - - void handle_wlan_status_ap_up(); - void handle_wlan_status_ap_down(); - - void init(bool debug); - nsapi_error_t wlan_set_channel(uint8_t channel); - nsapi_error_t wlan_connect( - const char *ssid, - const char *passwd, - nsapi_security_t security); - nsapi_error_t wlan_ap_start( - const char *ssid, - const char *pass, - nsapi_security_t security, - uint8_t channel); - - void timeout_user_connect(); - void update_scan_list(cbWLAN_ScanIndicationInfo *scan_info); - void send_user_response_msg(unsigned int type, nsapi_error_t error_code); - void wlan_status_indication(cbWLAN_StatusIndicationInfo status, void *data); - void wlan_scan_indication(cbWLAN_ScanIndicationInfo *scan_info, cb_boolean is_last_result); - - static bool _wlan_initialized; // Controls that cbWLAN is initiated only once - static emac_interface_t* _emac; // Not possible to remove added interfaces to the network stack => static and re-use - static int32_t _target_id; - - OdinWifiState _state; - OdinWifiState _state_sta; - OdinWifiState _state_ap; - - struct sta_s _sta; - struct ap_s _ap; - nsapi_stack_t _stack; - char _mac_addr_str[ODIN_WIFI_MAX_MAC_ADDR_STR]; - - cbWLAN_StatusConnectedInfo _wlan_status_connected_info; - cbWLAN_StatusDisconnectedInfo _wlan_status_disconnected_info; - - bool _scan_active; - WiFiAccessPoint *_scan_list; - nsapi_size_t _scan_list_size; - nsapi_size_t _scan_list_cnt; - struct scan_cache_s _scan_cache; - - friend struct wlan_callb_s; - - Mutex _mutex; - Queue _in_queue; - Queue _out_queue; - Queue _cache_queue; - MemoryPool *_msg_pool; - Thread _thread; - //Timeout _timeout; //Randomly lost interrupts/callbacks; replaced by Timer - Timer _timer; - - bool _debug; - int _dbg_timeout; + + nsapi_error_t connect_async(const char *ssid, + const char *pass, + nsapi_security_t security = NSAPI_SECURITY_NONE, + uint8_t channel = 0, + void *data = NULL, + unsigned timeout = 0); + + bool start(bool debug); + bool stop(); + + char _mac_addr_str[18]; + // Private context to share between C and C++ calls + PrivContext* _priv_context; + const char *_ssid; + const char *_pass; + char _ip_address[IPADDR_STRLEN_MAX]; + char _netmask[IPADDR_STRLEN_MAX]; + char _gateway[IPADDR_STRLEN_MAX]; + nsapi_security_t _security; + uint8_t _channel; + bool _use_dhcp; + int _timeout; + // Event queue when the driver context need to be used + EventQueue* _odin_event_queue; + int32_t target_id; + // Event queue for sending start up and connection events from driver to this class + MsgQueue _event_queue; + // Message queue for sending scan events from driver to this class + osMessageQId _scan_msg_queue_id; + osMessageQDef_t _queue_def; }; #endif diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/ublox-odin-w2-drivers/bt_types.h b/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/ublox-odin-w2-drivers/bt_types.h index d55b2a1f1a5..9a8b73ae367 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/ublox-odin-w2-drivers/bt_types.h +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/ublox-odin-w2-drivers/bt_types.h @@ -1,5 +1,5 @@ /*--------------------------------------------------------------------------- - * Copyright (c) 2016, u-blox Malm�, All Rights Reserved + * Copyright (c) 2016, u-blox Malmö, All Rights Reserved * SPDX-License-Identifier: LicenseRef-PBL * * This file and the related binary are licensed under the @@ -65,11 +65,6 @@ #define PACKET_TYPE_ALL (PACKET_TYPE_DM1 | PACKET_TYPE_DH1 | PACKET_TYPE_DM3 | PACKET_TYPE_DH3 | PACKET_TYPE_DM5 | PACKET_TYPE_DH5) -#define BD_ADDR_IS_STATIC_RANDOM(BdAddress) ((BdAddress[0] & 0xC0) == 0xC0) -#define BD_ADDR_IS_NON_RESOLVABLE(BdAddress) ((BdAddress[0] & 0xC0) == 0x00) -#define BD_ADDR_IS_RESOLVABLE(BdAddress) ((BdAddress[0] & 0xC0) == 0x40) - -#define BT_INVALID_STATIC_LINK_KEY (0) /*=========================================================================== * TYPES *=========================================================================*/ diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/ublox-odin-w2-drivers/cb_bt_conn_man.h b/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/ublox-odin-w2-drivers/cb_bt_conn_man.h index 8e402076b5a..4fe40ca6956 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/ublox-odin-w2-drivers/cb_bt_conn_man.h +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/ublox-odin-w2-drivers/cb_bt_conn_man.h @@ -129,17 +129,6 @@ typedef struct cb_char serviceName[cbBCM_SERVICE_NAME_MAX_LEN]; } cbBCM_ConnectionInfo; -typedef struct -{ - cb_uint8 flags; /** Reserved for future use. */ - cb_uint8 flowDirection; /** 0x00 for Outgoing Flow and 0x01 for Incoming Flow */ - cb_uint8 serviceType; /** 0x00 No Traffic; 0x01 Best Effort; 0x02 Guaranteed */ - cb_uint32 tokenRate; /** Token Rate in octets per second */ - cb_uint32 tokenBucketSize; /** Token Bucket Size in octets */ - cb_uint32 peakBandwidth; /** Peak Bandwidth in octets per second */ - cb_uint32 latency; /** Latency in microseconds */ -} cbBCM_FlowSpecParams; - typedef void (*cbBCM_ConnectInd)( cbBCM_Handle handle, cbBCM_ConnectionInfo info); @@ -167,7 +156,7 @@ typedef struct typedef void(*cbBCM_RoleDiscoveryCallback)( cbBCM_Handle handle, cb_int8 status, - cb_uint8 role); + cb_int8 role); typedef void (*cbBCM_RssiCallback)( cbBCM_Handle handle, @@ -237,13 +226,6 @@ typedef void(*cbBCM_LinkQualityCallback)( cbBCM_LinkQualityEvt linkQualityEvt, uint8 linkQuality); -typedef void(*cbBCM_ServiceClassEnabled)(cb_uint8 serviceChannel); - -typedef void(*cbBCM_SetFlowSpecCallback)( - cb_uint8 status, - cbBCM_Handle handle, - cbBCM_FlowSpecParams parameters); - /*=========================================================================== * FUNCTIONS *=========================================================================*/ @@ -263,14 +245,12 @@ extern void cbBCM_init(void); * @param pServerChannel Pointer to return variable. The server channel is used to identify * incoming connections. * @param pConnectionCallback Callback structure for connection management. - * @param pServiceClassEnabled Callback structure to inform when service is running. * @return If the operation is successful cbBCM_OK is returned. */ extern cb_int32 cbBCM_enableServerProfileSpp( cb_char *pServiceName, cb_uint8 *pServerChannel, - cbBCM_ConnectionCallback *pConnectionCallback, - cbBCM_ServiceClassEnabled pServiceClassEnabled); + cbBCM_ConnectionCallback *pConnectionCallback); /** * Enable a Dial Up Networking Profile (DUN)service record to @@ -280,14 +260,12 @@ extern cb_int32 cbBCM_enableServerProfileSpp( * @param pServerChannel Pointer to return variable. The server channel is used to identify * incoming connections. * @param pConnectionCallback Callback structure for connection management. - * @param pServiceClassEnabled Callback structure to inform when service is running. * @return If the operation is successful cbBCM_OK is returned. */ extern cb_int32 cbBCM_enableServerProfileDun( cb_char *pServiceName, cb_uint8 *pServerChannel, - cbBCM_ConnectionCallback *pConnectionCallback, - cbBCM_ServiceClassEnabled pServiceClassEnabled); + cbBCM_ConnectionCallback *pConnectionCallback); /** * Enable a service record with an application specific UUID. @@ -298,15 +276,13 @@ extern cb_int32 cbBCM_enableServerProfileDun( * @param pServerChannel Pointer to return variable. The server channel is used to identify * incoming connections. * @param pConnectionCallback Callback structure for connection management. - * @param pServiceClassEnabled Callback structure to inform when service is running. * @return If the operation is successful cbBCM_OK is returned. */ extern cb_int32 cbBCM_enableServerProfileUuid128( cb_uint8 *pUuid128, cb_char *pServiceName, cb_uint8 *pServerChannel, - cbBCM_ConnectionCallback *pConnectionCallback, - cbBCM_ServiceClassEnabled pServiceClassEnabled); + cbBCM_ConnectionCallback *pConnectionCallback); /** @@ -319,14 +295,12 @@ extern cb_int32 cbBCM_enableServerProfileUuid128( * @param pServiceName The name of the service * @param role The PAN role of the local device * @param pConnectionCallback Callback structure for connection management. -* @param pServiceClassEnabled Callback structure to inform when service is running. * @return If the operation is successful cbBCM_OK is returned. */ extern cb_int32 cbBCM_enableServerProfilePan( cb_char *pServiceName, cbBCM_PAN_Role role, - cbBCM_ConnectionCallback *pConnectionCallback, - cbBCM_ServiceClassEnabled pServiceClassEnabled); + cbBCM_ConnectionCallback *pConnectionCallback); /** * Enable device id service record.The device id service record is a method by which @@ -419,7 +393,7 @@ extern cb_uint16 cbBCM_getMaxLinksLE(void); * @param serverChannel RFCOMM server channel that shall be used. Set to * cbBCM_INVALID_SERVER_CHANNEL to perform automatic * service search to find the server channel. - * @param pAclParameters Link configuration including link supervision timeout + * @param pAclParameters Link configuration including link supervision timeout * and master slave policy. Pass NULL to use default connection * parameters. * @param pConnectionCallback Callback structure for connection management. @@ -465,7 +439,7 @@ extern cb_int32 cbBCM_rspConnectSppCnf( * @param serverChannel RFCOMM server channel that shall be used. Set to * cbBCM_INVALID_SERVER_CHANNEL to perform automatic * service search to find the server channel. - * @param pAclParameters Link configuration including link supervision timeout + * @param pAclParameters Link configuration including link supervision timeout * and master slave policy. Pass NULL to use default connection * parameters. * @param pConnectionCallback Callback structure for connection management. @@ -483,7 +457,7 @@ extern cbBCM_Handle cbBCM_reqConnectDun( * Accept or reject an incoming DUN connection. This is a * response to a cbBCM_ConnectInd connection indication. * - * @param handle Connection handle + * @param handle Connection handle * @param accept TRUE to accept the incoming connection. FALSE to reject. * @return If the operation is successful cbBCM_OK is returned. @@ -531,7 +505,7 @@ extern cbBCM_Handle cbBCM_reqConnectUuid( * Accept or reject an incoming SPP connection. This is a * response to a cbBCM_ConnectInd connection indication. * - * @param handle Connection handle + * @param handle Connection handle * @param accept TRUE to accept the incoming connection. FALSE to reject. * @return If the operation is successful cbBCM_OK is returned. @@ -568,7 +542,7 @@ extern cbBCM_Handle cbBCM_reqConnectPan( * Accept or reject an incoming PAN connection. This is a * response to a cbBCM_ConnectInd connection indication. * -* @param handle Connection handle +* @param handle Connection handle * @param accept TRUE to accept the incoming connection. * FALSE to reject. * @return If the operation is successful cbBCM_OK is returned. @@ -630,7 +604,7 @@ extern cbBCM_Handle cbBCM_reqConnectSps( /** * Accept or reject an incoming SPS connection. This is a * response to a cbBCM_ConnectInd connection indication. - * @param handle Connection handle + * @param handle Connection handle * @param accept TRUE to accept the incoming connection. * FALSE to reject. * @return If the operation is successful cbBCM_OK is returned. @@ -839,50 +813,10 @@ extern cb_int32 cbBCM_registerDataCallback( extern cbBCM_Handle cbBCM_getProtocolHandle( cbBCM_Handle handle); -/** -* @brief Get the bcm id from acl handle for an active connection. -* -* @param handle Connection handle -* @return bcm handle. -*/ -extern cbBCM_Handle cbBCM_getIdFromAclHandle(TConnHandle aclHandle); - -/** -* @brief Get the acl handle from bcm handle. -* -* @param handle bcm handle -* @return acl handle -*/ -extern TConnHandle cbBCM_getAclFromIdHandle(cbBCM_Handle bcmHandle); -/** -* @brief This will send cbHCI_cmdFlowSpecification command for the specified link -* with the specified parameters. -* @param handle Connection handle -* @param parameters Flow Specification parameters. For details see Bluetooth Core -* Specification [Vol 3] Part A, Section 5.3 -* @param flowSpecCallback Callback contains the data in Flow Specification Complete event -* @return If the operation is successful cbBCM_OK is returned. -*/ -extern cb_int32 cbBCM_setFlowSpecification( - cbBCM_Handle handle, - cbBCM_FlowSpecParams parameters, - cbBCM_SetFlowSpecCallback flowSpecCallback); - -/** -* @brief Change which packet types can be used for the connection identified by the handle -* @param handle Connection handle -* @param aclPacketType bit map according to packet types defined in bt_types.h -* @return If the operation is successful cbBCM_OK is returned. -*/ -extern cb_int32 cbBCM_changeConnectionPacketType( - cbBCM_Handle handle, - TPacketType aclPacketType); - #ifdef __cplusplus } #endif - #endif /* _CB_BT_CONN_MAN_H_ */ diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/ublox-odin-w2-drivers/cb_bt_man.h b/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/ublox-odin-w2-drivers/cb_bt_man.h index 101c0e45ce0..240081d526e 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/ublox-odin-w2-drivers/cb_bt_man.h +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/ublox-odin-w2-drivers/cb_bt_man.h @@ -141,7 +141,6 @@ typedef void (*cbBM_ChannelMapCallb)( TChannelMap *pChMap); typedef void (*cbBM_InitComplete)(void); -typedef void(*cbBM_LocalAddressCb)(void); typedef enum { @@ -150,17 +149,6 @@ typedef enum cbBM_LE_ROLE_PERIPHERAL = 2, } cbBM_LeRole; -typedef struct -{ - cb_uint8 flags; - cb_uint8 flowDirection; - cb_uint8 serviceType; - cb_uint32 tokenRate; - cb_uint32 tokenBucketSize; - cb_uint32 peakBandwidth; - cb_uint32 latency; -} cbBM_FlowSpecParams; - /** * Bluetooth Manager initialization parameters. */ @@ -169,13 +157,12 @@ typedef struct TBdAddr address; /** Bluetooth address that shall be assigned to controller. Pass invalidBdAddress to use controller default address*/ cbBM_LeRole leRole; /** Bluetooth low energy role */ cb_int8 maxOutputPower; /** Maximum output power. */ - cb_int32 nvdsStartIdLinkKeysClassic; /** Start id for CLASSIC link keys storage in NVDS. */ - cb_int32 maxLinkKeysClassic; /** Max number of CLASSIC link keys */ - cb_int32 nvdsStartIdLinkKeysLe; /** Start id for BLE link keys storage in NVDS. */ - cb_int32 maxLinkKeysLe; /** Max number of link keys BLE*/ + cb_uint32 nvdsStartIdLinkKeysClassic; /** Start id for CLASSIC link keys storage in NVDS. */ + cb_uint32 maxLinkKeysClassic; /** Max number of CLASSIC link keys */ + cb_uint32 nvdsStartIdLinkKeysLe; /** Start id for BLE link keys storage in NVDS. */ + cb_uint32 maxLinkKeysLe; /** Max number of link keys BLE*/ } cbBM_InitParams; -typedef void(*cbBM_ServiceEnabled)(cb_uint8 serviceChannel); /*=========================================================================== * FUNCTIONS *=========================================================================*/ @@ -197,70 +184,12 @@ extern void cbBM_init( cbBM_InitParams *pInitParameters, cbBM_InitComplete initCompleteCallback); -/** -* This function sets the default link supervision timeout. The specified timeout will -* apply for new connections. -* @param linkSupervisionTimeout timeout in milliseconds -* @return If the operation is successful cbBM_OK is returned. -*/ -extern cb_int32 cbBM_setLinkSupervisionTimeout( - cb_uint16 linkSupervisionTimeout); - -/** -* This function gets the default link supervision timeout. -* @return link supervision timeout in milliseconds. -*/ -extern cb_uint16 cbBM_getLinkSupervisionTimeout(void); - -/** -* This function enables or disables the fast connect feature (interlaced page scan). -* @param fastConnect -* @return cbBM_OK if in parameter is valid. -*/ -extern cb_int32 cbBM_setFastConnect( - cb_boolean fastConnect); -/** -* This function gets whether the fast connect feature is enabled or disabled. -* @return TRUE if feature is enabled -*/ -extern cb_boolean cbBM_getFastConnect(void); - -/** -* This function enables or disables the fast discovery feature (interlaced inquiry scan). -* @param fastDiscovery -* @return cbBM_OK if in parameter is valid. -*/ -extern cb_int32 cbBM_setFastDiscovery( - cb_boolean fastDiscovery); -/** -* This function gets whether the fast discovery feature is enabled or disabled. -* @return TRUE if feature is enabled -*/ -extern cb_boolean cbBM_getFastDiscovery(void); /** * This function sets all default parameters for LE. * This function needs to be called before the cbBM_init. */ extern void cbBM_setDefaultValuesLeParams(void); -/** -* This function executes HCI_cmdWrScanEnable command according to parameters. -* @param discoverableMode discoverable mode -* @param connectableMode connectable mode -* @return true if HCI command could be executed. -*/ -extern cb_int32 cbBM_updateScan( - cbBM_DiscoverableMode discoverableMode, - cbBM_ConnectableMode connectableMode); - -/** - * Get the current Bluetooth address of the device from radio. This can - * be a way to get a alive-message from the radio. - * - * @param callback to application when address has been read. - */ -extern void cbBM_checkRadioAlive(cbBM_LocalAddressCb callback); - /** * Get the current Bluetooth address of the device. * @param pAddress Pointer to return variable. @@ -406,11 +335,9 @@ extern cb_int32 cbBM_remoteName( * Add service class to inquiry response data. Typically * not used by the application. * @param uuid16 The UUID to add - * @param pCallback callback to indicate service is enabled. - * @param serviceChannel channel the service is started on. * @return If the operation is successful cbBM_OK is returned. */ -extern cb_int32 cbBM_addServiceClass(cb_uint16 uuid16, cbBM_ServiceEnabled pCallback,cb_uint8 serviceChannel); +extern cb_int32 cbBM_addServiceClass(cb_uint16 uuid16); /** * Check if service class is already registered. @@ -423,11 +350,9 @@ cb_boolean cbBM_isServiceClassRegistered(cb_uint16 uuid16 ); * Add service class to inquiry response data. Typically * not used by the application. * @param uuid128 The UUID to add. - * @param pCallback callback to indicate service is enabled. - * @param serviceChannel channel the service is started on. * @return If the operation is successful cbBM_OK is returned. */ -extern cb_int32 cbBM_add128BitsServiceClass(cb_uint8* uuid128, cbBM_ServiceEnabled pCallback, cb_uint8 serviceChannel); +extern cb_int32 cbBM_add128BitsServiceClass(cb_uint8* uuid128); /** * Set maximum Bluetooth Classic ACL links the stack @@ -596,7 +521,7 @@ extern cb_int32 cbBM_deviceDiscoveryLeCancel(void); /** * Perform a remote name request for Bluetooth Low Energy. * @param pAddress Pointer to address of remote device. - * @param remoteNameCallback Callback used to notify the the completion of the + * @param remoteNameCallback Callback used to notify the the completion of the * name request. * @return If the operation is successfully initiated cbBM_OK is returned. */ @@ -635,9 +560,6 @@ void cbBM_getConnectParameters(TAclParamsLe* aclParams); */ void cbBM_getRemoteNameReqParameters(TAclParamsLe* aclParams); - -cb_int32 cbBM_setForceClassicNotSupportedInAdv(cb_boolean enforceDisable); -cb_boolean cbBM_getForceClassicNotSupportedInAdv(void); /* * Sets the LE parameter. * @newValue new parameter value. diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/ublox-odin-w2-drivers/cb_bt_pan.h b/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/ublox-odin-w2-drivers/cb_bt_pan.h index 4072c1168b7..cfc7e8cb885 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/ublox-odin-w2-drivers/cb_bt_pan.h +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/ublox-odin-w2-drivers/cb_bt_pan.h @@ -14,7 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * - * Component : Bluetooth PAN Data Manager + * Component : Bluetooth Serial * File : cb_bt_pan.h * * Description : Data management for PAN profile diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/ublox-odin-w2-drivers/cb_bt_sec_man.h b/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/ublox-odin-w2-drivers/cb_bt_sec_man.h index f002fc45a5d..c6a38b49af7 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/ublox-odin-w2-drivers/cb_bt_sec_man.h +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/ublox-odin-w2-drivers/cb_bt_sec_man.h @@ -346,7 +346,7 @@ extern cb_int32 cbBSM_getAllNumberBondedDevices( * @return If the operation is successful cbBSM_OK is returned. */ extern cb_int32 cbBSM_getBondedDevice( - cb_int32 deviceIndex, + uint32 deviceIndex, TBdAddr* pBdAddr, cb_boolean pIsLe); @@ -365,14 +365,6 @@ extern cb_int32 cbBSM_deleteBondedDevice(TBdAddr* pBdAddress); */ extern cb_int32 cbBSM_deleteAllBondedDevices(void); -/** -* Initializes the static Link Keys for both classic and LE. -* nvdsId: nvds id for the static link key, -* (0) disables the use of a static link key. -* -* @return cbBSM_OK. -*/ -cb_int32 cbBSM_setStaticLinkKeyNvdsId(cb_int32 nvdsId); #ifdef __cplusplus } #endif diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/ublox-odin-w2-drivers/cb_bt_test_man.h b/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/ublox-odin-w2-drivers/cb_bt_test_man.h index aa2f149da6e..6cbc8b3767d 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/ublox-odin-w2-drivers/cb_bt_test_man.h +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/ublox-odin-w2-drivers/cb_bt_test_man.h @@ -89,7 +89,7 @@ extern cb_int32 cbBTM_enableDUT(cbBTM_TestCallback callback); * 0x03 = BT EDR 3MB (8-DPSK) * 0x04 = BT LE (BLE, GMSK) * 0x05 = ANT (GFSK) - * @param testPattern Range: 0x00 - 0x07 + * @param testPattern Range: 0x00 - 0x07 * 0x00 = PN9 * 0x01 = PN15 * 0x02 = ZOZO (101010101010101010) @@ -165,7 +165,7 @@ extern cb_int32 cbBTM_tiDrpbTesterConRx( * @param frequencyMode 0x00 = Hopping 0x03 = Single frequency * @param txSingleFrequency Transmission frequency in MHz,Range 2402 - 2480, 0xFFFF = no TX * @param rxSingleFrequency Transmission frequency in MHz,Range 2402 - 2480, 0xFFFF = no RX - * @param aclDataPattern ACL TX packet data pattern Range: 0x00 - 0x05 + * @param aclDataPattern ACL TX packet data pattern Range: 0x00 - 0x05 * 0x00 = All 0 * 0x01 = All 1 * 0x02 = ZOZO (101010101010101010) diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/ublox-odin-w2-drivers/cb_cert_utils.h b/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/ublox-odin-w2-drivers/cb_cert_utils.h deleted file mode 100644 index 3d96ba8dbf5..00000000000 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/ublox-odin-w2-drivers/cb_cert_utils.h +++ /dev/null @@ -1,80 +0,0 @@ -/*--------------------------------------------------------------------------- - * Copyright (c) 2016, u-blox Malm�, All Rights Reserved - * SPDX-License-Identifier: LicenseRef-PBL - * - * This file and the related binary are licensed under the - * Permissive Binary License, Version 1.0 (the "License"); - * you may not use these files except in compliance with the License. - * - * You may obtain a copy of the License here: - * LICENSE-permissive-binary-license-1.0.txt and at - * https://www.mbed.com/licenses/PBL-1.0 - * - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Component : WLAN - * File : cb_cert_utils.h - * - * Description : - *-------------------------------------------------------------------------*/ - -/** - * @file cb_cert_utils.h The main WLAN component interface. - * All functions declared extern needs to be provided by another/upper layer. - * @ingroup wlan - */ - -#ifndef _CB_CERT_UTILS_H_ -#define _CB_CERT_UTILS_H_ - -#include "cb_types.h" -#include "cb_status.h" - -#ifdef __cplusplus -extern "C" { -#endif - - -/*=========================================================================== - * DEFINES - *=========================================================================*/ -#define cbCERT_CRT_MAX_CHAIN_LENGTH 5ul - -/*=========================================================================== - * TYPES - *=========================================================================*/ - -typedef struct cbCERT_Stream_s cbCERT_Stream; -typedef cb_uint32 cbCERT_StreamPosition; - -/** - * Stream vtable interface used by WLAN supplicant to access SSL certificates - * for WPA Enterprise authentication. - * - * @ingroup wlan - */ -struct cbCERT_Stream_s { - cb_int32(*read)(const cbCERT_Stream *stream, void *buf, cb_uint32 count); /**< Read function pointer, place count bytes in buf. */ - cb_int32(*write)(const cbCERT_Stream *stream, void *buf, cb_uint32 count); /**< Read function pointer, place count bytes in buf. */ - void(*rewind)(const cbCERT_Stream *stream); /**< Rewind function pointer, rewind stream internal iterator to the beginning. Mandatory for all streams. */ - void(*setPosition)(const cbCERT_Stream *stream, cbCERT_StreamPosition position); /**< Set absolute position. */ - cbCERT_StreamPosition(*getPosition)(const cbCERT_Stream *stream); /**< Get current position. */ - cb_uint32(*getSize)(const cbCERT_Stream *stream); /**< GetSize function pointer, return total size of stream contents. */ -}; - -/*=========================================================================== - * CERT API - *=========================================================================*/ - -cbRTSL_Status cbCERT_Util_parseDERCert(cbCERT_Stream const * const certificate, cbCERT_Stream const * const outputStream); -cbRTSL_Status cbCERT_Util_parseDERKey(cbCERT_Stream const * const key, cbCERT_Stream const * const outputStream); -cbRTSL_Status cbCERT_Util_parsePEMCert(cbCERT_Stream const * const certificate, cbCERT_Stream const * const outputStream); -cbRTSL_Status cbCERT_Util_parsePEMKey(cbCERT_Stream const * const certificate, cb_char const * const key, cb_uint32 keyLength, cbCERT_Stream const * const outputStream); - -#ifdef __cplusplus -} -#endif - -#endif /* _CB_CERT_UTILS_H_ */ - diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/ublox-odin-w2-drivers/cb_gatt_client.h b/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/ublox-odin-w2-drivers/cb_gatt_client.h index 94f5d13b2ef..d41f6544229 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/ublox-odin-w2-drivers/cb_gatt_client.h +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/ublox-odin-w2-drivers/cb_gatt_client.h @@ -31,9 +31,9 @@ * app must wait until all responses from an outstanding request have been * received. * - In the callback of the request another request can not be done except when - * the request is interrupted by setting the return value to FALSE - * or when in the last callback which contains an error code. - * - Most of the GATT requests can be interrupted by returning FALSE in the + * - The request is interrupted by setting the return value to FALSE + * or when in the last callback which contains an error code. + * - Most of the GATT requests can be interrupted by returning FALSE in the * callback. * * See Bluetooth 4.0 specification for more info on GATT and ATT chapters: diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/ublox-odin-w2-drivers/cb_gatt_server.h b/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/ublox-odin-w2-drivers/cb_gatt_server.h index d2286c6dd49..23656acb8aa 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/ublox-odin-w2-drivers/cb_gatt_server.h +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/ublox-odin-w2-drivers/cb_gatt_server.h @@ -76,7 +76,7 @@ extern "C" { * cbGATT_CLIENT_CHAR_CONFIG - callback that is called when remote device writes the client config cbGATT_ServerWriteClientConfig * cbGATT_SERVER_CHAR_CONFIG - callback that is called when remote device writes the server config cbGATT_ServerWriteServerConfig * cbGATT_CHAR_USER_DESC and all other CHARACTERISTICS value - cbGATT_ServerWriteAttr callback - * @param pAttrHandle Pointer where to write the attribute handle in case it's needed by the app. + * @param pAttrHandle Pointer where to write the attribute handle in case it's needed by the app. * If not needed, pass NULL. Will be written after the service has been added. */ typedef struct @@ -152,7 +152,7 @@ typedef cbGATT_ErrorCode (*cbGATT_ServerReadAttr)( * @param pAttr Pointer to attribute record * @param pAttrValue Pointer where to get the data * @param length The length. - * @param writeMethod Which write method the client is using. + * @param writeMethod Which write method the client is using. * This depends on the properties in the attribute table. * @param offset The offset of the written data * @return cbGATT_ERROR_CODE_OK if accepted or some cbGATT_ERROR_CODE_* code when failed. @@ -183,7 +183,7 @@ typedef cbGATT_ErrorCode (*cbGATT_ServerReadClientConfig)( * @param connHandle Connection handle * @param attrHandle Handle of the attribute value * @param config The config to be stored - * @param writeMethod Which write method the client is using. + * @param writeMethod Which write method the client is using. * This depends on the properties in the attribute table. * @return cbGATT_ERROR_CODE_OK if accepted or some cbGATT_ERROR_CODE_* code when failed. */ @@ -210,7 +210,7 @@ typedef cbGATT_ErrorCode (*cbGATT_ServerReadServerConfig)( * @param connHandle Connection handle * @param attrHandle Handle of the attribute value * @param config The config to be stored - * @param writeMethod Which write method the client is using. + * @param writeMethod Which write method the client is using. * This depends on the properties in the attribute table. * @return cbGATT_ERROR_CODE_OK if accepted or some cbGATT_ERROR_CODE_* code when failed. */ @@ -254,7 +254,7 @@ cb_int32 cbGATT_deregisterAllServers(void); /** * Send notification to GATT client. The characteristicValueNotificationCnf * callback will be called when finished and a new notification can be sent. - * The client config notification must have been enabled by the GATT client + * The client config notification must have been enabled by the GATT client * before an notification can be sent. * @param connHandle Connection handle * @param attrHandle Handle of the attribute value @@ -264,16 +264,16 @@ cb_int32 cbGATT_deregisterAllServers(void); * @return cbGATT_OK if succeeded or some cbGATT_ERROR* when failed. */ cb_int32 cbGATT_notification( - TConnHandle connHandle, - cb_uint16 attrHandle, - cb_uint8* pData, - cb_uint16 length, + TConnHandle connHandle, + cb_uint16 attrHandle, + cb_uint8* pData, + cb_uint16 length, cb_uint8 appHandle); /** * Send indication to GATT client. The characteristicValueIndicationCnf * callback will be called when finished and a new indication can be sent. - * The client config indication must have been enabled by the GATT client + * The client config indication must have been enabled by the GATT client * before an indication can be sent. * @param connHandle Connection handle * @param attrHandle Handle of the attribute value @@ -283,17 +283,17 @@ cb_int32 cbGATT_notification( * @return cbGATT_OK if succeeded or some cbGATT_ERROR* when failed. */ cb_int32 cbGATT_indication( - TConnHandle connHandle, - cb_uint16 attrHandle, - cb_uint8* pData, - cb_uint16 length, + TConnHandle connHandle, + cb_uint16 attrHandle, + cb_uint8* pData, + cb_uint16 length, cb_uint8 appHandle); /** * Delay write respone to client, see cbGATT_ServerWriteAttr * @param connHandle Connection handle * @param attrHandle Handle of the attribute value - * @param errorCode Error code, use cbGATT_ERROR_CODE_OK if OK otherwise some cbGATT_ERROR_CODE_* + * @param errorCode Error code, use cbGATT_ERROR_CODE_OK if OK otherwise some cbGATT_ERROR_CODE_* * @return cbGATT_OK if succeeded or some cbGATT_ERROR* when failed. */ cb_int32 cbGATT_writeRsp( @@ -305,15 +305,15 @@ cb_int32 cbGATT_writeRsp( * Add service list to attribute database * @param pAttrList Attribute list * @param attrListSize Size of the attribute list - * @param startHandle Start handle. Note that startHandle for the application - * should start at lowest 1024, cbGATT_APP_START_SERVICE_HANDLE. + * @param startHandle Start handle. Note that startHandle for the application + * should start at lowest 1024, cbGATT_APP_START_SERVICE_HANDLE. * 1-1023 is reserved for GATT/GAP and other u-blox services. * @return cbGATT_OK if succeeded or some cbGATT_ERROR* when failed. */ cb_int32 cbGATT_addService( const cbGATT_Attribute* pAttrList, - cb_uint16 attrListSize, - cb_uint16 startHandle); + cb_uint16 attrListSize, + cb_int16 startHandle); /** * NOTE: Only for tests diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/ublox-odin-w2-drivers/cb_hw.h b/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/ublox-odin-w2-drivers/cb_hw.h index df4887ed3ce..b0b3f5cba55 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/ublox-odin-w2-drivers/cb_hw.h +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/ublox-odin-w2-drivers/cb_hw.h @@ -59,11 +59,6 @@ typedef enum { cbHW_IRQ_LOW = 12U }cbHW_PRIO_LVL; -typedef enum { - cbHW_SYSTICK_DISABLED, - cbHW_SYSTICK_LOW_FREQ, - cbHW_SYSTICK_DEFAULT, -} cbHW_SysTickMode; /*=========================================================================== * TYPES *=========================================================================*/ @@ -84,7 +79,6 @@ void cbHW_enterSleepMode(void); void cbHW_enterStopMode(void); void cbHW_setWakeupEvent(void); void cbHW_resetWakeupEvent(void); -void cbHW_setSysTickMode(cbHW_SysTickMode sysTickMode); /** * Wait for specified amount of microseconds. May be interrupt dependent. @@ -149,3 +143,4 @@ void cbHW_enableAllIrq(void); #endif + diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/ublox-odin-w2-drivers/cb_status.h b/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/ublox-odin-w2-drivers/cb_status.h index c1c51444936..9e2f5d72de6 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/ublox-odin-w2-drivers/cb_status.h +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/ublox-odin-w2-drivers/cb_status.h @@ -26,9 +26,7 @@ *=========================================================================*/ #define OK(status) (status == cbSTATUS_OK) -#define BUSY(status) (status == cbSTATUS_BUSY) -#define ERR(status) (status == cbSTATUS_ERROR) - + /*=========================================================================== * TYPES *=========================================================================*/ @@ -38,7 +36,6 @@ cbSTATUS_OK, cbSTATUS_ERROR, cbSTATUS_BUSY, - cbSTATUS_RECEIVE_DATA_MODE, cbSTATUS_TIMEOUT } cbRTSL_Status; diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/ublox-odin-w2-drivers/cb_wlan.h b/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/ublox-odin-w2-drivers/cb_wlan.h index b5f2992a543..a451e9ff8e1 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/ublox-odin-w2-drivers/cb_wlan.h +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/ublox-odin-w2-drivers/cb_wlan.h @@ -31,7 +31,6 @@ #include "cb_types.h" #include "cb_wlan_types.h" -#include "cb_cert_utils.h" #include "cb_status.h" #ifdef __cplusplus @@ -76,6 +75,25 @@ extern "C" { /*=========================================================================== * TYPES *=========================================================================*/ + +typedef struct cbWLAN_Stream_s cbWLAN_Stream; +typedef cb_uint32 cbWLAN_StreamPosition; + +/** + * Stream vtable interface used by WLAN supplicant to access SSL certificates + * for WPA Enterprise authentication. + * + * @ingroup wlan + */ +struct cbWLAN_Stream_s { + cb_int32 (*read)(const cbWLAN_Stream *stream, void *buf, cb_uint32 count); /**< Read function pointer, place count bytes in buf. */ + cb_int32 (*write)(const cbWLAN_Stream *stream, void *buf, cb_uint32 count); /**< Read function pointer, place count bytes in buf. */ + void (*rewind)(const cbWLAN_Stream *stream); /**< Rewind function pointer, rewind stream internal iterator to the beginning. Mandatory for all streams. */ + void (*setPosition)(const cbWLAN_Stream *stream, cbWLAN_StreamPosition position); /**< Set absolute position. */ + cbWLAN_StreamPosition (*getPosition)(const cbWLAN_Stream *stream); /**< Get current position. */ + cb_uint32 (*getSize)(const cbWLAN_Stream *stream); /**< GetSize function pointer, return total size of stream contents. */ +}; + /** * Start parameters passed to WLAN driver. * @@ -160,8 +178,8 @@ typedef struct cbWLAN_EnterpriseConnectParameters { cb_uint8 username[cbWLAN_MAX_USERNAME_LENGTH]; /**< Username string. */ cb_uint8 passphrase[cbWLAN_MAX_PASSPHRASE_LENGTH]; /**< Passphrase string. */ cb_uint8 domain[cbWLAN_MAX_DOMAIN_LENGTH]; /**< Domain string. */ - cbCERT_Stream *clientCertificate; /**< Stream handle to provide SSL certificate for authentication. */ - cbCERT_Stream *clientPrivateKey; /**< STream handle to provide SSL private key for authentication. */ + cbWLAN_Stream *clientCertificate; /**< Stream handle to provide SSL certificate for authentication. */ + cbWLAN_Stream *clientPrivateKey; /**< STream handle to provide SSL private key for authentication. */ } cbWLAN_EnterpriseConnectParameters; /** @@ -182,10 +200,9 @@ typedef struct cbWLAN_CommonApParameters { * @ingroup wlan */ typedef struct cbWLAN_WPAPSKApParameters { - cbWLAN_CipherSuite rsnCiphers; /**< Bit field indicating which ciphers that shall be displayed in RSN information elements. If 0 no RSN information elements is added to beacons and probe responses. */ - cbWLAN_CipherSuite wpaCiphers; /**< Bit field indicating which ciphers that shall be displayed in WPA information elements. If 0 no WPA information elements is added to beacons and probe responses. */ - cbWLAN_WPAPSK psk; /**< WPA pre-shared key*/ - cb_uint32 gtkRekeyInterval; /**< Group rekey interval in seconds */ + cbWLAN_CipherSuite rsnCiphers; /**< Bit field indicating which ciphers that shall be displayed in RSN information elements. If 0 no RSN information elements is added to beacons and probe responses. */ + cbWLAN_CipherSuite wpaCiphers; /**< Bit field indicating which ciphers that shall be displayed in WPA information elements. If 0 no WPA information elements is added to beacons and probe responses. */ + cbWLAN_WPAPSK psk; /**< WPA pre-shared key*/ } cbWLAN_WPAPSKApParameters; @@ -269,11 +286,8 @@ typedef enum { cbWLAN_IOCTL_GET_DTIM_ENABLE, //!< Get DTIM enable 0, disable 1 enable cbWLAN_IOCTL_SET_SLEEP_TIMEOUT, //!< Set enter power save entry delay (in ms). Power save mode will be entered only if there no activity during this delay cbWLAN_IOCTL_GET_SLEEP_TIMEOUT, //!< Get enter power save entry delay (in ms). Power save mode will be entered only if there no activity during this delay + cbWLAN_IOCTL_LAST, - cbWLAN_IOCTL_SET_GSETTING = 1000, //!< Pipe to @ref cbWM_gSet. - cbWLAN_IOCTL_SET_TSETTING = 2000, //!< Pipe to @ref cbWM_tSet. - cbWLAN_IOCTL_GET_GSETTING = 3000, //!< Pipe to @ref cbWM_gGet. - cbWLAN_IOCTL_GET_TSETTING = 4000, //!< Pipe to @ref cbWM_tGet. } cbWLAN_Ioctl; /** diff --git a/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/wifi_emac/wifi_emac_api.cpp b/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/wifi_emac/wifi_emac_api.cpp index 0839fcd7439..67eb1bb24b4 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/wifi_emac/wifi_emac_api.cpp +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_UBLOX_EVK_ODIN_W2/sdk/wifi_emac/wifi_emac_api.cpp @@ -328,11 +328,9 @@ static void wifi_set_link_state_cb(emac_interface_t *emac, emac_link_state_chang emac_interface_t* wifi_emac_get_interface() { if (_intf == NULL) { - _intf = (emac_interface_t*)malloc(sizeof(emac_interface_t)); - if (_intf) { - _intf->hw = NULL; - memcpy((void*)&_intf->ops, &wifi_emac_interface, sizeof(wifi_emac_interface)); - } + _intf = new emac_interface_t(); + _intf->hw = NULL; + memcpy((void*)&_intf->ops, &wifi_emac_interface, sizeof(wifi_emac_interface)); } return _intf; } diff --git a/targets/TARGET_STM/TARGET_STM32F4/analogin_api.c b/targets/TARGET_STM/TARGET_STM32F4/analogin_api.c index 80acc0664d2..62fac456916 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/analogin_api.c +++ b/targets/TARGET_STM/TARGET_STM32F4/analogin_api.c @@ -40,9 +40,6 @@ ADC_HandleTypeDef AdcHandle; void analogin_init(analogin_t *obj, PinName pin) { - uint32_t function = (uint32_t)NC; - obj->adc = (ADCName)NC; - #if defined(ADC1) static int adc1_inited = 0; #endif @@ -52,28 +49,21 @@ void analogin_init(analogin_t *obj, PinName pin) #if defined(ADC3) static int adc3_inited = 0; #endif - // ADC Internal Channels "pins" (Temperature, Vref, Vbat, ...) - // are described in PinNames.h and PeripheralPins.c - // Pin value must be >= 0xF0 - if (pin < 0xF0) { - // Normal channels - // Get the peripheral name from the pin and assign it to the object - obj->adc = (ADCName)pinmap_peripheral(pin, PinMap_ADC); - // Get the functions (adc channel) from the pin and assign it to the object - function = pinmap_function(pin, PinMap_ADC); - // Configure GPIO - pinmap_pinout(pin, PinMap_ADC); - } else { - // Internal channels - obj->adc = (ADCName)pinmap_peripheral(pin, PinMap_ADC_Internal); - function = pinmap_function(pin, PinMap_ADC_Internal); - // No GPIO configuration for internal channels - } + // Get the peripheral name from the pin and assign it to the object + obj->adc = (ADCName)pinmap_peripheral(pin, PinMap_ADC); MBED_ASSERT(obj->adc != (ADCName)NC); - MBED_ASSERT(function != (uint32_t)NC); + // Get the functions (adc channel) from the pin and assign it to the object + uint32_t function = pinmap_function(pin, PinMap_ADC); + MBED_ASSERT(function != (uint32_t)NC); obj->channel = STM_PIN_CHANNEL(function); + // Configure GPIO excepted for internal channels (Temperature, Vref, Vbat, ...) + // ADC Internal Channels "pins" are described in PinNames.h and must have a value >= 0xF0 + if (pin < 0xF0) { + pinmap_pinout(pin, PinMap_ADC); + } + // Save pin number for the read function obj->pin = pin; diff --git a/targets/TARGET_STM/TARGET_STM32F4/device/stm32f4xx_hal_def.h b/targets/TARGET_STM/TARGET_STM32F4/device/stm32f4xx_hal_def.h index d5a391acc21..6aedd87567c 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/device/stm32f4xx_hal_def.h +++ b/targets/TARGET_STM/TARGET_STM32F4/device/stm32f4xx_hal_def.h @@ -146,7 +146,7 @@ static inline void atomic_clr_u32(volatile uint32_t *ptr, uint32_t mask) #endif /* USE_RTOS */ -#if defined ( __GNUC__ ) && !defined ( __CC_ARM ) +#if defined ( __GNUC__ ) #ifndef __weak #define __weak __attribute__((weak)) #endif /* __weak */ diff --git a/targets/TARGET_STM/TARGET_STM32F4/device/stm32f4xx_hal_dma.c b/targets/TARGET_STM/TARGET_STM32F4/device/stm32f4xx_hal_dma.c index b71176bf28c..4ffd98d3a2b 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/device/stm32f4xx_hal_dma.c +++ b/targets/TARGET_STM/TARGET_STM32F4/device/stm32f4xx_hal_dma.c @@ -762,6 +762,9 @@ void HAL_DMA_IRQHandler(DMA_HandleTypeDef *hdma) /* Update error code */ hdma->ErrorCode |= HAL_DMA_ERROR_TE; + + /* Change the DMA state */ + hdma->State = HAL_DMA_STATE_ERROR; // FIX } } /* FIFO Error Interrupt management ******************************************/ @@ -774,6 +777,9 @@ void HAL_DMA_IRQHandler(DMA_HandleTypeDef *hdma) /* Update error code */ hdma->ErrorCode |= HAL_DMA_ERROR_FE; + + /* Change the DMA state */ + hdma->State = HAL_DMA_STATE_ERROR; // FIX } } /* Direct Mode Error Interrupt management ***********************************/ @@ -786,6 +792,9 @@ void HAL_DMA_IRQHandler(DMA_HandleTypeDef *hdma) /* Update error code */ hdma->ErrorCode |= HAL_DMA_ERROR_DME; + + /* Change the DMA state */ + hdma->State = HAL_DMA_STATE_ERROR; // FIX } } /* Half Transfer Complete Interrupt management ******************************/ @@ -802,6 +811,9 @@ void HAL_DMA_IRQHandler(DMA_HandleTypeDef *hdma) /* Current memory buffer used is Memory 0 */ if((hdma->Instance->CR & DMA_SxCR_CT) == RESET) { + /* Change DMA peripheral state */ + hdma->State = HAL_DMA_STATE_READY_HALF_MEM0; // FIX + if(hdma->XferHalfCpltCallback != NULL) { /* Half transfer callback */ @@ -811,6 +823,9 @@ void HAL_DMA_IRQHandler(DMA_HandleTypeDef *hdma) /* Current memory buffer used is Memory 1 */ else { + /* Change DMA peripheral state */ + hdma->State = HAL_DMA_STATE_READY_HALF_MEM1; // FIX + if(hdma->XferM1HalfCpltCallback != NULL) { /* Half transfer callback */ @@ -827,6 +842,9 @@ void HAL_DMA_IRQHandler(DMA_HandleTypeDef *hdma) hdma->Instance->CR &= ~(DMA_IT_HT); } + /* Change DMA peripheral state */ + hdma->State = HAL_DMA_STATE_READY_HALF_MEM0; // FIX + if(hdma->XferHalfCpltCallback != NULL) { /* Half transfer callback */ @@ -875,6 +893,9 @@ void HAL_DMA_IRQHandler(DMA_HandleTypeDef *hdma) /* Current memory buffer used is Memory 0 */ if((hdma->Instance->CR & DMA_SxCR_CT) == RESET) { + /* Change DMA peripheral state */ + hdma->State = HAL_DMA_STATE_READY_MEM1; // FIX + if(hdma->XferM1CpltCallback != NULL) { /* Transfer complete Callback for memory1 */ @@ -884,6 +905,9 @@ void HAL_DMA_IRQHandler(DMA_HandleTypeDef *hdma) /* Current memory buffer used is Memory 1 */ else { + /* Change DMA peripheral state */ + hdma->State = HAL_DMA_STATE_READY_MEM0; // FIX + if(hdma->XferCpltCallback != NULL) { /* Transfer complete Callback for memory0 */ @@ -894,6 +918,9 @@ void HAL_DMA_IRQHandler(DMA_HandleTypeDef *hdma) /* Disable the transfer complete interrupt if the DMA mode is not CIRCULAR */ else { + /* Change DMA peripheral state */ + hdma->State = HAL_DMA_STATE_READY_MEM0; // FIX + if((hdma->Instance->CR & DMA_SxCR_CIRC) == RESET) { /* Disable the transfer complete interrupt */ diff --git a/targets/TARGET_STM/TARGET_STM32F4/device/stm32f4xx_hal_dma.h b/targets/TARGET_STM/TARGET_STM32F4/device/stm32f4xx_hal_dma.h index 13258838fe4..d2c9e828d41 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/device/stm32f4xx_hal_dma.h +++ b/targets/TARGET_STM/TARGET_STM32F4/device/stm32f4xx_hal_dma.h @@ -122,7 +122,13 @@ typedef enum { HAL_DMA_STATE_RESET = 0x00U, /*!< DMA not yet initialized or disabled */ HAL_DMA_STATE_READY = 0x01U, /*!< DMA initialized and ready for use */ + HAL_DMA_STATE_READY_MEM0 = 0x11U, /*!< DMA Mem0 process success */ // FIX + HAL_DMA_STATE_READY_MEM1 = 0x21U, /*!< DMA Mem1 process success */ // FIX + HAL_DMA_STATE_READY_HALF_MEM0 = 0x31U, /*!< DMA Mem0 Half process success */ // FIX + HAL_DMA_STATE_READY_HALF_MEM1 = 0x41U, /*!< DMA Mem1 Half process success */ // FIX HAL_DMA_STATE_BUSY = 0x02U, /*!< DMA process is ongoing */ + HAL_DMA_STATE_BUSY_MEM0 = 0x12U, /*!< DMA Mem0 process is ongoing */ // FIX + HAL_DMA_STATE_BUSY_MEM1 = 0x22U, /*!< DMA Mem1 process is ongoing */ // FIX HAL_DMA_STATE_TIMEOUT = 0x03U, /*!< DMA timeout state */ HAL_DMA_STATE_ERROR = 0x04U, /*!< DMA error state */ HAL_DMA_STATE_ABORT = 0x05U, /*!< DMA Abort state */ diff --git a/targets/TARGET_STM/TARGET_STM32F4/device/stm32f4xx_hal_hcd.c b/targets/TARGET_STM/TARGET_STM32F4/device/stm32f4xx_hal_hcd.c index 91c0e76d596..25a8e574df2 100644 --- a/targets/TARGET_STM/TARGET_STM32F4/device/stm32f4xx_hal_hcd.c +++ b/targets/TARGET_STM/TARGET_STM32F4/device/stm32f4xx_hal_hcd.c @@ -931,14 +931,10 @@ static void HCD_HC_IN_IRQHandler(HCD_HandleTypeDef *hhcd, uint8_t chnum) /* re-activate the channel */ tmpreg = USBx_HC(chnum)->HCCHAR; tmpreg &= ~USB_OTG_HCCHAR_CHDIS; - if ( hhcd->hc[chnum].urb_state != URB_ERROR) { - tmpreg |= USB_OTG_HCCHAR_CHENA; - reactivate = 1; - } + tmpreg |= USB_OTG_HCCHAR_CHENA; USBx_HC(chnum)->HCCHAR = tmpreg; - + reactivate = 1; } - if (hhcd->hc[chnum].state == 0) reactivate = 1; __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_CHH); if (reactivate == 0) HAL_HCD_HC_NotifyURBChange_Callback(hhcd, chnum, hhcd->hc[chnum].urb_state); } diff --git a/features/unsupported/USBDevice/USBDevice/TARGET_STM/TARGET_STM32F7/TARGET_STM32F769xI/TARGET_DISCO_F769NI/USBHAL_STM32F769NI.h b/targets/TARGET_STM/TARGET_STM32F7/TARGET_DISCO_F769NI/USBHAL_STM32F769NI.h similarity index 100% rename from features/unsupported/USBDevice/USBDevice/TARGET_STM/TARGET_STM32F7/TARGET_STM32F769xI/TARGET_DISCO_F769NI/USBHAL_STM32F769NI.h rename to targets/TARGET_STM/TARGET_STM32F7/TARGET_DISCO_F769NI/USBHAL_STM32F769NI.h diff --git a/features/unsupported/USBDevice/USBDevice/TARGET_STM/TARGET_STM32F7/TARGET_STM32F769xI/TARGET_DISCO_F769NI/USBHAL_STM_TARGET.h b/targets/TARGET_STM/TARGET_STM32F7/TARGET_DISCO_F769NI/USBHAL_STM_TARGET.h similarity index 100% rename from features/unsupported/USBDevice/USBDevice/TARGET_STM/TARGET_STM32F7/TARGET_STM32F769xI/TARGET_DISCO_F769NI/USBHAL_STM_TARGET.h rename to targets/TARGET_STM/TARGET_STM32F7/TARGET_DISCO_F769NI/USBHAL_STM_TARGET.h diff --git a/features/unsupported/USBHost/USBHost/TARGET_STM/TARGET_STM32F7/TARGET_STM32F767xI/TARGET_NUCLEO_F767ZI/USBHALHost_STM_TARGET.h b/targets/TARGET_STM/TARGET_STM32F7/TARGET_NUCLEO_F767ZI/USBHALHost_STM_TARGET.h similarity index 100% rename from features/unsupported/USBHost/USBHost/TARGET_STM/TARGET_STM32F7/TARGET_STM32F767xI/TARGET_NUCLEO_F767ZI/USBHALHost_STM_TARGET.h rename to targets/TARGET_STM/TARGET_STM32F7/TARGET_NUCLEO_F767ZI/USBHALHost_STM_TARGET.h diff --git a/features/unsupported/USBDevice/USBDevice/TARGET_STM/TARGET_STM32F4/TARGET_STM32F446xE/TARGET_NUCLEO_F446ZE/USBHAL_STM_TARGET.h b/targets/TARGET_STM/TARGET_STM32F7/TARGET_NUCLEO_F767ZI/USBHAL_STM_TARGET.h similarity index 100% rename from features/unsupported/USBDevice/USBDevice/TARGET_STM/TARGET_STM32F4/TARGET_STM32F446xE/TARGET_NUCLEO_F446ZE/USBHAL_STM_TARGET.h rename to targets/TARGET_STM/TARGET_STM32F7/TARGET_NUCLEO_F767ZI/USBHAL_STM_TARGET.h diff --git a/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F746xG/TARGET_DISCO_F746NG/PeripheralPins.c b/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F746xG/TARGET_DISCO_F746NG/PeripheralPins.c index 3c6f75417bb..00e6344228d 100644 --- a/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F746xG/TARGET_DISCO_F746NG/PeripheralPins.c +++ b/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F746xG/TARGET_DISCO_F746NG/PeripheralPins.c @@ -47,10 +47,6 @@ const PinMap PinMap_ADC[] = { {PF_8, ADC_3, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 6, 0)}, // ADC3_IN6 - ARDUINO A3 {PF_9, ADC_3, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 7, 0)}, // ADC3_IN7 - ARDUINO A2 {PF_10, ADC_3, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 8, 0)}, // ADC3_IN8 - ARDUINO A1 - {NC, NC, 0} -}; - -const PinMap PinMap_ADC_Internal[] = { {ADC_TEMP, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 16, 0)}, // See in analogin_api.c the correct ADC channel used {ADC_VREF, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 17, 0)}, // See in analogin_api.c the correct ADC channel used {ADC_VBAT, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 18, 0)}, // See in analogin_api.c the correct ADC channel used diff --git a/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F746xG/TARGET_DISCO_F746NG/PinNames.h b/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F746xG/TARGET_DISCO_F746NG/PinNames.h index f834d11a3b4..7bcd0a29581 100644 --- a/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F746xG/TARGET_DISCO_F746NG/PinNames.h +++ b/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F746xG/TARGET_DISCO_F746NG/PinNames.h @@ -252,8 +252,6 @@ typedef enum { LED3 = PI_1, LED4 = PI_1, USER_BUTTON = PI_11, - // Standardized button names - BUTTON1 = USER_BUTTON, SERIAL_TX = PA_9, // Virtual Com Port SERIAL_RX = PB_7, // Virtual Com Port USBTX = PA_9, // Virtual Com Port diff --git a/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F746xG/TARGET_NUCLEO_F746ZG/PeripheralPins.c b/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F746xG/TARGET_NUCLEO_F746ZG/PeripheralPins.c index 7908d384477..0709bca3ee7 100644 --- a/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F746xG/TARGET_NUCLEO_F746ZG/PeripheralPins.c +++ b/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F746xG/TARGET_NUCLEO_F746ZG/PeripheralPins.c @@ -48,7 +48,7 @@ const PinMap PinMap_ADC[] = { {PA_4, ADC_2, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 4, 0)}, // ADC2_IN4 {PA_5, ADC_2, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 5, 0)}, // ADC2_IN5 - ARDUINO D13 {PA_6, ADC_2, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 6, 0)}, // ADC2_IN6 - ARDUINO D12 - {PA_7, ADC_2, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 7, 0)}, // ADC2_IN7 (used by ethernet when JP6 ON) - ARDUINO D11 (default configuration) + {PA_7, ADC_2, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 7, 0)}, // ADC2_IN7 (JP6) - ARDUINO D11 // {PB_0, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 8, 0)}, // ADC1_IN8 (used by LED1) {PB_1, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 9, 0)}, // ADC1_IN9 {PC_0, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0,10, 0)}, // ADC1_IN10 - ARDUINO A1 @@ -65,10 +65,6 @@ const PinMap PinMap_ADC[] = { {PF_8, ADC_3, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 6, 0)}, // ADC3_IN6 {PF_9, ADC_3, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 7, 0)}, // ADC3_IN7 {PF_10, ADC_3, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 8, 0)}, // ADC3_IN8 - ARDUINO A5 - {NC, NC, 0} -}; - -const PinMap PinMap_ADC_Internal[] = { {ADC_TEMP, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 16, 0)}, // See in analogin_api.c the correct ADC channel used {ADC_VREF, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 17, 0)}, // See in analogin_api.c the correct ADC channel used {ADC_VBAT, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 18, 0)}, // See in analogin_api.c the correct ADC channel used @@ -124,10 +120,10 @@ const PinMap PinMap_PWM[] = { // {PA_5, PWM_8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 1, 1)}, // TIM8_CH1N {PA_6, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 1, 0)}, // TIM3_CH1 // {PA_6, PWM_13, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF9_TIM13, 1, 0)}, // TIM13_CH1 - {PA_7, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 1, 1)}, // TIM1_CH1N (used by ethernet when JP6 ON) - ARDUINO D11 (default configuration) - // {PA_7, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 2, 0)}, // TIM3_CH2 (used by ethernet when JP6 ON) - // {PA_7, PWM_8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 1, 1)}, // TIM8_CH1N (used by ethernet when JP6 ON) - // {PA_7, PWM_14, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF9_TIM14, 1, 0)}, // TIM14_CH1 (used by ethernet when JP6 ON) + // {PA_7, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 1, 1)}, // TIM1_CH1N (used by ethernet) + // {PA_7, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 2, 0)}, // TIM3_CH2 (used by ethernet) + // {PA_7, PWM_8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 1, 1)}, // TIM8_CH1N (used by ethernet) + // {PA_7, PWM_14, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF9_TIM14, 1, 0)}, // TIM14_CH1 (used by ethernet) {PA_8, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 1, 0)}, // TIM1_CH1 // {PA_9, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 2, 0)}, // TIM1_CH2 (used by USB) // {PA_10, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 3, 0)}, // TIM1_CH3 (used by USB) @@ -142,9 +138,7 @@ const PinMap PinMap_PWM[] = { // {PB_1, PWM_8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 3, 1)}, // TIM8_CH3N {PB_3, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 2, 0)}, // TIM2_CH2 {PB_4, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 1, 0)}, // TIM3_CH1 - {PB_5, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 2, 0)}, // TIM3_CH2 - ARDUINO D11 (need HW and SW updates) - // HW solder bridge update : SB121 off, SB122 on - // SW : config from json files + {PB_5, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 2, 0)}, // TIM3_CH2 {PB_6, PWM_4, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM4, 1, 0)}, // TIM4_CH1 // {PB_7, PWM_4, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM4, 2, 0)}, // TIM4_CH2 (used by LED2) {PB_8, PWM_4, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM4, 3, 0)}, // TIM4_CH3 @@ -273,14 +267,12 @@ const PinMap PinMap_UART_CTS[] = { //*** SPI *** const PinMap PinMap_SPI_MOSI[] = { - {PA_7, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI1)}, // used by ethernet when JP6 ON - ARDUINO D11 (default configuration) + {PA_7, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI1)}, // ARDUINO D11 (remove JP6 to use it) {PB_2, SPI_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF7_SPI3)}, - {PB_5, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI1)}, // ARDUINO D11 (need HW and SW updates) - // HW solder bridge update : SB121 off, SB122 on - // SW : config from json files + {PB_5, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI1)}, // {PB_5, SPI_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF6_SPI3)}, {PB_15, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI2)}, - // {PC_1, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI2)}, // (used by ethernet) + // {PC_1, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI2)}, // (used by Ethernet) {PC_3, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI2)}, // ARDUINO A2 {PC_12, SPI_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF6_SPI3)}, {PD_6, SPI_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI3)}, @@ -318,7 +310,7 @@ const PinMap PinMap_SPI_SCLK[] = { {PE_2, SPI_4, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI4)}, {PE_12, SPI_4, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI4)}, {PF_7, SPI_5, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI5)}, - // {PG_13, SPI_6, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI6)}, // (used by ethernet) + // {PG_13, SPI_6, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI6)}, // (used by Ethernet) {NC, NC, 0} }; @@ -336,15 +328,11 @@ const PinMap PinMap_SPI_SSEL[] = { {NC, NC, 0} }; -//*** CAN *** - const PinMap PinMap_CAN_RD[] = { {PB_8 , CAN_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF9_CAN1)}, {PB_12 , CAN_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF9_CAN2)}, {PD_0 , CAN_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF9_CAN1)}, - {PB_5 , CAN_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF9_CAN2)}, // ARDUINO D11 (need HW and SW updates) - // HW solder bridge update : SB121 off, SB122 on - // SW : config from json files + {PB_5 , CAN_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF9_CAN2)}, {PA_11, CAN_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF9_CAN1)}, {NC, NC, 0} }; diff --git a/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F746xG/TARGET_NUCLEO_F746ZG/PinNames.h b/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F746xG/TARGET_NUCLEO_F746ZG/PinNames.h index e370605c0e8..d9078bfb886 100644 --- a/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F746xG/TARGET_NUCLEO_F746ZG/PinNames.h +++ b/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F746xG/TARGET_NUCLEO_F746ZG/PinNames.h @@ -183,7 +183,7 @@ typedef enum { D8 = PF_12, D9 = PD_15, D10 = PD_14, - D11 = STM32_D11_SPI_ETHERNET_PIN, /* config in targets.json file */ + D11 = PA_7, D12 = PA_6, D13 = PA_5, D14 = PB_9, @@ -195,8 +195,6 @@ typedef enum { LED3 = PB_14, // Red LED4 = PB_0, USER_BUTTON = PC_13, - // Standardized button names - BUTTON1 = USER_BUTTON, SERIAL_TX = PD_8, // Virtual Com Port SERIAL_RX = PD_9, // Virtual Com Port USBTX = PD_8, // Virtual Com Port diff --git a/features/unsupported/USBHost/USBHost/TARGET_STM/TARGET_STM32F4/TARGET_STM32F446xE/TARGET_NUCLEO_F446RE/USBHALHost_STM_TARGET.h b/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F746xG/TARGET_NUCLEO_F746ZG/USBHALHost_STM_TARGET.h similarity index 100% rename from features/unsupported/USBHost/USBHost/TARGET_STM/TARGET_STM32F4/TARGET_STM32F446xE/TARGET_NUCLEO_F446RE/USBHALHost_STM_TARGET.h rename to targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F746xG/TARGET_NUCLEO_F746ZG/USBHALHost_STM_TARGET.h diff --git a/features/unsupported/USBDevice/USBDevice/TARGET_STM/TARGET_STM32F7/TARGET_STM32F746xG/TARGET_NUCLEO_F746ZG/USBHAL_STM_TARGET.h b/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F746xG/TARGET_NUCLEO_F746ZG/USBHAL_STM_TARGET.h similarity index 100% rename from features/unsupported/USBDevice/USBDevice/TARGET_STM/TARGET_STM32F7/TARGET_STM32F746xG/TARGET_NUCLEO_F746ZG/USBHAL_STM_TARGET.h rename to targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F746xG/TARGET_NUCLEO_F746ZG/USBHAL_STM_TARGET.h diff --git a/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F756xG/TARGET_NUCLEO_F756ZG/PeripheralPins.c b/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F756xG/TARGET_NUCLEO_F756ZG/PeripheralPins.c index 7908d384477..0709bca3ee7 100644 --- a/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F756xG/TARGET_NUCLEO_F756ZG/PeripheralPins.c +++ b/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F756xG/TARGET_NUCLEO_F756ZG/PeripheralPins.c @@ -48,7 +48,7 @@ const PinMap PinMap_ADC[] = { {PA_4, ADC_2, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 4, 0)}, // ADC2_IN4 {PA_5, ADC_2, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 5, 0)}, // ADC2_IN5 - ARDUINO D13 {PA_6, ADC_2, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 6, 0)}, // ADC2_IN6 - ARDUINO D12 - {PA_7, ADC_2, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 7, 0)}, // ADC2_IN7 (used by ethernet when JP6 ON) - ARDUINO D11 (default configuration) + {PA_7, ADC_2, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 7, 0)}, // ADC2_IN7 (JP6) - ARDUINO D11 // {PB_0, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 8, 0)}, // ADC1_IN8 (used by LED1) {PB_1, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 9, 0)}, // ADC1_IN9 {PC_0, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0,10, 0)}, // ADC1_IN10 - ARDUINO A1 @@ -65,10 +65,6 @@ const PinMap PinMap_ADC[] = { {PF_8, ADC_3, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 6, 0)}, // ADC3_IN6 {PF_9, ADC_3, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 7, 0)}, // ADC3_IN7 {PF_10, ADC_3, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 8, 0)}, // ADC3_IN8 - ARDUINO A5 - {NC, NC, 0} -}; - -const PinMap PinMap_ADC_Internal[] = { {ADC_TEMP, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 16, 0)}, // See in analogin_api.c the correct ADC channel used {ADC_VREF, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 17, 0)}, // See in analogin_api.c the correct ADC channel used {ADC_VBAT, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 18, 0)}, // See in analogin_api.c the correct ADC channel used @@ -124,10 +120,10 @@ const PinMap PinMap_PWM[] = { // {PA_5, PWM_8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 1, 1)}, // TIM8_CH1N {PA_6, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 1, 0)}, // TIM3_CH1 // {PA_6, PWM_13, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF9_TIM13, 1, 0)}, // TIM13_CH1 - {PA_7, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 1, 1)}, // TIM1_CH1N (used by ethernet when JP6 ON) - ARDUINO D11 (default configuration) - // {PA_7, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 2, 0)}, // TIM3_CH2 (used by ethernet when JP6 ON) - // {PA_7, PWM_8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 1, 1)}, // TIM8_CH1N (used by ethernet when JP6 ON) - // {PA_7, PWM_14, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF9_TIM14, 1, 0)}, // TIM14_CH1 (used by ethernet when JP6 ON) + // {PA_7, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 1, 1)}, // TIM1_CH1N (used by ethernet) + // {PA_7, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 2, 0)}, // TIM3_CH2 (used by ethernet) + // {PA_7, PWM_8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 1, 1)}, // TIM8_CH1N (used by ethernet) + // {PA_7, PWM_14, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF9_TIM14, 1, 0)}, // TIM14_CH1 (used by ethernet) {PA_8, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 1, 0)}, // TIM1_CH1 // {PA_9, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 2, 0)}, // TIM1_CH2 (used by USB) // {PA_10, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 3, 0)}, // TIM1_CH3 (used by USB) @@ -142,9 +138,7 @@ const PinMap PinMap_PWM[] = { // {PB_1, PWM_8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 3, 1)}, // TIM8_CH3N {PB_3, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 2, 0)}, // TIM2_CH2 {PB_4, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 1, 0)}, // TIM3_CH1 - {PB_5, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 2, 0)}, // TIM3_CH2 - ARDUINO D11 (need HW and SW updates) - // HW solder bridge update : SB121 off, SB122 on - // SW : config from json files + {PB_5, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 2, 0)}, // TIM3_CH2 {PB_6, PWM_4, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM4, 1, 0)}, // TIM4_CH1 // {PB_7, PWM_4, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM4, 2, 0)}, // TIM4_CH2 (used by LED2) {PB_8, PWM_4, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM4, 3, 0)}, // TIM4_CH3 @@ -273,14 +267,12 @@ const PinMap PinMap_UART_CTS[] = { //*** SPI *** const PinMap PinMap_SPI_MOSI[] = { - {PA_7, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI1)}, // used by ethernet when JP6 ON - ARDUINO D11 (default configuration) + {PA_7, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI1)}, // ARDUINO D11 (remove JP6 to use it) {PB_2, SPI_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF7_SPI3)}, - {PB_5, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI1)}, // ARDUINO D11 (need HW and SW updates) - // HW solder bridge update : SB121 off, SB122 on - // SW : config from json files + {PB_5, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI1)}, // {PB_5, SPI_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF6_SPI3)}, {PB_15, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI2)}, - // {PC_1, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI2)}, // (used by ethernet) + // {PC_1, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI2)}, // (used by Ethernet) {PC_3, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI2)}, // ARDUINO A2 {PC_12, SPI_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF6_SPI3)}, {PD_6, SPI_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI3)}, @@ -318,7 +310,7 @@ const PinMap PinMap_SPI_SCLK[] = { {PE_2, SPI_4, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI4)}, {PE_12, SPI_4, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI4)}, {PF_7, SPI_5, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI5)}, - // {PG_13, SPI_6, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI6)}, // (used by ethernet) + // {PG_13, SPI_6, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI6)}, // (used by Ethernet) {NC, NC, 0} }; @@ -336,15 +328,11 @@ const PinMap PinMap_SPI_SSEL[] = { {NC, NC, 0} }; -//*** CAN *** - const PinMap PinMap_CAN_RD[] = { {PB_8 , CAN_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF9_CAN1)}, {PB_12 , CAN_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF9_CAN2)}, {PD_0 , CAN_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF9_CAN1)}, - {PB_5 , CAN_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF9_CAN2)}, // ARDUINO D11 (need HW and SW updates) - // HW solder bridge update : SB121 off, SB122 on - // SW : config from json files + {PB_5 , CAN_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF9_CAN2)}, {PA_11, CAN_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF9_CAN1)}, {NC, NC, 0} }; diff --git a/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F756xG/TARGET_NUCLEO_F756ZG/PinNames.h b/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F756xG/TARGET_NUCLEO_F756ZG/PinNames.h index e370605c0e8..d9078bfb886 100644 --- a/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F756xG/TARGET_NUCLEO_F756ZG/PinNames.h +++ b/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F756xG/TARGET_NUCLEO_F756ZG/PinNames.h @@ -183,7 +183,7 @@ typedef enum { D8 = PF_12, D9 = PD_15, D10 = PD_14, - D11 = STM32_D11_SPI_ETHERNET_PIN, /* config in targets.json file */ + D11 = PA_7, D12 = PA_6, D13 = PA_5, D14 = PB_9, @@ -195,8 +195,6 @@ typedef enum { LED3 = PB_14, // Red LED4 = PB_0, USER_BUTTON = PC_13, - // Standardized button names - BUTTON1 = USER_BUTTON, SERIAL_TX = PD_8, // Virtual Com Port SERIAL_RX = PD_9, // Virtual Com Port USBTX = PD_8, // Virtual Com Port diff --git a/features/unsupported/USBHost/USBHost/TARGET_STM/TARGET_STM32F7/TARGET_STM32F746xG/TARGET_NUCLEO_F746ZG/USBHALHost_STM_TARGET.h b/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F756xG/TARGET_NUCLEO_F756ZG/USBHALHost_STM_TARGET.h similarity index 100% rename from features/unsupported/USBHost/USBHost/TARGET_STM/TARGET_STM32F7/TARGET_STM32F746xG/TARGET_NUCLEO_F746ZG/USBHALHost_STM_TARGET.h rename to targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F756xG/TARGET_NUCLEO_F756ZG/USBHALHost_STM_TARGET.h diff --git a/features/unsupported/USBDevice/USBDevice/TARGET_STM/TARGET_STM32F7/TARGET_STM32F756xG/TARGET_NUCLEO_F756ZG/USBHAL_STM_TARGET.h b/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F756xG/TARGET_NUCLEO_F756ZG/USBHAL_STM_TARGET.h similarity index 100% rename from features/unsupported/USBDevice/USBDevice/TARGET_STM/TARGET_STM32F7/TARGET_STM32F756xG/TARGET_NUCLEO_F756ZG/USBHAL_STM_TARGET.h rename to targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F756xG/TARGET_NUCLEO_F756ZG/USBHAL_STM_TARGET.h diff --git a/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F756xG/device/TOOLCHAIN_IAR/stm32f756xg.icf b/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F756xG/device/TOOLCHAIN_IAR/stm32f756xg.icf index 09800c02be2..2982e0ddc7e 100644 --- a/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F756xG/device/TOOLCHAIN_IAR/stm32f756xg.icf +++ b/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F756xG/device/TOOLCHAIN_IAR/stm32f756xg.icf @@ -19,8 +19,9 @@ define region RAM_region = mem:[from __region_RAM_start__ to __region_RAM_end__] define region ITCMRAM_region = mem:[from __region_ITCMRAM_start__ to __region_ITCMRAM_end__]; /* Stack and Heap */ +/*Heap 1/4 of ram and stack 1/8*/ define symbol __size_cstack__ = 0x4000; -define symbol __size_heap__ = 0x10000; +define symbol __size_heap__ = 0x8000; define block CSTACK with alignment = 8, size = __size_cstack__ { }; define block HEAP with alignment = 8, size = __size_heap__ { }; define block STACKHEAP with fixed order { block HEAP, block CSTACK }; diff --git a/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F767xI/TARGET_NUCLEO_F767ZI/PeripheralPins.c b/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F767xI/TARGET_NUCLEO_F767ZI/PeripheralPins.c index 8f520ad7a58..99aa32741bf 100644 --- a/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F767xI/TARGET_NUCLEO_F767ZI/PeripheralPins.c +++ b/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F767xI/TARGET_NUCLEO_F767ZI/PeripheralPins.c @@ -48,7 +48,7 @@ const PinMap PinMap_ADC[] = { {PA_4, ADC_2, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 4, 0)}, // ADC2_IN4 {PA_5, ADC_2, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 5, 0)}, // ADC2_IN5 - ARDUINO D13 {PA_6, ADC_2, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 6, 0)}, // ADC2_IN6 - ARDUINO D12 - {PA_7, ADC_2, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 7, 0)}, // ADC2_IN7 (used by ethernet when JP6 ON) - ARDUINO D11 (default configuration) + {PA_7, ADC_2, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 7, 0)}, // ADC2_IN7 (JP6) - ARDUINO D11 // {PB_0, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 8, 0)}, // ADC1_IN8 (used by LED1) {PB_1, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 9, 0)}, // ADC1_IN9 {PC_0, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0,10, 0)}, // ADC1_IN10 - ARDUINO A1 @@ -65,10 +65,6 @@ const PinMap PinMap_ADC[] = { {PF_8, ADC_3, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 6, 0)}, // ADC3_IN6 {PF_9, ADC_3, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 7, 0)}, // ADC3_IN7 {PF_10, ADC_3, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 8, 0)}, // ADC3_IN8 - ARDUINO A5 - {NC, NC, 0} -}; - -const PinMap PinMap_ADC_Internal[] = { {ADC_TEMP, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 16, 0)}, // See in analogin_api.c the correct ADC channel used {ADC_VREF, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 17, 0)}, // See in analogin_api.c the correct ADC channel used {ADC_VBAT, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 18, 0)}, // See in analogin_api.c the correct ADC channel used @@ -124,10 +120,10 @@ const PinMap PinMap_PWM[] = { // {PA_5, PWM_8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 1, 1)}, // TIM8_CH1N {PA_6, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 1, 0)}, // TIM3_CH1 // {PA_6, PWM_13, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF9_TIM13, 1, 0)}, // TIM13_CH1 - {PA_7, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 1, 1)}, // TIM1_CH1N (used by ethernet when JP6 ON) - ARDUINO D11 (default configuration) - // {PA_7, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 2, 0)}, // TIM3_CH2 (used by ethernet when JP6 ON) - // {PA_7, PWM_8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 1, 1)}, // TIM8_CH1N (used by ethernet when JP6 ON) - // {PA_7, PWM_14, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF9_TIM14, 1, 0)}, // TIM14_CH1 (used by ethernet when JP6 ON) + // {PA_7, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 1, 1)}, // TIM1_CH1N (used by ethernet) + // {PA_7, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 2, 0)}, // TIM3_CH2 (used by ethernet) + // {PA_7, PWM_8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 1, 1)}, // TIM8_CH1N (used by ethernet) + // {PA_7, PWM_14, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF9_TIM14, 1, 0)}, // TIM14_CH1 (used by ethernet) {PA_8, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 1, 0)}, // TIM1_CH1 // {PA_9, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 2, 0)}, // TIM1_CH2 (used by USB) // {PA_10, PWM_1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1, 3, 0)}, // TIM1_CH3 (used by USB) @@ -142,9 +138,7 @@ const PinMap PinMap_PWM[] = { // {PB_1, PWM_8, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM8, 3, 1)}, // TIM8_CH3N {PB_3, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 2, 0)}, // TIM2_CH2 {PB_4, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 1, 0)}, // TIM3_CH1 - {PB_5, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 2, 0)}, // TIM3_CH2 - ARDUINO D11 (need HW and SW updates) - // HW solder bridge update : SB121 off, SB122 on - // SW : config from json files + {PB_5, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 2, 0)}, // TIM3_CH2 {PB_6, PWM_4, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM4, 1, 0)}, // TIM4_CH1 // {PB_7, PWM_4, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM4, 2, 0)}, // TIM4_CH2 (used by LED2) {PB_8, PWM_4, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM4, 3, 0)}, // TIM4_CH3 @@ -273,14 +267,12 @@ const PinMap PinMap_UART_CTS[] = { //*** SPI *** const PinMap PinMap_SPI_MOSI[] = { - {PA_7, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI1)}, // used by ethernet when JP6 ON - ARDUINO D11 (default configuration) + {PA_7, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI1)}, // ARDUINO D11 (remove JP6 to use it) {PB_2, SPI_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF7_SPI3)}, - {PB_5, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI1)}, // ARDUINO D11 (need HW and SW updates) - // HW solder bridge update : SB121 off, SB122 on - // SW : config from json files + {PB_5, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI1)}, // {PB_5, SPI_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF6_SPI3)}, {PB_15, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI2)}, - // {PC_1, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI2)}, // (used by ethernet) + // {PC_1, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI2)}, // (used by Ethernet) {PC_3, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI2)}, // ARDUINO A2 {PC_12, SPI_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF6_SPI3)}, {PD_6, SPI_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI3)}, @@ -318,7 +310,7 @@ const PinMap PinMap_SPI_SCLK[] = { {PE_2, SPI_4, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI4)}, {PE_12, SPI_4, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI4)}, {PF_7, SPI_5, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI5)}, - // {PG_13, SPI_6, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI6)}, // (used by ethernet) + // {PG_13, SPI_6, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF5_SPI6)}, // (used by Ethernet) {NC, NC, 0} }; @@ -342,9 +334,7 @@ const PinMap PinMap_CAN_RD[] = { {PA_8, CAN_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF11_CAN3)}, {PA_11, CAN_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF9_CAN1)}, {PB_3, CAN_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF11_CAN3)}, - {PB_5, CAN_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF9_CAN2)}, // ARDUINO D11 (need HW and SW updates) - // HW solder bridge update : SB121 off, SB122 on - // SW : config from json files + {PB_5, CAN_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF9_CAN2)}, {PB_8, CAN_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF9_CAN1)}, {PB_12, CAN_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF9_CAN2)}, {PD_0, CAN_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF9_CAN1)}, diff --git a/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F767xI/TARGET_NUCLEO_F767ZI/PinNames.h b/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F767xI/TARGET_NUCLEO_F767ZI/PinNames.h index e370605c0e8..d9078bfb886 100644 --- a/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F767xI/TARGET_NUCLEO_F767ZI/PinNames.h +++ b/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F767xI/TARGET_NUCLEO_F767ZI/PinNames.h @@ -183,7 +183,7 @@ typedef enum { D8 = PF_12, D9 = PD_15, D10 = PD_14, - D11 = STM32_D11_SPI_ETHERNET_PIN, /* config in targets.json file */ + D11 = PA_7, D12 = PA_6, D13 = PA_5, D14 = PB_9, @@ -195,8 +195,6 @@ typedef enum { LED3 = PB_14, // Red LED4 = PB_0, USER_BUTTON = PC_13, - // Standardized button names - BUTTON1 = USER_BUTTON, SERIAL_TX = PD_8, // Virtual Com Port SERIAL_RX = PD_9, // Virtual Com Port USBTX = PD_8, // Virtual Com Port diff --git a/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F767xI/device/TOOLCHAIN_IAR/stm32f767xi.icf b/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F767xI/device/TOOLCHAIN_IAR/stm32f767xi.icf index 1c73fc150da..7af894aeb41 100644 --- a/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F767xI/device/TOOLCHAIN_IAR/stm32f767xi.icf +++ b/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F767xI/device/TOOLCHAIN_IAR/stm32f767xi.icf @@ -19,8 +19,9 @@ define region RAM_region = mem:[from __region_RAM_start__ to __region_RAM_end__] define region ITCMRAM_region = mem:[from __region_ITCMRAM_start__ to __region_ITCMRAM_end__]; /* Stack and Heap */ +/*Heap 1/4 of ram and stack 1/8*/ define symbol __size_cstack__ = 0x8000; -define symbol __size_heap__ = 0x10000; +define symbol __size_heap__ = 0x8000; define block CSTACK with alignment = 8, size = __size_cstack__ { }; define block HEAP with alignment = 8, size = __size_heap__ { }; define block STACKHEAP with fixed order { block HEAP, block CSTACK }; diff --git a/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F769xI/TARGET_DISCO_F769NI/PeripheralPins.c b/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F769xI/TARGET_DISCO_F769NI/PeripheralPins.c index cdeac8394ab..5d0967e5eb2 100644 --- a/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F769xI/TARGET_DISCO_F769NI/PeripheralPins.c +++ b/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F769xI/TARGET_DISCO_F769NI/PeripheralPins.c @@ -52,10 +52,6 @@ const PinMap PinMap_ADC[] = { {PF_8, ADC_3, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 6, 0)}, // ADC3_IN6 - ARDUINO A4 {PF_9, ADC_3, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 7, 0)}, // ADC3_IN7 - ARDUINO A5 {PF_10, ADC_3, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 8, 0)}, // ADC3_IN8 - ARDUINO A3 - {NC, NC, 0} -}; - -const PinMap PinMap_ADC_Internal[] = { {ADC_TEMP, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 16, 0)}, // See in analogin_api.c the correct ADC channel used {ADC_VREF, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 17, 0)}, // See in analogin_api.c the correct ADC channel used {ADC_VBAT, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 18, 0)}, // See in analogin_api.c the correct ADC channel used diff --git a/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F769xI/TARGET_DISCO_F769NI/PinNames.h b/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F769xI/TARGET_DISCO_F769NI/PinNames.h index 10d0723997d..aa3d0bb0c3a 100644 --- a/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F769xI/TARGET_DISCO_F769NI/PinNames.h +++ b/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F769xI/TARGET_DISCO_F769NI/PinNames.h @@ -252,8 +252,6 @@ typedef enum { LED3 = PA_12, // LD3 = GREEN LED4 = PJ_13, USER_BUTTON = PA_0, - // Standardized button names - BUTTON1 = USER_BUTTON, SERIAL_TX = PA_9, // Virtual Com Port SERIAL_RX = PA_10, // Virtual Com Port USBTX = PA_9, // Virtual Com Port diff --git a/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F769xI/device/TOOLCHAIN_IAR/stm32f769xi.icf b/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F769xI/device/TOOLCHAIN_IAR/stm32f769xi.icf index 1c73fc150da..7af894aeb41 100644 --- a/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F769xI/device/TOOLCHAIN_IAR/stm32f769xi.icf +++ b/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F769xI/device/TOOLCHAIN_IAR/stm32f769xi.icf @@ -19,8 +19,9 @@ define region RAM_region = mem:[from __region_RAM_start__ to __region_RAM_end__] define region ITCMRAM_region = mem:[from __region_ITCMRAM_start__ to __region_ITCMRAM_end__]; /* Stack and Heap */ +/*Heap 1/4 of ram and stack 1/8*/ define symbol __size_cstack__ = 0x8000; -define symbol __size_heap__ = 0x10000; +define symbol __size_heap__ = 0x8000; define block CSTACK with alignment = 8, size = __size_cstack__ { }; define block HEAP with alignment = 8, size = __size_heap__ { }; define block STACKHEAP with fixed order { block HEAP, block CSTACK }; diff --git a/targets/TARGET_STM/TARGET_STM32F7/analogin_api.c b/targets/TARGET_STM/TARGET_STM32F7/analogin_api.c index 4751affe0b4..dac331aeba3 100644 --- a/targets/TARGET_STM/TARGET_STM32F7/analogin_api.c +++ b/targets/TARGET_STM/TARGET_STM32F7/analogin_api.c @@ -40,9 +40,6 @@ ADC_HandleTypeDef AdcHandle; void analogin_init(analogin_t *obj, PinName pin) { - uint32_t function = (uint32_t)NC; - obj->adc = (ADCName)NC; - #if defined(ADC1) static int adc1_inited = 0; #endif @@ -52,28 +49,22 @@ void analogin_init(analogin_t *obj, PinName pin) #if defined(ADC3) static int adc3_inited = 0; #endif - // ADC Internal Channels "pins" (Temperature, Vref, Vbat, ...) - // are described in PinNames.h and PeripheralPins.c - // Pin value must be >= 0xF0 - if (pin < 0xF0) { - // Normal channels - // Get the peripheral name from the pin and assign it to the object - obj->adc = (ADCName)pinmap_peripheral(pin, PinMap_ADC); - // Get the functions (adc channel) from the pin and assign it to the object - function = pinmap_function(pin, PinMap_ADC); - // Configure GPIO - pinmap_pinout(pin, PinMap_ADC); - } else { - // Internal channels - obj->adc = (ADCName)pinmap_peripheral(pin, PinMap_ADC_Internal); - function = pinmap_function(pin, PinMap_ADC_Internal); - // No GPIO configuration for internal channels - } + + // Get the peripheral name from the pin and assign it to the object + obj->adc = (ADCName)pinmap_peripheral(pin, PinMap_ADC); MBED_ASSERT(obj->adc != (ADCName)NC); - MBED_ASSERT(function != (uint32_t)NC); + // Get the functions (adc channel) from the pin and assign it to the object + uint32_t function = pinmap_function(pin, PinMap_ADC); + MBED_ASSERT(function != (uint32_t)NC); obj->channel = STM_PIN_CHANNEL(function); + // Configure GPIO excepted for internal channels (Temperature, Vref, Vbat, ...) + // ADC Internal Channels "pins" are described in PinNames.h and must have a value >= 0xF0 + if (pin < 0xF0) { + pinmap_pinout(pin, PinMap_ADC); + } + // Save pin number for the read function obj->pin = pin; diff --git a/targets/TARGET_STM/TARGET_STM32F7/device/stm32f7xx_hal_def.h b/targets/TARGET_STM/TARGET_STM32F7/device/stm32f7xx_hal_def.h index 3afc2682b8c..b41b409bf6c 100644 --- a/targets/TARGET_STM/TARGET_STM32F7/device/stm32f7xx_hal_def.h +++ b/targets/TARGET_STM/TARGET_STM32F7/device/stm32f7xx_hal_def.h @@ -145,7 +145,7 @@ static inline void atomic_clr_u32(volatile uint32_t *ptr, uint32_t mask) } while (__STREXW(newValue,(volatile unsigned long*) ptr)); } -#if defined ( __GNUC__ ) && !defined ( __CC_ARM ) +#if defined ( __GNUC__ ) #ifndef __weak #define __weak __attribute__((weak)) #endif /* __weak */ diff --git a/targets/TARGET_STM/TARGET_STM32F7/device/stm32f7xx_hal_hcd.c b/targets/TARGET_STM/TARGET_STM32F7/device/stm32f7xx_hal_hcd.c index 962ee719bf8..860708d4a2b 100644 --- a/targets/TARGET_STM/TARGET_STM32F7/device/stm32f7xx_hal_hcd.c +++ b/targets/TARGET_STM/TARGET_STM32F7/device/stm32f7xx_hal_hcd.c @@ -932,14 +932,11 @@ static void HCD_HC_IN_IRQHandler (HCD_HandleTypeDef *hhcd, uint8_t chnum) /* re-activate the channel */ tmpreg = USBx_HC(chnum)->HCCHAR; tmpreg &= ~USB_OTG_HCCHAR_CHDIS; - if ( hhcd->hc[chnum].urb_state != URB_ERROR) { - tmpreg |= USB_OTG_HCCHAR_CHENA; - reactivate = 1; - } + tmpreg |= USB_OTG_HCCHAR_CHENA; USBx_HC(chnum)->HCCHAR = tmpreg; + reactivate = 1; } __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_CHH); - if (hhcd->hc[chnum].state == 0) reactivate = 1; if (reactivate == 0 )HAL_HCD_HC_NotifyURBChange_Callback(hhcd, chnum, hhcd->hc[chnum].urb_state); } diff --git a/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L053C8/PinNames.h b/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L053C8/PinNames.h index 434a3ead33b..0713c2c7190 100644 --- a/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L053C8/PinNames.h +++ b/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L053C8/PinNames.h @@ -116,8 +116,6 @@ typedef enum { LED3 = PB_4, LED4 = PA_5, USER_BUTTON = PA_0, - // Standardized button names - BUTTON1 = USER_BUTTON, SERIAL_TX = PA_9, SERIAL_RX = PA_10, USBTX = PA_9, diff --git a/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L053C8/device/TOOLCHAIN_IAR/stm32l053xx.icf b/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L053C8/device/TOOLCHAIN_IAR/stm32l053xx.icf index 96e6cf2b5d5..cd494490d25 100644 --- a/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L053C8/device/TOOLCHAIN_IAR/stm32l053xx.icf +++ b/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L053C8/device/TOOLCHAIN_IAR/stm32l053xx.icf @@ -15,8 +15,8 @@ define region ROM_region = mem:[from __region_ROM_start__ to __region_ROM_end__] define region RAM_region = mem:[from __region_RAM_start__ to __region_RAM_end__]; /* Stack and Heap */ -define symbol __size_cstack__ = 0x400; -define symbol __size_heap__ = 0x800; +define symbol __size_cstack__ = 0x500; +define symbol __size_heap__ = 0x1000; define block CSTACK with alignment = 8, size = __size_cstack__ { }; define block HEAP with alignment = 8, size = __size_heap__ { }; define block STACKHEAP with fixed order { block HEAP, block CSTACK }; diff --git a/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L053C8/device/system_stm32l0xx.c b/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L053C8/device/system_stm32l0xx.c index a8e6abd1222..19e28260251 100644 --- a/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L053C8/device/system_stm32l0xx.c +++ b/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L053C8/device/system_stm32l0xx.c @@ -377,8 +377,10 @@ uint8_t SetSysClock_PLL_HSE(uint8_t bypass) RCC_OscInitStruct.HSEState = RCC_HSE_BYPASS; /* External 8 MHz clock on OSC_IN */ } RCC_OscInitStruct.HSIState = RCC_HSI_OFF; +#if !defined (STM32L031xx) && !defined (STM32L041xx) && !defined(STM32L051xx) && !defined(STM32L061xx) && !defined(STM32L071xx) && !defined(STM32L081xx) && \ + !defined (STM32L011xx) && !defined (STM32L021xx) RCC_OscInitStruct.HSI48State = RCC_HSI48_ON; /* For USB and RNG clock */ - +#endif // PLLCLK = (8 MHz * 8)/2 = 32 MHz RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; @@ -389,12 +391,6 @@ uint8_t SetSysClock_PLL_HSE(uint8_t bypass) return 0; // FAIL } - /* Select HSI48 as USB clock source */ - RCC_PeriphCLKInitTypeDef PeriphClkInitStruct; - PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_USB; - PeriphClkInitStruct.UsbClockSelection = RCC_USBCLKSOURCE_HSI48; - HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct); - /* Select PLL as system clock source and configure the HCLK, PCLK1 and PCLK2 clocks dividers */ RCC_ClkInitStruct.ClockType = (RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2); RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; // 32 MHz diff --git a/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L072CZ_LRWAN1/PeripheralNames.h b/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L072CZ_LRWAN1/PeripheralNames.h deleted file mode 100644 index 087804bb409..00000000000 --- a/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L072CZ_LRWAN1/PeripheralNames.h +++ /dev/null @@ -1,81 +0,0 @@ -/* mbed Microcontroller Library - ******************************************************************************* - * Copyright (c) 2017, STMicroelectronics - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************* - */ -#ifndef MBED_PERIPHERALNAMES_H -#define MBED_PERIPHERALNAMES_H - -#include "cmsis.h" - -#ifdef __cplusplus -extern "C" { -#endif - -typedef enum { - ADC_1 = (int)ADC1_BASE -} ADCName; - -typedef enum { - DAC_1 = (int)DAC_BASE -} DACName; - -typedef enum { - UART_1 = (int)USART1_BASE, - UART_2 = (int)USART2_BASE, - UART_4 = (int)USART4_BASE, - UART_5 = (int)USART5_BASE, - LPUART_1 = (int)LPUART1_BASE -} UARTName; - -#define STDIO_UART_TX PA_2 -#define STDIO_UART_RX PA_3 -#define STDIO_UART UART_2 - -typedef enum { - SPI_1 = (int)SPI1_BASE, - SPI_2 = (int)SPI2_BASE -} SPIName; - -typedef enum { - I2C_1 = (int)I2C1_BASE, - I2C_2 = (int)I2C2_BASE, - I2C_3 = (int)I2C3_BASE -} I2CName; - -typedef enum { - PWM_2 = (int)TIM2_BASE, - PWM_3 = (int)TIM3_BASE, - PWM_21 = (int)TIM21_BASE, - PWM_22 = (int)TIM22_BASE -} PWMName; - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L072CZ_LRWAN1/PeripheralPins.c b/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L072CZ_LRWAN1/PeripheralPins.c deleted file mode 100644 index 49baeaec073..00000000000 --- a/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L072CZ_LRWAN1/PeripheralPins.c +++ /dev/null @@ -1,213 +0,0 @@ -/* mbed Microcontroller Library - ******************************************************************************* - * Copyright (c) 2017, STMicroelectronics - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************* - */ - -#include "PeripheralPins.h" - -// ===== -// Note: Commented lines are alternative possibilities which are not used per default. -// If you change them, you will have also to modify the corresponding xxx_api.c file -// for pwmout, analogin, analogout, ... -// ===== - -//*** ADC *** - -const PinMap PinMap_ADC[] = { - {PA_0, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 0, 0)}, // ARDUINO A0 - {PA_1, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 1, 0)}, // Pin not available on any connector -// {PA_2, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 2, 0)}, // ARDUINO D1 - Used by STDIO_UART_TX -// {PA_3, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 3, 0)}, // ARDUINO D0 - Used by STDIO_UART_RX - {PA_4, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 4, 0)}, // ARDUINO A2 - {PA_5, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 5, 0)}, // CN3.7 - Used also to drive LED2 - {PA_6, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 6, 0)}, // Pin not available on any connector - {PA_7, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 7, 0)}, // Pin not available on any connector - {PB_0, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 8, 0)}, // Pin not available on any connector - {PB_1, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 9, 0)}, // Pin not available on any connector - {PC_0, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 10, 0)}, // Pin not available on any connector - {PC_1, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 11, 0)}, // Pin not available on any connector - {PC_2, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 12, 0)}, // Pin not available on any connector - {NC, NC, 0} -}; - -const PinMap PinMap_ADC_Internal[] = { - {ADC_TEMP, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 17, 0)}, // Internal channel - {ADC_VREF, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 0, 0)}, // Internal channel - {ADC_VBAT, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 18, 0)}, // Internal channel - {NC, NC, 0} -}; - -//*** DAC *** - -const PinMap PinMap_DAC[] = { - {PA_4, DAC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 1, 0)}, // ARDUINO A2 - {PA_5, DAC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 2, 0)}, // CN3.7 - Used also to drive LED2 - {NC, NC, 0} -}; - -//*** I2C *** - -const PinMap PinMap_I2C_SDA[] = { - {PA_10, I2C_1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF6_I2C1)}, // ARDUINO D2 - {PB_4, I2C_3, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF7_I2C3)}, // Pin not available on any connector - {PB_7, I2C_1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF1_I2C1)}, // ARDUINO D5 - Used also to drive LED4 - {PB_9, I2C_1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C1)}, // ARDUINO D14 - {PB_11, I2C_2, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF6_I2C2)}, // Pin not available on any connector - {PB_14, I2C_2, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF5_I2C2)}, // ARDUINO D12 - {PC_1, I2C_3, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF7_I2C3)}, // Pin not available on any connector - {NC, NC, 0} -}; - -const PinMap PinMap_I2C_SCL[] = { - {PA_8, I2C_3, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF7_I2C3)}, // ARDUINO D7 - {PA_9, I2C_1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF6_I2C1)}, // ARDUINO D8 - {PB_6, I2C_1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF1_I2C1)}, // ARDUINO D10 - Used also to drive LED3 - {PB_8, I2C_1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C1)}, // ARDUINO D15 - {PB_10, I2C_2, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF6_I2C2)}, // Pin not available on any connector - {PB_13, I2C_2, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF5_I2C2)}, // ARDUINO D13 - {PC_0, I2C_3, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF7_I2C3)}, // Pin not available on any connector - {NC, NC, 0} -}; - -//*** PWM *** -// Pins using TIM21 cannot be used as TIM21 is already used by ticker. -const PinMap PinMap_PWM[] = { - {PA_0, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM2, 1, 0)}, // ARDUINO A0 - {PA_1, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM2, 2, 0)}, // Pin not available on any connector -// {PA_2, PWM_21, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_TIM21, 1, 0)}, // ARDUINO D1 - Used by STDIO_UART_TX -// {PA_2, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM2, 3, 0)}, // ARDUINO D1 - Used by STDIO_UART_TX -// {PA_3, PWM_21, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_TIM21, 2, 0)}, // ARDUINO D0 - Used by STDIO_UART_RX -// {PA_3, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM2, 4, 0)}, // ARDUINO D0 - Used by STDIO_UART_RX - {PA_5, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_TIM2, 1, 0)}, // CN3.7 - Used also to drive LED2 - {PA_6, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 1, 0)}, // Pin not available on any connector - {PA_6_ALT0, PWM_22, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_TIM22, 1, 0)}, // Pin not available on any connector - {PA_7, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 2, 0)}, // Pin not available on any connector - {PA_7_ALT0, PWM_22, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_TIM22, 2, 0)}, // Pin not available on any connector - {PA_15, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_TIM2, 1, 0)}, // Pin not available on any connector - {PB_0, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 3, 0)}, // Pin not available on any connector - {PB_1, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 4, 0)}, // Pin not available on any connector - {PB_3, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM2, 2, 0)}, // Pin not available on any connector - {PB_4, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 1, 0)}, // Pin not available on any connector - {PB_4_ALT0, PWM_22, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_TIM22, 1, 0)}, // Pin not available on any connector - {PB_5, PWM_22, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_TIM22, 2, 0)}, // ARDUINO D4 - Used also to drive LED1 - {PB_5_ALT0, PWM_3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_TIM3, 2, 0)}, // ARDUINO D4 - Used also to drive LED1 - {PB_10, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM2, 3, 0)}, // Pin not available on any connector - {PB_11, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM2, 4, 0)}, // Pin not available on any connector -// {PB_13, PWM_21, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_TIM21, 1, 0)}, // ARDUINO D13 - TIM21 used by ticker -// {PB_14, PWM_21, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_TIM21, 2, 0)}, // ARDUINO D12 - TIM21 used by ticker - {NC, NC, 0} -}; - -//*** SERIAL *** - -const PinMap PinMap_UART_TX[] = { - {PA_0, UART_4, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_USART4)}, // ARDUINO A0 - {PA_2, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_USART2)}, // ARDUINO D1 - Used by STDIO_UART_TX -// {PA_2, LPUART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_LPUART1)}, // ARDUINO D1 - UART2 is already used by STDIO_UART_TX - {PA_9, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_USART1)}, // ARDUINO D8 - {PA_14, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_USART2)}, // Warning: this pin is used by SWCLK - {PA_14_ALT0, LPUART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_LPUART1)}, // Warning: this pin is used by SWCLK - {PB_3, UART_5, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_USART5)}, // Pin not available on any connector - {PB_6, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_USART1)}, // ARDUINO D10 - Used also to drive LED3 - {PB_10, LPUART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_LPUART1)}, // Pin not available on any connector - {PB_11, LPUART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_LPUART1)}, // Pin not available on any connector - {PC_1, LPUART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_LPUART1)}, // Pin not available on any connector - {NC, NC, 0} -}; - -const PinMap PinMap_UART_RX[] = { - {PA_1, UART_4, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_USART4)}, // Pin not available on any connector - {PA_3, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_USART2)}, // ARDUINO D0 - Used by STDIO_UART_RX -// {PA_3, LPUART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_LPUART1)}, // ARDUINO D0 - UART2 is already used by STDIO_UART_RX - {PA_10, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_USART1)}, // ARDUINO D2 - {PA_13, LPUART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_LPUART1)}, // Warning: this pin is used by SWDIO - {PA_15, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_USART2)}, // Pin not available on any connector - {PB_4, UART_5, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_USART5)}, // Pin not available on any connector - {PB_7, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_USART1)}, // ARDUINO D5 - Used also to drive LED4 - {PB_10, LPUART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_LPUART1)}, // Pin not available on any connector - {PB_11, LPUART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_LPUART1)}, // Pin not available on any connector - {PC_0, LPUART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_LPUART1)}, // Pin not available on any connector - {NC, NC, 0} -}; - -const PinMap PinMap_UART_RTS[] = { - {PA_1, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_USART2)}, // Pin not available on any connector - {PA_12, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_USART1)}, // CN3.14 - {PA_15, UART_4, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_USART4)}, // Pin not available on any connector - {PB_1, LPUART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_LPUART1)}, // Pin not available on any connector - {PB_3, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_USART1)}, // Pin not available on any connector - {PB_5, UART_5, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_USART5)}, // ARDUINO D4 - Used also to drive LED1 - {PB_12, LPUART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_LPUART1)}, // ARDUINO D9 - {PB_14, LPUART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_LPUART1)}, // ARDUINO D12 - {NC, NC, 0} -}; - -const PinMap PinMap_UART_CTS[] = { - {PA_0, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_USART2)}, // ARDUINO A0 - {PA_6, LPUART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_LPUART1)}, // Pin not available on any connector - {PA_11, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_USART1)}, // CN3.15 - {PB_4, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_USART1)}, // Pin not available on any connector - {PB_7, UART_4, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_USART4)}, // ARDUINO D5 - Used also to drive LED4 - {PB_13, LPUART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_LPUART1)}, // ARDUINO D13 - {NC, NC, 0} -}; - -//*** SPI *** - -const PinMap PinMap_SPI_MOSI[] = { - {PA_7, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_SPI1)}, // Pin not available on any connector - {PA_12, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_SPI1)}, // CN3.14 - {PB_5, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_SPI1)}, // ARDUINO D4 - Used also to drive LED1 - {PB_15, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_SPI2)}, // ARDUINO D11 - {NC, NC, 0} -}; - -const PinMap PinMap_SPI_MISO[] = { - {PA_6, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_SPI1)}, // Pin not available on any connector - {PA_11, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_SPI1)}, // CN3.15 - {PB_4, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_SPI1)}, // Pin not available on any connector - {PB_14, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_SPI2)}, // ARDUINO D12 - {PC_2, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_SPI2)}, // Pin not available on any connector - {NC, NC, 0} -}; - -const PinMap PinMap_SPI_SCLK[] = { - {PA_5, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_SPI1)}, // CN3.7 - Used also to drive LED2 - {PB_3, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_SPI1)}, // Pin not available on any connector - {PB_10, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI2)}, // Pin not available on any connector - {PB_13, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_SPI2)}, // ARDUINO D13 - {NC, NC, 0} -}; - -const PinMap PinMap_SPI_SSEL[] = { - {PA_4, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_SPI1)}, // ARDUINO A2 - {PA_15, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_SPI1)}, // Pin not available on any connector - {PB_9, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI2)}, // ARDUINO D14 - {PB_12, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_SPI2)}, // ARDUINO D9 - {NC, NC, 0} -}; diff --git a/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L072CZ_LRWAN1/PinNames.h b/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L072CZ_LRWAN1/PinNames.h deleted file mode 100644 index 8cc9c39e5e7..00000000000 --- a/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L072CZ_LRWAN1/PinNames.h +++ /dev/null @@ -1,149 +0,0 @@ -/* mbed Microcontroller Library - ******************************************************************************* - * Copyright (c) 2017, STMicroelectronics - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************* - */ -#ifndef MBED_PINNAMES_H -#define MBED_PINNAMES_H - -#include "cmsis.h" -#include "PinNamesTypes.h" - -#ifdef __cplusplus -extern "C" { -#endif - -typedef enum { - ALT0 = 0x100, - ALT1 = 0x200, - ALT2 = 0x300, - ALT3 = 0x400 -} ALTx; - -typedef enum { - PA_0 = 0x00, - PA_1 = 0x01, - PA_2 = 0x02, - PA_3 = 0x03, - PA_4 = 0x04, - PA_5 = 0x05, - PA_6 = 0x06, - PA_6_ALT0 = PA_6|ALT0, - PA_7 = 0x07, - PA_7_ALT0 = PA_7|ALT0, - PA_8 = 0x08, - PA_9 = 0x09, - PA_10 = 0x0A, - PA_11 = 0x0B, - PA_12 = 0x0C, - PA_13 = 0x0D, - PA_14 = 0x0E, - PA_14_ALT0 = PA_14|ALT0, - PA_15 = 0x0F, - - PB_0 = 0x10, - PB_1 = 0x11, - PB_2 = 0x12, - PB_3 = 0x13, - PB_4 = 0x14, - PB_4_ALT0 = PB_4|ALT0, - PB_5 = 0x15, - PB_5_ALT0 = PB_5|ALT0, - PB_6 = 0x16, - PB_7 = 0x17, - PB_8 = 0x18, - PB_9 = 0x19, - PB_10 = 0x1A, - PB_11 = 0x1B, - PB_12 = 0x1C, - PB_13 = 0x1D, - PB_14 = 0x1E, - PB_15 = 0x1F, - - PC_0 = 0x20, - PC_1 = 0x21, - PC_2 = 0x22, - - PH_0 = 0x70, - PH_1 = 0x71, - - // ADC internal channels - ADC_TEMP = 0xF0, - ADC_VREF = 0xF1, - ADC_VBAT = 0xF2, - - // Arduino connector namings - A0 = PA_0, - A1 = PA_0, // Alias - A2 = PA_4, - A3 = PA_4, // Alias - A4 = PB_9, // SB11 must be closed - A5 = PB_8, // SB12 must be closed - D0 = PA_3, - D1 = PA_2, - D2 = PA_10, - D3 = PB_13, - D4 = PB_5, - D5 = PB_7, - D6 = PB_2, - D7 = PA_8, - D8 = PA_9, - D9 = PB_12, - D10 = PB_6, - D11 = PB_15, - D12 = PB_14, - D13 = PB_13, // SB2 must be closed - D14 = PB_9, - D15 = PB_8, - - // Generic signals namings - LED1 = PB_5, // Green - LED2 = PA_5, // Red - LED3 = PB_6, // Blue - LED4 = PB_7, // Red - USER_BUTTON = PB_2, - SERIAL_TX = PA_2, - SERIAL_RX = PA_3, - USBTX = SERIAL_TX, - USBRX = SERIAL_RX, - I2C_SCL = D15, - I2C_SDA = D14, - SPI_MOSI = D11, - SPI_MISO = D12, - SPI_SCK = D13, - SPI_CS = D10, - PWM_OUT = D13, - - // Not connected - NC = (int)0xFFFFFFFF -} PinName; - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L072CZ_LRWAN1/device/TOOLCHAIN_ARM_MICRO/startup_stm32l072xx.S b/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L072CZ_LRWAN1/device/TOOLCHAIN_ARM_MICRO/startup_stm32l072xx.S deleted file mode 100644 index f36d2dce03a..00000000000 --- a/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L072CZ_LRWAN1/device/TOOLCHAIN_ARM_MICRO/startup_stm32l072xx.S +++ /dev/null @@ -1,244 +0,0 @@ -;******************** (C) COPYRIGHT 2016 STMicroelectronics ******************** -;* File Name : startup_stm32l072xx.s -;* Author : MCD Application Team -;* Version : V1.7.1 -;* Date : 25-November-2016 -;* Description : STM32l072xx Devices vector table for MDK-ARM toolchain. -;* This module performs: -;* - Set the initial SP -;* - Set the initial PC == Reset_Handler -;* - Set the vector table entries with the exceptions ISR address -;* - Branches to __main in the C lbrary (which eventually -;* calls main()). -;* After Reset the Cortex-M0+ processor is in Thread mode, -;* priority is Privileged, and the Stack is set to Main. -;******************************************************************************* -;* -;* Redistribution and use in source and binary forms, with or without modification, -;* are permitted provided that the following conditions are met: -;* 1. Redistributions of source code must retain the above copyright notice, -;* this list of conditions and the following disclaimer. -;* 2. Redistributions in binary form must reproduce the above copyright notice, -;* this list of conditions and the following disclaimer in the documentation -;* and/or other materials provided with the distribution. -;* 3. Neither the name of STMicroelectronics nor the names of its contributors -;* may be used to endorse or promote products derived from this software -;* without specific prior written permission. -;* -;* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -;* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -;* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -;* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -;* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -;* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -;* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -;* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -;* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -;* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -;* -;******************************************************************************* -; -; Amount of memory (in bytes) allocated for Stack -; Tailor this value to your application needs -; Stack Configuration -; Stack Size (in Bytes) <0x0-0xFFFFFFFF:8> -; - -Stack_Size EQU 0x00000400 - - AREA STACK, NOINIT, READWRITE, ALIGN=3 - EXPORT __initial_sp - -Stack_Mem SPACE Stack_Size -__initial_sp EQU 0x20005000 ; Top of RAM TODO � verifier - - -; Heap Configuration -; Heap Size (in Bytes) <0x0-0xFFFFFFFF:8> -; - -Heap_Size EQU 0x00000400 - - AREA HEAP, NOINIT, READWRITE, ALIGN=3 - EXPORT __heap_base - EXPORT __heap_limit - -__heap_base -Heap_Mem SPACE Heap_Size -__heap_limit EQU (__initial_sp - Stack_Size) - - PRESERVE8 - THUMB - - -; Vector Table Mapped to Address 0 at Reset - AREA RESET, DATA, READONLY - EXPORT __Vectors - EXPORT __Vectors_End - EXPORT __Vectors_Size - -__Vectors DCD __initial_sp ; Top of Stack - DCD Reset_Handler ; Reset Handler - DCD NMI_Handler ; NMI Handler - DCD HardFault_Handler ; Hard Fault Handler - DCD 0 ; Reserved - DCD 0 ; Reserved - DCD 0 ; Reserved - DCD 0 ; Reserved - DCD 0 ; Reserved - DCD 0 ; Reserved - DCD 0 ; Reserved - DCD SVC_Handler ; SVCall Handler - DCD 0 ; Reserved - DCD 0 ; Reserved - DCD PendSV_Handler ; PendSV Handler - DCD SysTick_Handler ; SysTick Handler - - ; External Interrupts - DCD WWDG_IRQHandler ; Window Watchdog - DCD PVD_IRQHandler ; PVD through EXTI Line detect - DCD RTC_IRQHandler ; RTC through EXTI Line - DCD FLASH_IRQHandler ; FLASH - DCD RCC_CRS_IRQHandler ; RCC and CRS - DCD EXTI0_1_IRQHandler ; EXTI Line 0 and 1 - DCD EXTI2_3_IRQHandler ; EXTI Line 2 and 3 - DCD EXTI4_15_IRQHandler ; EXTI Line 4 to 15 - DCD TSC_IRQHandler ; TSC - DCD DMA1_Channel1_IRQHandler ; DMA1 Channel 1 - DCD DMA1_Channel2_3_IRQHandler ; DMA1 Channel 2 and Channel 3 - DCD DMA1_Channel4_5_6_7_IRQHandler ; DMA1 Channel 4, Channel 5, Channel 6 and Channel 7 - DCD ADC1_COMP_IRQHandler ; ADC1, COMP1 and COMP2 - DCD LPTIM1_IRQHandler ; LPTIM1 - DCD USART4_5_IRQHandler ; USART4 and USART5 - DCD TIM2_IRQHandler ; TIM2 - DCD TIM3_IRQHandler ; TIM3 - DCD TIM6_DAC_IRQHandler ; TIM6 and DAC - DCD TIM7_IRQHandler ; TIM7 - DCD 0 ; Reserved - DCD TIM21_IRQHandler ; TIM21 - DCD I2C3_IRQHandler ; I2C3 - DCD TIM22_IRQHandler ; TIM22 - DCD I2C1_IRQHandler ; I2C1 - DCD I2C2_IRQHandler ; I2C2 - DCD SPI1_IRQHandler ; SPI1 - DCD SPI2_IRQHandler ; SPI2 - DCD USART1_IRQHandler ; USART1 - DCD USART2_IRQHandler ; USART2 - DCD RNG_LPUART1_IRQHandler ; RNG and LPUART1 - DCD 0 ; Reserved - DCD USB_IRQHandler ; USB - -__Vectors_End - -__Vectors_Size EQU __Vectors_End - __Vectors - - AREA |.text|, CODE, READONLY - -; Reset handler routine -Reset_Handler PROC - EXPORT Reset_Handler [WEAK] - IMPORT __main - IMPORT SystemInit - LDR R0, =SystemInit - BLX R0 - LDR R0, =__main - BX R0 - ENDP - -; Dummy Exception Handlers (infinite loops which can be modified) - -NMI_Handler PROC - EXPORT NMI_Handler [WEAK] - B . - ENDP -HardFault_Handler\ - PROC - EXPORT HardFault_Handler [WEAK] - B . - ENDP -SVC_Handler PROC - EXPORT SVC_Handler [WEAK] - B . - ENDP -PendSV_Handler PROC - EXPORT PendSV_Handler [WEAK] - B . - ENDP -SysTick_Handler PROC - EXPORT SysTick_Handler [WEAK] - B . - ENDP - -Default_Handler PROC - - EXPORT WWDG_IRQHandler [WEAK] - EXPORT PVD_IRQHandler [WEAK] - EXPORT RTC_IRQHandler [WEAK] - EXPORT FLASH_IRQHandler [WEAK] - EXPORT RCC_CRS_IRQHandler [WEAK] - EXPORT EXTI0_1_IRQHandler [WEAK] - EXPORT EXTI2_3_IRQHandler [WEAK] - EXPORT EXTI4_15_IRQHandler [WEAK] - EXPORT TSC_IRQHandler [WEAK] - EXPORT DMA1_Channel1_IRQHandler [WEAK] - EXPORT DMA1_Channel2_3_IRQHandler [WEAK] - EXPORT DMA1_Channel4_5_6_7_IRQHandler [WEAK] - EXPORT ADC1_COMP_IRQHandler [WEAK] - EXPORT LPTIM1_IRQHandler [WEAK] - EXPORT USART4_5_IRQHandler [WEAK] - EXPORT TIM2_IRQHandler [WEAK] - EXPORT TIM3_IRQHandler [WEAK] - EXPORT TIM6_DAC_IRQHandler [WEAK] - EXPORT TIM7_IRQHandler [WEAK] - EXPORT TIM21_IRQHandler [WEAK] - EXPORT TIM22_IRQHandler [WEAK] - EXPORT I2C1_IRQHandler [WEAK] - EXPORT I2C2_IRQHandler [WEAK] - EXPORT I2C3_IRQHandler [WEAK] - EXPORT SPI1_IRQHandler [WEAK] - EXPORT SPI2_IRQHandler [WEAK] - EXPORT USART1_IRQHandler [WEAK] - EXPORT USART2_IRQHandler [WEAK] - EXPORT RNG_LPUART1_IRQHandler [WEAK] - EXPORT USB_IRQHandler [WEAK] - - -WWDG_IRQHandler -PVD_IRQHandler -RTC_IRQHandler -FLASH_IRQHandler -RCC_CRS_IRQHandler -EXTI0_1_IRQHandler -EXTI2_3_IRQHandler -EXTI4_15_IRQHandler -TSC_IRQHandler -DMA1_Channel1_IRQHandler -DMA1_Channel2_3_IRQHandler -DMA1_Channel4_5_6_7_IRQHandler -ADC1_COMP_IRQHandler -LPTIM1_IRQHandler -USART4_5_IRQHandler -TIM2_IRQHandler -TIM3_IRQHandler -TIM6_DAC_IRQHandler -TIM7_IRQHandler -TIM21_IRQHandler -TIM22_IRQHandler -I2C1_IRQHandler -I2C2_IRQHandler -I2C3_IRQHandler -SPI1_IRQHandler -SPI2_IRQHandler -USART1_IRQHandler -USART2_IRQHandler -RNG_LPUART1_IRQHandler -USB_IRQHandler - - B . - - ENDP - - ALIGN - END - -;************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE***** diff --git a/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L072CZ_LRWAN1/device/TOOLCHAIN_ARM_MICRO/stm32l073xz.sct b/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L072CZ_LRWAN1/device/TOOLCHAIN_ARM_MICRO/stm32l073xz.sct deleted file mode 100644 index c4e915ba952..00000000000 --- a/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L072CZ_LRWAN1/device/TOOLCHAIN_ARM_MICRO/stm32l073xz.sct +++ /dev/null @@ -1,45 +0,0 @@ -; Scatter-Loading Description File -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -; Copyright (c) 2015, STMicroelectronics -; All rights reserved. -; -; Redistribution and use in source and binary forms, with or without -; modification, are permitted provided that the following conditions are met: -; -; 1. Redistributions of source code must retain the above copyright notice, -; this list of conditions and the following disclaimer. -; 2. Redistributions in binary form must reproduce the above copyright notice, -; this list of conditions and the following disclaimer in the documentation -; and/or other materials provided with the distribution. -; 3. Neither the name of STMicroelectronics nor the names of its contributors -; may be used to endorse or promote products derived from this software -; without specific prior written permission. -; -; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -; OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; - -; STM32L073RZ: 192KB FLASH (0x30000) + 20KB RAM (0x5000) -LR_IROM1 0x08000000 0x30000 { ; load region size_region - - ER_IROM1 0x08000000 0x30000 { ; load address = execution address - *.o (RESET, +First) - *(InRoot$$Sections) - .ANY (+RO) - } - - ; Total: 48 vectors = 192 bytes (0xC0) to be reserved in RAM - RW_IRAM1 (0x20000000+0xC0) (0x5000-0xC0) { ; RW data - .ANY (+RW +ZI) - } - -} - diff --git a/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L072CZ_LRWAN1/device/TOOLCHAIN_ARM_STD/startup_stm32l072xx.S b/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L072CZ_LRWAN1/device/TOOLCHAIN_ARM_STD/startup_stm32l072xx.S deleted file mode 100644 index 653372010ce..00000000000 --- a/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L072CZ_LRWAN1/device/TOOLCHAIN_ARM_STD/startup_stm32l072xx.S +++ /dev/null @@ -1,217 +0,0 @@ -;******************** (C) COPYRIGHT 2016 STMicroelectronics ******************** -;* File Name : startup_stm32l072xx.s -;* Author : MCD Application Team -;* Version : V1.7.1 -;* Date : 25-November-2016 -;* Description : STM32l072xx Devices vector table for MDK-ARM toolchain. -;* This module performs: -;* - Set the initial SP -;* - Set the initial PC == Reset_Handler -;* - Set the vector table entries with the exceptions ISR address -;* - Branches to __main in the C lbrary (which eventually -;* calls main()). -;* After Reset the Cortex-M0+ processor is in Thread mode, -;* priority is Privileged, and the Stack is set to Main. -;******************************************************************************* -;* -;* Redistribution and use in source and binary forms, with or without modification, -;* are permitted provided that the following conditions are met: -;* 1. Redistributions of source code must retain the above copyright notice, -;* this list of conditions and the following disclaimer. -;* 2. Redistributions in binary form must reproduce the above copyright notice, -;* this list of conditions and the following disclaimer in the documentation -;* and/or other materials provided with the distribution. -;* 3. Neither the name of STMicroelectronics nor the names of its contributors -;* may be used to endorse or promote products derived from this software -;* without specific prior written permission. -;* -;* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -;* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -;* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -;* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -;* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -;* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -;* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -;* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -;* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -;* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -;* -;******************************************************************************* - -__initial_sp EQU 0x20005000 ; Top of RAM TODO � verifier - - PRESERVE8 - THUMB - - -; Vector Table Mapped to Address 0 at Reset - AREA RESET, DATA, READONLY - EXPORT __Vectors - EXPORT __Vectors_End - EXPORT __Vectors_Size - -__Vectors DCD __initial_sp ; Top of Stack - DCD Reset_Handler ; Reset Handler - DCD NMI_Handler ; NMI Handler - DCD HardFault_Handler ; Hard Fault Handler - DCD 0 ; Reserved - DCD 0 ; Reserved - DCD 0 ; Reserved - DCD 0 ; Reserved - DCD 0 ; Reserved - DCD 0 ; Reserved - DCD 0 ; Reserved - DCD SVC_Handler ; SVCall Handler - DCD 0 ; Reserved - DCD 0 ; Reserved - DCD PendSV_Handler ; PendSV Handler - DCD SysTick_Handler ; SysTick Handler - - ; External Interrupts - DCD WWDG_IRQHandler ; Window Watchdog - DCD PVD_IRQHandler ; PVD through EXTI Line detect - DCD RTC_IRQHandler ; RTC through EXTI Line - DCD FLASH_IRQHandler ; FLASH - DCD RCC_CRS_IRQHandler ; RCC and CRS - DCD EXTI0_1_IRQHandler ; EXTI Line 0 and 1 - DCD EXTI2_3_IRQHandler ; EXTI Line 2 and 3 - DCD EXTI4_15_IRQHandler ; EXTI Line 4 to 15 - DCD TSC_IRQHandler ; TSC - DCD DMA1_Channel1_IRQHandler ; DMA1 Channel 1 - DCD DMA1_Channel2_3_IRQHandler ; DMA1 Channel 2 and Channel 3 - DCD DMA1_Channel4_5_6_7_IRQHandler ; DMA1 Channel 4, Channel 5, Channel 6 and Channel 7 - DCD ADC1_COMP_IRQHandler ; ADC1, COMP1 and COMP2 - DCD LPTIM1_IRQHandler ; LPTIM1 - DCD USART4_5_IRQHandler ; USART4 and USART5 - DCD TIM2_IRQHandler ; TIM2 - DCD TIM3_IRQHandler ; TIM3 - DCD TIM6_DAC_IRQHandler ; TIM6 and DAC - DCD TIM7_IRQHandler ; TIM7 - DCD 0 ; Reserved - DCD TIM21_IRQHandler ; TIM21 - DCD I2C3_IRQHandler ; I2C3 - DCD TIM22_IRQHandler ; TIM22 - DCD I2C1_IRQHandler ; I2C1 - DCD I2C2_IRQHandler ; I2C2 - DCD SPI1_IRQHandler ; SPI1 - DCD SPI2_IRQHandler ; SPI2 - DCD USART1_IRQHandler ; USART1 - DCD USART2_IRQHandler ; USART2 - DCD RNG_LPUART1_IRQHandler ; RNG and LPUART1 - DCD 0 ; Reserved - DCD USB_IRQHandler ; USB - -__Vectors_End - -__Vectors_Size EQU __Vectors_End - __Vectors - - AREA |.text|, CODE, READONLY - -; Reset handler routine -Reset_Handler PROC - EXPORT Reset_Handler [WEAK] - IMPORT __main - IMPORT SystemInit - LDR R0, =SystemInit - BLX R0 - LDR R0, =__main - BX R0 - ENDP - -; Dummy Exception Handlers (infinite loops which can be modified) - -NMI_Handler PROC - EXPORT NMI_Handler [WEAK] - B . - ENDP -HardFault_Handler\ - PROC - EXPORT HardFault_Handler [WEAK] - B . - ENDP -SVC_Handler PROC - EXPORT SVC_Handler [WEAK] - B . - ENDP -PendSV_Handler PROC - EXPORT PendSV_Handler [WEAK] - B . - ENDP -SysTick_Handler PROC - EXPORT SysTick_Handler [WEAK] - B . - ENDP - -Default_Handler PROC - - EXPORT WWDG_IRQHandler [WEAK] - EXPORT PVD_IRQHandler [WEAK] - EXPORT RTC_IRQHandler [WEAK] - EXPORT FLASH_IRQHandler [WEAK] - EXPORT RCC_CRS_IRQHandler [WEAK] - EXPORT EXTI0_1_IRQHandler [WEAK] - EXPORT EXTI2_3_IRQHandler [WEAK] - EXPORT EXTI4_15_IRQHandler [WEAK] - EXPORT TSC_IRQHandler [WEAK] - EXPORT DMA1_Channel1_IRQHandler [WEAK] - EXPORT DMA1_Channel2_3_IRQHandler [WEAK] - EXPORT DMA1_Channel4_5_6_7_IRQHandler [WEAK] - EXPORT ADC1_COMP_IRQHandler [WEAK] - EXPORT LPTIM1_IRQHandler [WEAK] - EXPORT USART4_5_IRQHandler [WEAK] - EXPORT TIM2_IRQHandler [WEAK] - EXPORT TIM3_IRQHandler [WEAK] - EXPORT TIM6_DAC_IRQHandler [WEAK] - EXPORT TIM7_IRQHandler [WEAK] - EXPORT TIM21_IRQHandler [WEAK] - EXPORT TIM22_IRQHandler [WEAK] - EXPORT I2C1_IRQHandler [WEAK] - EXPORT I2C2_IRQHandler [WEAK] - EXPORT I2C3_IRQHandler [WEAK] - EXPORT SPI1_IRQHandler [WEAK] - EXPORT SPI2_IRQHandler [WEAK] - EXPORT USART1_IRQHandler [WEAK] - EXPORT USART2_IRQHandler [WEAK] - EXPORT RNG_LPUART1_IRQHandler [WEAK] - EXPORT USB_IRQHandler [WEAK] - - -WWDG_IRQHandler -PVD_IRQHandler -RTC_IRQHandler -FLASH_IRQHandler -RCC_CRS_IRQHandler -EXTI0_1_IRQHandler -EXTI2_3_IRQHandler -EXTI4_15_IRQHandler -TSC_IRQHandler -DMA1_Channel1_IRQHandler -DMA1_Channel2_3_IRQHandler -DMA1_Channel4_5_6_7_IRQHandler -ADC1_COMP_IRQHandler -LPTIM1_IRQHandler -USART4_5_IRQHandler -TIM2_IRQHandler -TIM3_IRQHandler -TIM6_DAC_IRQHandler -TIM7_IRQHandler -TIM21_IRQHandler -TIM22_IRQHandler -I2C1_IRQHandler -I2C2_IRQHandler -I2C3_IRQHandler -SPI1_IRQHandler -SPI2_IRQHandler -USART1_IRQHandler -USART2_IRQHandler -RNG_LPUART1_IRQHandler -USB_IRQHandler - - B . - - ENDP - - ALIGN - END - -;************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE***** diff --git a/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L072CZ_LRWAN1/device/TOOLCHAIN_ARM_STD/stm32l073xz.sct b/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L072CZ_LRWAN1/device/TOOLCHAIN_ARM_STD/stm32l073xz.sct deleted file mode 100644 index c4e915ba952..00000000000 --- a/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L072CZ_LRWAN1/device/TOOLCHAIN_ARM_STD/stm32l073xz.sct +++ /dev/null @@ -1,45 +0,0 @@ -; Scatter-Loading Description File -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -; Copyright (c) 2015, STMicroelectronics -; All rights reserved. -; -; Redistribution and use in source and binary forms, with or without -; modification, are permitted provided that the following conditions are met: -; -; 1. Redistributions of source code must retain the above copyright notice, -; this list of conditions and the following disclaimer. -; 2. Redistributions in binary form must reproduce the above copyright notice, -; this list of conditions and the following disclaimer in the documentation -; and/or other materials provided with the distribution. -; 3. Neither the name of STMicroelectronics nor the names of its contributors -; may be used to endorse or promote products derived from this software -; without specific prior written permission. -; -; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -; OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; - -; STM32L073RZ: 192KB FLASH (0x30000) + 20KB RAM (0x5000) -LR_IROM1 0x08000000 0x30000 { ; load region size_region - - ER_IROM1 0x08000000 0x30000 { ; load address = execution address - *.o (RESET, +First) - *(InRoot$$Sections) - .ANY (+RO) - } - - ; Total: 48 vectors = 192 bytes (0xC0) to be reserved in RAM - RW_IRAM1 (0x20000000+0xC0) (0x5000-0xC0) { ; RW data - .ANY (+RW +ZI) - } - -} - diff --git a/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L072CZ_LRWAN1/device/TOOLCHAIN_ARM_STD/sys.cpp b/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L072CZ_LRWAN1/device/TOOLCHAIN_ARM_STD/sys.cpp deleted file mode 100644 index bb665909b98..00000000000 --- a/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L072CZ_LRWAN1/device/TOOLCHAIN_ARM_STD/sys.cpp +++ /dev/null @@ -1,56 +0,0 @@ -/* mbed Microcontroller Library - stackheap - * Setup a fixed single stack/heap memory model, - * between the top of the RW/ZI region and the stackpointer - ******************************************************************************* - * Copyright (c) 2014, STMicroelectronics - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************* - */ - -#ifdef __cplusplus -extern "C" { -#endif - -#include -#include - -extern char Image$$RW_IRAM1$$ZI$$Limit[]; - -extern __value_in_regs struct __initial_stackheap __user_setup_stackheap(uint32_t R0, uint32_t R1, uint32_t R2, uint32_t R3) { - uint32_t zi_limit = (uint32_t)Image$$RW_IRAM1$$ZI$$Limit; - uint32_t sp_limit = __current_sp(); - - zi_limit = (zi_limit + 7) & ~0x7; // ensure zi_limit is 8-byte aligned - - struct __initial_stackheap r; - r.heap_base = zi_limit; - r.heap_limit = sp_limit; - return r; -} - -#ifdef __cplusplus -} -#endif diff --git a/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L072CZ_LRWAN1/device/TOOLCHAIN_GCC_ARM/STM32L072XZ.ld b/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L072CZ_LRWAN1/device/TOOLCHAIN_GCC_ARM/STM32L072XZ.ld deleted file mode 100644 index 91fa744aa61..00000000000 --- a/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L072CZ_LRWAN1/device/TOOLCHAIN_GCC_ARM/STM32L072XZ.ld +++ /dev/null @@ -1,153 +0,0 @@ -/* Linker script to configure memory regions. */ -MEMORY -{ - FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 192k - RAM (rwx) : ORIGIN = 0x200000C0, LENGTH = 20K - 0xC0 -} - -/* Linker script to place sections and symbol values. Should be used together - * with other linker script that defines memory regions FLASH and RAM. - * It references following symbols, which must be defined in code: - * Reset_Handler : Entry of reset handler - * - * It defines following symbols, which code can use without definition: - * __exidx_start - * __exidx_end - * __etext - * __data_start__ - * __preinit_array_start - * __preinit_array_end - * __init_array_start - * __init_array_end - * __fini_array_start - * __fini_array_end - * __data_end__ - * __bss_start__ - * __bss_end__ - * __end__ - * end - * __HeapLimit - * __StackLimit - * __StackTop - * __stack - * _estack - */ -ENTRY(Reset_Handler) - -SECTIONS -{ - .text : - { - KEEP(*(.isr_vector)) - *(.text*) - KEEP(*(.init)) - KEEP(*(.fini)) - - /* .ctors */ - *crtbegin.o(.ctors) - *crtbegin?.o(.ctors) - *(EXCLUDE_FILE(*crtend?.o *crtend.o) .ctors) - *(SORT(.ctors.*)) - *(.ctors) - - /* .dtors */ - *crtbegin.o(.dtors) - *crtbegin?.o(.dtors) - *(EXCLUDE_FILE(*crtend?.o *crtend.o) .dtors) - *(SORT(.dtors.*)) - *(.dtors) - - *(.rodata*) - - KEEP(*(.eh_frame*)) - } > FLASH - - .ARM.extab : - { - *(.ARM.extab* .gnu.linkonce.armextab.*) - } > FLASH - - __exidx_start = .; - .ARM.exidx : - { - *(.ARM.exidx* .gnu.linkonce.armexidx.*) - } > FLASH - __exidx_end = .; - - __etext = .; - _sidata = .; - - .data : AT (__etext) - { - __data_start__ = .; - _sdata = .; - *(vtable) - *(.data*) - - . = ALIGN(4); - /* preinit data */ - PROVIDE_HIDDEN (__preinit_array_start = .); - KEEP(*(.preinit_array)) - PROVIDE_HIDDEN (__preinit_array_end = .); - - . = ALIGN(4); - /* init data */ - PROVIDE_HIDDEN (__init_array_start = .); - KEEP(*(SORT(.init_array.*))) - KEEP(*(.init_array)) - PROVIDE_HIDDEN (__init_array_end = .); - - - . = ALIGN(4); - /* finit data */ - PROVIDE_HIDDEN (__fini_array_start = .); - KEEP(*(SORT(.fini_array.*))) - KEEP(*(.fini_array)) - PROVIDE_HIDDEN (__fini_array_end = .); - - KEEP(*(.jcr*)) - . = ALIGN(4); - /* All data end */ - __data_end__ = .; - _edata = .; - - } > RAM - - .bss : - { - . = ALIGN(4); - __bss_start__ = .; - _sbss = .; - *(.bss*) - *(COMMON) - . = ALIGN(4); - __bss_end__ = .; - _ebss = .; - } > RAM - - .heap (COPY): - { - __end__ = .; - end = __end__; - *(.heap*) - __HeapLimit = .; - } > RAM - - /* .stack_dummy section doesn't contains any symbols. It is only - * used for linker to calculate size of stack sections, and assign - * values to stack symbols later */ - .stack_dummy (COPY): - { - *(.stack*) - } > RAM - - /* Set stack top to end of RAM, and stack limit move down by - * size of stack_dummy section */ - __StackTop = ORIGIN(RAM) + LENGTH(RAM); - _estack = __StackTop; - __StackLimit = __StackTop - SIZEOF(.stack_dummy); - PROVIDE(__stack = __StackTop); - - /* Check if data + heap + stack exceeds RAM limit */ - ASSERT(__StackLimit >= __HeapLimit, "region RAM overflowed with stack") -} diff --git a/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L072CZ_LRWAN1/device/TOOLCHAIN_GCC_ARM/startup_stm32l072xx.S b/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L072CZ_LRWAN1/device/TOOLCHAIN_GCC_ARM/startup_stm32l072xx.S deleted file mode 100644 index 1aad893bcbd..00000000000 --- a/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L072CZ_LRWAN1/device/TOOLCHAIN_GCC_ARM/startup_stm32l072xx.S +++ /dev/null @@ -1,288 +0,0 @@ -/** - ****************************************************************************** - * @file startup_stm32l072xx.s - * @author MCD Application Team - * @version V1.7.1 - * @date 25-November-2016 - * @brief STM32L072xx Devices vector table for Atollic TrueSTUDIO toolchain. - * This module performs: - * - Set the initial SP - * - Set the initial PC == Reset_Handler, - * - Set the vector table entries with the exceptions ISR address - * - Branches to main in the C library (which eventually - * calls main()). - * After Reset the Cortex-M0+ processor is in Thread mode, - * priority is Privileged, and the Stack is set to Main. - ****************************************************************************** - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ - - .syntax unified - .cpu cortex-m0plus - .fpu softvfp - .thumb - -.global g_pfnVectors -.global Default_Handler - -/* start address for the initialization values of the .data section. -defined in linker script */ -.word _sidata -/* start address for the .data section. defined in linker script */ -.word _sdata -/* end address for the .data section. defined in linker script */ -.word _edata - - .section .text.Reset_Handler - .weak Reset_Handler - .type Reset_Handler, %function -Reset_Handler: - ldr r0, =_estack - mov sp, r0 /* set stack pointer */ - -/* Copy the data segment initializers from flash to SRAM */ - movs r1, #0 - b LoopCopyDataInit - -CopyDataInit: - ldr r3, =_sidata - ldr r3, [r3, r1] - str r3, [r0, r1] - adds r1, r1, #4 - -LoopCopyDataInit: - ldr r0, =_sdata - ldr r3, =_edata - adds r2, r0, r1 - cmp r2, r3 - bcc CopyDataInit - -/* Call the clock system intitialization function.*/ - bl SystemInit -/* Call static constructors */ - //bl __libc_init_array -/* Call the application's entry point.*/ - //bl main - bl _start - -LoopForever: - b LoopForever - - -.size Reset_Handler, .-Reset_Handler - -/** - * @brief This is the code that gets called when the processor receives an - * unexpected interrupt. This simply enters an infinite loop, preserving - * the system state for examination by a debugger. - * - * @param None - * @retval : None -*/ - .section .text.Default_Handler,"ax",%progbits -Default_Handler: -Infinite_Loop: - b Infinite_Loop - .size Default_Handler, .-Default_Handler -/****************************************************************************** -* -* The minimal vector table for a Cortex M0. Note that the proper constructs -* must be placed on this to ensure that it ends up at physical address -* 0x0000.0000. -* -******************************************************************************/ - .section .isr_vector,"a",%progbits - .type g_pfnVectors, %object - .size g_pfnVectors, .-g_pfnVectors - - -g_pfnVectors: - .word _estack - .word Reset_Handler - .word NMI_Handler - .word HardFault_Handler - .word 0 - .word 0 - .word 0 - .word 0 - .word 0 - .word 0 - .word 0 - .word SVC_Handler - .word 0 - .word 0 - .word PendSV_Handler - .word SysTick_Handler - .word WWDG_IRQHandler /* Window WatchDog */ - .word PVD_IRQHandler /* PVD through EXTI Line detection */ - .word RTC_IRQHandler /* RTC through the EXTI line */ - .word FLASH_IRQHandler /* FLASH */ - .word RCC_CRS_IRQHandler /* RCC and CRS */ - .word EXTI0_1_IRQHandler /* EXTI Line 0 and 1 */ - .word EXTI2_3_IRQHandler /* EXTI Line 2 and 3 */ - .word EXTI4_15_IRQHandler /* EXTI Line 4 to 15 */ - .word TSC_IRQHandler /* TSC */ - .word DMA1_Channel1_IRQHandler /* DMA1 Channel 1 */ - .word DMA1_Channel2_3_IRQHandler /* DMA1 Channel 2 and Channel 3 */ - .word DMA1_Channel4_5_6_7_IRQHandler /* DMA1 Channel 4, Channel 5, Channel 6 and Channel 7*/ - .word ADC1_COMP_IRQHandler /* ADC1, COMP1 and COMP2 */ - .word LPTIM1_IRQHandler /* LPTIM1 */ - .word USART4_5_IRQHandler /* USART4 and USART 5 */ - .word TIM2_IRQHandler /* TIM2 */ - .word TIM3_IRQHandler /* TIM3 */ - .word TIM6_DAC_IRQHandler /* TIM6 and DAC */ - .word TIM7_IRQHandler /* TIM7 */ - .word 0 /* Reserved */ - .word TIM21_IRQHandler /* TIM21 */ - .word I2C3_IRQHandler /* I2C3 */ - .word TIM22_IRQHandler /* TIM22 */ - .word I2C1_IRQHandler /* I2C1 */ - .word I2C2_IRQHandler /* I2C2 */ - .word SPI1_IRQHandler /* SPI1 */ - .word SPI2_IRQHandler /* SPI2 */ - .word USART1_IRQHandler /* USART1 */ - .word USART2_IRQHandler /* USART2 */ - .word RNG_LPUART1_IRQHandler /* RNG and LPUART1 */ - .word 0 /* Reserved */ - .word USB_IRQHandler /* USB */ - -/******************************************************************************* -* -* Provide weak aliases for each Exception handler to the Default_Handler. -* As they are weak aliases, any function with the same name will override -* this definition. -* -*******************************************************************************/ - - .weak NMI_Handler - .thumb_set NMI_Handler,Default_Handler - - .weak HardFault_Handler - .thumb_set HardFault_Handler,Default_Handler - - .weak SVC_Handler - .thumb_set SVC_Handler,Default_Handler - - .weak PendSV_Handler - .thumb_set PendSV_Handler,Default_Handler - - .weak SysTick_Handler - .thumb_set SysTick_Handler,Default_Handler - - .weak WWDG_IRQHandler - .thumb_set WWDG_IRQHandler,Default_Handler - - .weak PVD_IRQHandler - .thumb_set PVD_IRQHandler,Default_Handler - - .weak RTC_IRQHandler - .thumb_set RTC_IRQHandler,Default_Handler - - .weak FLASH_IRQHandler - .thumb_set FLASH_IRQHandler,Default_Handler - - .weak RCC_CRS_IRQHandler - .thumb_set RCC_CRS_IRQHandler,Default_Handler - - .weak EXTI0_1_IRQHandler - .thumb_set EXTI0_1_IRQHandler,Default_Handler - - .weak EXTI2_3_IRQHandler - .thumb_set EXTI2_3_IRQHandler,Default_Handler - - .weak EXTI4_15_IRQHandler - .thumb_set EXTI4_15_IRQHandler,Default_Handler - - .weak TSC_IRQHandler - .thumb_set TSC_IRQHandler,Default_Handler - - .weak DMA1_Channel1_IRQHandler - .thumb_set DMA1_Channel1_IRQHandler,Default_Handler - - .weak DMA1_Channel2_3_IRQHandler - .thumb_set DMA1_Channel2_3_IRQHandler,Default_Handler - - .weak DMA1_Channel4_5_6_7_IRQHandler - .thumb_set DMA1_Channel4_5_6_7_IRQHandler,Default_Handler - - .weak ADC1_COMP_IRQHandler - .thumb_set ADC1_COMP_IRQHandler,Default_Handler - - .weak LPTIM1_IRQHandler - .thumb_set LPTIM1_IRQHandler,Default_Handler - - .weak USART4_5_IRQHandler - .thumb_set USART4_5_IRQHandler,Default_Handler - - .weak TIM2_IRQHandler - .thumb_set TIM2_IRQHandler,Default_Handler - - .weak TIM3_IRQHandler - .thumb_set TIM3_IRQHandler,Default_Handler - - .weak TIM6_DAC_IRQHandler - .thumb_set TIM6_DAC_IRQHandler,Default_Handler - - .weak TIM7_IRQHandler - .thumb_set TIM7_IRQHandler,Default_Handler - - .weak TIM21_IRQHandler - .thumb_set TIM21_IRQHandler,Default_Handler - - .weak I2C3_IRQHandler - .thumb_set I2C3_IRQHandler,Default_Handler - - .weak TIM22_IRQHandler - .thumb_set TIM22_IRQHandler,Default_Handler - - .weak I2C1_IRQHandler - .thumb_set I2C1_IRQHandler,Default_Handler - - .weak I2C2_IRQHandler - .thumb_set I2C2_IRQHandler,Default_Handler - - .weak SPI1_IRQHandler - .thumb_set SPI1_IRQHandler,Default_Handler - - .weak SPI2_IRQHandler - .thumb_set SPI2_IRQHandler,Default_Handler - - .weak USART1_IRQHandler - .thumb_set USART1_IRQHandler,Default_Handler - - .weak USART2_IRQHandler - .thumb_set USART2_IRQHandler,Default_Handler - - .weak RNG_LPUART1_IRQHandler - .thumb_set RNG_LPUART1_IRQHandler,Default_Handler - - .weak USB_IRQHandler - .thumb_set USB_IRQHandler,Default_Handler - - - -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ - diff --git a/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L072CZ_LRWAN1/device/TOOLCHAIN_IAR/startup_stm32l072xx.S b/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L072CZ_LRWAN1/device/TOOLCHAIN_IAR/startup_stm32l072xx.S deleted file mode 100644 index 4476016ea2d..00000000000 --- a/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L072CZ_LRWAN1/device/TOOLCHAIN_IAR/startup_stm32l072xx.S +++ /dev/null @@ -1,343 +0,0 @@ -;/******************** (C) COPYRIGHT 2016 STMicroelectronics ******************** -;* File Name : startup_stm32l072xx.s -;* Author : MCD Application Team -;* Version : V1.7.1 -;* Date : 25-November-2016 -;* Description : STM32L072xx Ultra Low Power Devices vector -;* This module performs: -;* - Set the initial SP -;* - Set the initial PC == _iar_program_start, -;* - Set the vector table entries with the exceptions ISR -;* address. -;* - Configure the system clock -;* - Branches to main in the C library (which eventually -;* calls main()). -;* After Reset the Cortex-M0+ processor is in Thread mode, -;* priority is Privileged, and the Stack is set to Main. -;******************************************************************************** -;* -;* Redistribution and use in source and binary forms, with or without modification, -;* are permitted provided that the following conditions are met: -;* 1. Redistributions of source code must retain the above copyright notice, -;* this list of conditions and the following disclaimer. -;* 2. Redistributions in binary form must reproduce the above copyright notice, -;* this list of conditions and the following disclaimer in the documentation -;* and/or other materials provided with the distribution. -;* 3. Neither the name of STMicroelectronics nor the names of its contributors -;* may be used to endorse or promote products derived from this software -;* without specific prior written permission. -;* -;* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -;* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -;* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -;* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -;* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -;* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -;* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -;* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -;* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -;* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -;* -;*******************************************************************************/ -; -; -; The modules in this file are included in the libraries, and may be replaced -; by any user-defined modules that define the PUBLIC symbol _program_start or -; a user defined start symbol. -; To override the cstartup defined in the library, simply add your modified -; version to the workbench project. -; -; The vector table is normally located at address 0. -; When debugging in RAM, it can be located in RAM, aligned to at least 2^6. -; The name "__vector_table" has special meaning for C-SPY: -; it is where the SP start value is found, and the NVIC vector -; table register (VTOR) is initialized to this address if != 0. -; -; Cortex-M version -; - - MODULE ?cstartup - - ;; Forward declaration of sections. - SECTION CSTACK:DATA:NOROOT(3) - - SECTION .intvec:CODE:NOROOT(2) - - EXTERN __iar_program_start - EXTERN SystemInit - PUBLIC __vector_table - - DATA -__vector_table - DCD sfe(CSTACK) - DCD Reset_Handler ; Reset Handler - - DCD NMI_Handler ; NMI Handler - DCD HardFault_Handler ; Hard Fault Handler - DCD 0 ; Reserved - DCD 0 ; Reserved - DCD 0 ; Reserved - DCD 0 ; Reserved - DCD 0 ; Reserved - DCD 0 ; Reserved - DCD 0 ; Reserved - DCD SVC_Handler ; SVCall Handler - DCD 0 ; Reserved - DCD 0 ; Reserved - DCD PendSV_Handler ; PendSV Handler - DCD SysTick_Handler ; SysTick Handler - - ; External Interrupts - DCD WWDG_IRQHandler ; Window Watchdog - DCD PVD_IRQHandler ; PVD through EXTI Line detect - DCD RTC_IRQHandler ; RTC through EXTI Line - DCD FLASH_IRQHandler ; FLASH - DCD RCC_CRS_IRQHandler ; RCC_CRS - DCD EXTI0_1_IRQHandler ; EXTI Line 0 and 1 - DCD EXTI2_3_IRQHandler ; EXTI Line 2 and 3 - DCD EXTI4_15_IRQHandler ; EXTI Line 4 to 15 - DCD TSC_IRQHandler ; TSC - DCD DMA1_Channel1_IRQHandler ; DMA1 Channel 1 - DCD DMA1_Channel2_3_IRQHandler ; DMA1 Channel 2 and Channel 3 - DCD DMA1_Channel4_5_6_7_IRQHandler ; DMA1 Channel 4, Channel 5, Channel 6 and Channel 7 - DCD ADC1_COMP_IRQHandler ; ADC1, COMP1 and COMP2 - DCD LPTIM1_IRQHandler ; LPTIM1 - DCD USART4_5_IRQHandler ; USART4 and USART5 - DCD TIM2_IRQHandler ; TIM2 - DCD TIM3_IRQHandler ; TIM3 - DCD TIM6_DAC_IRQHandler ; TIM6 and DAC - DCD TIM7_IRQHandler ; TIM7 - DCD 0 ; Reserved - DCD TIM21_IRQHandler ; TIM21 - DCD I2C3_IRQHandler ; I2C3 - DCD TIM22_IRQHandler ; TIM22 - DCD I2C1_IRQHandler ; I2C1 - DCD I2C2_IRQHandler ; I2C2 - DCD SPI1_IRQHandler ; SPI1 - DCD SPI2_IRQHandler ; SPI2 - DCD USART1_IRQHandler ; USART1 - DCD USART2_IRQHandler ; USART2 - DCD RNG_LPUART1_IRQHandler ; RNG and LPUART1 - DCD 0 ; Reserved - DCD USB_IRQHandler ; USB - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; -;; Default interrupt handlers. -;; - THUMB - PUBWEAK Reset_Handler - SECTION .text:CODE:NOROOT:REORDER(2) -Reset_Handler - LDR R0, =SystemInit - BLX R0 - LDR R0, =__iar_program_start - BX R0 - - PUBWEAK NMI_Handler - SECTION .text:CODE:NOROOT:REORDER(1) -NMI_Handler - B NMI_Handler - - - PUBWEAK HardFault_Handler - SECTION .text:CODE:NOROOT:REORDER(1) -HardFault_Handler - B HardFault_Handler - - - PUBWEAK SVC_Handler - SECTION .text:CODE:NOROOT:REORDER(1) -SVC_Handler - B SVC_Handler - - - PUBWEAK PendSV_Handler - SECTION .text:CODE:NOROOT:REORDER(1) -PendSV_Handler - B PendSV_Handler - - - PUBWEAK SysTick_Handler - SECTION .text:CODE:NOROOT:REORDER(1) -SysTick_Handler - B SysTick_Handler - - - PUBWEAK WWDG_IRQHandler - SECTION .text:CODE:NOROOT:REORDER(1) -WWDG_IRQHandler - B WWDG_IRQHandler - - - PUBWEAK PVD_IRQHandler - SECTION .text:CODE:NOROOT:REORDER(1) -PVD_IRQHandler - B PVD_IRQHandler - - - PUBWEAK RTC_IRQHandler - SECTION .text:CODE:NOROOT:REORDER(1) -RTC_IRQHandler - B RTC_IRQHandler - - - PUBWEAK FLASH_IRQHandler - SECTION .text:CODE:NOROOT:REORDER(1) -FLASH_IRQHandler - B FLASH_IRQHandler - - - PUBWEAK RCC_CRS_IRQHandler - SECTION .text:CODE:NOROOT:REORDER(1) -RCC_CRS_IRQHandler - B RCC_CRS_IRQHandler - - - PUBWEAK EXTI0_1_IRQHandler - SECTION .text:CODE:NOROOT:REORDER(1) -EXTI0_1_IRQHandler - B EXTI0_1_IRQHandler - - - PUBWEAK EXTI2_3_IRQHandler - SECTION .text:CODE:NOROOT:REORDER(1) -EXTI2_3_IRQHandler - B EXTI2_3_IRQHandler - - - PUBWEAK EXTI4_15_IRQHandler - SECTION .text:CODE:NOROOT:REORDER(1) -EXTI4_15_IRQHandler - B EXTI4_15_IRQHandler - - - PUBWEAK TSC_IRQHandler - SECTION .text:CODE:NOROOT:REORDER(1) -TSC_IRQHandler - B TSC_IRQHandler - - - PUBWEAK DMA1_Channel1_IRQHandler - SECTION .text:CODE:NOROOT:REORDER(1) -DMA1_Channel1_IRQHandler - B DMA1_Channel1_IRQHandler - - - PUBWEAK DMA1_Channel2_3_IRQHandler - SECTION .text:CODE:NOROOT:REORDER(1) -DMA1_Channel2_3_IRQHandler - B DMA1_Channel2_3_IRQHandler - - - PUBWEAK DMA1_Channel4_5_6_7_IRQHandler - SECTION .text:CODE:NOROOT:REORDER(1) -DMA1_Channel4_5_6_7_IRQHandler - B DMA1_Channel4_5_6_7_IRQHandler - - - PUBWEAK ADC1_COMP_IRQHandler - SECTION .text:CODE:NOROOT:REORDER(1) -ADC1_COMP_IRQHandler - B ADC1_COMP_IRQHandler - - - PUBWEAK LPTIM1_IRQHandler - SECTION .text:CODE:NOROOT:REORDER(1) -LPTIM1_IRQHandler - B LPTIM1_IRQHandler - - - PUBWEAK USART4_5_IRQHandler - SECTION .text:CODE:NOROOT:REORDER(1) -USART4_5_IRQHandler - B USART4_5_IRQHandler - - - PUBWEAK TIM2_IRQHandler - SECTION .text:CODE:NOROOT:REORDER(1) -TIM2_IRQHandler - B TIM2_IRQHandler - - - PUBWEAK TIM3_IRQHandler - SECTION .text:CODE:NOROOT:REORDER(1) -TIM3_IRQHandler - B TIM3_IRQHandler - - - PUBWEAK TIM6_DAC_IRQHandler - SECTION .text:CODE:NOROOT:REORDER(1) -TIM6_DAC_IRQHandler - B TIM6_DAC_IRQHandler - - PUBWEAK TIM7_IRQHandler - SECTION .text:CODE:NOROOT:REORDER(1) -TIM7_IRQHandler - B TIM7_IRQHandler - - PUBWEAK TIM21_IRQHandler - SECTION .text:CODE:NOROOT:REORDER(1) -TIM21_IRQHandler - B TIM21_IRQHandler - - PUBWEAK I2C3_IRQHandler - SECTION .text:CODE:NOROOT:REORDER(1) -I2C3_IRQHandler - B I2C3_IRQHandler - - PUBWEAK TIM22_IRQHandler - SECTION .text:CODE:NOROOT:REORDER(1) -TIM22_IRQHandler - B TIM22_IRQHandler - - - PUBWEAK I2C1_IRQHandler - SECTION .text:CODE:NOROOT:REORDER(1) -I2C1_IRQHandler - B I2C1_IRQHandler - - - PUBWEAK I2C2_IRQHandler - SECTION .text:CODE:NOROOT:REORDER(1) -I2C2_IRQHandler - B I2C2_IRQHandler - - - PUBWEAK SPI1_IRQHandler - SECTION .text:CODE:NOROOT:REORDER(1) -SPI1_IRQHandler - B SPI1_IRQHandler - - - PUBWEAK SPI2_IRQHandler - SECTION .text:CODE:NOROOT:REORDER(1) -SPI2_IRQHandler - B SPI2_IRQHandler - - - PUBWEAK USART1_IRQHandler - SECTION .text:CODE:NOROOT:REORDER(1) -USART1_IRQHandler - B USART1_IRQHandler - - - PUBWEAK USART2_IRQHandler - SECTION .text:CODE:NOROOT:REORDER(1) -USART2_IRQHandler - B USART2_IRQHandler - - - PUBWEAK RNG_LPUART1_IRQHandler - SECTION .text:CODE:NOROOT:REORDER(1) -RNG_LPUART1_IRQHandler - B RNG_LPUART1_IRQHandler - - - PUBWEAK USB_IRQHandler - SECTION .text:CODE:NOROOT:REORDER(1) -USB_IRQHandler - B USB_IRQHandler - - END -;************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE***** diff --git a/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L072CZ_LRWAN1/device/TOOLCHAIN_IAR/stm32l072xx.icf b/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L072CZ_LRWAN1/device/TOOLCHAIN_IAR/stm32l072xx.icf deleted file mode 100644 index 65a11a2b35a..00000000000 --- a/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L072CZ_LRWAN1/device/TOOLCHAIN_IAR/stm32l072xx.icf +++ /dev/null @@ -1,30 +0,0 @@ -/* [ROM = 192kb = 0x30000] */ -define symbol __intvec_start__ = 0x08000000; -define symbol __region_ROM_start__ = 0x08000000; -define symbol __region_ROM_end__ = 0x0802FFFF; - -/* [RAM = 20kb = 0x5000] Vector table dynamic copy: 48 vectors = 192 bytes (0xC0) to be reserved in RAM */ -define symbol __NVIC_start__ = 0x20000000; -define symbol __NVIC_end__ = 0x200000BF; /* Aligned on 8 bytes */ -define symbol __region_RAM_start__ = 0x200000C0; -define symbol __region_RAM_end__ = 0x20004FFF; - -/* Memory regions */ -define memory mem with size = 4G; -define region ROM_region = mem:[from __region_ROM_start__ to __region_ROM_end__]; -define region RAM_region = mem:[from __region_RAM_start__ to __region_RAM_end__]; - -/* Stack and Heap */ -define symbol __size_cstack__ = 0x500; -define symbol __size_heap__ = 0x1000; -define block CSTACK with alignment = 8, size = __size_cstack__ { }; -define block HEAP with alignment = 8, size = __size_heap__ { }; -define block STACKHEAP with fixed order { block HEAP, block CSTACK }; - -initialize by copy with packing = zeros { readwrite }; -do not initialize { section .noinit }; - -place at address mem:__intvec_start__ { readonly section .intvec }; - -place in ROM_region { readonly }; -place in RAM_region { readwrite, block STACKHEAP }; diff --git a/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L072CZ_LRWAN1/device/cmsis_nvic.c b/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L072CZ_LRWAN1/device/cmsis_nvic.c deleted file mode 100644 index 41a742b4aa1..00000000000 --- a/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L072CZ_LRWAN1/device/cmsis_nvic.c +++ /dev/null @@ -1,55 +0,0 @@ -/* mbed Microcontroller Library - * CMSIS-style functionality to support dynamic vectors - ******************************************************************************* - * Copyright (c) 2017, STMicroelectronics - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************* - */ -#include "cmsis_nvic.h" - -#define NVIC_RAM_VECTOR_ADDRESS (0x20000000) // Vectors positioned at start of RAM -#define NVIC_FLASH_VECTOR_ADDRESS (0x08000000) // Initial vector position in flash - -void NVIC_SetVector(IRQn_Type IRQn, uint32_t vector) { - uint32_t *vectors = (uint32_t *)SCB->VTOR; - uint32_t i; - - // Copy and switch to dynamic vectors if the first time called - if (SCB->VTOR == NVIC_FLASH_VECTOR_ADDRESS) { - uint32_t *old_vectors = vectors; - vectors = (uint32_t*)NVIC_RAM_VECTOR_ADDRESS; - for (i=0; iVTOR = (uint32_t)NVIC_RAM_VECTOR_ADDRESS; - } - vectors[IRQn + NVIC_USER_IRQ_OFFSET] = vector; -} - -uint32_t NVIC_GetVector(IRQn_Type IRQn) { - uint32_t *vectors = (uint32_t*)SCB->VTOR; - return vectors[IRQn + NVIC_USER_IRQ_OFFSET]; -} diff --git a/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L072CZ_LRWAN1/device/hal_tick.h b/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L072CZ_LRWAN1/device/hal_tick.h deleted file mode 100644 index e79a4e7568d..00000000000 --- a/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L072CZ_LRWAN1/device/hal_tick.h +++ /dev/null @@ -1,64 +0,0 @@ -/** - ****************************************************************************** - * @file hal_tick.h - * @author MCD Application Team - * @brief Initialization of HAL tick - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2017 STMicroelectronics

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ -#ifndef __HAL_TICK_H -#define __HAL_TICK_H - -#ifdef __cplusplus - extern "C" { -#endif - -#include "stm32l0xx.h" -#include "cmsis_nvic.h" - -#define TIM_MST TIM21 -#define TIM_MST_IRQ TIM21_IRQn -#define TIM_MST_RCC __TIM21_CLK_ENABLE() - -#define TIM_MST_RESET_ON __TIM21_FORCE_RESET() -#define TIM_MST_RESET_OFF __TIM21_RELEASE_RESET() - -#define TIM_MST_16BIT 1 // 1=16-bit timer, 0=32-bit timer - -#define TIM_MST_PCLK 2 // Select the peripheral clock number (1 or 2) - -#define HAL_TICK_DELAY (1000) // 1 ms - -#ifdef __cplusplus -} -#endif - -#endif // __HAL_TICK_H - -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L072CZ_LRWAN1/device/stm32l072xx.h b/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L072CZ_LRWAN1/device/stm32l072xx.h deleted file mode 100644 index a38c8690efc..00000000000 --- a/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L072CZ_LRWAN1/device/stm32l072xx.h +++ /dev/null @@ -1,7683 +0,0 @@ -/** - ****************************************************************************** - * @file stm32l072xx.h - * @author MCD Application Team - * @version V1.7.1 - * @date 25-November-2016 - * @brief CMSIS Cortex-M0+ Device Peripheral Access Layer Header File. - * This file contains all the peripheral register's definitions, bits - * definitions and memory mapping for stm32l072xx devices. - * - * This file contains: - * - Data structures and the address mapping for all peripherals - * - Peripheral's registers declarations and bits definition - * - Macros to access peripheral's registers hardware - * - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2016 STMicroelectronics

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ - -/** @addtogroup CMSIS - * @{ - */ - -/** @addtogroup stm32l072xx - * @{ - */ - -#ifndef __STM32L072xx_H -#define __STM32L072xx_H - -#ifdef __cplusplus - extern "C" { -#endif - - -/** @addtogroup Configuration_section_for_CMSIS - * @{ - */ -/** - * @brief Configuration of the Cortex-M0+ Processor and Core Peripherals - */ -#define __CM0PLUS_REV 0 /*!< Core Revision r0p0 */ -#define __MPU_PRESENT 1 /*!< STM32L0xx provides an MPU */ -#define __VTOR_PRESENT 1 /*!< Vector Table Register supported */ -#define __NVIC_PRIO_BITS 2 /*!< STM32L0xx uses 2 Bits for the Priority Levels */ -#define __Vendor_SysTickConfig 0 /*!< Set to 1 if different SysTick Config is used */ - -/** - * @} - */ - -/** @addtogroup Peripheral_interrupt_number_definition - * @{ - */ - -/** - * @brief stm32l072xx Interrupt Number Definition, according to the selected device - * in @ref Library_configuration_section - */ - -/*!< Interrupt Number Definition */ -typedef enum -{ -/****** Cortex-M0 Processor Exceptions Numbers ******************************************************/ - NonMaskableInt_IRQn = -14, /*!< 2 Non Maskable Interrupt */ - HardFault_IRQn = -13, /*!< 3 Cortex-M0+ Hard Fault Interrupt */ - SVC_IRQn = -5, /*!< 11 Cortex-M0+ SV Call Interrupt */ - PendSV_IRQn = -2, /*!< 14 Cortex-M0+ Pend SV Interrupt */ - SysTick_IRQn = -1, /*!< 15 Cortex-M0+ System Tick Interrupt */ - -/****** STM32L-0 specific Interrupt Numbers *********************************************************/ - WWDG_IRQn = 0, /*!< Window WatchDog Interrupt */ - PVD_IRQn = 1, /*!< PVD through EXTI Line detect Interrupt */ - RTC_IRQn = 2, /*!< RTC through EXTI Line Interrupt */ - FLASH_IRQn = 3, /*!< FLASH Interrupt */ - RCC_CRS_IRQn = 4, /*!< RCC and CRS Interrupts */ - EXTI0_1_IRQn = 5, /*!< EXTI Line 0 and 1 Interrupts */ - EXTI2_3_IRQn = 6, /*!< EXTI Line 2 and 3 Interrupts */ - EXTI4_15_IRQn = 7, /*!< EXTI Line 4 to 15 Interrupts */ - TSC_IRQn = 8, /*!< TSC Interrupt */ - DMA1_Channel1_IRQn = 9, /*!< DMA1 Channel 1 Interrupt */ - DMA1_Channel2_3_IRQn = 10, /*!< DMA1 Channel 2 and Channel 3 Interrupts */ - DMA1_Channel4_5_6_7_IRQn = 11, /*!< DMA1 Channel 4, Channel 5, Channel 6 and Channel 7 Interrupts */ - ADC1_COMP_IRQn = 12, /*!< ADC1, COMP1 and COMP2 Interrupts */ - LPTIM1_IRQn = 13, /*!< LPTIM1 Interrupt */ - USART4_5_IRQn = 14, /*!< USART4 and USART5 Interrupt */ - TIM2_IRQn = 15, /*!< TIM2 Interrupt */ - TIM3_IRQn = 16, /*!< TIM3 Interrupt */ - TIM6_DAC_IRQn = 17, /*!< TIM6 and DAC Interrupts */ - TIM7_IRQn = 18, /*!< TIM7 Interrupt */ - TIM21_IRQn = 20, /*!< TIM21 Interrupt */ - I2C3_IRQn = 21, /*!< I2C3 Interrupt */ - TIM22_IRQn = 22, /*!< TIM22 Interrupt */ - I2C1_IRQn = 23, /*!< I2C1 Interrupt */ - I2C2_IRQn = 24, /*!< I2C2 Interrupt */ - SPI1_IRQn = 25, /*!< SPI1 Interrupt */ - SPI2_IRQn = 26, /*!< SPI2 Interrupt */ - USART1_IRQn = 27, /*!< USART1 Interrupt */ - USART2_IRQn = 28, /*!< USART2 Interrupt */ - RNG_LPUART1_IRQn = 29, /*!< RNG and LPUART1 Interrupts */ - USB_IRQn = 31, /*!< USB global Interrupt */ -} IRQn_Type; - -/** - * @} - */ - -#include "core_cm0plus.h" -#include "system_stm32l0xx.h" -#include - -/** @addtogroup Peripheral_registers_structures - * @{ - */ - -/** - * @brief Analog to Digital Converter - */ - -typedef struct -{ - __IO uint32_t ISR; /*!< ADC Interrupt and Status register, Address offset:0x00 */ - __IO uint32_t IER; /*!< ADC Interrupt Enable register, Address offset:0x04 */ - __IO uint32_t CR; /*!< ADC Control register, Address offset:0x08 */ - __IO uint32_t CFGR1; /*!< ADC Configuration register 1, Address offset:0x0C */ - __IO uint32_t CFGR2; /*!< ADC Configuration register 2, Address offset:0x10 */ - __IO uint32_t SMPR; /*!< ADC Sampling time register, Address offset:0x14 */ - uint32_t RESERVED1; /*!< Reserved, 0x18 */ - uint32_t RESERVED2; /*!< Reserved, 0x1C */ - __IO uint32_t TR; /*!< ADC watchdog threshold register, Address offset:0x20 */ - uint32_t RESERVED3; /*!< Reserved, 0x24 */ - __IO uint32_t CHSELR; /*!< ADC channel selection register, Address offset:0x28 */ - uint32_t RESERVED4[5]; /*!< Reserved, 0x2C */ - __IO uint32_t DR; /*!< ADC data register, Address offset:0x40 */ - uint32_t RESERVED5[28]; /*!< Reserved, 0x44 - 0xB0 */ - __IO uint32_t CALFACT; /*!< ADC data register, Address offset:0xB4 */ -} ADC_TypeDef; - -typedef struct -{ - __IO uint32_t CCR; -} ADC_Common_TypeDef; - - -/** - * @brief Comparator - */ - -typedef struct -{ - __IO uint32_t CSR; /*!< COMP comparator control and status register, Address offset: 0x18 */ -} COMP_TypeDef; - -typedef struct -{ - __IO uint32_t CSR; /*!< COMP control and status register, used for bits common to several COMP instances, Address offset: 0x00 */ -} COMP_Common_TypeDef; - - -/** -* @brief CRC calculation unit -*/ - -typedef struct -{ -__IO uint32_t DR; /*!< CRC Data register, Address offset: 0x00 */ -__IO uint8_t IDR; /*!< CRC Independent data register, Address offset: 0x04 */ -uint8_t RESERVED0; /*!< Reserved, 0x05 */ -uint16_t RESERVED1; /*!< Reserved, 0x06 */ -__IO uint32_t CR; /*!< CRC Control register, Address offset: 0x08 */ -uint32_t RESERVED2; /*!< Reserved, 0x0C */ -__IO uint32_t INIT; /*!< Initial CRC value register, Address offset: 0x10 */ -__IO uint32_t POL; /*!< CRC polynomial register, Address offset: 0x14 */ -} CRC_TypeDef; - -/** - * @brief Clock Recovery System - */ - -typedef struct -{ -__IO uint32_t CR; /*!< CRS ccontrol register, Address offset: 0x00 */ -__IO uint32_t CFGR; /*!< CRS configuration register, Address offset: 0x04 */ -__IO uint32_t ISR; /*!< CRS interrupt and status register, Address offset: 0x08 */ -__IO uint32_t ICR; /*!< CRS interrupt flag clear register, Address offset: 0x0C */ -} CRS_TypeDef; - -/** - * @brief Digital to Analog Converter - */ - -typedef struct -{ - __IO uint32_t CR; /*!< DAC control register, Address offset: 0x00 */ - __IO uint32_t SWTRIGR; /*!< DAC software trigger register, Address offset: 0x04 */ - __IO uint32_t DHR12R1; /*!< DAC channel1 12-bit right-aligned data holding register, Address offset: 0x08 */ - __IO uint32_t DHR12L1; /*!< DAC channel1 12-bit left aligned data holding register, Address offset: 0x0C */ - __IO uint32_t DHR8R1; /*!< DAC channel1 8-bit right aligned data holding register, Address offset: 0x10 */ - __IO uint32_t DHR12R2; /*!< DAC channel2 12-bit right aligned data holding register, Address offset: 0x14 */ - __IO uint32_t DHR12L2; /*!< DAC channel2 12-bit left aligned data holding register, Address offset: 0x18 */ - __IO uint32_t DHR8R2; /*!< DAC channel2 8-bit right-aligned data holding register, Address offset: 0x1C */ - __IO uint32_t DHR12RD; /*!< Dual DAC 12-bit right-aligned data holding register, Address offset: 0x20 */ - __IO uint32_t DHR12LD; /*!< DUAL DAC 12-bit left aligned data holding register, Address offset: 0x24 */ - __IO uint32_t DHR8RD; /*!< DUAL DAC 8-bit right aligned data holding register, Address offset: 0x28 */ - __IO uint32_t DOR1; /*!< DAC channel1 data output register, Address offset: 0x2C */ - __IO uint32_t DOR2; /*!< DAC channel2 data output register, Address offset: 0x30 */ - __IO uint32_t SR; /*!< DAC status register, Address offset: 0x34 */ -} DAC_TypeDef; - -/** - * @brief Debug MCU - */ - -typedef struct -{ - __IO uint32_t IDCODE; /*!< MCU device ID code, Address offset: 0x00 */ - __IO uint32_t CR; /*!< Debug MCU configuration register, Address offset: 0x04 */ - __IO uint32_t APB1FZ; /*!< Debug MCU APB1 freeze register, Address offset: 0x08 */ - __IO uint32_t APB2FZ; /*!< Debug MCU APB2 freeze register, Address offset: 0x0C */ -}DBGMCU_TypeDef; - -/** - * @brief DMA Controller - */ - -typedef struct -{ - __IO uint32_t CCR; /*!< DMA channel x configuration register */ - __IO uint32_t CNDTR; /*!< DMA channel x number of data register */ - __IO uint32_t CPAR; /*!< DMA channel x peripheral address register */ - __IO uint32_t CMAR; /*!< DMA channel x memory address register */ -} DMA_Channel_TypeDef; - -typedef struct -{ - __IO uint32_t ISR; /*!< DMA interrupt status register, Address offset: 0x00 */ - __IO uint32_t IFCR; /*!< DMA interrupt flag clear register, Address offset: 0x04 */ -} DMA_TypeDef; - -typedef struct -{ - __IO uint32_t CSELR; /*!< DMA channel selection register, Address offset: 0xA8 */ -} DMA_Request_TypeDef; - -/** - * @brief External Interrupt/Event Controller - */ - -typedef struct -{ - __IO uint32_t IMR; /*!
© COPYRIGHT(c) 2015 STMicroelectronics
- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ - -/** @addtogroup CMSIS - * @{ - */ - -/** @addtogroup stm32l0xx - * @{ - */ - -#ifndef __STM32L0xx_H -#define __STM32L0xx_H - -#ifdef __cplusplus - extern "C" { -#endif /* __cplusplus */ - -/** @addtogroup Library_configuration_section - * @{ - */ - -/** - * @brief STM32 Family - */ -#if !defined (STM32L0) -#define STM32L0 -#endif /* STM32L0 */ - -/* Uncomment the line below according to the target STM32 device used in your - application - */ - -#if !defined (STM32L011xx) && !defined (STM32L021xx) && \ - !defined (STM32L031xx) && !defined (STM32L041xx) && \ - !defined (STM32L051xx) && !defined (STM32L052xx) && !defined (STM32L053xx) && \ - !defined (STM32L061xx) && !defined (STM32L062xx) && !defined (STM32L063xx) && \ - !defined (STM32L071xx) && !defined (STM32L072xx) && !defined (STM32L073xx) && \ - !defined (STM32L081xx) && !defined (STM32L082xx) && !defined (STM32L083xx) \ - /* #define STM32L011xx */ - /* #define STM32L021xx */ - /* #define STM32L031xx */ /*!< STM32L031C6, STM32L031E6, STM32L031F6, STM32L031G6, STM32L031K6 Devices */ - /* #define STM32L041xx */ /*!< STM32L041C6, STM32L041E6, STM32L041F6, STM32L041G6, STM32L041K6 Devices */ - /* #define STM32L051xx */ /*!< STM32L051K8, STM32L051C6, STM32L051C8, STM32L051R6, STM32L051R8 Devices */ - /* #define STM32L052xx */ /*!< STM32L052K6, STM32L052K8, STM32L052C6, STM32L052C8, STM32L052R6, STM32L052R8 Devices */ - /* #define STM32L053xx */ /*!< STM32L053C6, STM32L053C8, STM32L053R6, STM32L053R8 Devices */ - /* #define STM32L061xx */ /*!< */ - /* #define STM32L062xx */ /*!< STM32L062K8 */ - /* #define STM32L063xx */ /*!< STM32L063C8, STM32L063R8 */ - /* #define STM32L071xx */ /*!< */ - #define STM32L072xx /*!< */ - /* #define STM32L073xx */ /*!< STM32L073V8, STM32L073VB, STM32L073RB, STM32L073VZ, STM32L073RZ Devices */ - /* #define STM32L081xx */ /*!< */ - /* #define STM32L082xx */ /*!< */ - /* #define STM32L083xx */ /*!< */ -#endif - -/* Tip: To avoid modifying this file each time you need to switch between these - devices, you can define the device in your toolchain compiler preprocessor. - */ -#if !defined (USE_HAL_DRIVER) -/** - * @brief Comment the line below if you will not use the peripherals drivers. - In this case, these drivers will not be included and the application code will - be based on direct access to peripherals registers - */ -#define USE_HAL_DRIVER -#endif /* USE_HAL_DRIVER */ - -/** - * @brief CMSIS Device version number V1.7.0 - */ -#define __STM32L0xx_CMSIS_VERSION_MAIN (0x01) /*!< [31:24] main version */ -#define __STM32L0xx_CMSIS_VERSION_SUB1 (0x07) /*!< [23:16] sub1 version */ -#define __STM32L0xx_CMSIS_VERSION_SUB2 (0x00) /*!< [15:8] sub2 version */ -#define __STM32L0xx_CMSIS_VERSION_RC (0x00) /*!< [7:0] release candidate */ -#define __STM32L0xx_CMSIS_VERSION ((__STM32L0xx_CMSIS_VERSION_MAIN << 24)\ - |(__STM32L0xx_CMSIS_VERSION_SUB1 << 16)\ - |(__STM32L0xx_CMSIS_VERSION_SUB2 << 8 )\ - |(__STM32L0xx_CMSIS_VERSION_RC)) - -/** - * @} - */ - -/** @addtogroup Device_Included - * @{ - */ -#if defined(STM32L011xx) - #include "stm32l011xx.h" -#elif defined(STM32L021xx) - #include "stm32l021xx.h" -#elif defined(STM32L031xx) - #include "stm32l031xx.h" -#elif defined(STM32L041xx) - #include "stm32l041xx.h" -#elif defined(STM32L051xx) - #include "stm32l051xx.h" -#elif defined(STM32L052xx) - #include "stm32l052xx.h" -#elif defined(STM32L053xx) - #include "stm32l053xx.h" -#elif defined(STM32L062xx) - #include "stm32l062xx.h" -#elif defined(STM32L063xx) - #include "stm32l063xx.h" -#elif defined(STM32L061xx) - #include "stm32l061xx.h" -#elif defined(STM32L071xx) - #include "stm32l071xx.h" -#elif defined(STM32L072xx) - #include "stm32l072xx.h" -#elif defined(STM32L073xx) - #include "stm32l073xx.h" -#elif defined(STM32L082xx) - #include "stm32l082xx.h" -#elif defined(STM32L083xx) - #include "stm32l083xx.h" -#elif defined(STM32L081xx) - #include "stm32l081xx.h" -#else - #error "Please select first the target STM32L0xx device used in your application (in stm32l0xx.h file)" -#endif - -/** - * @} - */ - -/** @addtogroup Exported_types - * @{ - */ -typedef enum -{ - RESET = 0, - SET = !RESET -} FlagStatus, ITStatus; - -typedef enum -{ - DISABLE = 0, - ENABLE = !DISABLE -} FunctionalState; -#define IS_FUNCTIONAL_STATE(STATE) (((STATE) == DISABLE) || ((STATE) == ENABLE)) - -typedef enum -{ - ERROR = 0, - SUCCESS = !ERROR -} ErrorStatus; - -/** - * @} - */ - - -/** @addtogroup Exported_macro - * @{ - */ -#define SET_BIT(REG, BIT) ((REG) |= (BIT)) - -#define CLEAR_BIT(REG, BIT) ((REG) &= ~(BIT)) - -#define READ_BIT(REG, BIT) ((REG) & (BIT)) - -#define CLEAR_REG(REG) ((REG) = (0x0)) - -#define WRITE_REG(REG, VAL) ((REG) = (VAL)) - -#define READ_REG(REG) ((REG)) - -#define MODIFY_REG(REG, CLEARMASK, SETMASK) WRITE_REG((REG), (((READ_REG(REG)) & (~(CLEARMASK))) | (SETMASK))) - -/** - * @} - */ - -#if defined (USE_HAL_DRIVER) - #include "stm32l0xx_hal.h" -#endif /* USE_HAL_DRIVER */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* __STM32L0xx_H */ -/** - * @} - */ - -/** - * @} - */ - - - - -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L072CZ_LRWAN1/device/system_stm32l0xx.c b/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L072CZ_LRWAN1/device/system_stm32l0xx.c deleted file mode 100644 index 736df4d433a..00000000000 --- a/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L072CZ_LRWAN1/device/system_stm32l0xx.c +++ /dev/null @@ -1,480 +0,0 @@ -/** - ****************************************************************************** - * @file system_stm32l0xx.c - * @author MCD Application Team - * @version V1.7.0 - * @date 31-May-2016 - * @brief CMSIS Cortex-M0+ Device Peripheral Access Layer System Source File. - * - * This file provides two functions and one global variable to be called from - * user application: - * - SystemInit(): This function is called at startup just after reset and - * before branch to main program. This call is made inside - * the "startup_stm32l0xx.s" file. - * - * - SystemCoreClock variable: Contains the core clock (HCLK), it can be used - * by the user application to setup the SysTick - * timer or configure other parameters. - * - * - SystemCoreClockUpdate(): Updates the variable SystemCoreClock and must - * be called whenever the core clock is changed - * during program execution. - * - * This file configures the system clock as follows: - *----------------------------------------------------------------------------- - * System clock source | 1- PLL_HSE_EXTC | 3- PLL_HSI - * | (external 8 MHz clock) | (internal 16 MHz) - * | 2- PLL_HSE_XTAL | - * | (external 8 MHz xtal) | - *----------------------------------------------------------------------------- - * SYSCLK(MHz) | 32 | 32 - *----------------------------------------------------------------------------- - * AHBCLK (MHz) | 32 | 32 - *----------------------------------------------------------------------------- - * APB1CLK (MHz) | 32 | 32 - *----------------------------------------------------------------------------- - * APB2CLK (MHz) | 32 | 32 - *----------------------------------------------------------------------------- - * USB capable (48 MHz precise clock) | YES | YES - *----------------------------------------------------------------------------- - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2015 STMicroelectronics

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ - -/** @addtogroup CMSIS - * @{ - */ - -/** @addtogroup stm32l0xx_system - * @{ - */ - -/** @addtogroup STM32L0xx_System_Private_Includes - * @{ - */ - -#include "stm32l0xx.h" -#include "hal_tick.h" - -#if !defined (HSE_VALUE) - #define HSE_VALUE ((uint32_t)8000000U) /*!< Value of the External oscillator in Hz */ -#endif /* HSE_VALUE */ - -#if !defined (MSI_VALUE) - #define MSI_VALUE ((uint32_t)2000000U) /*!< Value of the Internal oscillator in Hz*/ -#endif /* MSI_VALUE */ - -#if !defined (HSI_VALUE) - #define HSI_VALUE ((uint32_t)16000000U) /*!< Value of the Internal oscillator in Hz*/ -#endif /* HSI_VALUE */ - - -/** - * @} - */ - -/** @addtogroup STM32L0xx_System_Private_TypesDefinitions - * @{ - */ - -/** - * @} - */ - -/** @addtogroup STM32L0xx_System_Private_Defines - * @{ - */ -/************************* Miscellaneous Configuration ************************/ - -/*!< Uncomment the following line if you need to relocate your vector Table in - Internal SRAM. */ -/* #define VECT_TAB_SRAM */ -#define VECT_TAB_OFFSET 0x00U /*!< Vector Table base offset field. - This value must be a multiple of 0x100. */ -/******************************************************************************/ -/** - * @} - */ - -/** @addtogroup STM32L0xx_System_Private_Macros - * @{ - */ - -/* Select the clock sources (other than HSI) to start with (0=OFF, 1=ON) */ -#define USE_PLL_HSE_EXTC (0) /* Use external clock */ -#define USE_PLL_HSE_XTAL (0) /* Use external xtal */ - -/** - * @} - */ - -/** @addtogroup STM32L0xx_System_Private_Variables - * @{ - */ - /* This variable is updated in three ways: - 1) by calling CMSIS function SystemCoreClockUpdate() - 2) by calling HAL API function HAL_RCC_GetHCLKFreq() - 3) each time HAL_RCC_ClockConfig() is called to configure the system clock frequency - Note: If you use this function to configure the system clock; then there - is no need to call the 2 first functions listed above, since SystemCoreClock - variable is updated automatically. - */ -uint32_t SystemCoreClock = 32000000; - const uint8_t AHBPrescTable[16] = {0U, 0U, 0U, 0U, 0U, 0U, 0U, 0U, 1U, 2U, 3U, 4U, 6U, 7U, 8U, 9U}; - const uint8_t APBPrescTable[8] = {0U, 0U, 0U, 0U, 1U, 2U, 3U, 4U}; - const uint8_t PLLMulTable[9] = {3U, 4U, 6U, 8U, 12U, 16U, 24U, 32U, 48U}; - -/** - * @} - */ - -/** @addtogroup STM32L0xx_System_Private_FunctionPrototypes - * @{ - */ - -#if (USE_PLL_HSE_XTAL != 0) || (USE_PLL_HSE_EXTC != 0) -uint8_t SetSysClock_PLL_HSE(uint8_t bypass); -#endif - -uint8_t SetSysClock_PLL_HSI(void); - -/** - * @} - */ - -/** @addtogroup STM32L0xx_System_Private_Functions - * @{ - */ - -/** - * @brief Setup the microcontroller system. - * @param None - * @retval None - */ -void SystemInit (void) -{ -/*!< Set MSION bit */ - RCC->CR |= (uint32_t)0x00000100U; - - /*!< Reset SW[1:0], HPRE[3:0], PPRE1[2:0], PPRE2[2:0], MCOSEL[2:0] and MCOPRE[2:0] bits */ - RCC->CFGR &= (uint32_t) 0x88FF400CU; - - /*!< Reset HSION, HSIDIVEN, HSEON, CSSON and PLLON bits */ - RCC->CR &= (uint32_t)0xFEF6FFF6U; - - /*!< Reset HSI48ON bit */ - RCC->CRRCR &= (uint32_t)0xFFFFFFFEU; - - /*!< Reset HSEBYP bit */ - RCC->CR &= (uint32_t)0xFFFBFFFFU; - - /*!< Reset PLLSRC, PLLMUL[3:0] and PLLDIV[1:0] bits */ - RCC->CFGR &= (uint32_t)0xFF02FFFFU; - - /*!< Disable all interrupts */ - RCC->CIER = 0x00000000U; - - /* Configure the Vector Table location add offset address ------------------*/ -#ifdef VECT_TAB_SRAM - SCB->VTOR = SRAM_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal SRAM */ -#else - SCB->VTOR = FLASH_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal FLASH */ -#endif - - /* Configure the Cube driver */ - SystemCoreClock = 8000000; // At this stage the HSI is used as system clock - HAL_Init(); - - /* Configure the System clock source, PLL Multiplier and Divider factors, - AHB/APBx prescalers and Flash settings */ - SetSysClock(); - - /* Reset the timer to avoid issues after the RAM initialization */ - TIM_MST_RESET_ON; - TIM_MST_RESET_OFF; -} - -/** - * @brief Update SystemCoreClock according to Clock Register Values - * The SystemCoreClock variable contains the core clock (HCLK), it can - * be used by the user application to setup the SysTick timer or configure - * other parameters. - * - * @note Each time the core clock (HCLK) changes, this function must be called - * to update SystemCoreClock variable value. Otherwise, any configuration - * based on this variable will be incorrect. - * - * @note - The system frequency computed by this function is not the real - * frequency in the chip. It is calculated based on the predefined - * constant and the selected clock source: - * - * - If SYSCLK source is MSI, SystemCoreClock will contain the MSI - * value as defined by the MSI range. - * - * - If SYSCLK source is HSI, SystemCoreClock will contain the HSI_VALUE(*) - * - * - If SYSCLK source is HSE, SystemCoreClock will contain the HSE_VALUE(**) - * - * - If SYSCLK source is PLL, SystemCoreClock will contain the HSE_VALUE(**) - * or HSI_VALUE(*) multiplied/divided by the PLL factors. - * - * (*) HSI_VALUE is a constant defined in stm32l0xx_hal.h file (default value - * 16 MHz) but the real value may vary depending on the variations - * in voltage and temperature. - * - * (**) HSE_VALUE is a constant defined in stm32l0xx_hal.h file (default value - * 8 MHz), user has to ensure that HSE_VALUE is same as the real - * frequency of the crystal used. Otherwise, this function may - * have wrong result. - * - * - The result of this function could be not correct when using fractional - * value for HSE crystal. - * @param None - * @retval None - */ -void SystemCoreClockUpdate (void) -{ - uint32_t tmp = 0U, pllmul = 0U, plldiv = 0U, pllsource = 0U, msirange = 0U; - - /* Get SYSCLK source -------------------------------------------------------*/ - tmp = RCC->CFGR & RCC_CFGR_SWS; - - switch (tmp) - { - case 0x00U: /* MSI used as system clock */ - msirange = (RCC->ICSCR & RCC_ICSCR_MSIRANGE) >> 13U; - SystemCoreClock = (32768U * (1U << (msirange + 1U))); - break; - case 0x04U: /* HSI used as system clock */ - SystemCoreClock = HSI_VALUE; - break; - case 0x08U: /* HSE used as system clock */ - SystemCoreClock = HSE_VALUE; - break; - case 0x0CU: /* PLL used as system clock */ - /* Get PLL clock source and multiplication factor ----------------------*/ - pllmul = RCC->CFGR & RCC_CFGR_PLLMUL; - plldiv = RCC->CFGR & RCC_CFGR_PLLDIV; - pllmul = PLLMulTable[(pllmul >> 18U)]; - plldiv = (plldiv >> 22U) + 1U; - - pllsource = RCC->CFGR & RCC_CFGR_PLLSRC; - - if (pllsource == 0x00U) - { - /* HSI oscillator clock selected as PLL clock entry */ - SystemCoreClock = (((HSI_VALUE) * pllmul) / plldiv); - } - else - { - /* HSE selected as PLL clock entry */ - SystemCoreClock = (((HSE_VALUE) * pllmul) / plldiv); - } - break; - default: /* MSI used as system clock */ - msirange = (RCC->ICSCR & RCC_ICSCR_MSIRANGE) >> 13U; - SystemCoreClock = (32768U * (1U << (msirange + 1U))); - break; - } - /* Compute HCLK clock frequency --------------------------------------------*/ - /* Get HCLK prescaler */ - tmp = AHBPrescTable[((RCC->CFGR & RCC_CFGR_HPRE) >> 4U)]; - /* HCLK clock frequency */ - SystemCoreClock >>= tmp; -} - -/** - * @brief Configures the System clock source, PLL Multiplier and Divider factors, - * AHB/APBx prescalers and Flash settings - * @note This function should be called only once the RCC clock configuration - * is reset to the default reset state (done in SystemInit() function). - * @param None - * @retval None - */ -void SetSysClock(void) -{ - /* 1- Try to start with HSE and external clock */ -#if USE_PLL_HSE_EXTC != 0 - if (SetSysClock_PLL_HSE(1) == 0) -#endif - { - /* 2- If fail try to start with HSE and external xtal */ - #if USE_PLL_HSE_XTAL != 0 - if (SetSysClock_PLL_HSE(0) == 0) - #endif - { - /* 3- If fail start with HSI clock */ - if (SetSysClock_PLL_HSI() == 0) - { - while(1) - { - // [TODO] Put something here to tell the user that a problem occured... - } - } - } - } - - /* Output clock on MCO1 pin(PA8) for debugging purpose */ - //HAL_RCC_MCOConfig(RCC_MCO1, RCC_MCO1SOURCE_SYSCLK, RCC_MCODIV_1); - //HAL_RCC_MCOConfig(RCC_MCO1, RCC_MCO1SOURCE_HSI48, RCC_MCODIV_1); -} - -#if (USE_PLL_HSE_XTAL != 0) || (USE_PLL_HSE_EXTC != 0) -/******************************************************************************/ -/* PLL (clocked by HSE) used as System clock source */ -/******************************************************************************/ -uint8_t SetSysClock_PLL_HSE(uint8_t bypass) -{ - RCC_ClkInitTypeDef RCC_ClkInitStruct; - RCC_OscInitTypeDef RCC_OscInitStruct; - - /* Used to gain time after DeepSleep in case HSI is used */ - if (__HAL_RCC_GET_FLAG(RCC_FLAG_HSIRDY) != RESET) - { - return 0; - } - - /* The voltage scaling allows optimizing the power consumption when the device is - clocked below the maximum system frequency, to update the voltage scaling value - regarding system frequency refer to product datasheet. */ - __PWR_CLK_ENABLE(); - __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1); - - /* Enable HSE and HSI48 oscillators and activate PLL with HSE as source */ - RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE | RCC_OSCILLATORTYPE_HSI48; - if (bypass == 0) - { - RCC_OscInitStruct.HSEState = RCC_HSE_ON; /* External 8 MHz xtal on OSC_IN/OSC_OUT */ - } - else - { - RCC_OscInitStruct.HSEState = RCC_HSE_BYPASS; /* External 8 MHz clock on OSC_IN */ - } - RCC_OscInitStruct.HSIState = RCC_HSI_OFF; -#if !defined (STM32L031xx) && !defined (STM32L041xx) && !defined(STM32L051xx) && !defined(STM32L061xx) && !defined(STM32L071xx) && !defined(STM32L081xx) && \ - !defined (STM32L011xx) && !defined (STM32L021xx) - RCC_OscInitStruct.HSI48State = RCC_HSI48_ON; /* For USB and RNG clock */ -#endif - // PLLCLK = (8 MHz * 8)/2 = 32 MHz - RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; - RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; - RCC_OscInitStruct.PLL.PLLMUL = RCC_PLLMUL_8; - RCC_OscInitStruct.PLL.PLLDIV = RCC_PLLDIV_2; - if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) - { - return 0; // FAIL - } - - /* Select PLL as system clock source and configure the HCLK, PCLK1 and PCLK2 clocks dividers */ - RCC_ClkInitStruct.ClockType = (RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2); - RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; // 32 MHz - RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; // 32 MHz - RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1; // 32 MHz - RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; // 32 MHz - if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_1) != HAL_OK) - { - return 0; // FAIL - } - - /* Output clock on MCO1 pin(PA8) for debugging purpose */ - //if (bypass == 0) - // HAL_RCC_MCOConfig(RCC_MCO1, RCC_MCO1SOURCE_HSE, RCC_MCODIV_2); // 4 MHz - //else - // HAL_RCC_MCOConfig(RCC_MCO1, RCC_MCO1SOURCE_HSE, RCC_MCODIV_1); // 8 MHz - - return 1; // OK -} -#endif - -/******************************************************************************/ -/* PLL (clocked by HSI) used as System clock source */ -/******************************************************************************/ -uint8_t SetSysClock_PLL_HSI(void) -{ - RCC_ClkInitTypeDef RCC_ClkInitStruct; - RCC_OscInitTypeDef RCC_OscInitStruct; - - /* Enable HSI and HSI48 oscillators and activate PLL with HSI as source */ - RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI | RCC_OSCILLATORTYPE_HSI48; - RCC_OscInitStruct.HSEState = RCC_HSE_OFF; - RCC_OscInitStruct.HSIState = RCC_HSI_ON; -#if !defined (STM32L031xx) && !defined (STM32L041xx) && !defined(STM32L051xx) && !defined(STM32L061xx) && !defined(STM32L071xx) && !defined(STM32L081xx) && \ - !defined (STM32L011xx) && !defined (STM32L021xx) - RCC_OscInitStruct.HSI48State = RCC_HSI48_ON; /* For USB and RNG clock */ -#endif - RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT; - // PLLCLK = (16 MHz * 6)/3 = 32 MHz - RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; - RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI; - RCC_OscInitStruct.PLL.PLLMUL = RCC_PLLMUL_6; - RCC_OscInitStruct.PLL.PLLDIV = RCC_PLLDIV_3; - if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) - { - return 0; // FAIL - } - - /* The voltage scaling allows optimizing the power consumption when the device is - clocked below the maximum system frequency, to update the voltage scaling value - regarding system frequency refer to product datasheet. */ - __PWR_CLK_ENABLE(); - __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1); - - /* Poll VOSF bit of in PWR_CSR. Wait until it is reset to 0 */ - while (__HAL_PWR_GET_FLAG(PWR_FLAG_VOS) != RESET) {}; - - /* Select PLL as system clock source and configure the HCLK, PCLK1 and PCLK2 clocks dividers */ - RCC_ClkInitStruct.ClockType = (RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2); - RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; // 32 MHz - RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; // 32 MHz - RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1; // 32 MHz - RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; // 32 MHz - if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_1) != HAL_OK) - { - return 0; // FAIL - } - - /* Output clock on MCO1 pin(PA8) for debugging purpose */ - //HAL_RCC_MCOConfig(RCC_MCO1, RCC_MCO1SOURCE_HSI, RCC_MCODIV_1); // 16 MHz - - return 1; // OK -} - -/** - * @} - */ - -/** - * @} - */ - -/** - * @} - */ - -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L072CZ_LRWAN1/device/system_stm32l0xx.h b/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L072CZ_LRWAN1/device/system_stm32l0xx.h deleted file mode 100644 index fcf76495699..00000000000 --- a/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L072CZ_LRWAN1/device/system_stm32l0xx.h +++ /dev/null @@ -1,128 +0,0 @@ -/** - ****************************************************************************** - * @file system_stm32l0xx.h - * @author MCD Application Team - * @version V1.7.0 - * @date 31-May-2016 - * @brief CMSIS Cortex-M0+ Device Peripheral Access Layer System Header File. - ****************************************************************************** - * @attention - * - *

© COPYRIGHT(c) 2015 STMicroelectronics

- * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ - -/** @addtogroup CMSIS - * @{ - */ - -/** @addtogroup stm32l0xx_system - * @{ - */ - -/** - * @brief Define to prevent recursive inclusion - */ -#ifndef __SYSTEM_STM32L0XX_H -#define __SYSTEM_STM32L0XX_H - -#ifdef __cplusplus - extern "C" { -#endif - -/** @addtogroup STM32L0xx_System_Includes - * @{ - */ - -/** - * @} - */ - - -/** @addtogroup STM32L0xx_System_Exported_types - * @{ - */ - /* This variable is updated in three ways: - 1) by calling CMSIS function SystemCoreClockUpdate() - 2) by calling HAL API function HAL_RCC_GetSysClockFreq() - 3) each time HAL_RCC_ClockConfig() is called to configure the system clock frequency - Note: If you use this function to configure the system clock; then there - is no need to call the 2 first functions listed above, since SystemCoreClock - variable is updated automatically. - */ -extern uint32_t SystemCoreClock; /*!< System Clock Frequency (Core Clock) */ -/* -*/ -extern const uint8_t AHBPrescTable[16]; /*!< AHB prescalers table values */ -extern const uint8_t APBPrescTable[8]; /*!< APB prescalers table values */ -extern const uint8_t PLLMulTable[9]; /*!< PLL multipiers table values */ - -/** - * @} - */ - -/** @addtogroup STM32L0xx_System_Exported_Constants - * @{ - */ - -/** - * @} - */ - -/** @addtogroup STM32L0xx_System_Exported_Macros - * @{ - */ - -/** - * @} - */ - -/** @addtogroup STM32L0xx_System_Exported_Functions - * @{ - */ - -extern void SystemInit(void); -extern void SystemCoreClockUpdate(void); -extern void SetSysClock(void); - -/** - * @} - */ - -#ifdef __cplusplus -} -#endif - -#endif /*__SYSTEM_STM32L0XX_H */ - -/** - * @} - */ - -/** - * @} - */ -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L072CZ_LRWAN1/objects.h b/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L072CZ_LRWAN1/objects.h deleted file mode 100644 index 63dc73c511b..00000000000 --- a/targets/TARGET_STM/TARGET_STM32L0/TARGET_DISCO_L072CZ_LRWAN1/objects.h +++ /dev/null @@ -1,79 +0,0 @@ -/* mbed Microcontroller Library - ******************************************************************************* - * Copyright (c) 2017, STMicroelectronics - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************* - */ -#ifndef MBED_OBJECTS_H -#define MBED_OBJECTS_H - -#include "cmsis.h" -#include "PortNames.h" -#include "PeripheralNames.h" -#include "PinNames.h" - -#ifdef __cplusplus -extern "C" { -#endif - -struct gpio_irq_s { - IRQn_Type irq_n; - uint32_t irq_index; - uint32_t event; - PinName pin; -}; - -struct port_s { - PortName port; - uint32_t mask; - PinDirection direction; - __IO uint32_t *reg_in; - __IO uint32_t *reg_out; -}; - -struct analogin_s { - ADCName adc; - PinName pin; - uint32_t channel; -}; - -struct dac_s { - DACName dac; - PinName pin; - uint32_t channel; -}; - -struct trng_s { - RNG_HandleTypeDef handle; -}; - -#include "common_objects.h" - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/targets/TARGET_STM/TARGET_STM32L0/TARGET_NUCLEO_L031K6/device/TOOLCHAIN_IAR/stm32l031xx.icf b/targets/TARGET_STM/TARGET_STM32L0/TARGET_NUCLEO_L031K6/device/TOOLCHAIN_IAR/stm32l031xx.icf index c2d7fcf1372..5f4a5d35216 100644 --- a/targets/TARGET_STM/TARGET_STM32L0/TARGET_NUCLEO_L031K6/device/TOOLCHAIN_IAR/stm32l031xx.icf +++ b/targets/TARGET_STM/TARGET_STM32L0/TARGET_NUCLEO_L031K6/device/TOOLCHAIN_IAR/stm32l031xx.icf @@ -15,8 +15,8 @@ define region ROM_region = mem:[from __region_ROM_start__ to __region_ROM_end__] define region RAM_region = mem:[from __region_RAM_start__ to __region_RAM_end__]; /* Stack and Heap */ -define symbol __size_cstack__ = 0x400; -define symbol __size_heap__ = 0x800; +define symbol __size_cstack__ = 0x500; +define symbol __size_heap__ = 0x1000; define block CSTACK with alignment = 8, size = __size_cstack__ { }; define block HEAP with alignment = 8, size = __size_heap__ { }; define block STACKHEAP with fixed order { block HEAP, block CSTACK }; diff --git a/targets/TARGET_STM/TARGET_STM32L0/TARGET_NUCLEO_L053R8/PinNames.h b/targets/TARGET_STM/TARGET_STM32L0/TARGET_NUCLEO_L053R8/PinNames.h index 1b5260c216b..0fe9a43ceee 100644 --- a/targets/TARGET_STM/TARGET_STM32L0/TARGET_NUCLEO_L053R8/PinNames.h +++ b/targets/TARGET_STM/TARGET_STM32L0/TARGET_NUCLEO_L053R8/PinNames.h @@ -129,8 +129,6 @@ typedef enum { LED3 = PA_5, LED4 = PA_5, USER_BUTTON = PC_13, - // Standardized button names - BUTTON1 = USER_BUTTON, SERIAL_TX = PA_2, SERIAL_RX = PA_3, USBTX = PA_2, diff --git a/targets/TARGET_STM/TARGET_STM32L0/TARGET_NUCLEO_L053R8/device/TOOLCHAIN_IAR/stm32l053xx.icf b/targets/TARGET_STM/TARGET_STM32L0/TARGET_NUCLEO_L053R8/device/TOOLCHAIN_IAR/stm32l053xx.icf index 96e6cf2b5d5..cd494490d25 100644 --- a/targets/TARGET_STM/TARGET_STM32L0/TARGET_NUCLEO_L053R8/device/TOOLCHAIN_IAR/stm32l053xx.icf +++ b/targets/TARGET_STM/TARGET_STM32L0/TARGET_NUCLEO_L053R8/device/TOOLCHAIN_IAR/stm32l053xx.icf @@ -15,8 +15,8 @@ define region ROM_region = mem:[from __region_ROM_start__ to __region_ROM_end__] define region RAM_region = mem:[from __region_RAM_start__ to __region_RAM_end__]; /* Stack and Heap */ -define symbol __size_cstack__ = 0x400; -define symbol __size_heap__ = 0x800; +define symbol __size_cstack__ = 0x500; +define symbol __size_heap__ = 0x1000; define block CSTACK with alignment = 8, size = __size_cstack__ { }; define block HEAP with alignment = 8, size = __size_heap__ { }; define block STACKHEAP with fixed order { block HEAP, block CSTACK }; diff --git a/targets/TARGET_STM/TARGET_STM32L0/TARGET_NUCLEO_L073RZ/PinNames.h b/targets/TARGET_STM/TARGET_STM32L0/TARGET_NUCLEO_L073RZ/PinNames.h index 1b5260c216b..0fe9a43ceee 100644 --- a/targets/TARGET_STM/TARGET_STM32L0/TARGET_NUCLEO_L073RZ/PinNames.h +++ b/targets/TARGET_STM/TARGET_STM32L0/TARGET_NUCLEO_L073RZ/PinNames.h @@ -129,8 +129,6 @@ typedef enum { LED3 = PA_5, LED4 = PA_5, USER_BUTTON = PC_13, - // Standardized button names - BUTTON1 = USER_BUTTON, SERIAL_TX = PA_2, SERIAL_RX = PA_3, USBTX = PA_2, diff --git a/targets/TARGET_STM/TARGET_STM32L0/device/stm32l0xx_hal_def.h b/targets/TARGET_STM/TARGET_STM32L0/device/stm32l0xx_hal_def.h index 2893f201c70..303a39a12b4 100644 --- a/targets/TARGET_STM/TARGET_STM32L0/device/stm32l0xx_hal_def.h +++ b/targets/TARGET_STM/TARGET_STM32L0/device/stm32l0xx_hal_def.h @@ -127,7 +127,7 @@ typedef enum }while (0) #endif /* USE_RTOS */ -#if defined ( __GNUC__ ) && !defined ( __CC_ARM ) +#if defined ( __GNUC__ ) #ifndef __weak #define __weak __attribute__((weak)) #endif /* __weak */ diff --git a/targets/TARGET_STM/TARGET_STM32L0/device/stm32l0xx_hal_rcc_ex.c b/targets/TARGET_STM/TARGET_STM32L0/device/stm32l0xx_hal_rcc_ex.c index 69eca7e257f..7466e9989a7 100644 --- a/targets/TARGET_STM/TARGET_STM32L0/device/stm32l0xx_hal_rcc_ex.c +++ b/targets/TARGET_STM/TARGET_STM32L0/device/stm32l0xx_hal_rcc_ex.c @@ -271,7 +271,7 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk __HAL_RCC_I2C1_CONFIG(PeriphClkInit->I2c1ClockSelection); } -#if defined (STM32L071xx) || defined(STM32L072xx) || defined(STM32L073xx) || \ +#if defined (STM32L071xx) || (STM32L072xx) || defined(STM32L073xx) || \ defined(STM32L081xx) || defined(STM32L082xx) || defined(STM32L083xx) /*------------------------------ I2C3 Configuration ------------------------*/ if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_I2C3) == RCC_PERIPHCLK_I2C3) diff --git a/targets/TARGET_STM/TARGET_STM32L1/TARGET_NUCLEO_L152RE/PinNames.h b/targets/TARGET_STM/TARGET_STM32L1/TARGET_NUCLEO_L152RE/PinNames.h index 31aabee3ccc..a5726d715aa 100644 --- a/targets/TARGET_STM/TARGET_STM32L1/TARGET_NUCLEO_L152RE/PinNames.h +++ b/targets/TARGET_STM/TARGET_STM32L1/TARGET_NUCLEO_L152RE/PinNames.h @@ -128,8 +128,6 @@ typedef enum { LED3 = PA_5, LED4 = PA_5, USER_BUTTON = PC_13, - // Standardized button names - BUTTON1 = USER_BUTTON, SERIAL_TX = PA_2, SERIAL_RX = PA_3, USBTX = PA_2, diff --git a/targets/TARGET_STM/TARGET_STM32L1/TARGET_NZ32_SC151/PinNames.h b/targets/TARGET_STM/TARGET_STM32L1/TARGET_NZ32_SC151/PinNames.h index 1cfad048419..3ef8175767f 100644 --- a/targets/TARGET_STM/TARGET_STM32L1/TARGET_NZ32_SC151/PinNames.h +++ b/targets/TARGET_STM/TARGET_STM32L1/TARGET_NZ32_SC151/PinNames.h @@ -104,8 +104,6 @@ typedef enum { LED3 = PB_2, LED4 = PB_2, USER_BUTTON = PC_3, - // Standardized button names - BUTTON1 = USER_BUTTON, #if (MX_DEFAULT_SERIAL_PINS == 0) //Use B10/B11 as default serial port diff --git a/targets/TARGET_STM/TARGET_STM32L1/device/stm32l1xx_hal_def.h b/targets/TARGET_STM/TARGET_STM32L1/device/stm32l1xx_hal_def.h index 6f95764c92e..ef60a7281ea 100644 --- a/targets/TARGET_STM/TARGET_STM32L1/device/stm32l1xx_hal_def.h +++ b/targets/TARGET_STM/TARGET_STM32L1/device/stm32l1xx_hal_def.h @@ -124,7 +124,7 @@ typedef enum }while (0) #endif /* USE_RTOS */ -#if defined ( __GNUC__ ) && !defined ( __CC_ARM ) +#if defined ( __GNUC__ ) #ifndef __weak #define __weak __attribute__((weak)) #endif /* __weak */ diff --git a/features/unsupported/USBHost/USBHost/TARGET_STM/TARGET_STM32L4/TARGET_STM32L476xG/TARGET_DISCO_L476VG/USBHALHost_DISCOL476VG.h b/targets/TARGET_STM/TARGET_STM32L4/TARGET_DISCO_L476VG/USBHALHost_DISCOL476VG.h similarity index 100% rename from features/unsupported/USBHost/USBHost/TARGET_STM/TARGET_STM32L4/TARGET_STM32L476xG/TARGET_DISCO_L476VG/USBHALHost_DISCOL476VG.h rename to targets/TARGET_STM/TARGET_STM32L4/TARGET_DISCO_L476VG/USBHALHost_DISCOL476VG.h diff --git a/features/unsupported/USBHost/USBHost/TARGET_STM/TARGET_STM32L4/TARGET_STM32L476xG/TARGET_DISCO_L476VG/USBHALHost_STM_TARGET.h b/targets/TARGET_STM/TARGET_STM32L4/TARGET_DISCO_L476VG/USBHALHost_STM_TARGET.h similarity index 100% rename from features/unsupported/USBHost/USBHost/TARGET_STM/TARGET_STM32L4/TARGET_STM32L476xG/TARGET_DISCO_L476VG/USBHALHost_STM_TARGET.h rename to targets/TARGET_STM/TARGET_STM32L4/TARGET_DISCO_L476VG/USBHALHost_STM_TARGET.h diff --git a/features/unsupported/USBDevice/USBDevice/TARGET_STM/TARGET_STM32L4/TARGET_STM32L476xG/TARGET_DISCO_L476VG/USBHAL_STM32L476VG.h b/targets/TARGET_STM/TARGET_STM32L4/TARGET_DISCO_L476VG/USBHAL_STM32L476VG.h similarity index 100% rename from features/unsupported/USBDevice/USBDevice/TARGET_STM/TARGET_STM32L4/TARGET_STM32L476xG/TARGET_DISCO_L476VG/USBHAL_STM32L476VG.h rename to targets/TARGET_STM/TARGET_STM32L4/TARGET_DISCO_L476VG/USBHAL_STM32L476VG.h diff --git a/features/unsupported/USBDevice/USBDevice/TARGET_STM/TARGET_STM32L4/TARGET_STM32L476xG/TARGET_DISCO_L476VG/USBHAL_STM_TARGET.h b/targets/TARGET_STM/TARGET_STM32L4/TARGET_DISCO_L476VG/USBHAL_STM_TARGET.h similarity index 100% rename from features/unsupported/USBDevice/USBDevice/TARGET_STM/TARGET_STM32L4/TARGET_STM32L476xG/TARGET_DISCO_L476VG/USBHAL_STM_TARGET.h rename to targets/TARGET_STM/TARGET_STM32L4/TARGET_DISCO_L476VG/USBHAL_STM_TARGET.h diff --git a/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L432xC/TARGET_NUCLEO_L432KC/PeripheralPins.c b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L432xC/TARGET_NUCLEO_L432KC/PeripheralPins.c index 279491f6acc..1cba4d67e27 100644 --- a/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L432xC/TARGET_NUCLEO_L432KC/PeripheralPins.c +++ b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L432xC/TARGET_NUCLEO_L432KC/PeripheralPins.c @@ -49,10 +49,6 @@ const PinMap PinMap_ADC[] = { {PA_7, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 12, 0)}, // ADC1_IN12 {PB_0, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 15, 0)}, // ADC1_IN15 // {PB_1, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 16, 0)}, // ADC1_IN16 - does not support channel >= 16 - {NC, NC, 0} -}; - -const PinMap PinMap_ADC_Internal[] = { {ADC_TEMP, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 17, 0)}, {ADC_VREF, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 0, 0)}, {ADC_VBAT, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 18, 0)}, diff --git a/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L476xG/TARGET_DISCO_L476VG/PeripheralPins.c b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L476xG/TARGET_DISCO_L476VG/PeripheralPins.c index 32d63680265..1d4366809f5 100644 --- a/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L476xG/TARGET_DISCO_L476VG/PeripheralPins.c +++ b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L476xG/TARGET_DISCO_L476VG/PeripheralPins.c @@ -55,10 +55,6 @@ const PinMap PinMap_ADC[] = { {PC_3, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 4, 0)}, // IN4 {PC_4, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 13, 0)}, // IN13 {PC_5, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 14, 0)}, // IN14 - {NC, NC, 0} -}; - -const PinMap PinMap_ADC_Internal[] = { {ADC_TEMP, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 17, 0)}, {ADC_VREF, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 0, 0)}, {ADC_VBAT, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 18, 0)}, diff --git a/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L476xG/TARGET_DISCO_L476VG/PinNames.h b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L476xG/TARGET_DISCO_L476VG/PinNames.h index 051bb42b2aa..a5c46bc0157 100644 --- a/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L476xG/TARGET_DISCO_L476VG/PinNames.h +++ b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L476xG/TARGET_DISCO_L476VG/PinNames.h @@ -142,13 +142,6 @@ typedef enum { JOYSTICK_UP = PA_3, JOYSTICK_DOWN = PA_5, USER_BUTTON = JOYSTICK_CENTER, - // Standardized button names - BUTTON1 = USER_BUTTON, - BUTTON2 = JOYSTICK_LEFT, - BUTTON3 = JOYSTICK_RIGHT, - BUTTON4 = JOYSTICK_UP, - BUTTON5 = JOYSTICK_DOWN, - SERIAL_TX = PD_5, SERIAL_RX = PD_6, USBTX = PD_5, diff --git a/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L476xG/TARGET_NUCLEO_L476RG/PeripheralPins.c b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L476xG/TARGET_NUCLEO_L476RG/PeripheralPins.c index 64317645e6a..2504f11bbcf 100644 --- a/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L476xG/TARGET_NUCLEO_L476RG/PeripheralPins.c +++ b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L476xG/TARGET_NUCLEO_L476RG/PeripheralPins.c @@ -41,8 +41,8 @@ const PinMap PinMap_ADC[] = { {PA_0, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 5, 0)}, // IN5 - ARDUINO A0 {PA_1, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 6, 0)}, // IN6 - ARDUINO A1 -// {PA_2, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 7, 0)}, // IN7 // PA_2 is used as SERIAL_TX -// {PA_3, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 8, 0)}, // IN8 // PA_3 is used as SERIAL_RX + {PA_2, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 7, 0)}, // IN7 + {PA_3, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 8, 0)}, // IN8 {PA_4, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 9, 0)}, // IN9 - ARDUINO A2 {PA_5, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 10, 0)}, // IN10 {PA_6, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 11, 0)}, // IN11 @@ -55,10 +55,6 @@ const PinMap PinMap_ADC[] = { {PC_3, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 4, 0)}, // IN4 {PC_4, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 13, 0)}, // IN13 {PC_5, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 14, 0)}, // IN14 - {NC, NC, 0} -}; - -const PinMap PinMap_ADC_Internal[] = { {ADC_TEMP, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 17, 0)}, {ADC_VREF, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 0, 0)}, {ADC_VBAT, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 18, 0)}, @@ -102,10 +98,10 @@ const PinMap PinMap_PWM[] = { {PA_1, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 2, 0)}, // TIM2_CH2 // {PA_1, PWM_5, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM5, 2, 0)}, // TIM5_CH2 (used by us_ticker) // {PA_1, PWM_15, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF14_TIM15, 1, 1)},// TIM15_CH1N -// {PA_2, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 3, 0)}, // TIM2_CH3 // PA_2 is used as SERIAL_TX + {PA_2, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 3, 0)}, // TIM2_CH3 // {PA_2, PWM_5, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM5, 3, 0)}, // TIM5_CH3 (used by us_ticker) // {PA_2, PWM_15, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF14_TIM15, 1, 0)},// TIM15_CH1 -// {PA_3, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 4, 0)}, // TIM2_CH4 // PA_3 is used as SERIAL_RX + {PA_3, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 4, 0)}, // TIM2_CH4 // {PA_3, PWM_5, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM5, 4, 0)}, // TIM5_CH4 (used by us_ticker) // {PA_3, PWM_15, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF14_TIM15, 2, 0)},// TIM15_CH2 {PA_5, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 1, 0)}, // TIM2_CH1 @@ -163,11 +159,11 @@ const PinMap PinMap_PWM[] = { const PinMap PinMap_UART_TX[] = { {PA_0, UART_4, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_UART4)}, - {PA_2, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART2)}, // SERIAL_TX + {PA_2, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART2)}, {PA_9, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)}, {PB_6, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)}, {PB_10, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)}, - {PB_11, LPUART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_LPUART1)}, +// {PB_11, LPUART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_LPUART1)}, // Already used by UART_RX {PC_1, LPUART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_LPUART1)}, {PC_4, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)}, {PC_10, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)}, @@ -178,10 +174,10 @@ const PinMap PinMap_UART_TX[] = { const PinMap PinMap_UART_RX[] = { {PA_1, UART_4, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_UART4)}, - {PA_3, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART2)}, // SERIAL_RX + {PA_3, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART2)}, {PA_10, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)}, {PB_7, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)}, - {PB_10, LPUART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_LPUART1)}, +// {PB_10, LPUART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_LPUART1)}, // Already used by UART_TX {PB_11, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)}, {PC_0, LPUART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_LPUART1)}, {PC_5, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)}, diff --git a/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L476xG/TARGET_NUCLEO_L476RG/PinNames.h b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L476xG/TARGET_NUCLEO_L476RG/PinNames.h index de35e5ac85f..2cea26f51af 100644 --- a/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L476xG/TARGET_NUCLEO_L476RG/PinNames.h +++ b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L476xG/TARGET_NUCLEO_L476RG/PinNames.h @@ -129,8 +129,6 @@ typedef enum { LED3 = PA_5, LED4 = PA_5, USER_BUTTON = PC_13, - // Standardized button names - BUTTON1 = USER_BUTTON, SERIAL_TX = PA_2, SERIAL_RX = PA_3, USBTX = PA_2, diff --git a/features/unsupported/USBHost/USBHost/TARGET_STM/TARGET_STM32L4/TARGET_STM32L476xG/TARGET_NUCLEO_L476RG/USBHALHost_STM_TARGET.h b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L476xG/TARGET_NUCLEO_L476RG/USBHALHost_STM_TARGET.h similarity index 100% rename from features/unsupported/USBHost/USBHost/TARGET_STM/TARGET_STM32L4/TARGET_STM32L476xG/TARGET_NUCLEO_L476RG/USBHALHost_STM_TARGET.h rename to targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L476xG/TARGET_NUCLEO_L476RG/USBHALHost_STM_TARGET.h diff --git a/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L486xG/TARGET_NUCLEO_L486RG/PeripheralPins.c b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L486xG/TARGET_NUCLEO_L486RG/PeripheralPins.c index 64317645e6a..2504f11bbcf 100644 --- a/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L486xG/TARGET_NUCLEO_L486RG/PeripheralPins.c +++ b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L486xG/TARGET_NUCLEO_L486RG/PeripheralPins.c @@ -41,8 +41,8 @@ const PinMap PinMap_ADC[] = { {PA_0, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 5, 0)}, // IN5 - ARDUINO A0 {PA_1, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 6, 0)}, // IN6 - ARDUINO A1 -// {PA_2, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 7, 0)}, // IN7 // PA_2 is used as SERIAL_TX -// {PA_3, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 8, 0)}, // IN8 // PA_3 is used as SERIAL_RX + {PA_2, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 7, 0)}, // IN7 + {PA_3, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 8, 0)}, // IN8 {PA_4, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 9, 0)}, // IN9 - ARDUINO A2 {PA_5, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 10, 0)}, // IN10 {PA_6, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 11, 0)}, // IN11 @@ -55,10 +55,6 @@ const PinMap PinMap_ADC[] = { {PC_3, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 4, 0)}, // IN4 {PC_4, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 13, 0)}, // IN13 {PC_5, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG_ADC_CONTROL, GPIO_NOPULL, 0, 14, 0)}, // IN14 - {NC, NC, 0} -}; - -const PinMap PinMap_ADC_Internal[] = { {ADC_TEMP, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 17, 0)}, {ADC_VREF, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 0, 0)}, {ADC_VBAT, ADC_1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 18, 0)}, @@ -102,10 +98,10 @@ const PinMap PinMap_PWM[] = { {PA_1, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 2, 0)}, // TIM2_CH2 // {PA_1, PWM_5, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM5, 2, 0)}, // TIM5_CH2 (used by us_ticker) // {PA_1, PWM_15, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF14_TIM15, 1, 1)},// TIM15_CH1N -// {PA_2, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 3, 0)}, // TIM2_CH3 // PA_2 is used as SERIAL_TX + {PA_2, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 3, 0)}, // TIM2_CH3 // {PA_2, PWM_5, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM5, 3, 0)}, // TIM5_CH3 (used by us_ticker) // {PA_2, PWM_15, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF14_TIM15, 1, 0)},// TIM15_CH1 -// {PA_3, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 4, 0)}, // TIM2_CH4 // PA_3 is used as SERIAL_RX + {PA_3, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 4, 0)}, // TIM2_CH4 // {PA_3, PWM_5, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM5, 4, 0)}, // TIM5_CH4 (used by us_ticker) // {PA_3, PWM_15, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF14_TIM15, 2, 0)},// TIM15_CH2 {PA_5, PWM_2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM2, 1, 0)}, // TIM2_CH1 @@ -163,11 +159,11 @@ const PinMap PinMap_PWM[] = { const PinMap PinMap_UART_TX[] = { {PA_0, UART_4, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_UART4)}, - {PA_2, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART2)}, // SERIAL_TX + {PA_2, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART2)}, {PA_9, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)}, {PB_6, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)}, {PB_10, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)}, - {PB_11, LPUART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_LPUART1)}, +// {PB_11, LPUART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_LPUART1)}, // Already used by UART_RX {PC_1, LPUART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_LPUART1)}, {PC_4, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)}, {PC_10, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)}, @@ -178,10 +174,10 @@ const PinMap PinMap_UART_TX[] = { const PinMap PinMap_UART_RX[] = { {PA_1, UART_4, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_UART4)}, - {PA_3, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART2)}, // SERIAL_RX + {PA_3, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART2)}, {PA_10, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)}, {PB_7, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART1)}, - {PB_10, LPUART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_LPUART1)}, +// {PB_10, LPUART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_LPUART1)}, // Already used by UART_TX {PB_11, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)}, {PC_0, LPUART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF8_LPUART1)}, {PC_5, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_USART3)}, diff --git a/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L486xG/TARGET_NUCLEO_L486RG/PinNames.h b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L486xG/TARGET_NUCLEO_L486RG/PinNames.h index de35e5ac85f..2cea26f51af 100644 --- a/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L486xG/TARGET_NUCLEO_L486RG/PinNames.h +++ b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L486xG/TARGET_NUCLEO_L486RG/PinNames.h @@ -129,8 +129,6 @@ typedef enum { LED3 = PA_5, LED4 = PA_5, USER_BUTTON = PC_13, - // Standardized button names - BUTTON1 = USER_BUTTON, SERIAL_TX = PA_2, SERIAL_RX = PA_3, USBTX = PA_2, diff --git a/features/unsupported/USBHost/USBHost/TARGET_STM/TARGET_STM32L4/TARGET_STM32L486xG/TARGET_NUCLEO_L486RG/USBHALHost_STM_TARGET.h b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L486xG/TARGET_NUCLEO_L486RG/USBHALHost_STM_TARGET.h similarity index 100% rename from features/unsupported/USBHost/USBHost/TARGET_STM/TARGET_STM32L4/TARGET_STM32L486xG/TARGET_NUCLEO_L486RG/USBHALHost_STM_TARGET.h rename to targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L486xG/TARGET_NUCLEO_L486RG/USBHALHost_STM_TARGET.h diff --git a/targets/TARGET_STM/TARGET_STM32L4/analogin_api.c b/targets/TARGET_STM/TARGET_STM32L4/analogin_api.c index 081241aec34..b49ff1637f3 100644 --- a/targets/TARGET_STM/TARGET_STM32L4/analogin_api.c +++ b/targets/TARGET_STM/TARGET_STM32L4/analogin_api.c @@ -42,30 +42,20 @@ int adc_inited = 0; void analogin_init(analogin_t *obj, PinName pin) { - uint32_t function = (uint32_t)NC; - obj->adc = (ADCName)NC; + // Get the peripheral name from the pin and assign it to the object + obj->adc = (ADCName)pinmap_peripheral(pin, PinMap_ADC); + MBED_ASSERT(obj->adc != (ADCName)NC); - // ADC Internal Channels "pins" (Temperature, Vref, Vbat, ...) - // are described in PinNames.h and PeripheralPins.c - // Pin value must be >= 0xF0 + // Get the pin function and assign the used channel to the object + uint32_t function = pinmap_function(pin, PinMap_ADC); + MBED_ASSERT(function != (uint32_t)NC); + obj->channel = STM_PIN_CHANNEL(function); + + // Configure GPIO excepted for internal channels (Temperature, Vref, Vbat, ...) + // ADC Internal Channels "pins" are described in PinNames.h and must have a value >= 0xF0 if (pin < 0xF0) { - // Normal channels - // Get the peripheral name from the pin and assign it to the object - obj->adc = (ADCName)pinmap_peripheral(pin, PinMap_ADC); - // Get the functions (adc channel) from the pin and assign it to the object - function = pinmap_function(pin, PinMap_ADC); - // Configure GPIO pinmap_pinout(pin, PinMap_ADC); - } else { - // Internal channels - obj->adc = (ADCName)pinmap_peripheral(pin, PinMap_ADC_Internal); - function = pinmap_function(pin, PinMap_ADC_Internal); - // No GPIO configuration for internal channels } - MBED_ASSERT(obj->adc != (ADCName)NC); - MBED_ASSERT(function != (uint32_t)NC); - - obj->channel = STM_PIN_CHANNEL(function); // Save pin number for the read function obj->pin = pin; diff --git a/targets/TARGET_STM/TARGET_STM32L4/device/stm32l4xx_hal_def.h b/targets/TARGET_STM/TARGET_STM32L4/device/stm32l4xx_hal_def.h index 7272c4d452a..290a56b3c3c 100644 --- a/targets/TARGET_STM/TARGET_STM32L4/device/stm32l4xx_hal_def.h +++ b/targets/TARGET_STM/TARGET_STM32L4/device/stm32l4xx_hal_def.h @@ -147,7 +147,7 @@ static inline void atomic_clr_u32(volatile uint32_t *ptr, uint32_t mask) } while (__STREXW(newValue,(volatile unsigned long*) ptr)); } -#if defined ( __GNUC__ ) && !defined ( __CC_ARM ) +#if defined ( __GNUC__ ) #ifndef __weak #define __weak __attribute__((weak)) #endif /* __weak */ diff --git a/targets/TARGET_STM/TARGET_STM32L4/device/stm32l4xx_hal_hcd.c b/targets/TARGET_STM/TARGET_STM32L4/device/stm32l4xx_hal_hcd.c index b51d39040e9..f43fde3ea96 100644 --- a/targets/TARGET_STM/TARGET_STM32L4/device/stm32l4xx_hal_hcd.c +++ b/targets/TARGET_STM/TARGET_STM32L4/device/stm32l4xx_hal_hcd.c @@ -939,14 +939,11 @@ static void HCD_HC_IN_IRQHandler (HCD_HandleTypeDef *hhcd, uint8_t chnum) /* re-activate the channel */ tmpreg = USBx_HC(chnum)->HCCHAR; tmpreg &= ~USB_OTG_HCCHAR_CHDIS; - if ( hhcd->hc[chnum].urb_state != URB_ERROR) { - tmpreg |= USB_OTG_HCCHAR_CHENA; - reactivate = 1; - } + tmpreg |= USB_OTG_HCCHAR_CHENA; USBx_HC(chnum)->HCCHAR = tmpreg; + reactivate = 1; } __HAL_HCD_CLEAR_HC_INT(chnum, USB_OTG_HCINT_CHH); - if (hhcd->hc[chnum].state == 0) reactivate = 1; if (reactivate == 0) HAL_HCD_HC_NotifyURBChange_Callback(hhcd, chnum, hhcd->hc[chnum].urb_state); } diff --git a/features/unsupported/USBHost/USBHost/TARGET_STM/USBHALHost_STM_144_64pins.h b/targets/TARGET_STM/USBHALHost_STM_144_64pins.h similarity index 100% rename from features/unsupported/USBHost/USBHost/TARGET_STM/USBHALHost_STM_144_64pins.h rename to targets/TARGET_STM/USBHALHost_STM_144_64pins.h diff --git a/features/unsupported/USBDevice/USBDevice/TARGET_STM/USBHAL_STM_144_64pins.h b/targets/TARGET_STM/USBHAL_STM_144_64pins.h similarity index 100% rename from features/unsupported/USBDevice/USBDevice/TARGET_STM/USBHAL_STM_144_64pins.h rename to targets/TARGET_STM/USBHAL_STM_144_64pins.h diff --git a/targets/TARGET_STM/can_api.c b/targets/TARGET_STM/can_api.c index 8b6340fedf8..27f382207f1 100644 --- a/targets/TARGET_STM/can_api.c +++ b/targets/TARGET_STM/can_api.c @@ -69,7 +69,7 @@ void can_init(can_t *obj, PinName rd, PinName td) CanHandle.Init.AWUM = DISABLE; CanHandle.Init.NART = DISABLE; CanHandle.Init.RFLM = DISABLE; - CanHandle.Init.TXFP = DISABLE; + CanHandle.Init.TXFP = ENABLE; CanHandle.Init.Mode = CAN_MODE_NORMAL; CanHandle.Init.SJW = CAN_SJW_1TQ; CanHandle.Init.BS1 = CAN_BS1_6TQ; diff --git a/targets/TARGET_STM/gpio_api.c b/targets/TARGET_STM/gpio_api.c index 60d300d32cd..d309b956933 100644 --- a/targets/TARGET_STM/gpio_api.c +++ b/targets/TARGET_STM/gpio_api.c @@ -41,34 +41,34 @@ GPIO_TypeDef *Set_GPIO_Clock(uint32_t port_idx) { switch (port_idx) { case PortA: gpio_add = GPIOA_BASE; - __HAL_RCC_GPIOA_CLK_ENABLE(); + __GPIOA_CLK_ENABLE(); break; case PortB: gpio_add = GPIOB_BASE; - __HAL_RCC_GPIOB_CLK_ENABLE(); + __GPIOB_CLK_ENABLE(); break; #if defined(GPIOC_BASE) case PortC: gpio_add = GPIOC_BASE; - __HAL_RCC_GPIOC_CLK_ENABLE(); + __GPIOC_CLK_ENABLE(); break; #endif #if defined GPIOD_BASE case PortD: gpio_add = GPIOD_BASE; - __HAL_RCC_GPIOD_CLK_ENABLE(); + __GPIOD_CLK_ENABLE(); break; #endif #if defined GPIOE_BASE case PortE: gpio_add = GPIOE_BASE; - __HAL_RCC_GPIOE_CLK_ENABLE(); + __GPIOE_CLK_ENABLE(); break; #endif #if defined GPIOF_BASE case PortF: gpio_add = GPIOF_BASE; - __HAL_RCC_GPIOF_CLK_ENABLE(); + __GPIOF_CLK_ENABLE(); break; #endif #if defined GPIOG_BASE @@ -78,31 +78,31 @@ GPIO_TypeDef *Set_GPIO_Clock(uint32_t port_idx) { HAL_PWREx_EnableVddIO2(); #endif gpio_add = GPIOG_BASE; - __HAL_RCC_GPIOG_CLK_ENABLE(); + __GPIOG_CLK_ENABLE(); break; #endif #if defined GPIOH_BASE case PortH: gpio_add = GPIOH_BASE; - __HAL_RCC_GPIOH_CLK_ENABLE(); + __GPIOH_CLK_ENABLE(); break; #endif #if defined GPIOI_BASE case PortI: gpio_add = GPIOI_BASE; - __HAL_RCC_GPIOI_CLK_ENABLE(); + __GPIOI_CLK_ENABLE(); break; #endif #if defined GPIOJ_BASE case PortJ: gpio_add = GPIOJ_BASE; - __HAL_RCC_GPIOJ_CLK_ENABLE(); + __GPIOJ_CLK_ENABLE(); break; #endif #if defined GPIOK_BASE case PortK: gpio_add = GPIOK_BASE; - __HAL_RCC_GPIOK_CLK_ENABLE(); + __GPIOK_CLK_ENABLE(); break; #endif default: diff --git a/targets/TARGET_STM/hal_tick_16b.c b/targets/TARGET_STM/hal_tick_16b.c index 150c25c677e..7133b35e8a7 100644 --- a/targets/TARGET_STM/hal_tick_16b.c +++ b/targets/TARGET_STM/hal_tick_16b.c @@ -84,12 +84,12 @@ void timer_oc_irq_handler(void) if (__HAL_TIM_GET_FLAG(&TimMasterHandle, TIM_FLAG_CC2) == SET) { if (__HAL_TIM_GET_IT_SOURCE(&TimMasterHandle, TIM_IT_CC2) == SET) { __HAL_TIM_CLEAR_IT(&TimMasterHandle, TIM_IT_CC2); - uint32_t val = __HAL_TIM_GET_COUNTER(&TimMasterHandle); + uint32_t val = __HAL_TIM_GetCounter(&TimMasterHandle); if ((val - PreviousVal) >= HAL_TICK_DELAY) { // Increment HAL variable HAL_IncTick(); // Prepare next interrupt - __HAL_TIM_SET_COMPARE(&TimMasterHandle, TIM_CHANNEL_2, val + HAL_TICK_DELAY); + __HAL_TIM_SetCompare(&TimMasterHandle, TIM_CHANNEL_2, val + HAL_TICK_DELAY); PreviousVal = val; #if DEBUG_TICK > 0 HAL_GPIO_TogglePin(GPIOB, GPIO_PIN_6); @@ -128,8 +128,8 @@ HAL_StatusTypeDef HAL_InitTick(uint32_t TickPriority) // Configure output compare channel 2 for HAL tick HAL_TIM_OC_Start(&TimMasterHandle, TIM_CHANNEL_2); - PreviousVal = __HAL_TIM_GET_COUNTER(&TimMasterHandle); - __HAL_TIM_SET_COMPARE(&TimMasterHandle, TIM_CHANNEL_2, PreviousVal + HAL_TICK_DELAY); + PreviousVal = __HAL_TIM_GetCounter(&TimMasterHandle); + __HAL_TIM_SetCompare(&TimMasterHandle, TIM_CHANNEL_2, PreviousVal + HAL_TICK_DELAY); // Configure interrupts // Update interrupt used for 32-bit counter @@ -155,7 +155,7 @@ HAL_StatusTypeDef HAL_InitTick(uint32_t TickPriority) HAL_TIM_Base_Start(&TimMasterHandle); #if DEBUG_TICK > 0 - __HAL_RCC_GPIOB_CLK_ENABLE(); + __GPIOB_CLK_ENABLE(); GPIO_InitTypeDef GPIO_InitStruct; GPIO_InitStruct.Pin = GPIO_PIN_6; GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; diff --git a/targets/TARGET_STM/hal_tick_32b.c b/targets/TARGET_STM/hal_tick_32b.c index 3ccd52b4ee5..0f9c3dccad2 100644 --- a/targets/TARGET_STM/hal_tick_32b.c +++ b/targets/TARGET_STM/hal_tick_32b.c @@ -47,7 +47,7 @@ void timer_irq_handler(void) // Increment HAL variable HAL_IncTick(); // Prepare next interrupt - __HAL_TIM_SET_COMPARE(&TimMasterHandle, TIM_CHANNEL_2, val + HAL_TICK_DELAY); + __HAL_TIM_SetCompare(&TimMasterHandle, TIM_CHANNEL_2, val + HAL_TICK_DELAY); PreviousVal = val; #if DEBUG_TICK > 0 HAL_GPIO_TogglePin(GPIOB, GPIO_PIN_6); @@ -115,11 +115,11 @@ HAL_StatusTypeDef HAL_InitTick(uint32_t TickPriority) // Channel 2 for HAL tick HAL_TIM_OC_Start(&TimMasterHandle, TIM_CHANNEL_2); PreviousVal = __HAL_TIM_GetCounter(&TimMasterHandle); - __HAL_TIM_SET_COMPARE(&TimMasterHandle, TIM_CHANNEL_2, PreviousVal + HAL_TICK_DELAY); + __HAL_TIM_SetCompare(&TimMasterHandle, TIM_CHANNEL_2, PreviousVal + HAL_TICK_DELAY); __HAL_TIM_ENABLE_IT(&TimMasterHandle, TIM_IT_CC2); #if DEBUG_TICK > 0 - __HAL_RCC_GPIOB_CLK_ENABLE(); + __GPIOB_CLK_ENABLE(); GPIO_InitTypeDef GPIO_InitStruct; GPIO_InitStruct.Pin = GPIO_PIN_6; GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; diff --git a/targets/TARGET_STM/i2c_api.c b/targets/TARGET_STM/i2c_api.c index 2c1cddf7c38..23e4fa6d13c 100644 --- a/targets/TARGET_STM/i2c_api.c +++ b/targets/TARGET_STM/i2c_api.c @@ -436,9 +436,9 @@ void i2c_frequency(i2c_t *obj, int hz) // I2C configuration handle->Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT; - handle->Init.DualAddressMode = I2C_DUALADDRESS_DISABLE; - handle->Init.GeneralCallMode = I2C_GENERALCALL_DISABLE; - handle->Init.NoStretchMode = I2C_NOSTRETCH_DISABLE; + handle->Init.DualAddressMode = I2C_DUALADDRESS_DISABLED; + handle->Init.GeneralCallMode = I2C_GENERALCALL_DISABLED; + handle->Init.NoStretchMode = I2C_NOSTRETCH_DISABLED; handle->Init.OwnAddress1 = 0; handle->Init.OwnAddress2 = 0; HAL_I2C_Init(handle); diff --git a/targets/TARGET_STM/mbed_rtx.h b/targets/TARGET_STM/mbed_rtx.h index f0d09701bf8..8b859dbfa59 100644 --- a/targets/TARGET_STM/mbed_rtx.h +++ b/targets/TARGET_STM/mbed_rtx.h @@ -302,21 +302,6 @@ #define OS_CLOCK 168000000 #endif -#elif defined(TARGET_UBLOX_C030) - -#ifndef INITIAL_SP -#define INITIAL_SP (0x20030000UL) -#endif -#ifndef OS_TASKCNT -#define OS_TASKCNT 14 -#endif -#ifndef OS_MAINSTKSIZE -#define OS_MAINSTKSIZE 512 -#endif -#ifndef OS_CLOCK -#define OS_CLOCK 168000000 -#endif - #elif defined(TARGET_STM32F469NI) #ifndef INITIAL_SP @@ -572,21 +557,6 @@ #define OS_CLOCK 32000000 #endif -#elif defined(TARGET_STM32L072CZ) - -#ifndef INITIAL_SP -#define INITIAL_SP (0x20005000UL) -#endif -#ifndef OS_TASKCNT -#define OS_TASKCNT 6 -#endif -#ifndef OS_MAINSTKSIZE -#define OS_MAINSTKSIZE 112 -#endif -#ifndef OS_CLOCK -#define OS_CLOCK 32000000 -#endif - #elif defined(TARGET_STM32L073RZ) #ifndef INITIAL_SP diff --git a/targets/TARGET_STM/rtc_api.c b/targets/TARGET_STM/rtc_api.c index 66255db0caa..7e97c2ef422 100644 --- a/targets/TARGET_STM/rtc_api.c +++ b/targets/TARGET_STM/rtc_api.c @@ -83,7 +83,7 @@ void rtc_init(void) error("PeriphClkInitStruct RTC failed with LSE\n"); } #else /* !RTC_LSI */ - __HAL_RCC_PWR_CLK_ENABLE(); + __PWR_CLK_ENABLE(); // Reset Backup domain __HAL_RCC_BACKUPRESET_FORCE(); @@ -147,7 +147,7 @@ void rtc_free(void) { #if RTC_LSI // Enable Power clock - __HAL_RCC_PWR_CLK_ENABLE(); + __PWR_CLK_ENABLE(); // Enable access to Backup domain HAL_PWR_EnableBkUpAccess(); diff --git a/targets/TARGET_STM/stm_spi_api.c b/targets/TARGET_STM/stm_spi_api.c index ba3f27371db..f756102e396 100644 --- a/targets/TARGET_STM/stm_spi_api.c +++ b/targets/TARGET_STM/stm_spi_api.c @@ -158,11 +158,11 @@ void spi_init(spi_t *obj, PinName mosi, PinName miso, PinName sclk, PinName ssel handle->Init.Direction = SPI_DIRECTION_2LINES; handle->Init.CLKPhase = SPI_PHASE_1EDGE; handle->Init.CLKPolarity = SPI_POLARITY_LOW; - handle->Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE; + handle->Init.CRCCalculation = SPI_CRCCALCULATION_DISABLED; handle->Init.CRCPolynomial = 7; handle->Init.DataSize = SPI_DATASIZE_8BIT; handle->Init.FirstBit = SPI_FIRSTBIT_MSB; - handle->Init.TIMode = SPI_TIMODE_DISABLE; + handle->Init.TIMode = SPI_TIMODE_DISABLED; init_spi(obj); } @@ -357,7 +357,7 @@ int spi_master_write(spi_t *obj, int value) size = (handle->Init.DataSize == SPI_DATASIZE_16BIT) ? 2 : 1; /* Use 10ms timeout */ - ret = HAL_SPI_TransmitReceive(handle,(uint8_t*)&value,(uint8_t*)&Rx,size,HAL_MAX_DELAY); + ret = HAL_SPI_TransmitReceive(handle,(uint8_t*)&value,(uint8_t*)&Rx,size,10); if(ret == HAL_OK) { return Rx; diff --git a/targets/TARGET_STM/us_ticker_16b.c b/targets/TARGET_STM/us_ticker_16b.c index 8480391dbd8..0b4f3747d71 100644 --- a/targets/TARGET_STM/us_ticker_16b.c +++ b/targets/TARGET_STM/us_ticker_16b.c @@ -35,7 +35,7 @@ void set_compare(uint16_t count) { TimMasterHandle.Instance = TIM_MST; // Set new output compare value - __HAL_TIM_SET_COMPARE(&TimMasterHandle, TIM_CHANNEL_1, count); + __HAL_TIM_SetCompare(&TimMasterHandle, TIM_CHANNEL_1, count); // Enable IT __HAL_TIM_ENABLE_IT(&TimMasterHandle, TIM_IT_CC1); } diff --git a/targets/TARGET_Silicon_Labs/TARGET_EFM32/TARGET_EFM32GG/TARGET_EFM32GG_STK3700/PinNames.h b/targets/TARGET_Silicon_Labs/TARGET_EFM32/TARGET_EFM32GG/TARGET_EFM32GG_STK3700/PinNames.h index 45570ee6379..bf783f73885 100644 --- a/targets/TARGET_Silicon_Labs/TARGET_EFM32/TARGET_EFM32GG/TARGET_EFM32GG_STK3700/PinNames.h +++ b/targets/TARGET_Silicon_Labs/TARGET_EFM32/TARGET_EFM32GG/TARGET_EFM32GG_STK3700/PinNames.h @@ -44,9 +44,6 @@ typedef enum { SW1 = PB10, BTN0 = SW0, BTN1 = SW1, - // Standardized button names - BUTTON1 = BTN0, - BUTTON2 = BTN1, /* Serial */ SERIAL_TX = PD0, diff --git a/targets/TARGET_Silicon_Labs/TARGET_EFM32/TARGET_EFM32HG/TARGET_EFM32HG_STK3400/PinNames.h b/targets/TARGET_Silicon_Labs/TARGET_EFM32/TARGET_EFM32HG/TARGET_EFM32HG_STK3400/PinNames.h index fa8bc7e6c33..0b249e0bebf 100644 --- a/targets/TARGET_Silicon_Labs/TARGET_EFM32/TARGET_EFM32HG/TARGET_EFM32HG_STK3400/PinNames.h +++ b/targets/TARGET_Silicon_Labs/TARGET_EFM32/TARGET_EFM32HG/TARGET_EFM32HG_STK3400/PinNames.h @@ -44,9 +44,6 @@ typedef enum { SW1 = PC10, BTN0 = SW0, BTN1 = SW1, - // Standardized button names - BUTTON1 = BTN0, - BUTTON2 = BTN1, /* Serial */ SERIAL_TX = PE10, diff --git a/targets/TARGET_Silicon_Labs/TARGET_EFM32/TARGET_EFM32LG/TARGET_EFM32LG_STK3600/PinNames.h b/targets/TARGET_Silicon_Labs/TARGET_EFM32/TARGET_EFM32LG/TARGET_EFM32LG_STK3600/PinNames.h index 45570ee6379..bf783f73885 100644 --- a/targets/TARGET_Silicon_Labs/TARGET_EFM32/TARGET_EFM32LG/TARGET_EFM32LG_STK3600/PinNames.h +++ b/targets/TARGET_Silicon_Labs/TARGET_EFM32/TARGET_EFM32LG/TARGET_EFM32LG_STK3600/PinNames.h @@ -44,9 +44,6 @@ typedef enum { SW1 = PB10, BTN0 = SW0, BTN1 = SW1, - // Standardized button names - BUTTON1 = BTN0, - BUTTON2 = BTN1, /* Serial */ SERIAL_TX = PD0, diff --git a/targets/TARGET_Silicon_Labs/TARGET_EFM32/TARGET_EFM32PG/TARGET_EFM32PG_STK3401/PinNames.h b/targets/TARGET_Silicon_Labs/TARGET_EFM32/TARGET_EFM32PG/TARGET_EFM32PG_STK3401/PinNames.h index 51832585007..4985448d14a 100644 --- a/targets/TARGET_Silicon_Labs/TARGET_EFM32/TARGET_EFM32PG/TARGET_EFM32PG_STK3401/PinNames.h +++ b/targets/TARGET_Silicon_Labs/TARGET_EFM32/TARGET_EFM32PG/TARGET_EFM32PG_STK3401/PinNames.h @@ -44,9 +44,6 @@ typedef enum { SW1 = PF7, BTN0 = SW0, BTN1 = SW1, - // Standardized button names - BUTTON1 = BTN0, - BUTTON2 = BTN1, /* Serial (just some usable pins) */ SERIAL_TX = PD10, diff --git a/targets/TARGET_Silicon_Labs/TARGET_EFM32/TARGET_EFM32PG12/PeripheralPins.c b/targets/TARGET_Silicon_Labs/TARGET_EFM32/TARGET_EFM32PG12/PeripheralPins.c index 79f7f1933ed..95baad0840a 100644 --- a/targets/TARGET_Silicon_Labs/TARGET_EFM32/TARGET_EFM32PG12/PeripheralPins.c +++ b/targets/TARGET_Silicon_Labs/TARGET_EFM32/TARGET_EFM32PG12/PeripheralPins.c @@ -100,37 +100,6 @@ const PinMap PinMap_I2C_SCL[] = { {PF7, I2C_0, 30}, {PA0, I2C_0, 31}, - {PA7, I2C_1, 0}, - {PA8, I2C_1, 1}, - {PA9, I2C_1, 2}, - {PI2, I2C_1, 3}, - {PI3, I2C_1, 4}, - {PB6, I2C_1, 5}, - {PB7, I2C_1, 6}, - {PB8, I2C_1, 7}, - {PB9, I2C_1, 8}, - {PB10, I2C_1, 9}, - {PJ14, I2C_1, 10}, - {PJ15, I2C_1, 11}, - {PC0, I2C_1, 12}, - {PC1, I2C_1, 13}, - {PC2, I2C_1, 14}, - {PC3, I2C_1, 15}, - {PC4, I2C_1, 16}, - {PC5, I2C_1, 17}, - {PF8, I2C_1, 20}, - {PF9, I2C_1, 21}, - {PF10, I2C_1, 22}, - {PF11, I2C_1, 23}, - {PF12, I2C_1, 24}, - {PF13, I2C_1, 25}, - {PF14, I2C_1, 26}, - {PF15, I2C_1, 27}, - {PK0, I2C_1, 28}, - {PK1, I2C_1, 29}, - {PK2, I2C_1, 30}, - {PA6, I2C_1, 31}, - {NC , NC , NC} }; @@ -170,39 +139,7 @@ const PinMap PinMap_I2C_SDA[] = { {PF6, I2C_0, 30}, {PF7, I2C_0, 31}, - {PA6, I2C_1, 0}, - {PA7, I2C_1, 1}, - {PA8, I2C_1, 2}, - {PA9, I2C_1, 3}, - {PI2, I2C_1, 4}, - {PI3, I2C_1, 5}, - {PB6, I2C_1, 6}, - {PB7, I2C_1, 7}, - {PB8, I2C_1, 8}, - {PB9, I2C_1, 9}, - {PB10, I2C_1, 10}, - {PJ14, I2C_1, 11}, - {PJ15, I2C_1, 12}, - {PC0, I2C_1, 13}, - {PC1, I2C_1, 14}, - {PC2, I2C_1, 15}, - {PC3, I2C_1, 16}, - {PC4, I2C_1, 17}, - {PC5, I2C_1, 18}, - {PF8, I2C_1, 21}, - {PF9, I2C_1, 22}, - {PF10, I2C_1, 23}, - {PF11, I2C_1, 24}, - {PF12, I2C_1, 25}, - {PF13, I2C_1, 26}, - {PF14, I2C_1, 27}, - {PF15, I2C_1, 28}, - {PK0, I2C_1, 29}, - {PK1, I2C_1, 30}, - {PK2, I2C_1, 31}, - /* Not connected */ - {NC , NC , NC} }; @@ -283,42 +220,6 @@ const PinMap PinMap_SPI_MOSI[] = { {PF6, SPI_1, 30}, {PF7, SPI_1, 31}, - /* USART2 */ - {PA6, SPI_2, 1}, - {PA7, SPI_2, 2}, - {PA8, SPI_2, 3}, - {PA9, SPI_2, 4}, - {PI0, SPI_2, 5}, - {PI1, SPI_2, 6}, - {PI2, SPI_2, 7}, - {PI3, SPI_2, 8}, - {PB6, SPI_2, 9}, - {PB7, SPI_2, 10}, - {PB8, SPI_2, 11}, - {PB9, SPI_2, 12}, - {PB10, SPI_2, 13}, - {PF8, SPI_2, 21}, - {PF9, SPI_2, 22}, - {PF10, SPI_2, 23}, - {PF11, SPI_2, 24}, - {PF12, SPI_2, 25}, - {PF13, SPI_2, 26}, - {PF14, SPI_2, 27}, - {PF15, SPI_2, 28}, - {PK0, SPI_2, 29}, - {PK1, SPI_2, 30}, - {PK2, SPI_2, 31}, - - /* USART3 */ - {PJ14, SPI_3, 16}, - {PJ15, SPI_3, 17}, - {PC0, SPI_3, 18}, - {PC1, SPI_3, 19}, - {PC2, SPI_3, 20}, - {PC3, SPI_3, 21}, - {PC4, SPI_3, 22}, - {PC5, SPI_3, 23}, - {NC , NC , NC} }; @@ -361,42 +262,6 @@ const PinMap PinMap_SPI_MISO[] = { {PF7, SPI_1, 30}, {PA0, SPI_1, 31}, - /* USART2 */ - {PA6, SPI_2, 0}, - {PA7, SPI_2, 1}, - {PA8, SPI_2, 2}, - {PA9, SPI_2, 3}, - {PI0, SPI_2, 4}, - {PI1, SPI_2, 5}, - {PI2, SPI_2, 6}, - {PI3, SPI_2, 7}, - {PB6, SPI_2, 8}, - {PB7, SPI_2, 9}, - {PB8, SPI_2, 10}, - {PB9, SPI_2, 11}, - {PB10, SPI_2, 12}, - {PF8, SPI_2, 20}, - {PF9, SPI_2, 21}, - {PF10, SPI_2, 22}, - {PF11, SPI_2, 23}, - {PF12, SPI_2, 24}, - {PF13, SPI_2, 25}, - {PF14, SPI_2, 26}, - {PF15, SPI_2, 27}, - {PK0, SPI_2, 28}, - {PK1, SPI_2, 29}, - {PK2, SPI_2, 30}, - - /* USART3 */ - {PJ14, SPI_3, 15}, - {PJ15, SPI_3, 16}, - {PC0, SPI_3, 17}, - {PC1, SPI_3, 18}, - {PC2, SPI_3, 19}, - {PC3, SPI_3, 20}, - {PC4, SPI_3, 21}, - {PC5, SPI_3, 22}, - {NC , NC , NC} }; @@ -440,42 +305,6 @@ const PinMap PinMap_SPI_CLK[] = { {PA0, SPI_1, 30}, {PA1, SPI_1, 31}, - /* USART2 */ - {PA7, SPI_2, 0}, - {PA8, SPI_2, 1}, - {PA9, SPI_2, 2}, - {PI0, SPI_2, 3}, - {PI1, SPI_2, 4}, - {PI2, SPI_2, 5}, - {PI3, SPI_2, 6}, - {PB6, SPI_2, 7}, - {PB7, SPI_2, 8}, - {PB8, SPI_2, 9}, - {PB9, SPI_2, 10}, - {PB10, SPI_2, 11}, - {PF8, SPI_2, 19}, - {PF9, SPI_2, 20}, - {PF10, SPI_2, 21}, - {PF11, SPI_2, 22}, - {PF12, SPI_2, 23}, - {PF13, SPI_2, 24}, - {PF14, SPI_2, 25}, - {PF15, SPI_2, 26}, - {PK0, SPI_2, 27}, - {PK1, SPI_2, 28}, - {PK2, SPI_2, 29}, - {PA6, SPI_2, 31}, - - /* USART3 */ - {PJ14, SPI_3, 14}, - {PJ15, SPI_3, 15}, - {PC0, SPI_3, 16}, - {PC1, SPI_3, 17}, - {PC2, SPI_3, 18}, - {PC3, SPI_3, 19}, - {PC4, SPI_3, 20}, - {PC5, SPI_3, 21}, - {NC , NC , NC} }; @@ -517,42 +346,6 @@ const PinMap PinMap_SPI_CS[] = { {PF6, SPI_1, 27}, {PF7, SPI_1, 28}, - /* USART2 */ - {PA8, SPI_2, 0}, - {PA9, SPI_2, 1}, - {PI0, SPI_2, 2}, - {PI1, SPI_2, 3}, - {PI2, SPI_2, 4}, - {PI3, SPI_2, 5}, - {PB6, SPI_2, 6}, - {PB7, SPI_2, 7}, - {PB8, SPI_2, 8}, - {PB9, SPI_2, 9}, - {PB10, SPI_2, 10}, - {PF8, SPI_2, 18}, - {PF9, SPI_2, 19}, - {PF10, SPI_2, 20}, - {PF11, SPI_2, 21}, - {PF12, SPI_2, 22}, - {PF13, SPI_2, 23}, - {PF14, SPI_2, 24}, - {PF15, SPI_2, 25}, - {PK0, SPI_2, 26}, - {PK1, SPI_2, 27}, - {PK2, SPI_2, 28}, - {PA6, SPI_2, 30}, - {PA7, SPI_2, 31}, - - /* USART3 */ - {PJ14, SPI_3, 13}, - {PJ15, SPI_3, 14}, - {PC0, SPI_3, 15}, - {PC1, SPI_3, 16}, - {PC2, SPI_3, 17}, - {PC3, SPI_3, 18}, - {PC4, SPI_3, 19}, - {PC5, SPI_3, 20}, - {NC , NC , NC} }; @@ -592,42 +385,6 @@ const PinMap PinMap_UART_TX[] = { {PF6, USART_1, 30}, {PF7, USART_1, 31}, - /* USART2 */ - {PA6, USART_2, 1}, - {PA7, USART_2, 2}, - {PA8, USART_2, 3}, - {PA9, USART_2, 4}, - {PI0, USART_2, 5}, - {PI1, USART_2, 6}, - {PI2, USART_2, 7}, - {PI3, USART_2, 8}, - {PB6, USART_2, 9}, - {PB7, USART_2, 10}, - {PB8, USART_2, 11}, - {PB9, USART_2, 12}, - {PB10, USART_2, 13}, - {PF8, USART_2, 21}, - {PF9, USART_2, 22}, - {PF10, USART_2, 23}, - {PF11, USART_2, 24}, - {PF12, USART_2, 25}, - {PF13, USART_2, 26}, - {PF14, USART_2, 27}, - {PF15, USART_2, 28}, - {PK0, USART_2, 29}, - {PK1, USART_2, 30}, - {PK2, USART_2, 31}, - - /* USART3 */ - {PJ14, USART_3, 16}, - {PJ15, USART_3, 17}, - {PC0, USART_3, 18}, - {PC1, USART_3, 19}, - {PC2, USART_3, 20}, - {PC3, USART_3, 21}, - {PC4, USART_3, 22}, - {PC5, USART_3, 23}, - {NC , NC , NC} }; @@ -666,41 +423,5 @@ const PinMap PinMap_UART_RX[] = { {PF6, USART_1, 29}, {PF7, USART_1, 30}, - /* USART2 */ - {PA6, USART_2, 0}, - {PA7, USART_2, 1}, - {PA8, USART_2, 2}, - {PA9, USART_2, 3}, - {PI0, USART_2, 4}, - {PI1, USART_2, 5}, - {PI2, USART_2, 6}, - {PI3, USART_2, 7}, - {PB6, USART_2, 8}, - {PB7, USART_2, 9}, - {PB8, USART_2, 10}, - {PB9, USART_2, 11}, - {PB10, USART_2, 12}, - {PF8, USART_2, 20}, - {PF9, USART_2, 21}, - {PF10, USART_2, 22}, - {PF11, USART_2, 23}, - {PF12, USART_2, 24}, - {PF13, USART_2, 25}, - {PF14, USART_2, 26}, - {PF15, USART_2, 27}, - {PK0, USART_2, 28}, - {PK1, USART_2, 29}, - {PK2, USART_2, 30}, - - /* USART3 */ - {PJ14, USART_3, 15}, - {PJ15, USART_3, 16}, - {PC0, USART_3, 17}, - {PC1, USART_3, 18}, - {PC2, USART_3, 19}, - {PC3, USART_3, 20}, - {PC4, USART_3, 21}, - {PC5, USART_3, 22}, - {NC , NC , NC} }; diff --git a/targets/TARGET_Silicon_Labs/TARGET_EFM32/TARGET_EFM32PG12/TARGET_EFM32PG12_STK3402/PinNames.h b/targets/TARGET_Silicon_Labs/TARGET_EFM32/TARGET_EFM32PG12/TARGET_EFM32PG12_STK3402/PinNames.h index 7be38062b49..8840ceb9dbd 100644 --- a/targets/TARGET_Silicon_Labs/TARGET_EFM32/TARGET_EFM32PG12/TARGET_EFM32PG12_STK3402/PinNames.h +++ b/targets/TARGET_Silicon_Labs/TARGET_EFM32/TARGET_EFM32PG12/TARGET_EFM32PG12_STK3402/PinNames.h @@ -44,9 +44,6 @@ typedef enum { SW1 = PF7, BTN0 = SW0, BTN1 = SW1, - // Standardized button names - BUTTON1 = BTN0, - BUTTON2 = BTN1, /* Expansion headers */ EXP3 = PA8, diff --git a/targets/TARGET_Silicon_Labs/TARGET_EFM32/TARGET_EFM32WG/TARGET_EFM32WG_STK3800/PinNames.h b/targets/TARGET_Silicon_Labs/TARGET_EFM32/TARGET_EFM32WG/TARGET_EFM32WG_STK3800/PinNames.h index 45570ee6379..bf783f73885 100644 --- a/targets/TARGET_Silicon_Labs/TARGET_EFM32/TARGET_EFM32WG/TARGET_EFM32WG_STK3800/PinNames.h +++ b/targets/TARGET_Silicon_Labs/TARGET_EFM32/TARGET_EFM32WG/TARGET_EFM32WG_STK3800/PinNames.h @@ -44,9 +44,6 @@ typedef enum { SW1 = PB10, BTN0 = SW0, BTN1 = SW1, - // Standardized button names - BUTTON1 = BTN0, - BUTTON2 = BTN1, /* Serial */ SERIAL_TX = PD0, diff --git a/targets/TARGET_Silicon_Labs/TARGET_EFM32/TARGET_EFM32ZG/TARGET_EFM32ZG_STK3200/PinNames.h b/targets/TARGET_Silicon_Labs/TARGET_EFM32/TARGET_EFM32ZG/TARGET_EFM32ZG_STK3200/PinNames.h index 818ba27b257..898dc0888a0 100644 --- a/targets/TARGET_Silicon_Labs/TARGET_EFM32/TARGET_EFM32ZG/TARGET_EFM32ZG_STK3200/PinNames.h +++ b/targets/TARGET_Silicon_Labs/TARGET_EFM32/TARGET_EFM32ZG/TARGET_EFM32ZG_STK3200/PinNames.h @@ -44,9 +44,6 @@ typedef enum { SW1 = PC9, BTN0 = SW0, BTN1 = SW1, - // Standardized button names - BUTTON1 = BTN0, - BUTTON2 = BTN1, /* Serial */ SERIAL_TX = PD7, diff --git a/targets/TARGET_Silicon_Labs/TARGET_EFM32/TARGET_EFR32MG1/TARGET_EFR32MG1_BRD4150/PinNames.h b/targets/TARGET_Silicon_Labs/TARGET_EFM32/TARGET_EFR32MG1/TARGET_EFR32MG1_BRD4150/PinNames.h index 51832585007..4985448d14a 100644 --- a/targets/TARGET_Silicon_Labs/TARGET_EFM32/TARGET_EFR32MG1/TARGET_EFR32MG1_BRD4150/PinNames.h +++ b/targets/TARGET_Silicon_Labs/TARGET_EFM32/TARGET_EFR32MG1/TARGET_EFR32MG1_BRD4150/PinNames.h @@ -44,9 +44,6 @@ typedef enum { SW1 = PF7, BTN0 = SW0, BTN1 = SW1, - // Standardized button names - BUTTON1 = BTN0, - BUTTON2 = BTN1, /* Serial (just some usable pins) */ SERIAL_TX = PD10, diff --git a/targets/TARGET_Silicon_Labs/TARGET_EFM32/TARGET_EFR32MG1/TARGET_TB_SENSE_1/PinNames.h b/targets/TARGET_Silicon_Labs/TARGET_EFM32/TARGET_EFR32MG1/TARGET_TB_SENSE_1/PinNames.h index bf3b399c62d..03adb39ac6c 100644 --- a/targets/TARGET_Silicon_Labs/TARGET_EFM32/TARGET_EFR32MG1/TARGET_TB_SENSE_1/PinNames.h +++ b/targets/TARGET_Silicon_Labs/TARGET_EFM32/TARGET_EFR32MG1/TARGET_TB_SENSE_1/PinNames.h @@ -44,9 +44,6 @@ typedef enum { SW1 = PD15, BTN0 = SW0, BTN1 = SW1, - // Standardized button names - BUTTON1 = BTN0, - BUTTON2 = BTN1, /* Serial (just some usable pins) */ SERIAL_TX = PD10, diff --git a/targets/TARGET_Silicon_Labs/TARGET_EFM32/TARGET_EFR32MG12/PeripheralPins.c b/targets/TARGET_Silicon_Labs/TARGET_EFM32/TARGET_EFR32MG12/PeripheralPins.c index 79f7f1933ed..95baad0840a 100644 --- a/targets/TARGET_Silicon_Labs/TARGET_EFM32/TARGET_EFR32MG12/PeripheralPins.c +++ b/targets/TARGET_Silicon_Labs/TARGET_EFM32/TARGET_EFR32MG12/PeripheralPins.c @@ -100,37 +100,6 @@ const PinMap PinMap_I2C_SCL[] = { {PF7, I2C_0, 30}, {PA0, I2C_0, 31}, - {PA7, I2C_1, 0}, - {PA8, I2C_1, 1}, - {PA9, I2C_1, 2}, - {PI2, I2C_1, 3}, - {PI3, I2C_1, 4}, - {PB6, I2C_1, 5}, - {PB7, I2C_1, 6}, - {PB8, I2C_1, 7}, - {PB9, I2C_1, 8}, - {PB10, I2C_1, 9}, - {PJ14, I2C_1, 10}, - {PJ15, I2C_1, 11}, - {PC0, I2C_1, 12}, - {PC1, I2C_1, 13}, - {PC2, I2C_1, 14}, - {PC3, I2C_1, 15}, - {PC4, I2C_1, 16}, - {PC5, I2C_1, 17}, - {PF8, I2C_1, 20}, - {PF9, I2C_1, 21}, - {PF10, I2C_1, 22}, - {PF11, I2C_1, 23}, - {PF12, I2C_1, 24}, - {PF13, I2C_1, 25}, - {PF14, I2C_1, 26}, - {PF15, I2C_1, 27}, - {PK0, I2C_1, 28}, - {PK1, I2C_1, 29}, - {PK2, I2C_1, 30}, - {PA6, I2C_1, 31}, - {NC , NC , NC} }; @@ -170,39 +139,7 @@ const PinMap PinMap_I2C_SDA[] = { {PF6, I2C_0, 30}, {PF7, I2C_0, 31}, - {PA6, I2C_1, 0}, - {PA7, I2C_1, 1}, - {PA8, I2C_1, 2}, - {PA9, I2C_1, 3}, - {PI2, I2C_1, 4}, - {PI3, I2C_1, 5}, - {PB6, I2C_1, 6}, - {PB7, I2C_1, 7}, - {PB8, I2C_1, 8}, - {PB9, I2C_1, 9}, - {PB10, I2C_1, 10}, - {PJ14, I2C_1, 11}, - {PJ15, I2C_1, 12}, - {PC0, I2C_1, 13}, - {PC1, I2C_1, 14}, - {PC2, I2C_1, 15}, - {PC3, I2C_1, 16}, - {PC4, I2C_1, 17}, - {PC5, I2C_1, 18}, - {PF8, I2C_1, 21}, - {PF9, I2C_1, 22}, - {PF10, I2C_1, 23}, - {PF11, I2C_1, 24}, - {PF12, I2C_1, 25}, - {PF13, I2C_1, 26}, - {PF14, I2C_1, 27}, - {PF15, I2C_1, 28}, - {PK0, I2C_1, 29}, - {PK1, I2C_1, 30}, - {PK2, I2C_1, 31}, - /* Not connected */ - {NC , NC , NC} }; @@ -283,42 +220,6 @@ const PinMap PinMap_SPI_MOSI[] = { {PF6, SPI_1, 30}, {PF7, SPI_1, 31}, - /* USART2 */ - {PA6, SPI_2, 1}, - {PA7, SPI_2, 2}, - {PA8, SPI_2, 3}, - {PA9, SPI_2, 4}, - {PI0, SPI_2, 5}, - {PI1, SPI_2, 6}, - {PI2, SPI_2, 7}, - {PI3, SPI_2, 8}, - {PB6, SPI_2, 9}, - {PB7, SPI_2, 10}, - {PB8, SPI_2, 11}, - {PB9, SPI_2, 12}, - {PB10, SPI_2, 13}, - {PF8, SPI_2, 21}, - {PF9, SPI_2, 22}, - {PF10, SPI_2, 23}, - {PF11, SPI_2, 24}, - {PF12, SPI_2, 25}, - {PF13, SPI_2, 26}, - {PF14, SPI_2, 27}, - {PF15, SPI_2, 28}, - {PK0, SPI_2, 29}, - {PK1, SPI_2, 30}, - {PK2, SPI_2, 31}, - - /* USART3 */ - {PJ14, SPI_3, 16}, - {PJ15, SPI_3, 17}, - {PC0, SPI_3, 18}, - {PC1, SPI_3, 19}, - {PC2, SPI_3, 20}, - {PC3, SPI_3, 21}, - {PC4, SPI_3, 22}, - {PC5, SPI_3, 23}, - {NC , NC , NC} }; @@ -361,42 +262,6 @@ const PinMap PinMap_SPI_MISO[] = { {PF7, SPI_1, 30}, {PA0, SPI_1, 31}, - /* USART2 */ - {PA6, SPI_2, 0}, - {PA7, SPI_2, 1}, - {PA8, SPI_2, 2}, - {PA9, SPI_2, 3}, - {PI0, SPI_2, 4}, - {PI1, SPI_2, 5}, - {PI2, SPI_2, 6}, - {PI3, SPI_2, 7}, - {PB6, SPI_2, 8}, - {PB7, SPI_2, 9}, - {PB8, SPI_2, 10}, - {PB9, SPI_2, 11}, - {PB10, SPI_2, 12}, - {PF8, SPI_2, 20}, - {PF9, SPI_2, 21}, - {PF10, SPI_2, 22}, - {PF11, SPI_2, 23}, - {PF12, SPI_2, 24}, - {PF13, SPI_2, 25}, - {PF14, SPI_2, 26}, - {PF15, SPI_2, 27}, - {PK0, SPI_2, 28}, - {PK1, SPI_2, 29}, - {PK2, SPI_2, 30}, - - /* USART3 */ - {PJ14, SPI_3, 15}, - {PJ15, SPI_3, 16}, - {PC0, SPI_3, 17}, - {PC1, SPI_3, 18}, - {PC2, SPI_3, 19}, - {PC3, SPI_3, 20}, - {PC4, SPI_3, 21}, - {PC5, SPI_3, 22}, - {NC , NC , NC} }; @@ -440,42 +305,6 @@ const PinMap PinMap_SPI_CLK[] = { {PA0, SPI_1, 30}, {PA1, SPI_1, 31}, - /* USART2 */ - {PA7, SPI_2, 0}, - {PA8, SPI_2, 1}, - {PA9, SPI_2, 2}, - {PI0, SPI_2, 3}, - {PI1, SPI_2, 4}, - {PI2, SPI_2, 5}, - {PI3, SPI_2, 6}, - {PB6, SPI_2, 7}, - {PB7, SPI_2, 8}, - {PB8, SPI_2, 9}, - {PB9, SPI_2, 10}, - {PB10, SPI_2, 11}, - {PF8, SPI_2, 19}, - {PF9, SPI_2, 20}, - {PF10, SPI_2, 21}, - {PF11, SPI_2, 22}, - {PF12, SPI_2, 23}, - {PF13, SPI_2, 24}, - {PF14, SPI_2, 25}, - {PF15, SPI_2, 26}, - {PK0, SPI_2, 27}, - {PK1, SPI_2, 28}, - {PK2, SPI_2, 29}, - {PA6, SPI_2, 31}, - - /* USART3 */ - {PJ14, SPI_3, 14}, - {PJ15, SPI_3, 15}, - {PC0, SPI_3, 16}, - {PC1, SPI_3, 17}, - {PC2, SPI_3, 18}, - {PC3, SPI_3, 19}, - {PC4, SPI_3, 20}, - {PC5, SPI_3, 21}, - {NC , NC , NC} }; @@ -517,42 +346,6 @@ const PinMap PinMap_SPI_CS[] = { {PF6, SPI_1, 27}, {PF7, SPI_1, 28}, - /* USART2 */ - {PA8, SPI_2, 0}, - {PA9, SPI_2, 1}, - {PI0, SPI_2, 2}, - {PI1, SPI_2, 3}, - {PI2, SPI_2, 4}, - {PI3, SPI_2, 5}, - {PB6, SPI_2, 6}, - {PB7, SPI_2, 7}, - {PB8, SPI_2, 8}, - {PB9, SPI_2, 9}, - {PB10, SPI_2, 10}, - {PF8, SPI_2, 18}, - {PF9, SPI_2, 19}, - {PF10, SPI_2, 20}, - {PF11, SPI_2, 21}, - {PF12, SPI_2, 22}, - {PF13, SPI_2, 23}, - {PF14, SPI_2, 24}, - {PF15, SPI_2, 25}, - {PK0, SPI_2, 26}, - {PK1, SPI_2, 27}, - {PK2, SPI_2, 28}, - {PA6, SPI_2, 30}, - {PA7, SPI_2, 31}, - - /* USART3 */ - {PJ14, SPI_3, 13}, - {PJ15, SPI_3, 14}, - {PC0, SPI_3, 15}, - {PC1, SPI_3, 16}, - {PC2, SPI_3, 17}, - {PC3, SPI_3, 18}, - {PC4, SPI_3, 19}, - {PC5, SPI_3, 20}, - {NC , NC , NC} }; @@ -592,42 +385,6 @@ const PinMap PinMap_UART_TX[] = { {PF6, USART_1, 30}, {PF7, USART_1, 31}, - /* USART2 */ - {PA6, USART_2, 1}, - {PA7, USART_2, 2}, - {PA8, USART_2, 3}, - {PA9, USART_2, 4}, - {PI0, USART_2, 5}, - {PI1, USART_2, 6}, - {PI2, USART_2, 7}, - {PI3, USART_2, 8}, - {PB6, USART_2, 9}, - {PB7, USART_2, 10}, - {PB8, USART_2, 11}, - {PB9, USART_2, 12}, - {PB10, USART_2, 13}, - {PF8, USART_2, 21}, - {PF9, USART_2, 22}, - {PF10, USART_2, 23}, - {PF11, USART_2, 24}, - {PF12, USART_2, 25}, - {PF13, USART_2, 26}, - {PF14, USART_2, 27}, - {PF15, USART_2, 28}, - {PK0, USART_2, 29}, - {PK1, USART_2, 30}, - {PK2, USART_2, 31}, - - /* USART3 */ - {PJ14, USART_3, 16}, - {PJ15, USART_3, 17}, - {PC0, USART_3, 18}, - {PC1, USART_3, 19}, - {PC2, USART_3, 20}, - {PC3, USART_3, 21}, - {PC4, USART_3, 22}, - {PC5, USART_3, 23}, - {NC , NC , NC} }; @@ -666,41 +423,5 @@ const PinMap PinMap_UART_RX[] = { {PF6, USART_1, 29}, {PF7, USART_1, 30}, - /* USART2 */ - {PA6, USART_2, 0}, - {PA7, USART_2, 1}, - {PA8, USART_2, 2}, - {PA9, USART_2, 3}, - {PI0, USART_2, 4}, - {PI1, USART_2, 5}, - {PI2, USART_2, 6}, - {PI3, USART_2, 7}, - {PB6, USART_2, 8}, - {PB7, USART_2, 9}, - {PB8, USART_2, 10}, - {PB9, USART_2, 11}, - {PB10, USART_2, 12}, - {PF8, USART_2, 20}, - {PF9, USART_2, 21}, - {PF10, USART_2, 22}, - {PF11, USART_2, 23}, - {PF12, USART_2, 24}, - {PF13, USART_2, 25}, - {PF14, USART_2, 26}, - {PF15, USART_2, 27}, - {PK0, USART_2, 28}, - {PK1, USART_2, 29}, - {PK2, USART_2, 30}, - - /* USART3 */ - {PJ14, USART_3, 15}, - {PJ15, USART_3, 16}, - {PC0, USART_3, 17}, - {PC1, USART_3, 18}, - {PC2, USART_3, 19}, - {PC3, USART_3, 20}, - {PC4, USART_3, 21}, - {PC5, USART_3, 22}, - {NC , NC , NC} }; diff --git a/targets/TARGET_Silicon_Labs/TARGET_EFM32/TARGET_EFR32MG12/TARGET_TB_SENSE_12/PinNames.h b/targets/TARGET_Silicon_Labs/TARGET_EFM32/TARGET_EFR32MG12/TARGET_TB_SENSE_12/PinNames.h index d378fb8fe5d..a56373d4d9e 100644 --- a/targets/TARGET_Silicon_Labs/TARGET_EFM32/TARGET_EFR32MG12/TARGET_TB_SENSE_12/PinNames.h +++ b/targets/TARGET_Silicon_Labs/TARGET_EFM32/TARGET_EFR32MG12/TARGET_TB_SENSE_12/PinNames.h @@ -44,9 +44,6 @@ typedef enum { SW1 = PD15, BTN0 = SW0, BTN1 = SW1, - // Standardized button names - BUTTON1 = BTN0, - BUTTON2 = BTN1, /* Expansion headers */ EXP3 = PA8, diff --git a/targets/TARGET_Silicon_Labs/TARGET_EFM32/common/objects.h b/targets/TARGET_Silicon_Labs/TARGET_EFM32/common/objects.h index 596e178a0da..4a67f222432 100644 --- a/targets/TARGET_Silicon_Labs/TARGET_EFM32/common/objects.h +++ b/targets/TARGET_Silicon_Labs/TARGET_EFM32/common/objects.h @@ -59,7 +59,6 @@ struct dac_s { #if DEVICE_I2C struct i2c_s { I2C_TypeDef *i2c; - uint32_t location; #if DEVICE_I2C_ASYNCH uint32_t events; I2C_TransferSeq_TypeDef xfer; @@ -117,8 +116,7 @@ struct serial_s { #if DEVICE_SPI struct spi_s { USART_TypeDef *spi; - uint32_t location; - uint32_t route; + int location; uint8_t bits; uint8_t master; #if DEVICE_SPI_ASYNCH diff --git a/targets/TARGET_Silicon_Labs/TARGET_EFM32/i2c_api.c b/targets/TARGET_Silicon_Labs/TARGET_EFM32/i2c_api.c index 123925aca4b..7c8f50e200b 100644 --- a/targets/TARGET_Silicon_Labs/TARGET_EFM32/i2c_api.c +++ b/targets/TARGET_Silicon_Labs/TARGET_EFM32/i2c_api.c @@ -121,13 +121,11 @@ void i2c_init(i2c_t *obj, PinName sda, PinName scl) int loc = pinmap_merge(loc_sda, loc_scl); MBED_ASSERT(loc != NC); /* Set location */ - obj->i2c.location = I2C_ROUTE_SDAPEN | I2C_ROUTE_SCLPEN | (loc << _I2C_ROUTE_LOCATION_SHIFT); obj->i2c.i2c->ROUTE = I2C_ROUTE_SDAPEN | I2C_ROUTE_SCLPEN | (loc << _I2C_ROUTE_LOCATION_SHIFT); #else obj->i2c.i2c->ROUTEPEN = I2C_ROUTEPEN_SDAPEN | I2C_ROUTEPEN_SCLPEN; - obj->i2c.location = (pin_location(sda, PinMap_I2C_SDA) << _I2C_ROUTELOC0_SDALOC_SHIFT) | - (pin_location(scl, PinMap_I2C_SCL) << _I2C_ROUTELOC0_SCLLOC_SHIFT); - obj->i2c.i2c->ROUTELOC0 = obj->i2c.location; + obj->i2c.i2c->ROUTELOC0 = (pin_location(sda, PinMap_I2C_SDA) << _I2C_ROUTELOC0_SDALOC_SHIFT) | + (pin_location(scl, PinMap_I2C_SCL) << _I2C_ROUTELOC0_SCLLOC_SHIFT); #endif /* Set up the pins for I2C use */ @@ -217,13 +215,6 @@ int i2c_start(i2c_t *obj) { I2C_TypeDef *i2c = obj->i2c.i2c; - /* Restore pin configuration in case we changed I2C object */ -#ifdef I2C_ROUTE_SDAPEN - obj->i2c.i2c->ROUTE = obj->i2c.location; -#else - obj->i2c.i2c->ROUTELOC0 = obj->i2c.location; -#endif - /* Ensure buffers are empty */ i2c->CMD = I2C_CMD_CLEARPC | I2C_CMD_CLEARTX; if (i2c->IF & I2C_IF_RXDATAV) { @@ -419,6 +410,7 @@ int i2c_slave_read(i2c_t *obj, char *data, int length) data[count] = i2c_byte_read(obj, 0); } + return count; } @@ -467,12 +459,6 @@ void i2c_transfer_asynch(i2c_t *obj, const void *tx, size_t tx_length, void *rx, if((tx_length == 0) && (rx_length == 0)) return; // For now, we are assuming a solely interrupt-driven implementation. -#ifdef I2C_ROUTE_SDAPEN - obj->i2c.i2c->ROUTE = obj->i2c.location; -#else - obj->i2c.i2c->ROUTELOC0 = obj->i2c.location; -#endif - // Store transfer config obj->i2c.xfer.addr = address; diff --git a/targets/TARGET_Silicon_Labs/TARGET_EFM32/pwmout_api.c b/targets/TARGET_Silicon_Labs/TARGET_EFM32/pwmout_api.c index ac0f70d55e5..2bf2fb28f6f 100644 --- a/targets/TARGET_Silicon_Labs/TARGET_EFM32/pwmout_api.c +++ b/targets/TARGET_Silicon_Labs/TARGET_EFM32/pwmout_api.c @@ -131,7 +131,7 @@ bool pwmout_all_inactive(void) { return true; } #else - if (!(PWM_TIMER->ROUTE & (TIMER_ROUTE_CC0PEN | TIMER_ROUTE_CC1PEN | TIMER_ROUTE_CC2PEN))) { + if(PWM_TIMER->ROUTE & (TIMER_ROUTE_CC0PEN | TIMER_ROUTE_CC1PEN | TIMER_ROUTE_CC2PEN)) { return true; } #endif @@ -210,11 +210,10 @@ void pwmout_init(pwmout_t *obj, PinName pin) #else // On P1, the route location is statically defined for the entire timer. PWM_TIMER->ROUTE &= ~_TIMER_ROUTE_LOCATION_MASK; - // Make sure the route location is not overwritten - if(pwmout_all_inactive()) { +if(pwmout_all_inactive()) { PWM_TIMER->ROUTE |= pinmap_find_function(pin,PinMap_PWM) << _TIMER_ROUTE_LOCATION_SHIFT; } else { - MBED_ASSERT(PWM_TIMER->ROUTE & _TIMER_ROUTE_LOCATION_MASK == pinmap_find_function(pin,PinMap_PWM) << _TIMER_ROUTE_LOCATION_SHIFT); + MBED_ASSERT((pinmap_find_function(pin,PinMap_PWM) << _TIMER_ROUTE_LOCATION_SHIFT) == (PWM_TIMER->ROUTE & _TIMER_ROUTE_LOCATION_MASK)); } #endif diff --git a/targets/TARGET_Silicon_Labs/TARGET_EFM32/spi_api.c b/targets/TARGET_Silicon_Labs/TARGET_EFM32/spi_api.c index abb401247fc..ad387d86ae0 100644 --- a/targets/TARGET_Silicon_Labs/TARGET_EFM32/spi_api.c +++ b/targets/TARGET_Silicon_Labs/TARGET_EFM32/spi_api.c @@ -213,12 +213,10 @@ void spi_enable_pins(spi_t *obj, uint8_t enable, PinName mosi, PinName miso, Pin obj->spi.spi->ROUTELOC0 &= ~_USART_ROUTELOC0_CSLOC_MASK; obj->spi.spi->ROUTELOC0 |= pin_location(cs, PinMap_SPI_MOSI)<<_USART_ROUTELOC0_CSLOC_SHIFT; } - obj->spi.location = obj->spi.spi->ROUTELOC0; - obj->spi.route = route; obj->spi.spi->ROUTEPEN = route; } #else - uint32_t route = USART_ROUTE_CLKPEN; + uint32_t route = USART_ROUTE_CLKPEN | (obj->spi.location << _USART_ROUTE_LOCATION_SHIFT); if (mosi != NC) { route |= USART_ROUTE_TXPEN; @@ -229,9 +227,7 @@ void spi_enable_pins(spi_t *obj, uint8_t enable, PinName mosi, PinName miso, Pin if (!obj->spi.master) { route |= USART_ROUTE_CSPEN; } - route |= obj->spi.location << _USART_ROUTE_LOCATION_SHIFT; obj->spi.spi->ROUTE = route; - obj->spi.route = route; } #endif void spi_enable(spi_t *obj, uint8_t enable) @@ -328,6 +324,14 @@ void spi_format(spi_t *obj, int bits, int mode, int slave) default: clockMode = usartClockMode0; } + + //save state +#ifdef _USART_ROUTEPEN_RESETVALUE + uint32_t route = obj->spi.spi->ROUTEPEN; + uint32_t loc = obj->spi.spi->ROUTELOC0; +#else + uint32_t route = obj->spi.spi->ROUTE; +#endif uint32_t iflags = obj->spi.spi->IEN; bool enabled = (obj->spi.spi->STATUS & (USART_STATUS_RXENS | USART_STATUS_TXENS)) != 0; @@ -335,10 +339,10 @@ void spi_format(spi_t *obj, int bits, int mode, int slave) //restore state #ifdef _USART_ROUTEPEN_RESETVALUE - obj->spi.spi->ROUTEPEN = obj->spi.route; - obj->spi.spi->ROUTELOC0 = obj->spi.location; + obj->spi.spi->ROUTEPEN = route; + obj->spi.spi->ROUTELOC0 = loc; #else - obj->spi.spi->ROUTE = obj->spi.route; + obj->spi.spi->ROUTE = route; #endif obj->spi.spi->IEN = iflags; diff --git a/targets/TARGET_WIZNET/TARGET_W7500x/TARGET_WIZwiki_W7500/device/TOOLCHAIN_GCC_ARM/startup_W7500.S b/targets/TARGET_WIZNET/TARGET_W7500x/TARGET_WIZwiki_W7500/device/TOOLCHAIN_GCC_ARM/startup_W7500.S index 48966901cbc..2808b2ad576 100644 --- a/targets/TARGET_WIZNET/TARGET_W7500x/TARGET_WIZwiki_W7500/device/TOOLCHAIN_GCC_ARM/startup_W7500.S +++ b/targets/TARGET_WIZNET/TARGET_W7500x/TARGET_WIZwiki_W7500/device/TOOLCHAIN_GCC_ARM/startup_W7500.S @@ -188,8 +188,8 @@ Reset_Handler: .LC3: #endif /* __STARTUP_CLEAR_BSS */ - bl _start - //bl main + /*bl _start*/ + bl main .pool .size Reset_Handler, . - Reset_Handler diff --git a/targets/TARGET_WIZNET/TARGET_W7500x/TARGET_WIZwiki_W7500/device/TOOLCHAIN_IAR/W7500_Flash.icf b/targets/TARGET_WIZNET/TARGET_W7500x/TARGET_WIZwiki_W7500/device/TOOLCHAIN_IAR/W7500_Flash.icf deleted file mode 100644 index dd71139d172..00000000000 --- a/targets/TARGET_WIZNET/TARGET_W7500x/TARGET_WIZwiki_W7500/device/TOOLCHAIN_IAR/W7500_Flash.icf +++ /dev/null @@ -1,31 +0,0 @@ -/*###ICF### Section handled by ICF editor, don't touch! ****/ -/*-Editor annotation file-*/ -/* IcfEditorFile="$TOOLKIT_DIR$\config\ide\IcfEditor\cortex_v1_0.xml" */ -/*-Specials-*/ -define symbol __ICFEDIT_intvec_start__ = 0x00000000; -/*-Memory Regions-*/ -define symbol __ICFEDIT_region_ROM_start__ = 0x00000000; -define symbol __ICFEDIT_region_ROM_end__ = 0x00020000; -define symbol __ICFEDIT_region_RAM_start__ = 0x20000000; -define symbol __ICFEDIT_region_RAM_end__ = 0x20004000; -/*-Sizes-*/ -define symbol __ICFEDIT_size_cstack__ = 0x00000400; -define symbol __ICFEDIT_size_heap__ = 0x00000400; -/**** End of ICF editor section. ###ICF###*/ - - -define memory mem with size = 4G; -define region ROM_region = mem:[from __ICFEDIT_region_ROM_start__ to __ICFEDIT_region_ROM_end__]; -define region RAM_region = mem:[from __ICFEDIT_region_RAM_start__ to __ICFEDIT_region_RAM_end__]; - -define block CSTACK with alignment = 8, size = __ICFEDIT_size_cstack__ { }; -define block HEAP with alignment = 8, size = __ICFEDIT_size_heap__ { }; - -initialize by copy { readwrite }; -do not initialize { section .noinit }; - -place at address mem:__ICFEDIT_intvec_start__ { readonly section .intvec }; - -place in ROM_region { readonly }; -place in RAM_region { readwrite, - block CSTACK, block HEAP }; \ No newline at end of file diff --git a/targets/TARGET_WIZNET/TARGET_W7500x/TARGET_WIZwiki_W7500/device/TOOLCHAIN_IAR/startup_W7500.s b/targets/TARGET_WIZNET/TARGET_W7500x/TARGET_WIZwiki_W7500/device/TOOLCHAIN_IAR/startup_W7500.s deleted file mode 100644 index 1b28c47f624..00000000000 --- a/targets/TARGET_WIZNET/TARGET_W7500x/TARGET_WIZwiki_W7500/device/TOOLCHAIN_IAR/startup_W7500.s +++ /dev/null @@ -1,305 +0,0 @@ -;/******************************************************************************************************************************************************* -; * Copyright �� 2016 -; * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ��Software��), -; * to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, -; * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: -; * -; * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. -; -; * THE SOFTWARE IS PROVIDED ��AS IS��, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -; * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -; * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -; * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -;*********************************************************************************************************************************************************/ -;/**************************************************************************//** -; * @file startup_ARMCM0.s -; * @brief CMSIS Core Device Startup File for -; * ARMCM0 Device Series -; * @version V1.08 -; * @date 23. November 2012 -; * -; * @note -; * -; ******************************************************************************/ -;/* Copyright (c) 2011 - 2012 ARM LIMITED -; -; All rights reserved. -; Redistribution and use in source and binary forms, with or without -; modification, are permitted provided that the following conditions are met: -; - Redistributions of source code must retain the above copyright -; notice, this list of conditions and the following disclaimer. -; - Redistributions in binary form must reproduce the above copyright -; notice, this list of conditions and the following disclaimer in the -; documentation and/or other materials provided with the distribution. -; - Neither the name of ARM nor the names of its contributors may be used -; to endorse or promote products derived from this software without -; specific prior written permission. -; * -; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -; ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE -; LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -; SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -; CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -; ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -; POSSIBILITY OF SUCH DAMAGE. -; ---------------------------------------------------------------------------*/ - - -; -; The modules in this file are included in the libraries, and may be replaced -; by any user-defined modules that define the PUBLIC symbol _program_start or -; a user defined start symbol. -; To override the cstartup defined in the library, simply add your modified -; version to the workbench project. -; -; The vector table is normally located at address 0. -; When debugging in RAM, it can be located in RAM, aligned to at least 2^6. -; The name "__vector_table" has special meaning for C-SPY: -; it is where the SP start value is found, and the NVIC vector -; table register (VTOR) is initialized to this address if != 0. -; -; Cortex-M version -; - - MODULE ?cstartup - - ;; Forward declaration of sections. - SECTION CSTACK:DATA:NOROOT(3) - - SECTION .intvec:CODE:NOROOT(2) - - EXTERN __iar_program_start - EXTERN SystemInit - PUBLIC __vector_table - PUBLIC __vector_table_0x1c - PUBLIC __Vectors - PUBLIC __Vectors_End - PUBLIC __Vectors_Size - - DATA - -__vector_table - DCD sfe(CSTACK) - DCD Reset_Handler ; Reset Handler - DCD NMI_Handler ; NMI Handler - DCD HardFault_Handler ; Hard Fault Handler - DCD 0 ; Reserved - DCD 0 ; Reserved - DCD 0 ; Reserved -__vector_table_0x1c - DCD 0 ; Reserved - DCD 0 ; Reserved - DCD 0 ; Reserved - DCD 0 ; Reserved - DCD SVC_Handler ; SVCall Handler - DCD 0 ; Reserved - DCD 0 ; Reserved - DCD PendSV_Handler ; PendSV Handler - DCD SysTick_Handler ; SysTick Handler - - ; Exterval Interrupts - DCD SSP0_Handler ; 16+ 0: SSP 0 Handler - DCD SSP1_Handler ; 16+ 1: SSP 1 Handler - DCD UART0_Handler ; 16+ 2: UART 0 Handler - DCD UART1_Handler ; 16+ 3: UART 1 Handler - DCD UART2_Handler ; 16+ 4: UART 2 Handler - DCD I2C0_Handler ; 16+ 5: I2C 0 Handler - DCD I2C1_Handler ; 16+ 6: I2C 1 Handler - DCD PORT0_Handler ; 16+ 7: GPIO Port 0 Combined Handler - DCD PORT1_Handler ; 16+ 8: GPIO Port 1 Combined Handler - DCD PORT2_Handler ; 16+ 9: GPIO Port 2 Combined Handler - DCD PORT3_Handler ; 16+10: GPIO Port 3 Combined Handler - DCD DMA_Handler ; 16+11: DMA Combined Handler - DCD DUALTIMER0_Handler ; 16+12: Dual timer 0 handler - DCD DUALTIMER1_Handler ; 16+13: Dual timer 1 handler - DCD PWM0_Handler ; 16+14: PWM0 Handler - DCD PWM1_Handler ; 16+15: PWM1 Handler - DCD PWM2_Handler ; 16+16: PWM2 Handler - DCD PWM3_Handler ; 16+17: PWM3 Handler - DCD PWM4_Handler ; 16+18: PWM4 Handler - DCD PWM5_Handler ; 16+19: PWM5 Handler - DCD PWM6_Handler ; 16+20: PWM6 Handler - DCD PWM7_Handler ; 16+21: PWM7 Handler - DCD RTC_Handler ; 16+22: RTC Handler - DCD ADC_Handler ; 16+23: ADC Handler - DCD WZTOE_Handler ; 16+24: WZTOE_Handler - DCD EXTI_Handler ; 16+25: EXTI_Handler -__Vectors_End - -__Vectors EQU __vector_table -__Vectors_Size EQU __Vectors_End - __Vectors - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; -;; Default interrupt handlers. -;; - THUMB - - PUBWEAK Reset_Handler - SECTION .text:CODE:REORDER:NOROOT(2) -Reset_Handler - LDR R0, =SystemInit - BLX R0 - LDR R0, =__iar_program_start - BX R0 - - PUBWEAK NMI_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -NMI_Handler - B NMI_Handler - - PUBWEAK HardFault_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -HardFault_Handler - B HardFault_Handler - - PUBWEAK SVC_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -SVC_Handler - B SVC_Handler - - PUBWEAK PendSV_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -PendSV_Handler - B PendSV_Handler - - PUBWEAK SysTick_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -SysTick_Handler - B SysTick_Handler - - PUBWEAK SSP0_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -SSP0_Handler - B SSP0_Handler - - PUBWEAK SSP1_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -SSP1_Handler - B SSP1_Handler - - PUBWEAK UART0_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -UART0_Handler - B UART0_Handler - - PUBWEAK UART1_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -UART1_Handler - B UART1_Handler - - PUBWEAK UART2_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -UART2_Handler - B UART2_Handler - - PUBWEAK I2C0_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -I2C0_Handler - B I2C0_Handler - - PUBWEAK I2C1_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -I2C1_Handler - B I2C1_Handler - - PUBWEAK PORT0_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -PORT0_Handler - B PORT0_Handler - - PUBWEAK PORT1_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -PORT1_Handler - B PORT1_Handler - - PUBWEAK PORT2_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -PORT2_Handler - B PORT2_Handler - - PUBWEAK PORT3_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -PORT3_Handler - B PORT3_Handler - - PUBWEAK DMA_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -DMA_Handler - B DMA_Handler - - PUBWEAK DUALTIMER0_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -DUALTIMER0_Handler - B DUALTIMER0_Handler - - PUBWEAK DUALTIMER1_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -DUALTIMER1_Handler - B DUALTIMER1_Handler - - PUBWEAK PWM0_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -PWM0_Handler - B PWM0_Handler - - PUBWEAK PWM1_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -PWM1_Handler - B PWM1_Handler - - PUBWEAK PWM2_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -PWM2_Handler - B PWM2_Handler - - PUBWEAK PWM3_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -PWM3_Handler - B PWM3_Handler - - PUBWEAK PWM4_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -PWM4_Handler - B PWM4_Handler - - PUBWEAK PWM5_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -PWM5_Handler - B PWM5_Handler - - PUBWEAK PWM6_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -PWM6_Handler - B PWM6_Handler - - PUBWEAK PWM7_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -PWM7_Handler - B PWM7_Handler - - PUBWEAK RTC_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -RTC_Handler - B RTC_Handler - - PUBWEAK ADC_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -ADC_Handler - B ADC_Handler - - PUBWEAK WZTOE_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -WZTOE_Handler - B WZTOE_Handler - - PUBWEAK EXTI_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -EXTI_Handler - B EXTI_Handler - - END diff --git a/targets/TARGET_WIZNET/TARGET_W7500x/TARGET_WIZwiki_W7500ECO/device/TOOLCHAIN_GCC_ARM/startup_W7500.S b/targets/TARGET_WIZNET/TARGET_W7500x/TARGET_WIZwiki_W7500ECO/device/TOOLCHAIN_GCC_ARM/startup_W7500.S index 48966901cbc..2808b2ad576 100644 --- a/targets/TARGET_WIZNET/TARGET_W7500x/TARGET_WIZwiki_W7500ECO/device/TOOLCHAIN_GCC_ARM/startup_W7500.S +++ b/targets/TARGET_WIZNET/TARGET_W7500x/TARGET_WIZwiki_W7500ECO/device/TOOLCHAIN_GCC_ARM/startup_W7500.S @@ -188,8 +188,8 @@ Reset_Handler: .LC3: #endif /* __STARTUP_CLEAR_BSS */ - bl _start - //bl main + /*bl _start*/ + bl main .pool .size Reset_Handler, . - Reset_Handler diff --git a/targets/TARGET_WIZNET/TARGET_W7500x/TARGET_WIZwiki_W7500ECO/device/TOOLCHAIN_GCC_ARM/startup_W7500.o b/targets/TARGET_WIZNET/TARGET_W7500x/TARGET_WIZwiki_W7500ECO/device/TOOLCHAIN_GCC_ARM/startup_W7500.o new file mode 100644 index 00000000000..61549404812 Binary files /dev/null and b/targets/TARGET_WIZNET/TARGET_W7500x/TARGET_WIZwiki_W7500ECO/device/TOOLCHAIN_GCC_ARM/startup_W7500.o differ diff --git a/targets/TARGET_WIZNET/TARGET_W7500x/TARGET_WIZwiki_W7500ECO/device/TOOLCHAIN_IAR/W7500_Flash.icf b/targets/TARGET_WIZNET/TARGET_W7500x/TARGET_WIZwiki_W7500ECO/device/TOOLCHAIN_IAR/W7500_Flash.icf deleted file mode 100644 index dd71139d172..00000000000 --- a/targets/TARGET_WIZNET/TARGET_W7500x/TARGET_WIZwiki_W7500ECO/device/TOOLCHAIN_IAR/W7500_Flash.icf +++ /dev/null @@ -1,31 +0,0 @@ -/*###ICF### Section handled by ICF editor, don't touch! ****/ -/*-Editor annotation file-*/ -/* IcfEditorFile="$TOOLKIT_DIR$\config\ide\IcfEditor\cortex_v1_0.xml" */ -/*-Specials-*/ -define symbol __ICFEDIT_intvec_start__ = 0x00000000; -/*-Memory Regions-*/ -define symbol __ICFEDIT_region_ROM_start__ = 0x00000000; -define symbol __ICFEDIT_region_ROM_end__ = 0x00020000; -define symbol __ICFEDIT_region_RAM_start__ = 0x20000000; -define symbol __ICFEDIT_region_RAM_end__ = 0x20004000; -/*-Sizes-*/ -define symbol __ICFEDIT_size_cstack__ = 0x00000400; -define symbol __ICFEDIT_size_heap__ = 0x00000400; -/**** End of ICF editor section. ###ICF###*/ - - -define memory mem with size = 4G; -define region ROM_region = mem:[from __ICFEDIT_region_ROM_start__ to __ICFEDIT_region_ROM_end__]; -define region RAM_region = mem:[from __ICFEDIT_region_RAM_start__ to __ICFEDIT_region_RAM_end__]; - -define block CSTACK with alignment = 8, size = __ICFEDIT_size_cstack__ { }; -define block HEAP with alignment = 8, size = __ICFEDIT_size_heap__ { }; - -initialize by copy { readwrite }; -do not initialize { section .noinit }; - -place at address mem:__ICFEDIT_intvec_start__ { readonly section .intvec }; - -place in ROM_region { readonly }; -place in RAM_region { readwrite, - block CSTACK, block HEAP }; \ No newline at end of file diff --git a/targets/TARGET_WIZNET/TARGET_W7500x/TARGET_WIZwiki_W7500ECO/device/TOOLCHAIN_IAR/startup_W7500.s b/targets/TARGET_WIZNET/TARGET_W7500x/TARGET_WIZwiki_W7500ECO/device/TOOLCHAIN_IAR/startup_W7500.s deleted file mode 100644 index 1b28c47f624..00000000000 --- a/targets/TARGET_WIZNET/TARGET_W7500x/TARGET_WIZwiki_W7500ECO/device/TOOLCHAIN_IAR/startup_W7500.s +++ /dev/null @@ -1,305 +0,0 @@ -;/******************************************************************************************************************************************************* -; * Copyright �� 2016 -; * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ��Software��), -; * to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, -; * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: -; * -; * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. -; -; * THE SOFTWARE IS PROVIDED ��AS IS��, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -; * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -; * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -; * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -;*********************************************************************************************************************************************************/ -;/**************************************************************************//** -; * @file startup_ARMCM0.s -; * @brief CMSIS Core Device Startup File for -; * ARMCM0 Device Series -; * @version V1.08 -; * @date 23. November 2012 -; * -; * @note -; * -; ******************************************************************************/ -;/* Copyright (c) 2011 - 2012 ARM LIMITED -; -; All rights reserved. -; Redistribution and use in source and binary forms, with or without -; modification, are permitted provided that the following conditions are met: -; - Redistributions of source code must retain the above copyright -; notice, this list of conditions and the following disclaimer. -; - Redistributions in binary form must reproduce the above copyright -; notice, this list of conditions and the following disclaimer in the -; documentation and/or other materials provided with the distribution. -; - Neither the name of ARM nor the names of its contributors may be used -; to endorse or promote products derived from this software without -; specific prior written permission. -; * -; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -; ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE -; LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -; SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -; CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -; ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -; POSSIBILITY OF SUCH DAMAGE. -; ---------------------------------------------------------------------------*/ - - -; -; The modules in this file are included in the libraries, and may be replaced -; by any user-defined modules that define the PUBLIC symbol _program_start or -; a user defined start symbol. -; To override the cstartup defined in the library, simply add your modified -; version to the workbench project. -; -; The vector table is normally located at address 0. -; When debugging in RAM, it can be located in RAM, aligned to at least 2^6. -; The name "__vector_table" has special meaning for C-SPY: -; it is where the SP start value is found, and the NVIC vector -; table register (VTOR) is initialized to this address if != 0. -; -; Cortex-M version -; - - MODULE ?cstartup - - ;; Forward declaration of sections. - SECTION CSTACK:DATA:NOROOT(3) - - SECTION .intvec:CODE:NOROOT(2) - - EXTERN __iar_program_start - EXTERN SystemInit - PUBLIC __vector_table - PUBLIC __vector_table_0x1c - PUBLIC __Vectors - PUBLIC __Vectors_End - PUBLIC __Vectors_Size - - DATA - -__vector_table - DCD sfe(CSTACK) - DCD Reset_Handler ; Reset Handler - DCD NMI_Handler ; NMI Handler - DCD HardFault_Handler ; Hard Fault Handler - DCD 0 ; Reserved - DCD 0 ; Reserved - DCD 0 ; Reserved -__vector_table_0x1c - DCD 0 ; Reserved - DCD 0 ; Reserved - DCD 0 ; Reserved - DCD 0 ; Reserved - DCD SVC_Handler ; SVCall Handler - DCD 0 ; Reserved - DCD 0 ; Reserved - DCD PendSV_Handler ; PendSV Handler - DCD SysTick_Handler ; SysTick Handler - - ; Exterval Interrupts - DCD SSP0_Handler ; 16+ 0: SSP 0 Handler - DCD SSP1_Handler ; 16+ 1: SSP 1 Handler - DCD UART0_Handler ; 16+ 2: UART 0 Handler - DCD UART1_Handler ; 16+ 3: UART 1 Handler - DCD UART2_Handler ; 16+ 4: UART 2 Handler - DCD I2C0_Handler ; 16+ 5: I2C 0 Handler - DCD I2C1_Handler ; 16+ 6: I2C 1 Handler - DCD PORT0_Handler ; 16+ 7: GPIO Port 0 Combined Handler - DCD PORT1_Handler ; 16+ 8: GPIO Port 1 Combined Handler - DCD PORT2_Handler ; 16+ 9: GPIO Port 2 Combined Handler - DCD PORT3_Handler ; 16+10: GPIO Port 3 Combined Handler - DCD DMA_Handler ; 16+11: DMA Combined Handler - DCD DUALTIMER0_Handler ; 16+12: Dual timer 0 handler - DCD DUALTIMER1_Handler ; 16+13: Dual timer 1 handler - DCD PWM0_Handler ; 16+14: PWM0 Handler - DCD PWM1_Handler ; 16+15: PWM1 Handler - DCD PWM2_Handler ; 16+16: PWM2 Handler - DCD PWM3_Handler ; 16+17: PWM3 Handler - DCD PWM4_Handler ; 16+18: PWM4 Handler - DCD PWM5_Handler ; 16+19: PWM5 Handler - DCD PWM6_Handler ; 16+20: PWM6 Handler - DCD PWM7_Handler ; 16+21: PWM7 Handler - DCD RTC_Handler ; 16+22: RTC Handler - DCD ADC_Handler ; 16+23: ADC Handler - DCD WZTOE_Handler ; 16+24: WZTOE_Handler - DCD EXTI_Handler ; 16+25: EXTI_Handler -__Vectors_End - -__Vectors EQU __vector_table -__Vectors_Size EQU __Vectors_End - __Vectors - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; -;; Default interrupt handlers. -;; - THUMB - - PUBWEAK Reset_Handler - SECTION .text:CODE:REORDER:NOROOT(2) -Reset_Handler - LDR R0, =SystemInit - BLX R0 - LDR R0, =__iar_program_start - BX R0 - - PUBWEAK NMI_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -NMI_Handler - B NMI_Handler - - PUBWEAK HardFault_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -HardFault_Handler - B HardFault_Handler - - PUBWEAK SVC_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -SVC_Handler - B SVC_Handler - - PUBWEAK PendSV_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -PendSV_Handler - B PendSV_Handler - - PUBWEAK SysTick_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -SysTick_Handler - B SysTick_Handler - - PUBWEAK SSP0_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -SSP0_Handler - B SSP0_Handler - - PUBWEAK SSP1_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -SSP1_Handler - B SSP1_Handler - - PUBWEAK UART0_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -UART0_Handler - B UART0_Handler - - PUBWEAK UART1_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -UART1_Handler - B UART1_Handler - - PUBWEAK UART2_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -UART2_Handler - B UART2_Handler - - PUBWEAK I2C0_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -I2C0_Handler - B I2C0_Handler - - PUBWEAK I2C1_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -I2C1_Handler - B I2C1_Handler - - PUBWEAK PORT0_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -PORT0_Handler - B PORT0_Handler - - PUBWEAK PORT1_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -PORT1_Handler - B PORT1_Handler - - PUBWEAK PORT2_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -PORT2_Handler - B PORT2_Handler - - PUBWEAK PORT3_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -PORT3_Handler - B PORT3_Handler - - PUBWEAK DMA_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -DMA_Handler - B DMA_Handler - - PUBWEAK DUALTIMER0_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -DUALTIMER0_Handler - B DUALTIMER0_Handler - - PUBWEAK DUALTIMER1_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -DUALTIMER1_Handler - B DUALTIMER1_Handler - - PUBWEAK PWM0_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -PWM0_Handler - B PWM0_Handler - - PUBWEAK PWM1_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -PWM1_Handler - B PWM1_Handler - - PUBWEAK PWM2_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -PWM2_Handler - B PWM2_Handler - - PUBWEAK PWM3_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -PWM3_Handler - B PWM3_Handler - - PUBWEAK PWM4_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -PWM4_Handler - B PWM4_Handler - - PUBWEAK PWM5_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -PWM5_Handler - B PWM5_Handler - - PUBWEAK PWM6_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -PWM6_Handler - B PWM6_Handler - - PUBWEAK PWM7_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -PWM7_Handler - B PWM7_Handler - - PUBWEAK RTC_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -RTC_Handler - B RTC_Handler - - PUBWEAK ADC_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -ADC_Handler - B ADC_Handler - - PUBWEAK WZTOE_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -WZTOE_Handler - B WZTOE_Handler - - PUBWEAK EXTI_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -EXTI_Handler - B EXTI_Handler - - END diff --git a/targets/TARGET_WIZNET/TARGET_W7500x/TARGET_WIZwiki_W7500P/device/TOOLCHAIN_GCC_ARM/startup_W7500.S b/targets/TARGET_WIZNET/TARGET_W7500x/TARGET_WIZwiki_W7500P/device/TOOLCHAIN_GCC_ARM/startup_W7500.S index 48966901cbc..2808b2ad576 100644 --- a/targets/TARGET_WIZNET/TARGET_W7500x/TARGET_WIZwiki_W7500P/device/TOOLCHAIN_GCC_ARM/startup_W7500.S +++ b/targets/TARGET_WIZNET/TARGET_W7500x/TARGET_WIZwiki_W7500P/device/TOOLCHAIN_GCC_ARM/startup_W7500.S @@ -188,8 +188,8 @@ Reset_Handler: .LC3: #endif /* __STARTUP_CLEAR_BSS */ - bl _start - //bl main + /*bl _start*/ + bl main .pool .size Reset_Handler, . - Reset_Handler diff --git a/targets/TARGET_WIZNET/TARGET_W7500x/TARGET_WIZwiki_W7500P/device/TOOLCHAIN_IAR/W7500_Flash.icf b/targets/TARGET_WIZNET/TARGET_W7500x/TARGET_WIZwiki_W7500P/device/TOOLCHAIN_IAR/W7500_Flash.icf deleted file mode 100644 index dd71139d172..00000000000 --- a/targets/TARGET_WIZNET/TARGET_W7500x/TARGET_WIZwiki_W7500P/device/TOOLCHAIN_IAR/W7500_Flash.icf +++ /dev/null @@ -1,31 +0,0 @@ -/*###ICF### Section handled by ICF editor, don't touch! ****/ -/*-Editor annotation file-*/ -/* IcfEditorFile="$TOOLKIT_DIR$\config\ide\IcfEditor\cortex_v1_0.xml" */ -/*-Specials-*/ -define symbol __ICFEDIT_intvec_start__ = 0x00000000; -/*-Memory Regions-*/ -define symbol __ICFEDIT_region_ROM_start__ = 0x00000000; -define symbol __ICFEDIT_region_ROM_end__ = 0x00020000; -define symbol __ICFEDIT_region_RAM_start__ = 0x20000000; -define symbol __ICFEDIT_region_RAM_end__ = 0x20004000; -/*-Sizes-*/ -define symbol __ICFEDIT_size_cstack__ = 0x00000400; -define symbol __ICFEDIT_size_heap__ = 0x00000400; -/**** End of ICF editor section. ###ICF###*/ - - -define memory mem with size = 4G; -define region ROM_region = mem:[from __ICFEDIT_region_ROM_start__ to __ICFEDIT_region_ROM_end__]; -define region RAM_region = mem:[from __ICFEDIT_region_RAM_start__ to __ICFEDIT_region_RAM_end__]; - -define block CSTACK with alignment = 8, size = __ICFEDIT_size_cstack__ { }; -define block HEAP with alignment = 8, size = __ICFEDIT_size_heap__ { }; - -initialize by copy { readwrite }; -do not initialize { section .noinit }; - -place at address mem:__ICFEDIT_intvec_start__ { readonly section .intvec }; - -place in ROM_region { readonly }; -place in RAM_region { readwrite, - block CSTACK, block HEAP }; \ No newline at end of file diff --git a/targets/TARGET_WIZNET/TARGET_W7500x/TARGET_WIZwiki_W7500P/device/TOOLCHAIN_IAR/startup_W7500.s b/targets/TARGET_WIZNET/TARGET_W7500x/TARGET_WIZwiki_W7500P/device/TOOLCHAIN_IAR/startup_W7500.s deleted file mode 100644 index 1b28c47f624..00000000000 --- a/targets/TARGET_WIZNET/TARGET_W7500x/TARGET_WIZwiki_W7500P/device/TOOLCHAIN_IAR/startup_W7500.s +++ /dev/null @@ -1,305 +0,0 @@ -;/******************************************************************************************************************************************************* -; * Copyright �� 2016 -; * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ��Software��), -; * to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, -; * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: -; * -; * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. -; -; * THE SOFTWARE IS PROVIDED ��AS IS��, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -; * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -; * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -; * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -;*********************************************************************************************************************************************************/ -;/**************************************************************************//** -; * @file startup_ARMCM0.s -; * @brief CMSIS Core Device Startup File for -; * ARMCM0 Device Series -; * @version V1.08 -; * @date 23. November 2012 -; * -; * @note -; * -; ******************************************************************************/ -;/* Copyright (c) 2011 - 2012 ARM LIMITED -; -; All rights reserved. -; Redistribution and use in source and binary forms, with or without -; modification, are permitted provided that the following conditions are met: -; - Redistributions of source code must retain the above copyright -; notice, this list of conditions and the following disclaimer. -; - Redistributions in binary form must reproduce the above copyright -; notice, this list of conditions and the following disclaimer in the -; documentation and/or other materials provided with the distribution. -; - Neither the name of ARM nor the names of its contributors may be used -; to endorse or promote products derived from this software without -; specific prior written permission. -; * -; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -; ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE -; LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -; SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -; CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -; ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -; POSSIBILITY OF SUCH DAMAGE. -; ---------------------------------------------------------------------------*/ - - -; -; The modules in this file are included in the libraries, and may be replaced -; by any user-defined modules that define the PUBLIC symbol _program_start or -; a user defined start symbol. -; To override the cstartup defined in the library, simply add your modified -; version to the workbench project. -; -; The vector table is normally located at address 0. -; When debugging in RAM, it can be located in RAM, aligned to at least 2^6. -; The name "__vector_table" has special meaning for C-SPY: -; it is where the SP start value is found, and the NVIC vector -; table register (VTOR) is initialized to this address if != 0. -; -; Cortex-M version -; - - MODULE ?cstartup - - ;; Forward declaration of sections. - SECTION CSTACK:DATA:NOROOT(3) - - SECTION .intvec:CODE:NOROOT(2) - - EXTERN __iar_program_start - EXTERN SystemInit - PUBLIC __vector_table - PUBLIC __vector_table_0x1c - PUBLIC __Vectors - PUBLIC __Vectors_End - PUBLIC __Vectors_Size - - DATA - -__vector_table - DCD sfe(CSTACK) - DCD Reset_Handler ; Reset Handler - DCD NMI_Handler ; NMI Handler - DCD HardFault_Handler ; Hard Fault Handler - DCD 0 ; Reserved - DCD 0 ; Reserved - DCD 0 ; Reserved -__vector_table_0x1c - DCD 0 ; Reserved - DCD 0 ; Reserved - DCD 0 ; Reserved - DCD 0 ; Reserved - DCD SVC_Handler ; SVCall Handler - DCD 0 ; Reserved - DCD 0 ; Reserved - DCD PendSV_Handler ; PendSV Handler - DCD SysTick_Handler ; SysTick Handler - - ; Exterval Interrupts - DCD SSP0_Handler ; 16+ 0: SSP 0 Handler - DCD SSP1_Handler ; 16+ 1: SSP 1 Handler - DCD UART0_Handler ; 16+ 2: UART 0 Handler - DCD UART1_Handler ; 16+ 3: UART 1 Handler - DCD UART2_Handler ; 16+ 4: UART 2 Handler - DCD I2C0_Handler ; 16+ 5: I2C 0 Handler - DCD I2C1_Handler ; 16+ 6: I2C 1 Handler - DCD PORT0_Handler ; 16+ 7: GPIO Port 0 Combined Handler - DCD PORT1_Handler ; 16+ 8: GPIO Port 1 Combined Handler - DCD PORT2_Handler ; 16+ 9: GPIO Port 2 Combined Handler - DCD PORT3_Handler ; 16+10: GPIO Port 3 Combined Handler - DCD DMA_Handler ; 16+11: DMA Combined Handler - DCD DUALTIMER0_Handler ; 16+12: Dual timer 0 handler - DCD DUALTIMER1_Handler ; 16+13: Dual timer 1 handler - DCD PWM0_Handler ; 16+14: PWM0 Handler - DCD PWM1_Handler ; 16+15: PWM1 Handler - DCD PWM2_Handler ; 16+16: PWM2 Handler - DCD PWM3_Handler ; 16+17: PWM3 Handler - DCD PWM4_Handler ; 16+18: PWM4 Handler - DCD PWM5_Handler ; 16+19: PWM5 Handler - DCD PWM6_Handler ; 16+20: PWM6 Handler - DCD PWM7_Handler ; 16+21: PWM7 Handler - DCD RTC_Handler ; 16+22: RTC Handler - DCD ADC_Handler ; 16+23: ADC Handler - DCD WZTOE_Handler ; 16+24: WZTOE_Handler - DCD EXTI_Handler ; 16+25: EXTI_Handler -__Vectors_End - -__Vectors EQU __vector_table -__Vectors_Size EQU __Vectors_End - __Vectors - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; -;; Default interrupt handlers. -;; - THUMB - - PUBWEAK Reset_Handler - SECTION .text:CODE:REORDER:NOROOT(2) -Reset_Handler - LDR R0, =SystemInit - BLX R0 - LDR R0, =__iar_program_start - BX R0 - - PUBWEAK NMI_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -NMI_Handler - B NMI_Handler - - PUBWEAK HardFault_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -HardFault_Handler - B HardFault_Handler - - PUBWEAK SVC_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -SVC_Handler - B SVC_Handler - - PUBWEAK PendSV_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -PendSV_Handler - B PendSV_Handler - - PUBWEAK SysTick_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -SysTick_Handler - B SysTick_Handler - - PUBWEAK SSP0_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -SSP0_Handler - B SSP0_Handler - - PUBWEAK SSP1_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -SSP1_Handler - B SSP1_Handler - - PUBWEAK UART0_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -UART0_Handler - B UART0_Handler - - PUBWEAK UART1_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -UART1_Handler - B UART1_Handler - - PUBWEAK UART2_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -UART2_Handler - B UART2_Handler - - PUBWEAK I2C0_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -I2C0_Handler - B I2C0_Handler - - PUBWEAK I2C1_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -I2C1_Handler - B I2C1_Handler - - PUBWEAK PORT0_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -PORT0_Handler - B PORT0_Handler - - PUBWEAK PORT1_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -PORT1_Handler - B PORT1_Handler - - PUBWEAK PORT2_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -PORT2_Handler - B PORT2_Handler - - PUBWEAK PORT3_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -PORT3_Handler - B PORT3_Handler - - PUBWEAK DMA_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -DMA_Handler - B DMA_Handler - - PUBWEAK DUALTIMER0_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -DUALTIMER0_Handler - B DUALTIMER0_Handler - - PUBWEAK DUALTIMER1_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -DUALTIMER1_Handler - B DUALTIMER1_Handler - - PUBWEAK PWM0_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -PWM0_Handler - B PWM0_Handler - - PUBWEAK PWM1_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -PWM1_Handler - B PWM1_Handler - - PUBWEAK PWM2_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -PWM2_Handler - B PWM2_Handler - - PUBWEAK PWM3_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -PWM3_Handler - B PWM3_Handler - - PUBWEAK PWM4_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -PWM4_Handler - B PWM4_Handler - - PUBWEAK PWM5_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -PWM5_Handler - B PWM5_Handler - - PUBWEAK PWM6_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -PWM6_Handler - B PWM6_Handler - - PUBWEAK PWM7_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -PWM7_Handler - B PWM7_Handler - - PUBWEAK RTC_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -RTC_Handler - B RTC_Handler - - PUBWEAK ADC_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -ADC_Handler - B ADC_Handler - - PUBWEAK WZTOE_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -WZTOE_Handler - B WZTOE_Handler - - PUBWEAK EXTI_Handler - SECTION .text:CODE:REORDER:NOROOT(1) -EXTI_Handler - B EXTI_Handler - - END diff --git a/targets/TARGET_WIZNET/TARGET_W7500x/W7500x_Peripheral_Library/W7500x_adc.c b/targets/TARGET_WIZNET/TARGET_W7500x/W7500x_Peripheral_Library/W7500x_adc.c index 294bfa7eeea..c713cc56980 100644 --- a/targets/TARGET_WIZNET/TARGET_W7500x/W7500x_Peripheral_Library/W7500x_adc.c +++ b/targets/TARGET_WIZNET/TARGET_W7500x/W7500x_Peripheral_Library/W7500x_adc.c @@ -36,21 +36,20 @@ uint8_t ADC_IsInterrupt (void) void ADC_InterruptClear (void) { - ADC->ADC_INT = ADC_INTCLEAR; + ADC->ADC_INT = ADC_INTCLEAR; } void ADC_Init (void) { - // ADC_CLK on - ADC_PowerDownEnable(ENABLE); - ADC_PowerDownEnable(DISABLE); - //ADC_ChannelSelect(num); + // ADC_CLK on + ADC_PowerDownEnable(DISABLE); + //ADC_ChannelSelect(num); } void ADC_DeInit (void) { - // ADC_CLK off - ADC_PowerDownEnable(ENABLE); - ADC_InterruptMask(DISABLE); + // ADC_CLK off + ADC_PowerDownEnable(ENABLE); + ADC_InterruptMask(DISABLE); } diff --git a/targets/TARGET_WIZNET/TARGET_W7500x/W7500x_Peripheral_Library/W7500x_gpio.c b/targets/TARGET_WIZNET/TARGET_W7500x/W7500x_Peripheral_Library/W7500x_gpio.c index 7af2ab0cdd4..1257eb4fa8b 100644 --- a/targets/TARGET_WIZNET/TARGET_W7500x/W7500x_Peripheral_Library/W7500x_gpio.c +++ b/targets/TARGET_WIZNET/TARGET_W7500x/W7500x_Peripheral_Library/W7500x_gpio.c @@ -67,8 +67,6 @@ void HAL_GPIO_Init(GPIO_TypeDef* GPIOx, GPIO_InitTypeDef* GPIO_InitStruct) assert_param(IS_GPIO_PIN(GPIO_InitStruct->GPIO_Pin)); // assert_param(IS_GPIO_PUPD(GPIO_InitStruct->GPIO_PuPd)); - GPIOx->INTTYPESET = 0x00FF; - if (GPIOx == GPIOA) px_pcr = PA_PCR; else if (GPIOx == GPIOB) px_pcr = PB_PCR; else if (GPIOx == GPIOC) px_pcr = PC_PCR; @@ -262,30 +260,26 @@ void HAL_PAD_AFConfig(PAD_Type Px, uint16_t GPIO_Pin, PAD_AF_TypeDef P_AF) if(Px == PAD_PA) { assert_param(IS_PA_NUM(i)); - //PA_AFSR->Port[i] &= ~(0x03ul); - //PA_AFSR->Port[i] |= P_AF; - PA_AFSR->Port[i] = P_AF; + PA_AFSR->Port[i] &= ~(0x03ul); + PA_AFSR->Port[i] |= P_AF; } else if(Px == PAD_PB) { assert_param(IS_PB_NUM(i)); - //PB_AFSR->Port[i] &= ~(0x03ul); - //PB_AFSR->Port[i] |= P_AF; - PB_AFSR->Port[i] = P_AF; + PB_AFSR->Port[i] &= ~(0x03ul); + PB_AFSR->Port[i] |= P_AF; } else if(Px == PAD_PC) { assert_param(IS_PC_NUM(i)); - //PC_AFSR->Port[i] &= ~(0x03ul); - //PC_AFSR->Port[i] |= P_AF; - PC_AFSR->Port[i] = P_AF; + PC_AFSR->Port[i] &= ~(0x03ul); + PC_AFSR->Port[i] |= P_AF; } else { assert_param(IS_PD_NUM(i)); - //PD_AFSR->Port[i] &= ~(0x03ul); - //PD_AFSR->Port[i] |= P_AF; - PD_AFSR->Port[i] = P_AF; + PD_AFSR->Port[i] &= ~(0x03ul); + PD_AFSR->Port[i] |= P_AF; } } } diff --git a/targets/TARGET_WIZNET/TARGET_W7500x/W7500x_Peripheral_Library/W7500x_uart.c b/targets/TARGET_WIZNET/TARGET_W7500x/W7500x_Peripheral_Library/W7500x_uart.c index e7436ef509a..560e154980f 100644 --- a/targets/TARGET_WIZNET/TARGET_W7500x/W7500x_Peripheral_Library/W7500x_uart.c +++ b/targets/TARGET_WIZNET/TARGET_W7500x/W7500x_Peripheral_Library/W7500x_uart.c @@ -1,59 +1,21 @@ -/******************************************************************************************************************************************************* - * Copyright �� 2016 - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ��Software��), - * to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, - * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - - * THE SOFTWARE IS PROVIDED ��AS IS��, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -*********************************************************************************************************************************************************/ /** ****************************************************************************** - * @file W7500x_stdPeriph_Driver/src/W7500x_uart.c - * @author IOP Team - * @version v1.0.0 - * @date 01-May-2015 - * @brief This file contains all the functions prototypes for the uart - * firmware library. + * @file W7500x_uart.c + * @author + * @version + * @date + * @brief ****************************************************************************** + * @attention * + * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ +#include "W7500x.h" #include "W7500x_uart.h" -/** @addtogroup W7500x_Periph_Driver - * @{ - */ - -/** @defgroup UART - * @brief UART driver modules - * @{ - */ - - -/* Private typedef -----------------------------------------------------------*/ -/* Private define ------------------------------------------------------------*/ -/* Private macro -------------------------------------------------------------*/ -/* Private variables ---------------------------------------------------------*/ -/* Private function prototypes -----------------------------------------------*/ -/* Private functions ---------------------------------------------------------*/ - -/** @defgroup UART_Private_Functions - * @{ - */ - -/** - * @brief Fills each UART_InitStruct member with its default value. - * @param UART_StructInit: pointer to a UART_InitTypeDef structure which will - * be initialized. - * @retval None - */ void UART_StructInit(UART_InitTypeDef* UART_InitStruct) { /* UART_InitStruct members default value */ @@ -62,34 +24,20 @@ void UART_StructInit(UART_InitTypeDef* UART_InitStruct) UART_InitStruct->UART_StopBits = UART_StopBits_1; UART_InitStruct->UART_Parity = UART_Parity_No ; UART_InitStruct->UART_Mode = UART_Mode_Rx | UART_Mode_Tx; - UART_InitStruct->UART_HardwareFlowControl = UART_HardwareFlowControl_None ; + UART_InitStruct->UART_HardwareFlowControl = UART_HardwareFlowControl_None ; } -/* Function check */ -/* This function is checking now. Update or remove maybe. */ -//Why be???? void UART_DeInit(UART_TypeDef *UARTx) { } -/** - * @brief Initializes the UART peripheral according to the specified - * parameters in the UART_InitStruct . - * @param UARTx: where x can be 1, 2 or 3 - * @param UART_InitStruct: pointer to a UART_InitTypeDef structure that contains - * the configuration information for the specified UART peripheral. - * @retval None - */ - uint32_t UART_Init(UART_TypeDef *UARTx, UART_InitTypeDef* UART_InitStruct) { - float baud_divisor; - uint32_t tmpreg=0x00, uartclock=0x00; - uint32_t integer_baud = 0x00, fractional_baud = 0x00; + uint32_t tmpreg=0x00, uartclock=0x00; + uint32_t integer_baud = 0x00, fractional_baud = 0x00; - /* Check the parameters */ assert_param(IS_UART_01_PERIPH(UARTx)); assert_param(IS_UART_WORD_LENGTH(UART_InitStruct->UART_WordLength)); assert_param(IS_UART_PARITY(UART_InitStruct->UART_Parity)); @@ -97,101 +45,53 @@ uint32_t UART_Init(UART_TypeDef *UARTx, UART_InitTypeDef* UART_InitStruct) assert_param(IS_UART_HARDWARE_FLOW_CONTROL(UART_InitStruct->UART_HardwareFlowControl)); assert_param(IS_UART_MODE(UART_InitStruct->UART_Mode)); - /* Write to UART CR */ - UARTx->CR &= ~(UART_CR_UARTEN); - /* Set baudrate */ - /* CRG_UARTCLK_SSR_RCLK: Set UART Clock using internal Oscilator ( 8MHz ) */ - /* CRG_UARTCLK_SSR_OCLK: Set UART Clock using external Oscilator */ - CRG->UARTCLK_SSR = CRG_UARTCLK_SSR_RCLK; // Set UART Clock using internal Oscilator ( 8MHz ) - //CRG->UARTCLK_SSR = CRG_UARTCLK_SSR_OCLK; // Set UART Clock using external Oscilator + UARTx->CR &= ~(UART_CR_UARTEN); + + // Set baudrate + CRG->UARTCLK_SSR = CRG_UARTCLK_SSR_RCLK; // Set UART Clock using internal Oscilator ( 8MHz ) + uartclock = (8000000UL) / (1 << CRG->UARTCLK_PVSR); - /* Set uartclock */ - uartclock = (8000000UL) / (1 << CRG->UARTCLK_PVSR); - - /*----------------------------- UARTx IBRD and FBRD Configuration ------------------------------*/ - baud_divisor = ((float)uartclock / (16 * UART_InitStruct->UART_BaudRate)); - integer_baud = (uint32_t)baud_divisor; - fractional_baud = (uint32_t)((baud_divisor - integer_baud) * 64 + 0.5); + baud_divisor = ((float)uartclock / (16 * UART_InitStruct->UART_BaudRate)); + integer_baud = (uint32_t)baud_divisor; + fractional_baud = (uint32_t)((baud_divisor - integer_baud) * 64 + 0.5); - UARTx->IBRD = integer_baud; - UARTx->FBRD = fractional_baud; + UARTx->IBRD = integer_baud; + UARTx->FBRD = fractional_baud; tmpreg = UARTx->LCR_H; tmpreg &= ~(0x00EE); tmpreg |= (UART_InitStruct->UART_WordLength | UART_InitStruct->UART_StopBits | UART_InitStruct->UART_Parity); - UARTx->LCR_H = tmpreg; + UARTx->LCR_H |= tmpreg; tmpreg = UARTx->CR; tmpreg &= ~(UART_CR_CTSEn | UART_CR_RTSEn | UART_CR_RXE | UART_CR_TXE | UART_CR_UARTEN); tmpreg |= (UART_InitStruct->UART_Mode | UART_InitStruct->UART_HardwareFlowControl); - UARTx->CR = tmpreg; - - /* Debug */ - /* UARTx->LCR_H |=0x10; */ - /* UARTx->IFLS | = 0x00; */ + UARTx->CR |= tmpreg; UARTx->CR |= UART_CR_UARTEN; return 0; } -/** - * @brief UART_FIFO_Enable - * @param case rx_fifo_level=0: 1/8 full, case rx_fifo_level=1: 1/4 full, case rx_fifo_level=2: 1/2 full, - * case rx_fifo_level=3: 3/4 full, case rx_fifo_level=4: 7/8 full - * @param case tx_fifo_level=0: 1/8 full, case tx_fifo_level=1: 1/4 full, case tx_fifo_level=2: 1/2 full, - * case tx_fifo_level=3: 3/4 full, case tx_fifo_level=4: 7/8 full - * @retval None - */ - -void UART_FIFO_Enable(UART_TypeDef *UARTx, uint16_t rx_fifo_level, uint16_t tx_fifo_level) -{ - UARTx->LCR_H |= UART_LCR_H_FEN; - UARTx->IFLS = (UART_IFLS_RXIFLSEL(rx_fifo_level) | UART_IFLS_TXIFLSEL(tx_fifo_level)); -} - -/** - * @brief UART_FIFO_Disable - * @param UARTx: Define structure at "W7500x.h" - * @retval None - */ -void UART_FIFO_Disable(UART_TypeDef *UARTx) -{ - UARTx->LCR_H &= ~(UART_LCR_H_FEN); -} -/** - * @brief UART_SendData - * @param UARTx: Define structure at "W7500x.h" - * @param Data: Unsigned short value - * @retval None - */ void UART_SendData(UART_TypeDef* UARTx, uint16_t Data) { - /* Check the parameters */ assert_param(IS_UART_01_PERIPH(UARTx)); + UARTx->DR = Data; } -/** - * @brief UART_ReceiveData - * @param UARTx: Define structure at "W7500x.h" - * @retval None - */ + uint16_t UART_ReceiveData(UART_TypeDef* UARTx) { - /* Check the parameters */ assert_param(IS_UART_01_PERIPH(UARTx)); + return (uint16_t)(UARTx->DR); } -/** - * @brief UART_SendBreak - * @param UARTx: Define structure at "W7500x.h" - * @retval None - */ + void UART_SendBreak(UART_TypeDef* UARTx) { assert_param(IS_UART_01_PERIPH(UARTx)); @@ -199,17 +99,11 @@ void UART_SendBreak(UART_TypeDef* UARTx) UARTx->LCR_H |= UART_LCR_H_BRK; } -/** - * @brief UART_GetRecvStatus - * @param UARTx: Define structure at "W7500x.h" - * @param UART_RECV_STATUS - * @retval bitstatus - */ + FlagStatus UART_GetRecvStatus(UART_TypeDef* UARTx, uint16_t UART_RECV_STATUS) { FlagStatus bitstatus = RESET; - - /* Check the parameters */ + assert_param(IS_UART_01_PERIPH(UARTx)); assert_param(IS_UART_RECV_STATUS(UART_RECV_STATUS)); @@ -225,44 +119,29 @@ FlagStatus UART_GetRecvStatus(UART_TypeDef* UARTx, uint16_t UART_RECV_STATUS) return bitstatus; } -/** - * @brief UART_ClearRecvStatus - * @param UARTx: Define structure at "W7500x.h" - * @param UART_RECV_STATUS - * @retval None - */ + void UART_ClearRecvStatus(UART_TypeDef* UARTx, uint16_t UART_RECV_STATUS) { - /* Check the parameters */ assert_param(IS_UART_01_PERIPH(UARTx)); assert_param(IS_UART_RECV_STATUS(UART_RECV_STATUS)); - /* Set STATUS.ECR*/ UARTx->STATUS.ECR = (uint16_t)UART_RECV_STATUS; } -/** - * @brief UART_GetFlagStatus - * @param UARTx: Define structure at "W7500x.h" - * @param UART_FLAG - * @retval bitstatus - */ + FlagStatus UART_GetFlagStatus(UART_TypeDef* UARTx, uint16_t UART_FLAG) { FlagStatus bitstatus = RESET; - /* Check the parameters */ assert_param(IS_UART_01_PERIPH(UARTx)); assert_param(IS_UART_FLAG(UART_FLAG)); if ((UARTx->FR & UART_FLAG) != (uint16_t)RESET) { - /* bitstatus setting to SET*/ bitstatus = SET; } else { - /*bitstatus setting to RESET*/ bitstatus = RESET; } @@ -270,194 +149,109 @@ FlagStatus UART_GetFlagStatus(UART_TypeDef* UARTx, uint16_t UART_FLAG) } -/* Function check */ -/* This function is checking now. Update or remove maybe. */ -//Why be? - +/* void UART_ClearFlag(UART_TypeDef* UARTx, uint16_t UART_FLAG) { } +*/ - -/** - * @brief UART_ITConfig - * @param UARTx: Define structure at "W7500x.h" - * @param UART_IT - * @param NewState - * @retval None - */ void UART_ITConfig(UART_TypeDef* UARTx, uint16_t UART_IT, FunctionalState NewState) { - /* Check the parameters */ assert_param(IS_UART_01_PERIPH(UARTx)); assert_param(IS_UART_IT_FLAG(UART_IT)); if ( NewState != DISABLE ) { - /*Set the IMSC*/ UARTx->IMSC |= UART_IT; } else { - /*Set the ICR*/ UARTx->ICR |= UART_IT; } } -/** - * @brief UART_GetITStatus - * @param UARTx: Define structure at "W7500x.h" - * @param UART_IT - * @param bitstatus - * @retval None - */ + ITStatus UART_GetITStatus(UART_TypeDef* UARTx, uint16_t UART_IT) { ITStatus bitstatus = RESET; - /* Check the parameters */ + assert_param(IS_UART_01_PERIPH(UARTx)); assert_param(IS_UART_IT_FLAG(UART_IT)); if ((UARTx->MIS & UART_IT) != (uint16_t)RESET) { - /*Set bitstatus = SET */ bitstatus = SET; } else { - /*Set bitstatus = RESET */ bitstatus = RESET; } return bitstatus; } -/** - * @brief UART_ITPendingBit - * @param UARTx: Define structure at "W7500x.h" - * @param UART_IT - * @retval None - */ void UART_ClearITPendingBit(UART_TypeDef* UARTx, uint16_t UART_IT) { - /* Check the parameters */ assert_param(IS_UART_01_PERIPH(UARTx)); assert_param(IS_UART_IT_FLAG(UART_IT)); - /* Set ICR */ UARTx->ICR |= UART_IT; } -/** - * @brief UART_DMA_Config - * @param UARTx: Define structure at "W7500x.h" - * @param UART_DMA_CONTROL - * @retval None - */ -void UART_DMA_Config(UART_TypeDef* UARTx, uint16_t UART_DMA_CONTROL) -{ - /* Check the parameters */ - assert_param(IS_UART_01_PERIPH(UARTx)); - assert_param(IS_UART_DMA_CONTROL(UART_DMA_CONTROL)); - - /*Set DMACR */ - UARTx->DMACR |= UART_DMA_CONTROL; -} -/* Function check */ -/* This function is checking now. Update or remove maybe. */ -//Why be? void S_UART_DeInit() { } -/** - * @brief S_UART_Init - * @param baud - * @retval None - */ uint32_t S_UART_Init(uint32_t baud) { uint32_t tmpreg=0x00; S_UART_SetBaud(baud); - /* Set temp register for UART2 CTRL */ tmpreg = UART2->CTRL; tmpreg &= ~(S_UART_CTRL_RX_EN | S_UART_CTRL_TX_EN); tmpreg |= (S_UART_CTRL_RX_EN | S_UART_CTRL_TX_EN); - - /* Write to UART2 CTRL */ UART2->CTRL = tmpreg; return 0; } -/** - * @brief S_UART_SetBaud - * @param baud - * @retval None - */ void S_UART_SetBaud(uint32_t baud) { uint32_t uartclock = 0x00, integer_baud = 0x00; - - /* Check the parameters */ - assert_param(IS_UART_MODE(S_UART_InitStruct->UART_Mode)); if(CRG->FCLK_SSR == CRG_FCLK_SSR_RCLK) { - /* Set uartclock: INTERN_XTAL */ - uartclock = INTERN_XTAL; + uartclock = INTERN_XTAL; } else if(CRG->FCLK_SSR == CRG_FCLK_SSR_OCLK) { - /* Set uartclock: EXTERN_XTAL */ uartclock = EXTERN_XTAL; } else { - /* Set uartclock: GetSystemClock */ uartclock = GetSystemClock(); } - /* Set (Calculate) integer_baud */ integer_baud = (uint32_t)(uartclock / baud); - /* Write UART2 BAUDDIV */ UART2->BAUDDIV = integer_baud; } - -/** - * @brief S_UART_SendData - * @param Data - * @retval None - */ void S_UART_SendData(uint16_t Data) { while(UART2->STATE & S_UART_STATE_TX_BUF_FULL); - /* Write UART2 DATA */ UART2->DATA = Data; } - -/** - * @brief S_UART_ReceiveData - * @retval UART2 DATA - */ uint16_t S_UART_ReceiveData() { return (uint16_t)(UART2->DATA); } -/** - * @brief S_UART_GetFlagStatus - * @param UART_STATE - * @retval bitstatus - */ FlagStatus S_UART_GetFlagStatus(uint16_t S_UART_STATE) { FlagStatus bitstatus = RESET; @@ -476,13 +270,6 @@ FlagStatus S_UART_GetFlagStatus(uint16_t S_UART_STATE) return bitstatus; } - -/** - * @brief S_UART_SetCTRL - * @param S_UART_CTRL - * @param NewState - * @retval None - */ void S_UART_SetCTRL(uint16_t S_UART_CTRL, FunctionalState NewState) { if ( NewState != DISABLE ) @@ -496,77 +283,49 @@ void S_UART_SetCTRL(uint16_t S_UART_CTRL, FunctionalState NewState) } -/** - * @brief S_UART_ITConfig - * @param S_UART_CTRL - * @param NewState - * @retval None - */ void S_UART_ITConfig(uint16_t S_UART_CTRL, FunctionalState NewState) { - /* Check the parameters */ assert_param(IS_S_UART_CTRL_FLAG(S_UART_CTRL)); if ( NewState != DISABLE ) { - /* Set UART2 CTRL: S_UART_CTRL */ UART2->CTRL |= S_UART_CTRL; } else { - /*Set UART2 CTRL: ~S_UART_CTRL */ UART2->CTRL &= ~(S_UART_CTRL); } } - -/** - * @brief S_UART_GetTStatus - * @param S_UART_INTSTATUS - * @retval bitstatus - */ ITStatus S_UART_GetITStatus(uint16_t S_UART_INTSTATUS) { ITStatus bitstatus = RESET; - - /* Check the parameters */ + assert_param(IS_S_UART_INTSATUS(S_UART_INTSTATUS)); if ((UART2->INT.STATUS & (S_UART_INTSTATUS)) != (uint16_t) RESET) { - /* Set bitstatus: SET */ bitstatus = SET; } else { - /* Set bitstatus: RESET */ bitstatus = RESET; } return bitstatus; } - -/** - * @brief S_UART_ClearITPendingBit - * @param S_UART_INTSTATUS - * @retval None - */ void S_UART_ClearITPendingBit(uint16_t S_UART_INTSTATUS) { - /* Check the parameters */ assert_param(IS_S_UART_INTSATUS(S_UART_INTSTATUS)); - /* Write UART2 INT.CLEAR: S_UART_INSTATUS */ + UART2->INT.CLEAR |= (S_UART_INTSTATUS); } - /**************************************************/ // It will be moved to application board's driver */ /**************************************************/ - - uint8_t UartPutc(UART_TypeDef* UARTx, uint8_t ch) { UART_SendData(UARTx,ch); @@ -576,8 +335,6 @@ uint8_t UartPutc(UART_TypeDef* UARTx, uint8_t ch) return (ch); } - - void UartPuts(UART_TypeDef* UARTx, uint8_t *str) { uint8_t ch; @@ -592,7 +349,6 @@ void UartPuts(UART_TypeDef* UARTx, uint8_t *str) }while(ch != 0); } - uint8_t UartGetc(UART_TypeDef* UARTx) { while(UARTx->FR & UART_FR_RXFE); @@ -608,8 +364,6 @@ uint8_t S_UartPutc(uint8_t ch) return (ch); } - - void S_UartPuts(uint8_t *str) { uint8_t ch; @@ -624,7 +378,6 @@ void S_UartPuts(uint8_t *str) }while(ch != 0); } - uint8_t S_UartGetc() { while( (UART2->STATE & S_UART_STATE_RX_BUF_FULL) == 0 ); @@ -632,16 +385,3 @@ uint8_t S_UartGetc() } -/** - * @} - */ - - -/** - * @} - */ - - -/** - * @} - */ diff --git a/targets/TARGET_WIZNET/TARGET_W7500x/W7500x_Peripheral_Library/W7500x_uart.h b/targets/TARGET_WIZNET/TARGET_W7500x/W7500x_Peripheral_Library/W7500x_uart.h index e85d3d73ca4..cc0b897b353 100644 --- a/targets/TARGET_WIZNET/TARGET_W7500x/W7500x_Peripheral_Library/W7500x_uart.h +++ b/targets/TARGET_WIZNET/TARGET_W7500x/W7500x_Peripheral_Library/W7500x_uart.h @@ -1,22 +1,9 @@ -/******************************************************************************************************************************************************* - * Copyright �� 2016 - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ��Software��), - * to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, - * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - - * THE SOFTWARE IS PROVIDED ��AS IS��, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -*********************************************************************************************************************************************************/ /** ****************************************************************************** - * @file W7500x_stdPeriph_Driver/inc/W7500x_uart.h - * @author IOP Team - * @version V1.0.0 - * @date 01-May-2015 + * @file + * @author + * @version + * @date * @brief This file contains all the functions prototypes for the UART * firmware library. ****************************************************************************** @@ -36,15 +23,6 @@ #include "W7500x.h" -/** @addtogroup W7500x_Periph_Driver - * @{ - */ - -/** @addtogroup UART - * @{ - */ - - /** * @brief UART Init Structure definition */ @@ -130,8 +108,7 @@ typedef struct #define UART_Mode_Rx ((uint16_t)(UART_CR_RXE)) #define UART_Mode_Tx ((uint16_t)(UART_CR_TXE)) #define IS_UART_MODE(MODE) (((MODE) == UART_Mode_Rx) || \ - ((MODE) == UART_Mode_Tx) || \ - ((MODE) == (UART_Mode_Rx | UART_Mode_Tx))) + ((MODE) == UART_Mode_Tx)) /** * @} @@ -156,22 +133,6 @@ typedef struct */ -/** @addtogroup UART_DMA_Control - * @{ - */ - -#define UART_DMAControl_DMAONERR ((uint16_t)UART_DMACR_DMAONERR) -#define UART_DMAControl_RXDMAE ((uint16_t)UART_DMACR_TXDMAE) -#define UART_DMAControl_TXDMAE ((uint16_t)UART_DMACR_RXDMAE) -#define IS_UART_DMA_CONTROL(CONTROL) \ - (((CONTROL) == UART_DMAControl_DMAONERR) || \ - ((CONTROL) == UART_DMAControl_TXDMAE) || \ - ((CONTROL) == UART_DMAControl_RXDMAE)) -/** - * @} - */ - - /** @addtogroup UART_Receive Status * @{ */ @@ -222,7 +183,7 @@ typedef struct #define UART_IT_FLAG_FEI ((uint16_t)0x01UL << 7) /*!< Framing error interrupt */ #define UART_IT_FLAG_RTI ((uint16_t)0x01UL << 6) /*!< Receive timeout interrupt */ #define UART_IT_FLAG_TXI ((uint16_t)0x01UL << 5) /*!< Transmit interrupt */ -#define UART_IT_FLAG_RXI ((uint16_t)0x01UL << 4) /*!< Receive interrupt */ +#define UART_IT_FLAG_RXI ((uint16_t)0x01UL << 4) /*!< Receive interrupt */ #define UART_IT_FLAG_DSRMI ((uint16_t)0x01UL << 3) /*!< UARTDSR modem interrupt */ #define UART_IT_FLAG_DCDMI ((uint16_t)0x01UL << 2) /*!< UARTDCD modem interrupt */ #define UART_IT_FLAG_CTSMI ((uint16_t)0x01UL << 1) /*!< UARTCTS modem interrupt */ @@ -312,8 +273,6 @@ typedef struct void UART_StructInit (UART_InitTypeDef* UART_InitStruct); uint32_t UART_Init (UART_TypeDef *UARTx, UART_InitTypeDef* UART_InitStruct); -void UART_FIFO_Enable (UART_TypeDef *UARTx, uint16_t rx_fifo_level, uint16_t tx_fifo_level); -void UART_FIFO_Disable (UART_TypeDef *UARTx); void UART_SendData (UART_TypeDef* UARTx, uint16_t Data); uint16_t UART_ReceiveData (UART_TypeDef* UARTx); void UART_SendBreak (UART_TypeDef* UARTx); @@ -322,7 +281,6 @@ FlagStatus UART_GetFlagStatus (UART_TypeDef* UARTx, uint16_t UART_FLAG); void UART_ITConfig (UART_TypeDef* UARTx, uint16_t UART_IT, FunctionalState NewState); ITStatus UART_GetITStatus (UART_TypeDef* UARTx, uint16_t UART_IT); void UART_ClearITPendingBit (UART_TypeDef* UARTx, uint16_t UART_IT); -void UART_DMA_Config(UART_TypeDef* UARTx, uint16_t UART_DMA_CONTROL); uint8_t UartPutc (UART_TypeDef* UARTx, uint8_t ch); void UartPuts (UART_TypeDef* UARTx, uint8_t *str); @@ -353,10 +311,3 @@ void S_UART_ClearITPendingBit(uint16_t S_UART_IT); #endif // __W7500X_UART_H -/** - * @} - */ - -/** - * @} - */ diff --git a/targets/TARGET_WIZNET/TARGET_W7500x/analogin_api.c b/targets/TARGET_WIZNET/TARGET_W7500x/analogin_api.c index 14fd15d73b3..a6998b91e5b 100644 --- a/targets/TARGET_WIZNET/TARGET_W7500x/analogin_api.c +++ b/targets/TARGET_WIZNET/TARGET_W7500x/analogin_api.c @@ -42,6 +42,8 @@ ADC_TypeDef * AdcHandle; +static int adc_inited = 0; + void analogin_init(analogin_t *obj, PinName pin) { // Get the peripheral name from the pin and assign it to the object @@ -55,8 +57,12 @@ void analogin_init(analogin_t *obj, PinName pin) // Save pin number for the read function obj->pin = pin; - // The ADC initialization - ADC_Init(); + // The ADC initialization is done once + if (adc_inited == 0) { + adc_inited = 1; + + ADC_Init(); + } } static inline uint16_t adc_read(analogin_t *obj) diff --git a/targets/TARGET_WIZNET/TARGET_W7500x/gpio_irq_api.c b/targets/TARGET_WIZNET/TARGET_W7500x/gpio_irq_api.c index d64ee892467..10ef6ae19b6 100644 --- a/targets/TARGET_WIZNET/TARGET_W7500x/gpio_irq_api.c +++ b/targets/TARGET_WIZNET/TARGET_W7500x/gpio_irq_api.c @@ -43,7 +43,6 @@ static gpio_irq_handler irq_handler; static uint32_t channel_ids[4][16]; - #ifdef __cplusplus extern "C"{ #endif @@ -51,7 +50,6 @@ void port_generic_handler(GPIO_TypeDef* GPIOx, uint32_t port_num); void PORT0_Handler(void) { - NVIC_ClearPendingIRQ(PORT0_IRQn); port_generic_handler(GPIOA, 0); } @@ -101,8 +99,6 @@ int gpio_irq_init(gpio_irq_t *obj, PinName pin, gpio_irq_handler handler, uint32 obj->pin_num = WIZ_PIN_NUM(pin); obj->pin_index = WIZ_PIN_INDEX(pin); - //gpio_irq_disable(obj); - if (pin == NC) return -1; if(obj->port_num == 0) @@ -114,11 +110,10 @@ int gpio_irq_init(gpio_irq_t *obj, PinName pin, gpio_irq_handler handler, uint32 else obj->irq_n = PORT3_IRQn; + //obj->event = EDGE_FALL; obj->pin = pin; - obj->event = EDGE_NONE; - + // Enable EXTI interrupt - NVIC_ClearPendingIRQ(obj->irq_n); NVIC_EnableIRQ(obj->irq_n); channel_ids[obj->port_num][obj->pin_num] = id; @@ -146,13 +141,10 @@ void gpio_irq_set(gpio_irq_t *obj, gpio_irq_event event, uint32_t enable) obj->rise_null = 0; } else if (event == IRQ_FALL) { - gpio->INTPOLCLR |= obj->pin_index; + gpio->INTPOLSET &= ~obj->pin_index; obj->event = EDGE_FALL; obj->fall_null = 0; } - - - gpio->INTENCLR |= obj->pin_index; gpio->INTTYPESET |= obj->pin_index; gpio->INTENSET |= obj->pin_index; diff --git a/targets/TARGET_WIZNET/TARGET_W7500x/pinmap.c b/targets/TARGET_WIZNET/TARGET_W7500x/pinmap.c index 4c1470e1a49..c69be952a2a 100644 --- a/targets/TARGET_WIZNET/TARGET_W7500x/pinmap.c +++ b/targets/TARGET_WIZNET/TARGET_W7500x/pinmap.c @@ -117,29 +117,17 @@ void pin_mode(PinName pin, PinMode pupd) uint32_t port_num = WIZ_PORT(pin); uint32_t pin_num = WIZ_PIN_NUM(pin); - switch(port_num) { + switch(port_num) { case PortA: - if(pupd != 0) { - PA_PCR->Port[pin_num] &= 0xFFFFFFFC; - } PA_PCR->Port[pin_num] |= pupd; break; case PortB: - if(pupd != 0) { - PB_PCR->Port[pin_num] &= 0xFFFFFFFC; - } PB_PCR->Port[pin_num] |= pupd; break; case PortC: - if(pupd != 0) { - PC_PCR->Port[pin_num] &= 0xFFFFFFFC; - } PC_PCR->Port[pin_num] |= pupd; break; case PortD: - if(pupd != 0) { - PD_PCR->Port[pin_num] &= 0xFFFFFFFC; - } PD_PCR->Port[pin_num] |= pupd; break; default: diff --git a/targets/TARGET_WIZNET/mbed_rtx.h b/targets/TARGET_WIZNET/mbed_rtx.h deleted file mode 100644 index c475509da13..00000000000 --- a/targets/TARGET_WIZNET/mbed_rtx.h +++ /dev/null @@ -1,67 +0,0 @@ -/* mbed Microcontroller Library - * Copyright (c) 2016 ARM Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * 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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * 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. - */ - -#ifndef MBED_MBED_RTX_H -#define MBED_MBED_RTX_H - -#if defined(TARGET_WIZWIKI_W7500) - -#ifndef INITIAL_SP -#define INITIAL_SP (0x20004000UL) -#endif -#ifndef OS_TASKCNT -#define OS_TASKCNT 6 -#endif -#ifndef OS_MAINSTKSIZE -#define OS_MAINSTKSIZE 128 -#endif -#ifndef OS_CLOCK -#define OS_CLOCK 20000000 -#endif - -#elif defined(TARGET_WIZWIKI_W7500P) - -#ifndef INITIAL_SP -#define INITIAL_SP (0x20004000UL) -#endif -#ifndef OS_TASKCNT -#define OS_TASKCNT 6 -#endif -#ifndef OS_MAINSTKSIZE -#define OS_MAINSTKSIZE 128 -#endif -#ifndef OS_CLOCK -#define OS_CLOCK 20000000 -#endif - -#elif defined(TARGET_WIZWIKI_W7500ECO) - -#ifndef INITIAL_SP -#define INITIAL_SP (0x20004000UL) -#endif -#ifndef OS_TASKCNT -#define OS_TASKCNT 6 -#endif -#ifndef OS_MAINSTKSIZE -#define OS_MAINSTKSIZE 128 -#endif -#ifndef OS_CLOCK -#define OS_CLOCK 20000000 -#endif - -#endif // - -#endif // MBED_MBED_RTX_H diff --git a/targets/targets.json b/targets/targets.json index 200b3dc0d4a..3ec7f735a6c 100644 --- a/targets/targets.json +++ b/targets/targets.json @@ -148,7 +148,15 @@ "device_name": "LPC11U35FHI33/501" }, "XADOW_M0": { - "inherits": ["LPC11U35_501"] + "inherits": ["LPCTarget"], + "core": "Cortex-M0", + "default_toolchain": "uARM", + "extra_labels": ["NXP", "LPC11UXX", "MCU_LPC11U35_501"], + "supported_toolchains": ["ARM", "uARM", "GCC_ARM", "GCC_CR", "IAR"], + "device_has": ["ANALOGIN", "ERROR_PATTERN", "I2C", "I2CSLAVE", "INTERRUPTIN", "PORTIN", "PORTINOUT", "PORTOUT", "PWMOUT", "SERIAL", "SLEEP", "SPI", "SPISLAVE"], + "default_lib": "small", + "release_versions": ["2"], + "device_name": "LPC11U35FHI33/501" }, "LPC11U35_Y5_MBUG": { "inherits": ["LPCTarget"], @@ -248,10 +256,10 @@ "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"], "macros": ["TARGET_LPC1768"], "inherits": ["LPCTarget"], - "device_has": ["ANALOGIN", "ANALOGOUT", "CAN", "DEBUG_AWARENESS", "ERROR_RED", "ETHERNET", "I2C", "I2CSLAVE", "INTERRUPTIN", "PORTIN", "PORTINOUT", "PORTOUT", "PWMOUT", "RTC", "SERIAL", "SERIAL_FC", "SLEEP", "SPI", "SPISLAVE", "STDIO_MESSAGES", "FLASH"], + "device_has": ["ANALOGIN", "ANALOGOUT", "CAN", "DEBUG_AWARENESS", "ERROR_RED", "ETHERNET", "I2C", "I2CSLAVE", "INTERRUPTIN", "PORTIN", "PORTINOUT", "PORTOUT", "PWMOUT", "RTC", "SERIAL", "SERIAL_FC", "SLEEP", "SPI", "SPISLAVE", "STDIO_MESSAGES"], "release_versions": ["2", "5"], "features": ["LWIP"], "device_name": "LPC1768" @@ -260,12 +268,26 @@ "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", "ERROR_PATTERN", "ETHERNET", "I2C", "I2CSLAVE", "INTERRUPTIN", "LOCALFILESYSTEM", "PORTIN", "PORTINOUT", "PORTOUT", "PWMOUT", "RTC", "SEMIHOST", "SERIAL", "SERIAL_FC", "SLEEP", "SPI", "SPISLAVE", "STDIO_MESSAGES", "FLASH"], + "device_has": ["ANALOGIN", "ANALOGOUT", "CAN", "DEBUG_AWARENESS", "ERROR_PATTERN", "ETHERNET", "I2C", "I2CSLAVE", "INTERRUPTIN", "LOCALFILESYSTEM", "PORTIN", "PORTINOUT", "PORTOUT", "PWMOUT", "RTC", "SEMIHOST", "SERIAL", "SERIAL_FC", "SLEEP", "SPI", "SPISLAVE", "STDIO_MESSAGES"], "device_name": "LPC1768" }, + "LPC2368": { + "inherits": ["LPCTarget"], + "core": "ARM7TDMI-S", + "extra_labels": ["NXP", "LPC23XX"], + "supported_toolchains": ["GCC_ARM", "GCC_CR"], + "device_has": ["ANALOGIN", "ANALOGOUT", "CAN", "ERROR_PATTERN", "ETHERNET", "I2C", "I2CSLAVE", "INTERRUPTIN", "LOCALFILESYSTEM", "PORTIN", "PORTINOUT", "PORTOUT", "PWMOUT", "RTC", "SEMIHOST", "SERIAL", "SPI", "SPISLAVE", "STDIO_MESSAGES"] + }, + "LPC2460": { + "inherits": ["LPCTarget"], + "core": "ARM7TDMI-S", + "extra_labels": ["NXP", "LPC2460"], + "supported_toolchains": ["GCC_ARM"], + "device_has": ["ANALOGIN", "ANALOGOUT", "CAN", "ERROR_PATTERN", "ETHERNET", "I2C", "I2CSLAVE", "INTERRUPTIN", "PORTIN", "PORTINOUT", "PORTOUT", "PWMOUT", "RTC", "SERIAL", "SPI", "SPISLAVE", "STDIO_MESSAGES"] + }, "LPC810": { "inherits": ["LPCTarget"], "core": "Cortex-M0+", @@ -325,7 +347,6 @@ "function": "LPC4088Code.binary_hook" }, "device_has": ["ANALOGIN", "ANALOGOUT", "CAN", "DEBUG_AWARENESS", "ERROR_PATTERN", "ETHERNET", "I2C", "I2CSLAVE", "INTERRUPTIN", "PORTIN", "PORTINOUT", "PORTOUT", "PWMOUT", "RTC", "SERIAL", "SLEEP", "SPI", "SPISLAVE", "STDIO_MESSAGES"], - "features": ["LWIP"], "device_name": "LPC4088FBD144" }, "LPC4088": { @@ -550,23 +571,6 @@ "release_versions": ["2", "5"], "device_name": "MKW41Z512xxx4" }, - "MCU_K24F1M": { - "core": "Cortex-M4F", - "supported_toolchains": ["ARM", "GCC_ARM", "IAR"], - "extra_labels": ["Freescale", "MCUXpresso_MCUS", "KSDK2_MCUS", "MCU_K24F", "KPSDK_MCUS", "KPSDK_CODE", "FLASH_CMSIS_ALGO"], - "is_disk_virtual": true, - "public": false, - "macros": ["CPU_MK24FN1M0VDC12", "FSL_RTOS_MBED"], - "inherits": ["Target"], - "device_has": ["ANALOGIN", "ANALOGOUT", "ERROR_RED", "I2C", "I2CSLAVE", "INTERRUPTIN", "LOWPOWERTIMER", "PORTIN", "PORTINOUT", "PORTOUT", "PWMOUT", "RTC", "SERIAL", "SERIAL_FC", "SERIAL_ASYNCH", "SLEEP", "SPI", "SPI_ASYNCH", "SPISLAVE", "STDIO_MESSAGES", "TRNG", "FLASH"], - "device_name": "MK24FN1M0xxx12" - }, - "RO359B": { - "supported_form_factors": ["ARDUINO"], - "inherits": ["MCU_K24F1M"], - "detect_code": ["1022"], - "release_versions": ["2", "5"] - }, "K64F": { "supported_form_factors": ["ARDUINO"], "core": "Cortex-M4F", @@ -618,7 +622,7 @@ "device_has": ["ANALOGIN", "ANALOGOUT", "ERROR_RED", "I2C", "I2CSLAVE", "INTERRUPTIN", "PORTIN", "PORTINOUT", "PORTOUT", "PWMOUT", "RTC", "SERIAL", "SERIAL_FC", "SLEEP", "SPI", "SPISLAVE", "STDIO_MESSAGES", "TRNG"], "features": ["LWIP"], "release_versions": ["2", "5"], - "device_name": "MK66FN2M0xxx18" + "device_name" : "MK66FN2M0xxx18" }, "K82F": { "supported_form_factors": ["ARDUINO"], @@ -631,7 +635,7 @@ "detect_code": ["0217"], "device_has": ["ANALOGIN", "ANALOGOUT", "ERROR_RED", "I2C", "I2CSLAVE", "INTERRUPTIN", "LOWPOWERTIMER", "PORTIN", "PORTINOUT", "PORTOUT", "PWMOUT", "RTC", "SERIAL", "SLEEP", "SPI", "SPISLAVE", "STDIO_MESSAGES"], "release_versions": ["2", "5"], - "device_name": "MK82FN256xxx15" + "device_name" : "MK82FN256xxx15" }, "NUCLEO_F030R8": { "supported_form_factors": ["ARDUINO", "MORPHO"], @@ -733,20 +737,13 @@ "default_toolchain": "ARM", "extra_labels": ["STM", "STM32F2", "STM32F207ZG"], "supported_toolchains": ["ARM", "uARM", "IAR", "GCC_ARM"], - "config": { - "d11_configuration": { - "help": "Value: PA_7 for the default board configuration, PB_5 in case of solder bridge update (SB121 off/ SB122 on)", - "value": "PA_7", - "macro_name": "STM32_D11_SPI_ETHERNET_PIN" - } - }, "inherits": ["Target"], "detect_code": ["0835"], "macros": ["TRANSACTION_QUEUE_SIZE_SPI=2", "USBHOST_OTHER"], "device_has": ["ANALOGIN", "ANALOGOUT", "CAN", "I2C", "I2CSLAVE", "I2C_ASYNCH", "INTERRUPTIN", "PORTIN", "PORTINOUT", "PORTOUT", "PWMOUT", "RTC", "SERIAL", "SERIAL_ASYNCH", "SERIAL_FC", "SLEEP", "SPI", "SPISLAVE", "SPI_ASYNCH", "STDIO_MESSAGES"], "features": ["LWIP"], "release_versions": ["2", "5"], - "device_name": "STM32F207ZG" + "device_name" : "STM32F207ZG" }, "NUCLEO_F302R8": { "supported_form_factors": ["ARDUINO", "MORPHO"], @@ -887,13 +884,6 @@ "inherits": ["Target"], "core": "Cortex-M4F", "default_toolchain": "ARM", - "config": { - "d11_configuration": { - "help": "Value: PA_7 for the default board configuration, PB_5 in case of solder bridge update (SB121 off/ SB122 on)", - "value": "PA_7", - "macro_name": "STM32_D11_SPI_ETHERNET_PIN" - } - }, "extra_labels": ["STM", "STM32F4", "STM32F429", "STM32F429ZI", "STM32F429xx", "STM32F429xI", "FLASH_CMSIS_ALGO"], "supported_toolchains": ["ARM", "uARM", "GCC_ARM", "IAR"], "progen": {"target": "nucleo-f429zi"}, @@ -902,7 +892,7 @@ "detect_code": ["0796"], "features": ["LWIP"], "release_versions": ["2", "5"], - "device_name": "STM32F429ZI", + "device_name" : "STM32F429ZI", "bootloader_supported": true }, "NUCLEO_F439ZI": { @@ -910,13 +900,6 @@ "inherits": ["Target"], "core": "Cortex-M4F", "default_toolchain": "ARM", - "config": { - "d11_configuration": { - "help": "Value: PA_7 for the default board configuration, PB_5 in case of solder bridge update (SB121 off/ SB122 on)", - "value": "PA_7", - "macro_name": "STM32_D11_SPI_ETHERNET_PIN" - } - }, "extra_labels": ["STM", "STM32F4", "STM32F439", "STM32F439ZI", "STM32F439xx", "STM32F439xI", "FLASH_CMSIS_ALGO"], "supported_toolchains": ["ARM", "uARM", "GCC_ARM", "IAR"], "progen": {"target": "nucleo-f439zi"}, @@ -925,7 +908,7 @@ "detect_code": ["0797"], "features": ["LWIP"], "release_versions": ["2", "5"], - "device_name": "STM32F439ZI" + "device_name" : "STM32F439ZI" }, "NUCLEO_F446RE": { "supported_form_factors": ["ARDUINO", "MORPHO"], @@ -935,7 +918,7 @@ "supported_toolchains": ["ARM", "uARM", "GCC_ARM", "IAR"], "inherits": ["Target"], "detect_code": ["0777"], - "macros": ["TRANSACTION_QUEUE_SIZE_SPI=2", "USB_STM_HAL", "USBHOST_OTHER"], + "macros": ["TRANSACTION_QUEUE_SIZE_SPI=2"], "device_has": ["ANALOGIN", "ANALOGOUT", "CAN", "ERROR_RED", "I2C", "I2CSLAVE", "I2C_ASYNCH", "INTERRUPTIN", "LOWPOWERTIMER", "PORTIN", "PORTINOUT", "PORTOUT", "PWMOUT", "RTC", "SERIAL", "SERIAL_ASYNCH", "SERIAL_FC", "SLEEP", "SPI", "SPISLAVE", "SPI_ASYNCH", "STDIO_MESSAGES"], "release_versions": ["2", "5"], "device_name": "STM32F446RE" @@ -948,10 +931,10 @@ "supported_toolchains": ["ARM", "uARM", "GCC_ARM", "IAR"], "inherits": ["Target"], "detect_code": ["0778"], - "macros": ["TRANSACTION_QUEUE_SIZE_SPI=2", "USB_STM_HAL", "USBHOST_OTHER"], + "macros": ["TRANSACTION_QUEUE_SIZE_SPI=2", "USB_STM_HAL", "USBHOST_OTHER"], "device_has": ["ANALOGIN", "ANALOGOUT", "CAN", "ERROR_RED", "I2C", "I2CSLAVE", "I2C_ASYNCH", "INTERRUPTIN", "LOWPOWERTIMER", "PORTIN", "PORTINOUT", "PORTOUT", "PWMOUT", "RTC", "SERIAL", "SERIAL_ASYNCH", "SERIAL_FC", "SLEEP", "SPI", "SPISLAVE", "SPI_ASYNCH", "STDIO_MESSAGES"], "release_versions": ["2", "5"], - "device_name": "STM32F446ZE" + "device_name" : "STM32F446ZE" }, "B96B_F446VE": { "supported_form_factors": ["ARDUINO", "MORPHO"], @@ -972,13 +955,6 @@ "extra_labels": ["STM", "STM32F7", "STM32F746", "STM32F746xG", "STM32F746ZG"], "supported_toolchains": ["ARM", "uARM", "GCC_ARM", "IAR"], "default_toolchain": "ARM", - "config": { - "d11_configuration": { - "help": "Value: PA_7 for the default board configuration, PB_5 in case of solder bridge update (SB121 off/ SB122 on)", - "value": "PA_7", - "macro_name": "STM32_D11_SPI_ETHERNET_PIN" - } - }, "macros": ["TRANSACTION_QUEUE_SIZE_SPI=2", "USBHOST_OTHER"], "supported_form_factors": ["ARDUINO"], "detect_code": ["0816"], @@ -993,13 +969,6 @@ "extra_labels": ["STM", "STM32F7", "STM32F756", "STM32F756xG", "STM32F756ZG"], "supported_toolchains": ["ARM", "uARM", "GCC_ARM", "IAR"], "default_toolchain": "ARM", - "config": { - "d11_configuration": { - "help": "Value: PA_7 for the default board configuration, PB_5 in case of solder bridge update (SB121 off/ SB122 on)", - "value": "PA_7", - "macro_name": "STM32_D11_SPI_ETHERNET_PIN" - } - }, "supported_form_factors": ["ARDUINO"], "detect_code": ["0819"], "device_has": ["ANALOGIN", "ANALOGOUT", "CAN", "I2C", "I2CSLAVE", "I2C_ASYNCH", "INTERRUPTIN", "LOWPOWERTIMER", "PORTIN", "PORTINOUT", "PORTOUT", "PWMOUT", "RTC", "SERIAL", "SERIAL_ASYNCH", "SLEEP", "SPI", "SPISLAVE", "STDIO_MESSAGES", "TRNG"], @@ -1013,20 +982,13 @@ "extra_labels": ["STM", "STM32F7", "STM32F767", "STM32F767xI", "STM32F767ZI"], "supported_toolchains": ["ARM", "uARM", "GCC_ARM", "IAR"], "default_toolchain": "ARM", - "config": { - "d11_configuration": { - "help": "Value: PA_7 for the default board configuration, PB_5 in case of solder bridge update (SB121 off/ SB122 on)", - "value": "PA_7", - "macro_name": "STM32_D11_SPI_ETHERNET_PIN" - } - }, "supported_form_factors": ["ARDUINO"], "macros": ["TRANSACTION_QUEUE_SIZE_SPI=2", "USBHOST_OTHER"], "detect_code": ["0818"], "device_has": ["ANALOGIN", "ANALOGOUT", "CAN", "I2C", "I2CSLAVE", "I2C_ASYNCH", "INTERRUPTIN", "LOWPOWERTIMER", "PORTIN", "PORTINOUT", "PORTOUT", "PWMOUT", "RTC", "SERIAL", "SERIAL_ASYNCH", "SLEEP", "SPI", "SPISLAVE", "SPI_ASYNCH", "STDIO_MESSAGES", "TRNG"], "features": ["LWIP"], "release_versions": ["2", "5"], - "device_name": "STM32F767ZI" + "device_name" : "STM32F767ZI" }, "NUCLEO_L011K4": { "inherits": ["Target"], @@ -1102,7 +1064,7 @@ "macros": ["TRANSACTION_QUEUE_SIZE_SPI=2"], "device_has": ["ANALOGIN", "ANALOGOUT", "I2C", "I2CSLAVE", "I2C_ASYNCH", "INTERRUPTIN", "LOWPOWERTIMER", "PORTIN", "PORTINOUT", "PORTOUT", "PWMOUT", "RTC", "SERIAL", "SERIAL_FC", "SLEEP", "SPI", "SPISLAVE", "CAN", "SPI_ASYNCH", "STDIO_MESSAGES", "TRNG"], "release_versions": ["2", "5"], - "device_name": "STM32L432KC" + "device_name" : "STM32L432KC" }, "NUCLEO_L476RG": { "supported_form_factors": ["ARDUINO", "MORPHO"], @@ -1149,6 +1111,7 @@ "supported_toolchains": ["ARM", "uARM", "GCC_ARM"], "program_cycle_s": 2, "extra_labels": ["STM", "STM32F4", "STM32F407", "STM32F407xG", "STM32F407VG"], + "macros": ["LSI_VALUE=32000"], "inherits": ["Target"], "macros": ["TRANSACTION_QUEUE_SIZE_SPI=2"], "device_has": ["ANALOGIN", "ANALOGOUT", "I2C", "I2CSLAVE", "INTERRUPTIN", "PORTIN", "PORTINOUT", "PORTOUT", "PWMOUT", "RTC", "SERIAL", "SLEEP", "SPI", "SPISLAVE", "SPI_ASYNCH", "STDIO_MESSAGES"], @@ -1243,19 +1206,6 @@ "release_versions": ["2"], "device_name": "STM32L053C8" }, - "DISCO_L072CZ_LRWAN1": { - "inherits": ["Target"], - "core": "Cortex-M0+", - "default_toolchain": "ARM", - "extra_labels": ["STM", "STM32L0", "STM32L072CZ", "STM32L072xx"], - "supported_toolchains": ["ARM", "uARM", "IAR", "GCC_ARM"], - "supported_form_factors": ["ARDUINO", "MORPHO"], - "macros": ["RTC_LSI=1"], - "detect_code": ["0833"], - "device_has": ["ANALOGIN", "ANALOGOUT", "I2C", "I2CSLAVE", "I2C_ASYNCH", "INTERRUPTIN", "LOWPOWERTIMER", "PORTIN", "PORTINOUT", "PORTOUT", "PWMOUT", "RTC", "SERIAL", "SERIAL_FC", "SERIAL_ASYNCH", "SLEEP", "SPI", "SPISLAVE", "SPI_ASYNCH", "STDIO_MESSAGES", "TRNG"], - "release_versions": ["2", "5"], - "device_name": "STM32L072CZ" - }, "DISCO_F746NG": { "inherits": ["Target"], "core": "Cortex-M7F", @@ -1342,10 +1292,10 @@ "default_toolchain": "ARM", "extra_labels": ["STM", "STM32L1", "STM32L151CC"], "supported_toolchains": ["ARM", "GCC_ARM", "IAR"], + "progen": {"target": "xdot-l151cc"}, "device_has": ["ANALOGIN", "ANALOGOUT", "I2C", "I2CSLAVE", "INTERRUPTIN", "PORTIN", "PORTINOUT", "PORTOUT", "PWMOUT", "RTC", "SERIAL", "SLEEP", "SPI", "SPISLAVE", "SPI_ASYNCH", "STDIO_MESSAGES"], "default_lib": "std", - "release_versions": ["5"], - "device_name": "STM32L151CC" + "release_versions": ["5"] }, "MOTE_L152RC": { "inherits": ["Target"], @@ -1378,33 +1328,12 @@ "extra_labels": ["STM", "STM32F4", "STM32F439", "STM32F439ZI","STM32F439xx", "FLASH_CMSIS_ALGO"], "macros": ["HSE_VALUE=24000000", "HSE_STARTUP_TIMEOUT=5000", "CB_INTERFACE_SDIO","CB_CHIP_WL18XX","SUPPORT_80211D_ALWAYS","WLAN_ENABLED","MBEDTLS_ARC4_C","MBEDTLS_DES_C","MBEDTLS_MD4_C","MBEDTLS_MD5_C","MBEDTLS_SHA1_C"], "inherits": ["Target"], - "device_has": ["ANALOGIN", "CAN", "EMAC", "I2C", "I2CSLAVE", "INTERRUPTIN", "PORTIN", "PORTINOUT", "PORTOUT", "PWMOUT", "SERIAL", "SPI", "SPISLAVE", "STDIO_MESSAGES", "TRNG", "FLASH"], + "device_has": ["ANALOGIN", "CAN", "EMAC", "I2C", "I2CSLAVE", "INTERRUPTIN", "PORTIN", "PORTINOUT", "PORTOUT", "PWMOUT", "SERIAL", "SLEEP", "SPI", "SPISLAVE", "STDIO_MESSAGES", "TRNG", "FLASH"], "features": ["LWIP"], "release_versions": ["5"], "device_name": "STM32F439ZI", "bootloader_supported": true }, - "UBLOX_C030": { - "supported_form_factors": ["ARDUINO"], - "core": "Cortex-M4F", - "default_toolchain": "ARM", - "supported_toolchains": ["GCC_ARM", "ARM", "IAR"], - "extra_labels": ["STM", "STM32F4", "STM32F437", "STM32F437VG", "STM32F437xx", "STM32F437xG"], - "macros": ["TRANSACTION_QUEUE_SIZE_SPI=2", "RTC_LSI=1", "HSE_VALUE=12000000"], - "inherits": ["Target"], - "device_has": ["ANALOGIN", "ANALOGOUT", "I2C", "I2CSLAVE", "INTERRUPTIN", "PORTIN", "PORTINOUT", "PORTOUT", "PWMOUT", "SERIAL", "SLEEP", "RTC", "SPI", "SPISLAVE", "STDIO_MESSAGES", "TRNG"], - "features": ["LWIP"], - "public": false, - "device_name": "STM32F437VG" - }, - "UBLOX_C030_U201": { - "inherits": ["UBLOX_C030"], - "release_versions": ["5"] - }, - "UBLOX_C030_N211": { - "inherits": ["UBLOX_C030"], - "release_versions": ["5"] - }, "NZ32_SC151": { "inherits": ["Target"], "core": "Cortex-M3", @@ -1906,6 +1835,29 @@ "features": ["BLE"], "release_versions": ["2", "5"] }, + "RZ_A1H": { + "supported_form_factors": ["ARDUINO"], + "core": "Cortex-A9", + "program_cycle_s": 2, + "extra_labels": ["RENESAS", "MBRZA1H"], + "supported_toolchains": ["ARM", "GCC_ARM", "IAR"], + "inherits": ["Target"], + "device_has": ["ANALOGIN", "CAN", "ERROR_PATTERN", "ETHERNET", "I2C", "I2CSLAVE", "I2C_ASYNCH", "INTERRUPTIN", "PORTIN", "PORTINOUT", "PORTOUT", "PWMOUT", "RTC", "SERIAL", "SERIAL_ASYNCH", "SERIAL_FC", "SPI", "SPISLAVE", "SPI_ASYNCH", "STDIO_MESSAGES"], + "features": ["LWIP"], + "release_versions": ["2", "5"] + }, + "VK_RZ_A1H": { + "inherits": ["Target"], + "core": "Cortex-A9", + "extra_labels": ["RENESAS", "VKRZA1H"], + "supported_toolchains": ["ARM", "GCC_ARM", "IAR"], + "default_toolchain": "ARM", + "program_cycle_s": 2, + "device_has": ["ANALOGIN", "CAN", "ERROR_PATTERN", "ETHERNET", "I2C", "I2CSLAVE", "INTERRUPTIN", "PORTIN", "PORTINOUT", "PORTOUT", "PWMOUT", "RTC", "SERIAL", "SERIAL_FC", "SPI", "SPISLAVE", "STDIO_MESSAGES"], + "features": ["LWIP"], + "default_lib": "std", + "release_versions": ["2", "5"] + }, "MAXWSNENV": { "inherits": ["Target"], "core": "Cortex-M3", @@ -2485,27 +2437,27 @@ "supported_form_factors": ["ARDUINO"], "core": "Cortex-M0", "extra_labels": ["WIZNET", "W7500x", "WIZwiki_W7500"], - "supported_toolchains": ["uARM", "ARM", "GCC_ARM", "IAR"], + "supported_toolchains": ["uARM", "ARM"], "inherits": ["Target"], "device_has": ["ANALOGIN", "I2C", "INTERRUPTIN", "PORTIN", "PORTINOUT", "PORTOUT", "PWMOUT", "RTC", "SERIAL", "SPI", "SPISLAVE", "STDIO_MESSAGES"], - "release_versions": ["2", "5"] + "release_versions": ["2"] }, "WIZWIKI_W7500P": { "supported_form_factors": ["ARDUINO"], "core": "Cortex-M0", "extra_labels": ["WIZNET", "W7500x", "WIZwiki_W7500P"], - "supported_toolchains": ["uARM", "ARM", "GCC_ARM", "IAR"], + "supported_toolchains": ["uARM", "ARM"], "inherits": ["Target"], "device_has": ["ANALOGIN", "I2C", "INTERRUPTIN", "PORTIN", "PORTINOUT", "PORTOUT", "PWMOUT", "RTC", "SERIAL", "SPI", "SPISLAVE", "STDIO_MESSAGES"], - "release_versions": ["2", "5"] + "release_versions": ["2"] }, "WIZWIKI_W7500ECO": { "inherits": ["Target"], "core": "Cortex-M0", "extra_labels": ["WIZNET", "W7500x", "WIZwiki_W7500ECO"], - "supported_toolchains": ["uARM", "ARM", "GCC_ARM", "IAR"], + "supported_toolchains": ["uARM", "ARM"], "device_has": ["ANALOGIN", "I2C", "INTERRUPTIN", "PORTIN", "PORTINOUT", "PORTOUT", "PWMOUT", "RTC", "SERIAL", "SPI", "SPISLAVE", "STDIO_MESSAGES"], - "release_versions": ["2", "5"] + "release_versions": ["2"] }, "SAMR21G18A": { "inherits": ["Target"], @@ -2525,7 +2477,7 @@ "supported_toolchains": ["GCC_ARM", "ARM", "uARM"], "device_has": ["ANALOGIN", "ANALOGOUT", "I2C", "I2CSLAVE", "I2C_ASYNCH", "INTERRUPTIN", "PORTIN", "PORTINOUT", "PORTOUT", "PWMOUT", "RTC", "SERIAL", "SERIAL_ASYNCH", "SERIAL_FC", "SLEEP", "SPI", "SPISLAVE", "SPI_ASYNCH"], "release_versions": ["2"], - "device_name": "ATSAMD21J18A" + "device_name" : "ATSAMD21J18A" }, "SAMD21G18A": { "inherits": ["Target"], @@ -2567,12 +2519,10 @@ "BLE_STACK_SUPPORT_REQD", "SOFTDEVICE_PRESENT", "S130", - "TARGET_MCU_NRF51822", - "CMSIS_VECTAB_VIRTUAL", - "CMSIS_VECTAB_VIRTUAL_HEADER_FILE=\"cmsis_nvic.h\"" + "TARGET_MCU_NRF51822" ], "MERGE_BOOTLOADER": false, - "extra_labels": ["NORDIC", "MCU_NRF51", "MCU_NRF51822_UNIFIED", "NRF5", "SDK11"], + "extra_labels": ["NORDIC", "MCU_NRF51", "MCU_NRF51822_UNIFIED", "NRF5"], "OUTPUT_EXT": "hex", "is_disk_virtual": true, "supported_toolchains": ["ARM", "GCC_ARM", "IAR"], @@ -2627,8 +2577,8 @@ "MCU_NRF52": { "inherits": ["Target"], "core": "Cortex-M4F", - "macros": ["NRF52", "TARGET_NRF52832", "BLE_STACK_SUPPORT_REQD", "SOFTDEVICE_PRESENT", "S132", "CMSIS_VECTAB_VIRTUAL", "CMSIS_VECTAB_VIRTUAL_HEADER_FILE=\"cmsis_nvic.h\""], - "extra_labels": ["NORDIC", "MCU_NRF52", "MCU_NRF52832", "NRF5", "SDK11"], + "macros": ["NRF52", "TARGET_NRF52832", "BLE_STACK_SUPPORT_REQD", "SOFTDEVICE_PRESENT", "S132"], + "extra_labels": ["NORDIC", "MCU_NRF52", "MCU_NRF52832", "NRF5"], "OUTPUT_EXT": "hex", "is_disk_virtual": true, "supported_toolchains": ["GCC_ARM", "ARM", "IAR"], @@ -2707,8 +2657,8 @@ "MCU_NRF52840": { "inherits": ["Target"], "core": "Cortex-M4F", - "macros": ["TARGET_NRF52840", "BLE_STACK_SUPPORT_REQD", "SOFTDEVICE_PRESENT", "S140", "NRF_SD_BLE_API_VERSION=5", "NRF52840_XXAA", "NRF_DFU_SETTINGS_VERSION=1", "NRF_SD_BLE_API_VERSION=5", "CMSIS_VECTAB_VIRTUAL", "CMSIS_VECTAB_VIRTUAL_HEADER_FILE=\"cmsis_nvic.h\""], - "extra_labels": ["NORDIC", "MCU_NRF52840", "NRF5", "SDK13"], + "macros": ["TARGET_NRF52840", "BLE_STACK_SUPPORT_REQD", "SOFTDEVICE_PRESENT", "S140", "NRF_SD_BLE_API_VERSION=5", "NRF52840_XXAA", "NRF_DFU_SETTINGS_VERSION=1", "NRF_SD_BLE_API_VERSION=5"], + "extra_labels": ["NORDIC", "MCU_NRF52840", "NRF5_SDK13"], "OUTPUT_EXT": "hex", "is_disk_virtual": true, "supported_toolchains": ["GCC_ARM", "ARM", "IAR"], @@ -2761,15 +2711,14 @@ "NUMAKER_PFM_NUC472": { "core": "Cortex-M4F", "default_toolchain": "ARM", - "extra_labels": ["NUVOTON", "NUC472", "NU_XRAM_SUPPORTED", "FLASH_CMSIS_ALGO"], + "extra_labels": ["NUVOTON", "NUC472", "NU_XRAM_SUPPORTED"], "is_disk_virtual": true, "supported_toolchains": ["ARM", "uARM", "GCC_ARM", "IAR"], "inherits": ["Target"], - "device_has": ["ANALOGIN", "I2C", "I2CSLAVE", "I2C_ASYNCH", "INTERRUPTIN", "LOWPOWERTIMER", "PORTIN", "PORTINOUT", "PORTOUT", "PWMOUT", "RTC", "SERIAL", "SERIAL_ASYNCH", "SERIAL_FC", "STDIO_MESSAGES", "SLEEP", "SPI", "SPISLAVE", "SPI_ASYNCH", "TRNG", "CAN", "FLASH"], + "device_has": ["ANALOGIN", "I2C", "I2CSLAVE", "I2C_ASYNCH", "INTERRUPTIN", "LOWPOWERTIMER", "PORTIN", "PORTINOUT", "PORTOUT", "PWMOUT", "RTC", "SERIAL", "SERIAL_ASYNCH", "SERIAL_FC", "STDIO_MESSAGES", "SLEEP", "SPI", "SPISLAVE", "SPI_ASYNCH", "TRNG", "CAN"], "features": ["LWIP"], "release_versions": ["5"], - "device_name": "NUC472HI8AE", - "bootloader_supported": true + "device_name": "NUC472HI8AE" }, "NCS36510": { "inherits": ["Target"], @@ -2810,15 +2759,14 @@ "NUMAKER_PFM_M453": { "core": "Cortex-M4F", "default_toolchain": "ARM", - "extra_labels": ["NUVOTON", "M451", "NUMAKER_PFM_M453", "FLASH_CMSIS_ALGO"], + "extra_labels": ["NUVOTON", "M451", "NUMAKER_PFM_M453"], "is_disk_virtual": true, "supported_toolchains": ["ARM", "uARM", "GCC_ARM", "IAR"], "inherits": ["Target"], "progen": {"target": "numaker-pfm-m453"}, - "device_has": ["ANALOGIN", "I2C", "I2CSLAVE", "I2C_ASYNCH", "INTERRUPTIN", "LOWPOWERTIMER", "PORTIN", "PORTINOUT", "PORTOUT", "PWMOUT", "RTC", "SERIAL", "SERIAL_ASYNCH", "SERIAL_FC", "STDIO_MESSAGES", "SLEEP", "SPI", "SPISLAVE", "SPI_ASYNCH", "CAN", "FLASH"], + "device_has": ["ANALOGIN", "I2C", "I2CSLAVE", "I2C_ASYNCH", "INTERRUPTIN", "LOWPOWERTIMER", "PORTIN", "PORTINOUT", "PORTOUT", "PWMOUT", "RTC", "SERIAL", "SERIAL_ASYNCH", "SERIAL_FC", "STDIO_MESSAGES", "SLEEP", "SPI", "SPISLAVE", "SPI_ASYNCH", "CAN"], "release_versions": ["2", "5"], - "device_name": "M453VG6AE", - "bootloader_supported": true + "device_name": "M453VG6AE" }, "HI2110": { "inherits": ["Target"], diff --git a/tools/build.py b/tools/build.py index 52c034ca132..999ebb3700a 100644 --- a/tools/build.py +++ b/tools/build.py @@ -68,6 +68,17 @@ default=False, help="Compile the rpc library") + parser.add_argument("-e", "--eth", + action="store_true", dest="eth", + default=False, + help="Compile the ethernet library") + + parser.add_argument("-U", "--usb_host", + action="store_true", + dest="usb_host", + default=False, + help="Compile the USB Host library") + parser.add_argument("-u", "--usb", action="store_true", dest="usb", @@ -80,6 +91,12 @@ default=False, help="Compile the DSP library") + parser.add_argument("-b", "--ublox", + action="store_true", + dest="ublox", + default=False, + help="Compile the u-blox library") + parser.add_argument( "--cpputest", action="store_true", dest="cpputest_lib", @@ -157,12 +174,20 @@ libraries = [] # Additional Libraries + if options.rtos: + libraries.extend(["rtx", "rtos"]) if options.rpc: libraries.extend(["rpc"]) + if options.eth: + libraries.append("eth") if options.usb: libraries.append("usb") + if options.usb_host: + libraries.append("usb_host") if options.dsp: libraries.extend(["dsp"]) + if options.ublox: + libraries.extend(["rtx", "rtos", "usb_host", "ublox"]) if options.cpputest_lib: libraries.extend(["cpputest"]) diff --git a/tools/build_api.py b/tools/build_api.py index f5e6d526c00..865971452cb 100644 --- a/tools/build_api.py +++ b/tools/build_api.py @@ -17,16 +17,12 @@ import re import tempfile -import datetime -import uuid from types import ListType from shutil import rmtree from os.path import join, exists, dirname, basename, abspath, normpath, splitext -from os.path import relpath from os import linesep, remove, makedirs from time import time from intelhex import IntelHex -from json import load, dump from tools.utils import mkdir, run_cmd, run_cmd_ext, NotSupportedException,\ ToolException, InvalidReleaseTargetException, intelhex_offset @@ -106,8 +102,6 @@ def add_result_to_report(report, result): report - the report to append to result - the result to append """ - result["date"] = datetime.datetime.utcnow().isoformat() - result["uuid"] = str(uuid.uuid1()) target = result["target_name"] toolchain = result["toolchain_name"] id_name = result['id'] @@ -151,8 +145,6 @@ def get_config(src_paths, target, toolchain_name): prev_features = features toolchain.config.validate_config() - if toolchain.config.has_regions: - _ = list(toolchain.config.regions) cfg, macros = toolchain.config.get_config_data() features = toolchain.config.get_features() @@ -291,8 +283,6 @@ def add_regions_to_profile(profile, config, toolchain_class): config - the configuration object that owns the region toolchain_class - the class of the toolchain being used """ - if not profile: - return regions = list(config.regions) for region in regions: for define in [(region.name.upper() + "_ADDR", region.start), @@ -318,7 +308,7 @@ def prepare_toolchain(src_paths, build_dir, target, toolchain_name, Positional arguments: src_paths - the paths to source directories - target - ['LPC1768', 'LPC11U24', etc.] + target - ['LPC1768', 'LPC11U24', 'LPC2368', etc.] toolchain_name - ['ARM', 'uARM', 'GCC_ARM', 'GCC_CR'] Keyword arguments: @@ -491,8 +481,8 @@ def build_project(src_paths, build_path, target, toolchain_name, build_profile=build_profile) # The first path will give the name to the library - name = (name or toolchain.config.name or - basename(normpath(abspath(src_paths[0])))) + if name is None: + name = basename(normpath(abspath(src_paths[0]))) toolchain.info("Building project %s (%s, %s)" % (name, toolchain.target.name, toolchain_name)) @@ -558,9 +548,6 @@ def build_project(src_paths, build_path, target, toolchain_name, cur_result["output"] = toolchain.get_output() + memap_table cur_result["result"] = "OK" cur_result["memory_usage"] = toolchain.map_outputs - cur_result["bin"] = res - cur_result["elf"] = splitext(res)[0] + ".elf" - cur_result.update(toolchain.report) add_result_to_report(report, cur_result) @@ -662,7 +649,6 @@ def build_library(src_paths, build_path, target, toolchain_name, prep_report(report, toolchain.target.name, toolchain_name, id_name) cur_result = create_result(toolchain.target.name, toolchain_name, id_name, description) - cur_result['type'] = 'library' if properties != None: prep_properties(properties, toolchain.target.name, toolchain_name, vendor_label) @@ -1040,14 +1026,13 @@ def build_mbed_libs(target, toolchain_name, verbose=False, # A number of compiled files need to be copied as objects as opposed to # way the linker search for symbols in archives. These are: - # - mbed_retarget.o: to make sure that the C standard lib symbols get + # - retarget.o: to make sure that the C standard lib symbols get # overridden - # - mbed_board.o: mbed_die is weak + # - board.o: mbed_die is weak # - mbed_overrides.o: this contains platform overrides of various # weak SDK functions - # - mbed_main.o: this contains main redirection - separate_names, separate_objects = ['mbed_retarget.o', 'mbed_board.o', - 'mbed_overrides.o', 'mbed_main.o'], [] + separate_names, separate_objects = ['retarget.o', 'board.o', + 'mbed_overrides.o'], [] for obj in objects: for name in separate_names: @@ -1113,75 +1098,6 @@ def get_unique_supported_toolchains(release_targets=None): return unique_supported_toolchains -def mcu_toolchain_list(release_version='5'): - """ Shows list of toolchains - - """ - - if isinstance(release_version, basestring): - # Force release_version to lowercase if it is a string - release_version = release_version.lower() - else: - # Otherwise default to printing all known targets and toolchains - release_version = 'all' - - - version_release_targets = {} - version_release_target_names = {} - - for version in RELEASE_VERSIONS: - version_release_targets[version] = get_mbed_official_release(version) - version_release_target_names[version] = [x[0] for x in - version_release_targets[ - version]] - - if release_version in RELEASE_VERSIONS: - release_targets = version_release_targets[release_version] - else: - release_targets = None - - unique_supported_toolchains = get_unique_supported_toolchains( - release_targets) - columns = ["mbed OS %s" % x for x in RELEASE_VERSIONS] + unique_supported_toolchains - return "\n".join(columns) - - -def mcu_target_list(release_version='5'): - """ Shows target list - - """ - - if isinstance(release_version, basestring): - # Force release_version to lowercase if it is a string - release_version = release_version.lower() - else: - # Otherwise default to printing all known targets and toolchains - release_version = 'all' - - - version_release_targets = {} - version_release_target_names = {} - - for version in RELEASE_VERSIONS: - version_release_targets[version] = get_mbed_official_release(version) - version_release_target_names[version] = [x[0] for x in - version_release_targets[ - version]] - - if release_version in RELEASE_VERSIONS: - release_targets = version_release_targets[release_version] - else: - release_targets = None - - target_names = [] - - if release_targets: - target_names = [x[0] for x in release_targets] - else: - target_names = TARGET_NAMES - - return "\n".join(target_names) - def mcu_toolchain_matrix(verbose_html=False, platform_filter=None, release_version='5'): @@ -1373,24 +1289,3 @@ def write_build_report(build_report, template_filename, filename): placeholder.write(template.render( failing_builds=build_report_failing, passing_builds=build_report_passing)) - - -def merge_build_data(filename, toolchain_report, app_type): - path_to_file = dirname(abspath(filename)) - try: - build_data = load(open(filename)) - except (IOError, ValueError): - build_data = {'builds': []} - for tgt in toolchain_report.values(): - for tc in tgt.values(): - for project in tc.values(): - for build in project: - try: - build[0]['elf'] = relpath(build[0]['elf'], path_to_file) - build[0]['bin'] = relpath(build[0]['bin'], path_to_file) - except KeyError: - pass - if 'type' not in build[0]: - build[0]['type'] = app_type - build_data['builds'].append(build[0]) - dump(build_data, open(filename, "wb"), indent=4, separators=(',', ': ')) diff --git a/tools/build_travis.py b/tools/build_travis.py index 7355559b656..d40404d9af8 100644 --- a/tools/build_travis.py +++ b/tools/build_travis.py @@ -24,237 +24,250 @@ ################################################################################ # Configure builds here -# "libs" can contain "dsp", "usb" +# "libs" can contain "dsp", "rtos", "eth", "usb_host", "usb", "ublox" build_list = ( - { "target": "LPC1768", "toolchains": "GCC_ARM", "libs": ["dsp", "usb"] }, - { "target": "LPC11U24", "toolchains": "GCC_ARM", "libs": ["dsp"] }, + { "target": "LPC1768", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "eth", "usb"] }, + { "target": "LPC2368", "toolchains": "GCC_ARM", "libs": [] }, + { "target": "LPC2460", "toolchains": "GCC_ARM", "libs": ["rtos", "usb"] }, + { "target": "LPC11U24", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos"] }, { "target": "OC_MBUINO", "toolchains": "GCC_ARM", "libs": [] }, { "target": "LPC11U24_301", "toolchains": "GCC_ARM", "libs": [] }, { "target": "B96B_F446VE", "toolchains": "GCC_ARM", "libs": ["dsp"] }, { "target": "NUCLEO_L053R8", "toolchains": "GCC_ARM", "libs": ["dsp"] }, - { "target": "NUCLEO_L152RE", "toolchains": "GCC_ARM", "libs": ["dsp"] }, + { "target": "NUCLEO_L152RE", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos"] }, { "target": "NUCLEO_F030R8", "toolchains": "GCC_ARM", "libs": ["dsp"] }, { "target": "NUCLEO_F031K6", "toolchains": "GCC_ARM", "libs": ["dsp"] }, { "target": "NUCLEO_F042K6", "toolchains": "GCC_ARM", "libs": ["dsp"] }, { "target": "NUCLEO_F070RB", "toolchains": "GCC_ARM", "libs": ["dsp"] }, - { "target": "NUCLEO_F072RB", "toolchains": "GCC_ARM", "libs": ["dsp"] }, - { "target": "NUCLEO_F091RC", "toolchains": "GCC_ARM", "libs": ["dsp"] }, - { "target": "NUCLEO_F103RB", "toolchains": "GCC_ARM" }, - { "target": "NUCLEO_F207ZG", "toolchains": "GCC_ARM", "libs": ["dsp", "usb"] }, - { "target": "NUCLEO_F302R8", "toolchains": "GCC_ARM", "libs": ["dsp"] }, - { "target": "NUCLEO_F303K8", "toolchains": "GCC_ARM", "libs": ["dsp"] }, - { "target": "NUCLEO_F303RE", "toolchains": "GCC_ARM", "libs": ["dsp"] }, - { "target": "NUCLEO_F303ZE", "toolchains": "GCC_ARM", "libs": ["dsp", "usb"] }, - { "target": "NUCLEO_F334R8", "toolchains": "GCC_ARM", "libs": ["dsp"] }, - { "target": "NUCLEO_F401RE", "toolchains": "GCC_ARM", "libs": ["dsp", "usb"] }, - { "target": "NUCLEO_F410RB", "toolchains": "GCC_ARM", "libs": ["dsp"] }, - { "target": "NUCLEO_F411RE", "toolchains": "GCC_ARM", "libs": ["dsp", "usb"] }, - { "target": "NUCLEO_F412ZG", "toolchains": "GCC_ARM", "libs": ["dsp"] }, + { "target": "NUCLEO_F072RB", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos"] }, + { "target": "NUCLEO_F091RC", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos"] }, + { "target": "NUCLEO_F103RB", "toolchains": "GCC_ARM", "libs": ["rtos"] }, + { "target": "NUCLEO_F207ZG", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "usb"] }, + { "target": "NUCLEO_F302R8", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos"] }, + { "target": "NUCLEO_F303K8", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos"] }, + { "target": "NUCLEO_F303RE", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos"] }, + { "target": "NUCLEO_F303ZE", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "usb"] }, + { "target": "NUCLEO_F334R8", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos"] }, + { "target": "NUCLEO_F401RE", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "usb"] }, + { "target": "NUCLEO_F410RB", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos"] }, + { "target": "NUCLEO_F411RE", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "usb"] }, + { "target": "NUCLEO_F412ZG", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos"] }, { "target": "NUCLEO_L432KC", "toolchains": "GCC_ARM", "libs": ["dsp"] }, - { "target": "NUCLEO_L476RG", "toolchains": "GCC_ARM", "libs": ["dsp"] }, + { "target": "NUCLEO_L476RG", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos"] }, { "target": "NUCLEO_L011K4", "toolchains": "GCC_ARM", "libs": ["dsp"] }, { "target": "NUCLEO_L031K6", "toolchains": "GCC_ARM", "libs": ["dsp"] }, { "target": "NUCLEO_L073RZ", "toolchains": "GCC_ARM", "libs": ["dsp"] }, - { "target": "NUCLEO_F429ZI", "toolchains": "GCC_ARM", "libs": ["dsp", "usb"] }, - { "target": "NUCLEO_F446RE", "toolchains": "GCC_ARM", "libs": ["dsp", "usb"] }, - { "target": "NUCLEO_F446ZE", "toolchains": "GCC_ARM", "libs": ["dsp", "usb"] }, - { "target": "NUCLEO_F746ZG", "toolchains": "GCC_ARM", "libs": ["dsp", "usb"] }, - { "target": "NUCLEO_F767ZI", "toolchains": "GCC_ARM", "libs": ["dsp", "usb"] }, + { "target": "NUCLEO_F429ZI", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "usb"] }, + { "target": "NUCLEO_F446RE", "toolchains": "GCC_ARM", "libs": ["dsp"] }, + { "target": "NUCLEO_F446ZE", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "usb"] }, + { "target": "NUCLEO_F746ZG", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "usb" ] }, + { "target": "NUCLEO_F767ZI", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "usb"] }, - { "target": "MOTE_L152RC", "toolchains": "GCC_ARM", "libs": ["dsp"] }, + { "target": "MOTE_L152RC", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos"] }, { "target": "ELMO_F411RE", "toolchains": "GCC_ARM", "libs": ["dsp"] }, - { "target": "MTS_MDOT_F405RG", "toolchains": "GCC_ARM", "libs": ["dsp"] }, - { "target": "MTS_MDOT_F411RE", "toolchains": "GCC_ARM", "libs": ["dsp"] }, + { "target": "MTS_MDOT_F405RG", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos"] }, + { "target": "MTS_MDOT_F411RE", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos"] }, { "target": "MTS_DRAGONFLY_F411RE", "toolchains": "GCC_ARM", "libs": ["dsp"] }, - { "target": "ARCH_MAX", "toolchains": "GCC_ARM", "libs": ["dsp"] }, + { "target": "ARCH_MAX", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos"] }, { "target": "DISCO_F051R8", "toolchains": "GCC_ARM", "libs": ["dsp"] }, - { "target": "DISCO_F303VC", "toolchains": "GCC_ARM", "libs": ["dsp"] }, - { "target": "DISCO_F334C8", "toolchains": "GCC_ARM", "libs": ["dsp"] }, + { "target": "DISCO_F303VC", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos"] }, + { "target": "DISCO_F334C8", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos"] }, { "target": "DISCO_F401VC", "toolchains": "GCC_ARM", "libs": ["dsp"] }, - { "target": "DISCO_F407VG", "toolchains": "GCC_ARM", "libs": ["dsp", "usb"] }, - { "target": "DISCO_F429ZI", "toolchains": "GCC_ARM", "libs": ["dsp"] }, - { "target": "DISCO_F469NI", "toolchains": "GCC_ARM", "libs": ["dsp"] }, + { "target": "DISCO_F407VG", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "usb"] }, + { "target": "DISCO_F429ZI", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos"] }, + { "target": "DISCO_F469NI", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos"] }, { "target": "DISCO_F746NG", "toolchains": "GCC_ARM", "libs": ["dsp"] }, - { "target": "DISCO_F769NI", "toolchains": "GCC_ARM", "libs": ["dsp"] }, + { "target": "DISCO_F769NI", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos"] }, - { "target": "LPC1114", "toolchains": "GCC_ARM", "libs": ["dsp"] }, - { "target": "LPC11U35_401", "toolchains": "GCC_ARM", "libs": ["dsp"] }, - { "target": "UBLOX_C027", "toolchains": "GCC_ARM", "libs": ["dsp"] }, + { "target": "LPC1114", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos"] }, + { "target": "LPC11U35_401", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos"] }, + { "target": "UBLOX_C027", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos"] }, { "target": "LPC11U35_501", "toolchains": "GCC_ARM", "libs": ["dsp"] }, - { "target": "LPC11U68", "toolchains": "GCC_ARM", "libs": ["dsp"] }, + { "target": "LPC11U68", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos"] }, { "target": "LPC11U37H_401", "toolchains": "GCC_ARM", "libs": ["dsp"] }, - { "target": "KL05Z", "toolchains": "GCC_ARM", "libs": ["dsp"] }, - { "target": "KL25Z", "toolchains": "GCC_ARM", "libs": ["dsp", "usb"] }, - { "target": "KL27Z", "toolchains": "GCC_ARM", "libs": ["dsp", "usb"] }, - { "target": "KL43Z", "toolchains": "GCC_ARM", "libs": ["dsp", "usb"] }, - { "target": "KL46Z", "toolchains": "GCC_ARM", "libs": ["dsp", "usb"] }, + { "target": "KL05Z", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos"] }, + { "target": "KL25Z", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "usb"] }, + { "target": "KL27Z", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "usb"] }, + { "target": "KL43Z", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "usb"] }, + { "target": "KL46Z", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "usb"] }, { "target": "K20D50M", "toolchains": "GCC_ARM", "libs": ["dsp"] }, { "target": "TEENSY3_1", "toolchains": "GCC_ARM", "libs": ["dsp"] }, - { "target": "K64F", "toolchains": "GCC_ARM", "libs": ["dsp", "usb"] }, - { "target": "K22F", "toolchains": "GCC_ARM", "libs": ["dsp", "usb"] }, - { "target": "LPC4088", "toolchains": "GCC_ARM", "libs": ["dsp", "usb"] }, - { "target": "ARCH_PRO", "toolchains": "GCC_ARM", "libs": ["dsp"] }, - { "target": "LPC1549", "toolchains": "GCC_ARM", "libs": ["dsp"] }, - { "target": "NRF51822", "toolchains": "GCC_ARM", "libs": ["dsp"] }, + { "target": "K64F", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "usb"] }, + { "target": "K22F", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "usb"] }, + { "target": "LPC4088", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "usb"] }, + { "target": "ARCH_PRO", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos"] }, + { "target": "LPC1549", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos"] }, + { "target": "NRF51822", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos"] }, { "target": "DELTA_DFCM_NNN40", "toolchains": "GCC_ARM", "libs": ["dsp"] }, - { "target": "NRF51_DK", "toolchains": "GCC_ARM", "libs": ["dsp"] }, - { "target": "NRF51_MICROBIT", "toolchains": "GCC_ARM", "libs": ["dsp"] }, + { "target": "NRF51_DK", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos"] }, + { "target": "NRF51_MICROBIT", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos"] }, { "target": "EFM32ZG_STK3200", "toolchains": "GCC_ARM", "libs": ["dsp"] }, - { "target": "EFM32HG_STK3400", "toolchains": "GCC_ARM", "libs": ["dsp", "usb"] }, - { "target": "EFM32LG_STK3600", "toolchains": "GCC_ARM", "libs": ["dsp", "usb"] }, - { "target": "EFM32GG_STK3700", "toolchains": "GCC_ARM", "libs": ["dsp", "usb"] }, - { "target": "EFM32WG_STK3800", "toolchains": "GCC_ARM", "libs": ["dsp", "usb"] }, - { "target": "EFM32PG_STK3401", "toolchains": "GCC_ARM", "libs": ["dsp"] }, + { "target": "EFM32HG_STK3400", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "usb"] }, + { "target": "EFM32LG_STK3600", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "usb"] }, + { "target": "EFM32GG_STK3700", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "usb"] }, + { "target": "EFM32WG_STK3800", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "usb"] }, + { "target": "EFM32PG_STK3401", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos"] }, { "target": "MAXWSNENV", "toolchains": "GCC_ARM", "libs": ["dsp"] }, { "target": "MAX32600MBED", "toolchains": "GCC_ARM", "libs": ["dsp"] }, { "target": "MAX32620HSP", "toolchains": "GCC_ARM", "libs": ["dsp"] }, + { "target": "RZ_A1H", "toolchains": "GCC_ARM", "libs": [] }, + { "target": "SAMR21G18A", "toolchains": "GCC_ARM", "libs": ["dsp"] }, { "target": "SAMD21J18A", "toolchains": "GCC_ARM", "libs": ["dsp"] }, { "target": "SAMD21G18A", "toolchains": "GCC_ARM", "libs": ["dsp"] }, { "target": "SAML21J18A", "toolchains": "GCC_ARM", "libs": ["dsp"] }, - - { "target": "DISCO_L476VG", "toolchains": "GCC_ARM", "libs": ["dsp", "usb"] }, - { "target": "DISCO_L072CZ_LRWAN1", "toolchains": "GCC_ARM", "libs": ["dsp"] }, - { "target": "NUMAKER_PFM_NUC472", "toolchains": "GCC_ARM", "libs": ["dsp", "usb"] }, - { "target": "NUMAKER_PFM_M453", "toolchains": "GCC_ARM", "libs": ["dsp", "usb"] }, + { "target": "DISCO_L476VG", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "usb"] }, + + { "target": "NUMAKER_PFM_NUC472", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "usb"] }, + { "target": "NUMAKER_PFM_M453", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "usb"] }, ) ################################################################################ -# Configure example test building (linking against external mbed SDK libraries) +# Configure example test building (linking against external mbed SDK libraries like rtos) linking_list = [ {"target": "LPC1768", "toolchains": "GCC_ARM", "tests": {"" : ["MBED_2", "MBED_10", "MBED_11", "MBED_15", "MBED_16", "MBED_17"], + "eth" : ["NET_1", "NET_2", "NET_3", "NET_4"], + "rtos" : ["RTOS_1", "RTOS_2", "RTOS_3"], "usb" : ["USB_1", "USB_2" ,"USB_3"], } }, {"target": "K64F", "toolchains": "GCC_ARM", "tests": {"" : ["MBED_2", "MBED_10", "MBED_11", "MBED_16"], + "rtos" : ["RTOS_1", "RTOS_2", "RTOS_3"], "usb" : ["USB_1", "USB_2" ,"USB_3"], } }, {"target": "K22F", "toolchains": "GCC_ARM", "tests": {"" : ["MBED_2", "MBED_10", "MBED_11", "MBED_16"], + "rtos" : ["RTOS_1", "RTOS_2", "RTOS_3"], "usb" : ["USB_1", "USB_2" ,"USB_3"], } }, {"target": "KL43Z", "toolchains": "GCC_ARM", "tests": {"" : ["MBED_2", "MBED_10", "MBED_11", "MBED_16"], - "usb" : ["USB_1", "USB_2" ,"USB_3"], - } - }, - {"target": "NUCLEO_F446RE", - "toolchains": "GCC_ARM", - "tests": {"" : ["MBED_2", "MBED_10", "MBED_11", "MBED_16"], + "rtos" : ["RTOS_1", "RTOS_2", "RTOS_3"], "usb" : ["USB_1", "USB_2" ,"USB_3"], } }, {"target": "NUCLEO_F446ZE", "toolchains": "GCC_ARM", "tests": {"" : ["MBED_2", "MBED_10", "MBED_11", "MBED_16"], + "rtos" : ["RTOS_1", "RTOS_2", "RTOS_3"], "usb" : ["USB_1", "USB_2" ,"USB_3"], - } - }, + } + }, {"target": "NUCLEO_F401RE", "toolchains": "GCC_ARM", "tests": {"" : ["MBED_2", "MBED_10", "MBED_11", "MBED_16"], + "rtos" : ["RTOS_1", "RTOS_2", "RTOS_3"], "usb" : ["USB_1", "USB_2" ,"USB_3"], } }, {"target": "NUCLEO_F411RE", "toolchains": "GCC_ARM", "tests": {"" : ["MBED_2", "MBED_10", "MBED_11", "MBED_16"], + "rtos" : ["RTOS_1", "RTOS_2", "RTOS_3"], "usb" : ["USB_1", "USB_2" ,"USB_3"], - } - }, + } + }, {"target": "NUCLEO_F412ZG", "toolchains": "GCC_ARM", "tests": {"" : ["MBED_2", "MBED_10", "MBED_11", "MBED_16"], + "rtos" : ["RTOS_1", "RTOS_2", "RTOS_3"], } }, {"target": "NUCLEO_F429ZI", "toolchains": "GCC_ARM", "tests": {"" : ["MBED_2", "MBED_10", "MBED_11", "MBED_16"], + "rtos" : ["RTOS_1", "RTOS_2", "RTOS_3"], "usb" : ["USB_1", "USB_2" ,"USB_3"], - } - }, + } + }, {"target": "NUCLEO_F207ZG", "toolchains": "GCC_ARM", "tests": {"" : ["MBED_2", "MBED_10", "MBED_11", "MBED_16"], + "rtos" : ["RTOS_1", "RTOS_2", "RTOS_3"], "usb" : ["USB_1", "USB_2" ,"USB_3"], - } - }, + } + }, {"target": "NUCLEO_F746ZG", "toolchains": "GCC_ARM", "tests": {"" : ["MBED_2", "MBED_10", "MBED_11", "MBED_16"], + "rtos" : ["RTOS_1", "RTOS_2", "RTOS_3"], "usb" : ["USB_1", "USB_2" ,"USB_3"], - } - }, + } + }, {"target": "NUCLEO_F767ZI", "toolchains": "GCC_ARM", "tests": {"" : ["MBED_2", "MBED_10", "MBED_11", "MBED_16"], + "rtos" : ["RTOS_1", "RTOS_2", "RTOS_3"], "usb" : ["USB_1", "USB_2" ,"USB_3"], - } - }, + } + }, {"target": "NUCLEO_L476RG", "toolchains": "GCC_ARM", "tests": {"" : ["MBED_2", "MBED_10", "MBED_11", "MBED_16"], + "rtos" : ["RTOS_1", "RTOS_2", "RTOS_3"], } }, {"target": "DISCO_F429ZI", "toolchains": "GCC_ARM", "tests": {"" : ["MBED_2", "MBED_10", "MBED_11", "MBED_16"], + "rtos" : ["RTOS_1", "RTOS_2", "RTOS_3"], } }, {"target": "DISCO_F407VG", "toolchains": "GCC_ARM", "tests": {"" : ["MBED_2", "MBED_10", "MBED_11", "MBED_16"], + "rtos" : ["RTOS_1", "RTOS_2", "RTOS_3"], "usb" : ["USB_1", "USB_2" ,"USB_3"], - } - }, + } + }, {"target": "NUCLEO_F303ZE", "toolchains": "GCC_ARM", "tests": {"" : ["MBED_2", "MBED_10", "MBED_11", "MBED_16"], + "rtos" : ["RTOS_1", "RTOS_2", "RTOS_3"], "usb" : ["USB_1", "USB_2" ,"USB_3"], - } - }, + } + }, {"target": "DISCO_L476VG", "toolchains": "GCC_ARM", "tests": {"" : ["MBED_2", "MBED_10", "MBED_11", "MBED_16"], + "rtos" : ["RTOS_1", "RTOS_2", "RTOS_3"], "usb" : ["USB_1", "USB_2" ,"USB_3"], - } - }, - {"target": "DISCO_L072CZ_LRWAN1", - "toolchains": "GCC_ARM", - "tests": {"" : ["MBED_2", "MBED_10", "MBED_11", "MBED_16"], - } + } }, {"target": "NUMAKER_PFM_NUC472", "toolchains": "GCC_ARM", "tests": {"" : ["MBED_2", "MBED_10", "MBED_11", "MBED_16"], + "rtos" : ["RTOS_1", "RTOS_2", "RTOS_3"], "usb" : ["USB_1", "USB_2" ,"USB_3"], } }, - {"target": "NUMAKER_PFM_M453", + {"target": "NUMAKER_PFM_M453", "toolchains": "GCC_ARM", "tests": {"" : ["MBED_2", "MBED_10", "MBED_11", "MBED_16"], + "rtos" : ["RTOS_1", "RTOS_2", "RTOS_3"], "usb" : ["USB_1", "USB_2" ,"USB_3"], } } + ] ################################################################################ diff --git a/tools/config/__init__.py b/tools/config.py similarity index 88% rename from tools/config/__init__.py rename to tools/config.py index 3f265f05afe..16ba893b0da 100644 --- a/tools/config/__init__.py +++ b/tools/config.py @@ -17,13 +17,10 @@ from copy import deepcopy import os -from os.path import dirname, abspath, exists import sys from collections import namedtuple -from os.path import splitext, relpath +from os.path import splitext from intelhex import IntelHex -from jinja2 import FileSystemLoader, StrictUndefined -from jinja2.environment import Environment # Implementation of mbed configuration mechanism from tools.utils import json_file_to_dict, intelhex_offset from tools.arm_pack_manager import Cache @@ -358,12 +355,10 @@ class Config(object): "library": {"name": str, "config": dict, "target_overrides": dict, "macros": list, "__config_path": str}, "application": {"config": dict, "target_overrides": dict, - "macros": list, "__config_path": str, - "artifact_name": str} + "macros": list, "__config_path": str} } - __unused_overrides = set(["target.bootloader_img", "target.restrict_size", - "target.mbed_app_start", "target.mbed_app_size"]) + __unused_overrides = set(["target.bootloader_img", "target.restrict_size"]) # Allowed features in configurations __allowed_features = [ @@ -389,26 +384,23 @@ def __init__(self, tgt, top_level_dirs=None, app_config=None): top_level_dirs may be None (in this case, the constructor will not search for a configuration file). """ - config_errors = [] - self.app_config_location = app_config - if self.app_config_location is None: + app_config_location = app_config + if app_config_location is None: for directory in top_level_dirs or []: full_path = os.path.join(directory, self.__mbed_app_config_name) if os.path.isfile(full_path): - if self.app_config_location is not None: + if app_config_location is not None: raise ConfigException("Duplicate '%s' file in '%s' and '%s'" % (self.__mbed_app_config_name, - self.app_config_location, full_path)) + app_config_location, full_path)) else: - self.app_config_location = full_path + app_config_location = full_path try: - self.app_config_data = json_file_to_dict(self.app_config_location) \ - if self.app_config_location else {} + self.app_config_data = json_file_to_dict(app_config_location) \ + if app_config_location else {} except ValueError as exc: + sys.stderr.write(str(exc) + "\n") self.app_config_data = {} - config_errors.append( - ConfigException("Could not parse mbed app configuration from %s" - % self.app_config_location)) # Check the keys in the application configuration data unknown_keys = set(self.app_config_data.keys()) - \ @@ -441,7 +433,7 @@ def __init__(self, tgt, top_level_dirs=None, app_config=None): self._process_config_and_overrides(self.app_config_data, {}, "app", "application") - self.config_errors = config_errors + self.config_errors = None def add_config_files(self, flist): """Add configuration files @@ -486,9 +478,7 @@ def has_regions(self): target_overrides = self.app_config_data['target_overrides'].get( self.target.name, {}) return ('target.bootloader_img' in target_overrides or - 'target.restrict_size' in target_overrides or - 'target.mbed_app_start' in target_overrides or - 'target.mbed_app_size' in target_overrides) + 'target.restrict_size' in target_overrides) else: return False @@ -498,41 +488,17 @@ def regions(self): if not self.target.bootloader_supported: raise ConfigException("Bootloader not supported on this target.") cmsis_part = Cache(False, False).index[self.target.device_name] + start = 0 target_overrides = self.app_config_data['target_overrides'].get( self.target.name, {}) - if (('target.bootloader_img' in target_overrides or - 'target.restrict_size' in target_overrides) and - ('target.mbed_app_start' in target_overrides or - 'target.mbed_app_size' in target_overrides)): - raise ConfigException( - "target.bootloader_img and target.restirct_size are " - "incompatible with target.mbed_app_start and " - "target.mbed_app_size") try: rom_size = int(cmsis_part['memory']['IROM1']['size'], 0) rom_start = int(cmsis_part['memory']['IROM1']['start'], 0) except KeyError: raise ConfigException("Not enough information in CMSIS packs to " "build a bootloader project") - if ('target.bootloader_img' in target_overrides or - 'target.restrict_size' in target_overrides): - return self._generate_booloader_build(target_overrides, - rom_size, rom_size) - elif ('target.mbed_app_start' in target_overrides or - 'target.mbed_app_size' in target_overrides): - return self._generate_linker_overrides(target_overrides, - rom_start, rom_size) - else: - raise ConfigException( - "Bootloader build requested but no bootlader configuration") - - @staticmethod - def _generate_booloader_build(target_overrides, rom_start, rom_size): - start = 0 if 'target.bootloader_img' in target_overrides: filename = target_overrides['target.bootloader_img'] - if not exists(filename): - raise ConfigException("Bootloader %s not found" % filename) part = intelhex_offset(filename, offset=rom_start) if part.minaddr() != rom_start: raise ConfigException("bootloader executable does not " @@ -554,27 +520,6 @@ def _generate_booloader_build(target_overrides, rom_start, rom_size): raise ConfigException("Not enough memory on device to fit all " "application regions") - @property - def report(self): - return {'app_config': self.app_config_location, - 'library_configs': map(relpath, self.processed_configs.keys())} - - @staticmethod - def _generate_linker_overrides(target_overrides, rom_start, rom_size): - if 'target.mbed_app_start' in target_overrides: - start = int(target_overrides['target.mbed_app_start'], 0) - else: - start = rom_start - if 'target.mbed_app_size' in target_overrides: - size = int(target_overrides['target.mbed_app_size'], 0) - else: - size = (rom_size + rom_start) - start - if start < rom_start: - raise ConfigException("Application starts before ROM") - if size + start > rom_size + rom_start: - raise ConfigException("Application ends after ROM") - yield Region("application", start, size, True, None) - def _process_config_and_overrides(self, data, params, unit_name, unit_kind): """Process "config_parameters" and "target_config_overrides" into a given dictionary @@ -852,13 +797,6 @@ def validate_config(self): return True - @property - def name(self): - if "artifact_name" in self.app_config_data: - return self.app_config_data["artifact_name"] - else: - return None - def load_resources(self, resources): """ Load configuration data from a Resources instance and expand it based on defined features. @@ -868,7 +806,6 @@ def load_resources(self, resources): """ # Update configuration files until added features creates no changes prev_features = set() - self.validate_config() while True: # Add/update the configuration with any .json files found while # scanning @@ -903,25 +840,57 @@ def config_to_header(config, fname=None): WARNING: if 'fname' names an existing file, it will be overwritten! """ - params, macros = config[0] or {}, config[1] or {} + params, macros = config[0], config[1] Config._check_required_parameters(params) - params_with_values = [p for p in params.values() if p.value is not None] - ctx = { - "cfg_params" : [(p.macro_name, str(p.value), p.set_by) - for p in params_with_values], - "macros": [(m.macro_name, str(m.macro_value or ""), m.defined_by) - for m in macros.values()], - "name_len": max([len(m.macro_name) for m in macros.values()] + - [len(m.macro_name) for m in params_with_values] - + [0]), - "val_len" : max([len(str(m.value)) for m in params_with_values] + - [len(m.macro_value or "") for m in macros.values()] - + [0]), - } - jinja_loader = FileSystemLoader(dirname(abspath(__file__))) - jinja_environment = Environment(loader=jinja_loader, - undefined=StrictUndefined) - header_data = jinja_environment.get_template("header.tmpl").render(ctx) + header_data = "// Automatically generated configuration file.\n" + header_data += "// DO NOT EDIT, content will be overwritten.\n\n" + header_data += "#ifndef __MBED_CONFIG_DATA__\n" + header_data += "#define __MBED_CONFIG_DATA__\n\n" + # Compute maximum length of macro names for proper alignment + max_param_macro_name_len = (max([len(m.macro_name) for m + in params.values() + if m.value is not None]) + if params else 0) + max_direct_macro_name_len = (max([len(m.macro_name) for m + in macros.values()]) + if macros else 0) + max_macro_name_len = max(max_param_macro_name_len, + max_direct_macro_name_len) + # Compute maximum length of macro values for proper alignment + max_param_macro_val_len = (max([len(str(m.value)) for m + in params.values() + if m.value is not None]) + if params else 0) + max_direct_macro_val_len = max([len(m.macro_value or "") for m + in macros.values()]) if macros else 0 + max_macro_val_len = max(max_param_macro_val_len, + max_direct_macro_val_len) + # Generate config parameters first + if params: + header_data += "// Configuration parameters\n" + for macro in params.values(): + if macro.value is not None: + header_data += ("#define {0:<{1}} {2!s:<{3}} " + + "// set by {4}\n")\ + .format(macro.macro_name, max_macro_name_len, + macro.value, max_macro_val_len, macro.set_by) + # Then macros + if macros: + header_data += "// Macros\n" + for macro in macros.values(): + if macro.macro_value: + header_data += ("#define {0:<{1}} {2!s:<{3}}" + + " // defined by {4}\n")\ + .format(macro.macro_name, max_macro_name_len, + macro.macro_value, max_macro_val_len, + macro.defined_by) + else: + header_data += ("#define {0:<{1}}" + + " // defined by {2}\n")\ + .format(macro.macro_name, + max_macro_name_len + max_macro_val_len + 1, + macro.defined_by) + header_data += "\n#endif\n" # If fname is given, write "header_data" to it if fname: with open(fname, "w+") as file_desc: diff --git a/tools/config/header.tmpl b/tools/config/header.tmpl deleted file mode 100644 index 83c9adcca0b..00000000000 --- a/tools/config/header.tmpl +++ /dev/null @@ -1,44 +0,0 @@ -/* - * mbed SDK - * Copyright (c) 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. - * You may obtain a copy of the License at - * - * 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, - * 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. - */ - -// Automatically generated configuration file. -// DO NOT EDIT, content will be overwritten. - -#ifndef __MBED_CONFIG_DATA__ -#define __MBED_CONFIG_DATA__ - -{% if cfg_params -%} -// Configuration parameters -{% for name, value, set_by in cfg_params -%} -{% if value is not none -%} -#define {{name.ljust(name_len)}} {{value.ljust(val_len)}} // set by {{set_by}} -{%- endif %} -{% endfor %} -{%- endif -%} - -{%- if macros -%} -// Macros -{% for name, value, set_by in macros -%} -{% if value is not none -%} -#define {{name.ljust(name_len)}} {{value.ljust(val_len)}} // defined by {{set_by}} -{%- else -%} -#define {{name.ljust(name_len + val_len + 1)}} // defined by {{set_by}} -{%- endif %} -{% endfor %} -{%- endif %} -#endif - diff --git a/tools/export/.mbed b/tools/export/.mbed deleted file mode 100644 index e87b56dce78..00000000000 --- a/tools/export/.mbed +++ /dev/null @@ -1 +0,0 @@ -ROOT=. diff --git a/tools/export/__init__.py b/tools/export/__init__.py index e586c22b86e..be8f9c8f5b8 100644 --- a/tools/export/__init__.py +++ b/tools/export/__init__.py @@ -30,9 +30,8 @@ from tools.toolchains import Resources from tools.export import lpcxpresso, ds5_5, iar, makefile from tools.export import embitz, coide, kds, simplicity, atmelstudio -from tools.export import sw4stm32, e2studio, zip, cmsis, uvision, cdt, vscode +from tools.export import sw4stm32, e2studio, zip, cmsis, uvision, cdt from tools.export import gnuarmeclipse -from tools.export import qtcreator from tools.targets import TARGET_NAMES EXPORTERS = { @@ -56,12 +55,8 @@ 'eclipse_iar' : cdt.EclipseIAR, 'eclipse_armc5' : cdt.EclipseArmc5, 'gnuarmeclipse': gnuarmeclipse.GNUARMEclipse, - 'qtcreator': qtcreator.QtCreator, 'zip' : zip.ZIP, - 'cmsis' : cmsis.CMSIS, - 'vscode_gcc_arm' : vscode.VSCodeGcc, - 'vscode_iar' : vscode.VSCodeIAR, - 'vscode_armc5' : vscode.VSCodeArmc5 + 'cmsis' : cmsis.CMSIS } ERROR_MESSAGE_UNSUPPORTED_TOOLCHAIN = """ @@ -73,14 +68,6 @@ To export this project please import the export version of the mbed library. """ -def mcu_ide_list(): - """Shows list of exportable ides - - """ - supported_ides = sorted(EXPORTERS.keys()) - return "\n".join(supported_ides) - - def mcu_ide_matrix(verbose_html=False): """Shows target map using prettytable @@ -151,7 +138,7 @@ def rewrite_basepath(file_name, resources, export_path, loc): export_path - the final destination of the file after export """ new_f = join(loc, relpath(file_name, resources.file_basepath[file_name])) - resources.file_basepath[new_f] = export_path + resources.file_basepath[join(export_path, new_f)] = export_path return new_f @@ -322,10 +309,10 @@ def export_project(src_paths, export_path, target, ide, libraries_paths=None, resources.file_basepath[config_header] = dirname(config_header) if zip_proj: - subtract_basepath(resources, ".") + subtract_basepath(resources, export_path) for loc, res in resource_dict.iteritems(): temp = copy.deepcopy(res) - subtract_basepath(temp, ".", loc) + subtract_basepath(temp, export_path, loc) resources.add(temp) else: for _, res in resource_dict.iteritems(): diff --git a/tools/export/cmsis/__init__.py b/tools/export/cmsis/__init__.py index b2df6e572ef..bd724667562 100644 --- a/tools/export/cmsis/__init__.py +++ b/tools/export/cmsis/__init__.py @@ -121,7 +121,7 @@ def group_project_files(self, sources, root_element): new_srcs = [] for f in list(files): spl = f.name.split(sep) - if len(spl) <= 2: + if len(spl)==2: file_element = Element('file', attrib={ 'category':f.type, @@ -148,4 +148,8 @@ def generate(self): 'device': DeviceCMSIS(self.target), 'date': '' } + # TODO: find how to keep prettyxml from adding xml version to this blob + #dom = parseString(ctx['project_files']) + #ctx['project_files'] = dom.toprettyxml(indent="\t") + self.gen_file('cmsis/cpdsc.tmpl', ctx, 'project.cpdsc') diff --git a/tools/export/coide/__init__.py b/tools/export/coide/__init__.py index 87ffda57117..5c570921c5e 100644 --- a/tools/export/coide/__init__.py +++ b/tools/export/coide/__init__.py @@ -30,6 +30,7 @@ class CoIDE(Exporter): 'ARCH_PRO', 'ARCH_MAX', 'UBLOX_C027', + 'NUCLEO_L011K4', 'NUCLEO_L053R8', 'NUCLEO_L152RE', 'NUCLEO_F030R8', @@ -38,14 +39,18 @@ class CoIDE(Exporter): 'NUCLEO_F072RB', 'NUCLEO_F091RC', 'NUCLEO_F103RB', + 'NUCLEO_F207ZG', 'NUCLEO_F302R8', 'NUCLEO_F303K8', 'NUCLEO_F303RE', 'NUCLEO_F334R8', + 'NUCLEO_F303ZE', 'NUCLEO_F401RE', 'NUCLEO_F410RB', 'NUCLEO_F411RE', + 'NUCLEO_F429ZI', 'NUCLEO_F446RE', + 'NUCLEO_F446ZE', 'DISCO_L053C8', 'DISCO_F051R8', 'DISCO_F100RB', @@ -54,6 +59,7 @@ class CoIDE(Exporter): 'DISCO_F401VC', 'DISCO_F407VG', 'DISCO_F429ZI', + 'DISCO_F469NI', 'MTS_MDOT_F405RG', 'MTS_MDOT_F411RE', 'MOTE_L152RC', diff --git a/tools/export/embitz/__init__.py b/tools/export/embitz/__init__.py index c308728d2d7..e75bc835c33 100644 --- a/tools/export/embitz/__init__.py +++ b/tools/export/embitz/__init__.py @@ -20,9 +20,7 @@ POST_BINARY_WHITELIST = set([ - "TEENSY3_1Code.binary_hook", - "LPCTargetCode.lpc_patch", - "LPC4088Code.binary_hook" + "TEENSY3_1Code.binary_hook" ]) diff --git a/tools/export/exporters.py b/tools/export/exporters.py index a60ea860309..e0fa5ae19b8 100644 --- a/tools/export/exporters.py +++ b/tools/export/exporters.py @@ -60,8 +60,7 @@ def __init__(self, target, export_dir, project_name, toolchain, jinja_loader = FileSystemLoader(os.path.dirname(os.path.abspath(__file__))) self.jinja_environment = Environment(loader=jinja_loader) self.resources = resources - self.generated_files = [join(self.TEMPLATE_DIR, "GettingStarted.html"), - join(self.TEMPLATE_DIR, ".mbed")] + self.generated_files = [join(self.TEMPLATE_DIR,"GettingStarted.html")] self.builder_files_dict = {} self.add_config() diff --git a/tools/export/gnuarmeclipse/__init__.py b/tools/export/gnuarmeclipse/__init__.py index 0ed9e69a430..30b4b6eb1ec 100644 --- a/tools/export/gnuarmeclipse/__init__.py +++ b/tools/export/gnuarmeclipse/__init__.py @@ -61,8 +61,6 @@ def id(self): POST_BINARY_WHITELIST = set([ "TEENSY3_1Code.binary_hook", "MCU_NRF51Code.binary_hook", - "LPCTargetCode.lpc_patch", - "LPC4088Code.binary_hook" ]) class GNUARMEclipse(Exporter): @@ -245,9 +243,7 @@ def generate(self): opts['ld']['object_files'] = objects opts['ld']['user_libraries'] = libraries opts['ld']['system_libraries'] = self.system_libraries - opts['ld']['script'] = join(id.capitalize(), - "linker-script-%s.ld" % id) - opts['cpp_cmd'] = " ".join(toolchain.preproc) + opts['ld']['script'] = self.ld_script # Unique IDs used in multiple places. # Those used only once are implemented with {{u.id}}. @@ -264,7 +260,6 @@ def generate(self): jinja_ctx = { 'name': self.project_name, - 'ld_script': self.ld_script, # Compiler & linker command line options 'options': self.options, @@ -274,13 +269,22 @@ def generate(self): 'u': u, } + # TODO: it would be good to have jinja stop if one of the + # expected context values is not defined. self.gen_file('gnuarmeclipse/.project.tmpl', jinja_ctx, '.project', trim_blocks=True, lstrip_blocks=True) self.gen_file('gnuarmeclipse/.cproject.tmpl', jinja_ctx, '.cproject', trim_blocks=True, lstrip_blocks=True) self.gen_file('gnuarmeclipse/makefile.targets.tmpl', jinja_ctx, 'makefile.targets', trim_blocks=True, lstrip_blocks=True) - self.gen_file('gnuarmeclipse/mbedignore.tmpl', jinja_ctx, '.mbedignore') + + if not exists('.mbedignore'): + print + print 'Create .mbedignore' + with open('.mbedignore', 'w') as f: + for bf in build_folders: + print bf + '/' + f.write(bf + '/\n') print print 'Done. Import the \'{0}\' project in Eclipse.'.format(self.project_name) diff --git a/tools/export/gnuarmeclipse/makefile.targets.tmpl b/tools/export/gnuarmeclipse/makefile.targets.tmpl index af439f28e46..00466357c77 100644 --- a/tools/export/gnuarmeclipse/makefile.targets.tmpl +++ b/tools/export/gnuarmeclipse/makefile.targets.tmpl @@ -3,11 +3,5 @@ mbedclean: $(RM) $(OBJS) $(RM) $(CC_DEPS)$(C++_DEPS)$(C_UPPER_DEPS)$(CXX_DEPS)$(ASM_DEPS)$(S_UPPER_DEPS)$(C_DEPS)$(CPP_DEPS) - $(RM) $(SECONDARY_FLASH)$(SECONDARY_SIZE) {{name}}.* linker-script-*.ld - -@echo ' ' - -{% for config, data in options.iteritems() %} -linker-script-{{config}}.ld: ../{{ld_script}} - {{data.cpp_cmd}} {{data.ld.other}} $< -o $@ -{{name}}.elf: linker-script-{{config}}.ld -{% endfor %} + $(RM) $(SECONDARY_FLASH)$(SECONDARY_SIZE) {{name}}.* + -@echo ' ' \ No newline at end of file diff --git a/tools/export/gnuarmeclipse/mbedignore.tmpl b/tools/export/gnuarmeclipse/mbedignore.tmpl deleted file mode 100644 index 175b9673f4d..00000000000 --- a/tools/export/gnuarmeclipse/mbedignore.tmpl +++ /dev/null @@ -1,3 +0,0 @@ -{%- for config in options.values() -%} -{{config.name}}/* -{% endfor -%} diff --git a/tools/export/iar/__init__.py b/tools/export/iar/__init__.py index e32118f4bf1..b85e465e97e 100644 --- a/tools/export/iar/__init__.py +++ b/tools/export/iar/__init__.py @@ -10,7 +10,6 @@ from tools.export.exporters import Exporter, TargetNotSupportedException import json from tools.export.cmsis import DeviceCMSIS -from tools.utils import NotSupportedException from multiprocessing import cpu_count class IAR(Exporter): @@ -79,9 +78,6 @@ def iar_device(self): "FPU2": 0, "NrRegs": 0, "NEON": '', - "CExtraOptionsCheck": 0, - "CExtraOptions": "", - "CMSISDAPJtagSpeedList": 0, } iar_defaults.update(device_info) @@ -101,8 +97,6 @@ def format_src(self, srcs): def generate(self): """Generate the .eww, .ewd, and .ewp files""" - if not self.resources.linker_script: - raise NotSupportedException("No linker script found.") srcs = self.resources.headers + self.resources.s_sources + \ self.resources.c_sources + self.resources.cpp_sources + \ self.resources.objects + self.resources.libraries @@ -114,7 +108,7 @@ def generate(self): template = ["--vla", "--no_static_destruction"] # Flag invalid if set in template # Optimizations are also set in template - invalid_flag = lambda x: x in template or re.match("-O(\d|time|n|hz?)", x) + invalid_flag = lambda x: x in template or re.match("-O(\d|time|n)", x) flags['c_flags'] = [flag for flag in c_flags if not invalid_flag(flag)] try: diff --git a/tools/export/iar/ewd.tmpl b/tools/export/iar/ewd.tmpl index debef364242..c5b321dcb38 100644 --- a/tools/export/iar/ewd.tmpl +++ b/tools/export/iar/ewd.tmpl @@ -57,11 +57,11 @@